1 //===- unittest/Format/FormatTest.cpp - Formatting unit tests -------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "clang/Format/Format.h" 10 11 #include "../Tooling/ReplacementTest.h" 12 #include "FormatTestUtils.h" 13 14 #include "llvm/Support/Debug.h" 15 #include "llvm/Support/MemoryBuffer.h" 16 #include "gtest/gtest.h" 17 18 #define DEBUG_TYPE "format-test" 19 20 using clang::tooling::ReplacementTest; 21 using clang::tooling::toReplacements; 22 using testing::ScopedTrace; 23 24 namespace clang { 25 namespace format { 26 namespace { 27 28 FormatStyle getGoogleStyle() { return getGoogleStyle(FormatStyle::LK_Cpp); } 29 30 class FormatTest : public ::testing::Test { 31 protected: 32 enum StatusCheck { SC_ExpectComplete, SC_ExpectIncomplete, SC_DoNotCheck }; 33 34 std::string format(llvm::StringRef Code, 35 const FormatStyle &Style = getLLVMStyle(), 36 StatusCheck CheckComplete = SC_ExpectComplete) { 37 LLVM_DEBUG(llvm::errs() << "---\n"); 38 LLVM_DEBUG(llvm::errs() << Code << "\n\n"); 39 std::vector<tooling::Range> Ranges(1, tooling::Range(0, Code.size())); 40 FormattingAttemptStatus Status; 41 tooling::Replacements Replaces = 42 reformat(Style, Code, Ranges, "<stdin>", &Status); 43 if (CheckComplete != SC_DoNotCheck) { 44 bool ExpectedCompleteFormat = CheckComplete == SC_ExpectComplete; 45 EXPECT_EQ(ExpectedCompleteFormat, Status.FormatComplete) 46 << Code << "\n\n"; 47 } 48 ReplacementCount = Replaces.size(); 49 auto Result = applyAllReplacements(Code, Replaces); 50 EXPECT_TRUE(static_cast<bool>(Result)); 51 LLVM_DEBUG(llvm::errs() << "\n" << *Result << "\n\n"); 52 return *Result; 53 } 54 55 FormatStyle getStyleWithColumns(FormatStyle Style, unsigned ColumnLimit) { 56 Style.ColumnLimit = ColumnLimit; 57 return Style; 58 } 59 60 FormatStyle getLLVMStyleWithColumns(unsigned ColumnLimit) { 61 return getStyleWithColumns(getLLVMStyle(), ColumnLimit); 62 } 63 64 FormatStyle getGoogleStyleWithColumns(unsigned ColumnLimit) { 65 return getStyleWithColumns(getGoogleStyle(), ColumnLimit); 66 } 67 68 void _verifyFormat(const char *File, int Line, llvm::StringRef Expected, 69 llvm::StringRef Code, 70 const FormatStyle &Style = getLLVMStyle()) { 71 ScopedTrace t(File, Line, ::testing::Message() << Code.str()); 72 EXPECT_EQ(Expected.str(), format(Expected, Style)) 73 << "Expected code is not stable"; 74 EXPECT_EQ(Expected.str(), format(Code, Style)); 75 if (Style.Language == FormatStyle::LK_Cpp) { 76 // Objective-C++ is a superset of C++, so everything checked for C++ 77 // needs to be checked for Objective-C++ as well. 78 FormatStyle ObjCStyle = Style; 79 ObjCStyle.Language = FormatStyle::LK_ObjC; 80 EXPECT_EQ(Expected.str(), format(test::messUp(Code), ObjCStyle)); 81 } 82 } 83 84 void _verifyFormat(const char *File, int Line, llvm::StringRef Code, 85 const FormatStyle &Style = getLLVMStyle()) { 86 _verifyFormat(File, Line, Code, test::messUp(Code), Style); 87 } 88 89 void _verifyIncompleteFormat(const char *File, int Line, llvm::StringRef Code, 90 const FormatStyle &Style = getLLVMStyle()) { 91 ScopedTrace t(File, Line, ::testing::Message() << Code.str()); 92 EXPECT_EQ(Code.str(), 93 format(test::messUp(Code), Style, SC_ExpectIncomplete)); 94 } 95 96 void _verifyIndependentOfContext(const char *File, int Line, 97 llvm::StringRef Text, 98 const FormatStyle &Style = getLLVMStyle()) { 99 _verifyFormat(File, Line, Text, Style); 100 _verifyFormat(File, Line, llvm::Twine("void f() { " + Text + " }").str(), 101 Style); 102 } 103 104 /// \brief Verify that clang-format does not crash on the given input. 105 void verifyNoCrash(llvm::StringRef Code, 106 const FormatStyle &Style = getLLVMStyle()) { 107 format(Code, Style, SC_DoNotCheck); 108 } 109 110 int ReplacementCount; 111 }; 112 113 #define verifyIndependentOfContext(...) \ 114 _verifyIndependentOfContext(__FILE__, __LINE__, __VA_ARGS__) 115 #define verifyIncompleteFormat(...) \ 116 _verifyIncompleteFormat(__FILE__, __LINE__, __VA_ARGS__) 117 #define verifyFormat(...) _verifyFormat(__FILE__, __LINE__, __VA_ARGS__) 118 #define verifyGoogleFormat(Code) verifyFormat(Code, getGoogleStyle()) 119 120 TEST_F(FormatTest, MessUp) { 121 EXPECT_EQ("1 2 3", test::messUp("1 2 3")); 122 EXPECT_EQ("1 2 3\n", test::messUp("1\n2\n3\n")); 123 EXPECT_EQ("a\n//b\nc", test::messUp("a\n//b\nc")); 124 EXPECT_EQ("a\n#b\nc", test::messUp("a\n#b\nc")); 125 EXPECT_EQ("a\n#b c d\ne", test::messUp("a\n#b\\\nc\\\nd\ne")); 126 } 127 128 TEST_F(FormatTest, DefaultLLVMStyleIsCpp) { 129 EXPECT_EQ(FormatStyle::LK_Cpp, getLLVMStyle().Language); 130 } 131 132 TEST_F(FormatTest, LLVMStyleOverride) { 133 EXPECT_EQ(FormatStyle::LK_Proto, 134 getLLVMStyle(FormatStyle::LK_Proto).Language); 135 } 136 137 //===----------------------------------------------------------------------===// 138 // Basic function tests. 139 //===----------------------------------------------------------------------===// 140 141 TEST_F(FormatTest, DoesNotChangeCorrectlyFormattedCode) { 142 EXPECT_EQ(";", format(";")); 143 } 144 145 TEST_F(FormatTest, FormatsGlobalStatementsAt0) { 146 EXPECT_EQ("int i;", format(" int i;")); 147 EXPECT_EQ("\nint i;", format(" \n\t \v \f int i;")); 148 EXPECT_EQ("int i;\nint j;", format(" int i; int j;")); 149 EXPECT_EQ("int i;\nint j;", format(" int i;\n int j;")); 150 } 151 152 TEST_F(FormatTest, FormatsUnwrappedLinesAtFirstFormat) { 153 EXPECT_EQ("int i;", format("int\ni;")); 154 } 155 156 TEST_F(FormatTest, FormatsNestedBlockStatements) { 157 EXPECT_EQ("{\n {\n {}\n }\n}", format("{{{}}}")); 158 } 159 160 TEST_F(FormatTest, FormatsNestedCall) { 161 verifyFormat("Method(f1, f2(f3));"); 162 verifyFormat("Method(f1(f2, f3()));"); 163 verifyFormat("Method(f1(f2, (f3())));"); 164 } 165 166 TEST_F(FormatTest, NestedNameSpecifiers) { 167 verifyFormat("vector<::Type> v;"); 168 verifyFormat("::ns::SomeFunction(::ns::SomeOtherFunction())"); 169 verifyFormat("static constexpr bool Bar = decltype(bar())::value;"); 170 verifyFormat("static constexpr bool Bar = typeof(bar())::value;"); 171 verifyFormat("static constexpr bool Bar = __underlying_type(bar())::value;"); 172 verifyFormat("static constexpr bool Bar = _Atomic(bar())::value;"); 173 verifyFormat("bool a = 2 < ::SomeFunction();"); 174 verifyFormat("ALWAYS_INLINE ::std::string getName();"); 175 verifyFormat("some::string getName();"); 176 } 177 178 TEST_F(FormatTest, OnlyGeneratesNecessaryReplacements) { 179 EXPECT_EQ("if (a) {\n" 180 " f();\n" 181 "}", 182 format("if(a){f();}")); 183 EXPECT_EQ(4, ReplacementCount); 184 EXPECT_EQ("if (a) {\n" 185 " f();\n" 186 "}", 187 format("if (a) {\n" 188 " f();\n" 189 "}")); 190 EXPECT_EQ(0, ReplacementCount); 191 EXPECT_EQ("/*\r\n" 192 "\r\n" 193 "*/\r\n", 194 format("/*\r\n" 195 "\r\n" 196 "*/\r\n")); 197 EXPECT_EQ(0, ReplacementCount); 198 } 199 200 TEST_F(FormatTest, RemovesEmptyLines) { 201 EXPECT_EQ("class C {\n" 202 " int i;\n" 203 "};", 204 format("class C {\n" 205 " int i;\n" 206 "\n" 207 "};")); 208 209 // Don't remove empty lines at the start of namespaces or extern "C" blocks. 210 EXPECT_EQ("namespace N {\n" 211 "\n" 212 "int i;\n" 213 "}", 214 format("namespace N {\n" 215 "\n" 216 "int i;\n" 217 "}", 218 getGoogleStyle())); 219 EXPECT_EQ("/* something */ namespace N {\n" 220 "\n" 221 "int i;\n" 222 "}", 223 format("/* something */ namespace N {\n" 224 "\n" 225 "int i;\n" 226 "}", 227 getGoogleStyle())); 228 EXPECT_EQ("inline namespace N {\n" 229 "\n" 230 "int i;\n" 231 "}", 232 format("inline namespace N {\n" 233 "\n" 234 "int i;\n" 235 "}", 236 getGoogleStyle())); 237 EXPECT_EQ("/* something */ inline namespace N {\n" 238 "\n" 239 "int i;\n" 240 "}", 241 format("/* something */ inline namespace N {\n" 242 "\n" 243 "int i;\n" 244 "}", 245 getGoogleStyle())); 246 EXPECT_EQ("export namespace N {\n" 247 "\n" 248 "int i;\n" 249 "}", 250 format("export namespace N {\n" 251 "\n" 252 "int i;\n" 253 "}", 254 getGoogleStyle())); 255 EXPECT_EQ("extern /**/ \"C\" /**/ {\n" 256 "\n" 257 "int i;\n" 258 "}", 259 format("extern /**/ \"C\" /**/ {\n" 260 "\n" 261 "int i;\n" 262 "}", 263 getGoogleStyle())); 264 265 auto CustomStyle = getLLVMStyle(); 266 CustomStyle.BreakBeforeBraces = FormatStyle::BS_Custom; 267 CustomStyle.BraceWrapping.AfterNamespace = true; 268 CustomStyle.KeepEmptyLinesAtTheStartOfBlocks = false; 269 EXPECT_EQ("namespace N\n" 270 "{\n" 271 "\n" 272 "int i;\n" 273 "}", 274 format("namespace N\n" 275 "{\n" 276 "\n" 277 "\n" 278 "int i;\n" 279 "}", 280 CustomStyle)); 281 EXPECT_EQ("/* something */ namespace N\n" 282 "{\n" 283 "\n" 284 "int i;\n" 285 "}", 286 format("/* something */ namespace N {\n" 287 "\n" 288 "\n" 289 "int i;\n" 290 "}", 291 CustomStyle)); 292 EXPECT_EQ("inline namespace N\n" 293 "{\n" 294 "\n" 295 "int i;\n" 296 "}", 297 format("inline namespace N\n" 298 "{\n" 299 "\n" 300 "\n" 301 "int i;\n" 302 "}", 303 CustomStyle)); 304 EXPECT_EQ("/* something */ inline namespace N\n" 305 "{\n" 306 "\n" 307 "int i;\n" 308 "}", 309 format("/* something */ inline namespace N\n" 310 "{\n" 311 "\n" 312 "int i;\n" 313 "}", 314 CustomStyle)); 315 EXPECT_EQ("export namespace N\n" 316 "{\n" 317 "\n" 318 "int i;\n" 319 "}", 320 format("export namespace N\n" 321 "{\n" 322 "\n" 323 "int i;\n" 324 "}", 325 CustomStyle)); 326 EXPECT_EQ("namespace a\n" 327 "{\n" 328 "namespace b\n" 329 "{\n" 330 "\n" 331 "class AA {};\n" 332 "\n" 333 "} // namespace b\n" 334 "} // namespace a\n", 335 format("namespace a\n" 336 "{\n" 337 "namespace b\n" 338 "{\n" 339 "\n" 340 "\n" 341 "class AA {};\n" 342 "\n" 343 "\n" 344 "}\n" 345 "}\n", 346 CustomStyle)); 347 EXPECT_EQ("namespace A /* comment */\n" 348 "{\n" 349 "class B {}\n" 350 "} // namespace A", 351 format("namespace A /* comment */ { class B {} }", CustomStyle)); 352 EXPECT_EQ("namespace A\n" 353 "{ /* comment */\n" 354 "class B {}\n" 355 "} // namespace A", 356 format("namespace A {/* comment */ class B {} }", CustomStyle)); 357 EXPECT_EQ("namespace A\n" 358 "{ /* comment */\n" 359 "\n" 360 "class B {}\n" 361 "\n" 362 "" 363 "} // namespace A", 364 format("namespace A { /* comment */\n" 365 "\n" 366 "\n" 367 "class B {}\n" 368 "\n" 369 "\n" 370 "}", 371 CustomStyle)); 372 EXPECT_EQ("namespace A /* comment */\n" 373 "{\n" 374 "\n" 375 "class B {}\n" 376 "\n" 377 "} // namespace A", 378 format("namespace A/* comment */ {\n" 379 "\n" 380 "\n" 381 "class B {}\n" 382 "\n" 383 "\n" 384 "}", 385 CustomStyle)); 386 387 // ...but do keep inlining and removing empty lines for non-block extern "C" 388 // functions. 389 verifyFormat("extern \"C\" int f() { return 42; }", getGoogleStyle()); 390 EXPECT_EQ("extern \"C\" int f() {\n" 391 " int i = 42;\n" 392 " return i;\n" 393 "}", 394 format("extern \"C\" int f() {\n" 395 "\n" 396 " int i = 42;\n" 397 " return i;\n" 398 "}", 399 getGoogleStyle())); 400 401 // Remove empty lines at the beginning and end of blocks. 402 EXPECT_EQ("void f() {\n" 403 "\n" 404 " if (a) {\n" 405 "\n" 406 " f();\n" 407 " }\n" 408 "}", 409 format("void f() {\n" 410 "\n" 411 " if (a) {\n" 412 "\n" 413 " f();\n" 414 "\n" 415 " }\n" 416 "\n" 417 "}", 418 getLLVMStyle())); 419 EXPECT_EQ("void f() {\n" 420 " if (a) {\n" 421 " f();\n" 422 " }\n" 423 "}", 424 format("void f() {\n" 425 "\n" 426 " if (a) {\n" 427 "\n" 428 " f();\n" 429 "\n" 430 " }\n" 431 "\n" 432 "}", 433 getGoogleStyle())); 434 435 // Don't remove empty lines in more complex control statements. 436 EXPECT_EQ("void f() {\n" 437 " if (a) {\n" 438 " f();\n" 439 "\n" 440 " } else if (b) {\n" 441 " f();\n" 442 " }\n" 443 "}", 444 format("void f() {\n" 445 " if (a) {\n" 446 " f();\n" 447 "\n" 448 " } else if (b) {\n" 449 " f();\n" 450 "\n" 451 " }\n" 452 "\n" 453 "}")); 454 455 // Don't remove empty lines before namespace endings. 456 FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle(); 457 LLVMWithNoNamespaceFix.FixNamespaceComments = false; 458 EXPECT_EQ("namespace {\n" 459 "int i;\n" 460 "\n" 461 "}", 462 format("namespace {\n" 463 "int i;\n" 464 "\n" 465 "}", 466 LLVMWithNoNamespaceFix)); 467 EXPECT_EQ("namespace {\n" 468 "int i;\n" 469 "}", 470 format("namespace {\n" 471 "int i;\n" 472 "}", 473 LLVMWithNoNamespaceFix)); 474 EXPECT_EQ("namespace {\n" 475 "int i;\n" 476 "\n" 477 "};", 478 format("namespace {\n" 479 "int i;\n" 480 "\n" 481 "};", 482 LLVMWithNoNamespaceFix)); 483 EXPECT_EQ("namespace {\n" 484 "int i;\n" 485 "};", 486 format("namespace {\n" 487 "int i;\n" 488 "};", 489 LLVMWithNoNamespaceFix)); 490 EXPECT_EQ("namespace {\n" 491 "int i;\n" 492 "\n" 493 "}", 494 format("namespace {\n" 495 "int i;\n" 496 "\n" 497 "}")); 498 EXPECT_EQ("namespace {\n" 499 "int i;\n" 500 "\n" 501 "} // namespace", 502 format("namespace {\n" 503 "int i;\n" 504 "\n" 505 "} // namespace")); 506 507 FormatStyle Style = getLLVMStyle(); 508 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 509 Style.MaxEmptyLinesToKeep = 2; 510 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 511 Style.BraceWrapping.AfterClass = true; 512 Style.BraceWrapping.AfterFunction = true; 513 Style.KeepEmptyLinesAtTheStartOfBlocks = false; 514 515 EXPECT_EQ("class Foo\n" 516 "{\n" 517 " Foo() {}\n" 518 "\n" 519 " void funk() {}\n" 520 "};", 521 format("class Foo\n" 522 "{\n" 523 " Foo()\n" 524 " {\n" 525 " }\n" 526 "\n" 527 " void funk() {}\n" 528 "};", 529 Style)); 530 } 531 532 TEST_F(FormatTest, RecognizesBinaryOperatorKeywords) { 533 verifyFormat("x = (a) and (b);"); 534 verifyFormat("x = (a) or (b);"); 535 verifyFormat("x = (a) bitand (b);"); 536 verifyFormat("x = (a) bitor (b);"); 537 verifyFormat("x = (a) not_eq (b);"); 538 verifyFormat("x = (a) and_eq (b);"); 539 verifyFormat("x = (a) or_eq (b);"); 540 verifyFormat("x = (a) xor (b);"); 541 } 542 543 TEST_F(FormatTest, RecognizesUnaryOperatorKeywords) { 544 verifyFormat("x = compl(a);"); 545 verifyFormat("x = not(a);"); 546 verifyFormat("x = bitand(a);"); 547 // Unary operator must not be merged with the next identifier 548 verifyFormat("x = compl a;"); 549 verifyFormat("x = not a;"); 550 verifyFormat("x = bitand a;"); 551 } 552 553 //===----------------------------------------------------------------------===// 554 // Tests for control statements. 555 //===----------------------------------------------------------------------===// 556 557 TEST_F(FormatTest, FormatIfWithoutCompoundStatement) { 558 verifyFormat("if (true)\n f();\ng();"); 559 verifyFormat("if (a)\n if (b)\n if (c)\n g();\nh();"); 560 verifyFormat("if (a)\n if (b) {\n f();\n }\ng();"); 561 verifyFormat("if constexpr (true)\n" 562 " f();\ng();"); 563 verifyFormat("if CONSTEXPR (true)\n" 564 " f();\ng();"); 565 verifyFormat("if constexpr (a)\n" 566 " if constexpr (b)\n" 567 " if constexpr (c)\n" 568 " g();\n" 569 "h();"); 570 verifyFormat("if CONSTEXPR (a)\n" 571 " if CONSTEXPR (b)\n" 572 " if CONSTEXPR (c)\n" 573 " g();\n" 574 "h();"); 575 verifyFormat("if constexpr (a)\n" 576 " if constexpr (b) {\n" 577 " f();\n" 578 " }\n" 579 "g();"); 580 verifyFormat("if CONSTEXPR (a)\n" 581 " if CONSTEXPR (b) {\n" 582 " f();\n" 583 " }\n" 584 "g();"); 585 586 verifyFormat("if consteval {\n}"); 587 verifyFormat("if !consteval {\n}"); 588 verifyFormat("if not consteval {\n}"); 589 verifyFormat("if consteval {\n} else {\n}"); 590 verifyFormat("if !consteval {\n} else {\n}"); 591 verifyFormat("if consteval {\n" 592 " f();\n" 593 "}"); 594 verifyFormat("if !consteval {\n" 595 " f();\n" 596 "}"); 597 verifyFormat("if consteval {\n" 598 " f();\n" 599 "} else {\n" 600 " g();\n" 601 "}"); 602 verifyFormat("if CONSTEVAL {\n" 603 " f();\n" 604 "}"); 605 verifyFormat("if !CONSTEVAL {\n" 606 " f();\n" 607 "}"); 608 609 verifyFormat("if (a)\n" 610 " g();"); 611 verifyFormat("if (a) {\n" 612 " g()\n" 613 "};"); 614 verifyFormat("if (a)\n" 615 " g();\n" 616 "else\n" 617 " g();"); 618 verifyFormat("if (a) {\n" 619 " g();\n" 620 "} else\n" 621 " g();"); 622 verifyFormat("if (a)\n" 623 " g();\n" 624 "else {\n" 625 " g();\n" 626 "}"); 627 verifyFormat("if (a) {\n" 628 " g();\n" 629 "} else {\n" 630 " g();\n" 631 "}"); 632 verifyFormat("if (a)\n" 633 " g();\n" 634 "else if (b)\n" 635 " g();\n" 636 "else\n" 637 " g();"); 638 verifyFormat("if (a) {\n" 639 " g();\n" 640 "} else if (b)\n" 641 " g();\n" 642 "else\n" 643 " g();"); 644 verifyFormat("if (a)\n" 645 " g();\n" 646 "else if (b) {\n" 647 " g();\n" 648 "} else\n" 649 " g();"); 650 verifyFormat("if (a)\n" 651 " g();\n" 652 "else if (b)\n" 653 " g();\n" 654 "else {\n" 655 " g();\n" 656 "}"); 657 verifyFormat("if (a)\n" 658 " g();\n" 659 "else if (b) {\n" 660 " g();\n" 661 "} else {\n" 662 " g();\n" 663 "}"); 664 verifyFormat("if (a) {\n" 665 " g();\n" 666 "} else if (b) {\n" 667 " g();\n" 668 "} else {\n" 669 " g();\n" 670 "}"); 671 672 FormatStyle AllowsMergedIf = getLLVMStyle(); 673 AllowsMergedIf.IfMacros.push_back("MYIF"); 674 AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left; 675 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 676 FormatStyle::SIS_WithoutElse; 677 verifyFormat("if (a)\n" 678 " // comment\n" 679 " f();", 680 AllowsMergedIf); 681 verifyFormat("{\n" 682 " if (a)\n" 683 " label:\n" 684 " f();\n" 685 "}", 686 AllowsMergedIf); 687 verifyFormat("#define A \\\n" 688 " if (a) \\\n" 689 " label: \\\n" 690 " f()", 691 AllowsMergedIf); 692 verifyFormat("if (a)\n" 693 " ;", 694 AllowsMergedIf); 695 verifyFormat("if (a)\n" 696 " if (b) return;", 697 AllowsMergedIf); 698 699 verifyFormat("if (a) // Can't merge this\n" 700 " f();\n", 701 AllowsMergedIf); 702 verifyFormat("if (a) /* still don't merge */\n" 703 " f();", 704 AllowsMergedIf); 705 verifyFormat("if (a) { // Never merge this\n" 706 " f();\n" 707 "}", 708 AllowsMergedIf); 709 verifyFormat("if (a) { /* Never merge this */\n" 710 " f();\n" 711 "}", 712 AllowsMergedIf); 713 verifyFormat("MYIF (a)\n" 714 " // comment\n" 715 " f();", 716 AllowsMergedIf); 717 verifyFormat("{\n" 718 " MYIF (a)\n" 719 " label:\n" 720 " f();\n" 721 "}", 722 AllowsMergedIf); 723 verifyFormat("#define A \\\n" 724 " MYIF (a) \\\n" 725 " label: \\\n" 726 " f()", 727 AllowsMergedIf); 728 verifyFormat("MYIF (a)\n" 729 " ;", 730 AllowsMergedIf); 731 verifyFormat("MYIF (a)\n" 732 " MYIF (b) return;", 733 AllowsMergedIf); 734 735 verifyFormat("MYIF (a) // Can't merge this\n" 736 " f();\n", 737 AllowsMergedIf); 738 verifyFormat("MYIF (a) /* still don't merge */\n" 739 " f();", 740 AllowsMergedIf); 741 verifyFormat("MYIF (a) { // Never merge this\n" 742 " f();\n" 743 "}", 744 AllowsMergedIf); 745 verifyFormat("MYIF (a) { /* Never merge this */\n" 746 " f();\n" 747 "}", 748 AllowsMergedIf); 749 750 AllowsMergedIf.ColumnLimit = 14; 751 // Where line-lengths matter, a 2-letter synonym that maintains line length. 752 // Not IF to avoid any confusion that IF is somehow special. 753 AllowsMergedIf.IfMacros.push_back("FI"); 754 verifyFormat("if (a) return;", AllowsMergedIf); 755 verifyFormat("if (aaaaaaaaa)\n" 756 " return;", 757 AllowsMergedIf); 758 verifyFormat("FI (a) return;", AllowsMergedIf); 759 verifyFormat("FI (aaaaaaaaa)\n" 760 " return;", 761 AllowsMergedIf); 762 763 AllowsMergedIf.ColumnLimit = 13; 764 verifyFormat("if (a)\n return;", AllowsMergedIf); 765 verifyFormat("FI (a)\n return;", AllowsMergedIf); 766 767 FormatStyle AllowsMergedIfElse = getLLVMStyle(); 768 AllowsMergedIfElse.IfMacros.push_back("MYIF"); 769 AllowsMergedIfElse.AllowShortIfStatementsOnASingleLine = 770 FormatStyle::SIS_AllIfsAndElse; 771 verifyFormat("if (a)\n" 772 " // comment\n" 773 " f();\n" 774 "else\n" 775 " // comment\n" 776 " f();", 777 AllowsMergedIfElse); 778 verifyFormat("{\n" 779 " if (a)\n" 780 " label:\n" 781 " f();\n" 782 " else\n" 783 " label:\n" 784 " f();\n" 785 "}", 786 AllowsMergedIfElse); 787 verifyFormat("if (a)\n" 788 " ;\n" 789 "else\n" 790 " ;", 791 AllowsMergedIfElse); 792 verifyFormat("if (a) {\n" 793 "} else {\n" 794 "}", 795 AllowsMergedIfElse); 796 verifyFormat("if (a) return;\n" 797 "else if (b) return;\n" 798 "else return;", 799 AllowsMergedIfElse); 800 verifyFormat("if (a) {\n" 801 "} else return;", 802 AllowsMergedIfElse); 803 verifyFormat("if (a) {\n" 804 "} else if (b) return;\n" 805 "else return;", 806 AllowsMergedIfElse); 807 verifyFormat("if (a) return;\n" 808 "else if (b) {\n" 809 "} else return;", 810 AllowsMergedIfElse); 811 verifyFormat("if (a)\n" 812 " if (b) return;\n" 813 " else return;", 814 AllowsMergedIfElse); 815 verifyFormat("if constexpr (a)\n" 816 " if constexpr (b) return;\n" 817 " else if constexpr (c) return;\n" 818 " else return;", 819 AllowsMergedIfElse); 820 verifyFormat("MYIF (a)\n" 821 " // comment\n" 822 " f();\n" 823 "else\n" 824 " // comment\n" 825 " f();", 826 AllowsMergedIfElse); 827 verifyFormat("{\n" 828 " MYIF (a)\n" 829 " label:\n" 830 " f();\n" 831 " else\n" 832 " label:\n" 833 " f();\n" 834 "}", 835 AllowsMergedIfElse); 836 verifyFormat("MYIF (a)\n" 837 " ;\n" 838 "else\n" 839 " ;", 840 AllowsMergedIfElse); 841 verifyFormat("MYIF (a) {\n" 842 "} else {\n" 843 "}", 844 AllowsMergedIfElse); 845 verifyFormat("MYIF (a) return;\n" 846 "else MYIF (b) return;\n" 847 "else return;", 848 AllowsMergedIfElse); 849 verifyFormat("MYIF (a) {\n" 850 "} else return;", 851 AllowsMergedIfElse); 852 verifyFormat("MYIF (a) {\n" 853 "} else MYIF (b) return;\n" 854 "else return;", 855 AllowsMergedIfElse); 856 verifyFormat("MYIF (a) return;\n" 857 "else MYIF (b) {\n" 858 "} else return;", 859 AllowsMergedIfElse); 860 verifyFormat("MYIF (a)\n" 861 " MYIF (b) return;\n" 862 " else return;", 863 AllowsMergedIfElse); 864 verifyFormat("MYIF constexpr (a)\n" 865 " MYIF constexpr (b) return;\n" 866 " else MYIF constexpr (c) return;\n" 867 " else return;", 868 AllowsMergedIfElse); 869 } 870 871 TEST_F(FormatTest, FormatIfWithoutCompoundStatementButElseWith) { 872 FormatStyle AllowsMergedIf = getLLVMStyle(); 873 AllowsMergedIf.IfMacros.push_back("MYIF"); 874 AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left; 875 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 876 FormatStyle::SIS_WithoutElse; 877 verifyFormat("if (a)\n" 878 " f();\n" 879 "else {\n" 880 " g();\n" 881 "}", 882 AllowsMergedIf); 883 verifyFormat("if (a)\n" 884 " f();\n" 885 "else\n" 886 " g();\n", 887 AllowsMergedIf); 888 889 verifyFormat("if (a) g();", AllowsMergedIf); 890 verifyFormat("if (a) {\n" 891 " g()\n" 892 "};", 893 AllowsMergedIf); 894 verifyFormat("if (a)\n" 895 " g();\n" 896 "else\n" 897 " g();", 898 AllowsMergedIf); 899 verifyFormat("if (a) {\n" 900 " g();\n" 901 "} else\n" 902 " g();", 903 AllowsMergedIf); 904 verifyFormat("if (a)\n" 905 " g();\n" 906 "else {\n" 907 " g();\n" 908 "}", 909 AllowsMergedIf); 910 verifyFormat("if (a) {\n" 911 " g();\n" 912 "} else {\n" 913 " g();\n" 914 "}", 915 AllowsMergedIf); 916 verifyFormat("if (a)\n" 917 " g();\n" 918 "else if (b)\n" 919 " g();\n" 920 "else\n" 921 " g();", 922 AllowsMergedIf); 923 verifyFormat("if (a) {\n" 924 " g();\n" 925 "} else if (b)\n" 926 " g();\n" 927 "else\n" 928 " g();", 929 AllowsMergedIf); 930 verifyFormat("if (a)\n" 931 " g();\n" 932 "else if (b) {\n" 933 " g();\n" 934 "} else\n" 935 " g();", 936 AllowsMergedIf); 937 verifyFormat("if (a)\n" 938 " g();\n" 939 "else if (b)\n" 940 " g();\n" 941 "else {\n" 942 " g();\n" 943 "}", 944 AllowsMergedIf); 945 verifyFormat("if (a)\n" 946 " g();\n" 947 "else if (b) {\n" 948 " g();\n" 949 "} else {\n" 950 " g();\n" 951 "}", 952 AllowsMergedIf); 953 verifyFormat("if (a) {\n" 954 " g();\n" 955 "} else if (b) {\n" 956 " g();\n" 957 "} else {\n" 958 " g();\n" 959 "}", 960 AllowsMergedIf); 961 verifyFormat("MYIF (a)\n" 962 " f();\n" 963 "else {\n" 964 " g();\n" 965 "}", 966 AllowsMergedIf); 967 verifyFormat("MYIF (a)\n" 968 " f();\n" 969 "else\n" 970 " g();\n", 971 AllowsMergedIf); 972 973 verifyFormat("MYIF (a) g();", AllowsMergedIf); 974 verifyFormat("MYIF (a) {\n" 975 " g()\n" 976 "};", 977 AllowsMergedIf); 978 verifyFormat("MYIF (a)\n" 979 " g();\n" 980 "else\n" 981 " g();", 982 AllowsMergedIf); 983 verifyFormat("MYIF (a) {\n" 984 " g();\n" 985 "} else\n" 986 " g();", 987 AllowsMergedIf); 988 verifyFormat("MYIF (a)\n" 989 " g();\n" 990 "else {\n" 991 " g();\n" 992 "}", 993 AllowsMergedIf); 994 verifyFormat("MYIF (a) {\n" 995 " g();\n" 996 "} else {\n" 997 " g();\n" 998 "}", 999 AllowsMergedIf); 1000 verifyFormat("MYIF (a)\n" 1001 " g();\n" 1002 "else MYIF (b)\n" 1003 " g();\n" 1004 "else\n" 1005 " g();", 1006 AllowsMergedIf); 1007 verifyFormat("MYIF (a)\n" 1008 " g();\n" 1009 "else if (b)\n" 1010 " g();\n" 1011 "else\n" 1012 " g();", 1013 AllowsMergedIf); 1014 verifyFormat("MYIF (a) {\n" 1015 " g();\n" 1016 "} else MYIF (b)\n" 1017 " g();\n" 1018 "else\n" 1019 " g();", 1020 AllowsMergedIf); 1021 verifyFormat("MYIF (a) {\n" 1022 " g();\n" 1023 "} else if (b)\n" 1024 " g();\n" 1025 "else\n" 1026 " g();", 1027 AllowsMergedIf); 1028 verifyFormat("MYIF (a)\n" 1029 " g();\n" 1030 "else MYIF (b) {\n" 1031 " g();\n" 1032 "} else\n" 1033 " g();", 1034 AllowsMergedIf); 1035 verifyFormat("MYIF (a)\n" 1036 " g();\n" 1037 "else if (b) {\n" 1038 " g();\n" 1039 "} else\n" 1040 " g();", 1041 AllowsMergedIf); 1042 verifyFormat("MYIF (a)\n" 1043 " g();\n" 1044 "else MYIF (b)\n" 1045 " g();\n" 1046 "else {\n" 1047 " g();\n" 1048 "}", 1049 AllowsMergedIf); 1050 verifyFormat("MYIF (a)\n" 1051 " g();\n" 1052 "else if (b)\n" 1053 " g();\n" 1054 "else {\n" 1055 " g();\n" 1056 "}", 1057 AllowsMergedIf); 1058 verifyFormat("MYIF (a)\n" 1059 " g();\n" 1060 "else MYIF (b) {\n" 1061 " g();\n" 1062 "} else {\n" 1063 " g();\n" 1064 "}", 1065 AllowsMergedIf); 1066 verifyFormat("MYIF (a)\n" 1067 " g();\n" 1068 "else if (b) {\n" 1069 " g();\n" 1070 "} else {\n" 1071 " g();\n" 1072 "}", 1073 AllowsMergedIf); 1074 verifyFormat("MYIF (a) {\n" 1075 " g();\n" 1076 "} else MYIF (b) {\n" 1077 " g();\n" 1078 "} else {\n" 1079 " g();\n" 1080 "}", 1081 AllowsMergedIf); 1082 verifyFormat("MYIF (a) {\n" 1083 " g();\n" 1084 "} else if (b) {\n" 1085 " g();\n" 1086 "} else {\n" 1087 " g();\n" 1088 "}", 1089 AllowsMergedIf); 1090 1091 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 1092 FormatStyle::SIS_OnlyFirstIf; 1093 1094 verifyFormat("if (a) f();\n" 1095 "else {\n" 1096 " g();\n" 1097 "}", 1098 AllowsMergedIf); 1099 verifyFormat("if (a) f();\n" 1100 "else {\n" 1101 " if (a) f();\n" 1102 " else {\n" 1103 " g();\n" 1104 " }\n" 1105 " g();\n" 1106 "}", 1107 AllowsMergedIf); 1108 1109 verifyFormat("if (a) g();", AllowsMergedIf); 1110 verifyFormat("if (a) {\n" 1111 " g()\n" 1112 "};", 1113 AllowsMergedIf); 1114 verifyFormat("if (a) g();\n" 1115 "else\n" 1116 " g();", 1117 AllowsMergedIf); 1118 verifyFormat("if (a) {\n" 1119 " g();\n" 1120 "} else\n" 1121 " g();", 1122 AllowsMergedIf); 1123 verifyFormat("if (a) g();\n" 1124 "else {\n" 1125 " g();\n" 1126 "}", 1127 AllowsMergedIf); 1128 verifyFormat("if (a) {\n" 1129 " g();\n" 1130 "} else {\n" 1131 " g();\n" 1132 "}", 1133 AllowsMergedIf); 1134 verifyFormat("if (a) g();\n" 1135 "else if (b)\n" 1136 " g();\n" 1137 "else\n" 1138 " g();", 1139 AllowsMergedIf); 1140 verifyFormat("if (a) {\n" 1141 " g();\n" 1142 "} else if (b)\n" 1143 " g();\n" 1144 "else\n" 1145 " g();", 1146 AllowsMergedIf); 1147 verifyFormat("if (a) g();\n" 1148 "else if (b) {\n" 1149 " g();\n" 1150 "} else\n" 1151 " g();", 1152 AllowsMergedIf); 1153 verifyFormat("if (a) g();\n" 1154 "else if (b)\n" 1155 " g();\n" 1156 "else {\n" 1157 " g();\n" 1158 "}", 1159 AllowsMergedIf); 1160 verifyFormat("if (a) g();\n" 1161 "else if (b) {\n" 1162 " g();\n" 1163 "} else {\n" 1164 " g();\n" 1165 "}", 1166 AllowsMergedIf); 1167 verifyFormat("if (a) {\n" 1168 " g();\n" 1169 "} else if (b) {\n" 1170 " g();\n" 1171 "} else {\n" 1172 " g();\n" 1173 "}", 1174 AllowsMergedIf); 1175 verifyFormat("MYIF (a) f();\n" 1176 "else {\n" 1177 " g();\n" 1178 "}", 1179 AllowsMergedIf); 1180 verifyFormat("MYIF (a) f();\n" 1181 "else {\n" 1182 " if (a) f();\n" 1183 " else {\n" 1184 " g();\n" 1185 " }\n" 1186 " g();\n" 1187 "}", 1188 AllowsMergedIf); 1189 1190 verifyFormat("MYIF (a) g();", AllowsMergedIf); 1191 verifyFormat("MYIF (a) {\n" 1192 " g()\n" 1193 "};", 1194 AllowsMergedIf); 1195 verifyFormat("MYIF (a) g();\n" 1196 "else\n" 1197 " g();", 1198 AllowsMergedIf); 1199 verifyFormat("MYIF (a) {\n" 1200 " g();\n" 1201 "} else\n" 1202 " g();", 1203 AllowsMergedIf); 1204 verifyFormat("MYIF (a) g();\n" 1205 "else {\n" 1206 " g();\n" 1207 "}", 1208 AllowsMergedIf); 1209 verifyFormat("MYIF (a) {\n" 1210 " g();\n" 1211 "} else {\n" 1212 " g();\n" 1213 "}", 1214 AllowsMergedIf); 1215 verifyFormat("MYIF (a) g();\n" 1216 "else MYIF (b)\n" 1217 " g();\n" 1218 "else\n" 1219 " g();", 1220 AllowsMergedIf); 1221 verifyFormat("MYIF (a) g();\n" 1222 "else if (b)\n" 1223 " g();\n" 1224 "else\n" 1225 " g();", 1226 AllowsMergedIf); 1227 verifyFormat("MYIF (a) {\n" 1228 " g();\n" 1229 "} else MYIF (b)\n" 1230 " g();\n" 1231 "else\n" 1232 " g();", 1233 AllowsMergedIf); 1234 verifyFormat("MYIF (a) {\n" 1235 " g();\n" 1236 "} else if (b)\n" 1237 " g();\n" 1238 "else\n" 1239 " g();", 1240 AllowsMergedIf); 1241 verifyFormat("MYIF (a) g();\n" 1242 "else MYIF (b) {\n" 1243 " g();\n" 1244 "} else\n" 1245 " g();", 1246 AllowsMergedIf); 1247 verifyFormat("MYIF (a) g();\n" 1248 "else if (b) {\n" 1249 " g();\n" 1250 "} else\n" 1251 " g();", 1252 AllowsMergedIf); 1253 verifyFormat("MYIF (a) g();\n" 1254 "else MYIF (b)\n" 1255 " g();\n" 1256 "else {\n" 1257 " g();\n" 1258 "}", 1259 AllowsMergedIf); 1260 verifyFormat("MYIF (a) g();\n" 1261 "else if (b)\n" 1262 " g();\n" 1263 "else {\n" 1264 " g();\n" 1265 "}", 1266 AllowsMergedIf); 1267 verifyFormat("MYIF (a) g();\n" 1268 "else MYIF (b) {\n" 1269 " g();\n" 1270 "} else {\n" 1271 " g();\n" 1272 "}", 1273 AllowsMergedIf); 1274 verifyFormat("MYIF (a) g();\n" 1275 "else if (b) {\n" 1276 " g();\n" 1277 "} else {\n" 1278 " g();\n" 1279 "}", 1280 AllowsMergedIf); 1281 verifyFormat("MYIF (a) {\n" 1282 " g();\n" 1283 "} else MYIF (b) {\n" 1284 " g();\n" 1285 "} else {\n" 1286 " g();\n" 1287 "}", 1288 AllowsMergedIf); 1289 verifyFormat("MYIF (a) {\n" 1290 " g();\n" 1291 "} else if (b) {\n" 1292 " g();\n" 1293 "} else {\n" 1294 " g();\n" 1295 "}", 1296 AllowsMergedIf); 1297 1298 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 1299 FormatStyle::SIS_AllIfsAndElse; 1300 1301 verifyFormat("if (a) f();\n" 1302 "else {\n" 1303 " g();\n" 1304 "}", 1305 AllowsMergedIf); 1306 verifyFormat("if (a) f();\n" 1307 "else {\n" 1308 " if (a) f();\n" 1309 " else {\n" 1310 " g();\n" 1311 " }\n" 1312 " g();\n" 1313 "}", 1314 AllowsMergedIf); 1315 1316 verifyFormat("if (a) g();", AllowsMergedIf); 1317 verifyFormat("if (a) {\n" 1318 " g()\n" 1319 "};", 1320 AllowsMergedIf); 1321 verifyFormat("if (a) g();\n" 1322 "else g();", 1323 AllowsMergedIf); 1324 verifyFormat("if (a) {\n" 1325 " g();\n" 1326 "} else g();", 1327 AllowsMergedIf); 1328 verifyFormat("if (a) g();\n" 1329 "else {\n" 1330 " g();\n" 1331 "}", 1332 AllowsMergedIf); 1333 verifyFormat("if (a) {\n" 1334 " g();\n" 1335 "} else {\n" 1336 " g();\n" 1337 "}", 1338 AllowsMergedIf); 1339 verifyFormat("if (a) g();\n" 1340 "else if (b) g();\n" 1341 "else g();", 1342 AllowsMergedIf); 1343 verifyFormat("if (a) {\n" 1344 " g();\n" 1345 "} else if (b) g();\n" 1346 "else g();", 1347 AllowsMergedIf); 1348 verifyFormat("if (a) g();\n" 1349 "else if (b) {\n" 1350 " g();\n" 1351 "} else g();", 1352 AllowsMergedIf); 1353 verifyFormat("if (a) g();\n" 1354 "else if (b) g();\n" 1355 "else {\n" 1356 " g();\n" 1357 "}", 1358 AllowsMergedIf); 1359 verifyFormat("if (a) g();\n" 1360 "else if (b) {\n" 1361 " g();\n" 1362 "} else {\n" 1363 " g();\n" 1364 "}", 1365 AllowsMergedIf); 1366 verifyFormat("if (a) {\n" 1367 " g();\n" 1368 "} else if (b) {\n" 1369 " g();\n" 1370 "} else {\n" 1371 " g();\n" 1372 "}", 1373 AllowsMergedIf); 1374 verifyFormat("MYIF (a) f();\n" 1375 "else {\n" 1376 " g();\n" 1377 "}", 1378 AllowsMergedIf); 1379 verifyFormat("MYIF (a) f();\n" 1380 "else {\n" 1381 " if (a) f();\n" 1382 " else {\n" 1383 " g();\n" 1384 " }\n" 1385 " g();\n" 1386 "}", 1387 AllowsMergedIf); 1388 1389 verifyFormat("MYIF (a) g();", AllowsMergedIf); 1390 verifyFormat("MYIF (a) {\n" 1391 " g()\n" 1392 "};", 1393 AllowsMergedIf); 1394 verifyFormat("MYIF (a) g();\n" 1395 "else g();", 1396 AllowsMergedIf); 1397 verifyFormat("MYIF (a) {\n" 1398 " g();\n" 1399 "} else g();", 1400 AllowsMergedIf); 1401 verifyFormat("MYIF (a) g();\n" 1402 "else {\n" 1403 " g();\n" 1404 "}", 1405 AllowsMergedIf); 1406 verifyFormat("MYIF (a) {\n" 1407 " g();\n" 1408 "} else {\n" 1409 " g();\n" 1410 "}", 1411 AllowsMergedIf); 1412 verifyFormat("MYIF (a) g();\n" 1413 "else MYIF (b) g();\n" 1414 "else g();", 1415 AllowsMergedIf); 1416 verifyFormat("MYIF (a) g();\n" 1417 "else if (b) g();\n" 1418 "else g();", 1419 AllowsMergedIf); 1420 verifyFormat("MYIF (a) {\n" 1421 " g();\n" 1422 "} else MYIF (b) g();\n" 1423 "else g();", 1424 AllowsMergedIf); 1425 verifyFormat("MYIF (a) {\n" 1426 " g();\n" 1427 "} else if (b) g();\n" 1428 "else g();", 1429 AllowsMergedIf); 1430 verifyFormat("MYIF (a) g();\n" 1431 "else MYIF (b) {\n" 1432 " g();\n" 1433 "} else g();", 1434 AllowsMergedIf); 1435 verifyFormat("MYIF (a) g();\n" 1436 "else if (b) {\n" 1437 " g();\n" 1438 "} else g();", 1439 AllowsMergedIf); 1440 verifyFormat("MYIF (a) g();\n" 1441 "else MYIF (b) g();\n" 1442 "else {\n" 1443 " g();\n" 1444 "}", 1445 AllowsMergedIf); 1446 verifyFormat("MYIF (a) g();\n" 1447 "else if (b) g();\n" 1448 "else {\n" 1449 " g();\n" 1450 "}", 1451 AllowsMergedIf); 1452 verifyFormat("MYIF (a) g();\n" 1453 "else MYIF (b) {\n" 1454 " g();\n" 1455 "} else {\n" 1456 " g();\n" 1457 "}", 1458 AllowsMergedIf); 1459 verifyFormat("MYIF (a) g();\n" 1460 "else if (b) {\n" 1461 " g();\n" 1462 "} else {\n" 1463 " g();\n" 1464 "}", 1465 AllowsMergedIf); 1466 verifyFormat("MYIF (a) {\n" 1467 " g();\n" 1468 "} else MYIF (b) {\n" 1469 " g();\n" 1470 "} else {\n" 1471 " g();\n" 1472 "}", 1473 AllowsMergedIf); 1474 verifyFormat("MYIF (a) {\n" 1475 " g();\n" 1476 "} else if (b) {\n" 1477 " g();\n" 1478 "} else {\n" 1479 " g();\n" 1480 "}", 1481 AllowsMergedIf); 1482 } 1483 1484 TEST_F(FormatTest, FormatLoopsWithoutCompoundStatement) { 1485 FormatStyle AllowsMergedLoops = getLLVMStyle(); 1486 AllowsMergedLoops.AllowShortLoopsOnASingleLine = true; 1487 verifyFormat("while (true) continue;", AllowsMergedLoops); 1488 verifyFormat("for (;;) continue;", AllowsMergedLoops); 1489 verifyFormat("for (int &v : vec) v *= 2;", AllowsMergedLoops); 1490 verifyFormat("BOOST_FOREACH (int &v, vec) v *= 2;", AllowsMergedLoops); 1491 verifyFormat("while (true)\n" 1492 " ;", 1493 AllowsMergedLoops); 1494 verifyFormat("for (;;)\n" 1495 " ;", 1496 AllowsMergedLoops); 1497 verifyFormat("for (;;)\n" 1498 " for (;;) continue;", 1499 AllowsMergedLoops); 1500 verifyFormat("for (;;)\n" 1501 " while (true) continue;", 1502 AllowsMergedLoops); 1503 verifyFormat("while (true)\n" 1504 " for (;;) continue;", 1505 AllowsMergedLoops); 1506 verifyFormat("BOOST_FOREACH (int &v, vec)\n" 1507 " for (;;) continue;", 1508 AllowsMergedLoops); 1509 verifyFormat("for (;;)\n" 1510 " BOOST_FOREACH (int &v, vec) continue;", 1511 AllowsMergedLoops); 1512 verifyFormat("for (;;) // Can't merge this\n" 1513 " continue;", 1514 AllowsMergedLoops); 1515 verifyFormat("for (;;) /* still don't merge */\n" 1516 " continue;", 1517 AllowsMergedLoops); 1518 verifyFormat("do a++;\n" 1519 "while (true);", 1520 AllowsMergedLoops); 1521 verifyFormat("do /* Don't merge */\n" 1522 " a++;\n" 1523 "while (true);", 1524 AllowsMergedLoops); 1525 verifyFormat("do // Don't merge\n" 1526 " a++;\n" 1527 "while (true);", 1528 AllowsMergedLoops); 1529 verifyFormat("do\n" 1530 " // Don't merge\n" 1531 " a++;\n" 1532 "while (true);", 1533 AllowsMergedLoops); 1534 // Without braces labels are interpreted differently. 1535 verifyFormat("{\n" 1536 " do\n" 1537 " label:\n" 1538 " a++;\n" 1539 " while (true);\n" 1540 "}", 1541 AllowsMergedLoops); 1542 } 1543 1544 TEST_F(FormatTest, FormatShortBracedStatements) { 1545 FormatStyle AllowSimpleBracedStatements = getLLVMStyle(); 1546 EXPECT_EQ(AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine, false); 1547 EXPECT_EQ(AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine, 1548 FormatStyle::SIS_Never); 1549 EXPECT_EQ(AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine, false); 1550 EXPECT_EQ(AllowSimpleBracedStatements.BraceWrapping.AfterFunction, false); 1551 verifyFormat("for (;;) {\n" 1552 " f();\n" 1553 "}"); 1554 verifyFormat("/*comment*/ for (;;) {\n" 1555 " f();\n" 1556 "}"); 1557 verifyFormat("BOOST_FOREACH (int v, vec) {\n" 1558 " f();\n" 1559 "}"); 1560 verifyFormat("/*comment*/ BOOST_FOREACH (int v, vec) {\n" 1561 " f();\n" 1562 "}"); 1563 verifyFormat("while (true) {\n" 1564 " f();\n" 1565 "}"); 1566 verifyFormat("/*comment*/ while (true) {\n" 1567 " f();\n" 1568 "}"); 1569 verifyFormat("if (true) {\n" 1570 " f();\n" 1571 "}"); 1572 verifyFormat("/*comment*/ if (true) {\n" 1573 " f();\n" 1574 "}"); 1575 1576 AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine = 1577 FormatStyle::SBS_Empty; 1578 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1579 FormatStyle::SIS_WithoutElse; 1580 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1581 verifyFormat("if (i) break;", AllowSimpleBracedStatements); 1582 verifyFormat("if (i > 0) {\n" 1583 " return i;\n" 1584 "}", 1585 AllowSimpleBracedStatements); 1586 1587 AllowSimpleBracedStatements.IfMacros.push_back("MYIF"); 1588 // Where line-lengths matter, a 2-letter synonym that maintains line length. 1589 // Not IF to avoid any confusion that IF is somehow special. 1590 AllowSimpleBracedStatements.IfMacros.push_back("FI"); 1591 AllowSimpleBracedStatements.ColumnLimit = 40; 1592 AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine = 1593 FormatStyle::SBS_Always; 1594 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true; 1595 AllowSimpleBracedStatements.BreakBeforeBraces = FormatStyle::BS_Custom; 1596 AllowSimpleBracedStatements.BraceWrapping.AfterFunction = true; 1597 AllowSimpleBracedStatements.BraceWrapping.SplitEmptyRecord = false; 1598 1599 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1600 verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements); 1601 verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1602 verifyFormat("if consteval {}", AllowSimpleBracedStatements); 1603 verifyFormat("if !consteval {}", AllowSimpleBracedStatements); 1604 verifyFormat("if CONSTEVAL {}", AllowSimpleBracedStatements); 1605 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1606 verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements); 1607 verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1608 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1609 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1610 verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements); 1611 verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements); 1612 verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1613 verifyFormat("if consteval { f(); }", AllowSimpleBracedStatements); 1614 verifyFormat("if CONSTEVAL { f(); }", AllowSimpleBracedStatements); 1615 verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements); 1616 verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements); 1617 verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1618 verifyFormat("MYIF consteval { f(); }", AllowSimpleBracedStatements); 1619 verifyFormat("MYIF CONSTEVAL { f(); }", AllowSimpleBracedStatements); 1620 verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements); 1621 verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements); 1622 verifyFormat("if (true) { fffffffffffffffffffffff(); }", 1623 AllowSimpleBracedStatements); 1624 verifyFormat("if (true) {\n" 1625 " ffffffffffffffffffffffff();\n" 1626 "}", 1627 AllowSimpleBracedStatements); 1628 verifyFormat("if (true) {\n" 1629 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1630 "}", 1631 AllowSimpleBracedStatements); 1632 verifyFormat("if (true) { //\n" 1633 " f();\n" 1634 "}", 1635 AllowSimpleBracedStatements); 1636 verifyFormat("if (true) {\n" 1637 " f();\n" 1638 " f();\n" 1639 "}", 1640 AllowSimpleBracedStatements); 1641 verifyFormat("if (true) {\n" 1642 " f();\n" 1643 "} else {\n" 1644 " f();\n" 1645 "}", 1646 AllowSimpleBracedStatements); 1647 verifyFormat("FI (true) { fffffffffffffffffffffff(); }", 1648 AllowSimpleBracedStatements); 1649 verifyFormat("MYIF (true) {\n" 1650 " ffffffffffffffffffffffff();\n" 1651 "}", 1652 AllowSimpleBracedStatements); 1653 verifyFormat("MYIF (true) {\n" 1654 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1655 "}", 1656 AllowSimpleBracedStatements); 1657 verifyFormat("MYIF (true) { //\n" 1658 " f();\n" 1659 "}", 1660 AllowSimpleBracedStatements); 1661 verifyFormat("MYIF (true) {\n" 1662 " f();\n" 1663 " f();\n" 1664 "}", 1665 AllowSimpleBracedStatements); 1666 verifyFormat("MYIF (true) {\n" 1667 " f();\n" 1668 "} else {\n" 1669 " f();\n" 1670 "}", 1671 AllowSimpleBracedStatements); 1672 1673 verifyFormat("struct A2 {\n" 1674 " int X;\n" 1675 "};", 1676 AllowSimpleBracedStatements); 1677 verifyFormat("typedef struct A2 {\n" 1678 " int X;\n" 1679 "} A2_t;", 1680 AllowSimpleBracedStatements); 1681 verifyFormat("template <int> struct A2 {\n" 1682 " struct B {};\n" 1683 "};", 1684 AllowSimpleBracedStatements); 1685 1686 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1687 FormatStyle::SIS_Never; 1688 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1689 verifyFormat("if (true) {\n" 1690 " f();\n" 1691 "}", 1692 AllowSimpleBracedStatements); 1693 verifyFormat("if (true) {\n" 1694 " f();\n" 1695 "} else {\n" 1696 " f();\n" 1697 "}", 1698 AllowSimpleBracedStatements); 1699 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1700 verifyFormat("MYIF (true) {\n" 1701 " f();\n" 1702 "}", 1703 AllowSimpleBracedStatements); 1704 verifyFormat("MYIF (true) {\n" 1705 " f();\n" 1706 "} else {\n" 1707 " f();\n" 1708 "}", 1709 AllowSimpleBracedStatements); 1710 1711 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false; 1712 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1713 verifyFormat("while (true) {\n" 1714 " f();\n" 1715 "}", 1716 AllowSimpleBracedStatements); 1717 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1718 verifyFormat("for (;;) {\n" 1719 " f();\n" 1720 "}", 1721 AllowSimpleBracedStatements); 1722 verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements); 1723 verifyFormat("BOOST_FOREACH (int v, vec) {\n" 1724 " f();\n" 1725 "}", 1726 AllowSimpleBracedStatements); 1727 1728 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1729 FormatStyle::SIS_WithoutElse; 1730 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true; 1731 AllowSimpleBracedStatements.BraceWrapping.AfterControlStatement = 1732 FormatStyle::BWACS_Always; 1733 1734 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1735 verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements); 1736 verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1737 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1738 verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements); 1739 verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1740 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1741 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1742 verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements); 1743 verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements); 1744 verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1745 verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements); 1746 verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements); 1747 verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1748 verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements); 1749 verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements); 1750 verifyFormat("if (true) { fffffffffffffffffffffff(); }", 1751 AllowSimpleBracedStatements); 1752 verifyFormat("if (true)\n" 1753 "{\n" 1754 " ffffffffffffffffffffffff();\n" 1755 "}", 1756 AllowSimpleBracedStatements); 1757 verifyFormat("if (true)\n" 1758 "{\n" 1759 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1760 "}", 1761 AllowSimpleBracedStatements); 1762 verifyFormat("if (true)\n" 1763 "{ //\n" 1764 " f();\n" 1765 "}", 1766 AllowSimpleBracedStatements); 1767 verifyFormat("if (true)\n" 1768 "{\n" 1769 " f();\n" 1770 " f();\n" 1771 "}", 1772 AllowSimpleBracedStatements); 1773 verifyFormat("if (true)\n" 1774 "{\n" 1775 " f();\n" 1776 "} else\n" 1777 "{\n" 1778 " f();\n" 1779 "}", 1780 AllowSimpleBracedStatements); 1781 verifyFormat("FI (true) { fffffffffffffffffffffff(); }", 1782 AllowSimpleBracedStatements); 1783 verifyFormat("MYIF (true)\n" 1784 "{\n" 1785 " ffffffffffffffffffffffff();\n" 1786 "}", 1787 AllowSimpleBracedStatements); 1788 verifyFormat("MYIF (true)\n" 1789 "{\n" 1790 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1791 "}", 1792 AllowSimpleBracedStatements); 1793 verifyFormat("MYIF (true)\n" 1794 "{ //\n" 1795 " f();\n" 1796 "}", 1797 AllowSimpleBracedStatements); 1798 verifyFormat("MYIF (true)\n" 1799 "{\n" 1800 " f();\n" 1801 " f();\n" 1802 "}", 1803 AllowSimpleBracedStatements); 1804 verifyFormat("MYIF (true)\n" 1805 "{\n" 1806 " f();\n" 1807 "} else\n" 1808 "{\n" 1809 " f();\n" 1810 "}", 1811 AllowSimpleBracedStatements); 1812 1813 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1814 FormatStyle::SIS_Never; 1815 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1816 verifyFormat("if (true)\n" 1817 "{\n" 1818 " f();\n" 1819 "}", 1820 AllowSimpleBracedStatements); 1821 verifyFormat("if (true)\n" 1822 "{\n" 1823 " f();\n" 1824 "} else\n" 1825 "{\n" 1826 " f();\n" 1827 "}", 1828 AllowSimpleBracedStatements); 1829 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1830 verifyFormat("MYIF (true)\n" 1831 "{\n" 1832 " f();\n" 1833 "}", 1834 AllowSimpleBracedStatements); 1835 verifyFormat("MYIF (true)\n" 1836 "{\n" 1837 " f();\n" 1838 "} else\n" 1839 "{\n" 1840 " f();\n" 1841 "}", 1842 AllowSimpleBracedStatements); 1843 1844 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false; 1845 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1846 verifyFormat("while (true)\n" 1847 "{\n" 1848 " f();\n" 1849 "}", 1850 AllowSimpleBracedStatements); 1851 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1852 verifyFormat("for (;;)\n" 1853 "{\n" 1854 " f();\n" 1855 "}", 1856 AllowSimpleBracedStatements); 1857 verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements); 1858 verifyFormat("BOOST_FOREACH (int v, vec)\n" 1859 "{\n" 1860 " f();\n" 1861 "}", 1862 AllowSimpleBracedStatements); 1863 } 1864 1865 TEST_F(FormatTest, UnderstandsMacros) { 1866 verifyFormat("#define A (parentheses)"); 1867 verifyFormat("/* comment */ #define A (parentheses)"); 1868 verifyFormat("/* comment */ /* another comment */ #define A (parentheses)"); 1869 // Even the partial code should never be merged. 1870 EXPECT_EQ("/* comment */ #define A (parentheses)\n" 1871 "#", 1872 format("/* comment */ #define A (parentheses)\n" 1873 "#")); 1874 verifyFormat("/* comment */ #define A (parentheses)\n" 1875 "#\n"); 1876 verifyFormat("/* comment */ #define A (parentheses)\n" 1877 "#define B (parentheses)"); 1878 verifyFormat("#define true ((int)1)"); 1879 verifyFormat("#define and(x)"); 1880 verifyFormat("#define if(x) x"); 1881 verifyFormat("#define return(x) (x)"); 1882 verifyFormat("#define while(x) for (; x;)"); 1883 verifyFormat("#define xor(x) (^(x))"); 1884 verifyFormat("#define __except(x)"); 1885 verifyFormat("#define __try(x)"); 1886 1887 // https://llvm.org/PR54348. 1888 verifyFormat( 1889 "#define A" 1890 " " 1891 "\\\n" 1892 " class & {}"); 1893 1894 FormatStyle Style = getLLVMStyle(); 1895 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 1896 Style.BraceWrapping.AfterFunction = true; 1897 // Test that a macro definition never gets merged with the following 1898 // definition. 1899 // FIXME: The AAA macro definition probably should not be split into 3 lines. 1900 verifyFormat("#define AAA " 1901 " \\\n" 1902 " N " 1903 " \\\n" 1904 " {\n" 1905 "#define BBB }\n", 1906 Style); 1907 // verifyFormat("#define AAA N { //\n", Style); 1908 1909 verifyFormat("MACRO(return)"); 1910 verifyFormat("MACRO(co_await)"); 1911 verifyFormat("MACRO(co_return)"); 1912 verifyFormat("MACRO(co_yield)"); 1913 verifyFormat("MACRO(return, something)"); 1914 verifyFormat("MACRO(co_return, something)"); 1915 verifyFormat("MACRO(something##something)"); 1916 verifyFormat("MACRO(return##something)"); 1917 verifyFormat("MACRO(co_return##something)"); 1918 } 1919 1920 TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) { 1921 FormatStyle Style = getLLVMStyleWithColumns(60); 1922 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 1923 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse; 1924 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 1925 EXPECT_EQ("#define A \\\n" 1926 " if (HANDLEwernufrnuLwrmviferuvnierv) \\\n" 1927 " { \\\n" 1928 " RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n" 1929 " }\n" 1930 "X;", 1931 format("#define A \\\n" 1932 " if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n" 1933 " RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n" 1934 " }\n" 1935 "X;", 1936 Style)); 1937 } 1938 1939 TEST_F(FormatTest, ParseIfElse) { 1940 verifyFormat("if (true)\n" 1941 " if (true)\n" 1942 " if (true)\n" 1943 " f();\n" 1944 " else\n" 1945 " g();\n" 1946 " else\n" 1947 " h();\n" 1948 "else\n" 1949 " i();"); 1950 verifyFormat("if (true)\n" 1951 " if (true)\n" 1952 " if (true) {\n" 1953 " if (true)\n" 1954 " f();\n" 1955 " } else {\n" 1956 " g();\n" 1957 " }\n" 1958 " else\n" 1959 " h();\n" 1960 "else {\n" 1961 " i();\n" 1962 "}"); 1963 verifyFormat("if (true)\n" 1964 " if constexpr (true)\n" 1965 " if (true) {\n" 1966 " if constexpr (true)\n" 1967 " f();\n" 1968 " } else {\n" 1969 " g();\n" 1970 " }\n" 1971 " else\n" 1972 " h();\n" 1973 "else {\n" 1974 " i();\n" 1975 "}"); 1976 verifyFormat("if (true)\n" 1977 " if CONSTEXPR (true)\n" 1978 " if (true) {\n" 1979 " if CONSTEXPR (true)\n" 1980 " f();\n" 1981 " } else {\n" 1982 " g();\n" 1983 " }\n" 1984 " else\n" 1985 " h();\n" 1986 "else {\n" 1987 " i();\n" 1988 "}"); 1989 verifyFormat("void f() {\n" 1990 " if (a) {\n" 1991 " } else {\n" 1992 " }\n" 1993 "}"); 1994 } 1995 1996 TEST_F(FormatTest, ElseIf) { 1997 verifyFormat("if (a) {\n} else if (b) {\n}"); 1998 verifyFormat("if (a)\n" 1999 " f();\n" 2000 "else if (b)\n" 2001 " g();\n" 2002 "else\n" 2003 " h();"); 2004 verifyFormat("if (a)\n" 2005 " f();\n" 2006 "else // comment\n" 2007 " if (b) {\n" 2008 " g();\n" 2009 " h();\n" 2010 " }"); 2011 verifyFormat("if constexpr (a)\n" 2012 " f();\n" 2013 "else if constexpr (b)\n" 2014 " g();\n" 2015 "else\n" 2016 " h();"); 2017 verifyFormat("if CONSTEXPR (a)\n" 2018 " f();\n" 2019 "else if CONSTEXPR (b)\n" 2020 " g();\n" 2021 "else\n" 2022 " h();"); 2023 verifyFormat("if (a) {\n" 2024 " f();\n" 2025 "}\n" 2026 "// or else ..\n" 2027 "else {\n" 2028 " g()\n" 2029 "}"); 2030 2031 verifyFormat("if (a) {\n" 2032 "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2033 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 2034 "}"); 2035 verifyFormat("if (a) {\n" 2036 "} else if constexpr (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2037 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 2038 "}"); 2039 verifyFormat("if (a) {\n" 2040 "} else if CONSTEXPR (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2041 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 2042 "}"); 2043 verifyFormat("if (a) {\n" 2044 "} else if (\n" 2045 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 2046 "}", 2047 getLLVMStyleWithColumns(62)); 2048 verifyFormat("if (a) {\n" 2049 "} else if constexpr (\n" 2050 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 2051 "}", 2052 getLLVMStyleWithColumns(62)); 2053 verifyFormat("if (a) {\n" 2054 "} else if CONSTEXPR (\n" 2055 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 2056 "}", 2057 getLLVMStyleWithColumns(62)); 2058 } 2059 2060 TEST_F(FormatTest, SeparatePointerReferenceAlignment) { 2061 FormatStyle Style = getLLVMStyle(); 2062 EXPECT_EQ(Style.PointerAlignment, FormatStyle::PAS_Right); 2063 EXPECT_EQ(Style.ReferenceAlignment, FormatStyle::RAS_Pointer); 2064 verifyFormat("int *f1(int *a, int &b, int &&c);", Style); 2065 verifyFormat("int &f2(int &&c, int *a, int &b);", Style); 2066 verifyFormat("int &&f3(int &b, int &&c, int *a);", Style); 2067 verifyFormat("int *f1(int &a) const &;", Style); 2068 verifyFormat("int *f1(int &a) const & = 0;", Style); 2069 verifyFormat("int *a = f1();", Style); 2070 verifyFormat("int &b = f2();", Style); 2071 verifyFormat("int &&c = f3();", Style); 2072 verifyFormat("for (auto a = 0, b = 0; const auto &c : {1, 2, 3})", Style); 2073 verifyFormat("for (auto a = 0, b = 0; const int &c : {1, 2, 3})", Style); 2074 verifyFormat("for (auto a = 0, b = 0; const Foo &c : {1, 2, 3})", Style); 2075 verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style); 2076 verifyFormat("for (int a = 0, b = 0; const auto &c : {1, 2, 3})", Style); 2077 verifyFormat("for (int a = 0, b = 0; const int &c : {1, 2, 3})", Style); 2078 verifyFormat("for (int a = 0, b = 0; const Foo &c : {1, 2, 3})", Style); 2079 verifyFormat("for (int a = 0, b++; const auto &c : {1, 2, 3})", Style); 2080 verifyFormat("for (int a = 0, b++; const int &c : {1, 2, 3})", Style); 2081 verifyFormat("for (int a = 0, b++; const Foo &c : {1, 2, 3})", Style); 2082 verifyFormat("for (auto x = 0; auto &c : {1, 2, 3})", Style); 2083 verifyFormat("for (auto x = 0; int &c : {1, 2, 3})", Style); 2084 verifyFormat("for (int x = 0; auto &c : {1, 2, 3})", Style); 2085 verifyFormat("for (int x = 0; int &c : {1, 2, 3})", Style); 2086 verifyFormat("for (f(); auto &c : {1, 2, 3})", Style); 2087 verifyFormat("for (f(); int &c : {1, 2, 3})", Style); 2088 verifyFormat( 2089 "function<int(int &)> res1 = [](int &a) { return 0000000000000; },\n" 2090 " res2 = [](int &a) { return 0000000000000; };", 2091 Style); 2092 2093 Style.AlignConsecutiveDeclarations.Enabled = true; 2094 verifyFormat("Const unsigned int *c;\n" 2095 "const unsigned int *d;\n" 2096 "Const unsigned int &e;\n" 2097 "const unsigned int &f;\n" 2098 "const unsigned &&g;\n" 2099 "Const unsigned h;", 2100 Style); 2101 2102 Style.PointerAlignment = FormatStyle::PAS_Left; 2103 Style.ReferenceAlignment = FormatStyle::RAS_Pointer; 2104 verifyFormat("int* f1(int* a, int& b, int&& c);", Style); 2105 verifyFormat("int& f2(int&& c, int* a, int& b);", Style); 2106 verifyFormat("int&& f3(int& b, int&& c, int* a);", Style); 2107 verifyFormat("int* f1(int& a) const& = 0;", Style); 2108 verifyFormat("int* a = f1();", Style); 2109 verifyFormat("int& b = f2();", Style); 2110 verifyFormat("int&& c = f3();", Style); 2111 verifyFormat("for (auto a = 0, b = 0; const auto& c : {1, 2, 3})", Style); 2112 verifyFormat("for (auto a = 0, b = 0; const int& c : {1, 2, 3})", Style); 2113 verifyFormat("for (auto a = 0, b = 0; const Foo& c : {1, 2, 3})", Style); 2114 verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style); 2115 verifyFormat("for (int a = 0, b = 0; const auto& c : {1, 2, 3})", Style); 2116 verifyFormat("for (int a = 0, b = 0; const int& c : {1, 2, 3})", Style); 2117 verifyFormat("for (int a = 0, b = 0; const Foo& c : {1, 2, 3})", Style); 2118 verifyFormat("for (int a = 0, b = 0; const Foo* c : {1, 2, 3})", Style); 2119 verifyFormat("for (int a = 0, b++; const auto& c : {1, 2, 3})", Style); 2120 verifyFormat("for (int a = 0, b++; const int& c : {1, 2, 3})", Style); 2121 verifyFormat("for (int a = 0, b++; const Foo& c : {1, 2, 3})", Style); 2122 verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style); 2123 verifyFormat("for (auto x = 0; auto& c : {1, 2, 3})", Style); 2124 verifyFormat("for (auto x = 0; int& c : {1, 2, 3})", Style); 2125 verifyFormat("for (int x = 0; auto& c : {1, 2, 3})", Style); 2126 verifyFormat("for (int x = 0; int& c : {1, 2, 3})", Style); 2127 verifyFormat("for (f(); auto& c : {1, 2, 3})", Style); 2128 verifyFormat("for (f(); int& c : {1, 2, 3})", Style); 2129 verifyFormat( 2130 "function<int(int&)> res1 = [](int& a) { return 0000000000000; },\n" 2131 " res2 = [](int& a) { return 0000000000000; };", 2132 Style); 2133 2134 Style.AlignConsecutiveDeclarations.Enabled = true; 2135 verifyFormat("Const unsigned int* c;\n" 2136 "const unsigned int* d;\n" 2137 "Const unsigned int& e;\n" 2138 "const unsigned int& f;\n" 2139 "const unsigned&& g;\n" 2140 "Const unsigned h;", 2141 Style); 2142 2143 Style.PointerAlignment = FormatStyle::PAS_Right; 2144 Style.ReferenceAlignment = FormatStyle::RAS_Left; 2145 verifyFormat("int *f1(int *a, int& b, int&& c);", Style); 2146 verifyFormat("int& f2(int&& c, int *a, int& b);", Style); 2147 verifyFormat("int&& f3(int& b, int&& c, int *a);", Style); 2148 verifyFormat("int *a = f1();", Style); 2149 verifyFormat("int& b = f2();", Style); 2150 verifyFormat("int&& c = f3();", Style); 2151 verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style); 2152 verifyFormat("for (int a = 0, b = 0; const Foo *c : {1, 2, 3})", Style); 2153 verifyFormat("for (int a = 0, b++; const Foo *c : {1, 2, 3})", Style); 2154 2155 Style.AlignConsecutiveDeclarations.Enabled = true; 2156 verifyFormat("Const unsigned int *c;\n" 2157 "const unsigned int *d;\n" 2158 "Const unsigned int& e;\n" 2159 "const unsigned int& f;\n" 2160 "const unsigned g;\n" 2161 "Const unsigned h;", 2162 Style); 2163 2164 Style.PointerAlignment = FormatStyle::PAS_Left; 2165 Style.ReferenceAlignment = FormatStyle::RAS_Middle; 2166 verifyFormat("int* f1(int* a, int & b, int && c);", Style); 2167 verifyFormat("int & f2(int && c, int* a, int & b);", Style); 2168 verifyFormat("int && f3(int & b, int && c, int* a);", Style); 2169 verifyFormat("int* a = f1();", Style); 2170 verifyFormat("int & b = f2();", Style); 2171 verifyFormat("int && c = f3();", Style); 2172 verifyFormat("for (auto a = 0, b = 0; const auto & c : {1, 2, 3})", Style); 2173 verifyFormat("for (auto a = 0, b = 0; const int & c : {1, 2, 3})", Style); 2174 verifyFormat("for (auto a = 0, b = 0; const Foo & c : {1, 2, 3})", Style); 2175 verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style); 2176 verifyFormat("for (int a = 0, b++; const auto & c : {1, 2, 3})", Style); 2177 verifyFormat("for (int a = 0, b++; const int & c : {1, 2, 3})", Style); 2178 verifyFormat("for (int a = 0, b++; const Foo & c : {1, 2, 3})", Style); 2179 verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style); 2180 verifyFormat("for (auto x = 0; auto & c : {1, 2, 3})", Style); 2181 verifyFormat("for (auto x = 0; int & c : {1, 2, 3})", Style); 2182 verifyFormat("for (int x = 0; auto & c : {1, 2, 3})", Style); 2183 verifyFormat("for (int x = 0; int & c : {1, 2, 3})", Style); 2184 verifyFormat("for (f(); auto & c : {1, 2, 3})", Style); 2185 verifyFormat("for (f(); int & c : {1, 2, 3})", Style); 2186 verifyFormat( 2187 "function<int(int &)> res1 = [](int & a) { return 0000000000000; },\n" 2188 " res2 = [](int & a) { return 0000000000000; };", 2189 Style); 2190 2191 Style.AlignConsecutiveDeclarations.Enabled = true; 2192 verifyFormat("Const unsigned int* c;\n" 2193 "const unsigned int* d;\n" 2194 "Const unsigned int & e;\n" 2195 "const unsigned int & f;\n" 2196 "const unsigned && g;\n" 2197 "Const unsigned h;", 2198 Style); 2199 2200 Style.PointerAlignment = FormatStyle::PAS_Middle; 2201 Style.ReferenceAlignment = FormatStyle::RAS_Right; 2202 verifyFormat("int * f1(int * a, int &b, int &&c);", Style); 2203 verifyFormat("int &f2(int &&c, int * a, int &b);", Style); 2204 verifyFormat("int &&f3(int &b, int &&c, int * a);", Style); 2205 verifyFormat("int * a = f1();", Style); 2206 verifyFormat("int &b = f2();", Style); 2207 verifyFormat("int &&c = f3();", Style); 2208 verifyFormat("for (auto a = 0, b = 0; const Foo * c : {1, 2, 3})", Style); 2209 verifyFormat("for (int a = 0, b = 0; const Foo * c : {1, 2, 3})", Style); 2210 verifyFormat("for (int a = 0, b++; const Foo * c : {1, 2, 3})", Style); 2211 2212 // FIXME: we don't handle this yet, so output may be arbitrary until it's 2213 // specifically handled 2214 // verifyFormat("int Add2(BTree * &Root, char * szToAdd)", Style); 2215 } 2216 2217 TEST_F(FormatTest, FormatsForLoop) { 2218 verifyFormat( 2219 "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n" 2220 " ++VeryVeryLongLoopVariable)\n" 2221 " ;"); 2222 verifyFormat("for (;;)\n" 2223 " f();"); 2224 verifyFormat("for (;;) {\n}"); 2225 verifyFormat("for (;;) {\n" 2226 " f();\n" 2227 "}"); 2228 verifyFormat("for (int i = 0; (i < 10); ++i) {\n}"); 2229 2230 verifyFormat( 2231 "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n" 2232 " E = UnwrappedLines.end();\n" 2233 " I != E; ++I) {\n}"); 2234 2235 verifyFormat( 2236 "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n" 2237 " ++IIIII) {\n}"); 2238 verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n" 2239 " aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n" 2240 " aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}"); 2241 verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n" 2242 " I = FD->getDeclsInPrototypeScope().begin(),\n" 2243 " E = FD->getDeclsInPrototypeScope().end();\n" 2244 " I != E; ++I) {\n}"); 2245 verifyFormat("for (SmallVectorImpl<TemplateIdAnnotationn *>::iterator\n" 2246 " I = Container.begin(),\n" 2247 " E = Container.end();\n" 2248 " I != E; ++I) {\n}", 2249 getLLVMStyleWithColumns(76)); 2250 2251 verifyFormat( 2252 "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n" 2253 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n" 2254 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2255 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 2256 " ++aaaaaaaaaaa) {\n}"); 2257 verifyFormat("for (int i = 0; i < aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 2258 " bbbbbbbbbbbbbbbbbbbb < ccccccccccccccc;\n" 2259 " ++i) {\n}"); 2260 verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n" 2261 " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n" 2262 "}"); 2263 verifyFormat("for (some_namespace::SomeIterator iter( // force break\n" 2264 " aaaaaaaaaa);\n" 2265 " iter; ++iter) {\n" 2266 "}"); 2267 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2268 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 2269 " aaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbbbbbbb;\n" 2270 " ++aaaaaaaaaaaaaaaaaaaaaaaaaaa) {"); 2271 2272 // These should not be formatted as Objective-C for-in loops. 2273 verifyFormat("for (Foo *x = 0; x != in; x++) {\n}"); 2274 verifyFormat("Foo *x;\nfor (x = 0; x != in; x++) {\n}"); 2275 verifyFormat("Foo *x;\nfor (x in y) {\n}"); 2276 verifyFormat( 2277 "for (const Foo<Bar> &baz = in.value(); !baz.at_end(); ++baz) {\n}"); 2278 2279 FormatStyle NoBinPacking = getLLVMStyle(); 2280 NoBinPacking.BinPackParameters = false; 2281 verifyFormat("for (int aaaaaaaaaaa = 1;\n" 2282 " aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n" 2283 " aaaaaaaaaaaaaaaa,\n" 2284 " aaaaaaaaaaaaaaaa,\n" 2285 " aaaaaaaaaaaaaaaa);\n" 2286 " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n" 2287 "}", 2288 NoBinPacking); 2289 verifyFormat( 2290 "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n" 2291 " E = UnwrappedLines.end();\n" 2292 " I != E;\n" 2293 " ++I) {\n}", 2294 NoBinPacking); 2295 2296 FormatStyle AlignLeft = getLLVMStyle(); 2297 AlignLeft.PointerAlignment = FormatStyle::PAS_Left; 2298 verifyFormat("for (A* a = start; a < end; ++a, ++value) {\n}", AlignLeft); 2299 } 2300 2301 TEST_F(FormatTest, RangeBasedForLoops) { 2302 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 2303 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 2304 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n" 2305 " aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}"); 2306 verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n" 2307 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 2308 verifyFormat("for (aaaaaaaaa aaaaaaaaaaaaaaaaaaaaa :\n" 2309 " aaaaaaaaaaaa.aaaaaaaaaaaa().aaaaaaaaa().a()) {\n}"); 2310 } 2311 2312 TEST_F(FormatTest, ForEachLoops) { 2313 FormatStyle Style = getLLVMStyle(); 2314 EXPECT_EQ(Style.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 2315 EXPECT_EQ(Style.AllowShortLoopsOnASingleLine, false); 2316 verifyFormat("void f() {\n" 2317 " for (;;) {\n" 2318 " }\n" 2319 " foreach (Item *item, itemlist) {\n" 2320 " }\n" 2321 " Q_FOREACH (Item *item, itemlist) {\n" 2322 " }\n" 2323 " BOOST_FOREACH (Item *item, itemlist) {\n" 2324 " }\n" 2325 " UNKNOWN_FOREACH(Item * item, itemlist) {}\n" 2326 "}", 2327 Style); 2328 verifyFormat("void f() {\n" 2329 " for (;;)\n" 2330 " int j = 1;\n" 2331 " Q_FOREACH (int v, vec)\n" 2332 " v *= 2;\n" 2333 " for (;;) {\n" 2334 " int j = 1;\n" 2335 " }\n" 2336 " Q_FOREACH (int v, vec) {\n" 2337 " v *= 2;\n" 2338 " }\n" 2339 "}", 2340 Style); 2341 2342 FormatStyle ShortBlocks = getLLVMStyle(); 2343 ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 2344 EXPECT_EQ(ShortBlocks.AllowShortLoopsOnASingleLine, false); 2345 verifyFormat("void f() {\n" 2346 " for (;;)\n" 2347 " int j = 1;\n" 2348 " Q_FOREACH (int &v, vec)\n" 2349 " v *= 2;\n" 2350 " for (;;) {\n" 2351 " int j = 1;\n" 2352 " }\n" 2353 " Q_FOREACH (int &v, vec) {\n" 2354 " int j = 1;\n" 2355 " }\n" 2356 "}", 2357 ShortBlocks); 2358 2359 FormatStyle ShortLoops = getLLVMStyle(); 2360 ShortLoops.AllowShortLoopsOnASingleLine = true; 2361 EXPECT_EQ(ShortLoops.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 2362 verifyFormat("void f() {\n" 2363 " for (;;) int j = 1;\n" 2364 " Q_FOREACH (int &v, vec) int j = 1;\n" 2365 " for (;;) {\n" 2366 " int j = 1;\n" 2367 " }\n" 2368 " Q_FOREACH (int &v, vec) {\n" 2369 " int j = 1;\n" 2370 " }\n" 2371 "}", 2372 ShortLoops); 2373 2374 FormatStyle ShortBlocksAndLoops = getLLVMStyle(); 2375 ShortBlocksAndLoops.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 2376 ShortBlocksAndLoops.AllowShortLoopsOnASingleLine = true; 2377 verifyFormat("void f() {\n" 2378 " for (;;) int j = 1;\n" 2379 " Q_FOREACH (int &v, vec) int j = 1;\n" 2380 " for (;;) { int j = 1; }\n" 2381 " Q_FOREACH (int &v, vec) { int j = 1; }\n" 2382 "}", 2383 ShortBlocksAndLoops); 2384 2385 Style.SpaceBeforeParens = 2386 FormatStyle::SBPO_ControlStatementsExceptControlMacros; 2387 verifyFormat("void f() {\n" 2388 " for (;;) {\n" 2389 " }\n" 2390 " foreach(Item *item, itemlist) {\n" 2391 " }\n" 2392 " Q_FOREACH(Item *item, itemlist) {\n" 2393 " }\n" 2394 " BOOST_FOREACH(Item *item, itemlist) {\n" 2395 " }\n" 2396 " UNKNOWN_FOREACH(Item * item, itemlist) {}\n" 2397 "}", 2398 Style); 2399 2400 // As function-like macros. 2401 verifyFormat("#define foreach(x, y)\n" 2402 "#define Q_FOREACH(x, y)\n" 2403 "#define BOOST_FOREACH(x, y)\n" 2404 "#define UNKNOWN_FOREACH(x, y)\n"); 2405 2406 // Not as function-like macros. 2407 verifyFormat("#define foreach (x, y)\n" 2408 "#define Q_FOREACH (x, y)\n" 2409 "#define BOOST_FOREACH (x, y)\n" 2410 "#define UNKNOWN_FOREACH (x, y)\n"); 2411 2412 // handle microsoft non standard extension 2413 verifyFormat("for each (char c in x->MyStringProperty)"); 2414 } 2415 2416 TEST_F(FormatTest, FormatsWhileLoop) { 2417 verifyFormat("while (true) {\n}"); 2418 verifyFormat("while (true)\n" 2419 " f();"); 2420 verifyFormat("while () {\n}"); 2421 verifyFormat("while () {\n" 2422 " f();\n" 2423 "}"); 2424 } 2425 2426 TEST_F(FormatTest, FormatsDoWhile) { 2427 verifyFormat("do {\n" 2428 " do_something();\n" 2429 "} while (something());"); 2430 verifyFormat("do\n" 2431 " do_something();\n" 2432 "while (something());"); 2433 } 2434 2435 TEST_F(FormatTest, FormatsSwitchStatement) { 2436 verifyFormat("switch (x) {\n" 2437 "case 1:\n" 2438 " f();\n" 2439 " break;\n" 2440 "case kFoo:\n" 2441 "case ns::kBar:\n" 2442 "case kBaz:\n" 2443 " break;\n" 2444 "default:\n" 2445 " g();\n" 2446 " break;\n" 2447 "}"); 2448 verifyFormat("switch (x) {\n" 2449 "case 1: {\n" 2450 " f();\n" 2451 " break;\n" 2452 "}\n" 2453 "case 2: {\n" 2454 " break;\n" 2455 "}\n" 2456 "}"); 2457 verifyFormat("switch (x) {\n" 2458 "case 1: {\n" 2459 " f();\n" 2460 " {\n" 2461 " g();\n" 2462 " h();\n" 2463 " }\n" 2464 " break;\n" 2465 "}\n" 2466 "}"); 2467 verifyFormat("switch (x) {\n" 2468 "case 1: {\n" 2469 " f();\n" 2470 " if (foo) {\n" 2471 " g();\n" 2472 " h();\n" 2473 " }\n" 2474 " break;\n" 2475 "}\n" 2476 "}"); 2477 verifyFormat("switch (x) {\n" 2478 "case 1: {\n" 2479 " f();\n" 2480 " g();\n" 2481 "} break;\n" 2482 "}"); 2483 verifyFormat("switch (test)\n" 2484 " ;"); 2485 verifyFormat("switch (x) {\n" 2486 "default: {\n" 2487 " // Do nothing.\n" 2488 "}\n" 2489 "}"); 2490 verifyFormat("switch (x) {\n" 2491 "// comment\n" 2492 "// if 1, do f()\n" 2493 "case 1:\n" 2494 " f();\n" 2495 "}"); 2496 verifyFormat("switch (x) {\n" 2497 "case 1:\n" 2498 " // Do amazing stuff\n" 2499 " {\n" 2500 " f();\n" 2501 " g();\n" 2502 " }\n" 2503 " break;\n" 2504 "}"); 2505 verifyFormat("#define A \\\n" 2506 " switch (x) { \\\n" 2507 " case a: \\\n" 2508 " foo = b; \\\n" 2509 " }", 2510 getLLVMStyleWithColumns(20)); 2511 verifyFormat("#define OPERATION_CASE(name) \\\n" 2512 " case OP_name: \\\n" 2513 " return operations::Operation##name\n", 2514 getLLVMStyleWithColumns(40)); 2515 verifyFormat("switch (x) {\n" 2516 "case 1:;\n" 2517 "default:;\n" 2518 " int i;\n" 2519 "}"); 2520 2521 verifyGoogleFormat("switch (x) {\n" 2522 " case 1:\n" 2523 " f();\n" 2524 " break;\n" 2525 " case kFoo:\n" 2526 " case ns::kBar:\n" 2527 " case kBaz:\n" 2528 " break;\n" 2529 " default:\n" 2530 " g();\n" 2531 " break;\n" 2532 "}"); 2533 verifyGoogleFormat("switch (x) {\n" 2534 " case 1: {\n" 2535 " f();\n" 2536 " break;\n" 2537 " }\n" 2538 "}"); 2539 verifyGoogleFormat("switch (test)\n" 2540 " ;"); 2541 2542 verifyGoogleFormat("#define OPERATION_CASE(name) \\\n" 2543 " case OP_name: \\\n" 2544 " return operations::Operation##name\n"); 2545 verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n" 2546 " // Get the correction operation class.\n" 2547 " switch (OpCode) {\n" 2548 " CASE(Add);\n" 2549 " CASE(Subtract);\n" 2550 " default:\n" 2551 " return operations::Unknown;\n" 2552 " }\n" 2553 "#undef OPERATION_CASE\n" 2554 "}"); 2555 verifyFormat("DEBUG({\n" 2556 " switch (x) {\n" 2557 " case A:\n" 2558 " f();\n" 2559 " break;\n" 2560 " // fallthrough\n" 2561 " case B:\n" 2562 " g();\n" 2563 " break;\n" 2564 " }\n" 2565 "});"); 2566 EXPECT_EQ("DEBUG({\n" 2567 " switch (x) {\n" 2568 " case A:\n" 2569 " f();\n" 2570 " break;\n" 2571 " // On B:\n" 2572 " case B:\n" 2573 " g();\n" 2574 " break;\n" 2575 " }\n" 2576 "});", 2577 format("DEBUG({\n" 2578 " switch (x) {\n" 2579 " case A:\n" 2580 " f();\n" 2581 " break;\n" 2582 " // On B:\n" 2583 " case B:\n" 2584 " g();\n" 2585 " break;\n" 2586 " }\n" 2587 "});", 2588 getLLVMStyle())); 2589 EXPECT_EQ("switch (n) {\n" 2590 "case 0: {\n" 2591 " return false;\n" 2592 "}\n" 2593 "default: {\n" 2594 " return true;\n" 2595 "}\n" 2596 "}", 2597 format("switch (n)\n" 2598 "{\n" 2599 "case 0: {\n" 2600 " return false;\n" 2601 "}\n" 2602 "default: {\n" 2603 " return true;\n" 2604 "}\n" 2605 "}", 2606 getLLVMStyle())); 2607 verifyFormat("switch (a) {\n" 2608 "case (b):\n" 2609 " return;\n" 2610 "}"); 2611 2612 verifyFormat("switch (a) {\n" 2613 "case some_namespace::\n" 2614 " some_constant:\n" 2615 " return;\n" 2616 "}", 2617 getLLVMStyleWithColumns(34)); 2618 2619 verifyFormat("switch (a) {\n" 2620 "[[likely]] case 1:\n" 2621 " return;\n" 2622 "}"); 2623 verifyFormat("switch (a) {\n" 2624 "[[likely]] [[other::likely]] case 1:\n" 2625 " return;\n" 2626 "}"); 2627 verifyFormat("switch (x) {\n" 2628 "case 1:\n" 2629 " return;\n" 2630 "[[likely]] case 2:\n" 2631 " return;\n" 2632 "}"); 2633 verifyFormat("switch (a) {\n" 2634 "case 1:\n" 2635 "[[likely]] case 2:\n" 2636 " return;\n" 2637 "}"); 2638 FormatStyle Attributes = getLLVMStyle(); 2639 Attributes.AttributeMacros.push_back("LIKELY"); 2640 Attributes.AttributeMacros.push_back("OTHER_LIKELY"); 2641 verifyFormat("switch (a) {\n" 2642 "LIKELY case b:\n" 2643 " return;\n" 2644 "}", 2645 Attributes); 2646 verifyFormat("switch (a) {\n" 2647 "LIKELY OTHER_LIKELY() case b:\n" 2648 " return;\n" 2649 "}", 2650 Attributes); 2651 verifyFormat("switch (a) {\n" 2652 "case 1:\n" 2653 " return;\n" 2654 "LIKELY case 2:\n" 2655 " return;\n" 2656 "}", 2657 Attributes); 2658 verifyFormat("switch (a) {\n" 2659 "case 1:\n" 2660 "LIKELY case 2:\n" 2661 " return;\n" 2662 "}", 2663 Attributes); 2664 2665 FormatStyle Style = getLLVMStyle(); 2666 Style.IndentCaseLabels = true; 2667 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 2668 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2669 Style.BraceWrapping.AfterCaseLabel = true; 2670 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 2671 EXPECT_EQ("switch (n)\n" 2672 "{\n" 2673 " case 0:\n" 2674 " {\n" 2675 " return false;\n" 2676 " }\n" 2677 " default:\n" 2678 " {\n" 2679 " return true;\n" 2680 " }\n" 2681 "}", 2682 format("switch (n) {\n" 2683 " case 0: {\n" 2684 " return false;\n" 2685 " }\n" 2686 " default: {\n" 2687 " return true;\n" 2688 " }\n" 2689 "}", 2690 Style)); 2691 Style.BraceWrapping.AfterCaseLabel = false; 2692 EXPECT_EQ("switch (n)\n" 2693 "{\n" 2694 " case 0: {\n" 2695 " return false;\n" 2696 " }\n" 2697 " default: {\n" 2698 " return true;\n" 2699 " }\n" 2700 "}", 2701 format("switch (n) {\n" 2702 " case 0:\n" 2703 " {\n" 2704 " return false;\n" 2705 " }\n" 2706 " default:\n" 2707 " {\n" 2708 " return true;\n" 2709 " }\n" 2710 "}", 2711 Style)); 2712 Style.IndentCaseLabels = false; 2713 Style.IndentCaseBlocks = true; 2714 EXPECT_EQ("switch (n)\n" 2715 "{\n" 2716 "case 0:\n" 2717 " {\n" 2718 " return false;\n" 2719 " }\n" 2720 "case 1:\n" 2721 " break;\n" 2722 "default:\n" 2723 " {\n" 2724 " return true;\n" 2725 " }\n" 2726 "}", 2727 format("switch (n) {\n" 2728 "case 0: {\n" 2729 " return false;\n" 2730 "}\n" 2731 "case 1:\n" 2732 " break;\n" 2733 "default: {\n" 2734 " return true;\n" 2735 "}\n" 2736 "}", 2737 Style)); 2738 Style.IndentCaseLabels = true; 2739 Style.IndentCaseBlocks = true; 2740 EXPECT_EQ("switch (n)\n" 2741 "{\n" 2742 " case 0:\n" 2743 " {\n" 2744 " return false;\n" 2745 " }\n" 2746 " case 1:\n" 2747 " break;\n" 2748 " default:\n" 2749 " {\n" 2750 " return true;\n" 2751 " }\n" 2752 "}", 2753 format("switch (n) {\n" 2754 "case 0: {\n" 2755 " return false;\n" 2756 "}\n" 2757 "case 1:\n" 2758 " break;\n" 2759 "default: {\n" 2760 " return true;\n" 2761 "}\n" 2762 "}", 2763 Style)); 2764 } 2765 2766 TEST_F(FormatTest, CaseRanges) { 2767 verifyFormat("switch (x) {\n" 2768 "case 'A' ... 'Z':\n" 2769 "case 1 ... 5:\n" 2770 "case a ... b:\n" 2771 " break;\n" 2772 "}"); 2773 } 2774 2775 TEST_F(FormatTest, ShortEnums) { 2776 FormatStyle Style = getLLVMStyle(); 2777 EXPECT_TRUE(Style.AllowShortEnumsOnASingleLine); 2778 EXPECT_FALSE(Style.BraceWrapping.AfterEnum); 2779 verifyFormat("enum { A, B, C } ShortEnum1, ShortEnum2;", Style); 2780 verifyFormat("typedef enum { A, B, C } ShortEnum1, ShortEnum2;", Style); 2781 Style.AllowShortEnumsOnASingleLine = false; 2782 verifyFormat("enum {\n" 2783 " A,\n" 2784 " B,\n" 2785 " C\n" 2786 "} ShortEnum1, ShortEnum2;", 2787 Style); 2788 verifyFormat("typedef enum {\n" 2789 " A,\n" 2790 " B,\n" 2791 " C\n" 2792 "} ShortEnum1, ShortEnum2;", 2793 Style); 2794 verifyFormat("enum {\n" 2795 " A,\n" 2796 "} ShortEnum1, ShortEnum2;", 2797 Style); 2798 verifyFormat("typedef enum {\n" 2799 " A,\n" 2800 "} ShortEnum1, ShortEnum2;", 2801 Style); 2802 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2803 Style.BraceWrapping.AfterEnum = true; 2804 verifyFormat("enum\n" 2805 "{\n" 2806 " A,\n" 2807 " B,\n" 2808 " C\n" 2809 "} ShortEnum1, ShortEnum2;", 2810 Style); 2811 verifyFormat("typedef enum\n" 2812 "{\n" 2813 " A,\n" 2814 " B,\n" 2815 " C\n" 2816 "} ShortEnum1, ShortEnum2;", 2817 Style); 2818 } 2819 2820 TEST_F(FormatTest, ShortCaseLabels) { 2821 FormatStyle Style = getLLVMStyle(); 2822 Style.AllowShortCaseLabelsOnASingleLine = true; 2823 verifyFormat("switch (a) {\n" 2824 "case 1: x = 1; break;\n" 2825 "case 2: return;\n" 2826 "case 3:\n" 2827 "case 4:\n" 2828 "case 5: return;\n" 2829 "case 6: // comment\n" 2830 " return;\n" 2831 "case 7:\n" 2832 " // comment\n" 2833 " return;\n" 2834 "case 8:\n" 2835 " x = 8; // comment\n" 2836 " break;\n" 2837 "default: y = 1; break;\n" 2838 "}", 2839 Style); 2840 verifyFormat("switch (a) {\n" 2841 "case 0: return; // comment\n" 2842 "case 1: break; // comment\n" 2843 "case 2: return;\n" 2844 "// comment\n" 2845 "case 3: return;\n" 2846 "// comment 1\n" 2847 "// comment 2\n" 2848 "// comment 3\n" 2849 "case 4: break; /* comment */\n" 2850 "case 5:\n" 2851 " // comment\n" 2852 " break;\n" 2853 "case 6: /* comment */ x = 1; break;\n" 2854 "case 7: x = /* comment */ 1; break;\n" 2855 "case 8:\n" 2856 " x = 1; /* comment */\n" 2857 " break;\n" 2858 "case 9:\n" 2859 " break; // comment line 1\n" 2860 " // comment line 2\n" 2861 "}", 2862 Style); 2863 EXPECT_EQ("switch (a) {\n" 2864 "case 1:\n" 2865 " x = 8;\n" 2866 " // fall through\n" 2867 "case 2: x = 8;\n" 2868 "// comment\n" 2869 "case 3:\n" 2870 " return; /* comment line 1\n" 2871 " * comment line 2 */\n" 2872 "case 4: i = 8;\n" 2873 "// something else\n" 2874 "#if FOO\n" 2875 "case 5: break;\n" 2876 "#endif\n" 2877 "}", 2878 format("switch (a) {\n" 2879 "case 1: x = 8;\n" 2880 " // fall through\n" 2881 "case 2:\n" 2882 " x = 8;\n" 2883 "// comment\n" 2884 "case 3:\n" 2885 " return; /* comment line 1\n" 2886 " * comment line 2 */\n" 2887 "case 4:\n" 2888 " i = 8;\n" 2889 "// something else\n" 2890 "#if FOO\n" 2891 "case 5: break;\n" 2892 "#endif\n" 2893 "}", 2894 Style)); 2895 EXPECT_EQ("switch (a) {\n" 2896 "case 0:\n" 2897 " return; // long long long long long long long long long long " 2898 "long long comment\n" 2899 " // line\n" 2900 "}", 2901 format("switch (a) {\n" 2902 "case 0: return; // long long long long long long long long " 2903 "long long long long comment line\n" 2904 "}", 2905 Style)); 2906 EXPECT_EQ("switch (a) {\n" 2907 "case 0:\n" 2908 " return; /* long long long long long long long long long long " 2909 "long long comment\n" 2910 " line */\n" 2911 "}", 2912 format("switch (a) {\n" 2913 "case 0: return; /* long long long long long long long long " 2914 "long long long long comment line */\n" 2915 "}", 2916 Style)); 2917 verifyFormat("switch (a) {\n" 2918 "#if FOO\n" 2919 "case 0: return 0;\n" 2920 "#endif\n" 2921 "}", 2922 Style); 2923 verifyFormat("switch (a) {\n" 2924 "case 1: {\n" 2925 "}\n" 2926 "case 2: {\n" 2927 " return;\n" 2928 "}\n" 2929 "case 3: {\n" 2930 " x = 1;\n" 2931 " return;\n" 2932 "}\n" 2933 "case 4:\n" 2934 " if (x)\n" 2935 " return;\n" 2936 "}", 2937 Style); 2938 Style.ColumnLimit = 21; 2939 verifyFormat("switch (a) {\n" 2940 "case 1: x = 1; break;\n" 2941 "case 2: return;\n" 2942 "case 3:\n" 2943 "case 4:\n" 2944 "case 5: return;\n" 2945 "default:\n" 2946 " y = 1;\n" 2947 " break;\n" 2948 "}", 2949 Style); 2950 Style.ColumnLimit = 80; 2951 Style.AllowShortCaseLabelsOnASingleLine = false; 2952 Style.IndentCaseLabels = true; 2953 EXPECT_EQ("switch (n) {\n" 2954 " default /*comments*/:\n" 2955 " return true;\n" 2956 " case 0:\n" 2957 " return false;\n" 2958 "}", 2959 format("switch (n) {\n" 2960 "default/*comments*/:\n" 2961 " return true;\n" 2962 "case 0:\n" 2963 " return false;\n" 2964 "}", 2965 Style)); 2966 Style.AllowShortCaseLabelsOnASingleLine = true; 2967 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2968 Style.BraceWrapping.AfterCaseLabel = true; 2969 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 2970 EXPECT_EQ("switch (n)\n" 2971 "{\n" 2972 " case 0:\n" 2973 " {\n" 2974 " return false;\n" 2975 " }\n" 2976 " default:\n" 2977 " {\n" 2978 " return true;\n" 2979 " }\n" 2980 "}", 2981 format("switch (n) {\n" 2982 " case 0: {\n" 2983 " return false;\n" 2984 " }\n" 2985 " default:\n" 2986 " {\n" 2987 " return true;\n" 2988 " }\n" 2989 "}", 2990 Style)); 2991 } 2992 2993 TEST_F(FormatTest, FormatsLabels) { 2994 verifyFormat("void f() {\n" 2995 " some_code();\n" 2996 "test_label:\n" 2997 " some_other_code();\n" 2998 " {\n" 2999 " some_more_code();\n" 3000 " another_label:\n" 3001 " some_more_code();\n" 3002 " }\n" 3003 "}"); 3004 verifyFormat("{\n" 3005 " some_code();\n" 3006 "test_label:\n" 3007 " some_other_code();\n" 3008 "}"); 3009 verifyFormat("{\n" 3010 " some_code();\n" 3011 "test_label:;\n" 3012 " int i = 0;\n" 3013 "}"); 3014 FormatStyle Style = getLLVMStyle(); 3015 Style.IndentGotoLabels = false; 3016 verifyFormat("void f() {\n" 3017 " some_code();\n" 3018 "test_label:\n" 3019 " some_other_code();\n" 3020 " {\n" 3021 " some_more_code();\n" 3022 "another_label:\n" 3023 " some_more_code();\n" 3024 " }\n" 3025 "}", 3026 Style); 3027 verifyFormat("{\n" 3028 " some_code();\n" 3029 "test_label:\n" 3030 " some_other_code();\n" 3031 "}", 3032 Style); 3033 verifyFormat("{\n" 3034 " some_code();\n" 3035 "test_label:;\n" 3036 " int i = 0;\n" 3037 "}"); 3038 } 3039 3040 TEST_F(FormatTest, MultiLineControlStatements) { 3041 FormatStyle Style = getLLVMStyleWithColumns(20); 3042 Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom; 3043 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine; 3044 // Short lines should keep opening brace on same line. 3045 EXPECT_EQ("if (foo) {\n" 3046 " bar();\n" 3047 "}", 3048 format("if(foo){bar();}", Style)); 3049 EXPECT_EQ("if (foo) {\n" 3050 " bar();\n" 3051 "} else {\n" 3052 " baz();\n" 3053 "}", 3054 format("if(foo){bar();}else{baz();}", Style)); 3055 EXPECT_EQ("if (foo && bar) {\n" 3056 " baz();\n" 3057 "}", 3058 format("if(foo&&bar){baz();}", Style)); 3059 EXPECT_EQ("if (foo) {\n" 3060 " bar();\n" 3061 "} else if (baz) {\n" 3062 " quux();\n" 3063 "}", 3064 format("if(foo){bar();}else if(baz){quux();}", Style)); 3065 EXPECT_EQ( 3066 "if (foo) {\n" 3067 " bar();\n" 3068 "} else if (baz) {\n" 3069 " quux();\n" 3070 "} else {\n" 3071 " foobar();\n" 3072 "}", 3073 format("if(foo){bar();}else if(baz){quux();}else{foobar();}", Style)); 3074 EXPECT_EQ("for (;;) {\n" 3075 " foo();\n" 3076 "}", 3077 format("for(;;){foo();}")); 3078 EXPECT_EQ("while (1) {\n" 3079 " foo();\n" 3080 "}", 3081 format("while(1){foo();}", Style)); 3082 EXPECT_EQ("switch (foo) {\n" 3083 "case bar:\n" 3084 " return;\n" 3085 "}", 3086 format("switch(foo){case bar:return;}", Style)); 3087 EXPECT_EQ("try {\n" 3088 " foo();\n" 3089 "} catch (...) {\n" 3090 " bar();\n" 3091 "}", 3092 format("try{foo();}catch(...){bar();}", Style)); 3093 EXPECT_EQ("do {\n" 3094 " foo();\n" 3095 "} while (bar &&\n" 3096 " baz);", 3097 format("do{foo();}while(bar&&baz);", Style)); 3098 // Long lines should put opening brace on new line. 3099 verifyFormat("void f() {\n" 3100 " if (a1 && a2 &&\n" 3101 " a3)\n" 3102 " {\n" 3103 " quux();\n" 3104 " }\n" 3105 "}", 3106 "void f(){if(a1&&a2&&a3){quux();}}", Style); 3107 EXPECT_EQ("if (foo && bar &&\n" 3108 " baz)\n" 3109 "{\n" 3110 " quux();\n" 3111 "}", 3112 format("if(foo&&bar&&baz){quux();}", Style)); 3113 EXPECT_EQ("if (foo && bar &&\n" 3114 " baz)\n" 3115 "{\n" 3116 " quux();\n" 3117 "}", 3118 format("if (foo && bar &&\n" 3119 " baz) {\n" 3120 " quux();\n" 3121 "}", 3122 Style)); 3123 EXPECT_EQ("if (foo) {\n" 3124 " bar();\n" 3125 "} else if (baz ||\n" 3126 " quux)\n" 3127 "{\n" 3128 " foobar();\n" 3129 "}", 3130 format("if(foo){bar();}else if(baz||quux){foobar();}", Style)); 3131 EXPECT_EQ( 3132 "if (foo) {\n" 3133 " bar();\n" 3134 "} else if (baz ||\n" 3135 " quux)\n" 3136 "{\n" 3137 " foobar();\n" 3138 "} else {\n" 3139 " barbaz();\n" 3140 "}", 3141 format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}", 3142 Style)); 3143 EXPECT_EQ("for (int i = 0;\n" 3144 " i < 10; ++i)\n" 3145 "{\n" 3146 " foo();\n" 3147 "}", 3148 format("for(int i=0;i<10;++i){foo();}", Style)); 3149 EXPECT_EQ("foreach (int i,\n" 3150 " list)\n" 3151 "{\n" 3152 " foo();\n" 3153 "}", 3154 format("foreach(int i, list){foo();}", Style)); 3155 Style.ColumnLimit = 3156 40; // to concentrate at brace wrapping, not line wrap due to column limit 3157 EXPECT_EQ("foreach (int i, list) {\n" 3158 " foo();\n" 3159 "}", 3160 format("foreach(int i, list){foo();}", Style)); 3161 Style.ColumnLimit = 3162 20; // to concentrate at brace wrapping, not line wrap due to column limit 3163 EXPECT_EQ("while (foo || bar ||\n" 3164 " baz)\n" 3165 "{\n" 3166 " quux();\n" 3167 "}", 3168 format("while(foo||bar||baz){quux();}", Style)); 3169 EXPECT_EQ("switch (\n" 3170 " foo = barbaz)\n" 3171 "{\n" 3172 "case quux:\n" 3173 " return;\n" 3174 "}", 3175 format("switch(foo=barbaz){case quux:return;}", Style)); 3176 EXPECT_EQ("try {\n" 3177 " foo();\n" 3178 "} catch (\n" 3179 " Exception &bar)\n" 3180 "{\n" 3181 " baz();\n" 3182 "}", 3183 format("try{foo();}catch(Exception&bar){baz();}", Style)); 3184 Style.ColumnLimit = 3185 40; // to concentrate at brace wrapping, not line wrap due to column limit 3186 EXPECT_EQ("try {\n" 3187 " foo();\n" 3188 "} catch (Exception &bar) {\n" 3189 " baz();\n" 3190 "}", 3191 format("try{foo();}catch(Exception&bar){baz();}", Style)); 3192 Style.ColumnLimit = 3193 20; // to concentrate at brace wrapping, not line wrap due to column limit 3194 3195 Style.BraceWrapping.BeforeElse = true; 3196 EXPECT_EQ( 3197 "if (foo) {\n" 3198 " bar();\n" 3199 "}\n" 3200 "else if (baz ||\n" 3201 " quux)\n" 3202 "{\n" 3203 " foobar();\n" 3204 "}\n" 3205 "else {\n" 3206 " barbaz();\n" 3207 "}", 3208 format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}", 3209 Style)); 3210 3211 Style.BraceWrapping.BeforeCatch = true; 3212 EXPECT_EQ("try {\n" 3213 " foo();\n" 3214 "}\n" 3215 "catch (...) {\n" 3216 " baz();\n" 3217 "}", 3218 format("try{foo();}catch(...){baz();}", Style)); 3219 3220 Style.BraceWrapping.AfterFunction = true; 3221 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine; 3222 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 3223 Style.ColumnLimit = 80; 3224 verifyFormat("void shortfunction() { bar(); }", Style); 3225 3226 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 3227 verifyFormat("void shortfunction()\n" 3228 "{\n" 3229 " bar();\n" 3230 "}", 3231 Style); 3232 } 3233 3234 TEST_F(FormatTest, BeforeWhile) { 3235 FormatStyle Style = getLLVMStyle(); 3236 Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom; 3237 3238 verifyFormat("do {\n" 3239 " foo();\n" 3240 "} while (1);", 3241 Style); 3242 Style.BraceWrapping.BeforeWhile = true; 3243 verifyFormat("do {\n" 3244 " foo();\n" 3245 "}\n" 3246 "while (1);", 3247 Style); 3248 } 3249 3250 //===----------------------------------------------------------------------===// 3251 // Tests for classes, namespaces, etc. 3252 //===----------------------------------------------------------------------===// 3253 3254 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) { 3255 verifyFormat("class A {};"); 3256 } 3257 3258 TEST_F(FormatTest, UnderstandsAccessSpecifiers) { 3259 verifyFormat("class A {\n" 3260 "public:\n" 3261 "public: // comment\n" 3262 "protected:\n" 3263 "private:\n" 3264 " void f() {}\n" 3265 "};"); 3266 verifyFormat("export class A {\n" 3267 "public:\n" 3268 "public: // comment\n" 3269 "protected:\n" 3270 "private:\n" 3271 " void f() {}\n" 3272 "};"); 3273 verifyGoogleFormat("class A {\n" 3274 " public:\n" 3275 " protected:\n" 3276 " private:\n" 3277 " void f() {}\n" 3278 "};"); 3279 verifyGoogleFormat("export class A {\n" 3280 " public:\n" 3281 " protected:\n" 3282 " private:\n" 3283 " void f() {}\n" 3284 "};"); 3285 verifyFormat("class A {\n" 3286 "public slots:\n" 3287 " void f1() {}\n" 3288 "public Q_SLOTS:\n" 3289 " void f2() {}\n" 3290 "protected slots:\n" 3291 " void f3() {}\n" 3292 "protected Q_SLOTS:\n" 3293 " void f4() {}\n" 3294 "private slots:\n" 3295 " void f5() {}\n" 3296 "private Q_SLOTS:\n" 3297 " void f6() {}\n" 3298 "signals:\n" 3299 " void g1();\n" 3300 "Q_SIGNALS:\n" 3301 " void g2();\n" 3302 "};"); 3303 3304 // Don't interpret 'signals' the wrong way. 3305 verifyFormat("signals.set();"); 3306 verifyFormat("for (Signals signals : f()) {\n}"); 3307 verifyFormat("{\n" 3308 " signals.set(); // This needs indentation.\n" 3309 "}"); 3310 verifyFormat("void f() {\n" 3311 "label:\n" 3312 " signals.baz();\n" 3313 "}"); 3314 verifyFormat("private[1];"); 3315 verifyFormat("testArray[public] = 1;"); 3316 verifyFormat("public();"); 3317 verifyFormat("myFunc(public);"); 3318 verifyFormat("std::vector<int> testVec = {private};"); 3319 verifyFormat("private.p = 1;"); 3320 verifyFormat("void function(private...){};"); 3321 verifyFormat("if (private && public)\n"); 3322 verifyFormat("private &= true;"); 3323 verifyFormat("int x = private * public;"); 3324 verifyFormat("public *= private;"); 3325 verifyFormat("int x = public + private;"); 3326 verifyFormat("private++;"); 3327 verifyFormat("++private;"); 3328 verifyFormat("public += private;"); 3329 verifyFormat("public = public - private;"); 3330 verifyFormat("public->foo();"); 3331 verifyFormat("private--;"); 3332 verifyFormat("--private;"); 3333 verifyFormat("public -= 1;"); 3334 verifyFormat("if (!private && !public)\n"); 3335 verifyFormat("public != private;"); 3336 verifyFormat("int x = public / private;"); 3337 verifyFormat("public /= 2;"); 3338 verifyFormat("public = public % 2;"); 3339 verifyFormat("public %= 2;"); 3340 verifyFormat("if (public < private)\n"); 3341 verifyFormat("public << private;"); 3342 verifyFormat("public <<= private;"); 3343 verifyFormat("if (public > private)\n"); 3344 verifyFormat("public >> private;"); 3345 verifyFormat("public >>= private;"); 3346 verifyFormat("public ^ private;"); 3347 verifyFormat("public ^= private;"); 3348 verifyFormat("public | private;"); 3349 verifyFormat("public |= private;"); 3350 verifyFormat("auto x = private ? 1 : 2;"); 3351 verifyFormat("if (public == private)\n"); 3352 verifyFormat("void foo(public, private)"); 3353 verifyFormat("public::foo();"); 3354 3355 verifyFormat("class A {\n" 3356 "public:\n" 3357 " std::unique_ptr<int *[]> b() { return nullptr; }\n" 3358 "\n" 3359 "private:\n" 3360 " int c;\n" 3361 "};"); 3362 } 3363 3364 TEST_F(FormatTest, SeparatesLogicalBlocks) { 3365 EXPECT_EQ("class A {\n" 3366 "public:\n" 3367 " void f();\n" 3368 "\n" 3369 "private:\n" 3370 " void g() {}\n" 3371 " // test\n" 3372 "protected:\n" 3373 " int h;\n" 3374 "};", 3375 format("class A {\n" 3376 "public:\n" 3377 "void f();\n" 3378 "private:\n" 3379 "void g() {}\n" 3380 "// test\n" 3381 "protected:\n" 3382 "int h;\n" 3383 "};")); 3384 EXPECT_EQ("class A {\n" 3385 "protected:\n" 3386 "public:\n" 3387 " void f();\n" 3388 "};", 3389 format("class A {\n" 3390 "protected:\n" 3391 "\n" 3392 "public:\n" 3393 "\n" 3394 " void f();\n" 3395 "};")); 3396 3397 // Even ensure proper spacing inside macros. 3398 EXPECT_EQ("#define B \\\n" 3399 " class A { \\\n" 3400 " protected: \\\n" 3401 " public: \\\n" 3402 " void f(); \\\n" 3403 " };", 3404 format("#define B \\\n" 3405 " class A { \\\n" 3406 " protected: \\\n" 3407 " \\\n" 3408 " public: \\\n" 3409 " \\\n" 3410 " void f(); \\\n" 3411 " };", 3412 getGoogleStyle())); 3413 // But don't remove empty lines after macros ending in access specifiers. 3414 EXPECT_EQ("#define A private:\n" 3415 "\n" 3416 "int i;", 3417 format("#define A private:\n" 3418 "\n" 3419 "int i;")); 3420 } 3421 3422 TEST_F(FormatTest, FormatsClasses) { 3423 verifyFormat("class A : public B {};"); 3424 verifyFormat("class A : public ::B {};"); 3425 3426 verifyFormat( 3427 "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3428 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};"); 3429 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n" 3430 " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3431 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};"); 3432 verifyFormat( 3433 "class A : public B, public C, public D, public E, public F {};"); 3434 verifyFormat("class AAAAAAAAAAAA : public B,\n" 3435 " public C,\n" 3436 " public D,\n" 3437 " public E,\n" 3438 " public F,\n" 3439 " public G {};"); 3440 3441 verifyFormat("class\n" 3442 " ReallyReallyLongClassName {\n" 3443 " int i;\n" 3444 "};", 3445 getLLVMStyleWithColumns(32)); 3446 verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n" 3447 " aaaaaaaaaaaaaaaa> {};"); 3448 verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n" 3449 " : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n" 3450 " aaaaaaaaaaaaaaaaaaaaaa> {};"); 3451 verifyFormat("template <class R, class C>\n" 3452 "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n" 3453 " : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};"); 3454 verifyFormat("class ::A::B {};"); 3455 } 3456 3457 TEST_F(FormatTest, BreakInheritanceStyle) { 3458 FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle(); 3459 StyleWithInheritanceBreakBeforeComma.BreakInheritanceList = 3460 FormatStyle::BILS_BeforeComma; 3461 verifyFormat("class MyClass : public X {};", 3462 StyleWithInheritanceBreakBeforeComma); 3463 verifyFormat("class MyClass\n" 3464 " : public X\n" 3465 " , public Y {};", 3466 StyleWithInheritanceBreakBeforeComma); 3467 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n" 3468 " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n" 3469 " , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};", 3470 StyleWithInheritanceBreakBeforeComma); 3471 verifyFormat("struct aaaaaaaaaaaaa\n" 3472 " : public aaaaaaaaaaaaaaaaaaa< // break\n" 3473 " aaaaaaaaaaaaaaaa> {};", 3474 StyleWithInheritanceBreakBeforeComma); 3475 3476 FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle(); 3477 StyleWithInheritanceBreakAfterColon.BreakInheritanceList = 3478 FormatStyle::BILS_AfterColon; 3479 verifyFormat("class MyClass : public X {};", 3480 StyleWithInheritanceBreakAfterColon); 3481 verifyFormat("class MyClass : public X, public Y {};", 3482 StyleWithInheritanceBreakAfterColon); 3483 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n" 3484 " public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3485 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};", 3486 StyleWithInheritanceBreakAfterColon); 3487 verifyFormat("struct aaaaaaaaaaaaa :\n" 3488 " public aaaaaaaaaaaaaaaaaaa< // break\n" 3489 " aaaaaaaaaaaaaaaa> {};", 3490 StyleWithInheritanceBreakAfterColon); 3491 3492 FormatStyle StyleWithInheritanceBreakAfterComma = getLLVMStyle(); 3493 StyleWithInheritanceBreakAfterComma.BreakInheritanceList = 3494 FormatStyle::BILS_AfterComma; 3495 verifyFormat("class MyClass : public X {};", 3496 StyleWithInheritanceBreakAfterComma); 3497 verifyFormat("class MyClass : public X,\n" 3498 " public Y {};", 3499 StyleWithInheritanceBreakAfterComma); 3500 verifyFormat( 3501 "class AAAAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3502 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC " 3503 "{};", 3504 StyleWithInheritanceBreakAfterComma); 3505 verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n" 3506 " aaaaaaaaaaaaaaaa> {};", 3507 StyleWithInheritanceBreakAfterComma); 3508 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n" 3509 " : public OnceBreak,\n" 3510 " public AlwaysBreak,\n" 3511 " EvenBasesFitInOneLine {};", 3512 StyleWithInheritanceBreakAfterComma); 3513 } 3514 3515 TEST_F(FormatTest, FormatsVariableDeclarationsAfterRecord) { 3516 verifyFormat("class A {\n} a, b;"); 3517 verifyFormat("struct A {\n} a, b;"); 3518 verifyFormat("union A {\n} a, b;"); 3519 3520 verifyFormat("constexpr class A {\n} a, b;"); 3521 verifyFormat("constexpr struct A {\n} a, b;"); 3522 verifyFormat("constexpr union A {\n} a, b;"); 3523 3524 verifyFormat("namespace {\nclass A {\n} a, b;\n} // namespace"); 3525 verifyFormat("namespace {\nstruct A {\n} a, b;\n} // namespace"); 3526 verifyFormat("namespace {\nunion A {\n} a, b;\n} // namespace"); 3527 3528 verifyFormat("namespace {\nconstexpr class A {\n} a, b;\n} // namespace"); 3529 verifyFormat("namespace {\nconstexpr struct A {\n} a, b;\n} // namespace"); 3530 verifyFormat("namespace {\nconstexpr union A {\n} a, b;\n} // namespace"); 3531 3532 verifyFormat("namespace ns {\n" 3533 "class {\n" 3534 "} a, b;\n" 3535 "} // namespace ns"); 3536 verifyFormat("namespace ns {\n" 3537 "const class {\n" 3538 "} a, b;\n" 3539 "} // namespace ns"); 3540 verifyFormat("namespace ns {\n" 3541 "constexpr class C {\n" 3542 "} a, b;\n" 3543 "} // namespace ns"); 3544 verifyFormat("namespace ns {\n" 3545 "class { /* comment */\n" 3546 "} a, b;\n" 3547 "} // namespace ns"); 3548 verifyFormat("namespace ns {\n" 3549 "const class { /* comment */\n" 3550 "} a, b;\n" 3551 "} // namespace ns"); 3552 } 3553 3554 TEST_F(FormatTest, FormatsEnum) { 3555 verifyFormat("enum {\n" 3556 " Zero,\n" 3557 " One = 1,\n" 3558 " Two = One + 1,\n" 3559 " Three = (One + Two),\n" 3560 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3561 " Five = (One, Two, Three, Four, 5)\n" 3562 "};"); 3563 verifyGoogleFormat("enum {\n" 3564 " Zero,\n" 3565 " One = 1,\n" 3566 " Two = One + 1,\n" 3567 " Three = (One + Two),\n" 3568 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3569 " Five = (One, Two, Three, Four, 5)\n" 3570 "};"); 3571 verifyFormat("enum Enum {};"); 3572 verifyFormat("enum {};"); 3573 verifyFormat("enum X E {} d;"); 3574 verifyFormat("enum __attribute__((...)) E {} d;"); 3575 verifyFormat("enum __declspec__((...)) E {} d;"); 3576 verifyFormat("enum [[nodiscard]] E {} d;"); 3577 verifyFormat("enum {\n" 3578 " Bar = Foo<int, int>::value\n" 3579 "};", 3580 getLLVMStyleWithColumns(30)); 3581 3582 verifyFormat("enum ShortEnum { A, B, C };"); 3583 verifyGoogleFormat("enum ShortEnum { A, B, C };"); 3584 3585 EXPECT_EQ("enum KeepEmptyLines {\n" 3586 " ONE,\n" 3587 "\n" 3588 " TWO,\n" 3589 "\n" 3590 " THREE\n" 3591 "}", 3592 format("enum KeepEmptyLines {\n" 3593 " ONE,\n" 3594 "\n" 3595 " TWO,\n" 3596 "\n" 3597 "\n" 3598 " THREE\n" 3599 "}")); 3600 verifyFormat("enum E { // comment\n" 3601 " ONE,\n" 3602 " TWO\n" 3603 "};\n" 3604 "int i;"); 3605 3606 FormatStyle EightIndent = getLLVMStyle(); 3607 EightIndent.IndentWidth = 8; 3608 verifyFormat("enum {\n" 3609 " VOID,\n" 3610 " CHAR,\n" 3611 " SHORT,\n" 3612 " INT,\n" 3613 " LONG,\n" 3614 " SIGNED,\n" 3615 " UNSIGNED,\n" 3616 " BOOL,\n" 3617 " FLOAT,\n" 3618 " DOUBLE,\n" 3619 " COMPLEX\n" 3620 "};", 3621 EightIndent); 3622 3623 verifyFormat("enum [[nodiscard]] E {\n" 3624 " ONE,\n" 3625 " TWO,\n" 3626 "};"); 3627 verifyFormat("enum [[nodiscard]] E {\n" 3628 " // Comment 1\n" 3629 " ONE,\n" 3630 " // Comment 2\n" 3631 " TWO,\n" 3632 "};"); 3633 3634 // Not enums. 3635 verifyFormat("enum X f() {\n" 3636 " a();\n" 3637 " return 42;\n" 3638 "}"); 3639 verifyFormat("enum X Type::f() {\n" 3640 " a();\n" 3641 " return 42;\n" 3642 "}"); 3643 verifyFormat("enum ::X f() {\n" 3644 " a();\n" 3645 " return 42;\n" 3646 "}"); 3647 verifyFormat("enum ns::X f() {\n" 3648 " a();\n" 3649 " return 42;\n" 3650 "}"); 3651 } 3652 3653 TEST_F(FormatTest, FormatsEnumsWithErrors) { 3654 verifyFormat("enum Type {\n" 3655 " One = 0; // These semicolons should be commas.\n" 3656 " Two = 1;\n" 3657 "};"); 3658 verifyFormat("namespace n {\n" 3659 "enum Type {\n" 3660 " One,\n" 3661 " Two, // missing };\n" 3662 " int i;\n" 3663 "}\n" 3664 "void g() {}"); 3665 } 3666 3667 TEST_F(FormatTest, FormatsEnumStruct) { 3668 verifyFormat("enum struct {\n" 3669 " Zero,\n" 3670 " One = 1,\n" 3671 " Two = One + 1,\n" 3672 " Three = (One + Two),\n" 3673 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3674 " Five = (One, Two, Three, Four, 5)\n" 3675 "};"); 3676 verifyFormat("enum struct Enum {};"); 3677 verifyFormat("enum struct {};"); 3678 verifyFormat("enum struct X E {} d;"); 3679 verifyFormat("enum struct __attribute__((...)) E {} d;"); 3680 verifyFormat("enum struct __declspec__((...)) E {} d;"); 3681 verifyFormat("enum struct [[nodiscard]] E {} d;"); 3682 verifyFormat("enum struct X f() {\n a();\n return 42;\n}"); 3683 3684 verifyFormat("enum struct [[nodiscard]] E {\n" 3685 " ONE,\n" 3686 " TWO,\n" 3687 "};"); 3688 verifyFormat("enum struct [[nodiscard]] E {\n" 3689 " // Comment 1\n" 3690 " ONE,\n" 3691 " // Comment 2\n" 3692 " TWO,\n" 3693 "};"); 3694 } 3695 3696 TEST_F(FormatTest, FormatsEnumClass) { 3697 verifyFormat("enum class {\n" 3698 " Zero,\n" 3699 " One = 1,\n" 3700 " Two = One + 1,\n" 3701 " Three = (One + Two),\n" 3702 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3703 " Five = (One, Two, Three, Four, 5)\n" 3704 "};"); 3705 verifyFormat("enum class Enum {};"); 3706 verifyFormat("enum class {};"); 3707 verifyFormat("enum class X E {} d;"); 3708 verifyFormat("enum class __attribute__((...)) E {} d;"); 3709 verifyFormat("enum class __declspec__((...)) E {} d;"); 3710 verifyFormat("enum class [[nodiscard]] E {} d;"); 3711 verifyFormat("enum class X f() {\n a();\n return 42;\n}"); 3712 3713 verifyFormat("enum class [[nodiscard]] E {\n" 3714 " ONE,\n" 3715 " TWO,\n" 3716 "};"); 3717 verifyFormat("enum class [[nodiscard]] E {\n" 3718 " // Comment 1\n" 3719 " ONE,\n" 3720 " // Comment 2\n" 3721 " TWO,\n" 3722 "};"); 3723 } 3724 3725 TEST_F(FormatTest, FormatsEnumTypes) { 3726 verifyFormat("enum X : int {\n" 3727 " A, // Force multiple lines.\n" 3728 " B\n" 3729 "};"); 3730 verifyFormat("enum X : int { A, B };"); 3731 verifyFormat("enum X : std::uint32_t { A, B };"); 3732 } 3733 3734 TEST_F(FormatTest, FormatsTypedefEnum) { 3735 FormatStyle Style = getLLVMStyleWithColumns(40); 3736 verifyFormat("typedef enum {} EmptyEnum;"); 3737 verifyFormat("typedef enum { A, B, C } ShortEnum;"); 3738 verifyFormat("typedef enum {\n" 3739 " ZERO = 0,\n" 3740 " ONE = 1,\n" 3741 " TWO = 2,\n" 3742 " THREE = 3\n" 3743 "} LongEnum;", 3744 Style); 3745 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 3746 Style.BraceWrapping.AfterEnum = true; 3747 verifyFormat("typedef enum {} EmptyEnum;"); 3748 verifyFormat("typedef enum { A, B, C } ShortEnum;"); 3749 verifyFormat("typedef enum\n" 3750 "{\n" 3751 " ZERO = 0,\n" 3752 " ONE = 1,\n" 3753 " TWO = 2,\n" 3754 " THREE = 3\n" 3755 "} LongEnum;", 3756 Style); 3757 } 3758 3759 TEST_F(FormatTest, FormatsNSEnums) { 3760 verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }"); 3761 verifyGoogleFormat( 3762 "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }"); 3763 verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n" 3764 " // Information about someDecentlyLongValue.\n" 3765 " someDecentlyLongValue,\n" 3766 " // Information about anotherDecentlyLongValue.\n" 3767 " anotherDecentlyLongValue,\n" 3768 " // Information about aThirdDecentlyLongValue.\n" 3769 " aThirdDecentlyLongValue\n" 3770 "};"); 3771 verifyGoogleFormat("typedef NS_CLOSED_ENUM(NSInteger, MyType) {\n" 3772 " // Information about someDecentlyLongValue.\n" 3773 " someDecentlyLongValue,\n" 3774 " // Information about anotherDecentlyLongValue.\n" 3775 " anotherDecentlyLongValue,\n" 3776 " // Information about aThirdDecentlyLongValue.\n" 3777 " aThirdDecentlyLongValue\n" 3778 "};"); 3779 verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n" 3780 " a = 1,\n" 3781 " b = 2,\n" 3782 " c = 3,\n" 3783 "};"); 3784 verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n" 3785 " a = 1,\n" 3786 " b = 2,\n" 3787 " c = 3,\n" 3788 "};"); 3789 verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n" 3790 " a = 1,\n" 3791 " b = 2,\n" 3792 " c = 3,\n" 3793 "};"); 3794 verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n" 3795 " a = 1,\n" 3796 " b = 2,\n" 3797 " c = 3,\n" 3798 "};"); 3799 } 3800 3801 TEST_F(FormatTest, FormatsBitfields) { 3802 verifyFormat("struct Bitfields {\n" 3803 " unsigned sClass : 8;\n" 3804 " unsigned ValueKind : 2;\n" 3805 "};"); 3806 verifyFormat("struct A {\n" 3807 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n" 3808 " bbbbbbbbbbbbbbbbbbbbbbbbb;\n" 3809 "};"); 3810 verifyFormat("struct MyStruct {\n" 3811 " uchar data;\n" 3812 " uchar : 8;\n" 3813 " uchar : 8;\n" 3814 " uchar other;\n" 3815 "};"); 3816 FormatStyle Style = getLLVMStyle(); 3817 Style.BitFieldColonSpacing = FormatStyle::BFCS_None; 3818 verifyFormat("struct Bitfields {\n" 3819 " unsigned sClass:8;\n" 3820 " unsigned ValueKind:2;\n" 3821 " uchar other;\n" 3822 "};", 3823 Style); 3824 verifyFormat("struct A {\n" 3825 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:1,\n" 3826 " bbbbbbbbbbbbbbbbbbbbbbbbb:2;\n" 3827 "};", 3828 Style); 3829 Style.BitFieldColonSpacing = FormatStyle::BFCS_Before; 3830 verifyFormat("struct Bitfields {\n" 3831 " unsigned sClass :8;\n" 3832 " unsigned ValueKind :2;\n" 3833 " uchar other;\n" 3834 "};", 3835 Style); 3836 Style.BitFieldColonSpacing = FormatStyle::BFCS_After; 3837 verifyFormat("struct Bitfields {\n" 3838 " unsigned sClass: 8;\n" 3839 " unsigned ValueKind: 2;\n" 3840 " uchar other;\n" 3841 "};", 3842 Style); 3843 } 3844 3845 TEST_F(FormatTest, FormatsNamespaces) { 3846 FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle(); 3847 LLVMWithNoNamespaceFix.FixNamespaceComments = false; 3848 3849 verifyFormat("namespace some_namespace {\n" 3850 "class A {};\n" 3851 "void f() { f(); }\n" 3852 "}", 3853 LLVMWithNoNamespaceFix); 3854 verifyFormat("#define M(x) x##x\n" 3855 "namespace M(x) {\n" 3856 "class A {};\n" 3857 "void f() { f(); }\n" 3858 "}", 3859 LLVMWithNoNamespaceFix); 3860 verifyFormat("#define M(x) x##x\n" 3861 "namespace N::inline M(x) {\n" 3862 "class A {};\n" 3863 "void f() { f(); }\n" 3864 "}", 3865 LLVMWithNoNamespaceFix); 3866 verifyFormat("#define M(x) x##x\n" 3867 "namespace M(x)::inline N {\n" 3868 "class A {};\n" 3869 "void f() { f(); }\n" 3870 "}", 3871 LLVMWithNoNamespaceFix); 3872 verifyFormat("#define M(x) x##x\n" 3873 "namespace N::M(x) {\n" 3874 "class A {};\n" 3875 "void f() { f(); }\n" 3876 "}", 3877 LLVMWithNoNamespaceFix); 3878 verifyFormat("#define M(x) x##x\n" 3879 "namespace M::N(x) {\n" 3880 "class A {};\n" 3881 "void f() { f(); }\n" 3882 "}", 3883 LLVMWithNoNamespaceFix); 3884 verifyFormat("namespace N::inline D {\n" 3885 "class A {};\n" 3886 "void f() { f(); }\n" 3887 "}", 3888 LLVMWithNoNamespaceFix); 3889 verifyFormat("namespace N::inline D::E {\n" 3890 "class A {};\n" 3891 "void f() { f(); }\n" 3892 "}", 3893 LLVMWithNoNamespaceFix); 3894 verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n" 3895 "class A {};\n" 3896 "void f() { f(); }\n" 3897 "}", 3898 LLVMWithNoNamespaceFix); 3899 verifyFormat("/* something */ namespace some_namespace {\n" 3900 "class A {};\n" 3901 "void f() { f(); }\n" 3902 "}", 3903 LLVMWithNoNamespaceFix); 3904 verifyFormat("namespace {\n" 3905 "class A {};\n" 3906 "void f() { f(); }\n" 3907 "}", 3908 LLVMWithNoNamespaceFix); 3909 verifyFormat("/* something */ namespace {\n" 3910 "class A {};\n" 3911 "void f() { f(); }\n" 3912 "}", 3913 LLVMWithNoNamespaceFix); 3914 verifyFormat("inline namespace X {\n" 3915 "class A {};\n" 3916 "void f() { f(); }\n" 3917 "}", 3918 LLVMWithNoNamespaceFix); 3919 verifyFormat("/* something */ inline namespace X {\n" 3920 "class A {};\n" 3921 "void f() { f(); }\n" 3922 "}", 3923 LLVMWithNoNamespaceFix); 3924 verifyFormat("export namespace X {\n" 3925 "class A {};\n" 3926 "void f() { f(); }\n" 3927 "}", 3928 LLVMWithNoNamespaceFix); 3929 verifyFormat("using namespace some_namespace;\n" 3930 "class A {};\n" 3931 "void f() { f(); }", 3932 LLVMWithNoNamespaceFix); 3933 3934 // This code is more common than we thought; if we 3935 // layout this correctly the semicolon will go into 3936 // its own line, which is undesirable. 3937 verifyFormat("namespace {};", LLVMWithNoNamespaceFix); 3938 verifyFormat("namespace {\n" 3939 "class A {};\n" 3940 "};", 3941 LLVMWithNoNamespaceFix); 3942 3943 verifyFormat("namespace {\n" 3944 "int SomeVariable = 0; // comment\n" 3945 "} // namespace", 3946 LLVMWithNoNamespaceFix); 3947 EXPECT_EQ("#ifndef HEADER_GUARD\n" 3948 "#define HEADER_GUARD\n" 3949 "namespace my_namespace {\n" 3950 "int i;\n" 3951 "} // my_namespace\n" 3952 "#endif // HEADER_GUARD", 3953 format("#ifndef HEADER_GUARD\n" 3954 " #define HEADER_GUARD\n" 3955 " namespace my_namespace {\n" 3956 "int i;\n" 3957 "} // my_namespace\n" 3958 "#endif // HEADER_GUARD", 3959 LLVMWithNoNamespaceFix)); 3960 3961 EXPECT_EQ("namespace A::B {\n" 3962 "class C {};\n" 3963 "}", 3964 format("namespace A::B {\n" 3965 "class C {};\n" 3966 "}", 3967 LLVMWithNoNamespaceFix)); 3968 3969 FormatStyle Style = getLLVMStyle(); 3970 Style.NamespaceIndentation = FormatStyle::NI_All; 3971 EXPECT_EQ("namespace out {\n" 3972 " int i;\n" 3973 " namespace in {\n" 3974 " int i;\n" 3975 " } // namespace in\n" 3976 "} // namespace out", 3977 format("namespace out {\n" 3978 "int i;\n" 3979 "namespace in {\n" 3980 "int i;\n" 3981 "} // namespace in\n" 3982 "} // namespace out", 3983 Style)); 3984 3985 FormatStyle ShortInlineFunctions = getLLVMStyle(); 3986 ShortInlineFunctions.NamespaceIndentation = FormatStyle::NI_All; 3987 ShortInlineFunctions.AllowShortFunctionsOnASingleLine = 3988 FormatStyle::SFS_Inline; 3989 verifyFormat("namespace {\n" 3990 " void f() {\n" 3991 " return;\n" 3992 " }\n" 3993 "} // namespace\n", 3994 ShortInlineFunctions); 3995 verifyFormat("namespace { /* comment */\n" 3996 " void f() {\n" 3997 " return;\n" 3998 " }\n" 3999 "} // namespace\n", 4000 ShortInlineFunctions); 4001 verifyFormat("namespace { // comment\n" 4002 " void f() {\n" 4003 " return;\n" 4004 " }\n" 4005 "} // namespace\n", 4006 ShortInlineFunctions); 4007 verifyFormat("namespace {\n" 4008 " int some_int;\n" 4009 " void f() {\n" 4010 " return;\n" 4011 " }\n" 4012 "} // namespace\n", 4013 ShortInlineFunctions); 4014 verifyFormat("namespace interface {\n" 4015 " void f() {\n" 4016 " return;\n" 4017 " }\n" 4018 "} // namespace interface\n", 4019 ShortInlineFunctions); 4020 verifyFormat("namespace {\n" 4021 " class X {\n" 4022 " void f() { return; }\n" 4023 " };\n" 4024 "} // namespace\n", 4025 ShortInlineFunctions); 4026 verifyFormat("namespace {\n" 4027 " class X { /* comment */\n" 4028 " void f() { return; }\n" 4029 " };\n" 4030 "} // namespace\n", 4031 ShortInlineFunctions); 4032 verifyFormat("namespace {\n" 4033 " class X { // comment\n" 4034 " void f() { return; }\n" 4035 " };\n" 4036 "} // namespace\n", 4037 ShortInlineFunctions); 4038 verifyFormat("namespace {\n" 4039 " struct X {\n" 4040 " void f() { return; }\n" 4041 " };\n" 4042 "} // namespace\n", 4043 ShortInlineFunctions); 4044 verifyFormat("namespace {\n" 4045 " union X {\n" 4046 " void f() { return; }\n" 4047 " };\n" 4048 "} // namespace\n", 4049 ShortInlineFunctions); 4050 verifyFormat("extern \"C\" {\n" 4051 "void f() {\n" 4052 " return;\n" 4053 "}\n" 4054 "} // namespace\n", 4055 ShortInlineFunctions); 4056 verifyFormat("namespace {\n" 4057 " class X {\n" 4058 " void f() { return; }\n" 4059 " } x;\n" 4060 "} // namespace\n", 4061 ShortInlineFunctions); 4062 verifyFormat("namespace {\n" 4063 " [[nodiscard]] class X {\n" 4064 " void f() { return; }\n" 4065 " };\n" 4066 "} // namespace\n", 4067 ShortInlineFunctions); 4068 verifyFormat("namespace {\n" 4069 " static class X {\n" 4070 " void f() { return; }\n" 4071 " } x;\n" 4072 "} // namespace\n", 4073 ShortInlineFunctions); 4074 verifyFormat("namespace {\n" 4075 " constexpr class X {\n" 4076 " void f() { return; }\n" 4077 " } x;\n" 4078 "} // namespace\n", 4079 ShortInlineFunctions); 4080 4081 ShortInlineFunctions.IndentExternBlock = FormatStyle::IEBS_Indent; 4082 verifyFormat("extern \"C\" {\n" 4083 " void f() {\n" 4084 " return;\n" 4085 " }\n" 4086 "} // namespace\n", 4087 ShortInlineFunctions); 4088 4089 Style.NamespaceIndentation = FormatStyle::NI_Inner; 4090 EXPECT_EQ("namespace out {\n" 4091 "int i;\n" 4092 "namespace in {\n" 4093 " int i;\n" 4094 "} // namespace in\n" 4095 "} // namespace out", 4096 format("namespace out {\n" 4097 "int i;\n" 4098 "namespace in {\n" 4099 "int i;\n" 4100 "} // namespace in\n" 4101 "} // namespace out", 4102 Style)); 4103 4104 Style.NamespaceIndentation = FormatStyle::NI_None; 4105 verifyFormat("template <class T>\n" 4106 "concept a_concept = X<>;\n" 4107 "namespace B {\n" 4108 "struct b_struct {};\n" 4109 "} // namespace B\n", 4110 Style); 4111 verifyFormat("template <int I>\n" 4112 "constexpr void foo()\n" 4113 " requires(I == 42)\n" 4114 "{}\n" 4115 "namespace ns {\n" 4116 "void foo() {}\n" 4117 "} // namespace ns\n", 4118 Style); 4119 } 4120 4121 TEST_F(FormatTest, NamespaceMacros) { 4122 FormatStyle Style = getLLVMStyle(); 4123 Style.NamespaceMacros.push_back("TESTSUITE"); 4124 4125 verifyFormat("TESTSUITE(A) {\n" 4126 "int foo();\n" 4127 "} // TESTSUITE(A)", 4128 Style); 4129 4130 verifyFormat("TESTSUITE(A, B) {\n" 4131 "int foo();\n" 4132 "} // TESTSUITE(A)", 4133 Style); 4134 4135 // Properly indent according to NamespaceIndentation style 4136 Style.NamespaceIndentation = FormatStyle::NI_All; 4137 verifyFormat("TESTSUITE(A) {\n" 4138 " int foo();\n" 4139 "} // TESTSUITE(A)", 4140 Style); 4141 verifyFormat("TESTSUITE(A) {\n" 4142 " namespace B {\n" 4143 " int foo();\n" 4144 " } // namespace B\n" 4145 "} // TESTSUITE(A)", 4146 Style); 4147 verifyFormat("namespace A {\n" 4148 " TESTSUITE(B) {\n" 4149 " int foo();\n" 4150 " } // TESTSUITE(B)\n" 4151 "} // namespace A", 4152 Style); 4153 4154 Style.NamespaceIndentation = FormatStyle::NI_Inner; 4155 verifyFormat("TESTSUITE(A) {\n" 4156 "TESTSUITE(B) {\n" 4157 " int foo();\n" 4158 "} // TESTSUITE(B)\n" 4159 "} // TESTSUITE(A)", 4160 Style); 4161 verifyFormat("TESTSUITE(A) {\n" 4162 "namespace B {\n" 4163 " int foo();\n" 4164 "} // namespace B\n" 4165 "} // TESTSUITE(A)", 4166 Style); 4167 verifyFormat("namespace A {\n" 4168 "TESTSUITE(B) {\n" 4169 " int foo();\n" 4170 "} // TESTSUITE(B)\n" 4171 "} // namespace A", 4172 Style); 4173 4174 // Properly merge namespace-macros blocks in CompactNamespaces mode 4175 Style.NamespaceIndentation = FormatStyle::NI_None; 4176 Style.CompactNamespaces = true; 4177 verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n" 4178 "}} // TESTSUITE(A::B)", 4179 Style); 4180 4181 EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n" 4182 "}} // TESTSUITE(out::in)", 4183 format("TESTSUITE(out) {\n" 4184 "TESTSUITE(in) {\n" 4185 "} // TESTSUITE(in)\n" 4186 "} // TESTSUITE(out)", 4187 Style)); 4188 4189 EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n" 4190 "}} // TESTSUITE(out::in)", 4191 format("TESTSUITE(out) {\n" 4192 "TESTSUITE(in) {\n" 4193 "} // TESTSUITE(in)\n" 4194 "} // TESTSUITE(out)", 4195 Style)); 4196 4197 // Do not merge different namespaces/macros 4198 EXPECT_EQ("namespace out {\n" 4199 "TESTSUITE(in) {\n" 4200 "} // TESTSUITE(in)\n" 4201 "} // namespace out", 4202 format("namespace out {\n" 4203 "TESTSUITE(in) {\n" 4204 "} // TESTSUITE(in)\n" 4205 "} // namespace out", 4206 Style)); 4207 EXPECT_EQ("TESTSUITE(out) {\n" 4208 "namespace in {\n" 4209 "} // namespace in\n" 4210 "} // TESTSUITE(out)", 4211 format("TESTSUITE(out) {\n" 4212 "namespace in {\n" 4213 "} // namespace in\n" 4214 "} // TESTSUITE(out)", 4215 Style)); 4216 Style.NamespaceMacros.push_back("FOOBAR"); 4217 EXPECT_EQ("TESTSUITE(out) {\n" 4218 "FOOBAR(in) {\n" 4219 "} // FOOBAR(in)\n" 4220 "} // TESTSUITE(out)", 4221 format("TESTSUITE(out) {\n" 4222 "FOOBAR(in) {\n" 4223 "} // FOOBAR(in)\n" 4224 "} // TESTSUITE(out)", 4225 Style)); 4226 } 4227 4228 TEST_F(FormatTest, FormatsCompactNamespaces) { 4229 FormatStyle Style = getLLVMStyle(); 4230 Style.CompactNamespaces = true; 4231 Style.NamespaceMacros.push_back("TESTSUITE"); 4232 4233 verifyFormat("namespace A { namespace B {\n" 4234 "}} // namespace A::B", 4235 Style); 4236 4237 EXPECT_EQ("namespace out { namespace in {\n" 4238 "}} // namespace out::in", 4239 format("namespace out {\n" 4240 "namespace in {\n" 4241 "} // namespace in\n" 4242 "} // namespace out", 4243 Style)); 4244 4245 // Only namespaces which have both consecutive opening and end get compacted 4246 EXPECT_EQ("namespace out {\n" 4247 "namespace in1 {\n" 4248 "} // namespace in1\n" 4249 "namespace in2 {\n" 4250 "} // namespace in2\n" 4251 "} // namespace out", 4252 format("namespace out {\n" 4253 "namespace in1 {\n" 4254 "} // namespace in1\n" 4255 "namespace in2 {\n" 4256 "} // namespace in2\n" 4257 "} // namespace out", 4258 Style)); 4259 4260 EXPECT_EQ("namespace out {\n" 4261 "int i;\n" 4262 "namespace in {\n" 4263 "int j;\n" 4264 "} // namespace in\n" 4265 "int k;\n" 4266 "} // namespace out", 4267 format("namespace out { int i;\n" 4268 "namespace in { int j; } // namespace in\n" 4269 "int k; } // namespace out", 4270 Style)); 4271 4272 EXPECT_EQ("namespace A { namespace B { namespace C {\n" 4273 "}}} // namespace A::B::C\n", 4274 format("namespace A { namespace B {\n" 4275 "namespace C {\n" 4276 "}} // namespace B::C\n" 4277 "} // namespace A\n", 4278 Style)); 4279 4280 Style.ColumnLimit = 40; 4281 EXPECT_EQ("namespace aaaaaaaaaa {\n" 4282 "namespace bbbbbbbbbb {\n" 4283 "}} // namespace aaaaaaaaaa::bbbbbbbbbb", 4284 format("namespace aaaaaaaaaa {\n" 4285 "namespace bbbbbbbbbb {\n" 4286 "} // namespace bbbbbbbbbb\n" 4287 "} // namespace aaaaaaaaaa", 4288 Style)); 4289 4290 EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n" 4291 "namespace cccccc {\n" 4292 "}}} // namespace aaaaaa::bbbbbb::cccccc", 4293 format("namespace aaaaaa {\n" 4294 "namespace bbbbbb {\n" 4295 "namespace cccccc {\n" 4296 "} // namespace cccccc\n" 4297 "} // namespace bbbbbb\n" 4298 "} // namespace aaaaaa", 4299 Style)); 4300 Style.ColumnLimit = 80; 4301 4302 // Extra semicolon after 'inner' closing brace prevents merging 4303 EXPECT_EQ("namespace out { namespace in {\n" 4304 "}; } // namespace out::in", 4305 format("namespace out {\n" 4306 "namespace in {\n" 4307 "}; // namespace in\n" 4308 "} // namespace out", 4309 Style)); 4310 4311 // Extra semicolon after 'outer' closing brace is conserved 4312 EXPECT_EQ("namespace out { namespace in {\n" 4313 "}}; // namespace out::in", 4314 format("namespace out {\n" 4315 "namespace in {\n" 4316 "} // namespace in\n" 4317 "}; // namespace out", 4318 Style)); 4319 4320 Style.NamespaceIndentation = FormatStyle::NI_All; 4321 EXPECT_EQ("namespace out { namespace in {\n" 4322 " int i;\n" 4323 "}} // namespace out::in", 4324 format("namespace out {\n" 4325 "namespace in {\n" 4326 "int i;\n" 4327 "} // namespace in\n" 4328 "} // namespace out", 4329 Style)); 4330 EXPECT_EQ("namespace out { namespace mid {\n" 4331 " namespace in {\n" 4332 " int j;\n" 4333 " } // namespace in\n" 4334 " int k;\n" 4335 "}} // namespace out::mid", 4336 format("namespace out { namespace mid {\n" 4337 "namespace in { int j; } // namespace in\n" 4338 "int k; }} // namespace out::mid", 4339 Style)); 4340 4341 Style.NamespaceIndentation = FormatStyle::NI_Inner; 4342 EXPECT_EQ("namespace out { namespace in {\n" 4343 " int i;\n" 4344 "}} // namespace out::in", 4345 format("namespace out {\n" 4346 "namespace in {\n" 4347 "int i;\n" 4348 "} // namespace in\n" 4349 "} // namespace out", 4350 Style)); 4351 EXPECT_EQ("namespace out { namespace mid { namespace in {\n" 4352 " int i;\n" 4353 "}}} // namespace out::mid::in", 4354 format("namespace out {\n" 4355 "namespace mid {\n" 4356 "namespace in {\n" 4357 "int i;\n" 4358 "} // namespace in\n" 4359 "} // namespace mid\n" 4360 "} // namespace out", 4361 Style)); 4362 4363 Style.CompactNamespaces = true; 4364 Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 4365 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4366 Style.BraceWrapping.BeforeLambdaBody = true; 4367 verifyFormat("namespace out { namespace in {\n" 4368 "}} // namespace out::in", 4369 Style); 4370 EXPECT_EQ("namespace out { namespace in {\n" 4371 "}} // namespace out::in", 4372 format("namespace out {\n" 4373 "namespace in {\n" 4374 "} // namespace in\n" 4375 "} // namespace out", 4376 Style)); 4377 } 4378 4379 TEST_F(FormatTest, FormatsExternC) { 4380 verifyFormat("extern \"C\" {\nint a;"); 4381 verifyFormat("extern \"C\" {}"); 4382 verifyFormat("extern \"C\" {\n" 4383 "int foo();\n" 4384 "}"); 4385 verifyFormat("extern \"C\" int foo() {}"); 4386 verifyFormat("extern \"C\" int foo();"); 4387 verifyFormat("extern \"C\" int foo() {\n" 4388 " int i = 42;\n" 4389 " return i;\n" 4390 "}"); 4391 4392 FormatStyle Style = getLLVMStyle(); 4393 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4394 Style.BraceWrapping.AfterFunction = true; 4395 verifyFormat("extern \"C\" int foo() {}", Style); 4396 verifyFormat("extern \"C\" int foo();", Style); 4397 verifyFormat("extern \"C\" int foo()\n" 4398 "{\n" 4399 " int i = 42;\n" 4400 " return i;\n" 4401 "}", 4402 Style); 4403 4404 Style.BraceWrapping.AfterExternBlock = true; 4405 Style.BraceWrapping.SplitEmptyRecord = false; 4406 verifyFormat("extern \"C\"\n" 4407 "{}", 4408 Style); 4409 verifyFormat("extern \"C\"\n" 4410 "{\n" 4411 " int foo();\n" 4412 "}", 4413 Style); 4414 } 4415 4416 TEST_F(FormatTest, IndentExternBlockStyle) { 4417 FormatStyle Style = getLLVMStyle(); 4418 Style.IndentWidth = 2; 4419 4420 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4421 verifyFormat("extern \"C\" { /*9*/\n" 4422 "}", 4423 Style); 4424 verifyFormat("extern \"C\" {\n" 4425 " int foo10();\n" 4426 "}", 4427 Style); 4428 4429 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 4430 verifyFormat("extern \"C\" { /*11*/\n" 4431 "}", 4432 Style); 4433 verifyFormat("extern \"C\" {\n" 4434 "int foo12();\n" 4435 "}", 4436 Style); 4437 4438 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4439 Style.BraceWrapping.AfterExternBlock = true; 4440 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4441 verifyFormat("extern \"C\"\n" 4442 "{ /*13*/\n" 4443 "}", 4444 Style); 4445 verifyFormat("extern \"C\"\n{\n" 4446 " int foo14();\n" 4447 "}", 4448 Style); 4449 4450 Style.BraceWrapping.AfterExternBlock = false; 4451 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 4452 verifyFormat("extern \"C\" { /*15*/\n" 4453 "}", 4454 Style); 4455 verifyFormat("extern \"C\" {\n" 4456 "int foo16();\n" 4457 "}", 4458 Style); 4459 4460 Style.BraceWrapping.AfterExternBlock = true; 4461 verifyFormat("extern \"C\"\n" 4462 "{ /*13*/\n" 4463 "}", 4464 Style); 4465 verifyFormat("extern \"C\"\n" 4466 "{\n" 4467 "int foo14();\n" 4468 "}", 4469 Style); 4470 4471 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4472 verifyFormat("extern \"C\"\n" 4473 "{ /*13*/\n" 4474 "}", 4475 Style); 4476 verifyFormat("extern \"C\"\n" 4477 "{\n" 4478 " int foo14();\n" 4479 "}", 4480 Style); 4481 } 4482 4483 TEST_F(FormatTest, FormatsInlineASM) { 4484 verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));"); 4485 verifyFormat("asm(\"nop\" ::: \"memory\");"); 4486 verifyFormat( 4487 "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n" 4488 " \"cpuid\\n\\t\"\n" 4489 " \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n" 4490 " : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n" 4491 " : \"a\"(value));"); 4492 EXPECT_EQ( 4493 "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n" 4494 " __asm {\n" 4495 " mov edx,[that] // vtable in edx\n" 4496 " mov eax,methodIndex\n" 4497 " call [edx][eax*4] // stdcall\n" 4498 " }\n" 4499 "}", 4500 format("void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n" 4501 " __asm {\n" 4502 " mov edx,[that] // vtable in edx\n" 4503 " mov eax,methodIndex\n" 4504 " call [edx][eax*4] // stdcall\n" 4505 " }\n" 4506 "}")); 4507 EXPECT_EQ("_asm {\n" 4508 " xor eax, eax;\n" 4509 " cpuid;\n" 4510 "}", 4511 format("_asm {\n" 4512 " xor eax, eax;\n" 4513 " cpuid;\n" 4514 "}")); 4515 verifyFormat("void function() {\n" 4516 " // comment\n" 4517 " asm(\"\");\n" 4518 "}"); 4519 EXPECT_EQ("__asm {\n" 4520 "}\n" 4521 "int i;", 4522 format("__asm {\n" 4523 "}\n" 4524 "int i;")); 4525 } 4526 4527 TEST_F(FormatTest, FormatTryCatch) { 4528 verifyFormat("try {\n" 4529 " throw a * b;\n" 4530 "} catch (int a) {\n" 4531 " // Do nothing.\n" 4532 "} catch (...) {\n" 4533 " exit(42);\n" 4534 "}"); 4535 4536 // Function-level try statements. 4537 verifyFormat("int f() try { return 4; } catch (...) {\n" 4538 " return 5;\n" 4539 "}"); 4540 verifyFormat("class A {\n" 4541 " int a;\n" 4542 " A() try : a(0) {\n" 4543 " } catch (...) {\n" 4544 " throw;\n" 4545 " }\n" 4546 "};\n"); 4547 verifyFormat("class A {\n" 4548 " int a;\n" 4549 " A() try : a(0), b{1} {\n" 4550 " } catch (...) {\n" 4551 " throw;\n" 4552 " }\n" 4553 "};\n"); 4554 verifyFormat("class A {\n" 4555 " int a;\n" 4556 " A() try : a(0), b{1}, c{2} {\n" 4557 " } catch (...) {\n" 4558 " throw;\n" 4559 " }\n" 4560 "};\n"); 4561 verifyFormat("class A {\n" 4562 " int a;\n" 4563 " A() try : a(0), b{1}, c{2} {\n" 4564 " { // New scope.\n" 4565 " }\n" 4566 " } catch (...) {\n" 4567 " throw;\n" 4568 " }\n" 4569 "};\n"); 4570 4571 // Incomplete try-catch blocks. 4572 verifyIncompleteFormat("try {} catch ("); 4573 } 4574 4575 TEST_F(FormatTest, FormatTryAsAVariable) { 4576 verifyFormat("int try;"); 4577 verifyFormat("int try, size;"); 4578 verifyFormat("try = foo();"); 4579 verifyFormat("if (try < size) {\n return true;\n}"); 4580 4581 verifyFormat("int catch;"); 4582 verifyFormat("int catch, size;"); 4583 verifyFormat("catch = foo();"); 4584 verifyFormat("if (catch < size) {\n return true;\n}"); 4585 4586 FormatStyle Style = getLLVMStyle(); 4587 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4588 Style.BraceWrapping.AfterFunction = true; 4589 Style.BraceWrapping.BeforeCatch = true; 4590 verifyFormat("try {\n" 4591 " int bar = 1;\n" 4592 "}\n" 4593 "catch (...) {\n" 4594 " int bar = 1;\n" 4595 "}", 4596 Style); 4597 verifyFormat("#if NO_EX\n" 4598 "try\n" 4599 "#endif\n" 4600 "{\n" 4601 "}\n" 4602 "#if NO_EX\n" 4603 "catch (...) {\n" 4604 "}", 4605 Style); 4606 verifyFormat("try /* abc */ {\n" 4607 " int bar = 1;\n" 4608 "}\n" 4609 "catch (...) {\n" 4610 " int bar = 1;\n" 4611 "}", 4612 Style); 4613 verifyFormat("try\n" 4614 "// abc\n" 4615 "{\n" 4616 " int bar = 1;\n" 4617 "}\n" 4618 "catch (...) {\n" 4619 " int bar = 1;\n" 4620 "}", 4621 Style); 4622 } 4623 4624 TEST_F(FormatTest, FormatSEHTryCatch) { 4625 verifyFormat("__try {\n" 4626 " int a = b * c;\n" 4627 "} __except (EXCEPTION_EXECUTE_HANDLER) {\n" 4628 " // Do nothing.\n" 4629 "}"); 4630 4631 verifyFormat("__try {\n" 4632 " int a = b * c;\n" 4633 "} __finally {\n" 4634 " // Do nothing.\n" 4635 "}"); 4636 4637 verifyFormat("DEBUG({\n" 4638 " __try {\n" 4639 " } __finally {\n" 4640 " }\n" 4641 "});\n"); 4642 } 4643 4644 TEST_F(FormatTest, IncompleteTryCatchBlocks) { 4645 verifyFormat("try {\n" 4646 " f();\n" 4647 "} catch {\n" 4648 " g();\n" 4649 "}"); 4650 verifyFormat("try {\n" 4651 " f();\n" 4652 "} catch (A a) MACRO(x) {\n" 4653 " g();\n" 4654 "} catch (B b) MACRO(x) {\n" 4655 " g();\n" 4656 "}"); 4657 } 4658 4659 TEST_F(FormatTest, FormatTryCatchBraceStyles) { 4660 FormatStyle Style = getLLVMStyle(); 4661 for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla, 4662 FormatStyle::BS_WebKit}) { 4663 Style.BreakBeforeBraces = BraceStyle; 4664 verifyFormat("try {\n" 4665 " // something\n" 4666 "} catch (...) {\n" 4667 " // something\n" 4668 "}", 4669 Style); 4670 } 4671 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 4672 verifyFormat("try {\n" 4673 " // something\n" 4674 "}\n" 4675 "catch (...) {\n" 4676 " // something\n" 4677 "}", 4678 Style); 4679 verifyFormat("__try {\n" 4680 " // something\n" 4681 "}\n" 4682 "__finally {\n" 4683 " // something\n" 4684 "}", 4685 Style); 4686 verifyFormat("@try {\n" 4687 " // something\n" 4688 "}\n" 4689 "@finally {\n" 4690 " // something\n" 4691 "}", 4692 Style); 4693 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 4694 verifyFormat("try\n" 4695 "{\n" 4696 " // something\n" 4697 "}\n" 4698 "catch (...)\n" 4699 "{\n" 4700 " // something\n" 4701 "}", 4702 Style); 4703 Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 4704 verifyFormat("try\n" 4705 " {\n" 4706 " // something white\n" 4707 " }\n" 4708 "catch (...)\n" 4709 " {\n" 4710 " // something white\n" 4711 " }", 4712 Style); 4713 Style.BreakBeforeBraces = FormatStyle::BS_GNU; 4714 verifyFormat("try\n" 4715 " {\n" 4716 " // something\n" 4717 " }\n" 4718 "catch (...)\n" 4719 " {\n" 4720 " // something\n" 4721 " }", 4722 Style); 4723 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4724 Style.BraceWrapping.BeforeCatch = true; 4725 verifyFormat("try {\n" 4726 " // something\n" 4727 "}\n" 4728 "catch (...) {\n" 4729 " // something\n" 4730 "}", 4731 Style); 4732 } 4733 4734 TEST_F(FormatTest, StaticInitializers) { 4735 verifyFormat("static SomeClass SC = {1, 'a'};"); 4736 4737 verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n" 4738 " 100000000, " 4739 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};"); 4740 4741 // Here, everything other than the "}" would fit on a line. 4742 verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n" 4743 " 10000000000000000000000000};"); 4744 EXPECT_EQ("S s = {a,\n" 4745 "\n" 4746 " b};", 4747 format("S s = {\n" 4748 " a,\n" 4749 "\n" 4750 " b\n" 4751 "};")); 4752 4753 // FIXME: This would fit into the column limit if we'd fit "{ {" on the first 4754 // line. However, the formatting looks a bit off and this probably doesn't 4755 // happen often in practice. 4756 verifyFormat("static int Variable[1] = {\n" 4757 " {1000000000000000000000000000000000000}};", 4758 getLLVMStyleWithColumns(40)); 4759 } 4760 4761 TEST_F(FormatTest, DesignatedInitializers) { 4762 verifyFormat("const struct A a = {.a = 1, .b = 2};"); 4763 verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n" 4764 " .bbbbbbbbbb = 2,\n" 4765 " .cccccccccc = 3,\n" 4766 " .dddddddddd = 4,\n" 4767 " .eeeeeeeeee = 5};"); 4768 verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n" 4769 " .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n" 4770 " .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n" 4771 " .ccccccccccccccccccccccccccc = 3,\n" 4772 " .ddddddddddddddddddddddddddd = 4,\n" 4773 " .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};"); 4774 4775 verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};"); 4776 4777 verifyFormat("const struct A a = {[0] = 1, [1] = 2};"); 4778 verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n" 4779 " [2] = bbbbbbbbbb,\n" 4780 " [3] = cccccccccc,\n" 4781 " [4] = dddddddddd,\n" 4782 " [5] = eeeeeeeeee};"); 4783 verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n" 4784 " [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 4785 " [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 4786 " [3] = cccccccccccccccccccccccccccccccccccccc,\n" 4787 " [4] = dddddddddddddddddddddddddddddddddddddd,\n" 4788 " [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};"); 4789 } 4790 4791 TEST_F(FormatTest, NestedStaticInitializers) { 4792 verifyFormat("static A x = {{{}}};\n"); 4793 verifyFormat("static A x = {{{init1, init2, init3, init4},\n" 4794 " {init1, init2, init3, init4}}};", 4795 getLLVMStyleWithColumns(50)); 4796 4797 verifyFormat("somes Status::global_reps[3] = {\n" 4798 " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n" 4799 " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n" 4800 " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};", 4801 getLLVMStyleWithColumns(60)); 4802 verifyGoogleFormat("SomeType Status::global_reps[3] = {\n" 4803 " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n" 4804 " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n" 4805 " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};"); 4806 verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n" 4807 " {rect.fRight - rect.fLeft, rect.fBottom - " 4808 "rect.fTop}};"); 4809 4810 verifyFormat( 4811 "SomeArrayOfSomeType a = {\n" 4812 " {{1, 2, 3},\n" 4813 " {1, 2, 3},\n" 4814 " {111111111111111111111111111111, 222222222222222222222222222222,\n" 4815 " 333333333333333333333333333333},\n" 4816 " {1, 2, 3},\n" 4817 " {1, 2, 3}}};"); 4818 verifyFormat( 4819 "SomeArrayOfSomeType a = {\n" 4820 " {{1, 2, 3}},\n" 4821 " {{1, 2, 3}},\n" 4822 " {{111111111111111111111111111111, 222222222222222222222222222222,\n" 4823 " 333333333333333333333333333333}},\n" 4824 " {{1, 2, 3}},\n" 4825 " {{1, 2, 3}}};"); 4826 4827 verifyFormat("struct {\n" 4828 " unsigned bit;\n" 4829 " const char *const name;\n" 4830 "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n" 4831 " {kOsWin, \"Windows\"},\n" 4832 " {kOsLinux, \"Linux\"},\n" 4833 " {kOsCrOS, \"Chrome OS\"}};"); 4834 verifyFormat("struct {\n" 4835 " unsigned bit;\n" 4836 " const char *const name;\n" 4837 "} kBitsToOs[] = {\n" 4838 " {kOsMac, \"Mac\"},\n" 4839 " {kOsWin, \"Windows\"},\n" 4840 " {kOsLinux, \"Linux\"},\n" 4841 " {kOsCrOS, \"Chrome OS\"},\n" 4842 "};"); 4843 } 4844 4845 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) { 4846 verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro(" 4847 " \\\n" 4848 " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)"); 4849 } 4850 4851 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) { 4852 verifyFormat("virtual void write(ELFWriter *writerrr,\n" 4853 " OwningPtr<FileOutputBuffer> &buffer) = 0;"); 4854 4855 // Do break defaulted and deleted functions. 4856 verifyFormat("virtual void ~Deeeeeeeestructor() =\n" 4857 " default;", 4858 getLLVMStyleWithColumns(40)); 4859 verifyFormat("virtual void ~Deeeeeeeestructor() =\n" 4860 " delete;", 4861 getLLVMStyleWithColumns(40)); 4862 } 4863 4864 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) { 4865 verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3", 4866 getLLVMStyleWithColumns(40)); 4867 verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"", 4868 getLLVMStyleWithColumns(40)); 4869 EXPECT_EQ("#define Q \\\n" 4870 " \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\" \\\n" 4871 " \"aaaaaaaa.cpp\"", 4872 format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"", 4873 getLLVMStyleWithColumns(40))); 4874 } 4875 4876 TEST_F(FormatTest, UnderstandsLinePPDirective) { 4877 EXPECT_EQ("# 123 \"A string literal\"", 4878 format(" # 123 \"A string literal\"")); 4879 } 4880 4881 TEST_F(FormatTest, LayoutUnknownPPDirective) { 4882 EXPECT_EQ("#;", format("#;")); 4883 verifyFormat("#\n;\n;\n;"); 4884 } 4885 4886 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) { 4887 EXPECT_EQ("#line 42 \"test\"\n", 4888 format("# \\\n line \\\n 42 \\\n \"test\"\n")); 4889 EXPECT_EQ("#define A B\n", format("# \\\n define \\\n A \\\n B\n", 4890 getLLVMStyleWithColumns(12))); 4891 } 4892 4893 TEST_F(FormatTest, EndOfFileEndsPPDirective) { 4894 EXPECT_EQ("#line 42 \"test\"", 4895 format("# \\\n line \\\n 42 \\\n \"test\"")); 4896 EXPECT_EQ("#define A B", format("# \\\n define \\\n A \\\n B")); 4897 } 4898 4899 TEST_F(FormatTest, DoesntRemoveUnknownTokens) { 4900 verifyFormat("#define A \\x20"); 4901 verifyFormat("#define A \\ x20"); 4902 EXPECT_EQ("#define A \\ x20", format("#define A \\ x20")); 4903 verifyFormat("#define A ''"); 4904 verifyFormat("#define A ''qqq"); 4905 verifyFormat("#define A `qqq"); 4906 verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");"); 4907 EXPECT_EQ("const char *c = STRINGIFY(\n" 4908 "\\na : b);", 4909 format("const char * c = STRINGIFY(\n" 4910 "\\na : b);")); 4911 4912 verifyFormat("a\r\\"); 4913 verifyFormat("a\v\\"); 4914 verifyFormat("a\f\\"); 4915 } 4916 4917 TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) { 4918 FormatStyle style = getChromiumStyle(FormatStyle::LK_Cpp); 4919 style.IndentWidth = 4; 4920 style.PPIndentWidth = 1; 4921 4922 style.IndentPPDirectives = FormatStyle::PPDIS_None; 4923 verifyFormat("#ifdef __linux__\n" 4924 "void foo() {\n" 4925 " int x = 0;\n" 4926 "}\n" 4927 "#define FOO\n" 4928 "#endif\n" 4929 "void bar() {\n" 4930 " int y = 0;\n" 4931 "}\n", 4932 style); 4933 4934 style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash; 4935 verifyFormat("#ifdef __linux__\n" 4936 "void foo() {\n" 4937 " int x = 0;\n" 4938 "}\n" 4939 "# define FOO foo\n" 4940 "#endif\n" 4941 "void bar() {\n" 4942 " int y = 0;\n" 4943 "}\n", 4944 style); 4945 4946 style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash; 4947 verifyFormat("#ifdef __linux__\n" 4948 "void foo() {\n" 4949 " int x = 0;\n" 4950 "}\n" 4951 " #define FOO foo\n" 4952 "#endif\n" 4953 "void bar() {\n" 4954 " int y = 0;\n" 4955 "}\n", 4956 style); 4957 } 4958 4959 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) { 4960 verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13)); 4961 verifyFormat("#define A( \\\n BB)", getLLVMStyleWithColumns(12)); 4962 verifyFormat("#define A( \\\n A, B)", getLLVMStyleWithColumns(12)); 4963 // FIXME: We never break before the macro name. 4964 verifyFormat("#define AA( \\\n B)", getLLVMStyleWithColumns(12)); 4965 4966 verifyFormat("#define A A\n#define A A"); 4967 verifyFormat("#define A(X) A\n#define A A"); 4968 4969 verifyFormat("#define Something Other", getLLVMStyleWithColumns(23)); 4970 verifyFormat("#define Something \\\n Other", getLLVMStyleWithColumns(22)); 4971 } 4972 4973 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) { 4974 EXPECT_EQ("// somecomment\n" 4975 "#include \"a.h\"\n" 4976 "#define A( \\\n" 4977 " A, B)\n" 4978 "#include \"b.h\"\n" 4979 "// somecomment\n", 4980 format(" // somecomment\n" 4981 " #include \"a.h\"\n" 4982 "#define A(A,\\\n" 4983 " B)\n" 4984 " #include \"b.h\"\n" 4985 " // somecomment\n", 4986 getLLVMStyleWithColumns(13))); 4987 } 4988 4989 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); } 4990 4991 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) { 4992 EXPECT_EQ("#define A \\\n" 4993 " c; \\\n" 4994 " e;\n" 4995 "f;", 4996 format("#define A c; e;\n" 4997 "f;", 4998 getLLVMStyleWithColumns(14))); 4999 } 5000 5001 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); } 5002 5003 TEST_F(FormatTest, MacroDefinitionInsideStatement) { 5004 EXPECT_EQ("int x,\n" 5005 "#define A\n" 5006 " y;", 5007 format("int x,\n#define A\ny;")); 5008 } 5009 5010 TEST_F(FormatTest, HashInMacroDefinition) { 5011 EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle())); 5012 EXPECT_EQ("#define A(c) u#c", format("#define A(c) u#c", getLLVMStyle())); 5013 EXPECT_EQ("#define A(c) U#c", format("#define A(c) U#c", getLLVMStyle())); 5014 EXPECT_EQ("#define A(c) u8#c", format("#define A(c) u8#c", getLLVMStyle())); 5015 EXPECT_EQ("#define A(c) LR#c", format("#define A(c) LR#c", getLLVMStyle())); 5016 EXPECT_EQ("#define A(c) uR#c", format("#define A(c) uR#c", getLLVMStyle())); 5017 EXPECT_EQ("#define A(c) UR#c", format("#define A(c) UR#c", getLLVMStyle())); 5018 EXPECT_EQ("#define A(c) u8R#c", format("#define A(c) u8R#c", getLLVMStyle())); 5019 verifyFormat("#define A \\\n b #c;", getLLVMStyleWithColumns(11)); 5020 verifyFormat("#define A \\\n" 5021 " { \\\n" 5022 " f(#c); \\\n" 5023 " }", 5024 getLLVMStyleWithColumns(11)); 5025 5026 verifyFormat("#define A(X) \\\n" 5027 " void function##X()", 5028 getLLVMStyleWithColumns(22)); 5029 5030 verifyFormat("#define A(a, b, c) \\\n" 5031 " void a##b##c()", 5032 getLLVMStyleWithColumns(22)); 5033 5034 verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22)); 5035 } 5036 5037 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) { 5038 EXPECT_EQ("#define A (x)", format("#define A (x)")); 5039 EXPECT_EQ("#define A(x)", format("#define A(x)")); 5040 5041 FormatStyle Style = getLLVMStyle(); 5042 Style.SpaceBeforeParens = FormatStyle::SBPO_Never; 5043 verifyFormat("#define true ((foo)1)", Style); 5044 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 5045 verifyFormat("#define false((foo)0)", Style); 5046 } 5047 5048 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) { 5049 EXPECT_EQ("#define A b;", format("#define A \\\n" 5050 " \\\n" 5051 " b;", 5052 getLLVMStyleWithColumns(25))); 5053 EXPECT_EQ("#define A \\\n" 5054 " \\\n" 5055 " a; \\\n" 5056 " b;", 5057 format("#define A \\\n" 5058 " \\\n" 5059 " a; \\\n" 5060 " b;", 5061 getLLVMStyleWithColumns(11))); 5062 EXPECT_EQ("#define A \\\n" 5063 " a; \\\n" 5064 " \\\n" 5065 " b;", 5066 format("#define A \\\n" 5067 " a; \\\n" 5068 " \\\n" 5069 " b;", 5070 getLLVMStyleWithColumns(11))); 5071 } 5072 5073 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) { 5074 verifyIncompleteFormat("#define A :"); 5075 verifyFormat("#define SOMECASES \\\n" 5076 " case 1: \\\n" 5077 " case 2\n", 5078 getLLVMStyleWithColumns(20)); 5079 verifyFormat("#define MACRO(a) \\\n" 5080 " if (a) \\\n" 5081 " f(); \\\n" 5082 " else \\\n" 5083 " g()", 5084 getLLVMStyleWithColumns(18)); 5085 verifyFormat("#define A template <typename T>"); 5086 verifyIncompleteFormat("#define STR(x) #x\n" 5087 "f(STR(this_is_a_string_literal{));"); 5088 verifyFormat("#pragma omp threadprivate( \\\n" 5089 " y)), // expected-warning", 5090 getLLVMStyleWithColumns(28)); 5091 verifyFormat("#d, = };"); 5092 verifyFormat("#if \"a"); 5093 verifyIncompleteFormat("({\n" 5094 "#define b \\\n" 5095 " } \\\n" 5096 " a\n" 5097 "a", 5098 getLLVMStyleWithColumns(15)); 5099 verifyFormat("#define A \\\n" 5100 " { \\\n" 5101 " {\n" 5102 "#define B \\\n" 5103 " } \\\n" 5104 " }", 5105 getLLVMStyleWithColumns(15)); 5106 verifyNoCrash("#if a\na(\n#else\n#endif\n{a"); 5107 verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}"); 5108 verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};"); 5109 verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() { \n)}"); 5110 } 5111 5112 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) { 5113 verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline. 5114 EXPECT_EQ("class A : public QObject {\n" 5115 " Q_OBJECT\n" 5116 "\n" 5117 " A() {}\n" 5118 "};", 5119 format("class A : public QObject {\n" 5120 " Q_OBJECT\n" 5121 "\n" 5122 " A() {\n}\n" 5123 "} ;")); 5124 EXPECT_EQ("MACRO\n" 5125 "/*static*/ int i;", 5126 format("MACRO\n" 5127 " /*static*/ int i;")); 5128 EXPECT_EQ("SOME_MACRO\n" 5129 "namespace {\n" 5130 "void f();\n" 5131 "} // namespace", 5132 format("SOME_MACRO\n" 5133 " namespace {\n" 5134 "void f( );\n" 5135 "} // namespace")); 5136 // Only if the identifier contains at least 5 characters. 5137 EXPECT_EQ("HTTP f();", format("HTTP\nf();")); 5138 EXPECT_EQ("MACRO\nf();", format("MACRO\nf();")); 5139 // Only if everything is upper case. 5140 EXPECT_EQ("class A : public QObject {\n" 5141 " Q_Object A() {}\n" 5142 "};", 5143 format("class A : public QObject {\n" 5144 " Q_Object\n" 5145 " A() {\n}\n" 5146 "} ;")); 5147 5148 // Only if the next line can actually start an unwrapped line. 5149 EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;", 5150 format("SOME_WEIRD_LOG_MACRO\n" 5151 "<< SomeThing;")); 5152 5153 verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), " 5154 "(n, buffers))\n", 5155 getChromiumStyle(FormatStyle::LK_Cpp)); 5156 5157 // See PR41483 5158 EXPECT_EQ("/**/ FOO(a)\n" 5159 "FOO(b)", 5160 format("/**/ FOO(a)\n" 5161 "FOO(b)")); 5162 } 5163 5164 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) { 5165 EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n" 5166 "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n" 5167 "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n" 5168 "class X {};\n" 5169 "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n" 5170 "int *createScopDetectionPass() { return 0; }", 5171 format(" INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n" 5172 " INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n" 5173 " INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n" 5174 " class X {};\n" 5175 " INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n" 5176 " int *createScopDetectionPass() { return 0; }")); 5177 // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as 5178 // braces, so that inner block is indented one level more. 5179 EXPECT_EQ("int q() {\n" 5180 " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n" 5181 " IPC_MESSAGE_HANDLER(xxx, qqq)\n" 5182 " IPC_END_MESSAGE_MAP()\n" 5183 "}", 5184 format("int q() {\n" 5185 " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n" 5186 " IPC_MESSAGE_HANDLER(xxx, qqq)\n" 5187 " IPC_END_MESSAGE_MAP()\n" 5188 "}")); 5189 5190 // Same inside macros. 5191 EXPECT_EQ("#define LIST(L) \\\n" 5192 " L(A) \\\n" 5193 " L(B) \\\n" 5194 " L(C)", 5195 format("#define LIST(L) \\\n" 5196 " L(A) \\\n" 5197 " L(B) \\\n" 5198 " L(C)", 5199 getGoogleStyle())); 5200 5201 // These must not be recognized as macros. 5202 EXPECT_EQ("int q() {\n" 5203 " f(x);\n" 5204 " f(x) {}\n" 5205 " f(x)->g();\n" 5206 " f(x)->*g();\n" 5207 " f(x).g();\n" 5208 " f(x) = x;\n" 5209 " f(x) += x;\n" 5210 " f(x) -= x;\n" 5211 " f(x) *= x;\n" 5212 " f(x) /= x;\n" 5213 " f(x) %= x;\n" 5214 " f(x) &= x;\n" 5215 " f(x) |= x;\n" 5216 " f(x) ^= x;\n" 5217 " f(x) >>= x;\n" 5218 " f(x) <<= x;\n" 5219 " f(x)[y].z();\n" 5220 " LOG(INFO) << x;\n" 5221 " ifstream(x) >> x;\n" 5222 "}\n", 5223 format("int q() {\n" 5224 " f(x)\n;\n" 5225 " f(x)\n {}\n" 5226 " f(x)\n->g();\n" 5227 " f(x)\n->*g();\n" 5228 " f(x)\n.g();\n" 5229 " f(x)\n = x;\n" 5230 " f(x)\n += x;\n" 5231 " f(x)\n -= x;\n" 5232 " f(x)\n *= x;\n" 5233 " f(x)\n /= x;\n" 5234 " f(x)\n %= x;\n" 5235 " f(x)\n &= x;\n" 5236 " f(x)\n |= x;\n" 5237 " f(x)\n ^= x;\n" 5238 " f(x)\n >>= x;\n" 5239 " f(x)\n <<= x;\n" 5240 " f(x)\n[y].z();\n" 5241 " LOG(INFO)\n << x;\n" 5242 " ifstream(x)\n >> x;\n" 5243 "}\n")); 5244 EXPECT_EQ("int q() {\n" 5245 " F(x)\n" 5246 " if (1) {\n" 5247 " }\n" 5248 " F(x)\n" 5249 " while (1) {\n" 5250 " }\n" 5251 " F(x)\n" 5252 " G(x);\n" 5253 " F(x)\n" 5254 " try {\n" 5255 " Q();\n" 5256 " } catch (...) {\n" 5257 " }\n" 5258 "}\n", 5259 format("int q() {\n" 5260 "F(x)\n" 5261 "if (1) {}\n" 5262 "F(x)\n" 5263 "while (1) {}\n" 5264 "F(x)\n" 5265 "G(x);\n" 5266 "F(x)\n" 5267 "try { Q(); } catch (...) {}\n" 5268 "}\n")); 5269 EXPECT_EQ("class A {\n" 5270 " A() : t(0) {}\n" 5271 " A(int i) noexcept() : {}\n" 5272 " A(X x)\n" // FIXME: function-level try blocks are broken. 5273 " try : t(0) {\n" 5274 " } catch (...) {\n" 5275 " }\n" 5276 "};", 5277 format("class A {\n" 5278 " A()\n : t(0) {}\n" 5279 " A(int i)\n noexcept() : {}\n" 5280 " A(X x)\n" 5281 " try : t(0) {} catch (...) {}\n" 5282 "};")); 5283 FormatStyle Style = getLLVMStyle(); 5284 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 5285 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 5286 Style.BraceWrapping.AfterFunction = true; 5287 EXPECT_EQ("void f()\n" 5288 "try\n" 5289 "{\n" 5290 "}", 5291 format("void f() try {\n" 5292 "}", 5293 Style)); 5294 EXPECT_EQ("class SomeClass {\n" 5295 "public:\n" 5296 " SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5297 "};", 5298 format("class SomeClass {\n" 5299 "public:\n" 5300 " SomeClass()\n" 5301 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5302 "};")); 5303 EXPECT_EQ("class SomeClass {\n" 5304 "public:\n" 5305 " SomeClass()\n" 5306 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5307 "};", 5308 format("class SomeClass {\n" 5309 "public:\n" 5310 " SomeClass()\n" 5311 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5312 "};", 5313 getLLVMStyleWithColumns(40))); 5314 5315 verifyFormat("MACRO(>)"); 5316 5317 // Some macros contain an implicit semicolon. 5318 Style = getLLVMStyle(); 5319 Style.StatementMacros.push_back("FOO"); 5320 verifyFormat("FOO(a) int b = 0;"); 5321 verifyFormat("FOO(a)\n" 5322 "int b = 0;", 5323 Style); 5324 verifyFormat("FOO(a);\n" 5325 "int b = 0;", 5326 Style); 5327 verifyFormat("FOO(argc, argv, \"4.0.2\")\n" 5328 "int b = 0;", 5329 Style); 5330 verifyFormat("FOO()\n" 5331 "int b = 0;", 5332 Style); 5333 verifyFormat("FOO\n" 5334 "int b = 0;", 5335 Style); 5336 verifyFormat("void f() {\n" 5337 " FOO(a)\n" 5338 " return a;\n" 5339 "}", 5340 Style); 5341 verifyFormat("FOO(a)\n" 5342 "FOO(b)", 5343 Style); 5344 verifyFormat("int a = 0;\n" 5345 "FOO(b)\n" 5346 "int c = 0;", 5347 Style); 5348 verifyFormat("int a = 0;\n" 5349 "int x = FOO(a)\n" 5350 "int b = 0;", 5351 Style); 5352 verifyFormat("void foo(int a) { FOO(a) }\n" 5353 "uint32_t bar() {}", 5354 Style); 5355 } 5356 5357 TEST_F(FormatTest, FormatsMacrosWithZeroColumnWidth) { 5358 FormatStyle ZeroColumn = getLLVMStyleWithColumns(0); 5359 5360 verifyFormat("#define A LOOOOOOOOOOOOOOOOOOONG() LOOOOOOOOOOOOOOOOOOONG()", 5361 ZeroColumn); 5362 } 5363 5364 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) { 5365 verifyFormat("#define A \\\n" 5366 " f({ \\\n" 5367 " g(); \\\n" 5368 " });", 5369 getLLVMStyleWithColumns(11)); 5370 } 5371 5372 TEST_F(FormatTest, IndentPreprocessorDirectives) { 5373 FormatStyle Style = getLLVMStyleWithColumns(40); 5374 Style.IndentPPDirectives = FormatStyle::PPDIS_None; 5375 verifyFormat("#ifdef _WIN32\n" 5376 "#define A 0\n" 5377 "#ifdef VAR2\n" 5378 "#define B 1\n" 5379 "#include <someheader.h>\n" 5380 "#define MACRO \\\n" 5381 " some_very_long_func_aaaaaaaaaa();\n" 5382 "#endif\n" 5383 "#else\n" 5384 "#define A 1\n" 5385 "#endif", 5386 Style); 5387 Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash; 5388 verifyFormat("#ifdef _WIN32\n" 5389 "# define A 0\n" 5390 "# ifdef VAR2\n" 5391 "# define B 1\n" 5392 "# include <someheader.h>\n" 5393 "# define MACRO \\\n" 5394 " some_very_long_func_aaaaaaaaaa();\n" 5395 "# endif\n" 5396 "#else\n" 5397 "# define A 1\n" 5398 "#endif", 5399 Style); 5400 verifyFormat("#if A\n" 5401 "# define MACRO \\\n" 5402 " void a(int x) { \\\n" 5403 " b(); \\\n" 5404 " c(); \\\n" 5405 " d(); \\\n" 5406 " e(); \\\n" 5407 " f(); \\\n" 5408 " }\n" 5409 "#endif", 5410 Style); 5411 // Comments before include guard. 5412 verifyFormat("// file comment\n" 5413 "// file comment\n" 5414 "#ifndef HEADER_H\n" 5415 "#define HEADER_H\n" 5416 "code();\n" 5417 "#endif", 5418 Style); 5419 // Test with include guards. 5420 verifyFormat("#ifndef HEADER_H\n" 5421 "#define HEADER_H\n" 5422 "code();\n" 5423 "#endif", 5424 Style); 5425 // Include guards must have a #define with the same variable immediately 5426 // after #ifndef. 5427 verifyFormat("#ifndef NOT_GUARD\n" 5428 "# define FOO\n" 5429 "code();\n" 5430 "#endif", 5431 Style); 5432 5433 // Include guards must cover the entire file. 5434 verifyFormat("code();\n" 5435 "code();\n" 5436 "#ifndef NOT_GUARD\n" 5437 "# define NOT_GUARD\n" 5438 "code();\n" 5439 "#endif", 5440 Style); 5441 verifyFormat("#ifndef NOT_GUARD\n" 5442 "# define NOT_GUARD\n" 5443 "code();\n" 5444 "#endif\n" 5445 "code();", 5446 Style); 5447 // Test with trailing blank lines. 5448 verifyFormat("#ifndef HEADER_H\n" 5449 "#define HEADER_H\n" 5450 "code();\n" 5451 "#endif\n", 5452 Style); 5453 // Include guards don't have #else. 5454 verifyFormat("#ifndef NOT_GUARD\n" 5455 "# define NOT_GUARD\n" 5456 "code();\n" 5457 "#else\n" 5458 "#endif", 5459 Style); 5460 verifyFormat("#ifndef NOT_GUARD\n" 5461 "# define NOT_GUARD\n" 5462 "code();\n" 5463 "#elif FOO\n" 5464 "#endif", 5465 Style); 5466 // Non-identifier #define after potential include guard. 5467 verifyFormat("#ifndef FOO\n" 5468 "# define 1\n" 5469 "#endif\n", 5470 Style); 5471 // #if closes past last non-preprocessor line. 5472 verifyFormat("#ifndef FOO\n" 5473 "#define FOO\n" 5474 "#if 1\n" 5475 "int i;\n" 5476 "# define A 0\n" 5477 "#endif\n" 5478 "#endif\n", 5479 Style); 5480 // Don't crash if there is an #elif directive without a condition. 5481 verifyFormat("#if 1\n" 5482 "int x;\n" 5483 "#elif\n" 5484 "int y;\n" 5485 "#else\n" 5486 "int z;\n" 5487 "#endif", 5488 Style); 5489 // FIXME: This doesn't handle the case where there's code between the 5490 // #ifndef and #define but all other conditions hold. This is because when 5491 // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the 5492 // previous code line yet, so we can't detect it. 5493 EXPECT_EQ("#ifndef NOT_GUARD\n" 5494 "code();\n" 5495 "#define NOT_GUARD\n" 5496 "code();\n" 5497 "#endif", 5498 format("#ifndef NOT_GUARD\n" 5499 "code();\n" 5500 "# define NOT_GUARD\n" 5501 "code();\n" 5502 "#endif", 5503 Style)); 5504 // FIXME: This doesn't handle cases where legitimate preprocessor lines may 5505 // be outside an include guard. Examples are #pragma once and 5506 // #pragma GCC diagnostic, or anything else that does not change the meaning 5507 // of the file if it's included multiple times. 5508 EXPECT_EQ("#ifdef WIN32\n" 5509 "# pragma once\n" 5510 "#endif\n" 5511 "#ifndef HEADER_H\n" 5512 "# define HEADER_H\n" 5513 "code();\n" 5514 "#endif", 5515 format("#ifdef WIN32\n" 5516 "# pragma once\n" 5517 "#endif\n" 5518 "#ifndef HEADER_H\n" 5519 "#define HEADER_H\n" 5520 "code();\n" 5521 "#endif", 5522 Style)); 5523 // FIXME: This does not detect when there is a single non-preprocessor line 5524 // in front of an include-guard-like structure where other conditions hold 5525 // because ScopedLineState hides the line. 5526 EXPECT_EQ("code();\n" 5527 "#ifndef HEADER_H\n" 5528 "#define HEADER_H\n" 5529 "code();\n" 5530 "#endif", 5531 format("code();\n" 5532 "#ifndef HEADER_H\n" 5533 "# define HEADER_H\n" 5534 "code();\n" 5535 "#endif", 5536 Style)); 5537 // Keep comments aligned with #, otherwise indent comments normally. These 5538 // tests cannot use verifyFormat because messUp manipulates leading 5539 // whitespace. 5540 { 5541 const char *Expected = "" 5542 "void f() {\n" 5543 "#if 1\n" 5544 "// Preprocessor aligned.\n" 5545 "# define A 0\n" 5546 " // Code. Separated by blank line.\n" 5547 "\n" 5548 "# define B 0\n" 5549 " // Code. Not aligned with #\n" 5550 "# define C 0\n" 5551 "#endif"; 5552 const char *ToFormat = "" 5553 "void f() {\n" 5554 "#if 1\n" 5555 "// Preprocessor aligned.\n" 5556 "# define A 0\n" 5557 "// Code. Separated by blank line.\n" 5558 "\n" 5559 "# define B 0\n" 5560 " // Code. Not aligned with #\n" 5561 "# define C 0\n" 5562 "#endif"; 5563 EXPECT_EQ(Expected, format(ToFormat, Style)); 5564 EXPECT_EQ(Expected, format(Expected, Style)); 5565 } 5566 // Keep block quotes aligned. 5567 { 5568 const char *Expected = "" 5569 "void f() {\n" 5570 "#if 1\n" 5571 "/* Preprocessor aligned. */\n" 5572 "# define A 0\n" 5573 " /* Code. Separated by blank line. */\n" 5574 "\n" 5575 "# define B 0\n" 5576 " /* Code. Not aligned with # */\n" 5577 "# define C 0\n" 5578 "#endif"; 5579 const char *ToFormat = "" 5580 "void f() {\n" 5581 "#if 1\n" 5582 "/* Preprocessor aligned. */\n" 5583 "# define A 0\n" 5584 "/* Code. Separated by blank line. */\n" 5585 "\n" 5586 "# define B 0\n" 5587 " /* Code. Not aligned with # */\n" 5588 "# define C 0\n" 5589 "#endif"; 5590 EXPECT_EQ(Expected, format(ToFormat, Style)); 5591 EXPECT_EQ(Expected, format(Expected, Style)); 5592 } 5593 // Keep comments aligned with un-indented directives. 5594 { 5595 const char *Expected = "" 5596 "void f() {\n" 5597 "// Preprocessor aligned.\n" 5598 "#define A 0\n" 5599 " // Code. Separated by blank line.\n" 5600 "\n" 5601 "#define B 0\n" 5602 " // Code. Not aligned with #\n" 5603 "#define C 0\n"; 5604 const char *ToFormat = "" 5605 "void f() {\n" 5606 "// Preprocessor aligned.\n" 5607 "#define A 0\n" 5608 "// Code. Separated by blank line.\n" 5609 "\n" 5610 "#define B 0\n" 5611 " // Code. Not aligned with #\n" 5612 "#define C 0\n"; 5613 EXPECT_EQ(Expected, format(ToFormat, Style)); 5614 EXPECT_EQ(Expected, format(Expected, Style)); 5615 } 5616 // Test AfterHash with tabs. 5617 { 5618 FormatStyle Tabbed = Style; 5619 Tabbed.UseTab = FormatStyle::UT_Always; 5620 Tabbed.IndentWidth = 8; 5621 Tabbed.TabWidth = 8; 5622 verifyFormat("#ifdef _WIN32\n" 5623 "#\tdefine A 0\n" 5624 "#\tifdef VAR2\n" 5625 "#\t\tdefine B 1\n" 5626 "#\t\tinclude <someheader.h>\n" 5627 "#\t\tdefine MACRO \\\n" 5628 "\t\t\tsome_very_long_func_aaaaaaaaaa();\n" 5629 "#\tendif\n" 5630 "#else\n" 5631 "#\tdefine A 1\n" 5632 "#endif", 5633 Tabbed); 5634 } 5635 5636 // Regression test: Multiline-macro inside include guards. 5637 verifyFormat("#ifndef HEADER_H\n" 5638 "#define HEADER_H\n" 5639 "#define A() \\\n" 5640 " int i; \\\n" 5641 " int j;\n" 5642 "#endif // HEADER_H", 5643 getLLVMStyleWithColumns(20)); 5644 5645 Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash; 5646 // Basic before hash indent tests 5647 verifyFormat("#ifdef _WIN32\n" 5648 " #define A 0\n" 5649 " #ifdef VAR2\n" 5650 " #define B 1\n" 5651 " #include <someheader.h>\n" 5652 " #define MACRO \\\n" 5653 " some_very_long_func_aaaaaaaaaa();\n" 5654 " #endif\n" 5655 "#else\n" 5656 " #define A 1\n" 5657 "#endif", 5658 Style); 5659 verifyFormat("#if A\n" 5660 " #define MACRO \\\n" 5661 " void a(int x) { \\\n" 5662 " b(); \\\n" 5663 " c(); \\\n" 5664 " d(); \\\n" 5665 " e(); \\\n" 5666 " f(); \\\n" 5667 " }\n" 5668 "#endif", 5669 Style); 5670 // Keep comments aligned with indented directives. These 5671 // tests cannot use verifyFormat because messUp manipulates leading 5672 // whitespace. 5673 { 5674 const char *Expected = "void f() {\n" 5675 "// Aligned to preprocessor.\n" 5676 "#if 1\n" 5677 " // Aligned to code.\n" 5678 " int a;\n" 5679 " #if 1\n" 5680 " // Aligned to preprocessor.\n" 5681 " #define A 0\n" 5682 " // Aligned to code.\n" 5683 " int b;\n" 5684 " #endif\n" 5685 "#endif\n" 5686 "}"; 5687 const char *ToFormat = "void f() {\n" 5688 "// Aligned to preprocessor.\n" 5689 "#if 1\n" 5690 "// Aligned to code.\n" 5691 "int a;\n" 5692 "#if 1\n" 5693 "// Aligned to preprocessor.\n" 5694 "#define A 0\n" 5695 "// Aligned to code.\n" 5696 "int b;\n" 5697 "#endif\n" 5698 "#endif\n" 5699 "}"; 5700 EXPECT_EQ(Expected, format(ToFormat, Style)); 5701 EXPECT_EQ(Expected, format(Expected, Style)); 5702 } 5703 { 5704 const char *Expected = "void f() {\n" 5705 "/* Aligned to preprocessor. */\n" 5706 "#if 1\n" 5707 " /* Aligned to code. */\n" 5708 " int a;\n" 5709 " #if 1\n" 5710 " /* Aligned to preprocessor. */\n" 5711 " #define A 0\n" 5712 " /* Aligned to code. */\n" 5713 " int b;\n" 5714 " #endif\n" 5715 "#endif\n" 5716 "}"; 5717 const char *ToFormat = "void f() {\n" 5718 "/* Aligned to preprocessor. */\n" 5719 "#if 1\n" 5720 "/* Aligned to code. */\n" 5721 "int a;\n" 5722 "#if 1\n" 5723 "/* Aligned to preprocessor. */\n" 5724 "#define A 0\n" 5725 "/* Aligned to code. */\n" 5726 "int b;\n" 5727 "#endif\n" 5728 "#endif\n" 5729 "}"; 5730 EXPECT_EQ(Expected, format(ToFormat, Style)); 5731 EXPECT_EQ(Expected, format(Expected, Style)); 5732 } 5733 5734 // Test single comment before preprocessor 5735 verifyFormat("// Comment\n" 5736 "\n" 5737 "#if 1\n" 5738 "#endif", 5739 Style); 5740 } 5741 5742 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) { 5743 verifyFormat("{\n { a #c; }\n}"); 5744 } 5745 5746 TEST_F(FormatTest, FormatUnbalancedStructuralElements) { 5747 EXPECT_EQ("#define A \\\n { \\\n {\nint i;", 5748 format("#define A { {\nint i;", getLLVMStyleWithColumns(11))); 5749 EXPECT_EQ("#define A \\\n } \\\n }\nint i;", 5750 format("#define A } }\nint i;", getLLVMStyleWithColumns(11))); 5751 } 5752 5753 TEST_F(FormatTest, EscapedNewlines) { 5754 FormatStyle Narrow = getLLVMStyleWithColumns(11); 5755 EXPECT_EQ("#define A \\\n int i; \\\n int j;", 5756 format("#define A \\\nint i;\\\n int j;", Narrow)); 5757 EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;")); 5758 EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();")); 5759 EXPECT_EQ("/* \\ \\ \\\n */", format("\\\n/* \\ \\ \\\n */")); 5760 EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>")); 5761 5762 FormatStyle AlignLeft = getLLVMStyle(); 5763 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left; 5764 EXPECT_EQ("#define MACRO(x) \\\n" 5765 "private: \\\n" 5766 " int x(int a);\n", 5767 format("#define MACRO(x) \\\n" 5768 "private: \\\n" 5769 " int x(int a);\n", 5770 AlignLeft)); 5771 5772 // CRLF line endings 5773 EXPECT_EQ("#define A \\\r\n int i; \\\r\n int j;", 5774 format("#define A \\\r\nint i;\\\r\n int j;", Narrow)); 5775 EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;")); 5776 EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();")); 5777 EXPECT_EQ("/* \\ \\ \\\r\n */", format("\\\r\n/* \\ \\ \\\r\n */")); 5778 EXPECT_EQ("<a\r\n\\\\\r\n>", format("<a\r\n\\\\\r\n>")); 5779 EXPECT_EQ("#define MACRO(x) \\\r\n" 5780 "private: \\\r\n" 5781 " int x(int a);\r\n", 5782 format("#define MACRO(x) \\\r\n" 5783 "private: \\\r\n" 5784 " int x(int a);\r\n", 5785 AlignLeft)); 5786 5787 FormatStyle DontAlign = getLLVMStyle(); 5788 DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 5789 DontAlign.MaxEmptyLinesToKeep = 3; 5790 // FIXME: can't use verifyFormat here because the newline before 5791 // "public:" is not inserted the first time it's reformatted 5792 EXPECT_EQ("#define A \\\n" 5793 " class Foo { \\\n" 5794 " void bar(); \\\n" 5795 "\\\n" 5796 "\\\n" 5797 "\\\n" 5798 " public: \\\n" 5799 " void baz(); \\\n" 5800 " };", 5801 format("#define A \\\n" 5802 " class Foo { \\\n" 5803 " void bar(); \\\n" 5804 "\\\n" 5805 "\\\n" 5806 "\\\n" 5807 " public: \\\n" 5808 " void baz(); \\\n" 5809 " };", 5810 DontAlign)); 5811 } 5812 5813 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) { 5814 verifyFormat("#define A \\\n" 5815 " int v( \\\n" 5816 " a); \\\n" 5817 " int i;", 5818 getLLVMStyleWithColumns(11)); 5819 } 5820 5821 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) { 5822 EXPECT_EQ( 5823 "#define ALooooooooooooooooooooooooooooooooooooooongMacro(" 5824 " \\\n" 5825 " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n" 5826 "\n" 5827 "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n" 5828 " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n", 5829 format(" #define ALooooooooooooooooooooooooooooooooooooooongMacro(" 5830 "\\\n" 5831 "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n" 5832 " \n" 5833 " AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n" 5834 " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n")); 5835 } 5836 5837 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) { 5838 EXPECT_EQ("int\n" 5839 "#define A\n" 5840 " a;", 5841 format("int\n#define A\na;")); 5842 verifyFormat("functionCallTo(\n" 5843 " someOtherFunction(\n" 5844 " withSomeParameters, whichInSequence,\n" 5845 " areLongerThanALine(andAnotherCall,\n" 5846 "#define A B\n" 5847 " withMoreParamters,\n" 5848 " whichStronglyInfluenceTheLayout),\n" 5849 " andMoreParameters),\n" 5850 " trailing);", 5851 getLLVMStyleWithColumns(69)); 5852 verifyFormat("Foo::Foo()\n" 5853 "#ifdef BAR\n" 5854 " : baz(0)\n" 5855 "#endif\n" 5856 "{\n" 5857 "}"); 5858 verifyFormat("void f() {\n" 5859 " if (true)\n" 5860 "#ifdef A\n" 5861 " f(42);\n" 5862 " x();\n" 5863 "#else\n" 5864 " g();\n" 5865 " x();\n" 5866 "#endif\n" 5867 "}"); 5868 verifyFormat("void f(param1, param2,\n" 5869 " param3,\n" 5870 "#ifdef A\n" 5871 " param4(param5,\n" 5872 "#ifdef A1\n" 5873 " param6,\n" 5874 "#ifdef A2\n" 5875 " param7),\n" 5876 "#else\n" 5877 " param8),\n" 5878 " param9,\n" 5879 "#endif\n" 5880 " param10,\n" 5881 "#endif\n" 5882 " param11)\n" 5883 "#else\n" 5884 " param12)\n" 5885 "#endif\n" 5886 "{\n" 5887 " x();\n" 5888 "}", 5889 getLLVMStyleWithColumns(28)); 5890 verifyFormat("#if 1\n" 5891 "int i;"); 5892 verifyFormat("#if 1\n" 5893 "#endif\n" 5894 "#if 1\n" 5895 "#else\n" 5896 "#endif\n"); 5897 verifyFormat("DEBUG({\n" 5898 " return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5899 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n" 5900 "});\n" 5901 "#if a\n" 5902 "#else\n" 5903 "#endif"); 5904 5905 verifyIncompleteFormat("void f(\n" 5906 "#if A\n" 5907 ");\n" 5908 "#else\n" 5909 "#endif"); 5910 } 5911 5912 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) { 5913 verifyFormat("#endif\n" 5914 "#if B"); 5915 } 5916 5917 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) { 5918 FormatStyle SingleLine = getLLVMStyle(); 5919 SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse; 5920 verifyFormat("#if 0\n" 5921 "#elif 1\n" 5922 "#endif\n" 5923 "void foo() {\n" 5924 " if (test) foo2();\n" 5925 "}", 5926 SingleLine); 5927 } 5928 5929 TEST_F(FormatTest, LayoutBlockInsideParens) { 5930 verifyFormat("functionCall({ int i; });"); 5931 verifyFormat("functionCall({\n" 5932 " int i;\n" 5933 " int j;\n" 5934 "});"); 5935 verifyFormat("functionCall(\n" 5936 " {\n" 5937 " int i;\n" 5938 " int j;\n" 5939 " },\n" 5940 " aaaa, bbbb, cccc);"); 5941 verifyFormat("functionA(functionB({\n" 5942 " int i;\n" 5943 " int j;\n" 5944 " }),\n" 5945 " aaaa, bbbb, cccc);"); 5946 verifyFormat("functionCall(\n" 5947 " {\n" 5948 " int i;\n" 5949 " int j;\n" 5950 " },\n" 5951 " aaaa, bbbb, // comment\n" 5952 " cccc);"); 5953 verifyFormat("functionA(functionB({\n" 5954 " int i;\n" 5955 " int j;\n" 5956 " }),\n" 5957 " aaaa, bbbb, // comment\n" 5958 " cccc);"); 5959 verifyFormat("functionCall(aaaa, bbbb, { int i; });"); 5960 verifyFormat("functionCall(aaaa, bbbb, {\n" 5961 " int i;\n" 5962 " int j;\n" 5963 "});"); 5964 verifyFormat( 5965 "Aaa(\n" // FIXME: There shouldn't be a linebreak here. 5966 " {\n" 5967 " int i; // break\n" 5968 " },\n" 5969 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 5970 " ccccccccccccccccc));"); 5971 verifyFormat("DEBUG({\n" 5972 " if (a)\n" 5973 " f();\n" 5974 "});"); 5975 } 5976 5977 TEST_F(FormatTest, LayoutBlockInsideStatement) { 5978 EXPECT_EQ("SOME_MACRO { int i; }\n" 5979 "int i;", 5980 format(" SOME_MACRO {int i;} int i;")); 5981 } 5982 5983 TEST_F(FormatTest, LayoutNestedBlocks) { 5984 verifyFormat("void AddOsStrings(unsigned bitmask) {\n" 5985 " struct s {\n" 5986 " int i;\n" 5987 " };\n" 5988 " s kBitsToOs[] = {{10}};\n" 5989 " for (int i = 0; i < 10; ++i)\n" 5990 " return;\n" 5991 "}"); 5992 verifyFormat("call(parameter, {\n" 5993 " something();\n" 5994 " // Comment using all columns.\n" 5995 " somethingelse();\n" 5996 "});", 5997 getLLVMStyleWithColumns(40)); 5998 verifyFormat("DEBUG( //\n" 5999 " { f(); }, a);"); 6000 verifyFormat("DEBUG( //\n" 6001 " {\n" 6002 " f(); //\n" 6003 " },\n" 6004 " a);"); 6005 6006 EXPECT_EQ("call(parameter, {\n" 6007 " something();\n" 6008 " // Comment too\n" 6009 " // looooooooooong.\n" 6010 " somethingElse();\n" 6011 "});", 6012 format("call(parameter, {\n" 6013 " something();\n" 6014 " // Comment too looooooooooong.\n" 6015 " somethingElse();\n" 6016 "});", 6017 getLLVMStyleWithColumns(29))); 6018 EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int i; });")); 6019 EXPECT_EQ("DEBUG({ // comment\n" 6020 " int i;\n" 6021 "});", 6022 format("DEBUG({ // comment\n" 6023 "int i;\n" 6024 "});")); 6025 EXPECT_EQ("DEBUG({\n" 6026 " int i;\n" 6027 "\n" 6028 " // comment\n" 6029 " int j;\n" 6030 "});", 6031 format("DEBUG({\n" 6032 " int i;\n" 6033 "\n" 6034 " // comment\n" 6035 " int j;\n" 6036 "});")); 6037 6038 verifyFormat("DEBUG({\n" 6039 " if (a)\n" 6040 " return;\n" 6041 "});"); 6042 verifyGoogleFormat("DEBUG({\n" 6043 " if (a) return;\n" 6044 "});"); 6045 FormatStyle Style = getGoogleStyle(); 6046 Style.ColumnLimit = 45; 6047 verifyFormat("Debug(\n" 6048 " aaaaa,\n" 6049 " {\n" 6050 " if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n" 6051 " },\n" 6052 " a);", 6053 Style); 6054 6055 verifyFormat("SomeFunction({MACRO({ return output; }), b});"); 6056 6057 verifyNoCrash("^{v^{a}}"); 6058 } 6059 6060 TEST_F(FormatTest, FormatNestedBlocksInMacros) { 6061 EXPECT_EQ("#define MACRO() \\\n" 6062 " Debug(aaa, /* force line break */ \\\n" 6063 " { \\\n" 6064 " int i; \\\n" 6065 " int j; \\\n" 6066 " })", 6067 format("#define MACRO() Debug(aaa, /* force line break */ \\\n" 6068 " { int i; int j; })", 6069 getGoogleStyle())); 6070 6071 EXPECT_EQ("#define A \\\n" 6072 " [] { \\\n" 6073 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 6074 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n" 6075 " }", 6076 format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 6077 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }", 6078 getGoogleStyle())); 6079 } 6080 6081 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) { 6082 EXPECT_EQ("{}", format("{}")); 6083 verifyFormat("enum E {};"); 6084 verifyFormat("enum E {}"); 6085 FormatStyle Style = getLLVMStyle(); 6086 Style.SpaceInEmptyBlock = true; 6087 EXPECT_EQ("void f() { }", format("void f() {}", Style)); 6088 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 6089 EXPECT_EQ("while (true) { }", format("while (true) {}", Style)); 6090 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 6091 Style.BraceWrapping.BeforeElse = false; 6092 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 6093 verifyFormat("if (a)\n" 6094 "{\n" 6095 "} else if (b)\n" 6096 "{\n" 6097 "} else\n" 6098 "{ }", 6099 Style); 6100 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never; 6101 verifyFormat("if (a) {\n" 6102 "} else if (b) {\n" 6103 "} else {\n" 6104 "}", 6105 Style); 6106 Style.BraceWrapping.BeforeElse = true; 6107 verifyFormat("if (a) { }\n" 6108 "else if (b) { }\n" 6109 "else { }", 6110 Style); 6111 } 6112 6113 TEST_F(FormatTest, FormatBeginBlockEndMacros) { 6114 FormatStyle Style = getLLVMStyle(); 6115 Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$"; 6116 Style.MacroBlockEnd = "^[A-Z_]+_END$"; 6117 verifyFormat("FOO_BEGIN\n" 6118 " FOO_ENTRY\n" 6119 "FOO_END", 6120 Style); 6121 verifyFormat("FOO_BEGIN\n" 6122 " NESTED_FOO_BEGIN\n" 6123 " NESTED_FOO_ENTRY\n" 6124 " NESTED_FOO_END\n" 6125 "FOO_END", 6126 Style); 6127 verifyFormat("FOO_BEGIN(Foo, Bar)\n" 6128 " int x;\n" 6129 " x = 1;\n" 6130 "FOO_END(Baz)", 6131 Style); 6132 } 6133 6134 //===----------------------------------------------------------------------===// 6135 // Line break tests. 6136 //===----------------------------------------------------------------------===// 6137 6138 TEST_F(FormatTest, PreventConfusingIndents) { 6139 verifyFormat( 6140 "void f() {\n" 6141 " SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n" 6142 " parameter, parameter, parameter)),\n" 6143 " SecondLongCall(parameter));\n" 6144 "}"); 6145 verifyFormat( 6146 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6147 " aaaaaaaaaaaaaaaaaaaaaaaa(\n" 6148 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6149 " aaaaaaaaaaaaaaaaaaaaaaaa);"); 6150 verifyFormat( 6151 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6152 " [aaaaaaaaaaaaaaaaaaaaaaaa\n" 6153 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n" 6154 " [aaaaaaaaaaaaaaaaaaaaaaaa]];"); 6155 verifyFormat( 6156 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 6157 " aaaaaaaaaaaaaaaaaaaaaaaa<\n" 6158 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n" 6159 " aaaaaaaaaaaaaaaaaaaaaaaa>;"); 6160 verifyFormat("int a = bbbb && ccc &&\n" 6161 " fffff(\n" 6162 "#define A Just forcing a new line\n" 6163 " ddd);"); 6164 } 6165 6166 TEST_F(FormatTest, LineBreakingInBinaryExpressions) { 6167 verifyFormat( 6168 "bool aaaaaaa =\n" 6169 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n" 6170 " bbbbbbbb();"); 6171 verifyFormat( 6172 "bool aaaaaaa =\n" 6173 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n" 6174 " bbbbbbbb();"); 6175 6176 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n" 6177 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n" 6178 " ccccccccc == ddddddddddd;"); 6179 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n" 6180 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n" 6181 " ccccccccc == ddddddddddd;"); 6182 verifyFormat( 6183 "bool aaaaaaaaaaaaaaaaaaaaa =\n" 6184 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n" 6185 " ccccccccc == ddddddddddd;"); 6186 6187 verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n" 6188 " aaaaaa) &&\n" 6189 " bbbbbb && cccccc;"); 6190 verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n" 6191 " aaaaaa) >>\n" 6192 " bbbbbb;"); 6193 verifyFormat("aa = Whitespaces.addUntouchableComment(\n" 6194 " SourceMgr.getSpellingColumnNumber(\n" 6195 " TheLine.Last->FormatTok.Tok.getLocation()) -\n" 6196 " 1);"); 6197 6198 verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6199 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n" 6200 " cccccc) {\n}"); 6201 verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6202 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n" 6203 " cccccc) {\n}"); 6204 verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6205 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n" 6206 " cccccc) {\n}"); 6207 verifyFormat("b = a &&\n" 6208 " // Comment\n" 6209 " b.c && d;"); 6210 6211 // If the LHS of a comparison is not a binary expression itself, the 6212 // additional linebreak confuses many people. 6213 verifyFormat( 6214 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6215 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n" 6216 "}"); 6217 verifyFormat( 6218 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6219 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 6220 "}"); 6221 verifyFormat( 6222 "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n" 6223 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 6224 "}"); 6225 verifyFormat( 6226 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6227 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n" 6228 "}"); 6229 // Even explicit parentheses stress the precedence enough to make the 6230 // additional break unnecessary. 6231 verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6232 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 6233 "}"); 6234 // This cases is borderline, but with the indentation it is still readable. 6235 verifyFormat( 6236 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6237 " aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6238 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 6239 "}", 6240 getLLVMStyleWithColumns(75)); 6241 6242 // If the LHS is a binary expression, we should still use the additional break 6243 // as otherwise the formatting hides the operator precedence. 6244 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6245 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6246 " 5) {\n" 6247 "}"); 6248 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6249 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n" 6250 " 5) {\n" 6251 "}"); 6252 6253 FormatStyle OnePerLine = getLLVMStyle(); 6254 OnePerLine.BinPackParameters = false; 6255 verifyFormat( 6256 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6257 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6258 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}", 6259 OnePerLine); 6260 6261 verifyFormat("int i = someFunction(aaaaaaa, 0)\n" 6262 " .aaa(aaaaaaaaaaaaa) *\n" 6263 " aaaaaaa +\n" 6264 " aaaaaaa;", 6265 getLLVMStyleWithColumns(40)); 6266 } 6267 6268 TEST_F(FormatTest, ExpressionIndentation) { 6269 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6270 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6271 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6272 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6273 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n" 6274 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n" 6275 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6276 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n" 6277 " ccccccccccccccccccccccccccccccccccccccccc;"); 6278 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6279 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6280 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6281 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 6282 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6283 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6284 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6285 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 6286 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6287 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6288 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6289 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 6290 verifyFormat("if () {\n" 6291 "} else if (aaaaa && bbbbb > // break\n" 6292 " ccccc) {\n" 6293 "}"); 6294 verifyFormat("if () {\n" 6295 "} else if constexpr (aaaaa && bbbbb > // break\n" 6296 " ccccc) {\n" 6297 "}"); 6298 verifyFormat("if () {\n" 6299 "} else if CONSTEXPR (aaaaa && bbbbb > // break\n" 6300 " ccccc) {\n" 6301 "}"); 6302 verifyFormat("if () {\n" 6303 "} else if (aaaaa &&\n" 6304 " bbbbb > // break\n" 6305 " ccccc &&\n" 6306 " ddddd) {\n" 6307 "}"); 6308 6309 // Presence of a trailing comment used to change indentation of b. 6310 verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n" 6311 " b;\n" 6312 "return aaaaaaaaaaaaaaaaaaa +\n" 6313 " b; //", 6314 getLLVMStyleWithColumns(30)); 6315 } 6316 6317 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) { 6318 // Not sure what the best system is here. Like this, the LHS can be found 6319 // immediately above an operator (everything with the same or a higher 6320 // indent). The RHS is aligned right of the operator and so compasses 6321 // everything until something with the same indent as the operator is found. 6322 // FIXME: Is this a good system? 6323 FormatStyle Style = getLLVMStyle(); 6324 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 6325 verifyFormat( 6326 "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6327 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6328 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6329 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6330 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6331 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6332 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6333 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6334 " > ccccccccccccccccccccccccccccccccccccccccc;", 6335 Style); 6336 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6337 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6338 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6339 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6340 Style); 6341 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6342 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6343 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6344 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6345 Style); 6346 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6347 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6348 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6349 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6350 Style); 6351 verifyFormat("if () {\n" 6352 "} else if (aaaaa\n" 6353 " && bbbbb // break\n" 6354 " > ccccc) {\n" 6355 "}", 6356 Style); 6357 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6358 " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6359 Style); 6360 verifyFormat("return (a)\n" 6361 " // comment\n" 6362 " + b;", 6363 Style); 6364 verifyFormat( 6365 "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6366 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6367 " + cc;", 6368 Style); 6369 6370 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6371 " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 6372 Style); 6373 6374 // Forced by comments. 6375 verifyFormat( 6376 "unsigned ContentSize =\n" 6377 " sizeof(int16_t) // DWARF ARange version number\n" 6378 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6379 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6380 " + sizeof(int8_t); // Segment Size (in bytes)"); 6381 6382 verifyFormat("return boost::fusion::at_c<0>(iiii).second\n" 6383 " == boost::fusion::at_c<1>(iiii).second;", 6384 Style); 6385 6386 Style.ColumnLimit = 60; 6387 verifyFormat("zzzzzzzzzz\n" 6388 " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6389 " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);", 6390 Style); 6391 6392 Style.ColumnLimit = 80; 6393 Style.IndentWidth = 4; 6394 Style.TabWidth = 4; 6395 Style.UseTab = FormatStyle::UT_Always; 6396 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6397 Style.AlignOperands = FormatStyle::OAS_DontAlign; 6398 EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n" 6399 "\t&& (someOtherLongishConditionPart1\n" 6400 "\t\t|| someOtherEvenLongerNestedConditionPart2);", 6401 format("return someVeryVeryLongConditionThatBarelyFitsOnALine && " 6402 "(someOtherLongishConditionPart1 || " 6403 "someOtherEvenLongerNestedConditionPart2);", 6404 Style)); 6405 } 6406 6407 TEST_F(FormatTest, ExpressionIndentationStrictAlign) { 6408 FormatStyle Style = getLLVMStyle(); 6409 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 6410 Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator; 6411 6412 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6413 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6414 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6415 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6416 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6417 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6418 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6419 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6420 " > ccccccccccccccccccccccccccccccccccccccccc;", 6421 Style); 6422 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6423 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6424 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6425 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6426 Style); 6427 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6428 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6429 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6430 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6431 Style); 6432 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6433 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6434 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6435 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6436 Style); 6437 verifyFormat("if () {\n" 6438 "} else if (aaaaa\n" 6439 " && bbbbb // break\n" 6440 " > ccccc) {\n" 6441 "}", 6442 Style); 6443 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6444 " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6445 Style); 6446 verifyFormat("return (a)\n" 6447 " // comment\n" 6448 " + b;", 6449 Style); 6450 verifyFormat( 6451 "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6452 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6453 " + cc;", 6454 Style); 6455 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 6456 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 6457 " : 3333333333333333;", 6458 Style); 6459 verifyFormat( 6460 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 6461 " : ccccccccccccccc ? dddddddddddddddddd\n" 6462 " : eeeeeeeeeeeeeeeeee)\n" 6463 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 6464 " : 3333333333333333;", 6465 Style); 6466 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6467 " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 6468 Style); 6469 6470 verifyFormat("return boost::fusion::at_c<0>(iiii).second\n" 6471 " == boost::fusion::at_c<1>(iiii).second;", 6472 Style); 6473 6474 Style.ColumnLimit = 60; 6475 verifyFormat("zzzzzzzzzzzzz\n" 6476 " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6477 " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);", 6478 Style); 6479 6480 // Forced by comments. 6481 Style.ColumnLimit = 80; 6482 verifyFormat( 6483 "unsigned ContentSize\n" 6484 " = sizeof(int16_t) // DWARF ARange version number\n" 6485 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6486 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6487 " + sizeof(int8_t); // Segment Size (in bytes)", 6488 Style); 6489 6490 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6491 verifyFormat( 6492 "unsigned ContentSize =\n" 6493 " sizeof(int16_t) // DWARF ARange version number\n" 6494 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6495 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6496 " + sizeof(int8_t); // Segment Size (in bytes)", 6497 Style); 6498 6499 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 6500 verifyFormat( 6501 "unsigned ContentSize =\n" 6502 " sizeof(int16_t) // DWARF ARange version number\n" 6503 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6504 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6505 " + sizeof(int8_t); // Segment Size (in bytes)", 6506 Style); 6507 } 6508 6509 TEST_F(FormatTest, EnforcedOperatorWraps) { 6510 // Here we'd like to wrap after the || operators, but a comment is forcing an 6511 // earlier wrap. 6512 verifyFormat("bool x = aaaaa //\n" 6513 " || bbbbb\n" 6514 " //\n" 6515 " || cccc;"); 6516 } 6517 6518 TEST_F(FormatTest, NoOperandAlignment) { 6519 FormatStyle Style = getLLVMStyle(); 6520 Style.AlignOperands = FormatStyle::OAS_DontAlign; 6521 verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n" 6522 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6523 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 6524 Style); 6525 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6526 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6527 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6528 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6529 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6530 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6531 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6532 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6533 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6534 " > ccccccccccccccccccccccccccccccccccccccccc;", 6535 Style); 6536 6537 verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6538 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6539 " + cc;", 6540 Style); 6541 verifyFormat("int a = aa\n" 6542 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6543 " * cccccccccccccccccccccccccccccccccccc;\n", 6544 Style); 6545 6546 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6547 verifyFormat("return (a > b\n" 6548 " // comment1\n" 6549 " // comment2\n" 6550 " || c);", 6551 Style); 6552 } 6553 6554 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) { 6555 FormatStyle Style = getLLVMStyle(); 6556 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6557 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 6558 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6559 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6560 Style); 6561 } 6562 6563 TEST_F(FormatTest, AllowBinPackingInsideArguments) { 6564 FormatStyle Style = getLLVMStyleWithColumns(40); 6565 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6566 Style.BinPackArguments = false; 6567 verifyFormat("void test() {\n" 6568 " someFunction(\n" 6569 " this + argument + is + quite\n" 6570 " + long + so + it + gets + wrapped\n" 6571 " + but + remains + bin - packed);\n" 6572 "}", 6573 Style); 6574 verifyFormat("void test() {\n" 6575 " someFunction(arg1,\n" 6576 " this + argument + is\n" 6577 " + quite + long + so\n" 6578 " + it + gets + wrapped\n" 6579 " + but + remains + bin\n" 6580 " - packed,\n" 6581 " arg3);\n" 6582 "}", 6583 Style); 6584 verifyFormat("void test() {\n" 6585 " someFunction(\n" 6586 " arg1,\n" 6587 " this + argument + has\n" 6588 " + anotherFunc(nested,\n" 6589 " calls + whose\n" 6590 " + arguments\n" 6591 " + are + also\n" 6592 " + wrapped,\n" 6593 " in + addition)\n" 6594 " + to + being + bin - packed,\n" 6595 " arg3);\n" 6596 "}", 6597 Style); 6598 6599 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 6600 verifyFormat("void test() {\n" 6601 " someFunction(\n" 6602 " arg1,\n" 6603 " this + argument + has +\n" 6604 " anotherFunc(nested,\n" 6605 " calls + whose +\n" 6606 " arguments +\n" 6607 " are + also +\n" 6608 " wrapped,\n" 6609 " in + addition) +\n" 6610 " to + being + bin - packed,\n" 6611 " arg3);\n" 6612 "}", 6613 Style); 6614 } 6615 6616 TEST_F(FormatTest, BreakBinaryOperatorsInPresenceOfTemplates) { 6617 auto Style = getLLVMStyleWithColumns(45); 6618 EXPECT_EQ(Style.BreakBeforeBinaryOperators, FormatStyle::BOS_None); 6619 verifyFormat("bool b =\n" 6620 " is_default_constructible_v<hash<T>> and\n" 6621 " is_copy_constructible_v<hash<T>> and\n" 6622 " is_move_constructible_v<hash<T>> and\n" 6623 " is_copy_assignable_v<hash<T>> and\n" 6624 " is_move_assignable_v<hash<T>> and\n" 6625 " is_destructible_v<hash<T>> and\n" 6626 " is_swappable_v<hash<T>> and\n" 6627 " is_callable_v<hash<T>(T)>;", 6628 Style); 6629 6630 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6631 verifyFormat("bool b = is_default_constructible_v<hash<T>>\n" 6632 " and is_copy_constructible_v<hash<T>>\n" 6633 " and is_move_constructible_v<hash<T>>\n" 6634 " and is_copy_assignable_v<hash<T>>\n" 6635 " and is_move_assignable_v<hash<T>>\n" 6636 " and is_destructible_v<hash<T>>\n" 6637 " and is_swappable_v<hash<T>>\n" 6638 " and is_callable_v<hash<T>(T)>;", 6639 Style); 6640 6641 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 6642 verifyFormat("bool b = is_default_constructible_v<hash<T>>\n" 6643 " and is_copy_constructible_v<hash<T>>\n" 6644 " and is_move_constructible_v<hash<T>>\n" 6645 " and is_copy_assignable_v<hash<T>>\n" 6646 " and is_move_assignable_v<hash<T>>\n" 6647 " and is_destructible_v<hash<T>>\n" 6648 " and is_swappable_v<hash<T>>\n" 6649 " and is_callable_v<hash<T>(T)>;", 6650 Style); 6651 } 6652 6653 TEST_F(FormatTest, ConstructorInitializers) { 6654 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}"); 6655 verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}", 6656 getLLVMStyleWithColumns(45)); 6657 verifyFormat("Constructor()\n" 6658 " : Inttializer(FitsOnTheLine) {}", 6659 getLLVMStyleWithColumns(44)); 6660 verifyFormat("Constructor()\n" 6661 " : Inttializer(FitsOnTheLine) {}", 6662 getLLVMStyleWithColumns(43)); 6663 6664 verifyFormat("template <typename T>\n" 6665 "Constructor() : Initializer(FitsOnTheLine) {}", 6666 getLLVMStyleWithColumns(45)); 6667 6668 verifyFormat( 6669 "SomeClass::Constructor()\n" 6670 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}"); 6671 6672 verifyFormat( 6673 "SomeClass::Constructor()\n" 6674 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6675 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}"); 6676 verifyFormat( 6677 "SomeClass::Constructor()\n" 6678 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6679 " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}"); 6680 verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6681 " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 6682 " : aaaaaaaaaa(aaaaaa) {}"); 6683 6684 verifyFormat("Constructor()\n" 6685 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6686 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6687 " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6688 " aaaaaaaaaaaaaaaaaaaaaaa() {}"); 6689 6690 verifyFormat("Constructor()\n" 6691 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6692 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 6693 6694 verifyFormat("Constructor(int Parameter = 0)\n" 6695 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n" 6696 " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}"); 6697 verifyFormat("Constructor()\n" 6698 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n" 6699 "}", 6700 getLLVMStyleWithColumns(60)); 6701 verifyFormat("Constructor()\n" 6702 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6703 " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}"); 6704 6705 // Here a line could be saved by splitting the second initializer onto two 6706 // lines, but that is not desirable. 6707 verifyFormat("Constructor()\n" 6708 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n" 6709 " aaaaaaaaaaa(aaaaaaaaaaa),\n" 6710 " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 6711 6712 FormatStyle OnePerLine = getLLVMStyle(); 6713 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_Never; 6714 verifyFormat("MyClass::MyClass()\n" 6715 " : a(a),\n" 6716 " b(b),\n" 6717 " c(c) {}", 6718 OnePerLine); 6719 verifyFormat("MyClass::MyClass()\n" 6720 " : a(a), // comment\n" 6721 " b(b),\n" 6722 " c(c) {}", 6723 OnePerLine); 6724 verifyFormat("MyClass::MyClass(int a)\n" 6725 " : b(a), // comment\n" 6726 " c(a + 1) { // lined up\n" 6727 "}", 6728 OnePerLine); 6729 verifyFormat("Constructor()\n" 6730 " : a(b, b, b) {}", 6731 OnePerLine); 6732 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6733 OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false; 6734 verifyFormat("SomeClass::Constructor()\n" 6735 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6736 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6737 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6738 OnePerLine); 6739 verifyFormat("SomeClass::Constructor()\n" 6740 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n" 6741 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6742 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6743 OnePerLine); 6744 verifyFormat("MyClass::MyClass(int var)\n" 6745 " : some_var_(var), // 4 space indent\n" 6746 " some_other_var_(var + 1) { // lined up\n" 6747 "}", 6748 OnePerLine); 6749 verifyFormat("Constructor()\n" 6750 " : aaaaa(aaaaaa),\n" 6751 " aaaaa(aaaaaa),\n" 6752 " aaaaa(aaaaaa),\n" 6753 " aaaaa(aaaaaa),\n" 6754 " aaaaa(aaaaaa) {}", 6755 OnePerLine); 6756 verifyFormat("Constructor()\n" 6757 " : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n" 6758 " aaaaaaaaaaaaaaaaaaaaaa) {}", 6759 OnePerLine); 6760 OnePerLine.BinPackParameters = false; 6761 verifyFormat( 6762 "Constructor()\n" 6763 " : aaaaaaaaaaaaaaaaaaaaaaaa(\n" 6764 " aaaaaaaaaaa().aaa(),\n" 6765 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6766 OnePerLine); 6767 OnePerLine.ColumnLimit = 60; 6768 verifyFormat("Constructor()\n" 6769 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6770 " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}", 6771 OnePerLine); 6772 6773 EXPECT_EQ("Constructor()\n" 6774 " : // Comment forcing unwanted break.\n" 6775 " aaaa(aaaa) {}", 6776 format("Constructor() :\n" 6777 " // Comment forcing unwanted break.\n" 6778 " aaaa(aaaa) {}")); 6779 } 6780 6781 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) { 6782 FormatStyle Style = getLLVMStyleWithColumns(60); 6783 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6784 Style.BinPackParameters = false; 6785 6786 for (int i = 0; i < 4; ++i) { 6787 // Test all combinations of parameters that should not have an effect. 6788 Style.AllowAllParametersOfDeclarationOnNextLine = i & 1; 6789 Style.AllowAllArgumentsOnNextLine = i & 2; 6790 6791 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6792 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6793 verifyFormat("Constructor()\n" 6794 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6795 Style); 6796 verifyFormat("Constructor() : a(a), b(b) {}", Style); 6797 6798 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6799 verifyFormat("Constructor()\n" 6800 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6801 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6802 Style); 6803 verifyFormat("Constructor() : a(a), b(b) {}", Style); 6804 6805 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 6806 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6807 verifyFormat("Constructor()\n" 6808 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6809 Style); 6810 6811 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6812 verifyFormat("Constructor()\n" 6813 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6814 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6815 Style); 6816 6817 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6818 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6819 verifyFormat("Constructor() :\n" 6820 " aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6821 Style); 6822 6823 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6824 verifyFormat("Constructor() :\n" 6825 " aaaaaaaaaaaaaaaaaa(a),\n" 6826 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6827 Style); 6828 } 6829 6830 // Test interactions between AllowAllParametersOfDeclarationOnNextLine and 6831 // AllowAllConstructorInitializersOnNextLine in all 6832 // BreakConstructorInitializers modes 6833 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6834 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6835 verifyFormat("SomeClassWithALongName::Constructor(\n" 6836 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n" 6837 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6838 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6839 Style); 6840 6841 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6842 verifyFormat("SomeClassWithALongName::Constructor(\n" 6843 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6844 " int bbbbbbbbbbbbb,\n" 6845 " int cccccccccccccccc)\n" 6846 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6847 Style); 6848 6849 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6850 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6851 verifyFormat("SomeClassWithALongName::Constructor(\n" 6852 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6853 " int bbbbbbbbbbbbb)\n" 6854 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6855 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6856 Style); 6857 6858 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 6859 6860 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6861 verifyFormat("SomeClassWithALongName::Constructor(\n" 6862 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n" 6863 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6864 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6865 Style); 6866 6867 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6868 verifyFormat("SomeClassWithALongName::Constructor(\n" 6869 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6870 " int bbbbbbbbbbbbb,\n" 6871 " int cccccccccccccccc)\n" 6872 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6873 Style); 6874 6875 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6876 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6877 verifyFormat("SomeClassWithALongName::Constructor(\n" 6878 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6879 " int bbbbbbbbbbbbb)\n" 6880 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6881 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6882 Style); 6883 6884 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6885 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6886 verifyFormat("SomeClassWithALongName::Constructor(\n" 6887 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n" 6888 " aaaaaaaaaaaaaaaaaaaa(a),\n" 6889 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6890 Style); 6891 6892 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6893 verifyFormat("SomeClassWithALongName::Constructor(\n" 6894 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6895 " int bbbbbbbbbbbbb,\n" 6896 " int cccccccccccccccc) :\n" 6897 " aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6898 Style); 6899 6900 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6901 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6902 verifyFormat("SomeClassWithALongName::Constructor(\n" 6903 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6904 " int bbbbbbbbbbbbb) :\n" 6905 " aaaaaaaaaaaaaaaaaaaa(a),\n" 6906 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6907 Style); 6908 } 6909 6910 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) { 6911 FormatStyle Style = getLLVMStyleWithColumns(60); 6912 Style.BinPackArguments = false; 6913 for (int i = 0; i < 4; ++i) { 6914 // Test all combinations of parameters that should not have an effect. 6915 Style.AllowAllParametersOfDeclarationOnNextLine = i & 1; 6916 Style.PackConstructorInitializers = 6917 i & 2 ? FormatStyle::PCIS_BinPack : FormatStyle::PCIS_Never; 6918 6919 Style.AllowAllArgumentsOnNextLine = true; 6920 verifyFormat("void foo() {\n" 6921 " FunctionCallWithReallyLongName(\n" 6922 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n" 6923 "}", 6924 Style); 6925 Style.AllowAllArgumentsOnNextLine = false; 6926 verifyFormat("void foo() {\n" 6927 " FunctionCallWithReallyLongName(\n" 6928 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6929 " bbbbbbbbbbbb);\n" 6930 "}", 6931 Style); 6932 6933 Style.AllowAllArgumentsOnNextLine = true; 6934 verifyFormat("void foo() {\n" 6935 " auto VariableWithReallyLongName = {\n" 6936 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n" 6937 "}", 6938 Style); 6939 Style.AllowAllArgumentsOnNextLine = false; 6940 verifyFormat("void foo() {\n" 6941 " auto VariableWithReallyLongName = {\n" 6942 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6943 " bbbbbbbbbbbb};\n" 6944 "}", 6945 Style); 6946 } 6947 6948 // This parameter should not affect declarations. 6949 Style.BinPackParameters = false; 6950 Style.AllowAllArgumentsOnNextLine = false; 6951 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6952 verifyFormat("void FunctionCallWithReallyLongName(\n" 6953 " int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);", 6954 Style); 6955 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6956 verifyFormat("void FunctionCallWithReallyLongName(\n" 6957 " int aaaaaaaaaaaaaaaaaaaaaaa,\n" 6958 " int bbbbbbbbbbbb);", 6959 Style); 6960 } 6961 6962 TEST_F(FormatTest, AllowAllArgumentsOnNextLineDontAlign) { 6963 // Check that AllowAllArgumentsOnNextLine is respected for both BAS_DontAlign 6964 // and BAS_Align. 6965 FormatStyle Style = getLLVMStyleWithColumns(35); 6966 StringRef Input = "functionCall(paramA, paramB, paramC);\n" 6967 "void functionDecl(int A, int B, int C);"; 6968 Style.AllowAllArgumentsOnNextLine = false; 6969 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6970 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6971 " paramC);\n" 6972 "void functionDecl(int A, int B,\n" 6973 " int C);"), 6974 format(Input, Style)); 6975 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 6976 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6977 " paramC);\n" 6978 "void functionDecl(int A, int B,\n" 6979 " int C);"), 6980 format(Input, Style)); 6981 // However, BAS_AlwaysBreak should take precedence over 6982 // AllowAllArgumentsOnNextLine. 6983 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 6984 EXPECT_EQ(StringRef("functionCall(\n" 6985 " paramA, paramB, paramC);\n" 6986 "void functionDecl(\n" 6987 " int A, int B, int C);"), 6988 format(Input, Style)); 6989 6990 // When AllowAllArgumentsOnNextLine is set, we prefer breaking before the 6991 // first argument. 6992 Style.AllowAllArgumentsOnNextLine = true; 6993 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 6994 EXPECT_EQ(StringRef("functionCall(\n" 6995 " paramA, paramB, paramC);\n" 6996 "void functionDecl(\n" 6997 " int A, int B, int C);"), 6998 format(Input, Style)); 6999 // It wouldn't fit on one line with aligned parameters so this setting 7000 // doesn't change anything for BAS_Align. 7001 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 7002 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 7003 " paramC);\n" 7004 "void functionDecl(int A, int B,\n" 7005 " int C);"), 7006 format(Input, Style)); 7007 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 7008 EXPECT_EQ(StringRef("functionCall(\n" 7009 " paramA, paramB, paramC);\n" 7010 "void functionDecl(\n" 7011 " int A, int B, int C);"), 7012 format(Input, Style)); 7013 } 7014 7015 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) { 7016 FormatStyle Style = getLLVMStyle(); 7017 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 7018 7019 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}"); 7020 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}", 7021 getStyleWithColumns(Style, 45)); 7022 verifyFormat("Constructor() :\n" 7023 " Initializer(FitsOnTheLine) {}", 7024 getStyleWithColumns(Style, 44)); 7025 verifyFormat("Constructor() :\n" 7026 " Initializer(FitsOnTheLine) {}", 7027 getStyleWithColumns(Style, 43)); 7028 7029 verifyFormat("template <typename T>\n" 7030 "Constructor() : Initializer(FitsOnTheLine) {}", 7031 getStyleWithColumns(Style, 50)); 7032 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 7033 verifyFormat( 7034 "SomeClass::Constructor() :\n" 7035 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 7036 Style); 7037 7038 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 7039 verifyFormat( 7040 "SomeClass::Constructor() :\n" 7041 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 7042 Style); 7043 7044 verifyFormat( 7045 "SomeClass::Constructor() :\n" 7046 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 7047 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 7048 Style); 7049 verifyFormat( 7050 "SomeClass::Constructor() :\n" 7051 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7052 " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 7053 Style); 7054 verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7055 " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 7056 " aaaaaaaaaa(aaaaaa) {}", 7057 Style); 7058 7059 verifyFormat("Constructor() :\n" 7060 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7061 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7062 " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7063 " aaaaaaaaaaaaaaaaaaaaaaa() {}", 7064 Style); 7065 7066 verifyFormat("Constructor() :\n" 7067 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7068 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7069 Style); 7070 7071 verifyFormat("Constructor(int Parameter = 0) :\n" 7072 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n" 7073 " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}", 7074 Style); 7075 verifyFormat("Constructor() :\n" 7076 " aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n" 7077 "}", 7078 getStyleWithColumns(Style, 60)); 7079 verifyFormat("Constructor() :\n" 7080 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7081 " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}", 7082 Style); 7083 7084 // Here a line could be saved by splitting the second initializer onto two 7085 // lines, but that is not desirable. 7086 verifyFormat("Constructor() :\n" 7087 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n" 7088 " aaaaaaaaaaa(aaaaaaaaaaa),\n" 7089 " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7090 Style); 7091 7092 FormatStyle OnePerLine = Style; 7093 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 7094 verifyFormat("SomeClass::Constructor() :\n" 7095 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 7096 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 7097 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 7098 OnePerLine); 7099 verifyFormat("SomeClass::Constructor() :\n" 7100 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n" 7101 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 7102 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 7103 OnePerLine); 7104 verifyFormat("MyClass::MyClass(int var) :\n" 7105 " some_var_(var), // 4 space indent\n" 7106 " some_other_var_(var + 1) { // lined up\n" 7107 "}", 7108 OnePerLine); 7109 verifyFormat("Constructor() :\n" 7110 " aaaaa(aaaaaa),\n" 7111 " aaaaa(aaaaaa),\n" 7112 " aaaaa(aaaaaa),\n" 7113 " aaaaa(aaaaaa),\n" 7114 " aaaaa(aaaaaa) {}", 7115 OnePerLine); 7116 verifyFormat("Constructor() :\n" 7117 " aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n" 7118 " aaaaaaaaaaaaaaaaaaaaaa) {}", 7119 OnePerLine); 7120 OnePerLine.BinPackParameters = false; 7121 verifyFormat("Constructor() :\n" 7122 " aaaaaaaaaaaaaaaaaaaaaaaa(\n" 7123 " aaaaaaaaaaa().aaa(),\n" 7124 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7125 OnePerLine); 7126 OnePerLine.ColumnLimit = 60; 7127 verifyFormat("Constructor() :\n" 7128 " aaaaaaaaaaaaaaaaaaaa(a),\n" 7129 " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}", 7130 OnePerLine); 7131 7132 EXPECT_EQ("Constructor() :\n" 7133 " // Comment forcing unwanted break.\n" 7134 " aaaa(aaaa) {}", 7135 format("Constructor() :\n" 7136 " // Comment forcing unwanted break.\n" 7137 " aaaa(aaaa) {}", 7138 Style)); 7139 7140 Style.ColumnLimit = 0; 7141 verifyFormat("SomeClass::Constructor() :\n" 7142 " a(a) {}", 7143 Style); 7144 verifyFormat("SomeClass::Constructor() noexcept :\n" 7145 " a(a) {}", 7146 Style); 7147 verifyFormat("SomeClass::Constructor() :\n" 7148 " a(a), b(b), c(c) {}", 7149 Style); 7150 verifyFormat("SomeClass::Constructor() :\n" 7151 " a(a) {\n" 7152 " foo();\n" 7153 " bar();\n" 7154 "}", 7155 Style); 7156 7157 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 7158 verifyFormat("SomeClass::Constructor() :\n" 7159 " a(a), b(b), c(c) {\n" 7160 "}", 7161 Style); 7162 verifyFormat("SomeClass::Constructor() :\n" 7163 " a(a) {\n" 7164 "}", 7165 Style); 7166 7167 Style.ColumnLimit = 80; 7168 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 7169 Style.ConstructorInitializerIndentWidth = 2; 7170 verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style); 7171 verifyFormat("SomeClass::Constructor() :\n" 7172 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7173 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}", 7174 Style); 7175 7176 // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as 7177 // well 7178 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 7179 verifyFormat( 7180 "class SomeClass\n" 7181 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7182 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7183 Style); 7184 Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma; 7185 verifyFormat( 7186 "class SomeClass\n" 7187 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7188 " , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7189 Style); 7190 Style.BreakInheritanceList = FormatStyle::BILS_AfterColon; 7191 verifyFormat( 7192 "class SomeClass :\n" 7193 " public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7194 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7195 Style); 7196 Style.BreakInheritanceList = FormatStyle::BILS_AfterComma; 7197 verifyFormat( 7198 "class SomeClass\n" 7199 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7200 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7201 Style); 7202 } 7203 7204 #ifndef EXPENSIVE_CHECKS 7205 // Expensive checks enables libstdc++ checking which includes validating the 7206 // state of ranges used in std::priority_queue - this blows out the 7207 // runtime/scalability of the function and makes this test unacceptably slow. 7208 TEST_F(FormatTest, MemoizationTests) { 7209 // This breaks if the memoization lookup does not take \c Indent and 7210 // \c LastSpace into account. 7211 verifyFormat( 7212 "extern CFRunLoopTimerRef\n" 7213 "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n" 7214 " CFTimeInterval interval, CFOptionFlags flags,\n" 7215 " CFIndex order, CFRunLoopTimerCallBack callout,\n" 7216 " CFRunLoopTimerContext *context) {}"); 7217 7218 // Deep nesting somewhat works around our memoization. 7219 verifyFormat( 7220 "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7221 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7222 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7223 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7224 " aaaaa())))))))))))))))))))))))))))))))))))))));", 7225 getLLVMStyleWithColumns(65)); 7226 verifyFormat( 7227 "aaaaa(\n" 7228 " aaaaa,\n" 7229 " aaaaa(\n" 7230 " aaaaa,\n" 7231 " aaaaa(\n" 7232 " aaaaa,\n" 7233 " aaaaa(\n" 7234 " aaaaa,\n" 7235 " aaaaa(\n" 7236 " aaaaa,\n" 7237 " aaaaa(\n" 7238 " aaaaa,\n" 7239 " aaaaa(\n" 7240 " aaaaa,\n" 7241 " aaaaa(\n" 7242 " aaaaa,\n" 7243 " aaaaa(\n" 7244 " aaaaa,\n" 7245 " aaaaa(\n" 7246 " aaaaa,\n" 7247 " aaaaa(\n" 7248 " aaaaa,\n" 7249 " aaaaa(\n" 7250 " aaaaa,\n" 7251 " aaaaa))))))))))));", 7252 getLLVMStyleWithColumns(65)); 7253 verifyFormat( 7254 "a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(), a), a), a), a),\n" 7255 " a),\n" 7256 " a),\n" 7257 " a),\n" 7258 " a),\n" 7259 " a),\n" 7260 " a),\n" 7261 " a),\n" 7262 " a),\n" 7263 " a),\n" 7264 " a),\n" 7265 " a),\n" 7266 " a),\n" 7267 " a),\n" 7268 " a),\n" 7269 " a),\n" 7270 " a),\n" 7271 " a)", 7272 getLLVMStyleWithColumns(65)); 7273 7274 // This test takes VERY long when memoization is broken. 7275 FormatStyle OnePerLine = getLLVMStyle(); 7276 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 7277 OnePerLine.BinPackParameters = false; 7278 std::string input = "Constructor()\n" 7279 " : aaaa(a,\n"; 7280 for (unsigned i = 0, e = 80; i != e; ++i) 7281 input += " a,\n"; 7282 input += " a) {}"; 7283 verifyFormat(input, OnePerLine); 7284 } 7285 #endif 7286 7287 TEST_F(FormatTest, BreaksAsHighAsPossible) { 7288 verifyFormat( 7289 "void f() {\n" 7290 " if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n" 7291 " (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n" 7292 " f();\n" 7293 "}"); 7294 verifyFormat("if (Intervals[i].getRange().getFirst() <\n" 7295 " Intervals[i - 1].getRange().getLast()) {\n}"); 7296 } 7297 7298 TEST_F(FormatTest, BreaksFunctionDeclarations) { 7299 // Principially, we break function declarations in a certain order: 7300 // 1) break amongst arguments. 7301 verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n" 7302 " Cccccccccccccc cccccccccccccc);"); 7303 verifyFormat("template <class TemplateIt>\n" 7304 "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n" 7305 " TemplateIt *stop) {}"); 7306 7307 // 2) break after return type. 7308 verifyFormat( 7309 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7310 "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);", 7311 getGoogleStyle()); 7312 7313 // 3) break after (. 7314 verifyFormat( 7315 "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n" 7316 " Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);", 7317 getGoogleStyle()); 7318 7319 // 4) break before after nested name specifiers. 7320 verifyFormat( 7321 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7322 "SomeClasssssssssssssssssssssssssssssssssssssss::\n" 7323 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);", 7324 getGoogleStyle()); 7325 7326 // However, there are exceptions, if a sufficient amount of lines can be 7327 // saved. 7328 // FIXME: The precise cut-offs wrt. the number of saved lines might need some 7329 // more adjusting. 7330 verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n" 7331 " Cccccccccccccc cccccccccc,\n" 7332 " Cccccccccccccc cccccccccc,\n" 7333 " Cccccccccccccc cccccccccc,\n" 7334 " Cccccccccccccc cccccccccc);"); 7335 verifyFormat( 7336 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7337 "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7338 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7339 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);", 7340 getGoogleStyle()); 7341 verifyFormat( 7342 "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n" 7343 " Cccccccccccccc cccccccccc,\n" 7344 " Cccccccccccccc cccccccccc,\n" 7345 " Cccccccccccccc cccccccccc,\n" 7346 " Cccccccccccccc cccccccccc,\n" 7347 " Cccccccccccccc cccccccccc,\n" 7348 " Cccccccccccccc cccccccccc);"); 7349 verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7350 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7351 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7352 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7353 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);"); 7354 7355 // Break after multi-line parameters. 7356 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7357 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7358 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7359 " bbbb bbbb);"); 7360 verifyFormat("void SomeLoooooooooooongFunction(\n" 7361 " std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n" 7362 " aaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7363 " int bbbbbbbbbbbbb);"); 7364 7365 // Treat overloaded operators like other functions. 7366 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 7367 "operator>(const SomeLoooooooooooooooooooooooooogType &other);"); 7368 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 7369 "operator>>(const SomeLooooooooooooooooooooooooogType &other);"); 7370 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 7371 "operator<<(const SomeLooooooooooooooooooooooooogType &other);"); 7372 verifyGoogleFormat( 7373 "SomeLoooooooooooooooooooooooooooooogType operator>>(\n" 7374 " const SomeLooooooooogType &a, const SomeLooooooooogType &b);"); 7375 verifyGoogleFormat( 7376 "SomeLoooooooooooooooooooooooooooooogType operator<<(\n" 7377 " const SomeLooooooooogType &a, const SomeLooooooooogType &b);"); 7378 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7379 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);"); 7380 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n" 7381 "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);"); 7382 verifyGoogleFormat( 7383 "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n" 7384 "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7385 " bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}"); 7386 verifyGoogleFormat("template <typename T>\n" 7387 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7388 "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n" 7389 " aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);"); 7390 7391 FormatStyle Style = getLLVMStyle(); 7392 Style.PointerAlignment = FormatStyle::PAS_Left; 7393 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7394 " aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}", 7395 Style); 7396 verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n" 7397 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7398 Style); 7399 } 7400 7401 TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) { 7402 // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516: 7403 // Prefer keeping `::` followed by `operator` together. 7404 EXPECT_EQ("const aaaa::bbbbbbb &\n" 7405 "ccccccccc::operator++() {\n" 7406 " stuff();\n" 7407 "}", 7408 format("const aaaa::bbbbbbb\n" 7409 "&ccccccccc::operator++() { stuff(); }", 7410 getLLVMStyleWithColumns(40))); 7411 } 7412 7413 TEST_F(FormatTest, TrailingReturnType) { 7414 verifyFormat("auto foo() -> int;\n"); 7415 // correct trailing return type spacing 7416 verifyFormat("auto operator->() -> int;\n"); 7417 verifyFormat("auto operator++(int) -> int;\n"); 7418 7419 verifyFormat("struct S {\n" 7420 " auto bar() const -> int;\n" 7421 "};"); 7422 verifyFormat("template <size_t Order, typename T>\n" 7423 "auto load_img(const std::string &filename)\n" 7424 " -> alias::tensor<Order, T, mem::tag::cpu> {}"); 7425 verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n" 7426 " -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}"); 7427 verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}"); 7428 verifyFormat("template <typename T>\n" 7429 "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n" 7430 " -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());"); 7431 7432 // Not trailing return types. 7433 verifyFormat("void f() { auto a = b->c(); }"); 7434 verifyFormat("auto a = p->foo();"); 7435 verifyFormat("int a = p->foo();"); 7436 verifyFormat("auto lmbd = [] NOEXCEPT -> int { return 0; };"); 7437 } 7438 7439 TEST_F(FormatTest, DeductionGuides) { 7440 verifyFormat("template <class T> A(const T &, const T &) -> A<T &>;"); 7441 verifyFormat("template <class T> explicit A(T &, T &&) -> A<T>;"); 7442 verifyFormat("template <class... Ts> S(Ts...) -> S<Ts...>;"); 7443 verifyFormat( 7444 "template <class... T>\n" 7445 "array(T &&...t) -> array<std::common_type_t<T...>, sizeof...(T)>;"); 7446 verifyFormat("template <class T> A() -> A<decltype(p->foo<3>())>;"); 7447 verifyFormat("template <class T> A() -> A<decltype(foo<traits<1>>)>;"); 7448 verifyFormat("template <class T> A() -> A<sizeof(p->foo<1>)>;"); 7449 verifyFormat("template <class T> A() -> A<(3 < 2)>;"); 7450 verifyFormat("template <class T> A() -> A<((3) < (2))>;"); 7451 verifyFormat("template <class T> x() -> x<1>;"); 7452 verifyFormat("template <class T> explicit x(T &) -> x<1>;"); 7453 7454 // Ensure not deduction guides. 7455 verifyFormat("c()->f<int>();"); 7456 verifyFormat("x()->foo<1>;"); 7457 verifyFormat("x = p->foo<3>();"); 7458 verifyFormat("x()->x<1>();"); 7459 verifyFormat("x()->x<1>;"); 7460 } 7461 7462 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) { 7463 // Avoid breaking before trailing 'const' or other trailing annotations, if 7464 // they are not function-like. 7465 FormatStyle Style = getGoogleStyleWithColumns(47); 7466 verifyFormat("void someLongFunction(\n" 7467 " int someLoooooooooooooongParameter) const {\n}", 7468 getLLVMStyleWithColumns(47)); 7469 verifyFormat("LoooooongReturnType\n" 7470 "someLoooooooongFunction() const {}", 7471 getLLVMStyleWithColumns(47)); 7472 verifyFormat("LoooooongReturnType someLoooooooongFunction()\n" 7473 " const {}", 7474 Style); 7475 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7476 " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;"); 7477 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7478 " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;"); 7479 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7480 " aaaaa aaaaaaaaaaaaaaaaaaaa) override final;"); 7481 verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n" 7482 " aaaaaaaaaaa aaaaa) const override;"); 7483 verifyGoogleFormat( 7484 "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7485 " const override;"); 7486 7487 // Even if the first parameter has to be wrapped. 7488 verifyFormat("void someLongFunction(\n" 7489 " int someLongParameter) const {}", 7490 getLLVMStyleWithColumns(46)); 7491 verifyFormat("void someLongFunction(\n" 7492 " int someLongParameter) const {}", 7493 Style); 7494 verifyFormat("void someLongFunction(\n" 7495 " int someLongParameter) override {}", 7496 Style); 7497 verifyFormat("void someLongFunction(\n" 7498 " int someLongParameter) OVERRIDE {}", 7499 Style); 7500 verifyFormat("void someLongFunction(\n" 7501 " int someLongParameter) final {}", 7502 Style); 7503 verifyFormat("void someLongFunction(\n" 7504 " int someLongParameter) FINAL {}", 7505 Style); 7506 verifyFormat("void someLongFunction(\n" 7507 " int parameter) const override {}", 7508 Style); 7509 7510 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 7511 verifyFormat("void someLongFunction(\n" 7512 " int someLongParameter) const\n" 7513 "{\n" 7514 "}", 7515 Style); 7516 7517 Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 7518 verifyFormat("void someLongFunction(\n" 7519 " int someLongParameter) const\n" 7520 " {\n" 7521 " }", 7522 Style); 7523 7524 // Unless these are unknown annotations. 7525 verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n" 7526 " aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7527 " LONG_AND_UGLY_ANNOTATION;"); 7528 7529 // Breaking before function-like trailing annotations is fine to keep them 7530 // close to their arguments. 7531 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7532 " LOCKS_EXCLUDED(aaaaaaaaaaaaa);"); 7533 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n" 7534 " LOCKS_EXCLUDED(aaaaaaaaaaaaa);"); 7535 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n" 7536 " LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}"); 7537 verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n" 7538 " AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);"); 7539 verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});"); 7540 7541 verifyFormat( 7542 "void aaaaaaaaaaaaaaaaaa()\n" 7543 " __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n" 7544 " aaaaaaaaaaaaaaaaaaaaaaaaa));"); 7545 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7546 " __attribute__((unused));"); 7547 verifyGoogleFormat( 7548 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7549 " GUARDED_BY(aaaaaaaaaaaa);"); 7550 verifyGoogleFormat( 7551 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7552 " GUARDED_BY(aaaaaaaaaaaa);"); 7553 verifyGoogleFormat( 7554 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n" 7555 " aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7556 verifyGoogleFormat( 7557 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n" 7558 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7559 } 7560 7561 TEST_F(FormatTest, FunctionAnnotations) { 7562 verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7563 "int OldFunction(const string ¶meter) {}"); 7564 verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7565 "string OldFunction(const string ¶meter) {}"); 7566 verifyFormat("template <typename T>\n" 7567 "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7568 "string OldFunction(const string ¶meter) {}"); 7569 7570 // Not function annotations. 7571 verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7572 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"); 7573 verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n" 7574 " ThisIsATestWithAReallyReallyReallyReallyLongName) {}"); 7575 verifyFormat("MACRO(abc).function() // wrap\n" 7576 " << abc;"); 7577 verifyFormat("MACRO(abc)->function() // wrap\n" 7578 " << abc;"); 7579 verifyFormat("MACRO(abc)::function() // wrap\n" 7580 " << abc;"); 7581 } 7582 7583 TEST_F(FormatTest, BreaksDesireably) { 7584 verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n" 7585 " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n" 7586 " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}"); 7587 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7588 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 7589 "}"); 7590 7591 verifyFormat( 7592 "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7593 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 7594 7595 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7596 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7597 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7598 7599 verifyFormat( 7600 "aaaaaaaa(aaaaaaaaaaaaa,\n" 7601 " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7602 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n" 7603 " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7604 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));"); 7605 7606 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 7607 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7608 7609 verifyFormat( 7610 "void f() {\n" 7611 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n" 7612 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 7613 "}"); 7614 verifyFormat( 7615 "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7616 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7617 verifyFormat( 7618 "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7619 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7620 verifyFormat( 7621 "aaaaaa(aaa,\n" 7622 " new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7623 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7624 " aaaa);"); 7625 verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7626 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7627 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7628 7629 // Indent consistently independent of call expression and unary operator. 7630 verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7631 " dddddddddddddddddddddddddddddd));"); 7632 verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7633 " dddddddddddddddddddddddddddddd));"); 7634 verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n" 7635 " dddddddddddddddddddddddddddddd));"); 7636 7637 // This test case breaks on an incorrect memoization, i.e. an optimization not 7638 // taking into account the StopAt value. 7639 verifyFormat( 7640 "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7641 " aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7642 " aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7643 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7644 7645 verifyFormat("{\n {\n {\n" 7646 " Annotation.SpaceRequiredBefore =\n" 7647 " Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n" 7648 " Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n" 7649 " }\n }\n}"); 7650 7651 // Break on an outer level if there was a break on an inner level. 7652 EXPECT_EQ("f(g(h(a, // comment\n" 7653 " b, c),\n" 7654 " d, e),\n" 7655 " x, y);", 7656 format("f(g(h(a, // comment\n" 7657 " b, c), d, e), x, y);")); 7658 7659 // Prefer breaking similar line breaks. 7660 verifyFormat( 7661 "const int kTrackingOptions = NSTrackingMouseMoved |\n" 7662 " NSTrackingMouseEnteredAndExited |\n" 7663 " NSTrackingActiveAlways;"); 7664 } 7665 7666 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) { 7667 FormatStyle NoBinPacking = getGoogleStyle(); 7668 NoBinPacking.BinPackParameters = false; 7669 NoBinPacking.BinPackArguments = true; 7670 verifyFormat("void f() {\n" 7671 " f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n" 7672 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 7673 "}", 7674 NoBinPacking); 7675 verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n" 7676 " int aaaaaaaaaaaaaaaaaaaa,\n" 7677 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7678 NoBinPacking); 7679 7680 NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false; 7681 verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7682 " vector<int> bbbbbbbbbbbbbbb);", 7683 NoBinPacking); 7684 // FIXME: This behavior difference is probably not wanted. However, currently 7685 // we cannot distinguish BreakBeforeParameter being set because of the wrapped 7686 // template arguments from BreakBeforeParameter being set because of the 7687 // one-per-line formatting. 7688 verifyFormat( 7689 "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n" 7690 " aaaaaaaaaa> aaaaaaaaaa);", 7691 NoBinPacking); 7692 verifyFormat( 7693 "void fffffffffff(\n" 7694 " aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n" 7695 " aaaaaaaaaa);"); 7696 } 7697 7698 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) { 7699 FormatStyle NoBinPacking = getGoogleStyle(); 7700 NoBinPacking.BinPackParameters = false; 7701 NoBinPacking.BinPackArguments = false; 7702 verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n" 7703 " aaaaaaaaaaaaaaaaaaaa,\n" 7704 " aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);", 7705 NoBinPacking); 7706 verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n" 7707 " aaaaaaaaaaaaa,\n" 7708 " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));", 7709 NoBinPacking); 7710 verifyFormat( 7711 "aaaaaaaa(aaaaaaaaaaaaa,\n" 7712 " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7713 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n" 7714 " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7715 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));", 7716 NoBinPacking); 7717 verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n" 7718 " .aaaaaaaaaaaaaaaaaa();", 7719 NoBinPacking); 7720 verifyFormat("void f() {\n" 7721 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7722 " aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n" 7723 "}", 7724 NoBinPacking); 7725 7726 verifyFormat( 7727 "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7728 " aaaaaaaaaaaa,\n" 7729 " aaaaaaaaaaaa);", 7730 NoBinPacking); 7731 verifyFormat( 7732 "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n" 7733 " ddddddddddddddddddddddddddddd),\n" 7734 " test);", 7735 NoBinPacking); 7736 7737 verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n" 7738 " aaaaaaaaaaaaaaaaaaaaaaa,\n" 7739 " aaaaaaaaaaaaaaaaaaaaaaa>\n" 7740 " aaaaaaaaaaaaaaaaaa;", 7741 NoBinPacking); 7742 verifyFormat("a(\"a\"\n" 7743 " \"a\",\n" 7744 " a);"); 7745 7746 NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false; 7747 verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n" 7748 " aaaaaaaaa,\n" 7749 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7750 NoBinPacking); 7751 verifyFormat( 7752 "void f() {\n" 7753 " aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n" 7754 " .aaaaaaa();\n" 7755 "}", 7756 NoBinPacking); 7757 verifyFormat( 7758 "template <class SomeType, class SomeOtherType>\n" 7759 "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}", 7760 NoBinPacking); 7761 } 7762 7763 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) { 7764 FormatStyle Style = getLLVMStyleWithColumns(15); 7765 Style.ExperimentalAutoDetectBinPacking = true; 7766 EXPECT_EQ("aaa(aaaa,\n" 7767 " aaaa,\n" 7768 " aaaa);\n" 7769 "aaa(aaaa,\n" 7770 " aaaa,\n" 7771 " aaaa);", 7772 format("aaa(aaaa,\n" // one-per-line 7773 " aaaa,\n" 7774 " aaaa );\n" 7775 "aaa(aaaa, aaaa, aaaa);", // inconclusive 7776 Style)); 7777 EXPECT_EQ("aaa(aaaa, aaaa,\n" 7778 " aaaa);\n" 7779 "aaa(aaaa, aaaa,\n" 7780 " aaaa);", 7781 format("aaa(aaaa, aaaa,\n" // bin-packed 7782 " aaaa );\n" 7783 "aaa(aaaa, aaaa, aaaa);", // inconclusive 7784 Style)); 7785 } 7786 7787 TEST_F(FormatTest, FormatsBuilderPattern) { 7788 verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n" 7789 " .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n" 7790 " .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n" 7791 " .StartsWith(\".init\", ORDER_INIT)\n" 7792 " .StartsWith(\".fini\", ORDER_FINI)\n" 7793 " .StartsWith(\".hash\", ORDER_HASH)\n" 7794 " .Default(ORDER_TEXT);\n"); 7795 7796 verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n" 7797 " aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();"); 7798 verifyFormat("aaaaaaa->aaaaaaa\n" 7799 " ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7800 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7801 " ->aaaaaaaa(aaaaaaaaaaaaaaa);"); 7802 verifyFormat( 7803 "aaaaaaa->aaaaaaa\n" 7804 " ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7805 " ->aaaaaaaa(aaaaaaaaaaaaaaa);"); 7806 verifyFormat( 7807 "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n" 7808 " aaaaaaaaaaaaaa);"); 7809 verifyFormat( 7810 "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n" 7811 " aaaaaa->aaaaaaaaaaaa()\n" 7812 " ->aaaaaaaaaaaaaaaa(\n" 7813 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7814 " ->aaaaaaaaaaaaaaaaa();"); 7815 verifyGoogleFormat( 7816 "void f() {\n" 7817 " someo->Add((new util::filetools::Handler(dir))\n" 7818 " ->OnEvent1(NewPermanentCallback(\n" 7819 " this, &HandlerHolderClass::EventHandlerCBA))\n" 7820 " ->OnEvent2(NewPermanentCallback(\n" 7821 " this, &HandlerHolderClass::EventHandlerCBB))\n" 7822 " ->OnEvent3(NewPermanentCallback(\n" 7823 " this, &HandlerHolderClass::EventHandlerCBC))\n" 7824 " ->OnEvent5(NewPermanentCallback(\n" 7825 " this, &HandlerHolderClass::EventHandlerCBD))\n" 7826 " ->OnEvent6(NewPermanentCallback(\n" 7827 " this, &HandlerHolderClass::EventHandlerCBE)));\n" 7828 "}"); 7829 7830 verifyFormat( 7831 "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();"); 7832 verifyFormat("aaaaaaaaaaaaaaa()\n" 7833 " .aaaaaaaaaaaaaaa()\n" 7834 " .aaaaaaaaaaaaaaa()\n" 7835 " .aaaaaaaaaaaaaaa()\n" 7836 " .aaaaaaaaaaaaaaa();"); 7837 verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7838 " .aaaaaaaaaaaaaaa()\n" 7839 " .aaaaaaaaaaaaaaa()\n" 7840 " .aaaaaaaaaaaaaaa();"); 7841 verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7842 " .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7843 " .aaaaaaaaaaaaaaa();"); 7844 verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n" 7845 " ->aaaaaaaaaaaaaae(0)\n" 7846 " ->aaaaaaaaaaaaaaa();"); 7847 7848 // Don't linewrap after very short segments. 7849 verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7850 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7851 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7852 verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7853 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7854 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7855 verifyFormat("aaa()\n" 7856 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7857 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7858 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7859 7860 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n" 7861 " .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7862 " .has<bbbbbbbbbbbbbbbbbbbbb>();"); 7863 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n" 7864 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 7865 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();"); 7866 7867 // Prefer not to break after empty parentheses. 7868 verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n" 7869 " First->LastNewlineOffset);"); 7870 7871 // Prefer not to create "hanging" indents. 7872 verifyFormat( 7873 "return !soooooooooooooome_map\n" 7874 " .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7875 " .second;"); 7876 verifyFormat( 7877 "return aaaaaaaaaaaaaaaa\n" 7878 " .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n" 7879 " .aaaa(aaaaaaaaaaaaaa);"); 7880 // No hanging indent here. 7881 verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n" 7882 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7883 verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n" 7884 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7885 verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n" 7886 " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7887 getLLVMStyleWithColumns(60)); 7888 verifyFormat("aaaaaaaaaaaaaaaaaa\n" 7889 " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n" 7890 " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7891 getLLVMStyleWithColumns(59)); 7892 verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7893 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7894 " .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7895 7896 // Dont break if only closing statements before member call 7897 verifyFormat("test() {\n" 7898 " ([]() -> {\n" 7899 " int b = 32;\n" 7900 " return 3;\n" 7901 " }).foo();\n" 7902 "}"); 7903 verifyFormat("test() {\n" 7904 " (\n" 7905 " []() -> {\n" 7906 " int b = 32;\n" 7907 " return 3;\n" 7908 " },\n" 7909 " foo, bar)\n" 7910 " .foo();\n" 7911 "}"); 7912 verifyFormat("test() {\n" 7913 " ([]() -> {\n" 7914 " int b = 32;\n" 7915 " return 3;\n" 7916 " })\n" 7917 " .foo()\n" 7918 " .bar();\n" 7919 "}"); 7920 verifyFormat("test() {\n" 7921 " ([]() -> {\n" 7922 " int b = 32;\n" 7923 " return 3;\n" 7924 " })\n" 7925 " .foo(\"aaaaaaaaaaaaaaaaa\"\n" 7926 " \"bbbb\");\n" 7927 "}", 7928 getLLVMStyleWithColumns(30)); 7929 } 7930 7931 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) { 7932 verifyFormat( 7933 "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 7934 " bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}"); 7935 verifyFormat( 7936 "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n" 7937 " bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}"); 7938 7939 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" 7940 " ccccccccccccccccccccccccc) {\n}"); 7941 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n" 7942 " ccccccccccccccccccccccccc) {\n}"); 7943 7944 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" 7945 " ccccccccccccccccccccccccc) {\n}"); 7946 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n" 7947 " ccccccccccccccccccccccccc) {\n}"); 7948 7949 verifyFormat( 7950 "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n" 7951 " ccccccccccccccccccccccccc) {\n}"); 7952 verifyFormat( 7953 "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n" 7954 " ccccccccccccccccccccccccc) {\n}"); 7955 7956 verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n" 7957 " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n" 7958 " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n" 7959 " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;"); 7960 verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n" 7961 " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n" 7962 " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n" 7963 " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;"); 7964 7965 verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n" 7966 " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n" 7967 " aaaaaaaaaaaaaaa != aa) {\n}"); 7968 verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n" 7969 " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n" 7970 " aaaaaaaaaaaaaaa != aa) {\n}"); 7971 } 7972 7973 TEST_F(FormatTest, BreaksAfterAssignments) { 7974 verifyFormat( 7975 "unsigned Cost =\n" 7976 " TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n" 7977 " SI->getPointerAddressSpaceee());\n"); 7978 verifyFormat( 7979 "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n" 7980 " Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());"); 7981 7982 verifyFormat( 7983 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n" 7984 " aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);"); 7985 verifyFormat("unsigned OriginalStartColumn =\n" 7986 " SourceMgr.getSpellingColumnNumber(\n" 7987 " Current.FormatTok.getStartOfNonWhitespace()) -\n" 7988 " 1;"); 7989 } 7990 7991 TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) { 7992 FormatStyle Style = getLLVMStyle(); 7993 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 7994 " bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;", 7995 Style); 7996 7997 Style.PenaltyBreakAssignment = 20; 7998 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n" 7999 " cccccccccccccccccccccccccc;", 8000 Style); 8001 } 8002 8003 TEST_F(FormatTest, AlignsAfterAssignments) { 8004 verifyFormat( 8005 "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 8006 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 8007 verifyFormat( 8008 "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 8009 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 8010 verifyFormat( 8011 "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 8012 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 8013 verifyFormat( 8014 "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 8015 " aaaaaaaaaaaaaaaaaaaaaaaaa);"); 8016 verifyFormat( 8017 "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n" 8018 " aaaaaaaaaaaaaaaaaaaaaaaa +\n" 8019 " aaaaaaaaaaaaaaaaaaaaaaaa;"); 8020 } 8021 8022 TEST_F(FormatTest, AlignsAfterReturn) { 8023 verifyFormat( 8024 "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 8025 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 8026 verifyFormat( 8027 "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 8028 " aaaaaaaaaaaaaaaaaaaaaaaaa);"); 8029 verifyFormat( 8030 "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n" 8031 " aaaaaaaaaaaaaaaaaaaaaa();"); 8032 verifyFormat( 8033 "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n" 8034 " aaaaaaaaaaaaaaaaaaaaaa());"); 8035 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8036 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8037 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8038 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n" 8039 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8040 verifyFormat("return\n" 8041 " // true if code is one of a or b.\n" 8042 " code == a || code == b;"); 8043 } 8044 8045 TEST_F(FormatTest, AlignsAfterOpenBracket) { 8046 verifyFormat( 8047 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n" 8048 " aaaaaaaaa aaaaaaa) {}"); 8049 verifyFormat( 8050 "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n" 8051 " aaaaaaaaaaa aaaaaaaaa);"); 8052 verifyFormat( 8053 "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n" 8054 " aaaaaaaaaaaaaaaaaaaaa));"); 8055 FormatStyle Style = getLLVMStyle(); 8056 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 8057 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8058 " aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}", 8059 Style); 8060 verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n" 8061 " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);", 8062 Style); 8063 verifyFormat("SomeLongVariableName->someFunction(\n" 8064 " foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));", 8065 Style); 8066 verifyFormat( 8067 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n" 8068 " aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 8069 Style); 8070 verifyFormat( 8071 "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n" 8072 " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8073 Style); 8074 verifyFormat( 8075 "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n" 8076 " aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));", 8077 Style); 8078 8079 verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n" 8080 " ccccccc(aaaaaaaaaaaaaaaaa, //\n" 8081 " b));", 8082 Style); 8083 8084 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 8085 Style.BinPackArguments = false; 8086 Style.BinPackParameters = false; 8087 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8088 " aaaaaaaaaaa aaaaaaaa,\n" 8089 " aaaaaaaaa aaaaaaa,\n" 8090 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 8091 Style); 8092 verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n" 8093 " aaaaaaaaaaa aaaaaaaaa,\n" 8094 " aaaaaaaaaaa aaaaaaaaa,\n" 8095 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8096 Style); 8097 verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n" 8098 " aaaaaaaaaaaaaaa,\n" 8099 " aaaaaaaaaaaaaaaaaaaaa,\n" 8100 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));", 8101 Style); 8102 verifyFormat( 8103 "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n" 8104 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));", 8105 Style); 8106 verifyFormat( 8107 "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n" 8108 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));", 8109 Style); 8110 verifyFormat( 8111 "aaaaaaaaaaaaaaaaaaaaaaaa(\n" 8112 " aaaaaaaaaaaaaaaaaaaaa(\n" 8113 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n" 8114 " aaaaaaaaaaaaaaaa);", 8115 Style); 8116 verifyFormat( 8117 "aaaaaaaaaaaaaaaaaaaaaaaa(\n" 8118 " aaaaaaaaaaaaaaaaaaaaa(\n" 8119 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n" 8120 " aaaaaaaaaaaaaaaa);", 8121 Style); 8122 } 8123 8124 TEST_F(FormatTest, ParenthesesAndOperandAlignment) { 8125 FormatStyle Style = getLLVMStyleWithColumns(40); 8126 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 8127 " bbbbbbbbbbbbbbbbbbbbbb);", 8128 Style); 8129 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 8130 Style.AlignOperands = FormatStyle::OAS_DontAlign; 8131 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 8132 " bbbbbbbbbbbbbbbbbbbbbb);", 8133 Style); 8134 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 8135 Style.AlignOperands = FormatStyle::OAS_Align; 8136 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 8137 " bbbbbbbbbbbbbbbbbbbbbb);", 8138 Style); 8139 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 8140 Style.AlignOperands = FormatStyle::OAS_DontAlign; 8141 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 8142 " bbbbbbbbbbbbbbbbbbbbbb);", 8143 Style); 8144 } 8145 8146 TEST_F(FormatTest, BreaksConditionalExpressions) { 8147 verifyFormat( 8148 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8149 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8150 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8151 verifyFormat( 8152 "aaaa(aaaaaaaaaa, aaaaaaaa,\n" 8153 " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8154 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8155 verifyFormat( 8156 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8157 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8158 verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n" 8159 " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8160 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8161 verifyFormat( 8162 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n" 8163 " : aaaaaaaaaaaaa);"); 8164 verifyFormat( 8165 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8166 " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8167 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8168 " aaaaaaaaaaaaa);"); 8169 verifyFormat( 8170 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8171 " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8172 " aaaaaaaaaaaaa);"); 8173 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8174 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8175 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8176 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8177 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8178 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8179 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8180 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8181 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8182 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8183 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8184 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8185 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8186 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8187 " ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8188 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8189 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8190 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8191 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8192 " : aaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8193 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n" 8194 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8195 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8196 " : aaaaaaaaaaaaaaaa;"); 8197 verifyFormat( 8198 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8199 " ? aaaaaaaaaaaaaaa\n" 8200 " : aaaaaaaaaaaaaaa;"); 8201 verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n" 8202 " aaaaaaaaa\n" 8203 " ? b\n" 8204 " : c);"); 8205 verifyFormat("return aaaa == bbbb\n" 8206 " // comment\n" 8207 " ? aaaa\n" 8208 " : bbbb;"); 8209 verifyFormat("unsigned Indent =\n" 8210 " format(TheLine.First,\n" 8211 " IndentForLevel[TheLine.Level] >= 0\n" 8212 " ? IndentForLevel[TheLine.Level]\n" 8213 " : TheLine * 2,\n" 8214 " TheLine.InPPDirective, PreviousEndOfLineColumn);", 8215 getLLVMStyleWithColumns(60)); 8216 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n" 8217 " ? aaaaaaaaaaaaaaa\n" 8218 " : bbbbbbbbbbbbbbb //\n" 8219 " ? ccccccccccccccc\n" 8220 " : ddddddddddddddd;"); 8221 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n" 8222 " ? aaaaaaaaaaaaaaa\n" 8223 " : (bbbbbbbbbbbbbbb //\n" 8224 " ? ccccccccccccccc\n" 8225 " : ddddddddddddddd);"); 8226 verifyFormat( 8227 "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8228 " ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 8229 " aaaaaaaaaaaaaaaaaaaaa +\n" 8230 " aaaaaaaaaaaaaaaaaaaaa\n" 8231 " : aaaaaaaaaa;"); 8232 verifyFormat( 8233 "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8234 " : aaaaaaaaaaaaaaaaaaaaaa\n" 8235 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8236 8237 FormatStyle NoBinPacking = getLLVMStyle(); 8238 NoBinPacking.BinPackArguments = false; 8239 verifyFormat( 8240 "void f() {\n" 8241 " g(aaa,\n" 8242 " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n" 8243 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8244 " ? aaaaaaaaaaaaaaa\n" 8245 " : aaaaaaaaaaaaaaa);\n" 8246 "}", 8247 NoBinPacking); 8248 verifyFormat( 8249 "void f() {\n" 8250 " g(aaa,\n" 8251 " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n" 8252 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8253 " ?: aaaaaaaaaaaaaaa);\n" 8254 "}", 8255 NoBinPacking); 8256 8257 verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n" 8258 " // comment.\n" 8259 " ccccccccccccccccccccccccccccccccccccccc\n" 8260 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8261 " : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);"); 8262 8263 // Assignments in conditional expressions. Apparently not uncommon :-(. 8264 verifyFormat("return a != b\n" 8265 " // comment\n" 8266 " ? a = b\n" 8267 " : a = b;"); 8268 verifyFormat("return a != b\n" 8269 " // comment\n" 8270 " ? a = a != b\n" 8271 " // comment\n" 8272 " ? a = b\n" 8273 " : a\n" 8274 " : a;\n"); 8275 verifyFormat("return a != b\n" 8276 " // comment\n" 8277 " ? a\n" 8278 " : a = a != b\n" 8279 " // comment\n" 8280 " ? a = b\n" 8281 " : a;"); 8282 8283 // Chained conditionals 8284 FormatStyle Style = getLLVMStyleWithColumns(70); 8285 Style.AlignOperands = FormatStyle::OAS_Align; 8286 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8287 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8288 " : 3333333333333333;", 8289 Style); 8290 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8291 " : bbbbbbbbbb ? 2222222222222222\n" 8292 " : 3333333333333333;", 8293 Style); 8294 verifyFormat("return aaaaaaaaaa ? 1111111111111111\n" 8295 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 8296 " : 3333333333333333;", 8297 Style); 8298 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8299 " : bbbbbbbbbbbbbb ? 222222\n" 8300 " : 333333;", 8301 Style); 8302 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8303 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8304 " : cccccccccccccc ? 3333333333333333\n" 8305 " : 4444444444444444;", 8306 Style); 8307 verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc)\n" 8308 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8309 " : 3333333333333333;", 8310 Style); 8311 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8312 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8313 " : (aaa ? bbb : ccc);", 8314 Style); 8315 verifyFormat( 8316 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8317 " : cccccccccccccccccc)\n" 8318 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8319 " : 3333333333333333;", 8320 Style); 8321 verifyFormat( 8322 "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8323 " : cccccccccccccccccc)\n" 8324 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8325 " : 3333333333333333;", 8326 Style); 8327 verifyFormat( 8328 "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8329 " : dddddddddddddddddd)\n" 8330 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8331 " : 3333333333333333;", 8332 Style); 8333 verifyFormat( 8334 "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8335 " : dddddddddddddddddd)\n" 8336 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8337 " : 3333333333333333;", 8338 Style); 8339 verifyFormat( 8340 "return aaaaaaaaa ? 1111111111111111\n" 8341 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8342 " : a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8343 " : dddddddddddddddddd)\n", 8344 Style); 8345 verifyFormat( 8346 "return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8347 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8348 " : (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8349 " : cccccccccccccccccc);", 8350 Style); 8351 verifyFormat( 8352 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8353 " : ccccccccccccccc ? dddddddddddddddddd\n" 8354 " : eeeeeeeeeeeeeeeeee)\n" 8355 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8356 " : 3333333333333333;", 8357 Style); 8358 verifyFormat( 8359 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8360 " : ccccccccccccccc ? dddddddddddddddddd\n" 8361 " : eeeeeeeeeeeeeeeeee)\n" 8362 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8363 " : 3333333333333333;", 8364 Style); 8365 verifyFormat( 8366 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8367 " : cccccccccccc ? dddddddddddddddddd\n" 8368 " : eeeeeeeeeeeeeeeeee)\n" 8369 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8370 " : 3333333333333333;", 8371 Style); 8372 verifyFormat( 8373 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8374 " : cccccccccccccccccc\n" 8375 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8376 " : 3333333333333333;", 8377 Style); 8378 verifyFormat( 8379 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8380 " : cccccccccccccccc ? dddddddddddddddddd\n" 8381 " : eeeeeeeeeeeeeeeeee\n" 8382 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8383 " : 3333333333333333;", 8384 Style); 8385 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa\n" 8386 " ? (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8387 " : cccccccccccccccccc ? dddddddddddddddddd\n" 8388 " : eeeeeeeeeeeeeeeeee)\n" 8389 " : bbbbbbbbbbbbbbbbbbb ? 2222222222222222\n" 8390 " : 3333333333333333;", 8391 Style); 8392 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaa\n" 8393 " ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8394 " : cccccccccccccccc ? dddddddddddddddddd\n" 8395 " : eeeeeeeeeeeeeeeeee\n" 8396 " : bbbbbbbbbbbbbbbbbbbbbbb ? 2222222222222222\n" 8397 " : 3333333333333333;", 8398 Style); 8399 8400 Style.AlignOperands = FormatStyle::OAS_DontAlign; 8401 Style.BreakBeforeTernaryOperators = false; 8402 // FIXME: Aligning the question marks is weird given DontAlign. 8403 // Consider disabling this alignment in this case. Also check whether this 8404 // will render the adjustment from https://reviews.llvm.org/D82199 8405 // unnecessary. 8406 verifyFormat("int x = aaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa :\n" 8407 " bbbb ? cccccccccccccccccc :\n" 8408 " ddddd;\n", 8409 Style); 8410 8411 EXPECT_EQ( 8412 "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n" 8413 " /*\n" 8414 " */\n" 8415 " function() {\n" 8416 " try {\n" 8417 " return JJJJJJJJJJJJJJ(\n" 8418 " pppppppppppppppppppppppppppppppppppppppppppppppppp);\n" 8419 " }\n" 8420 " } :\n" 8421 " function() {};", 8422 format( 8423 "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n" 8424 " /*\n" 8425 " */\n" 8426 " function() {\n" 8427 " try {\n" 8428 " return JJJJJJJJJJJJJJ(\n" 8429 " pppppppppppppppppppppppppppppppppppppppppppppppppp);\n" 8430 " }\n" 8431 " } :\n" 8432 " function() {};", 8433 getGoogleStyle(FormatStyle::LK_JavaScript))); 8434 } 8435 8436 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) { 8437 FormatStyle Style = getLLVMStyleWithColumns(70); 8438 Style.BreakBeforeTernaryOperators = false; 8439 verifyFormat( 8440 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8441 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8442 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8443 Style); 8444 verifyFormat( 8445 "aaaa(aaaaaaaaaa, aaaaaaaa,\n" 8446 " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8447 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8448 Style); 8449 verifyFormat( 8450 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8451 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8452 Style); 8453 verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n" 8454 " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8455 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8456 Style); 8457 verifyFormat( 8458 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n" 8459 " aaaaaaaaaaaaa);", 8460 Style); 8461 verifyFormat( 8462 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8463 " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8464 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8465 " aaaaaaaaaaaaa);", 8466 Style); 8467 verifyFormat( 8468 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8469 " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8470 " aaaaaaaaaaaaa);", 8471 Style); 8472 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8473 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8474 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 8475 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8476 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8477 Style); 8478 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8479 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8480 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8481 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 8482 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8483 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8484 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8485 Style); 8486 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8487 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n" 8488 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8489 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8490 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8491 Style); 8492 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8493 " aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8494 " aaaaaaaaaaaaaaaaaaaaaaaaaaa;", 8495 Style); 8496 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n" 8497 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8498 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8499 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 8500 Style); 8501 verifyFormat( 8502 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8503 " aaaaaaaaaaaaaaa :\n" 8504 " aaaaaaaaaaaaaaa;", 8505 Style); 8506 verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n" 8507 " aaaaaaaaa ?\n" 8508 " b :\n" 8509 " c);", 8510 Style); 8511 verifyFormat("unsigned Indent =\n" 8512 " format(TheLine.First,\n" 8513 " IndentForLevel[TheLine.Level] >= 0 ?\n" 8514 " IndentForLevel[TheLine.Level] :\n" 8515 " TheLine * 2,\n" 8516 " TheLine.InPPDirective, PreviousEndOfLineColumn);", 8517 Style); 8518 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n" 8519 " aaaaaaaaaaaaaaa :\n" 8520 " bbbbbbbbbbbbbbb ? //\n" 8521 " ccccccccccccccc :\n" 8522 " ddddddddddddddd;", 8523 Style); 8524 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n" 8525 " aaaaaaaaaaaaaaa :\n" 8526 " (bbbbbbbbbbbbbbb ? //\n" 8527 " ccccccccccccccc :\n" 8528 " ddddddddddddddd);", 8529 Style); 8530 verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8531 " /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n" 8532 " ccccccccccccccccccccccccccc;", 8533 Style); 8534 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8535 " aaaaa :\n" 8536 " bbbbbbbbbbbbbbb + cccccccccccccccc;", 8537 Style); 8538 8539 // Chained conditionals 8540 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8541 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8542 " 3333333333333333;", 8543 Style); 8544 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8545 " bbbbbbbbbb ? 2222222222222222 :\n" 8546 " 3333333333333333;", 8547 Style); 8548 verifyFormat("return aaaaaaaaaa ? 1111111111111111 :\n" 8549 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8550 " 3333333333333333;", 8551 Style); 8552 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8553 " bbbbbbbbbbbbbbbb ? 222222 :\n" 8554 " 333333;", 8555 Style); 8556 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8557 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8558 " cccccccccccccccc ? 3333333333333333 :\n" 8559 " 4444444444444444;", 8560 Style); 8561 verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc) :\n" 8562 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8563 " 3333333333333333;", 8564 Style); 8565 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8566 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8567 " (aaa ? bbb : ccc);", 8568 Style); 8569 verifyFormat( 8570 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8571 " cccccccccccccccccc) :\n" 8572 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8573 " 3333333333333333;", 8574 Style); 8575 verifyFormat( 8576 "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8577 " cccccccccccccccccc) :\n" 8578 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8579 " 3333333333333333;", 8580 Style); 8581 verifyFormat( 8582 "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8583 " dddddddddddddddddd) :\n" 8584 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8585 " 3333333333333333;", 8586 Style); 8587 verifyFormat( 8588 "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8589 " dddddddddddddddddd) :\n" 8590 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8591 " 3333333333333333;", 8592 Style); 8593 verifyFormat( 8594 "return aaaaaaaaa ? 1111111111111111 :\n" 8595 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8596 " a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8597 " dddddddddddddddddd)\n", 8598 Style); 8599 verifyFormat( 8600 "return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8601 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8602 " (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8603 " cccccccccccccccccc);", 8604 Style); 8605 verifyFormat( 8606 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8607 " ccccccccccccccccc ? dddddddddddddddddd :\n" 8608 " eeeeeeeeeeeeeeeeee) :\n" 8609 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8610 " 3333333333333333;", 8611 Style); 8612 verifyFormat( 8613 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8614 " ccccccccccccc ? dddddddddddddddddd :\n" 8615 " eeeeeeeeeeeeeeeeee) :\n" 8616 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8617 " 3333333333333333;", 8618 Style); 8619 verifyFormat( 8620 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8621 " ccccccccccccccccc ? dddddddddddddddddd :\n" 8622 " eeeeeeeeeeeeeeeeee) :\n" 8623 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8624 " 3333333333333333;", 8625 Style); 8626 verifyFormat( 8627 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8628 " cccccccccccccccccc :\n" 8629 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8630 " 3333333333333333;", 8631 Style); 8632 verifyFormat( 8633 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8634 " cccccccccccccccccc ? dddddddddddddddddd :\n" 8635 " eeeeeeeeeeeeeeeeee :\n" 8636 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8637 " 3333333333333333;", 8638 Style); 8639 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n" 8640 " (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8641 " cccccccccccccccccc ? dddddddddddddddddd :\n" 8642 " eeeeeeeeeeeeeeeeee) :\n" 8643 " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8644 " 3333333333333333;", 8645 Style); 8646 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n" 8647 " aaaaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8648 " cccccccccccccccccccc ? dddddddddddddddddd :\n" 8649 " eeeeeeeeeeeeeeeeee :\n" 8650 " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8651 " 3333333333333333;", 8652 Style); 8653 } 8654 8655 TEST_F(FormatTest, DeclarationsOfMultipleVariables) { 8656 verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n" 8657 " aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();"); 8658 verifyFormat("bool a = true, b = false;"); 8659 8660 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n" 8661 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n" 8662 " bbbbbbbbbbbbbbbbbbbbbbbbb =\n" 8663 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);"); 8664 verifyFormat( 8665 "bool aaaaaaaaaaaaaaaaaaaaa =\n" 8666 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n" 8667 " d = e && f;"); 8668 verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n" 8669 " c = cccccccccccccccccccc, d = dddddddddddddddddddd;"); 8670 verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n" 8671 " *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;"); 8672 verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n" 8673 " ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;"); 8674 8675 FormatStyle Style = getGoogleStyle(); 8676 Style.PointerAlignment = FormatStyle::PAS_Left; 8677 Style.DerivePointerAlignment = false; 8678 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8679 " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n" 8680 " *b = bbbbbbbbbbbbbbbbbbb;", 8681 Style); 8682 verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n" 8683 " *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;", 8684 Style); 8685 verifyFormat("vector<int*> a, b;", Style); 8686 verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style); 8687 verifyFormat("/*comment*/ for (int *p, *q; p != q; p = p->next) {\n}", Style); 8688 verifyFormat("if (int *p, *q; p != q) {\n p = p->next;\n}", Style); 8689 verifyFormat("/*comment*/ if (int *p, *q; p != q) {\n p = p->next;\n}", 8690 Style); 8691 verifyFormat("switch (int *p, *q; p != q) {\n default:\n break;\n}", 8692 Style); 8693 verifyFormat( 8694 "/*comment*/ switch (int *p, *q; p != q) {\n default:\n break;\n}", 8695 Style); 8696 8697 verifyFormat("if ([](int* p, int* q) {}()) {\n}", Style); 8698 verifyFormat("for ([](int* p, int* q) {}();;) {\n}", Style); 8699 verifyFormat("for (; [](int* p, int* q) {}();) {\n}", Style); 8700 verifyFormat("for (;; [](int* p, int* q) {}()) {\n}", Style); 8701 verifyFormat("switch ([](int* p, int* q) {}()) {\n default:\n break;\n}", 8702 Style); 8703 } 8704 8705 TEST_F(FormatTest, ConditionalExpressionsInBrackets) { 8706 verifyFormat("arr[foo ? bar : baz];"); 8707 verifyFormat("f()[foo ? bar : baz];"); 8708 verifyFormat("(a + b)[foo ? bar : baz];"); 8709 verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];"); 8710 } 8711 8712 TEST_F(FormatTest, AlignsStringLiterals) { 8713 verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n" 8714 " \"short literal\");"); 8715 verifyFormat( 8716 "looooooooooooooooooooooooongFunction(\n" 8717 " \"short literal\"\n" 8718 " \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");"); 8719 verifyFormat("someFunction(\"Always break between multi-line\"\n" 8720 " \" string literals\",\n" 8721 " and, other, parameters);"); 8722 EXPECT_EQ("fun + \"1243\" /* comment */\n" 8723 " \"5678\";", 8724 format("fun + \"1243\" /* comment */\n" 8725 " \"5678\";", 8726 getLLVMStyleWithColumns(28))); 8727 EXPECT_EQ( 8728 "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 8729 " \"aaaaaaaaaaaaaaaaaaaaa\"\n" 8730 " \"aaaaaaaaaaaaaaaa\";", 8731 format("aaaaaa =" 8732 "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa " 8733 "aaaaaaaaaaaaaaaaaaaaa\" " 8734 "\"aaaaaaaaaaaaaaaa\";")); 8735 verifyFormat("a = a + \"a\"\n" 8736 " \"a\"\n" 8737 " \"a\";"); 8738 verifyFormat("f(\"a\", \"b\"\n" 8739 " \"c\");"); 8740 8741 verifyFormat( 8742 "#define LL_FORMAT \"ll\"\n" 8743 "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n" 8744 " \"d, ddddddddd: %\" LL_FORMAT \"d\");"); 8745 8746 verifyFormat("#define A(X) \\\n" 8747 " \"aaaaa\" #X \"bbbbbb\" \\\n" 8748 " \"ccccc\"", 8749 getLLVMStyleWithColumns(23)); 8750 verifyFormat("#define A \"def\"\n" 8751 "f(\"abc\" A \"ghi\"\n" 8752 " \"jkl\");"); 8753 8754 verifyFormat("f(L\"a\"\n" 8755 " L\"b\");"); 8756 verifyFormat("#define A(X) \\\n" 8757 " L\"aaaaa\" #X L\"bbbbbb\" \\\n" 8758 " L\"ccccc\"", 8759 getLLVMStyleWithColumns(25)); 8760 8761 verifyFormat("f(@\"a\"\n" 8762 " @\"b\");"); 8763 verifyFormat("NSString s = @\"a\"\n" 8764 " @\"b\"\n" 8765 " @\"c\";"); 8766 verifyFormat("NSString s = @\"a\"\n" 8767 " \"b\"\n" 8768 " \"c\";"); 8769 } 8770 8771 TEST_F(FormatTest, ReturnTypeBreakingStyle) { 8772 FormatStyle Style = getLLVMStyle(); 8773 // No declarations or definitions should be moved to own line. 8774 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None; 8775 verifyFormat("class A {\n" 8776 " int f() { return 1; }\n" 8777 " int g();\n" 8778 "};\n" 8779 "int f() { return 1; }\n" 8780 "int g();\n", 8781 Style); 8782 8783 // All declarations and definitions should have the return type moved to its 8784 // own line. 8785 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 8786 Style.TypenameMacros = {"LIST"}; 8787 verifyFormat("SomeType\n" 8788 "funcdecl(LIST(uint64_t));", 8789 Style); 8790 verifyFormat("class E {\n" 8791 " int\n" 8792 " f() {\n" 8793 " return 1;\n" 8794 " }\n" 8795 " int\n" 8796 " g();\n" 8797 "};\n" 8798 "int\n" 8799 "f() {\n" 8800 " return 1;\n" 8801 "}\n" 8802 "int\n" 8803 "g();\n", 8804 Style); 8805 8806 // Top-level definitions, and no kinds of declarations should have the 8807 // return type moved to its own line. 8808 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions; 8809 verifyFormat("class B {\n" 8810 " int f() { return 1; }\n" 8811 " int g();\n" 8812 "};\n" 8813 "int\n" 8814 "f() {\n" 8815 " return 1;\n" 8816 "}\n" 8817 "int g();\n", 8818 Style); 8819 8820 // Top-level definitions and declarations should have the return type moved 8821 // to its own line. 8822 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel; 8823 verifyFormat("class C {\n" 8824 " int f() { return 1; }\n" 8825 " int g();\n" 8826 "};\n" 8827 "int\n" 8828 "f() {\n" 8829 " return 1;\n" 8830 "}\n" 8831 "int\n" 8832 "g();\n", 8833 Style); 8834 8835 // All definitions should have the return type moved to its own line, but no 8836 // kinds of declarations. 8837 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions; 8838 verifyFormat("class D {\n" 8839 " int\n" 8840 " f() {\n" 8841 " return 1;\n" 8842 " }\n" 8843 " int g();\n" 8844 "};\n" 8845 "int\n" 8846 "f() {\n" 8847 " return 1;\n" 8848 "}\n" 8849 "int g();\n", 8850 Style); 8851 verifyFormat("const char *\n" 8852 "f(void) {\n" // Break here. 8853 " return \"\";\n" 8854 "}\n" 8855 "const char *bar(void);\n", // No break here. 8856 Style); 8857 verifyFormat("template <class T>\n" 8858 "T *\n" 8859 "f(T &c) {\n" // Break here. 8860 " return NULL;\n" 8861 "}\n" 8862 "template <class T> T *f(T &c);\n", // No break here. 8863 Style); 8864 verifyFormat("class C {\n" 8865 " int\n" 8866 " operator+() {\n" 8867 " return 1;\n" 8868 " }\n" 8869 " int\n" 8870 " operator()() {\n" 8871 " return 1;\n" 8872 " }\n" 8873 "};\n", 8874 Style); 8875 verifyFormat("void\n" 8876 "A::operator()() {}\n" 8877 "void\n" 8878 "A::operator>>() {}\n" 8879 "void\n" 8880 "A::operator+() {}\n" 8881 "void\n" 8882 "A::operator*() {}\n" 8883 "void\n" 8884 "A::operator->() {}\n" 8885 "void\n" 8886 "A::operator void *() {}\n" 8887 "void\n" 8888 "A::operator void &() {}\n" 8889 "void\n" 8890 "A::operator void &&() {}\n" 8891 "void\n" 8892 "A::operator char *() {}\n" 8893 "void\n" 8894 "A::operator[]() {}\n" 8895 "void\n" 8896 "A::operator!() {}\n" 8897 "void\n" 8898 "A::operator**() {}\n" 8899 "void\n" 8900 "A::operator<Foo> *() {}\n" 8901 "void\n" 8902 "A::operator<Foo> **() {}\n" 8903 "void\n" 8904 "A::operator<Foo> &() {}\n" 8905 "void\n" 8906 "A::operator void **() {}\n", 8907 Style); 8908 verifyFormat("constexpr auto\n" 8909 "operator()() const -> reference {}\n" 8910 "constexpr auto\n" 8911 "operator>>() const -> reference {}\n" 8912 "constexpr auto\n" 8913 "operator+() const -> reference {}\n" 8914 "constexpr auto\n" 8915 "operator*() const -> reference {}\n" 8916 "constexpr auto\n" 8917 "operator->() const -> reference {}\n" 8918 "constexpr auto\n" 8919 "operator++() const -> reference {}\n" 8920 "constexpr auto\n" 8921 "operator void *() const -> reference {}\n" 8922 "constexpr auto\n" 8923 "operator void **() const -> reference {}\n" 8924 "constexpr auto\n" 8925 "operator void *() const -> reference {}\n" 8926 "constexpr auto\n" 8927 "operator void &() const -> reference {}\n" 8928 "constexpr auto\n" 8929 "operator void &&() const -> reference {}\n" 8930 "constexpr auto\n" 8931 "operator char *() const -> reference {}\n" 8932 "constexpr auto\n" 8933 "operator!() const -> reference {}\n" 8934 "constexpr auto\n" 8935 "operator[]() const -> reference {}\n", 8936 Style); 8937 verifyFormat("void *operator new(std::size_t s);", // No break here. 8938 Style); 8939 verifyFormat("void *\n" 8940 "operator new(std::size_t s) {}", 8941 Style); 8942 verifyFormat("void *\n" 8943 "operator delete[](void *ptr) {}", 8944 Style); 8945 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 8946 verifyFormat("const char *\n" 8947 "f(void)\n" // Break here. 8948 "{\n" 8949 " return \"\";\n" 8950 "}\n" 8951 "const char *bar(void);\n", // No break here. 8952 Style); 8953 verifyFormat("template <class T>\n" 8954 "T *\n" // Problem here: no line break 8955 "f(T &c)\n" // Break here. 8956 "{\n" 8957 " return NULL;\n" 8958 "}\n" 8959 "template <class T> T *f(T &c);\n", // No break here. 8960 Style); 8961 verifyFormat("int\n" 8962 "foo(A<bool> a)\n" 8963 "{\n" 8964 " return a;\n" 8965 "}\n", 8966 Style); 8967 verifyFormat("int\n" 8968 "foo(A<8> a)\n" 8969 "{\n" 8970 " return a;\n" 8971 "}\n", 8972 Style); 8973 verifyFormat("int\n" 8974 "foo(A<B<bool>, 8> a)\n" 8975 "{\n" 8976 " return a;\n" 8977 "}\n", 8978 Style); 8979 verifyFormat("int\n" 8980 "foo(A<B<8>, bool> a)\n" 8981 "{\n" 8982 " return a;\n" 8983 "}\n", 8984 Style); 8985 verifyFormat("int\n" 8986 "foo(A<B<bool>, bool> a)\n" 8987 "{\n" 8988 " return a;\n" 8989 "}\n", 8990 Style); 8991 verifyFormat("int\n" 8992 "foo(A<B<8>, 8> a)\n" 8993 "{\n" 8994 " return a;\n" 8995 "}\n", 8996 Style); 8997 8998 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 8999 Style.BraceWrapping.AfterFunction = true; 9000 verifyFormat("int f(i);\n" // No break here. 9001 "int\n" // Break here. 9002 "f(i)\n" 9003 "{\n" 9004 " return i + 1;\n" 9005 "}\n" 9006 "int\n" // Break here. 9007 "f(i)\n" 9008 "{\n" 9009 " return i + 1;\n" 9010 "};", 9011 Style); 9012 verifyFormat("int f(a, b, c);\n" // No break here. 9013 "int\n" // Break here. 9014 "f(a, b, c)\n" // Break here. 9015 "short a, b;\n" 9016 "float c;\n" 9017 "{\n" 9018 " return a + b < c;\n" 9019 "}\n" 9020 "int\n" // Break here. 9021 "f(a, b, c)\n" // Break here. 9022 "short a, b;\n" 9023 "float c;\n" 9024 "{\n" 9025 " return a + b < c;\n" 9026 "};", 9027 Style); 9028 verifyFormat("byte *\n" // Break here. 9029 "f(a)\n" // Break here. 9030 "byte a[];\n" 9031 "{\n" 9032 " return a;\n" 9033 "}", 9034 Style); 9035 verifyFormat("bool f(int a, int) override;\n" 9036 "Bar g(int a, Bar) final;\n" 9037 "Bar h(a, Bar) final;", 9038 Style); 9039 verifyFormat("int\n" 9040 "f(a)", 9041 Style); 9042 verifyFormat("bool\n" 9043 "f(size_t = 0, bool b = false)\n" 9044 "{\n" 9045 " return !b;\n" 9046 "}", 9047 Style); 9048 9049 // The return breaking style doesn't affect: 9050 // * function and object definitions with attribute-like macros 9051 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 9052 " ABSL_GUARDED_BY(mutex) = {};", 9053 getGoogleStyleWithColumns(40)); 9054 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 9055 " ABSL_GUARDED_BY(mutex); // comment", 9056 getGoogleStyleWithColumns(40)); 9057 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 9058 " ABSL_GUARDED_BY(mutex1)\n" 9059 " ABSL_GUARDED_BY(mutex2);", 9060 getGoogleStyleWithColumns(40)); 9061 verifyFormat("Tttttt f(int a, int b)\n" 9062 " ABSL_GUARDED_BY(mutex1)\n" 9063 " ABSL_GUARDED_BY(mutex2);", 9064 getGoogleStyleWithColumns(40)); 9065 // * typedefs 9066 verifyFormat("typedef ATTR(X) char x;", getGoogleStyle()); 9067 9068 Style = getGNUStyle(); 9069 9070 // Test for comments at the end of function declarations. 9071 verifyFormat("void\n" 9072 "foo (int a, /*abc*/ int b) // def\n" 9073 "{\n" 9074 "}\n", 9075 Style); 9076 9077 verifyFormat("void\n" 9078 "foo (int a, /* abc */ int b) /* def */\n" 9079 "{\n" 9080 "}\n", 9081 Style); 9082 9083 // Definitions that should not break after return type 9084 verifyFormat("void foo (int a, int b); // def\n", Style); 9085 verifyFormat("void foo (int a, int b); /* def */\n", Style); 9086 verifyFormat("void foo (int a, int b);\n", Style); 9087 } 9088 9089 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) { 9090 FormatStyle NoBreak = getLLVMStyle(); 9091 NoBreak.AlwaysBreakBeforeMultilineStrings = false; 9092 FormatStyle Break = getLLVMStyle(); 9093 Break.AlwaysBreakBeforeMultilineStrings = true; 9094 verifyFormat("aaaa = \"bbbb\"\n" 9095 " \"cccc\";", 9096 NoBreak); 9097 verifyFormat("aaaa =\n" 9098 " \"bbbb\"\n" 9099 " \"cccc\";", 9100 Break); 9101 verifyFormat("aaaa(\"bbbb\"\n" 9102 " \"cccc\");", 9103 NoBreak); 9104 verifyFormat("aaaa(\n" 9105 " \"bbbb\"\n" 9106 " \"cccc\");", 9107 Break); 9108 verifyFormat("aaaa(qqq, \"bbbb\"\n" 9109 " \"cccc\");", 9110 NoBreak); 9111 verifyFormat("aaaa(qqq,\n" 9112 " \"bbbb\"\n" 9113 " \"cccc\");", 9114 Break); 9115 verifyFormat("aaaa(qqq,\n" 9116 " L\"bbbb\"\n" 9117 " L\"cccc\");", 9118 Break); 9119 verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n" 9120 " \"bbbb\"));", 9121 Break); 9122 verifyFormat("string s = someFunction(\n" 9123 " \"abc\"\n" 9124 " \"abc\");", 9125 Break); 9126 9127 // As we break before unary operators, breaking right after them is bad. 9128 verifyFormat("string foo = abc ? \"x\"\n" 9129 " \"blah blah blah blah blah blah\"\n" 9130 " : \"y\";", 9131 Break); 9132 9133 // Don't break if there is no column gain. 9134 verifyFormat("f(\"aaaa\"\n" 9135 " \"bbbb\");", 9136 Break); 9137 9138 // Treat literals with escaped newlines like multi-line string literals. 9139 EXPECT_EQ("x = \"a\\\n" 9140 "b\\\n" 9141 "c\";", 9142 format("x = \"a\\\n" 9143 "b\\\n" 9144 "c\";", 9145 NoBreak)); 9146 EXPECT_EQ("xxxx =\n" 9147 " \"a\\\n" 9148 "b\\\n" 9149 "c\";", 9150 format("xxxx = \"a\\\n" 9151 "b\\\n" 9152 "c\";", 9153 Break)); 9154 9155 EXPECT_EQ("NSString *const kString =\n" 9156 " @\"aaaa\"\n" 9157 " @\"bbbb\";", 9158 format("NSString *const kString = @\"aaaa\"\n" 9159 "@\"bbbb\";", 9160 Break)); 9161 9162 Break.ColumnLimit = 0; 9163 verifyFormat("const char *hello = \"hello llvm\";", Break); 9164 } 9165 9166 TEST_F(FormatTest, AlignsPipes) { 9167 verifyFormat( 9168 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9169 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9170 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9171 verifyFormat( 9172 "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n" 9173 " << aaaaaaaaaaaaaaaaaaaa;"); 9174 verifyFormat( 9175 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9176 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9177 verifyFormat( 9178 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 9179 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9180 verifyFormat( 9181 "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n" 9182 " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n" 9183 " << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";"); 9184 verifyFormat( 9185 "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9186 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9187 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9188 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9189 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9190 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9191 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 9192 verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n" 9193 " << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);"); 9194 verifyFormat( 9195 "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9196 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9197 verifyFormat( 9198 "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n" 9199 " aaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9200 9201 verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n" 9202 " << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();"); 9203 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9204 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9205 " aaaaaaaaaaaaaaaaaaaaa)\n" 9206 " << aaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9207 verifyFormat("LOG_IF(aaa == //\n" 9208 " bbb)\n" 9209 " << a << b;"); 9210 9211 // But sometimes, breaking before the first "<<" is desirable. 9212 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 9213 " << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);"); 9214 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n" 9215 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9216 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9217 verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n" 9218 " << BEF << IsTemplate << Description << E->getType();"); 9219 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 9220 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9221 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9222 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 9223 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9224 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9225 " << aaa;"); 9226 9227 verifyFormat( 9228 "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9229 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9230 9231 // Incomplete string literal. 9232 EXPECT_EQ("llvm::errs() << \"\n" 9233 " << a;", 9234 format("llvm::errs() << \"\n<<a;")); 9235 9236 verifyFormat("void f() {\n" 9237 " CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n" 9238 " << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n" 9239 "}"); 9240 9241 // Handle 'endl'. 9242 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n" 9243 " << bbbbbbbbbbbbbbbbbbbbbb << endl;"); 9244 verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;"); 9245 9246 // Handle '\n'. 9247 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n" 9248 " << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";"); 9249 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n" 9250 " << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';"); 9251 verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n" 9252 " << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";"); 9253 verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";"); 9254 } 9255 9256 TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) { 9257 verifyFormat("return out << \"somepacket = {\\n\"\n" 9258 " << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n" 9259 " << \" bbbb = \" << pkt.bbbb << \"\\n\"\n" 9260 " << \" cccccc = \" << pkt.cccccc << \"\\n\"\n" 9261 " << \" ddd = [\" << pkt.ddd << \"]\\n\"\n" 9262 " << \"}\";"); 9263 9264 verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n" 9265 " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n" 9266 " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;"); 9267 verifyFormat( 9268 "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n" 9269 " << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n" 9270 " << \"ccccccccccccccccc = \" << ccccccccccccccccc\n" 9271 " << \"ddddddddddddddddd = \" << ddddddddddddddddd\n" 9272 " << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;"); 9273 verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n" 9274 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 9275 verifyFormat( 9276 "void f() {\n" 9277 " llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n" 9278 " << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 9279 "}"); 9280 9281 // Breaking before the first "<<" is generally not desirable. 9282 verifyFormat( 9283 "llvm::errs()\n" 9284 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9285 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9286 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9287 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 9288 getLLVMStyleWithColumns(70)); 9289 verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n" 9290 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9291 " << \"aaaaaaaaaaaaaaaaaaa: \"\n" 9292 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9293 " << \"aaaaaaaaaaaaaaaaaaa: \"\n" 9294 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 9295 getLLVMStyleWithColumns(70)); 9296 9297 verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n" 9298 " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n" 9299 " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;"); 9300 verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n" 9301 " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n" 9302 " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);"); 9303 verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n" 9304 " (aaaa + aaaa);", 9305 getLLVMStyleWithColumns(40)); 9306 verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n" 9307 " (aaaaaaa + aaaaa));", 9308 getLLVMStyleWithColumns(40)); 9309 verifyFormat( 9310 "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n" 9311 " SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n" 9312 " bbbbbbbbbbbbbbbbbbbbbbb);"); 9313 } 9314 9315 TEST_F(FormatTest, UnderstandsEquals) { 9316 verifyFormat( 9317 "aaaaaaaaaaaaaaaaa =\n" 9318 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9319 verifyFormat( 9320 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9321 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 9322 verifyFormat( 9323 "if (a) {\n" 9324 " f();\n" 9325 "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9326 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 9327 "}"); 9328 9329 verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9330 " 100000000 + 10000000) {\n}"); 9331 } 9332 9333 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) { 9334 verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n" 9335 " .looooooooooooooooooooooooooooooooooooooongFunction();"); 9336 9337 verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n" 9338 " ->looooooooooooooooooooooooooooooooooooooongFunction();"); 9339 9340 verifyFormat( 9341 "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n" 9342 " Parameter2);"); 9343 9344 verifyFormat( 9345 "ShortObject->shortFunction(\n" 9346 " LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n" 9347 " LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);"); 9348 9349 verifyFormat("loooooooooooooongFunction(\n" 9350 " LoooooooooooooongObject->looooooooooooooooongFunction());"); 9351 9352 verifyFormat( 9353 "function(LoooooooooooooooooooooooooooooooooooongObject\n" 9354 " ->loooooooooooooooooooooooooooooooooooooooongFunction());"); 9355 9356 verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n" 9357 " .WillRepeatedly(Return(SomeValue));"); 9358 verifyFormat("void f() {\n" 9359 " EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n" 9360 " .Times(2)\n" 9361 " .WillRepeatedly(Return(SomeValue));\n" 9362 "}"); 9363 verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n" 9364 " ccccccccccccccccccccccc);"); 9365 verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9366 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9367 " .aaaaa(aaaaa),\n" 9368 " aaaaaaaaaaaaaaaaaaaaa);"); 9369 verifyFormat("void f() {\n" 9370 " aaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9371 " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n" 9372 "}"); 9373 verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9374 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9375 " .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9376 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9377 " aaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 9378 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9379 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9380 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9381 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n" 9382 "}"); 9383 9384 // Here, it is not necessary to wrap at "." or "->". 9385 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n" 9386 " aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 9387 verifyFormat( 9388 "aaaaaaaaaaa->aaaaaaaaa(\n" 9389 " aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9390 " aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n"); 9391 9392 verifyFormat( 9393 "aaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9394 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());"); 9395 verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n" 9396 " aaaaaaaaa()->aaaaaa()->aaaaa());"); 9397 verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n" 9398 " aaaaaaaaa()->aaaaaa()->aaaaa());"); 9399 9400 verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9401 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9402 " .a();"); 9403 9404 FormatStyle NoBinPacking = getLLVMStyle(); 9405 NoBinPacking.BinPackParameters = false; 9406 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n" 9407 " .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n" 9408 " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n" 9409 " aaaaaaaaaaaaaaaaaaa,\n" 9410 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 9411 NoBinPacking); 9412 9413 // If there is a subsequent call, change to hanging indentation. 9414 verifyFormat( 9415 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9416 " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n" 9417 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9418 verifyFormat( 9419 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9420 " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));"); 9421 verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9422 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9423 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9424 verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9425 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9426 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());"); 9427 } 9428 9429 TEST_F(FormatTest, WrapsTemplateDeclarations) { 9430 verifyFormat("template <typename T>\n" 9431 "virtual void loooooooooooongFunction(int Param1, int Param2);"); 9432 verifyFormat("template <typename T>\n" 9433 "// T should be one of {A, B}.\n" 9434 "virtual void loooooooooooongFunction(int Param1, int Param2);"); 9435 verifyFormat( 9436 "template <typename T>\n" 9437 "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;"); 9438 verifyFormat("template <typename T>\n" 9439 "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n" 9440 " int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);"); 9441 verifyFormat( 9442 "template <typename T>\n" 9443 "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n" 9444 " int Paaaaaaaaaaaaaaaaaaaaram2);"); 9445 verifyFormat( 9446 "template <typename T>\n" 9447 "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n" 9448 " aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n" 9449 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9450 verifyFormat("template <typename T>\n" 9451 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9452 " int aaaaaaaaaaaaaaaaaaaaaa);"); 9453 verifyFormat( 9454 "template <typename T1, typename T2 = char, typename T3 = char,\n" 9455 " typename T4 = char>\n" 9456 "void f();"); 9457 verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n" 9458 " template <typename> class cccccccccccccccccccccc,\n" 9459 " typename ddddddddddddd>\n" 9460 "class C {};"); 9461 verifyFormat( 9462 "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n" 9463 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9464 9465 verifyFormat("void f() {\n" 9466 " a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n" 9467 " a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n" 9468 "}"); 9469 9470 verifyFormat("template <typename T> class C {};"); 9471 verifyFormat("template <typename T> void f();"); 9472 verifyFormat("template <typename T> void f() {}"); 9473 verifyFormat( 9474 "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n" 9475 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9476 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n" 9477 " new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n" 9478 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9479 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n" 9480 " bbbbbbbbbbbbbbbbbbbbbbbb);", 9481 getLLVMStyleWithColumns(72)); 9482 EXPECT_EQ("static_cast<A< //\n" 9483 " B> *>(\n" 9484 "\n" 9485 ");", 9486 format("static_cast<A<//\n" 9487 " B>*>(\n" 9488 "\n" 9489 " );")); 9490 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9491 " const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);"); 9492 9493 FormatStyle AlwaysBreak = getLLVMStyle(); 9494 AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 9495 verifyFormat("template <typename T>\nclass C {};", AlwaysBreak); 9496 verifyFormat("template <typename T>\nvoid f();", AlwaysBreak); 9497 verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak); 9498 verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9499 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n" 9500 " ccccccccccccccccccccccccccccccccccccccccccccccc);"); 9501 verifyFormat("template <template <typename> class Fooooooo,\n" 9502 " template <typename> class Baaaaaaar>\n" 9503 "struct C {};", 9504 AlwaysBreak); 9505 verifyFormat("template <typename T> // T can be A, B or C.\n" 9506 "struct C {};", 9507 AlwaysBreak); 9508 verifyFormat("template <enum E> class A {\n" 9509 "public:\n" 9510 " E *f();\n" 9511 "};"); 9512 9513 FormatStyle NeverBreak = getLLVMStyle(); 9514 NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No; 9515 verifyFormat("template <typename T> class C {};", NeverBreak); 9516 verifyFormat("template <typename T> void f();", NeverBreak); 9517 verifyFormat("template <typename T> void f() {}", NeverBreak); 9518 verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa " 9519 "bbbbbbbbbbbbbbbbbbbb) {}", 9520 NeverBreak); 9521 verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9522 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n" 9523 " ccccccccccccccccccccccccccccccccccccccccccccccc);", 9524 NeverBreak); 9525 verifyFormat("template <template <typename> class Fooooooo,\n" 9526 " template <typename> class Baaaaaaar>\n" 9527 "struct C {};", 9528 NeverBreak); 9529 verifyFormat("template <typename T> // T can be A, B or C.\n" 9530 "struct C {};", 9531 NeverBreak); 9532 verifyFormat("template <enum E> class A {\n" 9533 "public:\n" 9534 " E *f();\n" 9535 "};", 9536 NeverBreak); 9537 NeverBreak.PenaltyBreakTemplateDeclaration = 100; 9538 verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa " 9539 "bbbbbbbbbbbbbbbbbbbb) {}", 9540 NeverBreak); 9541 } 9542 9543 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) { 9544 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp); 9545 Style.ColumnLimit = 60; 9546 EXPECT_EQ("// Baseline - no comments.\n" 9547 "template <\n" 9548 " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n" 9549 "void f() {}", 9550 format("// Baseline - no comments.\n" 9551 "template <\n" 9552 " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n" 9553 "void f() {}", 9554 Style)); 9555 9556 EXPECT_EQ("template <\n" 9557 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9558 "void f() {}", 9559 format("template <\n" 9560 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9561 "void f() {}", 9562 Style)); 9563 9564 EXPECT_EQ( 9565 "template <\n" 9566 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n" 9567 "void f() {}", 9568 format("template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n" 9569 "void f() {}", 9570 Style)); 9571 9572 EXPECT_EQ( 9573 "template <\n" 9574 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9575 " // multiline\n" 9576 "void f() {}", 9577 format("template <\n" 9578 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9579 " // multiline\n" 9580 "void f() {}", 9581 Style)); 9582 9583 EXPECT_EQ( 9584 "template <typename aaaaaaaaaa<\n" 9585 " bbbbbbbbbbbb>::value> // trailing loooong\n" 9586 "void f() {}", 9587 format( 9588 "template <\n" 9589 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n" 9590 "void f() {}", 9591 Style)); 9592 } 9593 9594 TEST_F(FormatTest, WrapsTemplateParameters) { 9595 FormatStyle Style = getLLVMStyle(); 9596 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 9597 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 9598 verifyFormat( 9599 "template <typename... a> struct q {};\n" 9600 "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n" 9601 " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n" 9602 " y;", 9603 Style); 9604 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 9605 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 9606 verifyFormat( 9607 "template <typename... a> struct r {};\n" 9608 "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n" 9609 " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n" 9610 " y;", 9611 Style); 9612 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 9613 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 9614 verifyFormat("template <typename... a> struct s {};\n" 9615 "extern s<\n" 9616 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9617 "aaaaaaaaaaaaaaaaaaaaaa,\n" 9618 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9619 "aaaaaaaaaaaaaaaaaaaaaa>\n" 9620 " y;", 9621 Style); 9622 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 9623 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 9624 verifyFormat("template <typename... a> struct t {};\n" 9625 "extern t<\n" 9626 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9627 "aaaaaaaaaaaaaaaaaaaaaa,\n" 9628 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9629 "aaaaaaaaaaaaaaaaaaaaaa>\n" 9630 " y;", 9631 Style); 9632 } 9633 9634 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) { 9635 verifyFormat( 9636 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9637 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9638 verifyFormat( 9639 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9640 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9641 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());"); 9642 9643 // FIXME: Should we have the extra indent after the second break? 9644 verifyFormat( 9645 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9646 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9647 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9648 9649 verifyFormat( 9650 "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n" 9651 " cccccccccccccccccccccccccccccccccccccccccccccc());"); 9652 9653 // Breaking at nested name specifiers is generally not desirable. 9654 verifyFormat( 9655 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9656 " aaaaaaaaaaaaaaaaaaaaaaa);"); 9657 9658 verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n" 9659 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9660 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9661 " aaaaaaaaaaaaaaaaaaaaa);", 9662 getLLVMStyleWithColumns(74)); 9663 9664 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9665 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9666 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9667 } 9668 9669 TEST_F(FormatTest, UnderstandsTemplateParameters) { 9670 verifyFormat("A<int> a;"); 9671 verifyFormat("A<A<A<int>>> a;"); 9672 verifyFormat("A<A<A<int, 2>, 3>, 4> a;"); 9673 verifyFormat("bool x = a < 1 || 2 > a;"); 9674 verifyFormat("bool x = 5 < f<int>();"); 9675 verifyFormat("bool x = f<int>() > 5;"); 9676 verifyFormat("bool x = 5 < a<int>::x;"); 9677 verifyFormat("bool x = a < 4 ? a > 2 : false;"); 9678 verifyFormat("bool x = f() ? a < 2 : a > 2;"); 9679 9680 verifyGoogleFormat("A<A<int>> a;"); 9681 verifyGoogleFormat("A<A<A<int>>> a;"); 9682 verifyGoogleFormat("A<A<A<A<int>>>> a;"); 9683 verifyGoogleFormat("A<A<int> > a;"); 9684 verifyGoogleFormat("A<A<A<int> > > a;"); 9685 verifyGoogleFormat("A<A<A<A<int> > > > a;"); 9686 verifyGoogleFormat("A<::A<int>> a;"); 9687 verifyGoogleFormat("A<::A> a;"); 9688 verifyGoogleFormat("A< ::A> a;"); 9689 verifyGoogleFormat("A< ::A<int> > a;"); 9690 EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle())); 9691 EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle())); 9692 EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle())); 9693 EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle())); 9694 EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };", 9695 format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle())); 9696 9697 verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp)); 9698 9699 // template closer followed by a token that starts with > or = 9700 verifyFormat("bool b = a<1> > 1;"); 9701 verifyFormat("bool b = a<1> >= 1;"); 9702 verifyFormat("int i = a<1> >> 1;"); 9703 FormatStyle Style = getLLVMStyle(); 9704 Style.SpaceBeforeAssignmentOperators = false; 9705 verifyFormat("bool b= a<1> == 1;", Style); 9706 verifyFormat("a<int> = 1;", Style); 9707 verifyFormat("a<int> >>= 1;", Style); 9708 9709 verifyFormat("test < a | b >> c;"); 9710 verifyFormat("test<test<a | b>> c;"); 9711 verifyFormat("test >> a >> b;"); 9712 verifyFormat("test << a >> b;"); 9713 9714 verifyFormat("f<int>();"); 9715 verifyFormat("template <typename T> void f() {}"); 9716 verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;"); 9717 verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : " 9718 "sizeof(char)>::type>;"); 9719 verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};"); 9720 verifyFormat("f(a.operator()<A>());"); 9721 verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9722 " .template operator()<A>());", 9723 getLLVMStyleWithColumns(35)); 9724 verifyFormat("bool_constant<a && noexcept(f())>"); 9725 verifyFormat("bool_constant<a || noexcept(f())>"); 9726 9727 // Not template parameters. 9728 verifyFormat("return a < b && c > d;"); 9729 verifyFormat("void f() {\n" 9730 " while (a < b && c > d) {\n" 9731 " }\n" 9732 "}"); 9733 verifyFormat("template <typename... Types>\n" 9734 "typename enable_if<0 < sizeof...(Types)>::type Foo() {}"); 9735 9736 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9737 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);", 9738 getLLVMStyleWithColumns(60)); 9739 verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");"); 9740 verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}"); 9741 verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <"); 9742 verifyFormat("some_templated_type<decltype([](int i) { return i; })>"); 9743 } 9744 9745 TEST_F(FormatTest, UnderstandsShiftOperators) { 9746 verifyFormat("if (i < x >> 1)"); 9747 verifyFormat("while (i < x >> 1)"); 9748 verifyFormat("for (unsigned i = 0; i < i; ++i, v = v >> 1)"); 9749 verifyFormat("for (unsigned i = 0; i < x >> 1; ++i, v = v >> 1)"); 9750 verifyFormat( 9751 "for (std::vector<int>::iterator i = 0; i < x >> 1; ++i, v = v >> 1)"); 9752 verifyFormat("Foo.call<Bar<Function>>()"); 9753 verifyFormat("if (Foo.call<Bar<Function>>() == 0)"); 9754 verifyFormat("for (std::vector<std::pair<int>>::iterator i = 0; i < x >> 1; " 9755 "++i, v = v >> 1)"); 9756 verifyFormat("if (w<u<v<x>>, 1>::t)"); 9757 } 9758 9759 TEST_F(FormatTest, BitshiftOperatorWidth) { 9760 EXPECT_EQ("int a = 1 << 2; /* foo\n" 9761 " bar */", 9762 format("int a=1<<2; /* foo\n" 9763 " bar */")); 9764 9765 EXPECT_EQ("int b = 256 >> 1; /* foo\n" 9766 " bar */", 9767 format("int b =256>>1 ; /* foo\n" 9768 " bar */")); 9769 } 9770 9771 TEST_F(FormatTest, UnderstandsBinaryOperators) { 9772 verifyFormat("COMPARE(a, ==, b);"); 9773 verifyFormat("auto s = sizeof...(Ts) - 1;"); 9774 } 9775 9776 TEST_F(FormatTest, UnderstandsPointersToMembers) { 9777 verifyFormat("int A::*x;"); 9778 verifyFormat("int (S::*func)(void *);"); 9779 verifyFormat("void f() { int (S::*func)(void *); }"); 9780 verifyFormat("typedef bool *(Class::*Member)() const;"); 9781 verifyFormat("void f() {\n" 9782 " (a->*f)();\n" 9783 " a->*x;\n" 9784 " (a.*f)();\n" 9785 " ((*a).*f)();\n" 9786 " a.*x;\n" 9787 "}"); 9788 verifyFormat("void f() {\n" 9789 " (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n" 9790 " aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n" 9791 "}"); 9792 verifyFormat( 9793 "(aaaaaaaaaa->*bbbbbbb)(\n" 9794 " aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 9795 FormatStyle Style = getLLVMStyle(); 9796 Style.PointerAlignment = FormatStyle::PAS_Left; 9797 verifyFormat("typedef bool* (Class::*Member)() const;", Style); 9798 } 9799 9800 TEST_F(FormatTest, UnderstandsUnaryOperators) { 9801 verifyFormat("int a = -2;"); 9802 verifyFormat("f(-1, -2, -3);"); 9803 verifyFormat("a[-1] = 5;"); 9804 verifyFormat("int a = 5 + -2;"); 9805 verifyFormat("if (i == -1) {\n}"); 9806 verifyFormat("if (i != -1) {\n}"); 9807 verifyFormat("if (i > -1) {\n}"); 9808 verifyFormat("if (i < -1) {\n}"); 9809 verifyFormat("++(a->f());"); 9810 verifyFormat("--(a->f());"); 9811 verifyFormat("(a->f())++;"); 9812 verifyFormat("a[42]++;"); 9813 verifyFormat("if (!(a->f())) {\n}"); 9814 verifyFormat("if (!+i) {\n}"); 9815 verifyFormat("~&a;"); 9816 verifyFormat("for (x = 0; -10 < x; --x) {\n}"); 9817 verifyFormat("sizeof -x"); 9818 verifyFormat("sizeof +x"); 9819 verifyFormat("sizeof *x"); 9820 verifyFormat("sizeof &x"); 9821 verifyFormat("delete +x;"); 9822 verifyFormat("co_await +x;"); 9823 verifyFormat("case *x:"); 9824 verifyFormat("case &x:"); 9825 9826 verifyFormat("a-- > b;"); 9827 verifyFormat("b ? -a : c;"); 9828 verifyFormat("n * sizeof char16;"); 9829 verifyFormat("n * alignof char16;", getGoogleStyle()); 9830 verifyFormat("sizeof(char);"); 9831 verifyFormat("alignof(char);", getGoogleStyle()); 9832 9833 verifyFormat("return -1;"); 9834 verifyFormat("throw -1;"); 9835 verifyFormat("switch (a) {\n" 9836 "case -1:\n" 9837 " break;\n" 9838 "}"); 9839 verifyFormat("#define X -1"); 9840 verifyFormat("#define X -kConstant"); 9841 9842 verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};"); 9843 verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};"); 9844 9845 verifyFormat("int a = /* confusing comment */ -1;"); 9846 // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case. 9847 verifyFormat("int a = i /* confusing comment */++;"); 9848 9849 verifyFormat("co_yield -1;"); 9850 verifyFormat("co_return -1;"); 9851 9852 // Check that * is not treated as a binary operator when we set 9853 // PointerAlignment as PAS_Left after a keyword and not a declaration. 9854 FormatStyle PASLeftStyle = getLLVMStyle(); 9855 PASLeftStyle.PointerAlignment = FormatStyle::PAS_Left; 9856 verifyFormat("co_return *a;", PASLeftStyle); 9857 verifyFormat("co_await *a;", PASLeftStyle); 9858 verifyFormat("co_yield *a", PASLeftStyle); 9859 verifyFormat("return *a;", PASLeftStyle); 9860 } 9861 9862 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) { 9863 verifyFormat("if (!aaaaaaaaaa( // break\n" 9864 " aaaaa)) {\n" 9865 "}"); 9866 verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n" 9867 " aaaaa));"); 9868 verifyFormat("*aaa = aaaaaaa( // break\n" 9869 " bbbbbb);"); 9870 } 9871 9872 TEST_F(FormatTest, UnderstandsOverloadedOperators) { 9873 verifyFormat("bool operator<();"); 9874 verifyFormat("bool operator>();"); 9875 verifyFormat("bool operator=();"); 9876 verifyFormat("bool operator==();"); 9877 verifyFormat("bool operator!=();"); 9878 verifyFormat("int operator+();"); 9879 verifyFormat("int operator++();"); 9880 verifyFormat("int operator++(int) volatile noexcept;"); 9881 verifyFormat("bool operator,();"); 9882 verifyFormat("bool operator();"); 9883 verifyFormat("bool operator()();"); 9884 verifyFormat("bool operator[]();"); 9885 verifyFormat("operator bool();"); 9886 verifyFormat("operator int();"); 9887 verifyFormat("operator void *();"); 9888 verifyFormat("operator SomeType<int>();"); 9889 verifyFormat("operator SomeType<int, int>();"); 9890 verifyFormat("operator SomeType<SomeType<int>>();"); 9891 verifyFormat("operator< <>();"); 9892 verifyFormat("operator<< <>();"); 9893 verifyFormat("< <>"); 9894 9895 verifyFormat("void *operator new(std::size_t size);"); 9896 verifyFormat("void *operator new[](std::size_t size);"); 9897 verifyFormat("void operator delete(void *ptr);"); 9898 verifyFormat("void operator delete[](void *ptr);"); 9899 verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n" 9900 "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);"); 9901 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n" 9902 " aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;"); 9903 9904 verifyFormat( 9905 "ostream &operator<<(ostream &OutputStream,\n" 9906 " SomeReallyLongType WithSomeReallyLongValue);"); 9907 verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n" 9908 " const aaaaaaaaaaaaaaaaaaaaa &right) {\n" 9909 " return left.group < right.group;\n" 9910 "}"); 9911 verifyFormat("SomeType &operator=(const SomeType &S);"); 9912 verifyFormat("f.template operator()<int>();"); 9913 9914 verifyGoogleFormat("operator void*();"); 9915 verifyGoogleFormat("operator SomeType<SomeType<int>>();"); 9916 verifyGoogleFormat("operator ::A();"); 9917 9918 verifyFormat("using A::operator+;"); 9919 verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n" 9920 "int i;"); 9921 9922 // Calling an operator as a member function. 9923 verifyFormat("void f() { a.operator*(); }"); 9924 verifyFormat("void f() { a.operator*(b & b); }"); 9925 verifyFormat("void f() { a->operator&(a * b); }"); 9926 verifyFormat("void f() { NS::a.operator+(*b * *b); }"); 9927 // TODO: Calling an operator as a non-member function is hard to distinguish. 9928 // https://llvm.org/PR50629 9929 // verifyFormat("void f() { operator*(a & a); }"); 9930 // verifyFormat("void f() { operator&(a, b * b); }"); 9931 9932 verifyFormat("::operator delete(foo);"); 9933 verifyFormat("::operator new(n * sizeof(foo));"); 9934 verifyFormat("foo() { ::operator delete(foo); }"); 9935 verifyFormat("foo() { ::operator new(n * sizeof(foo)); }"); 9936 } 9937 9938 TEST_F(FormatTest, UnderstandsFunctionRefQualification) { 9939 verifyFormat("void A::b() && {}"); 9940 verifyFormat("void A::b() &&noexcept {}"); 9941 verifyFormat("Deleted &operator=(const Deleted &) & = default;"); 9942 verifyFormat("Deleted &operator=(const Deleted &) && = delete;"); 9943 verifyFormat("Deleted &operator=(const Deleted &) &noexcept = default;"); 9944 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;"); 9945 verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;"); 9946 verifyFormat("Deleted &operator=(const Deleted &) &;"); 9947 verifyFormat("Deleted &operator=(const Deleted &) &&;"); 9948 verifyFormat("SomeType MemberFunction(const Deleted &) &;"); 9949 verifyFormat("SomeType MemberFunction(const Deleted &) &&;"); 9950 verifyFormat("SomeType MemberFunction(const Deleted &) && {}"); 9951 verifyFormat("SomeType MemberFunction(const Deleted &) && final {}"); 9952 verifyFormat("SomeType MemberFunction(const Deleted &) && override {}"); 9953 verifyFormat("SomeType MemberFunction(const Deleted &) &&noexcept {}"); 9954 verifyFormat("void Fn(T const &) const &;"); 9955 verifyFormat("void Fn(T const volatile &&) const volatile &&;"); 9956 verifyFormat("void Fn(T const volatile &&) const volatile &&noexcept;"); 9957 verifyFormat("template <typename T>\n" 9958 "void F(T) && = delete;", 9959 getGoogleStyle()); 9960 verifyFormat("template <typename T> void operator=(T) &;"); 9961 verifyFormat("template <typename T> void operator=(T) const &;"); 9962 verifyFormat("template <typename T> void operator=(T) &noexcept;"); 9963 verifyFormat("template <typename T> void operator=(T) & = default;"); 9964 verifyFormat("template <typename T> void operator=(T) &&;"); 9965 verifyFormat("template <typename T> void operator=(T) && = delete;"); 9966 verifyFormat("template <typename T> void operator=(T) & {}"); 9967 verifyFormat("template <typename T> void operator=(T) && {}"); 9968 9969 FormatStyle AlignLeft = getLLVMStyle(); 9970 AlignLeft.PointerAlignment = FormatStyle::PAS_Left; 9971 verifyFormat("void A::b() && {}", AlignLeft); 9972 verifyFormat("void A::b() && noexcept {}", AlignLeft); 9973 verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft); 9974 verifyFormat("Deleted& operator=(const Deleted&) & noexcept = default;", 9975 AlignLeft); 9976 verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;", 9977 AlignLeft); 9978 verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft); 9979 verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft); 9980 verifyFormat("auto Function(T t) & -> void {}", AlignLeft); 9981 verifyFormat("auto Function(T... t) & -> void {}", AlignLeft); 9982 verifyFormat("auto Function(T) & -> void {}", AlignLeft); 9983 verifyFormat("auto Function(T) & -> void;", AlignLeft); 9984 verifyFormat("void Fn(T const&) const&;", AlignLeft); 9985 verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft); 9986 verifyFormat("void Fn(T const volatile&&) const volatile&& noexcept;", 9987 AlignLeft); 9988 verifyFormat("template <typename T> void operator=(T) &;", AlignLeft); 9989 verifyFormat("template <typename T> void operator=(T) const&;", AlignLeft); 9990 verifyFormat("template <typename T> void operator=(T) & noexcept;", 9991 AlignLeft); 9992 verifyFormat("template <typename T> void operator=(T) & = default;", 9993 AlignLeft); 9994 verifyFormat("template <typename T> void operator=(T) &&;", AlignLeft); 9995 verifyFormat("template <typename T> void operator=(T) && = delete;", 9996 AlignLeft); 9997 verifyFormat("template <typename T> void operator=(T) & {}", AlignLeft); 9998 verifyFormat("template <typename T> void operator=(T) && {}", AlignLeft); 9999 10000 FormatStyle AlignMiddle = getLLVMStyle(); 10001 AlignMiddle.PointerAlignment = FormatStyle::PAS_Middle; 10002 verifyFormat("void A::b() && {}", AlignMiddle); 10003 verifyFormat("void A::b() && noexcept {}", AlignMiddle); 10004 verifyFormat("Deleted & operator=(const Deleted &) & = default;", 10005 AlignMiddle); 10006 verifyFormat("Deleted & operator=(const Deleted &) & noexcept = default;", 10007 AlignMiddle); 10008 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", 10009 AlignMiddle); 10010 verifyFormat("Deleted & operator=(const Deleted &) &;", AlignMiddle); 10011 verifyFormat("SomeType MemberFunction(const Deleted &) &;", AlignMiddle); 10012 verifyFormat("auto Function(T t) & -> void {}", AlignMiddle); 10013 verifyFormat("auto Function(T... t) & -> void {}", AlignMiddle); 10014 verifyFormat("auto Function(T) & -> void {}", AlignMiddle); 10015 verifyFormat("auto Function(T) & -> void;", AlignMiddle); 10016 verifyFormat("void Fn(T const &) const &;", AlignMiddle); 10017 verifyFormat("void Fn(T const volatile &&) const volatile &&;", AlignMiddle); 10018 verifyFormat("void Fn(T const volatile &&) const volatile && noexcept;", 10019 AlignMiddle); 10020 verifyFormat("template <typename T> void operator=(T) &;", AlignMiddle); 10021 verifyFormat("template <typename T> void operator=(T) const &;", AlignMiddle); 10022 verifyFormat("template <typename T> void operator=(T) & noexcept;", 10023 AlignMiddle); 10024 verifyFormat("template <typename T> void operator=(T) & = default;", 10025 AlignMiddle); 10026 verifyFormat("template <typename T> void operator=(T) &&;", AlignMiddle); 10027 verifyFormat("template <typename T> void operator=(T) && = delete;", 10028 AlignMiddle); 10029 verifyFormat("template <typename T> void operator=(T) & {}", AlignMiddle); 10030 verifyFormat("template <typename T> void operator=(T) && {}", AlignMiddle); 10031 10032 FormatStyle Spaces = getLLVMStyle(); 10033 Spaces.SpacesInCStyleCastParentheses = true; 10034 verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces); 10035 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces); 10036 verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces); 10037 verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces); 10038 10039 Spaces.SpacesInCStyleCastParentheses = false; 10040 Spaces.SpacesInParentheses = true; 10041 verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces); 10042 verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;", 10043 Spaces); 10044 verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces); 10045 verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces); 10046 10047 FormatStyle BreakTemplate = getLLVMStyle(); 10048 BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 10049 10050 verifyFormat("struct f {\n" 10051 " template <class T>\n" 10052 " int &foo(const std::string &str) &noexcept {}\n" 10053 "};", 10054 BreakTemplate); 10055 10056 verifyFormat("struct f {\n" 10057 " template <class T>\n" 10058 " int &foo(const std::string &str) &&noexcept {}\n" 10059 "};", 10060 BreakTemplate); 10061 10062 verifyFormat("struct f {\n" 10063 " template <class T>\n" 10064 " int &foo(const std::string &str) const &noexcept {}\n" 10065 "};", 10066 BreakTemplate); 10067 10068 verifyFormat("struct f {\n" 10069 " template <class T>\n" 10070 " int &foo(const std::string &str) const &noexcept {}\n" 10071 "};", 10072 BreakTemplate); 10073 10074 verifyFormat("struct f {\n" 10075 " template <class T>\n" 10076 " auto foo(const std::string &str) &&noexcept -> int & {}\n" 10077 "};", 10078 BreakTemplate); 10079 10080 FormatStyle AlignLeftBreakTemplate = getLLVMStyle(); 10081 AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations = 10082 FormatStyle::BTDS_Yes; 10083 AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left; 10084 10085 verifyFormat("struct f {\n" 10086 " template <class T>\n" 10087 " int& foo(const std::string& str) & noexcept {}\n" 10088 "};", 10089 AlignLeftBreakTemplate); 10090 10091 verifyFormat("struct f {\n" 10092 " template <class T>\n" 10093 " int& foo(const std::string& str) && noexcept {}\n" 10094 "};", 10095 AlignLeftBreakTemplate); 10096 10097 verifyFormat("struct f {\n" 10098 " template <class T>\n" 10099 " int& foo(const std::string& str) const& noexcept {}\n" 10100 "};", 10101 AlignLeftBreakTemplate); 10102 10103 verifyFormat("struct f {\n" 10104 " template <class T>\n" 10105 " int& foo(const std::string& str) const&& noexcept {}\n" 10106 "};", 10107 AlignLeftBreakTemplate); 10108 10109 verifyFormat("struct f {\n" 10110 " template <class T>\n" 10111 " auto foo(const std::string& str) && noexcept -> int& {}\n" 10112 "};", 10113 AlignLeftBreakTemplate); 10114 10115 // The `&` in `Type&` should not be confused with a trailing `&` of 10116 // DEPRECATED(reason) member function. 10117 verifyFormat("struct f {\n" 10118 " template <class T>\n" 10119 " DEPRECATED(reason)\n" 10120 " Type &foo(arguments) {}\n" 10121 "};", 10122 BreakTemplate); 10123 10124 verifyFormat("struct f {\n" 10125 " template <class T>\n" 10126 " DEPRECATED(reason)\n" 10127 " Type& foo(arguments) {}\n" 10128 "};", 10129 AlignLeftBreakTemplate); 10130 10131 verifyFormat("void (*foopt)(int) = &func;"); 10132 10133 FormatStyle DerivePointerAlignment = getLLVMStyle(); 10134 DerivePointerAlignment.DerivePointerAlignment = true; 10135 // There's always a space between the function and its trailing qualifiers. 10136 // This isn't evidence for PAS_Right (or for PAS_Left). 10137 std::string Prefix = "void a() &;\n" 10138 "void b() &;\n"; 10139 verifyFormat(Prefix + "int* x;", DerivePointerAlignment); 10140 verifyFormat(Prefix + "int *x;", DerivePointerAlignment); 10141 // Same if the function is an overloaded operator, and with &&. 10142 Prefix = "void operator()() &&;\n" 10143 "void operator()() &&;\n"; 10144 verifyFormat(Prefix + "int* x;", DerivePointerAlignment); 10145 verifyFormat(Prefix + "int *x;", DerivePointerAlignment); 10146 // However a space between cv-qualifiers and ref-qualifiers *is* evidence. 10147 Prefix = "void a() const &;\n" 10148 "void b() const &;\n"; 10149 EXPECT_EQ(Prefix + "int *x;", 10150 format(Prefix + "int* x;", DerivePointerAlignment)); 10151 } 10152 10153 TEST_F(FormatTest, UnderstandsNewAndDelete) { 10154 verifyFormat("void f() {\n" 10155 " A *a = new A;\n" 10156 " A *a = new (placement) A;\n" 10157 " delete a;\n" 10158 " delete (A *)a;\n" 10159 "}"); 10160 verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n" 10161 " typename aaaaaaaaaaaaaaaaaaaaaaaa();"); 10162 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 10163 " new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n" 10164 " typename aaaaaaaaaaaaaaaaaaaaaaaa();"); 10165 verifyFormat("delete[] h->p;"); 10166 verifyFormat("delete[] (void *)p;"); 10167 10168 verifyFormat("void operator delete(void *foo) ATTRIB;"); 10169 verifyFormat("void operator new(void *foo) ATTRIB;"); 10170 verifyFormat("void operator delete[](void *foo) ATTRIB;"); 10171 verifyFormat("void operator delete(void *ptr) noexcept;"); 10172 10173 EXPECT_EQ("void new(link p);\n" 10174 "void delete(link p);\n", 10175 format("void new (link p);\n" 10176 "void delete (link p);\n")); 10177 } 10178 10179 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) { 10180 verifyFormat("int *f(int *a) {}"); 10181 verifyFormat("int main(int argc, char **argv) {}"); 10182 verifyFormat("Test::Test(int b) : a(b * b) {}"); 10183 verifyIndependentOfContext("f(a, *a);"); 10184 verifyFormat("void g() { f(*a); }"); 10185 verifyIndependentOfContext("int a = b * 10;"); 10186 verifyIndependentOfContext("int a = 10 * b;"); 10187 verifyIndependentOfContext("int a = b * c;"); 10188 verifyIndependentOfContext("int a += b * c;"); 10189 verifyIndependentOfContext("int a -= b * c;"); 10190 verifyIndependentOfContext("int a *= b * c;"); 10191 verifyIndependentOfContext("int a /= b * c;"); 10192 verifyIndependentOfContext("int a = *b;"); 10193 verifyIndependentOfContext("int a = *b * c;"); 10194 verifyIndependentOfContext("int a = b * *c;"); 10195 verifyIndependentOfContext("int a = b * (10);"); 10196 verifyIndependentOfContext("S << b * (10);"); 10197 verifyIndependentOfContext("return 10 * b;"); 10198 verifyIndependentOfContext("return *b * *c;"); 10199 verifyIndependentOfContext("return a & ~b;"); 10200 verifyIndependentOfContext("f(b ? *c : *d);"); 10201 verifyIndependentOfContext("int a = b ? *c : *d;"); 10202 verifyIndependentOfContext("*b = a;"); 10203 verifyIndependentOfContext("a * ~b;"); 10204 verifyIndependentOfContext("a * !b;"); 10205 verifyIndependentOfContext("a * +b;"); 10206 verifyIndependentOfContext("a * -b;"); 10207 verifyIndependentOfContext("a * ++b;"); 10208 verifyIndependentOfContext("a * --b;"); 10209 verifyIndependentOfContext("a[4] * b;"); 10210 verifyIndependentOfContext("a[a * a] = 1;"); 10211 verifyIndependentOfContext("f() * b;"); 10212 verifyIndependentOfContext("a * [self dostuff];"); 10213 verifyIndependentOfContext("int x = a * (a + b);"); 10214 verifyIndependentOfContext("(a *)(a + b);"); 10215 verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;"); 10216 verifyIndependentOfContext("int *pa = (int *)&a;"); 10217 verifyIndependentOfContext("return sizeof(int **);"); 10218 verifyIndependentOfContext("return sizeof(int ******);"); 10219 verifyIndependentOfContext("return (int **&)a;"); 10220 verifyIndependentOfContext("f((*PointerToArray)[10]);"); 10221 verifyFormat("void f(Type (*parameter)[10]) {}"); 10222 verifyFormat("void f(Type (¶meter)[10]) {}"); 10223 verifyGoogleFormat("return sizeof(int**);"); 10224 verifyIndependentOfContext("Type **A = static_cast<Type **>(P);"); 10225 verifyGoogleFormat("Type** A = static_cast<Type**>(P);"); 10226 verifyFormat("auto a = [](int **&, int ***) {};"); 10227 verifyFormat("auto PointerBinding = [](const char *S) {};"); 10228 verifyFormat("typedef typeof(int(int, int)) *MyFunc;"); 10229 verifyFormat("[](const decltype(*a) &value) {}"); 10230 verifyFormat("[](const typeof(*a) &value) {}"); 10231 verifyFormat("[](const _Atomic(a *) &value) {}"); 10232 verifyFormat("[](const __underlying_type(a) &value) {}"); 10233 verifyFormat("decltype(a * b) F();"); 10234 verifyFormat("typeof(a * b) F();"); 10235 verifyFormat("#define MACRO() [](A *a) { return 1; }"); 10236 verifyFormat("Constructor() : member([](A *a, B *b) {}) {}"); 10237 verifyIndependentOfContext("typedef void (*f)(int *a);"); 10238 verifyIndependentOfContext("int i{a * b};"); 10239 verifyIndependentOfContext("aaa && aaa->f();"); 10240 verifyIndependentOfContext("int x = ~*p;"); 10241 verifyFormat("Constructor() : a(a), area(width * height) {}"); 10242 verifyFormat("Constructor() : a(a), area(a, width * height) {}"); 10243 verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}"); 10244 verifyFormat("void f() { f(a, c * d); }"); 10245 verifyFormat("void f() { f(new a(), c * d); }"); 10246 verifyFormat("void f(const MyOverride &override);"); 10247 verifyFormat("void f(const MyFinal &final);"); 10248 verifyIndependentOfContext("bool a = f() && override.f();"); 10249 verifyIndependentOfContext("bool a = f() && final.f();"); 10250 10251 verifyIndependentOfContext("InvalidRegions[*R] = 0;"); 10252 10253 verifyIndependentOfContext("A<int *> a;"); 10254 verifyIndependentOfContext("A<int **> a;"); 10255 verifyIndependentOfContext("A<int *, int *> a;"); 10256 verifyIndependentOfContext("A<int *[]> a;"); 10257 verifyIndependentOfContext( 10258 "const char *const p = reinterpret_cast<const char *const>(q);"); 10259 verifyIndependentOfContext("A<int **, int **> a;"); 10260 verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);"); 10261 verifyFormat("for (char **a = b; *a; ++a) {\n}"); 10262 verifyFormat("for (; a && b;) {\n}"); 10263 verifyFormat("bool foo = true && [] { return false; }();"); 10264 10265 verifyFormat( 10266 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 10267 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 10268 10269 verifyGoogleFormat("int const* a = &b;"); 10270 verifyGoogleFormat("**outparam = 1;"); 10271 verifyGoogleFormat("*outparam = a * b;"); 10272 verifyGoogleFormat("int main(int argc, char** argv) {}"); 10273 verifyGoogleFormat("A<int*> a;"); 10274 verifyGoogleFormat("A<int**> a;"); 10275 verifyGoogleFormat("A<int*, int*> a;"); 10276 verifyGoogleFormat("A<int**, int**> a;"); 10277 verifyGoogleFormat("f(b ? *c : *d);"); 10278 verifyGoogleFormat("int a = b ? *c : *d;"); 10279 verifyGoogleFormat("Type* t = **x;"); 10280 verifyGoogleFormat("Type* t = *++*x;"); 10281 verifyGoogleFormat("*++*x;"); 10282 verifyGoogleFormat("Type* t = const_cast<T*>(&*x);"); 10283 verifyGoogleFormat("Type* t = x++ * y;"); 10284 verifyGoogleFormat( 10285 "const char* const p = reinterpret_cast<const char* const>(q);"); 10286 verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);"); 10287 verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);"); 10288 verifyGoogleFormat("template <typename T>\n" 10289 "void f(int i = 0, SomeType** temps = NULL);"); 10290 10291 FormatStyle Left = getLLVMStyle(); 10292 Left.PointerAlignment = FormatStyle::PAS_Left; 10293 verifyFormat("x = *a(x) = *a(y);", Left); 10294 verifyFormat("for (;; *a = b) {\n}", Left); 10295 verifyFormat("return *this += 1;", Left); 10296 verifyFormat("throw *x;", Left); 10297 verifyFormat("delete *x;", Left); 10298 verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left); 10299 verifyFormat("[](const decltype(*a)* ptr) {}", Left); 10300 verifyFormat("[](const typeof(*a)* ptr) {}", Left); 10301 verifyFormat("[](const _Atomic(a*)* ptr) {}", Left); 10302 verifyFormat("[](const __underlying_type(a)* ptr) {}", Left); 10303 verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left); 10304 verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left); 10305 verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left); 10306 verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left); 10307 10308 verifyIndependentOfContext("a = *(x + y);"); 10309 verifyIndependentOfContext("a = &(x + y);"); 10310 verifyIndependentOfContext("*(x + y).call();"); 10311 verifyIndependentOfContext("&(x + y)->call();"); 10312 verifyFormat("void f() { &(*I).first; }"); 10313 10314 verifyIndependentOfContext("f(b * /* confusing comment */ ++c);"); 10315 verifyFormat("f(* /* confusing comment */ foo);"); 10316 verifyFormat("void (* /*deleter*/)(const Slice &key, void *value)"); 10317 verifyFormat("void foo(int * // this is the first paramters\n" 10318 " ,\n" 10319 " int second);"); 10320 verifyFormat("double term = a * // first\n" 10321 " b;"); 10322 verifyFormat( 10323 "int *MyValues = {\n" 10324 " *A, // Operator detection might be confused by the '{'\n" 10325 " *BB // Operator detection might be confused by previous comment\n" 10326 "};"); 10327 10328 verifyIndependentOfContext("if (int *a = &b)"); 10329 verifyIndependentOfContext("if (int &a = *b)"); 10330 verifyIndependentOfContext("if (a & b[i])"); 10331 verifyIndependentOfContext("if constexpr (a & b[i])"); 10332 verifyIndependentOfContext("if CONSTEXPR (a & b[i])"); 10333 verifyIndependentOfContext("if (a * (b * c))"); 10334 verifyIndependentOfContext("if constexpr (a * (b * c))"); 10335 verifyIndependentOfContext("if CONSTEXPR (a * (b * c))"); 10336 verifyIndependentOfContext("if (a::b::c::d & b[i])"); 10337 verifyIndependentOfContext("if (*b[i])"); 10338 verifyIndependentOfContext("if (int *a = (&b))"); 10339 verifyIndependentOfContext("while (int *a = &b)"); 10340 verifyIndependentOfContext("while (a * (b * c))"); 10341 verifyIndependentOfContext("size = sizeof *a;"); 10342 verifyIndependentOfContext("if (a && (b = c))"); 10343 verifyFormat("void f() {\n" 10344 " for (const int &v : Values) {\n" 10345 " }\n" 10346 "}"); 10347 verifyFormat("for (int i = a * a; i < 10; ++i) {\n}"); 10348 verifyFormat("for (int i = 0; i < a * a; ++i) {\n}"); 10349 verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}"); 10350 10351 verifyFormat("#define A (!a * b)"); 10352 verifyFormat("#define MACRO \\\n" 10353 " int *i = a * b; \\\n" 10354 " void f(a *b);", 10355 getLLVMStyleWithColumns(19)); 10356 10357 verifyIndependentOfContext("A = new SomeType *[Length];"); 10358 verifyIndependentOfContext("A = new SomeType *[Length]();"); 10359 verifyIndependentOfContext("T **t = new T *;"); 10360 verifyIndependentOfContext("T **t = new T *();"); 10361 verifyGoogleFormat("A = new SomeType*[Length]();"); 10362 verifyGoogleFormat("A = new SomeType*[Length];"); 10363 verifyGoogleFormat("T** t = new T*;"); 10364 verifyGoogleFormat("T** t = new T*();"); 10365 10366 verifyFormat("STATIC_ASSERT((a & b) == 0);"); 10367 verifyFormat("STATIC_ASSERT(0 == (a & b));"); 10368 verifyFormat("template <bool a, bool b> " 10369 "typename t::if<x && y>::type f() {}"); 10370 verifyFormat("template <int *y> f() {}"); 10371 verifyFormat("vector<int *> v;"); 10372 verifyFormat("vector<int *const> v;"); 10373 verifyFormat("vector<int *const **const *> v;"); 10374 verifyFormat("vector<int *volatile> v;"); 10375 verifyFormat("vector<a *_Nonnull> v;"); 10376 verifyFormat("vector<a *_Nullable> v;"); 10377 verifyFormat("vector<a *_Null_unspecified> v;"); 10378 verifyFormat("vector<a *__ptr32> v;"); 10379 verifyFormat("vector<a *__ptr64> v;"); 10380 verifyFormat("vector<a *__capability> v;"); 10381 FormatStyle TypeMacros = getLLVMStyle(); 10382 TypeMacros.TypenameMacros = {"LIST"}; 10383 verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros); 10384 verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros); 10385 verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros); 10386 verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros); 10387 verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication 10388 10389 FormatStyle CustomQualifier = getLLVMStyle(); 10390 // Add identifiers that should not be parsed as a qualifier by default. 10391 CustomQualifier.AttributeMacros.push_back("__my_qualifier"); 10392 CustomQualifier.AttributeMacros.push_back("_My_qualifier"); 10393 CustomQualifier.AttributeMacros.push_back("my_other_qualifier"); 10394 verifyFormat("vector<a * __my_qualifier> parse_as_multiply;"); 10395 verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier); 10396 verifyFormat("vector<a * _My_qualifier> parse_as_multiply;"); 10397 verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier); 10398 verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;"); 10399 verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier); 10400 verifyFormat("vector<a * _NotAQualifier> v;"); 10401 verifyFormat("vector<a * __not_a_qualifier> v;"); 10402 verifyFormat("vector<a * b> v;"); 10403 verifyFormat("foo<b && false>();"); 10404 verifyFormat("foo<b & 1>();"); 10405 verifyFormat("foo<b & (1)>();"); 10406 verifyFormat("foo<b & (~0)>();"); 10407 verifyFormat("foo<b & (true)>();"); 10408 verifyFormat("foo<b & ((1))>();"); 10409 verifyFormat("foo<b & (/*comment*/ 1)>();"); 10410 verifyFormat("decltype(*::std::declval<const T &>()) void F();"); 10411 verifyFormat("typeof(*::std::declval<const T &>()) void F();"); 10412 verifyFormat("_Atomic(*::std::declval<const T &>()) void F();"); 10413 verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();"); 10414 verifyFormat( 10415 "template <class T, class = typename std::enable_if<\n" 10416 " std::is_integral<T>::value &&\n" 10417 " (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n" 10418 "void F();", 10419 getLLVMStyleWithColumns(70)); 10420 verifyFormat("template <class T,\n" 10421 " class = typename std::enable_if<\n" 10422 " std::is_integral<T>::value &&\n" 10423 " (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n" 10424 " class U>\n" 10425 "void F();", 10426 getLLVMStyleWithColumns(70)); 10427 verifyFormat( 10428 "template <class T,\n" 10429 " class = typename ::std::enable_if<\n" 10430 " ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n" 10431 "void F();", 10432 getGoogleStyleWithColumns(68)); 10433 10434 FormatStyle Style = getLLVMStyle(); 10435 Style.PointerAlignment = FormatStyle::PAS_Left; 10436 verifyFormat("struct {\n" 10437 "}* ptr;", 10438 Style); 10439 verifyFormat("union {\n" 10440 "}* ptr;", 10441 Style); 10442 verifyFormat("class {\n" 10443 "}* ptr;", 10444 Style); 10445 verifyFormat("struct {\n" 10446 "}&& ptr = {};", 10447 Style); 10448 verifyFormat("union {\n" 10449 "}&& ptr = {};", 10450 Style); 10451 verifyFormat("class {\n" 10452 "}&& ptr = {};", 10453 Style); 10454 10455 Style.PointerAlignment = FormatStyle::PAS_Middle; 10456 verifyFormat("struct {\n" 10457 "} * ptr;", 10458 Style); 10459 verifyFormat("union {\n" 10460 "} * ptr;", 10461 Style); 10462 verifyFormat("class {\n" 10463 "} * ptr;", 10464 Style); 10465 verifyFormat("struct {\n" 10466 "} && ptr = {};", 10467 Style); 10468 verifyFormat("union {\n" 10469 "} && ptr = {};", 10470 Style); 10471 verifyFormat("class {\n" 10472 "} && ptr = {};", 10473 Style); 10474 10475 Style.PointerAlignment = FormatStyle::PAS_Right; 10476 verifyFormat("struct {\n" 10477 "} *ptr;", 10478 Style); 10479 verifyFormat("union {\n" 10480 "} *ptr;", 10481 Style); 10482 verifyFormat("class {\n" 10483 "} *ptr;", 10484 Style); 10485 verifyFormat("struct {\n" 10486 "} &&ptr = {};", 10487 Style); 10488 verifyFormat("union {\n" 10489 "} &&ptr = {};", 10490 Style); 10491 verifyFormat("class {\n" 10492 "} &&ptr = {};", 10493 Style); 10494 10495 verifyIndependentOfContext("MACRO(int *i);"); 10496 verifyIndependentOfContext("MACRO(auto *a);"); 10497 verifyIndependentOfContext("MACRO(const A *a);"); 10498 verifyIndependentOfContext("MACRO(_Atomic(A) *a);"); 10499 verifyIndependentOfContext("MACRO(decltype(A) *a);"); 10500 verifyIndependentOfContext("MACRO(typeof(A) *a);"); 10501 verifyIndependentOfContext("MACRO(__underlying_type(A) *a);"); 10502 verifyIndependentOfContext("MACRO(A *const a);"); 10503 verifyIndependentOfContext("MACRO(A *restrict a);"); 10504 verifyIndependentOfContext("MACRO(A *__restrict__ a);"); 10505 verifyIndependentOfContext("MACRO(A *__restrict a);"); 10506 verifyIndependentOfContext("MACRO(A *volatile a);"); 10507 verifyIndependentOfContext("MACRO(A *__volatile a);"); 10508 verifyIndependentOfContext("MACRO(A *__volatile__ a);"); 10509 verifyIndependentOfContext("MACRO(A *_Nonnull a);"); 10510 verifyIndependentOfContext("MACRO(A *_Nullable a);"); 10511 verifyIndependentOfContext("MACRO(A *_Null_unspecified a);"); 10512 verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);"); 10513 verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);"); 10514 verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);"); 10515 verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);"); 10516 verifyIndependentOfContext("MACRO(A *__ptr32 a);"); 10517 verifyIndependentOfContext("MACRO(A *__ptr64 a);"); 10518 verifyIndependentOfContext("MACRO(A *__capability);"); 10519 verifyIndependentOfContext("MACRO(A &__capability);"); 10520 verifyFormat("MACRO(A *__my_qualifier);"); // type declaration 10521 verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication 10522 // If we add __my_qualifier to AttributeMacros it should always be parsed as 10523 // a type declaration: 10524 verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier); 10525 verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier); 10526 // Also check that TypenameMacros prevents parsing it as multiplication: 10527 verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication 10528 verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type 10529 10530 verifyIndependentOfContext("MACRO('0' <= c && c <= '9');"); 10531 verifyFormat("void f() { f(float{1}, a * a); }"); 10532 verifyFormat("void f() { f(float(1), a * a); }"); 10533 10534 verifyFormat("f((void (*)(int))g);"); 10535 verifyFormat("f((void (&)(int))g);"); 10536 verifyFormat("f((void (^)(int))g);"); 10537 10538 // FIXME: Is there a way to make this work? 10539 // verifyIndependentOfContext("MACRO(A *a);"); 10540 verifyFormat("MACRO(A &B);"); 10541 verifyFormat("MACRO(A *B);"); 10542 verifyFormat("void f() { MACRO(A * B); }"); 10543 verifyFormat("void f() { MACRO(A & B); }"); 10544 10545 // This lambda was mis-formatted after D88956 (treating it as a binop): 10546 verifyFormat("auto x = [](const decltype(x) &ptr) {};"); 10547 verifyFormat("auto x = [](const decltype(x) *ptr) {};"); 10548 verifyFormat("#define lambda [](const decltype(x) &ptr) {}"); 10549 verifyFormat("#define lambda [](const decltype(x) *ptr) {}"); 10550 10551 verifyFormat("DatumHandle const *operator->() const { return input_; }"); 10552 verifyFormat("return options != nullptr && operator==(*options);"); 10553 10554 EXPECT_EQ("#define OP(x) \\\n" 10555 " ostream &operator<<(ostream &s, const A &a) { \\\n" 10556 " return s << a.DebugString(); \\\n" 10557 " }", 10558 format("#define OP(x) \\\n" 10559 " ostream &operator<<(ostream &s, const A &a) { \\\n" 10560 " return s << a.DebugString(); \\\n" 10561 " }", 10562 getLLVMStyleWithColumns(50))); 10563 10564 // FIXME: We cannot handle this case yet; we might be able to figure out that 10565 // foo<x> d > v; doesn't make sense. 10566 verifyFormat("foo<a<b && c> d> v;"); 10567 10568 FormatStyle PointerMiddle = getLLVMStyle(); 10569 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle; 10570 verifyFormat("delete *x;", PointerMiddle); 10571 verifyFormat("int * x;", PointerMiddle); 10572 verifyFormat("int *[] x;", PointerMiddle); 10573 verifyFormat("template <int * y> f() {}", PointerMiddle); 10574 verifyFormat("int * f(int * a) {}", PointerMiddle); 10575 verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle); 10576 verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle); 10577 verifyFormat("A<int *> a;", PointerMiddle); 10578 verifyFormat("A<int **> a;", PointerMiddle); 10579 verifyFormat("A<int *, int *> a;", PointerMiddle); 10580 verifyFormat("A<int *[]> a;", PointerMiddle); 10581 verifyFormat("A = new SomeType *[Length]();", PointerMiddle); 10582 verifyFormat("A = new SomeType *[Length];", PointerMiddle); 10583 verifyFormat("T ** t = new T *;", PointerMiddle); 10584 10585 // Member function reference qualifiers aren't binary operators. 10586 verifyFormat("string // break\n" 10587 "operator()() & {}"); 10588 verifyFormat("string // break\n" 10589 "operator()() && {}"); 10590 verifyGoogleFormat("template <typename T>\n" 10591 "auto x() & -> int {}"); 10592 10593 // Should be binary operators when used as an argument expression (overloaded 10594 // operator invoked as a member function). 10595 verifyFormat("void f() { a.operator()(a * a); }"); 10596 verifyFormat("void f() { a->operator()(a & a); }"); 10597 verifyFormat("void f() { a.operator()(*a & *a); }"); 10598 verifyFormat("void f() { a->operator()(*a * *a); }"); 10599 10600 verifyFormat("int operator()(T (&&)[N]) { return 1; }"); 10601 verifyFormat("int operator()(T (&)[N]) { return 0; }"); 10602 } 10603 10604 TEST_F(FormatTest, UnderstandsAttributes) { 10605 verifyFormat("SomeType s __attribute__((unused)) (InitValue);"); 10606 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n" 10607 "aaaaaaaaaaaaaaaaaaaaaaa(int i);"); 10608 verifyFormat("__attribute__((nodebug)) ::qualified_type f();"); 10609 FormatStyle AfterType = getLLVMStyle(); 10610 AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 10611 verifyFormat("__attribute__((nodebug)) void\n" 10612 "foo() {}\n", 10613 AfterType); 10614 verifyFormat("__unused void\n" 10615 "foo() {}", 10616 AfterType); 10617 10618 FormatStyle CustomAttrs = getLLVMStyle(); 10619 CustomAttrs.AttributeMacros.push_back("__unused"); 10620 CustomAttrs.AttributeMacros.push_back("__attr1"); 10621 CustomAttrs.AttributeMacros.push_back("__attr2"); 10622 CustomAttrs.AttributeMacros.push_back("no_underscore_attr"); 10623 verifyFormat("vector<SomeType *__attribute((foo))> v;"); 10624 verifyFormat("vector<SomeType *__attribute__((foo))> v;"); 10625 verifyFormat("vector<SomeType * __not_attribute__((foo))> v;"); 10626 // Check that it is parsed as a multiplication without AttributeMacros and 10627 // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros. 10628 verifyFormat("vector<SomeType * __attr1> v;"); 10629 verifyFormat("vector<SomeType __attr1 *> v;"); 10630 verifyFormat("vector<SomeType __attr1 *const> v;"); 10631 verifyFormat("vector<SomeType __attr1 * __attr2> v;"); 10632 verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs); 10633 verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs); 10634 verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs); 10635 verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs); 10636 verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs); 10637 verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs); 10638 verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs); 10639 10640 // Check that these are not parsed as function declarations: 10641 CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 10642 CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman; 10643 verifyFormat("SomeType s(InitValue);", CustomAttrs); 10644 verifyFormat("SomeType s{InitValue};", CustomAttrs); 10645 verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs); 10646 verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs); 10647 verifyFormat("SomeType s __unused(InitValue);", CustomAttrs); 10648 verifyFormat("SomeType s __unused{InitValue};", CustomAttrs); 10649 verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs); 10650 verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs); 10651 } 10652 10653 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) { 10654 // Check that qualifiers on pointers don't break parsing of casts. 10655 verifyFormat("x = (foo *const)*v;"); 10656 verifyFormat("x = (foo *volatile)*v;"); 10657 verifyFormat("x = (foo *restrict)*v;"); 10658 verifyFormat("x = (foo *__attribute__((foo)))*v;"); 10659 verifyFormat("x = (foo *_Nonnull)*v;"); 10660 verifyFormat("x = (foo *_Nullable)*v;"); 10661 verifyFormat("x = (foo *_Null_unspecified)*v;"); 10662 verifyFormat("x = (foo *_Nonnull)*v;"); 10663 verifyFormat("x = (foo *[[clang::attr]])*v;"); 10664 verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;"); 10665 verifyFormat("x = (foo *__ptr32)*v;"); 10666 verifyFormat("x = (foo *__ptr64)*v;"); 10667 verifyFormat("x = (foo *__capability)*v;"); 10668 10669 // Check that we handle multiple trailing qualifiers and skip them all to 10670 // determine that the expression is a cast to a pointer type. 10671 FormatStyle LongPointerRight = getLLVMStyleWithColumns(999); 10672 FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999); 10673 LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left; 10674 StringRef AllQualifiers = 10675 "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified " 10676 "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability"; 10677 verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight); 10678 verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft); 10679 10680 // Also check that address-of is not parsed as a binary bitwise-and: 10681 verifyFormat("x = (foo *const)&v;"); 10682 verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight); 10683 verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft); 10684 10685 // Check custom qualifiers: 10686 FormatStyle CustomQualifier = getLLVMStyleWithColumns(999); 10687 CustomQualifier.AttributeMacros.push_back("__my_qualifier"); 10688 verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier. 10689 verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier); 10690 verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(), 10691 CustomQualifier); 10692 verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(), 10693 CustomQualifier); 10694 10695 // Check that unknown identifiers result in binary operator parsing: 10696 verifyFormat("x = (foo * __unknown_qualifier) * v;"); 10697 verifyFormat("x = (foo * __unknown_qualifier) & v;"); 10698 } 10699 10700 TEST_F(FormatTest, UnderstandsSquareAttributes) { 10701 verifyFormat("SomeType s [[unused]] (InitValue);"); 10702 verifyFormat("SomeType s [[gnu::unused]] (InitValue);"); 10703 verifyFormat("SomeType s [[using gnu: unused]] (InitValue);"); 10704 verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}"); 10705 verifyFormat("void f() [[deprecated(\"so sorry\")]];"); 10706 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10707 " [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);"); 10708 verifyFormat("[[nodiscard]] bool f() { return false; }"); 10709 verifyFormat("class [[nodiscard]] f {\npublic:\n f() {}\n}"); 10710 verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n f() {}\n}"); 10711 verifyFormat("class [[gnu::unused]] f {\npublic:\n f() {}\n}"); 10712 verifyFormat("[[nodiscard]] ::qualified_type f();"); 10713 10714 // Make sure we do not mistake attributes for array subscripts. 10715 verifyFormat("int a() {}\n" 10716 "[[unused]] int b() {}\n"); 10717 verifyFormat("NSArray *arr;\n" 10718 "arr[[Foo() bar]];"); 10719 10720 // On the other hand, we still need to correctly find array subscripts. 10721 verifyFormat("int a = std::vector<int>{1, 2, 3}[0];"); 10722 10723 // Make sure that we do not mistake Objective-C method inside array literals 10724 // as attributes, even if those method names are also keywords. 10725 verifyFormat("@[ [foo bar] ];"); 10726 verifyFormat("@[ [NSArray class] ];"); 10727 verifyFormat("@[ [foo enum] ];"); 10728 10729 verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }"); 10730 10731 // Make sure we do not parse attributes as lambda introducers. 10732 FormatStyle MultiLineFunctions = getLLVMStyle(); 10733 MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 10734 verifyFormat("[[unused]] int b() {\n" 10735 " return 42;\n" 10736 "}\n", 10737 MultiLineFunctions); 10738 } 10739 10740 TEST_F(FormatTest, AttributeClass) { 10741 FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp); 10742 verifyFormat("class S {\n" 10743 " S(S&&) = default;\n" 10744 "};", 10745 Style); 10746 verifyFormat("class [[nodiscard]] S {\n" 10747 " S(S&&) = default;\n" 10748 "};", 10749 Style); 10750 verifyFormat("class __attribute((maybeunused)) S {\n" 10751 " S(S&&) = default;\n" 10752 "};", 10753 Style); 10754 verifyFormat("struct S {\n" 10755 " S(S&&) = default;\n" 10756 "};", 10757 Style); 10758 verifyFormat("struct [[nodiscard]] S {\n" 10759 " S(S&&) = default;\n" 10760 "};", 10761 Style); 10762 } 10763 10764 TEST_F(FormatTest, AttributesAfterMacro) { 10765 FormatStyle Style = getLLVMStyle(); 10766 verifyFormat("MACRO;\n" 10767 "__attribute__((maybe_unused)) int foo() {\n" 10768 " //...\n" 10769 "}"); 10770 10771 verifyFormat("MACRO;\n" 10772 "[[nodiscard]] int foo() {\n" 10773 " //...\n" 10774 "}"); 10775 10776 EXPECT_EQ("MACRO\n\n" 10777 "__attribute__((maybe_unused)) int foo() {\n" 10778 " //...\n" 10779 "}", 10780 format("MACRO\n\n" 10781 "__attribute__((maybe_unused)) int foo() {\n" 10782 " //...\n" 10783 "}")); 10784 10785 EXPECT_EQ("MACRO\n\n" 10786 "[[nodiscard]] int foo() {\n" 10787 " //...\n" 10788 "}", 10789 format("MACRO\n\n" 10790 "[[nodiscard]] int foo() {\n" 10791 " //...\n" 10792 "}")); 10793 } 10794 10795 TEST_F(FormatTest, AttributePenaltyBreaking) { 10796 FormatStyle Style = getLLVMStyle(); 10797 verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n" 10798 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}", 10799 Style); 10800 verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n" 10801 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}", 10802 Style); 10803 verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const " 10804 "shared_ptr<ALongTypeName> &C d) {\n}", 10805 Style); 10806 } 10807 10808 TEST_F(FormatTest, UnderstandsEllipsis) { 10809 FormatStyle Style = getLLVMStyle(); 10810 verifyFormat("int printf(const char *fmt, ...);"); 10811 verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }"); 10812 verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}"); 10813 10814 verifyFormat("template <int *...PP> a;", Style); 10815 10816 Style.PointerAlignment = FormatStyle::PAS_Left; 10817 verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style); 10818 10819 verifyFormat("template <int*... PP> a;", Style); 10820 10821 Style.PointerAlignment = FormatStyle::PAS_Middle; 10822 verifyFormat("template <int *... PP> a;", Style); 10823 } 10824 10825 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) { 10826 EXPECT_EQ("int *a;\n" 10827 "int *a;\n" 10828 "int *a;", 10829 format("int *a;\n" 10830 "int* a;\n" 10831 "int *a;", 10832 getGoogleStyle())); 10833 EXPECT_EQ("int* a;\n" 10834 "int* a;\n" 10835 "int* a;", 10836 format("int* a;\n" 10837 "int* a;\n" 10838 "int *a;", 10839 getGoogleStyle())); 10840 EXPECT_EQ("int *a;\n" 10841 "int *a;\n" 10842 "int *a;", 10843 format("int *a;\n" 10844 "int * a;\n" 10845 "int * a;", 10846 getGoogleStyle())); 10847 EXPECT_EQ("auto x = [] {\n" 10848 " int *a;\n" 10849 " int *a;\n" 10850 " int *a;\n" 10851 "};", 10852 format("auto x=[]{int *a;\n" 10853 "int * a;\n" 10854 "int * a;};", 10855 getGoogleStyle())); 10856 } 10857 10858 TEST_F(FormatTest, UnderstandsRvalueReferences) { 10859 verifyFormat("int f(int &&a) {}"); 10860 verifyFormat("int f(int a, char &&b) {}"); 10861 verifyFormat("void f() { int &&a = b; }"); 10862 verifyGoogleFormat("int f(int a, char&& b) {}"); 10863 verifyGoogleFormat("void f() { int&& a = b; }"); 10864 10865 verifyIndependentOfContext("A<int &&> a;"); 10866 verifyIndependentOfContext("A<int &&, int &&> a;"); 10867 verifyGoogleFormat("A<int&&> a;"); 10868 verifyGoogleFormat("A<int&&, int&&> a;"); 10869 10870 // Not rvalue references: 10871 verifyFormat("template <bool B, bool C> class A {\n" 10872 " static_assert(B && C, \"Something is wrong\");\n" 10873 "};"); 10874 verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))"); 10875 verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))"); 10876 verifyFormat("#define A(a, b) (a && b)"); 10877 } 10878 10879 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) { 10880 verifyFormat("void f() {\n" 10881 " x[aaaaaaaaa -\n" 10882 " b] = 23;\n" 10883 "}", 10884 getLLVMStyleWithColumns(15)); 10885 } 10886 10887 TEST_F(FormatTest, FormatsCasts) { 10888 verifyFormat("Type *A = static_cast<Type *>(P);"); 10889 verifyFormat("static_cast<Type *>(P);"); 10890 verifyFormat("static_cast<Type &>(Fun)(Args);"); 10891 verifyFormat("static_cast<Type &>(*Fun)(Args);"); 10892 verifyFormat("if (static_cast<int>(A) + B >= 0)\n ;"); 10893 // Check that static_cast<...>(...) does not require the next token to be on 10894 // the same line. 10895 verifyFormat("some_loooong_output << something_something__ << " 10896 "static_cast<const void *>(R)\n" 10897 " << something;"); 10898 verifyFormat("a = static_cast<Type &>(*Fun)(Args);"); 10899 verifyFormat("const_cast<Type &>(*Fun)(Args);"); 10900 verifyFormat("dynamic_cast<Type &>(*Fun)(Args);"); 10901 verifyFormat("reinterpret_cast<Type &>(*Fun)(Args);"); 10902 verifyFormat("Type *A = (Type *)P;"); 10903 verifyFormat("Type *A = (vector<Type *, int *>)P;"); 10904 verifyFormat("int a = (int)(2.0f);"); 10905 verifyFormat("int a = (int)2.0f;"); 10906 verifyFormat("x[(int32)y];"); 10907 verifyFormat("x = (int32)y;"); 10908 verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)"); 10909 verifyFormat("int a = (int)*b;"); 10910 verifyFormat("int a = (int)2.0f;"); 10911 verifyFormat("int a = (int)~0;"); 10912 verifyFormat("int a = (int)++a;"); 10913 verifyFormat("int a = (int)sizeof(int);"); 10914 verifyFormat("int a = (int)+2;"); 10915 verifyFormat("my_int a = (my_int)2.0f;"); 10916 verifyFormat("my_int a = (my_int)sizeof(int);"); 10917 verifyFormat("return (my_int)aaa;"); 10918 verifyFormat("#define x ((int)-1)"); 10919 verifyFormat("#define LENGTH(x, y) (x) - (y) + 1"); 10920 verifyFormat("#define p(q) ((int *)&q)"); 10921 verifyFormat("fn(a)(b) + 1;"); 10922 10923 verifyFormat("void f() { my_int a = (my_int)*b; }"); 10924 verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }"); 10925 verifyFormat("my_int a = (my_int)~0;"); 10926 verifyFormat("my_int a = (my_int)++a;"); 10927 verifyFormat("my_int a = (my_int)-2;"); 10928 verifyFormat("my_int a = (my_int)1;"); 10929 verifyFormat("my_int a = (my_int *)1;"); 10930 verifyFormat("my_int a = (const my_int)-1;"); 10931 verifyFormat("my_int a = (const my_int *)-1;"); 10932 verifyFormat("my_int a = (my_int)(my_int)-1;"); 10933 verifyFormat("my_int a = (ns::my_int)-2;"); 10934 verifyFormat("case (my_int)ONE:"); 10935 verifyFormat("auto x = (X)this;"); 10936 // Casts in Obj-C style calls used to not be recognized as such. 10937 verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle()); 10938 10939 // FIXME: single value wrapped with paren will be treated as cast. 10940 verifyFormat("void f(int i = (kValue)*kMask) {}"); 10941 10942 verifyFormat("{ (void)F; }"); 10943 10944 // Don't break after a cast's 10945 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 10946 " (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n" 10947 " bbbbbbbbbbbbbbbbbbbbbb);"); 10948 10949 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(x)"); 10950 verifyFormat("#define CONF_BOOL(x) (bool *)(x)"); 10951 verifyFormat("#define CONF_BOOL(x) (bool)(x)"); 10952 verifyFormat("bool *y = (bool *)(void *)(x);"); 10953 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)(x)"); 10954 verifyFormat("bool *y = (bool *)(void *)(int)(x);"); 10955 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)foo(x)"); 10956 verifyFormat("bool *y = (bool *)(void *)(int)foo(x);"); 10957 10958 // These are not casts. 10959 verifyFormat("void f(int *) {}"); 10960 verifyFormat("f(foo)->b;"); 10961 verifyFormat("f(foo).b;"); 10962 verifyFormat("f(foo)(b);"); 10963 verifyFormat("f(foo)[b];"); 10964 verifyFormat("[](foo) { return 4; }(bar);"); 10965 verifyFormat("(*funptr)(foo)[4];"); 10966 verifyFormat("funptrs[4](foo)[4];"); 10967 verifyFormat("void f(int *);"); 10968 verifyFormat("void f(int *) = 0;"); 10969 verifyFormat("void f(SmallVector<int>) {}"); 10970 verifyFormat("void f(SmallVector<int>);"); 10971 verifyFormat("void f(SmallVector<int>) = 0;"); 10972 verifyFormat("void f(int i = (kA * kB) & kMask) {}"); 10973 verifyFormat("int a = sizeof(int) * b;"); 10974 verifyFormat("int a = alignof(int) * b;", getGoogleStyle()); 10975 verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;"); 10976 verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");"); 10977 verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;"); 10978 10979 // These are not casts, but at some point were confused with casts. 10980 verifyFormat("virtual void foo(int *) override;"); 10981 verifyFormat("virtual void foo(char &) const;"); 10982 verifyFormat("virtual void foo(int *a, char *) const;"); 10983 verifyFormat("int a = sizeof(int *) + b;"); 10984 verifyFormat("int a = alignof(int *) + b;", getGoogleStyle()); 10985 verifyFormat("bool b = f(g<int>) && c;"); 10986 verifyFormat("typedef void (*f)(int i) func;"); 10987 verifyFormat("void operator++(int) noexcept;"); 10988 verifyFormat("void operator++(int &) noexcept;"); 10989 verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t " 10990 "&) noexcept;"); 10991 verifyFormat( 10992 "void operator delete(std::size_t, const std::nothrow_t &) noexcept;"); 10993 verifyFormat("void operator delete(const std::nothrow_t &) noexcept;"); 10994 verifyFormat("void operator delete(std::nothrow_t &) noexcept;"); 10995 verifyFormat("void operator delete(nothrow_t &) noexcept;"); 10996 verifyFormat("void operator delete(foo &) noexcept;"); 10997 verifyFormat("void operator delete(foo) noexcept;"); 10998 verifyFormat("void operator delete(int) noexcept;"); 10999 verifyFormat("void operator delete(int &) noexcept;"); 11000 verifyFormat("void operator delete(int &) volatile noexcept;"); 11001 verifyFormat("void operator delete(int &) const"); 11002 verifyFormat("void operator delete(int &) = default"); 11003 verifyFormat("void operator delete(int &) = delete"); 11004 verifyFormat("void operator delete(int &) [[noreturn]]"); 11005 verifyFormat("void operator delete(int &) throw();"); 11006 verifyFormat("void operator delete(int &) throw(int);"); 11007 verifyFormat("auto operator delete(int &) -> int;"); 11008 verifyFormat("auto operator delete(int &) override"); 11009 verifyFormat("auto operator delete(int &) final"); 11010 11011 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n" 11012 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 11013 // FIXME: The indentation here is not ideal. 11014 verifyFormat( 11015 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11016 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n" 11017 " [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];"); 11018 } 11019 11020 TEST_F(FormatTest, FormatsFunctionTypes) { 11021 verifyFormat("A<bool()> a;"); 11022 verifyFormat("A<SomeType()> a;"); 11023 verifyFormat("A<void (*)(int, std::string)> a;"); 11024 verifyFormat("A<void *(int)>;"); 11025 verifyFormat("void *(*a)(int *, SomeType *);"); 11026 verifyFormat("int (*func)(void *);"); 11027 verifyFormat("void f() { int (*func)(void *); }"); 11028 verifyFormat("template <class CallbackClass>\n" 11029 "using MyCallback = void (CallbackClass::*)(SomeObject *Data);"); 11030 11031 verifyGoogleFormat("A<void*(int*, SomeType*)>;"); 11032 verifyGoogleFormat("void* (*a)(int);"); 11033 verifyGoogleFormat( 11034 "template <class CallbackClass>\n" 11035 "using MyCallback = void (CallbackClass::*)(SomeObject* Data);"); 11036 11037 // Other constructs can look somewhat like function types: 11038 verifyFormat("A<sizeof(*x)> a;"); 11039 verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)"); 11040 verifyFormat("some_var = function(*some_pointer_var)[0];"); 11041 verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }"); 11042 verifyFormat("int x = f(&h)();"); 11043 verifyFormat("returnsFunction(¶m1, ¶m2)(param);"); 11044 verifyFormat("std::function<\n" 11045 " LooooooooooongTemplatedType<\n" 11046 " SomeType>*(\n" 11047 " LooooooooooooooooongType type)>\n" 11048 " function;", 11049 getGoogleStyleWithColumns(40)); 11050 } 11051 11052 TEST_F(FormatTest, FormatsPointersToArrayTypes) { 11053 verifyFormat("A (*foo_)[6];"); 11054 verifyFormat("vector<int> (*foo_)[6];"); 11055 } 11056 11057 TEST_F(FormatTest, BreaksLongVariableDeclarations) { 11058 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 11059 " LoooooooooooooooooooooooooooooooooooooooongVariable;"); 11060 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n" 11061 " LoooooooooooooooooooooooooooooooooooooooongVariable;"); 11062 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 11063 " *LoooooooooooooooooooooooooooooooooooooooongVariable;"); 11064 11065 // Different ways of ()-initializiation. 11066 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 11067 " LoooooooooooooooooooooooooooooooooooooooongVariable(1);"); 11068 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 11069 " LoooooooooooooooooooooooooooooooooooooooongVariable(a);"); 11070 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 11071 " LoooooooooooooooooooooooooooooooooooooooongVariable({});"); 11072 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 11073 " LoooooooooooooooooooooooooooooooooooooongVariable([A a]);"); 11074 11075 // Lambdas should not confuse the variable declaration heuristic. 11076 verifyFormat("LooooooooooooooooongType\n" 11077 " variable(nullptr, [](A *a) {});", 11078 getLLVMStyleWithColumns(40)); 11079 } 11080 11081 TEST_F(FormatTest, BreaksLongDeclarations) { 11082 verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n" 11083 " AnotherNameForTheLongType;"); 11084 verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n" 11085 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 11086 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 11087 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();"); 11088 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n" 11089 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();"); 11090 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 11091 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 11092 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n" 11093 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 11094 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n" 11095 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 11096 verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n" 11097 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 11098 verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n" 11099 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 11100 verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n" 11101 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 11102 verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n" 11103 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 11104 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 11105 "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);"); 11106 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 11107 "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}"); 11108 FormatStyle Indented = getLLVMStyle(); 11109 Indented.IndentWrappedFunctionNames = true; 11110 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 11111 " LoooooooooooooooooooooooooooooooongFunctionDeclaration();", 11112 Indented); 11113 verifyFormat( 11114 "LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 11115 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 11116 Indented); 11117 verifyFormat( 11118 "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n" 11119 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 11120 Indented); 11121 verifyFormat( 11122 "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n" 11123 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 11124 Indented); 11125 11126 // FIXME: Without the comment, this breaks after "(". 11127 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType // break\n" 11128 " (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();", 11129 getGoogleStyle()); 11130 11131 verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n" 11132 " int LoooooooooooooooooooongParam2) {}"); 11133 verifyFormat( 11134 "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n" 11135 " SourceLocation L, IdentifierIn *II,\n" 11136 " Type *T) {}"); 11137 verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n" 11138 "ReallyReaaallyLongFunctionName(\n" 11139 " const std::string &SomeParameter,\n" 11140 " const SomeType<string, SomeOtherTemplateParameter>\n" 11141 " &ReallyReallyLongParameterName,\n" 11142 " const SomeType<string, SomeOtherTemplateParameter>\n" 11143 " &AnotherLongParameterName) {}"); 11144 verifyFormat("template <typename A>\n" 11145 "SomeLoooooooooooooooooooooongType<\n" 11146 " typename some_namespace::SomeOtherType<A>::Type>\n" 11147 "Function() {}"); 11148 11149 verifyGoogleFormat( 11150 "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n" 11151 " aaaaaaaaaaaaaaaaaaaaaaa;"); 11152 verifyGoogleFormat( 11153 "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n" 11154 " SourceLocation L) {}"); 11155 verifyGoogleFormat( 11156 "some_namespace::LongReturnType\n" 11157 "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n" 11158 " int first_long_parameter, int second_parameter) {}"); 11159 11160 verifyGoogleFormat("template <typename T>\n" 11161 "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n" 11162 "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}"); 11163 verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 11164 " int aaaaaaaaaaaaaaaaaaaaaaa);"); 11165 11166 verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n" 11167 " const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11168 " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 11169 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 11170 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n" 11171 " aaaaaaaaaaaaaaaaaaaaaaaa);"); 11172 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 11173 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 11174 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n" 11175 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 11176 11177 verifyFormat("template <typename T> // Templates on own line.\n" 11178 "static int // Some comment.\n" 11179 "MyFunction(int a);", 11180 getLLVMStyle()); 11181 } 11182 11183 TEST_F(FormatTest, FormatsAccessModifiers) { 11184 FormatStyle Style = getLLVMStyle(); 11185 EXPECT_EQ(Style.EmptyLineBeforeAccessModifier, 11186 FormatStyle::ELBAMS_LogicalBlock); 11187 verifyFormat("struct foo {\n" 11188 "private:\n" 11189 " void f() {}\n" 11190 "\n" 11191 "private:\n" 11192 " int i;\n" 11193 "\n" 11194 "protected:\n" 11195 " int j;\n" 11196 "};\n", 11197 Style); 11198 verifyFormat("struct foo {\n" 11199 "private:\n" 11200 " void f() {}\n" 11201 "\n" 11202 "private:\n" 11203 " int i;\n" 11204 "\n" 11205 "protected:\n" 11206 " int j;\n" 11207 "};\n", 11208 "struct foo {\n" 11209 "private:\n" 11210 " void f() {}\n" 11211 "private:\n" 11212 " int i;\n" 11213 "protected:\n" 11214 " int j;\n" 11215 "};\n", 11216 Style); 11217 verifyFormat("struct foo { /* comment */\n" 11218 "private:\n" 11219 " int i;\n" 11220 " // comment\n" 11221 "private:\n" 11222 " int j;\n" 11223 "};\n", 11224 Style); 11225 verifyFormat("struct foo {\n" 11226 "#ifdef FOO\n" 11227 "#endif\n" 11228 "private:\n" 11229 " int i;\n" 11230 "#ifdef FOO\n" 11231 "private:\n" 11232 "#endif\n" 11233 " int j;\n" 11234 "};\n", 11235 Style); 11236 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11237 verifyFormat("struct foo {\n" 11238 "private:\n" 11239 " void f() {}\n" 11240 "private:\n" 11241 " int i;\n" 11242 "protected:\n" 11243 " int j;\n" 11244 "};\n", 11245 Style); 11246 verifyFormat("struct foo {\n" 11247 "private:\n" 11248 " void f() {}\n" 11249 "private:\n" 11250 " int i;\n" 11251 "protected:\n" 11252 " int j;\n" 11253 "};\n", 11254 "struct foo {\n" 11255 "\n" 11256 "private:\n" 11257 " void f() {}\n" 11258 "\n" 11259 "private:\n" 11260 " int i;\n" 11261 "\n" 11262 "protected:\n" 11263 " int j;\n" 11264 "};\n", 11265 Style); 11266 verifyFormat("struct foo { /* comment */\n" 11267 "private:\n" 11268 " int i;\n" 11269 " // comment\n" 11270 "private:\n" 11271 " int j;\n" 11272 "};\n", 11273 "struct foo { /* comment */\n" 11274 "\n" 11275 "private:\n" 11276 " int i;\n" 11277 " // comment\n" 11278 "\n" 11279 "private:\n" 11280 " int j;\n" 11281 "};\n", 11282 Style); 11283 verifyFormat("struct foo {\n" 11284 "#ifdef FOO\n" 11285 "#endif\n" 11286 "private:\n" 11287 " int i;\n" 11288 "#ifdef FOO\n" 11289 "private:\n" 11290 "#endif\n" 11291 " int j;\n" 11292 "};\n", 11293 "struct foo {\n" 11294 "#ifdef FOO\n" 11295 "#endif\n" 11296 "\n" 11297 "private:\n" 11298 " int i;\n" 11299 "#ifdef FOO\n" 11300 "\n" 11301 "private:\n" 11302 "#endif\n" 11303 " int j;\n" 11304 "};\n", 11305 Style); 11306 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11307 verifyFormat("struct foo {\n" 11308 "private:\n" 11309 " void f() {}\n" 11310 "\n" 11311 "private:\n" 11312 " int i;\n" 11313 "\n" 11314 "protected:\n" 11315 " int j;\n" 11316 "};\n", 11317 Style); 11318 verifyFormat("struct foo {\n" 11319 "private:\n" 11320 " void f() {}\n" 11321 "\n" 11322 "private:\n" 11323 " int i;\n" 11324 "\n" 11325 "protected:\n" 11326 " int j;\n" 11327 "};\n", 11328 "struct foo {\n" 11329 "private:\n" 11330 " void f() {}\n" 11331 "private:\n" 11332 " int i;\n" 11333 "protected:\n" 11334 " int j;\n" 11335 "};\n", 11336 Style); 11337 verifyFormat("struct foo { /* comment */\n" 11338 "private:\n" 11339 " int i;\n" 11340 " // comment\n" 11341 "\n" 11342 "private:\n" 11343 " int j;\n" 11344 "};\n", 11345 "struct foo { /* comment */\n" 11346 "private:\n" 11347 " int i;\n" 11348 " // comment\n" 11349 "\n" 11350 "private:\n" 11351 " int j;\n" 11352 "};\n", 11353 Style); 11354 verifyFormat("struct foo {\n" 11355 "#ifdef FOO\n" 11356 "#endif\n" 11357 "\n" 11358 "private:\n" 11359 " int i;\n" 11360 "#ifdef FOO\n" 11361 "\n" 11362 "private:\n" 11363 "#endif\n" 11364 " int j;\n" 11365 "};\n", 11366 "struct foo {\n" 11367 "#ifdef FOO\n" 11368 "#endif\n" 11369 "private:\n" 11370 " int i;\n" 11371 "#ifdef FOO\n" 11372 "private:\n" 11373 "#endif\n" 11374 " int j;\n" 11375 "};\n", 11376 Style); 11377 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11378 EXPECT_EQ("struct foo {\n" 11379 "\n" 11380 "private:\n" 11381 " void f() {}\n" 11382 "\n" 11383 "private:\n" 11384 " int i;\n" 11385 "\n" 11386 "protected:\n" 11387 " int j;\n" 11388 "};\n", 11389 format("struct foo {\n" 11390 "\n" 11391 "private:\n" 11392 " void f() {}\n" 11393 "\n" 11394 "private:\n" 11395 " int i;\n" 11396 "\n" 11397 "protected:\n" 11398 " int j;\n" 11399 "};\n", 11400 Style)); 11401 verifyFormat("struct foo {\n" 11402 "private:\n" 11403 " void f() {}\n" 11404 "private:\n" 11405 " int i;\n" 11406 "protected:\n" 11407 " int j;\n" 11408 "};\n", 11409 Style); 11410 EXPECT_EQ("struct foo { /* comment */\n" 11411 "\n" 11412 "private:\n" 11413 " int i;\n" 11414 " // comment\n" 11415 "\n" 11416 "private:\n" 11417 " int j;\n" 11418 "};\n", 11419 format("struct foo { /* comment */\n" 11420 "\n" 11421 "private:\n" 11422 " int i;\n" 11423 " // comment\n" 11424 "\n" 11425 "private:\n" 11426 " int j;\n" 11427 "};\n", 11428 Style)); 11429 verifyFormat("struct foo { /* comment */\n" 11430 "private:\n" 11431 " int i;\n" 11432 " // comment\n" 11433 "private:\n" 11434 " int j;\n" 11435 "};\n", 11436 Style); 11437 EXPECT_EQ("struct foo {\n" 11438 "#ifdef FOO\n" 11439 "#endif\n" 11440 "\n" 11441 "private:\n" 11442 " int i;\n" 11443 "#ifdef FOO\n" 11444 "\n" 11445 "private:\n" 11446 "#endif\n" 11447 " int j;\n" 11448 "};\n", 11449 format("struct foo {\n" 11450 "#ifdef FOO\n" 11451 "#endif\n" 11452 "\n" 11453 "private:\n" 11454 " int i;\n" 11455 "#ifdef FOO\n" 11456 "\n" 11457 "private:\n" 11458 "#endif\n" 11459 " int j;\n" 11460 "};\n", 11461 Style)); 11462 verifyFormat("struct foo {\n" 11463 "#ifdef FOO\n" 11464 "#endif\n" 11465 "private:\n" 11466 " int i;\n" 11467 "#ifdef FOO\n" 11468 "private:\n" 11469 "#endif\n" 11470 " int j;\n" 11471 "};\n", 11472 Style); 11473 11474 FormatStyle NoEmptyLines = getLLVMStyle(); 11475 NoEmptyLines.MaxEmptyLinesToKeep = 0; 11476 verifyFormat("struct foo {\n" 11477 "private:\n" 11478 " void f() {}\n" 11479 "\n" 11480 "private:\n" 11481 " int i;\n" 11482 "\n" 11483 "public:\n" 11484 "protected:\n" 11485 " int j;\n" 11486 "};\n", 11487 NoEmptyLines); 11488 11489 NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11490 verifyFormat("struct foo {\n" 11491 "private:\n" 11492 " void f() {}\n" 11493 "private:\n" 11494 " int i;\n" 11495 "public:\n" 11496 "protected:\n" 11497 " int j;\n" 11498 "};\n", 11499 NoEmptyLines); 11500 11501 NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11502 verifyFormat("struct foo {\n" 11503 "private:\n" 11504 " void f() {}\n" 11505 "\n" 11506 "private:\n" 11507 " int i;\n" 11508 "\n" 11509 "public:\n" 11510 "\n" 11511 "protected:\n" 11512 " int j;\n" 11513 "};\n", 11514 NoEmptyLines); 11515 } 11516 11517 TEST_F(FormatTest, FormatsAfterAccessModifiers) { 11518 11519 FormatStyle Style = getLLVMStyle(); 11520 EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never); 11521 verifyFormat("struct foo {\n" 11522 "private:\n" 11523 " void f() {}\n" 11524 "\n" 11525 "private:\n" 11526 " int i;\n" 11527 "\n" 11528 "protected:\n" 11529 " int j;\n" 11530 "};\n", 11531 Style); 11532 11533 // Check if lines are removed. 11534 verifyFormat("struct foo {\n" 11535 "private:\n" 11536 " void f() {}\n" 11537 "\n" 11538 "private:\n" 11539 " int i;\n" 11540 "\n" 11541 "protected:\n" 11542 " int j;\n" 11543 "};\n", 11544 "struct foo {\n" 11545 "private:\n" 11546 "\n" 11547 " void f() {}\n" 11548 "\n" 11549 "private:\n" 11550 "\n" 11551 " int i;\n" 11552 "\n" 11553 "protected:\n" 11554 "\n" 11555 " int j;\n" 11556 "};\n", 11557 Style); 11558 11559 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11560 verifyFormat("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 // Check if lines are added. 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 "struct foo {\n" 11590 "private:\n" 11591 " void f() {}\n" 11592 "\n" 11593 "private:\n" 11594 " int i;\n" 11595 "\n" 11596 "protected:\n" 11597 " int j;\n" 11598 "};\n", 11599 Style); 11600 11601 // Leave tests rely on the code layout, test::messUp can not be used. 11602 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11603 Style.MaxEmptyLinesToKeep = 0u; 11604 verifyFormat("struct foo {\n" 11605 "private:\n" 11606 " void f() {}\n" 11607 "\n" 11608 "private:\n" 11609 " int i;\n" 11610 "\n" 11611 "protected:\n" 11612 " int j;\n" 11613 "};\n", 11614 Style); 11615 11616 // Check if MaxEmptyLinesToKeep is respected. 11617 EXPECT_EQ("struct foo {\n" 11618 "private:\n" 11619 " void f() {}\n" 11620 "\n" 11621 "private:\n" 11622 " int i;\n" 11623 "\n" 11624 "protected:\n" 11625 " int j;\n" 11626 "};\n", 11627 format("struct foo {\n" 11628 "private:\n" 11629 "\n\n\n" 11630 " void f() {}\n" 11631 "\n" 11632 "private:\n" 11633 "\n\n\n" 11634 " int i;\n" 11635 "\n" 11636 "protected:\n" 11637 "\n\n\n" 11638 " int j;\n" 11639 "};\n", 11640 Style)); 11641 11642 Style.MaxEmptyLinesToKeep = 1u; 11643 EXPECT_EQ("struct foo {\n" 11644 "private:\n" 11645 "\n" 11646 " void f() {}\n" 11647 "\n" 11648 "private:\n" 11649 "\n" 11650 " int i;\n" 11651 "\n" 11652 "protected:\n" 11653 "\n" 11654 " int j;\n" 11655 "};\n", 11656 format("struct foo {\n" 11657 "private:\n" 11658 "\n" 11659 " void f() {}\n" 11660 "\n" 11661 "private:\n" 11662 "\n" 11663 " int i;\n" 11664 "\n" 11665 "protected:\n" 11666 "\n" 11667 " int j;\n" 11668 "};\n", 11669 Style)); 11670 // Check if no lines are kept. 11671 EXPECT_EQ("struct foo {\n" 11672 "private:\n" 11673 " void f() {}\n" 11674 "\n" 11675 "private:\n" 11676 " int i;\n" 11677 "\n" 11678 "protected:\n" 11679 " int j;\n" 11680 "};\n", 11681 format("struct foo {\n" 11682 "private:\n" 11683 " void f() {}\n" 11684 "\n" 11685 "private:\n" 11686 " int i;\n" 11687 "\n" 11688 "protected:\n" 11689 " int j;\n" 11690 "};\n", 11691 Style)); 11692 // Check if MaxEmptyLinesToKeep is respected. 11693 EXPECT_EQ("struct foo {\n" 11694 "private:\n" 11695 "\n" 11696 " void f() {}\n" 11697 "\n" 11698 "private:\n" 11699 "\n" 11700 " int i;\n" 11701 "\n" 11702 "protected:\n" 11703 "\n" 11704 " int j;\n" 11705 "};\n", 11706 format("struct foo {\n" 11707 "private:\n" 11708 "\n\n\n" 11709 " void f() {}\n" 11710 "\n" 11711 "private:\n" 11712 "\n\n\n" 11713 " int i;\n" 11714 "\n" 11715 "protected:\n" 11716 "\n\n\n" 11717 " int j;\n" 11718 "};\n", 11719 Style)); 11720 11721 Style.MaxEmptyLinesToKeep = 10u; 11722 EXPECT_EQ("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 format("struct foo {\n" 11736 "private:\n" 11737 "\n\n\n" 11738 " void f() {}\n" 11739 "\n" 11740 "private:\n" 11741 "\n\n\n" 11742 " int i;\n" 11743 "\n" 11744 "protected:\n" 11745 "\n\n\n" 11746 " int j;\n" 11747 "};\n", 11748 Style)); 11749 11750 // Test with comments. 11751 Style = getLLVMStyle(); 11752 verifyFormat("struct foo {\n" 11753 "private:\n" 11754 " // comment\n" 11755 " void f() {}\n" 11756 "\n" 11757 "private: /* comment */\n" 11758 " int i;\n" 11759 "};\n", 11760 Style); 11761 verifyFormat("struct foo {\n" 11762 "private:\n" 11763 " // comment\n" 11764 " void f() {}\n" 11765 "\n" 11766 "private: /* comment */\n" 11767 " int i;\n" 11768 "};\n", 11769 "struct foo {\n" 11770 "private:\n" 11771 "\n" 11772 " // comment\n" 11773 " void f() {}\n" 11774 "\n" 11775 "private: /* comment */\n" 11776 "\n" 11777 " int i;\n" 11778 "};\n", 11779 Style); 11780 11781 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11782 verifyFormat("struct foo {\n" 11783 "private:\n" 11784 "\n" 11785 " // comment\n" 11786 " void f() {}\n" 11787 "\n" 11788 "private: /* comment */\n" 11789 "\n" 11790 " int i;\n" 11791 "};\n", 11792 "struct foo {\n" 11793 "private:\n" 11794 " // comment\n" 11795 " void f() {}\n" 11796 "\n" 11797 "private: /* comment */\n" 11798 " int i;\n" 11799 "};\n", 11800 Style); 11801 verifyFormat("struct foo {\n" 11802 "private:\n" 11803 "\n" 11804 " // comment\n" 11805 " void f() {}\n" 11806 "\n" 11807 "private: /* comment */\n" 11808 "\n" 11809 " int i;\n" 11810 "};\n", 11811 Style); 11812 11813 // Test with preprocessor defines. 11814 Style = getLLVMStyle(); 11815 verifyFormat("struct foo {\n" 11816 "private:\n" 11817 "#ifdef FOO\n" 11818 "#endif\n" 11819 " void f() {}\n" 11820 "};\n", 11821 Style); 11822 verifyFormat("struct foo {\n" 11823 "private:\n" 11824 "#ifdef FOO\n" 11825 "#endif\n" 11826 " void f() {}\n" 11827 "};\n", 11828 "struct foo {\n" 11829 "private:\n" 11830 "\n" 11831 "#ifdef FOO\n" 11832 "#endif\n" 11833 " void f() {}\n" 11834 "};\n", 11835 Style); 11836 11837 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11838 verifyFormat("struct foo {\n" 11839 "private:\n" 11840 "\n" 11841 "#ifdef FOO\n" 11842 "#endif\n" 11843 " void f() {}\n" 11844 "};\n", 11845 "struct foo {\n" 11846 "private:\n" 11847 "#ifdef FOO\n" 11848 "#endif\n" 11849 " void f() {}\n" 11850 "};\n", 11851 Style); 11852 verifyFormat("struct foo {\n" 11853 "private:\n" 11854 "\n" 11855 "#ifdef FOO\n" 11856 "#endif\n" 11857 " void f() {}\n" 11858 "};\n", 11859 Style); 11860 } 11861 11862 TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) { 11863 // Combined tests of EmptyLineAfterAccessModifier and 11864 // EmptyLineBeforeAccessModifier. 11865 FormatStyle Style = getLLVMStyle(); 11866 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11867 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11868 verifyFormat("struct foo {\n" 11869 "private:\n" 11870 "\n" 11871 "protected:\n" 11872 "};\n", 11873 Style); 11874 11875 Style.MaxEmptyLinesToKeep = 10u; 11876 // Both remove all new lines. 11877 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11878 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11879 verifyFormat("struct foo {\n" 11880 "private:\n" 11881 "protected:\n" 11882 "};\n", 11883 "struct foo {\n" 11884 "private:\n" 11885 "\n\n\n" 11886 "protected:\n" 11887 "};\n", 11888 Style); 11889 11890 // Leave tests rely on the code layout, test::messUp can not be used. 11891 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11892 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11893 Style.MaxEmptyLinesToKeep = 10u; 11894 EXPECT_EQ("struct foo {\n" 11895 "private:\n" 11896 "\n\n\n" 11897 "protected:\n" 11898 "};\n", 11899 format("struct foo {\n" 11900 "private:\n" 11901 "\n\n\n" 11902 "protected:\n" 11903 "};\n", 11904 Style)); 11905 Style.MaxEmptyLinesToKeep = 3u; 11906 EXPECT_EQ("struct foo {\n" 11907 "private:\n" 11908 "\n\n\n" 11909 "protected:\n" 11910 "};\n", 11911 format("struct foo {\n" 11912 "private:\n" 11913 "\n\n\n" 11914 "protected:\n" 11915 "};\n", 11916 Style)); 11917 Style.MaxEmptyLinesToKeep = 1u; 11918 EXPECT_EQ("struct foo {\n" 11919 "private:\n" 11920 "\n\n\n" 11921 "protected:\n" 11922 "};\n", 11923 format("struct foo {\n" 11924 "private:\n" 11925 "\n\n\n" 11926 "protected:\n" 11927 "};\n", 11928 Style)); // Based on new lines in original document and not 11929 // on the setting. 11930 11931 Style.MaxEmptyLinesToKeep = 10u; 11932 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11933 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11934 // Newlines are kept if they are greater than zero, 11935 // test::messUp removes all new lines which changes the logic 11936 EXPECT_EQ("struct foo {\n" 11937 "private:\n" 11938 "\n\n\n" 11939 "protected:\n" 11940 "};\n", 11941 format("struct foo {\n" 11942 "private:\n" 11943 "\n\n\n" 11944 "protected:\n" 11945 "};\n", 11946 Style)); 11947 11948 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11949 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11950 // test::messUp removes all new lines which changes the logic 11951 EXPECT_EQ("struct foo {\n" 11952 "private:\n" 11953 "\n\n\n" 11954 "protected:\n" 11955 "};\n", 11956 format("struct foo {\n" 11957 "private:\n" 11958 "\n\n\n" 11959 "protected:\n" 11960 "};\n", 11961 Style)); 11962 11963 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11964 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11965 EXPECT_EQ("struct foo {\n" 11966 "private:\n" 11967 "\n\n\n" 11968 "protected:\n" 11969 "};\n", 11970 format("struct foo {\n" 11971 "private:\n" 11972 "\n\n\n" 11973 "protected:\n" 11974 "};\n", 11975 Style)); // test::messUp removes all new lines which changes 11976 // the logic. 11977 11978 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11979 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11980 verifyFormat("struct foo {\n" 11981 "private:\n" 11982 "protected:\n" 11983 "};\n", 11984 "struct foo {\n" 11985 "private:\n" 11986 "\n\n\n" 11987 "protected:\n" 11988 "};\n", 11989 Style); 11990 11991 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11992 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11993 EXPECT_EQ("struct foo {\n" 11994 "private:\n" 11995 "\n\n\n" 11996 "protected:\n" 11997 "};\n", 11998 format("struct foo {\n" 11999 "private:\n" 12000 "\n\n\n" 12001 "protected:\n" 12002 "};\n", 12003 Style)); // test::messUp removes all new lines which changes 12004 // the logic. 12005 12006 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 12007 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 12008 verifyFormat("struct foo {\n" 12009 "private:\n" 12010 "protected:\n" 12011 "};\n", 12012 "struct foo {\n" 12013 "private:\n" 12014 "\n\n\n" 12015 "protected:\n" 12016 "};\n", 12017 Style); 12018 12019 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 12020 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 12021 verifyFormat("struct foo {\n" 12022 "private:\n" 12023 "protected:\n" 12024 "};\n", 12025 "struct foo {\n" 12026 "private:\n" 12027 "\n\n\n" 12028 "protected:\n" 12029 "};\n", 12030 Style); 12031 12032 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 12033 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 12034 verifyFormat("struct foo {\n" 12035 "private:\n" 12036 "protected:\n" 12037 "};\n", 12038 "struct foo {\n" 12039 "private:\n" 12040 "\n\n\n" 12041 "protected:\n" 12042 "};\n", 12043 Style); 12044 12045 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 12046 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 12047 verifyFormat("struct foo {\n" 12048 "private:\n" 12049 "protected:\n" 12050 "};\n", 12051 "struct foo {\n" 12052 "private:\n" 12053 "\n\n\n" 12054 "protected:\n" 12055 "};\n", 12056 Style); 12057 } 12058 12059 TEST_F(FormatTest, FormatsArrays) { 12060 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n" 12061 " [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;"); 12062 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n" 12063 " [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;"); 12064 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n" 12065 " aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}"); 12066 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 12067 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;"); 12068 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 12069 " [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;"); 12070 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 12071 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n" 12072 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;"); 12073 verifyFormat( 12074 "llvm::outs() << \"aaaaaaaaaaaa: \"\n" 12075 " << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n" 12076 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];"); 12077 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n" 12078 " .aaaaaaaaaaaaaaaaaaaaaa();"); 12079 12080 verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n" 12081 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];"); 12082 verifyFormat( 12083 "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n" 12084 " .aaaaaaa[0]\n" 12085 " .aaaaaaaaaaaaaaaaaaaaaa();"); 12086 verifyFormat("a[::b::c];"); 12087 12088 verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10)); 12089 12090 FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0); 12091 verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit); 12092 } 12093 12094 TEST_F(FormatTest, LineStartsWithSpecialCharacter) { 12095 verifyFormat("(a)->b();"); 12096 verifyFormat("--a;"); 12097 } 12098 12099 TEST_F(FormatTest, HandlesIncludeDirectives) { 12100 verifyFormat("#include <string>\n" 12101 "#include <a/b/c.h>\n" 12102 "#include \"a/b/string\"\n" 12103 "#include \"string.h\"\n" 12104 "#include \"string.h\"\n" 12105 "#include <a-a>\n" 12106 "#include < path with space >\n" 12107 "#include_next <test.h>" 12108 "#include \"abc.h\" // this is included for ABC\n" 12109 "#include \"some long include\" // with a comment\n" 12110 "#include \"some very long include path\"\n" 12111 "#include <some/very/long/include/path>\n", 12112 getLLVMStyleWithColumns(35)); 12113 EXPECT_EQ("#include \"a.h\"", format("#include \"a.h\"")); 12114 EXPECT_EQ("#include <a>", format("#include<a>")); 12115 12116 verifyFormat("#import <string>"); 12117 verifyFormat("#import <a/b/c.h>"); 12118 verifyFormat("#import \"a/b/string\""); 12119 verifyFormat("#import \"string.h\""); 12120 verifyFormat("#import \"string.h\""); 12121 verifyFormat("#if __has_include(<strstream>)\n" 12122 "#include <strstream>\n" 12123 "#endif"); 12124 12125 verifyFormat("#define MY_IMPORT <a/b>"); 12126 12127 verifyFormat("#if __has_include(<a/b>)"); 12128 verifyFormat("#if __has_include_next(<a/b>)"); 12129 verifyFormat("#define F __has_include(<a/b>)"); 12130 verifyFormat("#define F __has_include_next(<a/b>)"); 12131 12132 // Protocol buffer definition or missing "#". 12133 verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";", 12134 getLLVMStyleWithColumns(30)); 12135 12136 FormatStyle Style = getLLVMStyle(); 12137 Style.AlwaysBreakBeforeMultilineStrings = true; 12138 Style.ColumnLimit = 0; 12139 verifyFormat("#import \"abc.h\"", Style); 12140 12141 // But 'import' might also be a regular C++ namespace. 12142 verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12143 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 12144 } 12145 12146 //===----------------------------------------------------------------------===// 12147 // Error recovery tests. 12148 //===----------------------------------------------------------------------===// 12149 12150 TEST_F(FormatTest, IncompleteParameterLists) { 12151 FormatStyle NoBinPacking = getLLVMStyle(); 12152 NoBinPacking.BinPackParameters = false; 12153 verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n" 12154 " double *min_x,\n" 12155 " double *max_x,\n" 12156 " double *min_y,\n" 12157 " double *max_y,\n" 12158 " double *min_z,\n" 12159 " double *max_z, ) {}", 12160 NoBinPacking); 12161 } 12162 12163 TEST_F(FormatTest, IncorrectCodeTrailingStuff) { 12164 verifyFormat("void f() { return; }\n42"); 12165 verifyFormat("void f() {\n" 12166 " if (0)\n" 12167 " return;\n" 12168 "}\n" 12169 "42"); 12170 verifyFormat("void f() { return }\n42"); 12171 verifyFormat("void f() {\n" 12172 " if (0)\n" 12173 " return\n" 12174 "}\n" 12175 "42"); 12176 } 12177 12178 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) { 12179 EXPECT_EQ("void f() { return }", format("void f ( ) { return }")); 12180 EXPECT_EQ("void f() {\n" 12181 " if (a)\n" 12182 " return\n" 12183 "}", 12184 format("void f ( ) { if ( a ) return }")); 12185 EXPECT_EQ("namespace N {\n" 12186 "void f()\n" 12187 "}", 12188 format("namespace N { void f() }")); 12189 EXPECT_EQ("namespace N {\n" 12190 "void f() {}\n" 12191 "void g()\n" 12192 "} // namespace N", 12193 format("namespace N { void f( ) { } void g( ) }")); 12194 } 12195 12196 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) { 12197 verifyFormat("int aaaaaaaa =\n" 12198 " // Overlylongcomment\n" 12199 " b;", 12200 getLLVMStyleWithColumns(20)); 12201 verifyFormat("function(\n" 12202 " ShortArgument,\n" 12203 " LoooooooooooongArgument);\n", 12204 getLLVMStyleWithColumns(20)); 12205 } 12206 12207 TEST_F(FormatTest, IncorrectAccessSpecifier) { 12208 verifyFormat("public:"); 12209 verifyFormat("class A {\n" 12210 "public\n" 12211 " void f() {}\n" 12212 "};"); 12213 verifyFormat("public\n" 12214 "int qwerty;"); 12215 verifyFormat("public\n" 12216 "B {}"); 12217 verifyFormat("public\n" 12218 "{}"); 12219 verifyFormat("public\n" 12220 "B { int x; }"); 12221 } 12222 12223 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) { 12224 verifyFormat("{"); 12225 verifyFormat("#})"); 12226 verifyNoCrash("(/**/[:!] ?[)."); 12227 } 12228 12229 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) { 12230 // Found by oss-fuzz: 12231 // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212 12232 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp); 12233 Style.ColumnLimit = 60; 12234 verifyNoCrash( 12235 "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20" 12236 "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20" 12237 "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a", 12238 Style); 12239 } 12240 12241 TEST_F(FormatTest, IncorrectCodeDoNoWhile) { 12242 verifyFormat("do {\n}"); 12243 verifyFormat("do {\n}\n" 12244 "f();"); 12245 verifyFormat("do {\n}\n" 12246 "wheeee(fun);"); 12247 verifyFormat("do {\n" 12248 " f();\n" 12249 "}"); 12250 } 12251 12252 TEST_F(FormatTest, IncorrectCodeMissingParens) { 12253 verifyFormat("if {\n foo;\n foo();\n}"); 12254 verifyFormat("switch {\n foo;\n foo();\n}"); 12255 verifyIncompleteFormat("for {\n foo;\n foo();\n}"); 12256 verifyIncompleteFormat("ERROR: for target;"); 12257 verifyFormat("while {\n foo;\n foo();\n}"); 12258 verifyFormat("do {\n foo;\n foo();\n} while;"); 12259 } 12260 12261 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) { 12262 verifyIncompleteFormat("namespace {\n" 12263 "class Foo { Foo (\n" 12264 "};\n" 12265 "} // namespace"); 12266 } 12267 12268 TEST_F(FormatTest, IncorrectCodeErrorDetection) { 12269 EXPECT_EQ("{\n {}\n", format("{\n{\n}\n")); 12270 EXPECT_EQ("{\n {}\n", format("{\n {\n}\n")); 12271 EXPECT_EQ("{\n {}\n", format("{\n {\n }\n")); 12272 EXPECT_EQ("{\n {}\n}\n}\n", format("{\n {\n }\n }\n}\n")); 12273 12274 EXPECT_EQ("{\n" 12275 " {\n" 12276 " breakme(\n" 12277 " qwe);\n" 12278 " }\n", 12279 format("{\n" 12280 " {\n" 12281 " breakme(qwe);\n" 12282 "}\n", 12283 getLLVMStyleWithColumns(10))); 12284 } 12285 12286 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) { 12287 verifyFormat("int x = {\n" 12288 " avariable,\n" 12289 " b(alongervariable)};", 12290 getLLVMStyleWithColumns(25)); 12291 } 12292 12293 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) { 12294 verifyFormat("return (a)(b){1, 2, 3};"); 12295 } 12296 12297 TEST_F(FormatTest, LayoutCxx11BraceInitializers) { 12298 verifyFormat("vector<int> x{1, 2, 3, 4};"); 12299 verifyFormat("vector<int> x{\n" 12300 " 1,\n" 12301 " 2,\n" 12302 " 3,\n" 12303 " 4,\n" 12304 "};"); 12305 verifyFormat("vector<T> x{{}, {}, {}, {}};"); 12306 verifyFormat("f({1, 2});"); 12307 verifyFormat("auto v = Foo{-1};"); 12308 verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});"); 12309 verifyFormat("Class::Class : member{1, 2, 3} {}"); 12310 verifyFormat("new vector<int>{1, 2, 3};"); 12311 verifyFormat("new int[3]{1, 2, 3};"); 12312 verifyFormat("new int{1};"); 12313 verifyFormat("return {arg1, arg2};"); 12314 verifyFormat("return {arg1, SomeType{parameter}};"); 12315 verifyFormat("int count = set<int>{f(), g(), h()}.size();"); 12316 verifyFormat("new T{arg1, arg2};"); 12317 verifyFormat("f(MyMap[{composite, key}]);"); 12318 verifyFormat("class Class {\n" 12319 " T member = {arg1, arg2};\n" 12320 "};"); 12321 verifyFormat("vector<int> foo = {::SomeGlobalFunction()};"); 12322 verifyFormat("const struct A a = {.a = 1, .b = 2};"); 12323 verifyFormat("const struct A a = {[0] = 1, [1] = 2};"); 12324 verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");"); 12325 verifyFormat("int a = std::is_integral<int>{} + 0;"); 12326 12327 verifyFormat("int foo(int i) { return fo1{}(i); }"); 12328 verifyFormat("int foo(int i) { return fo1{}(i); }"); 12329 verifyFormat("auto i = decltype(x){};"); 12330 verifyFormat("auto i = typeof(x){};"); 12331 verifyFormat("auto i = _Atomic(x){};"); 12332 verifyFormat("std::vector<int> v = {1, 0 /* comment */};"); 12333 verifyFormat("Node n{1, Node{1000}, //\n" 12334 " 2};"); 12335 verifyFormat("Aaaa aaaaaaa{\n" 12336 " {\n" 12337 " aaaa,\n" 12338 " },\n" 12339 "};"); 12340 verifyFormat("class C : public D {\n" 12341 " SomeClass SC{2};\n" 12342 "};"); 12343 verifyFormat("class C : public A {\n" 12344 " class D : public B {\n" 12345 " void f() { int i{2}; }\n" 12346 " };\n" 12347 "};"); 12348 verifyFormat("#define A {a, a},"); 12349 // Don't confuse braced list initializers with compound statements. 12350 verifyFormat( 12351 "class A {\n" 12352 " A() : a{} {}\n" 12353 " A(int b) : b(b) {}\n" 12354 " A(int a, int b) : a(a), bs{{bs...}} { f(); }\n" 12355 " int a, b;\n" 12356 " explicit Expr(const Scalar<Result> &x) : u{Constant<Result>{x}} {}\n" 12357 " explicit Expr(Scalar<Result> &&x) : u{Constant<Result>{std::move(x)}} " 12358 "{}\n" 12359 "};"); 12360 12361 // Avoid breaking between equal sign and opening brace 12362 FormatStyle AvoidBreakingFirstArgument = getLLVMStyle(); 12363 AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200; 12364 verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n" 12365 " {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n" 12366 " {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n" 12367 " {\"ccccccccccccccccccccc\", 2}};", 12368 AvoidBreakingFirstArgument); 12369 12370 // Binpacking only if there is no trailing comma 12371 verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n" 12372 " cccccccccc, dddddddddd};", 12373 getLLVMStyleWithColumns(50)); 12374 verifyFormat("const Aaaaaa aaaaa = {\n" 12375 " aaaaaaaaaaa,\n" 12376 " bbbbbbbbbbb,\n" 12377 " ccccccccccc,\n" 12378 " ddddddddddd,\n" 12379 "};", 12380 getLLVMStyleWithColumns(50)); 12381 12382 // Cases where distinguising braced lists and blocks is hard. 12383 verifyFormat("vector<int> v{12} GUARDED_BY(mutex);"); 12384 verifyFormat("void f() {\n" 12385 " return; // comment\n" 12386 "}\n" 12387 "SomeType t;"); 12388 verifyFormat("void f() {\n" 12389 " if (a) {\n" 12390 " f();\n" 12391 " }\n" 12392 "}\n" 12393 "SomeType t;"); 12394 12395 // In combination with BinPackArguments = false. 12396 FormatStyle NoBinPacking = getLLVMStyle(); 12397 NoBinPacking.BinPackArguments = false; 12398 verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n" 12399 " bbbbb,\n" 12400 " ccccc,\n" 12401 " ddddd,\n" 12402 " eeeee,\n" 12403 " ffffff,\n" 12404 " ggggg,\n" 12405 " hhhhhh,\n" 12406 " iiiiii,\n" 12407 " jjjjjj,\n" 12408 " kkkkkk};", 12409 NoBinPacking); 12410 verifyFormat("const Aaaaaa aaaaa = {\n" 12411 " aaaaa,\n" 12412 " bbbbb,\n" 12413 " ccccc,\n" 12414 " ddddd,\n" 12415 " eeeee,\n" 12416 " ffffff,\n" 12417 " ggggg,\n" 12418 " hhhhhh,\n" 12419 " iiiiii,\n" 12420 " jjjjjj,\n" 12421 " kkkkkk,\n" 12422 "};", 12423 NoBinPacking); 12424 verifyFormat( 12425 "const Aaaaaa aaaaa = {\n" 12426 " aaaaa, bbbbb, ccccc, ddddd, eeeee, ffffff, ggggg, hhhhhh,\n" 12427 " iiiiii, jjjjjj, kkkkkk, aaaaa, bbbbb, ccccc, ddddd, eeeee,\n" 12428 " ffffff, ggggg, hhhhhh, iiiiii, jjjjjj, kkkkkk,\n" 12429 "};", 12430 NoBinPacking); 12431 12432 NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 12433 EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n" 12434 " CDDDP83848_BMCR_REGISTER,\n" 12435 " CDDDP83848_BMSR_REGISTER,\n" 12436 " CDDDP83848_RBR_REGISTER};", 12437 format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n" 12438 " CDDDP83848_BMSR_REGISTER,\n" 12439 " CDDDP83848_RBR_REGISTER};", 12440 NoBinPacking)); 12441 12442 // FIXME: The alignment of these trailing comments might be bad. Then again, 12443 // this might be utterly useless in real code. 12444 verifyFormat("Constructor::Constructor()\n" 12445 " : some_value{ //\n" 12446 " aaaaaaa, //\n" 12447 " bbbbbbb} {}"); 12448 12449 // In braced lists, the first comment is always assumed to belong to the 12450 // first element. Thus, it can be moved to the next or previous line as 12451 // appropriate. 12452 EXPECT_EQ("function({// First element:\n" 12453 " 1,\n" 12454 " // Second element:\n" 12455 " 2});", 12456 format("function({\n" 12457 " // First element:\n" 12458 " 1,\n" 12459 " // Second element:\n" 12460 " 2});")); 12461 EXPECT_EQ("std::vector<int> MyNumbers{\n" 12462 " // First element:\n" 12463 " 1,\n" 12464 " // Second element:\n" 12465 " 2};", 12466 format("std::vector<int> MyNumbers{// First element:\n" 12467 " 1,\n" 12468 " // Second element:\n" 12469 " 2};", 12470 getLLVMStyleWithColumns(30))); 12471 // A trailing comma should still lead to an enforced line break and no 12472 // binpacking. 12473 EXPECT_EQ("vector<int> SomeVector = {\n" 12474 " // aaa\n" 12475 " 1,\n" 12476 " 2,\n" 12477 "};", 12478 format("vector<int> SomeVector = { // aaa\n" 12479 " 1, 2, };")); 12480 12481 // C++11 brace initializer list l-braces should not be treated any differently 12482 // when breaking before lambda bodies is enabled 12483 FormatStyle BreakBeforeLambdaBody = getLLVMStyle(); 12484 BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 12485 BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 12486 BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true; 12487 verifyFormat( 12488 "std::runtime_error{\n" 12489 " \"Long string which will force a break onto the next line...\"};", 12490 BreakBeforeLambdaBody); 12491 12492 FormatStyle ExtraSpaces = getLLVMStyle(); 12493 ExtraSpaces.Cpp11BracedListStyle = false; 12494 ExtraSpaces.ColumnLimit = 75; 12495 verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces); 12496 verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces); 12497 verifyFormat("f({ 1, 2 });", ExtraSpaces); 12498 verifyFormat("auto v = Foo{ 1 };", ExtraSpaces); 12499 verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces); 12500 verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces); 12501 verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces); 12502 verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces); 12503 verifyFormat("return { arg1, arg2 };", ExtraSpaces); 12504 verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces); 12505 verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces); 12506 verifyFormat("new T{ arg1, arg2 };", ExtraSpaces); 12507 verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces); 12508 verifyFormat("class Class {\n" 12509 " T member = { arg1, arg2 };\n" 12510 "};", 12511 ExtraSpaces); 12512 verifyFormat( 12513 "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12514 " aaaaaaaaaaaaaaaaaaaa, aaaaa }\n" 12515 " : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 12516 " bbbbbbbbbbbbbbbbbbbb, bbbbb };", 12517 ExtraSpaces); 12518 verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces); 12519 verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });", 12520 ExtraSpaces); 12521 verifyFormat( 12522 "someFunction(OtherParam,\n" 12523 " BracedList{ // comment 1 (Forcing interesting break)\n" 12524 " param1, param2,\n" 12525 " // comment 2\n" 12526 " param3, param4 });", 12527 ExtraSpaces); 12528 verifyFormat( 12529 "std::this_thread::sleep_for(\n" 12530 " std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);", 12531 ExtraSpaces); 12532 verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n" 12533 " aaaaaaa,\n" 12534 " aaaaaaaaaa,\n" 12535 " aaaaa,\n" 12536 " aaaaaaaaaaaaaaa,\n" 12537 " aaa,\n" 12538 " aaaaaaaaaa,\n" 12539 " a,\n" 12540 " aaaaaaaaaaaaaaaaaaaaa,\n" 12541 " aaaaaaaaaaaa,\n" 12542 " aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n" 12543 " aaaaaaa,\n" 12544 " a};"); 12545 verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces); 12546 verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces); 12547 verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces); 12548 12549 // Avoid breaking between initializer/equal sign and opening brace 12550 ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200; 12551 verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n" 12552 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n" 12553 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n" 12554 " { \"ccccccccccccccccccccc\", 2 }\n" 12555 "};", 12556 ExtraSpaces); 12557 verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n" 12558 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n" 12559 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n" 12560 " { \"ccccccccccccccccccccc\", 2 }\n" 12561 "};", 12562 ExtraSpaces); 12563 12564 FormatStyle SpaceBeforeBrace = getLLVMStyle(); 12565 SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true; 12566 verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace); 12567 verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace); 12568 12569 FormatStyle SpaceBetweenBraces = getLLVMStyle(); 12570 SpaceBetweenBraces.SpacesInAngles = FormatStyle::SIAS_Always; 12571 SpaceBetweenBraces.SpacesInParentheses = true; 12572 SpaceBetweenBraces.SpacesInSquareBrackets = true; 12573 verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces); 12574 verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces); 12575 verifyFormat("vector< int > x{ // comment 1\n" 12576 " 1, 2, 3, 4 };", 12577 SpaceBetweenBraces); 12578 SpaceBetweenBraces.ColumnLimit = 20; 12579 EXPECT_EQ("vector< int > x{\n" 12580 " 1, 2, 3, 4 };", 12581 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces)); 12582 SpaceBetweenBraces.ColumnLimit = 24; 12583 EXPECT_EQ("vector< int > x{ 1, 2,\n" 12584 " 3, 4 };", 12585 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces)); 12586 EXPECT_EQ("vector< int > x{\n" 12587 " 1,\n" 12588 " 2,\n" 12589 " 3,\n" 12590 " 4,\n" 12591 "};", 12592 format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces)); 12593 verifyFormat("vector< int > x{};", SpaceBetweenBraces); 12594 SpaceBetweenBraces.SpaceInEmptyParentheses = true; 12595 verifyFormat("vector< int > x{ };", SpaceBetweenBraces); 12596 } 12597 12598 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) { 12599 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12600 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12601 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12602 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12603 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12604 " 1, 22, 333, 4444, 55555, 666666, 7777777};"); 12605 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n" 12606 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12607 " 1, 22, 333, 4444, 55555, //\n" 12608 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12609 " 1, 22, 333, 4444, 55555, 666666, 7777777};"); 12610 verifyFormat( 12611 "vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12612 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12613 " 1, 22, 333, 4444, 55555, 666666, // comment\n" 12614 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12615 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12616 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12617 " 7777777};"); 12618 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12619 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12620 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12621 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12622 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12623 " // Separating comment.\n" 12624 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12625 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12626 " // Leading comment\n" 12627 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12628 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12629 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12630 " 1, 1, 1, 1};", 12631 getLLVMStyleWithColumns(39)); 12632 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12633 " 1, 1, 1, 1};", 12634 getLLVMStyleWithColumns(38)); 12635 verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n" 12636 " 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};", 12637 getLLVMStyleWithColumns(43)); 12638 verifyFormat( 12639 "static unsigned SomeValues[10][3] = {\n" 12640 " {1, 4, 0}, {4, 9, 0}, {4, 5, 9}, {8, 5, 4}, {1, 8, 4},\n" 12641 " {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};"); 12642 verifyFormat("static auto fields = new vector<string>{\n" 12643 " \"aaaaaaaaaaaaa\",\n" 12644 " \"aaaaaaaaaaaaa\",\n" 12645 " \"aaaaaaaaaaaa\",\n" 12646 " \"aaaaaaaaaaaaaa\",\n" 12647 " \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n" 12648 " \"aaaaaaaaaaaa\",\n" 12649 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n" 12650 "};"); 12651 verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};"); 12652 verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n" 12653 " 2, bbbbbbbbbbbbbbbbbbbbbb,\n" 12654 " 3, cccccccccccccccccccccc};", 12655 getLLVMStyleWithColumns(60)); 12656 12657 // Trailing commas. 12658 verifyFormat("vector<int> x = {\n" 12659 " 1, 1, 1, 1, 1, 1, 1, 1,\n" 12660 "};", 12661 getLLVMStyleWithColumns(39)); 12662 verifyFormat("vector<int> x = {\n" 12663 " 1, 1, 1, 1, 1, 1, 1, 1, //\n" 12664 "};", 12665 getLLVMStyleWithColumns(39)); 12666 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12667 " 1, 1, 1, 1,\n" 12668 " /**/ /**/};", 12669 getLLVMStyleWithColumns(39)); 12670 12671 // Trailing comment in the first line. 12672 verifyFormat("vector<int> iiiiiiiiiiiiiii = { //\n" 12673 " 1111111111, 2222222222, 33333333333, 4444444444, //\n" 12674 " 111111111, 222222222, 3333333333, 444444444, //\n" 12675 " 11111111, 22222222, 333333333, 44444444};"); 12676 // Trailing comment in the last line. 12677 verifyFormat("int aaaaa[] = {\n" 12678 " 1, 2, 3, // comment\n" 12679 " 4, 5, 6 // comment\n" 12680 "};"); 12681 12682 // With nested lists, we should either format one item per line or all nested 12683 // lists one on line. 12684 // FIXME: For some nested lists, we can do better. 12685 verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n" 12686 " {aaaaaaaaaaaaaaaaaaa},\n" 12687 " {aaaaaaaaaaaaaaaaaaaaa},\n" 12688 " {aaaaaaaaaaaaaaaaa}};", 12689 getLLVMStyleWithColumns(60)); 12690 verifyFormat( 12691 "SomeStruct my_struct_array = {\n" 12692 " {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n" 12693 " aaaaaaaaaaaaa, aaaaaaa, aaa},\n" 12694 " {aaa, aaa},\n" 12695 " {aaa, aaa},\n" 12696 " {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n" 12697 " {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n" 12698 " aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};"); 12699 12700 // No column layout should be used here. 12701 verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n" 12702 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};"); 12703 12704 verifyNoCrash("a<,"); 12705 12706 // No braced initializer here. 12707 verifyFormat("void f() {\n" 12708 " struct Dummy {};\n" 12709 " f(v);\n" 12710 "}"); 12711 12712 // Long lists should be formatted in columns even if they are nested. 12713 verifyFormat( 12714 "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12715 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12716 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12717 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12718 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12719 " 1, 22, 333, 4444, 55555, 666666, 7777777});"); 12720 12721 // Allow "single-column" layout even if that violates the column limit. There 12722 // isn't going to be a better way. 12723 verifyFormat("std::vector<int> a = {\n" 12724 " aaaaaaaa,\n" 12725 " aaaaaaaa,\n" 12726 " aaaaaaaa,\n" 12727 " aaaaaaaa,\n" 12728 " aaaaaaaaaa,\n" 12729 " aaaaaaaa,\n" 12730 " aaaaaaaaaaaaaaaaaaaaaaaaaaa};", 12731 getLLVMStyleWithColumns(30)); 12732 verifyFormat("vector<int> aaaa = {\n" 12733 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12734 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12735 " aaaaaa.aaaaaaa,\n" 12736 " aaaaaa.aaaaaaa,\n" 12737 " aaaaaa.aaaaaaa,\n" 12738 " aaaaaa.aaaaaaa,\n" 12739 "};"); 12740 12741 // Don't create hanging lists. 12742 verifyFormat("someFunction(Param, {List1, List2,\n" 12743 " List3});", 12744 getLLVMStyleWithColumns(35)); 12745 verifyFormat("someFunction(Param, Param,\n" 12746 " {List1, List2,\n" 12747 " List3});", 12748 getLLVMStyleWithColumns(35)); 12749 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n" 12750 " aaaaaaaaaaaaaaaaaaaaaaa);"); 12751 } 12752 12753 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) { 12754 FormatStyle DoNotMerge = getLLVMStyle(); 12755 DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12756 12757 verifyFormat("void f() { return 42; }"); 12758 verifyFormat("void f() {\n" 12759 " return 42;\n" 12760 "}", 12761 DoNotMerge); 12762 verifyFormat("void f() {\n" 12763 " // Comment\n" 12764 "}"); 12765 verifyFormat("{\n" 12766 "#error {\n" 12767 " int a;\n" 12768 "}"); 12769 verifyFormat("{\n" 12770 " int a;\n" 12771 "#error {\n" 12772 "}"); 12773 verifyFormat("void f() {} // comment"); 12774 verifyFormat("void f() { int a; } // comment"); 12775 verifyFormat("void f() {\n" 12776 "} // comment", 12777 DoNotMerge); 12778 verifyFormat("void f() {\n" 12779 " int a;\n" 12780 "} // comment", 12781 DoNotMerge); 12782 verifyFormat("void f() {\n" 12783 "} // comment", 12784 getLLVMStyleWithColumns(15)); 12785 12786 verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23)); 12787 verifyFormat("void f() {\n return 42;\n}", getLLVMStyleWithColumns(22)); 12788 12789 verifyFormat("void f() {}", getLLVMStyleWithColumns(11)); 12790 verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10)); 12791 verifyFormat("class C {\n" 12792 " C()\n" 12793 " : iiiiiiii(nullptr),\n" 12794 " kkkkkkk(nullptr),\n" 12795 " mmmmmmm(nullptr),\n" 12796 " nnnnnnn(nullptr) {}\n" 12797 "};", 12798 getGoogleStyle()); 12799 12800 FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0); 12801 EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit)); 12802 EXPECT_EQ("class C {\n" 12803 " A() : b(0) {}\n" 12804 "};", 12805 format("class C{A():b(0){}};", NoColumnLimit)); 12806 EXPECT_EQ("A()\n" 12807 " : b(0) {\n" 12808 "}", 12809 format("A()\n:b(0)\n{\n}", NoColumnLimit)); 12810 12811 FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit; 12812 DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine = 12813 FormatStyle::SFS_None; 12814 EXPECT_EQ("A()\n" 12815 " : b(0) {\n" 12816 "}", 12817 format("A():b(0){}", DoNotMergeNoColumnLimit)); 12818 EXPECT_EQ("A()\n" 12819 " : b(0) {\n" 12820 "}", 12821 format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit)); 12822 12823 verifyFormat("#define A \\\n" 12824 " void f() { \\\n" 12825 " int i; \\\n" 12826 " }", 12827 getLLVMStyleWithColumns(20)); 12828 verifyFormat("#define A \\\n" 12829 " void f() { int i; }", 12830 getLLVMStyleWithColumns(21)); 12831 verifyFormat("#define A \\\n" 12832 " void f() { \\\n" 12833 " int i; \\\n" 12834 " } \\\n" 12835 " int j;", 12836 getLLVMStyleWithColumns(22)); 12837 verifyFormat("#define A \\\n" 12838 " void f() { int i; } \\\n" 12839 " int j;", 12840 getLLVMStyleWithColumns(23)); 12841 } 12842 12843 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) { 12844 FormatStyle MergeEmptyOnly = getLLVMStyle(); 12845 MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 12846 verifyFormat("class C {\n" 12847 " int f() {}\n" 12848 "};", 12849 MergeEmptyOnly); 12850 verifyFormat("class C {\n" 12851 " int f() {\n" 12852 " return 42;\n" 12853 " }\n" 12854 "};", 12855 MergeEmptyOnly); 12856 verifyFormat("int f() {}", MergeEmptyOnly); 12857 verifyFormat("int f() {\n" 12858 " return 42;\n" 12859 "}", 12860 MergeEmptyOnly); 12861 12862 // Also verify behavior when BraceWrapping.AfterFunction = true 12863 MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12864 MergeEmptyOnly.BraceWrapping.AfterFunction = true; 12865 verifyFormat("int f() {}", MergeEmptyOnly); 12866 verifyFormat("class C {\n" 12867 " int f() {}\n" 12868 "};", 12869 MergeEmptyOnly); 12870 } 12871 12872 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) { 12873 FormatStyle MergeInlineOnly = getLLVMStyle(); 12874 MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 12875 verifyFormat("class C {\n" 12876 " int f() { return 42; }\n" 12877 "};", 12878 MergeInlineOnly); 12879 verifyFormat("int f() {\n" 12880 " return 42;\n" 12881 "}", 12882 MergeInlineOnly); 12883 12884 // SFS_Inline implies SFS_Empty 12885 verifyFormat("class C {\n" 12886 " int f() {}\n" 12887 "};", 12888 MergeInlineOnly); 12889 verifyFormat("int f() {}", MergeInlineOnly); 12890 // https://llvm.org/PR54147 12891 verifyFormat("auto lambda = []() {\n" 12892 " // comment\n" 12893 " f();\n" 12894 " g();\n" 12895 "};", 12896 MergeInlineOnly); 12897 12898 verifyFormat("class C {\n" 12899 "#ifdef A\n" 12900 " int f() { return 42; }\n" 12901 "#endif\n" 12902 "};", 12903 MergeInlineOnly); 12904 12905 verifyFormat("struct S {\n" 12906 "// comment\n" 12907 "#ifdef FOO\n" 12908 " int foo() { bar(); }\n" 12909 "#endif\n" 12910 "};", 12911 MergeInlineOnly); 12912 12913 // Also verify behavior when BraceWrapping.AfterFunction = true 12914 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12915 MergeInlineOnly.BraceWrapping.AfterFunction = true; 12916 verifyFormat("class C {\n" 12917 " int f() { return 42; }\n" 12918 "};", 12919 MergeInlineOnly); 12920 verifyFormat("int f()\n" 12921 "{\n" 12922 " return 42;\n" 12923 "}", 12924 MergeInlineOnly); 12925 12926 // SFS_Inline implies SFS_Empty 12927 verifyFormat("int f() {}", MergeInlineOnly); 12928 verifyFormat("class C {\n" 12929 " int f() {}\n" 12930 "};", 12931 MergeInlineOnly); 12932 12933 MergeInlineOnly.BraceWrapping.AfterClass = true; 12934 MergeInlineOnly.BraceWrapping.AfterStruct = true; 12935 verifyFormat("class C\n" 12936 "{\n" 12937 " int f() { return 42; }\n" 12938 "};", 12939 MergeInlineOnly); 12940 verifyFormat("struct C\n" 12941 "{\n" 12942 " int f() { return 42; }\n" 12943 "};", 12944 MergeInlineOnly); 12945 verifyFormat("int f()\n" 12946 "{\n" 12947 " return 42;\n" 12948 "}", 12949 MergeInlineOnly); 12950 verifyFormat("int f() {}", MergeInlineOnly); 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("struct C\n" 12962 "// comment\n" 12963 "/* comment */\n" 12964 "// comment\n" 12965 "{\n" 12966 " int f() { return 42; }\n" 12967 "};", 12968 MergeInlineOnly); 12969 verifyFormat("/* comment */ struct C\n" 12970 "{\n" 12971 " int f() { return 42; }\n" 12972 "};", 12973 MergeInlineOnly); 12974 } 12975 12976 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) { 12977 FormatStyle MergeInlineOnly = getLLVMStyle(); 12978 MergeInlineOnly.AllowShortFunctionsOnASingleLine = 12979 FormatStyle::SFS_InlineOnly; 12980 verifyFormat("class C {\n" 12981 " int f() { return 42; }\n" 12982 "};", 12983 MergeInlineOnly); 12984 verifyFormat("int f() {\n" 12985 " return 42;\n" 12986 "}", 12987 MergeInlineOnly); 12988 12989 // SFS_InlineOnly does not imply SFS_Empty 12990 verifyFormat("class C {\n" 12991 " int f() {}\n" 12992 "};", 12993 MergeInlineOnly); 12994 verifyFormat("int f() {\n" 12995 "}", 12996 MergeInlineOnly); 12997 12998 // Also verify behavior when BraceWrapping.AfterFunction = true 12999 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 13000 MergeInlineOnly.BraceWrapping.AfterFunction = true; 13001 verifyFormat("class C {\n" 13002 " int f() { return 42; }\n" 13003 "};", 13004 MergeInlineOnly); 13005 verifyFormat("int f()\n" 13006 "{\n" 13007 " return 42;\n" 13008 "}", 13009 MergeInlineOnly); 13010 13011 // SFS_InlineOnly does not imply SFS_Empty 13012 verifyFormat("int f()\n" 13013 "{\n" 13014 "}", 13015 MergeInlineOnly); 13016 verifyFormat("class C {\n" 13017 " int f() {}\n" 13018 "};", 13019 MergeInlineOnly); 13020 } 13021 13022 TEST_F(FormatTest, SplitEmptyFunction) { 13023 FormatStyle Style = getLLVMStyleWithColumns(40); 13024 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 13025 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13026 Style.BraceWrapping.AfterFunction = true; 13027 Style.BraceWrapping.SplitEmptyFunction = false; 13028 13029 verifyFormat("int f()\n" 13030 "{}", 13031 Style); 13032 verifyFormat("int f()\n" 13033 "{\n" 13034 " return 42;\n" 13035 "}", 13036 Style); 13037 verifyFormat("int f()\n" 13038 "{\n" 13039 " // some comment\n" 13040 "}", 13041 Style); 13042 13043 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 13044 verifyFormat("int f() {}", Style); 13045 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 13046 "{}", 13047 Style); 13048 verifyFormat("int f()\n" 13049 "{\n" 13050 " return 0;\n" 13051 "}", 13052 Style); 13053 13054 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 13055 verifyFormat("class Foo {\n" 13056 " int f() {}\n" 13057 "};\n", 13058 Style); 13059 verifyFormat("class Foo {\n" 13060 " int f() { return 0; }\n" 13061 "};\n", 13062 Style); 13063 verifyFormat("class Foo {\n" 13064 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 13065 " {}\n" 13066 "};\n", 13067 Style); 13068 verifyFormat("class Foo {\n" 13069 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 13070 " {\n" 13071 " return 0;\n" 13072 " }\n" 13073 "};\n", 13074 Style); 13075 13076 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 13077 verifyFormat("int f() {}", Style); 13078 verifyFormat("int f() { return 0; }", Style); 13079 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 13080 "{}", 13081 Style); 13082 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 13083 "{\n" 13084 " return 0;\n" 13085 "}", 13086 Style); 13087 } 13088 13089 TEST_F(FormatTest, SplitEmptyFunctionButNotRecord) { 13090 FormatStyle Style = getLLVMStyleWithColumns(40); 13091 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 13092 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13093 Style.BraceWrapping.AfterFunction = true; 13094 Style.BraceWrapping.SplitEmptyFunction = true; 13095 Style.BraceWrapping.SplitEmptyRecord = false; 13096 13097 verifyFormat("class C {};", Style); 13098 verifyFormat("struct C {};", Style); 13099 verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 13100 " int bbbbbbbbbbbbbbbbbbbbbbbb)\n" 13101 "{\n" 13102 "}", 13103 Style); 13104 verifyFormat("class C {\n" 13105 " C()\n" 13106 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa(),\n" 13107 " bbbbbbbbbbbbbbbbbbb()\n" 13108 " {\n" 13109 " }\n" 13110 " void\n" 13111 " m(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 13112 " int bbbbbbbbbbbbbbbbbbbbbbbb)\n" 13113 " {\n" 13114 " }\n" 13115 "};", 13116 Style); 13117 } 13118 13119 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) { 13120 FormatStyle Style = getLLVMStyle(); 13121 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 13122 verifyFormat("#ifdef A\n" 13123 "int f() {}\n" 13124 "#else\n" 13125 "int g() {}\n" 13126 "#endif", 13127 Style); 13128 } 13129 13130 TEST_F(FormatTest, SplitEmptyClass) { 13131 FormatStyle Style = getLLVMStyle(); 13132 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13133 Style.BraceWrapping.AfterClass = true; 13134 Style.BraceWrapping.SplitEmptyRecord = false; 13135 13136 verifyFormat("class Foo\n" 13137 "{};", 13138 Style); 13139 verifyFormat("/* something */ class Foo\n" 13140 "{};", 13141 Style); 13142 verifyFormat("template <typename X> class Foo\n" 13143 "{};", 13144 Style); 13145 verifyFormat("class Foo\n" 13146 "{\n" 13147 " Foo();\n" 13148 "};", 13149 Style); 13150 verifyFormat("typedef class Foo\n" 13151 "{\n" 13152 "} Foo_t;", 13153 Style); 13154 13155 Style.BraceWrapping.SplitEmptyRecord = true; 13156 Style.BraceWrapping.AfterStruct = true; 13157 verifyFormat("class rep\n" 13158 "{\n" 13159 "};", 13160 Style); 13161 verifyFormat("struct rep\n" 13162 "{\n" 13163 "};", 13164 Style); 13165 verifyFormat("template <typename T> class rep\n" 13166 "{\n" 13167 "};", 13168 Style); 13169 verifyFormat("template <typename T> struct rep\n" 13170 "{\n" 13171 "};", 13172 Style); 13173 verifyFormat("class rep\n" 13174 "{\n" 13175 " int x;\n" 13176 "};", 13177 Style); 13178 verifyFormat("struct rep\n" 13179 "{\n" 13180 " int x;\n" 13181 "};", 13182 Style); 13183 verifyFormat("template <typename T> class rep\n" 13184 "{\n" 13185 " int x;\n" 13186 "};", 13187 Style); 13188 verifyFormat("template <typename T> struct rep\n" 13189 "{\n" 13190 " int x;\n" 13191 "};", 13192 Style); 13193 verifyFormat("template <typename T> class rep // Foo\n" 13194 "{\n" 13195 " int x;\n" 13196 "};", 13197 Style); 13198 verifyFormat("template <typename T> struct rep // Bar\n" 13199 "{\n" 13200 " int x;\n" 13201 "};", 13202 Style); 13203 13204 verifyFormat("template <typename T> class rep<T>\n" 13205 "{\n" 13206 " int x;\n" 13207 "};", 13208 Style); 13209 13210 verifyFormat("template <typename T> class rep<std::complex<T>>\n" 13211 "{\n" 13212 " int x;\n" 13213 "};", 13214 Style); 13215 verifyFormat("template <typename T> class rep<std::complex<T>>\n" 13216 "{\n" 13217 "};", 13218 Style); 13219 13220 verifyFormat("#include \"stdint.h\"\n" 13221 "namespace rep {}", 13222 Style); 13223 verifyFormat("#include <stdint.h>\n" 13224 "namespace rep {}", 13225 Style); 13226 verifyFormat("#include <stdint.h>\n" 13227 "namespace rep {}", 13228 "#include <stdint.h>\n" 13229 "namespace rep {\n" 13230 "\n" 13231 "\n" 13232 "}", 13233 Style); 13234 } 13235 13236 TEST_F(FormatTest, SplitEmptyStruct) { 13237 FormatStyle Style = getLLVMStyle(); 13238 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13239 Style.BraceWrapping.AfterStruct = true; 13240 Style.BraceWrapping.SplitEmptyRecord = false; 13241 13242 verifyFormat("struct Foo\n" 13243 "{};", 13244 Style); 13245 verifyFormat("/* something */ struct Foo\n" 13246 "{};", 13247 Style); 13248 verifyFormat("template <typename X> struct Foo\n" 13249 "{};", 13250 Style); 13251 verifyFormat("struct Foo\n" 13252 "{\n" 13253 " Foo();\n" 13254 "};", 13255 Style); 13256 verifyFormat("typedef struct Foo\n" 13257 "{\n" 13258 "} Foo_t;", 13259 Style); 13260 // typedef struct Bar {} Bar_t; 13261 } 13262 13263 TEST_F(FormatTest, SplitEmptyUnion) { 13264 FormatStyle Style = getLLVMStyle(); 13265 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13266 Style.BraceWrapping.AfterUnion = true; 13267 Style.BraceWrapping.SplitEmptyRecord = false; 13268 13269 verifyFormat("union Foo\n" 13270 "{};", 13271 Style); 13272 verifyFormat("/* something */ union Foo\n" 13273 "{};", 13274 Style); 13275 verifyFormat("union Foo\n" 13276 "{\n" 13277 " A,\n" 13278 "};", 13279 Style); 13280 verifyFormat("typedef union Foo\n" 13281 "{\n" 13282 "} Foo_t;", 13283 Style); 13284 } 13285 13286 TEST_F(FormatTest, SplitEmptyNamespace) { 13287 FormatStyle Style = getLLVMStyle(); 13288 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13289 Style.BraceWrapping.AfterNamespace = true; 13290 Style.BraceWrapping.SplitEmptyNamespace = false; 13291 13292 verifyFormat("namespace Foo\n" 13293 "{};", 13294 Style); 13295 verifyFormat("/* something */ namespace Foo\n" 13296 "{};", 13297 Style); 13298 verifyFormat("inline namespace Foo\n" 13299 "{};", 13300 Style); 13301 verifyFormat("/* something */ inline namespace Foo\n" 13302 "{};", 13303 Style); 13304 verifyFormat("export namespace Foo\n" 13305 "{};", 13306 Style); 13307 verifyFormat("namespace Foo\n" 13308 "{\n" 13309 "void Bar();\n" 13310 "};", 13311 Style); 13312 } 13313 13314 TEST_F(FormatTest, NeverMergeShortRecords) { 13315 FormatStyle Style = getLLVMStyle(); 13316 13317 verifyFormat("class Foo {\n" 13318 " Foo();\n" 13319 "};", 13320 Style); 13321 verifyFormat("typedef class Foo {\n" 13322 " Foo();\n" 13323 "} Foo_t;", 13324 Style); 13325 verifyFormat("struct Foo {\n" 13326 " Foo();\n" 13327 "};", 13328 Style); 13329 verifyFormat("typedef struct Foo {\n" 13330 " Foo();\n" 13331 "} Foo_t;", 13332 Style); 13333 verifyFormat("union Foo {\n" 13334 " A,\n" 13335 "};", 13336 Style); 13337 verifyFormat("typedef union Foo {\n" 13338 " A,\n" 13339 "} Foo_t;", 13340 Style); 13341 verifyFormat("namespace Foo {\n" 13342 "void Bar();\n" 13343 "};", 13344 Style); 13345 13346 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13347 Style.BraceWrapping.AfterClass = true; 13348 Style.BraceWrapping.AfterStruct = true; 13349 Style.BraceWrapping.AfterUnion = true; 13350 Style.BraceWrapping.AfterNamespace = true; 13351 verifyFormat("class Foo\n" 13352 "{\n" 13353 " Foo();\n" 13354 "};", 13355 Style); 13356 verifyFormat("typedef class Foo\n" 13357 "{\n" 13358 " Foo();\n" 13359 "} Foo_t;", 13360 Style); 13361 verifyFormat("struct Foo\n" 13362 "{\n" 13363 " Foo();\n" 13364 "};", 13365 Style); 13366 verifyFormat("typedef struct Foo\n" 13367 "{\n" 13368 " Foo();\n" 13369 "} Foo_t;", 13370 Style); 13371 verifyFormat("union Foo\n" 13372 "{\n" 13373 " A,\n" 13374 "};", 13375 Style); 13376 verifyFormat("typedef union Foo\n" 13377 "{\n" 13378 " A,\n" 13379 "} Foo_t;", 13380 Style); 13381 verifyFormat("namespace Foo\n" 13382 "{\n" 13383 "void Bar();\n" 13384 "};", 13385 Style); 13386 } 13387 13388 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) { 13389 // Elaborate type variable declarations. 13390 verifyFormat("struct foo a = {bar};\nint n;"); 13391 verifyFormat("class foo a = {bar};\nint n;"); 13392 verifyFormat("union foo a = {bar};\nint n;"); 13393 13394 // Elaborate types inside function definitions. 13395 verifyFormat("struct foo f() {}\nint n;"); 13396 verifyFormat("class foo f() {}\nint n;"); 13397 verifyFormat("union foo f() {}\nint n;"); 13398 13399 // Templates. 13400 verifyFormat("template <class X> void f() {}\nint n;"); 13401 verifyFormat("template <struct X> void f() {}\nint n;"); 13402 verifyFormat("template <union X> void f() {}\nint n;"); 13403 13404 // Actual definitions... 13405 verifyFormat("struct {\n} n;"); 13406 verifyFormat( 13407 "template <template <class T, class Y>, class Z> class X {\n} n;"); 13408 verifyFormat("union Z {\n int n;\n} x;"); 13409 verifyFormat("class MACRO Z {\n} n;"); 13410 verifyFormat("class MACRO(X) Z {\n} n;"); 13411 verifyFormat("class __attribute__(X) Z {\n} n;"); 13412 verifyFormat("class __declspec(X) Z {\n} n;"); 13413 verifyFormat("class A##B##C {\n} n;"); 13414 verifyFormat("class alignas(16) Z {\n} n;"); 13415 verifyFormat("class MACRO(X) alignas(16) Z {\n} n;"); 13416 verifyFormat("class MACROA MACRO(X) Z {\n} n;"); 13417 13418 // Redefinition from nested context: 13419 verifyFormat("class A::B::C {\n} n;"); 13420 13421 // Template definitions. 13422 verifyFormat( 13423 "template <typename F>\n" 13424 "Matcher(const Matcher<F> &Other,\n" 13425 " typename enable_if_c<is_base_of<F, T>::value &&\n" 13426 " !is_same<F, T>::value>::type * = 0)\n" 13427 " : Implementation(new ImplicitCastMatcher<F>(Other)) {}"); 13428 13429 // FIXME: This is still incorrectly handled at the formatter side. 13430 verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};"); 13431 verifyFormat("int i = SomeFunction(a<b, a> b);"); 13432 13433 // FIXME: 13434 // This now gets parsed incorrectly as class definition. 13435 // verifyFormat("class A<int> f() {\n}\nint n;"); 13436 13437 // Elaborate types where incorrectly parsing the structural element would 13438 // break the indent. 13439 verifyFormat("if (true)\n" 13440 " class X x;\n" 13441 "else\n" 13442 " f();\n"); 13443 13444 // This is simply incomplete. Formatting is not important, but must not crash. 13445 verifyFormat("class A:"); 13446 } 13447 13448 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) { 13449 EXPECT_EQ("#error Leave all white!!!!! space* alone!\n", 13450 format("#error Leave all white!!!!! space* alone!\n")); 13451 EXPECT_EQ( 13452 "#warning Leave all white!!!!! space* alone!\n", 13453 format("#warning Leave all white!!!!! space* alone!\n")); 13454 EXPECT_EQ("#error 1", format(" # error 1")); 13455 EXPECT_EQ("#warning 1", format(" # warning 1")); 13456 } 13457 13458 TEST_F(FormatTest, FormatHashIfExpressions) { 13459 verifyFormat("#if AAAA && BBBB"); 13460 verifyFormat("#if (AAAA && BBBB)"); 13461 verifyFormat("#elif (AAAA && BBBB)"); 13462 // FIXME: Come up with a better indentation for #elif. 13463 verifyFormat( 13464 "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) && \\\n" 13465 " defined(BBBBBBBB)\n" 13466 "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) && \\\n" 13467 " defined(BBBBBBBB)\n" 13468 "#endif", 13469 getLLVMStyleWithColumns(65)); 13470 } 13471 13472 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) { 13473 FormatStyle AllowsMergedIf = getGoogleStyle(); 13474 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 13475 FormatStyle::SIS_WithoutElse; 13476 verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf); 13477 verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf); 13478 verifyFormat("if (true)\n#error E\n return 42;", AllowsMergedIf); 13479 EXPECT_EQ("if (true) return 42;", 13480 format("if (true)\nreturn 42;", AllowsMergedIf)); 13481 FormatStyle ShortMergedIf = AllowsMergedIf; 13482 ShortMergedIf.ColumnLimit = 25; 13483 verifyFormat("#define A \\\n" 13484 " if (true) return 42;", 13485 ShortMergedIf); 13486 verifyFormat("#define A \\\n" 13487 " f(); \\\n" 13488 " if (true)\n" 13489 "#define B", 13490 ShortMergedIf); 13491 verifyFormat("#define A \\\n" 13492 " f(); \\\n" 13493 " if (true)\n" 13494 "g();", 13495 ShortMergedIf); 13496 verifyFormat("{\n" 13497 "#ifdef A\n" 13498 " // Comment\n" 13499 " if (true) continue;\n" 13500 "#endif\n" 13501 " // Comment\n" 13502 " if (true) continue;\n" 13503 "}", 13504 ShortMergedIf); 13505 ShortMergedIf.ColumnLimit = 33; 13506 verifyFormat("#define A \\\n" 13507 " if constexpr (true) return 42;", 13508 ShortMergedIf); 13509 verifyFormat("#define A \\\n" 13510 " if CONSTEXPR (true) return 42;", 13511 ShortMergedIf); 13512 ShortMergedIf.ColumnLimit = 29; 13513 verifyFormat("#define A \\\n" 13514 " if (aaaaaaaaaa) return 1; \\\n" 13515 " return 2;", 13516 ShortMergedIf); 13517 ShortMergedIf.ColumnLimit = 28; 13518 verifyFormat("#define A \\\n" 13519 " if (aaaaaaaaaa) \\\n" 13520 " return 1; \\\n" 13521 " return 2;", 13522 ShortMergedIf); 13523 verifyFormat("#define A \\\n" 13524 " if constexpr (aaaaaaa) \\\n" 13525 " return 1; \\\n" 13526 " return 2;", 13527 ShortMergedIf); 13528 verifyFormat("#define A \\\n" 13529 " if CONSTEXPR (aaaaaaa) \\\n" 13530 " return 1; \\\n" 13531 " return 2;", 13532 ShortMergedIf); 13533 13534 verifyFormat("//\n" 13535 "#define a \\\n" 13536 " if \\\n" 13537 " 0", 13538 getChromiumStyle(FormatStyle::LK_Cpp)); 13539 } 13540 13541 TEST_F(FormatTest, FormatStarDependingOnContext) { 13542 verifyFormat("void f(int *a);"); 13543 verifyFormat("void f() { f(fint * b); }"); 13544 verifyFormat("class A {\n void f(int *a);\n};"); 13545 verifyFormat("class A {\n int *a;\n};"); 13546 verifyFormat("namespace a {\n" 13547 "namespace b {\n" 13548 "class A {\n" 13549 " void f() {}\n" 13550 " int *a;\n" 13551 "};\n" 13552 "} // namespace b\n" 13553 "} // namespace a"); 13554 } 13555 13556 TEST_F(FormatTest, SpecialTokensAtEndOfLine) { 13557 verifyFormat("while"); 13558 verifyFormat("operator"); 13559 } 13560 13561 TEST_F(FormatTest, SkipsDeeplyNestedLines) { 13562 // This code would be painfully slow to format if we didn't skip it. 13563 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 13564 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13565 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13566 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13567 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13568 "A(1, 1)\n" 13569 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x 13570 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13571 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13572 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13573 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13574 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13575 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13576 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13577 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13578 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n"); 13579 // Deeply nested part is untouched, rest is formatted. 13580 EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n", 13581 format(std::string("int i;\n") + Code + "int j;\n", 13582 getLLVMStyle(), SC_ExpectIncomplete)); 13583 } 13584 13585 //===----------------------------------------------------------------------===// 13586 // Objective-C tests. 13587 //===----------------------------------------------------------------------===// 13588 13589 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) { 13590 verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;"); 13591 EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;", 13592 format("-(NSUInteger)indexOfObject:(id)anObject;")); 13593 EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;")); 13594 EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;")); 13595 EXPECT_EQ("- (NSInteger)Method3:(id)anObject;", 13596 format("-(NSInteger)Method3:(id)anObject;")); 13597 EXPECT_EQ("- (NSInteger)Method4:(id)anObject;", 13598 format("-(NSInteger)Method4:(id)anObject;")); 13599 EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;", 13600 format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;")); 13601 EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;", 13602 format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;")); 13603 EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject " 13604 "forAllCells:(BOOL)flag;", 13605 format("- (void)sendAction:(SEL)aSelector to:(id)anObject " 13606 "forAllCells:(BOOL)flag;")); 13607 13608 // Very long objectiveC method declaration. 13609 verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n" 13610 " (SoooooooooooooooooooooomeType *)bbbbbbbbbb;"); 13611 verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n" 13612 " inRange:(NSRange)range\n" 13613 " outRange:(NSRange)out_range\n" 13614 " outRange1:(NSRange)out_range1\n" 13615 " outRange2:(NSRange)out_range2\n" 13616 " outRange3:(NSRange)out_range3\n" 13617 " outRange4:(NSRange)out_range4\n" 13618 " outRange5:(NSRange)out_range5\n" 13619 " outRange6:(NSRange)out_range6\n" 13620 " outRange7:(NSRange)out_range7\n" 13621 " outRange8:(NSRange)out_range8\n" 13622 " outRange9:(NSRange)out_range9;"); 13623 13624 // When the function name has to be wrapped. 13625 FormatStyle Style = getLLVMStyle(); 13626 // ObjC ignores IndentWrappedFunctionNames when wrapping methods 13627 // and always indents instead. 13628 Style.IndentWrappedFunctionNames = false; 13629 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n" 13630 " veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n" 13631 " anotherName:(NSString)bbbbbbbbbbbbbb {\n" 13632 "}", 13633 Style); 13634 Style.IndentWrappedFunctionNames = true; 13635 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n" 13636 " veryLooooooooooongName:(NSString)cccccccccccccc\n" 13637 " anotherName:(NSString)dddddddddddddd {\n" 13638 "}", 13639 Style); 13640 13641 verifyFormat("- (int)sum:(vector<int>)numbers;"); 13642 verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;"); 13643 // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC 13644 // protocol lists (but not for template classes): 13645 // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;"); 13646 13647 verifyFormat("- (int (*)())foo:(int (*)())f;"); 13648 verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;"); 13649 13650 // If there's no return type (very rare in practice!), LLVM and Google style 13651 // agree. 13652 verifyFormat("- foo;"); 13653 verifyFormat("- foo:(int)f;"); 13654 verifyGoogleFormat("- foo:(int)foo;"); 13655 } 13656 13657 TEST_F(FormatTest, BreaksStringLiterals) { 13658 EXPECT_EQ("\"some text \"\n" 13659 "\"other\";", 13660 format("\"some text other\";", getLLVMStyleWithColumns(12))); 13661 EXPECT_EQ("\"some text \"\n" 13662 "\"other\";", 13663 format("\\\n\"some text other\";", getLLVMStyleWithColumns(12))); 13664 EXPECT_EQ( 13665 "#define A \\\n" 13666 " \"some \" \\\n" 13667 " \"text \" \\\n" 13668 " \"other\";", 13669 format("#define A \"some text other\";", getLLVMStyleWithColumns(12))); 13670 EXPECT_EQ( 13671 "#define A \\\n" 13672 " \"so \" \\\n" 13673 " \"text \" \\\n" 13674 " \"other\";", 13675 format("#define A \"so text other\";", getLLVMStyleWithColumns(12))); 13676 13677 EXPECT_EQ("\"some text\"", 13678 format("\"some text\"", getLLVMStyleWithColumns(1))); 13679 EXPECT_EQ("\"some text\"", 13680 format("\"some text\"", getLLVMStyleWithColumns(11))); 13681 EXPECT_EQ("\"some \"\n" 13682 "\"text\"", 13683 format("\"some text\"", getLLVMStyleWithColumns(10))); 13684 EXPECT_EQ("\"some \"\n" 13685 "\"text\"", 13686 format("\"some text\"", getLLVMStyleWithColumns(7))); 13687 EXPECT_EQ("\"some\"\n" 13688 "\" tex\"\n" 13689 "\"t\"", 13690 format("\"some text\"", getLLVMStyleWithColumns(6))); 13691 EXPECT_EQ("\"some\"\n" 13692 "\" tex\"\n" 13693 "\" and\"", 13694 format("\"some tex and\"", getLLVMStyleWithColumns(6))); 13695 EXPECT_EQ("\"some\"\n" 13696 "\"/tex\"\n" 13697 "\"/and\"", 13698 format("\"some/tex/and\"", getLLVMStyleWithColumns(6))); 13699 13700 EXPECT_EQ("variable =\n" 13701 " \"long string \"\n" 13702 " \"literal\";", 13703 format("variable = \"long string literal\";", 13704 getLLVMStyleWithColumns(20))); 13705 13706 EXPECT_EQ("variable = f(\n" 13707 " \"long string \"\n" 13708 " \"literal\",\n" 13709 " short,\n" 13710 " loooooooooooooooooooong);", 13711 format("variable = f(\"long string literal\", short, " 13712 "loooooooooooooooooooong);", 13713 getLLVMStyleWithColumns(20))); 13714 13715 EXPECT_EQ( 13716 "f(g(\"long string \"\n" 13717 " \"literal\"),\n" 13718 " b);", 13719 format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20))); 13720 EXPECT_EQ("f(g(\"long string \"\n" 13721 " \"literal\",\n" 13722 " a),\n" 13723 " b);", 13724 format("f(g(\"long string literal\", a), b);", 13725 getLLVMStyleWithColumns(20))); 13726 EXPECT_EQ( 13727 "f(\"one two\".split(\n" 13728 " variable));", 13729 format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20))); 13730 EXPECT_EQ("f(\"one two three four five six \"\n" 13731 " \"seven\".split(\n" 13732 " really_looooong_variable));", 13733 format("f(\"one two three four five six seven\"." 13734 "split(really_looooong_variable));", 13735 getLLVMStyleWithColumns(33))); 13736 13737 EXPECT_EQ("f(\"some \"\n" 13738 " \"text\",\n" 13739 " other);", 13740 format("f(\"some text\", other);", getLLVMStyleWithColumns(10))); 13741 13742 // Only break as a last resort. 13743 verifyFormat( 13744 "aaaaaaaaaaaaaaaaaaaa(\n" 13745 " aaaaaaaaaaaaaaaaaaaa,\n" 13746 " aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));"); 13747 13748 EXPECT_EQ("\"splitmea\"\n" 13749 "\"trandomp\"\n" 13750 "\"oint\"", 13751 format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10))); 13752 13753 EXPECT_EQ("\"split/\"\n" 13754 "\"pathat/\"\n" 13755 "\"slashes\"", 13756 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10))); 13757 13758 EXPECT_EQ("\"split/\"\n" 13759 "\"pathat/\"\n" 13760 "\"slashes\"", 13761 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10))); 13762 EXPECT_EQ("\"split at \"\n" 13763 "\"spaces/at/\"\n" 13764 "\"slashes.at.any$\"\n" 13765 "\"non-alphanumeric%\"\n" 13766 "\"1111111111characte\"\n" 13767 "\"rs\"", 13768 format("\"split at " 13769 "spaces/at/" 13770 "slashes.at." 13771 "any$non-" 13772 "alphanumeric%" 13773 "1111111111characte" 13774 "rs\"", 13775 getLLVMStyleWithColumns(20))); 13776 13777 // Verify that splitting the strings understands 13778 // Style::AlwaysBreakBeforeMultilineStrings. 13779 EXPECT_EQ("aaaaaaaaaaaa(\n" 13780 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n" 13781 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");", 13782 format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa " 13783 "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa " 13784 "aaaaaaaaaaaaaaaaaaaaaa\");", 13785 getGoogleStyle())); 13786 EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13787 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";", 13788 format("return \"aaaaaaaaaaaaaaaaaaaaaa " 13789 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa " 13790 "aaaaaaaaaaaaaaaaaaaaaa\";", 13791 getGoogleStyle())); 13792 EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13793 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";", 13794 format("llvm::outs() << " 13795 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa" 13796 "aaaaaaaaaaaaaaaaaaa\";")); 13797 EXPECT_EQ("ffff(\n" 13798 " {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13799 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});", 13800 format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa " 13801 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});", 13802 getGoogleStyle())); 13803 13804 FormatStyle Style = getLLVMStyleWithColumns(12); 13805 Style.BreakStringLiterals = false; 13806 EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style)); 13807 13808 FormatStyle AlignLeft = getLLVMStyleWithColumns(12); 13809 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left; 13810 EXPECT_EQ("#define A \\\n" 13811 " \"some \" \\\n" 13812 " \"text \" \\\n" 13813 " \"other\";", 13814 format("#define A \"some text other\";", AlignLeft)); 13815 } 13816 13817 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) { 13818 EXPECT_EQ("C a = \"some more \"\n" 13819 " \"text\";", 13820 format("C a = \"some more text\";", getLLVMStyleWithColumns(18))); 13821 } 13822 13823 TEST_F(FormatTest, FullyRemoveEmptyLines) { 13824 FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80); 13825 NoEmptyLines.MaxEmptyLinesToKeep = 0; 13826 EXPECT_EQ("int i = a(b());", 13827 format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines)); 13828 } 13829 13830 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) { 13831 EXPECT_EQ( 13832 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 13833 "(\n" 13834 " \"x\t\");", 13835 format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 13836 "aaaaaaa(" 13837 "\"x\t\");")); 13838 } 13839 13840 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) { 13841 EXPECT_EQ( 13842 "u8\"utf8 string \"\n" 13843 "u8\"literal\";", 13844 format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16))); 13845 EXPECT_EQ( 13846 "u\"utf16 string \"\n" 13847 "u\"literal\";", 13848 format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16))); 13849 EXPECT_EQ( 13850 "U\"utf32 string \"\n" 13851 "U\"literal\";", 13852 format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16))); 13853 EXPECT_EQ("L\"wide string \"\n" 13854 "L\"literal\";", 13855 format("L\"wide string literal\";", getGoogleStyleWithColumns(16))); 13856 EXPECT_EQ("@\"NSString \"\n" 13857 "@\"literal\";", 13858 format("@\"NSString literal\";", getGoogleStyleWithColumns(19))); 13859 verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26)); 13860 13861 // This input makes clang-format try to split the incomplete unicode escape 13862 // sequence, which used to lead to a crasher. 13863 verifyNoCrash( 13864 "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 13865 getLLVMStyleWithColumns(60)); 13866 } 13867 13868 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) { 13869 FormatStyle Style = getGoogleStyleWithColumns(15); 13870 EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style)); 13871 EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style)); 13872 EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style)); 13873 EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style)); 13874 EXPECT_EQ("u8R\"x(raw literal)x\";", 13875 format("u8R\"x(raw literal)x\";", Style)); 13876 } 13877 13878 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) { 13879 FormatStyle Style = getLLVMStyleWithColumns(20); 13880 EXPECT_EQ( 13881 "_T(\"aaaaaaaaaaaaaa\")\n" 13882 "_T(\"aaaaaaaaaaaaaa\")\n" 13883 "_T(\"aaaaaaaaaaaa\")", 13884 format(" _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style)); 13885 EXPECT_EQ("f(x,\n" 13886 " _T(\"aaaaaaaaaaaa\")\n" 13887 " _T(\"aaa\"),\n" 13888 " z);", 13889 format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style)); 13890 13891 // FIXME: Handle embedded spaces in one iteration. 13892 // EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n" 13893 // "_T(\"aaaaaaaaaaaaa\")\n" 13894 // "_T(\"aaaaaaaaaaaaa\")\n" 13895 // "_T(\"a\")", 13896 // format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", 13897 // getLLVMStyleWithColumns(20))); 13898 EXPECT_EQ( 13899 "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", 13900 format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style)); 13901 EXPECT_EQ("f(\n" 13902 "#if !TEST\n" 13903 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n" 13904 "#endif\n" 13905 ");", 13906 format("f(\n" 13907 "#if !TEST\n" 13908 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n" 13909 "#endif\n" 13910 ");")); 13911 EXPECT_EQ("f(\n" 13912 "\n" 13913 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));", 13914 format("f(\n" 13915 "\n" 13916 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));")); 13917 // Regression test for accessing tokens past the end of a vector in the 13918 // TokenLexer. 13919 verifyNoCrash(R"(_T( 13920 " 13921 ) 13922 )"); 13923 } 13924 13925 TEST_F(FormatTest, BreaksStringLiteralOperands) { 13926 // In a function call with two operands, the second can be broken with no line 13927 // break before it. 13928 EXPECT_EQ( 13929 "func(a, \"long long \"\n" 13930 " \"long long\");", 13931 format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24))); 13932 // In a function call with three operands, the second must be broken with a 13933 // line break before it. 13934 EXPECT_EQ("func(a,\n" 13935 " \"long long long \"\n" 13936 " \"long\",\n" 13937 " c);", 13938 format("func(a, \"long long long long\", c);", 13939 getLLVMStyleWithColumns(24))); 13940 // In a function call with three operands, the third must be broken with a 13941 // line break before it. 13942 EXPECT_EQ("func(a, b,\n" 13943 " \"long long long \"\n" 13944 " \"long\");", 13945 format("func(a, b, \"long long long long\");", 13946 getLLVMStyleWithColumns(24))); 13947 // In a function call with three operands, both the second and the third must 13948 // be broken with a line break before them. 13949 EXPECT_EQ("func(a,\n" 13950 " \"long long long \"\n" 13951 " \"long\",\n" 13952 " \"long long long \"\n" 13953 " \"long\");", 13954 format("func(a, \"long long long long\", \"long long long long\");", 13955 getLLVMStyleWithColumns(24))); 13956 // In a chain of << with two operands, the second can be broken with no line 13957 // break before it. 13958 EXPECT_EQ("a << \"line line \"\n" 13959 " \"line\";", 13960 format("a << \"line line line\";", getLLVMStyleWithColumns(20))); 13961 // In a chain of << with three operands, the second can be broken with no line 13962 // break before it. 13963 EXPECT_EQ( 13964 "abcde << \"line \"\n" 13965 " \"line line\"\n" 13966 " << c;", 13967 format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20))); 13968 // In a chain of << with three operands, the third must be broken with a line 13969 // break before it. 13970 EXPECT_EQ( 13971 "a << b\n" 13972 " << \"line line \"\n" 13973 " \"line\";", 13974 format("a << b << \"line line line\";", getLLVMStyleWithColumns(20))); 13975 // In a chain of << with three operands, the second can be broken with no line 13976 // break before it and the third must be broken with a line break before it. 13977 EXPECT_EQ("abcd << \"line line \"\n" 13978 " \"line\"\n" 13979 " << \"line line \"\n" 13980 " \"line\";", 13981 format("abcd << \"line line line\" << \"line line line\";", 13982 getLLVMStyleWithColumns(20))); 13983 // In a chain of binary operators with two operands, the second can be broken 13984 // with no line break before it. 13985 EXPECT_EQ( 13986 "abcd + \"line line \"\n" 13987 " \"line line\";", 13988 format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20))); 13989 // In a chain of binary operators with three operands, the second must be 13990 // broken with a line break before it. 13991 EXPECT_EQ("abcd +\n" 13992 " \"line line \"\n" 13993 " \"line line\" +\n" 13994 " e;", 13995 format("abcd + \"line line line line\" + e;", 13996 getLLVMStyleWithColumns(20))); 13997 // In a function call with two operands, with AlignAfterOpenBracket enabled, 13998 // the first must be broken with a line break before it. 13999 FormatStyle Style = getLLVMStyleWithColumns(25); 14000 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 14001 EXPECT_EQ("someFunction(\n" 14002 " \"long long long \"\n" 14003 " \"long\",\n" 14004 " a);", 14005 format("someFunction(\"long long long long\", a);", Style)); 14006 } 14007 14008 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) { 14009 EXPECT_EQ( 14010 "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 14011 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 14012 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";", 14013 format("aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 14014 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 14015 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";")); 14016 } 14017 14018 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) { 14019 EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);", 14020 format("f(g(R\"x(raw literal)x\", a), b);", getGoogleStyle())); 14021 EXPECT_EQ("fffffffffff(g(R\"x(\n" 14022 "multiline raw string literal xxxxxxxxxxxxxx\n" 14023 ")x\",\n" 14024 " a),\n" 14025 " b);", 14026 format("fffffffffff(g(R\"x(\n" 14027 "multiline raw string literal xxxxxxxxxxxxxx\n" 14028 ")x\", a), b);", 14029 getGoogleStyleWithColumns(20))); 14030 EXPECT_EQ("fffffffffff(\n" 14031 " g(R\"x(qqq\n" 14032 "multiline raw string literal xxxxxxxxxxxxxx\n" 14033 ")x\",\n" 14034 " a),\n" 14035 " b);", 14036 format("fffffffffff(g(R\"x(qqq\n" 14037 "multiline raw string literal xxxxxxxxxxxxxx\n" 14038 ")x\", a), b);", 14039 getGoogleStyleWithColumns(20))); 14040 14041 EXPECT_EQ("fffffffffff(R\"x(\n" 14042 "multiline raw string literal xxxxxxxxxxxxxx\n" 14043 ")x\");", 14044 format("fffffffffff(R\"x(\n" 14045 "multiline raw string literal xxxxxxxxxxxxxx\n" 14046 ")x\");", 14047 getGoogleStyleWithColumns(20))); 14048 EXPECT_EQ("fffffffffff(R\"x(\n" 14049 "multiline raw string literal xxxxxxxxxxxxxx\n" 14050 ")x\" + bbbbbb);", 14051 format("fffffffffff(R\"x(\n" 14052 "multiline raw string literal xxxxxxxxxxxxxx\n" 14053 ")x\" + bbbbbb);", 14054 getGoogleStyleWithColumns(20))); 14055 EXPECT_EQ("fffffffffff(\n" 14056 " R\"x(\n" 14057 "multiline raw string literal xxxxxxxxxxxxxx\n" 14058 ")x\" +\n" 14059 " bbbbbb);", 14060 format("fffffffffff(\n" 14061 " R\"x(\n" 14062 "multiline raw string literal xxxxxxxxxxxxxx\n" 14063 ")x\" + bbbbbb);", 14064 getGoogleStyleWithColumns(20))); 14065 EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);", 14066 format("fffffffffff(\n" 14067 " R\"(single line raw string)\" + bbbbbb);")); 14068 } 14069 14070 TEST_F(FormatTest, SkipsUnknownStringLiterals) { 14071 verifyFormat("string a = \"unterminated;"); 14072 EXPECT_EQ("function(\"unterminated,\n" 14073 " OtherParameter);", 14074 format("function( \"unterminated,\n" 14075 " OtherParameter);")); 14076 } 14077 14078 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) { 14079 FormatStyle Style = getLLVMStyle(); 14080 Style.Standard = FormatStyle::LS_Cpp03; 14081 EXPECT_EQ("#define x(_a) printf(\"foo\" _a);", 14082 format("#define x(_a) printf(\"foo\"_a);", Style)); 14083 } 14084 14085 TEST_F(FormatTest, CppLexVersion) { 14086 FormatStyle Style = getLLVMStyle(); 14087 // Formatting of x * y differs if x is a type. 14088 verifyFormat("void foo() { MACRO(a * b); }", Style); 14089 verifyFormat("void foo() { MACRO(int *b); }", Style); 14090 14091 // LLVM style uses latest lexer. 14092 verifyFormat("void foo() { MACRO(char8_t *b); }", Style); 14093 Style.Standard = FormatStyle::LS_Cpp17; 14094 // But in c++17, char8_t isn't a keyword. 14095 verifyFormat("void foo() { MACRO(char8_t * b); }", Style); 14096 } 14097 14098 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); } 14099 14100 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) { 14101 EXPECT_EQ("someFunction(\"aaabbbcccd\"\n" 14102 " \"ddeeefff\");", 14103 format("someFunction(\"aaabbbcccdddeeefff\");", 14104 getLLVMStyleWithColumns(25))); 14105 EXPECT_EQ("someFunction1234567890(\n" 14106 " \"aaabbbcccdddeeefff\");", 14107 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 14108 getLLVMStyleWithColumns(26))); 14109 EXPECT_EQ("someFunction1234567890(\n" 14110 " \"aaabbbcccdddeeeff\"\n" 14111 " \"f\");", 14112 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 14113 getLLVMStyleWithColumns(25))); 14114 EXPECT_EQ("someFunction1234567890(\n" 14115 " \"aaabbbcccdddeeeff\"\n" 14116 " \"f\");", 14117 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 14118 getLLVMStyleWithColumns(24))); 14119 EXPECT_EQ("someFunction(\n" 14120 " \"aaabbbcc ddde \"\n" 14121 " \"efff\");", 14122 format("someFunction(\"aaabbbcc ddde efff\");", 14123 getLLVMStyleWithColumns(25))); 14124 EXPECT_EQ("someFunction(\"aaabbbccc \"\n" 14125 " \"ddeeefff\");", 14126 format("someFunction(\"aaabbbccc ddeeefff\");", 14127 getLLVMStyleWithColumns(25))); 14128 EXPECT_EQ("someFunction1234567890(\n" 14129 " \"aaabb \"\n" 14130 " \"cccdddeeefff\");", 14131 format("someFunction1234567890(\"aaabb cccdddeeefff\");", 14132 getLLVMStyleWithColumns(25))); 14133 EXPECT_EQ("#define A \\\n" 14134 " string s = \\\n" 14135 " \"123456789\" \\\n" 14136 " \"0\"; \\\n" 14137 " int i;", 14138 format("#define A string s = \"1234567890\"; int i;", 14139 getLLVMStyleWithColumns(20))); 14140 EXPECT_EQ("someFunction(\n" 14141 " \"aaabbbcc \"\n" 14142 " \"dddeeefff\");", 14143 format("someFunction(\"aaabbbcc dddeeefff\");", 14144 getLLVMStyleWithColumns(25))); 14145 } 14146 14147 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) { 14148 EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3))); 14149 EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2))); 14150 EXPECT_EQ("\"test\"\n" 14151 "\"\\n\"", 14152 format("\"test\\n\"", getLLVMStyleWithColumns(7))); 14153 EXPECT_EQ("\"tes\\\\\"\n" 14154 "\"n\"", 14155 format("\"tes\\\\n\"", getLLVMStyleWithColumns(7))); 14156 EXPECT_EQ("\"\\\\\\\\\"\n" 14157 "\"\\n\"", 14158 format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7))); 14159 EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7))); 14160 EXPECT_EQ("\"\\uff01\"\n" 14161 "\"test\"", 14162 format("\"\\uff01test\"", getLLVMStyleWithColumns(8))); 14163 EXPECT_EQ("\"\\Uff01ff02\"", 14164 format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11))); 14165 EXPECT_EQ("\"\\x000000000001\"\n" 14166 "\"next\"", 14167 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16))); 14168 EXPECT_EQ("\"\\x000000000001next\"", 14169 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15))); 14170 EXPECT_EQ("\"\\x000000000001\"", 14171 format("\"\\x000000000001\"", getLLVMStyleWithColumns(7))); 14172 EXPECT_EQ("\"test\"\n" 14173 "\"\\000000\"\n" 14174 "\"000001\"", 14175 format("\"test\\000000000001\"", getLLVMStyleWithColumns(9))); 14176 EXPECT_EQ("\"test\\000\"\n" 14177 "\"00000000\"\n" 14178 "\"1\"", 14179 format("\"test\\000000000001\"", getLLVMStyleWithColumns(10))); 14180 } 14181 14182 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) { 14183 verifyFormat("void f() {\n" 14184 " return g() {}\n" 14185 " void h() {}"); 14186 verifyFormat("int a[] = {void forgot_closing_brace(){f();\n" 14187 "g();\n" 14188 "}"); 14189 } 14190 14191 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) { 14192 verifyFormat( 14193 "void f() { return C{param1, param2}.SomeCall(param1, param2); }"); 14194 } 14195 14196 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) { 14197 verifyFormat("class X {\n" 14198 " void f() {\n" 14199 " }\n" 14200 "};", 14201 getLLVMStyleWithColumns(12)); 14202 } 14203 14204 TEST_F(FormatTest, ConfigurableIndentWidth) { 14205 FormatStyle EightIndent = getLLVMStyleWithColumns(18); 14206 EightIndent.IndentWidth = 8; 14207 EightIndent.ContinuationIndentWidth = 8; 14208 verifyFormat("void f() {\n" 14209 " someFunction();\n" 14210 " if (true) {\n" 14211 " f();\n" 14212 " }\n" 14213 "}", 14214 EightIndent); 14215 verifyFormat("class X {\n" 14216 " void f() {\n" 14217 " }\n" 14218 "};", 14219 EightIndent); 14220 verifyFormat("int x[] = {\n" 14221 " call(),\n" 14222 " call()};", 14223 EightIndent); 14224 } 14225 14226 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) { 14227 verifyFormat("double\n" 14228 "f();", 14229 getLLVMStyleWithColumns(8)); 14230 } 14231 14232 TEST_F(FormatTest, ConfigurableUseOfTab) { 14233 FormatStyle Tab = getLLVMStyleWithColumns(42); 14234 Tab.IndentWidth = 8; 14235 Tab.UseTab = FormatStyle::UT_Always; 14236 Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left; 14237 14238 EXPECT_EQ("if (aaaaaaaa && // q\n" 14239 " bb)\t\t// w\n" 14240 "\t;", 14241 format("if (aaaaaaaa &&// q\n" 14242 "bb)// w\n" 14243 ";", 14244 Tab)); 14245 EXPECT_EQ("if (aaa && bbb) // w\n" 14246 "\t;", 14247 format("if(aaa&&bbb)// w\n" 14248 ";", 14249 Tab)); 14250 14251 verifyFormat("class X {\n" 14252 "\tvoid f() {\n" 14253 "\t\tsomeFunction(parameter1,\n" 14254 "\t\t\t parameter2);\n" 14255 "\t}\n" 14256 "};", 14257 Tab); 14258 verifyFormat("#define A \\\n" 14259 "\tvoid f() { \\\n" 14260 "\t\tsomeFunction( \\\n" 14261 "\t\t parameter1, \\\n" 14262 "\t\t parameter2); \\\n" 14263 "\t}", 14264 Tab); 14265 verifyFormat("int a;\t // x\n" 14266 "int bbbbbbbb; // x\n", 14267 Tab); 14268 14269 FormatStyle TabAlignment = Tab; 14270 TabAlignment.AlignConsecutiveDeclarations.Enabled = true; 14271 TabAlignment.PointerAlignment = FormatStyle::PAS_Left; 14272 verifyFormat("unsigned long long big;\n" 14273 "char*\t\t ptr;", 14274 TabAlignment); 14275 TabAlignment.PointerAlignment = FormatStyle::PAS_Middle; 14276 verifyFormat("unsigned long long big;\n" 14277 "char *\t\t ptr;", 14278 TabAlignment); 14279 TabAlignment.PointerAlignment = FormatStyle::PAS_Right; 14280 verifyFormat("unsigned long long big;\n" 14281 "char\t\t *ptr;", 14282 TabAlignment); 14283 14284 Tab.TabWidth = 4; 14285 Tab.IndentWidth = 8; 14286 verifyFormat("class TabWidth4Indent8 {\n" 14287 "\t\tvoid f() {\n" 14288 "\t\t\t\tsomeFunction(parameter1,\n" 14289 "\t\t\t\t\t\t\t parameter2);\n" 14290 "\t\t}\n" 14291 "};", 14292 Tab); 14293 14294 Tab.TabWidth = 4; 14295 Tab.IndentWidth = 4; 14296 verifyFormat("class TabWidth4Indent4 {\n" 14297 "\tvoid f() {\n" 14298 "\t\tsomeFunction(parameter1,\n" 14299 "\t\t\t\t\t parameter2);\n" 14300 "\t}\n" 14301 "};", 14302 Tab); 14303 14304 Tab.TabWidth = 8; 14305 Tab.IndentWidth = 4; 14306 verifyFormat("class TabWidth8Indent4 {\n" 14307 " void f() {\n" 14308 "\tsomeFunction(parameter1,\n" 14309 "\t\t parameter2);\n" 14310 " }\n" 14311 "};", 14312 Tab); 14313 14314 Tab.TabWidth = 8; 14315 Tab.IndentWidth = 8; 14316 EXPECT_EQ("/*\n" 14317 "\t a\t\tcomment\n" 14318 "\t in multiple lines\n" 14319 " */", 14320 format(" /*\t \t \n" 14321 " \t \t a\t\tcomment\t \t\n" 14322 " \t \t in multiple lines\t\n" 14323 " \t */", 14324 Tab)); 14325 14326 TabAlignment.UseTab = FormatStyle::UT_ForIndentation; 14327 TabAlignment.PointerAlignment = FormatStyle::PAS_Left; 14328 verifyFormat("void f() {\n" 14329 "\tunsigned long long big;\n" 14330 "\tchar* ptr;\n" 14331 "}", 14332 TabAlignment); 14333 TabAlignment.PointerAlignment = FormatStyle::PAS_Middle; 14334 verifyFormat("void f() {\n" 14335 "\tunsigned long long big;\n" 14336 "\tchar * ptr;\n" 14337 "}", 14338 TabAlignment); 14339 TabAlignment.PointerAlignment = FormatStyle::PAS_Right; 14340 verifyFormat("void f() {\n" 14341 "\tunsigned long long big;\n" 14342 "\tchar *ptr;\n" 14343 "}", 14344 TabAlignment); 14345 14346 Tab.UseTab = FormatStyle::UT_ForIndentation; 14347 verifyFormat("{\n" 14348 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14349 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14350 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14351 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14352 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14353 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14354 "};", 14355 Tab); 14356 verifyFormat("enum AA {\n" 14357 "\ta1, // Force multiple lines\n" 14358 "\ta2,\n" 14359 "\ta3\n" 14360 "};", 14361 Tab); 14362 EXPECT_EQ("if (aaaaaaaa && // q\n" 14363 " bb) // w\n" 14364 "\t;", 14365 format("if (aaaaaaaa &&// q\n" 14366 "bb)// w\n" 14367 ";", 14368 Tab)); 14369 verifyFormat("class X {\n" 14370 "\tvoid f() {\n" 14371 "\t\tsomeFunction(parameter1,\n" 14372 "\t\t parameter2);\n" 14373 "\t}\n" 14374 "};", 14375 Tab); 14376 verifyFormat("{\n" 14377 "\tQ(\n" 14378 "\t {\n" 14379 "\t\t int a;\n" 14380 "\t\t someFunction(aaaaaaaa,\n" 14381 "\t\t bbbbbbb);\n" 14382 "\t },\n" 14383 "\t p);\n" 14384 "}", 14385 Tab); 14386 EXPECT_EQ("{\n" 14387 "\t/* aaaa\n" 14388 "\t bbbb */\n" 14389 "}", 14390 format("{\n" 14391 "/* aaaa\n" 14392 " bbbb */\n" 14393 "}", 14394 Tab)); 14395 EXPECT_EQ("{\n" 14396 "\t/*\n" 14397 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14398 "\t bbbbbbbbbbbbb\n" 14399 "\t*/\n" 14400 "}", 14401 format("{\n" 14402 "/*\n" 14403 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14404 "*/\n" 14405 "}", 14406 Tab)); 14407 EXPECT_EQ("{\n" 14408 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14409 "\t// bbbbbbbbbbbbb\n" 14410 "}", 14411 format("{\n" 14412 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14413 "}", 14414 Tab)); 14415 EXPECT_EQ("{\n" 14416 "\t/*\n" 14417 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14418 "\t bbbbbbbbbbbbb\n" 14419 "\t*/\n" 14420 "}", 14421 format("{\n" 14422 "\t/*\n" 14423 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14424 "\t*/\n" 14425 "}", 14426 Tab)); 14427 EXPECT_EQ("{\n" 14428 "\t/*\n" 14429 "\n" 14430 "\t*/\n" 14431 "}", 14432 format("{\n" 14433 "\t/*\n" 14434 "\n" 14435 "\t*/\n" 14436 "}", 14437 Tab)); 14438 EXPECT_EQ("{\n" 14439 "\t/*\n" 14440 " asdf\n" 14441 "\t*/\n" 14442 "}", 14443 format("{\n" 14444 "\t/*\n" 14445 " asdf\n" 14446 "\t*/\n" 14447 "}", 14448 Tab)); 14449 14450 verifyFormat("void f() {\n" 14451 "\treturn true ? aaaaaaaaaaaaaaaaaa\n" 14452 "\t : bbbbbbbbbbbbbbbbbb\n" 14453 "}", 14454 Tab); 14455 FormatStyle TabNoBreak = Tab; 14456 TabNoBreak.BreakBeforeTernaryOperators = false; 14457 verifyFormat("void f() {\n" 14458 "\treturn true ? aaaaaaaaaaaaaaaaaa :\n" 14459 "\t bbbbbbbbbbbbbbbbbb\n" 14460 "}", 14461 TabNoBreak); 14462 verifyFormat("void f() {\n" 14463 "\treturn true ?\n" 14464 "\t aaaaaaaaaaaaaaaaaaaa :\n" 14465 "\t bbbbbbbbbbbbbbbbbbbb\n" 14466 "}", 14467 TabNoBreak); 14468 14469 Tab.UseTab = FormatStyle::UT_Never; 14470 EXPECT_EQ("/*\n" 14471 " a\t\tcomment\n" 14472 " in multiple lines\n" 14473 " */", 14474 format(" /*\t \t \n" 14475 " \t \t a\t\tcomment\t \t\n" 14476 " \t \t in multiple lines\t\n" 14477 " \t */", 14478 Tab)); 14479 EXPECT_EQ("/* some\n" 14480 " comment */", 14481 format(" \t \t /* some\n" 14482 " \t \t comment */", 14483 Tab)); 14484 EXPECT_EQ("int a; /* some\n" 14485 " comment */", 14486 format(" \t \t int a; /* some\n" 14487 " \t \t comment */", 14488 Tab)); 14489 14490 EXPECT_EQ("int a; /* some\n" 14491 "comment */", 14492 format(" \t \t int\ta; /* some\n" 14493 " \t \t comment */", 14494 Tab)); 14495 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14496 " comment */", 14497 format(" \t \t f(\"\t\t\"); /* some\n" 14498 " \t \t comment */", 14499 Tab)); 14500 EXPECT_EQ("{\n" 14501 " /*\n" 14502 " * Comment\n" 14503 " */\n" 14504 " int i;\n" 14505 "}", 14506 format("{\n" 14507 "\t/*\n" 14508 "\t * Comment\n" 14509 "\t */\n" 14510 "\t int i;\n" 14511 "}", 14512 Tab)); 14513 14514 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation; 14515 Tab.TabWidth = 8; 14516 Tab.IndentWidth = 8; 14517 EXPECT_EQ("if (aaaaaaaa && // q\n" 14518 " bb) // w\n" 14519 "\t;", 14520 format("if (aaaaaaaa &&// q\n" 14521 "bb)// w\n" 14522 ";", 14523 Tab)); 14524 EXPECT_EQ("if (aaa && bbb) // w\n" 14525 "\t;", 14526 format("if(aaa&&bbb)// w\n" 14527 ";", 14528 Tab)); 14529 verifyFormat("class X {\n" 14530 "\tvoid f() {\n" 14531 "\t\tsomeFunction(parameter1,\n" 14532 "\t\t\t parameter2);\n" 14533 "\t}\n" 14534 "};", 14535 Tab); 14536 verifyFormat("#define A \\\n" 14537 "\tvoid f() { \\\n" 14538 "\t\tsomeFunction( \\\n" 14539 "\t\t parameter1, \\\n" 14540 "\t\t parameter2); \\\n" 14541 "\t}", 14542 Tab); 14543 Tab.TabWidth = 4; 14544 Tab.IndentWidth = 8; 14545 verifyFormat("class TabWidth4Indent8 {\n" 14546 "\t\tvoid f() {\n" 14547 "\t\t\t\tsomeFunction(parameter1,\n" 14548 "\t\t\t\t\t\t\t parameter2);\n" 14549 "\t\t}\n" 14550 "};", 14551 Tab); 14552 Tab.TabWidth = 4; 14553 Tab.IndentWidth = 4; 14554 verifyFormat("class TabWidth4Indent4 {\n" 14555 "\tvoid f() {\n" 14556 "\t\tsomeFunction(parameter1,\n" 14557 "\t\t\t\t\t parameter2);\n" 14558 "\t}\n" 14559 "};", 14560 Tab); 14561 Tab.TabWidth = 8; 14562 Tab.IndentWidth = 4; 14563 verifyFormat("class TabWidth8Indent4 {\n" 14564 " void f() {\n" 14565 "\tsomeFunction(parameter1,\n" 14566 "\t\t parameter2);\n" 14567 " }\n" 14568 "};", 14569 Tab); 14570 Tab.TabWidth = 8; 14571 Tab.IndentWidth = 8; 14572 EXPECT_EQ("/*\n" 14573 "\t a\t\tcomment\n" 14574 "\t in multiple lines\n" 14575 " */", 14576 format(" /*\t \t \n" 14577 " \t \t a\t\tcomment\t \t\n" 14578 " \t \t in multiple lines\t\n" 14579 " \t */", 14580 Tab)); 14581 verifyFormat("{\n" 14582 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14583 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14584 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14585 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14586 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14587 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14588 "};", 14589 Tab); 14590 verifyFormat("enum AA {\n" 14591 "\ta1, // Force multiple lines\n" 14592 "\ta2,\n" 14593 "\ta3\n" 14594 "};", 14595 Tab); 14596 EXPECT_EQ("if (aaaaaaaa && // q\n" 14597 " bb) // w\n" 14598 "\t;", 14599 format("if (aaaaaaaa &&// q\n" 14600 "bb)// w\n" 14601 ";", 14602 Tab)); 14603 verifyFormat("class X {\n" 14604 "\tvoid f() {\n" 14605 "\t\tsomeFunction(parameter1,\n" 14606 "\t\t\t parameter2);\n" 14607 "\t}\n" 14608 "};", 14609 Tab); 14610 verifyFormat("{\n" 14611 "\tQ(\n" 14612 "\t {\n" 14613 "\t\t int a;\n" 14614 "\t\t someFunction(aaaaaaaa,\n" 14615 "\t\t\t\t bbbbbbb);\n" 14616 "\t },\n" 14617 "\t p);\n" 14618 "}", 14619 Tab); 14620 EXPECT_EQ("{\n" 14621 "\t/* aaaa\n" 14622 "\t bbbb */\n" 14623 "}", 14624 format("{\n" 14625 "/* aaaa\n" 14626 " bbbb */\n" 14627 "}", 14628 Tab)); 14629 EXPECT_EQ("{\n" 14630 "\t/*\n" 14631 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14632 "\t bbbbbbbbbbbbb\n" 14633 "\t*/\n" 14634 "}", 14635 format("{\n" 14636 "/*\n" 14637 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14638 "*/\n" 14639 "}", 14640 Tab)); 14641 EXPECT_EQ("{\n" 14642 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14643 "\t// bbbbbbbbbbbbb\n" 14644 "}", 14645 format("{\n" 14646 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14647 "}", 14648 Tab)); 14649 EXPECT_EQ("{\n" 14650 "\t/*\n" 14651 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14652 "\t bbbbbbbbbbbbb\n" 14653 "\t*/\n" 14654 "}", 14655 format("{\n" 14656 "\t/*\n" 14657 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14658 "\t*/\n" 14659 "}", 14660 Tab)); 14661 EXPECT_EQ("{\n" 14662 "\t/*\n" 14663 "\n" 14664 "\t*/\n" 14665 "}", 14666 format("{\n" 14667 "\t/*\n" 14668 "\n" 14669 "\t*/\n" 14670 "}", 14671 Tab)); 14672 EXPECT_EQ("{\n" 14673 "\t/*\n" 14674 " asdf\n" 14675 "\t*/\n" 14676 "}", 14677 format("{\n" 14678 "\t/*\n" 14679 " asdf\n" 14680 "\t*/\n" 14681 "}", 14682 Tab)); 14683 EXPECT_EQ("/* some\n" 14684 " comment */", 14685 format(" \t \t /* some\n" 14686 " \t \t comment */", 14687 Tab)); 14688 EXPECT_EQ("int a; /* some\n" 14689 " comment */", 14690 format(" \t \t int a; /* some\n" 14691 " \t \t comment */", 14692 Tab)); 14693 EXPECT_EQ("int a; /* some\n" 14694 "comment */", 14695 format(" \t \t int\ta; /* some\n" 14696 " \t \t comment */", 14697 Tab)); 14698 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14699 " comment */", 14700 format(" \t \t f(\"\t\t\"); /* some\n" 14701 " \t \t comment */", 14702 Tab)); 14703 EXPECT_EQ("{\n" 14704 "\t/*\n" 14705 "\t * Comment\n" 14706 "\t */\n" 14707 "\tint i;\n" 14708 "}", 14709 format("{\n" 14710 "\t/*\n" 14711 "\t * Comment\n" 14712 "\t */\n" 14713 "\t int i;\n" 14714 "}", 14715 Tab)); 14716 Tab.TabWidth = 2; 14717 Tab.IndentWidth = 2; 14718 EXPECT_EQ("{\n" 14719 "\t/* aaaa\n" 14720 "\t\t bbbb */\n" 14721 "}", 14722 format("{\n" 14723 "/* aaaa\n" 14724 "\t bbbb */\n" 14725 "}", 14726 Tab)); 14727 EXPECT_EQ("{\n" 14728 "\t/*\n" 14729 "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14730 "\t\tbbbbbbbbbbbbb\n" 14731 "\t*/\n" 14732 "}", 14733 format("{\n" 14734 "/*\n" 14735 "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14736 "*/\n" 14737 "}", 14738 Tab)); 14739 Tab.AlignConsecutiveAssignments.Enabled = true; 14740 Tab.AlignConsecutiveDeclarations.Enabled = true; 14741 Tab.TabWidth = 4; 14742 Tab.IndentWidth = 4; 14743 verifyFormat("class Assign {\n" 14744 "\tvoid f() {\n" 14745 "\t\tint x = 123;\n" 14746 "\t\tint random = 4;\n" 14747 "\t\tstd::string alphabet =\n" 14748 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n" 14749 "\t}\n" 14750 "};", 14751 Tab); 14752 14753 Tab.UseTab = FormatStyle::UT_AlignWithSpaces; 14754 Tab.TabWidth = 8; 14755 Tab.IndentWidth = 8; 14756 EXPECT_EQ("if (aaaaaaaa && // q\n" 14757 " bb) // w\n" 14758 "\t;", 14759 format("if (aaaaaaaa &&// q\n" 14760 "bb)// w\n" 14761 ";", 14762 Tab)); 14763 EXPECT_EQ("if (aaa && bbb) // w\n" 14764 "\t;", 14765 format("if(aaa&&bbb)// w\n" 14766 ";", 14767 Tab)); 14768 verifyFormat("class X {\n" 14769 "\tvoid f() {\n" 14770 "\t\tsomeFunction(parameter1,\n" 14771 "\t\t parameter2);\n" 14772 "\t}\n" 14773 "};", 14774 Tab); 14775 verifyFormat("#define A \\\n" 14776 "\tvoid f() { \\\n" 14777 "\t\tsomeFunction( \\\n" 14778 "\t\t parameter1, \\\n" 14779 "\t\t parameter2); \\\n" 14780 "\t}", 14781 Tab); 14782 Tab.TabWidth = 4; 14783 Tab.IndentWidth = 8; 14784 verifyFormat("class TabWidth4Indent8 {\n" 14785 "\t\tvoid f() {\n" 14786 "\t\t\t\tsomeFunction(parameter1,\n" 14787 "\t\t\t\t parameter2);\n" 14788 "\t\t}\n" 14789 "};", 14790 Tab); 14791 Tab.TabWidth = 4; 14792 Tab.IndentWidth = 4; 14793 verifyFormat("class TabWidth4Indent4 {\n" 14794 "\tvoid f() {\n" 14795 "\t\tsomeFunction(parameter1,\n" 14796 "\t\t parameter2);\n" 14797 "\t}\n" 14798 "};", 14799 Tab); 14800 Tab.TabWidth = 8; 14801 Tab.IndentWidth = 4; 14802 verifyFormat("class TabWidth8Indent4 {\n" 14803 " void f() {\n" 14804 "\tsomeFunction(parameter1,\n" 14805 "\t parameter2);\n" 14806 " }\n" 14807 "};", 14808 Tab); 14809 Tab.TabWidth = 8; 14810 Tab.IndentWidth = 8; 14811 EXPECT_EQ("/*\n" 14812 " a\t\tcomment\n" 14813 " in multiple lines\n" 14814 " */", 14815 format(" /*\t \t \n" 14816 " \t \t a\t\tcomment\t \t\n" 14817 " \t \t in multiple lines\t\n" 14818 " \t */", 14819 Tab)); 14820 verifyFormat("{\n" 14821 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14822 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14823 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14824 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14825 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14826 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14827 "};", 14828 Tab); 14829 verifyFormat("enum AA {\n" 14830 "\ta1, // Force multiple lines\n" 14831 "\ta2,\n" 14832 "\ta3\n" 14833 "};", 14834 Tab); 14835 EXPECT_EQ("if (aaaaaaaa && // q\n" 14836 " bb) // w\n" 14837 "\t;", 14838 format("if (aaaaaaaa &&// q\n" 14839 "bb)// w\n" 14840 ";", 14841 Tab)); 14842 verifyFormat("class X {\n" 14843 "\tvoid f() {\n" 14844 "\t\tsomeFunction(parameter1,\n" 14845 "\t\t parameter2);\n" 14846 "\t}\n" 14847 "};", 14848 Tab); 14849 verifyFormat("{\n" 14850 "\tQ(\n" 14851 "\t {\n" 14852 "\t\t int a;\n" 14853 "\t\t someFunction(aaaaaaaa,\n" 14854 "\t\t bbbbbbb);\n" 14855 "\t },\n" 14856 "\t p);\n" 14857 "}", 14858 Tab); 14859 EXPECT_EQ("{\n" 14860 "\t/* aaaa\n" 14861 "\t bbbb */\n" 14862 "}", 14863 format("{\n" 14864 "/* aaaa\n" 14865 " bbbb */\n" 14866 "}", 14867 Tab)); 14868 EXPECT_EQ("{\n" 14869 "\t/*\n" 14870 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14871 "\t bbbbbbbbbbbbb\n" 14872 "\t*/\n" 14873 "}", 14874 format("{\n" 14875 "/*\n" 14876 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14877 "*/\n" 14878 "}", 14879 Tab)); 14880 EXPECT_EQ("{\n" 14881 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14882 "\t// bbbbbbbbbbbbb\n" 14883 "}", 14884 format("{\n" 14885 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14886 "}", 14887 Tab)); 14888 EXPECT_EQ("{\n" 14889 "\t/*\n" 14890 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14891 "\t bbbbbbbbbbbbb\n" 14892 "\t*/\n" 14893 "}", 14894 format("{\n" 14895 "\t/*\n" 14896 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14897 "\t*/\n" 14898 "}", 14899 Tab)); 14900 EXPECT_EQ("{\n" 14901 "\t/*\n" 14902 "\n" 14903 "\t*/\n" 14904 "}", 14905 format("{\n" 14906 "\t/*\n" 14907 "\n" 14908 "\t*/\n" 14909 "}", 14910 Tab)); 14911 EXPECT_EQ("{\n" 14912 "\t/*\n" 14913 " asdf\n" 14914 "\t*/\n" 14915 "}", 14916 format("{\n" 14917 "\t/*\n" 14918 " asdf\n" 14919 "\t*/\n" 14920 "}", 14921 Tab)); 14922 EXPECT_EQ("/* some\n" 14923 " comment */", 14924 format(" \t \t /* some\n" 14925 " \t \t comment */", 14926 Tab)); 14927 EXPECT_EQ("int a; /* some\n" 14928 " comment */", 14929 format(" \t \t int a; /* some\n" 14930 " \t \t comment */", 14931 Tab)); 14932 EXPECT_EQ("int a; /* some\n" 14933 "comment */", 14934 format(" \t \t int\ta; /* some\n" 14935 " \t \t comment */", 14936 Tab)); 14937 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14938 " comment */", 14939 format(" \t \t f(\"\t\t\"); /* some\n" 14940 " \t \t comment */", 14941 Tab)); 14942 EXPECT_EQ("{\n" 14943 "\t/*\n" 14944 "\t * Comment\n" 14945 "\t */\n" 14946 "\tint i;\n" 14947 "}", 14948 format("{\n" 14949 "\t/*\n" 14950 "\t * Comment\n" 14951 "\t */\n" 14952 "\t int i;\n" 14953 "}", 14954 Tab)); 14955 Tab.TabWidth = 2; 14956 Tab.IndentWidth = 2; 14957 EXPECT_EQ("{\n" 14958 "\t/* aaaa\n" 14959 "\t bbbb */\n" 14960 "}", 14961 format("{\n" 14962 "/* aaaa\n" 14963 " bbbb */\n" 14964 "}", 14965 Tab)); 14966 EXPECT_EQ("{\n" 14967 "\t/*\n" 14968 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14969 "\t bbbbbbbbbbbbb\n" 14970 "\t*/\n" 14971 "}", 14972 format("{\n" 14973 "/*\n" 14974 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14975 "*/\n" 14976 "}", 14977 Tab)); 14978 Tab.AlignConsecutiveAssignments.Enabled = true; 14979 Tab.AlignConsecutiveDeclarations.Enabled = true; 14980 Tab.TabWidth = 4; 14981 Tab.IndentWidth = 4; 14982 verifyFormat("class Assign {\n" 14983 "\tvoid f() {\n" 14984 "\t\tint x = 123;\n" 14985 "\t\tint random = 4;\n" 14986 "\t\tstd::string alphabet =\n" 14987 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n" 14988 "\t}\n" 14989 "};", 14990 Tab); 14991 Tab.AlignOperands = FormatStyle::OAS_Align; 14992 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n" 14993 " cccccccccccccccccccc;", 14994 Tab); 14995 // no alignment 14996 verifyFormat("int aaaaaaaaaa =\n" 14997 "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 14998 Tab); 14999 verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n" 15000 " : bbbbbbbbbbbbbb ? 222222222222222\n" 15001 " : 333333333333333;", 15002 Tab); 15003 Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 15004 Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator; 15005 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n" 15006 " + cccccccccccccccccccc;", 15007 Tab); 15008 } 15009 15010 TEST_F(FormatTest, ZeroTabWidth) { 15011 FormatStyle Tab = getLLVMStyleWithColumns(42); 15012 Tab.IndentWidth = 8; 15013 Tab.UseTab = FormatStyle::UT_Never; 15014 Tab.TabWidth = 0; 15015 EXPECT_EQ("void a(){\n" 15016 " // line starts with '\t'\n" 15017 "};", 15018 format("void a(){\n" 15019 "\t// line starts with '\t'\n" 15020 "};", 15021 Tab)); 15022 15023 EXPECT_EQ("void a(){\n" 15024 " // line starts with '\t'\n" 15025 "};", 15026 format("void a(){\n" 15027 "\t\t// line starts with '\t'\n" 15028 "};", 15029 Tab)); 15030 15031 Tab.UseTab = FormatStyle::UT_ForIndentation; 15032 EXPECT_EQ("void a(){\n" 15033 " // line starts with '\t'\n" 15034 "};", 15035 format("void a(){\n" 15036 "\t// line starts with '\t'\n" 15037 "};", 15038 Tab)); 15039 15040 EXPECT_EQ("void a(){\n" 15041 " // line starts with '\t'\n" 15042 "};", 15043 format("void a(){\n" 15044 "\t\t// line starts with '\t'\n" 15045 "};", 15046 Tab)); 15047 15048 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation; 15049 EXPECT_EQ("void a(){\n" 15050 " // line starts with '\t'\n" 15051 "};", 15052 format("void a(){\n" 15053 "\t// line starts with '\t'\n" 15054 "};", 15055 Tab)); 15056 15057 EXPECT_EQ("void a(){\n" 15058 " // line starts with '\t'\n" 15059 "};", 15060 format("void a(){\n" 15061 "\t\t// line starts with '\t'\n" 15062 "};", 15063 Tab)); 15064 15065 Tab.UseTab = FormatStyle::UT_AlignWithSpaces; 15066 EXPECT_EQ("void a(){\n" 15067 " // line starts with '\t'\n" 15068 "};", 15069 format("void a(){\n" 15070 "\t// line starts with '\t'\n" 15071 "};", 15072 Tab)); 15073 15074 EXPECT_EQ("void a(){\n" 15075 " // line starts with '\t'\n" 15076 "};", 15077 format("void a(){\n" 15078 "\t\t// line starts with '\t'\n" 15079 "};", 15080 Tab)); 15081 15082 Tab.UseTab = FormatStyle::UT_Always; 15083 EXPECT_EQ("void a(){\n" 15084 "// line starts with '\t'\n" 15085 "};", 15086 format("void a(){\n" 15087 "\t// line starts with '\t'\n" 15088 "};", 15089 Tab)); 15090 15091 EXPECT_EQ("void a(){\n" 15092 "// line starts with '\t'\n" 15093 "};", 15094 format("void a(){\n" 15095 "\t\t// line starts with '\t'\n" 15096 "};", 15097 Tab)); 15098 } 15099 15100 TEST_F(FormatTest, CalculatesOriginalColumn) { 15101 EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 15102 "q\"; /* some\n" 15103 " comment */", 15104 format(" \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 15105 "q\"; /* some\n" 15106 " comment */", 15107 getLLVMStyle())); 15108 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n" 15109 "/* some\n" 15110 " comment */", 15111 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n" 15112 " /* some\n" 15113 " comment */", 15114 getLLVMStyle())); 15115 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 15116 "qqq\n" 15117 "/* some\n" 15118 " comment */", 15119 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 15120 "qqq\n" 15121 " /* some\n" 15122 " comment */", 15123 getLLVMStyle())); 15124 EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 15125 "wwww; /* some\n" 15126 " comment */", 15127 format(" inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 15128 "wwww; /* some\n" 15129 " comment */", 15130 getLLVMStyle())); 15131 } 15132 15133 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) { 15134 FormatStyle NoSpace = getLLVMStyle(); 15135 NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never; 15136 15137 verifyFormat("while(true)\n" 15138 " continue;", 15139 NoSpace); 15140 verifyFormat("for(;;)\n" 15141 " continue;", 15142 NoSpace); 15143 verifyFormat("if(true)\n" 15144 " f();\n" 15145 "else if(true)\n" 15146 " f();", 15147 NoSpace); 15148 verifyFormat("do {\n" 15149 " do_something();\n" 15150 "} while(something());", 15151 NoSpace); 15152 verifyFormat("switch(x) {\n" 15153 "default:\n" 15154 " break;\n" 15155 "}", 15156 NoSpace); 15157 verifyFormat("auto i = std::make_unique<int>(5);", NoSpace); 15158 verifyFormat("size_t x = sizeof(x);", NoSpace); 15159 verifyFormat("auto f(int x) -> decltype(x);", NoSpace); 15160 verifyFormat("auto f(int x) -> typeof(x);", NoSpace); 15161 verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace); 15162 verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace); 15163 verifyFormat("int f(T x) noexcept(x.create());", NoSpace); 15164 verifyFormat("alignas(128) char a[128];", NoSpace); 15165 verifyFormat("size_t x = alignof(MyType);", NoSpace); 15166 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace); 15167 verifyFormat("int f() throw(Deprecated);", NoSpace); 15168 verifyFormat("typedef void (*cb)(int);", NoSpace); 15169 verifyFormat("T A::operator()();", NoSpace); 15170 verifyFormat("X A::operator++(T);", NoSpace); 15171 verifyFormat("auto lambda = []() { return 0; };", NoSpace); 15172 15173 FormatStyle Space = getLLVMStyle(); 15174 Space.SpaceBeforeParens = FormatStyle::SBPO_Always; 15175 15176 verifyFormat("int f ();", Space); 15177 verifyFormat("void f (int a, T b) {\n" 15178 " while (true)\n" 15179 " continue;\n" 15180 "}", 15181 Space); 15182 verifyFormat("if (true)\n" 15183 " f ();\n" 15184 "else if (true)\n" 15185 " f ();", 15186 Space); 15187 verifyFormat("do {\n" 15188 " do_something ();\n" 15189 "} while (something ());", 15190 Space); 15191 verifyFormat("switch (x) {\n" 15192 "default:\n" 15193 " break;\n" 15194 "}", 15195 Space); 15196 verifyFormat("A::A () : a (1) {}", Space); 15197 verifyFormat("void f () __attribute__ ((asdf));", Space); 15198 verifyFormat("*(&a + 1);\n" 15199 "&((&a)[1]);\n" 15200 "a[(b + c) * d];\n" 15201 "(((a + 1) * 2) + 3) * 4;", 15202 Space); 15203 verifyFormat("#define A(x) x", Space); 15204 verifyFormat("#define A (x) x", Space); 15205 verifyFormat("#if defined(x)\n" 15206 "#endif", 15207 Space); 15208 verifyFormat("auto i = std::make_unique<int> (5);", Space); 15209 verifyFormat("size_t x = sizeof (x);", Space); 15210 verifyFormat("auto f (int x) -> decltype (x);", Space); 15211 verifyFormat("auto f (int x) -> typeof (x);", Space); 15212 verifyFormat("auto f (int x) -> _Atomic (x);", Space); 15213 verifyFormat("auto f (int x) -> __underlying_type (x);", Space); 15214 verifyFormat("int f (T x) noexcept (x.create ());", Space); 15215 verifyFormat("alignas (128) char a[128];", Space); 15216 verifyFormat("size_t x = alignof (MyType);", Space); 15217 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space); 15218 verifyFormat("int f () throw (Deprecated);", Space); 15219 verifyFormat("typedef void (*cb) (int);", Space); 15220 // FIXME these tests regressed behaviour. 15221 // verifyFormat("T A::operator() ();", Space); 15222 // verifyFormat("X A::operator++ (T);", Space); 15223 verifyFormat("auto lambda = [] () { return 0; };", Space); 15224 verifyFormat("int x = int (y);", Space); 15225 verifyFormat("#define F(...) __VA_OPT__ (__VA_ARGS__)", Space); 15226 verifyFormat("__builtin_LINE ()", Space); 15227 verifyFormat("__builtin_UNKNOWN ()", Space); 15228 15229 FormatStyle SomeSpace = getLLVMStyle(); 15230 SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses; 15231 15232 verifyFormat("[]() -> float {}", SomeSpace); 15233 verifyFormat("[] (auto foo) {}", SomeSpace); 15234 verifyFormat("[foo]() -> int {}", SomeSpace); 15235 verifyFormat("int f();", SomeSpace); 15236 verifyFormat("void f (int a, T b) {\n" 15237 " while (true)\n" 15238 " continue;\n" 15239 "}", 15240 SomeSpace); 15241 verifyFormat("if (true)\n" 15242 " f();\n" 15243 "else if (true)\n" 15244 " f();", 15245 SomeSpace); 15246 verifyFormat("do {\n" 15247 " do_something();\n" 15248 "} while (something());", 15249 SomeSpace); 15250 verifyFormat("switch (x) {\n" 15251 "default:\n" 15252 " break;\n" 15253 "}", 15254 SomeSpace); 15255 verifyFormat("A::A() : a (1) {}", SomeSpace); 15256 verifyFormat("void f() __attribute__ ((asdf));", SomeSpace); 15257 verifyFormat("*(&a + 1);\n" 15258 "&((&a)[1]);\n" 15259 "a[(b + c) * d];\n" 15260 "(((a + 1) * 2) + 3) * 4;", 15261 SomeSpace); 15262 verifyFormat("#define A(x) x", SomeSpace); 15263 verifyFormat("#define A (x) x", SomeSpace); 15264 verifyFormat("#if defined(x)\n" 15265 "#endif", 15266 SomeSpace); 15267 verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace); 15268 verifyFormat("size_t x = sizeof (x);", SomeSpace); 15269 verifyFormat("auto f (int x) -> decltype (x);", SomeSpace); 15270 verifyFormat("auto f (int x) -> typeof (x);", SomeSpace); 15271 verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace); 15272 verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace); 15273 verifyFormat("int f (T x) noexcept (x.create());", SomeSpace); 15274 verifyFormat("alignas (128) char a[128];", SomeSpace); 15275 verifyFormat("size_t x = alignof (MyType);", SomeSpace); 15276 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", 15277 SomeSpace); 15278 verifyFormat("int f() throw (Deprecated);", SomeSpace); 15279 verifyFormat("typedef void (*cb) (int);", SomeSpace); 15280 verifyFormat("T A::operator()();", SomeSpace); 15281 // FIXME these tests regressed behaviour. 15282 // verifyFormat("X A::operator++ (T);", SomeSpace); 15283 verifyFormat("int x = int (y);", SomeSpace); 15284 verifyFormat("auto lambda = []() { return 0; };", SomeSpace); 15285 15286 FormatStyle SpaceControlStatements = getLLVMStyle(); 15287 SpaceControlStatements.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15288 SpaceControlStatements.SpaceBeforeParensOptions.AfterControlStatements = true; 15289 15290 verifyFormat("while (true)\n" 15291 " continue;", 15292 SpaceControlStatements); 15293 verifyFormat("if (true)\n" 15294 " f();\n" 15295 "else if (true)\n" 15296 " f();", 15297 SpaceControlStatements); 15298 verifyFormat("for (;;) {\n" 15299 " do_something();\n" 15300 "}", 15301 SpaceControlStatements); 15302 verifyFormat("do {\n" 15303 " do_something();\n" 15304 "} while (something());", 15305 SpaceControlStatements); 15306 verifyFormat("switch (x) {\n" 15307 "default:\n" 15308 " break;\n" 15309 "}", 15310 SpaceControlStatements); 15311 15312 FormatStyle SpaceFuncDecl = getLLVMStyle(); 15313 SpaceFuncDecl.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15314 SpaceFuncDecl.SpaceBeforeParensOptions.AfterFunctionDeclarationName = true; 15315 15316 verifyFormat("int f ();", SpaceFuncDecl); 15317 verifyFormat("void f(int a, T b) {}", SpaceFuncDecl); 15318 verifyFormat("A::A() : a(1) {}", SpaceFuncDecl); 15319 verifyFormat("void f () __attribute__((asdf));", SpaceFuncDecl); 15320 verifyFormat("#define A(x) x", SpaceFuncDecl); 15321 verifyFormat("#define A (x) x", SpaceFuncDecl); 15322 verifyFormat("#if defined(x)\n" 15323 "#endif", 15324 SpaceFuncDecl); 15325 verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDecl); 15326 verifyFormat("size_t x = sizeof(x);", SpaceFuncDecl); 15327 verifyFormat("auto f (int x) -> decltype(x);", SpaceFuncDecl); 15328 verifyFormat("auto f (int x) -> typeof(x);", SpaceFuncDecl); 15329 verifyFormat("auto f (int x) -> _Atomic(x);", SpaceFuncDecl); 15330 verifyFormat("auto f (int x) -> __underlying_type(x);", SpaceFuncDecl); 15331 verifyFormat("int f (T x) noexcept(x.create());", SpaceFuncDecl); 15332 verifyFormat("alignas(128) char a[128];", SpaceFuncDecl); 15333 verifyFormat("size_t x = alignof(MyType);", SpaceFuncDecl); 15334 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", 15335 SpaceFuncDecl); 15336 verifyFormat("int f () throw(Deprecated);", SpaceFuncDecl); 15337 verifyFormat("typedef void (*cb)(int);", SpaceFuncDecl); 15338 // FIXME these tests regressed behaviour. 15339 // verifyFormat("T A::operator() ();", SpaceFuncDecl); 15340 // verifyFormat("X A::operator++ (T);", SpaceFuncDecl); 15341 verifyFormat("T A::operator()() {}", SpaceFuncDecl); 15342 verifyFormat("auto lambda = []() { return 0; };", SpaceFuncDecl); 15343 verifyFormat("int x = int(y);", SpaceFuncDecl); 15344 verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}", 15345 SpaceFuncDecl); 15346 15347 FormatStyle SpaceFuncDef = getLLVMStyle(); 15348 SpaceFuncDef.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15349 SpaceFuncDef.SpaceBeforeParensOptions.AfterFunctionDefinitionName = true; 15350 15351 verifyFormat("int f();", SpaceFuncDef); 15352 verifyFormat("void f (int a, T b) {}", SpaceFuncDef); 15353 verifyFormat("A::A() : a(1) {}", SpaceFuncDef); 15354 verifyFormat("void f() __attribute__((asdf));", SpaceFuncDef); 15355 verifyFormat("#define A(x) x", SpaceFuncDef); 15356 verifyFormat("#define A (x) x", SpaceFuncDef); 15357 verifyFormat("#if defined(x)\n" 15358 "#endif", 15359 SpaceFuncDef); 15360 verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDef); 15361 verifyFormat("size_t x = sizeof(x);", SpaceFuncDef); 15362 verifyFormat("auto f(int x) -> decltype(x);", SpaceFuncDef); 15363 verifyFormat("auto f(int x) -> typeof(x);", SpaceFuncDef); 15364 verifyFormat("auto f(int x) -> _Atomic(x);", SpaceFuncDef); 15365 verifyFormat("auto f(int x) -> __underlying_type(x);", SpaceFuncDef); 15366 verifyFormat("int f(T x) noexcept(x.create());", SpaceFuncDef); 15367 verifyFormat("alignas(128) char a[128];", SpaceFuncDef); 15368 verifyFormat("size_t x = alignof(MyType);", SpaceFuncDef); 15369 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", 15370 SpaceFuncDef); 15371 verifyFormat("int f() throw(Deprecated);", SpaceFuncDef); 15372 verifyFormat("typedef void (*cb)(int);", SpaceFuncDef); 15373 verifyFormat("T A::operator()();", SpaceFuncDef); 15374 verifyFormat("X A::operator++(T);", SpaceFuncDef); 15375 // verifyFormat("T A::operator() () {}", SpaceFuncDef); 15376 verifyFormat("auto lambda = [] () { return 0; };", SpaceFuncDef); 15377 verifyFormat("int x = int(y);", SpaceFuncDef); 15378 verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}", 15379 SpaceFuncDef); 15380 15381 FormatStyle SpaceIfMacros = getLLVMStyle(); 15382 SpaceIfMacros.IfMacros.clear(); 15383 SpaceIfMacros.IfMacros.push_back("MYIF"); 15384 SpaceIfMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15385 SpaceIfMacros.SpaceBeforeParensOptions.AfterIfMacros = true; 15386 verifyFormat("MYIF (a)\n return;", SpaceIfMacros); 15387 verifyFormat("MYIF (a)\n return;\nelse MYIF (b)\n return;", SpaceIfMacros); 15388 verifyFormat("MYIF (a)\n return;\nelse\n return;", SpaceIfMacros); 15389 15390 FormatStyle SpaceForeachMacros = getLLVMStyle(); 15391 EXPECT_EQ(SpaceForeachMacros.AllowShortBlocksOnASingleLine, 15392 FormatStyle::SBS_Never); 15393 EXPECT_EQ(SpaceForeachMacros.AllowShortLoopsOnASingleLine, false); 15394 SpaceForeachMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15395 SpaceForeachMacros.SpaceBeforeParensOptions.AfterForeachMacros = true; 15396 verifyFormat("for (;;) {\n" 15397 "}", 15398 SpaceForeachMacros); 15399 verifyFormat("foreach (Item *item, itemlist) {\n" 15400 "}", 15401 SpaceForeachMacros); 15402 verifyFormat("Q_FOREACH (Item *item, itemlist) {\n" 15403 "}", 15404 SpaceForeachMacros); 15405 verifyFormat("BOOST_FOREACH (Item *item, itemlist) {\n" 15406 "}", 15407 SpaceForeachMacros); 15408 verifyFormat("UNKNOWN_FOREACH(Item *item, itemlist) {}", SpaceForeachMacros); 15409 15410 FormatStyle SomeSpace2 = getLLVMStyle(); 15411 SomeSpace2.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15412 SomeSpace2.SpaceBeforeParensOptions.BeforeNonEmptyParentheses = true; 15413 verifyFormat("[]() -> float {}", SomeSpace2); 15414 verifyFormat("[] (auto foo) {}", SomeSpace2); 15415 verifyFormat("[foo]() -> int {}", SomeSpace2); 15416 verifyFormat("int f();", SomeSpace2); 15417 verifyFormat("void f (int a, T b) {\n" 15418 " while (true)\n" 15419 " continue;\n" 15420 "}", 15421 SomeSpace2); 15422 verifyFormat("if (true)\n" 15423 " f();\n" 15424 "else if (true)\n" 15425 " f();", 15426 SomeSpace2); 15427 verifyFormat("do {\n" 15428 " do_something();\n" 15429 "} while (something());", 15430 SomeSpace2); 15431 verifyFormat("switch (x) {\n" 15432 "default:\n" 15433 " break;\n" 15434 "}", 15435 SomeSpace2); 15436 verifyFormat("A::A() : a (1) {}", SomeSpace2); 15437 verifyFormat("void f() __attribute__ ((asdf));", SomeSpace2); 15438 verifyFormat("*(&a + 1);\n" 15439 "&((&a)[1]);\n" 15440 "a[(b + c) * d];\n" 15441 "(((a + 1) * 2) + 3) * 4;", 15442 SomeSpace2); 15443 verifyFormat("#define A(x) x", SomeSpace2); 15444 verifyFormat("#define A (x) x", SomeSpace2); 15445 verifyFormat("#if defined(x)\n" 15446 "#endif", 15447 SomeSpace2); 15448 verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace2); 15449 verifyFormat("size_t x = sizeof (x);", SomeSpace2); 15450 verifyFormat("auto f (int x) -> decltype (x);", SomeSpace2); 15451 verifyFormat("auto f (int x) -> typeof (x);", SomeSpace2); 15452 verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace2); 15453 verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace2); 15454 verifyFormat("int f (T x) noexcept (x.create());", SomeSpace2); 15455 verifyFormat("alignas (128) char a[128];", SomeSpace2); 15456 verifyFormat("size_t x = alignof (MyType);", SomeSpace2); 15457 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", 15458 SomeSpace2); 15459 verifyFormat("int f() throw (Deprecated);", SomeSpace2); 15460 verifyFormat("typedef void (*cb) (int);", SomeSpace2); 15461 verifyFormat("T A::operator()();", SomeSpace2); 15462 // verifyFormat("X A::operator++ (T);", SomeSpace2); 15463 verifyFormat("int x = int (y);", SomeSpace2); 15464 verifyFormat("auto lambda = []() { return 0; };", SomeSpace2); 15465 15466 FormatStyle SpaceAfterOverloadedOperator = getLLVMStyle(); 15467 SpaceAfterOverloadedOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15468 SpaceAfterOverloadedOperator.SpaceBeforeParensOptions 15469 .AfterOverloadedOperator = true; 15470 15471 verifyFormat("auto operator++ () -> int;", SpaceAfterOverloadedOperator); 15472 verifyFormat("X A::operator++ ();", SpaceAfterOverloadedOperator); 15473 verifyFormat("some_object.operator++ ();", SpaceAfterOverloadedOperator); 15474 verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator); 15475 15476 SpaceAfterOverloadedOperator.SpaceBeforeParensOptions 15477 .AfterOverloadedOperator = false; 15478 15479 verifyFormat("auto operator++() -> int;", SpaceAfterOverloadedOperator); 15480 verifyFormat("X A::operator++();", SpaceAfterOverloadedOperator); 15481 verifyFormat("some_object.operator++();", SpaceAfterOverloadedOperator); 15482 verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator); 15483 15484 auto SpaceAfterRequires = getLLVMStyle(); 15485 SpaceAfterRequires.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15486 EXPECT_FALSE( 15487 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause); 15488 EXPECT_FALSE( 15489 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression); 15490 verifyFormat("void f(auto x)\n" 15491 " requires requires(int i) { x + i; }\n" 15492 "{}", 15493 SpaceAfterRequires); 15494 verifyFormat("void f(auto x)\n" 15495 " requires(requires(int i) { x + i; })\n" 15496 "{}", 15497 SpaceAfterRequires); 15498 verifyFormat("if (requires(int i) { x + i; })\n" 15499 " return;", 15500 SpaceAfterRequires); 15501 verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires); 15502 verifyFormat("template <typename T>\n" 15503 " requires(Foo<T>)\n" 15504 "class Bar;", 15505 SpaceAfterRequires); 15506 15507 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true; 15508 verifyFormat("void f(auto x)\n" 15509 " requires requires(int i) { x + i; }\n" 15510 "{}", 15511 SpaceAfterRequires); 15512 verifyFormat("void f(auto x)\n" 15513 " requires (requires(int i) { x + i; })\n" 15514 "{}", 15515 SpaceAfterRequires); 15516 verifyFormat("if (requires(int i) { x + i; })\n" 15517 " return;", 15518 SpaceAfterRequires); 15519 verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires); 15520 verifyFormat("template <typename T>\n" 15521 " requires (Foo<T>)\n" 15522 "class Bar;", 15523 SpaceAfterRequires); 15524 15525 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = false; 15526 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression = true; 15527 verifyFormat("void f(auto x)\n" 15528 " requires requires (int i) { x + i; }\n" 15529 "{}", 15530 SpaceAfterRequires); 15531 verifyFormat("void f(auto x)\n" 15532 " requires(requires (int i) { x + i; })\n" 15533 "{}", 15534 SpaceAfterRequires); 15535 verifyFormat("if (requires (int i) { x + i; })\n" 15536 " return;", 15537 SpaceAfterRequires); 15538 verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires); 15539 verifyFormat("template <typename T>\n" 15540 " requires(Foo<T>)\n" 15541 "class Bar;", 15542 SpaceAfterRequires); 15543 15544 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true; 15545 verifyFormat("void f(auto x)\n" 15546 " requires requires (int i) { x + i; }\n" 15547 "{}", 15548 SpaceAfterRequires); 15549 verifyFormat("void f(auto x)\n" 15550 " requires (requires (int i) { x + i; })\n" 15551 "{}", 15552 SpaceAfterRequires); 15553 verifyFormat("if (requires (int i) { x + i; })\n" 15554 " return;", 15555 SpaceAfterRequires); 15556 verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires); 15557 verifyFormat("template <typename T>\n" 15558 " requires (Foo<T>)\n" 15559 "class Bar;", 15560 SpaceAfterRequires); 15561 } 15562 15563 TEST_F(FormatTest, SpaceAfterLogicalNot) { 15564 FormatStyle Spaces = getLLVMStyle(); 15565 Spaces.SpaceAfterLogicalNot = true; 15566 15567 verifyFormat("bool x = ! y", Spaces); 15568 verifyFormat("if (! isFailure())", Spaces); 15569 verifyFormat("if (! (a && b))", Spaces); 15570 verifyFormat("\"Error!\"", Spaces); 15571 verifyFormat("! ! x", Spaces); 15572 } 15573 15574 TEST_F(FormatTest, ConfigurableSpacesInParentheses) { 15575 FormatStyle Spaces = getLLVMStyle(); 15576 15577 Spaces.SpacesInParentheses = true; 15578 verifyFormat("do_something( ::globalVar );", Spaces); 15579 verifyFormat("call( x, y, z );", Spaces); 15580 verifyFormat("call();", Spaces); 15581 verifyFormat("std::function<void( int, int )> callback;", Spaces); 15582 verifyFormat("void inFunction() { std::function<void( int, int )> fct; }", 15583 Spaces); 15584 verifyFormat("while ( (bool)1 )\n" 15585 " continue;", 15586 Spaces); 15587 verifyFormat("for ( ;; )\n" 15588 " continue;", 15589 Spaces); 15590 verifyFormat("if ( true )\n" 15591 " f();\n" 15592 "else if ( true )\n" 15593 " f();", 15594 Spaces); 15595 verifyFormat("do {\n" 15596 " do_something( (int)i );\n" 15597 "} while ( something() );", 15598 Spaces); 15599 verifyFormat("switch ( x ) {\n" 15600 "default:\n" 15601 " break;\n" 15602 "}", 15603 Spaces); 15604 15605 Spaces.SpacesInParentheses = false; 15606 Spaces.SpacesInCStyleCastParentheses = true; 15607 verifyFormat("Type *A = ( Type * )P;", Spaces); 15608 verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces); 15609 verifyFormat("x = ( int32 )y;", Spaces); 15610 verifyFormat("int a = ( int )(2.0f);", Spaces); 15611 verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces); 15612 verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces); 15613 verifyFormat("#define x (( int )-1)", Spaces); 15614 15615 // Run the first set of tests again with: 15616 Spaces.SpacesInParentheses = false; 15617 Spaces.SpaceInEmptyParentheses = true; 15618 Spaces.SpacesInCStyleCastParentheses = true; 15619 verifyFormat("call(x, y, z);", Spaces); 15620 verifyFormat("call( );", Spaces); 15621 verifyFormat("std::function<void(int, int)> callback;", Spaces); 15622 verifyFormat("while (( bool )1)\n" 15623 " continue;", 15624 Spaces); 15625 verifyFormat("for (;;)\n" 15626 " continue;", 15627 Spaces); 15628 verifyFormat("if (true)\n" 15629 " f( );\n" 15630 "else if (true)\n" 15631 " f( );", 15632 Spaces); 15633 verifyFormat("do {\n" 15634 " do_something(( int )i);\n" 15635 "} while (something( ));", 15636 Spaces); 15637 verifyFormat("switch (x) {\n" 15638 "default:\n" 15639 " break;\n" 15640 "}", 15641 Spaces); 15642 15643 // Run the first set of tests again with: 15644 Spaces.SpaceAfterCStyleCast = true; 15645 verifyFormat("call(x, y, z);", Spaces); 15646 verifyFormat("call( );", Spaces); 15647 verifyFormat("std::function<void(int, int)> callback;", Spaces); 15648 verifyFormat("while (( bool ) 1)\n" 15649 " continue;", 15650 Spaces); 15651 verifyFormat("for (;;)\n" 15652 " continue;", 15653 Spaces); 15654 verifyFormat("if (true)\n" 15655 " f( );\n" 15656 "else if (true)\n" 15657 " f( );", 15658 Spaces); 15659 verifyFormat("do {\n" 15660 " do_something(( int ) i);\n" 15661 "} while (something( ));", 15662 Spaces); 15663 verifyFormat("switch (x) {\n" 15664 "default:\n" 15665 " break;\n" 15666 "}", 15667 Spaces); 15668 verifyFormat("#define CONF_BOOL(x) ( bool * ) ( void * ) (x)", Spaces); 15669 verifyFormat("#define CONF_BOOL(x) ( bool * ) (x)", Spaces); 15670 verifyFormat("#define CONF_BOOL(x) ( bool ) (x)", Spaces); 15671 verifyFormat("bool *y = ( bool * ) ( void * ) (x);", Spaces); 15672 verifyFormat("bool *y = ( bool * ) (x);", Spaces); 15673 15674 // Run subset of tests again with: 15675 Spaces.SpacesInCStyleCastParentheses = false; 15676 Spaces.SpaceAfterCStyleCast = true; 15677 verifyFormat("while ((bool) 1)\n" 15678 " continue;", 15679 Spaces); 15680 verifyFormat("do {\n" 15681 " do_something((int) i);\n" 15682 "} while (something( ));", 15683 Spaces); 15684 15685 verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces); 15686 verifyFormat("size_t idx = (size_t) a;", Spaces); 15687 verifyFormat("size_t idx = (size_t) (a - 1);", Spaces); 15688 verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces); 15689 verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces); 15690 verifyFormat("size_t idx = (*foo)(a - 1);", Spaces); 15691 verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces); 15692 verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (x)", Spaces); 15693 verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (int) (x)", Spaces); 15694 verifyFormat("bool *y = (bool *) (void *) (x);", Spaces); 15695 verifyFormat("bool *y = (bool *) (void *) (int) (x);", Spaces); 15696 verifyFormat("bool *y = (bool *) (void *) (int) foo(x);", Spaces); 15697 Spaces.ColumnLimit = 80; 15698 Spaces.IndentWidth = 4; 15699 Spaces.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 15700 verifyFormat("void foo( ) {\n" 15701 " size_t foo = (*(function))(\n" 15702 " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, " 15703 "BarrrrrrrrrrrrLong,\n" 15704 " FoooooooooLooooong);\n" 15705 "}", 15706 Spaces); 15707 Spaces.SpaceAfterCStyleCast = false; 15708 verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces); 15709 verifyFormat("size_t idx = (size_t)a;", Spaces); 15710 verifyFormat("size_t idx = (size_t)(a - 1);", Spaces); 15711 verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces); 15712 verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces); 15713 verifyFormat("size_t idx = (*foo)(a - 1);", Spaces); 15714 verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces); 15715 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 } 15724 15725 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) { 15726 verifyFormat("int a[5];"); 15727 verifyFormat("a[3] += 42;"); 15728 15729 FormatStyle Spaces = getLLVMStyle(); 15730 Spaces.SpacesInSquareBrackets = true; 15731 // Not lambdas. 15732 verifyFormat("int a[ 5 ];", Spaces); 15733 verifyFormat("a[ 3 ] += 42;", Spaces); 15734 verifyFormat("constexpr char hello[]{\"hello\"};", Spaces); 15735 verifyFormat("double &operator[](int i) { return 0; }\n" 15736 "int i;", 15737 Spaces); 15738 verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces); 15739 verifyFormat("int i = a[ a ][ a ]->f();", Spaces); 15740 verifyFormat("int i = (*b)[ a ]->f();", Spaces); 15741 // Lambdas. 15742 verifyFormat("int c = []() -> int { return 2; }();\n", Spaces); 15743 verifyFormat("return [ i, args... ] {};", Spaces); 15744 verifyFormat("int foo = [ &bar ]() {};", Spaces); 15745 verifyFormat("int foo = [ = ]() {};", Spaces); 15746 verifyFormat("int foo = [ & ]() {};", Spaces); 15747 verifyFormat("int foo = [ =, &bar ]() {};", Spaces); 15748 verifyFormat("int foo = [ &bar, = ]() {};", Spaces); 15749 } 15750 15751 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) { 15752 FormatStyle NoSpaceStyle = getLLVMStyle(); 15753 verifyFormat("int a[5];", NoSpaceStyle); 15754 verifyFormat("a[3] += 42;", NoSpaceStyle); 15755 15756 verifyFormat("int a[1];", NoSpaceStyle); 15757 verifyFormat("int 1 [a];", NoSpaceStyle); 15758 verifyFormat("int a[1][2];", NoSpaceStyle); 15759 verifyFormat("a[7] = 5;", NoSpaceStyle); 15760 verifyFormat("int a = (f())[23];", NoSpaceStyle); 15761 verifyFormat("f([] {})", NoSpaceStyle); 15762 15763 FormatStyle Space = getLLVMStyle(); 15764 Space.SpaceBeforeSquareBrackets = true; 15765 verifyFormat("int c = []() -> int { return 2; }();\n", Space); 15766 verifyFormat("return [i, args...] {};", Space); 15767 15768 verifyFormat("int a [5];", Space); 15769 verifyFormat("a [3] += 42;", Space); 15770 verifyFormat("constexpr char hello []{\"hello\"};", Space); 15771 verifyFormat("double &operator[](int i) { return 0; }\n" 15772 "int i;", 15773 Space); 15774 verifyFormat("std::unique_ptr<int []> foo() {}", Space); 15775 verifyFormat("int i = a [a][a]->f();", Space); 15776 verifyFormat("int i = (*b) [a]->f();", Space); 15777 15778 verifyFormat("int a [1];", Space); 15779 verifyFormat("int 1 [a];", Space); 15780 verifyFormat("int a [1][2];", Space); 15781 verifyFormat("a [7] = 5;", Space); 15782 verifyFormat("int a = (f()) [23];", Space); 15783 verifyFormat("f([] {})", Space); 15784 } 15785 15786 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) { 15787 verifyFormat("int a = 5;"); 15788 verifyFormat("a += 42;"); 15789 verifyFormat("a or_eq 8;"); 15790 15791 FormatStyle Spaces = getLLVMStyle(); 15792 Spaces.SpaceBeforeAssignmentOperators = false; 15793 verifyFormat("int a= 5;", Spaces); 15794 verifyFormat("a+= 42;", Spaces); 15795 verifyFormat("a or_eq 8;", Spaces); 15796 } 15797 15798 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) { 15799 verifyFormat("class Foo : public Bar {};"); 15800 verifyFormat("Foo::Foo() : foo(1) {}"); 15801 verifyFormat("for (auto a : b) {\n}"); 15802 verifyFormat("int x = a ? b : c;"); 15803 verifyFormat("{\n" 15804 "label0:\n" 15805 " int x = 0;\n" 15806 "}"); 15807 verifyFormat("switch (x) {\n" 15808 "case 1:\n" 15809 "default:\n" 15810 "}"); 15811 verifyFormat("switch (allBraces) {\n" 15812 "case 1: {\n" 15813 " break;\n" 15814 "}\n" 15815 "case 2: {\n" 15816 " [[fallthrough]];\n" 15817 "}\n" 15818 "default: {\n" 15819 " break;\n" 15820 "}\n" 15821 "}"); 15822 15823 FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30); 15824 CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false; 15825 verifyFormat("class Foo : public Bar {};", CtorInitializerStyle); 15826 verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle); 15827 verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle); 15828 verifyFormat("int x = a ? b : c;", CtorInitializerStyle); 15829 verifyFormat("{\n" 15830 "label1:\n" 15831 " int x = 0;\n" 15832 "}", 15833 CtorInitializerStyle); 15834 verifyFormat("switch (x) {\n" 15835 "case 1:\n" 15836 "default:\n" 15837 "}", 15838 CtorInitializerStyle); 15839 verifyFormat("switch (allBraces) {\n" 15840 "case 1: {\n" 15841 " break;\n" 15842 "}\n" 15843 "case 2: {\n" 15844 " [[fallthrough]];\n" 15845 "}\n" 15846 "default: {\n" 15847 " break;\n" 15848 "}\n" 15849 "}", 15850 CtorInitializerStyle); 15851 CtorInitializerStyle.BreakConstructorInitializers = 15852 FormatStyle::BCIS_AfterColon; 15853 verifyFormat("Fooooooooooo::Fooooooooooo():\n" 15854 " aaaaaaaaaaaaaaaa(1),\n" 15855 " bbbbbbbbbbbbbbbb(2) {}", 15856 CtorInitializerStyle); 15857 CtorInitializerStyle.BreakConstructorInitializers = 15858 FormatStyle::BCIS_BeforeComma; 15859 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15860 " : aaaaaaaaaaaaaaaa(1)\n" 15861 " , bbbbbbbbbbbbbbbb(2) {}", 15862 CtorInitializerStyle); 15863 CtorInitializerStyle.BreakConstructorInitializers = 15864 FormatStyle::BCIS_BeforeColon; 15865 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15866 " : aaaaaaaaaaaaaaaa(1),\n" 15867 " bbbbbbbbbbbbbbbb(2) {}", 15868 CtorInitializerStyle); 15869 CtorInitializerStyle.ConstructorInitializerIndentWidth = 0; 15870 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15871 ": aaaaaaaaaaaaaaaa(1),\n" 15872 " bbbbbbbbbbbbbbbb(2) {}", 15873 CtorInitializerStyle); 15874 15875 FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30); 15876 InheritanceStyle.SpaceBeforeInheritanceColon = false; 15877 verifyFormat("class Foo: public Bar {};", InheritanceStyle); 15878 verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle); 15879 verifyFormat("for (auto a : b) {\n}", InheritanceStyle); 15880 verifyFormat("int x = a ? b : c;", InheritanceStyle); 15881 verifyFormat("{\n" 15882 "label2:\n" 15883 " int x = 0;\n" 15884 "}", 15885 InheritanceStyle); 15886 verifyFormat("switch (x) {\n" 15887 "case 1:\n" 15888 "default:\n" 15889 "}", 15890 InheritanceStyle); 15891 verifyFormat("switch (allBraces) {\n" 15892 "case 1: {\n" 15893 " break;\n" 15894 "}\n" 15895 "case 2: {\n" 15896 " [[fallthrough]];\n" 15897 "}\n" 15898 "default: {\n" 15899 " break;\n" 15900 "}\n" 15901 "}", 15902 InheritanceStyle); 15903 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterComma; 15904 verifyFormat("class Foooooooooooooooooooooo\n" 15905 " : public aaaaaaaaaaaaaaaaaa,\n" 15906 " public bbbbbbbbbbbbbbbbbb {\n" 15907 "}", 15908 InheritanceStyle); 15909 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon; 15910 verifyFormat("class Foooooooooooooooooooooo:\n" 15911 " public aaaaaaaaaaaaaaaaaa,\n" 15912 " public bbbbbbbbbbbbbbbbbb {\n" 15913 "}", 15914 InheritanceStyle); 15915 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma; 15916 verifyFormat("class Foooooooooooooooooooooo\n" 15917 " : public aaaaaaaaaaaaaaaaaa\n" 15918 " , public bbbbbbbbbbbbbbbbbb {\n" 15919 "}", 15920 InheritanceStyle); 15921 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 15922 verifyFormat("class Foooooooooooooooooooooo\n" 15923 " : public aaaaaaaaaaaaaaaaaa,\n" 15924 " public bbbbbbbbbbbbbbbbbb {\n" 15925 "}", 15926 InheritanceStyle); 15927 InheritanceStyle.ConstructorInitializerIndentWidth = 0; 15928 verifyFormat("class Foooooooooooooooooooooo\n" 15929 ": public aaaaaaaaaaaaaaaaaa,\n" 15930 " public bbbbbbbbbbbbbbbbbb {}", 15931 InheritanceStyle); 15932 15933 FormatStyle ForLoopStyle = getLLVMStyle(); 15934 ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false; 15935 verifyFormat("class Foo : public Bar {};", ForLoopStyle); 15936 verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle); 15937 verifyFormat("for (auto a: b) {\n}", ForLoopStyle); 15938 verifyFormat("int x = a ? b : c;", ForLoopStyle); 15939 verifyFormat("{\n" 15940 "label2:\n" 15941 " int x = 0;\n" 15942 "}", 15943 ForLoopStyle); 15944 verifyFormat("switch (x) {\n" 15945 "case 1:\n" 15946 "default:\n" 15947 "}", 15948 ForLoopStyle); 15949 verifyFormat("switch (allBraces) {\n" 15950 "case 1: {\n" 15951 " break;\n" 15952 "}\n" 15953 "case 2: {\n" 15954 " [[fallthrough]];\n" 15955 "}\n" 15956 "default: {\n" 15957 " break;\n" 15958 "}\n" 15959 "}", 15960 ForLoopStyle); 15961 15962 FormatStyle CaseStyle = getLLVMStyle(); 15963 CaseStyle.SpaceBeforeCaseColon = true; 15964 verifyFormat("class Foo : public Bar {};", CaseStyle); 15965 verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle); 15966 verifyFormat("for (auto a : b) {\n}", CaseStyle); 15967 verifyFormat("int x = a ? b : c;", CaseStyle); 15968 verifyFormat("switch (x) {\n" 15969 "case 1 :\n" 15970 "default :\n" 15971 "}", 15972 CaseStyle); 15973 verifyFormat("switch (allBraces) {\n" 15974 "case 1 : {\n" 15975 " break;\n" 15976 "}\n" 15977 "case 2 : {\n" 15978 " [[fallthrough]];\n" 15979 "}\n" 15980 "default : {\n" 15981 " break;\n" 15982 "}\n" 15983 "}", 15984 CaseStyle); 15985 15986 FormatStyle NoSpaceStyle = getLLVMStyle(); 15987 EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false); 15988 NoSpaceStyle.SpaceBeforeCtorInitializerColon = false; 15989 NoSpaceStyle.SpaceBeforeInheritanceColon = false; 15990 NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false; 15991 verifyFormat("class Foo: public Bar {};", NoSpaceStyle); 15992 verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle); 15993 verifyFormat("for (auto a: b) {\n}", NoSpaceStyle); 15994 verifyFormat("int x = a ? b : c;", NoSpaceStyle); 15995 verifyFormat("{\n" 15996 "label3:\n" 15997 " int x = 0;\n" 15998 "}", 15999 NoSpaceStyle); 16000 verifyFormat("switch (x) {\n" 16001 "case 1:\n" 16002 "default:\n" 16003 "}", 16004 NoSpaceStyle); 16005 verifyFormat("switch (allBraces) {\n" 16006 "case 1: {\n" 16007 " break;\n" 16008 "}\n" 16009 "case 2: {\n" 16010 " [[fallthrough]];\n" 16011 "}\n" 16012 "default: {\n" 16013 " break;\n" 16014 "}\n" 16015 "}", 16016 NoSpaceStyle); 16017 16018 FormatStyle InvertedSpaceStyle = getLLVMStyle(); 16019 InvertedSpaceStyle.SpaceBeforeCaseColon = true; 16020 InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false; 16021 InvertedSpaceStyle.SpaceBeforeInheritanceColon = false; 16022 InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false; 16023 verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle); 16024 verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle); 16025 verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle); 16026 verifyFormat("int x = a ? b : c;", InvertedSpaceStyle); 16027 verifyFormat("{\n" 16028 "label3:\n" 16029 " int x = 0;\n" 16030 "}", 16031 InvertedSpaceStyle); 16032 verifyFormat("switch (x) {\n" 16033 "case 1 :\n" 16034 "case 2 : {\n" 16035 " break;\n" 16036 "}\n" 16037 "default :\n" 16038 " break;\n" 16039 "}", 16040 InvertedSpaceStyle); 16041 verifyFormat("switch (allBraces) {\n" 16042 "case 1 : {\n" 16043 " break;\n" 16044 "}\n" 16045 "case 2 : {\n" 16046 " [[fallthrough]];\n" 16047 "}\n" 16048 "default : {\n" 16049 " break;\n" 16050 "}\n" 16051 "}", 16052 InvertedSpaceStyle); 16053 } 16054 16055 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) { 16056 FormatStyle Style = getLLVMStyle(); 16057 16058 Style.PointerAlignment = FormatStyle::PAS_Left; 16059 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default; 16060 verifyFormat("void* const* x = NULL;", Style); 16061 16062 #define verifyQualifierSpaces(Code, Pointers, Qualifiers) \ 16063 do { \ 16064 Style.PointerAlignment = FormatStyle::Pointers; \ 16065 Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers; \ 16066 verifyFormat(Code, Style); \ 16067 } while (false) 16068 16069 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default); 16070 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default); 16071 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default); 16072 16073 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before); 16074 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before); 16075 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before); 16076 16077 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After); 16078 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After); 16079 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After); 16080 16081 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both); 16082 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both); 16083 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both); 16084 16085 verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default); 16086 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, 16087 SAPQ_Default); 16088 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 16089 SAPQ_Default); 16090 16091 verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before); 16092 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, 16093 SAPQ_Before); 16094 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 16095 SAPQ_Before); 16096 16097 verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After); 16098 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After); 16099 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 16100 SAPQ_After); 16101 16102 verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both); 16103 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both); 16104 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both); 16105 16106 #undef verifyQualifierSpaces 16107 16108 FormatStyle Spaces = getLLVMStyle(); 16109 Spaces.AttributeMacros.push_back("qualified"); 16110 Spaces.PointerAlignment = FormatStyle::PAS_Right; 16111 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default; 16112 verifyFormat("SomeType *volatile *a = NULL;", Spaces); 16113 verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces); 16114 verifyFormat("std::vector<SomeType *const *> x;", Spaces); 16115 verifyFormat("std::vector<SomeType *qualified *> x;", Spaces); 16116 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 16117 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before; 16118 verifyFormat("SomeType * volatile *a = NULL;", Spaces); 16119 verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces); 16120 verifyFormat("std::vector<SomeType * const *> x;", Spaces); 16121 verifyFormat("std::vector<SomeType * qualified *> x;", Spaces); 16122 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 16123 16124 // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left. 16125 Spaces.PointerAlignment = FormatStyle::PAS_Left; 16126 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before; 16127 verifyFormat("SomeType* volatile* a = NULL;", Spaces); 16128 verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces); 16129 verifyFormat("std::vector<SomeType* const*> x;", Spaces); 16130 verifyFormat("std::vector<SomeType* qualified*> x;", Spaces); 16131 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 16132 // However, setting it to SAPQ_After should add spaces after __attribute, etc. 16133 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After; 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 // PAS_Middle should not have any noticeable changes even for SAPQ_Both 16141 Spaces.PointerAlignment = FormatStyle::PAS_Middle; 16142 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After; 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 } 16149 16150 TEST_F(FormatTest, AlignConsecutiveMacros) { 16151 FormatStyle Style = getLLVMStyle(); 16152 Style.AlignConsecutiveAssignments.Enabled = true; 16153 Style.AlignConsecutiveDeclarations.Enabled = true; 16154 16155 verifyFormat("#define a 3\n" 16156 "#define bbbb 4\n" 16157 "#define ccc (5)", 16158 Style); 16159 16160 verifyFormat("#define f(x) (x * x)\n" 16161 "#define fff(x, y, z) (x * y + z)\n" 16162 "#define ffff(x, y) (x - y)", 16163 Style); 16164 16165 verifyFormat("#define foo(x, y) (x + y)\n" 16166 "#define bar (5, 6)(2 + 2)", 16167 Style); 16168 16169 verifyFormat("#define a 3\n" 16170 "#define bbbb 4\n" 16171 "#define ccc (5)\n" 16172 "#define f(x) (x * x)\n" 16173 "#define fff(x, y, z) (x * y + z)\n" 16174 "#define ffff(x, y) (x - y)", 16175 Style); 16176 16177 Style.AlignConsecutiveMacros.Enabled = true; 16178 verifyFormat("#define a 3\n" 16179 "#define bbbb 4\n" 16180 "#define ccc (5)", 16181 Style); 16182 16183 verifyFormat("#define true 1\n" 16184 "#define false 0", 16185 Style); 16186 16187 verifyFormat("#define f(x) (x * x)\n" 16188 "#define fff(x, y, z) (x * y + z)\n" 16189 "#define ffff(x, y) (x - y)", 16190 Style); 16191 16192 verifyFormat("#define foo(x, y) (x + y)\n" 16193 "#define bar (5, 6)(2 + 2)", 16194 Style); 16195 16196 verifyFormat("#define a 3\n" 16197 "#define bbbb 4\n" 16198 "#define ccc (5)\n" 16199 "#define f(x) (x * x)\n" 16200 "#define fff(x, y, z) (x * y + z)\n" 16201 "#define ffff(x, y) (x - y)", 16202 Style); 16203 16204 verifyFormat("#define a 5\n" 16205 "#define foo(x, y) (x + y)\n" 16206 "#define CCC (6)\n" 16207 "auto lambda = []() {\n" 16208 " auto ii = 0;\n" 16209 " float j = 0;\n" 16210 " return 0;\n" 16211 "};\n" 16212 "int i = 0;\n" 16213 "float i2 = 0;\n" 16214 "auto v = type{\n" 16215 " i = 1, //\n" 16216 " (i = 2), //\n" 16217 " i = 3 //\n" 16218 "};", 16219 Style); 16220 16221 Style.AlignConsecutiveMacros.Enabled = false; 16222 Style.ColumnLimit = 20; 16223 16224 verifyFormat("#define a \\\n" 16225 " \"aabbbbbbbbbbbb\"\n" 16226 "#define D \\\n" 16227 " \"aabbbbbbbbbbbb\" \\\n" 16228 " \"ccddeeeeeeeee\"\n" 16229 "#define B \\\n" 16230 " \"QQQQQQQQQQQQQ\" \\\n" 16231 " \"FFFFFFFFFFFFF\" \\\n" 16232 " \"LLLLLLLL\"\n", 16233 Style); 16234 16235 Style.AlignConsecutiveMacros.Enabled = true; 16236 verifyFormat("#define a \\\n" 16237 " \"aabbbbbbbbbbbb\"\n" 16238 "#define D \\\n" 16239 " \"aabbbbbbbbbbbb\" \\\n" 16240 " \"ccddeeeeeeeee\"\n" 16241 "#define B \\\n" 16242 " \"QQQQQQQQQQQQQ\" \\\n" 16243 " \"FFFFFFFFFFFFF\" \\\n" 16244 " \"LLLLLLLL\"\n", 16245 Style); 16246 16247 // Test across comments 16248 Style.MaxEmptyLinesToKeep = 10; 16249 Style.ReflowComments = false; 16250 Style.AlignConsecutiveMacros.AcrossComments = true; 16251 EXPECT_EQ("#define a 3\n" 16252 "// line comment\n" 16253 "#define bbbb 4\n" 16254 "#define ccc (5)", 16255 format("#define a 3\n" 16256 "// line comment\n" 16257 "#define bbbb 4\n" 16258 "#define ccc (5)", 16259 Style)); 16260 16261 EXPECT_EQ("#define a 3\n" 16262 "/* block comment */\n" 16263 "#define bbbb 4\n" 16264 "#define ccc (5)", 16265 format("#define a 3\n" 16266 "/* block comment */\n" 16267 "#define bbbb 4\n" 16268 "#define ccc (5)", 16269 Style)); 16270 16271 EXPECT_EQ("#define a 3\n" 16272 "/* multi-line *\n" 16273 " * block comment */\n" 16274 "#define bbbb 4\n" 16275 "#define ccc (5)", 16276 format("#define a 3\n" 16277 "/* multi-line *\n" 16278 " * block comment */\n" 16279 "#define bbbb 4\n" 16280 "#define ccc (5)", 16281 Style)); 16282 16283 EXPECT_EQ("#define a 3\n" 16284 "// multi-line line comment\n" 16285 "//\n" 16286 "#define bbbb 4\n" 16287 "#define ccc (5)", 16288 format("#define a 3\n" 16289 "// multi-line line comment\n" 16290 "//\n" 16291 "#define bbbb 4\n" 16292 "#define ccc (5)", 16293 Style)); 16294 16295 EXPECT_EQ("#define a 3\n" 16296 "// empty lines still break.\n" 16297 "\n" 16298 "#define bbbb 4\n" 16299 "#define ccc (5)", 16300 format("#define a 3\n" 16301 "// empty lines still break.\n" 16302 "\n" 16303 "#define bbbb 4\n" 16304 "#define ccc (5)", 16305 Style)); 16306 16307 // Test across empty lines 16308 Style.AlignConsecutiveMacros.AcrossComments = false; 16309 Style.AlignConsecutiveMacros.AcrossEmptyLines = true; 16310 EXPECT_EQ("#define a 3\n" 16311 "\n" 16312 "#define bbbb 4\n" 16313 "#define ccc (5)", 16314 format("#define a 3\n" 16315 "\n" 16316 "#define bbbb 4\n" 16317 "#define ccc (5)", 16318 Style)); 16319 16320 EXPECT_EQ("#define a 3\n" 16321 "\n" 16322 "\n" 16323 "\n" 16324 "#define bbbb 4\n" 16325 "#define ccc (5)", 16326 format("#define a 3\n" 16327 "\n" 16328 "\n" 16329 "\n" 16330 "#define bbbb 4\n" 16331 "#define ccc (5)", 16332 Style)); 16333 16334 EXPECT_EQ("#define a 3\n" 16335 "// comments should break alignment\n" 16336 "//\n" 16337 "#define bbbb 4\n" 16338 "#define ccc (5)", 16339 format("#define a 3\n" 16340 "// comments should break alignment\n" 16341 "//\n" 16342 "#define bbbb 4\n" 16343 "#define ccc (5)", 16344 Style)); 16345 16346 // Test across empty lines and comments 16347 Style.AlignConsecutiveMacros.AcrossComments = true; 16348 verifyFormat("#define a 3\n" 16349 "\n" 16350 "// line comment\n" 16351 "#define bbbb 4\n" 16352 "#define ccc (5)", 16353 Style); 16354 16355 EXPECT_EQ("#define a 3\n" 16356 "\n" 16357 "\n" 16358 "/* multi-line *\n" 16359 " * block comment */\n" 16360 "\n" 16361 "\n" 16362 "#define bbbb 4\n" 16363 "#define ccc (5)", 16364 format("#define a 3\n" 16365 "\n" 16366 "\n" 16367 "/* multi-line *\n" 16368 " * block comment */\n" 16369 "\n" 16370 "\n" 16371 "#define bbbb 4\n" 16372 "#define ccc (5)", 16373 Style)); 16374 16375 EXPECT_EQ("#define a 3\n" 16376 "\n" 16377 "\n" 16378 "/* multi-line *\n" 16379 " * block comment */\n" 16380 "\n" 16381 "\n" 16382 "#define bbbb 4\n" 16383 "#define ccc (5)", 16384 format("#define a 3\n" 16385 "\n" 16386 "\n" 16387 "/* multi-line *\n" 16388 " * block comment */\n" 16389 "\n" 16390 "\n" 16391 "#define bbbb 4\n" 16392 "#define ccc (5)", 16393 Style)); 16394 } 16395 16396 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) { 16397 FormatStyle Alignment = getLLVMStyle(); 16398 Alignment.AlignConsecutiveMacros.Enabled = true; 16399 Alignment.AlignConsecutiveAssignments.Enabled = true; 16400 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true; 16401 16402 Alignment.MaxEmptyLinesToKeep = 10; 16403 /* Test alignment across empty lines */ 16404 EXPECT_EQ("int a = 5;\n" 16405 "\n" 16406 "int oneTwoThree = 123;", 16407 format("int a = 5;\n" 16408 "\n" 16409 "int oneTwoThree= 123;", 16410 Alignment)); 16411 EXPECT_EQ("int a = 5;\n" 16412 "int one = 1;\n" 16413 "\n" 16414 "int oneTwoThree = 123;", 16415 format("int a = 5;\n" 16416 "int one = 1;\n" 16417 "\n" 16418 "int oneTwoThree = 123;", 16419 Alignment)); 16420 EXPECT_EQ("int a = 5;\n" 16421 "int one = 1;\n" 16422 "\n" 16423 "int oneTwoThree = 123;\n" 16424 "int oneTwo = 12;", 16425 format("int a = 5;\n" 16426 "int one = 1;\n" 16427 "\n" 16428 "int oneTwoThree = 123;\n" 16429 "int oneTwo = 12;", 16430 Alignment)); 16431 16432 /* Test across comments */ 16433 EXPECT_EQ("int a = 5;\n" 16434 "/* block comment */\n" 16435 "int oneTwoThree = 123;", 16436 format("int a = 5;\n" 16437 "/* block comment */\n" 16438 "int oneTwoThree=123;", 16439 Alignment)); 16440 16441 EXPECT_EQ("int a = 5;\n" 16442 "// line comment\n" 16443 "int oneTwoThree = 123;", 16444 format("int a = 5;\n" 16445 "// line comment\n" 16446 "int oneTwoThree=123;", 16447 Alignment)); 16448 16449 /* Test across comments and newlines */ 16450 EXPECT_EQ("int a = 5;\n" 16451 "\n" 16452 "/* block comment */\n" 16453 "int oneTwoThree = 123;", 16454 format("int a = 5;\n" 16455 "\n" 16456 "/* block comment */\n" 16457 "int oneTwoThree=123;", 16458 Alignment)); 16459 16460 EXPECT_EQ("int a = 5;\n" 16461 "\n" 16462 "// line comment\n" 16463 "int oneTwoThree = 123;", 16464 format("int a = 5;\n" 16465 "\n" 16466 "// line comment\n" 16467 "int oneTwoThree=123;", 16468 Alignment)); 16469 } 16470 16471 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) { 16472 FormatStyle Alignment = getLLVMStyle(); 16473 Alignment.AlignConsecutiveDeclarations.Enabled = true; 16474 Alignment.AlignConsecutiveDeclarations.AcrossEmptyLines = true; 16475 Alignment.AlignConsecutiveDeclarations.AcrossComments = true; 16476 16477 Alignment.MaxEmptyLinesToKeep = 10; 16478 /* Test alignment across empty lines */ 16479 EXPECT_EQ("int a = 5;\n" 16480 "\n" 16481 "float const oneTwoThree = 123;", 16482 format("int a = 5;\n" 16483 "\n" 16484 "float const oneTwoThree = 123;", 16485 Alignment)); 16486 EXPECT_EQ("int a = 5;\n" 16487 "float const one = 1;\n" 16488 "\n" 16489 "int oneTwoThree = 123;", 16490 format("int a = 5;\n" 16491 "float const one = 1;\n" 16492 "\n" 16493 "int oneTwoThree = 123;", 16494 Alignment)); 16495 16496 /* Test across comments */ 16497 EXPECT_EQ("float const a = 5;\n" 16498 "/* block comment */\n" 16499 "int oneTwoThree = 123;", 16500 format("float const a = 5;\n" 16501 "/* block comment */\n" 16502 "int oneTwoThree=123;", 16503 Alignment)); 16504 16505 EXPECT_EQ("float const a = 5;\n" 16506 "// line comment\n" 16507 "int oneTwoThree = 123;", 16508 format("float const a = 5;\n" 16509 "// line comment\n" 16510 "int oneTwoThree=123;", 16511 Alignment)); 16512 16513 /* Test across comments and newlines */ 16514 EXPECT_EQ("float const a = 5;\n" 16515 "\n" 16516 "/* block comment */\n" 16517 "int oneTwoThree = 123;", 16518 format("float const a = 5;\n" 16519 "\n" 16520 "/* block comment */\n" 16521 "int oneTwoThree=123;", 16522 Alignment)); 16523 16524 EXPECT_EQ("float const a = 5;\n" 16525 "\n" 16526 "// line comment\n" 16527 "int oneTwoThree = 123;", 16528 format("float const a = 5;\n" 16529 "\n" 16530 "// line comment\n" 16531 "int oneTwoThree=123;", 16532 Alignment)); 16533 } 16534 16535 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) { 16536 FormatStyle Alignment = getLLVMStyle(); 16537 Alignment.AlignConsecutiveBitFields.Enabled = true; 16538 Alignment.AlignConsecutiveBitFields.AcrossEmptyLines = true; 16539 Alignment.AlignConsecutiveBitFields.AcrossComments = true; 16540 16541 Alignment.MaxEmptyLinesToKeep = 10; 16542 /* Test alignment across empty lines */ 16543 EXPECT_EQ("int a : 5;\n" 16544 "\n" 16545 "int longbitfield : 6;", 16546 format("int a : 5;\n" 16547 "\n" 16548 "int longbitfield : 6;", 16549 Alignment)); 16550 EXPECT_EQ("int a : 5;\n" 16551 "int one : 1;\n" 16552 "\n" 16553 "int longbitfield : 6;", 16554 format("int a : 5;\n" 16555 "int one : 1;\n" 16556 "\n" 16557 "int longbitfield : 6;", 16558 Alignment)); 16559 16560 /* Test across comments */ 16561 EXPECT_EQ("int a : 5;\n" 16562 "/* block comment */\n" 16563 "int longbitfield : 6;", 16564 format("int a : 5;\n" 16565 "/* block comment */\n" 16566 "int longbitfield : 6;", 16567 Alignment)); 16568 EXPECT_EQ("int a : 5;\n" 16569 "int one : 1;\n" 16570 "// line comment\n" 16571 "int longbitfield : 6;", 16572 format("int a : 5;\n" 16573 "int one : 1;\n" 16574 "// line comment\n" 16575 "int longbitfield : 6;", 16576 Alignment)); 16577 16578 /* Test across comments and newlines */ 16579 EXPECT_EQ("int a : 5;\n" 16580 "/* block comment */\n" 16581 "\n" 16582 "int longbitfield : 6;", 16583 format("int a : 5;\n" 16584 "/* block comment */\n" 16585 "\n" 16586 "int longbitfield : 6;", 16587 Alignment)); 16588 EXPECT_EQ("int a : 5;\n" 16589 "int one : 1;\n" 16590 "\n" 16591 "// line comment\n" 16592 "\n" 16593 "int longbitfield : 6;", 16594 format("int a : 5;\n" 16595 "int one : 1;\n" 16596 "\n" 16597 "// line comment \n" 16598 "\n" 16599 "int longbitfield : 6;", 16600 Alignment)); 16601 } 16602 16603 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) { 16604 FormatStyle Alignment = getLLVMStyle(); 16605 Alignment.AlignConsecutiveMacros.Enabled = true; 16606 Alignment.AlignConsecutiveAssignments.Enabled = true; 16607 Alignment.AlignConsecutiveAssignments.AcrossComments = true; 16608 16609 Alignment.MaxEmptyLinesToKeep = 10; 16610 /* Test alignment across empty lines */ 16611 EXPECT_EQ("int a = 5;\n" 16612 "\n" 16613 "int oneTwoThree = 123;", 16614 format("int a = 5;\n" 16615 "\n" 16616 "int oneTwoThree= 123;", 16617 Alignment)); 16618 EXPECT_EQ("int a = 5;\n" 16619 "int one = 1;\n" 16620 "\n" 16621 "int oneTwoThree = 123;", 16622 format("int a = 5;\n" 16623 "int one = 1;\n" 16624 "\n" 16625 "int oneTwoThree = 123;", 16626 Alignment)); 16627 16628 /* Test across comments */ 16629 EXPECT_EQ("int a = 5;\n" 16630 "/* block comment */\n" 16631 "int oneTwoThree = 123;", 16632 format("int a = 5;\n" 16633 "/* block comment */\n" 16634 "int oneTwoThree=123;", 16635 Alignment)); 16636 16637 EXPECT_EQ("int a = 5;\n" 16638 "// line comment\n" 16639 "int oneTwoThree = 123;", 16640 format("int a = 5;\n" 16641 "// line comment\n" 16642 "int oneTwoThree=123;", 16643 Alignment)); 16644 16645 EXPECT_EQ("int a = 5;\n" 16646 "/*\n" 16647 " * multi-line block comment\n" 16648 " */\n" 16649 "int oneTwoThree = 123;", 16650 format("int a = 5;\n" 16651 "/*\n" 16652 " * multi-line block comment\n" 16653 " */\n" 16654 "int oneTwoThree=123;", 16655 Alignment)); 16656 16657 EXPECT_EQ("int a = 5;\n" 16658 "//\n" 16659 "// multi-line line comment\n" 16660 "//\n" 16661 "int oneTwoThree = 123;", 16662 format("int a = 5;\n" 16663 "//\n" 16664 "// multi-line line comment\n" 16665 "//\n" 16666 "int oneTwoThree=123;", 16667 Alignment)); 16668 16669 /* Test across comments and newlines */ 16670 EXPECT_EQ("int a = 5;\n" 16671 "\n" 16672 "/* block comment */\n" 16673 "int oneTwoThree = 123;", 16674 format("int a = 5;\n" 16675 "\n" 16676 "/* block comment */\n" 16677 "int oneTwoThree=123;", 16678 Alignment)); 16679 16680 EXPECT_EQ("int a = 5;\n" 16681 "\n" 16682 "// line comment\n" 16683 "int oneTwoThree = 123;", 16684 format("int a = 5;\n" 16685 "\n" 16686 "// line comment\n" 16687 "int oneTwoThree=123;", 16688 Alignment)); 16689 } 16690 16691 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) { 16692 FormatStyle Alignment = getLLVMStyle(); 16693 Alignment.AlignConsecutiveMacros.Enabled = true; 16694 Alignment.AlignConsecutiveAssignments.Enabled = true; 16695 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true; 16696 Alignment.AlignConsecutiveAssignments.AcrossComments = true; 16697 verifyFormat("int a = 5;\n" 16698 "int oneTwoThree = 123;", 16699 Alignment); 16700 verifyFormat("int a = method();\n" 16701 "int oneTwoThree = 133;", 16702 Alignment); 16703 verifyFormat("a &= 5;\n" 16704 "bcd *= 5;\n" 16705 "ghtyf += 5;\n" 16706 "dvfvdb -= 5;\n" 16707 "a /= 5;\n" 16708 "vdsvsv %= 5;\n" 16709 "sfdbddfbdfbb ^= 5;\n" 16710 "dvsdsv |= 5;\n" 16711 "int dsvvdvsdvvv = 123;", 16712 Alignment); 16713 verifyFormat("int i = 1, j = 10;\n" 16714 "something = 2000;", 16715 Alignment); 16716 verifyFormat("something = 2000;\n" 16717 "int i = 1, j = 10;\n", 16718 Alignment); 16719 verifyFormat("something = 2000;\n" 16720 "another = 911;\n" 16721 "int i = 1, j = 10;\n" 16722 "oneMore = 1;\n" 16723 "i = 2;", 16724 Alignment); 16725 verifyFormat("int a = 5;\n" 16726 "int one = 1;\n" 16727 "method();\n" 16728 "int oneTwoThree = 123;\n" 16729 "int oneTwo = 12;", 16730 Alignment); 16731 verifyFormat("int oneTwoThree = 123;\n" 16732 "int oneTwo = 12;\n" 16733 "method();\n", 16734 Alignment); 16735 verifyFormat("int oneTwoThree = 123; // comment\n" 16736 "int oneTwo = 12; // comment", 16737 Alignment); 16738 16739 // Bug 25167 16740 /* Uncomment when fixed 16741 verifyFormat("#if A\n" 16742 "#else\n" 16743 "int aaaaaaaa = 12;\n" 16744 "#endif\n" 16745 "#if B\n" 16746 "#else\n" 16747 "int a = 12;\n" 16748 "#endif\n", 16749 Alignment); 16750 verifyFormat("enum foo {\n" 16751 "#if A\n" 16752 "#else\n" 16753 " aaaaaaaa = 12;\n" 16754 "#endif\n" 16755 "#if B\n" 16756 "#else\n" 16757 " a = 12;\n" 16758 "#endif\n" 16759 "};\n", 16760 Alignment); 16761 */ 16762 16763 Alignment.MaxEmptyLinesToKeep = 10; 16764 /* Test alignment across empty lines */ 16765 EXPECT_EQ("int a = 5;\n" 16766 "\n" 16767 "int oneTwoThree = 123;", 16768 format("int a = 5;\n" 16769 "\n" 16770 "int oneTwoThree= 123;", 16771 Alignment)); 16772 EXPECT_EQ("int a = 5;\n" 16773 "int one = 1;\n" 16774 "\n" 16775 "int oneTwoThree = 123;", 16776 format("int a = 5;\n" 16777 "int one = 1;\n" 16778 "\n" 16779 "int oneTwoThree = 123;", 16780 Alignment)); 16781 EXPECT_EQ("int a = 5;\n" 16782 "int one = 1;\n" 16783 "\n" 16784 "int oneTwoThree = 123;\n" 16785 "int oneTwo = 12;", 16786 format("int a = 5;\n" 16787 "int one = 1;\n" 16788 "\n" 16789 "int oneTwoThree = 123;\n" 16790 "int oneTwo = 12;", 16791 Alignment)); 16792 16793 /* Test across comments */ 16794 EXPECT_EQ("int a = 5;\n" 16795 "/* block comment */\n" 16796 "int oneTwoThree = 123;", 16797 format("int a = 5;\n" 16798 "/* block comment */\n" 16799 "int oneTwoThree=123;", 16800 Alignment)); 16801 16802 EXPECT_EQ("int a = 5;\n" 16803 "// line comment\n" 16804 "int oneTwoThree = 123;", 16805 format("int a = 5;\n" 16806 "// line comment\n" 16807 "int oneTwoThree=123;", 16808 Alignment)); 16809 16810 /* Test across comments and newlines */ 16811 EXPECT_EQ("int a = 5;\n" 16812 "\n" 16813 "/* block comment */\n" 16814 "int oneTwoThree = 123;", 16815 format("int a = 5;\n" 16816 "\n" 16817 "/* block comment */\n" 16818 "int oneTwoThree=123;", 16819 Alignment)); 16820 16821 EXPECT_EQ("int a = 5;\n" 16822 "\n" 16823 "// line comment\n" 16824 "int oneTwoThree = 123;", 16825 format("int a = 5;\n" 16826 "\n" 16827 "// line comment\n" 16828 "int oneTwoThree=123;", 16829 Alignment)); 16830 16831 EXPECT_EQ("int a = 5;\n" 16832 "//\n" 16833 "// multi-line line comment\n" 16834 "//\n" 16835 "int oneTwoThree = 123;", 16836 format("int a = 5;\n" 16837 "//\n" 16838 "// multi-line line comment\n" 16839 "//\n" 16840 "int oneTwoThree=123;", 16841 Alignment)); 16842 16843 EXPECT_EQ("int a = 5;\n" 16844 "/*\n" 16845 " * multi-line block comment\n" 16846 " */\n" 16847 "int oneTwoThree = 123;", 16848 format("int a = 5;\n" 16849 "/*\n" 16850 " * multi-line block comment\n" 16851 " */\n" 16852 "int oneTwoThree=123;", 16853 Alignment)); 16854 16855 EXPECT_EQ("int a = 5;\n" 16856 "\n" 16857 "/* block comment */\n" 16858 "\n" 16859 "\n" 16860 "\n" 16861 "int oneTwoThree = 123;", 16862 format("int a = 5;\n" 16863 "\n" 16864 "/* block comment */\n" 16865 "\n" 16866 "\n" 16867 "\n" 16868 "int oneTwoThree=123;", 16869 Alignment)); 16870 16871 EXPECT_EQ("int a = 5;\n" 16872 "\n" 16873 "// line comment\n" 16874 "\n" 16875 "\n" 16876 "\n" 16877 "int oneTwoThree = 123;", 16878 format("int a = 5;\n" 16879 "\n" 16880 "// line comment\n" 16881 "\n" 16882 "\n" 16883 "\n" 16884 "int oneTwoThree=123;", 16885 Alignment)); 16886 16887 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 16888 verifyFormat("#define A \\\n" 16889 " int aaaa = 12; \\\n" 16890 " int b = 23; \\\n" 16891 " int ccc = 234; \\\n" 16892 " int dddddddddd = 2345;", 16893 Alignment); 16894 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 16895 verifyFormat("#define A \\\n" 16896 " int aaaa = 12; \\\n" 16897 " int b = 23; \\\n" 16898 " int ccc = 234; \\\n" 16899 " int dddddddddd = 2345;", 16900 Alignment); 16901 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 16902 verifyFormat("#define A " 16903 " \\\n" 16904 " int aaaa = 12; " 16905 " \\\n" 16906 " int b = 23; " 16907 " \\\n" 16908 " int ccc = 234; " 16909 " \\\n" 16910 " int dddddddddd = 2345;", 16911 Alignment); 16912 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 16913 "k = 4, int l = 5,\n" 16914 " int m = 6) {\n" 16915 " int j = 10;\n" 16916 " otherThing = 1;\n" 16917 "}", 16918 Alignment); 16919 verifyFormat("void SomeFunction(int parameter = 0) {\n" 16920 " int i = 1;\n" 16921 " int j = 2;\n" 16922 " int big = 10000;\n" 16923 "}", 16924 Alignment); 16925 verifyFormat("class C {\n" 16926 "public:\n" 16927 " int i = 1;\n" 16928 " virtual void f() = 0;\n" 16929 "};", 16930 Alignment); 16931 verifyFormat("int i = 1;\n" 16932 "if (SomeType t = getSomething()) {\n" 16933 "}\n" 16934 "int j = 2;\n" 16935 "int big = 10000;", 16936 Alignment); 16937 verifyFormat("int j = 7;\n" 16938 "for (int k = 0; k < N; ++k) {\n" 16939 "}\n" 16940 "int j = 2;\n" 16941 "int big = 10000;\n" 16942 "}", 16943 Alignment); 16944 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 16945 verifyFormat("int i = 1;\n" 16946 "LooooooooooongType loooooooooooooooooooooongVariable\n" 16947 " = someLooooooooooooooooongFunction();\n" 16948 "int j = 2;", 16949 Alignment); 16950 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 16951 verifyFormat("int i = 1;\n" 16952 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 16953 " someLooooooooooooooooongFunction();\n" 16954 "int j = 2;", 16955 Alignment); 16956 16957 verifyFormat("auto lambda = []() {\n" 16958 " auto i = 0;\n" 16959 " return 0;\n" 16960 "};\n" 16961 "int i = 0;\n" 16962 "auto v = type{\n" 16963 " i = 1, //\n" 16964 " (i = 2), //\n" 16965 " i = 3 //\n" 16966 "};", 16967 Alignment); 16968 16969 verifyFormat( 16970 "int i = 1;\n" 16971 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 16972 " loooooooooooooooooooooongParameterB);\n" 16973 "int j = 2;", 16974 Alignment); 16975 16976 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n" 16977 " typename B = very_long_type_name_1,\n" 16978 " typename T_2 = very_long_type_name_2>\n" 16979 "auto foo() {}\n", 16980 Alignment); 16981 verifyFormat("int a, b = 1;\n" 16982 "int c = 2;\n" 16983 "int dd = 3;\n", 16984 Alignment); 16985 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 16986 "float b[1][] = {{3.f}};\n", 16987 Alignment); 16988 verifyFormat("for (int i = 0; i < 1; i++)\n" 16989 " int x = 1;\n", 16990 Alignment); 16991 verifyFormat("for (i = 0; i < 1; i++)\n" 16992 " x = 1;\n" 16993 "y = 1;\n", 16994 Alignment); 16995 16996 Alignment.ReflowComments = true; 16997 Alignment.ColumnLimit = 50; 16998 EXPECT_EQ("int x = 0;\n" 16999 "int yy = 1; /// specificlennospace\n" 17000 "int zzz = 2;\n", 17001 format("int x = 0;\n" 17002 "int yy = 1; ///specificlennospace\n" 17003 "int zzz = 2;\n", 17004 Alignment)); 17005 } 17006 17007 TEST_F(FormatTest, AlignCompoundAssignments) { 17008 FormatStyle Alignment = getLLVMStyle(); 17009 Alignment.AlignConsecutiveAssignments.Enabled = true; 17010 Alignment.AlignConsecutiveAssignments.AlignCompound = true; 17011 Alignment.AlignConsecutiveAssignments.PadOperators = false; 17012 verifyFormat("sfdbddfbdfbb = 5;\n" 17013 "dvsdsv = 5;\n" 17014 "int dsvvdvsdvvv = 123;", 17015 Alignment); 17016 verifyFormat("sfdbddfbdfbb ^= 5;\n" 17017 "dvsdsv |= 5;\n" 17018 "int dsvvdvsdvvv = 123;", 17019 Alignment); 17020 verifyFormat("sfdbddfbdfbb ^= 5;\n" 17021 "dvsdsv <<= 5;\n" 17022 "int dsvvdvsdvvv = 123;", 17023 Alignment); 17024 // Test that `<=` is not treated as a compound assignment. 17025 verifyFormat("aa &= 5;\n" 17026 "b <= 10;\n" 17027 "c = 15;", 17028 Alignment); 17029 Alignment.AlignConsecutiveAssignments.PadOperators = true; 17030 verifyFormat("sfdbddfbdfbb = 5;\n" 17031 "dvsdsv = 5;\n" 17032 "int dsvvdvsdvvv = 123;", 17033 Alignment); 17034 verifyFormat("sfdbddfbdfbb ^= 5;\n" 17035 "dvsdsv |= 5;\n" 17036 "int dsvvdvsdvvv = 123;", 17037 Alignment); 17038 verifyFormat("sfdbddfbdfbb ^= 5;\n" 17039 "dvsdsv <<= 5;\n" 17040 "int dsvvdvsdvvv = 123;", 17041 Alignment); 17042 EXPECT_EQ("a += 5;\n" 17043 "one = 1;\n" 17044 "\n" 17045 "oneTwoThree = 123;\n", 17046 format("a += 5;\n" 17047 "one = 1;\n" 17048 "\n" 17049 "oneTwoThree = 123;\n", 17050 Alignment)); 17051 EXPECT_EQ("a += 5;\n" 17052 "one = 1;\n" 17053 "//\n" 17054 "oneTwoThree = 123;\n", 17055 format("a += 5;\n" 17056 "one = 1;\n" 17057 "//\n" 17058 "oneTwoThree = 123;\n", 17059 Alignment)); 17060 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true; 17061 EXPECT_EQ("a += 5;\n" 17062 "one = 1;\n" 17063 "\n" 17064 "oneTwoThree = 123;\n", 17065 format("a += 5;\n" 17066 "one = 1;\n" 17067 "\n" 17068 "oneTwoThree = 123;\n", 17069 Alignment)); 17070 EXPECT_EQ("a += 5;\n" 17071 "one = 1;\n" 17072 "//\n" 17073 "oneTwoThree = 123;\n", 17074 format("a += 5;\n" 17075 "one = 1;\n" 17076 "//\n" 17077 "oneTwoThree = 123;\n", 17078 Alignment)); 17079 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = false; 17080 Alignment.AlignConsecutiveAssignments.AcrossComments = true; 17081 EXPECT_EQ("a += 5;\n" 17082 "one = 1;\n" 17083 "\n" 17084 "oneTwoThree = 123;\n", 17085 format("a += 5;\n" 17086 "one = 1;\n" 17087 "\n" 17088 "oneTwoThree = 123;\n", 17089 Alignment)); 17090 EXPECT_EQ("a += 5;\n" 17091 "one = 1;\n" 17092 "//\n" 17093 "oneTwoThree = 123;\n", 17094 format("a += 5;\n" 17095 "one = 1;\n" 17096 "//\n" 17097 "oneTwoThree = 123;\n", 17098 Alignment)); 17099 Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true; 17100 EXPECT_EQ("a += 5;\n" 17101 "one >>= 1;\n" 17102 "\n" 17103 "oneTwoThree = 123;\n", 17104 format("a += 5;\n" 17105 "one >>= 1;\n" 17106 "\n" 17107 "oneTwoThree = 123;\n", 17108 Alignment)); 17109 EXPECT_EQ("a += 5;\n" 17110 "one = 1;\n" 17111 "//\n" 17112 "oneTwoThree <<= 123;\n", 17113 format("a += 5;\n" 17114 "one = 1;\n" 17115 "//\n" 17116 "oneTwoThree <<= 123;\n", 17117 Alignment)); 17118 } 17119 17120 TEST_F(FormatTest, AlignConsecutiveAssignments) { 17121 FormatStyle Alignment = getLLVMStyle(); 17122 Alignment.AlignConsecutiveMacros.Enabled = true; 17123 verifyFormat("int a = 5;\n" 17124 "int oneTwoThree = 123;", 17125 Alignment); 17126 verifyFormat("int a = 5;\n" 17127 "int oneTwoThree = 123;", 17128 Alignment); 17129 17130 Alignment.AlignConsecutiveAssignments.Enabled = true; 17131 verifyFormat("int a = 5;\n" 17132 "int oneTwoThree = 123;", 17133 Alignment); 17134 verifyFormat("int a = method();\n" 17135 "int oneTwoThree = 133;", 17136 Alignment); 17137 verifyFormat("aa <= 5;\n" 17138 "a &= 5;\n" 17139 "bcd *= 5;\n" 17140 "ghtyf += 5;\n" 17141 "dvfvdb -= 5;\n" 17142 "a /= 5;\n" 17143 "vdsvsv %= 5;\n" 17144 "sfdbddfbdfbb ^= 5;\n" 17145 "dvsdsv |= 5;\n" 17146 "int dsvvdvsdvvv = 123;", 17147 Alignment); 17148 verifyFormat("int i = 1, j = 10;\n" 17149 "something = 2000;", 17150 Alignment); 17151 verifyFormat("something = 2000;\n" 17152 "int i = 1, j = 10;\n", 17153 Alignment); 17154 verifyFormat("something = 2000;\n" 17155 "another = 911;\n" 17156 "int i = 1, j = 10;\n" 17157 "oneMore = 1;\n" 17158 "i = 2;", 17159 Alignment); 17160 verifyFormat("int a = 5;\n" 17161 "int one = 1;\n" 17162 "method();\n" 17163 "int oneTwoThree = 123;\n" 17164 "int oneTwo = 12;", 17165 Alignment); 17166 verifyFormat("int oneTwoThree = 123;\n" 17167 "int oneTwo = 12;\n" 17168 "method();\n", 17169 Alignment); 17170 verifyFormat("int oneTwoThree = 123; // comment\n" 17171 "int oneTwo = 12; // comment", 17172 Alignment); 17173 verifyFormat("int f() = default;\n" 17174 "int &operator() = default;\n" 17175 "int &operator=() {", 17176 Alignment); 17177 verifyFormat("int f() = delete;\n" 17178 "int &operator() = delete;\n" 17179 "int &operator=() {", 17180 Alignment); 17181 verifyFormat("int f() = default; // comment\n" 17182 "int &operator() = default; // comment\n" 17183 "int &operator=() {", 17184 Alignment); 17185 verifyFormat("int f() = default;\n" 17186 "int &operator() = default;\n" 17187 "int &operator==() {", 17188 Alignment); 17189 verifyFormat("int f() = default;\n" 17190 "int &operator() = default;\n" 17191 "int &operator<=() {", 17192 Alignment); 17193 verifyFormat("int f() = default;\n" 17194 "int &operator() = default;\n" 17195 "int &operator!=() {", 17196 Alignment); 17197 verifyFormat("int f() = default;\n" 17198 "int &operator() = default;\n" 17199 "int &operator=();", 17200 Alignment); 17201 verifyFormat("int f() = delete;\n" 17202 "int &operator() = delete;\n" 17203 "int &operator=();", 17204 Alignment); 17205 verifyFormat("/* long long padding */ int f() = default;\n" 17206 "int &operator() = default;\n" 17207 "int &operator/**/ =();", 17208 Alignment); 17209 // https://llvm.org/PR33697 17210 FormatStyle AlignmentWithPenalty = getLLVMStyle(); 17211 AlignmentWithPenalty.AlignConsecutiveAssignments.Enabled = true; 17212 AlignmentWithPenalty.PenaltyReturnTypeOnItsOwnLine = 5000; 17213 verifyFormat("class SSSSSSSSSSSSSSSSSSSSSSSSSSSS {\n" 17214 " void f() = delete;\n" 17215 " SSSSSSSSSSSSSSSSSSSSSSSSSSSS &operator=(\n" 17216 " const SSSSSSSSSSSSSSSSSSSSSSSSSSSS &other) = delete;\n" 17217 "};\n", 17218 AlignmentWithPenalty); 17219 17220 // Bug 25167 17221 /* Uncomment when fixed 17222 verifyFormat("#if A\n" 17223 "#else\n" 17224 "int aaaaaaaa = 12;\n" 17225 "#endif\n" 17226 "#if B\n" 17227 "#else\n" 17228 "int a = 12;\n" 17229 "#endif\n", 17230 Alignment); 17231 verifyFormat("enum foo {\n" 17232 "#if A\n" 17233 "#else\n" 17234 " aaaaaaaa = 12;\n" 17235 "#endif\n" 17236 "#if B\n" 17237 "#else\n" 17238 " a = 12;\n" 17239 "#endif\n" 17240 "};\n", 17241 Alignment); 17242 */ 17243 17244 EXPECT_EQ("int a = 5;\n" 17245 "\n" 17246 "int oneTwoThree = 123;", 17247 format("int a = 5;\n" 17248 "\n" 17249 "int oneTwoThree= 123;", 17250 Alignment)); 17251 EXPECT_EQ("int a = 5;\n" 17252 "int one = 1;\n" 17253 "\n" 17254 "int oneTwoThree = 123;", 17255 format("int a = 5;\n" 17256 "int one = 1;\n" 17257 "\n" 17258 "int oneTwoThree = 123;", 17259 Alignment)); 17260 EXPECT_EQ("int a = 5;\n" 17261 "int one = 1;\n" 17262 "\n" 17263 "int oneTwoThree = 123;\n" 17264 "int oneTwo = 12;", 17265 format("int a = 5;\n" 17266 "int one = 1;\n" 17267 "\n" 17268 "int oneTwoThree = 123;\n" 17269 "int oneTwo = 12;", 17270 Alignment)); 17271 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 17272 verifyFormat("#define A \\\n" 17273 " int aaaa = 12; \\\n" 17274 " int b = 23; \\\n" 17275 " int ccc = 234; \\\n" 17276 " int dddddddddd = 2345;", 17277 Alignment); 17278 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 17279 verifyFormat("#define A \\\n" 17280 " int aaaa = 12; \\\n" 17281 " int b = 23; \\\n" 17282 " int ccc = 234; \\\n" 17283 " int dddddddddd = 2345;", 17284 Alignment); 17285 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 17286 verifyFormat("#define A " 17287 " \\\n" 17288 " int aaaa = 12; " 17289 " \\\n" 17290 " int b = 23; " 17291 " \\\n" 17292 " int ccc = 234; " 17293 " \\\n" 17294 " int dddddddddd = 2345;", 17295 Alignment); 17296 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 17297 "k = 4, int l = 5,\n" 17298 " int m = 6) {\n" 17299 " int j = 10;\n" 17300 " otherThing = 1;\n" 17301 "}", 17302 Alignment); 17303 verifyFormat("void SomeFunction(int parameter = 0) {\n" 17304 " int i = 1;\n" 17305 " int j = 2;\n" 17306 " int big = 10000;\n" 17307 "}", 17308 Alignment); 17309 verifyFormat("class C {\n" 17310 "public:\n" 17311 " int i = 1;\n" 17312 " virtual void f() = 0;\n" 17313 "};", 17314 Alignment); 17315 verifyFormat("int i = 1;\n" 17316 "if (SomeType t = getSomething()) {\n" 17317 "}\n" 17318 "int j = 2;\n" 17319 "int big = 10000;", 17320 Alignment); 17321 verifyFormat("int j = 7;\n" 17322 "for (int k = 0; k < N; ++k) {\n" 17323 "}\n" 17324 "int j = 2;\n" 17325 "int big = 10000;\n" 17326 "}", 17327 Alignment); 17328 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 17329 verifyFormat("int i = 1;\n" 17330 "LooooooooooongType loooooooooooooooooooooongVariable\n" 17331 " = someLooooooooooooooooongFunction();\n" 17332 "int j = 2;", 17333 Alignment); 17334 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 17335 verifyFormat("int i = 1;\n" 17336 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 17337 " someLooooooooooooooooongFunction();\n" 17338 "int j = 2;", 17339 Alignment); 17340 17341 verifyFormat("auto lambda = []() {\n" 17342 " auto i = 0;\n" 17343 " return 0;\n" 17344 "};\n" 17345 "int i = 0;\n" 17346 "auto v = type{\n" 17347 " i = 1, //\n" 17348 " (i = 2), //\n" 17349 " i = 3 //\n" 17350 "};", 17351 Alignment); 17352 17353 verifyFormat( 17354 "int i = 1;\n" 17355 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 17356 " loooooooooooooooooooooongParameterB);\n" 17357 "int j = 2;", 17358 Alignment); 17359 17360 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n" 17361 " typename B = very_long_type_name_1,\n" 17362 " typename T_2 = very_long_type_name_2>\n" 17363 "auto foo() {}\n", 17364 Alignment); 17365 verifyFormat("int a, b = 1;\n" 17366 "int c = 2;\n" 17367 "int dd = 3;\n", 17368 Alignment); 17369 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17370 "float b[1][] = {{3.f}};\n", 17371 Alignment); 17372 verifyFormat("for (int i = 0; i < 1; i++)\n" 17373 " int x = 1;\n", 17374 Alignment); 17375 verifyFormat("for (i = 0; i < 1; i++)\n" 17376 " x = 1;\n" 17377 "y = 1;\n", 17378 Alignment); 17379 17380 EXPECT_EQ(Alignment.ReflowComments, true); 17381 Alignment.ColumnLimit = 50; 17382 EXPECT_EQ("int x = 0;\n" 17383 "int yy = 1; /// specificlennospace\n" 17384 "int zzz = 2;\n", 17385 format("int x = 0;\n" 17386 "int yy = 1; ///specificlennospace\n" 17387 "int zzz = 2;\n", 17388 Alignment)); 17389 17390 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17391 "auto b = [] {\n" 17392 " f();\n" 17393 " return;\n" 17394 "};", 17395 Alignment); 17396 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17397 "auto b = g([] {\n" 17398 " f();\n" 17399 " return;\n" 17400 "});", 17401 Alignment); 17402 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17403 "auto b = g(param, [] {\n" 17404 " f();\n" 17405 " return;\n" 17406 "});", 17407 Alignment); 17408 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17409 "auto b = [] {\n" 17410 " if (condition) {\n" 17411 " return;\n" 17412 " }\n" 17413 "};", 17414 Alignment); 17415 17416 verifyFormat("auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 17417 " ccc ? aaaaa : bbbbb,\n" 17418 " dddddddddddddddddddddddddd);", 17419 Alignment); 17420 // FIXME: https://llvm.org/PR53497 17421 // verifyFormat("auto aaaaaaaaaaaa = f();\n" 17422 // "auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 17423 // " ccc ? aaaaa : bbbbb,\n" 17424 // " dddddddddddddddddddddddddd);", 17425 // Alignment); 17426 17427 // Confirm proper handling of AlignConsecutiveAssignments with 17428 // BinPackArguments. 17429 // See https://llvm.org/PR55360 17430 Alignment = getLLVMStyleWithColumns(50); 17431 Alignment.AlignConsecutiveAssignments.Enabled = true; 17432 Alignment.BinPackArguments = false; 17433 verifyFormat("int a_long_name = 1;\n" 17434 "auto b = B({a_long_name, a_long_name},\n" 17435 " {a_longer_name_for_wrap,\n" 17436 " a_longer_name_for_wrap});", 17437 Alignment); 17438 verifyFormat("int a_long_name = 1;\n" 17439 "auto b = B{{a_long_name, a_long_name},\n" 17440 " {a_longer_name_for_wrap,\n" 17441 " a_longer_name_for_wrap}};", 17442 Alignment); 17443 } 17444 17445 TEST_F(FormatTest, AlignConsecutiveBitFields) { 17446 FormatStyle Alignment = getLLVMStyle(); 17447 Alignment.AlignConsecutiveBitFields.Enabled = true; 17448 verifyFormat("int const a : 5;\n" 17449 "int oneTwoThree : 23;", 17450 Alignment); 17451 17452 // Initializers are allowed starting with c++2a 17453 verifyFormat("int const a : 5 = 1;\n" 17454 "int oneTwoThree : 23 = 0;", 17455 Alignment); 17456 17457 Alignment.AlignConsecutiveDeclarations.Enabled = true; 17458 verifyFormat("int const a : 5;\n" 17459 "int oneTwoThree : 23;", 17460 Alignment); 17461 17462 verifyFormat("int const a : 5; // comment\n" 17463 "int oneTwoThree : 23; // comment", 17464 Alignment); 17465 17466 verifyFormat("int const a : 5 = 1;\n" 17467 "int oneTwoThree : 23 = 0;", 17468 Alignment); 17469 17470 Alignment.AlignConsecutiveAssignments.Enabled = true; 17471 verifyFormat("int const a : 5 = 1;\n" 17472 "int oneTwoThree : 23 = 0;", 17473 Alignment); 17474 verifyFormat("int const a : 5 = {1};\n" 17475 "int oneTwoThree : 23 = 0;", 17476 Alignment); 17477 17478 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None; 17479 verifyFormat("int const a :5;\n" 17480 "int oneTwoThree:23;", 17481 Alignment); 17482 17483 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before; 17484 verifyFormat("int const a :5;\n" 17485 "int oneTwoThree :23;", 17486 Alignment); 17487 17488 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After; 17489 verifyFormat("int const a : 5;\n" 17490 "int oneTwoThree: 23;", 17491 Alignment); 17492 17493 // Known limitations: ':' is only recognized as a bitfield colon when 17494 // followed by a number. 17495 /* 17496 verifyFormat("int oneTwoThree : SOME_CONSTANT;\n" 17497 "int a : 5;", 17498 Alignment); 17499 */ 17500 } 17501 17502 TEST_F(FormatTest, AlignConsecutiveDeclarations) { 17503 FormatStyle Alignment = getLLVMStyle(); 17504 Alignment.AlignConsecutiveMacros.Enabled = true; 17505 Alignment.PointerAlignment = FormatStyle::PAS_Right; 17506 verifyFormat("float const a = 5;\n" 17507 "int oneTwoThree = 123;", 17508 Alignment); 17509 verifyFormat("int a = 5;\n" 17510 "float const oneTwoThree = 123;", 17511 Alignment); 17512 17513 Alignment.AlignConsecutiveDeclarations.Enabled = true; 17514 verifyFormat("float const a = 5;\n" 17515 "int oneTwoThree = 123;", 17516 Alignment); 17517 verifyFormat("int a = method();\n" 17518 "float const oneTwoThree = 133;", 17519 Alignment); 17520 verifyFormat("int i = 1, j = 10;\n" 17521 "something = 2000;", 17522 Alignment); 17523 verifyFormat("something = 2000;\n" 17524 "int i = 1, j = 10;\n", 17525 Alignment); 17526 verifyFormat("float something = 2000;\n" 17527 "double another = 911;\n" 17528 "int i = 1, j = 10;\n" 17529 "const int *oneMore = 1;\n" 17530 "unsigned i = 2;", 17531 Alignment); 17532 verifyFormat("float a = 5;\n" 17533 "int one = 1;\n" 17534 "method();\n" 17535 "const double oneTwoThree = 123;\n" 17536 "const unsigned int oneTwo = 12;", 17537 Alignment); 17538 verifyFormat("int oneTwoThree{0}; // comment\n" 17539 "unsigned oneTwo; // comment", 17540 Alignment); 17541 verifyFormat("unsigned int *a;\n" 17542 "int *b;\n" 17543 "unsigned int Const *c;\n" 17544 "unsigned int const *d;\n" 17545 "unsigned int Const &e;\n" 17546 "unsigned int const &f;", 17547 Alignment); 17548 verifyFormat("Const unsigned int *c;\n" 17549 "const unsigned int *d;\n" 17550 "Const unsigned int &e;\n" 17551 "const unsigned int &f;\n" 17552 "const unsigned g;\n" 17553 "Const unsigned h;", 17554 Alignment); 17555 EXPECT_EQ("float const a = 5;\n" 17556 "\n" 17557 "int oneTwoThree = 123;", 17558 format("float const a = 5;\n" 17559 "\n" 17560 "int oneTwoThree= 123;", 17561 Alignment)); 17562 EXPECT_EQ("float a = 5;\n" 17563 "int one = 1;\n" 17564 "\n" 17565 "unsigned oneTwoThree = 123;", 17566 format("float a = 5;\n" 17567 "int one = 1;\n" 17568 "\n" 17569 "unsigned oneTwoThree = 123;", 17570 Alignment)); 17571 EXPECT_EQ("float a = 5;\n" 17572 "int one = 1;\n" 17573 "\n" 17574 "unsigned oneTwoThree = 123;\n" 17575 "int oneTwo = 12;", 17576 format("float a = 5;\n" 17577 "int one = 1;\n" 17578 "\n" 17579 "unsigned oneTwoThree = 123;\n" 17580 "int oneTwo = 12;", 17581 Alignment)); 17582 // Function prototype alignment 17583 verifyFormat("int a();\n" 17584 "double b();", 17585 Alignment); 17586 verifyFormat("int a(int x);\n" 17587 "double b();", 17588 Alignment); 17589 unsigned OldColumnLimit = Alignment.ColumnLimit; 17590 // We need to set ColumnLimit to zero, in order to stress nested alignments, 17591 // otherwise the function parameters will be re-flowed onto a single line. 17592 Alignment.ColumnLimit = 0; 17593 EXPECT_EQ("int a(int x,\n" 17594 " float y);\n" 17595 "double b(int x,\n" 17596 " double y);", 17597 format("int a(int x,\n" 17598 " float y);\n" 17599 "double b(int x,\n" 17600 " double y);", 17601 Alignment)); 17602 // This ensures that function parameters of function declarations are 17603 // correctly indented when their owning functions are indented. 17604 // The failure case here is for 'double y' to not be indented enough. 17605 EXPECT_EQ("double a(int x);\n" 17606 "int b(int y,\n" 17607 " double z);", 17608 format("double a(int x);\n" 17609 "int b(int y,\n" 17610 " double z);", 17611 Alignment)); 17612 // Set ColumnLimit low so that we induce wrapping immediately after 17613 // the function name and opening paren. 17614 Alignment.ColumnLimit = 13; 17615 verifyFormat("int function(\n" 17616 " int x,\n" 17617 " bool y);", 17618 Alignment); 17619 Alignment.ColumnLimit = OldColumnLimit; 17620 // Ensure function pointers don't screw up recursive alignment 17621 verifyFormat("int a(int x, void (*fp)(int y));\n" 17622 "double b();", 17623 Alignment); 17624 Alignment.AlignConsecutiveAssignments.Enabled = true; 17625 // Ensure recursive alignment is broken by function braces, so that the 17626 // "a = 1" does not align with subsequent assignments inside the function 17627 // body. 17628 verifyFormat("int func(int a = 1) {\n" 17629 " int b = 2;\n" 17630 " int cc = 3;\n" 17631 "}", 17632 Alignment); 17633 verifyFormat("float something = 2000;\n" 17634 "double another = 911;\n" 17635 "int i = 1, j = 10;\n" 17636 "const int *oneMore = 1;\n" 17637 "unsigned i = 2;", 17638 Alignment); 17639 verifyFormat("int oneTwoThree = {0}; // comment\n" 17640 "unsigned oneTwo = 0; // comment", 17641 Alignment); 17642 // Make sure that scope is correctly tracked, in the absence of braces 17643 verifyFormat("for (int i = 0; i < n; i++)\n" 17644 " j = i;\n" 17645 "double x = 1;\n", 17646 Alignment); 17647 verifyFormat("if (int i = 0)\n" 17648 " j = i;\n" 17649 "double x = 1;\n", 17650 Alignment); 17651 // Ensure operator[] and operator() are comprehended 17652 verifyFormat("struct test {\n" 17653 " long long int foo();\n" 17654 " int operator[](int a);\n" 17655 " double bar();\n" 17656 "};\n", 17657 Alignment); 17658 verifyFormat("struct test {\n" 17659 " long long int foo();\n" 17660 " int operator()(int a);\n" 17661 " double bar();\n" 17662 "};\n", 17663 Alignment); 17664 // http://llvm.org/PR52914 17665 verifyFormat("char *a[] = {\"a\", // comment\n" 17666 " \"bb\"};\n" 17667 "int bbbbbbb = 0;", 17668 Alignment); 17669 17670 // PAS_Right 17671 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17672 " int const i = 1;\n" 17673 " int *j = 2;\n" 17674 " int big = 10000;\n" 17675 "\n" 17676 " unsigned oneTwoThree = 123;\n" 17677 " int oneTwo = 12;\n" 17678 " method();\n" 17679 " float k = 2;\n" 17680 " int ll = 10000;\n" 17681 "}", 17682 format("void SomeFunction(int parameter= 0) {\n" 17683 " int const i= 1;\n" 17684 " int *j=2;\n" 17685 " int big = 10000;\n" 17686 "\n" 17687 "unsigned oneTwoThree =123;\n" 17688 "int oneTwo = 12;\n" 17689 " method();\n" 17690 "float k= 2;\n" 17691 "int ll=10000;\n" 17692 "}", 17693 Alignment)); 17694 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17695 " int const i = 1;\n" 17696 " int **j = 2, ***k;\n" 17697 " int &k = i;\n" 17698 " int &&l = i + j;\n" 17699 " int big = 10000;\n" 17700 "\n" 17701 " unsigned oneTwoThree = 123;\n" 17702 " int oneTwo = 12;\n" 17703 " method();\n" 17704 " float k = 2;\n" 17705 " int ll = 10000;\n" 17706 "}", 17707 format("void SomeFunction(int parameter= 0) {\n" 17708 " int const i= 1;\n" 17709 " int **j=2,***k;\n" 17710 "int &k=i;\n" 17711 "int &&l=i+j;\n" 17712 " int big = 10000;\n" 17713 "\n" 17714 "unsigned oneTwoThree =123;\n" 17715 "int oneTwo = 12;\n" 17716 " method();\n" 17717 "float k= 2;\n" 17718 "int ll=10000;\n" 17719 "}", 17720 Alignment)); 17721 // variables are aligned at their name, pointers are at the right most 17722 // position 17723 verifyFormat("int *a;\n" 17724 "int **b;\n" 17725 "int ***c;\n" 17726 "int foobar;\n", 17727 Alignment); 17728 17729 // PAS_Left 17730 FormatStyle AlignmentLeft = Alignment; 17731 AlignmentLeft.PointerAlignment = FormatStyle::PAS_Left; 17732 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17733 " int const i = 1;\n" 17734 " int* j = 2;\n" 17735 " int big = 10000;\n" 17736 "\n" 17737 " unsigned oneTwoThree = 123;\n" 17738 " int oneTwo = 12;\n" 17739 " method();\n" 17740 " float k = 2;\n" 17741 " int ll = 10000;\n" 17742 "}", 17743 format("void SomeFunction(int parameter= 0) {\n" 17744 " int const i= 1;\n" 17745 " int *j=2;\n" 17746 " int big = 10000;\n" 17747 "\n" 17748 "unsigned oneTwoThree =123;\n" 17749 "int oneTwo = 12;\n" 17750 " method();\n" 17751 "float k= 2;\n" 17752 "int ll=10000;\n" 17753 "}", 17754 AlignmentLeft)); 17755 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17756 " int const i = 1;\n" 17757 " int** j = 2;\n" 17758 " int& k = i;\n" 17759 " int&& l = i + j;\n" 17760 " int big = 10000;\n" 17761 "\n" 17762 " unsigned oneTwoThree = 123;\n" 17763 " int oneTwo = 12;\n" 17764 " method();\n" 17765 " float k = 2;\n" 17766 " int ll = 10000;\n" 17767 "}", 17768 format("void SomeFunction(int parameter= 0) {\n" 17769 " int const i= 1;\n" 17770 " int **j=2;\n" 17771 "int &k=i;\n" 17772 "int &&l=i+j;\n" 17773 " int big = 10000;\n" 17774 "\n" 17775 "unsigned oneTwoThree =123;\n" 17776 "int oneTwo = 12;\n" 17777 " method();\n" 17778 "float k= 2;\n" 17779 "int ll=10000;\n" 17780 "}", 17781 AlignmentLeft)); 17782 // variables are aligned at their name, pointers are at the left most position 17783 verifyFormat("int* a;\n" 17784 "int** b;\n" 17785 "int*** c;\n" 17786 "int foobar;\n", 17787 AlignmentLeft); 17788 17789 // PAS_Middle 17790 FormatStyle AlignmentMiddle = Alignment; 17791 AlignmentMiddle.PointerAlignment = FormatStyle::PAS_Middle; 17792 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17793 " int const i = 1;\n" 17794 " int * j = 2;\n" 17795 " int big = 10000;\n" 17796 "\n" 17797 " unsigned oneTwoThree = 123;\n" 17798 " int oneTwo = 12;\n" 17799 " method();\n" 17800 " float k = 2;\n" 17801 " int ll = 10000;\n" 17802 "}", 17803 format("void SomeFunction(int parameter= 0) {\n" 17804 " int const i= 1;\n" 17805 " int *j=2;\n" 17806 " int big = 10000;\n" 17807 "\n" 17808 "unsigned oneTwoThree =123;\n" 17809 "int oneTwo = 12;\n" 17810 " method();\n" 17811 "float k= 2;\n" 17812 "int ll=10000;\n" 17813 "}", 17814 AlignmentMiddle)); 17815 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17816 " int const i = 1;\n" 17817 " int ** j = 2, ***k;\n" 17818 " int & k = i;\n" 17819 " int && l = i + j;\n" 17820 " int big = 10000;\n" 17821 "\n" 17822 " unsigned oneTwoThree = 123;\n" 17823 " int oneTwo = 12;\n" 17824 " method();\n" 17825 " float k = 2;\n" 17826 " int ll = 10000;\n" 17827 "}", 17828 format("void SomeFunction(int parameter= 0) {\n" 17829 " int const i= 1;\n" 17830 " int **j=2,***k;\n" 17831 "int &k=i;\n" 17832 "int &&l=i+j;\n" 17833 " int big = 10000;\n" 17834 "\n" 17835 "unsigned oneTwoThree =123;\n" 17836 "int oneTwo = 12;\n" 17837 " method();\n" 17838 "float k= 2;\n" 17839 "int ll=10000;\n" 17840 "}", 17841 AlignmentMiddle)); 17842 // variables are aligned at their name, pointers are in the middle 17843 verifyFormat("int * a;\n" 17844 "int * b;\n" 17845 "int *** c;\n" 17846 "int foobar;\n", 17847 AlignmentMiddle); 17848 17849 Alignment.AlignConsecutiveAssignments.Enabled = false; 17850 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 17851 verifyFormat("#define A \\\n" 17852 " int aaaa = 12; \\\n" 17853 " float b = 23; \\\n" 17854 " const int ccc = 234; \\\n" 17855 " unsigned dddddddddd = 2345;", 17856 Alignment); 17857 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 17858 verifyFormat("#define A \\\n" 17859 " int aaaa = 12; \\\n" 17860 " float b = 23; \\\n" 17861 " const int ccc = 234; \\\n" 17862 " unsigned dddddddddd = 2345;", 17863 Alignment); 17864 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 17865 Alignment.ColumnLimit = 30; 17866 verifyFormat("#define A \\\n" 17867 " int aaaa = 12; \\\n" 17868 " float b = 23; \\\n" 17869 " const int ccc = 234; \\\n" 17870 " int dddddddddd = 2345;", 17871 Alignment); 17872 Alignment.ColumnLimit = 80; 17873 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 17874 "k = 4, int l = 5,\n" 17875 " int m = 6) {\n" 17876 " const int j = 10;\n" 17877 " otherThing = 1;\n" 17878 "}", 17879 Alignment); 17880 verifyFormat("void SomeFunction(int parameter = 0) {\n" 17881 " int const i = 1;\n" 17882 " int *j = 2;\n" 17883 " int big = 10000;\n" 17884 "}", 17885 Alignment); 17886 verifyFormat("class C {\n" 17887 "public:\n" 17888 " int i = 1;\n" 17889 " virtual void f() = 0;\n" 17890 "};", 17891 Alignment); 17892 verifyFormat("float i = 1;\n" 17893 "if (SomeType t = getSomething()) {\n" 17894 "}\n" 17895 "const unsigned j = 2;\n" 17896 "int big = 10000;", 17897 Alignment); 17898 verifyFormat("float j = 7;\n" 17899 "for (int k = 0; k < N; ++k) {\n" 17900 "}\n" 17901 "unsigned j = 2;\n" 17902 "int big = 10000;\n" 17903 "}", 17904 Alignment); 17905 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 17906 verifyFormat("float i = 1;\n" 17907 "LooooooooooongType loooooooooooooooooooooongVariable\n" 17908 " = someLooooooooooooooooongFunction();\n" 17909 "int j = 2;", 17910 Alignment); 17911 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 17912 verifyFormat("int i = 1;\n" 17913 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 17914 " someLooooooooooooooooongFunction();\n" 17915 "int j = 2;", 17916 Alignment); 17917 17918 Alignment.AlignConsecutiveAssignments.Enabled = true; 17919 verifyFormat("auto lambda = []() {\n" 17920 " auto ii = 0;\n" 17921 " float j = 0;\n" 17922 " return 0;\n" 17923 "};\n" 17924 "int i = 0;\n" 17925 "float i2 = 0;\n" 17926 "auto v = type{\n" 17927 " i = 1, //\n" 17928 " (i = 2), //\n" 17929 " i = 3 //\n" 17930 "};", 17931 Alignment); 17932 Alignment.AlignConsecutiveAssignments.Enabled = false; 17933 17934 verifyFormat( 17935 "int i = 1;\n" 17936 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 17937 " loooooooooooooooooooooongParameterB);\n" 17938 "int j = 2;", 17939 Alignment); 17940 17941 // Test interactions with ColumnLimit and AlignConsecutiveAssignments: 17942 // We expect declarations and assignments to align, as long as it doesn't 17943 // exceed the column limit, starting a new alignment sequence whenever it 17944 // happens. 17945 Alignment.AlignConsecutiveAssignments.Enabled = true; 17946 Alignment.ColumnLimit = 30; 17947 verifyFormat("float ii = 1;\n" 17948 "unsigned j = 2;\n" 17949 "int someVerylongVariable = 1;\n" 17950 "AnotherLongType ll = 123456;\n" 17951 "VeryVeryLongType k = 2;\n" 17952 "int myvar = 1;", 17953 Alignment); 17954 Alignment.ColumnLimit = 80; 17955 Alignment.AlignConsecutiveAssignments.Enabled = false; 17956 17957 verifyFormat( 17958 "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n" 17959 " typename LongType, typename B>\n" 17960 "auto foo() {}\n", 17961 Alignment); 17962 verifyFormat("float a, b = 1;\n" 17963 "int c = 2;\n" 17964 "int dd = 3;\n", 17965 Alignment); 17966 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17967 "float b[1][] = {{3.f}};\n", 17968 Alignment); 17969 Alignment.AlignConsecutiveAssignments.Enabled = true; 17970 verifyFormat("float a, b = 1;\n" 17971 "int c = 2;\n" 17972 "int dd = 3;\n", 17973 Alignment); 17974 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17975 "float b[1][] = {{3.f}};\n", 17976 Alignment); 17977 Alignment.AlignConsecutiveAssignments.Enabled = false; 17978 17979 Alignment.ColumnLimit = 30; 17980 Alignment.BinPackParameters = false; 17981 verifyFormat("void foo(float a,\n" 17982 " float b,\n" 17983 " int c,\n" 17984 " uint32_t *d) {\n" 17985 " int *e = 0;\n" 17986 " float f = 0;\n" 17987 " double g = 0;\n" 17988 "}\n" 17989 "void bar(ino_t a,\n" 17990 " int b,\n" 17991 " uint32_t *c,\n" 17992 " bool d) {}\n", 17993 Alignment); 17994 Alignment.BinPackParameters = true; 17995 Alignment.ColumnLimit = 80; 17996 17997 // Bug 33507 17998 Alignment.PointerAlignment = FormatStyle::PAS_Middle; 17999 verifyFormat( 18000 "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n" 18001 " static const Version verVs2017;\n" 18002 " return true;\n" 18003 "});\n", 18004 Alignment); 18005 Alignment.PointerAlignment = FormatStyle::PAS_Right; 18006 18007 // See llvm.org/PR35641 18008 Alignment.AlignConsecutiveDeclarations.Enabled = true; 18009 verifyFormat("int func() { //\n" 18010 " int b;\n" 18011 " unsigned c;\n" 18012 "}", 18013 Alignment); 18014 18015 // See PR37175 18016 FormatStyle Style = getMozillaStyle(); 18017 Style.AlignConsecutiveDeclarations.Enabled = true; 18018 EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n" 18019 "foo(int a);", 18020 format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style)); 18021 18022 Alignment.PointerAlignment = FormatStyle::PAS_Left; 18023 verifyFormat("unsigned int* a;\n" 18024 "int* b;\n" 18025 "unsigned int Const* c;\n" 18026 "unsigned int const* d;\n" 18027 "unsigned int Const& e;\n" 18028 "unsigned int const& f;", 18029 Alignment); 18030 verifyFormat("Const unsigned int* c;\n" 18031 "const unsigned int* d;\n" 18032 "Const unsigned int& e;\n" 18033 "const unsigned int& f;\n" 18034 "const unsigned g;\n" 18035 "Const unsigned h;", 18036 Alignment); 18037 18038 Alignment.PointerAlignment = FormatStyle::PAS_Middle; 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 // See PR46529 18055 FormatStyle BracedAlign = getLLVMStyle(); 18056 BracedAlign.AlignConsecutiveDeclarations.Enabled = true; 18057 verifyFormat("const auto result{[]() {\n" 18058 " const auto something = 1;\n" 18059 " return 2;\n" 18060 "}};", 18061 BracedAlign); 18062 verifyFormat("int foo{[]() {\n" 18063 " int bar{0};\n" 18064 " return 0;\n" 18065 "}()};", 18066 BracedAlign); 18067 BracedAlign.Cpp11BracedListStyle = false; 18068 verifyFormat("const auto result{ []() {\n" 18069 " const auto something = 1;\n" 18070 " return 2;\n" 18071 "} };", 18072 BracedAlign); 18073 verifyFormat("int foo{ []() {\n" 18074 " int bar{ 0 };\n" 18075 " return 0;\n" 18076 "}() };", 18077 BracedAlign); 18078 } 18079 18080 TEST_F(FormatTest, AlignWithLineBreaks) { 18081 auto Style = getLLVMStyleWithColumns(120); 18082 18083 EXPECT_EQ(Style.AlignConsecutiveAssignments, 18084 FormatStyle::AlignConsecutiveStyle( 18085 {/*Enabled=*/false, /*AcrossEmptyLines=*/false, 18086 /*AcrossComments=*/false, /*AlignCompound=*/false, 18087 /*PadOperators=*/true})); 18088 EXPECT_EQ(Style.AlignConsecutiveDeclarations, 18089 FormatStyle::AlignConsecutiveStyle({})); 18090 verifyFormat("void foo() {\n" 18091 " int myVar = 5;\n" 18092 " double x = 3.14;\n" 18093 " auto str = \"Hello \"\n" 18094 " \"World\";\n" 18095 " auto s = \"Hello \"\n" 18096 " \"Again\";\n" 18097 "}", 18098 Style); 18099 18100 // clang-format off 18101 verifyFormat("void foo() {\n" 18102 " const int capacityBefore = Entries.capacity();\n" 18103 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 18104 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 18105 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 18106 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 18107 "}", 18108 Style); 18109 // clang-format on 18110 18111 Style.AlignConsecutiveAssignments.Enabled = true; 18112 verifyFormat("void foo() {\n" 18113 " int myVar = 5;\n" 18114 " double x = 3.14;\n" 18115 " auto str = \"Hello \"\n" 18116 " \"World\";\n" 18117 " auto s = \"Hello \"\n" 18118 " \"Again\";\n" 18119 "}", 18120 Style); 18121 18122 // clang-format off 18123 verifyFormat("void foo() {\n" 18124 " const int capacityBefore = Entries.capacity();\n" 18125 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 18126 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 18127 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 18128 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 18129 "}", 18130 Style); 18131 // clang-format on 18132 18133 Style.AlignConsecutiveAssignments.Enabled = false; 18134 Style.AlignConsecutiveDeclarations.Enabled = true; 18135 verifyFormat("void foo() {\n" 18136 " int myVar = 5;\n" 18137 " double x = 3.14;\n" 18138 " auto str = \"Hello \"\n" 18139 " \"World\";\n" 18140 " auto s = \"Hello \"\n" 18141 " \"Again\";\n" 18142 "}", 18143 Style); 18144 18145 // clang-format off 18146 verifyFormat("void foo() {\n" 18147 " const int capacityBefore = Entries.capacity();\n" 18148 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 18149 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 18150 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 18151 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 18152 "}", 18153 Style); 18154 // clang-format on 18155 18156 Style.AlignConsecutiveAssignments.Enabled = true; 18157 Style.AlignConsecutiveDeclarations.Enabled = true; 18158 18159 verifyFormat("void foo() {\n" 18160 " int myVar = 5;\n" 18161 " double x = 3.14;\n" 18162 " auto str = \"Hello \"\n" 18163 " \"World\";\n" 18164 " auto s = \"Hello \"\n" 18165 " \"Again\";\n" 18166 "}", 18167 Style); 18168 18169 // clang-format off 18170 verifyFormat("void foo() {\n" 18171 " const int capacityBefore = Entries.capacity();\n" 18172 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 18173 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 18174 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 18175 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 18176 "}", 18177 Style); 18178 // clang-format on 18179 18180 Style = getLLVMStyleWithColumns(20); 18181 Style.AlignConsecutiveAssignments.Enabled = true; 18182 Style.IndentWidth = 4; 18183 18184 verifyFormat("void foo() {\n" 18185 " int i1 = 1;\n" 18186 " int j = 0;\n" 18187 " int k = bar(\n" 18188 " argument1,\n" 18189 " argument2);\n" 18190 "}", 18191 Style); 18192 18193 verifyFormat("unsigned i = 0;\n" 18194 "int a[] = {\n" 18195 " 1234567890,\n" 18196 " -1234567890};", 18197 Style); 18198 18199 Style.ColumnLimit = 120; 18200 18201 // clang-format off 18202 verifyFormat("void SomeFunc() {\n" 18203 " newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 18204 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 18205 " newWatcher.maxAge = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 18206 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 18207 " newWatcher.max = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 18208 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 18209 "}", 18210 Style); 18211 // clang-format on 18212 18213 Style.BinPackArguments = false; 18214 18215 // clang-format off 18216 verifyFormat("void SomeFunc() {\n" 18217 " newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(\n" 18218 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 18219 " newWatcher.maxAge = ToLegacyTimestamp(GetMaxAge(\n" 18220 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 18221 " newWatcher.max = ToLegacyTimestamp(GetMaxAge(\n" 18222 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 18223 "}", 18224 Style); 18225 // clang-format on 18226 } 18227 18228 TEST_F(FormatTest, AlignWithInitializerPeriods) { 18229 auto Style = getLLVMStyleWithColumns(60); 18230 18231 verifyFormat("void foo1(void) {\n" 18232 " BYTE p[1] = 1;\n" 18233 " A B = {.one_foooooooooooooooo = 2,\n" 18234 " .two_fooooooooooooo = 3,\n" 18235 " .three_fooooooooooooo = 4};\n" 18236 " BYTE payload = 2;\n" 18237 "}", 18238 Style); 18239 18240 Style.AlignConsecutiveAssignments.Enabled = true; 18241 Style.AlignConsecutiveDeclarations.Enabled = false; 18242 verifyFormat("void foo2(void) {\n" 18243 " BYTE p[1] = 1;\n" 18244 " A B = {.one_foooooooooooooooo = 2,\n" 18245 " .two_fooooooooooooo = 3,\n" 18246 " .three_fooooooooooooo = 4};\n" 18247 " BYTE payload = 2;\n" 18248 "}", 18249 Style); 18250 18251 Style.AlignConsecutiveAssignments.Enabled = false; 18252 Style.AlignConsecutiveDeclarations.Enabled = true; 18253 verifyFormat("void foo3(void) {\n" 18254 " BYTE p[1] = 1;\n" 18255 " A B = {.one_foooooooooooooooo = 2,\n" 18256 " .two_fooooooooooooo = 3,\n" 18257 " .three_fooooooooooooo = 4};\n" 18258 " BYTE payload = 2;\n" 18259 "}", 18260 Style); 18261 18262 Style.AlignConsecutiveAssignments.Enabled = true; 18263 Style.AlignConsecutiveDeclarations.Enabled = true; 18264 verifyFormat("void foo4(void) {\n" 18265 " BYTE p[1] = 1;\n" 18266 " A B = {.one_foooooooooooooooo = 2,\n" 18267 " .two_fooooooooooooo = 3,\n" 18268 " .three_fooooooooooooo = 4};\n" 18269 " BYTE payload = 2;\n" 18270 "}", 18271 Style); 18272 } 18273 18274 TEST_F(FormatTest, LinuxBraceBreaking) { 18275 FormatStyle LinuxBraceStyle = getLLVMStyle(); 18276 LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux; 18277 verifyFormat("namespace a\n" 18278 "{\n" 18279 "class A\n" 18280 "{\n" 18281 " void f()\n" 18282 " {\n" 18283 " if (true) {\n" 18284 " a();\n" 18285 " b();\n" 18286 " } else {\n" 18287 " a();\n" 18288 " }\n" 18289 " }\n" 18290 " void g() { return; }\n" 18291 "};\n" 18292 "struct B {\n" 18293 " int x;\n" 18294 "};\n" 18295 "} // namespace a\n", 18296 LinuxBraceStyle); 18297 verifyFormat("enum X {\n" 18298 " Y = 0,\n" 18299 "}\n", 18300 LinuxBraceStyle); 18301 verifyFormat("struct S {\n" 18302 " int Type;\n" 18303 " union {\n" 18304 " int x;\n" 18305 " double y;\n" 18306 " } Value;\n" 18307 " class C\n" 18308 " {\n" 18309 " MyFavoriteType Value;\n" 18310 " } Class;\n" 18311 "}\n", 18312 LinuxBraceStyle); 18313 } 18314 18315 TEST_F(FormatTest, MozillaBraceBreaking) { 18316 FormatStyle MozillaBraceStyle = getLLVMStyle(); 18317 MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla; 18318 MozillaBraceStyle.FixNamespaceComments = false; 18319 verifyFormat("namespace a {\n" 18320 "class A\n" 18321 "{\n" 18322 " void f()\n" 18323 " {\n" 18324 " if (true) {\n" 18325 " a();\n" 18326 " b();\n" 18327 " }\n" 18328 " }\n" 18329 " void g() { return; }\n" 18330 "};\n" 18331 "enum E\n" 18332 "{\n" 18333 " A,\n" 18334 " // foo\n" 18335 " B,\n" 18336 " C\n" 18337 "};\n" 18338 "struct B\n" 18339 "{\n" 18340 " int x;\n" 18341 "};\n" 18342 "}\n", 18343 MozillaBraceStyle); 18344 verifyFormat("struct S\n" 18345 "{\n" 18346 " int Type;\n" 18347 " union\n" 18348 " {\n" 18349 " int x;\n" 18350 " double y;\n" 18351 " } Value;\n" 18352 " class C\n" 18353 " {\n" 18354 " MyFavoriteType Value;\n" 18355 " } Class;\n" 18356 "}\n", 18357 MozillaBraceStyle); 18358 } 18359 18360 TEST_F(FormatTest, StroustrupBraceBreaking) { 18361 FormatStyle StroustrupBraceStyle = getLLVMStyle(); 18362 StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 18363 verifyFormat("namespace a {\n" 18364 "class A {\n" 18365 " void f()\n" 18366 " {\n" 18367 " if (true) {\n" 18368 " a();\n" 18369 " b();\n" 18370 " }\n" 18371 " }\n" 18372 " void g() { return; }\n" 18373 "};\n" 18374 "struct B {\n" 18375 " int x;\n" 18376 "};\n" 18377 "} // namespace a\n", 18378 StroustrupBraceStyle); 18379 18380 verifyFormat("void foo()\n" 18381 "{\n" 18382 " if (a) {\n" 18383 " a();\n" 18384 " }\n" 18385 " else {\n" 18386 " b();\n" 18387 " }\n" 18388 "}\n", 18389 StroustrupBraceStyle); 18390 18391 verifyFormat("#ifdef _DEBUG\n" 18392 "int foo(int i = 0)\n" 18393 "#else\n" 18394 "int foo(int i = 5)\n" 18395 "#endif\n" 18396 "{\n" 18397 " return i;\n" 18398 "}", 18399 StroustrupBraceStyle); 18400 18401 verifyFormat("void foo() {}\n" 18402 "void bar()\n" 18403 "#ifdef _DEBUG\n" 18404 "{\n" 18405 " foo();\n" 18406 "}\n" 18407 "#else\n" 18408 "{\n" 18409 "}\n" 18410 "#endif", 18411 StroustrupBraceStyle); 18412 18413 verifyFormat("void foobar() { int i = 5; }\n" 18414 "#ifdef _DEBUG\n" 18415 "void bar() {}\n" 18416 "#else\n" 18417 "void bar() { foobar(); }\n" 18418 "#endif", 18419 StroustrupBraceStyle); 18420 } 18421 18422 TEST_F(FormatTest, AllmanBraceBreaking) { 18423 FormatStyle AllmanBraceStyle = getLLVMStyle(); 18424 AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman; 18425 18426 EXPECT_EQ("namespace a\n" 18427 "{\n" 18428 "void f();\n" 18429 "void g();\n" 18430 "} // namespace a\n", 18431 format("namespace a\n" 18432 "{\n" 18433 "void f();\n" 18434 "void g();\n" 18435 "}\n", 18436 AllmanBraceStyle)); 18437 18438 verifyFormat("namespace a\n" 18439 "{\n" 18440 "class A\n" 18441 "{\n" 18442 " void f()\n" 18443 " {\n" 18444 " if (true)\n" 18445 " {\n" 18446 " a();\n" 18447 " b();\n" 18448 " }\n" 18449 " }\n" 18450 " void g() { return; }\n" 18451 "};\n" 18452 "struct B\n" 18453 "{\n" 18454 " int x;\n" 18455 "};\n" 18456 "union C\n" 18457 "{\n" 18458 "};\n" 18459 "} // namespace a", 18460 AllmanBraceStyle); 18461 18462 verifyFormat("void f()\n" 18463 "{\n" 18464 " if (true)\n" 18465 " {\n" 18466 " a();\n" 18467 " }\n" 18468 " else if (false)\n" 18469 " {\n" 18470 " b();\n" 18471 " }\n" 18472 " else\n" 18473 " {\n" 18474 " c();\n" 18475 " }\n" 18476 "}\n", 18477 AllmanBraceStyle); 18478 18479 verifyFormat("void f()\n" 18480 "{\n" 18481 " for (int i = 0; i < 10; ++i)\n" 18482 " {\n" 18483 " a();\n" 18484 " }\n" 18485 " while (false)\n" 18486 " {\n" 18487 " b();\n" 18488 " }\n" 18489 " do\n" 18490 " {\n" 18491 " c();\n" 18492 " } while (false)\n" 18493 "}\n", 18494 AllmanBraceStyle); 18495 18496 verifyFormat("void f(int a)\n" 18497 "{\n" 18498 " switch (a)\n" 18499 " {\n" 18500 " case 0:\n" 18501 " break;\n" 18502 " case 1:\n" 18503 " {\n" 18504 " break;\n" 18505 " }\n" 18506 " case 2:\n" 18507 " {\n" 18508 " }\n" 18509 " break;\n" 18510 " default:\n" 18511 " break;\n" 18512 " }\n" 18513 "}\n", 18514 AllmanBraceStyle); 18515 18516 verifyFormat("enum X\n" 18517 "{\n" 18518 " Y = 0,\n" 18519 "}\n", 18520 AllmanBraceStyle); 18521 verifyFormat("enum X\n" 18522 "{\n" 18523 " Y = 0\n" 18524 "}\n", 18525 AllmanBraceStyle); 18526 18527 verifyFormat("@interface BSApplicationController ()\n" 18528 "{\n" 18529 "@private\n" 18530 " id _extraIvar;\n" 18531 "}\n" 18532 "@end\n", 18533 AllmanBraceStyle); 18534 18535 verifyFormat("#ifdef _DEBUG\n" 18536 "int foo(int i = 0)\n" 18537 "#else\n" 18538 "int foo(int i = 5)\n" 18539 "#endif\n" 18540 "{\n" 18541 " return i;\n" 18542 "}", 18543 AllmanBraceStyle); 18544 18545 verifyFormat("void foo() {}\n" 18546 "void bar()\n" 18547 "#ifdef _DEBUG\n" 18548 "{\n" 18549 " foo();\n" 18550 "}\n" 18551 "#else\n" 18552 "{\n" 18553 "}\n" 18554 "#endif", 18555 AllmanBraceStyle); 18556 18557 verifyFormat("void foobar() { int i = 5; }\n" 18558 "#ifdef _DEBUG\n" 18559 "void bar() {}\n" 18560 "#else\n" 18561 "void bar() { foobar(); }\n" 18562 "#endif", 18563 AllmanBraceStyle); 18564 18565 EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine, 18566 FormatStyle::SLS_All); 18567 18568 verifyFormat("[](int i) { return i + 2; };\n" 18569 "[](int i, int j)\n" 18570 "{\n" 18571 " auto x = i + j;\n" 18572 " auto y = i * j;\n" 18573 " return x ^ y;\n" 18574 "};\n" 18575 "void foo()\n" 18576 "{\n" 18577 " auto shortLambda = [](int i) { return i + 2; };\n" 18578 " auto longLambda = [](int i, int j)\n" 18579 " {\n" 18580 " auto x = i + j;\n" 18581 " auto y = i * j;\n" 18582 " return x ^ y;\n" 18583 " };\n" 18584 "}", 18585 AllmanBraceStyle); 18586 18587 AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 18588 18589 verifyFormat("[](int i)\n" 18590 "{\n" 18591 " return i + 2;\n" 18592 "};\n" 18593 "[](int i, int j)\n" 18594 "{\n" 18595 " auto x = i + j;\n" 18596 " auto y = i * j;\n" 18597 " return x ^ y;\n" 18598 "};\n" 18599 "void foo()\n" 18600 "{\n" 18601 " auto shortLambda = [](int i)\n" 18602 " {\n" 18603 " return i + 2;\n" 18604 " };\n" 18605 " auto longLambda = [](int i, int j)\n" 18606 " {\n" 18607 " auto x = i + j;\n" 18608 " auto y = i * j;\n" 18609 " return x ^ y;\n" 18610 " };\n" 18611 "}", 18612 AllmanBraceStyle); 18613 18614 // Reset 18615 AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All; 18616 18617 // This shouldn't affect ObjC blocks.. 18618 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n" 18619 " // ...\n" 18620 " int i;\n" 18621 "}];", 18622 AllmanBraceStyle); 18623 verifyFormat("void (^block)(void) = ^{\n" 18624 " // ...\n" 18625 " int i;\n" 18626 "};", 18627 AllmanBraceStyle); 18628 // .. or dict literals. 18629 verifyFormat("void f()\n" 18630 "{\n" 18631 " // ...\n" 18632 " [object someMethod:@{@\"a\" : @\"b\"}];\n" 18633 "}", 18634 AllmanBraceStyle); 18635 verifyFormat("void f()\n" 18636 "{\n" 18637 " // ...\n" 18638 " [object someMethod:@{a : @\"b\"}];\n" 18639 "}", 18640 AllmanBraceStyle); 18641 verifyFormat("int f()\n" 18642 "{ // comment\n" 18643 " return 42;\n" 18644 "}", 18645 AllmanBraceStyle); 18646 18647 AllmanBraceStyle.ColumnLimit = 19; 18648 verifyFormat("void f() { int i; }", AllmanBraceStyle); 18649 AllmanBraceStyle.ColumnLimit = 18; 18650 verifyFormat("void f()\n" 18651 "{\n" 18652 " int i;\n" 18653 "}", 18654 AllmanBraceStyle); 18655 AllmanBraceStyle.ColumnLimit = 80; 18656 18657 FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle; 18658 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = 18659 FormatStyle::SIS_WithoutElse; 18660 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true; 18661 verifyFormat("void f(bool b)\n" 18662 "{\n" 18663 " if (b)\n" 18664 " {\n" 18665 " return;\n" 18666 " }\n" 18667 "}\n", 18668 BreakBeforeBraceShortIfs); 18669 verifyFormat("void f(bool b)\n" 18670 "{\n" 18671 " if constexpr (b)\n" 18672 " {\n" 18673 " return;\n" 18674 " }\n" 18675 "}\n", 18676 BreakBeforeBraceShortIfs); 18677 verifyFormat("void f(bool b)\n" 18678 "{\n" 18679 " if CONSTEXPR (b)\n" 18680 " {\n" 18681 " return;\n" 18682 " }\n" 18683 "}\n", 18684 BreakBeforeBraceShortIfs); 18685 verifyFormat("void f(bool b)\n" 18686 "{\n" 18687 " if (b) return;\n" 18688 "}\n", 18689 BreakBeforeBraceShortIfs); 18690 verifyFormat("void f(bool b)\n" 18691 "{\n" 18692 " if constexpr (b) return;\n" 18693 "}\n", 18694 BreakBeforeBraceShortIfs); 18695 verifyFormat("void f(bool b)\n" 18696 "{\n" 18697 " if CONSTEXPR (b) return;\n" 18698 "}\n", 18699 BreakBeforeBraceShortIfs); 18700 verifyFormat("void f(bool b)\n" 18701 "{\n" 18702 " while (b)\n" 18703 " {\n" 18704 " return;\n" 18705 " }\n" 18706 "}\n", 18707 BreakBeforeBraceShortIfs); 18708 } 18709 18710 TEST_F(FormatTest, WhitesmithsBraceBreaking) { 18711 FormatStyle WhitesmithsBraceStyle = getLLVMStyleWithColumns(0); 18712 WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 18713 18714 // Make a few changes to the style for testing purposes 18715 WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine = 18716 FormatStyle::SFS_Empty; 18717 WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 18718 18719 // FIXME: this test case can't decide whether there should be a blank line 18720 // after the ~D() line or not. It adds one if one doesn't exist in the test 18721 // and it removes the line if one exists. 18722 /* 18723 verifyFormat("class A;\n" 18724 "namespace B\n" 18725 " {\n" 18726 "class C;\n" 18727 "// Comment\n" 18728 "class D\n" 18729 " {\n" 18730 "public:\n" 18731 " D();\n" 18732 " ~D() {}\n" 18733 "private:\n" 18734 " enum E\n" 18735 " {\n" 18736 " F\n" 18737 " }\n" 18738 " };\n" 18739 " } // namespace B\n", 18740 WhitesmithsBraceStyle); 18741 */ 18742 18743 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None; 18744 verifyFormat("namespace a\n" 18745 " {\n" 18746 "class A\n" 18747 " {\n" 18748 " void f()\n" 18749 " {\n" 18750 " if (true)\n" 18751 " {\n" 18752 " a();\n" 18753 " b();\n" 18754 " }\n" 18755 " }\n" 18756 " void g()\n" 18757 " {\n" 18758 " return;\n" 18759 " }\n" 18760 " };\n" 18761 "struct B\n" 18762 " {\n" 18763 " int x;\n" 18764 " };\n" 18765 " } // namespace a", 18766 WhitesmithsBraceStyle); 18767 18768 verifyFormat("namespace a\n" 18769 " {\n" 18770 "namespace b\n" 18771 " {\n" 18772 "class A\n" 18773 " {\n" 18774 " void f()\n" 18775 " {\n" 18776 " if (true)\n" 18777 " {\n" 18778 " a();\n" 18779 " b();\n" 18780 " }\n" 18781 " }\n" 18782 " void g()\n" 18783 " {\n" 18784 " return;\n" 18785 " }\n" 18786 " };\n" 18787 "struct B\n" 18788 " {\n" 18789 " int x;\n" 18790 " };\n" 18791 " } // namespace b\n" 18792 " } // namespace a", 18793 WhitesmithsBraceStyle); 18794 18795 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner; 18796 verifyFormat("namespace a\n" 18797 " {\n" 18798 "namespace b\n" 18799 " {\n" 18800 " class A\n" 18801 " {\n" 18802 " void f()\n" 18803 " {\n" 18804 " if (true)\n" 18805 " {\n" 18806 " a();\n" 18807 " b();\n" 18808 " }\n" 18809 " }\n" 18810 " void g()\n" 18811 " {\n" 18812 " return;\n" 18813 " }\n" 18814 " };\n" 18815 " struct B\n" 18816 " {\n" 18817 " int x;\n" 18818 " };\n" 18819 " } // namespace b\n" 18820 " } // namespace a", 18821 WhitesmithsBraceStyle); 18822 18823 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All; 18824 verifyFormat("namespace a\n" 18825 " {\n" 18826 " namespace b\n" 18827 " {\n" 18828 " class A\n" 18829 " {\n" 18830 " void f()\n" 18831 " {\n" 18832 " if (true)\n" 18833 " {\n" 18834 " a();\n" 18835 " b();\n" 18836 " }\n" 18837 " }\n" 18838 " void g()\n" 18839 " {\n" 18840 " return;\n" 18841 " }\n" 18842 " };\n" 18843 " struct B\n" 18844 " {\n" 18845 " int x;\n" 18846 " };\n" 18847 " } // namespace b\n" 18848 " } // namespace a", 18849 WhitesmithsBraceStyle); 18850 18851 verifyFormat("void f()\n" 18852 " {\n" 18853 " if (true)\n" 18854 " {\n" 18855 " a();\n" 18856 " }\n" 18857 " else if (false)\n" 18858 " {\n" 18859 " b();\n" 18860 " }\n" 18861 " else\n" 18862 " {\n" 18863 " c();\n" 18864 " }\n" 18865 " }\n", 18866 WhitesmithsBraceStyle); 18867 18868 verifyFormat("void f()\n" 18869 " {\n" 18870 " for (int i = 0; i < 10; ++i)\n" 18871 " {\n" 18872 " a();\n" 18873 " }\n" 18874 " while (false)\n" 18875 " {\n" 18876 " b();\n" 18877 " }\n" 18878 " do\n" 18879 " {\n" 18880 " c();\n" 18881 " } while (false)\n" 18882 " }\n", 18883 WhitesmithsBraceStyle); 18884 18885 WhitesmithsBraceStyle.IndentCaseLabels = true; 18886 verifyFormat("void switchTest1(int a)\n" 18887 " {\n" 18888 " switch (a)\n" 18889 " {\n" 18890 " case 2:\n" 18891 " {\n" 18892 " }\n" 18893 " break;\n" 18894 " }\n" 18895 " }\n", 18896 WhitesmithsBraceStyle); 18897 18898 verifyFormat("void switchTest2(int a)\n" 18899 " {\n" 18900 " switch (a)\n" 18901 " {\n" 18902 " case 0:\n" 18903 " break;\n" 18904 " case 1:\n" 18905 " {\n" 18906 " break;\n" 18907 " }\n" 18908 " case 2:\n" 18909 " {\n" 18910 " }\n" 18911 " break;\n" 18912 " default:\n" 18913 " break;\n" 18914 " }\n" 18915 " }\n", 18916 WhitesmithsBraceStyle); 18917 18918 verifyFormat("void switchTest3(int a)\n" 18919 " {\n" 18920 " switch (a)\n" 18921 " {\n" 18922 " case 0:\n" 18923 " {\n" 18924 " foo(x);\n" 18925 " }\n" 18926 " break;\n" 18927 " default:\n" 18928 " {\n" 18929 " foo(1);\n" 18930 " }\n" 18931 " break;\n" 18932 " }\n" 18933 " }\n", 18934 WhitesmithsBraceStyle); 18935 18936 WhitesmithsBraceStyle.IndentCaseLabels = false; 18937 18938 verifyFormat("void switchTest4(int a)\n" 18939 " {\n" 18940 " switch (a)\n" 18941 " {\n" 18942 " case 2:\n" 18943 " {\n" 18944 " }\n" 18945 " break;\n" 18946 " }\n" 18947 " }\n", 18948 WhitesmithsBraceStyle); 18949 18950 verifyFormat("void switchTest5(int a)\n" 18951 " {\n" 18952 " switch (a)\n" 18953 " {\n" 18954 " case 0:\n" 18955 " break;\n" 18956 " case 1:\n" 18957 " {\n" 18958 " foo();\n" 18959 " break;\n" 18960 " }\n" 18961 " case 2:\n" 18962 " {\n" 18963 " }\n" 18964 " break;\n" 18965 " default:\n" 18966 " break;\n" 18967 " }\n" 18968 " }\n", 18969 WhitesmithsBraceStyle); 18970 18971 verifyFormat("void switchTest6(int a)\n" 18972 " {\n" 18973 " switch (a)\n" 18974 " {\n" 18975 " case 0:\n" 18976 " {\n" 18977 " foo(x);\n" 18978 " }\n" 18979 " break;\n" 18980 " default:\n" 18981 " {\n" 18982 " foo(1);\n" 18983 " }\n" 18984 " break;\n" 18985 " }\n" 18986 " }\n", 18987 WhitesmithsBraceStyle); 18988 18989 verifyFormat("enum X\n" 18990 " {\n" 18991 " Y = 0, // testing\n" 18992 " }\n", 18993 WhitesmithsBraceStyle); 18994 18995 verifyFormat("enum X\n" 18996 " {\n" 18997 " Y = 0\n" 18998 " }\n", 18999 WhitesmithsBraceStyle); 19000 verifyFormat("enum X\n" 19001 " {\n" 19002 " Y = 0,\n" 19003 " Z = 1\n" 19004 " };\n", 19005 WhitesmithsBraceStyle); 19006 19007 verifyFormat("@interface BSApplicationController ()\n" 19008 " {\n" 19009 "@private\n" 19010 " id _extraIvar;\n" 19011 " }\n" 19012 "@end\n", 19013 WhitesmithsBraceStyle); 19014 19015 verifyFormat("#ifdef _DEBUG\n" 19016 "int foo(int i = 0)\n" 19017 "#else\n" 19018 "int foo(int i = 5)\n" 19019 "#endif\n" 19020 " {\n" 19021 " return i;\n" 19022 " }", 19023 WhitesmithsBraceStyle); 19024 19025 verifyFormat("void foo() {}\n" 19026 "void bar()\n" 19027 "#ifdef _DEBUG\n" 19028 " {\n" 19029 " foo();\n" 19030 " }\n" 19031 "#else\n" 19032 " {\n" 19033 " }\n" 19034 "#endif", 19035 WhitesmithsBraceStyle); 19036 19037 verifyFormat("void foobar()\n" 19038 " {\n" 19039 " int i = 5;\n" 19040 " }\n" 19041 "#ifdef _DEBUG\n" 19042 "void bar()\n" 19043 " {\n" 19044 " }\n" 19045 "#else\n" 19046 "void bar()\n" 19047 " {\n" 19048 " foobar();\n" 19049 " }\n" 19050 "#endif", 19051 WhitesmithsBraceStyle); 19052 19053 // This shouldn't affect ObjC blocks.. 19054 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n" 19055 " // ...\n" 19056 " int i;\n" 19057 "}];", 19058 WhitesmithsBraceStyle); 19059 verifyFormat("void (^block)(void) = ^{\n" 19060 " // ...\n" 19061 " int i;\n" 19062 "};", 19063 WhitesmithsBraceStyle); 19064 // .. or dict literals. 19065 verifyFormat("void f()\n" 19066 " {\n" 19067 " [object someMethod:@{@\"a\" : @\"b\"}];\n" 19068 " }", 19069 WhitesmithsBraceStyle); 19070 19071 verifyFormat("int f()\n" 19072 " { // comment\n" 19073 " return 42;\n" 19074 " }", 19075 WhitesmithsBraceStyle); 19076 19077 FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle; 19078 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = 19079 FormatStyle::SIS_OnlyFirstIf; 19080 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true; 19081 verifyFormat("void f(bool b)\n" 19082 " {\n" 19083 " if (b)\n" 19084 " {\n" 19085 " return;\n" 19086 " }\n" 19087 " }\n", 19088 BreakBeforeBraceShortIfs); 19089 verifyFormat("void f(bool b)\n" 19090 " {\n" 19091 " if (b) return;\n" 19092 " }\n", 19093 BreakBeforeBraceShortIfs); 19094 verifyFormat("void f(bool b)\n" 19095 " {\n" 19096 " while (b)\n" 19097 " {\n" 19098 " return;\n" 19099 " }\n" 19100 " }\n", 19101 BreakBeforeBraceShortIfs); 19102 } 19103 19104 TEST_F(FormatTest, GNUBraceBreaking) { 19105 FormatStyle GNUBraceStyle = getLLVMStyle(); 19106 GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU; 19107 verifyFormat("namespace a\n" 19108 "{\n" 19109 "class A\n" 19110 "{\n" 19111 " void f()\n" 19112 " {\n" 19113 " int a;\n" 19114 " {\n" 19115 " int b;\n" 19116 " }\n" 19117 " if (true)\n" 19118 " {\n" 19119 " a();\n" 19120 " b();\n" 19121 " }\n" 19122 " }\n" 19123 " void g() { return; }\n" 19124 "}\n" 19125 "} // namespace a", 19126 GNUBraceStyle); 19127 19128 verifyFormat("void f()\n" 19129 "{\n" 19130 " if (true)\n" 19131 " {\n" 19132 " a();\n" 19133 " }\n" 19134 " else if (false)\n" 19135 " {\n" 19136 " b();\n" 19137 " }\n" 19138 " else\n" 19139 " {\n" 19140 " c();\n" 19141 " }\n" 19142 "}\n", 19143 GNUBraceStyle); 19144 19145 verifyFormat("void f()\n" 19146 "{\n" 19147 " for (int i = 0; i < 10; ++i)\n" 19148 " {\n" 19149 " a();\n" 19150 " }\n" 19151 " while (false)\n" 19152 " {\n" 19153 " b();\n" 19154 " }\n" 19155 " do\n" 19156 " {\n" 19157 " c();\n" 19158 " }\n" 19159 " while (false);\n" 19160 "}\n", 19161 GNUBraceStyle); 19162 19163 verifyFormat("void f(int a)\n" 19164 "{\n" 19165 " switch (a)\n" 19166 " {\n" 19167 " case 0:\n" 19168 " break;\n" 19169 " case 1:\n" 19170 " {\n" 19171 " break;\n" 19172 " }\n" 19173 " case 2:\n" 19174 " {\n" 19175 " }\n" 19176 " break;\n" 19177 " default:\n" 19178 " break;\n" 19179 " }\n" 19180 "}\n", 19181 GNUBraceStyle); 19182 19183 verifyFormat("enum X\n" 19184 "{\n" 19185 " Y = 0,\n" 19186 "}\n", 19187 GNUBraceStyle); 19188 19189 verifyFormat("@interface BSApplicationController ()\n" 19190 "{\n" 19191 "@private\n" 19192 " id _extraIvar;\n" 19193 "}\n" 19194 "@end\n", 19195 GNUBraceStyle); 19196 19197 verifyFormat("#ifdef _DEBUG\n" 19198 "int foo(int i = 0)\n" 19199 "#else\n" 19200 "int foo(int i = 5)\n" 19201 "#endif\n" 19202 "{\n" 19203 " return i;\n" 19204 "}", 19205 GNUBraceStyle); 19206 19207 verifyFormat("void foo() {}\n" 19208 "void bar()\n" 19209 "#ifdef _DEBUG\n" 19210 "{\n" 19211 " foo();\n" 19212 "}\n" 19213 "#else\n" 19214 "{\n" 19215 "}\n" 19216 "#endif", 19217 GNUBraceStyle); 19218 19219 verifyFormat("void foobar() { int i = 5; }\n" 19220 "#ifdef _DEBUG\n" 19221 "void bar() {}\n" 19222 "#else\n" 19223 "void bar() { foobar(); }\n" 19224 "#endif", 19225 GNUBraceStyle); 19226 } 19227 19228 TEST_F(FormatTest, WebKitBraceBreaking) { 19229 FormatStyle WebKitBraceStyle = getLLVMStyle(); 19230 WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit; 19231 WebKitBraceStyle.FixNamespaceComments = false; 19232 verifyFormat("namespace a {\n" 19233 "class A {\n" 19234 " void f()\n" 19235 " {\n" 19236 " if (true) {\n" 19237 " a();\n" 19238 " b();\n" 19239 " }\n" 19240 " }\n" 19241 " void g() { return; }\n" 19242 "};\n" 19243 "enum E {\n" 19244 " A,\n" 19245 " // foo\n" 19246 " B,\n" 19247 " C\n" 19248 "};\n" 19249 "struct B {\n" 19250 " int x;\n" 19251 "};\n" 19252 "}\n", 19253 WebKitBraceStyle); 19254 verifyFormat("struct S {\n" 19255 " int Type;\n" 19256 " union {\n" 19257 " int x;\n" 19258 " double y;\n" 19259 " } Value;\n" 19260 " class C {\n" 19261 " MyFavoriteType Value;\n" 19262 " } Class;\n" 19263 "};\n", 19264 WebKitBraceStyle); 19265 } 19266 19267 TEST_F(FormatTest, CatchExceptionReferenceBinding) { 19268 verifyFormat("void f() {\n" 19269 " try {\n" 19270 " } catch (const Exception &e) {\n" 19271 " }\n" 19272 "}\n", 19273 getLLVMStyle()); 19274 } 19275 19276 TEST_F(FormatTest, CatchAlignArrayOfStructuresRightAlignment) { 19277 auto Style = getLLVMStyle(); 19278 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 19279 Style.AlignConsecutiveAssignments.Enabled = true; 19280 Style.AlignConsecutiveDeclarations.Enabled = true; 19281 verifyFormat("struct test demo[] = {\n" 19282 " {56, 23, \"hello\"},\n" 19283 " {-1, 93463, \"world\"},\n" 19284 " { 7, 5, \"!!\"}\n" 19285 "};\n", 19286 Style); 19287 19288 verifyFormat("struct test demo[] = {\n" 19289 " {56, 23, \"hello\"}, // first line\n" 19290 " {-1, 93463, \"world\"}, // second line\n" 19291 " { 7, 5, \"!!\"} // third line\n" 19292 "};\n", 19293 Style); 19294 19295 verifyFormat("struct test demo[4] = {\n" 19296 " { 56, 23, 21, \"oh\"}, // first line\n" 19297 " { -1, 93463, 22, \"my\"}, // second line\n" 19298 " { 7, 5, 1, \"goodness\"} // third line\n" 19299 " {234, 5, 1, \"gracious\"} // fourth line\n" 19300 "};\n", 19301 Style); 19302 19303 verifyFormat("struct test demo[3] = {\n" 19304 " {56, 23, \"hello\"},\n" 19305 " {-1, 93463, \"world\"},\n" 19306 " { 7, 5, \"!!\"}\n" 19307 "};\n", 19308 Style); 19309 19310 verifyFormat("struct test demo[3] = {\n" 19311 " {int{56}, 23, \"hello\"},\n" 19312 " {int{-1}, 93463, \"world\"},\n" 19313 " { int{7}, 5, \"!!\"}\n" 19314 "};\n", 19315 Style); 19316 19317 verifyFormat("struct test demo[] = {\n" 19318 " {56, 23, \"hello\"},\n" 19319 " {-1, 93463, \"world\"},\n" 19320 " { 7, 5, \"!!\"},\n" 19321 "};\n", 19322 Style); 19323 19324 verifyFormat("test demo[] = {\n" 19325 " {56, 23, \"hello\"},\n" 19326 " {-1, 93463, \"world\"},\n" 19327 " { 7, 5, \"!!\"},\n" 19328 "};\n", 19329 Style); 19330 19331 verifyFormat("demo = std::array<struct test, 3>{\n" 19332 " test{56, 23, \"hello\"},\n" 19333 " test{-1, 93463, \"world\"},\n" 19334 " test{ 7, 5, \"!!\"},\n" 19335 "};\n", 19336 Style); 19337 19338 verifyFormat("test demo[] = {\n" 19339 " {56, 23, \"hello\"},\n" 19340 "#if X\n" 19341 " {-1, 93463, \"world\"},\n" 19342 "#endif\n" 19343 " { 7, 5, \"!!\"}\n" 19344 "};\n", 19345 Style); 19346 19347 verifyFormat( 19348 "test demo[] = {\n" 19349 " { 7, 23,\n" 19350 " \"hello world i am a very long line that really, in any\"\n" 19351 " \"just world, ought to be split over multiple lines\"},\n" 19352 " {-1, 93463, \"world\"},\n" 19353 " {56, 5, \"!!\"}\n" 19354 "};\n", 19355 Style); 19356 19357 verifyFormat("return GradForUnaryCwise(g, {\n" 19358 " {{\"sign\"}, \"Sign\", " 19359 " {\"x\", \"dy\"}},\n" 19360 " { {\"dx\"}, \"Mul\", {\"dy\"" 19361 ", \"sign\"}},\n" 19362 "});\n", 19363 Style); 19364 19365 Style.ColumnLimit = 0; 19366 EXPECT_EQ( 19367 "test demo[] = {\n" 19368 " {56, 23, \"hello world i am a very long line that really, " 19369 "in any just world, ought to be split over multiple lines\"},\n" 19370 " {-1, 93463, " 19371 " \"world\"},\n" 19372 " { 7, 5, " 19373 " \"!!\"},\n" 19374 "};", 19375 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19376 "that really, in any just world, ought to be split over multiple " 19377 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19378 Style)); 19379 19380 Style.ColumnLimit = 80; 19381 verifyFormat("test demo[] = {\n" 19382 " {56, 23, /* a comment */ \"hello\"},\n" 19383 " {-1, 93463, \"world\"},\n" 19384 " { 7, 5, \"!!\"}\n" 19385 "};\n", 19386 Style); 19387 19388 verifyFormat("test demo[] = {\n" 19389 " {56, 23, \"hello\"},\n" 19390 " {-1, 93463, \"world\" /* comment here */},\n" 19391 " { 7, 5, \"!!\"}\n" 19392 "};\n", 19393 Style); 19394 19395 verifyFormat("test demo[] = {\n" 19396 " {56, /* a comment */ 23, \"hello\"},\n" 19397 " {-1, 93463, \"world\"},\n" 19398 " { 7, 5, \"!!\"}\n" 19399 "};\n", 19400 Style); 19401 19402 Style.ColumnLimit = 20; 19403 EXPECT_EQ( 19404 "demo = std::array<\n" 19405 " struct test, 3>{\n" 19406 " test{\n" 19407 " 56, 23,\n" 19408 " \"hello \"\n" 19409 " \"world i \"\n" 19410 " \"am a very \"\n" 19411 " \"long line \"\n" 19412 " \"that \"\n" 19413 " \"really, \"\n" 19414 " \"in any \"\n" 19415 " \"just \"\n" 19416 " \"world, \"\n" 19417 " \"ought to \"\n" 19418 " \"be split \"\n" 19419 " \"over \"\n" 19420 " \"multiple \"\n" 19421 " \"lines\"},\n" 19422 " test{-1, 93463,\n" 19423 " \"world\"},\n" 19424 " test{ 7, 5,\n" 19425 " \"!!\" },\n" 19426 "};", 19427 format("demo = std::array<struct test, 3>{test{56, 23, \"hello world " 19428 "i am a very long line that really, in any just world, ought " 19429 "to be split over multiple lines\"},test{-1, 93463, \"world\"}," 19430 "test{7, 5, \"!!\"},};", 19431 Style)); 19432 // This caused a core dump by enabling Alignment in the LLVMStyle globally 19433 Style = getLLVMStyleWithColumns(50); 19434 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 19435 verifyFormat("static A x = {\n" 19436 " {{init1, init2, init3, init4},\n" 19437 " {init1, init2, init3, init4}}\n" 19438 "};", 19439 Style); 19440 // TODO: Fix the indentations below when this option is fully functional. 19441 verifyFormat("int a[][] = {\n" 19442 " {\n" 19443 " {0, 2}, //\n" 19444 " {1, 2} //\n" 19445 " }\n" 19446 "};", 19447 Style); 19448 Style.ColumnLimit = 100; 19449 EXPECT_EQ( 19450 "test demo[] = {\n" 19451 " {56, 23,\n" 19452 " \"hello world i am a very long line that really, in any just world" 19453 ", ought to be split over \"\n" 19454 " \"multiple lines\" },\n" 19455 " {-1, 93463, \"world\"},\n" 19456 " { 7, 5, \"!!\"},\n" 19457 "};", 19458 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19459 "that really, in any just world, ought to be split over multiple " 19460 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19461 Style)); 19462 19463 Style = getLLVMStyleWithColumns(50); 19464 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 19465 verifyFormat("struct test demo[] = {\n" 19466 " {56, 23, \"hello\"},\n" 19467 " {-1, 93463, \"world\"},\n" 19468 " { 7, 5, \"!!\"}\n" 19469 "};\n" 19470 "static A x = {\n" 19471 " {{init1, init2, init3, init4},\n" 19472 " {init1, init2, init3, init4}}\n" 19473 "};", 19474 Style); 19475 Style.ColumnLimit = 100; 19476 Style.AlignConsecutiveAssignments.AcrossComments = true; 19477 Style.AlignConsecutiveDeclarations.AcrossComments = true; 19478 verifyFormat("struct test demo[] = {\n" 19479 " {56, 23, \"hello\"},\n" 19480 " {-1, 93463, \"world\"},\n" 19481 " { 7, 5, \"!!\"}\n" 19482 "};\n" 19483 "struct test demo[4] = {\n" 19484 " { 56, 23, 21, \"oh\"}, // first line\n" 19485 " { -1, 93463, 22, \"my\"}, // second line\n" 19486 " { 7, 5, 1, \"goodness\"} // third line\n" 19487 " {234, 5, 1, \"gracious\"} // fourth line\n" 19488 "};\n", 19489 Style); 19490 EXPECT_EQ( 19491 "test demo[] = {\n" 19492 " {56,\n" 19493 " \"hello world i am a very long line that really, in any just world" 19494 ", ought to be split over \"\n" 19495 " \"multiple lines\", 23},\n" 19496 " {-1, \"world\", 93463},\n" 19497 " { 7, \"!!\", 5},\n" 19498 "};", 19499 format("test demo[] = {{56, \"hello world i am a very long line " 19500 "that really, in any just world, ought to be split over multiple " 19501 "lines\", 23},{-1, \"world\", 93463},{7, \"!!\", 5},};", 19502 Style)); 19503 } 19504 19505 TEST_F(FormatTest, CatchAlignArrayOfStructuresLeftAlignment) { 19506 auto Style = getLLVMStyle(); 19507 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 19508 /* FIXME: This case gets misformatted. 19509 verifyFormat("auto foo = Items{\n" 19510 " Section{0, bar(), },\n" 19511 " Section{1, boo() }\n" 19512 "};\n", 19513 Style); 19514 */ 19515 verifyFormat("auto foo = Items{\n" 19516 " Section{\n" 19517 " 0, bar(),\n" 19518 " }\n" 19519 "};\n", 19520 Style); 19521 verifyFormat("struct test demo[] = {\n" 19522 " {56, 23, \"hello\"},\n" 19523 " {-1, 93463, \"world\"},\n" 19524 " {7, 5, \"!!\" }\n" 19525 "};\n", 19526 Style); 19527 verifyFormat("struct test demo[] = {\n" 19528 " {56, 23, \"hello\"}, // first line\n" 19529 " {-1, 93463, \"world\"}, // second line\n" 19530 " {7, 5, \"!!\" } // third line\n" 19531 "};\n", 19532 Style); 19533 verifyFormat("struct test demo[4] = {\n" 19534 " {56, 23, 21, \"oh\" }, // first line\n" 19535 " {-1, 93463, 22, \"my\" }, // second line\n" 19536 " {7, 5, 1, \"goodness\"} // third line\n" 19537 " {234, 5, 1, \"gracious\"} // fourth line\n" 19538 "};\n", 19539 Style); 19540 verifyFormat("struct test demo[3] = {\n" 19541 " {56, 23, \"hello\"},\n" 19542 " {-1, 93463, \"world\"},\n" 19543 " {7, 5, \"!!\" }\n" 19544 "};\n", 19545 Style); 19546 19547 verifyFormat("struct test demo[3] = {\n" 19548 " {int{56}, 23, \"hello\"},\n" 19549 " {int{-1}, 93463, \"world\"},\n" 19550 " {int{7}, 5, \"!!\" }\n" 19551 "};\n", 19552 Style); 19553 verifyFormat("struct test demo[] = {\n" 19554 " {56, 23, \"hello\"},\n" 19555 " {-1, 93463, \"world\"},\n" 19556 " {7, 5, \"!!\" },\n" 19557 "};\n", 19558 Style); 19559 verifyFormat("test demo[] = {\n" 19560 " {56, 23, \"hello\"},\n" 19561 " {-1, 93463, \"world\"},\n" 19562 " {7, 5, \"!!\" },\n" 19563 "};\n", 19564 Style); 19565 verifyFormat("demo = std::array<struct test, 3>{\n" 19566 " test{56, 23, \"hello\"},\n" 19567 " test{-1, 93463, \"world\"},\n" 19568 " test{7, 5, \"!!\" },\n" 19569 "};\n", 19570 Style); 19571 verifyFormat("test demo[] = {\n" 19572 " {56, 23, \"hello\"},\n" 19573 "#if X\n" 19574 " {-1, 93463, \"world\"},\n" 19575 "#endif\n" 19576 " {7, 5, \"!!\" }\n" 19577 "};\n", 19578 Style); 19579 verifyFormat( 19580 "test demo[] = {\n" 19581 " {7, 23,\n" 19582 " \"hello world i am a very long line that really, in any\"\n" 19583 " \"just world, ought to be split over multiple lines\"},\n" 19584 " {-1, 93463, \"world\" },\n" 19585 " {56, 5, \"!!\" }\n" 19586 "};\n", 19587 Style); 19588 19589 verifyFormat("return GradForUnaryCwise(g, {\n" 19590 " {{\"sign\"}, \"Sign\", {\"x\", " 19591 "\"dy\"} },\n" 19592 " {{\"dx\"}, \"Mul\", " 19593 "{\"dy\", \"sign\"}},\n" 19594 "});\n", 19595 Style); 19596 19597 Style.ColumnLimit = 0; 19598 EXPECT_EQ( 19599 "test demo[] = {\n" 19600 " {56, 23, \"hello world i am a very long line that really, in any " 19601 "just world, ought to be split over multiple lines\"},\n" 19602 " {-1, 93463, \"world\" " 19603 " },\n" 19604 " {7, 5, \"!!\" " 19605 " },\n" 19606 "};", 19607 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19608 "that really, in any just world, ought to be split over multiple " 19609 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19610 Style)); 19611 19612 Style.ColumnLimit = 80; 19613 verifyFormat("test demo[] = {\n" 19614 " {56, 23, /* a comment */ \"hello\"},\n" 19615 " {-1, 93463, \"world\" },\n" 19616 " {7, 5, \"!!\" }\n" 19617 "};\n", 19618 Style); 19619 19620 verifyFormat("test demo[] = {\n" 19621 " {56, 23, \"hello\" },\n" 19622 " {-1, 93463, \"world\" /* comment here */},\n" 19623 " {7, 5, \"!!\" }\n" 19624 "};\n", 19625 Style); 19626 19627 verifyFormat("test demo[] = {\n" 19628 " {56, /* a comment */ 23, \"hello\"},\n" 19629 " {-1, 93463, \"world\"},\n" 19630 " {7, 5, \"!!\" }\n" 19631 "};\n", 19632 Style); 19633 19634 Style.ColumnLimit = 20; 19635 EXPECT_EQ( 19636 "demo = std::array<\n" 19637 " struct test, 3>{\n" 19638 " test{\n" 19639 " 56, 23,\n" 19640 " \"hello \"\n" 19641 " \"world i \"\n" 19642 " \"am a very \"\n" 19643 " \"long line \"\n" 19644 " \"that \"\n" 19645 " \"really, \"\n" 19646 " \"in any \"\n" 19647 " \"just \"\n" 19648 " \"world, \"\n" 19649 " \"ought to \"\n" 19650 " \"be split \"\n" 19651 " \"over \"\n" 19652 " \"multiple \"\n" 19653 " \"lines\"},\n" 19654 " test{-1, 93463,\n" 19655 " \"world\"},\n" 19656 " test{7, 5,\n" 19657 " \"!!\" },\n" 19658 "};", 19659 format("demo = std::array<struct test, 3>{test{56, 23, \"hello world " 19660 "i am a very long line that really, in any just world, ought " 19661 "to be split over multiple lines\"},test{-1, 93463, \"world\"}," 19662 "test{7, 5, \"!!\"},};", 19663 Style)); 19664 19665 // This caused a core dump by enabling Alignment in the LLVMStyle globally 19666 Style = getLLVMStyleWithColumns(50); 19667 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 19668 verifyFormat("static A x = {\n" 19669 " {{init1, init2, init3, init4},\n" 19670 " {init1, init2, init3, init4}}\n" 19671 "};", 19672 Style); 19673 Style.ColumnLimit = 100; 19674 EXPECT_EQ( 19675 "test demo[] = {\n" 19676 " {56, 23,\n" 19677 " \"hello world i am a very long line that really, in any just world" 19678 ", ought to be split over \"\n" 19679 " \"multiple lines\" },\n" 19680 " {-1, 93463, \"world\"},\n" 19681 " {7, 5, \"!!\" },\n" 19682 "};", 19683 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19684 "that really, in any just world, ought to be split over multiple " 19685 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19686 Style)); 19687 } 19688 19689 TEST_F(FormatTest, UnderstandsPragmas) { 19690 verifyFormat("#pragma omp reduction(| : var)"); 19691 verifyFormat("#pragma omp reduction(+ : var)"); 19692 19693 EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string " 19694 "(including parentheses).", 19695 format("#pragma mark Any non-hyphenated or hyphenated string " 19696 "(including parentheses).")); 19697 } 19698 19699 TEST_F(FormatTest, UnderstandPragmaOption) { 19700 verifyFormat("#pragma option -C -A"); 19701 19702 EXPECT_EQ("#pragma option -C -A", format("#pragma option -C -A")); 19703 } 19704 19705 TEST_F(FormatTest, UnderstandPragmaRegion) { 19706 auto Style = getLLVMStyleWithColumns(0); 19707 verifyFormat("#pragma region TEST(FOO : BAR)", Style); 19708 19709 EXPECT_EQ("#pragma region TEST(FOO : BAR)", 19710 format("#pragma region TEST(FOO : BAR)", Style)); 19711 } 19712 19713 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) { 19714 FormatStyle Style = getLLVMStyleWithColumns(20); 19715 19716 // See PR41213 19717 EXPECT_EQ("/*\n" 19718 " *\t9012345\n" 19719 " * /8901\n" 19720 " */", 19721 format("/*\n" 19722 " *\t9012345 /8901\n" 19723 " */", 19724 Style)); 19725 EXPECT_EQ("/*\n" 19726 " *345678\n" 19727 " *\t/8901\n" 19728 " */", 19729 format("/*\n" 19730 " *345678\t/8901\n" 19731 " */", 19732 Style)); 19733 19734 verifyFormat("int a; // the\n" 19735 " // comment", 19736 Style); 19737 EXPECT_EQ("int a; /* first line\n" 19738 " * second\n" 19739 " * line third\n" 19740 " * line\n" 19741 " */", 19742 format("int a; /* first line\n" 19743 " * second\n" 19744 " * line third\n" 19745 " * line\n" 19746 " */", 19747 Style)); 19748 EXPECT_EQ("int a; // first line\n" 19749 " // second\n" 19750 " // line third\n" 19751 " // line", 19752 format("int a; // first line\n" 19753 " // second line\n" 19754 " // third line", 19755 Style)); 19756 19757 Style.PenaltyExcessCharacter = 90; 19758 verifyFormat("int a; // the comment", Style); 19759 EXPECT_EQ("int a; // the comment\n" 19760 " // aaa", 19761 format("int a; // the comment aaa", Style)); 19762 EXPECT_EQ("int a; /* first line\n" 19763 " * second line\n" 19764 " * third line\n" 19765 " */", 19766 format("int a; /* first line\n" 19767 " * second line\n" 19768 " * third line\n" 19769 " */", 19770 Style)); 19771 EXPECT_EQ("int a; // first line\n" 19772 " // second line\n" 19773 " // third line", 19774 format("int a; // first line\n" 19775 " // second line\n" 19776 " // third line", 19777 Style)); 19778 // FIXME: Investigate why this is not getting the same layout as the test 19779 // above. 19780 EXPECT_EQ("int a; /* first line\n" 19781 " * second line\n" 19782 " * third line\n" 19783 " */", 19784 format("int a; /* first line second line third line" 19785 "\n*/", 19786 Style)); 19787 19788 EXPECT_EQ("// foo bar baz bazfoo\n" 19789 "// foo bar foo bar\n", 19790 format("// foo bar baz bazfoo\n" 19791 "// foo bar foo bar\n", 19792 Style)); 19793 EXPECT_EQ("// foo bar baz bazfoo\n" 19794 "// foo bar foo bar\n", 19795 format("// foo bar baz bazfoo\n" 19796 "// foo bar foo bar\n", 19797 Style)); 19798 19799 // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the 19800 // next one. 19801 EXPECT_EQ("// foo bar baz bazfoo\n" 19802 "// bar foo bar\n", 19803 format("// foo bar baz bazfoo bar\n" 19804 "// foo bar\n", 19805 Style)); 19806 19807 EXPECT_EQ("// foo bar baz bazfoo\n" 19808 "// foo bar baz bazfoo\n" 19809 "// bar foo bar\n", 19810 format("// foo bar baz bazfoo\n" 19811 "// foo bar baz bazfoo bar\n" 19812 "// foo bar\n", 19813 Style)); 19814 19815 EXPECT_EQ("// foo bar baz bazfoo\n" 19816 "// foo bar baz bazfoo\n" 19817 "// bar foo bar\n", 19818 format("// foo bar baz bazfoo\n" 19819 "// foo bar baz bazfoo bar\n" 19820 "// foo bar\n", 19821 Style)); 19822 19823 // Make sure we do not keep protruding characters if strict mode reflow is 19824 // cheaper than keeping protruding characters. 19825 Style.ColumnLimit = 21; 19826 EXPECT_EQ( 19827 "// foo foo foo foo\n" 19828 "// foo foo foo foo\n" 19829 "// foo foo foo foo\n", 19830 format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style)); 19831 19832 EXPECT_EQ("int a = /* long block\n" 19833 " comment */\n" 19834 " 42;", 19835 format("int a = /* long block comment */ 42;", Style)); 19836 } 19837 19838 TEST_F(FormatTest, BreakPenaltyAfterLParen) { 19839 FormatStyle Style = getLLVMStyle(); 19840 Style.ColumnLimit = 8; 19841 Style.PenaltyExcessCharacter = 15; 19842 verifyFormat("int foo(\n" 19843 " int aaaaaaaaaaaaaaaaaaaaaaaa);", 19844 Style); 19845 Style.PenaltyBreakOpenParenthesis = 200; 19846 EXPECT_EQ("int foo(int aaaaaaaaaaaaaaaaaaaaaaaa);", 19847 format("int foo(\n" 19848 " int aaaaaaaaaaaaaaaaaaaaaaaa);", 19849 Style)); 19850 } 19851 19852 TEST_F(FormatTest, BreakPenaltyAfterCastLParen) { 19853 FormatStyle Style = getLLVMStyle(); 19854 Style.ColumnLimit = 5; 19855 Style.PenaltyExcessCharacter = 150; 19856 verifyFormat("foo((\n" 19857 " int)aaaaaaaaaaaaaaaaaaaaaaaa);", 19858 19859 Style); 19860 Style.PenaltyBreakOpenParenthesis = 100000; 19861 EXPECT_EQ("foo((int)\n" 19862 " aaaaaaaaaaaaaaaaaaaaaaaa);", 19863 format("foo((\n" 19864 "int)aaaaaaaaaaaaaaaaaaaaaaaa);", 19865 Style)); 19866 } 19867 19868 TEST_F(FormatTest, BreakPenaltyAfterForLoopLParen) { 19869 FormatStyle Style = getLLVMStyle(); 19870 Style.ColumnLimit = 4; 19871 Style.PenaltyExcessCharacter = 100; 19872 verifyFormat("for (\n" 19873 " int iiiiiiiiiiiiiiiii =\n" 19874 " 0;\n" 19875 " iiiiiiiiiiiiiiiii <\n" 19876 " 2;\n" 19877 " iiiiiiiiiiiiiiiii++) {\n" 19878 "}", 19879 19880 Style); 19881 Style.PenaltyBreakOpenParenthesis = 1250; 19882 EXPECT_EQ("for (int iiiiiiiiiiiiiiiii =\n" 19883 " 0;\n" 19884 " iiiiiiiiiiiiiiiii <\n" 19885 " 2;\n" 19886 " iiiiiiiiiiiiiiiii++) {\n" 19887 "}", 19888 format("for (\n" 19889 " int iiiiiiiiiiiiiiiii =\n" 19890 " 0;\n" 19891 " iiiiiiiiiiiiiiiii <\n" 19892 " 2;\n" 19893 " iiiiiiiiiiiiiiiii++) {\n" 19894 "}", 19895 Style)); 19896 } 19897 19898 #define EXPECT_ALL_STYLES_EQUAL(Styles) \ 19899 for (size_t i = 1; i < Styles.size(); ++i) \ 19900 EXPECT_EQ(Styles[0], Styles[i]) \ 19901 << "Style #" << i << " of " << Styles.size() << " differs from Style #0" 19902 19903 TEST_F(FormatTest, GetsPredefinedStyleByName) { 19904 SmallVector<FormatStyle, 3> Styles; 19905 Styles.resize(3); 19906 19907 Styles[0] = getLLVMStyle(); 19908 EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1])); 19909 EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2])); 19910 EXPECT_ALL_STYLES_EQUAL(Styles); 19911 19912 Styles[0] = getGoogleStyle(); 19913 EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1])); 19914 EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2])); 19915 EXPECT_ALL_STYLES_EQUAL(Styles); 19916 19917 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript); 19918 EXPECT_TRUE( 19919 getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1])); 19920 EXPECT_TRUE( 19921 getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2])); 19922 EXPECT_ALL_STYLES_EQUAL(Styles); 19923 19924 Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp); 19925 EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1])); 19926 EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2])); 19927 EXPECT_ALL_STYLES_EQUAL(Styles); 19928 19929 Styles[0] = getMozillaStyle(); 19930 EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1])); 19931 EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2])); 19932 EXPECT_ALL_STYLES_EQUAL(Styles); 19933 19934 Styles[0] = getWebKitStyle(); 19935 EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1])); 19936 EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2])); 19937 EXPECT_ALL_STYLES_EQUAL(Styles); 19938 19939 Styles[0] = getGNUStyle(); 19940 EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1])); 19941 EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2])); 19942 EXPECT_ALL_STYLES_EQUAL(Styles); 19943 19944 EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0])); 19945 } 19946 19947 TEST_F(FormatTest, GetsCorrectBasedOnStyle) { 19948 SmallVector<FormatStyle, 8> Styles; 19949 Styles.resize(2); 19950 19951 Styles[0] = getGoogleStyle(); 19952 Styles[1] = getLLVMStyle(); 19953 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value()); 19954 EXPECT_ALL_STYLES_EQUAL(Styles); 19955 19956 Styles.resize(5); 19957 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript); 19958 Styles[1] = getLLVMStyle(); 19959 Styles[1].Language = FormatStyle::LK_JavaScript; 19960 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value()); 19961 19962 Styles[2] = getLLVMStyle(); 19963 Styles[2].Language = FormatStyle::LK_JavaScript; 19964 EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n" 19965 "BasedOnStyle: Google", 19966 &Styles[2]) 19967 .value()); 19968 19969 Styles[3] = getLLVMStyle(); 19970 Styles[3].Language = FormatStyle::LK_JavaScript; 19971 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n" 19972 "Language: JavaScript", 19973 &Styles[3]) 19974 .value()); 19975 19976 Styles[4] = getLLVMStyle(); 19977 Styles[4].Language = FormatStyle::LK_JavaScript; 19978 EXPECT_EQ(0, parseConfiguration("---\n" 19979 "BasedOnStyle: LLVM\n" 19980 "IndentWidth: 123\n" 19981 "---\n" 19982 "BasedOnStyle: Google\n" 19983 "Language: JavaScript", 19984 &Styles[4]) 19985 .value()); 19986 EXPECT_ALL_STYLES_EQUAL(Styles); 19987 } 19988 19989 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME) \ 19990 Style.FIELD = false; \ 19991 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value()); \ 19992 EXPECT_TRUE(Style.FIELD); \ 19993 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value()); \ 19994 EXPECT_FALSE(Style.FIELD); 19995 19996 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD) 19997 19998 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME) \ 19999 Style.STRUCT.FIELD = false; \ 20000 EXPECT_EQ(0, \ 20001 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": true", &Style) \ 20002 .value()); \ 20003 EXPECT_TRUE(Style.STRUCT.FIELD); \ 20004 EXPECT_EQ(0, \ 20005 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": false", &Style) \ 20006 .value()); \ 20007 EXPECT_FALSE(Style.STRUCT.FIELD); 20008 20009 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD) \ 20010 CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD) 20011 20012 #define CHECK_PARSE(TEXT, FIELD, VALUE) \ 20013 EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!"; \ 20014 EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value()); \ 20015 EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!" 20016 20017 TEST_F(FormatTest, ParsesConfigurationBools) { 20018 FormatStyle Style = {}; 20019 Style.Language = FormatStyle::LK_Cpp; 20020 CHECK_PARSE_BOOL(AlignTrailingComments); 20021 CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine); 20022 CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine); 20023 CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine); 20024 CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine); 20025 CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine); 20026 CHECK_PARSE_BOOL(BinPackArguments); 20027 CHECK_PARSE_BOOL(BinPackParameters); 20028 CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations); 20029 CHECK_PARSE_BOOL(BreakBeforeTernaryOperators); 20030 CHECK_PARSE_BOOL(BreakStringLiterals); 20031 CHECK_PARSE_BOOL(CompactNamespaces); 20032 CHECK_PARSE_BOOL(DeriveLineEnding); 20033 CHECK_PARSE_BOOL(DerivePointerAlignment); 20034 CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding"); 20035 CHECK_PARSE_BOOL(DisableFormat); 20036 CHECK_PARSE_BOOL(IndentAccessModifiers); 20037 CHECK_PARSE_BOOL(IndentCaseLabels); 20038 CHECK_PARSE_BOOL(IndentCaseBlocks); 20039 CHECK_PARSE_BOOL(IndentGotoLabels); 20040 CHECK_PARSE_BOOL_FIELD(IndentRequiresClause, "IndentRequires"); 20041 CHECK_PARSE_BOOL(IndentRequiresClause); 20042 CHECK_PARSE_BOOL(IndentWrappedFunctionNames); 20043 CHECK_PARSE_BOOL(InsertBraces); 20044 CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks); 20045 CHECK_PARSE_BOOL(ObjCSpaceAfterProperty); 20046 CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList); 20047 CHECK_PARSE_BOOL(Cpp11BracedListStyle); 20048 CHECK_PARSE_BOOL(ReflowComments); 20049 CHECK_PARSE_BOOL(RemoveBracesLLVM); 20050 CHECK_PARSE_BOOL(SortUsingDeclarations); 20051 CHECK_PARSE_BOOL(SpacesInParentheses); 20052 CHECK_PARSE_BOOL(SpacesInSquareBrackets); 20053 CHECK_PARSE_BOOL(SpacesInConditionalStatement); 20054 CHECK_PARSE_BOOL(SpaceInEmptyBlock); 20055 CHECK_PARSE_BOOL(SpaceInEmptyParentheses); 20056 CHECK_PARSE_BOOL(SpacesInContainerLiterals); 20057 CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses); 20058 CHECK_PARSE_BOOL(SpaceAfterCStyleCast); 20059 CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword); 20060 CHECK_PARSE_BOOL(SpaceAfterLogicalNot); 20061 CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators); 20062 CHECK_PARSE_BOOL(SpaceBeforeCaseColon); 20063 CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList); 20064 CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon); 20065 CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon); 20066 CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon); 20067 CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets); 20068 CHECK_PARSE_BOOL(UseCRLF); 20069 20070 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel); 20071 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass); 20072 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum); 20073 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction); 20074 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace); 20075 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration); 20076 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct); 20077 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion); 20078 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock); 20079 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch); 20080 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse); 20081 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody); 20082 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile); 20083 CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces); 20084 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction); 20085 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord); 20086 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace); 20087 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterControlStatements); 20088 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterForeachMacros); 20089 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, 20090 AfterFunctionDeclarationName); 20091 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, 20092 AfterFunctionDefinitionName); 20093 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterIfMacros); 20094 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterOverloadedOperator); 20095 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, BeforeNonEmptyParentheses); 20096 } 20097 20098 #undef CHECK_PARSE_BOOL 20099 20100 TEST_F(FormatTest, ParsesConfiguration) { 20101 FormatStyle Style = {}; 20102 Style.Language = FormatStyle::LK_Cpp; 20103 CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234); 20104 CHECK_PARSE("ConstructorInitializerIndentWidth: 1234", 20105 ConstructorInitializerIndentWidth, 1234u); 20106 CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u); 20107 CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u); 20108 CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u); 20109 CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u); 20110 CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234", 20111 PenaltyBreakBeforeFirstCallParameter, 1234u); 20112 CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234", 20113 PenaltyBreakTemplateDeclaration, 1234u); 20114 CHECK_PARSE("PenaltyBreakOpenParenthesis: 1234", PenaltyBreakOpenParenthesis, 20115 1234u); 20116 CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u); 20117 CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234", 20118 PenaltyReturnTypeOnItsOwnLine, 1234u); 20119 CHECK_PARSE("SpacesBeforeTrailingComments: 1234", 20120 SpacesBeforeTrailingComments, 1234u); 20121 CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u); 20122 CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u); 20123 CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$"); 20124 20125 Style.QualifierAlignment = FormatStyle::QAS_Right; 20126 CHECK_PARSE("QualifierAlignment: Leave", QualifierAlignment, 20127 FormatStyle::QAS_Leave); 20128 CHECK_PARSE("QualifierAlignment: Right", QualifierAlignment, 20129 FormatStyle::QAS_Right); 20130 CHECK_PARSE("QualifierAlignment: Left", QualifierAlignment, 20131 FormatStyle::QAS_Left); 20132 CHECK_PARSE("QualifierAlignment: Custom", QualifierAlignment, 20133 FormatStyle::QAS_Custom); 20134 20135 Style.QualifierOrder.clear(); 20136 CHECK_PARSE("QualifierOrder: [ const, volatile, type ]", QualifierOrder, 20137 std::vector<std::string>({"const", "volatile", "type"})); 20138 Style.QualifierOrder.clear(); 20139 CHECK_PARSE("QualifierOrder: [const, type]", QualifierOrder, 20140 std::vector<std::string>({"const", "type"})); 20141 Style.QualifierOrder.clear(); 20142 CHECK_PARSE("QualifierOrder: [volatile, type]", QualifierOrder, 20143 std::vector<std::string>({"volatile", "type"})); 20144 20145 #define CHECK_ALIGN_CONSECUTIVE(FIELD) \ 20146 do { \ 20147 Style.FIELD.Enabled = true; \ 20148 CHECK_PARSE(#FIELD ": None", FIELD, \ 20149 FormatStyle::AlignConsecutiveStyle( \ 20150 {/*Enabled=*/false, /*AcrossEmptyLines=*/false, \ 20151 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 20152 /*PadOperators=*/true})); \ 20153 CHECK_PARSE(#FIELD ": Consecutive", FIELD, \ 20154 FormatStyle::AlignConsecutiveStyle( \ 20155 {/*Enabled=*/true, /*AcrossEmptyLines=*/false, \ 20156 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 20157 /*PadOperators=*/true})); \ 20158 CHECK_PARSE(#FIELD ": AcrossEmptyLines", FIELD, \ 20159 FormatStyle::AlignConsecutiveStyle( \ 20160 {/*Enabled=*/true, /*AcrossEmptyLines=*/true, \ 20161 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 20162 /*PadOperators=*/true})); \ 20163 CHECK_PARSE(#FIELD ": AcrossEmptyLinesAndComments", FIELD, \ 20164 FormatStyle::AlignConsecutiveStyle( \ 20165 {/*Enabled=*/true, /*AcrossEmptyLines=*/true, \ 20166 /*AcrossComments=*/true, /*AlignCompound=*/false, \ 20167 /*PadOperators=*/true})); \ 20168 /* For backwards compability, false / true should still parse */ \ 20169 CHECK_PARSE(#FIELD ": false", FIELD, \ 20170 FormatStyle::AlignConsecutiveStyle( \ 20171 {/*Enabled=*/false, /*AcrossEmptyLines=*/false, \ 20172 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 20173 /*PadOperators=*/true})); \ 20174 CHECK_PARSE(#FIELD ": true", FIELD, \ 20175 FormatStyle::AlignConsecutiveStyle( \ 20176 {/*Enabled=*/true, /*AcrossEmptyLines=*/false, \ 20177 /*AcrossComments=*/false, /*AlignCompound=*/false, \ 20178 /*PadOperators=*/true})); \ 20179 \ 20180 CHECK_PARSE_NESTED_BOOL(FIELD, Enabled); \ 20181 CHECK_PARSE_NESTED_BOOL(FIELD, AcrossEmptyLines); \ 20182 CHECK_PARSE_NESTED_BOOL(FIELD, AcrossComments); \ 20183 CHECK_PARSE_NESTED_BOOL(FIELD, AlignCompound); \ 20184 CHECK_PARSE_NESTED_BOOL(FIELD, PadOperators); \ 20185 } while (false) 20186 20187 CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveAssignments); 20188 CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveBitFields); 20189 CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveMacros); 20190 CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveDeclarations); 20191 20192 #undef CHECK_ALIGN_CONSECUTIVE 20193 20194 Style.PointerAlignment = FormatStyle::PAS_Middle; 20195 CHECK_PARSE("PointerAlignment: Left", PointerAlignment, 20196 FormatStyle::PAS_Left); 20197 CHECK_PARSE("PointerAlignment: Right", PointerAlignment, 20198 FormatStyle::PAS_Right); 20199 CHECK_PARSE("PointerAlignment: Middle", PointerAlignment, 20200 FormatStyle::PAS_Middle); 20201 Style.ReferenceAlignment = FormatStyle::RAS_Middle; 20202 CHECK_PARSE("ReferenceAlignment: Pointer", ReferenceAlignment, 20203 FormatStyle::RAS_Pointer); 20204 CHECK_PARSE("ReferenceAlignment: Left", ReferenceAlignment, 20205 FormatStyle::RAS_Left); 20206 CHECK_PARSE("ReferenceAlignment: Right", ReferenceAlignment, 20207 FormatStyle::RAS_Right); 20208 CHECK_PARSE("ReferenceAlignment: Middle", ReferenceAlignment, 20209 FormatStyle::RAS_Middle); 20210 // For backward compatibility: 20211 CHECK_PARSE("PointerBindsToType: Left", PointerAlignment, 20212 FormatStyle::PAS_Left); 20213 CHECK_PARSE("PointerBindsToType: Right", PointerAlignment, 20214 FormatStyle::PAS_Right); 20215 CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment, 20216 FormatStyle::PAS_Middle); 20217 20218 Style.Standard = FormatStyle::LS_Auto; 20219 CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03); 20220 CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11); 20221 CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14); 20222 CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17); 20223 CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20); 20224 CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto); 20225 CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest); 20226 // Legacy aliases: 20227 CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03); 20228 CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest); 20229 CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03); 20230 CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11); 20231 20232 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 20233 CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment", 20234 BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment); 20235 CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators, 20236 FormatStyle::BOS_None); 20237 CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators, 20238 FormatStyle::BOS_All); 20239 // For backward compatibility: 20240 CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators, 20241 FormatStyle::BOS_None); 20242 CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators, 20243 FormatStyle::BOS_All); 20244 20245 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 20246 CHECK_PARSE("BreakConstructorInitializers: BeforeComma", 20247 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma); 20248 CHECK_PARSE("BreakConstructorInitializers: AfterColon", 20249 BreakConstructorInitializers, FormatStyle::BCIS_AfterColon); 20250 CHECK_PARSE("BreakConstructorInitializers: BeforeColon", 20251 BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon); 20252 // For backward compatibility: 20253 CHECK_PARSE("BreakConstructorInitializersBeforeComma: true", 20254 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma); 20255 20256 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 20257 CHECK_PARSE("BreakInheritanceList: AfterComma", BreakInheritanceList, 20258 FormatStyle::BILS_AfterComma); 20259 CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList, 20260 FormatStyle::BILS_BeforeComma); 20261 CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList, 20262 FormatStyle::BILS_AfterColon); 20263 CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList, 20264 FormatStyle::BILS_BeforeColon); 20265 // For backward compatibility: 20266 CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList, 20267 FormatStyle::BILS_BeforeComma); 20268 20269 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 20270 CHECK_PARSE("PackConstructorInitializers: Never", PackConstructorInitializers, 20271 FormatStyle::PCIS_Never); 20272 CHECK_PARSE("PackConstructorInitializers: BinPack", 20273 PackConstructorInitializers, FormatStyle::PCIS_BinPack); 20274 CHECK_PARSE("PackConstructorInitializers: CurrentLine", 20275 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 20276 CHECK_PARSE("PackConstructorInitializers: NextLine", 20277 PackConstructorInitializers, FormatStyle::PCIS_NextLine); 20278 // For backward compatibility: 20279 CHECK_PARSE("BasedOnStyle: Google\n" 20280 "ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 20281 "AllowAllConstructorInitializersOnNextLine: false", 20282 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 20283 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 20284 CHECK_PARSE("BasedOnStyle: Google\n" 20285 "ConstructorInitializerAllOnOneLineOrOnePerLine: false", 20286 PackConstructorInitializers, FormatStyle::PCIS_BinPack); 20287 CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 20288 "AllowAllConstructorInitializersOnNextLine: true", 20289 PackConstructorInitializers, FormatStyle::PCIS_NextLine); 20290 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 20291 CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 20292 "AllowAllConstructorInitializersOnNextLine: false", 20293 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 20294 20295 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 20296 CHECK_PARSE("EmptyLineBeforeAccessModifier: Never", 20297 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never); 20298 CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave", 20299 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave); 20300 CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock", 20301 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock); 20302 CHECK_PARSE("EmptyLineBeforeAccessModifier: Always", 20303 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always); 20304 20305 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 20306 CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket, 20307 FormatStyle::BAS_Align); 20308 CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket, 20309 FormatStyle::BAS_DontAlign); 20310 CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket, 20311 FormatStyle::BAS_AlwaysBreak); 20312 CHECK_PARSE("AlignAfterOpenBracket: BlockIndent", AlignAfterOpenBracket, 20313 FormatStyle::BAS_BlockIndent); 20314 // For backward compatibility: 20315 CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket, 20316 FormatStyle::BAS_DontAlign); 20317 CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket, 20318 FormatStyle::BAS_Align); 20319 20320 Style.AlignEscapedNewlines = FormatStyle::ENAS_Left; 20321 CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines, 20322 FormatStyle::ENAS_DontAlign); 20323 CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines, 20324 FormatStyle::ENAS_Left); 20325 CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines, 20326 FormatStyle::ENAS_Right); 20327 // For backward compatibility: 20328 CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines, 20329 FormatStyle::ENAS_Left); 20330 CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines, 20331 FormatStyle::ENAS_Right); 20332 20333 Style.AlignOperands = FormatStyle::OAS_Align; 20334 CHECK_PARSE("AlignOperands: DontAlign", AlignOperands, 20335 FormatStyle::OAS_DontAlign); 20336 CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align); 20337 CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands, 20338 FormatStyle::OAS_AlignAfterOperator); 20339 // For backward compatibility: 20340 CHECK_PARSE("AlignOperands: false", AlignOperands, 20341 FormatStyle::OAS_DontAlign); 20342 CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align); 20343 20344 Style.UseTab = FormatStyle::UT_ForIndentation; 20345 CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never); 20346 CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation); 20347 CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always); 20348 CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab, 20349 FormatStyle::UT_ForContinuationAndIndentation); 20350 CHECK_PARSE("UseTab: AlignWithSpaces", UseTab, 20351 FormatStyle::UT_AlignWithSpaces); 20352 // For backward compatibility: 20353 CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never); 20354 CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always); 20355 20356 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 20357 CHECK_PARSE("AllowShortBlocksOnASingleLine: Never", 20358 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 20359 CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty", 20360 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty); 20361 CHECK_PARSE("AllowShortBlocksOnASingleLine: Always", 20362 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always); 20363 // For backward compatibility: 20364 CHECK_PARSE("AllowShortBlocksOnASingleLine: false", 20365 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 20366 CHECK_PARSE("AllowShortBlocksOnASingleLine: true", 20367 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always); 20368 20369 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 20370 CHECK_PARSE("AllowShortFunctionsOnASingleLine: None", 20371 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None); 20372 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline", 20373 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline); 20374 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty", 20375 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty); 20376 CHECK_PARSE("AllowShortFunctionsOnASingleLine: All", 20377 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All); 20378 // For backward compatibility: 20379 CHECK_PARSE("AllowShortFunctionsOnASingleLine: false", 20380 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None); 20381 CHECK_PARSE("AllowShortFunctionsOnASingleLine: true", 20382 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All); 20383 20384 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both; 20385 CHECK_PARSE("SpaceAroundPointerQualifiers: Default", 20386 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default); 20387 CHECK_PARSE("SpaceAroundPointerQualifiers: Before", 20388 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before); 20389 CHECK_PARSE("SpaceAroundPointerQualifiers: After", 20390 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After); 20391 CHECK_PARSE("SpaceAroundPointerQualifiers: Both", 20392 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both); 20393 20394 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 20395 CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens, 20396 FormatStyle::SBPO_Never); 20397 CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens, 20398 FormatStyle::SBPO_Always); 20399 CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens, 20400 FormatStyle::SBPO_ControlStatements); 20401 CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptControlMacros", 20402 SpaceBeforeParens, 20403 FormatStyle::SBPO_ControlStatementsExceptControlMacros); 20404 CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens, 20405 FormatStyle::SBPO_NonEmptyParentheses); 20406 CHECK_PARSE("SpaceBeforeParens: Custom", SpaceBeforeParens, 20407 FormatStyle::SBPO_Custom); 20408 // For backward compatibility: 20409 CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens, 20410 FormatStyle::SBPO_Never); 20411 CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens, 20412 FormatStyle::SBPO_ControlStatements); 20413 CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptForEachMacros", 20414 SpaceBeforeParens, 20415 FormatStyle::SBPO_ControlStatementsExceptControlMacros); 20416 20417 Style.ColumnLimit = 123; 20418 FormatStyle BaseStyle = getLLVMStyle(); 20419 CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit); 20420 CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u); 20421 20422 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 20423 CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces, 20424 FormatStyle::BS_Attach); 20425 CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces, 20426 FormatStyle::BS_Linux); 20427 CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces, 20428 FormatStyle::BS_Mozilla); 20429 CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces, 20430 FormatStyle::BS_Stroustrup); 20431 CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces, 20432 FormatStyle::BS_Allman); 20433 CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces, 20434 FormatStyle::BS_Whitesmiths); 20435 CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU); 20436 CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces, 20437 FormatStyle::BS_WebKit); 20438 CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces, 20439 FormatStyle::BS_Custom); 20440 20441 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never; 20442 CHECK_PARSE("BraceWrapping:\n" 20443 " AfterControlStatement: MultiLine", 20444 BraceWrapping.AfterControlStatement, 20445 FormatStyle::BWACS_MultiLine); 20446 CHECK_PARSE("BraceWrapping:\n" 20447 " AfterControlStatement: Always", 20448 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always); 20449 CHECK_PARSE("BraceWrapping:\n" 20450 " AfterControlStatement: Never", 20451 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never); 20452 // For backward compatibility: 20453 CHECK_PARSE("BraceWrapping:\n" 20454 " AfterControlStatement: true", 20455 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always); 20456 CHECK_PARSE("BraceWrapping:\n" 20457 " AfterControlStatement: false", 20458 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never); 20459 20460 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 20461 CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType, 20462 FormatStyle::RTBS_None); 20463 CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType, 20464 FormatStyle::RTBS_All); 20465 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel", 20466 AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel); 20467 CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions", 20468 AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions); 20469 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions", 20470 AlwaysBreakAfterReturnType, 20471 FormatStyle::RTBS_TopLevelDefinitions); 20472 20473 Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 20474 CHECK_PARSE("AlwaysBreakTemplateDeclarations: No", 20475 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No); 20476 CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine", 20477 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine); 20478 CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes", 20479 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes); 20480 CHECK_PARSE("AlwaysBreakTemplateDeclarations: false", 20481 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine); 20482 CHECK_PARSE("AlwaysBreakTemplateDeclarations: true", 20483 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes); 20484 20485 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All; 20486 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None", 20487 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None); 20488 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All", 20489 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All); 20490 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel", 20491 AlwaysBreakAfterDefinitionReturnType, 20492 FormatStyle::DRTBS_TopLevel); 20493 20494 Style.NamespaceIndentation = FormatStyle::NI_All; 20495 CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation, 20496 FormatStyle::NI_None); 20497 CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation, 20498 FormatStyle::NI_Inner); 20499 CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation, 20500 FormatStyle::NI_All); 20501 20502 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_OnlyFirstIf; 20503 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never", 20504 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never); 20505 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse", 20506 AllowShortIfStatementsOnASingleLine, 20507 FormatStyle::SIS_WithoutElse); 20508 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: OnlyFirstIf", 20509 AllowShortIfStatementsOnASingleLine, 20510 FormatStyle::SIS_OnlyFirstIf); 20511 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: AllIfsAndElse", 20512 AllowShortIfStatementsOnASingleLine, 20513 FormatStyle::SIS_AllIfsAndElse); 20514 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always", 20515 AllowShortIfStatementsOnASingleLine, 20516 FormatStyle::SIS_OnlyFirstIf); 20517 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false", 20518 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never); 20519 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true", 20520 AllowShortIfStatementsOnASingleLine, 20521 FormatStyle::SIS_WithoutElse); 20522 20523 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 20524 CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock, 20525 FormatStyle::IEBS_AfterExternBlock); 20526 CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock, 20527 FormatStyle::IEBS_Indent); 20528 CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock, 20529 FormatStyle::IEBS_NoIndent); 20530 CHECK_PARSE("IndentExternBlock: true", IndentExternBlock, 20531 FormatStyle::IEBS_Indent); 20532 CHECK_PARSE("IndentExternBlock: false", IndentExternBlock, 20533 FormatStyle::IEBS_NoIndent); 20534 20535 Style.BitFieldColonSpacing = FormatStyle::BFCS_None; 20536 CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing, 20537 FormatStyle::BFCS_Both); 20538 CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing, 20539 FormatStyle::BFCS_None); 20540 CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing, 20541 FormatStyle::BFCS_Before); 20542 CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing, 20543 FormatStyle::BFCS_After); 20544 20545 Style.SortJavaStaticImport = FormatStyle::SJSIO_Before; 20546 CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport, 20547 FormatStyle::SJSIO_After); 20548 CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport, 20549 FormatStyle::SJSIO_Before); 20550 20551 // FIXME: This is required because parsing a configuration simply overwrites 20552 // the first N elements of the list instead of resetting it. 20553 Style.ForEachMacros.clear(); 20554 std::vector<std::string> BoostForeach; 20555 BoostForeach.push_back("BOOST_FOREACH"); 20556 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach); 20557 std::vector<std::string> BoostAndQForeach; 20558 BoostAndQForeach.push_back("BOOST_FOREACH"); 20559 BoostAndQForeach.push_back("Q_FOREACH"); 20560 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros, 20561 BoostAndQForeach); 20562 20563 Style.IfMacros.clear(); 20564 std::vector<std::string> CustomIfs; 20565 CustomIfs.push_back("MYIF"); 20566 CHECK_PARSE("IfMacros: [MYIF]", IfMacros, CustomIfs); 20567 20568 Style.AttributeMacros.clear(); 20569 CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros, 20570 std::vector<std::string>{"__capability"}); 20571 CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros, 20572 std::vector<std::string>({"attr1", "attr2"})); 20573 20574 Style.StatementAttributeLikeMacros.clear(); 20575 CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]", 20576 StatementAttributeLikeMacros, 20577 std::vector<std::string>({"emit", "Q_EMIT"})); 20578 20579 Style.StatementMacros.clear(); 20580 CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros, 20581 std::vector<std::string>{"QUNUSED"}); 20582 CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros, 20583 std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"})); 20584 20585 Style.NamespaceMacros.clear(); 20586 CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros, 20587 std::vector<std::string>{"TESTSUITE"}); 20588 CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros, 20589 std::vector<std::string>({"TESTSUITE", "SUITE"})); 20590 20591 Style.WhitespaceSensitiveMacros.clear(); 20592 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]", 20593 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"}); 20594 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]", 20595 WhitespaceSensitiveMacros, 20596 std::vector<std::string>({"STRINGIZE", "ASSERT"})); 20597 Style.WhitespaceSensitiveMacros.clear(); 20598 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']", 20599 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"}); 20600 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']", 20601 WhitespaceSensitiveMacros, 20602 std::vector<std::string>({"STRINGIZE", "ASSERT"})); 20603 20604 Style.IncludeStyle.IncludeCategories.clear(); 20605 std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = { 20606 {"abc/.*", 2, 0, false}, {".*", 1, 0, true}}; 20607 CHECK_PARSE("IncludeCategories:\n" 20608 " - Regex: abc/.*\n" 20609 " Priority: 2\n" 20610 " - Regex: .*\n" 20611 " Priority: 1\n" 20612 " CaseSensitive: true\n", 20613 IncludeStyle.IncludeCategories, ExpectedCategories); 20614 CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex, 20615 "abc$"); 20616 CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'", 20617 IncludeStyle.IncludeIsMainSourceRegex, "abc$"); 20618 20619 Style.SortIncludes = FormatStyle::SI_Never; 20620 CHECK_PARSE("SortIncludes: true", SortIncludes, 20621 FormatStyle::SI_CaseSensitive); 20622 CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never); 20623 CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes, 20624 FormatStyle::SI_CaseInsensitive); 20625 CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes, 20626 FormatStyle::SI_CaseSensitive); 20627 CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never); 20628 20629 Style.RawStringFormats.clear(); 20630 std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = { 20631 { 20632 FormatStyle::LK_TextProto, 20633 {"pb", "proto"}, 20634 {"PARSE_TEXT_PROTO"}, 20635 /*CanonicalDelimiter=*/"", 20636 "llvm", 20637 }, 20638 { 20639 FormatStyle::LK_Cpp, 20640 {"cc", "cpp"}, 20641 {"C_CODEBLOCK", "CPPEVAL"}, 20642 /*CanonicalDelimiter=*/"cc", 20643 /*BasedOnStyle=*/"", 20644 }, 20645 }; 20646 20647 CHECK_PARSE("RawStringFormats:\n" 20648 " - Language: TextProto\n" 20649 " Delimiters:\n" 20650 " - 'pb'\n" 20651 " - 'proto'\n" 20652 " EnclosingFunctions:\n" 20653 " - 'PARSE_TEXT_PROTO'\n" 20654 " BasedOnStyle: llvm\n" 20655 " - Language: Cpp\n" 20656 " Delimiters:\n" 20657 " - 'cc'\n" 20658 " - 'cpp'\n" 20659 " EnclosingFunctions:\n" 20660 " - 'C_CODEBLOCK'\n" 20661 " - 'CPPEVAL'\n" 20662 " CanonicalDelimiter: 'cc'", 20663 RawStringFormats, ExpectedRawStringFormats); 20664 20665 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20666 " Minimum: 0\n" 20667 " Maximum: 0", 20668 SpacesInLineCommentPrefix.Minimum, 0u); 20669 EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u); 20670 Style.SpacesInLineCommentPrefix.Minimum = 1; 20671 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20672 " Minimum: 2", 20673 SpacesInLineCommentPrefix.Minimum, 0u); 20674 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20675 " Maximum: -1", 20676 SpacesInLineCommentPrefix.Maximum, -1u); 20677 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20678 " Minimum: 2", 20679 SpacesInLineCommentPrefix.Minimum, 2u); 20680 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20681 " Maximum: 1", 20682 SpacesInLineCommentPrefix.Maximum, 1u); 20683 EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u); 20684 20685 Style.SpacesInAngles = FormatStyle::SIAS_Always; 20686 CHECK_PARSE("SpacesInAngles: Never", SpacesInAngles, FormatStyle::SIAS_Never); 20687 CHECK_PARSE("SpacesInAngles: Always", SpacesInAngles, 20688 FormatStyle::SIAS_Always); 20689 CHECK_PARSE("SpacesInAngles: Leave", SpacesInAngles, FormatStyle::SIAS_Leave); 20690 // For backward compatibility: 20691 CHECK_PARSE("SpacesInAngles: false", SpacesInAngles, FormatStyle::SIAS_Never); 20692 CHECK_PARSE("SpacesInAngles: true", SpacesInAngles, FormatStyle::SIAS_Always); 20693 20694 CHECK_PARSE("RequiresClausePosition: WithPreceding", RequiresClausePosition, 20695 FormatStyle::RCPS_WithPreceding); 20696 CHECK_PARSE("RequiresClausePosition: WithFollowing", RequiresClausePosition, 20697 FormatStyle::RCPS_WithFollowing); 20698 CHECK_PARSE("RequiresClausePosition: SingleLine", RequiresClausePosition, 20699 FormatStyle::RCPS_SingleLine); 20700 CHECK_PARSE("RequiresClausePosition: OwnLine", RequiresClausePosition, 20701 FormatStyle::RCPS_OwnLine); 20702 20703 CHECK_PARSE("BreakBeforeConceptDeclarations: Never", 20704 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Never); 20705 CHECK_PARSE("BreakBeforeConceptDeclarations: Always", 20706 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always); 20707 CHECK_PARSE("BreakBeforeConceptDeclarations: Allowed", 20708 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed); 20709 // For backward compatibility: 20710 CHECK_PARSE("BreakBeforeConceptDeclarations: true", 20711 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always); 20712 CHECK_PARSE("BreakBeforeConceptDeclarations: false", 20713 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed); 20714 } 20715 20716 TEST_F(FormatTest, ParsesConfigurationWithLanguages) { 20717 FormatStyle Style = {}; 20718 Style.Language = FormatStyle::LK_Cpp; 20719 CHECK_PARSE("Language: Cpp\n" 20720 "IndentWidth: 12", 20721 IndentWidth, 12u); 20722 EXPECT_EQ(parseConfiguration("Language: JavaScript\n" 20723 "IndentWidth: 34", 20724 &Style), 20725 ParseError::Unsuitable); 20726 FormatStyle BinPackedTCS = {}; 20727 BinPackedTCS.Language = FormatStyle::LK_JavaScript; 20728 EXPECT_EQ(parseConfiguration("BinPackArguments: true\n" 20729 "InsertTrailingCommas: Wrapped", 20730 &BinPackedTCS), 20731 ParseError::BinPackTrailingCommaConflict); 20732 EXPECT_EQ(12u, Style.IndentWidth); 20733 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u); 20734 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language); 20735 20736 Style.Language = FormatStyle::LK_JavaScript; 20737 CHECK_PARSE("Language: JavaScript\n" 20738 "IndentWidth: 12", 20739 IndentWidth, 12u); 20740 CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u); 20741 EXPECT_EQ(parseConfiguration("Language: Cpp\n" 20742 "IndentWidth: 34", 20743 &Style), 20744 ParseError::Unsuitable); 20745 EXPECT_EQ(23u, Style.IndentWidth); 20746 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u); 20747 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language); 20748 20749 CHECK_PARSE("BasedOnStyle: LLVM\n" 20750 "IndentWidth: 67", 20751 IndentWidth, 67u); 20752 20753 CHECK_PARSE("---\n" 20754 "Language: JavaScript\n" 20755 "IndentWidth: 12\n" 20756 "---\n" 20757 "Language: Cpp\n" 20758 "IndentWidth: 34\n" 20759 "...\n", 20760 IndentWidth, 12u); 20761 20762 Style.Language = FormatStyle::LK_Cpp; 20763 CHECK_PARSE("---\n" 20764 "Language: JavaScript\n" 20765 "IndentWidth: 12\n" 20766 "---\n" 20767 "Language: Cpp\n" 20768 "IndentWidth: 34\n" 20769 "...\n", 20770 IndentWidth, 34u); 20771 CHECK_PARSE("---\n" 20772 "IndentWidth: 78\n" 20773 "---\n" 20774 "Language: JavaScript\n" 20775 "IndentWidth: 56\n" 20776 "...\n", 20777 IndentWidth, 78u); 20778 20779 Style.ColumnLimit = 123; 20780 Style.IndentWidth = 234; 20781 Style.BreakBeforeBraces = FormatStyle::BS_Linux; 20782 Style.TabWidth = 345; 20783 EXPECT_FALSE(parseConfiguration("---\n" 20784 "IndentWidth: 456\n" 20785 "BreakBeforeBraces: Allman\n" 20786 "---\n" 20787 "Language: JavaScript\n" 20788 "IndentWidth: 111\n" 20789 "TabWidth: 111\n" 20790 "---\n" 20791 "Language: Cpp\n" 20792 "BreakBeforeBraces: Stroustrup\n" 20793 "TabWidth: 789\n" 20794 "...\n", 20795 &Style)); 20796 EXPECT_EQ(123u, Style.ColumnLimit); 20797 EXPECT_EQ(456u, Style.IndentWidth); 20798 EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces); 20799 EXPECT_EQ(789u, Style.TabWidth); 20800 20801 EXPECT_EQ(parseConfiguration("---\n" 20802 "Language: JavaScript\n" 20803 "IndentWidth: 56\n" 20804 "---\n" 20805 "IndentWidth: 78\n" 20806 "...\n", 20807 &Style), 20808 ParseError::Error); 20809 EXPECT_EQ(parseConfiguration("---\n" 20810 "Language: JavaScript\n" 20811 "IndentWidth: 56\n" 20812 "---\n" 20813 "Language: JavaScript\n" 20814 "IndentWidth: 78\n" 20815 "...\n", 20816 &Style), 20817 ParseError::Error); 20818 20819 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language); 20820 } 20821 20822 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) { 20823 FormatStyle Style = {}; 20824 Style.Language = FormatStyle::LK_JavaScript; 20825 Style.BreakBeforeTernaryOperators = true; 20826 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value()); 20827 EXPECT_FALSE(Style.BreakBeforeTernaryOperators); 20828 20829 Style.BreakBeforeTernaryOperators = true; 20830 EXPECT_EQ(0, parseConfiguration("---\n" 20831 "BasedOnStyle: Google\n" 20832 "---\n" 20833 "Language: JavaScript\n" 20834 "IndentWidth: 76\n" 20835 "...\n", 20836 &Style) 20837 .value()); 20838 EXPECT_FALSE(Style.BreakBeforeTernaryOperators); 20839 EXPECT_EQ(76u, Style.IndentWidth); 20840 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language); 20841 } 20842 20843 TEST_F(FormatTest, ConfigurationRoundTripTest) { 20844 FormatStyle Style = getLLVMStyle(); 20845 std::string YAML = configurationAsText(Style); 20846 FormatStyle ParsedStyle = {}; 20847 ParsedStyle.Language = FormatStyle::LK_Cpp; 20848 EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value()); 20849 EXPECT_EQ(Style, ParsedStyle); 20850 } 20851 20852 TEST_F(FormatTest, WorksFor8bitEncodings) { 20853 EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n" 20854 "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n" 20855 "\"\xe7\xe8\xec\xed\xfe\xfe \"\n" 20856 "\"\xef\xee\xf0\xf3...\"", 20857 format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 " 20858 "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe " 20859 "\xef\xee\xf0\xf3...\"", 20860 getLLVMStyleWithColumns(12))); 20861 } 20862 20863 TEST_F(FormatTest, HandlesUTF8BOM) { 20864 EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf")); 20865 EXPECT_EQ("\xef\xbb\xbf#include <iostream>", 20866 format("\xef\xbb\xbf#include <iostream>")); 20867 EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>", 20868 format("\xef\xbb\xbf\n#include <iostream>")); 20869 } 20870 20871 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers. 20872 #if !defined(_MSC_VER) 20873 20874 TEST_F(FormatTest, CountsUTF8CharactersProperly) { 20875 verifyFormat("\"Однажды в студёную зимнюю пору...\"", 20876 getLLVMStyleWithColumns(35)); 20877 verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"", 20878 getLLVMStyleWithColumns(31)); 20879 verifyFormat("// Однажды в студёную зимнюю пору...", 20880 getLLVMStyleWithColumns(36)); 20881 verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32)); 20882 verifyFormat("/* Однажды в студёную зимнюю пору... */", 20883 getLLVMStyleWithColumns(39)); 20884 verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */", 20885 getLLVMStyleWithColumns(35)); 20886 } 20887 20888 TEST_F(FormatTest, SplitsUTF8Strings) { 20889 // Non-printable characters' width is currently considered to be the length in 20890 // bytes in UTF8. The characters can be displayed in very different manner 20891 // (zero-width, single width with a substitution glyph, expanded to their code 20892 // (e.g. "<8d>"), so there's no single correct way to handle them. 20893 EXPECT_EQ("\"aaaaÄ\"\n" 20894 "\"\xc2\x8d\";", 20895 format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10))); 20896 EXPECT_EQ("\"aaaaaaaÄ\"\n" 20897 "\"\xc2\x8d\";", 20898 format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10))); 20899 EXPECT_EQ("\"Однажды, в \"\n" 20900 "\"студёную \"\n" 20901 "\"зимнюю \"\n" 20902 "\"пору,\"", 20903 format("\"Однажды, в студёную зимнюю пору,\"", 20904 getLLVMStyleWithColumns(13))); 20905 EXPECT_EQ( 20906 "\"一 二 三 \"\n" 20907 "\"四 五六 \"\n" 20908 "\"七 八 九 \"\n" 20909 "\"十\"", 20910 format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11))); 20911 EXPECT_EQ("\"一\t\"\n" 20912 "\"二 \t\"\n" 20913 "\"三 四 \"\n" 20914 "\"五\t\"\n" 20915 "\"六 \t\"\n" 20916 "\"七 \"\n" 20917 "\"八九十\tqq\"", 20918 format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"", 20919 getLLVMStyleWithColumns(11))); 20920 20921 // UTF8 character in an escape sequence. 20922 EXPECT_EQ("\"aaaaaa\"\n" 20923 "\"\\\xC2\x8D\"", 20924 format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10))); 20925 } 20926 20927 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) { 20928 EXPECT_EQ("const char *sssss =\n" 20929 " \"一二三四五六七八\\\n" 20930 " 九 十\";", 20931 format("const char *sssss = \"一二三四五六七八\\\n" 20932 " 九 十\";", 20933 getLLVMStyleWithColumns(30))); 20934 } 20935 20936 TEST_F(FormatTest, SplitsUTF8LineComments) { 20937 EXPECT_EQ("// aaaaÄ\xc2\x8d", 20938 format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10))); 20939 EXPECT_EQ("// Я из лесу\n" 20940 "// вышел; был\n" 20941 "// сильный\n" 20942 "// мороз.", 20943 format("// Я из лесу вышел; был сильный мороз.", 20944 getLLVMStyleWithColumns(13))); 20945 EXPECT_EQ("// 一二三\n" 20946 "// 四五六七\n" 20947 "// 八 九\n" 20948 "// 十", 20949 format("// 一二三 四五六七 八 九 十", getLLVMStyleWithColumns(9))); 20950 } 20951 20952 TEST_F(FormatTest, SplitsUTF8BlockComments) { 20953 EXPECT_EQ("/* Гляжу,\n" 20954 " * поднимается\n" 20955 " * медленно в\n" 20956 " * гору\n" 20957 " * Лошадка,\n" 20958 " * везущая\n" 20959 " * хворосту\n" 20960 " * воз. */", 20961 format("/* Гляжу, поднимается медленно в гору\n" 20962 " * Лошадка, везущая хворосту воз. */", 20963 getLLVMStyleWithColumns(13))); 20964 EXPECT_EQ( 20965 "/* 一二三\n" 20966 " * 四五六七\n" 20967 " * 八 九\n" 20968 " * 十 */", 20969 format("/* 一二三 四五六七 八 九 十 */", getLLVMStyleWithColumns(9))); 20970 EXPECT_EQ("/* \n" 20971 " * \n" 20972 " * - */", 20973 format("/* - */", getLLVMStyleWithColumns(12))); 20974 } 20975 20976 #endif // _MSC_VER 20977 20978 TEST_F(FormatTest, ConstructorInitializerIndentWidth) { 20979 FormatStyle Style = getLLVMStyle(); 20980 20981 Style.ConstructorInitializerIndentWidth = 4; 20982 verifyFormat( 20983 "SomeClass::Constructor()\n" 20984 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20985 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20986 Style); 20987 20988 Style.ConstructorInitializerIndentWidth = 2; 20989 verifyFormat( 20990 "SomeClass::Constructor()\n" 20991 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20992 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20993 Style); 20994 20995 Style.ConstructorInitializerIndentWidth = 0; 20996 verifyFormat( 20997 "SomeClass::Constructor()\n" 20998 ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20999 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 21000 Style); 21001 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 21002 verifyFormat( 21003 "SomeLongTemplateVariableName<\n" 21004 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>", 21005 Style); 21006 verifyFormat("bool smaller = 1 < " 21007 "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 21008 " " 21009 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 21010 Style); 21011 21012 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 21013 verifyFormat("SomeClass::Constructor() :\n" 21014 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n" 21015 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}", 21016 Style); 21017 } 21018 21019 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) { 21020 FormatStyle Style = getLLVMStyle(); 21021 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 21022 Style.ConstructorInitializerIndentWidth = 4; 21023 verifyFormat("SomeClass::Constructor()\n" 21024 " : a(a)\n" 21025 " , b(b)\n" 21026 " , c(c) {}", 21027 Style); 21028 verifyFormat("SomeClass::Constructor()\n" 21029 " : a(a) {}", 21030 Style); 21031 21032 Style.ColumnLimit = 0; 21033 verifyFormat("SomeClass::Constructor()\n" 21034 " : a(a) {}", 21035 Style); 21036 verifyFormat("SomeClass::Constructor() noexcept\n" 21037 " : a(a) {}", 21038 Style); 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) {\n" 21046 " foo();\n" 21047 " bar();\n" 21048 "}", 21049 Style); 21050 21051 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 21052 verifyFormat("SomeClass::Constructor()\n" 21053 " : a(a)\n" 21054 " , b(b)\n" 21055 " , c(c) {\n}", 21056 Style); 21057 verifyFormat("SomeClass::Constructor()\n" 21058 " : a(a) {\n}", 21059 Style); 21060 21061 Style.ColumnLimit = 80; 21062 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 21063 Style.ConstructorInitializerIndentWidth = 2; 21064 verifyFormat("SomeClass::Constructor()\n" 21065 " : a(a)\n" 21066 " , b(b)\n" 21067 " , c(c) {}", 21068 Style); 21069 21070 Style.ConstructorInitializerIndentWidth = 0; 21071 verifyFormat("SomeClass::Constructor()\n" 21072 ": a(a)\n" 21073 ", b(b)\n" 21074 ", c(c) {}", 21075 Style); 21076 21077 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 21078 Style.ConstructorInitializerIndentWidth = 4; 21079 verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style); 21080 verifyFormat( 21081 "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n", 21082 Style); 21083 verifyFormat( 21084 "SomeClass::Constructor()\n" 21085 " : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}", 21086 Style); 21087 Style.ConstructorInitializerIndentWidth = 4; 21088 Style.ColumnLimit = 60; 21089 verifyFormat("SomeClass::Constructor()\n" 21090 " : aaaaaaaa(aaaaaaaa)\n" 21091 " , aaaaaaaa(aaaaaaaa)\n" 21092 " , aaaaaaaa(aaaaaaaa) {}", 21093 Style); 21094 } 21095 21096 TEST_F(FormatTest, ConstructorInitializersWithPreprocessorDirective) { 21097 FormatStyle Style = getLLVMStyle(); 21098 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 21099 Style.ConstructorInitializerIndentWidth = 4; 21100 verifyFormat("SomeClass::Constructor()\n" 21101 " : a{a}\n" 21102 " , b{b} {}", 21103 Style); 21104 verifyFormat("SomeClass::Constructor()\n" 21105 " : a{a}\n" 21106 "#if CONDITION\n" 21107 " , b{b}\n" 21108 "#endif\n" 21109 "{\n}", 21110 Style); 21111 Style.ConstructorInitializerIndentWidth = 2; 21112 verifyFormat("SomeClass::Constructor()\n" 21113 "#if CONDITION\n" 21114 " : a{a}\n" 21115 "#endif\n" 21116 " , b{b}\n" 21117 " , c{c} {\n}", 21118 Style); 21119 Style.ConstructorInitializerIndentWidth = 0; 21120 verifyFormat("SomeClass::Constructor()\n" 21121 ": a{a}\n" 21122 "#ifdef CONDITION\n" 21123 ", b{b}\n" 21124 "#else\n" 21125 ", c{c}\n" 21126 "#endif\n" 21127 ", d{d} {\n}", 21128 Style); 21129 Style.ConstructorInitializerIndentWidth = 4; 21130 verifyFormat("SomeClass::Constructor()\n" 21131 " : a{a}\n" 21132 "#if WINDOWS\n" 21133 "#if DEBUG\n" 21134 " , b{0}\n" 21135 "#else\n" 21136 " , b{1}\n" 21137 "#endif\n" 21138 "#else\n" 21139 "#if DEBUG\n" 21140 " , b{2}\n" 21141 "#else\n" 21142 " , b{3}\n" 21143 "#endif\n" 21144 "#endif\n" 21145 "{\n}", 21146 Style); 21147 verifyFormat("SomeClass::Constructor()\n" 21148 " : a{a}\n" 21149 "#if WINDOWS\n" 21150 " , b{0}\n" 21151 "#if DEBUG\n" 21152 " , c{0}\n" 21153 "#else\n" 21154 " , c{1}\n" 21155 "#endif\n" 21156 "#else\n" 21157 "#if DEBUG\n" 21158 " , c{2}\n" 21159 "#else\n" 21160 " , c{3}\n" 21161 "#endif\n" 21162 " , b{1}\n" 21163 "#endif\n" 21164 "{\n}", 21165 Style); 21166 } 21167 21168 TEST_F(FormatTest, Destructors) { 21169 verifyFormat("void F(int &i) { i.~int(); }"); 21170 verifyFormat("void F(int &i) { i->~int(); }"); 21171 } 21172 21173 TEST_F(FormatTest, FormatsWithWebKitStyle) { 21174 FormatStyle Style = getWebKitStyle(); 21175 21176 // Don't indent in outer namespaces. 21177 verifyFormat("namespace outer {\n" 21178 "int i;\n" 21179 "namespace inner {\n" 21180 " int i;\n" 21181 "} // namespace inner\n" 21182 "} // namespace outer\n" 21183 "namespace other_outer {\n" 21184 "int i;\n" 21185 "}", 21186 Style); 21187 21188 // Don't indent case labels. 21189 verifyFormat("switch (variable) {\n" 21190 "case 1:\n" 21191 "case 2:\n" 21192 " doSomething();\n" 21193 " break;\n" 21194 "default:\n" 21195 " ++variable;\n" 21196 "}", 21197 Style); 21198 21199 // Wrap before binary operators. 21200 EXPECT_EQ("void f()\n" 21201 "{\n" 21202 " if (aaaaaaaaaaaaaaaa\n" 21203 " && bbbbbbbbbbbbbbbbbbbbbbbb\n" 21204 " && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n" 21205 " return;\n" 21206 "}", 21207 format("void f() {\n" 21208 "if (aaaaaaaaaaaaaaaa\n" 21209 "&& bbbbbbbbbbbbbbbbbbbbbbbb\n" 21210 "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n" 21211 "return;\n" 21212 "}", 21213 Style)); 21214 21215 // Allow functions on a single line. 21216 verifyFormat("void f() { return; }", Style); 21217 21218 // Allow empty blocks on a single line and insert a space in empty blocks. 21219 EXPECT_EQ("void f() { }", format("void f() {}", Style)); 21220 EXPECT_EQ("while (true) { }", format("while (true) {}", Style)); 21221 // However, don't merge non-empty short loops. 21222 EXPECT_EQ("while (true) {\n" 21223 " continue;\n" 21224 "}", 21225 format("while (true) { continue; }", Style)); 21226 21227 // Constructor initializers are formatted one per line with the "," on the 21228 // new line. 21229 verifyFormat("Constructor()\n" 21230 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 21231 " , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n" 21232 " aaaaaaaaaaaaaa)\n" 21233 " , aaaaaaaaaaaaaaaaaaaaaaa()\n" 21234 "{\n" 21235 "}", 21236 Style); 21237 verifyFormat("SomeClass::Constructor()\n" 21238 " : a(a)\n" 21239 "{\n" 21240 "}", 21241 Style); 21242 EXPECT_EQ("SomeClass::Constructor()\n" 21243 " : a(a)\n" 21244 "{\n" 21245 "}", 21246 format("SomeClass::Constructor():a(a){}", Style)); 21247 verifyFormat("SomeClass::Constructor()\n" 21248 " : a(a)\n" 21249 " , b(b)\n" 21250 " , c(c)\n" 21251 "{\n" 21252 "}", 21253 Style); 21254 verifyFormat("SomeClass::Constructor()\n" 21255 " : a(a)\n" 21256 "{\n" 21257 " foo();\n" 21258 " bar();\n" 21259 "}", 21260 Style); 21261 21262 // Access specifiers should be aligned left. 21263 verifyFormat("class C {\n" 21264 "public:\n" 21265 " int i;\n" 21266 "};", 21267 Style); 21268 21269 // Do not align comments. 21270 verifyFormat("int a; // Do not\n" 21271 "double b; // align comments.", 21272 Style); 21273 21274 // Do not align operands. 21275 EXPECT_EQ("ASSERT(aaaa\n" 21276 " || bbbb);", 21277 format("ASSERT ( aaaa\n||bbbb);", Style)); 21278 21279 // Accept input's line breaks. 21280 EXPECT_EQ("if (aaaaaaaaaaaaaaa\n" 21281 " || bbbbbbbbbbbbbbb) {\n" 21282 " i++;\n" 21283 "}", 21284 format("if (aaaaaaaaaaaaaaa\n" 21285 "|| bbbbbbbbbbbbbbb) { i++; }", 21286 Style)); 21287 EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n" 21288 " i++;\n" 21289 "}", 21290 format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style)); 21291 21292 // Don't automatically break all macro definitions (llvm.org/PR17842). 21293 verifyFormat("#define aNumber 10", Style); 21294 // However, generally keep the line breaks that the user authored. 21295 EXPECT_EQ("#define aNumber \\\n" 21296 " 10", 21297 format("#define aNumber \\\n" 21298 " 10", 21299 Style)); 21300 21301 // Keep empty and one-element array literals on a single line. 21302 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n" 21303 " copyItems:YES];", 21304 format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n" 21305 "copyItems:YES];", 21306 Style)); 21307 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n" 21308 " copyItems:YES];", 21309 format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n" 21310 " copyItems:YES];", 21311 Style)); 21312 // FIXME: This does not seem right, there should be more indentation before 21313 // the array literal's entries. Nested blocks have the same problem. 21314 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n" 21315 " @\"a\",\n" 21316 " @\"a\"\n" 21317 "]\n" 21318 " copyItems:YES];", 21319 format("NSArray* a = [[NSArray alloc] initWithArray:@[\n" 21320 " @\"a\",\n" 21321 " @\"a\"\n" 21322 " ]\n" 21323 " copyItems:YES];", 21324 Style)); 21325 EXPECT_EQ( 21326 "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n" 21327 " copyItems:YES];", 21328 format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n" 21329 " copyItems:YES];", 21330 Style)); 21331 21332 verifyFormat("[self.a b:c c:d];", Style); 21333 EXPECT_EQ("[self.a b:c\n" 21334 " c:d];", 21335 format("[self.a b:c\n" 21336 "c:d];", 21337 Style)); 21338 } 21339 21340 TEST_F(FormatTest, FormatsLambdas) { 21341 verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n"); 21342 verifyFormat( 21343 "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n"); 21344 verifyFormat("int c = [&] { [=] { return b++; }(); }();\n"); 21345 verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n"); 21346 verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n"); 21347 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n"); 21348 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n"); 21349 verifyFormat("auto c = [a = [b = 42] {}] {};\n"); 21350 verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n"); 21351 verifyFormat("int x = f(*+[] {});"); 21352 verifyFormat("void f() {\n" 21353 " other(x.begin(), x.end(), [&](int, int) { return 1; });\n" 21354 "}\n"); 21355 verifyFormat("void f() {\n" 21356 " other(x.begin(), //\n" 21357 " x.end(), //\n" 21358 " [&](int, int) { return 1; });\n" 21359 "}\n"); 21360 verifyFormat("void f() {\n" 21361 " other.other.other.other.other(\n" 21362 " x.begin(), x.end(),\n" 21363 " [something, rather](int, int, int, int, int, int, int) { " 21364 "return 1; });\n" 21365 "}\n"); 21366 verifyFormat( 21367 "void f() {\n" 21368 " other.other.other.other.other(\n" 21369 " x.begin(), x.end(),\n" 21370 " [something, rather](int, int, int, int, int, int, int) {\n" 21371 " //\n" 21372 " });\n" 21373 "}\n"); 21374 verifyFormat("SomeFunction([]() { // A cool function...\n" 21375 " return 43;\n" 21376 "});"); 21377 EXPECT_EQ("SomeFunction([]() {\n" 21378 "#define A a\n" 21379 " return 43;\n" 21380 "});", 21381 format("SomeFunction([](){\n" 21382 "#define A a\n" 21383 "return 43;\n" 21384 "});")); 21385 verifyFormat("void f() {\n" 21386 " SomeFunction([](decltype(x), A *a) {});\n" 21387 " SomeFunction([](typeof(x), A *a) {});\n" 21388 " SomeFunction([](_Atomic(x), A *a) {});\n" 21389 " SomeFunction([](__underlying_type(x), A *a) {});\n" 21390 "}"); 21391 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 21392 " [](const aaaaaaaaaa &a) { return a; });"); 21393 verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n" 21394 " SomeOtherFunctioooooooooooooooooooooooooon();\n" 21395 "});"); 21396 verifyFormat("Constructor()\n" 21397 " : Field([] { // comment\n" 21398 " int i;\n" 21399 " }) {}"); 21400 verifyFormat("auto my_lambda = [](const string &some_parameter) {\n" 21401 " return some_parameter.size();\n" 21402 "};"); 21403 verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n" 21404 " [](const string &s) { return s; };"); 21405 verifyFormat("int i = aaaaaa ? 1 //\n" 21406 " : [] {\n" 21407 " return 2; //\n" 21408 " }();"); 21409 verifyFormat("llvm::errs() << \"number of twos is \"\n" 21410 " << std::count_if(v.begin(), v.end(), [](int x) {\n" 21411 " return x == 2; // force break\n" 21412 " });"); 21413 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 21414 " [=](int iiiiiiiiiiii) {\n" 21415 " return aaaaaaaaaaaaaaaaaaaaaaa !=\n" 21416 " aaaaaaaaaaaaaaaaaaaaaaa;\n" 21417 " });", 21418 getLLVMStyleWithColumns(60)); 21419 21420 verifyFormat("SomeFunction({[&] {\n" 21421 " // comment\n" 21422 " },\n" 21423 " [&] {\n" 21424 " // comment\n" 21425 " }});"); 21426 verifyFormat("SomeFunction({[&] {\n" 21427 " // comment\n" 21428 "}});"); 21429 verifyFormat( 21430 "virtual aaaaaaaaaaaaaaaa(\n" 21431 " std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n" 21432 " aaaaa aaaaaaaaa);"); 21433 21434 // Lambdas with return types. 21435 verifyFormat("int c = []() -> int { return 2; }();\n"); 21436 verifyFormat("int c = []() -> int * { return 2; }();\n"); 21437 verifyFormat("int c = []() -> vector<int> { return {2}; }();\n"); 21438 verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());"); 21439 verifyFormat("foo([]() noexcept -> int {});"); 21440 verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};"); 21441 verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};"); 21442 verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};"); 21443 verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};"); 21444 verifyFormat("[a, a]() -> a<1> {};"); 21445 verifyFormat("[]() -> foo<5 + 2> { return {}; };"); 21446 verifyFormat("[]() -> foo<5 - 2> { return {}; };"); 21447 verifyFormat("[]() -> foo<5 / 2> { return {}; };"); 21448 verifyFormat("[]() -> foo<5 * 2> { return {}; };"); 21449 verifyFormat("[]() -> foo<5 % 2> { return {}; };"); 21450 verifyFormat("[]() -> foo<5 << 2> { return {}; };"); 21451 verifyFormat("[]() -> foo<!5> { return {}; };"); 21452 verifyFormat("[]() -> foo<~5> { return {}; };"); 21453 verifyFormat("[]() -> foo<5 | 2> { return {}; };"); 21454 verifyFormat("[]() -> foo<5 || 2> { return {}; };"); 21455 verifyFormat("[]() -> foo<5 & 2> { return {}; };"); 21456 verifyFormat("[]() -> foo<5 && 2> { return {}; };"); 21457 verifyFormat("[]() -> foo<5 == 2> { return {}; };"); 21458 verifyFormat("[]() -> foo<5 != 2> { return {}; };"); 21459 verifyFormat("[]() -> foo<5 >= 2> { return {}; };"); 21460 verifyFormat("[]() -> foo<5 <= 2> { return {}; };"); 21461 verifyFormat("[]() -> foo<5 < 2> { return {}; };"); 21462 verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };"); 21463 verifyFormat("namespace bar {\n" 21464 "// broken:\n" 21465 "auto foo{[]() -> foo<5 + 2> { return {}; }};\n" 21466 "} // namespace bar"); 21467 verifyFormat("namespace bar {\n" 21468 "// broken:\n" 21469 "auto foo{[]() -> foo<5 - 2> { return {}; }};\n" 21470 "} // namespace bar"); 21471 verifyFormat("namespace bar {\n" 21472 "// broken:\n" 21473 "auto foo{[]() -> foo<5 / 2> { return {}; }};\n" 21474 "} // namespace bar"); 21475 verifyFormat("namespace bar {\n" 21476 "// broken:\n" 21477 "auto foo{[]() -> foo<5 * 2> { return {}; }};\n" 21478 "} // namespace bar"); 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> { return {}; }};\n" 21490 "} // namespace bar"); 21491 verifyFormat("namespace bar {\n" 21492 "// broken:\n" 21493 "auto foo{[]() -> foo<~5> { 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 & 2> { return {}; }};\n" 21506 "} // namespace bar"); 21507 verifyFormat("namespace bar {\n" 21508 "// broken:\n" 21509 "auto foo{[]() -> foo<5 && 2> { 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<2 ? 1 : 0> { return {}; }};\n" 21534 "} // namespace bar"); 21535 verifyFormat("[]() -> a<1> {};"); 21536 verifyFormat("[]() -> a<1> { ; };"); 21537 verifyFormat("[]() -> a<1> { ; }();"); 21538 verifyFormat("[a, a]() -> a<true> {};"); 21539 verifyFormat("[]() -> a<true> {};"); 21540 verifyFormat("[]() -> a<true> { ; };"); 21541 verifyFormat("[]() -> a<true> { ; }();"); 21542 verifyFormat("[a, a]() -> a<false> {};"); 21543 verifyFormat("[]() -> a<false> {};"); 21544 verifyFormat("[]() -> a<false> { ; };"); 21545 verifyFormat("[]() -> a<false> { ; }();"); 21546 verifyFormat("auto foo{[]() -> foo<false> { ; }};"); 21547 verifyFormat("namespace bar {\n" 21548 "auto foo{[]() -> foo<false> { ; }};\n" 21549 "} // namespace bar"); 21550 verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n" 21551 " int j) -> int {\n" 21552 " return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n" 21553 "};"); 21554 verifyFormat( 21555 "aaaaaaaaaaaaaaaaaaaaaa(\n" 21556 " [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n" 21557 " return aaaaaaaaaaaaaaaaa;\n" 21558 " });", 21559 getLLVMStyleWithColumns(70)); 21560 verifyFormat("[]() //\n" 21561 " -> int {\n" 21562 " return 1; //\n" 21563 "};"); 21564 verifyFormat("[]() -> Void<T...> {};"); 21565 verifyFormat("[a, b]() -> Tuple<T...> { return {}; };"); 21566 verifyFormat("SomeFunction({[]() -> int[] { return {}; }});"); 21567 verifyFormat("SomeFunction({[]() -> int *[] { return {}; }});"); 21568 verifyFormat("SomeFunction({[]() -> int (*)[] { return {}; }});"); 21569 verifyFormat("SomeFunction({[]() -> ns::type<int (*)[]> { return {}; }});"); 21570 verifyFormat("return int{[x = x]() { return x; }()};"); 21571 21572 // Lambdas with explicit template argument lists. 21573 verifyFormat( 21574 "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n"); 21575 verifyFormat("auto L = []<class T>(T) {\n" 21576 " {\n" 21577 " f();\n" 21578 " g();\n" 21579 " }\n" 21580 "};\n"); 21581 verifyFormat("auto L = []<class... T>(T...) {\n" 21582 " {\n" 21583 " f();\n" 21584 " g();\n" 21585 " }\n" 21586 "};\n"); 21587 verifyFormat("auto L = []<typename... T>(T...) {\n" 21588 " {\n" 21589 " f();\n" 21590 " g();\n" 21591 " }\n" 21592 "};\n"); 21593 verifyFormat("auto L = []<template <typename...> class T>(T...) {\n" 21594 " {\n" 21595 " f();\n" 21596 " g();\n" 21597 " }\n" 21598 "};\n"); 21599 verifyFormat("auto L = []</*comment*/ class... T>(T...) {\n" 21600 " {\n" 21601 " f();\n" 21602 " g();\n" 21603 " }\n" 21604 "};\n"); 21605 21606 // Multiple lambdas in the same parentheses change indentation rules. These 21607 // lambdas are forced to start on new lines. 21608 verifyFormat("SomeFunction(\n" 21609 " []() {\n" 21610 " //\n" 21611 " },\n" 21612 " []() {\n" 21613 " //\n" 21614 " });"); 21615 21616 // A lambda passed as arg0 is always pushed to the next line. 21617 verifyFormat("SomeFunction(\n" 21618 " [this] {\n" 21619 " //\n" 21620 " },\n" 21621 " 1);\n"); 21622 21623 // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like 21624 // the arg0 case above. 21625 auto Style = getGoogleStyle(); 21626 Style.BinPackArguments = false; 21627 verifyFormat("SomeFunction(\n" 21628 " a,\n" 21629 " [this] {\n" 21630 " //\n" 21631 " },\n" 21632 " b);\n", 21633 Style); 21634 verifyFormat("SomeFunction(\n" 21635 " a,\n" 21636 " [this] {\n" 21637 " //\n" 21638 " },\n" 21639 " b);\n"); 21640 21641 // A lambda with a very long line forces arg0 to be pushed out irrespective of 21642 // the BinPackArguments value (as long as the code is wide enough). 21643 verifyFormat( 21644 "something->SomeFunction(\n" 21645 " a,\n" 21646 " [this] {\n" 21647 " " 21648 "D0000000000000000000000000000000000000000000000000000000000001();\n" 21649 " },\n" 21650 " b);\n"); 21651 21652 // A multi-line lambda is pulled up as long as the introducer fits on the 21653 // previous line and there are no further args. 21654 verifyFormat("function(1, [this, that] {\n" 21655 " //\n" 21656 "});\n"); 21657 verifyFormat("function([this, that] {\n" 21658 " //\n" 21659 "});\n"); 21660 // FIXME: this format is not ideal and we should consider forcing the first 21661 // arg onto its own line. 21662 verifyFormat("function(a, b, c, //\n" 21663 " d, [this, that] {\n" 21664 " //\n" 21665 " });\n"); 21666 21667 // Multiple lambdas are treated correctly even when there is a short arg0. 21668 verifyFormat("SomeFunction(\n" 21669 " 1,\n" 21670 " [this] {\n" 21671 " //\n" 21672 " },\n" 21673 " [this] {\n" 21674 " //\n" 21675 " },\n" 21676 " 1);\n"); 21677 21678 // More complex introducers. 21679 verifyFormat("return [i, args...] {};"); 21680 21681 // Not lambdas. 21682 verifyFormat("constexpr char hello[]{\"hello\"};"); 21683 verifyFormat("double &operator[](int i) { return 0; }\n" 21684 "int i;"); 21685 verifyFormat("std::unique_ptr<int[]> foo() {}"); 21686 verifyFormat("int i = a[a][a]->f();"); 21687 verifyFormat("int i = (*b)[a]->f();"); 21688 21689 // Other corner cases. 21690 verifyFormat("void f() {\n" 21691 " bar([]() {} // Did not respect SpacesBeforeTrailingComments\n" 21692 " );\n" 21693 "}"); 21694 verifyFormat("auto k = *[](int *j) { return j; }(&i);"); 21695 21696 // Lambdas created through weird macros. 21697 verifyFormat("void f() {\n" 21698 " MACRO((const AA &a) { return 1; });\n" 21699 " MACRO((AA &a) { return 1; });\n" 21700 "}"); 21701 21702 verifyFormat("if (blah_blah(whatever, whatever, [] {\n" 21703 " doo_dah();\n" 21704 " doo_dah();\n" 21705 " })) {\n" 21706 "}"); 21707 verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n" 21708 " doo_dah();\n" 21709 " doo_dah();\n" 21710 " })) {\n" 21711 "}"); 21712 verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n" 21713 " doo_dah();\n" 21714 " doo_dah();\n" 21715 " })) {\n" 21716 "}"); 21717 verifyFormat("auto lambda = []() {\n" 21718 " int a = 2\n" 21719 "#if A\n" 21720 " + 2\n" 21721 "#endif\n" 21722 " ;\n" 21723 "};"); 21724 21725 // Lambdas with complex multiline introducers. 21726 verifyFormat( 21727 "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 21728 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n" 21729 " -> ::std::unordered_set<\n" 21730 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n" 21731 " //\n" 21732 " });"); 21733 21734 FormatStyle DoNotMerge = getLLVMStyle(); 21735 DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 21736 verifyFormat("auto c = []() {\n" 21737 " return b;\n" 21738 "};", 21739 "auto c = []() { return b; };", DoNotMerge); 21740 verifyFormat("auto c = []() {\n" 21741 "};", 21742 " auto c = []() {};", DoNotMerge); 21743 21744 FormatStyle MergeEmptyOnly = getLLVMStyle(); 21745 MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty; 21746 verifyFormat("auto c = []() {\n" 21747 " return b;\n" 21748 "};", 21749 "auto c = []() {\n" 21750 " return b;\n" 21751 " };", 21752 MergeEmptyOnly); 21753 verifyFormat("auto c = []() {};", 21754 "auto c = []() {\n" 21755 "};", 21756 MergeEmptyOnly); 21757 21758 FormatStyle MergeInline = getLLVMStyle(); 21759 MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline; 21760 verifyFormat("auto c = []() {\n" 21761 " return b;\n" 21762 "};", 21763 "auto c = []() { return b; };", MergeInline); 21764 verifyFormat("function([]() { return b; })", "function([]() { return b; })", 21765 MergeInline); 21766 verifyFormat("function([]() { return b; }, a)", 21767 "function([]() { return b; }, a)", MergeInline); 21768 verifyFormat("function(a, []() { return b; })", 21769 "function(a, []() { return b; })", MergeInline); 21770 21771 // Check option "BraceWrapping.BeforeLambdaBody" and different state of 21772 // AllowShortLambdasOnASingleLine 21773 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle(); 21774 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 21775 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 21776 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21777 FormatStyle::ShortLambdaStyle::SLS_None; 21778 verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n" 21779 " []()\n" 21780 " {\n" 21781 " return 17;\n" 21782 " });", 21783 LLVMWithBeforeLambdaBody); 21784 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n" 21785 " []()\n" 21786 " {\n" 21787 " });", 21788 LLVMWithBeforeLambdaBody); 21789 verifyFormat("auto fct_SLS_None = []()\n" 21790 "{\n" 21791 " return 17;\n" 21792 "};", 21793 LLVMWithBeforeLambdaBody); 21794 verifyFormat("TwoNestedLambdas_SLS_None(\n" 21795 " []()\n" 21796 " {\n" 21797 " return Call(\n" 21798 " []()\n" 21799 " {\n" 21800 " return 17;\n" 21801 " });\n" 21802 " });", 21803 LLVMWithBeforeLambdaBody); 21804 verifyFormat("void Fct() {\n" 21805 " return {[]()\n" 21806 " {\n" 21807 " return 17;\n" 21808 " }};\n" 21809 "}", 21810 LLVMWithBeforeLambdaBody); 21811 21812 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21813 FormatStyle::ShortLambdaStyle::SLS_Empty; 21814 verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n" 21815 " []()\n" 21816 " {\n" 21817 " return 17;\n" 21818 " });", 21819 LLVMWithBeforeLambdaBody); 21820 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});", 21821 LLVMWithBeforeLambdaBody); 21822 verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL" 21823 "ongFunctionName_SLS_Empty(\n" 21824 " []() {});", 21825 LLVMWithBeforeLambdaBody); 21826 verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n" 21827 " []()\n" 21828 " {\n" 21829 " return 17;\n" 21830 " });", 21831 LLVMWithBeforeLambdaBody); 21832 verifyFormat("auto fct_SLS_Empty = []()\n" 21833 "{\n" 21834 " return 17;\n" 21835 "};", 21836 LLVMWithBeforeLambdaBody); 21837 verifyFormat("TwoNestedLambdas_SLS_Empty(\n" 21838 " []()\n" 21839 " {\n" 21840 " return Call([]() {});\n" 21841 " });", 21842 LLVMWithBeforeLambdaBody); 21843 verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n" 21844 " []()\n" 21845 " {\n" 21846 " return Call([]() {});\n" 21847 " });", 21848 LLVMWithBeforeLambdaBody); 21849 verifyFormat( 21850 "FctWithLongLineInLambda_SLS_Empty(\n" 21851 " []()\n" 21852 " {\n" 21853 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21854 " AndShouldNotBeConsiderAsInline,\n" 21855 " LambdaBodyMustBeBreak);\n" 21856 " });", 21857 LLVMWithBeforeLambdaBody); 21858 21859 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21860 FormatStyle::ShortLambdaStyle::SLS_Inline; 21861 verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });", 21862 LLVMWithBeforeLambdaBody); 21863 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});", 21864 LLVMWithBeforeLambdaBody); 21865 verifyFormat("auto fct_SLS_Inline = []()\n" 21866 "{\n" 21867 " return 17;\n" 21868 "};", 21869 LLVMWithBeforeLambdaBody); 21870 verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return " 21871 "17; }); });", 21872 LLVMWithBeforeLambdaBody); 21873 verifyFormat( 21874 "FctWithLongLineInLambda_SLS_Inline(\n" 21875 " []()\n" 21876 " {\n" 21877 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21878 " AndShouldNotBeConsiderAsInline,\n" 21879 " LambdaBodyMustBeBreak);\n" 21880 " });", 21881 LLVMWithBeforeLambdaBody); 21882 verifyFormat("FctWithMultipleParams_SLS_Inline(" 21883 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n" 21884 " []() { return 17; });", 21885 LLVMWithBeforeLambdaBody); 21886 verifyFormat( 21887 "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });", 21888 LLVMWithBeforeLambdaBody); 21889 21890 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21891 FormatStyle::ShortLambdaStyle::SLS_All; 21892 verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });", 21893 LLVMWithBeforeLambdaBody); 21894 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});", 21895 LLVMWithBeforeLambdaBody); 21896 verifyFormat("auto fct_SLS_All = []() { return 17; };", 21897 LLVMWithBeforeLambdaBody); 21898 verifyFormat("FctWithOneParam_SLS_All(\n" 21899 " []()\n" 21900 " {\n" 21901 " // A cool function...\n" 21902 " return 43;\n" 21903 " });", 21904 LLVMWithBeforeLambdaBody); 21905 verifyFormat("FctWithMultipleParams_SLS_All(" 21906 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n" 21907 " []() { return 17; });", 21908 LLVMWithBeforeLambdaBody); 21909 verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });", 21910 LLVMWithBeforeLambdaBody); 21911 verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });", 21912 LLVMWithBeforeLambdaBody); 21913 verifyFormat( 21914 "FctWithLongLineInLambda_SLS_All(\n" 21915 " []()\n" 21916 " {\n" 21917 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21918 " AndShouldNotBeConsiderAsInline,\n" 21919 " LambdaBodyMustBeBreak);\n" 21920 " });", 21921 LLVMWithBeforeLambdaBody); 21922 verifyFormat( 21923 "auto fct_SLS_All = []()\n" 21924 "{\n" 21925 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21926 " AndShouldNotBeConsiderAsInline,\n" 21927 " LambdaBodyMustBeBreak);\n" 21928 "};", 21929 LLVMWithBeforeLambdaBody); 21930 LLVMWithBeforeLambdaBody.BinPackParameters = false; 21931 verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);", 21932 LLVMWithBeforeLambdaBody); 21933 verifyFormat( 21934 "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n" 21935 " FirstParam,\n" 21936 " SecondParam,\n" 21937 " ThirdParam,\n" 21938 " FourthParam);", 21939 LLVMWithBeforeLambdaBody); 21940 verifyFormat("FctWithLongLineInLambda_SLS_All(\n" 21941 " []() { return " 21942 "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n" 21943 " FirstParam,\n" 21944 " SecondParam,\n" 21945 " ThirdParam,\n" 21946 " FourthParam);", 21947 LLVMWithBeforeLambdaBody); 21948 verifyFormat( 21949 "FctWithLongLineInLambda_SLS_All(FirstParam,\n" 21950 " SecondParam,\n" 21951 " ThirdParam,\n" 21952 " FourthParam,\n" 21953 " []() { return SomeValueNotSoLong; });", 21954 LLVMWithBeforeLambdaBody); 21955 verifyFormat("FctWithLongLineInLambda_SLS_All(\n" 21956 " []()\n" 21957 " {\n" 21958 " return " 21959 "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB" 21960 "eConsiderAsInline;\n" 21961 " });", 21962 LLVMWithBeforeLambdaBody); 21963 verifyFormat( 21964 "FctWithLongLineInLambda_SLS_All(\n" 21965 " []()\n" 21966 " {\n" 21967 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21968 " AndShouldNotBeConsiderAsInline,\n" 21969 " LambdaBodyMustBeBreak);\n" 21970 " });", 21971 LLVMWithBeforeLambdaBody); 21972 verifyFormat("FctWithTwoParams_SLS_All(\n" 21973 " []()\n" 21974 " {\n" 21975 " // A cool function...\n" 21976 " return 43;\n" 21977 " },\n" 21978 " 87);", 21979 LLVMWithBeforeLambdaBody); 21980 verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);", 21981 LLVMWithBeforeLambdaBody); 21982 verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });", 21983 LLVMWithBeforeLambdaBody); 21984 verifyFormat( 21985 "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });", 21986 LLVMWithBeforeLambdaBody); 21987 verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; " 21988 "}); }, x);", 21989 LLVMWithBeforeLambdaBody); 21990 verifyFormat("TwoNestedLambdas_SLS_All(\n" 21991 " []()\n" 21992 " {\n" 21993 " // A cool function...\n" 21994 " return Call([]() { return 17; });\n" 21995 " });", 21996 LLVMWithBeforeLambdaBody); 21997 verifyFormat("TwoNestedLambdas_SLS_All(\n" 21998 " []()\n" 21999 " {\n" 22000 " return Call(\n" 22001 " []()\n" 22002 " {\n" 22003 " // A cool function...\n" 22004 " return 17;\n" 22005 " });\n" 22006 " });", 22007 LLVMWithBeforeLambdaBody); 22008 22009 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 22010 FormatStyle::ShortLambdaStyle::SLS_None; 22011 22012 verifyFormat("auto select = [this]() -> const Library::Object *\n" 22013 "{\n" 22014 " return MyAssignment::SelectFromList(this);\n" 22015 "};\n", 22016 LLVMWithBeforeLambdaBody); 22017 22018 verifyFormat("auto select = [this]() -> const Library::Object &\n" 22019 "{\n" 22020 " return MyAssignment::SelectFromList(this);\n" 22021 "};\n", 22022 LLVMWithBeforeLambdaBody); 22023 22024 verifyFormat("auto select = [this]() -> std::unique_ptr<Object>\n" 22025 "{\n" 22026 " return MyAssignment::SelectFromList(this);\n" 22027 "};\n", 22028 LLVMWithBeforeLambdaBody); 22029 22030 verifyFormat("namespace test {\n" 22031 "class Test {\n" 22032 "public:\n" 22033 " Test() = default;\n" 22034 "};\n" 22035 "} // namespace test", 22036 LLVMWithBeforeLambdaBody); 22037 22038 // Lambdas with different indentation styles. 22039 Style = getLLVMStyleWithColumns(100); 22040 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 22041 " return promise.then(\n" 22042 " [this, &someVariable, someObject = " 22043 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 22044 " return someObject.startAsyncAction().then(\n" 22045 " [this, &someVariable](AsyncActionResult result) " 22046 "mutable { result.processMore(); });\n" 22047 " });\n" 22048 "}\n", 22049 format("SomeResult doSomething(SomeObject promise) {\n" 22050 " return promise.then([this, &someVariable, someObject = " 22051 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 22052 " return someObject.startAsyncAction().then([this, " 22053 "&someVariable](AsyncActionResult result) mutable {\n" 22054 " result.processMore();\n" 22055 " });\n" 22056 " });\n" 22057 "}\n", 22058 Style)); 22059 Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope; 22060 verifyFormat("test() {\n" 22061 " ([]() -> {\n" 22062 " int b = 32;\n" 22063 " return 3;\n" 22064 " }).foo();\n" 22065 "}", 22066 Style); 22067 verifyFormat("test() {\n" 22068 " []() -> {\n" 22069 " int b = 32;\n" 22070 " return 3;\n" 22071 " }\n" 22072 "}", 22073 Style); 22074 verifyFormat("std::sort(v.begin(), v.end(),\n" 22075 " [](const auto &someLongArgumentName, const auto " 22076 "&someOtherLongArgumentName) {\n" 22077 " return someLongArgumentName.someMemberVariable < " 22078 "someOtherLongArgumentName.someMemberVariable;\n" 22079 "});", 22080 Style); 22081 verifyFormat("test() {\n" 22082 " (\n" 22083 " []() -> {\n" 22084 " int b = 32;\n" 22085 " return 3;\n" 22086 " },\n" 22087 " foo, bar)\n" 22088 " .foo();\n" 22089 "}", 22090 Style); 22091 verifyFormat("test() {\n" 22092 " ([]() -> {\n" 22093 " int b = 32;\n" 22094 " return 3;\n" 22095 " })\n" 22096 " .foo()\n" 22097 " .bar();\n" 22098 "}", 22099 Style); 22100 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 22101 " return promise.then(\n" 22102 " [this, &someVariable, someObject = " 22103 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 22104 " return someObject.startAsyncAction().then(\n" 22105 " [this, &someVariable](AsyncActionResult result) mutable { " 22106 "result.processMore(); });\n" 22107 " });\n" 22108 "}\n", 22109 format("SomeResult doSomething(SomeObject promise) {\n" 22110 " return promise.then([this, &someVariable, someObject = " 22111 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 22112 " return someObject.startAsyncAction().then([this, " 22113 "&someVariable](AsyncActionResult result) mutable {\n" 22114 " result.processMore();\n" 22115 " });\n" 22116 " });\n" 22117 "}\n", 22118 Style)); 22119 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 22120 " return promise.then([this, &someVariable] {\n" 22121 " return someObject.startAsyncAction().then(\n" 22122 " [this, &someVariable](AsyncActionResult result) mutable { " 22123 "result.processMore(); });\n" 22124 " });\n" 22125 "}\n", 22126 format("SomeResult doSomething(SomeObject promise) {\n" 22127 " return promise.then([this, &someVariable] {\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 Style = getGoogleStyle(); 22136 Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope; 22137 EXPECT_EQ("#define A \\\n" 22138 " [] { \\\n" 22139 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 22140 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n" 22141 " }", 22142 format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 22143 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }", 22144 Style)); 22145 // TODO: The current formatting has a minor issue that's not worth fixing 22146 // right now whereby the closing brace is indented relative to the signature 22147 // instead of being aligned. This only happens with macros. 22148 } 22149 22150 TEST_F(FormatTest, LambdaWithLineComments) { 22151 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle(); 22152 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 22153 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 22154 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 22155 FormatStyle::ShortLambdaStyle::SLS_All; 22156 22157 verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody); 22158 verifyFormat("auto k = []() // comment\n" 22159 "{ return; }", 22160 LLVMWithBeforeLambdaBody); 22161 verifyFormat("auto k = []() /* comment */ { return; }", 22162 LLVMWithBeforeLambdaBody); 22163 verifyFormat("auto k = []() /* comment */ /* comment */ { return; }", 22164 LLVMWithBeforeLambdaBody); 22165 verifyFormat("auto k = []() // X\n" 22166 "{ return; }", 22167 LLVMWithBeforeLambdaBody); 22168 verifyFormat( 22169 "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" 22170 "{ return; }", 22171 LLVMWithBeforeLambdaBody); 22172 22173 LLVMWithBeforeLambdaBody.ColumnLimit = 0; 22174 22175 verifyFormat("foo([]()\n" 22176 " {\n" 22177 " bar(); //\n" 22178 " return 1; // comment\n" 22179 " }());", 22180 "foo([]() {\n" 22181 " bar(); //\n" 22182 " return 1; // comment\n" 22183 "}());", 22184 LLVMWithBeforeLambdaBody); 22185 verifyFormat("foo(\n" 22186 " 1, MACRO {\n" 22187 " baz();\n" 22188 " bar(); // comment\n" 22189 " },\n" 22190 " []() {});", 22191 "foo(\n" 22192 " 1, MACRO { baz(); bar(); // comment\n" 22193 " }, []() {}\n" 22194 ");", 22195 LLVMWithBeforeLambdaBody); 22196 } 22197 22198 TEST_F(FormatTest, EmptyLinesInLambdas) { 22199 verifyFormat("auto lambda = []() {\n" 22200 " x(); //\n" 22201 "};", 22202 "auto lambda = []() {\n" 22203 "\n" 22204 " x(); //\n" 22205 "\n" 22206 "};"); 22207 } 22208 22209 TEST_F(FormatTest, FormatsBlocks) { 22210 FormatStyle ShortBlocks = getLLVMStyle(); 22211 ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 22212 verifyFormat("int (^Block)(int, int);", ShortBlocks); 22213 verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks); 22214 verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks); 22215 verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks); 22216 verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks); 22217 verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks); 22218 22219 verifyFormat("foo(^{ bar(); });", ShortBlocks); 22220 verifyFormat("foo(a, ^{ bar(); });", ShortBlocks); 22221 verifyFormat("{ void (^block)(Object *x); }", ShortBlocks); 22222 22223 verifyFormat("[operation setCompletionBlock:^{\n" 22224 " [self onOperationDone];\n" 22225 "}];"); 22226 verifyFormat("int i = {[operation setCompletionBlock:^{\n" 22227 " [self onOperationDone];\n" 22228 "}]};"); 22229 verifyFormat("[operation setCompletionBlock:^(int *i) {\n" 22230 " f();\n" 22231 "}];"); 22232 verifyFormat("int a = [operation block:^int(int *i) {\n" 22233 " return 1;\n" 22234 "}];"); 22235 verifyFormat("[myObject doSomethingWith:arg1\n" 22236 " aaa:^int(int *a) {\n" 22237 " return 1;\n" 22238 " }\n" 22239 " bbb:f(a * bbbbbbbb)];"); 22240 22241 verifyFormat("[operation setCompletionBlock:^{\n" 22242 " [self.delegate newDataAvailable];\n" 22243 "}];", 22244 getLLVMStyleWithColumns(60)); 22245 verifyFormat("dispatch_async(_fileIOQueue, ^{\n" 22246 " NSString *path = [self sessionFilePath];\n" 22247 " if (path) {\n" 22248 " // ...\n" 22249 " }\n" 22250 "});"); 22251 verifyFormat("[[SessionService sharedService]\n" 22252 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 22253 " if (window) {\n" 22254 " [self windowDidLoad:window];\n" 22255 " } else {\n" 22256 " [self errorLoadingWindow];\n" 22257 " }\n" 22258 " }];"); 22259 verifyFormat("void (^largeBlock)(void) = ^{\n" 22260 " // ...\n" 22261 "};\n", 22262 getLLVMStyleWithColumns(40)); 22263 verifyFormat("[[SessionService sharedService]\n" 22264 " loadWindowWithCompletionBlock: //\n" 22265 " ^(SessionWindow *window) {\n" 22266 " if (window) {\n" 22267 " [self windowDidLoad:window];\n" 22268 " } else {\n" 22269 " [self errorLoadingWindow];\n" 22270 " }\n" 22271 " }];", 22272 getLLVMStyleWithColumns(60)); 22273 verifyFormat("[myObject doSomethingWith:arg1\n" 22274 " firstBlock:^(Foo *a) {\n" 22275 " // ...\n" 22276 " int i;\n" 22277 " }\n" 22278 " secondBlock:^(Bar *b) {\n" 22279 " // ...\n" 22280 " int i;\n" 22281 " }\n" 22282 " thirdBlock:^Foo(Bar *b) {\n" 22283 " // ...\n" 22284 " int i;\n" 22285 " }];"); 22286 verifyFormat("[myObject doSomethingWith:arg1\n" 22287 " firstBlock:-1\n" 22288 " secondBlock:^(Bar *b) {\n" 22289 " // ...\n" 22290 " int i;\n" 22291 " }];"); 22292 22293 verifyFormat("f(^{\n" 22294 " @autoreleasepool {\n" 22295 " if (a) {\n" 22296 " g();\n" 22297 " }\n" 22298 " }\n" 22299 "});"); 22300 verifyFormat("Block b = ^int *(A *a, B *b) {}"); 22301 verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n" 22302 "};"); 22303 22304 FormatStyle FourIndent = getLLVMStyle(); 22305 FourIndent.ObjCBlockIndentWidth = 4; 22306 verifyFormat("[operation setCompletionBlock:^{\n" 22307 " [self onOperationDone];\n" 22308 "}];", 22309 FourIndent); 22310 } 22311 22312 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) { 22313 FormatStyle ZeroColumn = getLLVMStyleWithColumns(0); 22314 22315 verifyFormat("[[SessionService sharedService] " 22316 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 22317 " if (window) {\n" 22318 " [self windowDidLoad:window];\n" 22319 " } else {\n" 22320 " [self errorLoadingWindow];\n" 22321 " }\n" 22322 "}];", 22323 ZeroColumn); 22324 EXPECT_EQ("[[SessionService sharedService]\n" 22325 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 22326 " if (window) {\n" 22327 " [self windowDidLoad:window];\n" 22328 " } else {\n" 22329 " [self errorLoadingWindow];\n" 22330 " }\n" 22331 " }];", 22332 format("[[SessionService sharedService]\n" 22333 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 22334 " if (window) {\n" 22335 " [self windowDidLoad:window];\n" 22336 " } else {\n" 22337 " [self errorLoadingWindow];\n" 22338 " }\n" 22339 "}];", 22340 ZeroColumn)); 22341 verifyFormat("[myObject doSomethingWith:arg1\n" 22342 " firstBlock:^(Foo *a) {\n" 22343 " // ...\n" 22344 " int i;\n" 22345 " }\n" 22346 " secondBlock:^(Bar *b) {\n" 22347 " // ...\n" 22348 " int i;\n" 22349 " }\n" 22350 " thirdBlock:^Foo(Bar *b) {\n" 22351 " // ...\n" 22352 " int i;\n" 22353 " }];", 22354 ZeroColumn); 22355 verifyFormat("f(^{\n" 22356 " @autoreleasepool {\n" 22357 " if (a) {\n" 22358 " g();\n" 22359 " }\n" 22360 " }\n" 22361 "});", 22362 ZeroColumn); 22363 verifyFormat("void (^largeBlock)(void) = ^{\n" 22364 " // ...\n" 22365 "};", 22366 ZeroColumn); 22367 22368 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 22369 EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };", 22370 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn)); 22371 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 22372 EXPECT_EQ("void (^largeBlock)(void) = ^{\n" 22373 " int i;\n" 22374 "};", 22375 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn)); 22376 } 22377 22378 TEST_F(FormatTest, SupportsCRLF) { 22379 EXPECT_EQ("int a;\r\n" 22380 "int b;\r\n" 22381 "int c;\r\n", 22382 format("int a;\r\n" 22383 " int b;\r\n" 22384 " int c;\r\n", 22385 getLLVMStyle())); 22386 EXPECT_EQ("int a;\r\n" 22387 "int b;\r\n" 22388 "int c;\r\n", 22389 format("int a;\r\n" 22390 " int b;\n" 22391 " int c;\r\n", 22392 getLLVMStyle())); 22393 EXPECT_EQ("int a;\n" 22394 "int b;\n" 22395 "int c;\n", 22396 format("int a;\r\n" 22397 " int b;\n" 22398 " int c;\n", 22399 getLLVMStyle())); 22400 EXPECT_EQ("\"aaaaaaa \"\r\n" 22401 "\"bbbbbbb\";\r\n", 22402 format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10))); 22403 EXPECT_EQ("#define A \\\r\n" 22404 " b; \\\r\n" 22405 " c; \\\r\n" 22406 " d;\r\n", 22407 format("#define A \\\r\n" 22408 " b; \\\r\n" 22409 " c; d; \r\n", 22410 getGoogleStyle())); 22411 22412 EXPECT_EQ("/*\r\n" 22413 "multi line block comments\r\n" 22414 "should not introduce\r\n" 22415 "an extra carriage return\r\n" 22416 "*/\r\n", 22417 format("/*\r\n" 22418 "multi line block comments\r\n" 22419 "should not introduce\r\n" 22420 "an extra carriage return\r\n" 22421 "*/\r\n")); 22422 EXPECT_EQ("/*\r\n" 22423 "\r\n" 22424 "*/", 22425 format("/*\r\n" 22426 " \r\r\r\n" 22427 "*/")); 22428 22429 FormatStyle style = getLLVMStyle(); 22430 22431 style.DeriveLineEnding = true; 22432 style.UseCRLF = false; 22433 EXPECT_EQ("union FooBarBazQux {\n" 22434 " int foo;\n" 22435 " int bar;\n" 22436 " int baz;\n" 22437 "};", 22438 format("union FooBarBazQux {\r\n" 22439 " int foo;\n" 22440 " int bar;\r\n" 22441 " int baz;\n" 22442 "};", 22443 style)); 22444 style.UseCRLF = true; 22445 EXPECT_EQ("union FooBarBazQux {\r\n" 22446 " int foo;\r\n" 22447 " int bar;\r\n" 22448 " int baz;\r\n" 22449 "};", 22450 format("union FooBarBazQux {\r\n" 22451 " int foo;\n" 22452 " int bar;\r\n" 22453 " int baz;\n" 22454 "};", 22455 style)); 22456 22457 style.DeriveLineEnding = false; 22458 style.UseCRLF = false; 22459 EXPECT_EQ("union FooBarBazQux {\n" 22460 " int foo;\n" 22461 " int bar;\n" 22462 " int baz;\n" 22463 " int qux;\n" 22464 "};", 22465 format("union FooBarBazQux {\r\n" 22466 " int foo;\n" 22467 " int bar;\r\n" 22468 " int baz;\n" 22469 " int qux;\r\n" 22470 "};", 22471 style)); 22472 style.UseCRLF = true; 22473 EXPECT_EQ("union FooBarBazQux {\r\n" 22474 " int foo;\r\n" 22475 " int bar;\r\n" 22476 " int baz;\r\n" 22477 " int qux;\r\n" 22478 "};", 22479 format("union FooBarBazQux {\r\n" 22480 " int foo;\n" 22481 " int bar;\r\n" 22482 " int baz;\n" 22483 " int qux;\n" 22484 "};", 22485 style)); 22486 22487 style.DeriveLineEnding = true; 22488 style.UseCRLF = false; 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;\r\n" 22500 "};", 22501 style)); 22502 style.UseCRLF = true; 22503 EXPECT_EQ("union FooBarBazQux {\n" 22504 " int foo;\n" 22505 " int bar;\n" 22506 " int baz;\n" 22507 " int qux;\n" 22508 "};", 22509 format("union FooBarBazQux {\r\n" 22510 " int foo;\n" 22511 " int bar;\r\n" 22512 " int baz;\n" 22513 " int qux;\n" 22514 "};", 22515 style)); 22516 } 22517 22518 TEST_F(FormatTest, MunchSemicolonAfterBlocks) { 22519 verifyFormat("MY_CLASS(C) {\n" 22520 " int i;\n" 22521 " int j;\n" 22522 "};"); 22523 } 22524 22525 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) { 22526 FormatStyle TwoIndent = getLLVMStyleWithColumns(15); 22527 TwoIndent.ContinuationIndentWidth = 2; 22528 22529 EXPECT_EQ("int i =\n" 22530 " longFunction(\n" 22531 " arg);", 22532 format("int i = longFunction(arg);", TwoIndent)); 22533 22534 FormatStyle SixIndent = getLLVMStyleWithColumns(20); 22535 SixIndent.ContinuationIndentWidth = 6; 22536 22537 EXPECT_EQ("int i =\n" 22538 " longFunction(\n" 22539 " arg);", 22540 format("int i = longFunction(arg);", SixIndent)); 22541 } 22542 22543 TEST_F(FormatTest, WrappedClosingParenthesisIndent) { 22544 FormatStyle Style = getLLVMStyle(); 22545 verifyFormat("int Foo::getter(\n" 22546 " //\n" 22547 ") const {\n" 22548 " return foo;\n" 22549 "}", 22550 Style); 22551 verifyFormat("void Foo::setter(\n" 22552 " //\n" 22553 ") {\n" 22554 " foo = 1;\n" 22555 "}", 22556 Style); 22557 } 22558 22559 TEST_F(FormatTest, SpacesInAngles) { 22560 FormatStyle Spaces = getLLVMStyle(); 22561 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22562 22563 verifyFormat("vector< ::std::string > x1;", Spaces); 22564 verifyFormat("Foo< int, Bar > x2;", Spaces); 22565 verifyFormat("Foo< ::int, ::Bar > x3;", Spaces); 22566 22567 verifyFormat("static_cast< int >(arg);", Spaces); 22568 verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces); 22569 verifyFormat("f< int, float >();", Spaces); 22570 verifyFormat("template <> g() {}", Spaces); 22571 verifyFormat("template < std::vector< int > > f() {}", Spaces); 22572 verifyFormat("std::function< void(int, int) > fct;", Spaces); 22573 verifyFormat("void inFunction() { std::function< void(int, int) > fct; }", 22574 Spaces); 22575 22576 Spaces.Standard = FormatStyle::LS_Cpp03; 22577 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22578 verifyFormat("A< A< int > >();", Spaces); 22579 22580 Spaces.SpacesInAngles = FormatStyle::SIAS_Never; 22581 verifyFormat("A<A<int> >();", Spaces); 22582 22583 Spaces.SpacesInAngles = FormatStyle::SIAS_Leave; 22584 verifyFormat("vector< ::std::string> x4;", "vector<::std::string> x4;", 22585 Spaces); 22586 verifyFormat("vector< ::std::string > x4;", "vector<::std::string > x4;", 22587 Spaces); 22588 22589 verifyFormat("A<A<int> >();", Spaces); 22590 verifyFormat("A<A<int> >();", "A<A<int>>();", Spaces); 22591 verifyFormat("A< A< int > >();", Spaces); 22592 22593 Spaces.Standard = FormatStyle::LS_Cpp11; 22594 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22595 verifyFormat("A< A< int > >();", Spaces); 22596 22597 Spaces.SpacesInAngles = FormatStyle::SIAS_Never; 22598 verifyFormat("vector<::std::string> x4;", Spaces); 22599 verifyFormat("vector<int> x5;", Spaces); 22600 verifyFormat("Foo<int, Bar> x6;", Spaces); 22601 verifyFormat("Foo<::int, ::Bar> x7;", Spaces); 22602 22603 verifyFormat("A<A<int>>();", Spaces); 22604 22605 Spaces.SpacesInAngles = FormatStyle::SIAS_Leave; 22606 verifyFormat("vector<::std::string> x4;", Spaces); 22607 verifyFormat("vector< ::std::string > x4;", Spaces); 22608 verifyFormat("vector<int> x5;", Spaces); 22609 verifyFormat("vector< int > x5;", Spaces); 22610 verifyFormat("Foo<int, Bar> x6;", Spaces); 22611 verifyFormat("Foo< int, Bar > x6;", Spaces); 22612 verifyFormat("Foo<::int, ::Bar> x7;", Spaces); 22613 verifyFormat("Foo< ::int, ::Bar > x7;", Spaces); 22614 22615 verifyFormat("A<A<int>>();", Spaces); 22616 verifyFormat("A< A< int > >();", Spaces); 22617 verifyFormat("A<A<int > >();", Spaces); 22618 verifyFormat("A< A< int>>();", Spaces); 22619 22620 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22621 verifyFormat("// clang-format off\n" 22622 "foo<<<1, 1>>>();\n" 22623 "// clang-format on\n", 22624 Spaces); 22625 verifyFormat("// clang-format off\n" 22626 "foo< < <1, 1> > >();\n" 22627 "// clang-format on\n", 22628 Spaces); 22629 } 22630 22631 TEST_F(FormatTest, SpaceAfterTemplateKeyword) { 22632 FormatStyle Style = getLLVMStyle(); 22633 Style.SpaceAfterTemplateKeyword = false; 22634 verifyFormat("template<int> void foo();", Style); 22635 } 22636 22637 TEST_F(FormatTest, TripleAngleBrackets) { 22638 verifyFormat("f<<<1, 1>>>();"); 22639 verifyFormat("f<<<1, 1, 1, s>>>();"); 22640 verifyFormat("f<<<a, b, c, d>>>();"); 22641 EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();")); 22642 verifyFormat("f<param><<<1, 1>>>();"); 22643 verifyFormat("f<1><<<1, 1>>>();"); 22644 EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();")); 22645 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 22646 "aaaaaaaaaaa<<<\n 1, 1>>>();"); 22647 verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n" 22648 " <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();"); 22649 } 22650 22651 TEST_F(FormatTest, MergeLessLessAtEnd) { 22652 verifyFormat("<<"); 22653 EXPECT_EQ("< < <", format("\\\n<<<")); 22654 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 22655 "aaallvm::outs() <<"); 22656 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 22657 "aaaallvm::outs()\n <<"); 22658 } 22659 22660 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) { 22661 std::string code = "#if A\n" 22662 "#if B\n" 22663 "a.\n" 22664 "#endif\n" 22665 " a = 1;\n" 22666 "#else\n" 22667 "#endif\n" 22668 "#if C\n" 22669 "#else\n" 22670 "#endif\n"; 22671 EXPECT_EQ(code, format(code)); 22672 } 22673 22674 TEST_F(FormatTest, HandleConflictMarkers) { 22675 // Git/SVN conflict markers. 22676 EXPECT_EQ("int a;\n" 22677 "void f() {\n" 22678 " callme(some(parameter1,\n" 22679 "<<<<<<< text by the vcs\n" 22680 " parameter2),\n" 22681 "||||||| text by the vcs\n" 22682 " parameter2),\n" 22683 " parameter3,\n" 22684 "======= text by the vcs\n" 22685 " parameter2, parameter3),\n" 22686 ">>>>>>> text by the vcs\n" 22687 " otherparameter);\n", 22688 format("int a;\n" 22689 "void f() {\n" 22690 " callme(some(parameter1,\n" 22691 "<<<<<<< text by the vcs\n" 22692 " parameter2),\n" 22693 "||||||| text by the vcs\n" 22694 " parameter2),\n" 22695 " parameter3,\n" 22696 "======= text by the vcs\n" 22697 " parameter2,\n" 22698 " parameter3),\n" 22699 ">>>>>>> text by the vcs\n" 22700 " otherparameter);\n")); 22701 22702 // Perforce markers. 22703 EXPECT_EQ("void f() {\n" 22704 " function(\n" 22705 ">>>> text by the vcs\n" 22706 " parameter,\n" 22707 "==== text by the vcs\n" 22708 " parameter,\n" 22709 "==== text by the vcs\n" 22710 " parameter,\n" 22711 "<<<< text by the vcs\n" 22712 " parameter);\n", 22713 format("void f() {\n" 22714 " function(\n" 22715 ">>>> text by the vcs\n" 22716 " parameter,\n" 22717 "==== text by the vcs\n" 22718 " parameter,\n" 22719 "==== text by the vcs\n" 22720 " parameter,\n" 22721 "<<<< text by the vcs\n" 22722 " parameter);\n")); 22723 22724 EXPECT_EQ("<<<<<<<\n" 22725 "|||||||\n" 22726 "=======\n" 22727 ">>>>>>>", 22728 format("<<<<<<<\n" 22729 "|||||||\n" 22730 "=======\n" 22731 ">>>>>>>")); 22732 22733 EXPECT_EQ("<<<<<<<\n" 22734 "|||||||\n" 22735 "int i;\n" 22736 "=======\n" 22737 ">>>>>>>", 22738 format("<<<<<<<\n" 22739 "|||||||\n" 22740 "int i;\n" 22741 "=======\n" 22742 ">>>>>>>")); 22743 22744 // FIXME: Handle parsing of macros around conflict markers correctly: 22745 EXPECT_EQ("#define Macro \\\n" 22746 "<<<<<<<\n" 22747 "Something \\\n" 22748 "|||||||\n" 22749 "Else \\\n" 22750 "=======\n" 22751 "Other \\\n" 22752 ">>>>>>>\n" 22753 " End int i;\n", 22754 format("#define Macro \\\n" 22755 "<<<<<<<\n" 22756 " Something \\\n" 22757 "|||||||\n" 22758 " Else \\\n" 22759 "=======\n" 22760 " Other \\\n" 22761 ">>>>>>>\n" 22762 " End\n" 22763 "int i;\n")); 22764 22765 verifyFormat(R"(==== 22766 #ifdef A 22767 a 22768 #else 22769 b 22770 #endif 22771 )"); 22772 } 22773 22774 TEST_F(FormatTest, DisableRegions) { 22775 EXPECT_EQ("int i;\n" 22776 "// clang-format off\n" 22777 " int j;\n" 22778 "// clang-format on\n" 22779 "int k;", 22780 format(" int i;\n" 22781 " // clang-format off\n" 22782 " int j;\n" 22783 " // clang-format on\n" 22784 " int k;")); 22785 EXPECT_EQ("int i;\n" 22786 "/* clang-format off */\n" 22787 " int j;\n" 22788 "/* clang-format on */\n" 22789 "int k;", 22790 format(" int i;\n" 22791 " /* clang-format off */\n" 22792 " int j;\n" 22793 " /* clang-format on */\n" 22794 " int k;")); 22795 22796 // Don't reflow comments within disabled regions. 22797 EXPECT_EQ("// clang-format off\n" 22798 "// long long long long long long line\n" 22799 "/* clang-format on */\n" 22800 "/* long long long\n" 22801 " * long long long\n" 22802 " * line */\n" 22803 "int i;\n" 22804 "/* clang-format off */\n" 22805 "/* long long long long long long line */\n", 22806 format("// clang-format off\n" 22807 "// long long long long long long line\n" 22808 "/* clang-format on */\n" 22809 "/* long long long long long long line */\n" 22810 "int i;\n" 22811 "/* clang-format off */\n" 22812 "/* long long long long long long line */\n", 22813 getLLVMStyleWithColumns(20))); 22814 } 22815 22816 TEST_F(FormatTest, DoNotCrashOnInvalidInput) { 22817 format("? ) ="); 22818 verifyNoCrash("#define a\\\n /**/}"); 22819 } 22820 22821 TEST_F(FormatTest, FormatsTableGenCode) { 22822 FormatStyle Style = getLLVMStyle(); 22823 Style.Language = FormatStyle::LK_TableGen; 22824 verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style); 22825 } 22826 22827 TEST_F(FormatTest, ArrayOfTemplates) { 22828 EXPECT_EQ("auto a = new unique_ptr<int>[10];", 22829 format("auto a = new unique_ptr<int > [ 10];")); 22830 22831 FormatStyle Spaces = getLLVMStyle(); 22832 Spaces.SpacesInSquareBrackets = true; 22833 EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];", 22834 format("auto a = new unique_ptr<int > [10];", Spaces)); 22835 } 22836 22837 TEST_F(FormatTest, ArrayAsTemplateType) { 22838 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;", 22839 format("auto a = unique_ptr < Foo < Bar>[ 10]> ;")); 22840 22841 FormatStyle Spaces = getLLVMStyle(); 22842 Spaces.SpacesInSquareBrackets = true; 22843 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;", 22844 format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces)); 22845 } 22846 22847 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); } 22848 22849 TEST(FormatStyle, GetStyleWithEmptyFileName) { 22850 llvm::vfs::InMemoryFileSystem FS; 22851 auto Style1 = getStyle("file", "", "Google", "", &FS); 22852 ASSERT_TRUE((bool)Style1); 22853 ASSERT_EQ(*Style1, getGoogleStyle()); 22854 } 22855 22856 TEST(FormatStyle, GetStyleOfFile) { 22857 llvm::vfs::InMemoryFileSystem FS; 22858 // Test 1: format file in the same directory. 22859 ASSERT_TRUE( 22860 FS.addFile("/a/.clang-format", 0, 22861 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM"))); 22862 ASSERT_TRUE( 22863 FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22864 auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS); 22865 ASSERT_TRUE((bool)Style1); 22866 ASSERT_EQ(*Style1, getLLVMStyle()); 22867 22868 // Test 2.1: fallback to default. 22869 ASSERT_TRUE( 22870 FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22871 auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS); 22872 ASSERT_TRUE((bool)Style2); 22873 ASSERT_EQ(*Style2, getMozillaStyle()); 22874 22875 // Test 2.2: no format on 'none' fallback style. 22876 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS); 22877 ASSERT_TRUE((bool)Style2); 22878 ASSERT_EQ(*Style2, getNoStyle()); 22879 22880 // Test 2.3: format if config is found with no based style while fallback is 22881 // 'none'. 22882 ASSERT_TRUE(FS.addFile("/b/.clang-format", 0, 22883 llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2"))); 22884 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS); 22885 ASSERT_TRUE((bool)Style2); 22886 ASSERT_EQ(*Style2, getLLVMStyle()); 22887 22888 // Test 2.4: format if yaml with no based style, while fallback is 'none'. 22889 Style2 = getStyle("{}", "a.h", "none", "", &FS); 22890 ASSERT_TRUE((bool)Style2); 22891 ASSERT_EQ(*Style2, getLLVMStyle()); 22892 22893 // Test 3: format file in parent directory. 22894 ASSERT_TRUE( 22895 FS.addFile("/c/.clang-format", 0, 22896 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 22897 ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0, 22898 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22899 auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS); 22900 ASSERT_TRUE((bool)Style3); 22901 ASSERT_EQ(*Style3, getGoogleStyle()); 22902 22903 // Test 4: error on invalid fallback style 22904 auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS); 22905 ASSERT_FALSE((bool)Style4); 22906 llvm::consumeError(Style4.takeError()); 22907 22908 // Test 5: error on invalid yaml on command line 22909 auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS); 22910 ASSERT_FALSE((bool)Style5); 22911 llvm::consumeError(Style5.takeError()); 22912 22913 // Test 6: error on invalid style 22914 auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS); 22915 ASSERT_FALSE((bool)Style6); 22916 llvm::consumeError(Style6.takeError()); 22917 22918 // Test 7: found config file, error on parsing it 22919 ASSERT_TRUE( 22920 FS.addFile("/d/.clang-format", 0, 22921 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n" 22922 "InvalidKey: InvalidValue"))); 22923 ASSERT_TRUE( 22924 FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22925 auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS); 22926 ASSERT_FALSE((bool)Style7a); 22927 llvm::consumeError(Style7a.takeError()); 22928 22929 auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true); 22930 ASSERT_TRUE((bool)Style7b); 22931 22932 // Test 8: inferred per-language defaults apply. 22933 auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS); 22934 ASSERT_TRUE((bool)StyleTd); 22935 ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen)); 22936 22937 // Test 9.1.1: overwriting a file style, when no parent file exists with no 22938 // fallback style. 22939 ASSERT_TRUE(FS.addFile( 22940 "/e/sub/.clang-format", 0, 22941 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n" 22942 "ColumnLimit: 20"))); 22943 ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0, 22944 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22945 auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS); 22946 ASSERT_TRUE(static_cast<bool>(Style9)); 22947 ASSERT_EQ(*Style9, [] { 22948 auto Style = getNoStyle(); 22949 Style.ColumnLimit = 20; 22950 return Style; 22951 }()); 22952 22953 // Test 9.1.2: propagate more than one level with no parent file. 22954 ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0, 22955 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22956 ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0, 22957 llvm::MemoryBuffer::getMemBuffer( 22958 "BasedOnStyle: InheritParentConfig\n" 22959 "WhitespaceSensitiveMacros: ['FOO', 'BAR']"))); 22960 std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"}; 22961 22962 ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros); 22963 Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS); 22964 ASSERT_TRUE(static_cast<bool>(Style9)); 22965 ASSERT_EQ(*Style9, [&NonDefaultWhiteSpaceMacros] { 22966 auto Style = getNoStyle(); 22967 Style.ColumnLimit = 20; 22968 Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros; 22969 return Style; 22970 }()); 22971 22972 // Test 9.2: with LLVM fallback style 22973 Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS); 22974 ASSERT_TRUE(static_cast<bool>(Style9)); 22975 ASSERT_EQ(*Style9, [] { 22976 auto Style = getLLVMStyle(); 22977 Style.ColumnLimit = 20; 22978 return Style; 22979 }()); 22980 22981 // Test 9.3: with a parent file 22982 ASSERT_TRUE( 22983 FS.addFile("/e/.clang-format", 0, 22984 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n" 22985 "UseTab: Always"))); 22986 Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS); 22987 ASSERT_TRUE(static_cast<bool>(Style9)); 22988 ASSERT_EQ(*Style9, [] { 22989 auto Style = getGoogleStyle(); 22990 Style.ColumnLimit = 20; 22991 Style.UseTab = FormatStyle::UT_Always; 22992 return Style; 22993 }()); 22994 22995 // Test 9.4: propagate more than one level with a parent file. 22996 const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] { 22997 auto Style = getGoogleStyle(); 22998 Style.ColumnLimit = 20; 22999 Style.UseTab = FormatStyle::UT_Always; 23000 Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros; 23001 return Style; 23002 }(); 23003 23004 ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros); 23005 Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS); 23006 ASSERT_TRUE(static_cast<bool>(Style9)); 23007 ASSERT_EQ(*Style9, SubSubStyle); 23008 23009 // Test 9.5: use InheritParentConfig as style name 23010 Style9 = 23011 getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS); 23012 ASSERT_TRUE(static_cast<bool>(Style9)); 23013 ASSERT_EQ(*Style9, SubSubStyle); 23014 23015 // Test 9.6: use command line style with inheritance 23016 Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp", 23017 "none", "", &FS); 23018 ASSERT_TRUE(static_cast<bool>(Style9)); 23019 ASSERT_EQ(*Style9, SubSubStyle); 23020 23021 // Test 9.7: use command line style with inheritance and own config 23022 Style9 = getStyle("{BasedOnStyle: InheritParentConfig, " 23023 "WhitespaceSensitiveMacros: ['FOO', 'BAR']}", 23024 "/e/sub/code.cpp", "none", "", &FS); 23025 ASSERT_TRUE(static_cast<bool>(Style9)); 23026 ASSERT_EQ(*Style9, SubSubStyle); 23027 23028 // Test 9.8: use inheritance from a file without BasedOnStyle 23029 ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0, 23030 llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123"))); 23031 ASSERT_TRUE( 23032 FS.addFile("/e/withoutbase/sub/.clang-format", 0, 23033 llvm::MemoryBuffer::getMemBuffer( 23034 "BasedOnStyle: InheritParentConfig\nIndentWidth: 7"))); 23035 // Make sure we do not use the fallback style 23036 Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS); 23037 ASSERT_TRUE(static_cast<bool>(Style9)); 23038 ASSERT_EQ(*Style9, [] { 23039 auto Style = getLLVMStyle(); 23040 Style.ColumnLimit = 123; 23041 return Style; 23042 }()); 23043 23044 Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS); 23045 ASSERT_TRUE(static_cast<bool>(Style9)); 23046 ASSERT_EQ(*Style9, [] { 23047 auto Style = getLLVMStyle(); 23048 Style.ColumnLimit = 123; 23049 Style.IndentWidth = 7; 23050 return Style; 23051 }()); 23052 23053 // Test 9.9: use inheritance from a specific config file. 23054 Style9 = getStyle("file:/e/sub/sub/.clang-format", "/e/sub/sub/code.cpp", 23055 "none", "", &FS); 23056 ASSERT_TRUE(static_cast<bool>(Style9)); 23057 ASSERT_EQ(*Style9, SubSubStyle); 23058 } 23059 23060 TEST(FormatStyle, GetStyleOfSpecificFile) { 23061 llvm::vfs::InMemoryFileSystem FS; 23062 // Specify absolute path to a format file in a parent directory. 23063 ASSERT_TRUE( 23064 FS.addFile("/e/.clang-format", 0, 23065 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM"))); 23066 ASSERT_TRUE( 23067 FS.addFile("/e/explicit.clang-format", 0, 23068 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 23069 ASSERT_TRUE(FS.addFile("/e/sub/sub/sub/test.cpp", 0, 23070 llvm::MemoryBuffer::getMemBuffer("int i;"))); 23071 auto Style = getStyle("file:/e/explicit.clang-format", 23072 "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS); 23073 ASSERT_TRUE(static_cast<bool>(Style)); 23074 ASSERT_EQ(*Style, getGoogleStyle()); 23075 23076 // Specify relative path to a format file. 23077 ASSERT_TRUE( 23078 FS.addFile("../../e/explicit.clang-format", 0, 23079 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 23080 Style = getStyle("file:../../e/explicit.clang-format", 23081 "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS); 23082 ASSERT_TRUE(static_cast<bool>(Style)); 23083 ASSERT_EQ(*Style, getGoogleStyle()); 23084 23085 // Specify path to a format file that does not exist. 23086 Style = getStyle("file:/e/missing.clang-format", "/e/sub/sub/sub/test.cpp", 23087 "LLVM", "", &FS); 23088 ASSERT_FALSE(static_cast<bool>(Style)); 23089 llvm::consumeError(Style.takeError()); 23090 23091 // Specify path to a file on the filesystem. 23092 SmallString<128> FormatFilePath; 23093 std::error_code ECF = llvm::sys::fs::createTemporaryFile( 23094 "FormatFileTest", "tpl", FormatFilePath); 23095 EXPECT_FALSE((bool)ECF); 23096 llvm::raw_fd_ostream FormatFileTest(FormatFilePath, ECF); 23097 EXPECT_FALSE((bool)ECF); 23098 FormatFileTest << "BasedOnStyle: Google\n"; 23099 FormatFileTest.close(); 23100 23101 SmallString<128> TestFilePath; 23102 std::error_code ECT = 23103 llvm::sys::fs::createTemporaryFile("CodeFileTest", "cc", TestFilePath); 23104 EXPECT_FALSE((bool)ECT); 23105 llvm::raw_fd_ostream CodeFileTest(TestFilePath, ECT); 23106 CodeFileTest << "int i;\n"; 23107 CodeFileTest.close(); 23108 23109 std::string format_file_arg = std::string("file:") + FormatFilePath.c_str(); 23110 Style = getStyle(format_file_arg, TestFilePath, "LLVM", "", nullptr); 23111 23112 llvm::sys::fs::remove(FormatFilePath.c_str()); 23113 llvm::sys::fs::remove(TestFilePath.c_str()); 23114 ASSERT_TRUE(static_cast<bool>(Style)); 23115 ASSERT_EQ(*Style, getGoogleStyle()); 23116 } 23117 23118 TEST_F(ReplacementTest, FormatCodeAfterReplacements) { 23119 // Column limit is 20. 23120 std::string Code = "Type *a =\n" 23121 " new Type();\n" 23122 "g(iiiii, 0, jjjjj,\n" 23123 " 0, kkkkk, 0, mm);\n" 23124 "int bad = format ;"; 23125 std::string Expected = "auto a = new Type();\n" 23126 "g(iiiii, nullptr,\n" 23127 " jjjjj, nullptr,\n" 23128 " kkkkk, nullptr,\n" 23129 " mm);\n" 23130 "int bad = format ;"; 23131 FileID ID = Context.createInMemoryFile("format.cpp", Code); 23132 tooling::Replacements Replaces = toReplacements( 23133 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6, 23134 "auto "), 23135 tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1, 23136 "nullptr"), 23137 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1, 23138 "nullptr"), 23139 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1, 23140 "nullptr")}); 23141 23142 FormatStyle Style = getLLVMStyle(); 23143 Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility. 23144 auto FormattedReplaces = formatReplacements(Code, Replaces, Style); 23145 EXPECT_TRUE(static_cast<bool>(FormattedReplaces)) 23146 << llvm::toString(FormattedReplaces.takeError()) << "\n"; 23147 auto Result = applyAllReplacements(Code, *FormattedReplaces); 23148 EXPECT_TRUE(static_cast<bool>(Result)); 23149 EXPECT_EQ(Expected, *Result); 23150 } 23151 23152 TEST_F(ReplacementTest, SortIncludesAfterReplacement) { 23153 std::string Code = "#include \"a.h\"\n" 23154 "#include \"c.h\"\n" 23155 "\n" 23156 "int main() {\n" 23157 " return 0;\n" 23158 "}"; 23159 std::string Expected = "#include \"a.h\"\n" 23160 "#include \"b.h\"\n" 23161 "#include \"c.h\"\n" 23162 "\n" 23163 "int main() {\n" 23164 " return 0;\n" 23165 "}"; 23166 FileID ID = Context.createInMemoryFile("fix.cpp", Code); 23167 tooling::Replacements Replaces = toReplacements( 23168 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0, 23169 "#include \"b.h\"\n")}); 23170 23171 FormatStyle Style = getLLVMStyle(); 23172 Style.SortIncludes = FormatStyle::SI_CaseSensitive; 23173 auto FormattedReplaces = formatReplacements(Code, Replaces, Style); 23174 EXPECT_TRUE(static_cast<bool>(FormattedReplaces)) 23175 << llvm::toString(FormattedReplaces.takeError()) << "\n"; 23176 auto Result = applyAllReplacements(Code, *FormattedReplaces); 23177 EXPECT_TRUE(static_cast<bool>(Result)); 23178 EXPECT_EQ(Expected, *Result); 23179 } 23180 23181 TEST_F(FormatTest, FormatSortsUsingDeclarations) { 23182 EXPECT_EQ("using std::cin;\n" 23183 "using std::cout;", 23184 format("using std::cout;\n" 23185 "using std::cin;", 23186 getGoogleStyle())); 23187 } 23188 23189 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) { 23190 FormatStyle Style = getLLVMStyle(); 23191 Style.Standard = FormatStyle::LS_Cpp03; 23192 // cpp03 recognize this string as identifier u8 and literal character 'a' 23193 EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style)); 23194 } 23195 23196 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) { 23197 // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers 23198 // all modes, including C++11, C++14 and C++17 23199 EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';")); 23200 } 23201 23202 TEST_F(FormatTest, DoNotFormatLikelyXml) { 23203 EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle())); 23204 EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle())); 23205 } 23206 23207 TEST_F(FormatTest, StructuredBindings) { 23208 // Structured bindings is a C++17 feature. 23209 // all modes, including C++11, C++14 and C++17 23210 verifyFormat("auto [a, b] = f();"); 23211 EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();")); 23212 EXPECT_EQ("const auto [a, b] = f();", format("const auto[a, b] = f();")); 23213 EXPECT_EQ("auto const [a, b] = f();", format("auto const[a, b] = f();")); 23214 EXPECT_EQ("auto const volatile [a, b] = f();", 23215 format("auto const volatile[a, b] = f();")); 23216 EXPECT_EQ("auto [a, b, c] = f();", format("auto [ a , b,c ] = f();")); 23217 EXPECT_EQ("auto &[a, b, c] = f();", 23218 format("auto &[ a , b,c ] = f();")); 23219 EXPECT_EQ("auto &&[a, b, c] = f();", 23220 format("auto &&[ a , b,c ] = f();")); 23221 EXPECT_EQ("auto const &[a, b] = f();", format("auto const&[a, b] = f();")); 23222 EXPECT_EQ("auto const volatile &&[a, b] = f();", 23223 format("auto const volatile &&[a, b] = f();")); 23224 EXPECT_EQ("auto const &&[a, b] = f();", 23225 format("auto const && [a, b] = f();")); 23226 EXPECT_EQ("const auto &[a, b] = f();", 23227 format("const auto & [a, b] = f();")); 23228 EXPECT_EQ("const auto volatile &&[a, b] = f();", 23229 format("const auto volatile &&[a, b] = f();")); 23230 EXPECT_EQ("volatile const auto &&[a, b] = f();", 23231 format("volatile const auto &&[a, b] = f();")); 23232 EXPECT_EQ("const auto &&[a, b] = f();", 23233 format("const auto && [a, b] = f();")); 23234 23235 // Make sure we don't mistake structured bindings for lambdas. 23236 FormatStyle PointerMiddle = getLLVMStyle(); 23237 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle; 23238 verifyFormat("auto [a1, b]{A * i};", getGoogleStyle()); 23239 verifyFormat("auto [a2, b]{A * i};", getLLVMStyle()); 23240 verifyFormat("auto [a3, b]{A * i};", PointerMiddle); 23241 verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle()); 23242 verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle()); 23243 verifyFormat("auto const [a3, b]{A * i};", PointerMiddle); 23244 verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle()); 23245 verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle()); 23246 verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle); 23247 verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle()); 23248 verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle()); 23249 verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle); 23250 23251 EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}", 23252 format("for (const auto && [a, b] : some_range) {\n}")); 23253 EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}", 23254 format("for (const auto & [a, b] : some_range) {\n}")); 23255 EXPECT_EQ("for (const auto [a, b] : some_range) {\n}", 23256 format("for (const auto[a, b] : some_range) {\n}")); 23257 EXPECT_EQ("auto [x, y](expr);", format("auto[x,y] (expr);")); 23258 EXPECT_EQ("auto &[x, y](expr);", format("auto & [x,y] (expr);")); 23259 EXPECT_EQ("auto &&[x, y](expr);", format("auto && [x,y] (expr);")); 23260 EXPECT_EQ("auto const &[x, y](expr);", 23261 format("auto const & [x,y] (expr);")); 23262 EXPECT_EQ("auto const &&[x, y](expr);", 23263 format("auto const && [x,y] (expr);")); 23264 EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y] {expr};")); 23265 EXPECT_EQ("auto const &[x, y]{expr};", 23266 format("auto const & [x,y] {expr};")); 23267 EXPECT_EQ("auto const &&[x, y]{expr};", 23268 format("auto const && [x,y] {expr};")); 23269 23270 FormatStyle Spaces = getLLVMStyle(); 23271 Spaces.SpacesInSquareBrackets = true; 23272 verifyFormat("auto [ a, b ] = f();", Spaces); 23273 verifyFormat("auto &&[ a, b ] = f();", Spaces); 23274 verifyFormat("auto &[ a, b ] = f();", Spaces); 23275 verifyFormat("auto const &&[ a, b ] = f();", Spaces); 23276 verifyFormat("auto const &[ a, b ] = f();", Spaces); 23277 } 23278 23279 TEST_F(FormatTest, FileAndCode) { 23280 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", "")); 23281 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", "")); 23282 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", "")); 23283 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "")); 23284 EXPECT_EQ(FormatStyle::LK_ObjC, 23285 guessLanguage("foo.h", "@interface Foo\n@end\n")); 23286 EXPECT_EQ( 23287 FormatStyle::LK_ObjC, 23288 guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }")); 23289 EXPECT_EQ(FormatStyle::LK_ObjC, 23290 guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))")); 23291 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;")); 23292 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", "")); 23293 EXPECT_EQ(FormatStyle::LK_ObjC, 23294 guessLanguage("foo", "@interface Foo\n@end\n")); 23295 EXPECT_EQ(FormatStyle::LK_ObjC, 23296 guessLanguage("foo.h", "int DoStuff(CGRect rect);\n")); 23297 EXPECT_EQ( 23298 FormatStyle::LK_ObjC, 23299 guessLanguage("foo.h", 23300 "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n")); 23301 EXPECT_EQ( 23302 FormatStyle::LK_Cpp, 23303 guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;")); 23304 // Only one of the two preprocessor regions has ObjC-like code. 23305 EXPECT_EQ(FormatStyle::LK_ObjC, 23306 guessLanguage("foo.h", "#if A\n" 23307 "#define B() C\n" 23308 "#else\n" 23309 "#define B() [NSString a:@\"\"]\n" 23310 "#endif\n")); 23311 } 23312 23313 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) { 23314 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];")); 23315 EXPECT_EQ(FormatStyle::LK_ObjC, 23316 guessLanguage("foo.h", "array[[calculator getIndex]];")); 23317 EXPECT_EQ(FormatStyle::LK_Cpp, 23318 guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];")); 23319 EXPECT_EQ( 23320 FormatStyle::LK_Cpp, 23321 guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];")); 23322 EXPECT_EQ(FormatStyle::LK_ObjC, 23323 guessLanguage("foo.h", "[[noreturn foo] bar];")); 23324 EXPECT_EQ(FormatStyle::LK_Cpp, 23325 guessLanguage("foo.h", "[[clang::fallthrough]];")); 23326 EXPECT_EQ(FormatStyle::LK_ObjC, 23327 guessLanguage("foo.h", "[[clang:fallthrough] foo];")); 23328 EXPECT_EQ(FormatStyle::LK_Cpp, 23329 guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];")); 23330 EXPECT_EQ(FormatStyle::LK_Cpp, 23331 guessLanguage("foo.h", "[[using clang: fallthrough]];")); 23332 EXPECT_EQ(FormatStyle::LK_ObjC, 23333 guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];")); 23334 EXPECT_EQ(FormatStyle::LK_Cpp, 23335 guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];")); 23336 EXPECT_EQ( 23337 FormatStyle::LK_Cpp, 23338 guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)")); 23339 EXPECT_EQ( 23340 FormatStyle::LK_Cpp, 23341 guessLanguage("foo.h", 23342 "[[clang::callable_when(\"unconsumed\", \"unknown\")]]")); 23343 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]")); 23344 } 23345 23346 TEST_F(FormatTest, GuessLanguageWithCaret) { 23347 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);")); 23348 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);")); 23349 EXPECT_EQ(FormatStyle::LK_ObjC, 23350 guessLanguage("foo.h", "int(^)(char, float);")); 23351 EXPECT_EQ(FormatStyle::LK_ObjC, 23352 guessLanguage("foo.h", "int(^foo)(char, float);")); 23353 EXPECT_EQ(FormatStyle::LK_ObjC, 23354 guessLanguage("foo.h", "int(^foo[10])(char, float);")); 23355 EXPECT_EQ(FormatStyle::LK_ObjC, 23356 guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);")); 23357 EXPECT_EQ( 23358 FormatStyle::LK_ObjC, 23359 guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);")); 23360 } 23361 23362 TEST_F(FormatTest, GuessLanguageWithPragmas) { 23363 EXPECT_EQ(FormatStyle::LK_Cpp, 23364 guessLanguage("foo.h", "__pragma(warning(disable:))")); 23365 EXPECT_EQ(FormatStyle::LK_Cpp, 23366 guessLanguage("foo.h", "#pragma(warning(disable:))")); 23367 EXPECT_EQ(FormatStyle::LK_Cpp, 23368 guessLanguage("foo.h", "_Pragma(warning(disable:))")); 23369 } 23370 23371 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) { 23372 // ASM symbolic names are identifiers that must be surrounded by [] without 23373 // space in between: 23374 // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands 23375 23376 // Example from https://bugs.llvm.org/show_bug.cgi?id=45108. 23377 verifyFormat(R"(// 23378 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result)); 23379 )"); 23380 23381 // A list of several ASM symbolic names. 23382 verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)"); 23383 23384 // ASM symbolic names in inline ASM with inputs and outputs. 23385 verifyFormat(R"(// 23386 asm("cmoveq %1, %2, %[result]" 23387 : [result] "=r"(result) 23388 : "r"(test), "r"(new), "[result]"(old)); 23389 )"); 23390 23391 // ASM symbolic names in inline ASM with no outputs. 23392 verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)"); 23393 } 23394 23395 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) { 23396 EXPECT_EQ(FormatStyle::LK_Cpp, 23397 guessLanguage("foo.h", "void f() {\n" 23398 " asm (\"mov %[e], %[d]\"\n" 23399 " : [d] \"=rm\" (d)\n" 23400 " [e] \"rm\" (*e));\n" 23401 "}")); 23402 EXPECT_EQ(FormatStyle::LK_Cpp, 23403 guessLanguage("foo.h", "void f() {\n" 23404 " _asm (\"mov %[e], %[d]\"\n" 23405 " : [d] \"=rm\" (d)\n" 23406 " [e] \"rm\" (*e));\n" 23407 "}")); 23408 EXPECT_EQ(FormatStyle::LK_Cpp, 23409 guessLanguage("foo.h", "void f() {\n" 23410 " __asm (\"mov %[e], %[d]\"\n" 23411 " : [d] \"=rm\" (d)\n" 23412 " [e] \"rm\" (*e));\n" 23413 "}")); 23414 EXPECT_EQ(FormatStyle::LK_Cpp, 23415 guessLanguage("foo.h", "void f() {\n" 23416 " __asm__ (\"mov %[e], %[d]\"\n" 23417 " : [d] \"=rm\" (d)\n" 23418 " [e] \"rm\" (*e));\n" 23419 "}")); 23420 EXPECT_EQ(FormatStyle::LK_Cpp, 23421 guessLanguage("foo.h", "void f() {\n" 23422 " asm (\"mov %[e], %[d]\"\n" 23423 " : [d] \"=rm\" (d),\n" 23424 " [e] \"rm\" (*e));\n" 23425 "}")); 23426 EXPECT_EQ(FormatStyle::LK_Cpp, 23427 guessLanguage("foo.h", "void f() {\n" 23428 " asm volatile (\"mov %[e], %[d]\"\n" 23429 " : [d] \"=rm\" (d)\n" 23430 " [e] \"rm\" (*e));\n" 23431 "}")); 23432 } 23433 23434 TEST_F(FormatTest, GuessLanguageWithChildLines) { 23435 EXPECT_EQ(FormatStyle::LK_Cpp, 23436 guessLanguage("foo.h", "#define FOO ({ std::string s; })")); 23437 EXPECT_EQ(FormatStyle::LK_ObjC, 23438 guessLanguage("foo.h", "#define FOO ({ NSString *s; })")); 23439 EXPECT_EQ( 23440 FormatStyle::LK_Cpp, 23441 guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })")); 23442 EXPECT_EQ( 23443 FormatStyle::LK_ObjC, 23444 guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })")); 23445 } 23446 23447 TEST_F(FormatTest, TypenameMacros) { 23448 std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"}; 23449 23450 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353 23451 FormatStyle Google = getGoogleStyleWithColumns(0); 23452 Google.TypenameMacros = TypenameMacros; 23453 verifyFormat("struct foo {\n" 23454 " int bar;\n" 23455 " TAILQ_ENTRY(a) bleh;\n" 23456 "};", 23457 Google); 23458 23459 FormatStyle Macros = getLLVMStyle(); 23460 Macros.TypenameMacros = TypenameMacros; 23461 23462 verifyFormat("STACK_OF(int) a;", Macros); 23463 verifyFormat("STACK_OF(int) *a;", Macros); 23464 verifyFormat("STACK_OF(int const *) *a;", Macros); 23465 verifyFormat("STACK_OF(int *const) *a;", Macros); 23466 verifyFormat("STACK_OF(int, string) a;", Macros); 23467 verifyFormat("STACK_OF(LIST(int)) a;", Macros); 23468 verifyFormat("STACK_OF(LIST(int)) a, b;", Macros); 23469 verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros); 23470 verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros); 23471 verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros); 23472 verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros); 23473 23474 Macros.PointerAlignment = FormatStyle::PAS_Left; 23475 verifyFormat("STACK_OF(int)* a;", Macros); 23476 verifyFormat("STACK_OF(int*)* a;", Macros); 23477 verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros); 23478 verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros); 23479 verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros); 23480 } 23481 23482 TEST_F(FormatTest, AtomicQualifier) { 23483 // Check that we treate _Atomic as a type and not a function call 23484 FormatStyle Google = getGoogleStyleWithColumns(0); 23485 verifyFormat("struct foo {\n" 23486 " int a1;\n" 23487 " _Atomic(a) a2;\n" 23488 " _Atomic(_Atomic(int) *const) a3;\n" 23489 "};", 23490 Google); 23491 verifyFormat("_Atomic(uint64_t) a;"); 23492 verifyFormat("_Atomic(uint64_t) *a;"); 23493 verifyFormat("_Atomic(uint64_t const *) *a;"); 23494 verifyFormat("_Atomic(uint64_t *const) *a;"); 23495 verifyFormat("_Atomic(const uint64_t *) *a;"); 23496 verifyFormat("_Atomic(uint64_t) a;"); 23497 verifyFormat("_Atomic(_Atomic(uint64_t)) a;"); 23498 verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;"); 23499 verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}"); 23500 verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);"); 23501 23502 verifyFormat("_Atomic(uint64_t) *s(InitValue);"); 23503 verifyFormat("_Atomic(uint64_t) *s{InitValue};"); 23504 FormatStyle Style = getLLVMStyle(); 23505 Style.PointerAlignment = FormatStyle::PAS_Left; 23506 verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style); 23507 verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style); 23508 verifyFormat("_Atomic(int)* a;", Style); 23509 verifyFormat("_Atomic(int*)* a;", Style); 23510 verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style); 23511 23512 Style.SpacesInCStyleCastParentheses = true; 23513 Style.SpacesInParentheses = false; 23514 verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style); 23515 Style.SpacesInCStyleCastParentheses = false; 23516 Style.SpacesInParentheses = true; 23517 verifyFormat("x = (_Atomic( uint64_t ))*a;", Style); 23518 verifyFormat("x = (_Atomic( uint64_t ))&a;", Style); 23519 } 23520 23521 TEST_F(FormatTest, AmbersandInLamda) { 23522 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899 23523 FormatStyle AlignStyle = getLLVMStyle(); 23524 AlignStyle.PointerAlignment = FormatStyle::PAS_Left; 23525 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle); 23526 AlignStyle.PointerAlignment = FormatStyle::PAS_Right; 23527 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle); 23528 } 23529 23530 TEST_F(FormatTest, SpacesInConditionalStatement) { 23531 FormatStyle Spaces = getLLVMStyle(); 23532 Spaces.IfMacros.clear(); 23533 Spaces.IfMacros.push_back("MYIF"); 23534 Spaces.SpacesInConditionalStatement = true; 23535 verifyFormat("for ( int i = 0; i; i++ )\n continue;", Spaces); 23536 verifyFormat("if ( !a )\n return;", Spaces); 23537 verifyFormat("if ( a )\n return;", Spaces); 23538 verifyFormat("if constexpr ( a )\n return;", Spaces); 23539 verifyFormat("MYIF ( a )\n return;", Spaces); 23540 verifyFormat("MYIF ( a )\n return;\nelse MYIF ( b )\n return;", Spaces); 23541 verifyFormat("MYIF ( a )\n return;\nelse\n return;", Spaces); 23542 verifyFormat("switch ( a )\ncase 1:\n return;", Spaces); 23543 verifyFormat("while ( a )\n return;", Spaces); 23544 verifyFormat("while ( (a && b) )\n return;", Spaces); 23545 verifyFormat("do {\n} while ( 1 != 0 );", Spaces); 23546 verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces); 23547 // Check that space on the left of "::" is inserted as expected at beginning 23548 // of condition. 23549 verifyFormat("while ( ::func() )\n return;", Spaces); 23550 23551 // Check impact of ControlStatementsExceptControlMacros is honored. 23552 Spaces.SpaceBeforeParens = 23553 FormatStyle::SBPO_ControlStatementsExceptControlMacros; 23554 verifyFormat("MYIF( a )\n return;", Spaces); 23555 verifyFormat("MYIF( a )\n return;\nelse MYIF( b )\n return;", Spaces); 23556 verifyFormat("MYIF( a )\n return;\nelse\n return;", Spaces); 23557 } 23558 23559 TEST_F(FormatTest, AlternativeOperators) { 23560 // Test case for ensuring alternate operators are not 23561 // combined with their right most neighbour. 23562 verifyFormat("int a and b;"); 23563 verifyFormat("int a and_eq b;"); 23564 verifyFormat("int a bitand b;"); 23565 verifyFormat("int a bitor b;"); 23566 verifyFormat("int a compl b;"); 23567 verifyFormat("int a not b;"); 23568 verifyFormat("int a not_eq b;"); 23569 verifyFormat("int a or b;"); 23570 verifyFormat("int a xor b;"); 23571 verifyFormat("int a xor_eq b;"); 23572 verifyFormat("return this not_eq bitand other;"); 23573 verifyFormat("bool operator not_eq(const X bitand other)"); 23574 23575 verifyFormat("int a and 5;"); 23576 verifyFormat("int a and_eq 5;"); 23577 verifyFormat("int a bitand 5;"); 23578 verifyFormat("int a bitor 5;"); 23579 verifyFormat("int a compl 5;"); 23580 verifyFormat("int a not 5;"); 23581 verifyFormat("int a not_eq 5;"); 23582 verifyFormat("int a or 5;"); 23583 verifyFormat("int a xor 5;"); 23584 verifyFormat("int a xor_eq 5;"); 23585 23586 verifyFormat("int a compl(5);"); 23587 verifyFormat("int a not(5);"); 23588 23589 /* FIXME handle alternate tokens 23590 * https://en.cppreference.com/w/cpp/language/operator_alternative 23591 // alternative tokens 23592 verifyFormat("compl foo();"); // ~foo(); 23593 verifyFormat("foo() <%%>;"); // foo(); 23594 verifyFormat("void foo() <%%>;"); // void foo(){} 23595 verifyFormat("int a <:1:>;"); // int a[1];[ 23596 verifyFormat("%:define ABC abc"); // #define ABC abc 23597 verifyFormat("%:%:"); // ## 23598 */ 23599 } 23600 23601 TEST_F(FormatTest, STLWhileNotDefineChed) { 23602 verifyFormat("#if defined(while)\n" 23603 "#define while EMIT WARNING C4005\n" 23604 "#endif // while"); 23605 } 23606 23607 TEST_F(FormatTest, OperatorSpacing) { 23608 FormatStyle Style = getLLVMStyle(); 23609 Style.PointerAlignment = FormatStyle::PAS_Right; 23610 verifyFormat("Foo::operator*();", Style); 23611 verifyFormat("Foo::operator void *();", Style); 23612 verifyFormat("Foo::operator void **();", Style); 23613 verifyFormat("Foo::operator void *&();", Style); 23614 verifyFormat("Foo::operator void *&&();", Style); 23615 verifyFormat("Foo::operator void const *();", Style); 23616 verifyFormat("Foo::operator void const **();", Style); 23617 verifyFormat("Foo::operator void const *&();", Style); 23618 verifyFormat("Foo::operator void const *&&();", Style); 23619 verifyFormat("Foo::operator()(void *);", Style); 23620 verifyFormat("Foo::operator*(void *);", Style); 23621 verifyFormat("Foo::operator*();", Style); 23622 verifyFormat("Foo::operator**();", Style); 23623 verifyFormat("Foo::operator&();", Style); 23624 verifyFormat("Foo::operator<int> *();", Style); 23625 verifyFormat("Foo::operator<Foo> *();", Style); 23626 verifyFormat("Foo::operator<int> **();", Style); 23627 verifyFormat("Foo::operator<Foo> **();", Style); 23628 verifyFormat("Foo::operator<int> &();", Style); 23629 verifyFormat("Foo::operator<Foo> &();", Style); 23630 verifyFormat("Foo::operator<int> &&();", Style); 23631 verifyFormat("Foo::operator<Foo> &&();", Style); 23632 verifyFormat("Foo::operator<int> *&();", Style); 23633 verifyFormat("Foo::operator<Foo> *&();", Style); 23634 verifyFormat("Foo::operator<int> *&&();", Style); 23635 verifyFormat("Foo::operator<Foo> *&&();", Style); 23636 verifyFormat("operator*(int (*)(), class Foo);", Style); 23637 23638 verifyFormat("Foo::operator&();", Style); 23639 verifyFormat("Foo::operator void &();", Style); 23640 verifyFormat("Foo::operator void const &();", Style); 23641 verifyFormat("Foo::operator()(void &);", Style); 23642 verifyFormat("Foo::operator&(void &);", Style); 23643 verifyFormat("Foo::operator&();", Style); 23644 verifyFormat("operator&(int (&)(), class Foo);", Style); 23645 verifyFormat("operator&&(int (&)(), class Foo);", Style); 23646 23647 verifyFormat("Foo::operator&&();", Style); 23648 verifyFormat("Foo::operator**();", Style); 23649 verifyFormat("Foo::operator void &&();", Style); 23650 verifyFormat("Foo::operator void const &&();", Style); 23651 verifyFormat("Foo::operator()(void &&);", Style); 23652 verifyFormat("Foo::operator&&(void &&);", Style); 23653 verifyFormat("Foo::operator&&();", Style); 23654 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23655 verifyFormat("operator const nsTArrayRight<E> &()", Style); 23656 verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()", 23657 Style); 23658 verifyFormat("operator void **()", Style); 23659 verifyFormat("operator const FooRight<Object> &()", Style); 23660 verifyFormat("operator const FooRight<Object> *()", Style); 23661 verifyFormat("operator const FooRight<Object> **()", Style); 23662 verifyFormat("operator const FooRight<Object> *&()", Style); 23663 verifyFormat("operator const FooRight<Object> *&&()", Style); 23664 23665 Style.PointerAlignment = FormatStyle::PAS_Left; 23666 verifyFormat("Foo::operator*();", Style); 23667 verifyFormat("Foo::operator**();", Style); 23668 verifyFormat("Foo::operator void*();", Style); 23669 verifyFormat("Foo::operator void**();", Style); 23670 verifyFormat("Foo::operator void*&();", Style); 23671 verifyFormat("Foo::operator void*&&();", Style); 23672 verifyFormat("Foo::operator void const*();", Style); 23673 verifyFormat("Foo::operator void const**();", Style); 23674 verifyFormat("Foo::operator void const*&();", Style); 23675 verifyFormat("Foo::operator void const*&&();", Style); 23676 verifyFormat("Foo::operator/*comment*/ void*();", Style); 23677 verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style); 23678 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style); 23679 verifyFormat("Foo::operator()(void*);", Style); 23680 verifyFormat("Foo::operator*(void*);", Style); 23681 verifyFormat("Foo::operator*();", Style); 23682 verifyFormat("Foo::operator<int>*();", Style); 23683 verifyFormat("Foo::operator<Foo>*();", Style); 23684 verifyFormat("Foo::operator<int>**();", Style); 23685 verifyFormat("Foo::operator<Foo>**();", Style); 23686 verifyFormat("Foo::operator<Foo>*&();", Style); 23687 verifyFormat("Foo::operator<int>&();", Style); 23688 verifyFormat("Foo::operator<Foo>&();", Style); 23689 verifyFormat("Foo::operator<int>&&();", Style); 23690 verifyFormat("Foo::operator<Foo>&&();", Style); 23691 verifyFormat("Foo::operator<int>*&();", Style); 23692 verifyFormat("Foo::operator<Foo>*&();", Style); 23693 verifyFormat("operator*(int (*)(), class Foo);", Style); 23694 23695 verifyFormat("Foo::operator&();", Style); 23696 verifyFormat("Foo::operator void&();", Style); 23697 verifyFormat("Foo::operator void const&();", Style); 23698 verifyFormat("Foo::operator/*comment*/ void&();", Style); 23699 verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style); 23700 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style); 23701 verifyFormat("Foo::operator()(void&);", Style); 23702 verifyFormat("Foo::operator&(void&);", Style); 23703 verifyFormat("Foo::operator&();", Style); 23704 verifyFormat("operator&(int (&)(), class Foo);", Style); 23705 verifyFormat("operator&(int (&&)(), class Foo);", Style); 23706 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23707 23708 verifyFormat("Foo::operator&&();", Style); 23709 verifyFormat("Foo::operator void&&();", Style); 23710 verifyFormat("Foo::operator void const&&();", Style); 23711 verifyFormat("Foo::operator/*comment*/ void&&();", Style); 23712 verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style); 23713 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style); 23714 verifyFormat("Foo::operator()(void&&);", Style); 23715 verifyFormat("Foo::operator&&(void&&);", Style); 23716 verifyFormat("Foo::operator&&();", Style); 23717 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23718 verifyFormat("operator const nsTArrayLeft<E>&()", Style); 23719 verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()", 23720 Style); 23721 verifyFormat("operator void**()", Style); 23722 verifyFormat("operator const FooLeft<Object>&()", Style); 23723 verifyFormat("operator const FooLeft<Object>*()", Style); 23724 verifyFormat("operator const FooLeft<Object>**()", Style); 23725 verifyFormat("operator const FooLeft<Object>*&()", Style); 23726 verifyFormat("operator const FooLeft<Object>*&&()", Style); 23727 23728 // PR45107 23729 verifyFormat("operator Vector<String>&();", Style); 23730 verifyFormat("operator const Vector<String>&();", Style); 23731 verifyFormat("operator foo::Bar*();", Style); 23732 verifyFormat("operator const Foo<X>::Bar<Y>*();", Style); 23733 verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();", 23734 Style); 23735 23736 Style.PointerAlignment = FormatStyle::PAS_Middle; 23737 verifyFormat("Foo::operator*();", Style); 23738 verifyFormat("Foo::operator void *();", Style); 23739 verifyFormat("Foo::operator()(void *);", Style); 23740 verifyFormat("Foo::operator*(void *);", Style); 23741 verifyFormat("Foo::operator*();", Style); 23742 verifyFormat("operator*(int (*)(), class Foo);", Style); 23743 23744 verifyFormat("Foo::operator&();", Style); 23745 verifyFormat("Foo::operator void &();", Style); 23746 verifyFormat("Foo::operator void const &();", Style); 23747 verifyFormat("Foo::operator()(void &);", Style); 23748 verifyFormat("Foo::operator&(void &);", Style); 23749 verifyFormat("Foo::operator&();", Style); 23750 verifyFormat("operator&(int (&)(), class Foo);", Style); 23751 23752 verifyFormat("Foo::operator&&();", Style); 23753 verifyFormat("Foo::operator void &&();", Style); 23754 verifyFormat("Foo::operator void const &&();", 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 23761 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) { 23762 FormatStyle Style = getLLVMStyle(); 23763 // PR46157 23764 verifyFormat("foo(operator+, -42);", Style); 23765 verifyFormat("foo(operator++, -42);", Style); 23766 verifyFormat("foo(operator--, -42);", Style); 23767 verifyFormat("foo(-42, operator--);", Style); 23768 verifyFormat("foo(-42, operator, );", Style); 23769 verifyFormat("foo(operator, , -42);", Style); 23770 } 23771 23772 TEST_F(FormatTest, WhitespaceSensitiveMacros) { 23773 FormatStyle Style = getLLVMStyle(); 23774 Style.WhitespaceSensitiveMacros.push_back("FOO"); 23775 23776 // Don't use the helpers here, since 'mess up' will change the whitespace 23777 // and these are all whitespace sensitive by definition 23778 EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);", 23779 format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style)); 23780 EXPECT_EQ( 23781 "FOO(String-ized&Messy+But\\(: :Still)=Intentional);", 23782 format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style)); 23783 EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);", 23784 format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style)); 23785 EXPECT_EQ("FOO(String-ized&Messy+But,: :\n" 23786 " Still=Intentional);", 23787 format("FOO(String-ized&Messy+But,: :\n" 23788 " Still=Intentional);", 23789 Style)); 23790 Style.AlignConsecutiveAssignments.Enabled = true; 23791 EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n" 23792 " Still=Intentional);", 23793 format("FOO(String-ized=&Messy+But,: :\n" 23794 " Still=Intentional);", 23795 Style)); 23796 23797 Style.ColumnLimit = 21; 23798 EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);", 23799 format("FOO(String-ized&Messy+But: :Still=Intentional);", Style)); 23800 } 23801 23802 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) { 23803 // These tests are not in NamespaceEndCommentsFixerTest because that doesn't 23804 // test its interaction with line wrapping 23805 FormatStyle Style = getLLVMStyleWithColumns(80); 23806 verifyFormat("namespace {\n" 23807 "int i;\n" 23808 "int j;\n" 23809 "} // namespace", 23810 Style); 23811 23812 verifyFormat("namespace AAA {\n" 23813 "int i;\n" 23814 "int j;\n" 23815 "} // namespace AAA", 23816 Style); 23817 23818 EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n" 23819 "int i;\n" 23820 "int j;\n" 23821 "} // namespace Averyveryveryverylongnamespace", 23822 format("namespace Averyveryveryverylongnamespace {\n" 23823 "int i;\n" 23824 "int j;\n" 23825 "}", 23826 Style)); 23827 23828 EXPECT_EQ( 23829 "namespace " 23830 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n" 23831 " went::mad::now {\n" 23832 "int i;\n" 23833 "int j;\n" 23834 "} // namespace\n" 23835 " // " 23836 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::" 23837 "went::mad::now", 23838 format("namespace " 23839 "would::it::save::you::a::lot::of::time::if_::i::" 23840 "just::gave::up::and_::went::mad::now {\n" 23841 "int i;\n" 23842 "int j;\n" 23843 "}", 23844 Style)); 23845 23846 // This used to duplicate the comment again and again on subsequent runs 23847 EXPECT_EQ( 23848 "namespace " 23849 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n" 23850 " went::mad::now {\n" 23851 "int i;\n" 23852 "int j;\n" 23853 "} // namespace\n" 23854 " // " 23855 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::" 23856 "went::mad::now", 23857 format("namespace " 23858 "would::it::save::you::a::lot::of::time::if_::i::" 23859 "just::gave::up::and_::went::mad::now {\n" 23860 "int i;\n" 23861 "int j;\n" 23862 "} // namespace\n" 23863 " // " 23864 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::" 23865 "and_::went::mad::now", 23866 Style)); 23867 } 23868 23869 TEST_F(FormatTest, LikelyUnlikely) { 23870 FormatStyle Style = getLLVMStyle(); 23871 23872 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23873 " return 29;\n" 23874 "}", 23875 Style); 23876 23877 verifyFormat("if (argc > 5) [[likely]] {\n" 23878 " return 29;\n" 23879 "}", 23880 Style); 23881 23882 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23883 " return 29;\n" 23884 "} else [[likely]] {\n" 23885 " return 42;\n" 23886 "}\n", 23887 Style); 23888 23889 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23890 " return 29;\n" 23891 "} else if (argc > 10) [[likely]] {\n" 23892 " return 99;\n" 23893 "} else {\n" 23894 " return 42;\n" 23895 "}\n", 23896 Style); 23897 23898 verifyFormat("if (argc > 5) [[gnu::unused]] {\n" 23899 " return 29;\n" 23900 "}", 23901 Style); 23902 23903 verifyFormat("if (argc > 5) [[unlikely]]\n" 23904 " return 29;\n", 23905 Style); 23906 verifyFormat("if (argc > 5) [[likely]]\n" 23907 " return 29;\n", 23908 Style); 23909 23910 verifyFormat("while (limit > 0) [[unlikely]] {\n" 23911 " --limit;\n" 23912 "}", 23913 Style); 23914 verifyFormat("for (auto &limit : limits) [[likely]] {\n" 23915 " --limit;\n" 23916 "}", 23917 Style); 23918 23919 verifyFormat("for (auto &limit : limits) [[unlikely]]\n" 23920 " --limit;", 23921 Style); 23922 verifyFormat("while (limit > 0) [[likely]]\n" 23923 " --limit;", 23924 Style); 23925 23926 Style.AttributeMacros.push_back("UNLIKELY"); 23927 Style.AttributeMacros.push_back("LIKELY"); 23928 verifyFormat("if (argc > 5) UNLIKELY\n" 23929 " return 29;\n", 23930 Style); 23931 23932 verifyFormat("if (argc > 5) UNLIKELY {\n" 23933 " return 29;\n" 23934 "}", 23935 Style); 23936 verifyFormat("if (argc > 5) UNLIKELY {\n" 23937 " return 29;\n" 23938 "} else [[likely]] {\n" 23939 " return 42;\n" 23940 "}\n", 23941 Style); 23942 verifyFormat("if (argc > 5) UNLIKELY {\n" 23943 " return 29;\n" 23944 "} else LIKELY {\n" 23945 " return 42;\n" 23946 "}\n", 23947 Style); 23948 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23949 " return 29;\n" 23950 "} else LIKELY {\n" 23951 " return 42;\n" 23952 "}\n", 23953 Style); 23954 23955 verifyFormat("for (auto &limit : limits) UNLIKELY {\n" 23956 " --limit;\n" 23957 "}", 23958 Style); 23959 verifyFormat("while (limit > 0) LIKELY {\n" 23960 " --limit;\n" 23961 "}", 23962 Style); 23963 23964 verifyFormat("while (limit > 0) UNLIKELY\n" 23965 " --limit;", 23966 Style); 23967 verifyFormat("for (auto &limit : limits) LIKELY\n" 23968 " --limit;", 23969 Style); 23970 } 23971 23972 TEST_F(FormatTest, PenaltyIndentedWhitespace) { 23973 verifyFormat("Constructor()\n" 23974 " : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 23975 " aaaa(aaaaaaaaaaaaaaaaaa, " 23976 "aaaaaaaaaaaaaaaaaat))"); 23977 verifyFormat("Constructor()\n" 23978 " : aaaaaaaaaaaaa(aaaaaa), " 23979 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)"); 23980 23981 FormatStyle StyleWithWhitespacePenalty = getLLVMStyle(); 23982 StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5; 23983 verifyFormat("Constructor()\n" 23984 " : aaaaaa(aaaaaa),\n" 23985 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 23986 " aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))", 23987 StyleWithWhitespacePenalty); 23988 verifyFormat("Constructor()\n" 23989 " : aaaaaaaaaaaaa(aaaaaa), " 23990 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)", 23991 StyleWithWhitespacePenalty); 23992 } 23993 23994 TEST_F(FormatTest, LLVMDefaultStyle) { 23995 FormatStyle Style = getLLVMStyle(); 23996 verifyFormat("extern \"C\" {\n" 23997 "int foo();\n" 23998 "}", 23999 Style); 24000 } 24001 TEST_F(FormatTest, GNUDefaultStyle) { 24002 FormatStyle Style = getGNUStyle(); 24003 verifyFormat("extern \"C\"\n" 24004 "{\n" 24005 " int foo ();\n" 24006 "}", 24007 Style); 24008 } 24009 TEST_F(FormatTest, MozillaDefaultStyle) { 24010 FormatStyle Style = getMozillaStyle(); 24011 verifyFormat("extern \"C\"\n" 24012 "{\n" 24013 " int foo();\n" 24014 "}", 24015 Style); 24016 } 24017 TEST_F(FormatTest, GoogleDefaultStyle) { 24018 FormatStyle Style = getGoogleStyle(); 24019 verifyFormat("extern \"C\" {\n" 24020 "int foo();\n" 24021 "}", 24022 Style); 24023 } 24024 TEST_F(FormatTest, ChromiumDefaultStyle) { 24025 FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp); 24026 verifyFormat("extern \"C\" {\n" 24027 "int foo();\n" 24028 "}", 24029 Style); 24030 } 24031 TEST_F(FormatTest, MicrosoftDefaultStyle) { 24032 FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp); 24033 verifyFormat("extern \"C\"\n" 24034 "{\n" 24035 " int foo();\n" 24036 "}", 24037 Style); 24038 } 24039 TEST_F(FormatTest, WebKitDefaultStyle) { 24040 FormatStyle Style = getWebKitStyle(); 24041 verifyFormat("extern \"C\" {\n" 24042 "int foo();\n" 24043 "}", 24044 Style); 24045 } 24046 24047 TEST_F(FormatTest, Concepts) { 24048 EXPECT_EQ(getLLVMStyle().BreakBeforeConceptDeclarations, 24049 FormatStyle::BBCDS_Always); 24050 verifyFormat("template <typename T>\n" 24051 "concept True = true;"); 24052 24053 verifyFormat("template <typename T>\n" 24054 "concept C = ((false || foo()) && C2<T>) ||\n" 24055 " (std::trait<T>::value && Baz) || sizeof(T) >= 6;", 24056 getLLVMStyleWithColumns(60)); 24057 24058 verifyFormat("template <typename T>\n" 24059 "concept DelayedCheck = true && requires(T t) { t.bar(); } && " 24060 "sizeof(T) <= 8;"); 24061 24062 verifyFormat("template <typename T>\n" 24063 "concept DelayedCheck = true && requires(T t) {\n" 24064 " t.bar();\n" 24065 " t.baz();\n" 24066 " } && sizeof(T) <= 8;"); 24067 24068 verifyFormat("template <typename T>\n" 24069 "concept DelayedCheck = true && requires(T t) { // Comment\n" 24070 " t.bar();\n" 24071 " t.baz();\n" 24072 " } && sizeof(T) <= 8;"); 24073 24074 verifyFormat("template <typename T>\n" 24075 "concept DelayedCheck = false || requires(T t) { t.bar(); } && " 24076 "sizeof(T) <= 8;"); 24077 24078 verifyFormat("template <typename T>\n" 24079 "concept DelayedCheck = !!false || requires(T t) { t.bar(); } " 24080 "&& sizeof(T) <= 8;"); 24081 24082 verifyFormat( 24083 "template <typename T>\n" 24084 "concept DelayedCheck = static_cast<bool>(0) ||\n" 24085 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 24086 24087 verifyFormat("template <typename T>\n" 24088 "concept DelayedCheck = bool(0) || requires(T t) { t.bar(); } " 24089 "&& sizeof(T) <= 8;"); 24090 24091 verifyFormat( 24092 "template <typename T>\n" 24093 "concept DelayedCheck = (bool)(0) ||\n" 24094 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 24095 24096 verifyFormat("template <typename T>\n" 24097 "concept DelayedCheck = (bool)0 || requires(T t) { t.bar(); } " 24098 "&& sizeof(T) <= 8;"); 24099 24100 verifyFormat("template <typename T>\n" 24101 "concept Size = sizeof(T) >= 5 && requires(T t) { t.bar(); } && " 24102 "sizeof(T) <= 8;"); 24103 24104 verifyFormat("template <typename T>\n" 24105 "concept Size = 2 < 5 && 2 <= 5 && 8 >= 5 && 8 > 5 &&\n" 24106 " requires(T t) {\n" 24107 " t.bar();\n" 24108 " t.baz();\n" 24109 " } && sizeof(T) <= 8 && !(4 < 3);", 24110 getLLVMStyleWithColumns(60)); 24111 24112 verifyFormat("template <typename T>\n" 24113 "concept TrueOrNot = IsAlwaysTrue || IsNeverTrue;"); 24114 24115 verifyFormat("template <typename T>\n" 24116 "concept C = foo();"); 24117 24118 verifyFormat("template <typename T>\n" 24119 "concept C = foo(T());"); 24120 24121 verifyFormat("template <typename T>\n" 24122 "concept C = foo(T{});"); 24123 24124 verifyFormat("template <typename T>\n" 24125 "concept Size = V<sizeof(T)>::Value > 5;"); 24126 24127 verifyFormat("template <typename T>\n" 24128 "concept True = S<T>::Value;"); 24129 24130 verifyFormat( 24131 "template <typename T>\n" 24132 "concept C = []() { return true; }() && requires(T t) { t.bar(); } &&\n" 24133 " sizeof(T) <= 8;"); 24134 24135 // FIXME: This is misformatted because the fake l paren starts at bool, not at 24136 // the lambda l square. 24137 verifyFormat("template <typename T>\n" 24138 "concept C = [] -> bool { return true; }() && requires(T t) { " 24139 "t.bar(); } &&\n" 24140 " sizeof(T) <= 8;"); 24141 24142 verifyFormat( 24143 "template <typename T>\n" 24144 "concept C = decltype([]() { return std::true_type{}; }())::value &&\n" 24145 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 24146 24147 verifyFormat("template <typename T>\n" 24148 "concept C = decltype([]() { return std::true_type{}; " 24149 "}())::value && requires(T t) { t.bar(); } && sizeof(T) <= 8;", 24150 getLLVMStyleWithColumns(120)); 24151 24152 verifyFormat("template <typename T>\n" 24153 "concept C = decltype([]() -> std::true_type { return {}; " 24154 "}())::value &&\n" 24155 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 24156 24157 verifyFormat("template <typename T>\n" 24158 "concept C = true;\n" 24159 "Foo Bar;"); 24160 24161 verifyFormat("template <typename T>\n" 24162 "concept Hashable = requires(T a) {\n" 24163 " { std::hash<T>{}(a) } -> " 24164 "std::convertible_to<std::size_t>;\n" 24165 " };"); 24166 24167 verifyFormat( 24168 "template <typename T>\n" 24169 "concept EqualityComparable = requires(T a, T b) {\n" 24170 " { a == b } -> std::same_as<bool>;\n" 24171 " };"); 24172 24173 verifyFormat( 24174 "template <typename T>\n" 24175 "concept EqualityComparable = requires(T a, T b) {\n" 24176 " { a == b } -> std::same_as<bool>;\n" 24177 " { a != b } -> std::same_as<bool>;\n" 24178 " };"); 24179 24180 verifyFormat("template <typename T>\n" 24181 "concept WeakEqualityComparable = requires(T a, T b) {\n" 24182 " { a == b };\n" 24183 " { a != b };\n" 24184 " };"); 24185 24186 verifyFormat("template <typename T>\n" 24187 "concept HasSizeT = requires { typename T::size_t; };"); 24188 24189 verifyFormat("template <typename T>\n" 24190 "concept Semiregular =\n" 24191 " DefaultConstructible<T> && CopyConstructible<T> && " 24192 "CopyAssignable<T> &&\n" 24193 " requires(T a, std::size_t n) {\n" 24194 " requires Same<T *, decltype(&a)>;\n" 24195 " { a.~T() } noexcept;\n" 24196 " requires Same<T *, decltype(new T)>;\n" 24197 " requires Same<T *, decltype(new T[n])>;\n" 24198 " { delete new T; };\n" 24199 " { delete new T[n]; };\n" 24200 " };"); 24201 24202 verifyFormat("template <typename T>\n" 24203 "concept Semiregular =\n" 24204 " requires(T a, std::size_t n) {\n" 24205 " requires Same<T *, decltype(&a)>;\n" 24206 " { a.~T() } noexcept;\n" 24207 " requires Same<T *, decltype(new T)>;\n" 24208 " requires Same<T *, decltype(new T[n])>;\n" 24209 " { delete new T; };\n" 24210 " { delete new T[n]; };\n" 24211 " { new T } -> std::same_as<T *>;\n" 24212 " } && DefaultConstructible<T> && CopyConstructible<T> && " 24213 "CopyAssignable<T>;"); 24214 24215 verifyFormat( 24216 "template <typename T>\n" 24217 "concept Semiregular =\n" 24218 " DefaultConstructible<T> && requires(T a, std::size_t n) {\n" 24219 " requires Same<T *, decltype(&a)>;\n" 24220 " { a.~T() } noexcept;\n" 24221 " requires Same<T *, decltype(new T)>;\n" 24222 " requires Same<T *, decltype(new " 24223 "T[n])>;\n" 24224 " { delete new T; };\n" 24225 " { delete new T[n]; };\n" 24226 " } && CopyConstructible<T> && " 24227 "CopyAssignable<T>;"); 24228 24229 verifyFormat("template <typename T>\n" 24230 "concept Two = requires(T t) {\n" 24231 " { t.foo() } -> std::same_as<Bar>;\n" 24232 " } && requires(T &&t) {\n" 24233 " { t.foo() } -> std::same_as<Bar &&>;\n" 24234 " };"); 24235 24236 verifyFormat( 24237 "template <typename T>\n" 24238 "concept C = requires(T x) {\n" 24239 " { *x } -> std::convertible_to<typename T::inner>;\n" 24240 " { x + 1 } noexcept -> std::same_as<int>;\n" 24241 " { x * 1 } -> std::convertible_to<T>;\n" 24242 " };"); 24243 24244 verifyFormat( 24245 "template <typename T, typename U = T>\n" 24246 "concept Swappable = requires(T &&t, U &&u) {\n" 24247 " swap(std::forward<T>(t), std::forward<U>(u));\n" 24248 " swap(std::forward<U>(u), std::forward<T>(t));\n" 24249 " };"); 24250 24251 verifyFormat("template <typename T, typename U>\n" 24252 "concept Common = requires(T &&t, U &&u) {\n" 24253 " typename CommonType<T, U>;\n" 24254 " { CommonType<T, U>(std::forward<T>(t)) };\n" 24255 " };"); 24256 24257 verifyFormat("template <typename T, typename U>\n" 24258 "concept Common = requires(T &&t, U &&u) {\n" 24259 " typename CommonType<T, U>;\n" 24260 " { CommonType<T, U>{std::forward<T>(t)} };\n" 24261 " };"); 24262 24263 verifyFormat( 24264 "template <typename T>\n" 24265 "concept C = requires(T t) {\n" 24266 " requires Bar<T> && Foo<T>;\n" 24267 " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n" 24268 " };"); 24269 24270 verifyFormat("template <typename T>\n" 24271 "concept HasFoo = requires(T t) {\n" 24272 " { t.foo() };\n" 24273 " t.foo();\n" 24274 " };\n" 24275 "template <typename T>\n" 24276 "concept HasBar = requires(T t) {\n" 24277 " { t.bar() };\n" 24278 " t.bar();\n" 24279 " };"); 24280 24281 verifyFormat("template <typename T>\n" 24282 "concept Large = sizeof(T) > 10;"); 24283 24284 verifyFormat("template <typename T, typename U>\n" 24285 "concept FooableWith = requires(T t, U u) {\n" 24286 " typename T::foo_type;\n" 24287 " { t.foo(u) } -> typename T::foo_type;\n" 24288 " t++;\n" 24289 " };\n" 24290 "void doFoo(FooableWith<int> auto t) { t.foo(3); }"); 24291 24292 verifyFormat("template <typename T>\n" 24293 "concept Context = is_specialization_of_v<context, T>;"); 24294 24295 verifyFormat("template <typename T>\n" 24296 "concept Node = std::is_object_v<T>;"); 24297 24298 verifyFormat("template <class T>\n" 24299 "concept integral = __is_integral(T);"); 24300 24301 verifyFormat("template <class T>\n" 24302 "concept is2D = __array_extent(T, 1) == 2;"); 24303 24304 verifyFormat("template <class T>\n" 24305 "concept isRhs = __is_rvalue_expr(std::declval<T>() + 2)"); 24306 24307 verifyFormat("template <class T, class T2>\n" 24308 "concept Same = __is_same_as<T, T2>;"); 24309 24310 verifyFormat( 24311 "template <class _InIt, class _OutIt>\n" 24312 "concept _Can_reread_dest =\n" 24313 " std::forward_iterator<_OutIt> &&\n" 24314 " std::same_as<std::iter_value_t<_InIt>, std::iter_value_t<_OutIt>>;"); 24315 24316 auto Style = getLLVMStyle(); 24317 Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Allowed; 24318 24319 verifyFormat( 24320 "template <typename T>\n" 24321 "concept C = requires(T t) {\n" 24322 " requires Bar<T> && Foo<T>;\n" 24323 " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n" 24324 " };", 24325 Style); 24326 24327 verifyFormat("template <typename T>\n" 24328 "concept HasFoo = requires(T t) {\n" 24329 " { t.foo() };\n" 24330 " t.foo();\n" 24331 " };\n" 24332 "template <typename T>\n" 24333 "concept HasBar = requires(T t) {\n" 24334 " { t.bar() };\n" 24335 " t.bar();\n" 24336 " };", 24337 Style); 24338 24339 verifyFormat("template <typename T> concept True = true;", Style); 24340 24341 verifyFormat("template <typename T>\n" 24342 "concept C = decltype([]() -> std::true_type { return {}; " 24343 "}())::value &&\n" 24344 " requires(T t) { t.bar(); } && sizeof(T) <= 8;", 24345 Style); 24346 24347 verifyFormat("template <typename T>\n" 24348 "concept Semiregular =\n" 24349 " DefaultConstructible<T> && CopyConstructible<T> && " 24350 "CopyAssignable<T> &&\n" 24351 " requires(T a, std::size_t n) {\n" 24352 " requires Same<T *, decltype(&a)>;\n" 24353 " { a.~T() } noexcept;\n" 24354 " requires Same<T *, decltype(new T)>;\n" 24355 " requires Same<T *, decltype(new T[n])>;\n" 24356 " { delete new T; };\n" 24357 " { delete new T[n]; };\n" 24358 " };", 24359 Style); 24360 24361 Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Never; 24362 24363 verifyFormat("template <typename T> concept C =\n" 24364 " requires(T t) {\n" 24365 " requires Bar<T> && Foo<T>;\n" 24366 " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n" 24367 " };", 24368 Style); 24369 24370 verifyFormat("template <typename T> concept HasFoo = requires(T t) {\n" 24371 " { t.foo() };\n" 24372 " t.foo();\n" 24373 " };\n" 24374 "template <typename T> concept HasBar = requires(T t) {\n" 24375 " { t.bar() };\n" 24376 " t.bar();\n" 24377 " };", 24378 Style); 24379 24380 verifyFormat("template <typename T> concept True = true;", Style); 24381 24382 verifyFormat( 24383 "template <typename T> concept C = decltype([]() -> std::true_type {\n" 24384 " return {};\n" 24385 " }())::value &&\n" 24386 " requires(T t) { t.bar(); } && " 24387 "sizeof(T) <= 8;", 24388 Style); 24389 24390 verifyFormat("template <typename T> concept Semiregular =\n" 24391 " DefaultConstructible<T> && CopyConstructible<T> && " 24392 "CopyAssignable<T> &&\n" 24393 " requires(T a, std::size_t n) {\n" 24394 " requires Same<T *, decltype(&a)>;\n" 24395 " { a.~T() } noexcept;\n" 24396 " requires Same<T *, decltype(new T)>;\n" 24397 " requires Same<T *, decltype(new T[n])>;\n" 24398 " { delete new T; };\n" 24399 " { delete new T[n]; };\n" 24400 " };", 24401 Style); 24402 24403 // The following tests are invalid C++, we just want to make sure we don't 24404 // assert. 24405 verifyFormat("template <typename T>\n" 24406 "concept C = requires C2<T>;"); 24407 24408 verifyFormat("template <typename T>\n" 24409 "concept C = 5 + 4;"); 24410 24411 verifyFormat("template <typename T>\n" 24412 "concept C =\n" 24413 "class X;"); 24414 24415 verifyFormat("template <typename T>\n" 24416 "concept C = [] && true;"); 24417 24418 verifyFormat("template <typename T>\n" 24419 "concept C = [] && requires(T t) { typename T::size_type; };"); 24420 } 24421 24422 TEST_F(FormatTest, RequiresClausesPositions) { 24423 auto Style = getLLVMStyle(); 24424 EXPECT_EQ(Style.RequiresClausePosition, FormatStyle::RCPS_OwnLine); 24425 EXPECT_EQ(Style.IndentRequiresClause, true); 24426 24427 verifyFormat("template <typename T>\n" 24428 " requires(Foo<T> && std::trait<T>)\n" 24429 "struct Bar;", 24430 Style); 24431 24432 verifyFormat("template <typename T>\n" 24433 " requires(Foo<T> && std::trait<T>)\n" 24434 "class Bar {\n" 24435 "public:\n" 24436 " Bar(T t);\n" 24437 " bool baz();\n" 24438 "};", 24439 Style); 24440 24441 verifyFormat( 24442 "template <typename T>\n" 24443 " requires requires(T &&t) {\n" 24444 " typename T::I;\n" 24445 " requires(F<typename T::I> && std::trait<typename T::I>);\n" 24446 " }\n" 24447 "Bar(T) -> Bar<typename T::I>;", 24448 Style); 24449 24450 verifyFormat("template <typename T>\n" 24451 " requires(Foo<T> && std::trait<T>)\n" 24452 "constexpr T MyGlobal;", 24453 Style); 24454 24455 verifyFormat("template <typename T>\n" 24456 " requires Foo<T> && requires(T t) {\n" 24457 " { t.baz() } -> std::same_as<bool>;\n" 24458 " requires std::same_as<T::Factor, int>;\n" 24459 " }\n" 24460 "inline int bar(T t) {\n" 24461 " return t.baz() ? T::Factor : 5;\n" 24462 "}", 24463 Style); 24464 24465 verifyFormat("template <typename T>\n" 24466 "inline int bar(T t)\n" 24467 " requires Foo<T> && requires(T t) {\n" 24468 " { t.baz() } -> std::same_as<bool>;\n" 24469 " requires std::same_as<T::Factor, int>;\n" 24470 " }\n" 24471 "{\n" 24472 " return t.baz() ? T::Factor : 5;\n" 24473 "}", 24474 Style); 24475 24476 verifyFormat("template <typename T>\n" 24477 " requires F<T>\n" 24478 "int bar(T t) {\n" 24479 " return 5;\n" 24480 "}", 24481 Style); 24482 24483 verifyFormat("template <typename T>\n" 24484 "int bar(T t)\n" 24485 " requires F<T>\n" 24486 "{\n" 24487 " return 5;\n" 24488 "}", 24489 Style); 24490 24491 verifyFormat("template <typename T>\n" 24492 "int bar(T t)\n" 24493 " requires F<T>;", 24494 Style); 24495 24496 Style.IndentRequiresClause = false; 24497 verifyFormat("template <typename T>\n" 24498 "requires F<T>\n" 24499 "int bar(T t) {\n" 24500 " return 5;\n" 24501 "}", 24502 Style); 24503 24504 verifyFormat("template <typename T>\n" 24505 "int bar(T t)\n" 24506 "requires F<T>\n" 24507 "{\n" 24508 " return 5;\n" 24509 "}", 24510 Style); 24511 24512 Style.RequiresClausePosition = FormatStyle::RCPS_SingleLine; 24513 verifyFormat("template <typename T> requires Foo<T> struct Bar {};\n" 24514 "template <typename T> requires Foo<T> void bar() {}\n" 24515 "template <typename T> void bar() requires Foo<T> {}\n" 24516 "template <typename T> void bar() requires Foo<T>;\n" 24517 "template <typename T> requires Foo<T> Bar(T) -> Bar<T>;", 24518 Style); 24519 24520 auto ColumnStyle = Style; 24521 ColumnStyle.ColumnLimit = 40; 24522 verifyFormat("template <typename AAAAAAA>\n" 24523 "requires Foo<T> struct Bar {};\n" 24524 "template <typename AAAAAAA>\n" 24525 "requires Foo<T> void bar() {}\n" 24526 "template <typename AAAAAAA>\n" 24527 "void bar() requires Foo<T> {}\n" 24528 "template <typename AAAAAAA>\n" 24529 "requires Foo<T> Baz(T) -> Baz<T>;", 24530 ColumnStyle); 24531 24532 verifyFormat("template <typename T>\n" 24533 "requires Foo<AAAAAAA> struct Bar {};\n" 24534 "template <typename T>\n" 24535 "requires Foo<AAAAAAA> void bar() {}\n" 24536 "template <typename T>\n" 24537 "void bar() requires Foo<AAAAAAA> {}\n" 24538 "template <typename T>\n" 24539 "requires Foo<AAAAAAA> Bar(T) -> Bar<T>;", 24540 ColumnStyle); 24541 24542 verifyFormat("template <typename AAAAAAA>\n" 24543 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24544 "struct Bar {};\n" 24545 "template <typename AAAAAAA>\n" 24546 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24547 "void bar() {}\n" 24548 "template <typename AAAAAAA>\n" 24549 "void bar()\n" 24550 " requires Foo<AAAAAAAAAAAAAAAA> {}\n" 24551 "template <typename AAAAAAA>\n" 24552 "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n" 24553 "template <typename AAAAAAA>\n" 24554 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24555 "Bar(T) -> Bar<T>;", 24556 ColumnStyle); 24557 24558 Style.RequiresClausePosition = FormatStyle::RCPS_WithFollowing; 24559 ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithFollowing; 24560 24561 verifyFormat("template <typename T>\n" 24562 "requires Foo<T> struct Bar {};\n" 24563 "template <typename T>\n" 24564 "requires Foo<T> void bar() {}\n" 24565 "template <typename T>\n" 24566 "void bar()\n" 24567 "requires Foo<T> {}\n" 24568 "template <typename T>\n" 24569 "void bar()\n" 24570 "requires Foo<T>;\n" 24571 "template <typename T>\n" 24572 "requires Foo<T> Bar(T) -> Bar<T>;", 24573 Style); 24574 24575 verifyFormat("template <typename AAAAAAA>\n" 24576 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24577 "struct Bar {};\n" 24578 "template <typename AAAAAAA>\n" 24579 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24580 "void bar() {}\n" 24581 "template <typename AAAAAAA>\n" 24582 "void bar()\n" 24583 "requires Foo<AAAAAAAAAAAAAAAA> {}\n" 24584 "template <typename AAAAAAA>\n" 24585 "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n" 24586 "template <typename AAAAAAA>\n" 24587 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24588 "Bar(T) -> Bar<T>;", 24589 ColumnStyle); 24590 24591 Style.IndentRequiresClause = true; 24592 ColumnStyle.IndentRequiresClause = true; 24593 24594 verifyFormat("template <typename T>\n" 24595 " requires Foo<T> struct Bar {};\n" 24596 "template <typename T>\n" 24597 " requires Foo<T> void bar() {}\n" 24598 "template <typename T>\n" 24599 "void bar()\n" 24600 " requires Foo<T> {}\n" 24601 "template <typename T>\n" 24602 " requires Foo<T> Bar(T) -> Bar<T>;", 24603 Style); 24604 24605 verifyFormat("template <typename AAAAAAA>\n" 24606 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24607 "struct Bar {};\n" 24608 "template <typename AAAAAAA>\n" 24609 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24610 "void bar() {}\n" 24611 "template <typename AAAAAAA>\n" 24612 "void bar()\n" 24613 " requires Foo<AAAAAAAAAAAAAAAA> {}\n" 24614 "template <typename AAAAAAA>\n" 24615 " requires Foo<AAAAAA> Bar(T) -> Bar<T>;\n" 24616 "template <typename AAAAAAA>\n" 24617 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24618 "Bar(T) -> Bar<T>;", 24619 ColumnStyle); 24620 24621 Style.RequiresClausePosition = FormatStyle::RCPS_WithPreceding; 24622 ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithPreceding; 24623 24624 verifyFormat("template <typename T> requires Foo<T>\n" 24625 "struct Bar {};\n" 24626 "template <typename T> requires Foo<T>\n" 24627 "void bar() {}\n" 24628 "template <typename T>\n" 24629 "void bar() requires Foo<T>\n" 24630 "{}\n" 24631 "template <typename T> void bar() requires Foo<T>;\n" 24632 "template <typename T> requires Foo<T>\n" 24633 "Bar(T) -> Bar<T>;", 24634 Style); 24635 24636 verifyFormat("template <typename AAAAAAA>\n" 24637 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24638 "struct Bar {};\n" 24639 "template <typename AAAAAAA>\n" 24640 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24641 "void bar() {}\n" 24642 "template <typename AAAAAAA>\n" 24643 "void bar()\n" 24644 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24645 "{}\n" 24646 "template <typename AAAAAAA>\n" 24647 "requires Foo<AAAAAAAA>\n" 24648 "Bar(T) -> Bar<T>;\n" 24649 "template <typename AAAAAAA>\n" 24650 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24651 "Bar(T) -> Bar<T>;", 24652 ColumnStyle); 24653 } 24654 24655 TEST_F(FormatTest, RequiresClauses) { 24656 verifyFormat("struct [[nodiscard]] zero_t {\n" 24657 " template <class T>\n" 24658 " requires requires { number_zero_v<T>; }\n" 24659 " [[nodiscard]] constexpr operator T() const {\n" 24660 " return number_zero_v<T>;\n" 24661 " }\n" 24662 "};"); 24663 24664 auto Style = getLLVMStyle(); 24665 24666 verifyFormat( 24667 "template <typename T>\n" 24668 " requires is_default_constructible_v<hash<T>> and\n" 24669 " is_copy_constructible_v<hash<T>> and\n" 24670 " is_move_constructible_v<hash<T>> and\n" 24671 " is_copy_assignable_v<hash<T>> and " 24672 "is_move_assignable_v<hash<T>> and\n" 24673 " is_destructible_v<hash<T>> and is_swappable_v<hash<T>> and\n" 24674 " is_callable_v<hash<T>(T)> and\n" 24675 " is_same_v<size_t, decltype(hash<T>(declval<T>()))> and\n" 24676 " is_same_v<size_t, decltype(hash<T>(declval<T &>()))> and\n" 24677 " is_same_v<size_t, decltype(hash<T>(declval<const T &>()))>\n" 24678 "struct S {};", 24679 Style); 24680 24681 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 24682 verifyFormat( 24683 "template <typename T>\n" 24684 " requires is_default_constructible_v<hash<T>>\n" 24685 " and is_copy_constructible_v<hash<T>>\n" 24686 " and is_move_constructible_v<hash<T>>\n" 24687 " and is_copy_assignable_v<hash<T>> and " 24688 "is_move_assignable_v<hash<T>>\n" 24689 " and is_destructible_v<hash<T>> and is_swappable_v<hash<T>>\n" 24690 " and is_callable_v<hash<T>(T)>\n" 24691 " and is_same_v<size_t, decltype(hash<T>(declval<T>()))>\n" 24692 " and is_same_v<size_t, decltype(hash<T>(declval<T &>()))>\n" 24693 " and is_same_v<size_t, decltype(hash<T>(declval<const T " 24694 "&>()))>\n" 24695 "struct S {};", 24696 Style); 24697 24698 // Not a clause, but we once hit an assert. 24699 verifyFormat("#if 0\n" 24700 "#else\n" 24701 "foo();\n" 24702 "#endif\n" 24703 "bar(requires);"); 24704 } 24705 24706 TEST_F(FormatTest, StatementAttributeLikeMacros) { 24707 FormatStyle Style = getLLVMStyle(); 24708 StringRef Source = "void Foo::slot() {\n" 24709 " unsigned char MyChar = 'x';\n" 24710 " emit signal(MyChar);\n" 24711 " Q_EMIT signal(MyChar);\n" 24712 "}"; 24713 24714 EXPECT_EQ(Source, format(Source, Style)); 24715 24716 Style.AlignConsecutiveDeclarations.Enabled = true; 24717 EXPECT_EQ("void Foo::slot() {\n" 24718 " unsigned char MyChar = 'x';\n" 24719 " emit signal(MyChar);\n" 24720 " Q_EMIT signal(MyChar);\n" 24721 "}", 24722 format(Source, Style)); 24723 24724 Style.StatementAttributeLikeMacros.push_back("emit"); 24725 EXPECT_EQ(Source, format(Source, Style)); 24726 24727 Style.StatementAttributeLikeMacros = {}; 24728 EXPECT_EQ("void Foo::slot() {\n" 24729 " unsigned char MyChar = 'x';\n" 24730 " emit signal(MyChar);\n" 24731 " Q_EMIT signal(MyChar);\n" 24732 "}", 24733 format(Source, Style)); 24734 } 24735 24736 TEST_F(FormatTest, IndentAccessModifiers) { 24737 FormatStyle Style = getLLVMStyle(); 24738 Style.IndentAccessModifiers = true; 24739 // Members are *two* levels below the record; 24740 // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation. 24741 verifyFormat("class C {\n" 24742 " int i;\n" 24743 "};\n", 24744 Style); 24745 verifyFormat("union C {\n" 24746 " int i;\n" 24747 " unsigned u;\n" 24748 "};\n", 24749 Style); 24750 // Access modifiers should be indented one level below the record. 24751 verifyFormat("class C {\n" 24752 " public:\n" 24753 " int i;\n" 24754 "};\n", 24755 Style); 24756 verifyFormat("struct S {\n" 24757 " private:\n" 24758 " class C {\n" 24759 " int j;\n" 24760 "\n" 24761 " public:\n" 24762 " C();\n" 24763 " };\n" 24764 "\n" 24765 " public:\n" 24766 " int i;\n" 24767 "};\n", 24768 Style); 24769 // Enumerations are not records and should be unaffected. 24770 Style.AllowShortEnumsOnASingleLine = false; 24771 verifyFormat("enum class E {\n" 24772 " A,\n" 24773 " B\n" 24774 "};\n", 24775 Style); 24776 // Test with a different indentation width; 24777 // also proves that the result is Style.AccessModifierOffset agnostic. 24778 Style.IndentWidth = 3; 24779 verifyFormat("class C {\n" 24780 " public:\n" 24781 " int i;\n" 24782 "};\n", 24783 Style); 24784 } 24785 24786 TEST_F(FormatTest, LimitlessStringsAndComments) { 24787 auto Style = getLLVMStyleWithColumns(0); 24788 constexpr StringRef Code = 24789 "/**\n" 24790 " * This is a multiline comment with quite some long lines, at least for " 24791 "the LLVM Style.\n" 24792 " * We will redo this with strings and line comments. Just to check if " 24793 "everything is working.\n" 24794 " */\n" 24795 "bool foo() {\n" 24796 " /* Single line multi line comment. */\n" 24797 " const std::string String = \"This is a multiline string with quite " 24798 "some long lines, at least for the LLVM Style.\"\n" 24799 " \"We already did it with multi line " 24800 "comments, and we will do it with line comments. Just to check if " 24801 "everything is working.\";\n" 24802 " // This is a line comment (block) with quite some long lines, at " 24803 "least for the LLVM Style.\n" 24804 " // We already did this with multi line comments and strings. Just to " 24805 "check if everything is working.\n" 24806 " const std::string SmallString = \"Hello World\";\n" 24807 " // Small line comment\n" 24808 " return String.size() > SmallString.size();\n" 24809 "}"; 24810 EXPECT_EQ(Code, format(Code, Style)); 24811 } 24812 24813 TEST_F(FormatTest, FormatDecayCopy) { 24814 // error cases from unit tests 24815 verifyFormat("foo(auto())"); 24816 verifyFormat("foo(auto{})"); 24817 verifyFormat("foo(auto({}))"); 24818 verifyFormat("foo(auto{{}})"); 24819 24820 verifyFormat("foo(auto(1))"); 24821 verifyFormat("foo(auto{1})"); 24822 verifyFormat("foo(new auto(1))"); 24823 verifyFormat("foo(new auto{1})"); 24824 verifyFormat("decltype(auto(1)) x;"); 24825 verifyFormat("decltype(auto{1}) x;"); 24826 verifyFormat("auto(x);"); 24827 verifyFormat("auto{x};"); 24828 verifyFormat("new auto{x};"); 24829 verifyFormat("auto{x} = y;"); 24830 verifyFormat("auto(x) = y;"); // actually a declaration, but this is clearly 24831 // the user's own fault 24832 verifyFormat("integral auto(x) = y;"); // actually a declaration, but this is 24833 // clearly the user's own fault 24834 verifyFormat("auto(*p)() = f;"); // actually a declaration; TODO FIXME 24835 } 24836 24837 TEST_F(FormatTest, Cpp20ModulesSupport) { 24838 FormatStyle Style = getLLVMStyle(); 24839 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 24840 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 24841 24842 verifyFormat("export import foo;", Style); 24843 verifyFormat("export import foo:bar;", Style); 24844 verifyFormat("export import foo.bar;", Style); 24845 verifyFormat("export import foo.bar:baz;", Style); 24846 verifyFormat("export import :bar;", Style); 24847 verifyFormat("export module foo:bar;", Style); 24848 verifyFormat("export module foo;", Style); 24849 verifyFormat("export module foo.bar;", Style); 24850 verifyFormat("export module foo.bar:baz;", Style); 24851 verifyFormat("export import <string_view>;", Style); 24852 24853 verifyFormat("export type_name var;", Style); 24854 verifyFormat("template <class T> export using A = B<T>;", Style); 24855 verifyFormat("export using A = B;", Style); 24856 verifyFormat("export int func() {\n" 24857 " foo();\n" 24858 "}", 24859 Style); 24860 verifyFormat("export struct {\n" 24861 " int foo;\n" 24862 "};", 24863 Style); 24864 verifyFormat("export {\n" 24865 " int foo;\n" 24866 "};", 24867 Style); 24868 verifyFormat("export export char const *hello() { return \"hello\"; }"); 24869 24870 verifyFormat("import bar;", Style); 24871 verifyFormat("import foo.bar;", Style); 24872 verifyFormat("import foo:bar;", Style); 24873 verifyFormat("import :bar;", Style); 24874 verifyFormat("import <ctime>;", Style); 24875 verifyFormat("import \"header\";", Style); 24876 24877 verifyFormat("module foo;", Style); 24878 verifyFormat("module foo:bar;", Style); 24879 verifyFormat("module foo.bar;", Style); 24880 verifyFormat("module;", Style); 24881 24882 verifyFormat("export namespace hi {\n" 24883 "const char *sayhi();\n" 24884 "}", 24885 Style); 24886 24887 verifyFormat("module :private;", Style); 24888 verifyFormat("import <foo/bar.h>;", Style); 24889 verifyFormat("import foo...bar;", Style); 24890 verifyFormat("import ..........;", Style); 24891 verifyFormat("module foo:private;", Style); 24892 verifyFormat("import a", Style); 24893 verifyFormat("module a", Style); 24894 verifyFormat("export import a", Style); 24895 verifyFormat("export module a", Style); 24896 24897 verifyFormat("import", Style); 24898 verifyFormat("module", Style); 24899 verifyFormat("export", Style); 24900 } 24901 24902 TEST_F(FormatTest, CoroutineForCoawait) { 24903 FormatStyle Style = getLLVMStyle(); 24904 verifyFormat("for co_await (auto x : range())\n ;"); 24905 verifyFormat("for (auto i : arr) {\n" 24906 "}", 24907 Style); 24908 verifyFormat("for co_await (auto i : arr) {\n" 24909 "}", 24910 Style); 24911 verifyFormat("for co_await (auto i : foo(T{})) {\n" 24912 "}", 24913 Style); 24914 } 24915 24916 TEST_F(FormatTest, CoroutineCoAwait) { 24917 verifyFormat("int x = co_await foo();"); 24918 verifyFormat("int x = (co_await foo());"); 24919 verifyFormat("co_await (42);"); 24920 verifyFormat("void operator co_await(int);"); 24921 verifyFormat("void operator co_await(a);"); 24922 verifyFormat("co_await a;"); 24923 verifyFormat("co_await missing_await_resume{};"); 24924 verifyFormat("co_await a; // comment"); 24925 verifyFormat("void test0() { co_await a; }"); 24926 verifyFormat("co_await co_await co_await foo();"); 24927 verifyFormat("co_await foo().bar();"); 24928 verifyFormat("co_await [this]() -> Task { co_return x; }"); 24929 verifyFormat("co_await [this](int a, int b) -> Task { co_return co_await " 24930 "foo(); }(x, y);"); 24931 24932 FormatStyle Style = getLLVMStyleWithColumns(40); 24933 verifyFormat("co_await [this](int a, int b) -> Task {\n" 24934 " co_return co_await foo();\n" 24935 "}(x, y);", 24936 Style); 24937 verifyFormat("co_await;"); 24938 } 24939 24940 TEST_F(FormatTest, CoroutineCoYield) { 24941 verifyFormat("int x = co_yield foo();"); 24942 verifyFormat("int x = (co_yield foo());"); 24943 verifyFormat("co_yield (42);"); 24944 verifyFormat("co_yield {42};"); 24945 verifyFormat("co_yield 42;"); 24946 verifyFormat("co_yield n++;"); 24947 verifyFormat("co_yield ++n;"); 24948 verifyFormat("co_yield;"); 24949 } 24950 24951 TEST_F(FormatTest, CoroutineCoReturn) { 24952 verifyFormat("co_return (42);"); 24953 verifyFormat("co_return;"); 24954 verifyFormat("co_return {};"); 24955 verifyFormat("co_return x;"); 24956 verifyFormat("co_return co_await foo();"); 24957 verifyFormat("co_return co_yield foo();"); 24958 } 24959 24960 TEST_F(FormatTest, EmptyShortBlock) { 24961 auto Style = getLLVMStyle(); 24962 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 24963 24964 verifyFormat("try {\n" 24965 " doA();\n" 24966 "} catch (Exception &e) {\n" 24967 " e.printStackTrace();\n" 24968 "}\n", 24969 Style); 24970 24971 verifyFormat("try {\n" 24972 " doA();\n" 24973 "} catch (Exception &e) {}\n", 24974 Style); 24975 } 24976 24977 TEST_F(FormatTest, ShortTemplatedArgumentLists) { 24978 auto Style = getLLVMStyle(); 24979 24980 verifyFormat("template <> struct S : Template<int (*)[]> {};\n", Style); 24981 verifyFormat("template <> struct S : Template<int (*)[10]> {};\n", Style); 24982 verifyFormat("struct Y : X<[] { return 0; }> {};", Style); 24983 verifyFormat("struct Y<[] { return 0; }> {};", Style); 24984 24985 verifyFormat("struct Z : X<decltype([] { return 0; }){}> {};", Style); 24986 verifyFormat("template <int N> struct Foo<char[N]> {};", Style); 24987 } 24988 24989 TEST_F(FormatTest, InsertBraces) { 24990 FormatStyle Style = getLLVMStyle(); 24991 Style.InsertBraces = true; 24992 24993 verifyFormat("// clang-format off\n" 24994 "// comment\n" 24995 "if (a) f();\n" 24996 "// clang-format on\n" 24997 "if (b) {\n" 24998 " g();\n" 24999 "}", 25000 "// clang-format off\n" 25001 "// comment\n" 25002 "if (a) f();\n" 25003 "// clang-format on\n" 25004 "if (b) g();", 25005 Style); 25006 25007 verifyFormat("if (a) {\n" 25008 " switch (b) {\n" 25009 " case 1:\n" 25010 " c = 0;\n" 25011 " break;\n" 25012 " default:\n" 25013 " c = 1;\n" 25014 " }\n" 25015 "}", 25016 "if (a)\n" 25017 " switch (b) {\n" 25018 " case 1:\n" 25019 " c = 0;\n" 25020 " break;\n" 25021 " default:\n" 25022 " c = 1;\n" 25023 " }", 25024 Style); 25025 25026 verifyFormat("for (auto node : nodes) {\n" 25027 " if (node) {\n" 25028 " break;\n" 25029 " }\n" 25030 "}", 25031 "for (auto node : nodes)\n" 25032 " if (node)\n" 25033 " break;", 25034 Style); 25035 25036 verifyFormat("for (auto node : nodes) {\n" 25037 " if (node)\n" 25038 "}", 25039 "for (auto node : nodes)\n" 25040 " if (node)", 25041 Style); 25042 25043 verifyFormat("do {\n" 25044 " --a;\n" 25045 "} while (a);", 25046 "do\n" 25047 " --a;\n" 25048 "while (a);", 25049 Style); 25050 25051 verifyFormat("if (i) {\n" 25052 " ++i;\n" 25053 "} else {\n" 25054 " --i;\n" 25055 "}", 25056 "if (i)\n" 25057 " ++i;\n" 25058 "else {\n" 25059 " --i;\n" 25060 "}", 25061 Style); 25062 25063 verifyFormat("void f() {\n" 25064 " while (j--) {\n" 25065 " while (i) {\n" 25066 " --i;\n" 25067 " }\n" 25068 " }\n" 25069 "}", 25070 "void f() {\n" 25071 " while (j--)\n" 25072 " while (i)\n" 25073 " --i;\n" 25074 "}", 25075 Style); 25076 25077 verifyFormat("f({\n" 25078 " if (a) {\n" 25079 " g();\n" 25080 " }\n" 25081 "});", 25082 "f({\n" 25083 " if (a)\n" 25084 " g();\n" 25085 "});", 25086 Style); 25087 25088 verifyFormat("if (a) {\n" 25089 " f();\n" 25090 "} else if (b) {\n" 25091 " g();\n" 25092 "} else {\n" 25093 " h();\n" 25094 "}", 25095 "if (a)\n" 25096 " f();\n" 25097 "else if (b)\n" 25098 " g();\n" 25099 "else\n" 25100 " h();", 25101 Style); 25102 25103 verifyFormat("if (a) {\n" 25104 " f();\n" 25105 "}\n" 25106 "// comment\n" 25107 "/* comment */", 25108 "if (a)\n" 25109 " f();\n" 25110 "// comment\n" 25111 "/* comment */", 25112 Style); 25113 25114 verifyFormat("if (a) {\n" 25115 " // foo\n" 25116 " // bar\n" 25117 " f();\n" 25118 "}", 25119 "if (a)\n" 25120 " // foo\n" 25121 " // bar\n" 25122 " f();", 25123 Style); 25124 25125 verifyFormat("if (a) { // comment\n" 25126 " // comment\n" 25127 " f();\n" 25128 "}", 25129 "if (a) // comment\n" 25130 " // comment\n" 25131 " f();", 25132 Style); 25133 25134 verifyFormat("if (a) {\n" 25135 " f(); // comment\n" 25136 "}", 25137 "if (a)\n" 25138 " f(); // comment", 25139 Style); 25140 25141 verifyFormat("if (a) {\n" 25142 " f();\n" 25143 "}\n" 25144 "#undef A\n" 25145 "#undef B", 25146 "if (a)\n" 25147 " f();\n" 25148 "#undef A\n" 25149 "#undef B", 25150 Style); 25151 25152 verifyFormat("if (a)\n" 25153 "#ifdef A\n" 25154 " f();\n" 25155 "#else\n" 25156 " g();\n" 25157 "#endif", 25158 Style); 25159 25160 verifyFormat("#if 0\n" 25161 "#elif 1\n" 25162 "#endif\n" 25163 "void f() {\n" 25164 " if (a) {\n" 25165 " g();\n" 25166 " }\n" 25167 "}", 25168 "#if 0\n" 25169 "#elif 1\n" 25170 "#endif\n" 25171 "void f() {\n" 25172 " if (a) g();\n" 25173 "}", 25174 Style); 25175 25176 Style.ColumnLimit = 15; 25177 25178 verifyFormat("#define A \\\n" 25179 " if (a) \\\n" 25180 " f();", 25181 Style); 25182 25183 verifyFormat("if (a + b >\n" 25184 " c) {\n" 25185 " f();\n" 25186 "}", 25187 "if (a + b > c)\n" 25188 " f();", 25189 Style); 25190 } 25191 25192 TEST_F(FormatTest, RemoveBraces) { 25193 FormatStyle Style = getLLVMStyle(); 25194 Style.RemoveBracesLLVM = true; 25195 25196 // The following test cases are fully-braced versions of the examples at 25197 // "llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single- 25198 // statement-bodies-of-if-else-loop-statements". 25199 25200 // Omit the braces since the body is simple and clearly associated with the 25201 // `if`. 25202 verifyFormat("if (isa<FunctionDecl>(D))\n" 25203 " handleFunctionDecl(D);\n" 25204 "else if (isa<VarDecl>(D))\n" 25205 " handleVarDecl(D);", 25206 "if (isa<FunctionDecl>(D)) {\n" 25207 " handleFunctionDecl(D);\n" 25208 "} else if (isa<VarDecl>(D)) {\n" 25209 " handleVarDecl(D);\n" 25210 "}", 25211 Style); 25212 25213 // Here we document the condition itself and not the body. 25214 verifyFormat("if (isa<VarDecl>(D)) {\n" 25215 " // It is necessary that we explain the situation with this\n" 25216 " // surprisingly long comment, so it would be unclear\n" 25217 " // without the braces whether the following statement is in\n" 25218 " // the scope of the `if`.\n" 25219 " // Because the condition is documented, we can't really\n" 25220 " // hoist this comment that applies to the body above the\n" 25221 " // `if`.\n" 25222 " handleOtherDecl(D);\n" 25223 "}", 25224 Style); 25225 25226 // Use braces on the outer `if` to avoid a potential dangling `else` 25227 // situation. 25228 verifyFormat("if (isa<VarDecl>(D)) {\n" 25229 " if (shouldProcessAttr(A))\n" 25230 " handleAttr(A);\n" 25231 "}", 25232 "if (isa<VarDecl>(D)) {\n" 25233 " if (shouldProcessAttr(A)) {\n" 25234 " handleAttr(A);\n" 25235 " }\n" 25236 "}", 25237 Style); 25238 25239 // Use braces for the `if` block to keep it uniform with the `else` block. 25240 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 25241 " handleFunctionDecl(D);\n" 25242 "} else {\n" 25243 " // In this `else` case, it is necessary that we explain the\n" 25244 " // situation with this surprisingly long comment, so it\n" 25245 " // would be unclear without the braces whether the\n" 25246 " // following statement is in the scope of the `if`.\n" 25247 " handleOtherDecl(D);\n" 25248 "}", 25249 Style); 25250 25251 // This should also omit braces. The `for` loop contains only a single 25252 // statement, so it shouldn't have braces. The `if` also only contains a 25253 // single simple statement (the `for` loop), so it also should omit braces. 25254 verifyFormat("if (isa<FunctionDecl>(D))\n" 25255 " for (auto *A : D.attrs())\n" 25256 " handleAttr(A);", 25257 "if (isa<FunctionDecl>(D)) {\n" 25258 " for (auto *A : D.attrs()) {\n" 25259 " handleAttr(A);\n" 25260 " }\n" 25261 "}", 25262 Style); 25263 25264 // Use braces for a `do-while` loop and its enclosing statement. 25265 verifyFormat("if (Tok->is(tok::l_brace)) {\n" 25266 " do {\n" 25267 " Tok = Tok->Next;\n" 25268 " } while (Tok);\n" 25269 "}", 25270 Style); 25271 25272 // Use braces for the outer `if` since the nested `for` is braced. 25273 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 25274 " for (auto *A : D.attrs()) {\n" 25275 " // In this `for` loop body, it is necessary that we\n" 25276 " // explain the situation with this surprisingly long\n" 25277 " // comment, forcing braces on the `for` block.\n" 25278 " handleAttr(A);\n" 25279 " }\n" 25280 "}", 25281 Style); 25282 25283 // Use braces on the outer block because there are more than two levels of 25284 // nesting. 25285 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 25286 " for (auto *A : D.attrs())\n" 25287 " for (ssize_t i : llvm::seq<ssize_t>(count))\n" 25288 " handleAttrOnDecl(D, A, i);\n" 25289 "}", 25290 "if (isa<FunctionDecl>(D)) {\n" 25291 " for (auto *A : D.attrs()) {\n" 25292 " for (ssize_t i : llvm::seq<ssize_t>(count)) {\n" 25293 " handleAttrOnDecl(D, A, i);\n" 25294 " }\n" 25295 " }\n" 25296 "}", 25297 Style); 25298 25299 // Use braces on the outer block because of a nested `if`; otherwise the 25300 // compiler would warn: `add explicit braces to avoid dangling else` 25301 verifyFormat("if (auto *D = dyn_cast<FunctionDecl>(D)) {\n" 25302 " if (shouldProcess(D))\n" 25303 " handleVarDecl(D);\n" 25304 " else\n" 25305 " markAsIgnored(D);\n" 25306 "}", 25307 "if (auto *D = dyn_cast<FunctionDecl>(D)) {\n" 25308 " if (shouldProcess(D)) {\n" 25309 " handleVarDecl(D);\n" 25310 " } else {\n" 25311 " markAsIgnored(D);\n" 25312 " }\n" 25313 "}", 25314 Style); 25315 25316 verifyFormat("// clang-format off\n" 25317 "// comment\n" 25318 "while (i > 0) { --i; }\n" 25319 "// clang-format on\n" 25320 "while (j < 0)\n" 25321 " ++j;", 25322 "// clang-format off\n" 25323 "// comment\n" 25324 "while (i > 0) { --i; }\n" 25325 "// clang-format on\n" 25326 "while (j < 0) { ++j; }", 25327 Style); 25328 25329 verifyFormat("if (a)\n" 25330 " b; // comment\n" 25331 "else if (c)\n" 25332 " d; /* comment */\n" 25333 "else\n" 25334 " e;", 25335 "if (a) {\n" 25336 " b; // comment\n" 25337 "} else if (c) {\n" 25338 " d; /* comment */\n" 25339 "} else {\n" 25340 " e;\n" 25341 "}", 25342 Style); 25343 25344 verifyFormat("if (a) {\n" 25345 " b;\n" 25346 " c;\n" 25347 "} else if (d) {\n" 25348 " e;\n" 25349 "}", 25350 Style); 25351 25352 verifyFormat("if (a) {\n" 25353 "#undef NDEBUG\n" 25354 " b;\n" 25355 "} else {\n" 25356 " c;\n" 25357 "}", 25358 Style); 25359 25360 verifyFormat("if (a) {\n" 25361 " // comment\n" 25362 "} else if (b) {\n" 25363 " c;\n" 25364 "}", 25365 Style); 25366 25367 verifyFormat("if (a) {\n" 25368 " b;\n" 25369 "} else {\n" 25370 " { c; }\n" 25371 "}", 25372 Style); 25373 25374 verifyFormat("if (a) {\n" 25375 " if (b) // comment\n" 25376 " c;\n" 25377 "} else if (d) {\n" 25378 " e;\n" 25379 "}", 25380 "if (a) {\n" 25381 " if (b) { // comment\n" 25382 " c;\n" 25383 " }\n" 25384 "} else if (d) {\n" 25385 " e;\n" 25386 "}", 25387 Style); 25388 25389 verifyFormat("if (a) {\n" 25390 " if (b) {\n" 25391 " c;\n" 25392 " // comment\n" 25393 " } else if (d) {\n" 25394 " e;\n" 25395 " }\n" 25396 "}", 25397 Style); 25398 25399 verifyFormat("if (a) {\n" 25400 " if (b)\n" 25401 " c;\n" 25402 "}", 25403 "if (a) {\n" 25404 " if (b) {\n" 25405 " c;\n" 25406 " }\n" 25407 "}", 25408 Style); 25409 25410 verifyFormat("if (a)\n" 25411 " if (b)\n" 25412 " c;\n" 25413 " else\n" 25414 " d;\n" 25415 "else\n" 25416 " e;", 25417 "if (a) {\n" 25418 " if (b) {\n" 25419 " c;\n" 25420 " } else {\n" 25421 " d;\n" 25422 " }\n" 25423 "} else {\n" 25424 " e;\n" 25425 "}", 25426 Style); 25427 25428 verifyFormat("if (a) {\n" 25429 " // comment\n" 25430 " if (b)\n" 25431 " c;\n" 25432 " else if (d)\n" 25433 " e;\n" 25434 "} else {\n" 25435 " g;\n" 25436 "}", 25437 "if (a) {\n" 25438 " // comment\n" 25439 " if (b) {\n" 25440 " c;\n" 25441 " } else if (d) {\n" 25442 " e;\n" 25443 " }\n" 25444 "} else {\n" 25445 " g;\n" 25446 "}", 25447 Style); 25448 25449 verifyFormat("if (a)\n" 25450 " b;\n" 25451 "else if (c)\n" 25452 " d;\n" 25453 "else\n" 25454 " e;", 25455 "if (a) {\n" 25456 " b;\n" 25457 "} else {\n" 25458 " if (c) {\n" 25459 " d;\n" 25460 " } else {\n" 25461 " e;\n" 25462 " }\n" 25463 "}", 25464 Style); 25465 25466 verifyFormat("if (a) {\n" 25467 " if (b)\n" 25468 " c;\n" 25469 " else if (d)\n" 25470 " e;\n" 25471 "} else {\n" 25472 " g;\n" 25473 "}", 25474 "if (a) {\n" 25475 " if (b)\n" 25476 " c;\n" 25477 " else {\n" 25478 " if (d)\n" 25479 " e;\n" 25480 " }\n" 25481 "} else {\n" 25482 " g;\n" 25483 "}", 25484 Style); 25485 25486 verifyFormat("if (isa<VarDecl>(D)) {\n" 25487 " for (auto *A : D.attrs())\n" 25488 " if (shouldProcessAttr(A))\n" 25489 " handleAttr(A);\n" 25490 "}", 25491 "if (isa<VarDecl>(D)) {\n" 25492 " for (auto *A : D.attrs()) {\n" 25493 " if (shouldProcessAttr(A)) {\n" 25494 " handleAttr(A);\n" 25495 " }\n" 25496 " }\n" 25497 "}", 25498 Style); 25499 25500 verifyFormat("do {\n" 25501 " ++I;\n" 25502 "} while (hasMore() && Filter(*I));", 25503 "do { ++I; } while (hasMore() && Filter(*I));", Style); 25504 25505 verifyFormat("if (a)\n" 25506 " if (b)\n" 25507 " c;\n" 25508 " else {\n" 25509 " if (d)\n" 25510 " e;\n" 25511 " }\n" 25512 "else\n" 25513 " f;", 25514 Style); 25515 25516 verifyFormat("if (a)\n" 25517 " if (b)\n" 25518 " c;\n" 25519 " else {\n" 25520 " if (d)\n" 25521 " e;\n" 25522 " else if (f)\n" 25523 " g;\n" 25524 " }\n" 25525 "else\n" 25526 " h;", 25527 Style); 25528 25529 verifyFormat("if (a) {\n" 25530 " b;\n" 25531 "} else if (c) {\n" 25532 " d;\n" 25533 " e;\n" 25534 "}", 25535 "if (a) {\n" 25536 " b;\n" 25537 "} else {\n" 25538 " if (c) {\n" 25539 " d;\n" 25540 " e;\n" 25541 " }\n" 25542 "}", 25543 Style); 25544 25545 verifyFormat("if (a) {\n" 25546 " b;\n" 25547 " c;\n" 25548 "} else if (d) {\n" 25549 " e;\n" 25550 " f;\n" 25551 "}", 25552 "if (a) {\n" 25553 " b;\n" 25554 " c;\n" 25555 "} else {\n" 25556 " if (d) {\n" 25557 " e;\n" 25558 " f;\n" 25559 " }\n" 25560 "}", 25561 Style); 25562 25563 verifyFormat("if (a) {\n" 25564 " b;\n" 25565 "} else if (c) {\n" 25566 " d;\n" 25567 "} else {\n" 25568 " e;\n" 25569 " f;\n" 25570 "}", 25571 "if (a) {\n" 25572 " b;\n" 25573 "} else {\n" 25574 " if (c) {\n" 25575 " d;\n" 25576 " } else {\n" 25577 " e;\n" 25578 " f;\n" 25579 " }\n" 25580 "}", 25581 Style); 25582 25583 verifyFormat("if (a) {\n" 25584 " b;\n" 25585 "} else if (c) {\n" 25586 " d;\n" 25587 "} else if (e) {\n" 25588 " f;\n" 25589 " g;\n" 25590 "}", 25591 "if (a) {\n" 25592 " b;\n" 25593 "} else {\n" 25594 " if (c) {\n" 25595 " d;\n" 25596 " } else if (e) {\n" 25597 " f;\n" 25598 " g;\n" 25599 " }\n" 25600 "}", 25601 Style); 25602 25603 verifyFormat("if (a) {\n" 25604 " if (b)\n" 25605 " c;\n" 25606 " else if (d) {\n" 25607 " e;\n" 25608 " f;\n" 25609 " }\n" 25610 "} else {\n" 25611 " g;\n" 25612 "}", 25613 "if (a) {\n" 25614 " if (b)\n" 25615 " c;\n" 25616 " else {\n" 25617 " if (d) {\n" 25618 " e;\n" 25619 " f;\n" 25620 " }\n" 25621 " }\n" 25622 "} else {\n" 25623 " g;\n" 25624 "}", 25625 Style); 25626 25627 verifyFormat("if (a)\n" 25628 " if (b)\n" 25629 " c;\n" 25630 " else {\n" 25631 " if (d) {\n" 25632 " e;\n" 25633 " f;\n" 25634 " }\n" 25635 " }\n" 25636 "else\n" 25637 " g;", 25638 Style); 25639 25640 verifyFormat("if (a) {\n" 25641 " b;\n" 25642 " c;\n" 25643 "} else { // comment\n" 25644 " if (d) {\n" 25645 " e;\n" 25646 " f;\n" 25647 " }\n" 25648 "}", 25649 Style); 25650 25651 verifyFormat("if (a)\n" 25652 " b;\n" 25653 "else if (c)\n" 25654 " while (d)\n" 25655 " e;\n" 25656 "// comment", 25657 "if (a)\n" 25658 "{\n" 25659 " b;\n" 25660 "} else if (c) {\n" 25661 " while (d) {\n" 25662 " e;\n" 25663 " }\n" 25664 "}\n" 25665 "// comment", 25666 Style); 25667 25668 verifyFormat("if (a) {\n" 25669 " b;\n" 25670 "} else if (c) {\n" 25671 " d;\n" 25672 "} else {\n" 25673 " e;\n" 25674 " g;\n" 25675 "}", 25676 Style); 25677 25678 verifyFormat("if (a) {\n" 25679 " b;\n" 25680 "} else if (c) {\n" 25681 " d;\n" 25682 "} else {\n" 25683 " e;\n" 25684 "} // comment", 25685 Style); 25686 25687 verifyFormat("int abs = [](int i) {\n" 25688 " if (i >= 0)\n" 25689 " return i;\n" 25690 " return -i;\n" 25691 "};", 25692 "int abs = [](int i) {\n" 25693 " if (i >= 0) {\n" 25694 " return i;\n" 25695 " }\n" 25696 " return -i;\n" 25697 "};", 25698 Style); 25699 25700 verifyFormat("if (a)\n" 25701 " foo();\n" 25702 "else\n" 25703 " bar();", 25704 "if (a)\n" 25705 "{\n" 25706 " foo();\n" 25707 "}\n" 25708 "else\n" 25709 "{\n" 25710 " bar();\n" 25711 "}", 25712 Style); 25713 25714 verifyFormat("if (a)\n" 25715 " foo();\n" 25716 "// comment\n" 25717 "else\n" 25718 " bar();", 25719 "if (a) {\n" 25720 " foo();\n" 25721 "}\n" 25722 "// comment\n" 25723 "else {\n" 25724 " bar();\n" 25725 "}", 25726 Style); 25727 25728 verifyFormat("if (a) {\n" 25729 "Label:\n" 25730 "}", 25731 Style); 25732 25733 verifyFormat("if (a) {\n" 25734 "Label:\n" 25735 " f();\n" 25736 "}", 25737 Style); 25738 25739 verifyFormat("if (a) {\n" 25740 " f();\n" 25741 "Label:\n" 25742 "}", 25743 Style); 25744 25745 verifyFormat("if consteval {\n" 25746 " f();\n" 25747 "} else {\n" 25748 " g();\n" 25749 "}", 25750 Style); 25751 25752 verifyFormat("if not consteval {\n" 25753 " f();\n" 25754 "} else if (a) {\n" 25755 " g();\n" 25756 "}", 25757 Style); 25758 25759 verifyFormat("if !consteval {\n" 25760 " g();\n" 25761 "}", 25762 Style); 25763 25764 Style.ColumnLimit = 65; 25765 verifyFormat("if (condition) {\n" 25766 " ff(Indices,\n" 25767 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 25768 "} else {\n" 25769 " ff(Indices,\n" 25770 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 25771 "}", 25772 Style); 25773 25774 Style.ColumnLimit = 20; 25775 25776 verifyFormat("int ab = [](int i) {\n" 25777 " if (i > 0) {\n" 25778 " i = 12345678 -\n" 25779 " i;\n" 25780 " }\n" 25781 " return i;\n" 25782 "};", 25783 Style); 25784 25785 verifyFormat("if (a) {\n" 25786 " b = c + // 1 -\n" 25787 " d;\n" 25788 "}", 25789 Style); 25790 25791 verifyFormat("if (a) {\n" 25792 " b = c >= 0 ? d\n" 25793 " : e;\n" 25794 "}", 25795 "if (a) {\n" 25796 " b = c >= 0 ? d : e;\n" 25797 "}", 25798 Style); 25799 25800 verifyFormat("if (a)\n" 25801 " b = c > 0 ? d : e;", 25802 "if (a) {\n" 25803 " b = c > 0 ? d : e;\n" 25804 "}", 25805 Style); 25806 25807 verifyFormat("if (-b >=\n" 25808 " c) { // Keep.\n" 25809 " foo();\n" 25810 "} else {\n" 25811 " bar();\n" 25812 "}", 25813 "if (-b >= c) { // Keep.\n" 25814 " foo();\n" 25815 "} else {\n" 25816 " bar();\n" 25817 "}", 25818 Style); 25819 25820 verifyFormat("if (a) /* Remove. */\n" 25821 " f();\n" 25822 "else\n" 25823 " g();", 25824 "if (a) <% /* Remove. */\n" 25825 " f();\n" 25826 "%> else <%\n" 25827 " g();\n" 25828 "%>", 25829 Style); 25830 25831 verifyFormat("while (\n" 25832 " !i--) <% // Keep.\n" 25833 " foo();\n" 25834 "%>", 25835 "while (!i--) <% // Keep.\n" 25836 " foo();\n" 25837 "%>", 25838 Style); 25839 25840 verifyFormat("for (int &i : chars)\n" 25841 " ++i;", 25842 "for (int &i :\n" 25843 " chars) {\n" 25844 " ++i;\n" 25845 "}", 25846 Style); 25847 25848 verifyFormat("if (a)\n" 25849 " b;\n" 25850 "else if (c) {\n" 25851 " d;\n" 25852 " e;\n" 25853 "} else\n" 25854 " f = g(foo, bar,\n" 25855 " baz);", 25856 "if (a)\n" 25857 " b;\n" 25858 "else {\n" 25859 " if (c) {\n" 25860 " d;\n" 25861 " e;\n" 25862 " } else\n" 25863 " f = g(foo, bar, baz);\n" 25864 "}", 25865 Style); 25866 25867 Style.ColumnLimit = 0; 25868 verifyFormat("if (a)\n" 25869 " b234567890223456789032345678904234567890 = " 25870 "c234567890223456789032345678904234567890;", 25871 "if (a) {\n" 25872 " b234567890223456789032345678904234567890 = " 25873 "c234567890223456789032345678904234567890;\n" 25874 "}", 25875 Style); 25876 25877 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 25878 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 25879 Style.BraceWrapping.BeforeElse = true; 25880 25881 Style.ColumnLimit = 65; 25882 25883 verifyFormat("if (condition)\n" 25884 "{\n" 25885 " ff(Indices,\n" 25886 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 25887 "}\n" 25888 "else\n" 25889 "{\n" 25890 " ff(Indices,\n" 25891 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 25892 "}", 25893 "if (condition) {\n" 25894 " ff(Indices,\n" 25895 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 25896 "} else {\n" 25897 " ff(Indices,\n" 25898 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 25899 "}", 25900 Style); 25901 25902 verifyFormat("if (a)\n" 25903 "{ //\n" 25904 " foo();\n" 25905 "}", 25906 "if (a) { //\n" 25907 " foo();\n" 25908 "}", 25909 Style); 25910 25911 Style.ColumnLimit = 20; 25912 25913 verifyFormat("int ab = [](int i) {\n" 25914 " if (i > 0)\n" 25915 " {\n" 25916 " i = 12345678 -\n" 25917 " i;\n" 25918 " }\n" 25919 " return i;\n" 25920 "};", 25921 "int ab = [](int i) {\n" 25922 " if (i > 0) {\n" 25923 " i = 12345678 -\n" 25924 " i;\n" 25925 " }\n" 25926 " return i;\n" 25927 "};", 25928 Style); 25929 25930 verifyFormat("if (a)\n" 25931 "{\n" 25932 " b = c + // 1 -\n" 25933 " d;\n" 25934 "}", 25935 "if (a) {\n" 25936 " b = c + // 1 -\n" 25937 " d;\n" 25938 "}", 25939 Style); 25940 25941 verifyFormat("if (a)\n" 25942 "{\n" 25943 " b = c >= 0 ? d\n" 25944 " : e;\n" 25945 "}", 25946 "if (a) {\n" 25947 " b = c >= 0 ? d : e;\n" 25948 "}", 25949 Style); 25950 25951 verifyFormat("if (a)\n" 25952 " b = c > 0 ? d : e;", 25953 "if (a)\n" 25954 "{\n" 25955 " b = c > 0 ? d : e;\n" 25956 "}", 25957 Style); 25958 25959 verifyFormat("if (foo + bar <=\n" 25960 " baz)\n" 25961 "{\n" 25962 " func(arg1, arg2);\n" 25963 "}", 25964 "if (foo + bar <= baz) {\n" 25965 " func(arg1, arg2);\n" 25966 "}", 25967 Style); 25968 25969 verifyFormat("if (foo + bar < baz)\n" 25970 " func(arg1, arg2);\n" 25971 "else\n" 25972 " func();", 25973 "if (foo + bar < baz)\n" 25974 "<%\n" 25975 " func(arg1, arg2);\n" 25976 "%>\n" 25977 "else\n" 25978 "<%\n" 25979 " func();\n" 25980 "%>", 25981 Style); 25982 25983 verifyFormat("while (i--)\n" 25984 "<% // Keep.\n" 25985 " foo();\n" 25986 "%>", 25987 "while (i--) <% // Keep.\n" 25988 " foo();\n" 25989 "%>", 25990 Style); 25991 25992 verifyFormat("for (int &i : chars)\n" 25993 " ++i;", 25994 "for (int &i : chars)\n" 25995 "{\n" 25996 " ++i;\n" 25997 "}", 25998 Style); 25999 } 26000 26001 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndent) { 26002 auto Style = getLLVMStyle(); 26003 26004 StringRef Short = "functionCall(paramA, paramB, paramC);\n" 26005 "void functionDecl(int a, int b, int c);"; 26006 26007 StringRef Medium = "functionCall(paramA, paramB, paramC, paramD, paramE, " 26008 "paramF, paramG, paramH, paramI);\n" 26009 "void functionDecl(int argumentA, int argumentB, int " 26010 "argumentC, int argumentD, int argumentE);"; 26011 26012 verifyFormat(Short, Style); 26013 26014 StringRef NoBreak = "functionCall(paramA, paramB, paramC, paramD, paramE, " 26015 "paramF, paramG, paramH,\n" 26016 " paramI);\n" 26017 "void functionDecl(int argumentA, int argumentB, int " 26018 "argumentC, int argumentD,\n" 26019 " int argumentE);"; 26020 26021 verifyFormat(NoBreak, Medium, Style); 26022 verifyFormat(NoBreak, 26023 "functionCall(\n" 26024 " paramA,\n" 26025 " paramB,\n" 26026 " paramC,\n" 26027 " paramD,\n" 26028 " paramE,\n" 26029 " paramF,\n" 26030 " paramG,\n" 26031 " paramH,\n" 26032 " paramI\n" 26033 ");\n" 26034 "void functionDecl(\n" 26035 " int argumentA,\n" 26036 " int argumentB,\n" 26037 " int argumentC,\n" 26038 " int argumentD,\n" 26039 " int argumentE\n" 26040 ");", 26041 Style); 26042 26043 verifyFormat("outerFunctionCall(nestedFunctionCall(argument1),\n" 26044 " nestedLongFunctionCall(argument1, " 26045 "argument2, argument3,\n" 26046 " argument4, " 26047 "argument5));", 26048 Style); 26049 26050 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 26051 26052 verifyFormat(Short, Style); 26053 verifyFormat( 26054 "functionCall(\n" 26055 " paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, " 26056 "paramI\n" 26057 ");\n" 26058 "void functionDecl(\n" 26059 " int argumentA, int argumentB, int argumentC, int argumentD, int " 26060 "argumentE\n" 26061 ");", 26062 Medium, Style); 26063 26064 Style.AllowAllArgumentsOnNextLine = false; 26065 Style.AllowAllParametersOfDeclarationOnNextLine = false; 26066 26067 verifyFormat(Short, Style); 26068 verifyFormat( 26069 "functionCall(\n" 26070 " paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, " 26071 "paramI\n" 26072 ");\n" 26073 "void functionDecl(\n" 26074 " int argumentA, int argumentB, int argumentC, int argumentD, int " 26075 "argumentE\n" 26076 ");", 26077 Medium, Style); 26078 26079 Style.BinPackArguments = false; 26080 Style.BinPackParameters = false; 26081 26082 verifyFormat(Short, Style); 26083 26084 verifyFormat("functionCall(\n" 26085 " paramA,\n" 26086 " paramB,\n" 26087 " paramC,\n" 26088 " paramD,\n" 26089 " paramE,\n" 26090 " paramF,\n" 26091 " paramG,\n" 26092 " paramH,\n" 26093 " paramI\n" 26094 ");\n" 26095 "void functionDecl(\n" 26096 " int argumentA,\n" 26097 " int argumentB,\n" 26098 " int argumentC,\n" 26099 " int argumentD,\n" 26100 " int argumentE\n" 26101 ");", 26102 Medium, Style); 26103 26104 verifyFormat("outerFunctionCall(\n" 26105 " nestedFunctionCall(argument1),\n" 26106 " nestedLongFunctionCall(\n" 26107 " argument1,\n" 26108 " argument2,\n" 26109 " argument3,\n" 26110 " argument4,\n" 26111 " argument5\n" 26112 " )\n" 26113 ");", 26114 Style); 26115 26116 verifyFormat("int a = (int)b;", Style); 26117 verifyFormat("int a = (int)b;", 26118 "int a = (\n" 26119 " int\n" 26120 ") b;", 26121 Style); 26122 26123 verifyFormat("return (true);", Style); 26124 verifyFormat("return (true);", 26125 "return (\n" 26126 " true\n" 26127 ");", 26128 Style); 26129 26130 verifyFormat("void foo();", Style); 26131 verifyFormat("void foo();", 26132 "void foo(\n" 26133 ");", 26134 Style); 26135 26136 verifyFormat("void foo() {}", Style); 26137 verifyFormat("void foo() {}", 26138 "void foo(\n" 26139 ") {\n" 26140 "}", 26141 Style); 26142 26143 verifyFormat("auto string = std::string();", Style); 26144 verifyFormat("auto string = std::string();", 26145 "auto string = std::string(\n" 26146 ");", 26147 Style); 26148 26149 verifyFormat("void (*functionPointer)() = nullptr;", Style); 26150 verifyFormat("void (*functionPointer)() = nullptr;", 26151 "void (\n" 26152 " *functionPointer\n" 26153 ")\n" 26154 "(\n" 26155 ") = nullptr;", 26156 Style); 26157 } 26158 26159 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentIfStatement) { 26160 auto Style = getLLVMStyle(); 26161 26162 verifyFormat("if (foo()) {\n" 26163 " return;\n" 26164 "}", 26165 Style); 26166 26167 verifyFormat("if (quitelongarg !=\n" 26168 " (alsolongarg - 1)) { // ABC is a very longgggggggggggg " 26169 "comment\n" 26170 " return;\n" 26171 "}", 26172 Style); 26173 26174 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 26175 26176 verifyFormat("if (foo()) {\n" 26177 " return;\n" 26178 "}", 26179 Style); 26180 26181 verifyFormat("if (quitelongarg !=\n" 26182 " (alsolongarg - 1)) { // ABC is a very longgggggggggggg " 26183 "comment\n" 26184 " return;\n" 26185 "}", 26186 Style); 26187 } 26188 26189 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentForStatement) { 26190 auto Style = getLLVMStyle(); 26191 26192 verifyFormat("for (int i = 0; i < 5; ++i) {\n" 26193 " doSomething();\n" 26194 "}", 26195 Style); 26196 26197 verifyFormat("for (int myReallyLongCountVariable = 0; " 26198 "myReallyLongCountVariable < count;\n" 26199 " myReallyLongCountVariable++) {\n" 26200 " doSomething();\n" 26201 "}", 26202 Style); 26203 26204 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 26205 26206 verifyFormat("for (int i = 0; i < 5; ++i) {\n" 26207 " doSomething();\n" 26208 "}", 26209 Style); 26210 26211 verifyFormat("for (int myReallyLongCountVariable = 0; " 26212 "myReallyLongCountVariable < count;\n" 26213 " myReallyLongCountVariable++) {\n" 26214 " doSomething();\n" 26215 "}", 26216 Style); 26217 } 26218 26219 TEST_F(FormatTest, UnderstandsDigraphs) { 26220 verifyFormat("int arr<:5:> = {};"); 26221 verifyFormat("int arr[5] = <%%>;"); 26222 verifyFormat("int arr<:::qualified_variable:> = {};"); 26223 verifyFormat("int arr[::qualified_variable] = <%%>;"); 26224 verifyFormat("%:include <header>"); 26225 verifyFormat("%:define A x##y"); 26226 verifyFormat("#define A x%:%:y"); 26227 } 26228 26229 TEST_F(FormatTest, AlignArrayOfStructuresLeftAlignmentNonSquare) { 26230 auto Style = getLLVMStyle(); 26231 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 26232 Style.AlignConsecutiveAssignments.Enabled = true; 26233 Style.AlignConsecutiveDeclarations.Enabled = true; 26234 26235 // The AlignArray code is incorrect for non square Arrays and can cause 26236 // crashes, these tests assert that the array is not changed but will 26237 // also act as regression tests for when it is properly fixed 26238 verifyFormat("struct test demo[] = {\n" 26239 " {1, 2},\n" 26240 " {3, 4, 5},\n" 26241 " {6, 7, 8}\n" 26242 "};", 26243 Style); 26244 verifyFormat("struct test demo[] = {\n" 26245 " {1, 2, 3, 4, 5},\n" 26246 " {3, 4, 5},\n" 26247 " {6, 7, 8}\n" 26248 "};", 26249 Style); 26250 verifyFormat("struct test demo[] = {\n" 26251 " {1, 2, 3, 4, 5},\n" 26252 " {3, 4, 5},\n" 26253 " {6, 7, 8, 9, 10, 11, 12}\n" 26254 "};", 26255 Style); 26256 verifyFormat("struct test demo[] = {\n" 26257 " {1, 2, 3},\n" 26258 " {3, 4, 5},\n" 26259 " {6, 7, 8, 9, 10, 11, 12}\n" 26260 "};", 26261 Style); 26262 26263 verifyFormat("S{\n" 26264 " {},\n" 26265 " {},\n" 26266 " {a, b}\n" 26267 "};", 26268 Style); 26269 verifyFormat("S{\n" 26270 " {},\n" 26271 " {},\n" 26272 " {a, b},\n" 26273 "};", 26274 Style); 26275 verifyFormat("void foo() {\n" 26276 " auto thing = test{\n" 26277 " {\n" 26278 " {13}, {something}, // A\n" 26279 " }\n" 26280 " };\n" 26281 "}", 26282 "void foo() {\n" 26283 " auto thing = test{\n" 26284 " {\n" 26285 " {13},\n" 26286 " {something}, // A\n" 26287 " }\n" 26288 " };\n" 26289 "}", 26290 Style); 26291 } 26292 26293 TEST_F(FormatTest, AlignArrayOfStructuresRightAlignmentNonSquare) { 26294 auto Style = getLLVMStyle(); 26295 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 26296 Style.AlignConsecutiveAssignments.Enabled = true; 26297 Style.AlignConsecutiveDeclarations.Enabled = true; 26298 26299 // The AlignArray code is incorrect for non square Arrays and can cause 26300 // crashes, these tests assert that the array is not changed but will 26301 // also act as regression tests for when it is properly fixed 26302 verifyFormat("struct test demo[] = {\n" 26303 " {1, 2},\n" 26304 " {3, 4, 5},\n" 26305 " {6, 7, 8}\n" 26306 "};", 26307 Style); 26308 verifyFormat("struct test demo[] = {\n" 26309 " {1, 2, 3, 4, 5},\n" 26310 " {3, 4, 5},\n" 26311 " {6, 7, 8}\n" 26312 "};", 26313 Style); 26314 verifyFormat("struct test demo[] = {\n" 26315 " {1, 2, 3, 4, 5},\n" 26316 " {3, 4, 5},\n" 26317 " {6, 7, 8, 9, 10, 11, 12}\n" 26318 "};", 26319 Style); 26320 verifyFormat("struct test demo[] = {\n" 26321 " {1, 2, 3},\n" 26322 " {3, 4, 5},\n" 26323 " {6, 7, 8, 9, 10, 11, 12}\n" 26324 "};", 26325 Style); 26326 26327 verifyFormat("S{\n" 26328 " {},\n" 26329 " {},\n" 26330 " {a, b}\n" 26331 "};", 26332 Style); 26333 verifyFormat("S{\n" 26334 " {},\n" 26335 " {},\n" 26336 " {a, b},\n" 26337 "};", 26338 Style); 26339 verifyFormat("void foo() {\n" 26340 " auto thing = test{\n" 26341 " {\n" 26342 " {13}, {something}, // A\n" 26343 " }\n" 26344 " };\n" 26345 "}", 26346 "void foo() {\n" 26347 " auto thing = test{\n" 26348 " {\n" 26349 " {13},\n" 26350 " {something}, // A\n" 26351 " }\n" 26352 " };\n" 26353 "}", 26354 Style); 26355 } 26356 26357 TEST_F(FormatTest, FormatsVariableTemplates) { 26358 verifyFormat("inline bool var = is_integral_v<int> && is_signed_v<int>;"); 26359 verifyFormat("template <typename T> " 26360 "inline bool var = is_integral_v<T> && is_signed_v<T>;"); 26361 } 26362 26363 } // namespace 26364 } // namespace format 26365 } // namespace clang 26366