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 EXPECT_EQ("if (foo && bar &&\n" 3100 " baz)\n" 3101 "{\n" 3102 " quux();\n" 3103 "}", 3104 format("if(foo&&bar&&baz){quux();}", Style)); 3105 EXPECT_EQ("if (foo && bar &&\n" 3106 " baz)\n" 3107 "{\n" 3108 " quux();\n" 3109 "}", 3110 format("if (foo && bar &&\n" 3111 " baz) {\n" 3112 " quux();\n" 3113 "}", 3114 Style)); 3115 EXPECT_EQ("if (foo) {\n" 3116 " bar();\n" 3117 "} else if (baz ||\n" 3118 " quux)\n" 3119 "{\n" 3120 " foobar();\n" 3121 "}", 3122 format("if(foo){bar();}else if(baz||quux){foobar();}", Style)); 3123 EXPECT_EQ( 3124 "if (foo) {\n" 3125 " bar();\n" 3126 "} else if (baz ||\n" 3127 " quux)\n" 3128 "{\n" 3129 " foobar();\n" 3130 "} else {\n" 3131 " barbaz();\n" 3132 "}", 3133 format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}", 3134 Style)); 3135 EXPECT_EQ("for (int i = 0;\n" 3136 " i < 10; ++i)\n" 3137 "{\n" 3138 " foo();\n" 3139 "}", 3140 format("for(int i=0;i<10;++i){foo();}", Style)); 3141 EXPECT_EQ("foreach (int i,\n" 3142 " list)\n" 3143 "{\n" 3144 " foo();\n" 3145 "}", 3146 format("foreach(int i, list){foo();}", Style)); 3147 Style.ColumnLimit = 3148 40; // to concentrate at brace wrapping, not line wrap due to column limit 3149 EXPECT_EQ("foreach (int i, list) {\n" 3150 " foo();\n" 3151 "}", 3152 format("foreach(int i, list){foo();}", Style)); 3153 Style.ColumnLimit = 3154 20; // to concentrate at brace wrapping, not line wrap due to column limit 3155 EXPECT_EQ("while (foo || bar ||\n" 3156 " baz)\n" 3157 "{\n" 3158 " quux();\n" 3159 "}", 3160 format("while(foo||bar||baz){quux();}", Style)); 3161 EXPECT_EQ("switch (\n" 3162 " foo = barbaz)\n" 3163 "{\n" 3164 "case quux:\n" 3165 " return;\n" 3166 "}", 3167 format("switch(foo=barbaz){case quux:return;}", Style)); 3168 EXPECT_EQ("try {\n" 3169 " foo();\n" 3170 "} catch (\n" 3171 " Exception &bar)\n" 3172 "{\n" 3173 " baz();\n" 3174 "}", 3175 format("try{foo();}catch(Exception&bar){baz();}", Style)); 3176 Style.ColumnLimit = 3177 40; // to concentrate at brace wrapping, not line wrap due to column limit 3178 EXPECT_EQ("try {\n" 3179 " foo();\n" 3180 "} catch (Exception &bar) {\n" 3181 " baz();\n" 3182 "}", 3183 format("try{foo();}catch(Exception&bar){baz();}", Style)); 3184 Style.ColumnLimit = 3185 20; // to concentrate at brace wrapping, not line wrap due to column limit 3186 3187 Style.BraceWrapping.BeforeElse = true; 3188 EXPECT_EQ( 3189 "if (foo) {\n" 3190 " bar();\n" 3191 "}\n" 3192 "else if (baz ||\n" 3193 " quux)\n" 3194 "{\n" 3195 " foobar();\n" 3196 "}\n" 3197 "else {\n" 3198 " barbaz();\n" 3199 "}", 3200 format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}", 3201 Style)); 3202 3203 Style.BraceWrapping.BeforeCatch = true; 3204 EXPECT_EQ("try {\n" 3205 " foo();\n" 3206 "}\n" 3207 "catch (...) {\n" 3208 " baz();\n" 3209 "}", 3210 format("try{foo();}catch(...){baz();}", Style)); 3211 3212 Style.BraceWrapping.AfterFunction = true; 3213 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine; 3214 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 3215 Style.ColumnLimit = 80; 3216 verifyFormat("void shortfunction() { bar(); }", Style); 3217 3218 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 3219 verifyFormat("void shortfunction()\n" 3220 "{\n" 3221 " bar();\n" 3222 "}", 3223 Style); 3224 } 3225 3226 TEST_F(FormatTest, BeforeWhile) { 3227 FormatStyle Style = getLLVMStyle(); 3228 Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom; 3229 3230 verifyFormat("do {\n" 3231 " foo();\n" 3232 "} while (1);", 3233 Style); 3234 Style.BraceWrapping.BeforeWhile = true; 3235 verifyFormat("do {\n" 3236 " foo();\n" 3237 "}\n" 3238 "while (1);", 3239 Style); 3240 } 3241 3242 //===----------------------------------------------------------------------===// 3243 // Tests for classes, namespaces, etc. 3244 //===----------------------------------------------------------------------===// 3245 3246 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) { 3247 verifyFormat("class A {};"); 3248 } 3249 3250 TEST_F(FormatTest, UnderstandsAccessSpecifiers) { 3251 verifyFormat("class A {\n" 3252 "public:\n" 3253 "public: // comment\n" 3254 "protected:\n" 3255 "private:\n" 3256 " void f() {}\n" 3257 "};"); 3258 verifyFormat("export class A {\n" 3259 "public:\n" 3260 "public: // comment\n" 3261 "protected:\n" 3262 "private:\n" 3263 " void f() {}\n" 3264 "};"); 3265 verifyGoogleFormat("class A {\n" 3266 " public:\n" 3267 " protected:\n" 3268 " private:\n" 3269 " void f() {}\n" 3270 "};"); 3271 verifyGoogleFormat("export class A {\n" 3272 " public:\n" 3273 " protected:\n" 3274 " private:\n" 3275 " void f() {}\n" 3276 "};"); 3277 verifyFormat("class A {\n" 3278 "public slots:\n" 3279 " void f1() {}\n" 3280 "public Q_SLOTS:\n" 3281 " void f2() {}\n" 3282 "protected slots:\n" 3283 " void f3() {}\n" 3284 "protected Q_SLOTS:\n" 3285 " void f4() {}\n" 3286 "private slots:\n" 3287 " void f5() {}\n" 3288 "private Q_SLOTS:\n" 3289 " void f6() {}\n" 3290 "signals:\n" 3291 " void g1();\n" 3292 "Q_SIGNALS:\n" 3293 " void g2();\n" 3294 "};"); 3295 3296 // Don't interpret 'signals' the wrong way. 3297 verifyFormat("signals.set();"); 3298 verifyFormat("for (Signals signals : f()) {\n}"); 3299 verifyFormat("{\n" 3300 " signals.set(); // This needs indentation.\n" 3301 "}"); 3302 verifyFormat("void f() {\n" 3303 "label:\n" 3304 " signals.baz();\n" 3305 "}"); 3306 verifyFormat("private[1];"); 3307 verifyFormat("testArray[public] = 1;"); 3308 verifyFormat("public();"); 3309 verifyFormat("myFunc(public);"); 3310 verifyFormat("std::vector<int> testVec = {private};"); 3311 verifyFormat("private.p = 1;"); 3312 verifyFormat("void function(private...){};"); 3313 verifyFormat("if (private && public)\n"); 3314 verifyFormat("private &= true;"); 3315 verifyFormat("int x = private * public;"); 3316 verifyFormat("public *= private;"); 3317 verifyFormat("int x = public + private;"); 3318 verifyFormat("private++;"); 3319 verifyFormat("++private;"); 3320 verifyFormat("public += private;"); 3321 verifyFormat("public = public - private;"); 3322 verifyFormat("public->foo();"); 3323 verifyFormat("private--;"); 3324 verifyFormat("--private;"); 3325 verifyFormat("public -= 1;"); 3326 verifyFormat("if (!private && !public)\n"); 3327 verifyFormat("public != private;"); 3328 verifyFormat("int x = public / private;"); 3329 verifyFormat("public /= 2;"); 3330 verifyFormat("public = public % 2;"); 3331 verifyFormat("public %= 2;"); 3332 verifyFormat("if (public < private)\n"); 3333 verifyFormat("public << private;"); 3334 verifyFormat("public <<= private;"); 3335 verifyFormat("if (public > private)\n"); 3336 verifyFormat("public >> private;"); 3337 verifyFormat("public >>= private;"); 3338 verifyFormat("public ^ private;"); 3339 verifyFormat("public ^= private;"); 3340 verifyFormat("public | private;"); 3341 verifyFormat("public |= private;"); 3342 verifyFormat("auto x = private ? 1 : 2;"); 3343 verifyFormat("if (public == private)\n"); 3344 verifyFormat("void foo(public, private)"); 3345 verifyFormat("public::foo();"); 3346 3347 verifyFormat("class A {\n" 3348 "public:\n" 3349 " std::unique_ptr<int *[]> b() { return nullptr; }\n" 3350 "\n" 3351 "private:\n" 3352 " int c;\n" 3353 "};"); 3354 } 3355 3356 TEST_F(FormatTest, SeparatesLogicalBlocks) { 3357 EXPECT_EQ("class A {\n" 3358 "public:\n" 3359 " void f();\n" 3360 "\n" 3361 "private:\n" 3362 " void g() {}\n" 3363 " // test\n" 3364 "protected:\n" 3365 " int h;\n" 3366 "};", 3367 format("class A {\n" 3368 "public:\n" 3369 "void f();\n" 3370 "private:\n" 3371 "void g() {}\n" 3372 "// test\n" 3373 "protected:\n" 3374 "int h;\n" 3375 "};")); 3376 EXPECT_EQ("class A {\n" 3377 "protected:\n" 3378 "public:\n" 3379 " void f();\n" 3380 "};", 3381 format("class A {\n" 3382 "protected:\n" 3383 "\n" 3384 "public:\n" 3385 "\n" 3386 " void f();\n" 3387 "};")); 3388 3389 // Even ensure proper spacing inside macros. 3390 EXPECT_EQ("#define B \\\n" 3391 " class A { \\\n" 3392 " protected: \\\n" 3393 " public: \\\n" 3394 " void f(); \\\n" 3395 " };", 3396 format("#define B \\\n" 3397 " class A { \\\n" 3398 " protected: \\\n" 3399 " \\\n" 3400 " public: \\\n" 3401 " \\\n" 3402 " void f(); \\\n" 3403 " };", 3404 getGoogleStyle())); 3405 // But don't remove empty lines after macros ending in access specifiers. 3406 EXPECT_EQ("#define A private:\n" 3407 "\n" 3408 "int i;", 3409 format("#define A private:\n" 3410 "\n" 3411 "int i;")); 3412 } 3413 3414 TEST_F(FormatTest, FormatsClasses) { 3415 verifyFormat("class A : public B {};"); 3416 verifyFormat("class A : public ::B {};"); 3417 3418 verifyFormat( 3419 "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3420 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};"); 3421 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n" 3422 " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3423 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};"); 3424 verifyFormat( 3425 "class A : public B, public C, public D, public E, public F {};"); 3426 verifyFormat("class AAAAAAAAAAAA : public B,\n" 3427 " public C,\n" 3428 " public D,\n" 3429 " public E,\n" 3430 " public F,\n" 3431 " public G {};"); 3432 3433 verifyFormat("class\n" 3434 " ReallyReallyLongClassName {\n" 3435 " int i;\n" 3436 "};", 3437 getLLVMStyleWithColumns(32)); 3438 verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n" 3439 " aaaaaaaaaaaaaaaa> {};"); 3440 verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n" 3441 " : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n" 3442 " aaaaaaaaaaaaaaaaaaaaaa> {};"); 3443 verifyFormat("template <class R, class C>\n" 3444 "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n" 3445 " : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};"); 3446 verifyFormat("class ::A::B {};"); 3447 } 3448 3449 TEST_F(FormatTest, BreakInheritanceStyle) { 3450 FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle(); 3451 StyleWithInheritanceBreakBeforeComma.BreakInheritanceList = 3452 FormatStyle::BILS_BeforeComma; 3453 verifyFormat("class MyClass : public X {};", 3454 StyleWithInheritanceBreakBeforeComma); 3455 verifyFormat("class MyClass\n" 3456 " : public X\n" 3457 " , public Y {};", 3458 StyleWithInheritanceBreakBeforeComma); 3459 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n" 3460 " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n" 3461 " , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};", 3462 StyleWithInheritanceBreakBeforeComma); 3463 verifyFormat("struct aaaaaaaaaaaaa\n" 3464 " : public aaaaaaaaaaaaaaaaaaa< // break\n" 3465 " aaaaaaaaaaaaaaaa> {};", 3466 StyleWithInheritanceBreakBeforeComma); 3467 3468 FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle(); 3469 StyleWithInheritanceBreakAfterColon.BreakInheritanceList = 3470 FormatStyle::BILS_AfterColon; 3471 verifyFormat("class MyClass : public X {};", 3472 StyleWithInheritanceBreakAfterColon); 3473 verifyFormat("class MyClass : public X, public Y {};", 3474 StyleWithInheritanceBreakAfterColon); 3475 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n" 3476 " public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3477 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};", 3478 StyleWithInheritanceBreakAfterColon); 3479 verifyFormat("struct aaaaaaaaaaaaa :\n" 3480 " public aaaaaaaaaaaaaaaaaaa< // break\n" 3481 " aaaaaaaaaaaaaaaa> {};", 3482 StyleWithInheritanceBreakAfterColon); 3483 3484 FormatStyle StyleWithInheritanceBreakAfterComma = getLLVMStyle(); 3485 StyleWithInheritanceBreakAfterComma.BreakInheritanceList = 3486 FormatStyle::BILS_AfterComma; 3487 verifyFormat("class MyClass : public X {};", 3488 StyleWithInheritanceBreakAfterComma); 3489 verifyFormat("class MyClass : public X,\n" 3490 " public Y {};", 3491 StyleWithInheritanceBreakAfterComma); 3492 verifyFormat( 3493 "class AAAAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3494 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC " 3495 "{};", 3496 StyleWithInheritanceBreakAfterComma); 3497 verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n" 3498 " aaaaaaaaaaaaaaaa> {};", 3499 StyleWithInheritanceBreakAfterComma); 3500 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n" 3501 " : public OnceBreak,\n" 3502 " public AlwaysBreak,\n" 3503 " EvenBasesFitInOneLine {};", 3504 StyleWithInheritanceBreakAfterComma); 3505 } 3506 3507 TEST_F(FormatTest, FormatsVariableDeclarationsAfterRecord) { 3508 verifyFormat("class A {\n} a, b;"); 3509 verifyFormat("struct A {\n} a, b;"); 3510 verifyFormat("union A {\n} a, b;"); 3511 3512 verifyFormat("constexpr class A {\n} a, b;"); 3513 verifyFormat("constexpr struct A {\n} a, b;"); 3514 verifyFormat("constexpr union A {\n} a, b;"); 3515 3516 verifyFormat("namespace {\nclass A {\n} a, b;\n} // namespace"); 3517 verifyFormat("namespace {\nstruct A {\n} a, b;\n} // namespace"); 3518 verifyFormat("namespace {\nunion A {\n} a, b;\n} // namespace"); 3519 3520 verifyFormat("namespace {\nconstexpr class A {\n} a, b;\n} // namespace"); 3521 verifyFormat("namespace {\nconstexpr struct A {\n} a, b;\n} // namespace"); 3522 verifyFormat("namespace {\nconstexpr union A {\n} a, b;\n} // namespace"); 3523 3524 verifyFormat("namespace ns {\n" 3525 "class {\n" 3526 "} a, b;\n" 3527 "} // namespace ns"); 3528 verifyFormat("namespace ns {\n" 3529 "const class {\n" 3530 "} a, b;\n" 3531 "} // namespace ns"); 3532 verifyFormat("namespace ns {\n" 3533 "constexpr class C {\n" 3534 "} a, b;\n" 3535 "} // namespace ns"); 3536 verifyFormat("namespace ns {\n" 3537 "class { /* comment */\n" 3538 "} a, b;\n" 3539 "} // namespace ns"); 3540 verifyFormat("namespace ns {\n" 3541 "const class { /* comment */\n" 3542 "} a, b;\n" 3543 "} // namespace ns"); 3544 } 3545 3546 TEST_F(FormatTest, FormatsEnum) { 3547 verifyFormat("enum {\n" 3548 " Zero,\n" 3549 " One = 1,\n" 3550 " Two = One + 1,\n" 3551 " Three = (One + Two),\n" 3552 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3553 " Five = (One, Two, Three, Four, 5)\n" 3554 "};"); 3555 verifyGoogleFormat("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 verifyFormat("enum Enum {};"); 3564 verifyFormat("enum {};"); 3565 verifyFormat("enum X E {} d;"); 3566 verifyFormat("enum __attribute__((...)) E {} d;"); 3567 verifyFormat("enum __declspec__((...)) E {} d;"); 3568 verifyFormat("enum {\n" 3569 " Bar = Foo<int, int>::value\n" 3570 "};", 3571 getLLVMStyleWithColumns(30)); 3572 3573 verifyFormat("enum ShortEnum { A, B, C };"); 3574 verifyGoogleFormat("enum ShortEnum { A, B, C };"); 3575 3576 EXPECT_EQ("enum KeepEmptyLines {\n" 3577 " ONE,\n" 3578 "\n" 3579 " TWO,\n" 3580 "\n" 3581 " THREE\n" 3582 "}", 3583 format("enum KeepEmptyLines {\n" 3584 " ONE,\n" 3585 "\n" 3586 " TWO,\n" 3587 "\n" 3588 "\n" 3589 " THREE\n" 3590 "}")); 3591 verifyFormat("enum E { // comment\n" 3592 " ONE,\n" 3593 " TWO\n" 3594 "};\n" 3595 "int i;"); 3596 3597 FormatStyle EightIndent = getLLVMStyle(); 3598 EightIndent.IndentWidth = 8; 3599 verifyFormat("enum {\n" 3600 " VOID,\n" 3601 " CHAR,\n" 3602 " SHORT,\n" 3603 " INT,\n" 3604 " LONG,\n" 3605 " SIGNED,\n" 3606 " UNSIGNED,\n" 3607 " BOOL,\n" 3608 " FLOAT,\n" 3609 " DOUBLE,\n" 3610 " COMPLEX\n" 3611 "};", 3612 EightIndent); 3613 3614 // Not enums. 3615 verifyFormat("enum X f() {\n" 3616 " a();\n" 3617 " return 42;\n" 3618 "}"); 3619 verifyFormat("enum X Type::f() {\n" 3620 " a();\n" 3621 " return 42;\n" 3622 "}"); 3623 verifyFormat("enum ::X f() {\n" 3624 " a();\n" 3625 " return 42;\n" 3626 "}"); 3627 verifyFormat("enum ns::X f() {\n" 3628 " a();\n" 3629 " return 42;\n" 3630 "}"); 3631 } 3632 3633 TEST_F(FormatTest, FormatsEnumsWithErrors) { 3634 verifyFormat("enum Type {\n" 3635 " One = 0; // These semicolons should be commas.\n" 3636 " Two = 1;\n" 3637 "};"); 3638 verifyFormat("namespace n {\n" 3639 "enum Type {\n" 3640 " One,\n" 3641 " Two, // missing };\n" 3642 " int i;\n" 3643 "}\n" 3644 "void g() {}"); 3645 } 3646 3647 TEST_F(FormatTest, FormatsEnumStruct) { 3648 verifyFormat("enum struct {\n" 3649 " Zero,\n" 3650 " One = 1,\n" 3651 " Two = One + 1,\n" 3652 " Three = (One + Two),\n" 3653 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3654 " Five = (One, Two, Three, Four, 5)\n" 3655 "};"); 3656 verifyFormat("enum struct Enum {};"); 3657 verifyFormat("enum struct {};"); 3658 verifyFormat("enum struct X E {} d;"); 3659 verifyFormat("enum struct __attribute__((...)) E {} d;"); 3660 verifyFormat("enum struct __declspec__((...)) E {} d;"); 3661 verifyFormat("enum struct X f() {\n a();\n return 42;\n}"); 3662 } 3663 3664 TEST_F(FormatTest, FormatsEnumClass) { 3665 verifyFormat("enum class {\n" 3666 " Zero,\n" 3667 " One = 1,\n" 3668 " Two = One + 1,\n" 3669 " Three = (One + Two),\n" 3670 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3671 " Five = (One, Two, Three, Four, 5)\n" 3672 "};"); 3673 verifyFormat("enum class Enum {};"); 3674 verifyFormat("enum class {};"); 3675 verifyFormat("enum class X E {} d;"); 3676 verifyFormat("enum class __attribute__((...)) E {} d;"); 3677 verifyFormat("enum class __declspec__((...)) E {} d;"); 3678 verifyFormat("enum class X f() {\n a();\n return 42;\n}"); 3679 } 3680 3681 TEST_F(FormatTest, FormatsEnumTypes) { 3682 verifyFormat("enum X : int {\n" 3683 " A, // Force multiple lines.\n" 3684 " B\n" 3685 "};"); 3686 verifyFormat("enum X : int { A, B };"); 3687 verifyFormat("enum X : std::uint32_t { A, B };"); 3688 } 3689 3690 TEST_F(FormatTest, FormatsTypedefEnum) { 3691 FormatStyle Style = getLLVMStyleWithColumns(40); 3692 verifyFormat("typedef enum {} EmptyEnum;"); 3693 verifyFormat("typedef enum { A, B, C } ShortEnum;"); 3694 verifyFormat("typedef enum {\n" 3695 " ZERO = 0,\n" 3696 " ONE = 1,\n" 3697 " TWO = 2,\n" 3698 " THREE = 3\n" 3699 "} LongEnum;", 3700 Style); 3701 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 3702 Style.BraceWrapping.AfterEnum = true; 3703 verifyFormat("typedef enum {} EmptyEnum;"); 3704 verifyFormat("typedef enum { A, B, C } ShortEnum;"); 3705 verifyFormat("typedef enum\n" 3706 "{\n" 3707 " ZERO = 0,\n" 3708 " ONE = 1,\n" 3709 " TWO = 2,\n" 3710 " THREE = 3\n" 3711 "} LongEnum;", 3712 Style); 3713 } 3714 3715 TEST_F(FormatTest, FormatsNSEnums) { 3716 verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }"); 3717 verifyGoogleFormat( 3718 "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }"); 3719 verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n" 3720 " // Information about someDecentlyLongValue.\n" 3721 " someDecentlyLongValue,\n" 3722 " // Information about anotherDecentlyLongValue.\n" 3723 " anotherDecentlyLongValue,\n" 3724 " // Information about aThirdDecentlyLongValue.\n" 3725 " aThirdDecentlyLongValue\n" 3726 "};"); 3727 verifyGoogleFormat("typedef NS_CLOSED_ENUM(NSInteger, MyType) {\n" 3728 " // Information about someDecentlyLongValue.\n" 3729 " someDecentlyLongValue,\n" 3730 " // Information about anotherDecentlyLongValue.\n" 3731 " anotherDecentlyLongValue,\n" 3732 " // Information about aThirdDecentlyLongValue.\n" 3733 " aThirdDecentlyLongValue\n" 3734 "};"); 3735 verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n" 3736 " a = 1,\n" 3737 " b = 2,\n" 3738 " c = 3,\n" 3739 "};"); 3740 verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n" 3741 " a = 1,\n" 3742 " b = 2,\n" 3743 " c = 3,\n" 3744 "};"); 3745 verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n" 3746 " a = 1,\n" 3747 " b = 2,\n" 3748 " c = 3,\n" 3749 "};"); 3750 verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n" 3751 " a = 1,\n" 3752 " b = 2,\n" 3753 " c = 3,\n" 3754 "};"); 3755 } 3756 3757 TEST_F(FormatTest, FormatsBitfields) { 3758 verifyFormat("struct Bitfields {\n" 3759 " unsigned sClass : 8;\n" 3760 " unsigned ValueKind : 2;\n" 3761 "};"); 3762 verifyFormat("struct A {\n" 3763 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n" 3764 " bbbbbbbbbbbbbbbbbbbbbbbbb;\n" 3765 "};"); 3766 verifyFormat("struct MyStruct {\n" 3767 " uchar data;\n" 3768 " uchar : 8;\n" 3769 " uchar : 8;\n" 3770 " uchar other;\n" 3771 "};"); 3772 FormatStyle Style = getLLVMStyle(); 3773 Style.BitFieldColonSpacing = FormatStyle::BFCS_None; 3774 verifyFormat("struct Bitfields {\n" 3775 " unsigned sClass:8;\n" 3776 " unsigned ValueKind:2;\n" 3777 " uchar other;\n" 3778 "};", 3779 Style); 3780 verifyFormat("struct A {\n" 3781 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:1,\n" 3782 " bbbbbbbbbbbbbbbbbbbbbbbbb:2;\n" 3783 "};", 3784 Style); 3785 Style.BitFieldColonSpacing = FormatStyle::BFCS_Before; 3786 verifyFormat("struct Bitfields {\n" 3787 " unsigned sClass :8;\n" 3788 " unsigned ValueKind :2;\n" 3789 " uchar other;\n" 3790 "};", 3791 Style); 3792 Style.BitFieldColonSpacing = FormatStyle::BFCS_After; 3793 verifyFormat("struct Bitfields {\n" 3794 " unsigned sClass: 8;\n" 3795 " unsigned ValueKind: 2;\n" 3796 " uchar other;\n" 3797 "};", 3798 Style); 3799 } 3800 3801 TEST_F(FormatTest, FormatsNamespaces) { 3802 FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle(); 3803 LLVMWithNoNamespaceFix.FixNamespaceComments = false; 3804 3805 verifyFormat("namespace some_namespace {\n" 3806 "class A {};\n" 3807 "void f() { f(); }\n" 3808 "}", 3809 LLVMWithNoNamespaceFix); 3810 verifyFormat("#define M(x) x##x\n" 3811 "namespace M(x) {\n" 3812 "class A {};\n" 3813 "void f() { f(); }\n" 3814 "}", 3815 LLVMWithNoNamespaceFix); 3816 verifyFormat("#define M(x) x##x\n" 3817 "namespace N::inline M(x) {\n" 3818 "class A {};\n" 3819 "void f() { f(); }\n" 3820 "}", 3821 LLVMWithNoNamespaceFix); 3822 verifyFormat("#define M(x) x##x\n" 3823 "namespace M(x)::inline N {\n" 3824 "class A {};\n" 3825 "void f() { f(); }\n" 3826 "}", 3827 LLVMWithNoNamespaceFix); 3828 verifyFormat("#define M(x) x##x\n" 3829 "namespace N::M(x) {\n" 3830 "class A {};\n" 3831 "void f() { f(); }\n" 3832 "}", 3833 LLVMWithNoNamespaceFix); 3834 verifyFormat("#define M(x) x##x\n" 3835 "namespace M::N(x) {\n" 3836 "class A {};\n" 3837 "void f() { f(); }\n" 3838 "}", 3839 LLVMWithNoNamespaceFix); 3840 verifyFormat("namespace N::inline D {\n" 3841 "class A {};\n" 3842 "void f() { f(); }\n" 3843 "}", 3844 LLVMWithNoNamespaceFix); 3845 verifyFormat("namespace N::inline D::E {\n" 3846 "class A {};\n" 3847 "void f() { f(); }\n" 3848 "}", 3849 LLVMWithNoNamespaceFix); 3850 verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n" 3851 "class A {};\n" 3852 "void f() { f(); }\n" 3853 "}", 3854 LLVMWithNoNamespaceFix); 3855 verifyFormat("/* something */ namespace some_namespace {\n" 3856 "class A {};\n" 3857 "void f() { f(); }\n" 3858 "}", 3859 LLVMWithNoNamespaceFix); 3860 verifyFormat("namespace {\n" 3861 "class A {};\n" 3862 "void f() { f(); }\n" 3863 "}", 3864 LLVMWithNoNamespaceFix); 3865 verifyFormat("/* something */ namespace {\n" 3866 "class A {};\n" 3867 "void f() { f(); }\n" 3868 "}", 3869 LLVMWithNoNamespaceFix); 3870 verifyFormat("inline namespace X {\n" 3871 "class A {};\n" 3872 "void f() { f(); }\n" 3873 "}", 3874 LLVMWithNoNamespaceFix); 3875 verifyFormat("/* something */ inline namespace X {\n" 3876 "class A {};\n" 3877 "void f() { f(); }\n" 3878 "}", 3879 LLVMWithNoNamespaceFix); 3880 verifyFormat("export namespace X {\n" 3881 "class A {};\n" 3882 "void f() { f(); }\n" 3883 "}", 3884 LLVMWithNoNamespaceFix); 3885 verifyFormat("using namespace some_namespace;\n" 3886 "class A {};\n" 3887 "void f() { f(); }", 3888 LLVMWithNoNamespaceFix); 3889 3890 // This code is more common than we thought; if we 3891 // layout this correctly the semicolon will go into 3892 // its own line, which is undesirable. 3893 verifyFormat("namespace {};", LLVMWithNoNamespaceFix); 3894 verifyFormat("namespace {\n" 3895 "class A {};\n" 3896 "};", 3897 LLVMWithNoNamespaceFix); 3898 3899 verifyFormat("namespace {\n" 3900 "int SomeVariable = 0; // comment\n" 3901 "} // namespace", 3902 LLVMWithNoNamespaceFix); 3903 EXPECT_EQ("#ifndef HEADER_GUARD\n" 3904 "#define HEADER_GUARD\n" 3905 "namespace my_namespace {\n" 3906 "int i;\n" 3907 "} // my_namespace\n" 3908 "#endif // HEADER_GUARD", 3909 format("#ifndef HEADER_GUARD\n" 3910 " #define HEADER_GUARD\n" 3911 " namespace my_namespace {\n" 3912 "int i;\n" 3913 "} // my_namespace\n" 3914 "#endif // HEADER_GUARD", 3915 LLVMWithNoNamespaceFix)); 3916 3917 EXPECT_EQ("namespace A::B {\n" 3918 "class C {};\n" 3919 "}", 3920 format("namespace A::B {\n" 3921 "class C {};\n" 3922 "}", 3923 LLVMWithNoNamespaceFix)); 3924 3925 FormatStyle Style = getLLVMStyle(); 3926 Style.NamespaceIndentation = FormatStyle::NI_All; 3927 EXPECT_EQ("namespace out {\n" 3928 " int i;\n" 3929 " namespace in {\n" 3930 " int i;\n" 3931 " } // namespace in\n" 3932 "} // namespace out", 3933 format("namespace out {\n" 3934 "int i;\n" 3935 "namespace in {\n" 3936 "int i;\n" 3937 "} // namespace in\n" 3938 "} // namespace out", 3939 Style)); 3940 3941 FormatStyle ShortInlineFunctions = getLLVMStyle(); 3942 ShortInlineFunctions.NamespaceIndentation = FormatStyle::NI_All; 3943 ShortInlineFunctions.AllowShortFunctionsOnASingleLine = 3944 FormatStyle::SFS_Inline; 3945 verifyFormat("namespace {\n" 3946 " void f() {\n" 3947 " return;\n" 3948 " }\n" 3949 "} // namespace\n", 3950 ShortInlineFunctions); 3951 verifyFormat("namespace { /* comment */\n" 3952 " void f() {\n" 3953 " return;\n" 3954 " }\n" 3955 "} // namespace\n", 3956 ShortInlineFunctions); 3957 verifyFormat("namespace { // comment\n" 3958 " void f() {\n" 3959 " return;\n" 3960 " }\n" 3961 "} // namespace\n", 3962 ShortInlineFunctions); 3963 verifyFormat("namespace {\n" 3964 " int some_int;\n" 3965 " void f() {\n" 3966 " return;\n" 3967 " }\n" 3968 "} // namespace\n", 3969 ShortInlineFunctions); 3970 verifyFormat("namespace interface {\n" 3971 " void f() {\n" 3972 " return;\n" 3973 " }\n" 3974 "} // namespace interface\n", 3975 ShortInlineFunctions); 3976 verifyFormat("namespace {\n" 3977 " class X {\n" 3978 " void f() { return; }\n" 3979 " };\n" 3980 "} // namespace\n", 3981 ShortInlineFunctions); 3982 verifyFormat("namespace {\n" 3983 " class X { /* comment */\n" 3984 " void f() { return; }\n" 3985 " };\n" 3986 "} // namespace\n", 3987 ShortInlineFunctions); 3988 verifyFormat("namespace {\n" 3989 " class X { // comment\n" 3990 " void f() { return; }\n" 3991 " };\n" 3992 "} // namespace\n", 3993 ShortInlineFunctions); 3994 verifyFormat("namespace {\n" 3995 " struct X {\n" 3996 " void f() { return; }\n" 3997 " };\n" 3998 "} // namespace\n", 3999 ShortInlineFunctions); 4000 verifyFormat("namespace {\n" 4001 " union X {\n" 4002 " void f() { return; }\n" 4003 " };\n" 4004 "} // namespace\n", 4005 ShortInlineFunctions); 4006 verifyFormat("extern \"C\" {\n" 4007 "void f() {\n" 4008 " return;\n" 4009 "}\n" 4010 "} // namespace\n", 4011 ShortInlineFunctions); 4012 verifyFormat("namespace {\n" 4013 " class X {\n" 4014 " void f() { return; }\n" 4015 " } x;\n" 4016 "} // namespace\n", 4017 ShortInlineFunctions); 4018 verifyFormat("namespace {\n" 4019 " [[nodiscard]] class X {\n" 4020 " void f() { return; }\n" 4021 " };\n" 4022 "} // namespace\n", 4023 ShortInlineFunctions); 4024 verifyFormat("namespace {\n" 4025 " static class X {\n" 4026 " void f() { return; }\n" 4027 " } x;\n" 4028 "} // namespace\n", 4029 ShortInlineFunctions); 4030 verifyFormat("namespace {\n" 4031 " constexpr class X {\n" 4032 " void f() { return; }\n" 4033 " } x;\n" 4034 "} // namespace\n", 4035 ShortInlineFunctions); 4036 4037 ShortInlineFunctions.IndentExternBlock = FormatStyle::IEBS_Indent; 4038 verifyFormat("extern \"C\" {\n" 4039 " void f() {\n" 4040 " return;\n" 4041 " }\n" 4042 "} // namespace\n", 4043 ShortInlineFunctions); 4044 4045 Style.NamespaceIndentation = FormatStyle::NI_Inner; 4046 EXPECT_EQ("namespace out {\n" 4047 "int i;\n" 4048 "namespace in {\n" 4049 " int i;\n" 4050 "} // namespace in\n" 4051 "} // namespace out", 4052 format("namespace out {\n" 4053 "int i;\n" 4054 "namespace in {\n" 4055 "int i;\n" 4056 "} // namespace in\n" 4057 "} // namespace out", 4058 Style)); 4059 4060 Style.NamespaceIndentation = FormatStyle::NI_None; 4061 verifyFormat("template <class T>\n" 4062 "concept a_concept = X<>;\n" 4063 "namespace B {\n" 4064 "struct b_struct {};\n" 4065 "} // namespace B\n", 4066 Style); 4067 verifyFormat("template <int I>\n" 4068 "constexpr void foo()\n" 4069 " requires(I == 42)\n" 4070 "{}\n" 4071 "namespace ns {\n" 4072 "void foo() {}\n" 4073 "} // namespace ns\n", 4074 Style); 4075 } 4076 4077 TEST_F(FormatTest, NamespaceMacros) { 4078 FormatStyle Style = getLLVMStyle(); 4079 Style.NamespaceMacros.push_back("TESTSUITE"); 4080 4081 verifyFormat("TESTSUITE(A) {\n" 4082 "int foo();\n" 4083 "} // TESTSUITE(A)", 4084 Style); 4085 4086 verifyFormat("TESTSUITE(A, B) {\n" 4087 "int foo();\n" 4088 "} // TESTSUITE(A)", 4089 Style); 4090 4091 // Properly indent according to NamespaceIndentation style 4092 Style.NamespaceIndentation = FormatStyle::NI_All; 4093 verifyFormat("TESTSUITE(A) {\n" 4094 " int foo();\n" 4095 "} // TESTSUITE(A)", 4096 Style); 4097 verifyFormat("TESTSUITE(A) {\n" 4098 " namespace B {\n" 4099 " int foo();\n" 4100 " } // namespace B\n" 4101 "} // TESTSUITE(A)", 4102 Style); 4103 verifyFormat("namespace A {\n" 4104 " TESTSUITE(B) {\n" 4105 " int foo();\n" 4106 " } // TESTSUITE(B)\n" 4107 "} // namespace A", 4108 Style); 4109 4110 Style.NamespaceIndentation = FormatStyle::NI_Inner; 4111 verifyFormat("TESTSUITE(A) {\n" 4112 "TESTSUITE(B) {\n" 4113 " int foo();\n" 4114 "} // TESTSUITE(B)\n" 4115 "} // TESTSUITE(A)", 4116 Style); 4117 verifyFormat("TESTSUITE(A) {\n" 4118 "namespace B {\n" 4119 " int foo();\n" 4120 "} // namespace B\n" 4121 "} // TESTSUITE(A)", 4122 Style); 4123 verifyFormat("namespace A {\n" 4124 "TESTSUITE(B) {\n" 4125 " int foo();\n" 4126 "} // TESTSUITE(B)\n" 4127 "} // namespace A", 4128 Style); 4129 4130 // Properly merge namespace-macros blocks in CompactNamespaces mode 4131 Style.NamespaceIndentation = FormatStyle::NI_None; 4132 Style.CompactNamespaces = true; 4133 verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n" 4134 "}} // TESTSUITE(A::B)", 4135 Style); 4136 4137 EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n" 4138 "}} // TESTSUITE(out::in)", 4139 format("TESTSUITE(out) {\n" 4140 "TESTSUITE(in) {\n" 4141 "} // TESTSUITE(in)\n" 4142 "} // TESTSUITE(out)", 4143 Style)); 4144 4145 EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n" 4146 "}} // TESTSUITE(out::in)", 4147 format("TESTSUITE(out) {\n" 4148 "TESTSUITE(in) {\n" 4149 "} // TESTSUITE(in)\n" 4150 "} // TESTSUITE(out)", 4151 Style)); 4152 4153 // Do not merge different namespaces/macros 4154 EXPECT_EQ("namespace out {\n" 4155 "TESTSUITE(in) {\n" 4156 "} // TESTSUITE(in)\n" 4157 "} // namespace out", 4158 format("namespace out {\n" 4159 "TESTSUITE(in) {\n" 4160 "} // TESTSUITE(in)\n" 4161 "} // namespace out", 4162 Style)); 4163 EXPECT_EQ("TESTSUITE(out) {\n" 4164 "namespace in {\n" 4165 "} // namespace in\n" 4166 "} // TESTSUITE(out)", 4167 format("TESTSUITE(out) {\n" 4168 "namespace in {\n" 4169 "} // namespace in\n" 4170 "} // TESTSUITE(out)", 4171 Style)); 4172 Style.NamespaceMacros.push_back("FOOBAR"); 4173 EXPECT_EQ("TESTSUITE(out) {\n" 4174 "FOOBAR(in) {\n" 4175 "} // FOOBAR(in)\n" 4176 "} // TESTSUITE(out)", 4177 format("TESTSUITE(out) {\n" 4178 "FOOBAR(in) {\n" 4179 "} // FOOBAR(in)\n" 4180 "} // TESTSUITE(out)", 4181 Style)); 4182 } 4183 4184 TEST_F(FormatTest, FormatsCompactNamespaces) { 4185 FormatStyle Style = getLLVMStyle(); 4186 Style.CompactNamespaces = true; 4187 Style.NamespaceMacros.push_back("TESTSUITE"); 4188 4189 verifyFormat("namespace A { namespace B {\n" 4190 "}} // namespace A::B", 4191 Style); 4192 4193 EXPECT_EQ("namespace out { namespace in {\n" 4194 "}} // namespace out::in", 4195 format("namespace out {\n" 4196 "namespace in {\n" 4197 "} // namespace in\n" 4198 "} // namespace out", 4199 Style)); 4200 4201 // Only namespaces which have both consecutive opening and end get compacted 4202 EXPECT_EQ("namespace out {\n" 4203 "namespace in1 {\n" 4204 "} // namespace in1\n" 4205 "namespace in2 {\n" 4206 "} // namespace in2\n" 4207 "} // namespace out", 4208 format("namespace out {\n" 4209 "namespace in1 {\n" 4210 "} // namespace in1\n" 4211 "namespace in2 {\n" 4212 "} // namespace in2\n" 4213 "} // namespace out", 4214 Style)); 4215 4216 EXPECT_EQ("namespace out {\n" 4217 "int i;\n" 4218 "namespace in {\n" 4219 "int j;\n" 4220 "} // namespace in\n" 4221 "int k;\n" 4222 "} // namespace out", 4223 format("namespace out { int i;\n" 4224 "namespace in { int j; } // namespace in\n" 4225 "int k; } // namespace out", 4226 Style)); 4227 4228 EXPECT_EQ("namespace A { namespace B { namespace C {\n" 4229 "}}} // namespace A::B::C\n", 4230 format("namespace A { namespace B {\n" 4231 "namespace C {\n" 4232 "}} // namespace B::C\n" 4233 "} // namespace A\n", 4234 Style)); 4235 4236 Style.ColumnLimit = 40; 4237 EXPECT_EQ("namespace aaaaaaaaaa {\n" 4238 "namespace bbbbbbbbbb {\n" 4239 "}} // namespace aaaaaaaaaa::bbbbbbbbbb", 4240 format("namespace aaaaaaaaaa {\n" 4241 "namespace bbbbbbbbbb {\n" 4242 "} // namespace bbbbbbbbbb\n" 4243 "} // namespace aaaaaaaaaa", 4244 Style)); 4245 4246 EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n" 4247 "namespace cccccc {\n" 4248 "}}} // namespace aaaaaa::bbbbbb::cccccc", 4249 format("namespace aaaaaa {\n" 4250 "namespace bbbbbb {\n" 4251 "namespace cccccc {\n" 4252 "} // namespace cccccc\n" 4253 "} // namespace bbbbbb\n" 4254 "} // namespace aaaaaa", 4255 Style)); 4256 Style.ColumnLimit = 80; 4257 4258 // Extra semicolon after 'inner' closing brace prevents merging 4259 EXPECT_EQ("namespace out { namespace in {\n" 4260 "}; } // namespace out::in", 4261 format("namespace out {\n" 4262 "namespace in {\n" 4263 "}; // namespace in\n" 4264 "} // namespace out", 4265 Style)); 4266 4267 // Extra semicolon after 'outer' closing brace is conserved 4268 EXPECT_EQ("namespace out { namespace in {\n" 4269 "}}; // namespace out::in", 4270 format("namespace out {\n" 4271 "namespace in {\n" 4272 "} // namespace in\n" 4273 "}; // namespace out", 4274 Style)); 4275 4276 Style.NamespaceIndentation = FormatStyle::NI_All; 4277 EXPECT_EQ("namespace out { namespace in {\n" 4278 " int i;\n" 4279 "}} // namespace out::in", 4280 format("namespace out {\n" 4281 "namespace in {\n" 4282 "int i;\n" 4283 "} // namespace in\n" 4284 "} // namespace out", 4285 Style)); 4286 EXPECT_EQ("namespace out { namespace mid {\n" 4287 " namespace in {\n" 4288 " int j;\n" 4289 " } // namespace in\n" 4290 " int k;\n" 4291 "}} // namespace out::mid", 4292 format("namespace out { namespace mid {\n" 4293 "namespace in { int j; } // namespace in\n" 4294 "int k; }} // namespace out::mid", 4295 Style)); 4296 4297 Style.NamespaceIndentation = FormatStyle::NI_Inner; 4298 EXPECT_EQ("namespace out { namespace in {\n" 4299 " int i;\n" 4300 "}} // namespace out::in", 4301 format("namespace out {\n" 4302 "namespace in {\n" 4303 "int i;\n" 4304 "} // namespace in\n" 4305 "} // namespace out", 4306 Style)); 4307 EXPECT_EQ("namespace out { namespace mid { namespace in {\n" 4308 " int i;\n" 4309 "}}} // namespace out::mid::in", 4310 format("namespace out {\n" 4311 "namespace mid {\n" 4312 "namespace in {\n" 4313 "int i;\n" 4314 "} // namespace in\n" 4315 "} // namespace mid\n" 4316 "} // namespace out", 4317 Style)); 4318 4319 Style.CompactNamespaces = true; 4320 Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 4321 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4322 Style.BraceWrapping.BeforeLambdaBody = true; 4323 verifyFormat("namespace out { namespace in {\n" 4324 "}} // namespace out::in", 4325 Style); 4326 EXPECT_EQ("namespace out { namespace in {\n" 4327 "}} // namespace out::in", 4328 format("namespace out {\n" 4329 "namespace in {\n" 4330 "} // namespace in\n" 4331 "} // namespace out", 4332 Style)); 4333 } 4334 4335 TEST_F(FormatTest, FormatsExternC) { 4336 verifyFormat("extern \"C\" {\nint a;"); 4337 verifyFormat("extern \"C\" {}"); 4338 verifyFormat("extern \"C\" {\n" 4339 "int foo();\n" 4340 "}"); 4341 verifyFormat("extern \"C\" int foo() {}"); 4342 verifyFormat("extern \"C\" int foo();"); 4343 verifyFormat("extern \"C\" int foo() {\n" 4344 " int i = 42;\n" 4345 " return i;\n" 4346 "}"); 4347 4348 FormatStyle Style = getLLVMStyle(); 4349 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4350 Style.BraceWrapping.AfterFunction = true; 4351 verifyFormat("extern \"C\" int foo() {}", Style); 4352 verifyFormat("extern \"C\" int foo();", Style); 4353 verifyFormat("extern \"C\" int foo()\n" 4354 "{\n" 4355 " int i = 42;\n" 4356 " return i;\n" 4357 "}", 4358 Style); 4359 4360 Style.BraceWrapping.AfterExternBlock = true; 4361 Style.BraceWrapping.SplitEmptyRecord = false; 4362 verifyFormat("extern \"C\"\n" 4363 "{}", 4364 Style); 4365 verifyFormat("extern \"C\"\n" 4366 "{\n" 4367 " int foo();\n" 4368 "}", 4369 Style); 4370 } 4371 4372 TEST_F(FormatTest, IndentExternBlockStyle) { 4373 FormatStyle Style = getLLVMStyle(); 4374 Style.IndentWidth = 2; 4375 4376 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4377 verifyFormat("extern \"C\" { /*9*/\n" 4378 "}", 4379 Style); 4380 verifyFormat("extern \"C\" {\n" 4381 " int foo10();\n" 4382 "}", 4383 Style); 4384 4385 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 4386 verifyFormat("extern \"C\" { /*11*/\n" 4387 "}", 4388 Style); 4389 verifyFormat("extern \"C\" {\n" 4390 "int foo12();\n" 4391 "}", 4392 Style); 4393 4394 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4395 Style.BraceWrapping.AfterExternBlock = true; 4396 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4397 verifyFormat("extern \"C\"\n" 4398 "{ /*13*/\n" 4399 "}", 4400 Style); 4401 verifyFormat("extern \"C\"\n{\n" 4402 " int foo14();\n" 4403 "}", 4404 Style); 4405 4406 Style.BraceWrapping.AfterExternBlock = false; 4407 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 4408 verifyFormat("extern \"C\" { /*15*/\n" 4409 "}", 4410 Style); 4411 verifyFormat("extern \"C\" {\n" 4412 "int foo16();\n" 4413 "}", 4414 Style); 4415 4416 Style.BraceWrapping.AfterExternBlock = true; 4417 verifyFormat("extern \"C\"\n" 4418 "{ /*13*/\n" 4419 "}", 4420 Style); 4421 verifyFormat("extern \"C\"\n" 4422 "{\n" 4423 "int foo14();\n" 4424 "}", 4425 Style); 4426 4427 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4428 verifyFormat("extern \"C\"\n" 4429 "{ /*13*/\n" 4430 "}", 4431 Style); 4432 verifyFormat("extern \"C\"\n" 4433 "{\n" 4434 " int foo14();\n" 4435 "}", 4436 Style); 4437 } 4438 4439 TEST_F(FormatTest, FormatsInlineASM) { 4440 verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));"); 4441 verifyFormat("asm(\"nop\" ::: \"memory\");"); 4442 verifyFormat( 4443 "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n" 4444 " \"cpuid\\n\\t\"\n" 4445 " \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n" 4446 " : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n" 4447 " : \"a\"(value));"); 4448 EXPECT_EQ( 4449 "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n" 4450 " __asm {\n" 4451 " mov edx,[that] // vtable in edx\n" 4452 " mov eax,methodIndex\n" 4453 " call [edx][eax*4] // stdcall\n" 4454 " }\n" 4455 "}", 4456 format("void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n" 4457 " __asm {\n" 4458 " mov edx,[that] // vtable in edx\n" 4459 " mov eax,methodIndex\n" 4460 " call [edx][eax*4] // stdcall\n" 4461 " }\n" 4462 "}")); 4463 EXPECT_EQ("_asm {\n" 4464 " xor eax, eax;\n" 4465 " cpuid;\n" 4466 "}", 4467 format("_asm {\n" 4468 " xor eax, eax;\n" 4469 " cpuid;\n" 4470 "}")); 4471 verifyFormat("void function() {\n" 4472 " // comment\n" 4473 " asm(\"\");\n" 4474 "}"); 4475 EXPECT_EQ("__asm {\n" 4476 "}\n" 4477 "int i;", 4478 format("__asm {\n" 4479 "}\n" 4480 "int i;")); 4481 } 4482 4483 TEST_F(FormatTest, FormatTryCatch) { 4484 verifyFormat("try {\n" 4485 " throw a * b;\n" 4486 "} catch (int a) {\n" 4487 " // Do nothing.\n" 4488 "} catch (...) {\n" 4489 " exit(42);\n" 4490 "}"); 4491 4492 // Function-level try statements. 4493 verifyFormat("int f() try { return 4; } catch (...) {\n" 4494 " return 5;\n" 4495 "}"); 4496 verifyFormat("class A {\n" 4497 " int a;\n" 4498 " A() try : a(0) {\n" 4499 " } catch (...) {\n" 4500 " throw;\n" 4501 " }\n" 4502 "};\n"); 4503 verifyFormat("class A {\n" 4504 " int a;\n" 4505 " A() try : a(0), b{1} {\n" 4506 " } catch (...) {\n" 4507 " throw;\n" 4508 " }\n" 4509 "};\n"); 4510 verifyFormat("class A {\n" 4511 " int a;\n" 4512 " A() try : a(0), b{1}, c{2} {\n" 4513 " } catch (...) {\n" 4514 " throw;\n" 4515 " }\n" 4516 "};\n"); 4517 verifyFormat("class A {\n" 4518 " int a;\n" 4519 " A() try : a(0), b{1}, c{2} {\n" 4520 " { // New scope.\n" 4521 " }\n" 4522 " } catch (...) {\n" 4523 " throw;\n" 4524 " }\n" 4525 "};\n"); 4526 4527 // Incomplete try-catch blocks. 4528 verifyIncompleteFormat("try {} catch ("); 4529 } 4530 4531 TEST_F(FormatTest, FormatTryAsAVariable) { 4532 verifyFormat("int try;"); 4533 verifyFormat("int try, size;"); 4534 verifyFormat("try = foo();"); 4535 verifyFormat("if (try < size) {\n return true;\n}"); 4536 4537 verifyFormat("int catch;"); 4538 verifyFormat("int catch, size;"); 4539 verifyFormat("catch = foo();"); 4540 verifyFormat("if (catch < size) {\n return true;\n}"); 4541 4542 FormatStyle Style = getLLVMStyle(); 4543 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4544 Style.BraceWrapping.AfterFunction = true; 4545 Style.BraceWrapping.BeforeCatch = true; 4546 verifyFormat("try {\n" 4547 " int bar = 1;\n" 4548 "}\n" 4549 "catch (...) {\n" 4550 " int bar = 1;\n" 4551 "}", 4552 Style); 4553 verifyFormat("#if NO_EX\n" 4554 "try\n" 4555 "#endif\n" 4556 "{\n" 4557 "}\n" 4558 "#if NO_EX\n" 4559 "catch (...) {\n" 4560 "}", 4561 Style); 4562 verifyFormat("try /* abc */ {\n" 4563 " int bar = 1;\n" 4564 "}\n" 4565 "catch (...) {\n" 4566 " int bar = 1;\n" 4567 "}", 4568 Style); 4569 verifyFormat("try\n" 4570 "// abc\n" 4571 "{\n" 4572 " int bar = 1;\n" 4573 "}\n" 4574 "catch (...) {\n" 4575 " int bar = 1;\n" 4576 "}", 4577 Style); 4578 } 4579 4580 TEST_F(FormatTest, FormatSEHTryCatch) { 4581 verifyFormat("__try {\n" 4582 " int a = b * c;\n" 4583 "} __except (EXCEPTION_EXECUTE_HANDLER) {\n" 4584 " // Do nothing.\n" 4585 "}"); 4586 4587 verifyFormat("__try {\n" 4588 " int a = b * c;\n" 4589 "} __finally {\n" 4590 " // Do nothing.\n" 4591 "}"); 4592 4593 verifyFormat("DEBUG({\n" 4594 " __try {\n" 4595 " } __finally {\n" 4596 " }\n" 4597 "});\n"); 4598 } 4599 4600 TEST_F(FormatTest, IncompleteTryCatchBlocks) { 4601 verifyFormat("try {\n" 4602 " f();\n" 4603 "} catch {\n" 4604 " g();\n" 4605 "}"); 4606 verifyFormat("try {\n" 4607 " f();\n" 4608 "} catch (A a) MACRO(x) {\n" 4609 " g();\n" 4610 "} catch (B b) MACRO(x) {\n" 4611 " g();\n" 4612 "}"); 4613 } 4614 4615 TEST_F(FormatTest, FormatTryCatchBraceStyles) { 4616 FormatStyle Style = getLLVMStyle(); 4617 for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla, 4618 FormatStyle::BS_WebKit}) { 4619 Style.BreakBeforeBraces = BraceStyle; 4620 verifyFormat("try {\n" 4621 " // something\n" 4622 "} catch (...) {\n" 4623 " // something\n" 4624 "}", 4625 Style); 4626 } 4627 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 4628 verifyFormat("try {\n" 4629 " // something\n" 4630 "}\n" 4631 "catch (...) {\n" 4632 " // something\n" 4633 "}", 4634 Style); 4635 verifyFormat("__try {\n" 4636 " // something\n" 4637 "}\n" 4638 "__finally {\n" 4639 " // something\n" 4640 "}", 4641 Style); 4642 verifyFormat("@try {\n" 4643 " // something\n" 4644 "}\n" 4645 "@finally {\n" 4646 " // something\n" 4647 "}", 4648 Style); 4649 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 4650 verifyFormat("try\n" 4651 "{\n" 4652 " // something\n" 4653 "}\n" 4654 "catch (...)\n" 4655 "{\n" 4656 " // something\n" 4657 "}", 4658 Style); 4659 Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 4660 verifyFormat("try\n" 4661 " {\n" 4662 " // something white\n" 4663 " }\n" 4664 "catch (...)\n" 4665 " {\n" 4666 " // something white\n" 4667 " }", 4668 Style); 4669 Style.BreakBeforeBraces = FormatStyle::BS_GNU; 4670 verifyFormat("try\n" 4671 " {\n" 4672 " // something\n" 4673 " }\n" 4674 "catch (...)\n" 4675 " {\n" 4676 " // something\n" 4677 " }", 4678 Style); 4679 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4680 Style.BraceWrapping.BeforeCatch = true; 4681 verifyFormat("try {\n" 4682 " // something\n" 4683 "}\n" 4684 "catch (...) {\n" 4685 " // something\n" 4686 "}", 4687 Style); 4688 } 4689 4690 TEST_F(FormatTest, StaticInitializers) { 4691 verifyFormat("static SomeClass SC = {1, 'a'};"); 4692 4693 verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n" 4694 " 100000000, " 4695 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};"); 4696 4697 // Here, everything other than the "}" would fit on a line. 4698 verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n" 4699 " 10000000000000000000000000};"); 4700 EXPECT_EQ("S s = {a,\n" 4701 "\n" 4702 " b};", 4703 format("S s = {\n" 4704 " a,\n" 4705 "\n" 4706 " b\n" 4707 "};")); 4708 4709 // FIXME: This would fit into the column limit if we'd fit "{ {" on the first 4710 // line. However, the formatting looks a bit off and this probably doesn't 4711 // happen often in practice. 4712 verifyFormat("static int Variable[1] = {\n" 4713 " {1000000000000000000000000000000000000}};", 4714 getLLVMStyleWithColumns(40)); 4715 } 4716 4717 TEST_F(FormatTest, DesignatedInitializers) { 4718 verifyFormat("const struct A a = {.a = 1, .b = 2};"); 4719 verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n" 4720 " .bbbbbbbbbb = 2,\n" 4721 " .cccccccccc = 3,\n" 4722 " .dddddddddd = 4,\n" 4723 " .eeeeeeeeee = 5};"); 4724 verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n" 4725 " .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n" 4726 " .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n" 4727 " .ccccccccccccccccccccccccccc = 3,\n" 4728 " .ddddddddddddddddddddddddddd = 4,\n" 4729 " .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};"); 4730 4731 verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};"); 4732 4733 verifyFormat("const struct A a = {[0] = 1, [1] = 2};"); 4734 verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n" 4735 " [2] = bbbbbbbbbb,\n" 4736 " [3] = cccccccccc,\n" 4737 " [4] = dddddddddd,\n" 4738 " [5] = eeeeeeeeee};"); 4739 verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n" 4740 " [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 4741 " [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 4742 " [3] = cccccccccccccccccccccccccccccccccccccc,\n" 4743 " [4] = dddddddddddddddddddddddddddddddddddddd,\n" 4744 " [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};"); 4745 } 4746 4747 TEST_F(FormatTest, NestedStaticInitializers) { 4748 verifyFormat("static A x = {{{}}};\n"); 4749 verifyFormat("static A x = {{{init1, init2, init3, init4},\n" 4750 " {init1, init2, init3, init4}}};", 4751 getLLVMStyleWithColumns(50)); 4752 4753 verifyFormat("somes Status::global_reps[3] = {\n" 4754 " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n" 4755 " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n" 4756 " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};", 4757 getLLVMStyleWithColumns(60)); 4758 verifyGoogleFormat("SomeType Status::global_reps[3] = {\n" 4759 " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n" 4760 " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n" 4761 " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};"); 4762 verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n" 4763 " {rect.fRight - rect.fLeft, rect.fBottom - " 4764 "rect.fTop}};"); 4765 4766 verifyFormat( 4767 "SomeArrayOfSomeType a = {\n" 4768 " {{1, 2, 3},\n" 4769 " {1, 2, 3},\n" 4770 " {111111111111111111111111111111, 222222222222222222222222222222,\n" 4771 " 333333333333333333333333333333},\n" 4772 " {1, 2, 3},\n" 4773 " {1, 2, 3}}};"); 4774 verifyFormat( 4775 "SomeArrayOfSomeType a = {\n" 4776 " {{1, 2, 3}},\n" 4777 " {{1, 2, 3}},\n" 4778 " {{111111111111111111111111111111, 222222222222222222222222222222,\n" 4779 " 333333333333333333333333333333}},\n" 4780 " {{1, 2, 3}},\n" 4781 " {{1, 2, 3}}};"); 4782 4783 verifyFormat("struct {\n" 4784 " unsigned bit;\n" 4785 " const char *const name;\n" 4786 "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n" 4787 " {kOsWin, \"Windows\"},\n" 4788 " {kOsLinux, \"Linux\"},\n" 4789 " {kOsCrOS, \"Chrome OS\"}};"); 4790 verifyFormat("struct {\n" 4791 " unsigned bit;\n" 4792 " const char *const name;\n" 4793 "} kBitsToOs[] = {\n" 4794 " {kOsMac, \"Mac\"},\n" 4795 " {kOsWin, \"Windows\"},\n" 4796 " {kOsLinux, \"Linux\"},\n" 4797 " {kOsCrOS, \"Chrome OS\"},\n" 4798 "};"); 4799 } 4800 4801 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) { 4802 verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro(" 4803 " \\\n" 4804 " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)"); 4805 } 4806 4807 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) { 4808 verifyFormat("virtual void write(ELFWriter *writerrr,\n" 4809 " OwningPtr<FileOutputBuffer> &buffer) = 0;"); 4810 4811 // Do break defaulted and deleted functions. 4812 verifyFormat("virtual void ~Deeeeeeeestructor() =\n" 4813 " default;", 4814 getLLVMStyleWithColumns(40)); 4815 verifyFormat("virtual void ~Deeeeeeeestructor() =\n" 4816 " delete;", 4817 getLLVMStyleWithColumns(40)); 4818 } 4819 4820 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) { 4821 verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3", 4822 getLLVMStyleWithColumns(40)); 4823 verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"", 4824 getLLVMStyleWithColumns(40)); 4825 EXPECT_EQ("#define Q \\\n" 4826 " \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\" \\\n" 4827 " \"aaaaaaaa.cpp\"", 4828 format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"", 4829 getLLVMStyleWithColumns(40))); 4830 } 4831 4832 TEST_F(FormatTest, UnderstandsLinePPDirective) { 4833 EXPECT_EQ("# 123 \"A string literal\"", 4834 format(" # 123 \"A string literal\"")); 4835 } 4836 4837 TEST_F(FormatTest, LayoutUnknownPPDirective) { 4838 EXPECT_EQ("#;", format("#;")); 4839 verifyFormat("#\n;\n;\n;"); 4840 } 4841 4842 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) { 4843 EXPECT_EQ("#line 42 \"test\"\n", 4844 format("# \\\n line \\\n 42 \\\n \"test\"\n")); 4845 EXPECT_EQ("#define A B\n", format("# \\\n define \\\n A \\\n B\n", 4846 getLLVMStyleWithColumns(12))); 4847 } 4848 4849 TEST_F(FormatTest, EndOfFileEndsPPDirective) { 4850 EXPECT_EQ("#line 42 \"test\"", 4851 format("# \\\n line \\\n 42 \\\n \"test\"")); 4852 EXPECT_EQ("#define A B", format("# \\\n define \\\n A \\\n B")); 4853 } 4854 4855 TEST_F(FormatTest, DoesntRemoveUnknownTokens) { 4856 verifyFormat("#define A \\x20"); 4857 verifyFormat("#define A \\ x20"); 4858 EXPECT_EQ("#define A \\ x20", format("#define A \\ x20")); 4859 verifyFormat("#define A ''"); 4860 verifyFormat("#define A ''qqq"); 4861 verifyFormat("#define A `qqq"); 4862 verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");"); 4863 EXPECT_EQ("const char *c = STRINGIFY(\n" 4864 "\\na : b);", 4865 format("const char * c = STRINGIFY(\n" 4866 "\\na : b);")); 4867 4868 verifyFormat("a\r\\"); 4869 verifyFormat("a\v\\"); 4870 verifyFormat("a\f\\"); 4871 } 4872 4873 TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) { 4874 FormatStyle style = getChromiumStyle(FormatStyle::LK_Cpp); 4875 style.IndentWidth = 4; 4876 style.PPIndentWidth = 1; 4877 4878 style.IndentPPDirectives = FormatStyle::PPDIS_None; 4879 verifyFormat("#ifdef __linux__\n" 4880 "void foo() {\n" 4881 " int x = 0;\n" 4882 "}\n" 4883 "#define FOO\n" 4884 "#endif\n" 4885 "void bar() {\n" 4886 " int y = 0;\n" 4887 "}\n", 4888 style); 4889 4890 style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash; 4891 verifyFormat("#ifdef __linux__\n" 4892 "void foo() {\n" 4893 " int x = 0;\n" 4894 "}\n" 4895 "# define FOO foo\n" 4896 "#endif\n" 4897 "void bar() {\n" 4898 " int y = 0;\n" 4899 "}\n", 4900 style); 4901 4902 style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash; 4903 verifyFormat("#ifdef __linux__\n" 4904 "void foo() {\n" 4905 " int x = 0;\n" 4906 "}\n" 4907 " #define FOO foo\n" 4908 "#endif\n" 4909 "void bar() {\n" 4910 " int y = 0;\n" 4911 "}\n", 4912 style); 4913 } 4914 4915 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) { 4916 verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13)); 4917 verifyFormat("#define A( \\\n BB)", getLLVMStyleWithColumns(12)); 4918 verifyFormat("#define A( \\\n A, B)", getLLVMStyleWithColumns(12)); 4919 // FIXME: We never break before the macro name. 4920 verifyFormat("#define AA( \\\n B)", getLLVMStyleWithColumns(12)); 4921 4922 verifyFormat("#define A A\n#define A A"); 4923 verifyFormat("#define A(X) A\n#define A A"); 4924 4925 verifyFormat("#define Something Other", getLLVMStyleWithColumns(23)); 4926 verifyFormat("#define Something \\\n Other", getLLVMStyleWithColumns(22)); 4927 } 4928 4929 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) { 4930 EXPECT_EQ("// somecomment\n" 4931 "#include \"a.h\"\n" 4932 "#define A( \\\n" 4933 " A, B)\n" 4934 "#include \"b.h\"\n" 4935 "// somecomment\n", 4936 format(" // somecomment\n" 4937 " #include \"a.h\"\n" 4938 "#define A(A,\\\n" 4939 " B)\n" 4940 " #include \"b.h\"\n" 4941 " // somecomment\n", 4942 getLLVMStyleWithColumns(13))); 4943 } 4944 4945 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); } 4946 4947 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) { 4948 EXPECT_EQ("#define A \\\n" 4949 " c; \\\n" 4950 " e;\n" 4951 "f;", 4952 format("#define A c; e;\n" 4953 "f;", 4954 getLLVMStyleWithColumns(14))); 4955 } 4956 4957 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); } 4958 4959 TEST_F(FormatTest, MacroDefinitionInsideStatement) { 4960 EXPECT_EQ("int x,\n" 4961 "#define A\n" 4962 " y;", 4963 format("int x,\n#define A\ny;")); 4964 } 4965 4966 TEST_F(FormatTest, HashInMacroDefinition) { 4967 EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle())); 4968 EXPECT_EQ("#define A(c) u#c", format("#define A(c) u#c", getLLVMStyle())); 4969 EXPECT_EQ("#define A(c) U#c", format("#define A(c) U#c", getLLVMStyle())); 4970 EXPECT_EQ("#define A(c) u8#c", format("#define A(c) u8#c", getLLVMStyle())); 4971 EXPECT_EQ("#define A(c) LR#c", format("#define A(c) LR#c", getLLVMStyle())); 4972 EXPECT_EQ("#define A(c) uR#c", format("#define A(c) uR#c", getLLVMStyle())); 4973 EXPECT_EQ("#define A(c) UR#c", format("#define A(c) UR#c", getLLVMStyle())); 4974 EXPECT_EQ("#define A(c) u8R#c", format("#define A(c) u8R#c", getLLVMStyle())); 4975 verifyFormat("#define A \\\n b #c;", getLLVMStyleWithColumns(11)); 4976 verifyFormat("#define A \\\n" 4977 " { \\\n" 4978 " f(#c); \\\n" 4979 " }", 4980 getLLVMStyleWithColumns(11)); 4981 4982 verifyFormat("#define A(X) \\\n" 4983 " void function##X()", 4984 getLLVMStyleWithColumns(22)); 4985 4986 verifyFormat("#define A(a, b, c) \\\n" 4987 " void a##b##c()", 4988 getLLVMStyleWithColumns(22)); 4989 4990 verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22)); 4991 } 4992 4993 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) { 4994 EXPECT_EQ("#define A (x)", format("#define A (x)")); 4995 EXPECT_EQ("#define A(x)", format("#define A(x)")); 4996 4997 FormatStyle Style = getLLVMStyle(); 4998 Style.SpaceBeforeParens = FormatStyle::SBPO_Never; 4999 verifyFormat("#define true ((foo)1)", Style); 5000 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 5001 verifyFormat("#define false((foo)0)", Style); 5002 } 5003 5004 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) { 5005 EXPECT_EQ("#define A b;", format("#define A \\\n" 5006 " \\\n" 5007 " b;", 5008 getLLVMStyleWithColumns(25))); 5009 EXPECT_EQ("#define A \\\n" 5010 " \\\n" 5011 " a; \\\n" 5012 " b;", 5013 format("#define A \\\n" 5014 " \\\n" 5015 " a; \\\n" 5016 " b;", 5017 getLLVMStyleWithColumns(11))); 5018 EXPECT_EQ("#define A \\\n" 5019 " a; \\\n" 5020 " \\\n" 5021 " b;", 5022 format("#define A \\\n" 5023 " a; \\\n" 5024 " \\\n" 5025 " b;", 5026 getLLVMStyleWithColumns(11))); 5027 } 5028 5029 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) { 5030 verifyIncompleteFormat("#define A :"); 5031 verifyFormat("#define SOMECASES \\\n" 5032 " case 1: \\\n" 5033 " case 2\n", 5034 getLLVMStyleWithColumns(20)); 5035 verifyFormat("#define MACRO(a) \\\n" 5036 " if (a) \\\n" 5037 " f(); \\\n" 5038 " else \\\n" 5039 " g()", 5040 getLLVMStyleWithColumns(18)); 5041 verifyFormat("#define A template <typename T>"); 5042 verifyIncompleteFormat("#define STR(x) #x\n" 5043 "f(STR(this_is_a_string_literal{));"); 5044 verifyFormat("#pragma omp threadprivate( \\\n" 5045 " y)), // expected-warning", 5046 getLLVMStyleWithColumns(28)); 5047 verifyFormat("#d, = };"); 5048 verifyFormat("#if \"a"); 5049 verifyIncompleteFormat("({\n" 5050 "#define b \\\n" 5051 " } \\\n" 5052 " a\n" 5053 "a", 5054 getLLVMStyleWithColumns(15)); 5055 verifyFormat("#define A \\\n" 5056 " { \\\n" 5057 " {\n" 5058 "#define B \\\n" 5059 " } \\\n" 5060 " }", 5061 getLLVMStyleWithColumns(15)); 5062 verifyNoCrash("#if a\na(\n#else\n#endif\n{a"); 5063 verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}"); 5064 verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};"); 5065 verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() { \n)}"); 5066 } 5067 5068 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) { 5069 verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline. 5070 EXPECT_EQ("class A : public QObject {\n" 5071 " Q_OBJECT\n" 5072 "\n" 5073 " A() {}\n" 5074 "};", 5075 format("class A : public QObject {\n" 5076 " Q_OBJECT\n" 5077 "\n" 5078 " A() {\n}\n" 5079 "} ;")); 5080 EXPECT_EQ("MACRO\n" 5081 "/*static*/ int i;", 5082 format("MACRO\n" 5083 " /*static*/ int i;")); 5084 EXPECT_EQ("SOME_MACRO\n" 5085 "namespace {\n" 5086 "void f();\n" 5087 "} // namespace", 5088 format("SOME_MACRO\n" 5089 " namespace {\n" 5090 "void f( );\n" 5091 "} // namespace")); 5092 // Only if the identifier contains at least 5 characters. 5093 EXPECT_EQ("HTTP f();", format("HTTP\nf();")); 5094 EXPECT_EQ("MACRO\nf();", format("MACRO\nf();")); 5095 // Only if everything is upper case. 5096 EXPECT_EQ("class A : public QObject {\n" 5097 " Q_Object A() {}\n" 5098 "};", 5099 format("class A : public QObject {\n" 5100 " Q_Object\n" 5101 " A() {\n}\n" 5102 "} ;")); 5103 5104 // Only if the next line can actually start an unwrapped line. 5105 EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;", 5106 format("SOME_WEIRD_LOG_MACRO\n" 5107 "<< SomeThing;")); 5108 5109 verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), " 5110 "(n, buffers))\n", 5111 getChromiumStyle(FormatStyle::LK_Cpp)); 5112 5113 // See PR41483 5114 EXPECT_EQ("/**/ FOO(a)\n" 5115 "FOO(b)", 5116 format("/**/ FOO(a)\n" 5117 "FOO(b)")); 5118 } 5119 5120 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) { 5121 EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n" 5122 "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n" 5123 "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n" 5124 "class X {};\n" 5125 "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n" 5126 "int *createScopDetectionPass() { return 0; }", 5127 format(" INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n" 5128 " INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n" 5129 " INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n" 5130 " class X {};\n" 5131 " INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n" 5132 " int *createScopDetectionPass() { return 0; }")); 5133 // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as 5134 // braces, so that inner block is indented one level more. 5135 EXPECT_EQ("int q() {\n" 5136 " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n" 5137 " IPC_MESSAGE_HANDLER(xxx, qqq)\n" 5138 " IPC_END_MESSAGE_MAP()\n" 5139 "}", 5140 format("int q() {\n" 5141 " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n" 5142 " IPC_MESSAGE_HANDLER(xxx, qqq)\n" 5143 " IPC_END_MESSAGE_MAP()\n" 5144 "}")); 5145 5146 // Same inside macros. 5147 EXPECT_EQ("#define LIST(L) \\\n" 5148 " L(A) \\\n" 5149 " L(B) \\\n" 5150 " L(C)", 5151 format("#define LIST(L) \\\n" 5152 " L(A) \\\n" 5153 " L(B) \\\n" 5154 " L(C)", 5155 getGoogleStyle())); 5156 5157 // These must not be recognized as macros. 5158 EXPECT_EQ("int q() {\n" 5159 " f(x);\n" 5160 " f(x) {}\n" 5161 " f(x)->g();\n" 5162 " f(x)->*g();\n" 5163 " f(x).g();\n" 5164 " f(x) = x;\n" 5165 " f(x) += x;\n" 5166 " f(x) -= x;\n" 5167 " f(x) *= x;\n" 5168 " f(x) /= x;\n" 5169 " f(x) %= x;\n" 5170 " f(x) &= x;\n" 5171 " f(x) |= x;\n" 5172 " f(x) ^= x;\n" 5173 " f(x) >>= x;\n" 5174 " f(x) <<= x;\n" 5175 " f(x)[y].z();\n" 5176 " LOG(INFO) << x;\n" 5177 " ifstream(x) >> x;\n" 5178 "}\n", 5179 format("int q() {\n" 5180 " f(x)\n;\n" 5181 " f(x)\n {}\n" 5182 " f(x)\n->g();\n" 5183 " f(x)\n->*g();\n" 5184 " f(x)\n.g();\n" 5185 " f(x)\n = x;\n" 5186 " f(x)\n += x;\n" 5187 " f(x)\n -= x;\n" 5188 " f(x)\n *= x;\n" 5189 " f(x)\n /= x;\n" 5190 " f(x)\n %= x;\n" 5191 " f(x)\n &= x;\n" 5192 " f(x)\n |= x;\n" 5193 " f(x)\n ^= x;\n" 5194 " f(x)\n >>= x;\n" 5195 " f(x)\n <<= x;\n" 5196 " f(x)\n[y].z();\n" 5197 " LOG(INFO)\n << x;\n" 5198 " ifstream(x)\n >> x;\n" 5199 "}\n")); 5200 EXPECT_EQ("int q() {\n" 5201 " F(x)\n" 5202 " if (1) {\n" 5203 " }\n" 5204 " F(x)\n" 5205 " while (1) {\n" 5206 " }\n" 5207 " F(x)\n" 5208 " G(x);\n" 5209 " F(x)\n" 5210 " try {\n" 5211 " Q();\n" 5212 " } catch (...) {\n" 5213 " }\n" 5214 "}\n", 5215 format("int q() {\n" 5216 "F(x)\n" 5217 "if (1) {}\n" 5218 "F(x)\n" 5219 "while (1) {}\n" 5220 "F(x)\n" 5221 "G(x);\n" 5222 "F(x)\n" 5223 "try { Q(); } catch (...) {}\n" 5224 "}\n")); 5225 EXPECT_EQ("class A {\n" 5226 " A() : t(0) {}\n" 5227 " A(int i) noexcept() : {}\n" 5228 " A(X x)\n" // FIXME: function-level try blocks are broken. 5229 " try : t(0) {\n" 5230 " } catch (...) {\n" 5231 " }\n" 5232 "};", 5233 format("class A {\n" 5234 " A()\n : t(0) {}\n" 5235 " A(int i)\n noexcept() : {}\n" 5236 " A(X x)\n" 5237 " try : t(0) {} catch (...) {}\n" 5238 "};")); 5239 FormatStyle Style = getLLVMStyle(); 5240 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 5241 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 5242 Style.BraceWrapping.AfterFunction = true; 5243 EXPECT_EQ("void f()\n" 5244 "try\n" 5245 "{\n" 5246 "}", 5247 format("void f() try {\n" 5248 "}", 5249 Style)); 5250 EXPECT_EQ("class SomeClass {\n" 5251 "public:\n" 5252 " SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5253 "};", 5254 format("class SomeClass {\n" 5255 "public:\n" 5256 " SomeClass()\n" 5257 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5258 "};")); 5259 EXPECT_EQ("class SomeClass {\n" 5260 "public:\n" 5261 " SomeClass()\n" 5262 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5263 "};", 5264 format("class SomeClass {\n" 5265 "public:\n" 5266 " SomeClass()\n" 5267 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5268 "};", 5269 getLLVMStyleWithColumns(40))); 5270 5271 verifyFormat("MACRO(>)"); 5272 5273 // Some macros contain an implicit semicolon. 5274 Style = getLLVMStyle(); 5275 Style.StatementMacros.push_back("FOO"); 5276 verifyFormat("FOO(a) int b = 0;"); 5277 verifyFormat("FOO(a)\n" 5278 "int b = 0;", 5279 Style); 5280 verifyFormat("FOO(a);\n" 5281 "int b = 0;", 5282 Style); 5283 verifyFormat("FOO(argc, argv, \"4.0.2\")\n" 5284 "int b = 0;", 5285 Style); 5286 verifyFormat("FOO()\n" 5287 "int b = 0;", 5288 Style); 5289 verifyFormat("FOO\n" 5290 "int b = 0;", 5291 Style); 5292 verifyFormat("void f() {\n" 5293 " FOO(a)\n" 5294 " return a;\n" 5295 "}", 5296 Style); 5297 verifyFormat("FOO(a)\n" 5298 "FOO(b)", 5299 Style); 5300 verifyFormat("int a = 0;\n" 5301 "FOO(b)\n" 5302 "int c = 0;", 5303 Style); 5304 verifyFormat("int a = 0;\n" 5305 "int x = FOO(a)\n" 5306 "int b = 0;", 5307 Style); 5308 verifyFormat("void foo(int a) { FOO(a) }\n" 5309 "uint32_t bar() {}", 5310 Style); 5311 } 5312 5313 TEST_F(FormatTest, FormatsMacrosWithZeroColumnWidth) { 5314 FormatStyle ZeroColumn = getLLVMStyleWithColumns(0); 5315 5316 verifyFormat("#define A LOOOOOOOOOOOOOOOOOOONG() LOOOOOOOOOOOOOOOOOOONG()", 5317 ZeroColumn); 5318 } 5319 5320 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) { 5321 verifyFormat("#define A \\\n" 5322 " f({ \\\n" 5323 " g(); \\\n" 5324 " });", 5325 getLLVMStyleWithColumns(11)); 5326 } 5327 5328 TEST_F(FormatTest, IndentPreprocessorDirectives) { 5329 FormatStyle Style = getLLVMStyleWithColumns(40); 5330 Style.IndentPPDirectives = FormatStyle::PPDIS_None; 5331 verifyFormat("#ifdef _WIN32\n" 5332 "#define A 0\n" 5333 "#ifdef VAR2\n" 5334 "#define B 1\n" 5335 "#include <someheader.h>\n" 5336 "#define MACRO \\\n" 5337 " some_very_long_func_aaaaaaaaaa();\n" 5338 "#endif\n" 5339 "#else\n" 5340 "#define A 1\n" 5341 "#endif", 5342 Style); 5343 Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash; 5344 verifyFormat("#ifdef _WIN32\n" 5345 "# define A 0\n" 5346 "# ifdef VAR2\n" 5347 "# define B 1\n" 5348 "# include <someheader.h>\n" 5349 "# define MACRO \\\n" 5350 " some_very_long_func_aaaaaaaaaa();\n" 5351 "# endif\n" 5352 "#else\n" 5353 "# define A 1\n" 5354 "#endif", 5355 Style); 5356 verifyFormat("#if A\n" 5357 "# define MACRO \\\n" 5358 " void a(int x) { \\\n" 5359 " b(); \\\n" 5360 " c(); \\\n" 5361 " d(); \\\n" 5362 " e(); \\\n" 5363 " f(); \\\n" 5364 " }\n" 5365 "#endif", 5366 Style); 5367 // Comments before include guard. 5368 verifyFormat("// file comment\n" 5369 "// file comment\n" 5370 "#ifndef HEADER_H\n" 5371 "#define HEADER_H\n" 5372 "code();\n" 5373 "#endif", 5374 Style); 5375 // Test with include guards. 5376 verifyFormat("#ifndef HEADER_H\n" 5377 "#define HEADER_H\n" 5378 "code();\n" 5379 "#endif", 5380 Style); 5381 // Include guards must have a #define with the same variable immediately 5382 // after #ifndef. 5383 verifyFormat("#ifndef NOT_GUARD\n" 5384 "# define FOO\n" 5385 "code();\n" 5386 "#endif", 5387 Style); 5388 5389 // Include guards must cover the entire file. 5390 verifyFormat("code();\n" 5391 "code();\n" 5392 "#ifndef NOT_GUARD\n" 5393 "# define NOT_GUARD\n" 5394 "code();\n" 5395 "#endif", 5396 Style); 5397 verifyFormat("#ifndef NOT_GUARD\n" 5398 "# define NOT_GUARD\n" 5399 "code();\n" 5400 "#endif\n" 5401 "code();", 5402 Style); 5403 // Test with trailing blank lines. 5404 verifyFormat("#ifndef HEADER_H\n" 5405 "#define HEADER_H\n" 5406 "code();\n" 5407 "#endif\n", 5408 Style); 5409 // Include guards don't have #else. 5410 verifyFormat("#ifndef NOT_GUARD\n" 5411 "# define NOT_GUARD\n" 5412 "code();\n" 5413 "#else\n" 5414 "#endif", 5415 Style); 5416 verifyFormat("#ifndef NOT_GUARD\n" 5417 "# define NOT_GUARD\n" 5418 "code();\n" 5419 "#elif FOO\n" 5420 "#endif", 5421 Style); 5422 // Non-identifier #define after potential include guard. 5423 verifyFormat("#ifndef FOO\n" 5424 "# define 1\n" 5425 "#endif\n", 5426 Style); 5427 // #if closes past last non-preprocessor line. 5428 verifyFormat("#ifndef FOO\n" 5429 "#define FOO\n" 5430 "#if 1\n" 5431 "int i;\n" 5432 "# define A 0\n" 5433 "#endif\n" 5434 "#endif\n", 5435 Style); 5436 // Don't crash if there is an #elif directive without a condition. 5437 verifyFormat("#if 1\n" 5438 "int x;\n" 5439 "#elif\n" 5440 "int y;\n" 5441 "#else\n" 5442 "int z;\n" 5443 "#endif", 5444 Style); 5445 // FIXME: This doesn't handle the case where there's code between the 5446 // #ifndef and #define but all other conditions hold. This is because when 5447 // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the 5448 // previous code line yet, so we can't detect it. 5449 EXPECT_EQ("#ifndef NOT_GUARD\n" 5450 "code();\n" 5451 "#define NOT_GUARD\n" 5452 "code();\n" 5453 "#endif", 5454 format("#ifndef NOT_GUARD\n" 5455 "code();\n" 5456 "# define NOT_GUARD\n" 5457 "code();\n" 5458 "#endif", 5459 Style)); 5460 // FIXME: This doesn't handle cases where legitimate preprocessor lines may 5461 // be outside an include guard. Examples are #pragma once and 5462 // #pragma GCC diagnostic, or anything else that does not change the meaning 5463 // of the file if it's included multiple times. 5464 EXPECT_EQ("#ifdef WIN32\n" 5465 "# pragma once\n" 5466 "#endif\n" 5467 "#ifndef HEADER_H\n" 5468 "# define HEADER_H\n" 5469 "code();\n" 5470 "#endif", 5471 format("#ifdef WIN32\n" 5472 "# pragma once\n" 5473 "#endif\n" 5474 "#ifndef HEADER_H\n" 5475 "#define HEADER_H\n" 5476 "code();\n" 5477 "#endif", 5478 Style)); 5479 // FIXME: This does not detect when there is a single non-preprocessor line 5480 // in front of an include-guard-like structure where other conditions hold 5481 // because ScopedLineState hides the line. 5482 EXPECT_EQ("code();\n" 5483 "#ifndef HEADER_H\n" 5484 "#define HEADER_H\n" 5485 "code();\n" 5486 "#endif", 5487 format("code();\n" 5488 "#ifndef HEADER_H\n" 5489 "# define HEADER_H\n" 5490 "code();\n" 5491 "#endif", 5492 Style)); 5493 // Keep comments aligned with #, otherwise indent comments normally. These 5494 // tests cannot use verifyFormat because messUp manipulates leading 5495 // whitespace. 5496 { 5497 const char *Expected = "" 5498 "void f() {\n" 5499 "#if 1\n" 5500 "// Preprocessor aligned.\n" 5501 "# define A 0\n" 5502 " // Code. Separated by blank line.\n" 5503 "\n" 5504 "# define B 0\n" 5505 " // Code. Not aligned with #\n" 5506 "# define C 0\n" 5507 "#endif"; 5508 const char *ToFormat = "" 5509 "void f() {\n" 5510 "#if 1\n" 5511 "// Preprocessor aligned.\n" 5512 "# define A 0\n" 5513 "// Code. Separated by blank line.\n" 5514 "\n" 5515 "# define B 0\n" 5516 " // Code. Not aligned with #\n" 5517 "# define C 0\n" 5518 "#endif"; 5519 EXPECT_EQ(Expected, format(ToFormat, Style)); 5520 EXPECT_EQ(Expected, format(Expected, Style)); 5521 } 5522 // Keep block quotes aligned. 5523 { 5524 const char *Expected = "" 5525 "void f() {\n" 5526 "#if 1\n" 5527 "/* Preprocessor aligned. */\n" 5528 "# define A 0\n" 5529 " /* Code. Separated by blank line. */\n" 5530 "\n" 5531 "# define B 0\n" 5532 " /* Code. Not aligned with # */\n" 5533 "# define C 0\n" 5534 "#endif"; 5535 const char *ToFormat = "" 5536 "void f() {\n" 5537 "#if 1\n" 5538 "/* Preprocessor aligned. */\n" 5539 "# define A 0\n" 5540 "/* Code. Separated by blank line. */\n" 5541 "\n" 5542 "# define B 0\n" 5543 " /* Code. Not aligned with # */\n" 5544 "# define C 0\n" 5545 "#endif"; 5546 EXPECT_EQ(Expected, format(ToFormat, Style)); 5547 EXPECT_EQ(Expected, format(Expected, Style)); 5548 } 5549 // Keep comments aligned with un-indented directives. 5550 { 5551 const char *Expected = "" 5552 "void f() {\n" 5553 "// Preprocessor aligned.\n" 5554 "#define A 0\n" 5555 " // Code. Separated by blank line.\n" 5556 "\n" 5557 "#define B 0\n" 5558 " // Code. Not aligned with #\n" 5559 "#define C 0\n"; 5560 const char *ToFormat = "" 5561 "void f() {\n" 5562 "// Preprocessor aligned.\n" 5563 "#define A 0\n" 5564 "// Code. Separated by blank line.\n" 5565 "\n" 5566 "#define B 0\n" 5567 " // Code. Not aligned with #\n" 5568 "#define C 0\n"; 5569 EXPECT_EQ(Expected, format(ToFormat, Style)); 5570 EXPECT_EQ(Expected, format(Expected, Style)); 5571 } 5572 // Test AfterHash with tabs. 5573 { 5574 FormatStyle Tabbed = Style; 5575 Tabbed.UseTab = FormatStyle::UT_Always; 5576 Tabbed.IndentWidth = 8; 5577 Tabbed.TabWidth = 8; 5578 verifyFormat("#ifdef _WIN32\n" 5579 "#\tdefine A 0\n" 5580 "#\tifdef VAR2\n" 5581 "#\t\tdefine B 1\n" 5582 "#\t\tinclude <someheader.h>\n" 5583 "#\t\tdefine MACRO \\\n" 5584 "\t\t\tsome_very_long_func_aaaaaaaaaa();\n" 5585 "#\tendif\n" 5586 "#else\n" 5587 "#\tdefine A 1\n" 5588 "#endif", 5589 Tabbed); 5590 } 5591 5592 // Regression test: Multiline-macro inside include guards. 5593 verifyFormat("#ifndef HEADER_H\n" 5594 "#define HEADER_H\n" 5595 "#define A() \\\n" 5596 " int i; \\\n" 5597 " int j;\n" 5598 "#endif // HEADER_H", 5599 getLLVMStyleWithColumns(20)); 5600 5601 Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash; 5602 // Basic before hash indent tests 5603 verifyFormat("#ifdef _WIN32\n" 5604 " #define A 0\n" 5605 " #ifdef VAR2\n" 5606 " #define B 1\n" 5607 " #include <someheader.h>\n" 5608 " #define MACRO \\\n" 5609 " some_very_long_func_aaaaaaaaaa();\n" 5610 " #endif\n" 5611 "#else\n" 5612 " #define A 1\n" 5613 "#endif", 5614 Style); 5615 verifyFormat("#if A\n" 5616 " #define MACRO \\\n" 5617 " void a(int x) { \\\n" 5618 " b(); \\\n" 5619 " c(); \\\n" 5620 " d(); \\\n" 5621 " e(); \\\n" 5622 " f(); \\\n" 5623 " }\n" 5624 "#endif", 5625 Style); 5626 // Keep comments aligned with indented directives. These 5627 // tests cannot use verifyFormat because messUp manipulates leading 5628 // whitespace. 5629 { 5630 const char *Expected = "void f() {\n" 5631 "// Aligned to preprocessor.\n" 5632 "#if 1\n" 5633 " // Aligned to code.\n" 5634 " int a;\n" 5635 " #if 1\n" 5636 " // Aligned to preprocessor.\n" 5637 " #define A 0\n" 5638 " // Aligned to code.\n" 5639 " int b;\n" 5640 " #endif\n" 5641 "#endif\n" 5642 "}"; 5643 const char *ToFormat = "void f() {\n" 5644 "// Aligned to preprocessor.\n" 5645 "#if 1\n" 5646 "// Aligned to code.\n" 5647 "int a;\n" 5648 "#if 1\n" 5649 "// Aligned to preprocessor.\n" 5650 "#define A 0\n" 5651 "// Aligned to code.\n" 5652 "int b;\n" 5653 "#endif\n" 5654 "#endif\n" 5655 "}"; 5656 EXPECT_EQ(Expected, format(ToFormat, Style)); 5657 EXPECT_EQ(Expected, format(Expected, Style)); 5658 } 5659 { 5660 const char *Expected = "void f() {\n" 5661 "/* Aligned to preprocessor. */\n" 5662 "#if 1\n" 5663 " /* Aligned to code. */\n" 5664 " int a;\n" 5665 " #if 1\n" 5666 " /* Aligned to preprocessor. */\n" 5667 " #define A 0\n" 5668 " /* Aligned to code. */\n" 5669 " int b;\n" 5670 " #endif\n" 5671 "#endif\n" 5672 "}"; 5673 const char *ToFormat = "void f() {\n" 5674 "/* Aligned to preprocessor. */\n" 5675 "#if 1\n" 5676 "/* Aligned to code. */\n" 5677 "int a;\n" 5678 "#if 1\n" 5679 "/* Aligned to preprocessor. */\n" 5680 "#define A 0\n" 5681 "/* Aligned to code. */\n" 5682 "int b;\n" 5683 "#endif\n" 5684 "#endif\n" 5685 "}"; 5686 EXPECT_EQ(Expected, format(ToFormat, Style)); 5687 EXPECT_EQ(Expected, format(Expected, Style)); 5688 } 5689 5690 // Test single comment before preprocessor 5691 verifyFormat("// Comment\n" 5692 "\n" 5693 "#if 1\n" 5694 "#endif", 5695 Style); 5696 } 5697 5698 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) { 5699 verifyFormat("{\n { a #c; }\n}"); 5700 } 5701 5702 TEST_F(FormatTest, FormatUnbalancedStructuralElements) { 5703 EXPECT_EQ("#define A \\\n { \\\n {\nint i;", 5704 format("#define A { {\nint i;", getLLVMStyleWithColumns(11))); 5705 EXPECT_EQ("#define A \\\n } \\\n }\nint i;", 5706 format("#define A } }\nint i;", getLLVMStyleWithColumns(11))); 5707 } 5708 5709 TEST_F(FormatTest, EscapedNewlines) { 5710 FormatStyle Narrow = getLLVMStyleWithColumns(11); 5711 EXPECT_EQ("#define A \\\n int i; \\\n int j;", 5712 format("#define A \\\nint i;\\\n int j;", Narrow)); 5713 EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;")); 5714 EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();")); 5715 EXPECT_EQ("/* \\ \\ \\\n */", format("\\\n/* \\ \\ \\\n */")); 5716 EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>")); 5717 5718 FormatStyle AlignLeft = getLLVMStyle(); 5719 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left; 5720 EXPECT_EQ("#define MACRO(x) \\\n" 5721 "private: \\\n" 5722 " int x(int a);\n", 5723 format("#define MACRO(x) \\\n" 5724 "private: \\\n" 5725 " int x(int a);\n", 5726 AlignLeft)); 5727 5728 // CRLF line endings 5729 EXPECT_EQ("#define A \\\r\n int i; \\\r\n int j;", 5730 format("#define A \\\r\nint i;\\\r\n int j;", Narrow)); 5731 EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;")); 5732 EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();")); 5733 EXPECT_EQ("/* \\ \\ \\\r\n */", format("\\\r\n/* \\ \\ \\\r\n */")); 5734 EXPECT_EQ("<a\r\n\\\\\r\n>", format("<a\r\n\\\\\r\n>")); 5735 EXPECT_EQ("#define MACRO(x) \\\r\n" 5736 "private: \\\r\n" 5737 " int x(int a);\r\n", 5738 format("#define MACRO(x) \\\r\n" 5739 "private: \\\r\n" 5740 " int x(int a);\r\n", 5741 AlignLeft)); 5742 5743 FormatStyle DontAlign = getLLVMStyle(); 5744 DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 5745 DontAlign.MaxEmptyLinesToKeep = 3; 5746 // FIXME: can't use verifyFormat here because the newline before 5747 // "public:" is not inserted the first time it's reformatted 5748 EXPECT_EQ("#define A \\\n" 5749 " class Foo { \\\n" 5750 " void bar(); \\\n" 5751 "\\\n" 5752 "\\\n" 5753 "\\\n" 5754 " public: \\\n" 5755 " void baz(); \\\n" 5756 " };", 5757 format("#define A \\\n" 5758 " class Foo { \\\n" 5759 " void bar(); \\\n" 5760 "\\\n" 5761 "\\\n" 5762 "\\\n" 5763 " public: \\\n" 5764 " void baz(); \\\n" 5765 " };", 5766 DontAlign)); 5767 } 5768 5769 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) { 5770 verifyFormat("#define A \\\n" 5771 " int v( \\\n" 5772 " a); \\\n" 5773 " int i;", 5774 getLLVMStyleWithColumns(11)); 5775 } 5776 5777 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) { 5778 EXPECT_EQ( 5779 "#define ALooooooooooooooooooooooooooooooooooooooongMacro(" 5780 " \\\n" 5781 " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n" 5782 "\n" 5783 "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n" 5784 " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n", 5785 format(" #define ALooooooooooooooooooooooooooooooooooooooongMacro(" 5786 "\\\n" 5787 "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n" 5788 " \n" 5789 " AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n" 5790 " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n")); 5791 } 5792 5793 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) { 5794 EXPECT_EQ("int\n" 5795 "#define A\n" 5796 " a;", 5797 format("int\n#define A\na;")); 5798 verifyFormat("functionCallTo(\n" 5799 " someOtherFunction(\n" 5800 " withSomeParameters, whichInSequence,\n" 5801 " areLongerThanALine(andAnotherCall,\n" 5802 "#define A B\n" 5803 " withMoreParamters,\n" 5804 " whichStronglyInfluenceTheLayout),\n" 5805 " andMoreParameters),\n" 5806 " trailing);", 5807 getLLVMStyleWithColumns(69)); 5808 verifyFormat("Foo::Foo()\n" 5809 "#ifdef BAR\n" 5810 " : baz(0)\n" 5811 "#endif\n" 5812 "{\n" 5813 "}"); 5814 verifyFormat("void f() {\n" 5815 " if (true)\n" 5816 "#ifdef A\n" 5817 " f(42);\n" 5818 " x();\n" 5819 "#else\n" 5820 " g();\n" 5821 " x();\n" 5822 "#endif\n" 5823 "}"); 5824 verifyFormat("void f(param1, param2,\n" 5825 " param3,\n" 5826 "#ifdef A\n" 5827 " param4(param5,\n" 5828 "#ifdef A1\n" 5829 " param6,\n" 5830 "#ifdef A2\n" 5831 " param7),\n" 5832 "#else\n" 5833 " param8),\n" 5834 " param9,\n" 5835 "#endif\n" 5836 " param10,\n" 5837 "#endif\n" 5838 " param11)\n" 5839 "#else\n" 5840 " param12)\n" 5841 "#endif\n" 5842 "{\n" 5843 " x();\n" 5844 "}", 5845 getLLVMStyleWithColumns(28)); 5846 verifyFormat("#if 1\n" 5847 "int i;"); 5848 verifyFormat("#if 1\n" 5849 "#endif\n" 5850 "#if 1\n" 5851 "#else\n" 5852 "#endif\n"); 5853 verifyFormat("DEBUG({\n" 5854 " return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5855 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n" 5856 "});\n" 5857 "#if a\n" 5858 "#else\n" 5859 "#endif"); 5860 5861 verifyIncompleteFormat("void f(\n" 5862 "#if A\n" 5863 ");\n" 5864 "#else\n" 5865 "#endif"); 5866 } 5867 5868 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) { 5869 verifyFormat("#endif\n" 5870 "#if B"); 5871 } 5872 5873 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) { 5874 FormatStyle SingleLine = getLLVMStyle(); 5875 SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse; 5876 verifyFormat("#if 0\n" 5877 "#elif 1\n" 5878 "#endif\n" 5879 "void foo() {\n" 5880 " if (test) foo2();\n" 5881 "}", 5882 SingleLine); 5883 } 5884 5885 TEST_F(FormatTest, LayoutBlockInsideParens) { 5886 verifyFormat("functionCall({ int i; });"); 5887 verifyFormat("functionCall({\n" 5888 " int i;\n" 5889 " int j;\n" 5890 "});"); 5891 verifyFormat("functionCall(\n" 5892 " {\n" 5893 " int i;\n" 5894 " int j;\n" 5895 " },\n" 5896 " aaaa, bbbb, cccc);"); 5897 verifyFormat("functionA(functionB({\n" 5898 " int i;\n" 5899 " int j;\n" 5900 " }),\n" 5901 " aaaa, bbbb, cccc);"); 5902 verifyFormat("functionCall(\n" 5903 " {\n" 5904 " int i;\n" 5905 " int j;\n" 5906 " },\n" 5907 " aaaa, bbbb, // comment\n" 5908 " cccc);"); 5909 verifyFormat("functionA(functionB({\n" 5910 " int i;\n" 5911 " int j;\n" 5912 " }),\n" 5913 " aaaa, bbbb, // comment\n" 5914 " cccc);"); 5915 verifyFormat("functionCall(aaaa, bbbb, { int i; });"); 5916 verifyFormat("functionCall(aaaa, bbbb, {\n" 5917 " int i;\n" 5918 " int j;\n" 5919 "});"); 5920 verifyFormat( 5921 "Aaa(\n" // FIXME: There shouldn't be a linebreak here. 5922 " {\n" 5923 " int i; // break\n" 5924 " },\n" 5925 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 5926 " ccccccccccccccccc));"); 5927 verifyFormat("DEBUG({\n" 5928 " if (a)\n" 5929 " f();\n" 5930 "});"); 5931 } 5932 5933 TEST_F(FormatTest, LayoutBlockInsideStatement) { 5934 EXPECT_EQ("SOME_MACRO { int i; }\n" 5935 "int i;", 5936 format(" SOME_MACRO {int i;} int i;")); 5937 } 5938 5939 TEST_F(FormatTest, LayoutNestedBlocks) { 5940 verifyFormat("void AddOsStrings(unsigned bitmask) {\n" 5941 " struct s {\n" 5942 " int i;\n" 5943 " };\n" 5944 " s kBitsToOs[] = {{10}};\n" 5945 " for (int i = 0; i < 10; ++i)\n" 5946 " return;\n" 5947 "}"); 5948 verifyFormat("call(parameter, {\n" 5949 " something();\n" 5950 " // Comment using all columns.\n" 5951 " somethingelse();\n" 5952 "});", 5953 getLLVMStyleWithColumns(40)); 5954 verifyFormat("DEBUG( //\n" 5955 " { f(); }, a);"); 5956 verifyFormat("DEBUG( //\n" 5957 " {\n" 5958 " f(); //\n" 5959 " },\n" 5960 " a);"); 5961 5962 EXPECT_EQ("call(parameter, {\n" 5963 " something();\n" 5964 " // Comment too\n" 5965 " // looooooooooong.\n" 5966 " somethingElse();\n" 5967 "});", 5968 format("call(parameter, {\n" 5969 " something();\n" 5970 " // Comment too looooooooooong.\n" 5971 " somethingElse();\n" 5972 "});", 5973 getLLVMStyleWithColumns(29))); 5974 EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int i; });")); 5975 EXPECT_EQ("DEBUG({ // comment\n" 5976 " int i;\n" 5977 "});", 5978 format("DEBUG({ // comment\n" 5979 "int i;\n" 5980 "});")); 5981 EXPECT_EQ("DEBUG({\n" 5982 " int i;\n" 5983 "\n" 5984 " // comment\n" 5985 " int j;\n" 5986 "});", 5987 format("DEBUG({\n" 5988 " int i;\n" 5989 "\n" 5990 " // comment\n" 5991 " int j;\n" 5992 "});")); 5993 5994 verifyFormat("DEBUG({\n" 5995 " if (a)\n" 5996 " return;\n" 5997 "});"); 5998 verifyGoogleFormat("DEBUG({\n" 5999 " if (a) return;\n" 6000 "});"); 6001 FormatStyle Style = getGoogleStyle(); 6002 Style.ColumnLimit = 45; 6003 verifyFormat("Debug(\n" 6004 " aaaaa,\n" 6005 " {\n" 6006 " if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n" 6007 " },\n" 6008 " a);", 6009 Style); 6010 6011 verifyFormat("SomeFunction({MACRO({ return output; }), b});"); 6012 6013 verifyNoCrash("^{v^{a}}"); 6014 } 6015 6016 TEST_F(FormatTest, FormatNestedBlocksInMacros) { 6017 EXPECT_EQ("#define MACRO() \\\n" 6018 " Debug(aaa, /* force line break */ \\\n" 6019 " { \\\n" 6020 " int i; \\\n" 6021 " int j; \\\n" 6022 " })", 6023 format("#define MACRO() Debug(aaa, /* force line break */ \\\n" 6024 " { int i; int j; })", 6025 getGoogleStyle())); 6026 6027 EXPECT_EQ("#define A \\\n" 6028 " [] { \\\n" 6029 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 6030 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n" 6031 " }", 6032 format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 6033 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }", 6034 getGoogleStyle())); 6035 } 6036 6037 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) { 6038 EXPECT_EQ("{}", format("{}")); 6039 verifyFormat("enum E {};"); 6040 verifyFormat("enum E {}"); 6041 FormatStyle Style = getLLVMStyle(); 6042 Style.SpaceInEmptyBlock = true; 6043 EXPECT_EQ("void f() { }", format("void f() {}", Style)); 6044 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 6045 EXPECT_EQ("while (true) { }", format("while (true) {}", Style)); 6046 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 6047 Style.BraceWrapping.BeforeElse = false; 6048 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 6049 verifyFormat("if (a)\n" 6050 "{\n" 6051 "} else if (b)\n" 6052 "{\n" 6053 "} else\n" 6054 "{ }", 6055 Style); 6056 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never; 6057 verifyFormat("if (a) {\n" 6058 "} else if (b) {\n" 6059 "} else {\n" 6060 "}", 6061 Style); 6062 Style.BraceWrapping.BeforeElse = true; 6063 verifyFormat("if (a) { }\n" 6064 "else if (b) { }\n" 6065 "else { }", 6066 Style); 6067 } 6068 6069 TEST_F(FormatTest, FormatBeginBlockEndMacros) { 6070 FormatStyle Style = getLLVMStyle(); 6071 Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$"; 6072 Style.MacroBlockEnd = "^[A-Z_]+_END$"; 6073 verifyFormat("FOO_BEGIN\n" 6074 " FOO_ENTRY\n" 6075 "FOO_END", 6076 Style); 6077 verifyFormat("FOO_BEGIN\n" 6078 " NESTED_FOO_BEGIN\n" 6079 " NESTED_FOO_ENTRY\n" 6080 " NESTED_FOO_END\n" 6081 "FOO_END", 6082 Style); 6083 verifyFormat("FOO_BEGIN(Foo, Bar)\n" 6084 " int x;\n" 6085 " x = 1;\n" 6086 "FOO_END(Baz)", 6087 Style); 6088 } 6089 6090 //===----------------------------------------------------------------------===// 6091 // Line break tests. 6092 //===----------------------------------------------------------------------===// 6093 6094 TEST_F(FormatTest, PreventConfusingIndents) { 6095 verifyFormat( 6096 "void f() {\n" 6097 " SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n" 6098 " parameter, parameter, parameter)),\n" 6099 " SecondLongCall(parameter));\n" 6100 "}"); 6101 verifyFormat( 6102 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6103 " aaaaaaaaaaaaaaaaaaaaaaaa(\n" 6104 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6105 " aaaaaaaaaaaaaaaaaaaaaaaa);"); 6106 verifyFormat( 6107 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6108 " [aaaaaaaaaaaaaaaaaaaaaaaa\n" 6109 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n" 6110 " [aaaaaaaaaaaaaaaaaaaaaaaa]];"); 6111 verifyFormat( 6112 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 6113 " aaaaaaaaaaaaaaaaaaaaaaaa<\n" 6114 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n" 6115 " aaaaaaaaaaaaaaaaaaaaaaaa>;"); 6116 verifyFormat("int a = bbbb && ccc &&\n" 6117 " fffff(\n" 6118 "#define A Just forcing a new line\n" 6119 " ddd);"); 6120 } 6121 6122 TEST_F(FormatTest, LineBreakingInBinaryExpressions) { 6123 verifyFormat( 6124 "bool aaaaaaa =\n" 6125 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n" 6126 " bbbbbbbb();"); 6127 verifyFormat( 6128 "bool aaaaaaa =\n" 6129 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n" 6130 " bbbbbbbb();"); 6131 6132 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n" 6133 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n" 6134 " ccccccccc == ddddddddddd;"); 6135 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n" 6136 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n" 6137 " ccccccccc == ddddddddddd;"); 6138 verifyFormat( 6139 "bool aaaaaaaaaaaaaaaaaaaaa =\n" 6140 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n" 6141 " ccccccccc == ddddddddddd;"); 6142 6143 verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n" 6144 " aaaaaa) &&\n" 6145 " bbbbbb && cccccc;"); 6146 verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n" 6147 " aaaaaa) >>\n" 6148 " bbbbbb;"); 6149 verifyFormat("aa = Whitespaces.addUntouchableComment(\n" 6150 " SourceMgr.getSpellingColumnNumber(\n" 6151 " TheLine.Last->FormatTok.Tok.getLocation()) -\n" 6152 " 1);"); 6153 6154 verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6155 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n" 6156 " cccccc) {\n}"); 6157 verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6158 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n" 6159 " cccccc) {\n}"); 6160 verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6161 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n" 6162 " cccccc) {\n}"); 6163 verifyFormat("b = a &&\n" 6164 " // Comment\n" 6165 " b.c && d;"); 6166 6167 // If the LHS of a comparison is not a binary expression itself, the 6168 // additional linebreak confuses many people. 6169 verifyFormat( 6170 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6171 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n" 6172 "}"); 6173 verifyFormat( 6174 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6175 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 6176 "}"); 6177 verifyFormat( 6178 "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n" 6179 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 6180 "}"); 6181 verifyFormat( 6182 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6183 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n" 6184 "}"); 6185 // Even explicit parentheses stress the precedence enough to make the 6186 // additional break unnecessary. 6187 verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6188 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 6189 "}"); 6190 // This cases is borderline, but with the indentation it is still readable. 6191 verifyFormat( 6192 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6193 " aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6194 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 6195 "}", 6196 getLLVMStyleWithColumns(75)); 6197 6198 // If the LHS is a binary expression, we should still use the additional break 6199 // as otherwise the formatting hides the operator precedence. 6200 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6201 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6202 " 5) {\n" 6203 "}"); 6204 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6205 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n" 6206 " 5) {\n" 6207 "}"); 6208 6209 FormatStyle OnePerLine = getLLVMStyle(); 6210 OnePerLine.BinPackParameters = false; 6211 verifyFormat( 6212 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6213 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6214 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}", 6215 OnePerLine); 6216 6217 verifyFormat("int i = someFunction(aaaaaaa, 0)\n" 6218 " .aaa(aaaaaaaaaaaaa) *\n" 6219 " aaaaaaa +\n" 6220 " aaaaaaa;", 6221 getLLVMStyleWithColumns(40)); 6222 } 6223 6224 TEST_F(FormatTest, ExpressionIndentation) { 6225 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6226 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6227 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6228 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6229 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n" 6230 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n" 6231 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6232 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n" 6233 " ccccccccccccccccccccccccccccccccccccccccc;"); 6234 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6235 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6236 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6237 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 6238 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6239 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6240 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6241 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 6242 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6243 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6244 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6245 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 6246 verifyFormat("if () {\n" 6247 "} else if (aaaaa && bbbbb > // break\n" 6248 " ccccc) {\n" 6249 "}"); 6250 verifyFormat("if () {\n" 6251 "} else if constexpr (aaaaa && bbbbb > // break\n" 6252 " ccccc) {\n" 6253 "}"); 6254 verifyFormat("if () {\n" 6255 "} else if CONSTEXPR (aaaaa && bbbbb > // break\n" 6256 " ccccc) {\n" 6257 "}"); 6258 verifyFormat("if () {\n" 6259 "} else if (aaaaa &&\n" 6260 " bbbbb > // break\n" 6261 " ccccc &&\n" 6262 " ddddd) {\n" 6263 "}"); 6264 6265 // Presence of a trailing comment used to change indentation of b. 6266 verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n" 6267 " b;\n" 6268 "return aaaaaaaaaaaaaaaaaaa +\n" 6269 " b; //", 6270 getLLVMStyleWithColumns(30)); 6271 } 6272 6273 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) { 6274 // Not sure what the best system is here. Like this, the LHS can be found 6275 // immediately above an operator (everything with the same or a higher 6276 // indent). The RHS is aligned right of the operator and so compasses 6277 // everything until something with the same indent as the operator is found. 6278 // FIXME: Is this a good system? 6279 FormatStyle Style = getLLVMStyle(); 6280 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 6281 verifyFormat( 6282 "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6283 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6284 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6285 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6286 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6287 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6288 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6289 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6290 " > ccccccccccccccccccccccccccccccccccccccccc;", 6291 Style); 6292 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6293 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6294 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6295 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6296 Style); 6297 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6298 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6299 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6300 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6301 Style); 6302 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6303 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6304 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6305 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6306 Style); 6307 verifyFormat("if () {\n" 6308 "} else if (aaaaa\n" 6309 " && bbbbb // break\n" 6310 " > ccccc) {\n" 6311 "}", 6312 Style); 6313 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6314 " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6315 Style); 6316 verifyFormat("return (a)\n" 6317 " // comment\n" 6318 " + b;", 6319 Style); 6320 verifyFormat( 6321 "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6322 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6323 " + cc;", 6324 Style); 6325 6326 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6327 " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 6328 Style); 6329 6330 // Forced by comments. 6331 verifyFormat( 6332 "unsigned ContentSize =\n" 6333 " sizeof(int16_t) // DWARF ARange version number\n" 6334 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6335 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6336 " + sizeof(int8_t); // Segment Size (in bytes)"); 6337 6338 verifyFormat("return boost::fusion::at_c<0>(iiii).second\n" 6339 " == boost::fusion::at_c<1>(iiii).second;", 6340 Style); 6341 6342 Style.ColumnLimit = 60; 6343 verifyFormat("zzzzzzzzzz\n" 6344 " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6345 " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);", 6346 Style); 6347 6348 Style.ColumnLimit = 80; 6349 Style.IndentWidth = 4; 6350 Style.TabWidth = 4; 6351 Style.UseTab = FormatStyle::UT_Always; 6352 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6353 Style.AlignOperands = FormatStyle::OAS_DontAlign; 6354 EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n" 6355 "\t&& (someOtherLongishConditionPart1\n" 6356 "\t\t|| someOtherEvenLongerNestedConditionPart2);", 6357 format("return someVeryVeryLongConditionThatBarelyFitsOnALine && " 6358 "(someOtherLongishConditionPart1 || " 6359 "someOtherEvenLongerNestedConditionPart2);", 6360 Style)); 6361 } 6362 6363 TEST_F(FormatTest, ExpressionIndentationStrictAlign) { 6364 FormatStyle Style = getLLVMStyle(); 6365 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 6366 Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator; 6367 6368 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6369 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6370 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6371 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6372 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6373 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6374 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6375 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6376 " > ccccccccccccccccccccccccccccccccccccccccc;", 6377 Style); 6378 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6379 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6380 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6381 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6382 Style); 6383 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6384 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6385 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6386 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6387 Style); 6388 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6389 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6390 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6391 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6392 Style); 6393 verifyFormat("if () {\n" 6394 "} else if (aaaaa\n" 6395 " && bbbbb // break\n" 6396 " > ccccc) {\n" 6397 "}", 6398 Style); 6399 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6400 " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6401 Style); 6402 verifyFormat("return (a)\n" 6403 " // comment\n" 6404 " + b;", 6405 Style); 6406 verifyFormat( 6407 "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6408 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6409 " + cc;", 6410 Style); 6411 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 6412 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 6413 " : 3333333333333333;", 6414 Style); 6415 verifyFormat( 6416 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 6417 " : ccccccccccccccc ? dddddddddddddddddd\n" 6418 " : eeeeeeeeeeeeeeeeee)\n" 6419 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 6420 " : 3333333333333333;", 6421 Style); 6422 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6423 " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 6424 Style); 6425 6426 verifyFormat("return boost::fusion::at_c<0>(iiii).second\n" 6427 " == boost::fusion::at_c<1>(iiii).second;", 6428 Style); 6429 6430 Style.ColumnLimit = 60; 6431 verifyFormat("zzzzzzzzzzzzz\n" 6432 " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6433 " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);", 6434 Style); 6435 6436 // Forced by comments. 6437 Style.ColumnLimit = 80; 6438 verifyFormat( 6439 "unsigned ContentSize\n" 6440 " = sizeof(int16_t) // DWARF ARange version number\n" 6441 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6442 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6443 " + sizeof(int8_t); // Segment Size (in bytes)", 6444 Style); 6445 6446 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6447 verifyFormat( 6448 "unsigned ContentSize =\n" 6449 " sizeof(int16_t) // DWARF ARange version number\n" 6450 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6451 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6452 " + sizeof(int8_t); // Segment Size (in bytes)", 6453 Style); 6454 6455 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 6456 verifyFormat( 6457 "unsigned ContentSize =\n" 6458 " sizeof(int16_t) // DWARF ARange version number\n" 6459 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6460 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6461 " + sizeof(int8_t); // Segment Size (in bytes)", 6462 Style); 6463 } 6464 6465 TEST_F(FormatTest, EnforcedOperatorWraps) { 6466 // Here we'd like to wrap after the || operators, but a comment is forcing an 6467 // earlier wrap. 6468 verifyFormat("bool x = aaaaa //\n" 6469 " || bbbbb\n" 6470 " //\n" 6471 " || cccc;"); 6472 } 6473 6474 TEST_F(FormatTest, NoOperandAlignment) { 6475 FormatStyle Style = getLLVMStyle(); 6476 Style.AlignOperands = FormatStyle::OAS_DontAlign; 6477 verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n" 6478 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6479 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 6480 Style); 6481 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6482 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6483 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6484 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6485 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6486 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6487 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6488 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6489 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6490 " > ccccccccccccccccccccccccccccccccccccccccc;", 6491 Style); 6492 6493 verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6494 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6495 " + cc;", 6496 Style); 6497 verifyFormat("int a = aa\n" 6498 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6499 " * cccccccccccccccccccccccccccccccccccc;\n", 6500 Style); 6501 6502 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6503 verifyFormat("return (a > b\n" 6504 " // comment1\n" 6505 " // comment2\n" 6506 " || c);", 6507 Style); 6508 } 6509 6510 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) { 6511 FormatStyle Style = getLLVMStyle(); 6512 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6513 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 6514 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6515 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6516 Style); 6517 } 6518 6519 TEST_F(FormatTest, AllowBinPackingInsideArguments) { 6520 FormatStyle Style = getLLVMStyleWithColumns(40); 6521 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6522 Style.BinPackArguments = false; 6523 verifyFormat("void test() {\n" 6524 " someFunction(\n" 6525 " this + argument + is + quite\n" 6526 " + long + so + it + gets + wrapped\n" 6527 " + but + remains + bin - packed);\n" 6528 "}", 6529 Style); 6530 verifyFormat("void test() {\n" 6531 " someFunction(arg1,\n" 6532 " this + argument + is\n" 6533 " + quite + long + so\n" 6534 " + it + gets + wrapped\n" 6535 " + but + remains + bin\n" 6536 " - packed,\n" 6537 " arg3);\n" 6538 "}", 6539 Style); 6540 verifyFormat("void test() {\n" 6541 " someFunction(\n" 6542 " arg1,\n" 6543 " this + argument + has\n" 6544 " + anotherFunc(nested,\n" 6545 " calls + whose\n" 6546 " + arguments\n" 6547 " + are + also\n" 6548 " + wrapped,\n" 6549 " in + addition)\n" 6550 " + to + being + bin - packed,\n" 6551 " arg3);\n" 6552 "}", 6553 Style); 6554 6555 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 6556 verifyFormat("void test() {\n" 6557 " someFunction(\n" 6558 " arg1,\n" 6559 " this + argument + has +\n" 6560 " anotherFunc(nested,\n" 6561 " calls + whose +\n" 6562 " arguments +\n" 6563 " are + also +\n" 6564 " wrapped,\n" 6565 " in + addition) +\n" 6566 " to + being + bin - packed,\n" 6567 " arg3);\n" 6568 "}", 6569 Style); 6570 } 6571 6572 TEST_F(FormatTest, BreakBinaryOperatorsInPresenceOfTemplates) { 6573 auto Style = getLLVMStyleWithColumns(45); 6574 EXPECT_EQ(Style.BreakBeforeBinaryOperators, FormatStyle::BOS_None); 6575 verifyFormat("bool b =\n" 6576 " is_default_constructible_v<hash<T>> and\n" 6577 " is_copy_constructible_v<hash<T>> and\n" 6578 " is_move_constructible_v<hash<T>> and\n" 6579 " is_copy_assignable_v<hash<T>> and\n" 6580 " is_move_assignable_v<hash<T>> and\n" 6581 " is_destructible_v<hash<T>> and\n" 6582 " is_swappable_v<hash<T>> and\n" 6583 " is_callable_v<hash<T>(T)>;", 6584 Style); 6585 6586 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6587 verifyFormat("bool b = is_default_constructible_v<hash<T>>\n" 6588 " and is_copy_constructible_v<hash<T>>\n" 6589 " and is_move_constructible_v<hash<T>>\n" 6590 " and is_copy_assignable_v<hash<T>>\n" 6591 " and is_move_assignable_v<hash<T>>\n" 6592 " and is_destructible_v<hash<T>>\n" 6593 " and is_swappable_v<hash<T>>\n" 6594 " and is_callable_v<hash<T>(T)>;", 6595 Style); 6596 6597 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 6598 verifyFormat("bool b = is_default_constructible_v<hash<T>>\n" 6599 " and is_copy_constructible_v<hash<T>>\n" 6600 " and is_move_constructible_v<hash<T>>\n" 6601 " and is_copy_assignable_v<hash<T>>\n" 6602 " and is_move_assignable_v<hash<T>>\n" 6603 " and is_destructible_v<hash<T>>\n" 6604 " and is_swappable_v<hash<T>>\n" 6605 " and is_callable_v<hash<T>(T)>;", 6606 Style); 6607 } 6608 6609 TEST_F(FormatTest, ConstructorInitializers) { 6610 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}"); 6611 verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}", 6612 getLLVMStyleWithColumns(45)); 6613 verifyFormat("Constructor()\n" 6614 " : Inttializer(FitsOnTheLine) {}", 6615 getLLVMStyleWithColumns(44)); 6616 verifyFormat("Constructor()\n" 6617 " : Inttializer(FitsOnTheLine) {}", 6618 getLLVMStyleWithColumns(43)); 6619 6620 verifyFormat("template <typename T>\n" 6621 "Constructor() : Initializer(FitsOnTheLine) {}", 6622 getLLVMStyleWithColumns(45)); 6623 6624 verifyFormat( 6625 "SomeClass::Constructor()\n" 6626 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}"); 6627 6628 verifyFormat( 6629 "SomeClass::Constructor()\n" 6630 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6631 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}"); 6632 verifyFormat( 6633 "SomeClass::Constructor()\n" 6634 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6635 " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}"); 6636 verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6637 " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 6638 " : aaaaaaaaaa(aaaaaa) {}"); 6639 6640 verifyFormat("Constructor()\n" 6641 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6642 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6643 " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6644 " aaaaaaaaaaaaaaaaaaaaaaa() {}"); 6645 6646 verifyFormat("Constructor()\n" 6647 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6648 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 6649 6650 verifyFormat("Constructor(int Parameter = 0)\n" 6651 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n" 6652 " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}"); 6653 verifyFormat("Constructor()\n" 6654 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n" 6655 "}", 6656 getLLVMStyleWithColumns(60)); 6657 verifyFormat("Constructor()\n" 6658 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6659 " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}"); 6660 6661 // Here a line could be saved by splitting the second initializer onto two 6662 // lines, but that is not desirable. 6663 verifyFormat("Constructor()\n" 6664 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n" 6665 " aaaaaaaaaaa(aaaaaaaaaaa),\n" 6666 " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 6667 6668 FormatStyle OnePerLine = getLLVMStyle(); 6669 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_Never; 6670 verifyFormat("MyClass::MyClass()\n" 6671 " : a(a),\n" 6672 " b(b),\n" 6673 " c(c) {}", 6674 OnePerLine); 6675 verifyFormat("MyClass::MyClass()\n" 6676 " : a(a), // comment\n" 6677 " b(b),\n" 6678 " c(c) {}", 6679 OnePerLine); 6680 verifyFormat("MyClass::MyClass(int a)\n" 6681 " : b(a), // comment\n" 6682 " c(a + 1) { // lined up\n" 6683 "}", 6684 OnePerLine); 6685 verifyFormat("Constructor()\n" 6686 " : a(b, b, b) {}", 6687 OnePerLine); 6688 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6689 OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false; 6690 verifyFormat("SomeClass::Constructor()\n" 6691 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6692 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6693 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6694 OnePerLine); 6695 verifyFormat("SomeClass::Constructor()\n" 6696 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n" 6697 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6698 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6699 OnePerLine); 6700 verifyFormat("MyClass::MyClass(int var)\n" 6701 " : some_var_(var), // 4 space indent\n" 6702 " some_other_var_(var + 1) { // lined up\n" 6703 "}", 6704 OnePerLine); 6705 verifyFormat("Constructor()\n" 6706 " : aaaaa(aaaaaa),\n" 6707 " aaaaa(aaaaaa),\n" 6708 " aaaaa(aaaaaa),\n" 6709 " aaaaa(aaaaaa),\n" 6710 " aaaaa(aaaaaa) {}", 6711 OnePerLine); 6712 verifyFormat("Constructor()\n" 6713 " : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n" 6714 " aaaaaaaaaaaaaaaaaaaaaa) {}", 6715 OnePerLine); 6716 OnePerLine.BinPackParameters = false; 6717 verifyFormat( 6718 "Constructor()\n" 6719 " : aaaaaaaaaaaaaaaaaaaaaaaa(\n" 6720 " aaaaaaaaaaa().aaa(),\n" 6721 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6722 OnePerLine); 6723 OnePerLine.ColumnLimit = 60; 6724 verifyFormat("Constructor()\n" 6725 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6726 " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}", 6727 OnePerLine); 6728 6729 EXPECT_EQ("Constructor()\n" 6730 " : // Comment forcing unwanted break.\n" 6731 " aaaa(aaaa) {}", 6732 format("Constructor() :\n" 6733 " // Comment forcing unwanted break.\n" 6734 " aaaa(aaaa) {}")); 6735 } 6736 6737 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) { 6738 FormatStyle Style = getLLVMStyleWithColumns(60); 6739 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6740 Style.BinPackParameters = false; 6741 6742 for (int i = 0; i < 4; ++i) { 6743 // Test all combinations of parameters that should not have an effect. 6744 Style.AllowAllParametersOfDeclarationOnNextLine = i & 1; 6745 Style.AllowAllArgumentsOnNextLine = i & 2; 6746 6747 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6748 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6749 verifyFormat("Constructor()\n" 6750 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6751 Style); 6752 verifyFormat("Constructor() : a(a), b(b) {}", Style); 6753 6754 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6755 verifyFormat("Constructor()\n" 6756 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6757 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6758 Style); 6759 verifyFormat("Constructor() : a(a), b(b) {}", Style); 6760 6761 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 6762 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6763 verifyFormat("Constructor()\n" 6764 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6765 Style); 6766 6767 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6768 verifyFormat("Constructor()\n" 6769 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6770 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6771 Style); 6772 6773 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6774 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6775 verifyFormat("Constructor() :\n" 6776 " aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6777 Style); 6778 6779 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6780 verifyFormat("Constructor() :\n" 6781 " aaaaaaaaaaaaaaaaaa(a),\n" 6782 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6783 Style); 6784 } 6785 6786 // Test interactions between AllowAllParametersOfDeclarationOnNextLine and 6787 // AllowAllConstructorInitializersOnNextLine in all 6788 // BreakConstructorInitializers modes 6789 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6790 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6791 verifyFormat("SomeClassWithALongName::Constructor(\n" 6792 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n" 6793 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6794 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6795 Style); 6796 6797 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6798 verifyFormat("SomeClassWithALongName::Constructor(\n" 6799 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6800 " int bbbbbbbbbbbbb,\n" 6801 " int cccccccccccccccc)\n" 6802 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6803 Style); 6804 6805 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6806 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6807 verifyFormat("SomeClassWithALongName::Constructor(\n" 6808 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6809 " int bbbbbbbbbbbbb)\n" 6810 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6811 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6812 Style); 6813 6814 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 6815 6816 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6817 verifyFormat("SomeClassWithALongName::Constructor(\n" 6818 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n" 6819 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6820 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6821 Style); 6822 6823 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6824 verifyFormat("SomeClassWithALongName::Constructor(\n" 6825 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6826 " int bbbbbbbbbbbbb,\n" 6827 " int cccccccccccccccc)\n" 6828 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6829 Style); 6830 6831 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6832 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6833 verifyFormat("SomeClassWithALongName::Constructor(\n" 6834 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6835 " int bbbbbbbbbbbbb)\n" 6836 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6837 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6838 Style); 6839 6840 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6841 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6842 verifyFormat("SomeClassWithALongName::Constructor(\n" 6843 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n" 6844 " aaaaaaaaaaaaaaaaaaaa(a),\n" 6845 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6846 Style); 6847 6848 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6849 verifyFormat("SomeClassWithALongName::Constructor(\n" 6850 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6851 " int bbbbbbbbbbbbb,\n" 6852 " int cccccccccccccccc) :\n" 6853 " aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6854 Style); 6855 6856 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6857 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6858 verifyFormat("SomeClassWithALongName::Constructor(\n" 6859 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6860 " int bbbbbbbbbbbbb) :\n" 6861 " aaaaaaaaaaaaaaaaaaaa(a),\n" 6862 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6863 Style); 6864 } 6865 6866 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) { 6867 FormatStyle Style = getLLVMStyleWithColumns(60); 6868 Style.BinPackArguments = false; 6869 for (int i = 0; i < 4; ++i) { 6870 // Test all combinations of parameters that should not have an effect. 6871 Style.AllowAllParametersOfDeclarationOnNextLine = i & 1; 6872 Style.PackConstructorInitializers = 6873 i & 2 ? FormatStyle::PCIS_BinPack : FormatStyle::PCIS_Never; 6874 6875 Style.AllowAllArgumentsOnNextLine = true; 6876 verifyFormat("void foo() {\n" 6877 " FunctionCallWithReallyLongName(\n" 6878 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n" 6879 "}", 6880 Style); 6881 Style.AllowAllArgumentsOnNextLine = false; 6882 verifyFormat("void foo() {\n" 6883 " FunctionCallWithReallyLongName(\n" 6884 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6885 " bbbbbbbbbbbb);\n" 6886 "}", 6887 Style); 6888 6889 Style.AllowAllArgumentsOnNextLine = true; 6890 verifyFormat("void foo() {\n" 6891 " auto VariableWithReallyLongName = {\n" 6892 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n" 6893 "}", 6894 Style); 6895 Style.AllowAllArgumentsOnNextLine = false; 6896 verifyFormat("void foo() {\n" 6897 " auto VariableWithReallyLongName = {\n" 6898 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6899 " bbbbbbbbbbbb};\n" 6900 "}", 6901 Style); 6902 } 6903 6904 // This parameter should not affect declarations. 6905 Style.BinPackParameters = false; 6906 Style.AllowAllArgumentsOnNextLine = false; 6907 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6908 verifyFormat("void FunctionCallWithReallyLongName(\n" 6909 " int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);", 6910 Style); 6911 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6912 verifyFormat("void FunctionCallWithReallyLongName(\n" 6913 " int aaaaaaaaaaaaaaaaaaaaaaa,\n" 6914 " int bbbbbbbbbbbb);", 6915 Style); 6916 } 6917 6918 TEST_F(FormatTest, AllowAllArgumentsOnNextLineDontAlign) { 6919 // Check that AllowAllArgumentsOnNextLine is respected for both BAS_DontAlign 6920 // and BAS_Align. 6921 FormatStyle Style = getLLVMStyleWithColumns(35); 6922 StringRef Input = "functionCall(paramA, paramB, paramC);\n" 6923 "void functionDecl(int A, int B, int C);"; 6924 Style.AllowAllArgumentsOnNextLine = false; 6925 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6926 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6927 " paramC);\n" 6928 "void functionDecl(int A, int B,\n" 6929 " int C);"), 6930 format(Input, Style)); 6931 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 6932 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6933 " paramC);\n" 6934 "void functionDecl(int A, int B,\n" 6935 " int C);"), 6936 format(Input, Style)); 6937 // However, BAS_AlwaysBreak should take precedence over 6938 // AllowAllArgumentsOnNextLine. 6939 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 6940 EXPECT_EQ(StringRef("functionCall(\n" 6941 " paramA, paramB, paramC);\n" 6942 "void functionDecl(\n" 6943 " int A, int B, int C);"), 6944 format(Input, Style)); 6945 6946 // When AllowAllArgumentsOnNextLine is set, we prefer breaking before the 6947 // first argument. 6948 Style.AllowAllArgumentsOnNextLine = true; 6949 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 6950 EXPECT_EQ(StringRef("functionCall(\n" 6951 " paramA, paramB, paramC);\n" 6952 "void functionDecl(\n" 6953 " int A, int B, int C);"), 6954 format(Input, Style)); 6955 // It wouldn't fit on one line with aligned parameters so this setting 6956 // doesn't change anything for BAS_Align. 6957 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 6958 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6959 " paramC);\n" 6960 "void functionDecl(int A, int B,\n" 6961 " int C);"), 6962 format(Input, Style)); 6963 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6964 EXPECT_EQ(StringRef("functionCall(\n" 6965 " paramA, paramB, paramC);\n" 6966 "void functionDecl(\n" 6967 " int A, int B, int C);"), 6968 format(Input, Style)); 6969 } 6970 6971 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) { 6972 FormatStyle Style = getLLVMStyle(); 6973 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6974 6975 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}"); 6976 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}", 6977 getStyleWithColumns(Style, 45)); 6978 verifyFormat("Constructor() :\n" 6979 " Initializer(FitsOnTheLine) {}", 6980 getStyleWithColumns(Style, 44)); 6981 verifyFormat("Constructor() :\n" 6982 " Initializer(FitsOnTheLine) {}", 6983 getStyleWithColumns(Style, 43)); 6984 6985 verifyFormat("template <typename T>\n" 6986 "Constructor() : Initializer(FitsOnTheLine) {}", 6987 getStyleWithColumns(Style, 50)); 6988 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6989 verifyFormat( 6990 "SomeClass::Constructor() :\n" 6991 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 6992 Style); 6993 6994 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 6995 verifyFormat( 6996 "SomeClass::Constructor() :\n" 6997 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 6998 Style); 6999 7000 verifyFormat( 7001 "SomeClass::Constructor() :\n" 7002 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 7003 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 7004 Style); 7005 verifyFormat( 7006 "SomeClass::Constructor() :\n" 7007 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7008 " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 7009 Style); 7010 verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7011 " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 7012 " aaaaaaaaaa(aaaaaa) {}", 7013 Style); 7014 7015 verifyFormat("Constructor() :\n" 7016 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7017 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7018 " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7019 " aaaaaaaaaaaaaaaaaaaaaaa() {}", 7020 Style); 7021 7022 verifyFormat("Constructor() :\n" 7023 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7024 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7025 Style); 7026 7027 verifyFormat("Constructor(int Parameter = 0) :\n" 7028 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n" 7029 " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}", 7030 Style); 7031 verifyFormat("Constructor() :\n" 7032 " aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n" 7033 "}", 7034 getStyleWithColumns(Style, 60)); 7035 verifyFormat("Constructor() :\n" 7036 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7037 " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}", 7038 Style); 7039 7040 // Here a line could be saved by splitting the second initializer onto two 7041 // lines, but that is not desirable. 7042 verifyFormat("Constructor() :\n" 7043 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n" 7044 " aaaaaaaaaaa(aaaaaaaaaaa),\n" 7045 " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7046 Style); 7047 7048 FormatStyle OnePerLine = Style; 7049 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 7050 verifyFormat("SomeClass::Constructor() :\n" 7051 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 7052 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 7053 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 7054 OnePerLine); 7055 verifyFormat("SomeClass::Constructor() :\n" 7056 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n" 7057 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 7058 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 7059 OnePerLine); 7060 verifyFormat("MyClass::MyClass(int var) :\n" 7061 " some_var_(var), // 4 space indent\n" 7062 " some_other_var_(var + 1) { // lined up\n" 7063 "}", 7064 OnePerLine); 7065 verifyFormat("Constructor() :\n" 7066 " aaaaa(aaaaaa),\n" 7067 " aaaaa(aaaaaa),\n" 7068 " aaaaa(aaaaaa),\n" 7069 " aaaaa(aaaaaa),\n" 7070 " aaaaa(aaaaaa) {}", 7071 OnePerLine); 7072 verifyFormat("Constructor() :\n" 7073 " aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n" 7074 " aaaaaaaaaaaaaaaaaaaaaa) {}", 7075 OnePerLine); 7076 OnePerLine.BinPackParameters = false; 7077 verifyFormat("Constructor() :\n" 7078 " aaaaaaaaaaaaaaaaaaaaaaaa(\n" 7079 " aaaaaaaaaaa().aaa(),\n" 7080 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7081 OnePerLine); 7082 OnePerLine.ColumnLimit = 60; 7083 verifyFormat("Constructor() :\n" 7084 " aaaaaaaaaaaaaaaaaaaa(a),\n" 7085 " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}", 7086 OnePerLine); 7087 7088 EXPECT_EQ("Constructor() :\n" 7089 " // Comment forcing unwanted break.\n" 7090 " aaaa(aaaa) {}", 7091 format("Constructor() :\n" 7092 " // Comment forcing unwanted break.\n" 7093 " aaaa(aaaa) {}", 7094 Style)); 7095 7096 Style.ColumnLimit = 0; 7097 verifyFormat("SomeClass::Constructor() :\n" 7098 " a(a) {}", 7099 Style); 7100 verifyFormat("SomeClass::Constructor() noexcept :\n" 7101 " a(a) {}", 7102 Style); 7103 verifyFormat("SomeClass::Constructor() :\n" 7104 " a(a), b(b), c(c) {}", 7105 Style); 7106 verifyFormat("SomeClass::Constructor() :\n" 7107 " a(a) {\n" 7108 " foo();\n" 7109 " bar();\n" 7110 "}", 7111 Style); 7112 7113 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 7114 verifyFormat("SomeClass::Constructor() :\n" 7115 " a(a), b(b), c(c) {\n" 7116 "}", 7117 Style); 7118 verifyFormat("SomeClass::Constructor() :\n" 7119 " a(a) {\n" 7120 "}", 7121 Style); 7122 7123 Style.ColumnLimit = 80; 7124 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 7125 Style.ConstructorInitializerIndentWidth = 2; 7126 verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style); 7127 verifyFormat("SomeClass::Constructor() :\n" 7128 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7129 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}", 7130 Style); 7131 7132 // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as 7133 // well 7134 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 7135 verifyFormat( 7136 "class SomeClass\n" 7137 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7138 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7139 Style); 7140 Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma; 7141 verifyFormat( 7142 "class SomeClass\n" 7143 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7144 " , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7145 Style); 7146 Style.BreakInheritanceList = FormatStyle::BILS_AfterColon; 7147 verifyFormat( 7148 "class SomeClass :\n" 7149 " public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7150 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7151 Style); 7152 Style.BreakInheritanceList = FormatStyle::BILS_AfterComma; 7153 verifyFormat( 7154 "class SomeClass\n" 7155 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7156 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7157 Style); 7158 } 7159 7160 #ifndef EXPENSIVE_CHECKS 7161 // Expensive checks enables libstdc++ checking which includes validating the 7162 // state of ranges used in std::priority_queue - this blows out the 7163 // runtime/scalability of the function and makes this test unacceptably slow. 7164 TEST_F(FormatTest, MemoizationTests) { 7165 // This breaks if the memoization lookup does not take \c Indent and 7166 // \c LastSpace into account. 7167 verifyFormat( 7168 "extern CFRunLoopTimerRef\n" 7169 "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n" 7170 " CFTimeInterval interval, CFOptionFlags flags,\n" 7171 " CFIndex order, CFRunLoopTimerCallBack callout,\n" 7172 " CFRunLoopTimerContext *context) {}"); 7173 7174 // Deep nesting somewhat works around our memoization. 7175 verifyFormat( 7176 "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7177 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7178 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7179 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7180 " aaaaa())))))))))))))))))))))))))))))))))))))));", 7181 getLLVMStyleWithColumns(65)); 7182 verifyFormat( 7183 "aaaaa(\n" 7184 " aaaaa,\n" 7185 " aaaaa(\n" 7186 " aaaaa,\n" 7187 " aaaaa(\n" 7188 " aaaaa,\n" 7189 " aaaaa(\n" 7190 " aaaaa,\n" 7191 " aaaaa(\n" 7192 " aaaaa,\n" 7193 " aaaaa(\n" 7194 " aaaaa,\n" 7195 " aaaaa(\n" 7196 " aaaaa,\n" 7197 " aaaaa(\n" 7198 " aaaaa,\n" 7199 " aaaaa(\n" 7200 " aaaaa,\n" 7201 " aaaaa(\n" 7202 " aaaaa,\n" 7203 " aaaaa(\n" 7204 " aaaaa,\n" 7205 " aaaaa(\n" 7206 " aaaaa,\n" 7207 " aaaaa))))))))))));", 7208 getLLVMStyleWithColumns(65)); 7209 verifyFormat( 7210 "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" 7211 " a),\n" 7212 " a),\n" 7213 " a),\n" 7214 " a),\n" 7215 " a),\n" 7216 " a),\n" 7217 " a),\n" 7218 " a),\n" 7219 " a),\n" 7220 " a),\n" 7221 " a),\n" 7222 " a),\n" 7223 " a),\n" 7224 " a),\n" 7225 " a),\n" 7226 " a),\n" 7227 " a)", 7228 getLLVMStyleWithColumns(65)); 7229 7230 // This test takes VERY long when memoization is broken. 7231 FormatStyle OnePerLine = getLLVMStyle(); 7232 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 7233 OnePerLine.BinPackParameters = false; 7234 std::string input = "Constructor()\n" 7235 " : aaaa(a,\n"; 7236 for (unsigned i = 0, e = 80; i != e; ++i) 7237 input += " a,\n"; 7238 input += " a) {}"; 7239 verifyFormat(input, OnePerLine); 7240 } 7241 #endif 7242 7243 TEST_F(FormatTest, BreaksAsHighAsPossible) { 7244 verifyFormat( 7245 "void f() {\n" 7246 " if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n" 7247 " (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n" 7248 " f();\n" 7249 "}"); 7250 verifyFormat("if (Intervals[i].getRange().getFirst() <\n" 7251 " Intervals[i - 1].getRange().getLast()) {\n}"); 7252 } 7253 7254 TEST_F(FormatTest, BreaksFunctionDeclarations) { 7255 // Principially, we break function declarations in a certain order: 7256 // 1) break amongst arguments. 7257 verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n" 7258 " Cccccccccccccc cccccccccccccc);"); 7259 verifyFormat("template <class TemplateIt>\n" 7260 "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n" 7261 " TemplateIt *stop) {}"); 7262 7263 // 2) break after return type. 7264 verifyFormat( 7265 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7266 "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);", 7267 getGoogleStyle()); 7268 7269 // 3) break after (. 7270 verifyFormat( 7271 "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n" 7272 " Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);", 7273 getGoogleStyle()); 7274 7275 // 4) break before after nested name specifiers. 7276 verifyFormat( 7277 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7278 "SomeClasssssssssssssssssssssssssssssssssssssss::\n" 7279 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);", 7280 getGoogleStyle()); 7281 7282 // However, there are exceptions, if a sufficient amount of lines can be 7283 // saved. 7284 // FIXME: The precise cut-offs wrt. the number of saved lines might need some 7285 // more adjusting. 7286 verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n" 7287 " Cccccccccccccc cccccccccc,\n" 7288 " Cccccccccccccc cccccccccc,\n" 7289 " Cccccccccccccc cccccccccc,\n" 7290 " Cccccccccccccc cccccccccc);"); 7291 verifyFormat( 7292 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7293 "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7294 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7295 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);", 7296 getGoogleStyle()); 7297 verifyFormat( 7298 "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n" 7299 " Cccccccccccccc cccccccccc,\n" 7300 " Cccccccccccccc cccccccccc,\n" 7301 " Cccccccccccccc cccccccccc,\n" 7302 " Cccccccccccccc cccccccccc,\n" 7303 " Cccccccccccccc cccccccccc,\n" 7304 " Cccccccccccccc cccccccccc);"); 7305 verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7306 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7307 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7308 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7309 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);"); 7310 7311 // Break after multi-line parameters. 7312 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7313 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7314 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7315 " bbbb bbbb);"); 7316 verifyFormat("void SomeLoooooooooooongFunction(\n" 7317 " std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n" 7318 " aaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7319 " int bbbbbbbbbbbbb);"); 7320 7321 // Treat overloaded operators like other functions. 7322 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 7323 "operator>(const SomeLoooooooooooooooooooooooooogType &other);"); 7324 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 7325 "operator>>(const SomeLooooooooooooooooooooooooogType &other);"); 7326 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 7327 "operator<<(const SomeLooooooooooooooooooooooooogType &other);"); 7328 verifyGoogleFormat( 7329 "SomeLoooooooooooooooooooooooooooooogType operator>>(\n" 7330 " const SomeLooooooooogType &a, const SomeLooooooooogType &b);"); 7331 verifyGoogleFormat( 7332 "SomeLoooooooooooooooooooooooooooooogType operator<<(\n" 7333 " const SomeLooooooooogType &a, const SomeLooooooooogType &b);"); 7334 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7335 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);"); 7336 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n" 7337 "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);"); 7338 verifyGoogleFormat( 7339 "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n" 7340 "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7341 " bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}"); 7342 verifyGoogleFormat("template <typename T>\n" 7343 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7344 "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n" 7345 " aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);"); 7346 7347 FormatStyle Style = getLLVMStyle(); 7348 Style.PointerAlignment = FormatStyle::PAS_Left; 7349 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7350 " aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}", 7351 Style); 7352 verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n" 7353 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7354 Style); 7355 } 7356 7357 TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) { 7358 // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516: 7359 // Prefer keeping `::` followed by `operator` together. 7360 EXPECT_EQ("const aaaa::bbbbbbb &\n" 7361 "ccccccccc::operator++() {\n" 7362 " stuff();\n" 7363 "}", 7364 format("const aaaa::bbbbbbb\n" 7365 "&ccccccccc::operator++() { stuff(); }", 7366 getLLVMStyleWithColumns(40))); 7367 } 7368 7369 TEST_F(FormatTest, TrailingReturnType) { 7370 verifyFormat("auto foo() -> int;\n"); 7371 // correct trailing return type spacing 7372 verifyFormat("auto operator->() -> int;\n"); 7373 verifyFormat("auto operator++(int) -> int;\n"); 7374 7375 verifyFormat("struct S {\n" 7376 " auto bar() const -> int;\n" 7377 "};"); 7378 verifyFormat("template <size_t Order, typename T>\n" 7379 "auto load_img(const std::string &filename)\n" 7380 " -> alias::tensor<Order, T, mem::tag::cpu> {}"); 7381 verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n" 7382 " -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}"); 7383 verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}"); 7384 verifyFormat("template <typename T>\n" 7385 "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n" 7386 " -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());"); 7387 7388 // Not trailing return types. 7389 verifyFormat("void f() { auto a = b->c(); }"); 7390 verifyFormat("auto a = p->foo();"); 7391 verifyFormat("int a = p->foo();"); 7392 verifyFormat("auto lmbd = [] NOEXCEPT -> int { return 0; };"); 7393 } 7394 7395 TEST_F(FormatTest, DeductionGuides) { 7396 verifyFormat("template <class T> A(const T &, const T &) -> A<T &>;"); 7397 verifyFormat("template <class T> explicit A(T &, T &&) -> A<T>;"); 7398 verifyFormat("template <class... Ts> S(Ts...) -> S<Ts...>;"); 7399 verifyFormat( 7400 "template <class... T>\n" 7401 "array(T &&...t) -> array<std::common_type_t<T...>, sizeof...(T)>;"); 7402 verifyFormat("template <class T> A() -> A<decltype(p->foo<3>())>;"); 7403 verifyFormat("template <class T> A() -> A<decltype(foo<traits<1>>)>;"); 7404 verifyFormat("template <class T> A() -> A<sizeof(p->foo<1>)>;"); 7405 verifyFormat("template <class T> A() -> A<(3 < 2)>;"); 7406 verifyFormat("template <class T> A() -> A<((3) < (2))>;"); 7407 verifyFormat("template <class T> x() -> x<1>;"); 7408 verifyFormat("template <class T> explicit x(T &) -> x<1>;"); 7409 7410 // Ensure not deduction guides. 7411 verifyFormat("c()->f<int>();"); 7412 verifyFormat("x()->foo<1>;"); 7413 verifyFormat("x = p->foo<3>();"); 7414 verifyFormat("x()->x<1>();"); 7415 verifyFormat("x()->x<1>;"); 7416 } 7417 7418 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) { 7419 // Avoid breaking before trailing 'const' or other trailing annotations, if 7420 // they are not function-like. 7421 FormatStyle Style = getGoogleStyleWithColumns(47); 7422 verifyFormat("void someLongFunction(\n" 7423 " int someLoooooooooooooongParameter) const {\n}", 7424 getLLVMStyleWithColumns(47)); 7425 verifyFormat("LoooooongReturnType\n" 7426 "someLoooooooongFunction() const {}", 7427 getLLVMStyleWithColumns(47)); 7428 verifyFormat("LoooooongReturnType someLoooooooongFunction()\n" 7429 " const {}", 7430 Style); 7431 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7432 " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;"); 7433 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7434 " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;"); 7435 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7436 " aaaaa aaaaaaaaaaaaaaaaaaaa) override final;"); 7437 verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n" 7438 " aaaaaaaaaaa aaaaa) const override;"); 7439 verifyGoogleFormat( 7440 "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7441 " const override;"); 7442 7443 // Even if the first parameter has to be wrapped. 7444 verifyFormat("void someLongFunction(\n" 7445 " int someLongParameter) const {}", 7446 getLLVMStyleWithColumns(46)); 7447 verifyFormat("void someLongFunction(\n" 7448 " int someLongParameter) const {}", 7449 Style); 7450 verifyFormat("void someLongFunction(\n" 7451 " int someLongParameter) override {}", 7452 Style); 7453 verifyFormat("void someLongFunction(\n" 7454 " int someLongParameter) OVERRIDE {}", 7455 Style); 7456 verifyFormat("void someLongFunction(\n" 7457 " int someLongParameter) final {}", 7458 Style); 7459 verifyFormat("void someLongFunction(\n" 7460 " int someLongParameter) FINAL {}", 7461 Style); 7462 verifyFormat("void someLongFunction(\n" 7463 " int parameter) const override {}", 7464 Style); 7465 7466 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 7467 verifyFormat("void someLongFunction(\n" 7468 " int someLongParameter) const\n" 7469 "{\n" 7470 "}", 7471 Style); 7472 7473 Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 7474 verifyFormat("void someLongFunction(\n" 7475 " int someLongParameter) const\n" 7476 " {\n" 7477 " }", 7478 Style); 7479 7480 // Unless these are unknown annotations. 7481 verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n" 7482 " aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7483 " LONG_AND_UGLY_ANNOTATION;"); 7484 7485 // Breaking before function-like trailing annotations is fine to keep them 7486 // close to their arguments. 7487 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7488 " LOCKS_EXCLUDED(aaaaaaaaaaaaa);"); 7489 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n" 7490 " LOCKS_EXCLUDED(aaaaaaaaaaaaa);"); 7491 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n" 7492 " LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}"); 7493 verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n" 7494 " AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);"); 7495 verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});"); 7496 7497 verifyFormat( 7498 "void aaaaaaaaaaaaaaaaaa()\n" 7499 " __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n" 7500 " aaaaaaaaaaaaaaaaaaaaaaaaa));"); 7501 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7502 " __attribute__((unused));"); 7503 verifyGoogleFormat( 7504 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7505 " GUARDED_BY(aaaaaaaaaaaa);"); 7506 verifyGoogleFormat( 7507 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7508 " GUARDED_BY(aaaaaaaaaaaa);"); 7509 verifyGoogleFormat( 7510 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n" 7511 " aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7512 verifyGoogleFormat( 7513 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n" 7514 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7515 } 7516 7517 TEST_F(FormatTest, FunctionAnnotations) { 7518 verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7519 "int OldFunction(const string ¶meter) {}"); 7520 verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7521 "string OldFunction(const string ¶meter) {}"); 7522 verifyFormat("template <typename T>\n" 7523 "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7524 "string OldFunction(const string ¶meter) {}"); 7525 7526 // Not function annotations. 7527 verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7528 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"); 7529 verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n" 7530 " ThisIsATestWithAReallyReallyReallyReallyLongName) {}"); 7531 verifyFormat("MACRO(abc).function() // wrap\n" 7532 " << abc;"); 7533 verifyFormat("MACRO(abc)->function() // wrap\n" 7534 " << abc;"); 7535 verifyFormat("MACRO(abc)::function() // wrap\n" 7536 " << abc;"); 7537 } 7538 7539 TEST_F(FormatTest, BreaksDesireably) { 7540 verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n" 7541 " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n" 7542 " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}"); 7543 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7544 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 7545 "}"); 7546 7547 verifyFormat( 7548 "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7549 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 7550 7551 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7552 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7553 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7554 7555 verifyFormat( 7556 "aaaaaaaa(aaaaaaaaaaaaa,\n" 7557 " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7558 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n" 7559 " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7560 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));"); 7561 7562 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 7563 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7564 7565 verifyFormat( 7566 "void f() {\n" 7567 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n" 7568 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 7569 "}"); 7570 verifyFormat( 7571 "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7572 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7573 verifyFormat( 7574 "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7575 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7576 verifyFormat( 7577 "aaaaaa(aaa,\n" 7578 " new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7579 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7580 " aaaa);"); 7581 verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7582 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7583 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7584 7585 // Indent consistently independent of call expression and unary operator. 7586 verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7587 " dddddddddddddddddddddddddddddd));"); 7588 verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7589 " dddddddddddddddddddddddddddddd));"); 7590 verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n" 7591 " dddddddddddddddddddddddddddddd));"); 7592 7593 // This test case breaks on an incorrect memoization, i.e. an optimization not 7594 // taking into account the StopAt value. 7595 verifyFormat( 7596 "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7597 " aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7598 " aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7599 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7600 7601 verifyFormat("{\n {\n {\n" 7602 " Annotation.SpaceRequiredBefore =\n" 7603 " Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n" 7604 " Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n" 7605 " }\n }\n}"); 7606 7607 // Break on an outer level if there was a break on an inner level. 7608 EXPECT_EQ("f(g(h(a, // comment\n" 7609 " b, c),\n" 7610 " d, e),\n" 7611 " x, y);", 7612 format("f(g(h(a, // comment\n" 7613 " b, c), d, e), x, y);")); 7614 7615 // Prefer breaking similar line breaks. 7616 verifyFormat( 7617 "const int kTrackingOptions = NSTrackingMouseMoved |\n" 7618 " NSTrackingMouseEnteredAndExited |\n" 7619 " NSTrackingActiveAlways;"); 7620 } 7621 7622 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) { 7623 FormatStyle NoBinPacking = getGoogleStyle(); 7624 NoBinPacking.BinPackParameters = false; 7625 NoBinPacking.BinPackArguments = true; 7626 verifyFormat("void f() {\n" 7627 " f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n" 7628 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 7629 "}", 7630 NoBinPacking); 7631 verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n" 7632 " int aaaaaaaaaaaaaaaaaaaa,\n" 7633 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7634 NoBinPacking); 7635 7636 NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false; 7637 verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7638 " vector<int> bbbbbbbbbbbbbbb);", 7639 NoBinPacking); 7640 // FIXME: This behavior difference is probably not wanted. However, currently 7641 // we cannot distinguish BreakBeforeParameter being set because of the wrapped 7642 // template arguments from BreakBeforeParameter being set because of the 7643 // one-per-line formatting. 7644 verifyFormat( 7645 "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n" 7646 " aaaaaaaaaa> aaaaaaaaaa);", 7647 NoBinPacking); 7648 verifyFormat( 7649 "void fffffffffff(\n" 7650 " aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n" 7651 " aaaaaaaaaa);"); 7652 } 7653 7654 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) { 7655 FormatStyle NoBinPacking = getGoogleStyle(); 7656 NoBinPacking.BinPackParameters = false; 7657 NoBinPacking.BinPackArguments = false; 7658 verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n" 7659 " aaaaaaaaaaaaaaaaaaaa,\n" 7660 " aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);", 7661 NoBinPacking); 7662 verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n" 7663 " aaaaaaaaaaaaa,\n" 7664 " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));", 7665 NoBinPacking); 7666 verifyFormat( 7667 "aaaaaaaa(aaaaaaaaaaaaa,\n" 7668 " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7669 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n" 7670 " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7671 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));", 7672 NoBinPacking); 7673 verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n" 7674 " .aaaaaaaaaaaaaaaaaa();", 7675 NoBinPacking); 7676 verifyFormat("void f() {\n" 7677 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7678 " aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n" 7679 "}", 7680 NoBinPacking); 7681 7682 verifyFormat( 7683 "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7684 " aaaaaaaaaaaa,\n" 7685 " aaaaaaaaaaaa);", 7686 NoBinPacking); 7687 verifyFormat( 7688 "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n" 7689 " ddddddddddddddddddddddddddddd),\n" 7690 " test);", 7691 NoBinPacking); 7692 7693 verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n" 7694 " aaaaaaaaaaaaaaaaaaaaaaa,\n" 7695 " aaaaaaaaaaaaaaaaaaaaaaa>\n" 7696 " aaaaaaaaaaaaaaaaaa;", 7697 NoBinPacking); 7698 verifyFormat("a(\"a\"\n" 7699 " \"a\",\n" 7700 " a);"); 7701 7702 NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false; 7703 verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n" 7704 " aaaaaaaaa,\n" 7705 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7706 NoBinPacking); 7707 verifyFormat( 7708 "void f() {\n" 7709 " aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n" 7710 " .aaaaaaa();\n" 7711 "}", 7712 NoBinPacking); 7713 verifyFormat( 7714 "template <class SomeType, class SomeOtherType>\n" 7715 "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}", 7716 NoBinPacking); 7717 } 7718 7719 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) { 7720 FormatStyle Style = getLLVMStyleWithColumns(15); 7721 Style.ExperimentalAutoDetectBinPacking = true; 7722 EXPECT_EQ("aaa(aaaa,\n" 7723 " aaaa,\n" 7724 " aaaa);\n" 7725 "aaa(aaaa,\n" 7726 " aaaa,\n" 7727 " aaaa);", 7728 format("aaa(aaaa,\n" // one-per-line 7729 " aaaa,\n" 7730 " aaaa );\n" 7731 "aaa(aaaa, aaaa, aaaa);", // inconclusive 7732 Style)); 7733 EXPECT_EQ("aaa(aaaa, aaaa,\n" 7734 " aaaa);\n" 7735 "aaa(aaaa, aaaa,\n" 7736 " aaaa);", 7737 format("aaa(aaaa, aaaa,\n" // bin-packed 7738 " aaaa );\n" 7739 "aaa(aaaa, aaaa, aaaa);", // inconclusive 7740 Style)); 7741 } 7742 7743 TEST_F(FormatTest, FormatsBuilderPattern) { 7744 verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n" 7745 " .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n" 7746 " .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n" 7747 " .StartsWith(\".init\", ORDER_INIT)\n" 7748 " .StartsWith(\".fini\", ORDER_FINI)\n" 7749 " .StartsWith(\".hash\", ORDER_HASH)\n" 7750 " .Default(ORDER_TEXT);\n"); 7751 7752 verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n" 7753 " aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();"); 7754 verifyFormat("aaaaaaa->aaaaaaa\n" 7755 " ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7756 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7757 " ->aaaaaaaa(aaaaaaaaaaaaaaa);"); 7758 verifyFormat( 7759 "aaaaaaa->aaaaaaa\n" 7760 " ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7761 " ->aaaaaaaa(aaaaaaaaaaaaaaa);"); 7762 verifyFormat( 7763 "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n" 7764 " aaaaaaaaaaaaaa);"); 7765 verifyFormat( 7766 "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n" 7767 " aaaaaa->aaaaaaaaaaaa()\n" 7768 " ->aaaaaaaaaaaaaaaa(\n" 7769 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7770 " ->aaaaaaaaaaaaaaaaa();"); 7771 verifyGoogleFormat( 7772 "void f() {\n" 7773 " someo->Add((new util::filetools::Handler(dir))\n" 7774 " ->OnEvent1(NewPermanentCallback(\n" 7775 " this, &HandlerHolderClass::EventHandlerCBA))\n" 7776 " ->OnEvent2(NewPermanentCallback(\n" 7777 " this, &HandlerHolderClass::EventHandlerCBB))\n" 7778 " ->OnEvent3(NewPermanentCallback(\n" 7779 " this, &HandlerHolderClass::EventHandlerCBC))\n" 7780 " ->OnEvent5(NewPermanentCallback(\n" 7781 " this, &HandlerHolderClass::EventHandlerCBD))\n" 7782 " ->OnEvent6(NewPermanentCallback(\n" 7783 " this, &HandlerHolderClass::EventHandlerCBE)));\n" 7784 "}"); 7785 7786 verifyFormat( 7787 "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();"); 7788 verifyFormat("aaaaaaaaaaaaaaa()\n" 7789 " .aaaaaaaaaaaaaaa()\n" 7790 " .aaaaaaaaaaaaaaa()\n" 7791 " .aaaaaaaaaaaaaaa()\n" 7792 " .aaaaaaaaaaaaaaa();"); 7793 verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7794 " .aaaaaaaaaaaaaaa()\n" 7795 " .aaaaaaaaaaaaaaa()\n" 7796 " .aaaaaaaaaaaaaaa();"); 7797 verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7798 " .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7799 " .aaaaaaaaaaaaaaa();"); 7800 verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n" 7801 " ->aaaaaaaaaaaaaae(0)\n" 7802 " ->aaaaaaaaaaaaaaa();"); 7803 7804 // Don't linewrap after very short segments. 7805 verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7806 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7807 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7808 verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7809 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7810 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7811 verifyFormat("aaa()\n" 7812 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7813 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7814 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7815 7816 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n" 7817 " .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7818 " .has<bbbbbbbbbbbbbbbbbbbbb>();"); 7819 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n" 7820 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 7821 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();"); 7822 7823 // Prefer not to break after empty parentheses. 7824 verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n" 7825 " First->LastNewlineOffset);"); 7826 7827 // Prefer not to create "hanging" indents. 7828 verifyFormat( 7829 "return !soooooooooooooome_map\n" 7830 " .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7831 " .second;"); 7832 verifyFormat( 7833 "return aaaaaaaaaaaaaaaa\n" 7834 " .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n" 7835 " .aaaa(aaaaaaaaaaaaaa);"); 7836 // No hanging indent here. 7837 verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n" 7838 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7839 verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n" 7840 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7841 verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n" 7842 " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7843 getLLVMStyleWithColumns(60)); 7844 verifyFormat("aaaaaaaaaaaaaaaaaa\n" 7845 " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n" 7846 " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7847 getLLVMStyleWithColumns(59)); 7848 verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7849 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7850 " .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7851 7852 // Dont break if only closing statements before member call 7853 verifyFormat("test() {\n" 7854 " ([]() -> {\n" 7855 " int b = 32;\n" 7856 " return 3;\n" 7857 " }).foo();\n" 7858 "}"); 7859 verifyFormat("test() {\n" 7860 " (\n" 7861 " []() -> {\n" 7862 " int b = 32;\n" 7863 " return 3;\n" 7864 " },\n" 7865 " foo, bar)\n" 7866 " .foo();\n" 7867 "}"); 7868 verifyFormat("test() {\n" 7869 " ([]() -> {\n" 7870 " int b = 32;\n" 7871 " return 3;\n" 7872 " })\n" 7873 " .foo()\n" 7874 " .bar();\n" 7875 "}"); 7876 verifyFormat("test() {\n" 7877 " ([]() -> {\n" 7878 " int b = 32;\n" 7879 " return 3;\n" 7880 " })\n" 7881 " .foo(\"aaaaaaaaaaaaaaaaa\"\n" 7882 " \"bbbb\");\n" 7883 "}", 7884 getLLVMStyleWithColumns(30)); 7885 } 7886 7887 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) { 7888 verifyFormat( 7889 "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 7890 " bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}"); 7891 verifyFormat( 7892 "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n" 7893 " bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}"); 7894 7895 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" 7896 " ccccccccccccccccccccccccc) {\n}"); 7897 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n" 7898 " ccccccccccccccccccccccccc) {\n}"); 7899 7900 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" 7901 " ccccccccccccccccccccccccc) {\n}"); 7902 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n" 7903 " ccccccccccccccccccccccccc) {\n}"); 7904 7905 verifyFormat( 7906 "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n" 7907 " ccccccccccccccccccccccccc) {\n}"); 7908 verifyFormat( 7909 "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n" 7910 " ccccccccccccccccccccccccc) {\n}"); 7911 7912 verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n" 7913 " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n" 7914 " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n" 7915 " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;"); 7916 verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n" 7917 " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n" 7918 " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n" 7919 " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;"); 7920 7921 verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n" 7922 " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n" 7923 " aaaaaaaaaaaaaaa != aa) {\n}"); 7924 verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n" 7925 " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n" 7926 " aaaaaaaaaaaaaaa != aa) {\n}"); 7927 } 7928 7929 TEST_F(FormatTest, BreaksAfterAssignments) { 7930 verifyFormat( 7931 "unsigned Cost =\n" 7932 " TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n" 7933 " SI->getPointerAddressSpaceee());\n"); 7934 verifyFormat( 7935 "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n" 7936 " Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());"); 7937 7938 verifyFormat( 7939 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n" 7940 " aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);"); 7941 verifyFormat("unsigned OriginalStartColumn =\n" 7942 " SourceMgr.getSpellingColumnNumber(\n" 7943 " Current.FormatTok.getStartOfNonWhitespace()) -\n" 7944 " 1;"); 7945 } 7946 7947 TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) { 7948 FormatStyle Style = getLLVMStyle(); 7949 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 7950 " bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;", 7951 Style); 7952 7953 Style.PenaltyBreakAssignment = 20; 7954 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n" 7955 " cccccccccccccccccccccccccc;", 7956 Style); 7957 } 7958 7959 TEST_F(FormatTest, AlignsAfterAssignments) { 7960 verifyFormat( 7961 "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7962 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7963 verifyFormat( 7964 "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7965 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7966 verifyFormat( 7967 "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7968 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7969 verifyFormat( 7970 "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7971 " aaaaaaaaaaaaaaaaaaaaaaaaa);"); 7972 verifyFormat( 7973 "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n" 7974 " aaaaaaaaaaaaaaaaaaaaaaaa +\n" 7975 " aaaaaaaaaaaaaaaaaaaaaaaa;"); 7976 } 7977 7978 TEST_F(FormatTest, AlignsAfterReturn) { 7979 verifyFormat( 7980 "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7981 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7982 verifyFormat( 7983 "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7984 " aaaaaaaaaaaaaaaaaaaaaaaaa);"); 7985 verifyFormat( 7986 "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n" 7987 " aaaaaaaaaaaaaaaaaaaaaa();"); 7988 verifyFormat( 7989 "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n" 7990 " aaaaaaaaaaaaaaaaaaaaaa());"); 7991 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7992 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7993 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7994 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n" 7995 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7996 verifyFormat("return\n" 7997 " // true if code is one of a or b.\n" 7998 " code == a || code == b;"); 7999 } 8000 8001 TEST_F(FormatTest, AlignsAfterOpenBracket) { 8002 verifyFormat( 8003 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n" 8004 " aaaaaaaaa aaaaaaa) {}"); 8005 verifyFormat( 8006 "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n" 8007 " aaaaaaaaaaa aaaaaaaaa);"); 8008 verifyFormat( 8009 "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n" 8010 " aaaaaaaaaaaaaaaaaaaaa));"); 8011 FormatStyle Style = getLLVMStyle(); 8012 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 8013 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8014 " aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}", 8015 Style); 8016 verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n" 8017 " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);", 8018 Style); 8019 verifyFormat("SomeLongVariableName->someFunction(\n" 8020 " foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));", 8021 Style); 8022 verifyFormat( 8023 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n" 8024 " aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 8025 Style); 8026 verifyFormat( 8027 "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n" 8028 " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8029 Style); 8030 verifyFormat( 8031 "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n" 8032 " aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));", 8033 Style); 8034 8035 verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n" 8036 " ccccccc(aaaaaaaaaaaaaaaaa, //\n" 8037 " b));", 8038 Style); 8039 8040 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 8041 Style.BinPackArguments = false; 8042 Style.BinPackParameters = false; 8043 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8044 " aaaaaaaaaaa aaaaaaaa,\n" 8045 " aaaaaaaaa aaaaaaa,\n" 8046 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 8047 Style); 8048 verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n" 8049 " aaaaaaaaaaa aaaaaaaaa,\n" 8050 " aaaaaaaaaaa aaaaaaaaa,\n" 8051 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8052 Style); 8053 verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n" 8054 " aaaaaaaaaaaaaaa,\n" 8055 " aaaaaaaaaaaaaaaaaaaaa,\n" 8056 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));", 8057 Style); 8058 verifyFormat( 8059 "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n" 8060 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));", 8061 Style); 8062 verifyFormat( 8063 "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n" 8064 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));", 8065 Style); 8066 verifyFormat( 8067 "aaaaaaaaaaaaaaaaaaaaaaaa(\n" 8068 " aaaaaaaaaaaaaaaaaaaaa(\n" 8069 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n" 8070 " aaaaaaaaaaaaaaaa);", 8071 Style); 8072 verifyFormat( 8073 "aaaaaaaaaaaaaaaaaaaaaaaa(\n" 8074 " aaaaaaaaaaaaaaaaaaaaa(\n" 8075 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n" 8076 " aaaaaaaaaaaaaaaa);", 8077 Style); 8078 } 8079 8080 TEST_F(FormatTest, ParenthesesAndOperandAlignment) { 8081 FormatStyle Style = getLLVMStyleWithColumns(40); 8082 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 8083 " bbbbbbbbbbbbbbbbbbbbbb);", 8084 Style); 8085 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 8086 Style.AlignOperands = FormatStyle::OAS_DontAlign; 8087 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 8088 " bbbbbbbbbbbbbbbbbbbbbb);", 8089 Style); 8090 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 8091 Style.AlignOperands = FormatStyle::OAS_Align; 8092 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 8093 " bbbbbbbbbbbbbbbbbbbbbb);", 8094 Style); 8095 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 8096 Style.AlignOperands = FormatStyle::OAS_DontAlign; 8097 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 8098 " bbbbbbbbbbbbbbbbbbbbbb);", 8099 Style); 8100 } 8101 8102 TEST_F(FormatTest, BreaksConditionalExpressions) { 8103 verifyFormat( 8104 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8105 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8106 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8107 verifyFormat( 8108 "aaaa(aaaaaaaaaa, aaaaaaaa,\n" 8109 " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8110 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8111 verifyFormat( 8112 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8113 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8114 verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n" 8115 " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8116 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8117 verifyFormat( 8118 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n" 8119 " : aaaaaaaaaaaaa);"); 8120 verifyFormat( 8121 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8122 " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8123 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8124 " aaaaaaaaaaaaa);"); 8125 verifyFormat( 8126 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8127 " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8128 " aaaaaaaaaaaaa);"); 8129 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8130 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8131 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8132 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8133 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8134 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8135 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8136 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8137 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8138 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8139 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8140 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8141 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8142 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8143 " ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8144 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8145 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8146 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8147 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8148 " : aaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8149 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n" 8150 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8151 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8152 " : aaaaaaaaaaaaaaaa;"); 8153 verifyFormat( 8154 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8155 " ? aaaaaaaaaaaaaaa\n" 8156 " : aaaaaaaaaaaaaaa;"); 8157 verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n" 8158 " aaaaaaaaa\n" 8159 " ? b\n" 8160 " : c);"); 8161 verifyFormat("return aaaa == bbbb\n" 8162 " // comment\n" 8163 " ? aaaa\n" 8164 " : bbbb;"); 8165 verifyFormat("unsigned Indent =\n" 8166 " format(TheLine.First,\n" 8167 " IndentForLevel[TheLine.Level] >= 0\n" 8168 " ? IndentForLevel[TheLine.Level]\n" 8169 " : TheLine * 2,\n" 8170 " TheLine.InPPDirective, PreviousEndOfLineColumn);", 8171 getLLVMStyleWithColumns(60)); 8172 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n" 8173 " ? aaaaaaaaaaaaaaa\n" 8174 " : bbbbbbbbbbbbbbb //\n" 8175 " ? ccccccccccccccc\n" 8176 " : ddddddddddddddd;"); 8177 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n" 8178 " ? aaaaaaaaaaaaaaa\n" 8179 " : (bbbbbbbbbbbbbbb //\n" 8180 " ? ccccccccccccccc\n" 8181 " : ddddddddddddddd);"); 8182 verifyFormat( 8183 "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8184 " ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 8185 " aaaaaaaaaaaaaaaaaaaaa +\n" 8186 " aaaaaaaaaaaaaaaaaaaaa\n" 8187 " : aaaaaaaaaa;"); 8188 verifyFormat( 8189 "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8190 " : aaaaaaaaaaaaaaaaaaaaaa\n" 8191 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8192 8193 FormatStyle NoBinPacking = getLLVMStyle(); 8194 NoBinPacking.BinPackArguments = false; 8195 verifyFormat( 8196 "void f() {\n" 8197 " g(aaa,\n" 8198 " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n" 8199 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8200 " ? aaaaaaaaaaaaaaa\n" 8201 " : aaaaaaaaaaaaaaa);\n" 8202 "}", 8203 NoBinPacking); 8204 verifyFormat( 8205 "void f() {\n" 8206 " g(aaa,\n" 8207 " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n" 8208 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8209 " ?: aaaaaaaaaaaaaaa);\n" 8210 "}", 8211 NoBinPacking); 8212 8213 verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n" 8214 " // comment.\n" 8215 " ccccccccccccccccccccccccccccccccccccccc\n" 8216 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8217 " : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);"); 8218 8219 // Assignments in conditional expressions. Apparently not uncommon :-(. 8220 verifyFormat("return a != b\n" 8221 " // comment\n" 8222 " ? a = b\n" 8223 " : a = b;"); 8224 verifyFormat("return a != b\n" 8225 " // comment\n" 8226 " ? a = a != b\n" 8227 " // comment\n" 8228 " ? a = b\n" 8229 " : a\n" 8230 " : a;\n"); 8231 verifyFormat("return a != b\n" 8232 " // comment\n" 8233 " ? a\n" 8234 " : a = a != b\n" 8235 " // comment\n" 8236 " ? a = b\n" 8237 " : a;"); 8238 8239 // Chained conditionals 8240 FormatStyle Style = getLLVMStyleWithColumns(70); 8241 Style.AlignOperands = FormatStyle::OAS_Align; 8242 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8243 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8244 " : 3333333333333333;", 8245 Style); 8246 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8247 " : bbbbbbbbbb ? 2222222222222222\n" 8248 " : 3333333333333333;", 8249 Style); 8250 verifyFormat("return aaaaaaaaaa ? 1111111111111111\n" 8251 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 8252 " : 3333333333333333;", 8253 Style); 8254 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8255 " : bbbbbbbbbbbbbb ? 222222\n" 8256 " : 333333;", 8257 Style); 8258 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8259 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8260 " : cccccccccccccc ? 3333333333333333\n" 8261 " : 4444444444444444;", 8262 Style); 8263 verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc)\n" 8264 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8265 " : 3333333333333333;", 8266 Style); 8267 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8268 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8269 " : (aaa ? bbb : ccc);", 8270 Style); 8271 verifyFormat( 8272 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8273 " : cccccccccccccccccc)\n" 8274 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8275 " : 3333333333333333;", 8276 Style); 8277 verifyFormat( 8278 "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8279 " : cccccccccccccccccc)\n" 8280 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8281 " : 3333333333333333;", 8282 Style); 8283 verifyFormat( 8284 "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8285 " : dddddddddddddddddd)\n" 8286 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8287 " : 3333333333333333;", 8288 Style); 8289 verifyFormat( 8290 "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8291 " : dddddddddddddddddd)\n" 8292 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8293 " : 3333333333333333;", 8294 Style); 8295 verifyFormat( 8296 "return aaaaaaaaa ? 1111111111111111\n" 8297 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8298 " : a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8299 " : dddddddddddddddddd)\n", 8300 Style); 8301 verifyFormat( 8302 "return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8303 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8304 " : (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8305 " : cccccccccccccccccc);", 8306 Style); 8307 verifyFormat( 8308 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8309 " : ccccccccccccccc ? dddddddddddddddddd\n" 8310 " : eeeeeeeeeeeeeeeeee)\n" 8311 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8312 " : 3333333333333333;", 8313 Style); 8314 verifyFormat( 8315 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8316 " : ccccccccccccccc ? dddddddddddddddddd\n" 8317 " : eeeeeeeeeeeeeeeeee)\n" 8318 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8319 " : 3333333333333333;", 8320 Style); 8321 verifyFormat( 8322 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8323 " : cccccccccccc ? dddddddddddddddddd\n" 8324 " : eeeeeeeeeeeeeeeeee)\n" 8325 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8326 " : 3333333333333333;", 8327 Style); 8328 verifyFormat( 8329 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8330 " : cccccccccccccccccc\n" 8331 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8332 " : 3333333333333333;", 8333 Style); 8334 verifyFormat( 8335 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8336 " : cccccccccccccccc ? dddddddddddddddddd\n" 8337 " : eeeeeeeeeeeeeeeeee\n" 8338 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8339 " : 3333333333333333;", 8340 Style); 8341 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa\n" 8342 " ? (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8343 " : cccccccccccccccccc ? dddddddddddddddddd\n" 8344 " : eeeeeeeeeeeeeeeeee)\n" 8345 " : bbbbbbbbbbbbbbbbbbb ? 2222222222222222\n" 8346 " : 3333333333333333;", 8347 Style); 8348 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaa\n" 8349 " ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8350 " : cccccccccccccccc ? dddddddddddddddddd\n" 8351 " : eeeeeeeeeeeeeeeeee\n" 8352 " : bbbbbbbbbbbbbbbbbbbbbbb ? 2222222222222222\n" 8353 " : 3333333333333333;", 8354 Style); 8355 8356 Style.AlignOperands = FormatStyle::OAS_DontAlign; 8357 Style.BreakBeforeTernaryOperators = false; 8358 // FIXME: Aligning the question marks is weird given DontAlign. 8359 // Consider disabling this alignment in this case. Also check whether this 8360 // will render the adjustment from https://reviews.llvm.org/D82199 8361 // unnecessary. 8362 verifyFormat("int x = aaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa :\n" 8363 " bbbb ? cccccccccccccccccc :\n" 8364 " ddddd;\n", 8365 Style); 8366 8367 EXPECT_EQ( 8368 "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n" 8369 " /*\n" 8370 " */\n" 8371 " function() {\n" 8372 " try {\n" 8373 " return JJJJJJJJJJJJJJ(\n" 8374 " pppppppppppppppppppppppppppppppppppppppppppppppppp);\n" 8375 " }\n" 8376 " } :\n" 8377 " function() {};", 8378 format( 8379 "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n" 8380 " /*\n" 8381 " */\n" 8382 " function() {\n" 8383 " try {\n" 8384 " return JJJJJJJJJJJJJJ(\n" 8385 " pppppppppppppppppppppppppppppppppppppppppppppppppp);\n" 8386 " }\n" 8387 " } :\n" 8388 " function() {};", 8389 getGoogleStyle(FormatStyle::LK_JavaScript))); 8390 } 8391 8392 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) { 8393 FormatStyle Style = getLLVMStyleWithColumns(70); 8394 Style.BreakBeforeTernaryOperators = false; 8395 verifyFormat( 8396 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8397 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8398 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8399 Style); 8400 verifyFormat( 8401 "aaaa(aaaaaaaaaa, aaaaaaaa,\n" 8402 " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8403 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8404 Style); 8405 verifyFormat( 8406 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8407 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8408 Style); 8409 verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n" 8410 " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8411 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8412 Style); 8413 verifyFormat( 8414 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n" 8415 " aaaaaaaaaaaaa);", 8416 Style); 8417 verifyFormat( 8418 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8419 " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8420 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8421 " aaaaaaaaaaaaa);", 8422 Style); 8423 verifyFormat( 8424 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8425 " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8426 " aaaaaaaaaaaaa);", 8427 Style); 8428 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8429 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8430 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 8431 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8432 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8433 Style); 8434 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8435 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8436 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8437 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 8438 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8439 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8440 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8441 Style); 8442 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8443 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n" 8444 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8445 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8446 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8447 Style); 8448 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8449 " aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8450 " aaaaaaaaaaaaaaaaaaaaaaaaaaa;", 8451 Style); 8452 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n" 8453 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8454 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8455 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 8456 Style); 8457 verifyFormat( 8458 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8459 " aaaaaaaaaaaaaaa :\n" 8460 " aaaaaaaaaaaaaaa;", 8461 Style); 8462 verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n" 8463 " aaaaaaaaa ?\n" 8464 " b :\n" 8465 " c);", 8466 Style); 8467 verifyFormat("unsigned Indent =\n" 8468 " format(TheLine.First,\n" 8469 " IndentForLevel[TheLine.Level] >= 0 ?\n" 8470 " IndentForLevel[TheLine.Level] :\n" 8471 " TheLine * 2,\n" 8472 " TheLine.InPPDirective, PreviousEndOfLineColumn);", 8473 Style); 8474 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n" 8475 " aaaaaaaaaaaaaaa :\n" 8476 " bbbbbbbbbbbbbbb ? //\n" 8477 " ccccccccccccccc :\n" 8478 " ddddddddddddddd;", 8479 Style); 8480 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n" 8481 " aaaaaaaaaaaaaaa :\n" 8482 " (bbbbbbbbbbbbbbb ? //\n" 8483 " ccccccccccccccc :\n" 8484 " ddddddddddddddd);", 8485 Style); 8486 verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8487 " /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n" 8488 " ccccccccccccccccccccccccccc;", 8489 Style); 8490 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8491 " aaaaa :\n" 8492 " bbbbbbbbbbbbbbb + cccccccccccccccc;", 8493 Style); 8494 8495 // Chained conditionals 8496 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8497 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8498 " 3333333333333333;", 8499 Style); 8500 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8501 " bbbbbbbbbb ? 2222222222222222 :\n" 8502 " 3333333333333333;", 8503 Style); 8504 verifyFormat("return aaaaaaaaaa ? 1111111111111111 :\n" 8505 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8506 " 3333333333333333;", 8507 Style); 8508 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8509 " bbbbbbbbbbbbbbbb ? 222222 :\n" 8510 " 333333;", 8511 Style); 8512 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8513 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8514 " cccccccccccccccc ? 3333333333333333 :\n" 8515 " 4444444444444444;", 8516 Style); 8517 verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc) :\n" 8518 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8519 " 3333333333333333;", 8520 Style); 8521 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8522 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8523 " (aaa ? bbb : ccc);", 8524 Style); 8525 verifyFormat( 8526 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8527 " cccccccccccccccccc) :\n" 8528 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8529 " 3333333333333333;", 8530 Style); 8531 verifyFormat( 8532 "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8533 " cccccccccccccccccc) :\n" 8534 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8535 " 3333333333333333;", 8536 Style); 8537 verifyFormat( 8538 "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8539 " dddddddddddddddddd) :\n" 8540 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8541 " 3333333333333333;", 8542 Style); 8543 verifyFormat( 8544 "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8545 " dddddddddddddddddd) :\n" 8546 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8547 " 3333333333333333;", 8548 Style); 8549 verifyFormat( 8550 "return aaaaaaaaa ? 1111111111111111 :\n" 8551 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8552 " a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8553 " dddddddddddddddddd)\n", 8554 Style); 8555 verifyFormat( 8556 "return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8557 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8558 " (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8559 " cccccccccccccccccc);", 8560 Style); 8561 verifyFormat( 8562 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8563 " ccccccccccccccccc ? dddddddddddddddddd :\n" 8564 " eeeeeeeeeeeeeeeeee) :\n" 8565 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8566 " 3333333333333333;", 8567 Style); 8568 verifyFormat( 8569 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8570 " ccccccccccccc ? dddddddddddddddddd :\n" 8571 " eeeeeeeeeeeeeeeeee) :\n" 8572 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8573 " 3333333333333333;", 8574 Style); 8575 verifyFormat( 8576 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8577 " ccccccccccccccccc ? dddddddddddddddddd :\n" 8578 " eeeeeeeeeeeeeeeeee) :\n" 8579 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8580 " 3333333333333333;", 8581 Style); 8582 verifyFormat( 8583 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8584 " cccccccccccccccccc :\n" 8585 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8586 " 3333333333333333;", 8587 Style); 8588 verifyFormat( 8589 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8590 " cccccccccccccccccc ? dddddddddddddddddd :\n" 8591 " eeeeeeeeeeeeeeeeee :\n" 8592 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8593 " 3333333333333333;", 8594 Style); 8595 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n" 8596 " (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8597 " cccccccccccccccccc ? dddddddddddddddddd :\n" 8598 " eeeeeeeeeeeeeeeeee) :\n" 8599 " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8600 " 3333333333333333;", 8601 Style); 8602 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n" 8603 " aaaaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8604 " cccccccccccccccccccc ? dddddddddddddddddd :\n" 8605 " eeeeeeeeeeeeeeeeee :\n" 8606 " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8607 " 3333333333333333;", 8608 Style); 8609 } 8610 8611 TEST_F(FormatTest, DeclarationsOfMultipleVariables) { 8612 verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n" 8613 " aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();"); 8614 verifyFormat("bool a = true, b = false;"); 8615 8616 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n" 8617 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n" 8618 " bbbbbbbbbbbbbbbbbbbbbbbbb =\n" 8619 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);"); 8620 verifyFormat( 8621 "bool aaaaaaaaaaaaaaaaaaaaa =\n" 8622 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n" 8623 " d = e && f;"); 8624 verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n" 8625 " c = cccccccccccccccccccc, d = dddddddddddddddddddd;"); 8626 verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n" 8627 " *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;"); 8628 verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n" 8629 " ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;"); 8630 8631 FormatStyle Style = getGoogleStyle(); 8632 Style.PointerAlignment = FormatStyle::PAS_Left; 8633 Style.DerivePointerAlignment = false; 8634 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8635 " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n" 8636 " *b = bbbbbbbbbbbbbbbbbbb;", 8637 Style); 8638 verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n" 8639 " *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;", 8640 Style); 8641 verifyFormat("vector<int*> a, b;", Style); 8642 verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style); 8643 verifyFormat("/*comment*/ for (int *p, *q; p != q; p = p->next) {\n}", Style); 8644 verifyFormat("if (int *p, *q; p != q) {\n p = p->next;\n}", Style); 8645 verifyFormat("/*comment*/ if (int *p, *q; p != q) {\n p = p->next;\n}", 8646 Style); 8647 verifyFormat("switch (int *p, *q; p != q) {\n default:\n break;\n}", 8648 Style); 8649 verifyFormat( 8650 "/*comment*/ switch (int *p, *q; p != q) {\n default:\n break;\n}", 8651 Style); 8652 8653 verifyFormat("if ([](int* p, int* q) {}()) {\n}", Style); 8654 verifyFormat("for ([](int* p, int* q) {}();;) {\n}", Style); 8655 verifyFormat("for (; [](int* p, int* q) {}();) {\n}", Style); 8656 verifyFormat("for (;; [](int* p, int* q) {}()) {\n}", Style); 8657 verifyFormat("switch ([](int* p, int* q) {}()) {\n default:\n break;\n}", 8658 Style); 8659 } 8660 8661 TEST_F(FormatTest, ConditionalExpressionsInBrackets) { 8662 verifyFormat("arr[foo ? bar : baz];"); 8663 verifyFormat("f()[foo ? bar : baz];"); 8664 verifyFormat("(a + b)[foo ? bar : baz];"); 8665 verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];"); 8666 } 8667 8668 TEST_F(FormatTest, AlignsStringLiterals) { 8669 verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n" 8670 " \"short literal\");"); 8671 verifyFormat( 8672 "looooooooooooooooooooooooongFunction(\n" 8673 " \"short literal\"\n" 8674 " \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");"); 8675 verifyFormat("someFunction(\"Always break between multi-line\"\n" 8676 " \" string literals\",\n" 8677 " and, other, parameters);"); 8678 EXPECT_EQ("fun + \"1243\" /* comment */\n" 8679 " \"5678\";", 8680 format("fun + \"1243\" /* comment */\n" 8681 " \"5678\";", 8682 getLLVMStyleWithColumns(28))); 8683 EXPECT_EQ( 8684 "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 8685 " \"aaaaaaaaaaaaaaaaaaaaa\"\n" 8686 " \"aaaaaaaaaaaaaaaa\";", 8687 format("aaaaaa =" 8688 "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa " 8689 "aaaaaaaaaaaaaaaaaaaaa\" " 8690 "\"aaaaaaaaaaaaaaaa\";")); 8691 verifyFormat("a = a + \"a\"\n" 8692 " \"a\"\n" 8693 " \"a\";"); 8694 verifyFormat("f(\"a\", \"b\"\n" 8695 " \"c\");"); 8696 8697 verifyFormat( 8698 "#define LL_FORMAT \"ll\"\n" 8699 "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n" 8700 " \"d, ddddddddd: %\" LL_FORMAT \"d\");"); 8701 8702 verifyFormat("#define A(X) \\\n" 8703 " \"aaaaa\" #X \"bbbbbb\" \\\n" 8704 " \"ccccc\"", 8705 getLLVMStyleWithColumns(23)); 8706 verifyFormat("#define A \"def\"\n" 8707 "f(\"abc\" A \"ghi\"\n" 8708 " \"jkl\");"); 8709 8710 verifyFormat("f(L\"a\"\n" 8711 " L\"b\");"); 8712 verifyFormat("#define A(X) \\\n" 8713 " L\"aaaaa\" #X L\"bbbbbb\" \\\n" 8714 " L\"ccccc\"", 8715 getLLVMStyleWithColumns(25)); 8716 8717 verifyFormat("f(@\"a\"\n" 8718 " @\"b\");"); 8719 verifyFormat("NSString s = @\"a\"\n" 8720 " @\"b\"\n" 8721 " @\"c\";"); 8722 verifyFormat("NSString s = @\"a\"\n" 8723 " \"b\"\n" 8724 " \"c\";"); 8725 } 8726 8727 TEST_F(FormatTest, ReturnTypeBreakingStyle) { 8728 FormatStyle Style = getLLVMStyle(); 8729 // No declarations or definitions should be moved to own line. 8730 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None; 8731 verifyFormat("class A {\n" 8732 " int f() { return 1; }\n" 8733 " int g();\n" 8734 "};\n" 8735 "int f() { return 1; }\n" 8736 "int g();\n", 8737 Style); 8738 8739 // All declarations and definitions should have the return type moved to its 8740 // own line. 8741 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 8742 Style.TypenameMacros = {"LIST"}; 8743 verifyFormat("SomeType\n" 8744 "funcdecl(LIST(uint64_t));", 8745 Style); 8746 verifyFormat("class E {\n" 8747 " int\n" 8748 " f() {\n" 8749 " return 1;\n" 8750 " }\n" 8751 " int\n" 8752 " g();\n" 8753 "};\n" 8754 "int\n" 8755 "f() {\n" 8756 " return 1;\n" 8757 "}\n" 8758 "int\n" 8759 "g();\n", 8760 Style); 8761 8762 // Top-level definitions, and no kinds of declarations should have the 8763 // return type moved to its own line. 8764 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions; 8765 verifyFormat("class B {\n" 8766 " int f() { return 1; }\n" 8767 " int g();\n" 8768 "};\n" 8769 "int\n" 8770 "f() {\n" 8771 " return 1;\n" 8772 "}\n" 8773 "int g();\n", 8774 Style); 8775 8776 // Top-level definitions and declarations should have the return type moved 8777 // to its own line. 8778 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel; 8779 verifyFormat("class C {\n" 8780 " int f() { return 1; }\n" 8781 " int g();\n" 8782 "};\n" 8783 "int\n" 8784 "f() {\n" 8785 " return 1;\n" 8786 "}\n" 8787 "int\n" 8788 "g();\n", 8789 Style); 8790 8791 // All definitions should have the return type moved to its own line, but no 8792 // kinds of declarations. 8793 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions; 8794 verifyFormat("class D {\n" 8795 " int\n" 8796 " f() {\n" 8797 " return 1;\n" 8798 " }\n" 8799 " int g();\n" 8800 "};\n" 8801 "int\n" 8802 "f() {\n" 8803 " return 1;\n" 8804 "}\n" 8805 "int g();\n", 8806 Style); 8807 verifyFormat("const char *\n" 8808 "f(void) {\n" // Break here. 8809 " return \"\";\n" 8810 "}\n" 8811 "const char *bar(void);\n", // No break here. 8812 Style); 8813 verifyFormat("template <class T>\n" 8814 "T *\n" 8815 "f(T &c) {\n" // Break here. 8816 " return NULL;\n" 8817 "}\n" 8818 "template <class T> T *f(T &c);\n", // No break here. 8819 Style); 8820 verifyFormat("class C {\n" 8821 " int\n" 8822 " operator+() {\n" 8823 " return 1;\n" 8824 " }\n" 8825 " int\n" 8826 " operator()() {\n" 8827 " return 1;\n" 8828 " }\n" 8829 "};\n", 8830 Style); 8831 verifyFormat("void\n" 8832 "A::operator()() {}\n" 8833 "void\n" 8834 "A::operator>>() {}\n" 8835 "void\n" 8836 "A::operator+() {}\n" 8837 "void\n" 8838 "A::operator*() {}\n" 8839 "void\n" 8840 "A::operator->() {}\n" 8841 "void\n" 8842 "A::operator void *() {}\n" 8843 "void\n" 8844 "A::operator void &() {}\n" 8845 "void\n" 8846 "A::operator void &&() {}\n" 8847 "void\n" 8848 "A::operator char *() {}\n" 8849 "void\n" 8850 "A::operator[]() {}\n" 8851 "void\n" 8852 "A::operator!() {}\n" 8853 "void\n" 8854 "A::operator**() {}\n" 8855 "void\n" 8856 "A::operator<Foo> *() {}\n" 8857 "void\n" 8858 "A::operator<Foo> **() {}\n" 8859 "void\n" 8860 "A::operator<Foo> &() {}\n" 8861 "void\n" 8862 "A::operator void **() {}\n", 8863 Style); 8864 verifyFormat("constexpr auto\n" 8865 "operator()() const -> reference {}\n" 8866 "constexpr auto\n" 8867 "operator>>() const -> reference {}\n" 8868 "constexpr auto\n" 8869 "operator+() const -> reference {}\n" 8870 "constexpr auto\n" 8871 "operator*() const -> reference {}\n" 8872 "constexpr auto\n" 8873 "operator->() const -> reference {}\n" 8874 "constexpr auto\n" 8875 "operator++() const -> reference {}\n" 8876 "constexpr auto\n" 8877 "operator void *() const -> reference {}\n" 8878 "constexpr auto\n" 8879 "operator void **() const -> reference {}\n" 8880 "constexpr auto\n" 8881 "operator void *() const -> reference {}\n" 8882 "constexpr auto\n" 8883 "operator void &() const -> reference {}\n" 8884 "constexpr auto\n" 8885 "operator void &&() const -> reference {}\n" 8886 "constexpr auto\n" 8887 "operator char *() const -> reference {}\n" 8888 "constexpr auto\n" 8889 "operator!() const -> reference {}\n" 8890 "constexpr auto\n" 8891 "operator[]() const -> reference {}\n", 8892 Style); 8893 verifyFormat("void *operator new(std::size_t s);", // No break here. 8894 Style); 8895 verifyFormat("void *\n" 8896 "operator new(std::size_t s) {}", 8897 Style); 8898 verifyFormat("void *\n" 8899 "operator delete[](void *ptr) {}", 8900 Style); 8901 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 8902 verifyFormat("const char *\n" 8903 "f(void)\n" // Break here. 8904 "{\n" 8905 " return \"\";\n" 8906 "}\n" 8907 "const char *bar(void);\n", // No break here. 8908 Style); 8909 verifyFormat("template <class T>\n" 8910 "T *\n" // Problem here: no line break 8911 "f(T &c)\n" // Break here. 8912 "{\n" 8913 " return NULL;\n" 8914 "}\n" 8915 "template <class T> T *f(T &c);\n", // No break here. 8916 Style); 8917 verifyFormat("int\n" 8918 "foo(A<bool> a)\n" 8919 "{\n" 8920 " return a;\n" 8921 "}\n", 8922 Style); 8923 verifyFormat("int\n" 8924 "foo(A<8> a)\n" 8925 "{\n" 8926 " return a;\n" 8927 "}\n", 8928 Style); 8929 verifyFormat("int\n" 8930 "foo(A<B<bool>, 8> a)\n" 8931 "{\n" 8932 " return a;\n" 8933 "}\n", 8934 Style); 8935 verifyFormat("int\n" 8936 "foo(A<B<8>, bool> a)\n" 8937 "{\n" 8938 " return a;\n" 8939 "}\n", 8940 Style); 8941 verifyFormat("int\n" 8942 "foo(A<B<bool>, bool> a)\n" 8943 "{\n" 8944 " return a;\n" 8945 "}\n", 8946 Style); 8947 verifyFormat("int\n" 8948 "foo(A<B<8>, 8> a)\n" 8949 "{\n" 8950 " return a;\n" 8951 "}\n", 8952 Style); 8953 8954 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 8955 Style.BraceWrapping.AfterFunction = true; 8956 verifyFormat("int f(i);\n" // No break here. 8957 "int\n" // Break here. 8958 "f(i)\n" 8959 "{\n" 8960 " return i + 1;\n" 8961 "}\n" 8962 "int\n" // Break here. 8963 "f(i)\n" 8964 "{\n" 8965 " return i + 1;\n" 8966 "};", 8967 Style); 8968 verifyFormat("int f(a, b, c);\n" // No break here. 8969 "int\n" // Break here. 8970 "f(a, b, c)\n" // Break here. 8971 "short a, b;\n" 8972 "float c;\n" 8973 "{\n" 8974 " return a + b < c;\n" 8975 "}\n" 8976 "int\n" // Break here. 8977 "f(a, b, c)\n" // Break here. 8978 "short a, b;\n" 8979 "float c;\n" 8980 "{\n" 8981 " return a + b < c;\n" 8982 "};", 8983 Style); 8984 verifyFormat("byte *\n" // Break here. 8985 "f(a)\n" // Break here. 8986 "byte a[];\n" 8987 "{\n" 8988 " return a;\n" 8989 "}", 8990 Style); 8991 verifyFormat("bool f(int a, int) override;\n" 8992 "Bar g(int a, Bar) final;\n" 8993 "Bar h(a, Bar) final;", 8994 Style); 8995 verifyFormat("int\n" 8996 "f(a)", 8997 Style); 8998 verifyFormat("bool\n" 8999 "f(size_t = 0, bool b = false)\n" 9000 "{\n" 9001 " return !b;\n" 9002 "}", 9003 Style); 9004 9005 // The return breaking style doesn't affect: 9006 // * function and object definitions with attribute-like macros 9007 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 9008 " ABSL_GUARDED_BY(mutex) = {};", 9009 getGoogleStyleWithColumns(40)); 9010 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 9011 " ABSL_GUARDED_BY(mutex); // comment", 9012 getGoogleStyleWithColumns(40)); 9013 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 9014 " ABSL_GUARDED_BY(mutex1)\n" 9015 " ABSL_GUARDED_BY(mutex2);", 9016 getGoogleStyleWithColumns(40)); 9017 verifyFormat("Tttttt f(int a, int b)\n" 9018 " ABSL_GUARDED_BY(mutex1)\n" 9019 " ABSL_GUARDED_BY(mutex2);", 9020 getGoogleStyleWithColumns(40)); 9021 // * typedefs 9022 verifyFormat("typedef ATTR(X) char x;", getGoogleStyle()); 9023 9024 Style = getGNUStyle(); 9025 9026 // Test for comments at the end of function declarations. 9027 verifyFormat("void\n" 9028 "foo (int a, /*abc*/ int b) // def\n" 9029 "{\n" 9030 "}\n", 9031 Style); 9032 9033 verifyFormat("void\n" 9034 "foo (int a, /* abc */ int b) /* def */\n" 9035 "{\n" 9036 "}\n", 9037 Style); 9038 9039 // Definitions that should not break after return type 9040 verifyFormat("void foo (int a, int b); // def\n", Style); 9041 verifyFormat("void foo (int a, int b); /* def */\n", Style); 9042 verifyFormat("void foo (int a, int b);\n", Style); 9043 } 9044 9045 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) { 9046 FormatStyle NoBreak = getLLVMStyle(); 9047 NoBreak.AlwaysBreakBeforeMultilineStrings = false; 9048 FormatStyle Break = getLLVMStyle(); 9049 Break.AlwaysBreakBeforeMultilineStrings = true; 9050 verifyFormat("aaaa = \"bbbb\"\n" 9051 " \"cccc\";", 9052 NoBreak); 9053 verifyFormat("aaaa =\n" 9054 " \"bbbb\"\n" 9055 " \"cccc\";", 9056 Break); 9057 verifyFormat("aaaa(\"bbbb\"\n" 9058 " \"cccc\");", 9059 NoBreak); 9060 verifyFormat("aaaa(\n" 9061 " \"bbbb\"\n" 9062 " \"cccc\");", 9063 Break); 9064 verifyFormat("aaaa(qqq, \"bbbb\"\n" 9065 " \"cccc\");", 9066 NoBreak); 9067 verifyFormat("aaaa(qqq,\n" 9068 " \"bbbb\"\n" 9069 " \"cccc\");", 9070 Break); 9071 verifyFormat("aaaa(qqq,\n" 9072 " L\"bbbb\"\n" 9073 " L\"cccc\");", 9074 Break); 9075 verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n" 9076 " \"bbbb\"));", 9077 Break); 9078 verifyFormat("string s = someFunction(\n" 9079 " \"abc\"\n" 9080 " \"abc\");", 9081 Break); 9082 9083 // As we break before unary operators, breaking right after them is bad. 9084 verifyFormat("string foo = abc ? \"x\"\n" 9085 " \"blah blah blah blah blah blah\"\n" 9086 " : \"y\";", 9087 Break); 9088 9089 // Don't break if there is no column gain. 9090 verifyFormat("f(\"aaaa\"\n" 9091 " \"bbbb\");", 9092 Break); 9093 9094 // Treat literals with escaped newlines like multi-line string literals. 9095 EXPECT_EQ("x = \"a\\\n" 9096 "b\\\n" 9097 "c\";", 9098 format("x = \"a\\\n" 9099 "b\\\n" 9100 "c\";", 9101 NoBreak)); 9102 EXPECT_EQ("xxxx =\n" 9103 " \"a\\\n" 9104 "b\\\n" 9105 "c\";", 9106 format("xxxx = \"a\\\n" 9107 "b\\\n" 9108 "c\";", 9109 Break)); 9110 9111 EXPECT_EQ("NSString *const kString =\n" 9112 " @\"aaaa\"\n" 9113 " @\"bbbb\";", 9114 format("NSString *const kString = @\"aaaa\"\n" 9115 "@\"bbbb\";", 9116 Break)); 9117 9118 Break.ColumnLimit = 0; 9119 verifyFormat("const char *hello = \"hello llvm\";", Break); 9120 } 9121 9122 TEST_F(FormatTest, AlignsPipes) { 9123 verifyFormat( 9124 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9125 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9126 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9127 verifyFormat( 9128 "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n" 9129 " << aaaaaaaaaaaaaaaaaaaa;"); 9130 verifyFormat( 9131 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9132 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9133 verifyFormat( 9134 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 9135 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9136 verifyFormat( 9137 "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n" 9138 " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n" 9139 " << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";"); 9140 verifyFormat( 9141 "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9142 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9143 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9144 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9145 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9146 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9147 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 9148 verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n" 9149 " << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);"); 9150 verifyFormat( 9151 "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9152 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9153 verifyFormat( 9154 "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n" 9155 " aaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9156 9157 verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n" 9158 " << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();"); 9159 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9160 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9161 " aaaaaaaaaaaaaaaaaaaaa)\n" 9162 " << aaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9163 verifyFormat("LOG_IF(aaa == //\n" 9164 " bbb)\n" 9165 " << a << b;"); 9166 9167 // But sometimes, breaking before the first "<<" is desirable. 9168 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 9169 " << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);"); 9170 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n" 9171 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9172 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9173 verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n" 9174 " << BEF << IsTemplate << Description << E->getType();"); 9175 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 9176 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9177 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9178 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 9179 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9180 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9181 " << aaa;"); 9182 9183 verifyFormat( 9184 "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9185 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9186 9187 // Incomplete string literal. 9188 EXPECT_EQ("llvm::errs() << \"\n" 9189 " << a;", 9190 format("llvm::errs() << \"\n<<a;")); 9191 9192 verifyFormat("void f() {\n" 9193 " CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n" 9194 " << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n" 9195 "}"); 9196 9197 // Handle 'endl'. 9198 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n" 9199 " << bbbbbbbbbbbbbbbbbbbbbb << endl;"); 9200 verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;"); 9201 9202 // Handle '\n'. 9203 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n" 9204 " << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";"); 9205 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n" 9206 " << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';"); 9207 verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n" 9208 " << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";"); 9209 verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";"); 9210 } 9211 9212 TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) { 9213 verifyFormat("return out << \"somepacket = {\\n\"\n" 9214 " << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n" 9215 " << \" bbbb = \" << pkt.bbbb << \"\\n\"\n" 9216 " << \" cccccc = \" << pkt.cccccc << \"\\n\"\n" 9217 " << \" ddd = [\" << pkt.ddd << \"]\\n\"\n" 9218 " << \"}\";"); 9219 9220 verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n" 9221 " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n" 9222 " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;"); 9223 verifyFormat( 9224 "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n" 9225 " << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n" 9226 " << \"ccccccccccccccccc = \" << ccccccccccccccccc\n" 9227 " << \"ddddddddddddddddd = \" << ddddddddddddddddd\n" 9228 " << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;"); 9229 verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n" 9230 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 9231 verifyFormat( 9232 "void f() {\n" 9233 " llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n" 9234 " << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 9235 "}"); 9236 9237 // Breaking before the first "<<" is generally not desirable. 9238 verifyFormat( 9239 "llvm::errs()\n" 9240 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9241 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9242 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9243 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 9244 getLLVMStyleWithColumns(70)); 9245 verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n" 9246 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9247 " << \"aaaaaaaaaaaaaaaaaaa: \"\n" 9248 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9249 " << \"aaaaaaaaaaaaaaaaaaa: \"\n" 9250 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 9251 getLLVMStyleWithColumns(70)); 9252 9253 verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n" 9254 " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n" 9255 " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;"); 9256 verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n" 9257 " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n" 9258 " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);"); 9259 verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n" 9260 " (aaaa + aaaa);", 9261 getLLVMStyleWithColumns(40)); 9262 verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n" 9263 " (aaaaaaa + aaaaa));", 9264 getLLVMStyleWithColumns(40)); 9265 verifyFormat( 9266 "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n" 9267 " SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n" 9268 " bbbbbbbbbbbbbbbbbbbbbbb);"); 9269 } 9270 9271 TEST_F(FormatTest, UnderstandsEquals) { 9272 verifyFormat( 9273 "aaaaaaaaaaaaaaaaa =\n" 9274 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9275 verifyFormat( 9276 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9277 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 9278 verifyFormat( 9279 "if (a) {\n" 9280 " f();\n" 9281 "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9282 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 9283 "}"); 9284 9285 verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9286 " 100000000 + 10000000) {\n}"); 9287 } 9288 9289 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) { 9290 verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n" 9291 " .looooooooooooooooooooooooooooooooooooooongFunction();"); 9292 9293 verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n" 9294 " ->looooooooooooooooooooooooooooooooooooooongFunction();"); 9295 9296 verifyFormat( 9297 "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n" 9298 " Parameter2);"); 9299 9300 verifyFormat( 9301 "ShortObject->shortFunction(\n" 9302 " LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n" 9303 " LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);"); 9304 9305 verifyFormat("loooooooooooooongFunction(\n" 9306 " LoooooooooooooongObject->looooooooooooooooongFunction());"); 9307 9308 verifyFormat( 9309 "function(LoooooooooooooooooooooooooooooooooooongObject\n" 9310 " ->loooooooooooooooooooooooooooooooooooooooongFunction());"); 9311 9312 verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n" 9313 " .WillRepeatedly(Return(SomeValue));"); 9314 verifyFormat("void f() {\n" 9315 " EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n" 9316 " .Times(2)\n" 9317 " .WillRepeatedly(Return(SomeValue));\n" 9318 "}"); 9319 verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n" 9320 " ccccccccccccccccccccccc);"); 9321 verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9322 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9323 " .aaaaa(aaaaa),\n" 9324 " aaaaaaaaaaaaaaaaaaaaa);"); 9325 verifyFormat("void f() {\n" 9326 " aaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9327 " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n" 9328 "}"); 9329 verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9330 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9331 " .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9332 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9333 " aaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 9334 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9335 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9336 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9337 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n" 9338 "}"); 9339 9340 // Here, it is not necessary to wrap at "." or "->". 9341 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n" 9342 " aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 9343 verifyFormat( 9344 "aaaaaaaaaaa->aaaaaaaaa(\n" 9345 " aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9346 " aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n"); 9347 9348 verifyFormat( 9349 "aaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9350 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());"); 9351 verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n" 9352 " aaaaaaaaa()->aaaaaa()->aaaaa());"); 9353 verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n" 9354 " aaaaaaaaa()->aaaaaa()->aaaaa());"); 9355 9356 verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9357 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9358 " .a();"); 9359 9360 FormatStyle NoBinPacking = getLLVMStyle(); 9361 NoBinPacking.BinPackParameters = false; 9362 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n" 9363 " .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n" 9364 " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n" 9365 " aaaaaaaaaaaaaaaaaaa,\n" 9366 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 9367 NoBinPacking); 9368 9369 // If there is a subsequent call, change to hanging indentation. 9370 verifyFormat( 9371 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9372 " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n" 9373 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9374 verifyFormat( 9375 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9376 " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));"); 9377 verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9378 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9379 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9380 verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9381 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9382 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());"); 9383 } 9384 9385 TEST_F(FormatTest, WrapsTemplateDeclarations) { 9386 verifyFormat("template <typename T>\n" 9387 "virtual void loooooooooooongFunction(int Param1, int Param2);"); 9388 verifyFormat("template <typename T>\n" 9389 "// T should be one of {A, B}.\n" 9390 "virtual void loooooooooooongFunction(int Param1, int Param2);"); 9391 verifyFormat( 9392 "template <typename T>\n" 9393 "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;"); 9394 verifyFormat("template <typename T>\n" 9395 "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n" 9396 " int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);"); 9397 verifyFormat( 9398 "template <typename T>\n" 9399 "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n" 9400 " int Paaaaaaaaaaaaaaaaaaaaram2);"); 9401 verifyFormat( 9402 "template <typename T>\n" 9403 "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n" 9404 " aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n" 9405 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9406 verifyFormat("template <typename T>\n" 9407 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9408 " int aaaaaaaaaaaaaaaaaaaaaa);"); 9409 verifyFormat( 9410 "template <typename T1, typename T2 = char, typename T3 = char,\n" 9411 " typename T4 = char>\n" 9412 "void f();"); 9413 verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n" 9414 " template <typename> class cccccccccccccccccccccc,\n" 9415 " typename ddddddddddddd>\n" 9416 "class C {};"); 9417 verifyFormat( 9418 "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n" 9419 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9420 9421 verifyFormat("void f() {\n" 9422 " a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n" 9423 " a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n" 9424 "}"); 9425 9426 verifyFormat("template <typename T> class C {};"); 9427 verifyFormat("template <typename T> void f();"); 9428 verifyFormat("template <typename T> void f() {}"); 9429 verifyFormat( 9430 "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n" 9431 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9432 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n" 9433 " new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n" 9434 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9435 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n" 9436 " bbbbbbbbbbbbbbbbbbbbbbbb);", 9437 getLLVMStyleWithColumns(72)); 9438 EXPECT_EQ("static_cast<A< //\n" 9439 " B> *>(\n" 9440 "\n" 9441 ");", 9442 format("static_cast<A<//\n" 9443 " B>*>(\n" 9444 "\n" 9445 " );")); 9446 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9447 " const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);"); 9448 9449 FormatStyle AlwaysBreak = getLLVMStyle(); 9450 AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 9451 verifyFormat("template <typename T>\nclass C {};", AlwaysBreak); 9452 verifyFormat("template <typename T>\nvoid f();", AlwaysBreak); 9453 verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak); 9454 verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9455 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n" 9456 " ccccccccccccccccccccccccccccccccccccccccccccccc);"); 9457 verifyFormat("template <template <typename> class Fooooooo,\n" 9458 " template <typename> class Baaaaaaar>\n" 9459 "struct C {};", 9460 AlwaysBreak); 9461 verifyFormat("template <typename T> // T can be A, B or C.\n" 9462 "struct C {};", 9463 AlwaysBreak); 9464 verifyFormat("template <enum E> class A {\n" 9465 "public:\n" 9466 " E *f();\n" 9467 "};"); 9468 9469 FormatStyle NeverBreak = getLLVMStyle(); 9470 NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No; 9471 verifyFormat("template <typename T> class C {};", NeverBreak); 9472 verifyFormat("template <typename T> void f();", NeverBreak); 9473 verifyFormat("template <typename T> void f() {}", NeverBreak); 9474 verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa " 9475 "bbbbbbbbbbbbbbbbbbbb) {}", 9476 NeverBreak); 9477 verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9478 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n" 9479 " ccccccccccccccccccccccccccccccccccccccccccccccc);", 9480 NeverBreak); 9481 verifyFormat("template <template <typename> class Fooooooo,\n" 9482 " template <typename> class Baaaaaaar>\n" 9483 "struct C {};", 9484 NeverBreak); 9485 verifyFormat("template <typename T> // T can be A, B or C.\n" 9486 "struct C {};", 9487 NeverBreak); 9488 verifyFormat("template <enum E> class A {\n" 9489 "public:\n" 9490 " E *f();\n" 9491 "};", 9492 NeverBreak); 9493 NeverBreak.PenaltyBreakTemplateDeclaration = 100; 9494 verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa " 9495 "bbbbbbbbbbbbbbbbbbbb) {}", 9496 NeverBreak); 9497 } 9498 9499 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) { 9500 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp); 9501 Style.ColumnLimit = 60; 9502 EXPECT_EQ("// Baseline - no comments.\n" 9503 "template <\n" 9504 " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n" 9505 "void f() {}", 9506 format("// Baseline - no comments.\n" 9507 "template <\n" 9508 " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n" 9509 "void f() {}", 9510 Style)); 9511 9512 EXPECT_EQ("template <\n" 9513 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9514 "void f() {}", 9515 format("template <\n" 9516 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9517 "void f() {}", 9518 Style)); 9519 9520 EXPECT_EQ( 9521 "template <\n" 9522 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n" 9523 "void f() {}", 9524 format("template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n" 9525 "void f() {}", 9526 Style)); 9527 9528 EXPECT_EQ( 9529 "template <\n" 9530 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9531 " // multiline\n" 9532 "void f() {}", 9533 format("template <\n" 9534 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9535 " // multiline\n" 9536 "void f() {}", 9537 Style)); 9538 9539 EXPECT_EQ( 9540 "template <typename aaaaaaaaaa<\n" 9541 " bbbbbbbbbbbb>::value> // trailing loooong\n" 9542 "void f() {}", 9543 format( 9544 "template <\n" 9545 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n" 9546 "void f() {}", 9547 Style)); 9548 } 9549 9550 TEST_F(FormatTest, WrapsTemplateParameters) { 9551 FormatStyle Style = getLLVMStyle(); 9552 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 9553 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 9554 verifyFormat( 9555 "template <typename... a> struct q {};\n" 9556 "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n" 9557 " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n" 9558 " y;", 9559 Style); 9560 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 9561 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 9562 verifyFormat( 9563 "template <typename... a> struct r {};\n" 9564 "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n" 9565 " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n" 9566 " y;", 9567 Style); 9568 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 9569 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 9570 verifyFormat("template <typename... a> struct s {};\n" 9571 "extern s<\n" 9572 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9573 "aaaaaaaaaaaaaaaaaaaaaa,\n" 9574 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9575 "aaaaaaaaaaaaaaaaaaaaaa>\n" 9576 " y;", 9577 Style); 9578 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 9579 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 9580 verifyFormat("template <typename... a> struct t {};\n" 9581 "extern t<\n" 9582 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9583 "aaaaaaaaaaaaaaaaaaaaaa,\n" 9584 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9585 "aaaaaaaaaaaaaaaaaaaaaa>\n" 9586 " y;", 9587 Style); 9588 } 9589 9590 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) { 9591 verifyFormat( 9592 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9593 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9594 verifyFormat( 9595 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9596 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9597 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());"); 9598 9599 // FIXME: Should we have the extra indent after the second break? 9600 verifyFormat( 9601 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9602 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9603 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9604 9605 verifyFormat( 9606 "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n" 9607 " cccccccccccccccccccccccccccccccccccccccccccccc());"); 9608 9609 // Breaking at nested name specifiers is generally not desirable. 9610 verifyFormat( 9611 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9612 " aaaaaaaaaaaaaaaaaaaaaaa);"); 9613 9614 verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n" 9615 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9616 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9617 " aaaaaaaaaaaaaaaaaaaaa);", 9618 getLLVMStyleWithColumns(74)); 9619 9620 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9621 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9622 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9623 } 9624 9625 TEST_F(FormatTest, UnderstandsTemplateParameters) { 9626 verifyFormat("A<int> a;"); 9627 verifyFormat("A<A<A<int>>> a;"); 9628 verifyFormat("A<A<A<int, 2>, 3>, 4> a;"); 9629 verifyFormat("bool x = a < 1 || 2 > a;"); 9630 verifyFormat("bool x = 5 < f<int>();"); 9631 verifyFormat("bool x = f<int>() > 5;"); 9632 verifyFormat("bool x = 5 < a<int>::x;"); 9633 verifyFormat("bool x = a < 4 ? a > 2 : false;"); 9634 verifyFormat("bool x = f() ? a < 2 : a > 2;"); 9635 9636 verifyGoogleFormat("A<A<int>> a;"); 9637 verifyGoogleFormat("A<A<A<int>>> a;"); 9638 verifyGoogleFormat("A<A<A<A<int>>>> a;"); 9639 verifyGoogleFormat("A<A<int> > a;"); 9640 verifyGoogleFormat("A<A<A<int> > > a;"); 9641 verifyGoogleFormat("A<A<A<A<int> > > > a;"); 9642 verifyGoogleFormat("A<::A<int>> a;"); 9643 verifyGoogleFormat("A<::A> a;"); 9644 verifyGoogleFormat("A< ::A> a;"); 9645 verifyGoogleFormat("A< ::A<int> > a;"); 9646 EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle())); 9647 EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle())); 9648 EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle())); 9649 EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle())); 9650 EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };", 9651 format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle())); 9652 9653 verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp)); 9654 9655 // template closer followed by a token that starts with > or = 9656 verifyFormat("bool b = a<1> > 1;"); 9657 verifyFormat("bool b = a<1> >= 1;"); 9658 verifyFormat("int i = a<1> >> 1;"); 9659 FormatStyle Style = getLLVMStyle(); 9660 Style.SpaceBeforeAssignmentOperators = false; 9661 verifyFormat("bool b= a<1> == 1;", Style); 9662 verifyFormat("a<int> = 1;", Style); 9663 verifyFormat("a<int> >>= 1;", Style); 9664 9665 verifyFormat("test < a | b >> c;"); 9666 verifyFormat("test<test<a | b>> c;"); 9667 verifyFormat("test >> a >> b;"); 9668 verifyFormat("test << a >> b;"); 9669 9670 verifyFormat("f<int>();"); 9671 verifyFormat("template <typename T> void f() {}"); 9672 verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;"); 9673 verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : " 9674 "sizeof(char)>::type>;"); 9675 verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};"); 9676 verifyFormat("f(a.operator()<A>());"); 9677 verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9678 " .template operator()<A>());", 9679 getLLVMStyleWithColumns(35)); 9680 verifyFormat("bool_constant<a && noexcept(f())>"); 9681 verifyFormat("bool_constant<a || noexcept(f())>"); 9682 9683 // Not template parameters. 9684 verifyFormat("return a < b && c > d;"); 9685 verifyFormat("void f() {\n" 9686 " while (a < b && c > d) {\n" 9687 " }\n" 9688 "}"); 9689 verifyFormat("template <typename... Types>\n" 9690 "typename enable_if<0 < sizeof...(Types)>::type Foo() {}"); 9691 9692 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9693 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);", 9694 getLLVMStyleWithColumns(60)); 9695 verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");"); 9696 verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}"); 9697 verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <"); 9698 verifyFormat("some_templated_type<decltype([](int i) { return i; })>"); 9699 } 9700 9701 TEST_F(FormatTest, UnderstandsShiftOperators) { 9702 verifyFormat("if (i < x >> 1)"); 9703 verifyFormat("while (i < x >> 1)"); 9704 verifyFormat("for (unsigned i = 0; i < i; ++i, v = v >> 1)"); 9705 verifyFormat("for (unsigned i = 0; i < x >> 1; ++i, v = v >> 1)"); 9706 verifyFormat( 9707 "for (std::vector<int>::iterator i = 0; i < x >> 1; ++i, v = v >> 1)"); 9708 verifyFormat("Foo.call<Bar<Function>>()"); 9709 verifyFormat("if (Foo.call<Bar<Function>>() == 0)"); 9710 verifyFormat("for (std::vector<std::pair<int>>::iterator i = 0; i < x >> 1; " 9711 "++i, v = v >> 1)"); 9712 verifyFormat("if (w<u<v<x>>, 1>::t)"); 9713 } 9714 9715 TEST_F(FormatTest, BitshiftOperatorWidth) { 9716 EXPECT_EQ("int a = 1 << 2; /* foo\n" 9717 " bar */", 9718 format("int a=1<<2; /* foo\n" 9719 " bar */")); 9720 9721 EXPECT_EQ("int b = 256 >> 1; /* foo\n" 9722 " bar */", 9723 format("int b =256>>1 ; /* foo\n" 9724 " bar */")); 9725 } 9726 9727 TEST_F(FormatTest, UnderstandsBinaryOperators) { 9728 verifyFormat("COMPARE(a, ==, b);"); 9729 verifyFormat("auto s = sizeof...(Ts) - 1;"); 9730 } 9731 9732 TEST_F(FormatTest, UnderstandsPointersToMembers) { 9733 verifyFormat("int A::*x;"); 9734 verifyFormat("int (S::*func)(void *);"); 9735 verifyFormat("void f() { int (S::*func)(void *); }"); 9736 verifyFormat("typedef bool *(Class::*Member)() const;"); 9737 verifyFormat("void f() {\n" 9738 " (a->*f)();\n" 9739 " a->*x;\n" 9740 " (a.*f)();\n" 9741 " ((*a).*f)();\n" 9742 " a.*x;\n" 9743 "}"); 9744 verifyFormat("void f() {\n" 9745 " (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n" 9746 " aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n" 9747 "}"); 9748 verifyFormat( 9749 "(aaaaaaaaaa->*bbbbbbb)(\n" 9750 " aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 9751 FormatStyle Style = getLLVMStyle(); 9752 Style.PointerAlignment = FormatStyle::PAS_Left; 9753 verifyFormat("typedef bool* (Class::*Member)() const;", Style); 9754 } 9755 9756 TEST_F(FormatTest, UnderstandsUnaryOperators) { 9757 verifyFormat("int a = -2;"); 9758 verifyFormat("f(-1, -2, -3);"); 9759 verifyFormat("a[-1] = 5;"); 9760 verifyFormat("int a = 5 + -2;"); 9761 verifyFormat("if (i == -1) {\n}"); 9762 verifyFormat("if (i != -1) {\n}"); 9763 verifyFormat("if (i > -1) {\n}"); 9764 verifyFormat("if (i < -1) {\n}"); 9765 verifyFormat("++(a->f());"); 9766 verifyFormat("--(a->f());"); 9767 verifyFormat("(a->f())++;"); 9768 verifyFormat("a[42]++;"); 9769 verifyFormat("if (!(a->f())) {\n}"); 9770 verifyFormat("if (!+i) {\n}"); 9771 verifyFormat("~&a;"); 9772 verifyFormat("for (x = 0; -10 < x; --x) {\n}"); 9773 verifyFormat("sizeof -x"); 9774 verifyFormat("sizeof +x"); 9775 verifyFormat("sizeof *x"); 9776 verifyFormat("sizeof &x"); 9777 verifyFormat("delete +x;"); 9778 verifyFormat("co_await +x;"); 9779 verifyFormat("case *x:"); 9780 verifyFormat("case &x:"); 9781 9782 verifyFormat("a-- > b;"); 9783 verifyFormat("b ? -a : c;"); 9784 verifyFormat("n * sizeof char16;"); 9785 verifyFormat("n * alignof char16;", getGoogleStyle()); 9786 verifyFormat("sizeof(char);"); 9787 verifyFormat("alignof(char);", getGoogleStyle()); 9788 9789 verifyFormat("return -1;"); 9790 verifyFormat("throw -1;"); 9791 verifyFormat("switch (a) {\n" 9792 "case -1:\n" 9793 " break;\n" 9794 "}"); 9795 verifyFormat("#define X -1"); 9796 verifyFormat("#define X -kConstant"); 9797 9798 verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};"); 9799 verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};"); 9800 9801 verifyFormat("int a = /* confusing comment */ -1;"); 9802 // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case. 9803 verifyFormat("int a = i /* confusing comment */++;"); 9804 9805 verifyFormat("co_yield -1;"); 9806 verifyFormat("co_return -1;"); 9807 9808 // Check that * is not treated as a binary operator when we set 9809 // PointerAlignment as PAS_Left after a keyword and not a declaration. 9810 FormatStyle PASLeftStyle = getLLVMStyle(); 9811 PASLeftStyle.PointerAlignment = FormatStyle::PAS_Left; 9812 verifyFormat("co_return *a;", PASLeftStyle); 9813 verifyFormat("co_await *a;", PASLeftStyle); 9814 verifyFormat("co_yield *a", PASLeftStyle); 9815 verifyFormat("return *a;", PASLeftStyle); 9816 } 9817 9818 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) { 9819 verifyFormat("if (!aaaaaaaaaa( // break\n" 9820 " aaaaa)) {\n" 9821 "}"); 9822 verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n" 9823 " aaaaa));"); 9824 verifyFormat("*aaa = aaaaaaa( // break\n" 9825 " bbbbbb);"); 9826 } 9827 9828 TEST_F(FormatTest, UnderstandsOverloadedOperators) { 9829 verifyFormat("bool operator<();"); 9830 verifyFormat("bool operator>();"); 9831 verifyFormat("bool operator=();"); 9832 verifyFormat("bool operator==();"); 9833 verifyFormat("bool operator!=();"); 9834 verifyFormat("int operator+();"); 9835 verifyFormat("int operator++();"); 9836 verifyFormat("int operator++(int) volatile noexcept;"); 9837 verifyFormat("bool operator,();"); 9838 verifyFormat("bool operator();"); 9839 verifyFormat("bool operator()();"); 9840 verifyFormat("bool operator[]();"); 9841 verifyFormat("operator bool();"); 9842 verifyFormat("operator int();"); 9843 verifyFormat("operator void *();"); 9844 verifyFormat("operator SomeType<int>();"); 9845 verifyFormat("operator SomeType<int, int>();"); 9846 verifyFormat("operator SomeType<SomeType<int>>();"); 9847 verifyFormat("operator< <>();"); 9848 verifyFormat("operator<< <>();"); 9849 verifyFormat("< <>"); 9850 9851 verifyFormat("void *operator new(std::size_t size);"); 9852 verifyFormat("void *operator new[](std::size_t size);"); 9853 verifyFormat("void operator delete(void *ptr);"); 9854 verifyFormat("void operator delete[](void *ptr);"); 9855 verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n" 9856 "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);"); 9857 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n" 9858 " aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;"); 9859 9860 verifyFormat( 9861 "ostream &operator<<(ostream &OutputStream,\n" 9862 " SomeReallyLongType WithSomeReallyLongValue);"); 9863 verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n" 9864 " const aaaaaaaaaaaaaaaaaaaaa &right) {\n" 9865 " return left.group < right.group;\n" 9866 "}"); 9867 verifyFormat("SomeType &operator=(const SomeType &S);"); 9868 verifyFormat("f.template operator()<int>();"); 9869 9870 verifyGoogleFormat("operator void*();"); 9871 verifyGoogleFormat("operator SomeType<SomeType<int>>();"); 9872 verifyGoogleFormat("operator ::A();"); 9873 9874 verifyFormat("using A::operator+;"); 9875 verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n" 9876 "int i;"); 9877 9878 // Calling an operator as a member function. 9879 verifyFormat("void f() { a.operator*(); }"); 9880 verifyFormat("void f() { a.operator*(b & b); }"); 9881 verifyFormat("void f() { a->operator&(a * b); }"); 9882 verifyFormat("void f() { NS::a.operator+(*b * *b); }"); 9883 // TODO: Calling an operator as a non-member function is hard to distinguish. 9884 // https://llvm.org/PR50629 9885 // verifyFormat("void f() { operator*(a & a); }"); 9886 // verifyFormat("void f() { operator&(a, b * b); }"); 9887 9888 verifyFormat("::operator delete(foo);"); 9889 verifyFormat("::operator new(n * sizeof(foo));"); 9890 verifyFormat("foo() { ::operator delete(foo); }"); 9891 verifyFormat("foo() { ::operator new(n * sizeof(foo)); }"); 9892 } 9893 9894 TEST_F(FormatTest, UnderstandsFunctionRefQualification) { 9895 verifyFormat("void A::b() && {}"); 9896 verifyFormat("void A::b() &&noexcept {}"); 9897 verifyFormat("Deleted &operator=(const Deleted &) & = default;"); 9898 verifyFormat("Deleted &operator=(const Deleted &) && = delete;"); 9899 verifyFormat("Deleted &operator=(const Deleted &) &noexcept = default;"); 9900 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;"); 9901 verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;"); 9902 verifyFormat("Deleted &operator=(const Deleted &) &;"); 9903 verifyFormat("Deleted &operator=(const Deleted &) &&;"); 9904 verifyFormat("SomeType MemberFunction(const Deleted &) &;"); 9905 verifyFormat("SomeType MemberFunction(const Deleted &) &&;"); 9906 verifyFormat("SomeType MemberFunction(const Deleted &) && {}"); 9907 verifyFormat("SomeType MemberFunction(const Deleted &) && final {}"); 9908 verifyFormat("SomeType MemberFunction(const Deleted &) && override {}"); 9909 verifyFormat("SomeType MemberFunction(const Deleted &) &&noexcept {}"); 9910 verifyFormat("void Fn(T const &) const &;"); 9911 verifyFormat("void Fn(T const volatile &&) const volatile &&;"); 9912 verifyFormat("void Fn(T const volatile &&) const volatile &&noexcept;"); 9913 verifyFormat("template <typename T>\n" 9914 "void F(T) && = delete;", 9915 getGoogleStyle()); 9916 verifyFormat("template <typename T> void operator=(T) &;"); 9917 verifyFormat("template <typename T> void operator=(T) const &;"); 9918 verifyFormat("template <typename T> void operator=(T) &noexcept;"); 9919 verifyFormat("template <typename T> void operator=(T) & = default;"); 9920 verifyFormat("template <typename T> void operator=(T) &&;"); 9921 verifyFormat("template <typename T> void operator=(T) && = delete;"); 9922 verifyFormat("template <typename T> void operator=(T) & {}"); 9923 verifyFormat("template <typename T> void operator=(T) && {}"); 9924 9925 FormatStyle AlignLeft = getLLVMStyle(); 9926 AlignLeft.PointerAlignment = FormatStyle::PAS_Left; 9927 verifyFormat("void A::b() && {}", AlignLeft); 9928 verifyFormat("void A::b() && noexcept {}", AlignLeft); 9929 verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft); 9930 verifyFormat("Deleted& operator=(const Deleted&) & noexcept = default;", 9931 AlignLeft); 9932 verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;", 9933 AlignLeft); 9934 verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft); 9935 verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft); 9936 verifyFormat("auto Function(T t) & -> void {}", AlignLeft); 9937 verifyFormat("auto Function(T... t) & -> void {}", AlignLeft); 9938 verifyFormat("auto Function(T) & -> void {}", AlignLeft); 9939 verifyFormat("auto Function(T) & -> void;", AlignLeft); 9940 verifyFormat("void Fn(T const&) const&;", AlignLeft); 9941 verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft); 9942 verifyFormat("void Fn(T const volatile&&) const volatile&& noexcept;", 9943 AlignLeft); 9944 verifyFormat("template <typename T> void operator=(T) &;", AlignLeft); 9945 verifyFormat("template <typename T> void operator=(T) const&;", AlignLeft); 9946 verifyFormat("template <typename T> void operator=(T) & noexcept;", 9947 AlignLeft); 9948 verifyFormat("template <typename T> void operator=(T) & = default;", 9949 AlignLeft); 9950 verifyFormat("template <typename T> void operator=(T) &&;", AlignLeft); 9951 verifyFormat("template <typename T> void operator=(T) && = delete;", 9952 AlignLeft); 9953 verifyFormat("template <typename T> void operator=(T) & {}", AlignLeft); 9954 verifyFormat("template <typename T> void operator=(T) && {}", AlignLeft); 9955 9956 FormatStyle AlignMiddle = getLLVMStyle(); 9957 AlignMiddle.PointerAlignment = FormatStyle::PAS_Middle; 9958 verifyFormat("void A::b() && {}", AlignMiddle); 9959 verifyFormat("void A::b() && noexcept {}", AlignMiddle); 9960 verifyFormat("Deleted & operator=(const Deleted &) & = default;", 9961 AlignMiddle); 9962 verifyFormat("Deleted & operator=(const Deleted &) & noexcept = default;", 9963 AlignMiddle); 9964 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", 9965 AlignMiddle); 9966 verifyFormat("Deleted & operator=(const Deleted &) &;", AlignMiddle); 9967 verifyFormat("SomeType MemberFunction(const Deleted &) &;", AlignMiddle); 9968 verifyFormat("auto Function(T t) & -> void {}", AlignMiddle); 9969 verifyFormat("auto Function(T... t) & -> void {}", AlignMiddle); 9970 verifyFormat("auto Function(T) & -> void {}", AlignMiddle); 9971 verifyFormat("auto Function(T) & -> void;", AlignMiddle); 9972 verifyFormat("void Fn(T const &) const &;", AlignMiddle); 9973 verifyFormat("void Fn(T const volatile &&) const volatile &&;", AlignMiddle); 9974 verifyFormat("void Fn(T const volatile &&) const volatile && noexcept;", 9975 AlignMiddle); 9976 verifyFormat("template <typename T> void operator=(T) &;", AlignMiddle); 9977 verifyFormat("template <typename T> void operator=(T) const &;", AlignMiddle); 9978 verifyFormat("template <typename T> void operator=(T) & noexcept;", 9979 AlignMiddle); 9980 verifyFormat("template <typename T> void operator=(T) & = default;", 9981 AlignMiddle); 9982 verifyFormat("template <typename T> void operator=(T) &&;", AlignMiddle); 9983 verifyFormat("template <typename T> void operator=(T) && = delete;", 9984 AlignMiddle); 9985 verifyFormat("template <typename T> void operator=(T) & {}", AlignMiddle); 9986 verifyFormat("template <typename T> void operator=(T) && {}", AlignMiddle); 9987 9988 FormatStyle Spaces = getLLVMStyle(); 9989 Spaces.SpacesInCStyleCastParentheses = true; 9990 verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces); 9991 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces); 9992 verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces); 9993 verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces); 9994 9995 Spaces.SpacesInCStyleCastParentheses = false; 9996 Spaces.SpacesInParentheses = true; 9997 verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces); 9998 verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;", 9999 Spaces); 10000 verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces); 10001 verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces); 10002 10003 FormatStyle BreakTemplate = getLLVMStyle(); 10004 BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 10005 10006 verifyFormat("struct f {\n" 10007 " template <class T>\n" 10008 " int &foo(const std::string &str) &noexcept {}\n" 10009 "};", 10010 BreakTemplate); 10011 10012 verifyFormat("struct f {\n" 10013 " template <class T>\n" 10014 " int &foo(const std::string &str) &&noexcept {}\n" 10015 "};", 10016 BreakTemplate); 10017 10018 verifyFormat("struct f {\n" 10019 " template <class T>\n" 10020 " int &foo(const std::string &str) const &noexcept {}\n" 10021 "};", 10022 BreakTemplate); 10023 10024 verifyFormat("struct f {\n" 10025 " template <class T>\n" 10026 " int &foo(const std::string &str) const &noexcept {}\n" 10027 "};", 10028 BreakTemplate); 10029 10030 verifyFormat("struct f {\n" 10031 " template <class T>\n" 10032 " auto foo(const std::string &str) &&noexcept -> int & {}\n" 10033 "};", 10034 BreakTemplate); 10035 10036 FormatStyle AlignLeftBreakTemplate = getLLVMStyle(); 10037 AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations = 10038 FormatStyle::BTDS_Yes; 10039 AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left; 10040 10041 verifyFormat("struct f {\n" 10042 " template <class T>\n" 10043 " int& foo(const std::string& str) & noexcept {}\n" 10044 "};", 10045 AlignLeftBreakTemplate); 10046 10047 verifyFormat("struct f {\n" 10048 " template <class T>\n" 10049 " int& foo(const std::string& str) && noexcept {}\n" 10050 "};", 10051 AlignLeftBreakTemplate); 10052 10053 verifyFormat("struct f {\n" 10054 " template <class T>\n" 10055 " int& foo(const std::string& str) const& noexcept {}\n" 10056 "};", 10057 AlignLeftBreakTemplate); 10058 10059 verifyFormat("struct f {\n" 10060 " template <class T>\n" 10061 " int& foo(const std::string& str) const&& noexcept {}\n" 10062 "};", 10063 AlignLeftBreakTemplate); 10064 10065 verifyFormat("struct f {\n" 10066 " template <class T>\n" 10067 " auto foo(const std::string& str) && noexcept -> int& {}\n" 10068 "};", 10069 AlignLeftBreakTemplate); 10070 10071 // The `&` in `Type&` should not be confused with a trailing `&` of 10072 // DEPRECATED(reason) member function. 10073 verifyFormat("struct f {\n" 10074 " template <class T>\n" 10075 " DEPRECATED(reason)\n" 10076 " Type &foo(arguments) {}\n" 10077 "};", 10078 BreakTemplate); 10079 10080 verifyFormat("struct f {\n" 10081 " template <class T>\n" 10082 " DEPRECATED(reason)\n" 10083 " Type& foo(arguments) {}\n" 10084 "};", 10085 AlignLeftBreakTemplate); 10086 10087 verifyFormat("void (*foopt)(int) = &func;"); 10088 10089 FormatStyle DerivePointerAlignment = getLLVMStyle(); 10090 DerivePointerAlignment.DerivePointerAlignment = true; 10091 // There's always a space between the function and its trailing qualifiers. 10092 // This isn't evidence for PAS_Right (or for PAS_Left). 10093 std::string Prefix = "void a() &;\n" 10094 "void b() &;\n"; 10095 verifyFormat(Prefix + "int* x;", DerivePointerAlignment); 10096 verifyFormat(Prefix + "int *x;", DerivePointerAlignment); 10097 // Same if the function is an overloaded operator, and with &&. 10098 Prefix = "void operator()() &&;\n" 10099 "void operator()() &&;\n"; 10100 verifyFormat(Prefix + "int* x;", DerivePointerAlignment); 10101 verifyFormat(Prefix + "int *x;", DerivePointerAlignment); 10102 // However a space between cv-qualifiers and ref-qualifiers *is* evidence. 10103 Prefix = "void a() const &;\n" 10104 "void b() const &;\n"; 10105 EXPECT_EQ(Prefix + "int *x;", 10106 format(Prefix + "int* x;", DerivePointerAlignment)); 10107 } 10108 10109 TEST_F(FormatTest, UnderstandsNewAndDelete) { 10110 verifyFormat("void f() {\n" 10111 " A *a = new A;\n" 10112 " A *a = new (placement) A;\n" 10113 " delete a;\n" 10114 " delete (A *)a;\n" 10115 "}"); 10116 verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n" 10117 " typename aaaaaaaaaaaaaaaaaaaaaaaa();"); 10118 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 10119 " new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n" 10120 " typename aaaaaaaaaaaaaaaaaaaaaaaa();"); 10121 verifyFormat("delete[] h->p;"); 10122 verifyFormat("delete[] (void *)p;"); 10123 10124 verifyFormat("void operator delete(void *foo) ATTRIB;"); 10125 verifyFormat("void operator new(void *foo) ATTRIB;"); 10126 verifyFormat("void operator delete[](void *foo) ATTRIB;"); 10127 verifyFormat("void operator delete(void *ptr) noexcept;"); 10128 10129 EXPECT_EQ("void new(link p);\n" 10130 "void delete(link p);\n", 10131 format("void new (link p);\n" 10132 "void delete (link p);\n")); 10133 } 10134 10135 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) { 10136 verifyFormat("int *f(int *a) {}"); 10137 verifyFormat("int main(int argc, char **argv) {}"); 10138 verifyFormat("Test::Test(int b) : a(b * b) {}"); 10139 verifyIndependentOfContext("f(a, *a);"); 10140 verifyFormat("void g() { f(*a); }"); 10141 verifyIndependentOfContext("int a = b * 10;"); 10142 verifyIndependentOfContext("int a = 10 * b;"); 10143 verifyIndependentOfContext("int a = b * c;"); 10144 verifyIndependentOfContext("int a += b * c;"); 10145 verifyIndependentOfContext("int a -= b * c;"); 10146 verifyIndependentOfContext("int a *= b * c;"); 10147 verifyIndependentOfContext("int a /= b * c;"); 10148 verifyIndependentOfContext("int a = *b;"); 10149 verifyIndependentOfContext("int a = *b * c;"); 10150 verifyIndependentOfContext("int a = b * *c;"); 10151 verifyIndependentOfContext("int a = b * (10);"); 10152 verifyIndependentOfContext("S << b * (10);"); 10153 verifyIndependentOfContext("return 10 * b;"); 10154 verifyIndependentOfContext("return *b * *c;"); 10155 verifyIndependentOfContext("return a & ~b;"); 10156 verifyIndependentOfContext("f(b ? *c : *d);"); 10157 verifyIndependentOfContext("int a = b ? *c : *d;"); 10158 verifyIndependentOfContext("*b = a;"); 10159 verifyIndependentOfContext("a * ~b;"); 10160 verifyIndependentOfContext("a * !b;"); 10161 verifyIndependentOfContext("a * +b;"); 10162 verifyIndependentOfContext("a * -b;"); 10163 verifyIndependentOfContext("a * ++b;"); 10164 verifyIndependentOfContext("a * --b;"); 10165 verifyIndependentOfContext("a[4] * b;"); 10166 verifyIndependentOfContext("a[a * a] = 1;"); 10167 verifyIndependentOfContext("f() * b;"); 10168 verifyIndependentOfContext("a * [self dostuff];"); 10169 verifyIndependentOfContext("int x = a * (a + b);"); 10170 verifyIndependentOfContext("(a *)(a + b);"); 10171 verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;"); 10172 verifyIndependentOfContext("int *pa = (int *)&a;"); 10173 verifyIndependentOfContext("return sizeof(int **);"); 10174 verifyIndependentOfContext("return sizeof(int ******);"); 10175 verifyIndependentOfContext("return (int **&)a;"); 10176 verifyIndependentOfContext("f((*PointerToArray)[10]);"); 10177 verifyFormat("void f(Type (*parameter)[10]) {}"); 10178 verifyFormat("void f(Type (¶meter)[10]) {}"); 10179 verifyGoogleFormat("return sizeof(int**);"); 10180 verifyIndependentOfContext("Type **A = static_cast<Type **>(P);"); 10181 verifyGoogleFormat("Type** A = static_cast<Type**>(P);"); 10182 verifyFormat("auto a = [](int **&, int ***) {};"); 10183 verifyFormat("auto PointerBinding = [](const char *S) {};"); 10184 verifyFormat("typedef typeof(int(int, int)) *MyFunc;"); 10185 verifyFormat("[](const decltype(*a) &value) {}"); 10186 verifyFormat("[](const typeof(*a) &value) {}"); 10187 verifyFormat("[](const _Atomic(a *) &value) {}"); 10188 verifyFormat("[](const __underlying_type(a) &value) {}"); 10189 verifyFormat("decltype(a * b) F();"); 10190 verifyFormat("typeof(a * b) F();"); 10191 verifyFormat("#define MACRO() [](A *a) { return 1; }"); 10192 verifyFormat("Constructor() : member([](A *a, B *b) {}) {}"); 10193 verifyIndependentOfContext("typedef void (*f)(int *a);"); 10194 verifyIndependentOfContext("int i{a * b};"); 10195 verifyIndependentOfContext("aaa && aaa->f();"); 10196 verifyIndependentOfContext("int x = ~*p;"); 10197 verifyFormat("Constructor() : a(a), area(width * height) {}"); 10198 verifyFormat("Constructor() : a(a), area(a, width * height) {}"); 10199 verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}"); 10200 verifyFormat("void f() { f(a, c * d); }"); 10201 verifyFormat("void f() { f(new a(), c * d); }"); 10202 verifyFormat("void f(const MyOverride &override);"); 10203 verifyFormat("void f(const MyFinal &final);"); 10204 verifyIndependentOfContext("bool a = f() && override.f();"); 10205 verifyIndependentOfContext("bool a = f() && final.f();"); 10206 10207 verifyIndependentOfContext("InvalidRegions[*R] = 0;"); 10208 10209 verifyIndependentOfContext("A<int *> a;"); 10210 verifyIndependentOfContext("A<int **> a;"); 10211 verifyIndependentOfContext("A<int *, int *> a;"); 10212 verifyIndependentOfContext("A<int *[]> a;"); 10213 verifyIndependentOfContext( 10214 "const char *const p = reinterpret_cast<const char *const>(q);"); 10215 verifyIndependentOfContext("A<int **, int **> a;"); 10216 verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);"); 10217 verifyFormat("for (char **a = b; *a; ++a) {\n}"); 10218 verifyFormat("for (; a && b;) {\n}"); 10219 verifyFormat("bool foo = true && [] { return false; }();"); 10220 10221 verifyFormat( 10222 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 10223 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 10224 10225 verifyGoogleFormat("int const* a = &b;"); 10226 verifyGoogleFormat("**outparam = 1;"); 10227 verifyGoogleFormat("*outparam = a * b;"); 10228 verifyGoogleFormat("int main(int argc, char** argv) {}"); 10229 verifyGoogleFormat("A<int*> a;"); 10230 verifyGoogleFormat("A<int**> a;"); 10231 verifyGoogleFormat("A<int*, int*> a;"); 10232 verifyGoogleFormat("A<int**, int**> a;"); 10233 verifyGoogleFormat("f(b ? *c : *d);"); 10234 verifyGoogleFormat("int a = b ? *c : *d;"); 10235 verifyGoogleFormat("Type* t = **x;"); 10236 verifyGoogleFormat("Type* t = *++*x;"); 10237 verifyGoogleFormat("*++*x;"); 10238 verifyGoogleFormat("Type* t = const_cast<T*>(&*x);"); 10239 verifyGoogleFormat("Type* t = x++ * y;"); 10240 verifyGoogleFormat( 10241 "const char* const p = reinterpret_cast<const char* const>(q);"); 10242 verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);"); 10243 verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);"); 10244 verifyGoogleFormat("template <typename T>\n" 10245 "void f(int i = 0, SomeType** temps = NULL);"); 10246 10247 FormatStyle Left = getLLVMStyle(); 10248 Left.PointerAlignment = FormatStyle::PAS_Left; 10249 verifyFormat("x = *a(x) = *a(y);", Left); 10250 verifyFormat("for (;; *a = b) {\n}", Left); 10251 verifyFormat("return *this += 1;", Left); 10252 verifyFormat("throw *x;", Left); 10253 verifyFormat("delete *x;", Left); 10254 verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left); 10255 verifyFormat("[](const decltype(*a)* ptr) {}", Left); 10256 verifyFormat("[](const typeof(*a)* ptr) {}", Left); 10257 verifyFormat("[](const _Atomic(a*)* ptr) {}", Left); 10258 verifyFormat("[](const __underlying_type(a)* ptr) {}", Left); 10259 verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left); 10260 verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left); 10261 verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left); 10262 verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left); 10263 10264 verifyIndependentOfContext("a = *(x + y);"); 10265 verifyIndependentOfContext("a = &(x + y);"); 10266 verifyIndependentOfContext("*(x + y).call();"); 10267 verifyIndependentOfContext("&(x + y)->call();"); 10268 verifyFormat("void f() { &(*I).first; }"); 10269 10270 verifyIndependentOfContext("f(b * /* confusing comment */ ++c);"); 10271 verifyFormat("f(* /* confusing comment */ foo);"); 10272 verifyFormat("void (* /*deleter*/)(const Slice &key, void *value)"); 10273 verifyFormat("void foo(int * // this is the first paramters\n" 10274 " ,\n" 10275 " int second);"); 10276 verifyFormat("double term = a * // first\n" 10277 " b;"); 10278 verifyFormat( 10279 "int *MyValues = {\n" 10280 " *A, // Operator detection might be confused by the '{'\n" 10281 " *BB // Operator detection might be confused by previous comment\n" 10282 "};"); 10283 10284 verifyIndependentOfContext("if (int *a = &b)"); 10285 verifyIndependentOfContext("if (int &a = *b)"); 10286 verifyIndependentOfContext("if (a & b[i])"); 10287 verifyIndependentOfContext("if constexpr (a & b[i])"); 10288 verifyIndependentOfContext("if CONSTEXPR (a & b[i])"); 10289 verifyIndependentOfContext("if (a * (b * c))"); 10290 verifyIndependentOfContext("if constexpr (a * (b * c))"); 10291 verifyIndependentOfContext("if CONSTEXPR (a * (b * c))"); 10292 verifyIndependentOfContext("if (a::b::c::d & b[i])"); 10293 verifyIndependentOfContext("if (*b[i])"); 10294 verifyIndependentOfContext("if (int *a = (&b))"); 10295 verifyIndependentOfContext("while (int *a = &b)"); 10296 verifyIndependentOfContext("while (a * (b * c))"); 10297 verifyIndependentOfContext("size = sizeof *a;"); 10298 verifyIndependentOfContext("if (a && (b = c))"); 10299 verifyFormat("void f() {\n" 10300 " for (const int &v : Values) {\n" 10301 " }\n" 10302 "}"); 10303 verifyFormat("for (int i = a * a; i < 10; ++i) {\n}"); 10304 verifyFormat("for (int i = 0; i < a * a; ++i) {\n}"); 10305 verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}"); 10306 10307 verifyFormat("#define A (!a * b)"); 10308 verifyFormat("#define MACRO \\\n" 10309 " int *i = a * b; \\\n" 10310 " void f(a *b);", 10311 getLLVMStyleWithColumns(19)); 10312 10313 verifyIndependentOfContext("A = new SomeType *[Length];"); 10314 verifyIndependentOfContext("A = new SomeType *[Length]();"); 10315 verifyIndependentOfContext("T **t = new T *;"); 10316 verifyIndependentOfContext("T **t = new T *();"); 10317 verifyGoogleFormat("A = new SomeType*[Length]();"); 10318 verifyGoogleFormat("A = new SomeType*[Length];"); 10319 verifyGoogleFormat("T** t = new T*;"); 10320 verifyGoogleFormat("T** t = new T*();"); 10321 10322 verifyFormat("STATIC_ASSERT((a & b) == 0);"); 10323 verifyFormat("STATIC_ASSERT(0 == (a & b));"); 10324 verifyFormat("template <bool a, bool b> " 10325 "typename t::if<x && y>::type f() {}"); 10326 verifyFormat("template <int *y> f() {}"); 10327 verifyFormat("vector<int *> v;"); 10328 verifyFormat("vector<int *const> v;"); 10329 verifyFormat("vector<int *const **const *> v;"); 10330 verifyFormat("vector<int *volatile> v;"); 10331 verifyFormat("vector<a *_Nonnull> v;"); 10332 verifyFormat("vector<a *_Nullable> v;"); 10333 verifyFormat("vector<a *_Null_unspecified> v;"); 10334 verifyFormat("vector<a *__ptr32> v;"); 10335 verifyFormat("vector<a *__ptr64> v;"); 10336 verifyFormat("vector<a *__capability> v;"); 10337 FormatStyle TypeMacros = getLLVMStyle(); 10338 TypeMacros.TypenameMacros = {"LIST"}; 10339 verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros); 10340 verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros); 10341 verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros); 10342 verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros); 10343 verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication 10344 10345 FormatStyle CustomQualifier = getLLVMStyle(); 10346 // Add identifiers that should not be parsed as a qualifier by default. 10347 CustomQualifier.AttributeMacros.push_back("__my_qualifier"); 10348 CustomQualifier.AttributeMacros.push_back("_My_qualifier"); 10349 CustomQualifier.AttributeMacros.push_back("my_other_qualifier"); 10350 verifyFormat("vector<a * __my_qualifier> parse_as_multiply;"); 10351 verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier); 10352 verifyFormat("vector<a * _My_qualifier> parse_as_multiply;"); 10353 verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier); 10354 verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;"); 10355 verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier); 10356 verifyFormat("vector<a * _NotAQualifier> v;"); 10357 verifyFormat("vector<a * __not_a_qualifier> v;"); 10358 verifyFormat("vector<a * b> v;"); 10359 verifyFormat("foo<b && false>();"); 10360 verifyFormat("foo<b & 1>();"); 10361 verifyFormat("foo<b & (1)>();"); 10362 verifyFormat("foo<b & (~0)>();"); 10363 verifyFormat("foo<b & (true)>();"); 10364 verifyFormat("foo<b & ((1))>();"); 10365 verifyFormat("foo<b & (/*comment*/ 1)>();"); 10366 verifyFormat("decltype(*::std::declval<const T &>()) void F();"); 10367 verifyFormat("typeof(*::std::declval<const T &>()) void F();"); 10368 verifyFormat("_Atomic(*::std::declval<const T &>()) void F();"); 10369 verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();"); 10370 verifyFormat( 10371 "template <class T, class = typename std::enable_if<\n" 10372 " std::is_integral<T>::value &&\n" 10373 " (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n" 10374 "void F();", 10375 getLLVMStyleWithColumns(70)); 10376 verifyFormat("template <class T,\n" 10377 " class = typename std::enable_if<\n" 10378 " std::is_integral<T>::value &&\n" 10379 " (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n" 10380 " class U>\n" 10381 "void F();", 10382 getLLVMStyleWithColumns(70)); 10383 verifyFormat( 10384 "template <class T,\n" 10385 " class = typename ::std::enable_if<\n" 10386 " ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n" 10387 "void F();", 10388 getGoogleStyleWithColumns(68)); 10389 10390 verifyIndependentOfContext("MACRO(int *i);"); 10391 verifyIndependentOfContext("MACRO(auto *a);"); 10392 verifyIndependentOfContext("MACRO(const A *a);"); 10393 verifyIndependentOfContext("MACRO(_Atomic(A) *a);"); 10394 verifyIndependentOfContext("MACRO(decltype(A) *a);"); 10395 verifyIndependentOfContext("MACRO(typeof(A) *a);"); 10396 verifyIndependentOfContext("MACRO(__underlying_type(A) *a);"); 10397 verifyIndependentOfContext("MACRO(A *const a);"); 10398 verifyIndependentOfContext("MACRO(A *restrict a);"); 10399 verifyIndependentOfContext("MACRO(A *__restrict__ a);"); 10400 verifyIndependentOfContext("MACRO(A *__restrict a);"); 10401 verifyIndependentOfContext("MACRO(A *volatile a);"); 10402 verifyIndependentOfContext("MACRO(A *__volatile a);"); 10403 verifyIndependentOfContext("MACRO(A *__volatile__ a);"); 10404 verifyIndependentOfContext("MACRO(A *_Nonnull a);"); 10405 verifyIndependentOfContext("MACRO(A *_Nullable a);"); 10406 verifyIndependentOfContext("MACRO(A *_Null_unspecified a);"); 10407 verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);"); 10408 verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);"); 10409 verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);"); 10410 verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);"); 10411 verifyIndependentOfContext("MACRO(A *__ptr32 a);"); 10412 verifyIndependentOfContext("MACRO(A *__ptr64 a);"); 10413 verifyIndependentOfContext("MACRO(A *__capability);"); 10414 verifyIndependentOfContext("MACRO(A &__capability);"); 10415 verifyFormat("MACRO(A *__my_qualifier);"); // type declaration 10416 verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication 10417 // If we add __my_qualifier to AttributeMacros it should always be parsed as 10418 // a type declaration: 10419 verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier); 10420 verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier); 10421 // Also check that TypenameMacros prevents parsing it as multiplication: 10422 verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication 10423 verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type 10424 10425 verifyIndependentOfContext("MACRO('0' <= c && c <= '9');"); 10426 verifyFormat("void f() { f(float{1}, a * a); }"); 10427 verifyFormat("void f() { f(float(1), a * a); }"); 10428 10429 verifyFormat("f((void (*)(int))g);"); 10430 verifyFormat("f((void (&)(int))g);"); 10431 verifyFormat("f((void (^)(int))g);"); 10432 10433 // FIXME: Is there a way to make this work? 10434 // verifyIndependentOfContext("MACRO(A *a);"); 10435 verifyFormat("MACRO(A &B);"); 10436 verifyFormat("MACRO(A *B);"); 10437 verifyFormat("void f() { MACRO(A * B); }"); 10438 verifyFormat("void f() { MACRO(A & B); }"); 10439 10440 // This lambda was mis-formatted after D88956 (treating it as a binop): 10441 verifyFormat("auto x = [](const decltype(x) &ptr) {};"); 10442 verifyFormat("auto x = [](const decltype(x) *ptr) {};"); 10443 verifyFormat("#define lambda [](const decltype(x) &ptr) {}"); 10444 verifyFormat("#define lambda [](const decltype(x) *ptr) {}"); 10445 10446 verifyFormat("DatumHandle const *operator->() const { return input_; }"); 10447 verifyFormat("return options != nullptr && operator==(*options);"); 10448 10449 EXPECT_EQ("#define OP(x) \\\n" 10450 " ostream &operator<<(ostream &s, const A &a) { \\\n" 10451 " return s << a.DebugString(); \\\n" 10452 " }", 10453 format("#define OP(x) \\\n" 10454 " ostream &operator<<(ostream &s, const A &a) { \\\n" 10455 " return s << a.DebugString(); \\\n" 10456 " }", 10457 getLLVMStyleWithColumns(50))); 10458 10459 // FIXME: We cannot handle this case yet; we might be able to figure out that 10460 // foo<x> d > v; doesn't make sense. 10461 verifyFormat("foo<a<b && c> d> v;"); 10462 10463 FormatStyle PointerMiddle = getLLVMStyle(); 10464 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle; 10465 verifyFormat("delete *x;", PointerMiddle); 10466 verifyFormat("int * x;", PointerMiddle); 10467 verifyFormat("int *[] x;", PointerMiddle); 10468 verifyFormat("template <int * y> f() {}", PointerMiddle); 10469 verifyFormat("int * f(int * a) {}", PointerMiddle); 10470 verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle); 10471 verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle); 10472 verifyFormat("A<int *> a;", PointerMiddle); 10473 verifyFormat("A<int **> a;", PointerMiddle); 10474 verifyFormat("A<int *, int *> a;", PointerMiddle); 10475 verifyFormat("A<int *[]> a;", PointerMiddle); 10476 verifyFormat("A = new SomeType *[Length]();", PointerMiddle); 10477 verifyFormat("A = new SomeType *[Length];", PointerMiddle); 10478 verifyFormat("T ** t = new T *;", PointerMiddle); 10479 10480 // Member function reference qualifiers aren't binary operators. 10481 verifyFormat("string // break\n" 10482 "operator()() & {}"); 10483 verifyFormat("string // break\n" 10484 "operator()() && {}"); 10485 verifyGoogleFormat("template <typename T>\n" 10486 "auto x() & -> int {}"); 10487 10488 // Should be binary operators when used as an argument expression (overloaded 10489 // operator invoked as a member function). 10490 verifyFormat("void f() { a.operator()(a * a); }"); 10491 verifyFormat("void f() { a->operator()(a & a); }"); 10492 verifyFormat("void f() { a.operator()(*a & *a); }"); 10493 verifyFormat("void f() { a->operator()(*a * *a); }"); 10494 10495 verifyFormat("int operator()(T (&&)[N]) { return 1; }"); 10496 verifyFormat("int operator()(T (&)[N]) { return 0; }"); 10497 } 10498 10499 TEST_F(FormatTest, UnderstandsAttributes) { 10500 verifyFormat("SomeType s __attribute__((unused)) (InitValue);"); 10501 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n" 10502 "aaaaaaaaaaaaaaaaaaaaaaa(int i);"); 10503 verifyFormat("__attribute__((nodebug)) ::qualified_type f();"); 10504 FormatStyle AfterType = getLLVMStyle(); 10505 AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 10506 verifyFormat("__attribute__((nodebug)) void\n" 10507 "foo() {}\n", 10508 AfterType); 10509 verifyFormat("__unused void\n" 10510 "foo() {}", 10511 AfterType); 10512 10513 FormatStyle CustomAttrs = getLLVMStyle(); 10514 CustomAttrs.AttributeMacros.push_back("__unused"); 10515 CustomAttrs.AttributeMacros.push_back("__attr1"); 10516 CustomAttrs.AttributeMacros.push_back("__attr2"); 10517 CustomAttrs.AttributeMacros.push_back("no_underscore_attr"); 10518 verifyFormat("vector<SomeType *__attribute((foo))> v;"); 10519 verifyFormat("vector<SomeType *__attribute__((foo))> v;"); 10520 verifyFormat("vector<SomeType * __not_attribute__((foo))> v;"); 10521 // Check that it is parsed as a multiplication without AttributeMacros and 10522 // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros. 10523 verifyFormat("vector<SomeType * __attr1> v;"); 10524 verifyFormat("vector<SomeType __attr1 *> v;"); 10525 verifyFormat("vector<SomeType __attr1 *const> v;"); 10526 verifyFormat("vector<SomeType __attr1 * __attr2> v;"); 10527 verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs); 10528 verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs); 10529 verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs); 10530 verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs); 10531 verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs); 10532 verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs); 10533 verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs); 10534 10535 // Check that these are not parsed as function declarations: 10536 CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 10537 CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman; 10538 verifyFormat("SomeType s(InitValue);", CustomAttrs); 10539 verifyFormat("SomeType s{InitValue};", CustomAttrs); 10540 verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs); 10541 verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs); 10542 verifyFormat("SomeType s __unused(InitValue);", CustomAttrs); 10543 verifyFormat("SomeType s __unused{InitValue};", CustomAttrs); 10544 verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs); 10545 verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs); 10546 } 10547 10548 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) { 10549 // Check that qualifiers on pointers don't break parsing of casts. 10550 verifyFormat("x = (foo *const)*v;"); 10551 verifyFormat("x = (foo *volatile)*v;"); 10552 verifyFormat("x = (foo *restrict)*v;"); 10553 verifyFormat("x = (foo *__attribute__((foo)))*v;"); 10554 verifyFormat("x = (foo *_Nonnull)*v;"); 10555 verifyFormat("x = (foo *_Nullable)*v;"); 10556 verifyFormat("x = (foo *_Null_unspecified)*v;"); 10557 verifyFormat("x = (foo *_Nonnull)*v;"); 10558 verifyFormat("x = (foo *[[clang::attr]])*v;"); 10559 verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;"); 10560 verifyFormat("x = (foo *__ptr32)*v;"); 10561 verifyFormat("x = (foo *__ptr64)*v;"); 10562 verifyFormat("x = (foo *__capability)*v;"); 10563 10564 // Check that we handle multiple trailing qualifiers and skip them all to 10565 // determine that the expression is a cast to a pointer type. 10566 FormatStyle LongPointerRight = getLLVMStyleWithColumns(999); 10567 FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999); 10568 LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left; 10569 StringRef AllQualifiers = 10570 "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified " 10571 "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability"; 10572 verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight); 10573 verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft); 10574 10575 // Also check that address-of is not parsed as a binary bitwise-and: 10576 verifyFormat("x = (foo *const)&v;"); 10577 verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight); 10578 verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft); 10579 10580 // Check custom qualifiers: 10581 FormatStyle CustomQualifier = getLLVMStyleWithColumns(999); 10582 CustomQualifier.AttributeMacros.push_back("__my_qualifier"); 10583 verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier. 10584 verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier); 10585 verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(), 10586 CustomQualifier); 10587 verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(), 10588 CustomQualifier); 10589 10590 // Check that unknown identifiers result in binary operator parsing: 10591 verifyFormat("x = (foo * __unknown_qualifier) * v;"); 10592 verifyFormat("x = (foo * __unknown_qualifier) & v;"); 10593 } 10594 10595 TEST_F(FormatTest, UnderstandsSquareAttributes) { 10596 verifyFormat("SomeType s [[unused]] (InitValue);"); 10597 verifyFormat("SomeType s [[gnu::unused]] (InitValue);"); 10598 verifyFormat("SomeType s [[using gnu: unused]] (InitValue);"); 10599 verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}"); 10600 verifyFormat("void f() [[deprecated(\"so sorry\")]];"); 10601 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10602 " [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);"); 10603 verifyFormat("[[nodiscard]] bool f() { return false; }"); 10604 verifyFormat("class [[nodiscard]] f {\npublic:\n f() {}\n}"); 10605 verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n f() {}\n}"); 10606 verifyFormat("class [[gnu::unused]] f {\npublic:\n f() {}\n}"); 10607 verifyFormat("[[nodiscard]] ::qualified_type f();"); 10608 10609 // Make sure we do not mistake attributes for array subscripts. 10610 verifyFormat("int a() {}\n" 10611 "[[unused]] int b() {}\n"); 10612 verifyFormat("NSArray *arr;\n" 10613 "arr[[Foo() bar]];"); 10614 10615 // On the other hand, we still need to correctly find array subscripts. 10616 verifyFormat("int a = std::vector<int>{1, 2, 3}[0];"); 10617 10618 // Make sure that we do not mistake Objective-C method inside array literals 10619 // as attributes, even if those method names are also keywords. 10620 verifyFormat("@[ [foo bar] ];"); 10621 verifyFormat("@[ [NSArray class] ];"); 10622 verifyFormat("@[ [foo enum] ];"); 10623 10624 verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }"); 10625 10626 // Make sure we do not parse attributes as lambda introducers. 10627 FormatStyle MultiLineFunctions = getLLVMStyle(); 10628 MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 10629 verifyFormat("[[unused]] int b() {\n" 10630 " return 42;\n" 10631 "}\n", 10632 MultiLineFunctions); 10633 } 10634 10635 TEST_F(FormatTest, AttributeClass) { 10636 FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp); 10637 verifyFormat("class S {\n" 10638 " S(S&&) = default;\n" 10639 "};", 10640 Style); 10641 verifyFormat("class [[nodiscard]] S {\n" 10642 " S(S&&) = default;\n" 10643 "};", 10644 Style); 10645 verifyFormat("class __attribute((maybeunused)) S {\n" 10646 " S(S&&) = default;\n" 10647 "};", 10648 Style); 10649 verifyFormat("struct S {\n" 10650 " S(S&&) = default;\n" 10651 "};", 10652 Style); 10653 verifyFormat("struct [[nodiscard]] S {\n" 10654 " S(S&&) = default;\n" 10655 "};", 10656 Style); 10657 } 10658 10659 TEST_F(FormatTest, AttributesAfterMacro) { 10660 FormatStyle Style = getLLVMStyle(); 10661 verifyFormat("MACRO;\n" 10662 "__attribute__((maybe_unused)) int foo() {\n" 10663 " //...\n" 10664 "}"); 10665 10666 verifyFormat("MACRO;\n" 10667 "[[nodiscard]] int foo() {\n" 10668 " //...\n" 10669 "}"); 10670 10671 EXPECT_EQ("MACRO\n\n" 10672 "__attribute__((maybe_unused)) int foo() {\n" 10673 " //...\n" 10674 "}", 10675 format("MACRO\n\n" 10676 "__attribute__((maybe_unused)) int foo() {\n" 10677 " //...\n" 10678 "}")); 10679 10680 EXPECT_EQ("MACRO\n\n" 10681 "[[nodiscard]] int foo() {\n" 10682 " //...\n" 10683 "}", 10684 format("MACRO\n\n" 10685 "[[nodiscard]] int foo() {\n" 10686 " //...\n" 10687 "}")); 10688 } 10689 10690 TEST_F(FormatTest, AttributePenaltyBreaking) { 10691 FormatStyle Style = getLLVMStyle(); 10692 verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n" 10693 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}", 10694 Style); 10695 verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n" 10696 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}", 10697 Style); 10698 verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const " 10699 "shared_ptr<ALongTypeName> &C d) {\n}", 10700 Style); 10701 } 10702 10703 TEST_F(FormatTest, UnderstandsEllipsis) { 10704 FormatStyle Style = getLLVMStyle(); 10705 verifyFormat("int printf(const char *fmt, ...);"); 10706 verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }"); 10707 verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}"); 10708 10709 verifyFormat("template <int *...PP> a;", Style); 10710 10711 Style.PointerAlignment = FormatStyle::PAS_Left; 10712 verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style); 10713 10714 verifyFormat("template <int*... PP> a;", Style); 10715 10716 Style.PointerAlignment = FormatStyle::PAS_Middle; 10717 verifyFormat("template <int *... PP> a;", Style); 10718 } 10719 10720 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) { 10721 EXPECT_EQ("int *a;\n" 10722 "int *a;\n" 10723 "int *a;", 10724 format("int *a;\n" 10725 "int* a;\n" 10726 "int *a;", 10727 getGoogleStyle())); 10728 EXPECT_EQ("int* a;\n" 10729 "int* a;\n" 10730 "int* a;", 10731 format("int* a;\n" 10732 "int* a;\n" 10733 "int *a;", 10734 getGoogleStyle())); 10735 EXPECT_EQ("int *a;\n" 10736 "int *a;\n" 10737 "int *a;", 10738 format("int *a;\n" 10739 "int * a;\n" 10740 "int * a;", 10741 getGoogleStyle())); 10742 EXPECT_EQ("auto x = [] {\n" 10743 " int *a;\n" 10744 " int *a;\n" 10745 " int *a;\n" 10746 "};", 10747 format("auto x=[]{int *a;\n" 10748 "int * a;\n" 10749 "int * a;};", 10750 getGoogleStyle())); 10751 } 10752 10753 TEST_F(FormatTest, UnderstandsRvalueReferences) { 10754 verifyFormat("int f(int &&a) {}"); 10755 verifyFormat("int f(int a, char &&b) {}"); 10756 verifyFormat("void f() { int &&a = b; }"); 10757 verifyGoogleFormat("int f(int a, char&& b) {}"); 10758 verifyGoogleFormat("void f() { int&& a = b; }"); 10759 10760 verifyIndependentOfContext("A<int &&> a;"); 10761 verifyIndependentOfContext("A<int &&, int &&> a;"); 10762 verifyGoogleFormat("A<int&&> a;"); 10763 verifyGoogleFormat("A<int&&, int&&> a;"); 10764 10765 // Not rvalue references: 10766 verifyFormat("template <bool B, bool C> class A {\n" 10767 " static_assert(B && C, \"Something is wrong\");\n" 10768 "};"); 10769 verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))"); 10770 verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))"); 10771 verifyFormat("#define A(a, b) (a && b)"); 10772 } 10773 10774 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) { 10775 verifyFormat("void f() {\n" 10776 " x[aaaaaaaaa -\n" 10777 " b] = 23;\n" 10778 "}", 10779 getLLVMStyleWithColumns(15)); 10780 } 10781 10782 TEST_F(FormatTest, FormatsCasts) { 10783 verifyFormat("Type *A = static_cast<Type *>(P);"); 10784 verifyFormat("static_cast<Type *>(P);"); 10785 verifyFormat("static_cast<Type &>(Fun)(Args);"); 10786 verifyFormat("static_cast<Type &>(*Fun)(Args);"); 10787 verifyFormat("if (static_cast<int>(A) + B >= 0)\n ;"); 10788 // Check that static_cast<...>(...) does not require the next token to be on 10789 // the same line. 10790 verifyFormat("some_loooong_output << something_something__ << " 10791 "static_cast<const void *>(R)\n" 10792 " << something;"); 10793 verifyFormat("a = static_cast<Type &>(*Fun)(Args);"); 10794 verifyFormat("const_cast<Type &>(*Fun)(Args);"); 10795 verifyFormat("dynamic_cast<Type &>(*Fun)(Args);"); 10796 verifyFormat("reinterpret_cast<Type &>(*Fun)(Args);"); 10797 verifyFormat("Type *A = (Type *)P;"); 10798 verifyFormat("Type *A = (vector<Type *, int *>)P;"); 10799 verifyFormat("int a = (int)(2.0f);"); 10800 verifyFormat("int a = (int)2.0f;"); 10801 verifyFormat("x[(int32)y];"); 10802 verifyFormat("x = (int32)y;"); 10803 verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)"); 10804 verifyFormat("int a = (int)*b;"); 10805 verifyFormat("int a = (int)2.0f;"); 10806 verifyFormat("int a = (int)~0;"); 10807 verifyFormat("int a = (int)++a;"); 10808 verifyFormat("int a = (int)sizeof(int);"); 10809 verifyFormat("int a = (int)+2;"); 10810 verifyFormat("my_int a = (my_int)2.0f;"); 10811 verifyFormat("my_int a = (my_int)sizeof(int);"); 10812 verifyFormat("return (my_int)aaa;"); 10813 verifyFormat("#define x ((int)-1)"); 10814 verifyFormat("#define LENGTH(x, y) (x) - (y) + 1"); 10815 verifyFormat("#define p(q) ((int *)&q)"); 10816 verifyFormat("fn(a)(b) + 1;"); 10817 10818 verifyFormat("void f() { my_int a = (my_int)*b; }"); 10819 verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }"); 10820 verifyFormat("my_int a = (my_int)~0;"); 10821 verifyFormat("my_int a = (my_int)++a;"); 10822 verifyFormat("my_int a = (my_int)-2;"); 10823 verifyFormat("my_int a = (my_int)1;"); 10824 verifyFormat("my_int a = (my_int *)1;"); 10825 verifyFormat("my_int a = (const my_int)-1;"); 10826 verifyFormat("my_int a = (const my_int *)-1;"); 10827 verifyFormat("my_int a = (my_int)(my_int)-1;"); 10828 verifyFormat("my_int a = (ns::my_int)-2;"); 10829 verifyFormat("case (my_int)ONE:"); 10830 verifyFormat("auto x = (X)this;"); 10831 // Casts in Obj-C style calls used to not be recognized as such. 10832 verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle()); 10833 10834 // FIXME: single value wrapped with paren will be treated as cast. 10835 verifyFormat("void f(int i = (kValue)*kMask) {}"); 10836 10837 verifyFormat("{ (void)F; }"); 10838 10839 // Don't break after a cast's 10840 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 10841 " (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n" 10842 " bbbbbbbbbbbbbbbbbbbbbb);"); 10843 10844 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(x)"); 10845 verifyFormat("#define CONF_BOOL(x) (bool *)(x)"); 10846 verifyFormat("#define CONF_BOOL(x) (bool)(x)"); 10847 verifyFormat("bool *y = (bool *)(void *)(x);"); 10848 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)(x)"); 10849 verifyFormat("bool *y = (bool *)(void *)(int)(x);"); 10850 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)foo(x)"); 10851 verifyFormat("bool *y = (bool *)(void *)(int)foo(x);"); 10852 10853 // These are not casts. 10854 verifyFormat("void f(int *) {}"); 10855 verifyFormat("f(foo)->b;"); 10856 verifyFormat("f(foo).b;"); 10857 verifyFormat("f(foo)(b);"); 10858 verifyFormat("f(foo)[b];"); 10859 verifyFormat("[](foo) { return 4; }(bar);"); 10860 verifyFormat("(*funptr)(foo)[4];"); 10861 verifyFormat("funptrs[4](foo)[4];"); 10862 verifyFormat("void f(int *);"); 10863 verifyFormat("void f(int *) = 0;"); 10864 verifyFormat("void f(SmallVector<int>) {}"); 10865 verifyFormat("void f(SmallVector<int>);"); 10866 verifyFormat("void f(SmallVector<int>) = 0;"); 10867 verifyFormat("void f(int i = (kA * kB) & kMask) {}"); 10868 verifyFormat("int a = sizeof(int) * b;"); 10869 verifyFormat("int a = alignof(int) * b;", getGoogleStyle()); 10870 verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;"); 10871 verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");"); 10872 verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;"); 10873 10874 // These are not casts, but at some point were confused with casts. 10875 verifyFormat("virtual void foo(int *) override;"); 10876 verifyFormat("virtual void foo(char &) const;"); 10877 verifyFormat("virtual void foo(int *a, char *) const;"); 10878 verifyFormat("int a = sizeof(int *) + b;"); 10879 verifyFormat("int a = alignof(int *) + b;", getGoogleStyle()); 10880 verifyFormat("bool b = f(g<int>) && c;"); 10881 verifyFormat("typedef void (*f)(int i) func;"); 10882 verifyFormat("void operator++(int) noexcept;"); 10883 verifyFormat("void operator++(int &) noexcept;"); 10884 verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t " 10885 "&) noexcept;"); 10886 verifyFormat( 10887 "void operator delete(std::size_t, const std::nothrow_t &) noexcept;"); 10888 verifyFormat("void operator delete(const std::nothrow_t &) noexcept;"); 10889 verifyFormat("void operator delete(std::nothrow_t &) noexcept;"); 10890 verifyFormat("void operator delete(nothrow_t &) noexcept;"); 10891 verifyFormat("void operator delete(foo &) noexcept;"); 10892 verifyFormat("void operator delete(foo) noexcept;"); 10893 verifyFormat("void operator delete(int) noexcept;"); 10894 verifyFormat("void operator delete(int &) noexcept;"); 10895 verifyFormat("void operator delete(int &) volatile noexcept;"); 10896 verifyFormat("void operator delete(int &) const"); 10897 verifyFormat("void operator delete(int &) = default"); 10898 verifyFormat("void operator delete(int &) = delete"); 10899 verifyFormat("void operator delete(int &) [[noreturn]]"); 10900 verifyFormat("void operator delete(int &) throw();"); 10901 verifyFormat("void operator delete(int &) throw(int);"); 10902 verifyFormat("auto operator delete(int &) -> int;"); 10903 verifyFormat("auto operator delete(int &) override"); 10904 verifyFormat("auto operator delete(int &) final"); 10905 10906 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n" 10907 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 10908 // FIXME: The indentation here is not ideal. 10909 verifyFormat( 10910 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10911 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n" 10912 " [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];"); 10913 } 10914 10915 TEST_F(FormatTest, FormatsFunctionTypes) { 10916 verifyFormat("A<bool()> a;"); 10917 verifyFormat("A<SomeType()> a;"); 10918 verifyFormat("A<void (*)(int, std::string)> a;"); 10919 verifyFormat("A<void *(int)>;"); 10920 verifyFormat("void *(*a)(int *, SomeType *);"); 10921 verifyFormat("int (*func)(void *);"); 10922 verifyFormat("void f() { int (*func)(void *); }"); 10923 verifyFormat("template <class CallbackClass>\n" 10924 "using MyCallback = void (CallbackClass::*)(SomeObject *Data);"); 10925 10926 verifyGoogleFormat("A<void*(int*, SomeType*)>;"); 10927 verifyGoogleFormat("void* (*a)(int);"); 10928 verifyGoogleFormat( 10929 "template <class CallbackClass>\n" 10930 "using MyCallback = void (CallbackClass::*)(SomeObject* Data);"); 10931 10932 // Other constructs can look somewhat like function types: 10933 verifyFormat("A<sizeof(*x)> a;"); 10934 verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)"); 10935 verifyFormat("some_var = function(*some_pointer_var)[0];"); 10936 verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }"); 10937 verifyFormat("int x = f(&h)();"); 10938 verifyFormat("returnsFunction(¶m1, ¶m2)(param);"); 10939 verifyFormat("std::function<\n" 10940 " LooooooooooongTemplatedType<\n" 10941 " SomeType>*(\n" 10942 " LooooooooooooooooongType type)>\n" 10943 " function;", 10944 getGoogleStyleWithColumns(40)); 10945 } 10946 10947 TEST_F(FormatTest, FormatsPointersToArrayTypes) { 10948 verifyFormat("A (*foo_)[6];"); 10949 verifyFormat("vector<int> (*foo_)[6];"); 10950 } 10951 10952 TEST_F(FormatTest, BreaksLongVariableDeclarations) { 10953 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10954 " LoooooooooooooooooooooooooooooooooooooooongVariable;"); 10955 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n" 10956 " LoooooooooooooooooooooooooooooooooooooooongVariable;"); 10957 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10958 " *LoooooooooooooooooooooooooooooooooooooooongVariable;"); 10959 10960 // Different ways of ()-initializiation. 10961 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10962 " LoooooooooooooooooooooooooooooooooooooooongVariable(1);"); 10963 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10964 " LoooooooooooooooooooooooooooooooooooooooongVariable(a);"); 10965 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10966 " LoooooooooooooooooooooooooooooooooooooooongVariable({});"); 10967 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10968 " LoooooooooooooooooooooooooooooooooooooongVariable([A a]);"); 10969 10970 // Lambdas should not confuse the variable declaration heuristic. 10971 verifyFormat("LooooooooooooooooongType\n" 10972 " variable(nullptr, [](A *a) {});", 10973 getLLVMStyleWithColumns(40)); 10974 } 10975 10976 TEST_F(FormatTest, BreaksLongDeclarations) { 10977 verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n" 10978 " AnotherNameForTheLongType;"); 10979 verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n" 10980 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 10981 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10982 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();"); 10983 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n" 10984 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();"); 10985 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10986 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10987 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n" 10988 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10989 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n" 10990 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10991 verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n" 10992 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10993 verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n" 10994 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10995 verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n" 10996 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10997 verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n" 10998 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10999 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 11000 "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);"); 11001 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 11002 "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}"); 11003 FormatStyle Indented = getLLVMStyle(); 11004 Indented.IndentWrappedFunctionNames = true; 11005 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 11006 " LoooooooooooooooooooooooooooooooongFunctionDeclaration();", 11007 Indented); 11008 verifyFormat( 11009 "LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 11010 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 11011 Indented); 11012 verifyFormat( 11013 "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n" 11014 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 11015 Indented); 11016 verifyFormat( 11017 "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n" 11018 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 11019 Indented); 11020 11021 // FIXME: Without the comment, this breaks after "(". 11022 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType // break\n" 11023 " (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();", 11024 getGoogleStyle()); 11025 11026 verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n" 11027 " int LoooooooooooooooooooongParam2) {}"); 11028 verifyFormat( 11029 "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n" 11030 " SourceLocation L, IdentifierIn *II,\n" 11031 " Type *T) {}"); 11032 verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n" 11033 "ReallyReaaallyLongFunctionName(\n" 11034 " const std::string &SomeParameter,\n" 11035 " const SomeType<string, SomeOtherTemplateParameter>\n" 11036 " &ReallyReallyLongParameterName,\n" 11037 " const SomeType<string, SomeOtherTemplateParameter>\n" 11038 " &AnotherLongParameterName) {}"); 11039 verifyFormat("template <typename A>\n" 11040 "SomeLoooooooooooooooooooooongType<\n" 11041 " typename some_namespace::SomeOtherType<A>::Type>\n" 11042 "Function() {}"); 11043 11044 verifyGoogleFormat( 11045 "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n" 11046 " aaaaaaaaaaaaaaaaaaaaaaa;"); 11047 verifyGoogleFormat( 11048 "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n" 11049 " SourceLocation L) {}"); 11050 verifyGoogleFormat( 11051 "some_namespace::LongReturnType\n" 11052 "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n" 11053 " int first_long_parameter, int second_parameter) {}"); 11054 11055 verifyGoogleFormat("template <typename T>\n" 11056 "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n" 11057 "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}"); 11058 verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 11059 " int aaaaaaaaaaaaaaaaaaaaaaa);"); 11060 11061 verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n" 11062 " const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11063 " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 11064 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 11065 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n" 11066 " aaaaaaaaaaaaaaaaaaaaaaaa);"); 11067 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 11068 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 11069 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n" 11070 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 11071 11072 verifyFormat("template <typename T> // Templates on own line.\n" 11073 "static int // Some comment.\n" 11074 "MyFunction(int a);", 11075 getLLVMStyle()); 11076 } 11077 11078 TEST_F(FormatTest, FormatsAccessModifiers) { 11079 FormatStyle Style = getLLVMStyle(); 11080 EXPECT_EQ(Style.EmptyLineBeforeAccessModifier, 11081 FormatStyle::ELBAMS_LogicalBlock); 11082 verifyFormat("struct foo {\n" 11083 "private:\n" 11084 " void f() {}\n" 11085 "\n" 11086 "private:\n" 11087 " int i;\n" 11088 "\n" 11089 "protected:\n" 11090 " int j;\n" 11091 "};\n", 11092 Style); 11093 verifyFormat("struct foo {\n" 11094 "private:\n" 11095 " void f() {}\n" 11096 "\n" 11097 "private:\n" 11098 " int i;\n" 11099 "\n" 11100 "protected:\n" 11101 " int j;\n" 11102 "};\n", 11103 "struct foo {\n" 11104 "private:\n" 11105 " void f() {}\n" 11106 "private:\n" 11107 " int i;\n" 11108 "protected:\n" 11109 " int j;\n" 11110 "};\n", 11111 Style); 11112 verifyFormat("struct foo { /* comment */\n" 11113 "private:\n" 11114 " int i;\n" 11115 " // comment\n" 11116 "private:\n" 11117 " int j;\n" 11118 "};\n", 11119 Style); 11120 verifyFormat("struct foo {\n" 11121 "#ifdef FOO\n" 11122 "#endif\n" 11123 "private:\n" 11124 " int i;\n" 11125 "#ifdef FOO\n" 11126 "private:\n" 11127 "#endif\n" 11128 " int j;\n" 11129 "};\n", 11130 Style); 11131 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11132 verifyFormat("struct foo {\n" 11133 "private:\n" 11134 " void f() {}\n" 11135 "private:\n" 11136 " int i;\n" 11137 "protected:\n" 11138 " int j;\n" 11139 "};\n", 11140 Style); 11141 verifyFormat("struct foo {\n" 11142 "private:\n" 11143 " void f() {}\n" 11144 "private:\n" 11145 " int i;\n" 11146 "protected:\n" 11147 " int j;\n" 11148 "};\n", 11149 "struct foo {\n" 11150 "\n" 11151 "private:\n" 11152 " void f() {}\n" 11153 "\n" 11154 "private:\n" 11155 " int i;\n" 11156 "\n" 11157 "protected:\n" 11158 " int j;\n" 11159 "};\n", 11160 Style); 11161 verifyFormat("struct foo { /* comment */\n" 11162 "private:\n" 11163 " int i;\n" 11164 " // comment\n" 11165 "private:\n" 11166 " int j;\n" 11167 "};\n", 11168 "struct foo { /* comment */\n" 11169 "\n" 11170 "private:\n" 11171 " int i;\n" 11172 " // comment\n" 11173 "\n" 11174 "private:\n" 11175 " int j;\n" 11176 "};\n", 11177 Style); 11178 verifyFormat("struct foo {\n" 11179 "#ifdef FOO\n" 11180 "#endif\n" 11181 "private:\n" 11182 " int i;\n" 11183 "#ifdef FOO\n" 11184 "private:\n" 11185 "#endif\n" 11186 " int j;\n" 11187 "};\n", 11188 "struct foo {\n" 11189 "#ifdef FOO\n" 11190 "#endif\n" 11191 "\n" 11192 "private:\n" 11193 " int i;\n" 11194 "#ifdef FOO\n" 11195 "\n" 11196 "private:\n" 11197 "#endif\n" 11198 " int j;\n" 11199 "};\n", 11200 Style); 11201 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11202 verifyFormat("struct foo {\n" 11203 "private:\n" 11204 " void f() {}\n" 11205 "\n" 11206 "private:\n" 11207 " int i;\n" 11208 "\n" 11209 "protected:\n" 11210 " int j;\n" 11211 "};\n", 11212 Style); 11213 verifyFormat("struct foo {\n" 11214 "private:\n" 11215 " void f() {}\n" 11216 "\n" 11217 "private:\n" 11218 " int i;\n" 11219 "\n" 11220 "protected:\n" 11221 " int j;\n" 11222 "};\n", 11223 "struct foo {\n" 11224 "private:\n" 11225 " void f() {}\n" 11226 "private:\n" 11227 " int i;\n" 11228 "protected:\n" 11229 " int j;\n" 11230 "};\n", 11231 Style); 11232 verifyFormat("struct foo { /* comment */\n" 11233 "private:\n" 11234 " int i;\n" 11235 " // comment\n" 11236 "\n" 11237 "private:\n" 11238 " int j;\n" 11239 "};\n", 11240 "struct foo { /* comment */\n" 11241 "private:\n" 11242 " int i;\n" 11243 " // comment\n" 11244 "\n" 11245 "private:\n" 11246 " int j;\n" 11247 "};\n", 11248 Style); 11249 verifyFormat("struct foo {\n" 11250 "#ifdef FOO\n" 11251 "#endif\n" 11252 "\n" 11253 "private:\n" 11254 " int i;\n" 11255 "#ifdef FOO\n" 11256 "\n" 11257 "private:\n" 11258 "#endif\n" 11259 " int j;\n" 11260 "};\n", 11261 "struct foo {\n" 11262 "#ifdef FOO\n" 11263 "#endif\n" 11264 "private:\n" 11265 " int i;\n" 11266 "#ifdef FOO\n" 11267 "private:\n" 11268 "#endif\n" 11269 " int j;\n" 11270 "};\n", 11271 Style); 11272 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11273 EXPECT_EQ("struct foo {\n" 11274 "\n" 11275 "private:\n" 11276 " void f() {}\n" 11277 "\n" 11278 "private:\n" 11279 " int i;\n" 11280 "\n" 11281 "protected:\n" 11282 " int j;\n" 11283 "};\n", 11284 format("struct foo {\n" 11285 "\n" 11286 "private:\n" 11287 " void f() {}\n" 11288 "\n" 11289 "private:\n" 11290 " int i;\n" 11291 "\n" 11292 "protected:\n" 11293 " int j;\n" 11294 "};\n", 11295 Style)); 11296 verifyFormat("struct foo {\n" 11297 "private:\n" 11298 " void f() {}\n" 11299 "private:\n" 11300 " int i;\n" 11301 "protected:\n" 11302 " int j;\n" 11303 "};\n", 11304 Style); 11305 EXPECT_EQ("struct foo { /* comment */\n" 11306 "\n" 11307 "private:\n" 11308 " int i;\n" 11309 " // comment\n" 11310 "\n" 11311 "private:\n" 11312 " int j;\n" 11313 "};\n", 11314 format("struct foo { /* comment */\n" 11315 "\n" 11316 "private:\n" 11317 " int i;\n" 11318 " // comment\n" 11319 "\n" 11320 "private:\n" 11321 " int j;\n" 11322 "};\n", 11323 Style)); 11324 verifyFormat("struct foo { /* comment */\n" 11325 "private:\n" 11326 " int i;\n" 11327 " // comment\n" 11328 "private:\n" 11329 " int j;\n" 11330 "};\n", 11331 Style); 11332 EXPECT_EQ("struct foo {\n" 11333 "#ifdef FOO\n" 11334 "#endif\n" 11335 "\n" 11336 "private:\n" 11337 " int i;\n" 11338 "#ifdef FOO\n" 11339 "\n" 11340 "private:\n" 11341 "#endif\n" 11342 " int j;\n" 11343 "};\n", 11344 format("struct foo {\n" 11345 "#ifdef FOO\n" 11346 "#endif\n" 11347 "\n" 11348 "private:\n" 11349 " int i;\n" 11350 "#ifdef FOO\n" 11351 "\n" 11352 "private:\n" 11353 "#endif\n" 11354 " int j;\n" 11355 "};\n", 11356 Style)); 11357 verifyFormat("struct foo {\n" 11358 "#ifdef FOO\n" 11359 "#endif\n" 11360 "private:\n" 11361 " int i;\n" 11362 "#ifdef FOO\n" 11363 "private:\n" 11364 "#endif\n" 11365 " int j;\n" 11366 "};\n", 11367 Style); 11368 11369 FormatStyle NoEmptyLines = getLLVMStyle(); 11370 NoEmptyLines.MaxEmptyLinesToKeep = 0; 11371 verifyFormat("struct foo {\n" 11372 "private:\n" 11373 " void f() {}\n" 11374 "\n" 11375 "private:\n" 11376 " int i;\n" 11377 "\n" 11378 "public:\n" 11379 "protected:\n" 11380 " int j;\n" 11381 "};\n", 11382 NoEmptyLines); 11383 11384 NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11385 verifyFormat("struct foo {\n" 11386 "private:\n" 11387 " void f() {}\n" 11388 "private:\n" 11389 " int i;\n" 11390 "public:\n" 11391 "protected:\n" 11392 " int j;\n" 11393 "};\n", 11394 NoEmptyLines); 11395 11396 NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11397 verifyFormat("struct foo {\n" 11398 "private:\n" 11399 " void f() {}\n" 11400 "\n" 11401 "private:\n" 11402 " int i;\n" 11403 "\n" 11404 "public:\n" 11405 "\n" 11406 "protected:\n" 11407 " int j;\n" 11408 "};\n", 11409 NoEmptyLines); 11410 } 11411 11412 TEST_F(FormatTest, FormatsAfterAccessModifiers) { 11413 11414 FormatStyle Style = getLLVMStyle(); 11415 EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never); 11416 verifyFormat("struct foo {\n" 11417 "private:\n" 11418 " void f() {}\n" 11419 "\n" 11420 "private:\n" 11421 " int i;\n" 11422 "\n" 11423 "protected:\n" 11424 " int j;\n" 11425 "};\n", 11426 Style); 11427 11428 // Check if lines are removed. 11429 verifyFormat("struct foo {\n" 11430 "private:\n" 11431 " void f() {}\n" 11432 "\n" 11433 "private:\n" 11434 " int i;\n" 11435 "\n" 11436 "protected:\n" 11437 " int j;\n" 11438 "};\n", 11439 "struct foo {\n" 11440 "private:\n" 11441 "\n" 11442 " void f() {}\n" 11443 "\n" 11444 "private:\n" 11445 "\n" 11446 " int i;\n" 11447 "\n" 11448 "protected:\n" 11449 "\n" 11450 " int j;\n" 11451 "};\n", 11452 Style); 11453 11454 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11455 verifyFormat("struct foo {\n" 11456 "private:\n" 11457 "\n" 11458 " void f() {}\n" 11459 "\n" 11460 "private:\n" 11461 "\n" 11462 " int i;\n" 11463 "\n" 11464 "protected:\n" 11465 "\n" 11466 " int j;\n" 11467 "};\n", 11468 Style); 11469 11470 // Check if lines are added. 11471 verifyFormat("struct foo {\n" 11472 "private:\n" 11473 "\n" 11474 " void f() {}\n" 11475 "\n" 11476 "private:\n" 11477 "\n" 11478 " int i;\n" 11479 "\n" 11480 "protected:\n" 11481 "\n" 11482 " int j;\n" 11483 "};\n", 11484 "struct foo {\n" 11485 "private:\n" 11486 " void f() {}\n" 11487 "\n" 11488 "private:\n" 11489 " int i;\n" 11490 "\n" 11491 "protected:\n" 11492 " int j;\n" 11493 "};\n", 11494 Style); 11495 11496 // Leave tests rely on the code layout, test::messUp can not be used. 11497 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11498 Style.MaxEmptyLinesToKeep = 0u; 11499 verifyFormat("struct foo {\n" 11500 "private:\n" 11501 " void f() {}\n" 11502 "\n" 11503 "private:\n" 11504 " int i;\n" 11505 "\n" 11506 "protected:\n" 11507 " int j;\n" 11508 "};\n", 11509 Style); 11510 11511 // Check if MaxEmptyLinesToKeep is respected. 11512 EXPECT_EQ("struct foo {\n" 11513 "private:\n" 11514 " void f() {}\n" 11515 "\n" 11516 "private:\n" 11517 " int i;\n" 11518 "\n" 11519 "protected:\n" 11520 " int j;\n" 11521 "};\n", 11522 format("struct foo {\n" 11523 "private:\n" 11524 "\n\n\n" 11525 " void f() {}\n" 11526 "\n" 11527 "private:\n" 11528 "\n\n\n" 11529 " int i;\n" 11530 "\n" 11531 "protected:\n" 11532 "\n\n\n" 11533 " int j;\n" 11534 "};\n", 11535 Style)); 11536 11537 Style.MaxEmptyLinesToKeep = 1u; 11538 EXPECT_EQ("struct foo {\n" 11539 "private:\n" 11540 "\n" 11541 " void f() {}\n" 11542 "\n" 11543 "private:\n" 11544 "\n" 11545 " int i;\n" 11546 "\n" 11547 "protected:\n" 11548 "\n" 11549 " int j;\n" 11550 "};\n", 11551 format("struct foo {\n" 11552 "private:\n" 11553 "\n" 11554 " void f() {}\n" 11555 "\n" 11556 "private:\n" 11557 "\n" 11558 " int i;\n" 11559 "\n" 11560 "protected:\n" 11561 "\n" 11562 " int j;\n" 11563 "};\n", 11564 Style)); 11565 // Check if no lines are kept. 11566 EXPECT_EQ("struct foo {\n" 11567 "private:\n" 11568 " void f() {}\n" 11569 "\n" 11570 "private:\n" 11571 " int i;\n" 11572 "\n" 11573 "protected:\n" 11574 " int j;\n" 11575 "};\n", 11576 format("struct foo {\n" 11577 "private:\n" 11578 " void f() {}\n" 11579 "\n" 11580 "private:\n" 11581 " int i;\n" 11582 "\n" 11583 "protected:\n" 11584 " int j;\n" 11585 "};\n", 11586 Style)); 11587 // Check if MaxEmptyLinesToKeep is respected. 11588 EXPECT_EQ("struct foo {\n" 11589 "private:\n" 11590 "\n" 11591 " void f() {}\n" 11592 "\n" 11593 "private:\n" 11594 "\n" 11595 " int i;\n" 11596 "\n" 11597 "protected:\n" 11598 "\n" 11599 " int j;\n" 11600 "};\n", 11601 format("struct foo {\n" 11602 "private:\n" 11603 "\n\n\n" 11604 " void f() {}\n" 11605 "\n" 11606 "private:\n" 11607 "\n\n\n" 11608 " int i;\n" 11609 "\n" 11610 "protected:\n" 11611 "\n\n\n" 11612 " int j;\n" 11613 "};\n", 11614 Style)); 11615 11616 Style.MaxEmptyLinesToKeep = 10u; 11617 EXPECT_EQ("struct foo {\n" 11618 "private:\n" 11619 "\n\n\n" 11620 " void f() {}\n" 11621 "\n" 11622 "private:\n" 11623 "\n\n\n" 11624 " int i;\n" 11625 "\n" 11626 "protected:\n" 11627 "\n\n\n" 11628 " int j;\n" 11629 "};\n", 11630 format("struct foo {\n" 11631 "private:\n" 11632 "\n\n\n" 11633 " void f() {}\n" 11634 "\n" 11635 "private:\n" 11636 "\n\n\n" 11637 " int i;\n" 11638 "\n" 11639 "protected:\n" 11640 "\n\n\n" 11641 " int j;\n" 11642 "};\n", 11643 Style)); 11644 11645 // Test with comments. 11646 Style = getLLVMStyle(); 11647 verifyFormat("struct foo {\n" 11648 "private:\n" 11649 " // comment\n" 11650 " void f() {}\n" 11651 "\n" 11652 "private: /* comment */\n" 11653 " int i;\n" 11654 "};\n", 11655 Style); 11656 verifyFormat("struct foo {\n" 11657 "private:\n" 11658 " // comment\n" 11659 " void f() {}\n" 11660 "\n" 11661 "private: /* comment */\n" 11662 " int i;\n" 11663 "};\n", 11664 "struct foo {\n" 11665 "private:\n" 11666 "\n" 11667 " // comment\n" 11668 " void f() {}\n" 11669 "\n" 11670 "private: /* comment */\n" 11671 "\n" 11672 " int i;\n" 11673 "};\n", 11674 Style); 11675 11676 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11677 verifyFormat("struct foo {\n" 11678 "private:\n" 11679 "\n" 11680 " // comment\n" 11681 " void f() {}\n" 11682 "\n" 11683 "private: /* comment */\n" 11684 "\n" 11685 " int i;\n" 11686 "};\n", 11687 "struct foo {\n" 11688 "private:\n" 11689 " // comment\n" 11690 " void f() {}\n" 11691 "\n" 11692 "private: /* comment */\n" 11693 " int i;\n" 11694 "};\n", 11695 Style); 11696 verifyFormat("struct foo {\n" 11697 "private:\n" 11698 "\n" 11699 " // comment\n" 11700 " void f() {}\n" 11701 "\n" 11702 "private: /* comment */\n" 11703 "\n" 11704 " int i;\n" 11705 "};\n", 11706 Style); 11707 11708 // Test with preprocessor defines. 11709 Style = getLLVMStyle(); 11710 verifyFormat("struct foo {\n" 11711 "private:\n" 11712 "#ifdef FOO\n" 11713 "#endif\n" 11714 " void f() {}\n" 11715 "};\n", 11716 Style); 11717 verifyFormat("struct foo {\n" 11718 "private:\n" 11719 "#ifdef FOO\n" 11720 "#endif\n" 11721 " void f() {}\n" 11722 "};\n", 11723 "struct foo {\n" 11724 "private:\n" 11725 "\n" 11726 "#ifdef FOO\n" 11727 "#endif\n" 11728 " void f() {}\n" 11729 "};\n", 11730 Style); 11731 11732 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11733 verifyFormat("struct foo {\n" 11734 "private:\n" 11735 "\n" 11736 "#ifdef FOO\n" 11737 "#endif\n" 11738 " void f() {}\n" 11739 "};\n", 11740 "struct foo {\n" 11741 "private:\n" 11742 "#ifdef FOO\n" 11743 "#endif\n" 11744 " void f() {}\n" 11745 "};\n", 11746 Style); 11747 verifyFormat("struct foo {\n" 11748 "private:\n" 11749 "\n" 11750 "#ifdef FOO\n" 11751 "#endif\n" 11752 " void f() {}\n" 11753 "};\n", 11754 Style); 11755 } 11756 11757 TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) { 11758 // Combined tests of EmptyLineAfterAccessModifier and 11759 // EmptyLineBeforeAccessModifier. 11760 FormatStyle Style = getLLVMStyle(); 11761 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11762 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11763 verifyFormat("struct foo {\n" 11764 "private:\n" 11765 "\n" 11766 "protected:\n" 11767 "};\n", 11768 Style); 11769 11770 Style.MaxEmptyLinesToKeep = 10u; 11771 // Both remove all new lines. 11772 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11773 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11774 verifyFormat("struct foo {\n" 11775 "private:\n" 11776 "protected:\n" 11777 "};\n", 11778 "struct foo {\n" 11779 "private:\n" 11780 "\n\n\n" 11781 "protected:\n" 11782 "};\n", 11783 Style); 11784 11785 // Leave tests rely on the code layout, test::messUp can not be used. 11786 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11787 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11788 Style.MaxEmptyLinesToKeep = 10u; 11789 EXPECT_EQ("struct foo {\n" 11790 "private:\n" 11791 "\n\n\n" 11792 "protected:\n" 11793 "};\n", 11794 format("struct foo {\n" 11795 "private:\n" 11796 "\n\n\n" 11797 "protected:\n" 11798 "};\n", 11799 Style)); 11800 Style.MaxEmptyLinesToKeep = 3u; 11801 EXPECT_EQ("struct foo {\n" 11802 "private:\n" 11803 "\n\n\n" 11804 "protected:\n" 11805 "};\n", 11806 format("struct foo {\n" 11807 "private:\n" 11808 "\n\n\n" 11809 "protected:\n" 11810 "};\n", 11811 Style)); 11812 Style.MaxEmptyLinesToKeep = 1u; 11813 EXPECT_EQ("struct foo {\n" 11814 "private:\n" 11815 "\n\n\n" 11816 "protected:\n" 11817 "};\n", 11818 format("struct foo {\n" 11819 "private:\n" 11820 "\n\n\n" 11821 "protected:\n" 11822 "};\n", 11823 Style)); // Based on new lines in original document and not 11824 // on the setting. 11825 11826 Style.MaxEmptyLinesToKeep = 10u; 11827 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11828 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11829 // Newlines are kept if they are greater than zero, 11830 // test::messUp removes all new lines which changes the logic 11831 EXPECT_EQ("struct foo {\n" 11832 "private:\n" 11833 "\n\n\n" 11834 "protected:\n" 11835 "};\n", 11836 format("struct foo {\n" 11837 "private:\n" 11838 "\n\n\n" 11839 "protected:\n" 11840 "};\n", 11841 Style)); 11842 11843 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11844 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11845 // test::messUp removes all new lines which changes the logic 11846 EXPECT_EQ("struct foo {\n" 11847 "private:\n" 11848 "\n\n\n" 11849 "protected:\n" 11850 "};\n", 11851 format("struct foo {\n" 11852 "private:\n" 11853 "\n\n\n" 11854 "protected:\n" 11855 "};\n", 11856 Style)); 11857 11858 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11859 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11860 EXPECT_EQ("struct foo {\n" 11861 "private:\n" 11862 "\n\n\n" 11863 "protected:\n" 11864 "};\n", 11865 format("struct foo {\n" 11866 "private:\n" 11867 "\n\n\n" 11868 "protected:\n" 11869 "};\n", 11870 Style)); // test::messUp removes all new lines which changes 11871 // the logic. 11872 11873 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11874 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11875 verifyFormat("struct foo {\n" 11876 "private:\n" 11877 "protected:\n" 11878 "};\n", 11879 "struct foo {\n" 11880 "private:\n" 11881 "\n\n\n" 11882 "protected:\n" 11883 "};\n", 11884 Style); 11885 11886 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11887 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11888 EXPECT_EQ("struct foo {\n" 11889 "private:\n" 11890 "\n\n\n" 11891 "protected:\n" 11892 "};\n", 11893 format("struct foo {\n" 11894 "private:\n" 11895 "\n\n\n" 11896 "protected:\n" 11897 "};\n", 11898 Style)); // test::messUp removes all new lines which changes 11899 // the logic. 11900 11901 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11902 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11903 verifyFormat("struct foo {\n" 11904 "private:\n" 11905 "protected:\n" 11906 "};\n", 11907 "struct foo {\n" 11908 "private:\n" 11909 "\n\n\n" 11910 "protected:\n" 11911 "};\n", 11912 Style); 11913 11914 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11915 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11916 verifyFormat("struct foo {\n" 11917 "private:\n" 11918 "protected:\n" 11919 "};\n", 11920 "struct foo {\n" 11921 "private:\n" 11922 "\n\n\n" 11923 "protected:\n" 11924 "};\n", 11925 Style); 11926 11927 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11928 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11929 verifyFormat("struct foo {\n" 11930 "private:\n" 11931 "protected:\n" 11932 "};\n", 11933 "struct foo {\n" 11934 "private:\n" 11935 "\n\n\n" 11936 "protected:\n" 11937 "};\n", 11938 Style); 11939 11940 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11941 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11942 verifyFormat("struct foo {\n" 11943 "private:\n" 11944 "protected:\n" 11945 "};\n", 11946 "struct foo {\n" 11947 "private:\n" 11948 "\n\n\n" 11949 "protected:\n" 11950 "};\n", 11951 Style); 11952 } 11953 11954 TEST_F(FormatTest, FormatsArrays) { 11955 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n" 11956 " [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;"); 11957 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n" 11958 " [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;"); 11959 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n" 11960 " aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}"); 11961 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11962 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;"); 11963 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11964 " [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;"); 11965 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11966 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n" 11967 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;"); 11968 verifyFormat( 11969 "llvm::outs() << \"aaaaaaaaaaaa: \"\n" 11970 " << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n" 11971 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];"); 11972 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n" 11973 " .aaaaaaaaaaaaaaaaaaaaaa();"); 11974 11975 verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n" 11976 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];"); 11977 verifyFormat( 11978 "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n" 11979 " .aaaaaaa[0]\n" 11980 " .aaaaaaaaaaaaaaaaaaaaaa();"); 11981 verifyFormat("a[::b::c];"); 11982 11983 verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10)); 11984 11985 FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0); 11986 verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit); 11987 } 11988 11989 TEST_F(FormatTest, LineStartsWithSpecialCharacter) { 11990 verifyFormat("(a)->b();"); 11991 verifyFormat("--a;"); 11992 } 11993 11994 TEST_F(FormatTest, HandlesIncludeDirectives) { 11995 verifyFormat("#include <string>\n" 11996 "#include <a/b/c.h>\n" 11997 "#include \"a/b/string\"\n" 11998 "#include \"string.h\"\n" 11999 "#include \"string.h\"\n" 12000 "#include <a-a>\n" 12001 "#include < path with space >\n" 12002 "#include_next <test.h>" 12003 "#include \"abc.h\" // this is included for ABC\n" 12004 "#include \"some long include\" // with a comment\n" 12005 "#include \"some very long include path\"\n" 12006 "#include <some/very/long/include/path>\n", 12007 getLLVMStyleWithColumns(35)); 12008 EXPECT_EQ("#include \"a.h\"", format("#include \"a.h\"")); 12009 EXPECT_EQ("#include <a>", format("#include<a>")); 12010 12011 verifyFormat("#import <string>"); 12012 verifyFormat("#import <a/b/c.h>"); 12013 verifyFormat("#import \"a/b/string\""); 12014 verifyFormat("#import \"string.h\""); 12015 verifyFormat("#import \"string.h\""); 12016 verifyFormat("#if __has_include(<strstream>)\n" 12017 "#include <strstream>\n" 12018 "#endif"); 12019 12020 verifyFormat("#define MY_IMPORT <a/b>"); 12021 12022 verifyFormat("#if __has_include(<a/b>)"); 12023 verifyFormat("#if __has_include_next(<a/b>)"); 12024 verifyFormat("#define F __has_include(<a/b>)"); 12025 verifyFormat("#define F __has_include_next(<a/b>)"); 12026 12027 // Protocol buffer definition or missing "#". 12028 verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";", 12029 getLLVMStyleWithColumns(30)); 12030 12031 FormatStyle Style = getLLVMStyle(); 12032 Style.AlwaysBreakBeforeMultilineStrings = true; 12033 Style.ColumnLimit = 0; 12034 verifyFormat("#import \"abc.h\"", Style); 12035 12036 // But 'import' might also be a regular C++ namespace. 12037 verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12038 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 12039 } 12040 12041 //===----------------------------------------------------------------------===// 12042 // Error recovery tests. 12043 //===----------------------------------------------------------------------===// 12044 12045 TEST_F(FormatTest, IncompleteParameterLists) { 12046 FormatStyle NoBinPacking = getLLVMStyle(); 12047 NoBinPacking.BinPackParameters = false; 12048 verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n" 12049 " double *min_x,\n" 12050 " double *max_x,\n" 12051 " double *min_y,\n" 12052 " double *max_y,\n" 12053 " double *min_z,\n" 12054 " double *max_z, ) {}", 12055 NoBinPacking); 12056 } 12057 12058 TEST_F(FormatTest, IncorrectCodeTrailingStuff) { 12059 verifyFormat("void f() { return; }\n42"); 12060 verifyFormat("void f() {\n" 12061 " if (0)\n" 12062 " return;\n" 12063 "}\n" 12064 "42"); 12065 verifyFormat("void f() { return }\n42"); 12066 verifyFormat("void f() {\n" 12067 " if (0)\n" 12068 " return\n" 12069 "}\n" 12070 "42"); 12071 } 12072 12073 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) { 12074 EXPECT_EQ("void f() { return }", format("void f ( ) { return }")); 12075 EXPECT_EQ("void f() {\n" 12076 " if (a)\n" 12077 " return\n" 12078 "}", 12079 format("void f ( ) { if ( a ) return }")); 12080 EXPECT_EQ("namespace N {\n" 12081 "void f()\n" 12082 "}", 12083 format("namespace N { void f() }")); 12084 EXPECT_EQ("namespace N {\n" 12085 "void f() {}\n" 12086 "void g()\n" 12087 "} // namespace N", 12088 format("namespace N { void f( ) { } void g( ) }")); 12089 } 12090 12091 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) { 12092 verifyFormat("int aaaaaaaa =\n" 12093 " // Overlylongcomment\n" 12094 " b;", 12095 getLLVMStyleWithColumns(20)); 12096 verifyFormat("function(\n" 12097 " ShortArgument,\n" 12098 " LoooooooooooongArgument);\n", 12099 getLLVMStyleWithColumns(20)); 12100 } 12101 12102 TEST_F(FormatTest, IncorrectAccessSpecifier) { 12103 verifyFormat("public:"); 12104 verifyFormat("class A {\n" 12105 "public\n" 12106 " void f() {}\n" 12107 "};"); 12108 verifyFormat("public\n" 12109 "int qwerty;"); 12110 verifyFormat("public\n" 12111 "B {}"); 12112 verifyFormat("public\n" 12113 "{}"); 12114 verifyFormat("public\n" 12115 "B { int x; }"); 12116 } 12117 12118 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) { 12119 verifyFormat("{"); 12120 verifyFormat("#})"); 12121 verifyNoCrash("(/**/[:!] ?[)."); 12122 } 12123 12124 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) { 12125 // Found by oss-fuzz: 12126 // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212 12127 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp); 12128 Style.ColumnLimit = 60; 12129 verifyNoCrash( 12130 "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20" 12131 "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20" 12132 "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a", 12133 Style); 12134 } 12135 12136 TEST_F(FormatTest, IncorrectCodeDoNoWhile) { 12137 verifyFormat("do {\n}"); 12138 verifyFormat("do {\n}\n" 12139 "f();"); 12140 verifyFormat("do {\n}\n" 12141 "wheeee(fun);"); 12142 verifyFormat("do {\n" 12143 " f();\n" 12144 "}"); 12145 } 12146 12147 TEST_F(FormatTest, IncorrectCodeMissingParens) { 12148 verifyFormat("if {\n foo;\n foo();\n}"); 12149 verifyFormat("switch {\n foo;\n foo();\n}"); 12150 verifyIncompleteFormat("for {\n foo;\n foo();\n}"); 12151 verifyIncompleteFormat("ERROR: for target;"); 12152 verifyFormat("while {\n foo;\n foo();\n}"); 12153 verifyFormat("do {\n foo;\n foo();\n} while;"); 12154 } 12155 12156 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) { 12157 verifyIncompleteFormat("namespace {\n" 12158 "class Foo { Foo (\n" 12159 "};\n" 12160 "} // namespace"); 12161 } 12162 12163 TEST_F(FormatTest, IncorrectCodeErrorDetection) { 12164 EXPECT_EQ("{\n {}\n", format("{\n{\n}\n")); 12165 EXPECT_EQ("{\n {}\n", format("{\n {\n}\n")); 12166 EXPECT_EQ("{\n {}\n", format("{\n {\n }\n")); 12167 EXPECT_EQ("{\n {}\n}\n}\n", format("{\n {\n }\n }\n}\n")); 12168 12169 EXPECT_EQ("{\n" 12170 " {\n" 12171 " breakme(\n" 12172 " qwe);\n" 12173 " }\n", 12174 format("{\n" 12175 " {\n" 12176 " breakme(qwe);\n" 12177 "}\n", 12178 getLLVMStyleWithColumns(10))); 12179 } 12180 12181 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) { 12182 verifyFormat("int x = {\n" 12183 " avariable,\n" 12184 " b(alongervariable)};", 12185 getLLVMStyleWithColumns(25)); 12186 } 12187 12188 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) { 12189 verifyFormat("return (a)(b){1, 2, 3};"); 12190 } 12191 12192 TEST_F(FormatTest, LayoutCxx11BraceInitializers) { 12193 verifyFormat("vector<int> x{1, 2, 3, 4};"); 12194 verifyFormat("vector<int> x{\n" 12195 " 1,\n" 12196 " 2,\n" 12197 " 3,\n" 12198 " 4,\n" 12199 "};"); 12200 verifyFormat("vector<T> x{{}, {}, {}, {}};"); 12201 verifyFormat("f({1, 2});"); 12202 verifyFormat("auto v = Foo{-1};"); 12203 verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});"); 12204 verifyFormat("Class::Class : member{1, 2, 3} {}"); 12205 verifyFormat("new vector<int>{1, 2, 3};"); 12206 verifyFormat("new int[3]{1, 2, 3};"); 12207 verifyFormat("new int{1};"); 12208 verifyFormat("return {arg1, arg2};"); 12209 verifyFormat("return {arg1, SomeType{parameter}};"); 12210 verifyFormat("int count = set<int>{f(), g(), h()}.size();"); 12211 verifyFormat("new T{arg1, arg2};"); 12212 verifyFormat("f(MyMap[{composite, key}]);"); 12213 verifyFormat("class Class {\n" 12214 " T member = {arg1, arg2};\n" 12215 "};"); 12216 verifyFormat("vector<int> foo = {::SomeGlobalFunction()};"); 12217 verifyFormat("const struct A a = {.a = 1, .b = 2};"); 12218 verifyFormat("const struct A a = {[0] = 1, [1] = 2};"); 12219 verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");"); 12220 verifyFormat("int a = std::is_integral<int>{} + 0;"); 12221 12222 verifyFormat("int foo(int i) { return fo1{}(i); }"); 12223 verifyFormat("int foo(int i) { return fo1{}(i); }"); 12224 verifyFormat("auto i = decltype(x){};"); 12225 verifyFormat("auto i = typeof(x){};"); 12226 verifyFormat("auto i = _Atomic(x){};"); 12227 verifyFormat("std::vector<int> v = {1, 0 /* comment */};"); 12228 verifyFormat("Node n{1, Node{1000}, //\n" 12229 " 2};"); 12230 verifyFormat("Aaaa aaaaaaa{\n" 12231 " {\n" 12232 " aaaa,\n" 12233 " },\n" 12234 "};"); 12235 verifyFormat("class C : public D {\n" 12236 " SomeClass SC{2};\n" 12237 "};"); 12238 verifyFormat("class C : public A {\n" 12239 " class D : public B {\n" 12240 " void f() { int i{2}; }\n" 12241 " };\n" 12242 "};"); 12243 verifyFormat("#define A {a, a},"); 12244 // Don't confuse braced list initializers with compound statements. 12245 verifyFormat( 12246 "class A {\n" 12247 " A() : a{} {}\n" 12248 " A(int b) : b(b) {}\n" 12249 " A(int a, int b) : a(a), bs{{bs...}} { f(); }\n" 12250 " int a, b;\n" 12251 " explicit Expr(const Scalar<Result> &x) : u{Constant<Result>{x}} {}\n" 12252 " explicit Expr(Scalar<Result> &&x) : u{Constant<Result>{std::move(x)}} " 12253 "{}\n" 12254 "};"); 12255 12256 // Avoid breaking between equal sign and opening brace 12257 FormatStyle AvoidBreakingFirstArgument = getLLVMStyle(); 12258 AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200; 12259 verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n" 12260 " {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n" 12261 " {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n" 12262 " {\"ccccccccccccccccccccc\", 2}};", 12263 AvoidBreakingFirstArgument); 12264 12265 // Binpacking only if there is no trailing comma 12266 verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n" 12267 " cccccccccc, dddddddddd};", 12268 getLLVMStyleWithColumns(50)); 12269 verifyFormat("const Aaaaaa aaaaa = {\n" 12270 " aaaaaaaaaaa,\n" 12271 " bbbbbbbbbbb,\n" 12272 " ccccccccccc,\n" 12273 " ddddddddddd,\n" 12274 "};", 12275 getLLVMStyleWithColumns(50)); 12276 12277 // Cases where distinguising braced lists and blocks is hard. 12278 verifyFormat("vector<int> v{12} GUARDED_BY(mutex);"); 12279 verifyFormat("void f() {\n" 12280 " return; // comment\n" 12281 "}\n" 12282 "SomeType t;"); 12283 verifyFormat("void f() {\n" 12284 " if (a) {\n" 12285 " f();\n" 12286 " }\n" 12287 "}\n" 12288 "SomeType t;"); 12289 12290 // In combination with BinPackArguments = false. 12291 FormatStyle NoBinPacking = getLLVMStyle(); 12292 NoBinPacking.BinPackArguments = false; 12293 verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n" 12294 " bbbbb,\n" 12295 " ccccc,\n" 12296 " ddddd,\n" 12297 " eeeee,\n" 12298 " ffffff,\n" 12299 " ggggg,\n" 12300 " hhhhhh,\n" 12301 " iiiiii,\n" 12302 " jjjjjj,\n" 12303 " kkkkkk};", 12304 NoBinPacking); 12305 verifyFormat("const Aaaaaa aaaaa = {\n" 12306 " aaaaa,\n" 12307 " bbbbb,\n" 12308 " ccccc,\n" 12309 " ddddd,\n" 12310 " eeeee,\n" 12311 " ffffff,\n" 12312 " ggggg,\n" 12313 " hhhhhh,\n" 12314 " iiiiii,\n" 12315 " jjjjjj,\n" 12316 " kkkkkk,\n" 12317 "};", 12318 NoBinPacking); 12319 verifyFormat( 12320 "const Aaaaaa aaaaa = {\n" 12321 " aaaaa, bbbbb, ccccc, ddddd, eeeee, ffffff, ggggg, hhhhhh,\n" 12322 " iiiiii, jjjjjj, kkkkkk, aaaaa, bbbbb, ccccc, ddddd, eeeee,\n" 12323 " ffffff, ggggg, hhhhhh, iiiiii, jjjjjj, kkkkkk,\n" 12324 "};", 12325 NoBinPacking); 12326 12327 NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 12328 EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n" 12329 " CDDDP83848_BMCR_REGISTER,\n" 12330 " CDDDP83848_BMSR_REGISTER,\n" 12331 " CDDDP83848_RBR_REGISTER};", 12332 format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n" 12333 " CDDDP83848_BMSR_REGISTER,\n" 12334 " CDDDP83848_RBR_REGISTER};", 12335 NoBinPacking)); 12336 12337 // FIXME: The alignment of these trailing comments might be bad. Then again, 12338 // this might be utterly useless in real code. 12339 verifyFormat("Constructor::Constructor()\n" 12340 " : some_value{ //\n" 12341 " aaaaaaa, //\n" 12342 " bbbbbbb} {}"); 12343 12344 // In braced lists, the first comment is always assumed to belong to the 12345 // first element. Thus, it can be moved to the next or previous line as 12346 // appropriate. 12347 EXPECT_EQ("function({// First element:\n" 12348 " 1,\n" 12349 " // Second element:\n" 12350 " 2});", 12351 format("function({\n" 12352 " // First element:\n" 12353 " 1,\n" 12354 " // Second element:\n" 12355 " 2});")); 12356 EXPECT_EQ("std::vector<int> MyNumbers{\n" 12357 " // First element:\n" 12358 " 1,\n" 12359 " // Second element:\n" 12360 " 2};", 12361 format("std::vector<int> MyNumbers{// First element:\n" 12362 " 1,\n" 12363 " // Second element:\n" 12364 " 2};", 12365 getLLVMStyleWithColumns(30))); 12366 // A trailing comma should still lead to an enforced line break and no 12367 // binpacking. 12368 EXPECT_EQ("vector<int> SomeVector = {\n" 12369 " // aaa\n" 12370 " 1,\n" 12371 " 2,\n" 12372 "};", 12373 format("vector<int> SomeVector = { // aaa\n" 12374 " 1, 2, };")); 12375 12376 // C++11 brace initializer list l-braces should not be treated any differently 12377 // when breaking before lambda bodies is enabled 12378 FormatStyle BreakBeforeLambdaBody = getLLVMStyle(); 12379 BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 12380 BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 12381 BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true; 12382 verifyFormat( 12383 "std::runtime_error{\n" 12384 " \"Long string which will force a break onto the next line...\"};", 12385 BreakBeforeLambdaBody); 12386 12387 FormatStyle ExtraSpaces = getLLVMStyle(); 12388 ExtraSpaces.Cpp11BracedListStyle = false; 12389 ExtraSpaces.ColumnLimit = 75; 12390 verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces); 12391 verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces); 12392 verifyFormat("f({ 1, 2 });", ExtraSpaces); 12393 verifyFormat("auto v = Foo{ 1 };", ExtraSpaces); 12394 verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces); 12395 verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces); 12396 verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces); 12397 verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces); 12398 verifyFormat("return { arg1, arg2 };", ExtraSpaces); 12399 verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces); 12400 verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces); 12401 verifyFormat("new T{ arg1, arg2 };", ExtraSpaces); 12402 verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces); 12403 verifyFormat("class Class {\n" 12404 " T member = { arg1, arg2 };\n" 12405 "};", 12406 ExtraSpaces); 12407 verifyFormat( 12408 "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12409 " aaaaaaaaaaaaaaaaaaaa, aaaaa }\n" 12410 " : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 12411 " bbbbbbbbbbbbbbbbbbbb, bbbbb };", 12412 ExtraSpaces); 12413 verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces); 12414 verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });", 12415 ExtraSpaces); 12416 verifyFormat( 12417 "someFunction(OtherParam,\n" 12418 " BracedList{ // comment 1 (Forcing interesting break)\n" 12419 " param1, param2,\n" 12420 " // comment 2\n" 12421 " param3, param4 });", 12422 ExtraSpaces); 12423 verifyFormat( 12424 "std::this_thread::sleep_for(\n" 12425 " std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);", 12426 ExtraSpaces); 12427 verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n" 12428 " aaaaaaa,\n" 12429 " aaaaaaaaaa,\n" 12430 " aaaaa,\n" 12431 " aaaaaaaaaaaaaaa,\n" 12432 " aaa,\n" 12433 " aaaaaaaaaa,\n" 12434 " a,\n" 12435 " aaaaaaaaaaaaaaaaaaaaa,\n" 12436 " aaaaaaaaaaaa,\n" 12437 " aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n" 12438 " aaaaaaa,\n" 12439 " a};"); 12440 verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces); 12441 verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces); 12442 verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces); 12443 12444 // Avoid breaking between initializer/equal sign and opening brace 12445 ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200; 12446 verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n" 12447 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n" 12448 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n" 12449 " { \"ccccccccccccccccccccc\", 2 }\n" 12450 "};", 12451 ExtraSpaces); 12452 verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n" 12453 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n" 12454 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n" 12455 " { \"ccccccccccccccccccccc\", 2 }\n" 12456 "};", 12457 ExtraSpaces); 12458 12459 FormatStyle SpaceBeforeBrace = getLLVMStyle(); 12460 SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true; 12461 verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace); 12462 verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace); 12463 12464 FormatStyle SpaceBetweenBraces = getLLVMStyle(); 12465 SpaceBetweenBraces.SpacesInAngles = FormatStyle::SIAS_Always; 12466 SpaceBetweenBraces.SpacesInParentheses = true; 12467 SpaceBetweenBraces.SpacesInSquareBrackets = true; 12468 verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces); 12469 verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces); 12470 verifyFormat("vector< int > x{ // comment 1\n" 12471 " 1, 2, 3, 4 };", 12472 SpaceBetweenBraces); 12473 SpaceBetweenBraces.ColumnLimit = 20; 12474 EXPECT_EQ("vector< int > x{\n" 12475 " 1, 2, 3, 4 };", 12476 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces)); 12477 SpaceBetweenBraces.ColumnLimit = 24; 12478 EXPECT_EQ("vector< int > x{ 1, 2,\n" 12479 " 3, 4 };", 12480 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces)); 12481 EXPECT_EQ("vector< int > x{\n" 12482 " 1,\n" 12483 " 2,\n" 12484 " 3,\n" 12485 " 4,\n" 12486 "};", 12487 format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces)); 12488 verifyFormat("vector< int > x{};", SpaceBetweenBraces); 12489 SpaceBetweenBraces.SpaceInEmptyParentheses = true; 12490 verifyFormat("vector< int > x{ };", SpaceBetweenBraces); 12491 } 12492 12493 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) { 12494 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12495 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12496 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12497 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12498 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12499 " 1, 22, 333, 4444, 55555, 666666, 7777777};"); 12500 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n" 12501 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12502 " 1, 22, 333, 4444, 55555, //\n" 12503 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12504 " 1, 22, 333, 4444, 55555, 666666, 7777777};"); 12505 verifyFormat( 12506 "vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12507 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12508 " 1, 22, 333, 4444, 55555, 666666, // comment\n" 12509 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12510 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12511 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12512 " 7777777};"); 12513 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12514 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12515 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12516 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12517 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12518 " // Separating comment.\n" 12519 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12520 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12521 " // Leading comment\n" 12522 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12523 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12524 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12525 " 1, 1, 1, 1};", 12526 getLLVMStyleWithColumns(39)); 12527 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12528 " 1, 1, 1, 1};", 12529 getLLVMStyleWithColumns(38)); 12530 verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n" 12531 " 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};", 12532 getLLVMStyleWithColumns(43)); 12533 verifyFormat( 12534 "static unsigned SomeValues[10][3] = {\n" 12535 " {1, 4, 0}, {4, 9, 0}, {4, 5, 9}, {8, 5, 4}, {1, 8, 4},\n" 12536 " {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};"); 12537 verifyFormat("static auto fields = new vector<string>{\n" 12538 " \"aaaaaaaaaaaaa\",\n" 12539 " \"aaaaaaaaaaaaa\",\n" 12540 " \"aaaaaaaaaaaa\",\n" 12541 " \"aaaaaaaaaaaaaa\",\n" 12542 " \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n" 12543 " \"aaaaaaaaaaaa\",\n" 12544 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n" 12545 "};"); 12546 verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};"); 12547 verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n" 12548 " 2, bbbbbbbbbbbbbbbbbbbbbb,\n" 12549 " 3, cccccccccccccccccccccc};", 12550 getLLVMStyleWithColumns(60)); 12551 12552 // Trailing commas. 12553 verifyFormat("vector<int> x = {\n" 12554 " 1, 1, 1, 1, 1, 1, 1, 1,\n" 12555 "};", 12556 getLLVMStyleWithColumns(39)); 12557 verifyFormat("vector<int> x = {\n" 12558 " 1, 1, 1, 1, 1, 1, 1, 1, //\n" 12559 "};", 12560 getLLVMStyleWithColumns(39)); 12561 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12562 " 1, 1, 1, 1,\n" 12563 " /**/ /**/};", 12564 getLLVMStyleWithColumns(39)); 12565 12566 // Trailing comment in the first line. 12567 verifyFormat("vector<int> iiiiiiiiiiiiiii = { //\n" 12568 " 1111111111, 2222222222, 33333333333, 4444444444, //\n" 12569 " 111111111, 222222222, 3333333333, 444444444, //\n" 12570 " 11111111, 22222222, 333333333, 44444444};"); 12571 // Trailing comment in the last line. 12572 verifyFormat("int aaaaa[] = {\n" 12573 " 1, 2, 3, // comment\n" 12574 " 4, 5, 6 // comment\n" 12575 "};"); 12576 12577 // With nested lists, we should either format one item per line or all nested 12578 // lists one on line. 12579 // FIXME: For some nested lists, we can do better. 12580 verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n" 12581 " {aaaaaaaaaaaaaaaaaaa},\n" 12582 " {aaaaaaaaaaaaaaaaaaaaa},\n" 12583 " {aaaaaaaaaaaaaaaaa}};", 12584 getLLVMStyleWithColumns(60)); 12585 verifyFormat( 12586 "SomeStruct my_struct_array = {\n" 12587 " {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n" 12588 " aaaaaaaaaaaaa, aaaaaaa, aaa},\n" 12589 " {aaa, aaa},\n" 12590 " {aaa, aaa},\n" 12591 " {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n" 12592 " {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n" 12593 " aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};"); 12594 12595 // No column layout should be used here. 12596 verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n" 12597 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};"); 12598 12599 verifyNoCrash("a<,"); 12600 12601 // No braced initializer here. 12602 verifyFormat("void f() {\n" 12603 " struct Dummy {};\n" 12604 " f(v);\n" 12605 "}"); 12606 12607 // Long lists should be formatted in columns even if they are nested. 12608 verifyFormat( 12609 "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12610 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12611 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12612 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12613 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12614 " 1, 22, 333, 4444, 55555, 666666, 7777777});"); 12615 12616 // Allow "single-column" layout even if that violates the column limit. There 12617 // isn't going to be a better way. 12618 verifyFormat("std::vector<int> a = {\n" 12619 " aaaaaaaa,\n" 12620 " aaaaaaaa,\n" 12621 " aaaaaaaa,\n" 12622 " aaaaaaaa,\n" 12623 " aaaaaaaaaa,\n" 12624 " aaaaaaaa,\n" 12625 " aaaaaaaaaaaaaaaaaaaaaaaaaaa};", 12626 getLLVMStyleWithColumns(30)); 12627 verifyFormat("vector<int> aaaa = {\n" 12628 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12629 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12630 " aaaaaa.aaaaaaa,\n" 12631 " aaaaaa.aaaaaaa,\n" 12632 " aaaaaa.aaaaaaa,\n" 12633 " aaaaaa.aaaaaaa,\n" 12634 "};"); 12635 12636 // Don't create hanging lists. 12637 verifyFormat("someFunction(Param, {List1, List2,\n" 12638 " List3});", 12639 getLLVMStyleWithColumns(35)); 12640 verifyFormat("someFunction(Param, Param,\n" 12641 " {List1, List2,\n" 12642 " List3});", 12643 getLLVMStyleWithColumns(35)); 12644 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n" 12645 " aaaaaaaaaaaaaaaaaaaaaaa);"); 12646 } 12647 12648 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) { 12649 FormatStyle DoNotMerge = getLLVMStyle(); 12650 DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12651 12652 verifyFormat("void f() { return 42; }"); 12653 verifyFormat("void f() {\n" 12654 " return 42;\n" 12655 "}", 12656 DoNotMerge); 12657 verifyFormat("void f() {\n" 12658 " // Comment\n" 12659 "}"); 12660 verifyFormat("{\n" 12661 "#error {\n" 12662 " int a;\n" 12663 "}"); 12664 verifyFormat("{\n" 12665 " int a;\n" 12666 "#error {\n" 12667 "}"); 12668 verifyFormat("void f() {} // comment"); 12669 verifyFormat("void f() { int a; } // comment"); 12670 verifyFormat("void f() {\n" 12671 "} // comment", 12672 DoNotMerge); 12673 verifyFormat("void f() {\n" 12674 " int a;\n" 12675 "} // comment", 12676 DoNotMerge); 12677 verifyFormat("void f() {\n" 12678 "} // comment", 12679 getLLVMStyleWithColumns(15)); 12680 12681 verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23)); 12682 verifyFormat("void f() {\n return 42;\n}", getLLVMStyleWithColumns(22)); 12683 12684 verifyFormat("void f() {}", getLLVMStyleWithColumns(11)); 12685 verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10)); 12686 verifyFormat("class C {\n" 12687 " C()\n" 12688 " : iiiiiiii(nullptr),\n" 12689 " kkkkkkk(nullptr),\n" 12690 " mmmmmmm(nullptr),\n" 12691 " nnnnnnn(nullptr) {}\n" 12692 "};", 12693 getGoogleStyle()); 12694 12695 FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0); 12696 EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit)); 12697 EXPECT_EQ("class C {\n" 12698 " A() : b(0) {}\n" 12699 "};", 12700 format("class C{A():b(0){}};", NoColumnLimit)); 12701 EXPECT_EQ("A()\n" 12702 " : b(0) {\n" 12703 "}", 12704 format("A()\n:b(0)\n{\n}", NoColumnLimit)); 12705 12706 FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit; 12707 DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine = 12708 FormatStyle::SFS_None; 12709 EXPECT_EQ("A()\n" 12710 " : b(0) {\n" 12711 "}", 12712 format("A():b(0){}", DoNotMergeNoColumnLimit)); 12713 EXPECT_EQ("A()\n" 12714 " : b(0) {\n" 12715 "}", 12716 format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit)); 12717 12718 verifyFormat("#define A \\\n" 12719 " void f() { \\\n" 12720 " int i; \\\n" 12721 " }", 12722 getLLVMStyleWithColumns(20)); 12723 verifyFormat("#define A \\\n" 12724 " void f() { int i; }", 12725 getLLVMStyleWithColumns(21)); 12726 verifyFormat("#define A \\\n" 12727 " void f() { \\\n" 12728 " int i; \\\n" 12729 " } \\\n" 12730 " int j;", 12731 getLLVMStyleWithColumns(22)); 12732 verifyFormat("#define A \\\n" 12733 " void f() { int i; } \\\n" 12734 " int j;", 12735 getLLVMStyleWithColumns(23)); 12736 } 12737 12738 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) { 12739 FormatStyle MergeEmptyOnly = getLLVMStyle(); 12740 MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 12741 verifyFormat("class C {\n" 12742 " int f() {}\n" 12743 "};", 12744 MergeEmptyOnly); 12745 verifyFormat("class C {\n" 12746 " int f() {\n" 12747 " return 42;\n" 12748 " }\n" 12749 "};", 12750 MergeEmptyOnly); 12751 verifyFormat("int f() {}", MergeEmptyOnly); 12752 verifyFormat("int f() {\n" 12753 " return 42;\n" 12754 "}", 12755 MergeEmptyOnly); 12756 12757 // Also verify behavior when BraceWrapping.AfterFunction = true 12758 MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12759 MergeEmptyOnly.BraceWrapping.AfterFunction = true; 12760 verifyFormat("int f() {}", MergeEmptyOnly); 12761 verifyFormat("class C {\n" 12762 " int f() {}\n" 12763 "};", 12764 MergeEmptyOnly); 12765 } 12766 12767 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) { 12768 FormatStyle MergeInlineOnly = getLLVMStyle(); 12769 MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 12770 verifyFormat("class C {\n" 12771 " int f() { return 42; }\n" 12772 "};", 12773 MergeInlineOnly); 12774 verifyFormat("int f() {\n" 12775 " return 42;\n" 12776 "}", 12777 MergeInlineOnly); 12778 12779 // SFS_Inline implies SFS_Empty 12780 verifyFormat("class C {\n" 12781 " int f() {}\n" 12782 "};", 12783 MergeInlineOnly); 12784 verifyFormat("int f() {}", MergeInlineOnly); 12785 // https://llvm.org/PR54147 12786 verifyFormat("auto lambda = []() {\n" 12787 " // comment\n" 12788 " f();\n" 12789 " g();\n" 12790 "};", 12791 MergeInlineOnly); 12792 12793 verifyFormat("class C {\n" 12794 "#ifdef A\n" 12795 " int f() { return 42; }\n" 12796 "#endif\n" 12797 "};", 12798 MergeInlineOnly); 12799 12800 verifyFormat("struct S {\n" 12801 "// comment\n" 12802 "#ifdef FOO\n" 12803 " int foo() { bar(); }\n" 12804 "#endif\n" 12805 "};", 12806 MergeInlineOnly); 12807 12808 // Also verify behavior when BraceWrapping.AfterFunction = true 12809 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12810 MergeInlineOnly.BraceWrapping.AfterFunction = true; 12811 verifyFormat("class C {\n" 12812 " int f() { return 42; }\n" 12813 "};", 12814 MergeInlineOnly); 12815 verifyFormat("int f()\n" 12816 "{\n" 12817 " return 42;\n" 12818 "}", 12819 MergeInlineOnly); 12820 12821 // SFS_Inline implies SFS_Empty 12822 verifyFormat("int f() {}", MergeInlineOnly); 12823 verifyFormat("class C {\n" 12824 " int f() {}\n" 12825 "};", 12826 MergeInlineOnly); 12827 12828 MergeInlineOnly.BraceWrapping.AfterClass = true; 12829 MergeInlineOnly.BraceWrapping.AfterStruct = true; 12830 verifyFormat("class C\n" 12831 "{\n" 12832 " int f() { return 42; }\n" 12833 "};", 12834 MergeInlineOnly); 12835 verifyFormat("struct C\n" 12836 "{\n" 12837 " int f() { return 42; }\n" 12838 "};", 12839 MergeInlineOnly); 12840 verifyFormat("int f()\n" 12841 "{\n" 12842 " return 42;\n" 12843 "}", 12844 MergeInlineOnly); 12845 verifyFormat("int f() {}", MergeInlineOnly); 12846 verifyFormat("class C\n" 12847 "{\n" 12848 " int f() { return 42; }\n" 12849 "};", 12850 MergeInlineOnly); 12851 verifyFormat("struct C\n" 12852 "{\n" 12853 " int f() { return 42; }\n" 12854 "};", 12855 MergeInlineOnly); 12856 verifyFormat("struct C\n" 12857 "// comment\n" 12858 "/* comment */\n" 12859 "// comment\n" 12860 "{\n" 12861 " int f() { return 42; }\n" 12862 "};", 12863 MergeInlineOnly); 12864 verifyFormat("/* comment */ struct C\n" 12865 "{\n" 12866 " int f() { return 42; }\n" 12867 "};", 12868 MergeInlineOnly); 12869 } 12870 12871 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) { 12872 FormatStyle MergeInlineOnly = getLLVMStyle(); 12873 MergeInlineOnly.AllowShortFunctionsOnASingleLine = 12874 FormatStyle::SFS_InlineOnly; 12875 verifyFormat("class C {\n" 12876 " int f() { return 42; }\n" 12877 "};", 12878 MergeInlineOnly); 12879 verifyFormat("int f() {\n" 12880 " return 42;\n" 12881 "}", 12882 MergeInlineOnly); 12883 12884 // SFS_InlineOnly does not imply SFS_Empty 12885 verifyFormat("class C {\n" 12886 " int f() {}\n" 12887 "};", 12888 MergeInlineOnly); 12889 verifyFormat("int f() {\n" 12890 "}", 12891 MergeInlineOnly); 12892 12893 // Also verify behavior when BraceWrapping.AfterFunction = true 12894 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12895 MergeInlineOnly.BraceWrapping.AfterFunction = true; 12896 verifyFormat("class C {\n" 12897 " int f() { return 42; }\n" 12898 "};", 12899 MergeInlineOnly); 12900 verifyFormat("int f()\n" 12901 "{\n" 12902 " return 42;\n" 12903 "}", 12904 MergeInlineOnly); 12905 12906 // SFS_InlineOnly does not imply SFS_Empty 12907 verifyFormat("int f()\n" 12908 "{\n" 12909 "}", 12910 MergeInlineOnly); 12911 verifyFormat("class C {\n" 12912 " int f() {}\n" 12913 "};", 12914 MergeInlineOnly); 12915 } 12916 12917 TEST_F(FormatTest, SplitEmptyFunction) { 12918 FormatStyle Style = getLLVMStyleWithColumns(40); 12919 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12920 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12921 Style.BraceWrapping.AfterFunction = true; 12922 Style.BraceWrapping.SplitEmptyFunction = false; 12923 12924 verifyFormat("int f()\n" 12925 "{}", 12926 Style); 12927 verifyFormat("int f()\n" 12928 "{\n" 12929 " return 42;\n" 12930 "}", 12931 Style); 12932 verifyFormat("int f()\n" 12933 "{\n" 12934 " // some comment\n" 12935 "}", 12936 Style); 12937 12938 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 12939 verifyFormat("int f() {}", Style); 12940 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12941 "{}", 12942 Style); 12943 verifyFormat("int f()\n" 12944 "{\n" 12945 " return 0;\n" 12946 "}", 12947 Style); 12948 12949 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 12950 verifyFormat("class Foo {\n" 12951 " int f() {}\n" 12952 "};\n", 12953 Style); 12954 verifyFormat("class Foo {\n" 12955 " int f() { return 0; }\n" 12956 "};\n", 12957 Style); 12958 verifyFormat("class Foo {\n" 12959 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12960 " {}\n" 12961 "};\n", 12962 Style); 12963 verifyFormat("class Foo {\n" 12964 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12965 " {\n" 12966 " return 0;\n" 12967 " }\n" 12968 "};\n", 12969 Style); 12970 12971 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 12972 verifyFormat("int f() {}", Style); 12973 verifyFormat("int f() { return 0; }", Style); 12974 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12975 "{}", 12976 Style); 12977 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12978 "{\n" 12979 " return 0;\n" 12980 "}", 12981 Style); 12982 } 12983 12984 TEST_F(FormatTest, SplitEmptyFunctionButNotRecord) { 12985 FormatStyle Style = getLLVMStyleWithColumns(40); 12986 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12987 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12988 Style.BraceWrapping.AfterFunction = true; 12989 Style.BraceWrapping.SplitEmptyFunction = true; 12990 Style.BraceWrapping.SplitEmptyRecord = false; 12991 12992 verifyFormat("class C {};", Style); 12993 verifyFormat("struct C {};", Style); 12994 verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12995 " int bbbbbbbbbbbbbbbbbbbbbbbb)\n" 12996 "{\n" 12997 "}", 12998 Style); 12999 verifyFormat("class C {\n" 13000 " C()\n" 13001 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa(),\n" 13002 " bbbbbbbbbbbbbbbbbbb()\n" 13003 " {\n" 13004 " }\n" 13005 " void\n" 13006 " m(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 13007 " int bbbbbbbbbbbbbbbbbbbbbbbb)\n" 13008 " {\n" 13009 " }\n" 13010 "};", 13011 Style); 13012 } 13013 13014 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) { 13015 FormatStyle Style = getLLVMStyle(); 13016 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 13017 verifyFormat("#ifdef A\n" 13018 "int f() {}\n" 13019 "#else\n" 13020 "int g() {}\n" 13021 "#endif", 13022 Style); 13023 } 13024 13025 TEST_F(FormatTest, SplitEmptyClass) { 13026 FormatStyle Style = getLLVMStyle(); 13027 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13028 Style.BraceWrapping.AfterClass = true; 13029 Style.BraceWrapping.SplitEmptyRecord = false; 13030 13031 verifyFormat("class Foo\n" 13032 "{};", 13033 Style); 13034 verifyFormat("/* something */ class Foo\n" 13035 "{};", 13036 Style); 13037 verifyFormat("template <typename X> class Foo\n" 13038 "{};", 13039 Style); 13040 verifyFormat("class Foo\n" 13041 "{\n" 13042 " Foo();\n" 13043 "};", 13044 Style); 13045 verifyFormat("typedef class Foo\n" 13046 "{\n" 13047 "} Foo_t;", 13048 Style); 13049 13050 Style.BraceWrapping.SplitEmptyRecord = true; 13051 Style.BraceWrapping.AfterStruct = true; 13052 verifyFormat("class rep\n" 13053 "{\n" 13054 "};", 13055 Style); 13056 verifyFormat("struct rep\n" 13057 "{\n" 13058 "};", 13059 Style); 13060 verifyFormat("template <typename T> class rep\n" 13061 "{\n" 13062 "};", 13063 Style); 13064 verifyFormat("template <typename T> struct rep\n" 13065 "{\n" 13066 "};", 13067 Style); 13068 verifyFormat("class rep\n" 13069 "{\n" 13070 " int x;\n" 13071 "};", 13072 Style); 13073 verifyFormat("struct rep\n" 13074 "{\n" 13075 " int x;\n" 13076 "};", 13077 Style); 13078 verifyFormat("template <typename T> class rep\n" 13079 "{\n" 13080 " int x;\n" 13081 "};", 13082 Style); 13083 verifyFormat("template <typename T> struct rep\n" 13084 "{\n" 13085 " int x;\n" 13086 "};", 13087 Style); 13088 verifyFormat("template <typename T> class rep // Foo\n" 13089 "{\n" 13090 " int x;\n" 13091 "};", 13092 Style); 13093 verifyFormat("template <typename T> struct rep // Bar\n" 13094 "{\n" 13095 " int x;\n" 13096 "};", 13097 Style); 13098 13099 verifyFormat("template <typename T> class rep<T>\n" 13100 "{\n" 13101 " int x;\n" 13102 "};", 13103 Style); 13104 13105 verifyFormat("template <typename T> class rep<std::complex<T>>\n" 13106 "{\n" 13107 " int x;\n" 13108 "};", 13109 Style); 13110 verifyFormat("template <typename T> class rep<std::complex<T>>\n" 13111 "{\n" 13112 "};", 13113 Style); 13114 13115 verifyFormat("#include \"stdint.h\"\n" 13116 "namespace rep {}", 13117 Style); 13118 verifyFormat("#include <stdint.h>\n" 13119 "namespace rep {}", 13120 Style); 13121 verifyFormat("#include <stdint.h>\n" 13122 "namespace rep {}", 13123 "#include <stdint.h>\n" 13124 "namespace rep {\n" 13125 "\n" 13126 "\n" 13127 "}", 13128 Style); 13129 } 13130 13131 TEST_F(FormatTest, SplitEmptyStruct) { 13132 FormatStyle Style = getLLVMStyle(); 13133 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13134 Style.BraceWrapping.AfterStruct = true; 13135 Style.BraceWrapping.SplitEmptyRecord = false; 13136 13137 verifyFormat("struct Foo\n" 13138 "{};", 13139 Style); 13140 verifyFormat("/* something */ struct Foo\n" 13141 "{};", 13142 Style); 13143 verifyFormat("template <typename X> struct Foo\n" 13144 "{};", 13145 Style); 13146 verifyFormat("struct Foo\n" 13147 "{\n" 13148 " Foo();\n" 13149 "};", 13150 Style); 13151 verifyFormat("typedef struct Foo\n" 13152 "{\n" 13153 "} Foo_t;", 13154 Style); 13155 // typedef struct Bar {} Bar_t; 13156 } 13157 13158 TEST_F(FormatTest, SplitEmptyUnion) { 13159 FormatStyle Style = getLLVMStyle(); 13160 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13161 Style.BraceWrapping.AfterUnion = true; 13162 Style.BraceWrapping.SplitEmptyRecord = false; 13163 13164 verifyFormat("union Foo\n" 13165 "{};", 13166 Style); 13167 verifyFormat("/* something */ union Foo\n" 13168 "{};", 13169 Style); 13170 verifyFormat("union Foo\n" 13171 "{\n" 13172 " A,\n" 13173 "};", 13174 Style); 13175 verifyFormat("typedef union Foo\n" 13176 "{\n" 13177 "} Foo_t;", 13178 Style); 13179 } 13180 13181 TEST_F(FormatTest, SplitEmptyNamespace) { 13182 FormatStyle Style = getLLVMStyle(); 13183 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13184 Style.BraceWrapping.AfterNamespace = true; 13185 Style.BraceWrapping.SplitEmptyNamespace = false; 13186 13187 verifyFormat("namespace Foo\n" 13188 "{};", 13189 Style); 13190 verifyFormat("/* something */ namespace Foo\n" 13191 "{};", 13192 Style); 13193 verifyFormat("inline namespace Foo\n" 13194 "{};", 13195 Style); 13196 verifyFormat("/* something */ inline namespace Foo\n" 13197 "{};", 13198 Style); 13199 verifyFormat("export namespace Foo\n" 13200 "{};", 13201 Style); 13202 verifyFormat("namespace Foo\n" 13203 "{\n" 13204 "void Bar();\n" 13205 "};", 13206 Style); 13207 } 13208 13209 TEST_F(FormatTest, NeverMergeShortRecords) { 13210 FormatStyle Style = getLLVMStyle(); 13211 13212 verifyFormat("class Foo {\n" 13213 " Foo();\n" 13214 "};", 13215 Style); 13216 verifyFormat("typedef class Foo {\n" 13217 " Foo();\n" 13218 "} Foo_t;", 13219 Style); 13220 verifyFormat("struct Foo {\n" 13221 " Foo();\n" 13222 "};", 13223 Style); 13224 verifyFormat("typedef struct Foo {\n" 13225 " Foo();\n" 13226 "} Foo_t;", 13227 Style); 13228 verifyFormat("union Foo {\n" 13229 " A,\n" 13230 "};", 13231 Style); 13232 verifyFormat("typedef union Foo {\n" 13233 " A,\n" 13234 "} Foo_t;", 13235 Style); 13236 verifyFormat("namespace Foo {\n" 13237 "void Bar();\n" 13238 "};", 13239 Style); 13240 13241 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13242 Style.BraceWrapping.AfterClass = true; 13243 Style.BraceWrapping.AfterStruct = true; 13244 Style.BraceWrapping.AfterUnion = true; 13245 Style.BraceWrapping.AfterNamespace = true; 13246 verifyFormat("class Foo\n" 13247 "{\n" 13248 " Foo();\n" 13249 "};", 13250 Style); 13251 verifyFormat("typedef class Foo\n" 13252 "{\n" 13253 " Foo();\n" 13254 "} Foo_t;", 13255 Style); 13256 verifyFormat("struct Foo\n" 13257 "{\n" 13258 " Foo();\n" 13259 "};", 13260 Style); 13261 verifyFormat("typedef struct Foo\n" 13262 "{\n" 13263 " Foo();\n" 13264 "} Foo_t;", 13265 Style); 13266 verifyFormat("union Foo\n" 13267 "{\n" 13268 " A,\n" 13269 "};", 13270 Style); 13271 verifyFormat("typedef union Foo\n" 13272 "{\n" 13273 " A,\n" 13274 "} Foo_t;", 13275 Style); 13276 verifyFormat("namespace Foo\n" 13277 "{\n" 13278 "void Bar();\n" 13279 "};", 13280 Style); 13281 } 13282 13283 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) { 13284 // Elaborate type variable declarations. 13285 verifyFormat("struct foo a = {bar};\nint n;"); 13286 verifyFormat("class foo a = {bar};\nint n;"); 13287 verifyFormat("union foo a = {bar};\nint n;"); 13288 13289 // Elaborate types inside function definitions. 13290 verifyFormat("struct foo f() {}\nint n;"); 13291 verifyFormat("class foo f() {}\nint n;"); 13292 verifyFormat("union foo f() {}\nint n;"); 13293 13294 // Templates. 13295 verifyFormat("template <class X> void f() {}\nint n;"); 13296 verifyFormat("template <struct X> void f() {}\nint n;"); 13297 verifyFormat("template <union X> void f() {}\nint n;"); 13298 13299 // Actual definitions... 13300 verifyFormat("struct {\n} n;"); 13301 verifyFormat( 13302 "template <template <class T, class Y>, class Z> class X {\n} n;"); 13303 verifyFormat("union Z {\n int n;\n} x;"); 13304 verifyFormat("class MACRO Z {\n} n;"); 13305 verifyFormat("class MACRO(X) Z {\n} n;"); 13306 verifyFormat("class __attribute__(X) Z {\n} n;"); 13307 verifyFormat("class __declspec(X) Z {\n} n;"); 13308 verifyFormat("class A##B##C {\n} n;"); 13309 verifyFormat("class alignas(16) Z {\n} n;"); 13310 verifyFormat("class MACRO(X) alignas(16) Z {\n} n;"); 13311 verifyFormat("class MACROA MACRO(X) Z {\n} n;"); 13312 13313 // Redefinition from nested context: 13314 verifyFormat("class A::B::C {\n} n;"); 13315 13316 // Template definitions. 13317 verifyFormat( 13318 "template <typename F>\n" 13319 "Matcher(const Matcher<F> &Other,\n" 13320 " typename enable_if_c<is_base_of<F, T>::value &&\n" 13321 " !is_same<F, T>::value>::type * = 0)\n" 13322 " : Implementation(new ImplicitCastMatcher<F>(Other)) {}"); 13323 13324 // FIXME: This is still incorrectly handled at the formatter side. 13325 verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};"); 13326 verifyFormat("int i = SomeFunction(a<b, a> b);"); 13327 13328 // FIXME: 13329 // This now gets parsed incorrectly as class definition. 13330 // verifyFormat("class A<int> f() {\n}\nint n;"); 13331 13332 // Elaborate types where incorrectly parsing the structural element would 13333 // break the indent. 13334 verifyFormat("if (true)\n" 13335 " class X x;\n" 13336 "else\n" 13337 " f();\n"); 13338 13339 // This is simply incomplete. Formatting is not important, but must not crash. 13340 verifyFormat("class A:"); 13341 } 13342 13343 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) { 13344 EXPECT_EQ("#error Leave all white!!!!! space* alone!\n", 13345 format("#error Leave all white!!!!! space* alone!\n")); 13346 EXPECT_EQ( 13347 "#warning Leave all white!!!!! space* alone!\n", 13348 format("#warning Leave all white!!!!! space* alone!\n")); 13349 EXPECT_EQ("#error 1", format(" # error 1")); 13350 EXPECT_EQ("#warning 1", format(" # warning 1")); 13351 } 13352 13353 TEST_F(FormatTest, FormatHashIfExpressions) { 13354 verifyFormat("#if AAAA && BBBB"); 13355 verifyFormat("#if (AAAA && BBBB)"); 13356 verifyFormat("#elif (AAAA && BBBB)"); 13357 // FIXME: Come up with a better indentation for #elif. 13358 verifyFormat( 13359 "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) && \\\n" 13360 " defined(BBBBBBBB)\n" 13361 "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) && \\\n" 13362 " defined(BBBBBBBB)\n" 13363 "#endif", 13364 getLLVMStyleWithColumns(65)); 13365 } 13366 13367 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) { 13368 FormatStyle AllowsMergedIf = getGoogleStyle(); 13369 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 13370 FormatStyle::SIS_WithoutElse; 13371 verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf); 13372 verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf); 13373 verifyFormat("if (true)\n#error E\n return 42;", AllowsMergedIf); 13374 EXPECT_EQ("if (true) return 42;", 13375 format("if (true)\nreturn 42;", AllowsMergedIf)); 13376 FormatStyle ShortMergedIf = AllowsMergedIf; 13377 ShortMergedIf.ColumnLimit = 25; 13378 verifyFormat("#define A \\\n" 13379 " if (true) return 42;", 13380 ShortMergedIf); 13381 verifyFormat("#define A \\\n" 13382 " f(); \\\n" 13383 " if (true)\n" 13384 "#define B", 13385 ShortMergedIf); 13386 verifyFormat("#define A \\\n" 13387 " f(); \\\n" 13388 " if (true)\n" 13389 "g();", 13390 ShortMergedIf); 13391 verifyFormat("{\n" 13392 "#ifdef A\n" 13393 " // Comment\n" 13394 " if (true) continue;\n" 13395 "#endif\n" 13396 " // Comment\n" 13397 " if (true) continue;\n" 13398 "}", 13399 ShortMergedIf); 13400 ShortMergedIf.ColumnLimit = 33; 13401 verifyFormat("#define A \\\n" 13402 " if constexpr (true) return 42;", 13403 ShortMergedIf); 13404 verifyFormat("#define A \\\n" 13405 " if CONSTEXPR (true) return 42;", 13406 ShortMergedIf); 13407 ShortMergedIf.ColumnLimit = 29; 13408 verifyFormat("#define A \\\n" 13409 " if (aaaaaaaaaa) return 1; \\\n" 13410 " return 2;", 13411 ShortMergedIf); 13412 ShortMergedIf.ColumnLimit = 28; 13413 verifyFormat("#define A \\\n" 13414 " if (aaaaaaaaaa) \\\n" 13415 " return 1; \\\n" 13416 " return 2;", 13417 ShortMergedIf); 13418 verifyFormat("#define A \\\n" 13419 " if constexpr (aaaaaaa) \\\n" 13420 " return 1; \\\n" 13421 " return 2;", 13422 ShortMergedIf); 13423 verifyFormat("#define A \\\n" 13424 " if CONSTEXPR (aaaaaaa) \\\n" 13425 " return 1; \\\n" 13426 " return 2;", 13427 ShortMergedIf); 13428 13429 verifyFormat("//\n" 13430 "#define a \\\n" 13431 " if \\\n" 13432 " 0", 13433 getChromiumStyle(FormatStyle::LK_Cpp)); 13434 } 13435 13436 TEST_F(FormatTest, FormatStarDependingOnContext) { 13437 verifyFormat("void f(int *a);"); 13438 verifyFormat("void f() { f(fint * b); }"); 13439 verifyFormat("class A {\n void f(int *a);\n};"); 13440 verifyFormat("class A {\n int *a;\n};"); 13441 verifyFormat("namespace a {\n" 13442 "namespace b {\n" 13443 "class A {\n" 13444 " void f() {}\n" 13445 " int *a;\n" 13446 "};\n" 13447 "} // namespace b\n" 13448 "} // namespace a"); 13449 } 13450 13451 TEST_F(FormatTest, SpecialTokensAtEndOfLine) { 13452 verifyFormat("while"); 13453 verifyFormat("operator"); 13454 } 13455 13456 TEST_F(FormatTest, SkipsDeeplyNestedLines) { 13457 // This code would be painfully slow to format if we didn't skip it. 13458 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 13459 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13460 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13461 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13462 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13463 "A(1, 1)\n" 13464 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x 13465 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13466 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13467 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13468 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13469 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13470 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13471 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13472 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13473 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n"); 13474 // Deeply nested part is untouched, rest is formatted. 13475 EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n", 13476 format(std::string("int i;\n") + Code + "int j;\n", 13477 getLLVMStyle(), SC_ExpectIncomplete)); 13478 } 13479 13480 //===----------------------------------------------------------------------===// 13481 // Objective-C tests. 13482 //===----------------------------------------------------------------------===// 13483 13484 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) { 13485 verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;"); 13486 EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;", 13487 format("-(NSUInteger)indexOfObject:(id)anObject;")); 13488 EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;")); 13489 EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;")); 13490 EXPECT_EQ("- (NSInteger)Method3:(id)anObject;", 13491 format("-(NSInteger)Method3:(id)anObject;")); 13492 EXPECT_EQ("- (NSInteger)Method4:(id)anObject;", 13493 format("-(NSInteger)Method4:(id)anObject;")); 13494 EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;", 13495 format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;")); 13496 EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;", 13497 format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;")); 13498 EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject " 13499 "forAllCells:(BOOL)flag;", 13500 format("- (void)sendAction:(SEL)aSelector to:(id)anObject " 13501 "forAllCells:(BOOL)flag;")); 13502 13503 // Very long objectiveC method declaration. 13504 verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n" 13505 " (SoooooooooooooooooooooomeType *)bbbbbbbbbb;"); 13506 verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n" 13507 " inRange:(NSRange)range\n" 13508 " outRange:(NSRange)out_range\n" 13509 " outRange1:(NSRange)out_range1\n" 13510 " outRange2:(NSRange)out_range2\n" 13511 " outRange3:(NSRange)out_range3\n" 13512 " outRange4:(NSRange)out_range4\n" 13513 " outRange5:(NSRange)out_range5\n" 13514 " outRange6:(NSRange)out_range6\n" 13515 " outRange7:(NSRange)out_range7\n" 13516 " outRange8:(NSRange)out_range8\n" 13517 " outRange9:(NSRange)out_range9;"); 13518 13519 // When the function name has to be wrapped. 13520 FormatStyle Style = getLLVMStyle(); 13521 // ObjC ignores IndentWrappedFunctionNames when wrapping methods 13522 // and always indents instead. 13523 Style.IndentWrappedFunctionNames = false; 13524 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n" 13525 " veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n" 13526 " anotherName:(NSString)bbbbbbbbbbbbbb {\n" 13527 "}", 13528 Style); 13529 Style.IndentWrappedFunctionNames = true; 13530 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n" 13531 " veryLooooooooooongName:(NSString)cccccccccccccc\n" 13532 " anotherName:(NSString)dddddddddddddd {\n" 13533 "}", 13534 Style); 13535 13536 verifyFormat("- (int)sum:(vector<int>)numbers;"); 13537 verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;"); 13538 // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC 13539 // protocol lists (but not for template classes): 13540 // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;"); 13541 13542 verifyFormat("- (int (*)())foo:(int (*)())f;"); 13543 verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;"); 13544 13545 // If there's no return type (very rare in practice!), LLVM and Google style 13546 // agree. 13547 verifyFormat("- foo;"); 13548 verifyFormat("- foo:(int)f;"); 13549 verifyGoogleFormat("- foo:(int)foo;"); 13550 } 13551 13552 TEST_F(FormatTest, BreaksStringLiterals) { 13553 EXPECT_EQ("\"some text \"\n" 13554 "\"other\";", 13555 format("\"some text other\";", getLLVMStyleWithColumns(12))); 13556 EXPECT_EQ("\"some text \"\n" 13557 "\"other\";", 13558 format("\\\n\"some text other\";", getLLVMStyleWithColumns(12))); 13559 EXPECT_EQ( 13560 "#define A \\\n" 13561 " \"some \" \\\n" 13562 " \"text \" \\\n" 13563 " \"other\";", 13564 format("#define A \"some text other\";", getLLVMStyleWithColumns(12))); 13565 EXPECT_EQ( 13566 "#define A \\\n" 13567 " \"so \" \\\n" 13568 " \"text \" \\\n" 13569 " \"other\";", 13570 format("#define A \"so text other\";", getLLVMStyleWithColumns(12))); 13571 13572 EXPECT_EQ("\"some text\"", 13573 format("\"some text\"", getLLVMStyleWithColumns(1))); 13574 EXPECT_EQ("\"some text\"", 13575 format("\"some text\"", getLLVMStyleWithColumns(11))); 13576 EXPECT_EQ("\"some \"\n" 13577 "\"text\"", 13578 format("\"some text\"", getLLVMStyleWithColumns(10))); 13579 EXPECT_EQ("\"some \"\n" 13580 "\"text\"", 13581 format("\"some text\"", getLLVMStyleWithColumns(7))); 13582 EXPECT_EQ("\"some\"\n" 13583 "\" tex\"\n" 13584 "\"t\"", 13585 format("\"some text\"", getLLVMStyleWithColumns(6))); 13586 EXPECT_EQ("\"some\"\n" 13587 "\" tex\"\n" 13588 "\" and\"", 13589 format("\"some tex and\"", getLLVMStyleWithColumns(6))); 13590 EXPECT_EQ("\"some\"\n" 13591 "\"/tex\"\n" 13592 "\"/and\"", 13593 format("\"some/tex/and\"", getLLVMStyleWithColumns(6))); 13594 13595 EXPECT_EQ("variable =\n" 13596 " \"long string \"\n" 13597 " \"literal\";", 13598 format("variable = \"long string literal\";", 13599 getLLVMStyleWithColumns(20))); 13600 13601 EXPECT_EQ("variable = f(\n" 13602 " \"long string \"\n" 13603 " \"literal\",\n" 13604 " short,\n" 13605 " loooooooooooooooooooong);", 13606 format("variable = f(\"long string literal\", short, " 13607 "loooooooooooooooooooong);", 13608 getLLVMStyleWithColumns(20))); 13609 13610 EXPECT_EQ( 13611 "f(g(\"long string \"\n" 13612 " \"literal\"),\n" 13613 " b);", 13614 format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20))); 13615 EXPECT_EQ("f(g(\"long string \"\n" 13616 " \"literal\",\n" 13617 " a),\n" 13618 " b);", 13619 format("f(g(\"long string literal\", a), b);", 13620 getLLVMStyleWithColumns(20))); 13621 EXPECT_EQ( 13622 "f(\"one two\".split(\n" 13623 " variable));", 13624 format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20))); 13625 EXPECT_EQ("f(\"one two three four five six \"\n" 13626 " \"seven\".split(\n" 13627 " really_looooong_variable));", 13628 format("f(\"one two three four five six seven\"." 13629 "split(really_looooong_variable));", 13630 getLLVMStyleWithColumns(33))); 13631 13632 EXPECT_EQ("f(\"some \"\n" 13633 " \"text\",\n" 13634 " other);", 13635 format("f(\"some text\", other);", getLLVMStyleWithColumns(10))); 13636 13637 // Only break as a last resort. 13638 verifyFormat( 13639 "aaaaaaaaaaaaaaaaaaaa(\n" 13640 " aaaaaaaaaaaaaaaaaaaa,\n" 13641 " aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));"); 13642 13643 EXPECT_EQ("\"splitmea\"\n" 13644 "\"trandomp\"\n" 13645 "\"oint\"", 13646 format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10))); 13647 13648 EXPECT_EQ("\"split/\"\n" 13649 "\"pathat/\"\n" 13650 "\"slashes\"", 13651 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10))); 13652 13653 EXPECT_EQ("\"split/\"\n" 13654 "\"pathat/\"\n" 13655 "\"slashes\"", 13656 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10))); 13657 EXPECT_EQ("\"split at \"\n" 13658 "\"spaces/at/\"\n" 13659 "\"slashes.at.any$\"\n" 13660 "\"non-alphanumeric%\"\n" 13661 "\"1111111111characte\"\n" 13662 "\"rs\"", 13663 format("\"split at " 13664 "spaces/at/" 13665 "slashes.at." 13666 "any$non-" 13667 "alphanumeric%" 13668 "1111111111characte" 13669 "rs\"", 13670 getLLVMStyleWithColumns(20))); 13671 13672 // Verify that splitting the strings understands 13673 // Style::AlwaysBreakBeforeMultilineStrings. 13674 EXPECT_EQ("aaaaaaaaaaaa(\n" 13675 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n" 13676 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");", 13677 format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa " 13678 "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa " 13679 "aaaaaaaaaaaaaaaaaaaaaa\");", 13680 getGoogleStyle())); 13681 EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13682 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";", 13683 format("return \"aaaaaaaaaaaaaaaaaaaaaa " 13684 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa " 13685 "aaaaaaaaaaaaaaaaaaaaaa\";", 13686 getGoogleStyle())); 13687 EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13688 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";", 13689 format("llvm::outs() << " 13690 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa" 13691 "aaaaaaaaaaaaaaaaaaa\";")); 13692 EXPECT_EQ("ffff(\n" 13693 " {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13694 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});", 13695 format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa " 13696 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});", 13697 getGoogleStyle())); 13698 13699 FormatStyle Style = getLLVMStyleWithColumns(12); 13700 Style.BreakStringLiterals = false; 13701 EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style)); 13702 13703 FormatStyle AlignLeft = getLLVMStyleWithColumns(12); 13704 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left; 13705 EXPECT_EQ("#define A \\\n" 13706 " \"some \" \\\n" 13707 " \"text \" \\\n" 13708 " \"other\";", 13709 format("#define A \"some text other\";", AlignLeft)); 13710 } 13711 13712 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) { 13713 EXPECT_EQ("C a = \"some more \"\n" 13714 " \"text\";", 13715 format("C a = \"some more text\";", getLLVMStyleWithColumns(18))); 13716 } 13717 13718 TEST_F(FormatTest, FullyRemoveEmptyLines) { 13719 FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80); 13720 NoEmptyLines.MaxEmptyLinesToKeep = 0; 13721 EXPECT_EQ("int i = a(b());", 13722 format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines)); 13723 } 13724 13725 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) { 13726 EXPECT_EQ( 13727 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 13728 "(\n" 13729 " \"x\t\");", 13730 format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 13731 "aaaaaaa(" 13732 "\"x\t\");")); 13733 } 13734 13735 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) { 13736 EXPECT_EQ( 13737 "u8\"utf8 string \"\n" 13738 "u8\"literal\";", 13739 format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16))); 13740 EXPECT_EQ( 13741 "u\"utf16 string \"\n" 13742 "u\"literal\";", 13743 format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16))); 13744 EXPECT_EQ( 13745 "U\"utf32 string \"\n" 13746 "U\"literal\";", 13747 format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16))); 13748 EXPECT_EQ("L\"wide string \"\n" 13749 "L\"literal\";", 13750 format("L\"wide string literal\";", getGoogleStyleWithColumns(16))); 13751 EXPECT_EQ("@\"NSString \"\n" 13752 "@\"literal\";", 13753 format("@\"NSString literal\";", getGoogleStyleWithColumns(19))); 13754 verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26)); 13755 13756 // This input makes clang-format try to split the incomplete unicode escape 13757 // sequence, which used to lead to a crasher. 13758 verifyNoCrash( 13759 "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 13760 getLLVMStyleWithColumns(60)); 13761 } 13762 13763 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) { 13764 FormatStyle Style = getGoogleStyleWithColumns(15); 13765 EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style)); 13766 EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style)); 13767 EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style)); 13768 EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style)); 13769 EXPECT_EQ("u8R\"x(raw literal)x\";", 13770 format("u8R\"x(raw literal)x\";", Style)); 13771 } 13772 13773 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) { 13774 FormatStyle Style = getLLVMStyleWithColumns(20); 13775 EXPECT_EQ( 13776 "_T(\"aaaaaaaaaaaaaa\")\n" 13777 "_T(\"aaaaaaaaaaaaaa\")\n" 13778 "_T(\"aaaaaaaaaaaa\")", 13779 format(" _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style)); 13780 EXPECT_EQ("f(x,\n" 13781 " _T(\"aaaaaaaaaaaa\")\n" 13782 " _T(\"aaa\"),\n" 13783 " z);", 13784 format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style)); 13785 13786 // FIXME: Handle embedded spaces in one iteration. 13787 // EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n" 13788 // "_T(\"aaaaaaaaaaaaa\")\n" 13789 // "_T(\"aaaaaaaaaaaaa\")\n" 13790 // "_T(\"a\")", 13791 // format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", 13792 // getLLVMStyleWithColumns(20))); 13793 EXPECT_EQ( 13794 "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", 13795 format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style)); 13796 EXPECT_EQ("f(\n" 13797 "#if !TEST\n" 13798 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n" 13799 "#endif\n" 13800 ");", 13801 format("f(\n" 13802 "#if !TEST\n" 13803 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n" 13804 "#endif\n" 13805 ");")); 13806 EXPECT_EQ("f(\n" 13807 "\n" 13808 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));", 13809 format("f(\n" 13810 "\n" 13811 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));")); 13812 // Regression test for accessing tokens past the end of a vector in the 13813 // TokenLexer. 13814 verifyNoCrash(R"(_T( 13815 " 13816 ) 13817 )"); 13818 } 13819 13820 TEST_F(FormatTest, BreaksStringLiteralOperands) { 13821 // In a function call with two operands, the second can be broken with no line 13822 // break before it. 13823 EXPECT_EQ( 13824 "func(a, \"long long \"\n" 13825 " \"long long\");", 13826 format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24))); 13827 // In a function call with three operands, the second must be broken with a 13828 // line break before it. 13829 EXPECT_EQ("func(a,\n" 13830 " \"long long long \"\n" 13831 " \"long\",\n" 13832 " c);", 13833 format("func(a, \"long long long long\", c);", 13834 getLLVMStyleWithColumns(24))); 13835 // In a function call with three operands, the third must be broken with a 13836 // line break before it. 13837 EXPECT_EQ("func(a, b,\n" 13838 " \"long long long \"\n" 13839 " \"long\");", 13840 format("func(a, b, \"long long long long\");", 13841 getLLVMStyleWithColumns(24))); 13842 // In a function call with three operands, both the second and the third must 13843 // be broken with a line break before them. 13844 EXPECT_EQ("func(a,\n" 13845 " \"long long long \"\n" 13846 " \"long\",\n" 13847 " \"long long long \"\n" 13848 " \"long\");", 13849 format("func(a, \"long long long long\", \"long long long long\");", 13850 getLLVMStyleWithColumns(24))); 13851 // In a chain of << with two operands, the second can be broken with no line 13852 // break before it. 13853 EXPECT_EQ("a << \"line line \"\n" 13854 " \"line\";", 13855 format("a << \"line line line\";", getLLVMStyleWithColumns(20))); 13856 // In a chain of << with three operands, the second can be broken with no line 13857 // break before it. 13858 EXPECT_EQ( 13859 "abcde << \"line \"\n" 13860 " \"line line\"\n" 13861 " << c;", 13862 format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20))); 13863 // In a chain of << with three operands, the third must be broken with a line 13864 // break before it. 13865 EXPECT_EQ( 13866 "a << b\n" 13867 " << \"line line \"\n" 13868 " \"line\";", 13869 format("a << b << \"line line line\";", getLLVMStyleWithColumns(20))); 13870 // In a chain of << with three operands, the second can be broken with no line 13871 // break before it and the third must be broken with a line break before it. 13872 EXPECT_EQ("abcd << \"line line \"\n" 13873 " \"line\"\n" 13874 " << \"line line \"\n" 13875 " \"line\";", 13876 format("abcd << \"line line line\" << \"line line line\";", 13877 getLLVMStyleWithColumns(20))); 13878 // In a chain of binary operators with two operands, the second can be broken 13879 // with no line break before it. 13880 EXPECT_EQ( 13881 "abcd + \"line line \"\n" 13882 " \"line line\";", 13883 format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20))); 13884 // In a chain of binary operators with three operands, the second must be 13885 // broken with a line break before it. 13886 EXPECT_EQ("abcd +\n" 13887 " \"line line \"\n" 13888 " \"line line\" +\n" 13889 " e;", 13890 format("abcd + \"line line line line\" + e;", 13891 getLLVMStyleWithColumns(20))); 13892 // In a function call with two operands, with AlignAfterOpenBracket enabled, 13893 // the first must be broken with a line break before it. 13894 FormatStyle Style = getLLVMStyleWithColumns(25); 13895 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 13896 EXPECT_EQ("someFunction(\n" 13897 " \"long long long \"\n" 13898 " \"long\",\n" 13899 " a);", 13900 format("someFunction(\"long long long long\", a);", Style)); 13901 } 13902 13903 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) { 13904 EXPECT_EQ( 13905 "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13906 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13907 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";", 13908 format("aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13909 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13910 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";")); 13911 } 13912 13913 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) { 13914 EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);", 13915 format("f(g(R\"x(raw literal)x\", a), b);", getGoogleStyle())); 13916 EXPECT_EQ("fffffffffff(g(R\"x(\n" 13917 "multiline raw string literal xxxxxxxxxxxxxx\n" 13918 ")x\",\n" 13919 " a),\n" 13920 " b);", 13921 format("fffffffffff(g(R\"x(\n" 13922 "multiline raw string literal xxxxxxxxxxxxxx\n" 13923 ")x\", a), b);", 13924 getGoogleStyleWithColumns(20))); 13925 EXPECT_EQ("fffffffffff(\n" 13926 " g(R\"x(qqq\n" 13927 "multiline raw string literal xxxxxxxxxxxxxx\n" 13928 ")x\",\n" 13929 " a),\n" 13930 " b);", 13931 format("fffffffffff(g(R\"x(qqq\n" 13932 "multiline raw string literal xxxxxxxxxxxxxx\n" 13933 ")x\", a), b);", 13934 getGoogleStyleWithColumns(20))); 13935 13936 EXPECT_EQ("fffffffffff(R\"x(\n" 13937 "multiline raw string literal xxxxxxxxxxxxxx\n" 13938 ")x\");", 13939 format("fffffffffff(R\"x(\n" 13940 "multiline raw string literal xxxxxxxxxxxxxx\n" 13941 ")x\");", 13942 getGoogleStyleWithColumns(20))); 13943 EXPECT_EQ("fffffffffff(R\"x(\n" 13944 "multiline raw string literal xxxxxxxxxxxxxx\n" 13945 ")x\" + bbbbbb);", 13946 format("fffffffffff(R\"x(\n" 13947 "multiline raw string literal xxxxxxxxxxxxxx\n" 13948 ")x\" + bbbbbb);", 13949 getGoogleStyleWithColumns(20))); 13950 EXPECT_EQ("fffffffffff(\n" 13951 " R\"x(\n" 13952 "multiline raw string literal xxxxxxxxxxxxxx\n" 13953 ")x\" +\n" 13954 " bbbbbb);", 13955 format("fffffffffff(\n" 13956 " R\"x(\n" 13957 "multiline raw string literal xxxxxxxxxxxxxx\n" 13958 ")x\" + bbbbbb);", 13959 getGoogleStyleWithColumns(20))); 13960 EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);", 13961 format("fffffffffff(\n" 13962 " R\"(single line raw string)\" + bbbbbb);")); 13963 } 13964 13965 TEST_F(FormatTest, SkipsUnknownStringLiterals) { 13966 verifyFormat("string a = \"unterminated;"); 13967 EXPECT_EQ("function(\"unterminated,\n" 13968 " OtherParameter);", 13969 format("function( \"unterminated,\n" 13970 " OtherParameter);")); 13971 } 13972 13973 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) { 13974 FormatStyle Style = getLLVMStyle(); 13975 Style.Standard = FormatStyle::LS_Cpp03; 13976 EXPECT_EQ("#define x(_a) printf(\"foo\" _a);", 13977 format("#define x(_a) printf(\"foo\"_a);", Style)); 13978 } 13979 13980 TEST_F(FormatTest, CppLexVersion) { 13981 FormatStyle Style = getLLVMStyle(); 13982 // Formatting of x * y differs if x is a type. 13983 verifyFormat("void foo() { MACRO(a * b); }", Style); 13984 verifyFormat("void foo() { MACRO(int *b); }", Style); 13985 13986 // LLVM style uses latest lexer. 13987 verifyFormat("void foo() { MACRO(char8_t *b); }", Style); 13988 Style.Standard = FormatStyle::LS_Cpp17; 13989 // But in c++17, char8_t isn't a keyword. 13990 verifyFormat("void foo() { MACRO(char8_t * b); }", Style); 13991 } 13992 13993 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); } 13994 13995 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) { 13996 EXPECT_EQ("someFunction(\"aaabbbcccd\"\n" 13997 " \"ddeeefff\");", 13998 format("someFunction(\"aaabbbcccdddeeefff\");", 13999 getLLVMStyleWithColumns(25))); 14000 EXPECT_EQ("someFunction1234567890(\n" 14001 " \"aaabbbcccdddeeefff\");", 14002 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 14003 getLLVMStyleWithColumns(26))); 14004 EXPECT_EQ("someFunction1234567890(\n" 14005 " \"aaabbbcccdddeeeff\"\n" 14006 " \"f\");", 14007 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 14008 getLLVMStyleWithColumns(25))); 14009 EXPECT_EQ("someFunction1234567890(\n" 14010 " \"aaabbbcccdddeeeff\"\n" 14011 " \"f\");", 14012 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 14013 getLLVMStyleWithColumns(24))); 14014 EXPECT_EQ("someFunction(\n" 14015 " \"aaabbbcc ddde \"\n" 14016 " \"efff\");", 14017 format("someFunction(\"aaabbbcc ddde efff\");", 14018 getLLVMStyleWithColumns(25))); 14019 EXPECT_EQ("someFunction(\"aaabbbccc \"\n" 14020 " \"ddeeefff\");", 14021 format("someFunction(\"aaabbbccc ddeeefff\");", 14022 getLLVMStyleWithColumns(25))); 14023 EXPECT_EQ("someFunction1234567890(\n" 14024 " \"aaabb \"\n" 14025 " \"cccdddeeefff\");", 14026 format("someFunction1234567890(\"aaabb cccdddeeefff\");", 14027 getLLVMStyleWithColumns(25))); 14028 EXPECT_EQ("#define A \\\n" 14029 " string s = \\\n" 14030 " \"123456789\" \\\n" 14031 " \"0\"; \\\n" 14032 " int i;", 14033 format("#define A string s = \"1234567890\"; int i;", 14034 getLLVMStyleWithColumns(20))); 14035 EXPECT_EQ("someFunction(\n" 14036 " \"aaabbbcc \"\n" 14037 " \"dddeeefff\");", 14038 format("someFunction(\"aaabbbcc dddeeefff\");", 14039 getLLVMStyleWithColumns(25))); 14040 } 14041 14042 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) { 14043 EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3))); 14044 EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2))); 14045 EXPECT_EQ("\"test\"\n" 14046 "\"\\n\"", 14047 format("\"test\\n\"", getLLVMStyleWithColumns(7))); 14048 EXPECT_EQ("\"tes\\\\\"\n" 14049 "\"n\"", 14050 format("\"tes\\\\n\"", getLLVMStyleWithColumns(7))); 14051 EXPECT_EQ("\"\\\\\\\\\"\n" 14052 "\"\\n\"", 14053 format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7))); 14054 EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7))); 14055 EXPECT_EQ("\"\\uff01\"\n" 14056 "\"test\"", 14057 format("\"\\uff01test\"", getLLVMStyleWithColumns(8))); 14058 EXPECT_EQ("\"\\Uff01ff02\"", 14059 format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11))); 14060 EXPECT_EQ("\"\\x000000000001\"\n" 14061 "\"next\"", 14062 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16))); 14063 EXPECT_EQ("\"\\x000000000001next\"", 14064 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15))); 14065 EXPECT_EQ("\"\\x000000000001\"", 14066 format("\"\\x000000000001\"", getLLVMStyleWithColumns(7))); 14067 EXPECT_EQ("\"test\"\n" 14068 "\"\\000000\"\n" 14069 "\"000001\"", 14070 format("\"test\\000000000001\"", getLLVMStyleWithColumns(9))); 14071 EXPECT_EQ("\"test\\000\"\n" 14072 "\"00000000\"\n" 14073 "\"1\"", 14074 format("\"test\\000000000001\"", getLLVMStyleWithColumns(10))); 14075 } 14076 14077 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) { 14078 verifyFormat("void f() {\n" 14079 " return g() {}\n" 14080 " void h() {}"); 14081 verifyFormat("int a[] = {void forgot_closing_brace(){f();\n" 14082 "g();\n" 14083 "}"); 14084 } 14085 14086 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) { 14087 verifyFormat( 14088 "void f() { return C{param1, param2}.SomeCall(param1, param2); }"); 14089 } 14090 14091 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) { 14092 verifyFormat("class X {\n" 14093 " void f() {\n" 14094 " }\n" 14095 "};", 14096 getLLVMStyleWithColumns(12)); 14097 } 14098 14099 TEST_F(FormatTest, ConfigurableIndentWidth) { 14100 FormatStyle EightIndent = getLLVMStyleWithColumns(18); 14101 EightIndent.IndentWidth = 8; 14102 EightIndent.ContinuationIndentWidth = 8; 14103 verifyFormat("void f() {\n" 14104 " someFunction();\n" 14105 " if (true) {\n" 14106 " f();\n" 14107 " }\n" 14108 "}", 14109 EightIndent); 14110 verifyFormat("class X {\n" 14111 " void f() {\n" 14112 " }\n" 14113 "};", 14114 EightIndent); 14115 verifyFormat("int x[] = {\n" 14116 " call(),\n" 14117 " call()};", 14118 EightIndent); 14119 } 14120 14121 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) { 14122 verifyFormat("double\n" 14123 "f();", 14124 getLLVMStyleWithColumns(8)); 14125 } 14126 14127 TEST_F(FormatTest, ConfigurableUseOfTab) { 14128 FormatStyle Tab = getLLVMStyleWithColumns(42); 14129 Tab.IndentWidth = 8; 14130 Tab.UseTab = FormatStyle::UT_Always; 14131 Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left; 14132 14133 EXPECT_EQ("if (aaaaaaaa && // q\n" 14134 " bb)\t\t// w\n" 14135 "\t;", 14136 format("if (aaaaaaaa &&// q\n" 14137 "bb)// w\n" 14138 ";", 14139 Tab)); 14140 EXPECT_EQ("if (aaa && bbb) // w\n" 14141 "\t;", 14142 format("if(aaa&&bbb)// w\n" 14143 ";", 14144 Tab)); 14145 14146 verifyFormat("class X {\n" 14147 "\tvoid f() {\n" 14148 "\t\tsomeFunction(parameter1,\n" 14149 "\t\t\t parameter2);\n" 14150 "\t}\n" 14151 "};", 14152 Tab); 14153 verifyFormat("#define A \\\n" 14154 "\tvoid f() { \\\n" 14155 "\t\tsomeFunction( \\\n" 14156 "\t\t parameter1, \\\n" 14157 "\t\t parameter2); \\\n" 14158 "\t}", 14159 Tab); 14160 verifyFormat("int a;\t // x\n" 14161 "int bbbbbbbb; // x\n", 14162 Tab); 14163 14164 Tab.TabWidth = 4; 14165 Tab.IndentWidth = 8; 14166 verifyFormat("class TabWidth4Indent8 {\n" 14167 "\t\tvoid f() {\n" 14168 "\t\t\t\tsomeFunction(parameter1,\n" 14169 "\t\t\t\t\t\t\t parameter2);\n" 14170 "\t\t}\n" 14171 "};", 14172 Tab); 14173 14174 Tab.TabWidth = 4; 14175 Tab.IndentWidth = 4; 14176 verifyFormat("class TabWidth4Indent4 {\n" 14177 "\tvoid f() {\n" 14178 "\t\tsomeFunction(parameter1,\n" 14179 "\t\t\t\t\t parameter2);\n" 14180 "\t}\n" 14181 "};", 14182 Tab); 14183 14184 Tab.TabWidth = 8; 14185 Tab.IndentWidth = 4; 14186 verifyFormat("class TabWidth8Indent4 {\n" 14187 " void f() {\n" 14188 "\tsomeFunction(parameter1,\n" 14189 "\t\t parameter2);\n" 14190 " }\n" 14191 "};", 14192 Tab); 14193 14194 Tab.TabWidth = 8; 14195 Tab.IndentWidth = 8; 14196 EXPECT_EQ("/*\n" 14197 "\t a\t\tcomment\n" 14198 "\t in multiple lines\n" 14199 " */", 14200 format(" /*\t \t \n" 14201 " \t \t a\t\tcomment\t \t\n" 14202 " \t \t in multiple lines\t\n" 14203 " \t */", 14204 Tab)); 14205 14206 Tab.UseTab = FormatStyle::UT_ForIndentation; 14207 verifyFormat("{\n" 14208 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14209 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14210 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14211 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14212 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14213 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14214 "};", 14215 Tab); 14216 verifyFormat("enum AA {\n" 14217 "\ta1, // Force multiple lines\n" 14218 "\ta2,\n" 14219 "\ta3\n" 14220 "};", 14221 Tab); 14222 EXPECT_EQ("if (aaaaaaaa && // q\n" 14223 " bb) // w\n" 14224 "\t;", 14225 format("if (aaaaaaaa &&// q\n" 14226 "bb)// w\n" 14227 ";", 14228 Tab)); 14229 verifyFormat("class X {\n" 14230 "\tvoid f() {\n" 14231 "\t\tsomeFunction(parameter1,\n" 14232 "\t\t parameter2);\n" 14233 "\t}\n" 14234 "};", 14235 Tab); 14236 verifyFormat("{\n" 14237 "\tQ(\n" 14238 "\t {\n" 14239 "\t\t int a;\n" 14240 "\t\t someFunction(aaaaaaaa,\n" 14241 "\t\t bbbbbbb);\n" 14242 "\t },\n" 14243 "\t p);\n" 14244 "}", 14245 Tab); 14246 EXPECT_EQ("{\n" 14247 "\t/* aaaa\n" 14248 "\t bbbb */\n" 14249 "}", 14250 format("{\n" 14251 "/* aaaa\n" 14252 " bbbb */\n" 14253 "}", 14254 Tab)); 14255 EXPECT_EQ("{\n" 14256 "\t/*\n" 14257 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14258 "\t bbbbbbbbbbbbb\n" 14259 "\t*/\n" 14260 "}", 14261 format("{\n" 14262 "/*\n" 14263 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14264 "*/\n" 14265 "}", 14266 Tab)); 14267 EXPECT_EQ("{\n" 14268 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14269 "\t// bbbbbbbbbbbbb\n" 14270 "}", 14271 format("{\n" 14272 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14273 "}", 14274 Tab)); 14275 EXPECT_EQ("{\n" 14276 "\t/*\n" 14277 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14278 "\t bbbbbbbbbbbbb\n" 14279 "\t*/\n" 14280 "}", 14281 format("{\n" 14282 "\t/*\n" 14283 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14284 "\t*/\n" 14285 "}", 14286 Tab)); 14287 EXPECT_EQ("{\n" 14288 "\t/*\n" 14289 "\n" 14290 "\t*/\n" 14291 "}", 14292 format("{\n" 14293 "\t/*\n" 14294 "\n" 14295 "\t*/\n" 14296 "}", 14297 Tab)); 14298 EXPECT_EQ("{\n" 14299 "\t/*\n" 14300 " asdf\n" 14301 "\t*/\n" 14302 "}", 14303 format("{\n" 14304 "\t/*\n" 14305 " asdf\n" 14306 "\t*/\n" 14307 "}", 14308 Tab)); 14309 14310 verifyFormat("void f() {\n" 14311 "\treturn true ? aaaaaaaaaaaaaaaaaa\n" 14312 "\t : bbbbbbbbbbbbbbbbbb\n" 14313 "}", 14314 Tab); 14315 FormatStyle TabNoBreak = Tab; 14316 TabNoBreak.BreakBeforeTernaryOperators = false; 14317 verifyFormat("void f() {\n" 14318 "\treturn true ? aaaaaaaaaaaaaaaaaa :\n" 14319 "\t bbbbbbbbbbbbbbbbbb\n" 14320 "}", 14321 TabNoBreak); 14322 verifyFormat("void f() {\n" 14323 "\treturn true ?\n" 14324 "\t aaaaaaaaaaaaaaaaaaaa :\n" 14325 "\t bbbbbbbbbbbbbbbbbbbb\n" 14326 "}", 14327 TabNoBreak); 14328 14329 Tab.UseTab = FormatStyle::UT_Never; 14330 EXPECT_EQ("/*\n" 14331 " a\t\tcomment\n" 14332 " in multiple lines\n" 14333 " */", 14334 format(" /*\t \t \n" 14335 " \t \t a\t\tcomment\t \t\n" 14336 " \t \t in multiple lines\t\n" 14337 " \t */", 14338 Tab)); 14339 EXPECT_EQ("/* some\n" 14340 " comment */", 14341 format(" \t \t /* some\n" 14342 " \t \t comment */", 14343 Tab)); 14344 EXPECT_EQ("int a; /* some\n" 14345 " comment */", 14346 format(" \t \t int a; /* some\n" 14347 " \t \t comment */", 14348 Tab)); 14349 14350 EXPECT_EQ("int a; /* some\n" 14351 "comment */", 14352 format(" \t \t int\ta; /* some\n" 14353 " \t \t comment */", 14354 Tab)); 14355 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14356 " comment */", 14357 format(" \t \t f(\"\t\t\"); /* some\n" 14358 " \t \t comment */", 14359 Tab)); 14360 EXPECT_EQ("{\n" 14361 " /*\n" 14362 " * Comment\n" 14363 " */\n" 14364 " int i;\n" 14365 "}", 14366 format("{\n" 14367 "\t/*\n" 14368 "\t * Comment\n" 14369 "\t */\n" 14370 "\t int i;\n" 14371 "}", 14372 Tab)); 14373 14374 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation; 14375 Tab.TabWidth = 8; 14376 Tab.IndentWidth = 8; 14377 EXPECT_EQ("if (aaaaaaaa && // q\n" 14378 " bb) // w\n" 14379 "\t;", 14380 format("if (aaaaaaaa &&// q\n" 14381 "bb)// w\n" 14382 ";", 14383 Tab)); 14384 EXPECT_EQ("if (aaa && bbb) // w\n" 14385 "\t;", 14386 format("if(aaa&&bbb)// w\n" 14387 ";", 14388 Tab)); 14389 verifyFormat("class X {\n" 14390 "\tvoid f() {\n" 14391 "\t\tsomeFunction(parameter1,\n" 14392 "\t\t\t parameter2);\n" 14393 "\t}\n" 14394 "};", 14395 Tab); 14396 verifyFormat("#define A \\\n" 14397 "\tvoid f() { \\\n" 14398 "\t\tsomeFunction( \\\n" 14399 "\t\t parameter1, \\\n" 14400 "\t\t parameter2); \\\n" 14401 "\t}", 14402 Tab); 14403 Tab.TabWidth = 4; 14404 Tab.IndentWidth = 8; 14405 verifyFormat("class TabWidth4Indent8 {\n" 14406 "\t\tvoid f() {\n" 14407 "\t\t\t\tsomeFunction(parameter1,\n" 14408 "\t\t\t\t\t\t\t parameter2);\n" 14409 "\t\t}\n" 14410 "};", 14411 Tab); 14412 Tab.TabWidth = 4; 14413 Tab.IndentWidth = 4; 14414 verifyFormat("class TabWidth4Indent4 {\n" 14415 "\tvoid f() {\n" 14416 "\t\tsomeFunction(parameter1,\n" 14417 "\t\t\t\t\t parameter2);\n" 14418 "\t}\n" 14419 "};", 14420 Tab); 14421 Tab.TabWidth = 8; 14422 Tab.IndentWidth = 4; 14423 verifyFormat("class TabWidth8Indent4 {\n" 14424 " void f() {\n" 14425 "\tsomeFunction(parameter1,\n" 14426 "\t\t parameter2);\n" 14427 " }\n" 14428 "};", 14429 Tab); 14430 Tab.TabWidth = 8; 14431 Tab.IndentWidth = 8; 14432 EXPECT_EQ("/*\n" 14433 "\t a\t\tcomment\n" 14434 "\t in multiple lines\n" 14435 " */", 14436 format(" /*\t \t \n" 14437 " \t \t a\t\tcomment\t \t\n" 14438 " \t \t in multiple lines\t\n" 14439 " \t */", 14440 Tab)); 14441 verifyFormat("{\n" 14442 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14443 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14444 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14445 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14446 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14447 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14448 "};", 14449 Tab); 14450 verifyFormat("enum AA {\n" 14451 "\ta1, // Force multiple lines\n" 14452 "\ta2,\n" 14453 "\ta3\n" 14454 "};", 14455 Tab); 14456 EXPECT_EQ("if (aaaaaaaa && // q\n" 14457 " bb) // w\n" 14458 "\t;", 14459 format("if (aaaaaaaa &&// q\n" 14460 "bb)// w\n" 14461 ";", 14462 Tab)); 14463 verifyFormat("class X {\n" 14464 "\tvoid f() {\n" 14465 "\t\tsomeFunction(parameter1,\n" 14466 "\t\t\t parameter2);\n" 14467 "\t}\n" 14468 "};", 14469 Tab); 14470 verifyFormat("{\n" 14471 "\tQ(\n" 14472 "\t {\n" 14473 "\t\t int a;\n" 14474 "\t\t someFunction(aaaaaaaa,\n" 14475 "\t\t\t\t bbbbbbb);\n" 14476 "\t },\n" 14477 "\t p);\n" 14478 "}", 14479 Tab); 14480 EXPECT_EQ("{\n" 14481 "\t/* aaaa\n" 14482 "\t bbbb */\n" 14483 "}", 14484 format("{\n" 14485 "/* aaaa\n" 14486 " bbbb */\n" 14487 "}", 14488 Tab)); 14489 EXPECT_EQ("{\n" 14490 "\t/*\n" 14491 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14492 "\t bbbbbbbbbbbbb\n" 14493 "\t*/\n" 14494 "}", 14495 format("{\n" 14496 "/*\n" 14497 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14498 "*/\n" 14499 "}", 14500 Tab)); 14501 EXPECT_EQ("{\n" 14502 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14503 "\t// bbbbbbbbbbbbb\n" 14504 "}", 14505 format("{\n" 14506 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14507 "}", 14508 Tab)); 14509 EXPECT_EQ("{\n" 14510 "\t/*\n" 14511 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14512 "\t bbbbbbbbbbbbb\n" 14513 "\t*/\n" 14514 "}", 14515 format("{\n" 14516 "\t/*\n" 14517 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14518 "\t*/\n" 14519 "}", 14520 Tab)); 14521 EXPECT_EQ("{\n" 14522 "\t/*\n" 14523 "\n" 14524 "\t*/\n" 14525 "}", 14526 format("{\n" 14527 "\t/*\n" 14528 "\n" 14529 "\t*/\n" 14530 "}", 14531 Tab)); 14532 EXPECT_EQ("{\n" 14533 "\t/*\n" 14534 " asdf\n" 14535 "\t*/\n" 14536 "}", 14537 format("{\n" 14538 "\t/*\n" 14539 " asdf\n" 14540 "\t*/\n" 14541 "}", 14542 Tab)); 14543 EXPECT_EQ("/* some\n" 14544 " comment */", 14545 format(" \t \t /* some\n" 14546 " \t \t comment */", 14547 Tab)); 14548 EXPECT_EQ("int a; /* some\n" 14549 " comment */", 14550 format(" \t \t int a; /* some\n" 14551 " \t \t comment */", 14552 Tab)); 14553 EXPECT_EQ("int a; /* some\n" 14554 "comment */", 14555 format(" \t \t int\ta; /* some\n" 14556 " \t \t comment */", 14557 Tab)); 14558 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14559 " comment */", 14560 format(" \t \t f(\"\t\t\"); /* some\n" 14561 " \t \t comment */", 14562 Tab)); 14563 EXPECT_EQ("{\n" 14564 "\t/*\n" 14565 "\t * Comment\n" 14566 "\t */\n" 14567 "\tint i;\n" 14568 "}", 14569 format("{\n" 14570 "\t/*\n" 14571 "\t * Comment\n" 14572 "\t */\n" 14573 "\t int i;\n" 14574 "}", 14575 Tab)); 14576 Tab.TabWidth = 2; 14577 Tab.IndentWidth = 2; 14578 EXPECT_EQ("{\n" 14579 "\t/* aaaa\n" 14580 "\t\t bbbb */\n" 14581 "}", 14582 format("{\n" 14583 "/* aaaa\n" 14584 "\t bbbb */\n" 14585 "}", 14586 Tab)); 14587 EXPECT_EQ("{\n" 14588 "\t/*\n" 14589 "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14590 "\t\tbbbbbbbbbbbbb\n" 14591 "\t*/\n" 14592 "}", 14593 format("{\n" 14594 "/*\n" 14595 "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14596 "*/\n" 14597 "}", 14598 Tab)); 14599 Tab.AlignConsecutiveAssignments.Enabled = true; 14600 Tab.AlignConsecutiveDeclarations.Enabled = true; 14601 Tab.TabWidth = 4; 14602 Tab.IndentWidth = 4; 14603 verifyFormat("class Assign {\n" 14604 "\tvoid f() {\n" 14605 "\t\tint x = 123;\n" 14606 "\t\tint random = 4;\n" 14607 "\t\tstd::string alphabet =\n" 14608 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n" 14609 "\t}\n" 14610 "};", 14611 Tab); 14612 14613 Tab.UseTab = FormatStyle::UT_AlignWithSpaces; 14614 Tab.TabWidth = 8; 14615 Tab.IndentWidth = 8; 14616 EXPECT_EQ("if (aaaaaaaa && // q\n" 14617 " bb) // w\n" 14618 "\t;", 14619 format("if (aaaaaaaa &&// q\n" 14620 "bb)// w\n" 14621 ";", 14622 Tab)); 14623 EXPECT_EQ("if (aaa && bbb) // w\n" 14624 "\t;", 14625 format("if(aaa&&bbb)// w\n" 14626 ";", 14627 Tab)); 14628 verifyFormat("class X {\n" 14629 "\tvoid f() {\n" 14630 "\t\tsomeFunction(parameter1,\n" 14631 "\t\t parameter2);\n" 14632 "\t}\n" 14633 "};", 14634 Tab); 14635 verifyFormat("#define A \\\n" 14636 "\tvoid f() { \\\n" 14637 "\t\tsomeFunction( \\\n" 14638 "\t\t parameter1, \\\n" 14639 "\t\t parameter2); \\\n" 14640 "\t}", 14641 Tab); 14642 Tab.TabWidth = 4; 14643 Tab.IndentWidth = 8; 14644 verifyFormat("class TabWidth4Indent8 {\n" 14645 "\t\tvoid f() {\n" 14646 "\t\t\t\tsomeFunction(parameter1,\n" 14647 "\t\t\t\t parameter2);\n" 14648 "\t\t}\n" 14649 "};", 14650 Tab); 14651 Tab.TabWidth = 4; 14652 Tab.IndentWidth = 4; 14653 verifyFormat("class TabWidth4Indent4 {\n" 14654 "\tvoid f() {\n" 14655 "\t\tsomeFunction(parameter1,\n" 14656 "\t\t parameter2);\n" 14657 "\t}\n" 14658 "};", 14659 Tab); 14660 Tab.TabWidth = 8; 14661 Tab.IndentWidth = 4; 14662 verifyFormat("class TabWidth8Indent4 {\n" 14663 " void f() {\n" 14664 "\tsomeFunction(parameter1,\n" 14665 "\t parameter2);\n" 14666 " }\n" 14667 "};", 14668 Tab); 14669 Tab.TabWidth = 8; 14670 Tab.IndentWidth = 8; 14671 EXPECT_EQ("/*\n" 14672 " a\t\tcomment\n" 14673 " in multiple lines\n" 14674 " */", 14675 format(" /*\t \t \n" 14676 " \t \t a\t\tcomment\t \t\n" 14677 " \t \t in multiple lines\t\n" 14678 " \t */", 14679 Tab)); 14680 verifyFormat("{\n" 14681 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14682 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14683 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14684 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14685 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14686 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14687 "};", 14688 Tab); 14689 verifyFormat("enum AA {\n" 14690 "\ta1, // Force multiple lines\n" 14691 "\ta2,\n" 14692 "\ta3\n" 14693 "};", 14694 Tab); 14695 EXPECT_EQ("if (aaaaaaaa && // q\n" 14696 " bb) // w\n" 14697 "\t;", 14698 format("if (aaaaaaaa &&// q\n" 14699 "bb)// w\n" 14700 ";", 14701 Tab)); 14702 verifyFormat("class X {\n" 14703 "\tvoid f() {\n" 14704 "\t\tsomeFunction(parameter1,\n" 14705 "\t\t parameter2);\n" 14706 "\t}\n" 14707 "};", 14708 Tab); 14709 verifyFormat("{\n" 14710 "\tQ(\n" 14711 "\t {\n" 14712 "\t\t int a;\n" 14713 "\t\t someFunction(aaaaaaaa,\n" 14714 "\t\t bbbbbbb);\n" 14715 "\t },\n" 14716 "\t p);\n" 14717 "}", 14718 Tab); 14719 EXPECT_EQ("{\n" 14720 "\t/* aaaa\n" 14721 "\t bbbb */\n" 14722 "}", 14723 format("{\n" 14724 "/* aaaa\n" 14725 " bbbb */\n" 14726 "}", 14727 Tab)); 14728 EXPECT_EQ("{\n" 14729 "\t/*\n" 14730 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14731 "\t bbbbbbbbbbbbb\n" 14732 "\t*/\n" 14733 "}", 14734 format("{\n" 14735 "/*\n" 14736 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14737 "*/\n" 14738 "}", 14739 Tab)); 14740 EXPECT_EQ("{\n" 14741 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14742 "\t// bbbbbbbbbbbbb\n" 14743 "}", 14744 format("{\n" 14745 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14746 "}", 14747 Tab)); 14748 EXPECT_EQ("{\n" 14749 "\t/*\n" 14750 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14751 "\t bbbbbbbbbbbbb\n" 14752 "\t*/\n" 14753 "}", 14754 format("{\n" 14755 "\t/*\n" 14756 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14757 "\t*/\n" 14758 "}", 14759 Tab)); 14760 EXPECT_EQ("{\n" 14761 "\t/*\n" 14762 "\n" 14763 "\t*/\n" 14764 "}", 14765 format("{\n" 14766 "\t/*\n" 14767 "\n" 14768 "\t*/\n" 14769 "}", 14770 Tab)); 14771 EXPECT_EQ("{\n" 14772 "\t/*\n" 14773 " asdf\n" 14774 "\t*/\n" 14775 "}", 14776 format("{\n" 14777 "\t/*\n" 14778 " asdf\n" 14779 "\t*/\n" 14780 "}", 14781 Tab)); 14782 EXPECT_EQ("/* some\n" 14783 " comment */", 14784 format(" \t \t /* some\n" 14785 " \t \t comment */", 14786 Tab)); 14787 EXPECT_EQ("int a; /* some\n" 14788 " comment */", 14789 format(" \t \t int a; /* some\n" 14790 " \t \t comment */", 14791 Tab)); 14792 EXPECT_EQ("int a; /* some\n" 14793 "comment */", 14794 format(" \t \t int\ta; /* some\n" 14795 " \t \t comment */", 14796 Tab)); 14797 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14798 " comment */", 14799 format(" \t \t f(\"\t\t\"); /* some\n" 14800 " \t \t comment */", 14801 Tab)); 14802 EXPECT_EQ("{\n" 14803 "\t/*\n" 14804 "\t * Comment\n" 14805 "\t */\n" 14806 "\tint i;\n" 14807 "}", 14808 format("{\n" 14809 "\t/*\n" 14810 "\t * Comment\n" 14811 "\t */\n" 14812 "\t int i;\n" 14813 "}", 14814 Tab)); 14815 Tab.TabWidth = 2; 14816 Tab.IndentWidth = 2; 14817 EXPECT_EQ("{\n" 14818 "\t/* aaaa\n" 14819 "\t bbbb */\n" 14820 "}", 14821 format("{\n" 14822 "/* aaaa\n" 14823 " bbbb */\n" 14824 "}", 14825 Tab)); 14826 EXPECT_EQ("{\n" 14827 "\t/*\n" 14828 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14829 "\t bbbbbbbbbbbbb\n" 14830 "\t*/\n" 14831 "}", 14832 format("{\n" 14833 "/*\n" 14834 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14835 "*/\n" 14836 "}", 14837 Tab)); 14838 Tab.AlignConsecutiveAssignments.Enabled = true; 14839 Tab.AlignConsecutiveDeclarations.Enabled = true; 14840 Tab.TabWidth = 4; 14841 Tab.IndentWidth = 4; 14842 verifyFormat("class Assign {\n" 14843 "\tvoid f() {\n" 14844 "\t\tint x = 123;\n" 14845 "\t\tint random = 4;\n" 14846 "\t\tstd::string alphabet =\n" 14847 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n" 14848 "\t}\n" 14849 "};", 14850 Tab); 14851 Tab.AlignOperands = FormatStyle::OAS_Align; 14852 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n" 14853 " cccccccccccccccccccc;", 14854 Tab); 14855 // no alignment 14856 verifyFormat("int aaaaaaaaaa =\n" 14857 "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 14858 Tab); 14859 verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n" 14860 " : bbbbbbbbbbbbbb ? 222222222222222\n" 14861 " : 333333333333333;", 14862 Tab); 14863 Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 14864 Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator; 14865 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n" 14866 " + cccccccccccccccccccc;", 14867 Tab); 14868 } 14869 14870 TEST_F(FormatTest, ZeroTabWidth) { 14871 FormatStyle Tab = getLLVMStyleWithColumns(42); 14872 Tab.IndentWidth = 8; 14873 Tab.UseTab = FormatStyle::UT_Never; 14874 Tab.TabWidth = 0; 14875 EXPECT_EQ("void a(){\n" 14876 " // line starts with '\t'\n" 14877 "};", 14878 format("void a(){\n" 14879 "\t// line starts with '\t'\n" 14880 "};", 14881 Tab)); 14882 14883 EXPECT_EQ("void a(){\n" 14884 " // line starts with '\t'\n" 14885 "};", 14886 format("void a(){\n" 14887 "\t\t// line starts with '\t'\n" 14888 "};", 14889 Tab)); 14890 14891 Tab.UseTab = FormatStyle::UT_ForIndentation; 14892 EXPECT_EQ("void a(){\n" 14893 " // line starts with '\t'\n" 14894 "};", 14895 format("void a(){\n" 14896 "\t// line starts with '\t'\n" 14897 "};", 14898 Tab)); 14899 14900 EXPECT_EQ("void a(){\n" 14901 " // line starts with '\t'\n" 14902 "};", 14903 format("void a(){\n" 14904 "\t\t// line starts with '\t'\n" 14905 "};", 14906 Tab)); 14907 14908 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation; 14909 EXPECT_EQ("void a(){\n" 14910 " // line starts with '\t'\n" 14911 "};", 14912 format("void a(){\n" 14913 "\t// line starts with '\t'\n" 14914 "};", 14915 Tab)); 14916 14917 EXPECT_EQ("void a(){\n" 14918 " // line starts with '\t'\n" 14919 "};", 14920 format("void a(){\n" 14921 "\t\t// line starts with '\t'\n" 14922 "};", 14923 Tab)); 14924 14925 Tab.UseTab = FormatStyle::UT_AlignWithSpaces; 14926 EXPECT_EQ("void a(){\n" 14927 " // line starts with '\t'\n" 14928 "};", 14929 format("void a(){\n" 14930 "\t// line starts with '\t'\n" 14931 "};", 14932 Tab)); 14933 14934 EXPECT_EQ("void a(){\n" 14935 " // line starts with '\t'\n" 14936 "};", 14937 format("void a(){\n" 14938 "\t\t// line starts with '\t'\n" 14939 "};", 14940 Tab)); 14941 14942 Tab.UseTab = FormatStyle::UT_Always; 14943 EXPECT_EQ("void a(){\n" 14944 "// line starts with '\t'\n" 14945 "};", 14946 format("void a(){\n" 14947 "\t// line starts with '\t'\n" 14948 "};", 14949 Tab)); 14950 14951 EXPECT_EQ("void a(){\n" 14952 "// line starts with '\t'\n" 14953 "};", 14954 format("void a(){\n" 14955 "\t\t// line starts with '\t'\n" 14956 "};", 14957 Tab)); 14958 } 14959 14960 TEST_F(FormatTest, CalculatesOriginalColumn) { 14961 EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14962 "q\"; /* some\n" 14963 " comment */", 14964 format(" \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14965 "q\"; /* some\n" 14966 " comment */", 14967 getLLVMStyle())); 14968 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n" 14969 "/* some\n" 14970 " comment */", 14971 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n" 14972 " /* some\n" 14973 " comment */", 14974 getLLVMStyle())); 14975 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14976 "qqq\n" 14977 "/* some\n" 14978 " comment */", 14979 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14980 "qqq\n" 14981 " /* some\n" 14982 " comment */", 14983 getLLVMStyle())); 14984 EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14985 "wwww; /* some\n" 14986 " comment */", 14987 format(" inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14988 "wwww; /* some\n" 14989 " comment */", 14990 getLLVMStyle())); 14991 } 14992 14993 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) { 14994 FormatStyle NoSpace = getLLVMStyle(); 14995 NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never; 14996 14997 verifyFormat("while(true)\n" 14998 " continue;", 14999 NoSpace); 15000 verifyFormat("for(;;)\n" 15001 " continue;", 15002 NoSpace); 15003 verifyFormat("if(true)\n" 15004 " f();\n" 15005 "else if(true)\n" 15006 " f();", 15007 NoSpace); 15008 verifyFormat("do {\n" 15009 " do_something();\n" 15010 "} while(something());", 15011 NoSpace); 15012 verifyFormat("switch(x) {\n" 15013 "default:\n" 15014 " break;\n" 15015 "}", 15016 NoSpace); 15017 verifyFormat("auto i = std::make_unique<int>(5);", NoSpace); 15018 verifyFormat("size_t x = sizeof(x);", NoSpace); 15019 verifyFormat("auto f(int x) -> decltype(x);", NoSpace); 15020 verifyFormat("auto f(int x) -> typeof(x);", NoSpace); 15021 verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace); 15022 verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace); 15023 verifyFormat("int f(T x) noexcept(x.create());", NoSpace); 15024 verifyFormat("alignas(128) char a[128];", NoSpace); 15025 verifyFormat("size_t x = alignof(MyType);", NoSpace); 15026 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace); 15027 verifyFormat("int f() throw(Deprecated);", NoSpace); 15028 verifyFormat("typedef void (*cb)(int);", NoSpace); 15029 verifyFormat("T A::operator()();", NoSpace); 15030 verifyFormat("X A::operator++(T);", NoSpace); 15031 verifyFormat("auto lambda = []() { return 0; };", NoSpace); 15032 15033 FormatStyle Space = getLLVMStyle(); 15034 Space.SpaceBeforeParens = FormatStyle::SBPO_Always; 15035 15036 verifyFormat("int f ();", Space); 15037 verifyFormat("void f (int a, T b) {\n" 15038 " while (true)\n" 15039 " continue;\n" 15040 "}", 15041 Space); 15042 verifyFormat("if (true)\n" 15043 " f ();\n" 15044 "else if (true)\n" 15045 " f ();", 15046 Space); 15047 verifyFormat("do {\n" 15048 " do_something ();\n" 15049 "} while (something ());", 15050 Space); 15051 verifyFormat("switch (x) {\n" 15052 "default:\n" 15053 " break;\n" 15054 "}", 15055 Space); 15056 verifyFormat("A::A () : a (1) {}", Space); 15057 verifyFormat("void f () __attribute__ ((asdf));", Space); 15058 verifyFormat("*(&a + 1);\n" 15059 "&((&a)[1]);\n" 15060 "a[(b + c) * d];\n" 15061 "(((a + 1) * 2) + 3) * 4;", 15062 Space); 15063 verifyFormat("#define A(x) x", Space); 15064 verifyFormat("#define A (x) x", Space); 15065 verifyFormat("#if defined(x)\n" 15066 "#endif", 15067 Space); 15068 verifyFormat("auto i = std::make_unique<int> (5);", Space); 15069 verifyFormat("size_t x = sizeof (x);", Space); 15070 verifyFormat("auto f (int x) -> decltype (x);", Space); 15071 verifyFormat("auto f (int x) -> typeof (x);", Space); 15072 verifyFormat("auto f (int x) -> _Atomic (x);", Space); 15073 verifyFormat("auto f (int x) -> __underlying_type (x);", Space); 15074 verifyFormat("int f (T x) noexcept (x.create ());", Space); 15075 verifyFormat("alignas (128) char a[128];", Space); 15076 verifyFormat("size_t x = alignof (MyType);", Space); 15077 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space); 15078 verifyFormat("int f () throw (Deprecated);", Space); 15079 verifyFormat("typedef void (*cb) (int);", Space); 15080 // FIXME these tests regressed behaviour. 15081 // verifyFormat("T A::operator() ();", Space); 15082 // verifyFormat("X A::operator++ (T);", Space); 15083 verifyFormat("auto lambda = [] () { return 0; };", Space); 15084 verifyFormat("int x = int (y);", Space); 15085 verifyFormat("#define F(...) __VA_OPT__ (__VA_ARGS__)", Space); 15086 verifyFormat("__builtin_LINE ()", Space); 15087 verifyFormat("__builtin_UNKNOWN ()", Space); 15088 15089 FormatStyle SomeSpace = getLLVMStyle(); 15090 SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses; 15091 15092 verifyFormat("[]() -> float {}", SomeSpace); 15093 verifyFormat("[] (auto foo) {}", SomeSpace); 15094 verifyFormat("[foo]() -> int {}", SomeSpace); 15095 verifyFormat("int f();", SomeSpace); 15096 verifyFormat("void f (int a, T b) {\n" 15097 " while (true)\n" 15098 " continue;\n" 15099 "}", 15100 SomeSpace); 15101 verifyFormat("if (true)\n" 15102 " f();\n" 15103 "else if (true)\n" 15104 " f();", 15105 SomeSpace); 15106 verifyFormat("do {\n" 15107 " do_something();\n" 15108 "} while (something());", 15109 SomeSpace); 15110 verifyFormat("switch (x) {\n" 15111 "default:\n" 15112 " break;\n" 15113 "}", 15114 SomeSpace); 15115 verifyFormat("A::A() : a (1) {}", SomeSpace); 15116 verifyFormat("void f() __attribute__ ((asdf));", SomeSpace); 15117 verifyFormat("*(&a + 1);\n" 15118 "&((&a)[1]);\n" 15119 "a[(b + c) * d];\n" 15120 "(((a + 1) * 2) + 3) * 4;", 15121 SomeSpace); 15122 verifyFormat("#define A(x) x", SomeSpace); 15123 verifyFormat("#define A (x) x", SomeSpace); 15124 verifyFormat("#if defined(x)\n" 15125 "#endif", 15126 SomeSpace); 15127 verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace); 15128 verifyFormat("size_t x = sizeof (x);", SomeSpace); 15129 verifyFormat("auto f (int x) -> decltype (x);", SomeSpace); 15130 verifyFormat("auto f (int x) -> typeof (x);", SomeSpace); 15131 verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace); 15132 verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace); 15133 verifyFormat("int f (T x) noexcept (x.create());", SomeSpace); 15134 verifyFormat("alignas (128) char a[128];", SomeSpace); 15135 verifyFormat("size_t x = alignof (MyType);", SomeSpace); 15136 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", 15137 SomeSpace); 15138 verifyFormat("int f() throw (Deprecated);", SomeSpace); 15139 verifyFormat("typedef void (*cb) (int);", SomeSpace); 15140 verifyFormat("T A::operator()();", SomeSpace); 15141 // FIXME these tests regressed behaviour. 15142 // verifyFormat("X A::operator++ (T);", SomeSpace); 15143 verifyFormat("int x = int (y);", SomeSpace); 15144 verifyFormat("auto lambda = []() { return 0; };", SomeSpace); 15145 15146 FormatStyle SpaceControlStatements = getLLVMStyle(); 15147 SpaceControlStatements.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15148 SpaceControlStatements.SpaceBeforeParensOptions.AfterControlStatements = true; 15149 15150 verifyFormat("while (true)\n" 15151 " continue;", 15152 SpaceControlStatements); 15153 verifyFormat("if (true)\n" 15154 " f();\n" 15155 "else if (true)\n" 15156 " f();", 15157 SpaceControlStatements); 15158 verifyFormat("for (;;) {\n" 15159 " do_something();\n" 15160 "}", 15161 SpaceControlStatements); 15162 verifyFormat("do {\n" 15163 " do_something();\n" 15164 "} while (something());", 15165 SpaceControlStatements); 15166 verifyFormat("switch (x) {\n" 15167 "default:\n" 15168 " break;\n" 15169 "}", 15170 SpaceControlStatements); 15171 15172 FormatStyle SpaceFuncDecl = getLLVMStyle(); 15173 SpaceFuncDecl.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15174 SpaceFuncDecl.SpaceBeforeParensOptions.AfterFunctionDeclarationName = true; 15175 15176 verifyFormat("int f ();", SpaceFuncDecl); 15177 verifyFormat("void f(int a, T b) {}", SpaceFuncDecl); 15178 verifyFormat("A::A() : a(1) {}", SpaceFuncDecl); 15179 verifyFormat("void f () __attribute__((asdf));", SpaceFuncDecl); 15180 verifyFormat("#define A(x) x", SpaceFuncDecl); 15181 verifyFormat("#define A (x) x", SpaceFuncDecl); 15182 verifyFormat("#if defined(x)\n" 15183 "#endif", 15184 SpaceFuncDecl); 15185 verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDecl); 15186 verifyFormat("size_t x = sizeof(x);", SpaceFuncDecl); 15187 verifyFormat("auto f (int x) -> decltype(x);", SpaceFuncDecl); 15188 verifyFormat("auto f (int x) -> typeof(x);", SpaceFuncDecl); 15189 verifyFormat("auto f (int x) -> _Atomic(x);", SpaceFuncDecl); 15190 verifyFormat("auto f (int x) -> __underlying_type(x);", SpaceFuncDecl); 15191 verifyFormat("int f (T x) noexcept(x.create());", SpaceFuncDecl); 15192 verifyFormat("alignas(128) char a[128];", SpaceFuncDecl); 15193 verifyFormat("size_t x = alignof(MyType);", SpaceFuncDecl); 15194 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", 15195 SpaceFuncDecl); 15196 verifyFormat("int f () throw(Deprecated);", SpaceFuncDecl); 15197 verifyFormat("typedef void (*cb)(int);", SpaceFuncDecl); 15198 // FIXME these tests regressed behaviour. 15199 // verifyFormat("T A::operator() ();", SpaceFuncDecl); 15200 // verifyFormat("X A::operator++ (T);", SpaceFuncDecl); 15201 verifyFormat("T A::operator()() {}", SpaceFuncDecl); 15202 verifyFormat("auto lambda = []() { return 0; };", SpaceFuncDecl); 15203 verifyFormat("int x = int(y);", SpaceFuncDecl); 15204 verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}", 15205 SpaceFuncDecl); 15206 15207 FormatStyle SpaceFuncDef = getLLVMStyle(); 15208 SpaceFuncDef.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15209 SpaceFuncDef.SpaceBeforeParensOptions.AfterFunctionDefinitionName = true; 15210 15211 verifyFormat("int f();", SpaceFuncDef); 15212 verifyFormat("void f (int a, T b) {}", SpaceFuncDef); 15213 verifyFormat("A::A() : a(1) {}", SpaceFuncDef); 15214 verifyFormat("void f() __attribute__((asdf));", SpaceFuncDef); 15215 verifyFormat("#define A(x) x", SpaceFuncDef); 15216 verifyFormat("#define A (x) x", SpaceFuncDef); 15217 verifyFormat("#if defined(x)\n" 15218 "#endif", 15219 SpaceFuncDef); 15220 verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDef); 15221 verifyFormat("size_t x = sizeof(x);", SpaceFuncDef); 15222 verifyFormat("auto f(int x) -> decltype(x);", SpaceFuncDef); 15223 verifyFormat("auto f(int x) -> typeof(x);", SpaceFuncDef); 15224 verifyFormat("auto f(int x) -> _Atomic(x);", SpaceFuncDef); 15225 verifyFormat("auto f(int x) -> __underlying_type(x);", SpaceFuncDef); 15226 verifyFormat("int f(T x) noexcept(x.create());", SpaceFuncDef); 15227 verifyFormat("alignas(128) char a[128];", SpaceFuncDef); 15228 verifyFormat("size_t x = alignof(MyType);", SpaceFuncDef); 15229 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", 15230 SpaceFuncDef); 15231 verifyFormat("int f() throw(Deprecated);", SpaceFuncDef); 15232 verifyFormat("typedef void (*cb)(int);", SpaceFuncDef); 15233 verifyFormat("T A::operator()();", SpaceFuncDef); 15234 verifyFormat("X A::operator++(T);", SpaceFuncDef); 15235 // verifyFormat("T A::operator() () {}", SpaceFuncDef); 15236 verifyFormat("auto lambda = [] () { return 0; };", SpaceFuncDef); 15237 verifyFormat("int x = int(y);", SpaceFuncDef); 15238 verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}", 15239 SpaceFuncDef); 15240 15241 FormatStyle SpaceIfMacros = getLLVMStyle(); 15242 SpaceIfMacros.IfMacros.clear(); 15243 SpaceIfMacros.IfMacros.push_back("MYIF"); 15244 SpaceIfMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15245 SpaceIfMacros.SpaceBeforeParensOptions.AfterIfMacros = true; 15246 verifyFormat("MYIF (a)\n return;", SpaceIfMacros); 15247 verifyFormat("MYIF (a)\n return;\nelse MYIF (b)\n return;", SpaceIfMacros); 15248 verifyFormat("MYIF (a)\n return;\nelse\n return;", SpaceIfMacros); 15249 15250 FormatStyle SpaceForeachMacros = getLLVMStyle(); 15251 EXPECT_EQ(SpaceForeachMacros.AllowShortBlocksOnASingleLine, 15252 FormatStyle::SBS_Never); 15253 EXPECT_EQ(SpaceForeachMacros.AllowShortLoopsOnASingleLine, false); 15254 SpaceForeachMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15255 SpaceForeachMacros.SpaceBeforeParensOptions.AfterForeachMacros = true; 15256 verifyFormat("for (;;) {\n" 15257 "}", 15258 SpaceForeachMacros); 15259 verifyFormat("foreach (Item *item, itemlist) {\n" 15260 "}", 15261 SpaceForeachMacros); 15262 verifyFormat("Q_FOREACH (Item *item, itemlist) {\n" 15263 "}", 15264 SpaceForeachMacros); 15265 verifyFormat("BOOST_FOREACH (Item *item, itemlist) {\n" 15266 "}", 15267 SpaceForeachMacros); 15268 verifyFormat("UNKNOWN_FOREACH(Item *item, itemlist) {}", SpaceForeachMacros); 15269 15270 FormatStyle SomeSpace2 = getLLVMStyle(); 15271 SomeSpace2.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15272 SomeSpace2.SpaceBeforeParensOptions.BeforeNonEmptyParentheses = true; 15273 verifyFormat("[]() -> float {}", SomeSpace2); 15274 verifyFormat("[] (auto foo) {}", SomeSpace2); 15275 verifyFormat("[foo]() -> int {}", SomeSpace2); 15276 verifyFormat("int f();", SomeSpace2); 15277 verifyFormat("void f (int a, T b) {\n" 15278 " while (true)\n" 15279 " continue;\n" 15280 "}", 15281 SomeSpace2); 15282 verifyFormat("if (true)\n" 15283 " f();\n" 15284 "else if (true)\n" 15285 " f();", 15286 SomeSpace2); 15287 verifyFormat("do {\n" 15288 " do_something();\n" 15289 "} while (something());", 15290 SomeSpace2); 15291 verifyFormat("switch (x) {\n" 15292 "default:\n" 15293 " break;\n" 15294 "}", 15295 SomeSpace2); 15296 verifyFormat("A::A() : a (1) {}", SomeSpace2); 15297 verifyFormat("void f() __attribute__ ((asdf));", SomeSpace2); 15298 verifyFormat("*(&a + 1);\n" 15299 "&((&a)[1]);\n" 15300 "a[(b + c) * d];\n" 15301 "(((a + 1) * 2) + 3) * 4;", 15302 SomeSpace2); 15303 verifyFormat("#define A(x) x", SomeSpace2); 15304 verifyFormat("#define A (x) x", SomeSpace2); 15305 verifyFormat("#if defined(x)\n" 15306 "#endif", 15307 SomeSpace2); 15308 verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace2); 15309 verifyFormat("size_t x = sizeof (x);", SomeSpace2); 15310 verifyFormat("auto f (int x) -> decltype (x);", SomeSpace2); 15311 verifyFormat("auto f (int x) -> typeof (x);", SomeSpace2); 15312 verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace2); 15313 verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace2); 15314 verifyFormat("int f (T x) noexcept (x.create());", SomeSpace2); 15315 verifyFormat("alignas (128) char a[128];", SomeSpace2); 15316 verifyFormat("size_t x = alignof (MyType);", SomeSpace2); 15317 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", 15318 SomeSpace2); 15319 verifyFormat("int f() throw (Deprecated);", SomeSpace2); 15320 verifyFormat("typedef void (*cb) (int);", SomeSpace2); 15321 verifyFormat("T A::operator()();", SomeSpace2); 15322 // verifyFormat("X A::operator++ (T);", SomeSpace2); 15323 verifyFormat("int x = int (y);", SomeSpace2); 15324 verifyFormat("auto lambda = []() { return 0; };", SomeSpace2); 15325 15326 FormatStyle SpaceAfterOverloadedOperator = getLLVMStyle(); 15327 SpaceAfterOverloadedOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15328 SpaceAfterOverloadedOperator.SpaceBeforeParensOptions 15329 .AfterOverloadedOperator = true; 15330 15331 verifyFormat("auto operator++ () -> int;", SpaceAfterOverloadedOperator); 15332 verifyFormat("X A::operator++ ();", SpaceAfterOverloadedOperator); 15333 verifyFormat("some_object.operator++ ();", SpaceAfterOverloadedOperator); 15334 verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator); 15335 15336 SpaceAfterOverloadedOperator.SpaceBeforeParensOptions 15337 .AfterOverloadedOperator = false; 15338 15339 verifyFormat("auto operator++() -> int;", SpaceAfterOverloadedOperator); 15340 verifyFormat("X A::operator++();", SpaceAfterOverloadedOperator); 15341 verifyFormat("some_object.operator++();", SpaceAfterOverloadedOperator); 15342 verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator); 15343 15344 auto SpaceAfterRequires = getLLVMStyle(); 15345 SpaceAfterRequires.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15346 EXPECT_FALSE( 15347 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause); 15348 EXPECT_FALSE( 15349 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression); 15350 verifyFormat("void f(auto x)\n" 15351 " requires requires(int i) { x + i; }\n" 15352 "{}", 15353 SpaceAfterRequires); 15354 verifyFormat("void f(auto x)\n" 15355 " requires(requires(int i) { x + i; })\n" 15356 "{}", 15357 SpaceAfterRequires); 15358 verifyFormat("if (requires(int i) { x + i; })\n" 15359 " return;", 15360 SpaceAfterRequires); 15361 verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires); 15362 verifyFormat("template <typename T>\n" 15363 " requires(Foo<T>)\n" 15364 "class Bar;", 15365 SpaceAfterRequires); 15366 15367 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true; 15368 verifyFormat("void f(auto x)\n" 15369 " requires requires(int i) { x + i; }\n" 15370 "{}", 15371 SpaceAfterRequires); 15372 verifyFormat("void f(auto x)\n" 15373 " requires (requires(int i) { x + i; })\n" 15374 "{}", 15375 SpaceAfterRequires); 15376 verifyFormat("if (requires(int i) { x + i; })\n" 15377 " return;", 15378 SpaceAfterRequires); 15379 verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires); 15380 verifyFormat("template <typename T>\n" 15381 " requires (Foo<T>)\n" 15382 "class Bar;", 15383 SpaceAfterRequires); 15384 15385 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = false; 15386 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression = true; 15387 verifyFormat("void f(auto x)\n" 15388 " requires requires (int i) { x + i; }\n" 15389 "{}", 15390 SpaceAfterRequires); 15391 verifyFormat("void f(auto x)\n" 15392 " requires(requires (int i) { x + i; })\n" 15393 "{}", 15394 SpaceAfterRequires); 15395 verifyFormat("if (requires (int i) { x + i; })\n" 15396 " return;", 15397 SpaceAfterRequires); 15398 verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires); 15399 verifyFormat("template <typename T>\n" 15400 " requires(Foo<T>)\n" 15401 "class Bar;", 15402 SpaceAfterRequires); 15403 15404 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true; 15405 verifyFormat("void f(auto x)\n" 15406 " requires requires (int i) { x + i; }\n" 15407 "{}", 15408 SpaceAfterRequires); 15409 verifyFormat("void f(auto x)\n" 15410 " requires (requires (int i) { x + i; })\n" 15411 "{}", 15412 SpaceAfterRequires); 15413 verifyFormat("if (requires (int i) { x + i; })\n" 15414 " return;", 15415 SpaceAfterRequires); 15416 verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires); 15417 verifyFormat("template <typename T>\n" 15418 " requires (Foo<T>)\n" 15419 "class Bar;", 15420 SpaceAfterRequires); 15421 } 15422 15423 TEST_F(FormatTest, SpaceAfterLogicalNot) { 15424 FormatStyle Spaces = getLLVMStyle(); 15425 Spaces.SpaceAfterLogicalNot = true; 15426 15427 verifyFormat("bool x = ! y", Spaces); 15428 verifyFormat("if (! isFailure())", Spaces); 15429 verifyFormat("if (! (a && b))", Spaces); 15430 verifyFormat("\"Error!\"", Spaces); 15431 verifyFormat("! ! x", Spaces); 15432 } 15433 15434 TEST_F(FormatTest, ConfigurableSpacesInParentheses) { 15435 FormatStyle Spaces = getLLVMStyle(); 15436 15437 Spaces.SpacesInParentheses = true; 15438 verifyFormat("do_something( ::globalVar );", Spaces); 15439 verifyFormat("call( x, y, z );", Spaces); 15440 verifyFormat("call();", Spaces); 15441 verifyFormat("std::function<void( int, int )> callback;", Spaces); 15442 verifyFormat("void inFunction() { std::function<void( int, int )> fct; }", 15443 Spaces); 15444 verifyFormat("while ( (bool)1 )\n" 15445 " continue;", 15446 Spaces); 15447 verifyFormat("for ( ;; )\n" 15448 " continue;", 15449 Spaces); 15450 verifyFormat("if ( true )\n" 15451 " f();\n" 15452 "else if ( true )\n" 15453 " f();", 15454 Spaces); 15455 verifyFormat("do {\n" 15456 " do_something( (int)i );\n" 15457 "} while ( something() );", 15458 Spaces); 15459 verifyFormat("switch ( x ) {\n" 15460 "default:\n" 15461 " break;\n" 15462 "}", 15463 Spaces); 15464 15465 Spaces.SpacesInParentheses = false; 15466 Spaces.SpacesInCStyleCastParentheses = true; 15467 verifyFormat("Type *A = ( Type * )P;", Spaces); 15468 verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces); 15469 verifyFormat("x = ( int32 )y;", Spaces); 15470 verifyFormat("int a = ( int )(2.0f);", Spaces); 15471 verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces); 15472 verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces); 15473 verifyFormat("#define x (( int )-1)", Spaces); 15474 15475 // Run the first set of tests again with: 15476 Spaces.SpacesInParentheses = false; 15477 Spaces.SpaceInEmptyParentheses = true; 15478 Spaces.SpacesInCStyleCastParentheses = true; 15479 verifyFormat("call(x, y, z);", Spaces); 15480 verifyFormat("call( );", Spaces); 15481 verifyFormat("std::function<void(int, int)> callback;", Spaces); 15482 verifyFormat("while (( bool )1)\n" 15483 " continue;", 15484 Spaces); 15485 verifyFormat("for (;;)\n" 15486 " continue;", 15487 Spaces); 15488 verifyFormat("if (true)\n" 15489 " f( );\n" 15490 "else if (true)\n" 15491 " f( );", 15492 Spaces); 15493 verifyFormat("do {\n" 15494 " do_something(( int )i);\n" 15495 "} while (something( ));", 15496 Spaces); 15497 verifyFormat("switch (x) {\n" 15498 "default:\n" 15499 " break;\n" 15500 "}", 15501 Spaces); 15502 15503 // Run the first set of tests again with: 15504 Spaces.SpaceAfterCStyleCast = true; 15505 verifyFormat("call(x, y, z);", Spaces); 15506 verifyFormat("call( );", Spaces); 15507 verifyFormat("std::function<void(int, int)> callback;", Spaces); 15508 verifyFormat("while (( bool ) 1)\n" 15509 " continue;", 15510 Spaces); 15511 verifyFormat("for (;;)\n" 15512 " continue;", 15513 Spaces); 15514 verifyFormat("if (true)\n" 15515 " f( );\n" 15516 "else if (true)\n" 15517 " f( );", 15518 Spaces); 15519 verifyFormat("do {\n" 15520 " do_something(( int ) i);\n" 15521 "} while (something( ));", 15522 Spaces); 15523 verifyFormat("switch (x) {\n" 15524 "default:\n" 15525 " break;\n" 15526 "}", 15527 Spaces); 15528 verifyFormat("#define CONF_BOOL(x) ( bool * ) ( void * ) (x)", Spaces); 15529 verifyFormat("#define CONF_BOOL(x) ( bool * ) (x)", Spaces); 15530 verifyFormat("#define CONF_BOOL(x) ( bool ) (x)", Spaces); 15531 verifyFormat("bool *y = ( bool * ) ( void * ) (x);", Spaces); 15532 verifyFormat("bool *y = ( bool * ) (x);", Spaces); 15533 15534 // Run subset of tests again with: 15535 Spaces.SpacesInCStyleCastParentheses = false; 15536 Spaces.SpaceAfterCStyleCast = true; 15537 verifyFormat("while ((bool) 1)\n" 15538 " continue;", 15539 Spaces); 15540 verifyFormat("do {\n" 15541 " do_something((int) i);\n" 15542 "} while (something( ));", 15543 Spaces); 15544 15545 verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces); 15546 verifyFormat("size_t idx = (size_t) a;", Spaces); 15547 verifyFormat("size_t idx = (size_t) (a - 1);", Spaces); 15548 verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces); 15549 verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces); 15550 verifyFormat("size_t idx = (*foo)(a - 1);", Spaces); 15551 verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces); 15552 verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (x)", Spaces); 15553 verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (int) (x)", Spaces); 15554 verifyFormat("bool *y = (bool *) (void *) (x);", Spaces); 15555 verifyFormat("bool *y = (bool *) (void *) (int) (x);", Spaces); 15556 verifyFormat("bool *y = (bool *) (void *) (int) foo(x);", Spaces); 15557 Spaces.ColumnLimit = 80; 15558 Spaces.IndentWidth = 4; 15559 Spaces.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 15560 verifyFormat("void foo( ) {\n" 15561 " size_t foo = (*(function))(\n" 15562 " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, " 15563 "BarrrrrrrrrrrrLong,\n" 15564 " FoooooooooLooooong);\n" 15565 "}", 15566 Spaces); 15567 Spaces.SpaceAfterCStyleCast = false; 15568 verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces); 15569 verifyFormat("size_t idx = (size_t)a;", Spaces); 15570 verifyFormat("size_t idx = (size_t)(a - 1);", Spaces); 15571 verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces); 15572 verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces); 15573 verifyFormat("size_t idx = (*foo)(a - 1);", Spaces); 15574 verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces); 15575 15576 verifyFormat("void foo( ) {\n" 15577 " size_t foo = (*(function))(\n" 15578 " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, " 15579 "BarrrrrrrrrrrrLong,\n" 15580 " FoooooooooLooooong);\n" 15581 "}", 15582 Spaces); 15583 } 15584 15585 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) { 15586 verifyFormat("int a[5];"); 15587 verifyFormat("a[3] += 42;"); 15588 15589 FormatStyle Spaces = getLLVMStyle(); 15590 Spaces.SpacesInSquareBrackets = true; 15591 // Not lambdas. 15592 verifyFormat("int a[ 5 ];", Spaces); 15593 verifyFormat("a[ 3 ] += 42;", Spaces); 15594 verifyFormat("constexpr char hello[]{\"hello\"};", Spaces); 15595 verifyFormat("double &operator[](int i) { return 0; }\n" 15596 "int i;", 15597 Spaces); 15598 verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces); 15599 verifyFormat("int i = a[ a ][ a ]->f();", Spaces); 15600 verifyFormat("int i = (*b)[ a ]->f();", Spaces); 15601 // Lambdas. 15602 verifyFormat("int c = []() -> int { return 2; }();\n", Spaces); 15603 verifyFormat("return [ i, args... ] {};", Spaces); 15604 verifyFormat("int foo = [ &bar ]() {};", Spaces); 15605 verifyFormat("int foo = [ = ]() {};", Spaces); 15606 verifyFormat("int foo = [ & ]() {};", Spaces); 15607 verifyFormat("int foo = [ =, &bar ]() {};", Spaces); 15608 verifyFormat("int foo = [ &bar, = ]() {};", Spaces); 15609 } 15610 15611 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) { 15612 FormatStyle NoSpaceStyle = getLLVMStyle(); 15613 verifyFormat("int a[5];", NoSpaceStyle); 15614 verifyFormat("a[3] += 42;", NoSpaceStyle); 15615 15616 verifyFormat("int a[1];", NoSpaceStyle); 15617 verifyFormat("int 1 [a];", NoSpaceStyle); 15618 verifyFormat("int a[1][2];", NoSpaceStyle); 15619 verifyFormat("a[7] = 5;", NoSpaceStyle); 15620 verifyFormat("int a = (f())[23];", NoSpaceStyle); 15621 verifyFormat("f([] {})", NoSpaceStyle); 15622 15623 FormatStyle Space = getLLVMStyle(); 15624 Space.SpaceBeforeSquareBrackets = true; 15625 verifyFormat("int c = []() -> int { return 2; }();\n", Space); 15626 verifyFormat("return [i, args...] {};", Space); 15627 15628 verifyFormat("int a [5];", Space); 15629 verifyFormat("a [3] += 42;", Space); 15630 verifyFormat("constexpr char hello []{\"hello\"};", Space); 15631 verifyFormat("double &operator[](int i) { return 0; }\n" 15632 "int i;", 15633 Space); 15634 verifyFormat("std::unique_ptr<int []> foo() {}", Space); 15635 verifyFormat("int i = a [a][a]->f();", Space); 15636 verifyFormat("int i = (*b) [a]->f();", Space); 15637 15638 verifyFormat("int a [1];", Space); 15639 verifyFormat("int 1 [a];", Space); 15640 verifyFormat("int a [1][2];", Space); 15641 verifyFormat("a [7] = 5;", Space); 15642 verifyFormat("int a = (f()) [23];", Space); 15643 verifyFormat("f([] {})", Space); 15644 } 15645 15646 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) { 15647 verifyFormat("int a = 5;"); 15648 verifyFormat("a += 42;"); 15649 verifyFormat("a or_eq 8;"); 15650 15651 FormatStyle Spaces = getLLVMStyle(); 15652 Spaces.SpaceBeforeAssignmentOperators = false; 15653 verifyFormat("int a= 5;", Spaces); 15654 verifyFormat("a+= 42;", Spaces); 15655 verifyFormat("a or_eq 8;", Spaces); 15656 } 15657 15658 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) { 15659 verifyFormat("class Foo : public Bar {};"); 15660 verifyFormat("Foo::Foo() : foo(1) {}"); 15661 verifyFormat("for (auto a : b) {\n}"); 15662 verifyFormat("int x = a ? b : c;"); 15663 verifyFormat("{\n" 15664 "label0:\n" 15665 " int x = 0;\n" 15666 "}"); 15667 verifyFormat("switch (x) {\n" 15668 "case 1:\n" 15669 "default:\n" 15670 "}"); 15671 verifyFormat("switch (allBraces) {\n" 15672 "case 1: {\n" 15673 " break;\n" 15674 "}\n" 15675 "case 2: {\n" 15676 " [[fallthrough]];\n" 15677 "}\n" 15678 "default: {\n" 15679 " break;\n" 15680 "}\n" 15681 "}"); 15682 15683 FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30); 15684 CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false; 15685 verifyFormat("class Foo : public Bar {};", CtorInitializerStyle); 15686 verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle); 15687 verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle); 15688 verifyFormat("int x = a ? b : c;", CtorInitializerStyle); 15689 verifyFormat("{\n" 15690 "label1:\n" 15691 " int x = 0;\n" 15692 "}", 15693 CtorInitializerStyle); 15694 verifyFormat("switch (x) {\n" 15695 "case 1:\n" 15696 "default:\n" 15697 "}", 15698 CtorInitializerStyle); 15699 verifyFormat("switch (allBraces) {\n" 15700 "case 1: {\n" 15701 " break;\n" 15702 "}\n" 15703 "case 2: {\n" 15704 " [[fallthrough]];\n" 15705 "}\n" 15706 "default: {\n" 15707 " break;\n" 15708 "}\n" 15709 "}", 15710 CtorInitializerStyle); 15711 CtorInitializerStyle.BreakConstructorInitializers = 15712 FormatStyle::BCIS_AfterColon; 15713 verifyFormat("Fooooooooooo::Fooooooooooo():\n" 15714 " aaaaaaaaaaaaaaaa(1),\n" 15715 " bbbbbbbbbbbbbbbb(2) {}", 15716 CtorInitializerStyle); 15717 CtorInitializerStyle.BreakConstructorInitializers = 15718 FormatStyle::BCIS_BeforeComma; 15719 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15720 " : aaaaaaaaaaaaaaaa(1)\n" 15721 " , bbbbbbbbbbbbbbbb(2) {}", 15722 CtorInitializerStyle); 15723 CtorInitializerStyle.BreakConstructorInitializers = 15724 FormatStyle::BCIS_BeforeColon; 15725 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15726 " : aaaaaaaaaaaaaaaa(1),\n" 15727 " bbbbbbbbbbbbbbbb(2) {}", 15728 CtorInitializerStyle); 15729 CtorInitializerStyle.ConstructorInitializerIndentWidth = 0; 15730 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15731 ": aaaaaaaaaaaaaaaa(1),\n" 15732 " bbbbbbbbbbbbbbbb(2) {}", 15733 CtorInitializerStyle); 15734 15735 FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30); 15736 InheritanceStyle.SpaceBeforeInheritanceColon = false; 15737 verifyFormat("class Foo: public Bar {};", InheritanceStyle); 15738 verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle); 15739 verifyFormat("for (auto a : b) {\n}", InheritanceStyle); 15740 verifyFormat("int x = a ? b : c;", InheritanceStyle); 15741 verifyFormat("{\n" 15742 "label2:\n" 15743 " int x = 0;\n" 15744 "}", 15745 InheritanceStyle); 15746 verifyFormat("switch (x) {\n" 15747 "case 1:\n" 15748 "default:\n" 15749 "}", 15750 InheritanceStyle); 15751 verifyFormat("switch (allBraces) {\n" 15752 "case 1: {\n" 15753 " break;\n" 15754 "}\n" 15755 "case 2: {\n" 15756 " [[fallthrough]];\n" 15757 "}\n" 15758 "default: {\n" 15759 " break;\n" 15760 "}\n" 15761 "}", 15762 InheritanceStyle); 15763 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterComma; 15764 verifyFormat("class Foooooooooooooooooooooo\n" 15765 " : public aaaaaaaaaaaaaaaaaa,\n" 15766 " public bbbbbbbbbbbbbbbbbb {\n" 15767 "}", 15768 InheritanceStyle); 15769 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon; 15770 verifyFormat("class Foooooooooooooooooooooo:\n" 15771 " public aaaaaaaaaaaaaaaaaa,\n" 15772 " public bbbbbbbbbbbbbbbbbb {\n" 15773 "}", 15774 InheritanceStyle); 15775 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma; 15776 verifyFormat("class Foooooooooooooooooooooo\n" 15777 " : public aaaaaaaaaaaaaaaaaa\n" 15778 " , public bbbbbbbbbbbbbbbbbb {\n" 15779 "}", 15780 InheritanceStyle); 15781 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 15782 verifyFormat("class Foooooooooooooooooooooo\n" 15783 " : public aaaaaaaaaaaaaaaaaa,\n" 15784 " public bbbbbbbbbbbbbbbbbb {\n" 15785 "}", 15786 InheritanceStyle); 15787 InheritanceStyle.ConstructorInitializerIndentWidth = 0; 15788 verifyFormat("class Foooooooooooooooooooooo\n" 15789 ": public aaaaaaaaaaaaaaaaaa,\n" 15790 " public bbbbbbbbbbbbbbbbbb {}", 15791 InheritanceStyle); 15792 15793 FormatStyle ForLoopStyle = getLLVMStyle(); 15794 ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false; 15795 verifyFormat("class Foo : public Bar {};", ForLoopStyle); 15796 verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle); 15797 verifyFormat("for (auto a: b) {\n}", ForLoopStyle); 15798 verifyFormat("int x = a ? b : c;", ForLoopStyle); 15799 verifyFormat("{\n" 15800 "label2:\n" 15801 " int x = 0;\n" 15802 "}", 15803 ForLoopStyle); 15804 verifyFormat("switch (x) {\n" 15805 "case 1:\n" 15806 "default:\n" 15807 "}", 15808 ForLoopStyle); 15809 verifyFormat("switch (allBraces) {\n" 15810 "case 1: {\n" 15811 " break;\n" 15812 "}\n" 15813 "case 2: {\n" 15814 " [[fallthrough]];\n" 15815 "}\n" 15816 "default: {\n" 15817 " break;\n" 15818 "}\n" 15819 "}", 15820 ForLoopStyle); 15821 15822 FormatStyle CaseStyle = getLLVMStyle(); 15823 CaseStyle.SpaceBeforeCaseColon = true; 15824 verifyFormat("class Foo : public Bar {};", CaseStyle); 15825 verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle); 15826 verifyFormat("for (auto a : b) {\n}", CaseStyle); 15827 verifyFormat("int x = a ? b : c;", CaseStyle); 15828 verifyFormat("switch (x) {\n" 15829 "case 1 :\n" 15830 "default :\n" 15831 "}", 15832 CaseStyle); 15833 verifyFormat("switch (allBraces) {\n" 15834 "case 1 : {\n" 15835 " break;\n" 15836 "}\n" 15837 "case 2 : {\n" 15838 " [[fallthrough]];\n" 15839 "}\n" 15840 "default : {\n" 15841 " break;\n" 15842 "}\n" 15843 "}", 15844 CaseStyle); 15845 15846 FormatStyle NoSpaceStyle = getLLVMStyle(); 15847 EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false); 15848 NoSpaceStyle.SpaceBeforeCtorInitializerColon = false; 15849 NoSpaceStyle.SpaceBeforeInheritanceColon = false; 15850 NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false; 15851 verifyFormat("class Foo: public Bar {};", NoSpaceStyle); 15852 verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle); 15853 verifyFormat("for (auto a: b) {\n}", NoSpaceStyle); 15854 verifyFormat("int x = a ? b : c;", NoSpaceStyle); 15855 verifyFormat("{\n" 15856 "label3:\n" 15857 " int x = 0;\n" 15858 "}", 15859 NoSpaceStyle); 15860 verifyFormat("switch (x) {\n" 15861 "case 1:\n" 15862 "default:\n" 15863 "}", 15864 NoSpaceStyle); 15865 verifyFormat("switch (allBraces) {\n" 15866 "case 1: {\n" 15867 " break;\n" 15868 "}\n" 15869 "case 2: {\n" 15870 " [[fallthrough]];\n" 15871 "}\n" 15872 "default: {\n" 15873 " break;\n" 15874 "}\n" 15875 "}", 15876 NoSpaceStyle); 15877 15878 FormatStyle InvertedSpaceStyle = getLLVMStyle(); 15879 InvertedSpaceStyle.SpaceBeforeCaseColon = true; 15880 InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false; 15881 InvertedSpaceStyle.SpaceBeforeInheritanceColon = false; 15882 InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false; 15883 verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle); 15884 verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle); 15885 verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle); 15886 verifyFormat("int x = a ? b : c;", InvertedSpaceStyle); 15887 verifyFormat("{\n" 15888 "label3:\n" 15889 " int x = 0;\n" 15890 "}", 15891 InvertedSpaceStyle); 15892 verifyFormat("switch (x) {\n" 15893 "case 1 :\n" 15894 "case 2 : {\n" 15895 " break;\n" 15896 "}\n" 15897 "default :\n" 15898 " break;\n" 15899 "}", 15900 InvertedSpaceStyle); 15901 verifyFormat("switch (allBraces) {\n" 15902 "case 1 : {\n" 15903 " break;\n" 15904 "}\n" 15905 "case 2 : {\n" 15906 " [[fallthrough]];\n" 15907 "}\n" 15908 "default : {\n" 15909 " break;\n" 15910 "}\n" 15911 "}", 15912 InvertedSpaceStyle); 15913 } 15914 15915 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) { 15916 FormatStyle Style = getLLVMStyle(); 15917 15918 Style.PointerAlignment = FormatStyle::PAS_Left; 15919 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default; 15920 verifyFormat("void* const* x = NULL;", Style); 15921 15922 #define verifyQualifierSpaces(Code, Pointers, Qualifiers) \ 15923 do { \ 15924 Style.PointerAlignment = FormatStyle::Pointers; \ 15925 Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers; \ 15926 verifyFormat(Code, Style); \ 15927 } while (false) 15928 15929 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default); 15930 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default); 15931 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default); 15932 15933 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before); 15934 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before); 15935 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before); 15936 15937 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After); 15938 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After); 15939 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After); 15940 15941 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both); 15942 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both); 15943 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both); 15944 15945 verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default); 15946 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, 15947 SAPQ_Default); 15948 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15949 SAPQ_Default); 15950 15951 verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before); 15952 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, 15953 SAPQ_Before); 15954 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15955 SAPQ_Before); 15956 15957 verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After); 15958 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After); 15959 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15960 SAPQ_After); 15961 15962 verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both); 15963 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both); 15964 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both); 15965 15966 #undef verifyQualifierSpaces 15967 15968 FormatStyle Spaces = getLLVMStyle(); 15969 Spaces.AttributeMacros.push_back("qualified"); 15970 Spaces.PointerAlignment = FormatStyle::PAS_Right; 15971 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default; 15972 verifyFormat("SomeType *volatile *a = NULL;", Spaces); 15973 verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces); 15974 verifyFormat("std::vector<SomeType *const *> x;", Spaces); 15975 verifyFormat("std::vector<SomeType *qualified *> x;", Spaces); 15976 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15977 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before; 15978 verifyFormat("SomeType * volatile *a = NULL;", Spaces); 15979 verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces); 15980 verifyFormat("std::vector<SomeType * const *> x;", Spaces); 15981 verifyFormat("std::vector<SomeType * qualified *> x;", Spaces); 15982 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15983 15984 // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left. 15985 Spaces.PointerAlignment = FormatStyle::PAS_Left; 15986 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before; 15987 verifyFormat("SomeType* volatile* a = NULL;", Spaces); 15988 verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces); 15989 verifyFormat("std::vector<SomeType* const*> x;", Spaces); 15990 verifyFormat("std::vector<SomeType* qualified*> x;", Spaces); 15991 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15992 // However, setting it to SAPQ_After should add spaces after __attribute, etc. 15993 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After; 15994 verifyFormat("SomeType* volatile * a = NULL;", Spaces); 15995 verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces); 15996 verifyFormat("std::vector<SomeType* const *> x;", Spaces); 15997 verifyFormat("std::vector<SomeType* qualified *> x;", Spaces); 15998 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15999 16000 // PAS_Middle should not have any noticeable changes even for SAPQ_Both 16001 Spaces.PointerAlignment = FormatStyle::PAS_Middle; 16002 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After; 16003 verifyFormat("SomeType * volatile * a = NULL;", Spaces); 16004 verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces); 16005 verifyFormat("std::vector<SomeType * const *> x;", Spaces); 16006 verifyFormat("std::vector<SomeType * qualified *> x;", Spaces); 16007 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 16008 } 16009 16010 TEST_F(FormatTest, AlignConsecutiveMacros) { 16011 FormatStyle Style = getLLVMStyle(); 16012 Style.AlignConsecutiveAssignments.Enabled = true; 16013 Style.AlignConsecutiveDeclarations.Enabled = true; 16014 16015 verifyFormat("#define a 3\n" 16016 "#define bbbb 4\n" 16017 "#define ccc (5)", 16018 Style); 16019 16020 verifyFormat("#define f(x) (x * x)\n" 16021 "#define fff(x, y, z) (x * y + z)\n" 16022 "#define ffff(x, y) (x - y)", 16023 Style); 16024 16025 verifyFormat("#define foo(x, y) (x + y)\n" 16026 "#define bar (5, 6)(2 + 2)", 16027 Style); 16028 16029 verifyFormat("#define a 3\n" 16030 "#define bbbb 4\n" 16031 "#define ccc (5)\n" 16032 "#define f(x) (x * x)\n" 16033 "#define fff(x, y, z) (x * y + z)\n" 16034 "#define ffff(x, y) (x - y)", 16035 Style); 16036 16037 Style.AlignConsecutiveMacros.Enabled = true; 16038 verifyFormat("#define a 3\n" 16039 "#define bbbb 4\n" 16040 "#define ccc (5)", 16041 Style); 16042 16043 verifyFormat("#define true 1\n" 16044 "#define false 0", 16045 Style); 16046 16047 verifyFormat("#define f(x) (x * x)\n" 16048 "#define fff(x, y, z) (x * y + z)\n" 16049 "#define ffff(x, y) (x - y)", 16050 Style); 16051 16052 verifyFormat("#define foo(x, y) (x + y)\n" 16053 "#define bar (5, 6)(2 + 2)", 16054 Style); 16055 16056 verifyFormat("#define a 3\n" 16057 "#define bbbb 4\n" 16058 "#define ccc (5)\n" 16059 "#define f(x) (x * x)\n" 16060 "#define fff(x, y, z) (x * y + z)\n" 16061 "#define ffff(x, y) (x - y)", 16062 Style); 16063 16064 verifyFormat("#define a 5\n" 16065 "#define foo(x, y) (x + y)\n" 16066 "#define CCC (6)\n" 16067 "auto lambda = []() {\n" 16068 " auto ii = 0;\n" 16069 " float j = 0;\n" 16070 " return 0;\n" 16071 "};\n" 16072 "int i = 0;\n" 16073 "float i2 = 0;\n" 16074 "auto v = type{\n" 16075 " i = 1, //\n" 16076 " (i = 2), //\n" 16077 " i = 3 //\n" 16078 "};", 16079 Style); 16080 16081 Style.AlignConsecutiveMacros.Enabled = false; 16082 Style.ColumnLimit = 20; 16083 16084 verifyFormat("#define a \\\n" 16085 " \"aabbbbbbbbbbbb\"\n" 16086 "#define D \\\n" 16087 " \"aabbbbbbbbbbbb\" \\\n" 16088 " \"ccddeeeeeeeee\"\n" 16089 "#define B \\\n" 16090 " \"QQQQQQQQQQQQQ\" \\\n" 16091 " \"FFFFFFFFFFFFF\" \\\n" 16092 " \"LLLLLLLL\"\n", 16093 Style); 16094 16095 Style.AlignConsecutiveMacros.Enabled = true; 16096 verifyFormat("#define a \\\n" 16097 " \"aabbbbbbbbbbbb\"\n" 16098 "#define D \\\n" 16099 " \"aabbbbbbbbbbbb\" \\\n" 16100 " \"ccddeeeeeeeee\"\n" 16101 "#define B \\\n" 16102 " \"QQQQQQQQQQQQQ\" \\\n" 16103 " \"FFFFFFFFFFFFF\" \\\n" 16104 " \"LLLLLLLL\"\n", 16105 Style); 16106 16107 // Test across comments 16108 Style.MaxEmptyLinesToKeep = 10; 16109 Style.ReflowComments = false; 16110 Style.AlignConsecutiveMacros.AcrossComments = true; 16111 EXPECT_EQ("#define a 3\n" 16112 "// line comment\n" 16113 "#define bbbb 4\n" 16114 "#define ccc (5)", 16115 format("#define a 3\n" 16116 "// line comment\n" 16117 "#define bbbb 4\n" 16118 "#define ccc (5)", 16119 Style)); 16120 16121 EXPECT_EQ("#define a 3\n" 16122 "/* block comment */\n" 16123 "#define bbbb 4\n" 16124 "#define ccc (5)", 16125 format("#define a 3\n" 16126 "/* block comment */\n" 16127 "#define bbbb 4\n" 16128 "#define ccc (5)", 16129 Style)); 16130 16131 EXPECT_EQ("#define a 3\n" 16132 "/* multi-line *\n" 16133 " * block comment */\n" 16134 "#define bbbb 4\n" 16135 "#define ccc (5)", 16136 format("#define a 3\n" 16137 "/* multi-line *\n" 16138 " * block comment */\n" 16139 "#define bbbb 4\n" 16140 "#define ccc (5)", 16141 Style)); 16142 16143 EXPECT_EQ("#define a 3\n" 16144 "// multi-line line comment\n" 16145 "//\n" 16146 "#define bbbb 4\n" 16147 "#define ccc (5)", 16148 format("#define a 3\n" 16149 "// multi-line line comment\n" 16150 "//\n" 16151 "#define bbbb 4\n" 16152 "#define ccc (5)", 16153 Style)); 16154 16155 EXPECT_EQ("#define a 3\n" 16156 "// empty lines still break.\n" 16157 "\n" 16158 "#define bbbb 4\n" 16159 "#define ccc (5)", 16160 format("#define a 3\n" 16161 "// empty lines still break.\n" 16162 "\n" 16163 "#define bbbb 4\n" 16164 "#define ccc (5)", 16165 Style)); 16166 16167 // Test across empty lines 16168 Style.AlignConsecutiveMacros.AcrossComments = false; 16169 Style.AlignConsecutiveMacros.AcrossEmptyLines = true; 16170 EXPECT_EQ("#define a 3\n" 16171 "\n" 16172 "#define bbbb 4\n" 16173 "#define ccc (5)", 16174 format("#define a 3\n" 16175 "\n" 16176 "#define bbbb 4\n" 16177 "#define ccc (5)", 16178 Style)); 16179 16180 EXPECT_EQ("#define a 3\n" 16181 "\n" 16182 "\n" 16183 "\n" 16184 "#define bbbb 4\n" 16185 "#define ccc (5)", 16186 format("#define a 3\n" 16187 "\n" 16188 "\n" 16189 "\n" 16190 "#define bbbb 4\n" 16191 "#define ccc (5)", 16192 Style)); 16193 16194 EXPECT_EQ("#define a 3\n" 16195 "// comments should break alignment\n" 16196 "//\n" 16197 "#define bbbb 4\n" 16198 "#define ccc (5)", 16199 format("#define a 3\n" 16200 "// comments should break alignment\n" 16201 "//\n" 16202 "#define bbbb 4\n" 16203 "#define ccc (5)", 16204 Style)); 16205 16206 // Test across empty lines and comments 16207 Style.AlignConsecutiveMacros.AcrossComments = true; 16208 verifyFormat("#define a 3\n" 16209 "\n" 16210 "// line comment\n" 16211 "#define bbbb 4\n" 16212 "#define ccc (5)", 16213 Style); 16214 16215 EXPECT_EQ("#define a 3\n" 16216 "\n" 16217 "\n" 16218 "/* multi-line *\n" 16219 " * block comment */\n" 16220 "\n" 16221 "\n" 16222 "#define bbbb 4\n" 16223 "#define ccc (5)", 16224 format("#define a 3\n" 16225 "\n" 16226 "\n" 16227 "/* multi-line *\n" 16228 " * block comment */\n" 16229 "\n" 16230 "\n" 16231 "#define bbbb 4\n" 16232 "#define ccc (5)", 16233 Style)); 16234 16235 EXPECT_EQ("#define a 3\n" 16236 "\n" 16237 "\n" 16238 "/* multi-line *\n" 16239 " * block comment */\n" 16240 "\n" 16241 "\n" 16242 "#define bbbb 4\n" 16243 "#define ccc (5)", 16244 format("#define a 3\n" 16245 "\n" 16246 "\n" 16247 "/* multi-line *\n" 16248 " * block comment */\n" 16249 "\n" 16250 "\n" 16251 "#define bbbb 4\n" 16252 "#define ccc (5)", 16253 Style)); 16254 } 16255 16256 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) { 16257 FormatStyle Alignment = getLLVMStyle(); 16258 Alignment.AlignConsecutiveMacros.Enabled = true; 16259 Alignment.AlignConsecutiveAssignments.Enabled = true; 16260 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true; 16261 16262 Alignment.MaxEmptyLinesToKeep = 10; 16263 /* Test alignment across empty lines */ 16264 EXPECT_EQ("int a = 5;\n" 16265 "\n" 16266 "int oneTwoThree = 123;", 16267 format("int a = 5;\n" 16268 "\n" 16269 "int oneTwoThree= 123;", 16270 Alignment)); 16271 EXPECT_EQ("int a = 5;\n" 16272 "int one = 1;\n" 16273 "\n" 16274 "int oneTwoThree = 123;", 16275 format("int a = 5;\n" 16276 "int one = 1;\n" 16277 "\n" 16278 "int oneTwoThree = 123;", 16279 Alignment)); 16280 EXPECT_EQ("int a = 5;\n" 16281 "int one = 1;\n" 16282 "\n" 16283 "int oneTwoThree = 123;\n" 16284 "int oneTwo = 12;", 16285 format("int a = 5;\n" 16286 "int one = 1;\n" 16287 "\n" 16288 "int oneTwoThree = 123;\n" 16289 "int oneTwo = 12;", 16290 Alignment)); 16291 16292 /* Test across comments */ 16293 EXPECT_EQ("int a = 5;\n" 16294 "/* block comment */\n" 16295 "int oneTwoThree = 123;", 16296 format("int a = 5;\n" 16297 "/* block comment */\n" 16298 "int oneTwoThree=123;", 16299 Alignment)); 16300 16301 EXPECT_EQ("int a = 5;\n" 16302 "// line comment\n" 16303 "int oneTwoThree = 123;", 16304 format("int a = 5;\n" 16305 "// line comment\n" 16306 "int oneTwoThree=123;", 16307 Alignment)); 16308 16309 /* Test across comments and newlines */ 16310 EXPECT_EQ("int a = 5;\n" 16311 "\n" 16312 "/* block comment */\n" 16313 "int oneTwoThree = 123;", 16314 format("int a = 5;\n" 16315 "\n" 16316 "/* block comment */\n" 16317 "int oneTwoThree=123;", 16318 Alignment)); 16319 16320 EXPECT_EQ("int a = 5;\n" 16321 "\n" 16322 "// line comment\n" 16323 "int oneTwoThree = 123;", 16324 format("int a = 5;\n" 16325 "\n" 16326 "// line comment\n" 16327 "int oneTwoThree=123;", 16328 Alignment)); 16329 } 16330 16331 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) { 16332 FormatStyle Alignment = getLLVMStyle(); 16333 Alignment.AlignConsecutiveDeclarations.Enabled = true; 16334 Alignment.AlignConsecutiveDeclarations.AcrossEmptyLines = true; 16335 Alignment.AlignConsecutiveDeclarations.AcrossComments = true; 16336 16337 Alignment.MaxEmptyLinesToKeep = 10; 16338 /* Test alignment across empty lines */ 16339 EXPECT_EQ("int a = 5;\n" 16340 "\n" 16341 "float const oneTwoThree = 123;", 16342 format("int a = 5;\n" 16343 "\n" 16344 "float const oneTwoThree = 123;", 16345 Alignment)); 16346 EXPECT_EQ("int a = 5;\n" 16347 "float const one = 1;\n" 16348 "\n" 16349 "int oneTwoThree = 123;", 16350 format("int a = 5;\n" 16351 "float const one = 1;\n" 16352 "\n" 16353 "int oneTwoThree = 123;", 16354 Alignment)); 16355 16356 /* Test across comments */ 16357 EXPECT_EQ("float const a = 5;\n" 16358 "/* block comment */\n" 16359 "int oneTwoThree = 123;", 16360 format("float const a = 5;\n" 16361 "/* block comment */\n" 16362 "int oneTwoThree=123;", 16363 Alignment)); 16364 16365 EXPECT_EQ("float const a = 5;\n" 16366 "// line comment\n" 16367 "int oneTwoThree = 123;", 16368 format("float const a = 5;\n" 16369 "// line comment\n" 16370 "int oneTwoThree=123;", 16371 Alignment)); 16372 16373 /* Test across comments and newlines */ 16374 EXPECT_EQ("float const a = 5;\n" 16375 "\n" 16376 "/* block comment */\n" 16377 "int oneTwoThree = 123;", 16378 format("float const a = 5;\n" 16379 "\n" 16380 "/* block comment */\n" 16381 "int oneTwoThree=123;", 16382 Alignment)); 16383 16384 EXPECT_EQ("float const a = 5;\n" 16385 "\n" 16386 "// line comment\n" 16387 "int oneTwoThree = 123;", 16388 format("float const a = 5;\n" 16389 "\n" 16390 "// line comment\n" 16391 "int oneTwoThree=123;", 16392 Alignment)); 16393 } 16394 16395 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) { 16396 FormatStyle Alignment = getLLVMStyle(); 16397 Alignment.AlignConsecutiveBitFields.Enabled = true; 16398 Alignment.AlignConsecutiveBitFields.AcrossEmptyLines = true; 16399 Alignment.AlignConsecutiveBitFields.AcrossComments = true; 16400 16401 Alignment.MaxEmptyLinesToKeep = 10; 16402 /* Test alignment across empty lines */ 16403 EXPECT_EQ("int a : 5;\n" 16404 "\n" 16405 "int longbitfield : 6;", 16406 format("int a : 5;\n" 16407 "\n" 16408 "int longbitfield : 6;", 16409 Alignment)); 16410 EXPECT_EQ("int a : 5;\n" 16411 "int one : 1;\n" 16412 "\n" 16413 "int longbitfield : 6;", 16414 format("int a : 5;\n" 16415 "int one : 1;\n" 16416 "\n" 16417 "int longbitfield : 6;", 16418 Alignment)); 16419 16420 /* Test across comments */ 16421 EXPECT_EQ("int a : 5;\n" 16422 "/* block comment */\n" 16423 "int longbitfield : 6;", 16424 format("int a : 5;\n" 16425 "/* block comment */\n" 16426 "int longbitfield : 6;", 16427 Alignment)); 16428 EXPECT_EQ("int a : 5;\n" 16429 "int one : 1;\n" 16430 "// line comment\n" 16431 "int longbitfield : 6;", 16432 format("int a : 5;\n" 16433 "int one : 1;\n" 16434 "// line comment\n" 16435 "int longbitfield : 6;", 16436 Alignment)); 16437 16438 /* Test across comments and newlines */ 16439 EXPECT_EQ("int a : 5;\n" 16440 "/* block comment */\n" 16441 "\n" 16442 "int longbitfield : 6;", 16443 format("int a : 5;\n" 16444 "/* block comment */\n" 16445 "\n" 16446 "int longbitfield : 6;", 16447 Alignment)); 16448 EXPECT_EQ("int a : 5;\n" 16449 "int one : 1;\n" 16450 "\n" 16451 "// line comment\n" 16452 "\n" 16453 "int longbitfield : 6;", 16454 format("int a : 5;\n" 16455 "int one : 1;\n" 16456 "\n" 16457 "// line comment \n" 16458 "\n" 16459 "int longbitfield : 6;", 16460 Alignment)); 16461 } 16462 16463 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) { 16464 FormatStyle Alignment = getLLVMStyle(); 16465 Alignment.AlignConsecutiveMacros.Enabled = true; 16466 Alignment.AlignConsecutiveAssignments.Enabled = true; 16467 Alignment.AlignConsecutiveAssignments.AcrossComments = true; 16468 16469 Alignment.MaxEmptyLinesToKeep = 10; 16470 /* Test alignment across empty lines */ 16471 EXPECT_EQ("int a = 5;\n" 16472 "\n" 16473 "int oneTwoThree = 123;", 16474 format("int a = 5;\n" 16475 "\n" 16476 "int oneTwoThree= 123;", 16477 Alignment)); 16478 EXPECT_EQ("int a = 5;\n" 16479 "int one = 1;\n" 16480 "\n" 16481 "int oneTwoThree = 123;", 16482 format("int a = 5;\n" 16483 "int one = 1;\n" 16484 "\n" 16485 "int oneTwoThree = 123;", 16486 Alignment)); 16487 16488 /* Test across comments */ 16489 EXPECT_EQ("int a = 5;\n" 16490 "/* block comment */\n" 16491 "int oneTwoThree = 123;", 16492 format("int a = 5;\n" 16493 "/* block comment */\n" 16494 "int oneTwoThree=123;", 16495 Alignment)); 16496 16497 EXPECT_EQ("int a = 5;\n" 16498 "// line comment\n" 16499 "int oneTwoThree = 123;", 16500 format("int a = 5;\n" 16501 "// line comment\n" 16502 "int oneTwoThree=123;", 16503 Alignment)); 16504 16505 EXPECT_EQ("int a = 5;\n" 16506 "/*\n" 16507 " * multi-line block comment\n" 16508 " */\n" 16509 "int oneTwoThree = 123;", 16510 format("int a = 5;\n" 16511 "/*\n" 16512 " * multi-line block comment\n" 16513 " */\n" 16514 "int oneTwoThree=123;", 16515 Alignment)); 16516 16517 EXPECT_EQ("int a = 5;\n" 16518 "//\n" 16519 "// multi-line line comment\n" 16520 "//\n" 16521 "int oneTwoThree = 123;", 16522 format("int a = 5;\n" 16523 "//\n" 16524 "// multi-line line comment\n" 16525 "//\n" 16526 "int oneTwoThree=123;", 16527 Alignment)); 16528 16529 /* Test across comments and newlines */ 16530 EXPECT_EQ("int a = 5;\n" 16531 "\n" 16532 "/* block comment */\n" 16533 "int oneTwoThree = 123;", 16534 format("int a = 5;\n" 16535 "\n" 16536 "/* block comment */\n" 16537 "int oneTwoThree=123;", 16538 Alignment)); 16539 16540 EXPECT_EQ("int a = 5;\n" 16541 "\n" 16542 "// line comment\n" 16543 "int oneTwoThree = 123;", 16544 format("int a = 5;\n" 16545 "\n" 16546 "// line comment\n" 16547 "int oneTwoThree=123;", 16548 Alignment)); 16549 } 16550 16551 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) { 16552 FormatStyle Alignment = getLLVMStyle(); 16553 Alignment.AlignConsecutiveMacros.Enabled = true; 16554 Alignment.AlignConsecutiveAssignments.Enabled = true; 16555 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true; 16556 Alignment.AlignConsecutiveAssignments.AcrossComments = true; 16557 verifyFormat("int a = 5;\n" 16558 "int oneTwoThree = 123;", 16559 Alignment); 16560 verifyFormat("int a = method();\n" 16561 "int oneTwoThree = 133;", 16562 Alignment); 16563 verifyFormat("a &= 5;\n" 16564 "bcd *= 5;\n" 16565 "ghtyf += 5;\n" 16566 "dvfvdb -= 5;\n" 16567 "a /= 5;\n" 16568 "vdsvsv %= 5;\n" 16569 "sfdbddfbdfbb ^= 5;\n" 16570 "dvsdsv |= 5;\n" 16571 "int dsvvdvsdvvv = 123;", 16572 Alignment); 16573 verifyFormat("int i = 1, j = 10;\n" 16574 "something = 2000;", 16575 Alignment); 16576 verifyFormat("something = 2000;\n" 16577 "int i = 1, j = 10;\n", 16578 Alignment); 16579 verifyFormat("something = 2000;\n" 16580 "another = 911;\n" 16581 "int i = 1, j = 10;\n" 16582 "oneMore = 1;\n" 16583 "i = 2;", 16584 Alignment); 16585 verifyFormat("int a = 5;\n" 16586 "int one = 1;\n" 16587 "method();\n" 16588 "int oneTwoThree = 123;\n" 16589 "int oneTwo = 12;", 16590 Alignment); 16591 verifyFormat("int oneTwoThree = 123;\n" 16592 "int oneTwo = 12;\n" 16593 "method();\n", 16594 Alignment); 16595 verifyFormat("int oneTwoThree = 123; // comment\n" 16596 "int oneTwo = 12; // comment", 16597 Alignment); 16598 16599 // Bug 25167 16600 /* Uncomment when fixed 16601 verifyFormat("#if A\n" 16602 "#else\n" 16603 "int aaaaaaaa = 12;\n" 16604 "#endif\n" 16605 "#if B\n" 16606 "#else\n" 16607 "int a = 12;\n" 16608 "#endif\n", 16609 Alignment); 16610 verifyFormat("enum foo {\n" 16611 "#if A\n" 16612 "#else\n" 16613 " aaaaaaaa = 12;\n" 16614 "#endif\n" 16615 "#if B\n" 16616 "#else\n" 16617 " a = 12;\n" 16618 "#endif\n" 16619 "};\n", 16620 Alignment); 16621 */ 16622 16623 Alignment.MaxEmptyLinesToKeep = 10; 16624 /* Test alignment across empty lines */ 16625 EXPECT_EQ("int a = 5;\n" 16626 "\n" 16627 "int oneTwoThree = 123;", 16628 format("int a = 5;\n" 16629 "\n" 16630 "int oneTwoThree= 123;", 16631 Alignment)); 16632 EXPECT_EQ("int a = 5;\n" 16633 "int one = 1;\n" 16634 "\n" 16635 "int oneTwoThree = 123;", 16636 format("int a = 5;\n" 16637 "int one = 1;\n" 16638 "\n" 16639 "int oneTwoThree = 123;", 16640 Alignment)); 16641 EXPECT_EQ("int a = 5;\n" 16642 "int one = 1;\n" 16643 "\n" 16644 "int oneTwoThree = 123;\n" 16645 "int oneTwo = 12;", 16646 format("int a = 5;\n" 16647 "int one = 1;\n" 16648 "\n" 16649 "int oneTwoThree = 123;\n" 16650 "int oneTwo = 12;", 16651 Alignment)); 16652 16653 /* Test across comments */ 16654 EXPECT_EQ("int a = 5;\n" 16655 "/* block comment */\n" 16656 "int oneTwoThree = 123;", 16657 format("int a = 5;\n" 16658 "/* block comment */\n" 16659 "int oneTwoThree=123;", 16660 Alignment)); 16661 16662 EXPECT_EQ("int a = 5;\n" 16663 "// line comment\n" 16664 "int oneTwoThree = 123;", 16665 format("int a = 5;\n" 16666 "// line comment\n" 16667 "int oneTwoThree=123;", 16668 Alignment)); 16669 16670 /* Test across comments and newlines */ 16671 EXPECT_EQ("int a = 5;\n" 16672 "\n" 16673 "/* block comment */\n" 16674 "int oneTwoThree = 123;", 16675 format("int a = 5;\n" 16676 "\n" 16677 "/* block comment */\n" 16678 "int oneTwoThree=123;", 16679 Alignment)); 16680 16681 EXPECT_EQ("int a = 5;\n" 16682 "\n" 16683 "// line comment\n" 16684 "int oneTwoThree = 123;", 16685 format("int a = 5;\n" 16686 "\n" 16687 "// line comment\n" 16688 "int oneTwoThree=123;", 16689 Alignment)); 16690 16691 EXPECT_EQ("int a = 5;\n" 16692 "//\n" 16693 "// multi-line line comment\n" 16694 "//\n" 16695 "int oneTwoThree = 123;", 16696 format("int a = 5;\n" 16697 "//\n" 16698 "// multi-line line comment\n" 16699 "//\n" 16700 "int oneTwoThree=123;", 16701 Alignment)); 16702 16703 EXPECT_EQ("int a = 5;\n" 16704 "/*\n" 16705 " * multi-line block comment\n" 16706 " */\n" 16707 "int oneTwoThree = 123;", 16708 format("int a = 5;\n" 16709 "/*\n" 16710 " * multi-line block comment\n" 16711 " */\n" 16712 "int oneTwoThree=123;", 16713 Alignment)); 16714 16715 EXPECT_EQ("int a = 5;\n" 16716 "\n" 16717 "/* block comment */\n" 16718 "\n" 16719 "\n" 16720 "\n" 16721 "int oneTwoThree = 123;", 16722 format("int a = 5;\n" 16723 "\n" 16724 "/* block comment */\n" 16725 "\n" 16726 "\n" 16727 "\n" 16728 "int oneTwoThree=123;", 16729 Alignment)); 16730 16731 EXPECT_EQ("int a = 5;\n" 16732 "\n" 16733 "// line comment\n" 16734 "\n" 16735 "\n" 16736 "\n" 16737 "int oneTwoThree = 123;", 16738 format("int a = 5;\n" 16739 "\n" 16740 "// line comment\n" 16741 "\n" 16742 "\n" 16743 "\n" 16744 "int oneTwoThree=123;", 16745 Alignment)); 16746 16747 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 16748 verifyFormat("#define A \\\n" 16749 " int aaaa = 12; \\\n" 16750 " int b = 23; \\\n" 16751 " int ccc = 234; \\\n" 16752 " int dddddddddd = 2345;", 16753 Alignment); 16754 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 16755 verifyFormat("#define A \\\n" 16756 " int aaaa = 12; \\\n" 16757 " int b = 23; \\\n" 16758 " int ccc = 234; \\\n" 16759 " int dddddddddd = 2345;", 16760 Alignment); 16761 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 16762 verifyFormat("#define A " 16763 " \\\n" 16764 " int aaaa = 12; " 16765 " \\\n" 16766 " int b = 23; " 16767 " \\\n" 16768 " int ccc = 234; " 16769 " \\\n" 16770 " int dddddddddd = 2345;", 16771 Alignment); 16772 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 16773 "k = 4, int l = 5,\n" 16774 " int m = 6) {\n" 16775 " int j = 10;\n" 16776 " otherThing = 1;\n" 16777 "}", 16778 Alignment); 16779 verifyFormat("void SomeFunction(int parameter = 0) {\n" 16780 " int i = 1;\n" 16781 " int j = 2;\n" 16782 " int big = 10000;\n" 16783 "}", 16784 Alignment); 16785 verifyFormat("class C {\n" 16786 "public:\n" 16787 " int i = 1;\n" 16788 " virtual void f() = 0;\n" 16789 "};", 16790 Alignment); 16791 verifyFormat("int i = 1;\n" 16792 "if (SomeType t = getSomething()) {\n" 16793 "}\n" 16794 "int j = 2;\n" 16795 "int big = 10000;", 16796 Alignment); 16797 verifyFormat("int j = 7;\n" 16798 "for (int k = 0; k < N; ++k) {\n" 16799 "}\n" 16800 "int j = 2;\n" 16801 "int big = 10000;\n" 16802 "}", 16803 Alignment); 16804 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 16805 verifyFormat("int i = 1;\n" 16806 "LooooooooooongType loooooooooooooooooooooongVariable\n" 16807 " = someLooooooooooooooooongFunction();\n" 16808 "int j = 2;", 16809 Alignment); 16810 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 16811 verifyFormat("int i = 1;\n" 16812 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 16813 " someLooooooooooooooooongFunction();\n" 16814 "int j = 2;", 16815 Alignment); 16816 16817 verifyFormat("auto lambda = []() {\n" 16818 " auto i = 0;\n" 16819 " return 0;\n" 16820 "};\n" 16821 "int i = 0;\n" 16822 "auto v = type{\n" 16823 " i = 1, //\n" 16824 " (i = 2), //\n" 16825 " i = 3 //\n" 16826 "};", 16827 Alignment); 16828 16829 verifyFormat( 16830 "int i = 1;\n" 16831 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 16832 " loooooooooooooooooooooongParameterB);\n" 16833 "int j = 2;", 16834 Alignment); 16835 16836 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n" 16837 " typename B = very_long_type_name_1,\n" 16838 " typename T_2 = very_long_type_name_2>\n" 16839 "auto foo() {}\n", 16840 Alignment); 16841 verifyFormat("int a, b = 1;\n" 16842 "int c = 2;\n" 16843 "int dd = 3;\n", 16844 Alignment); 16845 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 16846 "float b[1][] = {{3.f}};\n", 16847 Alignment); 16848 verifyFormat("for (int i = 0; i < 1; i++)\n" 16849 " int x = 1;\n", 16850 Alignment); 16851 verifyFormat("for (i = 0; i < 1; i++)\n" 16852 " x = 1;\n" 16853 "y = 1;\n", 16854 Alignment); 16855 16856 Alignment.ReflowComments = true; 16857 Alignment.ColumnLimit = 50; 16858 EXPECT_EQ("int x = 0;\n" 16859 "int yy = 1; /// specificlennospace\n" 16860 "int zzz = 2;\n", 16861 format("int x = 0;\n" 16862 "int yy = 1; ///specificlennospace\n" 16863 "int zzz = 2;\n", 16864 Alignment)); 16865 } 16866 16867 TEST_F(FormatTest, AlignCompoundAssignments) { 16868 FormatStyle Alignment = getLLVMStyle(); 16869 Alignment.AlignConsecutiveAssignments.Enabled = true; 16870 Alignment.AlignConsecutiveAssignments.AlignCompound = true; 16871 Alignment.AlignConsecutiveAssignments.PadOperators = false; 16872 verifyFormat("sfdbddfbdfbb = 5;\n" 16873 "dvsdsv = 5;\n" 16874 "int dsvvdvsdvvv = 123;", 16875 Alignment); 16876 verifyFormat("sfdbddfbdfbb ^= 5;\n" 16877 "dvsdsv |= 5;\n" 16878 "int dsvvdvsdvvv = 123;", 16879 Alignment); 16880 verifyFormat("sfdbddfbdfbb ^= 5;\n" 16881 "dvsdsv <<= 5;\n" 16882 "int dsvvdvsdvvv = 123;", 16883 Alignment); 16884 // Test that `<=` is not treated as a compound assignment. 16885 verifyFormat("aa &= 5;\n" 16886 "b <= 10;\n" 16887 "c = 15;", 16888 Alignment); 16889 Alignment.AlignConsecutiveAssignments.PadOperators = true; 16890 verifyFormat("sfdbddfbdfbb = 5;\n" 16891 "dvsdsv = 5;\n" 16892 "int dsvvdvsdvvv = 123;", 16893 Alignment); 16894 verifyFormat("sfdbddfbdfbb ^= 5;\n" 16895 "dvsdsv |= 5;\n" 16896 "int dsvvdvsdvvv = 123;", 16897 Alignment); 16898 verifyFormat("sfdbddfbdfbb ^= 5;\n" 16899 "dvsdsv <<= 5;\n" 16900 "int dsvvdvsdvvv = 123;", 16901 Alignment); 16902 EXPECT_EQ("a += 5;\n" 16903 "one = 1;\n" 16904 "\n" 16905 "oneTwoThree = 123;\n", 16906 format("a += 5;\n" 16907 "one = 1;\n" 16908 "\n" 16909 "oneTwoThree = 123;\n", 16910 Alignment)); 16911 EXPECT_EQ("a += 5;\n" 16912 "one = 1;\n" 16913 "//\n" 16914 "oneTwoThree = 123;\n", 16915 format("a += 5;\n" 16916 "one = 1;\n" 16917 "//\n" 16918 "oneTwoThree = 123;\n", 16919 Alignment)); 16920 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true; 16921 EXPECT_EQ("a += 5;\n" 16922 "one = 1;\n" 16923 "\n" 16924 "oneTwoThree = 123;\n", 16925 format("a += 5;\n" 16926 "one = 1;\n" 16927 "\n" 16928 "oneTwoThree = 123;\n", 16929 Alignment)); 16930 EXPECT_EQ("a += 5;\n" 16931 "one = 1;\n" 16932 "//\n" 16933 "oneTwoThree = 123;\n", 16934 format("a += 5;\n" 16935 "one = 1;\n" 16936 "//\n" 16937 "oneTwoThree = 123;\n", 16938 Alignment)); 16939 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = false; 16940 Alignment.AlignConsecutiveAssignments.AcrossComments = true; 16941 EXPECT_EQ("a += 5;\n" 16942 "one = 1;\n" 16943 "\n" 16944 "oneTwoThree = 123;\n", 16945 format("a += 5;\n" 16946 "one = 1;\n" 16947 "\n" 16948 "oneTwoThree = 123;\n", 16949 Alignment)); 16950 EXPECT_EQ("a += 5;\n" 16951 "one = 1;\n" 16952 "//\n" 16953 "oneTwoThree = 123;\n", 16954 format("a += 5;\n" 16955 "one = 1;\n" 16956 "//\n" 16957 "oneTwoThree = 123;\n", 16958 Alignment)); 16959 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true; 16960 EXPECT_EQ("a += 5;\n" 16961 "one >>= 1;\n" 16962 "\n" 16963 "oneTwoThree = 123;\n", 16964 format("a += 5;\n" 16965 "one >>= 1;\n" 16966 "\n" 16967 "oneTwoThree = 123;\n", 16968 Alignment)); 16969 EXPECT_EQ("a += 5;\n" 16970 "one = 1;\n" 16971 "//\n" 16972 "oneTwoThree <<= 123;\n", 16973 format("a += 5;\n" 16974 "one = 1;\n" 16975 "//\n" 16976 "oneTwoThree <<= 123;\n", 16977 Alignment)); 16978 } 16979 16980 TEST_F(FormatTest, AlignConsecutiveAssignments) { 16981 FormatStyle Alignment = getLLVMStyle(); 16982 Alignment.AlignConsecutiveMacros.Enabled = true; 16983 verifyFormat("int a = 5;\n" 16984 "int oneTwoThree = 123;", 16985 Alignment); 16986 verifyFormat("int a = 5;\n" 16987 "int oneTwoThree = 123;", 16988 Alignment); 16989 16990 Alignment.AlignConsecutiveAssignments.Enabled = true; 16991 verifyFormat("int a = 5;\n" 16992 "int oneTwoThree = 123;", 16993 Alignment); 16994 verifyFormat("int a = method();\n" 16995 "int oneTwoThree = 133;", 16996 Alignment); 16997 verifyFormat("aa <= 5;\n" 16998 "a &= 5;\n" 16999 "bcd *= 5;\n" 17000 "ghtyf += 5;\n" 17001 "dvfvdb -= 5;\n" 17002 "a /= 5;\n" 17003 "vdsvsv %= 5;\n" 17004 "sfdbddfbdfbb ^= 5;\n" 17005 "dvsdsv |= 5;\n" 17006 "int dsvvdvsdvvv = 123;", 17007 Alignment); 17008 verifyFormat("int i = 1, j = 10;\n" 17009 "something = 2000;", 17010 Alignment); 17011 verifyFormat("something = 2000;\n" 17012 "int i = 1, j = 10;\n", 17013 Alignment); 17014 verifyFormat("something = 2000;\n" 17015 "another = 911;\n" 17016 "int i = 1, j = 10;\n" 17017 "oneMore = 1;\n" 17018 "i = 2;", 17019 Alignment); 17020 verifyFormat("int a = 5;\n" 17021 "int one = 1;\n" 17022 "method();\n" 17023 "int oneTwoThree = 123;\n" 17024 "int oneTwo = 12;", 17025 Alignment); 17026 verifyFormat("int oneTwoThree = 123;\n" 17027 "int oneTwo = 12;\n" 17028 "method();\n", 17029 Alignment); 17030 verifyFormat("int oneTwoThree = 123; // comment\n" 17031 "int oneTwo = 12; // comment", 17032 Alignment); 17033 verifyFormat("int f() = default;\n" 17034 "int &operator() = default;\n" 17035 "int &operator=() {", 17036 Alignment); 17037 verifyFormat("int f() = delete;\n" 17038 "int &operator() = delete;\n" 17039 "int &operator=() {", 17040 Alignment); 17041 verifyFormat("int f() = default; // comment\n" 17042 "int &operator() = default; // comment\n" 17043 "int &operator=() {", 17044 Alignment); 17045 verifyFormat("int f() = default;\n" 17046 "int &operator() = default;\n" 17047 "int &operator==() {", 17048 Alignment); 17049 verifyFormat("int f() = default;\n" 17050 "int &operator() = default;\n" 17051 "int &operator<=() {", 17052 Alignment); 17053 verifyFormat("int f() = default;\n" 17054 "int &operator() = default;\n" 17055 "int &operator!=() {", 17056 Alignment); 17057 verifyFormat("int f() = default;\n" 17058 "int &operator() = default;\n" 17059 "int &operator=();", 17060 Alignment); 17061 verifyFormat("int f() = delete;\n" 17062 "int &operator() = delete;\n" 17063 "int &operator=();", 17064 Alignment); 17065 verifyFormat("/* long long padding */ int f() = default;\n" 17066 "int &operator() = default;\n" 17067 "int &operator/**/ =();", 17068 Alignment); 17069 // https://llvm.org/PR33697 17070 FormatStyle AlignmentWithPenalty = getLLVMStyle(); 17071 AlignmentWithPenalty.AlignConsecutiveAssignments.Enabled = true; 17072 AlignmentWithPenalty.PenaltyReturnTypeOnItsOwnLine = 5000; 17073 verifyFormat("class SSSSSSSSSSSSSSSSSSSSSSSSSSSS {\n" 17074 " void f() = delete;\n" 17075 " SSSSSSSSSSSSSSSSSSSSSSSSSSSS &operator=(\n" 17076 " const SSSSSSSSSSSSSSSSSSSSSSSSSSSS &other) = delete;\n" 17077 "};\n", 17078 AlignmentWithPenalty); 17079 17080 // Bug 25167 17081 /* Uncomment when fixed 17082 verifyFormat("#if A\n" 17083 "#else\n" 17084 "int aaaaaaaa = 12;\n" 17085 "#endif\n" 17086 "#if B\n" 17087 "#else\n" 17088 "int a = 12;\n" 17089 "#endif\n", 17090 Alignment); 17091 verifyFormat("enum foo {\n" 17092 "#if A\n" 17093 "#else\n" 17094 " aaaaaaaa = 12;\n" 17095 "#endif\n" 17096 "#if B\n" 17097 "#else\n" 17098 " a = 12;\n" 17099 "#endif\n" 17100 "};\n", 17101 Alignment); 17102 */ 17103 17104 EXPECT_EQ("int a = 5;\n" 17105 "\n" 17106 "int oneTwoThree = 123;", 17107 format("int a = 5;\n" 17108 "\n" 17109 "int oneTwoThree= 123;", 17110 Alignment)); 17111 EXPECT_EQ("int a = 5;\n" 17112 "int one = 1;\n" 17113 "\n" 17114 "int oneTwoThree = 123;", 17115 format("int a = 5;\n" 17116 "int one = 1;\n" 17117 "\n" 17118 "int oneTwoThree = 123;", 17119 Alignment)); 17120 EXPECT_EQ("int a = 5;\n" 17121 "int one = 1;\n" 17122 "\n" 17123 "int oneTwoThree = 123;\n" 17124 "int oneTwo = 12;", 17125 format("int a = 5;\n" 17126 "int one = 1;\n" 17127 "\n" 17128 "int oneTwoThree = 123;\n" 17129 "int oneTwo = 12;", 17130 Alignment)); 17131 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 17132 verifyFormat("#define A \\\n" 17133 " int aaaa = 12; \\\n" 17134 " int b = 23; \\\n" 17135 " int ccc = 234; \\\n" 17136 " int dddddddddd = 2345;", 17137 Alignment); 17138 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 17139 verifyFormat("#define A \\\n" 17140 " int aaaa = 12; \\\n" 17141 " int b = 23; \\\n" 17142 " int ccc = 234; \\\n" 17143 " int dddddddddd = 2345;", 17144 Alignment); 17145 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 17146 verifyFormat("#define A " 17147 " \\\n" 17148 " int aaaa = 12; " 17149 " \\\n" 17150 " int b = 23; " 17151 " \\\n" 17152 " int ccc = 234; " 17153 " \\\n" 17154 " int dddddddddd = 2345;", 17155 Alignment); 17156 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 17157 "k = 4, int l = 5,\n" 17158 " int m = 6) {\n" 17159 " int j = 10;\n" 17160 " otherThing = 1;\n" 17161 "}", 17162 Alignment); 17163 verifyFormat("void SomeFunction(int parameter = 0) {\n" 17164 " int i = 1;\n" 17165 " int j = 2;\n" 17166 " int big = 10000;\n" 17167 "}", 17168 Alignment); 17169 verifyFormat("class C {\n" 17170 "public:\n" 17171 " int i = 1;\n" 17172 " virtual void f() = 0;\n" 17173 "};", 17174 Alignment); 17175 verifyFormat("int i = 1;\n" 17176 "if (SomeType t = getSomething()) {\n" 17177 "}\n" 17178 "int j = 2;\n" 17179 "int big = 10000;", 17180 Alignment); 17181 verifyFormat("int j = 7;\n" 17182 "for (int k = 0; k < N; ++k) {\n" 17183 "}\n" 17184 "int j = 2;\n" 17185 "int big = 10000;\n" 17186 "}", 17187 Alignment); 17188 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 17189 verifyFormat("int i = 1;\n" 17190 "LooooooooooongType loooooooooooooooooooooongVariable\n" 17191 " = someLooooooooooooooooongFunction();\n" 17192 "int j = 2;", 17193 Alignment); 17194 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 17195 verifyFormat("int i = 1;\n" 17196 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 17197 " someLooooooooooooooooongFunction();\n" 17198 "int j = 2;", 17199 Alignment); 17200 17201 verifyFormat("auto lambda = []() {\n" 17202 " auto i = 0;\n" 17203 " return 0;\n" 17204 "};\n" 17205 "int i = 0;\n" 17206 "auto v = type{\n" 17207 " i = 1, //\n" 17208 " (i = 2), //\n" 17209 " i = 3 //\n" 17210 "};", 17211 Alignment); 17212 17213 verifyFormat( 17214 "int i = 1;\n" 17215 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 17216 " loooooooooooooooooooooongParameterB);\n" 17217 "int j = 2;", 17218 Alignment); 17219 17220 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n" 17221 " typename B = very_long_type_name_1,\n" 17222 " typename T_2 = very_long_type_name_2>\n" 17223 "auto foo() {}\n", 17224 Alignment); 17225 verifyFormat("int a, b = 1;\n" 17226 "int c = 2;\n" 17227 "int dd = 3;\n", 17228 Alignment); 17229 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17230 "float b[1][] = {{3.f}};\n", 17231 Alignment); 17232 verifyFormat("for (int i = 0; i < 1; i++)\n" 17233 " int x = 1;\n", 17234 Alignment); 17235 verifyFormat("for (i = 0; i < 1; i++)\n" 17236 " x = 1;\n" 17237 "y = 1;\n", 17238 Alignment); 17239 17240 EXPECT_EQ(Alignment.ReflowComments, true); 17241 Alignment.ColumnLimit = 50; 17242 EXPECT_EQ("int x = 0;\n" 17243 "int yy = 1; /// specificlennospace\n" 17244 "int zzz = 2;\n", 17245 format("int x = 0;\n" 17246 "int yy = 1; ///specificlennospace\n" 17247 "int zzz = 2;\n", 17248 Alignment)); 17249 17250 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17251 "auto b = [] {\n" 17252 " f();\n" 17253 " return;\n" 17254 "};", 17255 Alignment); 17256 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17257 "auto b = g([] {\n" 17258 " f();\n" 17259 " return;\n" 17260 "});", 17261 Alignment); 17262 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17263 "auto b = g(param, [] {\n" 17264 " f();\n" 17265 " return;\n" 17266 "});", 17267 Alignment); 17268 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17269 "auto b = [] {\n" 17270 " if (condition) {\n" 17271 " return;\n" 17272 " }\n" 17273 "};", 17274 Alignment); 17275 17276 verifyFormat("auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 17277 " ccc ? aaaaa : bbbbb,\n" 17278 " dddddddddddddddddddddddddd);", 17279 Alignment); 17280 // FIXME: https://llvm.org/PR53497 17281 // verifyFormat("auto aaaaaaaaaaaa = f();\n" 17282 // "auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 17283 // " ccc ? aaaaa : bbbbb,\n" 17284 // " dddddddddddddddddddddddddd);", 17285 // Alignment); 17286 } 17287 17288 TEST_F(FormatTest, AlignConsecutiveBitFields) { 17289 FormatStyle Alignment = getLLVMStyle(); 17290 Alignment.AlignConsecutiveBitFields.Enabled = true; 17291 verifyFormat("int const a : 5;\n" 17292 "int oneTwoThree : 23;", 17293 Alignment); 17294 17295 // Initializers are allowed starting with c++2a 17296 verifyFormat("int const a : 5 = 1;\n" 17297 "int oneTwoThree : 23 = 0;", 17298 Alignment); 17299 17300 Alignment.AlignConsecutiveDeclarations.Enabled = true; 17301 verifyFormat("int const a : 5;\n" 17302 "int oneTwoThree : 23;", 17303 Alignment); 17304 17305 verifyFormat("int const a : 5; // comment\n" 17306 "int oneTwoThree : 23; // comment", 17307 Alignment); 17308 17309 verifyFormat("int const a : 5 = 1;\n" 17310 "int oneTwoThree : 23 = 0;", 17311 Alignment); 17312 17313 Alignment.AlignConsecutiveAssignments.Enabled = true; 17314 verifyFormat("int const a : 5 = 1;\n" 17315 "int oneTwoThree : 23 = 0;", 17316 Alignment); 17317 verifyFormat("int const a : 5 = {1};\n" 17318 "int oneTwoThree : 23 = 0;", 17319 Alignment); 17320 17321 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None; 17322 verifyFormat("int const a :5;\n" 17323 "int oneTwoThree:23;", 17324 Alignment); 17325 17326 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before; 17327 verifyFormat("int const a :5;\n" 17328 "int oneTwoThree :23;", 17329 Alignment); 17330 17331 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After; 17332 verifyFormat("int const a : 5;\n" 17333 "int oneTwoThree: 23;", 17334 Alignment); 17335 17336 // Known limitations: ':' is only recognized as a bitfield colon when 17337 // followed by a number. 17338 /* 17339 verifyFormat("int oneTwoThree : SOME_CONSTANT;\n" 17340 "int a : 5;", 17341 Alignment); 17342 */ 17343 } 17344 17345 TEST_F(FormatTest, AlignConsecutiveDeclarations) { 17346 FormatStyle Alignment = getLLVMStyle(); 17347 Alignment.AlignConsecutiveMacros.Enabled = true; 17348 Alignment.PointerAlignment = FormatStyle::PAS_Right; 17349 verifyFormat("float const a = 5;\n" 17350 "int oneTwoThree = 123;", 17351 Alignment); 17352 verifyFormat("int a = 5;\n" 17353 "float const oneTwoThree = 123;", 17354 Alignment); 17355 17356 Alignment.AlignConsecutiveDeclarations.Enabled = true; 17357 verifyFormat("float const a = 5;\n" 17358 "int oneTwoThree = 123;", 17359 Alignment); 17360 verifyFormat("int a = method();\n" 17361 "float const oneTwoThree = 133;", 17362 Alignment); 17363 verifyFormat("int i = 1, j = 10;\n" 17364 "something = 2000;", 17365 Alignment); 17366 verifyFormat("something = 2000;\n" 17367 "int i = 1, j = 10;\n", 17368 Alignment); 17369 verifyFormat("float something = 2000;\n" 17370 "double another = 911;\n" 17371 "int i = 1, j = 10;\n" 17372 "const int *oneMore = 1;\n" 17373 "unsigned i = 2;", 17374 Alignment); 17375 verifyFormat("float a = 5;\n" 17376 "int one = 1;\n" 17377 "method();\n" 17378 "const double oneTwoThree = 123;\n" 17379 "const unsigned int oneTwo = 12;", 17380 Alignment); 17381 verifyFormat("int oneTwoThree{0}; // comment\n" 17382 "unsigned oneTwo; // comment", 17383 Alignment); 17384 verifyFormat("unsigned int *a;\n" 17385 "int *b;\n" 17386 "unsigned int Const *c;\n" 17387 "unsigned int const *d;\n" 17388 "unsigned int Const &e;\n" 17389 "unsigned int const &f;", 17390 Alignment); 17391 verifyFormat("Const unsigned int *c;\n" 17392 "const unsigned int *d;\n" 17393 "Const unsigned int &e;\n" 17394 "const unsigned int &f;\n" 17395 "const unsigned g;\n" 17396 "Const unsigned h;", 17397 Alignment); 17398 EXPECT_EQ("float const a = 5;\n" 17399 "\n" 17400 "int oneTwoThree = 123;", 17401 format("float const a = 5;\n" 17402 "\n" 17403 "int oneTwoThree= 123;", 17404 Alignment)); 17405 EXPECT_EQ("float a = 5;\n" 17406 "int one = 1;\n" 17407 "\n" 17408 "unsigned oneTwoThree = 123;", 17409 format("float a = 5;\n" 17410 "int one = 1;\n" 17411 "\n" 17412 "unsigned oneTwoThree = 123;", 17413 Alignment)); 17414 EXPECT_EQ("float a = 5;\n" 17415 "int one = 1;\n" 17416 "\n" 17417 "unsigned oneTwoThree = 123;\n" 17418 "int oneTwo = 12;", 17419 format("float a = 5;\n" 17420 "int one = 1;\n" 17421 "\n" 17422 "unsigned oneTwoThree = 123;\n" 17423 "int oneTwo = 12;", 17424 Alignment)); 17425 // Function prototype alignment 17426 verifyFormat("int a();\n" 17427 "double b();", 17428 Alignment); 17429 verifyFormat("int a(int x);\n" 17430 "double b();", 17431 Alignment); 17432 unsigned OldColumnLimit = Alignment.ColumnLimit; 17433 // We need to set ColumnLimit to zero, in order to stress nested alignments, 17434 // otherwise the function parameters will be re-flowed onto a single line. 17435 Alignment.ColumnLimit = 0; 17436 EXPECT_EQ("int a(int x,\n" 17437 " float y);\n" 17438 "double b(int x,\n" 17439 " double y);", 17440 format("int a(int x,\n" 17441 " float y);\n" 17442 "double b(int x,\n" 17443 " double y);", 17444 Alignment)); 17445 // This ensures that function parameters of function declarations are 17446 // correctly indented when their owning functions are indented. 17447 // The failure case here is for 'double y' to not be indented enough. 17448 EXPECT_EQ("double a(int x);\n" 17449 "int b(int y,\n" 17450 " double z);", 17451 format("double a(int x);\n" 17452 "int b(int y,\n" 17453 " double z);", 17454 Alignment)); 17455 // Set ColumnLimit low so that we induce wrapping immediately after 17456 // the function name and opening paren. 17457 Alignment.ColumnLimit = 13; 17458 verifyFormat("int function(\n" 17459 " int x,\n" 17460 " bool y);", 17461 Alignment); 17462 Alignment.ColumnLimit = OldColumnLimit; 17463 // Ensure function pointers don't screw up recursive alignment 17464 verifyFormat("int a(int x, void (*fp)(int y));\n" 17465 "double b();", 17466 Alignment); 17467 Alignment.AlignConsecutiveAssignments.Enabled = true; 17468 // Ensure recursive alignment is broken by function braces, so that the 17469 // "a = 1" does not align with subsequent assignments inside the function 17470 // body. 17471 verifyFormat("int func(int a = 1) {\n" 17472 " int b = 2;\n" 17473 " int cc = 3;\n" 17474 "}", 17475 Alignment); 17476 verifyFormat("float something = 2000;\n" 17477 "double another = 911;\n" 17478 "int i = 1, j = 10;\n" 17479 "const int *oneMore = 1;\n" 17480 "unsigned i = 2;", 17481 Alignment); 17482 verifyFormat("int oneTwoThree = {0}; // comment\n" 17483 "unsigned oneTwo = 0; // comment", 17484 Alignment); 17485 // Make sure that scope is correctly tracked, in the absence of braces 17486 verifyFormat("for (int i = 0; i < n; i++)\n" 17487 " j = i;\n" 17488 "double x = 1;\n", 17489 Alignment); 17490 verifyFormat("if (int i = 0)\n" 17491 " j = i;\n" 17492 "double x = 1;\n", 17493 Alignment); 17494 // Ensure operator[] and operator() are comprehended 17495 verifyFormat("struct test {\n" 17496 " long long int foo();\n" 17497 " int operator[](int a);\n" 17498 " double bar();\n" 17499 "};\n", 17500 Alignment); 17501 verifyFormat("struct test {\n" 17502 " long long int foo();\n" 17503 " int operator()(int a);\n" 17504 " double bar();\n" 17505 "};\n", 17506 Alignment); 17507 // http://llvm.org/PR52914 17508 verifyFormat("char *a[] = {\"a\", // comment\n" 17509 " \"bb\"};\n" 17510 "int bbbbbbb = 0;", 17511 Alignment); 17512 17513 // PAS_Right 17514 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17515 " int const i = 1;\n" 17516 " int *j = 2;\n" 17517 " int big = 10000;\n" 17518 "\n" 17519 " unsigned oneTwoThree = 123;\n" 17520 " int oneTwo = 12;\n" 17521 " method();\n" 17522 " float k = 2;\n" 17523 " int ll = 10000;\n" 17524 "}", 17525 format("void SomeFunction(int parameter= 0) {\n" 17526 " int const i= 1;\n" 17527 " int *j=2;\n" 17528 " int big = 10000;\n" 17529 "\n" 17530 "unsigned oneTwoThree =123;\n" 17531 "int oneTwo = 12;\n" 17532 " method();\n" 17533 "float k= 2;\n" 17534 "int ll=10000;\n" 17535 "}", 17536 Alignment)); 17537 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17538 " int const i = 1;\n" 17539 " int **j = 2, ***k;\n" 17540 " int &k = i;\n" 17541 " int &&l = i + j;\n" 17542 " int big = 10000;\n" 17543 "\n" 17544 " unsigned oneTwoThree = 123;\n" 17545 " int oneTwo = 12;\n" 17546 " method();\n" 17547 " float k = 2;\n" 17548 " int ll = 10000;\n" 17549 "}", 17550 format("void SomeFunction(int parameter= 0) {\n" 17551 " int const i= 1;\n" 17552 " int **j=2,***k;\n" 17553 "int &k=i;\n" 17554 "int &&l=i+j;\n" 17555 " int big = 10000;\n" 17556 "\n" 17557 "unsigned oneTwoThree =123;\n" 17558 "int oneTwo = 12;\n" 17559 " method();\n" 17560 "float k= 2;\n" 17561 "int ll=10000;\n" 17562 "}", 17563 Alignment)); 17564 // variables are aligned at their name, pointers are at the right most 17565 // position 17566 verifyFormat("int *a;\n" 17567 "int **b;\n" 17568 "int ***c;\n" 17569 "int foobar;\n", 17570 Alignment); 17571 17572 // PAS_Left 17573 FormatStyle AlignmentLeft = Alignment; 17574 AlignmentLeft.PointerAlignment = FormatStyle::PAS_Left; 17575 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17576 " int const i = 1;\n" 17577 " int* j = 2;\n" 17578 " int big = 10000;\n" 17579 "\n" 17580 " unsigned oneTwoThree = 123;\n" 17581 " int oneTwo = 12;\n" 17582 " method();\n" 17583 " float k = 2;\n" 17584 " int ll = 10000;\n" 17585 "}", 17586 format("void SomeFunction(int parameter= 0) {\n" 17587 " int const i= 1;\n" 17588 " int *j=2;\n" 17589 " int big = 10000;\n" 17590 "\n" 17591 "unsigned oneTwoThree =123;\n" 17592 "int oneTwo = 12;\n" 17593 " method();\n" 17594 "float k= 2;\n" 17595 "int ll=10000;\n" 17596 "}", 17597 AlignmentLeft)); 17598 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17599 " int const i = 1;\n" 17600 " int** j = 2;\n" 17601 " int& k = i;\n" 17602 " int&& l = i + j;\n" 17603 " int big = 10000;\n" 17604 "\n" 17605 " unsigned oneTwoThree = 123;\n" 17606 " int oneTwo = 12;\n" 17607 " method();\n" 17608 " float k = 2;\n" 17609 " int ll = 10000;\n" 17610 "}", 17611 format("void SomeFunction(int parameter= 0) {\n" 17612 " int const i= 1;\n" 17613 " int **j=2;\n" 17614 "int &k=i;\n" 17615 "int &&l=i+j;\n" 17616 " int big = 10000;\n" 17617 "\n" 17618 "unsigned oneTwoThree =123;\n" 17619 "int oneTwo = 12;\n" 17620 " method();\n" 17621 "float k= 2;\n" 17622 "int ll=10000;\n" 17623 "}", 17624 AlignmentLeft)); 17625 // variables are aligned at their name, pointers are at the left most position 17626 verifyFormat("int* a;\n" 17627 "int** b;\n" 17628 "int*** c;\n" 17629 "int foobar;\n", 17630 AlignmentLeft); 17631 17632 // PAS_Middle 17633 FormatStyle AlignmentMiddle = Alignment; 17634 AlignmentMiddle.PointerAlignment = FormatStyle::PAS_Middle; 17635 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17636 " int const i = 1;\n" 17637 " int * j = 2;\n" 17638 " int big = 10000;\n" 17639 "\n" 17640 " unsigned oneTwoThree = 123;\n" 17641 " int oneTwo = 12;\n" 17642 " method();\n" 17643 " float k = 2;\n" 17644 " int ll = 10000;\n" 17645 "}", 17646 format("void SomeFunction(int parameter= 0) {\n" 17647 " int const i= 1;\n" 17648 " int *j=2;\n" 17649 " int big = 10000;\n" 17650 "\n" 17651 "unsigned oneTwoThree =123;\n" 17652 "int oneTwo = 12;\n" 17653 " method();\n" 17654 "float k= 2;\n" 17655 "int ll=10000;\n" 17656 "}", 17657 AlignmentMiddle)); 17658 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17659 " int const i = 1;\n" 17660 " int ** j = 2, ***k;\n" 17661 " int & k = i;\n" 17662 " int && l = i + j;\n" 17663 " int big = 10000;\n" 17664 "\n" 17665 " unsigned oneTwoThree = 123;\n" 17666 " int oneTwo = 12;\n" 17667 " method();\n" 17668 " float k = 2;\n" 17669 " int ll = 10000;\n" 17670 "}", 17671 format("void SomeFunction(int parameter= 0) {\n" 17672 " int const i= 1;\n" 17673 " int **j=2,***k;\n" 17674 "int &k=i;\n" 17675 "int &&l=i+j;\n" 17676 " int big = 10000;\n" 17677 "\n" 17678 "unsigned oneTwoThree =123;\n" 17679 "int oneTwo = 12;\n" 17680 " method();\n" 17681 "float k= 2;\n" 17682 "int ll=10000;\n" 17683 "}", 17684 AlignmentMiddle)); 17685 // variables are aligned at their name, pointers are in the middle 17686 verifyFormat("int * a;\n" 17687 "int * b;\n" 17688 "int *** c;\n" 17689 "int foobar;\n", 17690 AlignmentMiddle); 17691 17692 Alignment.AlignConsecutiveAssignments.Enabled = false; 17693 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 17694 verifyFormat("#define A \\\n" 17695 " int aaaa = 12; \\\n" 17696 " float b = 23; \\\n" 17697 " const int ccc = 234; \\\n" 17698 " unsigned dddddddddd = 2345;", 17699 Alignment); 17700 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 17701 verifyFormat("#define A \\\n" 17702 " int aaaa = 12; \\\n" 17703 " float b = 23; \\\n" 17704 " const int ccc = 234; \\\n" 17705 " unsigned dddddddddd = 2345;", 17706 Alignment); 17707 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 17708 Alignment.ColumnLimit = 30; 17709 verifyFormat("#define A \\\n" 17710 " int aaaa = 12; \\\n" 17711 " float b = 23; \\\n" 17712 " const int ccc = 234; \\\n" 17713 " int dddddddddd = 2345;", 17714 Alignment); 17715 Alignment.ColumnLimit = 80; 17716 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 17717 "k = 4, int l = 5,\n" 17718 " int m = 6) {\n" 17719 " const int j = 10;\n" 17720 " otherThing = 1;\n" 17721 "}", 17722 Alignment); 17723 verifyFormat("void SomeFunction(int parameter = 0) {\n" 17724 " int const i = 1;\n" 17725 " int *j = 2;\n" 17726 " int big = 10000;\n" 17727 "}", 17728 Alignment); 17729 verifyFormat("class C {\n" 17730 "public:\n" 17731 " int i = 1;\n" 17732 " virtual void f() = 0;\n" 17733 "};", 17734 Alignment); 17735 verifyFormat("float i = 1;\n" 17736 "if (SomeType t = getSomething()) {\n" 17737 "}\n" 17738 "const unsigned j = 2;\n" 17739 "int big = 10000;", 17740 Alignment); 17741 verifyFormat("float j = 7;\n" 17742 "for (int k = 0; k < N; ++k) {\n" 17743 "}\n" 17744 "unsigned j = 2;\n" 17745 "int big = 10000;\n" 17746 "}", 17747 Alignment); 17748 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 17749 verifyFormat("float i = 1;\n" 17750 "LooooooooooongType loooooooooooooooooooooongVariable\n" 17751 " = someLooooooooooooooooongFunction();\n" 17752 "int j = 2;", 17753 Alignment); 17754 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 17755 verifyFormat("int i = 1;\n" 17756 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 17757 " someLooooooooooooooooongFunction();\n" 17758 "int j = 2;", 17759 Alignment); 17760 17761 Alignment.AlignConsecutiveAssignments.Enabled = true; 17762 verifyFormat("auto lambda = []() {\n" 17763 " auto ii = 0;\n" 17764 " float j = 0;\n" 17765 " return 0;\n" 17766 "};\n" 17767 "int i = 0;\n" 17768 "float i2 = 0;\n" 17769 "auto v = type{\n" 17770 " i = 1, //\n" 17771 " (i = 2), //\n" 17772 " i = 3 //\n" 17773 "};", 17774 Alignment); 17775 Alignment.AlignConsecutiveAssignments.Enabled = false; 17776 17777 verifyFormat( 17778 "int i = 1;\n" 17779 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 17780 " loooooooooooooooooooooongParameterB);\n" 17781 "int j = 2;", 17782 Alignment); 17783 17784 // Test interactions with ColumnLimit and AlignConsecutiveAssignments: 17785 // We expect declarations and assignments to align, as long as it doesn't 17786 // exceed the column limit, starting a new alignment sequence whenever it 17787 // happens. 17788 Alignment.AlignConsecutiveAssignments.Enabled = true; 17789 Alignment.ColumnLimit = 30; 17790 verifyFormat("float ii = 1;\n" 17791 "unsigned j = 2;\n" 17792 "int someVerylongVariable = 1;\n" 17793 "AnotherLongType ll = 123456;\n" 17794 "VeryVeryLongType k = 2;\n" 17795 "int myvar = 1;", 17796 Alignment); 17797 Alignment.ColumnLimit = 80; 17798 Alignment.AlignConsecutiveAssignments.Enabled = false; 17799 17800 verifyFormat( 17801 "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n" 17802 " typename LongType, typename B>\n" 17803 "auto foo() {}\n", 17804 Alignment); 17805 verifyFormat("float a, b = 1;\n" 17806 "int c = 2;\n" 17807 "int dd = 3;\n", 17808 Alignment); 17809 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17810 "float b[1][] = {{3.f}};\n", 17811 Alignment); 17812 Alignment.AlignConsecutiveAssignments.Enabled = true; 17813 verifyFormat("float a, b = 1;\n" 17814 "int c = 2;\n" 17815 "int dd = 3;\n", 17816 Alignment); 17817 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17818 "float b[1][] = {{3.f}};\n", 17819 Alignment); 17820 Alignment.AlignConsecutiveAssignments.Enabled = false; 17821 17822 Alignment.ColumnLimit = 30; 17823 Alignment.BinPackParameters = false; 17824 verifyFormat("void foo(float a,\n" 17825 " float b,\n" 17826 " int c,\n" 17827 " uint32_t *d) {\n" 17828 " int *e = 0;\n" 17829 " float f = 0;\n" 17830 " double g = 0;\n" 17831 "}\n" 17832 "void bar(ino_t a,\n" 17833 " int b,\n" 17834 " uint32_t *c,\n" 17835 " bool d) {}\n", 17836 Alignment); 17837 Alignment.BinPackParameters = true; 17838 Alignment.ColumnLimit = 80; 17839 17840 // Bug 33507 17841 Alignment.PointerAlignment = FormatStyle::PAS_Middle; 17842 verifyFormat( 17843 "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n" 17844 " static const Version verVs2017;\n" 17845 " return true;\n" 17846 "});\n", 17847 Alignment); 17848 Alignment.PointerAlignment = FormatStyle::PAS_Right; 17849 17850 // See llvm.org/PR35641 17851 Alignment.AlignConsecutiveDeclarations.Enabled = true; 17852 verifyFormat("int func() { //\n" 17853 " int b;\n" 17854 " unsigned c;\n" 17855 "}", 17856 Alignment); 17857 17858 // See PR37175 17859 FormatStyle Style = getMozillaStyle(); 17860 Style.AlignConsecutiveDeclarations.Enabled = true; 17861 EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n" 17862 "foo(int a);", 17863 format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style)); 17864 17865 Alignment.PointerAlignment = FormatStyle::PAS_Left; 17866 verifyFormat("unsigned int* a;\n" 17867 "int* b;\n" 17868 "unsigned int Const* c;\n" 17869 "unsigned int const* d;\n" 17870 "unsigned int Const& e;\n" 17871 "unsigned int const& f;", 17872 Alignment); 17873 verifyFormat("Const unsigned int* c;\n" 17874 "const unsigned int* d;\n" 17875 "Const unsigned int& e;\n" 17876 "const unsigned int& f;\n" 17877 "const unsigned g;\n" 17878 "Const unsigned h;", 17879 Alignment); 17880 17881 Alignment.PointerAlignment = FormatStyle::PAS_Middle; 17882 verifyFormat("unsigned int * a;\n" 17883 "int * b;\n" 17884 "unsigned int Const * c;\n" 17885 "unsigned int const * d;\n" 17886 "unsigned int Const & e;\n" 17887 "unsigned int const & f;", 17888 Alignment); 17889 verifyFormat("Const unsigned int * c;\n" 17890 "const unsigned int * d;\n" 17891 "Const unsigned int & e;\n" 17892 "const unsigned int & f;\n" 17893 "const unsigned g;\n" 17894 "Const unsigned h;", 17895 Alignment); 17896 17897 // See PR46529 17898 FormatStyle BracedAlign = getLLVMStyle(); 17899 BracedAlign.AlignConsecutiveDeclarations.Enabled = true; 17900 verifyFormat("const auto result{[]() {\n" 17901 " const auto something = 1;\n" 17902 " return 2;\n" 17903 "}};", 17904 BracedAlign); 17905 verifyFormat("int foo{[]() {\n" 17906 " int bar{0};\n" 17907 " return 0;\n" 17908 "}()};", 17909 BracedAlign); 17910 BracedAlign.Cpp11BracedListStyle = false; 17911 verifyFormat("const auto result{ []() {\n" 17912 " const auto something = 1;\n" 17913 " return 2;\n" 17914 "} };", 17915 BracedAlign); 17916 verifyFormat("int foo{ []() {\n" 17917 " int bar{ 0 };\n" 17918 " return 0;\n" 17919 "}() };", 17920 BracedAlign); 17921 } 17922 17923 TEST_F(FormatTest, AlignWithLineBreaks) { 17924 auto Style = getLLVMStyleWithColumns(120); 17925 17926 EXPECT_EQ(Style.AlignConsecutiveAssignments, 17927 FormatStyle::AlignConsecutiveStyle( 17928 {/*Enabled=*/false, /*AcrossEmptyLines=*/false, 17929 /*AcrossComments=*/false, /*AlignCompound=*/false, 17930 /*PadOperators=*/true})); 17931 EXPECT_EQ(Style.AlignConsecutiveDeclarations, 17932 FormatStyle::AlignConsecutiveStyle({})); 17933 verifyFormat("void foo() {\n" 17934 " int myVar = 5;\n" 17935 " double x = 3.14;\n" 17936 " auto str = \"Hello \"\n" 17937 " \"World\";\n" 17938 " auto s = \"Hello \"\n" 17939 " \"Again\";\n" 17940 "}", 17941 Style); 17942 17943 // clang-format off 17944 verifyFormat("void foo() {\n" 17945 " const int capacityBefore = Entries.capacity();\n" 17946 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17947 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17948 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17949 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17950 "}", 17951 Style); 17952 // clang-format on 17953 17954 Style.AlignConsecutiveAssignments.Enabled = true; 17955 verifyFormat("void foo() {\n" 17956 " int myVar = 5;\n" 17957 " double x = 3.14;\n" 17958 " auto str = \"Hello \"\n" 17959 " \"World\";\n" 17960 " auto s = \"Hello \"\n" 17961 " \"Again\";\n" 17962 "}", 17963 Style); 17964 17965 // clang-format off 17966 verifyFormat("void foo() {\n" 17967 " const int capacityBefore = Entries.capacity();\n" 17968 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17969 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17970 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17971 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17972 "}", 17973 Style); 17974 // clang-format on 17975 17976 Style.AlignConsecutiveAssignments.Enabled = false; 17977 Style.AlignConsecutiveDeclarations.Enabled = true; 17978 verifyFormat("void foo() {\n" 17979 " int myVar = 5;\n" 17980 " double x = 3.14;\n" 17981 " auto str = \"Hello \"\n" 17982 " \"World\";\n" 17983 " auto s = \"Hello \"\n" 17984 " \"Again\";\n" 17985 "}", 17986 Style); 17987 17988 // clang-format off 17989 verifyFormat("void foo() {\n" 17990 " const int capacityBefore = Entries.capacity();\n" 17991 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17992 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17993 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17994 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17995 "}", 17996 Style); 17997 // clang-format on 17998 17999 Style.AlignConsecutiveAssignments.Enabled = true; 18000 Style.AlignConsecutiveDeclarations.Enabled = true; 18001 18002 verifyFormat("void foo() {\n" 18003 " int myVar = 5;\n" 18004 " double x = 3.14;\n" 18005 " auto str = \"Hello \"\n" 18006 " \"World\";\n" 18007 " auto s = \"Hello \"\n" 18008 " \"Again\";\n" 18009 "}", 18010 Style); 18011 18012 // clang-format off 18013 verifyFormat("void foo() {\n" 18014 " const int capacityBefore = Entries.capacity();\n" 18015 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 18016 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 18017 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 18018 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 18019 "}", 18020 Style); 18021 // clang-format on 18022 18023 Style = getLLVMStyleWithColumns(20); 18024 Style.AlignConsecutiveAssignments.Enabled = true; 18025 Style.IndentWidth = 4; 18026 18027 verifyFormat("void foo() {\n" 18028 " int i1 = 1;\n" 18029 " int j = 0;\n" 18030 " int k = bar(\n" 18031 " argument1,\n" 18032 " argument2);\n" 18033 "}", 18034 Style); 18035 18036 verifyFormat("unsigned i = 0;\n" 18037 "int a[] = {\n" 18038 " 1234567890,\n" 18039 " -1234567890};", 18040 Style); 18041 18042 Style.ColumnLimit = 120; 18043 18044 // clang-format off 18045 verifyFormat("void SomeFunc() {\n" 18046 " newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 18047 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 18048 " newWatcher.maxAge = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 18049 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 18050 " newWatcher.max = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 18051 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 18052 "}", 18053 Style); 18054 // clang-format on 18055 18056 Style.BinPackArguments = false; 18057 18058 // clang-format off 18059 verifyFormat("void SomeFunc() {\n" 18060 " newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(\n" 18061 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 18062 " newWatcher.maxAge = ToLegacyTimestamp(GetMaxAge(\n" 18063 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 18064 " newWatcher.max = ToLegacyTimestamp(GetMaxAge(\n" 18065 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 18066 "}", 18067 Style); 18068 // clang-format on 18069 } 18070 18071 TEST_F(FormatTest, AlignWithInitializerPeriods) { 18072 auto Style = getLLVMStyleWithColumns(60); 18073 18074 verifyFormat("void foo1(void) {\n" 18075 " BYTE p[1] = 1;\n" 18076 " A B = {.one_foooooooooooooooo = 2,\n" 18077 " .two_fooooooooooooo = 3,\n" 18078 " .three_fooooooooooooo = 4};\n" 18079 " BYTE payload = 2;\n" 18080 "}", 18081 Style); 18082 18083 Style.AlignConsecutiveAssignments.Enabled = true; 18084 Style.AlignConsecutiveDeclarations.Enabled = false; 18085 verifyFormat("void foo2(void) {\n" 18086 " BYTE p[1] = 1;\n" 18087 " A B = {.one_foooooooooooooooo = 2,\n" 18088 " .two_fooooooooooooo = 3,\n" 18089 " .three_fooooooooooooo = 4};\n" 18090 " BYTE payload = 2;\n" 18091 "}", 18092 Style); 18093 18094 Style.AlignConsecutiveAssignments.Enabled = false; 18095 Style.AlignConsecutiveDeclarations.Enabled = true; 18096 verifyFormat("void foo3(void) {\n" 18097 " BYTE p[1] = 1;\n" 18098 " A B = {.one_foooooooooooooooo = 2,\n" 18099 " .two_fooooooooooooo = 3,\n" 18100 " .three_fooooooooooooo = 4};\n" 18101 " BYTE payload = 2;\n" 18102 "}", 18103 Style); 18104 18105 Style.AlignConsecutiveAssignments.Enabled = true; 18106 Style.AlignConsecutiveDeclarations.Enabled = true; 18107 verifyFormat("void foo4(void) {\n" 18108 " BYTE p[1] = 1;\n" 18109 " A B = {.one_foooooooooooooooo = 2,\n" 18110 " .two_fooooooooooooo = 3,\n" 18111 " .three_fooooooooooooo = 4};\n" 18112 " BYTE payload = 2;\n" 18113 "}", 18114 Style); 18115 } 18116 18117 TEST_F(FormatTest, LinuxBraceBreaking) { 18118 FormatStyle LinuxBraceStyle = getLLVMStyle(); 18119 LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux; 18120 verifyFormat("namespace a\n" 18121 "{\n" 18122 "class A\n" 18123 "{\n" 18124 " void f()\n" 18125 " {\n" 18126 " if (true) {\n" 18127 " a();\n" 18128 " b();\n" 18129 " } else {\n" 18130 " a();\n" 18131 " }\n" 18132 " }\n" 18133 " void g() { return; }\n" 18134 "};\n" 18135 "struct B {\n" 18136 " int x;\n" 18137 "};\n" 18138 "} // namespace a\n", 18139 LinuxBraceStyle); 18140 verifyFormat("enum X {\n" 18141 " Y = 0,\n" 18142 "}\n", 18143 LinuxBraceStyle); 18144 verifyFormat("struct S {\n" 18145 " int Type;\n" 18146 " union {\n" 18147 " int x;\n" 18148 " double y;\n" 18149 " } Value;\n" 18150 " class C\n" 18151 " {\n" 18152 " MyFavoriteType Value;\n" 18153 " } Class;\n" 18154 "}\n", 18155 LinuxBraceStyle); 18156 } 18157 18158 TEST_F(FormatTest, MozillaBraceBreaking) { 18159 FormatStyle MozillaBraceStyle = getLLVMStyle(); 18160 MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla; 18161 MozillaBraceStyle.FixNamespaceComments = false; 18162 verifyFormat("namespace a {\n" 18163 "class A\n" 18164 "{\n" 18165 " void f()\n" 18166 " {\n" 18167 " if (true) {\n" 18168 " a();\n" 18169 " b();\n" 18170 " }\n" 18171 " }\n" 18172 " void g() { return; }\n" 18173 "};\n" 18174 "enum E\n" 18175 "{\n" 18176 " A,\n" 18177 " // foo\n" 18178 " B,\n" 18179 " C\n" 18180 "};\n" 18181 "struct B\n" 18182 "{\n" 18183 " int x;\n" 18184 "};\n" 18185 "}\n", 18186 MozillaBraceStyle); 18187 verifyFormat("struct S\n" 18188 "{\n" 18189 " int Type;\n" 18190 " union\n" 18191 " {\n" 18192 " int x;\n" 18193 " double y;\n" 18194 " } Value;\n" 18195 " class C\n" 18196 " {\n" 18197 " MyFavoriteType Value;\n" 18198 " } Class;\n" 18199 "}\n", 18200 MozillaBraceStyle); 18201 } 18202 18203 TEST_F(FormatTest, StroustrupBraceBreaking) { 18204 FormatStyle StroustrupBraceStyle = getLLVMStyle(); 18205 StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 18206 verifyFormat("namespace a {\n" 18207 "class A {\n" 18208 " void f()\n" 18209 " {\n" 18210 " if (true) {\n" 18211 " a();\n" 18212 " b();\n" 18213 " }\n" 18214 " }\n" 18215 " void g() { return; }\n" 18216 "};\n" 18217 "struct B {\n" 18218 " int x;\n" 18219 "};\n" 18220 "} // namespace a\n", 18221 StroustrupBraceStyle); 18222 18223 verifyFormat("void foo()\n" 18224 "{\n" 18225 " if (a) {\n" 18226 " a();\n" 18227 " }\n" 18228 " else {\n" 18229 " b();\n" 18230 " }\n" 18231 "}\n", 18232 StroustrupBraceStyle); 18233 18234 verifyFormat("#ifdef _DEBUG\n" 18235 "int foo(int i = 0)\n" 18236 "#else\n" 18237 "int foo(int i = 5)\n" 18238 "#endif\n" 18239 "{\n" 18240 " return i;\n" 18241 "}", 18242 StroustrupBraceStyle); 18243 18244 verifyFormat("void foo() {}\n" 18245 "void bar()\n" 18246 "#ifdef _DEBUG\n" 18247 "{\n" 18248 " foo();\n" 18249 "}\n" 18250 "#else\n" 18251 "{\n" 18252 "}\n" 18253 "#endif", 18254 StroustrupBraceStyle); 18255 18256 verifyFormat("void foobar() { int i = 5; }\n" 18257 "#ifdef _DEBUG\n" 18258 "void bar() {}\n" 18259 "#else\n" 18260 "void bar() { foobar(); }\n" 18261 "#endif", 18262 StroustrupBraceStyle); 18263 } 18264 18265 TEST_F(FormatTest, AllmanBraceBreaking) { 18266 FormatStyle AllmanBraceStyle = getLLVMStyle(); 18267 AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman; 18268 18269 EXPECT_EQ("namespace a\n" 18270 "{\n" 18271 "void f();\n" 18272 "void g();\n" 18273 "} // namespace a\n", 18274 format("namespace a\n" 18275 "{\n" 18276 "void f();\n" 18277 "void g();\n" 18278 "}\n", 18279 AllmanBraceStyle)); 18280 18281 verifyFormat("namespace a\n" 18282 "{\n" 18283 "class A\n" 18284 "{\n" 18285 " void f()\n" 18286 " {\n" 18287 " if (true)\n" 18288 " {\n" 18289 " a();\n" 18290 " b();\n" 18291 " }\n" 18292 " }\n" 18293 " void g() { return; }\n" 18294 "};\n" 18295 "struct B\n" 18296 "{\n" 18297 " int x;\n" 18298 "};\n" 18299 "union C\n" 18300 "{\n" 18301 "};\n" 18302 "} // namespace a", 18303 AllmanBraceStyle); 18304 18305 verifyFormat("void f()\n" 18306 "{\n" 18307 " if (true)\n" 18308 " {\n" 18309 " a();\n" 18310 " }\n" 18311 " else if (false)\n" 18312 " {\n" 18313 " b();\n" 18314 " }\n" 18315 " else\n" 18316 " {\n" 18317 " c();\n" 18318 " }\n" 18319 "}\n", 18320 AllmanBraceStyle); 18321 18322 verifyFormat("void f()\n" 18323 "{\n" 18324 " for (int i = 0; i < 10; ++i)\n" 18325 " {\n" 18326 " a();\n" 18327 " }\n" 18328 " while (false)\n" 18329 " {\n" 18330 " b();\n" 18331 " }\n" 18332 " do\n" 18333 " {\n" 18334 " c();\n" 18335 " } while (false)\n" 18336 "}\n", 18337 AllmanBraceStyle); 18338 18339 verifyFormat("void f(int a)\n" 18340 "{\n" 18341 " switch (a)\n" 18342 " {\n" 18343 " case 0:\n" 18344 " break;\n" 18345 " case 1:\n" 18346 " {\n" 18347 " break;\n" 18348 " }\n" 18349 " case 2:\n" 18350 " {\n" 18351 " }\n" 18352 " break;\n" 18353 " default:\n" 18354 " break;\n" 18355 " }\n" 18356 "}\n", 18357 AllmanBraceStyle); 18358 18359 verifyFormat("enum X\n" 18360 "{\n" 18361 " Y = 0,\n" 18362 "}\n", 18363 AllmanBraceStyle); 18364 verifyFormat("enum X\n" 18365 "{\n" 18366 " Y = 0\n" 18367 "}\n", 18368 AllmanBraceStyle); 18369 18370 verifyFormat("@interface BSApplicationController ()\n" 18371 "{\n" 18372 "@private\n" 18373 " id _extraIvar;\n" 18374 "}\n" 18375 "@end\n", 18376 AllmanBraceStyle); 18377 18378 verifyFormat("#ifdef _DEBUG\n" 18379 "int foo(int i = 0)\n" 18380 "#else\n" 18381 "int foo(int i = 5)\n" 18382 "#endif\n" 18383 "{\n" 18384 " return i;\n" 18385 "}", 18386 AllmanBraceStyle); 18387 18388 verifyFormat("void foo() {}\n" 18389 "void bar()\n" 18390 "#ifdef _DEBUG\n" 18391 "{\n" 18392 " foo();\n" 18393 "}\n" 18394 "#else\n" 18395 "{\n" 18396 "}\n" 18397 "#endif", 18398 AllmanBraceStyle); 18399 18400 verifyFormat("void foobar() { int i = 5; }\n" 18401 "#ifdef _DEBUG\n" 18402 "void bar() {}\n" 18403 "#else\n" 18404 "void bar() { foobar(); }\n" 18405 "#endif", 18406 AllmanBraceStyle); 18407 18408 EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine, 18409 FormatStyle::SLS_All); 18410 18411 verifyFormat("[](int i) { return i + 2; };\n" 18412 "[](int i, int j)\n" 18413 "{\n" 18414 " auto x = i + j;\n" 18415 " auto y = i * j;\n" 18416 " return x ^ y;\n" 18417 "};\n" 18418 "void foo()\n" 18419 "{\n" 18420 " auto shortLambda = [](int i) { return i + 2; };\n" 18421 " auto longLambda = [](int i, int j)\n" 18422 " {\n" 18423 " auto x = i + j;\n" 18424 " auto y = i * j;\n" 18425 " return x ^ y;\n" 18426 " };\n" 18427 "}", 18428 AllmanBraceStyle); 18429 18430 AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 18431 18432 verifyFormat("[](int i)\n" 18433 "{\n" 18434 " return i + 2;\n" 18435 "};\n" 18436 "[](int i, int j)\n" 18437 "{\n" 18438 " auto x = i + j;\n" 18439 " auto y = i * j;\n" 18440 " return x ^ y;\n" 18441 "};\n" 18442 "void foo()\n" 18443 "{\n" 18444 " auto shortLambda = [](int i)\n" 18445 " {\n" 18446 " return i + 2;\n" 18447 " };\n" 18448 " auto longLambda = [](int i, int j)\n" 18449 " {\n" 18450 " auto x = i + j;\n" 18451 " auto y = i * j;\n" 18452 " return x ^ y;\n" 18453 " };\n" 18454 "}", 18455 AllmanBraceStyle); 18456 18457 // Reset 18458 AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All; 18459 18460 // This shouldn't affect ObjC blocks.. 18461 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n" 18462 " // ...\n" 18463 " int i;\n" 18464 "}];", 18465 AllmanBraceStyle); 18466 verifyFormat("void (^block)(void) = ^{\n" 18467 " // ...\n" 18468 " int i;\n" 18469 "};", 18470 AllmanBraceStyle); 18471 // .. or dict literals. 18472 verifyFormat("void f()\n" 18473 "{\n" 18474 " // ...\n" 18475 " [object someMethod:@{@\"a\" : @\"b\"}];\n" 18476 "}", 18477 AllmanBraceStyle); 18478 verifyFormat("void f()\n" 18479 "{\n" 18480 " // ...\n" 18481 " [object someMethod:@{a : @\"b\"}];\n" 18482 "}", 18483 AllmanBraceStyle); 18484 verifyFormat("int f()\n" 18485 "{ // comment\n" 18486 " return 42;\n" 18487 "}", 18488 AllmanBraceStyle); 18489 18490 AllmanBraceStyle.ColumnLimit = 19; 18491 verifyFormat("void f() { int i; }", AllmanBraceStyle); 18492 AllmanBraceStyle.ColumnLimit = 18; 18493 verifyFormat("void f()\n" 18494 "{\n" 18495 " int i;\n" 18496 "}", 18497 AllmanBraceStyle); 18498 AllmanBraceStyle.ColumnLimit = 80; 18499 18500 FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle; 18501 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = 18502 FormatStyle::SIS_WithoutElse; 18503 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true; 18504 verifyFormat("void f(bool b)\n" 18505 "{\n" 18506 " if (b)\n" 18507 " {\n" 18508 " return;\n" 18509 " }\n" 18510 "}\n", 18511 BreakBeforeBraceShortIfs); 18512 verifyFormat("void f(bool b)\n" 18513 "{\n" 18514 " if constexpr (b)\n" 18515 " {\n" 18516 " return;\n" 18517 " }\n" 18518 "}\n", 18519 BreakBeforeBraceShortIfs); 18520 verifyFormat("void f(bool b)\n" 18521 "{\n" 18522 " if CONSTEXPR (b)\n" 18523 " {\n" 18524 " return;\n" 18525 " }\n" 18526 "}\n", 18527 BreakBeforeBraceShortIfs); 18528 verifyFormat("void f(bool b)\n" 18529 "{\n" 18530 " if (b) return;\n" 18531 "}\n", 18532 BreakBeforeBraceShortIfs); 18533 verifyFormat("void f(bool b)\n" 18534 "{\n" 18535 " if constexpr (b) return;\n" 18536 "}\n", 18537 BreakBeforeBraceShortIfs); 18538 verifyFormat("void f(bool b)\n" 18539 "{\n" 18540 " if CONSTEXPR (b) return;\n" 18541 "}\n", 18542 BreakBeforeBraceShortIfs); 18543 verifyFormat("void f(bool b)\n" 18544 "{\n" 18545 " while (b)\n" 18546 " {\n" 18547 " return;\n" 18548 " }\n" 18549 "}\n", 18550 BreakBeforeBraceShortIfs); 18551 } 18552 18553 TEST_F(FormatTest, WhitesmithsBraceBreaking) { 18554 FormatStyle WhitesmithsBraceStyle = getLLVMStyleWithColumns(0); 18555 WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 18556 18557 // Make a few changes to the style for testing purposes 18558 WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine = 18559 FormatStyle::SFS_Empty; 18560 WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 18561 18562 // FIXME: this test case can't decide whether there should be a blank line 18563 // after the ~D() line or not. It adds one if one doesn't exist in the test 18564 // and it removes the line if one exists. 18565 /* 18566 verifyFormat("class A;\n" 18567 "namespace B\n" 18568 " {\n" 18569 "class C;\n" 18570 "// Comment\n" 18571 "class D\n" 18572 " {\n" 18573 "public:\n" 18574 " D();\n" 18575 " ~D() {}\n" 18576 "private:\n" 18577 " enum E\n" 18578 " {\n" 18579 " F\n" 18580 " }\n" 18581 " };\n" 18582 " } // namespace B\n", 18583 WhitesmithsBraceStyle); 18584 */ 18585 18586 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None; 18587 verifyFormat("namespace a\n" 18588 " {\n" 18589 "class A\n" 18590 " {\n" 18591 " void f()\n" 18592 " {\n" 18593 " if (true)\n" 18594 " {\n" 18595 " a();\n" 18596 " b();\n" 18597 " }\n" 18598 " }\n" 18599 " void g()\n" 18600 " {\n" 18601 " return;\n" 18602 " }\n" 18603 " };\n" 18604 "struct B\n" 18605 " {\n" 18606 " int x;\n" 18607 " };\n" 18608 " } // namespace a", 18609 WhitesmithsBraceStyle); 18610 18611 verifyFormat("namespace a\n" 18612 " {\n" 18613 "namespace b\n" 18614 " {\n" 18615 "class A\n" 18616 " {\n" 18617 " void f()\n" 18618 " {\n" 18619 " if (true)\n" 18620 " {\n" 18621 " a();\n" 18622 " b();\n" 18623 " }\n" 18624 " }\n" 18625 " void g()\n" 18626 " {\n" 18627 " return;\n" 18628 " }\n" 18629 " };\n" 18630 "struct B\n" 18631 " {\n" 18632 " int x;\n" 18633 " };\n" 18634 " } // namespace b\n" 18635 " } // namespace a", 18636 WhitesmithsBraceStyle); 18637 18638 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner; 18639 verifyFormat("namespace a\n" 18640 " {\n" 18641 "namespace b\n" 18642 " {\n" 18643 " class A\n" 18644 " {\n" 18645 " void f()\n" 18646 " {\n" 18647 " if (true)\n" 18648 " {\n" 18649 " a();\n" 18650 " b();\n" 18651 " }\n" 18652 " }\n" 18653 " void g()\n" 18654 " {\n" 18655 " return;\n" 18656 " }\n" 18657 " };\n" 18658 " struct B\n" 18659 " {\n" 18660 " int x;\n" 18661 " };\n" 18662 " } // namespace b\n" 18663 " } // namespace a", 18664 WhitesmithsBraceStyle); 18665 18666 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All; 18667 verifyFormat("namespace a\n" 18668 " {\n" 18669 " namespace b\n" 18670 " {\n" 18671 " class A\n" 18672 " {\n" 18673 " void f()\n" 18674 " {\n" 18675 " if (true)\n" 18676 " {\n" 18677 " a();\n" 18678 " b();\n" 18679 " }\n" 18680 " }\n" 18681 " void g()\n" 18682 " {\n" 18683 " return;\n" 18684 " }\n" 18685 " };\n" 18686 " struct B\n" 18687 " {\n" 18688 " int x;\n" 18689 " };\n" 18690 " } // namespace b\n" 18691 " } // namespace a", 18692 WhitesmithsBraceStyle); 18693 18694 verifyFormat("void f()\n" 18695 " {\n" 18696 " if (true)\n" 18697 " {\n" 18698 " a();\n" 18699 " }\n" 18700 " else if (false)\n" 18701 " {\n" 18702 " b();\n" 18703 " }\n" 18704 " else\n" 18705 " {\n" 18706 " c();\n" 18707 " }\n" 18708 " }\n", 18709 WhitesmithsBraceStyle); 18710 18711 verifyFormat("void f()\n" 18712 " {\n" 18713 " for (int i = 0; i < 10; ++i)\n" 18714 " {\n" 18715 " a();\n" 18716 " }\n" 18717 " while (false)\n" 18718 " {\n" 18719 " b();\n" 18720 " }\n" 18721 " do\n" 18722 " {\n" 18723 " c();\n" 18724 " } while (false)\n" 18725 " }\n", 18726 WhitesmithsBraceStyle); 18727 18728 WhitesmithsBraceStyle.IndentCaseLabels = true; 18729 verifyFormat("void switchTest1(int a)\n" 18730 " {\n" 18731 " switch (a)\n" 18732 " {\n" 18733 " case 2:\n" 18734 " {\n" 18735 " }\n" 18736 " break;\n" 18737 " }\n" 18738 " }\n", 18739 WhitesmithsBraceStyle); 18740 18741 verifyFormat("void switchTest2(int a)\n" 18742 " {\n" 18743 " switch (a)\n" 18744 " {\n" 18745 " case 0:\n" 18746 " break;\n" 18747 " case 1:\n" 18748 " {\n" 18749 " break;\n" 18750 " }\n" 18751 " case 2:\n" 18752 " {\n" 18753 " }\n" 18754 " break;\n" 18755 " default:\n" 18756 " break;\n" 18757 " }\n" 18758 " }\n", 18759 WhitesmithsBraceStyle); 18760 18761 verifyFormat("void switchTest3(int a)\n" 18762 " {\n" 18763 " switch (a)\n" 18764 " {\n" 18765 " case 0:\n" 18766 " {\n" 18767 " foo(x);\n" 18768 " }\n" 18769 " break;\n" 18770 " default:\n" 18771 " {\n" 18772 " foo(1);\n" 18773 " }\n" 18774 " break;\n" 18775 " }\n" 18776 " }\n", 18777 WhitesmithsBraceStyle); 18778 18779 WhitesmithsBraceStyle.IndentCaseLabels = false; 18780 18781 verifyFormat("void switchTest4(int a)\n" 18782 " {\n" 18783 " switch (a)\n" 18784 " {\n" 18785 " case 2:\n" 18786 " {\n" 18787 " }\n" 18788 " break;\n" 18789 " }\n" 18790 " }\n", 18791 WhitesmithsBraceStyle); 18792 18793 verifyFormat("void switchTest5(int a)\n" 18794 " {\n" 18795 " switch (a)\n" 18796 " {\n" 18797 " case 0:\n" 18798 " break;\n" 18799 " case 1:\n" 18800 " {\n" 18801 " foo();\n" 18802 " break;\n" 18803 " }\n" 18804 " case 2:\n" 18805 " {\n" 18806 " }\n" 18807 " break;\n" 18808 " default:\n" 18809 " break;\n" 18810 " }\n" 18811 " }\n", 18812 WhitesmithsBraceStyle); 18813 18814 verifyFormat("void switchTest6(int a)\n" 18815 " {\n" 18816 " switch (a)\n" 18817 " {\n" 18818 " case 0:\n" 18819 " {\n" 18820 " foo(x);\n" 18821 " }\n" 18822 " break;\n" 18823 " default:\n" 18824 " {\n" 18825 " foo(1);\n" 18826 " }\n" 18827 " break;\n" 18828 " }\n" 18829 " }\n", 18830 WhitesmithsBraceStyle); 18831 18832 verifyFormat("enum X\n" 18833 " {\n" 18834 " Y = 0, // testing\n" 18835 " }\n", 18836 WhitesmithsBraceStyle); 18837 18838 verifyFormat("enum X\n" 18839 " {\n" 18840 " Y = 0\n" 18841 " }\n", 18842 WhitesmithsBraceStyle); 18843 verifyFormat("enum X\n" 18844 " {\n" 18845 " Y = 0,\n" 18846 " Z = 1\n" 18847 " };\n", 18848 WhitesmithsBraceStyle); 18849 18850 verifyFormat("@interface BSApplicationController ()\n" 18851 " {\n" 18852 "@private\n" 18853 " id _extraIvar;\n" 18854 " }\n" 18855 "@end\n", 18856 WhitesmithsBraceStyle); 18857 18858 verifyFormat("#ifdef _DEBUG\n" 18859 "int foo(int i = 0)\n" 18860 "#else\n" 18861 "int foo(int i = 5)\n" 18862 "#endif\n" 18863 " {\n" 18864 " return i;\n" 18865 " }", 18866 WhitesmithsBraceStyle); 18867 18868 verifyFormat("void foo() {}\n" 18869 "void bar()\n" 18870 "#ifdef _DEBUG\n" 18871 " {\n" 18872 " foo();\n" 18873 " }\n" 18874 "#else\n" 18875 " {\n" 18876 " }\n" 18877 "#endif", 18878 WhitesmithsBraceStyle); 18879 18880 verifyFormat("void foobar()\n" 18881 " {\n" 18882 " int i = 5;\n" 18883 " }\n" 18884 "#ifdef _DEBUG\n" 18885 "void bar()\n" 18886 " {\n" 18887 " }\n" 18888 "#else\n" 18889 "void bar()\n" 18890 " {\n" 18891 " foobar();\n" 18892 " }\n" 18893 "#endif", 18894 WhitesmithsBraceStyle); 18895 18896 // This shouldn't affect ObjC blocks.. 18897 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n" 18898 " // ...\n" 18899 " int i;\n" 18900 "}];", 18901 WhitesmithsBraceStyle); 18902 verifyFormat("void (^block)(void) = ^{\n" 18903 " // ...\n" 18904 " int i;\n" 18905 "};", 18906 WhitesmithsBraceStyle); 18907 // .. or dict literals. 18908 verifyFormat("void f()\n" 18909 " {\n" 18910 " [object someMethod:@{@\"a\" : @\"b\"}];\n" 18911 " }", 18912 WhitesmithsBraceStyle); 18913 18914 verifyFormat("int f()\n" 18915 " { // comment\n" 18916 " return 42;\n" 18917 " }", 18918 WhitesmithsBraceStyle); 18919 18920 FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle; 18921 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = 18922 FormatStyle::SIS_OnlyFirstIf; 18923 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true; 18924 verifyFormat("void f(bool b)\n" 18925 " {\n" 18926 " if (b)\n" 18927 " {\n" 18928 " return;\n" 18929 " }\n" 18930 " }\n", 18931 BreakBeforeBraceShortIfs); 18932 verifyFormat("void f(bool b)\n" 18933 " {\n" 18934 " if (b) return;\n" 18935 " }\n", 18936 BreakBeforeBraceShortIfs); 18937 verifyFormat("void f(bool b)\n" 18938 " {\n" 18939 " while (b)\n" 18940 " {\n" 18941 " return;\n" 18942 " }\n" 18943 " }\n", 18944 BreakBeforeBraceShortIfs); 18945 } 18946 18947 TEST_F(FormatTest, GNUBraceBreaking) { 18948 FormatStyle GNUBraceStyle = getLLVMStyle(); 18949 GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU; 18950 verifyFormat("namespace a\n" 18951 "{\n" 18952 "class A\n" 18953 "{\n" 18954 " void f()\n" 18955 " {\n" 18956 " int a;\n" 18957 " {\n" 18958 " int b;\n" 18959 " }\n" 18960 " if (true)\n" 18961 " {\n" 18962 " a();\n" 18963 " b();\n" 18964 " }\n" 18965 " }\n" 18966 " void g() { return; }\n" 18967 "}\n" 18968 "} // namespace a", 18969 GNUBraceStyle); 18970 18971 verifyFormat("void f()\n" 18972 "{\n" 18973 " if (true)\n" 18974 " {\n" 18975 " a();\n" 18976 " }\n" 18977 " else if (false)\n" 18978 " {\n" 18979 " b();\n" 18980 " }\n" 18981 " else\n" 18982 " {\n" 18983 " c();\n" 18984 " }\n" 18985 "}\n", 18986 GNUBraceStyle); 18987 18988 verifyFormat("void f()\n" 18989 "{\n" 18990 " for (int i = 0; i < 10; ++i)\n" 18991 " {\n" 18992 " a();\n" 18993 " }\n" 18994 " while (false)\n" 18995 " {\n" 18996 " b();\n" 18997 " }\n" 18998 " do\n" 18999 " {\n" 19000 " c();\n" 19001 " }\n" 19002 " while (false);\n" 19003 "}\n", 19004 GNUBraceStyle); 19005 19006 verifyFormat("void f(int a)\n" 19007 "{\n" 19008 " switch (a)\n" 19009 " {\n" 19010 " case 0:\n" 19011 " break;\n" 19012 " case 1:\n" 19013 " {\n" 19014 " break;\n" 19015 " }\n" 19016 " case 2:\n" 19017 " {\n" 19018 " }\n" 19019 " break;\n" 19020 " default:\n" 19021 " break;\n" 19022 " }\n" 19023 "}\n", 19024 GNUBraceStyle); 19025 19026 verifyFormat("enum X\n" 19027 "{\n" 19028 " Y = 0,\n" 19029 "}\n", 19030 GNUBraceStyle); 19031 19032 verifyFormat("@interface BSApplicationController ()\n" 19033 "{\n" 19034 "@private\n" 19035 " id _extraIvar;\n" 19036 "}\n" 19037 "@end\n", 19038 GNUBraceStyle); 19039 19040 verifyFormat("#ifdef _DEBUG\n" 19041 "int foo(int i = 0)\n" 19042 "#else\n" 19043 "int foo(int i = 5)\n" 19044 "#endif\n" 19045 "{\n" 19046 " return i;\n" 19047 "}", 19048 GNUBraceStyle); 19049 19050 verifyFormat("void foo() {}\n" 19051 "void bar()\n" 19052 "#ifdef _DEBUG\n" 19053 "{\n" 19054 " foo();\n" 19055 "}\n" 19056 "#else\n" 19057 "{\n" 19058 "}\n" 19059 "#endif", 19060 GNUBraceStyle); 19061 19062 verifyFormat("void foobar() { int i = 5; }\n" 19063 "#ifdef _DEBUG\n" 19064 "void bar() {}\n" 19065 "#else\n" 19066 "void bar() { foobar(); }\n" 19067 "#endif", 19068 GNUBraceStyle); 19069 } 19070 19071 TEST_F(FormatTest, WebKitBraceBreaking) { 19072 FormatStyle WebKitBraceStyle = getLLVMStyle(); 19073 WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit; 19074 WebKitBraceStyle.FixNamespaceComments = false; 19075 verifyFormat("namespace a {\n" 19076 "class A {\n" 19077 " void f()\n" 19078 " {\n" 19079 " if (true) {\n" 19080 " a();\n" 19081 " b();\n" 19082 " }\n" 19083 " }\n" 19084 " void g() { return; }\n" 19085 "};\n" 19086 "enum E {\n" 19087 " A,\n" 19088 " // foo\n" 19089 " B,\n" 19090 " C\n" 19091 "};\n" 19092 "struct B {\n" 19093 " int x;\n" 19094 "};\n" 19095 "}\n", 19096 WebKitBraceStyle); 19097 verifyFormat("struct S {\n" 19098 " int Type;\n" 19099 " union {\n" 19100 " int x;\n" 19101 " double y;\n" 19102 " } Value;\n" 19103 " class C {\n" 19104 " MyFavoriteType Value;\n" 19105 " } Class;\n" 19106 "};\n", 19107 WebKitBraceStyle); 19108 } 19109 19110 TEST_F(FormatTest, CatchExceptionReferenceBinding) { 19111 verifyFormat("void f() {\n" 19112 " try {\n" 19113 " } catch (const Exception &e) {\n" 19114 " }\n" 19115 "}\n", 19116 getLLVMStyle()); 19117 } 19118 19119 TEST_F(FormatTest, CatchAlignArrayOfStructuresRightAlignment) { 19120 auto Style = getLLVMStyle(); 19121 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 19122 Style.AlignConsecutiveAssignments.Enabled = true; 19123 Style.AlignConsecutiveDeclarations.Enabled = true; 19124 verifyFormat("struct test demo[] = {\n" 19125 " {56, 23, \"hello\"},\n" 19126 " {-1, 93463, \"world\"},\n" 19127 " { 7, 5, \"!!\"}\n" 19128 "};\n", 19129 Style); 19130 19131 verifyFormat("struct test demo[] = {\n" 19132 " {56, 23, \"hello\"}, // first line\n" 19133 " {-1, 93463, \"world\"}, // second line\n" 19134 " { 7, 5, \"!!\"} // third line\n" 19135 "};\n", 19136 Style); 19137 19138 verifyFormat("struct test demo[4] = {\n" 19139 " { 56, 23, 21, \"oh\"}, // first line\n" 19140 " { -1, 93463, 22, \"my\"}, // second line\n" 19141 " { 7, 5, 1, \"goodness\"} // third line\n" 19142 " {234, 5, 1, \"gracious\"} // fourth line\n" 19143 "};\n", 19144 Style); 19145 19146 verifyFormat("struct test demo[3] = {\n" 19147 " {56, 23, \"hello\"},\n" 19148 " {-1, 93463, \"world\"},\n" 19149 " { 7, 5, \"!!\"}\n" 19150 "};\n", 19151 Style); 19152 19153 verifyFormat("struct test demo[3] = {\n" 19154 " {int{56}, 23, \"hello\"},\n" 19155 " {int{-1}, 93463, \"world\"},\n" 19156 " { int{7}, 5, \"!!\"}\n" 19157 "};\n", 19158 Style); 19159 19160 verifyFormat("struct test demo[] = {\n" 19161 " {56, 23, \"hello\"},\n" 19162 " {-1, 93463, \"world\"},\n" 19163 " { 7, 5, \"!!\"},\n" 19164 "};\n", 19165 Style); 19166 19167 verifyFormat("test demo[] = {\n" 19168 " {56, 23, \"hello\"},\n" 19169 " {-1, 93463, \"world\"},\n" 19170 " { 7, 5, \"!!\"},\n" 19171 "};\n", 19172 Style); 19173 19174 verifyFormat("demo = std::array<struct test, 3>{\n" 19175 " test{56, 23, \"hello\"},\n" 19176 " test{-1, 93463, \"world\"},\n" 19177 " test{ 7, 5, \"!!\"},\n" 19178 "};\n", 19179 Style); 19180 19181 verifyFormat("test demo[] = {\n" 19182 " {56, 23, \"hello\"},\n" 19183 "#if X\n" 19184 " {-1, 93463, \"world\"},\n" 19185 "#endif\n" 19186 " { 7, 5, \"!!\"}\n" 19187 "};\n", 19188 Style); 19189 19190 verifyFormat( 19191 "test demo[] = {\n" 19192 " { 7, 23,\n" 19193 " \"hello world i am a very long line that really, in any\"\n" 19194 " \"just world, ought to be split over multiple lines\"},\n" 19195 " {-1, 93463, \"world\"},\n" 19196 " {56, 5, \"!!\"}\n" 19197 "};\n", 19198 Style); 19199 19200 verifyFormat("return GradForUnaryCwise(g, {\n" 19201 " {{\"sign\"}, \"Sign\", " 19202 " {\"x\", \"dy\"}},\n" 19203 " { {\"dx\"}, \"Mul\", {\"dy\"" 19204 ", \"sign\"}},\n" 19205 "});\n", 19206 Style); 19207 19208 Style.ColumnLimit = 0; 19209 EXPECT_EQ( 19210 "test demo[] = {\n" 19211 " {56, 23, \"hello world i am a very long line that really, " 19212 "in any just world, ought to be split over multiple lines\"},\n" 19213 " {-1, 93463, " 19214 " \"world\"},\n" 19215 " { 7, 5, " 19216 " \"!!\"},\n" 19217 "};", 19218 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19219 "that really, in any just world, ought to be split over multiple " 19220 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19221 Style)); 19222 19223 Style.ColumnLimit = 80; 19224 verifyFormat("test demo[] = {\n" 19225 " {56, 23, /* a comment */ \"hello\"},\n" 19226 " {-1, 93463, \"world\"},\n" 19227 " { 7, 5, \"!!\"}\n" 19228 "};\n", 19229 Style); 19230 19231 verifyFormat("test demo[] = {\n" 19232 " {56, 23, \"hello\"},\n" 19233 " {-1, 93463, \"world\" /* comment here */},\n" 19234 " { 7, 5, \"!!\"}\n" 19235 "};\n", 19236 Style); 19237 19238 verifyFormat("test demo[] = {\n" 19239 " {56, /* a comment */ 23, \"hello\"},\n" 19240 " {-1, 93463, \"world\"},\n" 19241 " { 7, 5, \"!!\"}\n" 19242 "};\n", 19243 Style); 19244 19245 Style.ColumnLimit = 20; 19246 EXPECT_EQ( 19247 "demo = std::array<\n" 19248 " struct test, 3>{\n" 19249 " test{\n" 19250 " 56, 23,\n" 19251 " \"hello \"\n" 19252 " \"world i \"\n" 19253 " \"am a very \"\n" 19254 " \"long line \"\n" 19255 " \"that \"\n" 19256 " \"really, \"\n" 19257 " \"in any \"\n" 19258 " \"just \"\n" 19259 " \"world, \"\n" 19260 " \"ought to \"\n" 19261 " \"be split \"\n" 19262 " \"over \"\n" 19263 " \"multiple \"\n" 19264 " \"lines\"},\n" 19265 " test{-1, 93463,\n" 19266 " \"world\"},\n" 19267 " test{ 7, 5,\n" 19268 " \"!!\" },\n" 19269 "};", 19270 format("demo = std::array<struct test, 3>{test{56, 23, \"hello world " 19271 "i am a very long line that really, in any just world, ought " 19272 "to be split over multiple lines\"},test{-1, 93463, \"world\"}," 19273 "test{7, 5, \"!!\"},};", 19274 Style)); 19275 // This caused a core dump by enabling Alignment in the LLVMStyle globally 19276 Style = getLLVMStyleWithColumns(50); 19277 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 19278 verifyFormat("static A x = {\n" 19279 " {{init1, init2, init3, init4},\n" 19280 " {init1, init2, init3, init4}}\n" 19281 "};", 19282 Style); 19283 // TODO: Fix the indentations below when this option is fully functional. 19284 verifyFormat("int a[][] = {\n" 19285 " {\n" 19286 " {0, 2}, //\n" 19287 " {1, 2} //\n" 19288 " }\n" 19289 "};", 19290 Style); 19291 Style.ColumnLimit = 100; 19292 EXPECT_EQ( 19293 "test demo[] = {\n" 19294 " {56, 23,\n" 19295 " \"hello world i am a very long line that really, in any just world" 19296 ", ought to be split over \"\n" 19297 " \"multiple lines\" },\n" 19298 " {-1, 93463, \"world\"},\n" 19299 " { 7, 5, \"!!\"},\n" 19300 "};", 19301 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19302 "that really, in any just world, ought to be split over multiple " 19303 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19304 Style)); 19305 19306 Style = getLLVMStyleWithColumns(50); 19307 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 19308 verifyFormat("struct test demo[] = {\n" 19309 " {56, 23, \"hello\"},\n" 19310 " {-1, 93463, \"world\"},\n" 19311 " { 7, 5, \"!!\"}\n" 19312 "};\n" 19313 "static A x = {\n" 19314 " {{init1, init2, init3, init4},\n" 19315 " {init1, init2, init3, init4}}\n" 19316 "};", 19317 Style); 19318 Style.ColumnLimit = 100; 19319 Style.AlignConsecutiveAssignments.AcrossComments = true; 19320 Style.AlignConsecutiveDeclarations.AcrossComments = true; 19321 verifyFormat("struct test demo[] = {\n" 19322 " {56, 23, \"hello\"},\n" 19323 " {-1, 93463, \"world\"},\n" 19324 " { 7, 5, \"!!\"}\n" 19325 "};\n" 19326 "struct test demo[4] = {\n" 19327 " { 56, 23, 21, \"oh\"}, // first line\n" 19328 " { -1, 93463, 22, \"my\"}, // second line\n" 19329 " { 7, 5, 1, \"goodness\"} // third line\n" 19330 " {234, 5, 1, \"gracious\"} // fourth line\n" 19331 "};\n", 19332 Style); 19333 EXPECT_EQ( 19334 "test demo[] = {\n" 19335 " {56,\n" 19336 " \"hello world i am a very long line that really, in any just world" 19337 ", ought to be split over \"\n" 19338 " \"multiple lines\", 23},\n" 19339 " {-1, \"world\", 93463},\n" 19340 " { 7, \"!!\", 5},\n" 19341 "};", 19342 format("test demo[] = {{56, \"hello world i am a very long line " 19343 "that really, in any just world, ought to be split over multiple " 19344 "lines\", 23},{-1, \"world\", 93463},{7, \"!!\", 5},};", 19345 Style)); 19346 } 19347 19348 TEST_F(FormatTest, CatchAlignArrayOfStructuresLeftAlignment) { 19349 auto Style = getLLVMStyle(); 19350 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 19351 /* FIXME: This case gets misformatted. 19352 verifyFormat("auto foo = Items{\n" 19353 " Section{0, bar(), },\n" 19354 " Section{1, boo() }\n" 19355 "};\n", 19356 Style); 19357 */ 19358 verifyFormat("auto foo = Items{\n" 19359 " Section{\n" 19360 " 0, bar(),\n" 19361 " }\n" 19362 "};\n", 19363 Style); 19364 verifyFormat("struct test demo[] = {\n" 19365 " {56, 23, \"hello\"},\n" 19366 " {-1, 93463, \"world\"},\n" 19367 " {7, 5, \"!!\" }\n" 19368 "};\n", 19369 Style); 19370 verifyFormat("struct test demo[] = {\n" 19371 " {56, 23, \"hello\"}, // first line\n" 19372 " {-1, 93463, \"world\"}, // second line\n" 19373 " {7, 5, \"!!\" } // third line\n" 19374 "};\n", 19375 Style); 19376 verifyFormat("struct test demo[4] = {\n" 19377 " {56, 23, 21, \"oh\" }, // first line\n" 19378 " {-1, 93463, 22, \"my\" }, // second line\n" 19379 " {7, 5, 1, \"goodness\"} // third line\n" 19380 " {234, 5, 1, \"gracious\"} // fourth line\n" 19381 "};\n", 19382 Style); 19383 verifyFormat("struct test demo[3] = {\n" 19384 " {56, 23, \"hello\"},\n" 19385 " {-1, 93463, \"world\"},\n" 19386 " {7, 5, \"!!\" }\n" 19387 "};\n", 19388 Style); 19389 19390 verifyFormat("struct test demo[3] = {\n" 19391 " {int{56}, 23, \"hello\"},\n" 19392 " {int{-1}, 93463, \"world\"},\n" 19393 " {int{7}, 5, \"!!\" }\n" 19394 "};\n", 19395 Style); 19396 verifyFormat("struct test demo[] = {\n" 19397 " {56, 23, \"hello\"},\n" 19398 " {-1, 93463, \"world\"},\n" 19399 " {7, 5, \"!!\" },\n" 19400 "};\n", 19401 Style); 19402 verifyFormat("test demo[] = {\n" 19403 " {56, 23, \"hello\"},\n" 19404 " {-1, 93463, \"world\"},\n" 19405 " {7, 5, \"!!\" },\n" 19406 "};\n", 19407 Style); 19408 verifyFormat("demo = std::array<struct test, 3>{\n" 19409 " test{56, 23, \"hello\"},\n" 19410 " test{-1, 93463, \"world\"},\n" 19411 " test{7, 5, \"!!\" },\n" 19412 "};\n", 19413 Style); 19414 verifyFormat("test demo[] = {\n" 19415 " {56, 23, \"hello\"},\n" 19416 "#if X\n" 19417 " {-1, 93463, \"world\"},\n" 19418 "#endif\n" 19419 " {7, 5, \"!!\" }\n" 19420 "};\n", 19421 Style); 19422 verifyFormat( 19423 "test demo[] = {\n" 19424 " {7, 23,\n" 19425 " \"hello world i am a very long line that really, in any\"\n" 19426 " \"just world, ought to be split over multiple lines\"},\n" 19427 " {-1, 93463, \"world\" },\n" 19428 " {56, 5, \"!!\" }\n" 19429 "};\n", 19430 Style); 19431 19432 verifyFormat("return GradForUnaryCwise(g, {\n" 19433 " {{\"sign\"}, \"Sign\", {\"x\", " 19434 "\"dy\"} },\n" 19435 " {{\"dx\"}, \"Mul\", " 19436 "{\"dy\", \"sign\"}},\n" 19437 "});\n", 19438 Style); 19439 19440 Style.ColumnLimit = 0; 19441 EXPECT_EQ( 19442 "test demo[] = {\n" 19443 " {56, 23, \"hello world i am a very long line that really, in any " 19444 "just world, ought to be split over multiple lines\"},\n" 19445 " {-1, 93463, \"world\" " 19446 " },\n" 19447 " {7, 5, \"!!\" " 19448 " },\n" 19449 "};", 19450 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19451 "that really, in any just world, ought to be split over multiple " 19452 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19453 Style)); 19454 19455 Style.ColumnLimit = 80; 19456 verifyFormat("test demo[] = {\n" 19457 " {56, 23, /* a comment */ \"hello\"},\n" 19458 " {-1, 93463, \"world\" },\n" 19459 " {7, 5, \"!!\" }\n" 19460 "};\n", 19461 Style); 19462 19463 verifyFormat("test demo[] = {\n" 19464 " {56, 23, \"hello\" },\n" 19465 " {-1, 93463, \"world\" /* comment here */},\n" 19466 " {7, 5, \"!!\" }\n" 19467 "};\n", 19468 Style); 19469 19470 verifyFormat("test demo[] = {\n" 19471 " {56, /* a comment */ 23, \"hello\"},\n" 19472 " {-1, 93463, \"world\"},\n" 19473 " {7, 5, \"!!\" }\n" 19474 "};\n", 19475 Style); 19476 19477 Style.ColumnLimit = 20; 19478 EXPECT_EQ( 19479 "demo = std::array<\n" 19480 " struct test, 3>{\n" 19481 " test{\n" 19482 " 56, 23,\n" 19483 " \"hello \"\n" 19484 " \"world i \"\n" 19485 " \"am a very \"\n" 19486 " \"long line \"\n" 19487 " \"that \"\n" 19488 " \"really, \"\n" 19489 " \"in any \"\n" 19490 " \"just \"\n" 19491 " \"world, \"\n" 19492 " \"ought to \"\n" 19493 " \"be split \"\n" 19494 " \"over \"\n" 19495 " \"multiple \"\n" 19496 " \"lines\"},\n" 19497 " test{-1, 93463,\n" 19498 " \"world\"},\n" 19499 " test{7, 5,\n" 19500 " \"!!\" },\n" 19501 "};", 19502 format("demo = std::array<struct test, 3>{test{56, 23, \"hello world " 19503 "i am a very long line that really, in any just world, ought " 19504 "to be split over multiple lines\"},test{-1, 93463, \"world\"}," 19505 "test{7, 5, \"!!\"},};", 19506 Style)); 19507 19508 // This caused a core dump by enabling Alignment in the LLVMStyle globally 19509 Style = getLLVMStyleWithColumns(50); 19510 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 19511 verifyFormat("static A x = {\n" 19512 " {{init1, init2, init3, init4},\n" 19513 " {init1, init2, init3, init4}}\n" 19514 "};", 19515 Style); 19516 Style.ColumnLimit = 100; 19517 EXPECT_EQ( 19518 "test demo[] = {\n" 19519 " {56, 23,\n" 19520 " \"hello world i am a very long line that really, in any just world" 19521 ", ought to be split over \"\n" 19522 " \"multiple lines\" },\n" 19523 " {-1, 93463, \"world\"},\n" 19524 " {7, 5, \"!!\" },\n" 19525 "};", 19526 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19527 "that really, in any just world, ought to be split over multiple " 19528 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19529 Style)); 19530 } 19531 19532 TEST_F(FormatTest, UnderstandsPragmas) { 19533 verifyFormat("#pragma omp reduction(| : var)"); 19534 verifyFormat("#pragma omp reduction(+ : var)"); 19535 19536 EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string " 19537 "(including parentheses).", 19538 format("#pragma mark Any non-hyphenated or hyphenated string " 19539 "(including parentheses).")); 19540 } 19541 19542 TEST_F(FormatTest, UnderstandPragmaOption) { 19543 verifyFormat("#pragma option -C -A"); 19544 19545 EXPECT_EQ("#pragma option -C -A", format("#pragma option -C -A")); 19546 } 19547 19548 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) { 19549 FormatStyle Style = getLLVMStyleWithColumns(20); 19550 19551 // See PR41213 19552 EXPECT_EQ("/*\n" 19553 " *\t9012345\n" 19554 " * /8901\n" 19555 " */", 19556 format("/*\n" 19557 " *\t9012345 /8901\n" 19558 " */", 19559 Style)); 19560 EXPECT_EQ("/*\n" 19561 " *345678\n" 19562 " *\t/8901\n" 19563 " */", 19564 format("/*\n" 19565 " *345678\t/8901\n" 19566 " */", 19567 Style)); 19568 19569 verifyFormat("int a; // the\n" 19570 " // comment", 19571 Style); 19572 EXPECT_EQ("int a; /* first line\n" 19573 " * second\n" 19574 " * line third\n" 19575 " * line\n" 19576 " */", 19577 format("int a; /* first line\n" 19578 " * second\n" 19579 " * line third\n" 19580 " * line\n" 19581 " */", 19582 Style)); 19583 EXPECT_EQ("int a; // first line\n" 19584 " // second\n" 19585 " // line third\n" 19586 " // line", 19587 format("int a; // first line\n" 19588 " // second line\n" 19589 " // third line", 19590 Style)); 19591 19592 Style.PenaltyExcessCharacter = 90; 19593 verifyFormat("int a; // the comment", Style); 19594 EXPECT_EQ("int a; // the comment\n" 19595 " // aaa", 19596 format("int a; // the comment aaa", Style)); 19597 EXPECT_EQ("int a; /* first line\n" 19598 " * second line\n" 19599 " * third line\n" 19600 " */", 19601 format("int a; /* first line\n" 19602 " * second line\n" 19603 " * third line\n" 19604 " */", 19605 Style)); 19606 EXPECT_EQ("int a; // first line\n" 19607 " // second line\n" 19608 " // third line", 19609 format("int a; // first line\n" 19610 " // second line\n" 19611 " // third line", 19612 Style)); 19613 // FIXME: Investigate why this is not getting the same layout as the test 19614 // above. 19615 EXPECT_EQ("int a; /* first line\n" 19616 " * second line\n" 19617 " * third line\n" 19618 " */", 19619 format("int a; /* first line second line third line" 19620 "\n*/", 19621 Style)); 19622 19623 EXPECT_EQ("// foo bar baz bazfoo\n" 19624 "// foo bar foo bar\n", 19625 format("// foo bar baz bazfoo\n" 19626 "// foo bar foo bar\n", 19627 Style)); 19628 EXPECT_EQ("// foo bar baz bazfoo\n" 19629 "// foo bar foo bar\n", 19630 format("// foo bar baz bazfoo\n" 19631 "// foo bar foo bar\n", 19632 Style)); 19633 19634 // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the 19635 // next one. 19636 EXPECT_EQ("// foo bar baz bazfoo\n" 19637 "// bar foo bar\n", 19638 format("// foo bar baz bazfoo bar\n" 19639 "// foo bar\n", 19640 Style)); 19641 19642 EXPECT_EQ("// foo bar baz bazfoo\n" 19643 "// foo bar baz bazfoo\n" 19644 "// bar foo bar\n", 19645 format("// foo bar baz bazfoo\n" 19646 "// foo bar baz bazfoo bar\n" 19647 "// foo bar\n", 19648 Style)); 19649 19650 EXPECT_EQ("// foo bar baz bazfoo\n" 19651 "// foo bar baz bazfoo\n" 19652 "// bar foo bar\n", 19653 format("// foo bar baz bazfoo\n" 19654 "// foo bar baz bazfoo bar\n" 19655 "// foo bar\n", 19656 Style)); 19657 19658 // Make sure we do not keep protruding characters if strict mode reflow is 19659 // cheaper than keeping protruding characters. 19660 Style.ColumnLimit = 21; 19661 EXPECT_EQ( 19662 "// foo foo foo foo\n" 19663 "// foo foo foo foo\n" 19664 "// foo foo foo foo\n", 19665 format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style)); 19666 19667 EXPECT_EQ("int a = /* long block\n" 19668 " comment */\n" 19669 " 42;", 19670 format("int a = /* long block comment */ 42;", Style)); 19671 } 19672 19673 TEST_F(FormatTest, BreakPenaltyAfterLParen) { 19674 FormatStyle Style = getLLVMStyle(); 19675 Style.ColumnLimit = 8; 19676 Style.PenaltyExcessCharacter = 15; 19677 verifyFormat("int foo(\n" 19678 " int aaaaaaaaaaaaaaaaaaaaaaaa);", 19679 Style); 19680 Style.PenaltyBreakOpenParenthesis = 200; 19681 EXPECT_EQ("int foo(int aaaaaaaaaaaaaaaaaaaaaaaa);", 19682 format("int foo(\n" 19683 " int aaaaaaaaaaaaaaaaaaaaaaaa);", 19684 Style)); 19685 } 19686 19687 TEST_F(FormatTest, BreakPenaltyAfterCastLParen) { 19688 FormatStyle Style = getLLVMStyle(); 19689 Style.ColumnLimit = 5; 19690 Style.PenaltyExcessCharacter = 150; 19691 verifyFormat("foo((\n" 19692 " int)aaaaaaaaaaaaaaaaaaaaaaaa);", 19693 19694 Style); 19695 Style.PenaltyBreakOpenParenthesis = 100000; 19696 EXPECT_EQ("foo((int)\n" 19697 " aaaaaaaaaaaaaaaaaaaaaaaa);", 19698 format("foo((\n" 19699 "int)aaaaaaaaaaaaaaaaaaaaaaaa);", 19700 Style)); 19701 } 19702 19703 TEST_F(FormatTest, BreakPenaltyAfterForLoopLParen) { 19704 FormatStyle Style = getLLVMStyle(); 19705 Style.ColumnLimit = 4; 19706 Style.PenaltyExcessCharacter = 100; 19707 verifyFormat("for (\n" 19708 " int iiiiiiiiiiiiiiiii =\n" 19709 " 0;\n" 19710 " iiiiiiiiiiiiiiiii <\n" 19711 " 2;\n" 19712 " iiiiiiiiiiiiiiiii++) {\n" 19713 "}", 19714 19715 Style); 19716 Style.PenaltyBreakOpenParenthesis = 1250; 19717 EXPECT_EQ("for (int iiiiiiiiiiiiiiiii =\n" 19718 " 0;\n" 19719 " iiiiiiiiiiiiiiiii <\n" 19720 " 2;\n" 19721 " iiiiiiiiiiiiiiiii++) {\n" 19722 "}", 19723 format("for (\n" 19724 " int iiiiiiiiiiiiiiiii =\n" 19725 " 0;\n" 19726 " iiiiiiiiiiiiiiiii <\n" 19727 " 2;\n" 19728 " iiiiiiiiiiiiiiiii++) {\n" 19729 "}", 19730 Style)); 19731 } 19732 19733 #define EXPECT_ALL_STYLES_EQUAL(Styles) \ 19734 for (size_t i = 1; i < Styles.size(); ++i) \ 19735 EXPECT_EQ(Styles[0], Styles[i]) \ 19736 << "Style #" << i << " of " << Styles.size() << " differs from Style #0" 19737 19738 TEST_F(FormatTest, GetsPredefinedStyleByName) { 19739 SmallVector<FormatStyle, 3> Styles; 19740 Styles.resize(3); 19741 19742 Styles[0] = getLLVMStyle(); 19743 EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1])); 19744 EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2])); 19745 EXPECT_ALL_STYLES_EQUAL(Styles); 19746 19747 Styles[0] = getGoogleStyle(); 19748 EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1])); 19749 EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2])); 19750 EXPECT_ALL_STYLES_EQUAL(Styles); 19751 19752 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript); 19753 EXPECT_TRUE( 19754 getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1])); 19755 EXPECT_TRUE( 19756 getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2])); 19757 EXPECT_ALL_STYLES_EQUAL(Styles); 19758 19759 Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp); 19760 EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1])); 19761 EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2])); 19762 EXPECT_ALL_STYLES_EQUAL(Styles); 19763 19764 Styles[0] = getMozillaStyle(); 19765 EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1])); 19766 EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2])); 19767 EXPECT_ALL_STYLES_EQUAL(Styles); 19768 19769 Styles[0] = getWebKitStyle(); 19770 EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1])); 19771 EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2])); 19772 EXPECT_ALL_STYLES_EQUAL(Styles); 19773 19774 Styles[0] = getGNUStyle(); 19775 EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1])); 19776 EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2])); 19777 EXPECT_ALL_STYLES_EQUAL(Styles); 19778 19779 EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0])); 19780 } 19781 19782 TEST_F(FormatTest, GetsCorrectBasedOnStyle) { 19783 SmallVector<FormatStyle, 8> Styles; 19784 Styles.resize(2); 19785 19786 Styles[0] = getGoogleStyle(); 19787 Styles[1] = getLLVMStyle(); 19788 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value()); 19789 EXPECT_ALL_STYLES_EQUAL(Styles); 19790 19791 Styles.resize(5); 19792 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript); 19793 Styles[1] = getLLVMStyle(); 19794 Styles[1].Language = FormatStyle::LK_JavaScript; 19795 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value()); 19796 19797 Styles[2] = getLLVMStyle(); 19798 Styles[2].Language = FormatStyle::LK_JavaScript; 19799 EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n" 19800 "BasedOnStyle: Google", 19801 &Styles[2]) 19802 .value()); 19803 19804 Styles[3] = getLLVMStyle(); 19805 Styles[3].Language = FormatStyle::LK_JavaScript; 19806 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n" 19807 "Language: JavaScript", 19808 &Styles[3]) 19809 .value()); 19810 19811 Styles[4] = getLLVMStyle(); 19812 Styles[4].Language = FormatStyle::LK_JavaScript; 19813 EXPECT_EQ(0, parseConfiguration("---\n" 19814 "BasedOnStyle: LLVM\n" 19815 "IndentWidth: 123\n" 19816 "---\n" 19817 "BasedOnStyle: Google\n" 19818 "Language: JavaScript", 19819 &Styles[4]) 19820 .value()); 19821 EXPECT_ALL_STYLES_EQUAL(Styles); 19822 } 19823 19824 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME) \ 19825 Style.FIELD = false; \ 19826 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value()); \ 19827 EXPECT_TRUE(Style.FIELD); \ 19828 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value()); \ 19829 EXPECT_FALSE(Style.FIELD); 19830 19831 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD) 19832 19833 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME) \ 19834 Style.STRUCT.FIELD = false; \ 19835 EXPECT_EQ(0, \ 19836 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": true", &Style) \ 19837 .value()); \ 19838 EXPECT_TRUE(Style.STRUCT.FIELD); \ 19839 EXPECT_EQ(0, \ 19840 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": false", &Style) \ 19841 .value()); \ 19842 EXPECT_FALSE(Style.STRUCT.FIELD); 19843 19844 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD) \ 19845 CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD) 19846 19847 #define CHECK_PARSE(TEXT, FIELD, VALUE) \ 19848 EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!"; \ 19849 EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value()); \ 19850 EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!" 19851 19852 TEST_F(FormatTest, ParsesConfigurationBools) { 19853 FormatStyle Style = {}; 19854 Style.Language = FormatStyle::LK_Cpp; 19855 CHECK_PARSE_BOOL(AlignTrailingComments); 19856 CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine); 19857 CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine); 19858 CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine); 19859 CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine); 19860 CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine); 19861 CHECK_PARSE_BOOL(BinPackArguments); 19862 CHECK_PARSE_BOOL(BinPackParameters); 19863 CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations); 19864 CHECK_PARSE_BOOL(BreakBeforeTernaryOperators); 19865 CHECK_PARSE_BOOL(BreakStringLiterals); 19866 CHECK_PARSE_BOOL(CompactNamespaces); 19867 CHECK_PARSE_BOOL(DeriveLineEnding); 19868 CHECK_PARSE_BOOL(DerivePointerAlignment); 19869 CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding"); 19870 CHECK_PARSE_BOOL(DisableFormat); 19871 CHECK_PARSE_BOOL(IndentAccessModifiers); 19872 CHECK_PARSE_BOOL(IndentCaseLabels); 19873 CHECK_PARSE_BOOL(IndentCaseBlocks); 19874 CHECK_PARSE_BOOL(IndentGotoLabels); 19875 CHECK_PARSE_BOOL_FIELD(IndentRequiresClause, "IndentRequires"); 19876 CHECK_PARSE_BOOL(IndentRequiresClause); 19877 CHECK_PARSE_BOOL(IndentWrappedFunctionNames); 19878 CHECK_PARSE_BOOL(InsertBraces); 19879 CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks); 19880 CHECK_PARSE_BOOL(ObjCSpaceAfterProperty); 19881 CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList); 19882 CHECK_PARSE_BOOL(Cpp11BracedListStyle); 19883 CHECK_PARSE_BOOL(ReflowComments); 19884 CHECK_PARSE_BOOL(RemoveBracesLLVM); 19885 CHECK_PARSE_BOOL(SortUsingDeclarations); 19886 CHECK_PARSE_BOOL(SpacesInParentheses); 19887 CHECK_PARSE_BOOL(SpacesInSquareBrackets); 19888 CHECK_PARSE_BOOL(SpacesInConditionalStatement); 19889 CHECK_PARSE_BOOL(SpaceInEmptyBlock); 19890 CHECK_PARSE_BOOL(SpaceInEmptyParentheses); 19891 CHECK_PARSE_BOOL(SpacesInContainerLiterals); 19892 CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses); 19893 CHECK_PARSE_BOOL(SpaceAfterCStyleCast); 19894 CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword); 19895 CHECK_PARSE_BOOL(SpaceAfterLogicalNot); 19896 CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators); 19897 CHECK_PARSE_BOOL(SpaceBeforeCaseColon); 19898 CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList); 19899 CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon); 19900 CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon); 19901 CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon); 19902 CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets); 19903 CHECK_PARSE_BOOL(UseCRLF); 19904 19905 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel); 19906 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass); 19907 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum); 19908 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction); 19909 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace); 19910 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration); 19911 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct); 19912 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion); 19913 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock); 19914 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch); 19915 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse); 19916 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody); 19917 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile); 19918 CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces); 19919 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction); 19920 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord); 19921 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace); 19922 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterControlStatements); 19923 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterForeachMacros); 19924 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, 19925 AfterFunctionDeclarationName); 19926 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, 19927 AfterFunctionDefinitionName); 19928 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterIfMacros); 19929 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterOverloadedOperator); 19930 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, BeforeNonEmptyParentheses); 19931 } 19932 19933 #undef CHECK_PARSE_BOOL 19934 19935 TEST_F(FormatTest, ParsesConfiguration) { 19936 FormatStyle Style = {}; 19937 Style.Language = FormatStyle::LK_Cpp; 19938 CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234); 19939 CHECK_PARSE("ConstructorInitializerIndentWidth: 1234", 19940 ConstructorInitializerIndentWidth, 1234u); 19941 CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u); 19942 CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u); 19943 CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u); 19944 CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u); 19945 CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234", 19946 PenaltyBreakBeforeFirstCallParameter, 1234u); 19947 CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234", 19948 PenaltyBreakTemplateDeclaration, 1234u); 19949 CHECK_PARSE("PenaltyBreakOpenParenthesis: 1234", PenaltyBreakOpenParenthesis, 19950 1234u); 19951 CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u); 19952 CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234", 19953 PenaltyReturnTypeOnItsOwnLine, 1234u); 19954 CHECK_PARSE("SpacesBeforeTrailingComments: 1234", 19955 SpacesBeforeTrailingComments, 1234u); 19956 CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u); 19957 CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u); 19958 CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$"); 19959 19960 Style.QualifierAlignment = FormatStyle::QAS_Right; 19961 CHECK_PARSE("QualifierAlignment: Leave", QualifierAlignment, 19962 FormatStyle::QAS_Leave); 19963 CHECK_PARSE("QualifierAlignment: Right", QualifierAlignment, 19964 FormatStyle::QAS_Right); 19965 CHECK_PARSE("QualifierAlignment: Left", QualifierAlignment, 19966 FormatStyle::QAS_Left); 19967 CHECK_PARSE("QualifierAlignment: Custom", QualifierAlignment, 19968 FormatStyle::QAS_Custom); 19969 19970 Style.QualifierOrder.clear(); 19971 CHECK_PARSE("QualifierOrder: [ const, volatile, type ]", QualifierOrder, 19972 std::vector<std::string>({"const", "volatile", "type"})); 19973 Style.QualifierOrder.clear(); 19974 CHECK_PARSE("QualifierOrder: [const, type]", QualifierOrder, 19975 std::vector<std::string>({"const", "type"})); 19976 Style.QualifierOrder.clear(); 19977 CHECK_PARSE("QualifierOrder: [volatile, type]", QualifierOrder, 19978 std::vector<std::string>({"volatile", "type"})); 19979 19980 #define CHECK_ALIGN_CONSECUTIVE(FIELD) \ 19981 do { \ 19982 Style.FIELD.Enabled = true; \ 19983 CHECK_PARSE(#FIELD ": None", FIELD, \ 19984 FormatStyle::AlignConsecutiveStyle( \ 19985 {/*Enabled=*/false, /*AcrossEmptyLines=*/false, \ 19986 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 19987 /*PadOperators=*/true})); \ 19988 CHECK_PARSE(#FIELD ": Consecutive", FIELD, \ 19989 FormatStyle::AlignConsecutiveStyle( \ 19990 {/*Enabled=*/true, /*AcrossEmptyLines=*/false, \ 19991 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 19992 /*PadOperators=*/true})); \ 19993 CHECK_PARSE(#FIELD ": AcrossEmptyLines", FIELD, \ 19994 FormatStyle::AlignConsecutiveStyle( \ 19995 {/*Enabled=*/true, /*AcrossEmptyLines=*/true, \ 19996 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 19997 /*PadOperators=*/true})); \ 19998 CHECK_PARSE(#FIELD ": AcrossEmptyLinesAndComments", FIELD, \ 19999 FormatStyle::AlignConsecutiveStyle( \ 20000 {/*Enabled=*/true, /*AcrossEmptyLines=*/true, \ 20001 /*AcrossComments=*/true, /*AlignCompound=*/false, \ 20002 /*PadOperators=*/true})); \ 20003 /* For backwards compability, false / true should still parse */ \ 20004 CHECK_PARSE(#FIELD ": false", FIELD, \ 20005 FormatStyle::AlignConsecutiveStyle( \ 20006 {/*Enabled=*/false, /*AcrossEmptyLines=*/false, \ 20007 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 20008 /*PadOperators=*/true})); \ 20009 CHECK_PARSE(#FIELD ": true", FIELD, \ 20010 FormatStyle::AlignConsecutiveStyle( \ 20011 {/*Enabled=*/true, /*AcrossEmptyLines=*/false, \ 20012 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 20013 /*PadOperators=*/true})); \ 20014 \ 20015 CHECK_PARSE_NESTED_BOOL(FIELD, Enabled); \ 20016 CHECK_PARSE_NESTED_BOOL(FIELD, AcrossEmptyLines); \ 20017 CHECK_PARSE_NESTED_BOOL(FIELD, AcrossComments); \ 20018 CHECK_PARSE_NESTED_BOOL(FIELD, AlignCompound); \ 20019 CHECK_PARSE_NESTED_BOOL(FIELD, PadOperators); \ 20020 } while (false) 20021 20022 CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveAssignments); 20023 CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveBitFields); 20024 CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveMacros); 20025 CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveDeclarations); 20026 20027 #undef CHECK_ALIGN_CONSECUTIVE 20028 20029 Style.PointerAlignment = FormatStyle::PAS_Middle; 20030 CHECK_PARSE("PointerAlignment: Left", PointerAlignment, 20031 FormatStyle::PAS_Left); 20032 CHECK_PARSE("PointerAlignment: Right", PointerAlignment, 20033 FormatStyle::PAS_Right); 20034 CHECK_PARSE("PointerAlignment: Middle", PointerAlignment, 20035 FormatStyle::PAS_Middle); 20036 Style.ReferenceAlignment = FormatStyle::RAS_Middle; 20037 CHECK_PARSE("ReferenceAlignment: Pointer", ReferenceAlignment, 20038 FormatStyle::RAS_Pointer); 20039 CHECK_PARSE("ReferenceAlignment: Left", ReferenceAlignment, 20040 FormatStyle::RAS_Left); 20041 CHECK_PARSE("ReferenceAlignment: Right", ReferenceAlignment, 20042 FormatStyle::RAS_Right); 20043 CHECK_PARSE("ReferenceAlignment: Middle", ReferenceAlignment, 20044 FormatStyle::RAS_Middle); 20045 // For backward compatibility: 20046 CHECK_PARSE("PointerBindsToType: Left", PointerAlignment, 20047 FormatStyle::PAS_Left); 20048 CHECK_PARSE("PointerBindsToType: Right", PointerAlignment, 20049 FormatStyle::PAS_Right); 20050 CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment, 20051 FormatStyle::PAS_Middle); 20052 20053 Style.Standard = FormatStyle::LS_Auto; 20054 CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03); 20055 CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11); 20056 CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14); 20057 CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17); 20058 CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20); 20059 CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto); 20060 CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest); 20061 // Legacy aliases: 20062 CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03); 20063 CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest); 20064 CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03); 20065 CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11); 20066 20067 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 20068 CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment", 20069 BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment); 20070 CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators, 20071 FormatStyle::BOS_None); 20072 CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators, 20073 FormatStyle::BOS_All); 20074 // For backward compatibility: 20075 CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators, 20076 FormatStyle::BOS_None); 20077 CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators, 20078 FormatStyle::BOS_All); 20079 20080 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 20081 CHECK_PARSE("BreakConstructorInitializers: BeforeComma", 20082 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma); 20083 CHECK_PARSE("BreakConstructorInitializers: AfterColon", 20084 BreakConstructorInitializers, FormatStyle::BCIS_AfterColon); 20085 CHECK_PARSE("BreakConstructorInitializers: BeforeColon", 20086 BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon); 20087 // For backward compatibility: 20088 CHECK_PARSE("BreakConstructorInitializersBeforeComma: true", 20089 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma); 20090 20091 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 20092 CHECK_PARSE("BreakInheritanceList: AfterComma", BreakInheritanceList, 20093 FormatStyle::BILS_AfterComma); 20094 CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList, 20095 FormatStyle::BILS_BeforeComma); 20096 CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList, 20097 FormatStyle::BILS_AfterColon); 20098 CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList, 20099 FormatStyle::BILS_BeforeColon); 20100 // For backward compatibility: 20101 CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList, 20102 FormatStyle::BILS_BeforeComma); 20103 20104 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 20105 CHECK_PARSE("PackConstructorInitializers: Never", PackConstructorInitializers, 20106 FormatStyle::PCIS_Never); 20107 CHECK_PARSE("PackConstructorInitializers: BinPack", 20108 PackConstructorInitializers, FormatStyle::PCIS_BinPack); 20109 CHECK_PARSE("PackConstructorInitializers: CurrentLine", 20110 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 20111 CHECK_PARSE("PackConstructorInitializers: NextLine", 20112 PackConstructorInitializers, FormatStyle::PCIS_NextLine); 20113 // For backward compatibility: 20114 CHECK_PARSE("BasedOnStyle: Google\n" 20115 "ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 20116 "AllowAllConstructorInitializersOnNextLine: false", 20117 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 20118 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 20119 CHECK_PARSE("BasedOnStyle: Google\n" 20120 "ConstructorInitializerAllOnOneLineOrOnePerLine: false", 20121 PackConstructorInitializers, FormatStyle::PCIS_BinPack); 20122 CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 20123 "AllowAllConstructorInitializersOnNextLine: true", 20124 PackConstructorInitializers, FormatStyle::PCIS_NextLine); 20125 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 20126 CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 20127 "AllowAllConstructorInitializersOnNextLine: false", 20128 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 20129 20130 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 20131 CHECK_PARSE("EmptyLineBeforeAccessModifier: Never", 20132 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never); 20133 CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave", 20134 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave); 20135 CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock", 20136 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock); 20137 CHECK_PARSE("EmptyLineBeforeAccessModifier: Always", 20138 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always); 20139 20140 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 20141 CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket, 20142 FormatStyle::BAS_Align); 20143 CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket, 20144 FormatStyle::BAS_DontAlign); 20145 CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket, 20146 FormatStyle::BAS_AlwaysBreak); 20147 CHECK_PARSE("AlignAfterOpenBracket: BlockIndent", AlignAfterOpenBracket, 20148 FormatStyle::BAS_BlockIndent); 20149 // For backward compatibility: 20150 CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket, 20151 FormatStyle::BAS_DontAlign); 20152 CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket, 20153 FormatStyle::BAS_Align); 20154 20155 Style.AlignEscapedNewlines = FormatStyle::ENAS_Left; 20156 CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines, 20157 FormatStyle::ENAS_DontAlign); 20158 CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines, 20159 FormatStyle::ENAS_Left); 20160 CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines, 20161 FormatStyle::ENAS_Right); 20162 // For backward compatibility: 20163 CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines, 20164 FormatStyle::ENAS_Left); 20165 CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines, 20166 FormatStyle::ENAS_Right); 20167 20168 Style.AlignOperands = FormatStyle::OAS_Align; 20169 CHECK_PARSE("AlignOperands: DontAlign", AlignOperands, 20170 FormatStyle::OAS_DontAlign); 20171 CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align); 20172 CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands, 20173 FormatStyle::OAS_AlignAfterOperator); 20174 // For backward compatibility: 20175 CHECK_PARSE("AlignOperands: false", AlignOperands, 20176 FormatStyle::OAS_DontAlign); 20177 CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align); 20178 20179 Style.UseTab = FormatStyle::UT_ForIndentation; 20180 CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never); 20181 CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation); 20182 CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always); 20183 CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab, 20184 FormatStyle::UT_ForContinuationAndIndentation); 20185 CHECK_PARSE("UseTab: AlignWithSpaces", UseTab, 20186 FormatStyle::UT_AlignWithSpaces); 20187 // For backward compatibility: 20188 CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never); 20189 CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always); 20190 20191 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 20192 CHECK_PARSE("AllowShortBlocksOnASingleLine: Never", 20193 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 20194 CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty", 20195 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty); 20196 CHECK_PARSE("AllowShortBlocksOnASingleLine: Always", 20197 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always); 20198 // For backward compatibility: 20199 CHECK_PARSE("AllowShortBlocksOnASingleLine: false", 20200 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 20201 CHECK_PARSE("AllowShortBlocksOnASingleLine: true", 20202 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always); 20203 20204 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 20205 CHECK_PARSE("AllowShortFunctionsOnASingleLine: None", 20206 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None); 20207 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline", 20208 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline); 20209 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty", 20210 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty); 20211 CHECK_PARSE("AllowShortFunctionsOnASingleLine: All", 20212 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All); 20213 // For backward compatibility: 20214 CHECK_PARSE("AllowShortFunctionsOnASingleLine: false", 20215 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None); 20216 CHECK_PARSE("AllowShortFunctionsOnASingleLine: true", 20217 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All); 20218 20219 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both; 20220 CHECK_PARSE("SpaceAroundPointerQualifiers: Default", 20221 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default); 20222 CHECK_PARSE("SpaceAroundPointerQualifiers: Before", 20223 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before); 20224 CHECK_PARSE("SpaceAroundPointerQualifiers: After", 20225 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After); 20226 CHECK_PARSE("SpaceAroundPointerQualifiers: Both", 20227 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both); 20228 20229 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 20230 CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens, 20231 FormatStyle::SBPO_Never); 20232 CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens, 20233 FormatStyle::SBPO_Always); 20234 CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens, 20235 FormatStyle::SBPO_ControlStatements); 20236 CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptControlMacros", 20237 SpaceBeforeParens, 20238 FormatStyle::SBPO_ControlStatementsExceptControlMacros); 20239 CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens, 20240 FormatStyle::SBPO_NonEmptyParentheses); 20241 CHECK_PARSE("SpaceBeforeParens: Custom", SpaceBeforeParens, 20242 FormatStyle::SBPO_Custom); 20243 // For backward compatibility: 20244 CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens, 20245 FormatStyle::SBPO_Never); 20246 CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens, 20247 FormatStyle::SBPO_ControlStatements); 20248 CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptForEachMacros", 20249 SpaceBeforeParens, 20250 FormatStyle::SBPO_ControlStatementsExceptControlMacros); 20251 20252 Style.ColumnLimit = 123; 20253 FormatStyle BaseStyle = getLLVMStyle(); 20254 CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit); 20255 CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u); 20256 20257 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 20258 CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces, 20259 FormatStyle::BS_Attach); 20260 CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces, 20261 FormatStyle::BS_Linux); 20262 CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces, 20263 FormatStyle::BS_Mozilla); 20264 CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces, 20265 FormatStyle::BS_Stroustrup); 20266 CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces, 20267 FormatStyle::BS_Allman); 20268 CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces, 20269 FormatStyle::BS_Whitesmiths); 20270 CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU); 20271 CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces, 20272 FormatStyle::BS_WebKit); 20273 CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces, 20274 FormatStyle::BS_Custom); 20275 20276 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never; 20277 CHECK_PARSE("BraceWrapping:\n" 20278 " AfterControlStatement: MultiLine", 20279 BraceWrapping.AfterControlStatement, 20280 FormatStyle::BWACS_MultiLine); 20281 CHECK_PARSE("BraceWrapping:\n" 20282 " AfterControlStatement: Always", 20283 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always); 20284 CHECK_PARSE("BraceWrapping:\n" 20285 " AfterControlStatement: Never", 20286 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never); 20287 // For backward compatibility: 20288 CHECK_PARSE("BraceWrapping:\n" 20289 " AfterControlStatement: true", 20290 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always); 20291 CHECK_PARSE("BraceWrapping:\n" 20292 " AfterControlStatement: false", 20293 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never); 20294 20295 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 20296 CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType, 20297 FormatStyle::RTBS_None); 20298 CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType, 20299 FormatStyle::RTBS_All); 20300 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel", 20301 AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel); 20302 CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions", 20303 AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions); 20304 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions", 20305 AlwaysBreakAfterReturnType, 20306 FormatStyle::RTBS_TopLevelDefinitions); 20307 20308 Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 20309 CHECK_PARSE("AlwaysBreakTemplateDeclarations: No", 20310 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No); 20311 CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine", 20312 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine); 20313 CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes", 20314 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes); 20315 CHECK_PARSE("AlwaysBreakTemplateDeclarations: false", 20316 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine); 20317 CHECK_PARSE("AlwaysBreakTemplateDeclarations: true", 20318 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes); 20319 20320 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All; 20321 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None", 20322 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None); 20323 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All", 20324 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All); 20325 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel", 20326 AlwaysBreakAfterDefinitionReturnType, 20327 FormatStyle::DRTBS_TopLevel); 20328 20329 Style.NamespaceIndentation = FormatStyle::NI_All; 20330 CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation, 20331 FormatStyle::NI_None); 20332 CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation, 20333 FormatStyle::NI_Inner); 20334 CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation, 20335 FormatStyle::NI_All); 20336 20337 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_OnlyFirstIf; 20338 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never", 20339 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never); 20340 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse", 20341 AllowShortIfStatementsOnASingleLine, 20342 FormatStyle::SIS_WithoutElse); 20343 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: OnlyFirstIf", 20344 AllowShortIfStatementsOnASingleLine, 20345 FormatStyle::SIS_OnlyFirstIf); 20346 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: AllIfsAndElse", 20347 AllowShortIfStatementsOnASingleLine, 20348 FormatStyle::SIS_AllIfsAndElse); 20349 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always", 20350 AllowShortIfStatementsOnASingleLine, 20351 FormatStyle::SIS_OnlyFirstIf); 20352 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false", 20353 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never); 20354 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true", 20355 AllowShortIfStatementsOnASingleLine, 20356 FormatStyle::SIS_WithoutElse); 20357 20358 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 20359 CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock, 20360 FormatStyle::IEBS_AfterExternBlock); 20361 CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock, 20362 FormatStyle::IEBS_Indent); 20363 CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock, 20364 FormatStyle::IEBS_NoIndent); 20365 CHECK_PARSE("IndentExternBlock: true", IndentExternBlock, 20366 FormatStyle::IEBS_Indent); 20367 CHECK_PARSE("IndentExternBlock: false", IndentExternBlock, 20368 FormatStyle::IEBS_NoIndent); 20369 20370 Style.BitFieldColonSpacing = FormatStyle::BFCS_None; 20371 CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing, 20372 FormatStyle::BFCS_Both); 20373 CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing, 20374 FormatStyle::BFCS_None); 20375 CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing, 20376 FormatStyle::BFCS_Before); 20377 CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing, 20378 FormatStyle::BFCS_After); 20379 20380 Style.SortJavaStaticImport = FormatStyle::SJSIO_Before; 20381 CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport, 20382 FormatStyle::SJSIO_After); 20383 CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport, 20384 FormatStyle::SJSIO_Before); 20385 20386 // FIXME: This is required because parsing a configuration simply overwrites 20387 // the first N elements of the list instead of resetting it. 20388 Style.ForEachMacros.clear(); 20389 std::vector<std::string> BoostForeach; 20390 BoostForeach.push_back("BOOST_FOREACH"); 20391 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach); 20392 std::vector<std::string> BoostAndQForeach; 20393 BoostAndQForeach.push_back("BOOST_FOREACH"); 20394 BoostAndQForeach.push_back("Q_FOREACH"); 20395 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros, 20396 BoostAndQForeach); 20397 20398 Style.IfMacros.clear(); 20399 std::vector<std::string> CustomIfs; 20400 CustomIfs.push_back("MYIF"); 20401 CHECK_PARSE("IfMacros: [MYIF]", IfMacros, CustomIfs); 20402 20403 Style.AttributeMacros.clear(); 20404 CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros, 20405 std::vector<std::string>{"__capability"}); 20406 CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros, 20407 std::vector<std::string>({"attr1", "attr2"})); 20408 20409 Style.StatementAttributeLikeMacros.clear(); 20410 CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]", 20411 StatementAttributeLikeMacros, 20412 std::vector<std::string>({"emit", "Q_EMIT"})); 20413 20414 Style.StatementMacros.clear(); 20415 CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros, 20416 std::vector<std::string>{"QUNUSED"}); 20417 CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros, 20418 std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"})); 20419 20420 Style.NamespaceMacros.clear(); 20421 CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros, 20422 std::vector<std::string>{"TESTSUITE"}); 20423 CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros, 20424 std::vector<std::string>({"TESTSUITE", "SUITE"})); 20425 20426 Style.WhitespaceSensitiveMacros.clear(); 20427 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]", 20428 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"}); 20429 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]", 20430 WhitespaceSensitiveMacros, 20431 std::vector<std::string>({"STRINGIZE", "ASSERT"})); 20432 Style.WhitespaceSensitiveMacros.clear(); 20433 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']", 20434 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"}); 20435 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']", 20436 WhitespaceSensitiveMacros, 20437 std::vector<std::string>({"STRINGIZE", "ASSERT"})); 20438 20439 Style.IncludeStyle.IncludeCategories.clear(); 20440 std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = { 20441 {"abc/.*", 2, 0, false}, {".*", 1, 0, true}}; 20442 CHECK_PARSE("IncludeCategories:\n" 20443 " - Regex: abc/.*\n" 20444 " Priority: 2\n" 20445 " - Regex: .*\n" 20446 " Priority: 1\n" 20447 " CaseSensitive: true\n", 20448 IncludeStyle.IncludeCategories, ExpectedCategories); 20449 CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex, 20450 "abc$"); 20451 CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'", 20452 IncludeStyle.IncludeIsMainSourceRegex, "abc$"); 20453 20454 Style.SortIncludes = FormatStyle::SI_Never; 20455 CHECK_PARSE("SortIncludes: true", SortIncludes, 20456 FormatStyle::SI_CaseSensitive); 20457 CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never); 20458 CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes, 20459 FormatStyle::SI_CaseInsensitive); 20460 CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes, 20461 FormatStyle::SI_CaseSensitive); 20462 CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never); 20463 20464 Style.RawStringFormats.clear(); 20465 std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = { 20466 { 20467 FormatStyle::LK_TextProto, 20468 {"pb", "proto"}, 20469 {"PARSE_TEXT_PROTO"}, 20470 /*CanonicalDelimiter=*/"", 20471 "llvm", 20472 }, 20473 { 20474 FormatStyle::LK_Cpp, 20475 {"cc", "cpp"}, 20476 {"C_CODEBLOCK", "CPPEVAL"}, 20477 /*CanonicalDelimiter=*/"cc", 20478 /*BasedOnStyle=*/"", 20479 }, 20480 }; 20481 20482 CHECK_PARSE("RawStringFormats:\n" 20483 " - Language: TextProto\n" 20484 " Delimiters:\n" 20485 " - 'pb'\n" 20486 " - 'proto'\n" 20487 " EnclosingFunctions:\n" 20488 " - 'PARSE_TEXT_PROTO'\n" 20489 " BasedOnStyle: llvm\n" 20490 " - Language: Cpp\n" 20491 " Delimiters:\n" 20492 " - 'cc'\n" 20493 " - 'cpp'\n" 20494 " EnclosingFunctions:\n" 20495 " - 'C_CODEBLOCK'\n" 20496 " - 'CPPEVAL'\n" 20497 " CanonicalDelimiter: 'cc'", 20498 RawStringFormats, ExpectedRawStringFormats); 20499 20500 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20501 " Minimum: 0\n" 20502 " Maximum: 0", 20503 SpacesInLineCommentPrefix.Minimum, 0u); 20504 EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u); 20505 Style.SpacesInLineCommentPrefix.Minimum = 1; 20506 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20507 " Minimum: 2", 20508 SpacesInLineCommentPrefix.Minimum, 0u); 20509 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20510 " Maximum: -1", 20511 SpacesInLineCommentPrefix.Maximum, -1u); 20512 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20513 " Minimum: 2", 20514 SpacesInLineCommentPrefix.Minimum, 2u); 20515 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20516 " Maximum: 1", 20517 SpacesInLineCommentPrefix.Maximum, 1u); 20518 EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u); 20519 20520 Style.SpacesInAngles = FormatStyle::SIAS_Always; 20521 CHECK_PARSE("SpacesInAngles: Never", SpacesInAngles, FormatStyle::SIAS_Never); 20522 CHECK_PARSE("SpacesInAngles: Always", SpacesInAngles, 20523 FormatStyle::SIAS_Always); 20524 CHECK_PARSE("SpacesInAngles: Leave", SpacesInAngles, FormatStyle::SIAS_Leave); 20525 // For backward compatibility: 20526 CHECK_PARSE("SpacesInAngles: false", SpacesInAngles, FormatStyle::SIAS_Never); 20527 CHECK_PARSE("SpacesInAngles: true", SpacesInAngles, FormatStyle::SIAS_Always); 20528 20529 CHECK_PARSE("RequiresClausePosition: WithPreceding", RequiresClausePosition, 20530 FormatStyle::RCPS_WithPreceding); 20531 CHECK_PARSE("RequiresClausePosition: WithFollowing", RequiresClausePosition, 20532 FormatStyle::RCPS_WithFollowing); 20533 CHECK_PARSE("RequiresClausePosition: SingleLine", RequiresClausePosition, 20534 FormatStyle::RCPS_SingleLine); 20535 CHECK_PARSE("RequiresClausePosition: OwnLine", RequiresClausePosition, 20536 FormatStyle::RCPS_OwnLine); 20537 20538 CHECK_PARSE("BreakBeforeConceptDeclarations: Never", 20539 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Never); 20540 CHECK_PARSE("BreakBeforeConceptDeclarations: Always", 20541 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always); 20542 CHECK_PARSE("BreakBeforeConceptDeclarations: Allowed", 20543 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed); 20544 // For backward compatibility: 20545 CHECK_PARSE("BreakBeforeConceptDeclarations: true", 20546 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always); 20547 CHECK_PARSE("BreakBeforeConceptDeclarations: false", 20548 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed); 20549 } 20550 20551 TEST_F(FormatTest, ParsesConfigurationWithLanguages) { 20552 FormatStyle Style = {}; 20553 Style.Language = FormatStyle::LK_Cpp; 20554 CHECK_PARSE("Language: Cpp\n" 20555 "IndentWidth: 12", 20556 IndentWidth, 12u); 20557 EXPECT_EQ(parseConfiguration("Language: JavaScript\n" 20558 "IndentWidth: 34", 20559 &Style), 20560 ParseError::Unsuitable); 20561 FormatStyle BinPackedTCS = {}; 20562 BinPackedTCS.Language = FormatStyle::LK_JavaScript; 20563 EXPECT_EQ(parseConfiguration("BinPackArguments: true\n" 20564 "InsertTrailingCommas: Wrapped", 20565 &BinPackedTCS), 20566 ParseError::BinPackTrailingCommaConflict); 20567 EXPECT_EQ(12u, Style.IndentWidth); 20568 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u); 20569 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language); 20570 20571 Style.Language = FormatStyle::LK_JavaScript; 20572 CHECK_PARSE("Language: JavaScript\n" 20573 "IndentWidth: 12", 20574 IndentWidth, 12u); 20575 CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u); 20576 EXPECT_EQ(parseConfiguration("Language: Cpp\n" 20577 "IndentWidth: 34", 20578 &Style), 20579 ParseError::Unsuitable); 20580 EXPECT_EQ(23u, Style.IndentWidth); 20581 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u); 20582 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language); 20583 20584 CHECK_PARSE("BasedOnStyle: LLVM\n" 20585 "IndentWidth: 67", 20586 IndentWidth, 67u); 20587 20588 CHECK_PARSE("---\n" 20589 "Language: JavaScript\n" 20590 "IndentWidth: 12\n" 20591 "---\n" 20592 "Language: Cpp\n" 20593 "IndentWidth: 34\n" 20594 "...\n", 20595 IndentWidth, 12u); 20596 20597 Style.Language = FormatStyle::LK_Cpp; 20598 CHECK_PARSE("---\n" 20599 "Language: JavaScript\n" 20600 "IndentWidth: 12\n" 20601 "---\n" 20602 "Language: Cpp\n" 20603 "IndentWidth: 34\n" 20604 "...\n", 20605 IndentWidth, 34u); 20606 CHECK_PARSE("---\n" 20607 "IndentWidth: 78\n" 20608 "---\n" 20609 "Language: JavaScript\n" 20610 "IndentWidth: 56\n" 20611 "...\n", 20612 IndentWidth, 78u); 20613 20614 Style.ColumnLimit = 123; 20615 Style.IndentWidth = 234; 20616 Style.BreakBeforeBraces = FormatStyle::BS_Linux; 20617 Style.TabWidth = 345; 20618 EXPECT_FALSE(parseConfiguration("---\n" 20619 "IndentWidth: 456\n" 20620 "BreakBeforeBraces: Allman\n" 20621 "---\n" 20622 "Language: JavaScript\n" 20623 "IndentWidth: 111\n" 20624 "TabWidth: 111\n" 20625 "---\n" 20626 "Language: Cpp\n" 20627 "BreakBeforeBraces: Stroustrup\n" 20628 "TabWidth: 789\n" 20629 "...\n", 20630 &Style)); 20631 EXPECT_EQ(123u, Style.ColumnLimit); 20632 EXPECT_EQ(456u, Style.IndentWidth); 20633 EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces); 20634 EXPECT_EQ(789u, Style.TabWidth); 20635 20636 EXPECT_EQ(parseConfiguration("---\n" 20637 "Language: JavaScript\n" 20638 "IndentWidth: 56\n" 20639 "---\n" 20640 "IndentWidth: 78\n" 20641 "...\n", 20642 &Style), 20643 ParseError::Error); 20644 EXPECT_EQ(parseConfiguration("---\n" 20645 "Language: JavaScript\n" 20646 "IndentWidth: 56\n" 20647 "---\n" 20648 "Language: JavaScript\n" 20649 "IndentWidth: 78\n" 20650 "...\n", 20651 &Style), 20652 ParseError::Error); 20653 20654 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language); 20655 } 20656 20657 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) { 20658 FormatStyle Style = {}; 20659 Style.Language = FormatStyle::LK_JavaScript; 20660 Style.BreakBeforeTernaryOperators = true; 20661 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value()); 20662 EXPECT_FALSE(Style.BreakBeforeTernaryOperators); 20663 20664 Style.BreakBeforeTernaryOperators = true; 20665 EXPECT_EQ(0, parseConfiguration("---\n" 20666 "BasedOnStyle: Google\n" 20667 "---\n" 20668 "Language: JavaScript\n" 20669 "IndentWidth: 76\n" 20670 "...\n", 20671 &Style) 20672 .value()); 20673 EXPECT_FALSE(Style.BreakBeforeTernaryOperators); 20674 EXPECT_EQ(76u, Style.IndentWidth); 20675 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language); 20676 } 20677 20678 TEST_F(FormatTest, ConfigurationRoundTripTest) { 20679 FormatStyle Style = getLLVMStyle(); 20680 std::string YAML = configurationAsText(Style); 20681 FormatStyle ParsedStyle = {}; 20682 ParsedStyle.Language = FormatStyle::LK_Cpp; 20683 EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value()); 20684 EXPECT_EQ(Style, ParsedStyle); 20685 } 20686 20687 TEST_F(FormatTest, WorksFor8bitEncodings) { 20688 EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n" 20689 "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n" 20690 "\"\xe7\xe8\xec\xed\xfe\xfe \"\n" 20691 "\"\xef\xee\xf0\xf3...\"", 20692 format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 " 20693 "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe " 20694 "\xef\xee\xf0\xf3...\"", 20695 getLLVMStyleWithColumns(12))); 20696 } 20697 20698 TEST_F(FormatTest, HandlesUTF8BOM) { 20699 EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf")); 20700 EXPECT_EQ("\xef\xbb\xbf#include <iostream>", 20701 format("\xef\xbb\xbf#include <iostream>")); 20702 EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>", 20703 format("\xef\xbb\xbf\n#include <iostream>")); 20704 } 20705 20706 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers. 20707 #if !defined(_MSC_VER) 20708 20709 TEST_F(FormatTest, CountsUTF8CharactersProperly) { 20710 verifyFormat("\"Однажды в студёную зимнюю пору...\"", 20711 getLLVMStyleWithColumns(35)); 20712 verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"", 20713 getLLVMStyleWithColumns(31)); 20714 verifyFormat("// Однажды в студёную зимнюю пору...", 20715 getLLVMStyleWithColumns(36)); 20716 verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32)); 20717 verifyFormat("/* Однажды в студёную зимнюю пору... */", 20718 getLLVMStyleWithColumns(39)); 20719 verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */", 20720 getLLVMStyleWithColumns(35)); 20721 } 20722 20723 TEST_F(FormatTest, SplitsUTF8Strings) { 20724 // Non-printable characters' width is currently considered to be the length in 20725 // bytes in UTF8. The characters can be displayed in very different manner 20726 // (zero-width, single width with a substitution glyph, expanded to their code 20727 // (e.g. "<8d>"), so there's no single correct way to handle them. 20728 EXPECT_EQ("\"aaaaÄ\"\n" 20729 "\"\xc2\x8d\";", 20730 format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10))); 20731 EXPECT_EQ("\"aaaaaaaÄ\"\n" 20732 "\"\xc2\x8d\";", 20733 format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10))); 20734 EXPECT_EQ("\"Однажды, в \"\n" 20735 "\"студёную \"\n" 20736 "\"зимнюю \"\n" 20737 "\"пору,\"", 20738 format("\"Однажды, в студёную зимнюю пору,\"", 20739 getLLVMStyleWithColumns(13))); 20740 EXPECT_EQ( 20741 "\"一 二 三 \"\n" 20742 "\"四 五六 \"\n" 20743 "\"七 八 九 \"\n" 20744 "\"十\"", 20745 format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11))); 20746 EXPECT_EQ("\"一\t\"\n" 20747 "\"二 \t\"\n" 20748 "\"三 四 \"\n" 20749 "\"五\t\"\n" 20750 "\"六 \t\"\n" 20751 "\"七 \"\n" 20752 "\"八九十\tqq\"", 20753 format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"", 20754 getLLVMStyleWithColumns(11))); 20755 20756 // UTF8 character in an escape sequence. 20757 EXPECT_EQ("\"aaaaaa\"\n" 20758 "\"\\\xC2\x8D\"", 20759 format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10))); 20760 } 20761 20762 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) { 20763 EXPECT_EQ("const char *sssss =\n" 20764 " \"一二三四五六七八\\\n" 20765 " 九 十\";", 20766 format("const char *sssss = \"一二三四五六七八\\\n" 20767 " 九 十\";", 20768 getLLVMStyleWithColumns(30))); 20769 } 20770 20771 TEST_F(FormatTest, SplitsUTF8LineComments) { 20772 EXPECT_EQ("// aaaaÄ\xc2\x8d", 20773 format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10))); 20774 EXPECT_EQ("// Я из лесу\n" 20775 "// вышел; был\n" 20776 "// сильный\n" 20777 "// мороз.", 20778 format("// Я из лесу вышел; был сильный мороз.", 20779 getLLVMStyleWithColumns(13))); 20780 EXPECT_EQ("// 一二三\n" 20781 "// 四五六七\n" 20782 "// 八 九\n" 20783 "// 十", 20784 format("// 一二三 四五六七 八 九 十", getLLVMStyleWithColumns(9))); 20785 } 20786 20787 TEST_F(FormatTest, SplitsUTF8BlockComments) { 20788 EXPECT_EQ("/* Гляжу,\n" 20789 " * поднимается\n" 20790 " * медленно в\n" 20791 " * гору\n" 20792 " * Лошадка,\n" 20793 " * везущая\n" 20794 " * хворосту\n" 20795 " * воз. */", 20796 format("/* Гляжу, поднимается медленно в гору\n" 20797 " * Лошадка, везущая хворосту воз. */", 20798 getLLVMStyleWithColumns(13))); 20799 EXPECT_EQ( 20800 "/* 一二三\n" 20801 " * 四五六七\n" 20802 " * 八 九\n" 20803 " * 十 */", 20804 format("/* 一二三 四五六七 八 九 十 */", getLLVMStyleWithColumns(9))); 20805 EXPECT_EQ("/* \n" 20806 " * \n" 20807 " * - */", 20808 format("/* - */", getLLVMStyleWithColumns(12))); 20809 } 20810 20811 #endif // _MSC_VER 20812 20813 TEST_F(FormatTest, ConstructorInitializerIndentWidth) { 20814 FormatStyle Style = getLLVMStyle(); 20815 20816 Style.ConstructorInitializerIndentWidth = 4; 20817 verifyFormat( 20818 "SomeClass::Constructor()\n" 20819 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20820 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20821 Style); 20822 20823 Style.ConstructorInitializerIndentWidth = 2; 20824 verifyFormat( 20825 "SomeClass::Constructor()\n" 20826 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20827 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20828 Style); 20829 20830 Style.ConstructorInitializerIndentWidth = 0; 20831 verifyFormat( 20832 "SomeClass::Constructor()\n" 20833 ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20834 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20835 Style); 20836 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 20837 verifyFormat( 20838 "SomeLongTemplateVariableName<\n" 20839 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>", 20840 Style); 20841 verifyFormat("bool smaller = 1 < " 20842 "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 20843 " " 20844 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 20845 Style); 20846 20847 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 20848 verifyFormat("SomeClass::Constructor() :\n" 20849 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n" 20850 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}", 20851 Style); 20852 } 20853 20854 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) { 20855 FormatStyle Style = getLLVMStyle(); 20856 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 20857 Style.ConstructorInitializerIndentWidth = 4; 20858 verifyFormat("SomeClass::Constructor()\n" 20859 " : a(a)\n" 20860 " , b(b)\n" 20861 " , c(c) {}", 20862 Style); 20863 verifyFormat("SomeClass::Constructor()\n" 20864 " : a(a) {}", 20865 Style); 20866 20867 Style.ColumnLimit = 0; 20868 verifyFormat("SomeClass::Constructor()\n" 20869 " : a(a) {}", 20870 Style); 20871 verifyFormat("SomeClass::Constructor() noexcept\n" 20872 " : a(a) {}", 20873 Style); 20874 verifyFormat("SomeClass::Constructor()\n" 20875 " : a(a)\n" 20876 " , b(b)\n" 20877 " , c(c) {}", 20878 Style); 20879 verifyFormat("SomeClass::Constructor()\n" 20880 " : a(a) {\n" 20881 " foo();\n" 20882 " bar();\n" 20883 "}", 20884 Style); 20885 20886 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 20887 verifyFormat("SomeClass::Constructor()\n" 20888 " : a(a)\n" 20889 " , b(b)\n" 20890 " , c(c) {\n}", 20891 Style); 20892 verifyFormat("SomeClass::Constructor()\n" 20893 " : a(a) {\n}", 20894 Style); 20895 20896 Style.ColumnLimit = 80; 20897 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 20898 Style.ConstructorInitializerIndentWidth = 2; 20899 verifyFormat("SomeClass::Constructor()\n" 20900 " : a(a)\n" 20901 " , b(b)\n" 20902 " , c(c) {}", 20903 Style); 20904 20905 Style.ConstructorInitializerIndentWidth = 0; 20906 verifyFormat("SomeClass::Constructor()\n" 20907 ": a(a)\n" 20908 ", b(b)\n" 20909 ", c(c) {}", 20910 Style); 20911 20912 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 20913 Style.ConstructorInitializerIndentWidth = 4; 20914 verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style); 20915 verifyFormat( 20916 "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n", 20917 Style); 20918 verifyFormat( 20919 "SomeClass::Constructor()\n" 20920 " : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}", 20921 Style); 20922 Style.ConstructorInitializerIndentWidth = 4; 20923 Style.ColumnLimit = 60; 20924 verifyFormat("SomeClass::Constructor()\n" 20925 " : aaaaaaaa(aaaaaaaa)\n" 20926 " , aaaaaaaa(aaaaaaaa)\n" 20927 " , aaaaaaaa(aaaaaaaa) {}", 20928 Style); 20929 } 20930 20931 TEST_F(FormatTest, ConstructorInitializersWithPreprocessorDirective) { 20932 FormatStyle Style = getLLVMStyle(); 20933 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 20934 Style.ConstructorInitializerIndentWidth = 4; 20935 verifyFormat("SomeClass::Constructor()\n" 20936 " : a{a}\n" 20937 " , b{b} {}", 20938 Style); 20939 verifyFormat("SomeClass::Constructor()\n" 20940 " : a{a}\n" 20941 "#if CONDITION\n" 20942 " , b{b}\n" 20943 "#endif\n" 20944 "{\n}", 20945 Style); 20946 Style.ConstructorInitializerIndentWidth = 2; 20947 verifyFormat("SomeClass::Constructor()\n" 20948 "#if CONDITION\n" 20949 " : a{a}\n" 20950 "#endif\n" 20951 " , b{b}\n" 20952 " , c{c} {\n}", 20953 Style); 20954 Style.ConstructorInitializerIndentWidth = 0; 20955 verifyFormat("SomeClass::Constructor()\n" 20956 ": a{a}\n" 20957 "#ifdef CONDITION\n" 20958 ", b{b}\n" 20959 "#else\n" 20960 ", c{c}\n" 20961 "#endif\n" 20962 ", d{d} {\n}", 20963 Style); 20964 Style.ConstructorInitializerIndentWidth = 4; 20965 verifyFormat("SomeClass::Constructor()\n" 20966 " : a{a}\n" 20967 "#if WINDOWS\n" 20968 "#if DEBUG\n" 20969 " , b{0}\n" 20970 "#else\n" 20971 " , b{1}\n" 20972 "#endif\n" 20973 "#else\n" 20974 "#if DEBUG\n" 20975 " , b{2}\n" 20976 "#else\n" 20977 " , b{3}\n" 20978 "#endif\n" 20979 "#endif\n" 20980 "{\n}", 20981 Style); 20982 verifyFormat("SomeClass::Constructor()\n" 20983 " : a{a}\n" 20984 "#if WINDOWS\n" 20985 " , b{0}\n" 20986 "#if DEBUG\n" 20987 " , c{0}\n" 20988 "#else\n" 20989 " , c{1}\n" 20990 "#endif\n" 20991 "#else\n" 20992 "#if DEBUG\n" 20993 " , c{2}\n" 20994 "#else\n" 20995 " , c{3}\n" 20996 "#endif\n" 20997 " , b{1}\n" 20998 "#endif\n" 20999 "{\n}", 21000 Style); 21001 } 21002 21003 TEST_F(FormatTest, Destructors) { 21004 verifyFormat("void F(int &i) { i.~int(); }"); 21005 verifyFormat("void F(int &i) { i->~int(); }"); 21006 } 21007 21008 TEST_F(FormatTest, FormatsWithWebKitStyle) { 21009 FormatStyle Style = getWebKitStyle(); 21010 21011 // Don't indent in outer namespaces. 21012 verifyFormat("namespace outer {\n" 21013 "int i;\n" 21014 "namespace inner {\n" 21015 " int i;\n" 21016 "} // namespace inner\n" 21017 "} // namespace outer\n" 21018 "namespace other_outer {\n" 21019 "int i;\n" 21020 "}", 21021 Style); 21022 21023 // Don't indent case labels. 21024 verifyFormat("switch (variable) {\n" 21025 "case 1:\n" 21026 "case 2:\n" 21027 " doSomething();\n" 21028 " break;\n" 21029 "default:\n" 21030 " ++variable;\n" 21031 "}", 21032 Style); 21033 21034 // Wrap before binary operators. 21035 EXPECT_EQ("void f()\n" 21036 "{\n" 21037 " if (aaaaaaaaaaaaaaaa\n" 21038 " && bbbbbbbbbbbbbbbbbbbbbbbb\n" 21039 " && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n" 21040 " return;\n" 21041 "}", 21042 format("void f() {\n" 21043 "if (aaaaaaaaaaaaaaaa\n" 21044 "&& bbbbbbbbbbbbbbbbbbbbbbbb\n" 21045 "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n" 21046 "return;\n" 21047 "}", 21048 Style)); 21049 21050 // Allow functions on a single line. 21051 verifyFormat("void f() { return; }", Style); 21052 21053 // Allow empty blocks on a single line and insert a space in empty blocks. 21054 EXPECT_EQ("void f() { }", format("void f() {}", Style)); 21055 EXPECT_EQ("while (true) { }", format("while (true) {}", Style)); 21056 // However, don't merge non-empty short loops. 21057 EXPECT_EQ("while (true) {\n" 21058 " continue;\n" 21059 "}", 21060 format("while (true) { continue; }", Style)); 21061 21062 // Constructor initializers are formatted one per line with the "," on the 21063 // new line. 21064 verifyFormat("Constructor()\n" 21065 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 21066 " , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n" 21067 " aaaaaaaaaaaaaa)\n" 21068 " , aaaaaaaaaaaaaaaaaaaaaaa()\n" 21069 "{\n" 21070 "}", 21071 Style); 21072 verifyFormat("SomeClass::Constructor()\n" 21073 " : a(a)\n" 21074 "{\n" 21075 "}", 21076 Style); 21077 EXPECT_EQ("SomeClass::Constructor()\n" 21078 " : a(a)\n" 21079 "{\n" 21080 "}", 21081 format("SomeClass::Constructor():a(a){}", Style)); 21082 verifyFormat("SomeClass::Constructor()\n" 21083 " : a(a)\n" 21084 " , b(b)\n" 21085 " , c(c)\n" 21086 "{\n" 21087 "}", 21088 Style); 21089 verifyFormat("SomeClass::Constructor()\n" 21090 " : a(a)\n" 21091 "{\n" 21092 " foo();\n" 21093 " bar();\n" 21094 "}", 21095 Style); 21096 21097 // Access specifiers should be aligned left. 21098 verifyFormat("class C {\n" 21099 "public:\n" 21100 " int i;\n" 21101 "};", 21102 Style); 21103 21104 // Do not align comments. 21105 verifyFormat("int a; // Do not\n" 21106 "double b; // align comments.", 21107 Style); 21108 21109 // Do not align operands. 21110 EXPECT_EQ("ASSERT(aaaa\n" 21111 " || bbbb);", 21112 format("ASSERT ( aaaa\n||bbbb);", Style)); 21113 21114 // Accept input's line breaks. 21115 EXPECT_EQ("if (aaaaaaaaaaaaaaa\n" 21116 " || bbbbbbbbbbbbbbb) {\n" 21117 " i++;\n" 21118 "}", 21119 format("if (aaaaaaaaaaaaaaa\n" 21120 "|| bbbbbbbbbbbbbbb) { i++; }", 21121 Style)); 21122 EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n" 21123 " i++;\n" 21124 "}", 21125 format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style)); 21126 21127 // Don't automatically break all macro definitions (llvm.org/PR17842). 21128 verifyFormat("#define aNumber 10", Style); 21129 // However, generally keep the line breaks that the user authored. 21130 EXPECT_EQ("#define aNumber \\\n" 21131 " 10", 21132 format("#define aNumber \\\n" 21133 " 10", 21134 Style)); 21135 21136 // Keep empty and one-element array literals on a single line. 21137 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n" 21138 " copyItems:YES];", 21139 format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n" 21140 "copyItems:YES];", 21141 Style)); 21142 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n" 21143 " copyItems:YES];", 21144 format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n" 21145 " copyItems:YES];", 21146 Style)); 21147 // FIXME: This does not seem right, there should be more indentation before 21148 // the array literal's entries. Nested blocks have the same problem. 21149 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n" 21150 " @\"a\",\n" 21151 " @\"a\"\n" 21152 "]\n" 21153 " copyItems:YES];", 21154 format("NSArray* a = [[NSArray alloc] initWithArray:@[\n" 21155 " @\"a\",\n" 21156 " @\"a\"\n" 21157 " ]\n" 21158 " copyItems:YES];", 21159 Style)); 21160 EXPECT_EQ( 21161 "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n" 21162 " copyItems:YES];", 21163 format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n" 21164 " copyItems:YES];", 21165 Style)); 21166 21167 verifyFormat("[self.a b:c c:d];", Style); 21168 EXPECT_EQ("[self.a b:c\n" 21169 " c:d];", 21170 format("[self.a b:c\n" 21171 "c:d];", 21172 Style)); 21173 } 21174 21175 TEST_F(FormatTest, FormatsLambdas) { 21176 verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n"); 21177 verifyFormat( 21178 "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n"); 21179 verifyFormat("int c = [&] { [=] { return b++; }(); }();\n"); 21180 verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n"); 21181 verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n"); 21182 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n"); 21183 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n"); 21184 verifyFormat("auto c = [a = [b = 42] {}] {};\n"); 21185 verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n"); 21186 verifyFormat("int x = f(*+[] {});"); 21187 verifyFormat("void f() {\n" 21188 " other(x.begin(), x.end(), [&](int, int) { return 1; });\n" 21189 "}\n"); 21190 verifyFormat("void f() {\n" 21191 " other(x.begin(), //\n" 21192 " x.end(), //\n" 21193 " [&](int, int) { return 1; });\n" 21194 "}\n"); 21195 verifyFormat("void f() {\n" 21196 " other.other.other.other.other(\n" 21197 " x.begin(), x.end(),\n" 21198 " [something, rather](int, int, int, int, int, int, int) { " 21199 "return 1; });\n" 21200 "}\n"); 21201 verifyFormat( 21202 "void f() {\n" 21203 " other.other.other.other.other(\n" 21204 " x.begin(), x.end(),\n" 21205 " [something, rather](int, int, int, int, int, int, int) {\n" 21206 " //\n" 21207 " });\n" 21208 "}\n"); 21209 verifyFormat("SomeFunction([]() { // A cool function...\n" 21210 " return 43;\n" 21211 "});"); 21212 EXPECT_EQ("SomeFunction([]() {\n" 21213 "#define A a\n" 21214 " return 43;\n" 21215 "});", 21216 format("SomeFunction([](){\n" 21217 "#define A a\n" 21218 "return 43;\n" 21219 "});")); 21220 verifyFormat("void f() {\n" 21221 " SomeFunction([](decltype(x), A *a) {});\n" 21222 " SomeFunction([](typeof(x), A *a) {});\n" 21223 " SomeFunction([](_Atomic(x), A *a) {});\n" 21224 " SomeFunction([](__underlying_type(x), A *a) {});\n" 21225 "}"); 21226 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 21227 " [](const aaaaaaaaaa &a) { return a; });"); 21228 verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n" 21229 " SomeOtherFunctioooooooooooooooooooooooooon();\n" 21230 "});"); 21231 verifyFormat("Constructor()\n" 21232 " : Field([] { // comment\n" 21233 " int i;\n" 21234 " }) {}"); 21235 verifyFormat("auto my_lambda = [](const string &some_parameter) {\n" 21236 " return some_parameter.size();\n" 21237 "};"); 21238 verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n" 21239 " [](const string &s) { return s; };"); 21240 verifyFormat("int i = aaaaaa ? 1 //\n" 21241 " : [] {\n" 21242 " return 2; //\n" 21243 " }();"); 21244 verifyFormat("llvm::errs() << \"number of twos is \"\n" 21245 " << std::count_if(v.begin(), v.end(), [](int x) {\n" 21246 " return x == 2; // force break\n" 21247 " });"); 21248 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 21249 " [=](int iiiiiiiiiiii) {\n" 21250 " return aaaaaaaaaaaaaaaaaaaaaaa !=\n" 21251 " aaaaaaaaaaaaaaaaaaaaaaa;\n" 21252 " });", 21253 getLLVMStyleWithColumns(60)); 21254 21255 verifyFormat("SomeFunction({[&] {\n" 21256 " // comment\n" 21257 " },\n" 21258 " [&] {\n" 21259 " // comment\n" 21260 " }});"); 21261 verifyFormat("SomeFunction({[&] {\n" 21262 " // comment\n" 21263 "}});"); 21264 verifyFormat( 21265 "virtual aaaaaaaaaaaaaaaa(\n" 21266 " std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n" 21267 " aaaaa aaaaaaaaa);"); 21268 21269 // Lambdas with return types. 21270 verifyFormat("int c = []() -> int { return 2; }();\n"); 21271 verifyFormat("int c = []() -> int * { return 2; }();\n"); 21272 verifyFormat("int c = []() -> vector<int> { return {2}; }();\n"); 21273 verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());"); 21274 verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};"); 21275 verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};"); 21276 verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};"); 21277 verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};"); 21278 verifyFormat("[a, a]() -> a<1> {};"); 21279 verifyFormat("[]() -> foo<5 + 2> { return {}; };"); 21280 verifyFormat("[]() -> foo<5 - 2> { return {}; };"); 21281 verifyFormat("[]() -> foo<5 / 2> { return {}; };"); 21282 verifyFormat("[]() -> foo<5 * 2> { return {}; };"); 21283 verifyFormat("[]() -> foo<5 % 2> { return {}; };"); 21284 verifyFormat("[]() -> foo<5 << 2> { return {}; };"); 21285 verifyFormat("[]() -> foo<!5> { return {}; };"); 21286 verifyFormat("[]() -> foo<~5> { return {}; };"); 21287 verifyFormat("[]() -> foo<5 | 2> { return {}; };"); 21288 verifyFormat("[]() -> foo<5 || 2> { return {}; };"); 21289 verifyFormat("[]() -> foo<5 & 2> { return {}; };"); 21290 verifyFormat("[]() -> foo<5 && 2> { return {}; };"); 21291 verifyFormat("[]() -> foo<5 == 2> { return {}; };"); 21292 verifyFormat("[]() -> foo<5 != 2> { return {}; };"); 21293 verifyFormat("[]() -> foo<5 >= 2> { return {}; };"); 21294 verifyFormat("[]() -> foo<5 <= 2> { return {}; };"); 21295 verifyFormat("[]() -> foo<5 < 2> { return {}; };"); 21296 verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };"); 21297 verifyFormat("namespace bar {\n" 21298 "// broken:\n" 21299 "auto foo{[]() -> foo<5 + 2> { return {}; }};\n" 21300 "} // namespace bar"); 21301 verifyFormat("namespace bar {\n" 21302 "// broken:\n" 21303 "auto foo{[]() -> foo<5 - 2> { return {}; }};\n" 21304 "} // namespace bar"); 21305 verifyFormat("namespace bar {\n" 21306 "// broken:\n" 21307 "auto foo{[]() -> foo<5 / 2> { return {}; }};\n" 21308 "} // namespace bar"); 21309 verifyFormat("namespace bar {\n" 21310 "// broken:\n" 21311 "auto foo{[]() -> foo<5 * 2> { return {}; }};\n" 21312 "} // namespace bar"); 21313 verifyFormat("namespace bar {\n" 21314 "// broken:\n" 21315 "auto foo{[]() -> foo<5 % 2> { return {}; }};\n" 21316 "} // namespace bar"); 21317 verifyFormat("namespace bar {\n" 21318 "// broken:\n" 21319 "auto foo{[]() -> foo<5 << 2> { return {}; }};\n" 21320 "} // namespace bar"); 21321 verifyFormat("namespace bar {\n" 21322 "// broken:\n" 21323 "auto foo{[]() -> foo<!5> { return {}; }};\n" 21324 "} // namespace bar"); 21325 verifyFormat("namespace bar {\n" 21326 "// broken:\n" 21327 "auto foo{[]() -> foo<~5> { return {}; }};\n" 21328 "} // namespace bar"); 21329 verifyFormat("namespace bar {\n" 21330 "// broken:\n" 21331 "auto foo{[]() -> foo<5 | 2> { return {}; }};\n" 21332 "} // namespace bar"); 21333 verifyFormat("namespace bar {\n" 21334 "// broken:\n" 21335 "auto foo{[]() -> foo<5 || 2> { return {}; }};\n" 21336 "} // namespace bar"); 21337 verifyFormat("namespace bar {\n" 21338 "// broken:\n" 21339 "auto foo{[]() -> foo<5 & 2> { return {}; }};\n" 21340 "} // namespace bar"); 21341 verifyFormat("namespace bar {\n" 21342 "// broken:\n" 21343 "auto foo{[]() -> foo<5 && 2> { return {}; }};\n" 21344 "} // namespace bar"); 21345 verifyFormat("namespace bar {\n" 21346 "// broken:\n" 21347 "auto foo{[]() -> foo<5 == 2> { return {}; }};\n" 21348 "} // namespace bar"); 21349 verifyFormat("namespace bar {\n" 21350 "// broken:\n" 21351 "auto foo{[]() -> foo<5 != 2> { return {}; }};\n" 21352 "} // namespace bar"); 21353 verifyFormat("namespace bar {\n" 21354 "// broken:\n" 21355 "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n" 21356 "} // namespace bar"); 21357 verifyFormat("namespace bar {\n" 21358 "// broken:\n" 21359 "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n" 21360 "} // namespace bar"); 21361 verifyFormat("namespace bar {\n" 21362 "// broken:\n" 21363 "auto foo{[]() -> foo<5 < 2> { return {}; }};\n" 21364 "} // namespace bar"); 21365 verifyFormat("namespace bar {\n" 21366 "// broken:\n" 21367 "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n" 21368 "} // namespace bar"); 21369 verifyFormat("[]() -> a<1> {};"); 21370 verifyFormat("[]() -> a<1> { ; };"); 21371 verifyFormat("[]() -> a<1> { ; }();"); 21372 verifyFormat("[a, a]() -> a<true> {};"); 21373 verifyFormat("[]() -> a<true> {};"); 21374 verifyFormat("[]() -> a<true> { ; };"); 21375 verifyFormat("[]() -> a<true> { ; }();"); 21376 verifyFormat("[a, a]() -> a<false> {};"); 21377 verifyFormat("[]() -> a<false> {};"); 21378 verifyFormat("[]() -> a<false> { ; };"); 21379 verifyFormat("[]() -> a<false> { ; }();"); 21380 verifyFormat("auto foo{[]() -> foo<false> { ; }};"); 21381 verifyFormat("namespace bar {\n" 21382 "auto foo{[]() -> foo<false> { ; }};\n" 21383 "} // namespace bar"); 21384 verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n" 21385 " int j) -> int {\n" 21386 " return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n" 21387 "};"); 21388 verifyFormat( 21389 "aaaaaaaaaaaaaaaaaaaaaa(\n" 21390 " [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n" 21391 " return aaaaaaaaaaaaaaaaa;\n" 21392 " });", 21393 getLLVMStyleWithColumns(70)); 21394 verifyFormat("[]() //\n" 21395 " -> int {\n" 21396 " return 1; //\n" 21397 "};"); 21398 verifyFormat("[]() -> Void<T...> {};"); 21399 verifyFormat("[a, b]() -> Tuple<T...> { return {}; };"); 21400 verifyFormat("SomeFunction({[]() -> int[] { return {}; }});"); 21401 verifyFormat("SomeFunction({[]() -> int *[] { return {}; }});"); 21402 verifyFormat("SomeFunction({[]() -> int (*)[] { return {}; }});"); 21403 verifyFormat("SomeFunction({[]() -> ns::type<int (*)[]> { return {}; }});"); 21404 verifyFormat("return int{[x = x]() { return x; }()};"); 21405 21406 // Lambdas with explicit template argument lists. 21407 verifyFormat( 21408 "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n"); 21409 verifyFormat("auto L = []<class T>(T) {\n" 21410 " {\n" 21411 " f();\n" 21412 " g();\n" 21413 " }\n" 21414 "};\n"); 21415 verifyFormat("auto L = []<class... T>(T...) {\n" 21416 " {\n" 21417 " f();\n" 21418 " g();\n" 21419 " }\n" 21420 "};\n"); 21421 verifyFormat("auto L = []<typename... T>(T...) {\n" 21422 " {\n" 21423 " f();\n" 21424 " g();\n" 21425 " }\n" 21426 "};\n"); 21427 verifyFormat("auto L = []<template <typename...> class T>(T...) {\n" 21428 " {\n" 21429 " f();\n" 21430 " g();\n" 21431 " }\n" 21432 "};\n"); 21433 verifyFormat("auto L = []</*comment*/ class... T>(T...) {\n" 21434 " {\n" 21435 " f();\n" 21436 " g();\n" 21437 " }\n" 21438 "};\n"); 21439 21440 // Multiple lambdas in the same parentheses change indentation rules. These 21441 // lambdas are forced to start on new lines. 21442 verifyFormat("SomeFunction(\n" 21443 " []() {\n" 21444 " //\n" 21445 " },\n" 21446 " []() {\n" 21447 " //\n" 21448 " });"); 21449 21450 // A lambda passed as arg0 is always pushed to the next line. 21451 verifyFormat("SomeFunction(\n" 21452 " [this] {\n" 21453 " //\n" 21454 " },\n" 21455 " 1);\n"); 21456 21457 // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like 21458 // the arg0 case above. 21459 auto Style = getGoogleStyle(); 21460 Style.BinPackArguments = false; 21461 verifyFormat("SomeFunction(\n" 21462 " a,\n" 21463 " [this] {\n" 21464 " //\n" 21465 " },\n" 21466 " b);\n", 21467 Style); 21468 verifyFormat("SomeFunction(\n" 21469 " a,\n" 21470 " [this] {\n" 21471 " //\n" 21472 " },\n" 21473 " b);\n"); 21474 21475 // A lambda with a very long line forces arg0 to be pushed out irrespective of 21476 // the BinPackArguments value (as long as the code is wide enough). 21477 verifyFormat( 21478 "something->SomeFunction(\n" 21479 " a,\n" 21480 " [this] {\n" 21481 " " 21482 "D0000000000000000000000000000000000000000000000000000000000001();\n" 21483 " },\n" 21484 " b);\n"); 21485 21486 // A multi-line lambda is pulled up as long as the introducer fits on the 21487 // previous line and there are no further args. 21488 verifyFormat("function(1, [this, that] {\n" 21489 " //\n" 21490 "});\n"); 21491 verifyFormat("function([this, that] {\n" 21492 " //\n" 21493 "});\n"); 21494 // FIXME: this format is not ideal and we should consider forcing the first 21495 // arg onto its own line. 21496 verifyFormat("function(a, b, c, //\n" 21497 " d, [this, that] {\n" 21498 " //\n" 21499 " });\n"); 21500 21501 // Multiple lambdas are treated correctly even when there is a short arg0. 21502 verifyFormat("SomeFunction(\n" 21503 " 1,\n" 21504 " [this] {\n" 21505 " //\n" 21506 " },\n" 21507 " [this] {\n" 21508 " //\n" 21509 " },\n" 21510 " 1);\n"); 21511 21512 // More complex introducers. 21513 verifyFormat("return [i, args...] {};"); 21514 21515 // Not lambdas. 21516 verifyFormat("constexpr char hello[]{\"hello\"};"); 21517 verifyFormat("double &operator[](int i) { return 0; }\n" 21518 "int i;"); 21519 verifyFormat("std::unique_ptr<int[]> foo() {}"); 21520 verifyFormat("int i = a[a][a]->f();"); 21521 verifyFormat("int i = (*b)[a]->f();"); 21522 21523 // Other corner cases. 21524 verifyFormat("void f() {\n" 21525 " bar([]() {} // Did not respect SpacesBeforeTrailingComments\n" 21526 " );\n" 21527 "}"); 21528 verifyFormat("auto k = *[](int *j) { return j; }(&i);"); 21529 21530 // Lambdas created through weird macros. 21531 verifyFormat("void f() {\n" 21532 " MACRO((const AA &a) { return 1; });\n" 21533 " MACRO((AA &a) { return 1; });\n" 21534 "}"); 21535 21536 verifyFormat("if (blah_blah(whatever, whatever, [] {\n" 21537 " doo_dah();\n" 21538 " doo_dah();\n" 21539 " })) {\n" 21540 "}"); 21541 verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n" 21542 " doo_dah();\n" 21543 " doo_dah();\n" 21544 " })) {\n" 21545 "}"); 21546 verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n" 21547 " doo_dah();\n" 21548 " doo_dah();\n" 21549 " })) {\n" 21550 "}"); 21551 verifyFormat("auto lambda = []() {\n" 21552 " int a = 2\n" 21553 "#if A\n" 21554 " + 2\n" 21555 "#endif\n" 21556 " ;\n" 21557 "};"); 21558 21559 // Lambdas with complex multiline introducers. 21560 verifyFormat( 21561 "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 21562 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n" 21563 " -> ::std::unordered_set<\n" 21564 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n" 21565 " //\n" 21566 " });"); 21567 21568 FormatStyle DoNotMerge = getLLVMStyle(); 21569 DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 21570 verifyFormat("auto c = []() {\n" 21571 " return b;\n" 21572 "};", 21573 "auto c = []() { return b; };", DoNotMerge); 21574 verifyFormat("auto c = []() {\n" 21575 "};", 21576 " auto c = []() {};", DoNotMerge); 21577 21578 FormatStyle MergeEmptyOnly = getLLVMStyle(); 21579 MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty; 21580 verifyFormat("auto c = []() {\n" 21581 " return b;\n" 21582 "};", 21583 "auto c = []() {\n" 21584 " return b;\n" 21585 " };", 21586 MergeEmptyOnly); 21587 verifyFormat("auto c = []() {};", 21588 "auto c = []() {\n" 21589 "};", 21590 MergeEmptyOnly); 21591 21592 FormatStyle MergeInline = getLLVMStyle(); 21593 MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline; 21594 verifyFormat("auto c = []() {\n" 21595 " return b;\n" 21596 "};", 21597 "auto c = []() { return b; };", MergeInline); 21598 verifyFormat("function([]() { return b; })", "function([]() { return b; })", 21599 MergeInline); 21600 verifyFormat("function([]() { return b; }, a)", 21601 "function([]() { return b; }, a)", MergeInline); 21602 verifyFormat("function(a, []() { return b; })", 21603 "function(a, []() { return b; })", MergeInline); 21604 21605 // Check option "BraceWrapping.BeforeLambdaBody" and different state of 21606 // AllowShortLambdasOnASingleLine 21607 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle(); 21608 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 21609 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 21610 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21611 FormatStyle::ShortLambdaStyle::SLS_None; 21612 verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n" 21613 " []()\n" 21614 " {\n" 21615 " return 17;\n" 21616 " });", 21617 LLVMWithBeforeLambdaBody); 21618 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n" 21619 " []()\n" 21620 " {\n" 21621 " });", 21622 LLVMWithBeforeLambdaBody); 21623 verifyFormat("auto fct_SLS_None = []()\n" 21624 "{\n" 21625 " return 17;\n" 21626 "};", 21627 LLVMWithBeforeLambdaBody); 21628 verifyFormat("TwoNestedLambdas_SLS_None(\n" 21629 " []()\n" 21630 " {\n" 21631 " return Call(\n" 21632 " []()\n" 21633 " {\n" 21634 " return 17;\n" 21635 " });\n" 21636 " });", 21637 LLVMWithBeforeLambdaBody); 21638 verifyFormat("void Fct() {\n" 21639 " return {[]()\n" 21640 " {\n" 21641 " return 17;\n" 21642 " }};\n" 21643 "}", 21644 LLVMWithBeforeLambdaBody); 21645 21646 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21647 FormatStyle::ShortLambdaStyle::SLS_Empty; 21648 verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n" 21649 " []()\n" 21650 " {\n" 21651 " return 17;\n" 21652 " });", 21653 LLVMWithBeforeLambdaBody); 21654 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});", 21655 LLVMWithBeforeLambdaBody); 21656 verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL" 21657 "ongFunctionName_SLS_Empty(\n" 21658 " []() {});", 21659 LLVMWithBeforeLambdaBody); 21660 verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n" 21661 " []()\n" 21662 " {\n" 21663 " return 17;\n" 21664 " });", 21665 LLVMWithBeforeLambdaBody); 21666 verifyFormat("auto fct_SLS_Empty = []()\n" 21667 "{\n" 21668 " return 17;\n" 21669 "};", 21670 LLVMWithBeforeLambdaBody); 21671 verifyFormat("TwoNestedLambdas_SLS_Empty(\n" 21672 " []()\n" 21673 " {\n" 21674 " return Call([]() {});\n" 21675 " });", 21676 LLVMWithBeforeLambdaBody); 21677 verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n" 21678 " []()\n" 21679 " {\n" 21680 " return Call([]() {});\n" 21681 " });", 21682 LLVMWithBeforeLambdaBody); 21683 verifyFormat( 21684 "FctWithLongLineInLambda_SLS_Empty(\n" 21685 " []()\n" 21686 " {\n" 21687 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21688 " AndShouldNotBeConsiderAsInline,\n" 21689 " LambdaBodyMustBeBreak);\n" 21690 " });", 21691 LLVMWithBeforeLambdaBody); 21692 21693 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21694 FormatStyle::ShortLambdaStyle::SLS_Inline; 21695 verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });", 21696 LLVMWithBeforeLambdaBody); 21697 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});", 21698 LLVMWithBeforeLambdaBody); 21699 verifyFormat("auto fct_SLS_Inline = []()\n" 21700 "{\n" 21701 " return 17;\n" 21702 "};", 21703 LLVMWithBeforeLambdaBody); 21704 verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return " 21705 "17; }); });", 21706 LLVMWithBeforeLambdaBody); 21707 verifyFormat( 21708 "FctWithLongLineInLambda_SLS_Inline(\n" 21709 " []()\n" 21710 " {\n" 21711 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21712 " AndShouldNotBeConsiderAsInline,\n" 21713 " LambdaBodyMustBeBreak);\n" 21714 " });", 21715 LLVMWithBeforeLambdaBody); 21716 verifyFormat("FctWithMultipleParams_SLS_Inline(" 21717 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n" 21718 " []() { return 17; });", 21719 LLVMWithBeforeLambdaBody); 21720 verifyFormat( 21721 "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });", 21722 LLVMWithBeforeLambdaBody); 21723 21724 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21725 FormatStyle::ShortLambdaStyle::SLS_All; 21726 verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });", 21727 LLVMWithBeforeLambdaBody); 21728 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});", 21729 LLVMWithBeforeLambdaBody); 21730 verifyFormat("auto fct_SLS_All = []() { return 17; };", 21731 LLVMWithBeforeLambdaBody); 21732 verifyFormat("FctWithOneParam_SLS_All(\n" 21733 " []()\n" 21734 " {\n" 21735 " // A cool function...\n" 21736 " return 43;\n" 21737 " });", 21738 LLVMWithBeforeLambdaBody); 21739 verifyFormat("FctWithMultipleParams_SLS_All(" 21740 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n" 21741 " []() { return 17; });", 21742 LLVMWithBeforeLambdaBody); 21743 verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });", 21744 LLVMWithBeforeLambdaBody); 21745 verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });", 21746 LLVMWithBeforeLambdaBody); 21747 verifyFormat( 21748 "FctWithLongLineInLambda_SLS_All(\n" 21749 " []()\n" 21750 " {\n" 21751 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21752 " AndShouldNotBeConsiderAsInline,\n" 21753 " LambdaBodyMustBeBreak);\n" 21754 " });", 21755 LLVMWithBeforeLambdaBody); 21756 verifyFormat( 21757 "auto fct_SLS_All = []()\n" 21758 "{\n" 21759 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21760 " AndShouldNotBeConsiderAsInline,\n" 21761 " LambdaBodyMustBeBreak);\n" 21762 "};", 21763 LLVMWithBeforeLambdaBody); 21764 LLVMWithBeforeLambdaBody.BinPackParameters = false; 21765 verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);", 21766 LLVMWithBeforeLambdaBody); 21767 verifyFormat( 21768 "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n" 21769 " FirstParam,\n" 21770 " SecondParam,\n" 21771 " ThirdParam,\n" 21772 " FourthParam);", 21773 LLVMWithBeforeLambdaBody); 21774 verifyFormat("FctWithLongLineInLambda_SLS_All(\n" 21775 " []() { return " 21776 "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n" 21777 " FirstParam,\n" 21778 " SecondParam,\n" 21779 " ThirdParam,\n" 21780 " FourthParam);", 21781 LLVMWithBeforeLambdaBody); 21782 verifyFormat( 21783 "FctWithLongLineInLambda_SLS_All(FirstParam,\n" 21784 " SecondParam,\n" 21785 " ThirdParam,\n" 21786 " FourthParam,\n" 21787 " []() { return SomeValueNotSoLong; });", 21788 LLVMWithBeforeLambdaBody); 21789 verifyFormat("FctWithLongLineInLambda_SLS_All(\n" 21790 " []()\n" 21791 " {\n" 21792 " return " 21793 "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB" 21794 "eConsiderAsInline;\n" 21795 " });", 21796 LLVMWithBeforeLambdaBody); 21797 verifyFormat( 21798 "FctWithLongLineInLambda_SLS_All(\n" 21799 " []()\n" 21800 " {\n" 21801 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21802 " AndShouldNotBeConsiderAsInline,\n" 21803 " LambdaBodyMustBeBreak);\n" 21804 " });", 21805 LLVMWithBeforeLambdaBody); 21806 verifyFormat("FctWithTwoParams_SLS_All(\n" 21807 " []()\n" 21808 " {\n" 21809 " // A cool function...\n" 21810 " return 43;\n" 21811 " },\n" 21812 " 87);", 21813 LLVMWithBeforeLambdaBody); 21814 verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);", 21815 LLVMWithBeforeLambdaBody); 21816 verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });", 21817 LLVMWithBeforeLambdaBody); 21818 verifyFormat( 21819 "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });", 21820 LLVMWithBeforeLambdaBody); 21821 verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; " 21822 "}); }, x);", 21823 LLVMWithBeforeLambdaBody); 21824 verifyFormat("TwoNestedLambdas_SLS_All(\n" 21825 " []()\n" 21826 " {\n" 21827 " // A cool function...\n" 21828 " return Call([]() { return 17; });\n" 21829 " });", 21830 LLVMWithBeforeLambdaBody); 21831 verifyFormat("TwoNestedLambdas_SLS_All(\n" 21832 " []()\n" 21833 " {\n" 21834 " return Call(\n" 21835 " []()\n" 21836 " {\n" 21837 " // A cool function...\n" 21838 " return 17;\n" 21839 " });\n" 21840 " });", 21841 LLVMWithBeforeLambdaBody); 21842 21843 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21844 FormatStyle::ShortLambdaStyle::SLS_None; 21845 21846 verifyFormat("auto select = [this]() -> const Library::Object *\n" 21847 "{\n" 21848 " return MyAssignment::SelectFromList(this);\n" 21849 "};\n", 21850 LLVMWithBeforeLambdaBody); 21851 21852 verifyFormat("auto select = [this]() -> const Library::Object &\n" 21853 "{\n" 21854 " return MyAssignment::SelectFromList(this);\n" 21855 "};\n", 21856 LLVMWithBeforeLambdaBody); 21857 21858 verifyFormat("auto select = [this]() -> std::unique_ptr<Object>\n" 21859 "{\n" 21860 " return MyAssignment::SelectFromList(this);\n" 21861 "};\n", 21862 LLVMWithBeforeLambdaBody); 21863 21864 verifyFormat("namespace test {\n" 21865 "class Test {\n" 21866 "public:\n" 21867 " Test() = default;\n" 21868 "};\n" 21869 "} // namespace test", 21870 LLVMWithBeforeLambdaBody); 21871 21872 // Lambdas with different indentation styles. 21873 Style = getLLVMStyleWithColumns(100); 21874 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 21875 " return promise.then(\n" 21876 " [this, &someVariable, someObject = " 21877 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21878 " return someObject.startAsyncAction().then(\n" 21879 " [this, &someVariable](AsyncActionResult result) " 21880 "mutable { result.processMore(); });\n" 21881 " });\n" 21882 "}\n", 21883 format("SomeResult doSomething(SomeObject promise) {\n" 21884 " return promise.then([this, &someVariable, someObject = " 21885 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21886 " return someObject.startAsyncAction().then([this, " 21887 "&someVariable](AsyncActionResult result) mutable {\n" 21888 " result.processMore();\n" 21889 " });\n" 21890 " });\n" 21891 "}\n", 21892 Style)); 21893 Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope; 21894 verifyFormat("test() {\n" 21895 " ([]() -> {\n" 21896 " int b = 32;\n" 21897 " return 3;\n" 21898 " }).foo();\n" 21899 "}", 21900 Style); 21901 verifyFormat("test() {\n" 21902 " []() -> {\n" 21903 " int b = 32;\n" 21904 " return 3;\n" 21905 " }\n" 21906 "}", 21907 Style); 21908 verifyFormat("std::sort(v.begin(), v.end(),\n" 21909 " [](const auto &someLongArgumentName, const auto " 21910 "&someOtherLongArgumentName) {\n" 21911 " return someLongArgumentName.someMemberVariable < " 21912 "someOtherLongArgumentName.someMemberVariable;\n" 21913 "});", 21914 Style); 21915 verifyFormat("test() {\n" 21916 " (\n" 21917 " []() -> {\n" 21918 " int b = 32;\n" 21919 " return 3;\n" 21920 " },\n" 21921 " foo, bar)\n" 21922 " .foo();\n" 21923 "}", 21924 Style); 21925 verifyFormat("test() {\n" 21926 " ([]() -> {\n" 21927 " int b = 32;\n" 21928 " return 3;\n" 21929 " })\n" 21930 " .foo()\n" 21931 " .bar();\n" 21932 "}", 21933 Style); 21934 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 21935 " return promise.then(\n" 21936 " [this, &someVariable, someObject = " 21937 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21938 " return someObject.startAsyncAction().then(\n" 21939 " [this, &someVariable](AsyncActionResult result) mutable { " 21940 "result.processMore(); });\n" 21941 " });\n" 21942 "}\n", 21943 format("SomeResult doSomething(SomeObject promise) {\n" 21944 " return promise.then([this, &someVariable, someObject = " 21945 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21946 " return someObject.startAsyncAction().then([this, " 21947 "&someVariable](AsyncActionResult result) mutable {\n" 21948 " result.processMore();\n" 21949 " });\n" 21950 " });\n" 21951 "}\n", 21952 Style)); 21953 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 21954 " return promise.then([this, &someVariable] {\n" 21955 " return someObject.startAsyncAction().then(\n" 21956 " [this, &someVariable](AsyncActionResult result) mutable { " 21957 "result.processMore(); });\n" 21958 " });\n" 21959 "}\n", 21960 format("SomeResult doSomething(SomeObject promise) {\n" 21961 " return promise.then([this, &someVariable] {\n" 21962 " return someObject.startAsyncAction().then([this, " 21963 "&someVariable](AsyncActionResult result) mutable {\n" 21964 " result.processMore();\n" 21965 " });\n" 21966 " });\n" 21967 "}\n", 21968 Style)); 21969 Style = getGoogleStyle(); 21970 Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope; 21971 EXPECT_EQ("#define A \\\n" 21972 " [] { \\\n" 21973 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 21974 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n" 21975 " }", 21976 format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 21977 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }", 21978 Style)); 21979 // TODO: The current formatting has a minor issue that's not worth fixing 21980 // right now whereby the closing brace is indented relative to the signature 21981 // instead of being aligned. This only happens with macros. 21982 } 21983 21984 TEST_F(FormatTest, LambdaWithLineComments) { 21985 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle(); 21986 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 21987 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 21988 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21989 FormatStyle::ShortLambdaStyle::SLS_All; 21990 21991 verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody); 21992 verifyFormat("auto k = []() // comment\n" 21993 "{ return; }", 21994 LLVMWithBeforeLambdaBody); 21995 verifyFormat("auto k = []() /* comment */ { return; }", 21996 LLVMWithBeforeLambdaBody); 21997 verifyFormat("auto k = []() /* comment */ /* comment */ { return; }", 21998 LLVMWithBeforeLambdaBody); 21999 verifyFormat("auto k = []() // X\n" 22000 "{ return; }", 22001 LLVMWithBeforeLambdaBody); 22002 verifyFormat( 22003 "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" 22004 "{ return; }", 22005 LLVMWithBeforeLambdaBody); 22006 22007 LLVMWithBeforeLambdaBody.ColumnLimit = 0; 22008 22009 verifyFormat("foo([]()\n" 22010 " {\n" 22011 " bar(); //\n" 22012 " return 1; // comment\n" 22013 " }());", 22014 "foo([]() {\n" 22015 " bar(); //\n" 22016 " return 1; // comment\n" 22017 "}());", 22018 LLVMWithBeforeLambdaBody); 22019 verifyFormat("foo(\n" 22020 " 1, MACRO {\n" 22021 " baz();\n" 22022 " bar(); // comment\n" 22023 " },\n" 22024 " []() {});", 22025 "foo(\n" 22026 " 1, MACRO { baz(); bar(); // comment\n" 22027 " }, []() {}\n" 22028 ");", 22029 LLVMWithBeforeLambdaBody); 22030 } 22031 22032 TEST_F(FormatTest, EmptyLinesInLambdas) { 22033 verifyFormat("auto lambda = []() {\n" 22034 " x(); //\n" 22035 "};", 22036 "auto lambda = []() {\n" 22037 "\n" 22038 " x(); //\n" 22039 "\n" 22040 "};"); 22041 } 22042 22043 TEST_F(FormatTest, FormatsBlocks) { 22044 FormatStyle ShortBlocks = getLLVMStyle(); 22045 ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 22046 verifyFormat("int (^Block)(int, int);", ShortBlocks); 22047 verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks); 22048 verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks); 22049 verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks); 22050 verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks); 22051 verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks); 22052 22053 verifyFormat("foo(^{ bar(); });", ShortBlocks); 22054 verifyFormat("foo(a, ^{ bar(); });", ShortBlocks); 22055 verifyFormat("{ void (^block)(Object *x); }", ShortBlocks); 22056 22057 verifyFormat("[operation setCompletionBlock:^{\n" 22058 " [self onOperationDone];\n" 22059 "}];"); 22060 verifyFormat("int i = {[operation setCompletionBlock:^{\n" 22061 " [self onOperationDone];\n" 22062 "}]};"); 22063 verifyFormat("[operation setCompletionBlock:^(int *i) {\n" 22064 " f();\n" 22065 "}];"); 22066 verifyFormat("int a = [operation block:^int(int *i) {\n" 22067 " return 1;\n" 22068 "}];"); 22069 verifyFormat("[myObject doSomethingWith:arg1\n" 22070 " aaa:^int(int *a) {\n" 22071 " return 1;\n" 22072 " }\n" 22073 " bbb:f(a * bbbbbbbb)];"); 22074 22075 verifyFormat("[operation setCompletionBlock:^{\n" 22076 " [self.delegate newDataAvailable];\n" 22077 "}];", 22078 getLLVMStyleWithColumns(60)); 22079 verifyFormat("dispatch_async(_fileIOQueue, ^{\n" 22080 " NSString *path = [self sessionFilePath];\n" 22081 " if (path) {\n" 22082 " // ...\n" 22083 " }\n" 22084 "});"); 22085 verifyFormat("[[SessionService sharedService]\n" 22086 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 22087 " if (window) {\n" 22088 " [self windowDidLoad:window];\n" 22089 " } else {\n" 22090 " [self errorLoadingWindow];\n" 22091 " }\n" 22092 " }];"); 22093 verifyFormat("void (^largeBlock)(void) = ^{\n" 22094 " // ...\n" 22095 "};\n", 22096 getLLVMStyleWithColumns(40)); 22097 verifyFormat("[[SessionService sharedService]\n" 22098 " loadWindowWithCompletionBlock: //\n" 22099 " ^(SessionWindow *window) {\n" 22100 " if (window) {\n" 22101 " [self windowDidLoad:window];\n" 22102 " } else {\n" 22103 " [self errorLoadingWindow];\n" 22104 " }\n" 22105 " }];", 22106 getLLVMStyleWithColumns(60)); 22107 verifyFormat("[myObject doSomethingWith:arg1\n" 22108 " firstBlock:^(Foo *a) {\n" 22109 " // ...\n" 22110 " int i;\n" 22111 " }\n" 22112 " secondBlock:^(Bar *b) {\n" 22113 " // ...\n" 22114 " int i;\n" 22115 " }\n" 22116 " thirdBlock:^Foo(Bar *b) {\n" 22117 " // ...\n" 22118 " int i;\n" 22119 " }];"); 22120 verifyFormat("[myObject doSomethingWith:arg1\n" 22121 " firstBlock:-1\n" 22122 " secondBlock:^(Bar *b) {\n" 22123 " // ...\n" 22124 " int i;\n" 22125 " }];"); 22126 22127 verifyFormat("f(^{\n" 22128 " @autoreleasepool {\n" 22129 " if (a) {\n" 22130 " g();\n" 22131 " }\n" 22132 " }\n" 22133 "});"); 22134 verifyFormat("Block b = ^int *(A *a, B *b) {}"); 22135 verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n" 22136 "};"); 22137 22138 FormatStyle FourIndent = getLLVMStyle(); 22139 FourIndent.ObjCBlockIndentWidth = 4; 22140 verifyFormat("[operation setCompletionBlock:^{\n" 22141 " [self onOperationDone];\n" 22142 "}];", 22143 FourIndent); 22144 } 22145 22146 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) { 22147 FormatStyle ZeroColumn = getLLVMStyleWithColumns(0); 22148 22149 verifyFormat("[[SessionService sharedService] " 22150 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 22151 " if (window) {\n" 22152 " [self windowDidLoad:window];\n" 22153 " } else {\n" 22154 " [self errorLoadingWindow];\n" 22155 " }\n" 22156 "}];", 22157 ZeroColumn); 22158 EXPECT_EQ("[[SessionService sharedService]\n" 22159 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 22160 " if (window) {\n" 22161 " [self windowDidLoad:window];\n" 22162 " } else {\n" 22163 " [self errorLoadingWindow];\n" 22164 " }\n" 22165 " }];", 22166 format("[[SessionService sharedService]\n" 22167 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 22168 " if (window) {\n" 22169 " [self windowDidLoad:window];\n" 22170 " } else {\n" 22171 " [self errorLoadingWindow];\n" 22172 " }\n" 22173 "}];", 22174 ZeroColumn)); 22175 verifyFormat("[myObject doSomethingWith:arg1\n" 22176 " firstBlock:^(Foo *a) {\n" 22177 " // ...\n" 22178 " int i;\n" 22179 " }\n" 22180 " secondBlock:^(Bar *b) {\n" 22181 " // ...\n" 22182 " int i;\n" 22183 " }\n" 22184 " thirdBlock:^Foo(Bar *b) {\n" 22185 " // ...\n" 22186 " int i;\n" 22187 " }];", 22188 ZeroColumn); 22189 verifyFormat("f(^{\n" 22190 " @autoreleasepool {\n" 22191 " if (a) {\n" 22192 " g();\n" 22193 " }\n" 22194 " }\n" 22195 "});", 22196 ZeroColumn); 22197 verifyFormat("void (^largeBlock)(void) = ^{\n" 22198 " // ...\n" 22199 "};", 22200 ZeroColumn); 22201 22202 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 22203 EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };", 22204 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn)); 22205 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 22206 EXPECT_EQ("void (^largeBlock)(void) = ^{\n" 22207 " int i;\n" 22208 "};", 22209 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn)); 22210 } 22211 22212 TEST_F(FormatTest, SupportsCRLF) { 22213 EXPECT_EQ("int a;\r\n" 22214 "int b;\r\n" 22215 "int c;\r\n", 22216 format("int a;\r\n" 22217 " int b;\r\n" 22218 " int c;\r\n", 22219 getLLVMStyle())); 22220 EXPECT_EQ("int a;\r\n" 22221 "int b;\r\n" 22222 "int c;\r\n", 22223 format("int a;\r\n" 22224 " int b;\n" 22225 " int c;\r\n", 22226 getLLVMStyle())); 22227 EXPECT_EQ("int a;\n" 22228 "int b;\n" 22229 "int c;\n", 22230 format("int a;\r\n" 22231 " int b;\n" 22232 " int c;\n", 22233 getLLVMStyle())); 22234 EXPECT_EQ("\"aaaaaaa \"\r\n" 22235 "\"bbbbbbb\";\r\n", 22236 format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10))); 22237 EXPECT_EQ("#define A \\\r\n" 22238 " b; \\\r\n" 22239 " c; \\\r\n" 22240 " d;\r\n", 22241 format("#define A \\\r\n" 22242 " b; \\\r\n" 22243 " c; d; \r\n", 22244 getGoogleStyle())); 22245 22246 EXPECT_EQ("/*\r\n" 22247 "multi line block comments\r\n" 22248 "should not introduce\r\n" 22249 "an extra carriage return\r\n" 22250 "*/\r\n", 22251 format("/*\r\n" 22252 "multi line block comments\r\n" 22253 "should not introduce\r\n" 22254 "an extra carriage return\r\n" 22255 "*/\r\n")); 22256 EXPECT_EQ("/*\r\n" 22257 "\r\n" 22258 "*/", 22259 format("/*\r\n" 22260 " \r\r\r\n" 22261 "*/")); 22262 22263 FormatStyle style = getLLVMStyle(); 22264 22265 style.DeriveLineEnding = true; 22266 style.UseCRLF = false; 22267 EXPECT_EQ("union FooBarBazQux {\n" 22268 " int foo;\n" 22269 " int bar;\n" 22270 " int baz;\n" 22271 "};", 22272 format("union FooBarBazQux {\r\n" 22273 " int foo;\n" 22274 " int bar;\r\n" 22275 " int baz;\n" 22276 "};", 22277 style)); 22278 style.UseCRLF = true; 22279 EXPECT_EQ("union FooBarBazQux {\r\n" 22280 " int foo;\r\n" 22281 " int bar;\r\n" 22282 " int baz;\r\n" 22283 "};", 22284 format("union FooBarBazQux {\r\n" 22285 " int foo;\n" 22286 " int bar;\r\n" 22287 " int baz;\n" 22288 "};", 22289 style)); 22290 22291 style.DeriveLineEnding = false; 22292 style.UseCRLF = false; 22293 EXPECT_EQ("union FooBarBazQux {\n" 22294 " int foo;\n" 22295 " int bar;\n" 22296 " int baz;\n" 22297 " int qux;\n" 22298 "};", 22299 format("union FooBarBazQux {\r\n" 22300 " int foo;\n" 22301 " int bar;\r\n" 22302 " int baz;\n" 22303 " int qux;\r\n" 22304 "};", 22305 style)); 22306 style.UseCRLF = true; 22307 EXPECT_EQ("union FooBarBazQux {\r\n" 22308 " int foo;\r\n" 22309 " int bar;\r\n" 22310 " int baz;\r\n" 22311 " int qux;\r\n" 22312 "};", 22313 format("union FooBarBazQux {\r\n" 22314 " int foo;\n" 22315 " int bar;\r\n" 22316 " int baz;\n" 22317 " int qux;\n" 22318 "};", 22319 style)); 22320 22321 style.DeriveLineEnding = true; 22322 style.UseCRLF = false; 22323 EXPECT_EQ("union FooBarBazQux {\r\n" 22324 " int foo;\r\n" 22325 " int bar;\r\n" 22326 " int baz;\r\n" 22327 " int qux;\r\n" 22328 "};", 22329 format("union FooBarBazQux {\r\n" 22330 " int foo;\n" 22331 " int bar;\r\n" 22332 " int baz;\n" 22333 " int qux;\r\n" 22334 "};", 22335 style)); 22336 style.UseCRLF = true; 22337 EXPECT_EQ("union FooBarBazQux {\n" 22338 " int foo;\n" 22339 " int bar;\n" 22340 " int baz;\n" 22341 " int qux;\n" 22342 "};", 22343 format("union FooBarBazQux {\r\n" 22344 " int foo;\n" 22345 " int bar;\r\n" 22346 " int baz;\n" 22347 " int qux;\n" 22348 "};", 22349 style)); 22350 } 22351 22352 TEST_F(FormatTest, MunchSemicolonAfterBlocks) { 22353 verifyFormat("MY_CLASS(C) {\n" 22354 " int i;\n" 22355 " int j;\n" 22356 "};"); 22357 } 22358 22359 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) { 22360 FormatStyle TwoIndent = getLLVMStyleWithColumns(15); 22361 TwoIndent.ContinuationIndentWidth = 2; 22362 22363 EXPECT_EQ("int i =\n" 22364 " longFunction(\n" 22365 " arg);", 22366 format("int i = longFunction(arg);", TwoIndent)); 22367 22368 FormatStyle SixIndent = getLLVMStyleWithColumns(20); 22369 SixIndent.ContinuationIndentWidth = 6; 22370 22371 EXPECT_EQ("int i =\n" 22372 " longFunction(\n" 22373 " arg);", 22374 format("int i = longFunction(arg);", SixIndent)); 22375 } 22376 22377 TEST_F(FormatTest, WrappedClosingParenthesisIndent) { 22378 FormatStyle Style = getLLVMStyle(); 22379 verifyFormat("int Foo::getter(\n" 22380 " //\n" 22381 ") const {\n" 22382 " return foo;\n" 22383 "}", 22384 Style); 22385 verifyFormat("void Foo::setter(\n" 22386 " //\n" 22387 ") {\n" 22388 " foo = 1;\n" 22389 "}", 22390 Style); 22391 } 22392 22393 TEST_F(FormatTest, SpacesInAngles) { 22394 FormatStyle Spaces = getLLVMStyle(); 22395 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22396 22397 verifyFormat("vector< ::std::string > x1;", Spaces); 22398 verifyFormat("Foo< int, Bar > x2;", Spaces); 22399 verifyFormat("Foo< ::int, ::Bar > x3;", Spaces); 22400 22401 verifyFormat("static_cast< int >(arg);", Spaces); 22402 verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces); 22403 verifyFormat("f< int, float >();", Spaces); 22404 verifyFormat("template <> g() {}", Spaces); 22405 verifyFormat("template < std::vector< int > > f() {}", Spaces); 22406 verifyFormat("std::function< void(int, int) > fct;", Spaces); 22407 verifyFormat("void inFunction() { std::function< void(int, int) > fct; }", 22408 Spaces); 22409 22410 Spaces.Standard = FormatStyle::LS_Cpp03; 22411 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22412 verifyFormat("A< A< int > >();", Spaces); 22413 22414 Spaces.SpacesInAngles = FormatStyle::SIAS_Never; 22415 verifyFormat("A<A<int> >();", Spaces); 22416 22417 Spaces.SpacesInAngles = FormatStyle::SIAS_Leave; 22418 verifyFormat("vector< ::std::string> x4;", "vector<::std::string> x4;", 22419 Spaces); 22420 verifyFormat("vector< ::std::string > x4;", "vector<::std::string > x4;", 22421 Spaces); 22422 22423 verifyFormat("A<A<int> >();", Spaces); 22424 verifyFormat("A<A<int> >();", "A<A<int>>();", Spaces); 22425 verifyFormat("A< A< int > >();", Spaces); 22426 22427 Spaces.Standard = FormatStyle::LS_Cpp11; 22428 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22429 verifyFormat("A< A< int > >();", Spaces); 22430 22431 Spaces.SpacesInAngles = FormatStyle::SIAS_Never; 22432 verifyFormat("vector<::std::string> x4;", Spaces); 22433 verifyFormat("vector<int> x5;", Spaces); 22434 verifyFormat("Foo<int, Bar> x6;", Spaces); 22435 verifyFormat("Foo<::int, ::Bar> x7;", Spaces); 22436 22437 verifyFormat("A<A<int>>();", Spaces); 22438 22439 Spaces.SpacesInAngles = FormatStyle::SIAS_Leave; 22440 verifyFormat("vector<::std::string> x4;", Spaces); 22441 verifyFormat("vector< ::std::string > x4;", Spaces); 22442 verifyFormat("vector<int> x5;", Spaces); 22443 verifyFormat("vector< int > x5;", Spaces); 22444 verifyFormat("Foo<int, Bar> x6;", Spaces); 22445 verifyFormat("Foo< int, Bar > x6;", Spaces); 22446 verifyFormat("Foo<::int, ::Bar> x7;", Spaces); 22447 verifyFormat("Foo< ::int, ::Bar > x7;", Spaces); 22448 22449 verifyFormat("A<A<int>>();", Spaces); 22450 verifyFormat("A< A< int > >();", Spaces); 22451 verifyFormat("A<A<int > >();", Spaces); 22452 verifyFormat("A< A< int>>();", Spaces); 22453 22454 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22455 verifyFormat("// clang-format off\n" 22456 "foo<<<1, 1>>>();\n" 22457 "// clang-format on\n", 22458 Spaces); 22459 verifyFormat("// clang-format off\n" 22460 "foo< < <1, 1> > >();\n" 22461 "// clang-format on\n", 22462 Spaces); 22463 } 22464 22465 TEST_F(FormatTest, SpaceAfterTemplateKeyword) { 22466 FormatStyle Style = getLLVMStyle(); 22467 Style.SpaceAfterTemplateKeyword = false; 22468 verifyFormat("template<int> void foo();", Style); 22469 } 22470 22471 TEST_F(FormatTest, TripleAngleBrackets) { 22472 verifyFormat("f<<<1, 1>>>();"); 22473 verifyFormat("f<<<1, 1, 1, s>>>();"); 22474 verifyFormat("f<<<a, b, c, d>>>();"); 22475 EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();")); 22476 verifyFormat("f<param><<<1, 1>>>();"); 22477 verifyFormat("f<1><<<1, 1>>>();"); 22478 EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();")); 22479 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 22480 "aaaaaaaaaaa<<<\n 1, 1>>>();"); 22481 verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n" 22482 " <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();"); 22483 } 22484 22485 TEST_F(FormatTest, MergeLessLessAtEnd) { 22486 verifyFormat("<<"); 22487 EXPECT_EQ("< < <", format("\\\n<<<")); 22488 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 22489 "aaallvm::outs() <<"); 22490 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 22491 "aaaallvm::outs()\n <<"); 22492 } 22493 22494 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) { 22495 std::string code = "#if A\n" 22496 "#if B\n" 22497 "a.\n" 22498 "#endif\n" 22499 " a = 1;\n" 22500 "#else\n" 22501 "#endif\n" 22502 "#if C\n" 22503 "#else\n" 22504 "#endif\n"; 22505 EXPECT_EQ(code, format(code)); 22506 } 22507 22508 TEST_F(FormatTest, HandleConflictMarkers) { 22509 // Git/SVN conflict markers. 22510 EXPECT_EQ("int a;\n" 22511 "void f() {\n" 22512 " callme(some(parameter1,\n" 22513 "<<<<<<< text by the vcs\n" 22514 " parameter2),\n" 22515 "||||||| text by the vcs\n" 22516 " parameter2),\n" 22517 " parameter3,\n" 22518 "======= text by the vcs\n" 22519 " parameter2, parameter3),\n" 22520 ">>>>>>> text by the vcs\n" 22521 " otherparameter);\n", 22522 format("int a;\n" 22523 "void f() {\n" 22524 " callme(some(parameter1,\n" 22525 "<<<<<<< text by the vcs\n" 22526 " parameter2),\n" 22527 "||||||| text by the vcs\n" 22528 " parameter2),\n" 22529 " parameter3,\n" 22530 "======= text by the vcs\n" 22531 " parameter2,\n" 22532 " parameter3),\n" 22533 ">>>>>>> text by the vcs\n" 22534 " otherparameter);\n")); 22535 22536 // Perforce markers. 22537 EXPECT_EQ("void f() {\n" 22538 " function(\n" 22539 ">>>> text by the vcs\n" 22540 " parameter,\n" 22541 "==== text by the vcs\n" 22542 " parameter,\n" 22543 "==== text by the vcs\n" 22544 " parameter,\n" 22545 "<<<< text by the vcs\n" 22546 " parameter);\n", 22547 format("void f() {\n" 22548 " function(\n" 22549 ">>>> text by the vcs\n" 22550 " parameter,\n" 22551 "==== text by the vcs\n" 22552 " parameter,\n" 22553 "==== text by the vcs\n" 22554 " parameter,\n" 22555 "<<<< text by the vcs\n" 22556 " parameter);\n")); 22557 22558 EXPECT_EQ("<<<<<<<\n" 22559 "|||||||\n" 22560 "=======\n" 22561 ">>>>>>>", 22562 format("<<<<<<<\n" 22563 "|||||||\n" 22564 "=======\n" 22565 ">>>>>>>")); 22566 22567 EXPECT_EQ("<<<<<<<\n" 22568 "|||||||\n" 22569 "int i;\n" 22570 "=======\n" 22571 ">>>>>>>", 22572 format("<<<<<<<\n" 22573 "|||||||\n" 22574 "int i;\n" 22575 "=======\n" 22576 ">>>>>>>")); 22577 22578 // FIXME: Handle parsing of macros around conflict markers correctly: 22579 EXPECT_EQ("#define Macro \\\n" 22580 "<<<<<<<\n" 22581 "Something \\\n" 22582 "|||||||\n" 22583 "Else \\\n" 22584 "=======\n" 22585 "Other \\\n" 22586 ">>>>>>>\n" 22587 " End int i;\n", 22588 format("#define Macro \\\n" 22589 "<<<<<<<\n" 22590 " Something \\\n" 22591 "|||||||\n" 22592 " Else \\\n" 22593 "=======\n" 22594 " Other \\\n" 22595 ">>>>>>>\n" 22596 " End\n" 22597 "int i;\n")); 22598 22599 verifyFormat(R"(==== 22600 #ifdef A 22601 a 22602 #else 22603 b 22604 #endif 22605 )"); 22606 } 22607 22608 TEST_F(FormatTest, DisableRegions) { 22609 EXPECT_EQ("int i;\n" 22610 "// clang-format off\n" 22611 " int j;\n" 22612 "// clang-format on\n" 22613 "int k;", 22614 format(" int i;\n" 22615 " // clang-format off\n" 22616 " int j;\n" 22617 " // clang-format on\n" 22618 " int k;")); 22619 EXPECT_EQ("int i;\n" 22620 "/* clang-format off */\n" 22621 " int j;\n" 22622 "/* clang-format on */\n" 22623 "int k;", 22624 format(" int i;\n" 22625 " /* clang-format off */\n" 22626 " int j;\n" 22627 " /* clang-format on */\n" 22628 " int k;")); 22629 22630 // Don't reflow comments within disabled regions. 22631 EXPECT_EQ("// clang-format off\n" 22632 "// long long long long long long line\n" 22633 "/* clang-format on */\n" 22634 "/* long long long\n" 22635 " * long long long\n" 22636 " * line */\n" 22637 "int i;\n" 22638 "/* clang-format off */\n" 22639 "/* long long long long long long line */\n", 22640 format("// clang-format off\n" 22641 "// long long long long long long line\n" 22642 "/* clang-format on */\n" 22643 "/* long long long long long long line */\n" 22644 "int i;\n" 22645 "/* clang-format off */\n" 22646 "/* long long long long long long line */\n", 22647 getLLVMStyleWithColumns(20))); 22648 } 22649 22650 TEST_F(FormatTest, DoNotCrashOnInvalidInput) { 22651 format("? ) ="); 22652 verifyNoCrash("#define a\\\n /**/}"); 22653 } 22654 22655 TEST_F(FormatTest, FormatsTableGenCode) { 22656 FormatStyle Style = getLLVMStyle(); 22657 Style.Language = FormatStyle::LK_TableGen; 22658 verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style); 22659 } 22660 22661 TEST_F(FormatTest, ArrayOfTemplates) { 22662 EXPECT_EQ("auto a = new unique_ptr<int>[10];", 22663 format("auto a = new unique_ptr<int > [ 10];")); 22664 22665 FormatStyle Spaces = getLLVMStyle(); 22666 Spaces.SpacesInSquareBrackets = true; 22667 EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];", 22668 format("auto a = new unique_ptr<int > [10];", Spaces)); 22669 } 22670 22671 TEST_F(FormatTest, ArrayAsTemplateType) { 22672 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;", 22673 format("auto a = unique_ptr < Foo < Bar>[ 10]> ;")); 22674 22675 FormatStyle Spaces = getLLVMStyle(); 22676 Spaces.SpacesInSquareBrackets = true; 22677 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;", 22678 format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces)); 22679 } 22680 22681 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); } 22682 22683 TEST(FormatStyle, GetStyleWithEmptyFileName) { 22684 llvm::vfs::InMemoryFileSystem FS; 22685 auto Style1 = getStyle("file", "", "Google", "", &FS); 22686 ASSERT_TRUE((bool)Style1); 22687 ASSERT_EQ(*Style1, getGoogleStyle()); 22688 } 22689 22690 TEST(FormatStyle, GetStyleOfFile) { 22691 llvm::vfs::InMemoryFileSystem FS; 22692 // Test 1: format file in the same directory. 22693 ASSERT_TRUE( 22694 FS.addFile("/a/.clang-format", 0, 22695 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM"))); 22696 ASSERT_TRUE( 22697 FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22698 auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS); 22699 ASSERT_TRUE((bool)Style1); 22700 ASSERT_EQ(*Style1, getLLVMStyle()); 22701 22702 // Test 2.1: fallback to default. 22703 ASSERT_TRUE( 22704 FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22705 auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS); 22706 ASSERT_TRUE((bool)Style2); 22707 ASSERT_EQ(*Style2, getMozillaStyle()); 22708 22709 // Test 2.2: no format on 'none' fallback style. 22710 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS); 22711 ASSERT_TRUE((bool)Style2); 22712 ASSERT_EQ(*Style2, getNoStyle()); 22713 22714 // Test 2.3: format if config is found with no based style while fallback is 22715 // 'none'. 22716 ASSERT_TRUE(FS.addFile("/b/.clang-format", 0, 22717 llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2"))); 22718 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS); 22719 ASSERT_TRUE((bool)Style2); 22720 ASSERT_EQ(*Style2, getLLVMStyle()); 22721 22722 // Test 2.4: format if yaml with no based style, while fallback is 'none'. 22723 Style2 = getStyle("{}", "a.h", "none", "", &FS); 22724 ASSERT_TRUE((bool)Style2); 22725 ASSERT_EQ(*Style2, getLLVMStyle()); 22726 22727 // Test 3: format file in parent directory. 22728 ASSERT_TRUE( 22729 FS.addFile("/c/.clang-format", 0, 22730 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 22731 ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0, 22732 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22733 auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS); 22734 ASSERT_TRUE((bool)Style3); 22735 ASSERT_EQ(*Style3, getGoogleStyle()); 22736 22737 // Test 4: error on invalid fallback style 22738 auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS); 22739 ASSERT_FALSE((bool)Style4); 22740 llvm::consumeError(Style4.takeError()); 22741 22742 // Test 5: error on invalid yaml on command line 22743 auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS); 22744 ASSERT_FALSE((bool)Style5); 22745 llvm::consumeError(Style5.takeError()); 22746 22747 // Test 6: error on invalid style 22748 auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS); 22749 ASSERT_FALSE((bool)Style6); 22750 llvm::consumeError(Style6.takeError()); 22751 22752 // Test 7: found config file, error on parsing it 22753 ASSERT_TRUE( 22754 FS.addFile("/d/.clang-format", 0, 22755 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n" 22756 "InvalidKey: InvalidValue"))); 22757 ASSERT_TRUE( 22758 FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22759 auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS); 22760 ASSERT_FALSE((bool)Style7a); 22761 llvm::consumeError(Style7a.takeError()); 22762 22763 auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true); 22764 ASSERT_TRUE((bool)Style7b); 22765 22766 // Test 8: inferred per-language defaults apply. 22767 auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS); 22768 ASSERT_TRUE((bool)StyleTd); 22769 ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen)); 22770 22771 // Test 9.1.1: overwriting a file style, when no parent file exists with no 22772 // fallback style. 22773 ASSERT_TRUE(FS.addFile( 22774 "/e/sub/.clang-format", 0, 22775 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n" 22776 "ColumnLimit: 20"))); 22777 ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0, 22778 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22779 auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS); 22780 ASSERT_TRUE(static_cast<bool>(Style9)); 22781 ASSERT_EQ(*Style9, [] { 22782 auto Style = getNoStyle(); 22783 Style.ColumnLimit = 20; 22784 return Style; 22785 }()); 22786 22787 // Test 9.1.2: propagate more than one level with no parent file. 22788 ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0, 22789 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22790 ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0, 22791 llvm::MemoryBuffer::getMemBuffer( 22792 "BasedOnStyle: InheritParentConfig\n" 22793 "WhitespaceSensitiveMacros: ['FOO', 'BAR']"))); 22794 std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"}; 22795 22796 ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros); 22797 Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS); 22798 ASSERT_TRUE(static_cast<bool>(Style9)); 22799 ASSERT_EQ(*Style9, [&NonDefaultWhiteSpaceMacros] { 22800 auto Style = getNoStyle(); 22801 Style.ColumnLimit = 20; 22802 Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros; 22803 return Style; 22804 }()); 22805 22806 // Test 9.2: with LLVM fallback style 22807 Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS); 22808 ASSERT_TRUE(static_cast<bool>(Style9)); 22809 ASSERT_EQ(*Style9, [] { 22810 auto Style = getLLVMStyle(); 22811 Style.ColumnLimit = 20; 22812 return Style; 22813 }()); 22814 22815 // Test 9.3: with a parent file 22816 ASSERT_TRUE( 22817 FS.addFile("/e/.clang-format", 0, 22818 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n" 22819 "UseTab: Always"))); 22820 Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS); 22821 ASSERT_TRUE(static_cast<bool>(Style9)); 22822 ASSERT_EQ(*Style9, [] { 22823 auto Style = getGoogleStyle(); 22824 Style.ColumnLimit = 20; 22825 Style.UseTab = FormatStyle::UT_Always; 22826 return Style; 22827 }()); 22828 22829 // Test 9.4: propagate more than one level with a parent file. 22830 const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] { 22831 auto Style = getGoogleStyle(); 22832 Style.ColumnLimit = 20; 22833 Style.UseTab = FormatStyle::UT_Always; 22834 Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros; 22835 return Style; 22836 }(); 22837 22838 ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros); 22839 Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS); 22840 ASSERT_TRUE(static_cast<bool>(Style9)); 22841 ASSERT_EQ(*Style9, SubSubStyle); 22842 22843 // Test 9.5: use InheritParentConfig as style name 22844 Style9 = 22845 getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS); 22846 ASSERT_TRUE(static_cast<bool>(Style9)); 22847 ASSERT_EQ(*Style9, SubSubStyle); 22848 22849 // Test 9.6: use command line style with inheritance 22850 Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp", 22851 "none", "", &FS); 22852 ASSERT_TRUE(static_cast<bool>(Style9)); 22853 ASSERT_EQ(*Style9, SubSubStyle); 22854 22855 // Test 9.7: use command line style with inheritance and own config 22856 Style9 = getStyle("{BasedOnStyle: InheritParentConfig, " 22857 "WhitespaceSensitiveMacros: ['FOO', 'BAR']}", 22858 "/e/sub/code.cpp", "none", "", &FS); 22859 ASSERT_TRUE(static_cast<bool>(Style9)); 22860 ASSERT_EQ(*Style9, SubSubStyle); 22861 22862 // Test 9.8: use inheritance from a file without BasedOnStyle 22863 ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0, 22864 llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123"))); 22865 ASSERT_TRUE( 22866 FS.addFile("/e/withoutbase/sub/.clang-format", 0, 22867 llvm::MemoryBuffer::getMemBuffer( 22868 "BasedOnStyle: InheritParentConfig\nIndentWidth: 7"))); 22869 // Make sure we do not use the fallback style 22870 Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS); 22871 ASSERT_TRUE(static_cast<bool>(Style9)); 22872 ASSERT_EQ(*Style9, [] { 22873 auto Style = getLLVMStyle(); 22874 Style.ColumnLimit = 123; 22875 return Style; 22876 }()); 22877 22878 Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS); 22879 ASSERT_TRUE(static_cast<bool>(Style9)); 22880 ASSERT_EQ(*Style9, [] { 22881 auto Style = getLLVMStyle(); 22882 Style.ColumnLimit = 123; 22883 Style.IndentWidth = 7; 22884 return Style; 22885 }()); 22886 22887 // Test 9.9: use inheritance from a specific config file. 22888 Style9 = getStyle("file:/e/sub/sub/.clang-format", "/e/sub/sub/code.cpp", 22889 "none", "", &FS); 22890 ASSERT_TRUE(static_cast<bool>(Style9)); 22891 ASSERT_EQ(*Style9, SubSubStyle); 22892 } 22893 22894 TEST(FormatStyle, GetStyleOfSpecificFile) { 22895 llvm::vfs::InMemoryFileSystem FS; 22896 // Specify absolute path to a format file in a parent directory. 22897 ASSERT_TRUE( 22898 FS.addFile("/e/.clang-format", 0, 22899 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM"))); 22900 ASSERT_TRUE( 22901 FS.addFile("/e/explicit.clang-format", 0, 22902 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 22903 ASSERT_TRUE(FS.addFile("/e/sub/sub/sub/test.cpp", 0, 22904 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22905 auto Style = getStyle("file:/e/explicit.clang-format", 22906 "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS); 22907 ASSERT_TRUE(static_cast<bool>(Style)); 22908 ASSERT_EQ(*Style, getGoogleStyle()); 22909 22910 // Specify relative path to a format file. 22911 ASSERT_TRUE( 22912 FS.addFile("../../e/explicit.clang-format", 0, 22913 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 22914 Style = getStyle("file:../../e/explicit.clang-format", 22915 "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS); 22916 ASSERT_TRUE(static_cast<bool>(Style)); 22917 ASSERT_EQ(*Style, getGoogleStyle()); 22918 22919 // Specify path to a format file that does not exist. 22920 Style = getStyle("file:/e/missing.clang-format", "/e/sub/sub/sub/test.cpp", 22921 "LLVM", "", &FS); 22922 ASSERT_FALSE(static_cast<bool>(Style)); 22923 llvm::consumeError(Style.takeError()); 22924 22925 // Specify path to a file on the filesystem. 22926 SmallString<128> FormatFilePath; 22927 std::error_code ECF = llvm::sys::fs::createTemporaryFile( 22928 "FormatFileTest", "tpl", FormatFilePath); 22929 EXPECT_FALSE((bool)ECF); 22930 llvm::raw_fd_ostream FormatFileTest(FormatFilePath, ECF); 22931 EXPECT_FALSE((bool)ECF); 22932 FormatFileTest << "BasedOnStyle: Google\n"; 22933 FormatFileTest.close(); 22934 22935 SmallString<128> TestFilePath; 22936 std::error_code ECT = 22937 llvm::sys::fs::createTemporaryFile("CodeFileTest", "cc", TestFilePath); 22938 EXPECT_FALSE((bool)ECT); 22939 llvm::raw_fd_ostream CodeFileTest(TestFilePath, ECT); 22940 CodeFileTest << "int i;\n"; 22941 CodeFileTest.close(); 22942 22943 std::string format_file_arg = std::string("file:") + FormatFilePath.c_str(); 22944 Style = getStyle(format_file_arg, TestFilePath, "LLVM", "", nullptr); 22945 22946 llvm::sys::fs::remove(FormatFilePath.c_str()); 22947 llvm::sys::fs::remove(TestFilePath.c_str()); 22948 ASSERT_TRUE(static_cast<bool>(Style)); 22949 ASSERT_EQ(*Style, getGoogleStyle()); 22950 } 22951 22952 TEST_F(ReplacementTest, FormatCodeAfterReplacements) { 22953 // Column limit is 20. 22954 std::string Code = "Type *a =\n" 22955 " new Type();\n" 22956 "g(iiiii, 0, jjjjj,\n" 22957 " 0, kkkkk, 0, mm);\n" 22958 "int bad = format ;"; 22959 std::string Expected = "auto a = new Type();\n" 22960 "g(iiiii, nullptr,\n" 22961 " jjjjj, nullptr,\n" 22962 " kkkkk, nullptr,\n" 22963 " mm);\n" 22964 "int bad = format ;"; 22965 FileID ID = Context.createInMemoryFile("format.cpp", Code); 22966 tooling::Replacements Replaces = toReplacements( 22967 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6, 22968 "auto "), 22969 tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1, 22970 "nullptr"), 22971 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1, 22972 "nullptr"), 22973 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1, 22974 "nullptr")}); 22975 22976 FormatStyle Style = getLLVMStyle(); 22977 Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility. 22978 auto FormattedReplaces = formatReplacements(Code, Replaces, Style); 22979 EXPECT_TRUE(static_cast<bool>(FormattedReplaces)) 22980 << llvm::toString(FormattedReplaces.takeError()) << "\n"; 22981 auto Result = applyAllReplacements(Code, *FormattedReplaces); 22982 EXPECT_TRUE(static_cast<bool>(Result)); 22983 EXPECT_EQ(Expected, *Result); 22984 } 22985 22986 TEST_F(ReplacementTest, SortIncludesAfterReplacement) { 22987 std::string Code = "#include \"a.h\"\n" 22988 "#include \"c.h\"\n" 22989 "\n" 22990 "int main() {\n" 22991 " return 0;\n" 22992 "}"; 22993 std::string Expected = "#include \"a.h\"\n" 22994 "#include \"b.h\"\n" 22995 "#include \"c.h\"\n" 22996 "\n" 22997 "int main() {\n" 22998 " return 0;\n" 22999 "}"; 23000 FileID ID = Context.createInMemoryFile("fix.cpp", Code); 23001 tooling::Replacements Replaces = toReplacements( 23002 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0, 23003 "#include \"b.h\"\n")}); 23004 23005 FormatStyle Style = getLLVMStyle(); 23006 Style.SortIncludes = FormatStyle::SI_CaseSensitive; 23007 auto FormattedReplaces = formatReplacements(Code, Replaces, Style); 23008 EXPECT_TRUE(static_cast<bool>(FormattedReplaces)) 23009 << llvm::toString(FormattedReplaces.takeError()) << "\n"; 23010 auto Result = applyAllReplacements(Code, *FormattedReplaces); 23011 EXPECT_TRUE(static_cast<bool>(Result)); 23012 EXPECT_EQ(Expected, *Result); 23013 } 23014 23015 TEST_F(FormatTest, FormatSortsUsingDeclarations) { 23016 EXPECT_EQ("using std::cin;\n" 23017 "using std::cout;", 23018 format("using std::cout;\n" 23019 "using std::cin;", 23020 getGoogleStyle())); 23021 } 23022 23023 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) { 23024 FormatStyle Style = getLLVMStyle(); 23025 Style.Standard = FormatStyle::LS_Cpp03; 23026 // cpp03 recognize this string as identifier u8 and literal character 'a' 23027 EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style)); 23028 } 23029 23030 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) { 23031 // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers 23032 // all modes, including C++11, C++14 and C++17 23033 EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';")); 23034 } 23035 23036 TEST_F(FormatTest, DoNotFormatLikelyXml) { 23037 EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle())); 23038 EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle())); 23039 } 23040 23041 TEST_F(FormatTest, StructuredBindings) { 23042 // Structured bindings is a C++17 feature. 23043 // all modes, including C++11, C++14 and C++17 23044 verifyFormat("auto [a, b] = f();"); 23045 EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();")); 23046 EXPECT_EQ("const auto [a, b] = f();", format("const auto[a, b] = f();")); 23047 EXPECT_EQ("auto const [a, b] = f();", format("auto const[a, b] = f();")); 23048 EXPECT_EQ("auto const volatile [a, b] = f();", 23049 format("auto const volatile[a, b] = f();")); 23050 EXPECT_EQ("auto [a, b, c] = f();", format("auto [ a , b,c ] = f();")); 23051 EXPECT_EQ("auto &[a, b, c] = f();", 23052 format("auto &[ a , b,c ] = f();")); 23053 EXPECT_EQ("auto &&[a, b, c] = f();", 23054 format("auto &&[ a , b,c ] = f();")); 23055 EXPECT_EQ("auto const &[a, b] = f();", format("auto const&[a, b] = f();")); 23056 EXPECT_EQ("auto const volatile &&[a, b] = f();", 23057 format("auto const volatile &&[a, b] = f();")); 23058 EXPECT_EQ("auto const &&[a, b] = f();", 23059 format("auto const && [a, b] = f();")); 23060 EXPECT_EQ("const auto &[a, b] = f();", 23061 format("const auto & [a, b] = f();")); 23062 EXPECT_EQ("const auto volatile &&[a, b] = f();", 23063 format("const auto volatile &&[a, b] = f();")); 23064 EXPECT_EQ("volatile const auto &&[a, b] = f();", 23065 format("volatile const auto &&[a, b] = f();")); 23066 EXPECT_EQ("const auto &&[a, b] = f();", 23067 format("const auto && [a, b] = f();")); 23068 23069 // Make sure we don't mistake structured bindings for lambdas. 23070 FormatStyle PointerMiddle = getLLVMStyle(); 23071 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle; 23072 verifyFormat("auto [a1, b]{A * i};", getGoogleStyle()); 23073 verifyFormat("auto [a2, b]{A * i};", getLLVMStyle()); 23074 verifyFormat("auto [a3, b]{A * i};", PointerMiddle); 23075 verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle()); 23076 verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle()); 23077 verifyFormat("auto const [a3, b]{A * i};", PointerMiddle); 23078 verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle()); 23079 verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle()); 23080 verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle); 23081 verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle()); 23082 verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle()); 23083 verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle); 23084 23085 EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}", 23086 format("for (const auto && [a, b] : some_range) {\n}")); 23087 EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}", 23088 format("for (const auto & [a, b] : some_range) {\n}")); 23089 EXPECT_EQ("for (const auto [a, b] : some_range) {\n}", 23090 format("for (const auto[a, b] : some_range) {\n}")); 23091 EXPECT_EQ("auto [x, y](expr);", format("auto[x,y] (expr);")); 23092 EXPECT_EQ("auto &[x, y](expr);", format("auto & [x,y] (expr);")); 23093 EXPECT_EQ("auto &&[x, y](expr);", format("auto && [x,y] (expr);")); 23094 EXPECT_EQ("auto const &[x, y](expr);", 23095 format("auto const & [x,y] (expr);")); 23096 EXPECT_EQ("auto const &&[x, y](expr);", 23097 format("auto const && [x,y] (expr);")); 23098 EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y] {expr};")); 23099 EXPECT_EQ("auto const &[x, y]{expr};", 23100 format("auto const & [x,y] {expr};")); 23101 EXPECT_EQ("auto const &&[x, y]{expr};", 23102 format("auto const && [x,y] {expr};")); 23103 23104 FormatStyle Spaces = getLLVMStyle(); 23105 Spaces.SpacesInSquareBrackets = true; 23106 verifyFormat("auto [ a, b ] = f();", Spaces); 23107 verifyFormat("auto &&[ a, b ] = f();", Spaces); 23108 verifyFormat("auto &[ a, b ] = f();", Spaces); 23109 verifyFormat("auto const &&[ a, b ] = f();", Spaces); 23110 verifyFormat("auto const &[ a, b ] = f();", Spaces); 23111 } 23112 23113 TEST_F(FormatTest, FileAndCode) { 23114 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", "")); 23115 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", "")); 23116 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", "")); 23117 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "")); 23118 EXPECT_EQ(FormatStyle::LK_ObjC, 23119 guessLanguage("foo.h", "@interface Foo\n@end\n")); 23120 EXPECT_EQ( 23121 FormatStyle::LK_ObjC, 23122 guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }")); 23123 EXPECT_EQ(FormatStyle::LK_ObjC, 23124 guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))")); 23125 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;")); 23126 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", "")); 23127 EXPECT_EQ(FormatStyle::LK_ObjC, 23128 guessLanguage("foo", "@interface Foo\n@end\n")); 23129 EXPECT_EQ(FormatStyle::LK_ObjC, 23130 guessLanguage("foo.h", "int DoStuff(CGRect rect);\n")); 23131 EXPECT_EQ( 23132 FormatStyle::LK_ObjC, 23133 guessLanguage("foo.h", 23134 "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n")); 23135 EXPECT_EQ( 23136 FormatStyle::LK_Cpp, 23137 guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;")); 23138 // Only one of the two preprocessor regions has ObjC-like code. 23139 EXPECT_EQ(FormatStyle::LK_ObjC, 23140 guessLanguage("foo.h", "#if A\n" 23141 "#define B() C\n" 23142 "#else\n" 23143 "#define B() [NSString a:@\"\"]\n" 23144 "#endif\n")); 23145 } 23146 23147 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) { 23148 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];")); 23149 EXPECT_EQ(FormatStyle::LK_ObjC, 23150 guessLanguage("foo.h", "array[[calculator getIndex]];")); 23151 EXPECT_EQ(FormatStyle::LK_Cpp, 23152 guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];")); 23153 EXPECT_EQ( 23154 FormatStyle::LK_Cpp, 23155 guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];")); 23156 EXPECT_EQ(FormatStyle::LK_ObjC, 23157 guessLanguage("foo.h", "[[noreturn foo] bar];")); 23158 EXPECT_EQ(FormatStyle::LK_Cpp, 23159 guessLanguage("foo.h", "[[clang::fallthrough]];")); 23160 EXPECT_EQ(FormatStyle::LK_ObjC, 23161 guessLanguage("foo.h", "[[clang:fallthrough] foo];")); 23162 EXPECT_EQ(FormatStyle::LK_Cpp, 23163 guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];")); 23164 EXPECT_EQ(FormatStyle::LK_Cpp, 23165 guessLanguage("foo.h", "[[using clang: fallthrough]];")); 23166 EXPECT_EQ(FormatStyle::LK_ObjC, 23167 guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];")); 23168 EXPECT_EQ(FormatStyle::LK_Cpp, 23169 guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];")); 23170 EXPECT_EQ( 23171 FormatStyle::LK_Cpp, 23172 guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)")); 23173 EXPECT_EQ( 23174 FormatStyle::LK_Cpp, 23175 guessLanguage("foo.h", 23176 "[[clang::callable_when(\"unconsumed\", \"unknown\")]]")); 23177 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]")); 23178 } 23179 23180 TEST_F(FormatTest, GuessLanguageWithCaret) { 23181 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);")); 23182 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);")); 23183 EXPECT_EQ(FormatStyle::LK_ObjC, 23184 guessLanguage("foo.h", "int(^)(char, float);")); 23185 EXPECT_EQ(FormatStyle::LK_ObjC, 23186 guessLanguage("foo.h", "int(^foo)(char, float);")); 23187 EXPECT_EQ(FormatStyle::LK_ObjC, 23188 guessLanguage("foo.h", "int(^foo[10])(char, float);")); 23189 EXPECT_EQ(FormatStyle::LK_ObjC, 23190 guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);")); 23191 EXPECT_EQ( 23192 FormatStyle::LK_ObjC, 23193 guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);")); 23194 } 23195 23196 TEST_F(FormatTest, GuessLanguageWithPragmas) { 23197 EXPECT_EQ(FormatStyle::LK_Cpp, 23198 guessLanguage("foo.h", "__pragma(warning(disable:))")); 23199 EXPECT_EQ(FormatStyle::LK_Cpp, 23200 guessLanguage("foo.h", "#pragma(warning(disable:))")); 23201 EXPECT_EQ(FormatStyle::LK_Cpp, 23202 guessLanguage("foo.h", "_Pragma(warning(disable:))")); 23203 } 23204 23205 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) { 23206 // ASM symbolic names are identifiers that must be surrounded by [] without 23207 // space in between: 23208 // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands 23209 23210 // Example from https://bugs.llvm.org/show_bug.cgi?id=45108. 23211 verifyFormat(R"(// 23212 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result)); 23213 )"); 23214 23215 // A list of several ASM symbolic names. 23216 verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)"); 23217 23218 // ASM symbolic names in inline ASM with inputs and outputs. 23219 verifyFormat(R"(// 23220 asm("cmoveq %1, %2, %[result]" 23221 : [result] "=r"(result) 23222 : "r"(test), "r"(new), "[result]"(old)); 23223 )"); 23224 23225 // ASM symbolic names in inline ASM with no outputs. 23226 verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)"); 23227 } 23228 23229 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) { 23230 EXPECT_EQ(FormatStyle::LK_Cpp, 23231 guessLanguage("foo.h", "void f() {\n" 23232 " asm (\"mov %[e], %[d]\"\n" 23233 " : [d] \"=rm\" (d)\n" 23234 " [e] \"rm\" (*e));\n" 23235 "}")); 23236 EXPECT_EQ(FormatStyle::LK_Cpp, 23237 guessLanguage("foo.h", "void f() {\n" 23238 " _asm (\"mov %[e], %[d]\"\n" 23239 " : [d] \"=rm\" (d)\n" 23240 " [e] \"rm\" (*e));\n" 23241 "}")); 23242 EXPECT_EQ(FormatStyle::LK_Cpp, 23243 guessLanguage("foo.h", "void f() {\n" 23244 " __asm (\"mov %[e], %[d]\"\n" 23245 " : [d] \"=rm\" (d)\n" 23246 " [e] \"rm\" (*e));\n" 23247 "}")); 23248 EXPECT_EQ(FormatStyle::LK_Cpp, 23249 guessLanguage("foo.h", "void f() {\n" 23250 " __asm__ (\"mov %[e], %[d]\"\n" 23251 " : [d] \"=rm\" (d)\n" 23252 " [e] \"rm\" (*e));\n" 23253 "}")); 23254 EXPECT_EQ(FormatStyle::LK_Cpp, 23255 guessLanguage("foo.h", "void f() {\n" 23256 " asm (\"mov %[e], %[d]\"\n" 23257 " : [d] \"=rm\" (d),\n" 23258 " [e] \"rm\" (*e));\n" 23259 "}")); 23260 EXPECT_EQ(FormatStyle::LK_Cpp, 23261 guessLanguage("foo.h", "void f() {\n" 23262 " asm volatile (\"mov %[e], %[d]\"\n" 23263 " : [d] \"=rm\" (d)\n" 23264 " [e] \"rm\" (*e));\n" 23265 "}")); 23266 } 23267 23268 TEST_F(FormatTest, GuessLanguageWithChildLines) { 23269 EXPECT_EQ(FormatStyle::LK_Cpp, 23270 guessLanguage("foo.h", "#define FOO ({ std::string s; })")); 23271 EXPECT_EQ(FormatStyle::LK_ObjC, 23272 guessLanguage("foo.h", "#define FOO ({ NSString *s; })")); 23273 EXPECT_EQ( 23274 FormatStyle::LK_Cpp, 23275 guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })")); 23276 EXPECT_EQ( 23277 FormatStyle::LK_ObjC, 23278 guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })")); 23279 } 23280 23281 TEST_F(FormatTest, TypenameMacros) { 23282 std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"}; 23283 23284 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353 23285 FormatStyle Google = getGoogleStyleWithColumns(0); 23286 Google.TypenameMacros = TypenameMacros; 23287 verifyFormat("struct foo {\n" 23288 " int bar;\n" 23289 " TAILQ_ENTRY(a) bleh;\n" 23290 "};", 23291 Google); 23292 23293 FormatStyle Macros = getLLVMStyle(); 23294 Macros.TypenameMacros = TypenameMacros; 23295 23296 verifyFormat("STACK_OF(int) a;", Macros); 23297 verifyFormat("STACK_OF(int) *a;", Macros); 23298 verifyFormat("STACK_OF(int const *) *a;", Macros); 23299 verifyFormat("STACK_OF(int *const) *a;", Macros); 23300 verifyFormat("STACK_OF(int, string) a;", Macros); 23301 verifyFormat("STACK_OF(LIST(int)) a;", Macros); 23302 verifyFormat("STACK_OF(LIST(int)) a, b;", Macros); 23303 verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros); 23304 verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros); 23305 verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros); 23306 verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros); 23307 23308 Macros.PointerAlignment = FormatStyle::PAS_Left; 23309 verifyFormat("STACK_OF(int)* a;", Macros); 23310 verifyFormat("STACK_OF(int*)* a;", Macros); 23311 verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros); 23312 verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros); 23313 verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros); 23314 } 23315 23316 TEST_F(FormatTest, AtomicQualifier) { 23317 // Check that we treate _Atomic as a type and not a function call 23318 FormatStyle Google = getGoogleStyleWithColumns(0); 23319 verifyFormat("struct foo {\n" 23320 " int a1;\n" 23321 " _Atomic(a) a2;\n" 23322 " _Atomic(_Atomic(int) *const) a3;\n" 23323 "};", 23324 Google); 23325 verifyFormat("_Atomic(uint64_t) a;"); 23326 verifyFormat("_Atomic(uint64_t) *a;"); 23327 verifyFormat("_Atomic(uint64_t const *) *a;"); 23328 verifyFormat("_Atomic(uint64_t *const) *a;"); 23329 verifyFormat("_Atomic(const uint64_t *) *a;"); 23330 verifyFormat("_Atomic(uint64_t) a;"); 23331 verifyFormat("_Atomic(_Atomic(uint64_t)) a;"); 23332 verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;"); 23333 verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}"); 23334 verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);"); 23335 23336 verifyFormat("_Atomic(uint64_t) *s(InitValue);"); 23337 verifyFormat("_Atomic(uint64_t) *s{InitValue};"); 23338 FormatStyle Style = getLLVMStyle(); 23339 Style.PointerAlignment = FormatStyle::PAS_Left; 23340 verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style); 23341 verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style); 23342 verifyFormat("_Atomic(int)* a;", Style); 23343 verifyFormat("_Atomic(int*)* a;", Style); 23344 verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style); 23345 23346 Style.SpacesInCStyleCastParentheses = true; 23347 Style.SpacesInParentheses = false; 23348 verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style); 23349 Style.SpacesInCStyleCastParentheses = false; 23350 Style.SpacesInParentheses = true; 23351 verifyFormat("x = (_Atomic( uint64_t ))*a;", Style); 23352 verifyFormat("x = (_Atomic( uint64_t ))&a;", Style); 23353 } 23354 23355 TEST_F(FormatTest, AmbersandInLamda) { 23356 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899 23357 FormatStyle AlignStyle = getLLVMStyle(); 23358 AlignStyle.PointerAlignment = FormatStyle::PAS_Left; 23359 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle); 23360 AlignStyle.PointerAlignment = FormatStyle::PAS_Right; 23361 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle); 23362 } 23363 23364 TEST_F(FormatTest, SpacesInConditionalStatement) { 23365 FormatStyle Spaces = getLLVMStyle(); 23366 Spaces.IfMacros.clear(); 23367 Spaces.IfMacros.push_back("MYIF"); 23368 Spaces.SpacesInConditionalStatement = true; 23369 verifyFormat("for ( int i = 0; i; i++ )\n continue;", Spaces); 23370 verifyFormat("if ( !a )\n return;", Spaces); 23371 verifyFormat("if ( a )\n return;", Spaces); 23372 verifyFormat("if constexpr ( a )\n return;", Spaces); 23373 verifyFormat("MYIF ( a )\n return;", Spaces); 23374 verifyFormat("MYIF ( a )\n return;\nelse MYIF ( b )\n return;", Spaces); 23375 verifyFormat("MYIF ( a )\n return;\nelse\n return;", Spaces); 23376 verifyFormat("switch ( a )\ncase 1:\n return;", Spaces); 23377 verifyFormat("while ( a )\n return;", Spaces); 23378 verifyFormat("while ( (a && b) )\n return;", Spaces); 23379 verifyFormat("do {\n} while ( 1 != 0 );", Spaces); 23380 verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces); 23381 // Check that space on the left of "::" is inserted as expected at beginning 23382 // of condition. 23383 verifyFormat("while ( ::func() )\n return;", Spaces); 23384 23385 // Check impact of ControlStatementsExceptControlMacros is honored. 23386 Spaces.SpaceBeforeParens = 23387 FormatStyle::SBPO_ControlStatementsExceptControlMacros; 23388 verifyFormat("MYIF( a )\n return;", Spaces); 23389 verifyFormat("MYIF( a )\n return;\nelse MYIF( b )\n return;", Spaces); 23390 verifyFormat("MYIF( a )\n return;\nelse\n return;", Spaces); 23391 } 23392 23393 TEST_F(FormatTest, AlternativeOperators) { 23394 // Test case for ensuring alternate operators are not 23395 // combined with their right most neighbour. 23396 verifyFormat("int a and b;"); 23397 verifyFormat("int a and_eq b;"); 23398 verifyFormat("int a bitand b;"); 23399 verifyFormat("int a bitor b;"); 23400 verifyFormat("int a compl b;"); 23401 verifyFormat("int a not b;"); 23402 verifyFormat("int a not_eq b;"); 23403 verifyFormat("int a or b;"); 23404 verifyFormat("int a xor b;"); 23405 verifyFormat("int a xor_eq b;"); 23406 verifyFormat("return this not_eq bitand other;"); 23407 verifyFormat("bool operator not_eq(const X bitand other)"); 23408 23409 verifyFormat("int a and 5;"); 23410 verifyFormat("int a and_eq 5;"); 23411 verifyFormat("int a bitand 5;"); 23412 verifyFormat("int a bitor 5;"); 23413 verifyFormat("int a compl 5;"); 23414 verifyFormat("int a not 5;"); 23415 verifyFormat("int a not_eq 5;"); 23416 verifyFormat("int a or 5;"); 23417 verifyFormat("int a xor 5;"); 23418 verifyFormat("int a xor_eq 5;"); 23419 23420 verifyFormat("int a compl(5);"); 23421 verifyFormat("int a not(5);"); 23422 23423 /* FIXME handle alternate tokens 23424 * https://en.cppreference.com/w/cpp/language/operator_alternative 23425 // alternative tokens 23426 verifyFormat("compl foo();"); // ~foo(); 23427 verifyFormat("foo() <%%>;"); // foo(); 23428 verifyFormat("void foo() <%%>;"); // void foo(){} 23429 verifyFormat("int a <:1:>;"); // int a[1];[ 23430 verifyFormat("%:define ABC abc"); // #define ABC abc 23431 verifyFormat("%:%:"); // ## 23432 */ 23433 } 23434 23435 TEST_F(FormatTest, STLWhileNotDefineChed) { 23436 verifyFormat("#if defined(while)\n" 23437 "#define while EMIT WARNING C4005\n" 23438 "#endif // while"); 23439 } 23440 23441 TEST_F(FormatTest, OperatorSpacing) { 23442 FormatStyle Style = getLLVMStyle(); 23443 Style.PointerAlignment = FormatStyle::PAS_Right; 23444 verifyFormat("Foo::operator*();", Style); 23445 verifyFormat("Foo::operator void *();", Style); 23446 verifyFormat("Foo::operator void **();", Style); 23447 verifyFormat("Foo::operator void *&();", Style); 23448 verifyFormat("Foo::operator void *&&();", Style); 23449 verifyFormat("Foo::operator void const *();", Style); 23450 verifyFormat("Foo::operator void const **();", Style); 23451 verifyFormat("Foo::operator void const *&();", Style); 23452 verifyFormat("Foo::operator void const *&&();", Style); 23453 verifyFormat("Foo::operator()(void *);", Style); 23454 verifyFormat("Foo::operator*(void *);", Style); 23455 verifyFormat("Foo::operator*();", Style); 23456 verifyFormat("Foo::operator**();", Style); 23457 verifyFormat("Foo::operator&();", Style); 23458 verifyFormat("Foo::operator<int> *();", Style); 23459 verifyFormat("Foo::operator<Foo> *();", Style); 23460 verifyFormat("Foo::operator<int> **();", Style); 23461 verifyFormat("Foo::operator<Foo> **();", Style); 23462 verifyFormat("Foo::operator<int> &();", Style); 23463 verifyFormat("Foo::operator<Foo> &();", Style); 23464 verifyFormat("Foo::operator<int> &&();", Style); 23465 verifyFormat("Foo::operator<Foo> &&();", Style); 23466 verifyFormat("Foo::operator<int> *&();", Style); 23467 verifyFormat("Foo::operator<Foo> *&();", Style); 23468 verifyFormat("Foo::operator<int> *&&();", Style); 23469 verifyFormat("Foo::operator<Foo> *&&();", Style); 23470 verifyFormat("operator*(int (*)(), class Foo);", Style); 23471 23472 verifyFormat("Foo::operator&();", Style); 23473 verifyFormat("Foo::operator void &();", Style); 23474 verifyFormat("Foo::operator void const &();", Style); 23475 verifyFormat("Foo::operator()(void &);", Style); 23476 verifyFormat("Foo::operator&(void &);", Style); 23477 verifyFormat("Foo::operator&();", Style); 23478 verifyFormat("operator&(int (&)(), class Foo);", Style); 23479 verifyFormat("operator&&(int (&)(), class Foo);", Style); 23480 23481 verifyFormat("Foo::operator&&();", Style); 23482 verifyFormat("Foo::operator**();", Style); 23483 verifyFormat("Foo::operator void &&();", Style); 23484 verifyFormat("Foo::operator void const &&();", Style); 23485 verifyFormat("Foo::operator()(void &&);", Style); 23486 verifyFormat("Foo::operator&&(void &&);", Style); 23487 verifyFormat("Foo::operator&&();", Style); 23488 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23489 verifyFormat("operator const nsTArrayRight<E> &()", Style); 23490 verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()", 23491 Style); 23492 verifyFormat("operator void **()", Style); 23493 verifyFormat("operator const FooRight<Object> &()", Style); 23494 verifyFormat("operator const FooRight<Object> *()", Style); 23495 verifyFormat("operator const FooRight<Object> **()", Style); 23496 verifyFormat("operator const FooRight<Object> *&()", Style); 23497 verifyFormat("operator const FooRight<Object> *&&()", Style); 23498 23499 Style.PointerAlignment = FormatStyle::PAS_Left; 23500 verifyFormat("Foo::operator*();", Style); 23501 verifyFormat("Foo::operator**();", Style); 23502 verifyFormat("Foo::operator void*();", Style); 23503 verifyFormat("Foo::operator void**();", Style); 23504 verifyFormat("Foo::operator void*&();", Style); 23505 verifyFormat("Foo::operator void*&&();", Style); 23506 verifyFormat("Foo::operator void const*();", Style); 23507 verifyFormat("Foo::operator void const**();", Style); 23508 verifyFormat("Foo::operator void const*&();", Style); 23509 verifyFormat("Foo::operator void const*&&();", Style); 23510 verifyFormat("Foo::operator/*comment*/ void*();", Style); 23511 verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style); 23512 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style); 23513 verifyFormat("Foo::operator()(void*);", Style); 23514 verifyFormat("Foo::operator*(void*);", Style); 23515 verifyFormat("Foo::operator*();", Style); 23516 verifyFormat("Foo::operator<int>*();", Style); 23517 verifyFormat("Foo::operator<Foo>*();", Style); 23518 verifyFormat("Foo::operator<int>**();", Style); 23519 verifyFormat("Foo::operator<Foo>**();", Style); 23520 verifyFormat("Foo::operator<Foo>*&();", Style); 23521 verifyFormat("Foo::operator<int>&();", Style); 23522 verifyFormat("Foo::operator<Foo>&();", Style); 23523 verifyFormat("Foo::operator<int>&&();", Style); 23524 verifyFormat("Foo::operator<Foo>&&();", Style); 23525 verifyFormat("Foo::operator<int>*&();", Style); 23526 verifyFormat("Foo::operator<Foo>*&();", Style); 23527 verifyFormat("operator*(int (*)(), class Foo);", Style); 23528 23529 verifyFormat("Foo::operator&();", Style); 23530 verifyFormat("Foo::operator void&();", Style); 23531 verifyFormat("Foo::operator void const&();", Style); 23532 verifyFormat("Foo::operator/*comment*/ void&();", Style); 23533 verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style); 23534 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style); 23535 verifyFormat("Foo::operator()(void&);", Style); 23536 verifyFormat("Foo::operator&(void&);", Style); 23537 verifyFormat("Foo::operator&();", Style); 23538 verifyFormat("operator&(int (&)(), class Foo);", Style); 23539 verifyFormat("operator&(int (&&)(), class Foo);", Style); 23540 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23541 23542 verifyFormat("Foo::operator&&();", Style); 23543 verifyFormat("Foo::operator void&&();", Style); 23544 verifyFormat("Foo::operator void const&&();", Style); 23545 verifyFormat("Foo::operator/*comment*/ void&&();", Style); 23546 verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style); 23547 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style); 23548 verifyFormat("Foo::operator()(void&&);", Style); 23549 verifyFormat("Foo::operator&&(void&&);", Style); 23550 verifyFormat("Foo::operator&&();", Style); 23551 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23552 verifyFormat("operator const nsTArrayLeft<E>&()", Style); 23553 verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()", 23554 Style); 23555 verifyFormat("operator void**()", Style); 23556 verifyFormat("operator const FooLeft<Object>&()", Style); 23557 verifyFormat("operator const FooLeft<Object>*()", Style); 23558 verifyFormat("operator const FooLeft<Object>**()", Style); 23559 verifyFormat("operator const FooLeft<Object>*&()", Style); 23560 verifyFormat("operator const FooLeft<Object>*&&()", Style); 23561 23562 // PR45107 23563 verifyFormat("operator Vector<String>&();", Style); 23564 verifyFormat("operator const Vector<String>&();", Style); 23565 verifyFormat("operator foo::Bar*();", Style); 23566 verifyFormat("operator const Foo<X>::Bar<Y>*();", Style); 23567 verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();", 23568 Style); 23569 23570 Style.PointerAlignment = FormatStyle::PAS_Middle; 23571 verifyFormat("Foo::operator*();", Style); 23572 verifyFormat("Foo::operator void *();", Style); 23573 verifyFormat("Foo::operator()(void *);", Style); 23574 verifyFormat("Foo::operator*(void *);", Style); 23575 verifyFormat("Foo::operator*();", Style); 23576 verifyFormat("operator*(int (*)(), class Foo);", Style); 23577 23578 verifyFormat("Foo::operator&();", Style); 23579 verifyFormat("Foo::operator void &();", Style); 23580 verifyFormat("Foo::operator void const &();", Style); 23581 verifyFormat("Foo::operator()(void &);", Style); 23582 verifyFormat("Foo::operator&(void &);", Style); 23583 verifyFormat("Foo::operator&();", Style); 23584 verifyFormat("operator&(int (&)(), class Foo);", Style); 23585 23586 verifyFormat("Foo::operator&&();", Style); 23587 verifyFormat("Foo::operator void &&();", Style); 23588 verifyFormat("Foo::operator void const &&();", Style); 23589 verifyFormat("Foo::operator()(void &&);", Style); 23590 verifyFormat("Foo::operator&&(void &&);", Style); 23591 verifyFormat("Foo::operator&&();", Style); 23592 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23593 } 23594 23595 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) { 23596 FormatStyle Style = getLLVMStyle(); 23597 // PR46157 23598 verifyFormat("foo(operator+, -42);", Style); 23599 verifyFormat("foo(operator++, -42);", Style); 23600 verifyFormat("foo(operator--, -42);", Style); 23601 verifyFormat("foo(-42, operator--);", Style); 23602 verifyFormat("foo(-42, operator, );", Style); 23603 verifyFormat("foo(operator, , -42);", Style); 23604 } 23605 23606 TEST_F(FormatTest, WhitespaceSensitiveMacros) { 23607 FormatStyle Style = getLLVMStyle(); 23608 Style.WhitespaceSensitiveMacros.push_back("FOO"); 23609 23610 // Don't use the helpers here, since 'mess up' will change the whitespace 23611 // and these are all whitespace sensitive by definition 23612 23613 // Newlines are important here. 23614 EXPECT_EQ("FOO(1+2 );\n", format("FOO(1+2 );\n", Style)); 23615 EXPECT_EQ("FOO(1+2 )\n", format("FOO(1+2 )\n", Style)); 23616 23617 EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);", 23618 format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style)); 23619 EXPECT_EQ( 23620 "FOO(String-ized&Messy+But\\(: :Still)=Intentional);", 23621 format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style)); 23622 EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);", 23623 format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style)); 23624 EXPECT_EQ("FOO(String-ized&Messy+But,: :\n" 23625 " Still=Intentional);", 23626 format("FOO(String-ized&Messy+But,: :\n" 23627 " Still=Intentional);", 23628 Style)); 23629 Style.AlignConsecutiveAssignments.Enabled = true; 23630 EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n" 23631 " Still=Intentional);", 23632 format("FOO(String-ized=&Messy+But,: :\n" 23633 " Still=Intentional);", 23634 Style)); 23635 23636 Style.ColumnLimit = 21; 23637 EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);", 23638 format("FOO(String-ized&Messy+But: :Still=Intentional);", Style)); 23639 } 23640 23641 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) { 23642 // These tests are not in NamespaceEndCommentsFixerTest because that doesn't 23643 // test its interaction with line wrapping 23644 FormatStyle Style = getLLVMStyleWithColumns(80); 23645 verifyFormat("namespace {\n" 23646 "int i;\n" 23647 "int j;\n" 23648 "} // namespace", 23649 Style); 23650 23651 verifyFormat("namespace AAA {\n" 23652 "int i;\n" 23653 "int j;\n" 23654 "} // namespace AAA", 23655 Style); 23656 23657 EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n" 23658 "int i;\n" 23659 "int j;\n" 23660 "} // namespace Averyveryveryverylongnamespace", 23661 format("namespace Averyveryveryverylongnamespace {\n" 23662 "int i;\n" 23663 "int j;\n" 23664 "}", 23665 Style)); 23666 23667 EXPECT_EQ( 23668 "namespace " 23669 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n" 23670 " went::mad::now {\n" 23671 "int i;\n" 23672 "int j;\n" 23673 "} // namespace\n" 23674 " // " 23675 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::" 23676 "went::mad::now", 23677 format("namespace " 23678 "would::it::save::you::a::lot::of::time::if_::i::" 23679 "just::gave::up::and_::went::mad::now {\n" 23680 "int i;\n" 23681 "int j;\n" 23682 "}", 23683 Style)); 23684 23685 // This used to duplicate the comment again and again on subsequent runs 23686 EXPECT_EQ( 23687 "namespace " 23688 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n" 23689 " went::mad::now {\n" 23690 "int i;\n" 23691 "int j;\n" 23692 "} // namespace\n" 23693 " // " 23694 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::" 23695 "went::mad::now", 23696 format("namespace " 23697 "would::it::save::you::a::lot::of::time::if_::i::" 23698 "just::gave::up::and_::went::mad::now {\n" 23699 "int i;\n" 23700 "int j;\n" 23701 "} // namespace\n" 23702 " // " 23703 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::" 23704 "and_::went::mad::now", 23705 Style)); 23706 } 23707 23708 TEST_F(FormatTest, LikelyUnlikely) { 23709 FormatStyle Style = getLLVMStyle(); 23710 23711 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23712 " return 29;\n" 23713 "}", 23714 Style); 23715 23716 verifyFormat("if (argc > 5) [[likely]] {\n" 23717 " return 29;\n" 23718 "}", 23719 Style); 23720 23721 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23722 " return 29;\n" 23723 "} else [[likely]] {\n" 23724 " return 42;\n" 23725 "}\n", 23726 Style); 23727 23728 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23729 " return 29;\n" 23730 "} else if (argc > 10) [[likely]] {\n" 23731 " return 99;\n" 23732 "} else {\n" 23733 " return 42;\n" 23734 "}\n", 23735 Style); 23736 23737 verifyFormat("if (argc > 5) [[gnu::unused]] {\n" 23738 " return 29;\n" 23739 "}", 23740 Style); 23741 23742 verifyFormat("if (argc > 5) [[unlikely]]\n" 23743 " return 29;\n", 23744 Style); 23745 verifyFormat("if (argc > 5) [[likely]]\n" 23746 " return 29;\n", 23747 Style); 23748 23749 Style.AttributeMacros.push_back("UNLIKELY"); 23750 Style.AttributeMacros.push_back("LIKELY"); 23751 verifyFormat("if (argc > 5) UNLIKELY\n" 23752 " return 29;\n", 23753 Style); 23754 23755 verifyFormat("if (argc > 5) UNLIKELY {\n" 23756 " return 29;\n" 23757 "}", 23758 Style); 23759 verifyFormat("if (argc > 5) UNLIKELY {\n" 23760 " return 29;\n" 23761 "} else [[likely]] {\n" 23762 " return 42;\n" 23763 "}\n", 23764 Style); 23765 verifyFormat("if (argc > 5) UNLIKELY {\n" 23766 " return 29;\n" 23767 "} else LIKELY {\n" 23768 " return 42;\n" 23769 "}\n", 23770 Style); 23771 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23772 " return 29;\n" 23773 "} else LIKELY {\n" 23774 " return 42;\n" 23775 "}\n", 23776 Style); 23777 } 23778 23779 TEST_F(FormatTest, PenaltyIndentedWhitespace) { 23780 verifyFormat("Constructor()\n" 23781 " : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 23782 " aaaa(aaaaaaaaaaaaaaaaaa, " 23783 "aaaaaaaaaaaaaaaaaat))"); 23784 verifyFormat("Constructor()\n" 23785 " : aaaaaaaaaaaaa(aaaaaa), " 23786 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)"); 23787 23788 FormatStyle StyleWithWhitespacePenalty = getLLVMStyle(); 23789 StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5; 23790 verifyFormat("Constructor()\n" 23791 " : aaaaaa(aaaaaa),\n" 23792 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 23793 " aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))", 23794 StyleWithWhitespacePenalty); 23795 verifyFormat("Constructor()\n" 23796 " : aaaaaaaaaaaaa(aaaaaa), " 23797 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)", 23798 StyleWithWhitespacePenalty); 23799 } 23800 23801 TEST_F(FormatTest, LLVMDefaultStyle) { 23802 FormatStyle Style = getLLVMStyle(); 23803 verifyFormat("extern \"C\" {\n" 23804 "int foo();\n" 23805 "}", 23806 Style); 23807 } 23808 TEST_F(FormatTest, GNUDefaultStyle) { 23809 FormatStyle Style = getGNUStyle(); 23810 verifyFormat("extern \"C\"\n" 23811 "{\n" 23812 " int foo ();\n" 23813 "}", 23814 Style); 23815 } 23816 TEST_F(FormatTest, MozillaDefaultStyle) { 23817 FormatStyle Style = getMozillaStyle(); 23818 verifyFormat("extern \"C\"\n" 23819 "{\n" 23820 " int foo();\n" 23821 "}", 23822 Style); 23823 } 23824 TEST_F(FormatTest, GoogleDefaultStyle) { 23825 FormatStyle Style = getGoogleStyle(); 23826 verifyFormat("extern \"C\" {\n" 23827 "int foo();\n" 23828 "}", 23829 Style); 23830 } 23831 TEST_F(FormatTest, ChromiumDefaultStyle) { 23832 FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp); 23833 verifyFormat("extern \"C\" {\n" 23834 "int foo();\n" 23835 "}", 23836 Style); 23837 } 23838 TEST_F(FormatTest, MicrosoftDefaultStyle) { 23839 FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp); 23840 verifyFormat("extern \"C\"\n" 23841 "{\n" 23842 " int foo();\n" 23843 "}", 23844 Style); 23845 } 23846 TEST_F(FormatTest, WebKitDefaultStyle) { 23847 FormatStyle Style = getWebKitStyle(); 23848 verifyFormat("extern \"C\" {\n" 23849 "int foo();\n" 23850 "}", 23851 Style); 23852 } 23853 23854 TEST_F(FormatTest, Concepts) { 23855 EXPECT_EQ(getLLVMStyle().BreakBeforeConceptDeclarations, 23856 FormatStyle::BBCDS_Always); 23857 verifyFormat("template <typename T>\n" 23858 "concept True = true;"); 23859 23860 verifyFormat("template <typename T>\n" 23861 "concept C = ((false || foo()) && C2<T>) ||\n" 23862 " (std::trait<T>::value && Baz) || sizeof(T) >= 6;", 23863 getLLVMStyleWithColumns(60)); 23864 23865 verifyFormat("template <typename T>\n" 23866 "concept DelayedCheck = true && requires(T t) { t.bar(); } && " 23867 "sizeof(T) <= 8;"); 23868 23869 verifyFormat("template <typename T>\n" 23870 "concept DelayedCheck = true && requires(T t) {\n" 23871 " t.bar();\n" 23872 " t.baz();\n" 23873 " } && sizeof(T) <= 8;"); 23874 23875 verifyFormat("template <typename T>\n" 23876 "concept DelayedCheck = true && requires(T t) { // Comment\n" 23877 " t.bar();\n" 23878 " t.baz();\n" 23879 " } && sizeof(T) <= 8;"); 23880 23881 verifyFormat("template <typename T>\n" 23882 "concept DelayedCheck = false || requires(T t) { t.bar(); } && " 23883 "sizeof(T) <= 8;"); 23884 23885 verifyFormat("template <typename T>\n" 23886 "concept DelayedCheck = !!false || requires(T t) { t.bar(); } " 23887 "&& sizeof(T) <= 8;"); 23888 23889 verifyFormat( 23890 "template <typename T>\n" 23891 "concept DelayedCheck = static_cast<bool>(0) ||\n" 23892 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 23893 23894 verifyFormat("template <typename T>\n" 23895 "concept DelayedCheck = bool(0) || requires(T t) { t.bar(); } " 23896 "&& sizeof(T) <= 8;"); 23897 23898 verifyFormat( 23899 "template <typename T>\n" 23900 "concept DelayedCheck = (bool)(0) ||\n" 23901 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 23902 23903 verifyFormat("template <typename T>\n" 23904 "concept DelayedCheck = (bool)0 || requires(T t) { t.bar(); } " 23905 "&& sizeof(T) <= 8;"); 23906 23907 verifyFormat("template <typename T>\n" 23908 "concept Size = sizeof(T) >= 5 && requires(T t) { t.bar(); } && " 23909 "sizeof(T) <= 8;"); 23910 23911 verifyFormat("template <typename T>\n" 23912 "concept Size = 2 < 5 && 2 <= 5 && 8 >= 5 && 8 > 5 &&\n" 23913 " requires(T t) {\n" 23914 " t.bar();\n" 23915 " t.baz();\n" 23916 " } && sizeof(T) <= 8 && !(4 < 3);", 23917 getLLVMStyleWithColumns(60)); 23918 23919 verifyFormat("template <typename T>\n" 23920 "concept TrueOrNot = IsAlwaysTrue || IsNeverTrue;"); 23921 23922 verifyFormat("template <typename T>\n" 23923 "concept C = foo();"); 23924 23925 verifyFormat("template <typename T>\n" 23926 "concept C = foo(T());"); 23927 23928 verifyFormat("template <typename T>\n" 23929 "concept C = foo(T{});"); 23930 23931 verifyFormat("template <typename T>\n" 23932 "concept Size = V<sizeof(T)>::Value > 5;"); 23933 23934 verifyFormat("template <typename T>\n" 23935 "concept True = S<T>::Value;"); 23936 23937 verifyFormat( 23938 "template <typename T>\n" 23939 "concept C = []() { return true; }() && requires(T t) { t.bar(); } &&\n" 23940 " sizeof(T) <= 8;"); 23941 23942 // FIXME: This is misformatted because the fake l paren starts at bool, not at 23943 // the lambda l square. 23944 verifyFormat("template <typename T>\n" 23945 "concept C = [] -> bool { return true; }() && requires(T t) { " 23946 "t.bar(); } &&\n" 23947 " sizeof(T) <= 8;"); 23948 23949 verifyFormat( 23950 "template <typename T>\n" 23951 "concept C = decltype([]() { return std::true_type{}; }())::value &&\n" 23952 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 23953 23954 verifyFormat("template <typename T>\n" 23955 "concept C = decltype([]() { return std::true_type{}; " 23956 "}())::value && requires(T t) { t.bar(); } && sizeof(T) <= 8;", 23957 getLLVMStyleWithColumns(120)); 23958 23959 verifyFormat("template <typename T>\n" 23960 "concept C = decltype([]() -> std::true_type { return {}; " 23961 "}())::value &&\n" 23962 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 23963 23964 verifyFormat("template <typename T>\n" 23965 "concept C = true;\n" 23966 "Foo Bar;"); 23967 23968 verifyFormat("template <typename T>\n" 23969 "concept Hashable = requires(T a) {\n" 23970 " { std::hash<T>{}(a) } -> " 23971 "std::convertible_to<std::size_t>;\n" 23972 " };"); 23973 23974 verifyFormat( 23975 "template <typename T>\n" 23976 "concept EqualityComparable = requires(T a, T b) {\n" 23977 " { a == b } -> std::same_as<bool>;\n" 23978 " };"); 23979 23980 verifyFormat( 23981 "template <typename T>\n" 23982 "concept EqualityComparable = requires(T a, T b) {\n" 23983 " { a == b } -> std::same_as<bool>;\n" 23984 " { a != b } -> std::same_as<bool>;\n" 23985 " };"); 23986 23987 verifyFormat("template <typename T>\n" 23988 "concept WeakEqualityComparable = requires(T a, T b) {\n" 23989 " { a == b };\n" 23990 " { a != b };\n" 23991 " };"); 23992 23993 verifyFormat("template <typename T>\n" 23994 "concept HasSizeT = requires { typename T::size_t; };"); 23995 23996 verifyFormat("template <typename T>\n" 23997 "concept Semiregular =\n" 23998 " DefaultConstructible<T> && CopyConstructible<T> && " 23999 "CopyAssignable<T> &&\n" 24000 " requires(T a, std::size_t n) {\n" 24001 " requires Same<T *, decltype(&a)>;\n" 24002 " { a.~T() } noexcept;\n" 24003 " requires Same<T *, decltype(new T)>;\n" 24004 " requires Same<T *, decltype(new T[n])>;\n" 24005 " { delete new T; };\n" 24006 " { delete new T[n]; };\n" 24007 " };"); 24008 24009 verifyFormat("template <typename T>\n" 24010 "concept Semiregular =\n" 24011 " requires(T a, std::size_t n) {\n" 24012 " requires Same<T *, decltype(&a)>;\n" 24013 " { a.~T() } noexcept;\n" 24014 " requires Same<T *, decltype(new T)>;\n" 24015 " requires Same<T *, decltype(new T[n])>;\n" 24016 " { delete new T; };\n" 24017 " { delete new T[n]; };\n" 24018 " { new T } -> std::same_as<T *>;\n" 24019 " } && DefaultConstructible<T> && CopyConstructible<T> && " 24020 "CopyAssignable<T>;"); 24021 24022 verifyFormat( 24023 "template <typename T>\n" 24024 "concept Semiregular =\n" 24025 " DefaultConstructible<T> && requires(T a, std::size_t n) {\n" 24026 " requires Same<T *, decltype(&a)>;\n" 24027 " { a.~T() } noexcept;\n" 24028 " requires Same<T *, decltype(new T)>;\n" 24029 " requires Same<T *, decltype(new " 24030 "T[n])>;\n" 24031 " { delete new T; };\n" 24032 " { delete new T[n]; };\n" 24033 " } && CopyConstructible<T> && " 24034 "CopyAssignable<T>;"); 24035 24036 verifyFormat("template <typename T>\n" 24037 "concept Two = requires(T t) {\n" 24038 " { t.foo() } -> std::same_as<Bar>;\n" 24039 " } && requires(T &&t) {\n" 24040 " { t.foo() } -> std::same_as<Bar &&>;\n" 24041 " };"); 24042 24043 verifyFormat( 24044 "template <typename T>\n" 24045 "concept C = requires(T x) {\n" 24046 " { *x } -> std::convertible_to<typename T::inner>;\n" 24047 " { x + 1 } noexcept -> std::same_as<int>;\n" 24048 " { x * 1 } -> std::convertible_to<T>;\n" 24049 " };"); 24050 24051 verifyFormat( 24052 "template <typename T, typename U = T>\n" 24053 "concept Swappable = requires(T &&t, U &&u) {\n" 24054 " swap(std::forward<T>(t), std::forward<U>(u));\n" 24055 " swap(std::forward<U>(u), std::forward<T>(t));\n" 24056 " };"); 24057 24058 verifyFormat("template <typename T, typename U>\n" 24059 "concept Common = requires(T &&t, U &&u) {\n" 24060 " typename CommonType<T, U>;\n" 24061 " { CommonType<T, U>(std::forward<T>(t)) };\n" 24062 " };"); 24063 24064 verifyFormat("template <typename T, typename U>\n" 24065 "concept Common = requires(T &&t, U &&u) {\n" 24066 " typename CommonType<T, U>;\n" 24067 " { CommonType<T, U>{std::forward<T>(t)} };\n" 24068 " };"); 24069 24070 verifyFormat( 24071 "template <typename T>\n" 24072 "concept C = requires(T t) {\n" 24073 " requires Bar<T> && Foo<T>;\n" 24074 " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n" 24075 " };"); 24076 24077 verifyFormat("template <typename T>\n" 24078 "concept HasFoo = requires(T t) {\n" 24079 " { t.foo() };\n" 24080 " t.foo();\n" 24081 " };\n" 24082 "template <typename T>\n" 24083 "concept HasBar = requires(T t) {\n" 24084 " { t.bar() };\n" 24085 " t.bar();\n" 24086 " };"); 24087 24088 verifyFormat("template <typename T>\n" 24089 "concept Large = sizeof(T) > 10;"); 24090 24091 verifyFormat("template <typename T, typename U>\n" 24092 "concept FooableWith = requires(T t, U u) {\n" 24093 " typename T::foo_type;\n" 24094 " { t.foo(u) } -> typename T::foo_type;\n" 24095 " t++;\n" 24096 " };\n" 24097 "void doFoo(FooableWith<int> auto t) { t.foo(3); }"); 24098 24099 verifyFormat("template <typename T>\n" 24100 "concept Context = is_specialization_of_v<context, T>;"); 24101 24102 verifyFormat("template <typename T>\n" 24103 "concept Node = std::is_object_v<T>;"); 24104 24105 verifyFormat("template <class T>\n" 24106 "concept integral = __is_integral(T);"); 24107 24108 verifyFormat("template <class T>\n" 24109 "concept is2D = __array_extent(T, 1) == 2;"); 24110 24111 verifyFormat("template <class T>\n" 24112 "concept isRhs = __is_rvalue_expr(std::declval<T>() + 2)"); 24113 24114 verifyFormat("template <class T, class T2>\n" 24115 "concept Same = __is_same_as<T, T2>;"); 24116 24117 auto Style = getLLVMStyle(); 24118 Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Allowed; 24119 24120 verifyFormat( 24121 "template <typename T>\n" 24122 "concept C = requires(T t) {\n" 24123 " requires Bar<T> && Foo<T>;\n" 24124 " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n" 24125 " };", 24126 Style); 24127 24128 verifyFormat("template <typename T>\n" 24129 "concept HasFoo = requires(T t) {\n" 24130 " { t.foo() };\n" 24131 " t.foo();\n" 24132 " };\n" 24133 "template <typename T>\n" 24134 "concept HasBar = requires(T t) {\n" 24135 " { t.bar() };\n" 24136 " t.bar();\n" 24137 " };", 24138 Style); 24139 24140 verifyFormat("template <typename T> concept True = true;", Style); 24141 24142 verifyFormat("template <typename T>\n" 24143 "concept C = decltype([]() -> std::true_type { return {}; " 24144 "}())::value &&\n" 24145 " requires(T t) { t.bar(); } && sizeof(T) <= 8;", 24146 Style); 24147 24148 verifyFormat("template <typename T>\n" 24149 "concept Semiregular =\n" 24150 " DefaultConstructible<T> && CopyConstructible<T> && " 24151 "CopyAssignable<T> &&\n" 24152 " requires(T a, std::size_t n) {\n" 24153 " requires Same<T *, decltype(&a)>;\n" 24154 " { a.~T() } noexcept;\n" 24155 " requires Same<T *, decltype(new T)>;\n" 24156 " requires Same<T *, decltype(new T[n])>;\n" 24157 " { delete new T; };\n" 24158 " { delete new T[n]; };\n" 24159 " };", 24160 Style); 24161 24162 Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Never; 24163 24164 verifyFormat("template <typename T> concept C =\n" 24165 " requires(T t) {\n" 24166 " requires Bar<T> && Foo<T>;\n" 24167 " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n" 24168 " };", 24169 Style); 24170 24171 verifyFormat("template <typename T> concept HasFoo = requires(T t) {\n" 24172 " { t.foo() };\n" 24173 " t.foo();\n" 24174 " };\n" 24175 "template <typename T> concept HasBar = requires(T t) {\n" 24176 " { t.bar() };\n" 24177 " t.bar();\n" 24178 " };", 24179 Style); 24180 24181 verifyFormat("template <typename T> concept True = true;", Style); 24182 24183 verifyFormat( 24184 "template <typename T> concept C = decltype([]() -> std::true_type {\n" 24185 " return {};\n" 24186 " }())::value &&\n" 24187 " requires(T t) { t.bar(); } && " 24188 "sizeof(T) <= 8;", 24189 Style); 24190 24191 verifyFormat("template <typename T> concept Semiregular =\n" 24192 " DefaultConstructible<T> && CopyConstructible<T> && " 24193 "CopyAssignable<T> &&\n" 24194 " requires(T a, std::size_t n) {\n" 24195 " requires Same<T *, decltype(&a)>;\n" 24196 " { a.~T() } noexcept;\n" 24197 " requires Same<T *, decltype(new T)>;\n" 24198 " requires Same<T *, decltype(new T[n])>;\n" 24199 " { delete new T; };\n" 24200 " { delete new T[n]; };\n" 24201 " };", 24202 Style); 24203 24204 // The following tests are invalid C++, we just want to make sure we don't 24205 // assert. 24206 verifyFormat("template <typename T>\n" 24207 "concept C = requires C2<T>;"); 24208 24209 verifyFormat("template <typename T>\n" 24210 "concept C = 5 + 4;"); 24211 24212 verifyFormat("template <typename T>\n" 24213 "concept C =\n" 24214 "class X;"); 24215 24216 verifyFormat("template <typename T>\n" 24217 "concept C = [] && true;"); 24218 24219 verifyFormat("template <typename T>\n" 24220 "concept C = [] && requires(T t) { typename T::size_type; };"); 24221 } 24222 24223 TEST_F(FormatTest, RequiresClausesPositions) { 24224 auto Style = getLLVMStyle(); 24225 EXPECT_EQ(Style.RequiresClausePosition, FormatStyle::RCPS_OwnLine); 24226 EXPECT_EQ(Style.IndentRequiresClause, true); 24227 24228 verifyFormat("template <typename T>\n" 24229 " requires(Foo<T> && std::trait<T>)\n" 24230 "struct Bar;", 24231 Style); 24232 24233 verifyFormat("template <typename T>\n" 24234 " requires(Foo<T> && std::trait<T>)\n" 24235 "class Bar {\n" 24236 "public:\n" 24237 " Bar(T t);\n" 24238 " bool baz();\n" 24239 "};", 24240 Style); 24241 24242 verifyFormat( 24243 "template <typename T>\n" 24244 " requires requires(T &&t) {\n" 24245 " typename T::I;\n" 24246 " requires(F<typename T::I> && std::trait<typename T::I>);\n" 24247 " }\n" 24248 "Bar(T) -> Bar<typename T::I>;", 24249 Style); 24250 24251 verifyFormat("template <typename T>\n" 24252 " requires(Foo<T> && std::trait<T>)\n" 24253 "constexpr T MyGlobal;", 24254 Style); 24255 24256 verifyFormat("template <typename T>\n" 24257 " requires Foo<T> && requires(T t) {\n" 24258 " { t.baz() } -> std::same_as<bool>;\n" 24259 " requires std::same_as<T::Factor, int>;\n" 24260 " }\n" 24261 "inline int bar(T t) {\n" 24262 " return t.baz() ? T::Factor : 5;\n" 24263 "}", 24264 Style); 24265 24266 verifyFormat("template <typename T>\n" 24267 "inline int bar(T t)\n" 24268 " requires Foo<T> && requires(T t) {\n" 24269 " { t.baz() } -> std::same_as<bool>;\n" 24270 " requires std::same_as<T::Factor, int>;\n" 24271 " }\n" 24272 "{\n" 24273 " return t.baz() ? T::Factor : 5;\n" 24274 "}", 24275 Style); 24276 24277 verifyFormat("template <typename T>\n" 24278 " requires F<T>\n" 24279 "int bar(T t) {\n" 24280 " return 5;\n" 24281 "}", 24282 Style); 24283 24284 verifyFormat("template <typename T>\n" 24285 "int bar(T t)\n" 24286 " requires F<T>\n" 24287 "{\n" 24288 " return 5;\n" 24289 "}", 24290 Style); 24291 24292 verifyFormat("template <typename T>\n" 24293 "int bar(T t)\n" 24294 " requires F<T>;", 24295 Style); 24296 24297 Style.IndentRequiresClause = false; 24298 verifyFormat("template <typename T>\n" 24299 "requires F<T>\n" 24300 "int bar(T t) {\n" 24301 " return 5;\n" 24302 "}", 24303 Style); 24304 24305 verifyFormat("template <typename T>\n" 24306 "int bar(T t)\n" 24307 "requires F<T>\n" 24308 "{\n" 24309 " return 5;\n" 24310 "}", 24311 Style); 24312 24313 Style.RequiresClausePosition = FormatStyle::RCPS_SingleLine; 24314 verifyFormat("template <typename T> requires Foo<T> struct Bar {};\n" 24315 "template <typename T> requires Foo<T> void bar() {}\n" 24316 "template <typename T> void bar() requires Foo<T> {}\n" 24317 "template <typename T> void bar() requires Foo<T>;\n" 24318 "template <typename T> requires Foo<T> Bar(T) -> Bar<T>;", 24319 Style); 24320 24321 auto ColumnStyle = Style; 24322 ColumnStyle.ColumnLimit = 40; 24323 verifyFormat("template <typename AAAAAAA>\n" 24324 "requires Foo<T> struct Bar {};\n" 24325 "template <typename AAAAAAA>\n" 24326 "requires Foo<T> void bar() {}\n" 24327 "template <typename AAAAAAA>\n" 24328 "void bar() requires Foo<T> {}\n" 24329 "template <typename AAAAAAA>\n" 24330 "requires Foo<T> Baz(T) -> Baz<T>;", 24331 ColumnStyle); 24332 24333 verifyFormat("template <typename T>\n" 24334 "requires Foo<AAAAAAA> struct Bar {};\n" 24335 "template <typename T>\n" 24336 "requires Foo<AAAAAAA> void bar() {}\n" 24337 "template <typename T>\n" 24338 "void bar() requires Foo<AAAAAAA> {}\n" 24339 "template <typename T>\n" 24340 "requires Foo<AAAAAAA> Bar(T) -> Bar<T>;", 24341 ColumnStyle); 24342 24343 verifyFormat("template <typename AAAAAAA>\n" 24344 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24345 "struct Bar {};\n" 24346 "template <typename AAAAAAA>\n" 24347 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24348 "void bar() {}\n" 24349 "template <typename AAAAAAA>\n" 24350 "void bar()\n" 24351 " requires Foo<AAAAAAAAAAAAAAAA> {}\n" 24352 "template <typename AAAAAAA>\n" 24353 "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n" 24354 "template <typename AAAAAAA>\n" 24355 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24356 "Bar(T) -> Bar<T>;", 24357 ColumnStyle); 24358 24359 Style.RequiresClausePosition = FormatStyle::RCPS_WithFollowing; 24360 ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithFollowing; 24361 24362 verifyFormat("template <typename T>\n" 24363 "requires Foo<T> struct Bar {};\n" 24364 "template <typename T>\n" 24365 "requires Foo<T> void bar() {}\n" 24366 "template <typename T>\n" 24367 "void bar()\n" 24368 "requires Foo<T> {}\n" 24369 "template <typename T>\n" 24370 "void bar()\n" 24371 "requires Foo<T>;\n" 24372 "template <typename T>\n" 24373 "requires Foo<T> Bar(T) -> Bar<T>;", 24374 Style); 24375 24376 verifyFormat("template <typename AAAAAAA>\n" 24377 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24378 "struct Bar {};\n" 24379 "template <typename AAAAAAA>\n" 24380 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24381 "void bar() {}\n" 24382 "template <typename AAAAAAA>\n" 24383 "void bar()\n" 24384 "requires Foo<AAAAAAAAAAAAAAAA> {}\n" 24385 "template <typename AAAAAAA>\n" 24386 "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n" 24387 "template <typename AAAAAAA>\n" 24388 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24389 "Bar(T) -> Bar<T>;", 24390 ColumnStyle); 24391 24392 Style.IndentRequiresClause = true; 24393 ColumnStyle.IndentRequiresClause = true; 24394 24395 verifyFormat("template <typename T>\n" 24396 " requires Foo<T> struct Bar {};\n" 24397 "template <typename T>\n" 24398 " requires Foo<T> void bar() {}\n" 24399 "template <typename T>\n" 24400 "void bar()\n" 24401 " requires Foo<T> {}\n" 24402 "template <typename T>\n" 24403 " requires Foo<T> Bar(T) -> Bar<T>;", 24404 Style); 24405 24406 verifyFormat("template <typename AAAAAAA>\n" 24407 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24408 "struct Bar {};\n" 24409 "template <typename AAAAAAA>\n" 24410 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24411 "void bar() {}\n" 24412 "template <typename AAAAAAA>\n" 24413 "void bar()\n" 24414 " requires Foo<AAAAAAAAAAAAAAAA> {}\n" 24415 "template <typename AAAAAAA>\n" 24416 " requires Foo<AAAAAA> Bar(T) -> Bar<T>;\n" 24417 "template <typename AAAAAAA>\n" 24418 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24419 "Bar(T) -> Bar<T>;", 24420 ColumnStyle); 24421 24422 Style.RequiresClausePosition = FormatStyle::RCPS_WithPreceding; 24423 ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithPreceding; 24424 24425 verifyFormat("template <typename T> requires Foo<T>\n" 24426 "struct Bar {};\n" 24427 "template <typename T> requires Foo<T>\n" 24428 "void bar() {}\n" 24429 "template <typename T>\n" 24430 "void bar() requires Foo<T>\n" 24431 "{}\n" 24432 "template <typename T> void bar() requires Foo<T>;\n" 24433 "template <typename T> requires Foo<T>\n" 24434 "Bar(T) -> Bar<T>;", 24435 Style); 24436 24437 verifyFormat("template <typename AAAAAAA>\n" 24438 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24439 "struct Bar {};\n" 24440 "template <typename AAAAAAA>\n" 24441 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24442 "void bar() {}\n" 24443 "template <typename AAAAAAA>\n" 24444 "void bar()\n" 24445 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24446 "{}\n" 24447 "template <typename AAAAAAA>\n" 24448 "requires Foo<AAAAAAAA>\n" 24449 "Bar(T) -> Bar<T>;\n" 24450 "template <typename AAAAAAA>\n" 24451 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24452 "Bar(T) -> Bar<T>;", 24453 ColumnStyle); 24454 } 24455 24456 TEST_F(FormatTest, RequiresClauses) { 24457 verifyFormat("struct [[nodiscard]] zero_t {\n" 24458 " template <class T>\n" 24459 " requires requires { number_zero_v<T>; }\n" 24460 " [[nodiscard]] constexpr operator T() const {\n" 24461 " return number_zero_v<T>;\n" 24462 " }\n" 24463 "};"); 24464 24465 auto Style = getLLVMStyle(); 24466 24467 verifyFormat( 24468 "template <typename T>\n" 24469 " requires is_default_constructible_v<hash<T>> and\n" 24470 " is_copy_constructible_v<hash<T>> and\n" 24471 " is_move_constructible_v<hash<T>> and\n" 24472 " is_copy_assignable_v<hash<T>> and " 24473 "is_move_assignable_v<hash<T>> and\n" 24474 " is_destructible_v<hash<T>> and is_swappable_v<hash<T>> and\n" 24475 " is_callable_v<hash<T>(T)> and\n" 24476 " is_same_v<size_t, decltype(hash<T>(declval<T>()))> and\n" 24477 " is_same_v<size_t, decltype(hash<T>(declval<T &>()))> and\n" 24478 " is_same_v<size_t, decltype(hash<T>(declval<const T &>()))>\n" 24479 "struct S {};", 24480 Style); 24481 24482 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 24483 verifyFormat( 24484 "template <typename T>\n" 24485 " requires is_default_constructible_v<hash<T>>\n" 24486 " and is_copy_constructible_v<hash<T>>\n" 24487 " and is_move_constructible_v<hash<T>>\n" 24488 " and is_copy_assignable_v<hash<T>> and " 24489 "is_move_assignable_v<hash<T>>\n" 24490 " and is_destructible_v<hash<T>> and is_swappable_v<hash<T>>\n" 24491 " and is_callable_v<hash<T>(T)>\n" 24492 " and is_same_v<size_t, decltype(hash<T>(declval<T>()))>\n" 24493 " and is_same_v<size_t, decltype(hash<T>(declval<T &>()))>\n" 24494 " and is_same_v<size_t, decltype(hash<T>(declval<const T " 24495 "&>()))>\n" 24496 "struct S {};", 24497 Style); 24498 24499 // Not a clause, but we once hit an assert. 24500 verifyFormat("#if 0\n" 24501 "#else\n" 24502 "foo();\n" 24503 "#endif\n" 24504 "bar(requires);"); 24505 } 24506 24507 TEST_F(FormatTest, StatementAttributeLikeMacros) { 24508 FormatStyle Style = getLLVMStyle(); 24509 StringRef Source = "void Foo::slot() {\n" 24510 " unsigned char MyChar = 'x';\n" 24511 " emit signal(MyChar);\n" 24512 " Q_EMIT signal(MyChar);\n" 24513 "}"; 24514 24515 EXPECT_EQ(Source, format(Source, Style)); 24516 24517 Style.AlignConsecutiveDeclarations.Enabled = true; 24518 EXPECT_EQ("void Foo::slot() {\n" 24519 " unsigned char MyChar = 'x';\n" 24520 " emit signal(MyChar);\n" 24521 " Q_EMIT signal(MyChar);\n" 24522 "}", 24523 format(Source, Style)); 24524 24525 Style.StatementAttributeLikeMacros.push_back("emit"); 24526 EXPECT_EQ(Source, format(Source, Style)); 24527 24528 Style.StatementAttributeLikeMacros = {}; 24529 EXPECT_EQ("void Foo::slot() {\n" 24530 " unsigned char MyChar = 'x';\n" 24531 " emit signal(MyChar);\n" 24532 " Q_EMIT signal(MyChar);\n" 24533 "}", 24534 format(Source, Style)); 24535 } 24536 24537 TEST_F(FormatTest, IndentAccessModifiers) { 24538 FormatStyle Style = getLLVMStyle(); 24539 Style.IndentAccessModifiers = true; 24540 // Members are *two* levels below the record; 24541 // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation. 24542 verifyFormat("class C {\n" 24543 " int i;\n" 24544 "};\n", 24545 Style); 24546 verifyFormat("union C {\n" 24547 " int i;\n" 24548 " unsigned u;\n" 24549 "};\n", 24550 Style); 24551 // Access modifiers should be indented one level below the record. 24552 verifyFormat("class C {\n" 24553 " public:\n" 24554 " int i;\n" 24555 "};\n", 24556 Style); 24557 verifyFormat("struct S {\n" 24558 " private:\n" 24559 " class C {\n" 24560 " int j;\n" 24561 "\n" 24562 " public:\n" 24563 " C();\n" 24564 " };\n" 24565 "\n" 24566 " public:\n" 24567 " int i;\n" 24568 "};\n", 24569 Style); 24570 // Enumerations are not records and should be unaffected. 24571 Style.AllowShortEnumsOnASingleLine = false; 24572 verifyFormat("enum class E {\n" 24573 " A,\n" 24574 " B\n" 24575 "};\n", 24576 Style); 24577 // Test with a different indentation width; 24578 // also proves that the result is Style.AccessModifierOffset agnostic. 24579 Style.IndentWidth = 3; 24580 verifyFormat("class C {\n" 24581 " public:\n" 24582 " int i;\n" 24583 "};\n", 24584 Style); 24585 } 24586 24587 TEST_F(FormatTest, LimitlessStringsAndComments) { 24588 auto Style = getLLVMStyleWithColumns(0); 24589 constexpr StringRef Code = 24590 "/**\n" 24591 " * This is a multiline comment with quite some long lines, at least for " 24592 "the LLVM Style.\n" 24593 " * We will redo this with strings and line comments. Just to check if " 24594 "everything is working.\n" 24595 " */\n" 24596 "bool foo() {\n" 24597 " /* Single line multi line comment. */\n" 24598 " const std::string String = \"This is a multiline string with quite " 24599 "some long lines, at least for the LLVM Style.\"\n" 24600 " \"We already did it with multi line " 24601 "comments, and we will do it with line comments. Just to check if " 24602 "everything is working.\";\n" 24603 " // This is a line comment (block) with quite some long lines, at " 24604 "least for the LLVM Style.\n" 24605 " // We already did this with multi line comments and strings. Just to " 24606 "check if everything is working.\n" 24607 " const std::string SmallString = \"Hello World\";\n" 24608 " // Small line comment\n" 24609 " return String.size() > SmallString.size();\n" 24610 "}"; 24611 EXPECT_EQ(Code, format(Code, Style)); 24612 } 24613 24614 TEST_F(FormatTest, FormatDecayCopy) { 24615 // error cases from unit tests 24616 verifyFormat("foo(auto())"); 24617 verifyFormat("foo(auto{})"); 24618 verifyFormat("foo(auto({}))"); 24619 verifyFormat("foo(auto{{}})"); 24620 24621 verifyFormat("foo(auto(1))"); 24622 verifyFormat("foo(auto{1})"); 24623 verifyFormat("foo(new auto(1))"); 24624 verifyFormat("foo(new auto{1})"); 24625 verifyFormat("decltype(auto(1)) x;"); 24626 verifyFormat("decltype(auto{1}) x;"); 24627 verifyFormat("auto(x);"); 24628 verifyFormat("auto{x};"); 24629 verifyFormat("new auto{x};"); 24630 verifyFormat("auto{x} = y;"); 24631 verifyFormat("auto(x) = y;"); // actually a declaration, but this is clearly 24632 // the user's own fault 24633 verifyFormat("integral auto(x) = y;"); // actually a declaration, but this is 24634 // clearly the user's own fault 24635 verifyFormat("auto(*p)() = f;"); // actually a declaration; TODO FIXME 24636 } 24637 24638 TEST_F(FormatTest, Cpp20ModulesSupport) { 24639 FormatStyle Style = getLLVMStyle(); 24640 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 24641 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 24642 24643 verifyFormat("export import foo;", Style); 24644 verifyFormat("export import foo:bar;", Style); 24645 verifyFormat("export import foo.bar;", Style); 24646 verifyFormat("export import foo.bar:baz;", Style); 24647 verifyFormat("export import :bar;", Style); 24648 verifyFormat("export module foo:bar;", Style); 24649 verifyFormat("export module foo;", Style); 24650 verifyFormat("export module foo.bar;", Style); 24651 verifyFormat("export module foo.bar:baz;", Style); 24652 verifyFormat("export import <string_view>;", Style); 24653 24654 verifyFormat("export type_name var;", Style); 24655 verifyFormat("template <class T> export using A = B<T>;", Style); 24656 verifyFormat("export using A = B;", Style); 24657 verifyFormat("export int func() {\n" 24658 " foo();\n" 24659 "}", 24660 Style); 24661 verifyFormat("export struct {\n" 24662 " int foo;\n" 24663 "};", 24664 Style); 24665 verifyFormat("export {\n" 24666 " int foo;\n" 24667 "};", 24668 Style); 24669 verifyFormat("export export char const *hello() { return \"hello\"; }"); 24670 24671 verifyFormat("import bar;", Style); 24672 verifyFormat("import foo.bar;", Style); 24673 verifyFormat("import foo:bar;", Style); 24674 verifyFormat("import :bar;", Style); 24675 verifyFormat("import <ctime>;", Style); 24676 verifyFormat("import \"header\";", Style); 24677 24678 verifyFormat("module foo;", Style); 24679 verifyFormat("module foo:bar;", Style); 24680 verifyFormat("module foo.bar;", Style); 24681 verifyFormat("module;", Style); 24682 24683 verifyFormat("export namespace hi {\n" 24684 "const char *sayhi();\n" 24685 "}", 24686 Style); 24687 24688 verifyFormat("module :private;", Style); 24689 verifyFormat("import <foo/bar.h>;", Style); 24690 verifyFormat("import foo...bar;", Style); 24691 verifyFormat("import ..........;", Style); 24692 verifyFormat("module foo:private;", Style); 24693 verifyFormat("import a", Style); 24694 verifyFormat("module a", Style); 24695 verifyFormat("export import a", Style); 24696 verifyFormat("export module a", Style); 24697 24698 verifyFormat("import", Style); 24699 verifyFormat("module", Style); 24700 verifyFormat("export", Style); 24701 } 24702 24703 TEST_F(FormatTest, CoroutineForCoawait) { 24704 FormatStyle Style = getLLVMStyle(); 24705 verifyFormat("for co_await (auto x : range())\n ;"); 24706 verifyFormat("for (auto i : arr) {\n" 24707 "}", 24708 Style); 24709 verifyFormat("for co_await (auto i : arr) {\n" 24710 "}", 24711 Style); 24712 verifyFormat("for co_await (auto i : foo(T{})) {\n" 24713 "}", 24714 Style); 24715 } 24716 24717 TEST_F(FormatTest, CoroutineCoAwait) { 24718 verifyFormat("int x = co_await foo();"); 24719 verifyFormat("int x = (co_await foo());"); 24720 verifyFormat("co_await (42);"); 24721 verifyFormat("void operator co_await(int);"); 24722 verifyFormat("void operator co_await(a);"); 24723 verifyFormat("co_await a;"); 24724 verifyFormat("co_await missing_await_resume{};"); 24725 verifyFormat("co_await a; // comment"); 24726 verifyFormat("void test0() { co_await a; }"); 24727 verifyFormat("co_await co_await co_await foo();"); 24728 verifyFormat("co_await foo().bar();"); 24729 verifyFormat("co_await [this]() -> Task { co_return x; }"); 24730 verifyFormat("co_await [this](int a, int b) -> Task { co_return co_await " 24731 "foo(); }(x, y);"); 24732 24733 FormatStyle Style = getLLVMStyleWithColumns(40); 24734 verifyFormat("co_await [this](int a, int b) -> Task {\n" 24735 " co_return co_await foo();\n" 24736 "}(x, y);", 24737 Style); 24738 verifyFormat("co_await;"); 24739 } 24740 24741 TEST_F(FormatTest, CoroutineCoYield) { 24742 verifyFormat("int x = co_yield foo();"); 24743 verifyFormat("int x = (co_yield foo());"); 24744 verifyFormat("co_yield (42);"); 24745 verifyFormat("co_yield {42};"); 24746 verifyFormat("co_yield 42;"); 24747 verifyFormat("co_yield n++;"); 24748 verifyFormat("co_yield ++n;"); 24749 verifyFormat("co_yield;"); 24750 } 24751 24752 TEST_F(FormatTest, CoroutineCoReturn) { 24753 verifyFormat("co_return (42);"); 24754 verifyFormat("co_return;"); 24755 verifyFormat("co_return {};"); 24756 verifyFormat("co_return x;"); 24757 verifyFormat("co_return co_await foo();"); 24758 verifyFormat("co_return co_yield foo();"); 24759 } 24760 24761 TEST_F(FormatTest, EmptyShortBlock) { 24762 auto Style = getLLVMStyle(); 24763 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 24764 24765 verifyFormat("try {\n" 24766 " doA();\n" 24767 "} catch (Exception &e) {\n" 24768 " e.printStackTrace();\n" 24769 "}\n", 24770 Style); 24771 24772 verifyFormat("try {\n" 24773 " doA();\n" 24774 "} catch (Exception &e) {}\n", 24775 Style); 24776 } 24777 24778 TEST_F(FormatTest, ShortTemplatedArgumentLists) { 24779 auto Style = getLLVMStyle(); 24780 24781 verifyFormat("template <> struct S : Template<int (*)[]> {};\n", Style); 24782 verifyFormat("template <> struct S : Template<int (*)[10]> {};\n", Style); 24783 verifyFormat("struct Y : X<[] { return 0; }> {};", Style); 24784 verifyFormat("struct Y<[] { return 0; }> {};", Style); 24785 24786 verifyFormat("struct Z : X<decltype([] { return 0; }){}> {};", Style); 24787 verifyFormat("template <int N> struct Foo<char[N]> {};", Style); 24788 } 24789 24790 TEST_F(FormatTest, InsertBraces) { 24791 FormatStyle Style = getLLVMStyle(); 24792 Style.InsertBraces = true; 24793 24794 verifyFormat("// clang-format off\n" 24795 "// comment\n" 24796 "if (a) f();\n" 24797 "// clang-format on\n" 24798 "if (b) {\n" 24799 " g();\n" 24800 "}", 24801 "// clang-format off\n" 24802 "// comment\n" 24803 "if (a) f();\n" 24804 "// clang-format on\n" 24805 "if (b) g();", 24806 Style); 24807 24808 verifyFormat("if (a) {\n" 24809 " switch (b) {\n" 24810 " case 1:\n" 24811 " c = 0;\n" 24812 " break;\n" 24813 " default:\n" 24814 " c = 1;\n" 24815 " }\n" 24816 "}", 24817 "if (a)\n" 24818 " switch (b) {\n" 24819 " case 1:\n" 24820 " c = 0;\n" 24821 " break;\n" 24822 " default:\n" 24823 " c = 1;\n" 24824 " }", 24825 Style); 24826 24827 verifyFormat("for (auto node : nodes) {\n" 24828 " if (node) {\n" 24829 " break;\n" 24830 " }\n" 24831 "}", 24832 "for (auto node : nodes)\n" 24833 " if (node)\n" 24834 " break;", 24835 Style); 24836 24837 verifyFormat("for (auto node : nodes) {\n" 24838 " if (node)\n" 24839 "}", 24840 "for (auto node : nodes)\n" 24841 " if (node)", 24842 Style); 24843 24844 verifyFormat("do {\n" 24845 " --a;\n" 24846 "} while (a);", 24847 "do\n" 24848 " --a;\n" 24849 "while (a);", 24850 Style); 24851 24852 verifyFormat("if (i) {\n" 24853 " ++i;\n" 24854 "} else {\n" 24855 " --i;\n" 24856 "}", 24857 "if (i)\n" 24858 " ++i;\n" 24859 "else {\n" 24860 " --i;\n" 24861 "}", 24862 Style); 24863 24864 verifyFormat("void f() {\n" 24865 " while (j--) {\n" 24866 " while (i) {\n" 24867 " --i;\n" 24868 " }\n" 24869 " }\n" 24870 "}", 24871 "void f() {\n" 24872 " while (j--)\n" 24873 " while (i)\n" 24874 " --i;\n" 24875 "}", 24876 Style); 24877 24878 verifyFormat("f({\n" 24879 " if (a) {\n" 24880 " g();\n" 24881 " }\n" 24882 "});", 24883 "f({\n" 24884 " if (a)\n" 24885 " g();\n" 24886 "});", 24887 Style); 24888 24889 verifyFormat("if (a) {\n" 24890 " f();\n" 24891 "} else if (b) {\n" 24892 " g();\n" 24893 "} else {\n" 24894 " h();\n" 24895 "}", 24896 "if (a)\n" 24897 " f();\n" 24898 "else if (b)\n" 24899 " g();\n" 24900 "else\n" 24901 " h();", 24902 Style); 24903 24904 verifyFormat("if (a) {\n" 24905 " f();\n" 24906 "}\n" 24907 "// comment\n" 24908 "/* comment */", 24909 "if (a)\n" 24910 " f();\n" 24911 "// comment\n" 24912 "/* comment */", 24913 Style); 24914 24915 verifyFormat("if (a) {\n" 24916 " // foo\n" 24917 " // bar\n" 24918 " f();\n" 24919 "}", 24920 "if (a)\n" 24921 " // foo\n" 24922 " // bar\n" 24923 " f();", 24924 Style); 24925 24926 verifyFormat("if (a) { // comment\n" 24927 " // comment\n" 24928 " f();\n" 24929 "}", 24930 "if (a) // comment\n" 24931 " // comment\n" 24932 " f();", 24933 Style); 24934 24935 verifyFormat("if (a) {\n" 24936 " f(); // comment\n" 24937 "}", 24938 "if (a)\n" 24939 " f(); // comment", 24940 Style); 24941 24942 verifyFormat("if (a) {\n" 24943 " f();\n" 24944 "}\n" 24945 "#undef A\n" 24946 "#undef B", 24947 "if (a)\n" 24948 " f();\n" 24949 "#undef A\n" 24950 "#undef B", 24951 Style); 24952 24953 verifyFormat("if (a)\n" 24954 "#ifdef A\n" 24955 " f();\n" 24956 "#else\n" 24957 " g();\n" 24958 "#endif", 24959 Style); 24960 24961 verifyFormat("#if 0\n" 24962 "#elif 1\n" 24963 "#endif\n" 24964 "void f() {\n" 24965 " if (a) {\n" 24966 " g();\n" 24967 " }\n" 24968 "}", 24969 "#if 0\n" 24970 "#elif 1\n" 24971 "#endif\n" 24972 "void f() {\n" 24973 " if (a) g();\n" 24974 "}", 24975 Style); 24976 24977 Style.ColumnLimit = 15; 24978 24979 verifyFormat("#define A \\\n" 24980 " if (a) \\\n" 24981 " f();", 24982 Style); 24983 24984 verifyFormat("if (a + b >\n" 24985 " c) {\n" 24986 " f();\n" 24987 "}", 24988 "if (a + b > c)\n" 24989 " f();", 24990 Style); 24991 } 24992 24993 TEST_F(FormatTest, RemoveBraces) { 24994 FormatStyle Style = getLLVMStyle(); 24995 Style.RemoveBracesLLVM = true; 24996 24997 // The following eight test cases are fully-braced versions of the examples at 24998 // "llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single- 24999 // statement-bodies-of-if-else-loop-statements". 25000 25001 // 1. Omit the braces, since the body is simple and clearly associated with 25002 // the if. 25003 verifyFormat("if (isa<FunctionDecl>(D))\n" 25004 " handleFunctionDecl(D);\n" 25005 "else if (isa<VarDecl>(D))\n" 25006 " handleVarDecl(D);", 25007 "if (isa<FunctionDecl>(D)) {\n" 25008 " handleFunctionDecl(D);\n" 25009 "} else if (isa<VarDecl>(D)) {\n" 25010 " handleVarDecl(D);\n" 25011 "}", 25012 Style); 25013 25014 // 2. Here we document the condition itself and not the body. 25015 verifyFormat("if (isa<VarDecl>(D)) {\n" 25016 " // It is necessary that we explain the situation with this\n" 25017 " // surprisingly long comment, so it would be unclear\n" 25018 " // without the braces whether the following statement is in\n" 25019 " // the scope of the `if`.\n" 25020 " // Because the condition is documented, we can't really\n" 25021 " // hoist this comment that applies to the body above the\n" 25022 " // if.\n" 25023 " handleOtherDecl(D);\n" 25024 "}", 25025 Style); 25026 25027 // 3. Use braces on the outer `if` to avoid a potential dangling else 25028 // situation. 25029 verifyFormat("if (isa<VarDecl>(D)) {\n" 25030 " for (auto *A : D.attrs())\n" 25031 " if (shouldProcessAttr(A))\n" 25032 " handleAttr(A);\n" 25033 "}", 25034 "if (isa<VarDecl>(D)) {\n" 25035 " for (auto *A : D.attrs()) {\n" 25036 " if (shouldProcessAttr(A)) {\n" 25037 " handleAttr(A);\n" 25038 " }\n" 25039 " }\n" 25040 "}", 25041 Style); 25042 25043 // 4. Use braces for the `if` block to keep it uniform with the else block. 25044 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 25045 " handleFunctionDecl(D);\n" 25046 "} else {\n" 25047 " // In this else case, it is necessary that we explain the\n" 25048 " // situation with this surprisingly long comment, so it\n" 25049 " // would be unclear without the braces whether the\n" 25050 " // following statement is in the scope of the `if`.\n" 25051 " handleOtherDecl(D);\n" 25052 "}", 25053 Style); 25054 25055 // 5. This should also omit braces. The `for` loop contains only a single 25056 // statement, so it shouldn't have braces. The `if` also only contains a 25057 // single simple statement (the for loop), so it also should omit braces. 25058 verifyFormat("if (isa<FunctionDecl>(D))\n" 25059 " for (auto *A : D.attrs())\n" 25060 " handleAttr(A);", 25061 "if (isa<FunctionDecl>(D)) {\n" 25062 " for (auto *A : D.attrs()) {\n" 25063 " handleAttr(A);\n" 25064 " }\n" 25065 "}", 25066 Style); 25067 25068 // 6. Use braces for the outer `if` since the nested `for` is braced. 25069 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 25070 " for (auto *A : D.attrs()) {\n" 25071 " // In this for loop body, it is necessary that we explain\n" 25072 " // the situation with this surprisingly long comment,\n" 25073 " // forcing braces on the `for` block.\n" 25074 " handleAttr(A);\n" 25075 " }\n" 25076 "}", 25077 Style); 25078 25079 // 7. Use braces on the outer block because there are more than two levels of 25080 // nesting. 25081 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 25082 " for (auto *A : D.attrs())\n" 25083 " for (ssize_t i : llvm::seq<ssize_t>(count))\n" 25084 " handleAttrOnDecl(D, A, i);\n" 25085 "}", 25086 "if (isa<FunctionDecl>(D)) {\n" 25087 " for (auto *A : D.attrs()) {\n" 25088 " for (ssize_t i : llvm::seq<ssize_t>(count)) {\n" 25089 " handleAttrOnDecl(D, A, i);\n" 25090 " }\n" 25091 " }\n" 25092 "}", 25093 Style); 25094 25095 // 8. Use braces on the outer block because of a nested `if`, otherwise the 25096 // compiler would warn: `add explicit braces to avoid dangling else` 25097 verifyFormat("if (auto *D = dyn_cast<FunctionDecl>(D)) {\n" 25098 " if (shouldProcess(D))\n" 25099 " handleVarDecl(D);\n" 25100 " else\n" 25101 " markAsIgnored(D);\n" 25102 "}", 25103 "if (auto *D = dyn_cast<FunctionDecl>(D)) {\n" 25104 " if (shouldProcess(D)) {\n" 25105 " handleVarDecl(D);\n" 25106 " } else {\n" 25107 " markAsIgnored(D);\n" 25108 " }\n" 25109 "}", 25110 Style); 25111 25112 verifyFormat("// clang-format off\n" 25113 "// comment\n" 25114 "while (i > 0) { --i; }\n" 25115 "// clang-format on\n" 25116 "while (j < 0)\n" 25117 " ++j;", 25118 "// clang-format off\n" 25119 "// comment\n" 25120 "while (i > 0) { --i; }\n" 25121 "// clang-format on\n" 25122 "while (j < 0) { ++j; }", 25123 Style); 25124 25125 verifyFormat("if (a)\n" 25126 " b; // comment\n" 25127 "else if (c)\n" 25128 " d; /* comment */\n" 25129 "else\n" 25130 " e;", 25131 "if (a) {\n" 25132 " b; // comment\n" 25133 "} else if (c) {\n" 25134 " d; /* comment */\n" 25135 "} else {\n" 25136 " e;\n" 25137 "}", 25138 Style); 25139 25140 verifyFormat("if (a) {\n" 25141 " b;\n" 25142 " c;\n" 25143 "} else if (d) {\n" 25144 " e;\n" 25145 "}", 25146 Style); 25147 25148 verifyFormat("if (a) {\n" 25149 "#undef NDEBUG\n" 25150 " b;\n" 25151 "} else {\n" 25152 " c;\n" 25153 "}", 25154 Style); 25155 25156 verifyFormat("if (a) {\n" 25157 " // comment\n" 25158 "} else if (b) {\n" 25159 " c;\n" 25160 "}", 25161 Style); 25162 25163 verifyFormat("if (a) {\n" 25164 " b;\n" 25165 "} else {\n" 25166 " { c; }\n" 25167 "}", 25168 Style); 25169 25170 verifyFormat("if (a) {\n" 25171 " if (b) // comment\n" 25172 " c;\n" 25173 "} else if (d) {\n" 25174 " e;\n" 25175 "}", 25176 "if (a) {\n" 25177 " if (b) { // comment\n" 25178 " c;\n" 25179 " }\n" 25180 "} else if (d) {\n" 25181 " e;\n" 25182 "}", 25183 Style); 25184 25185 verifyFormat("if (a) {\n" 25186 " if (b) {\n" 25187 " c;\n" 25188 " // comment\n" 25189 " } else if (d) {\n" 25190 " e;\n" 25191 " }\n" 25192 "}", 25193 Style); 25194 25195 verifyFormat("if (a) {\n" 25196 " if (b)\n" 25197 " c;\n" 25198 "}", 25199 "if (a) {\n" 25200 " if (b) {\n" 25201 " c;\n" 25202 " }\n" 25203 "}", 25204 Style); 25205 25206 verifyFormat("if (a)\n" 25207 " if (b)\n" 25208 " c;\n" 25209 " else\n" 25210 " d;\n" 25211 "else\n" 25212 " e;", 25213 "if (a) {\n" 25214 " if (b) {\n" 25215 " c;\n" 25216 " } else {\n" 25217 " d;\n" 25218 " }\n" 25219 "} else {\n" 25220 " e;\n" 25221 "}", 25222 Style); 25223 25224 verifyFormat("if (a) {\n" 25225 " // comment\n" 25226 " if (b)\n" 25227 " c;\n" 25228 " else if (d)\n" 25229 " e;\n" 25230 "} else {\n" 25231 " g;\n" 25232 "}", 25233 "if (a) {\n" 25234 " // comment\n" 25235 " if (b) {\n" 25236 " c;\n" 25237 " } else if (d) {\n" 25238 " e;\n" 25239 " }\n" 25240 "} else {\n" 25241 " g;\n" 25242 "}", 25243 Style); 25244 25245 verifyFormat("if (a)\n" 25246 " b;\n" 25247 "else if (c)\n" 25248 " d;\n" 25249 "else\n" 25250 " e;", 25251 "if (a) {\n" 25252 " b;\n" 25253 "} else {\n" 25254 " if (c) {\n" 25255 " d;\n" 25256 " } else {\n" 25257 " e;\n" 25258 " }\n" 25259 "}", 25260 Style); 25261 25262 verifyFormat("if (a) {\n" 25263 " if (b)\n" 25264 " c;\n" 25265 " else if (d)\n" 25266 " e;\n" 25267 "} else {\n" 25268 " g;\n" 25269 "}", 25270 "if (a) {\n" 25271 " if (b)\n" 25272 " c;\n" 25273 " else {\n" 25274 " if (d)\n" 25275 " e;\n" 25276 " }\n" 25277 "} else {\n" 25278 " g;\n" 25279 "}", 25280 Style); 25281 25282 verifyFormat("if (a)\n" 25283 " b;\n" 25284 "else if (c)\n" 25285 " while (d)\n" 25286 " e;\n" 25287 "// comment", 25288 "if (a)\n" 25289 "{\n" 25290 " b;\n" 25291 "} else if (c) {\n" 25292 " while (d) {\n" 25293 " e;\n" 25294 " }\n" 25295 "}\n" 25296 "// comment", 25297 Style); 25298 25299 verifyFormat("if (a) {\n" 25300 " b;\n" 25301 "} else if (c) {\n" 25302 " d;\n" 25303 "} else {\n" 25304 " e;\n" 25305 " g;\n" 25306 "}", 25307 Style); 25308 25309 verifyFormat("if (a) {\n" 25310 " b;\n" 25311 "} else if (c) {\n" 25312 " d;\n" 25313 "} else {\n" 25314 " e;\n" 25315 "} // comment", 25316 Style); 25317 25318 verifyFormat("int abs = [](int i) {\n" 25319 " if (i >= 0)\n" 25320 " return i;\n" 25321 " return -i;\n" 25322 "};", 25323 "int abs = [](int i) {\n" 25324 " if (i >= 0) {\n" 25325 " return i;\n" 25326 " }\n" 25327 " return -i;\n" 25328 "};", 25329 Style); 25330 25331 verifyFormat("if (a)\n" 25332 " foo();\n" 25333 "else\n" 25334 " bar();", 25335 "if (a)\n" 25336 "{\n" 25337 " foo();\n" 25338 "}\n" 25339 "else\n" 25340 "{\n" 25341 " bar();\n" 25342 "}", 25343 Style); 25344 25345 verifyFormat("if (a) {\n" 25346 "Label:\n" 25347 "}", 25348 Style); 25349 25350 verifyFormat("if (a) {\n" 25351 "Label:\n" 25352 " f();\n" 25353 "}", 25354 Style); 25355 25356 verifyFormat("if (a) {\n" 25357 " f();\n" 25358 "Label:\n" 25359 "}", 25360 Style); 25361 25362 // FIXME: See https://github.com/llvm/llvm-project/issues/53543. 25363 #if 0 25364 Style.ColumnLimit = 65; 25365 25366 verifyFormat("if (condition) {\n" 25367 " ff(Indices,\n" 25368 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 25369 "} else {\n" 25370 " ff(Indices,\n" 25371 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 25372 "}", 25373 Style); 25374 25375 Style.ColumnLimit = 20; 25376 25377 verifyFormat("if (a) {\n" 25378 " b = c + // 1 -\n" 25379 " d;\n" 25380 "}", 25381 Style); 25382 25383 verifyFormat("if (a) {\n" 25384 " b = c >= 0 ? d\n" 25385 " : e;\n" 25386 "}", 25387 "if (a) {\n" 25388 " b = c >= 0 ? d : e;\n" 25389 "}", 25390 Style); 25391 #endif 25392 25393 Style.ColumnLimit = 20; 25394 25395 verifyFormat("if (a)\n" 25396 " b = c > 0 ? d : e;", 25397 "if (a) {\n" 25398 " b = c > 0 ? d : e;\n" 25399 "}", 25400 Style); 25401 25402 Style.ColumnLimit = 0; 25403 25404 verifyFormat("if (a)\n" 25405 " b234567890223456789032345678904234567890 = " 25406 "c234567890223456789032345678904234567890;", 25407 "if (a) {\n" 25408 " b234567890223456789032345678904234567890 = " 25409 "c234567890223456789032345678904234567890;\n" 25410 "}", 25411 Style); 25412 } 25413 25414 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndent) { 25415 auto Style = getLLVMStyle(); 25416 25417 StringRef Short = "functionCall(paramA, paramB, paramC);\n" 25418 "void functionDecl(int a, int b, int c);"; 25419 25420 StringRef Medium = "functionCall(paramA, paramB, paramC, paramD, paramE, " 25421 "paramF, paramG, paramH, paramI);\n" 25422 "void functionDecl(int argumentA, int argumentB, int " 25423 "argumentC, int argumentD, int argumentE);"; 25424 25425 verifyFormat(Short, Style); 25426 25427 StringRef NoBreak = "functionCall(paramA, paramB, paramC, paramD, paramE, " 25428 "paramF, paramG, paramH,\n" 25429 " paramI);\n" 25430 "void functionDecl(int argumentA, int argumentB, int " 25431 "argumentC, int argumentD,\n" 25432 " int argumentE);"; 25433 25434 verifyFormat(NoBreak, Medium, Style); 25435 verifyFormat(NoBreak, 25436 "functionCall(\n" 25437 " paramA,\n" 25438 " paramB,\n" 25439 " paramC,\n" 25440 " paramD,\n" 25441 " paramE,\n" 25442 " paramF,\n" 25443 " paramG,\n" 25444 " paramH,\n" 25445 " paramI\n" 25446 ");\n" 25447 "void functionDecl(\n" 25448 " int argumentA,\n" 25449 " int argumentB,\n" 25450 " int argumentC,\n" 25451 " int argumentD,\n" 25452 " int argumentE\n" 25453 ");", 25454 Style); 25455 25456 verifyFormat("outerFunctionCall(nestedFunctionCall(argument1),\n" 25457 " nestedLongFunctionCall(argument1, " 25458 "argument2, argument3,\n" 25459 " argument4, " 25460 "argument5));", 25461 Style); 25462 25463 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 25464 25465 verifyFormat(Short, Style); 25466 verifyFormat( 25467 "functionCall(\n" 25468 " paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, " 25469 "paramI\n" 25470 ");\n" 25471 "void functionDecl(\n" 25472 " int argumentA, int argumentB, int argumentC, int argumentD, int " 25473 "argumentE\n" 25474 ");", 25475 Medium, Style); 25476 25477 Style.AllowAllArgumentsOnNextLine = false; 25478 Style.AllowAllParametersOfDeclarationOnNextLine = false; 25479 25480 verifyFormat(Short, Style); 25481 verifyFormat( 25482 "functionCall(\n" 25483 " paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, " 25484 "paramI\n" 25485 ");\n" 25486 "void functionDecl(\n" 25487 " int argumentA, int argumentB, int argumentC, int argumentD, int " 25488 "argumentE\n" 25489 ");", 25490 Medium, Style); 25491 25492 Style.BinPackArguments = false; 25493 Style.BinPackParameters = false; 25494 25495 verifyFormat(Short, Style); 25496 25497 verifyFormat("functionCall(\n" 25498 " paramA,\n" 25499 " paramB,\n" 25500 " paramC,\n" 25501 " paramD,\n" 25502 " paramE,\n" 25503 " paramF,\n" 25504 " paramG,\n" 25505 " paramH,\n" 25506 " paramI\n" 25507 ");\n" 25508 "void functionDecl(\n" 25509 " int argumentA,\n" 25510 " int argumentB,\n" 25511 " int argumentC,\n" 25512 " int argumentD,\n" 25513 " int argumentE\n" 25514 ");", 25515 Medium, Style); 25516 25517 verifyFormat("outerFunctionCall(\n" 25518 " nestedFunctionCall(argument1),\n" 25519 " nestedLongFunctionCall(\n" 25520 " argument1,\n" 25521 " argument2,\n" 25522 " argument3,\n" 25523 " argument4,\n" 25524 " argument5\n" 25525 " )\n" 25526 ");", 25527 Style); 25528 25529 verifyFormat("int a = (int)b;", Style); 25530 verifyFormat("int a = (int)b;", 25531 "int a = (\n" 25532 " int\n" 25533 ") b;", 25534 Style); 25535 25536 verifyFormat("return (true);", Style); 25537 verifyFormat("return (true);", 25538 "return (\n" 25539 " true\n" 25540 ");", 25541 Style); 25542 25543 verifyFormat("void foo();", Style); 25544 verifyFormat("void foo();", 25545 "void foo(\n" 25546 ");", 25547 Style); 25548 25549 verifyFormat("void foo() {}", Style); 25550 verifyFormat("void foo() {}", 25551 "void foo(\n" 25552 ") {\n" 25553 "}", 25554 Style); 25555 25556 verifyFormat("auto string = std::string();", Style); 25557 verifyFormat("auto string = std::string();", 25558 "auto string = std::string(\n" 25559 ");", 25560 Style); 25561 25562 verifyFormat("void (*functionPointer)() = nullptr;", Style); 25563 verifyFormat("void (*functionPointer)() = nullptr;", 25564 "void (\n" 25565 " *functionPointer\n" 25566 ")\n" 25567 "(\n" 25568 ") = nullptr;", 25569 Style); 25570 } 25571 25572 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentIfStatement) { 25573 auto Style = getLLVMStyle(); 25574 25575 verifyFormat("if (foo()) {\n" 25576 " return;\n" 25577 "}", 25578 Style); 25579 25580 verifyFormat("if (quitelongarg !=\n" 25581 " (alsolongarg - 1)) { // ABC is a very longgggggggggggg " 25582 "comment\n" 25583 " return;\n" 25584 "}", 25585 Style); 25586 25587 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 25588 25589 verifyFormat("if (foo()) {\n" 25590 " return;\n" 25591 "}", 25592 Style); 25593 25594 verifyFormat("if (quitelongarg !=\n" 25595 " (alsolongarg - 1)) { // ABC is a very longgggggggggggg " 25596 "comment\n" 25597 " return;\n" 25598 "}", 25599 Style); 25600 } 25601 25602 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentForStatement) { 25603 auto Style = getLLVMStyle(); 25604 25605 verifyFormat("for (int i = 0; i < 5; ++i) {\n" 25606 " doSomething();\n" 25607 "}", 25608 Style); 25609 25610 verifyFormat("for (int myReallyLongCountVariable = 0; " 25611 "myReallyLongCountVariable < count;\n" 25612 " myReallyLongCountVariable++) {\n" 25613 " doSomething();\n" 25614 "}", 25615 Style); 25616 25617 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 25618 25619 verifyFormat("for (int i = 0; i < 5; ++i) {\n" 25620 " doSomething();\n" 25621 "}", 25622 Style); 25623 25624 verifyFormat("for (int myReallyLongCountVariable = 0; " 25625 "myReallyLongCountVariable < count;\n" 25626 " myReallyLongCountVariable++) {\n" 25627 " doSomething();\n" 25628 "}", 25629 Style); 25630 } 25631 25632 TEST_F(FormatTest, UnderstandsDigraphs) { 25633 verifyFormat("int arr<:5:> = {};"); 25634 verifyFormat("int arr[5] = <%%>;"); 25635 verifyFormat("int arr<:::qualified_variable:> = {};"); 25636 verifyFormat("int arr[::qualified_variable] = <%%>;"); 25637 verifyFormat("%:include <header>"); 25638 verifyFormat("%:define A x##y"); 25639 verifyFormat("#define A x%:%:y"); 25640 } 25641 25642 TEST_F(FormatTest, AlignArrayOfStructuresLeftAlignmentNonSquare) { 25643 auto Style = getLLVMStyle(); 25644 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 25645 Style.AlignConsecutiveAssignments.Enabled = true; 25646 Style.AlignConsecutiveDeclarations.Enabled = true; 25647 25648 // The AlignArray code is incorrect for non square Arrays and can cause 25649 // crashes, these tests assert that the array is not changed but will 25650 // also act as regression tests for when it is properly fixed 25651 verifyFormat("struct test demo[] = {\n" 25652 " {1, 2},\n" 25653 " {3, 4, 5},\n" 25654 " {6, 7, 8}\n" 25655 "};", 25656 Style); 25657 verifyFormat("struct test demo[] = {\n" 25658 " {1, 2, 3, 4, 5},\n" 25659 " {3, 4, 5},\n" 25660 " {6, 7, 8}\n" 25661 "};", 25662 Style); 25663 verifyFormat("struct test demo[] = {\n" 25664 " {1, 2, 3, 4, 5},\n" 25665 " {3, 4, 5},\n" 25666 " {6, 7, 8, 9, 10, 11, 12}\n" 25667 "};", 25668 Style); 25669 verifyFormat("struct test demo[] = {\n" 25670 " {1, 2, 3},\n" 25671 " {3, 4, 5},\n" 25672 " {6, 7, 8, 9, 10, 11, 12}\n" 25673 "};", 25674 Style); 25675 25676 verifyFormat("S{\n" 25677 " {},\n" 25678 " {},\n" 25679 " {a, b}\n" 25680 "};", 25681 Style); 25682 verifyFormat("S{\n" 25683 " {},\n" 25684 " {},\n" 25685 " {a, b},\n" 25686 "};", 25687 Style); 25688 verifyFormat("void foo() {\n" 25689 " auto thing = test{\n" 25690 " {\n" 25691 " {13}, {something}, // A\n" 25692 " }\n" 25693 " };\n" 25694 "}", 25695 "void foo() {\n" 25696 " auto thing = test{\n" 25697 " {\n" 25698 " {13},\n" 25699 " {something}, // A\n" 25700 " }\n" 25701 " };\n" 25702 "}", 25703 Style); 25704 } 25705 25706 TEST_F(FormatTest, AlignArrayOfStructuresRightAlignmentNonSquare) { 25707 auto Style = getLLVMStyle(); 25708 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 25709 Style.AlignConsecutiveAssignments.Enabled = true; 25710 Style.AlignConsecutiveDeclarations.Enabled = true; 25711 25712 // The AlignArray code is incorrect for non square Arrays and can cause 25713 // crashes, these tests assert that the array is not changed but will 25714 // also act as regression tests for when it is properly fixed 25715 verifyFormat("struct test demo[] = {\n" 25716 " {1, 2},\n" 25717 " {3, 4, 5},\n" 25718 " {6, 7, 8}\n" 25719 "};", 25720 Style); 25721 verifyFormat("struct test demo[] = {\n" 25722 " {1, 2, 3, 4, 5},\n" 25723 " {3, 4, 5},\n" 25724 " {6, 7, 8}\n" 25725 "};", 25726 Style); 25727 verifyFormat("struct test demo[] = {\n" 25728 " {1, 2, 3, 4, 5},\n" 25729 " {3, 4, 5},\n" 25730 " {6, 7, 8, 9, 10, 11, 12}\n" 25731 "};", 25732 Style); 25733 verifyFormat("struct test demo[] = {\n" 25734 " {1, 2, 3},\n" 25735 " {3, 4, 5},\n" 25736 " {6, 7, 8, 9, 10, 11, 12}\n" 25737 "};", 25738 Style); 25739 25740 verifyFormat("S{\n" 25741 " {},\n" 25742 " {},\n" 25743 " {a, b}\n" 25744 "};", 25745 Style); 25746 verifyFormat("S{\n" 25747 " {},\n" 25748 " {},\n" 25749 " {a, b},\n" 25750 "};", 25751 Style); 25752 verifyFormat("void foo() {\n" 25753 " auto thing = test{\n" 25754 " {\n" 25755 " {13}, {something}, // A\n" 25756 " }\n" 25757 " };\n" 25758 "}", 25759 "void foo() {\n" 25760 " auto thing = test{\n" 25761 " {\n" 25762 " {13},\n" 25763 " {something}, // A\n" 25764 " }\n" 25765 " };\n" 25766 "}", 25767 Style); 25768 } 25769 25770 TEST_F(FormatTest, FormatsVariableTemplates) { 25771 verifyFormat("inline bool var = is_integral_v<int> && is_signed_v<int>;"); 25772 verifyFormat("template <typename T> " 25773 "inline bool var = is_integral_v<T> && is_signed_v<T>;"); 25774 } 25775 25776 } // namespace 25777 } // namespace format 25778 } // namespace clang 25779