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 verifyFormat("Constructor() :\n" 7133 " // Comment forcing unwanted break.\n" 7134 " aaaa(aaaa) {}", 7135 Style); 7136 7137 Style.ColumnLimit = 0; 7138 verifyFormat("SomeClass::Constructor() :\n" 7139 " a(a) {}", 7140 Style); 7141 verifyFormat("SomeClass::Constructor() noexcept :\n" 7142 " a(a) {}", 7143 Style); 7144 verifyFormat("SomeClass::Constructor() :\n" 7145 " a(a), b(b), c(c) {}", 7146 Style); 7147 verifyFormat("SomeClass::Constructor() :\n" 7148 " a(a) {\n" 7149 " foo();\n" 7150 " bar();\n" 7151 "}", 7152 Style); 7153 7154 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 7155 verifyFormat("SomeClass::Constructor() :\n" 7156 " a(a), b(b), c(c) {\n" 7157 "}", 7158 Style); 7159 verifyFormat("SomeClass::Constructor() :\n" 7160 " a(a) {\n" 7161 "}", 7162 Style); 7163 7164 Style.ColumnLimit = 80; 7165 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 7166 Style.ConstructorInitializerIndentWidth = 2; 7167 verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style); 7168 verifyFormat("SomeClass::Constructor() :\n" 7169 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7170 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}", 7171 Style); 7172 7173 // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as 7174 // well 7175 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 7176 verifyFormat( 7177 "class SomeClass\n" 7178 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7179 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7180 Style); 7181 Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma; 7182 verifyFormat( 7183 "class SomeClass\n" 7184 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7185 " , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7186 Style); 7187 Style.BreakInheritanceList = FormatStyle::BILS_AfterColon; 7188 verifyFormat( 7189 "class SomeClass :\n" 7190 " public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7191 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7192 Style); 7193 Style.BreakInheritanceList = FormatStyle::BILS_AfterComma; 7194 verifyFormat( 7195 "class SomeClass\n" 7196 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7197 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7198 Style); 7199 } 7200 7201 #ifndef EXPENSIVE_CHECKS 7202 // Expensive checks enables libstdc++ checking which includes validating the 7203 // state of ranges used in std::priority_queue - this blows out the 7204 // runtime/scalability of the function and makes this test unacceptably slow. 7205 TEST_F(FormatTest, MemoizationTests) { 7206 // This breaks if the memoization lookup does not take \c Indent and 7207 // \c LastSpace into account. 7208 verifyFormat( 7209 "extern CFRunLoopTimerRef\n" 7210 "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n" 7211 " CFTimeInterval interval, CFOptionFlags flags,\n" 7212 " CFIndex order, CFRunLoopTimerCallBack callout,\n" 7213 " CFRunLoopTimerContext *context) {}"); 7214 7215 // Deep nesting somewhat works around our memoization. 7216 verifyFormat( 7217 "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7218 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7219 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7220 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7221 " aaaaa())))))))))))))))))))))))))))))))))))))));", 7222 getLLVMStyleWithColumns(65)); 7223 verifyFormat( 7224 "aaaaa(\n" 7225 " aaaaa,\n" 7226 " aaaaa(\n" 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))))))))))));", 7249 getLLVMStyleWithColumns(65)); 7250 verifyFormat( 7251 "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" 7252 " a),\n" 7253 " a),\n" 7254 " 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)", 7269 getLLVMStyleWithColumns(65)); 7270 7271 // This test takes VERY long when memoization is broken. 7272 FormatStyle OnePerLine = getLLVMStyle(); 7273 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 7274 OnePerLine.BinPackParameters = false; 7275 std::string input = "Constructor()\n" 7276 " : aaaa(a,\n"; 7277 for (unsigned i = 0, e = 80; i != e; ++i) 7278 input += " a,\n"; 7279 input += " a) {}"; 7280 verifyFormat(input, OnePerLine); 7281 } 7282 #endif 7283 7284 TEST_F(FormatTest, BreaksAsHighAsPossible) { 7285 verifyFormat( 7286 "void f() {\n" 7287 " if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n" 7288 " (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n" 7289 " f();\n" 7290 "}"); 7291 verifyFormat("if (Intervals[i].getRange().getFirst() <\n" 7292 " Intervals[i - 1].getRange().getLast()) {\n}"); 7293 } 7294 7295 TEST_F(FormatTest, BreaksFunctionDeclarations) { 7296 // Principially, we break function declarations in a certain order: 7297 // 1) break amongst arguments. 7298 verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n" 7299 " Cccccccccccccc cccccccccccccc);"); 7300 verifyFormat("template <class TemplateIt>\n" 7301 "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n" 7302 " TemplateIt *stop) {}"); 7303 7304 // 2) break after return type. 7305 verifyFormat( 7306 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7307 "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);", 7308 getGoogleStyle()); 7309 7310 // 3) break after (. 7311 verifyFormat( 7312 "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n" 7313 " Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);", 7314 getGoogleStyle()); 7315 7316 // 4) break before after nested name specifiers. 7317 verifyFormat( 7318 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7319 "SomeClasssssssssssssssssssssssssssssssssssssss::\n" 7320 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);", 7321 getGoogleStyle()); 7322 7323 // However, there are exceptions, if a sufficient amount of lines can be 7324 // saved. 7325 // FIXME: The precise cut-offs wrt. the number of saved lines might need some 7326 // more adjusting. 7327 verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n" 7328 " Cccccccccccccc cccccccccc,\n" 7329 " Cccccccccccccc cccccccccc,\n" 7330 " Cccccccccccccc cccccccccc,\n" 7331 " Cccccccccccccc cccccccccc);"); 7332 verifyFormat( 7333 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7334 "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7335 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7336 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);", 7337 getGoogleStyle()); 7338 verifyFormat( 7339 "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n" 7340 " Cccccccccccccc cccccccccc,\n" 7341 " Cccccccccccccc cccccccccc,\n" 7342 " Cccccccccccccc cccccccccc,\n" 7343 " Cccccccccccccc cccccccccc,\n" 7344 " Cccccccccccccc cccccccccc,\n" 7345 " Cccccccccccccc cccccccccc);"); 7346 verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7347 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7348 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7349 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7350 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);"); 7351 7352 // Break after multi-line parameters. 7353 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7354 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7355 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7356 " bbbb bbbb);"); 7357 verifyFormat("void SomeLoooooooooooongFunction(\n" 7358 " std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n" 7359 " aaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7360 " int bbbbbbbbbbbbb);"); 7361 7362 // Treat overloaded operators like other functions. 7363 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 7364 "operator>(const SomeLoooooooooooooooooooooooooogType &other);"); 7365 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 7366 "operator>>(const SomeLooooooooooooooooooooooooogType &other);"); 7367 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 7368 "operator<<(const SomeLooooooooooooooooooooooooogType &other);"); 7369 verifyGoogleFormat( 7370 "SomeLoooooooooooooooooooooooooooooogType operator>>(\n" 7371 " const SomeLooooooooogType &a, const SomeLooooooooogType &b);"); 7372 verifyGoogleFormat( 7373 "SomeLoooooooooooooooooooooooooooooogType operator<<(\n" 7374 " const SomeLooooooooogType &a, const SomeLooooooooogType &b);"); 7375 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7376 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);"); 7377 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n" 7378 "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);"); 7379 verifyGoogleFormat( 7380 "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n" 7381 "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7382 " bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}"); 7383 verifyGoogleFormat("template <typename T>\n" 7384 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7385 "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n" 7386 " aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);"); 7387 7388 FormatStyle Style = getLLVMStyle(); 7389 Style.PointerAlignment = FormatStyle::PAS_Left; 7390 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7391 " aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}", 7392 Style); 7393 verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n" 7394 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7395 Style); 7396 } 7397 7398 TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) { 7399 // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516: 7400 // Prefer keeping `::` followed by `operator` together. 7401 EXPECT_EQ("const aaaa::bbbbbbb &\n" 7402 "ccccccccc::operator++() {\n" 7403 " stuff();\n" 7404 "}", 7405 format("const aaaa::bbbbbbb\n" 7406 "&ccccccccc::operator++() { stuff(); }", 7407 getLLVMStyleWithColumns(40))); 7408 } 7409 7410 TEST_F(FormatTest, TrailingReturnType) { 7411 verifyFormat("auto foo() -> int;\n"); 7412 // correct trailing return type spacing 7413 verifyFormat("auto operator->() -> int;\n"); 7414 verifyFormat("auto operator++(int) -> int;\n"); 7415 7416 verifyFormat("struct S {\n" 7417 " auto bar() const -> int;\n" 7418 "};"); 7419 verifyFormat("template <size_t Order, typename T>\n" 7420 "auto load_img(const std::string &filename)\n" 7421 " -> alias::tensor<Order, T, mem::tag::cpu> {}"); 7422 verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n" 7423 " -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}"); 7424 verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}"); 7425 verifyFormat("template <typename T>\n" 7426 "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n" 7427 " -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());"); 7428 7429 // Not trailing return types. 7430 verifyFormat("void f() { auto a = b->c(); }"); 7431 verifyFormat("auto a = p->foo();"); 7432 verifyFormat("int a = p->foo();"); 7433 verifyFormat("auto lmbd = [] NOEXCEPT -> int { return 0; };"); 7434 } 7435 7436 TEST_F(FormatTest, DeductionGuides) { 7437 verifyFormat("template <class T> A(const T &, const T &) -> A<T &>;"); 7438 verifyFormat("template <class T> explicit A(T &, T &&) -> A<T>;"); 7439 verifyFormat("template <class... Ts> S(Ts...) -> S<Ts...>;"); 7440 verifyFormat( 7441 "template <class... T>\n" 7442 "array(T &&...t) -> array<std::common_type_t<T...>, sizeof...(T)>;"); 7443 verifyFormat("template <class T> A() -> A<decltype(p->foo<3>())>;"); 7444 verifyFormat("template <class T> A() -> A<decltype(foo<traits<1>>)>;"); 7445 verifyFormat("template <class T> A() -> A<sizeof(p->foo<1>)>;"); 7446 verifyFormat("template <class T> A() -> A<(3 < 2)>;"); 7447 verifyFormat("template <class T> A() -> A<((3) < (2))>;"); 7448 verifyFormat("template <class T> x() -> x<1>;"); 7449 verifyFormat("template <class T> explicit x(T &) -> x<1>;"); 7450 7451 // Ensure not deduction guides. 7452 verifyFormat("c()->f<int>();"); 7453 verifyFormat("x()->foo<1>;"); 7454 verifyFormat("x = p->foo<3>();"); 7455 verifyFormat("x()->x<1>();"); 7456 verifyFormat("x()->x<1>;"); 7457 } 7458 7459 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) { 7460 // Avoid breaking before trailing 'const' or other trailing annotations, if 7461 // they are not function-like. 7462 FormatStyle Style = getGoogleStyleWithColumns(47); 7463 verifyFormat("void someLongFunction(\n" 7464 " int someLoooooooooooooongParameter) const {\n}", 7465 getLLVMStyleWithColumns(47)); 7466 verifyFormat("LoooooongReturnType\n" 7467 "someLoooooooongFunction() const {}", 7468 getLLVMStyleWithColumns(47)); 7469 verifyFormat("LoooooongReturnType someLoooooooongFunction()\n" 7470 " const {}", 7471 Style); 7472 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7473 " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;"); 7474 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7475 " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;"); 7476 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7477 " aaaaa aaaaaaaaaaaaaaaaaaaa) override final;"); 7478 verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n" 7479 " aaaaaaaaaaa aaaaa) const override;"); 7480 verifyGoogleFormat( 7481 "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7482 " const override;"); 7483 7484 // Even if the first parameter has to be wrapped. 7485 verifyFormat("void someLongFunction(\n" 7486 " int someLongParameter) const {}", 7487 getLLVMStyleWithColumns(46)); 7488 verifyFormat("void someLongFunction(\n" 7489 " int someLongParameter) const {}", 7490 Style); 7491 verifyFormat("void someLongFunction(\n" 7492 " int someLongParameter) override {}", 7493 Style); 7494 verifyFormat("void someLongFunction(\n" 7495 " int someLongParameter) OVERRIDE {}", 7496 Style); 7497 verifyFormat("void someLongFunction(\n" 7498 " int someLongParameter) final {}", 7499 Style); 7500 verifyFormat("void someLongFunction(\n" 7501 " int someLongParameter) FINAL {}", 7502 Style); 7503 verifyFormat("void someLongFunction(\n" 7504 " int parameter) const override {}", 7505 Style); 7506 7507 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 7508 verifyFormat("void someLongFunction(\n" 7509 " int someLongParameter) const\n" 7510 "{\n" 7511 "}", 7512 Style); 7513 7514 Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 7515 verifyFormat("void someLongFunction(\n" 7516 " int someLongParameter) const\n" 7517 " {\n" 7518 " }", 7519 Style); 7520 7521 // Unless these are unknown annotations. 7522 verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n" 7523 " aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7524 " LONG_AND_UGLY_ANNOTATION;"); 7525 7526 // Breaking before function-like trailing annotations is fine to keep them 7527 // close to their arguments. 7528 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7529 " LOCKS_EXCLUDED(aaaaaaaaaaaaa);"); 7530 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n" 7531 " LOCKS_EXCLUDED(aaaaaaaaaaaaa);"); 7532 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n" 7533 " LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}"); 7534 verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n" 7535 " AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);"); 7536 verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});"); 7537 7538 verifyFormat( 7539 "void aaaaaaaaaaaaaaaaaa()\n" 7540 " __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n" 7541 " aaaaaaaaaaaaaaaaaaaaaaaaa));"); 7542 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7543 " __attribute__((unused));"); 7544 verifyGoogleFormat( 7545 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7546 " GUARDED_BY(aaaaaaaaaaaa);"); 7547 verifyGoogleFormat( 7548 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7549 " GUARDED_BY(aaaaaaaaaaaa);"); 7550 verifyGoogleFormat( 7551 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n" 7552 " aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7553 verifyGoogleFormat( 7554 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n" 7555 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7556 } 7557 7558 TEST_F(FormatTest, FunctionAnnotations) { 7559 verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7560 "int OldFunction(const string ¶meter) {}"); 7561 verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7562 "string OldFunction(const string ¶meter) {}"); 7563 verifyFormat("template <typename T>\n" 7564 "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7565 "string OldFunction(const string ¶meter) {}"); 7566 7567 // Not function annotations. 7568 verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7569 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"); 7570 verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n" 7571 " ThisIsATestWithAReallyReallyReallyReallyLongName) {}"); 7572 verifyFormat("MACRO(abc).function() // wrap\n" 7573 " << abc;"); 7574 verifyFormat("MACRO(abc)->function() // wrap\n" 7575 " << abc;"); 7576 verifyFormat("MACRO(abc)::function() // wrap\n" 7577 " << abc;"); 7578 } 7579 7580 TEST_F(FormatTest, BreaksDesireably) { 7581 verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n" 7582 " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n" 7583 " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}"); 7584 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7585 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 7586 "}"); 7587 7588 verifyFormat( 7589 "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7590 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 7591 7592 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7593 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7594 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7595 7596 verifyFormat( 7597 "aaaaaaaa(aaaaaaaaaaaaa,\n" 7598 " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7599 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n" 7600 " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7601 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));"); 7602 7603 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 7604 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7605 7606 verifyFormat( 7607 "void f() {\n" 7608 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n" 7609 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 7610 "}"); 7611 verifyFormat( 7612 "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7613 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7614 verifyFormat( 7615 "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7616 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7617 verifyFormat( 7618 "aaaaaa(aaa,\n" 7619 " new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7620 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7621 " aaaa);"); 7622 verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7623 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7624 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7625 7626 // Indent consistently independent of call expression and unary operator. 7627 verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7628 " dddddddddddddddddddddddddddddd));"); 7629 verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7630 " dddddddddddddddddddddddddddddd));"); 7631 verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n" 7632 " dddddddddddddddddddddddddddddd));"); 7633 7634 // This test case breaks on an incorrect memoization, i.e. an optimization not 7635 // taking into account the StopAt value. 7636 verifyFormat( 7637 "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7638 " aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7639 " aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7640 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7641 7642 verifyFormat("{\n {\n {\n" 7643 " Annotation.SpaceRequiredBefore =\n" 7644 " Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n" 7645 " Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n" 7646 " }\n }\n}"); 7647 7648 // Break on an outer level if there was a break on an inner level. 7649 EXPECT_EQ("f(g(h(a, // comment\n" 7650 " b, c),\n" 7651 " d, e),\n" 7652 " x, y);", 7653 format("f(g(h(a, // comment\n" 7654 " b, c), d, e), x, y);")); 7655 7656 // Prefer breaking similar line breaks. 7657 verifyFormat( 7658 "const int kTrackingOptions = NSTrackingMouseMoved |\n" 7659 " NSTrackingMouseEnteredAndExited |\n" 7660 " NSTrackingActiveAlways;"); 7661 } 7662 7663 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) { 7664 FormatStyle NoBinPacking = getGoogleStyle(); 7665 NoBinPacking.BinPackParameters = false; 7666 NoBinPacking.BinPackArguments = true; 7667 verifyFormat("void f() {\n" 7668 " f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n" 7669 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 7670 "}", 7671 NoBinPacking); 7672 verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n" 7673 " int aaaaaaaaaaaaaaaaaaaa,\n" 7674 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7675 NoBinPacking); 7676 7677 NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false; 7678 verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7679 " vector<int> bbbbbbbbbbbbbbb);", 7680 NoBinPacking); 7681 // FIXME: This behavior difference is probably not wanted. However, currently 7682 // we cannot distinguish BreakBeforeParameter being set because of the wrapped 7683 // template arguments from BreakBeforeParameter being set because of the 7684 // one-per-line formatting. 7685 verifyFormat( 7686 "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n" 7687 " aaaaaaaaaa> aaaaaaaaaa);", 7688 NoBinPacking); 7689 verifyFormat( 7690 "void fffffffffff(\n" 7691 " aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n" 7692 " aaaaaaaaaa);"); 7693 } 7694 7695 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) { 7696 FormatStyle NoBinPacking = getGoogleStyle(); 7697 NoBinPacking.BinPackParameters = false; 7698 NoBinPacking.BinPackArguments = false; 7699 verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n" 7700 " aaaaaaaaaaaaaaaaaaaa,\n" 7701 " aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);", 7702 NoBinPacking); 7703 verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n" 7704 " aaaaaaaaaaaaa,\n" 7705 " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));", 7706 NoBinPacking); 7707 verifyFormat( 7708 "aaaaaaaa(aaaaaaaaaaaaa,\n" 7709 " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7710 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n" 7711 " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7712 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));", 7713 NoBinPacking); 7714 verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n" 7715 " .aaaaaaaaaaaaaaaaaa();", 7716 NoBinPacking); 7717 verifyFormat("void f() {\n" 7718 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7719 " aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n" 7720 "}", 7721 NoBinPacking); 7722 7723 verifyFormat( 7724 "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7725 " aaaaaaaaaaaa,\n" 7726 " aaaaaaaaaaaa);", 7727 NoBinPacking); 7728 verifyFormat( 7729 "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n" 7730 " ddddddddddddddddddddddddddddd),\n" 7731 " test);", 7732 NoBinPacking); 7733 7734 verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n" 7735 " aaaaaaaaaaaaaaaaaaaaaaa,\n" 7736 " aaaaaaaaaaaaaaaaaaaaaaa>\n" 7737 " aaaaaaaaaaaaaaaaaa;", 7738 NoBinPacking); 7739 verifyFormat("a(\"a\"\n" 7740 " \"a\",\n" 7741 " a);"); 7742 7743 NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false; 7744 verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n" 7745 " aaaaaaaaa,\n" 7746 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7747 NoBinPacking); 7748 verifyFormat( 7749 "void f() {\n" 7750 " aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n" 7751 " .aaaaaaa();\n" 7752 "}", 7753 NoBinPacking); 7754 verifyFormat( 7755 "template <class SomeType, class SomeOtherType>\n" 7756 "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}", 7757 NoBinPacking); 7758 } 7759 7760 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) { 7761 FormatStyle Style = getLLVMStyleWithColumns(15); 7762 Style.ExperimentalAutoDetectBinPacking = true; 7763 EXPECT_EQ("aaa(aaaa,\n" 7764 " aaaa,\n" 7765 " aaaa);\n" 7766 "aaa(aaaa,\n" 7767 " aaaa,\n" 7768 " aaaa);", 7769 format("aaa(aaaa,\n" // one-per-line 7770 " aaaa,\n" 7771 " aaaa );\n" 7772 "aaa(aaaa, aaaa, aaaa);", // inconclusive 7773 Style)); 7774 EXPECT_EQ("aaa(aaaa, aaaa,\n" 7775 " aaaa);\n" 7776 "aaa(aaaa, aaaa,\n" 7777 " aaaa);", 7778 format("aaa(aaaa, aaaa,\n" // bin-packed 7779 " aaaa );\n" 7780 "aaa(aaaa, aaaa, aaaa);", // inconclusive 7781 Style)); 7782 } 7783 7784 TEST_F(FormatTest, FormatsBuilderPattern) { 7785 verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n" 7786 " .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n" 7787 " .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n" 7788 " .StartsWith(\".init\", ORDER_INIT)\n" 7789 " .StartsWith(\".fini\", ORDER_FINI)\n" 7790 " .StartsWith(\".hash\", ORDER_HASH)\n" 7791 " .Default(ORDER_TEXT);\n"); 7792 7793 verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n" 7794 " aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();"); 7795 verifyFormat("aaaaaaa->aaaaaaa\n" 7796 " ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7797 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7798 " ->aaaaaaaa(aaaaaaaaaaaaaaa);"); 7799 verifyFormat( 7800 "aaaaaaa->aaaaaaa\n" 7801 " ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7802 " ->aaaaaaaa(aaaaaaaaaaaaaaa);"); 7803 verifyFormat( 7804 "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n" 7805 " aaaaaaaaaaaaaa);"); 7806 verifyFormat( 7807 "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n" 7808 " aaaaaa->aaaaaaaaaaaa()\n" 7809 " ->aaaaaaaaaaaaaaaa(\n" 7810 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7811 " ->aaaaaaaaaaaaaaaaa();"); 7812 verifyGoogleFormat( 7813 "void f() {\n" 7814 " someo->Add((new util::filetools::Handler(dir))\n" 7815 " ->OnEvent1(NewPermanentCallback(\n" 7816 " this, &HandlerHolderClass::EventHandlerCBA))\n" 7817 " ->OnEvent2(NewPermanentCallback(\n" 7818 " this, &HandlerHolderClass::EventHandlerCBB))\n" 7819 " ->OnEvent3(NewPermanentCallback(\n" 7820 " this, &HandlerHolderClass::EventHandlerCBC))\n" 7821 " ->OnEvent5(NewPermanentCallback(\n" 7822 " this, &HandlerHolderClass::EventHandlerCBD))\n" 7823 " ->OnEvent6(NewPermanentCallback(\n" 7824 " this, &HandlerHolderClass::EventHandlerCBE)));\n" 7825 "}"); 7826 7827 verifyFormat( 7828 "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();"); 7829 verifyFormat("aaaaaaaaaaaaaaa()\n" 7830 " .aaaaaaaaaaaaaaa()\n" 7831 " .aaaaaaaaaaaaaaa()\n" 7832 " .aaaaaaaaaaaaaaa()\n" 7833 " .aaaaaaaaaaaaaaa();"); 7834 verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7835 " .aaaaaaaaaaaaaaa()\n" 7836 " .aaaaaaaaaaaaaaa()\n" 7837 " .aaaaaaaaaaaaaaa();"); 7838 verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7839 " .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7840 " .aaaaaaaaaaaaaaa();"); 7841 verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n" 7842 " ->aaaaaaaaaaaaaae(0)\n" 7843 " ->aaaaaaaaaaaaaaa();"); 7844 7845 // Don't linewrap after very short segments. 7846 verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7847 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7848 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7849 verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7850 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7851 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7852 verifyFormat("aaa()\n" 7853 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7854 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7855 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7856 7857 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n" 7858 " .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7859 " .has<bbbbbbbbbbbbbbbbbbbbb>();"); 7860 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n" 7861 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 7862 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();"); 7863 7864 // Prefer not to break after empty parentheses. 7865 verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n" 7866 " First->LastNewlineOffset);"); 7867 7868 // Prefer not to create "hanging" indents. 7869 verifyFormat( 7870 "return !soooooooooooooome_map\n" 7871 " .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7872 " .second;"); 7873 verifyFormat( 7874 "return aaaaaaaaaaaaaaaa\n" 7875 " .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n" 7876 " .aaaa(aaaaaaaaaaaaaa);"); 7877 // No hanging indent here. 7878 verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n" 7879 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7880 verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n" 7881 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7882 verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n" 7883 " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7884 getLLVMStyleWithColumns(60)); 7885 verifyFormat("aaaaaaaaaaaaaaaaaa\n" 7886 " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n" 7887 " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7888 getLLVMStyleWithColumns(59)); 7889 verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7890 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7891 " .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7892 7893 // Dont break if only closing statements before member call 7894 verifyFormat("test() {\n" 7895 " ([]() -> {\n" 7896 " int b = 32;\n" 7897 " return 3;\n" 7898 " }).foo();\n" 7899 "}"); 7900 verifyFormat("test() {\n" 7901 " (\n" 7902 " []() -> {\n" 7903 " int b = 32;\n" 7904 " return 3;\n" 7905 " },\n" 7906 " foo, bar)\n" 7907 " .foo();\n" 7908 "}"); 7909 verifyFormat("test() {\n" 7910 " ([]() -> {\n" 7911 " int b = 32;\n" 7912 " return 3;\n" 7913 " })\n" 7914 " .foo()\n" 7915 " .bar();\n" 7916 "}"); 7917 verifyFormat("test() {\n" 7918 " ([]() -> {\n" 7919 " int b = 32;\n" 7920 " return 3;\n" 7921 " })\n" 7922 " .foo(\"aaaaaaaaaaaaaaaaa\"\n" 7923 " \"bbbb\");\n" 7924 "}", 7925 getLLVMStyleWithColumns(30)); 7926 } 7927 7928 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) { 7929 verifyFormat( 7930 "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 7931 " bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}"); 7932 verifyFormat( 7933 "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n" 7934 " bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}"); 7935 7936 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" 7937 " ccccccccccccccccccccccccc) {\n}"); 7938 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n" 7939 " ccccccccccccccccccccccccc) {\n}"); 7940 7941 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" 7942 " ccccccccccccccccccccccccc) {\n}"); 7943 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n" 7944 " ccccccccccccccccccccccccc) {\n}"); 7945 7946 verifyFormat( 7947 "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n" 7948 " ccccccccccccccccccccccccc) {\n}"); 7949 verifyFormat( 7950 "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n" 7951 " ccccccccccccccccccccccccc) {\n}"); 7952 7953 verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n" 7954 " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n" 7955 " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n" 7956 " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;"); 7957 verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n" 7958 " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n" 7959 " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n" 7960 " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;"); 7961 7962 verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n" 7963 " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n" 7964 " aaaaaaaaaaaaaaa != aa) {\n}"); 7965 verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n" 7966 " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n" 7967 " aaaaaaaaaaaaaaa != aa) {\n}"); 7968 } 7969 7970 TEST_F(FormatTest, BreaksAfterAssignments) { 7971 verifyFormat( 7972 "unsigned Cost =\n" 7973 " TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n" 7974 " SI->getPointerAddressSpaceee());\n"); 7975 verifyFormat( 7976 "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n" 7977 " Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());"); 7978 7979 verifyFormat( 7980 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n" 7981 " aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);"); 7982 verifyFormat("unsigned OriginalStartColumn =\n" 7983 " SourceMgr.getSpellingColumnNumber(\n" 7984 " Current.FormatTok.getStartOfNonWhitespace()) -\n" 7985 " 1;"); 7986 } 7987 7988 TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) { 7989 FormatStyle Style = getLLVMStyle(); 7990 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 7991 " bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;", 7992 Style); 7993 7994 Style.PenaltyBreakAssignment = 20; 7995 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n" 7996 " cccccccccccccccccccccccccc;", 7997 Style); 7998 } 7999 8000 TEST_F(FormatTest, AlignsAfterAssignments) { 8001 verifyFormat( 8002 "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 8003 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 8004 verifyFormat( 8005 "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 8006 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 8007 verifyFormat( 8008 "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 8009 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 8010 verifyFormat( 8011 "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 8012 " aaaaaaaaaaaaaaaaaaaaaaaaa);"); 8013 verifyFormat( 8014 "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n" 8015 " aaaaaaaaaaaaaaaaaaaaaaaa +\n" 8016 " aaaaaaaaaaaaaaaaaaaaaaaa;"); 8017 } 8018 8019 TEST_F(FormatTest, AlignsAfterReturn) { 8020 verifyFormat( 8021 "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 8022 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 8023 verifyFormat( 8024 "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 8025 " aaaaaaaaaaaaaaaaaaaaaaaaa);"); 8026 verifyFormat( 8027 "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n" 8028 " aaaaaaaaaaaaaaaaaaaaaa();"); 8029 verifyFormat( 8030 "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n" 8031 " aaaaaaaaaaaaaaaaaaaaaa());"); 8032 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8033 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8034 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8035 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n" 8036 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8037 verifyFormat("return\n" 8038 " // true if code is one of a or b.\n" 8039 " code == a || code == b;"); 8040 } 8041 8042 TEST_F(FormatTest, AlignsAfterOpenBracket) { 8043 verifyFormat( 8044 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n" 8045 " aaaaaaaaa aaaaaaa) {}"); 8046 verifyFormat( 8047 "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n" 8048 " aaaaaaaaaaa aaaaaaaaa);"); 8049 verifyFormat( 8050 "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n" 8051 " aaaaaaaaaaaaaaaaaaaaa));"); 8052 FormatStyle Style = getLLVMStyle(); 8053 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 8054 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8055 " aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}", 8056 Style); 8057 verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n" 8058 " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);", 8059 Style); 8060 verifyFormat("SomeLongVariableName->someFunction(\n" 8061 " foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));", 8062 Style); 8063 verifyFormat( 8064 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n" 8065 " aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 8066 Style); 8067 verifyFormat( 8068 "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n" 8069 " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8070 Style); 8071 verifyFormat( 8072 "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n" 8073 " aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));", 8074 Style); 8075 8076 verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n" 8077 " ccccccc(aaaaaaaaaaaaaaaaa, //\n" 8078 " b));", 8079 Style); 8080 8081 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 8082 Style.BinPackArguments = false; 8083 Style.BinPackParameters = false; 8084 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8085 " aaaaaaaaaaa aaaaaaaa,\n" 8086 " aaaaaaaaa aaaaaaa,\n" 8087 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 8088 Style); 8089 verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n" 8090 " aaaaaaaaaaa aaaaaaaaa,\n" 8091 " aaaaaaaaaaa aaaaaaaaa,\n" 8092 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8093 Style); 8094 verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n" 8095 " aaaaaaaaaaaaaaa,\n" 8096 " aaaaaaaaaaaaaaaaaaaaa,\n" 8097 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));", 8098 Style); 8099 verifyFormat( 8100 "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n" 8101 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));", 8102 Style); 8103 verifyFormat( 8104 "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n" 8105 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));", 8106 Style); 8107 verifyFormat( 8108 "aaaaaaaaaaaaaaaaaaaaaaaa(\n" 8109 " aaaaaaaaaaaaaaaaaaaaa(\n" 8110 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n" 8111 " aaaaaaaaaaaaaaaa);", 8112 Style); 8113 verifyFormat( 8114 "aaaaaaaaaaaaaaaaaaaaaaaa(\n" 8115 " aaaaaaaaaaaaaaaaaaaaa(\n" 8116 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n" 8117 " aaaaaaaaaaaaaaaa);", 8118 Style); 8119 } 8120 8121 TEST_F(FormatTest, ParenthesesAndOperandAlignment) { 8122 FormatStyle Style = getLLVMStyleWithColumns(40); 8123 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 8124 " bbbbbbbbbbbbbbbbbbbbbb);", 8125 Style); 8126 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 8127 Style.AlignOperands = FormatStyle::OAS_DontAlign; 8128 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 8129 " bbbbbbbbbbbbbbbbbbbbbb);", 8130 Style); 8131 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 8132 Style.AlignOperands = FormatStyle::OAS_Align; 8133 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 8134 " bbbbbbbbbbbbbbbbbbbbbb);", 8135 Style); 8136 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 8137 Style.AlignOperands = FormatStyle::OAS_DontAlign; 8138 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 8139 " bbbbbbbbbbbbbbbbbbbbbb);", 8140 Style); 8141 } 8142 8143 TEST_F(FormatTest, BreaksConditionalExpressions) { 8144 verifyFormat( 8145 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8146 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8147 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8148 verifyFormat( 8149 "aaaa(aaaaaaaaaa, aaaaaaaa,\n" 8150 " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8151 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8152 verifyFormat( 8153 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8154 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8155 verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n" 8156 " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8157 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8158 verifyFormat( 8159 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n" 8160 " : aaaaaaaaaaaaa);"); 8161 verifyFormat( 8162 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8163 " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8164 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8165 " aaaaaaaaaaaaa);"); 8166 verifyFormat( 8167 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8168 " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8169 " aaaaaaaaaaaaa);"); 8170 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8171 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8172 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8173 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8174 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8175 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8176 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8177 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8178 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8179 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8180 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8181 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8182 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8183 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8184 " ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8185 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8186 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8187 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8188 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8189 " : aaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8190 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n" 8191 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8192 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8193 " : aaaaaaaaaaaaaaaa;"); 8194 verifyFormat( 8195 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8196 " ? aaaaaaaaaaaaaaa\n" 8197 " : aaaaaaaaaaaaaaa;"); 8198 verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n" 8199 " aaaaaaaaa\n" 8200 " ? b\n" 8201 " : c);"); 8202 verifyFormat("return aaaa == bbbb\n" 8203 " // comment\n" 8204 " ? aaaa\n" 8205 " : bbbb;"); 8206 verifyFormat("unsigned Indent =\n" 8207 " format(TheLine.First,\n" 8208 " IndentForLevel[TheLine.Level] >= 0\n" 8209 " ? IndentForLevel[TheLine.Level]\n" 8210 " : TheLine * 2,\n" 8211 " TheLine.InPPDirective, PreviousEndOfLineColumn);", 8212 getLLVMStyleWithColumns(60)); 8213 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n" 8214 " ? aaaaaaaaaaaaaaa\n" 8215 " : bbbbbbbbbbbbbbb //\n" 8216 " ? ccccccccccccccc\n" 8217 " : ddddddddddddddd;"); 8218 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n" 8219 " ? aaaaaaaaaaaaaaa\n" 8220 " : (bbbbbbbbbbbbbbb //\n" 8221 " ? ccccccccccccccc\n" 8222 " : ddddddddddddddd);"); 8223 verifyFormat( 8224 "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8225 " ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 8226 " aaaaaaaaaaaaaaaaaaaaa +\n" 8227 " aaaaaaaaaaaaaaaaaaaaa\n" 8228 " : aaaaaaaaaa;"); 8229 verifyFormat( 8230 "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8231 " : aaaaaaaaaaaaaaaaaaaaaa\n" 8232 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8233 8234 FormatStyle NoBinPacking = getLLVMStyle(); 8235 NoBinPacking.BinPackArguments = false; 8236 verifyFormat( 8237 "void f() {\n" 8238 " g(aaa,\n" 8239 " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n" 8240 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8241 " ? aaaaaaaaaaaaaaa\n" 8242 " : aaaaaaaaaaaaaaa);\n" 8243 "}", 8244 NoBinPacking); 8245 verifyFormat( 8246 "void f() {\n" 8247 " g(aaa,\n" 8248 " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n" 8249 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8250 " ?: aaaaaaaaaaaaaaa);\n" 8251 "}", 8252 NoBinPacking); 8253 8254 verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n" 8255 " // comment.\n" 8256 " ccccccccccccccccccccccccccccccccccccccc\n" 8257 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8258 " : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);"); 8259 8260 // Assignments in conditional expressions. Apparently not uncommon :-(. 8261 verifyFormat("return a != b\n" 8262 " // comment\n" 8263 " ? a = b\n" 8264 " : a = b;"); 8265 verifyFormat("return a != b\n" 8266 " // comment\n" 8267 " ? a = a != b\n" 8268 " // comment\n" 8269 " ? a = b\n" 8270 " : a\n" 8271 " : a;\n"); 8272 verifyFormat("return a != b\n" 8273 " // comment\n" 8274 " ? a\n" 8275 " : a = a != b\n" 8276 " // comment\n" 8277 " ? a = b\n" 8278 " : a;"); 8279 8280 // Chained conditionals 8281 FormatStyle Style = getLLVMStyleWithColumns(70); 8282 Style.AlignOperands = FormatStyle::OAS_Align; 8283 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8284 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8285 " : 3333333333333333;", 8286 Style); 8287 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8288 " : bbbbbbbbbb ? 2222222222222222\n" 8289 " : 3333333333333333;", 8290 Style); 8291 verifyFormat("return aaaaaaaaaa ? 1111111111111111\n" 8292 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 8293 " : 3333333333333333;", 8294 Style); 8295 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8296 " : bbbbbbbbbbbbbb ? 222222\n" 8297 " : 333333;", 8298 Style); 8299 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8300 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8301 " : cccccccccccccc ? 3333333333333333\n" 8302 " : 4444444444444444;", 8303 Style); 8304 verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc)\n" 8305 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8306 " : 3333333333333333;", 8307 Style); 8308 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8309 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8310 " : (aaa ? bbb : ccc);", 8311 Style); 8312 verifyFormat( 8313 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8314 " : cccccccccccccccccc)\n" 8315 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8316 " : 3333333333333333;", 8317 Style); 8318 verifyFormat( 8319 "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8320 " : cccccccccccccccccc)\n" 8321 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8322 " : 3333333333333333;", 8323 Style); 8324 verifyFormat( 8325 "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8326 " : dddddddddddddddddd)\n" 8327 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8328 " : 3333333333333333;", 8329 Style); 8330 verifyFormat( 8331 "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8332 " : dddddddddddddddddd)\n" 8333 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8334 " : 3333333333333333;", 8335 Style); 8336 verifyFormat( 8337 "return aaaaaaaaa ? 1111111111111111\n" 8338 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8339 " : a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8340 " : dddddddddddddddddd)\n", 8341 Style); 8342 verifyFormat( 8343 "return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8344 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8345 " : (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8346 " : cccccccccccccccccc);", 8347 Style); 8348 verifyFormat( 8349 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8350 " : ccccccccccccccc ? dddddddddddddddddd\n" 8351 " : eeeeeeeeeeeeeeeeee)\n" 8352 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8353 " : 3333333333333333;", 8354 Style); 8355 verifyFormat( 8356 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8357 " : ccccccccccccccc ? dddddddddddddddddd\n" 8358 " : eeeeeeeeeeeeeeeeee)\n" 8359 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8360 " : 3333333333333333;", 8361 Style); 8362 verifyFormat( 8363 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8364 " : cccccccccccc ? dddddddddddddddddd\n" 8365 " : eeeeeeeeeeeeeeeeee)\n" 8366 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8367 " : 3333333333333333;", 8368 Style); 8369 verifyFormat( 8370 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8371 " : cccccccccccccccccc\n" 8372 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8373 " : 3333333333333333;", 8374 Style); 8375 verifyFormat( 8376 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8377 " : cccccccccccccccc ? dddddddddddddddddd\n" 8378 " : eeeeeeeeeeeeeeeeee\n" 8379 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8380 " : 3333333333333333;", 8381 Style); 8382 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa\n" 8383 " ? (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8384 " : cccccccccccccccccc ? dddddddddddddddddd\n" 8385 " : eeeeeeeeeeeeeeeeee)\n" 8386 " : bbbbbbbbbbbbbbbbbbb ? 2222222222222222\n" 8387 " : 3333333333333333;", 8388 Style); 8389 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaa\n" 8390 " ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8391 " : cccccccccccccccc ? dddddddddddddddddd\n" 8392 " : eeeeeeeeeeeeeeeeee\n" 8393 " : bbbbbbbbbbbbbbbbbbbbbbb ? 2222222222222222\n" 8394 " : 3333333333333333;", 8395 Style); 8396 8397 Style.AlignOperands = FormatStyle::OAS_DontAlign; 8398 Style.BreakBeforeTernaryOperators = false; 8399 // FIXME: Aligning the question marks is weird given DontAlign. 8400 // Consider disabling this alignment in this case. Also check whether this 8401 // will render the adjustment from https://reviews.llvm.org/D82199 8402 // unnecessary. 8403 verifyFormat("int x = aaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa :\n" 8404 " bbbb ? cccccccccccccccccc :\n" 8405 " ddddd;\n", 8406 Style); 8407 8408 EXPECT_EQ( 8409 "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n" 8410 " /*\n" 8411 " */\n" 8412 " function() {\n" 8413 " try {\n" 8414 " return JJJJJJJJJJJJJJ(\n" 8415 " pppppppppppppppppppppppppppppppppppppppppppppppppp);\n" 8416 " }\n" 8417 " } :\n" 8418 " function() {};", 8419 format( 8420 "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n" 8421 " /*\n" 8422 " */\n" 8423 " function() {\n" 8424 " try {\n" 8425 " return JJJJJJJJJJJJJJ(\n" 8426 " pppppppppppppppppppppppppppppppppppppppppppppppppp);\n" 8427 " }\n" 8428 " } :\n" 8429 " function() {};", 8430 getGoogleStyle(FormatStyle::LK_JavaScript))); 8431 } 8432 8433 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) { 8434 FormatStyle Style = getLLVMStyleWithColumns(70); 8435 Style.BreakBeforeTernaryOperators = false; 8436 verifyFormat( 8437 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8438 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8439 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8440 Style); 8441 verifyFormat( 8442 "aaaa(aaaaaaaaaa, aaaaaaaa,\n" 8443 " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8444 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8445 Style); 8446 verifyFormat( 8447 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8448 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8449 Style); 8450 verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n" 8451 " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8452 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8453 Style); 8454 verifyFormat( 8455 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n" 8456 " aaaaaaaaaaaaa);", 8457 Style); 8458 verifyFormat( 8459 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8460 " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8461 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8462 " aaaaaaaaaaaaa);", 8463 Style); 8464 verifyFormat( 8465 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8466 " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8467 " aaaaaaaaaaaaa);", 8468 Style); 8469 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8470 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8471 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 8472 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8473 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8474 Style); 8475 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8476 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8477 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8478 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 8479 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8480 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8481 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8482 Style); 8483 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8484 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n" 8485 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8486 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8487 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8488 Style); 8489 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8490 " aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8491 " aaaaaaaaaaaaaaaaaaaaaaaaaaa;", 8492 Style); 8493 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n" 8494 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8495 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8496 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 8497 Style); 8498 verifyFormat( 8499 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8500 " aaaaaaaaaaaaaaa :\n" 8501 " aaaaaaaaaaaaaaa;", 8502 Style); 8503 verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n" 8504 " aaaaaaaaa ?\n" 8505 " b :\n" 8506 " c);", 8507 Style); 8508 verifyFormat("unsigned Indent =\n" 8509 " format(TheLine.First,\n" 8510 " IndentForLevel[TheLine.Level] >= 0 ?\n" 8511 " IndentForLevel[TheLine.Level] :\n" 8512 " TheLine * 2,\n" 8513 " TheLine.InPPDirective, PreviousEndOfLineColumn);", 8514 Style); 8515 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n" 8516 " aaaaaaaaaaaaaaa :\n" 8517 " bbbbbbbbbbbbbbb ? //\n" 8518 " ccccccccccccccc :\n" 8519 " ddddddddddddddd;", 8520 Style); 8521 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n" 8522 " aaaaaaaaaaaaaaa :\n" 8523 " (bbbbbbbbbbbbbbb ? //\n" 8524 " ccccccccccccccc :\n" 8525 " ddddddddddddddd);", 8526 Style); 8527 verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8528 " /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n" 8529 " ccccccccccccccccccccccccccc;", 8530 Style); 8531 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8532 " aaaaa :\n" 8533 " bbbbbbbbbbbbbbb + cccccccccccccccc;", 8534 Style); 8535 8536 // Chained conditionals 8537 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8538 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8539 " 3333333333333333;", 8540 Style); 8541 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8542 " bbbbbbbbbb ? 2222222222222222 :\n" 8543 " 3333333333333333;", 8544 Style); 8545 verifyFormat("return aaaaaaaaaa ? 1111111111111111 :\n" 8546 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8547 " 3333333333333333;", 8548 Style); 8549 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8550 " bbbbbbbbbbbbbbbb ? 222222 :\n" 8551 " 333333;", 8552 Style); 8553 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8554 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8555 " cccccccccccccccc ? 3333333333333333 :\n" 8556 " 4444444444444444;", 8557 Style); 8558 verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc) :\n" 8559 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8560 " 3333333333333333;", 8561 Style); 8562 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8563 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8564 " (aaa ? bbb : ccc);", 8565 Style); 8566 verifyFormat( 8567 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8568 " cccccccccccccccccc) :\n" 8569 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8570 " 3333333333333333;", 8571 Style); 8572 verifyFormat( 8573 "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8574 " cccccccccccccccccc) :\n" 8575 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8576 " 3333333333333333;", 8577 Style); 8578 verifyFormat( 8579 "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8580 " dddddddddddddddddd) :\n" 8581 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8582 " 3333333333333333;", 8583 Style); 8584 verifyFormat( 8585 "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8586 " dddddddddddddddddd) :\n" 8587 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8588 " 3333333333333333;", 8589 Style); 8590 verifyFormat( 8591 "return aaaaaaaaa ? 1111111111111111 :\n" 8592 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8593 " a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8594 " dddddddddddddddddd)\n", 8595 Style); 8596 verifyFormat( 8597 "return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8598 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8599 " (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8600 " cccccccccccccccccc);", 8601 Style); 8602 verifyFormat( 8603 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8604 " ccccccccccccccccc ? dddddddddddddddddd :\n" 8605 " eeeeeeeeeeeeeeeeee) :\n" 8606 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8607 " 3333333333333333;", 8608 Style); 8609 verifyFormat( 8610 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8611 " ccccccccccccc ? dddddddddddddddddd :\n" 8612 " eeeeeeeeeeeeeeeeee) :\n" 8613 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8614 " 3333333333333333;", 8615 Style); 8616 verifyFormat( 8617 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8618 " ccccccccccccccccc ? dddddddddddddddddd :\n" 8619 " eeeeeeeeeeeeeeeeee) :\n" 8620 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8621 " 3333333333333333;", 8622 Style); 8623 verifyFormat( 8624 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8625 " cccccccccccccccccc :\n" 8626 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8627 " 3333333333333333;", 8628 Style); 8629 verifyFormat( 8630 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8631 " cccccccccccccccccc ? dddddddddddddddddd :\n" 8632 " eeeeeeeeeeeeeeeeee :\n" 8633 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8634 " 3333333333333333;", 8635 Style); 8636 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n" 8637 " (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8638 " cccccccccccccccccc ? dddddddddddddddddd :\n" 8639 " eeeeeeeeeeeeeeeeee) :\n" 8640 " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8641 " 3333333333333333;", 8642 Style); 8643 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n" 8644 " aaaaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8645 " cccccccccccccccccccc ? dddddddddddddddddd :\n" 8646 " eeeeeeeeeeeeeeeeee :\n" 8647 " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8648 " 3333333333333333;", 8649 Style); 8650 } 8651 8652 TEST_F(FormatTest, DeclarationsOfMultipleVariables) { 8653 verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n" 8654 " aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();"); 8655 verifyFormat("bool a = true, b = false;"); 8656 8657 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n" 8658 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n" 8659 " bbbbbbbbbbbbbbbbbbbbbbbbb =\n" 8660 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);"); 8661 verifyFormat( 8662 "bool aaaaaaaaaaaaaaaaaaaaa =\n" 8663 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n" 8664 " d = e && f;"); 8665 verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n" 8666 " c = cccccccccccccccccccc, d = dddddddddddddddddddd;"); 8667 verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n" 8668 " *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;"); 8669 verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n" 8670 " ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;"); 8671 8672 FormatStyle Style = getGoogleStyle(); 8673 Style.PointerAlignment = FormatStyle::PAS_Left; 8674 Style.DerivePointerAlignment = false; 8675 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8676 " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n" 8677 " *b = bbbbbbbbbbbbbbbbbbb;", 8678 Style); 8679 verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n" 8680 " *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;", 8681 Style); 8682 verifyFormat("vector<int*> a, b;", Style); 8683 verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style); 8684 verifyFormat("/*comment*/ for (int *p, *q; p != q; p = p->next) {\n}", Style); 8685 verifyFormat("if (int *p, *q; p != q) {\n p = p->next;\n}", Style); 8686 verifyFormat("/*comment*/ if (int *p, *q; p != q) {\n p = p->next;\n}", 8687 Style); 8688 verifyFormat("switch (int *p, *q; p != q) {\n default:\n break;\n}", 8689 Style); 8690 verifyFormat( 8691 "/*comment*/ switch (int *p, *q; p != q) {\n default:\n break;\n}", 8692 Style); 8693 8694 verifyFormat("if ([](int* p, int* q) {}()) {\n}", Style); 8695 verifyFormat("for ([](int* p, int* q) {}();;) {\n}", Style); 8696 verifyFormat("for (; [](int* p, int* q) {}();) {\n}", Style); 8697 verifyFormat("for (;; [](int* p, int* q) {}()) {\n}", Style); 8698 verifyFormat("switch ([](int* p, int* q) {}()) {\n default:\n break;\n}", 8699 Style); 8700 } 8701 8702 TEST_F(FormatTest, ConditionalExpressionsInBrackets) { 8703 verifyFormat("arr[foo ? bar : baz];"); 8704 verifyFormat("f()[foo ? bar : baz];"); 8705 verifyFormat("(a + b)[foo ? bar : baz];"); 8706 verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];"); 8707 } 8708 8709 TEST_F(FormatTest, AlignsStringLiterals) { 8710 verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n" 8711 " \"short literal\");"); 8712 verifyFormat( 8713 "looooooooooooooooooooooooongFunction(\n" 8714 " \"short literal\"\n" 8715 " \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");"); 8716 verifyFormat("someFunction(\"Always break between multi-line\"\n" 8717 " \" string literals\",\n" 8718 " and, other, parameters);"); 8719 EXPECT_EQ("fun + \"1243\" /* comment */\n" 8720 " \"5678\";", 8721 format("fun + \"1243\" /* comment */\n" 8722 " \"5678\";", 8723 getLLVMStyleWithColumns(28))); 8724 EXPECT_EQ( 8725 "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 8726 " \"aaaaaaaaaaaaaaaaaaaaa\"\n" 8727 " \"aaaaaaaaaaaaaaaa\";", 8728 format("aaaaaa =" 8729 "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa " 8730 "aaaaaaaaaaaaaaaaaaaaa\" " 8731 "\"aaaaaaaaaaaaaaaa\";")); 8732 verifyFormat("a = a + \"a\"\n" 8733 " \"a\"\n" 8734 " \"a\";"); 8735 verifyFormat("f(\"a\", \"b\"\n" 8736 " \"c\");"); 8737 8738 verifyFormat( 8739 "#define LL_FORMAT \"ll\"\n" 8740 "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n" 8741 " \"d, ddddddddd: %\" LL_FORMAT \"d\");"); 8742 8743 verifyFormat("#define A(X) \\\n" 8744 " \"aaaaa\" #X \"bbbbbb\" \\\n" 8745 " \"ccccc\"", 8746 getLLVMStyleWithColumns(23)); 8747 verifyFormat("#define A \"def\"\n" 8748 "f(\"abc\" A \"ghi\"\n" 8749 " \"jkl\");"); 8750 8751 verifyFormat("f(L\"a\"\n" 8752 " L\"b\");"); 8753 verifyFormat("#define A(X) \\\n" 8754 " L\"aaaaa\" #X L\"bbbbbb\" \\\n" 8755 " L\"ccccc\"", 8756 getLLVMStyleWithColumns(25)); 8757 8758 verifyFormat("f(@\"a\"\n" 8759 " @\"b\");"); 8760 verifyFormat("NSString s = @\"a\"\n" 8761 " @\"b\"\n" 8762 " @\"c\";"); 8763 verifyFormat("NSString s = @\"a\"\n" 8764 " \"b\"\n" 8765 " \"c\";"); 8766 } 8767 8768 TEST_F(FormatTest, ReturnTypeBreakingStyle) { 8769 FormatStyle Style = getLLVMStyle(); 8770 // No declarations or definitions should be moved to own line. 8771 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None; 8772 verifyFormat("class A {\n" 8773 " int f() { return 1; }\n" 8774 " int g();\n" 8775 "};\n" 8776 "int f() { return 1; }\n" 8777 "int g();\n", 8778 Style); 8779 8780 // All declarations and definitions should have the return type moved to its 8781 // own line. 8782 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 8783 Style.TypenameMacros = {"LIST"}; 8784 verifyFormat("SomeType\n" 8785 "funcdecl(LIST(uint64_t));", 8786 Style); 8787 verifyFormat("class E {\n" 8788 " int\n" 8789 " f() {\n" 8790 " return 1;\n" 8791 " }\n" 8792 " int\n" 8793 " g();\n" 8794 "};\n" 8795 "int\n" 8796 "f() {\n" 8797 " return 1;\n" 8798 "}\n" 8799 "int\n" 8800 "g();\n", 8801 Style); 8802 8803 // Top-level definitions, and no kinds of declarations should have the 8804 // return type moved to its own line. 8805 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions; 8806 verifyFormat("class B {\n" 8807 " int f() { return 1; }\n" 8808 " int g();\n" 8809 "};\n" 8810 "int\n" 8811 "f() {\n" 8812 " return 1;\n" 8813 "}\n" 8814 "int g();\n", 8815 Style); 8816 8817 // Top-level definitions and declarations should have the return type moved 8818 // to its own line. 8819 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel; 8820 verifyFormat("class C {\n" 8821 " int f() { return 1; }\n" 8822 " int g();\n" 8823 "};\n" 8824 "int\n" 8825 "f() {\n" 8826 " return 1;\n" 8827 "}\n" 8828 "int\n" 8829 "g();\n", 8830 Style); 8831 8832 // All definitions should have the return type moved to its own line, but no 8833 // kinds of declarations. 8834 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions; 8835 verifyFormat("class D {\n" 8836 " int\n" 8837 " f() {\n" 8838 " return 1;\n" 8839 " }\n" 8840 " int g();\n" 8841 "};\n" 8842 "int\n" 8843 "f() {\n" 8844 " return 1;\n" 8845 "}\n" 8846 "int g();\n", 8847 Style); 8848 verifyFormat("const char *\n" 8849 "f(void) {\n" // Break here. 8850 " return \"\";\n" 8851 "}\n" 8852 "const char *bar(void);\n", // No break here. 8853 Style); 8854 verifyFormat("template <class T>\n" 8855 "T *\n" 8856 "f(T &c) {\n" // Break here. 8857 " return NULL;\n" 8858 "}\n" 8859 "template <class T> T *f(T &c);\n", // No break here. 8860 Style); 8861 verifyFormat("class C {\n" 8862 " int\n" 8863 " operator+() {\n" 8864 " return 1;\n" 8865 " }\n" 8866 " int\n" 8867 " operator()() {\n" 8868 " return 1;\n" 8869 " }\n" 8870 "};\n", 8871 Style); 8872 verifyFormat("void\n" 8873 "A::operator()() {}\n" 8874 "void\n" 8875 "A::operator>>() {}\n" 8876 "void\n" 8877 "A::operator+() {}\n" 8878 "void\n" 8879 "A::operator*() {}\n" 8880 "void\n" 8881 "A::operator->() {}\n" 8882 "void\n" 8883 "A::operator void *() {}\n" 8884 "void\n" 8885 "A::operator void &() {}\n" 8886 "void\n" 8887 "A::operator void &&() {}\n" 8888 "void\n" 8889 "A::operator char *() {}\n" 8890 "void\n" 8891 "A::operator[]() {}\n" 8892 "void\n" 8893 "A::operator!() {}\n" 8894 "void\n" 8895 "A::operator**() {}\n" 8896 "void\n" 8897 "A::operator<Foo> *() {}\n" 8898 "void\n" 8899 "A::operator<Foo> **() {}\n" 8900 "void\n" 8901 "A::operator<Foo> &() {}\n" 8902 "void\n" 8903 "A::operator void **() {}\n", 8904 Style); 8905 verifyFormat("constexpr auto\n" 8906 "operator()() const -> reference {}\n" 8907 "constexpr auto\n" 8908 "operator>>() const -> reference {}\n" 8909 "constexpr auto\n" 8910 "operator+() const -> reference {}\n" 8911 "constexpr auto\n" 8912 "operator*() const -> reference {}\n" 8913 "constexpr auto\n" 8914 "operator->() const -> reference {}\n" 8915 "constexpr auto\n" 8916 "operator++() const -> reference {}\n" 8917 "constexpr auto\n" 8918 "operator void *() const -> reference {}\n" 8919 "constexpr auto\n" 8920 "operator void **() const -> reference {}\n" 8921 "constexpr auto\n" 8922 "operator void *() const -> reference {}\n" 8923 "constexpr auto\n" 8924 "operator void &() const -> reference {}\n" 8925 "constexpr auto\n" 8926 "operator void &&() const -> reference {}\n" 8927 "constexpr auto\n" 8928 "operator char *() const -> reference {}\n" 8929 "constexpr auto\n" 8930 "operator!() const -> reference {}\n" 8931 "constexpr auto\n" 8932 "operator[]() const -> reference {}\n", 8933 Style); 8934 verifyFormat("void *operator new(std::size_t s);", // No break here. 8935 Style); 8936 verifyFormat("void *\n" 8937 "operator new(std::size_t s) {}", 8938 Style); 8939 verifyFormat("void *\n" 8940 "operator delete[](void *ptr) {}", 8941 Style); 8942 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 8943 verifyFormat("const char *\n" 8944 "f(void)\n" // Break here. 8945 "{\n" 8946 " return \"\";\n" 8947 "}\n" 8948 "const char *bar(void);\n", // No break here. 8949 Style); 8950 verifyFormat("template <class T>\n" 8951 "T *\n" // Problem here: no line break 8952 "f(T &c)\n" // Break here. 8953 "{\n" 8954 " return NULL;\n" 8955 "}\n" 8956 "template <class T> T *f(T &c);\n", // No break here. 8957 Style); 8958 verifyFormat("int\n" 8959 "foo(A<bool> a)\n" 8960 "{\n" 8961 " return a;\n" 8962 "}\n", 8963 Style); 8964 verifyFormat("int\n" 8965 "foo(A<8> a)\n" 8966 "{\n" 8967 " return a;\n" 8968 "}\n", 8969 Style); 8970 verifyFormat("int\n" 8971 "foo(A<B<bool>, 8> a)\n" 8972 "{\n" 8973 " return a;\n" 8974 "}\n", 8975 Style); 8976 verifyFormat("int\n" 8977 "foo(A<B<8>, bool> a)\n" 8978 "{\n" 8979 " return a;\n" 8980 "}\n", 8981 Style); 8982 verifyFormat("int\n" 8983 "foo(A<B<bool>, bool> a)\n" 8984 "{\n" 8985 " return a;\n" 8986 "}\n", 8987 Style); 8988 verifyFormat("int\n" 8989 "foo(A<B<8>, 8> a)\n" 8990 "{\n" 8991 " return a;\n" 8992 "}\n", 8993 Style); 8994 8995 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 8996 Style.BraceWrapping.AfterFunction = true; 8997 verifyFormat("int f(i);\n" // No break here. 8998 "int\n" // Break here. 8999 "f(i)\n" 9000 "{\n" 9001 " return i + 1;\n" 9002 "}\n" 9003 "int\n" // Break here. 9004 "f(i)\n" 9005 "{\n" 9006 " return i + 1;\n" 9007 "};", 9008 Style); 9009 verifyFormat("int f(a, b, c);\n" // No break here. 9010 "int\n" // Break here. 9011 "f(a, b, c)\n" // Break here. 9012 "short a, b;\n" 9013 "float c;\n" 9014 "{\n" 9015 " return a + b < c;\n" 9016 "}\n" 9017 "int\n" // Break here. 9018 "f(a, b, c)\n" // Break here. 9019 "short a, b;\n" 9020 "float c;\n" 9021 "{\n" 9022 " return a + b < c;\n" 9023 "};", 9024 Style); 9025 verifyFormat("byte *\n" // Break here. 9026 "f(a)\n" // Break here. 9027 "byte a[];\n" 9028 "{\n" 9029 " return a;\n" 9030 "}", 9031 Style); 9032 verifyFormat("bool f(int a, int) override;\n" 9033 "Bar g(int a, Bar) final;\n" 9034 "Bar h(a, Bar) final;", 9035 Style); 9036 verifyFormat("int\n" 9037 "f(a)", 9038 Style); 9039 verifyFormat("bool\n" 9040 "f(size_t = 0, bool b = false)\n" 9041 "{\n" 9042 " return !b;\n" 9043 "}", 9044 Style); 9045 9046 // The return breaking style doesn't affect: 9047 // * function and object definitions with attribute-like macros 9048 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 9049 " ABSL_GUARDED_BY(mutex) = {};", 9050 getGoogleStyleWithColumns(40)); 9051 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 9052 " ABSL_GUARDED_BY(mutex); // comment", 9053 getGoogleStyleWithColumns(40)); 9054 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 9055 " ABSL_GUARDED_BY(mutex1)\n" 9056 " ABSL_GUARDED_BY(mutex2);", 9057 getGoogleStyleWithColumns(40)); 9058 verifyFormat("Tttttt f(int a, int b)\n" 9059 " ABSL_GUARDED_BY(mutex1)\n" 9060 " ABSL_GUARDED_BY(mutex2);", 9061 getGoogleStyleWithColumns(40)); 9062 // * typedefs 9063 verifyFormat("typedef ATTR(X) char x;", getGoogleStyle()); 9064 9065 Style = getGNUStyle(); 9066 9067 // Test for comments at the end of function declarations. 9068 verifyFormat("void\n" 9069 "foo (int a, /*abc*/ int b) // def\n" 9070 "{\n" 9071 "}\n", 9072 Style); 9073 9074 verifyFormat("void\n" 9075 "foo (int a, /* abc */ int b) /* def */\n" 9076 "{\n" 9077 "}\n", 9078 Style); 9079 9080 // Definitions that should not break after return type 9081 verifyFormat("void foo (int a, int b); // def\n", Style); 9082 verifyFormat("void foo (int a, int b); /* def */\n", Style); 9083 verifyFormat("void foo (int a, int b);\n", Style); 9084 } 9085 9086 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) { 9087 FormatStyle NoBreak = getLLVMStyle(); 9088 NoBreak.AlwaysBreakBeforeMultilineStrings = false; 9089 FormatStyle Break = getLLVMStyle(); 9090 Break.AlwaysBreakBeforeMultilineStrings = true; 9091 verifyFormat("aaaa = \"bbbb\"\n" 9092 " \"cccc\";", 9093 NoBreak); 9094 verifyFormat("aaaa =\n" 9095 " \"bbbb\"\n" 9096 " \"cccc\";", 9097 Break); 9098 verifyFormat("aaaa(\"bbbb\"\n" 9099 " \"cccc\");", 9100 NoBreak); 9101 verifyFormat("aaaa(\n" 9102 " \"bbbb\"\n" 9103 " \"cccc\");", 9104 Break); 9105 verifyFormat("aaaa(qqq, \"bbbb\"\n" 9106 " \"cccc\");", 9107 NoBreak); 9108 verifyFormat("aaaa(qqq,\n" 9109 " \"bbbb\"\n" 9110 " \"cccc\");", 9111 Break); 9112 verifyFormat("aaaa(qqq,\n" 9113 " L\"bbbb\"\n" 9114 " L\"cccc\");", 9115 Break); 9116 verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n" 9117 " \"bbbb\"));", 9118 Break); 9119 verifyFormat("string s = someFunction(\n" 9120 " \"abc\"\n" 9121 " \"abc\");", 9122 Break); 9123 9124 // As we break before unary operators, breaking right after them is bad. 9125 verifyFormat("string foo = abc ? \"x\"\n" 9126 " \"blah blah blah blah blah blah\"\n" 9127 " : \"y\";", 9128 Break); 9129 9130 // Don't break if there is no column gain. 9131 verifyFormat("f(\"aaaa\"\n" 9132 " \"bbbb\");", 9133 Break); 9134 9135 // Treat literals with escaped newlines like multi-line string literals. 9136 EXPECT_EQ("x = \"a\\\n" 9137 "b\\\n" 9138 "c\";", 9139 format("x = \"a\\\n" 9140 "b\\\n" 9141 "c\";", 9142 NoBreak)); 9143 EXPECT_EQ("xxxx =\n" 9144 " \"a\\\n" 9145 "b\\\n" 9146 "c\";", 9147 format("xxxx = \"a\\\n" 9148 "b\\\n" 9149 "c\";", 9150 Break)); 9151 9152 EXPECT_EQ("NSString *const kString =\n" 9153 " @\"aaaa\"\n" 9154 " @\"bbbb\";", 9155 format("NSString *const kString = @\"aaaa\"\n" 9156 "@\"bbbb\";", 9157 Break)); 9158 9159 Break.ColumnLimit = 0; 9160 verifyFormat("const char *hello = \"hello llvm\";", Break); 9161 } 9162 9163 TEST_F(FormatTest, AlignsPipes) { 9164 verifyFormat( 9165 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9166 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9167 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9168 verifyFormat( 9169 "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n" 9170 " << aaaaaaaaaaaaaaaaaaaa;"); 9171 verifyFormat( 9172 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9173 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9174 verifyFormat( 9175 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 9176 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9177 verifyFormat( 9178 "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n" 9179 " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n" 9180 " << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";"); 9181 verifyFormat( 9182 "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9183 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9184 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9185 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9186 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9187 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9188 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 9189 verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n" 9190 " << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);"); 9191 verifyFormat( 9192 "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9193 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9194 verifyFormat( 9195 "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n" 9196 " aaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9197 9198 verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n" 9199 " << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();"); 9200 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9201 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9202 " aaaaaaaaaaaaaaaaaaaaa)\n" 9203 " << aaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9204 verifyFormat("LOG_IF(aaa == //\n" 9205 " bbb)\n" 9206 " << a << b;"); 9207 9208 // But sometimes, breaking before the first "<<" is desirable. 9209 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 9210 " << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);"); 9211 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n" 9212 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9213 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9214 verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n" 9215 " << BEF << IsTemplate << Description << E->getType();"); 9216 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 9217 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9218 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9219 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 9220 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9221 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9222 " << aaa;"); 9223 9224 verifyFormat( 9225 "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9226 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9227 9228 // Incomplete string literal. 9229 EXPECT_EQ("llvm::errs() << \"\n" 9230 " << a;", 9231 format("llvm::errs() << \"\n<<a;")); 9232 9233 verifyFormat("void f() {\n" 9234 " CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n" 9235 " << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n" 9236 "}"); 9237 9238 // Handle 'endl'. 9239 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n" 9240 " << bbbbbbbbbbbbbbbbbbbbbb << endl;"); 9241 verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;"); 9242 9243 // Handle '\n'. 9244 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n" 9245 " << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";"); 9246 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n" 9247 " << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';"); 9248 verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n" 9249 " << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";"); 9250 verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";"); 9251 } 9252 9253 TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) { 9254 verifyFormat("return out << \"somepacket = {\\n\"\n" 9255 " << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n" 9256 " << \" bbbb = \" << pkt.bbbb << \"\\n\"\n" 9257 " << \" cccccc = \" << pkt.cccccc << \"\\n\"\n" 9258 " << \" ddd = [\" << pkt.ddd << \"]\\n\"\n" 9259 " << \"}\";"); 9260 9261 verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n" 9262 " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n" 9263 " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;"); 9264 verifyFormat( 9265 "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n" 9266 " << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n" 9267 " << \"ccccccccccccccccc = \" << ccccccccccccccccc\n" 9268 " << \"ddddddddddddddddd = \" << ddddddddddddddddd\n" 9269 " << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;"); 9270 verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n" 9271 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 9272 verifyFormat( 9273 "void f() {\n" 9274 " llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n" 9275 " << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 9276 "}"); 9277 9278 // Breaking before the first "<<" is generally not desirable. 9279 verifyFormat( 9280 "llvm::errs()\n" 9281 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9282 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9283 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9284 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 9285 getLLVMStyleWithColumns(70)); 9286 verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n" 9287 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9288 " << \"aaaaaaaaaaaaaaaaaaa: \"\n" 9289 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9290 " << \"aaaaaaaaaaaaaaaaaaa: \"\n" 9291 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 9292 getLLVMStyleWithColumns(70)); 9293 9294 verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n" 9295 " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n" 9296 " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;"); 9297 verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n" 9298 " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n" 9299 " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);"); 9300 verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n" 9301 " (aaaa + aaaa);", 9302 getLLVMStyleWithColumns(40)); 9303 verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n" 9304 " (aaaaaaa + aaaaa));", 9305 getLLVMStyleWithColumns(40)); 9306 verifyFormat( 9307 "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n" 9308 " SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n" 9309 " bbbbbbbbbbbbbbbbbbbbbbb);"); 9310 } 9311 9312 TEST_F(FormatTest, UnderstandsEquals) { 9313 verifyFormat( 9314 "aaaaaaaaaaaaaaaaa =\n" 9315 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9316 verifyFormat( 9317 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9318 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 9319 verifyFormat( 9320 "if (a) {\n" 9321 " f();\n" 9322 "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9323 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 9324 "}"); 9325 9326 verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9327 " 100000000 + 10000000) {\n}"); 9328 } 9329 9330 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) { 9331 verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n" 9332 " .looooooooooooooooooooooooooooooooooooooongFunction();"); 9333 9334 verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n" 9335 " ->looooooooooooooooooooooooooooooooooooooongFunction();"); 9336 9337 verifyFormat( 9338 "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n" 9339 " Parameter2);"); 9340 9341 verifyFormat( 9342 "ShortObject->shortFunction(\n" 9343 " LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n" 9344 " LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);"); 9345 9346 verifyFormat("loooooooooooooongFunction(\n" 9347 " LoooooooooooooongObject->looooooooooooooooongFunction());"); 9348 9349 verifyFormat( 9350 "function(LoooooooooooooooooooooooooooooooooooongObject\n" 9351 " ->loooooooooooooooooooooooooooooooooooooooongFunction());"); 9352 9353 verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n" 9354 " .WillRepeatedly(Return(SomeValue));"); 9355 verifyFormat("void f() {\n" 9356 " EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n" 9357 " .Times(2)\n" 9358 " .WillRepeatedly(Return(SomeValue));\n" 9359 "}"); 9360 verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n" 9361 " ccccccccccccccccccccccc);"); 9362 verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9363 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9364 " .aaaaa(aaaaa),\n" 9365 " aaaaaaaaaaaaaaaaaaaaa);"); 9366 verifyFormat("void f() {\n" 9367 " aaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9368 " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n" 9369 "}"); 9370 verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9371 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9372 " .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9373 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9374 " aaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 9375 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9376 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9377 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9378 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n" 9379 "}"); 9380 9381 // Here, it is not necessary to wrap at "." or "->". 9382 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n" 9383 " aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 9384 verifyFormat( 9385 "aaaaaaaaaaa->aaaaaaaaa(\n" 9386 " aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9387 " aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n"); 9388 9389 verifyFormat( 9390 "aaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9391 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());"); 9392 verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n" 9393 " aaaaaaaaa()->aaaaaa()->aaaaa());"); 9394 verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n" 9395 " aaaaaaaaa()->aaaaaa()->aaaaa());"); 9396 9397 verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9398 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9399 " .a();"); 9400 9401 FormatStyle NoBinPacking = getLLVMStyle(); 9402 NoBinPacking.BinPackParameters = false; 9403 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n" 9404 " .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n" 9405 " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n" 9406 " aaaaaaaaaaaaaaaaaaa,\n" 9407 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 9408 NoBinPacking); 9409 9410 // If there is a subsequent call, change to hanging indentation. 9411 verifyFormat( 9412 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9413 " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n" 9414 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9415 verifyFormat( 9416 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9417 " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));"); 9418 verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9419 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9420 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9421 verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9422 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9423 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());"); 9424 } 9425 9426 TEST_F(FormatTest, WrapsTemplateDeclarations) { 9427 verifyFormat("template <typename T>\n" 9428 "virtual void loooooooooooongFunction(int Param1, int Param2);"); 9429 verifyFormat("template <typename T>\n" 9430 "// T should be one of {A, B}.\n" 9431 "virtual void loooooooooooongFunction(int Param1, int Param2);"); 9432 verifyFormat( 9433 "template <typename T>\n" 9434 "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;"); 9435 verifyFormat("template <typename T>\n" 9436 "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n" 9437 " int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);"); 9438 verifyFormat( 9439 "template <typename T>\n" 9440 "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n" 9441 " int Paaaaaaaaaaaaaaaaaaaaram2);"); 9442 verifyFormat( 9443 "template <typename T>\n" 9444 "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n" 9445 " aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n" 9446 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9447 verifyFormat("template <typename T>\n" 9448 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9449 " int aaaaaaaaaaaaaaaaaaaaaa);"); 9450 verifyFormat( 9451 "template <typename T1, typename T2 = char, typename T3 = char,\n" 9452 " typename T4 = char>\n" 9453 "void f();"); 9454 verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n" 9455 " template <typename> class cccccccccccccccccccccc,\n" 9456 " typename ddddddddddddd>\n" 9457 "class C {};"); 9458 verifyFormat( 9459 "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n" 9460 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9461 9462 verifyFormat("void f() {\n" 9463 " a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n" 9464 " a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n" 9465 "}"); 9466 9467 verifyFormat("template <typename T> class C {};"); 9468 verifyFormat("template <typename T> void f();"); 9469 verifyFormat("template <typename T> void f() {}"); 9470 verifyFormat( 9471 "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n" 9472 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9473 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n" 9474 " new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n" 9475 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9476 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n" 9477 " bbbbbbbbbbbbbbbbbbbbbbbb);", 9478 getLLVMStyleWithColumns(72)); 9479 EXPECT_EQ("static_cast<A< //\n" 9480 " B> *>(\n" 9481 "\n" 9482 ");", 9483 format("static_cast<A<//\n" 9484 " B>*>(\n" 9485 "\n" 9486 " );")); 9487 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9488 " const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);"); 9489 9490 FormatStyle AlwaysBreak = getLLVMStyle(); 9491 AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 9492 verifyFormat("template <typename T>\nclass C {};", AlwaysBreak); 9493 verifyFormat("template <typename T>\nvoid f();", AlwaysBreak); 9494 verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak); 9495 verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9496 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n" 9497 " ccccccccccccccccccccccccccccccccccccccccccccccc);"); 9498 verifyFormat("template <template <typename> class Fooooooo,\n" 9499 " template <typename> class Baaaaaaar>\n" 9500 "struct C {};", 9501 AlwaysBreak); 9502 verifyFormat("template <typename T> // T can be A, B or C.\n" 9503 "struct C {};", 9504 AlwaysBreak); 9505 verifyFormat("template <enum E> class A {\n" 9506 "public:\n" 9507 " E *f();\n" 9508 "};"); 9509 9510 FormatStyle NeverBreak = getLLVMStyle(); 9511 NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No; 9512 verifyFormat("template <typename T> class C {};", NeverBreak); 9513 verifyFormat("template <typename T> void f();", NeverBreak); 9514 verifyFormat("template <typename T> void f() {}", NeverBreak); 9515 verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa " 9516 "bbbbbbbbbbbbbbbbbbbb) {}", 9517 NeverBreak); 9518 verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9519 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n" 9520 " ccccccccccccccccccccccccccccccccccccccccccccccc);", 9521 NeverBreak); 9522 verifyFormat("template <template <typename> class Fooooooo,\n" 9523 " template <typename> class Baaaaaaar>\n" 9524 "struct C {};", 9525 NeverBreak); 9526 verifyFormat("template <typename T> // T can be A, B or C.\n" 9527 "struct C {};", 9528 NeverBreak); 9529 verifyFormat("template <enum E> class A {\n" 9530 "public:\n" 9531 " E *f();\n" 9532 "};", 9533 NeverBreak); 9534 NeverBreak.PenaltyBreakTemplateDeclaration = 100; 9535 verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa " 9536 "bbbbbbbbbbbbbbbbbbbb) {}", 9537 NeverBreak); 9538 } 9539 9540 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) { 9541 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp); 9542 Style.ColumnLimit = 60; 9543 EXPECT_EQ("// Baseline - no comments.\n" 9544 "template <\n" 9545 " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n" 9546 "void f() {}", 9547 format("// Baseline - no comments.\n" 9548 "template <\n" 9549 " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n" 9550 "void f() {}", 9551 Style)); 9552 9553 EXPECT_EQ("template <\n" 9554 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9555 "void f() {}", 9556 format("template <\n" 9557 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9558 "void f() {}", 9559 Style)); 9560 9561 EXPECT_EQ( 9562 "template <\n" 9563 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n" 9564 "void f() {}", 9565 format("template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n" 9566 "void f() {}", 9567 Style)); 9568 9569 EXPECT_EQ( 9570 "template <\n" 9571 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9572 " // multiline\n" 9573 "void f() {}", 9574 format("template <\n" 9575 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9576 " // multiline\n" 9577 "void f() {}", 9578 Style)); 9579 9580 EXPECT_EQ( 9581 "template <typename aaaaaaaaaa<\n" 9582 " bbbbbbbbbbbb>::value> // trailing loooong\n" 9583 "void f() {}", 9584 format( 9585 "template <\n" 9586 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n" 9587 "void f() {}", 9588 Style)); 9589 } 9590 9591 TEST_F(FormatTest, WrapsTemplateParameters) { 9592 FormatStyle Style = getLLVMStyle(); 9593 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 9594 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 9595 verifyFormat( 9596 "template <typename... a> struct q {};\n" 9597 "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n" 9598 " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n" 9599 " y;", 9600 Style); 9601 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 9602 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 9603 verifyFormat( 9604 "template <typename... a> struct r {};\n" 9605 "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n" 9606 " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n" 9607 " y;", 9608 Style); 9609 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 9610 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 9611 verifyFormat("template <typename... a> struct s {};\n" 9612 "extern s<\n" 9613 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9614 "aaaaaaaaaaaaaaaaaaaaaa,\n" 9615 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9616 "aaaaaaaaaaaaaaaaaaaaaa>\n" 9617 " y;", 9618 Style); 9619 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 9620 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 9621 verifyFormat("template <typename... a> struct t {};\n" 9622 "extern t<\n" 9623 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9624 "aaaaaaaaaaaaaaaaaaaaaa,\n" 9625 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9626 "aaaaaaaaaaaaaaaaaaaaaa>\n" 9627 " y;", 9628 Style); 9629 } 9630 9631 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) { 9632 verifyFormat( 9633 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9634 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9635 verifyFormat( 9636 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9637 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9638 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());"); 9639 9640 // FIXME: Should we have the extra indent after the second break? 9641 verifyFormat( 9642 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9643 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9644 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9645 9646 verifyFormat( 9647 "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n" 9648 " cccccccccccccccccccccccccccccccccccccccccccccc());"); 9649 9650 // Breaking at nested name specifiers is generally not desirable. 9651 verifyFormat( 9652 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9653 " aaaaaaaaaaaaaaaaaaaaaaa);"); 9654 9655 verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n" 9656 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9657 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9658 " aaaaaaaaaaaaaaaaaaaaa);", 9659 getLLVMStyleWithColumns(74)); 9660 9661 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9662 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9663 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9664 } 9665 9666 TEST_F(FormatTest, UnderstandsTemplateParameters) { 9667 verifyFormat("A<int> a;"); 9668 verifyFormat("A<A<A<int>>> a;"); 9669 verifyFormat("A<A<A<int, 2>, 3>, 4> a;"); 9670 verifyFormat("bool x = a < 1 || 2 > a;"); 9671 verifyFormat("bool x = 5 < f<int>();"); 9672 verifyFormat("bool x = f<int>() > 5;"); 9673 verifyFormat("bool x = 5 < a<int>::x;"); 9674 verifyFormat("bool x = a < 4 ? a > 2 : false;"); 9675 verifyFormat("bool x = f() ? a < 2 : a > 2;"); 9676 9677 verifyGoogleFormat("A<A<int>> a;"); 9678 verifyGoogleFormat("A<A<A<int>>> a;"); 9679 verifyGoogleFormat("A<A<A<A<int>>>> a;"); 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;"); 9685 verifyGoogleFormat("A< ::A> a;"); 9686 verifyGoogleFormat("A< ::A<int> > a;"); 9687 EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle())); 9688 EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle())); 9689 EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle())); 9690 EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle())); 9691 EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };", 9692 format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle())); 9693 9694 verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp)); 9695 9696 // template closer followed by a token that starts with > or = 9697 verifyFormat("bool b = a<1> > 1;"); 9698 verifyFormat("bool b = a<1> >= 1;"); 9699 verifyFormat("int i = a<1> >> 1;"); 9700 FormatStyle Style = getLLVMStyle(); 9701 Style.SpaceBeforeAssignmentOperators = false; 9702 verifyFormat("bool b= a<1> == 1;", Style); 9703 verifyFormat("a<int> = 1;", Style); 9704 verifyFormat("a<int> >>= 1;", Style); 9705 9706 verifyFormat("test < a | b >> c;"); 9707 verifyFormat("test<test<a | b>> c;"); 9708 verifyFormat("test >> a >> b;"); 9709 verifyFormat("test << a >> b;"); 9710 9711 verifyFormat("f<int>();"); 9712 verifyFormat("template <typename T> void f() {}"); 9713 verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;"); 9714 verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : " 9715 "sizeof(char)>::type>;"); 9716 verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};"); 9717 verifyFormat("f(a.operator()<A>());"); 9718 verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9719 " .template operator()<A>());", 9720 getLLVMStyleWithColumns(35)); 9721 verifyFormat("bool_constant<a && noexcept(f())>"); 9722 verifyFormat("bool_constant<a || noexcept(f())>"); 9723 9724 // Not template parameters. 9725 verifyFormat("return a < b && c > d;"); 9726 verifyFormat("void f() {\n" 9727 " while (a < b && c > d) {\n" 9728 " }\n" 9729 "}"); 9730 verifyFormat("template <typename... Types>\n" 9731 "typename enable_if<0 < sizeof...(Types)>::type Foo() {}"); 9732 9733 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9734 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);", 9735 getLLVMStyleWithColumns(60)); 9736 verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");"); 9737 verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}"); 9738 verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <"); 9739 verifyFormat("some_templated_type<decltype([](int i) { return i; })>"); 9740 } 9741 9742 TEST_F(FormatTest, UnderstandsShiftOperators) { 9743 verifyFormat("if (i < x >> 1)"); 9744 verifyFormat("while (i < x >> 1)"); 9745 verifyFormat("for (unsigned i = 0; i < i; ++i, v = v >> 1)"); 9746 verifyFormat("for (unsigned i = 0; i < x >> 1; ++i, v = v >> 1)"); 9747 verifyFormat( 9748 "for (std::vector<int>::iterator i = 0; i < x >> 1; ++i, v = v >> 1)"); 9749 verifyFormat("Foo.call<Bar<Function>>()"); 9750 verifyFormat("if (Foo.call<Bar<Function>>() == 0)"); 9751 verifyFormat("for (std::vector<std::pair<int>>::iterator i = 0; i < x >> 1; " 9752 "++i, v = v >> 1)"); 9753 verifyFormat("if (w<u<v<x>>, 1>::t)"); 9754 } 9755 9756 TEST_F(FormatTest, BitshiftOperatorWidth) { 9757 EXPECT_EQ("int a = 1 << 2; /* foo\n" 9758 " bar */", 9759 format("int a=1<<2; /* foo\n" 9760 " bar */")); 9761 9762 EXPECT_EQ("int b = 256 >> 1; /* foo\n" 9763 " bar */", 9764 format("int b =256>>1 ; /* foo\n" 9765 " bar */")); 9766 } 9767 9768 TEST_F(FormatTest, UnderstandsBinaryOperators) { 9769 verifyFormat("COMPARE(a, ==, b);"); 9770 verifyFormat("auto s = sizeof...(Ts) - 1;"); 9771 } 9772 9773 TEST_F(FormatTest, UnderstandsPointersToMembers) { 9774 verifyFormat("int A::*x;"); 9775 verifyFormat("int (S::*func)(void *);"); 9776 verifyFormat("void f() { int (S::*func)(void *); }"); 9777 verifyFormat("typedef bool *(Class::*Member)() const;"); 9778 verifyFormat("void f() {\n" 9779 " (a->*f)();\n" 9780 " a->*x;\n" 9781 " (a.*f)();\n" 9782 " ((*a).*f)();\n" 9783 " a.*x;\n" 9784 "}"); 9785 verifyFormat("void f() {\n" 9786 " (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n" 9787 " aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n" 9788 "}"); 9789 verifyFormat( 9790 "(aaaaaaaaaa->*bbbbbbb)(\n" 9791 " aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 9792 FormatStyle Style = getLLVMStyle(); 9793 Style.PointerAlignment = FormatStyle::PAS_Left; 9794 verifyFormat("typedef bool* (Class::*Member)() const;", Style); 9795 } 9796 9797 TEST_F(FormatTest, UnderstandsUnaryOperators) { 9798 verifyFormat("int a = -2;"); 9799 verifyFormat("f(-1, -2, -3);"); 9800 verifyFormat("a[-1] = 5;"); 9801 verifyFormat("int a = 5 + -2;"); 9802 verifyFormat("if (i == -1) {\n}"); 9803 verifyFormat("if (i != -1) {\n}"); 9804 verifyFormat("if (i > -1) {\n}"); 9805 verifyFormat("if (i < -1) {\n}"); 9806 verifyFormat("++(a->f());"); 9807 verifyFormat("--(a->f());"); 9808 verifyFormat("(a->f())++;"); 9809 verifyFormat("a[42]++;"); 9810 verifyFormat("if (!(a->f())) {\n}"); 9811 verifyFormat("if (!+i) {\n}"); 9812 verifyFormat("~&a;"); 9813 verifyFormat("for (x = 0; -10 < x; --x) {\n}"); 9814 verifyFormat("sizeof -x"); 9815 verifyFormat("sizeof +x"); 9816 verifyFormat("sizeof *x"); 9817 verifyFormat("sizeof &x"); 9818 verifyFormat("delete +x;"); 9819 verifyFormat("co_await +x;"); 9820 verifyFormat("case *x:"); 9821 verifyFormat("case &x:"); 9822 9823 verifyFormat("a-- > b;"); 9824 verifyFormat("b ? -a : c;"); 9825 verifyFormat("n * sizeof char16;"); 9826 verifyFormat("n * alignof char16;", getGoogleStyle()); 9827 verifyFormat("sizeof(char);"); 9828 verifyFormat("alignof(char);", getGoogleStyle()); 9829 9830 verifyFormat("return -1;"); 9831 verifyFormat("throw -1;"); 9832 verifyFormat("switch (a) {\n" 9833 "case -1:\n" 9834 " break;\n" 9835 "}"); 9836 verifyFormat("#define X -1"); 9837 verifyFormat("#define X -kConstant"); 9838 9839 verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};"); 9840 verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};"); 9841 9842 verifyFormat("int a = /* confusing comment */ -1;"); 9843 // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case. 9844 verifyFormat("int a = i /* confusing comment */++;"); 9845 9846 verifyFormat("co_yield -1;"); 9847 verifyFormat("co_return -1;"); 9848 9849 // Check that * is not treated as a binary operator when we set 9850 // PointerAlignment as PAS_Left after a keyword and not a declaration. 9851 FormatStyle PASLeftStyle = getLLVMStyle(); 9852 PASLeftStyle.PointerAlignment = FormatStyle::PAS_Left; 9853 verifyFormat("co_return *a;", PASLeftStyle); 9854 verifyFormat("co_await *a;", PASLeftStyle); 9855 verifyFormat("co_yield *a", PASLeftStyle); 9856 verifyFormat("return *a;", PASLeftStyle); 9857 } 9858 9859 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) { 9860 verifyFormat("if (!aaaaaaaaaa( // break\n" 9861 " aaaaa)) {\n" 9862 "}"); 9863 verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n" 9864 " aaaaa));"); 9865 verifyFormat("*aaa = aaaaaaa( // break\n" 9866 " bbbbbb);"); 9867 } 9868 9869 TEST_F(FormatTest, UnderstandsOverloadedOperators) { 9870 verifyFormat("bool operator<();"); 9871 verifyFormat("bool operator>();"); 9872 verifyFormat("bool operator=();"); 9873 verifyFormat("bool operator==();"); 9874 verifyFormat("bool operator!=();"); 9875 verifyFormat("int operator+();"); 9876 verifyFormat("int operator++();"); 9877 verifyFormat("int operator++(int) volatile noexcept;"); 9878 verifyFormat("bool operator,();"); 9879 verifyFormat("bool operator();"); 9880 verifyFormat("bool operator()();"); 9881 verifyFormat("bool operator[]();"); 9882 verifyFormat("operator bool();"); 9883 verifyFormat("operator int();"); 9884 verifyFormat("operator void *();"); 9885 verifyFormat("operator SomeType<int>();"); 9886 verifyFormat("operator SomeType<int, int>();"); 9887 verifyFormat("operator SomeType<SomeType<int>>();"); 9888 verifyFormat("operator< <>();"); 9889 verifyFormat("operator<< <>();"); 9890 verifyFormat("< <>"); 9891 9892 verifyFormat("void *operator new(std::size_t size);"); 9893 verifyFormat("void *operator new[](std::size_t size);"); 9894 verifyFormat("void operator delete(void *ptr);"); 9895 verifyFormat("void operator delete[](void *ptr);"); 9896 verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n" 9897 "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);"); 9898 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n" 9899 " aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;"); 9900 9901 verifyFormat( 9902 "ostream &operator<<(ostream &OutputStream,\n" 9903 " SomeReallyLongType WithSomeReallyLongValue);"); 9904 verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n" 9905 " const aaaaaaaaaaaaaaaaaaaaa &right) {\n" 9906 " return left.group < right.group;\n" 9907 "}"); 9908 verifyFormat("SomeType &operator=(const SomeType &S);"); 9909 verifyFormat("f.template operator()<int>();"); 9910 9911 verifyGoogleFormat("operator void*();"); 9912 verifyGoogleFormat("operator SomeType<SomeType<int>>();"); 9913 verifyGoogleFormat("operator ::A();"); 9914 9915 verifyFormat("using A::operator+;"); 9916 verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n" 9917 "int i;"); 9918 9919 // Calling an operator as a member function. 9920 verifyFormat("void f() { a.operator*(); }"); 9921 verifyFormat("void f() { a.operator*(b & b); }"); 9922 verifyFormat("void f() { a->operator&(a * b); }"); 9923 verifyFormat("void f() { NS::a.operator+(*b * *b); }"); 9924 // TODO: Calling an operator as a non-member function is hard to distinguish. 9925 // https://llvm.org/PR50629 9926 // verifyFormat("void f() { operator*(a & a); }"); 9927 // verifyFormat("void f() { operator&(a, b * b); }"); 9928 9929 verifyFormat("::operator delete(foo);"); 9930 verifyFormat("::operator new(n * sizeof(foo));"); 9931 verifyFormat("foo() { ::operator delete(foo); }"); 9932 verifyFormat("foo() { ::operator new(n * sizeof(foo)); }"); 9933 } 9934 9935 TEST_F(FormatTest, UnderstandsFunctionRefQualification) { 9936 verifyFormat("void A::b() && {}"); 9937 verifyFormat("void A::b() &&noexcept {}"); 9938 verifyFormat("Deleted &operator=(const Deleted &) & = default;"); 9939 verifyFormat("Deleted &operator=(const Deleted &) && = delete;"); 9940 verifyFormat("Deleted &operator=(const Deleted &) &noexcept = default;"); 9941 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;"); 9942 verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;"); 9943 verifyFormat("Deleted &operator=(const Deleted &) &;"); 9944 verifyFormat("Deleted &operator=(const Deleted &) &&;"); 9945 verifyFormat("SomeType MemberFunction(const Deleted &) &;"); 9946 verifyFormat("SomeType MemberFunction(const Deleted &) &&;"); 9947 verifyFormat("SomeType MemberFunction(const Deleted &) && {}"); 9948 verifyFormat("SomeType MemberFunction(const Deleted &) && final {}"); 9949 verifyFormat("SomeType MemberFunction(const Deleted &) && override {}"); 9950 verifyFormat("SomeType MemberFunction(const Deleted &) &&noexcept {}"); 9951 verifyFormat("void Fn(T const &) const &;"); 9952 verifyFormat("void Fn(T const volatile &&) const volatile &&;"); 9953 verifyFormat("void Fn(T const volatile &&) const volatile &&noexcept;"); 9954 verifyFormat("template <typename T>\n" 9955 "void F(T) && = delete;", 9956 getGoogleStyle()); 9957 verifyFormat("template <typename T> void operator=(T) &;"); 9958 verifyFormat("template <typename T> void operator=(T) const &;"); 9959 verifyFormat("template <typename T> void operator=(T) &noexcept;"); 9960 verifyFormat("template <typename T> void operator=(T) & = default;"); 9961 verifyFormat("template <typename T> void operator=(T) &&;"); 9962 verifyFormat("template <typename T> void operator=(T) && = delete;"); 9963 verifyFormat("template <typename T> void operator=(T) & {}"); 9964 verifyFormat("template <typename T> void operator=(T) && {}"); 9965 9966 FormatStyle AlignLeft = getLLVMStyle(); 9967 AlignLeft.PointerAlignment = FormatStyle::PAS_Left; 9968 verifyFormat("void A::b() && {}", AlignLeft); 9969 verifyFormat("void A::b() && noexcept {}", AlignLeft); 9970 verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft); 9971 verifyFormat("Deleted& operator=(const Deleted&) & noexcept = default;", 9972 AlignLeft); 9973 verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;", 9974 AlignLeft); 9975 verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft); 9976 verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft); 9977 verifyFormat("auto Function(T t) & -> void {}", AlignLeft); 9978 verifyFormat("auto Function(T... t) & -> void {}", AlignLeft); 9979 verifyFormat("auto Function(T) & -> void {}", AlignLeft); 9980 verifyFormat("auto Function(T) & -> void;", AlignLeft); 9981 verifyFormat("void Fn(T const&) const&;", AlignLeft); 9982 verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft); 9983 verifyFormat("void Fn(T const volatile&&) const volatile&& noexcept;", 9984 AlignLeft); 9985 verifyFormat("template <typename T> void operator=(T) &;", AlignLeft); 9986 verifyFormat("template <typename T> void operator=(T) const&;", AlignLeft); 9987 verifyFormat("template <typename T> void operator=(T) & noexcept;", 9988 AlignLeft); 9989 verifyFormat("template <typename T> void operator=(T) & = default;", 9990 AlignLeft); 9991 verifyFormat("template <typename T> void operator=(T) &&;", AlignLeft); 9992 verifyFormat("template <typename T> void operator=(T) && = delete;", 9993 AlignLeft); 9994 verifyFormat("template <typename T> void operator=(T) & {}", AlignLeft); 9995 verifyFormat("template <typename T> void operator=(T) && {}", AlignLeft); 9996 9997 FormatStyle AlignMiddle = getLLVMStyle(); 9998 AlignMiddle.PointerAlignment = FormatStyle::PAS_Middle; 9999 verifyFormat("void A::b() && {}", AlignMiddle); 10000 verifyFormat("void A::b() && noexcept {}", AlignMiddle); 10001 verifyFormat("Deleted & operator=(const Deleted &) & = default;", 10002 AlignMiddle); 10003 verifyFormat("Deleted & operator=(const Deleted &) & noexcept = default;", 10004 AlignMiddle); 10005 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", 10006 AlignMiddle); 10007 verifyFormat("Deleted & operator=(const Deleted &) &;", AlignMiddle); 10008 verifyFormat("SomeType MemberFunction(const Deleted &) &;", AlignMiddle); 10009 verifyFormat("auto Function(T t) & -> void {}", AlignMiddle); 10010 verifyFormat("auto Function(T... t) & -> void {}", AlignMiddle); 10011 verifyFormat("auto Function(T) & -> void {}", AlignMiddle); 10012 verifyFormat("auto Function(T) & -> void;", AlignMiddle); 10013 verifyFormat("void Fn(T const &) const &;", AlignMiddle); 10014 verifyFormat("void Fn(T const volatile &&) const volatile &&;", AlignMiddle); 10015 verifyFormat("void Fn(T const volatile &&) const volatile && noexcept;", 10016 AlignMiddle); 10017 verifyFormat("template <typename T> void operator=(T) &;", AlignMiddle); 10018 verifyFormat("template <typename T> void operator=(T) const &;", AlignMiddle); 10019 verifyFormat("template <typename T> void operator=(T) & noexcept;", 10020 AlignMiddle); 10021 verifyFormat("template <typename T> void operator=(T) & = default;", 10022 AlignMiddle); 10023 verifyFormat("template <typename T> void operator=(T) &&;", AlignMiddle); 10024 verifyFormat("template <typename T> void operator=(T) && = delete;", 10025 AlignMiddle); 10026 verifyFormat("template <typename T> void operator=(T) & {}", AlignMiddle); 10027 verifyFormat("template <typename T> void operator=(T) && {}", AlignMiddle); 10028 10029 FormatStyle Spaces = getLLVMStyle(); 10030 Spaces.SpacesInCStyleCastParentheses = true; 10031 verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces); 10032 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces); 10033 verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces); 10034 verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces); 10035 10036 Spaces.SpacesInCStyleCastParentheses = false; 10037 Spaces.SpacesInParentheses = true; 10038 verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces); 10039 verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;", 10040 Spaces); 10041 verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces); 10042 verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces); 10043 10044 FormatStyle BreakTemplate = getLLVMStyle(); 10045 BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 10046 10047 verifyFormat("struct f {\n" 10048 " template <class T>\n" 10049 " int &foo(const std::string &str) &noexcept {}\n" 10050 "};", 10051 BreakTemplate); 10052 10053 verifyFormat("struct f {\n" 10054 " template <class T>\n" 10055 " int &foo(const std::string &str) &&noexcept {}\n" 10056 "};", 10057 BreakTemplate); 10058 10059 verifyFormat("struct f {\n" 10060 " template <class T>\n" 10061 " int &foo(const std::string &str) const &noexcept {}\n" 10062 "};", 10063 BreakTemplate); 10064 10065 verifyFormat("struct f {\n" 10066 " template <class T>\n" 10067 " int &foo(const std::string &str) const &noexcept {}\n" 10068 "};", 10069 BreakTemplate); 10070 10071 verifyFormat("struct f {\n" 10072 " template <class T>\n" 10073 " auto foo(const std::string &str) &&noexcept -> int & {}\n" 10074 "};", 10075 BreakTemplate); 10076 10077 FormatStyle AlignLeftBreakTemplate = getLLVMStyle(); 10078 AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations = 10079 FormatStyle::BTDS_Yes; 10080 AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left; 10081 10082 verifyFormat("struct f {\n" 10083 " template <class T>\n" 10084 " int& foo(const std::string& str) & noexcept {}\n" 10085 "};", 10086 AlignLeftBreakTemplate); 10087 10088 verifyFormat("struct f {\n" 10089 " template <class T>\n" 10090 " int& foo(const std::string& str) && noexcept {}\n" 10091 "};", 10092 AlignLeftBreakTemplate); 10093 10094 verifyFormat("struct f {\n" 10095 " template <class T>\n" 10096 " int& foo(const std::string& str) const& noexcept {}\n" 10097 "};", 10098 AlignLeftBreakTemplate); 10099 10100 verifyFormat("struct f {\n" 10101 " template <class T>\n" 10102 " int& foo(const std::string& str) const&& noexcept {}\n" 10103 "};", 10104 AlignLeftBreakTemplate); 10105 10106 verifyFormat("struct f {\n" 10107 " template <class T>\n" 10108 " auto foo(const std::string& str) && noexcept -> int& {}\n" 10109 "};", 10110 AlignLeftBreakTemplate); 10111 10112 // The `&` in `Type&` should not be confused with a trailing `&` of 10113 // DEPRECATED(reason) member function. 10114 verifyFormat("struct f {\n" 10115 " template <class T>\n" 10116 " DEPRECATED(reason)\n" 10117 " Type &foo(arguments) {}\n" 10118 "};", 10119 BreakTemplate); 10120 10121 verifyFormat("struct f {\n" 10122 " template <class T>\n" 10123 " DEPRECATED(reason)\n" 10124 " Type& foo(arguments) {}\n" 10125 "};", 10126 AlignLeftBreakTemplate); 10127 10128 verifyFormat("void (*foopt)(int) = &func;"); 10129 10130 FormatStyle DerivePointerAlignment = getLLVMStyle(); 10131 DerivePointerAlignment.DerivePointerAlignment = true; 10132 // There's always a space between the function and its trailing qualifiers. 10133 // This isn't evidence for PAS_Right (or for PAS_Left). 10134 std::string Prefix = "void a() &;\n" 10135 "void b() &;\n"; 10136 verifyFormat(Prefix + "int* x;", DerivePointerAlignment); 10137 verifyFormat(Prefix + "int *x;", DerivePointerAlignment); 10138 // Same if the function is an overloaded operator, and with &&. 10139 Prefix = "void operator()() &&;\n" 10140 "void operator()() &&;\n"; 10141 verifyFormat(Prefix + "int* x;", DerivePointerAlignment); 10142 verifyFormat(Prefix + "int *x;", DerivePointerAlignment); 10143 // However a space between cv-qualifiers and ref-qualifiers *is* evidence. 10144 Prefix = "void a() const &;\n" 10145 "void b() const &;\n"; 10146 EXPECT_EQ(Prefix + "int *x;", 10147 format(Prefix + "int* x;", DerivePointerAlignment)); 10148 } 10149 10150 TEST_F(FormatTest, UnderstandsNewAndDelete) { 10151 verifyFormat("void f() {\n" 10152 " A *a = new A;\n" 10153 " A *a = new (placement) A;\n" 10154 " delete a;\n" 10155 " delete (A *)a;\n" 10156 "}"); 10157 verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n" 10158 " typename aaaaaaaaaaaaaaaaaaaaaaaa();"); 10159 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 10160 " new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n" 10161 " typename aaaaaaaaaaaaaaaaaaaaaaaa();"); 10162 verifyFormat("delete[] h->p;"); 10163 verifyFormat("delete[] (void *)p;"); 10164 10165 verifyFormat("void operator delete(void *foo) ATTRIB;"); 10166 verifyFormat("void operator new(void *foo) ATTRIB;"); 10167 verifyFormat("void operator delete[](void *foo) ATTRIB;"); 10168 verifyFormat("void operator delete(void *ptr) noexcept;"); 10169 10170 EXPECT_EQ("void new(link p);\n" 10171 "void delete(link p);\n", 10172 format("void new (link p);\n" 10173 "void delete (link p);\n")); 10174 } 10175 10176 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) { 10177 verifyFormat("int *f(int *a) {}"); 10178 verifyFormat("int main(int argc, char **argv) {}"); 10179 verifyFormat("Test::Test(int b) : a(b * b) {}"); 10180 verifyIndependentOfContext("f(a, *a);"); 10181 verifyFormat("void g() { f(*a); }"); 10182 verifyIndependentOfContext("int a = b * 10;"); 10183 verifyIndependentOfContext("int a = 10 * b;"); 10184 verifyIndependentOfContext("int a = b * c;"); 10185 verifyIndependentOfContext("int a += b * c;"); 10186 verifyIndependentOfContext("int a -= b * c;"); 10187 verifyIndependentOfContext("int a *= b * c;"); 10188 verifyIndependentOfContext("int a /= b * c;"); 10189 verifyIndependentOfContext("int a = *b;"); 10190 verifyIndependentOfContext("int a = *b * c;"); 10191 verifyIndependentOfContext("int a = b * *c;"); 10192 verifyIndependentOfContext("int a = b * (10);"); 10193 verifyIndependentOfContext("S << b * (10);"); 10194 verifyIndependentOfContext("return 10 * b;"); 10195 verifyIndependentOfContext("return *b * *c;"); 10196 verifyIndependentOfContext("return a & ~b;"); 10197 verifyIndependentOfContext("f(b ? *c : *d);"); 10198 verifyIndependentOfContext("int a = b ? *c : *d;"); 10199 verifyIndependentOfContext("*b = a;"); 10200 verifyIndependentOfContext("a * ~b;"); 10201 verifyIndependentOfContext("a * !b;"); 10202 verifyIndependentOfContext("a * +b;"); 10203 verifyIndependentOfContext("a * -b;"); 10204 verifyIndependentOfContext("a * ++b;"); 10205 verifyIndependentOfContext("a * --b;"); 10206 verifyIndependentOfContext("a[4] * b;"); 10207 verifyIndependentOfContext("a[a * a] = 1;"); 10208 verifyIndependentOfContext("f() * b;"); 10209 verifyIndependentOfContext("a * [self dostuff];"); 10210 verifyIndependentOfContext("int x = a * (a + b);"); 10211 verifyIndependentOfContext("(a *)(a + b);"); 10212 verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;"); 10213 verifyIndependentOfContext("int *pa = (int *)&a;"); 10214 verifyIndependentOfContext("return sizeof(int **);"); 10215 verifyIndependentOfContext("return sizeof(int ******);"); 10216 verifyIndependentOfContext("return (int **&)a;"); 10217 verifyIndependentOfContext("f((*PointerToArray)[10]);"); 10218 verifyFormat("void f(Type (*parameter)[10]) {}"); 10219 verifyFormat("void f(Type (¶meter)[10]) {}"); 10220 verifyGoogleFormat("return sizeof(int**);"); 10221 verifyIndependentOfContext("Type **A = static_cast<Type **>(P);"); 10222 verifyGoogleFormat("Type** A = static_cast<Type**>(P);"); 10223 verifyFormat("auto a = [](int **&, int ***) {};"); 10224 verifyFormat("auto PointerBinding = [](const char *S) {};"); 10225 verifyFormat("typedef typeof(int(int, int)) *MyFunc;"); 10226 verifyFormat("[](const decltype(*a) &value) {}"); 10227 verifyFormat("[](const typeof(*a) &value) {}"); 10228 verifyFormat("[](const _Atomic(a *) &value) {}"); 10229 verifyFormat("[](const __underlying_type(a) &value) {}"); 10230 verifyFormat("decltype(a * b) F();"); 10231 verifyFormat("typeof(a * b) F();"); 10232 verifyFormat("#define MACRO() [](A *a) { return 1; }"); 10233 verifyFormat("Constructor() : member([](A *a, B *b) {}) {}"); 10234 verifyIndependentOfContext("typedef void (*f)(int *a);"); 10235 verifyIndependentOfContext("int i{a * b};"); 10236 verifyIndependentOfContext("aaa && aaa->f();"); 10237 verifyIndependentOfContext("int x = ~*p;"); 10238 verifyFormat("Constructor() : a(a), area(width * height) {}"); 10239 verifyFormat("Constructor() : a(a), area(a, width * height) {}"); 10240 verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}"); 10241 verifyFormat("void f() { f(a, c * d); }"); 10242 verifyFormat("void f() { f(new a(), c * d); }"); 10243 verifyFormat("void f(const MyOverride &override);"); 10244 verifyFormat("void f(const MyFinal &final);"); 10245 verifyIndependentOfContext("bool a = f() && override.f();"); 10246 verifyIndependentOfContext("bool a = f() && final.f();"); 10247 10248 verifyIndependentOfContext("InvalidRegions[*R] = 0;"); 10249 10250 verifyIndependentOfContext("A<int *> a;"); 10251 verifyIndependentOfContext("A<int **> a;"); 10252 verifyIndependentOfContext("A<int *, int *> a;"); 10253 verifyIndependentOfContext("A<int *[]> a;"); 10254 verifyIndependentOfContext( 10255 "const char *const p = reinterpret_cast<const char *const>(q);"); 10256 verifyIndependentOfContext("A<int **, int **> a;"); 10257 verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);"); 10258 verifyFormat("for (char **a = b; *a; ++a) {\n}"); 10259 verifyFormat("for (; a && b;) {\n}"); 10260 verifyFormat("bool foo = true && [] { return false; }();"); 10261 10262 verifyFormat( 10263 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 10264 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 10265 10266 verifyGoogleFormat("int const* a = &b;"); 10267 verifyGoogleFormat("**outparam = 1;"); 10268 verifyGoogleFormat("*outparam = a * b;"); 10269 verifyGoogleFormat("int main(int argc, char** argv) {}"); 10270 verifyGoogleFormat("A<int*> a;"); 10271 verifyGoogleFormat("A<int**> a;"); 10272 verifyGoogleFormat("A<int*, int*> a;"); 10273 verifyGoogleFormat("A<int**, int**> a;"); 10274 verifyGoogleFormat("f(b ? *c : *d);"); 10275 verifyGoogleFormat("int a = b ? *c : *d;"); 10276 verifyGoogleFormat("Type* t = **x;"); 10277 verifyGoogleFormat("Type* t = *++*x;"); 10278 verifyGoogleFormat("*++*x;"); 10279 verifyGoogleFormat("Type* t = const_cast<T*>(&*x);"); 10280 verifyGoogleFormat("Type* t = x++ * y;"); 10281 verifyGoogleFormat( 10282 "const char* const p = reinterpret_cast<const char* const>(q);"); 10283 verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);"); 10284 verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);"); 10285 verifyGoogleFormat("template <typename T>\n" 10286 "void f(int i = 0, SomeType** temps = NULL);"); 10287 10288 FormatStyle Left = getLLVMStyle(); 10289 Left.PointerAlignment = FormatStyle::PAS_Left; 10290 verifyFormat("x = *a(x) = *a(y);", Left); 10291 verifyFormat("for (;; *a = b) {\n}", Left); 10292 verifyFormat("return *this += 1;", Left); 10293 verifyFormat("throw *x;", Left); 10294 verifyFormat("delete *x;", Left); 10295 verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left); 10296 verifyFormat("[](const decltype(*a)* ptr) {}", Left); 10297 verifyFormat("[](const typeof(*a)* ptr) {}", Left); 10298 verifyFormat("[](const _Atomic(a*)* ptr) {}", Left); 10299 verifyFormat("[](const __underlying_type(a)* ptr) {}", Left); 10300 verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left); 10301 verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left); 10302 verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left); 10303 verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left); 10304 10305 verifyIndependentOfContext("a = *(x + y);"); 10306 verifyIndependentOfContext("a = &(x + y);"); 10307 verifyIndependentOfContext("*(x + y).call();"); 10308 verifyIndependentOfContext("&(x + y)->call();"); 10309 verifyFormat("void f() { &(*I).first; }"); 10310 10311 verifyIndependentOfContext("f(b * /* confusing comment */ ++c);"); 10312 verifyFormat("f(* /* confusing comment */ foo);"); 10313 verifyFormat("void (* /*deleter*/)(const Slice &key, void *value)"); 10314 verifyFormat("void foo(int * // this is the first paramters\n" 10315 " ,\n" 10316 " int second);"); 10317 verifyFormat("double term = a * // first\n" 10318 " b;"); 10319 verifyFormat( 10320 "int *MyValues = {\n" 10321 " *A, // Operator detection might be confused by the '{'\n" 10322 " *BB // Operator detection might be confused by previous comment\n" 10323 "};"); 10324 10325 verifyIndependentOfContext("if (int *a = &b)"); 10326 verifyIndependentOfContext("if (int &a = *b)"); 10327 verifyIndependentOfContext("if (a & b[i])"); 10328 verifyIndependentOfContext("if constexpr (a & b[i])"); 10329 verifyIndependentOfContext("if CONSTEXPR (a & b[i])"); 10330 verifyIndependentOfContext("if (a * (b * c))"); 10331 verifyIndependentOfContext("if constexpr (a * (b * c))"); 10332 verifyIndependentOfContext("if CONSTEXPR (a * (b * c))"); 10333 verifyIndependentOfContext("if (a::b::c::d & b[i])"); 10334 verifyIndependentOfContext("if (*b[i])"); 10335 verifyIndependentOfContext("if (int *a = (&b))"); 10336 verifyIndependentOfContext("while (int *a = &b)"); 10337 verifyIndependentOfContext("while (a * (b * c))"); 10338 verifyIndependentOfContext("size = sizeof *a;"); 10339 verifyIndependentOfContext("if (a && (b = c))"); 10340 verifyFormat("void f() {\n" 10341 " for (const int &v : Values) {\n" 10342 " }\n" 10343 "}"); 10344 verifyFormat("for (int i = a * a; i < 10; ++i) {\n}"); 10345 verifyFormat("for (int i = 0; i < a * a; ++i) {\n}"); 10346 verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}"); 10347 10348 verifyFormat("#define A (!a * b)"); 10349 verifyFormat("#define MACRO \\\n" 10350 " int *i = a * b; \\\n" 10351 " void f(a *b);", 10352 getLLVMStyleWithColumns(19)); 10353 10354 verifyIndependentOfContext("A = new SomeType *[Length];"); 10355 verifyIndependentOfContext("A = new SomeType *[Length]();"); 10356 verifyIndependentOfContext("T **t = new T *;"); 10357 verifyIndependentOfContext("T **t = new T *();"); 10358 verifyGoogleFormat("A = new SomeType*[Length]();"); 10359 verifyGoogleFormat("A = new SomeType*[Length];"); 10360 verifyGoogleFormat("T** t = new T*;"); 10361 verifyGoogleFormat("T** t = new T*();"); 10362 10363 verifyFormat("STATIC_ASSERT((a & b) == 0);"); 10364 verifyFormat("STATIC_ASSERT(0 == (a & b));"); 10365 verifyFormat("template <bool a, bool b> " 10366 "typename t::if<x && y>::type f() {}"); 10367 verifyFormat("template <int *y> f() {}"); 10368 verifyFormat("vector<int *> v;"); 10369 verifyFormat("vector<int *const> v;"); 10370 verifyFormat("vector<int *const **const *> v;"); 10371 verifyFormat("vector<int *volatile> v;"); 10372 verifyFormat("vector<a *_Nonnull> v;"); 10373 verifyFormat("vector<a *_Nullable> v;"); 10374 verifyFormat("vector<a *_Null_unspecified> v;"); 10375 verifyFormat("vector<a *__ptr32> v;"); 10376 verifyFormat("vector<a *__ptr64> v;"); 10377 verifyFormat("vector<a *__capability> v;"); 10378 FormatStyle TypeMacros = getLLVMStyle(); 10379 TypeMacros.TypenameMacros = {"LIST"}; 10380 verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros); 10381 verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros); 10382 verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros); 10383 verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros); 10384 verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication 10385 10386 FormatStyle CustomQualifier = getLLVMStyle(); 10387 // Add identifiers that should not be parsed as a qualifier by default. 10388 CustomQualifier.AttributeMacros.push_back("__my_qualifier"); 10389 CustomQualifier.AttributeMacros.push_back("_My_qualifier"); 10390 CustomQualifier.AttributeMacros.push_back("my_other_qualifier"); 10391 verifyFormat("vector<a * __my_qualifier> parse_as_multiply;"); 10392 verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier); 10393 verifyFormat("vector<a * _My_qualifier> parse_as_multiply;"); 10394 verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier); 10395 verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;"); 10396 verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier); 10397 verifyFormat("vector<a * _NotAQualifier> v;"); 10398 verifyFormat("vector<a * __not_a_qualifier> v;"); 10399 verifyFormat("vector<a * b> v;"); 10400 verifyFormat("foo<b && false>();"); 10401 verifyFormat("foo<b & 1>();"); 10402 verifyFormat("foo<b & (1)>();"); 10403 verifyFormat("foo<b & (~0)>();"); 10404 verifyFormat("foo<b & (true)>();"); 10405 verifyFormat("foo<b & ((1))>();"); 10406 verifyFormat("foo<b & (/*comment*/ 1)>();"); 10407 verifyFormat("decltype(*::std::declval<const T &>()) void F();"); 10408 verifyFormat("typeof(*::std::declval<const T &>()) void F();"); 10409 verifyFormat("_Atomic(*::std::declval<const T &>()) void F();"); 10410 verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();"); 10411 verifyFormat( 10412 "template <class T, class = typename std::enable_if<\n" 10413 " std::is_integral<T>::value &&\n" 10414 " (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n" 10415 "void F();", 10416 getLLVMStyleWithColumns(70)); 10417 verifyFormat("template <class T,\n" 10418 " class = typename std::enable_if<\n" 10419 " std::is_integral<T>::value &&\n" 10420 " (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n" 10421 " class U>\n" 10422 "void F();", 10423 getLLVMStyleWithColumns(70)); 10424 verifyFormat( 10425 "template <class T,\n" 10426 " class = typename ::std::enable_if<\n" 10427 " ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n" 10428 "void F();", 10429 getGoogleStyleWithColumns(68)); 10430 10431 FormatStyle Style = getLLVMStyle(); 10432 Style.PointerAlignment = FormatStyle::PAS_Left; 10433 verifyFormat("struct {\n" 10434 "}* ptr;", 10435 Style); 10436 verifyFormat("union {\n" 10437 "}* ptr;", 10438 Style); 10439 verifyFormat("class {\n" 10440 "}* ptr;", 10441 Style); 10442 verifyFormat("struct {\n" 10443 "}&& ptr = {};", 10444 Style); 10445 verifyFormat("union {\n" 10446 "}&& ptr = {};", 10447 Style); 10448 verifyFormat("class {\n" 10449 "}&& ptr = {};", 10450 Style); 10451 10452 Style.PointerAlignment = FormatStyle::PAS_Middle; 10453 verifyFormat("struct {\n" 10454 "} * ptr;", 10455 Style); 10456 verifyFormat("union {\n" 10457 "} * ptr;", 10458 Style); 10459 verifyFormat("class {\n" 10460 "} * ptr;", 10461 Style); 10462 verifyFormat("struct {\n" 10463 "} && ptr = {};", 10464 Style); 10465 verifyFormat("union {\n" 10466 "} && ptr = {};", 10467 Style); 10468 verifyFormat("class {\n" 10469 "} && ptr = {};", 10470 Style); 10471 10472 Style.PointerAlignment = FormatStyle::PAS_Right; 10473 verifyFormat("struct {\n" 10474 "} *ptr;", 10475 Style); 10476 verifyFormat("union {\n" 10477 "} *ptr;", 10478 Style); 10479 verifyFormat("class {\n" 10480 "} *ptr;", 10481 Style); 10482 verifyFormat("struct {\n" 10483 "} &&ptr = {};", 10484 Style); 10485 verifyFormat("union {\n" 10486 "} &&ptr = {};", 10487 Style); 10488 verifyFormat("class {\n" 10489 "} &&ptr = {};", 10490 Style); 10491 10492 verifyIndependentOfContext("MACRO(int *i);"); 10493 verifyIndependentOfContext("MACRO(auto *a);"); 10494 verifyIndependentOfContext("MACRO(const A *a);"); 10495 verifyIndependentOfContext("MACRO(_Atomic(A) *a);"); 10496 verifyIndependentOfContext("MACRO(decltype(A) *a);"); 10497 verifyIndependentOfContext("MACRO(typeof(A) *a);"); 10498 verifyIndependentOfContext("MACRO(__underlying_type(A) *a);"); 10499 verifyIndependentOfContext("MACRO(A *const a);"); 10500 verifyIndependentOfContext("MACRO(A *restrict a);"); 10501 verifyIndependentOfContext("MACRO(A *__restrict__ a);"); 10502 verifyIndependentOfContext("MACRO(A *__restrict a);"); 10503 verifyIndependentOfContext("MACRO(A *volatile a);"); 10504 verifyIndependentOfContext("MACRO(A *__volatile a);"); 10505 verifyIndependentOfContext("MACRO(A *__volatile__ a);"); 10506 verifyIndependentOfContext("MACRO(A *_Nonnull a);"); 10507 verifyIndependentOfContext("MACRO(A *_Nullable a);"); 10508 verifyIndependentOfContext("MACRO(A *_Null_unspecified a);"); 10509 verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);"); 10510 verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);"); 10511 verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);"); 10512 verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);"); 10513 verifyIndependentOfContext("MACRO(A *__ptr32 a);"); 10514 verifyIndependentOfContext("MACRO(A *__ptr64 a);"); 10515 verifyIndependentOfContext("MACRO(A *__capability);"); 10516 verifyIndependentOfContext("MACRO(A &__capability);"); 10517 verifyFormat("MACRO(A *__my_qualifier);"); // type declaration 10518 verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication 10519 // If we add __my_qualifier to AttributeMacros it should always be parsed as 10520 // a type declaration: 10521 verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier); 10522 verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier); 10523 // Also check that TypenameMacros prevents parsing it as multiplication: 10524 verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication 10525 verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type 10526 10527 verifyIndependentOfContext("MACRO('0' <= c && c <= '9');"); 10528 verifyFormat("void f() { f(float{1}, a * a); }"); 10529 verifyFormat("void f() { f(float(1), a * a); }"); 10530 10531 verifyFormat("f((void (*)(int))g);"); 10532 verifyFormat("f((void (&)(int))g);"); 10533 verifyFormat("f((void (^)(int))g);"); 10534 10535 // FIXME: Is there a way to make this work? 10536 // verifyIndependentOfContext("MACRO(A *a);"); 10537 verifyFormat("MACRO(A &B);"); 10538 verifyFormat("MACRO(A *B);"); 10539 verifyFormat("void f() { MACRO(A * B); }"); 10540 verifyFormat("void f() { MACRO(A & B); }"); 10541 10542 // This lambda was mis-formatted after D88956 (treating it as a binop): 10543 verifyFormat("auto x = [](const decltype(x) &ptr) {};"); 10544 verifyFormat("auto x = [](const decltype(x) *ptr) {};"); 10545 verifyFormat("#define lambda [](const decltype(x) &ptr) {}"); 10546 verifyFormat("#define lambda [](const decltype(x) *ptr) {}"); 10547 10548 verifyFormat("DatumHandle const *operator->() const { return input_; }"); 10549 verifyFormat("return options != nullptr && operator==(*options);"); 10550 10551 EXPECT_EQ("#define OP(x) \\\n" 10552 " ostream &operator<<(ostream &s, const A &a) { \\\n" 10553 " return s << a.DebugString(); \\\n" 10554 " }", 10555 format("#define OP(x) \\\n" 10556 " ostream &operator<<(ostream &s, const A &a) { \\\n" 10557 " return s << a.DebugString(); \\\n" 10558 " }", 10559 getLLVMStyleWithColumns(50))); 10560 10561 // FIXME: We cannot handle this case yet; we might be able to figure out that 10562 // foo<x> d > v; doesn't make sense. 10563 verifyFormat("foo<a<b && c> d> v;"); 10564 10565 FormatStyle PointerMiddle = getLLVMStyle(); 10566 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle; 10567 verifyFormat("delete *x;", PointerMiddle); 10568 verifyFormat("int * x;", PointerMiddle); 10569 verifyFormat("int *[] x;", PointerMiddle); 10570 verifyFormat("template <int * y> f() {}", PointerMiddle); 10571 verifyFormat("int * f(int * a) {}", PointerMiddle); 10572 verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle); 10573 verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle); 10574 verifyFormat("A<int *> a;", PointerMiddle); 10575 verifyFormat("A<int **> a;", PointerMiddle); 10576 verifyFormat("A<int *, int *> a;", PointerMiddle); 10577 verifyFormat("A<int *[]> a;", PointerMiddle); 10578 verifyFormat("A = new SomeType *[Length]();", PointerMiddle); 10579 verifyFormat("A = new SomeType *[Length];", PointerMiddle); 10580 verifyFormat("T ** t = new T *;", PointerMiddle); 10581 10582 // Member function reference qualifiers aren't binary operators. 10583 verifyFormat("string // break\n" 10584 "operator()() & {}"); 10585 verifyFormat("string // break\n" 10586 "operator()() && {}"); 10587 verifyGoogleFormat("template <typename T>\n" 10588 "auto x() & -> int {}"); 10589 10590 // Should be binary operators when used as an argument expression (overloaded 10591 // operator invoked as a member function). 10592 verifyFormat("void f() { a.operator()(a * a); }"); 10593 verifyFormat("void f() { a->operator()(a & a); }"); 10594 verifyFormat("void f() { a.operator()(*a & *a); }"); 10595 verifyFormat("void f() { a->operator()(*a * *a); }"); 10596 10597 verifyFormat("int operator()(T (&&)[N]) { return 1; }"); 10598 verifyFormat("int operator()(T (&)[N]) { return 0; }"); 10599 } 10600 10601 TEST_F(FormatTest, UnderstandsAttributes) { 10602 verifyFormat("SomeType s __attribute__((unused)) (InitValue);"); 10603 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n" 10604 "aaaaaaaaaaaaaaaaaaaaaaa(int i);"); 10605 verifyFormat("__attribute__((nodebug)) ::qualified_type f();"); 10606 FormatStyle AfterType = getLLVMStyle(); 10607 AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 10608 verifyFormat("__attribute__((nodebug)) void\n" 10609 "foo() {}\n", 10610 AfterType); 10611 verifyFormat("__unused void\n" 10612 "foo() {}", 10613 AfterType); 10614 10615 FormatStyle CustomAttrs = getLLVMStyle(); 10616 CustomAttrs.AttributeMacros.push_back("__unused"); 10617 CustomAttrs.AttributeMacros.push_back("__attr1"); 10618 CustomAttrs.AttributeMacros.push_back("__attr2"); 10619 CustomAttrs.AttributeMacros.push_back("no_underscore_attr"); 10620 verifyFormat("vector<SomeType *__attribute((foo))> v;"); 10621 verifyFormat("vector<SomeType *__attribute__((foo))> v;"); 10622 verifyFormat("vector<SomeType * __not_attribute__((foo))> v;"); 10623 // Check that it is parsed as a multiplication without AttributeMacros and 10624 // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros. 10625 verifyFormat("vector<SomeType * __attr1> v;"); 10626 verifyFormat("vector<SomeType __attr1 *> v;"); 10627 verifyFormat("vector<SomeType __attr1 *const> v;"); 10628 verifyFormat("vector<SomeType __attr1 * __attr2> v;"); 10629 verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs); 10630 verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs); 10631 verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs); 10632 verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs); 10633 verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs); 10634 verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs); 10635 verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs); 10636 10637 // Check that these are not parsed as function declarations: 10638 CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 10639 CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman; 10640 verifyFormat("SomeType s(InitValue);", CustomAttrs); 10641 verifyFormat("SomeType s{InitValue};", CustomAttrs); 10642 verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs); 10643 verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs); 10644 verifyFormat("SomeType s __unused(InitValue);", CustomAttrs); 10645 verifyFormat("SomeType s __unused{InitValue};", CustomAttrs); 10646 verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs); 10647 verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs); 10648 } 10649 10650 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) { 10651 // Check that qualifiers on pointers don't break parsing of casts. 10652 verifyFormat("x = (foo *const)*v;"); 10653 verifyFormat("x = (foo *volatile)*v;"); 10654 verifyFormat("x = (foo *restrict)*v;"); 10655 verifyFormat("x = (foo *__attribute__((foo)))*v;"); 10656 verifyFormat("x = (foo *_Nonnull)*v;"); 10657 verifyFormat("x = (foo *_Nullable)*v;"); 10658 verifyFormat("x = (foo *_Null_unspecified)*v;"); 10659 verifyFormat("x = (foo *_Nonnull)*v;"); 10660 verifyFormat("x = (foo *[[clang::attr]])*v;"); 10661 verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;"); 10662 verifyFormat("x = (foo *__ptr32)*v;"); 10663 verifyFormat("x = (foo *__ptr64)*v;"); 10664 verifyFormat("x = (foo *__capability)*v;"); 10665 10666 // Check that we handle multiple trailing qualifiers and skip them all to 10667 // determine that the expression is a cast to a pointer type. 10668 FormatStyle LongPointerRight = getLLVMStyleWithColumns(999); 10669 FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999); 10670 LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left; 10671 StringRef AllQualifiers = 10672 "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified " 10673 "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability"; 10674 verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight); 10675 verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft); 10676 10677 // Also check that address-of is not parsed as a binary bitwise-and: 10678 verifyFormat("x = (foo *const)&v;"); 10679 verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight); 10680 verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft); 10681 10682 // Check custom qualifiers: 10683 FormatStyle CustomQualifier = getLLVMStyleWithColumns(999); 10684 CustomQualifier.AttributeMacros.push_back("__my_qualifier"); 10685 verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier. 10686 verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier); 10687 verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(), 10688 CustomQualifier); 10689 verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(), 10690 CustomQualifier); 10691 10692 // Check that unknown identifiers result in binary operator parsing: 10693 verifyFormat("x = (foo * __unknown_qualifier) * v;"); 10694 verifyFormat("x = (foo * __unknown_qualifier) & v;"); 10695 } 10696 10697 TEST_F(FormatTest, UnderstandsSquareAttributes) { 10698 verifyFormat("SomeType s [[unused]] (InitValue);"); 10699 verifyFormat("SomeType s [[gnu::unused]] (InitValue);"); 10700 verifyFormat("SomeType s [[using gnu: unused]] (InitValue);"); 10701 verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}"); 10702 verifyFormat("void f() [[deprecated(\"so sorry\")]];"); 10703 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10704 " [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);"); 10705 verifyFormat("[[nodiscard]] bool f() { return false; }"); 10706 verifyFormat("class [[nodiscard]] f {\npublic:\n f() {}\n}"); 10707 verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n f() {}\n}"); 10708 verifyFormat("class [[gnu::unused]] f {\npublic:\n f() {}\n}"); 10709 verifyFormat("[[nodiscard]] ::qualified_type f();"); 10710 10711 // Make sure we do not mistake attributes for array subscripts. 10712 verifyFormat("int a() {}\n" 10713 "[[unused]] int b() {}\n"); 10714 verifyFormat("NSArray *arr;\n" 10715 "arr[[Foo() bar]];"); 10716 10717 // On the other hand, we still need to correctly find array subscripts. 10718 verifyFormat("int a = std::vector<int>{1, 2, 3}[0];"); 10719 10720 // Make sure that we do not mistake Objective-C method inside array literals 10721 // as attributes, even if those method names are also keywords. 10722 verifyFormat("@[ [foo bar] ];"); 10723 verifyFormat("@[ [NSArray class] ];"); 10724 verifyFormat("@[ [foo enum] ];"); 10725 10726 verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }"); 10727 10728 // Make sure we do not parse attributes as lambda introducers. 10729 FormatStyle MultiLineFunctions = getLLVMStyle(); 10730 MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 10731 verifyFormat("[[unused]] int b() {\n" 10732 " return 42;\n" 10733 "}\n", 10734 MultiLineFunctions); 10735 } 10736 10737 TEST_F(FormatTest, AttributeClass) { 10738 FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp); 10739 verifyFormat("class S {\n" 10740 " S(S&&) = default;\n" 10741 "};", 10742 Style); 10743 verifyFormat("class [[nodiscard]] S {\n" 10744 " S(S&&) = default;\n" 10745 "};", 10746 Style); 10747 verifyFormat("class __attribute((maybeunused)) S {\n" 10748 " S(S&&) = default;\n" 10749 "};", 10750 Style); 10751 verifyFormat("struct S {\n" 10752 " S(S&&) = default;\n" 10753 "};", 10754 Style); 10755 verifyFormat("struct [[nodiscard]] S {\n" 10756 " S(S&&) = default;\n" 10757 "};", 10758 Style); 10759 } 10760 10761 TEST_F(FormatTest, AttributesAfterMacro) { 10762 FormatStyle Style = getLLVMStyle(); 10763 verifyFormat("MACRO;\n" 10764 "__attribute__((maybe_unused)) int foo() {\n" 10765 " //...\n" 10766 "}"); 10767 10768 verifyFormat("MACRO;\n" 10769 "[[nodiscard]] int foo() {\n" 10770 " //...\n" 10771 "}"); 10772 10773 EXPECT_EQ("MACRO\n\n" 10774 "__attribute__((maybe_unused)) int foo() {\n" 10775 " //...\n" 10776 "}", 10777 format("MACRO\n\n" 10778 "__attribute__((maybe_unused)) int foo() {\n" 10779 " //...\n" 10780 "}")); 10781 10782 EXPECT_EQ("MACRO\n\n" 10783 "[[nodiscard]] int foo() {\n" 10784 " //...\n" 10785 "}", 10786 format("MACRO\n\n" 10787 "[[nodiscard]] int foo() {\n" 10788 " //...\n" 10789 "}")); 10790 } 10791 10792 TEST_F(FormatTest, AttributePenaltyBreaking) { 10793 FormatStyle Style = getLLVMStyle(); 10794 verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n" 10795 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}", 10796 Style); 10797 verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n" 10798 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}", 10799 Style); 10800 verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const " 10801 "shared_ptr<ALongTypeName> &C d) {\n}", 10802 Style); 10803 } 10804 10805 TEST_F(FormatTest, UnderstandsEllipsis) { 10806 FormatStyle Style = getLLVMStyle(); 10807 verifyFormat("int printf(const char *fmt, ...);"); 10808 verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }"); 10809 verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}"); 10810 10811 verifyFormat("template <int *...PP> a;", Style); 10812 10813 Style.PointerAlignment = FormatStyle::PAS_Left; 10814 verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style); 10815 10816 verifyFormat("template <int*... PP> a;", Style); 10817 10818 Style.PointerAlignment = FormatStyle::PAS_Middle; 10819 verifyFormat("template <int *... PP> a;", Style); 10820 } 10821 10822 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) { 10823 EXPECT_EQ("int *a;\n" 10824 "int *a;\n" 10825 "int *a;", 10826 format("int *a;\n" 10827 "int* a;\n" 10828 "int *a;", 10829 getGoogleStyle())); 10830 EXPECT_EQ("int* a;\n" 10831 "int* a;\n" 10832 "int* a;", 10833 format("int* a;\n" 10834 "int* a;\n" 10835 "int *a;", 10836 getGoogleStyle())); 10837 EXPECT_EQ("int *a;\n" 10838 "int *a;\n" 10839 "int *a;", 10840 format("int *a;\n" 10841 "int * a;\n" 10842 "int * a;", 10843 getGoogleStyle())); 10844 EXPECT_EQ("auto x = [] {\n" 10845 " int *a;\n" 10846 " int *a;\n" 10847 " int *a;\n" 10848 "};", 10849 format("auto x=[]{int *a;\n" 10850 "int * a;\n" 10851 "int * a;};", 10852 getGoogleStyle())); 10853 } 10854 10855 TEST_F(FormatTest, UnderstandsRvalueReferences) { 10856 verifyFormat("int f(int &&a) {}"); 10857 verifyFormat("int f(int a, char &&b) {}"); 10858 verifyFormat("void f() { int &&a = b; }"); 10859 verifyGoogleFormat("int f(int a, char&& b) {}"); 10860 verifyGoogleFormat("void f() { int&& a = b; }"); 10861 10862 verifyIndependentOfContext("A<int &&> a;"); 10863 verifyIndependentOfContext("A<int &&, int &&> a;"); 10864 verifyGoogleFormat("A<int&&> a;"); 10865 verifyGoogleFormat("A<int&&, int&&> a;"); 10866 10867 // Not rvalue references: 10868 verifyFormat("template <bool B, bool C> class A {\n" 10869 " static_assert(B && C, \"Something is wrong\");\n" 10870 "};"); 10871 verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))"); 10872 verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))"); 10873 verifyFormat("#define A(a, b) (a && b)"); 10874 } 10875 10876 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) { 10877 verifyFormat("void f() {\n" 10878 " x[aaaaaaaaa -\n" 10879 " b] = 23;\n" 10880 "}", 10881 getLLVMStyleWithColumns(15)); 10882 } 10883 10884 TEST_F(FormatTest, FormatsCasts) { 10885 verifyFormat("Type *A = static_cast<Type *>(P);"); 10886 verifyFormat("static_cast<Type *>(P);"); 10887 verifyFormat("static_cast<Type &>(Fun)(Args);"); 10888 verifyFormat("static_cast<Type &>(*Fun)(Args);"); 10889 verifyFormat("if (static_cast<int>(A) + B >= 0)\n ;"); 10890 // Check that static_cast<...>(...) does not require the next token to be on 10891 // the same line. 10892 verifyFormat("some_loooong_output << something_something__ << " 10893 "static_cast<const void *>(R)\n" 10894 " << something;"); 10895 verifyFormat("a = static_cast<Type &>(*Fun)(Args);"); 10896 verifyFormat("const_cast<Type &>(*Fun)(Args);"); 10897 verifyFormat("dynamic_cast<Type &>(*Fun)(Args);"); 10898 verifyFormat("reinterpret_cast<Type &>(*Fun)(Args);"); 10899 verifyFormat("Type *A = (Type *)P;"); 10900 verifyFormat("Type *A = (vector<Type *, int *>)P;"); 10901 verifyFormat("int a = (int)(2.0f);"); 10902 verifyFormat("int a = (int)2.0f;"); 10903 verifyFormat("x[(int32)y];"); 10904 verifyFormat("x = (int32)y;"); 10905 verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)"); 10906 verifyFormat("int a = (int)*b;"); 10907 verifyFormat("int a = (int)2.0f;"); 10908 verifyFormat("int a = (int)~0;"); 10909 verifyFormat("int a = (int)++a;"); 10910 verifyFormat("int a = (int)sizeof(int);"); 10911 verifyFormat("int a = (int)+2;"); 10912 verifyFormat("my_int a = (my_int)2.0f;"); 10913 verifyFormat("my_int a = (my_int)sizeof(int);"); 10914 verifyFormat("return (my_int)aaa;"); 10915 verifyFormat("#define x ((int)-1)"); 10916 verifyFormat("#define LENGTH(x, y) (x) - (y) + 1"); 10917 verifyFormat("#define p(q) ((int *)&q)"); 10918 verifyFormat("fn(a)(b) + 1;"); 10919 10920 verifyFormat("void f() { my_int a = (my_int)*b; }"); 10921 verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }"); 10922 verifyFormat("my_int a = (my_int)~0;"); 10923 verifyFormat("my_int a = (my_int)++a;"); 10924 verifyFormat("my_int a = (my_int)-2;"); 10925 verifyFormat("my_int a = (my_int)1;"); 10926 verifyFormat("my_int a = (my_int *)1;"); 10927 verifyFormat("my_int a = (const my_int)-1;"); 10928 verifyFormat("my_int a = (const my_int *)-1;"); 10929 verifyFormat("my_int a = (my_int)(my_int)-1;"); 10930 verifyFormat("my_int a = (ns::my_int)-2;"); 10931 verifyFormat("case (my_int)ONE:"); 10932 verifyFormat("auto x = (X)this;"); 10933 // Casts in Obj-C style calls used to not be recognized as such. 10934 verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle()); 10935 10936 // FIXME: single value wrapped with paren will be treated as cast. 10937 verifyFormat("void f(int i = (kValue)*kMask) {}"); 10938 10939 verifyFormat("{ (void)F; }"); 10940 10941 // Don't break after a cast's 10942 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 10943 " (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n" 10944 " bbbbbbbbbbbbbbbbbbbbbb);"); 10945 10946 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(x)"); 10947 verifyFormat("#define CONF_BOOL(x) (bool *)(x)"); 10948 verifyFormat("#define CONF_BOOL(x) (bool)(x)"); 10949 verifyFormat("bool *y = (bool *)(void *)(x);"); 10950 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)(x)"); 10951 verifyFormat("bool *y = (bool *)(void *)(int)(x);"); 10952 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)foo(x)"); 10953 verifyFormat("bool *y = (bool *)(void *)(int)foo(x);"); 10954 10955 // These are not casts. 10956 verifyFormat("void f(int *) {}"); 10957 verifyFormat("f(foo)->b;"); 10958 verifyFormat("f(foo).b;"); 10959 verifyFormat("f(foo)(b);"); 10960 verifyFormat("f(foo)[b];"); 10961 verifyFormat("[](foo) { return 4; }(bar);"); 10962 verifyFormat("(*funptr)(foo)[4];"); 10963 verifyFormat("funptrs[4](foo)[4];"); 10964 verifyFormat("void f(int *);"); 10965 verifyFormat("void f(int *) = 0;"); 10966 verifyFormat("void f(SmallVector<int>) {}"); 10967 verifyFormat("void f(SmallVector<int>);"); 10968 verifyFormat("void f(SmallVector<int>) = 0;"); 10969 verifyFormat("void f(int i = (kA * kB) & kMask) {}"); 10970 verifyFormat("int a = sizeof(int) * b;"); 10971 verifyFormat("int a = alignof(int) * b;", getGoogleStyle()); 10972 verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;"); 10973 verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");"); 10974 verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;"); 10975 10976 // These are not casts, but at some point were confused with casts. 10977 verifyFormat("virtual void foo(int *) override;"); 10978 verifyFormat("virtual void foo(char &) const;"); 10979 verifyFormat("virtual void foo(int *a, char *) const;"); 10980 verifyFormat("int a = sizeof(int *) + b;"); 10981 verifyFormat("int a = alignof(int *) + b;", getGoogleStyle()); 10982 verifyFormat("bool b = f(g<int>) && c;"); 10983 verifyFormat("typedef void (*f)(int i) func;"); 10984 verifyFormat("void operator++(int) noexcept;"); 10985 verifyFormat("void operator++(int &) noexcept;"); 10986 verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t " 10987 "&) noexcept;"); 10988 verifyFormat( 10989 "void operator delete(std::size_t, const std::nothrow_t &) noexcept;"); 10990 verifyFormat("void operator delete(const std::nothrow_t &) noexcept;"); 10991 verifyFormat("void operator delete(std::nothrow_t &) noexcept;"); 10992 verifyFormat("void operator delete(nothrow_t &) noexcept;"); 10993 verifyFormat("void operator delete(foo &) noexcept;"); 10994 verifyFormat("void operator delete(foo) noexcept;"); 10995 verifyFormat("void operator delete(int) noexcept;"); 10996 verifyFormat("void operator delete(int &) noexcept;"); 10997 verifyFormat("void operator delete(int &) volatile noexcept;"); 10998 verifyFormat("void operator delete(int &) const"); 10999 verifyFormat("void operator delete(int &) = default"); 11000 verifyFormat("void operator delete(int &) = delete"); 11001 verifyFormat("void operator delete(int &) [[noreturn]]"); 11002 verifyFormat("void operator delete(int &) throw();"); 11003 verifyFormat("void operator delete(int &) throw(int);"); 11004 verifyFormat("auto operator delete(int &) -> int;"); 11005 verifyFormat("auto operator delete(int &) override"); 11006 verifyFormat("auto operator delete(int &) final"); 11007 11008 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n" 11009 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 11010 // FIXME: The indentation here is not ideal. 11011 verifyFormat( 11012 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11013 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n" 11014 " [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];"); 11015 } 11016 11017 TEST_F(FormatTest, FormatsFunctionTypes) { 11018 verifyFormat("A<bool()> a;"); 11019 verifyFormat("A<SomeType()> a;"); 11020 verifyFormat("A<void (*)(int, std::string)> a;"); 11021 verifyFormat("A<void *(int)>;"); 11022 verifyFormat("void *(*a)(int *, SomeType *);"); 11023 verifyFormat("int (*func)(void *);"); 11024 verifyFormat("void f() { int (*func)(void *); }"); 11025 verifyFormat("template <class CallbackClass>\n" 11026 "using MyCallback = void (CallbackClass::*)(SomeObject *Data);"); 11027 11028 verifyGoogleFormat("A<void*(int*, SomeType*)>;"); 11029 verifyGoogleFormat("void* (*a)(int);"); 11030 verifyGoogleFormat( 11031 "template <class CallbackClass>\n" 11032 "using MyCallback = void (CallbackClass::*)(SomeObject* Data);"); 11033 11034 // Other constructs can look somewhat like function types: 11035 verifyFormat("A<sizeof(*x)> a;"); 11036 verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)"); 11037 verifyFormat("some_var = function(*some_pointer_var)[0];"); 11038 verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }"); 11039 verifyFormat("int x = f(&h)();"); 11040 verifyFormat("returnsFunction(¶m1, ¶m2)(param);"); 11041 verifyFormat("std::function<\n" 11042 " LooooooooooongTemplatedType<\n" 11043 " SomeType>*(\n" 11044 " LooooooooooooooooongType type)>\n" 11045 " function;", 11046 getGoogleStyleWithColumns(40)); 11047 } 11048 11049 TEST_F(FormatTest, FormatsPointersToArrayTypes) { 11050 verifyFormat("A (*foo_)[6];"); 11051 verifyFormat("vector<int> (*foo_)[6];"); 11052 } 11053 11054 TEST_F(FormatTest, BreaksLongVariableDeclarations) { 11055 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 11056 " LoooooooooooooooooooooooooooooooooooooooongVariable;"); 11057 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n" 11058 " LoooooooooooooooooooooooooooooooooooooooongVariable;"); 11059 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 11060 " *LoooooooooooooooooooooooooooooooooooooooongVariable;"); 11061 11062 // Different ways of ()-initializiation. 11063 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 11064 " LoooooooooooooooooooooooooooooooooooooooongVariable(1);"); 11065 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 11066 " LoooooooooooooooooooooooooooooooooooooooongVariable(a);"); 11067 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 11068 " LoooooooooooooooooooooooooooooooooooooooongVariable({});"); 11069 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 11070 " LoooooooooooooooooooooooooooooooooooooongVariable([A a]);"); 11071 11072 // Lambdas should not confuse the variable declaration heuristic. 11073 verifyFormat("LooooooooooooooooongType\n" 11074 " variable(nullptr, [](A *a) {});", 11075 getLLVMStyleWithColumns(40)); 11076 } 11077 11078 TEST_F(FormatTest, BreaksLongDeclarations) { 11079 verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n" 11080 " AnotherNameForTheLongType;"); 11081 verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n" 11082 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 11083 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 11084 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();"); 11085 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n" 11086 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();"); 11087 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 11088 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 11089 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n" 11090 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 11091 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n" 11092 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 11093 verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n" 11094 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 11095 verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n" 11096 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 11097 verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n" 11098 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 11099 verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n" 11100 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 11101 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 11102 "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);"); 11103 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 11104 "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}"); 11105 FormatStyle Indented = getLLVMStyle(); 11106 Indented.IndentWrappedFunctionNames = true; 11107 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 11108 " LoooooooooooooooooooooooooooooooongFunctionDeclaration();", 11109 Indented); 11110 verifyFormat( 11111 "LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 11112 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 11113 Indented); 11114 verifyFormat( 11115 "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n" 11116 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 11117 Indented); 11118 verifyFormat( 11119 "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n" 11120 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 11121 Indented); 11122 11123 // FIXME: Without the comment, this breaks after "(". 11124 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType // break\n" 11125 " (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();", 11126 getGoogleStyle()); 11127 11128 verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n" 11129 " int LoooooooooooooooooooongParam2) {}"); 11130 verifyFormat( 11131 "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n" 11132 " SourceLocation L, IdentifierIn *II,\n" 11133 " Type *T) {}"); 11134 verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n" 11135 "ReallyReaaallyLongFunctionName(\n" 11136 " const std::string &SomeParameter,\n" 11137 " const SomeType<string, SomeOtherTemplateParameter>\n" 11138 " &ReallyReallyLongParameterName,\n" 11139 " const SomeType<string, SomeOtherTemplateParameter>\n" 11140 " &AnotherLongParameterName) {}"); 11141 verifyFormat("template <typename A>\n" 11142 "SomeLoooooooooooooooooooooongType<\n" 11143 " typename some_namespace::SomeOtherType<A>::Type>\n" 11144 "Function() {}"); 11145 11146 verifyGoogleFormat( 11147 "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n" 11148 " aaaaaaaaaaaaaaaaaaaaaaa;"); 11149 verifyGoogleFormat( 11150 "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n" 11151 " SourceLocation L) {}"); 11152 verifyGoogleFormat( 11153 "some_namespace::LongReturnType\n" 11154 "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n" 11155 " int first_long_parameter, int second_parameter) {}"); 11156 11157 verifyGoogleFormat("template <typename T>\n" 11158 "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n" 11159 "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}"); 11160 verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 11161 " int aaaaaaaaaaaaaaaaaaaaaaa);"); 11162 11163 verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n" 11164 " const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11165 " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 11166 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 11167 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n" 11168 " aaaaaaaaaaaaaaaaaaaaaaaa);"); 11169 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 11170 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 11171 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n" 11172 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 11173 11174 verifyFormat("template <typename T> // Templates on own line.\n" 11175 "static int // Some comment.\n" 11176 "MyFunction(int a);", 11177 getLLVMStyle()); 11178 } 11179 11180 TEST_F(FormatTest, FormatsAccessModifiers) { 11181 FormatStyle Style = getLLVMStyle(); 11182 EXPECT_EQ(Style.EmptyLineBeforeAccessModifier, 11183 FormatStyle::ELBAMS_LogicalBlock); 11184 verifyFormat("struct foo {\n" 11185 "private:\n" 11186 " void f() {}\n" 11187 "\n" 11188 "private:\n" 11189 " int i;\n" 11190 "\n" 11191 "protected:\n" 11192 " int j;\n" 11193 "};\n", 11194 Style); 11195 verifyFormat("struct foo {\n" 11196 "private:\n" 11197 " void f() {}\n" 11198 "\n" 11199 "private:\n" 11200 " int i;\n" 11201 "\n" 11202 "protected:\n" 11203 " int j;\n" 11204 "};\n", 11205 "struct foo {\n" 11206 "private:\n" 11207 " void f() {}\n" 11208 "private:\n" 11209 " int i;\n" 11210 "protected:\n" 11211 " int j;\n" 11212 "};\n", 11213 Style); 11214 verifyFormat("struct foo { /* comment */\n" 11215 "private:\n" 11216 " int i;\n" 11217 " // comment\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 Style); 11233 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11234 verifyFormat("struct foo {\n" 11235 "private:\n" 11236 " void f() {}\n" 11237 "private:\n" 11238 " int i;\n" 11239 "protected:\n" 11240 " int j;\n" 11241 "};\n", 11242 Style); 11243 verifyFormat("struct foo {\n" 11244 "private:\n" 11245 " void f() {}\n" 11246 "private:\n" 11247 " int i;\n" 11248 "protected:\n" 11249 " int j;\n" 11250 "};\n", 11251 "struct foo {\n" 11252 "\n" 11253 "private:\n" 11254 " void f() {}\n" 11255 "\n" 11256 "private:\n" 11257 " int i;\n" 11258 "\n" 11259 "protected:\n" 11260 " int j;\n" 11261 "};\n", 11262 Style); 11263 verifyFormat("struct foo { /* comment */\n" 11264 "private:\n" 11265 " int i;\n" 11266 " // comment\n" 11267 "private:\n" 11268 " int j;\n" 11269 "};\n", 11270 "struct foo { /* comment */\n" 11271 "\n" 11272 "private:\n" 11273 " int i;\n" 11274 " // comment\n" 11275 "\n" 11276 "private:\n" 11277 " int j;\n" 11278 "};\n", 11279 Style); 11280 verifyFormat("struct foo {\n" 11281 "#ifdef FOO\n" 11282 "#endif\n" 11283 "private:\n" 11284 " int i;\n" 11285 "#ifdef FOO\n" 11286 "private:\n" 11287 "#endif\n" 11288 " int j;\n" 11289 "};\n", 11290 "struct foo {\n" 11291 "#ifdef FOO\n" 11292 "#endif\n" 11293 "\n" 11294 "private:\n" 11295 " int i;\n" 11296 "#ifdef FOO\n" 11297 "\n" 11298 "private:\n" 11299 "#endif\n" 11300 " int j;\n" 11301 "};\n", 11302 Style); 11303 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11304 verifyFormat("struct foo {\n" 11305 "private:\n" 11306 " void f() {}\n" 11307 "\n" 11308 "private:\n" 11309 " int i;\n" 11310 "\n" 11311 "protected:\n" 11312 " int j;\n" 11313 "};\n", 11314 Style); 11315 verifyFormat("struct foo {\n" 11316 "private:\n" 11317 " void f() {}\n" 11318 "\n" 11319 "private:\n" 11320 " int i;\n" 11321 "\n" 11322 "protected:\n" 11323 " int j;\n" 11324 "};\n", 11325 "struct foo {\n" 11326 "private:\n" 11327 " void f() {}\n" 11328 "private:\n" 11329 " int i;\n" 11330 "protected:\n" 11331 " int j;\n" 11332 "};\n", 11333 Style); 11334 verifyFormat("struct foo { /* comment */\n" 11335 "private:\n" 11336 " int i;\n" 11337 " // comment\n" 11338 "\n" 11339 "private:\n" 11340 " int j;\n" 11341 "};\n", 11342 "struct foo { /* comment */\n" 11343 "private:\n" 11344 " int i;\n" 11345 " // comment\n" 11346 "\n" 11347 "private:\n" 11348 " int j;\n" 11349 "};\n", 11350 Style); 11351 verifyFormat("struct foo {\n" 11352 "#ifdef FOO\n" 11353 "#endif\n" 11354 "\n" 11355 "private:\n" 11356 " int i;\n" 11357 "#ifdef FOO\n" 11358 "\n" 11359 "private:\n" 11360 "#endif\n" 11361 " int j;\n" 11362 "};\n", 11363 "struct foo {\n" 11364 "#ifdef FOO\n" 11365 "#endif\n" 11366 "private:\n" 11367 " int i;\n" 11368 "#ifdef FOO\n" 11369 "private:\n" 11370 "#endif\n" 11371 " int j;\n" 11372 "};\n", 11373 Style); 11374 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11375 EXPECT_EQ("struct foo {\n" 11376 "\n" 11377 "private:\n" 11378 " void f() {}\n" 11379 "\n" 11380 "private:\n" 11381 " int i;\n" 11382 "\n" 11383 "protected:\n" 11384 " int j;\n" 11385 "};\n", 11386 format("struct foo {\n" 11387 "\n" 11388 "private:\n" 11389 " void f() {}\n" 11390 "\n" 11391 "private:\n" 11392 " int i;\n" 11393 "\n" 11394 "protected:\n" 11395 " int j;\n" 11396 "};\n", 11397 Style)); 11398 verifyFormat("struct foo {\n" 11399 "private:\n" 11400 " void f() {}\n" 11401 "private:\n" 11402 " int i;\n" 11403 "protected:\n" 11404 " int j;\n" 11405 "};\n", 11406 Style); 11407 EXPECT_EQ("struct foo { /* comment */\n" 11408 "\n" 11409 "private:\n" 11410 " int i;\n" 11411 " // comment\n" 11412 "\n" 11413 "private:\n" 11414 " int j;\n" 11415 "};\n", 11416 format("struct foo { /* comment */\n" 11417 "\n" 11418 "private:\n" 11419 " int i;\n" 11420 " // comment\n" 11421 "\n" 11422 "private:\n" 11423 " int j;\n" 11424 "};\n", 11425 Style)); 11426 verifyFormat("struct foo { /* comment */\n" 11427 "private:\n" 11428 " int i;\n" 11429 " // comment\n" 11430 "private:\n" 11431 " int j;\n" 11432 "};\n", 11433 Style); 11434 EXPECT_EQ("struct foo {\n" 11435 "#ifdef FOO\n" 11436 "#endif\n" 11437 "\n" 11438 "private:\n" 11439 " int i;\n" 11440 "#ifdef FOO\n" 11441 "\n" 11442 "private:\n" 11443 "#endif\n" 11444 " int j;\n" 11445 "};\n", 11446 format("struct foo {\n" 11447 "#ifdef FOO\n" 11448 "#endif\n" 11449 "\n" 11450 "private:\n" 11451 " int i;\n" 11452 "#ifdef FOO\n" 11453 "\n" 11454 "private:\n" 11455 "#endif\n" 11456 " int j;\n" 11457 "};\n", 11458 Style)); 11459 verifyFormat("struct foo {\n" 11460 "#ifdef FOO\n" 11461 "#endif\n" 11462 "private:\n" 11463 " int i;\n" 11464 "#ifdef FOO\n" 11465 "private:\n" 11466 "#endif\n" 11467 " int j;\n" 11468 "};\n", 11469 Style); 11470 11471 FormatStyle NoEmptyLines = getLLVMStyle(); 11472 NoEmptyLines.MaxEmptyLinesToKeep = 0; 11473 verifyFormat("struct foo {\n" 11474 "private:\n" 11475 " void f() {}\n" 11476 "\n" 11477 "private:\n" 11478 " int i;\n" 11479 "\n" 11480 "public:\n" 11481 "protected:\n" 11482 " int j;\n" 11483 "};\n", 11484 NoEmptyLines); 11485 11486 NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11487 verifyFormat("struct foo {\n" 11488 "private:\n" 11489 " void f() {}\n" 11490 "private:\n" 11491 " int i;\n" 11492 "public:\n" 11493 "protected:\n" 11494 " int j;\n" 11495 "};\n", 11496 NoEmptyLines); 11497 11498 NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11499 verifyFormat("struct foo {\n" 11500 "private:\n" 11501 " void f() {}\n" 11502 "\n" 11503 "private:\n" 11504 " int i;\n" 11505 "\n" 11506 "public:\n" 11507 "\n" 11508 "protected:\n" 11509 " int j;\n" 11510 "};\n", 11511 NoEmptyLines); 11512 } 11513 11514 TEST_F(FormatTest, FormatsAfterAccessModifiers) { 11515 11516 FormatStyle Style = getLLVMStyle(); 11517 EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never); 11518 verifyFormat("struct foo {\n" 11519 "private:\n" 11520 " void f() {}\n" 11521 "\n" 11522 "private:\n" 11523 " int i;\n" 11524 "\n" 11525 "protected:\n" 11526 " int j;\n" 11527 "};\n", 11528 Style); 11529 11530 // Check if lines are removed. 11531 verifyFormat("struct foo {\n" 11532 "private:\n" 11533 " void f() {}\n" 11534 "\n" 11535 "private:\n" 11536 " int i;\n" 11537 "\n" 11538 "protected:\n" 11539 " int j;\n" 11540 "};\n", 11541 "struct foo {\n" 11542 "private:\n" 11543 "\n" 11544 " void f() {}\n" 11545 "\n" 11546 "private:\n" 11547 "\n" 11548 " int i;\n" 11549 "\n" 11550 "protected:\n" 11551 "\n" 11552 " int j;\n" 11553 "};\n", 11554 Style); 11555 11556 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11557 verifyFormat("struct foo {\n" 11558 "private:\n" 11559 "\n" 11560 " void f() {}\n" 11561 "\n" 11562 "private:\n" 11563 "\n" 11564 " int i;\n" 11565 "\n" 11566 "protected:\n" 11567 "\n" 11568 " int j;\n" 11569 "};\n", 11570 Style); 11571 11572 // Check if lines are added. 11573 verifyFormat("struct foo {\n" 11574 "private:\n" 11575 "\n" 11576 " void f() {}\n" 11577 "\n" 11578 "private:\n" 11579 "\n" 11580 " int i;\n" 11581 "\n" 11582 "protected:\n" 11583 "\n" 11584 " int j;\n" 11585 "};\n", 11586 "struct foo {\n" 11587 "private:\n" 11588 " void f() {}\n" 11589 "\n" 11590 "private:\n" 11591 " int i;\n" 11592 "\n" 11593 "protected:\n" 11594 " int j;\n" 11595 "};\n", 11596 Style); 11597 11598 // Leave tests rely on the code layout, test::messUp can not be used. 11599 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11600 Style.MaxEmptyLinesToKeep = 0u; 11601 verifyFormat("struct foo {\n" 11602 "private:\n" 11603 " void f() {}\n" 11604 "\n" 11605 "private:\n" 11606 " int i;\n" 11607 "\n" 11608 "protected:\n" 11609 " int j;\n" 11610 "};\n", 11611 Style); 11612 11613 // Check if MaxEmptyLinesToKeep is respected. 11614 EXPECT_EQ("struct foo {\n" 11615 "private:\n" 11616 " void f() {}\n" 11617 "\n" 11618 "private:\n" 11619 " int i;\n" 11620 "\n" 11621 "protected:\n" 11622 " int j;\n" 11623 "};\n", 11624 format("struct foo {\n" 11625 "private:\n" 11626 "\n\n\n" 11627 " void f() {}\n" 11628 "\n" 11629 "private:\n" 11630 "\n\n\n" 11631 " int i;\n" 11632 "\n" 11633 "protected:\n" 11634 "\n\n\n" 11635 " int j;\n" 11636 "};\n", 11637 Style)); 11638 11639 Style.MaxEmptyLinesToKeep = 1u; 11640 EXPECT_EQ("struct foo {\n" 11641 "private:\n" 11642 "\n" 11643 " void f() {}\n" 11644 "\n" 11645 "private:\n" 11646 "\n" 11647 " int i;\n" 11648 "\n" 11649 "protected:\n" 11650 "\n" 11651 " int j;\n" 11652 "};\n", 11653 format("struct foo {\n" 11654 "private:\n" 11655 "\n" 11656 " void f() {}\n" 11657 "\n" 11658 "private:\n" 11659 "\n" 11660 " int i;\n" 11661 "\n" 11662 "protected:\n" 11663 "\n" 11664 " int j;\n" 11665 "};\n", 11666 Style)); 11667 // Check if no lines are kept. 11668 EXPECT_EQ("struct foo {\n" 11669 "private:\n" 11670 " void f() {}\n" 11671 "\n" 11672 "private:\n" 11673 " int i;\n" 11674 "\n" 11675 "protected:\n" 11676 " int j;\n" 11677 "};\n", 11678 format("struct foo {\n" 11679 "private:\n" 11680 " void f() {}\n" 11681 "\n" 11682 "private:\n" 11683 " int i;\n" 11684 "\n" 11685 "protected:\n" 11686 " int j;\n" 11687 "};\n", 11688 Style)); 11689 // Check if MaxEmptyLinesToKeep is respected. 11690 EXPECT_EQ("struct foo {\n" 11691 "private:\n" 11692 "\n" 11693 " void f() {}\n" 11694 "\n" 11695 "private:\n" 11696 "\n" 11697 " int i;\n" 11698 "\n" 11699 "protected:\n" 11700 "\n" 11701 " int j;\n" 11702 "};\n", 11703 format("struct foo {\n" 11704 "private:\n" 11705 "\n\n\n" 11706 " void f() {}\n" 11707 "\n" 11708 "private:\n" 11709 "\n\n\n" 11710 " int i;\n" 11711 "\n" 11712 "protected:\n" 11713 "\n\n\n" 11714 " int j;\n" 11715 "};\n", 11716 Style)); 11717 11718 Style.MaxEmptyLinesToKeep = 10u; 11719 EXPECT_EQ("struct foo {\n" 11720 "private:\n" 11721 "\n\n\n" 11722 " void f() {}\n" 11723 "\n" 11724 "private:\n" 11725 "\n\n\n" 11726 " int i;\n" 11727 "\n" 11728 "protected:\n" 11729 "\n\n\n" 11730 " int j;\n" 11731 "};\n", 11732 format("struct foo {\n" 11733 "private:\n" 11734 "\n\n\n" 11735 " void f() {}\n" 11736 "\n" 11737 "private:\n" 11738 "\n\n\n" 11739 " int i;\n" 11740 "\n" 11741 "protected:\n" 11742 "\n\n\n" 11743 " int j;\n" 11744 "};\n", 11745 Style)); 11746 11747 // Test with comments. 11748 Style = getLLVMStyle(); 11749 verifyFormat("struct foo {\n" 11750 "private:\n" 11751 " // comment\n" 11752 " void f() {}\n" 11753 "\n" 11754 "private: /* comment */\n" 11755 " int i;\n" 11756 "};\n", 11757 Style); 11758 verifyFormat("struct foo {\n" 11759 "private:\n" 11760 " // comment\n" 11761 " void f() {}\n" 11762 "\n" 11763 "private: /* comment */\n" 11764 " int i;\n" 11765 "};\n", 11766 "struct foo {\n" 11767 "private:\n" 11768 "\n" 11769 " // comment\n" 11770 " void f() {}\n" 11771 "\n" 11772 "private: /* comment */\n" 11773 "\n" 11774 " int i;\n" 11775 "};\n", 11776 Style); 11777 11778 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11779 verifyFormat("struct foo {\n" 11780 "private:\n" 11781 "\n" 11782 " // comment\n" 11783 " void f() {}\n" 11784 "\n" 11785 "private: /* comment */\n" 11786 "\n" 11787 " int i;\n" 11788 "};\n", 11789 "struct foo {\n" 11790 "private:\n" 11791 " // comment\n" 11792 " void f() {}\n" 11793 "\n" 11794 "private: /* comment */\n" 11795 " int i;\n" 11796 "};\n", 11797 Style); 11798 verifyFormat("struct foo {\n" 11799 "private:\n" 11800 "\n" 11801 " // comment\n" 11802 " void f() {}\n" 11803 "\n" 11804 "private: /* comment */\n" 11805 "\n" 11806 " int i;\n" 11807 "};\n", 11808 Style); 11809 11810 // Test with preprocessor defines. 11811 Style = getLLVMStyle(); 11812 verifyFormat("struct foo {\n" 11813 "private:\n" 11814 "#ifdef FOO\n" 11815 "#endif\n" 11816 " void f() {}\n" 11817 "};\n", 11818 Style); 11819 verifyFormat("struct foo {\n" 11820 "private:\n" 11821 "#ifdef FOO\n" 11822 "#endif\n" 11823 " void f() {}\n" 11824 "};\n", 11825 "struct foo {\n" 11826 "private:\n" 11827 "\n" 11828 "#ifdef FOO\n" 11829 "#endif\n" 11830 " void f() {}\n" 11831 "};\n", 11832 Style); 11833 11834 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11835 verifyFormat("struct foo {\n" 11836 "private:\n" 11837 "\n" 11838 "#ifdef FOO\n" 11839 "#endif\n" 11840 " void f() {}\n" 11841 "};\n", 11842 "struct foo {\n" 11843 "private:\n" 11844 "#ifdef FOO\n" 11845 "#endif\n" 11846 " void f() {}\n" 11847 "};\n", 11848 Style); 11849 verifyFormat("struct foo {\n" 11850 "private:\n" 11851 "\n" 11852 "#ifdef FOO\n" 11853 "#endif\n" 11854 " void f() {}\n" 11855 "};\n", 11856 Style); 11857 } 11858 11859 TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) { 11860 // Combined tests of EmptyLineAfterAccessModifier and 11861 // EmptyLineBeforeAccessModifier. 11862 FormatStyle Style = getLLVMStyle(); 11863 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11864 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11865 verifyFormat("struct foo {\n" 11866 "private:\n" 11867 "\n" 11868 "protected:\n" 11869 "};\n", 11870 Style); 11871 11872 Style.MaxEmptyLinesToKeep = 10u; 11873 // Both remove all new lines. 11874 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11875 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11876 verifyFormat("struct foo {\n" 11877 "private:\n" 11878 "protected:\n" 11879 "};\n", 11880 "struct foo {\n" 11881 "private:\n" 11882 "\n\n\n" 11883 "protected:\n" 11884 "};\n", 11885 Style); 11886 11887 // Leave tests rely on the code layout, test::messUp can not be used. 11888 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11889 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11890 Style.MaxEmptyLinesToKeep = 10u; 11891 EXPECT_EQ("struct foo {\n" 11892 "private:\n" 11893 "\n\n\n" 11894 "protected:\n" 11895 "};\n", 11896 format("struct foo {\n" 11897 "private:\n" 11898 "\n\n\n" 11899 "protected:\n" 11900 "};\n", 11901 Style)); 11902 Style.MaxEmptyLinesToKeep = 3u; 11903 EXPECT_EQ("struct foo {\n" 11904 "private:\n" 11905 "\n\n\n" 11906 "protected:\n" 11907 "};\n", 11908 format("struct foo {\n" 11909 "private:\n" 11910 "\n\n\n" 11911 "protected:\n" 11912 "};\n", 11913 Style)); 11914 Style.MaxEmptyLinesToKeep = 1u; 11915 EXPECT_EQ("struct foo {\n" 11916 "private:\n" 11917 "\n\n\n" 11918 "protected:\n" 11919 "};\n", 11920 format("struct foo {\n" 11921 "private:\n" 11922 "\n\n\n" 11923 "protected:\n" 11924 "};\n", 11925 Style)); // Based on new lines in original document and not 11926 // on the setting. 11927 11928 Style.MaxEmptyLinesToKeep = 10u; 11929 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11930 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11931 // Newlines are kept if they are greater than zero, 11932 // test::messUp removes all new lines which changes the logic 11933 EXPECT_EQ("struct foo {\n" 11934 "private:\n" 11935 "\n\n\n" 11936 "protected:\n" 11937 "};\n", 11938 format("struct foo {\n" 11939 "private:\n" 11940 "\n\n\n" 11941 "protected:\n" 11942 "};\n", 11943 Style)); 11944 11945 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11946 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11947 // test::messUp removes all new lines which changes the logic 11948 EXPECT_EQ("struct foo {\n" 11949 "private:\n" 11950 "\n\n\n" 11951 "protected:\n" 11952 "};\n", 11953 format("struct foo {\n" 11954 "private:\n" 11955 "\n\n\n" 11956 "protected:\n" 11957 "};\n", 11958 Style)); 11959 11960 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11961 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11962 EXPECT_EQ("struct foo {\n" 11963 "private:\n" 11964 "\n\n\n" 11965 "protected:\n" 11966 "};\n", 11967 format("struct foo {\n" 11968 "private:\n" 11969 "\n\n\n" 11970 "protected:\n" 11971 "};\n", 11972 Style)); // test::messUp removes all new lines which changes 11973 // the logic. 11974 11975 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11976 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11977 verifyFormat("struct foo {\n" 11978 "private:\n" 11979 "protected:\n" 11980 "};\n", 11981 "struct foo {\n" 11982 "private:\n" 11983 "\n\n\n" 11984 "protected:\n" 11985 "};\n", 11986 Style); 11987 11988 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11989 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11990 EXPECT_EQ("struct foo {\n" 11991 "private:\n" 11992 "\n\n\n" 11993 "protected:\n" 11994 "};\n", 11995 format("struct foo {\n" 11996 "private:\n" 11997 "\n\n\n" 11998 "protected:\n" 11999 "};\n", 12000 Style)); // test::messUp removes all new lines which changes 12001 // the logic. 12002 12003 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 12004 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 12005 verifyFormat("struct foo {\n" 12006 "private:\n" 12007 "protected:\n" 12008 "};\n", 12009 "struct foo {\n" 12010 "private:\n" 12011 "\n\n\n" 12012 "protected:\n" 12013 "};\n", 12014 Style); 12015 12016 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 12017 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 12018 verifyFormat("struct foo {\n" 12019 "private:\n" 12020 "protected:\n" 12021 "};\n", 12022 "struct foo {\n" 12023 "private:\n" 12024 "\n\n\n" 12025 "protected:\n" 12026 "};\n", 12027 Style); 12028 12029 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 12030 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 12031 verifyFormat("struct foo {\n" 12032 "private:\n" 12033 "protected:\n" 12034 "};\n", 12035 "struct foo {\n" 12036 "private:\n" 12037 "\n\n\n" 12038 "protected:\n" 12039 "};\n", 12040 Style); 12041 12042 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 12043 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 12044 verifyFormat("struct foo {\n" 12045 "private:\n" 12046 "protected:\n" 12047 "};\n", 12048 "struct foo {\n" 12049 "private:\n" 12050 "\n\n\n" 12051 "protected:\n" 12052 "};\n", 12053 Style); 12054 } 12055 12056 TEST_F(FormatTest, FormatsArrays) { 12057 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n" 12058 " [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;"); 12059 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n" 12060 " [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;"); 12061 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n" 12062 " aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}"); 12063 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 12064 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;"); 12065 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 12066 " [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;"); 12067 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 12068 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n" 12069 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;"); 12070 verifyFormat( 12071 "llvm::outs() << \"aaaaaaaaaaaa: \"\n" 12072 " << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n" 12073 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];"); 12074 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n" 12075 " .aaaaaaaaaaaaaaaaaaaaaa();"); 12076 12077 verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n" 12078 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];"); 12079 verifyFormat( 12080 "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n" 12081 " .aaaaaaa[0]\n" 12082 " .aaaaaaaaaaaaaaaaaaaaaa();"); 12083 verifyFormat("a[::b::c];"); 12084 12085 verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10)); 12086 12087 FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0); 12088 verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit); 12089 } 12090 12091 TEST_F(FormatTest, LineStartsWithSpecialCharacter) { 12092 verifyFormat("(a)->b();"); 12093 verifyFormat("--a;"); 12094 } 12095 12096 TEST_F(FormatTest, HandlesIncludeDirectives) { 12097 verifyFormat("#include <string>\n" 12098 "#include <a/b/c.h>\n" 12099 "#include \"a/b/string\"\n" 12100 "#include \"string.h\"\n" 12101 "#include \"string.h\"\n" 12102 "#include <a-a>\n" 12103 "#include < path with space >\n" 12104 "#include_next <test.h>" 12105 "#include \"abc.h\" // this is included for ABC\n" 12106 "#include \"some long include\" // with a comment\n" 12107 "#include \"some very long include path\"\n" 12108 "#include <some/very/long/include/path>\n", 12109 getLLVMStyleWithColumns(35)); 12110 EXPECT_EQ("#include \"a.h\"", format("#include \"a.h\"")); 12111 EXPECT_EQ("#include <a>", format("#include<a>")); 12112 12113 verifyFormat("#import <string>"); 12114 verifyFormat("#import <a/b/c.h>"); 12115 verifyFormat("#import \"a/b/string\""); 12116 verifyFormat("#import \"string.h\""); 12117 verifyFormat("#import \"string.h\""); 12118 verifyFormat("#if __has_include(<strstream>)\n" 12119 "#include <strstream>\n" 12120 "#endif"); 12121 12122 verifyFormat("#define MY_IMPORT <a/b>"); 12123 12124 verifyFormat("#if __has_include(<a/b>)"); 12125 verifyFormat("#if __has_include_next(<a/b>)"); 12126 verifyFormat("#define F __has_include(<a/b>)"); 12127 verifyFormat("#define F __has_include_next(<a/b>)"); 12128 12129 // Protocol buffer definition or missing "#". 12130 verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";", 12131 getLLVMStyleWithColumns(30)); 12132 12133 FormatStyle Style = getLLVMStyle(); 12134 Style.AlwaysBreakBeforeMultilineStrings = true; 12135 Style.ColumnLimit = 0; 12136 verifyFormat("#import \"abc.h\"", Style); 12137 12138 // But 'import' might also be a regular C++ namespace. 12139 verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12140 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 12141 } 12142 12143 //===----------------------------------------------------------------------===// 12144 // Error recovery tests. 12145 //===----------------------------------------------------------------------===// 12146 12147 TEST_F(FormatTest, IncompleteParameterLists) { 12148 FormatStyle NoBinPacking = getLLVMStyle(); 12149 NoBinPacking.BinPackParameters = false; 12150 verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n" 12151 " double *min_x,\n" 12152 " double *max_x,\n" 12153 " double *min_y,\n" 12154 " double *max_y,\n" 12155 " double *min_z,\n" 12156 " double *max_z, ) {}", 12157 NoBinPacking); 12158 } 12159 12160 TEST_F(FormatTest, IncorrectCodeTrailingStuff) { 12161 verifyFormat("void f() { return; }\n42"); 12162 verifyFormat("void f() {\n" 12163 " if (0)\n" 12164 " return;\n" 12165 "}\n" 12166 "42"); 12167 verifyFormat("void f() { return }\n42"); 12168 verifyFormat("void f() {\n" 12169 " if (0)\n" 12170 " return\n" 12171 "}\n" 12172 "42"); 12173 } 12174 12175 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) { 12176 EXPECT_EQ("void f() { return }", format("void f ( ) { return }")); 12177 EXPECT_EQ("void f() {\n" 12178 " if (a)\n" 12179 " return\n" 12180 "}", 12181 format("void f ( ) { if ( a ) return }")); 12182 EXPECT_EQ("namespace N {\n" 12183 "void f()\n" 12184 "}", 12185 format("namespace N { void f() }")); 12186 EXPECT_EQ("namespace N {\n" 12187 "void f() {}\n" 12188 "void g()\n" 12189 "} // namespace N", 12190 format("namespace N { void f( ) { } void g( ) }")); 12191 } 12192 12193 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) { 12194 verifyFormat("int aaaaaaaa =\n" 12195 " // Overlylongcomment\n" 12196 " b;", 12197 getLLVMStyleWithColumns(20)); 12198 verifyFormat("function(\n" 12199 " ShortArgument,\n" 12200 " LoooooooooooongArgument);\n", 12201 getLLVMStyleWithColumns(20)); 12202 } 12203 12204 TEST_F(FormatTest, IncorrectAccessSpecifier) { 12205 verifyFormat("public:"); 12206 verifyFormat("class A {\n" 12207 "public\n" 12208 " void f() {}\n" 12209 "};"); 12210 verifyFormat("public\n" 12211 "int qwerty;"); 12212 verifyFormat("public\n" 12213 "B {}"); 12214 verifyFormat("public\n" 12215 "{}"); 12216 verifyFormat("public\n" 12217 "B { int x; }"); 12218 } 12219 12220 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) { 12221 verifyFormat("{"); 12222 verifyFormat("#})"); 12223 verifyNoCrash("(/**/[:!] ?[)."); 12224 } 12225 12226 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) { 12227 // Found by oss-fuzz: 12228 // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212 12229 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp); 12230 Style.ColumnLimit = 60; 12231 verifyNoCrash( 12232 "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20" 12233 "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20" 12234 "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a", 12235 Style); 12236 } 12237 12238 TEST_F(FormatTest, IncorrectCodeDoNoWhile) { 12239 verifyFormat("do {\n}"); 12240 verifyFormat("do {\n}\n" 12241 "f();"); 12242 verifyFormat("do {\n}\n" 12243 "wheeee(fun);"); 12244 verifyFormat("do {\n" 12245 " f();\n" 12246 "}"); 12247 } 12248 12249 TEST_F(FormatTest, IncorrectCodeMissingParens) { 12250 verifyFormat("if {\n foo;\n foo();\n}"); 12251 verifyFormat("switch {\n foo;\n foo();\n}"); 12252 verifyIncompleteFormat("for {\n foo;\n foo();\n}"); 12253 verifyIncompleteFormat("ERROR: for target;"); 12254 verifyFormat("while {\n foo;\n foo();\n}"); 12255 verifyFormat("do {\n foo;\n foo();\n} while;"); 12256 } 12257 12258 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) { 12259 verifyIncompleteFormat("namespace {\n" 12260 "class Foo { Foo (\n" 12261 "};\n" 12262 "} // namespace"); 12263 } 12264 12265 TEST_F(FormatTest, IncorrectCodeErrorDetection) { 12266 EXPECT_EQ("{\n {}\n", format("{\n{\n}\n")); 12267 EXPECT_EQ("{\n {}\n", format("{\n {\n}\n")); 12268 EXPECT_EQ("{\n {}\n", format("{\n {\n }\n")); 12269 EXPECT_EQ("{\n {}\n}\n}\n", format("{\n {\n }\n }\n}\n")); 12270 12271 EXPECT_EQ("{\n" 12272 " {\n" 12273 " breakme(\n" 12274 " qwe);\n" 12275 " }\n", 12276 format("{\n" 12277 " {\n" 12278 " breakme(qwe);\n" 12279 "}\n", 12280 getLLVMStyleWithColumns(10))); 12281 } 12282 12283 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) { 12284 verifyFormat("int x = {\n" 12285 " avariable,\n" 12286 " b(alongervariable)};", 12287 getLLVMStyleWithColumns(25)); 12288 } 12289 12290 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) { 12291 verifyFormat("return (a)(b){1, 2, 3};"); 12292 } 12293 12294 TEST_F(FormatTest, LayoutCxx11BraceInitializers) { 12295 verifyFormat("vector<int> x{1, 2, 3, 4};"); 12296 verifyFormat("vector<int> x{\n" 12297 " 1,\n" 12298 " 2,\n" 12299 " 3,\n" 12300 " 4,\n" 12301 "};"); 12302 verifyFormat("vector<T> x{{}, {}, {}, {}};"); 12303 verifyFormat("f({1, 2});"); 12304 verifyFormat("auto v = Foo{-1};"); 12305 verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});"); 12306 verifyFormat("Class::Class : member{1, 2, 3} {}"); 12307 verifyFormat("new vector<int>{1, 2, 3};"); 12308 verifyFormat("new int[3]{1, 2, 3};"); 12309 verifyFormat("new int{1};"); 12310 verifyFormat("return {arg1, arg2};"); 12311 verifyFormat("return {arg1, SomeType{parameter}};"); 12312 verifyFormat("int count = set<int>{f(), g(), h()}.size();"); 12313 verifyFormat("new T{arg1, arg2};"); 12314 verifyFormat("f(MyMap[{composite, key}]);"); 12315 verifyFormat("class Class {\n" 12316 " T member = {arg1, arg2};\n" 12317 "};"); 12318 verifyFormat("vector<int> foo = {::SomeGlobalFunction()};"); 12319 verifyFormat("const struct A a = {.a = 1, .b = 2};"); 12320 verifyFormat("const struct A a = {[0] = 1, [1] = 2};"); 12321 verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");"); 12322 verifyFormat("int a = std::is_integral<int>{} + 0;"); 12323 12324 verifyFormat("int foo(int i) { return fo1{}(i); }"); 12325 verifyFormat("int foo(int i) { return fo1{}(i); }"); 12326 verifyFormat("auto i = decltype(x){};"); 12327 verifyFormat("auto i = typeof(x){};"); 12328 verifyFormat("auto i = _Atomic(x){};"); 12329 verifyFormat("std::vector<int> v = {1, 0 /* comment */};"); 12330 verifyFormat("Node n{1, Node{1000}, //\n" 12331 " 2};"); 12332 verifyFormat("Aaaa aaaaaaa{\n" 12333 " {\n" 12334 " aaaa,\n" 12335 " },\n" 12336 "};"); 12337 verifyFormat("class C : public D {\n" 12338 " SomeClass SC{2};\n" 12339 "};"); 12340 verifyFormat("class C : public A {\n" 12341 " class D : public B {\n" 12342 " void f() { int i{2}; }\n" 12343 " };\n" 12344 "};"); 12345 verifyFormat("#define A {a, a},"); 12346 // Don't confuse braced list initializers with compound statements. 12347 verifyFormat( 12348 "class A {\n" 12349 " A() : a{} {}\n" 12350 " A(int b) : b(b) {}\n" 12351 " A(int a, int b) : a(a), bs{{bs...}} { f(); }\n" 12352 " int a, b;\n" 12353 " explicit Expr(const Scalar<Result> &x) : u{Constant<Result>{x}} {}\n" 12354 " explicit Expr(Scalar<Result> &&x) : u{Constant<Result>{std::move(x)}} " 12355 "{}\n" 12356 "};"); 12357 12358 // Avoid breaking between equal sign and opening brace 12359 FormatStyle AvoidBreakingFirstArgument = getLLVMStyle(); 12360 AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200; 12361 verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n" 12362 " {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n" 12363 " {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n" 12364 " {\"ccccccccccccccccccccc\", 2}};", 12365 AvoidBreakingFirstArgument); 12366 12367 // Binpacking only if there is no trailing comma 12368 verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n" 12369 " cccccccccc, dddddddddd};", 12370 getLLVMStyleWithColumns(50)); 12371 verifyFormat("const Aaaaaa aaaaa = {\n" 12372 " aaaaaaaaaaa,\n" 12373 " bbbbbbbbbbb,\n" 12374 " ccccccccccc,\n" 12375 " ddddddddddd,\n" 12376 "};", 12377 getLLVMStyleWithColumns(50)); 12378 12379 // Cases where distinguising braced lists and blocks is hard. 12380 verifyFormat("vector<int> v{12} GUARDED_BY(mutex);"); 12381 verifyFormat("void f() {\n" 12382 " return; // comment\n" 12383 "}\n" 12384 "SomeType t;"); 12385 verifyFormat("void f() {\n" 12386 " if (a) {\n" 12387 " f();\n" 12388 " }\n" 12389 "}\n" 12390 "SomeType t;"); 12391 12392 // In combination with BinPackArguments = false. 12393 FormatStyle NoBinPacking = getLLVMStyle(); 12394 NoBinPacking.BinPackArguments = false; 12395 verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n" 12396 " bbbbb,\n" 12397 " ccccc,\n" 12398 " ddddd,\n" 12399 " eeeee,\n" 12400 " ffffff,\n" 12401 " ggggg,\n" 12402 " hhhhhh,\n" 12403 " iiiiii,\n" 12404 " jjjjjj,\n" 12405 " kkkkkk};", 12406 NoBinPacking); 12407 verifyFormat("const Aaaaaa aaaaa = {\n" 12408 " aaaaa,\n" 12409 " bbbbb,\n" 12410 " ccccc,\n" 12411 " ddddd,\n" 12412 " eeeee,\n" 12413 " ffffff,\n" 12414 " ggggg,\n" 12415 " hhhhhh,\n" 12416 " iiiiii,\n" 12417 " jjjjjj,\n" 12418 " kkkkkk,\n" 12419 "};", 12420 NoBinPacking); 12421 verifyFormat( 12422 "const Aaaaaa aaaaa = {\n" 12423 " aaaaa, bbbbb, ccccc, ddddd, eeeee, ffffff, ggggg, hhhhhh,\n" 12424 " iiiiii, jjjjjj, kkkkkk, aaaaa, bbbbb, ccccc, ddddd, eeeee,\n" 12425 " ffffff, ggggg, hhhhhh, iiiiii, jjjjjj, kkkkkk,\n" 12426 "};", 12427 NoBinPacking); 12428 12429 NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 12430 EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n" 12431 " CDDDP83848_BMCR_REGISTER,\n" 12432 " CDDDP83848_BMSR_REGISTER,\n" 12433 " CDDDP83848_RBR_REGISTER};", 12434 format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n" 12435 " CDDDP83848_BMSR_REGISTER,\n" 12436 " CDDDP83848_RBR_REGISTER};", 12437 NoBinPacking)); 12438 12439 // FIXME: The alignment of these trailing comments might be bad. Then again, 12440 // this might be utterly useless in real code. 12441 verifyFormat("Constructor::Constructor()\n" 12442 " : some_value{ //\n" 12443 " aaaaaaa, //\n" 12444 " bbbbbbb} {}"); 12445 12446 // In braced lists, the first comment is always assumed to belong to the 12447 // first element. Thus, it can be moved to the next or previous line as 12448 // appropriate. 12449 EXPECT_EQ("function({// First element:\n" 12450 " 1,\n" 12451 " // Second element:\n" 12452 " 2});", 12453 format("function({\n" 12454 " // First element:\n" 12455 " 1,\n" 12456 " // Second element:\n" 12457 " 2});")); 12458 EXPECT_EQ("std::vector<int> MyNumbers{\n" 12459 " // First element:\n" 12460 " 1,\n" 12461 " // Second element:\n" 12462 " 2};", 12463 format("std::vector<int> MyNumbers{// First element:\n" 12464 " 1,\n" 12465 " // Second element:\n" 12466 " 2};", 12467 getLLVMStyleWithColumns(30))); 12468 // A trailing comma should still lead to an enforced line break and no 12469 // binpacking. 12470 EXPECT_EQ("vector<int> SomeVector = {\n" 12471 " // aaa\n" 12472 " 1,\n" 12473 " 2,\n" 12474 "};", 12475 format("vector<int> SomeVector = { // aaa\n" 12476 " 1, 2, };")); 12477 12478 // C++11 brace initializer list l-braces should not be treated any differently 12479 // when breaking before lambda bodies is enabled 12480 FormatStyle BreakBeforeLambdaBody = getLLVMStyle(); 12481 BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 12482 BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 12483 BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true; 12484 verifyFormat( 12485 "std::runtime_error{\n" 12486 " \"Long string which will force a break onto the next line...\"};", 12487 BreakBeforeLambdaBody); 12488 12489 FormatStyle ExtraSpaces = getLLVMStyle(); 12490 ExtraSpaces.Cpp11BracedListStyle = false; 12491 ExtraSpaces.ColumnLimit = 75; 12492 verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces); 12493 verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces); 12494 verifyFormat("f({ 1, 2 });", ExtraSpaces); 12495 verifyFormat("auto v = Foo{ 1 };", ExtraSpaces); 12496 verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces); 12497 verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces); 12498 verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces); 12499 verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces); 12500 verifyFormat("return { arg1, arg2 };", ExtraSpaces); 12501 verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces); 12502 verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces); 12503 verifyFormat("new T{ arg1, arg2 };", ExtraSpaces); 12504 verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces); 12505 verifyFormat("class Class {\n" 12506 " T member = { arg1, arg2 };\n" 12507 "};", 12508 ExtraSpaces); 12509 verifyFormat( 12510 "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12511 " aaaaaaaaaaaaaaaaaaaa, aaaaa }\n" 12512 " : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 12513 " bbbbbbbbbbbbbbbbbbbb, bbbbb };", 12514 ExtraSpaces); 12515 verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces); 12516 verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });", 12517 ExtraSpaces); 12518 verifyFormat( 12519 "someFunction(OtherParam,\n" 12520 " BracedList{ // comment 1 (Forcing interesting break)\n" 12521 " param1, param2,\n" 12522 " // comment 2\n" 12523 " param3, param4 });", 12524 ExtraSpaces); 12525 verifyFormat( 12526 "std::this_thread::sleep_for(\n" 12527 " std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);", 12528 ExtraSpaces); 12529 verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n" 12530 " aaaaaaa,\n" 12531 " aaaaaaaaaa,\n" 12532 " aaaaa,\n" 12533 " aaaaaaaaaaaaaaa,\n" 12534 " aaa,\n" 12535 " aaaaaaaaaa,\n" 12536 " a,\n" 12537 " aaaaaaaaaaaaaaaaaaaaa,\n" 12538 " aaaaaaaaaaaa,\n" 12539 " aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n" 12540 " aaaaaaa,\n" 12541 " a};"); 12542 verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces); 12543 verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces); 12544 verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces); 12545 12546 // Avoid breaking between initializer/equal sign and opening brace 12547 ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200; 12548 verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n" 12549 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n" 12550 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n" 12551 " { \"ccccccccccccccccccccc\", 2 }\n" 12552 "};", 12553 ExtraSpaces); 12554 verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n" 12555 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n" 12556 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n" 12557 " { \"ccccccccccccccccccccc\", 2 }\n" 12558 "};", 12559 ExtraSpaces); 12560 12561 FormatStyle SpaceBeforeBrace = getLLVMStyle(); 12562 SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true; 12563 verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace); 12564 verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace); 12565 12566 FormatStyle SpaceBetweenBraces = getLLVMStyle(); 12567 SpaceBetweenBraces.SpacesInAngles = FormatStyle::SIAS_Always; 12568 SpaceBetweenBraces.SpacesInParentheses = true; 12569 SpaceBetweenBraces.SpacesInSquareBrackets = true; 12570 verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces); 12571 verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces); 12572 verifyFormat("vector< int > x{ // comment 1\n" 12573 " 1, 2, 3, 4 };", 12574 SpaceBetweenBraces); 12575 SpaceBetweenBraces.ColumnLimit = 20; 12576 EXPECT_EQ("vector< int > x{\n" 12577 " 1, 2, 3, 4 };", 12578 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces)); 12579 SpaceBetweenBraces.ColumnLimit = 24; 12580 EXPECT_EQ("vector< int > x{ 1, 2,\n" 12581 " 3, 4 };", 12582 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces)); 12583 EXPECT_EQ("vector< int > x{\n" 12584 " 1,\n" 12585 " 2,\n" 12586 " 3,\n" 12587 " 4,\n" 12588 "};", 12589 format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces)); 12590 verifyFormat("vector< int > x{};", SpaceBetweenBraces); 12591 SpaceBetweenBraces.SpaceInEmptyParentheses = true; 12592 verifyFormat("vector< int > x{ };", SpaceBetweenBraces); 12593 } 12594 12595 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) { 12596 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12597 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12598 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12599 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12600 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12601 " 1, 22, 333, 4444, 55555, 666666, 7777777};"); 12602 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n" 12603 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12604 " 1, 22, 333, 4444, 55555, //\n" 12605 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12606 " 1, 22, 333, 4444, 55555, 666666, 7777777};"); 12607 verifyFormat( 12608 "vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12609 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12610 " 1, 22, 333, 4444, 55555, 666666, // comment\n" 12611 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12612 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12613 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12614 " 7777777};"); 12615 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12616 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12617 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12618 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12619 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12620 " // Separating comment.\n" 12621 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12622 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12623 " // Leading comment\n" 12624 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12625 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12626 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12627 " 1, 1, 1, 1};", 12628 getLLVMStyleWithColumns(39)); 12629 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12630 " 1, 1, 1, 1};", 12631 getLLVMStyleWithColumns(38)); 12632 verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n" 12633 " 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};", 12634 getLLVMStyleWithColumns(43)); 12635 verifyFormat( 12636 "static unsigned SomeValues[10][3] = {\n" 12637 " {1, 4, 0}, {4, 9, 0}, {4, 5, 9}, {8, 5, 4}, {1, 8, 4},\n" 12638 " {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};"); 12639 verifyFormat("static auto fields = new vector<string>{\n" 12640 " \"aaaaaaaaaaaaa\",\n" 12641 " \"aaaaaaaaaaaaa\",\n" 12642 " \"aaaaaaaaaaaa\",\n" 12643 " \"aaaaaaaaaaaaaa\",\n" 12644 " \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n" 12645 " \"aaaaaaaaaaaa\",\n" 12646 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n" 12647 "};"); 12648 verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};"); 12649 verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n" 12650 " 2, bbbbbbbbbbbbbbbbbbbbbb,\n" 12651 " 3, cccccccccccccccccccccc};", 12652 getLLVMStyleWithColumns(60)); 12653 12654 // Trailing commas. 12655 verifyFormat("vector<int> x = {\n" 12656 " 1, 1, 1, 1, 1, 1, 1, 1,\n" 12657 "};", 12658 getLLVMStyleWithColumns(39)); 12659 verifyFormat("vector<int> x = {\n" 12660 " 1, 1, 1, 1, 1, 1, 1, 1, //\n" 12661 "};", 12662 getLLVMStyleWithColumns(39)); 12663 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12664 " 1, 1, 1, 1,\n" 12665 " /**/ /**/};", 12666 getLLVMStyleWithColumns(39)); 12667 12668 // Trailing comment in the first line. 12669 verifyFormat("vector<int> iiiiiiiiiiiiiii = { //\n" 12670 " 1111111111, 2222222222, 33333333333, 4444444444, //\n" 12671 " 111111111, 222222222, 3333333333, 444444444, //\n" 12672 " 11111111, 22222222, 333333333, 44444444};"); 12673 // Trailing comment in the last line. 12674 verifyFormat("int aaaaa[] = {\n" 12675 " 1, 2, 3, // comment\n" 12676 " 4, 5, 6 // comment\n" 12677 "};"); 12678 12679 // With nested lists, we should either format one item per line or all nested 12680 // lists one on line. 12681 // FIXME: For some nested lists, we can do better. 12682 verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n" 12683 " {aaaaaaaaaaaaaaaaaaa},\n" 12684 " {aaaaaaaaaaaaaaaaaaaaa},\n" 12685 " {aaaaaaaaaaaaaaaaa}};", 12686 getLLVMStyleWithColumns(60)); 12687 verifyFormat( 12688 "SomeStruct my_struct_array = {\n" 12689 " {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n" 12690 " aaaaaaaaaaaaa, aaaaaaa, aaa},\n" 12691 " {aaa, aaa},\n" 12692 " {aaa, aaa},\n" 12693 " {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n" 12694 " {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n" 12695 " aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};"); 12696 12697 // No column layout should be used here. 12698 verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n" 12699 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};"); 12700 12701 verifyNoCrash("a<,"); 12702 12703 // No braced initializer here. 12704 verifyFormat("void f() {\n" 12705 " struct Dummy {};\n" 12706 " f(v);\n" 12707 "}"); 12708 12709 // Long lists should be formatted in columns even if they are nested. 12710 verifyFormat( 12711 "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12712 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12713 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12714 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12715 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12716 " 1, 22, 333, 4444, 55555, 666666, 7777777});"); 12717 12718 // Allow "single-column" layout even if that violates the column limit. There 12719 // isn't going to be a better way. 12720 verifyFormat("std::vector<int> a = {\n" 12721 " aaaaaaaa,\n" 12722 " aaaaaaaa,\n" 12723 " aaaaaaaa,\n" 12724 " aaaaaaaa,\n" 12725 " aaaaaaaaaa,\n" 12726 " aaaaaaaa,\n" 12727 " aaaaaaaaaaaaaaaaaaaaaaaaaaa};", 12728 getLLVMStyleWithColumns(30)); 12729 verifyFormat("vector<int> aaaa = {\n" 12730 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12731 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12732 " aaaaaa.aaaaaaa,\n" 12733 " aaaaaa.aaaaaaa,\n" 12734 " aaaaaa.aaaaaaa,\n" 12735 " aaaaaa.aaaaaaa,\n" 12736 "};"); 12737 12738 // Don't create hanging lists. 12739 verifyFormat("someFunction(Param, {List1, List2,\n" 12740 " List3});", 12741 getLLVMStyleWithColumns(35)); 12742 verifyFormat("someFunction(Param, Param,\n" 12743 " {List1, List2,\n" 12744 " List3});", 12745 getLLVMStyleWithColumns(35)); 12746 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n" 12747 " aaaaaaaaaaaaaaaaaaaaaaa);"); 12748 } 12749 12750 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) { 12751 FormatStyle DoNotMerge = getLLVMStyle(); 12752 DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12753 12754 verifyFormat("void f() { return 42; }"); 12755 verifyFormat("void f() {\n" 12756 " return 42;\n" 12757 "}", 12758 DoNotMerge); 12759 verifyFormat("void f() {\n" 12760 " // Comment\n" 12761 "}"); 12762 verifyFormat("{\n" 12763 "#error {\n" 12764 " int a;\n" 12765 "}"); 12766 verifyFormat("{\n" 12767 " int a;\n" 12768 "#error {\n" 12769 "}"); 12770 verifyFormat("void f() {} // comment"); 12771 verifyFormat("void f() { int a; } // comment"); 12772 verifyFormat("void f() {\n" 12773 "} // comment", 12774 DoNotMerge); 12775 verifyFormat("void f() {\n" 12776 " int a;\n" 12777 "} // comment", 12778 DoNotMerge); 12779 verifyFormat("void f() {\n" 12780 "} // comment", 12781 getLLVMStyleWithColumns(15)); 12782 12783 verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23)); 12784 verifyFormat("void f() {\n return 42;\n}", getLLVMStyleWithColumns(22)); 12785 12786 verifyFormat("void f() {}", getLLVMStyleWithColumns(11)); 12787 verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10)); 12788 verifyFormat("class C {\n" 12789 " C()\n" 12790 " : iiiiiiii(nullptr),\n" 12791 " kkkkkkk(nullptr),\n" 12792 " mmmmmmm(nullptr),\n" 12793 " nnnnnnn(nullptr) {}\n" 12794 "};", 12795 getGoogleStyle()); 12796 12797 FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0); 12798 EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit)); 12799 EXPECT_EQ("class C {\n" 12800 " A() : b(0) {}\n" 12801 "};", 12802 format("class C{A():b(0){}};", NoColumnLimit)); 12803 EXPECT_EQ("A()\n" 12804 " : b(0) {\n" 12805 "}", 12806 format("A()\n:b(0)\n{\n}", NoColumnLimit)); 12807 12808 FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit; 12809 DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine = 12810 FormatStyle::SFS_None; 12811 EXPECT_EQ("A()\n" 12812 " : b(0) {\n" 12813 "}", 12814 format("A():b(0){}", DoNotMergeNoColumnLimit)); 12815 EXPECT_EQ("A()\n" 12816 " : b(0) {\n" 12817 "}", 12818 format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit)); 12819 12820 verifyFormat("#define A \\\n" 12821 " void f() { \\\n" 12822 " int i; \\\n" 12823 " }", 12824 getLLVMStyleWithColumns(20)); 12825 verifyFormat("#define A \\\n" 12826 " void f() { int i; }", 12827 getLLVMStyleWithColumns(21)); 12828 verifyFormat("#define A \\\n" 12829 " void f() { \\\n" 12830 " int i; \\\n" 12831 " } \\\n" 12832 " int j;", 12833 getLLVMStyleWithColumns(22)); 12834 verifyFormat("#define A \\\n" 12835 " void f() { int i; } \\\n" 12836 " int j;", 12837 getLLVMStyleWithColumns(23)); 12838 } 12839 12840 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) { 12841 FormatStyle MergeEmptyOnly = getLLVMStyle(); 12842 MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 12843 verifyFormat("class C {\n" 12844 " int f() {}\n" 12845 "};", 12846 MergeEmptyOnly); 12847 verifyFormat("class C {\n" 12848 " int f() {\n" 12849 " return 42;\n" 12850 " }\n" 12851 "};", 12852 MergeEmptyOnly); 12853 verifyFormat("int f() {}", MergeEmptyOnly); 12854 verifyFormat("int f() {\n" 12855 " return 42;\n" 12856 "}", 12857 MergeEmptyOnly); 12858 12859 // Also verify behavior when BraceWrapping.AfterFunction = true 12860 MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12861 MergeEmptyOnly.BraceWrapping.AfterFunction = true; 12862 verifyFormat("int f() {}", MergeEmptyOnly); 12863 verifyFormat("class C {\n" 12864 " int f() {}\n" 12865 "};", 12866 MergeEmptyOnly); 12867 } 12868 12869 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) { 12870 FormatStyle MergeInlineOnly = getLLVMStyle(); 12871 MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 12872 verifyFormat("class C {\n" 12873 " int f() { return 42; }\n" 12874 "};", 12875 MergeInlineOnly); 12876 verifyFormat("int f() {\n" 12877 " return 42;\n" 12878 "}", 12879 MergeInlineOnly); 12880 12881 // SFS_Inline implies SFS_Empty 12882 verifyFormat("class C {\n" 12883 " int f() {}\n" 12884 "};", 12885 MergeInlineOnly); 12886 verifyFormat("int f() {}", MergeInlineOnly); 12887 // https://llvm.org/PR54147 12888 verifyFormat("auto lambda = []() {\n" 12889 " // comment\n" 12890 " f();\n" 12891 " g();\n" 12892 "};", 12893 MergeInlineOnly); 12894 12895 verifyFormat("class C {\n" 12896 "#ifdef A\n" 12897 " int f() { return 42; }\n" 12898 "#endif\n" 12899 "};", 12900 MergeInlineOnly); 12901 12902 verifyFormat("struct S {\n" 12903 "// comment\n" 12904 "#ifdef FOO\n" 12905 " int foo() { bar(); }\n" 12906 "#endif\n" 12907 "};", 12908 MergeInlineOnly); 12909 12910 // Also verify behavior when BraceWrapping.AfterFunction = true 12911 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12912 MergeInlineOnly.BraceWrapping.AfterFunction = true; 12913 verifyFormat("class C {\n" 12914 " int f() { return 42; }\n" 12915 "};", 12916 MergeInlineOnly); 12917 verifyFormat("int f()\n" 12918 "{\n" 12919 " return 42;\n" 12920 "}", 12921 MergeInlineOnly); 12922 12923 // SFS_Inline implies SFS_Empty 12924 verifyFormat("int f() {}", MergeInlineOnly); 12925 verifyFormat("class C {\n" 12926 " int f() {}\n" 12927 "};", 12928 MergeInlineOnly); 12929 12930 MergeInlineOnly.BraceWrapping.AfterClass = true; 12931 MergeInlineOnly.BraceWrapping.AfterStruct = true; 12932 verifyFormat("class C\n" 12933 "{\n" 12934 " int f() { return 42; }\n" 12935 "};", 12936 MergeInlineOnly); 12937 verifyFormat("struct C\n" 12938 "{\n" 12939 " int f() { return 42; }\n" 12940 "};", 12941 MergeInlineOnly); 12942 verifyFormat("int f()\n" 12943 "{\n" 12944 " return 42;\n" 12945 "}", 12946 MergeInlineOnly); 12947 verifyFormat("int f() {}", MergeInlineOnly); 12948 verifyFormat("class C\n" 12949 "{\n" 12950 " int f() { return 42; }\n" 12951 "};", 12952 MergeInlineOnly); 12953 verifyFormat("struct C\n" 12954 "{\n" 12955 " int f() { return 42; }\n" 12956 "};", 12957 MergeInlineOnly); 12958 verifyFormat("struct C\n" 12959 "// comment\n" 12960 "/* comment */\n" 12961 "// comment\n" 12962 "{\n" 12963 " int f() { return 42; }\n" 12964 "};", 12965 MergeInlineOnly); 12966 verifyFormat("/* comment */ struct C\n" 12967 "{\n" 12968 " int f() { return 42; }\n" 12969 "};", 12970 MergeInlineOnly); 12971 } 12972 12973 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) { 12974 FormatStyle MergeInlineOnly = getLLVMStyle(); 12975 MergeInlineOnly.AllowShortFunctionsOnASingleLine = 12976 FormatStyle::SFS_InlineOnly; 12977 verifyFormat("class C {\n" 12978 " int f() { return 42; }\n" 12979 "};", 12980 MergeInlineOnly); 12981 verifyFormat("int f() {\n" 12982 " return 42;\n" 12983 "}", 12984 MergeInlineOnly); 12985 12986 // SFS_InlineOnly does not imply SFS_Empty 12987 verifyFormat("class C {\n" 12988 " int f() {}\n" 12989 "};", 12990 MergeInlineOnly); 12991 verifyFormat("int f() {\n" 12992 "}", 12993 MergeInlineOnly); 12994 12995 // Also verify behavior when BraceWrapping.AfterFunction = true 12996 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12997 MergeInlineOnly.BraceWrapping.AfterFunction = true; 12998 verifyFormat("class C {\n" 12999 " int f() { return 42; }\n" 13000 "};", 13001 MergeInlineOnly); 13002 verifyFormat("int f()\n" 13003 "{\n" 13004 " return 42;\n" 13005 "}", 13006 MergeInlineOnly); 13007 13008 // SFS_InlineOnly does not imply SFS_Empty 13009 verifyFormat("int f()\n" 13010 "{\n" 13011 "}", 13012 MergeInlineOnly); 13013 verifyFormat("class C {\n" 13014 " int f() {}\n" 13015 "};", 13016 MergeInlineOnly); 13017 } 13018 13019 TEST_F(FormatTest, SplitEmptyFunction) { 13020 FormatStyle Style = getLLVMStyleWithColumns(40); 13021 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 13022 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13023 Style.BraceWrapping.AfterFunction = true; 13024 Style.BraceWrapping.SplitEmptyFunction = false; 13025 13026 verifyFormat("int f()\n" 13027 "{}", 13028 Style); 13029 verifyFormat("int f()\n" 13030 "{\n" 13031 " return 42;\n" 13032 "}", 13033 Style); 13034 verifyFormat("int f()\n" 13035 "{\n" 13036 " // some comment\n" 13037 "}", 13038 Style); 13039 13040 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 13041 verifyFormat("int f() {}", Style); 13042 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 13043 "{}", 13044 Style); 13045 verifyFormat("int f()\n" 13046 "{\n" 13047 " return 0;\n" 13048 "}", 13049 Style); 13050 13051 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 13052 verifyFormat("class Foo {\n" 13053 " int f() {}\n" 13054 "};\n", 13055 Style); 13056 verifyFormat("class Foo {\n" 13057 " int f() { return 0; }\n" 13058 "};\n", 13059 Style); 13060 verifyFormat("class Foo {\n" 13061 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 13062 " {}\n" 13063 "};\n", 13064 Style); 13065 verifyFormat("class Foo {\n" 13066 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 13067 " {\n" 13068 " return 0;\n" 13069 " }\n" 13070 "};\n", 13071 Style); 13072 13073 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 13074 verifyFormat("int f() {}", Style); 13075 verifyFormat("int f() { return 0; }", Style); 13076 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 13077 "{}", 13078 Style); 13079 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 13080 "{\n" 13081 " return 0;\n" 13082 "}", 13083 Style); 13084 } 13085 13086 TEST_F(FormatTest, SplitEmptyFunctionButNotRecord) { 13087 FormatStyle Style = getLLVMStyleWithColumns(40); 13088 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 13089 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13090 Style.BraceWrapping.AfterFunction = true; 13091 Style.BraceWrapping.SplitEmptyFunction = true; 13092 Style.BraceWrapping.SplitEmptyRecord = false; 13093 13094 verifyFormat("class C {};", Style); 13095 verifyFormat("struct C {};", Style); 13096 verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 13097 " int bbbbbbbbbbbbbbbbbbbbbbbb)\n" 13098 "{\n" 13099 "}", 13100 Style); 13101 verifyFormat("class C {\n" 13102 " C()\n" 13103 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa(),\n" 13104 " bbbbbbbbbbbbbbbbbbb()\n" 13105 " {\n" 13106 " }\n" 13107 " void\n" 13108 " m(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 13109 " int bbbbbbbbbbbbbbbbbbbbbbbb)\n" 13110 " {\n" 13111 " }\n" 13112 "};", 13113 Style); 13114 } 13115 13116 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) { 13117 FormatStyle Style = getLLVMStyle(); 13118 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 13119 verifyFormat("#ifdef A\n" 13120 "int f() {}\n" 13121 "#else\n" 13122 "int g() {}\n" 13123 "#endif", 13124 Style); 13125 } 13126 13127 TEST_F(FormatTest, SplitEmptyClass) { 13128 FormatStyle Style = getLLVMStyle(); 13129 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13130 Style.BraceWrapping.AfterClass = true; 13131 Style.BraceWrapping.SplitEmptyRecord = false; 13132 13133 verifyFormat("class Foo\n" 13134 "{};", 13135 Style); 13136 verifyFormat("/* something */ class Foo\n" 13137 "{};", 13138 Style); 13139 verifyFormat("template <typename X> class Foo\n" 13140 "{};", 13141 Style); 13142 verifyFormat("class Foo\n" 13143 "{\n" 13144 " Foo();\n" 13145 "};", 13146 Style); 13147 verifyFormat("typedef class Foo\n" 13148 "{\n" 13149 "} Foo_t;", 13150 Style); 13151 13152 Style.BraceWrapping.SplitEmptyRecord = true; 13153 Style.BraceWrapping.AfterStruct = true; 13154 verifyFormat("class rep\n" 13155 "{\n" 13156 "};", 13157 Style); 13158 verifyFormat("struct rep\n" 13159 "{\n" 13160 "};", 13161 Style); 13162 verifyFormat("template <typename T> class rep\n" 13163 "{\n" 13164 "};", 13165 Style); 13166 verifyFormat("template <typename T> struct rep\n" 13167 "{\n" 13168 "};", 13169 Style); 13170 verifyFormat("class rep\n" 13171 "{\n" 13172 " int x;\n" 13173 "};", 13174 Style); 13175 verifyFormat("struct rep\n" 13176 "{\n" 13177 " int x;\n" 13178 "};", 13179 Style); 13180 verifyFormat("template <typename T> class rep\n" 13181 "{\n" 13182 " int x;\n" 13183 "};", 13184 Style); 13185 verifyFormat("template <typename T> struct rep\n" 13186 "{\n" 13187 " int x;\n" 13188 "};", 13189 Style); 13190 verifyFormat("template <typename T> class rep // Foo\n" 13191 "{\n" 13192 " int x;\n" 13193 "};", 13194 Style); 13195 verifyFormat("template <typename T> struct rep // Bar\n" 13196 "{\n" 13197 " int x;\n" 13198 "};", 13199 Style); 13200 13201 verifyFormat("template <typename T> class rep<T>\n" 13202 "{\n" 13203 " int x;\n" 13204 "};", 13205 Style); 13206 13207 verifyFormat("template <typename T> class rep<std::complex<T>>\n" 13208 "{\n" 13209 " int x;\n" 13210 "};", 13211 Style); 13212 verifyFormat("template <typename T> class rep<std::complex<T>>\n" 13213 "{\n" 13214 "};", 13215 Style); 13216 13217 verifyFormat("#include \"stdint.h\"\n" 13218 "namespace rep {}", 13219 Style); 13220 verifyFormat("#include <stdint.h>\n" 13221 "namespace rep {}", 13222 Style); 13223 verifyFormat("#include <stdint.h>\n" 13224 "namespace rep {}", 13225 "#include <stdint.h>\n" 13226 "namespace rep {\n" 13227 "\n" 13228 "\n" 13229 "}", 13230 Style); 13231 } 13232 13233 TEST_F(FormatTest, SplitEmptyStruct) { 13234 FormatStyle Style = getLLVMStyle(); 13235 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13236 Style.BraceWrapping.AfterStruct = true; 13237 Style.BraceWrapping.SplitEmptyRecord = false; 13238 13239 verifyFormat("struct Foo\n" 13240 "{};", 13241 Style); 13242 verifyFormat("/* something */ struct Foo\n" 13243 "{};", 13244 Style); 13245 verifyFormat("template <typename X> struct Foo\n" 13246 "{};", 13247 Style); 13248 verifyFormat("struct Foo\n" 13249 "{\n" 13250 " Foo();\n" 13251 "};", 13252 Style); 13253 verifyFormat("typedef struct Foo\n" 13254 "{\n" 13255 "} Foo_t;", 13256 Style); 13257 // typedef struct Bar {} Bar_t; 13258 } 13259 13260 TEST_F(FormatTest, SplitEmptyUnion) { 13261 FormatStyle Style = getLLVMStyle(); 13262 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13263 Style.BraceWrapping.AfterUnion = true; 13264 Style.BraceWrapping.SplitEmptyRecord = false; 13265 13266 verifyFormat("union Foo\n" 13267 "{};", 13268 Style); 13269 verifyFormat("/* something */ union Foo\n" 13270 "{};", 13271 Style); 13272 verifyFormat("union Foo\n" 13273 "{\n" 13274 " A,\n" 13275 "};", 13276 Style); 13277 verifyFormat("typedef union Foo\n" 13278 "{\n" 13279 "} Foo_t;", 13280 Style); 13281 } 13282 13283 TEST_F(FormatTest, SplitEmptyNamespace) { 13284 FormatStyle Style = getLLVMStyle(); 13285 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13286 Style.BraceWrapping.AfterNamespace = true; 13287 Style.BraceWrapping.SplitEmptyNamespace = false; 13288 13289 verifyFormat("namespace Foo\n" 13290 "{};", 13291 Style); 13292 verifyFormat("/* something */ namespace Foo\n" 13293 "{};", 13294 Style); 13295 verifyFormat("inline namespace Foo\n" 13296 "{};", 13297 Style); 13298 verifyFormat("/* something */ inline namespace Foo\n" 13299 "{};", 13300 Style); 13301 verifyFormat("export namespace Foo\n" 13302 "{};", 13303 Style); 13304 verifyFormat("namespace Foo\n" 13305 "{\n" 13306 "void Bar();\n" 13307 "};", 13308 Style); 13309 } 13310 13311 TEST_F(FormatTest, NeverMergeShortRecords) { 13312 FormatStyle Style = getLLVMStyle(); 13313 13314 verifyFormat("class Foo {\n" 13315 " Foo();\n" 13316 "};", 13317 Style); 13318 verifyFormat("typedef class Foo {\n" 13319 " Foo();\n" 13320 "} Foo_t;", 13321 Style); 13322 verifyFormat("struct Foo {\n" 13323 " Foo();\n" 13324 "};", 13325 Style); 13326 verifyFormat("typedef struct Foo {\n" 13327 " Foo();\n" 13328 "} Foo_t;", 13329 Style); 13330 verifyFormat("union Foo {\n" 13331 " A,\n" 13332 "};", 13333 Style); 13334 verifyFormat("typedef union Foo {\n" 13335 " A,\n" 13336 "} Foo_t;", 13337 Style); 13338 verifyFormat("namespace Foo {\n" 13339 "void Bar();\n" 13340 "};", 13341 Style); 13342 13343 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13344 Style.BraceWrapping.AfterClass = true; 13345 Style.BraceWrapping.AfterStruct = true; 13346 Style.BraceWrapping.AfterUnion = true; 13347 Style.BraceWrapping.AfterNamespace = true; 13348 verifyFormat("class Foo\n" 13349 "{\n" 13350 " Foo();\n" 13351 "};", 13352 Style); 13353 verifyFormat("typedef class Foo\n" 13354 "{\n" 13355 " Foo();\n" 13356 "} Foo_t;", 13357 Style); 13358 verifyFormat("struct Foo\n" 13359 "{\n" 13360 " Foo();\n" 13361 "};", 13362 Style); 13363 verifyFormat("typedef struct Foo\n" 13364 "{\n" 13365 " Foo();\n" 13366 "} Foo_t;", 13367 Style); 13368 verifyFormat("union Foo\n" 13369 "{\n" 13370 " A,\n" 13371 "};", 13372 Style); 13373 verifyFormat("typedef union Foo\n" 13374 "{\n" 13375 " A,\n" 13376 "} Foo_t;", 13377 Style); 13378 verifyFormat("namespace Foo\n" 13379 "{\n" 13380 "void Bar();\n" 13381 "};", 13382 Style); 13383 } 13384 13385 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) { 13386 // Elaborate type variable declarations. 13387 verifyFormat("struct foo a = {bar};\nint n;"); 13388 verifyFormat("class foo a = {bar};\nint n;"); 13389 verifyFormat("union foo a = {bar};\nint n;"); 13390 13391 // Elaborate types inside function definitions. 13392 verifyFormat("struct foo f() {}\nint n;"); 13393 verifyFormat("class foo f() {}\nint n;"); 13394 verifyFormat("union foo f() {}\nint n;"); 13395 13396 // Templates. 13397 verifyFormat("template <class X> void f() {}\nint n;"); 13398 verifyFormat("template <struct X> void f() {}\nint n;"); 13399 verifyFormat("template <union X> void f() {}\nint n;"); 13400 13401 // Actual definitions... 13402 verifyFormat("struct {\n} n;"); 13403 verifyFormat( 13404 "template <template <class T, class Y>, class Z> class X {\n} n;"); 13405 verifyFormat("union Z {\n int n;\n} x;"); 13406 verifyFormat("class MACRO Z {\n} n;"); 13407 verifyFormat("class MACRO(X) Z {\n} n;"); 13408 verifyFormat("class __attribute__(X) Z {\n} n;"); 13409 verifyFormat("class __declspec(X) Z {\n} n;"); 13410 verifyFormat("class A##B##C {\n} n;"); 13411 verifyFormat("class alignas(16) Z {\n} n;"); 13412 verifyFormat("class MACRO(X) alignas(16) Z {\n} n;"); 13413 verifyFormat("class MACROA MACRO(X) Z {\n} n;"); 13414 13415 // Redefinition from nested context: 13416 verifyFormat("class A::B::C {\n} n;"); 13417 13418 // Template definitions. 13419 verifyFormat( 13420 "template <typename F>\n" 13421 "Matcher(const Matcher<F> &Other,\n" 13422 " typename enable_if_c<is_base_of<F, T>::value &&\n" 13423 " !is_same<F, T>::value>::type * = 0)\n" 13424 " : Implementation(new ImplicitCastMatcher<F>(Other)) {}"); 13425 13426 // FIXME: This is still incorrectly handled at the formatter side. 13427 verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};"); 13428 verifyFormat("int i = SomeFunction(a<b, a> b);"); 13429 13430 // FIXME: 13431 // This now gets parsed incorrectly as class definition. 13432 // verifyFormat("class A<int> f() {\n}\nint n;"); 13433 13434 // Elaborate types where incorrectly parsing the structural element would 13435 // break the indent. 13436 verifyFormat("if (true)\n" 13437 " class X x;\n" 13438 "else\n" 13439 " f();\n"); 13440 13441 // This is simply incomplete. Formatting is not important, but must not crash. 13442 verifyFormat("class A:"); 13443 } 13444 13445 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) { 13446 EXPECT_EQ("#error Leave all white!!!!! space* alone!\n", 13447 format("#error Leave all white!!!!! space* alone!\n")); 13448 EXPECT_EQ( 13449 "#warning Leave all white!!!!! space* alone!\n", 13450 format("#warning Leave all white!!!!! space* alone!\n")); 13451 EXPECT_EQ("#error 1", format(" # error 1")); 13452 EXPECT_EQ("#warning 1", format(" # warning 1")); 13453 } 13454 13455 TEST_F(FormatTest, FormatHashIfExpressions) { 13456 verifyFormat("#if AAAA && BBBB"); 13457 verifyFormat("#if (AAAA && BBBB)"); 13458 verifyFormat("#elif (AAAA && BBBB)"); 13459 // FIXME: Come up with a better indentation for #elif. 13460 verifyFormat( 13461 "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) && \\\n" 13462 " defined(BBBBBBBB)\n" 13463 "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) && \\\n" 13464 " defined(BBBBBBBB)\n" 13465 "#endif", 13466 getLLVMStyleWithColumns(65)); 13467 } 13468 13469 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) { 13470 FormatStyle AllowsMergedIf = getGoogleStyle(); 13471 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 13472 FormatStyle::SIS_WithoutElse; 13473 verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf); 13474 verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf); 13475 verifyFormat("if (true)\n#error E\n return 42;", AllowsMergedIf); 13476 EXPECT_EQ("if (true) return 42;", 13477 format("if (true)\nreturn 42;", AllowsMergedIf)); 13478 FormatStyle ShortMergedIf = AllowsMergedIf; 13479 ShortMergedIf.ColumnLimit = 25; 13480 verifyFormat("#define A \\\n" 13481 " if (true) return 42;", 13482 ShortMergedIf); 13483 verifyFormat("#define A \\\n" 13484 " f(); \\\n" 13485 " if (true)\n" 13486 "#define B", 13487 ShortMergedIf); 13488 verifyFormat("#define A \\\n" 13489 " f(); \\\n" 13490 " if (true)\n" 13491 "g();", 13492 ShortMergedIf); 13493 verifyFormat("{\n" 13494 "#ifdef A\n" 13495 " // Comment\n" 13496 " if (true) continue;\n" 13497 "#endif\n" 13498 " // Comment\n" 13499 " if (true) continue;\n" 13500 "}", 13501 ShortMergedIf); 13502 ShortMergedIf.ColumnLimit = 33; 13503 verifyFormat("#define A \\\n" 13504 " if constexpr (true) return 42;", 13505 ShortMergedIf); 13506 verifyFormat("#define A \\\n" 13507 " if CONSTEXPR (true) return 42;", 13508 ShortMergedIf); 13509 ShortMergedIf.ColumnLimit = 29; 13510 verifyFormat("#define A \\\n" 13511 " if (aaaaaaaaaa) return 1; \\\n" 13512 " return 2;", 13513 ShortMergedIf); 13514 ShortMergedIf.ColumnLimit = 28; 13515 verifyFormat("#define A \\\n" 13516 " if (aaaaaaaaaa) \\\n" 13517 " return 1; \\\n" 13518 " return 2;", 13519 ShortMergedIf); 13520 verifyFormat("#define A \\\n" 13521 " if constexpr (aaaaaaa) \\\n" 13522 " return 1; \\\n" 13523 " return 2;", 13524 ShortMergedIf); 13525 verifyFormat("#define A \\\n" 13526 " if CONSTEXPR (aaaaaaa) \\\n" 13527 " return 1; \\\n" 13528 " return 2;", 13529 ShortMergedIf); 13530 13531 verifyFormat("//\n" 13532 "#define a \\\n" 13533 " if \\\n" 13534 " 0", 13535 getChromiumStyle(FormatStyle::LK_Cpp)); 13536 } 13537 13538 TEST_F(FormatTest, FormatStarDependingOnContext) { 13539 verifyFormat("void f(int *a);"); 13540 verifyFormat("void f() { f(fint * b); }"); 13541 verifyFormat("class A {\n void f(int *a);\n};"); 13542 verifyFormat("class A {\n int *a;\n};"); 13543 verifyFormat("namespace a {\n" 13544 "namespace b {\n" 13545 "class A {\n" 13546 " void f() {}\n" 13547 " int *a;\n" 13548 "};\n" 13549 "} // namespace b\n" 13550 "} // namespace a"); 13551 } 13552 13553 TEST_F(FormatTest, SpecialTokensAtEndOfLine) { 13554 verifyFormat("while"); 13555 verifyFormat("operator"); 13556 } 13557 13558 TEST_F(FormatTest, SkipsDeeplyNestedLines) { 13559 // This code would be painfully slow to format if we didn't skip it. 13560 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 13561 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13562 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13563 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13564 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13565 "A(1, 1)\n" 13566 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x 13567 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13568 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13569 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13570 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13571 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13572 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13573 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13574 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13575 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n"); 13576 // Deeply nested part is untouched, rest is formatted. 13577 EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n", 13578 format(std::string("int i;\n") + Code + "int j;\n", 13579 getLLVMStyle(), SC_ExpectIncomplete)); 13580 } 13581 13582 //===----------------------------------------------------------------------===// 13583 // Objective-C tests. 13584 //===----------------------------------------------------------------------===// 13585 13586 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) { 13587 verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;"); 13588 EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;", 13589 format("-(NSUInteger)indexOfObject:(id)anObject;")); 13590 EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;")); 13591 EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;")); 13592 EXPECT_EQ("- (NSInteger)Method3:(id)anObject;", 13593 format("-(NSInteger)Method3:(id)anObject;")); 13594 EXPECT_EQ("- (NSInteger)Method4:(id)anObject;", 13595 format("-(NSInteger)Method4:(id)anObject;")); 13596 EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;", 13597 format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;")); 13598 EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;", 13599 format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;")); 13600 EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject " 13601 "forAllCells:(BOOL)flag;", 13602 format("- (void)sendAction:(SEL)aSelector to:(id)anObject " 13603 "forAllCells:(BOOL)flag;")); 13604 13605 // Very long objectiveC method declaration. 13606 verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n" 13607 " (SoooooooooooooooooooooomeType *)bbbbbbbbbb;"); 13608 verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n" 13609 " inRange:(NSRange)range\n" 13610 " outRange:(NSRange)out_range\n" 13611 " outRange1:(NSRange)out_range1\n" 13612 " outRange2:(NSRange)out_range2\n" 13613 " outRange3:(NSRange)out_range3\n" 13614 " outRange4:(NSRange)out_range4\n" 13615 " outRange5:(NSRange)out_range5\n" 13616 " outRange6:(NSRange)out_range6\n" 13617 " outRange7:(NSRange)out_range7\n" 13618 " outRange8:(NSRange)out_range8\n" 13619 " outRange9:(NSRange)out_range9;"); 13620 13621 // When the function name has to be wrapped. 13622 FormatStyle Style = getLLVMStyle(); 13623 // ObjC ignores IndentWrappedFunctionNames when wrapping methods 13624 // and always indents instead. 13625 Style.IndentWrappedFunctionNames = false; 13626 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n" 13627 " veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n" 13628 " anotherName:(NSString)bbbbbbbbbbbbbb {\n" 13629 "}", 13630 Style); 13631 Style.IndentWrappedFunctionNames = true; 13632 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n" 13633 " veryLooooooooooongName:(NSString)cccccccccccccc\n" 13634 " anotherName:(NSString)dddddddddddddd {\n" 13635 "}", 13636 Style); 13637 13638 verifyFormat("- (int)sum:(vector<int>)numbers;"); 13639 verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;"); 13640 // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC 13641 // protocol lists (but not for template classes): 13642 // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;"); 13643 13644 verifyFormat("- (int (*)())foo:(int (*)())f;"); 13645 verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;"); 13646 13647 // If there's no return type (very rare in practice!), LLVM and Google style 13648 // agree. 13649 verifyFormat("- foo;"); 13650 verifyFormat("- foo:(int)f;"); 13651 verifyGoogleFormat("- foo:(int)foo;"); 13652 } 13653 13654 TEST_F(FormatTest, BreaksStringLiterals) { 13655 EXPECT_EQ("\"some text \"\n" 13656 "\"other\";", 13657 format("\"some text other\";", getLLVMStyleWithColumns(12))); 13658 EXPECT_EQ("\"some text \"\n" 13659 "\"other\";", 13660 format("\\\n\"some text other\";", getLLVMStyleWithColumns(12))); 13661 EXPECT_EQ( 13662 "#define A \\\n" 13663 " \"some \" \\\n" 13664 " \"text \" \\\n" 13665 " \"other\";", 13666 format("#define A \"some text other\";", getLLVMStyleWithColumns(12))); 13667 EXPECT_EQ( 13668 "#define A \\\n" 13669 " \"so \" \\\n" 13670 " \"text \" \\\n" 13671 " \"other\";", 13672 format("#define A \"so text other\";", getLLVMStyleWithColumns(12))); 13673 13674 EXPECT_EQ("\"some text\"", 13675 format("\"some text\"", getLLVMStyleWithColumns(1))); 13676 EXPECT_EQ("\"some text\"", 13677 format("\"some text\"", getLLVMStyleWithColumns(11))); 13678 EXPECT_EQ("\"some \"\n" 13679 "\"text\"", 13680 format("\"some text\"", getLLVMStyleWithColumns(10))); 13681 EXPECT_EQ("\"some \"\n" 13682 "\"text\"", 13683 format("\"some text\"", getLLVMStyleWithColumns(7))); 13684 EXPECT_EQ("\"some\"\n" 13685 "\" tex\"\n" 13686 "\"t\"", 13687 format("\"some text\"", getLLVMStyleWithColumns(6))); 13688 EXPECT_EQ("\"some\"\n" 13689 "\" tex\"\n" 13690 "\" and\"", 13691 format("\"some tex and\"", getLLVMStyleWithColumns(6))); 13692 EXPECT_EQ("\"some\"\n" 13693 "\"/tex\"\n" 13694 "\"/and\"", 13695 format("\"some/tex/and\"", getLLVMStyleWithColumns(6))); 13696 13697 EXPECT_EQ("variable =\n" 13698 " \"long string \"\n" 13699 " \"literal\";", 13700 format("variable = \"long string literal\";", 13701 getLLVMStyleWithColumns(20))); 13702 13703 EXPECT_EQ("variable = f(\n" 13704 " \"long string \"\n" 13705 " \"literal\",\n" 13706 " short,\n" 13707 " loooooooooooooooooooong);", 13708 format("variable = f(\"long string literal\", short, " 13709 "loooooooooooooooooooong);", 13710 getLLVMStyleWithColumns(20))); 13711 13712 EXPECT_EQ( 13713 "f(g(\"long string \"\n" 13714 " \"literal\"),\n" 13715 " b);", 13716 format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20))); 13717 EXPECT_EQ("f(g(\"long string \"\n" 13718 " \"literal\",\n" 13719 " a),\n" 13720 " b);", 13721 format("f(g(\"long string literal\", a), b);", 13722 getLLVMStyleWithColumns(20))); 13723 EXPECT_EQ( 13724 "f(\"one two\".split(\n" 13725 " variable));", 13726 format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20))); 13727 EXPECT_EQ("f(\"one two three four five six \"\n" 13728 " \"seven\".split(\n" 13729 " really_looooong_variable));", 13730 format("f(\"one two three four five six seven\"." 13731 "split(really_looooong_variable));", 13732 getLLVMStyleWithColumns(33))); 13733 13734 EXPECT_EQ("f(\"some \"\n" 13735 " \"text\",\n" 13736 " other);", 13737 format("f(\"some text\", other);", getLLVMStyleWithColumns(10))); 13738 13739 // Only break as a last resort. 13740 verifyFormat( 13741 "aaaaaaaaaaaaaaaaaaaa(\n" 13742 " aaaaaaaaaaaaaaaaaaaa,\n" 13743 " aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));"); 13744 13745 EXPECT_EQ("\"splitmea\"\n" 13746 "\"trandomp\"\n" 13747 "\"oint\"", 13748 format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10))); 13749 13750 EXPECT_EQ("\"split/\"\n" 13751 "\"pathat/\"\n" 13752 "\"slashes\"", 13753 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10))); 13754 13755 EXPECT_EQ("\"split/\"\n" 13756 "\"pathat/\"\n" 13757 "\"slashes\"", 13758 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10))); 13759 EXPECT_EQ("\"split at \"\n" 13760 "\"spaces/at/\"\n" 13761 "\"slashes.at.any$\"\n" 13762 "\"non-alphanumeric%\"\n" 13763 "\"1111111111characte\"\n" 13764 "\"rs\"", 13765 format("\"split at " 13766 "spaces/at/" 13767 "slashes.at." 13768 "any$non-" 13769 "alphanumeric%" 13770 "1111111111characte" 13771 "rs\"", 13772 getLLVMStyleWithColumns(20))); 13773 13774 // Verify that splitting the strings understands 13775 // Style::AlwaysBreakBeforeMultilineStrings. 13776 EXPECT_EQ("aaaaaaaaaaaa(\n" 13777 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n" 13778 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");", 13779 format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa " 13780 "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa " 13781 "aaaaaaaaaaaaaaaaaaaaaa\");", 13782 getGoogleStyle())); 13783 EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13784 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";", 13785 format("return \"aaaaaaaaaaaaaaaaaaaaaa " 13786 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa " 13787 "aaaaaaaaaaaaaaaaaaaaaa\";", 13788 getGoogleStyle())); 13789 EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13790 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";", 13791 format("llvm::outs() << " 13792 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa" 13793 "aaaaaaaaaaaaaaaaaaa\";")); 13794 EXPECT_EQ("ffff(\n" 13795 " {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13796 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});", 13797 format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa " 13798 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});", 13799 getGoogleStyle())); 13800 13801 FormatStyle Style = getLLVMStyleWithColumns(12); 13802 Style.BreakStringLiterals = false; 13803 EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style)); 13804 13805 FormatStyle AlignLeft = getLLVMStyleWithColumns(12); 13806 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left; 13807 EXPECT_EQ("#define A \\\n" 13808 " \"some \" \\\n" 13809 " \"text \" \\\n" 13810 " \"other\";", 13811 format("#define A \"some text other\";", AlignLeft)); 13812 } 13813 13814 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) { 13815 EXPECT_EQ("C a = \"some more \"\n" 13816 " \"text\";", 13817 format("C a = \"some more text\";", getLLVMStyleWithColumns(18))); 13818 } 13819 13820 TEST_F(FormatTest, FullyRemoveEmptyLines) { 13821 FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80); 13822 NoEmptyLines.MaxEmptyLinesToKeep = 0; 13823 EXPECT_EQ("int i = a(b());", 13824 format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines)); 13825 } 13826 13827 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) { 13828 EXPECT_EQ( 13829 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 13830 "(\n" 13831 " \"x\t\");", 13832 format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 13833 "aaaaaaa(" 13834 "\"x\t\");")); 13835 } 13836 13837 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) { 13838 EXPECT_EQ( 13839 "u8\"utf8 string \"\n" 13840 "u8\"literal\";", 13841 format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16))); 13842 EXPECT_EQ( 13843 "u\"utf16 string \"\n" 13844 "u\"literal\";", 13845 format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16))); 13846 EXPECT_EQ( 13847 "U\"utf32 string \"\n" 13848 "U\"literal\";", 13849 format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16))); 13850 EXPECT_EQ("L\"wide string \"\n" 13851 "L\"literal\";", 13852 format("L\"wide string literal\";", getGoogleStyleWithColumns(16))); 13853 EXPECT_EQ("@\"NSString \"\n" 13854 "@\"literal\";", 13855 format("@\"NSString literal\";", getGoogleStyleWithColumns(19))); 13856 verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26)); 13857 13858 // This input makes clang-format try to split the incomplete unicode escape 13859 // sequence, which used to lead to a crasher. 13860 verifyNoCrash( 13861 "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 13862 getLLVMStyleWithColumns(60)); 13863 } 13864 13865 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) { 13866 FormatStyle Style = getGoogleStyleWithColumns(15); 13867 EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style)); 13868 EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style)); 13869 EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style)); 13870 EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style)); 13871 EXPECT_EQ("u8R\"x(raw literal)x\";", 13872 format("u8R\"x(raw literal)x\";", Style)); 13873 } 13874 13875 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) { 13876 FormatStyle Style = getLLVMStyleWithColumns(20); 13877 EXPECT_EQ( 13878 "_T(\"aaaaaaaaaaaaaa\")\n" 13879 "_T(\"aaaaaaaaaaaaaa\")\n" 13880 "_T(\"aaaaaaaaaaaa\")", 13881 format(" _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style)); 13882 EXPECT_EQ("f(x,\n" 13883 " _T(\"aaaaaaaaaaaa\")\n" 13884 " _T(\"aaa\"),\n" 13885 " z);", 13886 format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style)); 13887 13888 // FIXME: Handle embedded spaces in one iteration. 13889 // EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n" 13890 // "_T(\"aaaaaaaaaaaaa\")\n" 13891 // "_T(\"aaaaaaaaaaaaa\")\n" 13892 // "_T(\"a\")", 13893 // format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", 13894 // getLLVMStyleWithColumns(20))); 13895 EXPECT_EQ( 13896 "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", 13897 format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style)); 13898 EXPECT_EQ("f(\n" 13899 "#if !TEST\n" 13900 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n" 13901 "#endif\n" 13902 ");", 13903 format("f(\n" 13904 "#if !TEST\n" 13905 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n" 13906 "#endif\n" 13907 ");")); 13908 EXPECT_EQ("f(\n" 13909 "\n" 13910 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));", 13911 format("f(\n" 13912 "\n" 13913 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));")); 13914 // Regression test for accessing tokens past the end of a vector in the 13915 // TokenLexer. 13916 verifyNoCrash(R"(_T( 13917 " 13918 ) 13919 )"); 13920 } 13921 13922 TEST_F(FormatTest, BreaksStringLiteralOperands) { 13923 // In a function call with two operands, the second can be broken with no line 13924 // break before it. 13925 EXPECT_EQ( 13926 "func(a, \"long long \"\n" 13927 " \"long long\");", 13928 format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24))); 13929 // In a function call with three operands, the second must be broken with a 13930 // line break before it. 13931 EXPECT_EQ("func(a,\n" 13932 " \"long long long \"\n" 13933 " \"long\",\n" 13934 " c);", 13935 format("func(a, \"long long long long\", c);", 13936 getLLVMStyleWithColumns(24))); 13937 // In a function call with three operands, the third must be broken with a 13938 // line break before it. 13939 EXPECT_EQ("func(a, b,\n" 13940 " \"long long long \"\n" 13941 " \"long\");", 13942 format("func(a, b, \"long long long long\");", 13943 getLLVMStyleWithColumns(24))); 13944 // In a function call with three operands, both the second and the third must 13945 // be broken with a line break before them. 13946 EXPECT_EQ("func(a,\n" 13947 " \"long long long \"\n" 13948 " \"long\",\n" 13949 " \"long long long \"\n" 13950 " \"long\");", 13951 format("func(a, \"long long long long\", \"long long long long\");", 13952 getLLVMStyleWithColumns(24))); 13953 // In a chain of << with two operands, the second can be broken with no line 13954 // break before it. 13955 EXPECT_EQ("a << \"line line \"\n" 13956 " \"line\";", 13957 format("a << \"line line line\";", getLLVMStyleWithColumns(20))); 13958 // In a chain of << with three operands, the second can be broken with no line 13959 // break before it. 13960 EXPECT_EQ( 13961 "abcde << \"line \"\n" 13962 " \"line line\"\n" 13963 " << c;", 13964 format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20))); 13965 // In a chain of << with three operands, the third must be broken with a line 13966 // break before it. 13967 EXPECT_EQ( 13968 "a << b\n" 13969 " << \"line line \"\n" 13970 " \"line\";", 13971 format("a << b << \"line line line\";", getLLVMStyleWithColumns(20))); 13972 // In a chain of << with three operands, the second can be broken with no line 13973 // break before it and the third must be broken with a line break before it. 13974 EXPECT_EQ("abcd << \"line line \"\n" 13975 " \"line\"\n" 13976 " << \"line line \"\n" 13977 " \"line\";", 13978 format("abcd << \"line line line\" << \"line line line\";", 13979 getLLVMStyleWithColumns(20))); 13980 // In a chain of binary operators with two operands, the second can be broken 13981 // with no line break before it. 13982 EXPECT_EQ( 13983 "abcd + \"line line \"\n" 13984 " \"line line\";", 13985 format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20))); 13986 // In a chain of binary operators with three operands, the second must be 13987 // broken with a line break before it. 13988 EXPECT_EQ("abcd +\n" 13989 " \"line line \"\n" 13990 " \"line line\" +\n" 13991 " e;", 13992 format("abcd + \"line line line line\" + e;", 13993 getLLVMStyleWithColumns(20))); 13994 // In a function call with two operands, with AlignAfterOpenBracket enabled, 13995 // the first must be broken with a line break before it. 13996 FormatStyle Style = getLLVMStyleWithColumns(25); 13997 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 13998 EXPECT_EQ("someFunction(\n" 13999 " \"long long long \"\n" 14000 " \"long\",\n" 14001 " a);", 14002 format("someFunction(\"long long long long\", a);", Style)); 14003 } 14004 14005 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) { 14006 EXPECT_EQ( 14007 "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 14008 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 14009 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";", 14010 format("aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 14011 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 14012 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";")); 14013 } 14014 14015 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) { 14016 EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);", 14017 format("f(g(R\"x(raw literal)x\", a), b);", getGoogleStyle())); 14018 EXPECT_EQ("fffffffffff(g(R\"x(\n" 14019 "multiline raw string literal xxxxxxxxxxxxxx\n" 14020 ")x\",\n" 14021 " a),\n" 14022 " b);", 14023 format("fffffffffff(g(R\"x(\n" 14024 "multiline raw string literal xxxxxxxxxxxxxx\n" 14025 ")x\", a), b);", 14026 getGoogleStyleWithColumns(20))); 14027 EXPECT_EQ("fffffffffff(\n" 14028 " g(R\"x(qqq\n" 14029 "multiline raw string literal xxxxxxxxxxxxxx\n" 14030 ")x\",\n" 14031 " a),\n" 14032 " b);", 14033 format("fffffffffff(g(R\"x(qqq\n" 14034 "multiline raw string literal xxxxxxxxxxxxxx\n" 14035 ")x\", a), b);", 14036 getGoogleStyleWithColumns(20))); 14037 14038 EXPECT_EQ("fffffffffff(R\"x(\n" 14039 "multiline raw string literal xxxxxxxxxxxxxx\n" 14040 ")x\");", 14041 format("fffffffffff(R\"x(\n" 14042 "multiline raw string literal xxxxxxxxxxxxxx\n" 14043 ")x\");", 14044 getGoogleStyleWithColumns(20))); 14045 EXPECT_EQ("fffffffffff(R\"x(\n" 14046 "multiline raw string literal xxxxxxxxxxxxxx\n" 14047 ")x\" + bbbbbb);", 14048 format("fffffffffff(R\"x(\n" 14049 "multiline raw string literal xxxxxxxxxxxxxx\n" 14050 ")x\" + bbbbbb);", 14051 getGoogleStyleWithColumns(20))); 14052 EXPECT_EQ("fffffffffff(\n" 14053 " R\"x(\n" 14054 "multiline raw string literal xxxxxxxxxxxxxx\n" 14055 ")x\" +\n" 14056 " bbbbbb);", 14057 format("fffffffffff(\n" 14058 " R\"x(\n" 14059 "multiline raw string literal xxxxxxxxxxxxxx\n" 14060 ")x\" + bbbbbb);", 14061 getGoogleStyleWithColumns(20))); 14062 EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);", 14063 format("fffffffffff(\n" 14064 " R\"(single line raw string)\" + bbbbbb);")); 14065 } 14066 14067 TEST_F(FormatTest, SkipsUnknownStringLiterals) { 14068 verifyFormat("string a = \"unterminated;"); 14069 EXPECT_EQ("function(\"unterminated,\n" 14070 " OtherParameter);", 14071 format("function( \"unterminated,\n" 14072 " OtherParameter);")); 14073 } 14074 14075 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) { 14076 FormatStyle Style = getLLVMStyle(); 14077 Style.Standard = FormatStyle::LS_Cpp03; 14078 EXPECT_EQ("#define x(_a) printf(\"foo\" _a);", 14079 format("#define x(_a) printf(\"foo\"_a);", Style)); 14080 } 14081 14082 TEST_F(FormatTest, CppLexVersion) { 14083 FormatStyle Style = getLLVMStyle(); 14084 // Formatting of x * y differs if x is a type. 14085 verifyFormat("void foo() { MACRO(a * b); }", Style); 14086 verifyFormat("void foo() { MACRO(int *b); }", Style); 14087 14088 // LLVM style uses latest lexer. 14089 verifyFormat("void foo() { MACRO(char8_t *b); }", Style); 14090 Style.Standard = FormatStyle::LS_Cpp17; 14091 // But in c++17, char8_t isn't a keyword. 14092 verifyFormat("void foo() { MACRO(char8_t * b); }", Style); 14093 } 14094 14095 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); } 14096 14097 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) { 14098 EXPECT_EQ("someFunction(\"aaabbbcccd\"\n" 14099 " \"ddeeefff\");", 14100 format("someFunction(\"aaabbbcccdddeeefff\");", 14101 getLLVMStyleWithColumns(25))); 14102 EXPECT_EQ("someFunction1234567890(\n" 14103 " \"aaabbbcccdddeeefff\");", 14104 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 14105 getLLVMStyleWithColumns(26))); 14106 EXPECT_EQ("someFunction1234567890(\n" 14107 " \"aaabbbcccdddeeeff\"\n" 14108 " \"f\");", 14109 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 14110 getLLVMStyleWithColumns(25))); 14111 EXPECT_EQ("someFunction1234567890(\n" 14112 " \"aaabbbcccdddeeeff\"\n" 14113 " \"f\");", 14114 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 14115 getLLVMStyleWithColumns(24))); 14116 EXPECT_EQ("someFunction(\n" 14117 " \"aaabbbcc ddde \"\n" 14118 " \"efff\");", 14119 format("someFunction(\"aaabbbcc ddde efff\");", 14120 getLLVMStyleWithColumns(25))); 14121 EXPECT_EQ("someFunction(\"aaabbbccc \"\n" 14122 " \"ddeeefff\");", 14123 format("someFunction(\"aaabbbccc ddeeefff\");", 14124 getLLVMStyleWithColumns(25))); 14125 EXPECT_EQ("someFunction1234567890(\n" 14126 " \"aaabb \"\n" 14127 " \"cccdddeeefff\");", 14128 format("someFunction1234567890(\"aaabb cccdddeeefff\");", 14129 getLLVMStyleWithColumns(25))); 14130 EXPECT_EQ("#define A \\\n" 14131 " string s = \\\n" 14132 " \"123456789\" \\\n" 14133 " \"0\"; \\\n" 14134 " int i;", 14135 format("#define A string s = \"1234567890\"; int i;", 14136 getLLVMStyleWithColumns(20))); 14137 EXPECT_EQ("someFunction(\n" 14138 " \"aaabbbcc \"\n" 14139 " \"dddeeefff\");", 14140 format("someFunction(\"aaabbbcc dddeeefff\");", 14141 getLLVMStyleWithColumns(25))); 14142 } 14143 14144 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) { 14145 EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3))); 14146 EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2))); 14147 EXPECT_EQ("\"test\"\n" 14148 "\"\\n\"", 14149 format("\"test\\n\"", getLLVMStyleWithColumns(7))); 14150 EXPECT_EQ("\"tes\\\\\"\n" 14151 "\"n\"", 14152 format("\"tes\\\\n\"", getLLVMStyleWithColumns(7))); 14153 EXPECT_EQ("\"\\\\\\\\\"\n" 14154 "\"\\n\"", 14155 format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7))); 14156 EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7))); 14157 EXPECT_EQ("\"\\uff01\"\n" 14158 "\"test\"", 14159 format("\"\\uff01test\"", getLLVMStyleWithColumns(8))); 14160 EXPECT_EQ("\"\\Uff01ff02\"", 14161 format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11))); 14162 EXPECT_EQ("\"\\x000000000001\"\n" 14163 "\"next\"", 14164 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16))); 14165 EXPECT_EQ("\"\\x000000000001next\"", 14166 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15))); 14167 EXPECT_EQ("\"\\x000000000001\"", 14168 format("\"\\x000000000001\"", getLLVMStyleWithColumns(7))); 14169 EXPECT_EQ("\"test\"\n" 14170 "\"\\000000\"\n" 14171 "\"000001\"", 14172 format("\"test\\000000000001\"", getLLVMStyleWithColumns(9))); 14173 EXPECT_EQ("\"test\\000\"\n" 14174 "\"00000000\"\n" 14175 "\"1\"", 14176 format("\"test\\000000000001\"", getLLVMStyleWithColumns(10))); 14177 } 14178 14179 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) { 14180 verifyFormat("void f() {\n" 14181 " return g() {}\n" 14182 " void h() {}"); 14183 verifyFormat("int a[] = {void forgot_closing_brace(){f();\n" 14184 "g();\n" 14185 "}"); 14186 } 14187 14188 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) { 14189 verifyFormat( 14190 "void f() { return C{param1, param2}.SomeCall(param1, param2); }"); 14191 } 14192 14193 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) { 14194 verifyFormat("class X {\n" 14195 " void f() {\n" 14196 " }\n" 14197 "};", 14198 getLLVMStyleWithColumns(12)); 14199 } 14200 14201 TEST_F(FormatTest, ConfigurableIndentWidth) { 14202 FormatStyle EightIndent = getLLVMStyleWithColumns(18); 14203 EightIndent.IndentWidth = 8; 14204 EightIndent.ContinuationIndentWidth = 8; 14205 verifyFormat("void f() {\n" 14206 " someFunction();\n" 14207 " if (true) {\n" 14208 " f();\n" 14209 " }\n" 14210 "}", 14211 EightIndent); 14212 verifyFormat("class X {\n" 14213 " void f() {\n" 14214 " }\n" 14215 "};", 14216 EightIndent); 14217 verifyFormat("int x[] = {\n" 14218 " call(),\n" 14219 " call()};", 14220 EightIndent); 14221 } 14222 14223 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) { 14224 verifyFormat("double\n" 14225 "f();", 14226 getLLVMStyleWithColumns(8)); 14227 } 14228 14229 TEST_F(FormatTest, ConfigurableUseOfTab) { 14230 FormatStyle Tab = getLLVMStyleWithColumns(42); 14231 Tab.IndentWidth = 8; 14232 Tab.UseTab = FormatStyle::UT_Always; 14233 Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left; 14234 14235 EXPECT_EQ("if (aaaaaaaa && // q\n" 14236 " bb)\t\t// w\n" 14237 "\t;", 14238 format("if (aaaaaaaa &&// q\n" 14239 "bb)// w\n" 14240 ";", 14241 Tab)); 14242 EXPECT_EQ("if (aaa && bbb) // w\n" 14243 "\t;", 14244 format("if(aaa&&bbb)// w\n" 14245 ";", 14246 Tab)); 14247 14248 verifyFormat("class X {\n" 14249 "\tvoid f() {\n" 14250 "\t\tsomeFunction(parameter1,\n" 14251 "\t\t\t parameter2);\n" 14252 "\t}\n" 14253 "};", 14254 Tab); 14255 verifyFormat("#define A \\\n" 14256 "\tvoid f() { \\\n" 14257 "\t\tsomeFunction( \\\n" 14258 "\t\t parameter1, \\\n" 14259 "\t\t parameter2); \\\n" 14260 "\t}", 14261 Tab); 14262 verifyFormat("int a;\t // x\n" 14263 "int bbbbbbbb; // x\n", 14264 Tab); 14265 14266 FormatStyle TabAlignment = Tab; 14267 TabAlignment.AlignConsecutiveDeclarations.Enabled = true; 14268 TabAlignment.PointerAlignment = FormatStyle::PAS_Left; 14269 verifyFormat("unsigned long long big;\n" 14270 "char*\t\t ptr;", 14271 TabAlignment); 14272 TabAlignment.PointerAlignment = FormatStyle::PAS_Middle; 14273 verifyFormat("unsigned long long big;\n" 14274 "char *\t\t ptr;", 14275 TabAlignment); 14276 TabAlignment.PointerAlignment = FormatStyle::PAS_Right; 14277 verifyFormat("unsigned long long big;\n" 14278 "char\t\t *ptr;", 14279 TabAlignment); 14280 14281 Tab.TabWidth = 4; 14282 Tab.IndentWidth = 8; 14283 verifyFormat("class TabWidth4Indent8 {\n" 14284 "\t\tvoid f() {\n" 14285 "\t\t\t\tsomeFunction(parameter1,\n" 14286 "\t\t\t\t\t\t\t parameter2);\n" 14287 "\t\t}\n" 14288 "};", 14289 Tab); 14290 14291 Tab.TabWidth = 4; 14292 Tab.IndentWidth = 4; 14293 verifyFormat("class TabWidth4Indent4 {\n" 14294 "\tvoid f() {\n" 14295 "\t\tsomeFunction(parameter1,\n" 14296 "\t\t\t\t\t parameter2);\n" 14297 "\t}\n" 14298 "};", 14299 Tab); 14300 14301 Tab.TabWidth = 8; 14302 Tab.IndentWidth = 4; 14303 verifyFormat("class TabWidth8Indent4 {\n" 14304 " void f() {\n" 14305 "\tsomeFunction(parameter1,\n" 14306 "\t\t parameter2);\n" 14307 " }\n" 14308 "};", 14309 Tab); 14310 14311 Tab.TabWidth = 8; 14312 Tab.IndentWidth = 8; 14313 EXPECT_EQ("/*\n" 14314 "\t a\t\tcomment\n" 14315 "\t in multiple lines\n" 14316 " */", 14317 format(" /*\t \t \n" 14318 " \t \t a\t\tcomment\t \t\n" 14319 " \t \t in multiple lines\t\n" 14320 " \t */", 14321 Tab)); 14322 14323 TabAlignment.UseTab = FormatStyle::UT_ForIndentation; 14324 TabAlignment.PointerAlignment = FormatStyle::PAS_Left; 14325 verifyFormat("void f() {\n" 14326 "\tunsigned long long big;\n" 14327 "\tchar* ptr;\n" 14328 "}", 14329 TabAlignment); 14330 TabAlignment.PointerAlignment = FormatStyle::PAS_Middle; 14331 verifyFormat("void f() {\n" 14332 "\tunsigned long long big;\n" 14333 "\tchar * ptr;\n" 14334 "}", 14335 TabAlignment); 14336 TabAlignment.PointerAlignment = FormatStyle::PAS_Right; 14337 verifyFormat("void f() {\n" 14338 "\tunsigned long long big;\n" 14339 "\tchar *ptr;\n" 14340 "}", 14341 TabAlignment); 14342 14343 Tab.UseTab = FormatStyle::UT_ForIndentation; 14344 verifyFormat("{\n" 14345 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14346 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14347 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14348 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14349 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14350 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14351 "};", 14352 Tab); 14353 verifyFormat("enum AA {\n" 14354 "\ta1, // Force multiple lines\n" 14355 "\ta2,\n" 14356 "\ta3\n" 14357 "};", 14358 Tab); 14359 EXPECT_EQ("if (aaaaaaaa && // q\n" 14360 " bb) // w\n" 14361 "\t;", 14362 format("if (aaaaaaaa &&// q\n" 14363 "bb)// w\n" 14364 ";", 14365 Tab)); 14366 verifyFormat("class X {\n" 14367 "\tvoid f() {\n" 14368 "\t\tsomeFunction(parameter1,\n" 14369 "\t\t parameter2);\n" 14370 "\t}\n" 14371 "};", 14372 Tab); 14373 verifyFormat("{\n" 14374 "\tQ(\n" 14375 "\t {\n" 14376 "\t\t int a;\n" 14377 "\t\t someFunction(aaaaaaaa,\n" 14378 "\t\t bbbbbbb);\n" 14379 "\t },\n" 14380 "\t p);\n" 14381 "}", 14382 Tab); 14383 EXPECT_EQ("{\n" 14384 "\t/* aaaa\n" 14385 "\t bbbb */\n" 14386 "}", 14387 format("{\n" 14388 "/* aaaa\n" 14389 " bbbb */\n" 14390 "}", 14391 Tab)); 14392 EXPECT_EQ("{\n" 14393 "\t/*\n" 14394 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14395 "\t bbbbbbbbbbbbb\n" 14396 "\t*/\n" 14397 "}", 14398 format("{\n" 14399 "/*\n" 14400 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14401 "*/\n" 14402 "}", 14403 Tab)); 14404 EXPECT_EQ("{\n" 14405 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14406 "\t// bbbbbbbbbbbbb\n" 14407 "}", 14408 format("{\n" 14409 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14410 "}", 14411 Tab)); 14412 EXPECT_EQ("{\n" 14413 "\t/*\n" 14414 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14415 "\t bbbbbbbbbbbbb\n" 14416 "\t*/\n" 14417 "}", 14418 format("{\n" 14419 "\t/*\n" 14420 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14421 "\t*/\n" 14422 "}", 14423 Tab)); 14424 EXPECT_EQ("{\n" 14425 "\t/*\n" 14426 "\n" 14427 "\t*/\n" 14428 "}", 14429 format("{\n" 14430 "\t/*\n" 14431 "\n" 14432 "\t*/\n" 14433 "}", 14434 Tab)); 14435 EXPECT_EQ("{\n" 14436 "\t/*\n" 14437 " asdf\n" 14438 "\t*/\n" 14439 "}", 14440 format("{\n" 14441 "\t/*\n" 14442 " asdf\n" 14443 "\t*/\n" 14444 "}", 14445 Tab)); 14446 14447 verifyFormat("void f() {\n" 14448 "\treturn true ? aaaaaaaaaaaaaaaaaa\n" 14449 "\t : bbbbbbbbbbbbbbbbbb\n" 14450 "}", 14451 Tab); 14452 FormatStyle TabNoBreak = Tab; 14453 TabNoBreak.BreakBeforeTernaryOperators = false; 14454 verifyFormat("void f() {\n" 14455 "\treturn true ? aaaaaaaaaaaaaaaaaa :\n" 14456 "\t bbbbbbbbbbbbbbbbbb\n" 14457 "}", 14458 TabNoBreak); 14459 verifyFormat("void f() {\n" 14460 "\treturn true ?\n" 14461 "\t aaaaaaaaaaaaaaaaaaaa :\n" 14462 "\t bbbbbbbbbbbbbbbbbbbb\n" 14463 "}", 14464 TabNoBreak); 14465 14466 Tab.UseTab = FormatStyle::UT_Never; 14467 EXPECT_EQ("/*\n" 14468 " a\t\tcomment\n" 14469 " in multiple lines\n" 14470 " */", 14471 format(" /*\t \t \n" 14472 " \t \t a\t\tcomment\t \t\n" 14473 " \t \t in multiple lines\t\n" 14474 " \t */", 14475 Tab)); 14476 EXPECT_EQ("/* some\n" 14477 " comment */", 14478 format(" \t \t /* some\n" 14479 " \t \t comment */", 14480 Tab)); 14481 EXPECT_EQ("int a; /* some\n" 14482 " comment */", 14483 format(" \t \t int a; /* some\n" 14484 " \t \t comment */", 14485 Tab)); 14486 14487 EXPECT_EQ("int a; /* some\n" 14488 "comment */", 14489 format(" \t \t int\ta; /* some\n" 14490 " \t \t comment */", 14491 Tab)); 14492 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14493 " comment */", 14494 format(" \t \t f(\"\t\t\"); /* some\n" 14495 " \t \t comment */", 14496 Tab)); 14497 EXPECT_EQ("{\n" 14498 " /*\n" 14499 " * Comment\n" 14500 " */\n" 14501 " int i;\n" 14502 "}", 14503 format("{\n" 14504 "\t/*\n" 14505 "\t * Comment\n" 14506 "\t */\n" 14507 "\t int i;\n" 14508 "}", 14509 Tab)); 14510 14511 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation; 14512 Tab.TabWidth = 8; 14513 Tab.IndentWidth = 8; 14514 EXPECT_EQ("if (aaaaaaaa && // q\n" 14515 " bb) // w\n" 14516 "\t;", 14517 format("if (aaaaaaaa &&// q\n" 14518 "bb)// w\n" 14519 ";", 14520 Tab)); 14521 EXPECT_EQ("if (aaa && bbb) // w\n" 14522 "\t;", 14523 format("if(aaa&&bbb)// w\n" 14524 ";", 14525 Tab)); 14526 verifyFormat("class X {\n" 14527 "\tvoid f() {\n" 14528 "\t\tsomeFunction(parameter1,\n" 14529 "\t\t\t parameter2);\n" 14530 "\t}\n" 14531 "};", 14532 Tab); 14533 verifyFormat("#define A \\\n" 14534 "\tvoid f() { \\\n" 14535 "\t\tsomeFunction( \\\n" 14536 "\t\t parameter1, \\\n" 14537 "\t\t parameter2); \\\n" 14538 "\t}", 14539 Tab); 14540 Tab.TabWidth = 4; 14541 Tab.IndentWidth = 8; 14542 verifyFormat("class TabWidth4Indent8 {\n" 14543 "\t\tvoid f() {\n" 14544 "\t\t\t\tsomeFunction(parameter1,\n" 14545 "\t\t\t\t\t\t\t parameter2);\n" 14546 "\t\t}\n" 14547 "};", 14548 Tab); 14549 Tab.TabWidth = 4; 14550 Tab.IndentWidth = 4; 14551 verifyFormat("class TabWidth4Indent4 {\n" 14552 "\tvoid f() {\n" 14553 "\t\tsomeFunction(parameter1,\n" 14554 "\t\t\t\t\t parameter2);\n" 14555 "\t}\n" 14556 "};", 14557 Tab); 14558 Tab.TabWidth = 8; 14559 Tab.IndentWidth = 4; 14560 verifyFormat("class TabWidth8Indent4 {\n" 14561 " void f() {\n" 14562 "\tsomeFunction(parameter1,\n" 14563 "\t\t parameter2);\n" 14564 " }\n" 14565 "};", 14566 Tab); 14567 Tab.TabWidth = 8; 14568 Tab.IndentWidth = 8; 14569 EXPECT_EQ("/*\n" 14570 "\t a\t\tcomment\n" 14571 "\t in multiple lines\n" 14572 " */", 14573 format(" /*\t \t \n" 14574 " \t \t a\t\tcomment\t \t\n" 14575 " \t \t in multiple lines\t\n" 14576 " \t */", 14577 Tab)); 14578 verifyFormat("{\n" 14579 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14580 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14581 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14582 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14583 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14584 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14585 "};", 14586 Tab); 14587 verifyFormat("enum AA {\n" 14588 "\ta1, // Force multiple lines\n" 14589 "\ta2,\n" 14590 "\ta3\n" 14591 "};", 14592 Tab); 14593 EXPECT_EQ("if (aaaaaaaa && // q\n" 14594 " bb) // w\n" 14595 "\t;", 14596 format("if (aaaaaaaa &&// q\n" 14597 "bb)// w\n" 14598 ";", 14599 Tab)); 14600 verifyFormat("class X {\n" 14601 "\tvoid f() {\n" 14602 "\t\tsomeFunction(parameter1,\n" 14603 "\t\t\t parameter2);\n" 14604 "\t}\n" 14605 "};", 14606 Tab); 14607 verifyFormat("{\n" 14608 "\tQ(\n" 14609 "\t {\n" 14610 "\t\t int a;\n" 14611 "\t\t someFunction(aaaaaaaa,\n" 14612 "\t\t\t\t bbbbbbb);\n" 14613 "\t },\n" 14614 "\t p);\n" 14615 "}", 14616 Tab); 14617 EXPECT_EQ("{\n" 14618 "\t/* aaaa\n" 14619 "\t bbbb */\n" 14620 "}", 14621 format("{\n" 14622 "/* aaaa\n" 14623 " bbbb */\n" 14624 "}", 14625 Tab)); 14626 EXPECT_EQ("{\n" 14627 "\t/*\n" 14628 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14629 "\t bbbbbbbbbbbbb\n" 14630 "\t*/\n" 14631 "}", 14632 format("{\n" 14633 "/*\n" 14634 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14635 "*/\n" 14636 "}", 14637 Tab)); 14638 EXPECT_EQ("{\n" 14639 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14640 "\t// bbbbbbbbbbbbb\n" 14641 "}", 14642 format("{\n" 14643 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14644 "}", 14645 Tab)); 14646 EXPECT_EQ("{\n" 14647 "\t/*\n" 14648 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14649 "\t bbbbbbbbbbbbb\n" 14650 "\t*/\n" 14651 "}", 14652 format("{\n" 14653 "\t/*\n" 14654 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14655 "\t*/\n" 14656 "}", 14657 Tab)); 14658 EXPECT_EQ("{\n" 14659 "\t/*\n" 14660 "\n" 14661 "\t*/\n" 14662 "}", 14663 format("{\n" 14664 "\t/*\n" 14665 "\n" 14666 "\t*/\n" 14667 "}", 14668 Tab)); 14669 EXPECT_EQ("{\n" 14670 "\t/*\n" 14671 " asdf\n" 14672 "\t*/\n" 14673 "}", 14674 format("{\n" 14675 "\t/*\n" 14676 " asdf\n" 14677 "\t*/\n" 14678 "}", 14679 Tab)); 14680 EXPECT_EQ("/* some\n" 14681 " comment */", 14682 format(" \t \t /* some\n" 14683 " \t \t comment */", 14684 Tab)); 14685 EXPECT_EQ("int a; /* some\n" 14686 " comment */", 14687 format(" \t \t int a; /* some\n" 14688 " \t \t comment */", 14689 Tab)); 14690 EXPECT_EQ("int a; /* some\n" 14691 "comment */", 14692 format(" \t \t int\ta; /* some\n" 14693 " \t \t comment */", 14694 Tab)); 14695 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14696 " comment */", 14697 format(" \t \t f(\"\t\t\"); /* some\n" 14698 " \t \t comment */", 14699 Tab)); 14700 EXPECT_EQ("{\n" 14701 "\t/*\n" 14702 "\t * Comment\n" 14703 "\t */\n" 14704 "\tint i;\n" 14705 "}", 14706 format("{\n" 14707 "\t/*\n" 14708 "\t * Comment\n" 14709 "\t */\n" 14710 "\t int i;\n" 14711 "}", 14712 Tab)); 14713 Tab.TabWidth = 2; 14714 Tab.IndentWidth = 2; 14715 EXPECT_EQ("{\n" 14716 "\t/* aaaa\n" 14717 "\t\t bbbb */\n" 14718 "}", 14719 format("{\n" 14720 "/* aaaa\n" 14721 "\t bbbb */\n" 14722 "}", 14723 Tab)); 14724 EXPECT_EQ("{\n" 14725 "\t/*\n" 14726 "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14727 "\t\tbbbbbbbbbbbbb\n" 14728 "\t*/\n" 14729 "}", 14730 format("{\n" 14731 "/*\n" 14732 "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14733 "*/\n" 14734 "}", 14735 Tab)); 14736 Tab.AlignConsecutiveAssignments.Enabled = true; 14737 Tab.AlignConsecutiveDeclarations.Enabled = true; 14738 Tab.TabWidth = 4; 14739 Tab.IndentWidth = 4; 14740 verifyFormat("class Assign {\n" 14741 "\tvoid f() {\n" 14742 "\t\tint x = 123;\n" 14743 "\t\tint random = 4;\n" 14744 "\t\tstd::string alphabet =\n" 14745 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n" 14746 "\t}\n" 14747 "};", 14748 Tab); 14749 14750 Tab.UseTab = FormatStyle::UT_AlignWithSpaces; 14751 Tab.TabWidth = 8; 14752 Tab.IndentWidth = 8; 14753 EXPECT_EQ("if (aaaaaaaa && // q\n" 14754 " bb) // w\n" 14755 "\t;", 14756 format("if (aaaaaaaa &&// q\n" 14757 "bb)// w\n" 14758 ";", 14759 Tab)); 14760 EXPECT_EQ("if (aaa && bbb) // w\n" 14761 "\t;", 14762 format("if(aaa&&bbb)// w\n" 14763 ";", 14764 Tab)); 14765 verifyFormat("class X {\n" 14766 "\tvoid f() {\n" 14767 "\t\tsomeFunction(parameter1,\n" 14768 "\t\t parameter2);\n" 14769 "\t}\n" 14770 "};", 14771 Tab); 14772 verifyFormat("#define A \\\n" 14773 "\tvoid f() { \\\n" 14774 "\t\tsomeFunction( \\\n" 14775 "\t\t parameter1, \\\n" 14776 "\t\t parameter2); \\\n" 14777 "\t}", 14778 Tab); 14779 Tab.TabWidth = 4; 14780 Tab.IndentWidth = 8; 14781 verifyFormat("class TabWidth4Indent8 {\n" 14782 "\t\tvoid f() {\n" 14783 "\t\t\t\tsomeFunction(parameter1,\n" 14784 "\t\t\t\t parameter2);\n" 14785 "\t\t}\n" 14786 "};", 14787 Tab); 14788 Tab.TabWidth = 4; 14789 Tab.IndentWidth = 4; 14790 verifyFormat("class TabWidth4Indent4 {\n" 14791 "\tvoid f() {\n" 14792 "\t\tsomeFunction(parameter1,\n" 14793 "\t\t parameter2);\n" 14794 "\t}\n" 14795 "};", 14796 Tab); 14797 Tab.TabWidth = 8; 14798 Tab.IndentWidth = 4; 14799 verifyFormat("class TabWidth8Indent4 {\n" 14800 " void f() {\n" 14801 "\tsomeFunction(parameter1,\n" 14802 "\t parameter2);\n" 14803 " }\n" 14804 "};", 14805 Tab); 14806 Tab.TabWidth = 8; 14807 Tab.IndentWidth = 8; 14808 EXPECT_EQ("/*\n" 14809 " a\t\tcomment\n" 14810 " in multiple lines\n" 14811 " */", 14812 format(" /*\t \t \n" 14813 " \t \t a\t\tcomment\t \t\n" 14814 " \t \t in multiple lines\t\n" 14815 " \t */", 14816 Tab)); 14817 verifyFormat("{\n" 14818 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14819 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14820 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14821 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14822 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14823 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14824 "};", 14825 Tab); 14826 verifyFormat("enum AA {\n" 14827 "\ta1, // Force multiple lines\n" 14828 "\ta2,\n" 14829 "\ta3\n" 14830 "};", 14831 Tab); 14832 EXPECT_EQ("if (aaaaaaaa && // q\n" 14833 " bb) // w\n" 14834 "\t;", 14835 format("if (aaaaaaaa &&// q\n" 14836 "bb)// w\n" 14837 ";", 14838 Tab)); 14839 verifyFormat("class X {\n" 14840 "\tvoid f() {\n" 14841 "\t\tsomeFunction(parameter1,\n" 14842 "\t\t parameter2);\n" 14843 "\t}\n" 14844 "};", 14845 Tab); 14846 verifyFormat("{\n" 14847 "\tQ(\n" 14848 "\t {\n" 14849 "\t\t int a;\n" 14850 "\t\t someFunction(aaaaaaaa,\n" 14851 "\t\t bbbbbbb);\n" 14852 "\t },\n" 14853 "\t p);\n" 14854 "}", 14855 Tab); 14856 EXPECT_EQ("{\n" 14857 "\t/* aaaa\n" 14858 "\t bbbb */\n" 14859 "}", 14860 format("{\n" 14861 "/* aaaa\n" 14862 " bbbb */\n" 14863 "}", 14864 Tab)); 14865 EXPECT_EQ("{\n" 14866 "\t/*\n" 14867 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14868 "\t bbbbbbbbbbbbb\n" 14869 "\t*/\n" 14870 "}", 14871 format("{\n" 14872 "/*\n" 14873 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14874 "*/\n" 14875 "}", 14876 Tab)); 14877 EXPECT_EQ("{\n" 14878 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14879 "\t// bbbbbbbbbbbbb\n" 14880 "}", 14881 format("{\n" 14882 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14883 "}", 14884 Tab)); 14885 EXPECT_EQ("{\n" 14886 "\t/*\n" 14887 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14888 "\t bbbbbbbbbbbbb\n" 14889 "\t*/\n" 14890 "}", 14891 format("{\n" 14892 "\t/*\n" 14893 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14894 "\t*/\n" 14895 "}", 14896 Tab)); 14897 EXPECT_EQ("{\n" 14898 "\t/*\n" 14899 "\n" 14900 "\t*/\n" 14901 "}", 14902 format("{\n" 14903 "\t/*\n" 14904 "\n" 14905 "\t*/\n" 14906 "}", 14907 Tab)); 14908 EXPECT_EQ("{\n" 14909 "\t/*\n" 14910 " asdf\n" 14911 "\t*/\n" 14912 "}", 14913 format("{\n" 14914 "\t/*\n" 14915 " asdf\n" 14916 "\t*/\n" 14917 "}", 14918 Tab)); 14919 EXPECT_EQ("/* some\n" 14920 " comment */", 14921 format(" \t \t /* some\n" 14922 " \t \t comment */", 14923 Tab)); 14924 EXPECT_EQ("int a; /* some\n" 14925 " comment */", 14926 format(" \t \t int a; /* some\n" 14927 " \t \t comment */", 14928 Tab)); 14929 EXPECT_EQ("int a; /* some\n" 14930 "comment */", 14931 format(" \t \t int\ta; /* some\n" 14932 " \t \t comment */", 14933 Tab)); 14934 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14935 " comment */", 14936 format(" \t \t f(\"\t\t\"); /* some\n" 14937 " \t \t comment */", 14938 Tab)); 14939 EXPECT_EQ("{\n" 14940 "\t/*\n" 14941 "\t * Comment\n" 14942 "\t */\n" 14943 "\tint i;\n" 14944 "}", 14945 format("{\n" 14946 "\t/*\n" 14947 "\t * Comment\n" 14948 "\t */\n" 14949 "\t int i;\n" 14950 "}", 14951 Tab)); 14952 Tab.TabWidth = 2; 14953 Tab.IndentWidth = 2; 14954 EXPECT_EQ("{\n" 14955 "\t/* aaaa\n" 14956 "\t bbbb */\n" 14957 "}", 14958 format("{\n" 14959 "/* aaaa\n" 14960 " bbbb */\n" 14961 "}", 14962 Tab)); 14963 EXPECT_EQ("{\n" 14964 "\t/*\n" 14965 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14966 "\t bbbbbbbbbbbbb\n" 14967 "\t*/\n" 14968 "}", 14969 format("{\n" 14970 "/*\n" 14971 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14972 "*/\n" 14973 "}", 14974 Tab)); 14975 Tab.AlignConsecutiveAssignments.Enabled = true; 14976 Tab.AlignConsecutiveDeclarations.Enabled = true; 14977 Tab.TabWidth = 4; 14978 Tab.IndentWidth = 4; 14979 verifyFormat("class Assign {\n" 14980 "\tvoid f() {\n" 14981 "\t\tint x = 123;\n" 14982 "\t\tint random = 4;\n" 14983 "\t\tstd::string alphabet =\n" 14984 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n" 14985 "\t}\n" 14986 "};", 14987 Tab); 14988 Tab.AlignOperands = FormatStyle::OAS_Align; 14989 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n" 14990 " cccccccccccccccccccc;", 14991 Tab); 14992 // no alignment 14993 verifyFormat("int aaaaaaaaaa =\n" 14994 "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 14995 Tab); 14996 verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n" 14997 " : bbbbbbbbbbbbbb ? 222222222222222\n" 14998 " : 333333333333333;", 14999 Tab); 15000 Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 15001 Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator; 15002 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n" 15003 " + cccccccccccccccccccc;", 15004 Tab); 15005 } 15006 15007 TEST_F(FormatTest, ZeroTabWidth) { 15008 FormatStyle Tab = getLLVMStyleWithColumns(42); 15009 Tab.IndentWidth = 8; 15010 Tab.UseTab = FormatStyle::UT_Never; 15011 Tab.TabWidth = 0; 15012 EXPECT_EQ("void a(){\n" 15013 " // line starts with '\t'\n" 15014 "};", 15015 format("void a(){\n" 15016 "\t// line starts with '\t'\n" 15017 "};", 15018 Tab)); 15019 15020 EXPECT_EQ("void a(){\n" 15021 " // line starts with '\t'\n" 15022 "};", 15023 format("void a(){\n" 15024 "\t\t// line starts with '\t'\n" 15025 "};", 15026 Tab)); 15027 15028 Tab.UseTab = FormatStyle::UT_ForIndentation; 15029 EXPECT_EQ("void a(){\n" 15030 " // line starts with '\t'\n" 15031 "};", 15032 format("void a(){\n" 15033 "\t// line starts with '\t'\n" 15034 "};", 15035 Tab)); 15036 15037 EXPECT_EQ("void a(){\n" 15038 " // line starts with '\t'\n" 15039 "};", 15040 format("void a(){\n" 15041 "\t\t// line starts with '\t'\n" 15042 "};", 15043 Tab)); 15044 15045 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation; 15046 EXPECT_EQ("void a(){\n" 15047 " // line starts with '\t'\n" 15048 "};", 15049 format("void a(){\n" 15050 "\t// line starts with '\t'\n" 15051 "};", 15052 Tab)); 15053 15054 EXPECT_EQ("void a(){\n" 15055 " // line starts with '\t'\n" 15056 "};", 15057 format("void a(){\n" 15058 "\t\t// line starts with '\t'\n" 15059 "};", 15060 Tab)); 15061 15062 Tab.UseTab = FormatStyle::UT_AlignWithSpaces; 15063 EXPECT_EQ("void a(){\n" 15064 " // line starts with '\t'\n" 15065 "};", 15066 format("void a(){\n" 15067 "\t// line starts with '\t'\n" 15068 "};", 15069 Tab)); 15070 15071 EXPECT_EQ("void a(){\n" 15072 " // line starts with '\t'\n" 15073 "};", 15074 format("void a(){\n" 15075 "\t\t// line starts with '\t'\n" 15076 "};", 15077 Tab)); 15078 15079 Tab.UseTab = FormatStyle::UT_Always; 15080 EXPECT_EQ("void a(){\n" 15081 "// line starts with '\t'\n" 15082 "};", 15083 format("void a(){\n" 15084 "\t// line starts with '\t'\n" 15085 "};", 15086 Tab)); 15087 15088 EXPECT_EQ("void a(){\n" 15089 "// line starts with '\t'\n" 15090 "};", 15091 format("void a(){\n" 15092 "\t\t// line starts with '\t'\n" 15093 "};", 15094 Tab)); 15095 } 15096 15097 TEST_F(FormatTest, CalculatesOriginalColumn) { 15098 EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 15099 "q\"; /* some\n" 15100 " comment */", 15101 format(" \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 15102 "q\"; /* some\n" 15103 " comment */", 15104 getLLVMStyle())); 15105 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n" 15106 "/* some\n" 15107 " comment */", 15108 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n" 15109 " /* some\n" 15110 " comment */", 15111 getLLVMStyle())); 15112 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 15113 "qqq\n" 15114 "/* some\n" 15115 " comment */", 15116 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 15117 "qqq\n" 15118 " /* some\n" 15119 " comment */", 15120 getLLVMStyle())); 15121 EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 15122 "wwww; /* some\n" 15123 " comment */", 15124 format(" inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 15125 "wwww; /* some\n" 15126 " comment */", 15127 getLLVMStyle())); 15128 } 15129 15130 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) { 15131 FormatStyle NoSpace = getLLVMStyle(); 15132 NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never; 15133 15134 verifyFormat("while(true)\n" 15135 " continue;", 15136 NoSpace); 15137 verifyFormat("for(;;)\n" 15138 " continue;", 15139 NoSpace); 15140 verifyFormat("if(true)\n" 15141 " f();\n" 15142 "else if(true)\n" 15143 " f();", 15144 NoSpace); 15145 verifyFormat("do {\n" 15146 " do_something();\n" 15147 "} while(something());", 15148 NoSpace); 15149 verifyFormat("switch(x) {\n" 15150 "default:\n" 15151 " break;\n" 15152 "}", 15153 NoSpace); 15154 verifyFormat("auto i = std::make_unique<int>(5);", NoSpace); 15155 verifyFormat("size_t x = sizeof(x);", NoSpace); 15156 verifyFormat("auto f(int x) -> decltype(x);", NoSpace); 15157 verifyFormat("auto f(int x) -> typeof(x);", NoSpace); 15158 verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace); 15159 verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace); 15160 verifyFormat("int f(T x) noexcept(x.create());", NoSpace); 15161 verifyFormat("alignas(128) char a[128];", NoSpace); 15162 verifyFormat("size_t x = alignof(MyType);", NoSpace); 15163 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace); 15164 verifyFormat("int f() throw(Deprecated);", NoSpace); 15165 verifyFormat("typedef void (*cb)(int);", NoSpace); 15166 verifyFormat("T A::operator()();", NoSpace); 15167 verifyFormat("X A::operator++(T);", NoSpace); 15168 verifyFormat("auto lambda = []() { return 0; };", NoSpace); 15169 15170 FormatStyle Space = getLLVMStyle(); 15171 Space.SpaceBeforeParens = FormatStyle::SBPO_Always; 15172 15173 verifyFormat("int f ();", Space); 15174 verifyFormat("void f (int a, T b) {\n" 15175 " while (true)\n" 15176 " continue;\n" 15177 "}", 15178 Space); 15179 verifyFormat("if (true)\n" 15180 " f ();\n" 15181 "else if (true)\n" 15182 " f ();", 15183 Space); 15184 verifyFormat("do {\n" 15185 " do_something ();\n" 15186 "} while (something ());", 15187 Space); 15188 verifyFormat("switch (x) {\n" 15189 "default:\n" 15190 " break;\n" 15191 "}", 15192 Space); 15193 verifyFormat("A::A () : a (1) {}", Space); 15194 verifyFormat("void f () __attribute__ ((asdf));", Space); 15195 verifyFormat("*(&a + 1);\n" 15196 "&((&a)[1]);\n" 15197 "a[(b + c) * d];\n" 15198 "(((a + 1) * 2) + 3) * 4;", 15199 Space); 15200 verifyFormat("#define A(x) x", Space); 15201 verifyFormat("#define A (x) x", Space); 15202 verifyFormat("#if defined(x)\n" 15203 "#endif", 15204 Space); 15205 verifyFormat("auto i = std::make_unique<int> (5);", Space); 15206 verifyFormat("size_t x = sizeof (x);", Space); 15207 verifyFormat("auto f (int x) -> decltype (x);", Space); 15208 verifyFormat("auto f (int x) -> typeof (x);", Space); 15209 verifyFormat("auto f (int x) -> _Atomic (x);", Space); 15210 verifyFormat("auto f (int x) -> __underlying_type (x);", Space); 15211 verifyFormat("int f (T x) noexcept (x.create ());", Space); 15212 verifyFormat("alignas (128) char a[128];", Space); 15213 verifyFormat("size_t x = alignof (MyType);", Space); 15214 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space); 15215 verifyFormat("int f () throw (Deprecated);", Space); 15216 verifyFormat("typedef void (*cb) (int);", Space); 15217 // FIXME these tests regressed behaviour. 15218 // verifyFormat("T A::operator() ();", Space); 15219 // verifyFormat("X A::operator++ (T);", Space); 15220 verifyFormat("auto lambda = [] () { return 0; };", Space); 15221 verifyFormat("int x = int (y);", Space); 15222 verifyFormat("#define F(...) __VA_OPT__ (__VA_ARGS__)", Space); 15223 verifyFormat("__builtin_LINE ()", Space); 15224 verifyFormat("__builtin_UNKNOWN ()", Space); 15225 15226 FormatStyle SomeSpace = getLLVMStyle(); 15227 SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses; 15228 15229 verifyFormat("[]() -> float {}", SomeSpace); 15230 verifyFormat("[] (auto foo) {}", SomeSpace); 15231 verifyFormat("[foo]() -> int {}", SomeSpace); 15232 verifyFormat("int f();", SomeSpace); 15233 verifyFormat("void f (int a, T b) {\n" 15234 " while (true)\n" 15235 " continue;\n" 15236 "}", 15237 SomeSpace); 15238 verifyFormat("if (true)\n" 15239 " f();\n" 15240 "else if (true)\n" 15241 " f();", 15242 SomeSpace); 15243 verifyFormat("do {\n" 15244 " do_something();\n" 15245 "} while (something());", 15246 SomeSpace); 15247 verifyFormat("switch (x) {\n" 15248 "default:\n" 15249 " break;\n" 15250 "}", 15251 SomeSpace); 15252 verifyFormat("A::A() : a (1) {}", SomeSpace); 15253 verifyFormat("void f() __attribute__ ((asdf));", SomeSpace); 15254 verifyFormat("*(&a + 1);\n" 15255 "&((&a)[1]);\n" 15256 "a[(b + c) * d];\n" 15257 "(((a + 1) * 2) + 3) * 4;", 15258 SomeSpace); 15259 verifyFormat("#define A(x) x", SomeSpace); 15260 verifyFormat("#define A (x) x", SomeSpace); 15261 verifyFormat("#if defined(x)\n" 15262 "#endif", 15263 SomeSpace); 15264 verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace); 15265 verifyFormat("size_t x = sizeof (x);", SomeSpace); 15266 verifyFormat("auto f (int x) -> decltype (x);", SomeSpace); 15267 verifyFormat("auto f (int x) -> typeof (x);", SomeSpace); 15268 verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace); 15269 verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace); 15270 verifyFormat("int f (T x) noexcept (x.create());", SomeSpace); 15271 verifyFormat("alignas (128) char a[128];", SomeSpace); 15272 verifyFormat("size_t x = alignof (MyType);", SomeSpace); 15273 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", 15274 SomeSpace); 15275 verifyFormat("int f() throw (Deprecated);", SomeSpace); 15276 verifyFormat("typedef void (*cb) (int);", SomeSpace); 15277 verifyFormat("T A::operator()();", SomeSpace); 15278 // FIXME these tests regressed behaviour. 15279 // verifyFormat("X A::operator++ (T);", SomeSpace); 15280 verifyFormat("int x = int (y);", SomeSpace); 15281 verifyFormat("auto lambda = []() { return 0; };", SomeSpace); 15282 15283 FormatStyle SpaceControlStatements = getLLVMStyle(); 15284 SpaceControlStatements.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15285 SpaceControlStatements.SpaceBeforeParensOptions.AfterControlStatements = true; 15286 15287 verifyFormat("while (true)\n" 15288 " continue;", 15289 SpaceControlStatements); 15290 verifyFormat("if (true)\n" 15291 " f();\n" 15292 "else if (true)\n" 15293 " f();", 15294 SpaceControlStatements); 15295 verifyFormat("for (;;) {\n" 15296 " do_something();\n" 15297 "}", 15298 SpaceControlStatements); 15299 verifyFormat("do {\n" 15300 " do_something();\n" 15301 "} while (something());", 15302 SpaceControlStatements); 15303 verifyFormat("switch (x) {\n" 15304 "default:\n" 15305 " break;\n" 15306 "}", 15307 SpaceControlStatements); 15308 15309 FormatStyle SpaceFuncDecl = getLLVMStyle(); 15310 SpaceFuncDecl.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15311 SpaceFuncDecl.SpaceBeforeParensOptions.AfterFunctionDeclarationName = true; 15312 15313 verifyFormat("int f ();", SpaceFuncDecl); 15314 verifyFormat("void f(int a, T b) {}", SpaceFuncDecl); 15315 verifyFormat("A::A() : a(1) {}", SpaceFuncDecl); 15316 verifyFormat("void f () __attribute__((asdf));", SpaceFuncDecl); 15317 verifyFormat("#define A(x) x", SpaceFuncDecl); 15318 verifyFormat("#define A (x) x", SpaceFuncDecl); 15319 verifyFormat("#if defined(x)\n" 15320 "#endif", 15321 SpaceFuncDecl); 15322 verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDecl); 15323 verifyFormat("size_t x = sizeof(x);", SpaceFuncDecl); 15324 verifyFormat("auto f (int x) -> decltype(x);", SpaceFuncDecl); 15325 verifyFormat("auto f (int x) -> typeof(x);", SpaceFuncDecl); 15326 verifyFormat("auto f (int x) -> _Atomic(x);", SpaceFuncDecl); 15327 verifyFormat("auto f (int x) -> __underlying_type(x);", SpaceFuncDecl); 15328 verifyFormat("int f (T x) noexcept(x.create());", SpaceFuncDecl); 15329 verifyFormat("alignas(128) char a[128];", SpaceFuncDecl); 15330 verifyFormat("size_t x = alignof(MyType);", SpaceFuncDecl); 15331 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", 15332 SpaceFuncDecl); 15333 verifyFormat("int f () throw(Deprecated);", SpaceFuncDecl); 15334 verifyFormat("typedef void (*cb)(int);", SpaceFuncDecl); 15335 // FIXME these tests regressed behaviour. 15336 // verifyFormat("T A::operator() ();", SpaceFuncDecl); 15337 // verifyFormat("X A::operator++ (T);", SpaceFuncDecl); 15338 verifyFormat("T A::operator()() {}", SpaceFuncDecl); 15339 verifyFormat("auto lambda = []() { return 0; };", SpaceFuncDecl); 15340 verifyFormat("int x = int(y);", SpaceFuncDecl); 15341 verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}", 15342 SpaceFuncDecl); 15343 15344 FormatStyle SpaceFuncDef = getLLVMStyle(); 15345 SpaceFuncDef.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15346 SpaceFuncDef.SpaceBeforeParensOptions.AfterFunctionDefinitionName = true; 15347 15348 verifyFormat("int f();", SpaceFuncDef); 15349 verifyFormat("void f (int a, T b) {}", SpaceFuncDef); 15350 verifyFormat("A::A() : a(1) {}", SpaceFuncDef); 15351 verifyFormat("void f() __attribute__((asdf));", SpaceFuncDef); 15352 verifyFormat("#define A(x) x", SpaceFuncDef); 15353 verifyFormat("#define A (x) x", SpaceFuncDef); 15354 verifyFormat("#if defined(x)\n" 15355 "#endif", 15356 SpaceFuncDef); 15357 verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDef); 15358 verifyFormat("size_t x = sizeof(x);", SpaceFuncDef); 15359 verifyFormat("auto f(int x) -> decltype(x);", SpaceFuncDef); 15360 verifyFormat("auto f(int x) -> typeof(x);", SpaceFuncDef); 15361 verifyFormat("auto f(int x) -> _Atomic(x);", SpaceFuncDef); 15362 verifyFormat("auto f(int x) -> __underlying_type(x);", SpaceFuncDef); 15363 verifyFormat("int f(T x) noexcept(x.create());", SpaceFuncDef); 15364 verifyFormat("alignas(128) char a[128];", SpaceFuncDef); 15365 verifyFormat("size_t x = alignof(MyType);", SpaceFuncDef); 15366 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", 15367 SpaceFuncDef); 15368 verifyFormat("int f() throw(Deprecated);", SpaceFuncDef); 15369 verifyFormat("typedef void (*cb)(int);", SpaceFuncDef); 15370 verifyFormat("T A::operator()();", SpaceFuncDef); 15371 verifyFormat("X A::operator++(T);", SpaceFuncDef); 15372 // verifyFormat("T A::operator() () {}", SpaceFuncDef); 15373 verifyFormat("auto lambda = [] () { return 0; };", SpaceFuncDef); 15374 verifyFormat("int x = int(y);", SpaceFuncDef); 15375 verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}", 15376 SpaceFuncDef); 15377 15378 FormatStyle SpaceIfMacros = getLLVMStyle(); 15379 SpaceIfMacros.IfMacros.clear(); 15380 SpaceIfMacros.IfMacros.push_back("MYIF"); 15381 SpaceIfMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15382 SpaceIfMacros.SpaceBeforeParensOptions.AfterIfMacros = true; 15383 verifyFormat("MYIF (a)\n return;", SpaceIfMacros); 15384 verifyFormat("MYIF (a)\n return;\nelse MYIF (b)\n return;", SpaceIfMacros); 15385 verifyFormat("MYIF (a)\n return;\nelse\n return;", SpaceIfMacros); 15386 15387 FormatStyle SpaceForeachMacros = getLLVMStyle(); 15388 EXPECT_EQ(SpaceForeachMacros.AllowShortBlocksOnASingleLine, 15389 FormatStyle::SBS_Never); 15390 EXPECT_EQ(SpaceForeachMacros.AllowShortLoopsOnASingleLine, false); 15391 SpaceForeachMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15392 SpaceForeachMacros.SpaceBeforeParensOptions.AfterForeachMacros = true; 15393 verifyFormat("for (;;) {\n" 15394 "}", 15395 SpaceForeachMacros); 15396 verifyFormat("foreach (Item *item, itemlist) {\n" 15397 "}", 15398 SpaceForeachMacros); 15399 verifyFormat("Q_FOREACH (Item *item, itemlist) {\n" 15400 "}", 15401 SpaceForeachMacros); 15402 verifyFormat("BOOST_FOREACH (Item *item, itemlist) {\n" 15403 "}", 15404 SpaceForeachMacros); 15405 verifyFormat("UNKNOWN_FOREACH(Item *item, itemlist) {}", SpaceForeachMacros); 15406 15407 FormatStyle SomeSpace2 = getLLVMStyle(); 15408 SomeSpace2.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15409 SomeSpace2.SpaceBeforeParensOptions.BeforeNonEmptyParentheses = true; 15410 verifyFormat("[]() -> float {}", SomeSpace2); 15411 verifyFormat("[] (auto foo) {}", SomeSpace2); 15412 verifyFormat("[foo]() -> int {}", SomeSpace2); 15413 verifyFormat("int f();", SomeSpace2); 15414 verifyFormat("void f (int a, T b) {\n" 15415 " while (true)\n" 15416 " continue;\n" 15417 "}", 15418 SomeSpace2); 15419 verifyFormat("if (true)\n" 15420 " f();\n" 15421 "else if (true)\n" 15422 " f();", 15423 SomeSpace2); 15424 verifyFormat("do {\n" 15425 " do_something();\n" 15426 "} while (something());", 15427 SomeSpace2); 15428 verifyFormat("switch (x) {\n" 15429 "default:\n" 15430 " break;\n" 15431 "}", 15432 SomeSpace2); 15433 verifyFormat("A::A() : a (1) {}", SomeSpace2); 15434 verifyFormat("void f() __attribute__ ((asdf));", SomeSpace2); 15435 verifyFormat("*(&a + 1);\n" 15436 "&((&a)[1]);\n" 15437 "a[(b + c) * d];\n" 15438 "(((a + 1) * 2) + 3) * 4;", 15439 SomeSpace2); 15440 verifyFormat("#define A(x) x", SomeSpace2); 15441 verifyFormat("#define A (x) x", SomeSpace2); 15442 verifyFormat("#if defined(x)\n" 15443 "#endif", 15444 SomeSpace2); 15445 verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace2); 15446 verifyFormat("size_t x = sizeof (x);", SomeSpace2); 15447 verifyFormat("auto f (int x) -> decltype (x);", SomeSpace2); 15448 verifyFormat("auto f (int x) -> typeof (x);", SomeSpace2); 15449 verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace2); 15450 verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace2); 15451 verifyFormat("int f (T x) noexcept (x.create());", SomeSpace2); 15452 verifyFormat("alignas (128) char a[128];", SomeSpace2); 15453 verifyFormat("size_t x = alignof (MyType);", SomeSpace2); 15454 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", 15455 SomeSpace2); 15456 verifyFormat("int f() throw (Deprecated);", SomeSpace2); 15457 verifyFormat("typedef void (*cb) (int);", SomeSpace2); 15458 verifyFormat("T A::operator()();", SomeSpace2); 15459 // verifyFormat("X A::operator++ (T);", SomeSpace2); 15460 verifyFormat("int x = int (y);", SomeSpace2); 15461 verifyFormat("auto lambda = []() { return 0; };", SomeSpace2); 15462 15463 FormatStyle SpaceAfterOverloadedOperator = getLLVMStyle(); 15464 SpaceAfterOverloadedOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15465 SpaceAfterOverloadedOperator.SpaceBeforeParensOptions 15466 .AfterOverloadedOperator = true; 15467 15468 verifyFormat("auto operator++ () -> int;", SpaceAfterOverloadedOperator); 15469 verifyFormat("X A::operator++ ();", SpaceAfterOverloadedOperator); 15470 verifyFormat("some_object.operator++ ();", SpaceAfterOverloadedOperator); 15471 verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator); 15472 15473 SpaceAfterOverloadedOperator.SpaceBeforeParensOptions 15474 .AfterOverloadedOperator = false; 15475 15476 verifyFormat("auto operator++() -> int;", SpaceAfterOverloadedOperator); 15477 verifyFormat("X A::operator++();", SpaceAfterOverloadedOperator); 15478 verifyFormat("some_object.operator++();", SpaceAfterOverloadedOperator); 15479 verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator); 15480 15481 auto SpaceAfterRequires = getLLVMStyle(); 15482 SpaceAfterRequires.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15483 EXPECT_FALSE( 15484 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause); 15485 EXPECT_FALSE( 15486 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression); 15487 verifyFormat("void f(auto x)\n" 15488 " requires requires(int i) { x + i; }\n" 15489 "{}", 15490 SpaceAfterRequires); 15491 verifyFormat("void f(auto x)\n" 15492 " requires(requires(int i) { x + i; })\n" 15493 "{}", 15494 SpaceAfterRequires); 15495 verifyFormat("if (requires(int i) { x + i; })\n" 15496 " return;", 15497 SpaceAfterRequires); 15498 verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires); 15499 verifyFormat("template <typename T>\n" 15500 " requires(Foo<T>)\n" 15501 "class Bar;", 15502 SpaceAfterRequires); 15503 15504 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true; 15505 verifyFormat("void f(auto x)\n" 15506 " requires requires(int i) { x + i; }\n" 15507 "{}", 15508 SpaceAfterRequires); 15509 verifyFormat("void f(auto x)\n" 15510 " requires (requires(int i) { x + i; })\n" 15511 "{}", 15512 SpaceAfterRequires); 15513 verifyFormat("if (requires(int i) { x + i; })\n" 15514 " return;", 15515 SpaceAfterRequires); 15516 verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires); 15517 verifyFormat("template <typename T>\n" 15518 " requires (Foo<T>)\n" 15519 "class Bar;", 15520 SpaceAfterRequires); 15521 15522 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = false; 15523 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression = true; 15524 verifyFormat("void f(auto x)\n" 15525 " requires requires (int i) { x + i; }\n" 15526 "{}", 15527 SpaceAfterRequires); 15528 verifyFormat("void f(auto x)\n" 15529 " requires(requires (int i) { x + i; })\n" 15530 "{}", 15531 SpaceAfterRequires); 15532 verifyFormat("if (requires (int i) { x + i; })\n" 15533 " return;", 15534 SpaceAfterRequires); 15535 verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires); 15536 verifyFormat("template <typename T>\n" 15537 " requires(Foo<T>)\n" 15538 "class Bar;", 15539 SpaceAfterRequires); 15540 15541 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true; 15542 verifyFormat("void f(auto x)\n" 15543 " requires requires (int i) { x + i; }\n" 15544 "{}", 15545 SpaceAfterRequires); 15546 verifyFormat("void f(auto x)\n" 15547 " requires (requires (int i) { x + i; })\n" 15548 "{}", 15549 SpaceAfterRequires); 15550 verifyFormat("if (requires (int i) { x + i; })\n" 15551 " return;", 15552 SpaceAfterRequires); 15553 verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires); 15554 verifyFormat("template <typename T>\n" 15555 " requires (Foo<T>)\n" 15556 "class Bar;", 15557 SpaceAfterRequires); 15558 } 15559 15560 TEST_F(FormatTest, SpaceAfterLogicalNot) { 15561 FormatStyle Spaces = getLLVMStyle(); 15562 Spaces.SpaceAfterLogicalNot = true; 15563 15564 verifyFormat("bool x = ! y", Spaces); 15565 verifyFormat("if (! isFailure())", Spaces); 15566 verifyFormat("if (! (a && b))", Spaces); 15567 verifyFormat("\"Error!\"", Spaces); 15568 verifyFormat("! ! x", Spaces); 15569 } 15570 15571 TEST_F(FormatTest, ConfigurableSpacesInParentheses) { 15572 FormatStyle Spaces = getLLVMStyle(); 15573 15574 Spaces.SpacesInParentheses = true; 15575 verifyFormat("do_something( ::globalVar );", Spaces); 15576 verifyFormat("call( x, y, z );", Spaces); 15577 verifyFormat("call();", Spaces); 15578 verifyFormat("std::function<void( int, int )> callback;", Spaces); 15579 verifyFormat("void inFunction() { std::function<void( int, int )> fct; }", 15580 Spaces); 15581 verifyFormat("while ( (bool)1 )\n" 15582 " continue;", 15583 Spaces); 15584 verifyFormat("for ( ;; )\n" 15585 " continue;", 15586 Spaces); 15587 verifyFormat("if ( true )\n" 15588 " f();\n" 15589 "else if ( true )\n" 15590 " f();", 15591 Spaces); 15592 verifyFormat("do {\n" 15593 " do_something( (int)i );\n" 15594 "} while ( something() );", 15595 Spaces); 15596 verifyFormat("switch ( x ) {\n" 15597 "default:\n" 15598 " break;\n" 15599 "}", 15600 Spaces); 15601 15602 Spaces.SpacesInParentheses = false; 15603 Spaces.SpacesInCStyleCastParentheses = true; 15604 verifyFormat("Type *A = ( Type * )P;", Spaces); 15605 verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces); 15606 verifyFormat("x = ( int32 )y;", Spaces); 15607 verifyFormat("int a = ( int )(2.0f);", Spaces); 15608 verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces); 15609 verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces); 15610 verifyFormat("#define x (( int )-1)", Spaces); 15611 15612 // Run the first set of tests again with: 15613 Spaces.SpacesInParentheses = false; 15614 Spaces.SpaceInEmptyParentheses = true; 15615 Spaces.SpacesInCStyleCastParentheses = true; 15616 verifyFormat("call(x, y, z);", Spaces); 15617 verifyFormat("call( );", Spaces); 15618 verifyFormat("std::function<void(int, int)> callback;", Spaces); 15619 verifyFormat("while (( bool )1)\n" 15620 " continue;", 15621 Spaces); 15622 verifyFormat("for (;;)\n" 15623 " continue;", 15624 Spaces); 15625 verifyFormat("if (true)\n" 15626 " f( );\n" 15627 "else if (true)\n" 15628 " f( );", 15629 Spaces); 15630 verifyFormat("do {\n" 15631 " do_something(( int )i);\n" 15632 "} while (something( ));", 15633 Spaces); 15634 verifyFormat("switch (x) {\n" 15635 "default:\n" 15636 " break;\n" 15637 "}", 15638 Spaces); 15639 15640 // Run the first set of tests again with: 15641 Spaces.SpaceAfterCStyleCast = true; 15642 verifyFormat("call(x, y, z);", Spaces); 15643 verifyFormat("call( );", Spaces); 15644 verifyFormat("std::function<void(int, int)> callback;", Spaces); 15645 verifyFormat("while (( bool ) 1)\n" 15646 " continue;", 15647 Spaces); 15648 verifyFormat("for (;;)\n" 15649 " continue;", 15650 Spaces); 15651 verifyFormat("if (true)\n" 15652 " f( );\n" 15653 "else if (true)\n" 15654 " f( );", 15655 Spaces); 15656 verifyFormat("do {\n" 15657 " do_something(( int ) i);\n" 15658 "} while (something( ));", 15659 Spaces); 15660 verifyFormat("switch (x) {\n" 15661 "default:\n" 15662 " break;\n" 15663 "}", 15664 Spaces); 15665 verifyFormat("#define CONF_BOOL(x) ( bool * ) ( void * ) (x)", Spaces); 15666 verifyFormat("#define CONF_BOOL(x) ( bool * ) (x)", Spaces); 15667 verifyFormat("#define CONF_BOOL(x) ( bool ) (x)", Spaces); 15668 verifyFormat("bool *y = ( bool * ) ( void * ) (x);", Spaces); 15669 verifyFormat("bool *y = ( bool * ) (x);", Spaces); 15670 15671 // Run subset of tests again with: 15672 Spaces.SpacesInCStyleCastParentheses = false; 15673 Spaces.SpaceAfterCStyleCast = true; 15674 verifyFormat("while ((bool) 1)\n" 15675 " continue;", 15676 Spaces); 15677 verifyFormat("do {\n" 15678 " do_something((int) i);\n" 15679 "} while (something( ));", 15680 Spaces); 15681 15682 verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces); 15683 verifyFormat("size_t idx = (size_t) a;", Spaces); 15684 verifyFormat("size_t idx = (size_t) (a - 1);", Spaces); 15685 verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces); 15686 verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces); 15687 verifyFormat("size_t idx = (*foo)(a - 1);", Spaces); 15688 verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces); 15689 verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (x)", Spaces); 15690 verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (int) (x)", Spaces); 15691 verifyFormat("bool *y = (bool *) (void *) (x);", Spaces); 15692 verifyFormat("bool *y = (bool *) (void *) (int) (x);", Spaces); 15693 verifyFormat("bool *y = (bool *) (void *) (int) foo(x);", Spaces); 15694 Spaces.ColumnLimit = 80; 15695 Spaces.IndentWidth = 4; 15696 Spaces.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 15697 verifyFormat("void foo( ) {\n" 15698 " size_t foo = (*(function))(\n" 15699 " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, " 15700 "BarrrrrrrrrrrrLong,\n" 15701 " FoooooooooLooooong);\n" 15702 "}", 15703 Spaces); 15704 Spaces.SpaceAfterCStyleCast = false; 15705 verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces); 15706 verifyFormat("size_t idx = (size_t)a;", Spaces); 15707 verifyFormat("size_t idx = (size_t)(a - 1);", Spaces); 15708 verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces); 15709 verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces); 15710 verifyFormat("size_t idx = (*foo)(a - 1);", Spaces); 15711 verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces); 15712 15713 verifyFormat("void foo( ) {\n" 15714 " size_t foo = (*(function))(\n" 15715 " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, " 15716 "BarrrrrrrrrrrrLong,\n" 15717 " FoooooooooLooooong);\n" 15718 "}", 15719 Spaces); 15720 } 15721 15722 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) { 15723 verifyFormat("int a[5];"); 15724 verifyFormat("a[3] += 42;"); 15725 15726 FormatStyle Spaces = getLLVMStyle(); 15727 Spaces.SpacesInSquareBrackets = true; 15728 // Not lambdas. 15729 verifyFormat("int a[ 5 ];", Spaces); 15730 verifyFormat("a[ 3 ] += 42;", Spaces); 15731 verifyFormat("constexpr char hello[]{\"hello\"};", Spaces); 15732 verifyFormat("double &operator[](int i) { return 0; }\n" 15733 "int i;", 15734 Spaces); 15735 verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces); 15736 verifyFormat("int i = a[ a ][ a ]->f();", Spaces); 15737 verifyFormat("int i = (*b)[ a ]->f();", Spaces); 15738 // Lambdas. 15739 verifyFormat("int c = []() -> int { return 2; }();\n", Spaces); 15740 verifyFormat("return [ i, args... ] {};", Spaces); 15741 verifyFormat("int foo = [ &bar ]() {};", Spaces); 15742 verifyFormat("int foo = [ = ]() {};", Spaces); 15743 verifyFormat("int foo = [ & ]() {};", Spaces); 15744 verifyFormat("int foo = [ =, &bar ]() {};", Spaces); 15745 verifyFormat("int foo = [ &bar, = ]() {};", Spaces); 15746 } 15747 15748 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) { 15749 FormatStyle NoSpaceStyle = getLLVMStyle(); 15750 verifyFormat("int a[5];", NoSpaceStyle); 15751 verifyFormat("a[3] += 42;", NoSpaceStyle); 15752 15753 verifyFormat("int a[1];", NoSpaceStyle); 15754 verifyFormat("int 1 [a];", NoSpaceStyle); 15755 verifyFormat("int a[1][2];", NoSpaceStyle); 15756 verifyFormat("a[7] = 5;", NoSpaceStyle); 15757 verifyFormat("int a = (f())[23];", NoSpaceStyle); 15758 verifyFormat("f([] {})", NoSpaceStyle); 15759 15760 FormatStyle Space = getLLVMStyle(); 15761 Space.SpaceBeforeSquareBrackets = true; 15762 verifyFormat("int c = []() -> int { return 2; }();\n", Space); 15763 verifyFormat("return [i, args...] {};", Space); 15764 15765 verifyFormat("int a [5];", Space); 15766 verifyFormat("a [3] += 42;", Space); 15767 verifyFormat("constexpr char hello []{\"hello\"};", Space); 15768 verifyFormat("double &operator[](int i) { return 0; }\n" 15769 "int i;", 15770 Space); 15771 verifyFormat("std::unique_ptr<int []> foo() {}", Space); 15772 verifyFormat("int i = a [a][a]->f();", Space); 15773 verifyFormat("int i = (*b) [a]->f();", Space); 15774 15775 verifyFormat("int a [1];", Space); 15776 verifyFormat("int 1 [a];", Space); 15777 verifyFormat("int a [1][2];", Space); 15778 verifyFormat("a [7] = 5;", Space); 15779 verifyFormat("int a = (f()) [23];", Space); 15780 verifyFormat("f([] {})", Space); 15781 } 15782 15783 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) { 15784 verifyFormat("int a = 5;"); 15785 verifyFormat("a += 42;"); 15786 verifyFormat("a or_eq 8;"); 15787 15788 FormatStyle Spaces = getLLVMStyle(); 15789 Spaces.SpaceBeforeAssignmentOperators = false; 15790 verifyFormat("int a= 5;", Spaces); 15791 verifyFormat("a+= 42;", Spaces); 15792 verifyFormat("a or_eq 8;", Spaces); 15793 } 15794 15795 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) { 15796 verifyFormat("class Foo : public Bar {};"); 15797 verifyFormat("Foo::Foo() : foo(1) {}"); 15798 verifyFormat("for (auto a : b) {\n}"); 15799 verifyFormat("int x = a ? b : c;"); 15800 verifyFormat("{\n" 15801 "label0:\n" 15802 " int x = 0;\n" 15803 "}"); 15804 verifyFormat("switch (x) {\n" 15805 "case 1:\n" 15806 "default:\n" 15807 "}"); 15808 verifyFormat("switch (allBraces) {\n" 15809 "case 1: {\n" 15810 " break;\n" 15811 "}\n" 15812 "case 2: {\n" 15813 " [[fallthrough]];\n" 15814 "}\n" 15815 "default: {\n" 15816 " break;\n" 15817 "}\n" 15818 "}"); 15819 15820 FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30); 15821 CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false; 15822 verifyFormat("class Foo : public Bar {};", CtorInitializerStyle); 15823 verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle); 15824 verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle); 15825 verifyFormat("int x = a ? b : c;", CtorInitializerStyle); 15826 verifyFormat("{\n" 15827 "label1:\n" 15828 " int x = 0;\n" 15829 "}", 15830 CtorInitializerStyle); 15831 verifyFormat("switch (x) {\n" 15832 "case 1:\n" 15833 "default:\n" 15834 "}", 15835 CtorInitializerStyle); 15836 verifyFormat("switch (allBraces) {\n" 15837 "case 1: {\n" 15838 " break;\n" 15839 "}\n" 15840 "case 2: {\n" 15841 " [[fallthrough]];\n" 15842 "}\n" 15843 "default: {\n" 15844 " break;\n" 15845 "}\n" 15846 "}", 15847 CtorInitializerStyle); 15848 CtorInitializerStyle.BreakConstructorInitializers = 15849 FormatStyle::BCIS_AfterColon; 15850 verifyFormat("Fooooooooooo::Fooooooooooo():\n" 15851 " aaaaaaaaaaaaaaaa(1),\n" 15852 " bbbbbbbbbbbbbbbb(2) {}", 15853 CtorInitializerStyle); 15854 CtorInitializerStyle.BreakConstructorInitializers = 15855 FormatStyle::BCIS_BeforeComma; 15856 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15857 " : aaaaaaaaaaaaaaaa(1)\n" 15858 " , bbbbbbbbbbbbbbbb(2) {}", 15859 CtorInitializerStyle); 15860 CtorInitializerStyle.BreakConstructorInitializers = 15861 FormatStyle::BCIS_BeforeColon; 15862 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15863 " : aaaaaaaaaaaaaaaa(1),\n" 15864 " bbbbbbbbbbbbbbbb(2) {}", 15865 CtorInitializerStyle); 15866 CtorInitializerStyle.ConstructorInitializerIndentWidth = 0; 15867 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15868 ": aaaaaaaaaaaaaaaa(1),\n" 15869 " bbbbbbbbbbbbbbbb(2) {}", 15870 CtorInitializerStyle); 15871 15872 FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30); 15873 InheritanceStyle.SpaceBeforeInheritanceColon = false; 15874 verifyFormat("class Foo: public Bar {};", InheritanceStyle); 15875 verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle); 15876 verifyFormat("for (auto a : b) {\n}", InheritanceStyle); 15877 verifyFormat("int x = a ? b : c;", InheritanceStyle); 15878 verifyFormat("{\n" 15879 "label2:\n" 15880 " int x = 0;\n" 15881 "}", 15882 InheritanceStyle); 15883 verifyFormat("switch (x) {\n" 15884 "case 1:\n" 15885 "default:\n" 15886 "}", 15887 InheritanceStyle); 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 InheritanceStyle); 15900 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterComma; 15901 verifyFormat("class Foooooooooooooooooooooo\n" 15902 " : public aaaaaaaaaaaaaaaaaa,\n" 15903 " public bbbbbbbbbbbbbbbbbb {\n" 15904 "}", 15905 InheritanceStyle); 15906 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon; 15907 verifyFormat("class Foooooooooooooooooooooo:\n" 15908 " public aaaaaaaaaaaaaaaaaa,\n" 15909 " public bbbbbbbbbbbbbbbbbb {\n" 15910 "}", 15911 InheritanceStyle); 15912 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma; 15913 verifyFormat("class Foooooooooooooooooooooo\n" 15914 " : public aaaaaaaaaaaaaaaaaa\n" 15915 " , public bbbbbbbbbbbbbbbbbb {\n" 15916 "}", 15917 InheritanceStyle); 15918 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 15919 verifyFormat("class Foooooooooooooooooooooo\n" 15920 " : public aaaaaaaaaaaaaaaaaa,\n" 15921 " public bbbbbbbbbbbbbbbbbb {\n" 15922 "}", 15923 InheritanceStyle); 15924 InheritanceStyle.ConstructorInitializerIndentWidth = 0; 15925 verifyFormat("class Foooooooooooooooooooooo\n" 15926 ": public aaaaaaaaaaaaaaaaaa,\n" 15927 " public bbbbbbbbbbbbbbbbbb {}", 15928 InheritanceStyle); 15929 15930 FormatStyle ForLoopStyle = getLLVMStyle(); 15931 ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false; 15932 verifyFormat("class Foo : public Bar {};", ForLoopStyle); 15933 verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle); 15934 verifyFormat("for (auto a: b) {\n}", ForLoopStyle); 15935 verifyFormat("int x = a ? b : c;", ForLoopStyle); 15936 verifyFormat("{\n" 15937 "label2:\n" 15938 " int x = 0;\n" 15939 "}", 15940 ForLoopStyle); 15941 verifyFormat("switch (x) {\n" 15942 "case 1:\n" 15943 "default:\n" 15944 "}", 15945 ForLoopStyle); 15946 verifyFormat("switch (allBraces) {\n" 15947 "case 1: {\n" 15948 " break;\n" 15949 "}\n" 15950 "case 2: {\n" 15951 " [[fallthrough]];\n" 15952 "}\n" 15953 "default: {\n" 15954 " break;\n" 15955 "}\n" 15956 "}", 15957 ForLoopStyle); 15958 15959 FormatStyle CaseStyle = getLLVMStyle(); 15960 CaseStyle.SpaceBeforeCaseColon = true; 15961 verifyFormat("class Foo : public Bar {};", CaseStyle); 15962 verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle); 15963 verifyFormat("for (auto a : b) {\n}", CaseStyle); 15964 verifyFormat("int x = a ? b : c;", CaseStyle); 15965 verifyFormat("switch (x) {\n" 15966 "case 1 :\n" 15967 "default :\n" 15968 "}", 15969 CaseStyle); 15970 verifyFormat("switch (allBraces) {\n" 15971 "case 1 : {\n" 15972 " break;\n" 15973 "}\n" 15974 "case 2 : {\n" 15975 " [[fallthrough]];\n" 15976 "}\n" 15977 "default : {\n" 15978 " break;\n" 15979 "}\n" 15980 "}", 15981 CaseStyle); 15982 15983 FormatStyle NoSpaceStyle = getLLVMStyle(); 15984 EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false); 15985 NoSpaceStyle.SpaceBeforeCtorInitializerColon = false; 15986 NoSpaceStyle.SpaceBeforeInheritanceColon = false; 15987 NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false; 15988 verifyFormat("class Foo: public Bar {};", NoSpaceStyle); 15989 verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle); 15990 verifyFormat("for (auto a: b) {\n}", NoSpaceStyle); 15991 verifyFormat("int x = a ? b : c;", NoSpaceStyle); 15992 verifyFormat("{\n" 15993 "label3:\n" 15994 " int x = 0;\n" 15995 "}", 15996 NoSpaceStyle); 15997 verifyFormat("switch (x) {\n" 15998 "case 1:\n" 15999 "default:\n" 16000 "}", 16001 NoSpaceStyle); 16002 verifyFormat("switch (allBraces) {\n" 16003 "case 1: {\n" 16004 " break;\n" 16005 "}\n" 16006 "case 2: {\n" 16007 " [[fallthrough]];\n" 16008 "}\n" 16009 "default: {\n" 16010 " break;\n" 16011 "}\n" 16012 "}", 16013 NoSpaceStyle); 16014 16015 FormatStyle InvertedSpaceStyle = getLLVMStyle(); 16016 InvertedSpaceStyle.SpaceBeforeCaseColon = true; 16017 InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false; 16018 InvertedSpaceStyle.SpaceBeforeInheritanceColon = false; 16019 InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false; 16020 verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle); 16021 verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle); 16022 verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle); 16023 verifyFormat("int x = a ? b : c;", InvertedSpaceStyle); 16024 verifyFormat("{\n" 16025 "label3:\n" 16026 " int x = 0;\n" 16027 "}", 16028 InvertedSpaceStyle); 16029 verifyFormat("switch (x) {\n" 16030 "case 1 :\n" 16031 "case 2 : {\n" 16032 " break;\n" 16033 "}\n" 16034 "default :\n" 16035 " break;\n" 16036 "}", 16037 InvertedSpaceStyle); 16038 verifyFormat("switch (allBraces) {\n" 16039 "case 1 : {\n" 16040 " break;\n" 16041 "}\n" 16042 "case 2 : {\n" 16043 " [[fallthrough]];\n" 16044 "}\n" 16045 "default : {\n" 16046 " break;\n" 16047 "}\n" 16048 "}", 16049 InvertedSpaceStyle); 16050 } 16051 16052 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) { 16053 FormatStyle Style = getLLVMStyle(); 16054 16055 Style.PointerAlignment = FormatStyle::PAS_Left; 16056 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default; 16057 verifyFormat("void* const* x = NULL;", Style); 16058 16059 #define verifyQualifierSpaces(Code, Pointers, Qualifiers) \ 16060 do { \ 16061 Style.PointerAlignment = FormatStyle::Pointers; \ 16062 Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers; \ 16063 verifyFormat(Code, Style); \ 16064 } while (false) 16065 16066 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default); 16067 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default); 16068 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default); 16069 16070 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before); 16071 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before); 16072 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before); 16073 16074 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After); 16075 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After); 16076 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After); 16077 16078 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both); 16079 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both); 16080 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both); 16081 16082 verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default); 16083 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, 16084 SAPQ_Default); 16085 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 16086 SAPQ_Default); 16087 16088 verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before); 16089 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, 16090 SAPQ_Before); 16091 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 16092 SAPQ_Before); 16093 16094 verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After); 16095 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After); 16096 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 16097 SAPQ_After); 16098 16099 verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both); 16100 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both); 16101 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both); 16102 16103 #undef verifyQualifierSpaces 16104 16105 FormatStyle Spaces = getLLVMStyle(); 16106 Spaces.AttributeMacros.push_back("qualified"); 16107 Spaces.PointerAlignment = FormatStyle::PAS_Right; 16108 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default; 16109 verifyFormat("SomeType *volatile *a = NULL;", Spaces); 16110 verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces); 16111 verifyFormat("std::vector<SomeType *const *> x;", Spaces); 16112 verifyFormat("std::vector<SomeType *qualified *> x;", Spaces); 16113 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 16114 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before; 16115 verifyFormat("SomeType * volatile *a = NULL;", Spaces); 16116 verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces); 16117 verifyFormat("std::vector<SomeType * const *> x;", Spaces); 16118 verifyFormat("std::vector<SomeType * qualified *> x;", Spaces); 16119 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 16120 16121 // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left. 16122 Spaces.PointerAlignment = FormatStyle::PAS_Left; 16123 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before; 16124 verifyFormat("SomeType* volatile* a = NULL;", Spaces); 16125 verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces); 16126 verifyFormat("std::vector<SomeType* const*> x;", Spaces); 16127 verifyFormat("std::vector<SomeType* qualified*> x;", Spaces); 16128 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 16129 // However, setting it to SAPQ_After should add spaces after __attribute, etc. 16130 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After; 16131 verifyFormat("SomeType* volatile * a = NULL;", Spaces); 16132 verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces); 16133 verifyFormat("std::vector<SomeType* const *> x;", Spaces); 16134 verifyFormat("std::vector<SomeType* qualified *> x;", Spaces); 16135 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 16136 16137 // PAS_Middle should not have any noticeable changes even for SAPQ_Both 16138 Spaces.PointerAlignment = FormatStyle::PAS_Middle; 16139 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After; 16140 verifyFormat("SomeType * volatile * a = NULL;", Spaces); 16141 verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces); 16142 verifyFormat("std::vector<SomeType * const *> x;", Spaces); 16143 verifyFormat("std::vector<SomeType * qualified *> x;", Spaces); 16144 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 16145 } 16146 16147 TEST_F(FormatTest, AlignConsecutiveMacros) { 16148 FormatStyle Style = getLLVMStyle(); 16149 Style.AlignConsecutiveAssignments.Enabled = true; 16150 Style.AlignConsecutiveDeclarations.Enabled = true; 16151 16152 verifyFormat("#define a 3\n" 16153 "#define bbbb 4\n" 16154 "#define ccc (5)", 16155 Style); 16156 16157 verifyFormat("#define f(x) (x * x)\n" 16158 "#define fff(x, y, z) (x * y + z)\n" 16159 "#define ffff(x, y) (x - y)", 16160 Style); 16161 16162 verifyFormat("#define foo(x, y) (x + y)\n" 16163 "#define bar (5, 6)(2 + 2)", 16164 Style); 16165 16166 verifyFormat("#define a 3\n" 16167 "#define bbbb 4\n" 16168 "#define ccc (5)\n" 16169 "#define f(x) (x * x)\n" 16170 "#define fff(x, y, z) (x * y + z)\n" 16171 "#define ffff(x, y) (x - y)", 16172 Style); 16173 16174 Style.AlignConsecutiveMacros.Enabled = true; 16175 verifyFormat("#define a 3\n" 16176 "#define bbbb 4\n" 16177 "#define ccc (5)", 16178 Style); 16179 16180 verifyFormat("#define true 1\n" 16181 "#define false 0", 16182 Style); 16183 16184 verifyFormat("#define f(x) (x * x)\n" 16185 "#define fff(x, y, z) (x * y + z)\n" 16186 "#define ffff(x, y) (x - y)", 16187 Style); 16188 16189 verifyFormat("#define foo(x, y) (x + y)\n" 16190 "#define bar (5, 6)(2 + 2)", 16191 Style); 16192 16193 verifyFormat("#define a 3\n" 16194 "#define bbbb 4\n" 16195 "#define ccc (5)\n" 16196 "#define f(x) (x * x)\n" 16197 "#define fff(x, y, z) (x * y + z)\n" 16198 "#define ffff(x, y) (x - y)", 16199 Style); 16200 16201 verifyFormat("#define a 5\n" 16202 "#define foo(x, y) (x + y)\n" 16203 "#define CCC (6)\n" 16204 "auto lambda = []() {\n" 16205 " auto ii = 0;\n" 16206 " float j = 0;\n" 16207 " return 0;\n" 16208 "};\n" 16209 "int i = 0;\n" 16210 "float i2 = 0;\n" 16211 "auto v = type{\n" 16212 " i = 1, //\n" 16213 " (i = 2), //\n" 16214 " i = 3 //\n" 16215 "};", 16216 Style); 16217 16218 Style.AlignConsecutiveMacros.Enabled = false; 16219 Style.ColumnLimit = 20; 16220 16221 verifyFormat("#define a \\\n" 16222 " \"aabbbbbbbbbbbb\"\n" 16223 "#define D \\\n" 16224 " \"aabbbbbbbbbbbb\" \\\n" 16225 " \"ccddeeeeeeeee\"\n" 16226 "#define B \\\n" 16227 " \"QQQQQQQQQQQQQ\" \\\n" 16228 " \"FFFFFFFFFFFFF\" \\\n" 16229 " \"LLLLLLLL\"\n", 16230 Style); 16231 16232 Style.AlignConsecutiveMacros.Enabled = true; 16233 verifyFormat("#define a \\\n" 16234 " \"aabbbbbbbbbbbb\"\n" 16235 "#define D \\\n" 16236 " \"aabbbbbbbbbbbb\" \\\n" 16237 " \"ccddeeeeeeeee\"\n" 16238 "#define B \\\n" 16239 " \"QQQQQQQQQQQQQ\" \\\n" 16240 " \"FFFFFFFFFFFFF\" \\\n" 16241 " \"LLLLLLLL\"\n", 16242 Style); 16243 16244 // Test across comments 16245 Style.MaxEmptyLinesToKeep = 10; 16246 Style.ReflowComments = false; 16247 Style.AlignConsecutiveMacros.AcrossComments = true; 16248 EXPECT_EQ("#define a 3\n" 16249 "// line comment\n" 16250 "#define bbbb 4\n" 16251 "#define ccc (5)", 16252 format("#define a 3\n" 16253 "// line comment\n" 16254 "#define bbbb 4\n" 16255 "#define ccc (5)", 16256 Style)); 16257 16258 EXPECT_EQ("#define a 3\n" 16259 "/* block comment */\n" 16260 "#define bbbb 4\n" 16261 "#define ccc (5)", 16262 format("#define a 3\n" 16263 "/* block comment */\n" 16264 "#define bbbb 4\n" 16265 "#define ccc (5)", 16266 Style)); 16267 16268 EXPECT_EQ("#define a 3\n" 16269 "/* multi-line *\n" 16270 " * block comment */\n" 16271 "#define bbbb 4\n" 16272 "#define ccc (5)", 16273 format("#define a 3\n" 16274 "/* multi-line *\n" 16275 " * block comment */\n" 16276 "#define bbbb 4\n" 16277 "#define ccc (5)", 16278 Style)); 16279 16280 EXPECT_EQ("#define a 3\n" 16281 "// multi-line line comment\n" 16282 "//\n" 16283 "#define bbbb 4\n" 16284 "#define ccc (5)", 16285 format("#define a 3\n" 16286 "// multi-line line comment\n" 16287 "//\n" 16288 "#define bbbb 4\n" 16289 "#define ccc (5)", 16290 Style)); 16291 16292 EXPECT_EQ("#define a 3\n" 16293 "// empty lines still break.\n" 16294 "\n" 16295 "#define bbbb 4\n" 16296 "#define ccc (5)", 16297 format("#define a 3\n" 16298 "// empty lines still break.\n" 16299 "\n" 16300 "#define bbbb 4\n" 16301 "#define ccc (5)", 16302 Style)); 16303 16304 // Test across empty lines 16305 Style.AlignConsecutiveMacros.AcrossComments = false; 16306 Style.AlignConsecutiveMacros.AcrossEmptyLines = true; 16307 EXPECT_EQ("#define a 3\n" 16308 "\n" 16309 "#define bbbb 4\n" 16310 "#define ccc (5)", 16311 format("#define a 3\n" 16312 "\n" 16313 "#define bbbb 4\n" 16314 "#define ccc (5)", 16315 Style)); 16316 16317 EXPECT_EQ("#define a 3\n" 16318 "\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 "\n" 16327 "#define bbbb 4\n" 16328 "#define ccc (5)", 16329 Style)); 16330 16331 EXPECT_EQ("#define a 3\n" 16332 "// comments should break alignment\n" 16333 "//\n" 16334 "#define bbbb 4\n" 16335 "#define ccc (5)", 16336 format("#define a 3\n" 16337 "// comments should break alignment\n" 16338 "//\n" 16339 "#define bbbb 4\n" 16340 "#define ccc (5)", 16341 Style)); 16342 16343 // Test across empty lines and comments 16344 Style.AlignConsecutiveMacros.AcrossComments = true; 16345 verifyFormat("#define a 3\n" 16346 "\n" 16347 "// line comment\n" 16348 "#define bbbb 4\n" 16349 "#define ccc (5)", 16350 Style); 16351 16352 EXPECT_EQ("#define a 3\n" 16353 "\n" 16354 "\n" 16355 "/* multi-line *\n" 16356 " * block comment */\n" 16357 "\n" 16358 "\n" 16359 "#define bbbb 4\n" 16360 "#define ccc (5)", 16361 format("#define a 3\n" 16362 "\n" 16363 "\n" 16364 "/* multi-line *\n" 16365 " * block comment */\n" 16366 "\n" 16367 "\n" 16368 "#define bbbb 4\n" 16369 "#define ccc (5)", 16370 Style)); 16371 16372 EXPECT_EQ("#define a 3\n" 16373 "\n" 16374 "\n" 16375 "/* multi-line *\n" 16376 " * block comment */\n" 16377 "\n" 16378 "\n" 16379 "#define bbbb 4\n" 16380 "#define ccc (5)", 16381 format("#define a 3\n" 16382 "\n" 16383 "\n" 16384 "/* multi-line *\n" 16385 " * block comment */\n" 16386 "\n" 16387 "\n" 16388 "#define bbbb 4\n" 16389 "#define ccc (5)", 16390 Style)); 16391 } 16392 16393 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) { 16394 FormatStyle Alignment = getLLVMStyle(); 16395 Alignment.AlignConsecutiveMacros.Enabled = true; 16396 Alignment.AlignConsecutiveAssignments.Enabled = true; 16397 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true; 16398 16399 Alignment.MaxEmptyLinesToKeep = 10; 16400 /* Test alignment across empty lines */ 16401 EXPECT_EQ("int a = 5;\n" 16402 "\n" 16403 "int oneTwoThree = 123;", 16404 format("int a = 5;\n" 16405 "\n" 16406 "int oneTwoThree= 123;", 16407 Alignment)); 16408 EXPECT_EQ("int a = 5;\n" 16409 "int one = 1;\n" 16410 "\n" 16411 "int oneTwoThree = 123;", 16412 format("int a = 5;\n" 16413 "int one = 1;\n" 16414 "\n" 16415 "int oneTwoThree = 123;", 16416 Alignment)); 16417 EXPECT_EQ("int a = 5;\n" 16418 "int one = 1;\n" 16419 "\n" 16420 "int oneTwoThree = 123;\n" 16421 "int oneTwo = 12;", 16422 format("int a = 5;\n" 16423 "int one = 1;\n" 16424 "\n" 16425 "int oneTwoThree = 123;\n" 16426 "int oneTwo = 12;", 16427 Alignment)); 16428 16429 /* Test across comments */ 16430 EXPECT_EQ("int a = 5;\n" 16431 "/* block comment */\n" 16432 "int oneTwoThree = 123;", 16433 format("int a = 5;\n" 16434 "/* block comment */\n" 16435 "int oneTwoThree=123;", 16436 Alignment)); 16437 16438 EXPECT_EQ("int a = 5;\n" 16439 "// line comment\n" 16440 "int oneTwoThree = 123;", 16441 format("int a = 5;\n" 16442 "// line comment\n" 16443 "int oneTwoThree=123;", 16444 Alignment)); 16445 16446 /* Test across comments and newlines */ 16447 EXPECT_EQ("int a = 5;\n" 16448 "\n" 16449 "/* block comment */\n" 16450 "int oneTwoThree = 123;", 16451 format("int a = 5;\n" 16452 "\n" 16453 "/* block comment */\n" 16454 "int oneTwoThree=123;", 16455 Alignment)); 16456 16457 EXPECT_EQ("int a = 5;\n" 16458 "\n" 16459 "// line comment\n" 16460 "int oneTwoThree = 123;", 16461 format("int a = 5;\n" 16462 "\n" 16463 "// line comment\n" 16464 "int oneTwoThree=123;", 16465 Alignment)); 16466 } 16467 16468 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) { 16469 FormatStyle Alignment = getLLVMStyle(); 16470 Alignment.AlignConsecutiveDeclarations.Enabled = true; 16471 Alignment.AlignConsecutiveDeclarations.AcrossEmptyLines = true; 16472 Alignment.AlignConsecutiveDeclarations.AcrossComments = true; 16473 16474 Alignment.MaxEmptyLinesToKeep = 10; 16475 /* Test alignment across empty lines */ 16476 EXPECT_EQ("int a = 5;\n" 16477 "\n" 16478 "float const oneTwoThree = 123;", 16479 format("int a = 5;\n" 16480 "\n" 16481 "float const oneTwoThree = 123;", 16482 Alignment)); 16483 EXPECT_EQ("int a = 5;\n" 16484 "float const one = 1;\n" 16485 "\n" 16486 "int oneTwoThree = 123;", 16487 format("int a = 5;\n" 16488 "float const one = 1;\n" 16489 "\n" 16490 "int oneTwoThree = 123;", 16491 Alignment)); 16492 16493 /* Test across comments */ 16494 EXPECT_EQ("float const a = 5;\n" 16495 "/* block comment */\n" 16496 "int oneTwoThree = 123;", 16497 format("float const a = 5;\n" 16498 "/* block comment */\n" 16499 "int oneTwoThree=123;", 16500 Alignment)); 16501 16502 EXPECT_EQ("float const a = 5;\n" 16503 "// line comment\n" 16504 "int oneTwoThree = 123;", 16505 format("float const a = 5;\n" 16506 "// line comment\n" 16507 "int oneTwoThree=123;", 16508 Alignment)); 16509 16510 /* Test across comments and newlines */ 16511 EXPECT_EQ("float const a = 5;\n" 16512 "\n" 16513 "/* block comment */\n" 16514 "int oneTwoThree = 123;", 16515 format("float const a = 5;\n" 16516 "\n" 16517 "/* block comment */\n" 16518 "int oneTwoThree=123;", 16519 Alignment)); 16520 16521 EXPECT_EQ("float const a = 5;\n" 16522 "\n" 16523 "// line comment\n" 16524 "int oneTwoThree = 123;", 16525 format("float const a = 5;\n" 16526 "\n" 16527 "// line comment\n" 16528 "int oneTwoThree=123;", 16529 Alignment)); 16530 } 16531 16532 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) { 16533 FormatStyle Alignment = getLLVMStyle(); 16534 Alignment.AlignConsecutiveBitFields.Enabled = true; 16535 Alignment.AlignConsecutiveBitFields.AcrossEmptyLines = true; 16536 Alignment.AlignConsecutiveBitFields.AcrossComments = true; 16537 16538 Alignment.MaxEmptyLinesToKeep = 10; 16539 /* Test alignment across empty lines */ 16540 EXPECT_EQ("int a : 5;\n" 16541 "\n" 16542 "int longbitfield : 6;", 16543 format("int a : 5;\n" 16544 "\n" 16545 "int longbitfield : 6;", 16546 Alignment)); 16547 EXPECT_EQ("int a : 5;\n" 16548 "int one : 1;\n" 16549 "\n" 16550 "int longbitfield : 6;", 16551 format("int a : 5;\n" 16552 "int one : 1;\n" 16553 "\n" 16554 "int longbitfield : 6;", 16555 Alignment)); 16556 16557 /* Test across comments */ 16558 EXPECT_EQ("int a : 5;\n" 16559 "/* block comment */\n" 16560 "int longbitfield : 6;", 16561 format("int a : 5;\n" 16562 "/* block comment */\n" 16563 "int longbitfield : 6;", 16564 Alignment)); 16565 EXPECT_EQ("int a : 5;\n" 16566 "int one : 1;\n" 16567 "// line comment\n" 16568 "int longbitfield : 6;", 16569 format("int a : 5;\n" 16570 "int one : 1;\n" 16571 "// line comment\n" 16572 "int longbitfield : 6;", 16573 Alignment)); 16574 16575 /* Test across comments and newlines */ 16576 EXPECT_EQ("int a : 5;\n" 16577 "/* block comment */\n" 16578 "\n" 16579 "int longbitfield : 6;", 16580 format("int a : 5;\n" 16581 "/* block comment */\n" 16582 "\n" 16583 "int longbitfield : 6;", 16584 Alignment)); 16585 EXPECT_EQ("int a : 5;\n" 16586 "int one : 1;\n" 16587 "\n" 16588 "// line comment\n" 16589 "\n" 16590 "int longbitfield : 6;", 16591 format("int a : 5;\n" 16592 "int one : 1;\n" 16593 "\n" 16594 "// line comment \n" 16595 "\n" 16596 "int longbitfield : 6;", 16597 Alignment)); 16598 } 16599 16600 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) { 16601 FormatStyle Alignment = getLLVMStyle(); 16602 Alignment.AlignConsecutiveMacros.Enabled = true; 16603 Alignment.AlignConsecutiveAssignments.Enabled = true; 16604 Alignment.AlignConsecutiveAssignments.AcrossComments = true; 16605 16606 Alignment.MaxEmptyLinesToKeep = 10; 16607 /* Test alignment across empty lines */ 16608 EXPECT_EQ("int a = 5;\n" 16609 "\n" 16610 "int oneTwoThree = 123;", 16611 format("int a = 5;\n" 16612 "\n" 16613 "int oneTwoThree= 123;", 16614 Alignment)); 16615 EXPECT_EQ("int a = 5;\n" 16616 "int one = 1;\n" 16617 "\n" 16618 "int oneTwoThree = 123;", 16619 format("int a = 5;\n" 16620 "int one = 1;\n" 16621 "\n" 16622 "int oneTwoThree = 123;", 16623 Alignment)); 16624 16625 /* Test across comments */ 16626 EXPECT_EQ("int a = 5;\n" 16627 "/* block comment */\n" 16628 "int oneTwoThree = 123;", 16629 format("int a = 5;\n" 16630 "/* block comment */\n" 16631 "int oneTwoThree=123;", 16632 Alignment)); 16633 16634 EXPECT_EQ("int a = 5;\n" 16635 "// line comment\n" 16636 "int oneTwoThree = 123;", 16637 format("int a = 5;\n" 16638 "// line comment\n" 16639 "int oneTwoThree=123;", 16640 Alignment)); 16641 16642 EXPECT_EQ("int a = 5;\n" 16643 "/*\n" 16644 " * multi-line block comment\n" 16645 " */\n" 16646 "int oneTwoThree = 123;", 16647 format("int a = 5;\n" 16648 "/*\n" 16649 " * multi-line block comment\n" 16650 " */\n" 16651 "int oneTwoThree=123;", 16652 Alignment)); 16653 16654 EXPECT_EQ("int a = 5;\n" 16655 "//\n" 16656 "// multi-line line comment\n" 16657 "//\n" 16658 "int oneTwoThree = 123;", 16659 format("int a = 5;\n" 16660 "//\n" 16661 "// multi-line line comment\n" 16662 "//\n" 16663 "int oneTwoThree=123;", 16664 Alignment)); 16665 16666 /* Test across comments and newlines */ 16667 EXPECT_EQ("int a = 5;\n" 16668 "\n" 16669 "/* block comment */\n" 16670 "int oneTwoThree = 123;", 16671 format("int a = 5;\n" 16672 "\n" 16673 "/* block comment */\n" 16674 "int oneTwoThree=123;", 16675 Alignment)); 16676 16677 EXPECT_EQ("int a = 5;\n" 16678 "\n" 16679 "// line comment\n" 16680 "int oneTwoThree = 123;", 16681 format("int a = 5;\n" 16682 "\n" 16683 "// line comment\n" 16684 "int oneTwoThree=123;", 16685 Alignment)); 16686 } 16687 16688 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) { 16689 FormatStyle Alignment = getLLVMStyle(); 16690 Alignment.AlignConsecutiveMacros.Enabled = true; 16691 Alignment.AlignConsecutiveAssignments.Enabled = true; 16692 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true; 16693 Alignment.AlignConsecutiveAssignments.AcrossComments = true; 16694 verifyFormat("int a = 5;\n" 16695 "int oneTwoThree = 123;", 16696 Alignment); 16697 verifyFormat("int a = method();\n" 16698 "int oneTwoThree = 133;", 16699 Alignment); 16700 verifyFormat("a &= 5;\n" 16701 "bcd *= 5;\n" 16702 "ghtyf += 5;\n" 16703 "dvfvdb -= 5;\n" 16704 "a /= 5;\n" 16705 "vdsvsv %= 5;\n" 16706 "sfdbddfbdfbb ^= 5;\n" 16707 "dvsdsv |= 5;\n" 16708 "int dsvvdvsdvvv = 123;", 16709 Alignment); 16710 verifyFormat("int i = 1, j = 10;\n" 16711 "something = 2000;", 16712 Alignment); 16713 verifyFormat("something = 2000;\n" 16714 "int i = 1, j = 10;\n", 16715 Alignment); 16716 verifyFormat("something = 2000;\n" 16717 "another = 911;\n" 16718 "int i = 1, j = 10;\n" 16719 "oneMore = 1;\n" 16720 "i = 2;", 16721 Alignment); 16722 verifyFormat("int a = 5;\n" 16723 "int one = 1;\n" 16724 "method();\n" 16725 "int oneTwoThree = 123;\n" 16726 "int oneTwo = 12;", 16727 Alignment); 16728 verifyFormat("int oneTwoThree = 123;\n" 16729 "int oneTwo = 12;\n" 16730 "method();\n", 16731 Alignment); 16732 verifyFormat("int oneTwoThree = 123; // comment\n" 16733 "int oneTwo = 12; // comment", 16734 Alignment); 16735 16736 // Bug 25167 16737 /* Uncomment when fixed 16738 verifyFormat("#if A\n" 16739 "#else\n" 16740 "int aaaaaaaa = 12;\n" 16741 "#endif\n" 16742 "#if B\n" 16743 "#else\n" 16744 "int a = 12;\n" 16745 "#endif\n", 16746 Alignment); 16747 verifyFormat("enum foo {\n" 16748 "#if A\n" 16749 "#else\n" 16750 " aaaaaaaa = 12;\n" 16751 "#endif\n" 16752 "#if B\n" 16753 "#else\n" 16754 " a = 12;\n" 16755 "#endif\n" 16756 "};\n", 16757 Alignment); 16758 */ 16759 16760 Alignment.MaxEmptyLinesToKeep = 10; 16761 /* Test alignment across empty lines */ 16762 EXPECT_EQ("int a = 5;\n" 16763 "\n" 16764 "int oneTwoThree = 123;", 16765 format("int a = 5;\n" 16766 "\n" 16767 "int oneTwoThree= 123;", 16768 Alignment)); 16769 EXPECT_EQ("int a = 5;\n" 16770 "int one = 1;\n" 16771 "\n" 16772 "int oneTwoThree = 123;", 16773 format("int a = 5;\n" 16774 "int one = 1;\n" 16775 "\n" 16776 "int oneTwoThree = 123;", 16777 Alignment)); 16778 EXPECT_EQ("int a = 5;\n" 16779 "int one = 1;\n" 16780 "\n" 16781 "int oneTwoThree = 123;\n" 16782 "int oneTwo = 12;", 16783 format("int a = 5;\n" 16784 "int one = 1;\n" 16785 "\n" 16786 "int oneTwoThree = 123;\n" 16787 "int oneTwo = 12;", 16788 Alignment)); 16789 16790 /* Test across comments */ 16791 EXPECT_EQ("int a = 5;\n" 16792 "/* block comment */\n" 16793 "int oneTwoThree = 123;", 16794 format("int a = 5;\n" 16795 "/* block comment */\n" 16796 "int oneTwoThree=123;", 16797 Alignment)); 16798 16799 EXPECT_EQ("int a = 5;\n" 16800 "// line comment\n" 16801 "int oneTwoThree = 123;", 16802 format("int a = 5;\n" 16803 "// line comment\n" 16804 "int oneTwoThree=123;", 16805 Alignment)); 16806 16807 /* Test across comments and newlines */ 16808 EXPECT_EQ("int a = 5;\n" 16809 "\n" 16810 "/* block comment */\n" 16811 "int oneTwoThree = 123;", 16812 format("int a = 5;\n" 16813 "\n" 16814 "/* block comment */\n" 16815 "int oneTwoThree=123;", 16816 Alignment)); 16817 16818 EXPECT_EQ("int a = 5;\n" 16819 "\n" 16820 "// line comment\n" 16821 "int oneTwoThree = 123;", 16822 format("int a = 5;\n" 16823 "\n" 16824 "// line comment\n" 16825 "int oneTwoThree=123;", 16826 Alignment)); 16827 16828 EXPECT_EQ("int a = 5;\n" 16829 "//\n" 16830 "// multi-line line comment\n" 16831 "//\n" 16832 "int oneTwoThree = 123;", 16833 format("int a = 5;\n" 16834 "//\n" 16835 "// multi-line line comment\n" 16836 "//\n" 16837 "int oneTwoThree=123;", 16838 Alignment)); 16839 16840 EXPECT_EQ("int a = 5;\n" 16841 "/*\n" 16842 " * multi-line block comment\n" 16843 " */\n" 16844 "int oneTwoThree = 123;", 16845 format("int a = 5;\n" 16846 "/*\n" 16847 " * multi-line block comment\n" 16848 " */\n" 16849 "int oneTwoThree=123;", 16850 Alignment)); 16851 16852 EXPECT_EQ("int a = 5;\n" 16853 "\n" 16854 "/* block comment */\n" 16855 "\n" 16856 "\n" 16857 "\n" 16858 "int oneTwoThree = 123;", 16859 format("int a = 5;\n" 16860 "\n" 16861 "/* block comment */\n" 16862 "\n" 16863 "\n" 16864 "\n" 16865 "int oneTwoThree=123;", 16866 Alignment)); 16867 16868 EXPECT_EQ("int a = 5;\n" 16869 "\n" 16870 "// line comment\n" 16871 "\n" 16872 "\n" 16873 "\n" 16874 "int oneTwoThree = 123;", 16875 format("int a = 5;\n" 16876 "\n" 16877 "// line comment\n" 16878 "\n" 16879 "\n" 16880 "\n" 16881 "int oneTwoThree=123;", 16882 Alignment)); 16883 16884 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 16885 verifyFormat("#define A \\\n" 16886 " int aaaa = 12; \\\n" 16887 " int b = 23; \\\n" 16888 " int ccc = 234; \\\n" 16889 " int dddddddddd = 2345;", 16890 Alignment); 16891 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 16892 verifyFormat("#define A \\\n" 16893 " int aaaa = 12; \\\n" 16894 " int b = 23; \\\n" 16895 " int ccc = 234; \\\n" 16896 " int dddddddddd = 2345;", 16897 Alignment); 16898 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 16899 verifyFormat("#define A " 16900 " \\\n" 16901 " int aaaa = 12; " 16902 " \\\n" 16903 " int b = 23; " 16904 " \\\n" 16905 " int ccc = 234; " 16906 " \\\n" 16907 " int dddddddddd = 2345;", 16908 Alignment); 16909 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 16910 "k = 4, int l = 5,\n" 16911 " int m = 6) {\n" 16912 " int j = 10;\n" 16913 " otherThing = 1;\n" 16914 "}", 16915 Alignment); 16916 verifyFormat("void SomeFunction(int parameter = 0) {\n" 16917 " int i = 1;\n" 16918 " int j = 2;\n" 16919 " int big = 10000;\n" 16920 "}", 16921 Alignment); 16922 verifyFormat("class C {\n" 16923 "public:\n" 16924 " int i = 1;\n" 16925 " virtual void f() = 0;\n" 16926 "};", 16927 Alignment); 16928 verifyFormat("int i = 1;\n" 16929 "if (SomeType t = getSomething()) {\n" 16930 "}\n" 16931 "int j = 2;\n" 16932 "int big = 10000;", 16933 Alignment); 16934 verifyFormat("int j = 7;\n" 16935 "for (int k = 0; k < N; ++k) {\n" 16936 "}\n" 16937 "int j = 2;\n" 16938 "int big = 10000;\n" 16939 "}", 16940 Alignment); 16941 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 16942 verifyFormat("int i = 1;\n" 16943 "LooooooooooongType loooooooooooooooooooooongVariable\n" 16944 " = someLooooooooooooooooongFunction();\n" 16945 "int j = 2;", 16946 Alignment); 16947 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 16948 verifyFormat("int i = 1;\n" 16949 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 16950 " someLooooooooooooooooongFunction();\n" 16951 "int j = 2;", 16952 Alignment); 16953 16954 verifyFormat("auto lambda = []() {\n" 16955 " auto i = 0;\n" 16956 " return 0;\n" 16957 "};\n" 16958 "int i = 0;\n" 16959 "auto v = type{\n" 16960 " i = 1, //\n" 16961 " (i = 2), //\n" 16962 " i = 3 //\n" 16963 "};", 16964 Alignment); 16965 16966 verifyFormat( 16967 "int i = 1;\n" 16968 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 16969 " loooooooooooooooooooooongParameterB);\n" 16970 "int j = 2;", 16971 Alignment); 16972 16973 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n" 16974 " typename B = very_long_type_name_1,\n" 16975 " typename T_2 = very_long_type_name_2>\n" 16976 "auto foo() {}\n", 16977 Alignment); 16978 verifyFormat("int a, b = 1;\n" 16979 "int c = 2;\n" 16980 "int dd = 3;\n", 16981 Alignment); 16982 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 16983 "float b[1][] = {{3.f}};\n", 16984 Alignment); 16985 verifyFormat("for (int i = 0; i < 1; i++)\n" 16986 " int x = 1;\n", 16987 Alignment); 16988 verifyFormat("for (i = 0; i < 1; i++)\n" 16989 " x = 1;\n" 16990 "y = 1;\n", 16991 Alignment); 16992 16993 Alignment.ReflowComments = true; 16994 Alignment.ColumnLimit = 50; 16995 EXPECT_EQ("int x = 0;\n" 16996 "int yy = 1; /// specificlennospace\n" 16997 "int zzz = 2;\n", 16998 format("int x = 0;\n" 16999 "int yy = 1; ///specificlennospace\n" 17000 "int zzz = 2;\n", 17001 Alignment)); 17002 } 17003 17004 TEST_F(FormatTest, AlignCompoundAssignments) { 17005 FormatStyle Alignment = getLLVMStyle(); 17006 Alignment.AlignConsecutiveAssignments.Enabled = true; 17007 Alignment.AlignConsecutiveAssignments.AlignCompound = true; 17008 Alignment.AlignConsecutiveAssignments.PadOperators = false; 17009 verifyFormat("sfdbddfbdfbb = 5;\n" 17010 "dvsdsv = 5;\n" 17011 "int dsvvdvsdvvv = 123;", 17012 Alignment); 17013 verifyFormat("sfdbddfbdfbb ^= 5;\n" 17014 "dvsdsv |= 5;\n" 17015 "int dsvvdvsdvvv = 123;", 17016 Alignment); 17017 verifyFormat("sfdbddfbdfbb ^= 5;\n" 17018 "dvsdsv <<= 5;\n" 17019 "int dsvvdvsdvvv = 123;", 17020 Alignment); 17021 // Test that `<=` is not treated as a compound assignment. 17022 verifyFormat("aa &= 5;\n" 17023 "b <= 10;\n" 17024 "c = 15;", 17025 Alignment); 17026 Alignment.AlignConsecutiveAssignments.PadOperators = true; 17027 verifyFormat("sfdbddfbdfbb = 5;\n" 17028 "dvsdsv = 5;\n" 17029 "int dsvvdvsdvvv = 123;", 17030 Alignment); 17031 verifyFormat("sfdbddfbdfbb ^= 5;\n" 17032 "dvsdsv |= 5;\n" 17033 "int dsvvdvsdvvv = 123;", 17034 Alignment); 17035 verifyFormat("sfdbddfbdfbb ^= 5;\n" 17036 "dvsdsv <<= 5;\n" 17037 "int dsvvdvsdvvv = 123;", 17038 Alignment); 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 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true; 17058 EXPECT_EQ("a += 5;\n" 17059 "one = 1;\n" 17060 "\n" 17061 "oneTwoThree = 123;\n", 17062 format("a += 5;\n" 17063 "one = 1;\n" 17064 "\n" 17065 "oneTwoThree = 123;\n", 17066 Alignment)); 17067 EXPECT_EQ("a += 5;\n" 17068 "one = 1;\n" 17069 "//\n" 17070 "oneTwoThree = 123;\n", 17071 format("a += 5;\n" 17072 "one = 1;\n" 17073 "//\n" 17074 "oneTwoThree = 123;\n", 17075 Alignment)); 17076 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = false; 17077 Alignment.AlignConsecutiveAssignments.AcrossComments = true; 17078 EXPECT_EQ("a += 5;\n" 17079 "one = 1;\n" 17080 "\n" 17081 "oneTwoThree = 123;\n", 17082 format("a += 5;\n" 17083 "one = 1;\n" 17084 "\n" 17085 "oneTwoThree = 123;\n", 17086 Alignment)); 17087 EXPECT_EQ("a += 5;\n" 17088 "one = 1;\n" 17089 "//\n" 17090 "oneTwoThree = 123;\n", 17091 format("a += 5;\n" 17092 "one = 1;\n" 17093 "//\n" 17094 "oneTwoThree = 123;\n", 17095 Alignment)); 17096 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true; 17097 EXPECT_EQ("a += 5;\n" 17098 "one >>= 1;\n" 17099 "\n" 17100 "oneTwoThree = 123;\n", 17101 format("a += 5;\n" 17102 "one >>= 1;\n" 17103 "\n" 17104 "oneTwoThree = 123;\n", 17105 Alignment)); 17106 EXPECT_EQ("a += 5;\n" 17107 "one = 1;\n" 17108 "//\n" 17109 "oneTwoThree <<= 123;\n", 17110 format("a += 5;\n" 17111 "one = 1;\n" 17112 "//\n" 17113 "oneTwoThree <<= 123;\n", 17114 Alignment)); 17115 } 17116 17117 TEST_F(FormatTest, AlignConsecutiveAssignments) { 17118 FormatStyle Alignment = getLLVMStyle(); 17119 Alignment.AlignConsecutiveMacros.Enabled = true; 17120 verifyFormat("int a = 5;\n" 17121 "int oneTwoThree = 123;", 17122 Alignment); 17123 verifyFormat("int a = 5;\n" 17124 "int oneTwoThree = 123;", 17125 Alignment); 17126 17127 Alignment.AlignConsecutiveAssignments.Enabled = true; 17128 verifyFormat("int a = 5;\n" 17129 "int oneTwoThree = 123;", 17130 Alignment); 17131 verifyFormat("int a = method();\n" 17132 "int oneTwoThree = 133;", 17133 Alignment); 17134 verifyFormat("aa <= 5;\n" 17135 "a &= 5;\n" 17136 "bcd *= 5;\n" 17137 "ghtyf += 5;\n" 17138 "dvfvdb -= 5;\n" 17139 "a /= 5;\n" 17140 "vdsvsv %= 5;\n" 17141 "sfdbddfbdfbb ^= 5;\n" 17142 "dvsdsv |= 5;\n" 17143 "int dsvvdvsdvvv = 123;", 17144 Alignment); 17145 verifyFormat("int i = 1, j = 10;\n" 17146 "something = 2000;", 17147 Alignment); 17148 verifyFormat("something = 2000;\n" 17149 "int i = 1, j = 10;\n", 17150 Alignment); 17151 verifyFormat("something = 2000;\n" 17152 "another = 911;\n" 17153 "int i = 1, j = 10;\n" 17154 "oneMore = 1;\n" 17155 "i = 2;", 17156 Alignment); 17157 verifyFormat("int a = 5;\n" 17158 "int one = 1;\n" 17159 "method();\n" 17160 "int oneTwoThree = 123;\n" 17161 "int oneTwo = 12;", 17162 Alignment); 17163 verifyFormat("int oneTwoThree = 123;\n" 17164 "int oneTwo = 12;\n" 17165 "method();\n", 17166 Alignment); 17167 verifyFormat("int oneTwoThree = 123; // comment\n" 17168 "int oneTwo = 12; // comment", 17169 Alignment); 17170 verifyFormat("int f() = default;\n" 17171 "int &operator() = default;\n" 17172 "int &operator=() {", 17173 Alignment); 17174 verifyFormat("int f() = delete;\n" 17175 "int &operator() = delete;\n" 17176 "int &operator=() {", 17177 Alignment); 17178 verifyFormat("int f() = default; // comment\n" 17179 "int &operator() = default; // comment\n" 17180 "int &operator=() {", 17181 Alignment); 17182 verifyFormat("int f() = default;\n" 17183 "int &operator() = default;\n" 17184 "int &operator==() {", 17185 Alignment); 17186 verifyFormat("int f() = default;\n" 17187 "int &operator() = default;\n" 17188 "int &operator<=() {", 17189 Alignment); 17190 verifyFormat("int f() = default;\n" 17191 "int &operator() = default;\n" 17192 "int &operator!=() {", 17193 Alignment); 17194 verifyFormat("int f() = default;\n" 17195 "int &operator() = default;\n" 17196 "int &operator=();", 17197 Alignment); 17198 verifyFormat("int f() = delete;\n" 17199 "int &operator() = delete;\n" 17200 "int &operator=();", 17201 Alignment); 17202 verifyFormat("/* long long padding */ int f() = default;\n" 17203 "int &operator() = default;\n" 17204 "int &operator/**/ =();", 17205 Alignment); 17206 // https://llvm.org/PR33697 17207 FormatStyle AlignmentWithPenalty = getLLVMStyle(); 17208 AlignmentWithPenalty.AlignConsecutiveAssignments.Enabled = true; 17209 AlignmentWithPenalty.PenaltyReturnTypeOnItsOwnLine = 5000; 17210 verifyFormat("class SSSSSSSSSSSSSSSSSSSSSSSSSSSS {\n" 17211 " void f() = delete;\n" 17212 " SSSSSSSSSSSSSSSSSSSSSSSSSSSS &operator=(\n" 17213 " const SSSSSSSSSSSSSSSSSSSSSSSSSSSS &other) = delete;\n" 17214 "};\n", 17215 AlignmentWithPenalty); 17216 17217 // Bug 25167 17218 /* Uncomment when fixed 17219 verifyFormat("#if A\n" 17220 "#else\n" 17221 "int aaaaaaaa = 12;\n" 17222 "#endif\n" 17223 "#if B\n" 17224 "#else\n" 17225 "int a = 12;\n" 17226 "#endif\n", 17227 Alignment); 17228 verifyFormat("enum foo {\n" 17229 "#if A\n" 17230 "#else\n" 17231 " aaaaaaaa = 12;\n" 17232 "#endif\n" 17233 "#if B\n" 17234 "#else\n" 17235 " a = 12;\n" 17236 "#endif\n" 17237 "};\n", 17238 Alignment); 17239 */ 17240 17241 EXPECT_EQ("int a = 5;\n" 17242 "\n" 17243 "int oneTwoThree = 123;", 17244 format("int a = 5;\n" 17245 "\n" 17246 "int oneTwoThree= 123;", 17247 Alignment)); 17248 EXPECT_EQ("int a = 5;\n" 17249 "int one = 1;\n" 17250 "\n" 17251 "int oneTwoThree = 123;", 17252 format("int a = 5;\n" 17253 "int one = 1;\n" 17254 "\n" 17255 "int oneTwoThree = 123;", 17256 Alignment)); 17257 EXPECT_EQ("int a = 5;\n" 17258 "int one = 1;\n" 17259 "\n" 17260 "int oneTwoThree = 123;\n" 17261 "int oneTwo = 12;", 17262 format("int a = 5;\n" 17263 "int one = 1;\n" 17264 "\n" 17265 "int oneTwoThree = 123;\n" 17266 "int oneTwo = 12;", 17267 Alignment)); 17268 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 17269 verifyFormat("#define A \\\n" 17270 " int aaaa = 12; \\\n" 17271 " int b = 23; \\\n" 17272 " int ccc = 234; \\\n" 17273 " int dddddddddd = 2345;", 17274 Alignment); 17275 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 17276 verifyFormat("#define A \\\n" 17277 " int aaaa = 12; \\\n" 17278 " int b = 23; \\\n" 17279 " int ccc = 234; \\\n" 17280 " int dddddddddd = 2345;", 17281 Alignment); 17282 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 17283 verifyFormat("#define A " 17284 " \\\n" 17285 " int aaaa = 12; " 17286 " \\\n" 17287 " int b = 23; " 17288 " \\\n" 17289 " int ccc = 234; " 17290 " \\\n" 17291 " int dddddddddd = 2345;", 17292 Alignment); 17293 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 17294 "k = 4, int l = 5,\n" 17295 " int m = 6) {\n" 17296 " int j = 10;\n" 17297 " otherThing = 1;\n" 17298 "}", 17299 Alignment); 17300 verifyFormat("void SomeFunction(int parameter = 0) {\n" 17301 " int i = 1;\n" 17302 " int j = 2;\n" 17303 " int big = 10000;\n" 17304 "}", 17305 Alignment); 17306 verifyFormat("class C {\n" 17307 "public:\n" 17308 " int i = 1;\n" 17309 " virtual void f() = 0;\n" 17310 "};", 17311 Alignment); 17312 verifyFormat("int i = 1;\n" 17313 "if (SomeType t = getSomething()) {\n" 17314 "}\n" 17315 "int j = 2;\n" 17316 "int big = 10000;", 17317 Alignment); 17318 verifyFormat("int j = 7;\n" 17319 "for (int k = 0; k < N; ++k) {\n" 17320 "}\n" 17321 "int j = 2;\n" 17322 "int big = 10000;\n" 17323 "}", 17324 Alignment); 17325 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 17326 verifyFormat("int i = 1;\n" 17327 "LooooooooooongType loooooooooooooooooooooongVariable\n" 17328 " = someLooooooooooooooooongFunction();\n" 17329 "int j = 2;", 17330 Alignment); 17331 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 17332 verifyFormat("int i = 1;\n" 17333 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 17334 " someLooooooooooooooooongFunction();\n" 17335 "int j = 2;", 17336 Alignment); 17337 17338 verifyFormat("auto lambda = []() {\n" 17339 " auto i = 0;\n" 17340 " return 0;\n" 17341 "};\n" 17342 "int i = 0;\n" 17343 "auto v = type{\n" 17344 " i = 1, //\n" 17345 " (i = 2), //\n" 17346 " i = 3 //\n" 17347 "};", 17348 Alignment); 17349 17350 verifyFormat( 17351 "int i = 1;\n" 17352 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 17353 " loooooooooooooooooooooongParameterB);\n" 17354 "int j = 2;", 17355 Alignment); 17356 17357 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n" 17358 " typename B = very_long_type_name_1,\n" 17359 " typename T_2 = very_long_type_name_2>\n" 17360 "auto foo() {}\n", 17361 Alignment); 17362 verifyFormat("int a, b = 1;\n" 17363 "int c = 2;\n" 17364 "int dd = 3;\n", 17365 Alignment); 17366 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17367 "float b[1][] = {{3.f}};\n", 17368 Alignment); 17369 verifyFormat("for (int i = 0; i < 1; i++)\n" 17370 " int x = 1;\n", 17371 Alignment); 17372 verifyFormat("for (i = 0; i < 1; i++)\n" 17373 " x = 1;\n" 17374 "y = 1;\n", 17375 Alignment); 17376 17377 EXPECT_EQ(Alignment.ReflowComments, true); 17378 Alignment.ColumnLimit = 50; 17379 EXPECT_EQ("int x = 0;\n" 17380 "int yy = 1; /// specificlennospace\n" 17381 "int zzz = 2;\n", 17382 format("int x = 0;\n" 17383 "int yy = 1; ///specificlennospace\n" 17384 "int zzz = 2;\n", 17385 Alignment)); 17386 17387 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17388 "auto b = [] {\n" 17389 " f();\n" 17390 " return;\n" 17391 "};", 17392 Alignment); 17393 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17394 "auto b = g([] {\n" 17395 " f();\n" 17396 " return;\n" 17397 "});", 17398 Alignment); 17399 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17400 "auto b = g(param, [] {\n" 17401 " f();\n" 17402 " return;\n" 17403 "});", 17404 Alignment); 17405 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17406 "auto b = [] {\n" 17407 " if (condition) {\n" 17408 " return;\n" 17409 " }\n" 17410 "};", 17411 Alignment); 17412 17413 verifyFormat("auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 17414 " ccc ? aaaaa : bbbbb,\n" 17415 " dddddddddddddddddddddddddd);", 17416 Alignment); 17417 // FIXME: https://llvm.org/PR53497 17418 // verifyFormat("auto aaaaaaaaaaaa = f();\n" 17419 // "auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 17420 // " ccc ? aaaaa : bbbbb,\n" 17421 // " dddddddddddddddddddddddddd);", 17422 // Alignment); 17423 17424 // Confirm proper handling of AlignConsecutiveAssignments with 17425 // BinPackArguments. 17426 // See https://llvm.org/PR55360 17427 Alignment = getLLVMStyleWithColumns(50); 17428 Alignment.AlignConsecutiveAssignments.Enabled = true; 17429 Alignment.BinPackArguments = false; 17430 verifyFormat("int a_long_name = 1;\n" 17431 "auto b = B({a_long_name, a_long_name},\n" 17432 " {a_longer_name_for_wrap,\n" 17433 " a_longer_name_for_wrap});", 17434 Alignment); 17435 verifyFormat("int a_long_name = 1;\n" 17436 "auto b = B{{a_long_name, a_long_name},\n" 17437 " {a_longer_name_for_wrap,\n" 17438 " a_longer_name_for_wrap}};", 17439 Alignment); 17440 } 17441 17442 TEST_F(FormatTest, AlignConsecutiveBitFields) { 17443 FormatStyle Alignment = getLLVMStyle(); 17444 Alignment.AlignConsecutiveBitFields.Enabled = true; 17445 verifyFormat("int const a : 5;\n" 17446 "int oneTwoThree : 23;", 17447 Alignment); 17448 17449 // Initializers are allowed starting with c++2a 17450 verifyFormat("int const a : 5 = 1;\n" 17451 "int oneTwoThree : 23 = 0;", 17452 Alignment); 17453 17454 Alignment.AlignConsecutiveDeclarations.Enabled = true; 17455 verifyFormat("int const a : 5;\n" 17456 "int oneTwoThree : 23;", 17457 Alignment); 17458 17459 verifyFormat("int const a : 5; // comment\n" 17460 "int oneTwoThree : 23; // comment", 17461 Alignment); 17462 17463 verifyFormat("int const a : 5 = 1;\n" 17464 "int oneTwoThree : 23 = 0;", 17465 Alignment); 17466 17467 Alignment.AlignConsecutiveAssignments.Enabled = true; 17468 verifyFormat("int const a : 5 = 1;\n" 17469 "int oneTwoThree : 23 = 0;", 17470 Alignment); 17471 verifyFormat("int const a : 5 = {1};\n" 17472 "int oneTwoThree : 23 = 0;", 17473 Alignment); 17474 17475 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None; 17476 verifyFormat("int const a :5;\n" 17477 "int oneTwoThree:23;", 17478 Alignment); 17479 17480 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before; 17481 verifyFormat("int const a :5;\n" 17482 "int oneTwoThree :23;", 17483 Alignment); 17484 17485 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After; 17486 verifyFormat("int const a : 5;\n" 17487 "int oneTwoThree: 23;", 17488 Alignment); 17489 17490 // Known limitations: ':' is only recognized as a bitfield colon when 17491 // followed by a number. 17492 /* 17493 verifyFormat("int oneTwoThree : SOME_CONSTANT;\n" 17494 "int a : 5;", 17495 Alignment); 17496 */ 17497 } 17498 17499 TEST_F(FormatTest, AlignConsecutiveDeclarations) { 17500 FormatStyle Alignment = getLLVMStyle(); 17501 Alignment.AlignConsecutiveMacros.Enabled = true; 17502 Alignment.PointerAlignment = FormatStyle::PAS_Right; 17503 verifyFormat("float const a = 5;\n" 17504 "int oneTwoThree = 123;", 17505 Alignment); 17506 verifyFormat("int a = 5;\n" 17507 "float const oneTwoThree = 123;", 17508 Alignment); 17509 17510 Alignment.AlignConsecutiveDeclarations.Enabled = true; 17511 verifyFormat("float const a = 5;\n" 17512 "int oneTwoThree = 123;", 17513 Alignment); 17514 verifyFormat("int a = method();\n" 17515 "float const oneTwoThree = 133;", 17516 Alignment); 17517 verifyFormat("int i = 1, j = 10;\n" 17518 "something = 2000;", 17519 Alignment); 17520 verifyFormat("something = 2000;\n" 17521 "int i = 1, j = 10;\n", 17522 Alignment); 17523 verifyFormat("float something = 2000;\n" 17524 "double another = 911;\n" 17525 "int i = 1, j = 10;\n" 17526 "const int *oneMore = 1;\n" 17527 "unsigned i = 2;", 17528 Alignment); 17529 verifyFormat("float a = 5;\n" 17530 "int one = 1;\n" 17531 "method();\n" 17532 "const double oneTwoThree = 123;\n" 17533 "const unsigned int oneTwo = 12;", 17534 Alignment); 17535 verifyFormat("int oneTwoThree{0}; // comment\n" 17536 "unsigned oneTwo; // comment", 17537 Alignment); 17538 verifyFormat("unsigned int *a;\n" 17539 "int *b;\n" 17540 "unsigned int Const *c;\n" 17541 "unsigned int const *d;\n" 17542 "unsigned int Const &e;\n" 17543 "unsigned int const &f;", 17544 Alignment); 17545 verifyFormat("Const unsigned int *c;\n" 17546 "const unsigned int *d;\n" 17547 "Const unsigned int &e;\n" 17548 "const unsigned int &f;\n" 17549 "const unsigned g;\n" 17550 "Const unsigned h;", 17551 Alignment); 17552 EXPECT_EQ("float const a = 5;\n" 17553 "\n" 17554 "int oneTwoThree = 123;", 17555 format("float const a = 5;\n" 17556 "\n" 17557 "int oneTwoThree= 123;", 17558 Alignment)); 17559 EXPECT_EQ("float a = 5;\n" 17560 "int one = 1;\n" 17561 "\n" 17562 "unsigned oneTwoThree = 123;", 17563 format("float a = 5;\n" 17564 "int one = 1;\n" 17565 "\n" 17566 "unsigned oneTwoThree = 123;", 17567 Alignment)); 17568 EXPECT_EQ("float a = 5;\n" 17569 "int one = 1;\n" 17570 "\n" 17571 "unsigned oneTwoThree = 123;\n" 17572 "int oneTwo = 12;", 17573 format("float a = 5;\n" 17574 "int one = 1;\n" 17575 "\n" 17576 "unsigned oneTwoThree = 123;\n" 17577 "int oneTwo = 12;", 17578 Alignment)); 17579 // Function prototype alignment 17580 verifyFormat("int a();\n" 17581 "double b();", 17582 Alignment); 17583 verifyFormat("int a(int x);\n" 17584 "double b();", 17585 Alignment); 17586 unsigned OldColumnLimit = Alignment.ColumnLimit; 17587 // We need to set ColumnLimit to zero, in order to stress nested alignments, 17588 // otherwise the function parameters will be re-flowed onto a single line. 17589 Alignment.ColumnLimit = 0; 17590 EXPECT_EQ("int a(int x,\n" 17591 " float y);\n" 17592 "double b(int x,\n" 17593 " double y);", 17594 format("int a(int x,\n" 17595 " float y);\n" 17596 "double b(int x,\n" 17597 " double y);", 17598 Alignment)); 17599 // This ensures that function parameters of function declarations are 17600 // correctly indented when their owning functions are indented. 17601 // The failure case here is for 'double y' to not be indented enough. 17602 EXPECT_EQ("double a(int x);\n" 17603 "int b(int y,\n" 17604 " double z);", 17605 format("double a(int x);\n" 17606 "int b(int y,\n" 17607 " double z);", 17608 Alignment)); 17609 // Set ColumnLimit low so that we induce wrapping immediately after 17610 // the function name and opening paren. 17611 Alignment.ColumnLimit = 13; 17612 verifyFormat("int function(\n" 17613 " int x,\n" 17614 " bool y);", 17615 Alignment); 17616 Alignment.ColumnLimit = OldColumnLimit; 17617 // Ensure function pointers don't screw up recursive alignment 17618 verifyFormat("int a(int x, void (*fp)(int y));\n" 17619 "double b();", 17620 Alignment); 17621 Alignment.AlignConsecutiveAssignments.Enabled = true; 17622 // Ensure recursive alignment is broken by function braces, so that the 17623 // "a = 1" does not align with subsequent assignments inside the function 17624 // body. 17625 verifyFormat("int func(int a = 1) {\n" 17626 " int b = 2;\n" 17627 " int cc = 3;\n" 17628 "}", 17629 Alignment); 17630 verifyFormat("float something = 2000;\n" 17631 "double another = 911;\n" 17632 "int i = 1, j = 10;\n" 17633 "const int *oneMore = 1;\n" 17634 "unsigned i = 2;", 17635 Alignment); 17636 verifyFormat("int oneTwoThree = {0}; // comment\n" 17637 "unsigned oneTwo = 0; // comment", 17638 Alignment); 17639 // Make sure that scope is correctly tracked, in the absence of braces 17640 verifyFormat("for (int i = 0; i < n; i++)\n" 17641 " j = i;\n" 17642 "double x = 1;\n", 17643 Alignment); 17644 verifyFormat("if (int i = 0)\n" 17645 " j = i;\n" 17646 "double x = 1;\n", 17647 Alignment); 17648 // Ensure operator[] and operator() are comprehended 17649 verifyFormat("struct test {\n" 17650 " long long int foo();\n" 17651 " int operator[](int a);\n" 17652 " double bar();\n" 17653 "};\n", 17654 Alignment); 17655 verifyFormat("struct test {\n" 17656 " long long int foo();\n" 17657 " int operator()(int a);\n" 17658 " double bar();\n" 17659 "};\n", 17660 Alignment); 17661 // http://llvm.org/PR52914 17662 verifyFormat("char *a[] = {\"a\", // comment\n" 17663 " \"bb\"};\n" 17664 "int bbbbbbb = 0;", 17665 Alignment); 17666 17667 // PAS_Right 17668 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17669 " int const i = 1;\n" 17670 " int *j = 2;\n" 17671 " int big = 10000;\n" 17672 "\n" 17673 " unsigned oneTwoThree = 123;\n" 17674 " int oneTwo = 12;\n" 17675 " method();\n" 17676 " float k = 2;\n" 17677 " int ll = 10000;\n" 17678 "}", 17679 format("void SomeFunction(int parameter= 0) {\n" 17680 " int const i= 1;\n" 17681 " int *j=2;\n" 17682 " int big = 10000;\n" 17683 "\n" 17684 "unsigned oneTwoThree =123;\n" 17685 "int oneTwo = 12;\n" 17686 " method();\n" 17687 "float k= 2;\n" 17688 "int ll=10000;\n" 17689 "}", 17690 Alignment)); 17691 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17692 " int const i = 1;\n" 17693 " int **j = 2, ***k;\n" 17694 " int &k = i;\n" 17695 " int &&l = i + j;\n" 17696 " int big = 10000;\n" 17697 "\n" 17698 " unsigned oneTwoThree = 123;\n" 17699 " int oneTwo = 12;\n" 17700 " method();\n" 17701 " float k = 2;\n" 17702 " int ll = 10000;\n" 17703 "}", 17704 format("void SomeFunction(int parameter= 0) {\n" 17705 " int const i= 1;\n" 17706 " int **j=2,***k;\n" 17707 "int &k=i;\n" 17708 "int &&l=i+j;\n" 17709 " int big = 10000;\n" 17710 "\n" 17711 "unsigned oneTwoThree =123;\n" 17712 "int oneTwo = 12;\n" 17713 " method();\n" 17714 "float k= 2;\n" 17715 "int ll=10000;\n" 17716 "}", 17717 Alignment)); 17718 // variables are aligned at their name, pointers are at the right most 17719 // position 17720 verifyFormat("int *a;\n" 17721 "int **b;\n" 17722 "int ***c;\n" 17723 "int foobar;\n", 17724 Alignment); 17725 17726 // PAS_Left 17727 FormatStyle AlignmentLeft = Alignment; 17728 AlignmentLeft.PointerAlignment = FormatStyle::PAS_Left; 17729 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17730 " int const i = 1;\n" 17731 " int* j = 2;\n" 17732 " int big = 10000;\n" 17733 "\n" 17734 " unsigned oneTwoThree = 123;\n" 17735 " int oneTwo = 12;\n" 17736 " method();\n" 17737 " float k = 2;\n" 17738 " int ll = 10000;\n" 17739 "}", 17740 format("void SomeFunction(int parameter= 0) {\n" 17741 " int const i= 1;\n" 17742 " int *j=2;\n" 17743 " int big = 10000;\n" 17744 "\n" 17745 "unsigned oneTwoThree =123;\n" 17746 "int oneTwo = 12;\n" 17747 " method();\n" 17748 "float k= 2;\n" 17749 "int ll=10000;\n" 17750 "}", 17751 AlignmentLeft)); 17752 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17753 " int const i = 1;\n" 17754 " int** j = 2;\n" 17755 " int& k = i;\n" 17756 " int&& l = i + j;\n" 17757 " int big = 10000;\n" 17758 "\n" 17759 " unsigned oneTwoThree = 123;\n" 17760 " int oneTwo = 12;\n" 17761 " method();\n" 17762 " float k = 2;\n" 17763 " int ll = 10000;\n" 17764 "}", 17765 format("void SomeFunction(int parameter= 0) {\n" 17766 " int const i= 1;\n" 17767 " int **j=2;\n" 17768 "int &k=i;\n" 17769 "int &&l=i+j;\n" 17770 " int big = 10000;\n" 17771 "\n" 17772 "unsigned oneTwoThree =123;\n" 17773 "int oneTwo = 12;\n" 17774 " method();\n" 17775 "float k= 2;\n" 17776 "int ll=10000;\n" 17777 "}", 17778 AlignmentLeft)); 17779 // variables are aligned at their name, pointers are at the left most position 17780 verifyFormat("int* a;\n" 17781 "int** b;\n" 17782 "int*** c;\n" 17783 "int foobar;\n", 17784 AlignmentLeft); 17785 17786 // PAS_Middle 17787 FormatStyle AlignmentMiddle = Alignment; 17788 AlignmentMiddle.PointerAlignment = FormatStyle::PAS_Middle; 17789 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17790 " int const i = 1;\n" 17791 " int * j = 2;\n" 17792 " int big = 10000;\n" 17793 "\n" 17794 " unsigned oneTwoThree = 123;\n" 17795 " int oneTwo = 12;\n" 17796 " method();\n" 17797 " float k = 2;\n" 17798 " int ll = 10000;\n" 17799 "}", 17800 format("void SomeFunction(int parameter= 0) {\n" 17801 " int const i= 1;\n" 17802 " int *j=2;\n" 17803 " int big = 10000;\n" 17804 "\n" 17805 "unsigned oneTwoThree =123;\n" 17806 "int oneTwo = 12;\n" 17807 " method();\n" 17808 "float k= 2;\n" 17809 "int ll=10000;\n" 17810 "}", 17811 AlignmentMiddle)); 17812 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17813 " int const i = 1;\n" 17814 " int ** j = 2, ***k;\n" 17815 " int & k = i;\n" 17816 " int && l = i + j;\n" 17817 " int big = 10000;\n" 17818 "\n" 17819 " unsigned oneTwoThree = 123;\n" 17820 " int oneTwo = 12;\n" 17821 " method();\n" 17822 " float k = 2;\n" 17823 " int ll = 10000;\n" 17824 "}", 17825 format("void SomeFunction(int parameter= 0) {\n" 17826 " int const i= 1;\n" 17827 " int **j=2,***k;\n" 17828 "int &k=i;\n" 17829 "int &&l=i+j;\n" 17830 " int big = 10000;\n" 17831 "\n" 17832 "unsigned oneTwoThree =123;\n" 17833 "int oneTwo = 12;\n" 17834 " method();\n" 17835 "float k= 2;\n" 17836 "int ll=10000;\n" 17837 "}", 17838 AlignmentMiddle)); 17839 // variables are aligned at their name, pointers are in the middle 17840 verifyFormat("int * a;\n" 17841 "int * b;\n" 17842 "int *** c;\n" 17843 "int foobar;\n", 17844 AlignmentMiddle); 17845 17846 Alignment.AlignConsecutiveAssignments.Enabled = false; 17847 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 17848 verifyFormat("#define A \\\n" 17849 " int aaaa = 12; \\\n" 17850 " float b = 23; \\\n" 17851 " const int ccc = 234; \\\n" 17852 " unsigned dddddddddd = 2345;", 17853 Alignment); 17854 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 17855 verifyFormat("#define A \\\n" 17856 " int aaaa = 12; \\\n" 17857 " float b = 23; \\\n" 17858 " const int ccc = 234; \\\n" 17859 " unsigned dddddddddd = 2345;", 17860 Alignment); 17861 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 17862 Alignment.ColumnLimit = 30; 17863 verifyFormat("#define A \\\n" 17864 " int aaaa = 12; \\\n" 17865 " float b = 23; \\\n" 17866 " const int ccc = 234; \\\n" 17867 " int dddddddddd = 2345;", 17868 Alignment); 17869 Alignment.ColumnLimit = 80; 17870 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 17871 "k = 4, int l = 5,\n" 17872 " int m = 6) {\n" 17873 " const int j = 10;\n" 17874 " otherThing = 1;\n" 17875 "}", 17876 Alignment); 17877 verifyFormat("void SomeFunction(int parameter = 0) {\n" 17878 " int const i = 1;\n" 17879 " int *j = 2;\n" 17880 " int big = 10000;\n" 17881 "}", 17882 Alignment); 17883 verifyFormat("class C {\n" 17884 "public:\n" 17885 " int i = 1;\n" 17886 " virtual void f() = 0;\n" 17887 "};", 17888 Alignment); 17889 verifyFormat("float i = 1;\n" 17890 "if (SomeType t = getSomething()) {\n" 17891 "}\n" 17892 "const unsigned j = 2;\n" 17893 "int big = 10000;", 17894 Alignment); 17895 verifyFormat("float j = 7;\n" 17896 "for (int k = 0; k < N; ++k) {\n" 17897 "}\n" 17898 "unsigned j = 2;\n" 17899 "int big = 10000;\n" 17900 "}", 17901 Alignment); 17902 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 17903 verifyFormat("float i = 1;\n" 17904 "LooooooooooongType loooooooooooooooooooooongVariable\n" 17905 " = someLooooooooooooooooongFunction();\n" 17906 "int j = 2;", 17907 Alignment); 17908 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 17909 verifyFormat("int i = 1;\n" 17910 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 17911 " someLooooooooooooooooongFunction();\n" 17912 "int j = 2;", 17913 Alignment); 17914 17915 Alignment.AlignConsecutiveAssignments.Enabled = true; 17916 verifyFormat("auto lambda = []() {\n" 17917 " auto ii = 0;\n" 17918 " float j = 0;\n" 17919 " return 0;\n" 17920 "};\n" 17921 "int i = 0;\n" 17922 "float i2 = 0;\n" 17923 "auto v = type{\n" 17924 " i = 1, //\n" 17925 " (i = 2), //\n" 17926 " i = 3 //\n" 17927 "};", 17928 Alignment); 17929 Alignment.AlignConsecutiveAssignments.Enabled = false; 17930 17931 verifyFormat( 17932 "int i = 1;\n" 17933 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 17934 " loooooooooooooooooooooongParameterB);\n" 17935 "int j = 2;", 17936 Alignment); 17937 17938 // Test interactions with ColumnLimit and AlignConsecutiveAssignments: 17939 // We expect declarations and assignments to align, as long as it doesn't 17940 // exceed the column limit, starting a new alignment sequence whenever it 17941 // happens. 17942 Alignment.AlignConsecutiveAssignments.Enabled = true; 17943 Alignment.ColumnLimit = 30; 17944 verifyFormat("float ii = 1;\n" 17945 "unsigned j = 2;\n" 17946 "int someVerylongVariable = 1;\n" 17947 "AnotherLongType ll = 123456;\n" 17948 "VeryVeryLongType k = 2;\n" 17949 "int myvar = 1;", 17950 Alignment); 17951 Alignment.ColumnLimit = 80; 17952 Alignment.AlignConsecutiveAssignments.Enabled = false; 17953 17954 verifyFormat( 17955 "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n" 17956 " typename LongType, typename B>\n" 17957 "auto foo() {}\n", 17958 Alignment); 17959 verifyFormat("float a, b = 1;\n" 17960 "int c = 2;\n" 17961 "int dd = 3;\n", 17962 Alignment); 17963 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17964 "float b[1][] = {{3.f}};\n", 17965 Alignment); 17966 Alignment.AlignConsecutiveAssignments.Enabled = true; 17967 verifyFormat("float a, b = 1;\n" 17968 "int c = 2;\n" 17969 "int dd = 3;\n", 17970 Alignment); 17971 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17972 "float b[1][] = {{3.f}};\n", 17973 Alignment); 17974 Alignment.AlignConsecutiveAssignments.Enabled = false; 17975 17976 Alignment.ColumnLimit = 30; 17977 Alignment.BinPackParameters = false; 17978 verifyFormat("void foo(float a,\n" 17979 " float b,\n" 17980 " int c,\n" 17981 " uint32_t *d) {\n" 17982 " int *e = 0;\n" 17983 " float f = 0;\n" 17984 " double g = 0;\n" 17985 "}\n" 17986 "void bar(ino_t a,\n" 17987 " int b,\n" 17988 " uint32_t *c,\n" 17989 " bool d) {}\n", 17990 Alignment); 17991 Alignment.BinPackParameters = true; 17992 Alignment.ColumnLimit = 80; 17993 17994 // Bug 33507 17995 Alignment.PointerAlignment = FormatStyle::PAS_Middle; 17996 verifyFormat( 17997 "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n" 17998 " static const Version verVs2017;\n" 17999 " return true;\n" 18000 "});\n", 18001 Alignment); 18002 Alignment.PointerAlignment = FormatStyle::PAS_Right; 18003 18004 // See llvm.org/PR35641 18005 Alignment.AlignConsecutiveDeclarations.Enabled = true; 18006 verifyFormat("int func() { //\n" 18007 " int b;\n" 18008 " unsigned c;\n" 18009 "}", 18010 Alignment); 18011 18012 // See PR37175 18013 FormatStyle Style = getMozillaStyle(); 18014 Style.AlignConsecutiveDeclarations.Enabled = true; 18015 EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n" 18016 "foo(int a);", 18017 format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style)); 18018 18019 Alignment.PointerAlignment = FormatStyle::PAS_Left; 18020 verifyFormat("unsigned int* a;\n" 18021 "int* b;\n" 18022 "unsigned int Const* c;\n" 18023 "unsigned int const* d;\n" 18024 "unsigned int Const& e;\n" 18025 "unsigned int const& f;", 18026 Alignment); 18027 verifyFormat("Const unsigned int* c;\n" 18028 "const unsigned int* d;\n" 18029 "Const unsigned int& e;\n" 18030 "const unsigned int& f;\n" 18031 "const unsigned g;\n" 18032 "Const unsigned h;", 18033 Alignment); 18034 18035 Alignment.PointerAlignment = FormatStyle::PAS_Middle; 18036 verifyFormat("unsigned int * a;\n" 18037 "int * b;\n" 18038 "unsigned int Const * c;\n" 18039 "unsigned int const * d;\n" 18040 "unsigned int Const & e;\n" 18041 "unsigned int const & f;", 18042 Alignment); 18043 verifyFormat("Const unsigned int * c;\n" 18044 "const unsigned int * d;\n" 18045 "Const unsigned int & e;\n" 18046 "const unsigned int & f;\n" 18047 "const unsigned g;\n" 18048 "Const unsigned h;", 18049 Alignment); 18050 18051 // See PR46529 18052 FormatStyle BracedAlign = getLLVMStyle(); 18053 BracedAlign.AlignConsecutiveDeclarations.Enabled = true; 18054 verifyFormat("const auto result{[]() {\n" 18055 " const auto something = 1;\n" 18056 " return 2;\n" 18057 "}};", 18058 BracedAlign); 18059 verifyFormat("int foo{[]() {\n" 18060 " int bar{0};\n" 18061 " return 0;\n" 18062 "}()};", 18063 BracedAlign); 18064 BracedAlign.Cpp11BracedListStyle = false; 18065 verifyFormat("const auto result{ []() {\n" 18066 " const auto something = 1;\n" 18067 " return 2;\n" 18068 "} };", 18069 BracedAlign); 18070 verifyFormat("int foo{ []() {\n" 18071 " int bar{ 0 };\n" 18072 " return 0;\n" 18073 "}() };", 18074 BracedAlign); 18075 } 18076 18077 TEST_F(FormatTest, AlignWithLineBreaks) { 18078 auto Style = getLLVMStyleWithColumns(120); 18079 18080 EXPECT_EQ(Style.AlignConsecutiveAssignments, 18081 FormatStyle::AlignConsecutiveStyle( 18082 {/*Enabled=*/false, /*AcrossEmptyLines=*/false, 18083 /*AcrossComments=*/false, /*AlignCompound=*/false, 18084 /*PadOperators=*/true})); 18085 EXPECT_EQ(Style.AlignConsecutiveDeclarations, 18086 FormatStyle::AlignConsecutiveStyle({})); 18087 verifyFormat("void foo() {\n" 18088 " int myVar = 5;\n" 18089 " double x = 3.14;\n" 18090 " auto str = \"Hello \"\n" 18091 " \"World\";\n" 18092 " auto s = \"Hello \"\n" 18093 " \"Again\";\n" 18094 "}", 18095 Style); 18096 18097 // clang-format off 18098 verifyFormat("void foo() {\n" 18099 " const int capacityBefore = Entries.capacity();\n" 18100 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 18101 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 18102 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 18103 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 18104 "}", 18105 Style); 18106 // clang-format on 18107 18108 Style.AlignConsecutiveAssignments.Enabled = true; 18109 verifyFormat("void foo() {\n" 18110 " int myVar = 5;\n" 18111 " double x = 3.14;\n" 18112 " auto str = \"Hello \"\n" 18113 " \"World\";\n" 18114 " auto s = \"Hello \"\n" 18115 " \"Again\";\n" 18116 "}", 18117 Style); 18118 18119 // clang-format off 18120 verifyFormat("void foo() {\n" 18121 " const int capacityBefore = Entries.capacity();\n" 18122 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 18123 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 18124 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 18125 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 18126 "}", 18127 Style); 18128 // clang-format on 18129 18130 Style.AlignConsecutiveAssignments.Enabled = false; 18131 Style.AlignConsecutiveDeclarations.Enabled = true; 18132 verifyFormat("void foo() {\n" 18133 " int myVar = 5;\n" 18134 " double x = 3.14;\n" 18135 " auto str = \"Hello \"\n" 18136 " \"World\";\n" 18137 " auto s = \"Hello \"\n" 18138 " \"Again\";\n" 18139 "}", 18140 Style); 18141 18142 // clang-format off 18143 verifyFormat("void foo() {\n" 18144 " const int capacityBefore = Entries.capacity();\n" 18145 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 18146 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 18147 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 18148 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 18149 "}", 18150 Style); 18151 // clang-format on 18152 18153 Style.AlignConsecutiveAssignments.Enabled = true; 18154 Style.AlignConsecutiveDeclarations.Enabled = true; 18155 18156 verifyFormat("void foo() {\n" 18157 " int myVar = 5;\n" 18158 " double x = 3.14;\n" 18159 " auto str = \"Hello \"\n" 18160 " \"World\";\n" 18161 " auto s = \"Hello \"\n" 18162 " \"Again\";\n" 18163 "}", 18164 Style); 18165 18166 // clang-format off 18167 verifyFormat("void foo() {\n" 18168 " const int capacityBefore = Entries.capacity();\n" 18169 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 18170 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 18171 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 18172 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 18173 "}", 18174 Style); 18175 // clang-format on 18176 18177 Style = getLLVMStyleWithColumns(20); 18178 Style.AlignConsecutiveAssignments.Enabled = true; 18179 Style.IndentWidth = 4; 18180 18181 verifyFormat("void foo() {\n" 18182 " int i1 = 1;\n" 18183 " int j = 0;\n" 18184 " int k = bar(\n" 18185 " argument1,\n" 18186 " argument2);\n" 18187 "}", 18188 Style); 18189 18190 verifyFormat("unsigned i = 0;\n" 18191 "int a[] = {\n" 18192 " 1234567890,\n" 18193 " -1234567890};", 18194 Style); 18195 18196 Style.ColumnLimit = 120; 18197 18198 // clang-format off 18199 verifyFormat("void SomeFunc() {\n" 18200 " newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 18201 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 18202 " newWatcher.maxAge = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 18203 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 18204 " newWatcher.max = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 18205 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 18206 "}", 18207 Style); 18208 // clang-format on 18209 18210 Style.BinPackArguments = false; 18211 18212 // clang-format off 18213 verifyFormat("void SomeFunc() {\n" 18214 " newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(\n" 18215 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 18216 " newWatcher.maxAge = ToLegacyTimestamp(GetMaxAge(\n" 18217 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 18218 " newWatcher.max = ToLegacyTimestamp(GetMaxAge(\n" 18219 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 18220 "}", 18221 Style); 18222 // clang-format on 18223 } 18224 18225 TEST_F(FormatTest, AlignWithInitializerPeriods) { 18226 auto Style = getLLVMStyleWithColumns(60); 18227 18228 verifyFormat("void foo1(void) {\n" 18229 " BYTE p[1] = 1;\n" 18230 " A B = {.one_foooooooooooooooo = 2,\n" 18231 " .two_fooooooooooooo = 3,\n" 18232 " .three_fooooooooooooo = 4};\n" 18233 " BYTE payload = 2;\n" 18234 "}", 18235 Style); 18236 18237 Style.AlignConsecutiveAssignments.Enabled = true; 18238 Style.AlignConsecutiveDeclarations.Enabled = false; 18239 verifyFormat("void foo2(void) {\n" 18240 " BYTE p[1] = 1;\n" 18241 " A B = {.one_foooooooooooooooo = 2,\n" 18242 " .two_fooooooooooooo = 3,\n" 18243 " .three_fooooooooooooo = 4};\n" 18244 " BYTE payload = 2;\n" 18245 "}", 18246 Style); 18247 18248 Style.AlignConsecutiveAssignments.Enabled = false; 18249 Style.AlignConsecutiveDeclarations.Enabled = true; 18250 verifyFormat("void foo3(void) {\n" 18251 " BYTE p[1] = 1;\n" 18252 " A B = {.one_foooooooooooooooo = 2,\n" 18253 " .two_fooooooooooooo = 3,\n" 18254 " .three_fooooooooooooo = 4};\n" 18255 " BYTE payload = 2;\n" 18256 "}", 18257 Style); 18258 18259 Style.AlignConsecutiveAssignments.Enabled = true; 18260 Style.AlignConsecutiveDeclarations.Enabled = true; 18261 verifyFormat("void foo4(void) {\n" 18262 " BYTE p[1] = 1;\n" 18263 " A B = {.one_foooooooooooooooo = 2,\n" 18264 " .two_fooooooooooooo = 3,\n" 18265 " .three_fooooooooooooo = 4};\n" 18266 " BYTE payload = 2;\n" 18267 "}", 18268 Style); 18269 } 18270 18271 TEST_F(FormatTest, LinuxBraceBreaking) { 18272 FormatStyle LinuxBraceStyle = getLLVMStyle(); 18273 LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux; 18274 verifyFormat("namespace a\n" 18275 "{\n" 18276 "class A\n" 18277 "{\n" 18278 " void f()\n" 18279 " {\n" 18280 " if (true) {\n" 18281 " a();\n" 18282 " b();\n" 18283 " } else {\n" 18284 " a();\n" 18285 " }\n" 18286 " }\n" 18287 " void g() { return; }\n" 18288 "};\n" 18289 "struct B {\n" 18290 " int x;\n" 18291 "};\n" 18292 "} // namespace a\n", 18293 LinuxBraceStyle); 18294 verifyFormat("enum X {\n" 18295 " Y = 0,\n" 18296 "}\n", 18297 LinuxBraceStyle); 18298 verifyFormat("struct S {\n" 18299 " int Type;\n" 18300 " union {\n" 18301 " int x;\n" 18302 " double y;\n" 18303 " } Value;\n" 18304 " class C\n" 18305 " {\n" 18306 " MyFavoriteType Value;\n" 18307 " } Class;\n" 18308 "}\n", 18309 LinuxBraceStyle); 18310 } 18311 18312 TEST_F(FormatTest, MozillaBraceBreaking) { 18313 FormatStyle MozillaBraceStyle = getLLVMStyle(); 18314 MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla; 18315 MozillaBraceStyle.FixNamespaceComments = false; 18316 verifyFormat("namespace a {\n" 18317 "class A\n" 18318 "{\n" 18319 " void f()\n" 18320 " {\n" 18321 " if (true) {\n" 18322 " a();\n" 18323 " b();\n" 18324 " }\n" 18325 " }\n" 18326 " void g() { return; }\n" 18327 "};\n" 18328 "enum E\n" 18329 "{\n" 18330 " A,\n" 18331 " // foo\n" 18332 " B,\n" 18333 " C\n" 18334 "};\n" 18335 "struct B\n" 18336 "{\n" 18337 " int x;\n" 18338 "};\n" 18339 "}\n", 18340 MozillaBraceStyle); 18341 verifyFormat("struct S\n" 18342 "{\n" 18343 " int Type;\n" 18344 " union\n" 18345 " {\n" 18346 " int x;\n" 18347 " double y;\n" 18348 " } Value;\n" 18349 " class C\n" 18350 " {\n" 18351 " MyFavoriteType Value;\n" 18352 " } Class;\n" 18353 "}\n", 18354 MozillaBraceStyle); 18355 } 18356 18357 TEST_F(FormatTest, StroustrupBraceBreaking) { 18358 FormatStyle StroustrupBraceStyle = getLLVMStyle(); 18359 StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 18360 verifyFormat("namespace a {\n" 18361 "class A {\n" 18362 " void f()\n" 18363 " {\n" 18364 " if (true) {\n" 18365 " a();\n" 18366 " b();\n" 18367 " }\n" 18368 " }\n" 18369 " void g() { return; }\n" 18370 "};\n" 18371 "struct B {\n" 18372 " int x;\n" 18373 "};\n" 18374 "} // namespace a\n", 18375 StroustrupBraceStyle); 18376 18377 verifyFormat("void foo()\n" 18378 "{\n" 18379 " if (a) {\n" 18380 " a();\n" 18381 " }\n" 18382 " else {\n" 18383 " b();\n" 18384 " }\n" 18385 "}\n", 18386 StroustrupBraceStyle); 18387 18388 verifyFormat("#ifdef _DEBUG\n" 18389 "int foo(int i = 0)\n" 18390 "#else\n" 18391 "int foo(int i = 5)\n" 18392 "#endif\n" 18393 "{\n" 18394 " return i;\n" 18395 "}", 18396 StroustrupBraceStyle); 18397 18398 verifyFormat("void foo() {}\n" 18399 "void bar()\n" 18400 "#ifdef _DEBUG\n" 18401 "{\n" 18402 " foo();\n" 18403 "}\n" 18404 "#else\n" 18405 "{\n" 18406 "}\n" 18407 "#endif", 18408 StroustrupBraceStyle); 18409 18410 verifyFormat("void foobar() { int i = 5; }\n" 18411 "#ifdef _DEBUG\n" 18412 "void bar() {}\n" 18413 "#else\n" 18414 "void bar() { foobar(); }\n" 18415 "#endif", 18416 StroustrupBraceStyle); 18417 } 18418 18419 TEST_F(FormatTest, AllmanBraceBreaking) { 18420 FormatStyle AllmanBraceStyle = getLLVMStyle(); 18421 AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman; 18422 18423 EXPECT_EQ("namespace a\n" 18424 "{\n" 18425 "void f();\n" 18426 "void g();\n" 18427 "} // namespace a\n", 18428 format("namespace a\n" 18429 "{\n" 18430 "void f();\n" 18431 "void g();\n" 18432 "}\n", 18433 AllmanBraceStyle)); 18434 18435 verifyFormat("namespace a\n" 18436 "{\n" 18437 "class A\n" 18438 "{\n" 18439 " void f()\n" 18440 " {\n" 18441 " if (true)\n" 18442 " {\n" 18443 " a();\n" 18444 " b();\n" 18445 " }\n" 18446 " }\n" 18447 " void g() { return; }\n" 18448 "};\n" 18449 "struct B\n" 18450 "{\n" 18451 " int x;\n" 18452 "};\n" 18453 "union C\n" 18454 "{\n" 18455 "};\n" 18456 "} // namespace a", 18457 AllmanBraceStyle); 18458 18459 verifyFormat("void f()\n" 18460 "{\n" 18461 " if (true)\n" 18462 " {\n" 18463 " a();\n" 18464 " }\n" 18465 " else if (false)\n" 18466 " {\n" 18467 " b();\n" 18468 " }\n" 18469 " else\n" 18470 " {\n" 18471 " c();\n" 18472 " }\n" 18473 "}\n", 18474 AllmanBraceStyle); 18475 18476 verifyFormat("void f()\n" 18477 "{\n" 18478 " for (int i = 0; i < 10; ++i)\n" 18479 " {\n" 18480 " a();\n" 18481 " }\n" 18482 " while (false)\n" 18483 " {\n" 18484 " b();\n" 18485 " }\n" 18486 " do\n" 18487 " {\n" 18488 " c();\n" 18489 " } while (false)\n" 18490 "}\n", 18491 AllmanBraceStyle); 18492 18493 verifyFormat("void f(int a)\n" 18494 "{\n" 18495 " switch (a)\n" 18496 " {\n" 18497 " case 0:\n" 18498 " break;\n" 18499 " case 1:\n" 18500 " {\n" 18501 " break;\n" 18502 " }\n" 18503 " case 2:\n" 18504 " {\n" 18505 " }\n" 18506 " break;\n" 18507 " default:\n" 18508 " break;\n" 18509 " }\n" 18510 "}\n", 18511 AllmanBraceStyle); 18512 18513 verifyFormat("enum X\n" 18514 "{\n" 18515 " Y = 0,\n" 18516 "}\n", 18517 AllmanBraceStyle); 18518 verifyFormat("enum X\n" 18519 "{\n" 18520 " Y = 0\n" 18521 "}\n", 18522 AllmanBraceStyle); 18523 18524 verifyFormat("@interface BSApplicationController ()\n" 18525 "{\n" 18526 "@private\n" 18527 " id _extraIvar;\n" 18528 "}\n" 18529 "@end\n", 18530 AllmanBraceStyle); 18531 18532 verifyFormat("#ifdef _DEBUG\n" 18533 "int foo(int i = 0)\n" 18534 "#else\n" 18535 "int foo(int i = 5)\n" 18536 "#endif\n" 18537 "{\n" 18538 " return i;\n" 18539 "}", 18540 AllmanBraceStyle); 18541 18542 verifyFormat("void foo() {}\n" 18543 "void bar()\n" 18544 "#ifdef _DEBUG\n" 18545 "{\n" 18546 " foo();\n" 18547 "}\n" 18548 "#else\n" 18549 "{\n" 18550 "}\n" 18551 "#endif", 18552 AllmanBraceStyle); 18553 18554 verifyFormat("void foobar() { int i = 5; }\n" 18555 "#ifdef _DEBUG\n" 18556 "void bar() {}\n" 18557 "#else\n" 18558 "void bar() { foobar(); }\n" 18559 "#endif", 18560 AllmanBraceStyle); 18561 18562 EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine, 18563 FormatStyle::SLS_All); 18564 18565 verifyFormat("[](int i) { return i + 2; };\n" 18566 "[](int i, int j)\n" 18567 "{\n" 18568 " auto x = i + j;\n" 18569 " auto y = i * j;\n" 18570 " return x ^ y;\n" 18571 "};\n" 18572 "void foo()\n" 18573 "{\n" 18574 " auto shortLambda = [](int i) { return i + 2; };\n" 18575 " auto longLambda = [](int i, int j)\n" 18576 " {\n" 18577 " auto x = i + j;\n" 18578 " auto y = i * j;\n" 18579 " return x ^ y;\n" 18580 " };\n" 18581 "}", 18582 AllmanBraceStyle); 18583 18584 AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 18585 18586 verifyFormat("[](int i)\n" 18587 "{\n" 18588 " return i + 2;\n" 18589 "};\n" 18590 "[](int i, int j)\n" 18591 "{\n" 18592 " auto x = i + j;\n" 18593 " auto y = i * j;\n" 18594 " return x ^ y;\n" 18595 "};\n" 18596 "void foo()\n" 18597 "{\n" 18598 " auto shortLambda = [](int i)\n" 18599 " {\n" 18600 " return i + 2;\n" 18601 " };\n" 18602 " auto longLambda = [](int i, int j)\n" 18603 " {\n" 18604 " auto x = i + j;\n" 18605 " auto y = i * j;\n" 18606 " return x ^ y;\n" 18607 " };\n" 18608 "}", 18609 AllmanBraceStyle); 18610 18611 // Reset 18612 AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All; 18613 18614 // This shouldn't affect ObjC blocks.. 18615 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n" 18616 " // ...\n" 18617 " int i;\n" 18618 "}];", 18619 AllmanBraceStyle); 18620 verifyFormat("void (^block)(void) = ^{\n" 18621 " // ...\n" 18622 " int i;\n" 18623 "};", 18624 AllmanBraceStyle); 18625 // .. or dict literals. 18626 verifyFormat("void f()\n" 18627 "{\n" 18628 " // ...\n" 18629 " [object someMethod:@{@\"a\" : @\"b\"}];\n" 18630 "}", 18631 AllmanBraceStyle); 18632 verifyFormat("void f()\n" 18633 "{\n" 18634 " // ...\n" 18635 " [object someMethod:@{a : @\"b\"}];\n" 18636 "}", 18637 AllmanBraceStyle); 18638 verifyFormat("int f()\n" 18639 "{ // comment\n" 18640 " return 42;\n" 18641 "}", 18642 AllmanBraceStyle); 18643 18644 AllmanBraceStyle.ColumnLimit = 19; 18645 verifyFormat("void f() { int i; }", AllmanBraceStyle); 18646 AllmanBraceStyle.ColumnLimit = 18; 18647 verifyFormat("void f()\n" 18648 "{\n" 18649 " int i;\n" 18650 "}", 18651 AllmanBraceStyle); 18652 AllmanBraceStyle.ColumnLimit = 80; 18653 18654 FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle; 18655 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = 18656 FormatStyle::SIS_WithoutElse; 18657 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true; 18658 verifyFormat("void f(bool b)\n" 18659 "{\n" 18660 " if (b)\n" 18661 " {\n" 18662 " return;\n" 18663 " }\n" 18664 "}\n", 18665 BreakBeforeBraceShortIfs); 18666 verifyFormat("void f(bool b)\n" 18667 "{\n" 18668 " if constexpr (b)\n" 18669 " {\n" 18670 " return;\n" 18671 " }\n" 18672 "}\n", 18673 BreakBeforeBraceShortIfs); 18674 verifyFormat("void f(bool b)\n" 18675 "{\n" 18676 " if CONSTEXPR (b)\n" 18677 " {\n" 18678 " return;\n" 18679 " }\n" 18680 "}\n", 18681 BreakBeforeBraceShortIfs); 18682 verifyFormat("void f(bool b)\n" 18683 "{\n" 18684 " if (b) return;\n" 18685 "}\n", 18686 BreakBeforeBraceShortIfs); 18687 verifyFormat("void f(bool b)\n" 18688 "{\n" 18689 " if constexpr (b) return;\n" 18690 "}\n", 18691 BreakBeforeBraceShortIfs); 18692 verifyFormat("void f(bool b)\n" 18693 "{\n" 18694 " if CONSTEXPR (b) return;\n" 18695 "}\n", 18696 BreakBeforeBraceShortIfs); 18697 verifyFormat("void f(bool b)\n" 18698 "{\n" 18699 " while (b)\n" 18700 " {\n" 18701 " return;\n" 18702 " }\n" 18703 "}\n", 18704 BreakBeforeBraceShortIfs); 18705 } 18706 18707 TEST_F(FormatTest, WhitesmithsBraceBreaking) { 18708 FormatStyle WhitesmithsBraceStyle = getLLVMStyleWithColumns(0); 18709 WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 18710 18711 // Make a few changes to the style for testing purposes 18712 WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine = 18713 FormatStyle::SFS_Empty; 18714 WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 18715 18716 // FIXME: this test case can't decide whether there should be a blank line 18717 // after the ~D() line or not. It adds one if one doesn't exist in the test 18718 // and it removes the line if one exists. 18719 /* 18720 verifyFormat("class A;\n" 18721 "namespace B\n" 18722 " {\n" 18723 "class C;\n" 18724 "// Comment\n" 18725 "class D\n" 18726 " {\n" 18727 "public:\n" 18728 " D();\n" 18729 " ~D() {}\n" 18730 "private:\n" 18731 " enum E\n" 18732 " {\n" 18733 " F\n" 18734 " }\n" 18735 " };\n" 18736 " } // namespace B\n", 18737 WhitesmithsBraceStyle); 18738 */ 18739 18740 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None; 18741 verifyFormat("namespace a\n" 18742 " {\n" 18743 "class A\n" 18744 " {\n" 18745 " void f()\n" 18746 " {\n" 18747 " if (true)\n" 18748 " {\n" 18749 " a();\n" 18750 " b();\n" 18751 " }\n" 18752 " }\n" 18753 " void g()\n" 18754 " {\n" 18755 " return;\n" 18756 " }\n" 18757 " };\n" 18758 "struct B\n" 18759 " {\n" 18760 " int x;\n" 18761 " };\n" 18762 " } // namespace a", 18763 WhitesmithsBraceStyle); 18764 18765 verifyFormat("namespace a\n" 18766 " {\n" 18767 "namespace b\n" 18768 " {\n" 18769 "class A\n" 18770 " {\n" 18771 " void f()\n" 18772 " {\n" 18773 " if (true)\n" 18774 " {\n" 18775 " a();\n" 18776 " b();\n" 18777 " }\n" 18778 " }\n" 18779 " void g()\n" 18780 " {\n" 18781 " return;\n" 18782 " }\n" 18783 " };\n" 18784 "struct B\n" 18785 " {\n" 18786 " int x;\n" 18787 " };\n" 18788 " } // namespace b\n" 18789 " } // namespace a", 18790 WhitesmithsBraceStyle); 18791 18792 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner; 18793 verifyFormat("namespace a\n" 18794 " {\n" 18795 "namespace b\n" 18796 " {\n" 18797 " class A\n" 18798 " {\n" 18799 " void f()\n" 18800 " {\n" 18801 " if (true)\n" 18802 " {\n" 18803 " a();\n" 18804 " b();\n" 18805 " }\n" 18806 " }\n" 18807 " void g()\n" 18808 " {\n" 18809 " return;\n" 18810 " }\n" 18811 " };\n" 18812 " struct B\n" 18813 " {\n" 18814 " int x;\n" 18815 " };\n" 18816 " } // namespace b\n" 18817 " } // namespace a", 18818 WhitesmithsBraceStyle); 18819 18820 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All; 18821 verifyFormat("namespace a\n" 18822 " {\n" 18823 " namespace b\n" 18824 " {\n" 18825 " class A\n" 18826 " {\n" 18827 " void f()\n" 18828 " {\n" 18829 " if (true)\n" 18830 " {\n" 18831 " a();\n" 18832 " b();\n" 18833 " }\n" 18834 " }\n" 18835 " void g()\n" 18836 " {\n" 18837 " return;\n" 18838 " }\n" 18839 " };\n" 18840 " struct B\n" 18841 " {\n" 18842 " int x;\n" 18843 " };\n" 18844 " } // namespace b\n" 18845 " } // namespace a", 18846 WhitesmithsBraceStyle); 18847 18848 verifyFormat("void f()\n" 18849 " {\n" 18850 " if (true)\n" 18851 " {\n" 18852 " a();\n" 18853 " }\n" 18854 " else if (false)\n" 18855 " {\n" 18856 " b();\n" 18857 " }\n" 18858 " else\n" 18859 " {\n" 18860 " c();\n" 18861 " }\n" 18862 " }\n", 18863 WhitesmithsBraceStyle); 18864 18865 verifyFormat("void f()\n" 18866 " {\n" 18867 " for (int i = 0; i < 10; ++i)\n" 18868 " {\n" 18869 " a();\n" 18870 " }\n" 18871 " while (false)\n" 18872 " {\n" 18873 " b();\n" 18874 " }\n" 18875 " do\n" 18876 " {\n" 18877 " c();\n" 18878 " } while (false)\n" 18879 " }\n", 18880 WhitesmithsBraceStyle); 18881 18882 WhitesmithsBraceStyle.IndentCaseLabels = true; 18883 verifyFormat("void switchTest1(int a)\n" 18884 " {\n" 18885 " switch (a)\n" 18886 " {\n" 18887 " case 2:\n" 18888 " {\n" 18889 " }\n" 18890 " break;\n" 18891 " }\n" 18892 " }\n", 18893 WhitesmithsBraceStyle); 18894 18895 verifyFormat("void switchTest2(int a)\n" 18896 " {\n" 18897 " switch (a)\n" 18898 " {\n" 18899 " case 0:\n" 18900 " break;\n" 18901 " case 1:\n" 18902 " {\n" 18903 " break;\n" 18904 " }\n" 18905 " case 2:\n" 18906 " {\n" 18907 " }\n" 18908 " break;\n" 18909 " default:\n" 18910 " break;\n" 18911 " }\n" 18912 " }\n", 18913 WhitesmithsBraceStyle); 18914 18915 verifyFormat("void switchTest3(int a)\n" 18916 " {\n" 18917 " switch (a)\n" 18918 " {\n" 18919 " case 0:\n" 18920 " {\n" 18921 " foo(x);\n" 18922 " }\n" 18923 " break;\n" 18924 " default:\n" 18925 " {\n" 18926 " foo(1);\n" 18927 " }\n" 18928 " break;\n" 18929 " }\n" 18930 " }\n", 18931 WhitesmithsBraceStyle); 18932 18933 WhitesmithsBraceStyle.IndentCaseLabels = false; 18934 18935 verifyFormat("void switchTest4(int a)\n" 18936 " {\n" 18937 " switch (a)\n" 18938 " {\n" 18939 " case 2:\n" 18940 " {\n" 18941 " }\n" 18942 " break;\n" 18943 " }\n" 18944 " }\n", 18945 WhitesmithsBraceStyle); 18946 18947 verifyFormat("void switchTest5(int a)\n" 18948 " {\n" 18949 " switch (a)\n" 18950 " {\n" 18951 " case 0:\n" 18952 " break;\n" 18953 " case 1:\n" 18954 " {\n" 18955 " foo();\n" 18956 " break;\n" 18957 " }\n" 18958 " case 2:\n" 18959 " {\n" 18960 " }\n" 18961 " break;\n" 18962 " default:\n" 18963 " break;\n" 18964 " }\n" 18965 " }\n", 18966 WhitesmithsBraceStyle); 18967 18968 verifyFormat("void switchTest6(int a)\n" 18969 " {\n" 18970 " switch (a)\n" 18971 " {\n" 18972 " case 0:\n" 18973 " {\n" 18974 " foo(x);\n" 18975 " }\n" 18976 " break;\n" 18977 " default:\n" 18978 " {\n" 18979 " foo(1);\n" 18980 " }\n" 18981 " break;\n" 18982 " }\n" 18983 " }\n", 18984 WhitesmithsBraceStyle); 18985 18986 verifyFormat("enum X\n" 18987 " {\n" 18988 " Y = 0, // testing\n" 18989 " }\n", 18990 WhitesmithsBraceStyle); 18991 18992 verifyFormat("enum X\n" 18993 " {\n" 18994 " Y = 0\n" 18995 " }\n", 18996 WhitesmithsBraceStyle); 18997 verifyFormat("enum X\n" 18998 " {\n" 18999 " Y = 0,\n" 19000 " Z = 1\n" 19001 " };\n", 19002 WhitesmithsBraceStyle); 19003 19004 verifyFormat("@interface BSApplicationController ()\n" 19005 " {\n" 19006 "@private\n" 19007 " id _extraIvar;\n" 19008 " }\n" 19009 "@end\n", 19010 WhitesmithsBraceStyle); 19011 19012 verifyFormat("#ifdef _DEBUG\n" 19013 "int foo(int i = 0)\n" 19014 "#else\n" 19015 "int foo(int i = 5)\n" 19016 "#endif\n" 19017 " {\n" 19018 " return i;\n" 19019 " }", 19020 WhitesmithsBraceStyle); 19021 19022 verifyFormat("void foo() {}\n" 19023 "void bar()\n" 19024 "#ifdef _DEBUG\n" 19025 " {\n" 19026 " foo();\n" 19027 " }\n" 19028 "#else\n" 19029 " {\n" 19030 " }\n" 19031 "#endif", 19032 WhitesmithsBraceStyle); 19033 19034 verifyFormat("void foobar()\n" 19035 " {\n" 19036 " int i = 5;\n" 19037 " }\n" 19038 "#ifdef _DEBUG\n" 19039 "void bar()\n" 19040 " {\n" 19041 " }\n" 19042 "#else\n" 19043 "void bar()\n" 19044 " {\n" 19045 " foobar();\n" 19046 " }\n" 19047 "#endif", 19048 WhitesmithsBraceStyle); 19049 19050 // This shouldn't affect ObjC blocks.. 19051 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n" 19052 " // ...\n" 19053 " int i;\n" 19054 "}];", 19055 WhitesmithsBraceStyle); 19056 verifyFormat("void (^block)(void) = ^{\n" 19057 " // ...\n" 19058 " int i;\n" 19059 "};", 19060 WhitesmithsBraceStyle); 19061 // .. or dict literals. 19062 verifyFormat("void f()\n" 19063 " {\n" 19064 " [object someMethod:@{@\"a\" : @\"b\"}];\n" 19065 " }", 19066 WhitesmithsBraceStyle); 19067 19068 verifyFormat("int f()\n" 19069 " { // comment\n" 19070 " return 42;\n" 19071 " }", 19072 WhitesmithsBraceStyle); 19073 19074 FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle; 19075 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = 19076 FormatStyle::SIS_OnlyFirstIf; 19077 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true; 19078 verifyFormat("void f(bool b)\n" 19079 " {\n" 19080 " if (b)\n" 19081 " {\n" 19082 " return;\n" 19083 " }\n" 19084 " }\n", 19085 BreakBeforeBraceShortIfs); 19086 verifyFormat("void f(bool b)\n" 19087 " {\n" 19088 " if (b) return;\n" 19089 " }\n", 19090 BreakBeforeBraceShortIfs); 19091 verifyFormat("void f(bool b)\n" 19092 " {\n" 19093 " while (b)\n" 19094 " {\n" 19095 " return;\n" 19096 " }\n" 19097 " }\n", 19098 BreakBeforeBraceShortIfs); 19099 } 19100 19101 TEST_F(FormatTest, GNUBraceBreaking) { 19102 FormatStyle GNUBraceStyle = getLLVMStyle(); 19103 GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU; 19104 verifyFormat("namespace a\n" 19105 "{\n" 19106 "class A\n" 19107 "{\n" 19108 " void f()\n" 19109 " {\n" 19110 " int a;\n" 19111 " {\n" 19112 " int b;\n" 19113 " }\n" 19114 " if (true)\n" 19115 " {\n" 19116 " a();\n" 19117 " b();\n" 19118 " }\n" 19119 " }\n" 19120 " void g() { return; }\n" 19121 "}\n" 19122 "} // namespace a", 19123 GNUBraceStyle); 19124 19125 verifyFormat("void f()\n" 19126 "{\n" 19127 " if (true)\n" 19128 " {\n" 19129 " a();\n" 19130 " }\n" 19131 " else if (false)\n" 19132 " {\n" 19133 " b();\n" 19134 " }\n" 19135 " else\n" 19136 " {\n" 19137 " c();\n" 19138 " }\n" 19139 "}\n", 19140 GNUBraceStyle); 19141 19142 verifyFormat("void f()\n" 19143 "{\n" 19144 " for (int i = 0; i < 10; ++i)\n" 19145 " {\n" 19146 " a();\n" 19147 " }\n" 19148 " while (false)\n" 19149 " {\n" 19150 " b();\n" 19151 " }\n" 19152 " do\n" 19153 " {\n" 19154 " c();\n" 19155 " }\n" 19156 " while (false);\n" 19157 "}\n", 19158 GNUBraceStyle); 19159 19160 verifyFormat("void f(int a)\n" 19161 "{\n" 19162 " switch (a)\n" 19163 " {\n" 19164 " case 0:\n" 19165 " break;\n" 19166 " case 1:\n" 19167 " {\n" 19168 " break;\n" 19169 " }\n" 19170 " case 2:\n" 19171 " {\n" 19172 " }\n" 19173 " break;\n" 19174 " default:\n" 19175 " break;\n" 19176 " }\n" 19177 "}\n", 19178 GNUBraceStyle); 19179 19180 verifyFormat("enum X\n" 19181 "{\n" 19182 " Y = 0,\n" 19183 "}\n", 19184 GNUBraceStyle); 19185 19186 verifyFormat("@interface BSApplicationController ()\n" 19187 "{\n" 19188 "@private\n" 19189 " id _extraIvar;\n" 19190 "}\n" 19191 "@end\n", 19192 GNUBraceStyle); 19193 19194 verifyFormat("#ifdef _DEBUG\n" 19195 "int foo(int i = 0)\n" 19196 "#else\n" 19197 "int foo(int i = 5)\n" 19198 "#endif\n" 19199 "{\n" 19200 " return i;\n" 19201 "}", 19202 GNUBraceStyle); 19203 19204 verifyFormat("void foo() {}\n" 19205 "void bar()\n" 19206 "#ifdef _DEBUG\n" 19207 "{\n" 19208 " foo();\n" 19209 "}\n" 19210 "#else\n" 19211 "{\n" 19212 "}\n" 19213 "#endif", 19214 GNUBraceStyle); 19215 19216 verifyFormat("void foobar() { int i = 5; }\n" 19217 "#ifdef _DEBUG\n" 19218 "void bar() {}\n" 19219 "#else\n" 19220 "void bar() { foobar(); }\n" 19221 "#endif", 19222 GNUBraceStyle); 19223 } 19224 19225 TEST_F(FormatTest, WebKitBraceBreaking) { 19226 FormatStyle WebKitBraceStyle = getLLVMStyle(); 19227 WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit; 19228 WebKitBraceStyle.FixNamespaceComments = false; 19229 verifyFormat("namespace a {\n" 19230 "class A {\n" 19231 " void f()\n" 19232 " {\n" 19233 " if (true) {\n" 19234 " a();\n" 19235 " b();\n" 19236 " }\n" 19237 " }\n" 19238 " void g() { return; }\n" 19239 "};\n" 19240 "enum E {\n" 19241 " A,\n" 19242 " // foo\n" 19243 " B,\n" 19244 " C\n" 19245 "};\n" 19246 "struct B {\n" 19247 " int x;\n" 19248 "};\n" 19249 "}\n", 19250 WebKitBraceStyle); 19251 verifyFormat("struct S {\n" 19252 " int Type;\n" 19253 " union {\n" 19254 " int x;\n" 19255 " double y;\n" 19256 " } Value;\n" 19257 " class C {\n" 19258 " MyFavoriteType Value;\n" 19259 " } Class;\n" 19260 "};\n", 19261 WebKitBraceStyle); 19262 } 19263 19264 TEST_F(FormatTest, CatchExceptionReferenceBinding) { 19265 verifyFormat("void f() {\n" 19266 " try {\n" 19267 " } catch (const Exception &e) {\n" 19268 " }\n" 19269 "}\n", 19270 getLLVMStyle()); 19271 } 19272 19273 TEST_F(FormatTest, CatchAlignArrayOfStructuresRightAlignment) { 19274 auto Style = getLLVMStyle(); 19275 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 19276 Style.AlignConsecutiveAssignments.Enabled = true; 19277 Style.AlignConsecutiveDeclarations.Enabled = true; 19278 verifyFormat("struct test demo[] = {\n" 19279 " {56, 23, \"hello\"},\n" 19280 " {-1, 93463, \"world\"},\n" 19281 " { 7, 5, \"!!\"}\n" 19282 "};\n", 19283 Style); 19284 19285 verifyFormat("struct test demo[] = {\n" 19286 " {56, 23, \"hello\"}, // first line\n" 19287 " {-1, 93463, \"world\"}, // second line\n" 19288 " { 7, 5, \"!!\"} // third line\n" 19289 "};\n", 19290 Style); 19291 19292 verifyFormat("struct test demo[4] = {\n" 19293 " { 56, 23, 21, \"oh\"}, // first line\n" 19294 " { -1, 93463, 22, \"my\"}, // second line\n" 19295 " { 7, 5, 1, \"goodness\"} // third line\n" 19296 " {234, 5, 1, \"gracious\"} // fourth line\n" 19297 "};\n", 19298 Style); 19299 19300 verifyFormat("struct test demo[3] = {\n" 19301 " {56, 23, \"hello\"},\n" 19302 " {-1, 93463, \"world\"},\n" 19303 " { 7, 5, \"!!\"}\n" 19304 "};\n", 19305 Style); 19306 19307 verifyFormat("struct test demo[3] = {\n" 19308 " {int{56}, 23, \"hello\"},\n" 19309 " {int{-1}, 93463, \"world\"},\n" 19310 " { int{7}, 5, \"!!\"}\n" 19311 "};\n", 19312 Style); 19313 19314 verifyFormat("struct test demo[] = {\n" 19315 " {56, 23, \"hello\"},\n" 19316 " {-1, 93463, \"world\"},\n" 19317 " { 7, 5, \"!!\"},\n" 19318 "};\n", 19319 Style); 19320 19321 verifyFormat("test demo[] = {\n" 19322 " {56, 23, \"hello\"},\n" 19323 " {-1, 93463, \"world\"},\n" 19324 " { 7, 5, \"!!\"},\n" 19325 "};\n", 19326 Style); 19327 19328 verifyFormat("demo = std::array<struct test, 3>{\n" 19329 " test{56, 23, \"hello\"},\n" 19330 " test{-1, 93463, \"world\"},\n" 19331 " test{ 7, 5, \"!!\"},\n" 19332 "};\n", 19333 Style); 19334 19335 verifyFormat("test demo[] = {\n" 19336 " {56, 23, \"hello\"},\n" 19337 "#if X\n" 19338 " {-1, 93463, \"world\"},\n" 19339 "#endif\n" 19340 " { 7, 5, \"!!\"}\n" 19341 "};\n", 19342 Style); 19343 19344 verifyFormat( 19345 "test demo[] = {\n" 19346 " { 7, 23,\n" 19347 " \"hello world i am a very long line that really, in any\"\n" 19348 " \"just world, ought to be split over multiple lines\"},\n" 19349 " {-1, 93463, \"world\"},\n" 19350 " {56, 5, \"!!\"}\n" 19351 "};\n", 19352 Style); 19353 19354 verifyFormat("return GradForUnaryCwise(g, {\n" 19355 " {{\"sign\"}, \"Sign\", " 19356 " {\"x\", \"dy\"}},\n" 19357 " { {\"dx\"}, \"Mul\", {\"dy\"" 19358 ", \"sign\"}},\n" 19359 "});\n", 19360 Style); 19361 19362 Style.ColumnLimit = 0; 19363 EXPECT_EQ( 19364 "test demo[] = {\n" 19365 " {56, 23, \"hello world i am a very long line that really, " 19366 "in any just world, ought to be split over multiple lines\"},\n" 19367 " {-1, 93463, " 19368 " \"world\"},\n" 19369 " { 7, 5, " 19370 " \"!!\"},\n" 19371 "};", 19372 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19373 "that really, in any just world, ought to be split over multiple " 19374 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19375 Style)); 19376 19377 Style.ColumnLimit = 80; 19378 verifyFormat("test demo[] = {\n" 19379 " {56, 23, /* a comment */ \"hello\"},\n" 19380 " {-1, 93463, \"world\"},\n" 19381 " { 7, 5, \"!!\"}\n" 19382 "};\n", 19383 Style); 19384 19385 verifyFormat("test demo[] = {\n" 19386 " {56, 23, \"hello\"},\n" 19387 " {-1, 93463, \"world\" /* comment here */},\n" 19388 " { 7, 5, \"!!\"}\n" 19389 "};\n", 19390 Style); 19391 19392 verifyFormat("test demo[] = {\n" 19393 " {56, /* a comment */ 23, \"hello\"},\n" 19394 " {-1, 93463, \"world\"},\n" 19395 " { 7, 5, \"!!\"}\n" 19396 "};\n", 19397 Style); 19398 19399 Style.ColumnLimit = 20; 19400 EXPECT_EQ( 19401 "demo = std::array<\n" 19402 " struct test, 3>{\n" 19403 " test{\n" 19404 " 56, 23,\n" 19405 " \"hello \"\n" 19406 " \"world i \"\n" 19407 " \"am a very \"\n" 19408 " \"long line \"\n" 19409 " \"that \"\n" 19410 " \"really, \"\n" 19411 " \"in any \"\n" 19412 " \"just \"\n" 19413 " \"world, \"\n" 19414 " \"ought to \"\n" 19415 " \"be split \"\n" 19416 " \"over \"\n" 19417 " \"multiple \"\n" 19418 " \"lines\"},\n" 19419 " test{-1, 93463,\n" 19420 " \"world\"},\n" 19421 " test{ 7, 5,\n" 19422 " \"!!\" },\n" 19423 "};", 19424 format("demo = std::array<struct test, 3>{test{56, 23, \"hello world " 19425 "i am a very long line that really, in any just world, ought " 19426 "to be split over multiple lines\"},test{-1, 93463, \"world\"}," 19427 "test{7, 5, \"!!\"},};", 19428 Style)); 19429 // This caused a core dump by enabling Alignment in the LLVMStyle globally 19430 Style = getLLVMStyleWithColumns(50); 19431 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 19432 verifyFormat("static A x = {\n" 19433 " {{init1, init2, init3, init4},\n" 19434 " {init1, init2, init3, init4}}\n" 19435 "};", 19436 Style); 19437 // TODO: Fix the indentations below when this option is fully functional. 19438 verifyFormat("int a[][] = {\n" 19439 " {\n" 19440 " {0, 2}, //\n" 19441 " {1, 2} //\n" 19442 " }\n" 19443 "};", 19444 Style); 19445 Style.ColumnLimit = 100; 19446 EXPECT_EQ( 19447 "test demo[] = {\n" 19448 " {56, 23,\n" 19449 " \"hello world i am a very long line that really, in any just world" 19450 ", ought to be split over \"\n" 19451 " \"multiple lines\" },\n" 19452 " {-1, 93463, \"world\"},\n" 19453 " { 7, 5, \"!!\"},\n" 19454 "};", 19455 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19456 "that really, in any just world, ought to be split over multiple " 19457 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19458 Style)); 19459 19460 Style = getLLVMStyleWithColumns(50); 19461 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 19462 verifyFormat("struct test demo[] = {\n" 19463 " {56, 23, \"hello\"},\n" 19464 " {-1, 93463, \"world\"},\n" 19465 " { 7, 5, \"!!\"}\n" 19466 "};\n" 19467 "static A x = {\n" 19468 " {{init1, init2, init3, init4},\n" 19469 " {init1, init2, init3, init4}}\n" 19470 "};", 19471 Style); 19472 Style.ColumnLimit = 100; 19473 Style.AlignConsecutiveAssignments.AcrossComments = true; 19474 Style.AlignConsecutiveDeclarations.AcrossComments = true; 19475 verifyFormat("struct test demo[] = {\n" 19476 " {56, 23, \"hello\"},\n" 19477 " {-1, 93463, \"world\"},\n" 19478 " { 7, 5, \"!!\"}\n" 19479 "};\n" 19480 "struct test demo[4] = {\n" 19481 " { 56, 23, 21, \"oh\"}, // first line\n" 19482 " { -1, 93463, 22, \"my\"}, // second line\n" 19483 " { 7, 5, 1, \"goodness\"} // third line\n" 19484 " {234, 5, 1, \"gracious\"} // fourth line\n" 19485 "};\n", 19486 Style); 19487 EXPECT_EQ( 19488 "test demo[] = {\n" 19489 " {56,\n" 19490 " \"hello world i am a very long line that really, in any just world" 19491 ", ought to be split over \"\n" 19492 " \"multiple lines\", 23},\n" 19493 " {-1, \"world\", 93463},\n" 19494 " { 7, \"!!\", 5},\n" 19495 "};", 19496 format("test demo[] = {{56, \"hello world i am a very long line " 19497 "that really, in any just world, ought to be split over multiple " 19498 "lines\", 23},{-1, \"world\", 93463},{7, \"!!\", 5},};", 19499 Style)); 19500 } 19501 19502 TEST_F(FormatTest, CatchAlignArrayOfStructuresLeftAlignment) { 19503 auto Style = getLLVMStyle(); 19504 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 19505 /* FIXME: This case gets misformatted. 19506 verifyFormat("auto foo = Items{\n" 19507 " Section{0, bar(), },\n" 19508 " Section{1, boo() }\n" 19509 "};\n", 19510 Style); 19511 */ 19512 verifyFormat("auto foo = Items{\n" 19513 " Section{\n" 19514 " 0, bar(),\n" 19515 " }\n" 19516 "};\n", 19517 Style); 19518 verifyFormat("struct test demo[] = {\n" 19519 " {56, 23, \"hello\"},\n" 19520 " {-1, 93463, \"world\"},\n" 19521 " {7, 5, \"!!\" }\n" 19522 "};\n", 19523 Style); 19524 verifyFormat("struct test demo[] = {\n" 19525 " {56, 23, \"hello\"}, // first line\n" 19526 " {-1, 93463, \"world\"}, // second line\n" 19527 " {7, 5, \"!!\" } // third line\n" 19528 "};\n", 19529 Style); 19530 verifyFormat("struct test demo[4] = {\n" 19531 " {56, 23, 21, \"oh\" }, // first line\n" 19532 " {-1, 93463, 22, \"my\" }, // second line\n" 19533 " {7, 5, 1, \"goodness\"} // third line\n" 19534 " {234, 5, 1, \"gracious\"} // fourth line\n" 19535 "};\n", 19536 Style); 19537 verifyFormat("struct test demo[3] = {\n" 19538 " {56, 23, \"hello\"},\n" 19539 " {-1, 93463, \"world\"},\n" 19540 " {7, 5, \"!!\" }\n" 19541 "};\n", 19542 Style); 19543 19544 verifyFormat("struct test demo[3] = {\n" 19545 " {int{56}, 23, \"hello\"},\n" 19546 " {int{-1}, 93463, \"world\"},\n" 19547 " {int{7}, 5, \"!!\" }\n" 19548 "};\n", 19549 Style); 19550 verifyFormat("struct test demo[] = {\n" 19551 " {56, 23, \"hello\"},\n" 19552 " {-1, 93463, \"world\"},\n" 19553 " {7, 5, \"!!\" },\n" 19554 "};\n", 19555 Style); 19556 verifyFormat("test demo[] = {\n" 19557 " {56, 23, \"hello\"},\n" 19558 " {-1, 93463, \"world\"},\n" 19559 " {7, 5, \"!!\" },\n" 19560 "};\n", 19561 Style); 19562 verifyFormat("demo = std::array<struct test, 3>{\n" 19563 " test{56, 23, \"hello\"},\n" 19564 " test{-1, 93463, \"world\"},\n" 19565 " test{7, 5, \"!!\" },\n" 19566 "};\n", 19567 Style); 19568 verifyFormat("test demo[] = {\n" 19569 " {56, 23, \"hello\"},\n" 19570 "#if X\n" 19571 " {-1, 93463, \"world\"},\n" 19572 "#endif\n" 19573 " {7, 5, \"!!\" }\n" 19574 "};\n", 19575 Style); 19576 verifyFormat( 19577 "test demo[] = {\n" 19578 " {7, 23,\n" 19579 " \"hello world i am a very long line that really, in any\"\n" 19580 " \"just world, ought to be split over multiple lines\"},\n" 19581 " {-1, 93463, \"world\" },\n" 19582 " {56, 5, \"!!\" }\n" 19583 "};\n", 19584 Style); 19585 19586 verifyFormat("return GradForUnaryCwise(g, {\n" 19587 " {{\"sign\"}, \"Sign\", {\"x\", " 19588 "\"dy\"} },\n" 19589 " {{\"dx\"}, \"Mul\", " 19590 "{\"dy\", \"sign\"}},\n" 19591 "});\n", 19592 Style); 19593 19594 Style.ColumnLimit = 0; 19595 EXPECT_EQ( 19596 "test demo[] = {\n" 19597 " {56, 23, \"hello world i am a very long line that really, in any " 19598 "just world, ought to be split over multiple lines\"},\n" 19599 " {-1, 93463, \"world\" " 19600 " },\n" 19601 " {7, 5, \"!!\" " 19602 " },\n" 19603 "};", 19604 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19605 "that really, in any just world, ought to be split over multiple " 19606 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19607 Style)); 19608 19609 Style.ColumnLimit = 80; 19610 verifyFormat("test demo[] = {\n" 19611 " {56, 23, /* a comment */ \"hello\"},\n" 19612 " {-1, 93463, \"world\" },\n" 19613 " {7, 5, \"!!\" }\n" 19614 "};\n", 19615 Style); 19616 19617 verifyFormat("test demo[] = {\n" 19618 " {56, 23, \"hello\" },\n" 19619 " {-1, 93463, \"world\" /* comment here */},\n" 19620 " {7, 5, \"!!\" }\n" 19621 "};\n", 19622 Style); 19623 19624 verifyFormat("test demo[] = {\n" 19625 " {56, /* a comment */ 23, \"hello\"},\n" 19626 " {-1, 93463, \"world\"},\n" 19627 " {7, 5, \"!!\" }\n" 19628 "};\n", 19629 Style); 19630 19631 Style.ColumnLimit = 20; 19632 EXPECT_EQ( 19633 "demo = std::array<\n" 19634 " struct test, 3>{\n" 19635 " test{\n" 19636 " 56, 23,\n" 19637 " \"hello \"\n" 19638 " \"world i \"\n" 19639 " \"am a very \"\n" 19640 " \"long line \"\n" 19641 " \"that \"\n" 19642 " \"really, \"\n" 19643 " \"in any \"\n" 19644 " \"just \"\n" 19645 " \"world, \"\n" 19646 " \"ought to \"\n" 19647 " \"be split \"\n" 19648 " \"over \"\n" 19649 " \"multiple \"\n" 19650 " \"lines\"},\n" 19651 " test{-1, 93463,\n" 19652 " \"world\"},\n" 19653 " test{7, 5,\n" 19654 " \"!!\" },\n" 19655 "};", 19656 format("demo = std::array<struct test, 3>{test{56, 23, \"hello world " 19657 "i am a very long line that really, in any just world, ought " 19658 "to be split over multiple lines\"},test{-1, 93463, \"world\"}," 19659 "test{7, 5, \"!!\"},};", 19660 Style)); 19661 19662 // This caused a core dump by enabling Alignment in the LLVMStyle globally 19663 Style = getLLVMStyleWithColumns(50); 19664 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 19665 verifyFormat("static A x = {\n" 19666 " {{init1, init2, init3, init4},\n" 19667 " {init1, init2, init3, init4}}\n" 19668 "};", 19669 Style); 19670 Style.ColumnLimit = 100; 19671 EXPECT_EQ( 19672 "test demo[] = {\n" 19673 " {56, 23,\n" 19674 " \"hello world i am a very long line that really, in any just world" 19675 ", ought to be split over \"\n" 19676 " \"multiple lines\" },\n" 19677 " {-1, 93463, \"world\"},\n" 19678 " {7, 5, \"!!\" },\n" 19679 "};", 19680 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19681 "that really, in any just world, ought to be split over multiple " 19682 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19683 Style)); 19684 } 19685 19686 TEST_F(FormatTest, UnderstandsPragmas) { 19687 verifyFormat("#pragma omp reduction(| : var)"); 19688 verifyFormat("#pragma omp reduction(+ : var)"); 19689 19690 EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string " 19691 "(including parentheses).", 19692 format("#pragma mark Any non-hyphenated or hyphenated string " 19693 "(including parentheses).")); 19694 } 19695 19696 TEST_F(FormatTest, UnderstandPragmaOption) { 19697 verifyFormat("#pragma option -C -A"); 19698 19699 EXPECT_EQ("#pragma option -C -A", format("#pragma option -C -A")); 19700 } 19701 19702 TEST_F(FormatTest, UnderstandPragmaRegion) { 19703 auto Style = getLLVMStyleWithColumns(0); 19704 verifyFormat("#pragma region TEST(FOO : BAR)", Style); 19705 19706 EXPECT_EQ("#pragma region TEST(FOO : BAR)", 19707 format("#pragma region TEST(FOO : BAR)", Style)); 19708 } 19709 19710 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) { 19711 FormatStyle Style = getLLVMStyleWithColumns(20); 19712 19713 // See PR41213 19714 EXPECT_EQ("/*\n" 19715 " *\t9012345\n" 19716 " * /8901\n" 19717 " */", 19718 format("/*\n" 19719 " *\t9012345 /8901\n" 19720 " */", 19721 Style)); 19722 EXPECT_EQ("/*\n" 19723 " *345678\n" 19724 " *\t/8901\n" 19725 " */", 19726 format("/*\n" 19727 " *345678\t/8901\n" 19728 " */", 19729 Style)); 19730 19731 verifyFormat("int a; // the\n" 19732 " // comment", 19733 Style); 19734 EXPECT_EQ("int a; /* first line\n" 19735 " * second\n" 19736 " * line third\n" 19737 " * line\n" 19738 " */", 19739 format("int a; /* first line\n" 19740 " * second\n" 19741 " * line third\n" 19742 " * line\n" 19743 " */", 19744 Style)); 19745 EXPECT_EQ("int a; // first line\n" 19746 " // second\n" 19747 " // line third\n" 19748 " // line", 19749 format("int a; // first line\n" 19750 " // second line\n" 19751 " // third line", 19752 Style)); 19753 19754 Style.PenaltyExcessCharacter = 90; 19755 verifyFormat("int a; // the comment", Style); 19756 EXPECT_EQ("int a; // the comment\n" 19757 " // aaa", 19758 format("int a; // the comment aaa", Style)); 19759 EXPECT_EQ("int a; /* first line\n" 19760 " * second line\n" 19761 " * third line\n" 19762 " */", 19763 format("int a; /* first line\n" 19764 " * second line\n" 19765 " * third line\n" 19766 " */", 19767 Style)); 19768 EXPECT_EQ("int a; // first line\n" 19769 " // second line\n" 19770 " // third line", 19771 format("int a; // first line\n" 19772 " // second line\n" 19773 " // third line", 19774 Style)); 19775 // FIXME: Investigate why this is not getting the same layout as the test 19776 // above. 19777 EXPECT_EQ("int a; /* first line\n" 19778 " * second line\n" 19779 " * third line\n" 19780 " */", 19781 format("int a; /* first line second line third line" 19782 "\n*/", 19783 Style)); 19784 19785 EXPECT_EQ("// foo bar baz bazfoo\n" 19786 "// foo bar foo bar\n", 19787 format("// foo bar baz bazfoo\n" 19788 "// foo bar foo bar\n", 19789 Style)); 19790 EXPECT_EQ("// foo bar baz bazfoo\n" 19791 "// foo bar foo bar\n", 19792 format("// foo bar baz bazfoo\n" 19793 "// foo bar foo bar\n", 19794 Style)); 19795 19796 // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the 19797 // next one. 19798 EXPECT_EQ("// foo bar baz bazfoo\n" 19799 "// bar foo bar\n", 19800 format("// foo bar baz bazfoo bar\n" 19801 "// foo bar\n", 19802 Style)); 19803 19804 EXPECT_EQ("// foo bar baz bazfoo\n" 19805 "// foo bar baz bazfoo\n" 19806 "// bar foo bar\n", 19807 format("// foo bar baz bazfoo\n" 19808 "// foo bar baz bazfoo bar\n" 19809 "// foo bar\n", 19810 Style)); 19811 19812 EXPECT_EQ("// foo bar baz bazfoo\n" 19813 "// foo bar baz bazfoo\n" 19814 "// bar foo bar\n", 19815 format("// foo bar baz bazfoo\n" 19816 "// foo bar baz bazfoo bar\n" 19817 "// foo bar\n", 19818 Style)); 19819 19820 // Make sure we do not keep protruding characters if strict mode reflow is 19821 // cheaper than keeping protruding characters. 19822 Style.ColumnLimit = 21; 19823 EXPECT_EQ( 19824 "// foo foo foo foo\n" 19825 "// foo foo foo foo\n" 19826 "// foo foo foo foo\n", 19827 format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style)); 19828 19829 EXPECT_EQ("int a = /* long block\n" 19830 " comment */\n" 19831 " 42;", 19832 format("int a = /* long block comment */ 42;", Style)); 19833 } 19834 19835 TEST_F(FormatTest, BreakPenaltyAfterLParen) { 19836 FormatStyle Style = getLLVMStyle(); 19837 Style.ColumnLimit = 8; 19838 Style.PenaltyExcessCharacter = 15; 19839 verifyFormat("int foo(\n" 19840 " int aaaaaaaaaaaaaaaaaaaaaaaa);", 19841 Style); 19842 Style.PenaltyBreakOpenParenthesis = 200; 19843 EXPECT_EQ("int foo(int aaaaaaaaaaaaaaaaaaaaaaaa);", 19844 format("int foo(\n" 19845 " int aaaaaaaaaaaaaaaaaaaaaaaa);", 19846 Style)); 19847 } 19848 19849 TEST_F(FormatTest, BreakPenaltyAfterCastLParen) { 19850 FormatStyle Style = getLLVMStyle(); 19851 Style.ColumnLimit = 5; 19852 Style.PenaltyExcessCharacter = 150; 19853 verifyFormat("foo((\n" 19854 " int)aaaaaaaaaaaaaaaaaaaaaaaa);", 19855 19856 Style); 19857 Style.PenaltyBreakOpenParenthesis = 100000; 19858 EXPECT_EQ("foo((int)\n" 19859 " aaaaaaaaaaaaaaaaaaaaaaaa);", 19860 format("foo((\n" 19861 "int)aaaaaaaaaaaaaaaaaaaaaaaa);", 19862 Style)); 19863 } 19864 19865 TEST_F(FormatTest, BreakPenaltyAfterForLoopLParen) { 19866 FormatStyle Style = getLLVMStyle(); 19867 Style.ColumnLimit = 4; 19868 Style.PenaltyExcessCharacter = 100; 19869 verifyFormat("for (\n" 19870 " int iiiiiiiiiiiiiiiii =\n" 19871 " 0;\n" 19872 " iiiiiiiiiiiiiiiii <\n" 19873 " 2;\n" 19874 " iiiiiiiiiiiiiiiii++) {\n" 19875 "}", 19876 19877 Style); 19878 Style.PenaltyBreakOpenParenthesis = 1250; 19879 EXPECT_EQ("for (int iiiiiiiiiiiiiiiii =\n" 19880 " 0;\n" 19881 " iiiiiiiiiiiiiiiii <\n" 19882 " 2;\n" 19883 " iiiiiiiiiiiiiiiii++) {\n" 19884 "}", 19885 format("for (\n" 19886 " int iiiiiiiiiiiiiiiii =\n" 19887 " 0;\n" 19888 " iiiiiiiiiiiiiiiii <\n" 19889 " 2;\n" 19890 " iiiiiiiiiiiiiiiii++) {\n" 19891 "}", 19892 Style)); 19893 } 19894 19895 #define EXPECT_ALL_STYLES_EQUAL(Styles) \ 19896 for (size_t i = 1; i < Styles.size(); ++i) \ 19897 EXPECT_EQ(Styles[0], Styles[i]) \ 19898 << "Style #" << i << " of " << Styles.size() << " differs from Style #0" 19899 19900 TEST_F(FormatTest, GetsPredefinedStyleByName) { 19901 SmallVector<FormatStyle, 3> Styles; 19902 Styles.resize(3); 19903 19904 Styles[0] = getLLVMStyle(); 19905 EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1])); 19906 EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2])); 19907 EXPECT_ALL_STYLES_EQUAL(Styles); 19908 19909 Styles[0] = getGoogleStyle(); 19910 EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1])); 19911 EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2])); 19912 EXPECT_ALL_STYLES_EQUAL(Styles); 19913 19914 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript); 19915 EXPECT_TRUE( 19916 getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1])); 19917 EXPECT_TRUE( 19918 getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2])); 19919 EXPECT_ALL_STYLES_EQUAL(Styles); 19920 19921 Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp); 19922 EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1])); 19923 EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2])); 19924 EXPECT_ALL_STYLES_EQUAL(Styles); 19925 19926 Styles[0] = getMozillaStyle(); 19927 EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1])); 19928 EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2])); 19929 EXPECT_ALL_STYLES_EQUAL(Styles); 19930 19931 Styles[0] = getWebKitStyle(); 19932 EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1])); 19933 EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2])); 19934 EXPECT_ALL_STYLES_EQUAL(Styles); 19935 19936 Styles[0] = getGNUStyle(); 19937 EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1])); 19938 EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2])); 19939 EXPECT_ALL_STYLES_EQUAL(Styles); 19940 19941 EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0])); 19942 } 19943 19944 TEST_F(FormatTest, GetsCorrectBasedOnStyle) { 19945 SmallVector<FormatStyle, 8> Styles; 19946 Styles.resize(2); 19947 19948 Styles[0] = getGoogleStyle(); 19949 Styles[1] = getLLVMStyle(); 19950 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value()); 19951 EXPECT_ALL_STYLES_EQUAL(Styles); 19952 19953 Styles.resize(5); 19954 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript); 19955 Styles[1] = getLLVMStyle(); 19956 Styles[1].Language = FormatStyle::LK_JavaScript; 19957 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value()); 19958 19959 Styles[2] = getLLVMStyle(); 19960 Styles[2].Language = FormatStyle::LK_JavaScript; 19961 EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n" 19962 "BasedOnStyle: Google", 19963 &Styles[2]) 19964 .value()); 19965 19966 Styles[3] = getLLVMStyle(); 19967 Styles[3].Language = FormatStyle::LK_JavaScript; 19968 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n" 19969 "Language: JavaScript", 19970 &Styles[3]) 19971 .value()); 19972 19973 Styles[4] = getLLVMStyle(); 19974 Styles[4].Language = FormatStyle::LK_JavaScript; 19975 EXPECT_EQ(0, parseConfiguration("---\n" 19976 "BasedOnStyle: LLVM\n" 19977 "IndentWidth: 123\n" 19978 "---\n" 19979 "BasedOnStyle: Google\n" 19980 "Language: JavaScript", 19981 &Styles[4]) 19982 .value()); 19983 EXPECT_ALL_STYLES_EQUAL(Styles); 19984 } 19985 19986 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME) \ 19987 Style.FIELD = false; \ 19988 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value()); \ 19989 EXPECT_TRUE(Style.FIELD); \ 19990 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value()); \ 19991 EXPECT_FALSE(Style.FIELD); 19992 19993 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD) 19994 19995 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME) \ 19996 Style.STRUCT.FIELD = false; \ 19997 EXPECT_EQ(0, \ 19998 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": true", &Style) \ 19999 .value()); \ 20000 EXPECT_TRUE(Style.STRUCT.FIELD); \ 20001 EXPECT_EQ(0, \ 20002 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": false", &Style) \ 20003 .value()); \ 20004 EXPECT_FALSE(Style.STRUCT.FIELD); 20005 20006 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD) \ 20007 CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD) 20008 20009 #define CHECK_PARSE(TEXT, FIELD, VALUE) \ 20010 EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!"; \ 20011 EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value()); \ 20012 EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!" 20013 20014 TEST_F(FormatTest, ParsesConfigurationBools) { 20015 FormatStyle Style = {}; 20016 Style.Language = FormatStyle::LK_Cpp; 20017 CHECK_PARSE_BOOL(AlignTrailingComments); 20018 CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine); 20019 CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine); 20020 CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine); 20021 CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine); 20022 CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine); 20023 CHECK_PARSE_BOOL(BinPackArguments); 20024 CHECK_PARSE_BOOL(BinPackParameters); 20025 CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations); 20026 CHECK_PARSE_BOOL(BreakBeforeTernaryOperators); 20027 CHECK_PARSE_BOOL(BreakStringLiterals); 20028 CHECK_PARSE_BOOL(CompactNamespaces); 20029 CHECK_PARSE_BOOL(DeriveLineEnding); 20030 CHECK_PARSE_BOOL(DerivePointerAlignment); 20031 CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding"); 20032 CHECK_PARSE_BOOL(DisableFormat); 20033 CHECK_PARSE_BOOL(IndentAccessModifiers); 20034 CHECK_PARSE_BOOL(IndentCaseLabels); 20035 CHECK_PARSE_BOOL(IndentCaseBlocks); 20036 CHECK_PARSE_BOOL(IndentGotoLabels); 20037 CHECK_PARSE_BOOL_FIELD(IndentRequiresClause, "IndentRequires"); 20038 CHECK_PARSE_BOOL(IndentRequiresClause); 20039 CHECK_PARSE_BOOL(IndentWrappedFunctionNames); 20040 CHECK_PARSE_BOOL(InsertBraces); 20041 CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks); 20042 CHECK_PARSE_BOOL(ObjCSpaceAfterProperty); 20043 CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList); 20044 CHECK_PARSE_BOOL(Cpp11BracedListStyle); 20045 CHECK_PARSE_BOOL(ReflowComments); 20046 CHECK_PARSE_BOOL(RemoveBracesLLVM); 20047 CHECK_PARSE_BOOL(SortUsingDeclarations); 20048 CHECK_PARSE_BOOL(SpacesInParentheses); 20049 CHECK_PARSE_BOOL(SpacesInSquareBrackets); 20050 CHECK_PARSE_BOOL(SpacesInConditionalStatement); 20051 CHECK_PARSE_BOOL(SpaceInEmptyBlock); 20052 CHECK_PARSE_BOOL(SpaceInEmptyParentheses); 20053 CHECK_PARSE_BOOL(SpacesInContainerLiterals); 20054 CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses); 20055 CHECK_PARSE_BOOL(SpaceAfterCStyleCast); 20056 CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword); 20057 CHECK_PARSE_BOOL(SpaceAfterLogicalNot); 20058 CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators); 20059 CHECK_PARSE_BOOL(SpaceBeforeCaseColon); 20060 CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList); 20061 CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon); 20062 CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon); 20063 CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon); 20064 CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets); 20065 CHECK_PARSE_BOOL(UseCRLF); 20066 20067 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel); 20068 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass); 20069 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum); 20070 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction); 20071 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace); 20072 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration); 20073 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct); 20074 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion); 20075 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock); 20076 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch); 20077 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse); 20078 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody); 20079 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile); 20080 CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces); 20081 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction); 20082 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord); 20083 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace); 20084 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterControlStatements); 20085 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterForeachMacros); 20086 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, 20087 AfterFunctionDeclarationName); 20088 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, 20089 AfterFunctionDefinitionName); 20090 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterIfMacros); 20091 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterOverloadedOperator); 20092 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, BeforeNonEmptyParentheses); 20093 } 20094 20095 #undef CHECK_PARSE_BOOL 20096 20097 TEST_F(FormatTest, ParsesConfiguration) { 20098 FormatStyle Style = {}; 20099 Style.Language = FormatStyle::LK_Cpp; 20100 CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234); 20101 CHECK_PARSE("ConstructorInitializerIndentWidth: 1234", 20102 ConstructorInitializerIndentWidth, 1234u); 20103 CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u); 20104 CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u); 20105 CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u); 20106 CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u); 20107 CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234", 20108 PenaltyBreakBeforeFirstCallParameter, 1234u); 20109 CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234", 20110 PenaltyBreakTemplateDeclaration, 1234u); 20111 CHECK_PARSE("PenaltyBreakOpenParenthesis: 1234", PenaltyBreakOpenParenthesis, 20112 1234u); 20113 CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u); 20114 CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234", 20115 PenaltyReturnTypeOnItsOwnLine, 1234u); 20116 CHECK_PARSE("SpacesBeforeTrailingComments: 1234", 20117 SpacesBeforeTrailingComments, 1234u); 20118 CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u); 20119 CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u); 20120 CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$"); 20121 20122 Style.QualifierAlignment = FormatStyle::QAS_Right; 20123 CHECK_PARSE("QualifierAlignment: Leave", QualifierAlignment, 20124 FormatStyle::QAS_Leave); 20125 CHECK_PARSE("QualifierAlignment: Right", QualifierAlignment, 20126 FormatStyle::QAS_Right); 20127 CHECK_PARSE("QualifierAlignment: Left", QualifierAlignment, 20128 FormatStyle::QAS_Left); 20129 CHECK_PARSE("QualifierAlignment: Custom", QualifierAlignment, 20130 FormatStyle::QAS_Custom); 20131 20132 Style.QualifierOrder.clear(); 20133 CHECK_PARSE("QualifierOrder: [ const, volatile, type ]", QualifierOrder, 20134 std::vector<std::string>({"const", "volatile", "type"})); 20135 Style.QualifierOrder.clear(); 20136 CHECK_PARSE("QualifierOrder: [const, type]", QualifierOrder, 20137 std::vector<std::string>({"const", "type"})); 20138 Style.QualifierOrder.clear(); 20139 CHECK_PARSE("QualifierOrder: [volatile, type]", QualifierOrder, 20140 std::vector<std::string>({"volatile", "type"})); 20141 20142 #define CHECK_ALIGN_CONSECUTIVE(FIELD) \ 20143 do { \ 20144 Style.FIELD.Enabled = true; \ 20145 CHECK_PARSE(#FIELD ": None", FIELD, \ 20146 FormatStyle::AlignConsecutiveStyle( \ 20147 {/*Enabled=*/false, /*AcrossEmptyLines=*/false, \ 20148 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 20149 /*PadOperators=*/true})); \ 20150 CHECK_PARSE(#FIELD ": Consecutive", FIELD, \ 20151 FormatStyle::AlignConsecutiveStyle( \ 20152 {/*Enabled=*/true, /*AcrossEmptyLines=*/false, \ 20153 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 20154 /*PadOperators=*/true})); \ 20155 CHECK_PARSE(#FIELD ": AcrossEmptyLines", FIELD, \ 20156 FormatStyle::AlignConsecutiveStyle( \ 20157 {/*Enabled=*/true, /*AcrossEmptyLines=*/true, \ 20158 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 20159 /*PadOperators=*/true})); \ 20160 CHECK_PARSE(#FIELD ": AcrossEmptyLinesAndComments", FIELD, \ 20161 FormatStyle::AlignConsecutiveStyle( \ 20162 {/*Enabled=*/true, /*AcrossEmptyLines=*/true, \ 20163 /*AcrossComments=*/true, /*AlignCompound=*/false, \ 20164 /*PadOperators=*/true})); \ 20165 /* For backwards compability, false / true should still parse */ \ 20166 CHECK_PARSE(#FIELD ": false", FIELD, \ 20167 FormatStyle::AlignConsecutiveStyle( \ 20168 {/*Enabled=*/false, /*AcrossEmptyLines=*/false, \ 20169 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 20170 /*PadOperators=*/true})); \ 20171 CHECK_PARSE(#FIELD ": true", FIELD, \ 20172 FormatStyle::AlignConsecutiveStyle( \ 20173 {/*Enabled=*/true, /*AcrossEmptyLines=*/false, \ 20174 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 20175 /*PadOperators=*/true})); \ 20176 \ 20177 CHECK_PARSE_NESTED_BOOL(FIELD, Enabled); \ 20178 CHECK_PARSE_NESTED_BOOL(FIELD, AcrossEmptyLines); \ 20179 CHECK_PARSE_NESTED_BOOL(FIELD, AcrossComments); \ 20180 CHECK_PARSE_NESTED_BOOL(FIELD, AlignCompound); \ 20181 CHECK_PARSE_NESTED_BOOL(FIELD, PadOperators); \ 20182 } while (false) 20183 20184 CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveAssignments); 20185 CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveBitFields); 20186 CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveMacros); 20187 CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveDeclarations); 20188 20189 #undef CHECK_ALIGN_CONSECUTIVE 20190 20191 Style.PointerAlignment = FormatStyle::PAS_Middle; 20192 CHECK_PARSE("PointerAlignment: Left", PointerAlignment, 20193 FormatStyle::PAS_Left); 20194 CHECK_PARSE("PointerAlignment: Right", PointerAlignment, 20195 FormatStyle::PAS_Right); 20196 CHECK_PARSE("PointerAlignment: Middle", PointerAlignment, 20197 FormatStyle::PAS_Middle); 20198 Style.ReferenceAlignment = FormatStyle::RAS_Middle; 20199 CHECK_PARSE("ReferenceAlignment: Pointer", ReferenceAlignment, 20200 FormatStyle::RAS_Pointer); 20201 CHECK_PARSE("ReferenceAlignment: Left", ReferenceAlignment, 20202 FormatStyle::RAS_Left); 20203 CHECK_PARSE("ReferenceAlignment: Right", ReferenceAlignment, 20204 FormatStyle::RAS_Right); 20205 CHECK_PARSE("ReferenceAlignment: Middle", ReferenceAlignment, 20206 FormatStyle::RAS_Middle); 20207 // For backward compatibility: 20208 CHECK_PARSE("PointerBindsToType: Left", PointerAlignment, 20209 FormatStyle::PAS_Left); 20210 CHECK_PARSE("PointerBindsToType: Right", PointerAlignment, 20211 FormatStyle::PAS_Right); 20212 CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment, 20213 FormatStyle::PAS_Middle); 20214 20215 Style.Standard = FormatStyle::LS_Auto; 20216 CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03); 20217 CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11); 20218 CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14); 20219 CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17); 20220 CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20); 20221 CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto); 20222 CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest); 20223 // Legacy aliases: 20224 CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03); 20225 CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest); 20226 CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03); 20227 CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11); 20228 20229 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 20230 CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment", 20231 BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment); 20232 CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators, 20233 FormatStyle::BOS_None); 20234 CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators, 20235 FormatStyle::BOS_All); 20236 // For backward compatibility: 20237 CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators, 20238 FormatStyle::BOS_None); 20239 CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators, 20240 FormatStyle::BOS_All); 20241 20242 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 20243 CHECK_PARSE("BreakConstructorInitializers: BeforeComma", 20244 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma); 20245 CHECK_PARSE("BreakConstructorInitializers: AfterColon", 20246 BreakConstructorInitializers, FormatStyle::BCIS_AfterColon); 20247 CHECK_PARSE("BreakConstructorInitializers: BeforeColon", 20248 BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon); 20249 // For backward compatibility: 20250 CHECK_PARSE("BreakConstructorInitializersBeforeComma: true", 20251 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma); 20252 20253 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 20254 CHECK_PARSE("BreakInheritanceList: AfterComma", BreakInheritanceList, 20255 FormatStyle::BILS_AfterComma); 20256 CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList, 20257 FormatStyle::BILS_BeforeComma); 20258 CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList, 20259 FormatStyle::BILS_AfterColon); 20260 CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList, 20261 FormatStyle::BILS_BeforeColon); 20262 // For backward compatibility: 20263 CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList, 20264 FormatStyle::BILS_BeforeComma); 20265 20266 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 20267 CHECK_PARSE("PackConstructorInitializers: Never", PackConstructorInitializers, 20268 FormatStyle::PCIS_Never); 20269 CHECK_PARSE("PackConstructorInitializers: BinPack", 20270 PackConstructorInitializers, FormatStyle::PCIS_BinPack); 20271 CHECK_PARSE("PackConstructorInitializers: CurrentLine", 20272 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 20273 CHECK_PARSE("PackConstructorInitializers: NextLine", 20274 PackConstructorInitializers, FormatStyle::PCIS_NextLine); 20275 // For backward compatibility: 20276 CHECK_PARSE("BasedOnStyle: Google\n" 20277 "ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 20278 "AllowAllConstructorInitializersOnNextLine: false", 20279 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 20280 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 20281 CHECK_PARSE("BasedOnStyle: Google\n" 20282 "ConstructorInitializerAllOnOneLineOrOnePerLine: false", 20283 PackConstructorInitializers, FormatStyle::PCIS_BinPack); 20284 CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 20285 "AllowAllConstructorInitializersOnNextLine: true", 20286 PackConstructorInitializers, FormatStyle::PCIS_NextLine); 20287 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 20288 CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 20289 "AllowAllConstructorInitializersOnNextLine: false", 20290 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 20291 20292 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 20293 CHECK_PARSE("EmptyLineBeforeAccessModifier: Never", 20294 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never); 20295 CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave", 20296 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave); 20297 CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock", 20298 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock); 20299 CHECK_PARSE("EmptyLineBeforeAccessModifier: Always", 20300 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always); 20301 20302 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 20303 CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket, 20304 FormatStyle::BAS_Align); 20305 CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket, 20306 FormatStyle::BAS_DontAlign); 20307 CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket, 20308 FormatStyle::BAS_AlwaysBreak); 20309 CHECK_PARSE("AlignAfterOpenBracket: BlockIndent", AlignAfterOpenBracket, 20310 FormatStyle::BAS_BlockIndent); 20311 // For backward compatibility: 20312 CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket, 20313 FormatStyle::BAS_DontAlign); 20314 CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket, 20315 FormatStyle::BAS_Align); 20316 20317 Style.AlignEscapedNewlines = FormatStyle::ENAS_Left; 20318 CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines, 20319 FormatStyle::ENAS_DontAlign); 20320 CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines, 20321 FormatStyle::ENAS_Left); 20322 CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines, 20323 FormatStyle::ENAS_Right); 20324 // For backward compatibility: 20325 CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines, 20326 FormatStyle::ENAS_Left); 20327 CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines, 20328 FormatStyle::ENAS_Right); 20329 20330 Style.AlignOperands = FormatStyle::OAS_Align; 20331 CHECK_PARSE("AlignOperands: DontAlign", AlignOperands, 20332 FormatStyle::OAS_DontAlign); 20333 CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align); 20334 CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands, 20335 FormatStyle::OAS_AlignAfterOperator); 20336 // For backward compatibility: 20337 CHECK_PARSE("AlignOperands: false", AlignOperands, 20338 FormatStyle::OAS_DontAlign); 20339 CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align); 20340 20341 Style.UseTab = FormatStyle::UT_ForIndentation; 20342 CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never); 20343 CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation); 20344 CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always); 20345 CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab, 20346 FormatStyle::UT_ForContinuationAndIndentation); 20347 CHECK_PARSE("UseTab: AlignWithSpaces", UseTab, 20348 FormatStyle::UT_AlignWithSpaces); 20349 // For backward compatibility: 20350 CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never); 20351 CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always); 20352 20353 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 20354 CHECK_PARSE("AllowShortBlocksOnASingleLine: Never", 20355 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 20356 CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty", 20357 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty); 20358 CHECK_PARSE("AllowShortBlocksOnASingleLine: Always", 20359 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always); 20360 // For backward compatibility: 20361 CHECK_PARSE("AllowShortBlocksOnASingleLine: false", 20362 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 20363 CHECK_PARSE("AllowShortBlocksOnASingleLine: true", 20364 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always); 20365 20366 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 20367 CHECK_PARSE("AllowShortFunctionsOnASingleLine: None", 20368 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None); 20369 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline", 20370 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline); 20371 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty", 20372 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty); 20373 CHECK_PARSE("AllowShortFunctionsOnASingleLine: All", 20374 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All); 20375 // For backward compatibility: 20376 CHECK_PARSE("AllowShortFunctionsOnASingleLine: false", 20377 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None); 20378 CHECK_PARSE("AllowShortFunctionsOnASingleLine: true", 20379 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All); 20380 20381 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both; 20382 CHECK_PARSE("SpaceAroundPointerQualifiers: Default", 20383 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default); 20384 CHECK_PARSE("SpaceAroundPointerQualifiers: Before", 20385 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before); 20386 CHECK_PARSE("SpaceAroundPointerQualifiers: After", 20387 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After); 20388 CHECK_PARSE("SpaceAroundPointerQualifiers: Both", 20389 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both); 20390 20391 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 20392 CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens, 20393 FormatStyle::SBPO_Never); 20394 CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens, 20395 FormatStyle::SBPO_Always); 20396 CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens, 20397 FormatStyle::SBPO_ControlStatements); 20398 CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptControlMacros", 20399 SpaceBeforeParens, 20400 FormatStyle::SBPO_ControlStatementsExceptControlMacros); 20401 CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens, 20402 FormatStyle::SBPO_NonEmptyParentheses); 20403 CHECK_PARSE("SpaceBeforeParens: Custom", SpaceBeforeParens, 20404 FormatStyle::SBPO_Custom); 20405 // For backward compatibility: 20406 CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens, 20407 FormatStyle::SBPO_Never); 20408 CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens, 20409 FormatStyle::SBPO_ControlStatements); 20410 CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptForEachMacros", 20411 SpaceBeforeParens, 20412 FormatStyle::SBPO_ControlStatementsExceptControlMacros); 20413 20414 Style.ColumnLimit = 123; 20415 FormatStyle BaseStyle = getLLVMStyle(); 20416 CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit); 20417 CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u); 20418 20419 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 20420 CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces, 20421 FormatStyle::BS_Attach); 20422 CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces, 20423 FormatStyle::BS_Linux); 20424 CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces, 20425 FormatStyle::BS_Mozilla); 20426 CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces, 20427 FormatStyle::BS_Stroustrup); 20428 CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces, 20429 FormatStyle::BS_Allman); 20430 CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces, 20431 FormatStyle::BS_Whitesmiths); 20432 CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU); 20433 CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces, 20434 FormatStyle::BS_WebKit); 20435 CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces, 20436 FormatStyle::BS_Custom); 20437 20438 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never; 20439 CHECK_PARSE("BraceWrapping:\n" 20440 " AfterControlStatement: MultiLine", 20441 BraceWrapping.AfterControlStatement, 20442 FormatStyle::BWACS_MultiLine); 20443 CHECK_PARSE("BraceWrapping:\n" 20444 " AfterControlStatement: Always", 20445 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always); 20446 CHECK_PARSE("BraceWrapping:\n" 20447 " AfterControlStatement: Never", 20448 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never); 20449 // For backward compatibility: 20450 CHECK_PARSE("BraceWrapping:\n" 20451 " AfterControlStatement: true", 20452 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always); 20453 CHECK_PARSE("BraceWrapping:\n" 20454 " AfterControlStatement: false", 20455 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never); 20456 20457 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 20458 CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType, 20459 FormatStyle::RTBS_None); 20460 CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType, 20461 FormatStyle::RTBS_All); 20462 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel", 20463 AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel); 20464 CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions", 20465 AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions); 20466 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions", 20467 AlwaysBreakAfterReturnType, 20468 FormatStyle::RTBS_TopLevelDefinitions); 20469 20470 Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 20471 CHECK_PARSE("AlwaysBreakTemplateDeclarations: No", 20472 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No); 20473 CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine", 20474 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine); 20475 CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes", 20476 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes); 20477 CHECK_PARSE("AlwaysBreakTemplateDeclarations: false", 20478 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine); 20479 CHECK_PARSE("AlwaysBreakTemplateDeclarations: true", 20480 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes); 20481 20482 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All; 20483 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None", 20484 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None); 20485 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All", 20486 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All); 20487 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel", 20488 AlwaysBreakAfterDefinitionReturnType, 20489 FormatStyle::DRTBS_TopLevel); 20490 20491 Style.NamespaceIndentation = FormatStyle::NI_All; 20492 CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation, 20493 FormatStyle::NI_None); 20494 CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation, 20495 FormatStyle::NI_Inner); 20496 CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation, 20497 FormatStyle::NI_All); 20498 20499 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_OnlyFirstIf; 20500 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never", 20501 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never); 20502 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse", 20503 AllowShortIfStatementsOnASingleLine, 20504 FormatStyle::SIS_WithoutElse); 20505 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: OnlyFirstIf", 20506 AllowShortIfStatementsOnASingleLine, 20507 FormatStyle::SIS_OnlyFirstIf); 20508 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: AllIfsAndElse", 20509 AllowShortIfStatementsOnASingleLine, 20510 FormatStyle::SIS_AllIfsAndElse); 20511 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always", 20512 AllowShortIfStatementsOnASingleLine, 20513 FormatStyle::SIS_OnlyFirstIf); 20514 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false", 20515 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never); 20516 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true", 20517 AllowShortIfStatementsOnASingleLine, 20518 FormatStyle::SIS_WithoutElse); 20519 20520 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 20521 CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock, 20522 FormatStyle::IEBS_AfterExternBlock); 20523 CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock, 20524 FormatStyle::IEBS_Indent); 20525 CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock, 20526 FormatStyle::IEBS_NoIndent); 20527 CHECK_PARSE("IndentExternBlock: true", IndentExternBlock, 20528 FormatStyle::IEBS_Indent); 20529 CHECK_PARSE("IndentExternBlock: false", IndentExternBlock, 20530 FormatStyle::IEBS_NoIndent); 20531 20532 Style.BitFieldColonSpacing = FormatStyle::BFCS_None; 20533 CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing, 20534 FormatStyle::BFCS_Both); 20535 CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing, 20536 FormatStyle::BFCS_None); 20537 CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing, 20538 FormatStyle::BFCS_Before); 20539 CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing, 20540 FormatStyle::BFCS_After); 20541 20542 Style.SortJavaStaticImport = FormatStyle::SJSIO_Before; 20543 CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport, 20544 FormatStyle::SJSIO_After); 20545 CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport, 20546 FormatStyle::SJSIO_Before); 20547 20548 // FIXME: This is required because parsing a configuration simply overwrites 20549 // the first N elements of the list instead of resetting it. 20550 Style.ForEachMacros.clear(); 20551 std::vector<std::string> BoostForeach; 20552 BoostForeach.push_back("BOOST_FOREACH"); 20553 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach); 20554 std::vector<std::string> BoostAndQForeach; 20555 BoostAndQForeach.push_back("BOOST_FOREACH"); 20556 BoostAndQForeach.push_back("Q_FOREACH"); 20557 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros, 20558 BoostAndQForeach); 20559 20560 Style.IfMacros.clear(); 20561 std::vector<std::string> CustomIfs; 20562 CustomIfs.push_back("MYIF"); 20563 CHECK_PARSE("IfMacros: [MYIF]", IfMacros, CustomIfs); 20564 20565 Style.AttributeMacros.clear(); 20566 CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros, 20567 std::vector<std::string>{"__capability"}); 20568 CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros, 20569 std::vector<std::string>({"attr1", "attr2"})); 20570 20571 Style.StatementAttributeLikeMacros.clear(); 20572 CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]", 20573 StatementAttributeLikeMacros, 20574 std::vector<std::string>({"emit", "Q_EMIT"})); 20575 20576 Style.StatementMacros.clear(); 20577 CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros, 20578 std::vector<std::string>{"QUNUSED"}); 20579 CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros, 20580 std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"})); 20581 20582 Style.NamespaceMacros.clear(); 20583 CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros, 20584 std::vector<std::string>{"TESTSUITE"}); 20585 CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros, 20586 std::vector<std::string>({"TESTSUITE", "SUITE"})); 20587 20588 Style.WhitespaceSensitiveMacros.clear(); 20589 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]", 20590 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"}); 20591 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]", 20592 WhitespaceSensitiveMacros, 20593 std::vector<std::string>({"STRINGIZE", "ASSERT"})); 20594 Style.WhitespaceSensitiveMacros.clear(); 20595 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']", 20596 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"}); 20597 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']", 20598 WhitespaceSensitiveMacros, 20599 std::vector<std::string>({"STRINGIZE", "ASSERT"})); 20600 20601 Style.IncludeStyle.IncludeCategories.clear(); 20602 std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = { 20603 {"abc/.*", 2, 0, false}, {".*", 1, 0, true}}; 20604 CHECK_PARSE("IncludeCategories:\n" 20605 " - Regex: abc/.*\n" 20606 " Priority: 2\n" 20607 " - Regex: .*\n" 20608 " Priority: 1\n" 20609 " CaseSensitive: true\n", 20610 IncludeStyle.IncludeCategories, ExpectedCategories); 20611 CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex, 20612 "abc$"); 20613 CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'", 20614 IncludeStyle.IncludeIsMainSourceRegex, "abc$"); 20615 20616 Style.SortIncludes = FormatStyle::SI_Never; 20617 CHECK_PARSE("SortIncludes: true", SortIncludes, 20618 FormatStyle::SI_CaseSensitive); 20619 CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never); 20620 CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes, 20621 FormatStyle::SI_CaseInsensitive); 20622 CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes, 20623 FormatStyle::SI_CaseSensitive); 20624 CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never); 20625 20626 Style.RawStringFormats.clear(); 20627 std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = { 20628 { 20629 FormatStyle::LK_TextProto, 20630 {"pb", "proto"}, 20631 {"PARSE_TEXT_PROTO"}, 20632 /*CanonicalDelimiter=*/"", 20633 "llvm", 20634 }, 20635 { 20636 FormatStyle::LK_Cpp, 20637 {"cc", "cpp"}, 20638 {"C_CODEBLOCK", "CPPEVAL"}, 20639 /*CanonicalDelimiter=*/"cc", 20640 /*BasedOnStyle=*/"", 20641 }, 20642 }; 20643 20644 CHECK_PARSE("RawStringFormats:\n" 20645 " - Language: TextProto\n" 20646 " Delimiters:\n" 20647 " - 'pb'\n" 20648 " - 'proto'\n" 20649 " EnclosingFunctions:\n" 20650 " - 'PARSE_TEXT_PROTO'\n" 20651 " BasedOnStyle: llvm\n" 20652 " - Language: Cpp\n" 20653 " Delimiters:\n" 20654 " - 'cc'\n" 20655 " - 'cpp'\n" 20656 " EnclosingFunctions:\n" 20657 " - 'C_CODEBLOCK'\n" 20658 " - 'CPPEVAL'\n" 20659 " CanonicalDelimiter: 'cc'", 20660 RawStringFormats, ExpectedRawStringFormats); 20661 20662 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20663 " Minimum: 0\n" 20664 " Maximum: 0", 20665 SpacesInLineCommentPrefix.Minimum, 0u); 20666 EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u); 20667 Style.SpacesInLineCommentPrefix.Minimum = 1; 20668 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20669 " Minimum: 2", 20670 SpacesInLineCommentPrefix.Minimum, 0u); 20671 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20672 " Maximum: -1", 20673 SpacesInLineCommentPrefix.Maximum, -1u); 20674 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20675 " Minimum: 2", 20676 SpacesInLineCommentPrefix.Minimum, 2u); 20677 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20678 " Maximum: 1", 20679 SpacesInLineCommentPrefix.Maximum, 1u); 20680 EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u); 20681 20682 Style.SpacesInAngles = FormatStyle::SIAS_Always; 20683 CHECK_PARSE("SpacesInAngles: Never", SpacesInAngles, FormatStyle::SIAS_Never); 20684 CHECK_PARSE("SpacesInAngles: Always", SpacesInAngles, 20685 FormatStyle::SIAS_Always); 20686 CHECK_PARSE("SpacesInAngles: Leave", SpacesInAngles, FormatStyle::SIAS_Leave); 20687 // For backward compatibility: 20688 CHECK_PARSE("SpacesInAngles: false", SpacesInAngles, FormatStyle::SIAS_Never); 20689 CHECK_PARSE("SpacesInAngles: true", SpacesInAngles, FormatStyle::SIAS_Always); 20690 20691 CHECK_PARSE("RequiresClausePosition: WithPreceding", RequiresClausePosition, 20692 FormatStyle::RCPS_WithPreceding); 20693 CHECK_PARSE("RequiresClausePosition: WithFollowing", RequiresClausePosition, 20694 FormatStyle::RCPS_WithFollowing); 20695 CHECK_PARSE("RequiresClausePosition: SingleLine", RequiresClausePosition, 20696 FormatStyle::RCPS_SingleLine); 20697 CHECK_PARSE("RequiresClausePosition: OwnLine", RequiresClausePosition, 20698 FormatStyle::RCPS_OwnLine); 20699 20700 CHECK_PARSE("BreakBeforeConceptDeclarations: Never", 20701 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Never); 20702 CHECK_PARSE("BreakBeforeConceptDeclarations: Always", 20703 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always); 20704 CHECK_PARSE("BreakBeforeConceptDeclarations: Allowed", 20705 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed); 20706 // For backward compatibility: 20707 CHECK_PARSE("BreakBeforeConceptDeclarations: true", 20708 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always); 20709 CHECK_PARSE("BreakBeforeConceptDeclarations: false", 20710 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed); 20711 } 20712 20713 TEST_F(FormatTest, ParsesConfigurationWithLanguages) { 20714 FormatStyle Style = {}; 20715 Style.Language = FormatStyle::LK_Cpp; 20716 CHECK_PARSE("Language: Cpp\n" 20717 "IndentWidth: 12", 20718 IndentWidth, 12u); 20719 EXPECT_EQ(parseConfiguration("Language: JavaScript\n" 20720 "IndentWidth: 34", 20721 &Style), 20722 ParseError::Unsuitable); 20723 FormatStyle BinPackedTCS = {}; 20724 BinPackedTCS.Language = FormatStyle::LK_JavaScript; 20725 EXPECT_EQ(parseConfiguration("BinPackArguments: true\n" 20726 "InsertTrailingCommas: Wrapped", 20727 &BinPackedTCS), 20728 ParseError::BinPackTrailingCommaConflict); 20729 EXPECT_EQ(12u, Style.IndentWidth); 20730 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u); 20731 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language); 20732 20733 Style.Language = FormatStyle::LK_JavaScript; 20734 CHECK_PARSE("Language: JavaScript\n" 20735 "IndentWidth: 12", 20736 IndentWidth, 12u); 20737 CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u); 20738 EXPECT_EQ(parseConfiguration("Language: Cpp\n" 20739 "IndentWidth: 34", 20740 &Style), 20741 ParseError::Unsuitable); 20742 EXPECT_EQ(23u, Style.IndentWidth); 20743 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u); 20744 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language); 20745 20746 CHECK_PARSE("BasedOnStyle: LLVM\n" 20747 "IndentWidth: 67", 20748 IndentWidth, 67u); 20749 20750 CHECK_PARSE("---\n" 20751 "Language: JavaScript\n" 20752 "IndentWidth: 12\n" 20753 "---\n" 20754 "Language: Cpp\n" 20755 "IndentWidth: 34\n" 20756 "...\n", 20757 IndentWidth, 12u); 20758 20759 Style.Language = FormatStyle::LK_Cpp; 20760 CHECK_PARSE("---\n" 20761 "Language: JavaScript\n" 20762 "IndentWidth: 12\n" 20763 "---\n" 20764 "Language: Cpp\n" 20765 "IndentWidth: 34\n" 20766 "...\n", 20767 IndentWidth, 34u); 20768 CHECK_PARSE("---\n" 20769 "IndentWidth: 78\n" 20770 "---\n" 20771 "Language: JavaScript\n" 20772 "IndentWidth: 56\n" 20773 "...\n", 20774 IndentWidth, 78u); 20775 20776 Style.ColumnLimit = 123; 20777 Style.IndentWidth = 234; 20778 Style.BreakBeforeBraces = FormatStyle::BS_Linux; 20779 Style.TabWidth = 345; 20780 EXPECT_FALSE(parseConfiguration("---\n" 20781 "IndentWidth: 456\n" 20782 "BreakBeforeBraces: Allman\n" 20783 "---\n" 20784 "Language: JavaScript\n" 20785 "IndentWidth: 111\n" 20786 "TabWidth: 111\n" 20787 "---\n" 20788 "Language: Cpp\n" 20789 "BreakBeforeBraces: Stroustrup\n" 20790 "TabWidth: 789\n" 20791 "...\n", 20792 &Style)); 20793 EXPECT_EQ(123u, Style.ColumnLimit); 20794 EXPECT_EQ(456u, Style.IndentWidth); 20795 EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces); 20796 EXPECT_EQ(789u, Style.TabWidth); 20797 20798 EXPECT_EQ(parseConfiguration("---\n" 20799 "Language: JavaScript\n" 20800 "IndentWidth: 56\n" 20801 "---\n" 20802 "IndentWidth: 78\n" 20803 "...\n", 20804 &Style), 20805 ParseError::Error); 20806 EXPECT_EQ(parseConfiguration("---\n" 20807 "Language: JavaScript\n" 20808 "IndentWidth: 56\n" 20809 "---\n" 20810 "Language: JavaScript\n" 20811 "IndentWidth: 78\n" 20812 "...\n", 20813 &Style), 20814 ParseError::Error); 20815 20816 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language); 20817 } 20818 20819 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) { 20820 FormatStyle Style = {}; 20821 Style.Language = FormatStyle::LK_JavaScript; 20822 Style.BreakBeforeTernaryOperators = true; 20823 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value()); 20824 EXPECT_FALSE(Style.BreakBeforeTernaryOperators); 20825 20826 Style.BreakBeforeTernaryOperators = true; 20827 EXPECT_EQ(0, parseConfiguration("---\n" 20828 "BasedOnStyle: Google\n" 20829 "---\n" 20830 "Language: JavaScript\n" 20831 "IndentWidth: 76\n" 20832 "...\n", 20833 &Style) 20834 .value()); 20835 EXPECT_FALSE(Style.BreakBeforeTernaryOperators); 20836 EXPECT_EQ(76u, Style.IndentWidth); 20837 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language); 20838 } 20839 20840 TEST_F(FormatTest, ConfigurationRoundTripTest) { 20841 FormatStyle Style = getLLVMStyle(); 20842 std::string YAML = configurationAsText(Style); 20843 FormatStyle ParsedStyle = {}; 20844 ParsedStyle.Language = FormatStyle::LK_Cpp; 20845 EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value()); 20846 EXPECT_EQ(Style, ParsedStyle); 20847 } 20848 20849 TEST_F(FormatTest, WorksFor8bitEncodings) { 20850 EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n" 20851 "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n" 20852 "\"\xe7\xe8\xec\xed\xfe\xfe \"\n" 20853 "\"\xef\xee\xf0\xf3...\"", 20854 format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 " 20855 "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe " 20856 "\xef\xee\xf0\xf3...\"", 20857 getLLVMStyleWithColumns(12))); 20858 } 20859 20860 TEST_F(FormatTest, HandlesUTF8BOM) { 20861 EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf")); 20862 EXPECT_EQ("\xef\xbb\xbf#include <iostream>", 20863 format("\xef\xbb\xbf#include <iostream>")); 20864 EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>", 20865 format("\xef\xbb\xbf\n#include <iostream>")); 20866 } 20867 20868 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers. 20869 #if !defined(_MSC_VER) 20870 20871 TEST_F(FormatTest, CountsUTF8CharactersProperly) { 20872 verifyFormat("\"Однажды в студёную зимнюю пору...\"", 20873 getLLVMStyleWithColumns(35)); 20874 verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"", 20875 getLLVMStyleWithColumns(31)); 20876 verifyFormat("// Однажды в студёную зимнюю пору...", 20877 getLLVMStyleWithColumns(36)); 20878 verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32)); 20879 verifyFormat("/* Однажды в студёную зимнюю пору... */", 20880 getLLVMStyleWithColumns(39)); 20881 verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */", 20882 getLLVMStyleWithColumns(35)); 20883 } 20884 20885 TEST_F(FormatTest, SplitsUTF8Strings) { 20886 // Non-printable characters' width is currently considered to be the length in 20887 // bytes in UTF8. The characters can be displayed in very different manner 20888 // (zero-width, single width with a substitution glyph, expanded to their code 20889 // (e.g. "<8d>"), so there's no single correct way to handle them. 20890 EXPECT_EQ("\"aaaaÄ\"\n" 20891 "\"\xc2\x8d\";", 20892 format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10))); 20893 EXPECT_EQ("\"aaaaaaaÄ\"\n" 20894 "\"\xc2\x8d\";", 20895 format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10))); 20896 EXPECT_EQ("\"Однажды, в \"\n" 20897 "\"студёную \"\n" 20898 "\"зимнюю \"\n" 20899 "\"пору,\"", 20900 format("\"Однажды, в студёную зимнюю пору,\"", 20901 getLLVMStyleWithColumns(13))); 20902 EXPECT_EQ( 20903 "\"一 二 三 \"\n" 20904 "\"四 五六 \"\n" 20905 "\"七 八 九 \"\n" 20906 "\"十\"", 20907 format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11))); 20908 EXPECT_EQ("\"一\t\"\n" 20909 "\"二 \t\"\n" 20910 "\"三 四 \"\n" 20911 "\"五\t\"\n" 20912 "\"六 \t\"\n" 20913 "\"七 \"\n" 20914 "\"八九十\tqq\"", 20915 format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"", 20916 getLLVMStyleWithColumns(11))); 20917 20918 // UTF8 character in an escape sequence. 20919 EXPECT_EQ("\"aaaaaa\"\n" 20920 "\"\\\xC2\x8D\"", 20921 format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10))); 20922 } 20923 20924 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) { 20925 EXPECT_EQ("const char *sssss =\n" 20926 " \"一二三四五六七八\\\n" 20927 " 九 十\";", 20928 format("const char *sssss = \"一二三四五六七八\\\n" 20929 " 九 十\";", 20930 getLLVMStyleWithColumns(30))); 20931 } 20932 20933 TEST_F(FormatTest, SplitsUTF8LineComments) { 20934 EXPECT_EQ("// aaaaÄ\xc2\x8d", 20935 format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10))); 20936 EXPECT_EQ("// Я из лесу\n" 20937 "// вышел; был\n" 20938 "// сильный\n" 20939 "// мороз.", 20940 format("// Я из лесу вышел; был сильный мороз.", 20941 getLLVMStyleWithColumns(13))); 20942 EXPECT_EQ("// 一二三\n" 20943 "// 四五六七\n" 20944 "// 八 九\n" 20945 "// 十", 20946 format("// 一二三 四五六七 八 九 十", getLLVMStyleWithColumns(9))); 20947 } 20948 20949 TEST_F(FormatTest, SplitsUTF8BlockComments) { 20950 EXPECT_EQ("/* Гляжу,\n" 20951 " * поднимается\n" 20952 " * медленно в\n" 20953 " * гору\n" 20954 " * Лошадка,\n" 20955 " * везущая\n" 20956 " * хворосту\n" 20957 " * воз. */", 20958 format("/* Гляжу, поднимается медленно в гору\n" 20959 " * Лошадка, везущая хворосту воз. */", 20960 getLLVMStyleWithColumns(13))); 20961 EXPECT_EQ( 20962 "/* 一二三\n" 20963 " * 四五六七\n" 20964 " * 八 九\n" 20965 " * 十 */", 20966 format("/* 一二三 四五六七 八 九 十 */", getLLVMStyleWithColumns(9))); 20967 EXPECT_EQ("/* \n" 20968 " * \n" 20969 " * - */", 20970 format("/* - */", getLLVMStyleWithColumns(12))); 20971 } 20972 20973 #endif // _MSC_VER 20974 20975 TEST_F(FormatTest, ConstructorInitializerIndentWidth) { 20976 FormatStyle Style = getLLVMStyle(); 20977 20978 Style.ConstructorInitializerIndentWidth = 4; 20979 verifyFormat( 20980 "SomeClass::Constructor()\n" 20981 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20982 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20983 Style); 20984 20985 Style.ConstructorInitializerIndentWidth = 2; 20986 verifyFormat( 20987 "SomeClass::Constructor()\n" 20988 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20989 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20990 Style); 20991 20992 Style.ConstructorInitializerIndentWidth = 0; 20993 verifyFormat( 20994 "SomeClass::Constructor()\n" 20995 ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20996 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20997 Style); 20998 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 20999 verifyFormat( 21000 "SomeLongTemplateVariableName<\n" 21001 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>", 21002 Style); 21003 verifyFormat("bool smaller = 1 < " 21004 "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 21005 " " 21006 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 21007 Style); 21008 21009 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 21010 verifyFormat("SomeClass::Constructor() :\n" 21011 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n" 21012 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}", 21013 Style); 21014 } 21015 21016 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) { 21017 FormatStyle Style = getLLVMStyle(); 21018 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 21019 Style.ConstructorInitializerIndentWidth = 4; 21020 verifyFormat("SomeClass::Constructor()\n" 21021 " : a(a)\n" 21022 " , b(b)\n" 21023 " , c(c) {}", 21024 Style); 21025 verifyFormat("SomeClass::Constructor()\n" 21026 " : a(a) {}", 21027 Style); 21028 21029 Style.ColumnLimit = 0; 21030 verifyFormat("SomeClass::Constructor()\n" 21031 " : a(a) {}", 21032 Style); 21033 verifyFormat("SomeClass::Constructor() noexcept\n" 21034 " : a(a) {}", 21035 Style); 21036 verifyFormat("SomeClass::Constructor()\n" 21037 " : a(a)\n" 21038 " , b(b)\n" 21039 " , c(c) {}", 21040 Style); 21041 verifyFormat("SomeClass::Constructor()\n" 21042 " : a(a) {\n" 21043 " foo();\n" 21044 " bar();\n" 21045 "}", 21046 Style); 21047 21048 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 21049 verifyFormat("SomeClass::Constructor()\n" 21050 " : a(a)\n" 21051 " , b(b)\n" 21052 " , c(c) {\n}", 21053 Style); 21054 verifyFormat("SomeClass::Constructor()\n" 21055 " : a(a) {\n}", 21056 Style); 21057 21058 Style.ColumnLimit = 80; 21059 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 21060 Style.ConstructorInitializerIndentWidth = 2; 21061 verifyFormat("SomeClass::Constructor()\n" 21062 " : a(a)\n" 21063 " , b(b)\n" 21064 " , c(c) {}", 21065 Style); 21066 21067 Style.ConstructorInitializerIndentWidth = 0; 21068 verifyFormat("SomeClass::Constructor()\n" 21069 ": a(a)\n" 21070 ", b(b)\n" 21071 ", c(c) {}", 21072 Style); 21073 21074 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 21075 Style.ConstructorInitializerIndentWidth = 4; 21076 verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style); 21077 verifyFormat( 21078 "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n", 21079 Style); 21080 verifyFormat( 21081 "SomeClass::Constructor()\n" 21082 " : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}", 21083 Style); 21084 Style.ConstructorInitializerIndentWidth = 4; 21085 Style.ColumnLimit = 60; 21086 verifyFormat("SomeClass::Constructor()\n" 21087 " : aaaaaaaa(aaaaaaaa)\n" 21088 " , aaaaaaaa(aaaaaaaa)\n" 21089 " , aaaaaaaa(aaaaaaaa) {}", 21090 Style); 21091 } 21092 21093 TEST_F(FormatTest, ConstructorInitializersWithPreprocessorDirective) { 21094 FormatStyle Style = getLLVMStyle(); 21095 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 21096 Style.ConstructorInitializerIndentWidth = 4; 21097 verifyFormat("SomeClass::Constructor()\n" 21098 " : a{a}\n" 21099 " , b{b} {}", 21100 Style); 21101 verifyFormat("SomeClass::Constructor()\n" 21102 " : a{a}\n" 21103 "#if CONDITION\n" 21104 " , b{b}\n" 21105 "#endif\n" 21106 "{\n}", 21107 Style); 21108 Style.ConstructorInitializerIndentWidth = 2; 21109 verifyFormat("SomeClass::Constructor()\n" 21110 "#if CONDITION\n" 21111 " : a{a}\n" 21112 "#endif\n" 21113 " , b{b}\n" 21114 " , c{c} {\n}", 21115 Style); 21116 Style.ConstructorInitializerIndentWidth = 0; 21117 verifyFormat("SomeClass::Constructor()\n" 21118 ": a{a}\n" 21119 "#ifdef CONDITION\n" 21120 ", b{b}\n" 21121 "#else\n" 21122 ", c{c}\n" 21123 "#endif\n" 21124 ", d{d} {\n}", 21125 Style); 21126 Style.ConstructorInitializerIndentWidth = 4; 21127 verifyFormat("SomeClass::Constructor()\n" 21128 " : a{a}\n" 21129 "#if WINDOWS\n" 21130 "#if DEBUG\n" 21131 " , b{0}\n" 21132 "#else\n" 21133 " , b{1}\n" 21134 "#endif\n" 21135 "#else\n" 21136 "#if DEBUG\n" 21137 " , b{2}\n" 21138 "#else\n" 21139 " , b{3}\n" 21140 "#endif\n" 21141 "#endif\n" 21142 "{\n}", 21143 Style); 21144 verifyFormat("SomeClass::Constructor()\n" 21145 " : a{a}\n" 21146 "#if WINDOWS\n" 21147 " , b{0}\n" 21148 "#if DEBUG\n" 21149 " , c{0}\n" 21150 "#else\n" 21151 " , c{1}\n" 21152 "#endif\n" 21153 "#else\n" 21154 "#if DEBUG\n" 21155 " , c{2}\n" 21156 "#else\n" 21157 " , c{3}\n" 21158 "#endif\n" 21159 " , b{1}\n" 21160 "#endif\n" 21161 "{\n}", 21162 Style); 21163 } 21164 21165 TEST_F(FormatTest, Destructors) { 21166 verifyFormat("void F(int &i) { i.~int(); }"); 21167 verifyFormat("void F(int &i) { i->~int(); }"); 21168 } 21169 21170 TEST_F(FormatTest, FormatsWithWebKitStyle) { 21171 FormatStyle Style = getWebKitStyle(); 21172 21173 // Don't indent in outer namespaces. 21174 verifyFormat("namespace outer {\n" 21175 "int i;\n" 21176 "namespace inner {\n" 21177 " int i;\n" 21178 "} // namespace inner\n" 21179 "} // namespace outer\n" 21180 "namespace other_outer {\n" 21181 "int i;\n" 21182 "}", 21183 Style); 21184 21185 // Don't indent case labels. 21186 verifyFormat("switch (variable) {\n" 21187 "case 1:\n" 21188 "case 2:\n" 21189 " doSomething();\n" 21190 " break;\n" 21191 "default:\n" 21192 " ++variable;\n" 21193 "}", 21194 Style); 21195 21196 // Wrap before binary operators. 21197 EXPECT_EQ("void f()\n" 21198 "{\n" 21199 " if (aaaaaaaaaaaaaaaa\n" 21200 " && bbbbbbbbbbbbbbbbbbbbbbbb\n" 21201 " && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n" 21202 " return;\n" 21203 "}", 21204 format("void f() {\n" 21205 "if (aaaaaaaaaaaaaaaa\n" 21206 "&& bbbbbbbbbbbbbbbbbbbbbbbb\n" 21207 "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n" 21208 "return;\n" 21209 "}", 21210 Style)); 21211 21212 // Allow functions on a single line. 21213 verifyFormat("void f() { return; }", Style); 21214 21215 // Allow empty blocks on a single line and insert a space in empty blocks. 21216 EXPECT_EQ("void f() { }", format("void f() {}", Style)); 21217 EXPECT_EQ("while (true) { }", format("while (true) {}", Style)); 21218 // However, don't merge non-empty short loops. 21219 EXPECT_EQ("while (true) {\n" 21220 " continue;\n" 21221 "}", 21222 format("while (true) { continue; }", Style)); 21223 21224 // Constructor initializers are formatted one per line with the "," on the 21225 // new line. 21226 verifyFormat("Constructor()\n" 21227 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 21228 " , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n" 21229 " aaaaaaaaaaaaaa)\n" 21230 " , aaaaaaaaaaaaaaaaaaaaaaa()\n" 21231 "{\n" 21232 "}", 21233 Style); 21234 verifyFormat("SomeClass::Constructor()\n" 21235 " : a(a)\n" 21236 "{\n" 21237 "}", 21238 Style); 21239 EXPECT_EQ("SomeClass::Constructor()\n" 21240 " : a(a)\n" 21241 "{\n" 21242 "}", 21243 format("SomeClass::Constructor():a(a){}", Style)); 21244 verifyFormat("SomeClass::Constructor()\n" 21245 " : a(a)\n" 21246 " , b(b)\n" 21247 " , c(c)\n" 21248 "{\n" 21249 "}", 21250 Style); 21251 verifyFormat("SomeClass::Constructor()\n" 21252 " : a(a)\n" 21253 "{\n" 21254 " foo();\n" 21255 " bar();\n" 21256 "}", 21257 Style); 21258 21259 // Access specifiers should be aligned left. 21260 verifyFormat("class C {\n" 21261 "public:\n" 21262 " int i;\n" 21263 "};", 21264 Style); 21265 21266 // Do not align comments. 21267 verifyFormat("int a; // Do not\n" 21268 "double b; // align comments.", 21269 Style); 21270 21271 // Do not align operands. 21272 EXPECT_EQ("ASSERT(aaaa\n" 21273 " || bbbb);", 21274 format("ASSERT ( aaaa\n||bbbb);", Style)); 21275 21276 // Accept input's line breaks. 21277 EXPECT_EQ("if (aaaaaaaaaaaaaaa\n" 21278 " || bbbbbbbbbbbbbbb) {\n" 21279 " i++;\n" 21280 "}", 21281 format("if (aaaaaaaaaaaaaaa\n" 21282 "|| bbbbbbbbbbbbbbb) { i++; }", 21283 Style)); 21284 EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n" 21285 " i++;\n" 21286 "}", 21287 format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style)); 21288 21289 // Don't automatically break all macro definitions (llvm.org/PR17842). 21290 verifyFormat("#define aNumber 10", Style); 21291 // However, generally keep the line breaks that the user authored. 21292 EXPECT_EQ("#define aNumber \\\n" 21293 " 10", 21294 format("#define aNumber \\\n" 21295 " 10", 21296 Style)); 21297 21298 // Keep empty and one-element array literals on a single line. 21299 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n" 21300 " copyItems:YES];", 21301 format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n" 21302 "copyItems:YES];", 21303 Style)); 21304 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n" 21305 " copyItems:YES];", 21306 format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n" 21307 " copyItems:YES];", 21308 Style)); 21309 // FIXME: This does not seem right, there should be more indentation before 21310 // the array literal's entries. Nested blocks have the same problem. 21311 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n" 21312 " @\"a\",\n" 21313 " @\"a\"\n" 21314 "]\n" 21315 " copyItems:YES];", 21316 format("NSArray* a = [[NSArray alloc] initWithArray:@[\n" 21317 " @\"a\",\n" 21318 " @\"a\"\n" 21319 " ]\n" 21320 " copyItems:YES];", 21321 Style)); 21322 EXPECT_EQ( 21323 "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n" 21324 " copyItems:YES];", 21325 format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n" 21326 " copyItems:YES];", 21327 Style)); 21328 21329 verifyFormat("[self.a b:c c:d];", Style); 21330 EXPECT_EQ("[self.a b:c\n" 21331 " c:d];", 21332 format("[self.a b:c\n" 21333 "c:d];", 21334 Style)); 21335 } 21336 21337 TEST_F(FormatTest, FormatsLambdas) { 21338 verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n"); 21339 verifyFormat( 21340 "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n"); 21341 verifyFormat("int c = [&] { [=] { return b++; }(); }();\n"); 21342 verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n"); 21343 verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n"); 21344 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n"); 21345 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n"); 21346 verifyFormat("auto c = [a = [b = 42] {}] {};\n"); 21347 verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n"); 21348 verifyFormat("int x = f(*+[] {});"); 21349 verifyFormat("void f() {\n" 21350 " other(x.begin(), x.end(), [&](int, int) { return 1; });\n" 21351 "}\n"); 21352 verifyFormat("void f() {\n" 21353 " other(x.begin(), //\n" 21354 " x.end(), //\n" 21355 " [&](int, int) { return 1; });\n" 21356 "}\n"); 21357 verifyFormat("void f() {\n" 21358 " other.other.other.other.other(\n" 21359 " x.begin(), x.end(),\n" 21360 " [something, rather](int, int, int, int, int, int, int) { " 21361 "return 1; });\n" 21362 "}\n"); 21363 verifyFormat( 21364 "void f() {\n" 21365 " other.other.other.other.other(\n" 21366 " x.begin(), x.end(),\n" 21367 " [something, rather](int, int, int, int, int, int, int) {\n" 21368 " //\n" 21369 " });\n" 21370 "}\n"); 21371 verifyFormat("SomeFunction([]() { // A cool function...\n" 21372 " return 43;\n" 21373 "});"); 21374 EXPECT_EQ("SomeFunction([]() {\n" 21375 "#define A a\n" 21376 " return 43;\n" 21377 "});", 21378 format("SomeFunction([](){\n" 21379 "#define A a\n" 21380 "return 43;\n" 21381 "});")); 21382 verifyFormat("void f() {\n" 21383 " SomeFunction([](decltype(x), A *a) {});\n" 21384 " SomeFunction([](typeof(x), A *a) {});\n" 21385 " SomeFunction([](_Atomic(x), A *a) {});\n" 21386 " SomeFunction([](__underlying_type(x), A *a) {});\n" 21387 "}"); 21388 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 21389 " [](const aaaaaaaaaa &a) { return a; });"); 21390 verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n" 21391 " SomeOtherFunctioooooooooooooooooooooooooon();\n" 21392 "});"); 21393 verifyFormat("Constructor()\n" 21394 " : Field([] { // comment\n" 21395 " int i;\n" 21396 " }) {}"); 21397 verifyFormat("auto my_lambda = [](const string &some_parameter) {\n" 21398 " return some_parameter.size();\n" 21399 "};"); 21400 verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n" 21401 " [](const string &s) { return s; };"); 21402 verifyFormat("int i = aaaaaa ? 1 //\n" 21403 " : [] {\n" 21404 " return 2; //\n" 21405 " }();"); 21406 verifyFormat("llvm::errs() << \"number of twos is \"\n" 21407 " << std::count_if(v.begin(), v.end(), [](int x) {\n" 21408 " return x == 2; // force break\n" 21409 " });"); 21410 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 21411 " [=](int iiiiiiiiiiii) {\n" 21412 " return aaaaaaaaaaaaaaaaaaaaaaa !=\n" 21413 " aaaaaaaaaaaaaaaaaaaaaaa;\n" 21414 " });", 21415 getLLVMStyleWithColumns(60)); 21416 21417 verifyFormat("SomeFunction({[&] {\n" 21418 " // comment\n" 21419 " },\n" 21420 " [&] {\n" 21421 " // comment\n" 21422 " }});"); 21423 verifyFormat("SomeFunction({[&] {\n" 21424 " // comment\n" 21425 "}});"); 21426 verifyFormat( 21427 "virtual aaaaaaaaaaaaaaaa(\n" 21428 " std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n" 21429 " aaaaa aaaaaaaaa);"); 21430 21431 // Lambdas with return types. 21432 verifyFormat("int c = []() -> int { return 2; }();\n"); 21433 verifyFormat("int c = []() -> int * { return 2; }();\n"); 21434 verifyFormat("int c = []() -> vector<int> { return {2}; }();\n"); 21435 verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());"); 21436 verifyFormat("foo([]() noexcept -> int {});"); 21437 verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};"); 21438 verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};"); 21439 verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};"); 21440 verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};"); 21441 verifyFormat("[a, a]() -> a<1> {};"); 21442 verifyFormat("[]() -> foo<5 + 2> { return {}; };"); 21443 verifyFormat("[]() -> foo<5 - 2> { return {}; };"); 21444 verifyFormat("[]() -> foo<5 / 2> { return {}; };"); 21445 verifyFormat("[]() -> foo<5 * 2> { return {}; };"); 21446 verifyFormat("[]() -> foo<5 % 2> { return {}; };"); 21447 verifyFormat("[]() -> foo<5 << 2> { return {}; };"); 21448 verifyFormat("[]() -> foo<!5> { return {}; };"); 21449 verifyFormat("[]() -> foo<~5> { return {}; };"); 21450 verifyFormat("[]() -> foo<5 | 2> { return {}; };"); 21451 verifyFormat("[]() -> foo<5 || 2> { return {}; };"); 21452 verifyFormat("[]() -> foo<5 & 2> { return {}; };"); 21453 verifyFormat("[]() -> foo<5 && 2> { return {}; };"); 21454 verifyFormat("[]() -> foo<5 == 2> { return {}; };"); 21455 verifyFormat("[]() -> foo<5 != 2> { return {}; };"); 21456 verifyFormat("[]() -> foo<5 >= 2> { return {}; };"); 21457 verifyFormat("[]() -> foo<5 <= 2> { return {}; };"); 21458 verifyFormat("[]() -> foo<5 < 2> { return {}; };"); 21459 verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };"); 21460 verifyFormat("namespace bar {\n" 21461 "// broken:\n" 21462 "auto foo{[]() -> foo<5 + 2> { return {}; }};\n" 21463 "} // namespace bar"); 21464 verifyFormat("namespace bar {\n" 21465 "// broken:\n" 21466 "auto foo{[]() -> foo<5 - 2> { return {}; }};\n" 21467 "} // namespace bar"); 21468 verifyFormat("namespace bar {\n" 21469 "// broken:\n" 21470 "auto foo{[]() -> foo<5 / 2> { return {}; }};\n" 21471 "} // namespace bar"); 21472 verifyFormat("namespace bar {\n" 21473 "// broken:\n" 21474 "auto foo{[]() -> foo<5 * 2> { return {}; }};\n" 21475 "} // namespace bar"); 21476 verifyFormat("namespace bar {\n" 21477 "// broken:\n" 21478 "auto foo{[]() -> foo<5 % 2> { return {}; }};\n" 21479 "} // namespace bar"); 21480 verifyFormat("namespace bar {\n" 21481 "// broken:\n" 21482 "auto foo{[]() -> foo<5 << 2> { return {}; }};\n" 21483 "} // namespace bar"); 21484 verifyFormat("namespace bar {\n" 21485 "// broken:\n" 21486 "auto foo{[]() -> foo<!5> { return {}; }};\n" 21487 "} // namespace bar"); 21488 verifyFormat("namespace bar {\n" 21489 "// broken:\n" 21490 "auto foo{[]() -> foo<~5> { return {}; }};\n" 21491 "} // namespace bar"); 21492 verifyFormat("namespace bar {\n" 21493 "// broken:\n" 21494 "auto foo{[]() -> foo<5 | 2> { return {}; }};\n" 21495 "} // namespace bar"); 21496 verifyFormat("namespace bar {\n" 21497 "// broken:\n" 21498 "auto foo{[]() -> foo<5 || 2> { return {}; }};\n" 21499 "} // namespace bar"); 21500 verifyFormat("namespace bar {\n" 21501 "// broken:\n" 21502 "auto foo{[]() -> foo<5 & 2> { return {}; }};\n" 21503 "} // namespace bar"); 21504 verifyFormat("namespace bar {\n" 21505 "// broken:\n" 21506 "auto foo{[]() -> foo<5 && 2> { return {}; }};\n" 21507 "} // namespace bar"); 21508 verifyFormat("namespace bar {\n" 21509 "// broken:\n" 21510 "auto foo{[]() -> foo<5 == 2> { return {}; }};\n" 21511 "} // namespace bar"); 21512 verifyFormat("namespace bar {\n" 21513 "// broken:\n" 21514 "auto foo{[]() -> foo<5 != 2> { return {}; }};\n" 21515 "} // namespace bar"); 21516 verifyFormat("namespace bar {\n" 21517 "// broken:\n" 21518 "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n" 21519 "} // namespace bar"); 21520 verifyFormat("namespace bar {\n" 21521 "// broken:\n" 21522 "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n" 21523 "} // namespace bar"); 21524 verifyFormat("namespace bar {\n" 21525 "// broken:\n" 21526 "auto foo{[]() -> foo<5 < 2> { return {}; }};\n" 21527 "} // namespace bar"); 21528 verifyFormat("namespace bar {\n" 21529 "// broken:\n" 21530 "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n" 21531 "} // namespace bar"); 21532 verifyFormat("[]() -> a<1> {};"); 21533 verifyFormat("[]() -> a<1> { ; };"); 21534 verifyFormat("[]() -> a<1> { ; }();"); 21535 verifyFormat("[a, a]() -> a<true> {};"); 21536 verifyFormat("[]() -> a<true> {};"); 21537 verifyFormat("[]() -> a<true> { ; };"); 21538 verifyFormat("[]() -> a<true> { ; }();"); 21539 verifyFormat("[a, a]() -> a<false> {};"); 21540 verifyFormat("[]() -> a<false> {};"); 21541 verifyFormat("[]() -> a<false> { ; };"); 21542 verifyFormat("[]() -> a<false> { ; }();"); 21543 verifyFormat("auto foo{[]() -> foo<false> { ; }};"); 21544 verifyFormat("namespace bar {\n" 21545 "auto foo{[]() -> foo<false> { ; }};\n" 21546 "} // namespace bar"); 21547 verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n" 21548 " int j) -> int {\n" 21549 " return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n" 21550 "};"); 21551 verifyFormat( 21552 "aaaaaaaaaaaaaaaaaaaaaa(\n" 21553 " [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n" 21554 " return aaaaaaaaaaaaaaaaa;\n" 21555 " });", 21556 getLLVMStyleWithColumns(70)); 21557 verifyFormat("[]() //\n" 21558 " -> int {\n" 21559 " return 1; //\n" 21560 "};"); 21561 verifyFormat("[]() -> Void<T...> {};"); 21562 verifyFormat("[a, b]() -> Tuple<T...> { return {}; };"); 21563 verifyFormat("SomeFunction({[]() -> int[] { return {}; }});"); 21564 verifyFormat("SomeFunction({[]() -> int *[] { return {}; }});"); 21565 verifyFormat("SomeFunction({[]() -> int (*)[] { return {}; }});"); 21566 verifyFormat("SomeFunction({[]() -> ns::type<int (*)[]> { return {}; }});"); 21567 verifyFormat("return int{[x = x]() { return x; }()};"); 21568 21569 // Lambdas with explicit template argument lists. 21570 verifyFormat( 21571 "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n"); 21572 verifyFormat("auto L = []<class T>(T) {\n" 21573 " {\n" 21574 " f();\n" 21575 " g();\n" 21576 " }\n" 21577 "};\n"); 21578 verifyFormat("auto L = []<class... T>(T...) {\n" 21579 " {\n" 21580 " f();\n" 21581 " g();\n" 21582 " }\n" 21583 "};\n"); 21584 verifyFormat("auto L = []<typename... T>(T...) {\n" 21585 " {\n" 21586 " f();\n" 21587 " g();\n" 21588 " }\n" 21589 "};\n"); 21590 verifyFormat("auto L = []<template <typename...> class T>(T...) {\n" 21591 " {\n" 21592 " f();\n" 21593 " g();\n" 21594 " }\n" 21595 "};\n"); 21596 verifyFormat("auto L = []</*comment*/ class... T>(T...) {\n" 21597 " {\n" 21598 " f();\n" 21599 " g();\n" 21600 " }\n" 21601 "};\n"); 21602 21603 // Multiple lambdas in the same parentheses change indentation rules. These 21604 // lambdas are forced to start on new lines. 21605 verifyFormat("SomeFunction(\n" 21606 " []() {\n" 21607 " //\n" 21608 " },\n" 21609 " []() {\n" 21610 " //\n" 21611 " });"); 21612 21613 // A lambda passed as arg0 is always pushed to the next line. 21614 verifyFormat("SomeFunction(\n" 21615 " [this] {\n" 21616 " //\n" 21617 " },\n" 21618 " 1);\n"); 21619 21620 // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like 21621 // the arg0 case above. 21622 auto Style = getGoogleStyle(); 21623 Style.BinPackArguments = false; 21624 verifyFormat("SomeFunction(\n" 21625 " a,\n" 21626 " [this] {\n" 21627 " //\n" 21628 " },\n" 21629 " b);\n", 21630 Style); 21631 verifyFormat("SomeFunction(\n" 21632 " a,\n" 21633 " [this] {\n" 21634 " //\n" 21635 " },\n" 21636 " b);\n"); 21637 21638 // A lambda with a very long line forces arg0 to be pushed out irrespective of 21639 // the BinPackArguments value (as long as the code is wide enough). 21640 verifyFormat( 21641 "something->SomeFunction(\n" 21642 " a,\n" 21643 " [this] {\n" 21644 " " 21645 "D0000000000000000000000000000000000000000000000000000000000001();\n" 21646 " },\n" 21647 " b);\n"); 21648 21649 // A multi-line lambda is pulled up as long as the introducer fits on the 21650 // previous line and there are no further args. 21651 verifyFormat("function(1, [this, that] {\n" 21652 " //\n" 21653 "});\n"); 21654 verifyFormat("function([this, that] {\n" 21655 " //\n" 21656 "});\n"); 21657 // FIXME: this format is not ideal and we should consider forcing the first 21658 // arg onto its own line. 21659 verifyFormat("function(a, b, c, //\n" 21660 " d, [this, that] {\n" 21661 " //\n" 21662 " });\n"); 21663 21664 // Multiple lambdas are treated correctly even when there is a short arg0. 21665 verifyFormat("SomeFunction(\n" 21666 " 1,\n" 21667 " [this] {\n" 21668 " //\n" 21669 " },\n" 21670 " [this] {\n" 21671 " //\n" 21672 " },\n" 21673 " 1);\n"); 21674 21675 // More complex introducers. 21676 verifyFormat("return [i, args...] {};"); 21677 21678 // Not lambdas. 21679 verifyFormat("constexpr char hello[]{\"hello\"};"); 21680 verifyFormat("double &operator[](int i) { return 0; }\n" 21681 "int i;"); 21682 verifyFormat("std::unique_ptr<int[]> foo() {}"); 21683 verifyFormat("int i = a[a][a]->f();"); 21684 verifyFormat("int i = (*b)[a]->f();"); 21685 21686 // Other corner cases. 21687 verifyFormat("void f() {\n" 21688 " bar([]() {} // Did not respect SpacesBeforeTrailingComments\n" 21689 " );\n" 21690 "}"); 21691 verifyFormat("auto k = *[](int *j) { return j; }(&i);"); 21692 21693 // Lambdas created through weird macros. 21694 verifyFormat("void f() {\n" 21695 " MACRO((const AA &a) { return 1; });\n" 21696 " MACRO((AA &a) { return 1; });\n" 21697 "}"); 21698 21699 verifyFormat("if (blah_blah(whatever, whatever, [] {\n" 21700 " doo_dah();\n" 21701 " doo_dah();\n" 21702 " })) {\n" 21703 "}"); 21704 verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n" 21705 " doo_dah();\n" 21706 " doo_dah();\n" 21707 " })) {\n" 21708 "}"); 21709 verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n" 21710 " doo_dah();\n" 21711 " doo_dah();\n" 21712 " })) {\n" 21713 "}"); 21714 verifyFormat("auto lambda = []() {\n" 21715 " int a = 2\n" 21716 "#if A\n" 21717 " + 2\n" 21718 "#endif\n" 21719 " ;\n" 21720 "};"); 21721 21722 // Lambdas with complex multiline introducers. 21723 verifyFormat( 21724 "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 21725 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n" 21726 " -> ::std::unordered_set<\n" 21727 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n" 21728 " //\n" 21729 " });"); 21730 21731 FormatStyle DoNotMerge = getLLVMStyle(); 21732 DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 21733 verifyFormat("auto c = []() {\n" 21734 " return b;\n" 21735 "};", 21736 "auto c = []() { return b; };", DoNotMerge); 21737 verifyFormat("auto c = []() {\n" 21738 "};", 21739 " auto c = []() {};", DoNotMerge); 21740 21741 FormatStyle MergeEmptyOnly = getLLVMStyle(); 21742 MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty; 21743 verifyFormat("auto c = []() {\n" 21744 " return b;\n" 21745 "};", 21746 "auto c = []() {\n" 21747 " return b;\n" 21748 " };", 21749 MergeEmptyOnly); 21750 verifyFormat("auto c = []() {};", 21751 "auto c = []() {\n" 21752 "};", 21753 MergeEmptyOnly); 21754 21755 FormatStyle MergeInline = getLLVMStyle(); 21756 MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline; 21757 verifyFormat("auto c = []() {\n" 21758 " return b;\n" 21759 "};", 21760 "auto c = []() { return b; };", MergeInline); 21761 verifyFormat("function([]() { return b; })", "function([]() { return b; })", 21762 MergeInline); 21763 verifyFormat("function([]() { return b; }, a)", 21764 "function([]() { return b; }, a)", MergeInline); 21765 verifyFormat("function(a, []() { return b; })", 21766 "function(a, []() { return b; })", MergeInline); 21767 21768 // Check option "BraceWrapping.BeforeLambdaBody" and different state of 21769 // AllowShortLambdasOnASingleLine 21770 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle(); 21771 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 21772 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 21773 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21774 FormatStyle::ShortLambdaStyle::SLS_None; 21775 verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n" 21776 " []()\n" 21777 " {\n" 21778 " return 17;\n" 21779 " });", 21780 LLVMWithBeforeLambdaBody); 21781 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n" 21782 " []()\n" 21783 " {\n" 21784 " });", 21785 LLVMWithBeforeLambdaBody); 21786 verifyFormat("auto fct_SLS_None = []()\n" 21787 "{\n" 21788 " return 17;\n" 21789 "};", 21790 LLVMWithBeforeLambdaBody); 21791 verifyFormat("TwoNestedLambdas_SLS_None(\n" 21792 " []()\n" 21793 " {\n" 21794 " return Call(\n" 21795 " []()\n" 21796 " {\n" 21797 " return 17;\n" 21798 " });\n" 21799 " });", 21800 LLVMWithBeforeLambdaBody); 21801 verifyFormat("void Fct() {\n" 21802 " return {[]()\n" 21803 " {\n" 21804 " return 17;\n" 21805 " }};\n" 21806 "}", 21807 LLVMWithBeforeLambdaBody); 21808 21809 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21810 FormatStyle::ShortLambdaStyle::SLS_Empty; 21811 verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n" 21812 " []()\n" 21813 " {\n" 21814 " return 17;\n" 21815 " });", 21816 LLVMWithBeforeLambdaBody); 21817 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});", 21818 LLVMWithBeforeLambdaBody); 21819 verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL" 21820 "ongFunctionName_SLS_Empty(\n" 21821 " []() {});", 21822 LLVMWithBeforeLambdaBody); 21823 verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n" 21824 " []()\n" 21825 " {\n" 21826 " return 17;\n" 21827 " });", 21828 LLVMWithBeforeLambdaBody); 21829 verifyFormat("auto fct_SLS_Empty = []()\n" 21830 "{\n" 21831 " return 17;\n" 21832 "};", 21833 LLVMWithBeforeLambdaBody); 21834 verifyFormat("TwoNestedLambdas_SLS_Empty(\n" 21835 " []()\n" 21836 " {\n" 21837 " return Call([]() {});\n" 21838 " });", 21839 LLVMWithBeforeLambdaBody); 21840 verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n" 21841 " []()\n" 21842 " {\n" 21843 " return Call([]() {});\n" 21844 " });", 21845 LLVMWithBeforeLambdaBody); 21846 verifyFormat( 21847 "FctWithLongLineInLambda_SLS_Empty(\n" 21848 " []()\n" 21849 " {\n" 21850 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21851 " AndShouldNotBeConsiderAsInline,\n" 21852 " LambdaBodyMustBeBreak);\n" 21853 " });", 21854 LLVMWithBeforeLambdaBody); 21855 21856 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21857 FormatStyle::ShortLambdaStyle::SLS_Inline; 21858 verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });", 21859 LLVMWithBeforeLambdaBody); 21860 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});", 21861 LLVMWithBeforeLambdaBody); 21862 verifyFormat("auto fct_SLS_Inline = []()\n" 21863 "{\n" 21864 " return 17;\n" 21865 "};", 21866 LLVMWithBeforeLambdaBody); 21867 verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return " 21868 "17; }); });", 21869 LLVMWithBeforeLambdaBody); 21870 verifyFormat( 21871 "FctWithLongLineInLambda_SLS_Inline(\n" 21872 " []()\n" 21873 " {\n" 21874 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21875 " AndShouldNotBeConsiderAsInline,\n" 21876 " LambdaBodyMustBeBreak);\n" 21877 " });", 21878 LLVMWithBeforeLambdaBody); 21879 verifyFormat("FctWithMultipleParams_SLS_Inline(" 21880 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n" 21881 " []() { return 17; });", 21882 LLVMWithBeforeLambdaBody); 21883 verifyFormat( 21884 "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });", 21885 LLVMWithBeforeLambdaBody); 21886 21887 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21888 FormatStyle::ShortLambdaStyle::SLS_All; 21889 verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });", 21890 LLVMWithBeforeLambdaBody); 21891 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});", 21892 LLVMWithBeforeLambdaBody); 21893 verifyFormat("auto fct_SLS_All = []() { return 17; };", 21894 LLVMWithBeforeLambdaBody); 21895 verifyFormat("FctWithOneParam_SLS_All(\n" 21896 " []()\n" 21897 " {\n" 21898 " // A cool function...\n" 21899 " return 43;\n" 21900 " });", 21901 LLVMWithBeforeLambdaBody); 21902 verifyFormat("FctWithMultipleParams_SLS_All(" 21903 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n" 21904 " []() { return 17; });", 21905 LLVMWithBeforeLambdaBody); 21906 verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });", 21907 LLVMWithBeforeLambdaBody); 21908 verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });", 21909 LLVMWithBeforeLambdaBody); 21910 verifyFormat( 21911 "FctWithLongLineInLambda_SLS_All(\n" 21912 " []()\n" 21913 " {\n" 21914 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21915 " AndShouldNotBeConsiderAsInline,\n" 21916 " LambdaBodyMustBeBreak);\n" 21917 " });", 21918 LLVMWithBeforeLambdaBody); 21919 verifyFormat( 21920 "auto fct_SLS_All = []()\n" 21921 "{\n" 21922 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21923 " AndShouldNotBeConsiderAsInline,\n" 21924 " LambdaBodyMustBeBreak);\n" 21925 "};", 21926 LLVMWithBeforeLambdaBody); 21927 LLVMWithBeforeLambdaBody.BinPackParameters = false; 21928 verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);", 21929 LLVMWithBeforeLambdaBody); 21930 verifyFormat( 21931 "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n" 21932 " FirstParam,\n" 21933 " SecondParam,\n" 21934 " ThirdParam,\n" 21935 " FourthParam);", 21936 LLVMWithBeforeLambdaBody); 21937 verifyFormat("FctWithLongLineInLambda_SLS_All(\n" 21938 " []() { return " 21939 "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n" 21940 " FirstParam,\n" 21941 " SecondParam,\n" 21942 " ThirdParam,\n" 21943 " FourthParam);", 21944 LLVMWithBeforeLambdaBody); 21945 verifyFormat( 21946 "FctWithLongLineInLambda_SLS_All(FirstParam,\n" 21947 " SecondParam,\n" 21948 " ThirdParam,\n" 21949 " FourthParam,\n" 21950 " []() { return SomeValueNotSoLong; });", 21951 LLVMWithBeforeLambdaBody); 21952 verifyFormat("FctWithLongLineInLambda_SLS_All(\n" 21953 " []()\n" 21954 " {\n" 21955 " return " 21956 "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB" 21957 "eConsiderAsInline;\n" 21958 " });", 21959 LLVMWithBeforeLambdaBody); 21960 verifyFormat( 21961 "FctWithLongLineInLambda_SLS_All(\n" 21962 " []()\n" 21963 " {\n" 21964 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21965 " AndShouldNotBeConsiderAsInline,\n" 21966 " LambdaBodyMustBeBreak);\n" 21967 " });", 21968 LLVMWithBeforeLambdaBody); 21969 verifyFormat("FctWithTwoParams_SLS_All(\n" 21970 " []()\n" 21971 " {\n" 21972 " // A cool function...\n" 21973 " return 43;\n" 21974 " },\n" 21975 " 87);", 21976 LLVMWithBeforeLambdaBody); 21977 verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);", 21978 LLVMWithBeforeLambdaBody); 21979 verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });", 21980 LLVMWithBeforeLambdaBody); 21981 verifyFormat( 21982 "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });", 21983 LLVMWithBeforeLambdaBody); 21984 verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; " 21985 "}); }, x);", 21986 LLVMWithBeforeLambdaBody); 21987 verifyFormat("TwoNestedLambdas_SLS_All(\n" 21988 " []()\n" 21989 " {\n" 21990 " // A cool function...\n" 21991 " return Call([]() { return 17; });\n" 21992 " });", 21993 LLVMWithBeforeLambdaBody); 21994 verifyFormat("TwoNestedLambdas_SLS_All(\n" 21995 " []()\n" 21996 " {\n" 21997 " return Call(\n" 21998 " []()\n" 21999 " {\n" 22000 " // A cool function...\n" 22001 " return 17;\n" 22002 " });\n" 22003 " });", 22004 LLVMWithBeforeLambdaBody); 22005 22006 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 22007 FormatStyle::ShortLambdaStyle::SLS_None; 22008 22009 verifyFormat("auto select = [this]() -> const Library::Object *\n" 22010 "{\n" 22011 " return MyAssignment::SelectFromList(this);\n" 22012 "};\n", 22013 LLVMWithBeforeLambdaBody); 22014 22015 verifyFormat("auto select = [this]() -> const Library::Object &\n" 22016 "{\n" 22017 " return MyAssignment::SelectFromList(this);\n" 22018 "};\n", 22019 LLVMWithBeforeLambdaBody); 22020 22021 verifyFormat("auto select = [this]() -> std::unique_ptr<Object>\n" 22022 "{\n" 22023 " return MyAssignment::SelectFromList(this);\n" 22024 "};\n", 22025 LLVMWithBeforeLambdaBody); 22026 22027 verifyFormat("namespace test {\n" 22028 "class Test {\n" 22029 "public:\n" 22030 " Test() = default;\n" 22031 "};\n" 22032 "} // namespace test", 22033 LLVMWithBeforeLambdaBody); 22034 22035 // Lambdas with different indentation styles. 22036 Style = getLLVMStyleWithColumns(100); 22037 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 22038 " return promise.then(\n" 22039 " [this, &someVariable, someObject = " 22040 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 22041 " return someObject.startAsyncAction().then(\n" 22042 " [this, &someVariable](AsyncActionResult result) " 22043 "mutable { result.processMore(); });\n" 22044 " });\n" 22045 "}\n", 22046 format("SomeResult doSomething(SomeObject promise) {\n" 22047 " return promise.then([this, &someVariable, someObject = " 22048 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 22049 " return someObject.startAsyncAction().then([this, " 22050 "&someVariable](AsyncActionResult result) mutable {\n" 22051 " result.processMore();\n" 22052 " });\n" 22053 " });\n" 22054 "}\n", 22055 Style)); 22056 Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope; 22057 verifyFormat("test() {\n" 22058 " ([]() -> {\n" 22059 " int b = 32;\n" 22060 " return 3;\n" 22061 " }).foo();\n" 22062 "}", 22063 Style); 22064 verifyFormat("test() {\n" 22065 " []() -> {\n" 22066 " int b = 32;\n" 22067 " return 3;\n" 22068 " }\n" 22069 "}", 22070 Style); 22071 verifyFormat("std::sort(v.begin(), v.end(),\n" 22072 " [](const auto &someLongArgumentName, const auto " 22073 "&someOtherLongArgumentName) {\n" 22074 " return someLongArgumentName.someMemberVariable < " 22075 "someOtherLongArgumentName.someMemberVariable;\n" 22076 "});", 22077 Style); 22078 verifyFormat("test() {\n" 22079 " (\n" 22080 " []() -> {\n" 22081 " int b = 32;\n" 22082 " return 3;\n" 22083 " },\n" 22084 " foo, bar)\n" 22085 " .foo();\n" 22086 "}", 22087 Style); 22088 verifyFormat("test() {\n" 22089 " ([]() -> {\n" 22090 " int b = 32;\n" 22091 " return 3;\n" 22092 " })\n" 22093 " .foo()\n" 22094 " .bar();\n" 22095 "}", 22096 Style); 22097 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 22098 " return promise.then(\n" 22099 " [this, &someVariable, someObject = " 22100 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 22101 " return someObject.startAsyncAction().then(\n" 22102 " [this, &someVariable](AsyncActionResult result) mutable { " 22103 "result.processMore(); });\n" 22104 " });\n" 22105 "}\n", 22106 format("SomeResult doSomething(SomeObject promise) {\n" 22107 " return promise.then([this, &someVariable, someObject = " 22108 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 22109 " return someObject.startAsyncAction().then([this, " 22110 "&someVariable](AsyncActionResult result) mutable {\n" 22111 " result.processMore();\n" 22112 " });\n" 22113 " });\n" 22114 "}\n", 22115 Style)); 22116 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 22117 " return promise.then([this, &someVariable] {\n" 22118 " return someObject.startAsyncAction().then(\n" 22119 " [this, &someVariable](AsyncActionResult result) mutable { " 22120 "result.processMore(); });\n" 22121 " });\n" 22122 "}\n", 22123 format("SomeResult doSomething(SomeObject promise) {\n" 22124 " return promise.then([this, &someVariable] {\n" 22125 " return someObject.startAsyncAction().then([this, " 22126 "&someVariable](AsyncActionResult result) mutable {\n" 22127 " result.processMore();\n" 22128 " });\n" 22129 " });\n" 22130 "}\n", 22131 Style)); 22132 Style = getGoogleStyle(); 22133 Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope; 22134 EXPECT_EQ("#define A \\\n" 22135 " [] { \\\n" 22136 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 22137 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n" 22138 " }", 22139 format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 22140 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }", 22141 Style)); 22142 // TODO: The current formatting has a minor issue that's not worth fixing 22143 // right now whereby the closing brace is indented relative to the signature 22144 // instead of being aligned. This only happens with macros. 22145 } 22146 22147 TEST_F(FormatTest, LambdaWithLineComments) { 22148 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle(); 22149 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 22150 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 22151 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 22152 FormatStyle::ShortLambdaStyle::SLS_All; 22153 22154 verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody); 22155 verifyFormat("auto k = []() // comment\n" 22156 "{ return; }", 22157 LLVMWithBeforeLambdaBody); 22158 verifyFormat("auto k = []() /* comment */ { return; }", 22159 LLVMWithBeforeLambdaBody); 22160 verifyFormat("auto k = []() /* comment */ /* comment */ { return; }", 22161 LLVMWithBeforeLambdaBody); 22162 verifyFormat("auto k = []() // X\n" 22163 "{ return; }", 22164 LLVMWithBeforeLambdaBody); 22165 verifyFormat( 22166 "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" 22167 "{ return; }", 22168 LLVMWithBeforeLambdaBody); 22169 22170 LLVMWithBeforeLambdaBody.ColumnLimit = 0; 22171 22172 verifyFormat("foo([]()\n" 22173 " {\n" 22174 " bar(); //\n" 22175 " return 1; // comment\n" 22176 " }());", 22177 "foo([]() {\n" 22178 " bar(); //\n" 22179 " return 1; // comment\n" 22180 "}());", 22181 LLVMWithBeforeLambdaBody); 22182 verifyFormat("foo(\n" 22183 " 1, MACRO {\n" 22184 " baz();\n" 22185 " bar(); // comment\n" 22186 " },\n" 22187 " []() {});", 22188 "foo(\n" 22189 " 1, MACRO { baz(); bar(); // comment\n" 22190 " }, []() {}\n" 22191 ");", 22192 LLVMWithBeforeLambdaBody); 22193 } 22194 22195 TEST_F(FormatTest, EmptyLinesInLambdas) { 22196 verifyFormat("auto lambda = []() {\n" 22197 " x(); //\n" 22198 "};", 22199 "auto lambda = []() {\n" 22200 "\n" 22201 " x(); //\n" 22202 "\n" 22203 "};"); 22204 } 22205 22206 TEST_F(FormatTest, FormatsBlocks) { 22207 FormatStyle ShortBlocks = getLLVMStyle(); 22208 ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 22209 verifyFormat("int (^Block)(int, int);", ShortBlocks); 22210 verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks); 22211 verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks); 22212 verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks); 22213 verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks); 22214 verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks); 22215 22216 verifyFormat("foo(^{ bar(); });", ShortBlocks); 22217 verifyFormat("foo(a, ^{ bar(); });", ShortBlocks); 22218 verifyFormat("{ void (^block)(Object *x); }", ShortBlocks); 22219 22220 verifyFormat("[operation setCompletionBlock:^{\n" 22221 " [self onOperationDone];\n" 22222 "}];"); 22223 verifyFormat("int i = {[operation setCompletionBlock:^{\n" 22224 " [self onOperationDone];\n" 22225 "}]};"); 22226 verifyFormat("[operation setCompletionBlock:^(int *i) {\n" 22227 " f();\n" 22228 "}];"); 22229 verifyFormat("int a = [operation block:^int(int *i) {\n" 22230 " return 1;\n" 22231 "}];"); 22232 verifyFormat("[myObject doSomethingWith:arg1\n" 22233 " aaa:^int(int *a) {\n" 22234 " return 1;\n" 22235 " }\n" 22236 " bbb:f(a * bbbbbbbb)];"); 22237 22238 verifyFormat("[operation setCompletionBlock:^{\n" 22239 " [self.delegate newDataAvailable];\n" 22240 "}];", 22241 getLLVMStyleWithColumns(60)); 22242 verifyFormat("dispatch_async(_fileIOQueue, ^{\n" 22243 " NSString *path = [self sessionFilePath];\n" 22244 " if (path) {\n" 22245 " // ...\n" 22246 " }\n" 22247 "});"); 22248 verifyFormat("[[SessionService sharedService]\n" 22249 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 22250 " if (window) {\n" 22251 " [self windowDidLoad:window];\n" 22252 " } else {\n" 22253 " [self errorLoadingWindow];\n" 22254 " }\n" 22255 " }];"); 22256 verifyFormat("void (^largeBlock)(void) = ^{\n" 22257 " // ...\n" 22258 "};\n", 22259 getLLVMStyleWithColumns(40)); 22260 verifyFormat("[[SessionService sharedService]\n" 22261 " loadWindowWithCompletionBlock: //\n" 22262 " ^(SessionWindow *window) {\n" 22263 " if (window) {\n" 22264 " [self windowDidLoad:window];\n" 22265 " } else {\n" 22266 " [self errorLoadingWindow];\n" 22267 " }\n" 22268 " }];", 22269 getLLVMStyleWithColumns(60)); 22270 verifyFormat("[myObject doSomethingWith:arg1\n" 22271 " firstBlock:^(Foo *a) {\n" 22272 " // ...\n" 22273 " int i;\n" 22274 " }\n" 22275 " secondBlock:^(Bar *b) {\n" 22276 " // ...\n" 22277 " int i;\n" 22278 " }\n" 22279 " thirdBlock:^Foo(Bar *b) {\n" 22280 " // ...\n" 22281 " int i;\n" 22282 " }];"); 22283 verifyFormat("[myObject doSomethingWith:arg1\n" 22284 " firstBlock:-1\n" 22285 " secondBlock:^(Bar *b) {\n" 22286 " // ...\n" 22287 " int i;\n" 22288 " }];"); 22289 22290 verifyFormat("f(^{\n" 22291 " @autoreleasepool {\n" 22292 " if (a) {\n" 22293 " g();\n" 22294 " }\n" 22295 " }\n" 22296 "});"); 22297 verifyFormat("Block b = ^int *(A *a, B *b) {}"); 22298 verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n" 22299 "};"); 22300 22301 FormatStyle FourIndent = getLLVMStyle(); 22302 FourIndent.ObjCBlockIndentWidth = 4; 22303 verifyFormat("[operation setCompletionBlock:^{\n" 22304 " [self onOperationDone];\n" 22305 "}];", 22306 FourIndent); 22307 } 22308 22309 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) { 22310 FormatStyle ZeroColumn = getLLVMStyleWithColumns(0); 22311 22312 verifyFormat("[[SessionService sharedService] " 22313 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 22314 " if (window) {\n" 22315 " [self windowDidLoad:window];\n" 22316 " } else {\n" 22317 " [self errorLoadingWindow];\n" 22318 " }\n" 22319 "}];", 22320 ZeroColumn); 22321 EXPECT_EQ("[[SessionService sharedService]\n" 22322 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 22323 " if (window) {\n" 22324 " [self windowDidLoad:window];\n" 22325 " } else {\n" 22326 " [self errorLoadingWindow];\n" 22327 " }\n" 22328 " }];", 22329 format("[[SessionService sharedService]\n" 22330 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 22331 " if (window) {\n" 22332 " [self windowDidLoad:window];\n" 22333 " } else {\n" 22334 " [self errorLoadingWindow];\n" 22335 " }\n" 22336 "}];", 22337 ZeroColumn)); 22338 verifyFormat("[myObject doSomethingWith:arg1\n" 22339 " firstBlock:^(Foo *a) {\n" 22340 " // ...\n" 22341 " int i;\n" 22342 " }\n" 22343 " secondBlock:^(Bar *b) {\n" 22344 " // ...\n" 22345 " int i;\n" 22346 " }\n" 22347 " thirdBlock:^Foo(Bar *b) {\n" 22348 " // ...\n" 22349 " int i;\n" 22350 " }];", 22351 ZeroColumn); 22352 verifyFormat("f(^{\n" 22353 " @autoreleasepool {\n" 22354 " if (a) {\n" 22355 " g();\n" 22356 " }\n" 22357 " }\n" 22358 "});", 22359 ZeroColumn); 22360 verifyFormat("void (^largeBlock)(void) = ^{\n" 22361 " // ...\n" 22362 "};", 22363 ZeroColumn); 22364 22365 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 22366 EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };", 22367 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn)); 22368 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 22369 EXPECT_EQ("void (^largeBlock)(void) = ^{\n" 22370 " int i;\n" 22371 "};", 22372 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn)); 22373 } 22374 22375 TEST_F(FormatTest, SupportsCRLF) { 22376 EXPECT_EQ("int a;\r\n" 22377 "int b;\r\n" 22378 "int c;\r\n", 22379 format("int a;\r\n" 22380 " int b;\r\n" 22381 " int c;\r\n", 22382 getLLVMStyle())); 22383 EXPECT_EQ("int a;\r\n" 22384 "int b;\r\n" 22385 "int c;\r\n", 22386 format("int a;\r\n" 22387 " int b;\n" 22388 " int c;\r\n", 22389 getLLVMStyle())); 22390 EXPECT_EQ("int a;\n" 22391 "int b;\n" 22392 "int c;\n", 22393 format("int a;\r\n" 22394 " int b;\n" 22395 " int c;\n", 22396 getLLVMStyle())); 22397 EXPECT_EQ("\"aaaaaaa \"\r\n" 22398 "\"bbbbbbb\";\r\n", 22399 format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10))); 22400 EXPECT_EQ("#define A \\\r\n" 22401 " b; \\\r\n" 22402 " c; \\\r\n" 22403 " d;\r\n", 22404 format("#define A \\\r\n" 22405 " b; \\\r\n" 22406 " c; d; \r\n", 22407 getGoogleStyle())); 22408 22409 EXPECT_EQ("/*\r\n" 22410 "multi line block comments\r\n" 22411 "should not introduce\r\n" 22412 "an extra carriage return\r\n" 22413 "*/\r\n", 22414 format("/*\r\n" 22415 "multi line block comments\r\n" 22416 "should not introduce\r\n" 22417 "an extra carriage return\r\n" 22418 "*/\r\n")); 22419 EXPECT_EQ("/*\r\n" 22420 "\r\n" 22421 "*/", 22422 format("/*\r\n" 22423 " \r\r\r\n" 22424 "*/")); 22425 22426 FormatStyle style = getLLVMStyle(); 22427 22428 style.DeriveLineEnding = true; 22429 style.UseCRLF = false; 22430 EXPECT_EQ("union FooBarBazQux {\n" 22431 " int foo;\n" 22432 " int bar;\n" 22433 " int baz;\n" 22434 "};", 22435 format("union FooBarBazQux {\r\n" 22436 " int foo;\n" 22437 " int bar;\r\n" 22438 " int baz;\n" 22439 "};", 22440 style)); 22441 style.UseCRLF = true; 22442 EXPECT_EQ("union FooBarBazQux {\r\n" 22443 " int foo;\r\n" 22444 " int bar;\r\n" 22445 " int baz;\r\n" 22446 "};", 22447 format("union FooBarBazQux {\r\n" 22448 " int foo;\n" 22449 " int bar;\r\n" 22450 " int baz;\n" 22451 "};", 22452 style)); 22453 22454 style.DeriveLineEnding = false; 22455 style.UseCRLF = false; 22456 EXPECT_EQ("union FooBarBazQux {\n" 22457 " int foo;\n" 22458 " int bar;\n" 22459 " int baz;\n" 22460 " int qux;\n" 22461 "};", 22462 format("union FooBarBazQux {\r\n" 22463 " int foo;\n" 22464 " int bar;\r\n" 22465 " int baz;\n" 22466 " int qux;\r\n" 22467 "};", 22468 style)); 22469 style.UseCRLF = true; 22470 EXPECT_EQ("union FooBarBazQux {\r\n" 22471 " int foo;\r\n" 22472 " int bar;\r\n" 22473 " int baz;\r\n" 22474 " int qux;\r\n" 22475 "};", 22476 format("union FooBarBazQux {\r\n" 22477 " int foo;\n" 22478 " int bar;\r\n" 22479 " int baz;\n" 22480 " int qux;\n" 22481 "};", 22482 style)); 22483 22484 style.DeriveLineEnding = true; 22485 style.UseCRLF = false; 22486 EXPECT_EQ("union FooBarBazQux {\r\n" 22487 " int foo;\r\n" 22488 " int bar;\r\n" 22489 " int baz;\r\n" 22490 " int qux;\r\n" 22491 "};", 22492 format("union FooBarBazQux {\r\n" 22493 " int foo;\n" 22494 " int bar;\r\n" 22495 " int baz;\n" 22496 " int qux;\r\n" 22497 "};", 22498 style)); 22499 style.UseCRLF = true; 22500 EXPECT_EQ("union FooBarBazQux {\n" 22501 " int foo;\n" 22502 " int bar;\n" 22503 " int baz;\n" 22504 " int qux;\n" 22505 "};", 22506 format("union FooBarBazQux {\r\n" 22507 " int foo;\n" 22508 " int bar;\r\n" 22509 " int baz;\n" 22510 " int qux;\n" 22511 "};", 22512 style)); 22513 } 22514 22515 TEST_F(FormatTest, MunchSemicolonAfterBlocks) { 22516 verifyFormat("MY_CLASS(C) {\n" 22517 " int i;\n" 22518 " int j;\n" 22519 "};"); 22520 } 22521 22522 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) { 22523 FormatStyle TwoIndent = getLLVMStyleWithColumns(15); 22524 TwoIndent.ContinuationIndentWidth = 2; 22525 22526 EXPECT_EQ("int i =\n" 22527 " longFunction(\n" 22528 " arg);", 22529 format("int i = longFunction(arg);", TwoIndent)); 22530 22531 FormatStyle SixIndent = getLLVMStyleWithColumns(20); 22532 SixIndent.ContinuationIndentWidth = 6; 22533 22534 EXPECT_EQ("int i =\n" 22535 " longFunction(\n" 22536 " arg);", 22537 format("int i = longFunction(arg);", SixIndent)); 22538 } 22539 22540 TEST_F(FormatTest, WrappedClosingParenthesisIndent) { 22541 FormatStyle Style = getLLVMStyle(); 22542 verifyFormat("int Foo::getter(\n" 22543 " //\n" 22544 ") const {\n" 22545 " return foo;\n" 22546 "}", 22547 Style); 22548 verifyFormat("void Foo::setter(\n" 22549 " //\n" 22550 ") {\n" 22551 " foo = 1;\n" 22552 "}", 22553 Style); 22554 } 22555 22556 TEST_F(FormatTest, SpacesInAngles) { 22557 FormatStyle Spaces = getLLVMStyle(); 22558 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22559 22560 verifyFormat("vector< ::std::string > x1;", Spaces); 22561 verifyFormat("Foo< int, Bar > x2;", Spaces); 22562 verifyFormat("Foo< ::int, ::Bar > x3;", Spaces); 22563 22564 verifyFormat("static_cast< int >(arg);", Spaces); 22565 verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces); 22566 verifyFormat("f< int, float >();", Spaces); 22567 verifyFormat("template <> g() {}", Spaces); 22568 verifyFormat("template < std::vector< int > > f() {}", Spaces); 22569 verifyFormat("std::function< void(int, int) > fct;", Spaces); 22570 verifyFormat("void inFunction() { std::function< void(int, int) > fct; }", 22571 Spaces); 22572 22573 Spaces.Standard = FormatStyle::LS_Cpp03; 22574 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22575 verifyFormat("A< A< int > >();", Spaces); 22576 22577 Spaces.SpacesInAngles = FormatStyle::SIAS_Never; 22578 verifyFormat("A<A<int> >();", Spaces); 22579 22580 Spaces.SpacesInAngles = FormatStyle::SIAS_Leave; 22581 verifyFormat("vector< ::std::string> x4;", "vector<::std::string> x4;", 22582 Spaces); 22583 verifyFormat("vector< ::std::string > x4;", "vector<::std::string > x4;", 22584 Spaces); 22585 22586 verifyFormat("A<A<int> >();", Spaces); 22587 verifyFormat("A<A<int> >();", "A<A<int>>();", Spaces); 22588 verifyFormat("A< A< int > >();", Spaces); 22589 22590 Spaces.Standard = FormatStyle::LS_Cpp11; 22591 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22592 verifyFormat("A< A< int > >();", Spaces); 22593 22594 Spaces.SpacesInAngles = FormatStyle::SIAS_Never; 22595 verifyFormat("vector<::std::string> x4;", Spaces); 22596 verifyFormat("vector<int> x5;", Spaces); 22597 verifyFormat("Foo<int, Bar> x6;", Spaces); 22598 verifyFormat("Foo<::int, ::Bar> x7;", Spaces); 22599 22600 verifyFormat("A<A<int>>();", Spaces); 22601 22602 Spaces.SpacesInAngles = FormatStyle::SIAS_Leave; 22603 verifyFormat("vector<::std::string> x4;", Spaces); 22604 verifyFormat("vector< ::std::string > x4;", Spaces); 22605 verifyFormat("vector<int> x5;", Spaces); 22606 verifyFormat("vector< int > x5;", Spaces); 22607 verifyFormat("Foo<int, Bar> x6;", Spaces); 22608 verifyFormat("Foo< int, Bar > x6;", Spaces); 22609 verifyFormat("Foo<::int, ::Bar> x7;", Spaces); 22610 verifyFormat("Foo< ::int, ::Bar > x7;", Spaces); 22611 22612 verifyFormat("A<A<int>>();", Spaces); 22613 verifyFormat("A< A< int > >();", Spaces); 22614 verifyFormat("A<A<int > >();", Spaces); 22615 verifyFormat("A< A< int>>();", Spaces); 22616 22617 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22618 verifyFormat("// clang-format off\n" 22619 "foo<<<1, 1>>>();\n" 22620 "// clang-format on\n", 22621 Spaces); 22622 verifyFormat("// clang-format off\n" 22623 "foo< < <1, 1> > >();\n" 22624 "// clang-format on\n", 22625 Spaces); 22626 } 22627 22628 TEST_F(FormatTest, SpaceAfterTemplateKeyword) { 22629 FormatStyle Style = getLLVMStyle(); 22630 Style.SpaceAfterTemplateKeyword = false; 22631 verifyFormat("template<int> void foo();", Style); 22632 } 22633 22634 TEST_F(FormatTest, TripleAngleBrackets) { 22635 verifyFormat("f<<<1, 1>>>();"); 22636 verifyFormat("f<<<1, 1, 1, s>>>();"); 22637 verifyFormat("f<<<a, b, c, d>>>();"); 22638 EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();")); 22639 verifyFormat("f<param><<<1, 1>>>();"); 22640 verifyFormat("f<1><<<1, 1>>>();"); 22641 EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();")); 22642 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 22643 "aaaaaaaaaaa<<<\n 1, 1>>>();"); 22644 verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n" 22645 " <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();"); 22646 } 22647 22648 TEST_F(FormatTest, MergeLessLessAtEnd) { 22649 verifyFormat("<<"); 22650 EXPECT_EQ("< < <", format("\\\n<<<")); 22651 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 22652 "aaallvm::outs() <<"); 22653 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 22654 "aaaallvm::outs()\n <<"); 22655 } 22656 22657 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) { 22658 std::string code = "#if A\n" 22659 "#if B\n" 22660 "a.\n" 22661 "#endif\n" 22662 " a = 1;\n" 22663 "#else\n" 22664 "#endif\n" 22665 "#if C\n" 22666 "#else\n" 22667 "#endif\n"; 22668 EXPECT_EQ(code, format(code)); 22669 } 22670 22671 TEST_F(FormatTest, HandleConflictMarkers) { 22672 // Git/SVN conflict markers. 22673 EXPECT_EQ("int a;\n" 22674 "void f() {\n" 22675 " callme(some(parameter1,\n" 22676 "<<<<<<< text by the vcs\n" 22677 " parameter2),\n" 22678 "||||||| text by the vcs\n" 22679 " parameter2),\n" 22680 " parameter3,\n" 22681 "======= text by the vcs\n" 22682 " parameter2, parameter3),\n" 22683 ">>>>>>> text by the vcs\n" 22684 " otherparameter);\n", 22685 format("int a;\n" 22686 "void f() {\n" 22687 " callme(some(parameter1,\n" 22688 "<<<<<<< text by the vcs\n" 22689 " parameter2),\n" 22690 "||||||| text by the vcs\n" 22691 " parameter2),\n" 22692 " parameter3,\n" 22693 "======= text by the vcs\n" 22694 " parameter2,\n" 22695 " parameter3),\n" 22696 ">>>>>>> text by the vcs\n" 22697 " otherparameter);\n")); 22698 22699 // Perforce markers. 22700 EXPECT_EQ("void f() {\n" 22701 " function(\n" 22702 ">>>> text by the vcs\n" 22703 " parameter,\n" 22704 "==== text by the vcs\n" 22705 " parameter,\n" 22706 "==== text by the vcs\n" 22707 " parameter,\n" 22708 "<<<< text by the vcs\n" 22709 " parameter);\n", 22710 format("void f() {\n" 22711 " function(\n" 22712 ">>>> text by the vcs\n" 22713 " parameter,\n" 22714 "==== text by the vcs\n" 22715 " parameter,\n" 22716 "==== text by the vcs\n" 22717 " parameter,\n" 22718 "<<<< text by the vcs\n" 22719 " parameter);\n")); 22720 22721 EXPECT_EQ("<<<<<<<\n" 22722 "|||||||\n" 22723 "=======\n" 22724 ">>>>>>>", 22725 format("<<<<<<<\n" 22726 "|||||||\n" 22727 "=======\n" 22728 ">>>>>>>")); 22729 22730 EXPECT_EQ("<<<<<<<\n" 22731 "|||||||\n" 22732 "int i;\n" 22733 "=======\n" 22734 ">>>>>>>", 22735 format("<<<<<<<\n" 22736 "|||||||\n" 22737 "int i;\n" 22738 "=======\n" 22739 ">>>>>>>")); 22740 22741 // FIXME: Handle parsing of macros around conflict markers correctly: 22742 EXPECT_EQ("#define Macro \\\n" 22743 "<<<<<<<\n" 22744 "Something \\\n" 22745 "|||||||\n" 22746 "Else \\\n" 22747 "=======\n" 22748 "Other \\\n" 22749 ">>>>>>>\n" 22750 " End int i;\n", 22751 format("#define Macro \\\n" 22752 "<<<<<<<\n" 22753 " Something \\\n" 22754 "|||||||\n" 22755 " Else \\\n" 22756 "=======\n" 22757 " Other \\\n" 22758 ">>>>>>>\n" 22759 " End\n" 22760 "int i;\n")); 22761 22762 verifyFormat(R"(==== 22763 #ifdef A 22764 a 22765 #else 22766 b 22767 #endif 22768 )"); 22769 } 22770 22771 TEST_F(FormatTest, DisableRegions) { 22772 EXPECT_EQ("int i;\n" 22773 "// clang-format off\n" 22774 " int j;\n" 22775 "// clang-format on\n" 22776 "int k;", 22777 format(" int i;\n" 22778 " // clang-format off\n" 22779 " int j;\n" 22780 " // clang-format on\n" 22781 " int k;")); 22782 EXPECT_EQ("int i;\n" 22783 "/* clang-format off */\n" 22784 " int j;\n" 22785 "/* clang-format on */\n" 22786 "int k;", 22787 format(" int i;\n" 22788 " /* clang-format off */\n" 22789 " int j;\n" 22790 " /* clang-format on */\n" 22791 " int k;")); 22792 22793 // Don't reflow comments within disabled regions. 22794 EXPECT_EQ("// clang-format off\n" 22795 "// long long long long long long line\n" 22796 "/* clang-format on */\n" 22797 "/* long long long\n" 22798 " * long long long\n" 22799 " * line */\n" 22800 "int i;\n" 22801 "/* clang-format off */\n" 22802 "/* long long long long long long line */\n", 22803 format("// clang-format off\n" 22804 "// long long long long long long line\n" 22805 "/* clang-format on */\n" 22806 "/* long long long long long long line */\n" 22807 "int i;\n" 22808 "/* clang-format off */\n" 22809 "/* long long long long long long line */\n", 22810 getLLVMStyleWithColumns(20))); 22811 } 22812 22813 TEST_F(FormatTest, DoNotCrashOnInvalidInput) { 22814 format("? ) ="); 22815 verifyNoCrash("#define a\\\n /**/}"); 22816 } 22817 22818 TEST_F(FormatTest, FormatsTableGenCode) { 22819 FormatStyle Style = getLLVMStyle(); 22820 Style.Language = FormatStyle::LK_TableGen; 22821 verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style); 22822 } 22823 22824 TEST_F(FormatTest, ArrayOfTemplates) { 22825 EXPECT_EQ("auto a = new unique_ptr<int>[10];", 22826 format("auto a = new unique_ptr<int > [ 10];")); 22827 22828 FormatStyle Spaces = getLLVMStyle(); 22829 Spaces.SpacesInSquareBrackets = true; 22830 EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];", 22831 format("auto a = new unique_ptr<int > [10];", Spaces)); 22832 } 22833 22834 TEST_F(FormatTest, ArrayAsTemplateType) { 22835 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;", 22836 format("auto a = unique_ptr < Foo < Bar>[ 10]> ;")); 22837 22838 FormatStyle Spaces = getLLVMStyle(); 22839 Spaces.SpacesInSquareBrackets = true; 22840 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;", 22841 format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces)); 22842 } 22843 22844 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); } 22845 22846 TEST(FormatStyle, GetStyleWithEmptyFileName) { 22847 llvm::vfs::InMemoryFileSystem FS; 22848 auto Style1 = getStyle("file", "", "Google", "", &FS); 22849 ASSERT_TRUE((bool)Style1); 22850 ASSERT_EQ(*Style1, getGoogleStyle()); 22851 } 22852 22853 TEST(FormatStyle, GetStyleOfFile) { 22854 llvm::vfs::InMemoryFileSystem FS; 22855 // Test 1: format file in the same directory. 22856 ASSERT_TRUE( 22857 FS.addFile("/a/.clang-format", 0, 22858 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM"))); 22859 ASSERT_TRUE( 22860 FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22861 auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS); 22862 ASSERT_TRUE((bool)Style1); 22863 ASSERT_EQ(*Style1, getLLVMStyle()); 22864 22865 // Test 2.1: fallback to default. 22866 ASSERT_TRUE( 22867 FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22868 auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS); 22869 ASSERT_TRUE((bool)Style2); 22870 ASSERT_EQ(*Style2, getMozillaStyle()); 22871 22872 // Test 2.2: no format on 'none' fallback style. 22873 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS); 22874 ASSERT_TRUE((bool)Style2); 22875 ASSERT_EQ(*Style2, getNoStyle()); 22876 22877 // Test 2.3: format if config is found with no based style while fallback is 22878 // 'none'. 22879 ASSERT_TRUE(FS.addFile("/b/.clang-format", 0, 22880 llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2"))); 22881 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS); 22882 ASSERT_TRUE((bool)Style2); 22883 ASSERT_EQ(*Style2, getLLVMStyle()); 22884 22885 // Test 2.4: format if yaml with no based style, while fallback is 'none'. 22886 Style2 = getStyle("{}", "a.h", "none", "", &FS); 22887 ASSERT_TRUE((bool)Style2); 22888 ASSERT_EQ(*Style2, getLLVMStyle()); 22889 22890 // Test 3: format file in parent directory. 22891 ASSERT_TRUE( 22892 FS.addFile("/c/.clang-format", 0, 22893 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 22894 ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0, 22895 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22896 auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS); 22897 ASSERT_TRUE((bool)Style3); 22898 ASSERT_EQ(*Style3, getGoogleStyle()); 22899 22900 // Test 4: error on invalid fallback style 22901 auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS); 22902 ASSERT_FALSE((bool)Style4); 22903 llvm::consumeError(Style4.takeError()); 22904 22905 // Test 5: error on invalid yaml on command line 22906 auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS); 22907 ASSERT_FALSE((bool)Style5); 22908 llvm::consumeError(Style5.takeError()); 22909 22910 // Test 6: error on invalid style 22911 auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS); 22912 ASSERT_FALSE((bool)Style6); 22913 llvm::consumeError(Style6.takeError()); 22914 22915 // Test 7: found config file, error on parsing it 22916 ASSERT_TRUE( 22917 FS.addFile("/d/.clang-format", 0, 22918 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n" 22919 "InvalidKey: InvalidValue"))); 22920 ASSERT_TRUE( 22921 FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22922 auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS); 22923 ASSERT_FALSE((bool)Style7a); 22924 llvm::consumeError(Style7a.takeError()); 22925 22926 auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true); 22927 ASSERT_TRUE((bool)Style7b); 22928 22929 // Test 8: inferred per-language defaults apply. 22930 auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS); 22931 ASSERT_TRUE((bool)StyleTd); 22932 ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen)); 22933 22934 // Test 9.1.1: overwriting a file style, when no parent file exists with no 22935 // fallback style. 22936 ASSERT_TRUE(FS.addFile( 22937 "/e/sub/.clang-format", 0, 22938 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n" 22939 "ColumnLimit: 20"))); 22940 ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0, 22941 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22942 auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS); 22943 ASSERT_TRUE(static_cast<bool>(Style9)); 22944 ASSERT_EQ(*Style9, [] { 22945 auto Style = getNoStyle(); 22946 Style.ColumnLimit = 20; 22947 return Style; 22948 }()); 22949 22950 // Test 9.1.2: propagate more than one level with no parent file. 22951 ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0, 22952 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22953 ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0, 22954 llvm::MemoryBuffer::getMemBuffer( 22955 "BasedOnStyle: InheritParentConfig\n" 22956 "WhitespaceSensitiveMacros: ['FOO', 'BAR']"))); 22957 std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"}; 22958 22959 ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros); 22960 Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS); 22961 ASSERT_TRUE(static_cast<bool>(Style9)); 22962 ASSERT_EQ(*Style9, [&NonDefaultWhiteSpaceMacros] { 22963 auto Style = getNoStyle(); 22964 Style.ColumnLimit = 20; 22965 Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros; 22966 return Style; 22967 }()); 22968 22969 // Test 9.2: with LLVM fallback style 22970 Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS); 22971 ASSERT_TRUE(static_cast<bool>(Style9)); 22972 ASSERT_EQ(*Style9, [] { 22973 auto Style = getLLVMStyle(); 22974 Style.ColumnLimit = 20; 22975 return Style; 22976 }()); 22977 22978 // Test 9.3: with a parent file 22979 ASSERT_TRUE( 22980 FS.addFile("/e/.clang-format", 0, 22981 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n" 22982 "UseTab: Always"))); 22983 Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS); 22984 ASSERT_TRUE(static_cast<bool>(Style9)); 22985 ASSERT_EQ(*Style9, [] { 22986 auto Style = getGoogleStyle(); 22987 Style.ColumnLimit = 20; 22988 Style.UseTab = FormatStyle::UT_Always; 22989 return Style; 22990 }()); 22991 22992 // Test 9.4: propagate more than one level with a parent file. 22993 const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] { 22994 auto Style = getGoogleStyle(); 22995 Style.ColumnLimit = 20; 22996 Style.UseTab = FormatStyle::UT_Always; 22997 Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros; 22998 return Style; 22999 }(); 23000 23001 ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros); 23002 Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS); 23003 ASSERT_TRUE(static_cast<bool>(Style9)); 23004 ASSERT_EQ(*Style9, SubSubStyle); 23005 23006 // Test 9.5: use InheritParentConfig as style name 23007 Style9 = 23008 getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS); 23009 ASSERT_TRUE(static_cast<bool>(Style9)); 23010 ASSERT_EQ(*Style9, SubSubStyle); 23011 23012 // Test 9.6: use command line style with inheritance 23013 Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp", 23014 "none", "", &FS); 23015 ASSERT_TRUE(static_cast<bool>(Style9)); 23016 ASSERT_EQ(*Style9, SubSubStyle); 23017 23018 // Test 9.7: use command line style with inheritance and own config 23019 Style9 = getStyle("{BasedOnStyle: InheritParentConfig, " 23020 "WhitespaceSensitiveMacros: ['FOO', 'BAR']}", 23021 "/e/sub/code.cpp", "none", "", &FS); 23022 ASSERT_TRUE(static_cast<bool>(Style9)); 23023 ASSERT_EQ(*Style9, SubSubStyle); 23024 23025 // Test 9.8: use inheritance from a file without BasedOnStyle 23026 ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0, 23027 llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123"))); 23028 ASSERT_TRUE( 23029 FS.addFile("/e/withoutbase/sub/.clang-format", 0, 23030 llvm::MemoryBuffer::getMemBuffer( 23031 "BasedOnStyle: InheritParentConfig\nIndentWidth: 7"))); 23032 // Make sure we do not use the fallback style 23033 Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS); 23034 ASSERT_TRUE(static_cast<bool>(Style9)); 23035 ASSERT_EQ(*Style9, [] { 23036 auto Style = getLLVMStyle(); 23037 Style.ColumnLimit = 123; 23038 return Style; 23039 }()); 23040 23041 Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS); 23042 ASSERT_TRUE(static_cast<bool>(Style9)); 23043 ASSERT_EQ(*Style9, [] { 23044 auto Style = getLLVMStyle(); 23045 Style.ColumnLimit = 123; 23046 Style.IndentWidth = 7; 23047 return Style; 23048 }()); 23049 23050 // Test 9.9: use inheritance from a specific config file. 23051 Style9 = getStyle("file:/e/sub/sub/.clang-format", "/e/sub/sub/code.cpp", 23052 "none", "", &FS); 23053 ASSERT_TRUE(static_cast<bool>(Style9)); 23054 ASSERT_EQ(*Style9, SubSubStyle); 23055 } 23056 23057 TEST(FormatStyle, GetStyleOfSpecificFile) { 23058 llvm::vfs::InMemoryFileSystem FS; 23059 // Specify absolute path to a format file in a parent directory. 23060 ASSERT_TRUE( 23061 FS.addFile("/e/.clang-format", 0, 23062 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM"))); 23063 ASSERT_TRUE( 23064 FS.addFile("/e/explicit.clang-format", 0, 23065 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 23066 ASSERT_TRUE(FS.addFile("/e/sub/sub/sub/test.cpp", 0, 23067 llvm::MemoryBuffer::getMemBuffer("int i;"))); 23068 auto Style = getStyle("file:/e/explicit.clang-format", 23069 "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS); 23070 ASSERT_TRUE(static_cast<bool>(Style)); 23071 ASSERT_EQ(*Style, getGoogleStyle()); 23072 23073 // Specify relative path to a format file. 23074 ASSERT_TRUE( 23075 FS.addFile("../../e/explicit.clang-format", 0, 23076 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 23077 Style = getStyle("file:../../e/explicit.clang-format", 23078 "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS); 23079 ASSERT_TRUE(static_cast<bool>(Style)); 23080 ASSERT_EQ(*Style, getGoogleStyle()); 23081 23082 // Specify path to a format file that does not exist. 23083 Style = getStyle("file:/e/missing.clang-format", "/e/sub/sub/sub/test.cpp", 23084 "LLVM", "", &FS); 23085 ASSERT_FALSE(static_cast<bool>(Style)); 23086 llvm::consumeError(Style.takeError()); 23087 23088 // Specify path to a file on the filesystem. 23089 SmallString<128> FormatFilePath; 23090 std::error_code ECF = llvm::sys::fs::createTemporaryFile( 23091 "FormatFileTest", "tpl", FormatFilePath); 23092 EXPECT_FALSE((bool)ECF); 23093 llvm::raw_fd_ostream FormatFileTest(FormatFilePath, ECF); 23094 EXPECT_FALSE((bool)ECF); 23095 FormatFileTest << "BasedOnStyle: Google\n"; 23096 FormatFileTest.close(); 23097 23098 SmallString<128> TestFilePath; 23099 std::error_code ECT = 23100 llvm::sys::fs::createTemporaryFile("CodeFileTest", "cc", TestFilePath); 23101 EXPECT_FALSE((bool)ECT); 23102 llvm::raw_fd_ostream CodeFileTest(TestFilePath, ECT); 23103 CodeFileTest << "int i;\n"; 23104 CodeFileTest.close(); 23105 23106 std::string format_file_arg = std::string("file:") + FormatFilePath.c_str(); 23107 Style = getStyle(format_file_arg, TestFilePath, "LLVM", "", nullptr); 23108 23109 llvm::sys::fs::remove(FormatFilePath.c_str()); 23110 llvm::sys::fs::remove(TestFilePath.c_str()); 23111 ASSERT_TRUE(static_cast<bool>(Style)); 23112 ASSERT_EQ(*Style, getGoogleStyle()); 23113 } 23114 23115 TEST_F(ReplacementTest, FormatCodeAfterReplacements) { 23116 // Column limit is 20. 23117 std::string Code = "Type *a =\n" 23118 " new Type();\n" 23119 "g(iiiii, 0, jjjjj,\n" 23120 " 0, kkkkk, 0, mm);\n" 23121 "int bad = format ;"; 23122 std::string Expected = "auto a = new Type();\n" 23123 "g(iiiii, nullptr,\n" 23124 " jjjjj, nullptr,\n" 23125 " kkkkk, nullptr,\n" 23126 " mm);\n" 23127 "int bad = format ;"; 23128 FileID ID = Context.createInMemoryFile("format.cpp", Code); 23129 tooling::Replacements Replaces = toReplacements( 23130 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6, 23131 "auto "), 23132 tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1, 23133 "nullptr"), 23134 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1, 23135 "nullptr"), 23136 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1, 23137 "nullptr")}); 23138 23139 FormatStyle Style = getLLVMStyle(); 23140 Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility. 23141 auto FormattedReplaces = formatReplacements(Code, Replaces, Style); 23142 EXPECT_TRUE(static_cast<bool>(FormattedReplaces)) 23143 << llvm::toString(FormattedReplaces.takeError()) << "\n"; 23144 auto Result = applyAllReplacements(Code, *FormattedReplaces); 23145 EXPECT_TRUE(static_cast<bool>(Result)); 23146 EXPECT_EQ(Expected, *Result); 23147 } 23148 23149 TEST_F(ReplacementTest, SortIncludesAfterReplacement) { 23150 std::string Code = "#include \"a.h\"\n" 23151 "#include \"c.h\"\n" 23152 "\n" 23153 "int main() {\n" 23154 " return 0;\n" 23155 "}"; 23156 std::string Expected = "#include \"a.h\"\n" 23157 "#include \"b.h\"\n" 23158 "#include \"c.h\"\n" 23159 "\n" 23160 "int main() {\n" 23161 " return 0;\n" 23162 "}"; 23163 FileID ID = Context.createInMemoryFile("fix.cpp", Code); 23164 tooling::Replacements Replaces = toReplacements( 23165 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0, 23166 "#include \"b.h\"\n")}); 23167 23168 FormatStyle Style = getLLVMStyle(); 23169 Style.SortIncludes = FormatStyle::SI_CaseSensitive; 23170 auto FormattedReplaces = formatReplacements(Code, Replaces, Style); 23171 EXPECT_TRUE(static_cast<bool>(FormattedReplaces)) 23172 << llvm::toString(FormattedReplaces.takeError()) << "\n"; 23173 auto Result = applyAllReplacements(Code, *FormattedReplaces); 23174 EXPECT_TRUE(static_cast<bool>(Result)); 23175 EXPECT_EQ(Expected, *Result); 23176 } 23177 23178 TEST_F(FormatTest, FormatSortsUsingDeclarations) { 23179 EXPECT_EQ("using std::cin;\n" 23180 "using std::cout;", 23181 format("using std::cout;\n" 23182 "using std::cin;", 23183 getGoogleStyle())); 23184 } 23185 23186 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) { 23187 FormatStyle Style = getLLVMStyle(); 23188 Style.Standard = FormatStyle::LS_Cpp03; 23189 // cpp03 recognize this string as identifier u8 and literal character 'a' 23190 EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style)); 23191 } 23192 23193 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) { 23194 // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers 23195 // all modes, including C++11, C++14 and C++17 23196 EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';")); 23197 } 23198 23199 TEST_F(FormatTest, DoNotFormatLikelyXml) { 23200 EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle())); 23201 EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle())); 23202 } 23203 23204 TEST_F(FormatTest, StructuredBindings) { 23205 // Structured bindings is a C++17 feature. 23206 // all modes, including C++11, C++14 and C++17 23207 verifyFormat("auto [a, b] = f();"); 23208 EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();")); 23209 EXPECT_EQ("const auto [a, b] = f();", format("const auto[a, b] = f();")); 23210 EXPECT_EQ("auto const [a, b] = f();", format("auto const[a, b] = f();")); 23211 EXPECT_EQ("auto const volatile [a, b] = f();", 23212 format("auto const volatile[a, b] = f();")); 23213 EXPECT_EQ("auto [a, b, c] = f();", format("auto [ a , b,c ] = f();")); 23214 EXPECT_EQ("auto &[a, b, c] = f();", 23215 format("auto &[ a , b,c ] = f();")); 23216 EXPECT_EQ("auto &&[a, b, c] = f();", 23217 format("auto &&[ a , b,c ] = f();")); 23218 EXPECT_EQ("auto const &[a, b] = f();", format("auto const&[a, b] = f();")); 23219 EXPECT_EQ("auto const volatile &&[a, b] = f();", 23220 format("auto const volatile &&[a, b] = f();")); 23221 EXPECT_EQ("auto const &&[a, b] = f();", 23222 format("auto const && [a, b] = f();")); 23223 EXPECT_EQ("const auto &[a, b] = f();", 23224 format("const auto & [a, b] = f();")); 23225 EXPECT_EQ("const auto volatile &&[a, b] = f();", 23226 format("const auto volatile &&[a, b] = f();")); 23227 EXPECT_EQ("volatile const auto &&[a, b] = f();", 23228 format("volatile const auto &&[a, b] = f();")); 23229 EXPECT_EQ("const auto &&[a, b] = f();", 23230 format("const auto && [a, b] = f();")); 23231 23232 // Make sure we don't mistake structured bindings for lambdas. 23233 FormatStyle PointerMiddle = getLLVMStyle(); 23234 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle; 23235 verifyFormat("auto [a1, b]{A * i};", getGoogleStyle()); 23236 verifyFormat("auto [a2, b]{A * i};", getLLVMStyle()); 23237 verifyFormat("auto [a3, b]{A * i};", PointerMiddle); 23238 verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle()); 23239 verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle()); 23240 verifyFormat("auto const [a3, b]{A * i};", PointerMiddle); 23241 verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle()); 23242 verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle()); 23243 verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle); 23244 verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle()); 23245 verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle()); 23246 verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle); 23247 23248 EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}", 23249 format("for (const auto && [a, b] : some_range) {\n}")); 23250 EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}", 23251 format("for (const auto & [a, b] : some_range) {\n}")); 23252 EXPECT_EQ("for (const auto [a, b] : some_range) {\n}", 23253 format("for (const auto[a, b] : some_range) {\n}")); 23254 EXPECT_EQ("auto [x, y](expr);", format("auto[x,y] (expr);")); 23255 EXPECT_EQ("auto &[x, y](expr);", format("auto & [x,y] (expr);")); 23256 EXPECT_EQ("auto &&[x, y](expr);", format("auto && [x,y] (expr);")); 23257 EXPECT_EQ("auto const &[x, y](expr);", 23258 format("auto const & [x,y] (expr);")); 23259 EXPECT_EQ("auto const &&[x, y](expr);", 23260 format("auto const && [x,y] (expr);")); 23261 EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y] {expr};")); 23262 EXPECT_EQ("auto const &[x, y]{expr};", 23263 format("auto const & [x,y] {expr};")); 23264 EXPECT_EQ("auto const &&[x, y]{expr};", 23265 format("auto const && [x,y] {expr};")); 23266 23267 FormatStyle Spaces = getLLVMStyle(); 23268 Spaces.SpacesInSquareBrackets = true; 23269 verifyFormat("auto [ a, b ] = f();", Spaces); 23270 verifyFormat("auto &&[ a, b ] = f();", Spaces); 23271 verifyFormat("auto &[ a, b ] = f();", Spaces); 23272 verifyFormat("auto const &&[ a, b ] = f();", Spaces); 23273 verifyFormat("auto const &[ a, b ] = f();", Spaces); 23274 } 23275 23276 TEST_F(FormatTest, FileAndCode) { 23277 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", "")); 23278 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", "")); 23279 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", "")); 23280 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "")); 23281 EXPECT_EQ(FormatStyle::LK_ObjC, 23282 guessLanguage("foo.h", "@interface Foo\n@end\n")); 23283 EXPECT_EQ( 23284 FormatStyle::LK_ObjC, 23285 guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }")); 23286 EXPECT_EQ(FormatStyle::LK_ObjC, 23287 guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))")); 23288 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;")); 23289 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", "")); 23290 EXPECT_EQ(FormatStyle::LK_ObjC, 23291 guessLanguage("foo", "@interface Foo\n@end\n")); 23292 EXPECT_EQ(FormatStyle::LK_ObjC, 23293 guessLanguage("foo.h", "int DoStuff(CGRect rect);\n")); 23294 EXPECT_EQ( 23295 FormatStyle::LK_ObjC, 23296 guessLanguage("foo.h", 23297 "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n")); 23298 EXPECT_EQ( 23299 FormatStyle::LK_Cpp, 23300 guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;")); 23301 // Only one of the two preprocessor regions has ObjC-like code. 23302 EXPECT_EQ(FormatStyle::LK_ObjC, 23303 guessLanguage("foo.h", "#if A\n" 23304 "#define B() C\n" 23305 "#else\n" 23306 "#define B() [NSString a:@\"\"]\n" 23307 "#endif\n")); 23308 } 23309 23310 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) { 23311 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];")); 23312 EXPECT_EQ(FormatStyle::LK_ObjC, 23313 guessLanguage("foo.h", "array[[calculator getIndex]];")); 23314 EXPECT_EQ(FormatStyle::LK_Cpp, 23315 guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];")); 23316 EXPECT_EQ( 23317 FormatStyle::LK_Cpp, 23318 guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];")); 23319 EXPECT_EQ(FormatStyle::LK_ObjC, 23320 guessLanguage("foo.h", "[[noreturn foo] bar];")); 23321 EXPECT_EQ(FormatStyle::LK_Cpp, 23322 guessLanguage("foo.h", "[[clang::fallthrough]];")); 23323 EXPECT_EQ(FormatStyle::LK_ObjC, 23324 guessLanguage("foo.h", "[[clang:fallthrough] foo];")); 23325 EXPECT_EQ(FormatStyle::LK_Cpp, 23326 guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];")); 23327 EXPECT_EQ(FormatStyle::LK_Cpp, 23328 guessLanguage("foo.h", "[[using clang: fallthrough]];")); 23329 EXPECT_EQ(FormatStyle::LK_ObjC, 23330 guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];")); 23331 EXPECT_EQ(FormatStyle::LK_Cpp, 23332 guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];")); 23333 EXPECT_EQ( 23334 FormatStyle::LK_Cpp, 23335 guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)")); 23336 EXPECT_EQ( 23337 FormatStyle::LK_Cpp, 23338 guessLanguage("foo.h", 23339 "[[clang::callable_when(\"unconsumed\", \"unknown\")]]")); 23340 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]")); 23341 } 23342 23343 TEST_F(FormatTest, GuessLanguageWithCaret) { 23344 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);")); 23345 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);")); 23346 EXPECT_EQ(FormatStyle::LK_ObjC, 23347 guessLanguage("foo.h", "int(^)(char, float);")); 23348 EXPECT_EQ(FormatStyle::LK_ObjC, 23349 guessLanguage("foo.h", "int(^foo)(char, float);")); 23350 EXPECT_EQ(FormatStyle::LK_ObjC, 23351 guessLanguage("foo.h", "int(^foo[10])(char, float);")); 23352 EXPECT_EQ(FormatStyle::LK_ObjC, 23353 guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);")); 23354 EXPECT_EQ( 23355 FormatStyle::LK_ObjC, 23356 guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);")); 23357 } 23358 23359 TEST_F(FormatTest, GuessLanguageWithPragmas) { 23360 EXPECT_EQ(FormatStyle::LK_Cpp, 23361 guessLanguage("foo.h", "__pragma(warning(disable:))")); 23362 EXPECT_EQ(FormatStyle::LK_Cpp, 23363 guessLanguage("foo.h", "#pragma(warning(disable:))")); 23364 EXPECT_EQ(FormatStyle::LK_Cpp, 23365 guessLanguage("foo.h", "_Pragma(warning(disable:))")); 23366 } 23367 23368 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) { 23369 // ASM symbolic names are identifiers that must be surrounded by [] without 23370 // space in between: 23371 // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands 23372 23373 // Example from https://bugs.llvm.org/show_bug.cgi?id=45108. 23374 verifyFormat(R"(// 23375 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result)); 23376 )"); 23377 23378 // A list of several ASM symbolic names. 23379 verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)"); 23380 23381 // ASM symbolic names in inline ASM with inputs and outputs. 23382 verifyFormat(R"(// 23383 asm("cmoveq %1, %2, %[result]" 23384 : [result] "=r"(result) 23385 : "r"(test), "r"(new), "[result]"(old)); 23386 )"); 23387 23388 // ASM symbolic names in inline ASM with no outputs. 23389 verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)"); 23390 } 23391 23392 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) { 23393 EXPECT_EQ(FormatStyle::LK_Cpp, 23394 guessLanguage("foo.h", "void f() {\n" 23395 " asm (\"mov %[e], %[d]\"\n" 23396 " : [d] \"=rm\" (d)\n" 23397 " [e] \"rm\" (*e));\n" 23398 "}")); 23399 EXPECT_EQ(FormatStyle::LK_Cpp, 23400 guessLanguage("foo.h", "void f() {\n" 23401 " _asm (\"mov %[e], %[d]\"\n" 23402 " : [d] \"=rm\" (d)\n" 23403 " [e] \"rm\" (*e));\n" 23404 "}")); 23405 EXPECT_EQ(FormatStyle::LK_Cpp, 23406 guessLanguage("foo.h", "void f() {\n" 23407 " __asm (\"mov %[e], %[d]\"\n" 23408 " : [d] \"=rm\" (d)\n" 23409 " [e] \"rm\" (*e));\n" 23410 "}")); 23411 EXPECT_EQ(FormatStyle::LK_Cpp, 23412 guessLanguage("foo.h", "void f() {\n" 23413 " __asm__ (\"mov %[e], %[d]\"\n" 23414 " : [d] \"=rm\" (d)\n" 23415 " [e] \"rm\" (*e));\n" 23416 "}")); 23417 EXPECT_EQ(FormatStyle::LK_Cpp, 23418 guessLanguage("foo.h", "void f() {\n" 23419 " asm (\"mov %[e], %[d]\"\n" 23420 " : [d] \"=rm\" (d),\n" 23421 " [e] \"rm\" (*e));\n" 23422 "}")); 23423 EXPECT_EQ(FormatStyle::LK_Cpp, 23424 guessLanguage("foo.h", "void f() {\n" 23425 " asm volatile (\"mov %[e], %[d]\"\n" 23426 " : [d] \"=rm\" (d)\n" 23427 " [e] \"rm\" (*e));\n" 23428 "}")); 23429 } 23430 23431 TEST_F(FormatTest, GuessLanguageWithChildLines) { 23432 EXPECT_EQ(FormatStyle::LK_Cpp, 23433 guessLanguage("foo.h", "#define FOO ({ std::string s; })")); 23434 EXPECT_EQ(FormatStyle::LK_ObjC, 23435 guessLanguage("foo.h", "#define FOO ({ NSString *s; })")); 23436 EXPECT_EQ( 23437 FormatStyle::LK_Cpp, 23438 guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })")); 23439 EXPECT_EQ( 23440 FormatStyle::LK_ObjC, 23441 guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })")); 23442 } 23443 23444 TEST_F(FormatTest, TypenameMacros) { 23445 std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"}; 23446 23447 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353 23448 FormatStyle Google = getGoogleStyleWithColumns(0); 23449 Google.TypenameMacros = TypenameMacros; 23450 verifyFormat("struct foo {\n" 23451 " int bar;\n" 23452 " TAILQ_ENTRY(a) bleh;\n" 23453 "};", 23454 Google); 23455 23456 FormatStyle Macros = getLLVMStyle(); 23457 Macros.TypenameMacros = TypenameMacros; 23458 23459 verifyFormat("STACK_OF(int) a;", Macros); 23460 verifyFormat("STACK_OF(int) *a;", Macros); 23461 verifyFormat("STACK_OF(int const *) *a;", Macros); 23462 verifyFormat("STACK_OF(int *const) *a;", Macros); 23463 verifyFormat("STACK_OF(int, string) a;", Macros); 23464 verifyFormat("STACK_OF(LIST(int)) a;", Macros); 23465 verifyFormat("STACK_OF(LIST(int)) a, b;", Macros); 23466 verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros); 23467 verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros); 23468 verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros); 23469 verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros); 23470 23471 Macros.PointerAlignment = FormatStyle::PAS_Left; 23472 verifyFormat("STACK_OF(int)* a;", Macros); 23473 verifyFormat("STACK_OF(int*)* a;", Macros); 23474 verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros); 23475 verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros); 23476 verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros); 23477 } 23478 23479 TEST_F(FormatTest, AtomicQualifier) { 23480 // Check that we treate _Atomic as a type and not a function call 23481 FormatStyle Google = getGoogleStyleWithColumns(0); 23482 verifyFormat("struct foo {\n" 23483 " int a1;\n" 23484 " _Atomic(a) a2;\n" 23485 " _Atomic(_Atomic(int) *const) a3;\n" 23486 "};", 23487 Google); 23488 verifyFormat("_Atomic(uint64_t) a;"); 23489 verifyFormat("_Atomic(uint64_t) *a;"); 23490 verifyFormat("_Atomic(uint64_t const *) *a;"); 23491 verifyFormat("_Atomic(uint64_t *const) *a;"); 23492 verifyFormat("_Atomic(const uint64_t *) *a;"); 23493 verifyFormat("_Atomic(uint64_t) a;"); 23494 verifyFormat("_Atomic(_Atomic(uint64_t)) a;"); 23495 verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;"); 23496 verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}"); 23497 verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);"); 23498 23499 verifyFormat("_Atomic(uint64_t) *s(InitValue);"); 23500 verifyFormat("_Atomic(uint64_t) *s{InitValue};"); 23501 FormatStyle Style = getLLVMStyle(); 23502 Style.PointerAlignment = FormatStyle::PAS_Left; 23503 verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style); 23504 verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style); 23505 verifyFormat("_Atomic(int)* a;", Style); 23506 verifyFormat("_Atomic(int*)* a;", Style); 23507 verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style); 23508 23509 Style.SpacesInCStyleCastParentheses = true; 23510 Style.SpacesInParentheses = false; 23511 verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style); 23512 Style.SpacesInCStyleCastParentheses = false; 23513 Style.SpacesInParentheses = true; 23514 verifyFormat("x = (_Atomic( uint64_t ))*a;", Style); 23515 verifyFormat("x = (_Atomic( uint64_t ))&a;", Style); 23516 } 23517 23518 TEST_F(FormatTest, AmbersandInLamda) { 23519 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899 23520 FormatStyle AlignStyle = getLLVMStyle(); 23521 AlignStyle.PointerAlignment = FormatStyle::PAS_Left; 23522 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle); 23523 AlignStyle.PointerAlignment = FormatStyle::PAS_Right; 23524 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle); 23525 } 23526 23527 TEST_F(FormatTest, SpacesInConditionalStatement) { 23528 FormatStyle Spaces = getLLVMStyle(); 23529 Spaces.IfMacros.clear(); 23530 Spaces.IfMacros.push_back("MYIF"); 23531 Spaces.SpacesInConditionalStatement = true; 23532 verifyFormat("for ( int i = 0; i; i++ )\n continue;", Spaces); 23533 verifyFormat("if ( !a )\n return;", Spaces); 23534 verifyFormat("if ( a )\n return;", Spaces); 23535 verifyFormat("if constexpr ( a )\n return;", Spaces); 23536 verifyFormat("MYIF ( a )\n return;", Spaces); 23537 verifyFormat("MYIF ( a )\n return;\nelse MYIF ( b )\n return;", Spaces); 23538 verifyFormat("MYIF ( a )\n return;\nelse\n return;", Spaces); 23539 verifyFormat("switch ( a )\ncase 1:\n return;", Spaces); 23540 verifyFormat("while ( a )\n return;", Spaces); 23541 verifyFormat("while ( (a && b) )\n return;", Spaces); 23542 verifyFormat("do {\n} while ( 1 != 0 );", Spaces); 23543 verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces); 23544 // Check that space on the left of "::" is inserted as expected at beginning 23545 // of condition. 23546 verifyFormat("while ( ::func() )\n return;", Spaces); 23547 23548 // Check impact of ControlStatementsExceptControlMacros is honored. 23549 Spaces.SpaceBeforeParens = 23550 FormatStyle::SBPO_ControlStatementsExceptControlMacros; 23551 verifyFormat("MYIF( a )\n return;", Spaces); 23552 verifyFormat("MYIF( a )\n return;\nelse MYIF( b )\n return;", Spaces); 23553 verifyFormat("MYIF( a )\n return;\nelse\n return;", Spaces); 23554 } 23555 23556 TEST_F(FormatTest, AlternativeOperators) { 23557 // Test case for ensuring alternate operators are not 23558 // combined with their right most neighbour. 23559 verifyFormat("int a and b;"); 23560 verifyFormat("int a and_eq b;"); 23561 verifyFormat("int a bitand b;"); 23562 verifyFormat("int a bitor b;"); 23563 verifyFormat("int a compl b;"); 23564 verifyFormat("int a not b;"); 23565 verifyFormat("int a not_eq b;"); 23566 verifyFormat("int a or b;"); 23567 verifyFormat("int a xor b;"); 23568 verifyFormat("int a xor_eq b;"); 23569 verifyFormat("return this not_eq bitand other;"); 23570 verifyFormat("bool operator not_eq(const X bitand other)"); 23571 23572 verifyFormat("int a and 5;"); 23573 verifyFormat("int a and_eq 5;"); 23574 verifyFormat("int a bitand 5;"); 23575 verifyFormat("int a bitor 5;"); 23576 verifyFormat("int a compl 5;"); 23577 verifyFormat("int a not 5;"); 23578 verifyFormat("int a not_eq 5;"); 23579 verifyFormat("int a or 5;"); 23580 verifyFormat("int a xor 5;"); 23581 verifyFormat("int a xor_eq 5;"); 23582 23583 verifyFormat("int a compl(5);"); 23584 verifyFormat("int a not(5);"); 23585 23586 /* FIXME handle alternate tokens 23587 * https://en.cppreference.com/w/cpp/language/operator_alternative 23588 // alternative tokens 23589 verifyFormat("compl foo();"); // ~foo(); 23590 verifyFormat("foo() <%%>;"); // foo(); 23591 verifyFormat("void foo() <%%>;"); // void foo(){} 23592 verifyFormat("int a <:1:>;"); // int a[1];[ 23593 verifyFormat("%:define ABC abc"); // #define ABC abc 23594 verifyFormat("%:%:"); // ## 23595 */ 23596 } 23597 23598 TEST_F(FormatTest, STLWhileNotDefineChed) { 23599 verifyFormat("#if defined(while)\n" 23600 "#define while EMIT WARNING C4005\n" 23601 "#endif // while"); 23602 } 23603 23604 TEST_F(FormatTest, OperatorSpacing) { 23605 FormatStyle Style = getLLVMStyle(); 23606 Style.PointerAlignment = FormatStyle::PAS_Right; 23607 verifyFormat("Foo::operator*();", Style); 23608 verifyFormat("Foo::operator void *();", Style); 23609 verifyFormat("Foo::operator void **();", Style); 23610 verifyFormat("Foo::operator void *&();", Style); 23611 verifyFormat("Foo::operator void *&&();", 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 void const *&&();", Style); 23616 verifyFormat("Foo::operator()(void *);", Style); 23617 verifyFormat("Foo::operator*(void *);", Style); 23618 verifyFormat("Foo::operator*();", Style); 23619 verifyFormat("Foo::operator**();", 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<int> &();", Style); 23626 verifyFormat("Foo::operator<Foo> &();", Style); 23627 verifyFormat("Foo::operator<int> &&();", Style); 23628 verifyFormat("Foo::operator<Foo> &&();", Style); 23629 verifyFormat("Foo::operator<int> *&();", Style); 23630 verifyFormat("Foo::operator<Foo> *&();", Style); 23631 verifyFormat("Foo::operator<int> *&&();", Style); 23632 verifyFormat("Foo::operator<Foo> *&&();", Style); 23633 verifyFormat("operator*(int (*)(), class Foo);", Style); 23634 23635 verifyFormat("Foo::operator&();", Style); 23636 verifyFormat("Foo::operator void &();", Style); 23637 verifyFormat("Foo::operator void const &();", Style); 23638 verifyFormat("Foo::operator()(void &);", Style); 23639 verifyFormat("Foo::operator&(void &);", Style); 23640 verifyFormat("Foo::operator&();", Style); 23641 verifyFormat("operator&(int (&)(), class Foo);", Style); 23642 verifyFormat("operator&&(int (&)(), class Foo);", Style); 23643 23644 verifyFormat("Foo::operator&&();", Style); 23645 verifyFormat("Foo::operator**();", Style); 23646 verifyFormat("Foo::operator void &&();", Style); 23647 verifyFormat("Foo::operator void const &&();", Style); 23648 verifyFormat("Foo::operator()(void &&);", Style); 23649 verifyFormat("Foo::operator&&(void &&);", Style); 23650 verifyFormat("Foo::operator&&();", Style); 23651 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23652 verifyFormat("operator const nsTArrayRight<E> &()", Style); 23653 verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()", 23654 Style); 23655 verifyFormat("operator void **()", Style); 23656 verifyFormat("operator const FooRight<Object> &()", Style); 23657 verifyFormat("operator const FooRight<Object> *()", Style); 23658 verifyFormat("operator const FooRight<Object> **()", Style); 23659 verifyFormat("operator const FooRight<Object> *&()", Style); 23660 verifyFormat("operator const FooRight<Object> *&&()", Style); 23661 23662 Style.PointerAlignment = FormatStyle::PAS_Left; 23663 verifyFormat("Foo::operator*();", Style); 23664 verifyFormat("Foo::operator**();", Style); 23665 verifyFormat("Foo::operator void*();", Style); 23666 verifyFormat("Foo::operator void**();", Style); 23667 verifyFormat("Foo::operator void*&();", Style); 23668 verifyFormat("Foo::operator void*&&();", Style); 23669 verifyFormat("Foo::operator void const*();", Style); 23670 verifyFormat("Foo::operator void const**();", Style); 23671 verifyFormat("Foo::operator void const*&();", Style); 23672 verifyFormat("Foo::operator void const*&&();", Style); 23673 verifyFormat("Foo::operator/*comment*/ void*();", Style); 23674 verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style); 23675 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style); 23676 verifyFormat("Foo::operator()(void*);", Style); 23677 verifyFormat("Foo::operator*(void*);", Style); 23678 verifyFormat("Foo::operator*();", Style); 23679 verifyFormat("Foo::operator<int>*();", Style); 23680 verifyFormat("Foo::operator<Foo>*();", Style); 23681 verifyFormat("Foo::operator<int>**();", Style); 23682 verifyFormat("Foo::operator<Foo>**();", Style); 23683 verifyFormat("Foo::operator<Foo>*&();", Style); 23684 verifyFormat("Foo::operator<int>&();", Style); 23685 verifyFormat("Foo::operator<Foo>&();", Style); 23686 verifyFormat("Foo::operator<int>&&();", Style); 23687 verifyFormat("Foo::operator<Foo>&&();", Style); 23688 verifyFormat("Foo::operator<int>*&();", Style); 23689 verifyFormat("Foo::operator<Foo>*&();", Style); 23690 verifyFormat("operator*(int (*)(), class Foo);", Style); 23691 23692 verifyFormat("Foo::operator&();", Style); 23693 verifyFormat("Foo::operator void&();", Style); 23694 verifyFormat("Foo::operator void const&();", Style); 23695 verifyFormat("Foo::operator/*comment*/ void&();", Style); 23696 verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style); 23697 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style); 23698 verifyFormat("Foo::operator()(void&);", Style); 23699 verifyFormat("Foo::operator&(void&);", Style); 23700 verifyFormat("Foo::operator&();", Style); 23701 verifyFormat("operator&(int (&)(), class Foo);", Style); 23702 verifyFormat("operator&(int (&&)(), class Foo);", Style); 23703 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23704 23705 verifyFormat("Foo::operator&&();", Style); 23706 verifyFormat("Foo::operator void&&();", Style); 23707 verifyFormat("Foo::operator void const&&();", Style); 23708 verifyFormat("Foo::operator/*comment*/ void&&();", Style); 23709 verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style); 23710 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style); 23711 verifyFormat("Foo::operator()(void&&);", Style); 23712 verifyFormat("Foo::operator&&(void&&);", Style); 23713 verifyFormat("Foo::operator&&();", Style); 23714 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23715 verifyFormat("operator const nsTArrayLeft<E>&()", Style); 23716 verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()", 23717 Style); 23718 verifyFormat("operator void**()", Style); 23719 verifyFormat("operator const FooLeft<Object>&()", Style); 23720 verifyFormat("operator const FooLeft<Object>*()", Style); 23721 verifyFormat("operator const FooLeft<Object>**()", Style); 23722 verifyFormat("operator const FooLeft<Object>*&()", Style); 23723 verifyFormat("operator const FooLeft<Object>*&&()", Style); 23724 23725 // PR45107 23726 verifyFormat("operator Vector<String>&();", Style); 23727 verifyFormat("operator const Vector<String>&();", Style); 23728 verifyFormat("operator foo::Bar*();", Style); 23729 verifyFormat("operator const Foo<X>::Bar<Y>*();", Style); 23730 verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();", 23731 Style); 23732 23733 Style.PointerAlignment = FormatStyle::PAS_Middle; 23734 verifyFormat("Foo::operator*();", Style); 23735 verifyFormat("Foo::operator void *();", Style); 23736 verifyFormat("Foo::operator()(void *);", Style); 23737 verifyFormat("Foo::operator*(void *);", Style); 23738 verifyFormat("Foo::operator*();", Style); 23739 verifyFormat("operator*(int (*)(), class Foo);", Style); 23740 23741 verifyFormat("Foo::operator&();", Style); 23742 verifyFormat("Foo::operator void &();", Style); 23743 verifyFormat("Foo::operator void const &();", Style); 23744 verifyFormat("Foo::operator()(void &);", Style); 23745 verifyFormat("Foo::operator&(void &);", Style); 23746 verifyFormat("Foo::operator&();", Style); 23747 verifyFormat("operator&(int (&)(), class Foo);", Style); 23748 23749 verifyFormat("Foo::operator&&();", Style); 23750 verifyFormat("Foo::operator void &&();", Style); 23751 verifyFormat("Foo::operator void const &&();", Style); 23752 verifyFormat("Foo::operator()(void &&);", Style); 23753 verifyFormat("Foo::operator&&(void &&);", Style); 23754 verifyFormat("Foo::operator&&();", Style); 23755 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23756 } 23757 23758 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) { 23759 FormatStyle Style = getLLVMStyle(); 23760 // PR46157 23761 verifyFormat("foo(operator+, -42);", Style); 23762 verifyFormat("foo(operator++, -42);", Style); 23763 verifyFormat("foo(operator--, -42);", Style); 23764 verifyFormat("foo(-42, operator--);", Style); 23765 verifyFormat("foo(-42, operator, );", Style); 23766 verifyFormat("foo(operator, , -42);", Style); 23767 } 23768 23769 TEST_F(FormatTest, WhitespaceSensitiveMacros) { 23770 FormatStyle Style = getLLVMStyle(); 23771 Style.WhitespaceSensitiveMacros.push_back("FOO"); 23772 23773 // Don't use the helpers here, since 'mess up' will change the whitespace 23774 // and these are all whitespace sensitive by definition 23775 EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);", 23776 format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style)); 23777 EXPECT_EQ( 23778 "FOO(String-ized&Messy+But\\(: :Still)=Intentional);", 23779 format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style)); 23780 EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);", 23781 format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style)); 23782 EXPECT_EQ("FOO(String-ized&Messy+But,: :\n" 23783 " Still=Intentional);", 23784 format("FOO(String-ized&Messy+But,: :\n" 23785 " Still=Intentional);", 23786 Style)); 23787 Style.AlignConsecutiveAssignments.Enabled = true; 23788 EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n" 23789 " Still=Intentional);", 23790 format("FOO(String-ized=&Messy+But,: :\n" 23791 " Still=Intentional);", 23792 Style)); 23793 23794 Style.ColumnLimit = 21; 23795 EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);", 23796 format("FOO(String-ized&Messy+But: :Still=Intentional);", Style)); 23797 } 23798 23799 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) { 23800 // These tests are not in NamespaceEndCommentsFixerTest because that doesn't 23801 // test its interaction with line wrapping 23802 FormatStyle Style = getLLVMStyleWithColumns(80); 23803 verifyFormat("namespace {\n" 23804 "int i;\n" 23805 "int j;\n" 23806 "} // namespace", 23807 Style); 23808 23809 verifyFormat("namespace AAA {\n" 23810 "int i;\n" 23811 "int j;\n" 23812 "} // namespace AAA", 23813 Style); 23814 23815 EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n" 23816 "int i;\n" 23817 "int j;\n" 23818 "} // namespace Averyveryveryverylongnamespace", 23819 format("namespace Averyveryveryverylongnamespace {\n" 23820 "int i;\n" 23821 "int j;\n" 23822 "}", 23823 Style)); 23824 23825 EXPECT_EQ( 23826 "namespace " 23827 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n" 23828 " went::mad::now {\n" 23829 "int i;\n" 23830 "int j;\n" 23831 "} // namespace\n" 23832 " // " 23833 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::" 23834 "went::mad::now", 23835 format("namespace " 23836 "would::it::save::you::a::lot::of::time::if_::i::" 23837 "just::gave::up::and_::went::mad::now {\n" 23838 "int i;\n" 23839 "int j;\n" 23840 "}", 23841 Style)); 23842 23843 // This used to duplicate the comment again and again on subsequent runs 23844 EXPECT_EQ( 23845 "namespace " 23846 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n" 23847 " went::mad::now {\n" 23848 "int i;\n" 23849 "int j;\n" 23850 "} // namespace\n" 23851 " // " 23852 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::" 23853 "went::mad::now", 23854 format("namespace " 23855 "would::it::save::you::a::lot::of::time::if_::i::" 23856 "just::gave::up::and_::went::mad::now {\n" 23857 "int i;\n" 23858 "int j;\n" 23859 "} // namespace\n" 23860 " // " 23861 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::" 23862 "and_::went::mad::now", 23863 Style)); 23864 } 23865 23866 TEST_F(FormatTest, LikelyUnlikely) { 23867 FormatStyle Style = getLLVMStyle(); 23868 23869 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23870 " return 29;\n" 23871 "}", 23872 Style); 23873 23874 verifyFormat("if (argc > 5) [[likely]] {\n" 23875 " return 29;\n" 23876 "}", 23877 Style); 23878 23879 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23880 " return 29;\n" 23881 "} else [[likely]] {\n" 23882 " return 42;\n" 23883 "}\n", 23884 Style); 23885 23886 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23887 " return 29;\n" 23888 "} else if (argc > 10) [[likely]] {\n" 23889 " return 99;\n" 23890 "} else {\n" 23891 " return 42;\n" 23892 "}\n", 23893 Style); 23894 23895 verifyFormat("if (argc > 5) [[gnu::unused]] {\n" 23896 " return 29;\n" 23897 "}", 23898 Style); 23899 23900 verifyFormat("if (argc > 5) [[unlikely]]\n" 23901 " return 29;\n", 23902 Style); 23903 verifyFormat("if (argc > 5) [[likely]]\n" 23904 " return 29;\n", 23905 Style); 23906 23907 verifyFormat("while (limit > 0) [[unlikely]] {\n" 23908 " --limit;\n" 23909 "}", 23910 Style); 23911 verifyFormat("for (auto &limit : limits) [[likely]] {\n" 23912 " --limit;\n" 23913 "}", 23914 Style); 23915 23916 verifyFormat("for (auto &limit : limits) [[unlikely]]\n" 23917 " --limit;", 23918 Style); 23919 verifyFormat("while (limit > 0) [[likely]]\n" 23920 " --limit;", 23921 Style); 23922 23923 Style.AttributeMacros.push_back("UNLIKELY"); 23924 Style.AttributeMacros.push_back("LIKELY"); 23925 verifyFormat("if (argc > 5) UNLIKELY\n" 23926 " return 29;\n", 23927 Style); 23928 23929 verifyFormat("if (argc > 5) UNLIKELY {\n" 23930 " return 29;\n" 23931 "}", 23932 Style); 23933 verifyFormat("if (argc > 5) UNLIKELY {\n" 23934 " return 29;\n" 23935 "} else [[likely]] {\n" 23936 " return 42;\n" 23937 "}\n", 23938 Style); 23939 verifyFormat("if (argc > 5) UNLIKELY {\n" 23940 " return 29;\n" 23941 "} else LIKELY {\n" 23942 " return 42;\n" 23943 "}\n", 23944 Style); 23945 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23946 " return 29;\n" 23947 "} else LIKELY {\n" 23948 " return 42;\n" 23949 "}\n", 23950 Style); 23951 23952 verifyFormat("for (auto &limit : limits) UNLIKELY {\n" 23953 " --limit;\n" 23954 "}", 23955 Style); 23956 verifyFormat("while (limit > 0) LIKELY {\n" 23957 " --limit;\n" 23958 "}", 23959 Style); 23960 23961 verifyFormat("while (limit > 0) UNLIKELY\n" 23962 " --limit;", 23963 Style); 23964 verifyFormat("for (auto &limit : limits) LIKELY\n" 23965 " --limit;", 23966 Style); 23967 } 23968 23969 TEST_F(FormatTest, PenaltyIndentedWhitespace) { 23970 verifyFormat("Constructor()\n" 23971 " : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 23972 " aaaa(aaaaaaaaaaaaaaaaaa, " 23973 "aaaaaaaaaaaaaaaaaat))"); 23974 verifyFormat("Constructor()\n" 23975 " : aaaaaaaaaaaaa(aaaaaa), " 23976 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)"); 23977 23978 FormatStyle StyleWithWhitespacePenalty = getLLVMStyle(); 23979 StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5; 23980 verifyFormat("Constructor()\n" 23981 " : aaaaaa(aaaaaa),\n" 23982 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 23983 " aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))", 23984 StyleWithWhitespacePenalty); 23985 verifyFormat("Constructor()\n" 23986 " : aaaaaaaaaaaaa(aaaaaa), " 23987 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)", 23988 StyleWithWhitespacePenalty); 23989 } 23990 23991 TEST_F(FormatTest, LLVMDefaultStyle) { 23992 FormatStyle Style = getLLVMStyle(); 23993 verifyFormat("extern \"C\" {\n" 23994 "int foo();\n" 23995 "}", 23996 Style); 23997 } 23998 TEST_F(FormatTest, GNUDefaultStyle) { 23999 FormatStyle Style = getGNUStyle(); 24000 verifyFormat("extern \"C\"\n" 24001 "{\n" 24002 " int foo ();\n" 24003 "}", 24004 Style); 24005 } 24006 TEST_F(FormatTest, MozillaDefaultStyle) { 24007 FormatStyle Style = getMozillaStyle(); 24008 verifyFormat("extern \"C\"\n" 24009 "{\n" 24010 " int foo();\n" 24011 "}", 24012 Style); 24013 } 24014 TEST_F(FormatTest, GoogleDefaultStyle) { 24015 FormatStyle Style = getGoogleStyle(); 24016 verifyFormat("extern \"C\" {\n" 24017 "int foo();\n" 24018 "}", 24019 Style); 24020 } 24021 TEST_F(FormatTest, ChromiumDefaultStyle) { 24022 FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp); 24023 verifyFormat("extern \"C\" {\n" 24024 "int foo();\n" 24025 "}", 24026 Style); 24027 } 24028 TEST_F(FormatTest, MicrosoftDefaultStyle) { 24029 FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp); 24030 verifyFormat("extern \"C\"\n" 24031 "{\n" 24032 " int foo();\n" 24033 "}", 24034 Style); 24035 } 24036 TEST_F(FormatTest, WebKitDefaultStyle) { 24037 FormatStyle Style = getWebKitStyle(); 24038 verifyFormat("extern \"C\" {\n" 24039 "int foo();\n" 24040 "}", 24041 Style); 24042 } 24043 24044 TEST_F(FormatTest, Concepts) { 24045 EXPECT_EQ(getLLVMStyle().BreakBeforeConceptDeclarations, 24046 FormatStyle::BBCDS_Always); 24047 verifyFormat("template <typename T>\n" 24048 "concept True = true;"); 24049 24050 verifyFormat("template <typename T>\n" 24051 "concept C = ((false || foo()) && C2<T>) ||\n" 24052 " (std::trait<T>::value && Baz) || sizeof(T) >= 6;", 24053 getLLVMStyleWithColumns(60)); 24054 24055 verifyFormat("template <typename T>\n" 24056 "concept DelayedCheck = true && requires(T t) { t.bar(); } && " 24057 "sizeof(T) <= 8;"); 24058 24059 verifyFormat("template <typename T>\n" 24060 "concept DelayedCheck = true && requires(T t) {\n" 24061 " t.bar();\n" 24062 " t.baz();\n" 24063 " } && sizeof(T) <= 8;"); 24064 24065 verifyFormat("template <typename T>\n" 24066 "concept DelayedCheck = true && requires(T t) { // Comment\n" 24067 " t.bar();\n" 24068 " t.baz();\n" 24069 " } && sizeof(T) <= 8;"); 24070 24071 verifyFormat("template <typename T>\n" 24072 "concept DelayedCheck = false || requires(T t) { t.bar(); } && " 24073 "sizeof(T) <= 8;"); 24074 24075 verifyFormat("template <typename T>\n" 24076 "concept DelayedCheck = !!false || requires(T t) { t.bar(); } " 24077 "&& sizeof(T) <= 8;"); 24078 24079 verifyFormat( 24080 "template <typename T>\n" 24081 "concept DelayedCheck = static_cast<bool>(0) ||\n" 24082 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 24083 24084 verifyFormat("template <typename T>\n" 24085 "concept DelayedCheck = bool(0) || requires(T t) { t.bar(); } " 24086 "&& sizeof(T) <= 8;"); 24087 24088 verifyFormat( 24089 "template <typename T>\n" 24090 "concept DelayedCheck = (bool)(0) ||\n" 24091 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 24092 24093 verifyFormat("template <typename T>\n" 24094 "concept DelayedCheck = (bool)0 || requires(T t) { t.bar(); } " 24095 "&& sizeof(T) <= 8;"); 24096 24097 verifyFormat("template <typename T>\n" 24098 "concept Size = sizeof(T) >= 5 && requires(T t) { t.bar(); } && " 24099 "sizeof(T) <= 8;"); 24100 24101 verifyFormat("template <typename T>\n" 24102 "concept Size = 2 < 5 && 2 <= 5 && 8 >= 5 && 8 > 5 &&\n" 24103 " requires(T t) {\n" 24104 " t.bar();\n" 24105 " t.baz();\n" 24106 " } && sizeof(T) <= 8 && !(4 < 3);", 24107 getLLVMStyleWithColumns(60)); 24108 24109 verifyFormat("template <typename T>\n" 24110 "concept TrueOrNot = IsAlwaysTrue || IsNeverTrue;"); 24111 24112 verifyFormat("template <typename T>\n" 24113 "concept C = foo();"); 24114 24115 verifyFormat("template <typename T>\n" 24116 "concept C = foo(T());"); 24117 24118 verifyFormat("template <typename T>\n" 24119 "concept C = foo(T{});"); 24120 24121 verifyFormat("template <typename T>\n" 24122 "concept Size = V<sizeof(T)>::Value > 5;"); 24123 24124 verifyFormat("template <typename T>\n" 24125 "concept True = S<T>::Value;"); 24126 24127 verifyFormat( 24128 "template <typename T>\n" 24129 "concept C = []() { return true; }() && requires(T t) { t.bar(); } &&\n" 24130 " sizeof(T) <= 8;"); 24131 24132 // FIXME: This is misformatted because the fake l paren starts at bool, not at 24133 // the lambda l square. 24134 verifyFormat("template <typename T>\n" 24135 "concept C = [] -> bool { return true; }() && requires(T t) { " 24136 "t.bar(); } &&\n" 24137 " sizeof(T) <= 8;"); 24138 24139 verifyFormat( 24140 "template <typename T>\n" 24141 "concept C = decltype([]() { return std::true_type{}; }())::value &&\n" 24142 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 24143 24144 verifyFormat("template <typename T>\n" 24145 "concept C = decltype([]() { return std::true_type{}; " 24146 "}())::value && requires(T t) { t.bar(); } && sizeof(T) <= 8;", 24147 getLLVMStyleWithColumns(120)); 24148 24149 verifyFormat("template <typename T>\n" 24150 "concept C = decltype([]() -> std::true_type { return {}; " 24151 "}())::value &&\n" 24152 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 24153 24154 verifyFormat("template <typename T>\n" 24155 "concept C = true;\n" 24156 "Foo Bar;"); 24157 24158 verifyFormat("template <typename T>\n" 24159 "concept Hashable = requires(T a) {\n" 24160 " { std::hash<T>{}(a) } -> " 24161 "std::convertible_to<std::size_t>;\n" 24162 " };"); 24163 24164 verifyFormat( 24165 "template <typename T>\n" 24166 "concept EqualityComparable = requires(T a, T b) {\n" 24167 " { a == b } -> std::same_as<bool>;\n" 24168 " };"); 24169 24170 verifyFormat( 24171 "template <typename T>\n" 24172 "concept EqualityComparable = requires(T a, T b) {\n" 24173 " { a == b } -> std::same_as<bool>;\n" 24174 " { a != b } -> std::same_as<bool>;\n" 24175 " };"); 24176 24177 verifyFormat("template <typename T>\n" 24178 "concept WeakEqualityComparable = requires(T a, T b) {\n" 24179 " { a == b };\n" 24180 " { a != b };\n" 24181 " };"); 24182 24183 verifyFormat("template <typename T>\n" 24184 "concept HasSizeT = requires { typename T::size_t; };"); 24185 24186 verifyFormat("template <typename T>\n" 24187 "concept Semiregular =\n" 24188 " DefaultConstructible<T> && CopyConstructible<T> && " 24189 "CopyAssignable<T> &&\n" 24190 " requires(T a, std::size_t n) {\n" 24191 " requires Same<T *, decltype(&a)>;\n" 24192 " { a.~T() } noexcept;\n" 24193 " requires Same<T *, decltype(new T)>;\n" 24194 " requires Same<T *, decltype(new T[n])>;\n" 24195 " { delete new T; };\n" 24196 " { delete new T[n]; };\n" 24197 " };"); 24198 24199 verifyFormat("template <typename T>\n" 24200 "concept Semiregular =\n" 24201 " requires(T a, std::size_t n) {\n" 24202 " requires Same<T *, decltype(&a)>;\n" 24203 " { a.~T() } noexcept;\n" 24204 " requires Same<T *, decltype(new T)>;\n" 24205 " requires Same<T *, decltype(new T[n])>;\n" 24206 " { delete new T; };\n" 24207 " { delete new T[n]; };\n" 24208 " { new T } -> std::same_as<T *>;\n" 24209 " } && DefaultConstructible<T> && CopyConstructible<T> && " 24210 "CopyAssignable<T>;"); 24211 24212 verifyFormat( 24213 "template <typename T>\n" 24214 "concept Semiregular =\n" 24215 " DefaultConstructible<T> && requires(T a, std::size_t n) {\n" 24216 " requires Same<T *, decltype(&a)>;\n" 24217 " { a.~T() } noexcept;\n" 24218 " requires Same<T *, decltype(new T)>;\n" 24219 " requires Same<T *, decltype(new " 24220 "T[n])>;\n" 24221 " { delete new T; };\n" 24222 " { delete new T[n]; };\n" 24223 " } && CopyConstructible<T> && " 24224 "CopyAssignable<T>;"); 24225 24226 verifyFormat("template <typename T>\n" 24227 "concept Two = requires(T t) {\n" 24228 " { t.foo() } -> std::same_as<Bar>;\n" 24229 " } && requires(T &&t) {\n" 24230 " { t.foo() } -> std::same_as<Bar &&>;\n" 24231 " };"); 24232 24233 verifyFormat( 24234 "template <typename T>\n" 24235 "concept C = requires(T x) {\n" 24236 " { *x } -> std::convertible_to<typename T::inner>;\n" 24237 " { x + 1 } noexcept -> std::same_as<int>;\n" 24238 " { x * 1 } -> std::convertible_to<T>;\n" 24239 " };"); 24240 24241 verifyFormat( 24242 "template <typename T, typename U = T>\n" 24243 "concept Swappable = requires(T &&t, U &&u) {\n" 24244 " swap(std::forward<T>(t), std::forward<U>(u));\n" 24245 " swap(std::forward<U>(u), std::forward<T>(t));\n" 24246 " };"); 24247 24248 verifyFormat("template <typename T, typename U>\n" 24249 "concept Common = requires(T &&t, U &&u) {\n" 24250 " typename CommonType<T, U>;\n" 24251 " { CommonType<T, U>(std::forward<T>(t)) };\n" 24252 " };"); 24253 24254 verifyFormat("template <typename T, typename U>\n" 24255 "concept Common = requires(T &&t, U &&u) {\n" 24256 " typename CommonType<T, U>;\n" 24257 " { CommonType<T, U>{std::forward<T>(t)} };\n" 24258 " };"); 24259 24260 verifyFormat( 24261 "template <typename T>\n" 24262 "concept C = requires(T t) {\n" 24263 " requires Bar<T> && Foo<T>;\n" 24264 " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n" 24265 " };"); 24266 24267 verifyFormat("template <typename T>\n" 24268 "concept HasFoo = requires(T t) {\n" 24269 " { t.foo() };\n" 24270 " t.foo();\n" 24271 " };\n" 24272 "template <typename T>\n" 24273 "concept HasBar = requires(T t) {\n" 24274 " { t.bar() };\n" 24275 " t.bar();\n" 24276 " };"); 24277 24278 verifyFormat("template <typename T>\n" 24279 "concept Large = sizeof(T) > 10;"); 24280 24281 verifyFormat("template <typename T, typename U>\n" 24282 "concept FooableWith = requires(T t, U u) {\n" 24283 " typename T::foo_type;\n" 24284 " { t.foo(u) } -> typename T::foo_type;\n" 24285 " t++;\n" 24286 " };\n" 24287 "void doFoo(FooableWith<int> auto t) { t.foo(3); }"); 24288 24289 verifyFormat("template <typename T>\n" 24290 "concept Context = is_specialization_of_v<context, T>;"); 24291 24292 verifyFormat("template <typename T>\n" 24293 "concept Node = std::is_object_v<T>;"); 24294 24295 verifyFormat("template <class T>\n" 24296 "concept integral = __is_integral(T);"); 24297 24298 verifyFormat("template <class T>\n" 24299 "concept is2D = __array_extent(T, 1) == 2;"); 24300 24301 verifyFormat("template <class T>\n" 24302 "concept isRhs = __is_rvalue_expr(std::declval<T>() + 2)"); 24303 24304 verifyFormat("template <class T, class T2>\n" 24305 "concept Same = __is_same_as<T, T2>;"); 24306 24307 verifyFormat( 24308 "template <class _InIt, class _OutIt>\n" 24309 "concept _Can_reread_dest =\n" 24310 " std::forward_iterator<_OutIt> &&\n" 24311 " std::same_as<std::iter_value_t<_InIt>, std::iter_value_t<_OutIt>>;"); 24312 24313 auto Style = getLLVMStyle(); 24314 Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Allowed; 24315 24316 verifyFormat( 24317 "template <typename T>\n" 24318 "concept C = requires(T t) {\n" 24319 " requires Bar<T> && Foo<T>;\n" 24320 " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n" 24321 " };", 24322 Style); 24323 24324 verifyFormat("template <typename T>\n" 24325 "concept HasFoo = requires(T t) {\n" 24326 " { t.foo() };\n" 24327 " t.foo();\n" 24328 " };\n" 24329 "template <typename T>\n" 24330 "concept HasBar = requires(T t) {\n" 24331 " { t.bar() };\n" 24332 " t.bar();\n" 24333 " };", 24334 Style); 24335 24336 verifyFormat("template <typename T> concept True = true;", Style); 24337 24338 verifyFormat("template <typename T>\n" 24339 "concept C = decltype([]() -> std::true_type { return {}; " 24340 "}())::value &&\n" 24341 " requires(T t) { t.bar(); } && sizeof(T) <= 8;", 24342 Style); 24343 24344 verifyFormat("template <typename T>\n" 24345 "concept Semiregular =\n" 24346 " DefaultConstructible<T> && CopyConstructible<T> && " 24347 "CopyAssignable<T> &&\n" 24348 " requires(T a, std::size_t n) {\n" 24349 " requires Same<T *, decltype(&a)>;\n" 24350 " { a.~T() } noexcept;\n" 24351 " requires Same<T *, decltype(new T)>;\n" 24352 " requires Same<T *, decltype(new T[n])>;\n" 24353 " { delete new T; };\n" 24354 " { delete new T[n]; };\n" 24355 " };", 24356 Style); 24357 24358 Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Never; 24359 24360 verifyFormat("template <typename T> concept C =\n" 24361 " requires(T t) {\n" 24362 " requires Bar<T> && Foo<T>;\n" 24363 " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n" 24364 " };", 24365 Style); 24366 24367 verifyFormat("template <typename T> concept HasFoo = requires(T t) {\n" 24368 " { t.foo() };\n" 24369 " t.foo();\n" 24370 " };\n" 24371 "template <typename T> concept HasBar = requires(T t) {\n" 24372 " { t.bar() };\n" 24373 " t.bar();\n" 24374 " };", 24375 Style); 24376 24377 verifyFormat("template <typename T> concept True = true;", Style); 24378 24379 verifyFormat( 24380 "template <typename T> concept C = decltype([]() -> std::true_type {\n" 24381 " return {};\n" 24382 " }())::value &&\n" 24383 " requires(T t) { t.bar(); } && " 24384 "sizeof(T) <= 8;", 24385 Style); 24386 24387 verifyFormat("template <typename T> concept Semiregular =\n" 24388 " DefaultConstructible<T> && CopyConstructible<T> && " 24389 "CopyAssignable<T> &&\n" 24390 " requires(T a, std::size_t n) {\n" 24391 " requires Same<T *, decltype(&a)>;\n" 24392 " { a.~T() } noexcept;\n" 24393 " requires Same<T *, decltype(new T)>;\n" 24394 " requires Same<T *, decltype(new T[n])>;\n" 24395 " { delete new T; };\n" 24396 " { delete new T[n]; };\n" 24397 " };", 24398 Style); 24399 24400 // The following tests are invalid C++, we just want to make sure we don't 24401 // assert. 24402 verifyFormat("template <typename T>\n" 24403 "concept C = requires C2<T>;"); 24404 24405 verifyFormat("template <typename T>\n" 24406 "concept C = 5 + 4;"); 24407 24408 verifyFormat("template <typename T>\n" 24409 "concept C =\n" 24410 "class X;"); 24411 24412 verifyFormat("template <typename T>\n" 24413 "concept C = [] && true;"); 24414 24415 verifyFormat("template <typename T>\n" 24416 "concept C = [] && requires(T t) { typename T::size_type; };"); 24417 } 24418 24419 TEST_F(FormatTest, RequiresClausesPositions) { 24420 auto Style = getLLVMStyle(); 24421 EXPECT_EQ(Style.RequiresClausePosition, FormatStyle::RCPS_OwnLine); 24422 EXPECT_EQ(Style.IndentRequiresClause, true); 24423 24424 verifyFormat("template <typename T>\n" 24425 " requires(Foo<T> && std::trait<T>)\n" 24426 "struct Bar;", 24427 Style); 24428 24429 verifyFormat("template <typename T>\n" 24430 " requires(Foo<T> && std::trait<T>)\n" 24431 "class Bar {\n" 24432 "public:\n" 24433 " Bar(T t);\n" 24434 " bool baz();\n" 24435 "};", 24436 Style); 24437 24438 verifyFormat( 24439 "template <typename T>\n" 24440 " requires requires(T &&t) {\n" 24441 " typename T::I;\n" 24442 " requires(F<typename T::I> && std::trait<typename T::I>);\n" 24443 " }\n" 24444 "Bar(T) -> Bar<typename T::I>;", 24445 Style); 24446 24447 verifyFormat("template <typename T>\n" 24448 " requires(Foo<T> && std::trait<T>)\n" 24449 "constexpr T MyGlobal;", 24450 Style); 24451 24452 verifyFormat("template <typename T>\n" 24453 " requires Foo<T> && requires(T t) {\n" 24454 " { t.baz() } -> std::same_as<bool>;\n" 24455 " requires std::same_as<T::Factor, int>;\n" 24456 " }\n" 24457 "inline int bar(T t) {\n" 24458 " return t.baz() ? T::Factor : 5;\n" 24459 "}", 24460 Style); 24461 24462 verifyFormat("template <typename T>\n" 24463 "inline int bar(T t)\n" 24464 " requires Foo<T> && requires(T t) {\n" 24465 " { t.baz() } -> std::same_as<bool>;\n" 24466 " requires std::same_as<T::Factor, int>;\n" 24467 " }\n" 24468 "{\n" 24469 " return t.baz() ? T::Factor : 5;\n" 24470 "}", 24471 Style); 24472 24473 verifyFormat("template <typename T>\n" 24474 " requires F<T>\n" 24475 "int bar(T t) {\n" 24476 " return 5;\n" 24477 "}", 24478 Style); 24479 24480 verifyFormat("template <typename T>\n" 24481 "int bar(T t)\n" 24482 " requires F<T>\n" 24483 "{\n" 24484 " return 5;\n" 24485 "}", 24486 Style); 24487 24488 verifyFormat("template <typename T>\n" 24489 "int bar(T t)\n" 24490 " requires F<T>;", 24491 Style); 24492 24493 Style.IndentRequiresClause = false; 24494 verifyFormat("template <typename T>\n" 24495 "requires F<T>\n" 24496 "int bar(T t) {\n" 24497 " return 5;\n" 24498 "}", 24499 Style); 24500 24501 verifyFormat("template <typename T>\n" 24502 "int bar(T t)\n" 24503 "requires F<T>\n" 24504 "{\n" 24505 " return 5;\n" 24506 "}", 24507 Style); 24508 24509 Style.RequiresClausePosition = FormatStyle::RCPS_SingleLine; 24510 verifyFormat("template <typename T> requires Foo<T> struct Bar {};\n" 24511 "template <typename T> requires Foo<T> void bar() {}\n" 24512 "template <typename T> void bar() requires Foo<T> {}\n" 24513 "template <typename T> void bar() requires Foo<T>;\n" 24514 "template <typename T> requires Foo<T> Bar(T) -> Bar<T>;", 24515 Style); 24516 24517 auto ColumnStyle = Style; 24518 ColumnStyle.ColumnLimit = 40; 24519 verifyFormat("template <typename AAAAAAA>\n" 24520 "requires Foo<T> struct Bar {};\n" 24521 "template <typename AAAAAAA>\n" 24522 "requires Foo<T> void bar() {}\n" 24523 "template <typename AAAAAAA>\n" 24524 "void bar() requires Foo<T> {}\n" 24525 "template <typename AAAAAAA>\n" 24526 "requires Foo<T> Baz(T) -> Baz<T>;", 24527 ColumnStyle); 24528 24529 verifyFormat("template <typename T>\n" 24530 "requires Foo<AAAAAAA> struct Bar {};\n" 24531 "template <typename T>\n" 24532 "requires Foo<AAAAAAA> void bar() {}\n" 24533 "template <typename T>\n" 24534 "void bar() requires Foo<AAAAAAA> {}\n" 24535 "template <typename T>\n" 24536 "requires Foo<AAAAAAA> Bar(T) -> Bar<T>;", 24537 ColumnStyle); 24538 24539 verifyFormat("template <typename AAAAAAA>\n" 24540 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24541 "struct Bar {};\n" 24542 "template <typename AAAAAAA>\n" 24543 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24544 "void bar() {}\n" 24545 "template <typename AAAAAAA>\n" 24546 "void bar()\n" 24547 " requires Foo<AAAAAAAAAAAAAAAA> {}\n" 24548 "template <typename AAAAAAA>\n" 24549 "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n" 24550 "template <typename AAAAAAA>\n" 24551 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24552 "Bar(T) -> Bar<T>;", 24553 ColumnStyle); 24554 24555 Style.RequiresClausePosition = FormatStyle::RCPS_WithFollowing; 24556 ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithFollowing; 24557 24558 verifyFormat("template <typename T>\n" 24559 "requires Foo<T> struct Bar {};\n" 24560 "template <typename T>\n" 24561 "requires Foo<T> void bar() {}\n" 24562 "template <typename T>\n" 24563 "void bar()\n" 24564 "requires Foo<T> {}\n" 24565 "template <typename T>\n" 24566 "void bar()\n" 24567 "requires Foo<T>;\n" 24568 "template <typename T>\n" 24569 "requires Foo<T> Bar(T) -> Bar<T>;", 24570 Style); 24571 24572 verifyFormat("template <typename AAAAAAA>\n" 24573 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24574 "struct Bar {};\n" 24575 "template <typename AAAAAAA>\n" 24576 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24577 "void bar() {}\n" 24578 "template <typename AAAAAAA>\n" 24579 "void bar()\n" 24580 "requires Foo<AAAAAAAAAAAAAAAA> {}\n" 24581 "template <typename AAAAAAA>\n" 24582 "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n" 24583 "template <typename AAAAAAA>\n" 24584 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24585 "Bar(T) -> Bar<T>;", 24586 ColumnStyle); 24587 24588 Style.IndentRequiresClause = true; 24589 ColumnStyle.IndentRequiresClause = true; 24590 24591 verifyFormat("template <typename T>\n" 24592 " requires Foo<T> struct Bar {};\n" 24593 "template <typename T>\n" 24594 " requires Foo<T> void bar() {}\n" 24595 "template <typename T>\n" 24596 "void bar()\n" 24597 " requires Foo<T> {}\n" 24598 "template <typename T>\n" 24599 " requires Foo<T> Bar(T) -> Bar<T>;", 24600 Style); 24601 24602 verifyFormat("template <typename AAAAAAA>\n" 24603 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24604 "struct Bar {};\n" 24605 "template <typename AAAAAAA>\n" 24606 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24607 "void bar() {}\n" 24608 "template <typename AAAAAAA>\n" 24609 "void bar()\n" 24610 " requires Foo<AAAAAAAAAAAAAAAA> {}\n" 24611 "template <typename AAAAAAA>\n" 24612 " requires Foo<AAAAAA> Bar(T) -> Bar<T>;\n" 24613 "template <typename AAAAAAA>\n" 24614 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24615 "Bar(T) -> Bar<T>;", 24616 ColumnStyle); 24617 24618 Style.RequiresClausePosition = FormatStyle::RCPS_WithPreceding; 24619 ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithPreceding; 24620 24621 verifyFormat("template <typename T> requires Foo<T>\n" 24622 "struct Bar {};\n" 24623 "template <typename T> requires Foo<T>\n" 24624 "void bar() {}\n" 24625 "template <typename T>\n" 24626 "void bar() requires Foo<T>\n" 24627 "{}\n" 24628 "template <typename T> void bar() requires Foo<T>;\n" 24629 "template <typename T> requires Foo<T>\n" 24630 "Bar(T) -> Bar<T>;", 24631 Style); 24632 24633 verifyFormat("template <typename AAAAAAA>\n" 24634 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24635 "struct Bar {};\n" 24636 "template <typename AAAAAAA>\n" 24637 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24638 "void bar() {}\n" 24639 "template <typename AAAAAAA>\n" 24640 "void bar()\n" 24641 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24642 "{}\n" 24643 "template <typename AAAAAAA>\n" 24644 "requires Foo<AAAAAAAA>\n" 24645 "Bar(T) -> Bar<T>;\n" 24646 "template <typename AAAAAAA>\n" 24647 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24648 "Bar(T) -> Bar<T>;", 24649 ColumnStyle); 24650 } 24651 24652 TEST_F(FormatTest, RequiresClauses) { 24653 verifyFormat("struct [[nodiscard]] zero_t {\n" 24654 " template <class T>\n" 24655 " requires requires { number_zero_v<T>; }\n" 24656 " [[nodiscard]] constexpr operator T() const {\n" 24657 " return number_zero_v<T>;\n" 24658 " }\n" 24659 "};"); 24660 24661 auto Style = getLLVMStyle(); 24662 24663 verifyFormat( 24664 "template <typename T>\n" 24665 " requires is_default_constructible_v<hash<T>> and\n" 24666 " is_copy_constructible_v<hash<T>> and\n" 24667 " is_move_constructible_v<hash<T>> and\n" 24668 " is_copy_assignable_v<hash<T>> and " 24669 "is_move_assignable_v<hash<T>> and\n" 24670 " is_destructible_v<hash<T>> and is_swappable_v<hash<T>> and\n" 24671 " is_callable_v<hash<T>(T)> and\n" 24672 " is_same_v<size_t, decltype(hash<T>(declval<T>()))> and\n" 24673 " is_same_v<size_t, decltype(hash<T>(declval<T &>()))> and\n" 24674 " is_same_v<size_t, decltype(hash<T>(declval<const T &>()))>\n" 24675 "struct S {};", 24676 Style); 24677 24678 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 24679 verifyFormat( 24680 "template <typename T>\n" 24681 " requires is_default_constructible_v<hash<T>>\n" 24682 " and is_copy_constructible_v<hash<T>>\n" 24683 " and is_move_constructible_v<hash<T>>\n" 24684 " and is_copy_assignable_v<hash<T>> and " 24685 "is_move_assignable_v<hash<T>>\n" 24686 " and is_destructible_v<hash<T>> and is_swappable_v<hash<T>>\n" 24687 " and is_callable_v<hash<T>(T)>\n" 24688 " and is_same_v<size_t, decltype(hash<T>(declval<T>()))>\n" 24689 " and is_same_v<size_t, decltype(hash<T>(declval<T &>()))>\n" 24690 " and is_same_v<size_t, decltype(hash<T>(declval<const T " 24691 "&>()))>\n" 24692 "struct S {};", 24693 Style); 24694 24695 // Not a clause, but we once hit an assert. 24696 verifyFormat("#if 0\n" 24697 "#else\n" 24698 "foo();\n" 24699 "#endif\n" 24700 "bar(requires);"); 24701 } 24702 24703 TEST_F(FormatTest, StatementAttributeLikeMacros) { 24704 FormatStyle Style = getLLVMStyle(); 24705 StringRef Source = "void Foo::slot() {\n" 24706 " unsigned char MyChar = 'x';\n" 24707 " emit signal(MyChar);\n" 24708 " Q_EMIT signal(MyChar);\n" 24709 "}"; 24710 24711 EXPECT_EQ(Source, format(Source, Style)); 24712 24713 Style.AlignConsecutiveDeclarations.Enabled = true; 24714 EXPECT_EQ("void Foo::slot() {\n" 24715 " unsigned char MyChar = 'x';\n" 24716 " emit signal(MyChar);\n" 24717 " Q_EMIT signal(MyChar);\n" 24718 "}", 24719 format(Source, Style)); 24720 24721 Style.StatementAttributeLikeMacros.push_back("emit"); 24722 EXPECT_EQ(Source, format(Source, Style)); 24723 24724 Style.StatementAttributeLikeMacros = {}; 24725 EXPECT_EQ("void Foo::slot() {\n" 24726 " unsigned char MyChar = 'x';\n" 24727 " emit signal(MyChar);\n" 24728 " Q_EMIT signal(MyChar);\n" 24729 "}", 24730 format(Source, Style)); 24731 } 24732 24733 TEST_F(FormatTest, IndentAccessModifiers) { 24734 FormatStyle Style = getLLVMStyle(); 24735 Style.IndentAccessModifiers = true; 24736 // Members are *two* levels below the record; 24737 // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation. 24738 verifyFormat("class C {\n" 24739 " int i;\n" 24740 "};\n", 24741 Style); 24742 verifyFormat("union C {\n" 24743 " int i;\n" 24744 " unsigned u;\n" 24745 "};\n", 24746 Style); 24747 // Access modifiers should be indented one level below the record. 24748 verifyFormat("class C {\n" 24749 " public:\n" 24750 " int i;\n" 24751 "};\n", 24752 Style); 24753 verifyFormat("struct S {\n" 24754 " private:\n" 24755 " class C {\n" 24756 " int j;\n" 24757 "\n" 24758 " public:\n" 24759 " C();\n" 24760 " };\n" 24761 "\n" 24762 " public:\n" 24763 " int i;\n" 24764 "};\n", 24765 Style); 24766 // Enumerations are not records and should be unaffected. 24767 Style.AllowShortEnumsOnASingleLine = false; 24768 verifyFormat("enum class E {\n" 24769 " A,\n" 24770 " B\n" 24771 "};\n", 24772 Style); 24773 // Test with a different indentation width; 24774 // also proves that the result is Style.AccessModifierOffset agnostic. 24775 Style.IndentWidth = 3; 24776 verifyFormat("class C {\n" 24777 " public:\n" 24778 " int i;\n" 24779 "};\n", 24780 Style); 24781 } 24782 24783 TEST_F(FormatTest, LimitlessStringsAndComments) { 24784 auto Style = getLLVMStyleWithColumns(0); 24785 constexpr StringRef Code = 24786 "/**\n" 24787 " * This is a multiline comment with quite some long lines, at least for " 24788 "the LLVM Style.\n" 24789 " * We will redo this with strings and line comments. Just to check if " 24790 "everything is working.\n" 24791 " */\n" 24792 "bool foo() {\n" 24793 " /* Single line multi line comment. */\n" 24794 " const std::string String = \"This is a multiline string with quite " 24795 "some long lines, at least for the LLVM Style.\"\n" 24796 " \"We already did it with multi line " 24797 "comments, and we will do it with line comments. Just to check if " 24798 "everything is working.\";\n" 24799 " // This is a line comment (block) with quite some long lines, at " 24800 "least for the LLVM Style.\n" 24801 " // We already did this with multi line comments and strings. Just to " 24802 "check if everything is working.\n" 24803 " const std::string SmallString = \"Hello World\";\n" 24804 " // Small line comment\n" 24805 " return String.size() > SmallString.size();\n" 24806 "}"; 24807 EXPECT_EQ(Code, format(Code, Style)); 24808 } 24809 24810 TEST_F(FormatTest, FormatDecayCopy) { 24811 // error cases from unit tests 24812 verifyFormat("foo(auto())"); 24813 verifyFormat("foo(auto{})"); 24814 verifyFormat("foo(auto({}))"); 24815 verifyFormat("foo(auto{{}})"); 24816 24817 verifyFormat("foo(auto(1))"); 24818 verifyFormat("foo(auto{1})"); 24819 verifyFormat("foo(new auto(1))"); 24820 verifyFormat("foo(new auto{1})"); 24821 verifyFormat("decltype(auto(1)) x;"); 24822 verifyFormat("decltype(auto{1}) x;"); 24823 verifyFormat("auto(x);"); 24824 verifyFormat("auto{x};"); 24825 verifyFormat("new auto{x};"); 24826 verifyFormat("auto{x} = y;"); 24827 verifyFormat("auto(x) = y;"); // actually a declaration, but this is clearly 24828 // the user's own fault 24829 verifyFormat("integral auto(x) = y;"); // actually a declaration, but this is 24830 // clearly the user's own fault 24831 verifyFormat("auto(*p)() = f;"); // actually a declaration; TODO FIXME 24832 } 24833 24834 TEST_F(FormatTest, Cpp20ModulesSupport) { 24835 FormatStyle Style = getLLVMStyle(); 24836 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 24837 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 24838 24839 verifyFormat("export import foo;", Style); 24840 verifyFormat("export import foo:bar;", Style); 24841 verifyFormat("export import foo.bar;", Style); 24842 verifyFormat("export import foo.bar:baz;", Style); 24843 verifyFormat("export import :bar;", Style); 24844 verifyFormat("export module foo:bar;", Style); 24845 verifyFormat("export module foo;", Style); 24846 verifyFormat("export module foo.bar;", Style); 24847 verifyFormat("export module foo.bar:baz;", Style); 24848 verifyFormat("export import <string_view>;", Style); 24849 24850 verifyFormat("export type_name var;", Style); 24851 verifyFormat("template <class T> export using A = B<T>;", Style); 24852 verifyFormat("export using A = B;", Style); 24853 verifyFormat("export int func() {\n" 24854 " foo();\n" 24855 "}", 24856 Style); 24857 verifyFormat("export struct {\n" 24858 " int foo;\n" 24859 "};", 24860 Style); 24861 verifyFormat("export {\n" 24862 " int foo;\n" 24863 "};", 24864 Style); 24865 verifyFormat("export export char const *hello() { return \"hello\"; }"); 24866 24867 verifyFormat("import bar;", Style); 24868 verifyFormat("import foo.bar;", Style); 24869 verifyFormat("import foo:bar;", Style); 24870 verifyFormat("import :bar;", Style); 24871 verifyFormat("import <ctime>;", Style); 24872 verifyFormat("import \"header\";", Style); 24873 24874 verifyFormat("module foo;", Style); 24875 verifyFormat("module foo:bar;", Style); 24876 verifyFormat("module foo.bar;", Style); 24877 verifyFormat("module;", Style); 24878 24879 verifyFormat("export namespace hi {\n" 24880 "const char *sayhi();\n" 24881 "}", 24882 Style); 24883 24884 verifyFormat("module :private;", Style); 24885 verifyFormat("import <foo/bar.h>;", Style); 24886 verifyFormat("import foo...bar;", Style); 24887 verifyFormat("import ..........;", Style); 24888 verifyFormat("module foo:private;", Style); 24889 verifyFormat("import a", Style); 24890 verifyFormat("module a", Style); 24891 verifyFormat("export import a", Style); 24892 verifyFormat("export module a", Style); 24893 24894 verifyFormat("import", Style); 24895 verifyFormat("module", Style); 24896 verifyFormat("export", Style); 24897 } 24898 24899 TEST_F(FormatTest, CoroutineForCoawait) { 24900 FormatStyle Style = getLLVMStyle(); 24901 verifyFormat("for co_await (auto x : range())\n ;"); 24902 verifyFormat("for (auto i : arr) {\n" 24903 "}", 24904 Style); 24905 verifyFormat("for co_await (auto i : arr) {\n" 24906 "}", 24907 Style); 24908 verifyFormat("for co_await (auto i : foo(T{})) {\n" 24909 "}", 24910 Style); 24911 } 24912 24913 TEST_F(FormatTest, CoroutineCoAwait) { 24914 verifyFormat("int x = co_await foo();"); 24915 verifyFormat("int x = (co_await foo());"); 24916 verifyFormat("co_await (42);"); 24917 verifyFormat("void operator co_await(int);"); 24918 verifyFormat("void operator co_await(a);"); 24919 verifyFormat("co_await a;"); 24920 verifyFormat("co_await missing_await_resume{};"); 24921 verifyFormat("co_await a; // comment"); 24922 verifyFormat("void test0() { co_await a; }"); 24923 verifyFormat("co_await co_await co_await foo();"); 24924 verifyFormat("co_await foo().bar();"); 24925 verifyFormat("co_await [this]() -> Task { co_return x; }"); 24926 verifyFormat("co_await [this](int a, int b) -> Task { co_return co_await " 24927 "foo(); }(x, y);"); 24928 24929 FormatStyle Style = getLLVMStyleWithColumns(40); 24930 verifyFormat("co_await [this](int a, int b) -> Task {\n" 24931 " co_return co_await foo();\n" 24932 "}(x, y);", 24933 Style); 24934 verifyFormat("co_await;"); 24935 } 24936 24937 TEST_F(FormatTest, CoroutineCoYield) { 24938 verifyFormat("int x = co_yield foo();"); 24939 verifyFormat("int x = (co_yield foo());"); 24940 verifyFormat("co_yield (42);"); 24941 verifyFormat("co_yield {42};"); 24942 verifyFormat("co_yield 42;"); 24943 verifyFormat("co_yield n++;"); 24944 verifyFormat("co_yield ++n;"); 24945 verifyFormat("co_yield;"); 24946 } 24947 24948 TEST_F(FormatTest, CoroutineCoReturn) { 24949 verifyFormat("co_return (42);"); 24950 verifyFormat("co_return;"); 24951 verifyFormat("co_return {};"); 24952 verifyFormat("co_return x;"); 24953 verifyFormat("co_return co_await foo();"); 24954 verifyFormat("co_return co_yield foo();"); 24955 } 24956 24957 TEST_F(FormatTest, EmptyShortBlock) { 24958 auto Style = getLLVMStyle(); 24959 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 24960 24961 verifyFormat("try {\n" 24962 " doA();\n" 24963 "} catch (Exception &e) {\n" 24964 " e.printStackTrace();\n" 24965 "}\n", 24966 Style); 24967 24968 verifyFormat("try {\n" 24969 " doA();\n" 24970 "} catch (Exception &e) {}\n", 24971 Style); 24972 } 24973 24974 TEST_F(FormatTest, ShortTemplatedArgumentLists) { 24975 auto Style = getLLVMStyle(); 24976 24977 verifyFormat("template <> struct S : Template<int (*)[]> {};\n", Style); 24978 verifyFormat("template <> struct S : Template<int (*)[10]> {};\n", Style); 24979 verifyFormat("struct Y : X<[] { return 0; }> {};", Style); 24980 verifyFormat("struct Y<[] { return 0; }> {};", Style); 24981 24982 verifyFormat("struct Z : X<decltype([] { return 0; }){}> {};", Style); 24983 verifyFormat("template <int N> struct Foo<char[N]> {};", Style); 24984 } 24985 24986 TEST_F(FormatTest, InsertBraces) { 24987 FormatStyle Style = getLLVMStyle(); 24988 Style.InsertBraces = true; 24989 24990 verifyFormat("// clang-format off\n" 24991 "// comment\n" 24992 "if (a) f();\n" 24993 "// clang-format on\n" 24994 "if (b) {\n" 24995 " g();\n" 24996 "}", 24997 "// clang-format off\n" 24998 "// comment\n" 24999 "if (a) f();\n" 25000 "// clang-format on\n" 25001 "if (b) g();", 25002 Style); 25003 25004 verifyFormat("if (a) {\n" 25005 " switch (b) {\n" 25006 " case 1:\n" 25007 " c = 0;\n" 25008 " break;\n" 25009 " default:\n" 25010 " c = 1;\n" 25011 " }\n" 25012 "}", 25013 "if (a)\n" 25014 " switch (b) {\n" 25015 " case 1:\n" 25016 " c = 0;\n" 25017 " break;\n" 25018 " default:\n" 25019 " c = 1;\n" 25020 " }", 25021 Style); 25022 25023 verifyFormat("for (auto node : nodes) {\n" 25024 " if (node) {\n" 25025 " break;\n" 25026 " }\n" 25027 "}", 25028 "for (auto node : nodes)\n" 25029 " if (node)\n" 25030 " break;", 25031 Style); 25032 25033 verifyFormat("for (auto node : nodes) {\n" 25034 " if (node)\n" 25035 "}", 25036 "for (auto node : nodes)\n" 25037 " if (node)", 25038 Style); 25039 25040 verifyFormat("do {\n" 25041 " --a;\n" 25042 "} while (a);", 25043 "do\n" 25044 " --a;\n" 25045 "while (a);", 25046 Style); 25047 25048 verifyFormat("if (i) {\n" 25049 " ++i;\n" 25050 "} else {\n" 25051 " --i;\n" 25052 "}", 25053 "if (i)\n" 25054 " ++i;\n" 25055 "else {\n" 25056 " --i;\n" 25057 "}", 25058 Style); 25059 25060 verifyFormat("void f() {\n" 25061 " while (j--) {\n" 25062 " while (i) {\n" 25063 " --i;\n" 25064 " }\n" 25065 " }\n" 25066 "}", 25067 "void f() {\n" 25068 " while (j--)\n" 25069 " while (i)\n" 25070 " --i;\n" 25071 "}", 25072 Style); 25073 25074 verifyFormat("f({\n" 25075 " if (a) {\n" 25076 " g();\n" 25077 " }\n" 25078 "});", 25079 "f({\n" 25080 " if (a)\n" 25081 " g();\n" 25082 "});", 25083 Style); 25084 25085 verifyFormat("if (a) {\n" 25086 " f();\n" 25087 "} else if (b) {\n" 25088 " g();\n" 25089 "} else {\n" 25090 " h();\n" 25091 "}", 25092 "if (a)\n" 25093 " f();\n" 25094 "else if (b)\n" 25095 " g();\n" 25096 "else\n" 25097 " h();", 25098 Style); 25099 25100 verifyFormat("if (a) {\n" 25101 " f();\n" 25102 "}\n" 25103 "// comment\n" 25104 "/* comment */", 25105 "if (a)\n" 25106 " f();\n" 25107 "// comment\n" 25108 "/* comment */", 25109 Style); 25110 25111 verifyFormat("if (a) {\n" 25112 " // foo\n" 25113 " // bar\n" 25114 " f();\n" 25115 "}", 25116 "if (a)\n" 25117 " // foo\n" 25118 " // bar\n" 25119 " f();", 25120 Style); 25121 25122 verifyFormat("if (a) { // comment\n" 25123 " // comment\n" 25124 " f();\n" 25125 "}", 25126 "if (a) // comment\n" 25127 " // comment\n" 25128 " f();", 25129 Style); 25130 25131 verifyFormat("if (a) {\n" 25132 " f(); // comment\n" 25133 "}", 25134 "if (a)\n" 25135 " f(); // comment", 25136 Style); 25137 25138 verifyFormat("if (a) {\n" 25139 " f();\n" 25140 "}\n" 25141 "#undef A\n" 25142 "#undef B", 25143 "if (a)\n" 25144 " f();\n" 25145 "#undef A\n" 25146 "#undef B", 25147 Style); 25148 25149 verifyFormat("if (a)\n" 25150 "#ifdef A\n" 25151 " f();\n" 25152 "#else\n" 25153 " g();\n" 25154 "#endif", 25155 Style); 25156 25157 verifyFormat("#if 0\n" 25158 "#elif 1\n" 25159 "#endif\n" 25160 "void f() {\n" 25161 " if (a) {\n" 25162 " g();\n" 25163 " }\n" 25164 "}", 25165 "#if 0\n" 25166 "#elif 1\n" 25167 "#endif\n" 25168 "void f() {\n" 25169 " if (a) g();\n" 25170 "}", 25171 Style); 25172 25173 Style.ColumnLimit = 15; 25174 25175 verifyFormat("#define A \\\n" 25176 " if (a) \\\n" 25177 " f();", 25178 Style); 25179 25180 verifyFormat("if (a + b >\n" 25181 " c) {\n" 25182 " f();\n" 25183 "}", 25184 "if (a + b > c)\n" 25185 " f();", 25186 Style); 25187 } 25188 25189 TEST_F(FormatTest, RemoveBraces) { 25190 FormatStyle Style = getLLVMStyle(); 25191 Style.RemoveBracesLLVM = true; 25192 25193 // The following test cases are fully-braced versions of the examples at 25194 // "llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single- 25195 // statement-bodies-of-if-else-loop-statements". 25196 25197 // Omit the braces since the body is simple and clearly associated with the 25198 // `if`. 25199 verifyFormat("if (isa<FunctionDecl>(D))\n" 25200 " handleFunctionDecl(D);\n" 25201 "else if (isa<VarDecl>(D))\n" 25202 " handleVarDecl(D);", 25203 "if (isa<FunctionDecl>(D)) {\n" 25204 " handleFunctionDecl(D);\n" 25205 "} else if (isa<VarDecl>(D)) {\n" 25206 " handleVarDecl(D);\n" 25207 "}", 25208 Style); 25209 25210 // Here we document the condition itself and not the body. 25211 verifyFormat("if (isa<VarDecl>(D)) {\n" 25212 " // It is necessary that we explain the situation with this\n" 25213 " // surprisingly long comment, so it would be unclear\n" 25214 " // without the braces whether the following statement is in\n" 25215 " // the scope of the `if`.\n" 25216 " // Because the condition is documented, we can't really\n" 25217 " // hoist this comment that applies to the body above the\n" 25218 " // `if`.\n" 25219 " handleOtherDecl(D);\n" 25220 "}", 25221 Style); 25222 25223 // Use braces on the outer `if` to avoid a potential dangling `else` 25224 // situation. 25225 verifyFormat("if (isa<VarDecl>(D)) {\n" 25226 " if (shouldProcessAttr(A))\n" 25227 " handleAttr(A);\n" 25228 "}", 25229 "if (isa<VarDecl>(D)) {\n" 25230 " if (shouldProcessAttr(A)) {\n" 25231 " handleAttr(A);\n" 25232 " }\n" 25233 "}", 25234 Style); 25235 25236 // Use braces for the `if` block to keep it uniform with the `else` block. 25237 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 25238 " handleFunctionDecl(D);\n" 25239 "} else {\n" 25240 " // In this `else` case, it is necessary that we explain the\n" 25241 " // situation with this surprisingly long comment, so it\n" 25242 " // would be unclear without the braces whether the\n" 25243 " // following statement is in the scope of the `if`.\n" 25244 " handleOtherDecl(D);\n" 25245 "}", 25246 Style); 25247 25248 // This should also omit braces. The `for` loop contains only a single 25249 // statement, so it shouldn't have braces. The `if` also only contains a 25250 // single simple statement (the `for` loop), so it also should omit braces. 25251 verifyFormat("if (isa<FunctionDecl>(D))\n" 25252 " for (auto *A : D.attrs())\n" 25253 " handleAttr(A);", 25254 "if (isa<FunctionDecl>(D)) {\n" 25255 " for (auto *A : D.attrs()) {\n" 25256 " handleAttr(A);\n" 25257 " }\n" 25258 "}", 25259 Style); 25260 25261 // Use braces for a `do-while` loop and its enclosing statement. 25262 verifyFormat("if (Tok->is(tok::l_brace)) {\n" 25263 " do {\n" 25264 " Tok = Tok->Next;\n" 25265 " } while (Tok);\n" 25266 "}", 25267 Style); 25268 25269 // Use braces for the outer `if` since the nested `for` is braced. 25270 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 25271 " for (auto *A : D.attrs()) {\n" 25272 " // In this `for` loop body, it is necessary that we\n" 25273 " // explain the situation with this surprisingly long\n" 25274 " // comment, forcing braces on the `for` block.\n" 25275 " handleAttr(A);\n" 25276 " }\n" 25277 "}", 25278 Style); 25279 25280 // Use braces on the outer block because there are more than two levels of 25281 // nesting. 25282 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 25283 " for (auto *A : D.attrs())\n" 25284 " for (ssize_t i : llvm::seq<ssize_t>(count))\n" 25285 " handleAttrOnDecl(D, A, i);\n" 25286 "}", 25287 "if (isa<FunctionDecl>(D)) {\n" 25288 " for (auto *A : D.attrs()) {\n" 25289 " for (ssize_t i : llvm::seq<ssize_t>(count)) {\n" 25290 " handleAttrOnDecl(D, A, i);\n" 25291 " }\n" 25292 " }\n" 25293 "}", 25294 Style); 25295 25296 // Use braces on the outer block because of a nested `if`; otherwise the 25297 // compiler would warn: `add explicit braces to avoid dangling else` 25298 verifyFormat("if (auto *D = dyn_cast<FunctionDecl>(D)) {\n" 25299 " if (shouldProcess(D))\n" 25300 " handleVarDecl(D);\n" 25301 " else\n" 25302 " markAsIgnored(D);\n" 25303 "}", 25304 "if (auto *D = dyn_cast<FunctionDecl>(D)) {\n" 25305 " if (shouldProcess(D)) {\n" 25306 " handleVarDecl(D);\n" 25307 " } else {\n" 25308 " markAsIgnored(D);\n" 25309 " }\n" 25310 "}", 25311 Style); 25312 25313 verifyFormat("// clang-format off\n" 25314 "// comment\n" 25315 "while (i > 0) { --i; }\n" 25316 "// clang-format on\n" 25317 "while (j < 0)\n" 25318 " ++j;", 25319 "// clang-format off\n" 25320 "// comment\n" 25321 "while (i > 0) { --i; }\n" 25322 "// clang-format on\n" 25323 "while (j < 0) { ++j; }", 25324 Style); 25325 25326 verifyFormat("if (a)\n" 25327 " b; // comment\n" 25328 "else if (c)\n" 25329 " d; /* comment */\n" 25330 "else\n" 25331 " e;", 25332 "if (a) {\n" 25333 " b; // comment\n" 25334 "} else if (c) {\n" 25335 " d; /* comment */\n" 25336 "} else {\n" 25337 " e;\n" 25338 "}", 25339 Style); 25340 25341 verifyFormat("if (a) {\n" 25342 " b;\n" 25343 " c;\n" 25344 "} else if (d) {\n" 25345 " e;\n" 25346 "}", 25347 Style); 25348 25349 verifyFormat("if (a) {\n" 25350 "#undef NDEBUG\n" 25351 " b;\n" 25352 "} else {\n" 25353 " c;\n" 25354 "}", 25355 Style); 25356 25357 verifyFormat("if (a) {\n" 25358 " // comment\n" 25359 "} else if (b) {\n" 25360 " c;\n" 25361 "}", 25362 Style); 25363 25364 verifyFormat("if (a) {\n" 25365 " b;\n" 25366 "} else {\n" 25367 " { c; }\n" 25368 "}", 25369 Style); 25370 25371 verifyFormat("if (a) {\n" 25372 " if (b) // comment\n" 25373 " c;\n" 25374 "} else if (d) {\n" 25375 " e;\n" 25376 "}", 25377 "if (a) {\n" 25378 " if (b) { // comment\n" 25379 " c;\n" 25380 " }\n" 25381 "} else if (d) {\n" 25382 " e;\n" 25383 "}", 25384 Style); 25385 25386 verifyFormat("if (a) {\n" 25387 " if (b) {\n" 25388 " c;\n" 25389 " // comment\n" 25390 " } else if (d) {\n" 25391 " e;\n" 25392 " }\n" 25393 "}", 25394 Style); 25395 25396 verifyFormat("if (a) {\n" 25397 " if (b)\n" 25398 " c;\n" 25399 "}", 25400 "if (a) {\n" 25401 " if (b) {\n" 25402 " c;\n" 25403 " }\n" 25404 "}", 25405 Style); 25406 25407 verifyFormat("if (a)\n" 25408 " if (b)\n" 25409 " c;\n" 25410 " else\n" 25411 " d;\n" 25412 "else\n" 25413 " e;", 25414 "if (a) {\n" 25415 " if (b) {\n" 25416 " c;\n" 25417 " } else {\n" 25418 " d;\n" 25419 " }\n" 25420 "} else {\n" 25421 " e;\n" 25422 "}", 25423 Style); 25424 25425 verifyFormat("if (a) {\n" 25426 " // comment\n" 25427 " if (b)\n" 25428 " c;\n" 25429 " else if (d)\n" 25430 " e;\n" 25431 "} else {\n" 25432 " g;\n" 25433 "}", 25434 "if (a) {\n" 25435 " // comment\n" 25436 " if (b) {\n" 25437 " c;\n" 25438 " } else if (d) {\n" 25439 " e;\n" 25440 " }\n" 25441 "} else {\n" 25442 " g;\n" 25443 "}", 25444 Style); 25445 25446 verifyFormat("if (a)\n" 25447 " b;\n" 25448 "else if (c)\n" 25449 " d;\n" 25450 "else\n" 25451 " e;", 25452 "if (a) {\n" 25453 " b;\n" 25454 "} else {\n" 25455 " if (c) {\n" 25456 " d;\n" 25457 " } else {\n" 25458 " e;\n" 25459 " }\n" 25460 "}", 25461 Style); 25462 25463 verifyFormat("if (a) {\n" 25464 " if (b)\n" 25465 " c;\n" 25466 " else if (d)\n" 25467 " e;\n" 25468 "} else {\n" 25469 " g;\n" 25470 "}", 25471 "if (a) {\n" 25472 " if (b)\n" 25473 " c;\n" 25474 " else {\n" 25475 " if (d)\n" 25476 " e;\n" 25477 " }\n" 25478 "} else {\n" 25479 " g;\n" 25480 "}", 25481 Style); 25482 25483 verifyFormat("if (isa<VarDecl>(D)) {\n" 25484 " for (auto *A : D.attrs())\n" 25485 " if (shouldProcessAttr(A))\n" 25486 " handleAttr(A);\n" 25487 "}", 25488 "if (isa<VarDecl>(D)) {\n" 25489 " for (auto *A : D.attrs()) {\n" 25490 " if (shouldProcessAttr(A)) {\n" 25491 " handleAttr(A);\n" 25492 " }\n" 25493 " }\n" 25494 "}", 25495 Style); 25496 25497 verifyFormat("do {\n" 25498 " ++I;\n" 25499 "} while (hasMore() && Filter(*I));", 25500 "do { ++I; } while (hasMore() && Filter(*I));", Style); 25501 25502 verifyFormat("if (a)\n" 25503 " if (b)\n" 25504 " c;\n" 25505 " else {\n" 25506 " if (d)\n" 25507 " e;\n" 25508 " }\n" 25509 "else\n" 25510 " f;", 25511 Style); 25512 25513 verifyFormat("if (a)\n" 25514 " if (b)\n" 25515 " c;\n" 25516 " else {\n" 25517 " if (d)\n" 25518 " e;\n" 25519 " else if (f)\n" 25520 " g;\n" 25521 " }\n" 25522 "else\n" 25523 " h;", 25524 Style); 25525 25526 verifyFormat("if (a) {\n" 25527 " b;\n" 25528 "} else if (c) {\n" 25529 " d;\n" 25530 " e;\n" 25531 "}", 25532 "if (a) {\n" 25533 " b;\n" 25534 "} else {\n" 25535 " if (c) {\n" 25536 " d;\n" 25537 " e;\n" 25538 " }\n" 25539 "}", 25540 Style); 25541 25542 verifyFormat("if (a) {\n" 25543 " b;\n" 25544 " c;\n" 25545 "} else if (d) {\n" 25546 " e;\n" 25547 " f;\n" 25548 "}", 25549 "if (a) {\n" 25550 " b;\n" 25551 " c;\n" 25552 "} else {\n" 25553 " if (d) {\n" 25554 " e;\n" 25555 " f;\n" 25556 " }\n" 25557 "}", 25558 Style); 25559 25560 verifyFormat("if (a) {\n" 25561 " b;\n" 25562 "} else if (c) {\n" 25563 " d;\n" 25564 "} else {\n" 25565 " e;\n" 25566 " f;\n" 25567 "}", 25568 "if (a) {\n" 25569 " b;\n" 25570 "} else {\n" 25571 " if (c) {\n" 25572 " d;\n" 25573 " } else {\n" 25574 " e;\n" 25575 " f;\n" 25576 " }\n" 25577 "}", 25578 Style); 25579 25580 verifyFormat("if (a) {\n" 25581 " b;\n" 25582 "} else if (c) {\n" 25583 " d;\n" 25584 "} else if (e) {\n" 25585 " f;\n" 25586 " g;\n" 25587 "}", 25588 "if (a) {\n" 25589 " b;\n" 25590 "} else {\n" 25591 " if (c) {\n" 25592 " d;\n" 25593 " } else if (e) {\n" 25594 " f;\n" 25595 " g;\n" 25596 " }\n" 25597 "}", 25598 Style); 25599 25600 verifyFormat("if (a) {\n" 25601 " if (b)\n" 25602 " c;\n" 25603 " else if (d) {\n" 25604 " e;\n" 25605 " f;\n" 25606 " }\n" 25607 "} else {\n" 25608 " g;\n" 25609 "}", 25610 "if (a) {\n" 25611 " if (b)\n" 25612 " c;\n" 25613 " else {\n" 25614 " if (d) {\n" 25615 " e;\n" 25616 " f;\n" 25617 " }\n" 25618 " }\n" 25619 "} else {\n" 25620 " g;\n" 25621 "}", 25622 Style); 25623 25624 verifyFormat("if (a)\n" 25625 " if (b)\n" 25626 " c;\n" 25627 " else {\n" 25628 " if (d) {\n" 25629 " e;\n" 25630 " f;\n" 25631 " }\n" 25632 " }\n" 25633 "else\n" 25634 " g;", 25635 Style); 25636 25637 verifyFormat("if (a) {\n" 25638 " b;\n" 25639 " c;\n" 25640 "} else { // comment\n" 25641 " if (d) {\n" 25642 " e;\n" 25643 " f;\n" 25644 " }\n" 25645 "}", 25646 Style); 25647 25648 verifyFormat("if (a)\n" 25649 " b;\n" 25650 "else if (c)\n" 25651 " while (d)\n" 25652 " e;\n" 25653 "// comment", 25654 "if (a)\n" 25655 "{\n" 25656 " b;\n" 25657 "} else if (c) {\n" 25658 " while (d) {\n" 25659 " e;\n" 25660 " }\n" 25661 "}\n" 25662 "// comment", 25663 Style); 25664 25665 verifyFormat("if (a) {\n" 25666 " b;\n" 25667 "} else if (c) {\n" 25668 " d;\n" 25669 "} else {\n" 25670 " e;\n" 25671 " g;\n" 25672 "}", 25673 Style); 25674 25675 verifyFormat("if (a) {\n" 25676 " b;\n" 25677 "} else if (c) {\n" 25678 " d;\n" 25679 "} else {\n" 25680 " e;\n" 25681 "} // comment", 25682 Style); 25683 25684 verifyFormat("int abs = [](int i) {\n" 25685 " if (i >= 0)\n" 25686 " return i;\n" 25687 " return -i;\n" 25688 "};", 25689 "int abs = [](int i) {\n" 25690 " if (i >= 0) {\n" 25691 " return i;\n" 25692 " }\n" 25693 " return -i;\n" 25694 "};", 25695 Style); 25696 25697 verifyFormat("if (a)\n" 25698 " foo();\n" 25699 "else\n" 25700 " bar();", 25701 "if (a)\n" 25702 "{\n" 25703 " foo();\n" 25704 "}\n" 25705 "else\n" 25706 "{\n" 25707 " bar();\n" 25708 "}", 25709 Style); 25710 25711 verifyFormat("if (a)\n" 25712 " foo();\n" 25713 "// comment\n" 25714 "else\n" 25715 " bar();", 25716 "if (a) {\n" 25717 " foo();\n" 25718 "}\n" 25719 "// comment\n" 25720 "else {\n" 25721 " bar();\n" 25722 "}", 25723 Style); 25724 25725 verifyFormat("if (a) {\n" 25726 "Label:\n" 25727 "}", 25728 Style); 25729 25730 verifyFormat("if (a) {\n" 25731 "Label:\n" 25732 " f();\n" 25733 "}", 25734 Style); 25735 25736 verifyFormat("if (a) {\n" 25737 " f();\n" 25738 "Label:\n" 25739 "}", 25740 Style); 25741 25742 verifyFormat("if consteval {\n" 25743 " f();\n" 25744 "} else {\n" 25745 " g();\n" 25746 "}", 25747 Style); 25748 25749 verifyFormat("if not consteval {\n" 25750 " f();\n" 25751 "} else if (a) {\n" 25752 " g();\n" 25753 "}", 25754 Style); 25755 25756 verifyFormat("if !consteval {\n" 25757 " g();\n" 25758 "}", 25759 Style); 25760 25761 Style.ColumnLimit = 65; 25762 verifyFormat("if (condition) {\n" 25763 " ff(Indices,\n" 25764 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 25765 "} else {\n" 25766 " ff(Indices,\n" 25767 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 25768 "}", 25769 Style); 25770 25771 Style.ColumnLimit = 20; 25772 25773 verifyFormat("int ab = [](int i) {\n" 25774 " if (i > 0) {\n" 25775 " i = 12345678 -\n" 25776 " i;\n" 25777 " }\n" 25778 " return i;\n" 25779 "};", 25780 Style); 25781 25782 verifyFormat("if (a) {\n" 25783 " b = c + // 1 -\n" 25784 " d;\n" 25785 "}", 25786 Style); 25787 25788 verifyFormat("if (a) {\n" 25789 " b = c >= 0 ? d\n" 25790 " : e;\n" 25791 "}", 25792 "if (a) {\n" 25793 " b = c >= 0 ? d : e;\n" 25794 "}", 25795 Style); 25796 25797 verifyFormat("if (a)\n" 25798 " b = c > 0 ? d : e;", 25799 "if (a) {\n" 25800 " b = c > 0 ? d : e;\n" 25801 "}", 25802 Style); 25803 25804 verifyFormat("if (-b >=\n" 25805 " c) { // Keep.\n" 25806 " foo();\n" 25807 "} else {\n" 25808 " bar();\n" 25809 "}", 25810 "if (-b >= c) { // Keep.\n" 25811 " foo();\n" 25812 "} else {\n" 25813 " bar();\n" 25814 "}", 25815 Style); 25816 25817 verifyFormat("if (a) /* Remove. */\n" 25818 " f();\n" 25819 "else\n" 25820 " g();", 25821 "if (a) <% /* Remove. */\n" 25822 " f();\n" 25823 "%> else <%\n" 25824 " g();\n" 25825 "%>", 25826 Style); 25827 25828 verifyFormat("while (\n" 25829 " !i--) <% // Keep.\n" 25830 " foo();\n" 25831 "%>", 25832 "while (!i--) <% // Keep.\n" 25833 " foo();\n" 25834 "%>", 25835 Style); 25836 25837 verifyFormat("for (int &i : chars)\n" 25838 " ++i;", 25839 "for (int &i :\n" 25840 " chars) {\n" 25841 " ++i;\n" 25842 "}", 25843 Style); 25844 25845 verifyFormat("if (a)\n" 25846 " b;\n" 25847 "else if (c) {\n" 25848 " d;\n" 25849 " e;\n" 25850 "} else\n" 25851 " f = g(foo, bar,\n" 25852 " baz);", 25853 "if (a)\n" 25854 " b;\n" 25855 "else {\n" 25856 " if (c) {\n" 25857 " d;\n" 25858 " e;\n" 25859 " } else\n" 25860 " f = g(foo, bar, baz);\n" 25861 "}", 25862 Style); 25863 25864 Style.ColumnLimit = 0; 25865 verifyFormat("if (a)\n" 25866 " b234567890223456789032345678904234567890 = " 25867 "c234567890223456789032345678904234567890;", 25868 "if (a) {\n" 25869 " b234567890223456789032345678904234567890 = " 25870 "c234567890223456789032345678904234567890;\n" 25871 "}", 25872 Style); 25873 25874 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 25875 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 25876 Style.BraceWrapping.BeforeElse = true; 25877 25878 Style.ColumnLimit = 65; 25879 25880 verifyFormat("if (condition)\n" 25881 "{\n" 25882 " ff(Indices,\n" 25883 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 25884 "}\n" 25885 "else\n" 25886 "{\n" 25887 " ff(Indices,\n" 25888 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 25889 "}", 25890 "if (condition) {\n" 25891 " ff(Indices,\n" 25892 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 25893 "} else {\n" 25894 " ff(Indices,\n" 25895 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 25896 "}", 25897 Style); 25898 25899 verifyFormat("if (a)\n" 25900 "{ //\n" 25901 " foo();\n" 25902 "}", 25903 "if (a) { //\n" 25904 " foo();\n" 25905 "}", 25906 Style); 25907 25908 Style.ColumnLimit = 20; 25909 25910 verifyFormat("int ab = [](int i) {\n" 25911 " if (i > 0)\n" 25912 " {\n" 25913 " i = 12345678 -\n" 25914 " i;\n" 25915 " }\n" 25916 " return i;\n" 25917 "};", 25918 "int ab = [](int i) {\n" 25919 " if (i > 0) {\n" 25920 " i = 12345678 -\n" 25921 " i;\n" 25922 " }\n" 25923 " return i;\n" 25924 "};", 25925 Style); 25926 25927 verifyFormat("if (a)\n" 25928 "{\n" 25929 " b = c + // 1 -\n" 25930 " d;\n" 25931 "}", 25932 "if (a) {\n" 25933 " b = c + // 1 -\n" 25934 " d;\n" 25935 "}", 25936 Style); 25937 25938 verifyFormat("if (a)\n" 25939 "{\n" 25940 " b = c >= 0 ? d\n" 25941 " : e;\n" 25942 "}", 25943 "if (a) {\n" 25944 " b = c >= 0 ? d : e;\n" 25945 "}", 25946 Style); 25947 25948 verifyFormat("if (a)\n" 25949 " b = c > 0 ? d : e;", 25950 "if (a)\n" 25951 "{\n" 25952 " b = c > 0 ? d : e;\n" 25953 "}", 25954 Style); 25955 25956 verifyFormat("if (foo + bar <=\n" 25957 " baz)\n" 25958 "{\n" 25959 " func(arg1, arg2);\n" 25960 "}", 25961 "if (foo + bar <= baz) {\n" 25962 " func(arg1, arg2);\n" 25963 "}", 25964 Style); 25965 25966 verifyFormat("if (foo + bar < baz)\n" 25967 " func(arg1, arg2);\n" 25968 "else\n" 25969 " func();", 25970 "if (foo + bar < baz)\n" 25971 "<%\n" 25972 " func(arg1, arg2);\n" 25973 "%>\n" 25974 "else\n" 25975 "<%\n" 25976 " func();\n" 25977 "%>", 25978 Style); 25979 25980 verifyFormat("while (i--)\n" 25981 "<% // Keep.\n" 25982 " foo();\n" 25983 "%>", 25984 "while (i--) <% // Keep.\n" 25985 " foo();\n" 25986 "%>", 25987 Style); 25988 25989 verifyFormat("for (int &i : chars)\n" 25990 " ++i;", 25991 "for (int &i : chars)\n" 25992 "{\n" 25993 " ++i;\n" 25994 "}", 25995 Style); 25996 } 25997 25998 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndent) { 25999 auto Style = getLLVMStyle(); 26000 26001 StringRef Short = "functionCall(paramA, paramB, paramC);\n" 26002 "void functionDecl(int a, int b, int c);"; 26003 26004 StringRef Medium = "functionCall(paramA, paramB, paramC, paramD, paramE, " 26005 "paramF, paramG, paramH, paramI);\n" 26006 "void functionDecl(int argumentA, int argumentB, int " 26007 "argumentC, int argumentD, int argumentE);"; 26008 26009 verifyFormat(Short, Style); 26010 26011 StringRef NoBreak = "functionCall(paramA, paramB, paramC, paramD, paramE, " 26012 "paramF, paramG, paramH,\n" 26013 " paramI);\n" 26014 "void functionDecl(int argumentA, int argumentB, int " 26015 "argumentC, int argumentD,\n" 26016 " int argumentE);"; 26017 26018 verifyFormat(NoBreak, Medium, Style); 26019 verifyFormat(NoBreak, 26020 "functionCall(\n" 26021 " paramA,\n" 26022 " paramB,\n" 26023 " paramC,\n" 26024 " paramD,\n" 26025 " paramE,\n" 26026 " paramF,\n" 26027 " paramG,\n" 26028 " paramH,\n" 26029 " paramI\n" 26030 ");\n" 26031 "void functionDecl(\n" 26032 " int argumentA,\n" 26033 " int argumentB,\n" 26034 " int argumentC,\n" 26035 " int argumentD,\n" 26036 " int argumentE\n" 26037 ");", 26038 Style); 26039 26040 verifyFormat("outerFunctionCall(nestedFunctionCall(argument1),\n" 26041 " nestedLongFunctionCall(argument1, " 26042 "argument2, argument3,\n" 26043 " argument4, " 26044 "argument5));", 26045 Style); 26046 26047 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 26048 26049 verifyFormat(Short, Style); 26050 verifyFormat( 26051 "functionCall(\n" 26052 " paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, " 26053 "paramI\n" 26054 ");\n" 26055 "void functionDecl(\n" 26056 " int argumentA, int argumentB, int argumentC, int argumentD, int " 26057 "argumentE\n" 26058 ");", 26059 Medium, Style); 26060 26061 Style.AllowAllArgumentsOnNextLine = false; 26062 Style.AllowAllParametersOfDeclarationOnNextLine = false; 26063 26064 verifyFormat(Short, Style); 26065 verifyFormat( 26066 "functionCall(\n" 26067 " paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, " 26068 "paramI\n" 26069 ");\n" 26070 "void functionDecl(\n" 26071 " int argumentA, int argumentB, int argumentC, int argumentD, int " 26072 "argumentE\n" 26073 ");", 26074 Medium, Style); 26075 26076 Style.BinPackArguments = false; 26077 Style.BinPackParameters = false; 26078 26079 verifyFormat(Short, Style); 26080 26081 verifyFormat("functionCall(\n" 26082 " paramA,\n" 26083 " paramB,\n" 26084 " paramC,\n" 26085 " paramD,\n" 26086 " paramE,\n" 26087 " paramF,\n" 26088 " paramG,\n" 26089 " paramH,\n" 26090 " paramI\n" 26091 ");\n" 26092 "void functionDecl(\n" 26093 " int argumentA,\n" 26094 " int argumentB,\n" 26095 " int argumentC,\n" 26096 " int argumentD,\n" 26097 " int argumentE\n" 26098 ");", 26099 Medium, Style); 26100 26101 verifyFormat("outerFunctionCall(\n" 26102 " nestedFunctionCall(argument1),\n" 26103 " nestedLongFunctionCall(\n" 26104 " argument1,\n" 26105 " argument2,\n" 26106 " argument3,\n" 26107 " argument4,\n" 26108 " argument5\n" 26109 " )\n" 26110 ");", 26111 Style); 26112 26113 verifyFormat("int a = (int)b;", Style); 26114 verifyFormat("int a = (int)b;", 26115 "int a = (\n" 26116 " int\n" 26117 ") b;", 26118 Style); 26119 26120 verifyFormat("return (true);", Style); 26121 verifyFormat("return (true);", 26122 "return (\n" 26123 " true\n" 26124 ");", 26125 Style); 26126 26127 verifyFormat("void foo();", Style); 26128 verifyFormat("void foo();", 26129 "void foo(\n" 26130 ");", 26131 Style); 26132 26133 verifyFormat("void foo() {}", Style); 26134 verifyFormat("void foo() {}", 26135 "void foo(\n" 26136 ") {\n" 26137 "}", 26138 Style); 26139 26140 verifyFormat("auto string = std::string();", Style); 26141 verifyFormat("auto string = std::string();", 26142 "auto string = std::string(\n" 26143 ");", 26144 Style); 26145 26146 verifyFormat("void (*functionPointer)() = nullptr;", Style); 26147 verifyFormat("void (*functionPointer)() = nullptr;", 26148 "void (\n" 26149 " *functionPointer\n" 26150 ")\n" 26151 "(\n" 26152 ") = nullptr;", 26153 Style); 26154 } 26155 26156 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentIfStatement) { 26157 auto Style = getLLVMStyle(); 26158 26159 verifyFormat("if (foo()) {\n" 26160 " return;\n" 26161 "}", 26162 Style); 26163 26164 verifyFormat("if (quitelongarg !=\n" 26165 " (alsolongarg - 1)) { // ABC is a very longgggggggggggg " 26166 "comment\n" 26167 " return;\n" 26168 "}", 26169 Style); 26170 26171 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 26172 26173 verifyFormat("if (foo()) {\n" 26174 " return;\n" 26175 "}", 26176 Style); 26177 26178 verifyFormat("if (quitelongarg !=\n" 26179 " (alsolongarg - 1)) { // ABC is a very longgggggggggggg " 26180 "comment\n" 26181 " return;\n" 26182 "}", 26183 Style); 26184 } 26185 26186 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentForStatement) { 26187 auto Style = getLLVMStyle(); 26188 26189 verifyFormat("for (int i = 0; i < 5; ++i) {\n" 26190 " doSomething();\n" 26191 "}", 26192 Style); 26193 26194 verifyFormat("for (int myReallyLongCountVariable = 0; " 26195 "myReallyLongCountVariable < count;\n" 26196 " myReallyLongCountVariable++) {\n" 26197 " doSomething();\n" 26198 "}", 26199 Style); 26200 26201 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 26202 26203 verifyFormat("for (int i = 0; i < 5; ++i) {\n" 26204 " doSomething();\n" 26205 "}", 26206 Style); 26207 26208 verifyFormat("for (int myReallyLongCountVariable = 0; " 26209 "myReallyLongCountVariable < count;\n" 26210 " myReallyLongCountVariable++) {\n" 26211 " doSomething();\n" 26212 "}", 26213 Style); 26214 } 26215 26216 TEST_F(FormatTest, UnderstandsDigraphs) { 26217 verifyFormat("int arr<:5:> = {};"); 26218 verifyFormat("int arr[5] = <%%>;"); 26219 verifyFormat("int arr<:::qualified_variable:> = {};"); 26220 verifyFormat("int arr[::qualified_variable] = <%%>;"); 26221 verifyFormat("%:include <header>"); 26222 verifyFormat("%:define A x##y"); 26223 verifyFormat("#define A x%:%:y"); 26224 } 26225 26226 TEST_F(FormatTest, AlignArrayOfStructuresLeftAlignmentNonSquare) { 26227 auto Style = getLLVMStyle(); 26228 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 26229 Style.AlignConsecutiveAssignments.Enabled = true; 26230 Style.AlignConsecutiveDeclarations.Enabled = true; 26231 26232 // The AlignArray code is incorrect for non square Arrays and can cause 26233 // crashes, these tests assert that the array is not changed but will 26234 // also act as regression tests for when it is properly fixed 26235 verifyFormat("struct test demo[] = {\n" 26236 " {1, 2},\n" 26237 " {3, 4, 5},\n" 26238 " {6, 7, 8}\n" 26239 "};", 26240 Style); 26241 verifyFormat("struct test demo[] = {\n" 26242 " {1, 2, 3, 4, 5},\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, 9, 10, 11, 12}\n" 26251 "};", 26252 Style); 26253 verifyFormat("struct test demo[] = {\n" 26254 " {1, 2, 3},\n" 26255 " {3, 4, 5},\n" 26256 " {6, 7, 8, 9, 10, 11, 12}\n" 26257 "};", 26258 Style); 26259 26260 verifyFormat("S{\n" 26261 " {},\n" 26262 " {},\n" 26263 " {a, b}\n" 26264 "};", 26265 Style); 26266 verifyFormat("S{\n" 26267 " {},\n" 26268 " {},\n" 26269 " {a, b},\n" 26270 "};", 26271 Style); 26272 verifyFormat("void foo() {\n" 26273 " auto thing = test{\n" 26274 " {\n" 26275 " {13}, {something}, // A\n" 26276 " }\n" 26277 " };\n" 26278 "}", 26279 "void foo() {\n" 26280 " auto thing = test{\n" 26281 " {\n" 26282 " {13},\n" 26283 " {something}, // A\n" 26284 " }\n" 26285 " };\n" 26286 "}", 26287 Style); 26288 } 26289 26290 TEST_F(FormatTest, AlignArrayOfStructuresRightAlignmentNonSquare) { 26291 auto Style = getLLVMStyle(); 26292 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 26293 Style.AlignConsecutiveAssignments.Enabled = true; 26294 Style.AlignConsecutiveDeclarations.Enabled = true; 26295 26296 // The AlignArray code is incorrect for non square Arrays and can cause 26297 // crashes, these tests assert that the array is not changed but will 26298 // also act as regression tests for when it is properly fixed 26299 verifyFormat("struct test demo[] = {\n" 26300 " {1, 2},\n" 26301 " {3, 4, 5},\n" 26302 " {6, 7, 8}\n" 26303 "};", 26304 Style); 26305 verifyFormat("struct test demo[] = {\n" 26306 " {1, 2, 3, 4, 5},\n" 26307 " {3, 4, 5},\n" 26308 " {6, 7, 8}\n" 26309 "};", 26310 Style); 26311 verifyFormat("struct test demo[] = {\n" 26312 " {1, 2, 3, 4, 5},\n" 26313 " {3, 4, 5},\n" 26314 " {6, 7, 8, 9, 10, 11, 12}\n" 26315 "};", 26316 Style); 26317 verifyFormat("struct test demo[] = {\n" 26318 " {1, 2, 3},\n" 26319 " {3, 4, 5},\n" 26320 " {6, 7, 8, 9, 10, 11, 12}\n" 26321 "};", 26322 Style); 26323 26324 verifyFormat("S{\n" 26325 " {},\n" 26326 " {},\n" 26327 " {a, b}\n" 26328 "};", 26329 Style); 26330 verifyFormat("S{\n" 26331 " {},\n" 26332 " {},\n" 26333 " {a, b},\n" 26334 "};", 26335 Style); 26336 verifyFormat("void foo() {\n" 26337 " auto thing = test{\n" 26338 " {\n" 26339 " {13}, {something}, // A\n" 26340 " }\n" 26341 " };\n" 26342 "}", 26343 "void foo() {\n" 26344 " auto thing = test{\n" 26345 " {\n" 26346 " {13},\n" 26347 " {something}, // A\n" 26348 " }\n" 26349 " };\n" 26350 "}", 26351 Style); 26352 } 26353 26354 TEST_F(FormatTest, FormatsVariableTemplates) { 26355 verifyFormat("inline bool var = is_integral_v<int> && is_signed_v<int>;"); 26356 verifyFormat("template <typename T> " 26357 "inline bool var = is_integral_v<T> && is_signed_v<T>;"); 26358 } 26359 26360 } // namespace 26361 } // namespace format 26362 } // namespace clang 26363