1 //===- unittest/Format/FormatTest.cpp - Formatting unit tests -------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "clang/Format/Format.h" 10 11 #include "../Tooling/ReplacementTest.h" 12 #include "FormatTestUtils.h" 13 14 #include "llvm/Support/Debug.h" 15 #include "llvm/Support/MemoryBuffer.h" 16 #include "gtest/gtest.h" 17 18 #define DEBUG_TYPE "format-test" 19 20 using clang::tooling::ReplacementTest; 21 using clang::tooling::toReplacements; 22 using testing::ScopedTrace; 23 24 namespace clang { 25 namespace format { 26 namespace { 27 28 FormatStyle getGoogleStyle() { return getGoogleStyle(FormatStyle::LK_Cpp); } 29 30 class FormatTest : public ::testing::Test { 31 protected: 32 enum StatusCheck { SC_ExpectComplete, SC_ExpectIncomplete, SC_DoNotCheck }; 33 34 std::string format(llvm::StringRef Code, 35 const FormatStyle &Style = getLLVMStyle(), 36 StatusCheck CheckComplete = SC_ExpectComplete) { 37 LLVM_DEBUG(llvm::errs() << "---\n"); 38 LLVM_DEBUG(llvm::errs() << Code << "\n\n"); 39 std::vector<tooling::Range> Ranges(1, tooling::Range(0, Code.size())); 40 FormattingAttemptStatus Status; 41 tooling::Replacements Replaces = 42 reformat(Style, Code, Ranges, "<stdin>", &Status); 43 if (CheckComplete != SC_DoNotCheck) { 44 bool ExpectedCompleteFormat = CheckComplete == SC_ExpectComplete; 45 EXPECT_EQ(ExpectedCompleteFormat, Status.FormatComplete) 46 << Code << "\n\n"; 47 } 48 ReplacementCount = Replaces.size(); 49 auto Result = applyAllReplacements(Code, Replaces); 50 EXPECT_TRUE(static_cast<bool>(Result)); 51 LLVM_DEBUG(llvm::errs() << "\n" << *Result << "\n\n"); 52 return *Result; 53 } 54 55 FormatStyle getStyleWithColumns(FormatStyle Style, unsigned ColumnLimit) { 56 Style.ColumnLimit = ColumnLimit; 57 return Style; 58 } 59 60 FormatStyle getLLVMStyleWithColumns(unsigned ColumnLimit) { 61 return getStyleWithColumns(getLLVMStyle(), ColumnLimit); 62 } 63 64 FormatStyle getGoogleStyleWithColumns(unsigned ColumnLimit) { 65 return getStyleWithColumns(getGoogleStyle(), ColumnLimit); 66 } 67 68 void _verifyFormat(const char *File, int Line, llvm::StringRef Expected, 69 llvm::StringRef Code, 70 const FormatStyle &Style = getLLVMStyle()) { 71 ScopedTrace t(File, Line, ::testing::Message() << Code.str()); 72 EXPECT_EQ(Expected.str(), format(Expected, Style)) 73 << "Expected code is not stable"; 74 EXPECT_EQ(Expected.str(), format(Code, Style)); 75 if (Style.Language == FormatStyle::LK_Cpp) { 76 // Objective-C++ is a superset of C++, so everything checked for C++ 77 // needs to be checked for Objective-C++ as well. 78 FormatStyle ObjCStyle = Style; 79 ObjCStyle.Language = FormatStyle::LK_ObjC; 80 EXPECT_EQ(Expected.str(), format(test::messUp(Code), ObjCStyle)); 81 } 82 } 83 84 void _verifyFormat(const char *File, int Line, llvm::StringRef Code, 85 const FormatStyle &Style = getLLVMStyle()) { 86 _verifyFormat(File, Line, Code, test::messUp(Code), Style); 87 } 88 89 void _verifyIncompleteFormat(const char *File, int Line, llvm::StringRef Code, 90 const FormatStyle &Style = getLLVMStyle()) { 91 ScopedTrace t(File, Line, ::testing::Message() << Code.str()); 92 EXPECT_EQ(Code.str(), 93 format(test::messUp(Code), Style, SC_ExpectIncomplete)); 94 } 95 96 void _verifyIndependentOfContext(const char *File, int Line, 97 llvm::StringRef Text, 98 const FormatStyle &Style = getLLVMStyle()) { 99 _verifyFormat(File, Line, Text, Style); 100 _verifyFormat(File, Line, llvm::Twine("void f() { " + Text + " }").str(), 101 Style); 102 } 103 104 /// \brief Verify that clang-format does not crash on the given input. 105 void verifyNoCrash(llvm::StringRef Code, 106 const FormatStyle &Style = getLLVMStyle()) { 107 format(Code, Style, SC_DoNotCheck); 108 } 109 110 int ReplacementCount; 111 }; 112 113 #define verifyIndependentOfContext(...) \ 114 _verifyIndependentOfContext(__FILE__, __LINE__, __VA_ARGS__) 115 #define verifyIncompleteFormat(...) \ 116 _verifyIncompleteFormat(__FILE__, __LINE__, __VA_ARGS__) 117 #define verifyFormat(...) _verifyFormat(__FILE__, __LINE__, __VA_ARGS__) 118 #define verifyGoogleFormat(Code) verifyFormat(Code, getGoogleStyle()) 119 120 TEST_F(FormatTest, MessUp) { 121 EXPECT_EQ("1 2 3", test::messUp("1 2 3")); 122 EXPECT_EQ("1 2 3\n", test::messUp("1\n2\n3\n")); 123 EXPECT_EQ("a\n//b\nc", test::messUp("a\n//b\nc")); 124 EXPECT_EQ("a\n#b\nc", test::messUp("a\n#b\nc")); 125 EXPECT_EQ("a\n#b c d\ne", test::messUp("a\n#b\\\nc\\\nd\ne")); 126 } 127 128 TEST_F(FormatTest, DefaultLLVMStyleIsCpp) { 129 EXPECT_EQ(FormatStyle::LK_Cpp, getLLVMStyle().Language); 130 } 131 132 TEST_F(FormatTest, LLVMStyleOverride) { 133 EXPECT_EQ(FormatStyle::LK_Proto, 134 getLLVMStyle(FormatStyle::LK_Proto).Language); 135 } 136 137 //===----------------------------------------------------------------------===// 138 // Basic function tests. 139 //===----------------------------------------------------------------------===// 140 141 TEST_F(FormatTest, DoesNotChangeCorrectlyFormattedCode) { 142 EXPECT_EQ(";", format(";")); 143 } 144 145 TEST_F(FormatTest, FormatsGlobalStatementsAt0) { 146 EXPECT_EQ("int i;", format(" int i;")); 147 EXPECT_EQ("\nint i;", format(" \n\t \v \f int i;")); 148 EXPECT_EQ("int i;\nint j;", format(" int i; int j;")); 149 EXPECT_EQ("int i;\nint j;", format(" int i;\n int j;")); 150 } 151 152 TEST_F(FormatTest, FormatsUnwrappedLinesAtFirstFormat) { 153 EXPECT_EQ("int i;", format("int\ni;")); 154 } 155 156 TEST_F(FormatTest, FormatsNestedBlockStatements) { 157 EXPECT_EQ("{\n {\n {}\n }\n}", format("{{{}}}")); 158 } 159 160 TEST_F(FormatTest, FormatsNestedCall) { 161 verifyFormat("Method(f1, f2(f3));"); 162 verifyFormat("Method(f1(f2, f3()));"); 163 verifyFormat("Method(f1(f2, (f3())));"); 164 } 165 166 TEST_F(FormatTest, NestedNameSpecifiers) { 167 verifyFormat("vector<::Type> v;"); 168 verifyFormat("::ns::SomeFunction(::ns::SomeOtherFunction())"); 169 verifyFormat("static constexpr bool Bar = decltype(bar())::value;"); 170 verifyFormat("static constexpr bool Bar = typeof(bar())::value;"); 171 verifyFormat("static constexpr bool Bar = __underlying_type(bar())::value;"); 172 verifyFormat("static constexpr bool Bar = _Atomic(bar())::value;"); 173 verifyFormat("bool a = 2 < ::SomeFunction();"); 174 verifyFormat("ALWAYS_INLINE ::std::string getName();"); 175 verifyFormat("some::string getName();"); 176 } 177 178 TEST_F(FormatTest, OnlyGeneratesNecessaryReplacements) { 179 EXPECT_EQ("if (a) {\n" 180 " f();\n" 181 "}", 182 format("if(a){f();}")); 183 EXPECT_EQ(4, ReplacementCount); 184 EXPECT_EQ("if (a) {\n" 185 " f();\n" 186 "}", 187 format("if (a) {\n" 188 " f();\n" 189 "}")); 190 EXPECT_EQ(0, ReplacementCount); 191 EXPECT_EQ("/*\r\n" 192 "\r\n" 193 "*/\r\n", 194 format("/*\r\n" 195 "\r\n" 196 "*/\r\n")); 197 EXPECT_EQ(0, ReplacementCount); 198 } 199 200 TEST_F(FormatTest, RemovesEmptyLines) { 201 EXPECT_EQ("class C {\n" 202 " int i;\n" 203 "};", 204 format("class C {\n" 205 " int i;\n" 206 "\n" 207 "};")); 208 209 // Don't remove empty lines at the start of namespaces or extern "C" blocks. 210 EXPECT_EQ("namespace N {\n" 211 "\n" 212 "int i;\n" 213 "}", 214 format("namespace N {\n" 215 "\n" 216 "int i;\n" 217 "}", 218 getGoogleStyle())); 219 EXPECT_EQ("/* something */ namespace N {\n" 220 "\n" 221 "int i;\n" 222 "}", 223 format("/* something */ namespace N {\n" 224 "\n" 225 "int i;\n" 226 "}", 227 getGoogleStyle())); 228 EXPECT_EQ("inline namespace N {\n" 229 "\n" 230 "int i;\n" 231 "}", 232 format("inline namespace N {\n" 233 "\n" 234 "int i;\n" 235 "}", 236 getGoogleStyle())); 237 EXPECT_EQ("/* something */ inline namespace N {\n" 238 "\n" 239 "int i;\n" 240 "}", 241 format("/* something */ inline namespace N {\n" 242 "\n" 243 "int i;\n" 244 "}", 245 getGoogleStyle())); 246 EXPECT_EQ("export namespace N {\n" 247 "\n" 248 "int i;\n" 249 "}", 250 format("export namespace N {\n" 251 "\n" 252 "int i;\n" 253 "}", 254 getGoogleStyle())); 255 EXPECT_EQ("extern /**/ \"C\" /**/ {\n" 256 "\n" 257 "int i;\n" 258 "}", 259 format("extern /**/ \"C\" /**/ {\n" 260 "\n" 261 "int i;\n" 262 "}", 263 getGoogleStyle())); 264 265 auto CustomStyle = getLLVMStyle(); 266 CustomStyle.BreakBeforeBraces = FormatStyle::BS_Custom; 267 CustomStyle.BraceWrapping.AfterNamespace = true; 268 CustomStyle.KeepEmptyLinesAtTheStartOfBlocks = false; 269 EXPECT_EQ("namespace N\n" 270 "{\n" 271 "\n" 272 "int i;\n" 273 "}", 274 format("namespace N\n" 275 "{\n" 276 "\n" 277 "\n" 278 "int i;\n" 279 "}", 280 CustomStyle)); 281 EXPECT_EQ("/* something */ namespace N\n" 282 "{\n" 283 "\n" 284 "int i;\n" 285 "}", 286 format("/* something */ namespace N {\n" 287 "\n" 288 "\n" 289 "int i;\n" 290 "}", 291 CustomStyle)); 292 EXPECT_EQ("inline namespace N\n" 293 "{\n" 294 "\n" 295 "int i;\n" 296 "}", 297 format("inline namespace N\n" 298 "{\n" 299 "\n" 300 "\n" 301 "int i;\n" 302 "}", 303 CustomStyle)); 304 EXPECT_EQ("/* something */ inline namespace N\n" 305 "{\n" 306 "\n" 307 "int i;\n" 308 "}", 309 format("/* something */ inline namespace N\n" 310 "{\n" 311 "\n" 312 "int i;\n" 313 "}", 314 CustomStyle)); 315 EXPECT_EQ("export namespace N\n" 316 "{\n" 317 "\n" 318 "int i;\n" 319 "}", 320 format("export namespace N\n" 321 "{\n" 322 "\n" 323 "int i;\n" 324 "}", 325 CustomStyle)); 326 EXPECT_EQ("namespace a\n" 327 "{\n" 328 "namespace b\n" 329 "{\n" 330 "\n" 331 "class AA {};\n" 332 "\n" 333 "} // namespace b\n" 334 "} // namespace a\n", 335 format("namespace a\n" 336 "{\n" 337 "namespace b\n" 338 "{\n" 339 "\n" 340 "\n" 341 "class AA {};\n" 342 "\n" 343 "\n" 344 "}\n" 345 "}\n", 346 CustomStyle)); 347 EXPECT_EQ("namespace A /* comment */\n" 348 "{\n" 349 "class B {}\n" 350 "} // namespace A", 351 format("namespace A /* comment */ { class B {} }", CustomStyle)); 352 EXPECT_EQ("namespace A\n" 353 "{ /* comment */\n" 354 "class B {}\n" 355 "} // namespace A", 356 format("namespace A {/* comment */ class B {} }", CustomStyle)); 357 EXPECT_EQ("namespace A\n" 358 "{ /* comment */\n" 359 "\n" 360 "class B {}\n" 361 "\n" 362 "" 363 "} // namespace A", 364 format("namespace A { /* comment */\n" 365 "\n" 366 "\n" 367 "class B {}\n" 368 "\n" 369 "\n" 370 "}", 371 CustomStyle)); 372 EXPECT_EQ("namespace A /* comment */\n" 373 "{\n" 374 "\n" 375 "class B {}\n" 376 "\n" 377 "} // namespace A", 378 format("namespace A/* comment */ {\n" 379 "\n" 380 "\n" 381 "class B {}\n" 382 "\n" 383 "\n" 384 "}", 385 CustomStyle)); 386 387 // ...but do keep inlining and removing empty lines for non-block extern "C" 388 // functions. 389 verifyFormat("extern \"C\" int f() { return 42; }", getGoogleStyle()); 390 EXPECT_EQ("extern \"C\" int f() {\n" 391 " int i = 42;\n" 392 " return i;\n" 393 "}", 394 format("extern \"C\" int f() {\n" 395 "\n" 396 " int i = 42;\n" 397 " return i;\n" 398 "}", 399 getGoogleStyle())); 400 401 // Remove empty lines at the beginning and end of blocks. 402 EXPECT_EQ("void f() {\n" 403 "\n" 404 " if (a) {\n" 405 "\n" 406 " f();\n" 407 " }\n" 408 "}", 409 format("void f() {\n" 410 "\n" 411 " if (a) {\n" 412 "\n" 413 " f();\n" 414 "\n" 415 " }\n" 416 "\n" 417 "}", 418 getLLVMStyle())); 419 EXPECT_EQ("void f() {\n" 420 " if (a) {\n" 421 " f();\n" 422 " }\n" 423 "}", 424 format("void f() {\n" 425 "\n" 426 " if (a) {\n" 427 "\n" 428 " f();\n" 429 "\n" 430 " }\n" 431 "\n" 432 "}", 433 getGoogleStyle())); 434 435 // Don't remove empty lines in more complex control statements. 436 EXPECT_EQ("void f() {\n" 437 " if (a) {\n" 438 " f();\n" 439 "\n" 440 " } else if (b) {\n" 441 " f();\n" 442 " }\n" 443 "}", 444 format("void f() {\n" 445 " if (a) {\n" 446 " f();\n" 447 "\n" 448 " } else if (b) {\n" 449 " f();\n" 450 "\n" 451 " }\n" 452 "\n" 453 "}")); 454 455 // Don't remove empty lines before namespace endings. 456 FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle(); 457 LLVMWithNoNamespaceFix.FixNamespaceComments = false; 458 EXPECT_EQ("namespace {\n" 459 "int i;\n" 460 "\n" 461 "}", 462 format("namespace {\n" 463 "int i;\n" 464 "\n" 465 "}", 466 LLVMWithNoNamespaceFix)); 467 EXPECT_EQ("namespace {\n" 468 "int i;\n" 469 "}", 470 format("namespace {\n" 471 "int i;\n" 472 "}", 473 LLVMWithNoNamespaceFix)); 474 EXPECT_EQ("namespace {\n" 475 "int i;\n" 476 "\n" 477 "};", 478 format("namespace {\n" 479 "int i;\n" 480 "\n" 481 "};", 482 LLVMWithNoNamespaceFix)); 483 EXPECT_EQ("namespace {\n" 484 "int i;\n" 485 "};", 486 format("namespace {\n" 487 "int i;\n" 488 "};", 489 LLVMWithNoNamespaceFix)); 490 EXPECT_EQ("namespace {\n" 491 "int i;\n" 492 "\n" 493 "}", 494 format("namespace {\n" 495 "int i;\n" 496 "\n" 497 "}")); 498 EXPECT_EQ("namespace {\n" 499 "int i;\n" 500 "\n" 501 "} // namespace", 502 format("namespace {\n" 503 "int i;\n" 504 "\n" 505 "} // namespace")); 506 507 FormatStyle Style = getLLVMStyle(); 508 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 509 Style.MaxEmptyLinesToKeep = 2; 510 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 511 Style.BraceWrapping.AfterClass = true; 512 Style.BraceWrapping.AfterFunction = true; 513 Style.KeepEmptyLinesAtTheStartOfBlocks = false; 514 515 EXPECT_EQ("class Foo\n" 516 "{\n" 517 " Foo() {}\n" 518 "\n" 519 " void funk() {}\n" 520 "};", 521 format("class Foo\n" 522 "{\n" 523 " Foo()\n" 524 " {\n" 525 " }\n" 526 "\n" 527 " void funk() {}\n" 528 "};", 529 Style)); 530 } 531 532 TEST_F(FormatTest, RecognizesBinaryOperatorKeywords) { 533 verifyFormat("x = (a) and (b);"); 534 verifyFormat("x = (a) or (b);"); 535 verifyFormat("x = (a) bitand (b);"); 536 verifyFormat("x = (a) bitor (b);"); 537 verifyFormat("x = (a) not_eq (b);"); 538 verifyFormat("x = (a) and_eq (b);"); 539 verifyFormat("x = (a) or_eq (b);"); 540 verifyFormat("x = (a) xor (b);"); 541 } 542 543 TEST_F(FormatTest, RecognizesUnaryOperatorKeywords) { 544 verifyFormat("x = compl(a);"); 545 verifyFormat("x = not(a);"); 546 verifyFormat("x = bitand(a);"); 547 // Unary operator must not be merged with the next identifier 548 verifyFormat("x = compl a;"); 549 verifyFormat("x = not a;"); 550 verifyFormat("x = bitand a;"); 551 } 552 553 //===----------------------------------------------------------------------===// 554 // Tests for control statements. 555 //===----------------------------------------------------------------------===// 556 557 TEST_F(FormatTest, FormatIfWithoutCompoundStatement) { 558 verifyFormat("if (true)\n f();\ng();"); 559 verifyFormat("if (a)\n if (b)\n if (c)\n g();\nh();"); 560 verifyFormat("if (a)\n if (b) {\n f();\n }\ng();"); 561 verifyFormat("if constexpr (true)\n" 562 " f();\ng();"); 563 verifyFormat("if CONSTEXPR (true)\n" 564 " f();\ng();"); 565 verifyFormat("if constexpr (a)\n" 566 " if constexpr (b)\n" 567 " if constexpr (c)\n" 568 " g();\n" 569 "h();"); 570 verifyFormat("if CONSTEXPR (a)\n" 571 " if CONSTEXPR (b)\n" 572 " if CONSTEXPR (c)\n" 573 " g();\n" 574 "h();"); 575 verifyFormat("if constexpr (a)\n" 576 " if constexpr (b) {\n" 577 " f();\n" 578 " }\n" 579 "g();"); 580 verifyFormat("if CONSTEXPR (a)\n" 581 " if CONSTEXPR (b) {\n" 582 " f();\n" 583 " }\n" 584 "g();"); 585 586 verifyFormat("if consteval {\n}"); 587 verifyFormat("if !consteval {\n}"); 588 verifyFormat("if not consteval {\n}"); 589 verifyFormat("if consteval {\n} else {\n}"); 590 verifyFormat("if !consteval {\n} else {\n}"); 591 verifyFormat("if consteval {\n" 592 " f();\n" 593 "}"); 594 verifyFormat("if !consteval {\n" 595 " f();\n" 596 "}"); 597 verifyFormat("if consteval {\n" 598 " f();\n" 599 "} else {\n" 600 " g();\n" 601 "}"); 602 verifyFormat("if CONSTEVAL {\n" 603 " f();\n" 604 "}"); 605 verifyFormat("if !CONSTEVAL {\n" 606 " f();\n" 607 "}"); 608 609 verifyFormat("if (a)\n" 610 " g();"); 611 verifyFormat("if (a) {\n" 612 " g()\n" 613 "};"); 614 verifyFormat("if (a)\n" 615 " g();\n" 616 "else\n" 617 " g();"); 618 verifyFormat("if (a) {\n" 619 " g();\n" 620 "} else\n" 621 " g();"); 622 verifyFormat("if (a)\n" 623 " g();\n" 624 "else {\n" 625 " g();\n" 626 "}"); 627 verifyFormat("if (a) {\n" 628 " g();\n" 629 "} else {\n" 630 " g();\n" 631 "}"); 632 verifyFormat("if (a)\n" 633 " g();\n" 634 "else if (b)\n" 635 " g();\n" 636 "else\n" 637 " g();"); 638 verifyFormat("if (a) {\n" 639 " g();\n" 640 "} else if (b)\n" 641 " g();\n" 642 "else\n" 643 " g();"); 644 verifyFormat("if (a)\n" 645 " g();\n" 646 "else if (b) {\n" 647 " g();\n" 648 "} else\n" 649 " g();"); 650 verifyFormat("if (a)\n" 651 " g();\n" 652 "else if (b)\n" 653 " g();\n" 654 "else {\n" 655 " g();\n" 656 "}"); 657 verifyFormat("if (a)\n" 658 " g();\n" 659 "else if (b) {\n" 660 " g();\n" 661 "} else {\n" 662 " g();\n" 663 "}"); 664 verifyFormat("if (a) {\n" 665 " g();\n" 666 "} else if (b) {\n" 667 " g();\n" 668 "} else {\n" 669 " g();\n" 670 "}"); 671 672 FormatStyle AllowsMergedIf = getLLVMStyle(); 673 AllowsMergedIf.IfMacros.push_back("MYIF"); 674 AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left; 675 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 676 FormatStyle::SIS_WithoutElse; 677 verifyFormat("if (a)\n" 678 " // comment\n" 679 " f();", 680 AllowsMergedIf); 681 verifyFormat("{\n" 682 " if (a)\n" 683 " label:\n" 684 " f();\n" 685 "}", 686 AllowsMergedIf); 687 verifyFormat("#define A \\\n" 688 " if (a) \\\n" 689 " label: \\\n" 690 " f()", 691 AllowsMergedIf); 692 verifyFormat("if (a)\n" 693 " ;", 694 AllowsMergedIf); 695 verifyFormat("if (a)\n" 696 " if (b) return;", 697 AllowsMergedIf); 698 699 verifyFormat("if (a) // Can't merge this\n" 700 " f();\n", 701 AllowsMergedIf); 702 verifyFormat("if (a) /* still don't merge */\n" 703 " f();", 704 AllowsMergedIf); 705 verifyFormat("if (a) { // Never merge this\n" 706 " f();\n" 707 "}", 708 AllowsMergedIf); 709 verifyFormat("if (a) { /* Never merge this */\n" 710 " f();\n" 711 "}", 712 AllowsMergedIf); 713 verifyFormat("MYIF (a)\n" 714 " // comment\n" 715 " f();", 716 AllowsMergedIf); 717 verifyFormat("{\n" 718 " MYIF (a)\n" 719 " label:\n" 720 " f();\n" 721 "}", 722 AllowsMergedIf); 723 verifyFormat("#define A \\\n" 724 " MYIF (a) \\\n" 725 " label: \\\n" 726 " f()", 727 AllowsMergedIf); 728 verifyFormat("MYIF (a)\n" 729 " ;", 730 AllowsMergedIf); 731 verifyFormat("MYIF (a)\n" 732 " MYIF (b) return;", 733 AllowsMergedIf); 734 735 verifyFormat("MYIF (a) // Can't merge this\n" 736 " f();\n", 737 AllowsMergedIf); 738 verifyFormat("MYIF (a) /* still don't merge */\n" 739 " f();", 740 AllowsMergedIf); 741 verifyFormat("MYIF (a) { // Never merge this\n" 742 " f();\n" 743 "}", 744 AllowsMergedIf); 745 verifyFormat("MYIF (a) { /* Never merge this */\n" 746 " f();\n" 747 "}", 748 AllowsMergedIf); 749 750 AllowsMergedIf.ColumnLimit = 14; 751 // Where line-lengths matter, a 2-letter synonym that maintains line length. 752 // Not IF to avoid any confusion that IF is somehow special. 753 AllowsMergedIf.IfMacros.push_back("FI"); 754 verifyFormat("if (a) return;", AllowsMergedIf); 755 verifyFormat("if (aaaaaaaaa)\n" 756 " return;", 757 AllowsMergedIf); 758 verifyFormat("FI (a) return;", AllowsMergedIf); 759 verifyFormat("FI (aaaaaaaaa)\n" 760 " return;", 761 AllowsMergedIf); 762 763 AllowsMergedIf.ColumnLimit = 13; 764 verifyFormat("if (a)\n return;", AllowsMergedIf); 765 verifyFormat("FI (a)\n return;", AllowsMergedIf); 766 767 FormatStyle AllowsMergedIfElse = getLLVMStyle(); 768 AllowsMergedIfElse.IfMacros.push_back("MYIF"); 769 AllowsMergedIfElse.AllowShortIfStatementsOnASingleLine = 770 FormatStyle::SIS_AllIfsAndElse; 771 verifyFormat("if (a)\n" 772 " // comment\n" 773 " f();\n" 774 "else\n" 775 " // comment\n" 776 " f();", 777 AllowsMergedIfElse); 778 verifyFormat("{\n" 779 " if (a)\n" 780 " label:\n" 781 " f();\n" 782 " else\n" 783 " label:\n" 784 " f();\n" 785 "}", 786 AllowsMergedIfElse); 787 verifyFormat("if (a)\n" 788 " ;\n" 789 "else\n" 790 " ;", 791 AllowsMergedIfElse); 792 verifyFormat("if (a) {\n" 793 "} else {\n" 794 "}", 795 AllowsMergedIfElse); 796 verifyFormat("if (a) return;\n" 797 "else if (b) return;\n" 798 "else return;", 799 AllowsMergedIfElse); 800 verifyFormat("if (a) {\n" 801 "} else return;", 802 AllowsMergedIfElse); 803 verifyFormat("if (a) {\n" 804 "} else if (b) return;\n" 805 "else return;", 806 AllowsMergedIfElse); 807 verifyFormat("if (a) return;\n" 808 "else if (b) {\n" 809 "} else return;", 810 AllowsMergedIfElse); 811 verifyFormat("if (a)\n" 812 " if (b) return;\n" 813 " else return;", 814 AllowsMergedIfElse); 815 verifyFormat("if constexpr (a)\n" 816 " if constexpr (b) return;\n" 817 " else if constexpr (c) return;\n" 818 " else return;", 819 AllowsMergedIfElse); 820 verifyFormat("MYIF (a)\n" 821 " // comment\n" 822 " f();\n" 823 "else\n" 824 " // comment\n" 825 " f();", 826 AllowsMergedIfElse); 827 verifyFormat("{\n" 828 " MYIF (a)\n" 829 " label:\n" 830 " f();\n" 831 " else\n" 832 " label:\n" 833 " f();\n" 834 "}", 835 AllowsMergedIfElse); 836 verifyFormat("MYIF (a)\n" 837 " ;\n" 838 "else\n" 839 " ;", 840 AllowsMergedIfElse); 841 verifyFormat("MYIF (a) {\n" 842 "} else {\n" 843 "}", 844 AllowsMergedIfElse); 845 verifyFormat("MYIF (a) return;\n" 846 "else MYIF (b) return;\n" 847 "else return;", 848 AllowsMergedIfElse); 849 verifyFormat("MYIF (a) {\n" 850 "} else return;", 851 AllowsMergedIfElse); 852 verifyFormat("MYIF (a) {\n" 853 "} else MYIF (b) return;\n" 854 "else return;", 855 AllowsMergedIfElse); 856 verifyFormat("MYIF (a) return;\n" 857 "else MYIF (b) {\n" 858 "} else return;", 859 AllowsMergedIfElse); 860 verifyFormat("MYIF (a)\n" 861 " MYIF (b) return;\n" 862 " else return;", 863 AllowsMergedIfElse); 864 verifyFormat("MYIF constexpr (a)\n" 865 " MYIF constexpr (b) return;\n" 866 " else MYIF constexpr (c) return;\n" 867 " else return;", 868 AllowsMergedIfElse); 869 } 870 871 TEST_F(FormatTest, FormatIfWithoutCompoundStatementButElseWith) { 872 FormatStyle AllowsMergedIf = getLLVMStyle(); 873 AllowsMergedIf.IfMacros.push_back("MYIF"); 874 AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left; 875 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 876 FormatStyle::SIS_WithoutElse; 877 verifyFormat("if (a)\n" 878 " f();\n" 879 "else {\n" 880 " g();\n" 881 "}", 882 AllowsMergedIf); 883 verifyFormat("if (a)\n" 884 " f();\n" 885 "else\n" 886 " g();\n", 887 AllowsMergedIf); 888 889 verifyFormat("if (a) g();", AllowsMergedIf); 890 verifyFormat("if (a) {\n" 891 " g()\n" 892 "};", 893 AllowsMergedIf); 894 verifyFormat("if (a)\n" 895 " g();\n" 896 "else\n" 897 " g();", 898 AllowsMergedIf); 899 verifyFormat("if (a) {\n" 900 " g();\n" 901 "} else\n" 902 " g();", 903 AllowsMergedIf); 904 verifyFormat("if (a)\n" 905 " g();\n" 906 "else {\n" 907 " g();\n" 908 "}", 909 AllowsMergedIf); 910 verifyFormat("if (a) {\n" 911 " g();\n" 912 "} else {\n" 913 " g();\n" 914 "}", 915 AllowsMergedIf); 916 verifyFormat("if (a)\n" 917 " g();\n" 918 "else if (b)\n" 919 " g();\n" 920 "else\n" 921 " g();", 922 AllowsMergedIf); 923 verifyFormat("if (a) {\n" 924 " g();\n" 925 "} else if (b)\n" 926 " g();\n" 927 "else\n" 928 " g();", 929 AllowsMergedIf); 930 verifyFormat("if (a)\n" 931 " g();\n" 932 "else if (b) {\n" 933 " g();\n" 934 "} else\n" 935 " g();", 936 AllowsMergedIf); 937 verifyFormat("if (a)\n" 938 " g();\n" 939 "else if (b)\n" 940 " g();\n" 941 "else {\n" 942 " g();\n" 943 "}", 944 AllowsMergedIf); 945 verifyFormat("if (a)\n" 946 " g();\n" 947 "else if (b) {\n" 948 " g();\n" 949 "} else {\n" 950 " g();\n" 951 "}", 952 AllowsMergedIf); 953 verifyFormat("if (a) {\n" 954 " g();\n" 955 "} else if (b) {\n" 956 " g();\n" 957 "} else {\n" 958 " g();\n" 959 "}", 960 AllowsMergedIf); 961 verifyFormat("MYIF (a)\n" 962 " f();\n" 963 "else {\n" 964 " g();\n" 965 "}", 966 AllowsMergedIf); 967 verifyFormat("MYIF (a)\n" 968 " f();\n" 969 "else\n" 970 " g();\n", 971 AllowsMergedIf); 972 973 verifyFormat("MYIF (a) g();", AllowsMergedIf); 974 verifyFormat("MYIF (a) {\n" 975 " g()\n" 976 "};", 977 AllowsMergedIf); 978 verifyFormat("MYIF (a)\n" 979 " g();\n" 980 "else\n" 981 " g();", 982 AllowsMergedIf); 983 verifyFormat("MYIF (a) {\n" 984 " g();\n" 985 "} else\n" 986 " g();", 987 AllowsMergedIf); 988 verifyFormat("MYIF (a)\n" 989 " g();\n" 990 "else {\n" 991 " g();\n" 992 "}", 993 AllowsMergedIf); 994 verifyFormat("MYIF (a) {\n" 995 " g();\n" 996 "} else {\n" 997 " g();\n" 998 "}", 999 AllowsMergedIf); 1000 verifyFormat("MYIF (a)\n" 1001 " g();\n" 1002 "else MYIF (b)\n" 1003 " g();\n" 1004 "else\n" 1005 " g();", 1006 AllowsMergedIf); 1007 verifyFormat("MYIF (a)\n" 1008 " g();\n" 1009 "else if (b)\n" 1010 " g();\n" 1011 "else\n" 1012 " g();", 1013 AllowsMergedIf); 1014 verifyFormat("MYIF (a) {\n" 1015 " g();\n" 1016 "} else MYIF (b)\n" 1017 " g();\n" 1018 "else\n" 1019 " g();", 1020 AllowsMergedIf); 1021 verifyFormat("MYIF (a) {\n" 1022 " g();\n" 1023 "} else if (b)\n" 1024 " g();\n" 1025 "else\n" 1026 " g();", 1027 AllowsMergedIf); 1028 verifyFormat("MYIF (a)\n" 1029 " g();\n" 1030 "else MYIF (b) {\n" 1031 " g();\n" 1032 "} else\n" 1033 " g();", 1034 AllowsMergedIf); 1035 verifyFormat("MYIF (a)\n" 1036 " g();\n" 1037 "else if (b) {\n" 1038 " g();\n" 1039 "} else\n" 1040 " g();", 1041 AllowsMergedIf); 1042 verifyFormat("MYIF (a)\n" 1043 " g();\n" 1044 "else MYIF (b)\n" 1045 " g();\n" 1046 "else {\n" 1047 " g();\n" 1048 "}", 1049 AllowsMergedIf); 1050 verifyFormat("MYIF (a)\n" 1051 " g();\n" 1052 "else if (b)\n" 1053 " g();\n" 1054 "else {\n" 1055 " g();\n" 1056 "}", 1057 AllowsMergedIf); 1058 verifyFormat("MYIF (a)\n" 1059 " g();\n" 1060 "else MYIF (b) {\n" 1061 " g();\n" 1062 "} else {\n" 1063 " g();\n" 1064 "}", 1065 AllowsMergedIf); 1066 verifyFormat("MYIF (a)\n" 1067 " g();\n" 1068 "else if (b) {\n" 1069 " g();\n" 1070 "} else {\n" 1071 " g();\n" 1072 "}", 1073 AllowsMergedIf); 1074 verifyFormat("MYIF (a) {\n" 1075 " g();\n" 1076 "} else MYIF (b) {\n" 1077 " g();\n" 1078 "} else {\n" 1079 " g();\n" 1080 "}", 1081 AllowsMergedIf); 1082 verifyFormat("MYIF (a) {\n" 1083 " g();\n" 1084 "} else if (b) {\n" 1085 " g();\n" 1086 "} else {\n" 1087 " g();\n" 1088 "}", 1089 AllowsMergedIf); 1090 1091 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 1092 FormatStyle::SIS_OnlyFirstIf; 1093 1094 verifyFormat("if (a) f();\n" 1095 "else {\n" 1096 " g();\n" 1097 "}", 1098 AllowsMergedIf); 1099 verifyFormat("if (a) f();\n" 1100 "else {\n" 1101 " if (a) f();\n" 1102 " else {\n" 1103 " g();\n" 1104 " }\n" 1105 " g();\n" 1106 "}", 1107 AllowsMergedIf); 1108 1109 verifyFormat("if (a) g();", AllowsMergedIf); 1110 verifyFormat("if (a) {\n" 1111 " g()\n" 1112 "};", 1113 AllowsMergedIf); 1114 verifyFormat("if (a) g();\n" 1115 "else\n" 1116 " g();", 1117 AllowsMergedIf); 1118 verifyFormat("if (a) {\n" 1119 " g();\n" 1120 "} else\n" 1121 " g();", 1122 AllowsMergedIf); 1123 verifyFormat("if (a) g();\n" 1124 "else {\n" 1125 " g();\n" 1126 "}", 1127 AllowsMergedIf); 1128 verifyFormat("if (a) {\n" 1129 " g();\n" 1130 "} else {\n" 1131 " g();\n" 1132 "}", 1133 AllowsMergedIf); 1134 verifyFormat("if (a) g();\n" 1135 "else if (b)\n" 1136 " g();\n" 1137 "else\n" 1138 " g();", 1139 AllowsMergedIf); 1140 verifyFormat("if (a) {\n" 1141 " g();\n" 1142 "} else if (b)\n" 1143 " g();\n" 1144 "else\n" 1145 " g();", 1146 AllowsMergedIf); 1147 verifyFormat("if (a) g();\n" 1148 "else if (b) {\n" 1149 " g();\n" 1150 "} else\n" 1151 " g();", 1152 AllowsMergedIf); 1153 verifyFormat("if (a) g();\n" 1154 "else if (b)\n" 1155 " g();\n" 1156 "else {\n" 1157 " g();\n" 1158 "}", 1159 AllowsMergedIf); 1160 verifyFormat("if (a) g();\n" 1161 "else if (b) {\n" 1162 " g();\n" 1163 "} else {\n" 1164 " g();\n" 1165 "}", 1166 AllowsMergedIf); 1167 verifyFormat("if (a) {\n" 1168 " g();\n" 1169 "} else if (b) {\n" 1170 " g();\n" 1171 "} else {\n" 1172 " g();\n" 1173 "}", 1174 AllowsMergedIf); 1175 verifyFormat("MYIF (a) f();\n" 1176 "else {\n" 1177 " g();\n" 1178 "}", 1179 AllowsMergedIf); 1180 verifyFormat("MYIF (a) f();\n" 1181 "else {\n" 1182 " if (a) f();\n" 1183 " else {\n" 1184 " g();\n" 1185 " }\n" 1186 " g();\n" 1187 "}", 1188 AllowsMergedIf); 1189 1190 verifyFormat("MYIF (a) g();", AllowsMergedIf); 1191 verifyFormat("MYIF (a) {\n" 1192 " g()\n" 1193 "};", 1194 AllowsMergedIf); 1195 verifyFormat("MYIF (a) g();\n" 1196 "else\n" 1197 " g();", 1198 AllowsMergedIf); 1199 verifyFormat("MYIF (a) {\n" 1200 " g();\n" 1201 "} else\n" 1202 " g();", 1203 AllowsMergedIf); 1204 verifyFormat("MYIF (a) g();\n" 1205 "else {\n" 1206 " g();\n" 1207 "}", 1208 AllowsMergedIf); 1209 verifyFormat("MYIF (a) {\n" 1210 " g();\n" 1211 "} else {\n" 1212 " g();\n" 1213 "}", 1214 AllowsMergedIf); 1215 verifyFormat("MYIF (a) g();\n" 1216 "else MYIF (b)\n" 1217 " g();\n" 1218 "else\n" 1219 " g();", 1220 AllowsMergedIf); 1221 verifyFormat("MYIF (a) g();\n" 1222 "else if (b)\n" 1223 " g();\n" 1224 "else\n" 1225 " g();", 1226 AllowsMergedIf); 1227 verifyFormat("MYIF (a) {\n" 1228 " g();\n" 1229 "} else MYIF (b)\n" 1230 " g();\n" 1231 "else\n" 1232 " g();", 1233 AllowsMergedIf); 1234 verifyFormat("MYIF (a) {\n" 1235 " g();\n" 1236 "} else if (b)\n" 1237 " g();\n" 1238 "else\n" 1239 " g();", 1240 AllowsMergedIf); 1241 verifyFormat("MYIF (a) g();\n" 1242 "else MYIF (b) {\n" 1243 " g();\n" 1244 "} else\n" 1245 " g();", 1246 AllowsMergedIf); 1247 verifyFormat("MYIF (a) g();\n" 1248 "else if (b) {\n" 1249 " g();\n" 1250 "} else\n" 1251 " g();", 1252 AllowsMergedIf); 1253 verifyFormat("MYIF (a) g();\n" 1254 "else MYIF (b)\n" 1255 " g();\n" 1256 "else {\n" 1257 " g();\n" 1258 "}", 1259 AllowsMergedIf); 1260 verifyFormat("MYIF (a) g();\n" 1261 "else if (b)\n" 1262 " g();\n" 1263 "else {\n" 1264 " g();\n" 1265 "}", 1266 AllowsMergedIf); 1267 verifyFormat("MYIF (a) g();\n" 1268 "else MYIF (b) {\n" 1269 " g();\n" 1270 "} else {\n" 1271 " g();\n" 1272 "}", 1273 AllowsMergedIf); 1274 verifyFormat("MYIF (a) g();\n" 1275 "else if (b) {\n" 1276 " g();\n" 1277 "} else {\n" 1278 " g();\n" 1279 "}", 1280 AllowsMergedIf); 1281 verifyFormat("MYIF (a) {\n" 1282 " g();\n" 1283 "} else MYIF (b) {\n" 1284 " g();\n" 1285 "} else {\n" 1286 " g();\n" 1287 "}", 1288 AllowsMergedIf); 1289 verifyFormat("MYIF (a) {\n" 1290 " g();\n" 1291 "} else if (b) {\n" 1292 " g();\n" 1293 "} else {\n" 1294 " g();\n" 1295 "}", 1296 AllowsMergedIf); 1297 1298 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 1299 FormatStyle::SIS_AllIfsAndElse; 1300 1301 verifyFormat("if (a) f();\n" 1302 "else {\n" 1303 " g();\n" 1304 "}", 1305 AllowsMergedIf); 1306 verifyFormat("if (a) f();\n" 1307 "else {\n" 1308 " if (a) f();\n" 1309 " else {\n" 1310 " g();\n" 1311 " }\n" 1312 " g();\n" 1313 "}", 1314 AllowsMergedIf); 1315 1316 verifyFormat("if (a) g();", AllowsMergedIf); 1317 verifyFormat("if (a) {\n" 1318 " g()\n" 1319 "};", 1320 AllowsMergedIf); 1321 verifyFormat("if (a) g();\n" 1322 "else g();", 1323 AllowsMergedIf); 1324 verifyFormat("if (a) {\n" 1325 " g();\n" 1326 "} else g();", 1327 AllowsMergedIf); 1328 verifyFormat("if (a) g();\n" 1329 "else {\n" 1330 " g();\n" 1331 "}", 1332 AllowsMergedIf); 1333 verifyFormat("if (a) {\n" 1334 " g();\n" 1335 "} else {\n" 1336 " g();\n" 1337 "}", 1338 AllowsMergedIf); 1339 verifyFormat("if (a) g();\n" 1340 "else if (b) g();\n" 1341 "else g();", 1342 AllowsMergedIf); 1343 verifyFormat("if (a) {\n" 1344 " g();\n" 1345 "} else if (b) g();\n" 1346 "else g();", 1347 AllowsMergedIf); 1348 verifyFormat("if (a) g();\n" 1349 "else if (b) {\n" 1350 " g();\n" 1351 "} else g();", 1352 AllowsMergedIf); 1353 verifyFormat("if (a) g();\n" 1354 "else if (b) g();\n" 1355 "else {\n" 1356 " g();\n" 1357 "}", 1358 AllowsMergedIf); 1359 verifyFormat("if (a) g();\n" 1360 "else if (b) {\n" 1361 " g();\n" 1362 "} else {\n" 1363 " g();\n" 1364 "}", 1365 AllowsMergedIf); 1366 verifyFormat("if (a) {\n" 1367 " g();\n" 1368 "} else if (b) {\n" 1369 " g();\n" 1370 "} else {\n" 1371 " g();\n" 1372 "}", 1373 AllowsMergedIf); 1374 verifyFormat("MYIF (a) f();\n" 1375 "else {\n" 1376 " g();\n" 1377 "}", 1378 AllowsMergedIf); 1379 verifyFormat("MYIF (a) f();\n" 1380 "else {\n" 1381 " if (a) f();\n" 1382 " else {\n" 1383 " g();\n" 1384 " }\n" 1385 " g();\n" 1386 "}", 1387 AllowsMergedIf); 1388 1389 verifyFormat("MYIF (a) g();", AllowsMergedIf); 1390 verifyFormat("MYIF (a) {\n" 1391 " g()\n" 1392 "};", 1393 AllowsMergedIf); 1394 verifyFormat("MYIF (a) g();\n" 1395 "else g();", 1396 AllowsMergedIf); 1397 verifyFormat("MYIF (a) {\n" 1398 " g();\n" 1399 "} else g();", 1400 AllowsMergedIf); 1401 verifyFormat("MYIF (a) g();\n" 1402 "else {\n" 1403 " g();\n" 1404 "}", 1405 AllowsMergedIf); 1406 verifyFormat("MYIF (a) {\n" 1407 " g();\n" 1408 "} else {\n" 1409 " g();\n" 1410 "}", 1411 AllowsMergedIf); 1412 verifyFormat("MYIF (a) g();\n" 1413 "else MYIF (b) g();\n" 1414 "else g();", 1415 AllowsMergedIf); 1416 verifyFormat("MYIF (a) g();\n" 1417 "else if (b) g();\n" 1418 "else g();", 1419 AllowsMergedIf); 1420 verifyFormat("MYIF (a) {\n" 1421 " g();\n" 1422 "} else MYIF (b) g();\n" 1423 "else g();", 1424 AllowsMergedIf); 1425 verifyFormat("MYIF (a) {\n" 1426 " g();\n" 1427 "} else if (b) g();\n" 1428 "else g();", 1429 AllowsMergedIf); 1430 verifyFormat("MYIF (a) g();\n" 1431 "else MYIF (b) {\n" 1432 " g();\n" 1433 "} else g();", 1434 AllowsMergedIf); 1435 verifyFormat("MYIF (a) g();\n" 1436 "else if (b) {\n" 1437 " g();\n" 1438 "} else g();", 1439 AllowsMergedIf); 1440 verifyFormat("MYIF (a) g();\n" 1441 "else MYIF (b) g();\n" 1442 "else {\n" 1443 " g();\n" 1444 "}", 1445 AllowsMergedIf); 1446 verifyFormat("MYIF (a) g();\n" 1447 "else if (b) g();\n" 1448 "else {\n" 1449 " g();\n" 1450 "}", 1451 AllowsMergedIf); 1452 verifyFormat("MYIF (a) g();\n" 1453 "else MYIF (b) {\n" 1454 " g();\n" 1455 "} else {\n" 1456 " g();\n" 1457 "}", 1458 AllowsMergedIf); 1459 verifyFormat("MYIF (a) g();\n" 1460 "else if (b) {\n" 1461 " g();\n" 1462 "} else {\n" 1463 " g();\n" 1464 "}", 1465 AllowsMergedIf); 1466 verifyFormat("MYIF (a) {\n" 1467 " g();\n" 1468 "} else MYIF (b) {\n" 1469 " g();\n" 1470 "} else {\n" 1471 " g();\n" 1472 "}", 1473 AllowsMergedIf); 1474 verifyFormat("MYIF (a) {\n" 1475 " g();\n" 1476 "} else if (b) {\n" 1477 " g();\n" 1478 "} else {\n" 1479 " g();\n" 1480 "}", 1481 AllowsMergedIf); 1482 } 1483 1484 TEST_F(FormatTest, FormatLoopsWithoutCompoundStatement) { 1485 FormatStyle AllowsMergedLoops = getLLVMStyle(); 1486 AllowsMergedLoops.AllowShortLoopsOnASingleLine = true; 1487 verifyFormat("while (true) continue;", AllowsMergedLoops); 1488 verifyFormat("for (;;) continue;", AllowsMergedLoops); 1489 verifyFormat("for (int &v : vec) v *= 2;", AllowsMergedLoops); 1490 verifyFormat("BOOST_FOREACH (int &v, vec) v *= 2;", AllowsMergedLoops); 1491 verifyFormat("while (true)\n" 1492 " ;", 1493 AllowsMergedLoops); 1494 verifyFormat("for (;;)\n" 1495 " ;", 1496 AllowsMergedLoops); 1497 verifyFormat("for (;;)\n" 1498 " for (;;) continue;", 1499 AllowsMergedLoops); 1500 verifyFormat("for (;;)\n" 1501 " while (true) continue;", 1502 AllowsMergedLoops); 1503 verifyFormat("while (true)\n" 1504 " for (;;) continue;", 1505 AllowsMergedLoops); 1506 verifyFormat("BOOST_FOREACH (int &v, vec)\n" 1507 " for (;;) continue;", 1508 AllowsMergedLoops); 1509 verifyFormat("for (;;)\n" 1510 " BOOST_FOREACH (int &v, vec) continue;", 1511 AllowsMergedLoops); 1512 verifyFormat("for (;;) // Can't merge this\n" 1513 " continue;", 1514 AllowsMergedLoops); 1515 verifyFormat("for (;;) /* still don't merge */\n" 1516 " continue;", 1517 AllowsMergedLoops); 1518 verifyFormat("do a++;\n" 1519 "while (true);", 1520 AllowsMergedLoops); 1521 verifyFormat("do /* Don't merge */\n" 1522 " a++;\n" 1523 "while (true);", 1524 AllowsMergedLoops); 1525 verifyFormat("do // Don't merge\n" 1526 " a++;\n" 1527 "while (true);", 1528 AllowsMergedLoops); 1529 verifyFormat("do\n" 1530 " // Don't merge\n" 1531 " a++;\n" 1532 "while (true);", 1533 AllowsMergedLoops); 1534 // Without braces labels are interpreted differently. 1535 verifyFormat("{\n" 1536 " do\n" 1537 " label:\n" 1538 " a++;\n" 1539 " while (true);\n" 1540 "}", 1541 AllowsMergedLoops); 1542 } 1543 1544 TEST_F(FormatTest, FormatShortBracedStatements) { 1545 FormatStyle AllowSimpleBracedStatements = getLLVMStyle(); 1546 EXPECT_EQ(AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine, false); 1547 EXPECT_EQ(AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine, 1548 FormatStyle::SIS_Never); 1549 EXPECT_EQ(AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine, false); 1550 EXPECT_EQ(AllowSimpleBracedStatements.BraceWrapping.AfterFunction, false); 1551 verifyFormat("for (;;) {\n" 1552 " f();\n" 1553 "}"); 1554 verifyFormat("/*comment*/ for (;;) {\n" 1555 " f();\n" 1556 "}"); 1557 verifyFormat("BOOST_FOREACH (int v, vec) {\n" 1558 " f();\n" 1559 "}"); 1560 verifyFormat("/*comment*/ BOOST_FOREACH (int v, vec) {\n" 1561 " f();\n" 1562 "}"); 1563 verifyFormat("while (true) {\n" 1564 " f();\n" 1565 "}"); 1566 verifyFormat("/*comment*/ while (true) {\n" 1567 " f();\n" 1568 "}"); 1569 verifyFormat("if (true) {\n" 1570 " f();\n" 1571 "}"); 1572 verifyFormat("/*comment*/ if (true) {\n" 1573 " f();\n" 1574 "}"); 1575 1576 AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine = 1577 FormatStyle::SBS_Empty; 1578 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1579 FormatStyle::SIS_WithoutElse; 1580 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1581 verifyFormat("if (i) break;", AllowSimpleBracedStatements); 1582 verifyFormat("if (i > 0) {\n" 1583 " return i;\n" 1584 "}", 1585 AllowSimpleBracedStatements); 1586 1587 AllowSimpleBracedStatements.IfMacros.push_back("MYIF"); 1588 // Where line-lengths matter, a 2-letter synonym that maintains line length. 1589 // Not IF to avoid any confusion that IF is somehow special. 1590 AllowSimpleBracedStatements.IfMacros.push_back("FI"); 1591 AllowSimpleBracedStatements.ColumnLimit = 40; 1592 AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine = 1593 FormatStyle::SBS_Always; 1594 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true; 1595 AllowSimpleBracedStatements.BreakBeforeBraces = FormatStyle::BS_Custom; 1596 AllowSimpleBracedStatements.BraceWrapping.AfterFunction = true; 1597 AllowSimpleBracedStatements.BraceWrapping.SplitEmptyRecord = false; 1598 1599 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1600 verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements); 1601 verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1602 verifyFormat("if consteval {}", AllowSimpleBracedStatements); 1603 verifyFormat("if !consteval {}", AllowSimpleBracedStatements); 1604 verifyFormat("if CONSTEVAL {}", AllowSimpleBracedStatements); 1605 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1606 verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements); 1607 verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1608 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1609 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1610 verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements); 1611 verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements); 1612 verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1613 verifyFormat("if consteval { f(); }", AllowSimpleBracedStatements); 1614 verifyFormat("if CONSTEVAL { f(); }", AllowSimpleBracedStatements); 1615 verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements); 1616 verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements); 1617 verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1618 verifyFormat("MYIF consteval { f(); }", AllowSimpleBracedStatements); 1619 verifyFormat("MYIF CONSTEVAL { f(); }", AllowSimpleBracedStatements); 1620 verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements); 1621 verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements); 1622 verifyFormat("if (true) { fffffffffffffffffffffff(); }", 1623 AllowSimpleBracedStatements); 1624 verifyFormat("if (true) {\n" 1625 " ffffffffffffffffffffffff();\n" 1626 "}", 1627 AllowSimpleBracedStatements); 1628 verifyFormat("if (true) {\n" 1629 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1630 "}", 1631 AllowSimpleBracedStatements); 1632 verifyFormat("if (true) { //\n" 1633 " f();\n" 1634 "}", 1635 AllowSimpleBracedStatements); 1636 verifyFormat("if (true) {\n" 1637 " f();\n" 1638 " f();\n" 1639 "}", 1640 AllowSimpleBracedStatements); 1641 verifyFormat("if (true) {\n" 1642 " f();\n" 1643 "} else {\n" 1644 " f();\n" 1645 "}", 1646 AllowSimpleBracedStatements); 1647 verifyFormat("FI (true) { fffffffffffffffffffffff(); }", 1648 AllowSimpleBracedStatements); 1649 verifyFormat("MYIF (true) {\n" 1650 " ffffffffffffffffffffffff();\n" 1651 "}", 1652 AllowSimpleBracedStatements); 1653 verifyFormat("MYIF (true) {\n" 1654 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1655 "}", 1656 AllowSimpleBracedStatements); 1657 verifyFormat("MYIF (true) { //\n" 1658 " f();\n" 1659 "}", 1660 AllowSimpleBracedStatements); 1661 verifyFormat("MYIF (true) {\n" 1662 " f();\n" 1663 " f();\n" 1664 "}", 1665 AllowSimpleBracedStatements); 1666 verifyFormat("MYIF (true) {\n" 1667 " f();\n" 1668 "} else {\n" 1669 " f();\n" 1670 "}", 1671 AllowSimpleBracedStatements); 1672 1673 verifyFormat("struct A2 {\n" 1674 " int X;\n" 1675 "};", 1676 AllowSimpleBracedStatements); 1677 verifyFormat("typedef struct A2 {\n" 1678 " int X;\n" 1679 "} A2_t;", 1680 AllowSimpleBracedStatements); 1681 verifyFormat("template <int> struct A2 {\n" 1682 " struct B {};\n" 1683 "};", 1684 AllowSimpleBracedStatements); 1685 1686 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1687 FormatStyle::SIS_Never; 1688 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1689 verifyFormat("if (true) {\n" 1690 " f();\n" 1691 "}", 1692 AllowSimpleBracedStatements); 1693 verifyFormat("if (true) {\n" 1694 " f();\n" 1695 "} else {\n" 1696 " f();\n" 1697 "}", 1698 AllowSimpleBracedStatements); 1699 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1700 verifyFormat("MYIF (true) {\n" 1701 " f();\n" 1702 "}", 1703 AllowSimpleBracedStatements); 1704 verifyFormat("MYIF (true) {\n" 1705 " f();\n" 1706 "} else {\n" 1707 " f();\n" 1708 "}", 1709 AllowSimpleBracedStatements); 1710 1711 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false; 1712 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1713 verifyFormat("while (true) {\n" 1714 " f();\n" 1715 "}", 1716 AllowSimpleBracedStatements); 1717 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1718 verifyFormat("for (;;) {\n" 1719 " f();\n" 1720 "}", 1721 AllowSimpleBracedStatements); 1722 verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements); 1723 verifyFormat("BOOST_FOREACH (int v, vec) {\n" 1724 " f();\n" 1725 "}", 1726 AllowSimpleBracedStatements); 1727 1728 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1729 FormatStyle::SIS_WithoutElse; 1730 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true; 1731 AllowSimpleBracedStatements.BraceWrapping.AfterControlStatement = 1732 FormatStyle::BWACS_Always; 1733 1734 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1735 verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements); 1736 verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1737 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1738 verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements); 1739 verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1740 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1741 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1742 verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements); 1743 verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements); 1744 verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1745 verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements); 1746 verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements); 1747 verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1748 verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements); 1749 verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements); 1750 verifyFormat("if (true) { fffffffffffffffffffffff(); }", 1751 AllowSimpleBracedStatements); 1752 verifyFormat("if (true)\n" 1753 "{\n" 1754 " ffffffffffffffffffffffff();\n" 1755 "}", 1756 AllowSimpleBracedStatements); 1757 verifyFormat("if (true)\n" 1758 "{\n" 1759 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1760 "}", 1761 AllowSimpleBracedStatements); 1762 verifyFormat("if (true)\n" 1763 "{ //\n" 1764 " f();\n" 1765 "}", 1766 AllowSimpleBracedStatements); 1767 verifyFormat("if (true)\n" 1768 "{\n" 1769 " f();\n" 1770 " f();\n" 1771 "}", 1772 AllowSimpleBracedStatements); 1773 verifyFormat("if (true)\n" 1774 "{\n" 1775 " f();\n" 1776 "} else\n" 1777 "{\n" 1778 " f();\n" 1779 "}", 1780 AllowSimpleBracedStatements); 1781 verifyFormat("FI (true) { fffffffffffffffffffffff(); }", 1782 AllowSimpleBracedStatements); 1783 verifyFormat("MYIF (true)\n" 1784 "{\n" 1785 " ffffffffffffffffffffffff();\n" 1786 "}", 1787 AllowSimpleBracedStatements); 1788 verifyFormat("MYIF (true)\n" 1789 "{\n" 1790 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1791 "}", 1792 AllowSimpleBracedStatements); 1793 verifyFormat("MYIF (true)\n" 1794 "{ //\n" 1795 " f();\n" 1796 "}", 1797 AllowSimpleBracedStatements); 1798 verifyFormat("MYIF (true)\n" 1799 "{\n" 1800 " f();\n" 1801 " f();\n" 1802 "}", 1803 AllowSimpleBracedStatements); 1804 verifyFormat("MYIF (true)\n" 1805 "{\n" 1806 " f();\n" 1807 "} else\n" 1808 "{\n" 1809 " f();\n" 1810 "}", 1811 AllowSimpleBracedStatements); 1812 1813 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1814 FormatStyle::SIS_Never; 1815 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1816 verifyFormat("if (true)\n" 1817 "{\n" 1818 " f();\n" 1819 "}", 1820 AllowSimpleBracedStatements); 1821 verifyFormat("if (true)\n" 1822 "{\n" 1823 " f();\n" 1824 "} else\n" 1825 "{\n" 1826 " f();\n" 1827 "}", 1828 AllowSimpleBracedStatements); 1829 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1830 verifyFormat("MYIF (true)\n" 1831 "{\n" 1832 " f();\n" 1833 "}", 1834 AllowSimpleBracedStatements); 1835 verifyFormat("MYIF (true)\n" 1836 "{\n" 1837 " f();\n" 1838 "} else\n" 1839 "{\n" 1840 " f();\n" 1841 "}", 1842 AllowSimpleBracedStatements); 1843 1844 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false; 1845 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1846 verifyFormat("while (true)\n" 1847 "{\n" 1848 " f();\n" 1849 "}", 1850 AllowSimpleBracedStatements); 1851 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1852 verifyFormat("for (;;)\n" 1853 "{\n" 1854 " f();\n" 1855 "}", 1856 AllowSimpleBracedStatements); 1857 verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements); 1858 verifyFormat("BOOST_FOREACH (int v, vec)\n" 1859 "{\n" 1860 " f();\n" 1861 "}", 1862 AllowSimpleBracedStatements); 1863 } 1864 1865 TEST_F(FormatTest, UnderstandsMacros) { 1866 verifyFormat("#define A (parentheses)"); 1867 verifyFormat("/* comment */ #define A (parentheses)"); 1868 verifyFormat("/* comment */ /* another comment */ #define A (parentheses)"); 1869 // Even the partial code should never be merged. 1870 EXPECT_EQ("/* comment */ #define A (parentheses)\n" 1871 "#", 1872 format("/* comment */ #define A (parentheses)\n" 1873 "#")); 1874 verifyFormat("/* comment */ #define A (parentheses)\n" 1875 "#\n"); 1876 verifyFormat("/* comment */ #define A (parentheses)\n" 1877 "#define B (parentheses)"); 1878 verifyFormat("#define true ((int)1)"); 1879 verifyFormat("#define and(x)"); 1880 verifyFormat("#define if(x) x"); 1881 verifyFormat("#define return(x) (x)"); 1882 verifyFormat("#define while(x) for (; x;)"); 1883 verifyFormat("#define xor(x) (^(x))"); 1884 verifyFormat("#define __except(x)"); 1885 verifyFormat("#define __try(x)"); 1886 1887 // https://llvm.org/PR54348. 1888 verifyFormat( 1889 "#define A" 1890 " " 1891 "\\\n" 1892 " class & {}"); 1893 1894 FormatStyle Style = getLLVMStyle(); 1895 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 1896 Style.BraceWrapping.AfterFunction = true; 1897 // Test that a macro definition never gets merged with the following 1898 // definition. 1899 // FIXME: The AAA macro definition probably should not be split into 3 lines. 1900 verifyFormat("#define AAA " 1901 " \\\n" 1902 " N " 1903 " \\\n" 1904 " {\n" 1905 "#define BBB }\n", 1906 Style); 1907 // verifyFormat("#define AAA N { //\n", Style); 1908 1909 verifyFormat("MACRO(return)"); 1910 verifyFormat("MACRO(co_await)"); 1911 verifyFormat("MACRO(co_return)"); 1912 verifyFormat("MACRO(co_yield)"); 1913 verifyFormat("MACRO(return, something)"); 1914 verifyFormat("MACRO(co_return, something)"); 1915 verifyFormat("MACRO(something##something)"); 1916 verifyFormat("MACRO(return##something)"); 1917 verifyFormat("MACRO(co_return##something)"); 1918 } 1919 1920 TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) { 1921 FormatStyle Style = getLLVMStyleWithColumns(60); 1922 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 1923 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse; 1924 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 1925 EXPECT_EQ("#define A \\\n" 1926 " if (HANDLEwernufrnuLwrmviferuvnierv) \\\n" 1927 " { \\\n" 1928 " RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n" 1929 " }\n" 1930 "X;", 1931 format("#define A \\\n" 1932 " if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n" 1933 " RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n" 1934 " }\n" 1935 "X;", 1936 Style)); 1937 } 1938 1939 TEST_F(FormatTest, ParseIfElse) { 1940 verifyFormat("if (true)\n" 1941 " if (true)\n" 1942 " if (true)\n" 1943 " f();\n" 1944 " else\n" 1945 " g();\n" 1946 " else\n" 1947 " h();\n" 1948 "else\n" 1949 " i();"); 1950 verifyFormat("if (true)\n" 1951 " if (true)\n" 1952 " if (true) {\n" 1953 " if (true)\n" 1954 " f();\n" 1955 " } else {\n" 1956 " g();\n" 1957 " }\n" 1958 " else\n" 1959 " h();\n" 1960 "else {\n" 1961 " i();\n" 1962 "}"); 1963 verifyFormat("if (true)\n" 1964 " if constexpr (true)\n" 1965 " if (true) {\n" 1966 " if constexpr (true)\n" 1967 " f();\n" 1968 " } else {\n" 1969 " g();\n" 1970 " }\n" 1971 " else\n" 1972 " h();\n" 1973 "else {\n" 1974 " i();\n" 1975 "}"); 1976 verifyFormat("if (true)\n" 1977 " if CONSTEXPR (true)\n" 1978 " if (true) {\n" 1979 " if CONSTEXPR (true)\n" 1980 " f();\n" 1981 " } else {\n" 1982 " g();\n" 1983 " }\n" 1984 " else\n" 1985 " h();\n" 1986 "else {\n" 1987 " i();\n" 1988 "}"); 1989 verifyFormat("void f() {\n" 1990 " if (a) {\n" 1991 " } else {\n" 1992 " }\n" 1993 "}"); 1994 } 1995 1996 TEST_F(FormatTest, ElseIf) { 1997 verifyFormat("if (a) {\n} else if (b) {\n}"); 1998 verifyFormat("if (a)\n" 1999 " f();\n" 2000 "else if (b)\n" 2001 " g();\n" 2002 "else\n" 2003 " h();"); 2004 verifyFormat("if (a)\n" 2005 " f();\n" 2006 "else // comment\n" 2007 " if (b) {\n" 2008 " g();\n" 2009 " h();\n" 2010 " }"); 2011 verifyFormat("if constexpr (a)\n" 2012 " f();\n" 2013 "else if constexpr (b)\n" 2014 " g();\n" 2015 "else\n" 2016 " h();"); 2017 verifyFormat("if CONSTEXPR (a)\n" 2018 " f();\n" 2019 "else if CONSTEXPR (b)\n" 2020 " g();\n" 2021 "else\n" 2022 " h();"); 2023 verifyFormat("if (a) {\n" 2024 " f();\n" 2025 "}\n" 2026 "// or else ..\n" 2027 "else {\n" 2028 " g()\n" 2029 "}"); 2030 2031 verifyFormat("if (a) {\n" 2032 "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2033 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 2034 "}"); 2035 verifyFormat("if (a) {\n" 2036 "} else if constexpr (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2037 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 2038 "}"); 2039 verifyFormat("if (a) {\n" 2040 "} else if CONSTEXPR (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2041 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 2042 "}"); 2043 verifyFormat("if (a) {\n" 2044 "} else if (\n" 2045 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 2046 "}", 2047 getLLVMStyleWithColumns(62)); 2048 verifyFormat("if (a) {\n" 2049 "} else if constexpr (\n" 2050 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 2051 "}", 2052 getLLVMStyleWithColumns(62)); 2053 verifyFormat("if (a) {\n" 2054 "} else if CONSTEXPR (\n" 2055 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 2056 "}", 2057 getLLVMStyleWithColumns(62)); 2058 } 2059 2060 TEST_F(FormatTest, SeparatePointerReferenceAlignment) { 2061 FormatStyle Style = getLLVMStyle(); 2062 EXPECT_EQ(Style.PointerAlignment, FormatStyle::PAS_Right); 2063 EXPECT_EQ(Style.ReferenceAlignment, FormatStyle::RAS_Pointer); 2064 verifyFormat("int *f1(int *a, int &b, int &&c);", Style); 2065 verifyFormat("int &f2(int &&c, int *a, int &b);", Style); 2066 verifyFormat("int &&f3(int &b, int &&c, int *a);", Style); 2067 verifyFormat("int *f1(int &a) const &;", Style); 2068 verifyFormat("int *f1(int &a) const & = 0;", Style); 2069 verifyFormat("int *a = f1();", Style); 2070 verifyFormat("int &b = f2();", Style); 2071 verifyFormat("int &&c = f3();", Style); 2072 verifyFormat("for (auto a = 0, b = 0; const auto &c : {1, 2, 3})", Style); 2073 verifyFormat("for (auto a = 0, b = 0; const int &c : {1, 2, 3})", Style); 2074 verifyFormat("for (auto a = 0, b = 0; const Foo &c : {1, 2, 3})", Style); 2075 verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style); 2076 verifyFormat("for (int a = 0, b = 0; const auto &c : {1, 2, 3})", Style); 2077 verifyFormat("for (int a = 0, b = 0; const int &c : {1, 2, 3})", Style); 2078 verifyFormat("for (int a = 0, b = 0; const Foo &c : {1, 2, 3})", Style); 2079 verifyFormat("for (int a = 0, b++; const auto &c : {1, 2, 3})", Style); 2080 verifyFormat("for (int a = 0, b++; const int &c : {1, 2, 3})", Style); 2081 verifyFormat("for (int a = 0, b++; const Foo &c : {1, 2, 3})", Style); 2082 verifyFormat("for (auto x = 0; auto &c : {1, 2, 3})", Style); 2083 verifyFormat("for (auto x = 0; int &c : {1, 2, 3})", Style); 2084 verifyFormat("for (int x = 0; auto &c : {1, 2, 3})", Style); 2085 verifyFormat("for (int x = 0; int &c : {1, 2, 3})", Style); 2086 verifyFormat("for (f(); auto &c : {1, 2, 3})", Style); 2087 verifyFormat("for (f(); int &c : {1, 2, 3})", Style); 2088 verifyFormat( 2089 "function<int(int &)> res1 = [](int &a) { return 0000000000000; },\n" 2090 " res2 = [](int &a) { return 0000000000000; };", 2091 Style); 2092 2093 Style.AlignConsecutiveDeclarations.Enabled = true; 2094 verifyFormat("Const unsigned int *c;\n" 2095 "const unsigned int *d;\n" 2096 "Const unsigned int &e;\n" 2097 "const unsigned int &f;\n" 2098 "const unsigned &&g;\n" 2099 "Const unsigned h;", 2100 Style); 2101 2102 Style.PointerAlignment = FormatStyle::PAS_Left; 2103 Style.ReferenceAlignment = FormatStyle::RAS_Pointer; 2104 verifyFormat("int* f1(int* a, int& b, int&& c);", Style); 2105 verifyFormat("int& f2(int&& c, int* a, int& b);", Style); 2106 verifyFormat("int&& f3(int& b, int&& c, int* a);", Style); 2107 verifyFormat("int* f1(int& a) const& = 0;", Style); 2108 verifyFormat("int* a = f1();", Style); 2109 verifyFormat("int& b = f2();", Style); 2110 verifyFormat("int&& c = f3();", Style); 2111 verifyFormat("for (auto a = 0, b = 0; const auto& c : {1, 2, 3})", Style); 2112 verifyFormat("for (auto a = 0, b = 0; const int& c : {1, 2, 3})", Style); 2113 verifyFormat("for (auto a = 0, b = 0; const Foo& c : {1, 2, 3})", Style); 2114 verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style); 2115 verifyFormat("for (int a = 0, b = 0; const auto& c : {1, 2, 3})", Style); 2116 verifyFormat("for (int a = 0, b = 0; const int& c : {1, 2, 3})", Style); 2117 verifyFormat("for (int a = 0, b = 0; const Foo& c : {1, 2, 3})", Style); 2118 verifyFormat("for (int a = 0, b = 0; const Foo* c : {1, 2, 3})", Style); 2119 verifyFormat("for (int a = 0, b++; const auto& c : {1, 2, 3})", Style); 2120 verifyFormat("for (int a = 0, b++; const int& c : {1, 2, 3})", Style); 2121 verifyFormat("for (int a = 0, b++; const Foo& c : {1, 2, 3})", Style); 2122 verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style); 2123 verifyFormat("for (auto x = 0; auto& c : {1, 2, 3})", Style); 2124 verifyFormat("for (auto x = 0; int& c : {1, 2, 3})", Style); 2125 verifyFormat("for (int x = 0; auto& c : {1, 2, 3})", Style); 2126 verifyFormat("for (int x = 0; int& c : {1, 2, 3})", Style); 2127 verifyFormat("for (f(); auto& c : {1, 2, 3})", Style); 2128 verifyFormat("for (f(); int& c : {1, 2, 3})", Style); 2129 verifyFormat( 2130 "function<int(int&)> res1 = [](int& a) { return 0000000000000; },\n" 2131 " res2 = [](int& a) { return 0000000000000; };", 2132 Style); 2133 2134 Style.AlignConsecutiveDeclarations.Enabled = true; 2135 verifyFormat("Const unsigned int* c;\n" 2136 "const unsigned int* d;\n" 2137 "Const unsigned int& e;\n" 2138 "const unsigned int& f;\n" 2139 "const unsigned&& g;\n" 2140 "Const unsigned h;", 2141 Style); 2142 2143 Style.PointerAlignment = FormatStyle::PAS_Right; 2144 Style.ReferenceAlignment = FormatStyle::RAS_Left; 2145 verifyFormat("int *f1(int *a, int& b, int&& c);", Style); 2146 verifyFormat("int& f2(int&& c, int *a, int& b);", Style); 2147 verifyFormat("int&& f3(int& b, int&& c, int *a);", Style); 2148 verifyFormat("int *a = f1();", Style); 2149 verifyFormat("int& b = f2();", Style); 2150 verifyFormat("int&& c = f3();", Style); 2151 verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style); 2152 verifyFormat("for (int a = 0, b = 0; const Foo *c : {1, 2, 3})", Style); 2153 verifyFormat("for (int a = 0, b++; const Foo *c : {1, 2, 3})", Style); 2154 2155 Style.AlignConsecutiveDeclarations.Enabled = true; 2156 verifyFormat("Const unsigned int *c;\n" 2157 "const unsigned int *d;\n" 2158 "Const unsigned int& e;\n" 2159 "const unsigned int& f;\n" 2160 "const unsigned g;\n" 2161 "Const unsigned h;", 2162 Style); 2163 2164 Style.PointerAlignment = FormatStyle::PAS_Left; 2165 Style.ReferenceAlignment = FormatStyle::RAS_Middle; 2166 verifyFormat("int* f1(int* a, int & b, int && c);", Style); 2167 verifyFormat("int & f2(int && c, int* a, int & b);", Style); 2168 verifyFormat("int && f3(int & b, int && c, int* a);", Style); 2169 verifyFormat("int* a = f1();", Style); 2170 verifyFormat("int & b = f2();", Style); 2171 verifyFormat("int && c = f3();", Style); 2172 verifyFormat("for (auto a = 0, b = 0; const auto & c : {1, 2, 3})", Style); 2173 verifyFormat("for (auto a = 0, b = 0; const int & c : {1, 2, 3})", Style); 2174 verifyFormat("for (auto a = 0, b = 0; const Foo & c : {1, 2, 3})", Style); 2175 verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style); 2176 verifyFormat("for (int a = 0, b++; const auto & c : {1, 2, 3})", Style); 2177 verifyFormat("for (int a = 0, b++; const int & c : {1, 2, 3})", Style); 2178 verifyFormat("for (int a = 0, b++; const Foo & c : {1, 2, 3})", Style); 2179 verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style); 2180 verifyFormat("for (auto x = 0; auto & c : {1, 2, 3})", Style); 2181 verifyFormat("for (auto x = 0; int & c : {1, 2, 3})", Style); 2182 verifyFormat("for (int x = 0; auto & c : {1, 2, 3})", Style); 2183 verifyFormat("for (int x = 0; int & c : {1, 2, 3})", Style); 2184 verifyFormat("for (f(); auto & c : {1, 2, 3})", Style); 2185 verifyFormat("for (f(); int & c : {1, 2, 3})", Style); 2186 verifyFormat( 2187 "function<int(int &)> res1 = [](int & a) { return 0000000000000; },\n" 2188 " res2 = [](int & a) { return 0000000000000; };", 2189 Style); 2190 2191 Style.AlignConsecutiveDeclarations.Enabled = true; 2192 verifyFormat("Const unsigned int* c;\n" 2193 "const unsigned int* d;\n" 2194 "Const unsigned int & e;\n" 2195 "const unsigned int & f;\n" 2196 "const unsigned && g;\n" 2197 "Const unsigned h;", 2198 Style); 2199 2200 Style.PointerAlignment = FormatStyle::PAS_Middle; 2201 Style.ReferenceAlignment = FormatStyle::RAS_Right; 2202 verifyFormat("int * f1(int * a, int &b, int &&c);", Style); 2203 verifyFormat("int &f2(int &&c, int * a, int &b);", Style); 2204 verifyFormat("int &&f3(int &b, int &&c, int * a);", Style); 2205 verifyFormat("int * a = f1();", Style); 2206 verifyFormat("int &b = f2();", Style); 2207 verifyFormat("int &&c = f3();", Style); 2208 verifyFormat("for (auto a = 0, b = 0; const Foo * c : {1, 2, 3})", Style); 2209 verifyFormat("for (int a = 0, b = 0; const Foo * c : {1, 2, 3})", Style); 2210 verifyFormat("for (int a = 0, b++; const Foo * c : {1, 2, 3})", Style); 2211 2212 // FIXME: we don't handle this yet, so output may be arbitrary until it's 2213 // specifically handled 2214 // verifyFormat("int Add2(BTree * &Root, char * szToAdd)", Style); 2215 } 2216 2217 TEST_F(FormatTest, FormatsForLoop) { 2218 verifyFormat( 2219 "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n" 2220 " ++VeryVeryLongLoopVariable)\n" 2221 " ;"); 2222 verifyFormat("for (;;)\n" 2223 " f();"); 2224 verifyFormat("for (;;) {\n}"); 2225 verifyFormat("for (;;) {\n" 2226 " f();\n" 2227 "}"); 2228 verifyFormat("for (int i = 0; (i < 10); ++i) {\n}"); 2229 2230 verifyFormat( 2231 "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n" 2232 " E = UnwrappedLines.end();\n" 2233 " I != E; ++I) {\n}"); 2234 2235 verifyFormat( 2236 "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n" 2237 " ++IIIII) {\n}"); 2238 verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n" 2239 " aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n" 2240 " aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}"); 2241 verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n" 2242 " I = FD->getDeclsInPrototypeScope().begin(),\n" 2243 " E = FD->getDeclsInPrototypeScope().end();\n" 2244 " I != E; ++I) {\n}"); 2245 verifyFormat("for (SmallVectorImpl<TemplateIdAnnotationn *>::iterator\n" 2246 " I = Container.begin(),\n" 2247 " E = Container.end();\n" 2248 " I != E; ++I) {\n}", 2249 getLLVMStyleWithColumns(76)); 2250 2251 verifyFormat( 2252 "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n" 2253 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n" 2254 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2255 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 2256 " ++aaaaaaaaaaa) {\n}"); 2257 verifyFormat("for (int i = 0; i < aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 2258 " bbbbbbbbbbbbbbbbbbbb < ccccccccccccccc;\n" 2259 " ++i) {\n}"); 2260 verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n" 2261 " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n" 2262 "}"); 2263 verifyFormat("for (some_namespace::SomeIterator iter( // force break\n" 2264 " aaaaaaaaaa);\n" 2265 " iter; ++iter) {\n" 2266 "}"); 2267 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2268 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 2269 " aaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbbbbbbb;\n" 2270 " ++aaaaaaaaaaaaaaaaaaaaaaaaaaa) {"); 2271 2272 // These should not be formatted as Objective-C for-in loops. 2273 verifyFormat("for (Foo *x = 0; x != in; x++) {\n}"); 2274 verifyFormat("Foo *x;\nfor (x = 0; x != in; x++) {\n}"); 2275 verifyFormat("Foo *x;\nfor (x in y) {\n}"); 2276 verifyFormat( 2277 "for (const Foo<Bar> &baz = in.value(); !baz.at_end(); ++baz) {\n}"); 2278 2279 FormatStyle NoBinPacking = getLLVMStyle(); 2280 NoBinPacking.BinPackParameters = false; 2281 verifyFormat("for (int aaaaaaaaaaa = 1;\n" 2282 " aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n" 2283 " aaaaaaaaaaaaaaaa,\n" 2284 " aaaaaaaaaaaaaaaa,\n" 2285 " aaaaaaaaaaaaaaaa);\n" 2286 " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n" 2287 "}", 2288 NoBinPacking); 2289 verifyFormat( 2290 "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n" 2291 " E = UnwrappedLines.end();\n" 2292 " I != E;\n" 2293 " ++I) {\n}", 2294 NoBinPacking); 2295 2296 FormatStyle AlignLeft = getLLVMStyle(); 2297 AlignLeft.PointerAlignment = FormatStyle::PAS_Left; 2298 verifyFormat("for (A* a = start; a < end; ++a, ++value) {\n}", AlignLeft); 2299 } 2300 2301 TEST_F(FormatTest, RangeBasedForLoops) { 2302 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 2303 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 2304 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n" 2305 " aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}"); 2306 verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n" 2307 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 2308 verifyFormat("for (aaaaaaaaa aaaaaaaaaaaaaaaaaaaaa :\n" 2309 " aaaaaaaaaaaa.aaaaaaaaaaaa().aaaaaaaaa().a()) {\n}"); 2310 } 2311 2312 TEST_F(FormatTest, ForEachLoops) { 2313 FormatStyle Style = getLLVMStyle(); 2314 EXPECT_EQ(Style.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 2315 EXPECT_EQ(Style.AllowShortLoopsOnASingleLine, false); 2316 verifyFormat("void f() {\n" 2317 " for (;;) {\n" 2318 " }\n" 2319 " foreach (Item *item, itemlist) {\n" 2320 " }\n" 2321 " Q_FOREACH (Item *item, itemlist) {\n" 2322 " }\n" 2323 " BOOST_FOREACH (Item *item, itemlist) {\n" 2324 " }\n" 2325 " UNKNOWN_FOREACH(Item * item, itemlist) {}\n" 2326 "}", 2327 Style); 2328 verifyFormat("void f() {\n" 2329 " for (;;)\n" 2330 " int j = 1;\n" 2331 " Q_FOREACH (int v, vec)\n" 2332 " v *= 2;\n" 2333 " for (;;) {\n" 2334 " int j = 1;\n" 2335 " }\n" 2336 " Q_FOREACH (int v, vec) {\n" 2337 " v *= 2;\n" 2338 " }\n" 2339 "}", 2340 Style); 2341 2342 FormatStyle ShortBlocks = getLLVMStyle(); 2343 ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 2344 EXPECT_EQ(ShortBlocks.AllowShortLoopsOnASingleLine, false); 2345 verifyFormat("void f() {\n" 2346 " for (;;)\n" 2347 " int j = 1;\n" 2348 " Q_FOREACH (int &v, vec)\n" 2349 " v *= 2;\n" 2350 " for (;;) {\n" 2351 " int j = 1;\n" 2352 " }\n" 2353 " Q_FOREACH (int &v, vec) {\n" 2354 " int j = 1;\n" 2355 " }\n" 2356 "}", 2357 ShortBlocks); 2358 2359 FormatStyle ShortLoops = getLLVMStyle(); 2360 ShortLoops.AllowShortLoopsOnASingleLine = true; 2361 EXPECT_EQ(ShortLoops.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 2362 verifyFormat("void f() {\n" 2363 " for (;;) int j = 1;\n" 2364 " Q_FOREACH (int &v, vec) int j = 1;\n" 2365 " for (;;) {\n" 2366 " int j = 1;\n" 2367 " }\n" 2368 " Q_FOREACH (int &v, vec) {\n" 2369 " int j = 1;\n" 2370 " }\n" 2371 "}", 2372 ShortLoops); 2373 2374 FormatStyle ShortBlocksAndLoops = getLLVMStyle(); 2375 ShortBlocksAndLoops.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 2376 ShortBlocksAndLoops.AllowShortLoopsOnASingleLine = true; 2377 verifyFormat("void f() {\n" 2378 " for (;;) int j = 1;\n" 2379 " Q_FOREACH (int &v, vec) int j = 1;\n" 2380 " for (;;) { int j = 1; }\n" 2381 " Q_FOREACH (int &v, vec) { int j = 1; }\n" 2382 "}", 2383 ShortBlocksAndLoops); 2384 2385 Style.SpaceBeforeParens = 2386 FormatStyle::SBPO_ControlStatementsExceptControlMacros; 2387 verifyFormat("void f() {\n" 2388 " for (;;) {\n" 2389 " }\n" 2390 " foreach(Item *item, itemlist) {\n" 2391 " }\n" 2392 " Q_FOREACH(Item *item, itemlist) {\n" 2393 " }\n" 2394 " BOOST_FOREACH(Item *item, itemlist) {\n" 2395 " }\n" 2396 " UNKNOWN_FOREACH(Item * item, itemlist) {}\n" 2397 "}", 2398 Style); 2399 2400 // As function-like macros. 2401 verifyFormat("#define foreach(x, y)\n" 2402 "#define Q_FOREACH(x, y)\n" 2403 "#define BOOST_FOREACH(x, y)\n" 2404 "#define UNKNOWN_FOREACH(x, y)\n"); 2405 2406 // Not as function-like macros. 2407 verifyFormat("#define foreach (x, y)\n" 2408 "#define Q_FOREACH (x, y)\n" 2409 "#define BOOST_FOREACH (x, y)\n" 2410 "#define UNKNOWN_FOREACH (x, y)\n"); 2411 2412 // handle microsoft non standard extension 2413 verifyFormat("for each (char c in x->MyStringProperty)"); 2414 } 2415 2416 TEST_F(FormatTest, FormatsWhileLoop) { 2417 verifyFormat("while (true) {\n}"); 2418 verifyFormat("while (true)\n" 2419 " f();"); 2420 verifyFormat("while () {\n}"); 2421 verifyFormat("while () {\n" 2422 " f();\n" 2423 "}"); 2424 } 2425 2426 TEST_F(FormatTest, FormatsDoWhile) { 2427 verifyFormat("do {\n" 2428 " do_something();\n" 2429 "} while (something());"); 2430 verifyFormat("do\n" 2431 " do_something();\n" 2432 "while (something());"); 2433 } 2434 2435 TEST_F(FormatTest, FormatsSwitchStatement) { 2436 verifyFormat("switch (x) {\n" 2437 "case 1:\n" 2438 " f();\n" 2439 " break;\n" 2440 "case kFoo:\n" 2441 "case ns::kBar:\n" 2442 "case kBaz:\n" 2443 " break;\n" 2444 "default:\n" 2445 " g();\n" 2446 " break;\n" 2447 "}"); 2448 verifyFormat("switch (x) {\n" 2449 "case 1: {\n" 2450 " f();\n" 2451 " break;\n" 2452 "}\n" 2453 "case 2: {\n" 2454 " break;\n" 2455 "}\n" 2456 "}"); 2457 verifyFormat("switch (x) {\n" 2458 "case 1: {\n" 2459 " f();\n" 2460 " {\n" 2461 " g();\n" 2462 " h();\n" 2463 " }\n" 2464 " break;\n" 2465 "}\n" 2466 "}"); 2467 verifyFormat("switch (x) {\n" 2468 "case 1: {\n" 2469 " f();\n" 2470 " if (foo) {\n" 2471 " g();\n" 2472 " h();\n" 2473 " }\n" 2474 " break;\n" 2475 "}\n" 2476 "}"); 2477 verifyFormat("switch (x) {\n" 2478 "case 1: {\n" 2479 " f();\n" 2480 " g();\n" 2481 "} break;\n" 2482 "}"); 2483 verifyFormat("switch (test)\n" 2484 " ;"); 2485 verifyFormat("switch (x) {\n" 2486 "default: {\n" 2487 " // Do nothing.\n" 2488 "}\n" 2489 "}"); 2490 verifyFormat("switch (x) {\n" 2491 "// comment\n" 2492 "// if 1, do f()\n" 2493 "case 1:\n" 2494 " f();\n" 2495 "}"); 2496 verifyFormat("switch (x) {\n" 2497 "case 1:\n" 2498 " // Do amazing stuff\n" 2499 " {\n" 2500 " f();\n" 2501 " g();\n" 2502 " }\n" 2503 " break;\n" 2504 "}"); 2505 verifyFormat("#define A \\\n" 2506 " switch (x) { \\\n" 2507 " case a: \\\n" 2508 " foo = b; \\\n" 2509 " }", 2510 getLLVMStyleWithColumns(20)); 2511 verifyFormat("#define OPERATION_CASE(name) \\\n" 2512 " case OP_name: \\\n" 2513 " return operations::Operation##name\n", 2514 getLLVMStyleWithColumns(40)); 2515 verifyFormat("switch (x) {\n" 2516 "case 1:;\n" 2517 "default:;\n" 2518 " int i;\n" 2519 "}"); 2520 2521 verifyGoogleFormat("switch (x) {\n" 2522 " case 1:\n" 2523 " f();\n" 2524 " break;\n" 2525 " case kFoo:\n" 2526 " case ns::kBar:\n" 2527 " case kBaz:\n" 2528 " break;\n" 2529 " default:\n" 2530 " g();\n" 2531 " break;\n" 2532 "}"); 2533 verifyGoogleFormat("switch (x) {\n" 2534 " case 1: {\n" 2535 " f();\n" 2536 " break;\n" 2537 " }\n" 2538 "}"); 2539 verifyGoogleFormat("switch (test)\n" 2540 " ;"); 2541 2542 verifyGoogleFormat("#define OPERATION_CASE(name) \\\n" 2543 " case OP_name: \\\n" 2544 " return operations::Operation##name\n"); 2545 verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n" 2546 " // Get the correction operation class.\n" 2547 " switch (OpCode) {\n" 2548 " CASE(Add);\n" 2549 " CASE(Subtract);\n" 2550 " default:\n" 2551 " return operations::Unknown;\n" 2552 " }\n" 2553 "#undef OPERATION_CASE\n" 2554 "}"); 2555 verifyFormat("DEBUG({\n" 2556 " switch (x) {\n" 2557 " case A:\n" 2558 " f();\n" 2559 " break;\n" 2560 " // fallthrough\n" 2561 " case B:\n" 2562 " g();\n" 2563 " break;\n" 2564 " }\n" 2565 "});"); 2566 EXPECT_EQ("DEBUG({\n" 2567 " switch (x) {\n" 2568 " case A:\n" 2569 " f();\n" 2570 " break;\n" 2571 " // On B:\n" 2572 " case B:\n" 2573 " g();\n" 2574 " break;\n" 2575 " }\n" 2576 "});", 2577 format("DEBUG({\n" 2578 " switch (x) {\n" 2579 " case A:\n" 2580 " f();\n" 2581 " break;\n" 2582 " // On B:\n" 2583 " case B:\n" 2584 " g();\n" 2585 " break;\n" 2586 " }\n" 2587 "});", 2588 getLLVMStyle())); 2589 EXPECT_EQ("switch (n) {\n" 2590 "case 0: {\n" 2591 " return false;\n" 2592 "}\n" 2593 "default: {\n" 2594 " return true;\n" 2595 "}\n" 2596 "}", 2597 format("switch (n)\n" 2598 "{\n" 2599 "case 0: {\n" 2600 " return false;\n" 2601 "}\n" 2602 "default: {\n" 2603 " return true;\n" 2604 "}\n" 2605 "}", 2606 getLLVMStyle())); 2607 verifyFormat("switch (a) {\n" 2608 "case (b):\n" 2609 " return;\n" 2610 "}"); 2611 2612 verifyFormat("switch (a) {\n" 2613 "case some_namespace::\n" 2614 " some_constant:\n" 2615 " return;\n" 2616 "}", 2617 getLLVMStyleWithColumns(34)); 2618 2619 verifyFormat("switch (a) {\n" 2620 "[[likely]] case 1:\n" 2621 " return;\n" 2622 "}"); 2623 verifyFormat("switch (a) {\n" 2624 "[[likely]] [[other::likely]] case 1:\n" 2625 " return;\n" 2626 "}"); 2627 verifyFormat("switch (x) {\n" 2628 "case 1:\n" 2629 " return;\n" 2630 "[[likely]] case 2:\n" 2631 " return;\n" 2632 "}"); 2633 verifyFormat("switch (a) {\n" 2634 "case 1:\n" 2635 "[[likely]] case 2:\n" 2636 " return;\n" 2637 "}"); 2638 FormatStyle Attributes = getLLVMStyle(); 2639 Attributes.AttributeMacros.push_back("LIKELY"); 2640 Attributes.AttributeMacros.push_back("OTHER_LIKELY"); 2641 verifyFormat("switch (a) {\n" 2642 "LIKELY case b:\n" 2643 " return;\n" 2644 "}", 2645 Attributes); 2646 verifyFormat("switch (a) {\n" 2647 "LIKELY OTHER_LIKELY() case b:\n" 2648 " return;\n" 2649 "}", 2650 Attributes); 2651 verifyFormat("switch (a) {\n" 2652 "case 1:\n" 2653 " return;\n" 2654 "LIKELY case 2:\n" 2655 " return;\n" 2656 "}", 2657 Attributes); 2658 verifyFormat("switch (a) {\n" 2659 "case 1:\n" 2660 "LIKELY case 2:\n" 2661 " return;\n" 2662 "}", 2663 Attributes); 2664 2665 FormatStyle Style = getLLVMStyle(); 2666 Style.IndentCaseLabels = true; 2667 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 2668 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2669 Style.BraceWrapping.AfterCaseLabel = true; 2670 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 2671 EXPECT_EQ("switch (n)\n" 2672 "{\n" 2673 " case 0:\n" 2674 " {\n" 2675 " return false;\n" 2676 " }\n" 2677 " default:\n" 2678 " {\n" 2679 " return true;\n" 2680 " }\n" 2681 "}", 2682 format("switch (n) {\n" 2683 " case 0: {\n" 2684 " return false;\n" 2685 " }\n" 2686 " default: {\n" 2687 " return true;\n" 2688 " }\n" 2689 "}", 2690 Style)); 2691 Style.BraceWrapping.AfterCaseLabel = false; 2692 EXPECT_EQ("switch (n)\n" 2693 "{\n" 2694 " case 0: {\n" 2695 " return false;\n" 2696 " }\n" 2697 " default: {\n" 2698 " return true;\n" 2699 " }\n" 2700 "}", 2701 format("switch (n) {\n" 2702 " case 0:\n" 2703 " {\n" 2704 " return false;\n" 2705 " }\n" 2706 " default:\n" 2707 " {\n" 2708 " return true;\n" 2709 " }\n" 2710 "}", 2711 Style)); 2712 Style.IndentCaseLabels = false; 2713 Style.IndentCaseBlocks = true; 2714 EXPECT_EQ("switch (n)\n" 2715 "{\n" 2716 "case 0:\n" 2717 " {\n" 2718 " return false;\n" 2719 " }\n" 2720 "case 1:\n" 2721 " break;\n" 2722 "default:\n" 2723 " {\n" 2724 " return true;\n" 2725 " }\n" 2726 "}", 2727 format("switch (n) {\n" 2728 "case 0: {\n" 2729 " return false;\n" 2730 "}\n" 2731 "case 1:\n" 2732 " break;\n" 2733 "default: {\n" 2734 " return true;\n" 2735 "}\n" 2736 "}", 2737 Style)); 2738 Style.IndentCaseLabels = true; 2739 Style.IndentCaseBlocks = true; 2740 EXPECT_EQ("switch (n)\n" 2741 "{\n" 2742 " case 0:\n" 2743 " {\n" 2744 " return false;\n" 2745 " }\n" 2746 " case 1:\n" 2747 " break;\n" 2748 " default:\n" 2749 " {\n" 2750 " return true;\n" 2751 " }\n" 2752 "}", 2753 format("switch (n) {\n" 2754 "case 0: {\n" 2755 " return false;\n" 2756 "}\n" 2757 "case 1:\n" 2758 " break;\n" 2759 "default: {\n" 2760 " return true;\n" 2761 "}\n" 2762 "}", 2763 Style)); 2764 } 2765 2766 TEST_F(FormatTest, CaseRanges) { 2767 verifyFormat("switch (x) {\n" 2768 "case 'A' ... 'Z':\n" 2769 "case 1 ... 5:\n" 2770 "case a ... b:\n" 2771 " break;\n" 2772 "}"); 2773 } 2774 2775 TEST_F(FormatTest, ShortEnums) { 2776 FormatStyle Style = getLLVMStyle(); 2777 EXPECT_TRUE(Style.AllowShortEnumsOnASingleLine); 2778 EXPECT_FALSE(Style.BraceWrapping.AfterEnum); 2779 verifyFormat("enum { A, B, C } ShortEnum1, ShortEnum2;", Style); 2780 verifyFormat("typedef enum { A, B, C } ShortEnum1, ShortEnum2;", Style); 2781 Style.AllowShortEnumsOnASingleLine = false; 2782 verifyFormat("enum {\n" 2783 " A,\n" 2784 " B,\n" 2785 " C\n" 2786 "} ShortEnum1, ShortEnum2;", 2787 Style); 2788 verifyFormat("typedef enum {\n" 2789 " A,\n" 2790 " B,\n" 2791 " C\n" 2792 "} ShortEnum1, ShortEnum2;", 2793 Style); 2794 verifyFormat("enum {\n" 2795 " A,\n" 2796 "} ShortEnum1, ShortEnum2;", 2797 Style); 2798 verifyFormat("typedef enum {\n" 2799 " A,\n" 2800 "} ShortEnum1, ShortEnum2;", 2801 Style); 2802 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2803 Style.BraceWrapping.AfterEnum = true; 2804 verifyFormat("enum\n" 2805 "{\n" 2806 " A,\n" 2807 " B,\n" 2808 " C\n" 2809 "} ShortEnum1, ShortEnum2;", 2810 Style); 2811 verifyFormat("typedef enum\n" 2812 "{\n" 2813 " A,\n" 2814 " B,\n" 2815 " C\n" 2816 "} ShortEnum1, ShortEnum2;", 2817 Style); 2818 } 2819 2820 TEST_F(FormatTest, ShortCaseLabels) { 2821 FormatStyle Style = getLLVMStyle(); 2822 Style.AllowShortCaseLabelsOnASingleLine = true; 2823 verifyFormat("switch (a) {\n" 2824 "case 1: x = 1; break;\n" 2825 "case 2: return;\n" 2826 "case 3:\n" 2827 "case 4:\n" 2828 "case 5: return;\n" 2829 "case 6: // comment\n" 2830 " return;\n" 2831 "case 7:\n" 2832 " // comment\n" 2833 " return;\n" 2834 "case 8:\n" 2835 " x = 8; // comment\n" 2836 " break;\n" 2837 "default: y = 1; break;\n" 2838 "}", 2839 Style); 2840 verifyFormat("switch (a) {\n" 2841 "case 0: return; // comment\n" 2842 "case 1: break; // comment\n" 2843 "case 2: return;\n" 2844 "// comment\n" 2845 "case 3: return;\n" 2846 "// comment 1\n" 2847 "// comment 2\n" 2848 "// comment 3\n" 2849 "case 4: break; /* comment */\n" 2850 "case 5:\n" 2851 " // comment\n" 2852 " break;\n" 2853 "case 6: /* comment */ x = 1; break;\n" 2854 "case 7: x = /* comment */ 1; break;\n" 2855 "case 8:\n" 2856 " x = 1; /* comment */\n" 2857 " break;\n" 2858 "case 9:\n" 2859 " break; // comment line 1\n" 2860 " // comment line 2\n" 2861 "}", 2862 Style); 2863 EXPECT_EQ("switch (a) {\n" 2864 "case 1:\n" 2865 " x = 8;\n" 2866 " // fall through\n" 2867 "case 2: x = 8;\n" 2868 "// comment\n" 2869 "case 3:\n" 2870 " return; /* comment line 1\n" 2871 " * comment line 2 */\n" 2872 "case 4: i = 8;\n" 2873 "// something else\n" 2874 "#if FOO\n" 2875 "case 5: break;\n" 2876 "#endif\n" 2877 "}", 2878 format("switch (a) {\n" 2879 "case 1: x = 8;\n" 2880 " // fall through\n" 2881 "case 2:\n" 2882 " x = 8;\n" 2883 "// comment\n" 2884 "case 3:\n" 2885 " return; /* comment line 1\n" 2886 " * comment line 2 */\n" 2887 "case 4:\n" 2888 " i = 8;\n" 2889 "// something else\n" 2890 "#if FOO\n" 2891 "case 5: break;\n" 2892 "#endif\n" 2893 "}", 2894 Style)); 2895 EXPECT_EQ("switch (a) {\n" 2896 "case 0:\n" 2897 " return; // long long long long long long long long long long " 2898 "long long comment\n" 2899 " // line\n" 2900 "}", 2901 format("switch (a) {\n" 2902 "case 0: return; // long long long long long long long long " 2903 "long long long long comment line\n" 2904 "}", 2905 Style)); 2906 EXPECT_EQ("switch (a) {\n" 2907 "case 0:\n" 2908 " return; /* long long long long long long long long long long " 2909 "long long comment\n" 2910 " line */\n" 2911 "}", 2912 format("switch (a) {\n" 2913 "case 0: return; /* long long long long long long long long " 2914 "long long long long comment line */\n" 2915 "}", 2916 Style)); 2917 verifyFormat("switch (a) {\n" 2918 "#if FOO\n" 2919 "case 0: return 0;\n" 2920 "#endif\n" 2921 "}", 2922 Style); 2923 verifyFormat("switch (a) {\n" 2924 "case 1: {\n" 2925 "}\n" 2926 "case 2: {\n" 2927 " return;\n" 2928 "}\n" 2929 "case 3: {\n" 2930 " x = 1;\n" 2931 " return;\n" 2932 "}\n" 2933 "case 4:\n" 2934 " if (x)\n" 2935 " return;\n" 2936 "}", 2937 Style); 2938 Style.ColumnLimit = 21; 2939 verifyFormat("switch (a) {\n" 2940 "case 1: x = 1; break;\n" 2941 "case 2: return;\n" 2942 "case 3:\n" 2943 "case 4:\n" 2944 "case 5: return;\n" 2945 "default:\n" 2946 " y = 1;\n" 2947 " break;\n" 2948 "}", 2949 Style); 2950 Style.ColumnLimit = 80; 2951 Style.AllowShortCaseLabelsOnASingleLine = false; 2952 Style.IndentCaseLabels = true; 2953 EXPECT_EQ("switch (n) {\n" 2954 " default /*comments*/:\n" 2955 " return true;\n" 2956 " case 0:\n" 2957 " return false;\n" 2958 "}", 2959 format("switch (n) {\n" 2960 "default/*comments*/:\n" 2961 " return true;\n" 2962 "case 0:\n" 2963 " return false;\n" 2964 "}", 2965 Style)); 2966 Style.AllowShortCaseLabelsOnASingleLine = true; 2967 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2968 Style.BraceWrapping.AfterCaseLabel = true; 2969 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 2970 EXPECT_EQ("switch (n)\n" 2971 "{\n" 2972 " case 0:\n" 2973 " {\n" 2974 " return false;\n" 2975 " }\n" 2976 " default:\n" 2977 " {\n" 2978 " return true;\n" 2979 " }\n" 2980 "}", 2981 format("switch (n) {\n" 2982 " case 0: {\n" 2983 " return false;\n" 2984 " }\n" 2985 " default:\n" 2986 " {\n" 2987 " return true;\n" 2988 " }\n" 2989 "}", 2990 Style)); 2991 } 2992 2993 TEST_F(FormatTest, FormatsLabels) { 2994 verifyFormat("void f() {\n" 2995 " some_code();\n" 2996 "test_label:\n" 2997 " some_other_code();\n" 2998 " {\n" 2999 " some_more_code();\n" 3000 " another_label:\n" 3001 " some_more_code();\n" 3002 " }\n" 3003 "}"); 3004 verifyFormat("{\n" 3005 " some_code();\n" 3006 "test_label:\n" 3007 " some_other_code();\n" 3008 "}"); 3009 verifyFormat("{\n" 3010 " some_code();\n" 3011 "test_label:;\n" 3012 " int i = 0;\n" 3013 "}"); 3014 FormatStyle Style = getLLVMStyle(); 3015 Style.IndentGotoLabels = false; 3016 verifyFormat("void f() {\n" 3017 " some_code();\n" 3018 "test_label:\n" 3019 " some_other_code();\n" 3020 " {\n" 3021 " some_more_code();\n" 3022 "another_label:\n" 3023 " some_more_code();\n" 3024 " }\n" 3025 "}", 3026 Style); 3027 verifyFormat("{\n" 3028 " some_code();\n" 3029 "test_label:\n" 3030 " some_other_code();\n" 3031 "}", 3032 Style); 3033 verifyFormat("{\n" 3034 " some_code();\n" 3035 "test_label:;\n" 3036 " int i = 0;\n" 3037 "}"); 3038 } 3039 3040 TEST_F(FormatTest, MultiLineControlStatements) { 3041 FormatStyle Style = getLLVMStyleWithColumns(20); 3042 Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom; 3043 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine; 3044 // Short lines should keep opening brace on same line. 3045 EXPECT_EQ("if (foo) {\n" 3046 " bar();\n" 3047 "}", 3048 format("if(foo){bar();}", Style)); 3049 EXPECT_EQ("if (foo) {\n" 3050 " bar();\n" 3051 "} else {\n" 3052 " baz();\n" 3053 "}", 3054 format("if(foo){bar();}else{baz();}", Style)); 3055 EXPECT_EQ("if (foo && bar) {\n" 3056 " baz();\n" 3057 "}", 3058 format("if(foo&&bar){baz();}", Style)); 3059 EXPECT_EQ("if (foo) {\n" 3060 " bar();\n" 3061 "} else if (baz) {\n" 3062 " quux();\n" 3063 "}", 3064 format("if(foo){bar();}else if(baz){quux();}", Style)); 3065 EXPECT_EQ( 3066 "if (foo) {\n" 3067 " bar();\n" 3068 "} else if (baz) {\n" 3069 " quux();\n" 3070 "} else {\n" 3071 " foobar();\n" 3072 "}", 3073 format("if(foo){bar();}else if(baz){quux();}else{foobar();}", Style)); 3074 EXPECT_EQ("for (;;) {\n" 3075 " foo();\n" 3076 "}", 3077 format("for(;;){foo();}")); 3078 EXPECT_EQ("while (1) {\n" 3079 " foo();\n" 3080 "}", 3081 format("while(1){foo();}", Style)); 3082 EXPECT_EQ("switch (foo) {\n" 3083 "case bar:\n" 3084 " return;\n" 3085 "}", 3086 format("switch(foo){case bar:return;}", Style)); 3087 EXPECT_EQ("try {\n" 3088 " foo();\n" 3089 "} catch (...) {\n" 3090 " bar();\n" 3091 "}", 3092 format("try{foo();}catch(...){bar();}", Style)); 3093 EXPECT_EQ("do {\n" 3094 " foo();\n" 3095 "} while (bar &&\n" 3096 " baz);", 3097 format("do{foo();}while(bar&&baz);", Style)); 3098 // Long lines should put opening brace on new line. 3099 verifyFormat("void f() {\n" 3100 " if (a1 && a2 &&\n" 3101 " a3)\n" 3102 " {\n" 3103 " quux();\n" 3104 " }\n" 3105 "}", 3106 "void f(){if(a1&&a2&&a3){quux();}}", Style); 3107 EXPECT_EQ("if (foo && bar &&\n" 3108 " baz)\n" 3109 "{\n" 3110 " quux();\n" 3111 "}", 3112 format("if(foo&&bar&&baz){quux();}", Style)); 3113 EXPECT_EQ("if (foo && bar &&\n" 3114 " baz)\n" 3115 "{\n" 3116 " quux();\n" 3117 "}", 3118 format("if (foo && bar &&\n" 3119 " baz) {\n" 3120 " quux();\n" 3121 "}", 3122 Style)); 3123 EXPECT_EQ("if (foo) {\n" 3124 " bar();\n" 3125 "} else if (baz ||\n" 3126 " quux)\n" 3127 "{\n" 3128 " foobar();\n" 3129 "}", 3130 format("if(foo){bar();}else if(baz||quux){foobar();}", Style)); 3131 EXPECT_EQ( 3132 "if (foo) {\n" 3133 " bar();\n" 3134 "} else if (baz ||\n" 3135 " quux)\n" 3136 "{\n" 3137 " foobar();\n" 3138 "} else {\n" 3139 " barbaz();\n" 3140 "}", 3141 format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}", 3142 Style)); 3143 EXPECT_EQ("for (int i = 0;\n" 3144 " i < 10; ++i)\n" 3145 "{\n" 3146 " foo();\n" 3147 "}", 3148 format("for(int i=0;i<10;++i){foo();}", Style)); 3149 EXPECT_EQ("foreach (int i,\n" 3150 " list)\n" 3151 "{\n" 3152 " foo();\n" 3153 "}", 3154 format("foreach(int i, list){foo();}", Style)); 3155 Style.ColumnLimit = 3156 40; // to concentrate at brace wrapping, not line wrap due to column limit 3157 EXPECT_EQ("foreach (int i, list) {\n" 3158 " foo();\n" 3159 "}", 3160 format("foreach(int i, list){foo();}", Style)); 3161 Style.ColumnLimit = 3162 20; // to concentrate at brace wrapping, not line wrap due to column limit 3163 EXPECT_EQ("while (foo || bar ||\n" 3164 " baz)\n" 3165 "{\n" 3166 " quux();\n" 3167 "}", 3168 format("while(foo||bar||baz){quux();}", Style)); 3169 EXPECT_EQ("switch (\n" 3170 " foo = barbaz)\n" 3171 "{\n" 3172 "case quux:\n" 3173 " return;\n" 3174 "}", 3175 format("switch(foo=barbaz){case quux:return;}", Style)); 3176 EXPECT_EQ("try {\n" 3177 " foo();\n" 3178 "} catch (\n" 3179 " Exception &bar)\n" 3180 "{\n" 3181 " baz();\n" 3182 "}", 3183 format("try{foo();}catch(Exception&bar){baz();}", Style)); 3184 Style.ColumnLimit = 3185 40; // to concentrate at brace wrapping, not line wrap due to column limit 3186 EXPECT_EQ("try {\n" 3187 " foo();\n" 3188 "} catch (Exception &bar) {\n" 3189 " baz();\n" 3190 "}", 3191 format("try{foo();}catch(Exception&bar){baz();}", Style)); 3192 Style.ColumnLimit = 3193 20; // to concentrate at brace wrapping, not line wrap due to column limit 3194 3195 Style.BraceWrapping.BeforeElse = true; 3196 EXPECT_EQ( 3197 "if (foo) {\n" 3198 " bar();\n" 3199 "}\n" 3200 "else if (baz ||\n" 3201 " quux)\n" 3202 "{\n" 3203 " foobar();\n" 3204 "}\n" 3205 "else {\n" 3206 " barbaz();\n" 3207 "}", 3208 format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}", 3209 Style)); 3210 3211 Style.BraceWrapping.BeforeCatch = true; 3212 EXPECT_EQ("try {\n" 3213 " foo();\n" 3214 "}\n" 3215 "catch (...) {\n" 3216 " baz();\n" 3217 "}", 3218 format("try{foo();}catch(...){baz();}", Style)); 3219 3220 Style.BraceWrapping.AfterFunction = true; 3221 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine; 3222 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 3223 Style.ColumnLimit = 80; 3224 verifyFormat("void shortfunction() { bar(); }", Style); 3225 3226 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 3227 verifyFormat("void shortfunction()\n" 3228 "{\n" 3229 " bar();\n" 3230 "}", 3231 Style); 3232 } 3233 3234 TEST_F(FormatTest, BeforeWhile) { 3235 FormatStyle Style = getLLVMStyle(); 3236 Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom; 3237 3238 verifyFormat("do {\n" 3239 " foo();\n" 3240 "} while (1);", 3241 Style); 3242 Style.BraceWrapping.BeforeWhile = true; 3243 verifyFormat("do {\n" 3244 " foo();\n" 3245 "}\n" 3246 "while (1);", 3247 Style); 3248 } 3249 3250 //===----------------------------------------------------------------------===// 3251 // Tests for classes, namespaces, etc. 3252 //===----------------------------------------------------------------------===// 3253 3254 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) { 3255 verifyFormat("class A {};"); 3256 } 3257 3258 TEST_F(FormatTest, UnderstandsAccessSpecifiers) { 3259 verifyFormat("class A {\n" 3260 "public:\n" 3261 "public: // comment\n" 3262 "protected:\n" 3263 "private:\n" 3264 " void f() {}\n" 3265 "};"); 3266 verifyFormat("export class A {\n" 3267 "public:\n" 3268 "public: // comment\n" 3269 "protected:\n" 3270 "private:\n" 3271 " void f() {}\n" 3272 "};"); 3273 verifyGoogleFormat("class A {\n" 3274 " public:\n" 3275 " protected:\n" 3276 " private:\n" 3277 " void f() {}\n" 3278 "};"); 3279 verifyGoogleFormat("export class A {\n" 3280 " public:\n" 3281 " protected:\n" 3282 " private:\n" 3283 " void f() {}\n" 3284 "};"); 3285 verifyFormat("class A {\n" 3286 "public slots:\n" 3287 " void f1() {}\n" 3288 "public Q_SLOTS:\n" 3289 " void f2() {}\n" 3290 "protected slots:\n" 3291 " void f3() {}\n" 3292 "protected Q_SLOTS:\n" 3293 " void f4() {}\n" 3294 "private slots:\n" 3295 " void f5() {}\n" 3296 "private Q_SLOTS:\n" 3297 " void f6() {}\n" 3298 "signals:\n" 3299 " void g1();\n" 3300 "Q_SIGNALS:\n" 3301 " void g2();\n" 3302 "};"); 3303 3304 // Don't interpret 'signals' the wrong way. 3305 verifyFormat("signals.set();"); 3306 verifyFormat("for (Signals signals : f()) {\n}"); 3307 verifyFormat("{\n" 3308 " signals.set(); // This needs indentation.\n" 3309 "}"); 3310 verifyFormat("void f() {\n" 3311 "label:\n" 3312 " signals.baz();\n" 3313 "}"); 3314 verifyFormat("private[1];"); 3315 verifyFormat("testArray[public] = 1;"); 3316 verifyFormat("public();"); 3317 verifyFormat("myFunc(public);"); 3318 verifyFormat("std::vector<int> testVec = {private};"); 3319 verifyFormat("private.p = 1;"); 3320 verifyFormat("void function(private...){};"); 3321 verifyFormat("if (private && public)\n"); 3322 verifyFormat("private &= true;"); 3323 verifyFormat("int x = private * public;"); 3324 verifyFormat("public *= private;"); 3325 verifyFormat("int x = public + private;"); 3326 verifyFormat("private++;"); 3327 verifyFormat("++private;"); 3328 verifyFormat("public += private;"); 3329 verifyFormat("public = public - private;"); 3330 verifyFormat("public->foo();"); 3331 verifyFormat("private--;"); 3332 verifyFormat("--private;"); 3333 verifyFormat("public -= 1;"); 3334 verifyFormat("if (!private && !public)\n"); 3335 verifyFormat("public != private;"); 3336 verifyFormat("int x = public / private;"); 3337 verifyFormat("public /= 2;"); 3338 verifyFormat("public = public % 2;"); 3339 verifyFormat("public %= 2;"); 3340 verifyFormat("if (public < private)\n"); 3341 verifyFormat("public << private;"); 3342 verifyFormat("public <<= private;"); 3343 verifyFormat("if (public > private)\n"); 3344 verifyFormat("public >> private;"); 3345 verifyFormat("public >>= private;"); 3346 verifyFormat("public ^ private;"); 3347 verifyFormat("public ^= private;"); 3348 verifyFormat("public | private;"); 3349 verifyFormat("public |= private;"); 3350 verifyFormat("auto x = private ? 1 : 2;"); 3351 verifyFormat("if (public == private)\n"); 3352 verifyFormat("void foo(public, private)"); 3353 verifyFormat("public::foo();"); 3354 3355 verifyFormat("class A {\n" 3356 "public:\n" 3357 " std::unique_ptr<int *[]> b() { return nullptr; }\n" 3358 "\n" 3359 "private:\n" 3360 " int c;\n" 3361 "};"); 3362 } 3363 3364 TEST_F(FormatTest, SeparatesLogicalBlocks) { 3365 EXPECT_EQ("class A {\n" 3366 "public:\n" 3367 " void f();\n" 3368 "\n" 3369 "private:\n" 3370 " void g() {}\n" 3371 " // test\n" 3372 "protected:\n" 3373 " int h;\n" 3374 "};", 3375 format("class A {\n" 3376 "public:\n" 3377 "void f();\n" 3378 "private:\n" 3379 "void g() {}\n" 3380 "// test\n" 3381 "protected:\n" 3382 "int h;\n" 3383 "};")); 3384 EXPECT_EQ("class A {\n" 3385 "protected:\n" 3386 "public:\n" 3387 " void f();\n" 3388 "};", 3389 format("class A {\n" 3390 "protected:\n" 3391 "\n" 3392 "public:\n" 3393 "\n" 3394 " void f();\n" 3395 "};")); 3396 3397 // Even ensure proper spacing inside macros. 3398 EXPECT_EQ("#define B \\\n" 3399 " class A { \\\n" 3400 " protected: \\\n" 3401 " public: \\\n" 3402 " void f(); \\\n" 3403 " };", 3404 format("#define B \\\n" 3405 " class A { \\\n" 3406 " protected: \\\n" 3407 " \\\n" 3408 " public: \\\n" 3409 " \\\n" 3410 " void f(); \\\n" 3411 " };", 3412 getGoogleStyle())); 3413 // But don't remove empty lines after macros ending in access specifiers. 3414 EXPECT_EQ("#define A private:\n" 3415 "\n" 3416 "int i;", 3417 format("#define A private:\n" 3418 "\n" 3419 "int i;")); 3420 } 3421 3422 TEST_F(FormatTest, FormatsClasses) { 3423 verifyFormat("class A : public B {};"); 3424 verifyFormat("class A : public ::B {};"); 3425 3426 verifyFormat( 3427 "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3428 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};"); 3429 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n" 3430 " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3431 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};"); 3432 verifyFormat( 3433 "class A : public B, public C, public D, public E, public F {};"); 3434 verifyFormat("class AAAAAAAAAAAA : public B,\n" 3435 " public C,\n" 3436 " public D,\n" 3437 " public E,\n" 3438 " public F,\n" 3439 " public G {};"); 3440 3441 verifyFormat("class\n" 3442 " ReallyReallyLongClassName {\n" 3443 " int i;\n" 3444 "};", 3445 getLLVMStyleWithColumns(32)); 3446 verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n" 3447 " aaaaaaaaaaaaaaaa> {};"); 3448 verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n" 3449 " : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n" 3450 " aaaaaaaaaaaaaaaaaaaaaa> {};"); 3451 verifyFormat("template <class R, class C>\n" 3452 "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n" 3453 " : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};"); 3454 verifyFormat("class ::A::B {};"); 3455 } 3456 3457 TEST_F(FormatTest, BreakInheritanceStyle) { 3458 FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle(); 3459 StyleWithInheritanceBreakBeforeComma.BreakInheritanceList = 3460 FormatStyle::BILS_BeforeComma; 3461 verifyFormat("class MyClass : public X {};", 3462 StyleWithInheritanceBreakBeforeComma); 3463 verifyFormat("class MyClass\n" 3464 " : public X\n" 3465 " , public Y {};", 3466 StyleWithInheritanceBreakBeforeComma); 3467 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n" 3468 " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n" 3469 " , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};", 3470 StyleWithInheritanceBreakBeforeComma); 3471 verifyFormat("struct aaaaaaaaaaaaa\n" 3472 " : public aaaaaaaaaaaaaaaaaaa< // break\n" 3473 " aaaaaaaaaaaaaaaa> {};", 3474 StyleWithInheritanceBreakBeforeComma); 3475 3476 FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle(); 3477 StyleWithInheritanceBreakAfterColon.BreakInheritanceList = 3478 FormatStyle::BILS_AfterColon; 3479 verifyFormat("class MyClass : public X {};", 3480 StyleWithInheritanceBreakAfterColon); 3481 verifyFormat("class MyClass : public X, public Y {};", 3482 StyleWithInheritanceBreakAfterColon); 3483 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n" 3484 " public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3485 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};", 3486 StyleWithInheritanceBreakAfterColon); 3487 verifyFormat("struct aaaaaaaaaaaaa :\n" 3488 " public aaaaaaaaaaaaaaaaaaa< // break\n" 3489 " aaaaaaaaaaaaaaaa> {};", 3490 StyleWithInheritanceBreakAfterColon); 3491 3492 FormatStyle StyleWithInheritanceBreakAfterComma = getLLVMStyle(); 3493 StyleWithInheritanceBreakAfterComma.BreakInheritanceList = 3494 FormatStyle::BILS_AfterComma; 3495 verifyFormat("class MyClass : public X {};", 3496 StyleWithInheritanceBreakAfterComma); 3497 verifyFormat("class MyClass : public X,\n" 3498 " public Y {};", 3499 StyleWithInheritanceBreakAfterComma); 3500 verifyFormat( 3501 "class AAAAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3502 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC " 3503 "{};", 3504 StyleWithInheritanceBreakAfterComma); 3505 verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n" 3506 " aaaaaaaaaaaaaaaa> {};", 3507 StyleWithInheritanceBreakAfterComma); 3508 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n" 3509 " : public OnceBreak,\n" 3510 " public AlwaysBreak,\n" 3511 " EvenBasesFitInOneLine {};", 3512 StyleWithInheritanceBreakAfterComma); 3513 } 3514 3515 TEST_F(FormatTest, FormatsVariableDeclarationsAfterRecord) { 3516 verifyFormat("class A {\n} a, b;"); 3517 verifyFormat("struct A {\n} a, b;"); 3518 verifyFormat("union A {\n} a, b;"); 3519 3520 verifyFormat("constexpr class A {\n} a, b;"); 3521 verifyFormat("constexpr struct A {\n} a, b;"); 3522 verifyFormat("constexpr union A {\n} a, b;"); 3523 3524 verifyFormat("namespace {\nclass A {\n} a, b;\n} // namespace"); 3525 verifyFormat("namespace {\nstruct A {\n} a, b;\n} // namespace"); 3526 verifyFormat("namespace {\nunion A {\n} a, b;\n} // namespace"); 3527 3528 verifyFormat("namespace {\nconstexpr class A {\n} a, b;\n} // namespace"); 3529 verifyFormat("namespace {\nconstexpr struct A {\n} a, b;\n} // namespace"); 3530 verifyFormat("namespace {\nconstexpr union A {\n} a, b;\n} // namespace"); 3531 3532 verifyFormat("namespace ns {\n" 3533 "class {\n" 3534 "} a, b;\n" 3535 "} // namespace ns"); 3536 verifyFormat("namespace ns {\n" 3537 "const class {\n" 3538 "} a, b;\n" 3539 "} // namespace ns"); 3540 verifyFormat("namespace ns {\n" 3541 "constexpr class C {\n" 3542 "} a, b;\n" 3543 "} // namespace ns"); 3544 verifyFormat("namespace ns {\n" 3545 "class { /* comment */\n" 3546 "} a, b;\n" 3547 "} // namespace ns"); 3548 verifyFormat("namespace ns {\n" 3549 "const class { /* comment */\n" 3550 "} a, b;\n" 3551 "} // namespace ns"); 3552 } 3553 3554 TEST_F(FormatTest, FormatsEnum) { 3555 verifyFormat("enum {\n" 3556 " Zero,\n" 3557 " One = 1,\n" 3558 " Two = One + 1,\n" 3559 " Three = (One + Two),\n" 3560 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3561 " Five = (One, Two, Three, Four, 5)\n" 3562 "};"); 3563 verifyGoogleFormat("enum {\n" 3564 " Zero,\n" 3565 " One = 1,\n" 3566 " Two = One + 1,\n" 3567 " Three = (One + Two),\n" 3568 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3569 " Five = (One, Two, Three, Four, 5)\n" 3570 "};"); 3571 verifyFormat("enum Enum {};"); 3572 verifyFormat("enum {};"); 3573 verifyFormat("enum X E {} d;"); 3574 verifyFormat("enum __attribute__((...)) E {} d;"); 3575 verifyFormat("enum __declspec__((...)) E {} d;"); 3576 verifyFormat("enum [[nodiscard]] E {} d;"); 3577 verifyFormat("enum {\n" 3578 " Bar = Foo<int, int>::value\n" 3579 "};", 3580 getLLVMStyleWithColumns(30)); 3581 3582 verifyFormat("enum ShortEnum { A, B, C };"); 3583 verifyGoogleFormat("enum ShortEnum { A, B, C };"); 3584 3585 EXPECT_EQ("enum KeepEmptyLines {\n" 3586 " ONE,\n" 3587 "\n" 3588 " TWO,\n" 3589 "\n" 3590 " THREE\n" 3591 "}", 3592 format("enum KeepEmptyLines {\n" 3593 " ONE,\n" 3594 "\n" 3595 " TWO,\n" 3596 "\n" 3597 "\n" 3598 " THREE\n" 3599 "}")); 3600 verifyFormat("enum E { // comment\n" 3601 " ONE,\n" 3602 " TWO\n" 3603 "};\n" 3604 "int i;"); 3605 3606 FormatStyle EightIndent = getLLVMStyle(); 3607 EightIndent.IndentWidth = 8; 3608 verifyFormat("enum {\n" 3609 " VOID,\n" 3610 " CHAR,\n" 3611 " SHORT,\n" 3612 " INT,\n" 3613 " LONG,\n" 3614 " SIGNED,\n" 3615 " UNSIGNED,\n" 3616 " BOOL,\n" 3617 " FLOAT,\n" 3618 " DOUBLE,\n" 3619 " COMPLEX\n" 3620 "};", 3621 EightIndent); 3622 3623 verifyFormat("enum [[nodiscard]] E {\n" 3624 " ONE,\n" 3625 " TWO,\n" 3626 "};"); 3627 verifyFormat("enum [[nodiscard]] E {\n" 3628 " // Comment 1\n" 3629 " ONE,\n" 3630 " // Comment 2\n" 3631 " TWO,\n" 3632 "};"); 3633 3634 // Not enums. 3635 verifyFormat("enum X f() {\n" 3636 " a();\n" 3637 " return 42;\n" 3638 "}"); 3639 verifyFormat("enum X Type::f() {\n" 3640 " a();\n" 3641 " return 42;\n" 3642 "}"); 3643 verifyFormat("enum ::X f() {\n" 3644 " a();\n" 3645 " return 42;\n" 3646 "}"); 3647 verifyFormat("enum ns::X f() {\n" 3648 " a();\n" 3649 " return 42;\n" 3650 "}"); 3651 } 3652 3653 TEST_F(FormatTest, FormatsEnumsWithErrors) { 3654 verifyFormat("enum Type {\n" 3655 " One = 0; // These semicolons should be commas.\n" 3656 " Two = 1;\n" 3657 "};"); 3658 verifyFormat("namespace n {\n" 3659 "enum Type {\n" 3660 " One,\n" 3661 " Two, // missing };\n" 3662 " int i;\n" 3663 "}\n" 3664 "void g() {}"); 3665 } 3666 3667 TEST_F(FormatTest, FormatsEnumStruct) { 3668 verifyFormat("enum struct {\n" 3669 " Zero,\n" 3670 " One = 1,\n" 3671 " Two = One + 1,\n" 3672 " Three = (One + Two),\n" 3673 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3674 " Five = (One, Two, Three, Four, 5)\n" 3675 "};"); 3676 verifyFormat("enum struct Enum {};"); 3677 verifyFormat("enum struct {};"); 3678 verifyFormat("enum struct X E {} d;"); 3679 verifyFormat("enum struct __attribute__((...)) E {} d;"); 3680 verifyFormat("enum struct __declspec__((...)) E {} d;"); 3681 verifyFormat("enum struct [[nodiscard]] E {} d;"); 3682 verifyFormat("enum struct X f() {\n a();\n return 42;\n}"); 3683 3684 verifyFormat("enum struct [[nodiscard]] E {\n" 3685 " ONE,\n" 3686 " TWO,\n" 3687 "};"); 3688 verifyFormat("enum struct [[nodiscard]] E {\n" 3689 " // Comment 1\n" 3690 " ONE,\n" 3691 " // Comment 2\n" 3692 " TWO,\n" 3693 "};"); 3694 } 3695 3696 TEST_F(FormatTest, FormatsEnumClass) { 3697 verifyFormat("enum class {\n" 3698 " Zero,\n" 3699 " One = 1,\n" 3700 " Two = One + 1,\n" 3701 " Three = (One + Two),\n" 3702 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3703 " Five = (One, Two, Three, Four, 5)\n" 3704 "};"); 3705 verifyFormat("enum class Enum {};"); 3706 verifyFormat("enum class {};"); 3707 verifyFormat("enum class X E {} d;"); 3708 verifyFormat("enum class __attribute__((...)) E {} d;"); 3709 verifyFormat("enum class __declspec__((...)) E {} d;"); 3710 verifyFormat("enum class [[nodiscard]] E {} d;"); 3711 verifyFormat("enum class X f() {\n a();\n return 42;\n}"); 3712 3713 verifyFormat("enum class [[nodiscard]] E {\n" 3714 " ONE,\n" 3715 " TWO,\n" 3716 "};"); 3717 verifyFormat("enum class [[nodiscard]] E {\n" 3718 " // Comment 1\n" 3719 " ONE,\n" 3720 " // Comment 2\n" 3721 " TWO,\n" 3722 "};"); 3723 } 3724 3725 TEST_F(FormatTest, FormatsEnumTypes) { 3726 verifyFormat("enum X : int {\n" 3727 " A, // Force multiple lines.\n" 3728 " B\n" 3729 "};"); 3730 verifyFormat("enum X : int { A, B };"); 3731 verifyFormat("enum X : std::uint32_t { A, B };"); 3732 } 3733 3734 TEST_F(FormatTest, FormatsTypedefEnum) { 3735 FormatStyle Style = getLLVMStyleWithColumns(40); 3736 verifyFormat("typedef enum {} EmptyEnum;"); 3737 verifyFormat("typedef enum { A, B, C } ShortEnum;"); 3738 verifyFormat("typedef enum {\n" 3739 " ZERO = 0,\n" 3740 " ONE = 1,\n" 3741 " TWO = 2,\n" 3742 " THREE = 3\n" 3743 "} LongEnum;", 3744 Style); 3745 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 3746 Style.BraceWrapping.AfterEnum = true; 3747 verifyFormat("typedef enum {} EmptyEnum;"); 3748 verifyFormat("typedef enum { A, B, C } ShortEnum;"); 3749 verifyFormat("typedef enum\n" 3750 "{\n" 3751 " ZERO = 0,\n" 3752 " ONE = 1,\n" 3753 " TWO = 2,\n" 3754 " THREE = 3\n" 3755 "} LongEnum;", 3756 Style); 3757 } 3758 3759 TEST_F(FormatTest, FormatsNSEnums) { 3760 verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }"); 3761 verifyGoogleFormat( 3762 "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }"); 3763 verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n" 3764 " // Information about someDecentlyLongValue.\n" 3765 " someDecentlyLongValue,\n" 3766 " // Information about anotherDecentlyLongValue.\n" 3767 " anotherDecentlyLongValue,\n" 3768 " // Information about aThirdDecentlyLongValue.\n" 3769 " aThirdDecentlyLongValue\n" 3770 "};"); 3771 verifyGoogleFormat("typedef NS_CLOSED_ENUM(NSInteger, MyType) {\n" 3772 " // Information about someDecentlyLongValue.\n" 3773 " someDecentlyLongValue,\n" 3774 " // Information about anotherDecentlyLongValue.\n" 3775 " anotherDecentlyLongValue,\n" 3776 " // Information about aThirdDecentlyLongValue.\n" 3777 " aThirdDecentlyLongValue\n" 3778 "};"); 3779 verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n" 3780 " a = 1,\n" 3781 " b = 2,\n" 3782 " c = 3,\n" 3783 "};"); 3784 verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n" 3785 " a = 1,\n" 3786 " b = 2,\n" 3787 " c = 3,\n" 3788 "};"); 3789 verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n" 3790 " a = 1,\n" 3791 " b = 2,\n" 3792 " c = 3,\n" 3793 "};"); 3794 verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n" 3795 " a = 1,\n" 3796 " b = 2,\n" 3797 " c = 3,\n" 3798 "};"); 3799 } 3800 3801 TEST_F(FormatTest, FormatsBitfields) { 3802 verifyFormat("struct Bitfields {\n" 3803 " unsigned sClass : 8;\n" 3804 " unsigned ValueKind : 2;\n" 3805 "};"); 3806 verifyFormat("struct A {\n" 3807 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n" 3808 " bbbbbbbbbbbbbbbbbbbbbbbbb;\n" 3809 "};"); 3810 verifyFormat("struct MyStruct {\n" 3811 " uchar data;\n" 3812 " uchar : 8;\n" 3813 " uchar : 8;\n" 3814 " uchar other;\n" 3815 "};"); 3816 FormatStyle Style = getLLVMStyle(); 3817 Style.BitFieldColonSpacing = FormatStyle::BFCS_None; 3818 verifyFormat("struct Bitfields {\n" 3819 " unsigned sClass:8;\n" 3820 " unsigned ValueKind:2;\n" 3821 " uchar other;\n" 3822 "};", 3823 Style); 3824 verifyFormat("struct A {\n" 3825 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:1,\n" 3826 " bbbbbbbbbbbbbbbbbbbbbbbbb:2;\n" 3827 "};", 3828 Style); 3829 Style.BitFieldColonSpacing = FormatStyle::BFCS_Before; 3830 verifyFormat("struct Bitfields {\n" 3831 " unsigned sClass :8;\n" 3832 " unsigned ValueKind :2;\n" 3833 " uchar other;\n" 3834 "};", 3835 Style); 3836 Style.BitFieldColonSpacing = FormatStyle::BFCS_After; 3837 verifyFormat("struct Bitfields {\n" 3838 " unsigned sClass: 8;\n" 3839 " unsigned ValueKind: 2;\n" 3840 " uchar other;\n" 3841 "};", 3842 Style); 3843 } 3844 3845 TEST_F(FormatTest, FormatsNamespaces) { 3846 FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle(); 3847 LLVMWithNoNamespaceFix.FixNamespaceComments = false; 3848 3849 verifyFormat("namespace some_namespace {\n" 3850 "class A {};\n" 3851 "void f() { f(); }\n" 3852 "}", 3853 LLVMWithNoNamespaceFix); 3854 verifyFormat("#define M(x) x##x\n" 3855 "namespace M(x) {\n" 3856 "class A {};\n" 3857 "void f() { f(); }\n" 3858 "}", 3859 LLVMWithNoNamespaceFix); 3860 verifyFormat("#define M(x) x##x\n" 3861 "namespace N::inline M(x) {\n" 3862 "class A {};\n" 3863 "void f() { f(); }\n" 3864 "}", 3865 LLVMWithNoNamespaceFix); 3866 verifyFormat("#define M(x) x##x\n" 3867 "namespace M(x)::inline N {\n" 3868 "class A {};\n" 3869 "void f() { f(); }\n" 3870 "}", 3871 LLVMWithNoNamespaceFix); 3872 verifyFormat("#define M(x) x##x\n" 3873 "namespace N::M(x) {\n" 3874 "class A {};\n" 3875 "void f() { f(); }\n" 3876 "}", 3877 LLVMWithNoNamespaceFix); 3878 verifyFormat("#define M(x) x##x\n" 3879 "namespace M::N(x) {\n" 3880 "class A {};\n" 3881 "void f() { f(); }\n" 3882 "}", 3883 LLVMWithNoNamespaceFix); 3884 verifyFormat("namespace N::inline D {\n" 3885 "class A {};\n" 3886 "void f() { f(); }\n" 3887 "}", 3888 LLVMWithNoNamespaceFix); 3889 verifyFormat("namespace N::inline D::E {\n" 3890 "class A {};\n" 3891 "void f() { f(); }\n" 3892 "}", 3893 LLVMWithNoNamespaceFix); 3894 verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n" 3895 "class A {};\n" 3896 "void f() { f(); }\n" 3897 "}", 3898 LLVMWithNoNamespaceFix); 3899 verifyFormat("/* something */ namespace some_namespace {\n" 3900 "class A {};\n" 3901 "void f() { f(); }\n" 3902 "}", 3903 LLVMWithNoNamespaceFix); 3904 verifyFormat("namespace {\n" 3905 "class A {};\n" 3906 "void f() { f(); }\n" 3907 "}", 3908 LLVMWithNoNamespaceFix); 3909 verifyFormat("/* something */ namespace {\n" 3910 "class A {};\n" 3911 "void f() { f(); }\n" 3912 "}", 3913 LLVMWithNoNamespaceFix); 3914 verifyFormat("inline namespace X {\n" 3915 "class A {};\n" 3916 "void f() { f(); }\n" 3917 "}", 3918 LLVMWithNoNamespaceFix); 3919 verifyFormat("/* something */ inline namespace X {\n" 3920 "class A {};\n" 3921 "void f() { f(); }\n" 3922 "}", 3923 LLVMWithNoNamespaceFix); 3924 verifyFormat("export namespace X {\n" 3925 "class A {};\n" 3926 "void f() { f(); }\n" 3927 "}", 3928 LLVMWithNoNamespaceFix); 3929 verifyFormat("using namespace some_namespace;\n" 3930 "class A {};\n" 3931 "void f() { f(); }", 3932 LLVMWithNoNamespaceFix); 3933 3934 // This code is more common than we thought; if we 3935 // layout this correctly the semicolon will go into 3936 // its own line, which is undesirable. 3937 verifyFormat("namespace {};", LLVMWithNoNamespaceFix); 3938 verifyFormat("namespace {\n" 3939 "class A {};\n" 3940 "};", 3941 LLVMWithNoNamespaceFix); 3942 3943 verifyFormat("namespace {\n" 3944 "int SomeVariable = 0; // comment\n" 3945 "} // namespace", 3946 LLVMWithNoNamespaceFix); 3947 EXPECT_EQ("#ifndef HEADER_GUARD\n" 3948 "#define HEADER_GUARD\n" 3949 "namespace my_namespace {\n" 3950 "int i;\n" 3951 "} // my_namespace\n" 3952 "#endif // HEADER_GUARD", 3953 format("#ifndef HEADER_GUARD\n" 3954 " #define HEADER_GUARD\n" 3955 " namespace my_namespace {\n" 3956 "int i;\n" 3957 "} // my_namespace\n" 3958 "#endif // HEADER_GUARD", 3959 LLVMWithNoNamespaceFix)); 3960 3961 EXPECT_EQ("namespace A::B {\n" 3962 "class C {};\n" 3963 "}", 3964 format("namespace A::B {\n" 3965 "class C {};\n" 3966 "}", 3967 LLVMWithNoNamespaceFix)); 3968 3969 FormatStyle Style = getLLVMStyle(); 3970 Style.NamespaceIndentation = FormatStyle::NI_All; 3971 EXPECT_EQ("namespace out {\n" 3972 " int i;\n" 3973 " namespace in {\n" 3974 " int i;\n" 3975 " } // namespace in\n" 3976 "} // namespace out", 3977 format("namespace out {\n" 3978 "int i;\n" 3979 "namespace in {\n" 3980 "int i;\n" 3981 "} // namespace in\n" 3982 "} // namespace out", 3983 Style)); 3984 3985 FormatStyle ShortInlineFunctions = getLLVMStyle(); 3986 ShortInlineFunctions.NamespaceIndentation = FormatStyle::NI_All; 3987 ShortInlineFunctions.AllowShortFunctionsOnASingleLine = 3988 FormatStyle::SFS_Inline; 3989 verifyFormat("namespace {\n" 3990 " void f() {\n" 3991 " return;\n" 3992 " }\n" 3993 "} // namespace\n", 3994 ShortInlineFunctions); 3995 verifyFormat("namespace { /* comment */\n" 3996 " void f() {\n" 3997 " return;\n" 3998 " }\n" 3999 "} // namespace\n", 4000 ShortInlineFunctions); 4001 verifyFormat("namespace { // comment\n" 4002 " void f() {\n" 4003 " return;\n" 4004 " }\n" 4005 "} // namespace\n", 4006 ShortInlineFunctions); 4007 verifyFormat("namespace {\n" 4008 " int some_int;\n" 4009 " void f() {\n" 4010 " return;\n" 4011 " }\n" 4012 "} // namespace\n", 4013 ShortInlineFunctions); 4014 verifyFormat("namespace interface {\n" 4015 " void f() {\n" 4016 " return;\n" 4017 " }\n" 4018 "} // namespace interface\n", 4019 ShortInlineFunctions); 4020 verifyFormat("namespace {\n" 4021 " class X {\n" 4022 " void f() { return; }\n" 4023 " };\n" 4024 "} // namespace\n", 4025 ShortInlineFunctions); 4026 verifyFormat("namespace {\n" 4027 " class X { /* comment */\n" 4028 " void f() { return; }\n" 4029 " };\n" 4030 "} // namespace\n", 4031 ShortInlineFunctions); 4032 verifyFormat("namespace {\n" 4033 " class X { // comment\n" 4034 " void f() { return; }\n" 4035 " };\n" 4036 "} // namespace\n", 4037 ShortInlineFunctions); 4038 verifyFormat("namespace {\n" 4039 " struct X {\n" 4040 " void f() { return; }\n" 4041 " };\n" 4042 "} // namespace\n", 4043 ShortInlineFunctions); 4044 verifyFormat("namespace {\n" 4045 " union X {\n" 4046 " void f() { return; }\n" 4047 " };\n" 4048 "} // namespace\n", 4049 ShortInlineFunctions); 4050 verifyFormat("extern \"C\" {\n" 4051 "void f() {\n" 4052 " return;\n" 4053 "}\n" 4054 "} // namespace\n", 4055 ShortInlineFunctions); 4056 verifyFormat("namespace {\n" 4057 " class X {\n" 4058 " void f() { return; }\n" 4059 " } x;\n" 4060 "} // namespace\n", 4061 ShortInlineFunctions); 4062 verifyFormat("namespace {\n" 4063 " [[nodiscard]] class X {\n" 4064 " void f() { return; }\n" 4065 " };\n" 4066 "} // namespace\n", 4067 ShortInlineFunctions); 4068 verifyFormat("namespace {\n" 4069 " static class X {\n" 4070 " void f() { return; }\n" 4071 " } x;\n" 4072 "} // namespace\n", 4073 ShortInlineFunctions); 4074 verifyFormat("namespace {\n" 4075 " constexpr class X {\n" 4076 " void f() { return; }\n" 4077 " } x;\n" 4078 "} // namespace\n", 4079 ShortInlineFunctions); 4080 4081 ShortInlineFunctions.IndentExternBlock = FormatStyle::IEBS_Indent; 4082 verifyFormat("extern \"C\" {\n" 4083 " void f() {\n" 4084 " return;\n" 4085 " }\n" 4086 "} // namespace\n", 4087 ShortInlineFunctions); 4088 4089 Style.NamespaceIndentation = FormatStyle::NI_Inner; 4090 EXPECT_EQ("namespace out {\n" 4091 "int i;\n" 4092 "namespace in {\n" 4093 " int i;\n" 4094 "} // namespace in\n" 4095 "} // namespace out", 4096 format("namespace out {\n" 4097 "int i;\n" 4098 "namespace in {\n" 4099 "int i;\n" 4100 "} // namespace in\n" 4101 "} // namespace out", 4102 Style)); 4103 4104 Style.NamespaceIndentation = FormatStyle::NI_None; 4105 verifyFormat("template <class T>\n" 4106 "concept a_concept = X<>;\n" 4107 "namespace B {\n" 4108 "struct b_struct {};\n" 4109 "} // namespace B\n", 4110 Style); 4111 verifyFormat("template <int I>\n" 4112 "constexpr void foo()\n" 4113 " requires(I == 42)\n" 4114 "{}\n" 4115 "namespace ns {\n" 4116 "void foo() {}\n" 4117 "} // namespace ns\n", 4118 Style); 4119 } 4120 4121 TEST_F(FormatTest, NamespaceMacros) { 4122 FormatStyle Style = getLLVMStyle(); 4123 Style.NamespaceMacros.push_back("TESTSUITE"); 4124 4125 verifyFormat("TESTSUITE(A) {\n" 4126 "int foo();\n" 4127 "} // TESTSUITE(A)", 4128 Style); 4129 4130 verifyFormat("TESTSUITE(A, B) {\n" 4131 "int foo();\n" 4132 "} // TESTSUITE(A)", 4133 Style); 4134 4135 // Properly indent according to NamespaceIndentation style 4136 Style.NamespaceIndentation = FormatStyle::NI_All; 4137 verifyFormat("TESTSUITE(A) {\n" 4138 " int foo();\n" 4139 "} // TESTSUITE(A)", 4140 Style); 4141 verifyFormat("TESTSUITE(A) {\n" 4142 " namespace B {\n" 4143 " int foo();\n" 4144 " } // namespace B\n" 4145 "} // TESTSUITE(A)", 4146 Style); 4147 verifyFormat("namespace A {\n" 4148 " TESTSUITE(B) {\n" 4149 " int foo();\n" 4150 " } // TESTSUITE(B)\n" 4151 "} // namespace A", 4152 Style); 4153 4154 Style.NamespaceIndentation = FormatStyle::NI_Inner; 4155 verifyFormat("TESTSUITE(A) {\n" 4156 "TESTSUITE(B) {\n" 4157 " int foo();\n" 4158 "} // TESTSUITE(B)\n" 4159 "} // TESTSUITE(A)", 4160 Style); 4161 verifyFormat("TESTSUITE(A) {\n" 4162 "namespace B {\n" 4163 " int foo();\n" 4164 "} // namespace B\n" 4165 "} // TESTSUITE(A)", 4166 Style); 4167 verifyFormat("namespace A {\n" 4168 "TESTSUITE(B) {\n" 4169 " int foo();\n" 4170 "} // TESTSUITE(B)\n" 4171 "} // namespace A", 4172 Style); 4173 4174 // Properly merge namespace-macros blocks in CompactNamespaces mode 4175 Style.NamespaceIndentation = FormatStyle::NI_None; 4176 Style.CompactNamespaces = true; 4177 verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n" 4178 "}} // TESTSUITE(A::B)", 4179 Style); 4180 4181 EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n" 4182 "}} // TESTSUITE(out::in)", 4183 format("TESTSUITE(out) {\n" 4184 "TESTSUITE(in) {\n" 4185 "} // TESTSUITE(in)\n" 4186 "} // TESTSUITE(out)", 4187 Style)); 4188 4189 EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n" 4190 "}} // TESTSUITE(out::in)", 4191 format("TESTSUITE(out) {\n" 4192 "TESTSUITE(in) {\n" 4193 "} // TESTSUITE(in)\n" 4194 "} // TESTSUITE(out)", 4195 Style)); 4196 4197 // Do not merge different namespaces/macros 4198 EXPECT_EQ("namespace out {\n" 4199 "TESTSUITE(in) {\n" 4200 "} // TESTSUITE(in)\n" 4201 "} // namespace out", 4202 format("namespace out {\n" 4203 "TESTSUITE(in) {\n" 4204 "} // TESTSUITE(in)\n" 4205 "} // namespace out", 4206 Style)); 4207 EXPECT_EQ("TESTSUITE(out) {\n" 4208 "namespace in {\n" 4209 "} // namespace in\n" 4210 "} // TESTSUITE(out)", 4211 format("TESTSUITE(out) {\n" 4212 "namespace in {\n" 4213 "} // namespace in\n" 4214 "} // TESTSUITE(out)", 4215 Style)); 4216 Style.NamespaceMacros.push_back("FOOBAR"); 4217 EXPECT_EQ("TESTSUITE(out) {\n" 4218 "FOOBAR(in) {\n" 4219 "} // FOOBAR(in)\n" 4220 "} // TESTSUITE(out)", 4221 format("TESTSUITE(out) {\n" 4222 "FOOBAR(in) {\n" 4223 "} // FOOBAR(in)\n" 4224 "} // TESTSUITE(out)", 4225 Style)); 4226 } 4227 4228 TEST_F(FormatTest, FormatsCompactNamespaces) { 4229 FormatStyle Style = getLLVMStyle(); 4230 Style.CompactNamespaces = true; 4231 Style.NamespaceMacros.push_back("TESTSUITE"); 4232 4233 verifyFormat("namespace A { namespace B {\n" 4234 "}} // namespace A::B", 4235 Style); 4236 4237 EXPECT_EQ("namespace out { namespace in {\n" 4238 "}} // namespace out::in", 4239 format("namespace out {\n" 4240 "namespace in {\n" 4241 "} // namespace in\n" 4242 "} // namespace out", 4243 Style)); 4244 4245 // Only namespaces which have both consecutive opening and end get compacted 4246 EXPECT_EQ("namespace out {\n" 4247 "namespace in1 {\n" 4248 "} // namespace in1\n" 4249 "namespace in2 {\n" 4250 "} // namespace in2\n" 4251 "} // namespace out", 4252 format("namespace out {\n" 4253 "namespace in1 {\n" 4254 "} // namespace in1\n" 4255 "namespace in2 {\n" 4256 "} // namespace in2\n" 4257 "} // namespace out", 4258 Style)); 4259 4260 EXPECT_EQ("namespace out {\n" 4261 "int i;\n" 4262 "namespace in {\n" 4263 "int j;\n" 4264 "} // namespace in\n" 4265 "int k;\n" 4266 "} // namespace out", 4267 format("namespace out { int i;\n" 4268 "namespace in { int j; } // namespace in\n" 4269 "int k; } // namespace out", 4270 Style)); 4271 4272 EXPECT_EQ("namespace A { namespace B { namespace C {\n" 4273 "}}} // namespace A::B::C\n", 4274 format("namespace A { namespace B {\n" 4275 "namespace C {\n" 4276 "}} // namespace B::C\n" 4277 "} // namespace A\n", 4278 Style)); 4279 4280 Style.ColumnLimit = 40; 4281 EXPECT_EQ("namespace aaaaaaaaaa {\n" 4282 "namespace bbbbbbbbbb {\n" 4283 "}} // namespace aaaaaaaaaa::bbbbbbbbbb", 4284 format("namespace aaaaaaaaaa {\n" 4285 "namespace bbbbbbbbbb {\n" 4286 "} // namespace bbbbbbbbbb\n" 4287 "} // namespace aaaaaaaaaa", 4288 Style)); 4289 4290 EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n" 4291 "namespace cccccc {\n" 4292 "}}} // namespace aaaaaa::bbbbbb::cccccc", 4293 format("namespace aaaaaa {\n" 4294 "namespace bbbbbb {\n" 4295 "namespace cccccc {\n" 4296 "} // namespace cccccc\n" 4297 "} // namespace bbbbbb\n" 4298 "} // namespace aaaaaa", 4299 Style)); 4300 Style.ColumnLimit = 80; 4301 4302 // Extra semicolon after 'inner' closing brace prevents merging 4303 EXPECT_EQ("namespace out { namespace in {\n" 4304 "}; } // namespace out::in", 4305 format("namespace out {\n" 4306 "namespace in {\n" 4307 "}; // namespace in\n" 4308 "} // namespace out", 4309 Style)); 4310 4311 // Extra semicolon after 'outer' closing brace is conserved 4312 EXPECT_EQ("namespace out { namespace in {\n" 4313 "}}; // namespace out::in", 4314 format("namespace out {\n" 4315 "namespace in {\n" 4316 "} // namespace in\n" 4317 "}; // namespace out", 4318 Style)); 4319 4320 Style.NamespaceIndentation = FormatStyle::NI_All; 4321 EXPECT_EQ("namespace out { namespace in {\n" 4322 " int i;\n" 4323 "}} // namespace out::in", 4324 format("namespace out {\n" 4325 "namespace in {\n" 4326 "int i;\n" 4327 "} // namespace in\n" 4328 "} // namespace out", 4329 Style)); 4330 EXPECT_EQ("namespace out { namespace mid {\n" 4331 " namespace in {\n" 4332 " int j;\n" 4333 " } // namespace in\n" 4334 " int k;\n" 4335 "}} // namespace out::mid", 4336 format("namespace out { namespace mid {\n" 4337 "namespace in { int j; } // namespace in\n" 4338 "int k; }} // namespace out::mid", 4339 Style)); 4340 4341 Style.NamespaceIndentation = FormatStyle::NI_Inner; 4342 EXPECT_EQ("namespace out { namespace in {\n" 4343 " int i;\n" 4344 "}} // namespace out::in", 4345 format("namespace out {\n" 4346 "namespace in {\n" 4347 "int i;\n" 4348 "} // namespace in\n" 4349 "} // namespace out", 4350 Style)); 4351 EXPECT_EQ("namespace out { namespace mid { namespace in {\n" 4352 " int i;\n" 4353 "}}} // namespace out::mid::in", 4354 format("namespace out {\n" 4355 "namespace mid {\n" 4356 "namespace in {\n" 4357 "int i;\n" 4358 "} // namespace in\n" 4359 "} // namespace mid\n" 4360 "} // namespace out", 4361 Style)); 4362 4363 Style.CompactNamespaces = true; 4364 Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 4365 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4366 Style.BraceWrapping.BeforeLambdaBody = true; 4367 verifyFormat("namespace out { namespace in {\n" 4368 "}} // namespace out::in", 4369 Style); 4370 EXPECT_EQ("namespace out { namespace in {\n" 4371 "}} // namespace out::in", 4372 format("namespace out {\n" 4373 "namespace in {\n" 4374 "} // namespace in\n" 4375 "} // namespace out", 4376 Style)); 4377 } 4378 4379 TEST_F(FormatTest, FormatsExternC) { 4380 verifyFormat("extern \"C\" {\nint a;"); 4381 verifyFormat("extern \"C\" {}"); 4382 verifyFormat("extern \"C\" {\n" 4383 "int foo();\n" 4384 "}"); 4385 verifyFormat("extern \"C\" int foo() {}"); 4386 verifyFormat("extern \"C\" int foo();"); 4387 verifyFormat("extern \"C\" int foo() {\n" 4388 " int i = 42;\n" 4389 " return i;\n" 4390 "}"); 4391 4392 FormatStyle Style = getLLVMStyle(); 4393 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4394 Style.BraceWrapping.AfterFunction = true; 4395 verifyFormat("extern \"C\" int foo() {}", Style); 4396 verifyFormat("extern \"C\" int foo();", Style); 4397 verifyFormat("extern \"C\" int foo()\n" 4398 "{\n" 4399 " int i = 42;\n" 4400 " return i;\n" 4401 "}", 4402 Style); 4403 4404 Style.BraceWrapping.AfterExternBlock = true; 4405 Style.BraceWrapping.SplitEmptyRecord = false; 4406 verifyFormat("extern \"C\"\n" 4407 "{}", 4408 Style); 4409 verifyFormat("extern \"C\"\n" 4410 "{\n" 4411 " int foo();\n" 4412 "}", 4413 Style); 4414 } 4415 4416 TEST_F(FormatTest, IndentExternBlockStyle) { 4417 FormatStyle Style = getLLVMStyle(); 4418 Style.IndentWidth = 2; 4419 4420 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4421 verifyFormat("extern \"C\" { /*9*/\n" 4422 "}", 4423 Style); 4424 verifyFormat("extern \"C\" {\n" 4425 " int foo10();\n" 4426 "}", 4427 Style); 4428 4429 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 4430 verifyFormat("extern \"C\" { /*11*/\n" 4431 "}", 4432 Style); 4433 verifyFormat("extern \"C\" {\n" 4434 "int foo12();\n" 4435 "}", 4436 Style); 4437 4438 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4439 Style.BraceWrapping.AfterExternBlock = true; 4440 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4441 verifyFormat("extern \"C\"\n" 4442 "{ /*13*/\n" 4443 "}", 4444 Style); 4445 verifyFormat("extern \"C\"\n{\n" 4446 " int foo14();\n" 4447 "}", 4448 Style); 4449 4450 Style.BraceWrapping.AfterExternBlock = false; 4451 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 4452 verifyFormat("extern \"C\" { /*15*/\n" 4453 "}", 4454 Style); 4455 verifyFormat("extern \"C\" {\n" 4456 "int foo16();\n" 4457 "}", 4458 Style); 4459 4460 Style.BraceWrapping.AfterExternBlock = true; 4461 verifyFormat("extern \"C\"\n" 4462 "{ /*13*/\n" 4463 "}", 4464 Style); 4465 verifyFormat("extern \"C\"\n" 4466 "{\n" 4467 "int foo14();\n" 4468 "}", 4469 Style); 4470 4471 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4472 verifyFormat("extern \"C\"\n" 4473 "{ /*13*/\n" 4474 "}", 4475 Style); 4476 verifyFormat("extern \"C\"\n" 4477 "{\n" 4478 " int foo14();\n" 4479 "}", 4480 Style); 4481 } 4482 4483 TEST_F(FormatTest, FormatsInlineASM) { 4484 verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));"); 4485 verifyFormat("asm(\"nop\" ::: \"memory\");"); 4486 verifyFormat( 4487 "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n" 4488 " \"cpuid\\n\\t\"\n" 4489 " \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n" 4490 " : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n" 4491 " : \"a\"(value));"); 4492 EXPECT_EQ( 4493 "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n" 4494 " __asm {\n" 4495 " mov edx,[that] // vtable in edx\n" 4496 " mov eax,methodIndex\n" 4497 " call [edx][eax*4] // stdcall\n" 4498 " }\n" 4499 "}", 4500 format("void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n" 4501 " __asm {\n" 4502 " mov edx,[that] // vtable in edx\n" 4503 " mov eax,methodIndex\n" 4504 " call [edx][eax*4] // stdcall\n" 4505 " }\n" 4506 "}")); 4507 EXPECT_EQ("_asm {\n" 4508 " xor eax, eax;\n" 4509 " cpuid;\n" 4510 "}", 4511 format("_asm {\n" 4512 " xor eax, eax;\n" 4513 " cpuid;\n" 4514 "}")); 4515 verifyFormat("void function() {\n" 4516 " // comment\n" 4517 " asm(\"\");\n" 4518 "}"); 4519 EXPECT_EQ("__asm {\n" 4520 "}\n" 4521 "int i;", 4522 format("__asm {\n" 4523 "}\n" 4524 "int i;")); 4525 } 4526 4527 TEST_F(FormatTest, FormatTryCatch) { 4528 verifyFormat("try {\n" 4529 " throw a * b;\n" 4530 "} catch (int a) {\n" 4531 " // Do nothing.\n" 4532 "} catch (...) {\n" 4533 " exit(42);\n" 4534 "}"); 4535 4536 // Function-level try statements. 4537 verifyFormat("int f() try { return 4; } catch (...) {\n" 4538 " return 5;\n" 4539 "}"); 4540 verifyFormat("class A {\n" 4541 " int a;\n" 4542 " A() try : a(0) {\n" 4543 " } catch (...) {\n" 4544 " throw;\n" 4545 " }\n" 4546 "};\n"); 4547 verifyFormat("class A {\n" 4548 " int a;\n" 4549 " A() try : a(0), b{1} {\n" 4550 " } catch (...) {\n" 4551 " throw;\n" 4552 " }\n" 4553 "};\n"); 4554 verifyFormat("class A {\n" 4555 " int a;\n" 4556 " A() try : a(0), b{1}, c{2} {\n" 4557 " } catch (...) {\n" 4558 " throw;\n" 4559 " }\n" 4560 "};\n"); 4561 verifyFormat("class A {\n" 4562 " int a;\n" 4563 " A() try : a(0), b{1}, c{2} {\n" 4564 " { // New scope.\n" 4565 " }\n" 4566 " } catch (...) {\n" 4567 " throw;\n" 4568 " }\n" 4569 "};\n"); 4570 4571 // Incomplete try-catch blocks. 4572 verifyIncompleteFormat("try {} catch ("); 4573 } 4574 4575 TEST_F(FormatTest, FormatTryAsAVariable) { 4576 verifyFormat("int try;"); 4577 verifyFormat("int try, size;"); 4578 verifyFormat("try = foo();"); 4579 verifyFormat("if (try < size) {\n return true;\n}"); 4580 4581 verifyFormat("int catch;"); 4582 verifyFormat("int catch, size;"); 4583 verifyFormat("catch = foo();"); 4584 verifyFormat("if (catch < size) {\n return true;\n}"); 4585 4586 FormatStyle Style = getLLVMStyle(); 4587 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4588 Style.BraceWrapping.AfterFunction = true; 4589 Style.BraceWrapping.BeforeCatch = true; 4590 verifyFormat("try {\n" 4591 " int bar = 1;\n" 4592 "}\n" 4593 "catch (...) {\n" 4594 " int bar = 1;\n" 4595 "}", 4596 Style); 4597 verifyFormat("#if NO_EX\n" 4598 "try\n" 4599 "#endif\n" 4600 "{\n" 4601 "}\n" 4602 "#if NO_EX\n" 4603 "catch (...) {\n" 4604 "}", 4605 Style); 4606 verifyFormat("try /* abc */ {\n" 4607 " int bar = 1;\n" 4608 "}\n" 4609 "catch (...) {\n" 4610 " int bar = 1;\n" 4611 "}", 4612 Style); 4613 verifyFormat("try\n" 4614 "// abc\n" 4615 "{\n" 4616 " int bar = 1;\n" 4617 "}\n" 4618 "catch (...) {\n" 4619 " int bar = 1;\n" 4620 "}", 4621 Style); 4622 } 4623 4624 TEST_F(FormatTest, FormatSEHTryCatch) { 4625 verifyFormat("__try {\n" 4626 " int a = b * c;\n" 4627 "} __except (EXCEPTION_EXECUTE_HANDLER) {\n" 4628 " // Do nothing.\n" 4629 "}"); 4630 4631 verifyFormat("__try {\n" 4632 " int a = b * c;\n" 4633 "} __finally {\n" 4634 " // Do nothing.\n" 4635 "}"); 4636 4637 verifyFormat("DEBUG({\n" 4638 " __try {\n" 4639 " } __finally {\n" 4640 " }\n" 4641 "});\n"); 4642 } 4643 4644 TEST_F(FormatTest, IncompleteTryCatchBlocks) { 4645 verifyFormat("try {\n" 4646 " f();\n" 4647 "} catch {\n" 4648 " g();\n" 4649 "}"); 4650 verifyFormat("try {\n" 4651 " f();\n" 4652 "} catch (A a) MACRO(x) {\n" 4653 " g();\n" 4654 "} catch (B b) MACRO(x) {\n" 4655 " g();\n" 4656 "}"); 4657 } 4658 4659 TEST_F(FormatTest, FormatTryCatchBraceStyles) { 4660 FormatStyle Style = getLLVMStyle(); 4661 for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla, 4662 FormatStyle::BS_WebKit}) { 4663 Style.BreakBeforeBraces = BraceStyle; 4664 verifyFormat("try {\n" 4665 " // something\n" 4666 "} catch (...) {\n" 4667 " // something\n" 4668 "}", 4669 Style); 4670 } 4671 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 4672 verifyFormat("try {\n" 4673 " // something\n" 4674 "}\n" 4675 "catch (...) {\n" 4676 " // something\n" 4677 "}", 4678 Style); 4679 verifyFormat("__try {\n" 4680 " // something\n" 4681 "}\n" 4682 "__finally {\n" 4683 " // something\n" 4684 "}", 4685 Style); 4686 verifyFormat("@try {\n" 4687 " // something\n" 4688 "}\n" 4689 "@finally {\n" 4690 " // something\n" 4691 "}", 4692 Style); 4693 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 4694 verifyFormat("try\n" 4695 "{\n" 4696 " // something\n" 4697 "}\n" 4698 "catch (...)\n" 4699 "{\n" 4700 " // something\n" 4701 "}", 4702 Style); 4703 Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 4704 verifyFormat("try\n" 4705 " {\n" 4706 " // something white\n" 4707 " }\n" 4708 "catch (...)\n" 4709 " {\n" 4710 " // something white\n" 4711 " }", 4712 Style); 4713 Style.BreakBeforeBraces = FormatStyle::BS_GNU; 4714 verifyFormat("try\n" 4715 " {\n" 4716 " // something\n" 4717 " }\n" 4718 "catch (...)\n" 4719 " {\n" 4720 " // something\n" 4721 " }", 4722 Style); 4723 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4724 Style.BraceWrapping.BeforeCatch = true; 4725 verifyFormat("try {\n" 4726 " // something\n" 4727 "}\n" 4728 "catch (...) {\n" 4729 " // something\n" 4730 "}", 4731 Style); 4732 } 4733 4734 TEST_F(FormatTest, StaticInitializers) { 4735 verifyFormat("static SomeClass SC = {1, 'a'};"); 4736 4737 verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n" 4738 " 100000000, " 4739 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};"); 4740 4741 // Here, everything other than the "}" would fit on a line. 4742 verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n" 4743 " 10000000000000000000000000};"); 4744 EXPECT_EQ("S s = {a,\n" 4745 "\n" 4746 " b};", 4747 format("S s = {\n" 4748 " a,\n" 4749 "\n" 4750 " b\n" 4751 "};")); 4752 4753 // FIXME: This would fit into the column limit if we'd fit "{ {" on the first 4754 // line. However, the formatting looks a bit off and this probably doesn't 4755 // happen often in practice. 4756 verifyFormat("static int Variable[1] = {\n" 4757 " {1000000000000000000000000000000000000}};", 4758 getLLVMStyleWithColumns(40)); 4759 } 4760 4761 TEST_F(FormatTest, DesignatedInitializers) { 4762 verifyFormat("const struct A a = {.a = 1, .b = 2};"); 4763 verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n" 4764 " .bbbbbbbbbb = 2,\n" 4765 " .cccccccccc = 3,\n" 4766 " .dddddddddd = 4,\n" 4767 " .eeeeeeeeee = 5};"); 4768 verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n" 4769 " .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n" 4770 " .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n" 4771 " .ccccccccccccccccccccccccccc = 3,\n" 4772 " .ddddddddddddddddddddddddddd = 4,\n" 4773 " .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};"); 4774 4775 verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};"); 4776 4777 verifyFormat("const struct A a = {[0] = 1, [1] = 2};"); 4778 verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n" 4779 " [2] = bbbbbbbbbb,\n" 4780 " [3] = cccccccccc,\n" 4781 " [4] = dddddddddd,\n" 4782 " [5] = eeeeeeeeee};"); 4783 verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n" 4784 " [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 4785 " [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 4786 " [3] = cccccccccccccccccccccccccccccccccccccc,\n" 4787 " [4] = dddddddddddddddddddddddddddddddddddddd,\n" 4788 " [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};"); 4789 } 4790 4791 TEST_F(FormatTest, NestedStaticInitializers) { 4792 verifyFormat("static A x = {{{}}};\n"); 4793 verifyFormat("static A x = {{{init1, init2, init3, init4},\n" 4794 " {init1, init2, init3, init4}}};", 4795 getLLVMStyleWithColumns(50)); 4796 4797 verifyFormat("somes Status::global_reps[3] = {\n" 4798 " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n" 4799 " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n" 4800 " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};", 4801 getLLVMStyleWithColumns(60)); 4802 verifyGoogleFormat("SomeType Status::global_reps[3] = {\n" 4803 " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n" 4804 " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n" 4805 " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};"); 4806 verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n" 4807 " {rect.fRight - rect.fLeft, rect.fBottom - " 4808 "rect.fTop}};"); 4809 4810 verifyFormat( 4811 "SomeArrayOfSomeType a = {\n" 4812 " {{1, 2, 3},\n" 4813 " {1, 2, 3},\n" 4814 " {111111111111111111111111111111, 222222222222222222222222222222,\n" 4815 " 333333333333333333333333333333},\n" 4816 " {1, 2, 3},\n" 4817 " {1, 2, 3}}};"); 4818 verifyFormat( 4819 "SomeArrayOfSomeType a = {\n" 4820 " {{1, 2, 3}},\n" 4821 " {{1, 2, 3}},\n" 4822 " {{111111111111111111111111111111, 222222222222222222222222222222,\n" 4823 " 333333333333333333333333333333}},\n" 4824 " {{1, 2, 3}},\n" 4825 " {{1, 2, 3}}};"); 4826 4827 verifyFormat("struct {\n" 4828 " unsigned bit;\n" 4829 " const char *const name;\n" 4830 "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n" 4831 " {kOsWin, \"Windows\"},\n" 4832 " {kOsLinux, \"Linux\"},\n" 4833 " {kOsCrOS, \"Chrome OS\"}};"); 4834 verifyFormat("struct {\n" 4835 " unsigned bit;\n" 4836 " const char *const name;\n" 4837 "} kBitsToOs[] = {\n" 4838 " {kOsMac, \"Mac\"},\n" 4839 " {kOsWin, \"Windows\"},\n" 4840 " {kOsLinux, \"Linux\"},\n" 4841 " {kOsCrOS, \"Chrome OS\"},\n" 4842 "};"); 4843 } 4844 4845 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) { 4846 verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro(" 4847 " \\\n" 4848 " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)"); 4849 } 4850 4851 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) { 4852 verifyFormat("virtual void write(ELFWriter *writerrr,\n" 4853 " OwningPtr<FileOutputBuffer> &buffer) = 0;"); 4854 4855 // Do break defaulted and deleted functions. 4856 verifyFormat("virtual void ~Deeeeeeeestructor() =\n" 4857 " default;", 4858 getLLVMStyleWithColumns(40)); 4859 verifyFormat("virtual void ~Deeeeeeeestructor() =\n" 4860 " delete;", 4861 getLLVMStyleWithColumns(40)); 4862 } 4863 4864 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) { 4865 verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3", 4866 getLLVMStyleWithColumns(40)); 4867 verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"", 4868 getLLVMStyleWithColumns(40)); 4869 EXPECT_EQ("#define Q \\\n" 4870 " \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\" \\\n" 4871 " \"aaaaaaaa.cpp\"", 4872 format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"", 4873 getLLVMStyleWithColumns(40))); 4874 } 4875 4876 TEST_F(FormatTest, UnderstandsLinePPDirective) { 4877 EXPECT_EQ("# 123 \"A string literal\"", 4878 format(" # 123 \"A string literal\"")); 4879 } 4880 4881 TEST_F(FormatTest, LayoutUnknownPPDirective) { 4882 EXPECT_EQ("#;", format("#;")); 4883 verifyFormat("#\n;\n;\n;"); 4884 } 4885 4886 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) { 4887 EXPECT_EQ("#line 42 \"test\"\n", 4888 format("# \\\n line \\\n 42 \\\n \"test\"\n")); 4889 EXPECT_EQ("#define A B\n", format("# \\\n define \\\n A \\\n B\n", 4890 getLLVMStyleWithColumns(12))); 4891 } 4892 4893 TEST_F(FormatTest, EndOfFileEndsPPDirective) { 4894 EXPECT_EQ("#line 42 \"test\"", 4895 format("# \\\n line \\\n 42 \\\n \"test\"")); 4896 EXPECT_EQ("#define A B", format("# \\\n define \\\n A \\\n B")); 4897 } 4898 4899 TEST_F(FormatTest, DoesntRemoveUnknownTokens) { 4900 verifyFormat("#define A \\x20"); 4901 verifyFormat("#define A \\ x20"); 4902 EXPECT_EQ("#define A \\ x20", format("#define A \\ x20")); 4903 verifyFormat("#define A ''"); 4904 verifyFormat("#define A ''qqq"); 4905 verifyFormat("#define A `qqq"); 4906 verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");"); 4907 EXPECT_EQ("const char *c = STRINGIFY(\n" 4908 "\\na : b);", 4909 format("const char * c = STRINGIFY(\n" 4910 "\\na : b);")); 4911 4912 verifyFormat("a\r\\"); 4913 verifyFormat("a\v\\"); 4914 verifyFormat("a\f\\"); 4915 } 4916 4917 TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) { 4918 FormatStyle style = getChromiumStyle(FormatStyle::LK_Cpp); 4919 style.IndentWidth = 4; 4920 style.PPIndentWidth = 1; 4921 4922 style.IndentPPDirectives = FormatStyle::PPDIS_None; 4923 verifyFormat("#ifdef __linux__\n" 4924 "void foo() {\n" 4925 " int x = 0;\n" 4926 "}\n" 4927 "#define FOO\n" 4928 "#endif\n" 4929 "void bar() {\n" 4930 " int y = 0;\n" 4931 "}\n", 4932 style); 4933 4934 style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash; 4935 verifyFormat("#ifdef __linux__\n" 4936 "void foo() {\n" 4937 " int x = 0;\n" 4938 "}\n" 4939 "# define FOO foo\n" 4940 "#endif\n" 4941 "void bar() {\n" 4942 " int y = 0;\n" 4943 "}\n", 4944 style); 4945 4946 style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash; 4947 verifyFormat("#ifdef __linux__\n" 4948 "void foo() {\n" 4949 " int x = 0;\n" 4950 "}\n" 4951 " #define FOO foo\n" 4952 "#endif\n" 4953 "void bar() {\n" 4954 " int y = 0;\n" 4955 "}\n", 4956 style); 4957 } 4958 4959 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) { 4960 verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13)); 4961 verifyFormat("#define A( \\\n BB)", getLLVMStyleWithColumns(12)); 4962 verifyFormat("#define A( \\\n A, B)", getLLVMStyleWithColumns(12)); 4963 // FIXME: We never break before the macro name. 4964 verifyFormat("#define AA( \\\n B)", getLLVMStyleWithColumns(12)); 4965 4966 verifyFormat("#define A A\n#define A A"); 4967 verifyFormat("#define A(X) A\n#define A A"); 4968 4969 verifyFormat("#define Something Other", getLLVMStyleWithColumns(23)); 4970 verifyFormat("#define Something \\\n Other", getLLVMStyleWithColumns(22)); 4971 } 4972 4973 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) { 4974 EXPECT_EQ("// somecomment\n" 4975 "#include \"a.h\"\n" 4976 "#define A( \\\n" 4977 " A, B)\n" 4978 "#include \"b.h\"\n" 4979 "// somecomment\n", 4980 format(" // somecomment\n" 4981 " #include \"a.h\"\n" 4982 "#define A(A,\\\n" 4983 " B)\n" 4984 " #include \"b.h\"\n" 4985 " // somecomment\n", 4986 getLLVMStyleWithColumns(13))); 4987 } 4988 4989 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); } 4990 4991 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) { 4992 EXPECT_EQ("#define A \\\n" 4993 " c; \\\n" 4994 " e;\n" 4995 "f;", 4996 format("#define A c; e;\n" 4997 "f;", 4998 getLLVMStyleWithColumns(14))); 4999 } 5000 5001 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); } 5002 5003 TEST_F(FormatTest, MacroDefinitionInsideStatement) { 5004 EXPECT_EQ("int x,\n" 5005 "#define A\n" 5006 " y;", 5007 format("int x,\n#define A\ny;")); 5008 } 5009 5010 TEST_F(FormatTest, HashInMacroDefinition) { 5011 EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle())); 5012 EXPECT_EQ("#define A(c) u#c", format("#define A(c) u#c", getLLVMStyle())); 5013 EXPECT_EQ("#define A(c) U#c", format("#define A(c) U#c", getLLVMStyle())); 5014 EXPECT_EQ("#define A(c) u8#c", format("#define A(c) u8#c", getLLVMStyle())); 5015 EXPECT_EQ("#define A(c) LR#c", format("#define A(c) LR#c", getLLVMStyle())); 5016 EXPECT_EQ("#define A(c) uR#c", format("#define A(c) uR#c", getLLVMStyle())); 5017 EXPECT_EQ("#define A(c) UR#c", format("#define A(c) UR#c", getLLVMStyle())); 5018 EXPECT_EQ("#define A(c) u8R#c", format("#define A(c) u8R#c", getLLVMStyle())); 5019 verifyFormat("#define A \\\n b #c;", getLLVMStyleWithColumns(11)); 5020 verifyFormat("#define A \\\n" 5021 " { \\\n" 5022 " f(#c); \\\n" 5023 " }", 5024 getLLVMStyleWithColumns(11)); 5025 5026 verifyFormat("#define A(X) \\\n" 5027 " void function##X()", 5028 getLLVMStyleWithColumns(22)); 5029 5030 verifyFormat("#define A(a, b, c) \\\n" 5031 " void a##b##c()", 5032 getLLVMStyleWithColumns(22)); 5033 5034 verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22)); 5035 } 5036 5037 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) { 5038 EXPECT_EQ("#define A (x)", format("#define A (x)")); 5039 EXPECT_EQ("#define A(x)", format("#define A(x)")); 5040 5041 FormatStyle Style = getLLVMStyle(); 5042 Style.SpaceBeforeParens = FormatStyle::SBPO_Never; 5043 verifyFormat("#define true ((foo)1)", Style); 5044 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 5045 verifyFormat("#define false((foo)0)", Style); 5046 } 5047 5048 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) { 5049 EXPECT_EQ("#define A b;", format("#define A \\\n" 5050 " \\\n" 5051 " b;", 5052 getLLVMStyleWithColumns(25))); 5053 EXPECT_EQ("#define A \\\n" 5054 " \\\n" 5055 " a; \\\n" 5056 " b;", 5057 format("#define A \\\n" 5058 " \\\n" 5059 " a; \\\n" 5060 " b;", 5061 getLLVMStyleWithColumns(11))); 5062 EXPECT_EQ("#define A \\\n" 5063 " a; \\\n" 5064 " \\\n" 5065 " b;", 5066 format("#define A \\\n" 5067 " a; \\\n" 5068 " \\\n" 5069 " b;", 5070 getLLVMStyleWithColumns(11))); 5071 } 5072 5073 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) { 5074 verifyIncompleteFormat("#define A :"); 5075 verifyFormat("#define SOMECASES \\\n" 5076 " case 1: \\\n" 5077 " case 2\n", 5078 getLLVMStyleWithColumns(20)); 5079 verifyFormat("#define MACRO(a) \\\n" 5080 " if (a) \\\n" 5081 " f(); \\\n" 5082 " else \\\n" 5083 " g()", 5084 getLLVMStyleWithColumns(18)); 5085 verifyFormat("#define A template <typename T>"); 5086 verifyIncompleteFormat("#define STR(x) #x\n" 5087 "f(STR(this_is_a_string_literal{));"); 5088 verifyFormat("#pragma omp threadprivate( \\\n" 5089 " y)), // expected-warning", 5090 getLLVMStyleWithColumns(28)); 5091 verifyFormat("#d, = };"); 5092 verifyFormat("#if \"a"); 5093 verifyIncompleteFormat("({\n" 5094 "#define b \\\n" 5095 " } \\\n" 5096 " a\n" 5097 "a", 5098 getLLVMStyleWithColumns(15)); 5099 verifyFormat("#define A \\\n" 5100 " { \\\n" 5101 " {\n" 5102 "#define B \\\n" 5103 " } \\\n" 5104 " }", 5105 getLLVMStyleWithColumns(15)); 5106 verifyNoCrash("#if a\na(\n#else\n#endif\n{a"); 5107 verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}"); 5108 verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};"); 5109 verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() { \n)}"); 5110 } 5111 5112 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) { 5113 verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline. 5114 EXPECT_EQ("class A : public QObject {\n" 5115 " Q_OBJECT\n" 5116 "\n" 5117 " A() {}\n" 5118 "};", 5119 format("class A : public QObject {\n" 5120 " Q_OBJECT\n" 5121 "\n" 5122 " A() {\n}\n" 5123 "} ;")); 5124 EXPECT_EQ("MACRO\n" 5125 "/*static*/ int i;", 5126 format("MACRO\n" 5127 " /*static*/ int i;")); 5128 EXPECT_EQ("SOME_MACRO\n" 5129 "namespace {\n" 5130 "void f();\n" 5131 "} // namespace", 5132 format("SOME_MACRO\n" 5133 " namespace {\n" 5134 "void f( );\n" 5135 "} // namespace")); 5136 // Only if the identifier contains at least 5 characters. 5137 EXPECT_EQ("HTTP f();", format("HTTP\nf();")); 5138 EXPECT_EQ("MACRO\nf();", format("MACRO\nf();")); 5139 // Only if everything is upper case. 5140 EXPECT_EQ("class A : public QObject {\n" 5141 " Q_Object A() {}\n" 5142 "};", 5143 format("class A : public QObject {\n" 5144 " Q_Object\n" 5145 " A() {\n}\n" 5146 "} ;")); 5147 5148 // Only if the next line can actually start an unwrapped line. 5149 EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;", 5150 format("SOME_WEIRD_LOG_MACRO\n" 5151 "<< SomeThing;")); 5152 5153 verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), " 5154 "(n, buffers))\n", 5155 getChromiumStyle(FormatStyle::LK_Cpp)); 5156 5157 // See PR41483 5158 EXPECT_EQ("/**/ FOO(a)\n" 5159 "FOO(b)", 5160 format("/**/ FOO(a)\n" 5161 "FOO(b)")); 5162 } 5163 5164 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) { 5165 EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n" 5166 "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n" 5167 "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n" 5168 "class X {};\n" 5169 "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n" 5170 "int *createScopDetectionPass() { return 0; }", 5171 format(" INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n" 5172 " INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n" 5173 " INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n" 5174 " class X {};\n" 5175 " INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n" 5176 " int *createScopDetectionPass() { return 0; }")); 5177 // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as 5178 // braces, so that inner block is indented one level more. 5179 EXPECT_EQ("int q() {\n" 5180 " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n" 5181 " IPC_MESSAGE_HANDLER(xxx, qqq)\n" 5182 " IPC_END_MESSAGE_MAP()\n" 5183 "}", 5184 format("int q() {\n" 5185 " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n" 5186 " IPC_MESSAGE_HANDLER(xxx, qqq)\n" 5187 " IPC_END_MESSAGE_MAP()\n" 5188 "}")); 5189 5190 // Same inside macros. 5191 EXPECT_EQ("#define LIST(L) \\\n" 5192 " L(A) \\\n" 5193 " L(B) \\\n" 5194 " L(C)", 5195 format("#define LIST(L) \\\n" 5196 " L(A) \\\n" 5197 " L(B) \\\n" 5198 " L(C)", 5199 getGoogleStyle())); 5200 5201 // These must not be recognized as macros. 5202 EXPECT_EQ("int q() {\n" 5203 " f(x);\n" 5204 " f(x) {}\n" 5205 " f(x)->g();\n" 5206 " f(x)->*g();\n" 5207 " f(x).g();\n" 5208 " f(x) = x;\n" 5209 " f(x) += x;\n" 5210 " f(x) -= x;\n" 5211 " f(x) *= x;\n" 5212 " f(x) /= x;\n" 5213 " f(x) %= x;\n" 5214 " f(x) &= x;\n" 5215 " f(x) |= x;\n" 5216 " f(x) ^= x;\n" 5217 " f(x) >>= x;\n" 5218 " f(x) <<= x;\n" 5219 " f(x)[y].z();\n" 5220 " LOG(INFO) << x;\n" 5221 " ifstream(x) >> x;\n" 5222 "}\n", 5223 format("int q() {\n" 5224 " f(x)\n;\n" 5225 " f(x)\n {}\n" 5226 " f(x)\n->g();\n" 5227 " f(x)\n->*g();\n" 5228 " f(x)\n.g();\n" 5229 " f(x)\n = x;\n" 5230 " f(x)\n += x;\n" 5231 " f(x)\n -= x;\n" 5232 " f(x)\n *= x;\n" 5233 " f(x)\n /= x;\n" 5234 " f(x)\n %= x;\n" 5235 " f(x)\n &= x;\n" 5236 " f(x)\n |= x;\n" 5237 " f(x)\n ^= x;\n" 5238 " f(x)\n >>= x;\n" 5239 " f(x)\n <<= x;\n" 5240 " f(x)\n[y].z();\n" 5241 " LOG(INFO)\n << x;\n" 5242 " ifstream(x)\n >> x;\n" 5243 "}\n")); 5244 EXPECT_EQ("int q() {\n" 5245 " F(x)\n" 5246 " if (1) {\n" 5247 " }\n" 5248 " F(x)\n" 5249 " while (1) {\n" 5250 " }\n" 5251 " F(x)\n" 5252 " G(x);\n" 5253 " F(x)\n" 5254 " try {\n" 5255 " Q();\n" 5256 " } catch (...) {\n" 5257 " }\n" 5258 "}\n", 5259 format("int q() {\n" 5260 "F(x)\n" 5261 "if (1) {}\n" 5262 "F(x)\n" 5263 "while (1) {}\n" 5264 "F(x)\n" 5265 "G(x);\n" 5266 "F(x)\n" 5267 "try { Q(); } catch (...) {}\n" 5268 "}\n")); 5269 EXPECT_EQ("class A {\n" 5270 " A() : t(0) {}\n" 5271 " A(int i) noexcept() : {}\n" 5272 " A(X x)\n" // FIXME: function-level try blocks are broken. 5273 " try : t(0) {\n" 5274 " } catch (...) {\n" 5275 " }\n" 5276 "};", 5277 format("class A {\n" 5278 " A()\n : t(0) {}\n" 5279 " A(int i)\n noexcept() : {}\n" 5280 " A(X x)\n" 5281 " try : t(0) {} catch (...) {}\n" 5282 "};")); 5283 FormatStyle Style = getLLVMStyle(); 5284 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 5285 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 5286 Style.BraceWrapping.AfterFunction = true; 5287 EXPECT_EQ("void f()\n" 5288 "try\n" 5289 "{\n" 5290 "}", 5291 format("void f() try {\n" 5292 "}", 5293 Style)); 5294 EXPECT_EQ("class SomeClass {\n" 5295 "public:\n" 5296 " SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5297 "};", 5298 format("class SomeClass {\n" 5299 "public:\n" 5300 " SomeClass()\n" 5301 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5302 "};")); 5303 EXPECT_EQ("class SomeClass {\n" 5304 "public:\n" 5305 " SomeClass()\n" 5306 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5307 "};", 5308 format("class SomeClass {\n" 5309 "public:\n" 5310 " SomeClass()\n" 5311 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5312 "};", 5313 getLLVMStyleWithColumns(40))); 5314 5315 verifyFormat("MACRO(>)"); 5316 5317 // Some macros contain an implicit semicolon. 5318 Style = getLLVMStyle(); 5319 Style.StatementMacros.push_back("FOO"); 5320 verifyFormat("FOO(a) int b = 0;"); 5321 verifyFormat("FOO(a)\n" 5322 "int b = 0;", 5323 Style); 5324 verifyFormat("FOO(a);\n" 5325 "int b = 0;", 5326 Style); 5327 verifyFormat("FOO(argc, argv, \"4.0.2\")\n" 5328 "int b = 0;", 5329 Style); 5330 verifyFormat("FOO()\n" 5331 "int b = 0;", 5332 Style); 5333 verifyFormat("FOO\n" 5334 "int b = 0;", 5335 Style); 5336 verifyFormat("void f() {\n" 5337 " FOO(a)\n" 5338 " return a;\n" 5339 "}", 5340 Style); 5341 verifyFormat("FOO(a)\n" 5342 "FOO(b)", 5343 Style); 5344 verifyFormat("int a = 0;\n" 5345 "FOO(b)\n" 5346 "int c = 0;", 5347 Style); 5348 verifyFormat("int a = 0;\n" 5349 "int x = FOO(a)\n" 5350 "int b = 0;", 5351 Style); 5352 verifyFormat("void foo(int a) { FOO(a) }\n" 5353 "uint32_t bar() {}", 5354 Style); 5355 } 5356 5357 TEST_F(FormatTest, FormatsMacrosWithZeroColumnWidth) { 5358 FormatStyle ZeroColumn = getLLVMStyleWithColumns(0); 5359 5360 verifyFormat("#define A LOOOOOOOOOOOOOOOOOOONG() LOOOOOOOOOOOOOOOOOOONG()", 5361 ZeroColumn); 5362 } 5363 5364 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) { 5365 verifyFormat("#define A \\\n" 5366 " f({ \\\n" 5367 " g(); \\\n" 5368 " });", 5369 getLLVMStyleWithColumns(11)); 5370 } 5371 5372 TEST_F(FormatTest, IndentPreprocessorDirectives) { 5373 FormatStyle Style = getLLVMStyleWithColumns(40); 5374 Style.IndentPPDirectives = FormatStyle::PPDIS_None; 5375 verifyFormat("#ifdef _WIN32\n" 5376 "#define A 0\n" 5377 "#ifdef VAR2\n" 5378 "#define B 1\n" 5379 "#include <someheader.h>\n" 5380 "#define MACRO \\\n" 5381 " some_very_long_func_aaaaaaaaaa();\n" 5382 "#endif\n" 5383 "#else\n" 5384 "#define A 1\n" 5385 "#endif", 5386 Style); 5387 Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash; 5388 verifyFormat("#ifdef _WIN32\n" 5389 "# define A 0\n" 5390 "# ifdef VAR2\n" 5391 "# define B 1\n" 5392 "# include <someheader.h>\n" 5393 "# define MACRO \\\n" 5394 " some_very_long_func_aaaaaaaaaa();\n" 5395 "# endif\n" 5396 "#else\n" 5397 "# define A 1\n" 5398 "#endif", 5399 Style); 5400 verifyFormat("#if A\n" 5401 "# define MACRO \\\n" 5402 " void a(int x) { \\\n" 5403 " b(); \\\n" 5404 " c(); \\\n" 5405 " d(); \\\n" 5406 " e(); \\\n" 5407 " f(); \\\n" 5408 " }\n" 5409 "#endif", 5410 Style); 5411 // Comments before include guard. 5412 verifyFormat("// file comment\n" 5413 "// file comment\n" 5414 "#ifndef HEADER_H\n" 5415 "#define HEADER_H\n" 5416 "code();\n" 5417 "#endif", 5418 Style); 5419 // Test with include guards. 5420 verifyFormat("#ifndef HEADER_H\n" 5421 "#define HEADER_H\n" 5422 "code();\n" 5423 "#endif", 5424 Style); 5425 // Include guards must have a #define with the same variable immediately 5426 // after #ifndef. 5427 verifyFormat("#ifndef NOT_GUARD\n" 5428 "# define FOO\n" 5429 "code();\n" 5430 "#endif", 5431 Style); 5432 5433 // Include guards must cover the entire file. 5434 verifyFormat("code();\n" 5435 "code();\n" 5436 "#ifndef NOT_GUARD\n" 5437 "# define NOT_GUARD\n" 5438 "code();\n" 5439 "#endif", 5440 Style); 5441 verifyFormat("#ifndef NOT_GUARD\n" 5442 "# define NOT_GUARD\n" 5443 "code();\n" 5444 "#endif\n" 5445 "code();", 5446 Style); 5447 // Test with trailing blank lines. 5448 verifyFormat("#ifndef HEADER_H\n" 5449 "#define HEADER_H\n" 5450 "code();\n" 5451 "#endif\n", 5452 Style); 5453 // Include guards don't have #else. 5454 verifyFormat("#ifndef NOT_GUARD\n" 5455 "# define NOT_GUARD\n" 5456 "code();\n" 5457 "#else\n" 5458 "#endif", 5459 Style); 5460 verifyFormat("#ifndef NOT_GUARD\n" 5461 "# define NOT_GUARD\n" 5462 "code();\n" 5463 "#elif FOO\n" 5464 "#endif", 5465 Style); 5466 // Non-identifier #define after potential include guard. 5467 verifyFormat("#ifndef FOO\n" 5468 "# define 1\n" 5469 "#endif\n", 5470 Style); 5471 // #if closes past last non-preprocessor line. 5472 verifyFormat("#ifndef FOO\n" 5473 "#define FOO\n" 5474 "#if 1\n" 5475 "int i;\n" 5476 "# define A 0\n" 5477 "#endif\n" 5478 "#endif\n", 5479 Style); 5480 // Don't crash if there is an #elif directive without a condition. 5481 verifyFormat("#if 1\n" 5482 "int x;\n" 5483 "#elif\n" 5484 "int y;\n" 5485 "#else\n" 5486 "int z;\n" 5487 "#endif", 5488 Style); 5489 // FIXME: This doesn't handle the case where there's code between the 5490 // #ifndef and #define but all other conditions hold. This is because when 5491 // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the 5492 // previous code line yet, so we can't detect it. 5493 EXPECT_EQ("#ifndef NOT_GUARD\n" 5494 "code();\n" 5495 "#define NOT_GUARD\n" 5496 "code();\n" 5497 "#endif", 5498 format("#ifndef NOT_GUARD\n" 5499 "code();\n" 5500 "# define NOT_GUARD\n" 5501 "code();\n" 5502 "#endif", 5503 Style)); 5504 // FIXME: This doesn't handle cases where legitimate preprocessor lines may 5505 // be outside an include guard. Examples are #pragma once and 5506 // #pragma GCC diagnostic, or anything else that does not change the meaning 5507 // of the file if it's included multiple times. 5508 EXPECT_EQ("#ifdef WIN32\n" 5509 "# pragma once\n" 5510 "#endif\n" 5511 "#ifndef HEADER_H\n" 5512 "# define HEADER_H\n" 5513 "code();\n" 5514 "#endif", 5515 format("#ifdef WIN32\n" 5516 "# pragma once\n" 5517 "#endif\n" 5518 "#ifndef HEADER_H\n" 5519 "#define HEADER_H\n" 5520 "code();\n" 5521 "#endif", 5522 Style)); 5523 // FIXME: This does not detect when there is a single non-preprocessor line 5524 // in front of an include-guard-like structure where other conditions hold 5525 // because ScopedLineState hides the line. 5526 EXPECT_EQ("code();\n" 5527 "#ifndef HEADER_H\n" 5528 "#define HEADER_H\n" 5529 "code();\n" 5530 "#endif", 5531 format("code();\n" 5532 "#ifndef HEADER_H\n" 5533 "# define HEADER_H\n" 5534 "code();\n" 5535 "#endif", 5536 Style)); 5537 // Keep comments aligned with #, otherwise indent comments normally. These 5538 // tests cannot use verifyFormat because messUp manipulates leading 5539 // whitespace. 5540 { 5541 const char *Expected = "" 5542 "void f() {\n" 5543 "#if 1\n" 5544 "// Preprocessor aligned.\n" 5545 "# define A 0\n" 5546 " // Code. Separated by blank line.\n" 5547 "\n" 5548 "# define B 0\n" 5549 " // Code. Not aligned with #\n" 5550 "# define C 0\n" 5551 "#endif"; 5552 const char *ToFormat = "" 5553 "void f() {\n" 5554 "#if 1\n" 5555 "// Preprocessor aligned.\n" 5556 "# define A 0\n" 5557 "// Code. Separated by blank line.\n" 5558 "\n" 5559 "# define B 0\n" 5560 " // Code. Not aligned with #\n" 5561 "# define C 0\n" 5562 "#endif"; 5563 EXPECT_EQ(Expected, format(ToFormat, Style)); 5564 EXPECT_EQ(Expected, format(Expected, Style)); 5565 } 5566 // Keep block quotes aligned. 5567 { 5568 const char *Expected = "" 5569 "void f() {\n" 5570 "#if 1\n" 5571 "/* Preprocessor aligned. */\n" 5572 "# define A 0\n" 5573 " /* Code. Separated by blank line. */\n" 5574 "\n" 5575 "# define B 0\n" 5576 " /* Code. Not aligned with # */\n" 5577 "# define C 0\n" 5578 "#endif"; 5579 const char *ToFormat = "" 5580 "void f() {\n" 5581 "#if 1\n" 5582 "/* Preprocessor aligned. */\n" 5583 "# define A 0\n" 5584 "/* Code. Separated by blank line. */\n" 5585 "\n" 5586 "# define B 0\n" 5587 " /* Code. Not aligned with # */\n" 5588 "# define C 0\n" 5589 "#endif"; 5590 EXPECT_EQ(Expected, format(ToFormat, Style)); 5591 EXPECT_EQ(Expected, format(Expected, Style)); 5592 } 5593 // Keep comments aligned with un-indented directives. 5594 { 5595 const char *Expected = "" 5596 "void f() {\n" 5597 "// Preprocessor aligned.\n" 5598 "#define A 0\n" 5599 " // Code. Separated by blank line.\n" 5600 "\n" 5601 "#define B 0\n" 5602 " // Code. Not aligned with #\n" 5603 "#define C 0\n"; 5604 const char *ToFormat = "" 5605 "void f() {\n" 5606 "// Preprocessor aligned.\n" 5607 "#define A 0\n" 5608 "// Code. Separated by blank line.\n" 5609 "\n" 5610 "#define B 0\n" 5611 " // Code. Not aligned with #\n" 5612 "#define C 0\n"; 5613 EXPECT_EQ(Expected, format(ToFormat, Style)); 5614 EXPECT_EQ(Expected, format(Expected, Style)); 5615 } 5616 // Test AfterHash with tabs. 5617 { 5618 FormatStyle Tabbed = Style; 5619 Tabbed.UseTab = FormatStyle::UT_Always; 5620 Tabbed.IndentWidth = 8; 5621 Tabbed.TabWidth = 8; 5622 verifyFormat("#ifdef _WIN32\n" 5623 "#\tdefine A 0\n" 5624 "#\tifdef VAR2\n" 5625 "#\t\tdefine B 1\n" 5626 "#\t\tinclude <someheader.h>\n" 5627 "#\t\tdefine MACRO \\\n" 5628 "\t\t\tsome_very_long_func_aaaaaaaaaa();\n" 5629 "#\tendif\n" 5630 "#else\n" 5631 "#\tdefine A 1\n" 5632 "#endif", 5633 Tabbed); 5634 } 5635 5636 // Regression test: Multiline-macro inside include guards. 5637 verifyFormat("#ifndef HEADER_H\n" 5638 "#define HEADER_H\n" 5639 "#define A() \\\n" 5640 " int i; \\\n" 5641 " int j;\n" 5642 "#endif // HEADER_H", 5643 getLLVMStyleWithColumns(20)); 5644 5645 Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash; 5646 // Basic before hash indent tests 5647 verifyFormat("#ifdef _WIN32\n" 5648 " #define A 0\n" 5649 " #ifdef VAR2\n" 5650 " #define B 1\n" 5651 " #include <someheader.h>\n" 5652 " #define MACRO \\\n" 5653 " some_very_long_func_aaaaaaaaaa();\n" 5654 " #endif\n" 5655 "#else\n" 5656 " #define A 1\n" 5657 "#endif", 5658 Style); 5659 verifyFormat("#if A\n" 5660 " #define MACRO \\\n" 5661 " void a(int x) { \\\n" 5662 " b(); \\\n" 5663 " c(); \\\n" 5664 " d(); \\\n" 5665 " e(); \\\n" 5666 " f(); \\\n" 5667 " }\n" 5668 "#endif", 5669 Style); 5670 // Keep comments aligned with indented directives. These 5671 // tests cannot use verifyFormat because messUp manipulates leading 5672 // whitespace. 5673 { 5674 const char *Expected = "void f() {\n" 5675 "// Aligned to preprocessor.\n" 5676 "#if 1\n" 5677 " // Aligned to code.\n" 5678 " int a;\n" 5679 " #if 1\n" 5680 " // Aligned to preprocessor.\n" 5681 " #define A 0\n" 5682 " // Aligned to code.\n" 5683 " int b;\n" 5684 " #endif\n" 5685 "#endif\n" 5686 "}"; 5687 const char *ToFormat = "void f() {\n" 5688 "// Aligned to preprocessor.\n" 5689 "#if 1\n" 5690 "// Aligned to code.\n" 5691 "int a;\n" 5692 "#if 1\n" 5693 "// Aligned to preprocessor.\n" 5694 "#define A 0\n" 5695 "// Aligned to code.\n" 5696 "int b;\n" 5697 "#endif\n" 5698 "#endif\n" 5699 "}"; 5700 EXPECT_EQ(Expected, format(ToFormat, Style)); 5701 EXPECT_EQ(Expected, format(Expected, Style)); 5702 } 5703 { 5704 const char *Expected = "void f() {\n" 5705 "/* Aligned to preprocessor. */\n" 5706 "#if 1\n" 5707 " /* Aligned to code. */\n" 5708 " int a;\n" 5709 " #if 1\n" 5710 " /* Aligned to preprocessor. */\n" 5711 " #define A 0\n" 5712 " /* Aligned to code. */\n" 5713 " int b;\n" 5714 " #endif\n" 5715 "#endif\n" 5716 "}"; 5717 const char *ToFormat = "void f() {\n" 5718 "/* Aligned to preprocessor. */\n" 5719 "#if 1\n" 5720 "/* Aligned to code. */\n" 5721 "int a;\n" 5722 "#if 1\n" 5723 "/* Aligned to preprocessor. */\n" 5724 "#define A 0\n" 5725 "/* Aligned to code. */\n" 5726 "int b;\n" 5727 "#endif\n" 5728 "#endif\n" 5729 "}"; 5730 EXPECT_EQ(Expected, format(ToFormat, Style)); 5731 EXPECT_EQ(Expected, format(Expected, Style)); 5732 } 5733 5734 // Test single comment before preprocessor 5735 verifyFormat("// Comment\n" 5736 "\n" 5737 "#if 1\n" 5738 "#endif", 5739 Style); 5740 } 5741 5742 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) { 5743 verifyFormat("{\n { a #c; }\n}"); 5744 } 5745 5746 TEST_F(FormatTest, FormatUnbalancedStructuralElements) { 5747 EXPECT_EQ("#define A \\\n { \\\n {\nint i;", 5748 format("#define A { {\nint i;", getLLVMStyleWithColumns(11))); 5749 EXPECT_EQ("#define A \\\n } \\\n }\nint i;", 5750 format("#define A } }\nint i;", getLLVMStyleWithColumns(11))); 5751 } 5752 5753 TEST_F(FormatTest, EscapedNewlines) { 5754 FormatStyle Narrow = getLLVMStyleWithColumns(11); 5755 EXPECT_EQ("#define A \\\n int i; \\\n int j;", 5756 format("#define A \\\nint i;\\\n int j;", Narrow)); 5757 EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;")); 5758 EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();")); 5759 EXPECT_EQ("/* \\ \\ \\\n */", format("\\\n/* \\ \\ \\\n */")); 5760 EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>")); 5761 5762 FormatStyle AlignLeft = getLLVMStyle(); 5763 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left; 5764 EXPECT_EQ("#define MACRO(x) \\\n" 5765 "private: \\\n" 5766 " int x(int a);\n", 5767 format("#define MACRO(x) \\\n" 5768 "private: \\\n" 5769 " int x(int a);\n", 5770 AlignLeft)); 5771 5772 // CRLF line endings 5773 EXPECT_EQ("#define A \\\r\n int i; \\\r\n int j;", 5774 format("#define A \\\r\nint i;\\\r\n int j;", Narrow)); 5775 EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;")); 5776 EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();")); 5777 EXPECT_EQ("/* \\ \\ \\\r\n */", format("\\\r\n/* \\ \\ \\\r\n */")); 5778 EXPECT_EQ("<a\r\n\\\\\r\n>", format("<a\r\n\\\\\r\n>")); 5779 EXPECT_EQ("#define MACRO(x) \\\r\n" 5780 "private: \\\r\n" 5781 " int x(int a);\r\n", 5782 format("#define MACRO(x) \\\r\n" 5783 "private: \\\r\n" 5784 " int x(int a);\r\n", 5785 AlignLeft)); 5786 5787 FormatStyle DontAlign = getLLVMStyle(); 5788 DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 5789 DontAlign.MaxEmptyLinesToKeep = 3; 5790 // FIXME: can't use verifyFormat here because the newline before 5791 // "public:" is not inserted the first time it's reformatted 5792 EXPECT_EQ("#define A \\\n" 5793 " class Foo { \\\n" 5794 " void bar(); \\\n" 5795 "\\\n" 5796 "\\\n" 5797 "\\\n" 5798 " public: \\\n" 5799 " void baz(); \\\n" 5800 " };", 5801 format("#define A \\\n" 5802 " class Foo { \\\n" 5803 " void bar(); \\\n" 5804 "\\\n" 5805 "\\\n" 5806 "\\\n" 5807 " public: \\\n" 5808 " void baz(); \\\n" 5809 " };", 5810 DontAlign)); 5811 } 5812 5813 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) { 5814 verifyFormat("#define A \\\n" 5815 " int v( \\\n" 5816 " a); \\\n" 5817 " int i;", 5818 getLLVMStyleWithColumns(11)); 5819 } 5820 5821 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) { 5822 EXPECT_EQ( 5823 "#define ALooooooooooooooooooooooooooooooooooooooongMacro(" 5824 " \\\n" 5825 " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n" 5826 "\n" 5827 "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n" 5828 " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n", 5829 format(" #define ALooooooooooooooooooooooooooooooooooooooongMacro(" 5830 "\\\n" 5831 "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n" 5832 " \n" 5833 " AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n" 5834 " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n")); 5835 } 5836 5837 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) { 5838 EXPECT_EQ("int\n" 5839 "#define A\n" 5840 " a;", 5841 format("int\n#define A\na;")); 5842 verifyFormat("functionCallTo(\n" 5843 " someOtherFunction(\n" 5844 " withSomeParameters, whichInSequence,\n" 5845 " areLongerThanALine(andAnotherCall,\n" 5846 "#define A B\n" 5847 " withMoreParamters,\n" 5848 " whichStronglyInfluenceTheLayout),\n" 5849 " andMoreParameters),\n" 5850 " trailing);", 5851 getLLVMStyleWithColumns(69)); 5852 verifyFormat("Foo::Foo()\n" 5853 "#ifdef BAR\n" 5854 " : baz(0)\n" 5855 "#endif\n" 5856 "{\n" 5857 "}"); 5858 verifyFormat("void f() {\n" 5859 " if (true)\n" 5860 "#ifdef A\n" 5861 " f(42);\n" 5862 " x();\n" 5863 "#else\n" 5864 " g();\n" 5865 " x();\n" 5866 "#endif\n" 5867 "}"); 5868 verifyFormat("void f(param1, param2,\n" 5869 " param3,\n" 5870 "#ifdef A\n" 5871 " param4(param5,\n" 5872 "#ifdef A1\n" 5873 " param6,\n" 5874 "#ifdef A2\n" 5875 " param7),\n" 5876 "#else\n" 5877 " param8),\n" 5878 " param9,\n" 5879 "#endif\n" 5880 " param10,\n" 5881 "#endif\n" 5882 " param11)\n" 5883 "#else\n" 5884 " param12)\n" 5885 "#endif\n" 5886 "{\n" 5887 " x();\n" 5888 "}", 5889 getLLVMStyleWithColumns(28)); 5890 verifyFormat("#if 1\n" 5891 "int i;"); 5892 verifyFormat("#if 1\n" 5893 "#endif\n" 5894 "#if 1\n" 5895 "#else\n" 5896 "#endif\n"); 5897 verifyFormat("DEBUG({\n" 5898 " return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5899 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n" 5900 "});\n" 5901 "#if a\n" 5902 "#else\n" 5903 "#endif"); 5904 5905 verifyIncompleteFormat("void f(\n" 5906 "#if A\n" 5907 ");\n" 5908 "#else\n" 5909 "#endif"); 5910 } 5911 5912 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) { 5913 verifyFormat("#endif\n" 5914 "#if B"); 5915 } 5916 5917 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) { 5918 FormatStyle SingleLine = getLLVMStyle(); 5919 SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse; 5920 verifyFormat("#if 0\n" 5921 "#elif 1\n" 5922 "#endif\n" 5923 "void foo() {\n" 5924 " if (test) foo2();\n" 5925 "}", 5926 SingleLine); 5927 } 5928 5929 TEST_F(FormatTest, LayoutBlockInsideParens) { 5930 verifyFormat("functionCall({ int i; });"); 5931 verifyFormat("functionCall({\n" 5932 " int i;\n" 5933 " int j;\n" 5934 "});"); 5935 verifyFormat("functionCall(\n" 5936 " {\n" 5937 " int i;\n" 5938 " int j;\n" 5939 " },\n" 5940 " aaaa, bbbb, cccc);"); 5941 verifyFormat("functionA(functionB({\n" 5942 " int i;\n" 5943 " int j;\n" 5944 " }),\n" 5945 " aaaa, bbbb, cccc);"); 5946 verifyFormat("functionCall(\n" 5947 " {\n" 5948 " int i;\n" 5949 " int j;\n" 5950 " },\n" 5951 " aaaa, bbbb, // comment\n" 5952 " cccc);"); 5953 verifyFormat("functionA(functionB({\n" 5954 " int i;\n" 5955 " int j;\n" 5956 " }),\n" 5957 " aaaa, bbbb, // comment\n" 5958 " cccc);"); 5959 verifyFormat("functionCall(aaaa, bbbb, { int i; });"); 5960 verifyFormat("functionCall(aaaa, bbbb, {\n" 5961 " int i;\n" 5962 " int j;\n" 5963 "});"); 5964 verifyFormat( 5965 "Aaa(\n" // FIXME: There shouldn't be a linebreak here. 5966 " {\n" 5967 " int i; // break\n" 5968 " },\n" 5969 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 5970 " ccccccccccccccccc));"); 5971 verifyFormat("DEBUG({\n" 5972 " if (a)\n" 5973 " f();\n" 5974 "});"); 5975 } 5976 5977 TEST_F(FormatTest, LayoutBlockInsideStatement) { 5978 EXPECT_EQ("SOME_MACRO { int i; }\n" 5979 "int i;", 5980 format(" SOME_MACRO {int i;} int i;")); 5981 } 5982 5983 TEST_F(FormatTest, LayoutNestedBlocks) { 5984 verifyFormat("void AddOsStrings(unsigned bitmask) {\n" 5985 " struct s {\n" 5986 " int i;\n" 5987 " };\n" 5988 " s kBitsToOs[] = {{10}};\n" 5989 " for (int i = 0; i < 10; ++i)\n" 5990 " return;\n" 5991 "}"); 5992 verifyFormat("call(parameter, {\n" 5993 " something();\n" 5994 " // Comment using all columns.\n" 5995 " somethingelse();\n" 5996 "});", 5997 getLLVMStyleWithColumns(40)); 5998 verifyFormat("DEBUG( //\n" 5999 " { f(); }, a);"); 6000 verifyFormat("DEBUG( //\n" 6001 " {\n" 6002 " f(); //\n" 6003 " },\n" 6004 " a);"); 6005 6006 EXPECT_EQ("call(parameter, {\n" 6007 " something();\n" 6008 " // Comment too\n" 6009 " // looooooooooong.\n" 6010 " somethingElse();\n" 6011 "});", 6012 format("call(parameter, {\n" 6013 " something();\n" 6014 " // Comment too looooooooooong.\n" 6015 " somethingElse();\n" 6016 "});", 6017 getLLVMStyleWithColumns(29))); 6018 EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int i; });")); 6019 EXPECT_EQ("DEBUG({ // comment\n" 6020 " int i;\n" 6021 "});", 6022 format("DEBUG({ // comment\n" 6023 "int i;\n" 6024 "});")); 6025 EXPECT_EQ("DEBUG({\n" 6026 " int i;\n" 6027 "\n" 6028 " // comment\n" 6029 " int j;\n" 6030 "});", 6031 format("DEBUG({\n" 6032 " int i;\n" 6033 "\n" 6034 " // comment\n" 6035 " int j;\n" 6036 "});")); 6037 6038 verifyFormat("DEBUG({\n" 6039 " if (a)\n" 6040 " return;\n" 6041 "});"); 6042 verifyGoogleFormat("DEBUG({\n" 6043 " if (a) return;\n" 6044 "});"); 6045 FormatStyle Style = getGoogleStyle(); 6046 Style.ColumnLimit = 45; 6047 verifyFormat("Debug(\n" 6048 " aaaaa,\n" 6049 " {\n" 6050 " if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n" 6051 " },\n" 6052 " a);", 6053 Style); 6054 6055 verifyFormat("SomeFunction({MACRO({ return output; }), b});"); 6056 6057 verifyNoCrash("^{v^{a}}"); 6058 } 6059 6060 TEST_F(FormatTest, FormatNestedBlocksInMacros) { 6061 EXPECT_EQ("#define MACRO() \\\n" 6062 " Debug(aaa, /* force line break */ \\\n" 6063 " { \\\n" 6064 " int i; \\\n" 6065 " int j; \\\n" 6066 " })", 6067 format("#define MACRO() Debug(aaa, /* force line break */ \\\n" 6068 " { int i; int j; })", 6069 getGoogleStyle())); 6070 6071 EXPECT_EQ("#define A \\\n" 6072 " [] { \\\n" 6073 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 6074 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n" 6075 " }", 6076 format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 6077 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }", 6078 getGoogleStyle())); 6079 } 6080 6081 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) { 6082 EXPECT_EQ("{}", format("{}")); 6083 verifyFormat("enum E {};"); 6084 verifyFormat("enum E {}"); 6085 FormatStyle Style = getLLVMStyle(); 6086 Style.SpaceInEmptyBlock = true; 6087 EXPECT_EQ("void f() { }", format("void f() {}", Style)); 6088 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 6089 EXPECT_EQ("while (true) { }", format("while (true) {}", Style)); 6090 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 6091 Style.BraceWrapping.BeforeElse = false; 6092 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 6093 verifyFormat("if (a)\n" 6094 "{\n" 6095 "} else if (b)\n" 6096 "{\n" 6097 "} else\n" 6098 "{ }", 6099 Style); 6100 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never; 6101 verifyFormat("if (a) {\n" 6102 "} else if (b) {\n" 6103 "} else {\n" 6104 "}", 6105 Style); 6106 Style.BraceWrapping.BeforeElse = true; 6107 verifyFormat("if (a) { }\n" 6108 "else if (b) { }\n" 6109 "else { }", 6110 Style); 6111 } 6112 6113 TEST_F(FormatTest, FormatBeginBlockEndMacros) { 6114 FormatStyle Style = getLLVMStyle(); 6115 Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$"; 6116 Style.MacroBlockEnd = "^[A-Z_]+_END$"; 6117 verifyFormat("FOO_BEGIN\n" 6118 " FOO_ENTRY\n" 6119 "FOO_END", 6120 Style); 6121 verifyFormat("FOO_BEGIN\n" 6122 " NESTED_FOO_BEGIN\n" 6123 " NESTED_FOO_ENTRY\n" 6124 " NESTED_FOO_END\n" 6125 "FOO_END", 6126 Style); 6127 verifyFormat("FOO_BEGIN(Foo, Bar)\n" 6128 " int x;\n" 6129 " x = 1;\n" 6130 "FOO_END(Baz)", 6131 Style); 6132 } 6133 6134 //===----------------------------------------------------------------------===// 6135 // Line break tests. 6136 //===----------------------------------------------------------------------===// 6137 6138 TEST_F(FormatTest, PreventConfusingIndents) { 6139 verifyFormat( 6140 "void f() {\n" 6141 " SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n" 6142 " parameter, parameter, parameter)),\n" 6143 " SecondLongCall(parameter));\n" 6144 "}"); 6145 verifyFormat( 6146 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6147 " aaaaaaaaaaaaaaaaaaaaaaaa(\n" 6148 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6149 " aaaaaaaaaaaaaaaaaaaaaaaa);"); 6150 verifyFormat( 6151 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6152 " [aaaaaaaaaaaaaaaaaaaaaaaa\n" 6153 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n" 6154 " [aaaaaaaaaaaaaaaaaaaaaaaa]];"); 6155 verifyFormat( 6156 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 6157 " aaaaaaaaaaaaaaaaaaaaaaaa<\n" 6158 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n" 6159 " aaaaaaaaaaaaaaaaaaaaaaaa>;"); 6160 verifyFormat("int a = bbbb && ccc &&\n" 6161 " fffff(\n" 6162 "#define A Just forcing a new line\n" 6163 " ddd);"); 6164 } 6165 6166 TEST_F(FormatTest, LineBreakingInBinaryExpressions) { 6167 verifyFormat( 6168 "bool aaaaaaa =\n" 6169 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n" 6170 " bbbbbbbb();"); 6171 verifyFormat( 6172 "bool aaaaaaa =\n" 6173 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n" 6174 " bbbbbbbb();"); 6175 6176 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n" 6177 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n" 6178 " ccccccccc == ddddddddddd;"); 6179 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n" 6180 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n" 6181 " ccccccccc == ddddddddddd;"); 6182 verifyFormat( 6183 "bool aaaaaaaaaaaaaaaaaaaaa =\n" 6184 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n" 6185 " ccccccccc == ddddddddddd;"); 6186 6187 verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n" 6188 " aaaaaa) &&\n" 6189 " bbbbbb && cccccc;"); 6190 verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n" 6191 " aaaaaa) >>\n" 6192 " bbbbbb;"); 6193 verifyFormat("aa = Whitespaces.addUntouchableComment(\n" 6194 " SourceMgr.getSpellingColumnNumber(\n" 6195 " TheLine.Last->FormatTok.Tok.getLocation()) -\n" 6196 " 1);"); 6197 6198 verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6199 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n" 6200 " cccccc) {\n}"); 6201 verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6202 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n" 6203 " cccccc) {\n}"); 6204 verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6205 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n" 6206 " cccccc) {\n}"); 6207 verifyFormat("b = a &&\n" 6208 " // Comment\n" 6209 " b.c && d;"); 6210 6211 // If the LHS of a comparison is not a binary expression itself, the 6212 // additional linebreak confuses many people. 6213 verifyFormat( 6214 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6215 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n" 6216 "}"); 6217 verifyFormat( 6218 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6219 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 6220 "}"); 6221 verifyFormat( 6222 "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n" 6223 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 6224 "}"); 6225 verifyFormat( 6226 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6227 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n" 6228 "}"); 6229 // Even explicit parentheses stress the precedence enough to make the 6230 // additional break unnecessary. 6231 verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6232 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 6233 "}"); 6234 // This cases is borderline, but with the indentation it is still readable. 6235 verifyFormat( 6236 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6237 " aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6238 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 6239 "}", 6240 getLLVMStyleWithColumns(75)); 6241 6242 // If the LHS is a binary expression, we should still use the additional break 6243 // as otherwise the formatting hides the operator precedence. 6244 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6245 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6246 " 5) {\n" 6247 "}"); 6248 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6249 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n" 6250 " 5) {\n" 6251 "}"); 6252 6253 FormatStyle OnePerLine = getLLVMStyle(); 6254 OnePerLine.BinPackParameters = false; 6255 verifyFormat( 6256 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6257 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6258 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}", 6259 OnePerLine); 6260 6261 verifyFormat("int i = someFunction(aaaaaaa, 0)\n" 6262 " .aaa(aaaaaaaaaaaaa) *\n" 6263 " aaaaaaa +\n" 6264 " aaaaaaa;", 6265 getLLVMStyleWithColumns(40)); 6266 } 6267 6268 TEST_F(FormatTest, ExpressionIndentation) { 6269 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6270 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6271 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6272 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6273 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n" 6274 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n" 6275 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6276 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n" 6277 " ccccccccccccccccccccccccccccccccccccccccc;"); 6278 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6279 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6280 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6281 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 6282 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6283 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6284 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6285 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 6286 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6287 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6288 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6289 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 6290 verifyFormat("if () {\n" 6291 "} else if (aaaaa && bbbbb > // break\n" 6292 " ccccc) {\n" 6293 "}"); 6294 verifyFormat("if () {\n" 6295 "} else if constexpr (aaaaa && bbbbb > // break\n" 6296 " ccccc) {\n" 6297 "}"); 6298 verifyFormat("if () {\n" 6299 "} else if CONSTEXPR (aaaaa && bbbbb > // break\n" 6300 " ccccc) {\n" 6301 "}"); 6302 verifyFormat("if () {\n" 6303 "} else if (aaaaa &&\n" 6304 " bbbbb > // break\n" 6305 " ccccc &&\n" 6306 " ddddd) {\n" 6307 "}"); 6308 6309 // Presence of a trailing comment used to change indentation of b. 6310 verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n" 6311 " b;\n" 6312 "return aaaaaaaaaaaaaaaaaaa +\n" 6313 " b; //", 6314 getLLVMStyleWithColumns(30)); 6315 } 6316 6317 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) { 6318 // Not sure what the best system is here. Like this, the LHS can be found 6319 // immediately above an operator (everything with the same or a higher 6320 // indent). The RHS is aligned right of the operator and so compasses 6321 // everything until something with the same indent as the operator is found. 6322 // FIXME: Is this a good system? 6323 FormatStyle Style = getLLVMStyle(); 6324 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 6325 verifyFormat( 6326 "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6327 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6328 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6329 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6330 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6331 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6332 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6333 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6334 " > ccccccccccccccccccccccccccccccccccccccccc;", 6335 Style); 6336 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6337 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6338 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6339 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6340 Style); 6341 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6342 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6343 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6344 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6345 Style); 6346 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6347 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6348 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6349 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6350 Style); 6351 verifyFormat("if () {\n" 6352 "} else if (aaaaa\n" 6353 " && bbbbb // break\n" 6354 " > ccccc) {\n" 6355 "}", 6356 Style); 6357 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6358 " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6359 Style); 6360 verifyFormat("return (a)\n" 6361 " // comment\n" 6362 " + b;", 6363 Style); 6364 verifyFormat( 6365 "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6366 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6367 " + cc;", 6368 Style); 6369 6370 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6371 " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 6372 Style); 6373 6374 // Forced by comments. 6375 verifyFormat( 6376 "unsigned ContentSize =\n" 6377 " sizeof(int16_t) // DWARF ARange version number\n" 6378 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6379 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6380 " + sizeof(int8_t); // Segment Size (in bytes)"); 6381 6382 verifyFormat("return boost::fusion::at_c<0>(iiii).second\n" 6383 " == boost::fusion::at_c<1>(iiii).second;", 6384 Style); 6385 6386 Style.ColumnLimit = 60; 6387 verifyFormat("zzzzzzzzzz\n" 6388 " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6389 " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);", 6390 Style); 6391 6392 Style.ColumnLimit = 80; 6393 Style.IndentWidth = 4; 6394 Style.TabWidth = 4; 6395 Style.UseTab = FormatStyle::UT_Always; 6396 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6397 Style.AlignOperands = FormatStyle::OAS_DontAlign; 6398 EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n" 6399 "\t&& (someOtherLongishConditionPart1\n" 6400 "\t\t|| someOtherEvenLongerNestedConditionPart2);", 6401 format("return someVeryVeryLongConditionThatBarelyFitsOnALine && " 6402 "(someOtherLongishConditionPart1 || " 6403 "someOtherEvenLongerNestedConditionPart2);", 6404 Style)); 6405 } 6406 6407 TEST_F(FormatTest, ExpressionIndentationStrictAlign) { 6408 FormatStyle Style = getLLVMStyle(); 6409 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 6410 Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator; 6411 6412 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6413 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6414 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6415 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6416 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6417 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6418 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6419 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6420 " > ccccccccccccccccccccccccccccccccccccccccc;", 6421 Style); 6422 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6423 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6424 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6425 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6426 Style); 6427 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6428 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6429 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6430 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6431 Style); 6432 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6433 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6434 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6435 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6436 Style); 6437 verifyFormat("if () {\n" 6438 "} else if (aaaaa\n" 6439 " && bbbbb // break\n" 6440 " > ccccc) {\n" 6441 "}", 6442 Style); 6443 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6444 " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6445 Style); 6446 verifyFormat("return (a)\n" 6447 " // comment\n" 6448 " + b;", 6449 Style); 6450 verifyFormat( 6451 "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6452 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6453 " + cc;", 6454 Style); 6455 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 6456 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 6457 " : 3333333333333333;", 6458 Style); 6459 verifyFormat( 6460 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 6461 " : ccccccccccccccc ? dddddddddddddddddd\n" 6462 " : eeeeeeeeeeeeeeeeee)\n" 6463 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 6464 " : 3333333333333333;", 6465 Style); 6466 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6467 " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 6468 Style); 6469 6470 verifyFormat("return boost::fusion::at_c<0>(iiii).second\n" 6471 " == boost::fusion::at_c<1>(iiii).second;", 6472 Style); 6473 6474 Style.ColumnLimit = 60; 6475 verifyFormat("zzzzzzzzzzzzz\n" 6476 " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6477 " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);", 6478 Style); 6479 6480 // Forced by comments. 6481 Style.ColumnLimit = 80; 6482 verifyFormat( 6483 "unsigned ContentSize\n" 6484 " = sizeof(int16_t) // DWARF ARange version number\n" 6485 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6486 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6487 " + sizeof(int8_t); // Segment Size (in bytes)", 6488 Style); 6489 6490 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6491 verifyFormat( 6492 "unsigned ContentSize =\n" 6493 " sizeof(int16_t) // DWARF ARange version number\n" 6494 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6495 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6496 " + sizeof(int8_t); // Segment Size (in bytes)", 6497 Style); 6498 6499 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 6500 verifyFormat( 6501 "unsigned ContentSize =\n" 6502 " sizeof(int16_t) // DWARF ARange version number\n" 6503 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6504 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6505 " + sizeof(int8_t); // Segment Size (in bytes)", 6506 Style); 6507 } 6508 6509 TEST_F(FormatTest, EnforcedOperatorWraps) { 6510 // Here we'd like to wrap after the || operators, but a comment is forcing an 6511 // earlier wrap. 6512 verifyFormat("bool x = aaaaa //\n" 6513 " || bbbbb\n" 6514 " //\n" 6515 " || cccc;"); 6516 } 6517 6518 TEST_F(FormatTest, NoOperandAlignment) { 6519 FormatStyle Style = getLLVMStyle(); 6520 Style.AlignOperands = FormatStyle::OAS_DontAlign; 6521 verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n" 6522 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6523 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 6524 Style); 6525 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6526 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6527 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6528 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6529 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6530 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6531 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6532 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6533 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6534 " > ccccccccccccccccccccccccccccccccccccccccc;", 6535 Style); 6536 6537 verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6538 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6539 " + cc;", 6540 Style); 6541 verifyFormat("int a = aa\n" 6542 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6543 " * cccccccccccccccccccccccccccccccccccc;\n", 6544 Style); 6545 6546 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6547 verifyFormat("return (a > b\n" 6548 " // comment1\n" 6549 " // comment2\n" 6550 " || c);", 6551 Style); 6552 } 6553 6554 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) { 6555 FormatStyle Style = getLLVMStyle(); 6556 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6557 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 6558 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6559 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6560 Style); 6561 } 6562 6563 TEST_F(FormatTest, AllowBinPackingInsideArguments) { 6564 FormatStyle Style = getLLVMStyleWithColumns(40); 6565 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6566 Style.BinPackArguments = false; 6567 verifyFormat("void test() {\n" 6568 " someFunction(\n" 6569 " this + argument + is + quite\n" 6570 " + long + so + it + gets + wrapped\n" 6571 " + but + remains + bin - packed);\n" 6572 "}", 6573 Style); 6574 verifyFormat("void test() {\n" 6575 " someFunction(arg1,\n" 6576 " this + argument + is\n" 6577 " + quite + long + so\n" 6578 " + it + gets + wrapped\n" 6579 " + but + remains + bin\n" 6580 " - packed,\n" 6581 " arg3);\n" 6582 "}", 6583 Style); 6584 verifyFormat("void test() {\n" 6585 " someFunction(\n" 6586 " arg1,\n" 6587 " this + argument + has\n" 6588 " + anotherFunc(nested,\n" 6589 " calls + whose\n" 6590 " + arguments\n" 6591 " + are + also\n" 6592 " + wrapped,\n" 6593 " in + addition)\n" 6594 " + to + being + bin - packed,\n" 6595 " arg3);\n" 6596 "}", 6597 Style); 6598 6599 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 6600 verifyFormat("void test() {\n" 6601 " someFunction(\n" 6602 " arg1,\n" 6603 " this + argument + has +\n" 6604 " anotherFunc(nested,\n" 6605 " calls + whose +\n" 6606 " arguments +\n" 6607 " are + also +\n" 6608 " wrapped,\n" 6609 " in + addition) +\n" 6610 " to + being + bin - packed,\n" 6611 " arg3);\n" 6612 "}", 6613 Style); 6614 } 6615 6616 TEST_F(FormatTest, BreakBinaryOperatorsInPresenceOfTemplates) { 6617 auto Style = getLLVMStyleWithColumns(45); 6618 EXPECT_EQ(Style.BreakBeforeBinaryOperators, FormatStyle::BOS_None); 6619 verifyFormat("bool b =\n" 6620 " is_default_constructible_v<hash<T>> and\n" 6621 " is_copy_constructible_v<hash<T>> and\n" 6622 " is_move_constructible_v<hash<T>> and\n" 6623 " is_copy_assignable_v<hash<T>> and\n" 6624 " is_move_assignable_v<hash<T>> and\n" 6625 " is_destructible_v<hash<T>> and\n" 6626 " is_swappable_v<hash<T>> and\n" 6627 " is_callable_v<hash<T>(T)>;", 6628 Style); 6629 6630 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6631 verifyFormat("bool b = is_default_constructible_v<hash<T>>\n" 6632 " and is_copy_constructible_v<hash<T>>\n" 6633 " and is_move_constructible_v<hash<T>>\n" 6634 " and is_copy_assignable_v<hash<T>>\n" 6635 " and is_move_assignable_v<hash<T>>\n" 6636 " and is_destructible_v<hash<T>>\n" 6637 " and is_swappable_v<hash<T>>\n" 6638 " and is_callable_v<hash<T>(T)>;", 6639 Style); 6640 6641 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 6642 verifyFormat("bool b = is_default_constructible_v<hash<T>>\n" 6643 " and is_copy_constructible_v<hash<T>>\n" 6644 " and is_move_constructible_v<hash<T>>\n" 6645 " and is_copy_assignable_v<hash<T>>\n" 6646 " and is_move_assignable_v<hash<T>>\n" 6647 " and is_destructible_v<hash<T>>\n" 6648 " and is_swappable_v<hash<T>>\n" 6649 " and is_callable_v<hash<T>(T)>;", 6650 Style); 6651 } 6652 6653 TEST_F(FormatTest, ConstructorInitializers) { 6654 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}"); 6655 verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}", 6656 getLLVMStyleWithColumns(45)); 6657 verifyFormat("Constructor()\n" 6658 " : Inttializer(FitsOnTheLine) {}", 6659 getLLVMStyleWithColumns(44)); 6660 verifyFormat("Constructor()\n" 6661 " : Inttializer(FitsOnTheLine) {}", 6662 getLLVMStyleWithColumns(43)); 6663 6664 verifyFormat("template <typename T>\n" 6665 "Constructor() : Initializer(FitsOnTheLine) {}", 6666 getLLVMStyleWithColumns(45)); 6667 6668 verifyFormat( 6669 "SomeClass::Constructor()\n" 6670 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}"); 6671 6672 verifyFormat( 6673 "SomeClass::Constructor()\n" 6674 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6675 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}"); 6676 verifyFormat( 6677 "SomeClass::Constructor()\n" 6678 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6679 " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}"); 6680 verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6681 " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 6682 " : aaaaaaaaaa(aaaaaa) {}"); 6683 6684 verifyFormat("Constructor()\n" 6685 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6686 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6687 " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6688 " aaaaaaaaaaaaaaaaaaaaaaa() {}"); 6689 6690 verifyFormat("Constructor()\n" 6691 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6692 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 6693 6694 verifyFormat("Constructor(int Parameter = 0)\n" 6695 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n" 6696 " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}"); 6697 verifyFormat("Constructor()\n" 6698 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n" 6699 "}", 6700 getLLVMStyleWithColumns(60)); 6701 verifyFormat("Constructor()\n" 6702 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6703 " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}"); 6704 6705 // Here a line could be saved by splitting the second initializer onto two 6706 // lines, but that is not desirable. 6707 verifyFormat("Constructor()\n" 6708 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n" 6709 " aaaaaaaaaaa(aaaaaaaaaaa),\n" 6710 " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 6711 6712 FormatStyle OnePerLine = getLLVMStyle(); 6713 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_Never; 6714 verifyFormat("MyClass::MyClass()\n" 6715 " : a(a),\n" 6716 " b(b),\n" 6717 " c(c) {}", 6718 OnePerLine); 6719 verifyFormat("MyClass::MyClass()\n" 6720 " : a(a), // comment\n" 6721 " b(b),\n" 6722 " c(c) {}", 6723 OnePerLine); 6724 verifyFormat("MyClass::MyClass(int a)\n" 6725 " : b(a), // comment\n" 6726 " c(a + 1) { // lined up\n" 6727 "}", 6728 OnePerLine); 6729 verifyFormat("Constructor()\n" 6730 " : a(b, b, b) {}", 6731 OnePerLine); 6732 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6733 OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false; 6734 verifyFormat("SomeClass::Constructor()\n" 6735 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6736 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6737 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6738 OnePerLine); 6739 verifyFormat("SomeClass::Constructor()\n" 6740 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n" 6741 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6742 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6743 OnePerLine); 6744 verifyFormat("MyClass::MyClass(int var)\n" 6745 " : some_var_(var), // 4 space indent\n" 6746 " some_other_var_(var + 1) { // lined up\n" 6747 "}", 6748 OnePerLine); 6749 verifyFormat("Constructor()\n" 6750 " : aaaaa(aaaaaa),\n" 6751 " aaaaa(aaaaaa),\n" 6752 " aaaaa(aaaaaa),\n" 6753 " aaaaa(aaaaaa),\n" 6754 " aaaaa(aaaaaa) {}", 6755 OnePerLine); 6756 verifyFormat("Constructor()\n" 6757 " : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n" 6758 " aaaaaaaaaaaaaaaaaaaaaa) {}", 6759 OnePerLine); 6760 OnePerLine.BinPackParameters = false; 6761 verifyFormat( 6762 "Constructor()\n" 6763 " : aaaaaaaaaaaaaaaaaaaaaaaa(\n" 6764 " aaaaaaaaaaa().aaa(),\n" 6765 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6766 OnePerLine); 6767 OnePerLine.ColumnLimit = 60; 6768 verifyFormat("Constructor()\n" 6769 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6770 " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}", 6771 OnePerLine); 6772 6773 EXPECT_EQ("Constructor()\n" 6774 " : // Comment forcing unwanted break.\n" 6775 " aaaa(aaaa) {}", 6776 format("Constructor() :\n" 6777 " // Comment forcing unwanted break.\n" 6778 " aaaa(aaaa) {}")); 6779 } 6780 6781 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) { 6782 FormatStyle Style = getLLVMStyleWithColumns(60); 6783 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6784 Style.BinPackParameters = false; 6785 6786 for (int i = 0; i < 4; ++i) { 6787 // Test all combinations of parameters that should not have an effect. 6788 Style.AllowAllParametersOfDeclarationOnNextLine = i & 1; 6789 Style.AllowAllArgumentsOnNextLine = i & 2; 6790 6791 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6792 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6793 verifyFormat("Constructor()\n" 6794 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6795 Style); 6796 verifyFormat("Constructor() : a(a), b(b) {}", Style); 6797 6798 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6799 verifyFormat("Constructor()\n" 6800 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6801 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6802 Style); 6803 verifyFormat("Constructor() : a(a), b(b) {}", Style); 6804 6805 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 6806 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6807 verifyFormat("Constructor()\n" 6808 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6809 Style); 6810 6811 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6812 verifyFormat("Constructor()\n" 6813 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6814 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6815 Style); 6816 6817 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6818 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6819 verifyFormat("Constructor() :\n" 6820 " aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6821 Style); 6822 6823 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6824 verifyFormat("Constructor() :\n" 6825 " aaaaaaaaaaaaaaaaaa(a),\n" 6826 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6827 Style); 6828 } 6829 6830 // Test interactions between AllowAllParametersOfDeclarationOnNextLine and 6831 // AllowAllConstructorInitializersOnNextLine in all 6832 // BreakConstructorInitializers modes 6833 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6834 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6835 verifyFormat("SomeClassWithALongName::Constructor(\n" 6836 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n" 6837 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6838 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6839 Style); 6840 6841 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6842 verifyFormat("SomeClassWithALongName::Constructor(\n" 6843 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6844 " int bbbbbbbbbbbbb,\n" 6845 " int cccccccccccccccc)\n" 6846 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6847 Style); 6848 6849 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6850 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6851 verifyFormat("SomeClassWithALongName::Constructor(\n" 6852 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6853 " int bbbbbbbbbbbbb)\n" 6854 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6855 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6856 Style); 6857 6858 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 6859 6860 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6861 verifyFormat("SomeClassWithALongName::Constructor(\n" 6862 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n" 6863 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6864 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6865 Style); 6866 6867 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6868 verifyFormat("SomeClassWithALongName::Constructor(\n" 6869 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6870 " int bbbbbbbbbbbbb,\n" 6871 " int cccccccccccccccc)\n" 6872 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6873 Style); 6874 6875 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6876 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6877 verifyFormat("SomeClassWithALongName::Constructor(\n" 6878 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6879 " int bbbbbbbbbbbbb)\n" 6880 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6881 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6882 Style); 6883 6884 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6885 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6886 verifyFormat("SomeClassWithALongName::Constructor(\n" 6887 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n" 6888 " aaaaaaaaaaaaaaaaaaaa(a),\n" 6889 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6890 Style); 6891 6892 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6893 verifyFormat("SomeClassWithALongName::Constructor(\n" 6894 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6895 " int bbbbbbbbbbbbb,\n" 6896 " int cccccccccccccccc) :\n" 6897 " aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6898 Style); 6899 6900 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6901 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6902 verifyFormat("SomeClassWithALongName::Constructor(\n" 6903 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6904 " int bbbbbbbbbbbbb) :\n" 6905 " aaaaaaaaaaaaaaaaaaaa(a),\n" 6906 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6907 Style); 6908 } 6909 6910 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) { 6911 FormatStyle Style = getLLVMStyleWithColumns(60); 6912 Style.BinPackArguments = false; 6913 for (int i = 0; i < 4; ++i) { 6914 // Test all combinations of parameters that should not have an effect. 6915 Style.AllowAllParametersOfDeclarationOnNextLine = i & 1; 6916 Style.PackConstructorInitializers = 6917 i & 2 ? FormatStyle::PCIS_BinPack : FormatStyle::PCIS_Never; 6918 6919 Style.AllowAllArgumentsOnNextLine = true; 6920 verifyFormat("void foo() {\n" 6921 " FunctionCallWithReallyLongName(\n" 6922 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n" 6923 "}", 6924 Style); 6925 Style.AllowAllArgumentsOnNextLine = false; 6926 verifyFormat("void foo() {\n" 6927 " FunctionCallWithReallyLongName(\n" 6928 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6929 " bbbbbbbbbbbb);\n" 6930 "}", 6931 Style); 6932 6933 Style.AllowAllArgumentsOnNextLine = true; 6934 verifyFormat("void foo() {\n" 6935 " auto VariableWithReallyLongName = {\n" 6936 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n" 6937 "}", 6938 Style); 6939 Style.AllowAllArgumentsOnNextLine = false; 6940 verifyFormat("void foo() {\n" 6941 " auto VariableWithReallyLongName = {\n" 6942 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6943 " bbbbbbbbbbbb};\n" 6944 "}", 6945 Style); 6946 } 6947 6948 // This parameter should not affect declarations. 6949 Style.BinPackParameters = false; 6950 Style.AllowAllArgumentsOnNextLine = false; 6951 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6952 verifyFormat("void FunctionCallWithReallyLongName(\n" 6953 " int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);", 6954 Style); 6955 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6956 verifyFormat("void FunctionCallWithReallyLongName(\n" 6957 " int aaaaaaaaaaaaaaaaaaaaaaa,\n" 6958 " int bbbbbbbbbbbb);", 6959 Style); 6960 } 6961 6962 TEST_F(FormatTest, AllowAllArgumentsOnNextLineDontAlign) { 6963 // Check that AllowAllArgumentsOnNextLine is respected for both BAS_DontAlign 6964 // and BAS_Align. 6965 FormatStyle Style = getLLVMStyleWithColumns(35); 6966 StringRef Input = "functionCall(paramA, paramB, paramC);\n" 6967 "void functionDecl(int A, int B, int C);"; 6968 Style.AllowAllArgumentsOnNextLine = false; 6969 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6970 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6971 " paramC);\n" 6972 "void functionDecl(int A, int B,\n" 6973 " int C);"), 6974 format(Input, Style)); 6975 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 6976 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6977 " paramC);\n" 6978 "void functionDecl(int A, int B,\n" 6979 " int C);"), 6980 format(Input, Style)); 6981 // However, BAS_AlwaysBreak should take precedence over 6982 // AllowAllArgumentsOnNextLine. 6983 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 6984 EXPECT_EQ(StringRef("functionCall(\n" 6985 " paramA, paramB, paramC);\n" 6986 "void functionDecl(\n" 6987 " int A, int B, int C);"), 6988 format(Input, Style)); 6989 6990 // When AllowAllArgumentsOnNextLine is set, we prefer breaking before the 6991 // first argument. 6992 Style.AllowAllArgumentsOnNextLine = true; 6993 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 6994 EXPECT_EQ(StringRef("functionCall(\n" 6995 " paramA, paramB, paramC);\n" 6996 "void functionDecl(\n" 6997 " int A, int B, int C);"), 6998 format(Input, Style)); 6999 // It wouldn't fit on one line with aligned parameters so this setting 7000 // doesn't change anything for BAS_Align. 7001 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 7002 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 7003 " paramC);\n" 7004 "void functionDecl(int A, int B,\n" 7005 " int C);"), 7006 format(Input, Style)); 7007 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 7008 EXPECT_EQ(StringRef("functionCall(\n" 7009 " paramA, paramB, paramC);\n" 7010 "void functionDecl(\n" 7011 " int A, int B, int C);"), 7012 format(Input, Style)); 7013 } 7014 7015 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) { 7016 FormatStyle Style = getLLVMStyle(); 7017 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 7018 7019 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}"); 7020 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}", 7021 getStyleWithColumns(Style, 45)); 7022 verifyFormat("Constructor() :\n" 7023 " Initializer(FitsOnTheLine) {}", 7024 getStyleWithColumns(Style, 44)); 7025 verifyFormat("Constructor() :\n" 7026 " Initializer(FitsOnTheLine) {}", 7027 getStyleWithColumns(Style, 43)); 7028 7029 verifyFormat("template <typename T>\n" 7030 "Constructor() : Initializer(FitsOnTheLine) {}", 7031 getStyleWithColumns(Style, 50)); 7032 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 7033 verifyFormat( 7034 "SomeClass::Constructor() :\n" 7035 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 7036 Style); 7037 verifyFormat( 7038 "SomeClass::Constructor() : // NOLINT\n" 7039 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 7040 Style); 7041 7042 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 7043 verifyFormat( 7044 "SomeClass::Constructor() :\n" 7045 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 7046 Style); 7047 7048 verifyFormat( 7049 "SomeClass::Constructor() :\n" 7050 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 7051 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 7052 Style); 7053 verifyFormat( 7054 "SomeClass::Constructor() :\n" 7055 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7056 " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 7057 Style); 7058 verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7059 " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 7060 " aaaaaaaaaa(aaaaaa) {}", 7061 Style); 7062 7063 verifyFormat("Constructor() :\n" 7064 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7065 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7066 " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7067 " aaaaaaaaaaaaaaaaaaaaaaa() {}", 7068 Style); 7069 7070 verifyFormat("Constructor() :\n" 7071 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7072 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7073 Style); 7074 7075 verifyFormat("Constructor(int Parameter = 0) :\n" 7076 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n" 7077 " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}", 7078 Style); 7079 verifyFormat("Constructor() :\n" 7080 " aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n" 7081 "}", 7082 getStyleWithColumns(Style, 60)); 7083 verifyFormat("Constructor() :\n" 7084 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7085 " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}", 7086 Style); 7087 7088 // Here a line could be saved by splitting the second initializer onto two 7089 // lines, but that is not desirable. 7090 verifyFormat("Constructor() :\n" 7091 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n" 7092 " aaaaaaaaaaa(aaaaaaaaaaa),\n" 7093 " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7094 Style); 7095 7096 FormatStyle OnePerLine = Style; 7097 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 7098 verifyFormat("SomeClass::Constructor() :\n" 7099 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 7100 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 7101 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 7102 OnePerLine); 7103 verifyFormat("SomeClass::Constructor() :\n" 7104 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n" 7105 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 7106 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 7107 OnePerLine); 7108 verifyFormat("Foo::Foo(int i, int j) : // NOLINT\n" 7109 " i(i), // comment\n" 7110 " j(j) {}", 7111 OnePerLine); 7112 verifyFormat("MyClass::MyClass(int var) :\n" 7113 " some_var_(var), // 4 space indent\n" 7114 " some_other_var_(var + 1) { // lined up\n" 7115 "}", 7116 OnePerLine); 7117 verifyFormat("Constructor() :\n" 7118 " aaaaa(aaaaaa),\n" 7119 " aaaaa(aaaaaa),\n" 7120 " aaaaa(aaaaaa),\n" 7121 " aaaaa(aaaaaa),\n" 7122 " aaaaa(aaaaaa) {}", 7123 OnePerLine); 7124 verifyFormat("Constructor() :\n" 7125 " aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n" 7126 " aaaaaaaaaaaaaaaaaaaaaa) {}", 7127 OnePerLine); 7128 OnePerLine.BinPackParameters = false; 7129 verifyFormat("Constructor() :\n" 7130 " aaaaaaaaaaaaaaaaaaaaaaaa(\n" 7131 " aaaaaaaaaaa().aaa(),\n" 7132 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7133 OnePerLine); 7134 OnePerLine.ColumnLimit = 60; 7135 verifyFormat("Constructor() :\n" 7136 " aaaaaaaaaaaaaaaaaaaa(a),\n" 7137 " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}", 7138 OnePerLine); 7139 7140 verifyFormat("Constructor() :\n" 7141 " // Comment forcing unwanted break.\n" 7142 " aaaa(aaaa) {}", 7143 Style); 7144 verifyFormat("Constructor() : // NOLINT\n" 7145 " aaaa(aaaa) {}", 7146 Style); 7147 verifyFormat("Constructor() : // A very long trailing comment that cannot fit" 7148 " on a single\n" 7149 " // line.\n" 7150 " aaaa(aaaa) {}", 7151 "Constructor() : // A very long trailing comment that cannot fit" 7152 " on a single line.\n" 7153 " aaaa(aaaa) {}", 7154 Style); 7155 7156 Style.ColumnLimit = 0; 7157 verifyFormat("SomeClass::Constructor() :\n" 7158 " a(a) {}", 7159 Style); 7160 verifyFormat("SomeClass::Constructor() noexcept :\n" 7161 " a(a) {}", 7162 Style); 7163 verifyFormat("SomeClass::Constructor() :\n" 7164 " a(a), b(b), c(c) {}", 7165 Style); 7166 verifyFormat("SomeClass::Constructor() :\n" 7167 " a(a) {\n" 7168 " foo();\n" 7169 " bar();\n" 7170 "}", 7171 Style); 7172 7173 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 7174 verifyFormat("SomeClass::Constructor() :\n" 7175 " a(a), b(b), c(c) {\n" 7176 "}", 7177 Style); 7178 verifyFormat("SomeClass::Constructor() :\n" 7179 " a(a) {\n" 7180 "}", 7181 Style); 7182 7183 Style.ColumnLimit = 80; 7184 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 7185 Style.ConstructorInitializerIndentWidth = 2; 7186 verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style); 7187 verifyFormat("SomeClass::Constructor() :\n" 7188 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7189 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}", 7190 Style); 7191 7192 // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as 7193 // well 7194 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 7195 verifyFormat( 7196 "class SomeClass\n" 7197 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7198 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7199 Style); 7200 Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma; 7201 verifyFormat( 7202 "class SomeClass\n" 7203 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7204 " , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7205 Style); 7206 Style.BreakInheritanceList = FormatStyle::BILS_AfterColon; 7207 verifyFormat( 7208 "class SomeClass :\n" 7209 " public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7210 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7211 Style); 7212 Style.BreakInheritanceList = FormatStyle::BILS_AfterComma; 7213 verifyFormat( 7214 "class SomeClass\n" 7215 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7216 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7217 Style); 7218 } 7219 7220 #ifndef EXPENSIVE_CHECKS 7221 // Expensive checks enables libstdc++ checking which includes validating the 7222 // state of ranges used in std::priority_queue - this blows out the 7223 // runtime/scalability of the function and makes this test unacceptably slow. 7224 TEST_F(FormatTest, MemoizationTests) { 7225 // This breaks if the memoization lookup does not take \c Indent and 7226 // \c LastSpace into account. 7227 verifyFormat( 7228 "extern CFRunLoopTimerRef\n" 7229 "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n" 7230 " CFTimeInterval interval, CFOptionFlags flags,\n" 7231 " CFIndex order, CFRunLoopTimerCallBack callout,\n" 7232 " CFRunLoopTimerContext *context) {}"); 7233 7234 // Deep nesting somewhat works around our memoization. 7235 verifyFormat( 7236 "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7237 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7238 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7239 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7240 " aaaaa())))))))))))))))))))))))))))))))))))))));", 7241 getLLVMStyleWithColumns(65)); 7242 verifyFormat( 7243 "aaaaa(\n" 7244 " aaaaa,\n" 7245 " aaaaa(\n" 7246 " aaaaa,\n" 7247 " aaaaa(\n" 7248 " aaaaa,\n" 7249 " aaaaa(\n" 7250 " aaaaa,\n" 7251 " aaaaa(\n" 7252 " aaaaa,\n" 7253 " aaaaa(\n" 7254 " aaaaa,\n" 7255 " aaaaa(\n" 7256 " aaaaa,\n" 7257 " aaaaa(\n" 7258 " aaaaa,\n" 7259 " aaaaa(\n" 7260 " aaaaa,\n" 7261 " aaaaa(\n" 7262 " aaaaa,\n" 7263 " aaaaa(\n" 7264 " aaaaa,\n" 7265 " aaaaa(\n" 7266 " aaaaa,\n" 7267 " aaaaa))))))))))));", 7268 getLLVMStyleWithColumns(65)); 7269 verifyFormat( 7270 "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" 7271 " a),\n" 7272 " a),\n" 7273 " a),\n" 7274 " a),\n" 7275 " a),\n" 7276 " a),\n" 7277 " a),\n" 7278 " a),\n" 7279 " a),\n" 7280 " a),\n" 7281 " a),\n" 7282 " a),\n" 7283 " a),\n" 7284 " a),\n" 7285 " a),\n" 7286 " a),\n" 7287 " a)", 7288 getLLVMStyleWithColumns(65)); 7289 7290 // This test takes VERY long when memoization is broken. 7291 FormatStyle OnePerLine = getLLVMStyle(); 7292 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 7293 OnePerLine.BinPackParameters = false; 7294 std::string input = "Constructor()\n" 7295 " : aaaa(a,\n"; 7296 for (unsigned i = 0, e = 80; i != e; ++i) 7297 input += " a,\n"; 7298 input += " a) {}"; 7299 verifyFormat(input, OnePerLine); 7300 } 7301 #endif 7302 7303 TEST_F(FormatTest, BreaksAsHighAsPossible) { 7304 verifyFormat( 7305 "void f() {\n" 7306 " if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n" 7307 " (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n" 7308 " f();\n" 7309 "}"); 7310 verifyFormat("if (Intervals[i].getRange().getFirst() <\n" 7311 " Intervals[i - 1].getRange().getLast()) {\n}"); 7312 } 7313 7314 TEST_F(FormatTest, BreaksFunctionDeclarations) { 7315 // Principially, we break function declarations in a certain order: 7316 // 1) break amongst arguments. 7317 verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n" 7318 " Cccccccccccccc cccccccccccccc);"); 7319 verifyFormat("template <class TemplateIt>\n" 7320 "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n" 7321 " TemplateIt *stop) {}"); 7322 7323 // 2) break after return type. 7324 verifyFormat( 7325 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7326 "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);", 7327 getGoogleStyle()); 7328 7329 // 3) break after (. 7330 verifyFormat( 7331 "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n" 7332 " Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);", 7333 getGoogleStyle()); 7334 7335 // 4) break before after nested name specifiers. 7336 verifyFormat( 7337 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7338 "SomeClasssssssssssssssssssssssssssssssssssssss::\n" 7339 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);", 7340 getGoogleStyle()); 7341 7342 // However, there are exceptions, if a sufficient amount of lines can be 7343 // saved. 7344 // FIXME: The precise cut-offs wrt. the number of saved lines might need some 7345 // more adjusting. 7346 verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n" 7347 " Cccccccccccccc cccccccccc,\n" 7348 " Cccccccccccccc cccccccccc,\n" 7349 " Cccccccccccccc cccccccccc,\n" 7350 " Cccccccccccccc cccccccccc);"); 7351 verifyFormat( 7352 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7353 "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7354 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7355 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);", 7356 getGoogleStyle()); 7357 verifyFormat( 7358 "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n" 7359 " Cccccccccccccc cccccccccc,\n" 7360 " Cccccccccccccc cccccccccc,\n" 7361 " Cccccccccccccc cccccccccc,\n" 7362 " Cccccccccccccc cccccccccc,\n" 7363 " Cccccccccccccc cccccccccc,\n" 7364 " Cccccccccccccc cccccccccc);"); 7365 verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7366 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7367 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7368 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7369 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);"); 7370 7371 // Break after multi-line parameters. 7372 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7373 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7374 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7375 " bbbb bbbb);"); 7376 verifyFormat("void SomeLoooooooooooongFunction(\n" 7377 " std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n" 7378 " aaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7379 " int bbbbbbbbbbbbb);"); 7380 7381 // Treat overloaded operators like other functions. 7382 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 7383 "operator>(const SomeLoooooooooooooooooooooooooogType &other);"); 7384 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 7385 "operator>>(const SomeLooooooooooooooooooooooooogType &other);"); 7386 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 7387 "operator<<(const SomeLooooooooooooooooooooooooogType &other);"); 7388 verifyGoogleFormat( 7389 "SomeLoooooooooooooooooooooooooooooogType operator>>(\n" 7390 " const SomeLooooooooogType &a, const SomeLooooooooogType &b);"); 7391 verifyGoogleFormat( 7392 "SomeLoooooooooooooooooooooooooooooogType operator<<(\n" 7393 " const SomeLooooooooogType &a, const SomeLooooooooogType &b);"); 7394 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7395 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);"); 7396 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n" 7397 "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);"); 7398 verifyGoogleFormat( 7399 "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n" 7400 "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7401 " bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}"); 7402 verifyGoogleFormat("template <typename T>\n" 7403 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7404 "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n" 7405 " aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);"); 7406 7407 FormatStyle Style = getLLVMStyle(); 7408 Style.PointerAlignment = FormatStyle::PAS_Left; 7409 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7410 " aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}", 7411 Style); 7412 verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n" 7413 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7414 Style); 7415 } 7416 7417 TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) { 7418 // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516: 7419 // Prefer keeping `::` followed by `operator` together. 7420 EXPECT_EQ("const aaaa::bbbbbbb &\n" 7421 "ccccccccc::operator++() {\n" 7422 " stuff();\n" 7423 "}", 7424 format("const aaaa::bbbbbbb\n" 7425 "&ccccccccc::operator++() { stuff(); }", 7426 getLLVMStyleWithColumns(40))); 7427 } 7428 7429 TEST_F(FormatTest, TrailingReturnType) { 7430 verifyFormat("auto foo() -> int;\n"); 7431 // correct trailing return type spacing 7432 verifyFormat("auto operator->() -> int;\n"); 7433 verifyFormat("auto operator++(int) -> int;\n"); 7434 7435 verifyFormat("struct S {\n" 7436 " auto bar() const -> int;\n" 7437 "};"); 7438 verifyFormat("template <size_t Order, typename T>\n" 7439 "auto load_img(const std::string &filename)\n" 7440 " -> alias::tensor<Order, T, mem::tag::cpu> {}"); 7441 verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n" 7442 " -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}"); 7443 verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}"); 7444 verifyFormat("template <typename T>\n" 7445 "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n" 7446 " -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());"); 7447 7448 // Not trailing return types. 7449 verifyFormat("void f() { auto a = b->c(); }"); 7450 verifyFormat("auto a = p->foo();"); 7451 verifyFormat("int a = p->foo();"); 7452 verifyFormat("auto lmbd = [] NOEXCEPT -> int { return 0; };"); 7453 } 7454 7455 TEST_F(FormatTest, DeductionGuides) { 7456 verifyFormat("template <class T> A(const T &, const T &) -> A<T &>;"); 7457 verifyFormat("template <class T> explicit A(T &, T &&) -> A<T>;"); 7458 verifyFormat("template <class... Ts> S(Ts...) -> S<Ts...>;"); 7459 verifyFormat( 7460 "template <class... T>\n" 7461 "array(T &&...t) -> array<std::common_type_t<T...>, sizeof...(T)>;"); 7462 verifyFormat("template <class T> A() -> A<decltype(p->foo<3>())>;"); 7463 verifyFormat("template <class T> A() -> A<decltype(foo<traits<1>>)>;"); 7464 verifyFormat("template <class T> A() -> A<sizeof(p->foo<1>)>;"); 7465 verifyFormat("template <class T> A() -> A<(3 < 2)>;"); 7466 verifyFormat("template <class T> A() -> A<((3) < (2))>;"); 7467 verifyFormat("template <class T> x() -> x<1>;"); 7468 verifyFormat("template <class T> explicit x(T &) -> x<1>;"); 7469 7470 // Ensure not deduction guides. 7471 verifyFormat("c()->f<int>();"); 7472 verifyFormat("x()->foo<1>;"); 7473 verifyFormat("x = p->foo<3>();"); 7474 verifyFormat("x()->x<1>();"); 7475 verifyFormat("x()->x<1>;"); 7476 } 7477 7478 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) { 7479 // Avoid breaking before trailing 'const' or other trailing annotations, if 7480 // they are not function-like. 7481 FormatStyle Style = getGoogleStyleWithColumns(47); 7482 verifyFormat("void someLongFunction(\n" 7483 " int someLoooooooooooooongParameter) const {\n}", 7484 getLLVMStyleWithColumns(47)); 7485 verifyFormat("LoooooongReturnType\n" 7486 "someLoooooooongFunction() const {}", 7487 getLLVMStyleWithColumns(47)); 7488 verifyFormat("LoooooongReturnType someLoooooooongFunction()\n" 7489 " const {}", 7490 Style); 7491 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7492 " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;"); 7493 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7494 " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;"); 7495 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7496 " aaaaa aaaaaaaaaaaaaaaaaaaa) override final;"); 7497 verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n" 7498 " aaaaaaaaaaa aaaaa) const override;"); 7499 verifyGoogleFormat( 7500 "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7501 " const override;"); 7502 7503 // Even if the first parameter has to be wrapped. 7504 verifyFormat("void someLongFunction(\n" 7505 " int someLongParameter) const {}", 7506 getLLVMStyleWithColumns(46)); 7507 verifyFormat("void someLongFunction(\n" 7508 " int someLongParameter) const {}", 7509 Style); 7510 verifyFormat("void someLongFunction(\n" 7511 " int someLongParameter) override {}", 7512 Style); 7513 verifyFormat("void someLongFunction(\n" 7514 " int someLongParameter) OVERRIDE {}", 7515 Style); 7516 verifyFormat("void someLongFunction(\n" 7517 " int someLongParameter) final {}", 7518 Style); 7519 verifyFormat("void someLongFunction(\n" 7520 " int someLongParameter) FINAL {}", 7521 Style); 7522 verifyFormat("void someLongFunction(\n" 7523 " int parameter) const override {}", 7524 Style); 7525 7526 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 7527 verifyFormat("void someLongFunction(\n" 7528 " int someLongParameter) const\n" 7529 "{\n" 7530 "}", 7531 Style); 7532 7533 Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 7534 verifyFormat("void someLongFunction(\n" 7535 " int someLongParameter) const\n" 7536 " {\n" 7537 " }", 7538 Style); 7539 7540 // Unless these are unknown annotations. 7541 verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n" 7542 " aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7543 " LONG_AND_UGLY_ANNOTATION;"); 7544 7545 // Breaking before function-like trailing annotations is fine to keep them 7546 // close to their arguments. 7547 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7548 " LOCKS_EXCLUDED(aaaaaaaaaaaaa);"); 7549 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n" 7550 " LOCKS_EXCLUDED(aaaaaaaaaaaaa);"); 7551 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n" 7552 " LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}"); 7553 verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n" 7554 " AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);"); 7555 verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});"); 7556 7557 verifyFormat( 7558 "void aaaaaaaaaaaaaaaaaa()\n" 7559 " __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n" 7560 " aaaaaaaaaaaaaaaaaaaaaaaaa));"); 7561 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7562 " __attribute__((unused));"); 7563 verifyGoogleFormat( 7564 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7565 " GUARDED_BY(aaaaaaaaaaaa);"); 7566 verifyGoogleFormat( 7567 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7568 " GUARDED_BY(aaaaaaaaaaaa);"); 7569 verifyGoogleFormat( 7570 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n" 7571 " aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7572 verifyGoogleFormat( 7573 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n" 7574 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7575 } 7576 7577 TEST_F(FormatTest, FunctionAnnotations) { 7578 verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7579 "int OldFunction(const string ¶meter) {}"); 7580 verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7581 "string OldFunction(const string ¶meter) {}"); 7582 verifyFormat("template <typename T>\n" 7583 "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7584 "string OldFunction(const string ¶meter) {}"); 7585 7586 // Not function annotations. 7587 verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7588 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"); 7589 verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n" 7590 " ThisIsATestWithAReallyReallyReallyReallyLongName) {}"); 7591 verifyFormat("MACRO(abc).function() // wrap\n" 7592 " << abc;"); 7593 verifyFormat("MACRO(abc)->function() // wrap\n" 7594 " << abc;"); 7595 verifyFormat("MACRO(abc)::function() // wrap\n" 7596 " << abc;"); 7597 } 7598 7599 TEST_F(FormatTest, BreaksDesireably) { 7600 verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n" 7601 " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n" 7602 " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}"); 7603 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7604 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 7605 "}"); 7606 7607 verifyFormat( 7608 "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7609 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 7610 7611 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7612 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7613 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7614 7615 verifyFormat( 7616 "aaaaaaaa(aaaaaaaaaaaaa,\n" 7617 " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7618 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n" 7619 " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7620 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));"); 7621 7622 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 7623 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7624 7625 verifyFormat( 7626 "void f() {\n" 7627 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n" 7628 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 7629 "}"); 7630 verifyFormat( 7631 "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7632 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7633 verifyFormat( 7634 "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7635 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7636 verifyFormat( 7637 "aaaaaa(aaa,\n" 7638 " new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7639 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7640 " aaaa);"); 7641 verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7642 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7643 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7644 7645 // Indent consistently independent of call expression and unary operator. 7646 verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7647 " dddddddddddddddddddddddddddddd));"); 7648 verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7649 " dddddddddddddddddddddddddddddd));"); 7650 verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n" 7651 " dddddddddddddddddddddddddddddd));"); 7652 7653 // This test case breaks on an incorrect memoization, i.e. an optimization not 7654 // taking into account the StopAt value. 7655 verifyFormat( 7656 "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7657 " aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7658 " aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7659 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7660 7661 verifyFormat("{\n {\n {\n" 7662 " Annotation.SpaceRequiredBefore =\n" 7663 " Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n" 7664 " Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n" 7665 " }\n }\n}"); 7666 7667 // Break on an outer level if there was a break on an inner level. 7668 EXPECT_EQ("f(g(h(a, // comment\n" 7669 " b, c),\n" 7670 " d, e),\n" 7671 " x, y);", 7672 format("f(g(h(a, // comment\n" 7673 " b, c), d, e), x, y);")); 7674 7675 // Prefer breaking similar line breaks. 7676 verifyFormat( 7677 "const int kTrackingOptions = NSTrackingMouseMoved |\n" 7678 " NSTrackingMouseEnteredAndExited |\n" 7679 " NSTrackingActiveAlways;"); 7680 } 7681 7682 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) { 7683 FormatStyle NoBinPacking = getGoogleStyle(); 7684 NoBinPacking.BinPackParameters = false; 7685 NoBinPacking.BinPackArguments = true; 7686 verifyFormat("void f() {\n" 7687 " f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n" 7688 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 7689 "}", 7690 NoBinPacking); 7691 verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n" 7692 " int aaaaaaaaaaaaaaaaaaaa,\n" 7693 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7694 NoBinPacking); 7695 7696 NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false; 7697 verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7698 " vector<int> bbbbbbbbbbbbbbb);", 7699 NoBinPacking); 7700 // FIXME: This behavior difference is probably not wanted. However, currently 7701 // we cannot distinguish BreakBeforeParameter being set because of the wrapped 7702 // template arguments from BreakBeforeParameter being set because of the 7703 // one-per-line formatting. 7704 verifyFormat( 7705 "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n" 7706 " aaaaaaaaaa> aaaaaaaaaa);", 7707 NoBinPacking); 7708 verifyFormat( 7709 "void fffffffffff(\n" 7710 " aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n" 7711 " aaaaaaaaaa);"); 7712 } 7713 7714 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) { 7715 FormatStyle NoBinPacking = getGoogleStyle(); 7716 NoBinPacking.BinPackParameters = false; 7717 NoBinPacking.BinPackArguments = false; 7718 verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n" 7719 " aaaaaaaaaaaaaaaaaaaa,\n" 7720 " aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);", 7721 NoBinPacking); 7722 verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n" 7723 " aaaaaaaaaaaaa,\n" 7724 " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));", 7725 NoBinPacking); 7726 verifyFormat( 7727 "aaaaaaaa(aaaaaaaaaaaaa,\n" 7728 " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7729 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n" 7730 " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7731 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));", 7732 NoBinPacking); 7733 verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n" 7734 " .aaaaaaaaaaaaaaaaaa();", 7735 NoBinPacking); 7736 verifyFormat("void f() {\n" 7737 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7738 " aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n" 7739 "}", 7740 NoBinPacking); 7741 7742 verifyFormat( 7743 "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7744 " aaaaaaaaaaaa,\n" 7745 " aaaaaaaaaaaa);", 7746 NoBinPacking); 7747 verifyFormat( 7748 "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n" 7749 " ddddddddddddddddddddddddddddd),\n" 7750 " test);", 7751 NoBinPacking); 7752 7753 verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n" 7754 " aaaaaaaaaaaaaaaaaaaaaaa,\n" 7755 " aaaaaaaaaaaaaaaaaaaaaaa>\n" 7756 " aaaaaaaaaaaaaaaaaa;", 7757 NoBinPacking); 7758 verifyFormat("a(\"a\"\n" 7759 " \"a\",\n" 7760 " a);"); 7761 7762 NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false; 7763 verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n" 7764 " aaaaaaaaa,\n" 7765 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7766 NoBinPacking); 7767 verifyFormat( 7768 "void f() {\n" 7769 " aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n" 7770 " .aaaaaaa();\n" 7771 "}", 7772 NoBinPacking); 7773 verifyFormat( 7774 "template <class SomeType, class SomeOtherType>\n" 7775 "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}", 7776 NoBinPacking); 7777 } 7778 7779 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) { 7780 FormatStyle Style = getLLVMStyleWithColumns(15); 7781 Style.ExperimentalAutoDetectBinPacking = true; 7782 EXPECT_EQ("aaa(aaaa,\n" 7783 " aaaa,\n" 7784 " aaaa);\n" 7785 "aaa(aaaa,\n" 7786 " aaaa,\n" 7787 " aaaa);", 7788 format("aaa(aaaa,\n" // one-per-line 7789 " aaaa,\n" 7790 " aaaa );\n" 7791 "aaa(aaaa, aaaa, aaaa);", // inconclusive 7792 Style)); 7793 EXPECT_EQ("aaa(aaaa, aaaa,\n" 7794 " aaaa);\n" 7795 "aaa(aaaa, aaaa,\n" 7796 " aaaa);", 7797 format("aaa(aaaa, aaaa,\n" // bin-packed 7798 " aaaa );\n" 7799 "aaa(aaaa, aaaa, aaaa);", // inconclusive 7800 Style)); 7801 } 7802 7803 TEST_F(FormatTest, FormatsBuilderPattern) { 7804 verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n" 7805 " .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n" 7806 " .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n" 7807 " .StartsWith(\".init\", ORDER_INIT)\n" 7808 " .StartsWith(\".fini\", ORDER_FINI)\n" 7809 " .StartsWith(\".hash\", ORDER_HASH)\n" 7810 " .Default(ORDER_TEXT);\n"); 7811 7812 verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n" 7813 " aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();"); 7814 verifyFormat("aaaaaaa->aaaaaaa\n" 7815 " ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7816 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7817 " ->aaaaaaaa(aaaaaaaaaaaaaaa);"); 7818 verifyFormat( 7819 "aaaaaaa->aaaaaaa\n" 7820 " ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7821 " ->aaaaaaaa(aaaaaaaaaaaaaaa);"); 7822 verifyFormat( 7823 "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n" 7824 " aaaaaaaaaaaaaa);"); 7825 verifyFormat( 7826 "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n" 7827 " aaaaaa->aaaaaaaaaaaa()\n" 7828 " ->aaaaaaaaaaaaaaaa(\n" 7829 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7830 " ->aaaaaaaaaaaaaaaaa();"); 7831 verifyGoogleFormat( 7832 "void f() {\n" 7833 " someo->Add((new util::filetools::Handler(dir))\n" 7834 " ->OnEvent1(NewPermanentCallback(\n" 7835 " this, &HandlerHolderClass::EventHandlerCBA))\n" 7836 " ->OnEvent2(NewPermanentCallback(\n" 7837 " this, &HandlerHolderClass::EventHandlerCBB))\n" 7838 " ->OnEvent3(NewPermanentCallback(\n" 7839 " this, &HandlerHolderClass::EventHandlerCBC))\n" 7840 " ->OnEvent5(NewPermanentCallback(\n" 7841 " this, &HandlerHolderClass::EventHandlerCBD))\n" 7842 " ->OnEvent6(NewPermanentCallback(\n" 7843 " this, &HandlerHolderClass::EventHandlerCBE)));\n" 7844 "}"); 7845 7846 verifyFormat( 7847 "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();"); 7848 verifyFormat("aaaaaaaaaaaaaaa()\n" 7849 " .aaaaaaaaaaaaaaa()\n" 7850 " .aaaaaaaaaaaaaaa()\n" 7851 " .aaaaaaaaaaaaaaa()\n" 7852 " .aaaaaaaaaaaaaaa();"); 7853 verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7854 " .aaaaaaaaaaaaaaa()\n" 7855 " .aaaaaaaaaaaaaaa()\n" 7856 " .aaaaaaaaaaaaaaa();"); 7857 verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7858 " .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7859 " .aaaaaaaaaaaaaaa();"); 7860 verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n" 7861 " ->aaaaaaaaaaaaaae(0)\n" 7862 " ->aaaaaaaaaaaaaaa();"); 7863 7864 // Don't linewrap after very short segments. 7865 verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7866 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7867 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7868 verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7869 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7870 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7871 verifyFormat("aaa()\n" 7872 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7873 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7874 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7875 7876 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n" 7877 " .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7878 " .has<bbbbbbbbbbbbbbbbbbbbb>();"); 7879 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n" 7880 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 7881 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();"); 7882 7883 // Prefer not to break after empty parentheses. 7884 verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n" 7885 " First->LastNewlineOffset);"); 7886 7887 // Prefer not to create "hanging" indents. 7888 verifyFormat( 7889 "return !soooooooooooooome_map\n" 7890 " .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7891 " .second;"); 7892 verifyFormat( 7893 "return aaaaaaaaaaaaaaaa\n" 7894 " .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n" 7895 " .aaaa(aaaaaaaaaaaaaa);"); 7896 // No hanging indent here. 7897 verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n" 7898 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7899 verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n" 7900 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7901 verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n" 7902 " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7903 getLLVMStyleWithColumns(60)); 7904 verifyFormat("aaaaaaaaaaaaaaaaaa\n" 7905 " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n" 7906 " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7907 getLLVMStyleWithColumns(59)); 7908 verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7909 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7910 " .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7911 7912 // Dont break if only closing statements before member call 7913 verifyFormat("test() {\n" 7914 " ([]() -> {\n" 7915 " int b = 32;\n" 7916 " return 3;\n" 7917 " }).foo();\n" 7918 "}"); 7919 verifyFormat("test() {\n" 7920 " (\n" 7921 " []() -> {\n" 7922 " int b = 32;\n" 7923 " return 3;\n" 7924 " },\n" 7925 " foo, bar)\n" 7926 " .foo();\n" 7927 "}"); 7928 verifyFormat("test() {\n" 7929 " ([]() -> {\n" 7930 " int b = 32;\n" 7931 " return 3;\n" 7932 " })\n" 7933 " .foo()\n" 7934 " .bar();\n" 7935 "}"); 7936 verifyFormat("test() {\n" 7937 " ([]() -> {\n" 7938 " int b = 32;\n" 7939 " return 3;\n" 7940 " })\n" 7941 " .foo(\"aaaaaaaaaaaaaaaaa\"\n" 7942 " \"bbbb\");\n" 7943 "}", 7944 getLLVMStyleWithColumns(30)); 7945 } 7946 7947 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) { 7948 verifyFormat( 7949 "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 7950 " bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}"); 7951 verifyFormat( 7952 "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n" 7953 " bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}"); 7954 7955 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" 7956 " ccccccccccccccccccccccccc) {\n}"); 7957 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n" 7958 " ccccccccccccccccccccccccc) {\n}"); 7959 7960 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" 7961 " ccccccccccccccccccccccccc) {\n}"); 7962 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n" 7963 " ccccccccccccccccccccccccc) {\n}"); 7964 7965 verifyFormat( 7966 "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n" 7967 " ccccccccccccccccccccccccc) {\n}"); 7968 verifyFormat( 7969 "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n" 7970 " ccccccccccccccccccccccccc) {\n}"); 7971 7972 verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n" 7973 " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n" 7974 " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n" 7975 " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;"); 7976 verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n" 7977 " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n" 7978 " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n" 7979 " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;"); 7980 7981 verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n" 7982 " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n" 7983 " aaaaaaaaaaaaaaa != aa) {\n}"); 7984 verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n" 7985 " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n" 7986 " aaaaaaaaaaaaaaa != aa) {\n}"); 7987 } 7988 7989 TEST_F(FormatTest, BreaksAfterAssignments) { 7990 verifyFormat( 7991 "unsigned Cost =\n" 7992 " TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n" 7993 " SI->getPointerAddressSpaceee());\n"); 7994 verifyFormat( 7995 "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n" 7996 " Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());"); 7997 7998 verifyFormat( 7999 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n" 8000 " aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);"); 8001 verifyFormat("unsigned OriginalStartColumn =\n" 8002 " SourceMgr.getSpellingColumnNumber(\n" 8003 " Current.FormatTok.getStartOfNonWhitespace()) -\n" 8004 " 1;"); 8005 } 8006 8007 TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) { 8008 FormatStyle Style = getLLVMStyle(); 8009 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 8010 " bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;", 8011 Style); 8012 8013 Style.PenaltyBreakAssignment = 20; 8014 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n" 8015 " cccccccccccccccccccccccccc;", 8016 Style); 8017 } 8018 8019 TEST_F(FormatTest, AlignsAfterAssignments) { 8020 verifyFormat( 8021 "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 8022 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 8023 verifyFormat( 8024 "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 8025 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 8026 verifyFormat( 8027 "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 8028 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 8029 verifyFormat( 8030 "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 8031 " aaaaaaaaaaaaaaaaaaaaaaaaa);"); 8032 verifyFormat( 8033 "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n" 8034 " aaaaaaaaaaaaaaaaaaaaaaaa +\n" 8035 " aaaaaaaaaaaaaaaaaaaaaaaa;"); 8036 } 8037 8038 TEST_F(FormatTest, AlignsAfterReturn) { 8039 verifyFormat( 8040 "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 8041 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 8042 verifyFormat( 8043 "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 8044 " aaaaaaaaaaaaaaaaaaaaaaaaa);"); 8045 verifyFormat( 8046 "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n" 8047 " aaaaaaaaaaaaaaaaaaaaaa();"); 8048 verifyFormat( 8049 "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n" 8050 " aaaaaaaaaaaaaaaaaaaaaa());"); 8051 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8052 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8053 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8054 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n" 8055 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8056 verifyFormat("return\n" 8057 " // true if code is one of a or b.\n" 8058 " code == a || code == b;"); 8059 } 8060 8061 TEST_F(FormatTest, AlignsAfterOpenBracket) { 8062 verifyFormat( 8063 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n" 8064 " aaaaaaaaa aaaaaaa) {}"); 8065 verifyFormat( 8066 "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n" 8067 " aaaaaaaaaaa aaaaaaaaa);"); 8068 verifyFormat( 8069 "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n" 8070 " aaaaaaaaaaaaaaaaaaaaa));"); 8071 FormatStyle Style = getLLVMStyle(); 8072 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 8073 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8074 " aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}", 8075 Style); 8076 verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n" 8077 " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);", 8078 Style); 8079 verifyFormat("SomeLongVariableName->someFunction(\n" 8080 " foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));", 8081 Style); 8082 verifyFormat( 8083 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n" 8084 " aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 8085 Style); 8086 verifyFormat( 8087 "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n" 8088 " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8089 Style); 8090 verifyFormat( 8091 "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n" 8092 " aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));", 8093 Style); 8094 8095 verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n" 8096 " ccccccc(aaaaaaaaaaaaaaaaa, //\n" 8097 " b));", 8098 Style); 8099 8100 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 8101 Style.BinPackArguments = false; 8102 Style.BinPackParameters = false; 8103 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8104 " aaaaaaaaaaa aaaaaaaa,\n" 8105 " aaaaaaaaa aaaaaaa,\n" 8106 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 8107 Style); 8108 verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n" 8109 " aaaaaaaaaaa aaaaaaaaa,\n" 8110 " aaaaaaaaaaa aaaaaaaaa,\n" 8111 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8112 Style); 8113 verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n" 8114 " aaaaaaaaaaaaaaa,\n" 8115 " aaaaaaaaaaaaaaaaaaaaa,\n" 8116 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));", 8117 Style); 8118 verifyFormat( 8119 "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n" 8120 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));", 8121 Style); 8122 verifyFormat( 8123 "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n" 8124 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));", 8125 Style); 8126 verifyFormat( 8127 "aaaaaaaaaaaaaaaaaaaaaaaa(\n" 8128 " aaaaaaaaaaaaaaaaaaaaa(\n" 8129 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n" 8130 " aaaaaaaaaaaaaaaa);", 8131 Style); 8132 verifyFormat( 8133 "aaaaaaaaaaaaaaaaaaaaaaaa(\n" 8134 " aaaaaaaaaaaaaaaaaaaaa(\n" 8135 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n" 8136 " aaaaaaaaaaaaaaaa);", 8137 Style); 8138 } 8139 8140 TEST_F(FormatTest, ParenthesesAndOperandAlignment) { 8141 FormatStyle Style = getLLVMStyleWithColumns(40); 8142 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 8143 " bbbbbbbbbbbbbbbbbbbbbb);", 8144 Style); 8145 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 8146 Style.AlignOperands = FormatStyle::OAS_DontAlign; 8147 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 8148 " bbbbbbbbbbbbbbbbbbbbbb);", 8149 Style); 8150 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 8151 Style.AlignOperands = FormatStyle::OAS_Align; 8152 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 8153 " bbbbbbbbbbbbbbbbbbbbbb);", 8154 Style); 8155 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 8156 Style.AlignOperands = FormatStyle::OAS_DontAlign; 8157 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 8158 " bbbbbbbbbbbbbbbbbbbbbb);", 8159 Style); 8160 } 8161 8162 TEST_F(FormatTest, BreaksConditionalExpressions) { 8163 verifyFormat( 8164 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8165 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8166 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8167 verifyFormat( 8168 "aaaa(aaaaaaaaaa, aaaaaaaa,\n" 8169 " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8170 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8171 verifyFormat( 8172 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8173 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8174 verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n" 8175 " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8176 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8177 verifyFormat( 8178 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n" 8179 " : aaaaaaaaaaaaa);"); 8180 verifyFormat( 8181 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8182 " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8183 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8184 " aaaaaaaaaaaaa);"); 8185 verifyFormat( 8186 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8187 " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8188 " aaaaaaaaaaaaa);"); 8189 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8190 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8191 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8192 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8193 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8194 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8195 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8196 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8197 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8198 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8199 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8200 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8201 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8202 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8203 " ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8204 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8205 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8206 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8207 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8208 " : aaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8209 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n" 8210 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8211 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8212 " : aaaaaaaaaaaaaaaa;"); 8213 verifyFormat( 8214 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8215 " ? aaaaaaaaaaaaaaa\n" 8216 " : aaaaaaaaaaaaaaa;"); 8217 verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n" 8218 " aaaaaaaaa\n" 8219 " ? b\n" 8220 " : c);"); 8221 verifyFormat("return aaaa == bbbb\n" 8222 " // comment\n" 8223 " ? aaaa\n" 8224 " : bbbb;"); 8225 verifyFormat("unsigned Indent =\n" 8226 " format(TheLine.First,\n" 8227 " IndentForLevel[TheLine.Level] >= 0\n" 8228 " ? IndentForLevel[TheLine.Level]\n" 8229 " : TheLine * 2,\n" 8230 " TheLine.InPPDirective, PreviousEndOfLineColumn);", 8231 getLLVMStyleWithColumns(60)); 8232 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n" 8233 " ? aaaaaaaaaaaaaaa\n" 8234 " : bbbbbbbbbbbbbbb //\n" 8235 " ? ccccccccccccccc\n" 8236 " : ddddddddddddddd;"); 8237 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n" 8238 " ? aaaaaaaaaaaaaaa\n" 8239 " : (bbbbbbbbbbbbbbb //\n" 8240 " ? ccccccccccccccc\n" 8241 " : ddddddddddddddd);"); 8242 verifyFormat( 8243 "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8244 " ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 8245 " aaaaaaaaaaaaaaaaaaaaa +\n" 8246 " aaaaaaaaaaaaaaaaaaaaa\n" 8247 " : aaaaaaaaaa;"); 8248 verifyFormat( 8249 "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8250 " : aaaaaaaaaaaaaaaaaaaaaa\n" 8251 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8252 8253 FormatStyle NoBinPacking = getLLVMStyle(); 8254 NoBinPacking.BinPackArguments = false; 8255 verifyFormat( 8256 "void f() {\n" 8257 " g(aaa,\n" 8258 " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n" 8259 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8260 " ? aaaaaaaaaaaaaaa\n" 8261 " : aaaaaaaaaaaaaaa);\n" 8262 "}", 8263 NoBinPacking); 8264 verifyFormat( 8265 "void f() {\n" 8266 " g(aaa,\n" 8267 " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n" 8268 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8269 " ?: aaaaaaaaaaaaaaa);\n" 8270 "}", 8271 NoBinPacking); 8272 8273 verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n" 8274 " // comment.\n" 8275 " ccccccccccccccccccccccccccccccccccccccc\n" 8276 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8277 " : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);"); 8278 8279 // Assignments in conditional expressions. Apparently not uncommon :-(. 8280 verifyFormat("return a != b\n" 8281 " // comment\n" 8282 " ? a = b\n" 8283 " : a = b;"); 8284 verifyFormat("return a != b\n" 8285 " // comment\n" 8286 " ? a = a != b\n" 8287 " // comment\n" 8288 " ? a = b\n" 8289 " : a\n" 8290 " : a;\n"); 8291 verifyFormat("return a != b\n" 8292 " // comment\n" 8293 " ? a\n" 8294 " : a = a != b\n" 8295 " // comment\n" 8296 " ? a = b\n" 8297 " : a;"); 8298 8299 // Chained conditionals 8300 FormatStyle Style = getLLVMStyleWithColumns(70); 8301 Style.AlignOperands = FormatStyle::OAS_Align; 8302 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8303 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8304 " : 3333333333333333;", 8305 Style); 8306 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8307 " : bbbbbbbbbb ? 2222222222222222\n" 8308 " : 3333333333333333;", 8309 Style); 8310 verifyFormat("return aaaaaaaaaa ? 1111111111111111\n" 8311 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 8312 " : 3333333333333333;", 8313 Style); 8314 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8315 " : bbbbbbbbbbbbbb ? 222222\n" 8316 " : 333333;", 8317 Style); 8318 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8319 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8320 " : cccccccccccccc ? 3333333333333333\n" 8321 " : 4444444444444444;", 8322 Style); 8323 verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc)\n" 8324 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8325 " : 3333333333333333;", 8326 Style); 8327 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8328 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8329 " : (aaa ? bbb : ccc);", 8330 Style); 8331 verifyFormat( 8332 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8333 " : cccccccccccccccccc)\n" 8334 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8335 " : 3333333333333333;", 8336 Style); 8337 verifyFormat( 8338 "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8339 " : cccccccccccccccccc)\n" 8340 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8341 " : 3333333333333333;", 8342 Style); 8343 verifyFormat( 8344 "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8345 " : dddddddddddddddddd)\n" 8346 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8347 " : 3333333333333333;", 8348 Style); 8349 verifyFormat( 8350 "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8351 " : dddddddddddddddddd)\n" 8352 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8353 " : 3333333333333333;", 8354 Style); 8355 verifyFormat( 8356 "return aaaaaaaaa ? 1111111111111111\n" 8357 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8358 " : a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8359 " : dddddddddddddddddd)\n", 8360 Style); 8361 verifyFormat( 8362 "return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8363 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8364 " : (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8365 " : cccccccccccccccccc);", 8366 Style); 8367 verifyFormat( 8368 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8369 " : ccccccccccccccc ? dddddddddddddddddd\n" 8370 " : eeeeeeeeeeeeeeeeee)\n" 8371 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8372 " : 3333333333333333;", 8373 Style); 8374 verifyFormat( 8375 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8376 " : ccccccccccccccc ? dddddddddddddddddd\n" 8377 " : eeeeeeeeeeeeeeeeee)\n" 8378 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8379 " : 3333333333333333;", 8380 Style); 8381 verifyFormat( 8382 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8383 " : cccccccccccc ? dddddddddddddddddd\n" 8384 " : eeeeeeeeeeeeeeeeee)\n" 8385 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8386 " : 3333333333333333;", 8387 Style); 8388 verifyFormat( 8389 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8390 " : cccccccccccccccccc\n" 8391 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8392 " : 3333333333333333;", 8393 Style); 8394 verifyFormat( 8395 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8396 " : cccccccccccccccc ? dddddddddddddddddd\n" 8397 " : eeeeeeeeeeeeeeeeee\n" 8398 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8399 " : 3333333333333333;", 8400 Style); 8401 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa\n" 8402 " ? (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8403 " : cccccccccccccccccc ? dddddddddddddddddd\n" 8404 " : eeeeeeeeeeeeeeeeee)\n" 8405 " : bbbbbbbbbbbbbbbbbbb ? 2222222222222222\n" 8406 " : 3333333333333333;", 8407 Style); 8408 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaa\n" 8409 " ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8410 " : cccccccccccccccc ? dddddddddddddddddd\n" 8411 " : eeeeeeeeeeeeeeeeee\n" 8412 " : bbbbbbbbbbbbbbbbbbbbbbb ? 2222222222222222\n" 8413 " : 3333333333333333;", 8414 Style); 8415 8416 Style.AlignOperands = FormatStyle::OAS_DontAlign; 8417 Style.BreakBeforeTernaryOperators = false; 8418 // FIXME: Aligning the question marks is weird given DontAlign. 8419 // Consider disabling this alignment in this case. Also check whether this 8420 // will render the adjustment from https://reviews.llvm.org/D82199 8421 // unnecessary. 8422 verifyFormat("int x = aaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa :\n" 8423 " bbbb ? cccccccccccccccccc :\n" 8424 " ddddd;\n", 8425 Style); 8426 8427 EXPECT_EQ( 8428 "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n" 8429 " /*\n" 8430 " */\n" 8431 " function() {\n" 8432 " try {\n" 8433 " return JJJJJJJJJJJJJJ(\n" 8434 " pppppppppppppppppppppppppppppppppppppppppppppppppp);\n" 8435 " }\n" 8436 " } :\n" 8437 " function() {};", 8438 format( 8439 "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n" 8440 " /*\n" 8441 " */\n" 8442 " function() {\n" 8443 " try {\n" 8444 " return JJJJJJJJJJJJJJ(\n" 8445 " pppppppppppppppppppppppppppppppppppppppppppppppppp);\n" 8446 " }\n" 8447 " } :\n" 8448 " function() {};", 8449 getGoogleStyle(FormatStyle::LK_JavaScript))); 8450 } 8451 8452 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) { 8453 FormatStyle Style = getLLVMStyleWithColumns(70); 8454 Style.BreakBeforeTernaryOperators = false; 8455 verifyFormat( 8456 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8457 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8458 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8459 Style); 8460 verifyFormat( 8461 "aaaa(aaaaaaaaaa, aaaaaaaa,\n" 8462 " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8463 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8464 Style); 8465 verifyFormat( 8466 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8467 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8468 Style); 8469 verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n" 8470 " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8471 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8472 Style); 8473 verifyFormat( 8474 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n" 8475 " aaaaaaaaaaaaa);", 8476 Style); 8477 verifyFormat( 8478 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8479 " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8480 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8481 " aaaaaaaaaaaaa);", 8482 Style); 8483 verifyFormat( 8484 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8485 " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8486 " aaaaaaaaaaaaa);", 8487 Style); 8488 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8489 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8490 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 8491 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8492 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8493 Style); 8494 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8495 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8496 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8497 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 8498 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8499 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8500 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8501 Style); 8502 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8503 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n" 8504 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8505 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8506 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8507 Style); 8508 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8509 " aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8510 " aaaaaaaaaaaaaaaaaaaaaaaaaaa;", 8511 Style); 8512 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n" 8513 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8514 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8515 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 8516 Style); 8517 verifyFormat( 8518 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8519 " aaaaaaaaaaaaaaa :\n" 8520 " aaaaaaaaaaaaaaa;", 8521 Style); 8522 verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n" 8523 " aaaaaaaaa ?\n" 8524 " b :\n" 8525 " c);", 8526 Style); 8527 verifyFormat("unsigned Indent =\n" 8528 " format(TheLine.First,\n" 8529 " IndentForLevel[TheLine.Level] >= 0 ?\n" 8530 " IndentForLevel[TheLine.Level] :\n" 8531 " TheLine * 2,\n" 8532 " TheLine.InPPDirective, PreviousEndOfLineColumn);", 8533 Style); 8534 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n" 8535 " aaaaaaaaaaaaaaa :\n" 8536 " bbbbbbbbbbbbbbb ? //\n" 8537 " ccccccccccccccc :\n" 8538 " ddddddddddddddd;", 8539 Style); 8540 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n" 8541 " aaaaaaaaaaaaaaa :\n" 8542 " (bbbbbbbbbbbbbbb ? //\n" 8543 " ccccccccccccccc :\n" 8544 " ddddddddddddddd);", 8545 Style); 8546 verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8547 " /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n" 8548 " ccccccccccccccccccccccccccc;", 8549 Style); 8550 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8551 " aaaaa :\n" 8552 " bbbbbbbbbbbbbbb + cccccccccccccccc;", 8553 Style); 8554 8555 // Chained conditionals 8556 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8557 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8558 " 3333333333333333;", 8559 Style); 8560 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8561 " bbbbbbbbbb ? 2222222222222222 :\n" 8562 " 3333333333333333;", 8563 Style); 8564 verifyFormat("return aaaaaaaaaa ? 1111111111111111 :\n" 8565 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8566 " 3333333333333333;", 8567 Style); 8568 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8569 " bbbbbbbbbbbbbbbb ? 222222 :\n" 8570 " 333333;", 8571 Style); 8572 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8573 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8574 " cccccccccccccccc ? 3333333333333333 :\n" 8575 " 4444444444444444;", 8576 Style); 8577 verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc) :\n" 8578 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8579 " 3333333333333333;", 8580 Style); 8581 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8582 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8583 " (aaa ? bbb : ccc);", 8584 Style); 8585 verifyFormat( 8586 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8587 " cccccccccccccccccc) :\n" 8588 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8589 " 3333333333333333;", 8590 Style); 8591 verifyFormat( 8592 "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8593 " cccccccccccccccccc) :\n" 8594 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8595 " 3333333333333333;", 8596 Style); 8597 verifyFormat( 8598 "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8599 " dddddddddddddddddd) :\n" 8600 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8601 " 3333333333333333;", 8602 Style); 8603 verifyFormat( 8604 "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8605 " dddddddddddddddddd) :\n" 8606 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8607 " 3333333333333333;", 8608 Style); 8609 verifyFormat( 8610 "return aaaaaaaaa ? 1111111111111111 :\n" 8611 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8612 " a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8613 " dddddddddddddddddd)\n", 8614 Style); 8615 verifyFormat( 8616 "return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8617 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8618 " (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8619 " cccccccccccccccccc);", 8620 Style); 8621 verifyFormat( 8622 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8623 " ccccccccccccccccc ? dddddddddddddddddd :\n" 8624 " eeeeeeeeeeeeeeeeee) :\n" 8625 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8626 " 3333333333333333;", 8627 Style); 8628 verifyFormat( 8629 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8630 " ccccccccccccc ? dddddddddddddddddd :\n" 8631 " eeeeeeeeeeeeeeeeee) :\n" 8632 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8633 " 3333333333333333;", 8634 Style); 8635 verifyFormat( 8636 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8637 " ccccccccccccccccc ? dddddddddddddddddd :\n" 8638 " eeeeeeeeeeeeeeeeee) :\n" 8639 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8640 " 3333333333333333;", 8641 Style); 8642 verifyFormat( 8643 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8644 " cccccccccccccccccc :\n" 8645 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8646 " 3333333333333333;", 8647 Style); 8648 verifyFormat( 8649 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8650 " cccccccccccccccccc ? dddddddddddddddddd :\n" 8651 " eeeeeeeeeeeeeeeeee :\n" 8652 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8653 " 3333333333333333;", 8654 Style); 8655 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n" 8656 " (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8657 " cccccccccccccccccc ? dddddddddddddddddd :\n" 8658 " eeeeeeeeeeeeeeeeee) :\n" 8659 " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8660 " 3333333333333333;", 8661 Style); 8662 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n" 8663 " aaaaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8664 " cccccccccccccccccccc ? dddddddddddddddddd :\n" 8665 " eeeeeeeeeeeeeeeeee :\n" 8666 " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8667 " 3333333333333333;", 8668 Style); 8669 } 8670 8671 TEST_F(FormatTest, DeclarationsOfMultipleVariables) { 8672 verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n" 8673 " aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();"); 8674 verifyFormat("bool a = true, b = false;"); 8675 8676 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n" 8677 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n" 8678 " bbbbbbbbbbbbbbbbbbbbbbbbb =\n" 8679 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);"); 8680 verifyFormat( 8681 "bool aaaaaaaaaaaaaaaaaaaaa =\n" 8682 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n" 8683 " d = e && f;"); 8684 verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n" 8685 " c = cccccccccccccccccccc, d = dddddddddddddddddddd;"); 8686 verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n" 8687 " *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;"); 8688 verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n" 8689 " ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;"); 8690 8691 FormatStyle Style = getGoogleStyle(); 8692 Style.PointerAlignment = FormatStyle::PAS_Left; 8693 Style.DerivePointerAlignment = false; 8694 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8695 " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n" 8696 " *b = bbbbbbbbbbbbbbbbbbb;", 8697 Style); 8698 verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n" 8699 " *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;", 8700 Style); 8701 verifyFormat("vector<int*> a, b;", Style); 8702 verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style); 8703 verifyFormat("/*comment*/ for (int *p, *q; p != q; p = p->next) {\n}", Style); 8704 verifyFormat("if (int *p, *q; p != q) {\n p = p->next;\n}", Style); 8705 verifyFormat("/*comment*/ if (int *p, *q; p != q) {\n p = p->next;\n}", 8706 Style); 8707 verifyFormat("switch (int *p, *q; p != q) {\n default:\n break;\n}", 8708 Style); 8709 verifyFormat( 8710 "/*comment*/ switch (int *p, *q; p != q) {\n default:\n break;\n}", 8711 Style); 8712 8713 verifyFormat("if ([](int* p, int* q) {}()) {\n}", Style); 8714 verifyFormat("for ([](int* p, int* q) {}();;) {\n}", Style); 8715 verifyFormat("for (; [](int* p, int* q) {}();) {\n}", Style); 8716 verifyFormat("for (;; [](int* p, int* q) {}()) {\n}", Style); 8717 verifyFormat("switch ([](int* p, int* q) {}()) {\n default:\n break;\n}", 8718 Style); 8719 } 8720 8721 TEST_F(FormatTest, ConditionalExpressionsInBrackets) { 8722 verifyFormat("arr[foo ? bar : baz];"); 8723 verifyFormat("f()[foo ? bar : baz];"); 8724 verifyFormat("(a + b)[foo ? bar : baz];"); 8725 verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];"); 8726 } 8727 8728 TEST_F(FormatTest, AlignsStringLiterals) { 8729 verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n" 8730 " \"short literal\");"); 8731 verifyFormat( 8732 "looooooooooooooooooooooooongFunction(\n" 8733 " \"short literal\"\n" 8734 " \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");"); 8735 verifyFormat("someFunction(\"Always break between multi-line\"\n" 8736 " \" string literals\",\n" 8737 " and, other, parameters);"); 8738 EXPECT_EQ("fun + \"1243\" /* comment */\n" 8739 " \"5678\";", 8740 format("fun + \"1243\" /* comment */\n" 8741 " \"5678\";", 8742 getLLVMStyleWithColumns(28))); 8743 EXPECT_EQ( 8744 "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 8745 " \"aaaaaaaaaaaaaaaaaaaaa\"\n" 8746 " \"aaaaaaaaaaaaaaaa\";", 8747 format("aaaaaa =" 8748 "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa " 8749 "aaaaaaaaaaaaaaaaaaaaa\" " 8750 "\"aaaaaaaaaaaaaaaa\";")); 8751 verifyFormat("a = a + \"a\"\n" 8752 " \"a\"\n" 8753 " \"a\";"); 8754 verifyFormat("f(\"a\", \"b\"\n" 8755 " \"c\");"); 8756 8757 verifyFormat( 8758 "#define LL_FORMAT \"ll\"\n" 8759 "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n" 8760 " \"d, ddddddddd: %\" LL_FORMAT \"d\");"); 8761 8762 verifyFormat("#define A(X) \\\n" 8763 " \"aaaaa\" #X \"bbbbbb\" \\\n" 8764 " \"ccccc\"", 8765 getLLVMStyleWithColumns(23)); 8766 verifyFormat("#define A \"def\"\n" 8767 "f(\"abc\" A \"ghi\"\n" 8768 " \"jkl\");"); 8769 8770 verifyFormat("f(L\"a\"\n" 8771 " L\"b\");"); 8772 verifyFormat("#define A(X) \\\n" 8773 " L\"aaaaa\" #X L\"bbbbbb\" \\\n" 8774 " L\"ccccc\"", 8775 getLLVMStyleWithColumns(25)); 8776 8777 verifyFormat("f(@\"a\"\n" 8778 " @\"b\");"); 8779 verifyFormat("NSString s = @\"a\"\n" 8780 " @\"b\"\n" 8781 " @\"c\";"); 8782 verifyFormat("NSString s = @\"a\"\n" 8783 " \"b\"\n" 8784 " \"c\";"); 8785 } 8786 8787 TEST_F(FormatTest, ReturnTypeBreakingStyle) { 8788 FormatStyle Style = getLLVMStyle(); 8789 // No declarations or definitions should be moved to own line. 8790 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None; 8791 verifyFormat("class A {\n" 8792 " int f() { return 1; }\n" 8793 " int g();\n" 8794 "};\n" 8795 "int f() { return 1; }\n" 8796 "int g();\n", 8797 Style); 8798 8799 // All declarations and definitions should have the return type moved to its 8800 // own line. 8801 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 8802 Style.TypenameMacros = {"LIST"}; 8803 verifyFormat("SomeType\n" 8804 "funcdecl(LIST(uint64_t));", 8805 Style); 8806 verifyFormat("class E {\n" 8807 " int\n" 8808 " f() {\n" 8809 " return 1;\n" 8810 " }\n" 8811 " int\n" 8812 " g();\n" 8813 "};\n" 8814 "int\n" 8815 "f() {\n" 8816 " return 1;\n" 8817 "}\n" 8818 "int\n" 8819 "g();\n", 8820 Style); 8821 8822 // Top-level definitions, and no kinds of declarations should have the 8823 // return type moved to its own line. 8824 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions; 8825 verifyFormat("class B {\n" 8826 " int f() { return 1; }\n" 8827 " int g();\n" 8828 "};\n" 8829 "int\n" 8830 "f() {\n" 8831 " return 1;\n" 8832 "}\n" 8833 "int g();\n", 8834 Style); 8835 8836 // Top-level definitions and declarations should have the return type moved 8837 // to its own line. 8838 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel; 8839 verifyFormat("class C {\n" 8840 " int f() { return 1; }\n" 8841 " int g();\n" 8842 "};\n" 8843 "int\n" 8844 "f() {\n" 8845 " return 1;\n" 8846 "}\n" 8847 "int\n" 8848 "g();\n", 8849 Style); 8850 8851 // All definitions should have the return type moved to its own line, but no 8852 // kinds of declarations. 8853 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions; 8854 verifyFormat("class D {\n" 8855 " int\n" 8856 " f() {\n" 8857 " return 1;\n" 8858 " }\n" 8859 " int g();\n" 8860 "};\n" 8861 "int\n" 8862 "f() {\n" 8863 " return 1;\n" 8864 "}\n" 8865 "int g();\n", 8866 Style); 8867 verifyFormat("const char *\n" 8868 "f(void) {\n" // Break here. 8869 " return \"\";\n" 8870 "}\n" 8871 "const char *bar(void);\n", // No break here. 8872 Style); 8873 verifyFormat("template <class T>\n" 8874 "T *\n" 8875 "f(T &c) {\n" // Break here. 8876 " return NULL;\n" 8877 "}\n" 8878 "template <class T> T *f(T &c);\n", // No break here. 8879 Style); 8880 verifyFormat("class C {\n" 8881 " int\n" 8882 " operator+() {\n" 8883 " return 1;\n" 8884 " }\n" 8885 " int\n" 8886 " operator()() {\n" 8887 " return 1;\n" 8888 " }\n" 8889 "};\n", 8890 Style); 8891 verifyFormat("void\n" 8892 "A::operator()() {}\n" 8893 "void\n" 8894 "A::operator>>() {}\n" 8895 "void\n" 8896 "A::operator+() {}\n" 8897 "void\n" 8898 "A::operator*() {}\n" 8899 "void\n" 8900 "A::operator->() {}\n" 8901 "void\n" 8902 "A::operator void *() {}\n" 8903 "void\n" 8904 "A::operator void &() {}\n" 8905 "void\n" 8906 "A::operator void &&() {}\n" 8907 "void\n" 8908 "A::operator char *() {}\n" 8909 "void\n" 8910 "A::operator[]() {}\n" 8911 "void\n" 8912 "A::operator!() {}\n" 8913 "void\n" 8914 "A::operator**() {}\n" 8915 "void\n" 8916 "A::operator<Foo> *() {}\n" 8917 "void\n" 8918 "A::operator<Foo> **() {}\n" 8919 "void\n" 8920 "A::operator<Foo> &() {}\n" 8921 "void\n" 8922 "A::operator void **() {}\n", 8923 Style); 8924 verifyFormat("constexpr auto\n" 8925 "operator()() const -> reference {}\n" 8926 "constexpr auto\n" 8927 "operator>>() const -> reference {}\n" 8928 "constexpr auto\n" 8929 "operator+() const -> reference {}\n" 8930 "constexpr auto\n" 8931 "operator*() const -> reference {}\n" 8932 "constexpr auto\n" 8933 "operator->() const -> reference {}\n" 8934 "constexpr auto\n" 8935 "operator++() const -> reference {}\n" 8936 "constexpr auto\n" 8937 "operator void *() const -> reference {}\n" 8938 "constexpr auto\n" 8939 "operator void **() const -> reference {}\n" 8940 "constexpr auto\n" 8941 "operator void *() const -> reference {}\n" 8942 "constexpr auto\n" 8943 "operator void &() const -> reference {}\n" 8944 "constexpr auto\n" 8945 "operator void &&() const -> reference {}\n" 8946 "constexpr auto\n" 8947 "operator char *() const -> reference {}\n" 8948 "constexpr auto\n" 8949 "operator!() const -> reference {}\n" 8950 "constexpr auto\n" 8951 "operator[]() const -> reference {}\n", 8952 Style); 8953 verifyFormat("void *operator new(std::size_t s);", // No break here. 8954 Style); 8955 verifyFormat("void *\n" 8956 "operator new(std::size_t s) {}", 8957 Style); 8958 verifyFormat("void *\n" 8959 "operator delete[](void *ptr) {}", 8960 Style); 8961 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 8962 verifyFormat("const char *\n" 8963 "f(void)\n" // Break here. 8964 "{\n" 8965 " return \"\";\n" 8966 "}\n" 8967 "const char *bar(void);\n", // No break here. 8968 Style); 8969 verifyFormat("template <class T>\n" 8970 "T *\n" // Problem here: no line break 8971 "f(T &c)\n" // Break here. 8972 "{\n" 8973 " return NULL;\n" 8974 "}\n" 8975 "template <class T> T *f(T &c);\n", // No break here. 8976 Style); 8977 verifyFormat("int\n" 8978 "foo(A<bool> a)\n" 8979 "{\n" 8980 " return a;\n" 8981 "}\n", 8982 Style); 8983 verifyFormat("int\n" 8984 "foo(A<8> a)\n" 8985 "{\n" 8986 " return a;\n" 8987 "}\n", 8988 Style); 8989 verifyFormat("int\n" 8990 "foo(A<B<bool>, 8> a)\n" 8991 "{\n" 8992 " return a;\n" 8993 "}\n", 8994 Style); 8995 verifyFormat("int\n" 8996 "foo(A<B<8>, bool> a)\n" 8997 "{\n" 8998 " return a;\n" 8999 "}\n", 9000 Style); 9001 verifyFormat("int\n" 9002 "foo(A<B<bool>, bool> a)\n" 9003 "{\n" 9004 " return a;\n" 9005 "}\n", 9006 Style); 9007 verifyFormat("int\n" 9008 "foo(A<B<8>, 8> a)\n" 9009 "{\n" 9010 " return a;\n" 9011 "}\n", 9012 Style); 9013 9014 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 9015 Style.BraceWrapping.AfterFunction = true; 9016 verifyFormat("int f(i);\n" // No break here. 9017 "int\n" // Break here. 9018 "f(i)\n" 9019 "{\n" 9020 " return i + 1;\n" 9021 "}\n" 9022 "int\n" // Break here. 9023 "f(i)\n" 9024 "{\n" 9025 " return i + 1;\n" 9026 "};", 9027 Style); 9028 verifyFormat("int f(a, b, c);\n" // No break here. 9029 "int\n" // Break here. 9030 "f(a, b, c)\n" // Break here. 9031 "short a, b;\n" 9032 "float c;\n" 9033 "{\n" 9034 " return a + b < c;\n" 9035 "}\n" 9036 "int\n" // Break here. 9037 "f(a, b, c)\n" // Break here. 9038 "short a, b;\n" 9039 "float c;\n" 9040 "{\n" 9041 " return a + b < c;\n" 9042 "};", 9043 Style); 9044 verifyFormat("byte *\n" // Break here. 9045 "f(a)\n" // Break here. 9046 "byte a[];\n" 9047 "{\n" 9048 " return a;\n" 9049 "}", 9050 Style); 9051 verifyFormat("bool f(int a, int) override;\n" 9052 "Bar g(int a, Bar) final;\n" 9053 "Bar h(a, Bar) final;", 9054 Style); 9055 verifyFormat("int\n" 9056 "f(a)", 9057 Style); 9058 verifyFormat("bool\n" 9059 "f(size_t = 0, bool b = false)\n" 9060 "{\n" 9061 " return !b;\n" 9062 "}", 9063 Style); 9064 9065 // The return breaking style doesn't affect: 9066 // * function and object definitions with attribute-like macros 9067 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 9068 " ABSL_GUARDED_BY(mutex) = {};", 9069 getGoogleStyleWithColumns(40)); 9070 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 9071 " ABSL_GUARDED_BY(mutex); // comment", 9072 getGoogleStyleWithColumns(40)); 9073 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 9074 " ABSL_GUARDED_BY(mutex1)\n" 9075 " ABSL_GUARDED_BY(mutex2);", 9076 getGoogleStyleWithColumns(40)); 9077 verifyFormat("Tttttt f(int a, int b)\n" 9078 " ABSL_GUARDED_BY(mutex1)\n" 9079 " ABSL_GUARDED_BY(mutex2);", 9080 getGoogleStyleWithColumns(40)); 9081 // * typedefs 9082 verifyFormat("typedef ATTR(X) char x;", getGoogleStyle()); 9083 9084 Style = getGNUStyle(); 9085 9086 // Test for comments at the end of function declarations. 9087 verifyFormat("void\n" 9088 "foo (int a, /*abc*/ int b) // def\n" 9089 "{\n" 9090 "}\n", 9091 Style); 9092 9093 verifyFormat("void\n" 9094 "foo (int a, /* abc */ int b) /* def */\n" 9095 "{\n" 9096 "}\n", 9097 Style); 9098 9099 // Definitions that should not break after return type 9100 verifyFormat("void foo (int a, int b); // def\n", Style); 9101 verifyFormat("void foo (int a, int b); /* def */\n", Style); 9102 verifyFormat("void foo (int a, int b);\n", Style); 9103 } 9104 9105 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) { 9106 FormatStyle NoBreak = getLLVMStyle(); 9107 NoBreak.AlwaysBreakBeforeMultilineStrings = false; 9108 FormatStyle Break = getLLVMStyle(); 9109 Break.AlwaysBreakBeforeMultilineStrings = true; 9110 verifyFormat("aaaa = \"bbbb\"\n" 9111 " \"cccc\";", 9112 NoBreak); 9113 verifyFormat("aaaa =\n" 9114 " \"bbbb\"\n" 9115 " \"cccc\";", 9116 Break); 9117 verifyFormat("aaaa(\"bbbb\"\n" 9118 " \"cccc\");", 9119 NoBreak); 9120 verifyFormat("aaaa(\n" 9121 " \"bbbb\"\n" 9122 " \"cccc\");", 9123 Break); 9124 verifyFormat("aaaa(qqq, \"bbbb\"\n" 9125 " \"cccc\");", 9126 NoBreak); 9127 verifyFormat("aaaa(qqq,\n" 9128 " \"bbbb\"\n" 9129 " \"cccc\");", 9130 Break); 9131 verifyFormat("aaaa(qqq,\n" 9132 " L\"bbbb\"\n" 9133 " L\"cccc\");", 9134 Break); 9135 verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n" 9136 " \"bbbb\"));", 9137 Break); 9138 verifyFormat("string s = someFunction(\n" 9139 " \"abc\"\n" 9140 " \"abc\");", 9141 Break); 9142 9143 // As we break before unary operators, breaking right after them is bad. 9144 verifyFormat("string foo = abc ? \"x\"\n" 9145 " \"blah blah blah blah blah blah\"\n" 9146 " : \"y\";", 9147 Break); 9148 9149 // Don't break if there is no column gain. 9150 verifyFormat("f(\"aaaa\"\n" 9151 " \"bbbb\");", 9152 Break); 9153 9154 // Treat literals with escaped newlines like multi-line string literals. 9155 EXPECT_EQ("x = \"a\\\n" 9156 "b\\\n" 9157 "c\";", 9158 format("x = \"a\\\n" 9159 "b\\\n" 9160 "c\";", 9161 NoBreak)); 9162 EXPECT_EQ("xxxx =\n" 9163 " \"a\\\n" 9164 "b\\\n" 9165 "c\";", 9166 format("xxxx = \"a\\\n" 9167 "b\\\n" 9168 "c\";", 9169 Break)); 9170 9171 EXPECT_EQ("NSString *const kString =\n" 9172 " @\"aaaa\"\n" 9173 " @\"bbbb\";", 9174 format("NSString *const kString = @\"aaaa\"\n" 9175 "@\"bbbb\";", 9176 Break)); 9177 9178 Break.ColumnLimit = 0; 9179 verifyFormat("const char *hello = \"hello llvm\";", Break); 9180 } 9181 9182 TEST_F(FormatTest, AlignsPipes) { 9183 verifyFormat( 9184 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9185 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9186 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9187 verifyFormat( 9188 "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n" 9189 " << aaaaaaaaaaaaaaaaaaaa;"); 9190 verifyFormat( 9191 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9192 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9193 verifyFormat( 9194 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 9195 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9196 verifyFormat( 9197 "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n" 9198 " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n" 9199 " << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";"); 9200 verifyFormat( 9201 "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9202 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9203 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9204 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9205 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9206 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9207 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 9208 verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n" 9209 " << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);"); 9210 verifyFormat( 9211 "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9212 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9213 verifyFormat( 9214 "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n" 9215 " aaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9216 9217 verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n" 9218 " << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();"); 9219 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9220 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9221 " aaaaaaaaaaaaaaaaaaaaa)\n" 9222 " << aaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9223 verifyFormat("LOG_IF(aaa == //\n" 9224 " bbb)\n" 9225 " << a << b;"); 9226 9227 // But sometimes, breaking before the first "<<" is desirable. 9228 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 9229 " << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);"); 9230 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n" 9231 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9232 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9233 verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n" 9234 " << BEF << IsTemplate << Description << E->getType();"); 9235 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 9236 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9237 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9238 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 9239 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9240 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9241 " << aaa;"); 9242 9243 verifyFormat( 9244 "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9245 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9246 9247 // Incomplete string literal. 9248 EXPECT_EQ("llvm::errs() << \"\n" 9249 " << a;", 9250 format("llvm::errs() << \"\n<<a;")); 9251 9252 verifyFormat("void f() {\n" 9253 " CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n" 9254 " << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n" 9255 "}"); 9256 9257 // Handle 'endl'. 9258 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n" 9259 " << bbbbbbbbbbbbbbbbbbbbbb << endl;"); 9260 verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;"); 9261 9262 // Handle '\n'. 9263 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n" 9264 " << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";"); 9265 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n" 9266 " << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';"); 9267 verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n" 9268 " << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";"); 9269 verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";"); 9270 } 9271 9272 TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) { 9273 verifyFormat("return out << \"somepacket = {\\n\"\n" 9274 " << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n" 9275 " << \" bbbb = \" << pkt.bbbb << \"\\n\"\n" 9276 " << \" cccccc = \" << pkt.cccccc << \"\\n\"\n" 9277 " << \" ddd = [\" << pkt.ddd << \"]\\n\"\n" 9278 " << \"}\";"); 9279 9280 verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n" 9281 " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n" 9282 " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;"); 9283 verifyFormat( 9284 "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n" 9285 " << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n" 9286 " << \"ccccccccccccccccc = \" << ccccccccccccccccc\n" 9287 " << \"ddddddddddddddddd = \" << ddddddddddddddddd\n" 9288 " << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;"); 9289 verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n" 9290 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 9291 verifyFormat( 9292 "void f() {\n" 9293 " llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n" 9294 " << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 9295 "}"); 9296 9297 // Breaking before the first "<<" is generally not desirable. 9298 verifyFormat( 9299 "llvm::errs()\n" 9300 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9301 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9302 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9303 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 9304 getLLVMStyleWithColumns(70)); 9305 verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n" 9306 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9307 " << \"aaaaaaaaaaaaaaaaaaa: \"\n" 9308 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9309 " << \"aaaaaaaaaaaaaaaaaaa: \"\n" 9310 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 9311 getLLVMStyleWithColumns(70)); 9312 9313 verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n" 9314 " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n" 9315 " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;"); 9316 verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n" 9317 " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n" 9318 " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);"); 9319 verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n" 9320 " (aaaa + aaaa);", 9321 getLLVMStyleWithColumns(40)); 9322 verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n" 9323 " (aaaaaaa + aaaaa));", 9324 getLLVMStyleWithColumns(40)); 9325 verifyFormat( 9326 "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n" 9327 " SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n" 9328 " bbbbbbbbbbbbbbbbbbbbbbb);"); 9329 } 9330 9331 TEST_F(FormatTest, UnderstandsEquals) { 9332 verifyFormat( 9333 "aaaaaaaaaaaaaaaaa =\n" 9334 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9335 verifyFormat( 9336 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9337 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 9338 verifyFormat( 9339 "if (a) {\n" 9340 " f();\n" 9341 "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9342 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 9343 "}"); 9344 9345 verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9346 " 100000000 + 10000000) {\n}"); 9347 } 9348 9349 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) { 9350 verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n" 9351 " .looooooooooooooooooooooooooooooooooooooongFunction();"); 9352 9353 verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n" 9354 " ->looooooooooooooooooooooooooooooooooooooongFunction();"); 9355 9356 verifyFormat( 9357 "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n" 9358 " Parameter2);"); 9359 9360 verifyFormat( 9361 "ShortObject->shortFunction(\n" 9362 " LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n" 9363 " LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);"); 9364 9365 verifyFormat("loooooooooooooongFunction(\n" 9366 " LoooooooooooooongObject->looooooooooooooooongFunction());"); 9367 9368 verifyFormat( 9369 "function(LoooooooooooooooooooooooooooooooooooongObject\n" 9370 " ->loooooooooooooooooooooooooooooooooooooooongFunction());"); 9371 9372 verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n" 9373 " .WillRepeatedly(Return(SomeValue));"); 9374 verifyFormat("void f() {\n" 9375 " EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n" 9376 " .Times(2)\n" 9377 " .WillRepeatedly(Return(SomeValue));\n" 9378 "}"); 9379 verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n" 9380 " ccccccccccccccccccccccc);"); 9381 verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9382 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9383 " .aaaaa(aaaaa),\n" 9384 " aaaaaaaaaaaaaaaaaaaaa);"); 9385 verifyFormat("void f() {\n" 9386 " aaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9387 " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n" 9388 "}"); 9389 verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9390 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9391 " .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9392 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9393 " aaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 9394 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9395 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9396 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9397 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n" 9398 "}"); 9399 9400 // Here, it is not necessary to wrap at "." or "->". 9401 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n" 9402 " aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 9403 verifyFormat( 9404 "aaaaaaaaaaa->aaaaaaaaa(\n" 9405 " aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9406 " aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n"); 9407 9408 verifyFormat( 9409 "aaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9410 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());"); 9411 verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n" 9412 " aaaaaaaaa()->aaaaaa()->aaaaa());"); 9413 verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n" 9414 " aaaaaaaaa()->aaaaaa()->aaaaa());"); 9415 9416 verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9417 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9418 " .a();"); 9419 9420 FormatStyle NoBinPacking = getLLVMStyle(); 9421 NoBinPacking.BinPackParameters = false; 9422 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n" 9423 " .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n" 9424 " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n" 9425 " aaaaaaaaaaaaaaaaaaa,\n" 9426 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 9427 NoBinPacking); 9428 9429 // If there is a subsequent call, change to hanging indentation. 9430 verifyFormat( 9431 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9432 " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n" 9433 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9434 verifyFormat( 9435 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9436 " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));"); 9437 verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9438 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9439 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9440 verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9441 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9442 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());"); 9443 } 9444 9445 TEST_F(FormatTest, WrapsTemplateDeclarations) { 9446 verifyFormat("template <typename T>\n" 9447 "virtual void loooooooooooongFunction(int Param1, int Param2);"); 9448 verifyFormat("template <typename T>\n" 9449 "// T should be one of {A, B}.\n" 9450 "virtual void loooooooooooongFunction(int Param1, int Param2);"); 9451 verifyFormat( 9452 "template <typename T>\n" 9453 "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;"); 9454 verifyFormat("template <typename T>\n" 9455 "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n" 9456 " int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);"); 9457 verifyFormat( 9458 "template <typename T>\n" 9459 "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n" 9460 " int Paaaaaaaaaaaaaaaaaaaaram2);"); 9461 verifyFormat( 9462 "template <typename T>\n" 9463 "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n" 9464 " aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n" 9465 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9466 verifyFormat("template <typename T>\n" 9467 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9468 " int aaaaaaaaaaaaaaaaaaaaaa);"); 9469 verifyFormat( 9470 "template <typename T1, typename T2 = char, typename T3 = char,\n" 9471 " typename T4 = char>\n" 9472 "void f();"); 9473 verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n" 9474 " template <typename> class cccccccccccccccccccccc,\n" 9475 " typename ddddddddddddd>\n" 9476 "class C {};"); 9477 verifyFormat( 9478 "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n" 9479 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9480 9481 verifyFormat("void f() {\n" 9482 " a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n" 9483 " a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n" 9484 "}"); 9485 9486 verifyFormat("template <typename T> class C {};"); 9487 verifyFormat("template <typename T> void f();"); 9488 verifyFormat("template <typename T> void f() {}"); 9489 verifyFormat( 9490 "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n" 9491 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9492 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n" 9493 " new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n" 9494 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9495 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n" 9496 " bbbbbbbbbbbbbbbbbbbbbbbb);", 9497 getLLVMStyleWithColumns(72)); 9498 EXPECT_EQ("static_cast<A< //\n" 9499 " B> *>(\n" 9500 "\n" 9501 ");", 9502 format("static_cast<A<//\n" 9503 " B>*>(\n" 9504 "\n" 9505 " );")); 9506 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9507 " const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);"); 9508 9509 FormatStyle AlwaysBreak = getLLVMStyle(); 9510 AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 9511 verifyFormat("template <typename T>\nclass C {};", AlwaysBreak); 9512 verifyFormat("template <typename T>\nvoid f();", AlwaysBreak); 9513 verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak); 9514 verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9515 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n" 9516 " ccccccccccccccccccccccccccccccccccccccccccccccc);"); 9517 verifyFormat("template <template <typename> class Fooooooo,\n" 9518 " template <typename> class Baaaaaaar>\n" 9519 "struct C {};", 9520 AlwaysBreak); 9521 verifyFormat("template <typename T> // T can be A, B or C.\n" 9522 "struct C {};", 9523 AlwaysBreak); 9524 verifyFormat("template <enum E> class A {\n" 9525 "public:\n" 9526 " E *f();\n" 9527 "};"); 9528 9529 FormatStyle NeverBreak = getLLVMStyle(); 9530 NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No; 9531 verifyFormat("template <typename T> class C {};", NeverBreak); 9532 verifyFormat("template <typename T> void f();", NeverBreak); 9533 verifyFormat("template <typename T> void f() {}", NeverBreak); 9534 verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa " 9535 "bbbbbbbbbbbbbbbbbbbb) {}", 9536 NeverBreak); 9537 verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9538 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n" 9539 " ccccccccccccccccccccccccccccccccccccccccccccccc);", 9540 NeverBreak); 9541 verifyFormat("template <template <typename> class Fooooooo,\n" 9542 " template <typename> class Baaaaaaar>\n" 9543 "struct C {};", 9544 NeverBreak); 9545 verifyFormat("template <typename T> // T can be A, B or C.\n" 9546 "struct C {};", 9547 NeverBreak); 9548 verifyFormat("template <enum E> class A {\n" 9549 "public:\n" 9550 " E *f();\n" 9551 "};", 9552 NeverBreak); 9553 NeverBreak.PenaltyBreakTemplateDeclaration = 100; 9554 verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa " 9555 "bbbbbbbbbbbbbbbbbbbb) {}", 9556 NeverBreak); 9557 } 9558 9559 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) { 9560 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp); 9561 Style.ColumnLimit = 60; 9562 EXPECT_EQ("// Baseline - no comments.\n" 9563 "template <\n" 9564 " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n" 9565 "void f() {}", 9566 format("// Baseline - no comments.\n" 9567 "template <\n" 9568 " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n" 9569 "void f() {}", 9570 Style)); 9571 9572 EXPECT_EQ("template <\n" 9573 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9574 "void f() {}", 9575 format("template <\n" 9576 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9577 "void f() {}", 9578 Style)); 9579 9580 EXPECT_EQ( 9581 "template <\n" 9582 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n" 9583 "void f() {}", 9584 format("template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n" 9585 "void f() {}", 9586 Style)); 9587 9588 EXPECT_EQ( 9589 "template <\n" 9590 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9591 " // multiline\n" 9592 "void f() {}", 9593 format("template <\n" 9594 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9595 " // multiline\n" 9596 "void f() {}", 9597 Style)); 9598 9599 EXPECT_EQ( 9600 "template <typename aaaaaaaaaa<\n" 9601 " bbbbbbbbbbbb>::value> // trailing loooong\n" 9602 "void f() {}", 9603 format( 9604 "template <\n" 9605 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n" 9606 "void f() {}", 9607 Style)); 9608 } 9609 9610 TEST_F(FormatTest, WrapsTemplateParameters) { 9611 FormatStyle Style = getLLVMStyle(); 9612 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 9613 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 9614 verifyFormat( 9615 "template <typename... a> struct q {};\n" 9616 "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n" 9617 " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n" 9618 " y;", 9619 Style); 9620 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 9621 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 9622 verifyFormat( 9623 "template <typename... a> struct r {};\n" 9624 "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n" 9625 " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n" 9626 " y;", 9627 Style); 9628 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 9629 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 9630 verifyFormat("template <typename... a> struct s {};\n" 9631 "extern s<\n" 9632 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9633 "aaaaaaaaaaaaaaaaaaaaaa,\n" 9634 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9635 "aaaaaaaaaaaaaaaaaaaaaa>\n" 9636 " y;", 9637 Style); 9638 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 9639 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 9640 verifyFormat("template <typename... a> struct t {};\n" 9641 "extern t<\n" 9642 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9643 "aaaaaaaaaaaaaaaaaaaaaa,\n" 9644 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9645 "aaaaaaaaaaaaaaaaaaaaaa>\n" 9646 " y;", 9647 Style); 9648 } 9649 9650 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) { 9651 verifyFormat( 9652 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9653 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9654 verifyFormat( 9655 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9656 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9657 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());"); 9658 9659 // FIXME: Should we have the extra indent after the second break? 9660 verifyFormat( 9661 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9662 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9663 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9664 9665 verifyFormat( 9666 "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n" 9667 " cccccccccccccccccccccccccccccccccccccccccccccc());"); 9668 9669 // Breaking at nested name specifiers is generally not desirable. 9670 verifyFormat( 9671 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9672 " aaaaaaaaaaaaaaaaaaaaaaa);"); 9673 9674 verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n" 9675 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9676 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9677 " aaaaaaaaaaaaaaaaaaaaa);", 9678 getLLVMStyleWithColumns(74)); 9679 9680 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9681 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9682 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9683 } 9684 9685 TEST_F(FormatTest, UnderstandsTemplateParameters) { 9686 verifyFormat("A<int> a;"); 9687 verifyFormat("A<A<A<int>>> a;"); 9688 verifyFormat("A<A<A<int, 2>, 3>, 4> a;"); 9689 verifyFormat("bool x = a < 1 || 2 > a;"); 9690 verifyFormat("bool x = 5 < f<int>();"); 9691 verifyFormat("bool x = f<int>() > 5;"); 9692 verifyFormat("bool x = 5 < a<int>::x;"); 9693 verifyFormat("bool x = a < 4 ? a > 2 : false;"); 9694 verifyFormat("bool x = f() ? a < 2 : a > 2;"); 9695 9696 verifyGoogleFormat("A<A<int>> a;"); 9697 verifyGoogleFormat("A<A<A<int>>> a;"); 9698 verifyGoogleFormat("A<A<A<A<int>>>> a;"); 9699 verifyGoogleFormat("A<A<int> > a;"); 9700 verifyGoogleFormat("A<A<A<int> > > a;"); 9701 verifyGoogleFormat("A<A<A<A<int> > > > a;"); 9702 verifyGoogleFormat("A<::A<int>> a;"); 9703 verifyGoogleFormat("A<::A> a;"); 9704 verifyGoogleFormat("A< ::A> a;"); 9705 verifyGoogleFormat("A< ::A<int> > a;"); 9706 EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle())); 9707 EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle())); 9708 EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle())); 9709 EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle())); 9710 EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };", 9711 format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle())); 9712 9713 verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp)); 9714 9715 // template closer followed by a token that starts with > or = 9716 verifyFormat("bool b = a<1> > 1;"); 9717 verifyFormat("bool b = a<1> >= 1;"); 9718 verifyFormat("int i = a<1> >> 1;"); 9719 FormatStyle Style = getLLVMStyle(); 9720 Style.SpaceBeforeAssignmentOperators = false; 9721 verifyFormat("bool b= a<1> == 1;", Style); 9722 verifyFormat("a<int> = 1;", Style); 9723 verifyFormat("a<int> >>= 1;", Style); 9724 9725 verifyFormat("test < a | b >> c;"); 9726 verifyFormat("test<test<a | b>> c;"); 9727 verifyFormat("test >> a >> b;"); 9728 verifyFormat("test << a >> b;"); 9729 9730 verifyFormat("f<int>();"); 9731 verifyFormat("template <typename T> void f() {}"); 9732 verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;"); 9733 verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : " 9734 "sizeof(char)>::type>;"); 9735 verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};"); 9736 verifyFormat("f(a.operator()<A>());"); 9737 verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9738 " .template operator()<A>());", 9739 getLLVMStyleWithColumns(35)); 9740 verifyFormat("bool_constant<a && noexcept(f())>"); 9741 verifyFormat("bool_constant<a || noexcept(f())>"); 9742 9743 // Not template parameters. 9744 verifyFormat("return a < b && c > d;"); 9745 verifyFormat("void f() {\n" 9746 " while (a < b && c > d) {\n" 9747 " }\n" 9748 "}"); 9749 verifyFormat("template <typename... Types>\n" 9750 "typename enable_if<0 < sizeof...(Types)>::type Foo() {}"); 9751 9752 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9753 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);", 9754 getLLVMStyleWithColumns(60)); 9755 verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");"); 9756 verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}"); 9757 verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <"); 9758 verifyFormat("some_templated_type<decltype([](int i) { return i; })>"); 9759 } 9760 9761 TEST_F(FormatTest, UnderstandsShiftOperators) { 9762 verifyFormat("if (i < x >> 1)"); 9763 verifyFormat("while (i < x >> 1)"); 9764 verifyFormat("for (unsigned i = 0; i < i; ++i, v = v >> 1)"); 9765 verifyFormat("for (unsigned i = 0; i < x >> 1; ++i, v = v >> 1)"); 9766 verifyFormat( 9767 "for (std::vector<int>::iterator i = 0; i < x >> 1; ++i, v = v >> 1)"); 9768 verifyFormat("Foo.call<Bar<Function>>()"); 9769 verifyFormat("if (Foo.call<Bar<Function>>() == 0)"); 9770 verifyFormat("for (std::vector<std::pair<int>>::iterator i = 0; i < x >> 1; " 9771 "++i, v = v >> 1)"); 9772 verifyFormat("if (w<u<v<x>>, 1>::t)"); 9773 } 9774 9775 TEST_F(FormatTest, BitshiftOperatorWidth) { 9776 EXPECT_EQ("int a = 1 << 2; /* foo\n" 9777 " bar */", 9778 format("int a=1<<2; /* foo\n" 9779 " bar */")); 9780 9781 EXPECT_EQ("int b = 256 >> 1; /* foo\n" 9782 " bar */", 9783 format("int b =256>>1 ; /* foo\n" 9784 " bar */")); 9785 } 9786 9787 TEST_F(FormatTest, UnderstandsBinaryOperators) { 9788 verifyFormat("COMPARE(a, ==, b);"); 9789 verifyFormat("auto s = sizeof...(Ts) - 1;"); 9790 } 9791 9792 TEST_F(FormatTest, UnderstandsPointersToMembers) { 9793 verifyFormat("int A::*x;"); 9794 verifyFormat("int (S::*func)(void *);"); 9795 verifyFormat("void f() { int (S::*func)(void *); }"); 9796 verifyFormat("typedef bool *(Class::*Member)() const;"); 9797 verifyFormat("void f() {\n" 9798 " (a->*f)();\n" 9799 " a->*x;\n" 9800 " (a.*f)();\n" 9801 " ((*a).*f)();\n" 9802 " a.*x;\n" 9803 "}"); 9804 verifyFormat("void f() {\n" 9805 " (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n" 9806 " aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n" 9807 "}"); 9808 verifyFormat( 9809 "(aaaaaaaaaa->*bbbbbbb)(\n" 9810 " aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 9811 FormatStyle Style = getLLVMStyle(); 9812 Style.PointerAlignment = FormatStyle::PAS_Left; 9813 verifyFormat("typedef bool* (Class::*Member)() const;", Style); 9814 } 9815 9816 TEST_F(FormatTest, UnderstandsUnaryOperators) { 9817 verifyFormat("int a = -2;"); 9818 verifyFormat("f(-1, -2, -3);"); 9819 verifyFormat("a[-1] = 5;"); 9820 verifyFormat("int a = 5 + -2;"); 9821 verifyFormat("if (i == -1) {\n}"); 9822 verifyFormat("if (i != -1) {\n}"); 9823 verifyFormat("if (i > -1) {\n}"); 9824 verifyFormat("if (i < -1) {\n}"); 9825 verifyFormat("++(a->f());"); 9826 verifyFormat("--(a->f());"); 9827 verifyFormat("(a->f())++;"); 9828 verifyFormat("a[42]++;"); 9829 verifyFormat("if (!(a->f())) {\n}"); 9830 verifyFormat("if (!+i) {\n}"); 9831 verifyFormat("~&a;"); 9832 verifyFormat("for (x = 0; -10 < x; --x) {\n}"); 9833 verifyFormat("sizeof -x"); 9834 verifyFormat("sizeof +x"); 9835 verifyFormat("sizeof *x"); 9836 verifyFormat("sizeof &x"); 9837 verifyFormat("delete +x;"); 9838 verifyFormat("co_await +x;"); 9839 verifyFormat("case *x:"); 9840 verifyFormat("case &x:"); 9841 9842 verifyFormat("a-- > b;"); 9843 verifyFormat("b ? -a : c;"); 9844 verifyFormat("n * sizeof char16;"); 9845 verifyFormat("n * alignof char16;", getGoogleStyle()); 9846 verifyFormat("sizeof(char);"); 9847 verifyFormat("alignof(char);", getGoogleStyle()); 9848 9849 verifyFormat("return -1;"); 9850 verifyFormat("throw -1;"); 9851 verifyFormat("switch (a) {\n" 9852 "case -1:\n" 9853 " break;\n" 9854 "}"); 9855 verifyFormat("#define X -1"); 9856 verifyFormat("#define X -kConstant"); 9857 9858 verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};"); 9859 verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};"); 9860 9861 verifyFormat("int a = /* confusing comment */ -1;"); 9862 // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case. 9863 verifyFormat("int a = i /* confusing comment */++;"); 9864 9865 verifyFormat("co_yield -1;"); 9866 verifyFormat("co_return -1;"); 9867 9868 // Check that * is not treated as a binary operator when we set 9869 // PointerAlignment as PAS_Left after a keyword and not a declaration. 9870 FormatStyle PASLeftStyle = getLLVMStyle(); 9871 PASLeftStyle.PointerAlignment = FormatStyle::PAS_Left; 9872 verifyFormat("co_return *a;", PASLeftStyle); 9873 verifyFormat("co_await *a;", PASLeftStyle); 9874 verifyFormat("co_yield *a", PASLeftStyle); 9875 verifyFormat("return *a;", PASLeftStyle); 9876 } 9877 9878 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) { 9879 verifyFormat("if (!aaaaaaaaaa( // break\n" 9880 " aaaaa)) {\n" 9881 "}"); 9882 verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n" 9883 " aaaaa));"); 9884 verifyFormat("*aaa = aaaaaaa( // break\n" 9885 " bbbbbb);"); 9886 } 9887 9888 TEST_F(FormatTest, UnderstandsOverloadedOperators) { 9889 verifyFormat("bool operator<();"); 9890 verifyFormat("bool operator>();"); 9891 verifyFormat("bool operator=();"); 9892 verifyFormat("bool operator==();"); 9893 verifyFormat("bool operator!=();"); 9894 verifyFormat("int operator+();"); 9895 verifyFormat("int operator++();"); 9896 verifyFormat("int operator++(int) volatile noexcept;"); 9897 verifyFormat("bool operator,();"); 9898 verifyFormat("bool operator();"); 9899 verifyFormat("bool operator()();"); 9900 verifyFormat("bool operator[]();"); 9901 verifyFormat("operator bool();"); 9902 verifyFormat("operator int();"); 9903 verifyFormat("operator void *();"); 9904 verifyFormat("operator SomeType<int>();"); 9905 verifyFormat("operator SomeType<int, int>();"); 9906 verifyFormat("operator SomeType<SomeType<int>>();"); 9907 verifyFormat("operator< <>();"); 9908 verifyFormat("operator<< <>();"); 9909 verifyFormat("< <>"); 9910 9911 verifyFormat("void *operator new(std::size_t size);"); 9912 verifyFormat("void *operator new[](std::size_t size);"); 9913 verifyFormat("void operator delete(void *ptr);"); 9914 verifyFormat("void operator delete[](void *ptr);"); 9915 verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n" 9916 "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);"); 9917 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n" 9918 " aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;"); 9919 9920 verifyFormat( 9921 "ostream &operator<<(ostream &OutputStream,\n" 9922 " SomeReallyLongType WithSomeReallyLongValue);"); 9923 verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n" 9924 " const aaaaaaaaaaaaaaaaaaaaa &right) {\n" 9925 " return left.group < right.group;\n" 9926 "}"); 9927 verifyFormat("SomeType &operator=(const SomeType &S);"); 9928 verifyFormat("f.template operator()<int>();"); 9929 9930 verifyGoogleFormat("operator void*();"); 9931 verifyGoogleFormat("operator SomeType<SomeType<int>>();"); 9932 verifyGoogleFormat("operator ::A();"); 9933 9934 verifyFormat("using A::operator+;"); 9935 verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n" 9936 "int i;"); 9937 9938 // Calling an operator as a member function. 9939 verifyFormat("void f() { a.operator*(); }"); 9940 verifyFormat("void f() { a.operator*(b & b); }"); 9941 verifyFormat("void f() { a->operator&(a * b); }"); 9942 verifyFormat("void f() { NS::a.operator+(*b * *b); }"); 9943 // TODO: Calling an operator as a non-member function is hard to distinguish. 9944 // https://llvm.org/PR50629 9945 // verifyFormat("void f() { operator*(a & a); }"); 9946 // verifyFormat("void f() { operator&(a, b * b); }"); 9947 9948 verifyFormat("::operator delete(foo);"); 9949 verifyFormat("::operator new(n * sizeof(foo));"); 9950 verifyFormat("foo() { ::operator delete(foo); }"); 9951 verifyFormat("foo() { ::operator new(n * sizeof(foo)); }"); 9952 } 9953 9954 TEST_F(FormatTest, UnderstandsFunctionRefQualification) { 9955 verifyFormat("void A::b() && {}"); 9956 verifyFormat("void A::b() &&noexcept {}"); 9957 verifyFormat("Deleted &operator=(const Deleted &) & = default;"); 9958 verifyFormat("Deleted &operator=(const Deleted &) && = delete;"); 9959 verifyFormat("Deleted &operator=(const Deleted &) &noexcept = default;"); 9960 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;"); 9961 verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;"); 9962 verifyFormat("Deleted &operator=(const Deleted &) &;"); 9963 verifyFormat("Deleted &operator=(const Deleted &) &&;"); 9964 verifyFormat("SomeType MemberFunction(const Deleted &) &;"); 9965 verifyFormat("SomeType MemberFunction(const Deleted &) &&;"); 9966 verifyFormat("SomeType MemberFunction(const Deleted &) && {}"); 9967 verifyFormat("SomeType MemberFunction(const Deleted &) && final {}"); 9968 verifyFormat("SomeType MemberFunction(const Deleted &) && override {}"); 9969 verifyFormat("SomeType MemberFunction(const Deleted &) &&noexcept {}"); 9970 verifyFormat("void Fn(T const &) const &;"); 9971 verifyFormat("void Fn(T const volatile &&) const volatile &&;"); 9972 verifyFormat("void Fn(T const volatile &&) const volatile &&noexcept;"); 9973 verifyFormat("template <typename T>\n" 9974 "void F(T) && = delete;", 9975 getGoogleStyle()); 9976 verifyFormat("template <typename T> void operator=(T) &;"); 9977 verifyFormat("template <typename T> void operator=(T) const &;"); 9978 verifyFormat("template <typename T> void operator=(T) &noexcept;"); 9979 verifyFormat("template <typename T> void operator=(T) & = default;"); 9980 verifyFormat("template <typename T> void operator=(T) &&;"); 9981 verifyFormat("template <typename T> void operator=(T) && = delete;"); 9982 verifyFormat("template <typename T> void operator=(T) & {}"); 9983 verifyFormat("template <typename T> void operator=(T) && {}"); 9984 9985 FormatStyle AlignLeft = getLLVMStyle(); 9986 AlignLeft.PointerAlignment = FormatStyle::PAS_Left; 9987 verifyFormat("void A::b() && {}", AlignLeft); 9988 verifyFormat("void A::b() && noexcept {}", AlignLeft); 9989 verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft); 9990 verifyFormat("Deleted& operator=(const Deleted&) & noexcept = default;", 9991 AlignLeft); 9992 verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;", 9993 AlignLeft); 9994 verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft); 9995 verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft); 9996 verifyFormat("auto Function(T t) & -> void {}", AlignLeft); 9997 verifyFormat("auto Function(T... t) & -> void {}", AlignLeft); 9998 verifyFormat("auto Function(T) & -> void {}", AlignLeft); 9999 verifyFormat("auto Function(T) & -> void;", AlignLeft); 10000 verifyFormat("void Fn(T const&) const&;", AlignLeft); 10001 verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft); 10002 verifyFormat("void Fn(T const volatile&&) const volatile&& noexcept;", 10003 AlignLeft); 10004 verifyFormat("template <typename T> void operator=(T) &;", AlignLeft); 10005 verifyFormat("template <typename T> void operator=(T) const&;", AlignLeft); 10006 verifyFormat("template <typename T> void operator=(T) & noexcept;", 10007 AlignLeft); 10008 verifyFormat("template <typename T> void operator=(T) & = default;", 10009 AlignLeft); 10010 verifyFormat("template <typename T> void operator=(T) &&;", AlignLeft); 10011 verifyFormat("template <typename T> void operator=(T) && = delete;", 10012 AlignLeft); 10013 verifyFormat("template <typename T> void operator=(T) & {}", AlignLeft); 10014 verifyFormat("template <typename T> void operator=(T) && {}", AlignLeft); 10015 10016 FormatStyle AlignMiddle = getLLVMStyle(); 10017 AlignMiddle.PointerAlignment = FormatStyle::PAS_Middle; 10018 verifyFormat("void A::b() && {}", AlignMiddle); 10019 verifyFormat("void A::b() && noexcept {}", AlignMiddle); 10020 verifyFormat("Deleted & operator=(const Deleted &) & = default;", 10021 AlignMiddle); 10022 verifyFormat("Deleted & operator=(const Deleted &) & noexcept = default;", 10023 AlignMiddle); 10024 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", 10025 AlignMiddle); 10026 verifyFormat("Deleted & operator=(const Deleted &) &;", AlignMiddle); 10027 verifyFormat("SomeType MemberFunction(const Deleted &) &;", AlignMiddle); 10028 verifyFormat("auto Function(T t) & -> void {}", AlignMiddle); 10029 verifyFormat("auto Function(T... t) & -> void {}", AlignMiddle); 10030 verifyFormat("auto Function(T) & -> void {}", AlignMiddle); 10031 verifyFormat("auto Function(T) & -> void;", AlignMiddle); 10032 verifyFormat("void Fn(T const &) const &;", AlignMiddle); 10033 verifyFormat("void Fn(T const volatile &&) const volatile &&;", AlignMiddle); 10034 verifyFormat("void Fn(T const volatile &&) const volatile && noexcept;", 10035 AlignMiddle); 10036 verifyFormat("template <typename T> void operator=(T) &;", AlignMiddle); 10037 verifyFormat("template <typename T> void operator=(T) const &;", AlignMiddle); 10038 verifyFormat("template <typename T> void operator=(T) & noexcept;", 10039 AlignMiddle); 10040 verifyFormat("template <typename T> void operator=(T) & = default;", 10041 AlignMiddle); 10042 verifyFormat("template <typename T> void operator=(T) &&;", AlignMiddle); 10043 verifyFormat("template <typename T> void operator=(T) && = delete;", 10044 AlignMiddle); 10045 verifyFormat("template <typename T> void operator=(T) & {}", AlignMiddle); 10046 verifyFormat("template <typename T> void operator=(T) && {}", AlignMiddle); 10047 10048 FormatStyle Spaces = getLLVMStyle(); 10049 Spaces.SpacesInCStyleCastParentheses = true; 10050 verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces); 10051 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces); 10052 verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces); 10053 verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces); 10054 10055 Spaces.SpacesInCStyleCastParentheses = false; 10056 Spaces.SpacesInParentheses = true; 10057 verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces); 10058 verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;", 10059 Spaces); 10060 verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces); 10061 verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces); 10062 10063 FormatStyle BreakTemplate = getLLVMStyle(); 10064 BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 10065 10066 verifyFormat("struct f {\n" 10067 " template <class T>\n" 10068 " int &foo(const std::string &str) &noexcept {}\n" 10069 "};", 10070 BreakTemplate); 10071 10072 verifyFormat("struct f {\n" 10073 " template <class T>\n" 10074 " int &foo(const std::string &str) &&noexcept {}\n" 10075 "};", 10076 BreakTemplate); 10077 10078 verifyFormat("struct f {\n" 10079 " template <class T>\n" 10080 " int &foo(const std::string &str) const &noexcept {}\n" 10081 "};", 10082 BreakTemplate); 10083 10084 verifyFormat("struct f {\n" 10085 " template <class T>\n" 10086 " int &foo(const std::string &str) const &noexcept {}\n" 10087 "};", 10088 BreakTemplate); 10089 10090 verifyFormat("struct f {\n" 10091 " template <class T>\n" 10092 " auto foo(const std::string &str) &&noexcept -> int & {}\n" 10093 "};", 10094 BreakTemplate); 10095 10096 FormatStyle AlignLeftBreakTemplate = getLLVMStyle(); 10097 AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations = 10098 FormatStyle::BTDS_Yes; 10099 AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left; 10100 10101 verifyFormat("struct f {\n" 10102 " template <class T>\n" 10103 " int& foo(const std::string& str) & noexcept {}\n" 10104 "};", 10105 AlignLeftBreakTemplate); 10106 10107 verifyFormat("struct f {\n" 10108 " template <class T>\n" 10109 " int& foo(const std::string& str) && noexcept {}\n" 10110 "};", 10111 AlignLeftBreakTemplate); 10112 10113 verifyFormat("struct f {\n" 10114 " template <class T>\n" 10115 " int& foo(const std::string& str) const& noexcept {}\n" 10116 "};", 10117 AlignLeftBreakTemplate); 10118 10119 verifyFormat("struct f {\n" 10120 " template <class T>\n" 10121 " int& foo(const std::string& str) const&& noexcept {}\n" 10122 "};", 10123 AlignLeftBreakTemplate); 10124 10125 verifyFormat("struct f {\n" 10126 " template <class T>\n" 10127 " auto foo(const std::string& str) && noexcept -> int& {}\n" 10128 "};", 10129 AlignLeftBreakTemplate); 10130 10131 // The `&` in `Type&` should not be confused with a trailing `&` of 10132 // DEPRECATED(reason) member function. 10133 verifyFormat("struct f {\n" 10134 " template <class T>\n" 10135 " DEPRECATED(reason)\n" 10136 " Type &foo(arguments) {}\n" 10137 "};", 10138 BreakTemplate); 10139 10140 verifyFormat("struct f {\n" 10141 " template <class T>\n" 10142 " DEPRECATED(reason)\n" 10143 " Type& foo(arguments) {}\n" 10144 "};", 10145 AlignLeftBreakTemplate); 10146 10147 verifyFormat("void (*foopt)(int) = &func;"); 10148 10149 FormatStyle DerivePointerAlignment = getLLVMStyle(); 10150 DerivePointerAlignment.DerivePointerAlignment = true; 10151 // There's always a space between the function and its trailing qualifiers. 10152 // This isn't evidence for PAS_Right (or for PAS_Left). 10153 std::string Prefix = "void a() &;\n" 10154 "void b() &;\n"; 10155 verifyFormat(Prefix + "int* x;", DerivePointerAlignment); 10156 verifyFormat(Prefix + "int *x;", DerivePointerAlignment); 10157 // Same if the function is an overloaded operator, and with &&. 10158 Prefix = "void operator()() &&;\n" 10159 "void operator()() &&;\n"; 10160 verifyFormat(Prefix + "int* x;", DerivePointerAlignment); 10161 verifyFormat(Prefix + "int *x;", DerivePointerAlignment); 10162 // However a space between cv-qualifiers and ref-qualifiers *is* evidence. 10163 Prefix = "void a() const &;\n" 10164 "void b() const &;\n"; 10165 EXPECT_EQ(Prefix + "int *x;", 10166 format(Prefix + "int* x;", DerivePointerAlignment)); 10167 } 10168 10169 TEST_F(FormatTest, UnderstandsNewAndDelete) { 10170 verifyFormat("void f() {\n" 10171 " A *a = new A;\n" 10172 " A *a = new (placement) A;\n" 10173 " delete a;\n" 10174 " delete (A *)a;\n" 10175 "}"); 10176 verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n" 10177 " typename aaaaaaaaaaaaaaaaaaaaaaaa();"); 10178 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 10179 " new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n" 10180 " typename aaaaaaaaaaaaaaaaaaaaaaaa();"); 10181 verifyFormat("delete[] h->p;"); 10182 verifyFormat("delete[] (void *)p;"); 10183 10184 verifyFormat("void operator delete(void *foo) ATTRIB;"); 10185 verifyFormat("void operator new(void *foo) ATTRIB;"); 10186 verifyFormat("void operator delete[](void *foo) ATTRIB;"); 10187 verifyFormat("void operator delete(void *ptr) noexcept;"); 10188 10189 EXPECT_EQ("void new(link p);\n" 10190 "void delete(link p);\n", 10191 format("void new (link p);\n" 10192 "void delete (link p);\n")); 10193 } 10194 10195 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) { 10196 verifyFormat("int *f(int *a) {}"); 10197 verifyFormat("int main(int argc, char **argv) {}"); 10198 verifyFormat("Test::Test(int b) : a(b * b) {}"); 10199 verifyIndependentOfContext("f(a, *a);"); 10200 verifyFormat("void g() { f(*a); }"); 10201 verifyIndependentOfContext("int a = b * 10;"); 10202 verifyIndependentOfContext("int a = 10 * b;"); 10203 verifyIndependentOfContext("int a = b * c;"); 10204 verifyIndependentOfContext("int a += b * c;"); 10205 verifyIndependentOfContext("int a -= b * c;"); 10206 verifyIndependentOfContext("int a *= b * c;"); 10207 verifyIndependentOfContext("int a /= b * c;"); 10208 verifyIndependentOfContext("int a = *b;"); 10209 verifyIndependentOfContext("int a = *b * c;"); 10210 verifyIndependentOfContext("int a = b * *c;"); 10211 verifyIndependentOfContext("int a = b * (10);"); 10212 verifyIndependentOfContext("S << b * (10);"); 10213 verifyIndependentOfContext("return 10 * b;"); 10214 verifyIndependentOfContext("return *b * *c;"); 10215 verifyIndependentOfContext("return a & ~b;"); 10216 verifyIndependentOfContext("f(b ? *c : *d);"); 10217 verifyIndependentOfContext("int a = b ? *c : *d;"); 10218 verifyIndependentOfContext("*b = a;"); 10219 verifyIndependentOfContext("a * ~b;"); 10220 verifyIndependentOfContext("a * !b;"); 10221 verifyIndependentOfContext("a * +b;"); 10222 verifyIndependentOfContext("a * -b;"); 10223 verifyIndependentOfContext("a * ++b;"); 10224 verifyIndependentOfContext("a * --b;"); 10225 verifyIndependentOfContext("a[4] * b;"); 10226 verifyIndependentOfContext("a[a * a] = 1;"); 10227 verifyIndependentOfContext("f() * b;"); 10228 verifyIndependentOfContext("a * [self dostuff];"); 10229 verifyIndependentOfContext("int x = a * (a + b);"); 10230 verifyIndependentOfContext("(a *)(a + b);"); 10231 verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;"); 10232 verifyIndependentOfContext("int *pa = (int *)&a;"); 10233 verifyIndependentOfContext("return sizeof(int **);"); 10234 verifyIndependentOfContext("return sizeof(int ******);"); 10235 verifyIndependentOfContext("return (int **&)a;"); 10236 verifyIndependentOfContext("f((*PointerToArray)[10]);"); 10237 verifyFormat("void f(Type (*parameter)[10]) {}"); 10238 verifyFormat("void f(Type (¶meter)[10]) {}"); 10239 verifyGoogleFormat("return sizeof(int**);"); 10240 verifyIndependentOfContext("Type **A = static_cast<Type **>(P);"); 10241 verifyGoogleFormat("Type** A = static_cast<Type**>(P);"); 10242 verifyFormat("auto a = [](int **&, int ***) {};"); 10243 verifyFormat("auto PointerBinding = [](const char *S) {};"); 10244 verifyFormat("typedef typeof(int(int, int)) *MyFunc;"); 10245 verifyFormat("[](const decltype(*a) &value) {}"); 10246 verifyFormat("[](const typeof(*a) &value) {}"); 10247 verifyFormat("[](const _Atomic(a *) &value) {}"); 10248 verifyFormat("[](const __underlying_type(a) &value) {}"); 10249 verifyFormat("decltype(a * b) F();"); 10250 verifyFormat("typeof(a * b) F();"); 10251 verifyFormat("#define MACRO() [](A *a) { return 1; }"); 10252 verifyFormat("Constructor() : member([](A *a, B *b) {}) {}"); 10253 verifyIndependentOfContext("typedef void (*f)(int *a);"); 10254 verifyIndependentOfContext("int i{a * b};"); 10255 verifyIndependentOfContext("aaa && aaa->f();"); 10256 verifyIndependentOfContext("int x = ~*p;"); 10257 verifyFormat("Constructor() : a(a), area(width * height) {}"); 10258 verifyFormat("Constructor() : a(a), area(a, width * height) {}"); 10259 verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}"); 10260 verifyFormat("void f() { f(a, c * d); }"); 10261 verifyFormat("void f() { f(new a(), c * d); }"); 10262 verifyFormat("void f(const MyOverride &override);"); 10263 verifyFormat("void f(const MyFinal &final);"); 10264 verifyIndependentOfContext("bool a = f() && override.f();"); 10265 verifyIndependentOfContext("bool a = f() && final.f();"); 10266 10267 verifyIndependentOfContext("InvalidRegions[*R] = 0;"); 10268 10269 verifyIndependentOfContext("A<int *> a;"); 10270 verifyIndependentOfContext("A<int **> a;"); 10271 verifyIndependentOfContext("A<int *, int *> a;"); 10272 verifyIndependentOfContext("A<int *[]> a;"); 10273 verifyIndependentOfContext( 10274 "const char *const p = reinterpret_cast<const char *const>(q);"); 10275 verifyIndependentOfContext("A<int **, int **> a;"); 10276 verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);"); 10277 verifyFormat("for (char **a = b; *a; ++a) {\n}"); 10278 verifyFormat("for (; a && b;) {\n}"); 10279 verifyFormat("bool foo = true && [] { return false; }();"); 10280 10281 verifyFormat( 10282 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 10283 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 10284 10285 verifyGoogleFormat("int const* a = &b;"); 10286 verifyGoogleFormat("**outparam = 1;"); 10287 verifyGoogleFormat("*outparam = a * b;"); 10288 verifyGoogleFormat("int main(int argc, char** argv) {}"); 10289 verifyGoogleFormat("A<int*> a;"); 10290 verifyGoogleFormat("A<int**> a;"); 10291 verifyGoogleFormat("A<int*, int*> a;"); 10292 verifyGoogleFormat("A<int**, int**> a;"); 10293 verifyGoogleFormat("f(b ? *c : *d);"); 10294 verifyGoogleFormat("int a = b ? *c : *d;"); 10295 verifyGoogleFormat("Type* t = **x;"); 10296 verifyGoogleFormat("Type* t = *++*x;"); 10297 verifyGoogleFormat("*++*x;"); 10298 verifyGoogleFormat("Type* t = const_cast<T*>(&*x);"); 10299 verifyGoogleFormat("Type* t = x++ * y;"); 10300 verifyGoogleFormat( 10301 "const char* const p = reinterpret_cast<const char* const>(q);"); 10302 verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);"); 10303 verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);"); 10304 verifyGoogleFormat("template <typename T>\n" 10305 "void f(int i = 0, SomeType** temps = NULL);"); 10306 10307 FormatStyle Left = getLLVMStyle(); 10308 Left.PointerAlignment = FormatStyle::PAS_Left; 10309 verifyFormat("x = *a(x) = *a(y);", Left); 10310 verifyFormat("for (;; *a = b) {\n}", Left); 10311 verifyFormat("return *this += 1;", Left); 10312 verifyFormat("throw *x;", Left); 10313 verifyFormat("delete *x;", Left); 10314 verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left); 10315 verifyFormat("[](const decltype(*a)* ptr) {}", Left); 10316 verifyFormat("[](const typeof(*a)* ptr) {}", Left); 10317 verifyFormat("[](const _Atomic(a*)* ptr) {}", Left); 10318 verifyFormat("[](const __underlying_type(a)* ptr) {}", Left); 10319 verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left); 10320 verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left); 10321 verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left); 10322 verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left); 10323 10324 verifyIndependentOfContext("a = *(x + y);"); 10325 verifyIndependentOfContext("a = &(x + y);"); 10326 verifyIndependentOfContext("*(x + y).call();"); 10327 verifyIndependentOfContext("&(x + y)->call();"); 10328 verifyFormat("void f() { &(*I).first; }"); 10329 10330 verifyIndependentOfContext("f(b * /* confusing comment */ ++c);"); 10331 verifyFormat("f(* /* confusing comment */ foo);"); 10332 verifyFormat("void (* /*deleter*/)(const Slice &key, void *value)"); 10333 verifyFormat("void foo(int * // this is the first paramters\n" 10334 " ,\n" 10335 " int second);"); 10336 verifyFormat("double term = a * // first\n" 10337 " b;"); 10338 verifyFormat( 10339 "int *MyValues = {\n" 10340 " *A, // Operator detection might be confused by the '{'\n" 10341 " *BB // Operator detection might be confused by previous comment\n" 10342 "};"); 10343 10344 verifyIndependentOfContext("if (int *a = &b)"); 10345 verifyIndependentOfContext("if (int &a = *b)"); 10346 verifyIndependentOfContext("if (a & b[i])"); 10347 verifyIndependentOfContext("if constexpr (a & b[i])"); 10348 verifyIndependentOfContext("if CONSTEXPR (a & b[i])"); 10349 verifyIndependentOfContext("if (a * (b * c))"); 10350 verifyIndependentOfContext("if constexpr (a * (b * c))"); 10351 verifyIndependentOfContext("if CONSTEXPR (a * (b * c))"); 10352 verifyIndependentOfContext("if (a::b::c::d & b[i])"); 10353 verifyIndependentOfContext("if (*b[i])"); 10354 verifyIndependentOfContext("if (int *a = (&b))"); 10355 verifyIndependentOfContext("while (int *a = &b)"); 10356 verifyIndependentOfContext("while (a * (b * c))"); 10357 verifyIndependentOfContext("size = sizeof *a;"); 10358 verifyIndependentOfContext("if (a && (b = c))"); 10359 verifyFormat("void f() {\n" 10360 " for (const int &v : Values) {\n" 10361 " }\n" 10362 "}"); 10363 verifyFormat("for (int i = a * a; i < 10; ++i) {\n}"); 10364 verifyFormat("for (int i = 0; i < a * a; ++i) {\n}"); 10365 verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}"); 10366 10367 verifyFormat("#define A (!a * b)"); 10368 verifyFormat("#define MACRO \\\n" 10369 " int *i = a * b; \\\n" 10370 " void f(a *b);", 10371 getLLVMStyleWithColumns(19)); 10372 10373 verifyIndependentOfContext("A = new SomeType *[Length];"); 10374 verifyIndependentOfContext("A = new SomeType *[Length]();"); 10375 verifyIndependentOfContext("T **t = new T *;"); 10376 verifyIndependentOfContext("T **t = new T *();"); 10377 verifyGoogleFormat("A = new SomeType*[Length]();"); 10378 verifyGoogleFormat("A = new SomeType*[Length];"); 10379 verifyGoogleFormat("T** t = new T*;"); 10380 verifyGoogleFormat("T** t = new T*();"); 10381 10382 verifyFormat("STATIC_ASSERT((a & b) == 0);"); 10383 verifyFormat("STATIC_ASSERT(0 == (a & b));"); 10384 verifyFormat("template <bool a, bool b> " 10385 "typename t::if<x && y>::type f() {}"); 10386 verifyFormat("template <int *y> f() {}"); 10387 verifyFormat("vector<int *> v;"); 10388 verifyFormat("vector<int *const> v;"); 10389 verifyFormat("vector<int *const **const *> v;"); 10390 verifyFormat("vector<int *volatile> v;"); 10391 verifyFormat("vector<a *_Nonnull> v;"); 10392 verifyFormat("vector<a *_Nullable> v;"); 10393 verifyFormat("vector<a *_Null_unspecified> v;"); 10394 verifyFormat("vector<a *__ptr32> v;"); 10395 verifyFormat("vector<a *__ptr64> v;"); 10396 verifyFormat("vector<a *__capability> v;"); 10397 FormatStyle TypeMacros = getLLVMStyle(); 10398 TypeMacros.TypenameMacros = {"LIST"}; 10399 verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros); 10400 verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros); 10401 verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros); 10402 verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros); 10403 verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication 10404 10405 FormatStyle CustomQualifier = getLLVMStyle(); 10406 // Add identifiers that should not be parsed as a qualifier by default. 10407 CustomQualifier.AttributeMacros.push_back("__my_qualifier"); 10408 CustomQualifier.AttributeMacros.push_back("_My_qualifier"); 10409 CustomQualifier.AttributeMacros.push_back("my_other_qualifier"); 10410 verifyFormat("vector<a * __my_qualifier> parse_as_multiply;"); 10411 verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier); 10412 verifyFormat("vector<a * _My_qualifier> parse_as_multiply;"); 10413 verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier); 10414 verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;"); 10415 verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier); 10416 verifyFormat("vector<a * _NotAQualifier> v;"); 10417 verifyFormat("vector<a * __not_a_qualifier> v;"); 10418 verifyFormat("vector<a * b> v;"); 10419 verifyFormat("foo<b && false>();"); 10420 verifyFormat("foo<b & 1>();"); 10421 verifyFormat("foo<b & (1)>();"); 10422 verifyFormat("foo<b & (~0)>();"); 10423 verifyFormat("foo<b & (true)>();"); 10424 verifyFormat("foo<b & ((1))>();"); 10425 verifyFormat("foo<b & (/*comment*/ 1)>();"); 10426 verifyFormat("decltype(*::std::declval<const T &>()) void F();"); 10427 verifyFormat("typeof(*::std::declval<const T &>()) void F();"); 10428 verifyFormat("_Atomic(*::std::declval<const T &>()) void F();"); 10429 verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();"); 10430 verifyFormat( 10431 "template <class T, class = typename std::enable_if<\n" 10432 " std::is_integral<T>::value &&\n" 10433 " (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n" 10434 "void F();", 10435 getLLVMStyleWithColumns(70)); 10436 verifyFormat("template <class T,\n" 10437 " class = typename std::enable_if<\n" 10438 " std::is_integral<T>::value &&\n" 10439 " (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n" 10440 " class U>\n" 10441 "void F();", 10442 getLLVMStyleWithColumns(70)); 10443 verifyFormat( 10444 "template <class T,\n" 10445 " class = typename ::std::enable_if<\n" 10446 " ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n" 10447 "void F();", 10448 getGoogleStyleWithColumns(68)); 10449 10450 FormatStyle Style = getLLVMStyle(); 10451 Style.PointerAlignment = FormatStyle::PAS_Left; 10452 verifyFormat("struct {\n" 10453 "}* ptr;", 10454 Style); 10455 verifyFormat("union {\n" 10456 "}* ptr;", 10457 Style); 10458 verifyFormat("class {\n" 10459 "}* ptr;", 10460 Style); 10461 verifyFormat("struct {\n" 10462 "}&& ptr = {};", 10463 Style); 10464 verifyFormat("union {\n" 10465 "}&& ptr = {};", 10466 Style); 10467 verifyFormat("class {\n" 10468 "}&& ptr = {};", 10469 Style); 10470 10471 Style.PointerAlignment = FormatStyle::PAS_Middle; 10472 verifyFormat("struct {\n" 10473 "} * ptr;", 10474 Style); 10475 verifyFormat("union {\n" 10476 "} * ptr;", 10477 Style); 10478 verifyFormat("class {\n" 10479 "} * ptr;", 10480 Style); 10481 verifyFormat("struct {\n" 10482 "} && ptr = {};", 10483 Style); 10484 verifyFormat("union {\n" 10485 "} && ptr = {};", 10486 Style); 10487 verifyFormat("class {\n" 10488 "} && ptr = {};", 10489 Style); 10490 10491 Style.PointerAlignment = FormatStyle::PAS_Right; 10492 verifyFormat("struct {\n" 10493 "} *ptr;", 10494 Style); 10495 verifyFormat("union {\n" 10496 "} *ptr;", 10497 Style); 10498 verifyFormat("class {\n" 10499 "} *ptr;", 10500 Style); 10501 verifyFormat("struct {\n" 10502 "} &&ptr = {};", 10503 Style); 10504 verifyFormat("union {\n" 10505 "} &&ptr = {};", 10506 Style); 10507 verifyFormat("class {\n" 10508 "} &&ptr = {};", 10509 Style); 10510 10511 verifyIndependentOfContext("MACRO(int *i);"); 10512 verifyIndependentOfContext("MACRO(auto *a);"); 10513 verifyIndependentOfContext("MACRO(const A *a);"); 10514 verifyIndependentOfContext("MACRO(_Atomic(A) *a);"); 10515 verifyIndependentOfContext("MACRO(decltype(A) *a);"); 10516 verifyIndependentOfContext("MACRO(typeof(A) *a);"); 10517 verifyIndependentOfContext("MACRO(__underlying_type(A) *a);"); 10518 verifyIndependentOfContext("MACRO(A *const a);"); 10519 verifyIndependentOfContext("MACRO(A *restrict a);"); 10520 verifyIndependentOfContext("MACRO(A *__restrict__ a);"); 10521 verifyIndependentOfContext("MACRO(A *__restrict a);"); 10522 verifyIndependentOfContext("MACRO(A *volatile a);"); 10523 verifyIndependentOfContext("MACRO(A *__volatile a);"); 10524 verifyIndependentOfContext("MACRO(A *__volatile__ a);"); 10525 verifyIndependentOfContext("MACRO(A *_Nonnull a);"); 10526 verifyIndependentOfContext("MACRO(A *_Nullable a);"); 10527 verifyIndependentOfContext("MACRO(A *_Null_unspecified a);"); 10528 verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);"); 10529 verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);"); 10530 verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);"); 10531 verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);"); 10532 verifyIndependentOfContext("MACRO(A *__ptr32 a);"); 10533 verifyIndependentOfContext("MACRO(A *__ptr64 a);"); 10534 verifyIndependentOfContext("MACRO(A *__capability);"); 10535 verifyIndependentOfContext("MACRO(A &__capability);"); 10536 verifyFormat("MACRO(A *__my_qualifier);"); // type declaration 10537 verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication 10538 // If we add __my_qualifier to AttributeMacros it should always be parsed as 10539 // a type declaration: 10540 verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier); 10541 verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier); 10542 // Also check that TypenameMacros prevents parsing it as multiplication: 10543 verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication 10544 verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type 10545 10546 verifyIndependentOfContext("MACRO('0' <= c && c <= '9');"); 10547 verifyFormat("void f() { f(float{1}, a * a); }"); 10548 verifyFormat("void f() { f(float(1), a * a); }"); 10549 10550 verifyFormat("f((void (*)(int))g);"); 10551 verifyFormat("f((void (&)(int))g);"); 10552 verifyFormat("f((void (^)(int))g);"); 10553 10554 // FIXME: Is there a way to make this work? 10555 // verifyIndependentOfContext("MACRO(A *a);"); 10556 verifyFormat("MACRO(A &B);"); 10557 verifyFormat("MACRO(A *B);"); 10558 verifyFormat("void f() { MACRO(A * B); }"); 10559 verifyFormat("void f() { MACRO(A & B); }"); 10560 10561 // This lambda was mis-formatted after D88956 (treating it as a binop): 10562 verifyFormat("auto x = [](const decltype(x) &ptr) {};"); 10563 verifyFormat("auto x = [](const decltype(x) *ptr) {};"); 10564 verifyFormat("#define lambda [](const decltype(x) &ptr) {}"); 10565 verifyFormat("#define lambda [](const decltype(x) *ptr) {}"); 10566 10567 verifyFormat("DatumHandle const *operator->() const { return input_; }"); 10568 verifyFormat("return options != nullptr && operator==(*options);"); 10569 10570 EXPECT_EQ("#define OP(x) \\\n" 10571 " ostream &operator<<(ostream &s, const A &a) { \\\n" 10572 " return s << a.DebugString(); \\\n" 10573 " }", 10574 format("#define OP(x) \\\n" 10575 " ostream &operator<<(ostream &s, const A &a) { \\\n" 10576 " return s << a.DebugString(); \\\n" 10577 " }", 10578 getLLVMStyleWithColumns(50))); 10579 10580 // FIXME: We cannot handle this case yet; we might be able to figure out that 10581 // foo<x> d > v; doesn't make sense. 10582 verifyFormat("foo<a<b && c> d> v;"); 10583 10584 FormatStyle PointerMiddle = getLLVMStyle(); 10585 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle; 10586 verifyFormat("delete *x;", PointerMiddle); 10587 verifyFormat("int * x;", PointerMiddle); 10588 verifyFormat("int *[] x;", PointerMiddle); 10589 verifyFormat("template <int * y> f() {}", PointerMiddle); 10590 verifyFormat("int * f(int * a) {}", PointerMiddle); 10591 verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle); 10592 verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle); 10593 verifyFormat("A<int *> a;", PointerMiddle); 10594 verifyFormat("A<int **> a;", PointerMiddle); 10595 verifyFormat("A<int *, int *> a;", PointerMiddle); 10596 verifyFormat("A<int *[]> a;", PointerMiddle); 10597 verifyFormat("A = new SomeType *[Length]();", PointerMiddle); 10598 verifyFormat("A = new SomeType *[Length];", PointerMiddle); 10599 verifyFormat("T ** t = new T *;", PointerMiddle); 10600 10601 // Member function reference qualifiers aren't binary operators. 10602 verifyFormat("string // break\n" 10603 "operator()() & {}"); 10604 verifyFormat("string // break\n" 10605 "operator()() && {}"); 10606 verifyGoogleFormat("template <typename T>\n" 10607 "auto x() & -> int {}"); 10608 10609 // Should be binary operators when used as an argument expression (overloaded 10610 // operator invoked as a member function). 10611 verifyFormat("void f() { a.operator()(a * a); }"); 10612 verifyFormat("void f() { a->operator()(a & a); }"); 10613 verifyFormat("void f() { a.operator()(*a & *a); }"); 10614 verifyFormat("void f() { a->operator()(*a * *a); }"); 10615 10616 verifyFormat("int operator()(T (&&)[N]) { return 1; }"); 10617 verifyFormat("int operator()(T (&)[N]) { return 0; }"); 10618 } 10619 10620 TEST_F(FormatTest, UnderstandsAttributes) { 10621 verifyFormat("SomeType s __attribute__((unused)) (InitValue);"); 10622 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n" 10623 "aaaaaaaaaaaaaaaaaaaaaaa(int i);"); 10624 verifyFormat("__attribute__((nodebug)) ::qualified_type f();"); 10625 FormatStyle AfterType = getLLVMStyle(); 10626 AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 10627 verifyFormat("__attribute__((nodebug)) void\n" 10628 "foo() {}\n", 10629 AfterType); 10630 verifyFormat("__unused void\n" 10631 "foo() {}", 10632 AfterType); 10633 10634 FormatStyle CustomAttrs = getLLVMStyle(); 10635 CustomAttrs.AttributeMacros.push_back("__unused"); 10636 CustomAttrs.AttributeMacros.push_back("__attr1"); 10637 CustomAttrs.AttributeMacros.push_back("__attr2"); 10638 CustomAttrs.AttributeMacros.push_back("no_underscore_attr"); 10639 verifyFormat("vector<SomeType *__attribute((foo))> v;"); 10640 verifyFormat("vector<SomeType *__attribute__((foo))> v;"); 10641 verifyFormat("vector<SomeType * __not_attribute__((foo))> v;"); 10642 // Check that it is parsed as a multiplication without AttributeMacros and 10643 // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros. 10644 verifyFormat("vector<SomeType * __attr1> v;"); 10645 verifyFormat("vector<SomeType __attr1 *> v;"); 10646 verifyFormat("vector<SomeType __attr1 *const> v;"); 10647 verifyFormat("vector<SomeType __attr1 * __attr2> v;"); 10648 verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs); 10649 verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs); 10650 verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs); 10651 verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs); 10652 verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs); 10653 verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs); 10654 verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs); 10655 10656 // Check that these are not parsed as function declarations: 10657 CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 10658 CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman; 10659 verifyFormat("SomeType s(InitValue);", CustomAttrs); 10660 verifyFormat("SomeType s{InitValue};", CustomAttrs); 10661 verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs); 10662 verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs); 10663 verifyFormat("SomeType s __unused(InitValue);", CustomAttrs); 10664 verifyFormat("SomeType s __unused{InitValue};", CustomAttrs); 10665 verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs); 10666 verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs); 10667 } 10668 10669 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) { 10670 // Check that qualifiers on pointers don't break parsing of casts. 10671 verifyFormat("x = (foo *const)*v;"); 10672 verifyFormat("x = (foo *volatile)*v;"); 10673 verifyFormat("x = (foo *restrict)*v;"); 10674 verifyFormat("x = (foo *__attribute__((foo)))*v;"); 10675 verifyFormat("x = (foo *_Nonnull)*v;"); 10676 verifyFormat("x = (foo *_Nullable)*v;"); 10677 verifyFormat("x = (foo *_Null_unspecified)*v;"); 10678 verifyFormat("x = (foo *_Nonnull)*v;"); 10679 verifyFormat("x = (foo *[[clang::attr]])*v;"); 10680 verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;"); 10681 verifyFormat("x = (foo *__ptr32)*v;"); 10682 verifyFormat("x = (foo *__ptr64)*v;"); 10683 verifyFormat("x = (foo *__capability)*v;"); 10684 10685 // Check that we handle multiple trailing qualifiers and skip them all to 10686 // determine that the expression is a cast to a pointer type. 10687 FormatStyle LongPointerRight = getLLVMStyleWithColumns(999); 10688 FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999); 10689 LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left; 10690 StringRef AllQualifiers = 10691 "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified " 10692 "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability"; 10693 verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight); 10694 verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft); 10695 10696 // Also check that address-of is not parsed as a binary bitwise-and: 10697 verifyFormat("x = (foo *const)&v;"); 10698 verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight); 10699 verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft); 10700 10701 // Check custom qualifiers: 10702 FormatStyle CustomQualifier = getLLVMStyleWithColumns(999); 10703 CustomQualifier.AttributeMacros.push_back("__my_qualifier"); 10704 verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier. 10705 verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier); 10706 verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(), 10707 CustomQualifier); 10708 verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(), 10709 CustomQualifier); 10710 10711 // Check that unknown identifiers result in binary operator parsing: 10712 verifyFormat("x = (foo * __unknown_qualifier) * v;"); 10713 verifyFormat("x = (foo * __unknown_qualifier) & v;"); 10714 } 10715 10716 TEST_F(FormatTest, UnderstandsSquareAttributes) { 10717 verifyFormat("SomeType s [[unused]] (InitValue);"); 10718 verifyFormat("SomeType s [[gnu::unused]] (InitValue);"); 10719 verifyFormat("SomeType s [[using gnu: unused]] (InitValue);"); 10720 verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}"); 10721 verifyFormat("void f() [[deprecated(\"so sorry\")]];"); 10722 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10723 " [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);"); 10724 verifyFormat("[[nodiscard]] bool f() { return false; }"); 10725 verifyFormat("class [[nodiscard]] f {\npublic:\n f() {}\n}"); 10726 verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n f() {}\n}"); 10727 verifyFormat("class [[gnu::unused]] f {\npublic:\n f() {}\n}"); 10728 verifyFormat("[[nodiscard]] ::qualified_type f();"); 10729 10730 // Make sure we do not mistake attributes for array subscripts. 10731 verifyFormat("int a() {}\n" 10732 "[[unused]] int b() {}\n"); 10733 verifyFormat("NSArray *arr;\n" 10734 "arr[[Foo() bar]];"); 10735 10736 // On the other hand, we still need to correctly find array subscripts. 10737 verifyFormat("int a = std::vector<int>{1, 2, 3}[0];"); 10738 10739 // Make sure that we do not mistake Objective-C method inside array literals 10740 // as attributes, even if those method names are also keywords. 10741 verifyFormat("@[ [foo bar] ];"); 10742 verifyFormat("@[ [NSArray class] ];"); 10743 verifyFormat("@[ [foo enum] ];"); 10744 10745 verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }"); 10746 10747 // Make sure we do not parse attributes as lambda introducers. 10748 FormatStyle MultiLineFunctions = getLLVMStyle(); 10749 MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 10750 verifyFormat("[[unused]] int b() {\n" 10751 " return 42;\n" 10752 "}\n", 10753 MultiLineFunctions); 10754 } 10755 10756 TEST_F(FormatTest, AttributeClass) { 10757 FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp); 10758 verifyFormat("class S {\n" 10759 " S(S&&) = default;\n" 10760 "};", 10761 Style); 10762 verifyFormat("class [[nodiscard]] S {\n" 10763 " S(S&&) = default;\n" 10764 "};", 10765 Style); 10766 verifyFormat("class __attribute((maybeunused)) S {\n" 10767 " S(S&&) = default;\n" 10768 "};", 10769 Style); 10770 verifyFormat("struct S {\n" 10771 " S(S&&) = default;\n" 10772 "};", 10773 Style); 10774 verifyFormat("struct [[nodiscard]] S {\n" 10775 " S(S&&) = default;\n" 10776 "};", 10777 Style); 10778 } 10779 10780 TEST_F(FormatTest, AttributesAfterMacro) { 10781 FormatStyle Style = getLLVMStyle(); 10782 verifyFormat("MACRO;\n" 10783 "__attribute__((maybe_unused)) int foo() {\n" 10784 " //...\n" 10785 "}"); 10786 10787 verifyFormat("MACRO;\n" 10788 "[[nodiscard]] int foo() {\n" 10789 " //...\n" 10790 "}"); 10791 10792 EXPECT_EQ("MACRO\n\n" 10793 "__attribute__((maybe_unused)) int foo() {\n" 10794 " //...\n" 10795 "}", 10796 format("MACRO\n\n" 10797 "__attribute__((maybe_unused)) int foo() {\n" 10798 " //...\n" 10799 "}")); 10800 10801 EXPECT_EQ("MACRO\n\n" 10802 "[[nodiscard]] int foo() {\n" 10803 " //...\n" 10804 "}", 10805 format("MACRO\n\n" 10806 "[[nodiscard]] int foo() {\n" 10807 " //...\n" 10808 "}")); 10809 } 10810 10811 TEST_F(FormatTest, AttributePenaltyBreaking) { 10812 FormatStyle Style = getLLVMStyle(); 10813 verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n" 10814 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}", 10815 Style); 10816 verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n" 10817 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}", 10818 Style); 10819 verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const " 10820 "shared_ptr<ALongTypeName> &C d) {\n}", 10821 Style); 10822 } 10823 10824 TEST_F(FormatTest, UnderstandsEllipsis) { 10825 FormatStyle Style = getLLVMStyle(); 10826 verifyFormat("int printf(const char *fmt, ...);"); 10827 verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }"); 10828 verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}"); 10829 10830 verifyFormat("template <int *...PP> a;", Style); 10831 10832 Style.PointerAlignment = FormatStyle::PAS_Left; 10833 verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style); 10834 10835 verifyFormat("template <int*... PP> a;", Style); 10836 10837 Style.PointerAlignment = FormatStyle::PAS_Middle; 10838 verifyFormat("template <int *... PP> a;", Style); 10839 } 10840 10841 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) { 10842 EXPECT_EQ("int *a;\n" 10843 "int *a;\n" 10844 "int *a;", 10845 format("int *a;\n" 10846 "int* a;\n" 10847 "int *a;", 10848 getGoogleStyle())); 10849 EXPECT_EQ("int* a;\n" 10850 "int* a;\n" 10851 "int* a;", 10852 format("int* a;\n" 10853 "int* a;\n" 10854 "int *a;", 10855 getGoogleStyle())); 10856 EXPECT_EQ("int *a;\n" 10857 "int *a;\n" 10858 "int *a;", 10859 format("int *a;\n" 10860 "int * a;\n" 10861 "int * a;", 10862 getGoogleStyle())); 10863 EXPECT_EQ("auto x = [] {\n" 10864 " int *a;\n" 10865 " int *a;\n" 10866 " int *a;\n" 10867 "};", 10868 format("auto x=[]{int *a;\n" 10869 "int * a;\n" 10870 "int * a;};", 10871 getGoogleStyle())); 10872 } 10873 10874 TEST_F(FormatTest, UnderstandsRvalueReferences) { 10875 verifyFormat("int f(int &&a) {}"); 10876 verifyFormat("int f(int a, char &&b) {}"); 10877 verifyFormat("void f() { int &&a = b; }"); 10878 verifyGoogleFormat("int f(int a, char&& b) {}"); 10879 verifyGoogleFormat("void f() { int&& a = b; }"); 10880 10881 verifyIndependentOfContext("A<int &&> a;"); 10882 verifyIndependentOfContext("A<int &&, int &&> a;"); 10883 verifyGoogleFormat("A<int&&> a;"); 10884 verifyGoogleFormat("A<int&&, int&&> a;"); 10885 10886 // Not rvalue references: 10887 verifyFormat("template <bool B, bool C> class A {\n" 10888 " static_assert(B && C, \"Something is wrong\");\n" 10889 "};"); 10890 verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))"); 10891 verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))"); 10892 verifyFormat("#define A(a, b) (a && b)"); 10893 } 10894 10895 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) { 10896 verifyFormat("void f() {\n" 10897 " x[aaaaaaaaa -\n" 10898 " b] = 23;\n" 10899 "}", 10900 getLLVMStyleWithColumns(15)); 10901 } 10902 10903 TEST_F(FormatTest, FormatsCasts) { 10904 verifyFormat("Type *A = static_cast<Type *>(P);"); 10905 verifyFormat("static_cast<Type *>(P);"); 10906 verifyFormat("static_cast<Type &>(Fun)(Args);"); 10907 verifyFormat("static_cast<Type &>(*Fun)(Args);"); 10908 verifyFormat("if (static_cast<int>(A) + B >= 0)\n ;"); 10909 // Check that static_cast<...>(...) does not require the next token to be on 10910 // the same line. 10911 verifyFormat("some_loooong_output << something_something__ << " 10912 "static_cast<const void *>(R)\n" 10913 " << something;"); 10914 verifyFormat("a = static_cast<Type &>(*Fun)(Args);"); 10915 verifyFormat("const_cast<Type &>(*Fun)(Args);"); 10916 verifyFormat("dynamic_cast<Type &>(*Fun)(Args);"); 10917 verifyFormat("reinterpret_cast<Type &>(*Fun)(Args);"); 10918 verifyFormat("Type *A = (Type *)P;"); 10919 verifyFormat("Type *A = (vector<Type *, int *>)P;"); 10920 verifyFormat("int a = (int)(2.0f);"); 10921 verifyFormat("int a = (int)2.0f;"); 10922 verifyFormat("x[(int32)y];"); 10923 verifyFormat("x = (int32)y;"); 10924 verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)"); 10925 verifyFormat("int a = (int)*b;"); 10926 verifyFormat("int a = (int)2.0f;"); 10927 verifyFormat("int a = (int)~0;"); 10928 verifyFormat("int a = (int)++a;"); 10929 verifyFormat("int a = (int)sizeof(int);"); 10930 verifyFormat("int a = (int)+2;"); 10931 verifyFormat("my_int a = (my_int)2.0f;"); 10932 verifyFormat("my_int a = (my_int)sizeof(int);"); 10933 verifyFormat("return (my_int)aaa;"); 10934 verifyFormat("#define x ((int)-1)"); 10935 verifyFormat("#define LENGTH(x, y) (x) - (y) + 1"); 10936 verifyFormat("#define p(q) ((int *)&q)"); 10937 verifyFormat("fn(a)(b) + 1;"); 10938 10939 verifyFormat("void f() { my_int a = (my_int)*b; }"); 10940 verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }"); 10941 verifyFormat("my_int a = (my_int)~0;"); 10942 verifyFormat("my_int a = (my_int)++a;"); 10943 verifyFormat("my_int a = (my_int)-2;"); 10944 verifyFormat("my_int a = (my_int)1;"); 10945 verifyFormat("my_int a = (my_int *)1;"); 10946 verifyFormat("my_int a = (const my_int)-1;"); 10947 verifyFormat("my_int a = (const my_int *)-1;"); 10948 verifyFormat("my_int a = (my_int)(my_int)-1;"); 10949 verifyFormat("my_int a = (ns::my_int)-2;"); 10950 verifyFormat("case (my_int)ONE:"); 10951 verifyFormat("auto x = (X)this;"); 10952 // Casts in Obj-C style calls used to not be recognized as such. 10953 verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle()); 10954 10955 // FIXME: single value wrapped with paren will be treated as cast. 10956 verifyFormat("void f(int i = (kValue)*kMask) {}"); 10957 10958 verifyFormat("{ (void)F; }"); 10959 10960 // Don't break after a cast's 10961 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 10962 " (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n" 10963 " bbbbbbbbbbbbbbbbbbbbbb);"); 10964 10965 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(x)"); 10966 verifyFormat("#define CONF_BOOL(x) (bool *)(x)"); 10967 verifyFormat("#define CONF_BOOL(x) (bool)(x)"); 10968 verifyFormat("bool *y = (bool *)(void *)(x);"); 10969 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)(x)"); 10970 verifyFormat("bool *y = (bool *)(void *)(int)(x);"); 10971 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)foo(x)"); 10972 verifyFormat("bool *y = (bool *)(void *)(int)foo(x);"); 10973 10974 // These are not casts. 10975 verifyFormat("void f(int *) {}"); 10976 verifyFormat("f(foo)->b;"); 10977 verifyFormat("f(foo).b;"); 10978 verifyFormat("f(foo)(b);"); 10979 verifyFormat("f(foo)[b];"); 10980 verifyFormat("[](foo) { return 4; }(bar);"); 10981 verifyFormat("(*funptr)(foo)[4];"); 10982 verifyFormat("funptrs[4](foo)[4];"); 10983 verifyFormat("void f(int *);"); 10984 verifyFormat("void f(int *) = 0;"); 10985 verifyFormat("void f(SmallVector<int>) {}"); 10986 verifyFormat("void f(SmallVector<int>);"); 10987 verifyFormat("void f(SmallVector<int>) = 0;"); 10988 verifyFormat("void f(int i = (kA * kB) & kMask) {}"); 10989 verifyFormat("int a = sizeof(int) * b;"); 10990 verifyFormat("int a = alignof(int) * b;", getGoogleStyle()); 10991 verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;"); 10992 verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");"); 10993 verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;"); 10994 10995 // These are not casts, but at some point were confused with casts. 10996 verifyFormat("virtual void foo(int *) override;"); 10997 verifyFormat("virtual void foo(char &) const;"); 10998 verifyFormat("virtual void foo(int *a, char *) const;"); 10999 verifyFormat("int a = sizeof(int *) + b;"); 11000 verifyFormat("int a = alignof(int *) + b;", getGoogleStyle()); 11001 verifyFormat("bool b = f(g<int>) && c;"); 11002 verifyFormat("typedef void (*f)(int i) func;"); 11003 verifyFormat("void operator++(int) noexcept;"); 11004 verifyFormat("void operator++(int &) noexcept;"); 11005 verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t " 11006 "&) noexcept;"); 11007 verifyFormat( 11008 "void operator delete(std::size_t, const std::nothrow_t &) noexcept;"); 11009 verifyFormat("void operator delete(const std::nothrow_t &) noexcept;"); 11010 verifyFormat("void operator delete(std::nothrow_t &) noexcept;"); 11011 verifyFormat("void operator delete(nothrow_t &) noexcept;"); 11012 verifyFormat("void operator delete(foo &) noexcept;"); 11013 verifyFormat("void operator delete(foo) noexcept;"); 11014 verifyFormat("void operator delete(int) noexcept;"); 11015 verifyFormat("void operator delete(int &) noexcept;"); 11016 verifyFormat("void operator delete(int &) volatile noexcept;"); 11017 verifyFormat("void operator delete(int &) const"); 11018 verifyFormat("void operator delete(int &) = default"); 11019 verifyFormat("void operator delete(int &) = delete"); 11020 verifyFormat("void operator delete(int &) [[noreturn]]"); 11021 verifyFormat("void operator delete(int &) throw();"); 11022 verifyFormat("void operator delete(int &) throw(int);"); 11023 verifyFormat("auto operator delete(int &) -> int;"); 11024 verifyFormat("auto operator delete(int &) override"); 11025 verifyFormat("auto operator delete(int &) final"); 11026 11027 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n" 11028 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 11029 // FIXME: The indentation here is not ideal. 11030 verifyFormat( 11031 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11032 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n" 11033 " [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];"); 11034 } 11035 11036 TEST_F(FormatTest, FormatsFunctionTypes) { 11037 verifyFormat("A<bool()> a;"); 11038 verifyFormat("A<SomeType()> a;"); 11039 verifyFormat("A<void (*)(int, std::string)> a;"); 11040 verifyFormat("A<void *(int)>;"); 11041 verifyFormat("void *(*a)(int *, SomeType *);"); 11042 verifyFormat("int (*func)(void *);"); 11043 verifyFormat("void f() { int (*func)(void *); }"); 11044 verifyFormat("template <class CallbackClass>\n" 11045 "using MyCallback = void (CallbackClass::*)(SomeObject *Data);"); 11046 11047 verifyGoogleFormat("A<void*(int*, SomeType*)>;"); 11048 verifyGoogleFormat("void* (*a)(int);"); 11049 verifyGoogleFormat( 11050 "template <class CallbackClass>\n" 11051 "using MyCallback = void (CallbackClass::*)(SomeObject* Data);"); 11052 11053 // Other constructs can look somewhat like function types: 11054 verifyFormat("A<sizeof(*x)> a;"); 11055 verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)"); 11056 verifyFormat("some_var = function(*some_pointer_var)[0];"); 11057 verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }"); 11058 verifyFormat("int x = f(&h)();"); 11059 verifyFormat("returnsFunction(¶m1, ¶m2)(param);"); 11060 verifyFormat("std::function<\n" 11061 " LooooooooooongTemplatedType<\n" 11062 " SomeType>*(\n" 11063 " LooooooooooooooooongType type)>\n" 11064 " function;", 11065 getGoogleStyleWithColumns(40)); 11066 } 11067 11068 TEST_F(FormatTest, FormatsPointersToArrayTypes) { 11069 verifyFormat("A (*foo_)[6];"); 11070 verifyFormat("vector<int> (*foo_)[6];"); 11071 } 11072 11073 TEST_F(FormatTest, BreaksLongVariableDeclarations) { 11074 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 11075 " LoooooooooooooooooooooooooooooooooooooooongVariable;"); 11076 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n" 11077 " LoooooooooooooooooooooooooooooooooooooooongVariable;"); 11078 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 11079 " *LoooooooooooooooooooooooooooooooooooooooongVariable;"); 11080 11081 // Different ways of ()-initializiation. 11082 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 11083 " LoooooooooooooooooooooooooooooooooooooooongVariable(1);"); 11084 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 11085 " LoooooooooooooooooooooooooooooooooooooooongVariable(a);"); 11086 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 11087 " LoooooooooooooooooooooooooooooooooooooooongVariable({});"); 11088 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 11089 " LoooooooooooooooooooooooooooooooooooooongVariable([A a]);"); 11090 11091 // Lambdas should not confuse the variable declaration heuristic. 11092 verifyFormat("LooooooooooooooooongType\n" 11093 " variable(nullptr, [](A *a) {});", 11094 getLLVMStyleWithColumns(40)); 11095 } 11096 11097 TEST_F(FormatTest, BreaksLongDeclarations) { 11098 verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n" 11099 " AnotherNameForTheLongType;"); 11100 verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n" 11101 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 11102 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 11103 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();"); 11104 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n" 11105 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();"); 11106 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 11107 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 11108 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n" 11109 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 11110 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n" 11111 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 11112 verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n" 11113 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 11114 verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n" 11115 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 11116 verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n" 11117 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 11118 verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n" 11119 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 11120 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 11121 "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);"); 11122 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 11123 "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}"); 11124 FormatStyle Indented = getLLVMStyle(); 11125 Indented.IndentWrappedFunctionNames = true; 11126 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 11127 " LoooooooooooooooooooooooooooooooongFunctionDeclaration();", 11128 Indented); 11129 verifyFormat( 11130 "LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 11131 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 11132 Indented); 11133 verifyFormat( 11134 "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n" 11135 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 11136 Indented); 11137 verifyFormat( 11138 "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n" 11139 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 11140 Indented); 11141 11142 // FIXME: Without the comment, this breaks after "(". 11143 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType // break\n" 11144 " (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();", 11145 getGoogleStyle()); 11146 11147 verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n" 11148 " int LoooooooooooooooooooongParam2) {}"); 11149 verifyFormat( 11150 "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n" 11151 " SourceLocation L, IdentifierIn *II,\n" 11152 " Type *T) {}"); 11153 verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n" 11154 "ReallyReaaallyLongFunctionName(\n" 11155 " const std::string &SomeParameter,\n" 11156 " const SomeType<string, SomeOtherTemplateParameter>\n" 11157 " &ReallyReallyLongParameterName,\n" 11158 " const SomeType<string, SomeOtherTemplateParameter>\n" 11159 " &AnotherLongParameterName) {}"); 11160 verifyFormat("template <typename A>\n" 11161 "SomeLoooooooooooooooooooooongType<\n" 11162 " typename some_namespace::SomeOtherType<A>::Type>\n" 11163 "Function() {}"); 11164 11165 verifyGoogleFormat( 11166 "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n" 11167 " aaaaaaaaaaaaaaaaaaaaaaa;"); 11168 verifyGoogleFormat( 11169 "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n" 11170 " SourceLocation L) {}"); 11171 verifyGoogleFormat( 11172 "some_namespace::LongReturnType\n" 11173 "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n" 11174 " int first_long_parameter, int second_parameter) {}"); 11175 11176 verifyGoogleFormat("template <typename T>\n" 11177 "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n" 11178 "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}"); 11179 verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 11180 " int aaaaaaaaaaaaaaaaaaaaaaa);"); 11181 11182 verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n" 11183 " const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11184 " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 11185 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 11186 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n" 11187 " aaaaaaaaaaaaaaaaaaaaaaaa);"); 11188 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 11189 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 11190 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n" 11191 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 11192 11193 verifyFormat("template <typename T> // Templates on own line.\n" 11194 "static int // Some comment.\n" 11195 "MyFunction(int a);", 11196 getLLVMStyle()); 11197 } 11198 11199 TEST_F(FormatTest, FormatsAccessModifiers) { 11200 FormatStyle Style = getLLVMStyle(); 11201 EXPECT_EQ(Style.EmptyLineBeforeAccessModifier, 11202 FormatStyle::ELBAMS_LogicalBlock); 11203 verifyFormat("struct foo {\n" 11204 "private:\n" 11205 " void f() {}\n" 11206 "\n" 11207 "private:\n" 11208 " int i;\n" 11209 "\n" 11210 "protected:\n" 11211 " int j;\n" 11212 "};\n", 11213 Style); 11214 verifyFormat("struct foo {\n" 11215 "private:\n" 11216 " void f() {}\n" 11217 "\n" 11218 "private:\n" 11219 " int i;\n" 11220 "\n" 11221 "protected:\n" 11222 " int j;\n" 11223 "};\n", 11224 "struct foo {\n" 11225 "private:\n" 11226 " void f() {}\n" 11227 "private:\n" 11228 " int i;\n" 11229 "protected:\n" 11230 " int j;\n" 11231 "};\n", 11232 Style); 11233 verifyFormat("struct foo { /* comment */\n" 11234 "private:\n" 11235 " int i;\n" 11236 " // comment\n" 11237 "private:\n" 11238 " int j;\n" 11239 "};\n", 11240 Style); 11241 verifyFormat("struct foo {\n" 11242 "#ifdef FOO\n" 11243 "#endif\n" 11244 "private:\n" 11245 " int i;\n" 11246 "#ifdef FOO\n" 11247 "private:\n" 11248 "#endif\n" 11249 " int j;\n" 11250 "};\n", 11251 Style); 11252 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11253 verifyFormat("struct foo {\n" 11254 "private:\n" 11255 " void f() {}\n" 11256 "private:\n" 11257 " int i;\n" 11258 "protected:\n" 11259 " int j;\n" 11260 "};\n", 11261 Style); 11262 verifyFormat("struct foo {\n" 11263 "private:\n" 11264 " void f() {}\n" 11265 "private:\n" 11266 " int i;\n" 11267 "protected:\n" 11268 " int j;\n" 11269 "};\n", 11270 "struct foo {\n" 11271 "\n" 11272 "private:\n" 11273 " void f() {}\n" 11274 "\n" 11275 "private:\n" 11276 " int i;\n" 11277 "\n" 11278 "protected:\n" 11279 " int j;\n" 11280 "};\n", 11281 Style); 11282 verifyFormat("struct foo { /* comment */\n" 11283 "private:\n" 11284 " int i;\n" 11285 " // comment\n" 11286 "private:\n" 11287 " int j;\n" 11288 "};\n", 11289 "struct foo { /* comment */\n" 11290 "\n" 11291 "private:\n" 11292 " int i;\n" 11293 " // comment\n" 11294 "\n" 11295 "private:\n" 11296 " int j;\n" 11297 "};\n", 11298 Style); 11299 verifyFormat("struct foo {\n" 11300 "#ifdef FOO\n" 11301 "#endif\n" 11302 "private:\n" 11303 " int i;\n" 11304 "#ifdef FOO\n" 11305 "private:\n" 11306 "#endif\n" 11307 " int j;\n" 11308 "};\n", 11309 "struct foo {\n" 11310 "#ifdef FOO\n" 11311 "#endif\n" 11312 "\n" 11313 "private:\n" 11314 " int i;\n" 11315 "#ifdef FOO\n" 11316 "\n" 11317 "private:\n" 11318 "#endif\n" 11319 " int j;\n" 11320 "};\n", 11321 Style); 11322 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11323 verifyFormat("struct foo {\n" 11324 "private:\n" 11325 " void f() {}\n" 11326 "\n" 11327 "private:\n" 11328 " int i;\n" 11329 "\n" 11330 "protected:\n" 11331 " int j;\n" 11332 "};\n", 11333 Style); 11334 verifyFormat("struct foo {\n" 11335 "private:\n" 11336 " void f() {}\n" 11337 "\n" 11338 "private:\n" 11339 " int i;\n" 11340 "\n" 11341 "protected:\n" 11342 " int j;\n" 11343 "};\n", 11344 "struct foo {\n" 11345 "private:\n" 11346 " void f() {}\n" 11347 "private:\n" 11348 " int i;\n" 11349 "protected:\n" 11350 " int j;\n" 11351 "};\n", 11352 Style); 11353 verifyFormat("struct foo { /* comment */\n" 11354 "private:\n" 11355 " int i;\n" 11356 " // comment\n" 11357 "\n" 11358 "private:\n" 11359 " int j;\n" 11360 "};\n", 11361 "struct foo { /* comment */\n" 11362 "private:\n" 11363 " int i;\n" 11364 " // comment\n" 11365 "\n" 11366 "private:\n" 11367 " int j;\n" 11368 "};\n", 11369 Style); 11370 verifyFormat("struct foo {\n" 11371 "#ifdef FOO\n" 11372 "#endif\n" 11373 "\n" 11374 "private:\n" 11375 " int i;\n" 11376 "#ifdef FOO\n" 11377 "\n" 11378 "private:\n" 11379 "#endif\n" 11380 " int j;\n" 11381 "};\n", 11382 "struct foo {\n" 11383 "#ifdef FOO\n" 11384 "#endif\n" 11385 "private:\n" 11386 " int i;\n" 11387 "#ifdef FOO\n" 11388 "private:\n" 11389 "#endif\n" 11390 " int j;\n" 11391 "};\n", 11392 Style); 11393 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11394 EXPECT_EQ("struct foo {\n" 11395 "\n" 11396 "private:\n" 11397 " void f() {}\n" 11398 "\n" 11399 "private:\n" 11400 " int i;\n" 11401 "\n" 11402 "protected:\n" 11403 " int j;\n" 11404 "};\n", 11405 format("struct foo {\n" 11406 "\n" 11407 "private:\n" 11408 " void f() {}\n" 11409 "\n" 11410 "private:\n" 11411 " int i;\n" 11412 "\n" 11413 "protected:\n" 11414 " int j;\n" 11415 "};\n", 11416 Style)); 11417 verifyFormat("struct foo {\n" 11418 "private:\n" 11419 " void f() {}\n" 11420 "private:\n" 11421 " int i;\n" 11422 "protected:\n" 11423 " int j;\n" 11424 "};\n", 11425 Style); 11426 EXPECT_EQ("struct foo { /* comment */\n" 11427 "\n" 11428 "private:\n" 11429 " int i;\n" 11430 " // comment\n" 11431 "\n" 11432 "private:\n" 11433 " int j;\n" 11434 "};\n", 11435 format("struct foo { /* comment */\n" 11436 "\n" 11437 "private:\n" 11438 " int i;\n" 11439 " // comment\n" 11440 "\n" 11441 "private:\n" 11442 " int j;\n" 11443 "};\n", 11444 Style)); 11445 verifyFormat("struct foo { /* comment */\n" 11446 "private:\n" 11447 " int i;\n" 11448 " // comment\n" 11449 "private:\n" 11450 " int j;\n" 11451 "};\n", 11452 Style); 11453 EXPECT_EQ("struct foo {\n" 11454 "#ifdef FOO\n" 11455 "#endif\n" 11456 "\n" 11457 "private:\n" 11458 " int i;\n" 11459 "#ifdef FOO\n" 11460 "\n" 11461 "private:\n" 11462 "#endif\n" 11463 " int j;\n" 11464 "};\n", 11465 format("struct foo {\n" 11466 "#ifdef FOO\n" 11467 "#endif\n" 11468 "\n" 11469 "private:\n" 11470 " int i;\n" 11471 "#ifdef FOO\n" 11472 "\n" 11473 "private:\n" 11474 "#endif\n" 11475 " int j;\n" 11476 "};\n", 11477 Style)); 11478 verifyFormat("struct foo {\n" 11479 "#ifdef FOO\n" 11480 "#endif\n" 11481 "private:\n" 11482 " int i;\n" 11483 "#ifdef FOO\n" 11484 "private:\n" 11485 "#endif\n" 11486 " int j;\n" 11487 "};\n", 11488 Style); 11489 11490 FormatStyle NoEmptyLines = getLLVMStyle(); 11491 NoEmptyLines.MaxEmptyLinesToKeep = 0; 11492 verifyFormat("struct foo {\n" 11493 "private:\n" 11494 " void f() {}\n" 11495 "\n" 11496 "private:\n" 11497 " int i;\n" 11498 "\n" 11499 "public:\n" 11500 "protected:\n" 11501 " int j;\n" 11502 "};\n", 11503 NoEmptyLines); 11504 11505 NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11506 verifyFormat("struct foo {\n" 11507 "private:\n" 11508 " void f() {}\n" 11509 "private:\n" 11510 " int i;\n" 11511 "public:\n" 11512 "protected:\n" 11513 " int j;\n" 11514 "};\n", 11515 NoEmptyLines); 11516 11517 NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11518 verifyFormat("struct foo {\n" 11519 "private:\n" 11520 " void f() {}\n" 11521 "\n" 11522 "private:\n" 11523 " int i;\n" 11524 "\n" 11525 "public:\n" 11526 "\n" 11527 "protected:\n" 11528 " int j;\n" 11529 "};\n", 11530 NoEmptyLines); 11531 } 11532 11533 TEST_F(FormatTest, FormatsAfterAccessModifiers) { 11534 11535 FormatStyle Style = getLLVMStyle(); 11536 EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never); 11537 verifyFormat("struct foo {\n" 11538 "private:\n" 11539 " void f() {}\n" 11540 "\n" 11541 "private:\n" 11542 " int i;\n" 11543 "\n" 11544 "protected:\n" 11545 " int j;\n" 11546 "};\n", 11547 Style); 11548 11549 // Check if lines are removed. 11550 verifyFormat("struct foo {\n" 11551 "private:\n" 11552 " void f() {}\n" 11553 "\n" 11554 "private:\n" 11555 " int i;\n" 11556 "\n" 11557 "protected:\n" 11558 " int j;\n" 11559 "};\n", 11560 "struct foo {\n" 11561 "private:\n" 11562 "\n" 11563 " void f() {}\n" 11564 "\n" 11565 "private:\n" 11566 "\n" 11567 " int i;\n" 11568 "\n" 11569 "protected:\n" 11570 "\n" 11571 " int j;\n" 11572 "};\n", 11573 Style); 11574 11575 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11576 verifyFormat("struct foo {\n" 11577 "private:\n" 11578 "\n" 11579 " void f() {}\n" 11580 "\n" 11581 "private:\n" 11582 "\n" 11583 " int i;\n" 11584 "\n" 11585 "protected:\n" 11586 "\n" 11587 " int j;\n" 11588 "};\n", 11589 Style); 11590 11591 // Check if lines are added. 11592 verifyFormat("struct foo {\n" 11593 "private:\n" 11594 "\n" 11595 " void f() {}\n" 11596 "\n" 11597 "private:\n" 11598 "\n" 11599 " int i;\n" 11600 "\n" 11601 "protected:\n" 11602 "\n" 11603 " int j;\n" 11604 "};\n", 11605 "struct foo {\n" 11606 "private:\n" 11607 " void f() {}\n" 11608 "\n" 11609 "private:\n" 11610 " int i;\n" 11611 "\n" 11612 "protected:\n" 11613 " int j;\n" 11614 "};\n", 11615 Style); 11616 11617 // Leave tests rely on the code layout, test::messUp can not be used. 11618 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11619 Style.MaxEmptyLinesToKeep = 0u; 11620 verifyFormat("struct foo {\n" 11621 "private:\n" 11622 " void f() {}\n" 11623 "\n" 11624 "private:\n" 11625 " int i;\n" 11626 "\n" 11627 "protected:\n" 11628 " int j;\n" 11629 "};\n", 11630 Style); 11631 11632 // Check if MaxEmptyLinesToKeep is respected. 11633 EXPECT_EQ("struct foo {\n" 11634 "private:\n" 11635 " void f() {}\n" 11636 "\n" 11637 "private:\n" 11638 " int i;\n" 11639 "\n" 11640 "protected:\n" 11641 " int j;\n" 11642 "};\n", 11643 format("struct foo {\n" 11644 "private:\n" 11645 "\n\n\n" 11646 " void f() {}\n" 11647 "\n" 11648 "private:\n" 11649 "\n\n\n" 11650 " int i;\n" 11651 "\n" 11652 "protected:\n" 11653 "\n\n\n" 11654 " int j;\n" 11655 "};\n", 11656 Style)); 11657 11658 Style.MaxEmptyLinesToKeep = 1u; 11659 EXPECT_EQ("struct foo {\n" 11660 "private:\n" 11661 "\n" 11662 " void f() {}\n" 11663 "\n" 11664 "private:\n" 11665 "\n" 11666 " int i;\n" 11667 "\n" 11668 "protected:\n" 11669 "\n" 11670 " int j;\n" 11671 "};\n", 11672 format("struct foo {\n" 11673 "private:\n" 11674 "\n" 11675 " void f() {}\n" 11676 "\n" 11677 "private:\n" 11678 "\n" 11679 " int i;\n" 11680 "\n" 11681 "protected:\n" 11682 "\n" 11683 " int j;\n" 11684 "};\n", 11685 Style)); 11686 // Check if no lines are kept. 11687 EXPECT_EQ("struct foo {\n" 11688 "private:\n" 11689 " void f() {}\n" 11690 "\n" 11691 "private:\n" 11692 " int i;\n" 11693 "\n" 11694 "protected:\n" 11695 " int j;\n" 11696 "};\n", 11697 format("struct foo {\n" 11698 "private:\n" 11699 " void f() {}\n" 11700 "\n" 11701 "private:\n" 11702 " int i;\n" 11703 "\n" 11704 "protected:\n" 11705 " int j;\n" 11706 "};\n", 11707 Style)); 11708 // Check if MaxEmptyLinesToKeep is respected. 11709 EXPECT_EQ("struct foo {\n" 11710 "private:\n" 11711 "\n" 11712 " void f() {}\n" 11713 "\n" 11714 "private:\n" 11715 "\n" 11716 " int i;\n" 11717 "\n" 11718 "protected:\n" 11719 "\n" 11720 " int j;\n" 11721 "};\n", 11722 format("struct foo {\n" 11723 "private:\n" 11724 "\n\n\n" 11725 " void f() {}\n" 11726 "\n" 11727 "private:\n" 11728 "\n\n\n" 11729 " int i;\n" 11730 "\n" 11731 "protected:\n" 11732 "\n\n\n" 11733 " int j;\n" 11734 "};\n", 11735 Style)); 11736 11737 Style.MaxEmptyLinesToKeep = 10u; 11738 EXPECT_EQ("struct foo {\n" 11739 "private:\n" 11740 "\n\n\n" 11741 " void f() {}\n" 11742 "\n" 11743 "private:\n" 11744 "\n\n\n" 11745 " int i;\n" 11746 "\n" 11747 "protected:\n" 11748 "\n\n\n" 11749 " int j;\n" 11750 "};\n", 11751 format("struct foo {\n" 11752 "private:\n" 11753 "\n\n\n" 11754 " void f() {}\n" 11755 "\n" 11756 "private:\n" 11757 "\n\n\n" 11758 " int i;\n" 11759 "\n" 11760 "protected:\n" 11761 "\n\n\n" 11762 " int j;\n" 11763 "};\n", 11764 Style)); 11765 11766 // Test with comments. 11767 Style = getLLVMStyle(); 11768 verifyFormat("struct foo {\n" 11769 "private:\n" 11770 " // comment\n" 11771 " void f() {}\n" 11772 "\n" 11773 "private: /* comment */\n" 11774 " int i;\n" 11775 "};\n", 11776 Style); 11777 verifyFormat("struct foo {\n" 11778 "private:\n" 11779 " // comment\n" 11780 " void f() {}\n" 11781 "\n" 11782 "private: /* comment */\n" 11783 " int i;\n" 11784 "};\n", 11785 "struct foo {\n" 11786 "private:\n" 11787 "\n" 11788 " // comment\n" 11789 " void f() {}\n" 11790 "\n" 11791 "private: /* comment */\n" 11792 "\n" 11793 " int i;\n" 11794 "};\n", 11795 Style); 11796 11797 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11798 verifyFormat("struct foo {\n" 11799 "private:\n" 11800 "\n" 11801 " // comment\n" 11802 " void f() {}\n" 11803 "\n" 11804 "private: /* comment */\n" 11805 "\n" 11806 " int i;\n" 11807 "};\n", 11808 "struct foo {\n" 11809 "private:\n" 11810 " // comment\n" 11811 " void f() {}\n" 11812 "\n" 11813 "private: /* comment */\n" 11814 " int i;\n" 11815 "};\n", 11816 Style); 11817 verifyFormat("struct foo {\n" 11818 "private:\n" 11819 "\n" 11820 " // comment\n" 11821 " void f() {}\n" 11822 "\n" 11823 "private: /* comment */\n" 11824 "\n" 11825 " int i;\n" 11826 "};\n", 11827 Style); 11828 11829 // Test with preprocessor defines. 11830 Style = getLLVMStyle(); 11831 verifyFormat("struct foo {\n" 11832 "private:\n" 11833 "#ifdef FOO\n" 11834 "#endif\n" 11835 " void f() {}\n" 11836 "};\n", 11837 Style); 11838 verifyFormat("struct foo {\n" 11839 "private:\n" 11840 "#ifdef FOO\n" 11841 "#endif\n" 11842 " void f() {}\n" 11843 "};\n", 11844 "struct foo {\n" 11845 "private:\n" 11846 "\n" 11847 "#ifdef FOO\n" 11848 "#endif\n" 11849 " void f() {}\n" 11850 "};\n", 11851 Style); 11852 11853 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11854 verifyFormat("struct foo {\n" 11855 "private:\n" 11856 "\n" 11857 "#ifdef FOO\n" 11858 "#endif\n" 11859 " void f() {}\n" 11860 "};\n", 11861 "struct foo {\n" 11862 "private:\n" 11863 "#ifdef FOO\n" 11864 "#endif\n" 11865 " void f() {}\n" 11866 "};\n", 11867 Style); 11868 verifyFormat("struct foo {\n" 11869 "private:\n" 11870 "\n" 11871 "#ifdef FOO\n" 11872 "#endif\n" 11873 " void f() {}\n" 11874 "};\n", 11875 Style); 11876 } 11877 11878 TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) { 11879 // Combined tests of EmptyLineAfterAccessModifier and 11880 // EmptyLineBeforeAccessModifier. 11881 FormatStyle Style = getLLVMStyle(); 11882 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11883 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11884 verifyFormat("struct foo {\n" 11885 "private:\n" 11886 "\n" 11887 "protected:\n" 11888 "};\n", 11889 Style); 11890 11891 Style.MaxEmptyLinesToKeep = 10u; 11892 // Both remove all new lines. 11893 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11894 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11895 verifyFormat("struct foo {\n" 11896 "private:\n" 11897 "protected:\n" 11898 "};\n", 11899 "struct foo {\n" 11900 "private:\n" 11901 "\n\n\n" 11902 "protected:\n" 11903 "};\n", 11904 Style); 11905 11906 // Leave tests rely on the code layout, test::messUp can not be used. 11907 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11908 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11909 Style.MaxEmptyLinesToKeep = 10u; 11910 EXPECT_EQ("struct foo {\n" 11911 "private:\n" 11912 "\n\n\n" 11913 "protected:\n" 11914 "};\n", 11915 format("struct foo {\n" 11916 "private:\n" 11917 "\n\n\n" 11918 "protected:\n" 11919 "};\n", 11920 Style)); 11921 Style.MaxEmptyLinesToKeep = 3u; 11922 EXPECT_EQ("struct foo {\n" 11923 "private:\n" 11924 "\n\n\n" 11925 "protected:\n" 11926 "};\n", 11927 format("struct foo {\n" 11928 "private:\n" 11929 "\n\n\n" 11930 "protected:\n" 11931 "};\n", 11932 Style)); 11933 Style.MaxEmptyLinesToKeep = 1u; 11934 EXPECT_EQ("struct foo {\n" 11935 "private:\n" 11936 "\n\n\n" 11937 "protected:\n" 11938 "};\n", 11939 format("struct foo {\n" 11940 "private:\n" 11941 "\n\n\n" 11942 "protected:\n" 11943 "};\n", 11944 Style)); // Based on new lines in original document and not 11945 // on the setting. 11946 11947 Style.MaxEmptyLinesToKeep = 10u; 11948 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11949 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11950 // Newlines are kept if they are greater than zero, 11951 // test::messUp removes all new lines which changes the logic 11952 EXPECT_EQ("struct foo {\n" 11953 "private:\n" 11954 "\n\n\n" 11955 "protected:\n" 11956 "};\n", 11957 format("struct foo {\n" 11958 "private:\n" 11959 "\n\n\n" 11960 "protected:\n" 11961 "};\n", 11962 Style)); 11963 11964 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11965 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11966 // test::messUp removes all new lines which changes the logic 11967 EXPECT_EQ("struct foo {\n" 11968 "private:\n" 11969 "\n\n\n" 11970 "protected:\n" 11971 "};\n", 11972 format("struct foo {\n" 11973 "private:\n" 11974 "\n\n\n" 11975 "protected:\n" 11976 "};\n", 11977 Style)); 11978 11979 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11980 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11981 EXPECT_EQ("struct foo {\n" 11982 "private:\n" 11983 "\n\n\n" 11984 "protected:\n" 11985 "};\n", 11986 format("struct foo {\n" 11987 "private:\n" 11988 "\n\n\n" 11989 "protected:\n" 11990 "};\n", 11991 Style)); // test::messUp removes all new lines which changes 11992 // the logic. 11993 11994 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11995 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11996 verifyFormat("struct foo {\n" 11997 "private:\n" 11998 "protected:\n" 11999 "};\n", 12000 "struct foo {\n" 12001 "private:\n" 12002 "\n\n\n" 12003 "protected:\n" 12004 "};\n", 12005 Style); 12006 12007 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 12008 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 12009 EXPECT_EQ("struct foo {\n" 12010 "private:\n" 12011 "\n\n\n" 12012 "protected:\n" 12013 "};\n", 12014 format("struct foo {\n" 12015 "private:\n" 12016 "\n\n\n" 12017 "protected:\n" 12018 "};\n", 12019 Style)); // test::messUp removes all new lines which changes 12020 // the logic. 12021 12022 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 12023 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 12024 verifyFormat("struct foo {\n" 12025 "private:\n" 12026 "protected:\n" 12027 "};\n", 12028 "struct foo {\n" 12029 "private:\n" 12030 "\n\n\n" 12031 "protected:\n" 12032 "};\n", 12033 Style); 12034 12035 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 12036 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 12037 verifyFormat("struct foo {\n" 12038 "private:\n" 12039 "protected:\n" 12040 "};\n", 12041 "struct foo {\n" 12042 "private:\n" 12043 "\n\n\n" 12044 "protected:\n" 12045 "};\n", 12046 Style); 12047 12048 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 12049 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 12050 verifyFormat("struct foo {\n" 12051 "private:\n" 12052 "protected:\n" 12053 "};\n", 12054 "struct foo {\n" 12055 "private:\n" 12056 "\n\n\n" 12057 "protected:\n" 12058 "};\n", 12059 Style); 12060 12061 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 12062 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 12063 verifyFormat("struct foo {\n" 12064 "private:\n" 12065 "protected:\n" 12066 "};\n", 12067 "struct foo {\n" 12068 "private:\n" 12069 "\n\n\n" 12070 "protected:\n" 12071 "};\n", 12072 Style); 12073 } 12074 12075 TEST_F(FormatTest, FormatsArrays) { 12076 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n" 12077 " [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;"); 12078 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n" 12079 " [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;"); 12080 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n" 12081 " aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}"); 12082 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 12083 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;"); 12084 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 12085 " [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;"); 12086 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 12087 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n" 12088 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;"); 12089 verifyFormat( 12090 "llvm::outs() << \"aaaaaaaaaaaa: \"\n" 12091 " << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n" 12092 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];"); 12093 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n" 12094 " .aaaaaaaaaaaaaaaaaaaaaa();"); 12095 12096 verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n" 12097 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];"); 12098 verifyFormat( 12099 "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n" 12100 " .aaaaaaa[0]\n" 12101 " .aaaaaaaaaaaaaaaaaaaaaa();"); 12102 verifyFormat("a[::b::c];"); 12103 12104 verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10)); 12105 12106 FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0); 12107 verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit); 12108 } 12109 12110 TEST_F(FormatTest, LineStartsWithSpecialCharacter) { 12111 verifyFormat("(a)->b();"); 12112 verifyFormat("--a;"); 12113 } 12114 12115 TEST_F(FormatTest, HandlesIncludeDirectives) { 12116 verifyFormat("#include <string>\n" 12117 "#include <a/b/c.h>\n" 12118 "#include \"a/b/string\"\n" 12119 "#include \"string.h\"\n" 12120 "#include \"string.h\"\n" 12121 "#include <a-a>\n" 12122 "#include < path with space >\n" 12123 "#include_next <test.h>" 12124 "#include \"abc.h\" // this is included for ABC\n" 12125 "#include \"some long include\" // with a comment\n" 12126 "#include \"some very long include path\"\n" 12127 "#include <some/very/long/include/path>\n", 12128 getLLVMStyleWithColumns(35)); 12129 EXPECT_EQ("#include \"a.h\"", format("#include \"a.h\"")); 12130 EXPECT_EQ("#include <a>", format("#include<a>")); 12131 12132 verifyFormat("#import <string>"); 12133 verifyFormat("#import <a/b/c.h>"); 12134 verifyFormat("#import \"a/b/string\""); 12135 verifyFormat("#import \"string.h\""); 12136 verifyFormat("#import \"string.h\""); 12137 verifyFormat("#if __has_include(<strstream>)\n" 12138 "#include <strstream>\n" 12139 "#endif"); 12140 12141 verifyFormat("#define MY_IMPORT <a/b>"); 12142 12143 verifyFormat("#if __has_include(<a/b>)"); 12144 verifyFormat("#if __has_include_next(<a/b>)"); 12145 verifyFormat("#define F __has_include(<a/b>)"); 12146 verifyFormat("#define F __has_include_next(<a/b>)"); 12147 12148 // Protocol buffer definition or missing "#". 12149 verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";", 12150 getLLVMStyleWithColumns(30)); 12151 12152 FormatStyle Style = getLLVMStyle(); 12153 Style.AlwaysBreakBeforeMultilineStrings = true; 12154 Style.ColumnLimit = 0; 12155 verifyFormat("#import \"abc.h\"", Style); 12156 12157 // But 'import' might also be a regular C++ namespace. 12158 verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12159 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 12160 } 12161 12162 //===----------------------------------------------------------------------===// 12163 // Error recovery tests. 12164 //===----------------------------------------------------------------------===// 12165 12166 TEST_F(FormatTest, IncompleteParameterLists) { 12167 FormatStyle NoBinPacking = getLLVMStyle(); 12168 NoBinPacking.BinPackParameters = false; 12169 verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n" 12170 " double *min_x,\n" 12171 " double *max_x,\n" 12172 " double *min_y,\n" 12173 " double *max_y,\n" 12174 " double *min_z,\n" 12175 " double *max_z, ) {}", 12176 NoBinPacking); 12177 } 12178 12179 TEST_F(FormatTest, IncorrectCodeTrailingStuff) { 12180 verifyFormat("void f() { return; }\n42"); 12181 verifyFormat("void f() {\n" 12182 " if (0)\n" 12183 " return;\n" 12184 "}\n" 12185 "42"); 12186 verifyFormat("void f() { return }\n42"); 12187 verifyFormat("void f() {\n" 12188 " if (0)\n" 12189 " return\n" 12190 "}\n" 12191 "42"); 12192 } 12193 12194 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) { 12195 EXPECT_EQ("void f() { return }", format("void f ( ) { return }")); 12196 EXPECT_EQ("void f() {\n" 12197 " if (a)\n" 12198 " return\n" 12199 "}", 12200 format("void f ( ) { if ( a ) return }")); 12201 EXPECT_EQ("namespace N {\n" 12202 "void f()\n" 12203 "}", 12204 format("namespace N { void f() }")); 12205 EXPECT_EQ("namespace N {\n" 12206 "void f() {}\n" 12207 "void g()\n" 12208 "} // namespace N", 12209 format("namespace N { void f( ) { } void g( ) }")); 12210 } 12211 12212 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) { 12213 verifyFormat("int aaaaaaaa =\n" 12214 " // Overlylongcomment\n" 12215 " b;", 12216 getLLVMStyleWithColumns(20)); 12217 verifyFormat("function(\n" 12218 " ShortArgument,\n" 12219 " LoooooooooooongArgument);\n", 12220 getLLVMStyleWithColumns(20)); 12221 } 12222 12223 TEST_F(FormatTest, IncorrectAccessSpecifier) { 12224 verifyFormat("public:"); 12225 verifyFormat("class A {\n" 12226 "public\n" 12227 " void f() {}\n" 12228 "};"); 12229 verifyFormat("public\n" 12230 "int qwerty;"); 12231 verifyFormat("public\n" 12232 "B {}"); 12233 verifyFormat("public\n" 12234 "{}"); 12235 verifyFormat("public\n" 12236 "B { int x; }"); 12237 } 12238 12239 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) { 12240 verifyFormat("{"); 12241 verifyFormat("#})"); 12242 verifyNoCrash("(/**/[:!] ?[)."); 12243 } 12244 12245 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) { 12246 // Found by oss-fuzz: 12247 // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212 12248 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp); 12249 Style.ColumnLimit = 60; 12250 verifyNoCrash( 12251 "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20" 12252 "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20" 12253 "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a", 12254 Style); 12255 } 12256 12257 TEST_F(FormatTest, IncorrectCodeDoNoWhile) { 12258 verifyFormat("do {\n}"); 12259 verifyFormat("do {\n}\n" 12260 "f();"); 12261 verifyFormat("do {\n}\n" 12262 "wheeee(fun);"); 12263 verifyFormat("do {\n" 12264 " f();\n" 12265 "}"); 12266 } 12267 12268 TEST_F(FormatTest, IncorrectCodeMissingParens) { 12269 verifyFormat("if {\n foo;\n foo();\n}"); 12270 verifyFormat("switch {\n foo;\n foo();\n}"); 12271 verifyIncompleteFormat("for {\n foo;\n foo();\n}"); 12272 verifyIncompleteFormat("ERROR: for target;"); 12273 verifyFormat("while {\n foo;\n foo();\n}"); 12274 verifyFormat("do {\n foo;\n foo();\n} while;"); 12275 } 12276 12277 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) { 12278 verifyIncompleteFormat("namespace {\n" 12279 "class Foo { Foo (\n" 12280 "};\n" 12281 "} // namespace"); 12282 } 12283 12284 TEST_F(FormatTest, IncorrectCodeErrorDetection) { 12285 EXPECT_EQ("{\n {}\n", format("{\n{\n}\n")); 12286 EXPECT_EQ("{\n {}\n", format("{\n {\n}\n")); 12287 EXPECT_EQ("{\n {}\n", format("{\n {\n }\n")); 12288 EXPECT_EQ("{\n {}\n}\n}\n", format("{\n {\n }\n }\n}\n")); 12289 12290 EXPECT_EQ("{\n" 12291 " {\n" 12292 " breakme(\n" 12293 " qwe);\n" 12294 " }\n", 12295 format("{\n" 12296 " {\n" 12297 " breakme(qwe);\n" 12298 "}\n", 12299 getLLVMStyleWithColumns(10))); 12300 } 12301 12302 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) { 12303 verifyFormat("int x = {\n" 12304 " avariable,\n" 12305 " b(alongervariable)};", 12306 getLLVMStyleWithColumns(25)); 12307 } 12308 12309 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) { 12310 verifyFormat("return (a)(b){1, 2, 3};"); 12311 } 12312 12313 TEST_F(FormatTest, LayoutCxx11BraceInitializers) { 12314 verifyFormat("vector<int> x{1, 2, 3, 4};"); 12315 verifyFormat("vector<int> x{\n" 12316 " 1,\n" 12317 " 2,\n" 12318 " 3,\n" 12319 " 4,\n" 12320 "};"); 12321 verifyFormat("vector<T> x{{}, {}, {}, {}};"); 12322 verifyFormat("f({1, 2});"); 12323 verifyFormat("auto v = Foo{-1};"); 12324 verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});"); 12325 verifyFormat("Class::Class : member{1, 2, 3} {}"); 12326 verifyFormat("new vector<int>{1, 2, 3};"); 12327 verifyFormat("new int[3]{1, 2, 3};"); 12328 verifyFormat("new int{1};"); 12329 verifyFormat("return {arg1, arg2};"); 12330 verifyFormat("return {arg1, SomeType{parameter}};"); 12331 verifyFormat("int count = set<int>{f(), g(), h()}.size();"); 12332 verifyFormat("new T{arg1, arg2};"); 12333 verifyFormat("f(MyMap[{composite, key}]);"); 12334 verifyFormat("class Class {\n" 12335 " T member = {arg1, arg2};\n" 12336 "};"); 12337 verifyFormat("vector<int> foo = {::SomeGlobalFunction()};"); 12338 verifyFormat("const struct A a = {.a = 1, .b = 2};"); 12339 verifyFormat("const struct A a = {[0] = 1, [1] = 2};"); 12340 verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");"); 12341 verifyFormat("int a = std::is_integral<int>{} + 0;"); 12342 12343 verifyFormat("int foo(int i) { return fo1{}(i); }"); 12344 verifyFormat("int foo(int i) { return fo1{}(i); }"); 12345 verifyFormat("auto i = decltype(x){};"); 12346 verifyFormat("auto i = typeof(x){};"); 12347 verifyFormat("auto i = _Atomic(x){};"); 12348 verifyFormat("std::vector<int> v = {1, 0 /* comment */};"); 12349 verifyFormat("Node n{1, Node{1000}, //\n" 12350 " 2};"); 12351 verifyFormat("Aaaa aaaaaaa{\n" 12352 " {\n" 12353 " aaaa,\n" 12354 " },\n" 12355 "};"); 12356 verifyFormat("class C : public D {\n" 12357 " SomeClass SC{2};\n" 12358 "};"); 12359 verifyFormat("class C : public A {\n" 12360 " class D : public B {\n" 12361 " void f() { int i{2}; }\n" 12362 " };\n" 12363 "};"); 12364 verifyFormat("#define A {a, a},"); 12365 // Don't confuse braced list initializers with compound statements. 12366 verifyFormat( 12367 "class A {\n" 12368 " A() : a{} {}\n" 12369 " A(int b) : b(b) {}\n" 12370 " A(int a, int b) : a(a), bs{{bs...}} { f(); }\n" 12371 " int a, b;\n" 12372 " explicit Expr(const Scalar<Result> &x) : u{Constant<Result>{x}} {}\n" 12373 " explicit Expr(Scalar<Result> &&x) : u{Constant<Result>{std::move(x)}} " 12374 "{}\n" 12375 "};"); 12376 12377 // Avoid breaking between equal sign and opening brace 12378 FormatStyle AvoidBreakingFirstArgument = getLLVMStyle(); 12379 AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200; 12380 verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n" 12381 " {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n" 12382 " {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n" 12383 " {\"ccccccccccccccccccccc\", 2}};", 12384 AvoidBreakingFirstArgument); 12385 12386 // Binpacking only if there is no trailing comma 12387 verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n" 12388 " cccccccccc, dddddddddd};", 12389 getLLVMStyleWithColumns(50)); 12390 verifyFormat("const Aaaaaa aaaaa = {\n" 12391 " aaaaaaaaaaa,\n" 12392 " bbbbbbbbbbb,\n" 12393 " ccccccccccc,\n" 12394 " ddddddddddd,\n" 12395 "};", 12396 getLLVMStyleWithColumns(50)); 12397 12398 // Cases where distinguising braced lists and blocks is hard. 12399 verifyFormat("vector<int> v{12} GUARDED_BY(mutex);"); 12400 verifyFormat("void f() {\n" 12401 " return; // comment\n" 12402 "}\n" 12403 "SomeType t;"); 12404 verifyFormat("void f() {\n" 12405 " if (a) {\n" 12406 " f();\n" 12407 " }\n" 12408 "}\n" 12409 "SomeType t;"); 12410 12411 // In combination with BinPackArguments = false. 12412 FormatStyle NoBinPacking = getLLVMStyle(); 12413 NoBinPacking.BinPackArguments = false; 12414 verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n" 12415 " bbbbb,\n" 12416 " ccccc,\n" 12417 " ddddd,\n" 12418 " eeeee,\n" 12419 " ffffff,\n" 12420 " ggggg,\n" 12421 " hhhhhh,\n" 12422 " iiiiii,\n" 12423 " jjjjjj,\n" 12424 " kkkkkk};", 12425 NoBinPacking); 12426 verifyFormat("const Aaaaaa aaaaa = {\n" 12427 " aaaaa,\n" 12428 " bbbbb,\n" 12429 " ccccc,\n" 12430 " ddddd,\n" 12431 " eeeee,\n" 12432 " ffffff,\n" 12433 " ggggg,\n" 12434 " hhhhhh,\n" 12435 " iiiiii,\n" 12436 " jjjjjj,\n" 12437 " kkkkkk,\n" 12438 "};", 12439 NoBinPacking); 12440 verifyFormat( 12441 "const Aaaaaa aaaaa = {\n" 12442 " aaaaa, bbbbb, ccccc, ddddd, eeeee, ffffff, ggggg, hhhhhh,\n" 12443 " iiiiii, jjjjjj, kkkkkk, aaaaa, bbbbb, ccccc, ddddd, eeeee,\n" 12444 " ffffff, ggggg, hhhhhh, iiiiii, jjjjjj, kkkkkk,\n" 12445 "};", 12446 NoBinPacking); 12447 12448 NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 12449 EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n" 12450 " CDDDP83848_BMCR_REGISTER,\n" 12451 " CDDDP83848_BMSR_REGISTER,\n" 12452 " CDDDP83848_RBR_REGISTER};", 12453 format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n" 12454 " CDDDP83848_BMSR_REGISTER,\n" 12455 " CDDDP83848_RBR_REGISTER};", 12456 NoBinPacking)); 12457 12458 // FIXME: The alignment of these trailing comments might be bad. Then again, 12459 // this might be utterly useless in real code. 12460 verifyFormat("Constructor::Constructor()\n" 12461 " : some_value{ //\n" 12462 " aaaaaaa, //\n" 12463 " bbbbbbb} {}"); 12464 12465 // In braced lists, the first comment is always assumed to belong to the 12466 // first element. Thus, it can be moved to the next or previous line as 12467 // appropriate. 12468 EXPECT_EQ("function({// First element:\n" 12469 " 1,\n" 12470 " // Second element:\n" 12471 " 2});", 12472 format("function({\n" 12473 " // First element:\n" 12474 " 1,\n" 12475 " // Second element:\n" 12476 " 2});")); 12477 EXPECT_EQ("std::vector<int> MyNumbers{\n" 12478 " // First element:\n" 12479 " 1,\n" 12480 " // Second element:\n" 12481 " 2};", 12482 format("std::vector<int> MyNumbers{// First element:\n" 12483 " 1,\n" 12484 " // Second element:\n" 12485 " 2};", 12486 getLLVMStyleWithColumns(30))); 12487 // A trailing comma should still lead to an enforced line break and no 12488 // binpacking. 12489 EXPECT_EQ("vector<int> SomeVector = {\n" 12490 " // aaa\n" 12491 " 1,\n" 12492 " 2,\n" 12493 "};", 12494 format("vector<int> SomeVector = { // aaa\n" 12495 " 1, 2, };")); 12496 12497 // C++11 brace initializer list l-braces should not be treated any differently 12498 // when breaking before lambda bodies is enabled 12499 FormatStyle BreakBeforeLambdaBody = getLLVMStyle(); 12500 BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 12501 BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 12502 BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true; 12503 verifyFormat( 12504 "std::runtime_error{\n" 12505 " \"Long string which will force a break onto the next line...\"};", 12506 BreakBeforeLambdaBody); 12507 12508 FormatStyle ExtraSpaces = getLLVMStyle(); 12509 ExtraSpaces.Cpp11BracedListStyle = false; 12510 ExtraSpaces.ColumnLimit = 75; 12511 verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces); 12512 verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces); 12513 verifyFormat("f({ 1, 2 });", ExtraSpaces); 12514 verifyFormat("auto v = Foo{ 1 };", ExtraSpaces); 12515 verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces); 12516 verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces); 12517 verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces); 12518 verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces); 12519 verifyFormat("return { arg1, arg2 };", ExtraSpaces); 12520 verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces); 12521 verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces); 12522 verifyFormat("new T{ arg1, arg2 };", ExtraSpaces); 12523 verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces); 12524 verifyFormat("class Class {\n" 12525 " T member = { arg1, arg2 };\n" 12526 "};", 12527 ExtraSpaces); 12528 verifyFormat( 12529 "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12530 " aaaaaaaaaaaaaaaaaaaa, aaaaa }\n" 12531 " : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 12532 " bbbbbbbbbbbbbbbbbbbb, bbbbb };", 12533 ExtraSpaces); 12534 verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces); 12535 verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });", 12536 ExtraSpaces); 12537 verifyFormat( 12538 "someFunction(OtherParam,\n" 12539 " BracedList{ // comment 1 (Forcing interesting break)\n" 12540 " param1, param2,\n" 12541 " // comment 2\n" 12542 " param3, param4 });", 12543 ExtraSpaces); 12544 verifyFormat( 12545 "std::this_thread::sleep_for(\n" 12546 " std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);", 12547 ExtraSpaces); 12548 verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n" 12549 " aaaaaaa,\n" 12550 " aaaaaaaaaa,\n" 12551 " aaaaa,\n" 12552 " aaaaaaaaaaaaaaa,\n" 12553 " aaa,\n" 12554 " aaaaaaaaaa,\n" 12555 " a,\n" 12556 " aaaaaaaaaaaaaaaaaaaaa,\n" 12557 " aaaaaaaaaaaa,\n" 12558 " aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n" 12559 " aaaaaaa,\n" 12560 " a};"); 12561 verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces); 12562 verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces); 12563 verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces); 12564 12565 // Avoid breaking between initializer/equal sign and opening brace 12566 ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200; 12567 verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n" 12568 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n" 12569 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n" 12570 " { \"ccccccccccccccccccccc\", 2 }\n" 12571 "};", 12572 ExtraSpaces); 12573 verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n" 12574 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n" 12575 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n" 12576 " { \"ccccccccccccccccccccc\", 2 }\n" 12577 "};", 12578 ExtraSpaces); 12579 12580 FormatStyle SpaceBeforeBrace = getLLVMStyle(); 12581 SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true; 12582 verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace); 12583 verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace); 12584 12585 FormatStyle SpaceBetweenBraces = getLLVMStyle(); 12586 SpaceBetweenBraces.SpacesInAngles = FormatStyle::SIAS_Always; 12587 SpaceBetweenBraces.SpacesInParentheses = true; 12588 SpaceBetweenBraces.SpacesInSquareBrackets = true; 12589 verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces); 12590 verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces); 12591 verifyFormat("vector< int > x{ // comment 1\n" 12592 " 1, 2, 3, 4 };", 12593 SpaceBetweenBraces); 12594 SpaceBetweenBraces.ColumnLimit = 20; 12595 EXPECT_EQ("vector< int > x{\n" 12596 " 1, 2, 3, 4 };", 12597 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces)); 12598 SpaceBetweenBraces.ColumnLimit = 24; 12599 EXPECT_EQ("vector< int > x{ 1, 2,\n" 12600 " 3, 4 };", 12601 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces)); 12602 EXPECT_EQ("vector< int > x{\n" 12603 " 1,\n" 12604 " 2,\n" 12605 " 3,\n" 12606 " 4,\n" 12607 "};", 12608 format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces)); 12609 verifyFormat("vector< int > x{};", SpaceBetweenBraces); 12610 SpaceBetweenBraces.SpaceInEmptyParentheses = true; 12611 verifyFormat("vector< int > x{ };", SpaceBetweenBraces); 12612 } 12613 12614 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) { 12615 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12616 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12617 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12618 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12619 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12620 " 1, 22, 333, 4444, 55555, 666666, 7777777};"); 12621 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n" 12622 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12623 " 1, 22, 333, 4444, 55555, //\n" 12624 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12625 " 1, 22, 333, 4444, 55555, 666666, 7777777};"); 12626 verifyFormat( 12627 "vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12628 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12629 " 1, 22, 333, 4444, 55555, 666666, // comment\n" 12630 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12631 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12632 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12633 " 7777777};"); 12634 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12635 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12636 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12637 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12638 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12639 " // Separating comment.\n" 12640 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12641 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12642 " // Leading comment\n" 12643 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12644 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12645 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12646 " 1, 1, 1, 1};", 12647 getLLVMStyleWithColumns(39)); 12648 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12649 " 1, 1, 1, 1};", 12650 getLLVMStyleWithColumns(38)); 12651 verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n" 12652 " 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};", 12653 getLLVMStyleWithColumns(43)); 12654 verifyFormat( 12655 "static unsigned SomeValues[10][3] = {\n" 12656 " {1, 4, 0}, {4, 9, 0}, {4, 5, 9}, {8, 5, 4}, {1, 8, 4},\n" 12657 " {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};"); 12658 verifyFormat("static auto fields = new vector<string>{\n" 12659 " \"aaaaaaaaaaaaa\",\n" 12660 " \"aaaaaaaaaaaaa\",\n" 12661 " \"aaaaaaaaaaaa\",\n" 12662 " \"aaaaaaaaaaaaaa\",\n" 12663 " \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n" 12664 " \"aaaaaaaaaaaa\",\n" 12665 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n" 12666 "};"); 12667 verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};"); 12668 verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n" 12669 " 2, bbbbbbbbbbbbbbbbbbbbbb,\n" 12670 " 3, cccccccccccccccccccccc};", 12671 getLLVMStyleWithColumns(60)); 12672 12673 // Trailing commas. 12674 verifyFormat("vector<int> x = {\n" 12675 " 1, 1, 1, 1, 1, 1, 1, 1,\n" 12676 "};", 12677 getLLVMStyleWithColumns(39)); 12678 verifyFormat("vector<int> x = {\n" 12679 " 1, 1, 1, 1, 1, 1, 1, 1, //\n" 12680 "};", 12681 getLLVMStyleWithColumns(39)); 12682 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12683 " 1, 1, 1, 1,\n" 12684 " /**/ /**/};", 12685 getLLVMStyleWithColumns(39)); 12686 12687 // Trailing comment in the first line. 12688 verifyFormat("vector<int> iiiiiiiiiiiiiii = { //\n" 12689 " 1111111111, 2222222222, 33333333333, 4444444444, //\n" 12690 " 111111111, 222222222, 3333333333, 444444444, //\n" 12691 " 11111111, 22222222, 333333333, 44444444};"); 12692 // Trailing comment in the last line. 12693 verifyFormat("int aaaaa[] = {\n" 12694 " 1, 2, 3, // comment\n" 12695 " 4, 5, 6 // comment\n" 12696 "};"); 12697 12698 // With nested lists, we should either format one item per line or all nested 12699 // lists one on line. 12700 // FIXME: For some nested lists, we can do better. 12701 verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n" 12702 " {aaaaaaaaaaaaaaaaaaa},\n" 12703 " {aaaaaaaaaaaaaaaaaaaaa},\n" 12704 " {aaaaaaaaaaaaaaaaa}};", 12705 getLLVMStyleWithColumns(60)); 12706 verifyFormat( 12707 "SomeStruct my_struct_array = {\n" 12708 " {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n" 12709 " aaaaaaaaaaaaa, aaaaaaa, aaa},\n" 12710 " {aaa, aaa},\n" 12711 " {aaa, aaa},\n" 12712 " {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n" 12713 " {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n" 12714 " aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};"); 12715 12716 // No column layout should be used here. 12717 verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n" 12718 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};"); 12719 12720 verifyNoCrash("a<,"); 12721 12722 // No braced initializer here. 12723 verifyFormat("void f() {\n" 12724 " struct Dummy {};\n" 12725 " f(v);\n" 12726 "}"); 12727 12728 // Long lists should be formatted in columns even if they are nested. 12729 verifyFormat( 12730 "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12731 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12732 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12733 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12734 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12735 " 1, 22, 333, 4444, 55555, 666666, 7777777});"); 12736 12737 // Allow "single-column" layout even if that violates the column limit. There 12738 // isn't going to be a better way. 12739 verifyFormat("std::vector<int> a = {\n" 12740 " aaaaaaaa,\n" 12741 " aaaaaaaa,\n" 12742 " aaaaaaaa,\n" 12743 " aaaaaaaa,\n" 12744 " aaaaaaaaaa,\n" 12745 " aaaaaaaa,\n" 12746 " aaaaaaaaaaaaaaaaaaaaaaaaaaa};", 12747 getLLVMStyleWithColumns(30)); 12748 verifyFormat("vector<int> aaaa = {\n" 12749 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12750 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12751 " aaaaaa.aaaaaaa,\n" 12752 " aaaaaa.aaaaaaa,\n" 12753 " aaaaaa.aaaaaaa,\n" 12754 " aaaaaa.aaaaaaa,\n" 12755 "};"); 12756 12757 // Don't create hanging lists. 12758 verifyFormat("someFunction(Param, {List1, List2,\n" 12759 " List3});", 12760 getLLVMStyleWithColumns(35)); 12761 verifyFormat("someFunction(Param, Param,\n" 12762 " {List1, List2,\n" 12763 " List3});", 12764 getLLVMStyleWithColumns(35)); 12765 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n" 12766 " aaaaaaaaaaaaaaaaaaaaaaa);"); 12767 } 12768 12769 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) { 12770 FormatStyle DoNotMerge = getLLVMStyle(); 12771 DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12772 12773 verifyFormat("void f() { return 42; }"); 12774 verifyFormat("void f() {\n" 12775 " return 42;\n" 12776 "}", 12777 DoNotMerge); 12778 verifyFormat("void f() {\n" 12779 " // Comment\n" 12780 "}"); 12781 verifyFormat("{\n" 12782 "#error {\n" 12783 " int a;\n" 12784 "}"); 12785 verifyFormat("{\n" 12786 " int a;\n" 12787 "#error {\n" 12788 "}"); 12789 verifyFormat("void f() {} // comment"); 12790 verifyFormat("void f() { int a; } // comment"); 12791 verifyFormat("void f() {\n" 12792 "} // comment", 12793 DoNotMerge); 12794 verifyFormat("void f() {\n" 12795 " int a;\n" 12796 "} // comment", 12797 DoNotMerge); 12798 verifyFormat("void f() {\n" 12799 "} // comment", 12800 getLLVMStyleWithColumns(15)); 12801 12802 verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23)); 12803 verifyFormat("void f() {\n return 42;\n}", getLLVMStyleWithColumns(22)); 12804 12805 verifyFormat("void f() {}", getLLVMStyleWithColumns(11)); 12806 verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10)); 12807 verifyFormat("class C {\n" 12808 " C()\n" 12809 " : iiiiiiii(nullptr),\n" 12810 " kkkkkkk(nullptr),\n" 12811 " mmmmmmm(nullptr),\n" 12812 " nnnnnnn(nullptr) {}\n" 12813 "};", 12814 getGoogleStyle()); 12815 12816 FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0); 12817 EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit)); 12818 EXPECT_EQ("class C {\n" 12819 " A() : b(0) {}\n" 12820 "};", 12821 format("class C{A():b(0){}};", NoColumnLimit)); 12822 EXPECT_EQ("A()\n" 12823 " : b(0) {\n" 12824 "}", 12825 format("A()\n:b(0)\n{\n}", NoColumnLimit)); 12826 12827 FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit; 12828 DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine = 12829 FormatStyle::SFS_None; 12830 EXPECT_EQ("A()\n" 12831 " : b(0) {\n" 12832 "}", 12833 format("A():b(0){}", DoNotMergeNoColumnLimit)); 12834 EXPECT_EQ("A()\n" 12835 " : b(0) {\n" 12836 "}", 12837 format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit)); 12838 12839 verifyFormat("#define A \\\n" 12840 " void f() { \\\n" 12841 " int i; \\\n" 12842 " }", 12843 getLLVMStyleWithColumns(20)); 12844 verifyFormat("#define A \\\n" 12845 " void f() { int i; }", 12846 getLLVMStyleWithColumns(21)); 12847 verifyFormat("#define A \\\n" 12848 " void f() { \\\n" 12849 " int i; \\\n" 12850 " } \\\n" 12851 " int j;", 12852 getLLVMStyleWithColumns(22)); 12853 verifyFormat("#define A \\\n" 12854 " void f() { int i; } \\\n" 12855 " int j;", 12856 getLLVMStyleWithColumns(23)); 12857 } 12858 12859 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) { 12860 FormatStyle MergeEmptyOnly = getLLVMStyle(); 12861 MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 12862 verifyFormat("class C {\n" 12863 " int f() {}\n" 12864 "};", 12865 MergeEmptyOnly); 12866 verifyFormat("class C {\n" 12867 " int f() {\n" 12868 " return 42;\n" 12869 " }\n" 12870 "};", 12871 MergeEmptyOnly); 12872 verifyFormat("int f() {}", MergeEmptyOnly); 12873 verifyFormat("int f() {\n" 12874 " return 42;\n" 12875 "}", 12876 MergeEmptyOnly); 12877 12878 // Also verify behavior when BraceWrapping.AfterFunction = true 12879 MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12880 MergeEmptyOnly.BraceWrapping.AfterFunction = true; 12881 verifyFormat("int f() {}", MergeEmptyOnly); 12882 verifyFormat("class C {\n" 12883 " int f() {}\n" 12884 "};", 12885 MergeEmptyOnly); 12886 } 12887 12888 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) { 12889 FormatStyle MergeInlineOnly = getLLVMStyle(); 12890 MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 12891 verifyFormat("class C {\n" 12892 " int f() { return 42; }\n" 12893 "};", 12894 MergeInlineOnly); 12895 verifyFormat("int f() {\n" 12896 " return 42;\n" 12897 "}", 12898 MergeInlineOnly); 12899 12900 // SFS_Inline implies SFS_Empty 12901 verifyFormat("class C {\n" 12902 " int f() {}\n" 12903 "};", 12904 MergeInlineOnly); 12905 verifyFormat("int f() {}", MergeInlineOnly); 12906 // https://llvm.org/PR54147 12907 verifyFormat("auto lambda = []() {\n" 12908 " // comment\n" 12909 " f();\n" 12910 " g();\n" 12911 "};", 12912 MergeInlineOnly); 12913 12914 verifyFormat("class C {\n" 12915 "#ifdef A\n" 12916 " int f() { return 42; }\n" 12917 "#endif\n" 12918 "};", 12919 MergeInlineOnly); 12920 12921 verifyFormat("struct S {\n" 12922 "// comment\n" 12923 "#ifdef FOO\n" 12924 " int foo() { bar(); }\n" 12925 "#endif\n" 12926 "};", 12927 MergeInlineOnly); 12928 12929 // Also verify behavior when BraceWrapping.AfterFunction = true 12930 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12931 MergeInlineOnly.BraceWrapping.AfterFunction = true; 12932 verifyFormat("class C {\n" 12933 " int f() { return 42; }\n" 12934 "};", 12935 MergeInlineOnly); 12936 verifyFormat("int f()\n" 12937 "{\n" 12938 " return 42;\n" 12939 "}", 12940 MergeInlineOnly); 12941 12942 // SFS_Inline implies SFS_Empty 12943 verifyFormat("int f() {}", MergeInlineOnly); 12944 verifyFormat("class C {\n" 12945 " int f() {}\n" 12946 "};", 12947 MergeInlineOnly); 12948 12949 MergeInlineOnly.BraceWrapping.AfterClass = true; 12950 MergeInlineOnly.BraceWrapping.AfterStruct = true; 12951 verifyFormat("class C\n" 12952 "{\n" 12953 " int f() { return 42; }\n" 12954 "};", 12955 MergeInlineOnly); 12956 verifyFormat("struct C\n" 12957 "{\n" 12958 " int f() { return 42; }\n" 12959 "};", 12960 MergeInlineOnly); 12961 verifyFormat("int f()\n" 12962 "{\n" 12963 " return 42;\n" 12964 "}", 12965 MergeInlineOnly); 12966 verifyFormat("int f() {}", MergeInlineOnly); 12967 verifyFormat("class C\n" 12968 "{\n" 12969 " int f() { return 42; }\n" 12970 "};", 12971 MergeInlineOnly); 12972 verifyFormat("struct C\n" 12973 "{\n" 12974 " int f() { return 42; }\n" 12975 "};", 12976 MergeInlineOnly); 12977 verifyFormat("struct C\n" 12978 "// comment\n" 12979 "/* comment */\n" 12980 "// comment\n" 12981 "{\n" 12982 " int f() { return 42; }\n" 12983 "};", 12984 MergeInlineOnly); 12985 verifyFormat("/* comment */ struct C\n" 12986 "{\n" 12987 " int f() { return 42; }\n" 12988 "};", 12989 MergeInlineOnly); 12990 } 12991 12992 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) { 12993 FormatStyle MergeInlineOnly = getLLVMStyle(); 12994 MergeInlineOnly.AllowShortFunctionsOnASingleLine = 12995 FormatStyle::SFS_InlineOnly; 12996 verifyFormat("class C {\n" 12997 " int f() { return 42; }\n" 12998 "};", 12999 MergeInlineOnly); 13000 verifyFormat("int f() {\n" 13001 " return 42;\n" 13002 "}", 13003 MergeInlineOnly); 13004 13005 // SFS_InlineOnly does not imply SFS_Empty 13006 verifyFormat("class C {\n" 13007 " int f() {}\n" 13008 "};", 13009 MergeInlineOnly); 13010 verifyFormat("int f() {\n" 13011 "}", 13012 MergeInlineOnly); 13013 13014 // Also verify behavior when BraceWrapping.AfterFunction = true 13015 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 13016 MergeInlineOnly.BraceWrapping.AfterFunction = true; 13017 verifyFormat("class C {\n" 13018 " int f() { return 42; }\n" 13019 "};", 13020 MergeInlineOnly); 13021 verifyFormat("int f()\n" 13022 "{\n" 13023 " return 42;\n" 13024 "}", 13025 MergeInlineOnly); 13026 13027 // SFS_InlineOnly does not imply SFS_Empty 13028 verifyFormat("int f()\n" 13029 "{\n" 13030 "}", 13031 MergeInlineOnly); 13032 verifyFormat("class C {\n" 13033 " int f() {}\n" 13034 "};", 13035 MergeInlineOnly); 13036 } 13037 13038 TEST_F(FormatTest, SplitEmptyFunction) { 13039 FormatStyle Style = getLLVMStyleWithColumns(40); 13040 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 13041 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13042 Style.BraceWrapping.AfterFunction = true; 13043 Style.BraceWrapping.SplitEmptyFunction = false; 13044 13045 verifyFormat("int f()\n" 13046 "{}", 13047 Style); 13048 verifyFormat("int f()\n" 13049 "{\n" 13050 " return 42;\n" 13051 "}", 13052 Style); 13053 verifyFormat("int f()\n" 13054 "{\n" 13055 " // some comment\n" 13056 "}", 13057 Style); 13058 13059 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 13060 verifyFormat("int f() {}", Style); 13061 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 13062 "{}", 13063 Style); 13064 verifyFormat("int f()\n" 13065 "{\n" 13066 " return 0;\n" 13067 "}", 13068 Style); 13069 13070 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 13071 verifyFormat("class Foo {\n" 13072 " int f() {}\n" 13073 "};\n", 13074 Style); 13075 verifyFormat("class Foo {\n" 13076 " int f() { return 0; }\n" 13077 "};\n", 13078 Style); 13079 verifyFormat("class Foo {\n" 13080 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 13081 " {}\n" 13082 "};\n", 13083 Style); 13084 verifyFormat("class Foo {\n" 13085 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 13086 " {\n" 13087 " return 0;\n" 13088 " }\n" 13089 "};\n", 13090 Style); 13091 13092 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 13093 verifyFormat("int f() {}", Style); 13094 verifyFormat("int f() { return 0; }", Style); 13095 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 13096 "{}", 13097 Style); 13098 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 13099 "{\n" 13100 " return 0;\n" 13101 "}", 13102 Style); 13103 } 13104 13105 TEST_F(FormatTest, SplitEmptyFunctionButNotRecord) { 13106 FormatStyle Style = getLLVMStyleWithColumns(40); 13107 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 13108 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13109 Style.BraceWrapping.AfterFunction = true; 13110 Style.BraceWrapping.SplitEmptyFunction = true; 13111 Style.BraceWrapping.SplitEmptyRecord = false; 13112 13113 verifyFormat("class C {};", Style); 13114 verifyFormat("struct C {};", Style); 13115 verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 13116 " int bbbbbbbbbbbbbbbbbbbbbbbb)\n" 13117 "{\n" 13118 "}", 13119 Style); 13120 verifyFormat("class C {\n" 13121 " C()\n" 13122 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa(),\n" 13123 " bbbbbbbbbbbbbbbbbbb()\n" 13124 " {\n" 13125 " }\n" 13126 " void\n" 13127 " m(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 13128 " int bbbbbbbbbbbbbbbbbbbbbbbb)\n" 13129 " {\n" 13130 " }\n" 13131 "};", 13132 Style); 13133 } 13134 13135 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) { 13136 FormatStyle Style = getLLVMStyle(); 13137 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 13138 verifyFormat("#ifdef A\n" 13139 "int f() {}\n" 13140 "#else\n" 13141 "int g() {}\n" 13142 "#endif", 13143 Style); 13144 } 13145 13146 TEST_F(FormatTest, SplitEmptyClass) { 13147 FormatStyle Style = getLLVMStyle(); 13148 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13149 Style.BraceWrapping.AfterClass = true; 13150 Style.BraceWrapping.SplitEmptyRecord = false; 13151 13152 verifyFormat("class Foo\n" 13153 "{};", 13154 Style); 13155 verifyFormat("/* something */ class Foo\n" 13156 "{};", 13157 Style); 13158 verifyFormat("template <typename X> class Foo\n" 13159 "{};", 13160 Style); 13161 verifyFormat("class Foo\n" 13162 "{\n" 13163 " Foo();\n" 13164 "};", 13165 Style); 13166 verifyFormat("typedef class Foo\n" 13167 "{\n" 13168 "} Foo_t;", 13169 Style); 13170 13171 Style.BraceWrapping.SplitEmptyRecord = true; 13172 Style.BraceWrapping.AfterStruct = true; 13173 verifyFormat("class rep\n" 13174 "{\n" 13175 "};", 13176 Style); 13177 verifyFormat("struct rep\n" 13178 "{\n" 13179 "};", 13180 Style); 13181 verifyFormat("template <typename T> class rep\n" 13182 "{\n" 13183 "};", 13184 Style); 13185 verifyFormat("template <typename T> struct rep\n" 13186 "{\n" 13187 "};", 13188 Style); 13189 verifyFormat("class rep\n" 13190 "{\n" 13191 " int x;\n" 13192 "};", 13193 Style); 13194 verifyFormat("struct rep\n" 13195 "{\n" 13196 " int x;\n" 13197 "};", 13198 Style); 13199 verifyFormat("template <typename T> class rep\n" 13200 "{\n" 13201 " int x;\n" 13202 "};", 13203 Style); 13204 verifyFormat("template <typename T> struct rep\n" 13205 "{\n" 13206 " int x;\n" 13207 "};", 13208 Style); 13209 verifyFormat("template <typename T> class rep // Foo\n" 13210 "{\n" 13211 " int x;\n" 13212 "};", 13213 Style); 13214 verifyFormat("template <typename T> struct rep // Bar\n" 13215 "{\n" 13216 " int x;\n" 13217 "};", 13218 Style); 13219 13220 verifyFormat("template <typename T> class rep<T>\n" 13221 "{\n" 13222 " int x;\n" 13223 "};", 13224 Style); 13225 13226 verifyFormat("template <typename T> class rep<std::complex<T>>\n" 13227 "{\n" 13228 " int x;\n" 13229 "};", 13230 Style); 13231 verifyFormat("template <typename T> class rep<std::complex<T>>\n" 13232 "{\n" 13233 "};", 13234 Style); 13235 13236 verifyFormat("#include \"stdint.h\"\n" 13237 "namespace rep {}", 13238 Style); 13239 verifyFormat("#include <stdint.h>\n" 13240 "namespace rep {}", 13241 Style); 13242 verifyFormat("#include <stdint.h>\n" 13243 "namespace rep {}", 13244 "#include <stdint.h>\n" 13245 "namespace rep {\n" 13246 "\n" 13247 "\n" 13248 "}", 13249 Style); 13250 } 13251 13252 TEST_F(FormatTest, SplitEmptyStruct) { 13253 FormatStyle Style = getLLVMStyle(); 13254 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13255 Style.BraceWrapping.AfterStruct = true; 13256 Style.BraceWrapping.SplitEmptyRecord = false; 13257 13258 verifyFormat("struct Foo\n" 13259 "{};", 13260 Style); 13261 verifyFormat("/* something */ struct Foo\n" 13262 "{};", 13263 Style); 13264 verifyFormat("template <typename X> struct Foo\n" 13265 "{};", 13266 Style); 13267 verifyFormat("struct Foo\n" 13268 "{\n" 13269 " Foo();\n" 13270 "};", 13271 Style); 13272 verifyFormat("typedef struct Foo\n" 13273 "{\n" 13274 "} Foo_t;", 13275 Style); 13276 // typedef struct Bar {} Bar_t; 13277 } 13278 13279 TEST_F(FormatTest, SplitEmptyUnion) { 13280 FormatStyle Style = getLLVMStyle(); 13281 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13282 Style.BraceWrapping.AfterUnion = true; 13283 Style.BraceWrapping.SplitEmptyRecord = false; 13284 13285 verifyFormat("union Foo\n" 13286 "{};", 13287 Style); 13288 verifyFormat("/* something */ union Foo\n" 13289 "{};", 13290 Style); 13291 verifyFormat("union Foo\n" 13292 "{\n" 13293 " A,\n" 13294 "};", 13295 Style); 13296 verifyFormat("typedef union Foo\n" 13297 "{\n" 13298 "} Foo_t;", 13299 Style); 13300 } 13301 13302 TEST_F(FormatTest, SplitEmptyNamespace) { 13303 FormatStyle Style = getLLVMStyle(); 13304 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13305 Style.BraceWrapping.AfterNamespace = true; 13306 Style.BraceWrapping.SplitEmptyNamespace = false; 13307 13308 verifyFormat("namespace Foo\n" 13309 "{};", 13310 Style); 13311 verifyFormat("/* something */ namespace Foo\n" 13312 "{};", 13313 Style); 13314 verifyFormat("inline namespace Foo\n" 13315 "{};", 13316 Style); 13317 verifyFormat("/* something */ inline namespace Foo\n" 13318 "{};", 13319 Style); 13320 verifyFormat("export namespace Foo\n" 13321 "{};", 13322 Style); 13323 verifyFormat("namespace Foo\n" 13324 "{\n" 13325 "void Bar();\n" 13326 "};", 13327 Style); 13328 } 13329 13330 TEST_F(FormatTest, NeverMergeShortRecords) { 13331 FormatStyle Style = getLLVMStyle(); 13332 13333 verifyFormat("class Foo {\n" 13334 " Foo();\n" 13335 "};", 13336 Style); 13337 verifyFormat("typedef class Foo {\n" 13338 " Foo();\n" 13339 "} Foo_t;", 13340 Style); 13341 verifyFormat("struct Foo {\n" 13342 " Foo();\n" 13343 "};", 13344 Style); 13345 verifyFormat("typedef struct Foo {\n" 13346 " Foo();\n" 13347 "} Foo_t;", 13348 Style); 13349 verifyFormat("union Foo {\n" 13350 " A,\n" 13351 "};", 13352 Style); 13353 verifyFormat("typedef union Foo {\n" 13354 " A,\n" 13355 "} Foo_t;", 13356 Style); 13357 verifyFormat("namespace Foo {\n" 13358 "void Bar();\n" 13359 "};", 13360 Style); 13361 13362 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13363 Style.BraceWrapping.AfterClass = true; 13364 Style.BraceWrapping.AfterStruct = true; 13365 Style.BraceWrapping.AfterUnion = true; 13366 Style.BraceWrapping.AfterNamespace = true; 13367 verifyFormat("class Foo\n" 13368 "{\n" 13369 " Foo();\n" 13370 "};", 13371 Style); 13372 verifyFormat("typedef class Foo\n" 13373 "{\n" 13374 " Foo();\n" 13375 "} Foo_t;", 13376 Style); 13377 verifyFormat("struct Foo\n" 13378 "{\n" 13379 " Foo();\n" 13380 "};", 13381 Style); 13382 verifyFormat("typedef struct Foo\n" 13383 "{\n" 13384 " Foo();\n" 13385 "} Foo_t;", 13386 Style); 13387 verifyFormat("union Foo\n" 13388 "{\n" 13389 " A,\n" 13390 "};", 13391 Style); 13392 verifyFormat("typedef union Foo\n" 13393 "{\n" 13394 " A,\n" 13395 "} Foo_t;", 13396 Style); 13397 verifyFormat("namespace Foo\n" 13398 "{\n" 13399 "void Bar();\n" 13400 "};", 13401 Style); 13402 } 13403 13404 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) { 13405 // Elaborate type variable declarations. 13406 verifyFormat("struct foo a = {bar};\nint n;"); 13407 verifyFormat("class foo a = {bar};\nint n;"); 13408 verifyFormat("union foo a = {bar};\nint n;"); 13409 13410 // Elaborate types inside function definitions. 13411 verifyFormat("struct foo f() {}\nint n;"); 13412 verifyFormat("class foo f() {}\nint n;"); 13413 verifyFormat("union foo f() {}\nint n;"); 13414 13415 // Templates. 13416 verifyFormat("template <class X> void f() {}\nint n;"); 13417 verifyFormat("template <struct X> void f() {}\nint n;"); 13418 verifyFormat("template <union X> void f() {}\nint n;"); 13419 13420 // Actual definitions... 13421 verifyFormat("struct {\n} n;"); 13422 verifyFormat( 13423 "template <template <class T, class Y>, class Z> class X {\n} n;"); 13424 verifyFormat("union Z {\n int n;\n} x;"); 13425 verifyFormat("class MACRO Z {\n} n;"); 13426 verifyFormat("class MACRO(X) Z {\n} n;"); 13427 verifyFormat("class __attribute__(X) Z {\n} n;"); 13428 verifyFormat("class __declspec(X) Z {\n} n;"); 13429 verifyFormat("class A##B##C {\n} n;"); 13430 verifyFormat("class alignas(16) Z {\n} n;"); 13431 verifyFormat("class MACRO(X) alignas(16) Z {\n} n;"); 13432 verifyFormat("class MACROA MACRO(X) Z {\n} n;"); 13433 13434 // Redefinition from nested context: 13435 verifyFormat("class A::B::C {\n} n;"); 13436 13437 // Template definitions. 13438 verifyFormat( 13439 "template <typename F>\n" 13440 "Matcher(const Matcher<F> &Other,\n" 13441 " typename enable_if_c<is_base_of<F, T>::value &&\n" 13442 " !is_same<F, T>::value>::type * = 0)\n" 13443 " : Implementation(new ImplicitCastMatcher<F>(Other)) {}"); 13444 13445 // FIXME: This is still incorrectly handled at the formatter side. 13446 verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};"); 13447 verifyFormat("int i = SomeFunction(a<b, a> b);"); 13448 13449 // FIXME: 13450 // This now gets parsed incorrectly as class definition. 13451 // verifyFormat("class A<int> f() {\n}\nint n;"); 13452 13453 // Elaborate types where incorrectly parsing the structural element would 13454 // break the indent. 13455 verifyFormat("if (true)\n" 13456 " class X x;\n" 13457 "else\n" 13458 " f();\n"); 13459 13460 // This is simply incomplete. Formatting is not important, but must not crash. 13461 verifyFormat("class A:"); 13462 } 13463 13464 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) { 13465 EXPECT_EQ("#error Leave all white!!!!! space* alone!\n", 13466 format("#error Leave all white!!!!! space* alone!\n")); 13467 EXPECT_EQ( 13468 "#warning Leave all white!!!!! space* alone!\n", 13469 format("#warning Leave all white!!!!! space* alone!\n")); 13470 EXPECT_EQ("#error 1", format(" # error 1")); 13471 EXPECT_EQ("#warning 1", format(" # warning 1")); 13472 } 13473 13474 TEST_F(FormatTest, FormatHashIfExpressions) { 13475 verifyFormat("#if AAAA && BBBB"); 13476 verifyFormat("#if (AAAA && BBBB)"); 13477 verifyFormat("#elif (AAAA && BBBB)"); 13478 // FIXME: Come up with a better indentation for #elif. 13479 verifyFormat( 13480 "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) && \\\n" 13481 " defined(BBBBBBBB)\n" 13482 "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) && \\\n" 13483 " defined(BBBBBBBB)\n" 13484 "#endif", 13485 getLLVMStyleWithColumns(65)); 13486 } 13487 13488 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) { 13489 FormatStyle AllowsMergedIf = getGoogleStyle(); 13490 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 13491 FormatStyle::SIS_WithoutElse; 13492 verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf); 13493 verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf); 13494 verifyFormat("if (true)\n#error E\n return 42;", AllowsMergedIf); 13495 EXPECT_EQ("if (true) return 42;", 13496 format("if (true)\nreturn 42;", AllowsMergedIf)); 13497 FormatStyle ShortMergedIf = AllowsMergedIf; 13498 ShortMergedIf.ColumnLimit = 25; 13499 verifyFormat("#define A \\\n" 13500 " if (true) return 42;", 13501 ShortMergedIf); 13502 verifyFormat("#define A \\\n" 13503 " f(); \\\n" 13504 " if (true)\n" 13505 "#define B", 13506 ShortMergedIf); 13507 verifyFormat("#define A \\\n" 13508 " f(); \\\n" 13509 " if (true)\n" 13510 "g();", 13511 ShortMergedIf); 13512 verifyFormat("{\n" 13513 "#ifdef A\n" 13514 " // Comment\n" 13515 " if (true) continue;\n" 13516 "#endif\n" 13517 " // Comment\n" 13518 " if (true) continue;\n" 13519 "}", 13520 ShortMergedIf); 13521 ShortMergedIf.ColumnLimit = 33; 13522 verifyFormat("#define A \\\n" 13523 " if constexpr (true) return 42;", 13524 ShortMergedIf); 13525 verifyFormat("#define A \\\n" 13526 " if CONSTEXPR (true) return 42;", 13527 ShortMergedIf); 13528 ShortMergedIf.ColumnLimit = 29; 13529 verifyFormat("#define A \\\n" 13530 " if (aaaaaaaaaa) return 1; \\\n" 13531 " return 2;", 13532 ShortMergedIf); 13533 ShortMergedIf.ColumnLimit = 28; 13534 verifyFormat("#define A \\\n" 13535 " if (aaaaaaaaaa) \\\n" 13536 " return 1; \\\n" 13537 " return 2;", 13538 ShortMergedIf); 13539 verifyFormat("#define A \\\n" 13540 " if constexpr (aaaaaaa) \\\n" 13541 " return 1; \\\n" 13542 " return 2;", 13543 ShortMergedIf); 13544 verifyFormat("#define A \\\n" 13545 " if CONSTEXPR (aaaaaaa) \\\n" 13546 " return 1; \\\n" 13547 " return 2;", 13548 ShortMergedIf); 13549 13550 verifyFormat("//\n" 13551 "#define a \\\n" 13552 " if \\\n" 13553 " 0", 13554 getChromiumStyle(FormatStyle::LK_Cpp)); 13555 } 13556 13557 TEST_F(FormatTest, FormatStarDependingOnContext) { 13558 verifyFormat("void f(int *a);"); 13559 verifyFormat("void f() { f(fint * b); }"); 13560 verifyFormat("class A {\n void f(int *a);\n};"); 13561 verifyFormat("class A {\n int *a;\n};"); 13562 verifyFormat("namespace a {\n" 13563 "namespace b {\n" 13564 "class A {\n" 13565 " void f() {}\n" 13566 " int *a;\n" 13567 "};\n" 13568 "} // namespace b\n" 13569 "} // namespace a"); 13570 } 13571 13572 TEST_F(FormatTest, SpecialTokensAtEndOfLine) { 13573 verifyFormat("while"); 13574 verifyFormat("operator"); 13575 } 13576 13577 TEST_F(FormatTest, SkipsDeeplyNestedLines) { 13578 // This code would be painfully slow to format if we didn't skip it. 13579 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 13580 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13581 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13582 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13583 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13584 "A(1, 1)\n" 13585 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x 13586 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13587 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13588 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13589 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13590 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13591 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13592 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13593 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13594 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n"); 13595 // Deeply nested part is untouched, rest is formatted. 13596 EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n", 13597 format(std::string("int i;\n") + Code + "int j;\n", 13598 getLLVMStyle(), SC_ExpectIncomplete)); 13599 } 13600 13601 //===----------------------------------------------------------------------===// 13602 // Objective-C tests. 13603 //===----------------------------------------------------------------------===// 13604 13605 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) { 13606 verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;"); 13607 EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;", 13608 format("-(NSUInteger)indexOfObject:(id)anObject;")); 13609 EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;")); 13610 EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;")); 13611 EXPECT_EQ("- (NSInteger)Method3:(id)anObject;", 13612 format("-(NSInteger)Method3:(id)anObject;")); 13613 EXPECT_EQ("- (NSInteger)Method4:(id)anObject;", 13614 format("-(NSInteger)Method4:(id)anObject;")); 13615 EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;", 13616 format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;")); 13617 EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;", 13618 format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;")); 13619 EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject " 13620 "forAllCells:(BOOL)flag;", 13621 format("- (void)sendAction:(SEL)aSelector to:(id)anObject " 13622 "forAllCells:(BOOL)flag;")); 13623 13624 // Very long objectiveC method declaration. 13625 verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n" 13626 " (SoooooooooooooooooooooomeType *)bbbbbbbbbb;"); 13627 verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n" 13628 " inRange:(NSRange)range\n" 13629 " outRange:(NSRange)out_range\n" 13630 " outRange1:(NSRange)out_range1\n" 13631 " outRange2:(NSRange)out_range2\n" 13632 " outRange3:(NSRange)out_range3\n" 13633 " outRange4:(NSRange)out_range4\n" 13634 " outRange5:(NSRange)out_range5\n" 13635 " outRange6:(NSRange)out_range6\n" 13636 " outRange7:(NSRange)out_range7\n" 13637 " outRange8:(NSRange)out_range8\n" 13638 " outRange9:(NSRange)out_range9;"); 13639 13640 // When the function name has to be wrapped. 13641 FormatStyle Style = getLLVMStyle(); 13642 // ObjC ignores IndentWrappedFunctionNames when wrapping methods 13643 // and always indents instead. 13644 Style.IndentWrappedFunctionNames = false; 13645 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n" 13646 " veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n" 13647 " anotherName:(NSString)bbbbbbbbbbbbbb {\n" 13648 "}", 13649 Style); 13650 Style.IndentWrappedFunctionNames = true; 13651 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n" 13652 " veryLooooooooooongName:(NSString)cccccccccccccc\n" 13653 " anotherName:(NSString)dddddddddddddd {\n" 13654 "}", 13655 Style); 13656 13657 verifyFormat("- (int)sum:(vector<int>)numbers;"); 13658 verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;"); 13659 // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC 13660 // protocol lists (but not for template classes): 13661 // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;"); 13662 13663 verifyFormat("- (int (*)())foo:(int (*)())f;"); 13664 verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;"); 13665 13666 // If there's no return type (very rare in practice!), LLVM and Google style 13667 // agree. 13668 verifyFormat("- foo;"); 13669 verifyFormat("- foo:(int)f;"); 13670 verifyGoogleFormat("- foo:(int)foo;"); 13671 } 13672 13673 TEST_F(FormatTest, BreaksStringLiterals) { 13674 EXPECT_EQ("\"some text \"\n" 13675 "\"other\";", 13676 format("\"some text other\";", getLLVMStyleWithColumns(12))); 13677 EXPECT_EQ("\"some text \"\n" 13678 "\"other\";", 13679 format("\\\n\"some text other\";", getLLVMStyleWithColumns(12))); 13680 EXPECT_EQ( 13681 "#define A \\\n" 13682 " \"some \" \\\n" 13683 " \"text \" \\\n" 13684 " \"other\";", 13685 format("#define A \"some text other\";", getLLVMStyleWithColumns(12))); 13686 EXPECT_EQ( 13687 "#define A \\\n" 13688 " \"so \" \\\n" 13689 " \"text \" \\\n" 13690 " \"other\";", 13691 format("#define A \"so text other\";", getLLVMStyleWithColumns(12))); 13692 13693 EXPECT_EQ("\"some text\"", 13694 format("\"some text\"", getLLVMStyleWithColumns(1))); 13695 EXPECT_EQ("\"some text\"", 13696 format("\"some text\"", getLLVMStyleWithColumns(11))); 13697 EXPECT_EQ("\"some \"\n" 13698 "\"text\"", 13699 format("\"some text\"", getLLVMStyleWithColumns(10))); 13700 EXPECT_EQ("\"some \"\n" 13701 "\"text\"", 13702 format("\"some text\"", getLLVMStyleWithColumns(7))); 13703 EXPECT_EQ("\"some\"\n" 13704 "\" tex\"\n" 13705 "\"t\"", 13706 format("\"some text\"", getLLVMStyleWithColumns(6))); 13707 EXPECT_EQ("\"some\"\n" 13708 "\" tex\"\n" 13709 "\" and\"", 13710 format("\"some tex and\"", getLLVMStyleWithColumns(6))); 13711 EXPECT_EQ("\"some\"\n" 13712 "\"/tex\"\n" 13713 "\"/and\"", 13714 format("\"some/tex/and\"", getLLVMStyleWithColumns(6))); 13715 13716 EXPECT_EQ("variable =\n" 13717 " \"long string \"\n" 13718 " \"literal\";", 13719 format("variable = \"long string literal\";", 13720 getLLVMStyleWithColumns(20))); 13721 13722 EXPECT_EQ("variable = f(\n" 13723 " \"long string \"\n" 13724 " \"literal\",\n" 13725 " short,\n" 13726 " loooooooooooooooooooong);", 13727 format("variable = f(\"long string literal\", short, " 13728 "loooooooooooooooooooong);", 13729 getLLVMStyleWithColumns(20))); 13730 13731 EXPECT_EQ( 13732 "f(g(\"long string \"\n" 13733 " \"literal\"),\n" 13734 " b);", 13735 format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20))); 13736 EXPECT_EQ("f(g(\"long string \"\n" 13737 " \"literal\",\n" 13738 " a),\n" 13739 " b);", 13740 format("f(g(\"long string literal\", a), b);", 13741 getLLVMStyleWithColumns(20))); 13742 EXPECT_EQ( 13743 "f(\"one two\".split(\n" 13744 " variable));", 13745 format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20))); 13746 EXPECT_EQ("f(\"one two three four five six \"\n" 13747 " \"seven\".split(\n" 13748 " really_looooong_variable));", 13749 format("f(\"one two three four five six seven\"." 13750 "split(really_looooong_variable));", 13751 getLLVMStyleWithColumns(33))); 13752 13753 EXPECT_EQ("f(\"some \"\n" 13754 " \"text\",\n" 13755 " other);", 13756 format("f(\"some text\", other);", getLLVMStyleWithColumns(10))); 13757 13758 // Only break as a last resort. 13759 verifyFormat( 13760 "aaaaaaaaaaaaaaaaaaaa(\n" 13761 " aaaaaaaaaaaaaaaaaaaa,\n" 13762 " aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));"); 13763 13764 EXPECT_EQ("\"splitmea\"\n" 13765 "\"trandomp\"\n" 13766 "\"oint\"", 13767 format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10))); 13768 13769 EXPECT_EQ("\"split/\"\n" 13770 "\"pathat/\"\n" 13771 "\"slashes\"", 13772 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10))); 13773 13774 EXPECT_EQ("\"split/\"\n" 13775 "\"pathat/\"\n" 13776 "\"slashes\"", 13777 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10))); 13778 EXPECT_EQ("\"split at \"\n" 13779 "\"spaces/at/\"\n" 13780 "\"slashes.at.any$\"\n" 13781 "\"non-alphanumeric%\"\n" 13782 "\"1111111111characte\"\n" 13783 "\"rs\"", 13784 format("\"split at " 13785 "spaces/at/" 13786 "slashes.at." 13787 "any$non-" 13788 "alphanumeric%" 13789 "1111111111characte" 13790 "rs\"", 13791 getLLVMStyleWithColumns(20))); 13792 13793 // Verify that splitting the strings understands 13794 // Style::AlwaysBreakBeforeMultilineStrings. 13795 EXPECT_EQ("aaaaaaaaaaaa(\n" 13796 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n" 13797 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");", 13798 format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa " 13799 "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa " 13800 "aaaaaaaaaaaaaaaaaaaaaa\");", 13801 getGoogleStyle())); 13802 EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13803 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";", 13804 format("return \"aaaaaaaaaaaaaaaaaaaaaa " 13805 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa " 13806 "aaaaaaaaaaaaaaaaaaaaaa\";", 13807 getGoogleStyle())); 13808 EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13809 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";", 13810 format("llvm::outs() << " 13811 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa" 13812 "aaaaaaaaaaaaaaaaaaa\";")); 13813 EXPECT_EQ("ffff(\n" 13814 " {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13815 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});", 13816 format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa " 13817 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});", 13818 getGoogleStyle())); 13819 13820 FormatStyle Style = getLLVMStyleWithColumns(12); 13821 Style.BreakStringLiterals = false; 13822 EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style)); 13823 13824 FormatStyle AlignLeft = getLLVMStyleWithColumns(12); 13825 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left; 13826 EXPECT_EQ("#define A \\\n" 13827 " \"some \" \\\n" 13828 " \"text \" \\\n" 13829 " \"other\";", 13830 format("#define A \"some text other\";", AlignLeft)); 13831 } 13832 13833 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) { 13834 EXPECT_EQ("C a = \"some more \"\n" 13835 " \"text\";", 13836 format("C a = \"some more text\";", getLLVMStyleWithColumns(18))); 13837 } 13838 13839 TEST_F(FormatTest, FullyRemoveEmptyLines) { 13840 FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80); 13841 NoEmptyLines.MaxEmptyLinesToKeep = 0; 13842 EXPECT_EQ("int i = a(b());", 13843 format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines)); 13844 } 13845 13846 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) { 13847 EXPECT_EQ( 13848 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 13849 "(\n" 13850 " \"x\t\");", 13851 format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 13852 "aaaaaaa(" 13853 "\"x\t\");")); 13854 } 13855 13856 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) { 13857 EXPECT_EQ( 13858 "u8\"utf8 string \"\n" 13859 "u8\"literal\";", 13860 format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16))); 13861 EXPECT_EQ( 13862 "u\"utf16 string \"\n" 13863 "u\"literal\";", 13864 format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16))); 13865 EXPECT_EQ( 13866 "U\"utf32 string \"\n" 13867 "U\"literal\";", 13868 format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16))); 13869 EXPECT_EQ("L\"wide string \"\n" 13870 "L\"literal\";", 13871 format("L\"wide string literal\";", getGoogleStyleWithColumns(16))); 13872 EXPECT_EQ("@\"NSString \"\n" 13873 "@\"literal\";", 13874 format("@\"NSString literal\";", getGoogleStyleWithColumns(19))); 13875 verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26)); 13876 13877 // This input makes clang-format try to split the incomplete unicode escape 13878 // sequence, which used to lead to a crasher. 13879 verifyNoCrash( 13880 "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 13881 getLLVMStyleWithColumns(60)); 13882 } 13883 13884 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) { 13885 FormatStyle Style = getGoogleStyleWithColumns(15); 13886 EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style)); 13887 EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style)); 13888 EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style)); 13889 EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style)); 13890 EXPECT_EQ("u8R\"x(raw literal)x\";", 13891 format("u8R\"x(raw literal)x\";", Style)); 13892 } 13893 13894 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) { 13895 FormatStyle Style = getLLVMStyleWithColumns(20); 13896 EXPECT_EQ( 13897 "_T(\"aaaaaaaaaaaaaa\")\n" 13898 "_T(\"aaaaaaaaaaaaaa\")\n" 13899 "_T(\"aaaaaaaaaaaa\")", 13900 format(" _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style)); 13901 EXPECT_EQ("f(x,\n" 13902 " _T(\"aaaaaaaaaaaa\")\n" 13903 " _T(\"aaa\"),\n" 13904 " z);", 13905 format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style)); 13906 13907 // FIXME: Handle embedded spaces in one iteration. 13908 // EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n" 13909 // "_T(\"aaaaaaaaaaaaa\")\n" 13910 // "_T(\"aaaaaaaaaaaaa\")\n" 13911 // "_T(\"a\")", 13912 // format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", 13913 // getLLVMStyleWithColumns(20))); 13914 EXPECT_EQ( 13915 "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", 13916 format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style)); 13917 EXPECT_EQ("f(\n" 13918 "#if !TEST\n" 13919 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n" 13920 "#endif\n" 13921 ");", 13922 format("f(\n" 13923 "#if !TEST\n" 13924 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n" 13925 "#endif\n" 13926 ");")); 13927 EXPECT_EQ("f(\n" 13928 "\n" 13929 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));", 13930 format("f(\n" 13931 "\n" 13932 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));")); 13933 // Regression test for accessing tokens past the end of a vector in the 13934 // TokenLexer. 13935 verifyNoCrash(R"(_T( 13936 " 13937 ) 13938 )"); 13939 } 13940 13941 TEST_F(FormatTest, BreaksStringLiteralOperands) { 13942 // In a function call with two operands, the second can be broken with no line 13943 // break before it. 13944 EXPECT_EQ( 13945 "func(a, \"long long \"\n" 13946 " \"long long\");", 13947 format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24))); 13948 // In a function call with three operands, the second must be broken with a 13949 // line break before it. 13950 EXPECT_EQ("func(a,\n" 13951 " \"long long long \"\n" 13952 " \"long\",\n" 13953 " c);", 13954 format("func(a, \"long long long long\", c);", 13955 getLLVMStyleWithColumns(24))); 13956 // In a function call with three operands, the third must be broken with a 13957 // line break before it. 13958 EXPECT_EQ("func(a, b,\n" 13959 " \"long long long \"\n" 13960 " \"long\");", 13961 format("func(a, b, \"long long long long\");", 13962 getLLVMStyleWithColumns(24))); 13963 // In a function call with three operands, both the second and the third must 13964 // be broken with a line break before them. 13965 EXPECT_EQ("func(a,\n" 13966 " \"long long long \"\n" 13967 " \"long\",\n" 13968 " \"long long long \"\n" 13969 " \"long\");", 13970 format("func(a, \"long long long long\", \"long long long long\");", 13971 getLLVMStyleWithColumns(24))); 13972 // In a chain of << with two operands, the second can be broken with no line 13973 // break before it. 13974 EXPECT_EQ("a << \"line line \"\n" 13975 " \"line\";", 13976 format("a << \"line line line\";", getLLVMStyleWithColumns(20))); 13977 // In a chain of << with three operands, the second can be broken with no line 13978 // break before it. 13979 EXPECT_EQ( 13980 "abcde << \"line \"\n" 13981 " \"line line\"\n" 13982 " << c;", 13983 format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20))); 13984 // In a chain of << with three operands, the third must be broken with a line 13985 // break before it. 13986 EXPECT_EQ( 13987 "a << b\n" 13988 " << \"line line \"\n" 13989 " \"line\";", 13990 format("a << b << \"line line line\";", getLLVMStyleWithColumns(20))); 13991 // In a chain of << with three operands, the second can be broken with no line 13992 // break before it and the third must be broken with a line break before it. 13993 EXPECT_EQ("abcd << \"line line \"\n" 13994 " \"line\"\n" 13995 " << \"line line \"\n" 13996 " \"line\";", 13997 format("abcd << \"line line line\" << \"line line line\";", 13998 getLLVMStyleWithColumns(20))); 13999 // In a chain of binary operators with two operands, the second can be broken 14000 // with no line break before it. 14001 EXPECT_EQ( 14002 "abcd + \"line line \"\n" 14003 " \"line line\";", 14004 format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20))); 14005 // In a chain of binary operators with three operands, the second must be 14006 // broken with a line break before it. 14007 EXPECT_EQ("abcd +\n" 14008 " \"line line \"\n" 14009 " \"line line\" +\n" 14010 " e;", 14011 format("abcd + \"line line line line\" + e;", 14012 getLLVMStyleWithColumns(20))); 14013 // In a function call with two operands, with AlignAfterOpenBracket enabled, 14014 // the first must be broken with a line break before it. 14015 FormatStyle Style = getLLVMStyleWithColumns(25); 14016 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 14017 EXPECT_EQ("someFunction(\n" 14018 " \"long long long \"\n" 14019 " \"long\",\n" 14020 " a);", 14021 format("someFunction(\"long long long long\", a);", Style)); 14022 } 14023 14024 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) { 14025 EXPECT_EQ( 14026 "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 14027 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 14028 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";", 14029 format("aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 14030 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 14031 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";")); 14032 } 14033 14034 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) { 14035 EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);", 14036 format("f(g(R\"x(raw literal)x\", a), b);", getGoogleStyle())); 14037 EXPECT_EQ("fffffffffff(g(R\"x(\n" 14038 "multiline raw string literal xxxxxxxxxxxxxx\n" 14039 ")x\",\n" 14040 " a),\n" 14041 " b);", 14042 format("fffffffffff(g(R\"x(\n" 14043 "multiline raw string literal xxxxxxxxxxxxxx\n" 14044 ")x\", a), b);", 14045 getGoogleStyleWithColumns(20))); 14046 EXPECT_EQ("fffffffffff(\n" 14047 " g(R\"x(qqq\n" 14048 "multiline raw string literal xxxxxxxxxxxxxx\n" 14049 ")x\",\n" 14050 " a),\n" 14051 " b);", 14052 format("fffffffffff(g(R\"x(qqq\n" 14053 "multiline raw string literal xxxxxxxxxxxxxx\n" 14054 ")x\", a), b);", 14055 getGoogleStyleWithColumns(20))); 14056 14057 EXPECT_EQ("fffffffffff(R\"x(\n" 14058 "multiline raw string literal xxxxxxxxxxxxxx\n" 14059 ")x\");", 14060 format("fffffffffff(R\"x(\n" 14061 "multiline raw string literal xxxxxxxxxxxxxx\n" 14062 ")x\");", 14063 getGoogleStyleWithColumns(20))); 14064 EXPECT_EQ("fffffffffff(R\"x(\n" 14065 "multiline raw string literal xxxxxxxxxxxxxx\n" 14066 ")x\" + bbbbbb);", 14067 format("fffffffffff(R\"x(\n" 14068 "multiline raw string literal xxxxxxxxxxxxxx\n" 14069 ")x\" + bbbbbb);", 14070 getGoogleStyleWithColumns(20))); 14071 EXPECT_EQ("fffffffffff(\n" 14072 " R\"x(\n" 14073 "multiline raw string literal xxxxxxxxxxxxxx\n" 14074 ")x\" +\n" 14075 " bbbbbb);", 14076 format("fffffffffff(\n" 14077 " R\"x(\n" 14078 "multiline raw string literal xxxxxxxxxxxxxx\n" 14079 ")x\" + bbbbbb);", 14080 getGoogleStyleWithColumns(20))); 14081 EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);", 14082 format("fffffffffff(\n" 14083 " R\"(single line raw string)\" + bbbbbb);")); 14084 } 14085 14086 TEST_F(FormatTest, SkipsUnknownStringLiterals) { 14087 verifyFormat("string a = \"unterminated;"); 14088 EXPECT_EQ("function(\"unterminated,\n" 14089 " OtherParameter);", 14090 format("function( \"unterminated,\n" 14091 " OtherParameter);")); 14092 } 14093 14094 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) { 14095 FormatStyle Style = getLLVMStyle(); 14096 Style.Standard = FormatStyle::LS_Cpp03; 14097 EXPECT_EQ("#define x(_a) printf(\"foo\" _a);", 14098 format("#define x(_a) printf(\"foo\"_a);", Style)); 14099 } 14100 14101 TEST_F(FormatTest, CppLexVersion) { 14102 FormatStyle Style = getLLVMStyle(); 14103 // Formatting of x * y differs if x is a type. 14104 verifyFormat("void foo() { MACRO(a * b); }", Style); 14105 verifyFormat("void foo() { MACRO(int *b); }", Style); 14106 14107 // LLVM style uses latest lexer. 14108 verifyFormat("void foo() { MACRO(char8_t *b); }", Style); 14109 Style.Standard = FormatStyle::LS_Cpp17; 14110 // But in c++17, char8_t isn't a keyword. 14111 verifyFormat("void foo() { MACRO(char8_t * b); }", Style); 14112 } 14113 14114 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); } 14115 14116 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) { 14117 EXPECT_EQ("someFunction(\"aaabbbcccd\"\n" 14118 " \"ddeeefff\");", 14119 format("someFunction(\"aaabbbcccdddeeefff\");", 14120 getLLVMStyleWithColumns(25))); 14121 EXPECT_EQ("someFunction1234567890(\n" 14122 " \"aaabbbcccdddeeefff\");", 14123 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 14124 getLLVMStyleWithColumns(26))); 14125 EXPECT_EQ("someFunction1234567890(\n" 14126 " \"aaabbbcccdddeeeff\"\n" 14127 " \"f\");", 14128 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 14129 getLLVMStyleWithColumns(25))); 14130 EXPECT_EQ("someFunction1234567890(\n" 14131 " \"aaabbbcccdddeeeff\"\n" 14132 " \"f\");", 14133 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 14134 getLLVMStyleWithColumns(24))); 14135 EXPECT_EQ("someFunction(\n" 14136 " \"aaabbbcc ddde \"\n" 14137 " \"efff\");", 14138 format("someFunction(\"aaabbbcc ddde efff\");", 14139 getLLVMStyleWithColumns(25))); 14140 EXPECT_EQ("someFunction(\"aaabbbccc \"\n" 14141 " \"ddeeefff\");", 14142 format("someFunction(\"aaabbbccc ddeeefff\");", 14143 getLLVMStyleWithColumns(25))); 14144 EXPECT_EQ("someFunction1234567890(\n" 14145 " \"aaabb \"\n" 14146 " \"cccdddeeefff\");", 14147 format("someFunction1234567890(\"aaabb cccdddeeefff\");", 14148 getLLVMStyleWithColumns(25))); 14149 EXPECT_EQ("#define A \\\n" 14150 " string s = \\\n" 14151 " \"123456789\" \\\n" 14152 " \"0\"; \\\n" 14153 " int i;", 14154 format("#define A string s = \"1234567890\"; int i;", 14155 getLLVMStyleWithColumns(20))); 14156 EXPECT_EQ("someFunction(\n" 14157 " \"aaabbbcc \"\n" 14158 " \"dddeeefff\");", 14159 format("someFunction(\"aaabbbcc dddeeefff\");", 14160 getLLVMStyleWithColumns(25))); 14161 } 14162 14163 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) { 14164 EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3))); 14165 EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2))); 14166 EXPECT_EQ("\"test\"\n" 14167 "\"\\n\"", 14168 format("\"test\\n\"", getLLVMStyleWithColumns(7))); 14169 EXPECT_EQ("\"tes\\\\\"\n" 14170 "\"n\"", 14171 format("\"tes\\\\n\"", getLLVMStyleWithColumns(7))); 14172 EXPECT_EQ("\"\\\\\\\\\"\n" 14173 "\"\\n\"", 14174 format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7))); 14175 EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7))); 14176 EXPECT_EQ("\"\\uff01\"\n" 14177 "\"test\"", 14178 format("\"\\uff01test\"", getLLVMStyleWithColumns(8))); 14179 EXPECT_EQ("\"\\Uff01ff02\"", 14180 format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11))); 14181 EXPECT_EQ("\"\\x000000000001\"\n" 14182 "\"next\"", 14183 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16))); 14184 EXPECT_EQ("\"\\x000000000001next\"", 14185 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15))); 14186 EXPECT_EQ("\"\\x000000000001\"", 14187 format("\"\\x000000000001\"", getLLVMStyleWithColumns(7))); 14188 EXPECT_EQ("\"test\"\n" 14189 "\"\\000000\"\n" 14190 "\"000001\"", 14191 format("\"test\\000000000001\"", getLLVMStyleWithColumns(9))); 14192 EXPECT_EQ("\"test\\000\"\n" 14193 "\"00000000\"\n" 14194 "\"1\"", 14195 format("\"test\\000000000001\"", getLLVMStyleWithColumns(10))); 14196 } 14197 14198 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) { 14199 verifyFormat("void f() {\n" 14200 " return g() {}\n" 14201 " void h() {}"); 14202 verifyFormat("int a[] = {void forgot_closing_brace(){f();\n" 14203 "g();\n" 14204 "}"); 14205 } 14206 14207 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) { 14208 verifyFormat( 14209 "void f() { return C{param1, param2}.SomeCall(param1, param2); }"); 14210 } 14211 14212 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) { 14213 verifyFormat("class X {\n" 14214 " void f() {\n" 14215 " }\n" 14216 "};", 14217 getLLVMStyleWithColumns(12)); 14218 } 14219 14220 TEST_F(FormatTest, ConfigurableIndentWidth) { 14221 FormatStyle EightIndent = getLLVMStyleWithColumns(18); 14222 EightIndent.IndentWidth = 8; 14223 EightIndent.ContinuationIndentWidth = 8; 14224 verifyFormat("void f() {\n" 14225 " someFunction();\n" 14226 " if (true) {\n" 14227 " f();\n" 14228 " }\n" 14229 "}", 14230 EightIndent); 14231 verifyFormat("class X {\n" 14232 " void f() {\n" 14233 " }\n" 14234 "};", 14235 EightIndent); 14236 verifyFormat("int x[] = {\n" 14237 " call(),\n" 14238 " call()};", 14239 EightIndent); 14240 } 14241 14242 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) { 14243 verifyFormat("double\n" 14244 "f();", 14245 getLLVMStyleWithColumns(8)); 14246 } 14247 14248 TEST_F(FormatTest, ConfigurableUseOfTab) { 14249 FormatStyle Tab = getLLVMStyleWithColumns(42); 14250 Tab.IndentWidth = 8; 14251 Tab.UseTab = FormatStyle::UT_Always; 14252 Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left; 14253 14254 EXPECT_EQ("if (aaaaaaaa && // q\n" 14255 " bb)\t\t// w\n" 14256 "\t;", 14257 format("if (aaaaaaaa &&// q\n" 14258 "bb)// w\n" 14259 ";", 14260 Tab)); 14261 EXPECT_EQ("if (aaa && bbb) // w\n" 14262 "\t;", 14263 format("if(aaa&&bbb)// w\n" 14264 ";", 14265 Tab)); 14266 14267 verifyFormat("class X {\n" 14268 "\tvoid f() {\n" 14269 "\t\tsomeFunction(parameter1,\n" 14270 "\t\t\t parameter2);\n" 14271 "\t}\n" 14272 "};", 14273 Tab); 14274 verifyFormat("#define A \\\n" 14275 "\tvoid f() { \\\n" 14276 "\t\tsomeFunction( \\\n" 14277 "\t\t parameter1, \\\n" 14278 "\t\t parameter2); \\\n" 14279 "\t}", 14280 Tab); 14281 verifyFormat("int a;\t // x\n" 14282 "int bbbbbbbb; // x\n", 14283 Tab); 14284 14285 FormatStyle TabAlignment = Tab; 14286 TabAlignment.AlignConsecutiveDeclarations.Enabled = true; 14287 TabAlignment.PointerAlignment = FormatStyle::PAS_Left; 14288 verifyFormat("unsigned long long big;\n" 14289 "char*\t\t ptr;", 14290 TabAlignment); 14291 TabAlignment.PointerAlignment = FormatStyle::PAS_Middle; 14292 verifyFormat("unsigned long long big;\n" 14293 "char *\t\t ptr;", 14294 TabAlignment); 14295 TabAlignment.PointerAlignment = FormatStyle::PAS_Right; 14296 verifyFormat("unsigned long long big;\n" 14297 "char\t\t *ptr;", 14298 TabAlignment); 14299 14300 Tab.TabWidth = 4; 14301 Tab.IndentWidth = 8; 14302 verifyFormat("class TabWidth4Indent8 {\n" 14303 "\t\tvoid f() {\n" 14304 "\t\t\t\tsomeFunction(parameter1,\n" 14305 "\t\t\t\t\t\t\t parameter2);\n" 14306 "\t\t}\n" 14307 "};", 14308 Tab); 14309 14310 Tab.TabWidth = 4; 14311 Tab.IndentWidth = 4; 14312 verifyFormat("class TabWidth4Indent4 {\n" 14313 "\tvoid f() {\n" 14314 "\t\tsomeFunction(parameter1,\n" 14315 "\t\t\t\t\t parameter2);\n" 14316 "\t}\n" 14317 "};", 14318 Tab); 14319 14320 Tab.TabWidth = 8; 14321 Tab.IndentWidth = 4; 14322 verifyFormat("class TabWidth8Indent4 {\n" 14323 " void f() {\n" 14324 "\tsomeFunction(parameter1,\n" 14325 "\t\t parameter2);\n" 14326 " }\n" 14327 "};", 14328 Tab); 14329 14330 Tab.TabWidth = 8; 14331 Tab.IndentWidth = 8; 14332 EXPECT_EQ("/*\n" 14333 "\t a\t\tcomment\n" 14334 "\t in multiple lines\n" 14335 " */", 14336 format(" /*\t \t \n" 14337 " \t \t a\t\tcomment\t \t\n" 14338 " \t \t in multiple lines\t\n" 14339 " \t */", 14340 Tab)); 14341 14342 TabAlignment.UseTab = FormatStyle::UT_ForIndentation; 14343 TabAlignment.PointerAlignment = FormatStyle::PAS_Left; 14344 verifyFormat("void f() {\n" 14345 "\tunsigned long long big;\n" 14346 "\tchar* ptr;\n" 14347 "}", 14348 TabAlignment); 14349 TabAlignment.PointerAlignment = FormatStyle::PAS_Middle; 14350 verifyFormat("void f() {\n" 14351 "\tunsigned long long big;\n" 14352 "\tchar * ptr;\n" 14353 "}", 14354 TabAlignment); 14355 TabAlignment.PointerAlignment = FormatStyle::PAS_Right; 14356 verifyFormat("void f() {\n" 14357 "\tunsigned long long big;\n" 14358 "\tchar *ptr;\n" 14359 "}", 14360 TabAlignment); 14361 14362 Tab.UseTab = FormatStyle::UT_ForIndentation; 14363 verifyFormat("{\n" 14364 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14365 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14366 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14367 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14368 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14369 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14370 "};", 14371 Tab); 14372 verifyFormat("enum AA {\n" 14373 "\ta1, // Force multiple lines\n" 14374 "\ta2,\n" 14375 "\ta3\n" 14376 "};", 14377 Tab); 14378 EXPECT_EQ("if (aaaaaaaa && // q\n" 14379 " bb) // w\n" 14380 "\t;", 14381 format("if (aaaaaaaa &&// q\n" 14382 "bb)// w\n" 14383 ";", 14384 Tab)); 14385 verifyFormat("class X {\n" 14386 "\tvoid f() {\n" 14387 "\t\tsomeFunction(parameter1,\n" 14388 "\t\t parameter2);\n" 14389 "\t}\n" 14390 "};", 14391 Tab); 14392 verifyFormat("{\n" 14393 "\tQ(\n" 14394 "\t {\n" 14395 "\t\t int a;\n" 14396 "\t\t someFunction(aaaaaaaa,\n" 14397 "\t\t bbbbbbb);\n" 14398 "\t },\n" 14399 "\t p);\n" 14400 "}", 14401 Tab); 14402 EXPECT_EQ("{\n" 14403 "\t/* aaaa\n" 14404 "\t bbbb */\n" 14405 "}", 14406 format("{\n" 14407 "/* aaaa\n" 14408 " bbbb */\n" 14409 "}", 14410 Tab)); 14411 EXPECT_EQ("{\n" 14412 "\t/*\n" 14413 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14414 "\t bbbbbbbbbbbbb\n" 14415 "\t*/\n" 14416 "}", 14417 format("{\n" 14418 "/*\n" 14419 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14420 "*/\n" 14421 "}", 14422 Tab)); 14423 EXPECT_EQ("{\n" 14424 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14425 "\t// bbbbbbbbbbbbb\n" 14426 "}", 14427 format("{\n" 14428 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14429 "}", 14430 Tab)); 14431 EXPECT_EQ("{\n" 14432 "\t/*\n" 14433 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14434 "\t bbbbbbbbbbbbb\n" 14435 "\t*/\n" 14436 "}", 14437 format("{\n" 14438 "\t/*\n" 14439 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14440 "\t*/\n" 14441 "}", 14442 Tab)); 14443 EXPECT_EQ("{\n" 14444 "\t/*\n" 14445 "\n" 14446 "\t*/\n" 14447 "}", 14448 format("{\n" 14449 "\t/*\n" 14450 "\n" 14451 "\t*/\n" 14452 "}", 14453 Tab)); 14454 EXPECT_EQ("{\n" 14455 "\t/*\n" 14456 " asdf\n" 14457 "\t*/\n" 14458 "}", 14459 format("{\n" 14460 "\t/*\n" 14461 " asdf\n" 14462 "\t*/\n" 14463 "}", 14464 Tab)); 14465 14466 verifyFormat("void f() {\n" 14467 "\treturn true ? aaaaaaaaaaaaaaaaaa\n" 14468 "\t : bbbbbbbbbbbbbbbbbb\n" 14469 "}", 14470 Tab); 14471 FormatStyle TabNoBreak = Tab; 14472 TabNoBreak.BreakBeforeTernaryOperators = false; 14473 verifyFormat("void f() {\n" 14474 "\treturn true ? aaaaaaaaaaaaaaaaaa :\n" 14475 "\t bbbbbbbbbbbbbbbbbb\n" 14476 "}", 14477 TabNoBreak); 14478 verifyFormat("void f() {\n" 14479 "\treturn true ?\n" 14480 "\t aaaaaaaaaaaaaaaaaaaa :\n" 14481 "\t bbbbbbbbbbbbbbbbbbbb\n" 14482 "}", 14483 TabNoBreak); 14484 14485 Tab.UseTab = FormatStyle::UT_Never; 14486 EXPECT_EQ("/*\n" 14487 " a\t\tcomment\n" 14488 " in multiple lines\n" 14489 " */", 14490 format(" /*\t \t \n" 14491 " \t \t a\t\tcomment\t \t\n" 14492 " \t \t in multiple lines\t\n" 14493 " \t */", 14494 Tab)); 14495 EXPECT_EQ("/* some\n" 14496 " comment */", 14497 format(" \t \t /* some\n" 14498 " \t \t comment */", 14499 Tab)); 14500 EXPECT_EQ("int a; /* some\n" 14501 " comment */", 14502 format(" \t \t int a; /* some\n" 14503 " \t \t comment */", 14504 Tab)); 14505 14506 EXPECT_EQ("int a; /* some\n" 14507 "comment */", 14508 format(" \t \t int\ta; /* some\n" 14509 " \t \t comment */", 14510 Tab)); 14511 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14512 " comment */", 14513 format(" \t \t f(\"\t\t\"); /* some\n" 14514 " \t \t comment */", 14515 Tab)); 14516 EXPECT_EQ("{\n" 14517 " /*\n" 14518 " * Comment\n" 14519 " */\n" 14520 " int i;\n" 14521 "}", 14522 format("{\n" 14523 "\t/*\n" 14524 "\t * Comment\n" 14525 "\t */\n" 14526 "\t int i;\n" 14527 "}", 14528 Tab)); 14529 14530 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation; 14531 Tab.TabWidth = 8; 14532 Tab.IndentWidth = 8; 14533 EXPECT_EQ("if (aaaaaaaa && // q\n" 14534 " bb) // w\n" 14535 "\t;", 14536 format("if (aaaaaaaa &&// q\n" 14537 "bb)// w\n" 14538 ";", 14539 Tab)); 14540 EXPECT_EQ("if (aaa && bbb) // w\n" 14541 "\t;", 14542 format("if(aaa&&bbb)// w\n" 14543 ";", 14544 Tab)); 14545 verifyFormat("class X {\n" 14546 "\tvoid f() {\n" 14547 "\t\tsomeFunction(parameter1,\n" 14548 "\t\t\t parameter2);\n" 14549 "\t}\n" 14550 "};", 14551 Tab); 14552 verifyFormat("#define A \\\n" 14553 "\tvoid f() { \\\n" 14554 "\t\tsomeFunction( \\\n" 14555 "\t\t parameter1, \\\n" 14556 "\t\t parameter2); \\\n" 14557 "\t}", 14558 Tab); 14559 Tab.TabWidth = 4; 14560 Tab.IndentWidth = 8; 14561 verifyFormat("class TabWidth4Indent8 {\n" 14562 "\t\tvoid f() {\n" 14563 "\t\t\t\tsomeFunction(parameter1,\n" 14564 "\t\t\t\t\t\t\t parameter2);\n" 14565 "\t\t}\n" 14566 "};", 14567 Tab); 14568 Tab.TabWidth = 4; 14569 Tab.IndentWidth = 4; 14570 verifyFormat("class TabWidth4Indent4 {\n" 14571 "\tvoid f() {\n" 14572 "\t\tsomeFunction(parameter1,\n" 14573 "\t\t\t\t\t parameter2);\n" 14574 "\t}\n" 14575 "};", 14576 Tab); 14577 Tab.TabWidth = 8; 14578 Tab.IndentWidth = 4; 14579 verifyFormat("class TabWidth8Indent4 {\n" 14580 " void f() {\n" 14581 "\tsomeFunction(parameter1,\n" 14582 "\t\t parameter2);\n" 14583 " }\n" 14584 "};", 14585 Tab); 14586 Tab.TabWidth = 8; 14587 Tab.IndentWidth = 8; 14588 EXPECT_EQ("/*\n" 14589 "\t a\t\tcomment\n" 14590 "\t in multiple lines\n" 14591 " */", 14592 format(" /*\t \t \n" 14593 " \t \t a\t\tcomment\t \t\n" 14594 " \t \t in multiple lines\t\n" 14595 " \t */", 14596 Tab)); 14597 verifyFormat("{\n" 14598 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14599 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14600 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14601 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14602 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14603 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14604 "};", 14605 Tab); 14606 verifyFormat("enum AA {\n" 14607 "\ta1, // Force multiple lines\n" 14608 "\ta2,\n" 14609 "\ta3\n" 14610 "};", 14611 Tab); 14612 EXPECT_EQ("if (aaaaaaaa && // q\n" 14613 " bb) // w\n" 14614 "\t;", 14615 format("if (aaaaaaaa &&// q\n" 14616 "bb)// w\n" 14617 ";", 14618 Tab)); 14619 verifyFormat("class X {\n" 14620 "\tvoid f() {\n" 14621 "\t\tsomeFunction(parameter1,\n" 14622 "\t\t\t parameter2);\n" 14623 "\t}\n" 14624 "};", 14625 Tab); 14626 verifyFormat("{\n" 14627 "\tQ(\n" 14628 "\t {\n" 14629 "\t\t int a;\n" 14630 "\t\t someFunction(aaaaaaaa,\n" 14631 "\t\t\t\t bbbbbbb);\n" 14632 "\t },\n" 14633 "\t p);\n" 14634 "}", 14635 Tab); 14636 EXPECT_EQ("{\n" 14637 "\t/* aaaa\n" 14638 "\t bbbb */\n" 14639 "}", 14640 format("{\n" 14641 "/* aaaa\n" 14642 " bbbb */\n" 14643 "}", 14644 Tab)); 14645 EXPECT_EQ("{\n" 14646 "\t/*\n" 14647 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14648 "\t bbbbbbbbbbbbb\n" 14649 "\t*/\n" 14650 "}", 14651 format("{\n" 14652 "/*\n" 14653 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14654 "*/\n" 14655 "}", 14656 Tab)); 14657 EXPECT_EQ("{\n" 14658 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14659 "\t// bbbbbbbbbbbbb\n" 14660 "}", 14661 format("{\n" 14662 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14663 "}", 14664 Tab)); 14665 EXPECT_EQ("{\n" 14666 "\t/*\n" 14667 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14668 "\t bbbbbbbbbbbbb\n" 14669 "\t*/\n" 14670 "}", 14671 format("{\n" 14672 "\t/*\n" 14673 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14674 "\t*/\n" 14675 "}", 14676 Tab)); 14677 EXPECT_EQ("{\n" 14678 "\t/*\n" 14679 "\n" 14680 "\t*/\n" 14681 "}", 14682 format("{\n" 14683 "\t/*\n" 14684 "\n" 14685 "\t*/\n" 14686 "}", 14687 Tab)); 14688 EXPECT_EQ("{\n" 14689 "\t/*\n" 14690 " asdf\n" 14691 "\t*/\n" 14692 "}", 14693 format("{\n" 14694 "\t/*\n" 14695 " asdf\n" 14696 "\t*/\n" 14697 "}", 14698 Tab)); 14699 EXPECT_EQ("/* some\n" 14700 " comment */", 14701 format(" \t \t /* some\n" 14702 " \t \t comment */", 14703 Tab)); 14704 EXPECT_EQ("int a; /* some\n" 14705 " comment */", 14706 format(" \t \t int a; /* some\n" 14707 " \t \t comment */", 14708 Tab)); 14709 EXPECT_EQ("int a; /* some\n" 14710 "comment */", 14711 format(" \t \t int\ta; /* some\n" 14712 " \t \t comment */", 14713 Tab)); 14714 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14715 " comment */", 14716 format(" \t \t f(\"\t\t\"); /* some\n" 14717 " \t \t comment */", 14718 Tab)); 14719 EXPECT_EQ("{\n" 14720 "\t/*\n" 14721 "\t * Comment\n" 14722 "\t */\n" 14723 "\tint i;\n" 14724 "}", 14725 format("{\n" 14726 "\t/*\n" 14727 "\t * Comment\n" 14728 "\t */\n" 14729 "\t int i;\n" 14730 "}", 14731 Tab)); 14732 Tab.TabWidth = 2; 14733 Tab.IndentWidth = 2; 14734 EXPECT_EQ("{\n" 14735 "\t/* aaaa\n" 14736 "\t\t bbbb */\n" 14737 "}", 14738 format("{\n" 14739 "/* aaaa\n" 14740 "\t bbbb */\n" 14741 "}", 14742 Tab)); 14743 EXPECT_EQ("{\n" 14744 "\t/*\n" 14745 "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14746 "\t\tbbbbbbbbbbbbb\n" 14747 "\t*/\n" 14748 "}", 14749 format("{\n" 14750 "/*\n" 14751 "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14752 "*/\n" 14753 "}", 14754 Tab)); 14755 Tab.AlignConsecutiveAssignments.Enabled = true; 14756 Tab.AlignConsecutiveDeclarations.Enabled = true; 14757 Tab.TabWidth = 4; 14758 Tab.IndentWidth = 4; 14759 verifyFormat("class Assign {\n" 14760 "\tvoid f() {\n" 14761 "\t\tint x = 123;\n" 14762 "\t\tint random = 4;\n" 14763 "\t\tstd::string alphabet =\n" 14764 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n" 14765 "\t}\n" 14766 "};", 14767 Tab); 14768 14769 Tab.UseTab = FormatStyle::UT_AlignWithSpaces; 14770 Tab.TabWidth = 8; 14771 Tab.IndentWidth = 8; 14772 EXPECT_EQ("if (aaaaaaaa && // q\n" 14773 " bb) // w\n" 14774 "\t;", 14775 format("if (aaaaaaaa &&// q\n" 14776 "bb)// w\n" 14777 ";", 14778 Tab)); 14779 EXPECT_EQ("if (aaa && bbb) // w\n" 14780 "\t;", 14781 format("if(aaa&&bbb)// w\n" 14782 ";", 14783 Tab)); 14784 verifyFormat("class X {\n" 14785 "\tvoid f() {\n" 14786 "\t\tsomeFunction(parameter1,\n" 14787 "\t\t parameter2);\n" 14788 "\t}\n" 14789 "};", 14790 Tab); 14791 verifyFormat("#define A \\\n" 14792 "\tvoid f() { \\\n" 14793 "\t\tsomeFunction( \\\n" 14794 "\t\t parameter1, \\\n" 14795 "\t\t parameter2); \\\n" 14796 "\t}", 14797 Tab); 14798 Tab.TabWidth = 4; 14799 Tab.IndentWidth = 8; 14800 verifyFormat("class TabWidth4Indent8 {\n" 14801 "\t\tvoid f() {\n" 14802 "\t\t\t\tsomeFunction(parameter1,\n" 14803 "\t\t\t\t parameter2);\n" 14804 "\t\t}\n" 14805 "};", 14806 Tab); 14807 Tab.TabWidth = 4; 14808 Tab.IndentWidth = 4; 14809 verifyFormat("class TabWidth4Indent4 {\n" 14810 "\tvoid f() {\n" 14811 "\t\tsomeFunction(parameter1,\n" 14812 "\t\t parameter2);\n" 14813 "\t}\n" 14814 "};", 14815 Tab); 14816 Tab.TabWidth = 8; 14817 Tab.IndentWidth = 4; 14818 verifyFormat("class TabWidth8Indent4 {\n" 14819 " void f() {\n" 14820 "\tsomeFunction(parameter1,\n" 14821 "\t parameter2);\n" 14822 " }\n" 14823 "};", 14824 Tab); 14825 Tab.TabWidth = 8; 14826 Tab.IndentWidth = 8; 14827 EXPECT_EQ("/*\n" 14828 " a\t\tcomment\n" 14829 " in multiple lines\n" 14830 " */", 14831 format(" /*\t \t \n" 14832 " \t \t a\t\tcomment\t \t\n" 14833 " \t \t in multiple lines\t\n" 14834 " \t */", 14835 Tab)); 14836 verifyFormat("{\n" 14837 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14838 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14839 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14840 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14841 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14842 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14843 "};", 14844 Tab); 14845 verifyFormat("enum AA {\n" 14846 "\ta1, // Force multiple lines\n" 14847 "\ta2,\n" 14848 "\ta3\n" 14849 "};", 14850 Tab); 14851 EXPECT_EQ("if (aaaaaaaa && // q\n" 14852 " bb) // w\n" 14853 "\t;", 14854 format("if (aaaaaaaa &&// q\n" 14855 "bb)// w\n" 14856 ";", 14857 Tab)); 14858 verifyFormat("class X {\n" 14859 "\tvoid f() {\n" 14860 "\t\tsomeFunction(parameter1,\n" 14861 "\t\t parameter2);\n" 14862 "\t}\n" 14863 "};", 14864 Tab); 14865 verifyFormat("{\n" 14866 "\tQ(\n" 14867 "\t {\n" 14868 "\t\t int a;\n" 14869 "\t\t someFunction(aaaaaaaa,\n" 14870 "\t\t bbbbbbb);\n" 14871 "\t },\n" 14872 "\t p);\n" 14873 "}", 14874 Tab); 14875 EXPECT_EQ("{\n" 14876 "\t/* aaaa\n" 14877 "\t bbbb */\n" 14878 "}", 14879 format("{\n" 14880 "/* aaaa\n" 14881 " bbbb */\n" 14882 "}", 14883 Tab)); 14884 EXPECT_EQ("{\n" 14885 "\t/*\n" 14886 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14887 "\t bbbbbbbbbbbbb\n" 14888 "\t*/\n" 14889 "}", 14890 format("{\n" 14891 "/*\n" 14892 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14893 "*/\n" 14894 "}", 14895 Tab)); 14896 EXPECT_EQ("{\n" 14897 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14898 "\t// bbbbbbbbbbbbb\n" 14899 "}", 14900 format("{\n" 14901 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14902 "}", 14903 Tab)); 14904 EXPECT_EQ("{\n" 14905 "\t/*\n" 14906 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14907 "\t bbbbbbbbbbbbb\n" 14908 "\t*/\n" 14909 "}", 14910 format("{\n" 14911 "\t/*\n" 14912 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14913 "\t*/\n" 14914 "}", 14915 Tab)); 14916 EXPECT_EQ("{\n" 14917 "\t/*\n" 14918 "\n" 14919 "\t*/\n" 14920 "}", 14921 format("{\n" 14922 "\t/*\n" 14923 "\n" 14924 "\t*/\n" 14925 "}", 14926 Tab)); 14927 EXPECT_EQ("{\n" 14928 "\t/*\n" 14929 " asdf\n" 14930 "\t*/\n" 14931 "}", 14932 format("{\n" 14933 "\t/*\n" 14934 " asdf\n" 14935 "\t*/\n" 14936 "}", 14937 Tab)); 14938 EXPECT_EQ("/* some\n" 14939 " comment */", 14940 format(" \t \t /* some\n" 14941 " \t \t comment */", 14942 Tab)); 14943 EXPECT_EQ("int a; /* some\n" 14944 " comment */", 14945 format(" \t \t int a; /* some\n" 14946 " \t \t comment */", 14947 Tab)); 14948 EXPECT_EQ("int a; /* some\n" 14949 "comment */", 14950 format(" \t \t int\ta; /* some\n" 14951 " \t \t comment */", 14952 Tab)); 14953 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14954 " comment */", 14955 format(" \t \t f(\"\t\t\"); /* some\n" 14956 " \t \t comment */", 14957 Tab)); 14958 EXPECT_EQ("{\n" 14959 "\t/*\n" 14960 "\t * Comment\n" 14961 "\t */\n" 14962 "\tint i;\n" 14963 "}", 14964 format("{\n" 14965 "\t/*\n" 14966 "\t * Comment\n" 14967 "\t */\n" 14968 "\t int i;\n" 14969 "}", 14970 Tab)); 14971 Tab.TabWidth = 2; 14972 Tab.IndentWidth = 2; 14973 EXPECT_EQ("{\n" 14974 "\t/* aaaa\n" 14975 "\t bbbb */\n" 14976 "}", 14977 format("{\n" 14978 "/* aaaa\n" 14979 " bbbb */\n" 14980 "}", 14981 Tab)); 14982 EXPECT_EQ("{\n" 14983 "\t/*\n" 14984 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14985 "\t bbbbbbbbbbbbb\n" 14986 "\t*/\n" 14987 "}", 14988 format("{\n" 14989 "/*\n" 14990 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14991 "*/\n" 14992 "}", 14993 Tab)); 14994 Tab.AlignConsecutiveAssignments.Enabled = true; 14995 Tab.AlignConsecutiveDeclarations.Enabled = true; 14996 Tab.TabWidth = 4; 14997 Tab.IndentWidth = 4; 14998 verifyFormat("class Assign {\n" 14999 "\tvoid f() {\n" 15000 "\t\tint x = 123;\n" 15001 "\t\tint random = 4;\n" 15002 "\t\tstd::string alphabet =\n" 15003 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n" 15004 "\t}\n" 15005 "};", 15006 Tab); 15007 Tab.AlignOperands = FormatStyle::OAS_Align; 15008 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n" 15009 " cccccccccccccccccccc;", 15010 Tab); 15011 // no alignment 15012 verifyFormat("int aaaaaaaaaa =\n" 15013 "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 15014 Tab); 15015 verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n" 15016 " : bbbbbbbbbbbbbb ? 222222222222222\n" 15017 " : 333333333333333;", 15018 Tab); 15019 Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 15020 Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator; 15021 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n" 15022 " + cccccccccccccccccccc;", 15023 Tab); 15024 } 15025 15026 TEST_F(FormatTest, ZeroTabWidth) { 15027 FormatStyle Tab = getLLVMStyleWithColumns(42); 15028 Tab.IndentWidth = 8; 15029 Tab.UseTab = FormatStyle::UT_Never; 15030 Tab.TabWidth = 0; 15031 EXPECT_EQ("void a(){\n" 15032 " // line starts with '\t'\n" 15033 "};", 15034 format("void a(){\n" 15035 "\t// line starts with '\t'\n" 15036 "};", 15037 Tab)); 15038 15039 EXPECT_EQ("void a(){\n" 15040 " // line starts with '\t'\n" 15041 "};", 15042 format("void a(){\n" 15043 "\t\t// line starts with '\t'\n" 15044 "};", 15045 Tab)); 15046 15047 Tab.UseTab = FormatStyle::UT_ForIndentation; 15048 EXPECT_EQ("void a(){\n" 15049 " // line starts with '\t'\n" 15050 "};", 15051 format("void a(){\n" 15052 "\t// line starts with '\t'\n" 15053 "};", 15054 Tab)); 15055 15056 EXPECT_EQ("void a(){\n" 15057 " // line starts with '\t'\n" 15058 "};", 15059 format("void a(){\n" 15060 "\t\t// line starts with '\t'\n" 15061 "};", 15062 Tab)); 15063 15064 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation; 15065 EXPECT_EQ("void a(){\n" 15066 " // line starts with '\t'\n" 15067 "};", 15068 format("void a(){\n" 15069 "\t// line starts with '\t'\n" 15070 "};", 15071 Tab)); 15072 15073 EXPECT_EQ("void a(){\n" 15074 " // line starts with '\t'\n" 15075 "};", 15076 format("void a(){\n" 15077 "\t\t// line starts with '\t'\n" 15078 "};", 15079 Tab)); 15080 15081 Tab.UseTab = FormatStyle::UT_AlignWithSpaces; 15082 EXPECT_EQ("void a(){\n" 15083 " // line starts with '\t'\n" 15084 "};", 15085 format("void a(){\n" 15086 "\t// line starts with '\t'\n" 15087 "};", 15088 Tab)); 15089 15090 EXPECT_EQ("void a(){\n" 15091 " // line starts with '\t'\n" 15092 "};", 15093 format("void a(){\n" 15094 "\t\t// line starts with '\t'\n" 15095 "};", 15096 Tab)); 15097 15098 Tab.UseTab = FormatStyle::UT_Always; 15099 EXPECT_EQ("void a(){\n" 15100 "// line starts with '\t'\n" 15101 "};", 15102 format("void a(){\n" 15103 "\t// line starts with '\t'\n" 15104 "};", 15105 Tab)); 15106 15107 EXPECT_EQ("void a(){\n" 15108 "// line starts with '\t'\n" 15109 "};", 15110 format("void a(){\n" 15111 "\t\t// line starts with '\t'\n" 15112 "};", 15113 Tab)); 15114 } 15115 15116 TEST_F(FormatTest, CalculatesOriginalColumn) { 15117 EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 15118 "q\"; /* some\n" 15119 " comment */", 15120 format(" \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 15121 "q\"; /* some\n" 15122 " comment */", 15123 getLLVMStyle())); 15124 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n" 15125 "/* some\n" 15126 " comment */", 15127 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n" 15128 " /* some\n" 15129 " comment */", 15130 getLLVMStyle())); 15131 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 15132 "qqq\n" 15133 "/* some\n" 15134 " comment */", 15135 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 15136 "qqq\n" 15137 " /* some\n" 15138 " comment */", 15139 getLLVMStyle())); 15140 EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 15141 "wwww; /* some\n" 15142 " comment */", 15143 format(" inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 15144 "wwww; /* some\n" 15145 " comment */", 15146 getLLVMStyle())); 15147 } 15148 15149 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) { 15150 FormatStyle NoSpace = getLLVMStyle(); 15151 NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never; 15152 15153 verifyFormat("while(true)\n" 15154 " continue;", 15155 NoSpace); 15156 verifyFormat("for(;;)\n" 15157 " continue;", 15158 NoSpace); 15159 verifyFormat("if(true)\n" 15160 " f();\n" 15161 "else if(true)\n" 15162 " f();", 15163 NoSpace); 15164 verifyFormat("do {\n" 15165 " do_something();\n" 15166 "} while(something());", 15167 NoSpace); 15168 verifyFormat("switch(x) {\n" 15169 "default:\n" 15170 " break;\n" 15171 "}", 15172 NoSpace); 15173 verifyFormat("auto i = std::make_unique<int>(5);", NoSpace); 15174 verifyFormat("size_t x = sizeof(x);", NoSpace); 15175 verifyFormat("auto f(int x) -> decltype(x);", NoSpace); 15176 verifyFormat("auto f(int x) -> typeof(x);", NoSpace); 15177 verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace); 15178 verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace); 15179 verifyFormat("int f(T x) noexcept(x.create());", NoSpace); 15180 verifyFormat("alignas(128) char a[128];", NoSpace); 15181 verifyFormat("size_t x = alignof(MyType);", NoSpace); 15182 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace); 15183 verifyFormat("int f() throw(Deprecated);", NoSpace); 15184 verifyFormat("typedef void (*cb)(int);", NoSpace); 15185 verifyFormat("T A::operator()();", NoSpace); 15186 verifyFormat("X A::operator++(T);", NoSpace); 15187 verifyFormat("auto lambda = []() { return 0; };", NoSpace); 15188 15189 FormatStyle Space = getLLVMStyle(); 15190 Space.SpaceBeforeParens = FormatStyle::SBPO_Always; 15191 15192 verifyFormat("int f ();", Space); 15193 verifyFormat("void f (int a, T b) {\n" 15194 " while (true)\n" 15195 " continue;\n" 15196 "}", 15197 Space); 15198 verifyFormat("if (true)\n" 15199 " f ();\n" 15200 "else if (true)\n" 15201 " f ();", 15202 Space); 15203 verifyFormat("do {\n" 15204 " do_something ();\n" 15205 "} while (something ());", 15206 Space); 15207 verifyFormat("switch (x) {\n" 15208 "default:\n" 15209 " break;\n" 15210 "}", 15211 Space); 15212 verifyFormat("A::A () : a (1) {}", Space); 15213 verifyFormat("void f () __attribute__ ((asdf));", Space); 15214 verifyFormat("*(&a + 1);\n" 15215 "&((&a)[1]);\n" 15216 "a[(b + c) * d];\n" 15217 "(((a + 1) * 2) + 3) * 4;", 15218 Space); 15219 verifyFormat("#define A(x) x", Space); 15220 verifyFormat("#define A (x) x", Space); 15221 verifyFormat("#if defined(x)\n" 15222 "#endif", 15223 Space); 15224 verifyFormat("auto i = std::make_unique<int> (5);", Space); 15225 verifyFormat("size_t x = sizeof (x);", Space); 15226 verifyFormat("auto f (int x) -> decltype (x);", Space); 15227 verifyFormat("auto f (int x) -> typeof (x);", Space); 15228 verifyFormat("auto f (int x) -> _Atomic (x);", Space); 15229 verifyFormat("auto f (int x) -> __underlying_type (x);", Space); 15230 verifyFormat("int f (T x) noexcept (x.create ());", Space); 15231 verifyFormat("alignas (128) char a[128];", Space); 15232 verifyFormat("size_t x = alignof (MyType);", Space); 15233 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space); 15234 verifyFormat("int f () throw (Deprecated);", Space); 15235 verifyFormat("typedef void (*cb) (int);", Space); 15236 // FIXME these tests regressed behaviour. 15237 // verifyFormat("T A::operator() ();", Space); 15238 // verifyFormat("X A::operator++ (T);", Space); 15239 verifyFormat("auto lambda = [] () { return 0; };", Space); 15240 verifyFormat("int x = int (y);", Space); 15241 verifyFormat("#define F(...) __VA_OPT__ (__VA_ARGS__)", Space); 15242 verifyFormat("__builtin_LINE ()", Space); 15243 verifyFormat("__builtin_UNKNOWN ()", Space); 15244 15245 FormatStyle SomeSpace = getLLVMStyle(); 15246 SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses; 15247 15248 verifyFormat("[]() -> float {}", SomeSpace); 15249 verifyFormat("[] (auto foo) {}", SomeSpace); 15250 verifyFormat("[foo]() -> int {}", SomeSpace); 15251 verifyFormat("int f();", SomeSpace); 15252 verifyFormat("void f (int a, T b) {\n" 15253 " while (true)\n" 15254 " continue;\n" 15255 "}", 15256 SomeSpace); 15257 verifyFormat("if (true)\n" 15258 " f();\n" 15259 "else if (true)\n" 15260 " f();", 15261 SomeSpace); 15262 verifyFormat("do {\n" 15263 " do_something();\n" 15264 "} while (something());", 15265 SomeSpace); 15266 verifyFormat("switch (x) {\n" 15267 "default:\n" 15268 " break;\n" 15269 "}", 15270 SomeSpace); 15271 verifyFormat("A::A() : a (1) {}", SomeSpace); 15272 verifyFormat("void f() __attribute__ ((asdf));", SomeSpace); 15273 verifyFormat("*(&a + 1);\n" 15274 "&((&a)[1]);\n" 15275 "a[(b + c) * d];\n" 15276 "(((a + 1) * 2) + 3) * 4;", 15277 SomeSpace); 15278 verifyFormat("#define A(x) x", SomeSpace); 15279 verifyFormat("#define A (x) x", SomeSpace); 15280 verifyFormat("#if defined(x)\n" 15281 "#endif", 15282 SomeSpace); 15283 verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace); 15284 verifyFormat("size_t x = sizeof (x);", SomeSpace); 15285 verifyFormat("auto f (int x) -> decltype (x);", SomeSpace); 15286 verifyFormat("auto f (int x) -> typeof (x);", SomeSpace); 15287 verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace); 15288 verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace); 15289 verifyFormat("int f (T x) noexcept (x.create());", SomeSpace); 15290 verifyFormat("alignas (128) char a[128];", SomeSpace); 15291 verifyFormat("size_t x = alignof (MyType);", SomeSpace); 15292 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", 15293 SomeSpace); 15294 verifyFormat("int f() throw (Deprecated);", SomeSpace); 15295 verifyFormat("typedef void (*cb) (int);", SomeSpace); 15296 verifyFormat("T A::operator()();", SomeSpace); 15297 // FIXME these tests regressed behaviour. 15298 // verifyFormat("X A::operator++ (T);", SomeSpace); 15299 verifyFormat("int x = int (y);", SomeSpace); 15300 verifyFormat("auto lambda = []() { return 0; };", SomeSpace); 15301 15302 FormatStyle SpaceControlStatements = getLLVMStyle(); 15303 SpaceControlStatements.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15304 SpaceControlStatements.SpaceBeforeParensOptions.AfterControlStatements = true; 15305 15306 verifyFormat("while (true)\n" 15307 " continue;", 15308 SpaceControlStatements); 15309 verifyFormat("if (true)\n" 15310 " f();\n" 15311 "else if (true)\n" 15312 " f();", 15313 SpaceControlStatements); 15314 verifyFormat("for (;;) {\n" 15315 " do_something();\n" 15316 "}", 15317 SpaceControlStatements); 15318 verifyFormat("do {\n" 15319 " do_something();\n" 15320 "} while (something());", 15321 SpaceControlStatements); 15322 verifyFormat("switch (x) {\n" 15323 "default:\n" 15324 " break;\n" 15325 "}", 15326 SpaceControlStatements); 15327 15328 FormatStyle SpaceFuncDecl = getLLVMStyle(); 15329 SpaceFuncDecl.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15330 SpaceFuncDecl.SpaceBeforeParensOptions.AfterFunctionDeclarationName = true; 15331 15332 verifyFormat("int f ();", SpaceFuncDecl); 15333 verifyFormat("void f(int a, T b) {}", SpaceFuncDecl); 15334 verifyFormat("A::A() : a(1) {}", SpaceFuncDecl); 15335 verifyFormat("void f () __attribute__((asdf));", SpaceFuncDecl); 15336 verifyFormat("#define A(x) x", SpaceFuncDecl); 15337 verifyFormat("#define A (x) x", SpaceFuncDecl); 15338 verifyFormat("#if defined(x)\n" 15339 "#endif", 15340 SpaceFuncDecl); 15341 verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDecl); 15342 verifyFormat("size_t x = sizeof(x);", SpaceFuncDecl); 15343 verifyFormat("auto f (int x) -> decltype(x);", SpaceFuncDecl); 15344 verifyFormat("auto f (int x) -> typeof(x);", SpaceFuncDecl); 15345 verifyFormat("auto f (int x) -> _Atomic(x);", SpaceFuncDecl); 15346 verifyFormat("auto f (int x) -> __underlying_type(x);", SpaceFuncDecl); 15347 verifyFormat("int f (T x) noexcept(x.create());", SpaceFuncDecl); 15348 verifyFormat("alignas(128) char a[128];", SpaceFuncDecl); 15349 verifyFormat("size_t x = alignof(MyType);", SpaceFuncDecl); 15350 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", 15351 SpaceFuncDecl); 15352 verifyFormat("int f () throw(Deprecated);", SpaceFuncDecl); 15353 verifyFormat("typedef void (*cb)(int);", SpaceFuncDecl); 15354 // FIXME these tests regressed behaviour. 15355 // verifyFormat("T A::operator() ();", SpaceFuncDecl); 15356 // verifyFormat("X A::operator++ (T);", SpaceFuncDecl); 15357 verifyFormat("T A::operator()() {}", SpaceFuncDecl); 15358 verifyFormat("auto lambda = []() { return 0; };", SpaceFuncDecl); 15359 verifyFormat("int x = int(y);", SpaceFuncDecl); 15360 verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}", 15361 SpaceFuncDecl); 15362 15363 FormatStyle SpaceFuncDef = getLLVMStyle(); 15364 SpaceFuncDef.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15365 SpaceFuncDef.SpaceBeforeParensOptions.AfterFunctionDefinitionName = true; 15366 15367 verifyFormat("int f();", SpaceFuncDef); 15368 verifyFormat("void f (int a, T b) {}", SpaceFuncDef); 15369 verifyFormat("A::A() : a(1) {}", SpaceFuncDef); 15370 verifyFormat("void f() __attribute__((asdf));", SpaceFuncDef); 15371 verifyFormat("#define A(x) x", SpaceFuncDef); 15372 verifyFormat("#define A (x) x", SpaceFuncDef); 15373 verifyFormat("#if defined(x)\n" 15374 "#endif", 15375 SpaceFuncDef); 15376 verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDef); 15377 verifyFormat("size_t x = sizeof(x);", SpaceFuncDef); 15378 verifyFormat("auto f(int x) -> decltype(x);", SpaceFuncDef); 15379 verifyFormat("auto f(int x) -> typeof(x);", SpaceFuncDef); 15380 verifyFormat("auto f(int x) -> _Atomic(x);", SpaceFuncDef); 15381 verifyFormat("auto f(int x) -> __underlying_type(x);", SpaceFuncDef); 15382 verifyFormat("int f(T x) noexcept(x.create());", SpaceFuncDef); 15383 verifyFormat("alignas(128) char a[128];", SpaceFuncDef); 15384 verifyFormat("size_t x = alignof(MyType);", SpaceFuncDef); 15385 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", 15386 SpaceFuncDef); 15387 verifyFormat("int f() throw(Deprecated);", SpaceFuncDef); 15388 verifyFormat("typedef void (*cb)(int);", SpaceFuncDef); 15389 verifyFormat("T A::operator()();", SpaceFuncDef); 15390 verifyFormat("X A::operator++(T);", SpaceFuncDef); 15391 // verifyFormat("T A::operator() () {}", SpaceFuncDef); 15392 verifyFormat("auto lambda = [] () { return 0; };", SpaceFuncDef); 15393 verifyFormat("int x = int(y);", SpaceFuncDef); 15394 verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}", 15395 SpaceFuncDef); 15396 15397 FormatStyle SpaceIfMacros = getLLVMStyle(); 15398 SpaceIfMacros.IfMacros.clear(); 15399 SpaceIfMacros.IfMacros.push_back("MYIF"); 15400 SpaceIfMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15401 SpaceIfMacros.SpaceBeforeParensOptions.AfterIfMacros = true; 15402 verifyFormat("MYIF (a)\n return;", SpaceIfMacros); 15403 verifyFormat("MYIF (a)\n return;\nelse MYIF (b)\n return;", SpaceIfMacros); 15404 verifyFormat("MYIF (a)\n return;\nelse\n return;", SpaceIfMacros); 15405 15406 FormatStyle SpaceForeachMacros = getLLVMStyle(); 15407 EXPECT_EQ(SpaceForeachMacros.AllowShortBlocksOnASingleLine, 15408 FormatStyle::SBS_Never); 15409 EXPECT_EQ(SpaceForeachMacros.AllowShortLoopsOnASingleLine, false); 15410 SpaceForeachMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15411 SpaceForeachMacros.SpaceBeforeParensOptions.AfterForeachMacros = true; 15412 verifyFormat("for (;;) {\n" 15413 "}", 15414 SpaceForeachMacros); 15415 verifyFormat("foreach (Item *item, itemlist) {\n" 15416 "}", 15417 SpaceForeachMacros); 15418 verifyFormat("Q_FOREACH (Item *item, itemlist) {\n" 15419 "}", 15420 SpaceForeachMacros); 15421 verifyFormat("BOOST_FOREACH (Item *item, itemlist) {\n" 15422 "}", 15423 SpaceForeachMacros); 15424 verifyFormat("UNKNOWN_FOREACH(Item *item, itemlist) {}", SpaceForeachMacros); 15425 15426 FormatStyle SomeSpace2 = getLLVMStyle(); 15427 SomeSpace2.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15428 SomeSpace2.SpaceBeforeParensOptions.BeforeNonEmptyParentheses = true; 15429 verifyFormat("[]() -> float {}", SomeSpace2); 15430 verifyFormat("[] (auto foo) {}", SomeSpace2); 15431 verifyFormat("[foo]() -> int {}", SomeSpace2); 15432 verifyFormat("int f();", SomeSpace2); 15433 verifyFormat("void f (int a, T b) {\n" 15434 " while (true)\n" 15435 " continue;\n" 15436 "}", 15437 SomeSpace2); 15438 verifyFormat("if (true)\n" 15439 " f();\n" 15440 "else if (true)\n" 15441 " f();", 15442 SomeSpace2); 15443 verifyFormat("do {\n" 15444 " do_something();\n" 15445 "} while (something());", 15446 SomeSpace2); 15447 verifyFormat("switch (x) {\n" 15448 "default:\n" 15449 " break;\n" 15450 "}", 15451 SomeSpace2); 15452 verifyFormat("A::A() : a (1) {}", SomeSpace2); 15453 verifyFormat("void f() __attribute__ ((asdf));", SomeSpace2); 15454 verifyFormat("*(&a + 1);\n" 15455 "&((&a)[1]);\n" 15456 "a[(b + c) * d];\n" 15457 "(((a + 1) * 2) + 3) * 4;", 15458 SomeSpace2); 15459 verifyFormat("#define A(x) x", SomeSpace2); 15460 verifyFormat("#define A (x) x", SomeSpace2); 15461 verifyFormat("#if defined(x)\n" 15462 "#endif", 15463 SomeSpace2); 15464 verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace2); 15465 verifyFormat("size_t x = sizeof (x);", SomeSpace2); 15466 verifyFormat("auto f (int x) -> decltype (x);", SomeSpace2); 15467 verifyFormat("auto f (int x) -> typeof (x);", SomeSpace2); 15468 verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace2); 15469 verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace2); 15470 verifyFormat("int f (T x) noexcept (x.create());", SomeSpace2); 15471 verifyFormat("alignas (128) char a[128];", SomeSpace2); 15472 verifyFormat("size_t x = alignof (MyType);", SomeSpace2); 15473 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", 15474 SomeSpace2); 15475 verifyFormat("int f() throw (Deprecated);", SomeSpace2); 15476 verifyFormat("typedef void (*cb) (int);", SomeSpace2); 15477 verifyFormat("T A::operator()();", SomeSpace2); 15478 // verifyFormat("X A::operator++ (T);", SomeSpace2); 15479 verifyFormat("int x = int (y);", SomeSpace2); 15480 verifyFormat("auto lambda = []() { return 0; };", SomeSpace2); 15481 15482 FormatStyle SpaceAfterOverloadedOperator = getLLVMStyle(); 15483 SpaceAfterOverloadedOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15484 SpaceAfterOverloadedOperator.SpaceBeforeParensOptions 15485 .AfterOverloadedOperator = true; 15486 15487 verifyFormat("auto operator++ () -> int;", SpaceAfterOverloadedOperator); 15488 verifyFormat("X A::operator++ ();", SpaceAfterOverloadedOperator); 15489 verifyFormat("some_object.operator++ ();", SpaceAfterOverloadedOperator); 15490 verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator); 15491 15492 SpaceAfterOverloadedOperator.SpaceBeforeParensOptions 15493 .AfterOverloadedOperator = false; 15494 15495 verifyFormat("auto operator++() -> int;", SpaceAfterOverloadedOperator); 15496 verifyFormat("X A::operator++();", SpaceAfterOverloadedOperator); 15497 verifyFormat("some_object.operator++();", SpaceAfterOverloadedOperator); 15498 verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator); 15499 15500 auto SpaceAfterRequires = getLLVMStyle(); 15501 SpaceAfterRequires.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15502 EXPECT_FALSE( 15503 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause); 15504 EXPECT_FALSE( 15505 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression); 15506 verifyFormat("void f(auto x)\n" 15507 " requires requires(int i) { x + i; }\n" 15508 "{}", 15509 SpaceAfterRequires); 15510 verifyFormat("void f(auto x)\n" 15511 " requires(requires(int i) { x + i; })\n" 15512 "{}", 15513 SpaceAfterRequires); 15514 verifyFormat("if (requires(int i) { x + i; })\n" 15515 " return;", 15516 SpaceAfterRequires); 15517 verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires); 15518 verifyFormat("template <typename T>\n" 15519 " requires(Foo<T>)\n" 15520 "class Bar;", 15521 SpaceAfterRequires); 15522 15523 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true; 15524 verifyFormat("void f(auto x)\n" 15525 " requires requires(int i) { x + i; }\n" 15526 "{}", 15527 SpaceAfterRequires); 15528 verifyFormat("void f(auto x)\n" 15529 " requires (requires(int i) { x + i; })\n" 15530 "{}", 15531 SpaceAfterRequires); 15532 verifyFormat("if (requires(int i) { x + i; })\n" 15533 " return;", 15534 SpaceAfterRequires); 15535 verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires); 15536 verifyFormat("template <typename T>\n" 15537 " requires (Foo<T>)\n" 15538 "class Bar;", 15539 SpaceAfterRequires); 15540 15541 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = false; 15542 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression = true; 15543 verifyFormat("void f(auto x)\n" 15544 " requires requires (int i) { x + i; }\n" 15545 "{}", 15546 SpaceAfterRequires); 15547 verifyFormat("void f(auto x)\n" 15548 " requires(requires (int i) { x + i; })\n" 15549 "{}", 15550 SpaceAfterRequires); 15551 verifyFormat("if (requires (int i) { x + i; })\n" 15552 " return;", 15553 SpaceAfterRequires); 15554 verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires); 15555 verifyFormat("template <typename T>\n" 15556 " requires(Foo<T>)\n" 15557 "class Bar;", 15558 SpaceAfterRequires); 15559 15560 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true; 15561 verifyFormat("void f(auto x)\n" 15562 " requires requires (int i) { x + i; }\n" 15563 "{}", 15564 SpaceAfterRequires); 15565 verifyFormat("void f(auto x)\n" 15566 " requires (requires (int i) { x + i; })\n" 15567 "{}", 15568 SpaceAfterRequires); 15569 verifyFormat("if (requires (int i) { x + i; })\n" 15570 " return;", 15571 SpaceAfterRequires); 15572 verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires); 15573 verifyFormat("template <typename T>\n" 15574 " requires (Foo<T>)\n" 15575 "class Bar;", 15576 SpaceAfterRequires); 15577 } 15578 15579 TEST_F(FormatTest, SpaceAfterLogicalNot) { 15580 FormatStyle Spaces = getLLVMStyle(); 15581 Spaces.SpaceAfterLogicalNot = true; 15582 15583 verifyFormat("bool x = ! y", Spaces); 15584 verifyFormat("if (! isFailure())", Spaces); 15585 verifyFormat("if (! (a && b))", Spaces); 15586 verifyFormat("\"Error!\"", Spaces); 15587 verifyFormat("! ! x", Spaces); 15588 } 15589 15590 TEST_F(FormatTest, ConfigurableSpacesInParentheses) { 15591 FormatStyle Spaces = getLLVMStyle(); 15592 15593 Spaces.SpacesInParentheses = true; 15594 verifyFormat("do_something( ::globalVar );", Spaces); 15595 verifyFormat("call( x, y, z );", Spaces); 15596 verifyFormat("call();", Spaces); 15597 verifyFormat("std::function<void( int, int )> callback;", Spaces); 15598 verifyFormat("void inFunction() { std::function<void( int, int )> fct; }", 15599 Spaces); 15600 verifyFormat("while ( (bool)1 )\n" 15601 " continue;", 15602 Spaces); 15603 verifyFormat("for ( ;; )\n" 15604 " continue;", 15605 Spaces); 15606 verifyFormat("if ( true )\n" 15607 " f();\n" 15608 "else if ( true )\n" 15609 " f();", 15610 Spaces); 15611 verifyFormat("do {\n" 15612 " do_something( (int)i );\n" 15613 "} while ( something() );", 15614 Spaces); 15615 verifyFormat("switch ( x ) {\n" 15616 "default:\n" 15617 " break;\n" 15618 "}", 15619 Spaces); 15620 15621 Spaces.SpacesInParentheses = false; 15622 Spaces.SpacesInCStyleCastParentheses = true; 15623 verifyFormat("Type *A = ( Type * )P;", Spaces); 15624 verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces); 15625 verifyFormat("x = ( int32 )y;", Spaces); 15626 verifyFormat("int a = ( int )(2.0f);", Spaces); 15627 verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces); 15628 verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces); 15629 verifyFormat("#define x (( int )-1)", Spaces); 15630 15631 // Run the first set of tests again with: 15632 Spaces.SpacesInParentheses = false; 15633 Spaces.SpaceInEmptyParentheses = true; 15634 Spaces.SpacesInCStyleCastParentheses = true; 15635 verifyFormat("call(x, y, z);", Spaces); 15636 verifyFormat("call( );", Spaces); 15637 verifyFormat("std::function<void(int, int)> callback;", Spaces); 15638 verifyFormat("while (( bool )1)\n" 15639 " continue;", 15640 Spaces); 15641 verifyFormat("for (;;)\n" 15642 " continue;", 15643 Spaces); 15644 verifyFormat("if (true)\n" 15645 " f( );\n" 15646 "else if (true)\n" 15647 " f( );", 15648 Spaces); 15649 verifyFormat("do {\n" 15650 " do_something(( int )i);\n" 15651 "} while (something( ));", 15652 Spaces); 15653 verifyFormat("switch (x) {\n" 15654 "default:\n" 15655 " break;\n" 15656 "}", 15657 Spaces); 15658 15659 // Run the first set of tests again with: 15660 Spaces.SpaceAfterCStyleCast = true; 15661 verifyFormat("call(x, y, z);", Spaces); 15662 verifyFormat("call( );", Spaces); 15663 verifyFormat("std::function<void(int, int)> callback;", Spaces); 15664 verifyFormat("while (( bool ) 1)\n" 15665 " continue;", 15666 Spaces); 15667 verifyFormat("for (;;)\n" 15668 " continue;", 15669 Spaces); 15670 verifyFormat("if (true)\n" 15671 " f( );\n" 15672 "else if (true)\n" 15673 " f( );", 15674 Spaces); 15675 verifyFormat("do {\n" 15676 " do_something(( int ) i);\n" 15677 "} while (something( ));", 15678 Spaces); 15679 verifyFormat("switch (x) {\n" 15680 "default:\n" 15681 " break;\n" 15682 "}", 15683 Spaces); 15684 verifyFormat("#define CONF_BOOL(x) ( bool * ) ( void * ) (x)", Spaces); 15685 verifyFormat("#define CONF_BOOL(x) ( bool * ) (x)", Spaces); 15686 verifyFormat("#define CONF_BOOL(x) ( bool ) (x)", Spaces); 15687 verifyFormat("bool *y = ( bool * ) ( void * ) (x);", Spaces); 15688 verifyFormat("bool *y = ( bool * ) (x);", Spaces); 15689 15690 // Run subset of tests again with: 15691 Spaces.SpacesInCStyleCastParentheses = false; 15692 Spaces.SpaceAfterCStyleCast = true; 15693 verifyFormat("while ((bool) 1)\n" 15694 " continue;", 15695 Spaces); 15696 verifyFormat("do {\n" 15697 " do_something((int) i);\n" 15698 "} while (something( ));", 15699 Spaces); 15700 15701 verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces); 15702 verifyFormat("size_t idx = (size_t) a;", Spaces); 15703 verifyFormat("size_t idx = (size_t) (a - 1);", Spaces); 15704 verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces); 15705 verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces); 15706 verifyFormat("size_t idx = (*foo)(a - 1);", Spaces); 15707 verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces); 15708 verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (x)", Spaces); 15709 verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (int) (x)", Spaces); 15710 verifyFormat("bool *y = (bool *) (void *) (x);", Spaces); 15711 verifyFormat("bool *y = (bool *) (void *) (int) (x);", Spaces); 15712 verifyFormat("bool *y = (bool *) (void *) (int) foo(x);", Spaces); 15713 Spaces.ColumnLimit = 80; 15714 Spaces.IndentWidth = 4; 15715 Spaces.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 15716 verifyFormat("void foo( ) {\n" 15717 " size_t foo = (*(function))(\n" 15718 " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, " 15719 "BarrrrrrrrrrrrLong,\n" 15720 " FoooooooooLooooong);\n" 15721 "}", 15722 Spaces); 15723 Spaces.SpaceAfterCStyleCast = false; 15724 verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces); 15725 verifyFormat("size_t idx = (size_t)a;", Spaces); 15726 verifyFormat("size_t idx = (size_t)(a - 1);", Spaces); 15727 verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces); 15728 verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces); 15729 verifyFormat("size_t idx = (*foo)(a - 1);", Spaces); 15730 verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces); 15731 15732 verifyFormat("void foo( ) {\n" 15733 " size_t foo = (*(function))(\n" 15734 " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, " 15735 "BarrrrrrrrrrrrLong,\n" 15736 " FoooooooooLooooong);\n" 15737 "}", 15738 Spaces); 15739 } 15740 15741 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) { 15742 verifyFormat("int a[5];"); 15743 verifyFormat("a[3] += 42;"); 15744 15745 FormatStyle Spaces = getLLVMStyle(); 15746 Spaces.SpacesInSquareBrackets = true; 15747 // Not lambdas. 15748 verifyFormat("int a[ 5 ];", Spaces); 15749 verifyFormat("a[ 3 ] += 42;", Spaces); 15750 verifyFormat("constexpr char hello[]{\"hello\"};", Spaces); 15751 verifyFormat("double &operator[](int i) { return 0; }\n" 15752 "int i;", 15753 Spaces); 15754 verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces); 15755 verifyFormat("int i = a[ a ][ a ]->f();", Spaces); 15756 verifyFormat("int i = (*b)[ a ]->f();", Spaces); 15757 // Lambdas. 15758 verifyFormat("int c = []() -> int { return 2; }();\n", Spaces); 15759 verifyFormat("return [ i, args... ] {};", Spaces); 15760 verifyFormat("int foo = [ &bar ]() {};", Spaces); 15761 verifyFormat("int foo = [ = ]() {};", Spaces); 15762 verifyFormat("int foo = [ & ]() {};", Spaces); 15763 verifyFormat("int foo = [ =, &bar ]() {};", Spaces); 15764 verifyFormat("int foo = [ &bar, = ]() {};", Spaces); 15765 } 15766 15767 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) { 15768 FormatStyle NoSpaceStyle = getLLVMStyle(); 15769 verifyFormat("int a[5];", NoSpaceStyle); 15770 verifyFormat("a[3] += 42;", NoSpaceStyle); 15771 15772 verifyFormat("int a[1];", NoSpaceStyle); 15773 verifyFormat("int 1 [a];", NoSpaceStyle); 15774 verifyFormat("int a[1][2];", NoSpaceStyle); 15775 verifyFormat("a[7] = 5;", NoSpaceStyle); 15776 verifyFormat("int a = (f())[23];", NoSpaceStyle); 15777 verifyFormat("f([] {})", NoSpaceStyle); 15778 15779 FormatStyle Space = getLLVMStyle(); 15780 Space.SpaceBeforeSquareBrackets = true; 15781 verifyFormat("int c = []() -> int { return 2; }();\n", Space); 15782 verifyFormat("return [i, args...] {};", Space); 15783 15784 verifyFormat("int a [5];", Space); 15785 verifyFormat("a [3] += 42;", Space); 15786 verifyFormat("constexpr char hello []{\"hello\"};", Space); 15787 verifyFormat("double &operator[](int i) { return 0; }\n" 15788 "int i;", 15789 Space); 15790 verifyFormat("std::unique_ptr<int []> foo() {}", Space); 15791 verifyFormat("int i = a [a][a]->f();", Space); 15792 verifyFormat("int i = (*b) [a]->f();", Space); 15793 15794 verifyFormat("int a [1];", Space); 15795 verifyFormat("int 1 [a];", Space); 15796 verifyFormat("int a [1][2];", Space); 15797 verifyFormat("a [7] = 5;", Space); 15798 verifyFormat("int a = (f()) [23];", Space); 15799 verifyFormat("f([] {})", Space); 15800 } 15801 15802 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) { 15803 verifyFormat("int a = 5;"); 15804 verifyFormat("a += 42;"); 15805 verifyFormat("a or_eq 8;"); 15806 15807 FormatStyle Spaces = getLLVMStyle(); 15808 Spaces.SpaceBeforeAssignmentOperators = false; 15809 verifyFormat("int a= 5;", Spaces); 15810 verifyFormat("a+= 42;", Spaces); 15811 verifyFormat("a or_eq 8;", Spaces); 15812 } 15813 15814 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) { 15815 verifyFormat("class Foo : public Bar {};"); 15816 verifyFormat("Foo::Foo() : foo(1) {}"); 15817 verifyFormat("for (auto a : b) {\n}"); 15818 verifyFormat("int x = a ? b : c;"); 15819 verifyFormat("{\n" 15820 "label0:\n" 15821 " int x = 0;\n" 15822 "}"); 15823 verifyFormat("switch (x) {\n" 15824 "case 1:\n" 15825 "default:\n" 15826 "}"); 15827 verifyFormat("switch (allBraces) {\n" 15828 "case 1: {\n" 15829 " break;\n" 15830 "}\n" 15831 "case 2: {\n" 15832 " [[fallthrough]];\n" 15833 "}\n" 15834 "default: {\n" 15835 " break;\n" 15836 "}\n" 15837 "}"); 15838 15839 FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30); 15840 CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false; 15841 verifyFormat("class Foo : public Bar {};", CtorInitializerStyle); 15842 verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle); 15843 verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle); 15844 verifyFormat("int x = a ? b : c;", CtorInitializerStyle); 15845 verifyFormat("{\n" 15846 "label1:\n" 15847 " int x = 0;\n" 15848 "}", 15849 CtorInitializerStyle); 15850 verifyFormat("switch (x) {\n" 15851 "case 1:\n" 15852 "default:\n" 15853 "}", 15854 CtorInitializerStyle); 15855 verifyFormat("switch (allBraces) {\n" 15856 "case 1: {\n" 15857 " break;\n" 15858 "}\n" 15859 "case 2: {\n" 15860 " [[fallthrough]];\n" 15861 "}\n" 15862 "default: {\n" 15863 " break;\n" 15864 "}\n" 15865 "}", 15866 CtorInitializerStyle); 15867 CtorInitializerStyle.BreakConstructorInitializers = 15868 FormatStyle::BCIS_AfterColon; 15869 verifyFormat("Fooooooooooo::Fooooooooooo():\n" 15870 " aaaaaaaaaaaaaaaa(1),\n" 15871 " bbbbbbbbbbbbbbbb(2) {}", 15872 CtorInitializerStyle); 15873 CtorInitializerStyle.BreakConstructorInitializers = 15874 FormatStyle::BCIS_BeforeComma; 15875 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15876 " : aaaaaaaaaaaaaaaa(1)\n" 15877 " , bbbbbbbbbbbbbbbb(2) {}", 15878 CtorInitializerStyle); 15879 CtorInitializerStyle.BreakConstructorInitializers = 15880 FormatStyle::BCIS_BeforeColon; 15881 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15882 " : aaaaaaaaaaaaaaaa(1),\n" 15883 " bbbbbbbbbbbbbbbb(2) {}", 15884 CtorInitializerStyle); 15885 CtorInitializerStyle.ConstructorInitializerIndentWidth = 0; 15886 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15887 ": aaaaaaaaaaaaaaaa(1),\n" 15888 " bbbbbbbbbbbbbbbb(2) {}", 15889 CtorInitializerStyle); 15890 15891 FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30); 15892 InheritanceStyle.SpaceBeforeInheritanceColon = false; 15893 verifyFormat("class Foo: public Bar {};", InheritanceStyle); 15894 verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle); 15895 verifyFormat("for (auto a : b) {\n}", InheritanceStyle); 15896 verifyFormat("int x = a ? b : c;", InheritanceStyle); 15897 verifyFormat("{\n" 15898 "label2:\n" 15899 " int x = 0;\n" 15900 "}", 15901 InheritanceStyle); 15902 verifyFormat("switch (x) {\n" 15903 "case 1:\n" 15904 "default:\n" 15905 "}", 15906 InheritanceStyle); 15907 verifyFormat("switch (allBraces) {\n" 15908 "case 1: {\n" 15909 " break;\n" 15910 "}\n" 15911 "case 2: {\n" 15912 " [[fallthrough]];\n" 15913 "}\n" 15914 "default: {\n" 15915 " break;\n" 15916 "}\n" 15917 "}", 15918 InheritanceStyle); 15919 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterComma; 15920 verifyFormat("class Foooooooooooooooooooooo\n" 15921 " : public aaaaaaaaaaaaaaaaaa,\n" 15922 " public bbbbbbbbbbbbbbbbbb {\n" 15923 "}", 15924 InheritanceStyle); 15925 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon; 15926 verifyFormat("class Foooooooooooooooooooooo:\n" 15927 " public aaaaaaaaaaaaaaaaaa,\n" 15928 " public bbbbbbbbbbbbbbbbbb {\n" 15929 "}", 15930 InheritanceStyle); 15931 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma; 15932 verifyFormat("class Foooooooooooooooooooooo\n" 15933 " : public aaaaaaaaaaaaaaaaaa\n" 15934 " , public bbbbbbbbbbbbbbbbbb {\n" 15935 "}", 15936 InheritanceStyle); 15937 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 15938 verifyFormat("class Foooooooooooooooooooooo\n" 15939 " : public aaaaaaaaaaaaaaaaaa,\n" 15940 " public bbbbbbbbbbbbbbbbbb {\n" 15941 "}", 15942 InheritanceStyle); 15943 InheritanceStyle.ConstructorInitializerIndentWidth = 0; 15944 verifyFormat("class Foooooooooooooooooooooo\n" 15945 ": public aaaaaaaaaaaaaaaaaa,\n" 15946 " public bbbbbbbbbbbbbbbbbb {}", 15947 InheritanceStyle); 15948 15949 FormatStyle ForLoopStyle = getLLVMStyle(); 15950 ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false; 15951 verifyFormat("class Foo : public Bar {};", ForLoopStyle); 15952 verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle); 15953 verifyFormat("for (auto a: b) {\n}", ForLoopStyle); 15954 verifyFormat("int x = a ? b : c;", ForLoopStyle); 15955 verifyFormat("{\n" 15956 "label2:\n" 15957 " int x = 0;\n" 15958 "}", 15959 ForLoopStyle); 15960 verifyFormat("switch (x) {\n" 15961 "case 1:\n" 15962 "default:\n" 15963 "}", 15964 ForLoopStyle); 15965 verifyFormat("switch (allBraces) {\n" 15966 "case 1: {\n" 15967 " break;\n" 15968 "}\n" 15969 "case 2: {\n" 15970 " [[fallthrough]];\n" 15971 "}\n" 15972 "default: {\n" 15973 " break;\n" 15974 "}\n" 15975 "}", 15976 ForLoopStyle); 15977 15978 FormatStyle CaseStyle = getLLVMStyle(); 15979 CaseStyle.SpaceBeforeCaseColon = true; 15980 verifyFormat("class Foo : public Bar {};", CaseStyle); 15981 verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle); 15982 verifyFormat("for (auto a : b) {\n}", CaseStyle); 15983 verifyFormat("int x = a ? b : c;", CaseStyle); 15984 verifyFormat("switch (x) {\n" 15985 "case 1 :\n" 15986 "default :\n" 15987 "}", 15988 CaseStyle); 15989 verifyFormat("switch (allBraces) {\n" 15990 "case 1 : {\n" 15991 " break;\n" 15992 "}\n" 15993 "case 2 : {\n" 15994 " [[fallthrough]];\n" 15995 "}\n" 15996 "default : {\n" 15997 " break;\n" 15998 "}\n" 15999 "}", 16000 CaseStyle); 16001 16002 FormatStyle NoSpaceStyle = getLLVMStyle(); 16003 EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false); 16004 NoSpaceStyle.SpaceBeforeCtorInitializerColon = false; 16005 NoSpaceStyle.SpaceBeforeInheritanceColon = false; 16006 NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false; 16007 verifyFormat("class Foo: public Bar {};", NoSpaceStyle); 16008 verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle); 16009 verifyFormat("for (auto a: b) {\n}", NoSpaceStyle); 16010 verifyFormat("int x = a ? b : c;", NoSpaceStyle); 16011 verifyFormat("{\n" 16012 "label3:\n" 16013 " int x = 0;\n" 16014 "}", 16015 NoSpaceStyle); 16016 verifyFormat("switch (x) {\n" 16017 "case 1:\n" 16018 "default:\n" 16019 "}", 16020 NoSpaceStyle); 16021 verifyFormat("switch (allBraces) {\n" 16022 "case 1: {\n" 16023 " break;\n" 16024 "}\n" 16025 "case 2: {\n" 16026 " [[fallthrough]];\n" 16027 "}\n" 16028 "default: {\n" 16029 " break;\n" 16030 "}\n" 16031 "}", 16032 NoSpaceStyle); 16033 16034 FormatStyle InvertedSpaceStyle = getLLVMStyle(); 16035 InvertedSpaceStyle.SpaceBeforeCaseColon = true; 16036 InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false; 16037 InvertedSpaceStyle.SpaceBeforeInheritanceColon = false; 16038 InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false; 16039 verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle); 16040 verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle); 16041 verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle); 16042 verifyFormat("int x = a ? b : c;", InvertedSpaceStyle); 16043 verifyFormat("{\n" 16044 "label3:\n" 16045 " int x = 0;\n" 16046 "}", 16047 InvertedSpaceStyle); 16048 verifyFormat("switch (x) {\n" 16049 "case 1 :\n" 16050 "case 2 : {\n" 16051 " break;\n" 16052 "}\n" 16053 "default :\n" 16054 " break;\n" 16055 "}", 16056 InvertedSpaceStyle); 16057 verifyFormat("switch (allBraces) {\n" 16058 "case 1 : {\n" 16059 " break;\n" 16060 "}\n" 16061 "case 2 : {\n" 16062 " [[fallthrough]];\n" 16063 "}\n" 16064 "default : {\n" 16065 " break;\n" 16066 "}\n" 16067 "}", 16068 InvertedSpaceStyle); 16069 } 16070 16071 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) { 16072 FormatStyle Style = getLLVMStyle(); 16073 16074 Style.PointerAlignment = FormatStyle::PAS_Left; 16075 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default; 16076 verifyFormat("void* const* x = NULL;", Style); 16077 16078 #define verifyQualifierSpaces(Code, Pointers, Qualifiers) \ 16079 do { \ 16080 Style.PointerAlignment = FormatStyle::Pointers; \ 16081 Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers; \ 16082 verifyFormat(Code, Style); \ 16083 } while (false) 16084 16085 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default); 16086 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default); 16087 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default); 16088 16089 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before); 16090 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before); 16091 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before); 16092 16093 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After); 16094 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After); 16095 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After); 16096 16097 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both); 16098 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both); 16099 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both); 16100 16101 verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default); 16102 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, 16103 SAPQ_Default); 16104 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 16105 SAPQ_Default); 16106 16107 verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before); 16108 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, 16109 SAPQ_Before); 16110 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 16111 SAPQ_Before); 16112 16113 verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After); 16114 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After); 16115 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 16116 SAPQ_After); 16117 16118 verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both); 16119 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both); 16120 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both); 16121 16122 #undef verifyQualifierSpaces 16123 16124 FormatStyle Spaces = getLLVMStyle(); 16125 Spaces.AttributeMacros.push_back("qualified"); 16126 Spaces.PointerAlignment = FormatStyle::PAS_Right; 16127 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default; 16128 verifyFormat("SomeType *volatile *a = NULL;", Spaces); 16129 verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces); 16130 verifyFormat("std::vector<SomeType *const *> x;", Spaces); 16131 verifyFormat("std::vector<SomeType *qualified *> x;", Spaces); 16132 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 16133 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before; 16134 verifyFormat("SomeType * volatile *a = NULL;", Spaces); 16135 verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces); 16136 verifyFormat("std::vector<SomeType * const *> x;", Spaces); 16137 verifyFormat("std::vector<SomeType * qualified *> x;", Spaces); 16138 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 16139 16140 // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left. 16141 Spaces.PointerAlignment = FormatStyle::PAS_Left; 16142 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before; 16143 verifyFormat("SomeType* volatile* a = NULL;", Spaces); 16144 verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces); 16145 verifyFormat("std::vector<SomeType* const*> x;", Spaces); 16146 verifyFormat("std::vector<SomeType* qualified*> x;", Spaces); 16147 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 16148 // However, setting it to SAPQ_After should add spaces after __attribute, etc. 16149 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After; 16150 verifyFormat("SomeType* volatile * a = NULL;", Spaces); 16151 verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces); 16152 verifyFormat("std::vector<SomeType* const *> x;", Spaces); 16153 verifyFormat("std::vector<SomeType* qualified *> x;", Spaces); 16154 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 16155 16156 // PAS_Middle should not have any noticeable changes even for SAPQ_Both 16157 Spaces.PointerAlignment = FormatStyle::PAS_Middle; 16158 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After; 16159 verifyFormat("SomeType * volatile * a = NULL;", Spaces); 16160 verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces); 16161 verifyFormat("std::vector<SomeType * const *> x;", Spaces); 16162 verifyFormat("std::vector<SomeType * qualified *> x;", Spaces); 16163 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 16164 } 16165 16166 TEST_F(FormatTest, AlignConsecutiveMacros) { 16167 FormatStyle Style = getLLVMStyle(); 16168 Style.AlignConsecutiveAssignments.Enabled = true; 16169 Style.AlignConsecutiveDeclarations.Enabled = true; 16170 16171 verifyFormat("#define a 3\n" 16172 "#define bbbb 4\n" 16173 "#define ccc (5)", 16174 Style); 16175 16176 verifyFormat("#define f(x) (x * x)\n" 16177 "#define fff(x, y, z) (x * y + z)\n" 16178 "#define ffff(x, y) (x - y)", 16179 Style); 16180 16181 verifyFormat("#define foo(x, y) (x + y)\n" 16182 "#define bar (5, 6)(2 + 2)", 16183 Style); 16184 16185 verifyFormat("#define a 3\n" 16186 "#define bbbb 4\n" 16187 "#define ccc (5)\n" 16188 "#define f(x) (x * x)\n" 16189 "#define fff(x, y, z) (x * y + z)\n" 16190 "#define ffff(x, y) (x - y)", 16191 Style); 16192 16193 Style.AlignConsecutiveMacros.Enabled = true; 16194 verifyFormat("#define a 3\n" 16195 "#define bbbb 4\n" 16196 "#define ccc (5)", 16197 Style); 16198 16199 verifyFormat("#define true 1\n" 16200 "#define false 0", 16201 Style); 16202 16203 verifyFormat("#define f(x) (x * x)\n" 16204 "#define fff(x, y, z) (x * y + z)\n" 16205 "#define ffff(x, y) (x - y)", 16206 Style); 16207 16208 verifyFormat("#define foo(x, y) (x + y)\n" 16209 "#define bar (5, 6)(2 + 2)", 16210 Style); 16211 16212 verifyFormat("#define a 3\n" 16213 "#define bbbb 4\n" 16214 "#define ccc (5)\n" 16215 "#define f(x) (x * x)\n" 16216 "#define fff(x, y, z) (x * y + z)\n" 16217 "#define ffff(x, y) (x - y)", 16218 Style); 16219 16220 verifyFormat("#define a 5\n" 16221 "#define foo(x, y) (x + y)\n" 16222 "#define CCC (6)\n" 16223 "auto lambda = []() {\n" 16224 " auto ii = 0;\n" 16225 " float j = 0;\n" 16226 " return 0;\n" 16227 "};\n" 16228 "int i = 0;\n" 16229 "float i2 = 0;\n" 16230 "auto v = type{\n" 16231 " i = 1, //\n" 16232 " (i = 2), //\n" 16233 " i = 3 //\n" 16234 "};", 16235 Style); 16236 16237 Style.AlignConsecutiveMacros.Enabled = false; 16238 Style.ColumnLimit = 20; 16239 16240 verifyFormat("#define a \\\n" 16241 " \"aabbbbbbbbbbbb\"\n" 16242 "#define D \\\n" 16243 " \"aabbbbbbbbbbbb\" \\\n" 16244 " \"ccddeeeeeeeee\"\n" 16245 "#define B \\\n" 16246 " \"QQQQQQQQQQQQQ\" \\\n" 16247 " \"FFFFFFFFFFFFF\" \\\n" 16248 " \"LLLLLLLL\"\n", 16249 Style); 16250 16251 Style.AlignConsecutiveMacros.Enabled = true; 16252 verifyFormat("#define a \\\n" 16253 " \"aabbbbbbbbbbbb\"\n" 16254 "#define D \\\n" 16255 " \"aabbbbbbbbbbbb\" \\\n" 16256 " \"ccddeeeeeeeee\"\n" 16257 "#define B \\\n" 16258 " \"QQQQQQQQQQQQQ\" \\\n" 16259 " \"FFFFFFFFFFFFF\" \\\n" 16260 " \"LLLLLLLL\"\n", 16261 Style); 16262 16263 // Test across comments 16264 Style.MaxEmptyLinesToKeep = 10; 16265 Style.ReflowComments = false; 16266 Style.AlignConsecutiveMacros.AcrossComments = true; 16267 EXPECT_EQ("#define a 3\n" 16268 "// line comment\n" 16269 "#define bbbb 4\n" 16270 "#define ccc (5)", 16271 format("#define a 3\n" 16272 "// line comment\n" 16273 "#define bbbb 4\n" 16274 "#define ccc (5)", 16275 Style)); 16276 16277 EXPECT_EQ("#define a 3\n" 16278 "/* block comment */\n" 16279 "#define bbbb 4\n" 16280 "#define ccc (5)", 16281 format("#define a 3\n" 16282 "/* block comment */\n" 16283 "#define bbbb 4\n" 16284 "#define ccc (5)", 16285 Style)); 16286 16287 EXPECT_EQ("#define a 3\n" 16288 "/* multi-line *\n" 16289 " * block comment */\n" 16290 "#define bbbb 4\n" 16291 "#define ccc (5)", 16292 format("#define a 3\n" 16293 "/* multi-line *\n" 16294 " * block comment */\n" 16295 "#define bbbb 4\n" 16296 "#define ccc (5)", 16297 Style)); 16298 16299 EXPECT_EQ("#define a 3\n" 16300 "// multi-line line comment\n" 16301 "//\n" 16302 "#define bbbb 4\n" 16303 "#define ccc (5)", 16304 format("#define a 3\n" 16305 "// multi-line line comment\n" 16306 "//\n" 16307 "#define bbbb 4\n" 16308 "#define ccc (5)", 16309 Style)); 16310 16311 EXPECT_EQ("#define a 3\n" 16312 "// empty lines still break.\n" 16313 "\n" 16314 "#define bbbb 4\n" 16315 "#define ccc (5)", 16316 format("#define a 3\n" 16317 "// empty lines still break.\n" 16318 "\n" 16319 "#define bbbb 4\n" 16320 "#define ccc (5)", 16321 Style)); 16322 16323 // Test across empty lines 16324 Style.AlignConsecutiveMacros.AcrossComments = false; 16325 Style.AlignConsecutiveMacros.AcrossEmptyLines = true; 16326 EXPECT_EQ("#define a 3\n" 16327 "\n" 16328 "#define bbbb 4\n" 16329 "#define ccc (5)", 16330 format("#define a 3\n" 16331 "\n" 16332 "#define bbbb 4\n" 16333 "#define ccc (5)", 16334 Style)); 16335 16336 EXPECT_EQ("#define a 3\n" 16337 "\n" 16338 "\n" 16339 "\n" 16340 "#define bbbb 4\n" 16341 "#define ccc (5)", 16342 format("#define a 3\n" 16343 "\n" 16344 "\n" 16345 "\n" 16346 "#define bbbb 4\n" 16347 "#define ccc (5)", 16348 Style)); 16349 16350 EXPECT_EQ("#define a 3\n" 16351 "// comments should break alignment\n" 16352 "//\n" 16353 "#define bbbb 4\n" 16354 "#define ccc (5)", 16355 format("#define a 3\n" 16356 "// comments should break alignment\n" 16357 "//\n" 16358 "#define bbbb 4\n" 16359 "#define ccc (5)", 16360 Style)); 16361 16362 // Test across empty lines and comments 16363 Style.AlignConsecutiveMacros.AcrossComments = true; 16364 verifyFormat("#define a 3\n" 16365 "\n" 16366 "// line comment\n" 16367 "#define bbbb 4\n" 16368 "#define ccc (5)", 16369 Style); 16370 16371 EXPECT_EQ("#define a 3\n" 16372 "\n" 16373 "\n" 16374 "/* multi-line *\n" 16375 " * block comment */\n" 16376 "\n" 16377 "\n" 16378 "#define bbbb 4\n" 16379 "#define ccc (5)", 16380 format("#define a 3\n" 16381 "\n" 16382 "\n" 16383 "/* multi-line *\n" 16384 " * block comment */\n" 16385 "\n" 16386 "\n" 16387 "#define bbbb 4\n" 16388 "#define ccc (5)", 16389 Style)); 16390 16391 EXPECT_EQ("#define a 3\n" 16392 "\n" 16393 "\n" 16394 "/* multi-line *\n" 16395 " * block comment */\n" 16396 "\n" 16397 "\n" 16398 "#define bbbb 4\n" 16399 "#define ccc (5)", 16400 format("#define a 3\n" 16401 "\n" 16402 "\n" 16403 "/* multi-line *\n" 16404 " * block comment */\n" 16405 "\n" 16406 "\n" 16407 "#define bbbb 4\n" 16408 "#define ccc (5)", 16409 Style)); 16410 } 16411 16412 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) { 16413 FormatStyle Alignment = getLLVMStyle(); 16414 Alignment.AlignConsecutiveMacros.Enabled = true; 16415 Alignment.AlignConsecutiveAssignments.Enabled = true; 16416 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true; 16417 16418 Alignment.MaxEmptyLinesToKeep = 10; 16419 /* Test alignment across empty lines */ 16420 EXPECT_EQ("int a = 5;\n" 16421 "\n" 16422 "int oneTwoThree = 123;", 16423 format("int a = 5;\n" 16424 "\n" 16425 "int oneTwoThree= 123;", 16426 Alignment)); 16427 EXPECT_EQ("int a = 5;\n" 16428 "int one = 1;\n" 16429 "\n" 16430 "int oneTwoThree = 123;", 16431 format("int a = 5;\n" 16432 "int one = 1;\n" 16433 "\n" 16434 "int oneTwoThree = 123;", 16435 Alignment)); 16436 EXPECT_EQ("int a = 5;\n" 16437 "int one = 1;\n" 16438 "\n" 16439 "int oneTwoThree = 123;\n" 16440 "int oneTwo = 12;", 16441 format("int a = 5;\n" 16442 "int one = 1;\n" 16443 "\n" 16444 "int oneTwoThree = 123;\n" 16445 "int oneTwo = 12;", 16446 Alignment)); 16447 16448 /* Test across comments */ 16449 EXPECT_EQ("int a = 5;\n" 16450 "/* block comment */\n" 16451 "int oneTwoThree = 123;", 16452 format("int a = 5;\n" 16453 "/* block comment */\n" 16454 "int oneTwoThree=123;", 16455 Alignment)); 16456 16457 EXPECT_EQ("int a = 5;\n" 16458 "// line comment\n" 16459 "int oneTwoThree = 123;", 16460 format("int a = 5;\n" 16461 "// line comment\n" 16462 "int oneTwoThree=123;", 16463 Alignment)); 16464 16465 /* Test across comments and newlines */ 16466 EXPECT_EQ("int a = 5;\n" 16467 "\n" 16468 "/* block comment */\n" 16469 "int oneTwoThree = 123;", 16470 format("int a = 5;\n" 16471 "\n" 16472 "/* block comment */\n" 16473 "int oneTwoThree=123;", 16474 Alignment)); 16475 16476 EXPECT_EQ("int a = 5;\n" 16477 "\n" 16478 "// line comment\n" 16479 "int oneTwoThree = 123;", 16480 format("int a = 5;\n" 16481 "\n" 16482 "// line comment\n" 16483 "int oneTwoThree=123;", 16484 Alignment)); 16485 } 16486 16487 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) { 16488 FormatStyle Alignment = getLLVMStyle(); 16489 Alignment.AlignConsecutiveDeclarations.Enabled = true; 16490 Alignment.AlignConsecutiveDeclarations.AcrossEmptyLines = true; 16491 Alignment.AlignConsecutiveDeclarations.AcrossComments = true; 16492 16493 Alignment.MaxEmptyLinesToKeep = 10; 16494 /* Test alignment across empty lines */ 16495 EXPECT_EQ("int a = 5;\n" 16496 "\n" 16497 "float const oneTwoThree = 123;", 16498 format("int a = 5;\n" 16499 "\n" 16500 "float const oneTwoThree = 123;", 16501 Alignment)); 16502 EXPECT_EQ("int a = 5;\n" 16503 "float const one = 1;\n" 16504 "\n" 16505 "int oneTwoThree = 123;", 16506 format("int a = 5;\n" 16507 "float const one = 1;\n" 16508 "\n" 16509 "int oneTwoThree = 123;", 16510 Alignment)); 16511 16512 /* Test across comments */ 16513 EXPECT_EQ("float const a = 5;\n" 16514 "/* block comment */\n" 16515 "int oneTwoThree = 123;", 16516 format("float const a = 5;\n" 16517 "/* block comment */\n" 16518 "int oneTwoThree=123;", 16519 Alignment)); 16520 16521 EXPECT_EQ("float const a = 5;\n" 16522 "// line comment\n" 16523 "int oneTwoThree = 123;", 16524 format("float const a = 5;\n" 16525 "// line comment\n" 16526 "int oneTwoThree=123;", 16527 Alignment)); 16528 16529 /* Test across comments and newlines */ 16530 EXPECT_EQ("float const a = 5;\n" 16531 "\n" 16532 "/* block comment */\n" 16533 "int oneTwoThree = 123;", 16534 format("float const a = 5;\n" 16535 "\n" 16536 "/* block comment */\n" 16537 "int oneTwoThree=123;", 16538 Alignment)); 16539 16540 EXPECT_EQ("float const a = 5;\n" 16541 "\n" 16542 "// line comment\n" 16543 "int oneTwoThree = 123;", 16544 format("float const a = 5;\n" 16545 "\n" 16546 "// line comment\n" 16547 "int oneTwoThree=123;", 16548 Alignment)); 16549 } 16550 16551 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) { 16552 FormatStyle Alignment = getLLVMStyle(); 16553 Alignment.AlignConsecutiveBitFields.Enabled = true; 16554 Alignment.AlignConsecutiveBitFields.AcrossEmptyLines = true; 16555 Alignment.AlignConsecutiveBitFields.AcrossComments = true; 16556 16557 Alignment.MaxEmptyLinesToKeep = 10; 16558 /* Test alignment across empty lines */ 16559 EXPECT_EQ("int a : 5;\n" 16560 "\n" 16561 "int longbitfield : 6;", 16562 format("int a : 5;\n" 16563 "\n" 16564 "int longbitfield : 6;", 16565 Alignment)); 16566 EXPECT_EQ("int a : 5;\n" 16567 "int one : 1;\n" 16568 "\n" 16569 "int longbitfield : 6;", 16570 format("int a : 5;\n" 16571 "int one : 1;\n" 16572 "\n" 16573 "int longbitfield : 6;", 16574 Alignment)); 16575 16576 /* Test across comments */ 16577 EXPECT_EQ("int a : 5;\n" 16578 "/* block comment */\n" 16579 "int longbitfield : 6;", 16580 format("int a : 5;\n" 16581 "/* block comment */\n" 16582 "int longbitfield : 6;", 16583 Alignment)); 16584 EXPECT_EQ("int a : 5;\n" 16585 "int one : 1;\n" 16586 "// line comment\n" 16587 "int longbitfield : 6;", 16588 format("int a : 5;\n" 16589 "int one : 1;\n" 16590 "// line comment\n" 16591 "int longbitfield : 6;", 16592 Alignment)); 16593 16594 /* Test across comments and newlines */ 16595 EXPECT_EQ("int a : 5;\n" 16596 "/* block comment */\n" 16597 "\n" 16598 "int longbitfield : 6;", 16599 format("int a : 5;\n" 16600 "/* block comment */\n" 16601 "\n" 16602 "int longbitfield : 6;", 16603 Alignment)); 16604 EXPECT_EQ("int a : 5;\n" 16605 "int one : 1;\n" 16606 "\n" 16607 "// line comment\n" 16608 "\n" 16609 "int longbitfield : 6;", 16610 format("int a : 5;\n" 16611 "int one : 1;\n" 16612 "\n" 16613 "// line comment \n" 16614 "\n" 16615 "int longbitfield : 6;", 16616 Alignment)); 16617 } 16618 16619 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) { 16620 FormatStyle Alignment = getLLVMStyle(); 16621 Alignment.AlignConsecutiveMacros.Enabled = true; 16622 Alignment.AlignConsecutiveAssignments.Enabled = true; 16623 Alignment.AlignConsecutiveAssignments.AcrossComments = true; 16624 16625 Alignment.MaxEmptyLinesToKeep = 10; 16626 /* Test alignment across empty lines */ 16627 EXPECT_EQ("int a = 5;\n" 16628 "\n" 16629 "int oneTwoThree = 123;", 16630 format("int a = 5;\n" 16631 "\n" 16632 "int oneTwoThree= 123;", 16633 Alignment)); 16634 EXPECT_EQ("int a = 5;\n" 16635 "int one = 1;\n" 16636 "\n" 16637 "int oneTwoThree = 123;", 16638 format("int a = 5;\n" 16639 "int one = 1;\n" 16640 "\n" 16641 "int oneTwoThree = 123;", 16642 Alignment)); 16643 16644 /* Test across comments */ 16645 EXPECT_EQ("int a = 5;\n" 16646 "/* block comment */\n" 16647 "int oneTwoThree = 123;", 16648 format("int a = 5;\n" 16649 "/* block comment */\n" 16650 "int oneTwoThree=123;", 16651 Alignment)); 16652 16653 EXPECT_EQ("int a = 5;\n" 16654 "// line comment\n" 16655 "int oneTwoThree = 123;", 16656 format("int a = 5;\n" 16657 "// line comment\n" 16658 "int oneTwoThree=123;", 16659 Alignment)); 16660 16661 EXPECT_EQ("int a = 5;\n" 16662 "/*\n" 16663 " * multi-line block comment\n" 16664 " */\n" 16665 "int oneTwoThree = 123;", 16666 format("int a = 5;\n" 16667 "/*\n" 16668 " * multi-line block comment\n" 16669 " */\n" 16670 "int oneTwoThree=123;", 16671 Alignment)); 16672 16673 EXPECT_EQ("int a = 5;\n" 16674 "//\n" 16675 "// multi-line line comment\n" 16676 "//\n" 16677 "int oneTwoThree = 123;", 16678 format("int a = 5;\n" 16679 "//\n" 16680 "// multi-line line comment\n" 16681 "//\n" 16682 "int oneTwoThree=123;", 16683 Alignment)); 16684 16685 /* Test across comments and newlines */ 16686 EXPECT_EQ("int a = 5;\n" 16687 "\n" 16688 "/* block comment */\n" 16689 "int oneTwoThree = 123;", 16690 format("int a = 5;\n" 16691 "\n" 16692 "/* block comment */\n" 16693 "int oneTwoThree=123;", 16694 Alignment)); 16695 16696 EXPECT_EQ("int a = 5;\n" 16697 "\n" 16698 "// line comment\n" 16699 "int oneTwoThree = 123;", 16700 format("int a = 5;\n" 16701 "\n" 16702 "// line comment\n" 16703 "int oneTwoThree=123;", 16704 Alignment)); 16705 } 16706 16707 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) { 16708 FormatStyle Alignment = getLLVMStyle(); 16709 Alignment.AlignConsecutiveMacros.Enabled = true; 16710 Alignment.AlignConsecutiveAssignments.Enabled = true; 16711 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true; 16712 Alignment.AlignConsecutiveAssignments.AcrossComments = true; 16713 verifyFormat("int a = 5;\n" 16714 "int oneTwoThree = 123;", 16715 Alignment); 16716 verifyFormat("int a = method();\n" 16717 "int oneTwoThree = 133;", 16718 Alignment); 16719 verifyFormat("a &= 5;\n" 16720 "bcd *= 5;\n" 16721 "ghtyf += 5;\n" 16722 "dvfvdb -= 5;\n" 16723 "a /= 5;\n" 16724 "vdsvsv %= 5;\n" 16725 "sfdbddfbdfbb ^= 5;\n" 16726 "dvsdsv |= 5;\n" 16727 "int dsvvdvsdvvv = 123;", 16728 Alignment); 16729 verifyFormat("int i = 1, j = 10;\n" 16730 "something = 2000;", 16731 Alignment); 16732 verifyFormat("something = 2000;\n" 16733 "int i = 1, j = 10;\n", 16734 Alignment); 16735 verifyFormat("something = 2000;\n" 16736 "another = 911;\n" 16737 "int i = 1, j = 10;\n" 16738 "oneMore = 1;\n" 16739 "i = 2;", 16740 Alignment); 16741 verifyFormat("int a = 5;\n" 16742 "int one = 1;\n" 16743 "method();\n" 16744 "int oneTwoThree = 123;\n" 16745 "int oneTwo = 12;", 16746 Alignment); 16747 verifyFormat("int oneTwoThree = 123;\n" 16748 "int oneTwo = 12;\n" 16749 "method();\n", 16750 Alignment); 16751 verifyFormat("int oneTwoThree = 123; // comment\n" 16752 "int oneTwo = 12; // comment", 16753 Alignment); 16754 16755 // Bug 25167 16756 /* Uncomment when fixed 16757 verifyFormat("#if A\n" 16758 "#else\n" 16759 "int aaaaaaaa = 12;\n" 16760 "#endif\n" 16761 "#if B\n" 16762 "#else\n" 16763 "int a = 12;\n" 16764 "#endif\n", 16765 Alignment); 16766 verifyFormat("enum foo {\n" 16767 "#if A\n" 16768 "#else\n" 16769 " aaaaaaaa = 12;\n" 16770 "#endif\n" 16771 "#if B\n" 16772 "#else\n" 16773 " a = 12;\n" 16774 "#endif\n" 16775 "};\n", 16776 Alignment); 16777 */ 16778 16779 Alignment.MaxEmptyLinesToKeep = 10; 16780 /* Test alignment across empty lines */ 16781 EXPECT_EQ("int a = 5;\n" 16782 "\n" 16783 "int oneTwoThree = 123;", 16784 format("int a = 5;\n" 16785 "\n" 16786 "int oneTwoThree= 123;", 16787 Alignment)); 16788 EXPECT_EQ("int a = 5;\n" 16789 "int one = 1;\n" 16790 "\n" 16791 "int oneTwoThree = 123;", 16792 format("int a = 5;\n" 16793 "int one = 1;\n" 16794 "\n" 16795 "int oneTwoThree = 123;", 16796 Alignment)); 16797 EXPECT_EQ("int a = 5;\n" 16798 "int one = 1;\n" 16799 "\n" 16800 "int oneTwoThree = 123;\n" 16801 "int oneTwo = 12;", 16802 format("int a = 5;\n" 16803 "int one = 1;\n" 16804 "\n" 16805 "int oneTwoThree = 123;\n" 16806 "int oneTwo = 12;", 16807 Alignment)); 16808 16809 /* Test across comments */ 16810 EXPECT_EQ("int a = 5;\n" 16811 "/* block comment */\n" 16812 "int oneTwoThree = 123;", 16813 format("int a = 5;\n" 16814 "/* block comment */\n" 16815 "int oneTwoThree=123;", 16816 Alignment)); 16817 16818 EXPECT_EQ("int a = 5;\n" 16819 "// line comment\n" 16820 "int oneTwoThree = 123;", 16821 format("int a = 5;\n" 16822 "// line comment\n" 16823 "int oneTwoThree=123;", 16824 Alignment)); 16825 16826 /* Test across comments and newlines */ 16827 EXPECT_EQ("int a = 5;\n" 16828 "\n" 16829 "/* block comment */\n" 16830 "int oneTwoThree = 123;", 16831 format("int a = 5;\n" 16832 "\n" 16833 "/* block comment */\n" 16834 "int oneTwoThree=123;", 16835 Alignment)); 16836 16837 EXPECT_EQ("int a = 5;\n" 16838 "\n" 16839 "// line comment\n" 16840 "int oneTwoThree = 123;", 16841 format("int a = 5;\n" 16842 "\n" 16843 "// line comment\n" 16844 "int oneTwoThree=123;", 16845 Alignment)); 16846 16847 EXPECT_EQ("int a = 5;\n" 16848 "//\n" 16849 "// multi-line line comment\n" 16850 "//\n" 16851 "int oneTwoThree = 123;", 16852 format("int a = 5;\n" 16853 "//\n" 16854 "// multi-line line comment\n" 16855 "//\n" 16856 "int oneTwoThree=123;", 16857 Alignment)); 16858 16859 EXPECT_EQ("int a = 5;\n" 16860 "/*\n" 16861 " * multi-line block comment\n" 16862 " */\n" 16863 "int oneTwoThree = 123;", 16864 format("int a = 5;\n" 16865 "/*\n" 16866 " * multi-line block comment\n" 16867 " */\n" 16868 "int oneTwoThree=123;", 16869 Alignment)); 16870 16871 EXPECT_EQ("int a = 5;\n" 16872 "\n" 16873 "/* block comment */\n" 16874 "\n" 16875 "\n" 16876 "\n" 16877 "int oneTwoThree = 123;", 16878 format("int a = 5;\n" 16879 "\n" 16880 "/* block comment */\n" 16881 "\n" 16882 "\n" 16883 "\n" 16884 "int oneTwoThree=123;", 16885 Alignment)); 16886 16887 EXPECT_EQ("int a = 5;\n" 16888 "\n" 16889 "// line comment\n" 16890 "\n" 16891 "\n" 16892 "\n" 16893 "int oneTwoThree = 123;", 16894 format("int a = 5;\n" 16895 "\n" 16896 "// line comment\n" 16897 "\n" 16898 "\n" 16899 "\n" 16900 "int oneTwoThree=123;", 16901 Alignment)); 16902 16903 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 16904 verifyFormat("#define A \\\n" 16905 " int aaaa = 12; \\\n" 16906 " int b = 23; \\\n" 16907 " int ccc = 234; \\\n" 16908 " int dddddddddd = 2345;", 16909 Alignment); 16910 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 16911 verifyFormat("#define A \\\n" 16912 " int aaaa = 12; \\\n" 16913 " int b = 23; \\\n" 16914 " int ccc = 234; \\\n" 16915 " int dddddddddd = 2345;", 16916 Alignment); 16917 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 16918 verifyFormat("#define A " 16919 " \\\n" 16920 " int aaaa = 12; " 16921 " \\\n" 16922 " int b = 23; " 16923 " \\\n" 16924 " int ccc = 234; " 16925 " \\\n" 16926 " int dddddddddd = 2345;", 16927 Alignment); 16928 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 16929 "k = 4, int l = 5,\n" 16930 " int m = 6) {\n" 16931 " int j = 10;\n" 16932 " otherThing = 1;\n" 16933 "}", 16934 Alignment); 16935 verifyFormat("void SomeFunction(int parameter = 0) {\n" 16936 " int i = 1;\n" 16937 " int j = 2;\n" 16938 " int big = 10000;\n" 16939 "}", 16940 Alignment); 16941 verifyFormat("class C {\n" 16942 "public:\n" 16943 " int i = 1;\n" 16944 " virtual void f() = 0;\n" 16945 "};", 16946 Alignment); 16947 verifyFormat("int i = 1;\n" 16948 "if (SomeType t = getSomething()) {\n" 16949 "}\n" 16950 "int j = 2;\n" 16951 "int big = 10000;", 16952 Alignment); 16953 verifyFormat("int j = 7;\n" 16954 "for (int k = 0; k < N; ++k) {\n" 16955 "}\n" 16956 "int j = 2;\n" 16957 "int big = 10000;\n" 16958 "}", 16959 Alignment); 16960 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 16961 verifyFormat("int i = 1;\n" 16962 "LooooooooooongType loooooooooooooooooooooongVariable\n" 16963 " = someLooooooooooooooooongFunction();\n" 16964 "int j = 2;", 16965 Alignment); 16966 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 16967 verifyFormat("int i = 1;\n" 16968 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 16969 " someLooooooooooooooooongFunction();\n" 16970 "int j = 2;", 16971 Alignment); 16972 16973 verifyFormat("auto lambda = []() {\n" 16974 " auto i = 0;\n" 16975 " return 0;\n" 16976 "};\n" 16977 "int i = 0;\n" 16978 "auto v = type{\n" 16979 " i = 1, //\n" 16980 " (i = 2), //\n" 16981 " i = 3 //\n" 16982 "};", 16983 Alignment); 16984 16985 verifyFormat( 16986 "int i = 1;\n" 16987 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 16988 " loooooooooooooooooooooongParameterB);\n" 16989 "int j = 2;", 16990 Alignment); 16991 16992 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n" 16993 " typename B = very_long_type_name_1,\n" 16994 " typename T_2 = very_long_type_name_2>\n" 16995 "auto foo() {}\n", 16996 Alignment); 16997 verifyFormat("int a, b = 1;\n" 16998 "int c = 2;\n" 16999 "int dd = 3;\n", 17000 Alignment); 17001 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17002 "float b[1][] = {{3.f}};\n", 17003 Alignment); 17004 verifyFormat("for (int i = 0; i < 1; i++)\n" 17005 " int x = 1;\n", 17006 Alignment); 17007 verifyFormat("for (i = 0; i < 1; i++)\n" 17008 " x = 1;\n" 17009 "y = 1;\n", 17010 Alignment); 17011 17012 Alignment.ReflowComments = true; 17013 Alignment.ColumnLimit = 50; 17014 EXPECT_EQ("int x = 0;\n" 17015 "int yy = 1; /// specificlennospace\n" 17016 "int zzz = 2;\n", 17017 format("int x = 0;\n" 17018 "int yy = 1; ///specificlennospace\n" 17019 "int zzz = 2;\n", 17020 Alignment)); 17021 } 17022 17023 TEST_F(FormatTest, AlignCompoundAssignments) { 17024 FormatStyle Alignment = getLLVMStyle(); 17025 Alignment.AlignConsecutiveAssignments.Enabled = true; 17026 Alignment.AlignConsecutiveAssignments.AlignCompound = true; 17027 Alignment.AlignConsecutiveAssignments.PadOperators = false; 17028 verifyFormat("sfdbddfbdfbb = 5;\n" 17029 "dvsdsv = 5;\n" 17030 "int dsvvdvsdvvv = 123;", 17031 Alignment); 17032 verifyFormat("sfdbddfbdfbb ^= 5;\n" 17033 "dvsdsv |= 5;\n" 17034 "int dsvvdvsdvvv = 123;", 17035 Alignment); 17036 verifyFormat("sfdbddfbdfbb ^= 5;\n" 17037 "dvsdsv <<= 5;\n" 17038 "int dsvvdvsdvvv = 123;", 17039 Alignment); 17040 // Test that `<=` is not treated as a compound assignment. 17041 verifyFormat("aa &= 5;\n" 17042 "b <= 10;\n" 17043 "c = 15;", 17044 Alignment); 17045 Alignment.AlignConsecutiveAssignments.PadOperators = true; 17046 verifyFormat("sfdbddfbdfbb = 5;\n" 17047 "dvsdsv = 5;\n" 17048 "int dsvvdvsdvvv = 123;", 17049 Alignment); 17050 verifyFormat("sfdbddfbdfbb ^= 5;\n" 17051 "dvsdsv |= 5;\n" 17052 "int dsvvdvsdvvv = 123;", 17053 Alignment); 17054 verifyFormat("sfdbddfbdfbb ^= 5;\n" 17055 "dvsdsv <<= 5;\n" 17056 "int dsvvdvsdvvv = 123;", 17057 Alignment); 17058 EXPECT_EQ("a += 5;\n" 17059 "one = 1;\n" 17060 "\n" 17061 "oneTwoThree = 123;\n", 17062 format("a += 5;\n" 17063 "one = 1;\n" 17064 "\n" 17065 "oneTwoThree = 123;\n", 17066 Alignment)); 17067 EXPECT_EQ("a += 5;\n" 17068 "one = 1;\n" 17069 "//\n" 17070 "oneTwoThree = 123;\n", 17071 format("a += 5;\n" 17072 "one = 1;\n" 17073 "//\n" 17074 "oneTwoThree = 123;\n", 17075 Alignment)); 17076 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true; 17077 EXPECT_EQ("a += 5;\n" 17078 "one = 1;\n" 17079 "\n" 17080 "oneTwoThree = 123;\n", 17081 format("a += 5;\n" 17082 "one = 1;\n" 17083 "\n" 17084 "oneTwoThree = 123;\n", 17085 Alignment)); 17086 EXPECT_EQ("a += 5;\n" 17087 "one = 1;\n" 17088 "//\n" 17089 "oneTwoThree = 123;\n", 17090 format("a += 5;\n" 17091 "one = 1;\n" 17092 "//\n" 17093 "oneTwoThree = 123;\n", 17094 Alignment)); 17095 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = false; 17096 Alignment.AlignConsecutiveAssignments.AcrossComments = true; 17097 EXPECT_EQ("a += 5;\n" 17098 "one = 1;\n" 17099 "\n" 17100 "oneTwoThree = 123;\n", 17101 format("a += 5;\n" 17102 "one = 1;\n" 17103 "\n" 17104 "oneTwoThree = 123;\n", 17105 Alignment)); 17106 EXPECT_EQ("a += 5;\n" 17107 "one = 1;\n" 17108 "//\n" 17109 "oneTwoThree = 123;\n", 17110 format("a += 5;\n" 17111 "one = 1;\n" 17112 "//\n" 17113 "oneTwoThree = 123;\n", 17114 Alignment)); 17115 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true; 17116 EXPECT_EQ("a += 5;\n" 17117 "one >>= 1;\n" 17118 "\n" 17119 "oneTwoThree = 123;\n", 17120 format("a += 5;\n" 17121 "one >>= 1;\n" 17122 "\n" 17123 "oneTwoThree = 123;\n", 17124 Alignment)); 17125 EXPECT_EQ("a += 5;\n" 17126 "one = 1;\n" 17127 "//\n" 17128 "oneTwoThree <<= 123;\n", 17129 format("a += 5;\n" 17130 "one = 1;\n" 17131 "//\n" 17132 "oneTwoThree <<= 123;\n", 17133 Alignment)); 17134 } 17135 17136 TEST_F(FormatTest, AlignConsecutiveAssignments) { 17137 FormatStyle Alignment = getLLVMStyle(); 17138 Alignment.AlignConsecutiveMacros.Enabled = true; 17139 verifyFormat("int a = 5;\n" 17140 "int oneTwoThree = 123;", 17141 Alignment); 17142 verifyFormat("int a = 5;\n" 17143 "int oneTwoThree = 123;", 17144 Alignment); 17145 17146 Alignment.AlignConsecutiveAssignments.Enabled = true; 17147 verifyFormat("int a = 5;\n" 17148 "int oneTwoThree = 123;", 17149 Alignment); 17150 verifyFormat("int a = method();\n" 17151 "int oneTwoThree = 133;", 17152 Alignment); 17153 verifyFormat("aa <= 5;\n" 17154 "a &= 5;\n" 17155 "bcd *= 5;\n" 17156 "ghtyf += 5;\n" 17157 "dvfvdb -= 5;\n" 17158 "a /= 5;\n" 17159 "vdsvsv %= 5;\n" 17160 "sfdbddfbdfbb ^= 5;\n" 17161 "dvsdsv |= 5;\n" 17162 "int dsvvdvsdvvv = 123;", 17163 Alignment); 17164 verifyFormat("int i = 1, j = 10;\n" 17165 "something = 2000;", 17166 Alignment); 17167 verifyFormat("something = 2000;\n" 17168 "int i = 1, j = 10;\n", 17169 Alignment); 17170 verifyFormat("something = 2000;\n" 17171 "another = 911;\n" 17172 "int i = 1, j = 10;\n" 17173 "oneMore = 1;\n" 17174 "i = 2;", 17175 Alignment); 17176 verifyFormat("int a = 5;\n" 17177 "int one = 1;\n" 17178 "method();\n" 17179 "int oneTwoThree = 123;\n" 17180 "int oneTwo = 12;", 17181 Alignment); 17182 verifyFormat("int oneTwoThree = 123;\n" 17183 "int oneTwo = 12;\n" 17184 "method();\n", 17185 Alignment); 17186 verifyFormat("int oneTwoThree = 123; // comment\n" 17187 "int oneTwo = 12; // comment", 17188 Alignment); 17189 verifyFormat("int f() = default;\n" 17190 "int &operator() = default;\n" 17191 "int &operator=() {", 17192 Alignment); 17193 verifyFormat("int f() = delete;\n" 17194 "int &operator() = delete;\n" 17195 "int &operator=() {", 17196 Alignment); 17197 verifyFormat("int f() = default; // comment\n" 17198 "int &operator() = default; // comment\n" 17199 "int &operator=() {", 17200 Alignment); 17201 verifyFormat("int f() = default;\n" 17202 "int &operator() = default;\n" 17203 "int &operator==() {", 17204 Alignment); 17205 verifyFormat("int f() = default;\n" 17206 "int &operator() = default;\n" 17207 "int &operator<=() {", 17208 Alignment); 17209 verifyFormat("int f() = default;\n" 17210 "int &operator() = default;\n" 17211 "int &operator!=() {", 17212 Alignment); 17213 verifyFormat("int f() = default;\n" 17214 "int &operator() = default;\n" 17215 "int &operator=();", 17216 Alignment); 17217 verifyFormat("int f() = delete;\n" 17218 "int &operator() = delete;\n" 17219 "int &operator=();", 17220 Alignment); 17221 verifyFormat("/* long long padding */ int f() = default;\n" 17222 "int &operator() = default;\n" 17223 "int &operator/**/ =();", 17224 Alignment); 17225 // https://llvm.org/PR33697 17226 FormatStyle AlignmentWithPenalty = getLLVMStyle(); 17227 AlignmentWithPenalty.AlignConsecutiveAssignments.Enabled = true; 17228 AlignmentWithPenalty.PenaltyReturnTypeOnItsOwnLine = 5000; 17229 verifyFormat("class SSSSSSSSSSSSSSSSSSSSSSSSSSSS {\n" 17230 " void f() = delete;\n" 17231 " SSSSSSSSSSSSSSSSSSSSSSSSSSSS &operator=(\n" 17232 " const SSSSSSSSSSSSSSSSSSSSSSSSSSSS &other) = delete;\n" 17233 "};\n", 17234 AlignmentWithPenalty); 17235 17236 // Bug 25167 17237 /* Uncomment when fixed 17238 verifyFormat("#if A\n" 17239 "#else\n" 17240 "int aaaaaaaa = 12;\n" 17241 "#endif\n" 17242 "#if B\n" 17243 "#else\n" 17244 "int a = 12;\n" 17245 "#endif\n", 17246 Alignment); 17247 verifyFormat("enum foo {\n" 17248 "#if A\n" 17249 "#else\n" 17250 " aaaaaaaa = 12;\n" 17251 "#endif\n" 17252 "#if B\n" 17253 "#else\n" 17254 " a = 12;\n" 17255 "#endif\n" 17256 "};\n", 17257 Alignment); 17258 */ 17259 17260 EXPECT_EQ("int a = 5;\n" 17261 "\n" 17262 "int oneTwoThree = 123;", 17263 format("int a = 5;\n" 17264 "\n" 17265 "int oneTwoThree= 123;", 17266 Alignment)); 17267 EXPECT_EQ("int a = 5;\n" 17268 "int one = 1;\n" 17269 "\n" 17270 "int oneTwoThree = 123;", 17271 format("int a = 5;\n" 17272 "int one = 1;\n" 17273 "\n" 17274 "int oneTwoThree = 123;", 17275 Alignment)); 17276 EXPECT_EQ("int a = 5;\n" 17277 "int one = 1;\n" 17278 "\n" 17279 "int oneTwoThree = 123;\n" 17280 "int oneTwo = 12;", 17281 format("int a = 5;\n" 17282 "int one = 1;\n" 17283 "\n" 17284 "int oneTwoThree = 123;\n" 17285 "int oneTwo = 12;", 17286 Alignment)); 17287 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 17288 verifyFormat("#define A \\\n" 17289 " int aaaa = 12; \\\n" 17290 " int b = 23; \\\n" 17291 " int ccc = 234; \\\n" 17292 " int dddddddddd = 2345;", 17293 Alignment); 17294 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 17295 verifyFormat("#define A \\\n" 17296 " int aaaa = 12; \\\n" 17297 " int b = 23; \\\n" 17298 " int ccc = 234; \\\n" 17299 " int dddddddddd = 2345;", 17300 Alignment); 17301 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 17302 verifyFormat("#define A " 17303 " \\\n" 17304 " int aaaa = 12; " 17305 " \\\n" 17306 " int b = 23; " 17307 " \\\n" 17308 " int ccc = 234; " 17309 " \\\n" 17310 " int dddddddddd = 2345;", 17311 Alignment); 17312 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 17313 "k = 4, int l = 5,\n" 17314 " int m = 6) {\n" 17315 " int j = 10;\n" 17316 " otherThing = 1;\n" 17317 "}", 17318 Alignment); 17319 verifyFormat("void SomeFunction(int parameter = 0) {\n" 17320 " int i = 1;\n" 17321 " int j = 2;\n" 17322 " int big = 10000;\n" 17323 "}", 17324 Alignment); 17325 verifyFormat("class C {\n" 17326 "public:\n" 17327 " int i = 1;\n" 17328 " virtual void f() = 0;\n" 17329 "};", 17330 Alignment); 17331 verifyFormat("int i = 1;\n" 17332 "if (SomeType t = getSomething()) {\n" 17333 "}\n" 17334 "int j = 2;\n" 17335 "int big = 10000;", 17336 Alignment); 17337 verifyFormat("int j = 7;\n" 17338 "for (int k = 0; k < N; ++k) {\n" 17339 "}\n" 17340 "int j = 2;\n" 17341 "int big = 10000;\n" 17342 "}", 17343 Alignment); 17344 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 17345 verifyFormat("int i = 1;\n" 17346 "LooooooooooongType loooooooooooooooooooooongVariable\n" 17347 " = someLooooooooooooooooongFunction();\n" 17348 "int j = 2;", 17349 Alignment); 17350 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 17351 verifyFormat("int i = 1;\n" 17352 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 17353 " someLooooooooooooooooongFunction();\n" 17354 "int j = 2;", 17355 Alignment); 17356 17357 verifyFormat("auto lambda = []() {\n" 17358 " auto i = 0;\n" 17359 " return 0;\n" 17360 "};\n" 17361 "int i = 0;\n" 17362 "auto v = type{\n" 17363 " i = 1, //\n" 17364 " (i = 2), //\n" 17365 " i = 3 //\n" 17366 "};", 17367 Alignment); 17368 17369 verifyFormat( 17370 "int i = 1;\n" 17371 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 17372 " loooooooooooooooooooooongParameterB);\n" 17373 "int j = 2;", 17374 Alignment); 17375 17376 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n" 17377 " typename B = very_long_type_name_1,\n" 17378 " typename T_2 = very_long_type_name_2>\n" 17379 "auto foo() {}\n", 17380 Alignment); 17381 verifyFormat("int a, b = 1;\n" 17382 "int c = 2;\n" 17383 "int dd = 3;\n", 17384 Alignment); 17385 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17386 "float b[1][] = {{3.f}};\n", 17387 Alignment); 17388 verifyFormat("for (int i = 0; i < 1; i++)\n" 17389 " int x = 1;\n", 17390 Alignment); 17391 verifyFormat("for (i = 0; i < 1; i++)\n" 17392 " x = 1;\n" 17393 "y = 1;\n", 17394 Alignment); 17395 17396 EXPECT_EQ(Alignment.ReflowComments, true); 17397 Alignment.ColumnLimit = 50; 17398 EXPECT_EQ("int x = 0;\n" 17399 "int yy = 1; /// specificlennospace\n" 17400 "int zzz = 2;\n", 17401 format("int x = 0;\n" 17402 "int yy = 1; ///specificlennospace\n" 17403 "int zzz = 2;\n", 17404 Alignment)); 17405 17406 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17407 "auto b = [] {\n" 17408 " f();\n" 17409 " return;\n" 17410 "};", 17411 Alignment); 17412 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17413 "auto b = g([] {\n" 17414 " f();\n" 17415 " return;\n" 17416 "});", 17417 Alignment); 17418 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17419 "auto b = g(param, [] {\n" 17420 " f();\n" 17421 " return;\n" 17422 "});", 17423 Alignment); 17424 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17425 "auto b = [] {\n" 17426 " if (condition) {\n" 17427 " return;\n" 17428 " }\n" 17429 "};", 17430 Alignment); 17431 17432 verifyFormat("auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 17433 " ccc ? aaaaa : bbbbb,\n" 17434 " dddddddddddddddddddddddddd);", 17435 Alignment); 17436 // FIXME: https://llvm.org/PR53497 17437 // verifyFormat("auto aaaaaaaaaaaa = f();\n" 17438 // "auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 17439 // " ccc ? aaaaa : bbbbb,\n" 17440 // " dddddddddddddddddddddddddd);", 17441 // Alignment); 17442 17443 // Confirm proper handling of AlignConsecutiveAssignments with 17444 // BinPackArguments. 17445 // See https://llvm.org/PR55360 17446 Alignment = getLLVMStyleWithColumns(50); 17447 Alignment.AlignConsecutiveAssignments.Enabled = true; 17448 Alignment.BinPackArguments = false; 17449 verifyFormat("int a_long_name = 1;\n" 17450 "auto b = B({a_long_name, a_long_name},\n" 17451 " {a_longer_name_for_wrap,\n" 17452 " a_longer_name_for_wrap});", 17453 Alignment); 17454 verifyFormat("int a_long_name = 1;\n" 17455 "auto b = B{{a_long_name, a_long_name},\n" 17456 " {a_longer_name_for_wrap,\n" 17457 " a_longer_name_for_wrap}};", 17458 Alignment); 17459 } 17460 17461 TEST_F(FormatTest, AlignConsecutiveBitFields) { 17462 FormatStyle Alignment = getLLVMStyle(); 17463 Alignment.AlignConsecutiveBitFields.Enabled = true; 17464 verifyFormat("int const a : 5;\n" 17465 "int oneTwoThree : 23;", 17466 Alignment); 17467 17468 // Initializers are allowed starting with c++2a 17469 verifyFormat("int const a : 5 = 1;\n" 17470 "int oneTwoThree : 23 = 0;", 17471 Alignment); 17472 17473 Alignment.AlignConsecutiveDeclarations.Enabled = true; 17474 verifyFormat("int const a : 5;\n" 17475 "int oneTwoThree : 23;", 17476 Alignment); 17477 17478 verifyFormat("int const a : 5; // comment\n" 17479 "int oneTwoThree : 23; // comment", 17480 Alignment); 17481 17482 verifyFormat("int const a : 5 = 1;\n" 17483 "int oneTwoThree : 23 = 0;", 17484 Alignment); 17485 17486 Alignment.AlignConsecutiveAssignments.Enabled = true; 17487 verifyFormat("int const a : 5 = 1;\n" 17488 "int oneTwoThree : 23 = 0;", 17489 Alignment); 17490 verifyFormat("int const a : 5 = {1};\n" 17491 "int oneTwoThree : 23 = 0;", 17492 Alignment); 17493 17494 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None; 17495 verifyFormat("int const a :5;\n" 17496 "int oneTwoThree:23;", 17497 Alignment); 17498 17499 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before; 17500 verifyFormat("int const a :5;\n" 17501 "int oneTwoThree :23;", 17502 Alignment); 17503 17504 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After; 17505 verifyFormat("int const a : 5;\n" 17506 "int oneTwoThree: 23;", 17507 Alignment); 17508 17509 // Known limitations: ':' is only recognized as a bitfield colon when 17510 // followed by a number. 17511 /* 17512 verifyFormat("int oneTwoThree : SOME_CONSTANT;\n" 17513 "int a : 5;", 17514 Alignment); 17515 */ 17516 } 17517 17518 TEST_F(FormatTest, AlignConsecutiveDeclarations) { 17519 FormatStyle Alignment = getLLVMStyle(); 17520 Alignment.AlignConsecutiveMacros.Enabled = true; 17521 Alignment.PointerAlignment = FormatStyle::PAS_Right; 17522 verifyFormat("float const a = 5;\n" 17523 "int oneTwoThree = 123;", 17524 Alignment); 17525 verifyFormat("int a = 5;\n" 17526 "float const oneTwoThree = 123;", 17527 Alignment); 17528 17529 Alignment.AlignConsecutiveDeclarations.Enabled = true; 17530 verifyFormat("float const a = 5;\n" 17531 "int oneTwoThree = 123;", 17532 Alignment); 17533 verifyFormat("int a = method();\n" 17534 "float const oneTwoThree = 133;", 17535 Alignment); 17536 verifyFormat("int i = 1, j = 10;\n" 17537 "something = 2000;", 17538 Alignment); 17539 verifyFormat("something = 2000;\n" 17540 "int i = 1, j = 10;\n", 17541 Alignment); 17542 verifyFormat("float something = 2000;\n" 17543 "double another = 911;\n" 17544 "int i = 1, j = 10;\n" 17545 "const int *oneMore = 1;\n" 17546 "unsigned i = 2;", 17547 Alignment); 17548 verifyFormat("float a = 5;\n" 17549 "int one = 1;\n" 17550 "method();\n" 17551 "const double oneTwoThree = 123;\n" 17552 "const unsigned int oneTwo = 12;", 17553 Alignment); 17554 verifyFormat("int oneTwoThree{0}; // comment\n" 17555 "unsigned oneTwo; // comment", 17556 Alignment); 17557 verifyFormat("unsigned int *a;\n" 17558 "int *b;\n" 17559 "unsigned int Const *c;\n" 17560 "unsigned int const *d;\n" 17561 "unsigned int Const &e;\n" 17562 "unsigned int const &f;", 17563 Alignment); 17564 verifyFormat("Const unsigned int *c;\n" 17565 "const unsigned int *d;\n" 17566 "Const unsigned int &e;\n" 17567 "const unsigned int &f;\n" 17568 "const unsigned g;\n" 17569 "Const unsigned h;", 17570 Alignment); 17571 EXPECT_EQ("float const a = 5;\n" 17572 "\n" 17573 "int oneTwoThree = 123;", 17574 format("float const a = 5;\n" 17575 "\n" 17576 "int oneTwoThree= 123;", 17577 Alignment)); 17578 EXPECT_EQ("float a = 5;\n" 17579 "int one = 1;\n" 17580 "\n" 17581 "unsigned oneTwoThree = 123;", 17582 format("float a = 5;\n" 17583 "int one = 1;\n" 17584 "\n" 17585 "unsigned oneTwoThree = 123;", 17586 Alignment)); 17587 EXPECT_EQ("float a = 5;\n" 17588 "int one = 1;\n" 17589 "\n" 17590 "unsigned oneTwoThree = 123;\n" 17591 "int oneTwo = 12;", 17592 format("float a = 5;\n" 17593 "int one = 1;\n" 17594 "\n" 17595 "unsigned oneTwoThree = 123;\n" 17596 "int oneTwo = 12;", 17597 Alignment)); 17598 // Function prototype alignment 17599 verifyFormat("int a();\n" 17600 "double b();", 17601 Alignment); 17602 verifyFormat("int a(int x);\n" 17603 "double b();", 17604 Alignment); 17605 unsigned OldColumnLimit = Alignment.ColumnLimit; 17606 // We need to set ColumnLimit to zero, in order to stress nested alignments, 17607 // otherwise the function parameters will be re-flowed onto a single line. 17608 Alignment.ColumnLimit = 0; 17609 EXPECT_EQ("int a(int x,\n" 17610 " float y);\n" 17611 "double b(int x,\n" 17612 " double y);", 17613 format("int a(int x,\n" 17614 " float y);\n" 17615 "double b(int x,\n" 17616 " double y);", 17617 Alignment)); 17618 // This ensures that function parameters of function declarations are 17619 // correctly indented when their owning functions are indented. 17620 // The failure case here is for 'double y' to not be indented enough. 17621 EXPECT_EQ("double a(int x);\n" 17622 "int b(int y,\n" 17623 " double z);", 17624 format("double a(int x);\n" 17625 "int b(int y,\n" 17626 " double z);", 17627 Alignment)); 17628 // Set ColumnLimit low so that we induce wrapping immediately after 17629 // the function name and opening paren. 17630 Alignment.ColumnLimit = 13; 17631 verifyFormat("int function(\n" 17632 " int x,\n" 17633 " bool y);", 17634 Alignment); 17635 Alignment.ColumnLimit = OldColumnLimit; 17636 // Ensure function pointers don't screw up recursive alignment 17637 verifyFormat("int a(int x, void (*fp)(int y));\n" 17638 "double b();", 17639 Alignment); 17640 Alignment.AlignConsecutiveAssignments.Enabled = true; 17641 // Ensure recursive alignment is broken by function braces, so that the 17642 // "a = 1" does not align with subsequent assignments inside the function 17643 // body. 17644 verifyFormat("int func(int a = 1) {\n" 17645 " int b = 2;\n" 17646 " int cc = 3;\n" 17647 "}", 17648 Alignment); 17649 verifyFormat("float something = 2000;\n" 17650 "double another = 911;\n" 17651 "int i = 1, j = 10;\n" 17652 "const int *oneMore = 1;\n" 17653 "unsigned i = 2;", 17654 Alignment); 17655 verifyFormat("int oneTwoThree = {0}; // comment\n" 17656 "unsigned oneTwo = 0; // comment", 17657 Alignment); 17658 // Make sure that scope is correctly tracked, in the absence of braces 17659 verifyFormat("for (int i = 0; i < n; i++)\n" 17660 " j = i;\n" 17661 "double x = 1;\n", 17662 Alignment); 17663 verifyFormat("if (int i = 0)\n" 17664 " j = i;\n" 17665 "double x = 1;\n", 17666 Alignment); 17667 // Ensure operator[] and operator() are comprehended 17668 verifyFormat("struct test {\n" 17669 " long long int foo();\n" 17670 " int operator[](int a);\n" 17671 " double bar();\n" 17672 "};\n", 17673 Alignment); 17674 verifyFormat("struct test {\n" 17675 " long long int foo();\n" 17676 " int operator()(int a);\n" 17677 " double bar();\n" 17678 "};\n", 17679 Alignment); 17680 // http://llvm.org/PR52914 17681 verifyFormat("char *a[] = {\"a\", // comment\n" 17682 " \"bb\"};\n" 17683 "int bbbbbbb = 0;", 17684 Alignment); 17685 17686 // PAS_Right 17687 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17688 " int const i = 1;\n" 17689 " int *j = 2;\n" 17690 " int big = 10000;\n" 17691 "\n" 17692 " unsigned oneTwoThree = 123;\n" 17693 " int oneTwo = 12;\n" 17694 " method();\n" 17695 " float k = 2;\n" 17696 " int ll = 10000;\n" 17697 "}", 17698 format("void SomeFunction(int parameter= 0) {\n" 17699 " int const i= 1;\n" 17700 " int *j=2;\n" 17701 " int big = 10000;\n" 17702 "\n" 17703 "unsigned oneTwoThree =123;\n" 17704 "int oneTwo = 12;\n" 17705 " method();\n" 17706 "float k= 2;\n" 17707 "int ll=10000;\n" 17708 "}", 17709 Alignment)); 17710 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17711 " int const i = 1;\n" 17712 " int **j = 2, ***k;\n" 17713 " int &k = i;\n" 17714 " int &&l = i + j;\n" 17715 " int big = 10000;\n" 17716 "\n" 17717 " unsigned oneTwoThree = 123;\n" 17718 " int oneTwo = 12;\n" 17719 " method();\n" 17720 " float k = 2;\n" 17721 " int ll = 10000;\n" 17722 "}", 17723 format("void SomeFunction(int parameter= 0) {\n" 17724 " int const i= 1;\n" 17725 " int **j=2,***k;\n" 17726 "int &k=i;\n" 17727 "int &&l=i+j;\n" 17728 " int big = 10000;\n" 17729 "\n" 17730 "unsigned oneTwoThree =123;\n" 17731 "int oneTwo = 12;\n" 17732 " method();\n" 17733 "float k= 2;\n" 17734 "int ll=10000;\n" 17735 "}", 17736 Alignment)); 17737 // variables are aligned at their name, pointers are at the right most 17738 // position 17739 verifyFormat("int *a;\n" 17740 "int **b;\n" 17741 "int ***c;\n" 17742 "int foobar;\n", 17743 Alignment); 17744 17745 // PAS_Left 17746 FormatStyle AlignmentLeft = Alignment; 17747 AlignmentLeft.PointerAlignment = FormatStyle::PAS_Left; 17748 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17749 " int const i = 1;\n" 17750 " int* j = 2;\n" 17751 " int big = 10000;\n" 17752 "\n" 17753 " unsigned oneTwoThree = 123;\n" 17754 " int oneTwo = 12;\n" 17755 " method();\n" 17756 " float k = 2;\n" 17757 " int ll = 10000;\n" 17758 "}", 17759 format("void SomeFunction(int parameter= 0) {\n" 17760 " int const i= 1;\n" 17761 " int *j=2;\n" 17762 " int big = 10000;\n" 17763 "\n" 17764 "unsigned oneTwoThree =123;\n" 17765 "int oneTwo = 12;\n" 17766 " method();\n" 17767 "float k= 2;\n" 17768 "int ll=10000;\n" 17769 "}", 17770 AlignmentLeft)); 17771 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17772 " int const i = 1;\n" 17773 " int** j = 2;\n" 17774 " int& k = i;\n" 17775 " int&& l = i + j;\n" 17776 " int big = 10000;\n" 17777 "\n" 17778 " unsigned oneTwoThree = 123;\n" 17779 " int oneTwo = 12;\n" 17780 " method();\n" 17781 " float k = 2;\n" 17782 " int ll = 10000;\n" 17783 "}", 17784 format("void SomeFunction(int parameter= 0) {\n" 17785 " int const i= 1;\n" 17786 " int **j=2;\n" 17787 "int &k=i;\n" 17788 "int &&l=i+j;\n" 17789 " int big = 10000;\n" 17790 "\n" 17791 "unsigned oneTwoThree =123;\n" 17792 "int oneTwo = 12;\n" 17793 " method();\n" 17794 "float k= 2;\n" 17795 "int ll=10000;\n" 17796 "}", 17797 AlignmentLeft)); 17798 // variables are aligned at their name, pointers are at the left most position 17799 verifyFormat("int* a;\n" 17800 "int** b;\n" 17801 "int*** c;\n" 17802 "int foobar;\n", 17803 AlignmentLeft); 17804 17805 // PAS_Middle 17806 FormatStyle AlignmentMiddle = Alignment; 17807 AlignmentMiddle.PointerAlignment = FormatStyle::PAS_Middle; 17808 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17809 " int const i = 1;\n" 17810 " int * j = 2;\n" 17811 " int big = 10000;\n" 17812 "\n" 17813 " unsigned oneTwoThree = 123;\n" 17814 " int oneTwo = 12;\n" 17815 " method();\n" 17816 " float k = 2;\n" 17817 " int ll = 10000;\n" 17818 "}", 17819 format("void SomeFunction(int parameter= 0) {\n" 17820 " int const i= 1;\n" 17821 " int *j=2;\n" 17822 " int big = 10000;\n" 17823 "\n" 17824 "unsigned oneTwoThree =123;\n" 17825 "int oneTwo = 12;\n" 17826 " method();\n" 17827 "float k= 2;\n" 17828 "int ll=10000;\n" 17829 "}", 17830 AlignmentMiddle)); 17831 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17832 " int const i = 1;\n" 17833 " int ** j = 2, ***k;\n" 17834 " int & k = i;\n" 17835 " int && l = i + j;\n" 17836 " int big = 10000;\n" 17837 "\n" 17838 " unsigned oneTwoThree = 123;\n" 17839 " int oneTwo = 12;\n" 17840 " method();\n" 17841 " float k = 2;\n" 17842 " int ll = 10000;\n" 17843 "}", 17844 format("void SomeFunction(int parameter= 0) {\n" 17845 " int const i= 1;\n" 17846 " int **j=2,***k;\n" 17847 "int &k=i;\n" 17848 "int &&l=i+j;\n" 17849 " int big = 10000;\n" 17850 "\n" 17851 "unsigned oneTwoThree =123;\n" 17852 "int oneTwo = 12;\n" 17853 " method();\n" 17854 "float k= 2;\n" 17855 "int ll=10000;\n" 17856 "}", 17857 AlignmentMiddle)); 17858 // variables are aligned at their name, pointers are in the middle 17859 verifyFormat("int * a;\n" 17860 "int * b;\n" 17861 "int *** c;\n" 17862 "int foobar;\n", 17863 AlignmentMiddle); 17864 17865 Alignment.AlignConsecutiveAssignments.Enabled = false; 17866 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 17867 verifyFormat("#define A \\\n" 17868 " int aaaa = 12; \\\n" 17869 " float b = 23; \\\n" 17870 " const int ccc = 234; \\\n" 17871 " unsigned dddddddddd = 2345;", 17872 Alignment); 17873 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 17874 verifyFormat("#define A \\\n" 17875 " int aaaa = 12; \\\n" 17876 " float b = 23; \\\n" 17877 " const int ccc = 234; \\\n" 17878 " unsigned dddddddddd = 2345;", 17879 Alignment); 17880 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 17881 Alignment.ColumnLimit = 30; 17882 verifyFormat("#define A \\\n" 17883 " int aaaa = 12; \\\n" 17884 " float b = 23; \\\n" 17885 " const int ccc = 234; \\\n" 17886 " int dddddddddd = 2345;", 17887 Alignment); 17888 Alignment.ColumnLimit = 80; 17889 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 17890 "k = 4, int l = 5,\n" 17891 " int m = 6) {\n" 17892 " const int j = 10;\n" 17893 " otherThing = 1;\n" 17894 "}", 17895 Alignment); 17896 verifyFormat("void SomeFunction(int parameter = 0) {\n" 17897 " int const i = 1;\n" 17898 " int *j = 2;\n" 17899 " int big = 10000;\n" 17900 "}", 17901 Alignment); 17902 verifyFormat("class C {\n" 17903 "public:\n" 17904 " int i = 1;\n" 17905 " virtual void f() = 0;\n" 17906 "};", 17907 Alignment); 17908 verifyFormat("float i = 1;\n" 17909 "if (SomeType t = getSomething()) {\n" 17910 "}\n" 17911 "const unsigned j = 2;\n" 17912 "int big = 10000;", 17913 Alignment); 17914 verifyFormat("float j = 7;\n" 17915 "for (int k = 0; k < N; ++k) {\n" 17916 "}\n" 17917 "unsigned j = 2;\n" 17918 "int big = 10000;\n" 17919 "}", 17920 Alignment); 17921 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 17922 verifyFormat("float i = 1;\n" 17923 "LooooooooooongType loooooooooooooooooooooongVariable\n" 17924 " = someLooooooooooooooooongFunction();\n" 17925 "int j = 2;", 17926 Alignment); 17927 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 17928 verifyFormat("int i = 1;\n" 17929 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 17930 " someLooooooooooooooooongFunction();\n" 17931 "int j = 2;", 17932 Alignment); 17933 17934 Alignment.AlignConsecutiveAssignments.Enabled = true; 17935 verifyFormat("auto lambda = []() {\n" 17936 " auto ii = 0;\n" 17937 " float j = 0;\n" 17938 " return 0;\n" 17939 "};\n" 17940 "int i = 0;\n" 17941 "float i2 = 0;\n" 17942 "auto v = type{\n" 17943 " i = 1, //\n" 17944 " (i = 2), //\n" 17945 " i = 3 //\n" 17946 "};", 17947 Alignment); 17948 Alignment.AlignConsecutiveAssignments.Enabled = false; 17949 17950 verifyFormat( 17951 "int i = 1;\n" 17952 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 17953 " loooooooooooooooooooooongParameterB);\n" 17954 "int j = 2;", 17955 Alignment); 17956 17957 // Test interactions with ColumnLimit and AlignConsecutiveAssignments: 17958 // We expect declarations and assignments to align, as long as it doesn't 17959 // exceed the column limit, starting a new alignment sequence whenever it 17960 // happens. 17961 Alignment.AlignConsecutiveAssignments.Enabled = true; 17962 Alignment.ColumnLimit = 30; 17963 verifyFormat("float ii = 1;\n" 17964 "unsigned j = 2;\n" 17965 "int someVerylongVariable = 1;\n" 17966 "AnotherLongType ll = 123456;\n" 17967 "VeryVeryLongType k = 2;\n" 17968 "int myvar = 1;", 17969 Alignment); 17970 Alignment.ColumnLimit = 80; 17971 Alignment.AlignConsecutiveAssignments.Enabled = false; 17972 17973 verifyFormat( 17974 "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n" 17975 " typename LongType, typename B>\n" 17976 "auto foo() {}\n", 17977 Alignment); 17978 verifyFormat("float a, b = 1;\n" 17979 "int c = 2;\n" 17980 "int dd = 3;\n", 17981 Alignment); 17982 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17983 "float b[1][] = {{3.f}};\n", 17984 Alignment); 17985 Alignment.AlignConsecutiveAssignments.Enabled = true; 17986 verifyFormat("float a, b = 1;\n" 17987 "int c = 2;\n" 17988 "int dd = 3;\n", 17989 Alignment); 17990 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17991 "float b[1][] = {{3.f}};\n", 17992 Alignment); 17993 Alignment.AlignConsecutiveAssignments.Enabled = false; 17994 17995 Alignment.ColumnLimit = 30; 17996 Alignment.BinPackParameters = false; 17997 verifyFormat("void foo(float a,\n" 17998 " float b,\n" 17999 " int c,\n" 18000 " uint32_t *d) {\n" 18001 " int *e = 0;\n" 18002 " float f = 0;\n" 18003 " double g = 0;\n" 18004 "}\n" 18005 "void bar(ino_t a,\n" 18006 " int b,\n" 18007 " uint32_t *c,\n" 18008 " bool d) {}\n", 18009 Alignment); 18010 Alignment.BinPackParameters = true; 18011 Alignment.ColumnLimit = 80; 18012 18013 // Bug 33507 18014 Alignment.PointerAlignment = FormatStyle::PAS_Middle; 18015 verifyFormat( 18016 "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n" 18017 " static const Version verVs2017;\n" 18018 " return true;\n" 18019 "});\n", 18020 Alignment); 18021 Alignment.PointerAlignment = FormatStyle::PAS_Right; 18022 18023 // See llvm.org/PR35641 18024 Alignment.AlignConsecutiveDeclarations.Enabled = true; 18025 verifyFormat("int func() { //\n" 18026 " int b;\n" 18027 " unsigned c;\n" 18028 "}", 18029 Alignment); 18030 18031 // See PR37175 18032 FormatStyle Style = getMozillaStyle(); 18033 Style.AlignConsecutiveDeclarations.Enabled = true; 18034 EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n" 18035 "foo(int a);", 18036 format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style)); 18037 18038 Alignment.PointerAlignment = FormatStyle::PAS_Left; 18039 verifyFormat("unsigned int* a;\n" 18040 "int* b;\n" 18041 "unsigned int Const* c;\n" 18042 "unsigned int const* d;\n" 18043 "unsigned int Const& e;\n" 18044 "unsigned int const& f;", 18045 Alignment); 18046 verifyFormat("Const unsigned int* c;\n" 18047 "const unsigned int* d;\n" 18048 "Const unsigned int& e;\n" 18049 "const unsigned int& f;\n" 18050 "const unsigned g;\n" 18051 "Const unsigned h;", 18052 Alignment); 18053 18054 Alignment.PointerAlignment = FormatStyle::PAS_Middle; 18055 verifyFormat("unsigned int * a;\n" 18056 "int * b;\n" 18057 "unsigned int Const * c;\n" 18058 "unsigned int const * d;\n" 18059 "unsigned int Const & e;\n" 18060 "unsigned int const & f;", 18061 Alignment); 18062 verifyFormat("Const unsigned int * c;\n" 18063 "const unsigned int * d;\n" 18064 "Const unsigned int & e;\n" 18065 "const unsigned int & f;\n" 18066 "const unsigned g;\n" 18067 "Const unsigned h;", 18068 Alignment); 18069 18070 // See PR46529 18071 FormatStyle BracedAlign = getLLVMStyle(); 18072 BracedAlign.AlignConsecutiveDeclarations.Enabled = true; 18073 verifyFormat("const auto result{[]() {\n" 18074 " const auto something = 1;\n" 18075 " return 2;\n" 18076 "}};", 18077 BracedAlign); 18078 verifyFormat("int foo{[]() {\n" 18079 " int bar{0};\n" 18080 " return 0;\n" 18081 "}()};", 18082 BracedAlign); 18083 BracedAlign.Cpp11BracedListStyle = false; 18084 verifyFormat("const auto result{ []() {\n" 18085 " const auto something = 1;\n" 18086 " return 2;\n" 18087 "} };", 18088 BracedAlign); 18089 verifyFormat("int foo{ []() {\n" 18090 " int bar{ 0 };\n" 18091 " return 0;\n" 18092 "}() };", 18093 BracedAlign); 18094 } 18095 18096 TEST_F(FormatTest, AlignWithLineBreaks) { 18097 auto Style = getLLVMStyleWithColumns(120); 18098 18099 EXPECT_EQ(Style.AlignConsecutiveAssignments, 18100 FormatStyle::AlignConsecutiveStyle( 18101 {/*Enabled=*/false, /*AcrossEmptyLines=*/false, 18102 /*AcrossComments=*/false, /*AlignCompound=*/false, 18103 /*PadOperators=*/true})); 18104 EXPECT_EQ(Style.AlignConsecutiveDeclarations, 18105 FormatStyle::AlignConsecutiveStyle({})); 18106 verifyFormat("void foo() {\n" 18107 " int myVar = 5;\n" 18108 " double x = 3.14;\n" 18109 " auto str = \"Hello \"\n" 18110 " \"World\";\n" 18111 " auto s = \"Hello \"\n" 18112 " \"Again\";\n" 18113 "}", 18114 Style); 18115 18116 // clang-format off 18117 verifyFormat("void foo() {\n" 18118 " const int capacityBefore = Entries.capacity();\n" 18119 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 18120 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 18121 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 18122 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 18123 "}", 18124 Style); 18125 // clang-format on 18126 18127 Style.AlignConsecutiveAssignments.Enabled = true; 18128 verifyFormat("void foo() {\n" 18129 " int myVar = 5;\n" 18130 " double x = 3.14;\n" 18131 " auto str = \"Hello \"\n" 18132 " \"World\";\n" 18133 " auto s = \"Hello \"\n" 18134 " \"Again\";\n" 18135 "}", 18136 Style); 18137 18138 // clang-format off 18139 verifyFormat("void foo() {\n" 18140 " const int capacityBefore = Entries.capacity();\n" 18141 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 18142 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 18143 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 18144 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 18145 "}", 18146 Style); 18147 // clang-format on 18148 18149 Style.AlignConsecutiveAssignments.Enabled = false; 18150 Style.AlignConsecutiveDeclarations.Enabled = true; 18151 verifyFormat("void foo() {\n" 18152 " int myVar = 5;\n" 18153 " double x = 3.14;\n" 18154 " auto str = \"Hello \"\n" 18155 " \"World\";\n" 18156 " auto s = \"Hello \"\n" 18157 " \"Again\";\n" 18158 "}", 18159 Style); 18160 18161 // clang-format off 18162 verifyFormat("void foo() {\n" 18163 " const int capacityBefore = Entries.capacity();\n" 18164 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 18165 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 18166 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 18167 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 18168 "}", 18169 Style); 18170 // clang-format on 18171 18172 Style.AlignConsecutiveAssignments.Enabled = true; 18173 Style.AlignConsecutiveDeclarations.Enabled = true; 18174 18175 verifyFormat("void foo() {\n" 18176 " int myVar = 5;\n" 18177 " double x = 3.14;\n" 18178 " auto str = \"Hello \"\n" 18179 " \"World\";\n" 18180 " auto s = \"Hello \"\n" 18181 " \"Again\";\n" 18182 "}", 18183 Style); 18184 18185 // clang-format off 18186 verifyFormat("void foo() {\n" 18187 " const int capacityBefore = Entries.capacity();\n" 18188 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 18189 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 18190 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 18191 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 18192 "}", 18193 Style); 18194 // clang-format on 18195 18196 Style = getLLVMStyleWithColumns(20); 18197 Style.AlignConsecutiveAssignments.Enabled = true; 18198 Style.IndentWidth = 4; 18199 18200 verifyFormat("void foo() {\n" 18201 " int i1 = 1;\n" 18202 " int j = 0;\n" 18203 " int k = bar(\n" 18204 " argument1,\n" 18205 " argument2);\n" 18206 "}", 18207 Style); 18208 18209 verifyFormat("unsigned i = 0;\n" 18210 "int a[] = {\n" 18211 " 1234567890,\n" 18212 " -1234567890};", 18213 Style); 18214 18215 Style.ColumnLimit = 120; 18216 18217 // clang-format off 18218 verifyFormat("void SomeFunc() {\n" 18219 " newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 18220 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 18221 " newWatcher.maxAge = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 18222 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 18223 " newWatcher.max = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 18224 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 18225 "}", 18226 Style); 18227 // clang-format on 18228 18229 Style.BinPackArguments = false; 18230 18231 // clang-format off 18232 verifyFormat("void SomeFunc() {\n" 18233 " newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(\n" 18234 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 18235 " newWatcher.maxAge = ToLegacyTimestamp(GetMaxAge(\n" 18236 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 18237 " newWatcher.max = ToLegacyTimestamp(GetMaxAge(\n" 18238 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 18239 "}", 18240 Style); 18241 // clang-format on 18242 } 18243 18244 TEST_F(FormatTest, AlignWithInitializerPeriods) { 18245 auto Style = getLLVMStyleWithColumns(60); 18246 18247 verifyFormat("void foo1(void) {\n" 18248 " BYTE p[1] = 1;\n" 18249 " A B = {.one_foooooooooooooooo = 2,\n" 18250 " .two_fooooooooooooo = 3,\n" 18251 " .three_fooooooooooooo = 4};\n" 18252 " BYTE payload = 2;\n" 18253 "}", 18254 Style); 18255 18256 Style.AlignConsecutiveAssignments.Enabled = true; 18257 Style.AlignConsecutiveDeclarations.Enabled = false; 18258 verifyFormat("void foo2(void) {\n" 18259 " BYTE p[1] = 1;\n" 18260 " A B = {.one_foooooooooooooooo = 2,\n" 18261 " .two_fooooooooooooo = 3,\n" 18262 " .three_fooooooooooooo = 4};\n" 18263 " BYTE payload = 2;\n" 18264 "}", 18265 Style); 18266 18267 Style.AlignConsecutiveAssignments.Enabled = false; 18268 Style.AlignConsecutiveDeclarations.Enabled = true; 18269 verifyFormat("void foo3(void) {\n" 18270 " BYTE p[1] = 1;\n" 18271 " A B = {.one_foooooooooooooooo = 2,\n" 18272 " .two_fooooooooooooo = 3,\n" 18273 " .three_fooooooooooooo = 4};\n" 18274 " BYTE payload = 2;\n" 18275 "}", 18276 Style); 18277 18278 Style.AlignConsecutiveAssignments.Enabled = true; 18279 Style.AlignConsecutiveDeclarations.Enabled = true; 18280 verifyFormat("void foo4(void) {\n" 18281 " BYTE p[1] = 1;\n" 18282 " A B = {.one_foooooooooooooooo = 2,\n" 18283 " .two_fooooooooooooo = 3,\n" 18284 " .three_fooooooooooooo = 4};\n" 18285 " BYTE payload = 2;\n" 18286 "}", 18287 Style); 18288 } 18289 18290 TEST_F(FormatTest, LinuxBraceBreaking) { 18291 FormatStyle LinuxBraceStyle = getLLVMStyle(); 18292 LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux; 18293 verifyFormat("namespace a\n" 18294 "{\n" 18295 "class A\n" 18296 "{\n" 18297 " void f()\n" 18298 " {\n" 18299 " if (true) {\n" 18300 " a();\n" 18301 " b();\n" 18302 " } else {\n" 18303 " a();\n" 18304 " }\n" 18305 " }\n" 18306 " void g() { return; }\n" 18307 "};\n" 18308 "struct B {\n" 18309 " int x;\n" 18310 "};\n" 18311 "} // namespace a\n", 18312 LinuxBraceStyle); 18313 verifyFormat("enum X {\n" 18314 " Y = 0,\n" 18315 "}\n", 18316 LinuxBraceStyle); 18317 verifyFormat("struct S {\n" 18318 " int Type;\n" 18319 " union {\n" 18320 " int x;\n" 18321 " double y;\n" 18322 " } Value;\n" 18323 " class C\n" 18324 " {\n" 18325 " MyFavoriteType Value;\n" 18326 " } Class;\n" 18327 "}\n", 18328 LinuxBraceStyle); 18329 } 18330 18331 TEST_F(FormatTest, MozillaBraceBreaking) { 18332 FormatStyle MozillaBraceStyle = getLLVMStyle(); 18333 MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla; 18334 MozillaBraceStyle.FixNamespaceComments = false; 18335 verifyFormat("namespace a {\n" 18336 "class A\n" 18337 "{\n" 18338 " void f()\n" 18339 " {\n" 18340 " if (true) {\n" 18341 " a();\n" 18342 " b();\n" 18343 " }\n" 18344 " }\n" 18345 " void g() { return; }\n" 18346 "};\n" 18347 "enum E\n" 18348 "{\n" 18349 " A,\n" 18350 " // foo\n" 18351 " B,\n" 18352 " C\n" 18353 "};\n" 18354 "struct B\n" 18355 "{\n" 18356 " int x;\n" 18357 "};\n" 18358 "}\n", 18359 MozillaBraceStyle); 18360 verifyFormat("struct S\n" 18361 "{\n" 18362 " int Type;\n" 18363 " union\n" 18364 " {\n" 18365 " int x;\n" 18366 " double y;\n" 18367 " } Value;\n" 18368 " class C\n" 18369 " {\n" 18370 " MyFavoriteType Value;\n" 18371 " } Class;\n" 18372 "}\n", 18373 MozillaBraceStyle); 18374 } 18375 18376 TEST_F(FormatTest, StroustrupBraceBreaking) { 18377 FormatStyle StroustrupBraceStyle = getLLVMStyle(); 18378 StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 18379 verifyFormat("namespace a {\n" 18380 "class A {\n" 18381 " void f()\n" 18382 " {\n" 18383 " if (true) {\n" 18384 " a();\n" 18385 " b();\n" 18386 " }\n" 18387 " }\n" 18388 " void g() { return; }\n" 18389 "};\n" 18390 "struct B {\n" 18391 " int x;\n" 18392 "};\n" 18393 "} // namespace a\n", 18394 StroustrupBraceStyle); 18395 18396 verifyFormat("void foo()\n" 18397 "{\n" 18398 " if (a) {\n" 18399 " a();\n" 18400 " }\n" 18401 " else {\n" 18402 " b();\n" 18403 " }\n" 18404 "}\n", 18405 StroustrupBraceStyle); 18406 18407 verifyFormat("#ifdef _DEBUG\n" 18408 "int foo(int i = 0)\n" 18409 "#else\n" 18410 "int foo(int i = 5)\n" 18411 "#endif\n" 18412 "{\n" 18413 " return i;\n" 18414 "}", 18415 StroustrupBraceStyle); 18416 18417 verifyFormat("void foo() {}\n" 18418 "void bar()\n" 18419 "#ifdef _DEBUG\n" 18420 "{\n" 18421 " foo();\n" 18422 "}\n" 18423 "#else\n" 18424 "{\n" 18425 "}\n" 18426 "#endif", 18427 StroustrupBraceStyle); 18428 18429 verifyFormat("void foobar() { int i = 5; }\n" 18430 "#ifdef _DEBUG\n" 18431 "void bar() {}\n" 18432 "#else\n" 18433 "void bar() { foobar(); }\n" 18434 "#endif", 18435 StroustrupBraceStyle); 18436 } 18437 18438 TEST_F(FormatTest, AllmanBraceBreaking) { 18439 FormatStyle AllmanBraceStyle = getLLVMStyle(); 18440 AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman; 18441 18442 EXPECT_EQ("namespace a\n" 18443 "{\n" 18444 "void f();\n" 18445 "void g();\n" 18446 "} // namespace a\n", 18447 format("namespace a\n" 18448 "{\n" 18449 "void f();\n" 18450 "void g();\n" 18451 "}\n", 18452 AllmanBraceStyle)); 18453 18454 verifyFormat("namespace a\n" 18455 "{\n" 18456 "class A\n" 18457 "{\n" 18458 " void f()\n" 18459 " {\n" 18460 " if (true)\n" 18461 " {\n" 18462 " a();\n" 18463 " b();\n" 18464 " }\n" 18465 " }\n" 18466 " void g() { return; }\n" 18467 "};\n" 18468 "struct B\n" 18469 "{\n" 18470 " int x;\n" 18471 "};\n" 18472 "union C\n" 18473 "{\n" 18474 "};\n" 18475 "} // namespace a", 18476 AllmanBraceStyle); 18477 18478 verifyFormat("void f()\n" 18479 "{\n" 18480 " if (true)\n" 18481 " {\n" 18482 " a();\n" 18483 " }\n" 18484 " else if (false)\n" 18485 " {\n" 18486 " b();\n" 18487 " }\n" 18488 " else\n" 18489 " {\n" 18490 " c();\n" 18491 " }\n" 18492 "}\n", 18493 AllmanBraceStyle); 18494 18495 verifyFormat("void f()\n" 18496 "{\n" 18497 " for (int i = 0; i < 10; ++i)\n" 18498 " {\n" 18499 " a();\n" 18500 " }\n" 18501 " while (false)\n" 18502 " {\n" 18503 " b();\n" 18504 " }\n" 18505 " do\n" 18506 " {\n" 18507 " c();\n" 18508 " } while (false)\n" 18509 "}\n", 18510 AllmanBraceStyle); 18511 18512 verifyFormat("void f(int a)\n" 18513 "{\n" 18514 " switch (a)\n" 18515 " {\n" 18516 " case 0:\n" 18517 " break;\n" 18518 " case 1:\n" 18519 " {\n" 18520 " break;\n" 18521 " }\n" 18522 " case 2:\n" 18523 " {\n" 18524 " }\n" 18525 " break;\n" 18526 " default:\n" 18527 " break;\n" 18528 " }\n" 18529 "}\n", 18530 AllmanBraceStyle); 18531 18532 verifyFormat("enum X\n" 18533 "{\n" 18534 " Y = 0,\n" 18535 "}\n", 18536 AllmanBraceStyle); 18537 verifyFormat("enum X\n" 18538 "{\n" 18539 " Y = 0\n" 18540 "}\n", 18541 AllmanBraceStyle); 18542 18543 verifyFormat("@interface BSApplicationController ()\n" 18544 "{\n" 18545 "@private\n" 18546 " id _extraIvar;\n" 18547 "}\n" 18548 "@end\n", 18549 AllmanBraceStyle); 18550 18551 verifyFormat("#ifdef _DEBUG\n" 18552 "int foo(int i = 0)\n" 18553 "#else\n" 18554 "int foo(int i = 5)\n" 18555 "#endif\n" 18556 "{\n" 18557 " return i;\n" 18558 "}", 18559 AllmanBraceStyle); 18560 18561 verifyFormat("void foo() {}\n" 18562 "void bar()\n" 18563 "#ifdef _DEBUG\n" 18564 "{\n" 18565 " foo();\n" 18566 "}\n" 18567 "#else\n" 18568 "{\n" 18569 "}\n" 18570 "#endif", 18571 AllmanBraceStyle); 18572 18573 verifyFormat("void foobar() { int i = 5; }\n" 18574 "#ifdef _DEBUG\n" 18575 "void bar() {}\n" 18576 "#else\n" 18577 "void bar() { foobar(); }\n" 18578 "#endif", 18579 AllmanBraceStyle); 18580 18581 EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine, 18582 FormatStyle::SLS_All); 18583 18584 verifyFormat("[](int i) { return i + 2; };\n" 18585 "[](int i, int j)\n" 18586 "{\n" 18587 " auto x = i + j;\n" 18588 " auto y = i * j;\n" 18589 " return x ^ y;\n" 18590 "};\n" 18591 "void foo()\n" 18592 "{\n" 18593 " auto shortLambda = [](int i) { return i + 2; };\n" 18594 " auto longLambda = [](int i, int j)\n" 18595 " {\n" 18596 " auto x = i + j;\n" 18597 " auto y = i * j;\n" 18598 " return x ^ y;\n" 18599 " };\n" 18600 "}", 18601 AllmanBraceStyle); 18602 18603 AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 18604 18605 verifyFormat("[](int i)\n" 18606 "{\n" 18607 " return i + 2;\n" 18608 "};\n" 18609 "[](int i, int j)\n" 18610 "{\n" 18611 " auto x = i + j;\n" 18612 " auto y = i * j;\n" 18613 " return x ^ y;\n" 18614 "};\n" 18615 "void foo()\n" 18616 "{\n" 18617 " auto shortLambda = [](int i)\n" 18618 " {\n" 18619 " return i + 2;\n" 18620 " };\n" 18621 " auto longLambda = [](int i, int j)\n" 18622 " {\n" 18623 " auto x = i + j;\n" 18624 " auto y = i * j;\n" 18625 " return x ^ y;\n" 18626 " };\n" 18627 "}", 18628 AllmanBraceStyle); 18629 18630 // Reset 18631 AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All; 18632 18633 // This shouldn't affect ObjC blocks.. 18634 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n" 18635 " // ...\n" 18636 " int i;\n" 18637 "}];", 18638 AllmanBraceStyle); 18639 verifyFormat("void (^block)(void) = ^{\n" 18640 " // ...\n" 18641 " int i;\n" 18642 "};", 18643 AllmanBraceStyle); 18644 // .. or dict literals. 18645 verifyFormat("void f()\n" 18646 "{\n" 18647 " // ...\n" 18648 " [object someMethod:@{@\"a\" : @\"b\"}];\n" 18649 "}", 18650 AllmanBraceStyle); 18651 verifyFormat("void f()\n" 18652 "{\n" 18653 " // ...\n" 18654 " [object someMethod:@{a : @\"b\"}];\n" 18655 "}", 18656 AllmanBraceStyle); 18657 verifyFormat("int f()\n" 18658 "{ // comment\n" 18659 " return 42;\n" 18660 "}", 18661 AllmanBraceStyle); 18662 18663 AllmanBraceStyle.ColumnLimit = 19; 18664 verifyFormat("void f() { int i; }", AllmanBraceStyle); 18665 AllmanBraceStyle.ColumnLimit = 18; 18666 verifyFormat("void f()\n" 18667 "{\n" 18668 " int i;\n" 18669 "}", 18670 AllmanBraceStyle); 18671 AllmanBraceStyle.ColumnLimit = 80; 18672 18673 FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle; 18674 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = 18675 FormatStyle::SIS_WithoutElse; 18676 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true; 18677 verifyFormat("void f(bool b)\n" 18678 "{\n" 18679 " if (b)\n" 18680 " {\n" 18681 " return;\n" 18682 " }\n" 18683 "}\n", 18684 BreakBeforeBraceShortIfs); 18685 verifyFormat("void f(bool b)\n" 18686 "{\n" 18687 " if constexpr (b)\n" 18688 " {\n" 18689 " return;\n" 18690 " }\n" 18691 "}\n", 18692 BreakBeforeBraceShortIfs); 18693 verifyFormat("void f(bool b)\n" 18694 "{\n" 18695 " if CONSTEXPR (b)\n" 18696 " {\n" 18697 " return;\n" 18698 " }\n" 18699 "}\n", 18700 BreakBeforeBraceShortIfs); 18701 verifyFormat("void f(bool b)\n" 18702 "{\n" 18703 " if (b) return;\n" 18704 "}\n", 18705 BreakBeforeBraceShortIfs); 18706 verifyFormat("void f(bool b)\n" 18707 "{\n" 18708 " if constexpr (b) return;\n" 18709 "}\n", 18710 BreakBeforeBraceShortIfs); 18711 verifyFormat("void f(bool b)\n" 18712 "{\n" 18713 " if CONSTEXPR (b) return;\n" 18714 "}\n", 18715 BreakBeforeBraceShortIfs); 18716 verifyFormat("void f(bool b)\n" 18717 "{\n" 18718 " while (b)\n" 18719 " {\n" 18720 " return;\n" 18721 " }\n" 18722 "}\n", 18723 BreakBeforeBraceShortIfs); 18724 } 18725 18726 TEST_F(FormatTest, WhitesmithsBraceBreaking) { 18727 FormatStyle WhitesmithsBraceStyle = getLLVMStyleWithColumns(0); 18728 WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 18729 18730 // Make a few changes to the style for testing purposes 18731 WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine = 18732 FormatStyle::SFS_Empty; 18733 WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 18734 18735 // FIXME: this test case can't decide whether there should be a blank line 18736 // after the ~D() line or not. It adds one if one doesn't exist in the test 18737 // and it removes the line if one exists. 18738 /* 18739 verifyFormat("class A;\n" 18740 "namespace B\n" 18741 " {\n" 18742 "class C;\n" 18743 "// Comment\n" 18744 "class D\n" 18745 " {\n" 18746 "public:\n" 18747 " D();\n" 18748 " ~D() {}\n" 18749 "private:\n" 18750 " enum E\n" 18751 " {\n" 18752 " F\n" 18753 " }\n" 18754 " };\n" 18755 " } // namespace B\n", 18756 WhitesmithsBraceStyle); 18757 */ 18758 18759 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None; 18760 verifyFormat("namespace a\n" 18761 " {\n" 18762 "class A\n" 18763 " {\n" 18764 " void f()\n" 18765 " {\n" 18766 " if (true)\n" 18767 " {\n" 18768 " a();\n" 18769 " b();\n" 18770 " }\n" 18771 " }\n" 18772 " void g()\n" 18773 " {\n" 18774 " return;\n" 18775 " }\n" 18776 " };\n" 18777 "struct B\n" 18778 " {\n" 18779 " int x;\n" 18780 " };\n" 18781 " } // namespace a", 18782 WhitesmithsBraceStyle); 18783 18784 verifyFormat("namespace a\n" 18785 " {\n" 18786 "namespace b\n" 18787 " {\n" 18788 "class A\n" 18789 " {\n" 18790 " void f()\n" 18791 " {\n" 18792 " if (true)\n" 18793 " {\n" 18794 " a();\n" 18795 " b();\n" 18796 " }\n" 18797 " }\n" 18798 " void g()\n" 18799 " {\n" 18800 " return;\n" 18801 " }\n" 18802 " };\n" 18803 "struct B\n" 18804 " {\n" 18805 " int x;\n" 18806 " };\n" 18807 " } // namespace b\n" 18808 " } // namespace a", 18809 WhitesmithsBraceStyle); 18810 18811 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner; 18812 verifyFormat("namespace a\n" 18813 " {\n" 18814 "namespace b\n" 18815 " {\n" 18816 " class A\n" 18817 " {\n" 18818 " void f()\n" 18819 " {\n" 18820 " if (true)\n" 18821 " {\n" 18822 " a();\n" 18823 " b();\n" 18824 " }\n" 18825 " }\n" 18826 " void g()\n" 18827 " {\n" 18828 " return;\n" 18829 " }\n" 18830 " };\n" 18831 " struct B\n" 18832 " {\n" 18833 " int x;\n" 18834 " };\n" 18835 " } // namespace b\n" 18836 " } // namespace a", 18837 WhitesmithsBraceStyle); 18838 18839 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All; 18840 verifyFormat("namespace a\n" 18841 " {\n" 18842 " namespace b\n" 18843 " {\n" 18844 " class A\n" 18845 " {\n" 18846 " void f()\n" 18847 " {\n" 18848 " if (true)\n" 18849 " {\n" 18850 " a();\n" 18851 " b();\n" 18852 " }\n" 18853 " }\n" 18854 " void g()\n" 18855 " {\n" 18856 " return;\n" 18857 " }\n" 18858 " };\n" 18859 " struct B\n" 18860 " {\n" 18861 " int x;\n" 18862 " };\n" 18863 " } // namespace b\n" 18864 " } // namespace a", 18865 WhitesmithsBraceStyle); 18866 18867 verifyFormat("void f()\n" 18868 " {\n" 18869 " if (true)\n" 18870 " {\n" 18871 " a();\n" 18872 " }\n" 18873 " else if (false)\n" 18874 " {\n" 18875 " b();\n" 18876 " }\n" 18877 " else\n" 18878 " {\n" 18879 " c();\n" 18880 " }\n" 18881 " }\n", 18882 WhitesmithsBraceStyle); 18883 18884 verifyFormat("void f()\n" 18885 " {\n" 18886 " for (int i = 0; i < 10; ++i)\n" 18887 " {\n" 18888 " a();\n" 18889 " }\n" 18890 " while (false)\n" 18891 " {\n" 18892 " b();\n" 18893 " }\n" 18894 " do\n" 18895 " {\n" 18896 " c();\n" 18897 " } while (false)\n" 18898 " }\n", 18899 WhitesmithsBraceStyle); 18900 18901 WhitesmithsBraceStyle.IndentCaseLabels = true; 18902 verifyFormat("void switchTest1(int a)\n" 18903 " {\n" 18904 " switch (a)\n" 18905 " {\n" 18906 " case 2:\n" 18907 " {\n" 18908 " }\n" 18909 " break;\n" 18910 " }\n" 18911 " }\n", 18912 WhitesmithsBraceStyle); 18913 18914 verifyFormat("void switchTest2(int a)\n" 18915 " {\n" 18916 " switch (a)\n" 18917 " {\n" 18918 " case 0:\n" 18919 " break;\n" 18920 " case 1:\n" 18921 " {\n" 18922 " break;\n" 18923 " }\n" 18924 " case 2:\n" 18925 " {\n" 18926 " }\n" 18927 " break;\n" 18928 " default:\n" 18929 " break;\n" 18930 " }\n" 18931 " }\n", 18932 WhitesmithsBraceStyle); 18933 18934 verifyFormat("void switchTest3(int a)\n" 18935 " {\n" 18936 " switch (a)\n" 18937 " {\n" 18938 " case 0:\n" 18939 " {\n" 18940 " foo(x);\n" 18941 " }\n" 18942 " break;\n" 18943 " default:\n" 18944 " {\n" 18945 " foo(1);\n" 18946 " }\n" 18947 " break;\n" 18948 " }\n" 18949 " }\n", 18950 WhitesmithsBraceStyle); 18951 18952 WhitesmithsBraceStyle.IndentCaseLabels = false; 18953 18954 verifyFormat("void switchTest4(int a)\n" 18955 " {\n" 18956 " switch (a)\n" 18957 " {\n" 18958 " case 2:\n" 18959 " {\n" 18960 " }\n" 18961 " break;\n" 18962 " }\n" 18963 " }\n", 18964 WhitesmithsBraceStyle); 18965 18966 verifyFormat("void switchTest5(int a)\n" 18967 " {\n" 18968 " switch (a)\n" 18969 " {\n" 18970 " case 0:\n" 18971 " break;\n" 18972 " case 1:\n" 18973 " {\n" 18974 " foo();\n" 18975 " break;\n" 18976 " }\n" 18977 " case 2:\n" 18978 " {\n" 18979 " }\n" 18980 " break;\n" 18981 " default:\n" 18982 " break;\n" 18983 " }\n" 18984 " }\n", 18985 WhitesmithsBraceStyle); 18986 18987 verifyFormat("void switchTest6(int a)\n" 18988 " {\n" 18989 " switch (a)\n" 18990 " {\n" 18991 " case 0:\n" 18992 " {\n" 18993 " foo(x);\n" 18994 " }\n" 18995 " break;\n" 18996 " default:\n" 18997 " {\n" 18998 " foo(1);\n" 18999 " }\n" 19000 " break;\n" 19001 " }\n" 19002 " }\n", 19003 WhitesmithsBraceStyle); 19004 19005 verifyFormat("enum X\n" 19006 " {\n" 19007 " Y = 0, // testing\n" 19008 " }\n", 19009 WhitesmithsBraceStyle); 19010 19011 verifyFormat("enum X\n" 19012 " {\n" 19013 " Y = 0\n" 19014 " }\n", 19015 WhitesmithsBraceStyle); 19016 verifyFormat("enum X\n" 19017 " {\n" 19018 " Y = 0,\n" 19019 " Z = 1\n" 19020 " };\n", 19021 WhitesmithsBraceStyle); 19022 19023 verifyFormat("@interface BSApplicationController ()\n" 19024 " {\n" 19025 "@private\n" 19026 " id _extraIvar;\n" 19027 " }\n" 19028 "@end\n", 19029 WhitesmithsBraceStyle); 19030 19031 verifyFormat("#ifdef _DEBUG\n" 19032 "int foo(int i = 0)\n" 19033 "#else\n" 19034 "int foo(int i = 5)\n" 19035 "#endif\n" 19036 " {\n" 19037 " return i;\n" 19038 " }", 19039 WhitesmithsBraceStyle); 19040 19041 verifyFormat("void foo() {}\n" 19042 "void bar()\n" 19043 "#ifdef _DEBUG\n" 19044 " {\n" 19045 " foo();\n" 19046 " }\n" 19047 "#else\n" 19048 " {\n" 19049 " }\n" 19050 "#endif", 19051 WhitesmithsBraceStyle); 19052 19053 verifyFormat("void foobar()\n" 19054 " {\n" 19055 " int i = 5;\n" 19056 " }\n" 19057 "#ifdef _DEBUG\n" 19058 "void bar()\n" 19059 " {\n" 19060 " }\n" 19061 "#else\n" 19062 "void bar()\n" 19063 " {\n" 19064 " foobar();\n" 19065 " }\n" 19066 "#endif", 19067 WhitesmithsBraceStyle); 19068 19069 // This shouldn't affect ObjC blocks.. 19070 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n" 19071 " // ...\n" 19072 " int i;\n" 19073 "}];", 19074 WhitesmithsBraceStyle); 19075 verifyFormat("void (^block)(void) = ^{\n" 19076 " // ...\n" 19077 " int i;\n" 19078 "};", 19079 WhitesmithsBraceStyle); 19080 // .. or dict literals. 19081 verifyFormat("void f()\n" 19082 " {\n" 19083 " [object someMethod:@{@\"a\" : @\"b\"}];\n" 19084 " }", 19085 WhitesmithsBraceStyle); 19086 19087 verifyFormat("int f()\n" 19088 " { // comment\n" 19089 " return 42;\n" 19090 " }", 19091 WhitesmithsBraceStyle); 19092 19093 FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle; 19094 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = 19095 FormatStyle::SIS_OnlyFirstIf; 19096 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true; 19097 verifyFormat("void f(bool b)\n" 19098 " {\n" 19099 " if (b)\n" 19100 " {\n" 19101 " return;\n" 19102 " }\n" 19103 " }\n", 19104 BreakBeforeBraceShortIfs); 19105 verifyFormat("void f(bool b)\n" 19106 " {\n" 19107 " if (b) return;\n" 19108 " }\n", 19109 BreakBeforeBraceShortIfs); 19110 verifyFormat("void f(bool b)\n" 19111 " {\n" 19112 " while (b)\n" 19113 " {\n" 19114 " return;\n" 19115 " }\n" 19116 " }\n", 19117 BreakBeforeBraceShortIfs); 19118 } 19119 19120 TEST_F(FormatTest, GNUBraceBreaking) { 19121 FormatStyle GNUBraceStyle = getLLVMStyle(); 19122 GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU; 19123 verifyFormat("namespace a\n" 19124 "{\n" 19125 "class A\n" 19126 "{\n" 19127 " void f()\n" 19128 " {\n" 19129 " int a;\n" 19130 " {\n" 19131 " int b;\n" 19132 " }\n" 19133 " if (true)\n" 19134 " {\n" 19135 " a();\n" 19136 " b();\n" 19137 " }\n" 19138 " }\n" 19139 " void g() { return; }\n" 19140 "}\n" 19141 "} // namespace a", 19142 GNUBraceStyle); 19143 19144 verifyFormat("void f()\n" 19145 "{\n" 19146 " if (true)\n" 19147 " {\n" 19148 " a();\n" 19149 " }\n" 19150 " else if (false)\n" 19151 " {\n" 19152 " b();\n" 19153 " }\n" 19154 " else\n" 19155 " {\n" 19156 " c();\n" 19157 " }\n" 19158 "}\n", 19159 GNUBraceStyle); 19160 19161 verifyFormat("void f()\n" 19162 "{\n" 19163 " for (int i = 0; i < 10; ++i)\n" 19164 " {\n" 19165 " a();\n" 19166 " }\n" 19167 " while (false)\n" 19168 " {\n" 19169 " b();\n" 19170 " }\n" 19171 " do\n" 19172 " {\n" 19173 " c();\n" 19174 " }\n" 19175 " while (false);\n" 19176 "}\n", 19177 GNUBraceStyle); 19178 19179 verifyFormat("void f(int a)\n" 19180 "{\n" 19181 " switch (a)\n" 19182 " {\n" 19183 " case 0:\n" 19184 " break;\n" 19185 " case 1:\n" 19186 " {\n" 19187 " break;\n" 19188 " }\n" 19189 " case 2:\n" 19190 " {\n" 19191 " }\n" 19192 " break;\n" 19193 " default:\n" 19194 " break;\n" 19195 " }\n" 19196 "}\n", 19197 GNUBraceStyle); 19198 19199 verifyFormat("enum X\n" 19200 "{\n" 19201 " Y = 0,\n" 19202 "}\n", 19203 GNUBraceStyle); 19204 19205 verifyFormat("@interface BSApplicationController ()\n" 19206 "{\n" 19207 "@private\n" 19208 " id _extraIvar;\n" 19209 "}\n" 19210 "@end\n", 19211 GNUBraceStyle); 19212 19213 verifyFormat("#ifdef _DEBUG\n" 19214 "int foo(int i = 0)\n" 19215 "#else\n" 19216 "int foo(int i = 5)\n" 19217 "#endif\n" 19218 "{\n" 19219 " return i;\n" 19220 "}", 19221 GNUBraceStyle); 19222 19223 verifyFormat("void foo() {}\n" 19224 "void bar()\n" 19225 "#ifdef _DEBUG\n" 19226 "{\n" 19227 " foo();\n" 19228 "}\n" 19229 "#else\n" 19230 "{\n" 19231 "}\n" 19232 "#endif", 19233 GNUBraceStyle); 19234 19235 verifyFormat("void foobar() { int i = 5; }\n" 19236 "#ifdef _DEBUG\n" 19237 "void bar() {}\n" 19238 "#else\n" 19239 "void bar() { foobar(); }\n" 19240 "#endif", 19241 GNUBraceStyle); 19242 } 19243 19244 TEST_F(FormatTest, WebKitBraceBreaking) { 19245 FormatStyle WebKitBraceStyle = getLLVMStyle(); 19246 WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit; 19247 WebKitBraceStyle.FixNamespaceComments = false; 19248 verifyFormat("namespace a {\n" 19249 "class A {\n" 19250 " void f()\n" 19251 " {\n" 19252 " if (true) {\n" 19253 " a();\n" 19254 " b();\n" 19255 " }\n" 19256 " }\n" 19257 " void g() { return; }\n" 19258 "};\n" 19259 "enum E {\n" 19260 " A,\n" 19261 " // foo\n" 19262 " B,\n" 19263 " C\n" 19264 "};\n" 19265 "struct B {\n" 19266 " int x;\n" 19267 "};\n" 19268 "}\n", 19269 WebKitBraceStyle); 19270 verifyFormat("struct S {\n" 19271 " int Type;\n" 19272 " union {\n" 19273 " int x;\n" 19274 " double y;\n" 19275 " } Value;\n" 19276 " class C {\n" 19277 " MyFavoriteType Value;\n" 19278 " } Class;\n" 19279 "};\n", 19280 WebKitBraceStyle); 19281 } 19282 19283 TEST_F(FormatTest, CatchExceptionReferenceBinding) { 19284 verifyFormat("void f() {\n" 19285 " try {\n" 19286 " } catch (const Exception &e) {\n" 19287 " }\n" 19288 "}\n", 19289 getLLVMStyle()); 19290 } 19291 19292 TEST_F(FormatTest, CatchAlignArrayOfStructuresRightAlignment) { 19293 auto Style = getLLVMStyle(); 19294 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 19295 Style.AlignConsecutiveAssignments.Enabled = true; 19296 Style.AlignConsecutiveDeclarations.Enabled = true; 19297 verifyFormat("struct test demo[] = {\n" 19298 " {56, 23, \"hello\"},\n" 19299 " {-1, 93463, \"world\"},\n" 19300 " { 7, 5, \"!!\"}\n" 19301 "};\n", 19302 Style); 19303 19304 verifyFormat("struct test demo[] = {\n" 19305 " {56, 23, \"hello\"}, // first line\n" 19306 " {-1, 93463, \"world\"}, // second line\n" 19307 " { 7, 5, \"!!\"} // third line\n" 19308 "};\n", 19309 Style); 19310 19311 verifyFormat("struct test demo[4] = {\n" 19312 " { 56, 23, 21, \"oh\"}, // first line\n" 19313 " { -1, 93463, 22, \"my\"}, // second line\n" 19314 " { 7, 5, 1, \"goodness\"} // third line\n" 19315 " {234, 5, 1, \"gracious\"} // fourth line\n" 19316 "};\n", 19317 Style); 19318 19319 verifyFormat("struct test demo[3] = {\n" 19320 " {56, 23, \"hello\"},\n" 19321 " {-1, 93463, \"world\"},\n" 19322 " { 7, 5, \"!!\"}\n" 19323 "};\n", 19324 Style); 19325 19326 verifyFormat("struct test demo[3] = {\n" 19327 " {int{56}, 23, \"hello\"},\n" 19328 " {int{-1}, 93463, \"world\"},\n" 19329 " { int{7}, 5, \"!!\"}\n" 19330 "};\n", 19331 Style); 19332 19333 verifyFormat("struct test demo[] = {\n" 19334 " {56, 23, \"hello\"},\n" 19335 " {-1, 93463, \"world\"},\n" 19336 " { 7, 5, \"!!\"},\n" 19337 "};\n", 19338 Style); 19339 19340 verifyFormat("test demo[] = {\n" 19341 " {56, 23, \"hello\"},\n" 19342 " {-1, 93463, \"world\"},\n" 19343 " { 7, 5, \"!!\"},\n" 19344 "};\n", 19345 Style); 19346 19347 verifyFormat("demo = std::array<struct test, 3>{\n" 19348 " test{56, 23, \"hello\"},\n" 19349 " test{-1, 93463, \"world\"},\n" 19350 " test{ 7, 5, \"!!\"},\n" 19351 "};\n", 19352 Style); 19353 19354 verifyFormat("test demo[] = {\n" 19355 " {56, 23, \"hello\"},\n" 19356 "#if X\n" 19357 " {-1, 93463, \"world\"},\n" 19358 "#endif\n" 19359 " { 7, 5, \"!!\"}\n" 19360 "};\n", 19361 Style); 19362 19363 verifyFormat( 19364 "test demo[] = {\n" 19365 " { 7, 23,\n" 19366 " \"hello world i am a very long line that really, in any\"\n" 19367 " \"just world, ought to be split over multiple lines\"},\n" 19368 " {-1, 93463, \"world\"},\n" 19369 " {56, 5, \"!!\"}\n" 19370 "};\n", 19371 Style); 19372 19373 verifyFormat("return GradForUnaryCwise(g, {\n" 19374 " {{\"sign\"}, \"Sign\", " 19375 " {\"x\", \"dy\"}},\n" 19376 " { {\"dx\"}, \"Mul\", {\"dy\"" 19377 ", \"sign\"}},\n" 19378 "});\n", 19379 Style); 19380 19381 Style.ColumnLimit = 0; 19382 EXPECT_EQ( 19383 "test demo[] = {\n" 19384 " {56, 23, \"hello world i am a very long line that really, " 19385 "in any just world, ought to be split over multiple lines\"},\n" 19386 " {-1, 93463, " 19387 " \"world\"},\n" 19388 " { 7, 5, " 19389 " \"!!\"},\n" 19390 "};", 19391 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19392 "that really, in any just world, ought to be split over multiple " 19393 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19394 Style)); 19395 19396 Style.ColumnLimit = 80; 19397 verifyFormat("test demo[] = {\n" 19398 " {56, 23, /* a comment */ \"hello\"},\n" 19399 " {-1, 93463, \"world\"},\n" 19400 " { 7, 5, \"!!\"}\n" 19401 "};\n", 19402 Style); 19403 19404 verifyFormat("test demo[] = {\n" 19405 " {56, 23, \"hello\"},\n" 19406 " {-1, 93463, \"world\" /* comment here */},\n" 19407 " { 7, 5, \"!!\"}\n" 19408 "};\n", 19409 Style); 19410 19411 verifyFormat("test demo[] = {\n" 19412 " {56, /* a comment */ 23, \"hello\"},\n" 19413 " {-1, 93463, \"world\"},\n" 19414 " { 7, 5, \"!!\"}\n" 19415 "};\n", 19416 Style); 19417 19418 Style.ColumnLimit = 20; 19419 EXPECT_EQ( 19420 "demo = std::array<\n" 19421 " struct test, 3>{\n" 19422 " test{\n" 19423 " 56, 23,\n" 19424 " \"hello \"\n" 19425 " \"world i \"\n" 19426 " \"am a very \"\n" 19427 " \"long line \"\n" 19428 " \"that \"\n" 19429 " \"really, \"\n" 19430 " \"in any \"\n" 19431 " \"just \"\n" 19432 " \"world, \"\n" 19433 " \"ought to \"\n" 19434 " \"be split \"\n" 19435 " \"over \"\n" 19436 " \"multiple \"\n" 19437 " \"lines\"},\n" 19438 " test{-1, 93463,\n" 19439 " \"world\"},\n" 19440 " test{ 7, 5,\n" 19441 " \"!!\" },\n" 19442 "};", 19443 format("demo = std::array<struct test, 3>{test{56, 23, \"hello world " 19444 "i am a very long line that really, in any just world, ought " 19445 "to be split over multiple lines\"},test{-1, 93463, \"world\"}," 19446 "test{7, 5, \"!!\"},};", 19447 Style)); 19448 // This caused a core dump by enabling Alignment in the LLVMStyle globally 19449 Style = getLLVMStyleWithColumns(50); 19450 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 19451 verifyFormat("static A x = {\n" 19452 " {{init1, init2, init3, init4},\n" 19453 " {init1, init2, init3, init4}}\n" 19454 "};", 19455 Style); 19456 // TODO: Fix the indentations below when this option is fully functional. 19457 verifyFormat("int a[][] = {\n" 19458 " {\n" 19459 " {0, 2}, //\n" 19460 " {1, 2} //\n" 19461 " }\n" 19462 "};", 19463 Style); 19464 Style.ColumnLimit = 100; 19465 EXPECT_EQ( 19466 "test demo[] = {\n" 19467 " {56, 23,\n" 19468 " \"hello world i am a very long line that really, in any just world" 19469 ", ought to be split over \"\n" 19470 " \"multiple lines\" },\n" 19471 " {-1, 93463, \"world\"},\n" 19472 " { 7, 5, \"!!\"},\n" 19473 "};", 19474 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19475 "that really, in any just world, ought to be split over multiple " 19476 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19477 Style)); 19478 19479 Style = getLLVMStyleWithColumns(50); 19480 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 19481 verifyFormat("struct test demo[] = {\n" 19482 " {56, 23, \"hello\"},\n" 19483 " {-1, 93463, \"world\"},\n" 19484 " { 7, 5, \"!!\"}\n" 19485 "};\n" 19486 "static A x = {\n" 19487 " {{init1, init2, init3, init4},\n" 19488 " {init1, init2, init3, init4}}\n" 19489 "};", 19490 Style); 19491 Style.ColumnLimit = 100; 19492 Style.AlignConsecutiveAssignments.AcrossComments = true; 19493 Style.AlignConsecutiveDeclarations.AcrossComments = true; 19494 verifyFormat("struct test demo[] = {\n" 19495 " {56, 23, \"hello\"},\n" 19496 " {-1, 93463, \"world\"},\n" 19497 " { 7, 5, \"!!\"}\n" 19498 "};\n" 19499 "struct test demo[4] = {\n" 19500 " { 56, 23, 21, \"oh\"}, // first line\n" 19501 " { -1, 93463, 22, \"my\"}, // second line\n" 19502 " { 7, 5, 1, \"goodness\"} // third line\n" 19503 " {234, 5, 1, \"gracious\"} // fourth line\n" 19504 "};\n", 19505 Style); 19506 EXPECT_EQ( 19507 "test demo[] = {\n" 19508 " {56,\n" 19509 " \"hello world i am a very long line that really, in any just world" 19510 ", ought to be split over \"\n" 19511 " \"multiple lines\", 23},\n" 19512 " {-1, \"world\", 93463},\n" 19513 " { 7, \"!!\", 5},\n" 19514 "};", 19515 format("test demo[] = {{56, \"hello world i am a very long line " 19516 "that really, in any just world, ought to be split over multiple " 19517 "lines\", 23},{-1, \"world\", 93463},{7, \"!!\", 5},};", 19518 Style)); 19519 } 19520 19521 TEST_F(FormatTest, CatchAlignArrayOfStructuresLeftAlignment) { 19522 auto Style = getLLVMStyle(); 19523 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 19524 /* FIXME: This case gets misformatted. 19525 verifyFormat("auto foo = Items{\n" 19526 " Section{0, bar(), },\n" 19527 " Section{1, boo() }\n" 19528 "};\n", 19529 Style); 19530 */ 19531 verifyFormat("auto foo = Items{\n" 19532 " Section{\n" 19533 " 0, bar(),\n" 19534 " }\n" 19535 "};\n", 19536 Style); 19537 verifyFormat("struct test demo[] = {\n" 19538 " {56, 23, \"hello\"},\n" 19539 " {-1, 93463, \"world\"},\n" 19540 " {7, 5, \"!!\" }\n" 19541 "};\n", 19542 Style); 19543 verifyFormat("struct test demo[] = {\n" 19544 " {56, 23, \"hello\"}, // first line\n" 19545 " {-1, 93463, \"world\"}, // second line\n" 19546 " {7, 5, \"!!\" } // third line\n" 19547 "};\n", 19548 Style); 19549 verifyFormat("struct test demo[4] = {\n" 19550 " {56, 23, 21, \"oh\" }, // first line\n" 19551 " {-1, 93463, 22, \"my\" }, // second line\n" 19552 " {7, 5, 1, \"goodness\"} // third line\n" 19553 " {234, 5, 1, \"gracious\"} // fourth line\n" 19554 "};\n", 19555 Style); 19556 verifyFormat("struct test demo[3] = {\n" 19557 " {56, 23, \"hello\"},\n" 19558 " {-1, 93463, \"world\"},\n" 19559 " {7, 5, \"!!\" }\n" 19560 "};\n", 19561 Style); 19562 19563 verifyFormat("struct test demo[3] = {\n" 19564 " {int{56}, 23, \"hello\"},\n" 19565 " {int{-1}, 93463, \"world\"},\n" 19566 " {int{7}, 5, \"!!\" }\n" 19567 "};\n", 19568 Style); 19569 verifyFormat("struct test demo[] = {\n" 19570 " {56, 23, \"hello\"},\n" 19571 " {-1, 93463, \"world\"},\n" 19572 " {7, 5, \"!!\" },\n" 19573 "};\n", 19574 Style); 19575 verifyFormat("test demo[] = {\n" 19576 " {56, 23, \"hello\"},\n" 19577 " {-1, 93463, \"world\"},\n" 19578 " {7, 5, \"!!\" },\n" 19579 "};\n", 19580 Style); 19581 verifyFormat("demo = std::array<struct test, 3>{\n" 19582 " test{56, 23, \"hello\"},\n" 19583 " test{-1, 93463, \"world\"},\n" 19584 " test{7, 5, \"!!\" },\n" 19585 "};\n", 19586 Style); 19587 verifyFormat("test demo[] = {\n" 19588 " {56, 23, \"hello\"},\n" 19589 "#if X\n" 19590 " {-1, 93463, \"world\"},\n" 19591 "#endif\n" 19592 " {7, 5, \"!!\" }\n" 19593 "};\n", 19594 Style); 19595 verifyFormat( 19596 "test demo[] = {\n" 19597 " {7, 23,\n" 19598 " \"hello world i am a very long line that really, in any\"\n" 19599 " \"just world, ought to be split over multiple lines\"},\n" 19600 " {-1, 93463, \"world\" },\n" 19601 " {56, 5, \"!!\" }\n" 19602 "};\n", 19603 Style); 19604 19605 verifyFormat("return GradForUnaryCwise(g, {\n" 19606 " {{\"sign\"}, \"Sign\", {\"x\", " 19607 "\"dy\"} },\n" 19608 " {{\"dx\"}, \"Mul\", " 19609 "{\"dy\", \"sign\"}},\n" 19610 "});\n", 19611 Style); 19612 19613 Style.ColumnLimit = 0; 19614 EXPECT_EQ( 19615 "test demo[] = {\n" 19616 " {56, 23, \"hello world i am a very long line that really, in any " 19617 "just world, ought to be split over multiple lines\"},\n" 19618 " {-1, 93463, \"world\" " 19619 " },\n" 19620 " {7, 5, \"!!\" " 19621 " },\n" 19622 "};", 19623 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19624 "that really, in any just world, ought to be split over multiple " 19625 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19626 Style)); 19627 19628 Style.ColumnLimit = 80; 19629 verifyFormat("test demo[] = {\n" 19630 " {56, 23, /* a comment */ \"hello\"},\n" 19631 " {-1, 93463, \"world\" },\n" 19632 " {7, 5, \"!!\" }\n" 19633 "};\n", 19634 Style); 19635 19636 verifyFormat("test demo[] = {\n" 19637 " {56, 23, \"hello\" },\n" 19638 " {-1, 93463, \"world\" /* comment here */},\n" 19639 " {7, 5, \"!!\" }\n" 19640 "};\n", 19641 Style); 19642 19643 verifyFormat("test demo[] = {\n" 19644 " {56, /* a comment */ 23, \"hello\"},\n" 19645 " {-1, 93463, \"world\"},\n" 19646 " {7, 5, \"!!\" }\n" 19647 "};\n", 19648 Style); 19649 19650 Style.ColumnLimit = 20; 19651 EXPECT_EQ( 19652 "demo = std::array<\n" 19653 " struct test, 3>{\n" 19654 " test{\n" 19655 " 56, 23,\n" 19656 " \"hello \"\n" 19657 " \"world i \"\n" 19658 " \"am a very \"\n" 19659 " \"long line \"\n" 19660 " \"that \"\n" 19661 " \"really, \"\n" 19662 " \"in any \"\n" 19663 " \"just \"\n" 19664 " \"world, \"\n" 19665 " \"ought to \"\n" 19666 " \"be split \"\n" 19667 " \"over \"\n" 19668 " \"multiple \"\n" 19669 " \"lines\"},\n" 19670 " test{-1, 93463,\n" 19671 " \"world\"},\n" 19672 " test{7, 5,\n" 19673 " \"!!\" },\n" 19674 "};", 19675 format("demo = std::array<struct test, 3>{test{56, 23, \"hello world " 19676 "i am a very long line that really, in any just world, ought " 19677 "to be split over multiple lines\"},test{-1, 93463, \"world\"}," 19678 "test{7, 5, \"!!\"},};", 19679 Style)); 19680 19681 // This caused a core dump by enabling Alignment in the LLVMStyle globally 19682 Style = getLLVMStyleWithColumns(50); 19683 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 19684 verifyFormat("static A x = {\n" 19685 " {{init1, init2, init3, init4},\n" 19686 " {init1, init2, init3, init4}}\n" 19687 "};", 19688 Style); 19689 Style.ColumnLimit = 100; 19690 EXPECT_EQ( 19691 "test demo[] = {\n" 19692 " {56, 23,\n" 19693 " \"hello world i am a very long line that really, in any just world" 19694 ", ought to be split over \"\n" 19695 " \"multiple lines\" },\n" 19696 " {-1, 93463, \"world\"},\n" 19697 " {7, 5, \"!!\" },\n" 19698 "};", 19699 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19700 "that really, in any just world, ought to be split over multiple " 19701 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19702 Style)); 19703 } 19704 19705 TEST_F(FormatTest, UnderstandsPragmas) { 19706 verifyFormat("#pragma omp reduction(| : var)"); 19707 verifyFormat("#pragma omp reduction(+ : var)"); 19708 19709 EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string " 19710 "(including parentheses).", 19711 format("#pragma mark Any non-hyphenated or hyphenated string " 19712 "(including parentheses).")); 19713 } 19714 19715 TEST_F(FormatTest, UnderstandPragmaOption) { 19716 verifyFormat("#pragma option -C -A"); 19717 19718 EXPECT_EQ("#pragma option -C -A", format("#pragma option -C -A")); 19719 } 19720 19721 TEST_F(FormatTest, UnderstandPragmaRegion) { 19722 auto Style = getLLVMStyleWithColumns(0); 19723 verifyFormat("#pragma region TEST(FOO : BAR)", Style); 19724 19725 EXPECT_EQ("#pragma region TEST(FOO : BAR)", 19726 format("#pragma region TEST(FOO : BAR)", Style)); 19727 } 19728 19729 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) { 19730 FormatStyle Style = getLLVMStyleWithColumns(20); 19731 19732 // See PR41213 19733 EXPECT_EQ("/*\n" 19734 " *\t9012345\n" 19735 " * /8901\n" 19736 " */", 19737 format("/*\n" 19738 " *\t9012345 /8901\n" 19739 " */", 19740 Style)); 19741 EXPECT_EQ("/*\n" 19742 " *345678\n" 19743 " *\t/8901\n" 19744 " */", 19745 format("/*\n" 19746 " *345678\t/8901\n" 19747 " */", 19748 Style)); 19749 19750 verifyFormat("int a; // the\n" 19751 " // comment", 19752 Style); 19753 EXPECT_EQ("int a; /* first line\n" 19754 " * second\n" 19755 " * line third\n" 19756 " * line\n" 19757 " */", 19758 format("int a; /* first line\n" 19759 " * second\n" 19760 " * line third\n" 19761 " * line\n" 19762 " */", 19763 Style)); 19764 EXPECT_EQ("int a; // first line\n" 19765 " // second\n" 19766 " // line third\n" 19767 " // line", 19768 format("int a; // first line\n" 19769 " // second line\n" 19770 " // third line", 19771 Style)); 19772 19773 Style.PenaltyExcessCharacter = 90; 19774 verifyFormat("int a; // the comment", Style); 19775 EXPECT_EQ("int a; // the comment\n" 19776 " // aaa", 19777 format("int a; // the comment aaa", Style)); 19778 EXPECT_EQ("int a; /* first line\n" 19779 " * second line\n" 19780 " * third line\n" 19781 " */", 19782 format("int a; /* first line\n" 19783 " * second line\n" 19784 " * third line\n" 19785 " */", 19786 Style)); 19787 EXPECT_EQ("int a; // first line\n" 19788 " // second line\n" 19789 " // third line", 19790 format("int a; // first line\n" 19791 " // second line\n" 19792 " // third line", 19793 Style)); 19794 // FIXME: Investigate why this is not getting the same layout as the test 19795 // above. 19796 EXPECT_EQ("int a; /* first line\n" 19797 " * second line\n" 19798 " * third line\n" 19799 " */", 19800 format("int a; /* first line second line third line" 19801 "\n*/", 19802 Style)); 19803 19804 EXPECT_EQ("// foo bar baz bazfoo\n" 19805 "// foo bar foo bar\n", 19806 format("// foo bar baz bazfoo\n" 19807 "// foo bar foo bar\n", 19808 Style)); 19809 EXPECT_EQ("// foo bar baz bazfoo\n" 19810 "// foo bar foo bar\n", 19811 format("// foo bar baz bazfoo\n" 19812 "// foo bar foo bar\n", 19813 Style)); 19814 19815 // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the 19816 // next one. 19817 EXPECT_EQ("// foo bar baz bazfoo\n" 19818 "// bar foo bar\n", 19819 format("// foo bar baz bazfoo bar\n" 19820 "// foo bar\n", 19821 Style)); 19822 19823 EXPECT_EQ("// foo bar baz bazfoo\n" 19824 "// foo bar baz bazfoo\n" 19825 "// bar foo bar\n", 19826 format("// foo bar baz bazfoo\n" 19827 "// foo bar baz bazfoo bar\n" 19828 "// foo bar\n", 19829 Style)); 19830 19831 EXPECT_EQ("// foo bar baz bazfoo\n" 19832 "// foo bar baz bazfoo\n" 19833 "// bar foo bar\n", 19834 format("// foo bar baz bazfoo\n" 19835 "// foo bar baz bazfoo bar\n" 19836 "// foo bar\n", 19837 Style)); 19838 19839 // Make sure we do not keep protruding characters if strict mode reflow is 19840 // cheaper than keeping protruding characters. 19841 Style.ColumnLimit = 21; 19842 EXPECT_EQ( 19843 "// foo foo foo foo\n" 19844 "// foo foo foo foo\n" 19845 "// foo foo foo foo\n", 19846 format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style)); 19847 19848 EXPECT_EQ("int a = /* long block\n" 19849 " comment */\n" 19850 " 42;", 19851 format("int a = /* long block comment */ 42;", Style)); 19852 } 19853 19854 TEST_F(FormatTest, BreakPenaltyAfterLParen) { 19855 FormatStyle Style = getLLVMStyle(); 19856 Style.ColumnLimit = 8; 19857 Style.PenaltyExcessCharacter = 15; 19858 verifyFormat("int foo(\n" 19859 " int aaaaaaaaaaaaaaaaaaaaaaaa);", 19860 Style); 19861 Style.PenaltyBreakOpenParenthesis = 200; 19862 EXPECT_EQ("int foo(int aaaaaaaaaaaaaaaaaaaaaaaa);", 19863 format("int foo(\n" 19864 " int aaaaaaaaaaaaaaaaaaaaaaaa);", 19865 Style)); 19866 } 19867 19868 TEST_F(FormatTest, BreakPenaltyAfterCastLParen) { 19869 FormatStyle Style = getLLVMStyle(); 19870 Style.ColumnLimit = 5; 19871 Style.PenaltyExcessCharacter = 150; 19872 verifyFormat("foo((\n" 19873 " int)aaaaaaaaaaaaaaaaaaaaaaaa);", 19874 19875 Style); 19876 Style.PenaltyBreakOpenParenthesis = 100000; 19877 EXPECT_EQ("foo((int)\n" 19878 " aaaaaaaaaaaaaaaaaaaaaaaa);", 19879 format("foo((\n" 19880 "int)aaaaaaaaaaaaaaaaaaaaaaaa);", 19881 Style)); 19882 } 19883 19884 TEST_F(FormatTest, BreakPenaltyAfterForLoopLParen) { 19885 FormatStyle Style = getLLVMStyle(); 19886 Style.ColumnLimit = 4; 19887 Style.PenaltyExcessCharacter = 100; 19888 verifyFormat("for (\n" 19889 " int iiiiiiiiiiiiiiiii =\n" 19890 " 0;\n" 19891 " iiiiiiiiiiiiiiiii <\n" 19892 " 2;\n" 19893 " iiiiiiiiiiiiiiiii++) {\n" 19894 "}", 19895 19896 Style); 19897 Style.PenaltyBreakOpenParenthesis = 1250; 19898 EXPECT_EQ("for (int iiiiiiiiiiiiiiiii =\n" 19899 " 0;\n" 19900 " iiiiiiiiiiiiiiiii <\n" 19901 " 2;\n" 19902 " iiiiiiiiiiiiiiiii++) {\n" 19903 "}", 19904 format("for (\n" 19905 " int iiiiiiiiiiiiiiiii =\n" 19906 " 0;\n" 19907 " iiiiiiiiiiiiiiiii <\n" 19908 " 2;\n" 19909 " iiiiiiiiiiiiiiiii++) {\n" 19910 "}", 19911 Style)); 19912 } 19913 19914 #define EXPECT_ALL_STYLES_EQUAL(Styles) \ 19915 for (size_t i = 1; i < Styles.size(); ++i) \ 19916 EXPECT_EQ(Styles[0], Styles[i]) \ 19917 << "Style #" << i << " of " << Styles.size() << " differs from Style #0" 19918 19919 TEST_F(FormatTest, GetsPredefinedStyleByName) { 19920 SmallVector<FormatStyle, 3> Styles; 19921 Styles.resize(3); 19922 19923 Styles[0] = getLLVMStyle(); 19924 EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1])); 19925 EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2])); 19926 EXPECT_ALL_STYLES_EQUAL(Styles); 19927 19928 Styles[0] = getGoogleStyle(); 19929 EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1])); 19930 EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2])); 19931 EXPECT_ALL_STYLES_EQUAL(Styles); 19932 19933 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript); 19934 EXPECT_TRUE( 19935 getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1])); 19936 EXPECT_TRUE( 19937 getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2])); 19938 EXPECT_ALL_STYLES_EQUAL(Styles); 19939 19940 Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp); 19941 EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1])); 19942 EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2])); 19943 EXPECT_ALL_STYLES_EQUAL(Styles); 19944 19945 Styles[0] = getMozillaStyle(); 19946 EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1])); 19947 EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2])); 19948 EXPECT_ALL_STYLES_EQUAL(Styles); 19949 19950 Styles[0] = getWebKitStyle(); 19951 EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1])); 19952 EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2])); 19953 EXPECT_ALL_STYLES_EQUAL(Styles); 19954 19955 Styles[0] = getGNUStyle(); 19956 EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1])); 19957 EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2])); 19958 EXPECT_ALL_STYLES_EQUAL(Styles); 19959 19960 EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0])); 19961 } 19962 19963 TEST_F(FormatTest, GetsCorrectBasedOnStyle) { 19964 SmallVector<FormatStyle, 8> Styles; 19965 Styles.resize(2); 19966 19967 Styles[0] = getGoogleStyle(); 19968 Styles[1] = getLLVMStyle(); 19969 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value()); 19970 EXPECT_ALL_STYLES_EQUAL(Styles); 19971 19972 Styles.resize(5); 19973 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript); 19974 Styles[1] = getLLVMStyle(); 19975 Styles[1].Language = FormatStyle::LK_JavaScript; 19976 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value()); 19977 19978 Styles[2] = getLLVMStyle(); 19979 Styles[2].Language = FormatStyle::LK_JavaScript; 19980 EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n" 19981 "BasedOnStyle: Google", 19982 &Styles[2]) 19983 .value()); 19984 19985 Styles[3] = getLLVMStyle(); 19986 Styles[3].Language = FormatStyle::LK_JavaScript; 19987 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n" 19988 "Language: JavaScript", 19989 &Styles[3]) 19990 .value()); 19991 19992 Styles[4] = getLLVMStyle(); 19993 Styles[4].Language = FormatStyle::LK_JavaScript; 19994 EXPECT_EQ(0, parseConfiguration("---\n" 19995 "BasedOnStyle: LLVM\n" 19996 "IndentWidth: 123\n" 19997 "---\n" 19998 "BasedOnStyle: Google\n" 19999 "Language: JavaScript", 20000 &Styles[4]) 20001 .value()); 20002 EXPECT_ALL_STYLES_EQUAL(Styles); 20003 } 20004 20005 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME) \ 20006 Style.FIELD = false; \ 20007 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value()); \ 20008 EXPECT_TRUE(Style.FIELD); \ 20009 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value()); \ 20010 EXPECT_FALSE(Style.FIELD); 20011 20012 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD) 20013 20014 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME) \ 20015 Style.STRUCT.FIELD = false; \ 20016 EXPECT_EQ(0, \ 20017 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": true", &Style) \ 20018 .value()); \ 20019 EXPECT_TRUE(Style.STRUCT.FIELD); \ 20020 EXPECT_EQ(0, \ 20021 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": false", &Style) \ 20022 .value()); \ 20023 EXPECT_FALSE(Style.STRUCT.FIELD); 20024 20025 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD) \ 20026 CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD) 20027 20028 #define CHECK_PARSE(TEXT, FIELD, VALUE) \ 20029 EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!"; \ 20030 EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value()); \ 20031 EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!" 20032 20033 TEST_F(FormatTest, ParsesConfigurationBools) { 20034 FormatStyle Style = {}; 20035 Style.Language = FormatStyle::LK_Cpp; 20036 CHECK_PARSE_BOOL(AlignTrailingComments); 20037 CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine); 20038 CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine); 20039 CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine); 20040 CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine); 20041 CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine); 20042 CHECK_PARSE_BOOL(BinPackArguments); 20043 CHECK_PARSE_BOOL(BinPackParameters); 20044 CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations); 20045 CHECK_PARSE_BOOL(BreakBeforeTernaryOperators); 20046 CHECK_PARSE_BOOL(BreakStringLiterals); 20047 CHECK_PARSE_BOOL(CompactNamespaces); 20048 CHECK_PARSE_BOOL(DeriveLineEnding); 20049 CHECK_PARSE_BOOL(DerivePointerAlignment); 20050 CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding"); 20051 CHECK_PARSE_BOOL(DisableFormat); 20052 CHECK_PARSE_BOOL(IndentAccessModifiers); 20053 CHECK_PARSE_BOOL(IndentCaseLabels); 20054 CHECK_PARSE_BOOL(IndentCaseBlocks); 20055 CHECK_PARSE_BOOL(IndentGotoLabels); 20056 CHECK_PARSE_BOOL_FIELD(IndentRequiresClause, "IndentRequires"); 20057 CHECK_PARSE_BOOL(IndentRequiresClause); 20058 CHECK_PARSE_BOOL(IndentWrappedFunctionNames); 20059 CHECK_PARSE_BOOL(InsertBraces); 20060 CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks); 20061 CHECK_PARSE_BOOL(ObjCSpaceAfterProperty); 20062 CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList); 20063 CHECK_PARSE_BOOL(Cpp11BracedListStyle); 20064 CHECK_PARSE_BOOL(ReflowComments); 20065 CHECK_PARSE_BOOL(RemoveBracesLLVM); 20066 CHECK_PARSE_BOOL(SortUsingDeclarations); 20067 CHECK_PARSE_BOOL(SpacesInParentheses); 20068 CHECK_PARSE_BOOL(SpacesInSquareBrackets); 20069 CHECK_PARSE_BOOL(SpacesInConditionalStatement); 20070 CHECK_PARSE_BOOL(SpaceInEmptyBlock); 20071 CHECK_PARSE_BOOL(SpaceInEmptyParentheses); 20072 CHECK_PARSE_BOOL(SpacesInContainerLiterals); 20073 CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses); 20074 CHECK_PARSE_BOOL(SpaceAfterCStyleCast); 20075 CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword); 20076 CHECK_PARSE_BOOL(SpaceAfterLogicalNot); 20077 CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators); 20078 CHECK_PARSE_BOOL(SpaceBeforeCaseColon); 20079 CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList); 20080 CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon); 20081 CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon); 20082 CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon); 20083 CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets); 20084 CHECK_PARSE_BOOL(UseCRLF); 20085 20086 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel); 20087 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass); 20088 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum); 20089 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction); 20090 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace); 20091 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration); 20092 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct); 20093 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion); 20094 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock); 20095 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch); 20096 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse); 20097 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody); 20098 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile); 20099 CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces); 20100 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction); 20101 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord); 20102 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace); 20103 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterControlStatements); 20104 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterForeachMacros); 20105 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, 20106 AfterFunctionDeclarationName); 20107 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, 20108 AfterFunctionDefinitionName); 20109 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterIfMacros); 20110 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterOverloadedOperator); 20111 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, BeforeNonEmptyParentheses); 20112 } 20113 20114 #undef CHECK_PARSE_BOOL 20115 20116 TEST_F(FormatTest, ParsesConfiguration) { 20117 FormatStyle Style = {}; 20118 Style.Language = FormatStyle::LK_Cpp; 20119 CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234); 20120 CHECK_PARSE("ConstructorInitializerIndentWidth: 1234", 20121 ConstructorInitializerIndentWidth, 1234u); 20122 CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u); 20123 CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u); 20124 CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u); 20125 CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u); 20126 CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234", 20127 PenaltyBreakBeforeFirstCallParameter, 1234u); 20128 CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234", 20129 PenaltyBreakTemplateDeclaration, 1234u); 20130 CHECK_PARSE("PenaltyBreakOpenParenthesis: 1234", PenaltyBreakOpenParenthesis, 20131 1234u); 20132 CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u); 20133 CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234", 20134 PenaltyReturnTypeOnItsOwnLine, 1234u); 20135 CHECK_PARSE("SpacesBeforeTrailingComments: 1234", 20136 SpacesBeforeTrailingComments, 1234u); 20137 CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u); 20138 CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u); 20139 CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$"); 20140 20141 Style.QualifierAlignment = FormatStyle::QAS_Right; 20142 CHECK_PARSE("QualifierAlignment: Leave", QualifierAlignment, 20143 FormatStyle::QAS_Leave); 20144 CHECK_PARSE("QualifierAlignment: Right", QualifierAlignment, 20145 FormatStyle::QAS_Right); 20146 CHECK_PARSE("QualifierAlignment: Left", QualifierAlignment, 20147 FormatStyle::QAS_Left); 20148 CHECK_PARSE("QualifierAlignment: Custom", QualifierAlignment, 20149 FormatStyle::QAS_Custom); 20150 20151 Style.QualifierOrder.clear(); 20152 CHECK_PARSE("QualifierOrder: [ const, volatile, type ]", QualifierOrder, 20153 std::vector<std::string>({"const", "volatile", "type"})); 20154 Style.QualifierOrder.clear(); 20155 CHECK_PARSE("QualifierOrder: [const, type]", QualifierOrder, 20156 std::vector<std::string>({"const", "type"})); 20157 Style.QualifierOrder.clear(); 20158 CHECK_PARSE("QualifierOrder: [volatile, type]", QualifierOrder, 20159 std::vector<std::string>({"volatile", "type"})); 20160 20161 #define CHECK_ALIGN_CONSECUTIVE(FIELD) \ 20162 do { \ 20163 Style.FIELD.Enabled = true; \ 20164 CHECK_PARSE(#FIELD ": None", FIELD, \ 20165 FormatStyle::AlignConsecutiveStyle( \ 20166 {/*Enabled=*/false, /*AcrossEmptyLines=*/false, \ 20167 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 20168 /*PadOperators=*/true})); \ 20169 CHECK_PARSE(#FIELD ": Consecutive", FIELD, \ 20170 FormatStyle::AlignConsecutiveStyle( \ 20171 {/*Enabled=*/true, /*AcrossEmptyLines=*/false, \ 20172 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 20173 /*PadOperators=*/true})); \ 20174 CHECK_PARSE(#FIELD ": AcrossEmptyLines", FIELD, \ 20175 FormatStyle::AlignConsecutiveStyle( \ 20176 {/*Enabled=*/true, /*AcrossEmptyLines=*/true, \ 20177 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 20178 /*PadOperators=*/true})); \ 20179 CHECK_PARSE(#FIELD ": AcrossEmptyLinesAndComments", FIELD, \ 20180 FormatStyle::AlignConsecutiveStyle( \ 20181 {/*Enabled=*/true, /*AcrossEmptyLines=*/true, \ 20182 /*AcrossComments=*/true, /*AlignCompound=*/false, \ 20183 /*PadOperators=*/true})); \ 20184 /* For backwards compability, false / true should still parse */ \ 20185 CHECK_PARSE(#FIELD ": false", FIELD, \ 20186 FormatStyle::AlignConsecutiveStyle( \ 20187 {/*Enabled=*/false, /*AcrossEmptyLines=*/false, \ 20188 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 20189 /*PadOperators=*/true})); \ 20190 CHECK_PARSE(#FIELD ": true", FIELD, \ 20191 FormatStyle::AlignConsecutiveStyle( \ 20192 {/*Enabled=*/true, /*AcrossEmptyLines=*/false, \ 20193 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 20194 /*PadOperators=*/true})); \ 20195 \ 20196 CHECK_PARSE_NESTED_BOOL(FIELD, Enabled); \ 20197 CHECK_PARSE_NESTED_BOOL(FIELD, AcrossEmptyLines); \ 20198 CHECK_PARSE_NESTED_BOOL(FIELD, AcrossComments); \ 20199 CHECK_PARSE_NESTED_BOOL(FIELD, AlignCompound); \ 20200 CHECK_PARSE_NESTED_BOOL(FIELD, PadOperators); \ 20201 } while (false) 20202 20203 CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveAssignments); 20204 CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveBitFields); 20205 CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveMacros); 20206 CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveDeclarations); 20207 20208 #undef CHECK_ALIGN_CONSECUTIVE 20209 20210 Style.PointerAlignment = FormatStyle::PAS_Middle; 20211 CHECK_PARSE("PointerAlignment: Left", PointerAlignment, 20212 FormatStyle::PAS_Left); 20213 CHECK_PARSE("PointerAlignment: Right", PointerAlignment, 20214 FormatStyle::PAS_Right); 20215 CHECK_PARSE("PointerAlignment: Middle", PointerAlignment, 20216 FormatStyle::PAS_Middle); 20217 Style.ReferenceAlignment = FormatStyle::RAS_Middle; 20218 CHECK_PARSE("ReferenceAlignment: Pointer", ReferenceAlignment, 20219 FormatStyle::RAS_Pointer); 20220 CHECK_PARSE("ReferenceAlignment: Left", ReferenceAlignment, 20221 FormatStyle::RAS_Left); 20222 CHECK_PARSE("ReferenceAlignment: Right", ReferenceAlignment, 20223 FormatStyle::RAS_Right); 20224 CHECK_PARSE("ReferenceAlignment: Middle", ReferenceAlignment, 20225 FormatStyle::RAS_Middle); 20226 // For backward compatibility: 20227 CHECK_PARSE("PointerBindsToType: Left", PointerAlignment, 20228 FormatStyle::PAS_Left); 20229 CHECK_PARSE("PointerBindsToType: Right", PointerAlignment, 20230 FormatStyle::PAS_Right); 20231 CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment, 20232 FormatStyle::PAS_Middle); 20233 20234 Style.Standard = FormatStyle::LS_Auto; 20235 CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03); 20236 CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11); 20237 CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14); 20238 CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17); 20239 CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20); 20240 CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto); 20241 CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest); 20242 // Legacy aliases: 20243 CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03); 20244 CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest); 20245 CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03); 20246 CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11); 20247 20248 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 20249 CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment", 20250 BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment); 20251 CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators, 20252 FormatStyle::BOS_None); 20253 CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators, 20254 FormatStyle::BOS_All); 20255 // For backward compatibility: 20256 CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators, 20257 FormatStyle::BOS_None); 20258 CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators, 20259 FormatStyle::BOS_All); 20260 20261 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 20262 CHECK_PARSE("BreakConstructorInitializers: BeforeComma", 20263 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma); 20264 CHECK_PARSE("BreakConstructorInitializers: AfterColon", 20265 BreakConstructorInitializers, FormatStyle::BCIS_AfterColon); 20266 CHECK_PARSE("BreakConstructorInitializers: BeforeColon", 20267 BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon); 20268 // For backward compatibility: 20269 CHECK_PARSE("BreakConstructorInitializersBeforeComma: true", 20270 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma); 20271 20272 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 20273 CHECK_PARSE("BreakInheritanceList: AfterComma", BreakInheritanceList, 20274 FormatStyle::BILS_AfterComma); 20275 CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList, 20276 FormatStyle::BILS_BeforeComma); 20277 CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList, 20278 FormatStyle::BILS_AfterColon); 20279 CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList, 20280 FormatStyle::BILS_BeforeColon); 20281 // For backward compatibility: 20282 CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList, 20283 FormatStyle::BILS_BeforeComma); 20284 20285 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 20286 CHECK_PARSE("PackConstructorInitializers: Never", PackConstructorInitializers, 20287 FormatStyle::PCIS_Never); 20288 CHECK_PARSE("PackConstructorInitializers: BinPack", 20289 PackConstructorInitializers, FormatStyle::PCIS_BinPack); 20290 CHECK_PARSE("PackConstructorInitializers: CurrentLine", 20291 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 20292 CHECK_PARSE("PackConstructorInitializers: NextLine", 20293 PackConstructorInitializers, FormatStyle::PCIS_NextLine); 20294 // For backward compatibility: 20295 CHECK_PARSE("BasedOnStyle: Google\n" 20296 "ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 20297 "AllowAllConstructorInitializersOnNextLine: false", 20298 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 20299 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 20300 CHECK_PARSE("BasedOnStyle: Google\n" 20301 "ConstructorInitializerAllOnOneLineOrOnePerLine: false", 20302 PackConstructorInitializers, FormatStyle::PCIS_BinPack); 20303 CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 20304 "AllowAllConstructorInitializersOnNextLine: true", 20305 PackConstructorInitializers, FormatStyle::PCIS_NextLine); 20306 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 20307 CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 20308 "AllowAllConstructorInitializersOnNextLine: false", 20309 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 20310 20311 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 20312 CHECK_PARSE("EmptyLineBeforeAccessModifier: Never", 20313 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never); 20314 CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave", 20315 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave); 20316 CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock", 20317 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock); 20318 CHECK_PARSE("EmptyLineBeforeAccessModifier: Always", 20319 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always); 20320 20321 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 20322 CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket, 20323 FormatStyle::BAS_Align); 20324 CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket, 20325 FormatStyle::BAS_DontAlign); 20326 CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket, 20327 FormatStyle::BAS_AlwaysBreak); 20328 CHECK_PARSE("AlignAfterOpenBracket: BlockIndent", AlignAfterOpenBracket, 20329 FormatStyle::BAS_BlockIndent); 20330 // For backward compatibility: 20331 CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket, 20332 FormatStyle::BAS_DontAlign); 20333 CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket, 20334 FormatStyle::BAS_Align); 20335 20336 Style.AlignEscapedNewlines = FormatStyle::ENAS_Left; 20337 CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines, 20338 FormatStyle::ENAS_DontAlign); 20339 CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines, 20340 FormatStyle::ENAS_Left); 20341 CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines, 20342 FormatStyle::ENAS_Right); 20343 // For backward compatibility: 20344 CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines, 20345 FormatStyle::ENAS_Left); 20346 CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines, 20347 FormatStyle::ENAS_Right); 20348 20349 Style.AlignOperands = FormatStyle::OAS_Align; 20350 CHECK_PARSE("AlignOperands: DontAlign", AlignOperands, 20351 FormatStyle::OAS_DontAlign); 20352 CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align); 20353 CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands, 20354 FormatStyle::OAS_AlignAfterOperator); 20355 // For backward compatibility: 20356 CHECK_PARSE("AlignOperands: false", AlignOperands, 20357 FormatStyle::OAS_DontAlign); 20358 CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align); 20359 20360 Style.UseTab = FormatStyle::UT_ForIndentation; 20361 CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never); 20362 CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation); 20363 CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always); 20364 CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab, 20365 FormatStyle::UT_ForContinuationAndIndentation); 20366 CHECK_PARSE("UseTab: AlignWithSpaces", UseTab, 20367 FormatStyle::UT_AlignWithSpaces); 20368 // For backward compatibility: 20369 CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never); 20370 CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always); 20371 20372 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 20373 CHECK_PARSE("AllowShortBlocksOnASingleLine: Never", 20374 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 20375 CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty", 20376 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty); 20377 CHECK_PARSE("AllowShortBlocksOnASingleLine: Always", 20378 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always); 20379 // For backward compatibility: 20380 CHECK_PARSE("AllowShortBlocksOnASingleLine: false", 20381 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 20382 CHECK_PARSE("AllowShortBlocksOnASingleLine: true", 20383 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always); 20384 20385 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 20386 CHECK_PARSE("AllowShortFunctionsOnASingleLine: None", 20387 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None); 20388 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline", 20389 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline); 20390 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty", 20391 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty); 20392 CHECK_PARSE("AllowShortFunctionsOnASingleLine: All", 20393 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All); 20394 // For backward compatibility: 20395 CHECK_PARSE("AllowShortFunctionsOnASingleLine: false", 20396 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None); 20397 CHECK_PARSE("AllowShortFunctionsOnASingleLine: true", 20398 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All); 20399 20400 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both; 20401 CHECK_PARSE("SpaceAroundPointerQualifiers: Default", 20402 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default); 20403 CHECK_PARSE("SpaceAroundPointerQualifiers: Before", 20404 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before); 20405 CHECK_PARSE("SpaceAroundPointerQualifiers: After", 20406 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After); 20407 CHECK_PARSE("SpaceAroundPointerQualifiers: Both", 20408 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both); 20409 20410 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 20411 CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens, 20412 FormatStyle::SBPO_Never); 20413 CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens, 20414 FormatStyle::SBPO_Always); 20415 CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens, 20416 FormatStyle::SBPO_ControlStatements); 20417 CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptControlMacros", 20418 SpaceBeforeParens, 20419 FormatStyle::SBPO_ControlStatementsExceptControlMacros); 20420 CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens, 20421 FormatStyle::SBPO_NonEmptyParentheses); 20422 CHECK_PARSE("SpaceBeforeParens: Custom", SpaceBeforeParens, 20423 FormatStyle::SBPO_Custom); 20424 // For backward compatibility: 20425 CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens, 20426 FormatStyle::SBPO_Never); 20427 CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens, 20428 FormatStyle::SBPO_ControlStatements); 20429 CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptForEachMacros", 20430 SpaceBeforeParens, 20431 FormatStyle::SBPO_ControlStatementsExceptControlMacros); 20432 20433 Style.ColumnLimit = 123; 20434 FormatStyle BaseStyle = getLLVMStyle(); 20435 CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit); 20436 CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u); 20437 20438 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 20439 CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces, 20440 FormatStyle::BS_Attach); 20441 CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces, 20442 FormatStyle::BS_Linux); 20443 CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces, 20444 FormatStyle::BS_Mozilla); 20445 CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces, 20446 FormatStyle::BS_Stroustrup); 20447 CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces, 20448 FormatStyle::BS_Allman); 20449 CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces, 20450 FormatStyle::BS_Whitesmiths); 20451 CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU); 20452 CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces, 20453 FormatStyle::BS_WebKit); 20454 CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces, 20455 FormatStyle::BS_Custom); 20456 20457 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never; 20458 CHECK_PARSE("BraceWrapping:\n" 20459 " AfterControlStatement: MultiLine", 20460 BraceWrapping.AfterControlStatement, 20461 FormatStyle::BWACS_MultiLine); 20462 CHECK_PARSE("BraceWrapping:\n" 20463 " AfterControlStatement: Always", 20464 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always); 20465 CHECK_PARSE("BraceWrapping:\n" 20466 " AfterControlStatement: Never", 20467 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never); 20468 // For backward compatibility: 20469 CHECK_PARSE("BraceWrapping:\n" 20470 " AfterControlStatement: true", 20471 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always); 20472 CHECK_PARSE("BraceWrapping:\n" 20473 " AfterControlStatement: false", 20474 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never); 20475 20476 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 20477 CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType, 20478 FormatStyle::RTBS_None); 20479 CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType, 20480 FormatStyle::RTBS_All); 20481 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel", 20482 AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel); 20483 CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions", 20484 AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions); 20485 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions", 20486 AlwaysBreakAfterReturnType, 20487 FormatStyle::RTBS_TopLevelDefinitions); 20488 20489 Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 20490 CHECK_PARSE("AlwaysBreakTemplateDeclarations: No", 20491 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No); 20492 CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine", 20493 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine); 20494 CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes", 20495 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes); 20496 CHECK_PARSE("AlwaysBreakTemplateDeclarations: false", 20497 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine); 20498 CHECK_PARSE("AlwaysBreakTemplateDeclarations: true", 20499 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes); 20500 20501 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All; 20502 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None", 20503 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None); 20504 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All", 20505 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All); 20506 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel", 20507 AlwaysBreakAfterDefinitionReturnType, 20508 FormatStyle::DRTBS_TopLevel); 20509 20510 Style.NamespaceIndentation = FormatStyle::NI_All; 20511 CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation, 20512 FormatStyle::NI_None); 20513 CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation, 20514 FormatStyle::NI_Inner); 20515 CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation, 20516 FormatStyle::NI_All); 20517 20518 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_OnlyFirstIf; 20519 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never", 20520 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never); 20521 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse", 20522 AllowShortIfStatementsOnASingleLine, 20523 FormatStyle::SIS_WithoutElse); 20524 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: OnlyFirstIf", 20525 AllowShortIfStatementsOnASingleLine, 20526 FormatStyle::SIS_OnlyFirstIf); 20527 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: AllIfsAndElse", 20528 AllowShortIfStatementsOnASingleLine, 20529 FormatStyle::SIS_AllIfsAndElse); 20530 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always", 20531 AllowShortIfStatementsOnASingleLine, 20532 FormatStyle::SIS_OnlyFirstIf); 20533 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false", 20534 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never); 20535 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true", 20536 AllowShortIfStatementsOnASingleLine, 20537 FormatStyle::SIS_WithoutElse); 20538 20539 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 20540 CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock, 20541 FormatStyle::IEBS_AfterExternBlock); 20542 CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock, 20543 FormatStyle::IEBS_Indent); 20544 CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock, 20545 FormatStyle::IEBS_NoIndent); 20546 CHECK_PARSE("IndentExternBlock: true", IndentExternBlock, 20547 FormatStyle::IEBS_Indent); 20548 CHECK_PARSE("IndentExternBlock: false", IndentExternBlock, 20549 FormatStyle::IEBS_NoIndent); 20550 20551 Style.BitFieldColonSpacing = FormatStyle::BFCS_None; 20552 CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing, 20553 FormatStyle::BFCS_Both); 20554 CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing, 20555 FormatStyle::BFCS_None); 20556 CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing, 20557 FormatStyle::BFCS_Before); 20558 CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing, 20559 FormatStyle::BFCS_After); 20560 20561 Style.SortJavaStaticImport = FormatStyle::SJSIO_Before; 20562 CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport, 20563 FormatStyle::SJSIO_After); 20564 CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport, 20565 FormatStyle::SJSIO_Before); 20566 20567 // FIXME: This is required because parsing a configuration simply overwrites 20568 // the first N elements of the list instead of resetting it. 20569 Style.ForEachMacros.clear(); 20570 std::vector<std::string> BoostForeach; 20571 BoostForeach.push_back("BOOST_FOREACH"); 20572 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach); 20573 std::vector<std::string> BoostAndQForeach; 20574 BoostAndQForeach.push_back("BOOST_FOREACH"); 20575 BoostAndQForeach.push_back("Q_FOREACH"); 20576 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros, 20577 BoostAndQForeach); 20578 20579 Style.IfMacros.clear(); 20580 std::vector<std::string> CustomIfs; 20581 CustomIfs.push_back("MYIF"); 20582 CHECK_PARSE("IfMacros: [MYIF]", IfMacros, CustomIfs); 20583 20584 Style.AttributeMacros.clear(); 20585 CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros, 20586 std::vector<std::string>{"__capability"}); 20587 CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros, 20588 std::vector<std::string>({"attr1", "attr2"})); 20589 20590 Style.StatementAttributeLikeMacros.clear(); 20591 CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]", 20592 StatementAttributeLikeMacros, 20593 std::vector<std::string>({"emit", "Q_EMIT"})); 20594 20595 Style.StatementMacros.clear(); 20596 CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros, 20597 std::vector<std::string>{"QUNUSED"}); 20598 CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros, 20599 std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"})); 20600 20601 Style.NamespaceMacros.clear(); 20602 CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros, 20603 std::vector<std::string>{"TESTSUITE"}); 20604 CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros, 20605 std::vector<std::string>({"TESTSUITE", "SUITE"})); 20606 20607 Style.WhitespaceSensitiveMacros.clear(); 20608 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]", 20609 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"}); 20610 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]", 20611 WhitespaceSensitiveMacros, 20612 std::vector<std::string>({"STRINGIZE", "ASSERT"})); 20613 Style.WhitespaceSensitiveMacros.clear(); 20614 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']", 20615 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"}); 20616 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']", 20617 WhitespaceSensitiveMacros, 20618 std::vector<std::string>({"STRINGIZE", "ASSERT"})); 20619 20620 Style.IncludeStyle.IncludeCategories.clear(); 20621 std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = { 20622 {"abc/.*", 2, 0, false}, {".*", 1, 0, true}}; 20623 CHECK_PARSE("IncludeCategories:\n" 20624 " - Regex: abc/.*\n" 20625 " Priority: 2\n" 20626 " - Regex: .*\n" 20627 " Priority: 1\n" 20628 " CaseSensitive: true\n", 20629 IncludeStyle.IncludeCategories, ExpectedCategories); 20630 CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex, 20631 "abc$"); 20632 CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'", 20633 IncludeStyle.IncludeIsMainSourceRegex, "abc$"); 20634 20635 Style.SortIncludes = FormatStyle::SI_Never; 20636 CHECK_PARSE("SortIncludes: true", SortIncludes, 20637 FormatStyle::SI_CaseSensitive); 20638 CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never); 20639 CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes, 20640 FormatStyle::SI_CaseInsensitive); 20641 CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes, 20642 FormatStyle::SI_CaseSensitive); 20643 CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never); 20644 20645 Style.RawStringFormats.clear(); 20646 std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = { 20647 { 20648 FormatStyle::LK_TextProto, 20649 {"pb", "proto"}, 20650 {"PARSE_TEXT_PROTO"}, 20651 /*CanonicalDelimiter=*/"", 20652 "llvm", 20653 }, 20654 { 20655 FormatStyle::LK_Cpp, 20656 {"cc", "cpp"}, 20657 {"C_CODEBLOCK", "CPPEVAL"}, 20658 /*CanonicalDelimiter=*/"cc", 20659 /*BasedOnStyle=*/"", 20660 }, 20661 }; 20662 20663 CHECK_PARSE("RawStringFormats:\n" 20664 " - Language: TextProto\n" 20665 " Delimiters:\n" 20666 " - 'pb'\n" 20667 " - 'proto'\n" 20668 " EnclosingFunctions:\n" 20669 " - 'PARSE_TEXT_PROTO'\n" 20670 " BasedOnStyle: llvm\n" 20671 " - Language: Cpp\n" 20672 " Delimiters:\n" 20673 " - 'cc'\n" 20674 " - 'cpp'\n" 20675 " EnclosingFunctions:\n" 20676 " - 'C_CODEBLOCK'\n" 20677 " - 'CPPEVAL'\n" 20678 " CanonicalDelimiter: 'cc'", 20679 RawStringFormats, ExpectedRawStringFormats); 20680 20681 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20682 " Minimum: 0\n" 20683 " Maximum: 0", 20684 SpacesInLineCommentPrefix.Minimum, 0u); 20685 EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u); 20686 Style.SpacesInLineCommentPrefix.Minimum = 1; 20687 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20688 " Minimum: 2", 20689 SpacesInLineCommentPrefix.Minimum, 0u); 20690 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20691 " Maximum: -1", 20692 SpacesInLineCommentPrefix.Maximum, -1u); 20693 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20694 " Minimum: 2", 20695 SpacesInLineCommentPrefix.Minimum, 2u); 20696 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20697 " Maximum: 1", 20698 SpacesInLineCommentPrefix.Maximum, 1u); 20699 EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u); 20700 20701 Style.SpacesInAngles = FormatStyle::SIAS_Always; 20702 CHECK_PARSE("SpacesInAngles: Never", SpacesInAngles, FormatStyle::SIAS_Never); 20703 CHECK_PARSE("SpacesInAngles: Always", SpacesInAngles, 20704 FormatStyle::SIAS_Always); 20705 CHECK_PARSE("SpacesInAngles: Leave", SpacesInAngles, FormatStyle::SIAS_Leave); 20706 // For backward compatibility: 20707 CHECK_PARSE("SpacesInAngles: false", SpacesInAngles, FormatStyle::SIAS_Never); 20708 CHECK_PARSE("SpacesInAngles: true", SpacesInAngles, FormatStyle::SIAS_Always); 20709 20710 CHECK_PARSE("RequiresClausePosition: WithPreceding", RequiresClausePosition, 20711 FormatStyle::RCPS_WithPreceding); 20712 CHECK_PARSE("RequiresClausePosition: WithFollowing", RequiresClausePosition, 20713 FormatStyle::RCPS_WithFollowing); 20714 CHECK_PARSE("RequiresClausePosition: SingleLine", RequiresClausePosition, 20715 FormatStyle::RCPS_SingleLine); 20716 CHECK_PARSE("RequiresClausePosition: OwnLine", RequiresClausePosition, 20717 FormatStyle::RCPS_OwnLine); 20718 20719 CHECK_PARSE("BreakBeforeConceptDeclarations: Never", 20720 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Never); 20721 CHECK_PARSE("BreakBeforeConceptDeclarations: Always", 20722 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always); 20723 CHECK_PARSE("BreakBeforeConceptDeclarations: Allowed", 20724 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed); 20725 // For backward compatibility: 20726 CHECK_PARSE("BreakBeforeConceptDeclarations: true", 20727 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always); 20728 CHECK_PARSE("BreakBeforeConceptDeclarations: false", 20729 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed); 20730 } 20731 20732 TEST_F(FormatTest, ParsesConfigurationWithLanguages) { 20733 FormatStyle Style = {}; 20734 Style.Language = FormatStyle::LK_Cpp; 20735 CHECK_PARSE("Language: Cpp\n" 20736 "IndentWidth: 12", 20737 IndentWidth, 12u); 20738 EXPECT_EQ(parseConfiguration("Language: JavaScript\n" 20739 "IndentWidth: 34", 20740 &Style), 20741 ParseError::Unsuitable); 20742 FormatStyle BinPackedTCS = {}; 20743 BinPackedTCS.Language = FormatStyle::LK_JavaScript; 20744 EXPECT_EQ(parseConfiguration("BinPackArguments: true\n" 20745 "InsertTrailingCommas: Wrapped", 20746 &BinPackedTCS), 20747 ParseError::BinPackTrailingCommaConflict); 20748 EXPECT_EQ(12u, Style.IndentWidth); 20749 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u); 20750 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language); 20751 20752 Style.Language = FormatStyle::LK_JavaScript; 20753 CHECK_PARSE("Language: JavaScript\n" 20754 "IndentWidth: 12", 20755 IndentWidth, 12u); 20756 CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u); 20757 EXPECT_EQ(parseConfiguration("Language: Cpp\n" 20758 "IndentWidth: 34", 20759 &Style), 20760 ParseError::Unsuitable); 20761 EXPECT_EQ(23u, Style.IndentWidth); 20762 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u); 20763 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language); 20764 20765 CHECK_PARSE("BasedOnStyle: LLVM\n" 20766 "IndentWidth: 67", 20767 IndentWidth, 67u); 20768 20769 CHECK_PARSE("---\n" 20770 "Language: JavaScript\n" 20771 "IndentWidth: 12\n" 20772 "---\n" 20773 "Language: Cpp\n" 20774 "IndentWidth: 34\n" 20775 "...\n", 20776 IndentWidth, 12u); 20777 20778 Style.Language = FormatStyle::LK_Cpp; 20779 CHECK_PARSE("---\n" 20780 "Language: JavaScript\n" 20781 "IndentWidth: 12\n" 20782 "---\n" 20783 "Language: Cpp\n" 20784 "IndentWidth: 34\n" 20785 "...\n", 20786 IndentWidth, 34u); 20787 CHECK_PARSE("---\n" 20788 "IndentWidth: 78\n" 20789 "---\n" 20790 "Language: JavaScript\n" 20791 "IndentWidth: 56\n" 20792 "...\n", 20793 IndentWidth, 78u); 20794 20795 Style.ColumnLimit = 123; 20796 Style.IndentWidth = 234; 20797 Style.BreakBeforeBraces = FormatStyle::BS_Linux; 20798 Style.TabWidth = 345; 20799 EXPECT_FALSE(parseConfiguration("---\n" 20800 "IndentWidth: 456\n" 20801 "BreakBeforeBraces: Allman\n" 20802 "---\n" 20803 "Language: JavaScript\n" 20804 "IndentWidth: 111\n" 20805 "TabWidth: 111\n" 20806 "---\n" 20807 "Language: Cpp\n" 20808 "BreakBeforeBraces: Stroustrup\n" 20809 "TabWidth: 789\n" 20810 "...\n", 20811 &Style)); 20812 EXPECT_EQ(123u, Style.ColumnLimit); 20813 EXPECT_EQ(456u, Style.IndentWidth); 20814 EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces); 20815 EXPECT_EQ(789u, Style.TabWidth); 20816 20817 EXPECT_EQ(parseConfiguration("---\n" 20818 "Language: JavaScript\n" 20819 "IndentWidth: 56\n" 20820 "---\n" 20821 "IndentWidth: 78\n" 20822 "...\n", 20823 &Style), 20824 ParseError::Error); 20825 EXPECT_EQ(parseConfiguration("---\n" 20826 "Language: JavaScript\n" 20827 "IndentWidth: 56\n" 20828 "---\n" 20829 "Language: JavaScript\n" 20830 "IndentWidth: 78\n" 20831 "...\n", 20832 &Style), 20833 ParseError::Error); 20834 20835 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language); 20836 } 20837 20838 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) { 20839 FormatStyle Style = {}; 20840 Style.Language = FormatStyle::LK_JavaScript; 20841 Style.BreakBeforeTernaryOperators = true; 20842 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value()); 20843 EXPECT_FALSE(Style.BreakBeforeTernaryOperators); 20844 20845 Style.BreakBeforeTernaryOperators = true; 20846 EXPECT_EQ(0, parseConfiguration("---\n" 20847 "BasedOnStyle: Google\n" 20848 "---\n" 20849 "Language: JavaScript\n" 20850 "IndentWidth: 76\n" 20851 "...\n", 20852 &Style) 20853 .value()); 20854 EXPECT_FALSE(Style.BreakBeforeTernaryOperators); 20855 EXPECT_EQ(76u, Style.IndentWidth); 20856 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language); 20857 } 20858 20859 TEST_F(FormatTest, ConfigurationRoundTripTest) { 20860 FormatStyle Style = getLLVMStyle(); 20861 std::string YAML = configurationAsText(Style); 20862 FormatStyle ParsedStyle = {}; 20863 ParsedStyle.Language = FormatStyle::LK_Cpp; 20864 EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value()); 20865 EXPECT_EQ(Style, ParsedStyle); 20866 } 20867 20868 TEST_F(FormatTest, WorksFor8bitEncodings) { 20869 EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n" 20870 "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n" 20871 "\"\xe7\xe8\xec\xed\xfe\xfe \"\n" 20872 "\"\xef\xee\xf0\xf3...\"", 20873 format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 " 20874 "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe " 20875 "\xef\xee\xf0\xf3...\"", 20876 getLLVMStyleWithColumns(12))); 20877 } 20878 20879 TEST_F(FormatTest, HandlesUTF8BOM) { 20880 EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf")); 20881 EXPECT_EQ("\xef\xbb\xbf#include <iostream>", 20882 format("\xef\xbb\xbf#include <iostream>")); 20883 EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>", 20884 format("\xef\xbb\xbf\n#include <iostream>")); 20885 } 20886 20887 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers. 20888 #if !defined(_MSC_VER) 20889 20890 TEST_F(FormatTest, CountsUTF8CharactersProperly) { 20891 verifyFormat("\"Однажды в студёную зимнюю пору...\"", 20892 getLLVMStyleWithColumns(35)); 20893 verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"", 20894 getLLVMStyleWithColumns(31)); 20895 verifyFormat("// Однажды в студёную зимнюю пору...", 20896 getLLVMStyleWithColumns(36)); 20897 verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32)); 20898 verifyFormat("/* Однажды в студёную зимнюю пору... */", 20899 getLLVMStyleWithColumns(39)); 20900 verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */", 20901 getLLVMStyleWithColumns(35)); 20902 } 20903 20904 TEST_F(FormatTest, SplitsUTF8Strings) { 20905 // Non-printable characters' width is currently considered to be the length in 20906 // bytes in UTF8. The characters can be displayed in very different manner 20907 // (zero-width, single width with a substitution glyph, expanded to their code 20908 // (e.g. "<8d>"), so there's no single correct way to handle them. 20909 EXPECT_EQ("\"aaaaÄ\"\n" 20910 "\"\xc2\x8d\";", 20911 format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10))); 20912 EXPECT_EQ("\"aaaaaaaÄ\"\n" 20913 "\"\xc2\x8d\";", 20914 format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10))); 20915 EXPECT_EQ("\"Однажды, в \"\n" 20916 "\"студёную \"\n" 20917 "\"зимнюю \"\n" 20918 "\"пору,\"", 20919 format("\"Однажды, в студёную зимнюю пору,\"", 20920 getLLVMStyleWithColumns(13))); 20921 EXPECT_EQ( 20922 "\"一 二 三 \"\n" 20923 "\"四 五六 \"\n" 20924 "\"七 八 九 \"\n" 20925 "\"十\"", 20926 format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11))); 20927 EXPECT_EQ("\"一\t\"\n" 20928 "\"二 \t\"\n" 20929 "\"三 四 \"\n" 20930 "\"五\t\"\n" 20931 "\"六 \t\"\n" 20932 "\"七 \"\n" 20933 "\"八九十\tqq\"", 20934 format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"", 20935 getLLVMStyleWithColumns(11))); 20936 20937 // UTF8 character in an escape sequence. 20938 EXPECT_EQ("\"aaaaaa\"\n" 20939 "\"\\\xC2\x8D\"", 20940 format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10))); 20941 } 20942 20943 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) { 20944 EXPECT_EQ("const char *sssss =\n" 20945 " \"一二三四五六七八\\\n" 20946 " 九 十\";", 20947 format("const char *sssss = \"一二三四五六七八\\\n" 20948 " 九 十\";", 20949 getLLVMStyleWithColumns(30))); 20950 } 20951 20952 TEST_F(FormatTest, SplitsUTF8LineComments) { 20953 EXPECT_EQ("// aaaaÄ\xc2\x8d", 20954 format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10))); 20955 EXPECT_EQ("// Я из лесу\n" 20956 "// вышел; был\n" 20957 "// сильный\n" 20958 "// мороз.", 20959 format("// Я из лесу вышел; был сильный мороз.", 20960 getLLVMStyleWithColumns(13))); 20961 EXPECT_EQ("// 一二三\n" 20962 "// 四五六七\n" 20963 "// 八 九\n" 20964 "// 十", 20965 format("// 一二三 四五六七 八 九 十", getLLVMStyleWithColumns(9))); 20966 } 20967 20968 TEST_F(FormatTest, SplitsUTF8BlockComments) { 20969 EXPECT_EQ("/* Гляжу,\n" 20970 " * поднимается\n" 20971 " * медленно в\n" 20972 " * гору\n" 20973 " * Лошадка,\n" 20974 " * везущая\n" 20975 " * хворосту\n" 20976 " * воз. */", 20977 format("/* Гляжу, поднимается медленно в гору\n" 20978 " * Лошадка, везущая хворосту воз. */", 20979 getLLVMStyleWithColumns(13))); 20980 EXPECT_EQ( 20981 "/* 一二三\n" 20982 " * 四五六七\n" 20983 " * 八 九\n" 20984 " * 十 */", 20985 format("/* 一二三 四五六七 八 九 十 */", getLLVMStyleWithColumns(9))); 20986 EXPECT_EQ("/* \n" 20987 " * \n" 20988 " * - */", 20989 format("/* - */", getLLVMStyleWithColumns(12))); 20990 } 20991 20992 #endif // _MSC_VER 20993 20994 TEST_F(FormatTest, ConstructorInitializerIndentWidth) { 20995 FormatStyle Style = getLLVMStyle(); 20996 20997 Style.ConstructorInitializerIndentWidth = 4; 20998 verifyFormat( 20999 "SomeClass::Constructor()\n" 21000 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 21001 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 21002 Style); 21003 21004 Style.ConstructorInitializerIndentWidth = 2; 21005 verifyFormat( 21006 "SomeClass::Constructor()\n" 21007 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 21008 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 21009 Style); 21010 21011 Style.ConstructorInitializerIndentWidth = 0; 21012 verifyFormat( 21013 "SomeClass::Constructor()\n" 21014 ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 21015 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 21016 Style); 21017 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 21018 verifyFormat( 21019 "SomeLongTemplateVariableName<\n" 21020 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>", 21021 Style); 21022 verifyFormat("bool smaller = 1 < " 21023 "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 21024 " " 21025 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 21026 Style); 21027 21028 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 21029 verifyFormat("SomeClass::Constructor() :\n" 21030 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n" 21031 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}", 21032 Style); 21033 } 21034 21035 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) { 21036 FormatStyle Style = getLLVMStyle(); 21037 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 21038 Style.ConstructorInitializerIndentWidth = 4; 21039 verifyFormat("SomeClass::Constructor()\n" 21040 " : a(a)\n" 21041 " , b(b)\n" 21042 " , c(c) {}", 21043 Style); 21044 verifyFormat("SomeClass::Constructor()\n" 21045 " : a(a) {}", 21046 Style); 21047 21048 Style.ColumnLimit = 0; 21049 verifyFormat("SomeClass::Constructor()\n" 21050 " : a(a) {}", 21051 Style); 21052 verifyFormat("SomeClass::Constructor() noexcept\n" 21053 " : a(a) {}", 21054 Style); 21055 verifyFormat("SomeClass::Constructor()\n" 21056 " : a(a)\n" 21057 " , b(b)\n" 21058 " , c(c) {}", 21059 Style); 21060 verifyFormat("SomeClass::Constructor()\n" 21061 " : a(a) {\n" 21062 " foo();\n" 21063 " bar();\n" 21064 "}", 21065 Style); 21066 21067 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 21068 verifyFormat("SomeClass::Constructor()\n" 21069 " : a(a)\n" 21070 " , b(b)\n" 21071 " , c(c) {\n}", 21072 Style); 21073 verifyFormat("SomeClass::Constructor()\n" 21074 " : a(a) {\n}", 21075 Style); 21076 21077 Style.ColumnLimit = 80; 21078 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 21079 Style.ConstructorInitializerIndentWidth = 2; 21080 verifyFormat("SomeClass::Constructor()\n" 21081 " : a(a)\n" 21082 " , b(b)\n" 21083 " , c(c) {}", 21084 Style); 21085 21086 Style.ConstructorInitializerIndentWidth = 0; 21087 verifyFormat("SomeClass::Constructor()\n" 21088 ": a(a)\n" 21089 ", b(b)\n" 21090 ", c(c) {}", 21091 Style); 21092 21093 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 21094 Style.ConstructorInitializerIndentWidth = 4; 21095 verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style); 21096 verifyFormat( 21097 "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n", 21098 Style); 21099 verifyFormat( 21100 "SomeClass::Constructor()\n" 21101 " : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}", 21102 Style); 21103 Style.ConstructorInitializerIndentWidth = 4; 21104 Style.ColumnLimit = 60; 21105 verifyFormat("SomeClass::Constructor()\n" 21106 " : aaaaaaaa(aaaaaaaa)\n" 21107 " , aaaaaaaa(aaaaaaaa)\n" 21108 " , aaaaaaaa(aaaaaaaa) {}", 21109 Style); 21110 } 21111 21112 TEST_F(FormatTest, ConstructorInitializersWithPreprocessorDirective) { 21113 FormatStyle Style = getLLVMStyle(); 21114 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 21115 Style.ConstructorInitializerIndentWidth = 4; 21116 verifyFormat("SomeClass::Constructor()\n" 21117 " : a{a}\n" 21118 " , b{b} {}", 21119 Style); 21120 verifyFormat("SomeClass::Constructor()\n" 21121 " : a{a}\n" 21122 "#if CONDITION\n" 21123 " , b{b}\n" 21124 "#endif\n" 21125 "{\n}", 21126 Style); 21127 Style.ConstructorInitializerIndentWidth = 2; 21128 verifyFormat("SomeClass::Constructor()\n" 21129 "#if CONDITION\n" 21130 " : a{a}\n" 21131 "#endif\n" 21132 " , b{b}\n" 21133 " , c{c} {\n}", 21134 Style); 21135 Style.ConstructorInitializerIndentWidth = 0; 21136 verifyFormat("SomeClass::Constructor()\n" 21137 ": a{a}\n" 21138 "#ifdef CONDITION\n" 21139 ", b{b}\n" 21140 "#else\n" 21141 ", c{c}\n" 21142 "#endif\n" 21143 ", d{d} {\n}", 21144 Style); 21145 Style.ConstructorInitializerIndentWidth = 4; 21146 verifyFormat("SomeClass::Constructor()\n" 21147 " : a{a}\n" 21148 "#if WINDOWS\n" 21149 "#if DEBUG\n" 21150 " , b{0}\n" 21151 "#else\n" 21152 " , b{1}\n" 21153 "#endif\n" 21154 "#else\n" 21155 "#if DEBUG\n" 21156 " , b{2}\n" 21157 "#else\n" 21158 " , b{3}\n" 21159 "#endif\n" 21160 "#endif\n" 21161 "{\n}", 21162 Style); 21163 verifyFormat("SomeClass::Constructor()\n" 21164 " : a{a}\n" 21165 "#if WINDOWS\n" 21166 " , b{0}\n" 21167 "#if DEBUG\n" 21168 " , c{0}\n" 21169 "#else\n" 21170 " , c{1}\n" 21171 "#endif\n" 21172 "#else\n" 21173 "#if DEBUG\n" 21174 " , c{2}\n" 21175 "#else\n" 21176 " , c{3}\n" 21177 "#endif\n" 21178 " , b{1}\n" 21179 "#endif\n" 21180 "{\n}", 21181 Style); 21182 } 21183 21184 TEST_F(FormatTest, Destructors) { 21185 verifyFormat("void F(int &i) { i.~int(); }"); 21186 verifyFormat("void F(int &i) { i->~int(); }"); 21187 } 21188 21189 TEST_F(FormatTest, FormatsWithWebKitStyle) { 21190 FormatStyle Style = getWebKitStyle(); 21191 21192 // Don't indent in outer namespaces. 21193 verifyFormat("namespace outer {\n" 21194 "int i;\n" 21195 "namespace inner {\n" 21196 " int i;\n" 21197 "} // namespace inner\n" 21198 "} // namespace outer\n" 21199 "namespace other_outer {\n" 21200 "int i;\n" 21201 "}", 21202 Style); 21203 21204 // Don't indent case labels. 21205 verifyFormat("switch (variable) {\n" 21206 "case 1:\n" 21207 "case 2:\n" 21208 " doSomething();\n" 21209 " break;\n" 21210 "default:\n" 21211 " ++variable;\n" 21212 "}", 21213 Style); 21214 21215 // Wrap before binary operators. 21216 EXPECT_EQ("void f()\n" 21217 "{\n" 21218 " if (aaaaaaaaaaaaaaaa\n" 21219 " && bbbbbbbbbbbbbbbbbbbbbbbb\n" 21220 " && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n" 21221 " return;\n" 21222 "}", 21223 format("void f() {\n" 21224 "if (aaaaaaaaaaaaaaaa\n" 21225 "&& bbbbbbbbbbbbbbbbbbbbbbbb\n" 21226 "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n" 21227 "return;\n" 21228 "}", 21229 Style)); 21230 21231 // Allow functions on a single line. 21232 verifyFormat("void f() { return; }", Style); 21233 21234 // Allow empty blocks on a single line and insert a space in empty blocks. 21235 EXPECT_EQ("void f() { }", format("void f() {}", Style)); 21236 EXPECT_EQ("while (true) { }", format("while (true) {}", Style)); 21237 // However, don't merge non-empty short loops. 21238 EXPECT_EQ("while (true) {\n" 21239 " continue;\n" 21240 "}", 21241 format("while (true) { continue; }", Style)); 21242 21243 // Constructor initializers are formatted one per line with the "," on the 21244 // new line. 21245 verifyFormat("Constructor()\n" 21246 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 21247 " , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n" 21248 " aaaaaaaaaaaaaa)\n" 21249 " , aaaaaaaaaaaaaaaaaaaaaaa()\n" 21250 "{\n" 21251 "}", 21252 Style); 21253 verifyFormat("SomeClass::Constructor()\n" 21254 " : a(a)\n" 21255 "{\n" 21256 "}", 21257 Style); 21258 EXPECT_EQ("SomeClass::Constructor()\n" 21259 " : a(a)\n" 21260 "{\n" 21261 "}", 21262 format("SomeClass::Constructor():a(a){}", Style)); 21263 verifyFormat("SomeClass::Constructor()\n" 21264 " : a(a)\n" 21265 " , b(b)\n" 21266 " , c(c)\n" 21267 "{\n" 21268 "}", 21269 Style); 21270 verifyFormat("SomeClass::Constructor()\n" 21271 " : a(a)\n" 21272 "{\n" 21273 " foo();\n" 21274 " bar();\n" 21275 "}", 21276 Style); 21277 21278 // Access specifiers should be aligned left. 21279 verifyFormat("class C {\n" 21280 "public:\n" 21281 " int i;\n" 21282 "};", 21283 Style); 21284 21285 // Do not align comments. 21286 verifyFormat("int a; // Do not\n" 21287 "double b; // align comments.", 21288 Style); 21289 21290 // Do not align operands. 21291 EXPECT_EQ("ASSERT(aaaa\n" 21292 " || bbbb);", 21293 format("ASSERT ( aaaa\n||bbbb);", Style)); 21294 21295 // Accept input's line breaks. 21296 EXPECT_EQ("if (aaaaaaaaaaaaaaa\n" 21297 " || bbbbbbbbbbbbbbb) {\n" 21298 " i++;\n" 21299 "}", 21300 format("if (aaaaaaaaaaaaaaa\n" 21301 "|| bbbbbbbbbbbbbbb) { i++; }", 21302 Style)); 21303 EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n" 21304 " i++;\n" 21305 "}", 21306 format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style)); 21307 21308 // Don't automatically break all macro definitions (llvm.org/PR17842). 21309 verifyFormat("#define aNumber 10", Style); 21310 // However, generally keep the line breaks that the user authored. 21311 EXPECT_EQ("#define aNumber \\\n" 21312 " 10", 21313 format("#define aNumber \\\n" 21314 " 10", 21315 Style)); 21316 21317 // Keep empty and one-element array literals on a single line. 21318 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n" 21319 " copyItems:YES];", 21320 format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n" 21321 "copyItems:YES];", 21322 Style)); 21323 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n" 21324 " copyItems:YES];", 21325 format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n" 21326 " copyItems:YES];", 21327 Style)); 21328 // FIXME: This does not seem right, there should be more indentation before 21329 // the array literal's entries. Nested blocks have the same problem. 21330 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n" 21331 " @\"a\",\n" 21332 " @\"a\"\n" 21333 "]\n" 21334 " copyItems:YES];", 21335 format("NSArray* a = [[NSArray alloc] initWithArray:@[\n" 21336 " @\"a\",\n" 21337 " @\"a\"\n" 21338 " ]\n" 21339 " copyItems:YES];", 21340 Style)); 21341 EXPECT_EQ( 21342 "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n" 21343 " copyItems:YES];", 21344 format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n" 21345 " copyItems:YES];", 21346 Style)); 21347 21348 verifyFormat("[self.a b:c c:d];", Style); 21349 EXPECT_EQ("[self.a b:c\n" 21350 " c:d];", 21351 format("[self.a b:c\n" 21352 "c:d];", 21353 Style)); 21354 } 21355 21356 TEST_F(FormatTest, FormatsLambdas) { 21357 verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n"); 21358 verifyFormat( 21359 "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n"); 21360 verifyFormat("int c = [&] { [=] { return b++; }(); }();\n"); 21361 verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n"); 21362 verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n"); 21363 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n"); 21364 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n"); 21365 verifyFormat("auto c = [a = [b = 42] {}] {};\n"); 21366 verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n"); 21367 verifyFormat("int x = f(*+[] {});"); 21368 verifyFormat("void f() {\n" 21369 " other(x.begin(), x.end(), [&](int, int) { return 1; });\n" 21370 "}\n"); 21371 verifyFormat("void f() {\n" 21372 " other(x.begin(), //\n" 21373 " x.end(), //\n" 21374 " [&](int, int) { return 1; });\n" 21375 "}\n"); 21376 verifyFormat("void f() {\n" 21377 " other.other.other.other.other(\n" 21378 " x.begin(), x.end(),\n" 21379 " [something, rather](int, int, int, int, int, int, int) { " 21380 "return 1; });\n" 21381 "}\n"); 21382 verifyFormat( 21383 "void f() {\n" 21384 " other.other.other.other.other(\n" 21385 " x.begin(), x.end(),\n" 21386 " [something, rather](int, int, int, int, int, int, int) {\n" 21387 " //\n" 21388 " });\n" 21389 "}\n"); 21390 verifyFormat("SomeFunction([]() { // A cool function...\n" 21391 " return 43;\n" 21392 "});"); 21393 EXPECT_EQ("SomeFunction([]() {\n" 21394 "#define A a\n" 21395 " return 43;\n" 21396 "});", 21397 format("SomeFunction([](){\n" 21398 "#define A a\n" 21399 "return 43;\n" 21400 "});")); 21401 verifyFormat("void f() {\n" 21402 " SomeFunction([](decltype(x), A *a) {});\n" 21403 " SomeFunction([](typeof(x), A *a) {});\n" 21404 " SomeFunction([](_Atomic(x), A *a) {});\n" 21405 " SomeFunction([](__underlying_type(x), A *a) {});\n" 21406 "}"); 21407 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 21408 " [](const aaaaaaaaaa &a) { return a; });"); 21409 verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n" 21410 " SomeOtherFunctioooooooooooooooooooooooooon();\n" 21411 "});"); 21412 verifyFormat("Constructor()\n" 21413 " : Field([] { // comment\n" 21414 " int i;\n" 21415 " }) {}"); 21416 verifyFormat("auto my_lambda = [](const string &some_parameter) {\n" 21417 " return some_parameter.size();\n" 21418 "};"); 21419 verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n" 21420 " [](const string &s) { return s; };"); 21421 verifyFormat("int i = aaaaaa ? 1 //\n" 21422 " : [] {\n" 21423 " return 2; //\n" 21424 " }();"); 21425 verifyFormat("llvm::errs() << \"number of twos is \"\n" 21426 " << std::count_if(v.begin(), v.end(), [](int x) {\n" 21427 " return x == 2; // force break\n" 21428 " });"); 21429 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 21430 " [=](int iiiiiiiiiiii) {\n" 21431 " return aaaaaaaaaaaaaaaaaaaaaaa !=\n" 21432 " aaaaaaaaaaaaaaaaaaaaaaa;\n" 21433 " });", 21434 getLLVMStyleWithColumns(60)); 21435 21436 verifyFormat("SomeFunction({[&] {\n" 21437 " // comment\n" 21438 " },\n" 21439 " [&] {\n" 21440 " // comment\n" 21441 " }});"); 21442 verifyFormat("SomeFunction({[&] {\n" 21443 " // comment\n" 21444 "}});"); 21445 verifyFormat( 21446 "virtual aaaaaaaaaaaaaaaa(\n" 21447 " std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n" 21448 " aaaaa aaaaaaaaa);"); 21449 21450 // Lambdas with return types. 21451 verifyFormat("int c = []() -> int { return 2; }();\n"); 21452 verifyFormat("int c = []() -> int * { return 2; }();\n"); 21453 verifyFormat("int c = []() -> vector<int> { return {2}; }();\n"); 21454 verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());"); 21455 verifyFormat("foo([]() noexcept -> int {});"); 21456 verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};"); 21457 verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};"); 21458 verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};"); 21459 verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};"); 21460 verifyFormat("[a, a]() -> a<1> {};"); 21461 verifyFormat("[]() -> foo<5 + 2> { return {}; };"); 21462 verifyFormat("[]() -> foo<5 - 2> { return {}; };"); 21463 verifyFormat("[]() -> foo<5 / 2> { return {}; };"); 21464 verifyFormat("[]() -> foo<5 * 2> { return {}; };"); 21465 verifyFormat("[]() -> foo<5 % 2> { return {}; };"); 21466 verifyFormat("[]() -> foo<5 << 2> { return {}; };"); 21467 verifyFormat("[]() -> foo<!5> { return {}; };"); 21468 verifyFormat("[]() -> foo<~5> { return {}; };"); 21469 verifyFormat("[]() -> foo<5 | 2> { return {}; };"); 21470 verifyFormat("[]() -> foo<5 || 2> { return {}; };"); 21471 verifyFormat("[]() -> foo<5 & 2> { return {}; };"); 21472 verifyFormat("[]() -> foo<5 && 2> { return {}; };"); 21473 verifyFormat("[]() -> foo<5 == 2> { return {}; };"); 21474 verifyFormat("[]() -> foo<5 != 2> { return {}; };"); 21475 verifyFormat("[]() -> foo<5 >= 2> { return {}; };"); 21476 verifyFormat("[]() -> foo<5 <= 2> { return {}; };"); 21477 verifyFormat("[]() -> foo<5 < 2> { return {}; };"); 21478 verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };"); 21479 verifyFormat("namespace bar {\n" 21480 "// broken:\n" 21481 "auto foo{[]() -> foo<5 + 2> { return {}; }};\n" 21482 "} // namespace bar"); 21483 verifyFormat("namespace bar {\n" 21484 "// broken:\n" 21485 "auto foo{[]() -> foo<5 - 2> { return {}; }};\n" 21486 "} // namespace bar"); 21487 verifyFormat("namespace bar {\n" 21488 "// broken:\n" 21489 "auto foo{[]() -> foo<5 / 2> { return {}; }};\n" 21490 "} // namespace bar"); 21491 verifyFormat("namespace bar {\n" 21492 "// broken:\n" 21493 "auto foo{[]() -> foo<5 * 2> { return {}; }};\n" 21494 "} // namespace bar"); 21495 verifyFormat("namespace bar {\n" 21496 "// broken:\n" 21497 "auto foo{[]() -> foo<5 % 2> { return {}; }};\n" 21498 "} // namespace bar"); 21499 verifyFormat("namespace bar {\n" 21500 "// broken:\n" 21501 "auto foo{[]() -> foo<5 << 2> { return {}; }};\n" 21502 "} // namespace bar"); 21503 verifyFormat("namespace bar {\n" 21504 "// broken:\n" 21505 "auto foo{[]() -> foo<!5> { return {}; }};\n" 21506 "} // namespace bar"); 21507 verifyFormat("namespace bar {\n" 21508 "// broken:\n" 21509 "auto foo{[]() -> foo<~5> { return {}; }};\n" 21510 "} // namespace bar"); 21511 verifyFormat("namespace bar {\n" 21512 "// broken:\n" 21513 "auto foo{[]() -> foo<5 | 2> { return {}; }};\n" 21514 "} // namespace bar"); 21515 verifyFormat("namespace bar {\n" 21516 "// broken:\n" 21517 "auto foo{[]() -> foo<5 || 2> { return {}; }};\n" 21518 "} // namespace bar"); 21519 verifyFormat("namespace bar {\n" 21520 "// broken:\n" 21521 "auto foo{[]() -> foo<5 & 2> { return {}; }};\n" 21522 "} // namespace bar"); 21523 verifyFormat("namespace bar {\n" 21524 "// broken:\n" 21525 "auto foo{[]() -> foo<5 && 2> { return {}; }};\n" 21526 "} // namespace bar"); 21527 verifyFormat("namespace bar {\n" 21528 "// broken:\n" 21529 "auto foo{[]() -> foo<5 == 2> { return {}; }};\n" 21530 "} // namespace bar"); 21531 verifyFormat("namespace bar {\n" 21532 "// broken:\n" 21533 "auto foo{[]() -> foo<5 != 2> { return {}; }};\n" 21534 "} // namespace bar"); 21535 verifyFormat("namespace bar {\n" 21536 "// broken:\n" 21537 "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n" 21538 "} // namespace bar"); 21539 verifyFormat("namespace bar {\n" 21540 "// broken:\n" 21541 "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n" 21542 "} // namespace bar"); 21543 verifyFormat("namespace bar {\n" 21544 "// broken:\n" 21545 "auto foo{[]() -> foo<5 < 2> { return {}; }};\n" 21546 "} // namespace bar"); 21547 verifyFormat("namespace bar {\n" 21548 "// broken:\n" 21549 "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n" 21550 "} // namespace bar"); 21551 verifyFormat("[]() -> a<1> {};"); 21552 verifyFormat("[]() -> a<1> { ; };"); 21553 verifyFormat("[]() -> a<1> { ; }();"); 21554 verifyFormat("[a, a]() -> a<true> {};"); 21555 verifyFormat("[]() -> a<true> {};"); 21556 verifyFormat("[]() -> a<true> { ; };"); 21557 verifyFormat("[]() -> a<true> { ; }();"); 21558 verifyFormat("[a, a]() -> a<false> {};"); 21559 verifyFormat("[]() -> a<false> {};"); 21560 verifyFormat("[]() -> a<false> { ; };"); 21561 verifyFormat("[]() -> a<false> { ; }();"); 21562 verifyFormat("auto foo{[]() -> foo<false> { ; }};"); 21563 verifyFormat("namespace bar {\n" 21564 "auto foo{[]() -> foo<false> { ; }};\n" 21565 "} // namespace bar"); 21566 verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n" 21567 " int j) -> int {\n" 21568 " return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n" 21569 "};"); 21570 verifyFormat( 21571 "aaaaaaaaaaaaaaaaaaaaaa(\n" 21572 " [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n" 21573 " return aaaaaaaaaaaaaaaaa;\n" 21574 " });", 21575 getLLVMStyleWithColumns(70)); 21576 verifyFormat("[]() //\n" 21577 " -> int {\n" 21578 " return 1; //\n" 21579 "};"); 21580 verifyFormat("[]() -> Void<T...> {};"); 21581 verifyFormat("[a, b]() -> Tuple<T...> { return {}; };"); 21582 verifyFormat("SomeFunction({[]() -> int[] { return {}; }});"); 21583 verifyFormat("SomeFunction({[]() -> int *[] { return {}; }});"); 21584 verifyFormat("SomeFunction({[]() -> int (*)[] { return {}; }});"); 21585 verifyFormat("SomeFunction({[]() -> ns::type<int (*)[]> { return {}; }});"); 21586 verifyFormat("return int{[x = x]() { return x; }()};"); 21587 21588 // Lambdas with explicit template argument lists. 21589 verifyFormat( 21590 "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n"); 21591 verifyFormat("auto L = []<class T>(T) {\n" 21592 " {\n" 21593 " f();\n" 21594 " g();\n" 21595 " }\n" 21596 "};\n"); 21597 verifyFormat("auto L = []<class... T>(T...) {\n" 21598 " {\n" 21599 " f();\n" 21600 " g();\n" 21601 " }\n" 21602 "};\n"); 21603 verifyFormat("auto L = []<typename... T>(T...) {\n" 21604 " {\n" 21605 " f();\n" 21606 " g();\n" 21607 " }\n" 21608 "};\n"); 21609 verifyFormat("auto L = []<template <typename...> class T>(T...) {\n" 21610 " {\n" 21611 " f();\n" 21612 " g();\n" 21613 " }\n" 21614 "};\n"); 21615 verifyFormat("auto L = []</*comment*/ class... T>(T...) {\n" 21616 " {\n" 21617 " f();\n" 21618 " g();\n" 21619 " }\n" 21620 "};\n"); 21621 21622 // Multiple lambdas in the same parentheses change indentation rules. These 21623 // lambdas are forced to start on new lines. 21624 verifyFormat("SomeFunction(\n" 21625 " []() {\n" 21626 " //\n" 21627 " },\n" 21628 " []() {\n" 21629 " //\n" 21630 " });"); 21631 21632 // A lambda passed as arg0 is always pushed to the next line. 21633 verifyFormat("SomeFunction(\n" 21634 " [this] {\n" 21635 " //\n" 21636 " },\n" 21637 " 1);\n"); 21638 21639 // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like 21640 // the arg0 case above. 21641 auto Style = getGoogleStyle(); 21642 Style.BinPackArguments = false; 21643 verifyFormat("SomeFunction(\n" 21644 " a,\n" 21645 " [this] {\n" 21646 " //\n" 21647 " },\n" 21648 " b);\n", 21649 Style); 21650 verifyFormat("SomeFunction(\n" 21651 " a,\n" 21652 " [this] {\n" 21653 " //\n" 21654 " },\n" 21655 " b);\n"); 21656 21657 // A lambda with a very long line forces arg0 to be pushed out irrespective of 21658 // the BinPackArguments value (as long as the code is wide enough). 21659 verifyFormat( 21660 "something->SomeFunction(\n" 21661 " a,\n" 21662 " [this] {\n" 21663 " " 21664 "D0000000000000000000000000000000000000000000000000000000000001();\n" 21665 " },\n" 21666 " b);\n"); 21667 21668 // A multi-line lambda is pulled up as long as the introducer fits on the 21669 // previous line and there are no further args. 21670 verifyFormat("function(1, [this, that] {\n" 21671 " //\n" 21672 "});\n"); 21673 verifyFormat("function([this, that] {\n" 21674 " //\n" 21675 "});\n"); 21676 // FIXME: this format is not ideal and we should consider forcing the first 21677 // arg onto its own line. 21678 verifyFormat("function(a, b, c, //\n" 21679 " d, [this, that] {\n" 21680 " //\n" 21681 " });\n"); 21682 21683 // Multiple lambdas are treated correctly even when there is a short arg0. 21684 verifyFormat("SomeFunction(\n" 21685 " 1,\n" 21686 " [this] {\n" 21687 " //\n" 21688 " },\n" 21689 " [this] {\n" 21690 " //\n" 21691 " },\n" 21692 " 1);\n"); 21693 21694 // More complex introducers. 21695 verifyFormat("return [i, args...] {};"); 21696 21697 // Not lambdas. 21698 verifyFormat("constexpr char hello[]{\"hello\"};"); 21699 verifyFormat("double &operator[](int i) { return 0; }\n" 21700 "int i;"); 21701 verifyFormat("std::unique_ptr<int[]> foo() {}"); 21702 verifyFormat("int i = a[a][a]->f();"); 21703 verifyFormat("int i = (*b)[a]->f();"); 21704 21705 // Other corner cases. 21706 verifyFormat("void f() {\n" 21707 " bar([]() {} // Did not respect SpacesBeforeTrailingComments\n" 21708 " );\n" 21709 "}"); 21710 verifyFormat("auto k = *[](int *j) { return j; }(&i);"); 21711 21712 // Lambdas created through weird macros. 21713 verifyFormat("void f() {\n" 21714 " MACRO((const AA &a) { return 1; });\n" 21715 " MACRO((AA &a) { return 1; });\n" 21716 "}"); 21717 21718 verifyFormat("if (blah_blah(whatever, whatever, [] {\n" 21719 " doo_dah();\n" 21720 " doo_dah();\n" 21721 " })) {\n" 21722 "}"); 21723 verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n" 21724 " doo_dah();\n" 21725 " doo_dah();\n" 21726 " })) {\n" 21727 "}"); 21728 verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n" 21729 " doo_dah();\n" 21730 " doo_dah();\n" 21731 " })) {\n" 21732 "}"); 21733 verifyFormat("auto lambda = []() {\n" 21734 " int a = 2\n" 21735 "#if A\n" 21736 " + 2\n" 21737 "#endif\n" 21738 " ;\n" 21739 "};"); 21740 21741 // Lambdas with complex multiline introducers. 21742 verifyFormat( 21743 "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 21744 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n" 21745 " -> ::std::unordered_set<\n" 21746 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n" 21747 " //\n" 21748 " });"); 21749 21750 FormatStyle DoNotMerge = getLLVMStyle(); 21751 DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 21752 verifyFormat("auto c = []() {\n" 21753 " return b;\n" 21754 "};", 21755 "auto c = []() { return b; };", DoNotMerge); 21756 verifyFormat("auto c = []() {\n" 21757 "};", 21758 " auto c = []() {};", DoNotMerge); 21759 21760 FormatStyle MergeEmptyOnly = getLLVMStyle(); 21761 MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty; 21762 verifyFormat("auto c = []() {\n" 21763 " return b;\n" 21764 "};", 21765 "auto c = []() {\n" 21766 " return b;\n" 21767 " };", 21768 MergeEmptyOnly); 21769 verifyFormat("auto c = []() {};", 21770 "auto c = []() {\n" 21771 "};", 21772 MergeEmptyOnly); 21773 21774 FormatStyle MergeInline = getLLVMStyle(); 21775 MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline; 21776 verifyFormat("auto c = []() {\n" 21777 " return b;\n" 21778 "};", 21779 "auto c = []() { return b; };", MergeInline); 21780 verifyFormat("function([]() { return b; })", "function([]() { return b; })", 21781 MergeInline); 21782 verifyFormat("function([]() { return b; }, a)", 21783 "function([]() { return b; }, a)", MergeInline); 21784 verifyFormat("function(a, []() { return b; })", 21785 "function(a, []() { return b; })", MergeInline); 21786 21787 // Check option "BraceWrapping.BeforeLambdaBody" and different state of 21788 // AllowShortLambdasOnASingleLine 21789 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle(); 21790 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 21791 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 21792 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21793 FormatStyle::ShortLambdaStyle::SLS_None; 21794 verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n" 21795 " []()\n" 21796 " {\n" 21797 " return 17;\n" 21798 " });", 21799 LLVMWithBeforeLambdaBody); 21800 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n" 21801 " []()\n" 21802 " {\n" 21803 " });", 21804 LLVMWithBeforeLambdaBody); 21805 verifyFormat("auto fct_SLS_None = []()\n" 21806 "{\n" 21807 " return 17;\n" 21808 "};", 21809 LLVMWithBeforeLambdaBody); 21810 verifyFormat("TwoNestedLambdas_SLS_None(\n" 21811 " []()\n" 21812 " {\n" 21813 " return Call(\n" 21814 " []()\n" 21815 " {\n" 21816 " return 17;\n" 21817 " });\n" 21818 " });", 21819 LLVMWithBeforeLambdaBody); 21820 verifyFormat("void Fct() {\n" 21821 " return {[]()\n" 21822 " {\n" 21823 " return 17;\n" 21824 " }};\n" 21825 "}", 21826 LLVMWithBeforeLambdaBody); 21827 21828 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21829 FormatStyle::ShortLambdaStyle::SLS_Empty; 21830 verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n" 21831 " []()\n" 21832 " {\n" 21833 " return 17;\n" 21834 " });", 21835 LLVMWithBeforeLambdaBody); 21836 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});", 21837 LLVMWithBeforeLambdaBody); 21838 verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL" 21839 "ongFunctionName_SLS_Empty(\n" 21840 " []() {});", 21841 LLVMWithBeforeLambdaBody); 21842 verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n" 21843 " []()\n" 21844 " {\n" 21845 " return 17;\n" 21846 " });", 21847 LLVMWithBeforeLambdaBody); 21848 verifyFormat("auto fct_SLS_Empty = []()\n" 21849 "{\n" 21850 " return 17;\n" 21851 "};", 21852 LLVMWithBeforeLambdaBody); 21853 verifyFormat("TwoNestedLambdas_SLS_Empty(\n" 21854 " []()\n" 21855 " {\n" 21856 " return Call([]() {});\n" 21857 " });", 21858 LLVMWithBeforeLambdaBody); 21859 verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n" 21860 " []()\n" 21861 " {\n" 21862 " return Call([]() {});\n" 21863 " });", 21864 LLVMWithBeforeLambdaBody); 21865 verifyFormat( 21866 "FctWithLongLineInLambda_SLS_Empty(\n" 21867 " []()\n" 21868 " {\n" 21869 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21870 " AndShouldNotBeConsiderAsInline,\n" 21871 " LambdaBodyMustBeBreak);\n" 21872 " });", 21873 LLVMWithBeforeLambdaBody); 21874 21875 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21876 FormatStyle::ShortLambdaStyle::SLS_Inline; 21877 verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });", 21878 LLVMWithBeforeLambdaBody); 21879 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});", 21880 LLVMWithBeforeLambdaBody); 21881 verifyFormat("auto fct_SLS_Inline = []()\n" 21882 "{\n" 21883 " return 17;\n" 21884 "};", 21885 LLVMWithBeforeLambdaBody); 21886 verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return " 21887 "17; }); });", 21888 LLVMWithBeforeLambdaBody); 21889 verifyFormat( 21890 "FctWithLongLineInLambda_SLS_Inline(\n" 21891 " []()\n" 21892 " {\n" 21893 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21894 " AndShouldNotBeConsiderAsInline,\n" 21895 " LambdaBodyMustBeBreak);\n" 21896 " });", 21897 LLVMWithBeforeLambdaBody); 21898 verifyFormat("FctWithMultipleParams_SLS_Inline(" 21899 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n" 21900 " []() { return 17; });", 21901 LLVMWithBeforeLambdaBody); 21902 verifyFormat( 21903 "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });", 21904 LLVMWithBeforeLambdaBody); 21905 21906 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21907 FormatStyle::ShortLambdaStyle::SLS_All; 21908 verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });", 21909 LLVMWithBeforeLambdaBody); 21910 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});", 21911 LLVMWithBeforeLambdaBody); 21912 verifyFormat("auto fct_SLS_All = []() { return 17; };", 21913 LLVMWithBeforeLambdaBody); 21914 verifyFormat("FctWithOneParam_SLS_All(\n" 21915 " []()\n" 21916 " {\n" 21917 " // A cool function...\n" 21918 " return 43;\n" 21919 " });", 21920 LLVMWithBeforeLambdaBody); 21921 verifyFormat("FctWithMultipleParams_SLS_All(" 21922 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n" 21923 " []() { return 17; });", 21924 LLVMWithBeforeLambdaBody); 21925 verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });", 21926 LLVMWithBeforeLambdaBody); 21927 verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });", 21928 LLVMWithBeforeLambdaBody); 21929 verifyFormat( 21930 "FctWithLongLineInLambda_SLS_All(\n" 21931 " []()\n" 21932 " {\n" 21933 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21934 " AndShouldNotBeConsiderAsInline,\n" 21935 " LambdaBodyMustBeBreak);\n" 21936 " });", 21937 LLVMWithBeforeLambdaBody); 21938 verifyFormat( 21939 "auto fct_SLS_All = []()\n" 21940 "{\n" 21941 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21942 " AndShouldNotBeConsiderAsInline,\n" 21943 " LambdaBodyMustBeBreak);\n" 21944 "};", 21945 LLVMWithBeforeLambdaBody); 21946 LLVMWithBeforeLambdaBody.BinPackParameters = false; 21947 verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);", 21948 LLVMWithBeforeLambdaBody); 21949 verifyFormat( 21950 "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n" 21951 " FirstParam,\n" 21952 " SecondParam,\n" 21953 " ThirdParam,\n" 21954 " FourthParam);", 21955 LLVMWithBeforeLambdaBody); 21956 verifyFormat("FctWithLongLineInLambda_SLS_All(\n" 21957 " []() { return " 21958 "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n" 21959 " FirstParam,\n" 21960 " SecondParam,\n" 21961 " ThirdParam,\n" 21962 " FourthParam);", 21963 LLVMWithBeforeLambdaBody); 21964 verifyFormat( 21965 "FctWithLongLineInLambda_SLS_All(FirstParam,\n" 21966 " SecondParam,\n" 21967 " ThirdParam,\n" 21968 " FourthParam,\n" 21969 " []() { return SomeValueNotSoLong; });", 21970 LLVMWithBeforeLambdaBody); 21971 verifyFormat("FctWithLongLineInLambda_SLS_All(\n" 21972 " []()\n" 21973 " {\n" 21974 " return " 21975 "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB" 21976 "eConsiderAsInline;\n" 21977 " });", 21978 LLVMWithBeforeLambdaBody); 21979 verifyFormat( 21980 "FctWithLongLineInLambda_SLS_All(\n" 21981 " []()\n" 21982 " {\n" 21983 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21984 " AndShouldNotBeConsiderAsInline,\n" 21985 " LambdaBodyMustBeBreak);\n" 21986 " });", 21987 LLVMWithBeforeLambdaBody); 21988 verifyFormat("FctWithTwoParams_SLS_All(\n" 21989 " []()\n" 21990 " {\n" 21991 " // A cool function...\n" 21992 " return 43;\n" 21993 " },\n" 21994 " 87);", 21995 LLVMWithBeforeLambdaBody); 21996 verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);", 21997 LLVMWithBeforeLambdaBody); 21998 verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });", 21999 LLVMWithBeforeLambdaBody); 22000 verifyFormat( 22001 "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });", 22002 LLVMWithBeforeLambdaBody); 22003 verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; " 22004 "}); }, x);", 22005 LLVMWithBeforeLambdaBody); 22006 verifyFormat("TwoNestedLambdas_SLS_All(\n" 22007 " []()\n" 22008 " {\n" 22009 " // A cool function...\n" 22010 " return Call([]() { return 17; });\n" 22011 " });", 22012 LLVMWithBeforeLambdaBody); 22013 verifyFormat("TwoNestedLambdas_SLS_All(\n" 22014 " []()\n" 22015 " {\n" 22016 " return Call(\n" 22017 " []()\n" 22018 " {\n" 22019 " // A cool function...\n" 22020 " return 17;\n" 22021 " });\n" 22022 " });", 22023 LLVMWithBeforeLambdaBody); 22024 22025 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 22026 FormatStyle::ShortLambdaStyle::SLS_None; 22027 22028 verifyFormat("auto select = [this]() -> const Library::Object *\n" 22029 "{\n" 22030 " return MyAssignment::SelectFromList(this);\n" 22031 "};\n", 22032 LLVMWithBeforeLambdaBody); 22033 22034 verifyFormat("auto select = [this]() -> const Library::Object &\n" 22035 "{\n" 22036 " return MyAssignment::SelectFromList(this);\n" 22037 "};\n", 22038 LLVMWithBeforeLambdaBody); 22039 22040 verifyFormat("auto select = [this]() -> std::unique_ptr<Object>\n" 22041 "{\n" 22042 " return MyAssignment::SelectFromList(this);\n" 22043 "};\n", 22044 LLVMWithBeforeLambdaBody); 22045 22046 verifyFormat("namespace test {\n" 22047 "class Test {\n" 22048 "public:\n" 22049 " Test() = default;\n" 22050 "};\n" 22051 "} // namespace test", 22052 LLVMWithBeforeLambdaBody); 22053 22054 // Lambdas with different indentation styles. 22055 Style = getLLVMStyleWithColumns(100); 22056 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 22057 " return promise.then(\n" 22058 " [this, &someVariable, someObject = " 22059 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 22060 " return someObject.startAsyncAction().then(\n" 22061 " [this, &someVariable](AsyncActionResult result) " 22062 "mutable { result.processMore(); });\n" 22063 " });\n" 22064 "}\n", 22065 format("SomeResult doSomething(SomeObject promise) {\n" 22066 " return promise.then([this, &someVariable, someObject = " 22067 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 22068 " return someObject.startAsyncAction().then([this, " 22069 "&someVariable](AsyncActionResult result) mutable {\n" 22070 " result.processMore();\n" 22071 " });\n" 22072 " });\n" 22073 "}\n", 22074 Style)); 22075 Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope; 22076 verifyFormat("test() {\n" 22077 " ([]() -> {\n" 22078 " int b = 32;\n" 22079 " return 3;\n" 22080 " }).foo();\n" 22081 "}", 22082 Style); 22083 verifyFormat("test() {\n" 22084 " []() -> {\n" 22085 " int b = 32;\n" 22086 " return 3;\n" 22087 " }\n" 22088 "}", 22089 Style); 22090 verifyFormat("std::sort(v.begin(), v.end(),\n" 22091 " [](const auto &someLongArgumentName, const auto " 22092 "&someOtherLongArgumentName) {\n" 22093 " return someLongArgumentName.someMemberVariable < " 22094 "someOtherLongArgumentName.someMemberVariable;\n" 22095 "});", 22096 Style); 22097 verifyFormat("test() {\n" 22098 " (\n" 22099 " []() -> {\n" 22100 " int b = 32;\n" 22101 " return 3;\n" 22102 " },\n" 22103 " foo, bar)\n" 22104 " .foo();\n" 22105 "}", 22106 Style); 22107 verifyFormat("test() {\n" 22108 " ([]() -> {\n" 22109 " int b = 32;\n" 22110 " return 3;\n" 22111 " })\n" 22112 " .foo()\n" 22113 " .bar();\n" 22114 "}", 22115 Style); 22116 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 22117 " return promise.then(\n" 22118 " [this, &someVariable, someObject = " 22119 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 22120 " return someObject.startAsyncAction().then(\n" 22121 " [this, &someVariable](AsyncActionResult result) mutable { " 22122 "result.processMore(); });\n" 22123 " });\n" 22124 "}\n", 22125 format("SomeResult doSomething(SomeObject promise) {\n" 22126 " return promise.then([this, &someVariable, someObject = " 22127 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 22128 " return someObject.startAsyncAction().then([this, " 22129 "&someVariable](AsyncActionResult result) mutable {\n" 22130 " result.processMore();\n" 22131 " });\n" 22132 " });\n" 22133 "}\n", 22134 Style)); 22135 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 22136 " return promise.then([this, &someVariable] {\n" 22137 " return someObject.startAsyncAction().then(\n" 22138 " [this, &someVariable](AsyncActionResult result) mutable { " 22139 "result.processMore(); });\n" 22140 " });\n" 22141 "}\n", 22142 format("SomeResult doSomething(SomeObject promise) {\n" 22143 " return promise.then([this, &someVariable] {\n" 22144 " return someObject.startAsyncAction().then([this, " 22145 "&someVariable](AsyncActionResult result) mutable {\n" 22146 " result.processMore();\n" 22147 " });\n" 22148 " });\n" 22149 "}\n", 22150 Style)); 22151 Style = getGoogleStyle(); 22152 Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope; 22153 EXPECT_EQ("#define A \\\n" 22154 " [] { \\\n" 22155 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 22156 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n" 22157 " }", 22158 format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 22159 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }", 22160 Style)); 22161 // TODO: The current formatting has a minor issue that's not worth fixing 22162 // right now whereby the closing brace is indented relative to the signature 22163 // instead of being aligned. This only happens with macros. 22164 } 22165 22166 TEST_F(FormatTest, LambdaWithLineComments) { 22167 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle(); 22168 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 22169 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 22170 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 22171 FormatStyle::ShortLambdaStyle::SLS_All; 22172 22173 verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody); 22174 verifyFormat("auto k = []() // comment\n" 22175 "{ return; }", 22176 LLVMWithBeforeLambdaBody); 22177 verifyFormat("auto k = []() /* comment */ { return; }", 22178 LLVMWithBeforeLambdaBody); 22179 verifyFormat("auto k = []() /* comment */ /* comment */ { return; }", 22180 LLVMWithBeforeLambdaBody); 22181 verifyFormat("auto k = []() // X\n" 22182 "{ return; }", 22183 LLVMWithBeforeLambdaBody); 22184 verifyFormat( 22185 "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" 22186 "{ return; }", 22187 LLVMWithBeforeLambdaBody); 22188 22189 LLVMWithBeforeLambdaBody.ColumnLimit = 0; 22190 22191 verifyFormat("foo([]()\n" 22192 " {\n" 22193 " bar(); //\n" 22194 " return 1; // comment\n" 22195 " }());", 22196 "foo([]() {\n" 22197 " bar(); //\n" 22198 " return 1; // comment\n" 22199 "}());", 22200 LLVMWithBeforeLambdaBody); 22201 verifyFormat("foo(\n" 22202 " 1, MACRO {\n" 22203 " baz();\n" 22204 " bar(); // comment\n" 22205 " },\n" 22206 " []() {});", 22207 "foo(\n" 22208 " 1, MACRO { baz(); bar(); // comment\n" 22209 " }, []() {}\n" 22210 ");", 22211 LLVMWithBeforeLambdaBody); 22212 } 22213 22214 TEST_F(FormatTest, EmptyLinesInLambdas) { 22215 verifyFormat("auto lambda = []() {\n" 22216 " x(); //\n" 22217 "};", 22218 "auto lambda = []() {\n" 22219 "\n" 22220 " x(); //\n" 22221 "\n" 22222 "};"); 22223 } 22224 22225 TEST_F(FormatTest, FormatsBlocks) { 22226 FormatStyle ShortBlocks = getLLVMStyle(); 22227 ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 22228 verifyFormat("int (^Block)(int, int);", ShortBlocks); 22229 verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks); 22230 verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks); 22231 verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks); 22232 verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks); 22233 verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks); 22234 22235 verifyFormat("foo(^{ bar(); });", ShortBlocks); 22236 verifyFormat("foo(a, ^{ bar(); });", ShortBlocks); 22237 verifyFormat("{ void (^block)(Object *x); }", ShortBlocks); 22238 22239 verifyFormat("[operation setCompletionBlock:^{\n" 22240 " [self onOperationDone];\n" 22241 "}];"); 22242 verifyFormat("int i = {[operation setCompletionBlock:^{\n" 22243 " [self onOperationDone];\n" 22244 "}]};"); 22245 verifyFormat("[operation setCompletionBlock:^(int *i) {\n" 22246 " f();\n" 22247 "}];"); 22248 verifyFormat("int a = [operation block:^int(int *i) {\n" 22249 " return 1;\n" 22250 "}];"); 22251 verifyFormat("[myObject doSomethingWith:arg1\n" 22252 " aaa:^int(int *a) {\n" 22253 " return 1;\n" 22254 " }\n" 22255 " bbb:f(a * bbbbbbbb)];"); 22256 22257 verifyFormat("[operation setCompletionBlock:^{\n" 22258 " [self.delegate newDataAvailable];\n" 22259 "}];", 22260 getLLVMStyleWithColumns(60)); 22261 verifyFormat("dispatch_async(_fileIOQueue, ^{\n" 22262 " NSString *path = [self sessionFilePath];\n" 22263 " if (path) {\n" 22264 " // ...\n" 22265 " }\n" 22266 "});"); 22267 verifyFormat("[[SessionService sharedService]\n" 22268 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 22269 " if (window) {\n" 22270 " [self windowDidLoad:window];\n" 22271 " } else {\n" 22272 " [self errorLoadingWindow];\n" 22273 " }\n" 22274 " }];"); 22275 verifyFormat("void (^largeBlock)(void) = ^{\n" 22276 " // ...\n" 22277 "};\n", 22278 getLLVMStyleWithColumns(40)); 22279 verifyFormat("[[SessionService sharedService]\n" 22280 " loadWindowWithCompletionBlock: //\n" 22281 " ^(SessionWindow *window) {\n" 22282 " if (window) {\n" 22283 " [self windowDidLoad:window];\n" 22284 " } else {\n" 22285 " [self errorLoadingWindow];\n" 22286 " }\n" 22287 " }];", 22288 getLLVMStyleWithColumns(60)); 22289 verifyFormat("[myObject doSomethingWith:arg1\n" 22290 " firstBlock:^(Foo *a) {\n" 22291 " // ...\n" 22292 " int i;\n" 22293 " }\n" 22294 " secondBlock:^(Bar *b) {\n" 22295 " // ...\n" 22296 " int i;\n" 22297 " }\n" 22298 " thirdBlock:^Foo(Bar *b) {\n" 22299 " // ...\n" 22300 " int i;\n" 22301 " }];"); 22302 verifyFormat("[myObject doSomethingWith:arg1\n" 22303 " firstBlock:-1\n" 22304 " secondBlock:^(Bar *b) {\n" 22305 " // ...\n" 22306 " int i;\n" 22307 " }];"); 22308 22309 verifyFormat("f(^{\n" 22310 " @autoreleasepool {\n" 22311 " if (a) {\n" 22312 " g();\n" 22313 " }\n" 22314 " }\n" 22315 "});"); 22316 verifyFormat("Block b = ^int *(A *a, B *b) {}"); 22317 verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n" 22318 "};"); 22319 22320 FormatStyle FourIndent = getLLVMStyle(); 22321 FourIndent.ObjCBlockIndentWidth = 4; 22322 verifyFormat("[operation setCompletionBlock:^{\n" 22323 " [self onOperationDone];\n" 22324 "}];", 22325 FourIndent); 22326 } 22327 22328 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) { 22329 FormatStyle ZeroColumn = getLLVMStyleWithColumns(0); 22330 22331 verifyFormat("[[SessionService sharedService] " 22332 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 22333 " if (window) {\n" 22334 " [self windowDidLoad:window];\n" 22335 " } else {\n" 22336 " [self errorLoadingWindow];\n" 22337 " }\n" 22338 "}];", 22339 ZeroColumn); 22340 EXPECT_EQ("[[SessionService sharedService]\n" 22341 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 22342 " if (window) {\n" 22343 " [self windowDidLoad:window];\n" 22344 " } else {\n" 22345 " [self errorLoadingWindow];\n" 22346 " }\n" 22347 " }];", 22348 format("[[SessionService sharedService]\n" 22349 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 22350 " if (window) {\n" 22351 " [self windowDidLoad:window];\n" 22352 " } else {\n" 22353 " [self errorLoadingWindow];\n" 22354 " }\n" 22355 "}];", 22356 ZeroColumn)); 22357 verifyFormat("[myObject doSomethingWith:arg1\n" 22358 " firstBlock:^(Foo *a) {\n" 22359 " // ...\n" 22360 " int i;\n" 22361 " }\n" 22362 " secondBlock:^(Bar *b) {\n" 22363 " // ...\n" 22364 " int i;\n" 22365 " }\n" 22366 " thirdBlock:^Foo(Bar *b) {\n" 22367 " // ...\n" 22368 " int i;\n" 22369 " }];", 22370 ZeroColumn); 22371 verifyFormat("f(^{\n" 22372 " @autoreleasepool {\n" 22373 " if (a) {\n" 22374 " g();\n" 22375 " }\n" 22376 " }\n" 22377 "});", 22378 ZeroColumn); 22379 verifyFormat("void (^largeBlock)(void) = ^{\n" 22380 " // ...\n" 22381 "};", 22382 ZeroColumn); 22383 22384 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 22385 EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };", 22386 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn)); 22387 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 22388 EXPECT_EQ("void (^largeBlock)(void) = ^{\n" 22389 " int i;\n" 22390 "};", 22391 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn)); 22392 } 22393 22394 TEST_F(FormatTest, SupportsCRLF) { 22395 EXPECT_EQ("int a;\r\n" 22396 "int b;\r\n" 22397 "int c;\r\n", 22398 format("int a;\r\n" 22399 " int b;\r\n" 22400 " int c;\r\n", 22401 getLLVMStyle())); 22402 EXPECT_EQ("int a;\r\n" 22403 "int b;\r\n" 22404 "int c;\r\n", 22405 format("int a;\r\n" 22406 " int b;\n" 22407 " int c;\r\n", 22408 getLLVMStyle())); 22409 EXPECT_EQ("int a;\n" 22410 "int b;\n" 22411 "int c;\n", 22412 format("int a;\r\n" 22413 " int b;\n" 22414 " int c;\n", 22415 getLLVMStyle())); 22416 EXPECT_EQ("\"aaaaaaa \"\r\n" 22417 "\"bbbbbbb\";\r\n", 22418 format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10))); 22419 EXPECT_EQ("#define A \\\r\n" 22420 " b; \\\r\n" 22421 " c; \\\r\n" 22422 " d;\r\n", 22423 format("#define A \\\r\n" 22424 " b; \\\r\n" 22425 " c; d; \r\n", 22426 getGoogleStyle())); 22427 22428 EXPECT_EQ("/*\r\n" 22429 "multi line block comments\r\n" 22430 "should not introduce\r\n" 22431 "an extra carriage return\r\n" 22432 "*/\r\n", 22433 format("/*\r\n" 22434 "multi line block comments\r\n" 22435 "should not introduce\r\n" 22436 "an extra carriage return\r\n" 22437 "*/\r\n")); 22438 EXPECT_EQ("/*\r\n" 22439 "\r\n" 22440 "*/", 22441 format("/*\r\n" 22442 " \r\r\r\n" 22443 "*/")); 22444 22445 FormatStyle style = getLLVMStyle(); 22446 22447 style.DeriveLineEnding = true; 22448 style.UseCRLF = false; 22449 EXPECT_EQ("union FooBarBazQux {\n" 22450 " int foo;\n" 22451 " int bar;\n" 22452 " int baz;\n" 22453 "};", 22454 format("union FooBarBazQux {\r\n" 22455 " int foo;\n" 22456 " int bar;\r\n" 22457 " int baz;\n" 22458 "};", 22459 style)); 22460 style.UseCRLF = true; 22461 EXPECT_EQ("union FooBarBazQux {\r\n" 22462 " int foo;\r\n" 22463 " int bar;\r\n" 22464 " int baz;\r\n" 22465 "};", 22466 format("union FooBarBazQux {\r\n" 22467 " int foo;\n" 22468 " int bar;\r\n" 22469 " int baz;\n" 22470 "};", 22471 style)); 22472 22473 style.DeriveLineEnding = false; 22474 style.UseCRLF = false; 22475 EXPECT_EQ("union FooBarBazQux {\n" 22476 " int foo;\n" 22477 " int bar;\n" 22478 " int baz;\n" 22479 " int qux;\n" 22480 "};", 22481 format("union FooBarBazQux {\r\n" 22482 " int foo;\n" 22483 " int bar;\r\n" 22484 " int baz;\n" 22485 " int qux;\r\n" 22486 "};", 22487 style)); 22488 style.UseCRLF = true; 22489 EXPECT_EQ("union FooBarBazQux {\r\n" 22490 " int foo;\r\n" 22491 " int bar;\r\n" 22492 " int baz;\r\n" 22493 " int qux;\r\n" 22494 "};", 22495 format("union FooBarBazQux {\r\n" 22496 " int foo;\n" 22497 " int bar;\r\n" 22498 " int baz;\n" 22499 " int qux;\n" 22500 "};", 22501 style)); 22502 22503 style.DeriveLineEnding = true; 22504 style.UseCRLF = false; 22505 EXPECT_EQ("union FooBarBazQux {\r\n" 22506 " int foo;\r\n" 22507 " int bar;\r\n" 22508 " int baz;\r\n" 22509 " int qux;\r\n" 22510 "};", 22511 format("union FooBarBazQux {\r\n" 22512 " int foo;\n" 22513 " int bar;\r\n" 22514 " int baz;\n" 22515 " int qux;\r\n" 22516 "};", 22517 style)); 22518 style.UseCRLF = true; 22519 EXPECT_EQ("union FooBarBazQux {\n" 22520 " int foo;\n" 22521 " int bar;\n" 22522 " int baz;\n" 22523 " int qux;\n" 22524 "};", 22525 format("union FooBarBazQux {\r\n" 22526 " int foo;\n" 22527 " int bar;\r\n" 22528 " int baz;\n" 22529 " int qux;\n" 22530 "};", 22531 style)); 22532 } 22533 22534 TEST_F(FormatTest, MunchSemicolonAfterBlocks) { 22535 verifyFormat("MY_CLASS(C) {\n" 22536 " int i;\n" 22537 " int j;\n" 22538 "};"); 22539 } 22540 22541 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) { 22542 FormatStyle TwoIndent = getLLVMStyleWithColumns(15); 22543 TwoIndent.ContinuationIndentWidth = 2; 22544 22545 EXPECT_EQ("int i =\n" 22546 " longFunction(\n" 22547 " arg);", 22548 format("int i = longFunction(arg);", TwoIndent)); 22549 22550 FormatStyle SixIndent = getLLVMStyleWithColumns(20); 22551 SixIndent.ContinuationIndentWidth = 6; 22552 22553 EXPECT_EQ("int i =\n" 22554 " longFunction(\n" 22555 " arg);", 22556 format("int i = longFunction(arg);", SixIndent)); 22557 } 22558 22559 TEST_F(FormatTest, WrappedClosingParenthesisIndent) { 22560 FormatStyle Style = getLLVMStyle(); 22561 verifyFormat("int Foo::getter(\n" 22562 " //\n" 22563 ") const {\n" 22564 " return foo;\n" 22565 "}", 22566 Style); 22567 verifyFormat("void Foo::setter(\n" 22568 " //\n" 22569 ") {\n" 22570 " foo = 1;\n" 22571 "}", 22572 Style); 22573 } 22574 22575 TEST_F(FormatTest, SpacesInAngles) { 22576 FormatStyle Spaces = getLLVMStyle(); 22577 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22578 22579 verifyFormat("vector< ::std::string > x1;", Spaces); 22580 verifyFormat("Foo< int, Bar > x2;", Spaces); 22581 verifyFormat("Foo< ::int, ::Bar > x3;", Spaces); 22582 22583 verifyFormat("static_cast< int >(arg);", Spaces); 22584 verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces); 22585 verifyFormat("f< int, float >();", Spaces); 22586 verifyFormat("template <> g() {}", Spaces); 22587 verifyFormat("template < std::vector< int > > f() {}", Spaces); 22588 verifyFormat("std::function< void(int, int) > fct;", Spaces); 22589 verifyFormat("void inFunction() { std::function< void(int, int) > fct; }", 22590 Spaces); 22591 22592 Spaces.Standard = FormatStyle::LS_Cpp03; 22593 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22594 verifyFormat("A< A< int > >();", Spaces); 22595 22596 Spaces.SpacesInAngles = FormatStyle::SIAS_Never; 22597 verifyFormat("A<A<int> >();", Spaces); 22598 22599 Spaces.SpacesInAngles = FormatStyle::SIAS_Leave; 22600 verifyFormat("vector< ::std::string> x4;", "vector<::std::string> x4;", 22601 Spaces); 22602 verifyFormat("vector< ::std::string > x4;", "vector<::std::string > x4;", 22603 Spaces); 22604 22605 verifyFormat("A<A<int> >();", Spaces); 22606 verifyFormat("A<A<int> >();", "A<A<int>>();", Spaces); 22607 verifyFormat("A< A< int > >();", Spaces); 22608 22609 Spaces.Standard = FormatStyle::LS_Cpp11; 22610 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22611 verifyFormat("A< A< int > >();", Spaces); 22612 22613 Spaces.SpacesInAngles = FormatStyle::SIAS_Never; 22614 verifyFormat("vector<::std::string> x4;", Spaces); 22615 verifyFormat("vector<int> x5;", Spaces); 22616 verifyFormat("Foo<int, Bar> x6;", Spaces); 22617 verifyFormat("Foo<::int, ::Bar> x7;", Spaces); 22618 22619 verifyFormat("A<A<int>>();", Spaces); 22620 22621 Spaces.SpacesInAngles = FormatStyle::SIAS_Leave; 22622 verifyFormat("vector<::std::string> x4;", Spaces); 22623 verifyFormat("vector< ::std::string > x4;", Spaces); 22624 verifyFormat("vector<int> x5;", Spaces); 22625 verifyFormat("vector< int > x5;", Spaces); 22626 verifyFormat("Foo<int, Bar> x6;", Spaces); 22627 verifyFormat("Foo< int, Bar > x6;", Spaces); 22628 verifyFormat("Foo<::int, ::Bar> x7;", Spaces); 22629 verifyFormat("Foo< ::int, ::Bar > x7;", Spaces); 22630 22631 verifyFormat("A<A<int>>();", Spaces); 22632 verifyFormat("A< A< int > >();", Spaces); 22633 verifyFormat("A<A<int > >();", Spaces); 22634 verifyFormat("A< A< int>>();", Spaces); 22635 22636 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22637 verifyFormat("// clang-format off\n" 22638 "foo<<<1, 1>>>();\n" 22639 "// clang-format on\n", 22640 Spaces); 22641 verifyFormat("// clang-format off\n" 22642 "foo< < <1, 1> > >();\n" 22643 "// clang-format on\n", 22644 Spaces); 22645 } 22646 22647 TEST_F(FormatTest, SpaceAfterTemplateKeyword) { 22648 FormatStyle Style = getLLVMStyle(); 22649 Style.SpaceAfterTemplateKeyword = false; 22650 verifyFormat("template<int> void foo();", Style); 22651 } 22652 22653 TEST_F(FormatTest, TripleAngleBrackets) { 22654 verifyFormat("f<<<1, 1>>>();"); 22655 verifyFormat("f<<<1, 1, 1, s>>>();"); 22656 verifyFormat("f<<<a, b, c, d>>>();"); 22657 EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();")); 22658 verifyFormat("f<param><<<1, 1>>>();"); 22659 verifyFormat("f<1><<<1, 1>>>();"); 22660 EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();")); 22661 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 22662 "aaaaaaaaaaa<<<\n 1, 1>>>();"); 22663 verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n" 22664 " <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();"); 22665 } 22666 22667 TEST_F(FormatTest, MergeLessLessAtEnd) { 22668 verifyFormat("<<"); 22669 EXPECT_EQ("< < <", format("\\\n<<<")); 22670 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 22671 "aaallvm::outs() <<"); 22672 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 22673 "aaaallvm::outs()\n <<"); 22674 } 22675 22676 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) { 22677 std::string code = "#if A\n" 22678 "#if B\n" 22679 "a.\n" 22680 "#endif\n" 22681 " a = 1;\n" 22682 "#else\n" 22683 "#endif\n" 22684 "#if C\n" 22685 "#else\n" 22686 "#endif\n"; 22687 EXPECT_EQ(code, format(code)); 22688 } 22689 22690 TEST_F(FormatTest, HandleConflictMarkers) { 22691 // Git/SVN conflict markers. 22692 EXPECT_EQ("int a;\n" 22693 "void f() {\n" 22694 " callme(some(parameter1,\n" 22695 "<<<<<<< text by the vcs\n" 22696 " parameter2),\n" 22697 "||||||| text by the vcs\n" 22698 " parameter2),\n" 22699 " parameter3,\n" 22700 "======= text by the vcs\n" 22701 " parameter2, parameter3),\n" 22702 ">>>>>>> text by the vcs\n" 22703 " otherparameter);\n", 22704 format("int a;\n" 22705 "void f() {\n" 22706 " callme(some(parameter1,\n" 22707 "<<<<<<< text by the vcs\n" 22708 " parameter2),\n" 22709 "||||||| text by the vcs\n" 22710 " parameter2),\n" 22711 " parameter3,\n" 22712 "======= text by the vcs\n" 22713 " parameter2,\n" 22714 " parameter3),\n" 22715 ">>>>>>> text by the vcs\n" 22716 " otherparameter);\n")); 22717 22718 // Perforce markers. 22719 EXPECT_EQ("void f() {\n" 22720 " function(\n" 22721 ">>>> text by the vcs\n" 22722 " parameter,\n" 22723 "==== text by the vcs\n" 22724 " parameter,\n" 22725 "==== text by the vcs\n" 22726 " parameter,\n" 22727 "<<<< text by the vcs\n" 22728 " parameter);\n", 22729 format("void f() {\n" 22730 " function(\n" 22731 ">>>> text by the vcs\n" 22732 " parameter,\n" 22733 "==== text by the vcs\n" 22734 " parameter,\n" 22735 "==== text by the vcs\n" 22736 " parameter,\n" 22737 "<<<< text by the vcs\n" 22738 " parameter);\n")); 22739 22740 EXPECT_EQ("<<<<<<<\n" 22741 "|||||||\n" 22742 "=======\n" 22743 ">>>>>>>", 22744 format("<<<<<<<\n" 22745 "|||||||\n" 22746 "=======\n" 22747 ">>>>>>>")); 22748 22749 EXPECT_EQ("<<<<<<<\n" 22750 "|||||||\n" 22751 "int i;\n" 22752 "=======\n" 22753 ">>>>>>>", 22754 format("<<<<<<<\n" 22755 "|||||||\n" 22756 "int i;\n" 22757 "=======\n" 22758 ">>>>>>>")); 22759 22760 // FIXME: Handle parsing of macros around conflict markers correctly: 22761 EXPECT_EQ("#define Macro \\\n" 22762 "<<<<<<<\n" 22763 "Something \\\n" 22764 "|||||||\n" 22765 "Else \\\n" 22766 "=======\n" 22767 "Other \\\n" 22768 ">>>>>>>\n" 22769 " End int i;\n", 22770 format("#define Macro \\\n" 22771 "<<<<<<<\n" 22772 " Something \\\n" 22773 "|||||||\n" 22774 " Else \\\n" 22775 "=======\n" 22776 " Other \\\n" 22777 ">>>>>>>\n" 22778 " End\n" 22779 "int i;\n")); 22780 22781 verifyFormat(R"(==== 22782 #ifdef A 22783 a 22784 #else 22785 b 22786 #endif 22787 )"); 22788 } 22789 22790 TEST_F(FormatTest, DisableRegions) { 22791 EXPECT_EQ("int i;\n" 22792 "// clang-format off\n" 22793 " int j;\n" 22794 "// clang-format on\n" 22795 "int k;", 22796 format(" int i;\n" 22797 " // clang-format off\n" 22798 " int j;\n" 22799 " // clang-format on\n" 22800 " int k;")); 22801 EXPECT_EQ("int i;\n" 22802 "/* clang-format off */\n" 22803 " int j;\n" 22804 "/* clang-format on */\n" 22805 "int k;", 22806 format(" int i;\n" 22807 " /* clang-format off */\n" 22808 " int j;\n" 22809 " /* clang-format on */\n" 22810 " int k;")); 22811 22812 // Don't reflow comments within disabled regions. 22813 EXPECT_EQ("// clang-format off\n" 22814 "// long long long long long long line\n" 22815 "/* clang-format on */\n" 22816 "/* long long long\n" 22817 " * long long long\n" 22818 " * line */\n" 22819 "int i;\n" 22820 "/* clang-format off */\n" 22821 "/* long long long long long long line */\n", 22822 format("// clang-format off\n" 22823 "// long long long long long long line\n" 22824 "/* clang-format on */\n" 22825 "/* long long long long long long line */\n" 22826 "int i;\n" 22827 "/* clang-format off */\n" 22828 "/* long long long long long long line */\n", 22829 getLLVMStyleWithColumns(20))); 22830 } 22831 22832 TEST_F(FormatTest, DoNotCrashOnInvalidInput) { 22833 format("? ) ="); 22834 verifyNoCrash("#define a\\\n /**/}"); 22835 } 22836 22837 TEST_F(FormatTest, FormatsTableGenCode) { 22838 FormatStyle Style = getLLVMStyle(); 22839 Style.Language = FormatStyle::LK_TableGen; 22840 verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style); 22841 } 22842 22843 TEST_F(FormatTest, ArrayOfTemplates) { 22844 EXPECT_EQ("auto a = new unique_ptr<int>[10];", 22845 format("auto a = new unique_ptr<int > [ 10];")); 22846 22847 FormatStyle Spaces = getLLVMStyle(); 22848 Spaces.SpacesInSquareBrackets = true; 22849 EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];", 22850 format("auto a = new unique_ptr<int > [10];", Spaces)); 22851 } 22852 22853 TEST_F(FormatTest, ArrayAsTemplateType) { 22854 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;", 22855 format("auto a = unique_ptr < Foo < Bar>[ 10]> ;")); 22856 22857 FormatStyle Spaces = getLLVMStyle(); 22858 Spaces.SpacesInSquareBrackets = true; 22859 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;", 22860 format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces)); 22861 } 22862 22863 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); } 22864 22865 TEST(FormatStyle, GetStyleWithEmptyFileName) { 22866 llvm::vfs::InMemoryFileSystem FS; 22867 auto Style1 = getStyle("file", "", "Google", "", &FS); 22868 ASSERT_TRUE((bool)Style1); 22869 ASSERT_EQ(*Style1, getGoogleStyle()); 22870 } 22871 22872 TEST(FormatStyle, GetStyleOfFile) { 22873 llvm::vfs::InMemoryFileSystem FS; 22874 // Test 1: format file in the same directory. 22875 ASSERT_TRUE( 22876 FS.addFile("/a/.clang-format", 0, 22877 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM"))); 22878 ASSERT_TRUE( 22879 FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22880 auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS); 22881 ASSERT_TRUE((bool)Style1); 22882 ASSERT_EQ(*Style1, getLLVMStyle()); 22883 22884 // Test 2.1: fallback to default. 22885 ASSERT_TRUE( 22886 FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22887 auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS); 22888 ASSERT_TRUE((bool)Style2); 22889 ASSERT_EQ(*Style2, getMozillaStyle()); 22890 22891 // Test 2.2: no format on 'none' fallback style. 22892 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS); 22893 ASSERT_TRUE((bool)Style2); 22894 ASSERT_EQ(*Style2, getNoStyle()); 22895 22896 // Test 2.3: format if config is found with no based style while fallback is 22897 // 'none'. 22898 ASSERT_TRUE(FS.addFile("/b/.clang-format", 0, 22899 llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2"))); 22900 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS); 22901 ASSERT_TRUE((bool)Style2); 22902 ASSERT_EQ(*Style2, getLLVMStyle()); 22903 22904 // Test 2.4: format if yaml with no based style, while fallback is 'none'. 22905 Style2 = getStyle("{}", "a.h", "none", "", &FS); 22906 ASSERT_TRUE((bool)Style2); 22907 ASSERT_EQ(*Style2, getLLVMStyle()); 22908 22909 // Test 3: format file in parent directory. 22910 ASSERT_TRUE( 22911 FS.addFile("/c/.clang-format", 0, 22912 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 22913 ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0, 22914 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22915 auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS); 22916 ASSERT_TRUE((bool)Style3); 22917 ASSERT_EQ(*Style3, getGoogleStyle()); 22918 22919 // Test 4: error on invalid fallback style 22920 auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS); 22921 ASSERT_FALSE((bool)Style4); 22922 llvm::consumeError(Style4.takeError()); 22923 22924 // Test 5: error on invalid yaml on command line 22925 auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS); 22926 ASSERT_FALSE((bool)Style5); 22927 llvm::consumeError(Style5.takeError()); 22928 22929 // Test 6: error on invalid style 22930 auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS); 22931 ASSERT_FALSE((bool)Style6); 22932 llvm::consumeError(Style6.takeError()); 22933 22934 // Test 7: found config file, error on parsing it 22935 ASSERT_TRUE( 22936 FS.addFile("/d/.clang-format", 0, 22937 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n" 22938 "InvalidKey: InvalidValue"))); 22939 ASSERT_TRUE( 22940 FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22941 auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS); 22942 ASSERT_FALSE((bool)Style7a); 22943 llvm::consumeError(Style7a.takeError()); 22944 22945 auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true); 22946 ASSERT_TRUE((bool)Style7b); 22947 22948 // Test 8: inferred per-language defaults apply. 22949 auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS); 22950 ASSERT_TRUE((bool)StyleTd); 22951 ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen)); 22952 22953 // Test 9.1.1: overwriting a file style, when no parent file exists with no 22954 // fallback style. 22955 ASSERT_TRUE(FS.addFile( 22956 "/e/sub/.clang-format", 0, 22957 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n" 22958 "ColumnLimit: 20"))); 22959 ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0, 22960 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22961 auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS); 22962 ASSERT_TRUE(static_cast<bool>(Style9)); 22963 ASSERT_EQ(*Style9, [] { 22964 auto Style = getNoStyle(); 22965 Style.ColumnLimit = 20; 22966 return Style; 22967 }()); 22968 22969 // Test 9.1.2: propagate more than one level with no parent file. 22970 ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0, 22971 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22972 ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0, 22973 llvm::MemoryBuffer::getMemBuffer( 22974 "BasedOnStyle: InheritParentConfig\n" 22975 "WhitespaceSensitiveMacros: ['FOO', 'BAR']"))); 22976 std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"}; 22977 22978 ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros); 22979 Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS); 22980 ASSERT_TRUE(static_cast<bool>(Style9)); 22981 ASSERT_EQ(*Style9, [&NonDefaultWhiteSpaceMacros] { 22982 auto Style = getNoStyle(); 22983 Style.ColumnLimit = 20; 22984 Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros; 22985 return Style; 22986 }()); 22987 22988 // Test 9.2: with LLVM fallback style 22989 Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS); 22990 ASSERT_TRUE(static_cast<bool>(Style9)); 22991 ASSERT_EQ(*Style9, [] { 22992 auto Style = getLLVMStyle(); 22993 Style.ColumnLimit = 20; 22994 return Style; 22995 }()); 22996 22997 // Test 9.3: with a parent file 22998 ASSERT_TRUE( 22999 FS.addFile("/e/.clang-format", 0, 23000 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n" 23001 "UseTab: Always"))); 23002 Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS); 23003 ASSERT_TRUE(static_cast<bool>(Style9)); 23004 ASSERT_EQ(*Style9, [] { 23005 auto Style = getGoogleStyle(); 23006 Style.ColumnLimit = 20; 23007 Style.UseTab = FormatStyle::UT_Always; 23008 return Style; 23009 }()); 23010 23011 // Test 9.4: propagate more than one level with a parent file. 23012 const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] { 23013 auto Style = getGoogleStyle(); 23014 Style.ColumnLimit = 20; 23015 Style.UseTab = FormatStyle::UT_Always; 23016 Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros; 23017 return Style; 23018 }(); 23019 23020 ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros); 23021 Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS); 23022 ASSERT_TRUE(static_cast<bool>(Style9)); 23023 ASSERT_EQ(*Style9, SubSubStyle); 23024 23025 // Test 9.5: use InheritParentConfig as style name 23026 Style9 = 23027 getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS); 23028 ASSERT_TRUE(static_cast<bool>(Style9)); 23029 ASSERT_EQ(*Style9, SubSubStyle); 23030 23031 // Test 9.6: use command line style with inheritance 23032 Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp", 23033 "none", "", &FS); 23034 ASSERT_TRUE(static_cast<bool>(Style9)); 23035 ASSERT_EQ(*Style9, SubSubStyle); 23036 23037 // Test 9.7: use command line style with inheritance and own config 23038 Style9 = getStyle("{BasedOnStyle: InheritParentConfig, " 23039 "WhitespaceSensitiveMacros: ['FOO', 'BAR']}", 23040 "/e/sub/code.cpp", "none", "", &FS); 23041 ASSERT_TRUE(static_cast<bool>(Style9)); 23042 ASSERT_EQ(*Style9, SubSubStyle); 23043 23044 // Test 9.8: use inheritance from a file without BasedOnStyle 23045 ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0, 23046 llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123"))); 23047 ASSERT_TRUE( 23048 FS.addFile("/e/withoutbase/sub/.clang-format", 0, 23049 llvm::MemoryBuffer::getMemBuffer( 23050 "BasedOnStyle: InheritParentConfig\nIndentWidth: 7"))); 23051 // Make sure we do not use the fallback style 23052 Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS); 23053 ASSERT_TRUE(static_cast<bool>(Style9)); 23054 ASSERT_EQ(*Style9, [] { 23055 auto Style = getLLVMStyle(); 23056 Style.ColumnLimit = 123; 23057 return Style; 23058 }()); 23059 23060 Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS); 23061 ASSERT_TRUE(static_cast<bool>(Style9)); 23062 ASSERT_EQ(*Style9, [] { 23063 auto Style = getLLVMStyle(); 23064 Style.ColumnLimit = 123; 23065 Style.IndentWidth = 7; 23066 return Style; 23067 }()); 23068 23069 // Test 9.9: use inheritance from a specific config file. 23070 Style9 = getStyle("file:/e/sub/sub/.clang-format", "/e/sub/sub/code.cpp", 23071 "none", "", &FS); 23072 ASSERT_TRUE(static_cast<bool>(Style9)); 23073 ASSERT_EQ(*Style9, SubSubStyle); 23074 } 23075 23076 TEST(FormatStyle, GetStyleOfSpecificFile) { 23077 llvm::vfs::InMemoryFileSystem FS; 23078 // Specify absolute path to a format file in a parent directory. 23079 ASSERT_TRUE( 23080 FS.addFile("/e/.clang-format", 0, 23081 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM"))); 23082 ASSERT_TRUE( 23083 FS.addFile("/e/explicit.clang-format", 0, 23084 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 23085 ASSERT_TRUE(FS.addFile("/e/sub/sub/sub/test.cpp", 0, 23086 llvm::MemoryBuffer::getMemBuffer("int i;"))); 23087 auto Style = getStyle("file:/e/explicit.clang-format", 23088 "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS); 23089 ASSERT_TRUE(static_cast<bool>(Style)); 23090 ASSERT_EQ(*Style, getGoogleStyle()); 23091 23092 // Specify relative path to a format file. 23093 ASSERT_TRUE( 23094 FS.addFile("../../e/explicit.clang-format", 0, 23095 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 23096 Style = getStyle("file:../../e/explicit.clang-format", 23097 "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS); 23098 ASSERT_TRUE(static_cast<bool>(Style)); 23099 ASSERT_EQ(*Style, getGoogleStyle()); 23100 23101 // Specify path to a format file that does not exist. 23102 Style = getStyle("file:/e/missing.clang-format", "/e/sub/sub/sub/test.cpp", 23103 "LLVM", "", &FS); 23104 ASSERT_FALSE(static_cast<bool>(Style)); 23105 llvm::consumeError(Style.takeError()); 23106 23107 // Specify path to a file on the filesystem. 23108 SmallString<128> FormatFilePath; 23109 std::error_code ECF = llvm::sys::fs::createTemporaryFile( 23110 "FormatFileTest", "tpl", FormatFilePath); 23111 EXPECT_FALSE((bool)ECF); 23112 llvm::raw_fd_ostream FormatFileTest(FormatFilePath, ECF); 23113 EXPECT_FALSE((bool)ECF); 23114 FormatFileTest << "BasedOnStyle: Google\n"; 23115 FormatFileTest.close(); 23116 23117 SmallString<128> TestFilePath; 23118 std::error_code ECT = 23119 llvm::sys::fs::createTemporaryFile("CodeFileTest", "cc", TestFilePath); 23120 EXPECT_FALSE((bool)ECT); 23121 llvm::raw_fd_ostream CodeFileTest(TestFilePath, ECT); 23122 CodeFileTest << "int i;\n"; 23123 CodeFileTest.close(); 23124 23125 std::string format_file_arg = std::string("file:") + FormatFilePath.c_str(); 23126 Style = getStyle(format_file_arg, TestFilePath, "LLVM", "", nullptr); 23127 23128 llvm::sys::fs::remove(FormatFilePath.c_str()); 23129 llvm::sys::fs::remove(TestFilePath.c_str()); 23130 ASSERT_TRUE(static_cast<bool>(Style)); 23131 ASSERT_EQ(*Style, getGoogleStyle()); 23132 } 23133 23134 TEST_F(ReplacementTest, FormatCodeAfterReplacements) { 23135 // Column limit is 20. 23136 std::string Code = "Type *a =\n" 23137 " new Type();\n" 23138 "g(iiiii, 0, jjjjj,\n" 23139 " 0, kkkkk, 0, mm);\n" 23140 "int bad = format ;"; 23141 std::string Expected = "auto a = new Type();\n" 23142 "g(iiiii, nullptr,\n" 23143 " jjjjj, nullptr,\n" 23144 " kkkkk, nullptr,\n" 23145 " mm);\n" 23146 "int bad = format ;"; 23147 FileID ID = Context.createInMemoryFile("format.cpp", Code); 23148 tooling::Replacements Replaces = toReplacements( 23149 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6, 23150 "auto "), 23151 tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1, 23152 "nullptr"), 23153 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1, 23154 "nullptr"), 23155 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1, 23156 "nullptr")}); 23157 23158 FormatStyle Style = getLLVMStyle(); 23159 Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility. 23160 auto FormattedReplaces = formatReplacements(Code, Replaces, Style); 23161 EXPECT_TRUE(static_cast<bool>(FormattedReplaces)) 23162 << llvm::toString(FormattedReplaces.takeError()) << "\n"; 23163 auto Result = applyAllReplacements(Code, *FormattedReplaces); 23164 EXPECT_TRUE(static_cast<bool>(Result)); 23165 EXPECT_EQ(Expected, *Result); 23166 } 23167 23168 TEST_F(ReplacementTest, SortIncludesAfterReplacement) { 23169 std::string Code = "#include \"a.h\"\n" 23170 "#include \"c.h\"\n" 23171 "\n" 23172 "int main() {\n" 23173 " return 0;\n" 23174 "}"; 23175 std::string Expected = "#include \"a.h\"\n" 23176 "#include \"b.h\"\n" 23177 "#include \"c.h\"\n" 23178 "\n" 23179 "int main() {\n" 23180 " return 0;\n" 23181 "}"; 23182 FileID ID = Context.createInMemoryFile("fix.cpp", Code); 23183 tooling::Replacements Replaces = toReplacements( 23184 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0, 23185 "#include \"b.h\"\n")}); 23186 23187 FormatStyle Style = getLLVMStyle(); 23188 Style.SortIncludes = FormatStyle::SI_CaseSensitive; 23189 auto FormattedReplaces = formatReplacements(Code, Replaces, Style); 23190 EXPECT_TRUE(static_cast<bool>(FormattedReplaces)) 23191 << llvm::toString(FormattedReplaces.takeError()) << "\n"; 23192 auto Result = applyAllReplacements(Code, *FormattedReplaces); 23193 EXPECT_TRUE(static_cast<bool>(Result)); 23194 EXPECT_EQ(Expected, *Result); 23195 } 23196 23197 TEST_F(FormatTest, FormatSortsUsingDeclarations) { 23198 EXPECT_EQ("using std::cin;\n" 23199 "using std::cout;", 23200 format("using std::cout;\n" 23201 "using std::cin;", 23202 getGoogleStyle())); 23203 } 23204 23205 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) { 23206 FormatStyle Style = getLLVMStyle(); 23207 Style.Standard = FormatStyle::LS_Cpp03; 23208 // cpp03 recognize this string as identifier u8 and literal character 'a' 23209 EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style)); 23210 } 23211 23212 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) { 23213 // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers 23214 // all modes, including C++11, C++14 and C++17 23215 EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';")); 23216 } 23217 23218 TEST_F(FormatTest, DoNotFormatLikelyXml) { 23219 EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle())); 23220 EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle())); 23221 } 23222 23223 TEST_F(FormatTest, StructuredBindings) { 23224 // Structured bindings is a C++17 feature. 23225 // all modes, including C++11, C++14 and C++17 23226 verifyFormat("auto [a, b] = f();"); 23227 EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();")); 23228 EXPECT_EQ("const auto [a, b] = f();", format("const auto[a, b] = f();")); 23229 EXPECT_EQ("auto const [a, b] = f();", format("auto const[a, b] = f();")); 23230 EXPECT_EQ("auto const volatile [a, b] = f();", 23231 format("auto const volatile[a, b] = f();")); 23232 EXPECT_EQ("auto [a, b, c] = f();", format("auto [ a , b,c ] = f();")); 23233 EXPECT_EQ("auto &[a, b, c] = f();", 23234 format("auto &[ a , b,c ] = f();")); 23235 EXPECT_EQ("auto &&[a, b, c] = f();", 23236 format("auto &&[ a , b,c ] = f();")); 23237 EXPECT_EQ("auto const &[a, b] = f();", format("auto const&[a, b] = f();")); 23238 EXPECT_EQ("auto const volatile &&[a, b] = f();", 23239 format("auto const volatile &&[a, b] = f();")); 23240 EXPECT_EQ("auto const &&[a, b] = f();", 23241 format("auto const && [a, b] = f();")); 23242 EXPECT_EQ("const auto &[a, b] = f();", 23243 format("const auto & [a, b] = f();")); 23244 EXPECT_EQ("const auto volatile &&[a, b] = f();", 23245 format("const auto volatile &&[a, b] = f();")); 23246 EXPECT_EQ("volatile const auto &&[a, b] = f();", 23247 format("volatile const auto &&[a, b] = f();")); 23248 EXPECT_EQ("const auto &&[a, b] = f();", 23249 format("const auto && [a, b] = f();")); 23250 23251 // Make sure we don't mistake structured bindings for lambdas. 23252 FormatStyle PointerMiddle = getLLVMStyle(); 23253 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle; 23254 verifyFormat("auto [a1, b]{A * i};", getGoogleStyle()); 23255 verifyFormat("auto [a2, b]{A * i};", getLLVMStyle()); 23256 verifyFormat("auto [a3, b]{A * i};", PointerMiddle); 23257 verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle()); 23258 verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle()); 23259 verifyFormat("auto const [a3, b]{A * i};", PointerMiddle); 23260 verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle()); 23261 verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle()); 23262 verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle); 23263 verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle()); 23264 verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle()); 23265 verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle); 23266 23267 EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}", 23268 format("for (const auto && [a, b] : some_range) {\n}")); 23269 EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}", 23270 format("for (const auto & [a, b] : some_range) {\n}")); 23271 EXPECT_EQ("for (const auto [a, b] : some_range) {\n}", 23272 format("for (const auto[a, b] : some_range) {\n}")); 23273 EXPECT_EQ("auto [x, y](expr);", format("auto[x,y] (expr);")); 23274 EXPECT_EQ("auto &[x, y](expr);", format("auto & [x,y] (expr);")); 23275 EXPECT_EQ("auto &&[x, y](expr);", format("auto && [x,y] (expr);")); 23276 EXPECT_EQ("auto const &[x, y](expr);", 23277 format("auto const & [x,y] (expr);")); 23278 EXPECT_EQ("auto const &&[x, y](expr);", 23279 format("auto const && [x,y] (expr);")); 23280 EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y] {expr};")); 23281 EXPECT_EQ("auto const &[x, y]{expr};", 23282 format("auto const & [x,y] {expr};")); 23283 EXPECT_EQ("auto const &&[x, y]{expr};", 23284 format("auto const && [x,y] {expr};")); 23285 23286 FormatStyle Spaces = getLLVMStyle(); 23287 Spaces.SpacesInSquareBrackets = true; 23288 verifyFormat("auto [ a, b ] = f();", Spaces); 23289 verifyFormat("auto &&[ a, b ] = f();", Spaces); 23290 verifyFormat("auto &[ a, b ] = f();", Spaces); 23291 verifyFormat("auto const &&[ a, b ] = f();", Spaces); 23292 verifyFormat("auto const &[ a, b ] = f();", Spaces); 23293 } 23294 23295 TEST_F(FormatTest, FileAndCode) { 23296 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", "")); 23297 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", "")); 23298 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", "")); 23299 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "")); 23300 EXPECT_EQ(FormatStyle::LK_ObjC, 23301 guessLanguage("foo.h", "@interface Foo\n@end\n")); 23302 EXPECT_EQ( 23303 FormatStyle::LK_ObjC, 23304 guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }")); 23305 EXPECT_EQ(FormatStyle::LK_ObjC, 23306 guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))")); 23307 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;")); 23308 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", "")); 23309 EXPECT_EQ(FormatStyle::LK_ObjC, 23310 guessLanguage("foo", "@interface Foo\n@end\n")); 23311 EXPECT_EQ(FormatStyle::LK_ObjC, 23312 guessLanguage("foo.h", "int DoStuff(CGRect rect);\n")); 23313 EXPECT_EQ( 23314 FormatStyle::LK_ObjC, 23315 guessLanguage("foo.h", 23316 "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n")); 23317 EXPECT_EQ( 23318 FormatStyle::LK_Cpp, 23319 guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;")); 23320 // Only one of the two preprocessor regions has ObjC-like code. 23321 EXPECT_EQ(FormatStyle::LK_ObjC, 23322 guessLanguage("foo.h", "#if A\n" 23323 "#define B() C\n" 23324 "#else\n" 23325 "#define B() [NSString a:@\"\"]\n" 23326 "#endif\n")); 23327 } 23328 23329 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) { 23330 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];")); 23331 EXPECT_EQ(FormatStyle::LK_ObjC, 23332 guessLanguage("foo.h", "array[[calculator getIndex]];")); 23333 EXPECT_EQ(FormatStyle::LK_Cpp, 23334 guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];")); 23335 EXPECT_EQ( 23336 FormatStyle::LK_Cpp, 23337 guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];")); 23338 EXPECT_EQ(FormatStyle::LK_ObjC, 23339 guessLanguage("foo.h", "[[noreturn foo] bar];")); 23340 EXPECT_EQ(FormatStyle::LK_Cpp, 23341 guessLanguage("foo.h", "[[clang::fallthrough]];")); 23342 EXPECT_EQ(FormatStyle::LK_ObjC, 23343 guessLanguage("foo.h", "[[clang:fallthrough] foo];")); 23344 EXPECT_EQ(FormatStyle::LK_Cpp, 23345 guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];")); 23346 EXPECT_EQ(FormatStyle::LK_Cpp, 23347 guessLanguage("foo.h", "[[using clang: fallthrough]];")); 23348 EXPECT_EQ(FormatStyle::LK_ObjC, 23349 guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];")); 23350 EXPECT_EQ(FormatStyle::LK_Cpp, 23351 guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];")); 23352 EXPECT_EQ( 23353 FormatStyle::LK_Cpp, 23354 guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)")); 23355 EXPECT_EQ( 23356 FormatStyle::LK_Cpp, 23357 guessLanguage("foo.h", 23358 "[[clang::callable_when(\"unconsumed\", \"unknown\")]]")); 23359 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]")); 23360 } 23361 23362 TEST_F(FormatTest, GuessLanguageWithCaret) { 23363 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);")); 23364 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);")); 23365 EXPECT_EQ(FormatStyle::LK_ObjC, 23366 guessLanguage("foo.h", "int(^)(char, float);")); 23367 EXPECT_EQ(FormatStyle::LK_ObjC, 23368 guessLanguage("foo.h", "int(^foo)(char, float);")); 23369 EXPECT_EQ(FormatStyle::LK_ObjC, 23370 guessLanguage("foo.h", "int(^foo[10])(char, float);")); 23371 EXPECT_EQ(FormatStyle::LK_ObjC, 23372 guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);")); 23373 EXPECT_EQ( 23374 FormatStyle::LK_ObjC, 23375 guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);")); 23376 } 23377 23378 TEST_F(FormatTest, GuessLanguageWithPragmas) { 23379 EXPECT_EQ(FormatStyle::LK_Cpp, 23380 guessLanguage("foo.h", "__pragma(warning(disable:))")); 23381 EXPECT_EQ(FormatStyle::LK_Cpp, 23382 guessLanguage("foo.h", "#pragma(warning(disable:))")); 23383 EXPECT_EQ(FormatStyle::LK_Cpp, 23384 guessLanguage("foo.h", "_Pragma(warning(disable:))")); 23385 } 23386 23387 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) { 23388 // ASM symbolic names are identifiers that must be surrounded by [] without 23389 // space in between: 23390 // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands 23391 23392 // Example from https://bugs.llvm.org/show_bug.cgi?id=45108. 23393 verifyFormat(R"(// 23394 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result)); 23395 )"); 23396 23397 // A list of several ASM symbolic names. 23398 verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)"); 23399 23400 // ASM symbolic names in inline ASM with inputs and outputs. 23401 verifyFormat(R"(// 23402 asm("cmoveq %1, %2, %[result]" 23403 : [result] "=r"(result) 23404 : "r"(test), "r"(new), "[result]"(old)); 23405 )"); 23406 23407 // ASM symbolic names in inline ASM with no outputs. 23408 verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)"); 23409 } 23410 23411 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) { 23412 EXPECT_EQ(FormatStyle::LK_Cpp, 23413 guessLanguage("foo.h", "void f() {\n" 23414 " asm (\"mov %[e], %[d]\"\n" 23415 " : [d] \"=rm\" (d)\n" 23416 " [e] \"rm\" (*e));\n" 23417 "}")); 23418 EXPECT_EQ(FormatStyle::LK_Cpp, 23419 guessLanguage("foo.h", "void f() {\n" 23420 " _asm (\"mov %[e], %[d]\"\n" 23421 " : [d] \"=rm\" (d)\n" 23422 " [e] \"rm\" (*e));\n" 23423 "}")); 23424 EXPECT_EQ(FormatStyle::LK_Cpp, 23425 guessLanguage("foo.h", "void f() {\n" 23426 " __asm (\"mov %[e], %[d]\"\n" 23427 " : [d] \"=rm\" (d)\n" 23428 " [e] \"rm\" (*e));\n" 23429 "}")); 23430 EXPECT_EQ(FormatStyle::LK_Cpp, 23431 guessLanguage("foo.h", "void f() {\n" 23432 " __asm__ (\"mov %[e], %[d]\"\n" 23433 " : [d] \"=rm\" (d)\n" 23434 " [e] \"rm\" (*e));\n" 23435 "}")); 23436 EXPECT_EQ(FormatStyle::LK_Cpp, 23437 guessLanguage("foo.h", "void f() {\n" 23438 " asm (\"mov %[e], %[d]\"\n" 23439 " : [d] \"=rm\" (d),\n" 23440 " [e] \"rm\" (*e));\n" 23441 "}")); 23442 EXPECT_EQ(FormatStyle::LK_Cpp, 23443 guessLanguage("foo.h", "void f() {\n" 23444 " asm volatile (\"mov %[e], %[d]\"\n" 23445 " : [d] \"=rm\" (d)\n" 23446 " [e] \"rm\" (*e));\n" 23447 "}")); 23448 } 23449 23450 TEST_F(FormatTest, GuessLanguageWithChildLines) { 23451 EXPECT_EQ(FormatStyle::LK_Cpp, 23452 guessLanguage("foo.h", "#define FOO ({ std::string s; })")); 23453 EXPECT_EQ(FormatStyle::LK_ObjC, 23454 guessLanguage("foo.h", "#define FOO ({ NSString *s; })")); 23455 EXPECT_EQ( 23456 FormatStyle::LK_Cpp, 23457 guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })")); 23458 EXPECT_EQ( 23459 FormatStyle::LK_ObjC, 23460 guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })")); 23461 } 23462 23463 TEST_F(FormatTest, TypenameMacros) { 23464 std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"}; 23465 23466 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353 23467 FormatStyle Google = getGoogleStyleWithColumns(0); 23468 Google.TypenameMacros = TypenameMacros; 23469 verifyFormat("struct foo {\n" 23470 " int bar;\n" 23471 " TAILQ_ENTRY(a) bleh;\n" 23472 "};", 23473 Google); 23474 23475 FormatStyle Macros = getLLVMStyle(); 23476 Macros.TypenameMacros = TypenameMacros; 23477 23478 verifyFormat("STACK_OF(int) a;", Macros); 23479 verifyFormat("STACK_OF(int) *a;", Macros); 23480 verifyFormat("STACK_OF(int const *) *a;", Macros); 23481 verifyFormat("STACK_OF(int *const) *a;", Macros); 23482 verifyFormat("STACK_OF(int, string) a;", Macros); 23483 verifyFormat("STACK_OF(LIST(int)) a;", Macros); 23484 verifyFormat("STACK_OF(LIST(int)) a, b;", Macros); 23485 verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros); 23486 verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros); 23487 verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros); 23488 verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros); 23489 23490 Macros.PointerAlignment = FormatStyle::PAS_Left; 23491 verifyFormat("STACK_OF(int)* a;", Macros); 23492 verifyFormat("STACK_OF(int*)* a;", Macros); 23493 verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros); 23494 verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros); 23495 verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros); 23496 } 23497 23498 TEST_F(FormatTest, AtomicQualifier) { 23499 // Check that we treate _Atomic as a type and not a function call 23500 FormatStyle Google = getGoogleStyleWithColumns(0); 23501 verifyFormat("struct foo {\n" 23502 " int a1;\n" 23503 " _Atomic(a) a2;\n" 23504 " _Atomic(_Atomic(int) *const) a3;\n" 23505 "};", 23506 Google); 23507 verifyFormat("_Atomic(uint64_t) a;"); 23508 verifyFormat("_Atomic(uint64_t) *a;"); 23509 verifyFormat("_Atomic(uint64_t const *) *a;"); 23510 verifyFormat("_Atomic(uint64_t *const) *a;"); 23511 verifyFormat("_Atomic(const uint64_t *) *a;"); 23512 verifyFormat("_Atomic(uint64_t) a;"); 23513 verifyFormat("_Atomic(_Atomic(uint64_t)) a;"); 23514 verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;"); 23515 verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}"); 23516 verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);"); 23517 23518 verifyFormat("_Atomic(uint64_t) *s(InitValue);"); 23519 verifyFormat("_Atomic(uint64_t) *s{InitValue};"); 23520 FormatStyle Style = getLLVMStyle(); 23521 Style.PointerAlignment = FormatStyle::PAS_Left; 23522 verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style); 23523 verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style); 23524 verifyFormat("_Atomic(int)* a;", Style); 23525 verifyFormat("_Atomic(int*)* a;", Style); 23526 verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style); 23527 23528 Style.SpacesInCStyleCastParentheses = true; 23529 Style.SpacesInParentheses = false; 23530 verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style); 23531 Style.SpacesInCStyleCastParentheses = false; 23532 Style.SpacesInParentheses = true; 23533 verifyFormat("x = (_Atomic( uint64_t ))*a;", Style); 23534 verifyFormat("x = (_Atomic( uint64_t ))&a;", Style); 23535 } 23536 23537 TEST_F(FormatTest, AmbersandInLamda) { 23538 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899 23539 FormatStyle AlignStyle = getLLVMStyle(); 23540 AlignStyle.PointerAlignment = FormatStyle::PAS_Left; 23541 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle); 23542 AlignStyle.PointerAlignment = FormatStyle::PAS_Right; 23543 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle); 23544 } 23545 23546 TEST_F(FormatTest, SpacesInConditionalStatement) { 23547 FormatStyle Spaces = getLLVMStyle(); 23548 Spaces.IfMacros.clear(); 23549 Spaces.IfMacros.push_back("MYIF"); 23550 Spaces.SpacesInConditionalStatement = true; 23551 verifyFormat("for ( int i = 0; i; i++ )\n continue;", Spaces); 23552 verifyFormat("if ( !a )\n return;", Spaces); 23553 verifyFormat("if ( a )\n return;", Spaces); 23554 verifyFormat("if constexpr ( a )\n return;", Spaces); 23555 verifyFormat("MYIF ( a )\n return;", Spaces); 23556 verifyFormat("MYIF ( a )\n return;\nelse MYIF ( b )\n return;", Spaces); 23557 verifyFormat("MYIF ( a )\n return;\nelse\n return;", Spaces); 23558 verifyFormat("switch ( a )\ncase 1:\n return;", Spaces); 23559 verifyFormat("while ( a )\n return;", Spaces); 23560 verifyFormat("while ( (a && b) )\n return;", Spaces); 23561 verifyFormat("do {\n} while ( 1 != 0 );", Spaces); 23562 verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces); 23563 // Check that space on the left of "::" is inserted as expected at beginning 23564 // of condition. 23565 verifyFormat("while ( ::func() )\n return;", Spaces); 23566 23567 // Check impact of ControlStatementsExceptControlMacros is honored. 23568 Spaces.SpaceBeforeParens = 23569 FormatStyle::SBPO_ControlStatementsExceptControlMacros; 23570 verifyFormat("MYIF( a )\n return;", Spaces); 23571 verifyFormat("MYIF( a )\n return;\nelse MYIF( b )\n return;", Spaces); 23572 verifyFormat("MYIF( a )\n return;\nelse\n return;", Spaces); 23573 } 23574 23575 TEST_F(FormatTest, AlternativeOperators) { 23576 // Test case for ensuring alternate operators are not 23577 // combined with their right most neighbour. 23578 verifyFormat("int a and b;"); 23579 verifyFormat("int a and_eq b;"); 23580 verifyFormat("int a bitand b;"); 23581 verifyFormat("int a bitor b;"); 23582 verifyFormat("int a compl b;"); 23583 verifyFormat("int a not b;"); 23584 verifyFormat("int a not_eq b;"); 23585 verifyFormat("int a or b;"); 23586 verifyFormat("int a xor b;"); 23587 verifyFormat("int a xor_eq b;"); 23588 verifyFormat("return this not_eq bitand other;"); 23589 verifyFormat("bool operator not_eq(const X bitand other)"); 23590 23591 verifyFormat("int a and 5;"); 23592 verifyFormat("int a and_eq 5;"); 23593 verifyFormat("int a bitand 5;"); 23594 verifyFormat("int a bitor 5;"); 23595 verifyFormat("int a compl 5;"); 23596 verifyFormat("int a not 5;"); 23597 verifyFormat("int a not_eq 5;"); 23598 verifyFormat("int a or 5;"); 23599 verifyFormat("int a xor 5;"); 23600 verifyFormat("int a xor_eq 5;"); 23601 23602 verifyFormat("int a compl(5);"); 23603 verifyFormat("int a not(5);"); 23604 23605 /* FIXME handle alternate tokens 23606 * https://en.cppreference.com/w/cpp/language/operator_alternative 23607 // alternative tokens 23608 verifyFormat("compl foo();"); // ~foo(); 23609 verifyFormat("foo() <%%>;"); // foo(); 23610 verifyFormat("void foo() <%%>;"); // void foo(){} 23611 verifyFormat("int a <:1:>;"); // int a[1];[ 23612 verifyFormat("%:define ABC abc"); // #define ABC abc 23613 verifyFormat("%:%:"); // ## 23614 */ 23615 } 23616 23617 TEST_F(FormatTest, STLWhileNotDefineChed) { 23618 verifyFormat("#if defined(while)\n" 23619 "#define while EMIT WARNING C4005\n" 23620 "#endif // while"); 23621 } 23622 23623 TEST_F(FormatTest, OperatorSpacing) { 23624 FormatStyle Style = getLLVMStyle(); 23625 Style.PointerAlignment = FormatStyle::PAS_Right; 23626 verifyFormat("Foo::operator*();", Style); 23627 verifyFormat("Foo::operator void *();", Style); 23628 verifyFormat("Foo::operator void **();", Style); 23629 verifyFormat("Foo::operator void *&();", Style); 23630 verifyFormat("Foo::operator void *&&();", Style); 23631 verifyFormat("Foo::operator void const *();", Style); 23632 verifyFormat("Foo::operator void const **();", Style); 23633 verifyFormat("Foo::operator void const *&();", Style); 23634 verifyFormat("Foo::operator void const *&&();", Style); 23635 verifyFormat("Foo::operator()(void *);", Style); 23636 verifyFormat("Foo::operator*(void *);", Style); 23637 verifyFormat("Foo::operator*();", Style); 23638 verifyFormat("Foo::operator**();", Style); 23639 verifyFormat("Foo::operator&();", Style); 23640 verifyFormat("Foo::operator<int> *();", Style); 23641 verifyFormat("Foo::operator<Foo> *();", Style); 23642 verifyFormat("Foo::operator<int> **();", Style); 23643 verifyFormat("Foo::operator<Foo> **();", Style); 23644 verifyFormat("Foo::operator<int> &();", Style); 23645 verifyFormat("Foo::operator<Foo> &();", Style); 23646 verifyFormat("Foo::operator<int> &&();", Style); 23647 verifyFormat("Foo::operator<Foo> &&();", Style); 23648 verifyFormat("Foo::operator<int> *&();", Style); 23649 verifyFormat("Foo::operator<Foo> *&();", Style); 23650 verifyFormat("Foo::operator<int> *&&();", Style); 23651 verifyFormat("Foo::operator<Foo> *&&();", Style); 23652 verifyFormat("operator*(int (*)(), class Foo);", Style); 23653 23654 verifyFormat("Foo::operator&();", Style); 23655 verifyFormat("Foo::operator void &();", Style); 23656 verifyFormat("Foo::operator void const &();", Style); 23657 verifyFormat("Foo::operator()(void &);", Style); 23658 verifyFormat("Foo::operator&(void &);", Style); 23659 verifyFormat("Foo::operator&();", Style); 23660 verifyFormat("operator&(int (&)(), class Foo);", Style); 23661 verifyFormat("operator&&(int (&)(), class Foo);", Style); 23662 23663 verifyFormat("Foo::operator&&();", Style); 23664 verifyFormat("Foo::operator**();", Style); 23665 verifyFormat("Foo::operator void &&();", Style); 23666 verifyFormat("Foo::operator void const &&();", Style); 23667 verifyFormat("Foo::operator()(void &&);", Style); 23668 verifyFormat("Foo::operator&&(void &&);", Style); 23669 verifyFormat("Foo::operator&&();", Style); 23670 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23671 verifyFormat("operator const nsTArrayRight<E> &()", Style); 23672 verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()", 23673 Style); 23674 verifyFormat("operator void **()", Style); 23675 verifyFormat("operator const FooRight<Object> &()", Style); 23676 verifyFormat("operator const FooRight<Object> *()", Style); 23677 verifyFormat("operator const FooRight<Object> **()", Style); 23678 verifyFormat("operator const FooRight<Object> *&()", Style); 23679 verifyFormat("operator const FooRight<Object> *&&()", Style); 23680 23681 Style.PointerAlignment = FormatStyle::PAS_Left; 23682 verifyFormat("Foo::operator*();", Style); 23683 verifyFormat("Foo::operator**();", Style); 23684 verifyFormat("Foo::operator void*();", Style); 23685 verifyFormat("Foo::operator void**();", Style); 23686 verifyFormat("Foo::operator void*&();", Style); 23687 verifyFormat("Foo::operator void*&&();", Style); 23688 verifyFormat("Foo::operator void const*();", Style); 23689 verifyFormat("Foo::operator void const**();", Style); 23690 verifyFormat("Foo::operator void const*&();", Style); 23691 verifyFormat("Foo::operator void const*&&();", Style); 23692 verifyFormat("Foo::operator/*comment*/ void*();", Style); 23693 verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style); 23694 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style); 23695 verifyFormat("Foo::operator()(void*);", Style); 23696 verifyFormat("Foo::operator*(void*);", Style); 23697 verifyFormat("Foo::operator*();", Style); 23698 verifyFormat("Foo::operator<int>*();", Style); 23699 verifyFormat("Foo::operator<Foo>*();", Style); 23700 verifyFormat("Foo::operator<int>**();", Style); 23701 verifyFormat("Foo::operator<Foo>**();", Style); 23702 verifyFormat("Foo::operator<Foo>*&();", Style); 23703 verifyFormat("Foo::operator<int>&();", Style); 23704 verifyFormat("Foo::operator<Foo>&();", Style); 23705 verifyFormat("Foo::operator<int>&&();", Style); 23706 verifyFormat("Foo::operator<Foo>&&();", Style); 23707 verifyFormat("Foo::operator<int>*&();", Style); 23708 verifyFormat("Foo::operator<Foo>*&();", Style); 23709 verifyFormat("operator*(int (*)(), class Foo);", Style); 23710 23711 verifyFormat("Foo::operator&();", Style); 23712 verifyFormat("Foo::operator void&();", Style); 23713 verifyFormat("Foo::operator void const&();", Style); 23714 verifyFormat("Foo::operator/*comment*/ void&();", Style); 23715 verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style); 23716 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style); 23717 verifyFormat("Foo::operator()(void&);", Style); 23718 verifyFormat("Foo::operator&(void&);", Style); 23719 verifyFormat("Foo::operator&();", Style); 23720 verifyFormat("operator&(int (&)(), class Foo);", Style); 23721 verifyFormat("operator&(int (&&)(), class Foo);", Style); 23722 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23723 23724 verifyFormat("Foo::operator&&();", Style); 23725 verifyFormat("Foo::operator void&&();", Style); 23726 verifyFormat("Foo::operator void const&&();", Style); 23727 verifyFormat("Foo::operator/*comment*/ void&&();", Style); 23728 verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style); 23729 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style); 23730 verifyFormat("Foo::operator()(void&&);", Style); 23731 verifyFormat("Foo::operator&&(void&&);", Style); 23732 verifyFormat("Foo::operator&&();", Style); 23733 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23734 verifyFormat("operator const nsTArrayLeft<E>&()", Style); 23735 verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()", 23736 Style); 23737 verifyFormat("operator void**()", Style); 23738 verifyFormat("operator const FooLeft<Object>&()", Style); 23739 verifyFormat("operator const FooLeft<Object>*()", Style); 23740 verifyFormat("operator const FooLeft<Object>**()", Style); 23741 verifyFormat("operator const FooLeft<Object>*&()", Style); 23742 verifyFormat("operator const FooLeft<Object>*&&()", Style); 23743 23744 // PR45107 23745 verifyFormat("operator Vector<String>&();", Style); 23746 verifyFormat("operator const Vector<String>&();", Style); 23747 verifyFormat("operator foo::Bar*();", Style); 23748 verifyFormat("operator const Foo<X>::Bar<Y>*();", Style); 23749 verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();", 23750 Style); 23751 23752 Style.PointerAlignment = FormatStyle::PAS_Middle; 23753 verifyFormat("Foo::operator*();", Style); 23754 verifyFormat("Foo::operator void *();", Style); 23755 verifyFormat("Foo::operator()(void *);", Style); 23756 verifyFormat("Foo::operator*(void *);", Style); 23757 verifyFormat("Foo::operator*();", Style); 23758 verifyFormat("operator*(int (*)(), class Foo);", Style); 23759 23760 verifyFormat("Foo::operator&();", Style); 23761 verifyFormat("Foo::operator void &();", Style); 23762 verifyFormat("Foo::operator void const &();", Style); 23763 verifyFormat("Foo::operator()(void &);", Style); 23764 verifyFormat("Foo::operator&(void &);", Style); 23765 verifyFormat("Foo::operator&();", Style); 23766 verifyFormat("operator&(int (&)(), class Foo);", Style); 23767 23768 verifyFormat("Foo::operator&&();", Style); 23769 verifyFormat("Foo::operator void &&();", Style); 23770 verifyFormat("Foo::operator void const &&();", Style); 23771 verifyFormat("Foo::operator()(void &&);", Style); 23772 verifyFormat("Foo::operator&&(void &&);", Style); 23773 verifyFormat("Foo::operator&&();", Style); 23774 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23775 } 23776 23777 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) { 23778 FormatStyle Style = getLLVMStyle(); 23779 // PR46157 23780 verifyFormat("foo(operator+, -42);", Style); 23781 verifyFormat("foo(operator++, -42);", Style); 23782 verifyFormat("foo(operator--, -42);", Style); 23783 verifyFormat("foo(-42, operator--);", Style); 23784 verifyFormat("foo(-42, operator, );", Style); 23785 verifyFormat("foo(operator, , -42);", Style); 23786 } 23787 23788 TEST_F(FormatTest, WhitespaceSensitiveMacros) { 23789 FormatStyle Style = getLLVMStyle(); 23790 Style.WhitespaceSensitiveMacros.push_back("FOO"); 23791 23792 // Don't use the helpers here, since 'mess up' will change the whitespace 23793 // and these are all whitespace sensitive by definition 23794 EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);", 23795 format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style)); 23796 EXPECT_EQ( 23797 "FOO(String-ized&Messy+But\\(: :Still)=Intentional);", 23798 format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style)); 23799 EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);", 23800 format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style)); 23801 EXPECT_EQ("FOO(String-ized&Messy+But,: :\n" 23802 " Still=Intentional);", 23803 format("FOO(String-ized&Messy+But,: :\n" 23804 " Still=Intentional);", 23805 Style)); 23806 Style.AlignConsecutiveAssignments.Enabled = true; 23807 EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n" 23808 " Still=Intentional);", 23809 format("FOO(String-ized=&Messy+But,: :\n" 23810 " Still=Intentional);", 23811 Style)); 23812 23813 Style.ColumnLimit = 21; 23814 EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);", 23815 format("FOO(String-ized&Messy+But: :Still=Intentional);", Style)); 23816 } 23817 23818 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) { 23819 // These tests are not in NamespaceEndCommentsFixerTest because that doesn't 23820 // test its interaction with line wrapping 23821 FormatStyle Style = getLLVMStyleWithColumns(80); 23822 verifyFormat("namespace {\n" 23823 "int i;\n" 23824 "int j;\n" 23825 "} // namespace", 23826 Style); 23827 23828 verifyFormat("namespace AAA {\n" 23829 "int i;\n" 23830 "int j;\n" 23831 "} // namespace AAA", 23832 Style); 23833 23834 EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n" 23835 "int i;\n" 23836 "int j;\n" 23837 "} // namespace Averyveryveryverylongnamespace", 23838 format("namespace Averyveryveryverylongnamespace {\n" 23839 "int i;\n" 23840 "int j;\n" 23841 "}", 23842 Style)); 23843 23844 EXPECT_EQ( 23845 "namespace " 23846 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n" 23847 " went::mad::now {\n" 23848 "int i;\n" 23849 "int j;\n" 23850 "} // namespace\n" 23851 " // " 23852 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::" 23853 "went::mad::now", 23854 format("namespace " 23855 "would::it::save::you::a::lot::of::time::if_::i::" 23856 "just::gave::up::and_::went::mad::now {\n" 23857 "int i;\n" 23858 "int j;\n" 23859 "}", 23860 Style)); 23861 23862 // This used to duplicate the comment again and again on subsequent runs 23863 EXPECT_EQ( 23864 "namespace " 23865 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n" 23866 " went::mad::now {\n" 23867 "int i;\n" 23868 "int j;\n" 23869 "} // namespace\n" 23870 " // " 23871 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::" 23872 "went::mad::now", 23873 format("namespace " 23874 "would::it::save::you::a::lot::of::time::if_::i::" 23875 "just::gave::up::and_::went::mad::now {\n" 23876 "int i;\n" 23877 "int j;\n" 23878 "} // namespace\n" 23879 " // " 23880 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::" 23881 "and_::went::mad::now", 23882 Style)); 23883 } 23884 23885 TEST_F(FormatTest, LikelyUnlikely) { 23886 FormatStyle Style = getLLVMStyle(); 23887 23888 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23889 " return 29;\n" 23890 "}", 23891 Style); 23892 23893 verifyFormat("if (argc > 5) [[likely]] {\n" 23894 " return 29;\n" 23895 "}", 23896 Style); 23897 23898 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23899 " return 29;\n" 23900 "} else [[likely]] {\n" 23901 " return 42;\n" 23902 "}\n", 23903 Style); 23904 23905 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23906 " return 29;\n" 23907 "} else if (argc > 10) [[likely]] {\n" 23908 " return 99;\n" 23909 "} else {\n" 23910 " return 42;\n" 23911 "}\n", 23912 Style); 23913 23914 verifyFormat("if (argc > 5) [[gnu::unused]] {\n" 23915 " return 29;\n" 23916 "}", 23917 Style); 23918 23919 verifyFormat("if (argc > 5) [[unlikely]]\n" 23920 " return 29;\n", 23921 Style); 23922 verifyFormat("if (argc > 5) [[likely]]\n" 23923 " return 29;\n", 23924 Style); 23925 23926 verifyFormat("while (limit > 0) [[unlikely]] {\n" 23927 " --limit;\n" 23928 "}", 23929 Style); 23930 verifyFormat("for (auto &limit : limits) [[likely]] {\n" 23931 " --limit;\n" 23932 "}", 23933 Style); 23934 23935 verifyFormat("for (auto &limit : limits) [[unlikely]]\n" 23936 " --limit;", 23937 Style); 23938 verifyFormat("while (limit > 0) [[likely]]\n" 23939 " --limit;", 23940 Style); 23941 23942 Style.AttributeMacros.push_back("UNLIKELY"); 23943 Style.AttributeMacros.push_back("LIKELY"); 23944 verifyFormat("if (argc > 5) UNLIKELY\n" 23945 " return 29;\n", 23946 Style); 23947 23948 verifyFormat("if (argc > 5) UNLIKELY {\n" 23949 " return 29;\n" 23950 "}", 23951 Style); 23952 verifyFormat("if (argc > 5) UNLIKELY {\n" 23953 " return 29;\n" 23954 "} else [[likely]] {\n" 23955 " return 42;\n" 23956 "}\n", 23957 Style); 23958 verifyFormat("if (argc > 5) UNLIKELY {\n" 23959 " return 29;\n" 23960 "} else LIKELY {\n" 23961 " return 42;\n" 23962 "}\n", 23963 Style); 23964 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23965 " return 29;\n" 23966 "} else LIKELY {\n" 23967 " return 42;\n" 23968 "}\n", 23969 Style); 23970 23971 verifyFormat("for (auto &limit : limits) UNLIKELY {\n" 23972 " --limit;\n" 23973 "}", 23974 Style); 23975 verifyFormat("while (limit > 0) LIKELY {\n" 23976 " --limit;\n" 23977 "}", 23978 Style); 23979 23980 verifyFormat("while (limit > 0) UNLIKELY\n" 23981 " --limit;", 23982 Style); 23983 verifyFormat("for (auto &limit : limits) LIKELY\n" 23984 " --limit;", 23985 Style); 23986 } 23987 23988 TEST_F(FormatTest, PenaltyIndentedWhitespace) { 23989 verifyFormat("Constructor()\n" 23990 " : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 23991 " aaaa(aaaaaaaaaaaaaaaaaa, " 23992 "aaaaaaaaaaaaaaaaaat))"); 23993 verifyFormat("Constructor()\n" 23994 " : aaaaaaaaaaaaa(aaaaaa), " 23995 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)"); 23996 23997 FormatStyle StyleWithWhitespacePenalty = getLLVMStyle(); 23998 StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5; 23999 verifyFormat("Constructor()\n" 24000 " : aaaaaa(aaaaaa),\n" 24001 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 24002 " aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))", 24003 StyleWithWhitespacePenalty); 24004 verifyFormat("Constructor()\n" 24005 " : aaaaaaaaaaaaa(aaaaaa), " 24006 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)", 24007 StyleWithWhitespacePenalty); 24008 } 24009 24010 TEST_F(FormatTest, LLVMDefaultStyle) { 24011 FormatStyle Style = getLLVMStyle(); 24012 verifyFormat("extern \"C\" {\n" 24013 "int foo();\n" 24014 "}", 24015 Style); 24016 } 24017 TEST_F(FormatTest, GNUDefaultStyle) { 24018 FormatStyle Style = getGNUStyle(); 24019 verifyFormat("extern \"C\"\n" 24020 "{\n" 24021 " int foo ();\n" 24022 "}", 24023 Style); 24024 } 24025 TEST_F(FormatTest, MozillaDefaultStyle) { 24026 FormatStyle Style = getMozillaStyle(); 24027 verifyFormat("extern \"C\"\n" 24028 "{\n" 24029 " int foo();\n" 24030 "}", 24031 Style); 24032 } 24033 TEST_F(FormatTest, GoogleDefaultStyle) { 24034 FormatStyle Style = getGoogleStyle(); 24035 verifyFormat("extern \"C\" {\n" 24036 "int foo();\n" 24037 "}", 24038 Style); 24039 } 24040 TEST_F(FormatTest, ChromiumDefaultStyle) { 24041 FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp); 24042 verifyFormat("extern \"C\" {\n" 24043 "int foo();\n" 24044 "}", 24045 Style); 24046 } 24047 TEST_F(FormatTest, MicrosoftDefaultStyle) { 24048 FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp); 24049 verifyFormat("extern \"C\"\n" 24050 "{\n" 24051 " int foo();\n" 24052 "}", 24053 Style); 24054 } 24055 TEST_F(FormatTest, WebKitDefaultStyle) { 24056 FormatStyle Style = getWebKitStyle(); 24057 verifyFormat("extern \"C\" {\n" 24058 "int foo();\n" 24059 "}", 24060 Style); 24061 } 24062 24063 TEST_F(FormatTest, Concepts) { 24064 EXPECT_EQ(getLLVMStyle().BreakBeforeConceptDeclarations, 24065 FormatStyle::BBCDS_Always); 24066 verifyFormat("template <typename T>\n" 24067 "concept True = true;"); 24068 24069 verifyFormat("template <typename T>\n" 24070 "concept C = ((false || foo()) && C2<T>) ||\n" 24071 " (std::trait<T>::value && Baz) || sizeof(T) >= 6;", 24072 getLLVMStyleWithColumns(60)); 24073 24074 verifyFormat("template <typename T>\n" 24075 "concept DelayedCheck = true && requires(T t) { t.bar(); } && " 24076 "sizeof(T) <= 8;"); 24077 24078 verifyFormat("template <typename T>\n" 24079 "concept DelayedCheck = true && requires(T t) {\n" 24080 " t.bar();\n" 24081 " t.baz();\n" 24082 " } && sizeof(T) <= 8;"); 24083 24084 verifyFormat("template <typename T>\n" 24085 "concept DelayedCheck = true && requires(T t) { // Comment\n" 24086 " t.bar();\n" 24087 " t.baz();\n" 24088 " } && sizeof(T) <= 8;"); 24089 24090 verifyFormat("template <typename T>\n" 24091 "concept DelayedCheck = false || requires(T t) { t.bar(); } && " 24092 "sizeof(T) <= 8;"); 24093 24094 verifyFormat("template <typename T>\n" 24095 "concept DelayedCheck = !!false || requires(T t) { t.bar(); } " 24096 "&& sizeof(T) <= 8;"); 24097 24098 verifyFormat( 24099 "template <typename T>\n" 24100 "concept DelayedCheck = static_cast<bool>(0) ||\n" 24101 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 24102 24103 verifyFormat("template <typename T>\n" 24104 "concept DelayedCheck = bool(0) || requires(T t) { t.bar(); } " 24105 "&& sizeof(T) <= 8;"); 24106 24107 verifyFormat( 24108 "template <typename T>\n" 24109 "concept DelayedCheck = (bool)(0) ||\n" 24110 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 24111 24112 verifyFormat("template <typename T>\n" 24113 "concept DelayedCheck = (bool)0 || requires(T t) { t.bar(); } " 24114 "&& sizeof(T) <= 8;"); 24115 24116 verifyFormat("template <typename T>\n" 24117 "concept Size = sizeof(T) >= 5 && requires(T t) { t.bar(); } && " 24118 "sizeof(T) <= 8;"); 24119 24120 verifyFormat("template <typename T>\n" 24121 "concept Size = 2 < 5 && 2 <= 5 && 8 >= 5 && 8 > 5 &&\n" 24122 " requires(T t) {\n" 24123 " t.bar();\n" 24124 " t.baz();\n" 24125 " } && sizeof(T) <= 8 && !(4 < 3);", 24126 getLLVMStyleWithColumns(60)); 24127 24128 verifyFormat("template <typename T>\n" 24129 "concept TrueOrNot = IsAlwaysTrue || IsNeverTrue;"); 24130 24131 verifyFormat("template <typename T>\n" 24132 "concept C = foo();"); 24133 24134 verifyFormat("template <typename T>\n" 24135 "concept C = foo(T());"); 24136 24137 verifyFormat("template <typename T>\n" 24138 "concept C = foo(T{});"); 24139 24140 verifyFormat("template <typename T>\n" 24141 "concept Size = V<sizeof(T)>::Value > 5;"); 24142 24143 verifyFormat("template <typename T>\n" 24144 "concept True = S<T>::Value;"); 24145 24146 verifyFormat( 24147 "template <typename T>\n" 24148 "concept C = []() { return true; }() && requires(T t) { t.bar(); } &&\n" 24149 " sizeof(T) <= 8;"); 24150 24151 // FIXME: This is misformatted because the fake l paren starts at bool, not at 24152 // the lambda l square. 24153 verifyFormat("template <typename T>\n" 24154 "concept C = [] -> bool { return true; }() && requires(T t) { " 24155 "t.bar(); } &&\n" 24156 " sizeof(T) <= 8;"); 24157 24158 verifyFormat( 24159 "template <typename T>\n" 24160 "concept C = decltype([]() { return std::true_type{}; }())::value &&\n" 24161 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 24162 24163 verifyFormat("template <typename T>\n" 24164 "concept C = decltype([]() { return std::true_type{}; " 24165 "}())::value && requires(T t) { t.bar(); } && sizeof(T) <= 8;", 24166 getLLVMStyleWithColumns(120)); 24167 24168 verifyFormat("template <typename T>\n" 24169 "concept C = decltype([]() -> std::true_type { return {}; " 24170 "}())::value &&\n" 24171 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 24172 24173 verifyFormat("template <typename T>\n" 24174 "concept C = true;\n" 24175 "Foo Bar;"); 24176 24177 verifyFormat("template <typename T>\n" 24178 "concept Hashable = requires(T a) {\n" 24179 " { std::hash<T>{}(a) } -> " 24180 "std::convertible_to<std::size_t>;\n" 24181 " };"); 24182 24183 verifyFormat( 24184 "template <typename T>\n" 24185 "concept EqualityComparable = requires(T a, T b) {\n" 24186 " { a == b } -> std::same_as<bool>;\n" 24187 " };"); 24188 24189 verifyFormat( 24190 "template <typename T>\n" 24191 "concept EqualityComparable = requires(T a, T b) {\n" 24192 " { a == b } -> std::same_as<bool>;\n" 24193 " { a != b } -> std::same_as<bool>;\n" 24194 " };"); 24195 24196 verifyFormat("template <typename T>\n" 24197 "concept WeakEqualityComparable = requires(T a, T b) {\n" 24198 " { a == b };\n" 24199 " { a != b };\n" 24200 " };"); 24201 24202 verifyFormat("template <typename T>\n" 24203 "concept HasSizeT = requires { typename T::size_t; };"); 24204 24205 verifyFormat("template <typename T>\n" 24206 "concept Semiregular =\n" 24207 " DefaultConstructible<T> && CopyConstructible<T> && " 24208 "CopyAssignable<T> &&\n" 24209 " requires(T a, std::size_t n) {\n" 24210 " requires Same<T *, decltype(&a)>;\n" 24211 " { a.~T() } noexcept;\n" 24212 " requires Same<T *, decltype(new T)>;\n" 24213 " requires Same<T *, decltype(new T[n])>;\n" 24214 " { delete new T; };\n" 24215 " { delete new T[n]; };\n" 24216 " };"); 24217 24218 verifyFormat("template <typename T>\n" 24219 "concept Semiregular =\n" 24220 " requires(T a, std::size_t n) {\n" 24221 " requires Same<T *, decltype(&a)>;\n" 24222 " { a.~T() } noexcept;\n" 24223 " requires Same<T *, decltype(new T)>;\n" 24224 " requires Same<T *, decltype(new T[n])>;\n" 24225 " { delete new T; };\n" 24226 " { delete new T[n]; };\n" 24227 " { new T } -> std::same_as<T *>;\n" 24228 " } && DefaultConstructible<T> && CopyConstructible<T> && " 24229 "CopyAssignable<T>;"); 24230 24231 verifyFormat( 24232 "template <typename T>\n" 24233 "concept Semiregular =\n" 24234 " DefaultConstructible<T> && requires(T a, std::size_t n) {\n" 24235 " requires Same<T *, decltype(&a)>;\n" 24236 " { a.~T() } noexcept;\n" 24237 " requires Same<T *, decltype(new T)>;\n" 24238 " requires Same<T *, decltype(new " 24239 "T[n])>;\n" 24240 " { delete new T; };\n" 24241 " { delete new T[n]; };\n" 24242 " } && CopyConstructible<T> && " 24243 "CopyAssignable<T>;"); 24244 24245 verifyFormat("template <typename T>\n" 24246 "concept Two = requires(T t) {\n" 24247 " { t.foo() } -> std::same_as<Bar>;\n" 24248 " } && requires(T &&t) {\n" 24249 " { t.foo() } -> std::same_as<Bar &&>;\n" 24250 " };"); 24251 24252 verifyFormat( 24253 "template <typename T>\n" 24254 "concept C = requires(T x) {\n" 24255 " { *x } -> std::convertible_to<typename T::inner>;\n" 24256 " { x + 1 } noexcept -> std::same_as<int>;\n" 24257 " { x * 1 } -> std::convertible_to<T>;\n" 24258 " };"); 24259 24260 verifyFormat( 24261 "template <typename T, typename U = T>\n" 24262 "concept Swappable = requires(T &&t, U &&u) {\n" 24263 " swap(std::forward<T>(t), std::forward<U>(u));\n" 24264 " swap(std::forward<U>(u), std::forward<T>(t));\n" 24265 " };"); 24266 24267 verifyFormat("template <typename T, typename U>\n" 24268 "concept Common = requires(T &&t, U &&u) {\n" 24269 " typename CommonType<T, U>;\n" 24270 " { CommonType<T, U>(std::forward<T>(t)) };\n" 24271 " };"); 24272 24273 verifyFormat("template <typename T, typename U>\n" 24274 "concept Common = requires(T &&t, U &&u) {\n" 24275 " typename CommonType<T, U>;\n" 24276 " { CommonType<T, U>{std::forward<T>(t)} };\n" 24277 " };"); 24278 24279 verifyFormat( 24280 "template <typename T>\n" 24281 "concept C = requires(T t) {\n" 24282 " requires Bar<T> && Foo<T>;\n" 24283 " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n" 24284 " };"); 24285 24286 verifyFormat("template <typename T>\n" 24287 "concept HasFoo = requires(T t) {\n" 24288 " { t.foo() };\n" 24289 " t.foo();\n" 24290 " };\n" 24291 "template <typename T>\n" 24292 "concept HasBar = requires(T t) {\n" 24293 " { t.bar() };\n" 24294 " t.bar();\n" 24295 " };"); 24296 24297 verifyFormat("template <typename T>\n" 24298 "concept Large = sizeof(T) > 10;"); 24299 24300 verifyFormat("template <typename T, typename U>\n" 24301 "concept FooableWith = requires(T t, U u) {\n" 24302 " typename T::foo_type;\n" 24303 " { t.foo(u) } -> typename T::foo_type;\n" 24304 " t++;\n" 24305 " };\n" 24306 "void doFoo(FooableWith<int> auto t) { t.foo(3); }"); 24307 24308 verifyFormat("template <typename T>\n" 24309 "concept Context = is_specialization_of_v<context, T>;"); 24310 24311 verifyFormat("template <typename T>\n" 24312 "concept Node = std::is_object_v<T>;"); 24313 24314 verifyFormat("template <class T>\n" 24315 "concept integral = __is_integral(T);"); 24316 24317 verifyFormat("template <class T>\n" 24318 "concept is2D = __array_extent(T, 1) == 2;"); 24319 24320 verifyFormat("template <class T>\n" 24321 "concept isRhs = __is_rvalue_expr(std::declval<T>() + 2)"); 24322 24323 verifyFormat("template <class T, class T2>\n" 24324 "concept Same = __is_same_as<T, T2>;"); 24325 24326 verifyFormat( 24327 "template <class _InIt, class _OutIt>\n" 24328 "concept _Can_reread_dest =\n" 24329 " std::forward_iterator<_OutIt> &&\n" 24330 " std::same_as<std::iter_value_t<_InIt>, std::iter_value_t<_OutIt>>;"); 24331 24332 auto Style = getLLVMStyle(); 24333 Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Allowed; 24334 24335 verifyFormat( 24336 "template <typename T>\n" 24337 "concept C = requires(T t) {\n" 24338 " requires Bar<T> && Foo<T>;\n" 24339 " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n" 24340 " };", 24341 Style); 24342 24343 verifyFormat("template <typename T>\n" 24344 "concept HasFoo = requires(T t) {\n" 24345 " { t.foo() };\n" 24346 " t.foo();\n" 24347 " };\n" 24348 "template <typename T>\n" 24349 "concept HasBar = requires(T t) {\n" 24350 " { t.bar() };\n" 24351 " t.bar();\n" 24352 " };", 24353 Style); 24354 24355 verifyFormat("template <typename T> concept True = true;", Style); 24356 24357 verifyFormat("template <typename T>\n" 24358 "concept C = decltype([]() -> std::true_type { return {}; " 24359 "}())::value &&\n" 24360 " requires(T t) { t.bar(); } && sizeof(T) <= 8;", 24361 Style); 24362 24363 verifyFormat("template <typename T>\n" 24364 "concept Semiregular =\n" 24365 " DefaultConstructible<T> && CopyConstructible<T> && " 24366 "CopyAssignable<T> &&\n" 24367 " requires(T a, std::size_t n) {\n" 24368 " requires Same<T *, decltype(&a)>;\n" 24369 " { a.~T() } noexcept;\n" 24370 " requires Same<T *, decltype(new T)>;\n" 24371 " requires Same<T *, decltype(new T[n])>;\n" 24372 " { delete new T; };\n" 24373 " { delete new T[n]; };\n" 24374 " };", 24375 Style); 24376 24377 Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Never; 24378 24379 verifyFormat("template <typename T> concept C =\n" 24380 " requires(T t) {\n" 24381 " requires Bar<T> && Foo<T>;\n" 24382 " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n" 24383 " };", 24384 Style); 24385 24386 verifyFormat("template <typename T> concept HasFoo = requires(T t) {\n" 24387 " { t.foo() };\n" 24388 " t.foo();\n" 24389 " };\n" 24390 "template <typename T> concept HasBar = requires(T t) {\n" 24391 " { t.bar() };\n" 24392 " t.bar();\n" 24393 " };", 24394 Style); 24395 24396 verifyFormat("template <typename T> concept True = true;", Style); 24397 24398 verifyFormat( 24399 "template <typename T> concept C = decltype([]() -> std::true_type {\n" 24400 " return {};\n" 24401 " }())::value &&\n" 24402 " requires(T t) { t.bar(); } && " 24403 "sizeof(T) <= 8;", 24404 Style); 24405 24406 verifyFormat("template <typename T> concept Semiregular =\n" 24407 " DefaultConstructible<T> && CopyConstructible<T> && " 24408 "CopyAssignable<T> &&\n" 24409 " requires(T a, std::size_t n) {\n" 24410 " requires Same<T *, decltype(&a)>;\n" 24411 " { a.~T() } noexcept;\n" 24412 " requires Same<T *, decltype(new T)>;\n" 24413 " requires Same<T *, decltype(new T[n])>;\n" 24414 " { delete new T; };\n" 24415 " { delete new T[n]; };\n" 24416 " };", 24417 Style); 24418 24419 // The following tests are invalid C++, we just want to make sure we don't 24420 // assert. 24421 verifyFormat("template <typename T>\n" 24422 "concept C = requires C2<T>;"); 24423 24424 verifyFormat("template <typename T>\n" 24425 "concept C = 5 + 4;"); 24426 24427 verifyFormat("template <typename T>\n" 24428 "concept C =\n" 24429 "class X;"); 24430 24431 verifyFormat("template <typename T>\n" 24432 "concept C = [] && true;"); 24433 24434 verifyFormat("template <typename T>\n" 24435 "concept C = [] && requires(T t) { typename T::size_type; };"); 24436 } 24437 24438 TEST_F(FormatTest, RequiresClausesPositions) { 24439 auto Style = getLLVMStyle(); 24440 EXPECT_EQ(Style.RequiresClausePosition, FormatStyle::RCPS_OwnLine); 24441 EXPECT_EQ(Style.IndentRequiresClause, true); 24442 24443 verifyFormat("template <typename T>\n" 24444 " requires(Foo<T> && std::trait<T>)\n" 24445 "struct Bar;", 24446 Style); 24447 24448 verifyFormat("template <typename T>\n" 24449 " requires(Foo<T> && std::trait<T>)\n" 24450 "class Bar {\n" 24451 "public:\n" 24452 " Bar(T t);\n" 24453 " bool baz();\n" 24454 "};", 24455 Style); 24456 24457 verifyFormat( 24458 "template <typename T>\n" 24459 " requires requires(T &&t) {\n" 24460 " typename T::I;\n" 24461 " requires(F<typename T::I> && std::trait<typename T::I>);\n" 24462 " }\n" 24463 "Bar(T) -> Bar<typename T::I>;", 24464 Style); 24465 24466 verifyFormat("template <typename T>\n" 24467 " requires(Foo<T> && std::trait<T>)\n" 24468 "constexpr T MyGlobal;", 24469 Style); 24470 24471 verifyFormat("template <typename T>\n" 24472 " requires Foo<T> && requires(T t) {\n" 24473 " { t.baz() } -> std::same_as<bool>;\n" 24474 " requires std::same_as<T::Factor, int>;\n" 24475 " }\n" 24476 "inline int bar(T t) {\n" 24477 " return t.baz() ? T::Factor : 5;\n" 24478 "}", 24479 Style); 24480 24481 verifyFormat("template <typename T>\n" 24482 "inline int bar(T t)\n" 24483 " requires Foo<T> && requires(T t) {\n" 24484 " { t.baz() } -> std::same_as<bool>;\n" 24485 " requires std::same_as<T::Factor, int>;\n" 24486 " }\n" 24487 "{\n" 24488 " return t.baz() ? T::Factor : 5;\n" 24489 "}", 24490 Style); 24491 24492 verifyFormat("template <typename T>\n" 24493 " requires F<T>\n" 24494 "int bar(T t) {\n" 24495 " return 5;\n" 24496 "}", 24497 Style); 24498 24499 verifyFormat("template <typename T>\n" 24500 "int bar(T t)\n" 24501 " requires F<T>\n" 24502 "{\n" 24503 " return 5;\n" 24504 "}", 24505 Style); 24506 24507 verifyFormat("template <typename T>\n" 24508 "int bar(T t)\n" 24509 " requires F<T>;", 24510 Style); 24511 24512 Style.IndentRequiresClause = false; 24513 verifyFormat("template <typename T>\n" 24514 "requires F<T>\n" 24515 "int bar(T t) {\n" 24516 " return 5;\n" 24517 "}", 24518 Style); 24519 24520 verifyFormat("template <typename T>\n" 24521 "int bar(T t)\n" 24522 "requires F<T>\n" 24523 "{\n" 24524 " return 5;\n" 24525 "}", 24526 Style); 24527 24528 Style.RequiresClausePosition = FormatStyle::RCPS_SingleLine; 24529 verifyFormat("template <typename T> requires Foo<T> struct Bar {};\n" 24530 "template <typename T> requires Foo<T> void bar() {}\n" 24531 "template <typename T> void bar() requires Foo<T> {}\n" 24532 "template <typename T> void bar() requires Foo<T>;\n" 24533 "template <typename T> requires Foo<T> Bar(T) -> Bar<T>;", 24534 Style); 24535 24536 auto ColumnStyle = Style; 24537 ColumnStyle.ColumnLimit = 40; 24538 verifyFormat("template <typename AAAAAAA>\n" 24539 "requires Foo<T> struct Bar {};\n" 24540 "template <typename AAAAAAA>\n" 24541 "requires Foo<T> void bar() {}\n" 24542 "template <typename AAAAAAA>\n" 24543 "void bar() requires Foo<T> {}\n" 24544 "template <typename AAAAAAA>\n" 24545 "requires Foo<T> Baz(T) -> Baz<T>;", 24546 ColumnStyle); 24547 24548 verifyFormat("template <typename T>\n" 24549 "requires Foo<AAAAAAA> struct Bar {};\n" 24550 "template <typename T>\n" 24551 "requires Foo<AAAAAAA> void bar() {}\n" 24552 "template <typename T>\n" 24553 "void bar() requires Foo<AAAAAAA> {}\n" 24554 "template <typename T>\n" 24555 "requires Foo<AAAAAAA> Bar(T) -> Bar<T>;", 24556 ColumnStyle); 24557 24558 verifyFormat("template <typename AAAAAAA>\n" 24559 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24560 "struct Bar {};\n" 24561 "template <typename AAAAAAA>\n" 24562 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24563 "void bar() {}\n" 24564 "template <typename AAAAAAA>\n" 24565 "void bar()\n" 24566 " requires Foo<AAAAAAAAAAAAAAAA> {}\n" 24567 "template <typename AAAAAAA>\n" 24568 "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n" 24569 "template <typename AAAAAAA>\n" 24570 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24571 "Bar(T) -> Bar<T>;", 24572 ColumnStyle); 24573 24574 Style.RequiresClausePosition = FormatStyle::RCPS_WithFollowing; 24575 ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithFollowing; 24576 24577 verifyFormat("template <typename T>\n" 24578 "requires Foo<T> struct Bar {};\n" 24579 "template <typename T>\n" 24580 "requires Foo<T> void bar() {}\n" 24581 "template <typename T>\n" 24582 "void bar()\n" 24583 "requires Foo<T> {}\n" 24584 "template <typename T>\n" 24585 "void bar()\n" 24586 "requires Foo<T>;\n" 24587 "template <typename T>\n" 24588 "requires Foo<T> Bar(T) -> Bar<T>;", 24589 Style); 24590 24591 verifyFormat("template <typename AAAAAAA>\n" 24592 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24593 "struct Bar {};\n" 24594 "template <typename AAAAAAA>\n" 24595 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24596 "void bar() {}\n" 24597 "template <typename AAAAAAA>\n" 24598 "void bar()\n" 24599 "requires Foo<AAAAAAAAAAAAAAAA> {}\n" 24600 "template <typename AAAAAAA>\n" 24601 "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n" 24602 "template <typename AAAAAAA>\n" 24603 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24604 "Bar(T) -> Bar<T>;", 24605 ColumnStyle); 24606 24607 Style.IndentRequiresClause = true; 24608 ColumnStyle.IndentRequiresClause = true; 24609 24610 verifyFormat("template <typename T>\n" 24611 " requires Foo<T> struct Bar {};\n" 24612 "template <typename T>\n" 24613 " requires Foo<T> void bar() {}\n" 24614 "template <typename T>\n" 24615 "void bar()\n" 24616 " requires Foo<T> {}\n" 24617 "template <typename T>\n" 24618 " requires Foo<T> Bar(T) -> Bar<T>;", 24619 Style); 24620 24621 verifyFormat("template <typename AAAAAAA>\n" 24622 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24623 "struct Bar {};\n" 24624 "template <typename AAAAAAA>\n" 24625 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24626 "void bar() {}\n" 24627 "template <typename AAAAAAA>\n" 24628 "void bar()\n" 24629 " requires Foo<AAAAAAAAAAAAAAAA> {}\n" 24630 "template <typename AAAAAAA>\n" 24631 " requires Foo<AAAAAA> Bar(T) -> Bar<T>;\n" 24632 "template <typename AAAAAAA>\n" 24633 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24634 "Bar(T) -> Bar<T>;", 24635 ColumnStyle); 24636 24637 Style.RequiresClausePosition = FormatStyle::RCPS_WithPreceding; 24638 ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithPreceding; 24639 24640 verifyFormat("template <typename T> requires Foo<T>\n" 24641 "struct Bar {};\n" 24642 "template <typename T> requires Foo<T>\n" 24643 "void bar() {}\n" 24644 "template <typename T>\n" 24645 "void bar() requires Foo<T>\n" 24646 "{}\n" 24647 "template <typename T> void bar() requires Foo<T>;\n" 24648 "template <typename T> requires Foo<T>\n" 24649 "Bar(T) -> Bar<T>;", 24650 Style); 24651 24652 verifyFormat("template <typename AAAAAAA>\n" 24653 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24654 "struct Bar {};\n" 24655 "template <typename AAAAAAA>\n" 24656 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24657 "void bar() {}\n" 24658 "template <typename AAAAAAA>\n" 24659 "void bar()\n" 24660 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24661 "{}\n" 24662 "template <typename AAAAAAA>\n" 24663 "requires Foo<AAAAAAAA>\n" 24664 "Bar(T) -> Bar<T>;\n" 24665 "template <typename AAAAAAA>\n" 24666 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24667 "Bar(T) -> Bar<T>;", 24668 ColumnStyle); 24669 } 24670 24671 TEST_F(FormatTest, RequiresClauses) { 24672 verifyFormat("struct [[nodiscard]] zero_t {\n" 24673 " template <class T>\n" 24674 " requires requires { number_zero_v<T>; }\n" 24675 " [[nodiscard]] constexpr operator T() const {\n" 24676 " return number_zero_v<T>;\n" 24677 " }\n" 24678 "};"); 24679 24680 auto Style = getLLVMStyle(); 24681 24682 verifyFormat( 24683 "template <typename T>\n" 24684 " requires is_default_constructible_v<hash<T>> and\n" 24685 " is_copy_constructible_v<hash<T>> and\n" 24686 " is_move_constructible_v<hash<T>> and\n" 24687 " is_copy_assignable_v<hash<T>> and " 24688 "is_move_assignable_v<hash<T>> and\n" 24689 " is_destructible_v<hash<T>> and is_swappable_v<hash<T>> and\n" 24690 " is_callable_v<hash<T>(T)> and\n" 24691 " is_same_v<size_t, decltype(hash<T>(declval<T>()))> and\n" 24692 " is_same_v<size_t, decltype(hash<T>(declval<T &>()))> and\n" 24693 " is_same_v<size_t, decltype(hash<T>(declval<const T &>()))>\n" 24694 "struct S {};", 24695 Style); 24696 24697 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 24698 verifyFormat( 24699 "template <typename T>\n" 24700 " requires is_default_constructible_v<hash<T>>\n" 24701 " and is_copy_constructible_v<hash<T>>\n" 24702 " and is_move_constructible_v<hash<T>>\n" 24703 " and is_copy_assignable_v<hash<T>> and " 24704 "is_move_assignable_v<hash<T>>\n" 24705 " and is_destructible_v<hash<T>> and is_swappable_v<hash<T>>\n" 24706 " and is_callable_v<hash<T>(T)>\n" 24707 " and is_same_v<size_t, decltype(hash<T>(declval<T>()))>\n" 24708 " and is_same_v<size_t, decltype(hash<T>(declval<T &>()))>\n" 24709 " and is_same_v<size_t, decltype(hash<T>(declval<const T " 24710 "&>()))>\n" 24711 "struct S {};", 24712 Style); 24713 24714 // Not a clause, but we once hit an assert. 24715 verifyFormat("#if 0\n" 24716 "#else\n" 24717 "foo();\n" 24718 "#endif\n" 24719 "bar(requires);"); 24720 } 24721 24722 TEST_F(FormatTest, StatementAttributeLikeMacros) { 24723 FormatStyle Style = getLLVMStyle(); 24724 StringRef Source = "void Foo::slot() {\n" 24725 " unsigned char MyChar = 'x';\n" 24726 " emit signal(MyChar);\n" 24727 " Q_EMIT signal(MyChar);\n" 24728 "}"; 24729 24730 EXPECT_EQ(Source, format(Source, Style)); 24731 24732 Style.AlignConsecutiveDeclarations.Enabled = true; 24733 EXPECT_EQ("void Foo::slot() {\n" 24734 " unsigned char MyChar = 'x';\n" 24735 " emit signal(MyChar);\n" 24736 " Q_EMIT signal(MyChar);\n" 24737 "}", 24738 format(Source, Style)); 24739 24740 Style.StatementAttributeLikeMacros.push_back("emit"); 24741 EXPECT_EQ(Source, format(Source, Style)); 24742 24743 Style.StatementAttributeLikeMacros = {}; 24744 EXPECT_EQ("void Foo::slot() {\n" 24745 " unsigned char MyChar = 'x';\n" 24746 " emit signal(MyChar);\n" 24747 " Q_EMIT signal(MyChar);\n" 24748 "}", 24749 format(Source, Style)); 24750 } 24751 24752 TEST_F(FormatTest, IndentAccessModifiers) { 24753 FormatStyle Style = getLLVMStyle(); 24754 Style.IndentAccessModifiers = true; 24755 // Members are *two* levels below the record; 24756 // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation. 24757 verifyFormat("class C {\n" 24758 " int i;\n" 24759 "};\n", 24760 Style); 24761 verifyFormat("union C {\n" 24762 " int i;\n" 24763 " unsigned u;\n" 24764 "};\n", 24765 Style); 24766 // Access modifiers should be indented one level below the record. 24767 verifyFormat("class C {\n" 24768 " public:\n" 24769 " int i;\n" 24770 "};\n", 24771 Style); 24772 verifyFormat("struct S {\n" 24773 " private:\n" 24774 " class C {\n" 24775 " int j;\n" 24776 "\n" 24777 " public:\n" 24778 " C();\n" 24779 " };\n" 24780 "\n" 24781 " public:\n" 24782 " int i;\n" 24783 "};\n", 24784 Style); 24785 // Enumerations are not records and should be unaffected. 24786 Style.AllowShortEnumsOnASingleLine = false; 24787 verifyFormat("enum class E {\n" 24788 " A,\n" 24789 " B\n" 24790 "};\n", 24791 Style); 24792 // Test with a different indentation width; 24793 // also proves that the result is Style.AccessModifierOffset agnostic. 24794 Style.IndentWidth = 3; 24795 verifyFormat("class C {\n" 24796 " public:\n" 24797 " int i;\n" 24798 "};\n", 24799 Style); 24800 } 24801 24802 TEST_F(FormatTest, LimitlessStringsAndComments) { 24803 auto Style = getLLVMStyleWithColumns(0); 24804 constexpr StringRef Code = 24805 "/**\n" 24806 " * This is a multiline comment with quite some long lines, at least for " 24807 "the LLVM Style.\n" 24808 " * We will redo this with strings and line comments. Just to check if " 24809 "everything is working.\n" 24810 " */\n" 24811 "bool foo() {\n" 24812 " /* Single line multi line comment. */\n" 24813 " const std::string String = \"This is a multiline string with quite " 24814 "some long lines, at least for the LLVM Style.\"\n" 24815 " \"We already did it with multi line " 24816 "comments, and we will do it with line comments. Just to check if " 24817 "everything is working.\";\n" 24818 " // This is a line comment (block) with quite some long lines, at " 24819 "least for the LLVM Style.\n" 24820 " // We already did this with multi line comments and strings. Just to " 24821 "check if everything is working.\n" 24822 " const std::string SmallString = \"Hello World\";\n" 24823 " // Small line comment\n" 24824 " return String.size() > SmallString.size();\n" 24825 "}"; 24826 EXPECT_EQ(Code, format(Code, Style)); 24827 } 24828 24829 TEST_F(FormatTest, FormatDecayCopy) { 24830 // error cases from unit tests 24831 verifyFormat("foo(auto())"); 24832 verifyFormat("foo(auto{})"); 24833 verifyFormat("foo(auto({}))"); 24834 verifyFormat("foo(auto{{}})"); 24835 24836 verifyFormat("foo(auto(1))"); 24837 verifyFormat("foo(auto{1})"); 24838 verifyFormat("foo(new auto(1))"); 24839 verifyFormat("foo(new auto{1})"); 24840 verifyFormat("decltype(auto(1)) x;"); 24841 verifyFormat("decltype(auto{1}) x;"); 24842 verifyFormat("auto(x);"); 24843 verifyFormat("auto{x};"); 24844 verifyFormat("new auto{x};"); 24845 verifyFormat("auto{x} = y;"); 24846 verifyFormat("auto(x) = y;"); // actually a declaration, but this is clearly 24847 // the user's own fault 24848 verifyFormat("integral auto(x) = y;"); // actually a declaration, but this is 24849 // clearly the user's own fault 24850 verifyFormat("auto(*p)() = f;"); // actually a declaration; TODO FIXME 24851 } 24852 24853 TEST_F(FormatTest, Cpp20ModulesSupport) { 24854 FormatStyle Style = getLLVMStyle(); 24855 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 24856 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 24857 24858 verifyFormat("export import foo;", Style); 24859 verifyFormat("export import foo:bar;", Style); 24860 verifyFormat("export import foo.bar;", Style); 24861 verifyFormat("export import foo.bar:baz;", Style); 24862 verifyFormat("export import :bar;", Style); 24863 verifyFormat("export module foo:bar;", Style); 24864 verifyFormat("export module foo;", Style); 24865 verifyFormat("export module foo.bar;", Style); 24866 verifyFormat("export module foo.bar:baz;", Style); 24867 verifyFormat("export import <string_view>;", Style); 24868 24869 verifyFormat("export type_name var;", Style); 24870 verifyFormat("template <class T> export using A = B<T>;", Style); 24871 verifyFormat("export using A = B;", Style); 24872 verifyFormat("export int func() {\n" 24873 " foo();\n" 24874 "}", 24875 Style); 24876 verifyFormat("export struct {\n" 24877 " int foo;\n" 24878 "};", 24879 Style); 24880 verifyFormat("export {\n" 24881 " int foo;\n" 24882 "};", 24883 Style); 24884 verifyFormat("export export char const *hello() { return \"hello\"; }"); 24885 24886 verifyFormat("import bar;", Style); 24887 verifyFormat("import foo.bar;", Style); 24888 verifyFormat("import foo:bar;", Style); 24889 verifyFormat("import :bar;", Style); 24890 verifyFormat("import <ctime>;", Style); 24891 verifyFormat("import \"header\";", Style); 24892 24893 verifyFormat("module foo;", Style); 24894 verifyFormat("module foo:bar;", Style); 24895 verifyFormat("module foo.bar;", Style); 24896 verifyFormat("module;", Style); 24897 24898 verifyFormat("export namespace hi {\n" 24899 "const char *sayhi();\n" 24900 "}", 24901 Style); 24902 24903 verifyFormat("module :private;", Style); 24904 verifyFormat("import <foo/bar.h>;", Style); 24905 verifyFormat("import foo...bar;", Style); 24906 verifyFormat("import ..........;", Style); 24907 verifyFormat("module foo:private;", Style); 24908 verifyFormat("import a", Style); 24909 verifyFormat("module a", Style); 24910 verifyFormat("export import a", Style); 24911 verifyFormat("export module a", Style); 24912 24913 verifyFormat("import", Style); 24914 verifyFormat("module", Style); 24915 verifyFormat("export", Style); 24916 } 24917 24918 TEST_F(FormatTest, CoroutineForCoawait) { 24919 FormatStyle Style = getLLVMStyle(); 24920 verifyFormat("for co_await (auto x : range())\n ;"); 24921 verifyFormat("for (auto i : arr) {\n" 24922 "}", 24923 Style); 24924 verifyFormat("for co_await (auto i : arr) {\n" 24925 "}", 24926 Style); 24927 verifyFormat("for co_await (auto i : foo(T{})) {\n" 24928 "}", 24929 Style); 24930 } 24931 24932 TEST_F(FormatTest, CoroutineCoAwait) { 24933 verifyFormat("int x = co_await foo();"); 24934 verifyFormat("int x = (co_await foo());"); 24935 verifyFormat("co_await (42);"); 24936 verifyFormat("void operator co_await(int);"); 24937 verifyFormat("void operator co_await(a);"); 24938 verifyFormat("co_await a;"); 24939 verifyFormat("co_await missing_await_resume{};"); 24940 verifyFormat("co_await a; // comment"); 24941 verifyFormat("void test0() { co_await a; }"); 24942 verifyFormat("co_await co_await co_await foo();"); 24943 verifyFormat("co_await foo().bar();"); 24944 verifyFormat("co_await [this]() -> Task { co_return x; }"); 24945 verifyFormat("co_await [this](int a, int b) -> Task { co_return co_await " 24946 "foo(); }(x, y);"); 24947 24948 FormatStyle Style = getLLVMStyleWithColumns(40); 24949 verifyFormat("co_await [this](int a, int b) -> Task {\n" 24950 " co_return co_await foo();\n" 24951 "}(x, y);", 24952 Style); 24953 verifyFormat("co_await;"); 24954 } 24955 24956 TEST_F(FormatTest, CoroutineCoYield) { 24957 verifyFormat("int x = co_yield foo();"); 24958 verifyFormat("int x = (co_yield foo());"); 24959 verifyFormat("co_yield (42);"); 24960 verifyFormat("co_yield {42};"); 24961 verifyFormat("co_yield 42;"); 24962 verifyFormat("co_yield n++;"); 24963 verifyFormat("co_yield ++n;"); 24964 verifyFormat("co_yield;"); 24965 } 24966 24967 TEST_F(FormatTest, CoroutineCoReturn) { 24968 verifyFormat("co_return (42);"); 24969 verifyFormat("co_return;"); 24970 verifyFormat("co_return {};"); 24971 verifyFormat("co_return x;"); 24972 verifyFormat("co_return co_await foo();"); 24973 verifyFormat("co_return co_yield foo();"); 24974 } 24975 24976 TEST_F(FormatTest, EmptyShortBlock) { 24977 auto Style = getLLVMStyle(); 24978 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 24979 24980 verifyFormat("try {\n" 24981 " doA();\n" 24982 "} catch (Exception &e) {\n" 24983 " e.printStackTrace();\n" 24984 "}\n", 24985 Style); 24986 24987 verifyFormat("try {\n" 24988 " doA();\n" 24989 "} catch (Exception &e) {}\n", 24990 Style); 24991 } 24992 24993 TEST_F(FormatTest, ShortTemplatedArgumentLists) { 24994 auto Style = getLLVMStyle(); 24995 24996 verifyFormat("template <> struct S : Template<int (*)[]> {};\n", Style); 24997 verifyFormat("template <> struct S : Template<int (*)[10]> {};\n", Style); 24998 verifyFormat("struct Y : X<[] { return 0; }> {};", Style); 24999 verifyFormat("struct Y<[] { return 0; }> {};", Style); 25000 25001 verifyFormat("struct Z : X<decltype([] { return 0; }){}> {};", Style); 25002 verifyFormat("template <int N> struct Foo<char[N]> {};", Style); 25003 } 25004 25005 TEST_F(FormatTest, InsertBraces) { 25006 FormatStyle Style = getLLVMStyle(); 25007 Style.InsertBraces = true; 25008 25009 verifyFormat("// clang-format off\n" 25010 "// comment\n" 25011 "if (a) f();\n" 25012 "// clang-format on\n" 25013 "if (b) {\n" 25014 " g();\n" 25015 "}", 25016 "// clang-format off\n" 25017 "// comment\n" 25018 "if (a) f();\n" 25019 "// clang-format on\n" 25020 "if (b) g();", 25021 Style); 25022 25023 verifyFormat("if (a) {\n" 25024 " switch (b) {\n" 25025 " case 1:\n" 25026 " c = 0;\n" 25027 " break;\n" 25028 " default:\n" 25029 " c = 1;\n" 25030 " }\n" 25031 "}", 25032 "if (a)\n" 25033 " switch (b) {\n" 25034 " case 1:\n" 25035 " c = 0;\n" 25036 " break;\n" 25037 " default:\n" 25038 " c = 1;\n" 25039 " }", 25040 Style); 25041 25042 verifyFormat("for (auto node : nodes) {\n" 25043 " if (node) {\n" 25044 " break;\n" 25045 " }\n" 25046 "}", 25047 "for (auto node : nodes)\n" 25048 " if (node)\n" 25049 " break;", 25050 Style); 25051 25052 verifyFormat("for (auto node : nodes) {\n" 25053 " if (node)\n" 25054 "}", 25055 "for (auto node : nodes)\n" 25056 " if (node)", 25057 Style); 25058 25059 verifyFormat("do {\n" 25060 " --a;\n" 25061 "} while (a);", 25062 "do\n" 25063 " --a;\n" 25064 "while (a);", 25065 Style); 25066 25067 verifyFormat("if (i) {\n" 25068 " ++i;\n" 25069 "} else {\n" 25070 " --i;\n" 25071 "}", 25072 "if (i)\n" 25073 " ++i;\n" 25074 "else {\n" 25075 " --i;\n" 25076 "}", 25077 Style); 25078 25079 verifyFormat("void f() {\n" 25080 " while (j--) {\n" 25081 " while (i) {\n" 25082 " --i;\n" 25083 " }\n" 25084 " }\n" 25085 "}", 25086 "void f() {\n" 25087 " while (j--)\n" 25088 " while (i)\n" 25089 " --i;\n" 25090 "}", 25091 Style); 25092 25093 verifyFormat("f({\n" 25094 " if (a) {\n" 25095 " g();\n" 25096 " }\n" 25097 "});", 25098 "f({\n" 25099 " if (a)\n" 25100 " g();\n" 25101 "});", 25102 Style); 25103 25104 verifyFormat("if (a) {\n" 25105 " f();\n" 25106 "} else if (b) {\n" 25107 " g();\n" 25108 "} else {\n" 25109 " h();\n" 25110 "}", 25111 "if (a)\n" 25112 " f();\n" 25113 "else if (b)\n" 25114 " g();\n" 25115 "else\n" 25116 " h();", 25117 Style); 25118 25119 verifyFormat("if (a) {\n" 25120 " f();\n" 25121 "}\n" 25122 "// comment\n" 25123 "/* comment */", 25124 "if (a)\n" 25125 " f();\n" 25126 "// comment\n" 25127 "/* comment */", 25128 Style); 25129 25130 verifyFormat("if (a) {\n" 25131 " // foo\n" 25132 " // bar\n" 25133 " f();\n" 25134 "}", 25135 "if (a)\n" 25136 " // foo\n" 25137 " // bar\n" 25138 " f();", 25139 Style); 25140 25141 verifyFormat("if (a) { // comment\n" 25142 " // comment\n" 25143 " f();\n" 25144 "}", 25145 "if (a) // comment\n" 25146 " // comment\n" 25147 " f();", 25148 Style); 25149 25150 verifyFormat("if (a) {\n" 25151 " f(); // comment\n" 25152 "}", 25153 "if (a)\n" 25154 " f(); // comment", 25155 Style); 25156 25157 verifyFormat("if (a) {\n" 25158 " f();\n" 25159 "}\n" 25160 "#undef A\n" 25161 "#undef B", 25162 "if (a)\n" 25163 " f();\n" 25164 "#undef A\n" 25165 "#undef B", 25166 Style); 25167 25168 verifyFormat("if (a)\n" 25169 "#ifdef A\n" 25170 " f();\n" 25171 "#else\n" 25172 " g();\n" 25173 "#endif", 25174 Style); 25175 25176 verifyFormat("#if 0\n" 25177 "#elif 1\n" 25178 "#endif\n" 25179 "void f() {\n" 25180 " if (a) {\n" 25181 " g();\n" 25182 " }\n" 25183 "}", 25184 "#if 0\n" 25185 "#elif 1\n" 25186 "#endif\n" 25187 "void f() {\n" 25188 " if (a) g();\n" 25189 "}", 25190 Style); 25191 25192 Style.ColumnLimit = 15; 25193 25194 verifyFormat("#define A \\\n" 25195 " if (a) \\\n" 25196 " f();", 25197 Style); 25198 25199 verifyFormat("if (a + b >\n" 25200 " c) {\n" 25201 " f();\n" 25202 "}", 25203 "if (a + b > c)\n" 25204 " f();", 25205 Style); 25206 } 25207 25208 TEST_F(FormatTest, RemoveBraces) { 25209 FormatStyle Style = getLLVMStyle(); 25210 Style.RemoveBracesLLVM = true; 25211 25212 // The following test cases are fully-braced versions of the examples at 25213 // "llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single- 25214 // statement-bodies-of-if-else-loop-statements". 25215 25216 // Omit the braces since the body is simple and clearly associated with the 25217 // `if`. 25218 verifyFormat("if (isa<FunctionDecl>(D))\n" 25219 " handleFunctionDecl(D);\n" 25220 "else if (isa<VarDecl>(D))\n" 25221 " handleVarDecl(D);", 25222 "if (isa<FunctionDecl>(D)) {\n" 25223 " handleFunctionDecl(D);\n" 25224 "} else if (isa<VarDecl>(D)) {\n" 25225 " handleVarDecl(D);\n" 25226 "}", 25227 Style); 25228 25229 // Here we document the condition itself and not the body. 25230 verifyFormat("if (isa<VarDecl>(D)) {\n" 25231 " // It is necessary that we explain the situation with this\n" 25232 " // surprisingly long comment, so it would be unclear\n" 25233 " // without the braces whether the following statement is in\n" 25234 " // the scope of the `if`.\n" 25235 " // Because the condition is documented, we can't really\n" 25236 " // hoist this comment that applies to the body above the\n" 25237 " // `if`.\n" 25238 " handleOtherDecl(D);\n" 25239 "}", 25240 Style); 25241 25242 // Use braces on the outer `if` to avoid a potential dangling `else` 25243 // situation. 25244 verifyFormat("if (isa<VarDecl>(D)) {\n" 25245 " if (shouldProcessAttr(A))\n" 25246 " handleAttr(A);\n" 25247 "}", 25248 "if (isa<VarDecl>(D)) {\n" 25249 " if (shouldProcessAttr(A)) {\n" 25250 " handleAttr(A);\n" 25251 " }\n" 25252 "}", 25253 Style); 25254 25255 // Use braces for the `if` block to keep it uniform with the `else` block. 25256 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 25257 " handleFunctionDecl(D);\n" 25258 "} else {\n" 25259 " // In this `else` case, it is necessary that we explain the\n" 25260 " // situation with this surprisingly long comment, so it\n" 25261 " // would be unclear without the braces whether the\n" 25262 " // following statement is in the scope of the `if`.\n" 25263 " handleOtherDecl(D);\n" 25264 "}", 25265 Style); 25266 25267 // This should also omit braces. The `for` loop contains only a single 25268 // statement, so it shouldn't have braces. The `if` also only contains a 25269 // single simple statement (the `for` loop), so it also should omit braces. 25270 verifyFormat("if (isa<FunctionDecl>(D))\n" 25271 " for (auto *A : D.attrs())\n" 25272 " handleAttr(A);", 25273 "if (isa<FunctionDecl>(D)) {\n" 25274 " for (auto *A : D.attrs()) {\n" 25275 " handleAttr(A);\n" 25276 " }\n" 25277 "}", 25278 Style); 25279 25280 // Use braces for a `do-while` loop and its enclosing statement. 25281 verifyFormat("if (Tok->is(tok::l_brace)) {\n" 25282 " do {\n" 25283 " Tok = Tok->Next;\n" 25284 " } while (Tok);\n" 25285 "}", 25286 Style); 25287 25288 // Use braces for the outer `if` since the nested `for` is braced. 25289 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 25290 " for (auto *A : D.attrs()) {\n" 25291 " // In this `for` loop body, it is necessary that we\n" 25292 " // explain the situation with this surprisingly long\n" 25293 " // comment, forcing braces on the `for` block.\n" 25294 " handleAttr(A);\n" 25295 " }\n" 25296 "}", 25297 Style); 25298 25299 // Use braces on the outer block because there are more than two levels of 25300 // nesting. 25301 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 25302 " for (auto *A : D.attrs())\n" 25303 " for (ssize_t i : llvm::seq<ssize_t>(count))\n" 25304 " handleAttrOnDecl(D, A, i);\n" 25305 "}", 25306 "if (isa<FunctionDecl>(D)) {\n" 25307 " for (auto *A : D.attrs()) {\n" 25308 " for (ssize_t i : llvm::seq<ssize_t>(count)) {\n" 25309 " handleAttrOnDecl(D, A, i);\n" 25310 " }\n" 25311 " }\n" 25312 "}", 25313 Style); 25314 25315 // Use braces on the outer block because of a nested `if`; otherwise the 25316 // compiler would warn: `add explicit braces to avoid dangling else` 25317 verifyFormat("if (auto *D = dyn_cast<FunctionDecl>(D)) {\n" 25318 " if (shouldProcess(D))\n" 25319 " handleVarDecl(D);\n" 25320 " else\n" 25321 " markAsIgnored(D);\n" 25322 "}", 25323 "if (auto *D = dyn_cast<FunctionDecl>(D)) {\n" 25324 " if (shouldProcess(D)) {\n" 25325 " handleVarDecl(D);\n" 25326 " } else {\n" 25327 " markAsIgnored(D);\n" 25328 " }\n" 25329 "}", 25330 Style); 25331 25332 verifyFormat("// clang-format off\n" 25333 "// comment\n" 25334 "while (i > 0) { --i; }\n" 25335 "// clang-format on\n" 25336 "while (j < 0)\n" 25337 " ++j;", 25338 "// clang-format off\n" 25339 "// comment\n" 25340 "while (i > 0) { --i; }\n" 25341 "// clang-format on\n" 25342 "while (j < 0) { ++j; }", 25343 Style); 25344 25345 verifyFormat("if (a)\n" 25346 " b; // comment\n" 25347 "else if (c)\n" 25348 " d; /* comment */\n" 25349 "else\n" 25350 " e;", 25351 "if (a) {\n" 25352 " b; // comment\n" 25353 "} else if (c) {\n" 25354 " d; /* comment */\n" 25355 "} else {\n" 25356 " e;\n" 25357 "}", 25358 Style); 25359 25360 verifyFormat("if (a) {\n" 25361 " b;\n" 25362 " c;\n" 25363 "} else if (d) {\n" 25364 " e;\n" 25365 "}", 25366 Style); 25367 25368 verifyFormat("if (a) {\n" 25369 "#undef NDEBUG\n" 25370 " b;\n" 25371 "} else {\n" 25372 " c;\n" 25373 "}", 25374 Style); 25375 25376 verifyFormat("if (a) {\n" 25377 " // comment\n" 25378 "} else if (b) {\n" 25379 " c;\n" 25380 "}", 25381 Style); 25382 25383 verifyFormat("if (a) {\n" 25384 " b;\n" 25385 "} else {\n" 25386 " { c; }\n" 25387 "}", 25388 Style); 25389 25390 verifyFormat("if (a) {\n" 25391 " if (b) // comment\n" 25392 " c;\n" 25393 "} else if (d) {\n" 25394 " e;\n" 25395 "}", 25396 "if (a) {\n" 25397 " if (b) { // comment\n" 25398 " c;\n" 25399 " }\n" 25400 "} else if (d) {\n" 25401 " e;\n" 25402 "}", 25403 Style); 25404 25405 verifyFormat("if (a) {\n" 25406 " if (b) {\n" 25407 " c;\n" 25408 " // comment\n" 25409 " } else if (d) {\n" 25410 " e;\n" 25411 " }\n" 25412 "}", 25413 Style); 25414 25415 verifyFormat("if (a) {\n" 25416 " if (b)\n" 25417 " c;\n" 25418 "}", 25419 "if (a) {\n" 25420 " if (b) {\n" 25421 " c;\n" 25422 " }\n" 25423 "}", 25424 Style); 25425 25426 verifyFormat("if (a)\n" 25427 " if (b)\n" 25428 " c;\n" 25429 " else\n" 25430 " d;\n" 25431 "else\n" 25432 " e;", 25433 "if (a) {\n" 25434 " if (b) {\n" 25435 " c;\n" 25436 " } else {\n" 25437 " d;\n" 25438 " }\n" 25439 "} else {\n" 25440 " e;\n" 25441 "}", 25442 Style); 25443 25444 verifyFormat("if (a) {\n" 25445 " // comment\n" 25446 " if (b)\n" 25447 " c;\n" 25448 " else if (d)\n" 25449 " e;\n" 25450 "} else {\n" 25451 " g;\n" 25452 "}", 25453 "if (a) {\n" 25454 " // comment\n" 25455 " if (b) {\n" 25456 " c;\n" 25457 " } else if (d) {\n" 25458 " e;\n" 25459 " }\n" 25460 "} else {\n" 25461 " g;\n" 25462 "}", 25463 Style); 25464 25465 verifyFormat("if (a)\n" 25466 " b;\n" 25467 "else if (c)\n" 25468 " d;\n" 25469 "else\n" 25470 " e;", 25471 "if (a) {\n" 25472 " b;\n" 25473 "} else {\n" 25474 " if (c) {\n" 25475 " d;\n" 25476 " } else {\n" 25477 " e;\n" 25478 " }\n" 25479 "}", 25480 Style); 25481 25482 verifyFormat("if (a) {\n" 25483 " if (b)\n" 25484 " c;\n" 25485 " else if (d)\n" 25486 " e;\n" 25487 "} else {\n" 25488 " g;\n" 25489 "}", 25490 "if (a) {\n" 25491 " if (b)\n" 25492 " c;\n" 25493 " else {\n" 25494 " if (d)\n" 25495 " e;\n" 25496 " }\n" 25497 "} else {\n" 25498 " g;\n" 25499 "}", 25500 Style); 25501 25502 verifyFormat("if (isa<VarDecl>(D)) {\n" 25503 " for (auto *A : D.attrs())\n" 25504 " if (shouldProcessAttr(A))\n" 25505 " handleAttr(A);\n" 25506 "}", 25507 "if (isa<VarDecl>(D)) {\n" 25508 " for (auto *A : D.attrs()) {\n" 25509 " if (shouldProcessAttr(A)) {\n" 25510 " handleAttr(A);\n" 25511 " }\n" 25512 " }\n" 25513 "}", 25514 Style); 25515 25516 verifyFormat("do {\n" 25517 " ++I;\n" 25518 "} while (hasMore() && Filter(*I));", 25519 "do { ++I; } while (hasMore() && Filter(*I));", Style); 25520 25521 verifyFormat("if (a)\n" 25522 " if (b)\n" 25523 " c;\n" 25524 " else {\n" 25525 " if (d)\n" 25526 " e;\n" 25527 " }\n" 25528 "else\n" 25529 " f;", 25530 Style); 25531 25532 verifyFormat("if (a)\n" 25533 " if (b)\n" 25534 " c;\n" 25535 " else {\n" 25536 " if (d)\n" 25537 " e;\n" 25538 " else if (f)\n" 25539 " g;\n" 25540 " }\n" 25541 "else\n" 25542 " h;", 25543 Style); 25544 25545 verifyFormat("if (a) {\n" 25546 " b;\n" 25547 "} else if (c) {\n" 25548 " d;\n" 25549 " e;\n" 25550 "}", 25551 "if (a) {\n" 25552 " b;\n" 25553 "} else {\n" 25554 " if (c) {\n" 25555 " d;\n" 25556 " e;\n" 25557 " }\n" 25558 "}", 25559 Style); 25560 25561 verifyFormat("if (a) {\n" 25562 " b;\n" 25563 " c;\n" 25564 "} else if (d) {\n" 25565 " e;\n" 25566 " f;\n" 25567 "}", 25568 "if (a) {\n" 25569 " b;\n" 25570 " c;\n" 25571 "} else {\n" 25572 " if (d) {\n" 25573 " e;\n" 25574 " f;\n" 25575 " }\n" 25576 "}", 25577 Style); 25578 25579 verifyFormat("if (a) {\n" 25580 " b;\n" 25581 "} else if (c) {\n" 25582 " d;\n" 25583 "} else {\n" 25584 " e;\n" 25585 " f;\n" 25586 "}", 25587 "if (a) {\n" 25588 " b;\n" 25589 "} else {\n" 25590 " if (c) {\n" 25591 " d;\n" 25592 " } else {\n" 25593 " e;\n" 25594 " f;\n" 25595 " }\n" 25596 "}", 25597 Style); 25598 25599 verifyFormat("if (a) {\n" 25600 " b;\n" 25601 "} else if (c) {\n" 25602 " d;\n" 25603 "} else if (e) {\n" 25604 " f;\n" 25605 " g;\n" 25606 "}", 25607 "if (a) {\n" 25608 " b;\n" 25609 "} else {\n" 25610 " if (c) {\n" 25611 " d;\n" 25612 " } else if (e) {\n" 25613 " f;\n" 25614 " g;\n" 25615 " }\n" 25616 "}", 25617 Style); 25618 25619 verifyFormat("if (a) {\n" 25620 " if (b)\n" 25621 " c;\n" 25622 " else if (d) {\n" 25623 " e;\n" 25624 " f;\n" 25625 " }\n" 25626 "} else {\n" 25627 " g;\n" 25628 "}", 25629 "if (a) {\n" 25630 " if (b)\n" 25631 " c;\n" 25632 " else {\n" 25633 " if (d) {\n" 25634 " e;\n" 25635 " f;\n" 25636 " }\n" 25637 " }\n" 25638 "} else {\n" 25639 " g;\n" 25640 "}", 25641 Style); 25642 25643 verifyFormat("if (a)\n" 25644 " if (b)\n" 25645 " c;\n" 25646 " else {\n" 25647 " if (d) {\n" 25648 " e;\n" 25649 " f;\n" 25650 " }\n" 25651 " }\n" 25652 "else\n" 25653 " g;", 25654 Style); 25655 25656 verifyFormat("if (a) {\n" 25657 " b;\n" 25658 " c;\n" 25659 "} else { // comment\n" 25660 " if (d) {\n" 25661 " e;\n" 25662 " f;\n" 25663 " }\n" 25664 "}", 25665 Style); 25666 25667 verifyFormat("if (a)\n" 25668 " b;\n" 25669 "else if (c)\n" 25670 " while (d)\n" 25671 " e;\n" 25672 "// comment", 25673 "if (a)\n" 25674 "{\n" 25675 " b;\n" 25676 "} else if (c) {\n" 25677 " while (d) {\n" 25678 " e;\n" 25679 " }\n" 25680 "}\n" 25681 "// comment", 25682 Style); 25683 25684 verifyFormat("if (a) {\n" 25685 " b;\n" 25686 "} else if (c) {\n" 25687 " d;\n" 25688 "} else {\n" 25689 " e;\n" 25690 " g;\n" 25691 "}", 25692 Style); 25693 25694 verifyFormat("if (a) {\n" 25695 " b;\n" 25696 "} else if (c) {\n" 25697 " d;\n" 25698 "} else {\n" 25699 " e;\n" 25700 "} // comment", 25701 Style); 25702 25703 verifyFormat("int abs = [](int i) {\n" 25704 " if (i >= 0)\n" 25705 " return i;\n" 25706 " return -i;\n" 25707 "};", 25708 "int abs = [](int i) {\n" 25709 " if (i >= 0) {\n" 25710 " return i;\n" 25711 " }\n" 25712 " return -i;\n" 25713 "};", 25714 Style); 25715 25716 verifyFormat("if (a)\n" 25717 " foo();\n" 25718 "else\n" 25719 " bar();", 25720 "if (a)\n" 25721 "{\n" 25722 " foo();\n" 25723 "}\n" 25724 "else\n" 25725 "{\n" 25726 " bar();\n" 25727 "}", 25728 Style); 25729 25730 verifyFormat("if (a)\n" 25731 " foo();\n" 25732 "// comment\n" 25733 "else\n" 25734 " bar();", 25735 "if (a) {\n" 25736 " foo();\n" 25737 "}\n" 25738 "// comment\n" 25739 "else {\n" 25740 " bar();\n" 25741 "}", 25742 Style); 25743 25744 verifyFormat("if (a) {\n" 25745 "Label:\n" 25746 "}", 25747 Style); 25748 25749 verifyFormat("if (a) {\n" 25750 "Label:\n" 25751 " f();\n" 25752 "}", 25753 Style); 25754 25755 verifyFormat("if (a) {\n" 25756 " f();\n" 25757 "Label:\n" 25758 "}", 25759 Style); 25760 25761 verifyFormat("if consteval {\n" 25762 " f();\n" 25763 "} else {\n" 25764 " g();\n" 25765 "}", 25766 Style); 25767 25768 verifyFormat("if not consteval {\n" 25769 " f();\n" 25770 "} else if (a) {\n" 25771 " g();\n" 25772 "}", 25773 Style); 25774 25775 verifyFormat("if !consteval {\n" 25776 " g();\n" 25777 "}", 25778 Style); 25779 25780 Style.ColumnLimit = 65; 25781 verifyFormat("if (condition) {\n" 25782 " ff(Indices,\n" 25783 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 25784 "} else {\n" 25785 " ff(Indices,\n" 25786 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 25787 "}", 25788 Style); 25789 25790 Style.ColumnLimit = 20; 25791 25792 verifyFormat("int ab = [](int i) {\n" 25793 " if (i > 0) {\n" 25794 " i = 12345678 -\n" 25795 " i;\n" 25796 " }\n" 25797 " return i;\n" 25798 "};", 25799 Style); 25800 25801 verifyFormat("if (a) {\n" 25802 " b = c + // 1 -\n" 25803 " d;\n" 25804 "}", 25805 Style); 25806 25807 verifyFormat("if (a) {\n" 25808 " b = c >= 0 ? d\n" 25809 " : e;\n" 25810 "}", 25811 "if (a) {\n" 25812 " b = c >= 0 ? d : e;\n" 25813 "}", 25814 Style); 25815 25816 verifyFormat("if (a)\n" 25817 " b = c > 0 ? d : e;", 25818 "if (a) {\n" 25819 " b = c > 0 ? d : e;\n" 25820 "}", 25821 Style); 25822 25823 verifyFormat("if (-b >=\n" 25824 " c) { // Keep.\n" 25825 " foo();\n" 25826 "} else {\n" 25827 " bar();\n" 25828 "}", 25829 "if (-b >= c) { // Keep.\n" 25830 " foo();\n" 25831 "} else {\n" 25832 " bar();\n" 25833 "}", 25834 Style); 25835 25836 verifyFormat("if (a) /* Remove. */\n" 25837 " f();\n" 25838 "else\n" 25839 " g();", 25840 "if (a) <% /* Remove. */\n" 25841 " f();\n" 25842 "%> else <%\n" 25843 " g();\n" 25844 "%>", 25845 Style); 25846 25847 verifyFormat("while (\n" 25848 " !i--) <% // Keep.\n" 25849 " foo();\n" 25850 "%>", 25851 "while (!i--) <% // Keep.\n" 25852 " foo();\n" 25853 "%>", 25854 Style); 25855 25856 verifyFormat("for (int &i : chars)\n" 25857 " ++i;", 25858 "for (int &i :\n" 25859 " chars) {\n" 25860 " ++i;\n" 25861 "}", 25862 Style); 25863 25864 verifyFormat("if (a)\n" 25865 " b;\n" 25866 "else if (c) {\n" 25867 " d;\n" 25868 " e;\n" 25869 "} else\n" 25870 " f = g(foo, bar,\n" 25871 " baz);", 25872 "if (a)\n" 25873 " b;\n" 25874 "else {\n" 25875 " if (c) {\n" 25876 " d;\n" 25877 " e;\n" 25878 " } else\n" 25879 " f = g(foo, bar, baz);\n" 25880 "}", 25881 Style); 25882 25883 Style.ColumnLimit = 0; 25884 verifyFormat("if (a)\n" 25885 " b234567890223456789032345678904234567890 = " 25886 "c234567890223456789032345678904234567890;", 25887 "if (a) {\n" 25888 " b234567890223456789032345678904234567890 = " 25889 "c234567890223456789032345678904234567890;\n" 25890 "}", 25891 Style); 25892 25893 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 25894 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 25895 Style.BraceWrapping.BeforeElse = true; 25896 25897 Style.ColumnLimit = 65; 25898 25899 verifyFormat("if (condition)\n" 25900 "{\n" 25901 " ff(Indices,\n" 25902 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 25903 "}\n" 25904 "else\n" 25905 "{\n" 25906 " ff(Indices,\n" 25907 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 25908 "}", 25909 "if (condition) {\n" 25910 " ff(Indices,\n" 25911 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 25912 "} else {\n" 25913 " ff(Indices,\n" 25914 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 25915 "}", 25916 Style); 25917 25918 verifyFormat("if (a)\n" 25919 "{ //\n" 25920 " foo();\n" 25921 "}", 25922 "if (a) { //\n" 25923 " foo();\n" 25924 "}", 25925 Style); 25926 25927 Style.ColumnLimit = 20; 25928 25929 verifyFormat("int ab = [](int i) {\n" 25930 " if (i > 0)\n" 25931 " {\n" 25932 " i = 12345678 -\n" 25933 " i;\n" 25934 " }\n" 25935 " return i;\n" 25936 "};", 25937 "int ab = [](int i) {\n" 25938 " if (i > 0) {\n" 25939 " i = 12345678 -\n" 25940 " i;\n" 25941 " }\n" 25942 " return i;\n" 25943 "};", 25944 Style); 25945 25946 verifyFormat("if (a)\n" 25947 "{\n" 25948 " b = c + // 1 -\n" 25949 " d;\n" 25950 "}", 25951 "if (a) {\n" 25952 " b = c + // 1 -\n" 25953 " d;\n" 25954 "}", 25955 Style); 25956 25957 verifyFormat("if (a)\n" 25958 "{\n" 25959 " b = c >= 0 ? d\n" 25960 " : e;\n" 25961 "}", 25962 "if (a) {\n" 25963 " b = c >= 0 ? d : e;\n" 25964 "}", 25965 Style); 25966 25967 verifyFormat("if (a)\n" 25968 " b = c > 0 ? d : e;", 25969 "if (a)\n" 25970 "{\n" 25971 " b = c > 0 ? d : e;\n" 25972 "}", 25973 Style); 25974 25975 verifyFormat("if (foo + bar <=\n" 25976 " baz)\n" 25977 "{\n" 25978 " func(arg1, arg2);\n" 25979 "}", 25980 "if (foo + bar <= baz) {\n" 25981 " func(arg1, arg2);\n" 25982 "}", 25983 Style); 25984 25985 verifyFormat("if (foo + bar < baz)\n" 25986 " func(arg1, arg2);\n" 25987 "else\n" 25988 " func();", 25989 "if (foo + bar < baz)\n" 25990 "<%\n" 25991 " func(arg1, arg2);\n" 25992 "%>\n" 25993 "else\n" 25994 "<%\n" 25995 " func();\n" 25996 "%>", 25997 Style); 25998 25999 verifyFormat("while (i--)\n" 26000 "<% // Keep.\n" 26001 " foo();\n" 26002 "%>", 26003 "while (i--) <% // Keep.\n" 26004 " foo();\n" 26005 "%>", 26006 Style); 26007 26008 verifyFormat("for (int &i : chars)\n" 26009 " ++i;", 26010 "for (int &i : chars)\n" 26011 "{\n" 26012 " ++i;\n" 26013 "}", 26014 Style); 26015 } 26016 26017 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndent) { 26018 auto Style = getLLVMStyle(); 26019 26020 StringRef Short = "functionCall(paramA, paramB, paramC);\n" 26021 "void functionDecl(int a, int b, int c);"; 26022 26023 StringRef Medium = "functionCall(paramA, paramB, paramC, paramD, paramE, " 26024 "paramF, paramG, paramH, paramI);\n" 26025 "void functionDecl(int argumentA, int argumentB, int " 26026 "argumentC, int argumentD, int argumentE);"; 26027 26028 verifyFormat(Short, Style); 26029 26030 StringRef NoBreak = "functionCall(paramA, paramB, paramC, paramD, paramE, " 26031 "paramF, paramG, paramH,\n" 26032 " paramI);\n" 26033 "void functionDecl(int argumentA, int argumentB, int " 26034 "argumentC, int argumentD,\n" 26035 " int argumentE);"; 26036 26037 verifyFormat(NoBreak, Medium, Style); 26038 verifyFormat(NoBreak, 26039 "functionCall(\n" 26040 " paramA,\n" 26041 " paramB,\n" 26042 " paramC,\n" 26043 " paramD,\n" 26044 " paramE,\n" 26045 " paramF,\n" 26046 " paramG,\n" 26047 " paramH,\n" 26048 " paramI\n" 26049 ");\n" 26050 "void functionDecl(\n" 26051 " int argumentA,\n" 26052 " int argumentB,\n" 26053 " int argumentC,\n" 26054 " int argumentD,\n" 26055 " int argumentE\n" 26056 ");", 26057 Style); 26058 26059 verifyFormat("outerFunctionCall(nestedFunctionCall(argument1),\n" 26060 " nestedLongFunctionCall(argument1, " 26061 "argument2, argument3,\n" 26062 " argument4, " 26063 "argument5));", 26064 Style); 26065 26066 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 26067 26068 verifyFormat(Short, Style); 26069 verifyFormat( 26070 "functionCall(\n" 26071 " paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, " 26072 "paramI\n" 26073 ");\n" 26074 "void functionDecl(\n" 26075 " int argumentA, int argumentB, int argumentC, int argumentD, int " 26076 "argumentE\n" 26077 ");", 26078 Medium, Style); 26079 26080 Style.AllowAllArgumentsOnNextLine = false; 26081 Style.AllowAllParametersOfDeclarationOnNextLine = false; 26082 26083 verifyFormat(Short, Style); 26084 verifyFormat( 26085 "functionCall(\n" 26086 " paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, " 26087 "paramI\n" 26088 ");\n" 26089 "void functionDecl(\n" 26090 " int argumentA, int argumentB, int argumentC, int argumentD, int " 26091 "argumentE\n" 26092 ");", 26093 Medium, Style); 26094 26095 Style.BinPackArguments = false; 26096 Style.BinPackParameters = false; 26097 26098 verifyFormat(Short, Style); 26099 26100 verifyFormat("functionCall(\n" 26101 " paramA,\n" 26102 " paramB,\n" 26103 " paramC,\n" 26104 " paramD,\n" 26105 " paramE,\n" 26106 " paramF,\n" 26107 " paramG,\n" 26108 " paramH,\n" 26109 " paramI\n" 26110 ");\n" 26111 "void functionDecl(\n" 26112 " int argumentA,\n" 26113 " int argumentB,\n" 26114 " int argumentC,\n" 26115 " int argumentD,\n" 26116 " int argumentE\n" 26117 ");", 26118 Medium, Style); 26119 26120 verifyFormat("outerFunctionCall(\n" 26121 " nestedFunctionCall(argument1),\n" 26122 " nestedLongFunctionCall(\n" 26123 " argument1,\n" 26124 " argument2,\n" 26125 " argument3,\n" 26126 " argument4,\n" 26127 " argument5\n" 26128 " )\n" 26129 ");", 26130 Style); 26131 26132 verifyFormat("int a = (int)b;", Style); 26133 verifyFormat("int a = (int)b;", 26134 "int a = (\n" 26135 " int\n" 26136 ") b;", 26137 Style); 26138 26139 verifyFormat("return (true);", Style); 26140 verifyFormat("return (true);", 26141 "return (\n" 26142 " true\n" 26143 ");", 26144 Style); 26145 26146 verifyFormat("void foo();", Style); 26147 verifyFormat("void foo();", 26148 "void foo(\n" 26149 ");", 26150 Style); 26151 26152 verifyFormat("void foo() {}", Style); 26153 verifyFormat("void foo() {}", 26154 "void foo(\n" 26155 ") {\n" 26156 "}", 26157 Style); 26158 26159 verifyFormat("auto string = std::string();", Style); 26160 verifyFormat("auto string = std::string();", 26161 "auto string = std::string(\n" 26162 ");", 26163 Style); 26164 26165 verifyFormat("void (*functionPointer)() = nullptr;", Style); 26166 verifyFormat("void (*functionPointer)() = nullptr;", 26167 "void (\n" 26168 " *functionPointer\n" 26169 ")\n" 26170 "(\n" 26171 ") = nullptr;", 26172 Style); 26173 } 26174 26175 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentIfStatement) { 26176 auto Style = getLLVMStyle(); 26177 26178 verifyFormat("if (foo()) {\n" 26179 " return;\n" 26180 "}", 26181 Style); 26182 26183 verifyFormat("if (quitelongarg !=\n" 26184 " (alsolongarg - 1)) { // ABC is a very longgggggggggggg " 26185 "comment\n" 26186 " return;\n" 26187 "}", 26188 Style); 26189 26190 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 26191 26192 verifyFormat("if (foo()) {\n" 26193 " return;\n" 26194 "}", 26195 Style); 26196 26197 verifyFormat("if (quitelongarg !=\n" 26198 " (alsolongarg - 1)) { // ABC is a very longgggggggggggg " 26199 "comment\n" 26200 " return;\n" 26201 "}", 26202 Style); 26203 } 26204 26205 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentForStatement) { 26206 auto Style = getLLVMStyle(); 26207 26208 verifyFormat("for (int i = 0; i < 5; ++i) {\n" 26209 " doSomething();\n" 26210 "}", 26211 Style); 26212 26213 verifyFormat("for (int myReallyLongCountVariable = 0; " 26214 "myReallyLongCountVariable < count;\n" 26215 " myReallyLongCountVariable++) {\n" 26216 " doSomething();\n" 26217 "}", 26218 Style); 26219 26220 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 26221 26222 verifyFormat("for (int i = 0; i < 5; ++i) {\n" 26223 " doSomething();\n" 26224 "}", 26225 Style); 26226 26227 verifyFormat("for (int myReallyLongCountVariable = 0; " 26228 "myReallyLongCountVariable < count;\n" 26229 " myReallyLongCountVariable++) {\n" 26230 " doSomething();\n" 26231 "}", 26232 Style); 26233 } 26234 26235 TEST_F(FormatTest, UnderstandsDigraphs) { 26236 verifyFormat("int arr<:5:> = {};"); 26237 verifyFormat("int arr[5] = <%%>;"); 26238 verifyFormat("int arr<:::qualified_variable:> = {};"); 26239 verifyFormat("int arr[::qualified_variable] = <%%>;"); 26240 verifyFormat("%:include <header>"); 26241 verifyFormat("%:define A x##y"); 26242 verifyFormat("#define A x%:%:y"); 26243 } 26244 26245 TEST_F(FormatTest, AlignArrayOfStructuresLeftAlignmentNonSquare) { 26246 auto Style = getLLVMStyle(); 26247 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 26248 Style.AlignConsecutiveAssignments.Enabled = true; 26249 Style.AlignConsecutiveDeclarations.Enabled = true; 26250 26251 // The AlignArray code is incorrect for non square Arrays and can cause 26252 // crashes, these tests assert that the array is not changed but will 26253 // also act as regression tests for when it is properly fixed 26254 verifyFormat("struct test demo[] = {\n" 26255 " {1, 2},\n" 26256 " {3, 4, 5},\n" 26257 " {6, 7, 8}\n" 26258 "};", 26259 Style); 26260 verifyFormat("struct test demo[] = {\n" 26261 " {1, 2, 3, 4, 5},\n" 26262 " {3, 4, 5},\n" 26263 " {6, 7, 8}\n" 26264 "};", 26265 Style); 26266 verifyFormat("struct test demo[] = {\n" 26267 " {1, 2, 3, 4, 5},\n" 26268 " {3, 4, 5},\n" 26269 " {6, 7, 8, 9, 10, 11, 12}\n" 26270 "};", 26271 Style); 26272 verifyFormat("struct test demo[] = {\n" 26273 " {1, 2, 3},\n" 26274 " {3, 4, 5},\n" 26275 " {6, 7, 8, 9, 10, 11, 12}\n" 26276 "};", 26277 Style); 26278 26279 verifyFormat("S{\n" 26280 " {},\n" 26281 " {},\n" 26282 " {a, b}\n" 26283 "};", 26284 Style); 26285 verifyFormat("S{\n" 26286 " {},\n" 26287 " {},\n" 26288 " {a, b},\n" 26289 "};", 26290 Style); 26291 verifyFormat("void foo() {\n" 26292 " auto thing = test{\n" 26293 " {\n" 26294 " {13}, {something}, // A\n" 26295 " }\n" 26296 " };\n" 26297 "}", 26298 "void foo() {\n" 26299 " auto thing = test{\n" 26300 " {\n" 26301 " {13},\n" 26302 " {something}, // A\n" 26303 " }\n" 26304 " };\n" 26305 "}", 26306 Style); 26307 } 26308 26309 TEST_F(FormatTest, AlignArrayOfStructuresRightAlignmentNonSquare) { 26310 auto Style = getLLVMStyle(); 26311 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 26312 Style.AlignConsecutiveAssignments.Enabled = true; 26313 Style.AlignConsecutiveDeclarations.Enabled = true; 26314 26315 // The AlignArray code is incorrect for non square Arrays and can cause 26316 // crashes, these tests assert that the array is not changed but will 26317 // also act as regression tests for when it is properly fixed 26318 verifyFormat("struct test demo[] = {\n" 26319 " {1, 2},\n" 26320 " {3, 4, 5},\n" 26321 " {6, 7, 8}\n" 26322 "};", 26323 Style); 26324 verifyFormat("struct test demo[] = {\n" 26325 " {1, 2, 3, 4, 5},\n" 26326 " {3, 4, 5},\n" 26327 " {6, 7, 8}\n" 26328 "};", 26329 Style); 26330 verifyFormat("struct test demo[] = {\n" 26331 " {1, 2, 3, 4, 5},\n" 26332 " {3, 4, 5},\n" 26333 " {6, 7, 8, 9, 10, 11, 12}\n" 26334 "};", 26335 Style); 26336 verifyFormat("struct test demo[] = {\n" 26337 " {1, 2, 3},\n" 26338 " {3, 4, 5},\n" 26339 " {6, 7, 8, 9, 10, 11, 12}\n" 26340 "};", 26341 Style); 26342 26343 verifyFormat("S{\n" 26344 " {},\n" 26345 " {},\n" 26346 " {a, b}\n" 26347 "};", 26348 Style); 26349 verifyFormat("S{\n" 26350 " {},\n" 26351 " {},\n" 26352 " {a, b},\n" 26353 "};", 26354 Style); 26355 verifyFormat("void foo() {\n" 26356 " auto thing = test{\n" 26357 " {\n" 26358 " {13}, {something}, // A\n" 26359 " }\n" 26360 " };\n" 26361 "}", 26362 "void foo() {\n" 26363 " auto thing = test{\n" 26364 " {\n" 26365 " {13},\n" 26366 " {something}, // A\n" 26367 " }\n" 26368 " };\n" 26369 "}", 26370 Style); 26371 } 26372 26373 TEST_F(FormatTest, FormatsVariableTemplates) { 26374 verifyFormat("inline bool var = is_integral_v<int> && is_signed_v<int>;"); 26375 verifyFormat("template <typename T> " 26376 "inline bool var = is_integral_v<T> && is_signed_v<T>;"); 26377 } 26378 26379 } // namespace 26380 } // namespace format 26381 } // namespace clang 26382