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.IfMacros.push_back("MYIF"); 1577 // Where line-lengths matter, a 2-letter synonym that maintains line length. 1578 // Not IF to avoid any confusion that IF is somehow special. 1579 AllowSimpleBracedStatements.IfMacros.push_back("FI"); 1580 AllowSimpleBracedStatements.ColumnLimit = 40; 1581 AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine = 1582 FormatStyle::SBS_Always; 1583 1584 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1585 FormatStyle::SIS_WithoutElse; 1586 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true; 1587 1588 AllowSimpleBracedStatements.BreakBeforeBraces = FormatStyle::BS_Custom; 1589 AllowSimpleBracedStatements.BraceWrapping.AfterFunction = true; 1590 AllowSimpleBracedStatements.BraceWrapping.SplitEmptyRecord = false; 1591 1592 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1593 verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements); 1594 verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1595 verifyFormat("if consteval {}", AllowSimpleBracedStatements); 1596 verifyFormat("if !consteval {}", AllowSimpleBracedStatements); 1597 verifyFormat("if CONSTEVAL {}", AllowSimpleBracedStatements); 1598 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1599 verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements); 1600 verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1601 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1602 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1603 verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements); 1604 verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements); 1605 verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1606 verifyFormat("if consteval { f(); }", AllowSimpleBracedStatements); 1607 verifyFormat("if CONSTEVAL { f(); }", AllowSimpleBracedStatements); 1608 verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements); 1609 verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements); 1610 verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1611 verifyFormat("MYIF consteval { f(); }", AllowSimpleBracedStatements); 1612 verifyFormat("MYIF CONSTEVAL { f(); }", AllowSimpleBracedStatements); 1613 verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements); 1614 verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements); 1615 verifyFormat("if (true) { fffffffffffffffffffffff(); }", 1616 AllowSimpleBracedStatements); 1617 verifyFormat("if (true) {\n" 1618 " ffffffffffffffffffffffff();\n" 1619 "}", 1620 AllowSimpleBracedStatements); 1621 verifyFormat("if (true) {\n" 1622 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1623 "}", 1624 AllowSimpleBracedStatements); 1625 verifyFormat("if (true) { //\n" 1626 " f();\n" 1627 "}", 1628 AllowSimpleBracedStatements); 1629 verifyFormat("if (true) {\n" 1630 " f();\n" 1631 " f();\n" 1632 "}", 1633 AllowSimpleBracedStatements); 1634 verifyFormat("if (true) {\n" 1635 " f();\n" 1636 "} else {\n" 1637 " f();\n" 1638 "}", 1639 AllowSimpleBracedStatements); 1640 verifyFormat("FI (true) { fffffffffffffffffffffff(); }", 1641 AllowSimpleBracedStatements); 1642 verifyFormat("MYIF (true) {\n" 1643 " ffffffffffffffffffffffff();\n" 1644 "}", 1645 AllowSimpleBracedStatements); 1646 verifyFormat("MYIF (true) {\n" 1647 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1648 "}", 1649 AllowSimpleBracedStatements); 1650 verifyFormat("MYIF (true) { //\n" 1651 " f();\n" 1652 "}", 1653 AllowSimpleBracedStatements); 1654 verifyFormat("MYIF (true) {\n" 1655 " f();\n" 1656 " f();\n" 1657 "}", 1658 AllowSimpleBracedStatements); 1659 verifyFormat("MYIF (true) {\n" 1660 " f();\n" 1661 "} else {\n" 1662 " f();\n" 1663 "}", 1664 AllowSimpleBracedStatements); 1665 1666 verifyFormat("struct A2 {\n" 1667 " int X;\n" 1668 "};", 1669 AllowSimpleBracedStatements); 1670 verifyFormat("typedef struct A2 {\n" 1671 " int X;\n" 1672 "} A2_t;", 1673 AllowSimpleBracedStatements); 1674 verifyFormat("template <int> struct A2 {\n" 1675 " struct B {};\n" 1676 "};", 1677 AllowSimpleBracedStatements); 1678 1679 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1680 FormatStyle::SIS_Never; 1681 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1682 verifyFormat("if (true) {\n" 1683 " f();\n" 1684 "}", 1685 AllowSimpleBracedStatements); 1686 verifyFormat("if (true) {\n" 1687 " f();\n" 1688 "} else {\n" 1689 " f();\n" 1690 "}", 1691 AllowSimpleBracedStatements); 1692 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1693 verifyFormat("MYIF (true) {\n" 1694 " f();\n" 1695 "}", 1696 AllowSimpleBracedStatements); 1697 verifyFormat("MYIF (true) {\n" 1698 " f();\n" 1699 "} else {\n" 1700 " f();\n" 1701 "}", 1702 AllowSimpleBracedStatements); 1703 1704 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false; 1705 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1706 verifyFormat("while (true) {\n" 1707 " f();\n" 1708 "}", 1709 AllowSimpleBracedStatements); 1710 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1711 verifyFormat("for (;;) {\n" 1712 " f();\n" 1713 "}", 1714 AllowSimpleBracedStatements); 1715 verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements); 1716 verifyFormat("BOOST_FOREACH (int v, vec) {\n" 1717 " f();\n" 1718 "}", 1719 AllowSimpleBracedStatements); 1720 1721 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1722 FormatStyle::SIS_WithoutElse; 1723 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true; 1724 AllowSimpleBracedStatements.BraceWrapping.AfterControlStatement = 1725 FormatStyle::BWACS_Always; 1726 1727 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1728 verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements); 1729 verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1730 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1731 verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements); 1732 verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1733 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1734 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1735 verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements); 1736 verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements); 1737 verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1738 verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements); 1739 verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements); 1740 verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1741 verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements); 1742 verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements); 1743 verifyFormat("if (true) { fffffffffffffffffffffff(); }", 1744 AllowSimpleBracedStatements); 1745 verifyFormat("if (true)\n" 1746 "{\n" 1747 " ffffffffffffffffffffffff();\n" 1748 "}", 1749 AllowSimpleBracedStatements); 1750 verifyFormat("if (true)\n" 1751 "{\n" 1752 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1753 "}", 1754 AllowSimpleBracedStatements); 1755 verifyFormat("if (true)\n" 1756 "{ //\n" 1757 " f();\n" 1758 "}", 1759 AllowSimpleBracedStatements); 1760 verifyFormat("if (true)\n" 1761 "{\n" 1762 " f();\n" 1763 " f();\n" 1764 "}", 1765 AllowSimpleBracedStatements); 1766 verifyFormat("if (true)\n" 1767 "{\n" 1768 " f();\n" 1769 "} else\n" 1770 "{\n" 1771 " f();\n" 1772 "}", 1773 AllowSimpleBracedStatements); 1774 verifyFormat("FI (true) { fffffffffffffffffffffff(); }", 1775 AllowSimpleBracedStatements); 1776 verifyFormat("MYIF (true)\n" 1777 "{\n" 1778 " ffffffffffffffffffffffff();\n" 1779 "}", 1780 AllowSimpleBracedStatements); 1781 verifyFormat("MYIF (true)\n" 1782 "{\n" 1783 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1784 "}", 1785 AllowSimpleBracedStatements); 1786 verifyFormat("MYIF (true)\n" 1787 "{ //\n" 1788 " f();\n" 1789 "}", 1790 AllowSimpleBracedStatements); 1791 verifyFormat("MYIF (true)\n" 1792 "{\n" 1793 " f();\n" 1794 " f();\n" 1795 "}", 1796 AllowSimpleBracedStatements); 1797 verifyFormat("MYIF (true)\n" 1798 "{\n" 1799 " f();\n" 1800 "} else\n" 1801 "{\n" 1802 " f();\n" 1803 "}", 1804 AllowSimpleBracedStatements); 1805 1806 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1807 FormatStyle::SIS_Never; 1808 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1809 verifyFormat("if (true)\n" 1810 "{\n" 1811 " f();\n" 1812 "}", 1813 AllowSimpleBracedStatements); 1814 verifyFormat("if (true)\n" 1815 "{\n" 1816 " f();\n" 1817 "} else\n" 1818 "{\n" 1819 " f();\n" 1820 "}", 1821 AllowSimpleBracedStatements); 1822 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1823 verifyFormat("MYIF (true)\n" 1824 "{\n" 1825 " f();\n" 1826 "}", 1827 AllowSimpleBracedStatements); 1828 verifyFormat("MYIF (true)\n" 1829 "{\n" 1830 " f();\n" 1831 "} else\n" 1832 "{\n" 1833 " f();\n" 1834 "}", 1835 AllowSimpleBracedStatements); 1836 1837 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false; 1838 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1839 verifyFormat("while (true)\n" 1840 "{\n" 1841 " f();\n" 1842 "}", 1843 AllowSimpleBracedStatements); 1844 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1845 verifyFormat("for (;;)\n" 1846 "{\n" 1847 " f();\n" 1848 "}", 1849 AllowSimpleBracedStatements); 1850 verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements); 1851 verifyFormat("BOOST_FOREACH (int v, vec)\n" 1852 "{\n" 1853 " f();\n" 1854 "}", 1855 AllowSimpleBracedStatements); 1856 } 1857 1858 TEST_F(FormatTest, UnderstandsMacros) { 1859 verifyFormat("#define A (parentheses)"); 1860 verifyFormat("/* comment */ #define A (parentheses)"); 1861 verifyFormat("/* comment */ /* another comment */ #define A (parentheses)"); 1862 // Even the partial code should never be merged. 1863 EXPECT_EQ("/* comment */ #define A (parentheses)\n" 1864 "#", 1865 format("/* comment */ #define A (parentheses)\n" 1866 "#")); 1867 verifyFormat("/* comment */ #define A (parentheses)\n" 1868 "#\n"); 1869 verifyFormat("/* comment */ #define A (parentheses)\n" 1870 "#define B (parentheses)"); 1871 verifyFormat("#define true ((int)1)"); 1872 verifyFormat("#define and(x)"); 1873 verifyFormat("#define if(x) x"); 1874 verifyFormat("#define return(x) (x)"); 1875 verifyFormat("#define while(x) for (; x;)"); 1876 verifyFormat("#define xor(x) (^(x))"); 1877 verifyFormat("#define __except(x)"); 1878 verifyFormat("#define __try(x)"); 1879 1880 FormatStyle Style = getLLVMStyle(); 1881 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 1882 Style.BraceWrapping.AfterFunction = true; 1883 // Test that a macro definition never gets merged with the following 1884 // definition. 1885 // FIXME: The AAA macro definition probably should not be split into 3 lines. 1886 verifyFormat("#define AAA " 1887 " \\\n" 1888 " N " 1889 " \\\n" 1890 " {\n" 1891 "#define BBB }\n", 1892 Style); 1893 // verifyFormat("#define AAA N { //\n", Style); 1894 1895 verifyFormat("MACRO(return)"); 1896 verifyFormat("MACRO(co_await)"); 1897 verifyFormat("MACRO(co_return)"); 1898 verifyFormat("MACRO(co_yield)"); 1899 verifyFormat("MACRO(return, something)"); 1900 verifyFormat("MACRO(co_return, something)"); 1901 verifyFormat("MACRO(something##something)"); 1902 verifyFormat("MACRO(return##something)"); 1903 verifyFormat("MACRO(co_return##something)"); 1904 } 1905 1906 TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) { 1907 FormatStyle Style = getLLVMStyleWithColumns(60); 1908 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 1909 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse; 1910 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 1911 EXPECT_EQ("#define A \\\n" 1912 " if (HANDLEwernufrnuLwrmviferuvnierv) \\\n" 1913 " { \\\n" 1914 " RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n" 1915 " }\n" 1916 "X;", 1917 format("#define A \\\n" 1918 " if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n" 1919 " RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n" 1920 " }\n" 1921 "X;", 1922 Style)); 1923 } 1924 1925 TEST_F(FormatTest, ParseIfElse) { 1926 verifyFormat("if (true)\n" 1927 " if (true)\n" 1928 " if (true)\n" 1929 " f();\n" 1930 " else\n" 1931 " g();\n" 1932 " else\n" 1933 " h();\n" 1934 "else\n" 1935 " i();"); 1936 verifyFormat("if (true)\n" 1937 " if (true)\n" 1938 " if (true) {\n" 1939 " if (true)\n" 1940 " f();\n" 1941 " } else {\n" 1942 " g();\n" 1943 " }\n" 1944 " else\n" 1945 " h();\n" 1946 "else {\n" 1947 " i();\n" 1948 "}"); 1949 verifyFormat("if (true)\n" 1950 " if constexpr (true)\n" 1951 " if (true) {\n" 1952 " if constexpr (true)\n" 1953 " f();\n" 1954 " } else {\n" 1955 " g();\n" 1956 " }\n" 1957 " else\n" 1958 " h();\n" 1959 "else {\n" 1960 " i();\n" 1961 "}"); 1962 verifyFormat("if (true)\n" 1963 " if CONSTEXPR (true)\n" 1964 " if (true) {\n" 1965 " if CONSTEXPR (true)\n" 1966 " f();\n" 1967 " } else {\n" 1968 " g();\n" 1969 " }\n" 1970 " else\n" 1971 " h();\n" 1972 "else {\n" 1973 " i();\n" 1974 "}"); 1975 verifyFormat("void f() {\n" 1976 " if (a) {\n" 1977 " } else {\n" 1978 " }\n" 1979 "}"); 1980 } 1981 1982 TEST_F(FormatTest, ElseIf) { 1983 verifyFormat("if (a) {\n} else if (b) {\n}"); 1984 verifyFormat("if (a)\n" 1985 " f();\n" 1986 "else if (b)\n" 1987 " g();\n" 1988 "else\n" 1989 " h();"); 1990 verifyFormat("if (a)\n" 1991 " f();\n" 1992 "else // comment\n" 1993 " if (b) {\n" 1994 " g();\n" 1995 " h();\n" 1996 " }"); 1997 verifyFormat("if constexpr (a)\n" 1998 " f();\n" 1999 "else if constexpr (b)\n" 2000 " g();\n" 2001 "else\n" 2002 " h();"); 2003 verifyFormat("if CONSTEXPR (a)\n" 2004 " f();\n" 2005 "else if CONSTEXPR (b)\n" 2006 " g();\n" 2007 "else\n" 2008 " h();"); 2009 verifyFormat("if (a) {\n" 2010 " f();\n" 2011 "}\n" 2012 "// or else ..\n" 2013 "else {\n" 2014 " g()\n" 2015 "}"); 2016 2017 verifyFormat("if (a) {\n" 2018 "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2019 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 2020 "}"); 2021 verifyFormat("if (a) {\n" 2022 "} else if constexpr (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2023 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 2024 "}"); 2025 verifyFormat("if (a) {\n" 2026 "} else if CONSTEXPR (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2027 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 2028 "}"); 2029 verifyFormat("if (a) {\n" 2030 "} else if (\n" 2031 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 2032 "}", 2033 getLLVMStyleWithColumns(62)); 2034 verifyFormat("if (a) {\n" 2035 "} else if constexpr (\n" 2036 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 2037 "}", 2038 getLLVMStyleWithColumns(62)); 2039 verifyFormat("if (a) {\n" 2040 "} else if CONSTEXPR (\n" 2041 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 2042 "}", 2043 getLLVMStyleWithColumns(62)); 2044 } 2045 2046 TEST_F(FormatTest, SeparatePointerReferenceAlignment) { 2047 FormatStyle Style = getLLVMStyle(); 2048 EXPECT_EQ(Style.PointerAlignment, FormatStyle::PAS_Right); 2049 EXPECT_EQ(Style.ReferenceAlignment, FormatStyle::RAS_Pointer); 2050 verifyFormat("int *f1(int *a, int &b, int &&c);", Style); 2051 verifyFormat("int &f2(int &&c, int *a, int &b);", Style); 2052 verifyFormat("int &&f3(int &b, int &&c, int *a);", Style); 2053 verifyFormat("int *f1(int &a) const &;", Style); 2054 verifyFormat("int *f1(int &a) const & = 0;", Style); 2055 verifyFormat("int *a = f1();", Style); 2056 verifyFormat("int &b = f2();", Style); 2057 verifyFormat("int &&c = f3();", Style); 2058 verifyFormat("for (auto a = 0, b = 0; const auto &c : {1, 2, 3})", Style); 2059 verifyFormat("for (auto a = 0, b = 0; const int &c : {1, 2, 3})", Style); 2060 verifyFormat("for (auto a = 0, b = 0; const Foo &c : {1, 2, 3})", Style); 2061 verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style); 2062 verifyFormat("for (int a = 0, b = 0; const auto &c : {1, 2, 3})", Style); 2063 verifyFormat("for (int a = 0, b = 0; const int &c : {1, 2, 3})", Style); 2064 verifyFormat("for (int a = 0, b = 0; const Foo &c : {1, 2, 3})", Style); 2065 verifyFormat("for (int a = 0, b++; const auto &c : {1, 2, 3})", Style); 2066 verifyFormat("for (int a = 0, b++; const int &c : {1, 2, 3})", Style); 2067 verifyFormat("for (int a = 0, b++; const Foo &c : {1, 2, 3})", Style); 2068 verifyFormat("for (auto x = 0; auto &c : {1, 2, 3})", Style); 2069 verifyFormat("for (auto x = 0; int &c : {1, 2, 3})", Style); 2070 verifyFormat("for (int x = 0; auto &c : {1, 2, 3})", Style); 2071 verifyFormat("for (int x = 0; int &c : {1, 2, 3})", Style); 2072 verifyFormat("for (f(); auto &c : {1, 2, 3})", Style); 2073 verifyFormat("for (f(); int &c : {1, 2, 3})", Style); 2074 verifyFormat( 2075 "function<int(int &)> res1 = [](int &a) { return 0000000000000; },\n" 2076 " res2 = [](int &a) { return 0000000000000; };", 2077 Style); 2078 2079 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 2080 verifyFormat("Const unsigned int *c;\n" 2081 "const unsigned int *d;\n" 2082 "Const unsigned int &e;\n" 2083 "const unsigned int &f;\n" 2084 "const unsigned &&g;\n" 2085 "Const unsigned h;", 2086 Style); 2087 2088 Style.PointerAlignment = FormatStyle::PAS_Left; 2089 Style.ReferenceAlignment = FormatStyle::RAS_Pointer; 2090 verifyFormat("int* f1(int* a, int& b, int&& c);", Style); 2091 verifyFormat("int& f2(int&& c, int* a, int& b);", Style); 2092 verifyFormat("int&& f3(int& b, int&& c, int* a);", Style); 2093 verifyFormat("int* f1(int& a) const& = 0;", Style); 2094 verifyFormat("int* a = f1();", Style); 2095 verifyFormat("int& b = f2();", Style); 2096 verifyFormat("int&& c = f3();", Style); 2097 verifyFormat("for (auto a = 0, b = 0; const auto& c : {1, 2, 3})", Style); 2098 verifyFormat("for (auto a = 0, b = 0; const int& c : {1, 2, 3})", Style); 2099 verifyFormat("for (auto a = 0, b = 0; const Foo& c : {1, 2, 3})", Style); 2100 verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style); 2101 verifyFormat("for (int a = 0, b = 0; const auto& c : {1, 2, 3})", Style); 2102 verifyFormat("for (int a = 0, b = 0; const int& c : {1, 2, 3})", Style); 2103 verifyFormat("for (int a = 0, b = 0; const Foo& c : {1, 2, 3})", Style); 2104 verifyFormat("for (int a = 0, b = 0; const Foo* c : {1, 2, 3})", Style); 2105 verifyFormat("for (int a = 0, b++; const auto& c : {1, 2, 3})", Style); 2106 verifyFormat("for (int a = 0, b++; const int& c : {1, 2, 3})", Style); 2107 verifyFormat("for (int a = 0, b++; const Foo& c : {1, 2, 3})", Style); 2108 verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style); 2109 verifyFormat("for (auto x = 0; auto& c : {1, 2, 3})", Style); 2110 verifyFormat("for (auto x = 0; int& c : {1, 2, 3})", Style); 2111 verifyFormat("for (int x = 0; auto& c : {1, 2, 3})", Style); 2112 verifyFormat("for (int x = 0; int& c : {1, 2, 3})", Style); 2113 verifyFormat("for (f(); auto& c : {1, 2, 3})", Style); 2114 verifyFormat("for (f(); int& c : {1, 2, 3})", Style); 2115 verifyFormat( 2116 "function<int(int&)> res1 = [](int& a) { return 0000000000000; },\n" 2117 " res2 = [](int& a) { return 0000000000000; };", 2118 Style); 2119 2120 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 2121 verifyFormat("Const unsigned int* c;\n" 2122 "const unsigned int* d;\n" 2123 "Const unsigned int& e;\n" 2124 "const unsigned int& f;\n" 2125 "const unsigned&& g;\n" 2126 "Const unsigned h;", 2127 Style); 2128 2129 Style.PointerAlignment = FormatStyle::PAS_Right; 2130 Style.ReferenceAlignment = FormatStyle::RAS_Left; 2131 verifyFormat("int *f1(int *a, int& b, int&& c);", Style); 2132 verifyFormat("int& f2(int&& c, int *a, int& b);", Style); 2133 verifyFormat("int&& f3(int& b, int&& c, int *a);", Style); 2134 verifyFormat("int *a = f1();", Style); 2135 verifyFormat("int& b = f2();", Style); 2136 verifyFormat("int&& c = f3();", Style); 2137 verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style); 2138 verifyFormat("for (int a = 0, b = 0; const Foo *c : {1, 2, 3})", Style); 2139 verifyFormat("for (int a = 0, b++; const Foo *c : {1, 2, 3})", Style); 2140 2141 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 2142 verifyFormat("Const unsigned int *c;\n" 2143 "const unsigned int *d;\n" 2144 "Const unsigned int& e;\n" 2145 "const unsigned int& f;\n" 2146 "const unsigned g;\n" 2147 "Const unsigned h;", 2148 Style); 2149 2150 Style.PointerAlignment = FormatStyle::PAS_Left; 2151 Style.ReferenceAlignment = FormatStyle::RAS_Middle; 2152 verifyFormat("int* f1(int* a, int & b, int && c);", Style); 2153 verifyFormat("int & f2(int && c, int* a, int & b);", Style); 2154 verifyFormat("int && f3(int & b, int && c, int* a);", Style); 2155 verifyFormat("int* a = f1();", Style); 2156 verifyFormat("int & b = f2();", Style); 2157 verifyFormat("int && c = f3();", Style); 2158 verifyFormat("for (auto a = 0, b = 0; const auto & c : {1, 2, 3})", Style); 2159 verifyFormat("for (auto a = 0, b = 0; const int & c : {1, 2, 3})", Style); 2160 verifyFormat("for (auto a = 0, b = 0; const Foo & c : {1, 2, 3})", Style); 2161 verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style); 2162 verifyFormat("for (int a = 0, b++; const auto & c : {1, 2, 3})", Style); 2163 verifyFormat("for (int a = 0, b++; const int & c : {1, 2, 3})", Style); 2164 verifyFormat("for (int a = 0, b++; const Foo & c : {1, 2, 3})", Style); 2165 verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style); 2166 verifyFormat("for (auto x = 0; auto & c : {1, 2, 3})", Style); 2167 verifyFormat("for (auto x = 0; int & c : {1, 2, 3})", Style); 2168 verifyFormat("for (int x = 0; auto & c : {1, 2, 3})", Style); 2169 verifyFormat("for (int x = 0; int & c : {1, 2, 3})", Style); 2170 verifyFormat("for (f(); auto & c : {1, 2, 3})", Style); 2171 verifyFormat("for (f(); int & c : {1, 2, 3})", Style); 2172 verifyFormat( 2173 "function<int(int &)> res1 = [](int & a) { return 0000000000000; },\n" 2174 " res2 = [](int & a) { return 0000000000000; };", 2175 Style); 2176 2177 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 2178 verifyFormat("Const unsigned int* c;\n" 2179 "const unsigned int* d;\n" 2180 "Const unsigned int & e;\n" 2181 "const unsigned int & f;\n" 2182 "const unsigned && g;\n" 2183 "Const unsigned h;", 2184 Style); 2185 2186 Style.PointerAlignment = FormatStyle::PAS_Middle; 2187 Style.ReferenceAlignment = FormatStyle::RAS_Right; 2188 verifyFormat("int * f1(int * a, int &b, int &&c);", Style); 2189 verifyFormat("int &f2(int &&c, int * a, int &b);", Style); 2190 verifyFormat("int &&f3(int &b, int &&c, int * a);", Style); 2191 verifyFormat("int * a = f1();", Style); 2192 verifyFormat("int &b = f2();", Style); 2193 verifyFormat("int &&c = f3();", Style); 2194 verifyFormat("for (auto a = 0, b = 0; const Foo * c : {1, 2, 3})", Style); 2195 verifyFormat("for (int a = 0, b = 0; const Foo * c : {1, 2, 3})", Style); 2196 verifyFormat("for (int a = 0, b++; const Foo * c : {1, 2, 3})", Style); 2197 2198 // FIXME: we don't handle this yet, so output may be arbitrary until it's 2199 // specifically handled 2200 // verifyFormat("int Add2(BTree * &Root, char * szToAdd)", Style); 2201 } 2202 2203 TEST_F(FormatTest, FormatsForLoop) { 2204 verifyFormat( 2205 "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n" 2206 " ++VeryVeryLongLoopVariable)\n" 2207 " ;"); 2208 verifyFormat("for (;;)\n" 2209 " f();"); 2210 verifyFormat("for (;;) {\n}"); 2211 verifyFormat("for (;;) {\n" 2212 " f();\n" 2213 "}"); 2214 verifyFormat("for (int i = 0; (i < 10); ++i) {\n}"); 2215 2216 verifyFormat( 2217 "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n" 2218 " E = UnwrappedLines.end();\n" 2219 " I != E; ++I) {\n}"); 2220 2221 verifyFormat( 2222 "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n" 2223 " ++IIIII) {\n}"); 2224 verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n" 2225 " aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n" 2226 " aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}"); 2227 verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n" 2228 " I = FD->getDeclsInPrototypeScope().begin(),\n" 2229 " E = FD->getDeclsInPrototypeScope().end();\n" 2230 " I != E; ++I) {\n}"); 2231 verifyFormat("for (SmallVectorImpl<TemplateIdAnnotationn *>::iterator\n" 2232 " I = Container.begin(),\n" 2233 " E = Container.end();\n" 2234 " I != E; ++I) {\n}", 2235 getLLVMStyleWithColumns(76)); 2236 2237 verifyFormat( 2238 "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n" 2239 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n" 2240 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2241 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 2242 " ++aaaaaaaaaaa) {\n}"); 2243 verifyFormat("for (int i = 0; i < aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 2244 " bbbbbbbbbbbbbbbbbbbb < ccccccccccccccc;\n" 2245 " ++i) {\n}"); 2246 verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n" 2247 " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n" 2248 "}"); 2249 verifyFormat("for (some_namespace::SomeIterator iter( // force break\n" 2250 " aaaaaaaaaa);\n" 2251 " iter; ++iter) {\n" 2252 "}"); 2253 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2254 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 2255 " aaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbbbbbbb;\n" 2256 " ++aaaaaaaaaaaaaaaaaaaaaaaaaaa) {"); 2257 2258 // These should not be formatted as Objective-C for-in loops. 2259 verifyFormat("for (Foo *x = 0; x != in; x++) {\n}"); 2260 verifyFormat("Foo *x;\nfor (x = 0; x != in; x++) {\n}"); 2261 verifyFormat("Foo *x;\nfor (x in y) {\n}"); 2262 verifyFormat( 2263 "for (const Foo<Bar> &baz = in.value(); !baz.at_end(); ++baz) {\n}"); 2264 2265 FormatStyle NoBinPacking = getLLVMStyle(); 2266 NoBinPacking.BinPackParameters = false; 2267 verifyFormat("for (int aaaaaaaaaaa = 1;\n" 2268 " aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n" 2269 " aaaaaaaaaaaaaaaa,\n" 2270 " aaaaaaaaaaaaaaaa,\n" 2271 " aaaaaaaaaaaaaaaa);\n" 2272 " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n" 2273 "}", 2274 NoBinPacking); 2275 verifyFormat( 2276 "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n" 2277 " E = UnwrappedLines.end();\n" 2278 " I != E;\n" 2279 " ++I) {\n}", 2280 NoBinPacking); 2281 2282 FormatStyle AlignLeft = getLLVMStyle(); 2283 AlignLeft.PointerAlignment = FormatStyle::PAS_Left; 2284 verifyFormat("for (A* a = start; a < end; ++a, ++value) {\n}", AlignLeft); 2285 } 2286 2287 TEST_F(FormatTest, RangeBasedForLoops) { 2288 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 2289 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 2290 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n" 2291 " aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}"); 2292 verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n" 2293 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 2294 verifyFormat("for (aaaaaaaaa aaaaaaaaaaaaaaaaaaaaa :\n" 2295 " aaaaaaaaaaaa.aaaaaaaaaaaa().aaaaaaaaa().a()) {\n}"); 2296 } 2297 2298 TEST_F(FormatTest, ForEachLoops) { 2299 FormatStyle Style = getLLVMStyle(); 2300 EXPECT_EQ(Style.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 2301 EXPECT_EQ(Style.AllowShortLoopsOnASingleLine, false); 2302 verifyFormat("void f() {\n" 2303 " for (;;) {\n" 2304 " }\n" 2305 " foreach (Item *item, itemlist) {\n" 2306 " }\n" 2307 " Q_FOREACH (Item *item, itemlist) {\n" 2308 " }\n" 2309 " BOOST_FOREACH (Item *item, itemlist) {\n" 2310 " }\n" 2311 " UNKNOWN_FOREACH(Item * item, itemlist) {}\n" 2312 "}", 2313 Style); 2314 verifyFormat("void f() {\n" 2315 " for (;;)\n" 2316 " int j = 1;\n" 2317 " Q_FOREACH (int v, vec)\n" 2318 " v *= 2;\n" 2319 " for (;;) {\n" 2320 " int j = 1;\n" 2321 " }\n" 2322 " Q_FOREACH (int v, vec) {\n" 2323 " v *= 2;\n" 2324 " }\n" 2325 "}", 2326 Style); 2327 2328 FormatStyle ShortBlocks = getLLVMStyle(); 2329 ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 2330 EXPECT_EQ(ShortBlocks.AllowShortLoopsOnASingleLine, false); 2331 verifyFormat("void f() {\n" 2332 " for (;;)\n" 2333 " int j = 1;\n" 2334 " Q_FOREACH (int &v, vec)\n" 2335 " v *= 2;\n" 2336 " for (;;) {\n" 2337 " int j = 1;\n" 2338 " }\n" 2339 " Q_FOREACH (int &v, vec) {\n" 2340 " int j = 1;\n" 2341 " }\n" 2342 "}", 2343 ShortBlocks); 2344 2345 FormatStyle ShortLoops = getLLVMStyle(); 2346 ShortLoops.AllowShortLoopsOnASingleLine = true; 2347 EXPECT_EQ(ShortLoops.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 2348 verifyFormat("void f() {\n" 2349 " for (;;) int j = 1;\n" 2350 " Q_FOREACH (int &v, vec) int j = 1;\n" 2351 " for (;;) {\n" 2352 " int j = 1;\n" 2353 " }\n" 2354 " Q_FOREACH (int &v, vec) {\n" 2355 " int j = 1;\n" 2356 " }\n" 2357 "}", 2358 ShortLoops); 2359 2360 FormatStyle ShortBlocksAndLoops = getLLVMStyle(); 2361 ShortBlocksAndLoops.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 2362 ShortBlocksAndLoops.AllowShortLoopsOnASingleLine = true; 2363 verifyFormat("void f() {\n" 2364 " for (;;) int j = 1;\n" 2365 " Q_FOREACH (int &v, vec) int j = 1;\n" 2366 " for (;;) { int j = 1; }\n" 2367 " Q_FOREACH (int &v, vec) { int j = 1; }\n" 2368 "}", 2369 ShortBlocksAndLoops); 2370 2371 Style.SpaceBeforeParens = 2372 FormatStyle::SBPO_ControlStatementsExceptControlMacros; 2373 verifyFormat("void f() {\n" 2374 " for (;;) {\n" 2375 " }\n" 2376 " foreach(Item *item, itemlist) {\n" 2377 " }\n" 2378 " Q_FOREACH(Item *item, itemlist) {\n" 2379 " }\n" 2380 " BOOST_FOREACH(Item *item, itemlist) {\n" 2381 " }\n" 2382 " UNKNOWN_FOREACH(Item * item, itemlist) {}\n" 2383 "}", 2384 Style); 2385 2386 // As function-like macros. 2387 verifyFormat("#define foreach(x, y)\n" 2388 "#define Q_FOREACH(x, y)\n" 2389 "#define BOOST_FOREACH(x, y)\n" 2390 "#define UNKNOWN_FOREACH(x, y)\n"); 2391 2392 // Not as function-like macros. 2393 verifyFormat("#define foreach (x, y)\n" 2394 "#define Q_FOREACH (x, y)\n" 2395 "#define BOOST_FOREACH (x, y)\n" 2396 "#define UNKNOWN_FOREACH (x, y)\n"); 2397 2398 // handle microsoft non standard extension 2399 verifyFormat("for each (char c in x->MyStringProperty)"); 2400 } 2401 2402 TEST_F(FormatTest, FormatsWhileLoop) { 2403 verifyFormat("while (true) {\n}"); 2404 verifyFormat("while (true)\n" 2405 " f();"); 2406 verifyFormat("while () {\n}"); 2407 verifyFormat("while () {\n" 2408 " f();\n" 2409 "}"); 2410 } 2411 2412 TEST_F(FormatTest, FormatsDoWhile) { 2413 verifyFormat("do {\n" 2414 " do_something();\n" 2415 "} while (something());"); 2416 verifyFormat("do\n" 2417 " do_something();\n" 2418 "while (something());"); 2419 } 2420 2421 TEST_F(FormatTest, FormatsSwitchStatement) { 2422 verifyFormat("switch (x) {\n" 2423 "case 1:\n" 2424 " f();\n" 2425 " break;\n" 2426 "case kFoo:\n" 2427 "case ns::kBar:\n" 2428 "case kBaz:\n" 2429 " break;\n" 2430 "default:\n" 2431 " g();\n" 2432 " break;\n" 2433 "}"); 2434 verifyFormat("switch (x) {\n" 2435 "case 1: {\n" 2436 " f();\n" 2437 " break;\n" 2438 "}\n" 2439 "case 2: {\n" 2440 " break;\n" 2441 "}\n" 2442 "}"); 2443 verifyFormat("switch (x) {\n" 2444 "case 1: {\n" 2445 " f();\n" 2446 " {\n" 2447 " g();\n" 2448 " h();\n" 2449 " }\n" 2450 " break;\n" 2451 "}\n" 2452 "}"); 2453 verifyFormat("switch (x) {\n" 2454 "case 1: {\n" 2455 " f();\n" 2456 " if (foo) {\n" 2457 " g();\n" 2458 " h();\n" 2459 " }\n" 2460 " break;\n" 2461 "}\n" 2462 "}"); 2463 verifyFormat("switch (x) {\n" 2464 "case 1: {\n" 2465 " f();\n" 2466 " g();\n" 2467 "} break;\n" 2468 "}"); 2469 verifyFormat("switch (test)\n" 2470 " ;"); 2471 verifyFormat("switch (x) {\n" 2472 "default: {\n" 2473 " // Do nothing.\n" 2474 "}\n" 2475 "}"); 2476 verifyFormat("switch (x) {\n" 2477 "// comment\n" 2478 "// if 1, do f()\n" 2479 "case 1:\n" 2480 " f();\n" 2481 "}"); 2482 verifyFormat("switch (x) {\n" 2483 "case 1:\n" 2484 " // Do amazing stuff\n" 2485 " {\n" 2486 " f();\n" 2487 " g();\n" 2488 " }\n" 2489 " break;\n" 2490 "}"); 2491 verifyFormat("#define A \\\n" 2492 " switch (x) { \\\n" 2493 " case a: \\\n" 2494 " foo = b; \\\n" 2495 " }", 2496 getLLVMStyleWithColumns(20)); 2497 verifyFormat("#define OPERATION_CASE(name) \\\n" 2498 " case OP_name: \\\n" 2499 " return operations::Operation##name\n", 2500 getLLVMStyleWithColumns(40)); 2501 verifyFormat("switch (x) {\n" 2502 "case 1:;\n" 2503 "default:;\n" 2504 " int i;\n" 2505 "}"); 2506 2507 verifyGoogleFormat("switch (x) {\n" 2508 " case 1:\n" 2509 " f();\n" 2510 " break;\n" 2511 " case kFoo:\n" 2512 " case ns::kBar:\n" 2513 " case kBaz:\n" 2514 " break;\n" 2515 " default:\n" 2516 " g();\n" 2517 " break;\n" 2518 "}"); 2519 verifyGoogleFormat("switch (x) {\n" 2520 " case 1: {\n" 2521 " f();\n" 2522 " break;\n" 2523 " }\n" 2524 "}"); 2525 verifyGoogleFormat("switch (test)\n" 2526 " ;"); 2527 2528 verifyGoogleFormat("#define OPERATION_CASE(name) \\\n" 2529 " case OP_name: \\\n" 2530 " return operations::Operation##name\n"); 2531 verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n" 2532 " // Get the correction operation class.\n" 2533 " switch (OpCode) {\n" 2534 " CASE(Add);\n" 2535 " CASE(Subtract);\n" 2536 " default:\n" 2537 " return operations::Unknown;\n" 2538 " }\n" 2539 "#undef OPERATION_CASE\n" 2540 "}"); 2541 verifyFormat("DEBUG({\n" 2542 " switch (x) {\n" 2543 " case A:\n" 2544 " f();\n" 2545 " break;\n" 2546 " // fallthrough\n" 2547 " case B:\n" 2548 " g();\n" 2549 " break;\n" 2550 " }\n" 2551 "});"); 2552 EXPECT_EQ("DEBUG({\n" 2553 " switch (x) {\n" 2554 " case A:\n" 2555 " f();\n" 2556 " break;\n" 2557 " // On B:\n" 2558 " case B:\n" 2559 " g();\n" 2560 " break;\n" 2561 " }\n" 2562 "});", 2563 format("DEBUG({\n" 2564 " switch (x) {\n" 2565 " case A:\n" 2566 " f();\n" 2567 " break;\n" 2568 " // On B:\n" 2569 " case B:\n" 2570 " g();\n" 2571 " break;\n" 2572 " }\n" 2573 "});", 2574 getLLVMStyle())); 2575 EXPECT_EQ("switch (n) {\n" 2576 "case 0: {\n" 2577 " return false;\n" 2578 "}\n" 2579 "default: {\n" 2580 " return true;\n" 2581 "}\n" 2582 "}", 2583 format("switch (n)\n" 2584 "{\n" 2585 "case 0: {\n" 2586 " return false;\n" 2587 "}\n" 2588 "default: {\n" 2589 " return true;\n" 2590 "}\n" 2591 "}", 2592 getLLVMStyle())); 2593 verifyFormat("switch (a) {\n" 2594 "case (b):\n" 2595 " return;\n" 2596 "}"); 2597 2598 verifyFormat("switch (a) {\n" 2599 "case some_namespace::\n" 2600 " some_constant:\n" 2601 " return;\n" 2602 "}", 2603 getLLVMStyleWithColumns(34)); 2604 2605 FormatStyle Style = getLLVMStyle(); 2606 Style.IndentCaseLabels = true; 2607 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 2608 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2609 Style.BraceWrapping.AfterCaseLabel = true; 2610 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 2611 EXPECT_EQ("switch (n)\n" 2612 "{\n" 2613 " case 0:\n" 2614 " {\n" 2615 " return false;\n" 2616 " }\n" 2617 " default:\n" 2618 " {\n" 2619 " return true;\n" 2620 " }\n" 2621 "}", 2622 format("switch (n) {\n" 2623 " case 0: {\n" 2624 " return false;\n" 2625 " }\n" 2626 " default: {\n" 2627 " return true;\n" 2628 " }\n" 2629 "}", 2630 Style)); 2631 Style.BraceWrapping.AfterCaseLabel = false; 2632 EXPECT_EQ("switch (n)\n" 2633 "{\n" 2634 " case 0: {\n" 2635 " return false;\n" 2636 " }\n" 2637 " default: {\n" 2638 " return true;\n" 2639 " }\n" 2640 "}", 2641 format("switch (n) {\n" 2642 " case 0:\n" 2643 " {\n" 2644 " return false;\n" 2645 " }\n" 2646 " default:\n" 2647 " {\n" 2648 " return true;\n" 2649 " }\n" 2650 "}", 2651 Style)); 2652 Style.IndentCaseLabels = false; 2653 Style.IndentCaseBlocks = true; 2654 EXPECT_EQ("switch (n)\n" 2655 "{\n" 2656 "case 0:\n" 2657 " {\n" 2658 " return false;\n" 2659 " }\n" 2660 "case 1:\n" 2661 " break;\n" 2662 "default:\n" 2663 " {\n" 2664 " return true;\n" 2665 " }\n" 2666 "}", 2667 format("switch (n) {\n" 2668 "case 0: {\n" 2669 " return false;\n" 2670 "}\n" 2671 "case 1:\n" 2672 " break;\n" 2673 "default: {\n" 2674 " return true;\n" 2675 "}\n" 2676 "}", 2677 Style)); 2678 Style.IndentCaseLabels = true; 2679 Style.IndentCaseBlocks = true; 2680 EXPECT_EQ("switch (n)\n" 2681 "{\n" 2682 " case 0:\n" 2683 " {\n" 2684 " return false;\n" 2685 " }\n" 2686 " case 1:\n" 2687 " break;\n" 2688 " default:\n" 2689 " {\n" 2690 " return true;\n" 2691 " }\n" 2692 "}", 2693 format("switch (n) {\n" 2694 "case 0: {\n" 2695 " return false;\n" 2696 "}\n" 2697 "case 1:\n" 2698 " break;\n" 2699 "default: {\n" 2700 " return true;\n" 2701 "}\n" 2702 "}", 2703 Style)); 2704 } 2705 2706 TEST_F(FormatTest, CaseRanges) { 2707 verifyFormat("switch (x) {\n" 2708 "case 'A' ... 'Z':\n" 2709 "case 1 ... 5:\n" 2710 "case a ... b:\n" 2711 " break;\n" 2712 "}"); 2713 } 2714 2715 TEST_F(FormatTest, ShortEnums) { 2716 FormatStyle Style = getLLVMStyle(); 2717 Style.AllowShortEnumsOnASingleLine = true; 2718 verifyFormat("enum { A, B, C } ShortEnum1, ShortEnum2;", Style); 2719 verifyFormat("typedef enum { A, B, C } ShortEnum1, ShortEnum2;", Style); 2720 Style.AllowShortEnumsOnASingleLine = false; 2721 verifyFormat("enum {\n" 2722 " A,\n" 2723 " B,\n" 2724 " C\n" 2725 "} ShortEnum1, ShortEnum2;", 2726 Style); 2727 verifyFormat("typedef enum {\n" 2728 " A,\n" 2729 " B,\n" 2730 " C\n" 2731 "} ShortEnum1, ShortEnum2;", 2732 Style); 2733 verifyFormat("enum {\n" 2734 " A,\n" 2735 "} ShortEnum1, ShortEnum2;", 2736 Style); 2737 verifyFormat("typedef enum {\n" 2738 " A,\n" 2739 "} ShortEnum1, ShortEnum2;", 2740 Style); 2741 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2742 Style.BraceWrapping.AfterEnum = true; 2743 verifyFormat("enum\n" 2744 "{\n" 2745 " A,\n" 2746 " B,\n" 2747 " C\n" 2748 "} ShortEnum1, ShortEnum2;", 2749 Style); 2750 verifyFormat("typedef enum\n" 2751 "{\n" 2752 " A,\n" 2753 " B,\n" 2754 " C\n" 2755 "} ShortEnum1, ShortEnum2;", 2756 Style); 2757 } 2758 2759 TEST_F(FormatTest, ShortCaseLabels) { 2760 FormatStyle Style = getLLVMStyle(); 2761 Style.AllowShortCaseLabelsOnASingleLine = true; 2762 verifyFormat("switch (a) {\n" 2763 "case 1: x = 1; break;\n" 2764 "case 2: return;\n" 2765 "case 3:\n" 2766 "case 4:\n" 2767 "case 5: return;\n" 2768 "case 6: // comment\n" 2769 " return;\n" 2770 "case 7:\n" 2771 " // comment\n" 2772 " return;\n" 2773 "case 8:\n" 2774 " x = 8; // comment\n" 2775 " break;\n" 2776 "default: y = 1; break;\n" 2777 "}", 2778 Style); 2779 verifyFormat("switch (a) {\n" 2780 "case 0: return; // comment\n" 2781 "case 1: break; // comment\n" 2782 "case 2: return;\n" 2783 "// comment\n" 2784 "case 3: return;\n" 2785 "// comment 1\n" 2786 "// comment 2\n" 2787 "// comment 3\n" 2788 "case 4: break; /* comment */\n" 2789 "case 5:\n" 2790 " // comment\n" 2791 " break;\n" 2792 "case 6: /* comment */ x = 1; break;\n" 2793 "case 7: x = /* comment */ 1; break;\n" 2794 "case 8:\n" 2795 " x = 1; /* comment */\n" 2796 " break;\n" 2797 "case 9:\n" 2798 " break; // comment line 1\n" 2799 " // comment line 2\n" 2800 "}", 2801 Style); 2802 EXPECT_EQ("switch (a) {\n" 2803 "case 1:\n" 2804 " x = 8;\n" 2805 " // fall through\n" 2806 "case 2: x = 8;\n" 2807 "// comment\n" 2808 "case 3:\n" 2809 " return; /* comment line 1\n" 2810 " * comment line 2 */\n" 2811 "case 4: i = 8;\n" 2812 "// something else\n" 2813 "#if FOO\n" 2814 "case 5: break;\n" 2815 "#endif\n" 2816 "}", 2817 format("switch (a) {\n" 2818 "case 1: x = 8;\n" 2819 " // fall through\n" 2820 "case 2:\n" 2821 " x = 8;\n" 2822 "// comment\n" 2823 "case 3:\n" 2824 " return; /* comment line 1\n" 2825 " * comment line 2 */\n" 2826 "case 4:\n" 2827 " i = 8;\n" 2828 "// something else\n" 2829 "#if FOO\n" 2830 "case 5: break;\n" 2831 "#endif\n" 2832 "}", 2833 Style)); 2834 EXPECT_EQ("switch (a) {\n" 2835 "case 0:\n" 2836 " return; // long long long long long long long long long long " 2837 "long long comment\n" 2838 " // line\n" 2839 "}", 2840 format("switch (a) {\n" 2841 "case 0: return; // long long long long long long long long " 2842 "long long long long comment line\n" 2843 "}", 2844 Style)); 2845 EXPECT_EQ("switch (a) {\n" 2846 "case 0:\n" 2847 " return; /* long long long long long long long long long long " 2848 "long long comment\n" 2849 " line */\n" 2850 "}", 2851 format("switch (a) {\n" 2852 "case 0: return; /* long long long long long long long long " 2853 "long long long long comment line */\n" 2854 "}", 2855 Style)); 2856 verifyFormat("switch (a) {\n" 2857 "#if FOO\n" 2858 "case 0: return 0;\n" 2859 "#endif\n" 2860 "}", 2861 Style); 2862 verifyFormat("switch (a) {\n" 2863 "case 1: {\n" 2864 "}\n" 2865 "case 2: {\n" 2866 " return;\n" 2867 "}\n" 2868 "case 3: {\n" 2869 " x = 1;\n" 2870 " return;\n" 2871 "}\n" 2872 "case 4:\n" 2873 " if (x)\n" 2874 " return;\n" 2875 "}", 2876 Style); 2877 Style.ColumnLimit = 21; 2878 verifyFormat("switch (a) {\n" 2879 "case 1: x = 1; break;\n" 2880 "case 2: return;\n" 2881 "case 3:\n" 2882 "case 4:\n" 2883 "case 5: return;\n" 2884 "default:\n" 2885 " y = 1;\n" 2886 " break;\n" 2887 "}", 2888 Style); 2889 Style.ColumnLimit = 80; 2890 Style.AllowShortCaseLabelsOnASingleLine = false; 2891 Style.IndentCaseLabels = true; 2892 EXPECT_EQ("switch (n) {\n" 2893 " default /*comments*/:\n" 2894 " return true;\n" 2895 " case 0:\n" 2896 " return false;\n" 2897 "}", 2898 format("switch (n) {\n" 2899 "default/*comments*/:\n" 2900 " return true;\n" 2901 "case 0:\n" 2902 " return false;\n" 2903 "}", 2904 Style)); 2905 Style.AllowShortCaseLabelsOnASingleLine = true; 2906 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2907 Style.BraceWrapping.AfterCaseLabel = true; 2908 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 2909 EXPECT_EQ("switch (n)\n" 2910 "{\n" 2911 " case 0:\n" 2912 " {\n" 2913 " return false;\n" 2914 " }\n" 2915 " default:\n" 2916 " {\n" 2917 " return true;\n" 2918 " }\n" 2919 "}", 2920 format("switch (n) {\n" 2921 " case 0: {\n" 2922 " return false;\n" 2923 " }\n" 2924 " default:\n" 2925 " {\n" 2926 " return true;\n" 2927 " }\n" 2928 "}", 2929 Style)); 2930 } 2931 2932 TEST_F(FormatTest, FormatsLabels) { 2933 verifyFormat("void f() {\n" 2934 " some_code();\n" 2935 "test_label:\n" 2936 " some_other_code();\n" 2937 " {\n" 2938 " some_more_code();\n" 2939 " another_label:\n" 2940 " some_more_code();\n" 2941 " }\n" 2942 "}"); 2943 verifyFormat("{\n" 2944 " some_code();\n" 2945 "test_label:\n" 2946 " some_other_code();\n" 2947 "}"); 2948 verifyFormat("{\n" 2949 " some_code();\n" 2950 "test_label:;\n" 2951 " int i = 0;\n" 2952 "}"); 2953 FormatStyle Style = getLLVMStyle(); 2954 Style.IndentGotoLabels = false; 2955 verifyFormat("void f() {\n" 2956 " some_code();\n" 2957 "test_label:\n" 2958 " some_other_code();\n" 2959 " {\n" 2960 " some_more_code();\n" 2961 "another_label:\n" 2962 " some_more_code();\n" 2963 " }\n" 2964 "}", 2965 Style); 2966 verifyFormat("{\n" 2967 " some_code();\n" 2968 "test_label:\n" 2969 " some_other_code();\n" 2970 "}", 2971 Style); 2972 verifyFormat("{\n" 2973 " some_code();\n" 2974 "test_label:;\n" 2975 " int i = 0;\n" 2976 "}"); 2977 } 2978 2979 TEST_F(FormatTest, MultiLineControlStatements) { 2980 FormatStyle Style = getLLVMStyleWithColumns(20); 2981 Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom; 2982 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine; 2983 // Short lines should keep opening brace on same line. 2984 EXPECT_EQ("if (foo) {\n" 2985 " bar();\n" 2986 "}", 2987 format("if(foo){bar();}", Style)); 2988 EXPECT_EQ("if (foo) {\n" 2989 " bar();\n" 2990 "} else {\n" 2991 " baz();\n" 2992 "}", 2993 format("if(foo){bar();}else{baz();}", Style)); 2994 EXPECT_EQ("if (foo && bar) {\n" 2995 " baz();\n" 2996 "}", 2997 format("if(foo&&bar){baz();}", Style)); 2998 EXPECT_EQ("if (foo) {\n" 2999 " bar();\n" 3000 "} else if (baz) {\n" 3001 " quux();\n" 3002 "}", 3003 format("if(foo){bar();}else if(baz){quux();}", Style)); 3004 EXPECT_EQ( 3005 "if (foo) {\n" 3006 " bar();\n" 3007 "} else if (baz) {\n" 3008 " quux();\n" 3009 "} else {\n" 3010 " foobar();\n" 3011 "}", 3012 format("if(foo){bar();}else if(baz){quux();}else{foobar();}", Style)); 3013 EXPECT_EQ("for (;;) {\n" 3014 " foo();\n" 3015 "}", 3016 format("for(;;){foo();}")); 3017 EXPECT_EQ("while (1) {\n" 3018 " foo();\n" 3019 "}", 3020 format("while(1){foo();}", Style)); 3021 EXPECT_EQ("switch (foo) {\n" 3022 "case bar:\n" 3023 " return;\n" 3024 "}", 3025 format("switch(foo){case bar:return;}", Style)); 3026 EXPECT_EQ("try {\n" 3027 " foo();\n" 3028 "} catch (...) {\n" 3029 " bar();\n" 3030 "}", 3031 format("try{foo();}catch(...){bar();}", Style)); 3032 EXPECT_EQ("do {\n" 3033 " foo();\n" 3034 "} while (bar &&\n" 3035 " baz);", 3036 format("do{foo();}while(bar&&baz);", Style)); 3037 // Long lines should put opening brace on new line. 3038 EXPECT_EQ("if (foo && bar &&\n" 3039 " baz)\n" 3040 "{\n" 3041 " quux();\n" 3042 "}", 3043 format("if(foo&&bar&&baz){quux();}", Style)); 3044 EXPECT_EQ("if (foo && bar &&\n" 3045 " baz)\n" 3046 "{\n" 3047 " quux();\n" 3048 "}", 3049 format("if (foo && bar &&\n" 3050 " baz) {\n" 3051 " quux();\n" 3052 "}", 3053 Style)); 3054 EXPECT_EQ("if (foo) {\n" 3055 " bar();\n" 3056 "} else if (baz ||\n" 3057 " quux)\n" 3058 "{\n" 3059 " foobar();\n" 3060 "}", 3061 format("if(foo){bar();}else if(baz||quux){foobar();}", Style)); 3062 EXPECT_EQ( 3063 "if (foo) {\n" 3064 " bar();\n" 3065 "} else if (baz ||\n" 3066 " quux)\n" 3067 "{\n" 3068 " foobar();\n" 3069 "} else {\n" 3070 " barbaz();\n" 3071 "}", 3072 format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}", 3073 Style)); 3074 EXPECT_EQ("for (int i = 0;\n" 3075 " i < 10; ++i)\n" 3076 "{\n" 3077 " foo();\n" 3078 "}", 3079 format("for(int i=0;i<10;++i){foo();}", Style)); 3080 EXPECT_EQ("foreach (int i,\n" 3081 " list)\n" 3082 "{\n" 3083 " foo();\n" 3084 "}", 3085 format("foreach(int i, list){foo();}", Style)); 3086 Style.ColumnLimit = 3087 40; // to concentrate at brace wrapping, not line wrap due to column limit 3088 EXPECT_EQ("foreach (int i, list) {\n" 3089 " foo();\n" 3090 "}", 3091 format("foreach(int i, list){foo();}", Style)); 3092 Style.ColumnLimit = 3093 20; // to concentrate at brace wrapping, not line wrap due to column limit 3094 EXPECT_EQ("while (foo || bar ||\n" 3095 " baz)\n" 3096 "{\n" 3097 " quux();\n" 3098 "}", 3099 format("while(foo||bar||baz){quux();}", Style)); 3100 EXPECT_EQ("switch (\n" 3101 " foo = barbaz)\n" 3102 "{\n" 3103 "case quux:\n" 3104 " return;\n" 3105 "}", 3106 format("switch(foo=barbaz){case quux:return;}", Style)); 3107 EXPECT_EQ("try {\n" 3108 " foo();\n" 3109 "} catch (\n" 3110 " Exception &bar)\n" 3111 "{\n" 3112 " baz();\n" 3113 "}", 3114 format("try{foo();}catch(Exception&bar){baz();}", Style)); 3115 Style.ColumnLimit = 3116 40; // to concentrate at brace wrapping, not line wrap due to column limit 3117 EXPECT_EQ("try {\n" 3118 " foo();\n" 3119 "} catch (Exception &bar) {\n" 3120 " baz();\n" 3121 "}", 3122 format("try{foo();}catch(Exception&bar){baz();}", Style)); 3123 Style.ColumnLimit = 3124 20; // to concentrate at brace wrapping, not line wrap due to column limit 3125 3126 Style.BraceWrapping.BeforeElse = true; 3127 EXPECT_EQ( 3128 "if (foo) {\n" 3129 " bar();\n" 3130 "}\n" 3131 "else if (baz ||\n" 3132 " quux)\n" 3133 "{\n" 3134 " foobar();\n" 3135 "}\n" 3136 "else {\n" 3137 " barbaz();\n" 3138 "}", 3139 format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}", 3140 Style)); 3141 3142 Style.BraceWrapping.BeforeCatch = true; 3143 EXPECT_EQ("try {\n" 3144 " foo();\n" 3145 "}\n" 3146 "catch (...) {\n" 3147 " baz();\n" 3148 "}", 3149 format("try{foo();}catch(...){baz();}", Style)); 3150 3151 Style.BraceWrapping.AfterFunction = true; 3152 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine; 3153 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 3154 Style.ColumnLimit = 80; 3155 verifyFormat("void shortfunction() { bar(); }", Style); 3156 3157 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 3158 verifyFormat("void shortfunction()\n" 3159 "{\n" 3160 " bar();\n" 3161 "}", 3162 Style); 3163 } 3164 3165 TEST_F(FormatTest, BeforeWhile) { 3166 FormatStyle Style = getLLVMStyle(); 3167 Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom; 3168 3169 verifyFormat("do {\n" 3170 " foo();\n" 3171 "} while (1);", 3172 Style); 3173 Style.BraceWrapping.BeforeWhile = true; 3174 verifyFormat("do {\n" 3175 " foo();\n" 3176 "}\n" 3177 "while (1);", 3178 Style); 3179 } 3180 3181 //===----------------------------------------------------------------------===// 3182 // Tests for classes, namespaces, etc. 3183 //===----------------------------------------------------------------------===// 3184 3185 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) { 3186 verifyFormat("class A {};"); 3187 } 3188 3189 TEST_F(FormatTest, UnderstandsAccessSpecifiers) { 3190 verifyFormat("class A {\n" 3191 "public:\n" 3192 "public: // comment\n" 3193 "protected:\n" 3194 "private:\n" 3195 " void f() {}\n" 3196 "};"); 3197 verifyFormat("export class A {\n" 3198 "public:\n" 3199 "public: // comment\n" 3200 "protected:\n" 3201 "private:\n" 3202 " void f() {}\n" 3203 "};"); 3204 verifyGoogleFormat("class A {\n" 3205 " public:\n" 3206 " protected:\n" 3207 " private:\n" 3208 " void f() {}\n" 3209 "};"); 3210 verifyGoogleFormat("export class A {\n" 3211 " public:\n" 3212 " protected:\n" 3213 " private:\n" 3214 " void f() {}\n" 3215 "};"); 3216 verifyFormat("class A {\n" 3217 "public slots:\n" 3218 " void f1() {}\n" 3219 "public Q_SLOTS:\n" 3220 " void f2() {}\n" 3221 "protected slots:\n" 3222 " void f3() {}\n" 3223 "protected Q_SLOTS:\n" 3224 " void f4() {}\n" 3225 "private slots:\n" 3226 " void f5() {}\n" 3227 "private Q_SLOTS:\n" 3228 " void f6() {}\n" 3229 "signals:\n" 3230 " void g1();\n" 3231 "Q_SIGNALS:\n" 3232 " void g2();\n" 3233 "};"); 3234 3235 // Don't interpret 'signals' the wrong way. 3236 verifyFormat("signals.set();"); 3237 verifyFormat("for (Signals signals : f()) {\n}"); 3238 verifyFormat("{\n" 3239 " signals.set(); // This needs indentation.\n" 3240 "}"); 3241 verifyFormat("void f() {\n" 3242 "label:\n" 3243 " signals.baz();\n" 3244 "}"); 3245 verifyFormat("private[1];"); 3246 verifyFormat("testArray[public] = 1;"); 3247 verifyFormat("public();"); 3248 verifyFormat("myFunc(public);"); 3249 verifyFormat("std::vector<int> testVec = {private};"); 3250 verifyFormat("private.p = 1;"); 3251 verifyFormat("void function(private...){};"); 3252 verifyFormat("if (private && public)\n"); 3253 verifyFormat("private &= true;"); 3254 verifyFormat("int x = private * public;"); 3255 verifyFormat("public *= private;"); 3256 verifyFormat("int x = public + private;"); 3257 verifyFormat("private++;"); 3258 verifyFormat("++private;"); 3259 verifyFormat("public += private;"); 3260 verifyFormat("public = public - private;"); 3261 verifyFormat("public->foo();"); 3262 verifyFormat("private--;"); 3263 verifyFormat("--private;"); 3264 verifyFormat("public -= 1;"); 3265 verifyFormat("if (!private && !public)\n"); 3266 verifyFormat("public != private;"); 3267 verifyFormat("int x = public / private;"); 3268 verifyFormat("public /= 2;"); 3269 verifyFormat("public = public % 2;"); 3270 verifyFormat("public %= 2;"); 3271 verifyFormat("if (public < private)\n"); 3272 verifyFormat("public << private;"); 3273 verifyFormat("public <<= private;"); 3274 verifyFormat("if (public > private)\n"); 3275 verifyFormat("public >> private;"); 3276 verifyFormat("public >>= private;"); 3277 verifyFormat("public ^ private;"); 3278 verifyFormat("public ^= private;"); 3279 verifyFormat("public | private;"); 3280 verifyFormat("public |= private;"); 3281 verifyFormat("auto x = private ? 1 : 2;"); 3282 verifyFormat("if (public == private)\n"); 3283 verifyFormat("void foo(public, private)"); 3284 verifyFormat("public::foo();"); 3285 } 3286 3287 TEST_F(FormatTest, SeparatesLogicalBlocks) { 3288 EXPECT_EQ("class A {\n" 3289 "public:\n" 3290 " void f();\n" 3291 "\n" 3292 "private:\n" 3293 " void g() {}\n" 3294 " // test\n" 3295 "protected:\n" 3296 " int h;\n" 3297 "};", 3298 format("class A {\n" 3299 "public:\n" 3300 "void f();\n" 3301 "private:\n" 3302 "void g() {}\n" 3303 "// test\n" 3304 "protected:\n" 3305 "int h;\n" 3306 "};")); 3307 EXPECT_EQ("class A {\n" 3308 "protected:\n" 3309 "public:\n" 3310 " void f();\n" 3311 "};", 3312 format("class A {\n" 3313 "protected:\n" 3314 "\n" 3315 "public:\n" 3316 "\n" 3317 " void f();\n" 3318 "};")); 3319 3320 // Even ensure proper spacing inside macros. 3321 EXPECT_EQ("#define B \\\n" 3322 " class A { \\\n" 3323 " protected: \\\n" 3324 " public: \\\n" 3325 " void f(); \\\n" 3326 " };", 3327 format("#define B \\\n" 3328 " class A { \\\n" 3329 " protected: \\\n" 3330 " \\\n" 3331 " public: \\\n" 3332 " \\\n" 3333 " void f(); \\\n" 3334 " };", 3335 getGoogleStyle())); 3336 // But don't remove empty lines after macros ending in access specifiers. 3337 EXPECT_EQ("#define A private:\n" 3338 "\n" 3339 "int i;", 3340 format("#define A private:\n" 3341 "\n" 3342 "int i;")); 3343 } 3344 3345 TEST_F(FormatTest, FormatsClasses) { 3346 verifyFormat("class A : public B {};"); 3347 verifyFormat("class A : public ::B {};"); 3348 3349 verifyFormat( 3350 "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3351 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};"); 3352 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n" 3353 " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3354 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};"); 3355 verifyFormat( 3356 "class A : public B, public C, public D, public E, public F {};"); 3357 verifyFormat("class AAAAAAAAAAAA : public B,\n" 3358 " public C,\n" 3359 " public D,\n" 3360 " public E,\n" 3361 " public F,\n" 3362 " public G {};"); 3363 3364 verifyFormat("class\n" 3365 " ReallyReallyLongClassName {\n" 3366 " int i;\n" 3367 "};", 3368 getLLVMStyleWithColumns(32)); 3369 verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n" 3370 " aaaaaaaaaaaaaaaa> {};"); 3371 verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n" 3372 " : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n" 3373 " aaaaaaaaaaaaaaaaaaaaaa> {};"); 3374 verifyFormat("template <class R, class C>\n" 3375 "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n" 3376 " : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};"); 3377 verifyFormat("class ::A::B {};"); 3378 } 3379 3380 TEST_F(FormatTest, BreakInheritanceStyle) { 3381 FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle(); 3382 StyleWithInheritanceBreakBeforeComma.BreakInheritanceList = 3383 FormatStyle::BILS_BeforeComma; 3384 verifyFormat("class MyClass : public X {};", 3385 StyleWithInheritanceBreakBeforeComma); 3386 verifyFormat("class MyClass\n" 3387 " : public X\n" 3388 " , public Y {};", 3389 StyleWithInheritanceBreakBeforeComma); 3390 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n" 3391 " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n" 3392 " , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};", 3393 StyleWithInheritanceBreakBeforeComma); 3394 verifyFormat("struct aaaaaaaaaaaaa\n" 3395 " : public aaaaaaaaaaaaaaaaaaa< // break\n" 3396 " aaaaaaaaaaaaaaaa> {};", 3397 StyleWithInheritanceBreakBeforeComma); 3398 3399 FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle(); 3400 StyleWithInheritanceBreakAfterColon.BreakInheritanceList = 3401 FormatStyle::BILS_AfterColon; 3402 verifyFormat("class MyClass : public X {};", 3403 StyleWithInheritanceBreakAfterColon); 3404 verifyFormat("class MyClass : public X, public Y {};", 3405 StyleWithInheritanceBreakAfterColon); 3406 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n" 3407 " public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3408 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};", 3409 StyleWithInheritanceBreakAfterColon); 3410 verifyFormat("struct aaaaaaaaaaaaa :\n" 3411 " public aaaaaaaaaaaaaaaaaaa< // break\n" 3412 " aaaaaaaaaaaaaaaa> {};", 3413 StyleWithInheritanceBreakAfterColon); 3414 3415 FormatStyle StyleWithInheritanceBreakAfterComma = getLLVMStyle(); 3416 StyleWithInheritanceBreakAfterComma.BreakInheritanceList = 3417 FormatStyle::BILS_AfterComma; 3418 verifyFormat("class MyClass : public X {};", 3419 StyleWithInheritanceBreakAfterComma); 3420 verifyFormat("class MyClass : public X,\n" 3421 " public Y {};", 3422 StyleWithInheritanceBreakAfterComma); 3423 verifyFormat( 3424 "class AAAAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3425 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC " 3426 "{};", 3427 StyleWithInheritanceBreakAfterComma); 3428 verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n" 3429 " aaaaaaaaaaaaaaaa> {};", 3430 StyleWithInheritanceBreakAfterComma); 3431 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n" 3432 " : public OnceBreak,\n" 3433 " public AlwaysBreak,\n" 3434 " EvenBasesFitInOneLine {};", 3435 StyleWithInheritanceBreakAfterComma); 3436 } 3437 3438 TEST_F(FormatTest, FormatsVariableDeclarationsAfterRecord) { 3439 verifyFormat("class A {\n} a, b;"); 3440 verifyFormat("struct A {\n} a, b;"); 3441 verifyFormat("union A {\n} a, b;"); 3442 3443 verifyFormat("constexpr class A {\n} a, b;"); 3444 verifyFormat("constexpr struct A {\n} a, b;"); 3445 verifyFormat("constexpr union A {\n} a, b;"); 3446 3447 verifyFormat("namespace {\nclass A {\n} a, b;\n} // namespace"); 3448 verifyFormat("namespace {\nstruct A {\n} a, b;\n} // namespace"); 3449 verifyFormat("namespace {\nunion A {\n} a, b;\n} // namespace"); 3450 3451 verifyFormat("namespace {\nconstexpr class A {\n} a, b;\n} // namespace"); 3452 verifyFormat("namespace {\nconstexpr struct A {\n} a, b;\n} // namespace"); 3453 verifyFormat("namespace {\nconstexpr union A {\n} a, b;\n} // namespace"); 3454 3455 verifyFormat("namespace ns {\n" 3456 "class {\n" 3457 "} a, b;\n" 3458 "} // namespace ns"); 3459 verifyFormat("namespace ns {\n" 3460 "const class {\n" 3461 "} a, b;\n" 3462 "} // namespace ns"); 3463 verifyFormat("namespace ns {\n" 3464 "constexpr class C {\n" 3465 "} a, b;\n" 3466 "} // namespace ns"); 3467 verifyFormat("namespace ns {\n" 3468 "class { /* comment */\n" 3469 "} a, b;\n" 3470 "} // namespace ns"); 3471 verifyFormat("namespace ns {\n" 3472 "const class { /* comment */\n" 3473 "} a, b;\n" 3474 "} // namespace ns"); 3475 } 3476 3477 TEST_F(FormatTest, FormatsEnum) { 3478 verifyFormat("enum {\n" 3479 " Zero,\n" 3480 " One = 1,\n" 3481 " Two = One + 1,\n" 3482 " Three = (One + Two),\n" 3483 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3484 " Five = (One, Two, Three, Four, 5)\n" 3485 "};"); 3486 verifyGoogleFormat("enum {\n" 3487 " Zero,\n" 3488 " One = 1,\n" 3489 " Two = One + 1,\n" 3490 " Three = (One + Two),\n" 3491 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3492 " Five = (One, Two, Three, Four, 5)\n" 3493 "};"); 3494 verifyFormat("enum Enum {};"); 3495 verifyFormat("enum {};"); 3496 verifyFormat("enum X E {} d;"); 3497 verifyFormat("enum __attribute__((...)) E {} d;"); 3498 verifyFormat("enum __declspec__((...)) E {} d;"); 3499 verifyFormat("enum {\n" 3500 " Bar = Foo<int, int>::value\n" 3501 "};", 3502 getLLVMStyleWithColumns(30)); 3503 3504 verifyFormat("enum ShortEnum { A, B, C };"); 3505 verifyGoogleFormat("enum ShortEnum { A, B, C };"); 3506 3507 EXPECT_EQ("enum KeepEmptyLines {\n" 3508 " ONE,\n" 3509 "\n" 3510 " TWO,\n" 3511 "\n" 3512 " THREE\n" 3513 "}", 3514 format("enum KeepEmptyLines {\n" 3515 " ONE,\n" 3516 "\n" 3517 " TWO,\n" 3518 "\n" 3519 "\n" 3520 " THREE\n" 3521 "}")); 3522 verifyFormat("enum E { // comment\n" 3523 " ONE,\n" 3524 " TWO\n" 3525 "};\n" 3526 "int i;"); 3527 3528 FormatStyle EightIndent = getLLVMStyle(); 3529 EightIndent.IndentWidth = 8; 3530 verifyFormat("enum {\n" 3531 " VOID,\n" 3532 " CHAR,\n" 3533 " SHORT,\n" 3534 " INT,\n" 3535 " LONG,\n" 3536 " SIGNED,\n" 3537 " UNSIGNED,\n" 3538 " BOOL,\n" 3539 " FLOAT,\n" 3540 " DOUBLE,\n" 3541 " COMPLEX\n" 3542 "};", 3543 EightIndent); 3544 3545 // Not enums. 3546 verifyFormat("enum X f() {\n" 3547 " a();\n" 3548 " return 42;\n" 3549 "}"); 3550 verifyFormat("enum X Type::f() {\n" 3551 " a();\n" 3552 " return 42;\n" 3553 "}"); 3554 verifyFormat("enum ::X f() {\n" 3555 " a();\n" 3556 " return 42;\n" 3557 "}"); 3558 verifyFormat("enum ns::X f() {\n" 3559 " a();\n" 3560 " return 42;\n" 3561 "}"); 3562 } 3563 3564 TEST_F(FormatTest, FormatsEnumsWithErrors) { 3565 verifyFormat("enum Type {\n" 3566 " One = 0; // These semicolons should be commas.\n" 3567 " Two = 1;\n" 3568 "};"); 3569 verifyFormat("namespace n {\n" 3570 "enum Type {\n" 3571 " One,\n" 3572 " Two, // missing };\n" 3573 " int i;\n" 3574 "}\n" 3575 "void g() {}"); 3576 } 3577 3578 TEST_F(FormatTest, FormatsEnumStruct) { 3579 verifyFormat("enum struct {\n" 3580 " Zero,\n" 3581 " One = 1,\n" 3582 " Two = One + 1,\n" 3583 " Three = (One + Two),\n" 3584 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3585 " Five = (One, Two, Three, Four, 5)\n" 3586 "};"); 3587 verifyFormat("enum struct Enum {};"); 3588 verifyFormat("enum struct {};"); 3589 verifyFormat("enum struct X E {} d;"); 3590 verifyFormat("enum struct __attribute__((...)) E {} d;"); 3591 verifyFormat("enum struct __declspec__((...)) E {} d;"); 3592 verifyFormat("enum struct X f() {\n a();\n return 42;\n}"); 3593 } 3594 3595 TEST_F(FormatTest, FormatsEnumClass) { 3596 verifyFormat("enum class {\n" 3597 " Zero,\n" 3598 " One = 1,\n" 3599 " Two = One + 1,\n" 3600 " Three = (One + Two),\n" 3601 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3602 " Five = (One, Two, Three, Four, 5)\n" 3603 "};"); 3604 verifyFormat("enum class Enum {};"); 3605 verifyFormat("enum class {};"); 3606 verifyFormat("enum class X E {} d;"); 3607 verifyFormat("enum class __attribute__((...)) E {} d;"); 3608 verifyFormat("enum class __declspec__((...)) E {} d;"); 3609 verifyFormat("enum class X f() {\n a();\n return 42;\n}"); 3610 } 3611 3612 TEST_F(FormatTest, FormatsEnumTypes) { 3613 verifyFormat("enum X : int {\n" 3614 " A, // Force multiple lines.\n" 3615 " B\n" 3616 "};"); 3617 verifyFormat("enum X : int { A, B };"); 3618 verifyFormat("enum X : std::uint32_t { A, B };"); 3619 } 3620 3621 TEST_F(FormatTest, FormatsTypedefEnum) { 3622 FormatStyle Style = getLLVMStyleWithColumns(40); 3623 verifyFormat("typedef enum {} EmptyEnum;"); 3624 verifyFormat("typedef enum { A, B, C } ShortEnum;"); 3625 verifyFormat("typedef enum {\n" 3626 " ZERO = 0,\n" 3627 " ONE = 1,\n" 3628 " TWO = 2,\n" 3629 " THREE = 3\n" 3630 "} LongEnum;", 3631 Style); 3632 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 3633 Style.BraceWrapping.AfterEnum = true; 3634 verifyFormat("typedef enum {} EmptyEnum;"); 3635 verifyFormat("typedef enum { A, B, C } ShortEnum;"); 3636 verifyFormat("typedef enum\n" 3637 "{\n" 3638 " ZERO = 0,\n" 3639 " ONE = 1,\n" 3640 " TWO = 2,\n" 3641 " THREE = 3\n" 3642 "} LongEnum;", 3643 Style); 3644 } 3645 3646 TEST_F(FormatTest, FormatsNSEnums) { 3647 verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }"); 3648 verifyGoogleFormat( 3649 "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }"); 3650 verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n" 3651 " // Information about someDecentlyLongValue.\n" 3652 " someDecentlyLongValue,\n" 3653 " // Information about anotherDecentlyLongValue.\n" 3654 " anotherDecentlyLongValue,\n" 3655 " // Information about aThirdDecentlyLongValue.\n" 3656 " aThirdDecentlyLongValue\n" 3657 "};"); 3658 verifyGoogleFormat("typedef NS_CLOSED_ENUM(NSInteger, MyType) {\n" 3659 " // Information about someDecentlyLongValue.\n" 3660 " someDecentlyLongValue,\n" 3661 " // Information about anotherDecentlyLongValue.\n" 3662 " anotherDecentlyLongValue,\n" 3663 " // Information about aThirdDecentlyLongValue.\n" 3664 " aThirdDecentlyLongValue\n" 3665 "};"); 3666 verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n" 3667 " a = 1,\n" 3668 " b = 2,\n" 3669 " c = 3,\n" 3670 "};"); 3671 verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n" 3672 " a = 1,\n" 3673 " b = 2,\n" 3674 " c = 3,\n" 3675 "};"); 3676 verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n" 3677 " a = 1,\n" 3678 " b = 2,\n" 3679 " c = 3,\n" 3680 "};"); 3681 verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n" 3682 " a = 1,\n" 3683 " b = 2,\n" 3684 " c = 3,\n" 3685 "};"); 3686 } 3687 3688 TEST_F(FormatTest, FormatsBitfields) { 3689 verifyFormat("struct Bitfields {\n" 3690 " unsigned sClass : 8;\n" 3691 " unsigned ValueKind : 2;\n" 3692 "};"); 3693 verifyFormat("struct A {\n" 3694 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n" 3695 " bbbbbbbbbbbbbbbbbbbbbbbbb;\n" 3696 "};"); 3697 verifyFormat("struct MyStruct {\n" 3698 " uchar data;\n" 3699 " uchar : 8;\n" 3700 " uchar : 8;\n" 3701 " uchar other;\n" 3702 "};"); 3703 FormatStyle Style = getLLVMStyle(); 3704 Style.BitFieldColonSpacing = FormatStyle::BFCS_None; 3705 verifyFormat("struct Bitfields {\n" 3706 " unsigned sClass:8;\n" 3707 " unsigned ValueKind:2;\n" 3708 " uchar other;\n" 3709 "};", 3710 Style); 3711 verifyFormat("struct A {\n" 3712 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:1,\n" 3713 " bbbbbbbbbbbbbbbbbbbbbbbbb:2;\n" 3714 "};", 3715 Style); 3716 Style.BitFieldColonSpacing = FormatStyle::BFCS_Before; 3717 verifyFormat("struct Bitfields {\n" 3718 " unsigned sClass :8;\n" 3719 " unsigned ValueKind :2;\n" 3720 " uchar other;\n" 3721 "};", 3722 Style); 3723 Style.BitFieldColonSpacing = FormatStyle::BFCS_After; 3724 verifyFormat("struct Bitfields {\n" 3725 " unsigned sClass: 8;\n" 3726 " unsigned ValueKind: 2;\n" 3727 " uchar other;\n" 3728 "};", 3729 Style); 3730 } 3731 3732 TEST_F(FormatTest, FormatsNamespaces) { 3733 FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle(); 3734 LLVMWithNoNamespaceFix.FixNamespaceComments = false; 3735 3736 verifyFormat("namespace some_namespace {\n" 3737 "class A {};\n" 3738 "void f() { f(); }\n" 3739 "}", 3740 LLVMWithNoNamespaceFix); 3741 verifyFormat("#define M(x) x##x\n" 3742 "namespace M(x) {\n" 3743 "class A {};\n" 3744 "void f() { f(); }\n" 3745 "}", 3746 LLVMWithNoNamespaceFix); 3747 verifyFormat("#define M(x) x##x\n" 3748 "namespace N::inline M(x) {\n" 3749 "class A {};\n" 3750 "void f() { f(); }\n" 3751 "}", 3752 LLVMWithNoNamespaceFix); 3753 verifyFormat("#define M(x) x##x\n" 3754 "namespace M(x)::inline N {\n" 3755 "class A {};\n" 3756 "void f() { f(); }\n" 3757 "}", 3758 LLVMWithNoNamespaceFix); 3759 verifyFormat("#define M(x) x##x\n" 3760 "namespace N::M(x) {\n" 3761 "class A {};\n" 3762 "void f() { f(); }\n" 3763 "}", 3764 LLVMWithNoNamespaceFix); 3765 verifyFormat("#define M(x) x##x\n" 3766 "namespace M::N(x) {\n" 3767 "class A {};\n" 3768 "void f() { f(); }\n" 3769 "}", 3770 LLVMWithNoNamespaceFix); 3771 verifyFormat("namespace N::inline D {\n" 3772 "class A {};\n" 3773 "void f() { f(); }\n" 3774 "}", 3775 LLVMWithNoNamespaceFix); 3776 verifyFormat("namespace N::inline D::E {\n" 3777 "class A {};\n" 3778 "void f() { f(); }\n" 3779 "}", 3780 LLVMWithNoNamespaceFix); 3781 verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n" 3782 "class A {};\n" 3783 "void f() { f(); }\n" 3784 "}", 3785 LLVMWithNoNamespaceFix); 3786 verifyFormat("/* something */ namespace some_namespace {\n" 3787 "class A {};\n" 3788 "void f() { f(); }\n" 3789 "}", 3790 LLVMWithNoNamespaceFix); 3791 verifyFormat("namespace {\n" 3792 "class A {};\n" 3793 "void f() { f(); }\n" 3794 "}", 3795 LLVMWithNoNamespaceFix); 3796 verifyFormat("/* something */ namespace {\n" 3797 "class A {};\n" 3798 "void f() { f(); }\n" 3799 "}", 3800 LLVMWithNoNamespaceFix); 3801 verifyFormat("inline namespace X {\n" 3802 "class A {};\n" 3803 "void f() { f(); }\n" 3804 "}", 3805 LLVMWithNoNamespaceFix); 3806 verifyFormat("/* something */ inline namespace X {\n" 3807 "class A {};\n" 3808 "void f() { f(); }\n" 3809 "}", 3810 LLVMWithNoNamespaceFix); 3811 verifyFormat("export namespace X {\n" 3812 "class A {};\n" 3813 "void f() { f(); }\n" 3814 "}", 3815 LLVMWithNoNamespaceFix); 3816 verifyFormat("using namespace some_namespace;\n" 3817 "class A {};\n" 3818 "void f() { f(); }", 3819 LLVMWithNoNamespaceFix); 3820 3821 // This code is more common than we thought; if we 3822 // layout this correctly the semicolon will go into 3823 // its own line, which is undesirable. 3824 verifyFormat("namespace {};", LLVMWithNoNamespaceFix); 3825 verifyFormat("namespace {\n" 3826 "class A {};\n" 3827 "};", 3828 LLVMWithNoNamespaceFix); 3829 3830 verifyFormat("namespace {\n" 3831 "int SomeVariable = 0; // comment\n" 3832 "} // namespace", 3833 LLVMWithNoNamespaceFix); 3834 EXPECT_EQ("#ifndef HEADER_GUARD\n" 3835 "#define HEADER_GUARD\n" 3836 "namespace my_namespace {\n" 3837 "int i;\n" 3838 "} // my_namespace\n" 3839 "#endif // HEADER_GUARD", 3840 format("#ifndef HEADER_GUARD\n" 3841 " #define HEADER_GUARD\n" 3842 " namespace my_namespace {\n" 3843 "int i;\n" 3844 "} // my_namespace\n" 3845 "#endif // HEADER_GUARD", 3846 LLVMWithNoNamespaceFix)); 3847 3848 EXPECT_EQ("namespace A::B {\n" 3849 "class C {};\n" 3850 "}", 3851 format("namespace A::B {\n" 3852 "class C {};\n" 3853 "}", 3854 LLVMWithNoNamespaceFix)); 3855 3856 FormatStyle Style = getLLVMStyle(); 3857 Style.NamespaceIndentation = FormatStyle::NI_All; 3858 EXPECT_EQ("namespace out {\n" 3859 " int i;\n" 3860 " namespace in {\n" 3861 " int i;\n" 3862 " } // namespace in\n" 3863 "} // namespace out", 3864 format("namespace out {\n" 3865 "int i;\n" 3866 "namespace in {\n" 3867 "int i;\n" 3868 "} // namespace in\n" 3869 "} // namespace out", 3870 Style)); 3871 3872 FormatStyle ShortInlineFunctions = getLLVMStyle(); 3873 ShortInlineFunctions.NamespaceIndentation = FormatStyle::NI_All; 3874 ShortInlineFunctions.AllowShortFunctionsOnASingleLine = 3875 FormatStyle::SFS_Inline; 3876 verifyFormat("namespace {\n" 3877 " void f() {\n" 3878 " return;\n" 3879 " }\n" 3880 "} // namespace\n", 3881 ShortInlineFunctions); 3882 verifyFormat("namespace { /* comment */\n" 3883 " void f() {\n" 3884 " return;\n" 3885 " }\n" 3886 "} // namespace\n", 3887 ShortInlineFunctions); 3888 verifyFormat("namespace { // comment\n" 3889 " void f() {\n" 3890 " return;\n" 3891 " }\n" 3892 "} // namespace\n", 3893 ShortInlineFunctions); 3894 verifyFormat("namespace {\n" 3895 " int some_int;\n" 3896 " void f() {\n" 3897 " return;\n" 3898 " }\n" 3899 "} // namespace\n", 3900 ShortInlineFunctions); 3901 verifyFormat("namespace interface {\n" 3902 " void f() {\n" 3903 " return;\n" 3904 " }\n" 3905 "} // namespace interface\n", 3906 ShortInlineFunctions); 3907 verifyFormat("namespace {\n" 3908 " class X {\n" 3909 " void f() { return; }\n" 3910 " };\n" 3911 "} // namespace\n", 3912 ShortInlineFunctions); 3913 verifyFormat("namespace {\n" 3914 " class X { /* comment */\n" 3915 " void f() { return; }\n" 3916 " };\n" 3917 "} // namespace\n", 3918 ShortInlineFunctions); 3919 verifyFormat("namespace {\n" 3920 " class X { // comment\n" 3921 " void f() { return; }\n" 3922 " };\n" 3923 "} // namespace\n", 3924 ShortInlineFunctions); 3925 verifyFormat("namespace {\n" 3926 " struct X {\n" 3927 " void f() { return; }\n" 3928 " };\n" 3929 "} // namespace\n", 3930 ShortInlineFunctions); 3931 verifyFormat("namespace {\n" 3932 " union X {\n" 3933 " void f() { return; }\n" 3934 " };\n" 3935 "} // namespace\n", 3936 ShortInlineFunctions); 3937 verifyFormat("extern \"C\" {\n" 3938 "void f() {\n" 3939 " return;\n" 3940 "}\n" 3941 "} // namespace\n", 3942 ShortInlineFunctions); 3943 verifyFormat("namespace {\n" 3944 " class X {\n" 3945 " void f() { return; }\n" 3946 " } x;\n" 3947 "} // namespace\n", 3948 ShortInlineFunctions); 3949 verifyFormat("namespace {\n" 3950 " [[nodiscard]] class X {\n" 3951 " void f() { return; }\n" 3952 " };\n" 3953 "} // namespace\n", 3954 ShortInlineFunctions); 3955 verifyFormat("namespace {\n" 3956 " static class X {\n" 3957 " void f() { return; }\n" 3958 " } x;\n" 3959 "} // namespace\n", 3960 ShortInlineFunctions); 3961 verifyFormat("namespace {\n" 3962 " constexpr class X {\n" 3963 " void f() { return; }\n" 3964 " } x;\n" 3965 "} // namespace\n", 3966 ShortInlineFunctions); 3967 3968 ShortInlineFunctions.IndentExternBlock = FormatStyle::IEBS_Indent; 3969 verifyFormat("extern \"C\" {\n" 3970 " void f() {\n" 3971 " return;\n" 3972 " }\n" 3973 "} // namespace\n", 3974 ShortInlineFunctions); 3975 3976 Style.NamespaceIndentation = FormatStyle::NI_Inner; 3977 EXPECT_EQ("namespace out {\n" 3978 "int i;\n" 3979 "namespace in {\n" 3980 " int i;\n" 3981 "} // namespace in\n" 3982 "} // namespace out", 3983 format("namespace out {\n" 3984 "int i;\n" 3985 "namespace in {\n" 3986 "int i;\n" 3987 "} // namespace in\n" 3988 "} // namespace out", 3989 Style)); 3990 3991 Style.NamespaceIndentation = FormatStyle::NI_None; 3992 verifyFormat("template <class T>\n" 3993 "concept a_concept = X<>;\n" 3994 "namespace B {\n" 3995 "struct b_struct {};\n" 3996 "} // namespace B\n", 3997 Style); 3998 verifyFormat("template <int I>\n" 3999 "constexpr void foo()\n" 4000 " requires(I == 42)\n" 4001 "{}\n" 4002 "namespace ns {\n" 4003 "void foo() {}\n" 4004 "} // namespace ns\n", 4005 Style); 4006 } 4007 4008 TEST_F(FormatTest, NamespaceMacros) { 4009 FormatStyle Style = getLLVMStyle(); 4010 Style.NamespaceMacros.push_back("TESTSUITE"); 4011 4012 verifyFormat("TESTSUITE(A) {\n" 4013 "int foo();\n" 4014 "} // TESTSUITE(A)", 4015 Style); 4016 4017 verifyFormat("TESTSUITE(A, B) {\n" 4018 "int foo();\n" 4019 "} // TESTSUITE(A)", 4020 Style); 4021 4022 // Properly indent according to NamespaceIndentation style 4023 Style.NamespaceIndentation = FormatStyle::NI_All; 4024 verifyFormat("TESTSUITE(A) {\n" 4025 " int foo();\n" 4026 "} // TESTSUITE(A)", 4027 Style); 4028 verifyFormat("TESTSUITE(A) {\n" 4029 " namespace B {\n" 4030 " int foo();\n" 4031 " } // namespace B\n" 4032 "} // TESTSUITE(A)", 4033 Style); 4034 verifyFormat("namespace A {\n" 4035 " TESTSUITE(B) {\n" 4036 " int foo();\n" 4037 " } // TESTSUITE(B)\n" 4038 "} // namespace A", 4039 Style); 4040 4041 Style.NamespaceIndentation = FormatStyle::NI_Inner; 4042 verifyFormat("TESTSUITE(A) {\n" 4043 "TESTSUITE(B) {\n" 4044 " int foo();\n" 4045 "} // TESTSUITE(B)\n" 4046 "} // TESTSUITE(A)", 4047 Style); 4048 verifyFormat("TESTSUITE(A) {\n" 4049 "namespace B {\n" 4050 " int foo();\n" 4051 "} // namespace B\n" 4052 "} // TESTSUITE(A)", 4053 Style); 4054 verifyFormat("namespace A {\n" 4055 "TESTSUITE(B) {\n" 4056 " int foo();\n" 4057 "} // TESTSUITE(B)\n" 4058 "} // namespace A", 4059 Style); 4060 4061 // Properly merge namespace-macros blocks in CompactNamespaces mode 4062 Style.NamespaceIndentation = FormatStyle::NI_None; 4063 Style.CompactNamespaces = true; 4064 verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n" 4065 "}} // TESTSUITE(A::B)", 4066 Style); 4067 4068 EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n" 4069 "}} // TESTSUITE(out::in)", 4070 format("TESTSUITE(out) {\n" 4071 "TESTSUITE(in) {\n" 4072 "} // TESTSUITE(in)\n" 4073 "} // TESTSUITE(out)", 4074 Style)); 4075 4076 EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n" 4077 "}} // TESTSUITE(out::in)", 4078 format("TESTSUITE(out) {\n" 4079 "TESTSUITE(in) {\n" 4080 "} // TESTSUITE(in)\n" 4081 "} // TESTSUITE(out)", 4082 Style)); 4083 4084 // Do not merge different namespaces/macros 4085 EXPECT_EQ("namespace out {\n" 4086 "TESTSUITE(in) {\n" 4087 "} // TESTSUITE(in)\n" 4088 "} // namespace out", 4089 format("namespace out {\n" 4090 "TESTSUITE(in) {\n" 4091 "} // TESTSUITE(in)\n" 4092 "} // namespace out", 4093 Style)); 4094 EXPECT_EQ("TESTSUITE(out) {\n" 4095 "namespace in {\n" 4096 "} // namespace in\n" 4097 "} // TESTSUITE(out)", 4098 format("TESTSUITE(out) {\n" 4099 "namespace in {\n" 4100 "} // namespace in\n" 4101 "} // TESTSUITE(out)", 4102 Style)); 4103 Style.NamespaceMacros.push_back("FOOBAR"); 4104 EXPECT_EQ("TESTSUITE(out) {\n" 4105 "FOOBAR(in) {\n" 4106 "} // FOOBAR(in)\n" 4107 "} // TESTSUITE(out)", 4108 format("TESTSUITE(out) {\n" 4109 "FOOBAR(in) {\n" 4110 "} // FOOBAR(in)\n" 4111 "} // TESTSUITE(out)", 4112 Style)); 4113 } 4114 4115 TEST_F(FormatTest, FormatsCompactNamespaces) { 4116 FormatStyle Style = getLLVMStyle(); 4117 Style.CompactNamespaces = true; 4118 Style.NamespaceMacros.push_back("TESTSUITE"); 4119 4120 verifyFormat("namespace A { namespace B {\n" 4121 "}} // namespace A::B", 4122 Style); 4123 4124 EXPECT_EQ("namespace out { namespace in {\n" 4125 "}} // namespace out::in", 4126 format("namespace out {\n" 4127 "namespace in {\n" 4128 "} // namespace in\n" 4129 "} // namespace out", 4130 Style)); 4131 4132 // Only namespaces which have both consecutive opening and end get compacted 4133 EXPECT_EQ("namespace out {\n" 4134 "namespace in1 {\n" 4135 "} // namespace in1\n" 4136 "namespace in2 {\n" 4137 "} // namespace in2\n" 4138 "} // namespace out", 4139 format("namespace out {\n" 4140 "namespace in1 {\n" 4141 "} // namespace in1\n" 4142 "namespace in2 {\n" 4143 "} // namespace in2\n" 4144 "} // namespace out", 4145 Style)); 4146 4147 EXPECT_EQ("namespace out {\n" 4148 "int i;\n" 4149 "namespace in {\n" 4150 "int j;\n" 4151 "} // namespace in\n" 4152 "int k;\n" 4153 "} // namespace out", 4154 format("namespace out { int i;\n" 4155 "namespace in { int j; } // namespace in\n" 4156 "int k; } // namespace out", 4157 Style)); 4158 4159 EXPECT_EQ("namespace A { namespace B { namespace C {\n" 4160 "}}} // namespace A::B::C\n", 4161 format("namespace A { namespace B {\n" 4162 "namespace C {\n" 4163 "}} // namespace B::C\n" 4164 "} // namespace A\n", 4165 Style)); 4166 4167 Style.ColumnLimit = 40; 4168 EXPECT_EQ("namespace aaaaaaaaaa {\n" 4169 "namespace bbbbbbbbbb {\n" 4170 "}} // namespace aaaaaaaaaa::bbbbbbbbbb", 4171 format("namespace aaaaaaaaaa {\n" 4172 "namespace bbbbbbbbbb {\n" 4173 "} // namespace bbbbbbbbbb\n" 4174 "} // namespace aaaaaaaaaa", 4175 Style)); 4176 4177 EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n" 4178 "namespace cccccc {\n" 4179 "}}} // namespace aaaaaa::bbbbbb::cccccc", 4180 format("namespace aaaaaa {\n" 4181 "namespace bbbbbb {\n" 4182 "namespace cccccc {\n" 4183 "} // namespace cccccc\n" 4184 "} // namespace bbbbbb\n" 4185 "} // namespace aaaaaa", 4186 Style)); 4187 Style.ColumnLimit = 80; 4188 4189 // Extra semicolon after 'inner' closing brace prevents merging 4190 EXPECT_EQ("namespace out { namespace in {\n" 4191 "}; } // namespace out::in", 4192 format("namespace out {\n" 4193 "namespace in {\n" 4194 "}; // namespace in\n" 4195 "} // namespace out", 4196 Style)); 4197 4198 // Extra semicolon after 'outer' closing brace is conserved 4199 EXPECT_EQ("namespace out { namespace in {\n" 4200 "}}; // namespace out::in", 4201 format("namespace out {\n" 4202 "namespace in {\n" 4203 "} // namespace in\n" 4204 "}; // namespace out", 4205 Style)); 4206 4207 Style.NamespaceIndentation = FormatStyle::NI_All; 4208 EXPECT_EQ("namespace out { namespace in {\n" 4209 " int i;\n" 4210 "}} // namespace out::in", 4211 format("namespace out {\n" 4212 "namespace in {\n" 4213 "int i;\n" 4214 "} // namespace in\n" 4215 "} // namespace out", 4216 Style)); 4217 EXPECT_EQ("namespace out { namespace mid {\n" 4218 " namespace in {\n" 4219 " int j;\n" 4220 " } // namespace in\n" 4221 " int k;\n" 4222 "}} // namespace out::mid", 4223 format("namespace out { namespace mid {\n" 4224 "namespace in { int j; } // namespace in\n" 4225 "int k; }} // namespace out::mid", 4226 Style)); 4227 4228 Style.NamespaceIndentation = FormatStyle::NI_Inner; 4229 EXPECT_EQ("namespace out { namespace in {\n" 4230 " int i;\n" 4231 "}} // namespace out::in", 4232 format("namespace out {\n" 4233 "namespace in {\n" 4234 "int i;\n" 4235 "} // namespace in\n" 4236 "} // namespace out", 4237 Style)); 4238 EXPECT_EQ("namespace out { namespace mid { namespace in {\n" 4239 " int i;\n" 4240 "}}} // namespace out::mid::in", 4241 format("namespace out {\n" 4242 "namespace mid {\n" 4243 "namespace in {\n" 4244 "int i;\n" 4245 "} // namespace in\n" 4246 "} // namespace mid\n" 4247 "} // namespace out", 4248 Style)); 4249 4250 Style.CompactNamespaces = true; 4251 Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 4252 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4253 Style.BraceWrapping.BeforeLambdaBody = true; 4254 verifyFormat("namespace out { namespace in {\n" 4255 "}} // namespace out::in", 4256 Style); 4257 EXPECT_EQ("namespace out { namespace in {\n" 4258 "}} // namespace out::in", 4259 format("namespace out {\n" 4260 "namespace in {\n" 4261 "} // namespace in\n" 4262 "} // namespace out", 4263 Style)); 4264 } 4265 4266 TEST_F(FormatTest, FormatsExternC) { 4267 verifyFormat("extern \"C\" {\nint a;"); 4268 verifyFormat("extern \"C\" {}"); 4269 verifyFormat("extern \"C\" {\n" 4270 "int foo();\n" 4271 "}"); 4272 verifyFormat("extern \"C\" int foo() {}"); 4273 verifyFormat("extern \"C\" int foo();"); 4274 verifyFormat("extern \"C\" int foo() {\n" 4275 " int i = 42;\n" 4276 " return i;\n" 4277 "}"); 4278 4279 FormatStyle Style = getLLVMStyle(); 4280 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4281 Style.BraceWrapping.AfterFunction = true; 4282 verifyFormat("extern \"C\" int foo() {}", Style); 4283 verifyFormat("extern \"C\" int foo();", Style); 4284 verifyFormat("extern \"C\" int foo()\n" 4285 "{\n" 4286 " int i = 42;\n" 4287 " return i;\n" 4288 "}", 4289 Style); 4290 4291 Style.BraceWrapping.AfterExternBlock = true; 4292 Style.BraceWrapping.SplitEmptyRecord = false; 4293 verifyFormat("extern \"C\"\n" 4294 "{}", 4295 Style); 4296 verifyFormat("extern \"C\"\n" 4297 "{\n" 4298 " int foo();\n" 4299 "}", 4300 Style); 4301 } 4302 4303 TEST_F(FormatTest, IndentExternBlockStyle) { 4304 FormatStyle Style = getLLVMStyle(); 4305 Style.IndentWidth = 2; 4306 4307 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4308 verifyFormat("extern \"C\" { /*9*/\n" 4309 "}", 4310 Style); 4311 verifyFormat("extern \"C\" {\n" 4312 " int foo10();\n" 4313 "}", 4314 Style); 4315 4316 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 4317 verifyFormat("extern \"C\" { /*11*/\n" 4318 "}", 4319 Style); 4320 verifyFormat("extern \"C\" {\n" 4321 "int foo12();\n" 4322 "}", 4323 Style); 4324 4325 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4326 Style.BraceWrapping.AfterExternBlock = true; 4327 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4328 verifyFormat("extern \"C\"\n" 4329 "{ /*13*/\n" 4330 "}", 4331 Style); 4332 verifyFormat("extern \"C\"\n{\n" 4333 " int foo14();\n" 4334 "}", 4335 Style); 4336 4337 Style.BraceWrapping.AfterExternBlock = false; 4338 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 4339 verifyFormat("extern \"C\" { /*15*/\n" 4340 "}", 4341 Style); 4342 verifyFormat("extern \"C\" {\n" 4343 "int foo16();\n" 4344 "}", 4345 Style); 4346 4347 Style.BraceWrapping.AfterExternBlock = true; 4348 verifyFormat("extern \"C\"\n" 4349 "{ /*13*/\n" 4350 "}", 4351 Style); 4352 verifyFormat("extern \"C\"\n" 4353 "{\n" 4354 "int foo14();\n" 4355 "}", 4356 Style); 4357 4358 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4359 verifyFormat("extern \"C\"\n" 4360 "{ /*13*/\n" 4361 "}", 4362 Style); 4363 verifyFormat("extern \"C\"\n" 4364 "{\n" 4365 " int foo14();\n" 4366 "}", 4367 Style); 4368 } 4369 4370 TEST_F(FormatTest, FormatsInlineASM) { 4371 verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));"); 4372 verifyFormat("asm(\"nop\" ::: \"memory\");"); 4373 verifyFormat( 4374 "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n" 4375 " \"cpuid\\n\\t\"\n" 4376 " \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n" 4377 " : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n" 4378 " : \"a\"(value));"); 4379 EXPECT_EQ( 4380 "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n" 4381 " __asm {\n" 4382 " mov edx,[that] // vtable in edx\n" 4383 " mov eax,methodIndex\n" 4384 " call [edx][eax*4] // stdcall\n" 4385 " }\n" 4386 "}", 4387 format("void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n" 4388 " __asm {\n" 4389 " mov edx,[that] // vtable in edx\n" 4390 " mov eax,methodIndex\n" 4391 " call [edx][eax*4] // stdcall\n" 4392 " }\n" 4393 "}")); 4394 EXPECT_EQ("_asm {\n" 4395 " xor eax, eax;\n" 4396 " cpuid;\n" 4397 "}", 4398 format("_asm {\n" 4399 " xor eax, eax;\n" 4400 " cpuid;\n" 4401 "}")); 4402 verifyFormat("void function() {\n" 4403 " // comment\n" 4404 " asm(\"\");\n" 4405 "}"); 4406 EXPECT_EQ("__asm {\n" 4407 "}\n" 4408 "int i;", 4409 format("__asm {\n" 4410 "}\n" 4411 "int i;")); 4412 } 4413 4414 TEST_F(FormatTest, FormatTryCatch) { 4415 verifyFormat("try {\n" 4416 " throw a * b;\n" 4417 "} catch (int a) {\n" 4418 " // Do nothing.\n" 4419 "} catch (...) {\n" 4420 " exit(42);\n" 4421 "}"); 4422 4423 // Function-level try statements. 4424 verifyFormat("int f() try { return 4; } catch (...) {\n" 4425 " return 5;\n" 4426 "}"); 4427 verifyFormat("class A {\n" 4428 " int a;\n" 4429 " A() try : a(0) {\n" 4430 " } catch (...) {\n" 4431 " throw;\n" 4432 " }\n" 4433 "};\n"); 4434 verifyFormat("class A {\n" 4435 " int a;\n" 4436 " A() try : a(0), b{1} {\n" 4437 " } catch (...) {\n" 4438 " throw;\n" 4439 " }\n" 4440 "};\n"); 4441 verifyFormat("class A {\n" 4442 " int a;\n" 4443 " A() try : a(0), b{1}, c{2} {\n" 4444 " } catch (...) {\n" 4445 " throw;\n" 4446 " }\n" 4447 "};\n"); 4448 verifyFormat("class A {\n" 4449 " int a;\n" 4450 " A() try : a(0), b{1}, c{2} {\n" 4451 " { // New scope.\n" 4452 " }\n" 4453 " } catch (...) {\n" 4454 " throw;\n" 4455 " }\n" 4456 "};\n"); 4457 4458 // Incomplete try-catch blocks. 4459 verifyIncompleteFormat("try {} catch ("); 4460 } 4461 4462 TEST_F(FormatTest, FormatTryAsAVariable) { 4463 verifyFormat("int try;"); 4464 verifyFormat("int try, size;"); 4465 verifyFormat("try = foo();"); 4466 verifyFormat("if (try < size) {\n return true;\n}"); 4467 4468 verifyFormat("int catch;"); 4469 verifyFormat("int catch, size;"); 4470 verifyFormat("catch = foo();"); 4471 verifyFormat("if (catch < size) {\n return true;\n}"); 4472 4473 FormatStyle Style = getLLVMStyle(); 4474 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4475 Style.BraceWrapping.AfterFunction = true; 4476 Style.BraceWrapping.BeforeCatch = true; 4477 verifyFormat("try {\n" 4478 " int bar = 1;\n" 4479 "}\n" 4480 "catch (...) {\n" 4481 " int bar = 1;\n" 4482 "}", 4483 Style); 4484 verifyFormat("#if NO_EX\n" 4485 "try\n" 4486 "#endif\n" 4487 "{\n" 4488 "}\n" 4489 "#if NO_EX\n" 4490 "catch (...) {\n" 4491 "}", 4492 Style); 4493 verifyFormat("try /* abc */ {\n" 4494 " int bar = 1;\n" 4495 "}\n" 4496 "catch (...) {\n" 4497 " int bar = 1;\n" 4498 "}", 4499 Style); 4500 verifyFormat("try\n" 4501 "// abc\n" 4502 "{\n" 4503 " int bar = 1;\n" 4504 "}\n" 4505 "catch (...) {\n" 4506 " int bar = 1;\n" 4507 "}", 4508 Style); 4509 } 4510 4511 TEST_F(FormatTest, FormatSEHTryCatch) { 4512 verifyFormat("__try {\n" 4513 " int a = b * c;\n" 4514 "} __except (EXCEPTION_EXECUTE_HANDLER) {\n" 4515 " // Do nothing.\n" 4516 "}"); 4517 4518 verifyFormat("__try {\n" 4519 " int a = b * c;\n" 4520 "} __finally {\n" 4521 " // Do nothing.\n" 4522 "}"); 4523 4524 verifyFormat("DEBUG({\n" 4525 " __try {\n" 4526 " } __finally {\n" 4527 " }\n" 4528 "});\n"); 4529 } 4530 4531 TEST_F(FormatTest, IncompleteTryCatchBlocks) { 4532 verifyFormat("try {\n" 4533 " f();\n" 4534 "} catch {\n" 4535 " g();\n" 4536 "}"); 4537 verifyFormat("try {\n" 4538 " f();\n" 4539 "} catch (A a) MACRO(x) {\n" 4540 " g();\n" 4541 "} catch (B b) MACRO(x) {\n" 4542 " g();\n" 4543 "}"); 4544 } 4545 4546 TEST_F(FormatTest, FormatTryCatchBraceStyles) { 4547 FormatStyle Style = getLLVMStyle(); 4548 for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla, 4549 FormatStyle::BS_WebKit}) { 4550 Style.BreakBeforeBraces = BraceStyle; 4551 verifyFormat("try {\n" 4552 " // something\n" 4553 "} catch (...) {\n" 4554 " // something\n" 4555 "}", 4556 Style); 4557 } 4558 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 4559 verifyFormat("try {\n" 4560 " // something\n" 4561 "}\n" 4562 "catch (...) {\n" 4563 " // something\n" 4564 "}", 4565 Style); 4566 verifyFormat("__try {\n" 4567 " // something\n" 4568 "}\n" 4569 "__finally {\n" 4570 " // something\n" 4571 "}", 4572 Style); 4573 verifyFormat("@try {\n" 4574 " // something\n" 4575 "}\n" 4576 "@finally {\n" 4577 " // something\n" 4578 "}", 4579 Style); 4580 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 4581 verifyFormat("try\n" 4582 "{\n" 4583 " // something\n" 4584 "}\n" 4585 "catch (...)\n" 4586 "{\n" 4587 " // something\n" 4588 "}", 4589 Style); 4590 Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 4591 verifyFormat("try\n" 4592 " {\n" 4593 " // something white\n" 4594 " }\n" 4595 "catch (...)\n" 4596 " {\n" 4597 " // something white\n" 4598 " }", 4599 Style); 4600 Style.BreakBeforeBraces = FormatStyle::BS_GNU; 4601 verifyFormat("try\n" 4602 " {\n" 4603 " // something\n" 4604 " }\n" 4605 "catch (...)\n" 4606 " {\n" 4607 " // something\n" 4608 " }", 4609 Style); 4610 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4611 Style.BraceWrapping.BeforeCatch = true; 4612 verifyFormat("try {\n" 4613 " // something\n" 4614 "}\n" 4615 "catch (...) {\n" 4616 " // something\n" 4617 "}", 4618 Style); 4619 } 4620 4621 TEST_F(FormatTest, StaticInitializers) { 4622 verifyFormat("static SomeClass SC = {1, 'a'};"); 4623 4624 verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n" 4625 " 100000000, " 4626 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};"); 4627 4628 // Here, everything other than the "}" would fit on a line. 4629 verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n" 4630 " 10000000000000000000000000};"); 4631 EXPECT_EQ("S s = {a,\n" 4632 "\n" 4633 " b};", 4634 format("S s = {\n" 4635 " a,\n" 4636 "\n" 4637 " b\n" 4638 "};")); 4639 4640 // FIXME: This would fit into the column limit if we'd fit "{ {" on the first 4641 // line. However, the formatting looks a bit off and this probably doesn't 4642 // happen often in practice. 4643 verifyFormat("static int Variable[1] = {\n" 4644 " {1000000000000000000000000000000000000}};", 4645 getLLVMStyleWithColumns(40)); 4646 } 4647 4648 TEST_F(FormatTest, DesignatedInitializers) { 4649 verifyFormat("const struct A a = {.a = 1, .b = 2};"); 4650 verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n" 4651 " .bbbbbbbbbb = 2,\n" 4652 " .cccccccccc = 3,\n" 4653 " .dddddddddd = 4,\n" 4654 " .eeeeeeeeee = 5};"); 4655 verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n" 4656 " .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n" 4657 " .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n" 4658 " .ccccccccccccccccccccccccccc = 3,\n" 4659 " .ddddddddddddddddddddddddddd = 4,\n" 4660 " .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};"); 4661 4662 verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};"); 4663 4664 verifyFormat("const struct A a = {[0] = 1, [1] = 2};"); 4665 verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n" 4666 " [2] = bbbbbbbbbb,\n" 4667 " [3] = cccccccccc,\n" 4668 " [4] = dddddddddd,\n" 4669 " [5] = eeeeeeeeee};"); 4670 verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n" 4671 " [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 4672 " [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 4673 " [3] = cccccccccccccccccccccccccccccccccccccc,\n" 4674 " [4] = dddddddddddddddddddddddddddddddddddddd,\n" 4675 " [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};"); 4676 } 4677 4678 TEST_F(FormatTest, NestedStaticInitializers) { 4679 verifyFormat("static A x = {{{}}};\n"); 4680 verifyFormat("static A x = {{{init1, init2, init3, init4},\n" 4681 " {init1, init2, init3, init4}}};", 4682 getLLVMStyleWithColumns(50)); 4683 4684 verifyFormat("somes Status::global_reps[3] = {\n" 4685 " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n" 4686 " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n" 4687 " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};", 4688 getLLVMStyleWithColumns(60)); 4689 verifyGoogleFormat("SomeType Status::global_reps[3] = {\n" 4690 " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n" 4691 " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n" 4692 " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};"); 4693 verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n" 4694 " {rect.fRight - rect.fLeft, rect.fBottom - " 4695 "rect.fTop}};"); 4696 4697 verifyFormat( 4698 "SomeArrayOfSomeType a = {\n" 4699 " {{1, 2, 3},\n" 4700 " {1, 2, 3},\n" 4701 " {111111111111111111111111111111, 222222222222222222222222222222,\n" 4702 " 333333333333333333333333333333},\n" 4703 " {1, 2, 3},\n" 4704 " {1, 2, 3}}};"); 4705 verifyFormat( 4706 "SomeArrayOfSomeType a = {\n" 4707 " {{1, 2, 3}},\n" 4708 " {{1, 2, 3}},\n" 4709 " {{111111111111111111111111111111, 222222222222222222222222222222,\n" 4710 " 333333333333333333333333333333}},\n" 4711 " {{1, 2, 3}},\n" 4712 " {{1, 2, 3}}};"); 4713 4714 verifyFormat("struct {\n" 4715 " unsigned bit;\n" 4716 " const char *const name;\n" 4717 "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n" 4718 " {kOsWin, \"Windows\"},\n" 4719 " {kOsLinux, \"Linux\"},\n" 4720 " {kOsCrOS, \"Chrome OS\"}};"); 4721 verifyFormat("struct {\n" 4722 " unsigned bit;\n" 4723 " const char *const name;\n" 4724 "} kBitsToOs[] = {\n" 4725 " {kOsMac, \"Mac\"},\n" 4726 " {kOsWin, \"Windows\"},\n" 4727 " {kOsLinux, \"Linux\"},\n" 4728 " {kOsCrOS, \"Chrome OS\"},\n" 4729 "};"); 4730 } 4731 4732 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) { 4733 verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro(" 4734 " \\\n" 4735 " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)"); 4736 } 4737 4738 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) { 4739 verifyFormat("virtual void write(ELFWriter *writerrr,\n" 4740 " OwningPtr<FileOutputBuffer> &buffer) = 0;"); 4741 4742 // Do break defaulted and deleted functions. 4743 verifyFormat("virtual void ~Deeeeeeeestructor() =\n" 4744 " default;", 4745 getLLVMStyleWithColumns(40)); 4746 verifyFormat("virtual void ~Deeeeeeeestructor() =\n" 4747 " delete;", 4748 getLLVMStyleWithColumns(40)); 4749 } 4750 4751 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) { 4752 verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3", 4753 getLLVMStyleWithColumns(40)); 4754 verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"", 4755 getLLVMStyleWithColumns(40)); 4756 EXPECT_EQ("#define Q \\\n" 4757 " \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\" \\\n" 4758 " \"aaaaaaaa.cpp\"", 4759 format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"", 4760 getLLVMStyleWithColumns(40))); 4761 } 4762 4763 TEST_F(FormatTest, UnderstandsLinePPDirective) { 4764 EXPECT_EQ("# 123 \"A string literal\"", 4765 format(" # 123 \"A string literal\"")); 4766 } 4767 4768 TEST_F(FormatTest, LayoutUnknownPPDirective) { 4769 EXPECT_EQ("#;", format("#;")); 4770 verifyFormat("#\n;\n;\n;"); 4771 } 4772 4773 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) { 4774 EXPECT_EQ("#line 42 \"test\"\n", 4775 format("# \\\n line \\\n 42 \\\n \"test\"\n")); 4776 EXPECT_EQ("#define A B\n", format("# \\\n define \\\n A \\\n B\n", 4777 getLLVMStyleWithColumns(12))); 4778 } 4779 4780 TEST_F(FormatTest, EndOfFileEndsPPDirective) { 4781 EXPECT_EQ("#line 42 \"test\"", 4782 format("# \\\n line \\\n 42 \\\n \"test\"")); 4783 EXPECT_EQ("#define A B", format("# \\\n define \\\n A \\\n B")); 4784 } 4785 4786 TEST_F(FormatTest, DoesntRemoveUnknownTokens) { 4787 verifyFormat("#define A \\x20"); 4788 verifyFormat("#define A \\ x20"); 4789 EXPECT_EQ("#define A \\ x20", format("#define A \\ x20")); 4790 verifyFormat("#define A ''"); 4791 verifyFormat("#define A ''qqq"); 4792 verifyFormat("#define A `qqq"); 4793 verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");"); 4794 EXPECT_EQ("const char *c = STRINGIFY(\n" 4795 "\\na : b);", 4796 format("const char * c = STRINGIFY(\n" 4797 "\\na : b);")); 4798 4799 verifyFormat("a\r\\"); 4800 verifyFormat("a\v\\"); 4801 verifyFormat("a\f\\"); 4802 } 4803 4804 TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) { 4805 FormatStyle style = getChromiumStyle(FormatStyle::LK_Cpp); 4806 style.IndentWidth = 4; 4807 style.PPIndentWidth = 1; 4808 4809 style.IndentPPDirectives = FormatStyle::PPDIS_None; 4810 verifyFormat("#ifdef __linux__\n" 4811 "void foo() {\n" 4812 " int x = 0;\n" 4813 "}\n" 4814 "#define FOO\n" 4815 "#endif\n" 4816 "void bar() {\n" 4817 " int y = 0;\n" 4818 "}\n", 4819 style); 4820 4821 style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash; 4822 verifyFormat("#ifdef __linux__\n" 4823 "void foo() {\n" 4824 " int x = 0;\n" 4825 "}\n" 4826 "# define FOO foo\n" 4827 "#endif\n" 4828 "void bar() {\n" 4829 " int y = 0;\n" 4830 "}\n", 4831 style); 4832 4833 style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash; 4834 verifyFormat("#ifdef __linux__\n" 4835 "void foo() {\n" 4836 " int x = 0;\n" 4837 "}\n" 4838 " #define FOO foo\n" 4839 "#endif\n" 4840 "void bar() {\n" 4841 " int y = 0;\n" 4842 "}\n", 4843 style); 4844 } 4845 4846 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) { 4847 verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13)); 4848 verifyFormat("#define A( \\\n BB)", getLLVMStyleWithColumns(12)); 4849 verifyFormat("#define A( \\\n A, B)", getLLVMStyleWithColumns(12)); 4850 // FIXME: We never break before the macro name. 4851 verifyFormat("#define AA( \\\n B)", getLLVMStyleWithColumns(12)); 4852 4853 verifyFormat("#define A A\n#define A A"); 4854 verifyFormat("#define A(X) A\n#define A A"); 4855 4856 verifyFormat("#define Something Other", getLLVMStyleWithColumns(23)); 4857 verifyFormat("#define Something \\\n Other", getLLVMStyleWithColumns(22)); 4858 } 4859 4860 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) { 4861 EXPECT_EQ("// somecomment\n" 4862 "#include \"a.h\"\n" 4863 "#define A( \\\n" 4864 " A, B)\n" 4865 "#include \"b.h\"\n" 4866 "// somecomment\n", 4867 format(" // somecomment\n" 4868 " #include \"a.h\"\n" 4869 "#define A(A,\\\n" 4870 " B)\n" 4871 " #include \"b.h\"\n" 4872 " // somecomment\n", 4873 getLLVMStyleWithColumns(13))); 4874 } 4875 4876 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); } 4877 4878 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) { 4879 EXPECT_EQ("#define A \\\n" 4880 " c; \\\n" 4881 " e;\n" 4882 "f;", 4883 format("#define A c; e;\n" 4884 "f;", 4885 getLLVMStyleWithColumns(14))); 4886 } 4887 4888 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); } 4889 4890 TEST_F(FormatTest, MacroDefinitionInsideStatement) { 4891 EXPECT_EQ("int x,\n" 4892 "#define A\n" 4893 " y;", 4894 format("int x,\n#define A\ny;")); 4895 } 4896 4897 TEST_F(FormatTest, HashInMacroDefinition) { 4898 EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle())); 4899 EXPECT_EQ("#define A(c) u#c", format("#define A(c) u#c", getLLVMStyle())); 4900 EXPECT_EQ("#define A(c) U#c", format("#define A(c) U#c", getLLVMStyle())); 4901 EXPECT_EQ("#define A(c) u8#c", format("#define A(c) u8#c", getLLVMStyle())); 4902 EXPECT_EQ("#define A(c) LR#c", format("#define A(c) LR#c", getLLVMStyle())); 4903 EXPECT_EQ("#define A(c) uR#c", format("#define A(c) uR#c", getLLVMStyle())); 4904 EXPECT_EQ("#define A(c) UR#c", format("#define A(c) UR#c", getLLVMStyle())); 4905 EXPECT_EQ("#define A(c) u8R#c", format("#define A(c) u8R#c", getLLVMStyle())); 4906 verifyFormat("#define A \\\n b #c;", getLLVMStyleWithColumns(11)); 4907 verifyFormat("#define A \\\n" 4908 " { \\\n" 4909 " f(#c); \\\n" 4910 " }", 4911 getLLVMStyleWithColumns(11)); 4912 4913 verifyFormat("#define A(X) \\\n" 4914 " void function##X()", 4915 getLLVMStyleWithColumns(22)); 4916 4917 verifyFormat("#define A(a, b, c) \\\n" 4918 " void a##b##c()", 4919 getLLVMStyleWithColumns(22)); 4920 4921 verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22)); 4922 } 4923 4924 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) { 4925 EXPECT_EQ("#define A (x)", format("#define A (x)")); 4926 EXPECT_EQ("#define A(x)", format("#define A(x)")); 4927 4928 FormatStyle Style = getLLVMStyle(); 4929 Style.SpaceBeforeParens = FormatStyle::SBPO_Never; 4930 verifyFormat("#define true ((foo)1)", Style); 4931 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 4932 verifyFormat("#define false((foo)0)", Style); 4933 } 4934 4935 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) { 4936 EXPECT_EQ("#define A b;", format("#define A \\\n" 4937 " \\\n" 4938 " b;", 4939 getLLVMStyleWithColumns(25))); 4940 EXPECT_EQ("#define A \\\n" 4941 " \\\n" 4942 " a; \\\n" 4943 " b;", 4944 format("#define A \\\n" 4945 " \\\n" 4946 " a; \\\n" 4947 " b;", 4948 getLLVMStyleWithColumns(11))); 4949 EXPECT_EQ("#define A \\\n" 4950 " a; \\\n" 4951 " \\\n" 4952 " b;", 4953 format("#define A \\\n" 4954 " a; \\\n" 4955 " \\\n" 4956 " b;", 4957 getLLVMStyleWithColumns(11))); 4958 } 4959 4960 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) { 4961 verifyIncompleteFormat("#define A :"); 4962 verifyFormat("#define SOMECASES \\\n" 4963 " case 1: \\\n" 4964 " case 2\n", 4965 getLLVMStyleWithColumns(20)); 4966 verifyFormat("#define MACRO(a) \\\n" 4967 " if (a) \\\n" 4968 " f(); \\\n" 4969 " else \\\n" 4970 " g()", 4971 getLLVMStyleWithColumns(18)); 4972 verifyFormat("#define A template <typename T>"); 4973 verifyIncompleteFormat("#define STR(x) #x\n" 4974 "f(STR(this_is_a_string_literal{));"); 4975 verifyFormat("#pragma omp threadprivate( \\\n" 4976 " y)), // expected-warning", 4977 getLLVMStyleWithColumns(28)); 4978 verifyFormat("#d, = };"); 4979 verifyFormat("#if \"a"); 4980 verifyIncompleteFormat("({\n" 4981 "#define b \\\n" 4982 " } \\\n" 4983 " a\n" 4984 "a", 4985 getLLVMStyleWithColumns(15)); 4986 verifyFormat("#define A \\\n" 4987 " { \\\n" 4988 " {\n" 4989 "#define B \\\n" 4990 " } \\\n" 4991 " }", 4992 getLLVMStyleWithColumns(15)); 4993 verifyNoCrash("#if a\na(\n#else\n#endif\n{a"); 4994 verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}"); 4995 verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};"); 4996 verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() { \n)}"); 4997 } 4998 4999 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) { 5000 verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline. 5001 EXPECT_EQ("class A : public QObject {\n" 5002 " Q_OBJECT\n" 5003 "\n" 5004 " A() {}\n" 5005 "};", 5006 format("class A : public QObject {\n" 5007 " Q_OBJECT\n" 5008 "\n" 5009 " A() {\n}\n" 5010 "} ;")); 5011 EXPECT_EQ("MACRO\n" 5012 "/*static*/ int i;", 5013 format("MACRO\n" 5014 " /*static*/ int i;")); 5015 EXPECT_EQ("SOME_MACRO\n" 5016 "namespace {\n" 5017 "void f();\n" 5018 "} // namespace", 5019 format("SOME_MACRO\n" 5020 " namespace {\n" 5021 "void f( );\n" 5022 "} // namespace")); 5023 // Only if the identifier contains at least 5 characters. 5024 EXPECT_EQ("HTTP f();", format("HTTP\nf();")); 5025 EXPECT_EQ("MACRO\nf();", format("MACRO\nf();")); 5026 // Only if everything is upper case. 5027 EXPECT_EQ("class A : public QObject {\n" 5028 " Q_Object A() {}\n" 5029 "};", 5030 format("class A : public QObject {\n" 5031 " Q_Object\n" 5032 " A() {\n}\n" 5033 "} ;")); 5034 5035 // Only if the next line can actually start an unwrapped line. 5036 EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;", 5037 format("SOME_WEIRD_LOG_MACRO\n" 5038 "<< SomeThing;")); 5039 5040 verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), " 5041 "(n, buffers))\n", 5042 getChromiumStyle(FormatStyle::LK_Cpp)); 5043 5044 // See PR41483 5045 EXPECT_EQ("/**/ FOO(a)\n" 5046 "FOO(b)", 5047 format("/**/ FOO(a)\n" 5048 "FOO(b)")); 5049 } 5050 5051 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) { 5052 EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n" 5053 "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n" 5054 "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n" 5055 "class X {};\n" 5056 "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n" 5057 "int *createScopDetectionPass() { return 0; }", 5058 format(" INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n" 5059 " INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n" 5060 " INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n" 5061 " class X {};\n" 5062 " INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n" 5063 " int *createScopDetectionPass() { return 0; }")); 5064 // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as 5065 // braces, so that inner block is indented one level more. 5066 EXPECT_EQ("int q() {\n" 5067 " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n" 5068 " IPC_MESSAGE_HANDLER(xxx, qqq)\n" 5069 " IPC_END_MESSAGE_MAP()\n" 5070 "}", 5071 format("int q() {\n" 5072 " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n" 5073 " IPC_MESSAGE_HANDLER(xxx, qqq)\n" 5074 " IPC_END_MESSAGE_MAP()\n" 5075 "}")); 5076 5077 // Same inside macros. 5078 EXPECT_EQ("#define LIST(L) \\\n" 5079 " L(A) \\\n" 5080 " L(B) \\\n" 5081 " L(C)", 5082 format("#define LIST(L) \\\n" 5083 " L(A) \\\n" 5084 " L(B) \\\n" 5085 " L(C)", 5086 getGoogleStyle())); 5087 5088 // These must not be recognized as macros. 5089 EXPECT_EQ("int q() {\n" 5090 " f(x);\n" 5091 " f(x) {}\n" 5092 " f(x)->g();\n" 5093 " f(x)->*g();\n" 5094 " f(x).g();\n" 5095 " f(x) = x;\n" 5096 " f(x) += x;\n" 5097 " f(x) -= x;\n" 5098 " f(x) *= x;\n" 5099 " f(x) /= x;\n" 5100 " f(x) %= x;\n" 5101 " f(x) &= x;\n" 5102 " f(x) |= x;\n" 5103 " f(x) ^= x;\n" 5104 " f(x) >>= x;\n" 5105 " f(x) <<= x;\n" 5106 " f(x)[y].z();\n" 5107 " LOG(INFO) << x;\n" 5108 " ifstream(x) >> x;\n" 5109 "}\n", 5110 format("int q() {\n" 5111 " f(x)\n;\n" 5112 " f(x)\n {}\n" 5113 " f(x)\n->g();\n" 5114 " f(x)\n->*g();\n" 5115 " f(x)\n.g();\n" 5116 " f(x)\n = x;\n" 5117 " f(x)\n += x;\n" 5118 " f(x)\n -= x;\n" 5119 " f(x)\n *= x;\n" 5120 " f(x)\n /= x;\n" 5121 " f(x)\n %= x;\n" 5122 " f(x)\n &= x;\n" 5123 " f(x)\n |= x;\n" 5124 " f(x)\n ^= x;\n" 5125 " f(x)\n >>= x;\n" 5126 " f(x)\n <<= x;\n" 5127 " f(x)\n[y].z();\n" 5128 " LOG(INFO)\n << x;\n" 5129 " ifstream(x)\n >> x;\n" 5130 "}\n")); 5131 EXPECT_EQ("int q() {\n" 5132 " F(x)\n" 5133 " if (1) {\n" 5134 " }\n" 5135 " F(x)\n" 5136 " while (1) {\n" 5137 " }\n" 5138 " F(x)\n" 5139 " G(x);\n" 5140 " F(x)\n" 5141 " try {\n" 5142 " Q();\n" 5143 " } catch (...) {\n" 5144 " }\n" 5145 "}\n", 5146 format("int q() {\n" 5147 "F(x)\n" 5148 "if (1) {}\n" 5149 "F(x)\n" 5150 "while (1) {}\n" 5151 "F(x)\n" 5152 "G(x);\n" 5153 "F(x)\n" 5154 "try { Q(); } catch (...) {}\n" 5155 "}\n")); 5156 EXPECT_EQ("class A {\n" 5157 " A() : t(0) {}\n" 5158 " A(int i) noexcept() : {}\n" 5159 " A(X x)\n" // FIXME: function-level try blocks are broken. 5160 " try : t(0) {\n" 5161 " } catch (...) {\n" 5162 " }\n" 5163 "};", 5164 format("class A {\n" 5165 " A()\n : t(0) {}\n" 5166 " A(int i)\n noexcept() : {}\n" 5167 " A(X x)\n" 5168 " try : t(0) {} catch (...) {}\n" 5169 "};")); 5170 FormatStyle Style = getLLVMStyle(); 5171 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 5172 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 5173 Style.BraceWrapping.AfterFunction = true; 5174 EXPECT_EQ("void f()\n" 5175 "try\n" 5176 "{\n" 5177 "}", 5178 format("void f() try {\n" 5179 "}", 5180 Style)); 5181 EXPECT_EQ("class SomeClass {\n" 5182 "public:\n" 5183 " SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5184 "};", 5185 format("class SomeClass {\n" 5186 "public:\n" 5187 " SomeClass()\n" 5188 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5189 "};")); 5190 EXPECT_EQ("class SomeClass {\n" 5191 "public:\n" 5192 " SomeClass()\n" 5193 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5194 "};", 5195 format("class SomeClass {\n" 5196 "public:\n" 5197 " SomeClass()\n" 5198 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5199 "};", 5200 getLLVMStyleWithColumns(40))); 5201 5202 verifyFormat("MACRO(>)"); 5203 5204 // Some macros contain an implicit semicolon. 5205 Style = getLLVMStyle(); 5206 Style.StatementMacros.push_back("FOO"); 5207 verifyFormat("FOO(a) int b = 0;"); 5208 verifyFormat("FOO(a)\n" 5209 "int b = 0;", 5210 Style); 5211 verifyFormat("FOO(a);\n" 5212 "int b = 0;", 5213 Style); 5214 verifyFormat("FOO(argc, argv, \"4.0.2\")\n" 5215 "int b = 0;", 5216 Style); 5217 verifyFormat("FOO()\n" 5218 "int b = 0;", 5219 Style); 5220 verifyFormat("FOO\n" 5221 "int b = 0;", 5222 Style); 5223 verifyFormat("void f() {\n" 5224 " FOO(a)\n" 5225 " return a;\n" 5226 "}", 5227 Style); 5228 verifyFormat("FOO(a)\n" 5229 "FOO(b)", 5230 Style); 5231 verifyFormat("int a = 0;\n" 5232 "FOO(b)\n" 5233 "int c = 0;", 5234 Style); 5235 verifyFormat("int a = 0;\n" 5236 "int x = FOO(a)\n" 5237 "int b = 0;", 5238 Style); 5239 verifyFormat("void foo(int a) { FOO(a) }\n" 5240 "uint32_t bar() {}", 5241 Style); 5242 } 5243 5244 TEST_F(FormatTest, FormatsMacrosWithZeroColumnWidth) { 5245 FormatStyle ZeroColumn = getLLVMStyleWithColumns(0); 5246 5247 verifyFormat("#define A LOOOOOOOOOOOOOOOOOOONG() LOOOOOOOOOOOOOOOOOOONG()", 5248 ZeroColumn); 5249 } 5250 5251 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) { 5252 verifyFormat("#define A \\\n" 5253 " f({ \\\n" 5254 " g(); \\\n" 5255 " });", 5256 getLLVMStyleWithColumns(11)); 5257 } 5258 5259 TEST_F(FormatTest, IndentPreprocessorDirectives) { 5260 FormatStyle Style = getLLVMStyleWithColumns(40); 5261 Style.IndentPPDirectives = FormatStyle::PPDIS_None; 5262 verifyFormat("#ifdef _WIN32\n" 5263 "#define A 0\n" 5264 "#ifdef VAR2\n" 5265 "#define B 1\n" 5266 "#include <someheader.h>\n" 5267 "#define MACRO \\\n" 5268 " some_very_long_func_aaaaaaaaaa();\n" 5269 "#endif\n" 5270 "#else\n" 5271 "#define A 1\n" 5272 "#endif", 5273 Style); 5274 Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash; 5275 verifyFormat("#ifdef _WIN32\n" 5276 "# define A 0\n" 5277 "# ifdef VAR2\n" 5278 "# define B 1\n" 5279 "# include <someheader.h>\n" 5280 "# define MACRO \\\n" 5281 " some_very_long_func_aaaaaaaaaa();\n" 5282 "# endif\n" 5283 "#else\n" 5284 "# define A 1\n" 5285 "#endif", 5286 Style); 5287 verifyFormat("#if A\n" 5288 "# define MACRO \\\n" 5289 " void a(int x) { \\\n" 5290 " b(); \\\n" 5291 " c(); \\\n" 5292 " d(); \\\n" 5293 " e(); \\\n" 5294 " f(); \\\n" 5295 " }\n" 5296 "#endif", 5297 Style); 5298 // Comments before include guard. 5299 verifyFormat("// file comment\n" 5300 "// file comment\n" 5301 "#ifndef HEADER_H\n" 5302 "#define HEADER_H\n" 5303 "code();\n" 5304 "#endif", 5305 Style); 5306 // Test with include guards. 5307 verifyFormat("#ifndef HEADER_H\n" 5308 "#define HEADER_H\n" 5309 "code();\n" 5310 "#endif", 5311 Style); 5312 // Include guards must have a #define with the same variable immediately 5313 // after #ifndef. 5314 verifyFormat("#ifndef NOT_GUARD\n" 5315 "# define FOO\n" 5316 "code();\n" 5317 "#endif", 5318 Style); 5319 5320 // Include guards must cover the entire file. 5321 verifyFormat("code();\n" 5322 "code();\n" 5323 "#ifndef NOT_GUARD\n" 5324 "# define NOT_GUARD\n" 5325 "code();\n" 5326 "#endif", 5327 Style); 5328 verifyFormat("#ifndef NOT_GUARD\n" 5329 "# define NOT_GUARD\n" 5330 "code();\n" 5331 "#endif\n" 5332 "code();", 5333 Style); 5334 // Test with trailing blank lines. 5335 verifyFormat("#ifndef HEADER_H\n" 5336 "#define HEADER_H\n" 5337 "code();\n" 5338 "#endif\n", 5339 Style); 5340 // Include guards don't have #else. 5341 verifyFormat("#ifndef NOT_GUARD\n" 5342 "# define NOT_GUARD\n" 5343 "code();\n" 5344 "#else\n" 5345 "#endif", 5346 Style); 5347 verifyFormat("#ifndef NOT_GUARD\n" 5348 "# define NOT_GUARD\n" 5349 "code();\n" 5350 "#elif FOO\n" 5351 "#endif", 5352 Style); 5353 // Non-identifier #define after potential include guard. 5354 verifyFormat("#ifndef FOO\n" 5355 "# define 1\n" 5356 "#endif\n", 5357 Style); 5358 // #if closes past last non-preprocessor line. 5359 verifyFormat("#ifndef FOO\n" 5360 "#define FOO\n" 5361 "#if 1\n" 5362 "int i;\n" 5363 "# define A 0\n" 5364 "#endif\n" 5365 "#endif\n", 5366 Style); 5367 // Don't crash if there is an #elif directive without a condition. 5368 verifyFormat("#if 1\n" 5369 "int x;\n" 5370 "#elif\n" 5371 "int y;\n" 5372 "#else\n" 5373 "int z;\n" 5374 "#endif", 5375 Style); 5376 // FIXME: This doesn't handle the case where there's code between the 5377 // #ifndef and #define but all other conditions hold. This is because when 5378 // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the 5379 // previous code line yet, so we can't detect it. 5380 EXPECT_EQ("#ifndef NOT_GUARD\n" 5381 "code();\n" 5382 "#define NOT_GUARD\n" 5383 "code();\n" 5384 "#endif", 5385 format("#ifndef NOT_GUARD\n" 5386 "code();\n" 5387 "# define NOT_GUARD\n" 5388 "code();\n" 5389 "#endif", 5390 Style)); 5391 // FIXME: This doesn't handle cases where legitimate preprocessor lines may 5392 // be outside an include guard. Examples are #pragma once and 5393 // #pragma GCC diagnostic, or anything else that does not change the meaning 5394 // of the file if it's included multiple times. 5395 EXPECT_EQ("#ifdef WIN32\n" 5396 "# pragma once\n" 5397 "#endif\n" 5398 "#ifndef HEADER_H\n" 5399 "# define HEADER_H\n" 5400 "code();\n" 5401 "#endif", 5402 format("#ifdef WIN32\n" 5403 "# pragma once\n" 5404 "#endif\n" 5405 "#ifndef HEADER_H\n" 5406 "#define HEADER_H\n" 5407 "code();\n" 5408 "#endif", 5409 Style)); 5410 // FIXME: This does not detect when there is a single non-preprocessor line 5411 // in front of an include-guard-like structure where other conditions hold 5412 // because ScopedLineState hides the line. 5413 EXPECT_EQ("code();\n" 5414 "#ifndef HEADER_H\n" 5415 "#define HEADER_H\n" 5416 "code();\n" 5417 "#endif", 5418 format("code();\n" 5419 "#ifndef HEADER_H\n" 5420 "# define HEADER_H\n" 5421 "code();\n" 5422 "#endif", 5423 Style)); 5424 // Keep comments aligned with #, otherwise indent comments normally. These 5425 // tests cannot use verifyFormat because messUp manipulates leading 5426 // whitespace. 5427 { 5428 const char *Expected = "" 5429 "void f() {\n" 5430 "#if 1\n" 5431 "// Preprocessor aligned.\n" 5432 "# define A 0\n" 5433 " // Code. Separated by blank line.\n" 5434 "\n" 5435 "# define B 0\n" 5436 " // Code. Not aligned with #\n" 5437 "# define C 0\n" 5438 "#endif"; 5439 const char *ToFormat = "" 5440 "void f() {\n" 5441 "#if 1\n" 5442 "// Preprocessor aligned.\n" 5443 "# define A 0\n" 5444 "// Code. Separated by blank line.\n" 5445 "\n" 5446 "# define B 0\n" 5447 " // Code. Not aligned with #\n" 5448 "# define C 0\n" 5449 "#endif"; 5450 EXPECT_EQ(Expected, format(ToFormat, Style)); 5451 EXPECT_EQ(Expected, format(Expected, Style)); 5452 } 5453 // Keep block quotes aligned. 5454 { 5455 const char *Expected = "" 5456 "void f() {\n" 5457 "#if 1\n" 5458 "/* Preprocessor aligned. */\n" 5459 "# define A 0\n" 5460 " /* Code. Separated by blank line. */\n" 5461 "\n" 5462 "# define B 0\n" 5463 " /* Code. Not aligned with # */\n" 5464 "# define C 0\n" 5465 "#endif"; 5466 const char *ToFormat = "" 5467 "void f() {\n" 5468 "#if 1\n" 5469 "/* Preprocessor aligned. */\n" 5470 "# define A 0\n" 5471 "/* Code. Separated by blank line. */\n" 5472 "\n" 5473 "# define B 0\n" 5474 " /* Code. Not aligned with # */\n" 5475 "# define C 0\n" 5476 "#endif"; 5477 EXPECT_EQ(Expected, format(ToFormat, Style)); 5478 EXPECT_EQ(Expected, format(Expected, Style)); 5479 } 5480 // Keep comments aligned with un-indented directives. 5481 { 5482 const char *Expected = "" 5483 "void f() {\n" 5484 "// Preprocessor aligned.\n" 5485 "#define A 0\n" 5486 " // Code. Separated by blank line.\n" 5487 "\n" 5488 "#define B 0\n" 5489 " // Code. Not aligned with #\n" 5490 "#define C 0\n"; 5491 const char *ToFormat = "" 5492 "void f() {\n" 5493 "// Preprocessor aligned.\n" 5494 "#define A 0\n" 5495 "// Code. Separated by blank line.\n" 5496 "\n" 5497 "#define B 0\n" 5498 " // Code. Not aligned with #\n" 5499 "#define C 0\n"; 5500 EXPECT_EQ(Expected, format(ToFormat, Style)); 5501 EXPECT_EQ(Expected, format(Expected, Style)); 5502 } 5503 // Test AfterHash with tabs. 5504 { 5505 FormatStyle Tabbed = Style; 5506 Tabbed.UseTab = FormatStyle::UT_Always; 5507 Tabbed.IndentWidth = 8; 5508 Tabbed.TabWidth = 8; 5509 verifyFormat("#ifdef _WIN32\n" 5510 "#\tdefine A 0\n" 5511 "#\tifdef VAR2\n" 5512 "#\t\tdefine B 1\n" 5513 "#\t\tinclude <someheader.h>\n" 5514 "#\t\tdefine MACRO \\\n" 5515 "\t\t\tsome_very_long_func_aaaaaaaaaa();\n" 5516 "#\tendif\n" 5517 "#else\n" 5518 "#\tdefine A 1\n" 5519 "#endif", 5520 Tabbed); 5521 } 5522 5523 // Regression test: Multiline-macro inside include guards. 5524 verifyFormat("#ifndef HEADER_H\n" 5525 "#define HEADER_H\n" 5526 "#define A() \\\n" 5527 " int i; \\\n" 5528 " int j;\n" 5529 "#endif // HEADER_H", 5530 getLLVMStyleWithColumns(20)); 5531 5532 Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash; 5533 // Basic before hash indent tests 5534 verifyFormat("#ifdef _WIN32\n" 5535 " #define A 0\n" 5536 " #ifdef VAR2\n" 5537 " #define B 1\n" 5538 " #include <someheader.h>\n" 5539 " #define MACRO \\\n" 5540 " some_very_long_func_aaaaaaaaaa();\n" 5541 " #endif\n" 5542 "#else\n" 5543 " #define A 1\n" 5544 "#endif", 5545 Style); 5546 verifyFormat("#if A\n" 5547 " #define MACRO \\\n" 5548 " void a(int x) { \\\n" 5549 " b(); \\\n" 5550 " c(); \\\n" 5551 " d(); \\\n" 5552 " e(); \\\n" 5553 " f(); \\\n" 5554 " }\n" 5555 "#endif", 5556 Style); 5557 // Keep comments aligned with indented directives. These 5558 // tests cannot use verifyFormat because messUp manipulates leading 5559 // whitespace. 5560 { 5561 const char *Expected = "void f() {\n" 5562 "// Aligned to preprocessor.\n" 5563 "#if 1\n" 5564 " // Aligned to code.\n" 5565 " int a;\n" 5566 " #if 1\n" 5567 " // Aligned to preprocessor.\n" 5568 " #define A 0\n" 5569 " // Aligned to code.\n" 5570 " int b;\n" 5571 " #endif\n" 5572 "#endif\n" 5573 "}"; 5574 const char *ToFormat = "void f() {\n" 5575 "// Aligned to preprocessor.\n" 5576 "#if 1\n" 5577 "// Aligned to code.\n" 5578 "int a;\n" 5579 "#if 1\n" 5580 "// Aligned to preprocessor.\n" 5581 "#define A 0\n" 5582 "// Aligned to code.\n" 5583 "int b;\n" 5584 "#endif\n" 5585 "#endif\n" 5586 "}"; 5587 EXPECT_EQ(Expected, format(ToFormat, Style)); 5588 EXPECT_EQ(Expected, format(Expected, Style)); 5589 } 5590 { 5591 const char *Expected = "void f() {\n" 5592 "/* Aligned to preprocessor. */\n" 5593 "#if 1\n" 5594 " /* Aligned to code. */\n" 5595 " int a;\n" 5596 " #if 1\n" 5597 " /* Aligned to preprocessor. */\n" 5598 " #define A 0\n" 5599 " /* Aligned to code. */\n" 5600 " int b;\n" 5601 " #endif\n" 5602 "#endif\n" 5603 "}"; 5604 const char *ToFormat = "void f() {\n" 5605 "/* Aligned to preprocessor. */\n" 5606 "#if 1\n" 5607 "/* Aligned to code. */\n" 5608 "int a;\n" 5609 "#if 1\n" 5610 "/* Aligned to preprocessor. */\n" 5611 "#define A 0\n" 5612 "/* Aligned to code. */\n" 5613 "int b;\n" 5614 "#endif\n" 5615 "#endif\n" 5616 "}"; 5617 EXPECT_EQ(Expected, format(ToFormat, Style)); 5618 EXPECT_EQ(Expected, format(Expected, Style)); 5619 } 5620 5621 // Test single comment before preprocessor 5622 verifyFormat("// Comment\n" 5623 "\n" 5624 "#if 1\n" 5625 "#endif", 5626 Style); 5627 } 5628 5629 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) { 5630 verifyFormat("{\n { a #c; }\n}"); 5631 } 5632 5633 TEST_F(FormatTest, FormatUnbalancedStructuralElements) { 5634 EXPECT_EQ("#define A \\\n { \\\n {\nint i;", 5635 format("#define A { {\nint i;", getLLVMStyleWithColumns(11))); 5636 EXPECT_EQ("#define A \\\n } \\\n }\nint i;", 5637 format("#define A } }\nint i;", getLLVMStyleWithColumns(11))); 5638 } 5639 5640 TEST_F(FormatTest, EscapedNewlines) { 5641 FormatStyle Narrow = getLLVMStyleWithColumns(11); 5642 EXPECT_EQ("#define A \\\n int i; \\\n int j;", 5643 format("#define A \\\nint i;\\\n int j;", Narrow)); 5644 EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;")); 5645 EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();")); 5646 EXPECT_EQ("/* \\ \\ \\\n */", format("\\\n/* \\ \\ \\\n */")); 5647 EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>")); 5648 5649 FormatStyle AlignLeft = getLLVMStyle(); 5650 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left; 5651 EXPECT_EQ("#define MACRO(x) \\\n" 5652 "private: \\\n" 5653 " int x(int a);\n", 5654 format("#define MACRO(x) \\\n" 5655 "private: \\\n" 5656 " int x(int a);\n", 5657 AlignLeft)); 5658 5659 // CRLF line endings 5660 EXPECT_EQ("#define A \\\r\n int i; \\\r\n int j;", 5661 format("#define A \\\r\nint i;\\\r\n int j;", Narrow)); 5662 EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;")); 5663 EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();")); 5664 EXPECT_EQ("/* \\ \\ \\\r\n */", format("\\\r\n/* \\ \\ \\\r\n */")); 5665 EXPECT_EQ("<a\r\n\\\\\r\n>", format("<a\r\n\\\\\r\n>")); 5666 EXPECT_EQ("#define MACRO(x) \\\r\n" 5667 "private: \\\r\n" 5668 " int x(int a);\r\n", 5669 format("#define MACRO(x) \\\r\n" 5670 "private: \\\r\n" 5671 " int x(int a);\r\n", 5672 AlignLeft)); 5673 5674 FormatStyle DontAlign = getLLVMStyle(); 5675 DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 5676 DontAlign.MaxEmptyLinesToKeep = 3; 5677 // FIXME: can't use verifyFormat here because the newline before 5678 // "public:" is not inserted the first time it's reformatted 5679 EXPECT_EQ("#define A \\\n" 5680 " class Foo { \\\n" 5681 " void bar(); \\\n" 5682 "\\\n" 5683 "\\\n" 5684 "\\\n" 5685 " public: \\\n" 5686 " void baz(); \\\n" 5687 " };", 5688 format("#define A \\\n" 5689 " class Foo { \\\n" 5690 " void bar(); \\\n" 5691 "\\\n" 5692 "\\\n" 5693 "\\\n" 5694 " public: \\\n" 5695 " void baz(); \\\n" 5696 " };", 5697 DontAlign)); 5698 } 5699 5700 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) { 5701 verifyFormat("#define A \\\n" 5702 " int v( \\\n" 5703 " a); \\\n" 5704 " int i;", 5705 getLLVMStyleWithColumns(11)); 5706 } 5707 5708 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) { 5709 EXPECT_EQ( 5710 "#define ALooooooooooooooooooooooooooooooooooooooongMacro(" 5711 " \\\n" 5712 " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n" 5713 "\n" 5714 "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n" 5715 " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n", 5716 format(" #define ALooooooooooooooooooooooooooooooooooooooongMacro(" 5717 "\\\n" 5718 "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n" 5719 " \n" 5720 " AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n" 5721 " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n")); 5722 } 5723 5724 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) { 5725 EXPECT_EQ("int\n" 5726 "#define A\n" 5727 " a;", 5728 format("int\n#define A\na;")); 5729 verifyFormat("functionCallTo(\n" 5730 " someOtherFunction(\n" 5731 " withSomeParameters, whichInSequence,\n" 5732 " areLongerThanALine(andAnotherCall,\n" 5733 "#define A B\n" 5734 " withMoreParamters,\n" 5735 " whichStronglyInfluenceTheLayout),\n" 5736 " andMoreParameters),\n" 5737 " trailing);", 5738 getLLVMStyleWithColumns(69)); 5739 verifyFormat("Foo::Foo()\n" 5740 "#ifdef BAR\n" 5741 " : baz(0)\n" 5742 "#endif\n" 5743 "{\n" 5744 "}"); 5745 verifyFormat("void f() {\n" 5746 " if (true)\n" 5747 "#ifdef A\n" 5748 " f(42);\n" 5749 " x();\n" 5750 "#else\n" 5751 " g();\n" 5752 " x();\n" 5753 "#endif\n" 5754 "}"); 5755 verifyFormat("void f(param1, param2,\n" 5756 " param3,\n" 5757 "#ifdef A\n" 5758 " param4(param5,\n" 5759 "#ifdef A1\n" 5760 " param6,\n" 5761 "#ifdef A2\n" 5762 " param7),\n" 5763 "#else\n" 5764 " param8),\n" 5765 " param9,\n" 5766 "#endif\n" 5767 " param10,\n" 5768 "#endif\n" 5769 " param11)\n" 5770 "#else\n" 5771 " param12)\n" 5772 "#endif\n" 5773 "{\n" 5774 " x();\n" 5775 "}", 5776 getLLVMStyleWithColumns(28)); 5777 verifyFormat("#if 1\n" 5778 "int i;"); 5779 verifyFormat("#if 1\n" 5780 "#endif\n" 5781 "#if 1\n" 5782 "#else\n" 5783 "#endif\n"); 5784 verifyFormat("DEBUG({\n" 5785 " return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5786 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n" 5787 "});\n" 5788 "#if a\n" 5789 "#else\n" 5790 "#endif"); 5791 5792 verifyIncompleteFormat("void f(\n" 5793 "#if A\n" 5794 ");\n" 5795 "#else\n" 5796 "#endif"); 5797 } 5798 5799 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) { 5800 verifyFormat("#endif\n" 5801 "#if B"); 5802 } 5803 5804 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) { 5805 FormatStyle SingleLine = getLLVMStyle(); 5806 SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse; 5807 verifyFormat("#if 0\n" 5808 "#elif 1\n" 5809 "#endif\n" 5810 "void foo() {\n" 5811 " if (test) foo2();\n" 5812 "}", 5813 SingleLine); 5814 } 5815 5816 TEST_F(FormatTest, LayoutBlockInsideParens) { 5817 verifyFormat("functionCall({ int i; });"); 5818 verifyFormat("functionCall({\n" 5819 " int i;\n" 5820 " int j;\n" 5821 "});"); 5822 verifyFormat("functionCall(\n" 5823 " {\n" 5824 " int i;\n" 5825 " int j;\n" 5826 " },\n" 5827 " aaaa, bbbb, cccc);"); 5828 verifyFormat("functionA(functionB({\n" 5829 " int i;\n" 5830 " int j;\n" 5831 " }),\n" 5832 " aaaa, bbbb, cccc);"); 5833 verifyFormat("functionCall(\n" 5834 " {\n" 5835 " int i;\n" 5836 " int j;\n" 5837 " },\n" 5838 " aaaa, bbbb, // comment\n" 5839 " cccc);"); 5840 verifyFormat("functionA(functionB({\n" 5841 " int i;\n" 5842 " int j;\n" 5843 " }),\n" 5844 " aaaa, bbbb, // comment\n" 5845 " cccc);"); 5846 verifyFormat("functionCall(aaaa, bbbb, { int i; });"); 5847 verifyFormat("functionCall(aaaa, bbbb, {\n" 5848 " int i;\n" 5849 " int j;\n" 5850 "});"); 5851 verifyFormat( 5852 "Aaa(\n" // FIXME: There shouldn't be a linebreak here. 5853 " {\n" 5854 " int i; // break\n" 5855 " },\n" 5856 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 5857 " ccccccccccccccccc));"); 5858 verifyFormat("DEBUG({\n" 5859 " if (a)\n" 5860 " f();\n" 5861 "});"); 5862 } 5863 5864 TEST_F(FormatTest, LayoutBlockInsideStatement) { 5865 EXPECT_EQ("SOME_MACRO { int i; }\n" 5866 "int i;", 5867 format(" SOME_MACRO {int i;} int i;")); 5868 } 5869 5870 TEST_F(FormatTest, LayoutNestedBlocks) { 5871 verifyFormat("void AddOsStrings(unsigned bitmask) {\n" 5872 " struct s {\n" 5873 " int i;\n" 5874 " };\n" 5875 " s kBitsToOs[] = {{10}};\n" 5876 " for (int i = 0; i < 10; ++i)\n" 5877 " return;\n" 5878 "}"); 5879 verifyFormat("call(parameter, {\n" 5880 " something();\n" 5881 " // Comment using all columns.\n" 5882 " somethingelse();\n" 5883 "});", 5884 getLLVMStyleWithColumns(40)); 5885 verifyFormat("DEBUG( //\n" 5886 " { f(); }, a);"); 5887 verifyFormat("DEBUG( //\n" 5888 " {\n" 5889 " f(); //\n" 5890 " },\n" 5891 " a);"); 5892 5893 EXPECT_EQ("call(parameter, {\n" 5894 " something();\n" 5895 " // Comment too\n" 5896 " // looooooooooong.\n" 5897 " somethingElse();\n" 5898 "});", 5899 format("call(parameter, {\n" 5900 " something();\n" 5901 " // Comment too looooooooooong.\n" 5902 " somethingElse();\n" 5903 "});", 5904 getLLVMStyleWithColumns(29))); 5905 EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int i; });")); 5906 EXPECT_EQ("DEBUG({ // comment\n" 5907 " int i;\n" 5908 "});", 5909 format("DEBUG({ // comment\n" 5910 "int i;\n" 5911 "});")); 5912 EXPECT_EQ("DEBUG({\n" 5913 " int i;\n" 5914 "\n" 5915 " // comment\n" 5916 " int j;\n" 5917 "});", 5918 format("DEBUG({\n" 5919 " int i;\n" 5920 "\n" 5921 " // comment\n" 5922 " int j;\n" 5923 "});")); 5924 5925 verifyFormat("DEBUG({\n" 5926 " if (a)\n" 5927 " return;\n" 5928 "});"); 5929 verifyGoogleFormat("DEBUG({\n" 5930 " if (a) return;\n" 5931 "});"); 5932 FormatStyle Style = getGoogleStyle(); 5933 Style.ColumnLimit = 45; 5934 verifyFormat("Debug(\n" 5935 " aaaaa,\n" 5936 " {\n" 5937 " if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n" 5938 " },\n" 5939 " a);", 5940 Style); 5941 5942 verifyFormat("SomeFunction({MACRO({ return output; }), b});"); 5943 5944 verifyNoCrash("^{v^{a}}"); 5945 } 5946 5947 TEST_F(FormatTest, FormatNestedBlocksInMacros) { 5948 EXPECT_EQ("#define MACRO() \\\n" 5949 " Debug(aaa, /* force line break */ \\\n" 5950 " { \\\n" 5951 " int i; \\\n" 5952 " int j; \\\n" 5953 " })", 5954 format("#define MACRO() Debug(aaa, /* force line break */ \\\n" 5955 " { int i; int j; })", 5956 getGoogleStyle())); 5957 5958 EXPECT_EQ("#define A \\\n" 5959 " [] { \\\n" 5960 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 5961 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n" 5962 " }", 5963 format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 5964 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }", 5965 getGoogleStyle())); 5966 } 5967 5968 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) { 5969 EXPECT_EQ("{}", format("{}")); 5970 verifyFormat("enum E {};"); 5971 verifyFormat("enum E {}"); 5972 FormatStyle Style = getLLVMStyle(); 5973 Style.SpaceInEmptyBlock = true; 5974 EXPECT_EQ("void f() { }", format("void f() {}", Style)); 5975 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 5976 EXPECT_EQ("while (true) { }", format("while (true) {}", Style)); 5977 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 5978 Style.BraceWrapping.BeforeElse = false; 5979 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 5980 verifyFormat("if (a)\n" 5981 "{\n" 5982 "} else if (b)\n" 5983 "{\n" 5984 "} else\n" 5985 "{ }", 5986 Style); 5987 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never; 5988 verifyFormat("if (a) {\n" 5989 "} else if (b) {\n" 5990 "} else {\n" 5991 "}", 5992 Style); 5993 Style.BraceWrapping.BeforeElse = true; 5994 verifyFormat("if (a) { }\n" 5995 "else if (b) { }\n" 5996 "else { }", 5997 Style); 5998 } 5999 6000 TEST_F(FormatTest, FormatBeginBlockEndMacros) { 6001 FormatStyle Style = getLLVMStyle(); 6002 Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$"; 6003 Style.MacroBlockEnd = "^[A-Z_]+_END$"; 6004 verifyFormat("FOO_BEGIN\n" 6005 " FOO_ENTRY\n" 6006 "FOO_END", 6007 Style); 6008 verifyFormat("FOO_BEGIN\n" 6009 " NESTED_FOO_BEGIN\n" 6010 " NESTED_FOO_ENTRY\n" 6011 " NESTED_FOO_END\n" 6012 "FOO_END", 6013 Style); 6014 verifyFormat("FOO_BEGIN(Foo, Bar)\n" 6015 " int x;\n" 6016 " x = 1;\n" 6017 "FOO_END(Baz)", 6018 Style); 6019 } 6020 6021 //===----------------------------------------------------------------------===// 6022 // Line break tests. 6023 //===----------------------------------------------------------------------===// 6024 6025 TEST_F(FormatTest, PreventConfusingIndents) { 6026 verifyFormat( 6027 "void f() {\n" 6028 " SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n" 6029 " parameter, parameter, parameter)),\n" 6030 " SecondLongCall(parameter));\n" 6031 "}"); 6032 verifyFormat( 6033 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6034 " aaaaaaaaaaaaaaaaaaaaaaaa(\n" 6035 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6036 " aaaaaaaaaaaaaaaaaaaaaaaa);"); 6037 verifyFormat( 6038 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6039 " [aaaaaaaaaaaaaaaaaaaaaaaa\n" 6040 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n" 6041 " [aaaaaaaaaaaaaaaaaaaaaaaa]];"); 6042 verifyFormat( 6043 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 6044 " aaaaaaaaaaaaaaaaaaaaaaaa<\n" 6045 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n" 6046 " aaaaaaaaaaaaaaaaaaaaaaaa>;"); 6047 verifyFormat("int a = bbbb && ccc &&\n" 6048 " fffff(\n" 6049 "#define A Just forcing a new line\n" 6050 " ddd);"); 6051 } 6052 6053 TEST_F(FormatTest, LineBreakingInBinaryExpressions) { 6054 verifyFormat( 6055 "bool aaaaaaa =\n" 6056 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n" 6057 " bbbbbbbb();"); 6058 verifyFormat( 6059 "bool aaaaaaa =\n" 6060 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n" 6061 " bbbbbbbb();"); 6062 6063 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n" 6064 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n" 6065 " ccccccccc == ddddddddddd;"); 6066 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n" 6067 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n" 6068 " ccccccccc == ddddddddddd;"); 6069 verifyFormat( 6070 "bool aaaaaaaaaaaaaaaaaaaaa =\n" 6071 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n" 6072 " ccccccccc == ddddddddddd;"); 6073 6074 verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n" 6075 " aaaaaa) &&\n" 6076 " bbbbbb && cccccc;"); 6077 verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n" 6078 " aaaaaa) >>\n" 6079 " bbbbbb;"); 6080 verifyFormat("aa = Whitespaces.addUntouchableComment(\n" 6081 " SourceMgr.getSpellingColumnNumber(\n" 6082 " TheLine.Last->FormatTok.Tok.getLocation()) -\n" 6083 " 1);"); 6084 6085 verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6086 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n" 6087 " cccccc) {\n}"); 6088 verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6089 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n" 6090 " cccccc) {\n}"); 6091 verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6092 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n" 6093 " cccccc) {\n}"); 6094 verifyFormat("b = a &&\n" 6095 " // Comment\n" 6096 " b.c && d;"); 6097 6098 // If the LHS of a comparison is not a binary expression itself, the 6099 // additional linebreak confuses many people. 6100 verifyFormat( 6101 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6102 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n" 6103 "}"); 6104 verifyFormat( 6105 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6106 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 6107 "}"); 6108 verifyFormat( 6109 "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n" 6110 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 6111 "}"); 6112 verifyFormat( 6113 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6114 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n" 6115 "}"); 6116 // Even explicit parentheses stress the precedence enough to make the 6117 // additional break unnecessary. 6118 verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6119 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 6120 "}"); 6121 // This cases is borderline, but with the indentation it is still readable. 6122 verifyFormat( 6123 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6124 " aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6125 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 6126 "}", 6127 getLLVMStyleWithColumns(75)); 6128 6129 // If the LHS is a binary expression, we should still use the additional break 6130 // as otherwise the formatting hides the operator precedence. 6131 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6132 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6133 " 5) {\n" 6134 "}"); 6135 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6136 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n" 6137 " 5) {\n" 6138 "}"); 6139 6140 FormatStyle OnePerLine = getLLVMStyle(); 6141 OnePerLine.BinPackParameters = false; 6142 verifyFormat( 6143 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6144 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6145 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}", 6146 OnePerLine); 6147 6148 verifyFormat("int i = someFunction(aaaaaaa, 0)\n" 6149 " .aaa(aaaaaaaaaaaaa) *\n" 6150 " aaaaaaa +\n" 6151 " aaaaaaa;", 6152 getLLVMStyleWithColumns(40)); 6153 } 6154 6155 TEST_F(FormatTest, ExpressionIndentation) { 6156 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6157 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6158 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6159 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6160 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n" 6161 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n" 6162 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6163 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n" 6164 " ccccccccccccccccccccccccccccccccccccccccc;"); 6165 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6166 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6167 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6168 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 6169 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6170 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6171 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6172 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 6173 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6174 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6175 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6176 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 6177 verifyFormat("if () {\n" 6178 "} else if (aaaaa && bbbbb > // break\n" 6179 " ccccc) {\n" 6180 "}"); 6181 verifyFormat("if () {\n" 6182 "} else if constexpr (aaaaa && bbbbb > // break\n" 6183 " ccccc) {\n" 6184 "}"); 6185 verifyFormat("if () {\n" 6186 "} else if CONSTEXPR (aaaaa && bbbbb > // break\n" 6187 " ccccc) {\n" 6188 "}"); 6189 verifyFormat("if () {\n" 6190 "} else if (aaaaa &&\n" 6191 " bbbbb > // break\n" 6192 " ccccc &&\n" 6193 " ddddd) {\n" 6194 "}"); 6195 6196 // Presence of a trailing comment used to change indentation of b. 6197 verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n" 6198 " b;\n" 6199 "return aaaaaaaaaaaaaaaaaaa +\n" 6200 " b; //", 6201 getLLVMStyleWithColumns(30)); 6202 } 6203 6204 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) { 6205 // Not sure what the best system is here. Like this, the LHS can be found 6206 // immediately above an operator (everything with the same or a higher 6207 // indent). The RHS is aligned right of the operator and so compasses 6208 // everything until something with the same indent as the operator is found. 6209 // FIXME: Is this a good system? 6210 FormatStyle Style = getLLVMStyle(); 6211 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 6212 verifyFormat( 6213 "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6214 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6215 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6216 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6217 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6218 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6219 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6220 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6221 " > ccccccccccccccccccccccccccccccccccccccccc;", 6222 Style); 6223 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6224 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6225 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6226 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6227 Style); 6228 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6229 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6230 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6231 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6232 Style); 6233 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6234 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6235 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6236 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6237 Style); 6238 verifyFormat("if () {\n" 6239 "} else if (aaaaa\n" 6240 " && bbbbb // break\n" 6241 " > ccccc) {\n" 6242 "}", 6243 Style); 6244 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6245 " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6246 Style); 6247 verifyFormat("return (a)\n" 6248 " // comment\n" 6249 " + b;", 6250 Style); 6251 verifyFormat( 6252 "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6253 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6254 " + cc;", 6255 Style); 6256 6257 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6258 " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 6259 Style); 6260 6261 // Forced by comments. 6262 verifyFormat( 6263 "unsigned ContentSize =\n" 6264 " sizeof(int16_t) // DWARF ARange version number\n" 6265 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6266 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6267 " + sizeof(int8_t); // Segment Size (in bytes)"); 6268 6269 verifyFormat("return boost::fusion::at_c<0>(iiii).second\n" 6270 " == boost::fusion::at_c<1>(iiii).second;", 6271 Style); 6272 6273 Style.ColumnLimit = 60; 6274 verifyFormat("zzzzzzzzzz\n" 6275 " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6276 " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);", 6277 Style); 6278 6279 Style.ColumnLimit = 80; 6280 Style.IndentWidth = 4; 6281 Style.TabWidth = 4; 6282 Style.UseTab = FormatStyle::UT_Always; 6283 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6284 Style.AlignOperands = FormatStyle::OAS_DontAlign; 6285 EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n" 6286 "\t&& (someOtherLongishConditionPart1\n" 6287 "\t\t|| someOtherEvenLongerNestedConditionPart2);", 6288 format("return someVeryVeryLongConditionThatBarelyFitsOnALine && " 6289 "(someOtherLongishConditionPart1 || " 6290 "someOtherEvenLongerNestedConditionPart2);", 6291 Style)); 6292 } 6293 6294 TEST_F(FormatTest, ExpressionIndentationStrictAlign) { 6295 FormatStyle Style = getLLVMStyle(); 6296 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 6297 Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator; 6298 6299 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6300 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6301 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6302 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6303 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6304 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6305 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6306 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6307 " > ccccccccccccccccccccccccccccccccccccccccc;", 6308 Style); 6309 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6310 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6311 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6312 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6313 Style); 6314 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6315 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6316 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6317 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6318 Style); 6319 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6320 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6321 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6322 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6323 Style); 6324 verifyFormat("if () {\n" 6325 "} else if (aaaaa\n" 6326 " && bbbbb // break\n" 6327 " > ccccc) {\n" 6328 "}", 6329 Style); 6330 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6331 " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6332 Style); 6333 verifyFormat("return (a)\n" 6334 " // comment\n" 6335 " + b;", 6336 Style); 6337 verifyFormat( 6338 "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6339 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6340 " + cc;", 6341 Style); 6342 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 6343 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 6344 " : 3333333333333333;", 6345 Style); 6346 verifyFormat( 6347 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 6348 " : ccccccccccccccc ? dddddddddddddddddd\n" 6349 " : eeeeeeeeeeeeeeeeee)\n" 6350 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 6351 " : 3333333333333333;", 6352 Style); 6353 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6354 " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 6355 Style); 6356 6357 verifyFormat("return boost::fusion::at_c<0>(iiii).second\n" 6358 " == boost::fusion::at_c<1>(iiii).second;", 6359 Style); 6360 6361 Style.ColumnLimit = 60; 6362 verifyFormat("zzzzzzzzzzzzz\n" 6363 " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6364 " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);", 6365 Style); 6366 6367 // Forced by comments. 6368 Style.ColumnLimit = 80; 6369 verifyFormat( 6370 "unsigned ContentSize\n" 6371 " = sizeof(int16_t) // DWARF ARange version number\n" 6372 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6373 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6374 " + sizeof(int8_t); // Segment Size (in bytes)", 6375 Style); 6376 6377 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6378 verifyFormat( 6379 "unsigned ContentSize =\n" 6380 " sizeof(int16_t) // DWARF ARange version number\n" 6381 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6382 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6383 " + sizeof(int8_t); // Segment Size (in bytes)", 6384 Style); 6385 6386 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 6387 verifyFormat( 6388 "unsigned ContentSize =\n" 6389 " sizeof(int16_t) // DWARF ARange version number\n" 6390 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6391 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6392 " + sizeof(int8_t); // Segment Size (in bytes)", 6393 Style); 6394 } 6395 6396 TEST_F(FormatTest, EnforcedOperatorWraps) { 6397 // Here we'd like to wrap after the || operators, but a comment is forcing an 6398 // earlier wrap. 6399 verifyFormat("bool x = aaaaa //\n" 6400 " || bbbbb\n" 6401 " //\n" 6402 " || cccc;"); 6403 } 6404 6405 TEST_F(FormatTest, NoOperandAlignment) { 6406 FormatStyle Style = getLLVMStyle(); 6407 Style.AlignOperands = FormatStyle::OAS_DontAlign; 6408 verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n" 6409 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6410 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 6411 Style); 6412 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6413 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6414 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6415 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6416 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6417 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6418 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6419 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6420 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6421 " > ccccccccccccccccccccccccccccccccccccccccc;", 6422 Style); 6423 6424 verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6425 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6426 " + cc;", 6427 Style); 6428 verifyFormat("int a = aa\n" 6429 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6430 " * cccccccccccccccccccccccccccccccccccc;\n", 6431 Style); 6432 6433 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6434 verifyFormat("return (a > b\n" 6435 " // comment1\n" 6436 " // comment2\n" 6437 " || c);", 6438 Style); 6439 } 6440 6441 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) { 6442 FormatStyle Style = getLLVMStyle(); 6443 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6444 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 6445 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6446 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6447 Style); 6448 } 6449 6450 TEST_F(FormatTest, AllowBinPackingInsideArguments) { 6451 FormatStyle Style = getLLVMStyleWithColumns(40); 6452 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6453 Style.BinPackArguments = false; 6454 verifyFormat("void test() {\n" 6455 " someFunction(\n" 6456 " this + argument + is + quite\n" 6457 " + long + so + it + gets + wrapped\n" 6458 " + but + remains + bin - packed);\n" 6459 "}", 6460 Style); 6461 verifyFormat("void test() {\n" 6462 " someFunction(arg1,\n" 6463 " this + argument + is\n" 6464 " + quite + long + so\n" 6465 " + it + gets + wrapped\n" 6466 " + but + remains + bin\n" 6467 " - packed,\n" 6468 " arg3);\n" 6469 "}", 6470 Style); 6471 verifyFormat("void test() {\n" 6472 " someFunction(\n" 6473 " arg1,\n" 6474 " this + argument + has\n" 6475 " + anotherFunc(nested,\n" 6476 " calls + whose\n" 6477 " + arguments\n" 6478 " + are + also\n" 6479 " + wrapped,\n" 6480 " in + addition)\n" 6481 " + to + being + bin - packed,\n" 6482 " arg3);\n" 6483 "}", 6484 Style); 6485 6486 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 6487 verifyFormat("void test() {\n" 6488 " someFunction(\n" 6489 " arg1,\n" 6490 " this + argument + has +\n" 6491 " anotherFunc(nested,\n" 6492 " calls + whose +\n" 6493 " arguments +\n" 6494 " are + also +\n" 6495 " wrapped,\n" 6496 " in + addition) +\n" 6497 " to + being + bin - packed,\n" 6498 " arg3);\n" 6499 "}", 6500 Style); 6501 } 6502 6503 TEST_F(FormatTest, BreakBinaryOperatorsInPresenceOfTemplates) { 6504 auto Style = getLLVMStyleWithColumns(45); 6505 EXPECT_EQ(Style.BreakBeforeBinaryOperators, FormatStyle::BOS_None); 6506 verifyFormat("bool b =\n" 6507 " is_default_constructible_v<hash<T>> and\n" 6508 " is_copy_constructible_v<hash<T>> and\n" 6509 " is_move_constructible_v<hash<T>> and\n" 6510 " is_copy_assignable_v<hash<T>> and\n" 6511 " is_move_assignable_v<hash<T>> and\n" 6512 " is_destructible_v<hash<T>> and\n" 6513 " is_swappable_v<hash<T>> and\n" 6514 " is_callable_v<hash<T>(T)>;", 6515 Style); 6516 6517 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6518 verifyFormat("bool b = is_default_constructible_v<hash<T>>\n" 6519 " and is_copy_constructible_v<hash<T>>\n" 6520 " and is_move_constructible_v<hash<T>>\n" 6521 " and is_copy_assignable_v<hash<T>>\n" 6522 " and is_move_assignable_v<hash<T>>\n" 6523 " and is_destructible_v<hash<T>>\n" 6524 " and is_swappable_v<hash<T>>\n" 6525 " and is_callable_v<hash<T>(T)>;", 6526 Style); 6527 6528 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 6529 verifyFormat("bool b = is_default_constructible_v<hash<T>>\n" 6530 " and is_copy_constructible_v<hash<T>>\n" 6531 " and is_move_constructible_v<hash<T>>\n" 6532 " and is_copy_assignable_v<hash<T>>\n" 6533 " and is_move_assignable_v<hash<T>>\n" 6534 " and is_destructible_v<hash<T>>\n" 6535 " and is_swappable_v<hash<T>>\n" 6536 " and is_callable_v<hash<T>(T)>;", 6537 Style); 6538 } 6539 6540 TEST_F(FormatTest, ConstructorInitializers) { 6541 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}"); 6542 verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}", 6543 getLLVMStyleWithColumns(45)); 6544 verifyFormat("Constructor()\n" 6545 " : Inttializer(FitsOnTheLine) {}", 6546 getLLVMStyleWithColumns(44)); 6547 verifyFormat("Constructor()\n" 6548 " : Inttializer(FitsOnTheLine) {}", 6549 getLLVMStyleWithColumns(43)); 6550 6551 verifyFormat("template <typename T>\n" 6552 "Constructor() : Initializer(FitsOnTheLine) {}", 6553 getLLVMStyleWithColumns(45)); 6554 6555 verifyFormat( 6556 "SomeClass::Constructor()\n" 6557 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}"); 6558 6559 verifyFormat( 6560 "SomeClass::Constructor()\n" 6561 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6562 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}"); 6563 verifyFormat( 6564 "SomeClass::Constructor()\n" 6565 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6566 " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}"); 6567 verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6568 " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 6569 " : aaaaaaaaaa(aaaaaa) {}"); 6570 6571 verifyFormat("Constructor()\n" 6572 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6573 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6574 " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6575 " aaaaaaaaaaaaaaaaaaaaaaa() {}"); 6576 6577 verifyFormat("Constructor()\n" 6578 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6579 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 6580 6581 verifyFormat("Constructor(int Parameter = 0)\n" 6582 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n" 6583 " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}"); 6584 verifyFormat("Constructor()\n" 6585 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n" 6586 "}", 6587 getLLVMStyleWithColumns(60)); 6588 verifyFormat("Constructor()\n" 6589 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6590 " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}"); 6591 6592 // Here a line could be saved by splitting the second initializer onto two 6593 // lines, but that is not desirable. 6594 verifyFormat("Constructor()\n" 6595 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n" 6596 " aaaaaaaaaaa(aaaaaaaaaaa),\n" 6597 " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 6598 6599 FormatStyle OnePerLine = getLLVMStyle(); 6600 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_Never; 6601 verifyFormat("MyClass::MyClass()\n" 6602 " : a(a),\n" 6603 " b(b),\n" 6604 " c(c) {}", 6605 OnePerLine); 6606 verifyFormat("MyClass::MyClass()\n" 6607 " : a(a), // comment\n" 6608 " b(b),\n" 6609 " c(c) {}", 6610 OnePerLine); 6611 verifyFormat("MyClass::MyClass(int a)\n" 6612 " : b(a), // comment\n" 6613 " c(a + 1) { // lined up\n" 6614 "}", 6615 OnePerLine); 6616 verifyFormat("Constructor()\n" 6617 " : a(b, b, b) {}", 6618 OnePerLine); 6619 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6620 OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false; 6621 verifyFormat("SomeClass::Constructor()\n" 6622 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6623 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6624 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6625 OnePerLine); 6626 verifyFormat("SomeClass::Constructor()\n" 6627 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n" 6628 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6629 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6630 OnePerLine); 6631 verifyFormat("MyClass::MyClass(int var)\n" 6632 " : some_var_(var), // 4 space indent\n" 6633 " some_other_var_(var + 1) { // lined up\n" 6634 "}", 6635 OnePerLine); 6636 verifyFormat("Constructor()\n" 6637 " : aaaaa(aaaaaa),\n" 6638 " aaaaa(aaaaaa),\n" 6639 " aaaaa(aaaaaa),\n" 6640 " aaaaa(aaaaaa),\n" 6641 " aaaaa(aaaaaa) {}", 6642 OnePerLine); 6643 verifyFormat("Constructor()\n" 6644 " : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n" 6645 " aaaaaaaaaaaaaaaaaaaaaa) {}", 6646 OnePerLine); 6647 OnePerLine.BinPackParameters = false; 6648 verifyFormat( 6649 "Constructor()\n" 6650 " : aaaaaaaaaaaaaaaaaaaaaaaa(\n" 6651 " aaaaaaaaaaa().aaa(),\n" 6652 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6653 OnePerLine); 6654 OnePerLine.ColumnLimit = 60; 6655 verifyFormat("Constructor()\n" 6656 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6657 " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}", 6658 OnePerLine); 6659 6660 EXPECT_EQ("Constructor()\n" 6661 " : // Comment forcing unwanted break.\n" 6662 " aaaa(aaaa) {}", 6663 format("Constructor() :\n" 6664 " // Comment forcing unwanted break.\n" 6665 " aaaa(aaaa) {}")); 6666 } 6667 6668 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) { 6669 FormatStyle Style = getLLVMStyleWithColumns(60); 6670 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6671 Style.BinPackParameters = false; 6672 6673 for (int i = 0; i < 4; ++i) { 6674 // Test all combinations of parameters that should not have an effect. 6675 Style.AllowAllParametersOfDeclarationOnNextLine = i & 1; 6676 Style.AllowAllArgumentsOnNextLine = i & 2; 6677 6678 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6679 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6680 verifyFormat("Constructor()\n" 6681 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6682 Style); 6683 verifyFormat("Constructor() : a(a), b(b) {}", Style); 6684 6685 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6686 verifyFormat("Constructor()\n" 6687 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6688 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6689 Style); 6690 verifyFormat("Constructor() : a(a), b(b) {}", Style); 6691 6692 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 6693 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6694 verifyFormat("Constructor()\n" 6695 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6696 Style); 6697 6698 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6699 verifyFormat("Constructor()\n" 6700 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6701 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6702 Style); 6703 6704 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6705 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6706 verifyFormat("Constructor() :\n" 6707 " aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6708 Style); 6709 6710 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6711 verifyFormat("Constructor() :\n" 6712 " aaaaaaaaaaaaaaaaaa(a),\n" 6713 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6714 Style); 6715 } 6716 6717 // Test interactions between AllowAllParametersOfDeclarationOnNextLine and 6718 // AllowAllConstructorInitializersOnNextLine in all 6719 // BreakConstructorInitializers modes 6720 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6721 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6722 verifyFormat("SomeClassWithALongName::Constructor(\n" 6723 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n" 6724 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6725 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6726 Style); 6727 6728 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6729 verifyFormat("SomeClassWithALongName::Constructor(\n" 6730 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6731 " int bbbbbbbbbbbbb,\n" 6732 " int cccccccccccccccc)\n" 6733 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6734 Style); 6735 6736 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6737 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6738 verifyFormat("SomeClassWithALongName::Constructor(\n" 6739 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6740 " int bbbbbbbbbbbbb)\n" 6741 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6742 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6743 Style); 6744 6745 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 6746 6747 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6748 verifyFormat("SomeClassWithALongName::Constructor(\n" 6749 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n" 6750 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6751 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6752 Style); 6753 6754 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6755 verifyFormat("SomeClassWithALongName::Constructor(\n" 6756 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6757 " int bbbbbbbbbbbbb,\n" 6758 " int cccccccccccccccc)\n" 6759 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6760 Style); 6761 6762 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6763 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6764 verifyFormat("SomeClassWithALongName::Constructor(\n" 6765 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6766 " int bbbbbbbbbbbbb)\n" 6767 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6768 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6769 Style); 6770 6771 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6772 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6773 verifyFormat("SomeClassWithALongName::Constructor(\n" 6774 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n" 6775 " aaaaaaaaaaaaaaaaaaaa(a),\n" 6776 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6777 Style); 6778 6779 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6780 verifyFormat("SomeClassWithALongName::Constructor(\n" 6781 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6782 " int bbbbbbbbbbbbb,\n" 6783 " int cccccccccccccccc) :\n" 6784 " aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6785 Style); 6786 6787 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6788 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6789 verifyFormat("SomeClassWithALongName::Constructor(\n" 6790 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6791 " int bbbbbbbbbbbbb) :\n" 6792 " aaaaaaaaaaaaaaaaaaaa(a),\n" 6793 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6794 Style); 6795 } 6796 6797 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) { 6798 FormatStyle Style = getLLVMStyleWithColumns(60); 6799 Style.BinPackArguments = false; 6800 for (int i = 0; i < 4; ++i) { 6801 // Test all combinations of parameters that should not have an effect. 6802 Style.AllowAllParametersOfDeclarationOnNextLine = i & 1; 6803 Style.PackConstructorInitializers = 6804 i & 2 ? FormatStyle::PCIS_BinPack : FormatStyle::PCIS_Never; 6805 6806 Style.AllowAllArgumentsOnNextLine = true; 6807 verifyFormat("void foo() {\n" 6808 " FunctionCallWithReallyLongName(\n" 6809 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n" 6810 "}", 6811 Style); 6812 Style.AllowAllArgumentsOnNextLine = false; 6813 verifyFormat("void foo() {\n" 6814 " FunctionCallWithReallyLongName(\n" 6815 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6816 " bbbbbbbbbbbb);\n" 6817 "}", 6818 Style); 6819 6820 Style.AllowAllArgumentsOnNextLine = true; 6821 verifyFormat("void foo() {\n" 6822 " auto VariableWithReallyLongName = {\n" 6823 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n" 6824 "}", 6825 Style); 6826 Style.AllowAllArgumentsOnNextLine = false; 6827 verifyFormat("void foo() {\n" 6828 " auto VariableWithReallyLongName = {\n" 6829 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6830 " bbbbbbbbbbbb};\n" 6831 "}", 6832 Style); 6833 } 6834 6835 // This parameter should not affect declarations. 6836 Style.BinPackParameters = false; 6837 Style.AllowAllArgumentsOnNextLine = false; 6838 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6839 verifyFormat("void FunctionCallWithReallyLongName(\n" 6840 " int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);", 6841 Style); 6842 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6843 verifyFormat("void FunctionCallWithReallyLongName(\n" 6844 " int aaaaaaaaaaaaaaaaaaaaaaa,\n" 6845 " int bbbbbbbbbbbb);", 6846 Style); 6847 } 6848 6849 TEST_F(FormatTest, AllowAllArgumentsOnNextLineDontAlign) { 6850 // Check that AllowAllArgumentsOnNextLine is respected for both BAS_DontAlign 6851 // and BAS_Align. 6852 FormatStyle Style = getLLVMStyleWithColumns(35); 6853 StringRef Input = "functionCall(paramA, paramB, paramC);\n" 6854 "void functionDecl(int A, int B, int C);"; 6855 Style.AllowAllArgumentsOnNextLine = false; 6856 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6857 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6858 " paramC);\n" 6859 "void functionDecl(int A, int B,\n" 6860 " int C);"), 6861 format(Input, Style)); 6862 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 6863 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6864 " paramC);\n" 6865 "void functionDecl(int A, int B,\n" 6866 " int C);"), 6867 format(Input, Style)); 6868 // However, BAS_AlwaysBreak should take precedence over 6869 // AllowAllArgumentsOnNextLine. 6870 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 6871 EXPECT_EQ(StringRef("functionCall(\n" 6872 " paramA, paramB, paramC);\n" 6873 "void functionDecl(\n" 6874 " int A, int B, int C);"), 6875 format(Input, Style)); 6876 6877 // When AllowAllArgumentsOnNextLine is set, we prefer breaking before the 6878 // first argument. 6879 Style.AllowAllArgumentsOnNextLine = true; 6880 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 6881 EXPECT_EQ(StringRef("functionCall(\n" 6882 " paramA, paramB, paramC);\n" 6883 "void functionDecl(\n" 6884 " int A, int B, int C);"), 6885 format(Input, Style)); 6886 // It wouldn't fit on one line with aligned parameters so this setting 6887 // doesn't change anything for BAS_Align. 6888 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 6889 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6890 " paramC);\n" 6891 "void functionDecl(int A, int B,\n" 6892 " int C);"), 6893 format(Input, Style)); 6894 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6895 EXPECT_EQ(StringRef("functionCall(\n" 6896 " paramA, paramB, paramC);\n" 6897 "void functionDecl(\n" 6898 " int A, int B, int C);"), 6899 format(Input, Style)); 6900 } 6901 6902 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) { 6903 FormatStyle Style = getLLVMStyle(); 6904 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6905 6906 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}"); 6907 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}", 6908 getStyleWithColumns(Style, 45)); 6909 verifyFormat("Constructor() :\n" 6910 " Initializer(FitsOnTheLine) {}", 6911 getStyleWithColumns(Style, 44)); 6912 verifyFormat("Constructor() :\n" 6913 " Initializer(FitsOnTheLine) {}", 6914 getStyleWithColumns(Style, 43)); 6915 6916 verifyFormat("template <typename T>\n" 6917 "Constructor() : Initializer(FitsOnTheLine) {}", 6918 getStyleWithColumns(Style, 50)); 6919 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6920 verifyFormat( 6921 "SomeClass::Constructor() :\n" 6922 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 6923 Style); 6924 6925 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 6926 verifyFormat( 6927 "SomeClass::Constructor() :\n" 6928 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 6929 Style); 6930 6931 verifyFormat( 6932 "SomeClass::Constructor() :\n" 6933 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6934 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6935 Style); 6936 verifyFormat( 6937 "SomeClass::Constructor() :\n" 6938 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6939 " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 6940 Style); 6941 verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6942 " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 6943 " aaaaaaaaaa(aaaaaa) {}", 6944 Style); 6945 6946 verifyFormat("Constructor() :\n" 6947 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6948 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6949 " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6950 " aaaaaaaaaaaaaaaaaaaaaaa() {}", 6951 Style); 6952 6953 verifyFormat("Constructor() :\n" 6954 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6955 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6956 Style); 6957 6958 verifyFormat("Constructor(int Parameter = 0) :\n" 6959 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n" 6960 " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}", 6961 Style); 6962 verifyFormat("Constructor() :\n" 6963 " aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n" 6964 "}", 6965 getStyleWithColumns(Style, 60)); 6966 verifyFormat("Constructor() :\n" 6967 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6968 " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}", 6969 Style); 6970 6971 // Here a line could be saved by splitting the second initializer onto two 6972 // lines, but that is not desirable. 6973 verifyFormat("Constructor() :\n" 6974 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n" 6975 " aaaaaaaaaaa(aaaaaaaaaaa),\n" 6976 " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6977 Style); 6978 6979 FormatStyle OnePerLine = Style; 6980 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6981 verifyFormat("SomeClass::Constructor() :\n" 6982 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6983 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6984 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6985 OnePerLine); 6986 verifyFormat("SomeClass::Constructor() :\n" 6987 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n" 6988 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6989 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6990 OnePerLine); 6991 verifyFormat("MyClass::MyClass(int var) :\n" 6992 " some_var_(var), // 4 space indent\n" 6993 " some_other_var_(var + 1) { // lined up\n" 6994 "}", 6995 OnePerLine); 6996 verifyFormat("Constructor() :\n" 6997 " aaaaa(aaaaaa),\n" 6998 " aaaaa(aaaaaa),\n" 6999 " aaaaa(aaaaaa),\n" 7000 " aaaaa(aaaaaa),\n" 7001 " aaaaa(aaaaaa) {}", 7002 OnePerLine); 7003 verifyFormat("Constructor() :\n" 7004 " aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n" 7005 " aaaaaaaaaaaaaaaaaaaaaa) {}", 7006 OnePerLine); 7007 OnePerLine.BinPackParameters = false; 7008 verifyFormat("Constructor() :\n" 7009 " aaaaaaaaaaaaaaaaaaaaaaaa(\n" 7010 " aaaaaaaaaaa().aaa(),\n" 7011 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7012 OnePerLine); 7013 OnePerLine.ColumnLimit = 60; 7014 verifyFormat("Constructor() :\n" 7015 " aaaaaaaaaaaaaaaaaaaa(a),\n" 7016 " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}", 7017 OnePerLine); 7018 7019 EXPECT_EQ("Constructor() :\n" 7020 " // Comment forcing unwanted break.\n" 7021 " aaaa(aaaa) {}", 7022 format("Constructor() :\n" 7023 " // Comment forcing unwanted break.\n" 7024 " aaaa(aaaa) {}", 7025 Style)); 7026 7027 Style.ColumnLimit = 0; 7028 verifyFormat("SomeClass::Constructor() :\n" 7029 " a(a) {}", 7030 Style); 7031 verifyFormat("SomeClass::Constructor() noexcept :\n" 7032 " a(a) {}", 7033 Style); 7034 verifyFormat("SomeClass::Constructor() :\n" 7035 " a(a), b(b), c(c) {}", 7036 Style); 7037 verifyFormat("SomeClass::Constructor() :\n" 7038 " a(a) {\n" 7039 " foo();\n" 7040 " bar();\n" 7041 "}", 7042 Style); 7043 7044 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 7045 verifyFormat("SomeClass::Constructor() :\n" 7046 " a(a), b(b), c(c) {\n" 7047 "}", 7048 Style); 7049 verifyFormat("SomeClass::Constructor() :\n" 7050 " a(a) {\n" 7051 "}", 7052 Style); 7053 7054 Style.ColumnLimit = 80; 7055 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 7056 Style.ConstructorInitializerIndentWidth = 2; 7057 verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style); 7058 verifyFormat("SomeClass::Constructor() :\n" 7059 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7060 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}", 7061 Style); 7062 7063 // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as 7064 // well 7065 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 7066 verifyFormat( 7067 "class SomeClass\n" 7068 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7069 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7070 Style); 7071 Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma; 7072 verifyFormat( 7073 "class SomeClass\n" 7074 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7075 " , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7076 Style); 7077 Style.BreakInheritanceList = FormatStyle::BILS_AfterColon; 7078 verifyFormat( 7079 "class SomeClass :\n" 7080 " public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7081 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7082 Style); 7083 Style.BreakInheritanceList = FormatStyle::BILS_AfterComma; 7084 verifyFormat( 7085 "class SomeClass\n" 7086 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7087 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7088 Style); 7089 } 7090 7091 #ifndef EXPENSIVE_CHECKS 7092 // Expensive checks enables libstdc++ checking which includes validating the 7093 // state of ranges used in std::priority_queue - this blows out the 7094 // runtime/scalability of the function and makes this test unacceptably slow. 7095 TEST_F(FormatTest, MemoizationTests) { 7096 // This breaks if the memoization lookup does not take \c Indent and 7097 // \c LastSpace into account. 7098 verifyFormat( 7099 "extern CFRunLoopTimerRef\n" 7100 "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n" 7101 " CFTimeInterval interval, CFOptionFlags flags,\n" 7102 " CFIndex order, CFRunLoopTimerCallBack callout,\n" 7103 " CFRunLoopTimerContext *context) {}"); 7104 7105 // Deep nesting somewhat works around our memoization. 7106 verifyFormat( 7107 "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7108 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7109 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7110 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7111 " aaaaa())))))))))))))))))))))))))))))))))))))));", 7112 getLLVMStyleWithColumns(65)); 7113 verifyFormat( 7114 "aaaaa(\n" 7115 " aaaaa,\n" 7116 " aaaaa(\n" 7117 " aaaaa,\n" 7118 " aaaaa(\n" 7119 " aaaaa,\n" 7120 " aaaaa(\n" 7121 " aaaaa,\n" 7122 " aaaaa(\n" 7123 " aaaaa,\n" 7124 " aaaaa(\n" 7125 " aaaaa,\n" 7126 " aaaaa(\n" 7127 " aaaaa,\n" 7128 " aaaaa(\n" 7129 " aaaaa,\n" 7130 " aaaaa(\n" 7131 " aaaaa,\n" 7132 " aaaaa(\n" 7133 " aaaaa,\n" 7134 " aaaaa(\n" 7135 " aaaaa,\n" 7136 " aaaaa(\n" 7137 " aaaaa,\n" 7138 " aaaaa))))))))))));", 7139 getLLVMStyleWithColumns(65)); 7140 verifyFormat( 7141 "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" 7142 " a),\n" 7143 " a),\n" 7144 " a),\n" 7145 " a),\n" 7146 " a),\n" 7147 " a),\n" 7148 " a),\n" 7149 " a),\n" 7150 " a),\n" 7151 " a),\n" 7152 " a),\n" 7153 " a),\n" 7154 " a),\n" 7155 " a),\n" 7156 " a),\n" 7157 " a),\n" 7158 " a)", 7159 getLLVMStyleWithColumns(65)); 7160 7161 // This test takes VERY long when memoization is broken. 7162 FormatStyle OnePerLine = getLLVMStyle(); 7163 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 7164 OnePerLine.BinPackParameters = false; 7165 std::string input = "Constructor()\n" 7166 " : aaaa(a,\n"; 7167 for (unsigned i = 0, e = 80; i != e; ++i) { 7168 input += " a,\n"; 7169 } 7170 input += " a) {}"; 7171 verifyFormat(input, OnePerLine); 7172 } 7173 #endif 7174 7175 TEST_F(FormatTest, BreaksAsHighAsPossible) { 7176 verifyFormat( 7177 "void f() {\n" 7178 " if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n" 7179 " (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n" 7180 " f();\n" 7181 "}"); 7182 verifyFormat("if (Intervals[i].getRange().getFirst() <\n" 7183 " Intervals[i - 1].getRange().getLast()) {\n}"); 7184 } 7185 7186 TEST_F(FormatTest, BreaksFunctionDeclarations) { 7187 // Principially, we break function declarations in a certain order: 7188 // 1) break amongst arguments. 7189 verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n" 7190 " Cccccccccccccc cccccccccccccc);"); 7191 verifyFormat("template <class TemplateIt>\n" 7192 "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n" 7193 " TemplateIt *stop) {}"); 7194 7195 // 2) break after return type. 7196 verifyFormat( 7197 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7198 "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);", 7199 getGoogleStyle()); 7200 7201 // 3) break after (. 7202 verifyFormat( 7203 "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n" 7204 " Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);", 7205 getGoogleStyle()); 7206 7207 // 4) break before after nested name specifiers. 7208 verifyFormat( 7209 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7210 "SomeClasssssssssssssssssssssssssssssssssssssss::\n" 7211 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);", 7212 getGoogleStyle()); 7213 7214 // However, there are exceptions, if a sufficient amount of lines can be 7215 // saved. 7216 // FIXME: The precise cut-offs wrt. the number of saved lines might need some 7217 // more adjusting. 7218 verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n" 7219 " Cccccccccccccc cccccccccc,\n" 7220 " Cccccccccccccc cccccccccc,\n" 7221 " Cccccccccccccc cccccccccc,\n" 7222 " Cccccccccccccc cccccccccc);"); 7223 verifyFormat( 7224 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7225 "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7226 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7227 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);", 7228 getGoogleStyle()); 7229 verifyFormat( 7230 "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n" 7231 " Cccccccccccccc cccccccccc,\n" 7232 " Cccccccccccccc cccccccccc,\n" 7233 " Cccccccccccccc cccccccccc,\n" 7234 " Cccccccccccccc cccccccccc,\n" 7235 " Cccccccccccccc cccccccccc,\n" 7236 " Cccccccccccccc cccccccccc);"); 7237 verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7238 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7239 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7240 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7241 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);"); 7242 7243 // Break after multi-line parameters. 7244 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7245 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7246 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7247 " bbbb bbbb);"); 7248 verifyFormat("void SomeLoooooooooooongFunction(\n" 7249 " std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n" 7250 " aaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7251 " int bbbbbbbbbbbbb);"); 7252 7253 // Treat overloaded operators like other functions. 7254 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 7255 "operator>(const SomeLoooooooooooooooooooooooooogType &other);"); 7256 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 7257 "operator>>(const SomeLooooooooooooooooooooooooogType &other);"); 7258 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 7259 "operator<<(const SomeLooooooooooooooooooooooooogType &other);"); 7260 verifyGoogleFormat( 7261 "SomeLoooooooooooooooooooooooooooooogType operator>>(\n" 7262 " const SomeLooooooooogType &a, const SomeLooooooooogType &b);"); 7263 verifyGoogleFormat( 7264 "SomeLoooooooooooooooooooooooooooooogType operator<<(\n" 7265 " const SomeLooooooooogType &a, const SomeLooooooooogType &b);"); 7266 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7267 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);"); 7268 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n" 7269 "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);"); 7270 verifyGoogleFormat( 7271 "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n" 7272 "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7273 " bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}"); 7274 verifyGoogleFormat("template <typename T>\n" 7275 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7276 "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n" 7277 " aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);"); 7278 7279 FormatStyle Style = getLLVMStyle(); 7280 Style.PointerAlignment = FormatStyle::PAS_Left; 7281 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7282 " aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}", 7283 Style); 7284 verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n" 7285 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7286 Style); 7287 } 7288 7289 TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) { 7290 // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516: 7291 // Prefer keeping `::` followed by `operator` together. 7292 EXPECT_EQ("const aaaa::bbbbbbb &\n" 7293 "ccccccccc::operator++() {\n" 7294 " stuff();\n" 7295 "}", 7296 format("const aaaa::bbbbbbb\n" 7297 "&ccccccccc::operator++() { stuff(); }", 7298 getLLVMStyleWithColumns(40))); 7299 } 7300 7301 TEST_F(FormatTest, TrailingReturnType) { 7302 verifyFormat("auto foo() -> int;\n"); 7303 // correct trailing return type spacing 7304 verifyFormat("auto operator->() -> int;\n"); 7305 verifyFormat("auto operator++(int) -> int;\n"); 7306 7307 verifyFormat("struct S {\n" 7308 " auto bar() const -> int;\n" 7309 "};"); 7310 verifyFormat("template <size_t Order, typename T>\n" 7311 "auto load_img(const std::string &filename)\n" 7312 " -> alias::tensor<Order, T, mem::tag::cpu> {}"); 7313 verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n" 7314 " -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}"); 7315 verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}"); 7316 verifyFormat("template <typename T>\n" 7317 "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n" 7318 " -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());"); 7319 7320 // Not trailing return types. 7321 verifyFormat("void f() { auto a = b->c(); }"); 7322 verifyFormat("auto a = p->foo();"); 7323 verifyFormat("int a = p->foo();"); 7324 verifyFormat("auto lmbd = [] NOEXCEPT -> int { return 0; };"); 7325 } 7326 7327 TEST_F(FormatTest, DeductionGuides) { 7328 verifyFormat("template <class T> A(const T &, const T &) -> A<T &>;"); 7329 verifyFormat("template <class T> explicit A(T &, T &&) -> A<T>;"); 7330 verifyFormat("template <class... Ts> S(Ts...) -> S<Ts...>;"); 7331 verifyFormat( 7332 "template <class... T>\n" 7333 "array(T &&...t) -> array<std::common_type_t<T...>, sizeof...(T)>;"); 7334 verifyFormat("template <class T> A() -> A<decltype(p->foo<3>())>;"); 7335 verifyFormat("template <class T> A() -> A<decltype(foo<traits<1>>)>;"); 7336 verifyFormat("template <class T> A() -> A<sizeof(p->foo<1>)>;"); 7337 verifyFormat("template <class T> A() -> A<(3 < 2)>;"); 7338 verifyFormat("template <class T> A() -> A<((3) < (2))>;"); 7339 verifyFormat("template <class T> x() -> x<1>;"); 7340 verifyFormat("template <class T> explicit x(T &) -> x<1>;"); 7341 7342 // Ensure not deduction guides. 7343 verifyFormat("c()->f<int>();"); 7344 verifyFormat("x()->foo<1>;"); 7345 verifyFormat("x = p->foo<3>();"); 7346 verifyFormat("x()->x<1>();"); 7347 verifyFormat("x()->x<1>;"); 7348 } 7349 7350 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) { 7351 // Avoid breaking before trailing 'const' or other trailing annotations, if 7352 // they are not function-like. 7353 FormatStyle Style = getGoogleStyleWithColumns(47); 7354 verifyFormat("void someLongFunction(\n" 7355 " int someLoooooooooooooongParameter) const {\n}", 7356 getLLVMStyleWithColumns(47)); 7357 verifyFormat("LoooooongReturnType\n" 7358 "someLoooooooongFunction() const {}", 7359 getLLVMStyleWithColumns(47)); 7360 verifyFormat("LoooooongReturnType someLoooooooongFunction()\n" 7361 " const {}", 7362 Style); 7363 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7364 " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;"); 7365 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7366 " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;"); 7367 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7368 " aaaaa aaaaaaaaaaaaaaaaaaaa) override final;"); 7369 verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n" 7370 " aaaaaaaaaaa aaaaa) const override;"); 7371 verifyGoogleFormat( 7372 "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7373 " const override;"); 7374 7375 // Even if the first parameter has to be wrapped. 7376 verifyFormat("void someLongFunction(\n" 7377 " int someLongParameter) const {}", 7378 getLLVMStyleWithColumns(46)); 7379 verifyFormat("void someLongFunction(\n" 7380 " int someLongParameter) const {}", 7381 Style); 7382 verifyFormat("void someLongFunction(\n" 7383 " int someLongParameter) override {}", 7384 Style); 7385 verifyFormat("void someLongFunction(\n" 7386 " int someLongParameter) OVERRIDE {}", 7387 Style); 7388 verifyFormat("void someLongFunction(\n" 7389 " int someLongParameter) final {}", 7390 Style); 7391 verifyFormat("void someLongFunction(\n" 7392 " int someLongParameter) FINAL {}", 7393 Style); 7394 verifyFormat("void someLongFunction(\n" 7395 " int parameter) const override {}", 7396 Style); 7397 7398 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 7399 verifyFormat("void someLongFunction(\n" 7400 " int someLongParameter) const\n" 7401 "{\n" 7402 "}", 7403 Style); 7404 7405 Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 7406 verifyFormat("void someLongFunction(\n" 7407 " int someLongParameter) const\n" 7408 " {\n" 7409 " }", 7410 Style); 7411 7412 // Unless these are unknown annotations. 7413 verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n" 7414 " aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7415 " LONG_AND_UGLY_ANNOTATION;"); 7416 7417 // Breaking before function-like trailing annotations is fine to keep them 7418 // close to their arguments. 7419 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7420 " LOCKS_EXCLUDED(aaaaaaaaaaaaa);"); 7421 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n" 7422 " LOCKS_EXCLUDED(aaaaaaaaaaaaa);"); 7423 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n" 7424 " LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}"); 7425 verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n" 7426 " AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);"); 7427 verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});"); 7428 7429 verifyFormat( 7430 "void aaaaaaaaaaaaaaaaaa()\n" 7431 " __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n" 7432 " aaaaaaaaaaaaaaaaaaaaaaaaa));"); 7433 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7434 " __attribute__((unused));"); 7435 verifyGoogleFormat( 7436 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7437 " GUARDED_BY(aaaaaaaaaaaa);"); 7438 verifyGoogleFormat( 7439 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7440 " GUARDED_BY(aaaaaaaaaaaa);"); 7441 verifyGoogleFormat( 7442 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n" 7443 " aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7444 verifyGoogleFormat( 7445 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n" 7446 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7447 } 7448 7449 TEST_F(FormatTest, FunctionAnnotations) { 7450 verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7451 "int OldFunction(const string ¶meter) {}"); 7452 verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7453 "string OldFunction(const string ¶meter) {}"); 7454 verifyFormat("template <typename T>\n" 7455 "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7456 "string OldFunction(const string ¶meter) {}"); 7457 7458 // Not function annotations. 7459 verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7460 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"); 7461 verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n" 7462 " ThisIsATestWithAReallyReallyReallyReallyLongName) {}"); 7463 verifyFormat("MACRO(abc).function() // wrap\n" 7464 " << abc;"); 7465 verifyFormat("MACRO(abc)->function() // wrap\n" 7466 " << abc;"); 7467 verifyFormat("MACRO(abc)::function() // wrap\n" 7468 " << abc;"); 7469 } 7470 7471 TEST_F(FormatTest, BreaksDesireably) { 7472 verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n" 7473 " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n" 7474 " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}"); 7475 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7476 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 7477 "}"); 7478 7479 verifyFormat( 7480 "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7481 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 7482 7483 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7484 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7485 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7486 7487 verifyFormat( 7488 "aaaaaaaa(aaaaaaaaaaaaa,\n" 7489 " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7490 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n" 7491 " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7492 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));"); 7493 7494 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 7495 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7496 7497 verifyFormat( 7498 "void f() {\n" 7499 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n" 7500 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 7501 "}"); 7502 verifyFormat( 7503 "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7504 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7505 verifyFormat( 7506 "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7507 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7508 verifyFormat( 7509 "aaaaaa(aaa,\n" 7510 " new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7511 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7512 " aaaa);"); 7513 verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7514 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7515 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7516 7517 // Indent consistently independent of call expression and unary operator. 7518 verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7519 " dddddddddddddddddddddddddddddd));"); 7520 verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7521 " dddddddddddddddddddddddddddddd));"); 7522 verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n" 7523 " dddddddddddddddddddddddddddddd));"); 7524 7525 // This test case breaks on an incorrect memoization, i.e. an optimization not 7526 // taking into account the StopAt value. 7527 verifyFormat( 7528 "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7529 " aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7530 " aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7531 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7532 7533 verifyFormat("{\n {\n {\n" 7534 " Annotation.SpaceRequiredBefore =\n" 7535 " Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n" 7536 " Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n" 7537 " }\n }\n}"); 7538 7539 // Break on an outer level if there was a break on an inner level. 7540 EXPECT_EQ("f(g(h(a, // comment\n" 7541 " b, c),\n" 7542 " d, e),\n" 7543 " x, y);", 7544 format("f(g(h(a, // comment\n" 7545 " b, c), d, e), x, y);")); 7546 7547 // Prefer breaking similar line breaks. 7548 verifyFormat( 7549 "const int kTrackingOptions = NSTrackingMouseMoved |\n" 7550 " NSTrackingMouseEnteredAndExited |\n" 7551 " NSTrackingActiveAlways;"); 7552 } 7553 7554 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) { 7555 FormatStyle NoBinPacking = getGoogleStyle(); 7556 NoBinPacking.BinPackParameters = false; 7557 NoBinPacking.BinPackArguments = true; 7558 verifyFormat("void f() {\n" 7559 " f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n" 7560 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 7561 "}", 7562 NoBinPacking); 7563 verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n" 7564 " int aaaaaaaaaaaaaaaaaaaa,\n" 7565 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7566 NoBinPacking); 7567 7568 NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false; 7569 verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7570 " vector<int> bbbbbbbbbbbbbbb);", 7571 NoBinPacking); 7572 // FIXME: This behavior difference is probably not wanted. However, currently 7573 // we cannot distinguish BreakBeforeParameter being set because of the wrapped 7574 // template arguments from BreakBeforeParameter being set because of the 7575 // one-per-line formatting. 7576 verifyFormat( 7577 "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n" 7578 " aaaaaaaaaa> aaaaaaaaaa);", 7579 NoBinPacking); 7580 verifyFormat( 7581 "void fffffffffff(\n" 7582 " aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n" 7583 " aaaaaaaaaa);"); 7584 } 7585 7586 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) { 7587 FormatStyle NoBinPacking = getGoogleStyle(); 7588 NoBinPacking.BinPackParameters = false; 7589 NoBinPacking.BinPackArguments = false; 7590 verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n" 7591 " aaaaaaaaaaaaaaaaaaaa,\n" 7592 " aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);", 7593 NoBinPacking); 7594 verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n" 7595 " aaaaaaaaaaaaa,\n" 7596 " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));", 7597 NoBinPacking); 7598 verifyFormat( 7599 "aaaaaaaa(aaaaaaaaaaaaa,\n" 7600 " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7601 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n" 7602 " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7603 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));", 7604 NoBinPacking); 7605 verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n" 7606 " .aaaaaaaaaaaaaaaaaa();", 7607 NoBinPacking); 7608 verifyFormat("void f() {\n" 7609 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7610 " aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n" 7611 "}", 7612 NoBinPacking); 7613 7614 verifyFormat( 7615 "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7616 " aaaaaaaaaaaa,\n" 7617 " aaaaaaaaaaaa);", 7618 NoBinPacking); 7619 verifyFormat( 7620 "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n" 7621 " ddddddddddddddddddddddddddddd),\n" 7622 " test);", 7623 NoBinPacking); 7624 7625 verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n" 7626 " aaaaaaaaaaaaaaaaaaaaaaa,\n" 7627 " aaaaaaaaaaaaaaaaaaaaaaa>\n" 7628 " aaaaaaaaaaaaaaaaaa;", 7629 NoBinPacking); 7630 verifyFormat("a(\"a\"\n" 7631 " \"a\",\n" 7632 " a);"); 7633 7634 NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false; 7635 verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n" 7636 " aaaaaaaaa,\n" 7637 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7638 NoBinPacking); 7639 verifyFormat( 7640 "void f() {\n" 7641 " aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n" 7642 " .aaaaaaa();\n" 7643 "}", 7644 NoBinPacking); 7645 verifyFormat( 7646 "template <class SomeType, class SomeOtherType>\n" 7647 "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}", 7648 NoBinPacking); 7649 } 7650 7651 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) { 7652 FormatStyle Style = getLLVMStyleWithColumns(15); 7653 Style.ExperimentalAutoDetectBinPacking = true; 7654 EXPECT_EQ("aaa(aaaa,\n" 7655 " aaaa,\n" 7656 " aaaa);\n" 7657 "aaa(aaaa,\n" 7658 " aaaa,\n" 7659 " aaaa);", 7660 format("aaa(aaaa,\n" // one-per-line 7661 " aaaa,\n" 7662 " aaaa );\n" 7663 "aaa(aaaa, aaaa, aaaa);", // inconclusive 7664 Style)); 7665 EXPECT_EQ("aaa(aaaa, aaaa,\n" 7666 " aaaa);\n" 7667 "aaa(aaaa, aaaa,\n" 7668 " aaaa);", 7669 format("aaa(aaaa, aaaa,\n" // bin-packed 7670 " aaaa );\n" 7671 "aaa(aaaa, aaaa, aaaa);", // inconclusive 7672 Style)); 7673 } 7674 7675 TEST_F(FormatTest, FormatsBuilderPattern) { 7676 verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n" 7677 " .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n" 7678 " .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n" 7679 " .StartsWith(\".init\", ORDER_INIT)\n" 7680 " .StartsWith(\".fini\", ORDER_FINI)\n" 7681 " .StartsWith(\".hash\", ORDER_HASH)\n" 7682 " .Default(ORDER_TEXT);\n"); 7683 7684 verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n" 7685 " aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();"); 7686 verifyFormat("aaaaaaa->aaaaaaa\n" 7687 " ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7688 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7689 " ->aaaaaaaa(aaaaaaaaaaaaaaa);"); 7690 verifyFormat( 7691 "aaaaaaa->aaaaaaa\n" 7692 " ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7693 " ->aaaaaaaa(aaaaaaaaaaaaaaa);"); 7694 verifyFormat( 7695 "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n" 7696 " aaaaaaaaaaaaaa);"); 7697 verifyFormat( 7698 "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n" 7699 " aaaaaa->aaaaaaaaaaaa()\n" 7700 " ->aaaaaaaaaaaaaaaa(\n" 7701 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7702 " ->aaaaaaaaaaaaaaaaa();"); 7703 verifyGoogleFormat( 7704 "void f() {\n" 7705 " someo->Add((new util::filetools::Handler(dir))\n" 7706 " ->OnEvent1(NewPermanentCallback(\n" 7707 " this, &HandlerHolderClass::EventHandlerCBA))\n" 7708 " ->OnEvent2(NewPermanentCallback(\n" 7709 " this, &HandlerHolderClass::EventHandlerCBB))\n" 7710 " ->OnEvent3(NewPermanentCallback(\n" 7711 " this, &HandlerHolderClass::EventHandlerCBC))\n" 7712 " ->OnEvent5(NewPermanentCallback(\n" 7713 " this, &HandlerHolderClass::EventHandlerCBD))\n" 7714 " ->OnEvent6(NewPermanentCallback(\n" 7715 " this, &HandlerHolderClass::EventHandlerCBE)));\n" 7716 "}"); 7717 7718 verifyFormat( 7719 "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();"); 7720 verifyFormat("aaaaaaaaaaaaaaa()\n" 7721 " .aaaaaaaaaaaaaaa()\n" 7722 " .aaaaaaaaaaaaaaa()\n" 7723 " .aaaaaaaaaaaaaaa()\n" 7724 " .aaaaaaaaaaaaaaa();"); 7725 verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7726 " .aaaaaaaaaaaaaaa()\n" 7727 " .aaaaaaaaaaaaaaa()\n" 7728 " .aaaaaaaaaaaaaaa();"); 7729 verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7730 " .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7731 " .aaaaaaaaaaaaaaa();"); 7732 verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n" 7733 " ->aaaaaaaaaaaaaae(0)\n" 7734 " ->aaaaaaaaaaaaaaa();"); 7735 7736 // Don't linewrap after very short segments. 7737 verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7738 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7739 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7740 verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7741 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7742 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7743 verifyFormat("aaa()\n" 7744 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7745 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7746 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7747 7748 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n" 7749 " .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7750 " .has<bbbbbbbbbbbbbbbbbbbbb>();"); 7751 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n" 7752 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 7753 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();"); 7754 7755 // Prefer not to break after empty parentheses. 7756 verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n" 7757 " First->LastNewlineOffset);"); 7758 7759 // Prefer not to create "hanging" indents. 7760 verifyFormat( 7761 "return !soooooooooooooome_map\n" 7762 " .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7763 " .second;"); 7764 verifyFormat( 7765 "return aaaaaaaaaaaaaaaa\n" 7766 " .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n" 7767 " .aaaa(aaaaaaaaaaaaaa);"); 7768 // No hanging indent here. 7769 verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n" 7770 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7771 verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n" 7772 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7773 verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n" 7774 " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7775 getLLVMStyleWithColumns(60)); 7776 verifyFormat("aaaaaaaaaaaaaaaaaa\n" 7777 " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n" 7778 " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7779 getLLVMStyleWithColumns(59)); 7780 verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7781 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7782 " .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7783 7784 // Dont break if only closing statements before member call 7785 verifyFormat("test() {\n" 7786 " ([]() -> {\n" 7787 " int b = 32;\n" 7788 " return 3;\n" 7789 " }).foo();\n" 7790 "}"); 7791 verifyFormat("test() {\n" 7792 " (\n" 7793 " []() -> {\n" 7794 " int b = 32;\n" 7795 " return 3;\n" 7796 " },\n" 7797 " foo, bar)\n" 7798 " .foo();\n" 7799 "}"); 7800 verifyFormat("test() {\n" 7801 " ([]() -> {\n" 7802 " int b = 32;\n" 7803 " return 3;\n" 7804 " })\n" 7805 " .foo()\n" 7806 " .bar();\n" 7807 "}"); 7808 verifyFormat("test() {\n" 7809 " ([]() -> {\n" 7810 " int b = 32;\n" 7811 " return 3;\n" 7812 " })\n" 7813 " .foo(\"aaaaaaaaaaaaaaaaa\"\n" 7814 " \"bbbb\");\n" 7815 "}", 7816 getLLVMStyleWithColumns(30)); 7817 } 7818 7819 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) { 7820 verifyFormat( 7821 "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 7822 " bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}"); 7823 verifyFormat( 7824 "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n" 7825 " bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}"); 7826 7827 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" 7828 " ccccccccccccccccccccccccc) {\n}"); 7829 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n" 7830 " ccccccccccccccccccccccccc) {\n}"); 7831 7832 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" 7833 " ccccccccccccccccccccccccc) {\n}"); 7834 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n" 7835 " ccccccccccccccccccccccccc) {\n}"); 7836 7837 verifyFormat( 7838 "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n" 7839 " ccccccccccccccccccccccccc) {\n}"); 7840 verifyFormat( 7841 "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n" 7842 " ccccccccccccccccccccccccc) {\n}"); 7843 7844 verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n" 7845 " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n" 7846 " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n" 7847 " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;"); 7848 verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n" 7849 " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n" 7850 " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n" 7851 " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;"); 7852 7853 verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n" 7854 " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n" 7855 " aaaaaaaaaaaaaaa != aa) {\n}"); 7856 verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n" 7857 " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n" 7858 " aaaaaaaaaaaaaaa != aa) {\n}"); 7859 } 7860 7861 TEST_F(FormatTest, BreaksAfterAssignments) { 7862 verifyFormat( 7863 "unsigned Cost =\n" 7864 " TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n" 7865 " SI->getPointerAddressSpaceee());\n"); 7866 verifyFormat( 7867 "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n" 7868 " Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());"); 7869 7870 verifyFormat( 7871 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n" 7872 " aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);"); 7873 verifyFormat("unsigned OriginalStartColumn =\n" 7874 " SourceMgr.getSpellingColumnNumber(\n" 7875 " Current.FormatTok.getStartOfNonWhitespace()) -\n" 7876 " 1;"); 7877 } 7878 7879 TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) { 7880 FormatStyle Style = getLLVMStyle(); 7881 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 7882 " bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;", 7883 Style); 7884 7885 Style.PenaltyBreakAssignment = 20; 7886 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n" 7887 " cccccccccccccccccccccccccc;", 7888 Style); 7889 } 7890 7891 TEST_F(FormatTest, AlignsAfterAssignments) { 7892 verifyFormat( 7893 "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7894 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7895 verifyFormat( 7896 "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7897 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7898 verifyFormat( 7899 "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7900 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7901 verifyFormat( 7902 "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7903 " aaaaaaaaaaaaaaaaaaaaaaaaa);"); 7904 verifyFormat( 7905 "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n" 7906 " aaaaaaaaaaaaaaaaaaaaaaaa +\n" 7907 " aaaaaaaaaaaaaaaaaaaaaaaa;"); 7908 } 7909 7910 TEST_F(FormatTest, AlignsAfterReturn) { 7911 verifyFormat( 7912 "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7913 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7914 verifyFormat( 7915 "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7916 " aaaaaaaaaaaaaaaaaaaaaaaaa);"); 7917 verifyFormat( 7918 "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n" 7919 " aaaaaaaaaaaaaaaaaaaaaa();"); 7920 verifyFormat( 7921 "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n" 7922 " aaaaaaaaaaaaaaaaaaaaaa());"); 7923 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7924 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7925 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7926 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n" 7927 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7928 verifyFormat("return\n" 7929 " // true if code is one of a or b.\n" 7930 " code == a || code == b;"); 7931 } 7932 7933 TEST_F(FormatTest, AlignsAfterOpenBracket) { 7934 verifyFormat( 7935 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n" 7936 " aaaaaaaaa aaaaaaa) {}"); 7937 verifyFormat( 7938 "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n" 7939 " aaaaaaaaaaa aaaaaaaaa);"); 7940 verifyFormat( 7941 "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n" 7942 " aaaaaaaaaaaaaaaaaaaaa));"); 7943 FormatStyle Style = getLLVMStyle(); 7944 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 7945 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7946 " aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}", 7947 Style); 7948 verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n" 7949 " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);", 7950 Style); 7951 verifyFormat("SomeLongVariableName->someFunction(\n" 7952 " foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));", 7953 Style); 7954 verifyFormat( 7955 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n" 7956 " aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7957 Style); 7958 verifyFormat( 7959 "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n" 7960 " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7961 Style); 7962 verifyFormat( 7963 "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n" 7964 " aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));", 7965 Style); 7966 7967 verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n" 7968 " ccccccc(aaaaaaaaaaaaaaaaa, //\n" 7969 " b));", 7970 Style); 7971 7972 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 7973 Style.BinPackArguments = false; 7974 Style.BinPackParameters = false; 7975 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7976 " aaaaaaaaaaa aaaaaaaa,\n" 7977 " aaaaaaaaa aaaaaaa,\n" 7978 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7979 Style); 7980 verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n" 7981 " aaaaaaaaaaa aaaaaaaaa,\n" 7982 " aaaaaaaaaaa aaaaaaaaa,\n" 7983 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7984 Style); 7985 verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n" 7986 " aaaaaaaaaaaaaaa,\n" 7987 " aaaaaaaaaaaaaaaaaaaaa,\n" 7988 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));", 7989 Style); 7990 verifyFormat( 7991 "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n" 7992 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));", 7993 Style); 7994 verifyFormat( 7995 "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n" 7996 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));", 7997 Style); 7998 verifyFormat( 7999 "aaaaaaaaaaaaaaaaaaaaaaaa(\n" 8000 " aaaaaaaaaaaaaaaaaaaaa(\n" 8001 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n" 8002 " aaaaaaaaaaaaaaaa);", 8003 Style); 8004 verifyFormat( 8005 "aaaaaaaaaaaaaaaaaaaaaaaa(\n" 8006 " aaaaaaaaaaaaaaaaaaaaa(\n" 8007 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n" 8008 " aaaaaaaaaaaaaaaa);", 8009 Style); 8010 } 8011 8012 TEST_F(FormatTest, ParenthesesAndOperandAlignment) { 8013 FormatStyle Style = getLLVMStyleWithColumns(40); 8014 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 8015 " bbbbbbbbbbbbbbbbbbbbbb);", 8016 Style); 8017 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 8018 Style.AlignOperands = FormatStyle::OAS_DontAlign; 8019 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 8020 " bbbbbbbbbbbbbbbbbbbbbb);", 8021 Style); 8022 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 8023 Style.AlignOperands = FormatStyle::OAS_Align; 8024 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 8025 " bbbbbbbbbbbbbbbbbbbbbb);", 8026 Style); 8027 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 8028 Style.AlignOperands = FormatStyle::OAS_DontAlign; 8029 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 8030 " bbbbbbbbbbbbbbbbbbbbbb);", 8031 Style); 8032 } 8033 8034 TEST_F(FormatTest, BreaksConditionalExpressions) { 8035 verifyFormat( 8036 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8037 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8038 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8039 verifyFormat( 8040 "aaaa(aaaaaaaaaa, aaaaaaaa,\n" 8041 " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8042 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8043 verifyFormat( 8044 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8045 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8046 verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n" 8047 " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8048 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8049 verifyFormat( 8050 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n" 8051 " : aaaaaaaaaaaaa);"); 8052 verifyFormat( 8053 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8054 " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8055 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8056 " aaaaaaaaaaaaa);"); 8057 verifyFormat( 8058 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8059 " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8060 " aaaaaaaaaaaaa);"); 8061 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8062 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8063 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8064 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8065 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8066 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8067 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8068 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8069 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8070 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8071 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8072 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8073 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8074 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8075 " ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8076 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8077 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8078 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8079 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8080 " : aaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8081 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n" 8082 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8083 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8084 " : aaaaaaaaaaaaaaaa;"); 8085 verifyFormat( 8086 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8087 " ? aaaaaaaaaaaaaaa\n" 8088 " : aaaaaaaaaaaaaaa;"); 8089 verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n" 8090 " aaaaaaaaa\n" 8091 " ? b\n" 8092 " : c);"); 8093 verifyFormat("return aaaa == bbbb\n" 8094 " // comment\n" 8095 " ? aaaa\n" 8096 " : bbbb;"); 8097 verifyFormat("unsigned Indent =\n" 8098 " format(TheLine.First,\n" 8099 " IndentForLevel[TheLine.Level] >= 0\n" 8100 " ? IndentForLevel[TheLine.Level]\n" 8101 " : TheLine * 2,\n" 8102 " TheLine.InPPDirective, PreviousEndOfLineColumn);", 8103 getLLVMStyleWithColumns(60)); 8104 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n" 8105 " ? aaaaaaaaaaaaaaa\n" 8106 " : bbbbbbbbbbbbbbb //\n" 8107 " ? ccccccccccccccc\n" 8108 " : ddddddddddddddd;"); 8109 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n" 8110 " ? aaaaaaaaaaaaaaa\n" 8111 " : (bbbbbbbbbbbbbbb //\n" 8112 " ? ccccccccccccccc\n" 8113 " : ddddddddddddddd);"); 8114 verifyFormat( 8115 "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8116 " ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 8117 " aaaaaaaaaaaaaaaaaaaaa +\n" 8118 " aaaaaaaaaaaaaaaaaaaaa\n" 8119 " : aaaaaaaaaa;"); 8120 verifyFormat( 8121 "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8122 " : aaaaaaaaaaaaaaaaaaaaaa\n" 8123 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8124 8125 FormatStyle NoBinPacking = getLLVMStyle(); 8126 NoBinPacking.BinPackArguments = false; 8127 verifyFormat( 8128 "void f() {\n" 8129 " g(aaa,\n" 8130 " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n" 8131 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8132 " ? aaaaaaaaaaaaaaa\n" 8133 " : aaaaaaaaaaaaaaa);\n" 8134 "}", 8135 NoBinPacking); 8136 verifyFormat( 8137 "void f() {\n" 8138 " g(aaa,\n" 8139 " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n" 8140 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8141 " ?: aaaaaaaaaaaaaaa);\n" 8142 "}", 8143 NoBinPacking); 8144 8145 verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n" 8146 " // comment.\n" 8147 " ccccccccccccccccccccccccccccccccccccccc\n" 8148 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8149 " : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);"); 8150 8151 // Assignments in conditional expressions. Apparently not uncommon :-(. 8152 verifyFormat("return a != b\n" 8153 " // comment\n" 8154 " ? a = b\n" 8155 " : a = b;"); 8156 verifyFormat("return a != b\n" 8157 " // comment\n" 8158 " ? a = a != b\n" 8159 " // comment\n" 8160 " ? a = b\n" 8161 " : a\n" 8162 " : a;\n"); 8163 verifyFormat("return a != b\n" 8164 " // comment\n" 8165 " ? a\n" 8166 " : a = a != b\n" 8167 " // comment\n" 8168 " ? a = b\n" 8169 " : a;"); 8170 8171 // Chained conditionals 8172 FormatStyle Style = getLLVMStyleWithColumns(70); 8173 Style.AlignOperands = FormatStyle::OAS_Align; 8174 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8175 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8176 " : 3333333333333333;", 8177 Style); 8178 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8179 " : bbbbbbbbbb ? 2222222222222222\n" 8180 " : 3333333333333333;", 8181 Style); 8182 verifyFormat("return aaaaaaaaaa ? 1111111111111111\n" 8183 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 8184 " : 3333333333333333;", 8185 Style); 8186 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8187 " : bbbbbbbbbbbbbb ? 222222\n" 8188 " : 333333;", 8189 Style); 8190 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8191 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8192 " : cccccccccccccc ? 3333333333333333\n" 8193 " : 4444444444444444;", 8194 Style); 8195 verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc)\n" 8196 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8197 " : 3333333333333333;", 8198 Style); 8199 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8200 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8201 " : (aaa ? bbb : ccc);", 8202 Style); 8203 verifyFormat( 8204 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8205 " : cccccccccccccccccc)\n" 8206 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8207 " : 3333333333333333;", 8208 Style); 8209 verifyFormat( 8210 "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8211 " : cccccccccccccccccc)\n" 8212 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8213 " : 3333333333333333;", 8214 Style); 8215 verifyFormat( 8216 "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8217 " : dddddddddddddddddd)\n" 8218 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8219 " : 3333333333333333;", 8220 Style); 8221 verifyFormat( 8222 "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8223 " : dddddddddddddddddd)\n" 8224 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8225 " : 3333333333333333;", 8226 Style); 8227 verifyFormat( 8228 "return aaaaaaaaa ? 1111111111111111\n" 8229 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8230 " : a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8231 " : dddddddddddddddddd)\n", 8232 Style); 8233 verifyFormat( 8234 "return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8235 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8236 " : (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8237 " : cccccccccccccccccc);", 8238 Style); 8239 verifyFormat( 8240 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8241 " : ccccccccccccccc ? dddddddddddddddddd\n" 8242 " : eeeeeeeeeeeeeeeeee)\n" 8243 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8244 " : 3333333333333333;", 8245 Style); 8246 verifyFormat( 8247 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8248 " : ccccccccccccccc ? dddddddddddddddddd\n" 8249 " : eeeeeeeeeeeeeeeeee)\n" 8250 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8251 " : 3333333333333333;", 8252 Style); 8253 verifyFormat( 8254 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8255 " : cccccccccccc ? dddddddddddddddddd\n" 8256 " : eeeeeeeeeeeeeeeeee)\n" 8257 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8258 " : 3333333333333333;", 8259 Style); 8260 verifyFormat( 8261 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8262 " : cccccccccccccccccc\n" 8263 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8264 " : 3333333333333333;", 8265 Style); 8266 verifyFormat( 8267 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8268 " : cccccccccccccccc ? dddddddddddddddddd\n" 8269 " : eeeeeeeeeeeeeeeeee\n" 8270 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8271 " : 3333333333333333;", 8272 Style); 8273 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa\n" 8274 " ? (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8275 " : cccccccccccccccccc ? dddddddddddddddddd\n" 8276 " : eeeeeeeeeeeeeeeeee)\n" 8277 " : bbbbbbbbbbbbbbbbbbb ? 2222222222222222\n" 8278 " : 3333333333333333;", 8279 Style); 8280 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaa\n" 8281 " ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8282 " : cccccccccccccccc ? dddddddddddddddddd\n" 8283 " : eeeeeeeeeeeeeeeeee\n" 8284 " : bbbbbbbbbbbbbbbbbbbbbbb ? 2222222222222222\n" 8285 " : 3333333333333333;", 8286 Style); 8287 8288 Style.AlignOperands = FormatStyle::OAS_DontAlign; 8289 Style.BreakBeforeTernaryOperators = false; 8290 // FIXME: Aligning the question marks is weird given DontAlign. 8291 // Consider disabling this alignment in this case. Also check whether this 8292 // will render the adjustment from https://reviews.llvm.org/D82199 8293 // unnecessary. 8294 verifyFormat("int x = aaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa :\n" 8295 " bbbb ? cccccccccccccccccc :\n" 8296 " ddddd;\n", 8297 Style); 8298 8299 EXPECT_EQ( 8300 "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n" 8301 " /*\n" 8302 " */\n" 8303 " function() {\n" 8304 " try {\n" 8305 " return JJJJJJJJJJJJJJ(\n" 8306 " pppppppppppppppppppppppppppppppppppppppppppppppppp);\n" 8307 " }\n" 8308 " } :\n" 8309 " function() {};", 8310 format( 8311 "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n" 8312 " /*\n" 8313 " */\n" 8314 " function() {\n" 8315 " try {\n" 8316 " return JJJJJJJJJJJJJJ(\n" 8317 " pppppppppppppppppppppppppppppppppppppppppppppppppp);\n" 8318 " }\n" 8319 " } :\n" 8320 " function() {};", 8321 getGoogleStyle(FormatStyle::LK_JavaScript))); 8322 } 8323 8324 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) { 8325 FormatStyle Style = getLLVMStyleWithColumns(70); 8326 Style.BreakBeforeTernaryOperators = false; 8327 verifyFormat( 8328 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8329 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8330 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8331 Style); 8332 verifyFormat( 8333 "aaaa(aaaaaaaaaa, aaaaaaaa,\n" 8334 " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8335 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8336 Style); 8337 verifyFormat( 8338 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8339 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8340 Style); 8341 verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n" 8342 " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8343 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8344 Style); 8345 verifyFormat( 8346 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n" 8347 " aaaaaaaaaaaaa);", 8348 Style); 8349 verifyFormat( 8350 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8351 " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8352 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8353 " aaaaaaaaaaaaa);", 8354 Style); 8355 verifyFormat( 8356 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8357 " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8358 " aaaaaaaaaaaaa);", 8359 Style); 8360 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8361 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8362 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 8363 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8364 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8365 Style); 8366 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8367 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8368 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8369 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 8370 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8371 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8372 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8373 Style); 8374 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8375 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n" 8376 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8377 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8378 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8379 Style); 8380 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8381 " aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8382 " aaaaaaaaaaaaaaaaaaaaaaaaaaa;", 8383 Style); 8384 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n" 8385 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8386 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8387 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 8388 Style); 8389 verifyFormat( 8390 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8391 " aaaaaaaaaaaaaaa :\n" 8392 " aaaaaaaaaaaaaaa;", 8393 Style); 8394 verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n" 8395 " aaaaaaaaa ?\n" 8396 " b :\n" 8397 " c);", 8398 Style); 8399 verifyFormat("unsigned Indent =\n" 8400 " format(TheLine.First,\n" 8401 " IndentForLevel[TheLine.Level] >= 0 ?\n" 8402 " IndentForLevel[TheLine.Level] :\n" 8403 " TheLine * 2,\n" 8404 " TheLine.InPPDirective, PreviousEndOfLineColumn);", 8405 Style); 8406 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n" 8407 " aaaaaaaaaaaaaaa :\n" 8408 " bbbbbbbbbbbbbbb ? //\n" 8409 " ccccccccccccccc :\n" 8410 " ddddddddddddddd;", 8411 Style); 8412 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n" 8413 " aaaaaaaaaaaaaaa :\n" 8414 " (bbbbbbbbbbbbbbb ? //\n" 8415 " ccccccccccccccc :\n" 8416 " ddddddddddddddd);", 8417 Style); 8418 verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8419 " /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n" 8420 " ccccccccccccccccccccccccccc;", 8421 Style); 8422 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8423 " aaaaa :\n" 8424 " bbbbbbbbbbbbbbb + cccccccccccccccc;", 8425 Style); 8426 8427 // Chained conditionals 8428 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8429 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8430 " 3333333333333333;", 8431 Style); 8432 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8433 " bbbbbbbbbb ? 2222222222222222 :\n" 8434 " 3333333333333333;", 8435 Style); 8436 verifyFormat("return aaaaaaaaaa ? 1111111111111111 :\n" 8437 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8438 " 3333333333333333;", 8439 Style); 8440 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8441 " bbbbbbbbbbbbbbbb ? 222222 :\n" 8442 " 333333;", 8443 Style); 8444 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8445 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8446 " cccccccccccccccc ? 3333333333333333 :\n" 8447 " 4444444444444444;", 8448 Style); 8449 verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc) :\n" 8450 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8451 " 3333333333333333;", 8452 Style); 8453 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8454 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8455 " (aaa ? bbb : ccc);", 8456 Style); 8457 verifyFormat( 8458 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8459 " cccccccccccccccccc) :\n" 8460 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8461 " 3333333333333333;", 8462 Style); 8463 verifyFormat( 8464 "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8465 " cccccccccccccccccc) :\n" 8466 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8467 " 3333333333333333;", 8468 Style); 8469 verifyFormat( 8470 "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8471 " dddddddddddddddddd) :\n" 8472 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8473 " 3333333333333333;", 8474 Style); 8475 verifyFormat( 8476 "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8477 " dddddddddddddddddd) :\n" 8478 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8479 " 3333333333333333;", 8480 Style); 8481 verifyFormat( 8482 "return aaaaaaaaa ? 1111111111111111 :\n" 8483 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8484 " a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8485 " dddddddddddddddddd)\n", 8486 Style); 8487 verifyFormat( 8488 "return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8489 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8490 " (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8491 " cccccccccccccccccc);", 8492 Style); 8493 verifyFormat( 8494 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8495 " ccccccccccccccccc ? dddddddddddddddddd :\n" 8496 " eeeeeeeeeeeeeeeeee) :\n" 8497 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8498 " 3333333333333333;", 8499 Style); 8500 verifyFormat( 8501 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8502 " ccccccccccccc ? dddddddddddddddddd :\n" 8503 " eeeeeeeeeeeeeeeeee) :\n" 8504 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8505 " 3333333333333333;", 8506 Style); 8507 verifyFormat( 8508 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8509 " ccccccccccccccccc ? dddddddddddddddddd :\n" 8510 " eeeeeeeeeeeeeeeeee) :\n" 8511 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8512 " 3333333333333333;", 8513 Style); 8514 verifyFormat( 8515 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8516 " cccccccccccccccccc :\n" 8517 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8518 " 3333333333333333;", 8519 Style); 8520 verifyFormat( 8521 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8522 " cccccccccccccccccc ? dddddddddddddddddd :\n" 8523 " eeeeeeeeeeeeeeeeee :\n" 8524 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8525 " 3333333333333333;", 8526 Style); 8527 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n" 8528 " (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8529 " cccccccccccccccccc ? dddddddddddddddddd :\n" 8530 " eeeeeeeeeeeeeeeeee) :\n" 8531 " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8532 " 3333333333333333;", 8533 Style); 8534 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n" 8535 " aaaaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8536 " cccccccccccccccccccc ? dddddddddddddddddd :\n" 8537 " eeeeeeeeeeeeeeeeee :\n" 8538 " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8539 " 3333333333333333;", 8540 Style); 8541 } 8542 8543 TEST_F(FormatTest, DeclarationsOfMultipleVariables) { 8544 verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n" 8545 " aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();"); 8546 verifyFormat("bool a = true, b = false;"); 8547 8548 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n" 8549 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n" 8550 " bbbbbbbbbbbbbbbbbbbbbbbbb =\n" 8551 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);"); 8552 verifyFormat( 8553 "bool aaaaaaaaaaaaaaaaaaaaa =\n" 8554 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n" 8555 " d = e && f;"); 8556 verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n" 8557 " c = cccccccccccccccccccc, d = dddddddddddddddddddd;"); 8558 verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n" 8559 " *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;"); 8560 verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n" 8561 " ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;"); 8562 8563 FormatStyle Style = getGoogleStyle(); 8564 Style.PointerAlignment = FormatStyle::PAS_Left; 8565 Style.DerivePointerAlignment = false; 8566 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8567 " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n" 8568 " *b = bbbbbbbbbbbbbbbbbbb;", 8569 Style); 8570 verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n" 8571 " *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;", 8572 Style); 8573 verifyFormat("vector<int*> a, b;", Style); 8574 verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style); 8575 verifyFormat("/*comment*/ for (int *p, *q; p != q; p = p->next) {\n}", Style); 8576 verifyFormat("if (int *p, *q; p != q) {\n p = p->next;\n}", Style); 8577 verifyFormat("/*comment*/ if (int *p, *q; p != q) {\n p = p->next;\n}", 8578 Style); 8579 verifyFormat("switch (int *p, *q; p != q) {\n default:\n break;\n}", 8580 Style); 8581 verifyFormat( 8582 "/*comment*/ switch (int *p, *q; p != q) {\n default:\n break;\n}", 8583 Style); 8584 8585 verifyFormat("if ([](int* p, int* q) {}()) {\n}", Style); 8586 verifyFormat("for ([](int* p, int* q) {}();;) {\n}", Style); 8587 verifyFormat("for (; [](int* p, int* q) {}();) {\n}", Style); 8588 verifyFormat("for (;; [](int* p, int* q) {}()) {\n}", Style); 8589 verifyFormat("switch ([](int* p, int* q) {}()) {\n default:\n break;\n}", 8590 Style); 8591 } 8592 8593 TEST_F(FormatTest, ConditionalExpressionsInBrackets) { 8594 verifyFormat("arr[foo ? bar : baz];"); 8595 verifyFormat("f()[foo ? bar : baz];"); 8596 verifyFormat("(a + b)[foo ? bar : baz];"); 8597 verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];"); 8598 } 8599 8600 TEST_F(FormatTest, AlignsStringLiterals) { 8601 verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n" 8602 " \"short literal\");"); 8603 verifyFormat( 8604 "looooooooooooooooooooooooongFunction(\n" 8605 " \"short literal\"\n" 8606 " \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");"); 8607 verifyFormat("someFunction(\"Always break between multi-line\"\n" 8608 " \" string literals\",\n" 8609 " and, other, parameters);"); 8610 EXPECT_EQ("fun + \"1243\" /* comment */\n" 8611 " \"5678\";", 8612 format("fun + \"1243\" /* comment */\n" 8613 " \"5678\";", 8614 getLLVMStyleWithColumns(28))); 8615 EXPECT_EQ( 8616 "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 8617 " \"aaaaaaaaaaaaaaaaaaaaa\"\n" 8618 " \"aaaaaaaaaaaaaaaa\";", 8619 format("aaaaaa =" 8620 "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa " 8621 "aaaaaaaaaaaaaaaaaaaaa\" " 8622 "\"aaaaaaaaaaaaaaaa\";")); 8623 verifyFormat("a = a + \"a\"\n" 8624 " \"a\"\n" 8625 " \"a\";"); 8626 verifyFormat("f(\"a\", \"b\"\n" 8627 " \"c\");"); 8628 8629 verifyFormat( 8630 "#define LL_FORMAT \"ll\"\n" 8631 "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n" 8632 " \"d, ddddddddd: %\" LL_FORMAT \"d\");"); 8633 8634 verifyFormat("#define A(X) \\\n" 8635 " \"aaaaa\" #X \"bbbbbb\" \\\n" 8636 " \"ccccc\"", 8637 getLLVMStyleWithColumns(23)); 8638 verifyFormat("#define A \"def\"\n" 8639 "f(\"abc\" A \"ghi\"\n" 8640 " \"jkl\");"); 8641 8642 verifyFormat("f(L\"a\"\n" 8643 " L\"b\");"); 8644 verifyFormat("#define A(X) \\\n" 8645 " L\"aaaaa\" #X L\"bbbbbb\" \\\n" 8646 " L\"ccccc\"", 8647 getLLVMStyleWithColumns(25)); 8648 8649 verifyFormat("f(@\"a\"\n" 8650 " @\"b\");"); 8651 verifyFormat("NSString s = @\"a\"\n" 8652 " @\"b\"\n" 8653 " @\"c\";"); 8654 verifyFormat("NSString s = @\"a\"\n" 8655 " \"b\"\n" 8656 " \"c\";"); 8657 } 8658 8659 TEST_F(FormatTest, ReturnTypeBreakingStyle) { 8660 FormatStyle Style = getLLVMStyle(); 8661 // No declarations or definitions should be moved to own line. 8662 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None; 8663 verifyFormat("class A {\n" 8664 " int f() { return 1; }\n" 8665 " int g();\n" 8666 "};\n" 8667 "int f() { return 1; }\n" 8668 "int g();\n", 8669 Style); 8670 8671 // All declarations and definitions should have the return type moved to its 8672 // own line. 8673 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 8674 Style.TypenameMacros = {"LIST"}; 8675 verifyFormat("SomeType\n" 8676 "funcdecl(LIST(uint64_t));", 8677 Style); 8678 verifyFormat("class E {\n" 8679 " int\n" 8680 " f() {\n" 8681 " return 1;\n" 8682 " }\n" 8683 " int\n" 8684 " g();\n" 8685 "};\n" 8686 "int\n" 8687 "f() {\n" 8688 " return 1;\n" 8689 "}\n" 8690 "int\n" 8691 "g();\n", 8692 Style); 8693 8694 // Top-level definitions, and no kinds of declarations should have the 8695 // return type moved to its own line. 8696 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions; 8697 verifyFormat("class B {\n" 8698 " int f() { return 1; }\n" 8699 " int g();\n" 8700 "};\n" 8701 "int\n" 8702 "f() {\n" 8703 " return 1;\n" 8704 "}\n" 8705 "int g();\n", 8706 Style); 8707 8708 // Top-level definitions and declarations should have the return type moved 8709 // to its own line. 8710 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel; 8711 verifyFormat("class C {\n" 8712 " int f() { return 1; }\n" 8713 " int g();\n" 8714 "};\n" 8715 "int\n" 8716 "f() {\n" 8717 " return 1;\n" 8718 "}\n" 8719 "int\n" 8720 "g();\n", 8721 Style); 8722 8723 // All definitions should have the return type moved to its own line, but no 8724 // kinds of declarations. 8725 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions; 8726 verifyFormat("class D {\n" 8727 " int\n" 8728 " f() {\n" 8729 " return 1;\n" 8730 " }\n" 8731 " int g();\n" 8732 "};\n" 8733 "int\n" 8734 "f() {\n" 8735 " return 1;\n" 8736 "}\n" 8737 "int g();\n", 8738 Style); 8739 verifyFormat("const char *\n" 8740 "f(void) {\n" // Break here. 8741 " return \"\";\n" 8742 "}\n" 8743 "const char *bar(void);\n", // No break here. 8744 Style); 8745 verifyFormat("template <class T>\n" 8746 "T *\n" 8747 "f(T &c) {\n" // Break here. 8748 " return NULL;\n" 8749 "}\n" 8750 "template <class T> T *f(T &c);\n", // No break here. 8751 Style); 8752 verifyFormat("class C {\n" 8753 " int\n" 8754 " operator+() {\n" 8755 " return 1;\n" 8756 " }\n" 8757 " int\n" 8758 " operator()() {\n" 8759 " return 1;\n" 8760 " }\n" 8761 "};\n", 8762 Style); 8763 verifyFormat("void\n" 8764 "A::operator()() {}\n" 8765 "void\n" 8766 "A::operator>>() {}\n" 8767 "void\n" 8768 "A::operator+() {}\n" 8769 "void\n" 8770 "A::operator*() {}\n" 8771 "void\n" 8772 "A::operator->() {}\n" 8773 "void\n" 8774 "A::operator void *() {}\n" 8775 "void\n" 8776 "A::operator void &() {}\n" 8777 "void\n" 8778 "A::operator void &&() {}\n" 8779 "void\n" 8780 "A::operator char *() {}\n" 8781 "void\n" 8782 "A::operator[]() {}\n" 8783 "void\n" 8784 "A::operator!() {}\n" 8785 "void\n" 8786 "A::operator**() {}\n" 8787 "void\n" 8788 "A::operator<Foo> *() {}\n" 8789 "void\n" 8790 "A::operator<Foo> **() {}\n" 8791 "void\n" 8792 "A::operator<Foo> &() {}\n" 8793 "void\n" 8794 "A::operator void **() {}\n", 8795 Style); 8796 verifyFormat("constexpr auto\n" 8797 "operator()() const -> reference {}\n" 8798 "constexpr auto\n" 8799 "operator>>() const -> reference {}\n" 8800 "constexpr auto\n" 8801 "operator+() const -> reference {}\n" 8802 "constexpr auto\n" 8803 "operator*() const -> reference {}\n" 8804 "constexpr auto\n" 8805 "operator->() const -> reference {}\n" 8806 "constexpr auto\n" 8807 "operator++() const -> reference {}\n" 8808 "constexpr auto\n" 8809 "operator void *() const -> reference {}\n" 8810 "constexpr auto\n" 8811 "operator void **() const -> reference {}\n" 8812 "constexpr auto\n" 8813 "operator void *() const -> reference {}\n" 8814 "constexpr auto\n" 8815 "operator void &() const -> reference {}\n" 8816 "constexpr auto\n" 8817 "operator void &&() const -> reference {}\n" 8818 "constexpr auto\n" 8819 "operator char *() const -> reference {}\n" 8820 "constexpr auto\n" 8821 "operator!() const -> reference {}\n" 8822 "constexpr auto\n" 8823 "operator[]() const -> reference {}\n", 8824 Style); 8825 verifyFormat("void *operator new(std::size_t s);", // No break here. 8826 Style); 8827 verifyFormat("void *\n" 8828 "operator new(std::size_t s) {}", 8829 Style); 8830 verifyFormat("void *\n" 8831 "operator delete[](void *ptr) {}", 8832 Style); 8833 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 8834 verifyFormat("const char *\n" 8835 "f(void)\n" // Break here. 8836 "{\n" 8837 " return \"\";\n" 8838 "}\n" 8839 "const char *bar(void);\n", // No break here. 8840 Style); 8841 verifyFormat("template <class T>\n" 8842 "T *\n" // Problem here: no line break 8843 "f(T &c)\n" // Break here. 8844 "{\n" 8845 " return NULL;\n" 8846 "}\n" 8847 "template <class T> T *f(T &c);\n", // No break here. 8848 Style); 8849 verifyFormat("int\n" 8850 "foo(A<bool> a)\n" 8851 "{\n" 8852 " return a;\n" 8853 "}\n", 8854 Style); 8855 verifyFormat("int\n" 8856 "foo(A<8> a)\n" 8857 "{\n" 8858 " return a;\n" 8859 "}\n", 8860 Style); 8861 verifyFormat("int\n" 8862 "foo(A<B<bool>, 8> a)\n" 8863 "{\n" 8864 " return a;\n" 8865 "}\n", 8866 Style); 8867 verifyFormat("int\n" 8868 "foo(A<B<8>, bool> a)\n" 8869 "{\n" 8870 " return a;\n" 8871 "}\n", 8872 Style); 8873 verifyFormat("int\n" 8874 "foo(A<B<bool>, bool> a)\n" 8875 "{\n" 8876 " return a;\n" 8877 "}\n", 8878 Style); 8879 verifyFormat("int\n" 8880 "foo(A<B<8>, 8> a)\n" 8881 "{\n" 8882 " return a;\n" 8883 "}\n", 8884 Style); 8885 8886 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 8887 Style.BraceWrapping.AfterFunction = true; 8888 verifyFormat("int f(i);\n" // No break here. 8889 "int\n" // Break here. 8890 "f(i)\n" 8891 "{\n" 8892 " return i + 1;\n" 8893 "}\n" 8894 "int\n" // Break here. 8895 "f(i)\n" 8896 "{\n" 8897 " return i + 1;\n" 8898 "};", 8899 Style); 8900 verifyFormat("int f(a, b, c);\n" // No break here. 8901 "int\n" // Break here. 8902 "f(a, b, c)\n" // Break here. 8903 "short a, b;\n" 8904 "float c;\n" 8905 "{\n" 8906 " return a + b < c;\n" 8907 "}\n" 8908 "int\n" // Break here. 8909 "f(a, b, c)\n" // Break here. 8910 "short a, b;\n" 8911 "float c;\n" 8912 "{\n" 8913 " return a + b < c;\n" 8914 "};", 8915 Style); 8916 verifyFormat("byte *\n" // Break here. 8917 "f(a)\n" // Break here. 8918 "byte a[];\n" 8919 "{\n" 8920 " return a;\n" 8921 "}", 8922 Style); 8923 verifyFormat("bool f(int a, int) override;\n" 8924 "Bar g(int a, Bar) final;\n" 8925 "Bar h(a, Bar) final;", 8926 Style); 8927 verifyFormat("int\n" 8928 "f(a)", 8929 Style); 8930 verifyFormat("bool\n" 8931 "f(size_t = 0, bool b = false)\n" 8932 "{\n" 8933 " return !b;\n" 8934 "}", 8935 Style); 8936 8937 // The return breaking style doesn't affect: 8938 // * function and object definitions with attribute-like macros 8939 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 8940 " ABSL_GUARDED_BY(mutex) = {};", 8941 getGoogleStyleWithColumns(40)); 8942 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 8943 " ABSL_GUARDED_BY(mutex); // comment", 8944 getGoogleStyleWithColumns(40)); 8945 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 8946 " ABSL_GUARDED_BY(mutex1)\n" 8947 " ABSL_GUARDED_BY(mutex2);", 8948 getGoogleStyleWithColumns(40)); 8949 verifyFormat("Tttttt f(int a, int b)\n" 8950 " ABSL_GUARDED_BY(mutex1)\n" 8951 " ABSL_GUARDED_BY(mutex2);", 8952 getGoogleStyleWithColumns(40)); 8953 // * typedefs 8954 verifyFormat("typedef ATTR(X) char x;", getGoogleStyle()); 8955 8956 Style = getGNUStyle(); 8957 8958 // Test for comments at the end of function declarations. 8959 verifyFormat("void\n" 8960 "foo (int a, /*abc*/ int b) // def\n" 8961 "{\n" 8962 "}\n", 8963 Style); 8964 8965 verifyFormat("void\n" 8966 "foo (int a, /* abc */ int b) /* def */\n" 8967 "{\n" 8968 "}\n", 8969 Style); 8970 8971 // Definitions that should not break after return type 8972 verifyFormat("void foo (int a, int b); // def\n", Style); 8973 verifyFormat("void foo (int a, int b); /* def */\n", Style); 8974 verifyFormat("void foo (int a, int b);\n", Style); 8975 } 8976 8977 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) { 8978 FormatStyle NoBreak = getLLVMStyle(); 8979 NoBreak.AlwaysBreakBeforeMultilineStrings = false; 8980 FormatStyle Break = getLLVMStyle(); 8981 Break.AlwaysBreakBeforeMultilineStrings = true; 8982 verifyFormat("aaaa = \"bbbb\"\n" 8983 " \"cccc\";", 8984 NoBreak); 8985 verifyFormat("aaaa =\n" 8986 " \"bbbb\"\n" 8987 " \"cccc\";", 8988 Break); 8989 verifyFormat("aaaa(\"bbbb\"\n" 8990 " \"cccc\");", 8991 NoBreak); 8992 verifyFormat("aaaa(\n" 8993 " \"bbbb\"\n" 8994 " \"cccc\");", 8995 Break); 8996 verifyFormat("aaaa(qqq, \"bbbb\"\n" 8997 " \"cccc\");", 8998 NoBreak); 8999 verifyFormat("aaaa(qqq,\n" 9000 " \"bbbb\"\n" 9001 " \"cccc\");", 9002 Break); 9003 verifyFormat("aaaa(qqq,\n" 9004 " L\"bbbb\"\n" 9005 " L\"cccc\");", 9006 Break); 9007 verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n" 9008 " \"bbbb\"));", 9009 Break); 9010 verifyFormat("string s = someFunction(\n" 9011 " \"abc\"\n" 9012 " \"abc\");", 9013 Break); 9014 9015 // As we break before unary operators, breaking right after them is bad. 9016 verifyFormat("string foo = abc ? \"x\"\n" 9017 " \"blah blah blah blah blah blah\"\n" 9018 " : \"y\";", 9019 Break); 9020 9021 // Don't break if there is no column gain. 9022 verifyFormat("f(\"aaaa\"\n" 9023 " \"bbbb\");", 9024 Break); 9025 9026 // Treat literals with escaped newlines like multi-line string literals. 9027 EXPECT_EQ("x = \"a\\\n" 9028 "b\\\n" 9029 "c\";", 9030 format("x = \"a\\\n" 9031 "b\\\n" 9032 "c\";", 9033 NoBreak)); 9034 EXPECT_EQ("xxxx =\n" 9035 " \"a\\\n" 9036 "b\\\n" 9037 "c\";", 9038 format("xxxx = \"a\\\n" 9039 "b\\\n" 9040 "c\";", 9041 Break)); 9042 9043 EXPECT_EQ("NSString *const kString =\n" 9044 " @\"aaaa\"\n" 9045 " @\"bbbb\";", 9046 format("NSString *const kString = @\"aaaa\"\n" 9047 "@\"bbbb\";", 9048 Break)); 9049 9050 Break.ColumnLimit = 0; 9051 verifyFormat("const char *hello = \"hello llvm\";", Break); 9052 } 9053 9054 TEST_F(FormatTest, AlignsPipes) { 9055 verifyFormat( 9056 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9057 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9058 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9059 verifyFormat( 9060 "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n" 9061 " << aaaaaaaaaaaaaaaaaaaa;"); 9062 verifyFormat( 9063 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9064 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9065 verifyFormat( 9066 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 9067 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9068 verifyFormat( 9069 "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n" 9070 " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n" 9071 " << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";"); 9072 verifyFormat( 9073 "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9074 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9075 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9076 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9077 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9078 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9079 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 9080 verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n" 9081 " << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);"); 9082 verifyFormat( 9083 "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9084 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9085 verifyFormat( 9086 "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n" 9087 " aaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9088 9089 verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n" 9090 " << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();"); 9091 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9092 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9093 " aaaaaaaaaaaaaaaaaaaaa)\n" 9094 " << aaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9095 verifyFormat("LOG_IF(aaa == //\n" 9096 " bbb)\n" 9097 " << a << b;"); 9098 9099 // But sometimes, breaking before the first "<<" is desirable. 9100 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 9101 " << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);"); 9102 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n" 9103 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9104 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9105 verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n" 9106 " << BEF << IsTemplate << Description << E->getType();"); 9107 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 9108 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9109 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9110 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 9111 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9112 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9113 " << aaa;"); 9114 9115 verifyFormat( 9116 "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9117 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9118 9119 // Incomplete string literal. 9120 EXPECT_EQ("llvm::errs() << \"\n" 9121 " << a;", 9122 format("llvm::errs() << \"\n<<a;")); 9123 9124 verifyFormat("void f() {\n" 9125 " CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n" 9126 " << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n" 9127 "}"); 9128 9129 // Handle 'endl'. 9130 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n" 9131 " << bbbbbbbbbbbbbbbbbbbbbb << endl;"); 9132 verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;"); 9133 9134 // Handle '\n'. 9135 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n" 9136 " << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";"); 9137 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n" 9138 " << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';"); 9139 verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n" 9140 " << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";"); 9141 verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";"); 9142 } 9143 9144 TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) { 9145 verifyFormat("return out << \"somepacket = {\\n\"\n" 9146 " << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n" 9147 " << \" bbbb = \" << pkt.bbbb << \"\\n\"\n" 9148 " << \" cccccc = \" << pkt.cccccc << \"\\n\"\n" 9149 " << \" ddd = [\" << pkt.ddd << \"]\\n\"\n" 9150 " << \"}\";"); 9151 9152 verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n" 9153 " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n" 9154 " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;"); 9155 verifyFormat( 9156 "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n" 9157 " << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n" 9158 " << \"ccccccccccccccccc = \" << ccccccccccccccccc\n" 9159 " << \"ddddddddddddddddd = \" << ddddddddddddddddd\n" 9160 " << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;"); 9161 verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n" 9162 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 9163 verifyFormat( 9164 "void f() {\n" 9165 " llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n" 9166 " << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 9167 "}"); 9168 9169 // Breaking before the first "<<" is generally not desirable. 9170 verifyFormat( 9171 "llvm::errs()\n" 9172 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9173 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9174 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9175 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 9176 getLLVMStyleWithColumns(70)); 9177 verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n" 9178 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9179 " << \"aaaaaaaaaaaaaaaaaaa: \"\n" 9180 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9181 " << \"aaaaaaaaaaaaaaaaaaa: \"\n" 9182 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 9183 getLLVMStyleWithColumns(70)); 9184 9185 verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n" 9186 " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n" 9187 " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;"); 9188 verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n" 9189 " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n" 9190 " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);"); 9191 verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n" 9192 " (aaaa + aaaa);", 9193 getLLVMStyleWithColumns(40)); 9194 verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n" 9195 " (aaaaaaa + aaaaa));", 9196 getLLVMStyleWithColumns(40)); 9197 verifyFormat( 9198 "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n" 9199 " SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n" 9200 " bbbbbbbbbbbbbbbbbbbbbbb);"); 9201 } 9202 9203 TEST_F(FormatTest, UnderstandsEquals) { 9204 verifyFormat( 9205 "aaaaaaaaaaaaaaaaa =\n" 9206 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9207 verifyFormat( 9208 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9209 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 9210 verifyFormat( 9211 "if (a) {\n" 9212 " f();\n" 9213 "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9214 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 9215 "}"); 9216 9217 verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9218 " 100000000 + 10000000) {\n}"); 9219 } 9220 9221 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) { 9222 verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n" 9223 " .looooooooooooooooooooooooooooooooooooooongFunction();"); 9224 9225 verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n" 9226 " ->looooooooooooooooooooooooooooooooooooooongFunction();"); 9227 9228 verifyFormat( 9229 "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n" 9230 " Parameter2);"); 9231 9232 verifyFormat( 9233 "ShortObject->shortFunction(\n" 9234 " LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n" 9235 " LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);"); 9236 9237 verifyFormat("loooooooooooooongFunction(\n" 9238 " LoooooooooooooongObject->looooooooooooooooongFunction());"); 9239 9240 verifyFormat( 9241 "function(LoooooooooooooooooooooooooooooooooooongObject\n" 9242 " ->loooooooooooooooooooooooooooooooooooooooongFunction());"); 9243 9244 verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n" 9245 " .WillRepeatedly(Return(SomeValue));"); 9246 verifyFormat("void f() {\n" 9247 " EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n" 9248 " .Times(2)\n" 9249 " .WillRepeatedly(Return(SomeValue));\n" 9250 "}"); 9251 verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n" 9252 " ccccccccccccccccccccccc);"); 9253 verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9254 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9255 " .aaaaa(aaaaa),\n" 9256 " aaaaaaaaaaaaaaaaaaaaa);"); 9257 verifyFormat("void f() {\n" 9258 " aaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9259 " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n" 9260 "}"); 9261 verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9262 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9263 " .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9264 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9265 " aaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 9266 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9267 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9268 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9269 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n" 9270 "}"); 9271 9272 // Here, it is not necessary to wrap at "." or "->". 9273 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n" 9274 " aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 9275 verifyFormat( 9276 "aaaaaaaaaaa->aaaaaaaaa(\n" 9277 " aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9278 " aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n"); 9279 9280 verifyFormat( 9281 "aaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9282 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());"); 9283 verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n" 9284 " aaaaaaaaa()->aaaaaa()->aaaaa());"); 9285 verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n" 9286 " aaaaaaaaa()->aaaaaa()->aaaaa());"); 9287 9288 verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9289 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9290 " .a();"); 9291 9292 FormatStyle NoBinPacking = getLLVMStyle(); 9293 NoBinPacking.BinPackParameters = false; 9294 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n" 9295 " .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n" 9296 " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n" 9297 " aaaaaaaaaaaaaaaaaaa,\n" 9298 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 9299 NoBinPacking); 9300 9301 // If there is a subsequent call, change to hanging indentation. 9302 verifyFormat( 9303 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9304 " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n" 9305 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9306 verifyFormat( 9307 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9308 " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));"); 9309 verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9310 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9311 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9312 verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9313 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9314 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());"); 9315 } 9316 9317 TEST_F(FormatTest, WrapsTemplateDeclarations) { 9318 verifyFormat("template <typename T>\n" 9319 "virtual void loooooooooooongFunction(int Param1, int Param2);"); 9320 verifyFormat("template <typename T>\n" 9321 "// T should be one of {A, B}.\n" 9322 "virtual void loooooooooooongFunction(int Param1, int Param2);"); 9323 verifyFormat( 9324 "template <typename T>\n" 9325 "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;"); 9326 verifyFormat("template <typename T>\n" 9327 "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n" 9328 " int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);"); 9329 verifyFormat( 9330 "template <typename T>\n" 9331 "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n" 9332 " int Paaaaaaaaaaaaaaaaaaaaram2);"); 9333 verifyFormat( 9334 "template <typename T>\n" 9335 "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n" 9336 " aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n" 9337 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9338 verifyFormat("template <typename T>\n" 9339 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9340 " int aaaaaaaaaaaaaaaaaaaaaa);"); 9341 verifyFormat( 9342 "template <typename T1, typename T2 = char, typename T3 = char,\n" 9343 " typename T4 = char>\n" 9344 "void f();"); 9345 verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n" 9346 " template <typename> class cccccccccccccccccccccc,\n" 9347 " typename ddddddddddddd>\n" 9348 "class C {};"); 9349 verifyFormat( 9350 "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n" 9351 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9352 9353 verifyFormat("void f() {\n" 9354 " a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n" 9355 " a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n" 9356 "}"); 9357 9358 verifyFormat("template <typename T> class C {};"); 9359 verifyFormat("template <typename T> void f();"); 9360 verifyFormat("template <typename T> void f() {}"); 9361 verifyFormat( 9362 "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n" 9363 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9364 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n" 9365 " new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n" 9366 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9367 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n" 9368 " bbbbbbbbbbbbbbbbbbbbbbbb);", 9369 getLLVMStyleWithColumns(72)); 9370 EXPECT_EQ("static_cast<A< //\n" 9371 " B> *>(\n" 9372 "\n" 9373 ");", 9374 format("static_cast<A<//\n" 9375 " B>*>(\n" 9376 "\n" 9377 " );")); 9378 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9379 " const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);"); 9380 9381 FormatStyle AlwaysBreak = getLLVMStyle(); 9382 AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 9383 verifyFormat("template <typename T>\nclass C {};", AlwaysBreak); 9384 verifyFormat("template <typename T>\nvoid f();", AlwaysBreak); 9385 verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak); 9386 verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9387 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n" 9388 " ccccccccccccccccccccccccccccccccccccccccccccccc);"); 9389 verifyFormat("template <template <typename> class Fooooooo,\n" 9390 " template <typename> class Baaaaaaar>\n" 9391 "struct C {};", 9392 AlwaysBreak); 9393 verifyFormat("template <typename T> // T can be A, B or C.\n" 9394 "struct C {};", 9395 AlwaysBreak); 9396 verifyFormat("template <enum E> class A {\n" 9397 "public:\n" 9398 " E *f();\n" 9399 "};"); 9400 9401 FormatStyle NeverBreak = getLLVMStyle(); 9402 NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No; 9403 verifyFormat("template <typename T> class C {};", NeverBreak); 9404 verifyFormat("template <typename T> void f();", NeverBreak); 9405 verifyFormat("template <typename T> void f() {}", NeverBreak); 9406 verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa " 9407 "bbbbbbbbbbbbbbbbbbbb) {}", 9408 NeverBreak); 9409 verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9410 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n" 9411 " ccccccccccccccccccccccccccccccccccccccccccccccc);", 9412 NeverBreak); 9413 verifyFormat("template <template <typename> class Fooooooo,\n" 9414 " template <typename> class Baaaaaaar>\n" 9415 "struct C {};", 9416 NeverBreak); 9417 verifyFormat("template <typename T> // T can be A, B or C.\n" 9418 "struct C {};", 9419 NeverBreak); 9420 verifyFormat("template <enum E> class A {\n" 9421 "public:\n" 9422 " E *f();\n" 9423 "};", 9424 NeverBreak); 9425 NeverBreak.PenaltyBreakTemplateDeclaration = 100; 9426 verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa " 9427 "bbbbbbbbbbbbbbbbbbbb) {}", 9428 NeverBreak); 9429 } 9430 9431 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) { 9432 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp); 9433 Style.ColumnLimit = 60; 9434 EXPECT_EQ("// Baseline - no comments.\n" 9435 "template <\n" 9436 " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n" 9437 "void f() {}", 9438 format("// Baseline - no comments.\n" 9439 "template <\n" 9440 " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n" 9441 "void f() {}", 9442 Style)); 9443 9444 EXPECT_EQ("template <\n" 9445 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9446 "void f() {}", 9447 format("template <\n" 9448 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9449 "void f() {}", 9450 Style)); 9451 9452 EXPECT_EQ( 9453 "template <\n" 9454 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n" 9455 "void f() {}", 9456 format("template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n" 9457 "void f() {}", 9458 Style)); 9459 9460 EXPECT_EQ( 9461 "template <\n" 9462 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9463 " // multiline\n" 9464 "void f() {}", 9465 format("template <\n" 9466 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9467 " // multiline\n" 9468 "void f() {}", 9469 Style)); 9470 9471 EXPECT_EQ( 9472 "template <typename aaaaaaaaaa<\n" 9473 " bbbbbbbbbbbb>::value> // trailing loooong\n" 9474 "void f() {}", 9475 format( 9476 "template <\n" 9477 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n" 9478 "void f() {}", 9479 Style)); 9480 } 9481 9482 TEST_F(FormatTest, WrapsTemplateParameters) { 9483 FormatStyle Style = getLLVMStyle(); 9484 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 9485 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 9486 verifyFormat( 9487 "template <typename... a> struct q {};\n" 9488 "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n" 9489 " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n" 9490 " y;", 9491 Style); 9492 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 9493 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 9494 verifyFormat( 9495 "template <typename... a> struct r {};\n" 9496 "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n" 9497 " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n" 9498 " y;", 9499 Style); 9500 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 9501 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 9502 verifyFormat("template <typename... a> struct s {};\n" 9503 "extern s<\n" 9504 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9505 "aaaaaaaaaaaaaaaaaaaaaa,\n" 9506 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9507 "aaaaaaaaaaaaaaaaaaaaaa>\n" 9508 " y;", 9509 Style); 9510 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 9511 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 9512 verifyFormat("template <typename... a> struct t {};\n" 9513 "extern t<\n" 9514 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9515 "aaaaaaaaaaaaaaaaaaaaaa,\n" 9516 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9517 "aaaaaaaaaaaaaaaaaaaaaa>\n" 9518 " y;", 9519 Style); 9520 } 9521 9522 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) { 9523 verifyFormat( 9524 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9525 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9526 verifyFormat( 9527 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9528 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9529 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());"); 9530 9531 // FIXME: Should we have the extra indent after the second break? 9532 verifyFormat( 9533 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9534 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9535 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9536 9537 verifyFormat( 9538 "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n" 9539 " cccccccccccccccccccccccccccccccccccccccccccccc());"); 9540 9541 // Breaking at nested name specifiers is generally not desirable. 9542 verifyFormat( 9543 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9544 " aaaaaaaaaaaaaaaaaaaaaaa);"); 9545 9546 verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n" 9547 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9548 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9549 " aaaaaaaaaaaaaaaaaaaaa);", 9550 getLLVMStyleWithColumns(74)); 9551 9552 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9553 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9554 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9555 } 9556 9557 TEST_F(FormatTest, UnderstandsTemplateParameters) { 9558 verifyFormat("A<int> a;"); 9559 verifyFormat("A<A<A<int>>> a;"); 9560 verifyFormat("A<A<A<int, 2>, 3>, 4> a;"); 9561 verifyFormat("bool x = a < 1 || 2 > a;"); 9562 verifyFormat("bool x = 5 < f<int>();"); 9563 verifyFormat("bool x = f<int>() > 5;"); 9564 verifyFormat("bool x = 5 < a<int>::x;"); 9565 verifyFormat("bool x = a < 4 ? a > 2 : false;"); 9566 verifyFormat("bool x = f() ? a < 2 : a > 2;"); 9567 9568 verifyGoogleFormat("A<A<int>> a;"); 9569 verifyGoogleFormat("A<A<A<int>>> a;"); 9570 verifyGoogleFormat("A<A<A<A<int>>>> a;"); 9571 verifyGoogleFormat("A<A<int> > a;"); 9572 verifyGoogleFormat("A<A<A<int> > > a;"); 9573 verifyGoogleFormat("A<A<A<A<int> > > > a;"); 9574 verifyGoogleFormat("A<::A<int>> a;"); 9575 verifyGoogleFormat("A<::A> a;"); 9576 verifyGoogleFormat("A< ::A> a;"); 9577 verifyGoogleFormat("A< ::A<int> > a;"); 9578 EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle())); 9579 EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle())); 9580 EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle())); 9581 EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle())); 9582 EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };", 9583 format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle())); 9584 9585 verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp)); 9586 9587 // template closer followed by a token that starts with > or = 9588 verifyFormat("bool b = a<1> > 1;"); 9589 verifyFormat("bool b = a<1> >= 1;"); 9590 verifyFormat("int i = a<1> >> 1;"); 9591 FormatStyle Style = getLLVMStyle(); 9592 Style.SpaceBeforeAssignmentOperators = false; 9593 verifyFormat("bool b= a<1> == 1;", Style); 9594 verifyFormat("a<int> = 1;", Style); 9595 verifyFormat("a<int> >>= 1;", Style); 9596 9597 verifyFormat("test < a | b >> c;"); 9598 verifyFormat("test<test<a | b>> c;"); 9599 verifyFormat("test >> a >> b;"); 9600 verifyFormat("test << a >> b;"); 9601 9602 verifyFormat("f<int>();"); 9603 verifyFormat("template <typename T> void f() {}"); 9604 verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;"); 9605 verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : " 9606 "sizeof(char)>::type>;"); 9607 verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};"); 9608 verifyFormat("f(a.operator()<A>());"); 9609 verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9610 " .template operator()<A>());", 9611 getLLVMStyleWithColumns(35)); 9612 verifyFormat("bool_constant<a && noexcept(f())>"); 9613 verifyFormat("bool_constant<a || noexcept(f())>"); 9614 9615 // Not template parameters. 9616 verifyFormat("return a < b && c > d;"); 9617 verifyFormat("void f() {\n" 9618 " while (a < b && c > d) {\n" 9619 " }\n" 9620 "}"); 9621 verifyFormat("template <typename... Types>\n" 9622 "typename enable_if<0 < sizeof...(Types)>::type Foo() {}"); 9623 9624 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9625 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);", 9626 getLLVMStyleWithColumns(60)); 9627 verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");"); 9628 verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}"); 9629 verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <"); 9630 verifyFormat("some_templated_type<decltype([](int i) { return i; })>"); 9631 } 9632 9633 TEST_F(FormatTest, UnderstandsShiftOperators) { 9634 verifyFormat("if (i < x >> 1)"); 9635 verifyFormat("while (i < x >> 1)"); 9636 verifyFormat("for (unsigned i = 0; i < i; ++i, v = v >> 1)"); 9637 verifyFormat("for (unsigned i = 0; i < x >> 1; ++i, v = v >> 1)"); 9638 verifyFormat( 9639 "for (std::vector<int>::iterator i = 0; i < x >> 1; ++i, v = v >> 1)"); 9640 verifyFormat("Foo.call<Bar<Function>>()"); 9641 verifyFormat("if (Foo.call<Bar<Function>>() == 0)"); 9642 verifyFormat("for (std::vector<std::pair<int>>::iterator i = 0; i < x >> 1; " 9643 "++i, v = v >> 1)"); 9644 verifyFormat("if (w<u<v<x>>, 1>::t)"); 9645 } 9646 9647 TEST_F(FormatTest, BitshiftOperatorWidth) { 9648 EXPECT_EQ("int a = 1 << 2; /* foo\n" 9649 " bar */", 9650 format("int a=1<<2; /* foo\n" 9651 " bar */")); 9652 9653 EXPECT_EQ("int b = 256 >> 1; /* foo\n" 9654 " bar */", 9655 format("int b =256>>1 ; /* foo\n" 9656 " bar */")); 9657 } 9658 9659 TEST_F(FormatTest, UnderstandsBinaryOperators) { 9660 verifyFormat("COMPARE(a, ==, b);"); 9661 verifyFormat("auto s = sizeof...(Ts) - 1;"); 9662 } 9663 9664 TEST_F(FormatTest, UnderstandsPointersToMembers) { 9665 verifyFormat("int A::*x;"); 9666 verifyFormat("int (S::*func)(void *);"); 9667 verifyFormat("void f() { int (S::*func)(void *); }"); 9668 verifyFormat("typedef bool *(Class::*Member)() const;"); 9669 verifyFormat("void f() {\n" 9670 " (a->*f)();\n" 9671 " a->*x;\n" 9672 " (a.*f)();\n" 9673 " ((*a).*f)();\n" 9674 " a.*x;\n" 9675 "}"); 9676 verifyFormat("void f() {\n" 9677 " (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n" 9678 " aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n" 9679 "}"); 9680 verifyFormat( 9681 "(aaaaaaaaaa->*bbbbbbb)(\n" 9682 " aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 9683 FormatStyle Style = getLLVMStyle(); 9684 Style.PointerAlignment = FormatStyle::PAS_Left; 9685 verifyFormat("typedef bool* (Class::*Member)() const;", Style); 9686 } 9687 9688 TEST_F(FormatTest, UnderstandsUnaryOperators) { 9689 verifyFormat("int a = -2;"); 9690 verifyFormat("f(-1, -2, -3);"); 9691 verifyFormat("a[-1] = 5;"); 9692 verifyFormat("int a = 5 + -2;"); 9693 verifyFormat("if (i == -1) {\n}"); 9694 verifyFormat("if (i != -1) {\n}"); 9695 verifyFormat("if (i > -1) {\n}"); 9696 verifyFormat("if (i < -1) {\n}"); 9697 verifyFormat("++(a->f());"); 9698 verifyFormat("--(a->f());"); 9699 verifyFormat("(a->f())++;"); 9700 verifyFormat("a[42]++;"); 9701 verifyFormat("if (!(a->f())) {\n}"); 9702 verifyFormat("if (!+i) {\n}"); 9703 verifyFormat("~&a;"); 9704 9705 verifyFormat("a-- > b;"); 9706 verifyFormat("b ? -a : c;"); 9707 verifyFormat("n * sizeof char16;"); 9708 verifyFormat("n * alignof char16;", getGoogleStyle()); 9709 verifyFormat("sizeof(char);"); 9710 verifyFormat("alignof(char);", getGoogleStyle()); 9711 9712 verifyFormat("return -1;"); 9713 verifyFormat("throw -1;"); 9714 verifyFormat("switch (a) {\n" 9715 "case -1:\n" 9716 " break;\n" 9717 "}"); 9718 verifyFormat("#define X -1"); 9719 verifyFormat("#define X -kConstant"); 9720 9721 verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};"); 9722 verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};"); 9723 9724 verifyFormat("int a = /* confusing comment */ -1;"); 9725 // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case. 9726 verifyFormat("int a = i /* confusing comment */++;"); 9727 9728 verifyFormat("co_yield -1;"); 9729 verifyFormat("co_return -1;"); 9730 9731 // Check that * is not treated as a binary operator when we set 9732 // PointerAlignment as PAS_Left after a keyword and not a declaration. 9733 FormatStyle PASLeftStyle = getLLVMStyle(); 9734 PASLeftStyle.PointerAlignment = FormatStyle::PAS_Left; 9735 verifyFormat("co_return *a;", PASLeftStyle); 9736 verifyFormat("co_await *a;", PASLeftStyle); 9737 verifyFormat("co_yield *a", PASLeftStyle); 9738 verifyFormat("return *a;", PASLeftStyle); 9739 } 9740 9741 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) { 9742 verifyFormat("if (!aaaaaaaaaa( // break\n" 9743 " aaaaa)) {\n" 9744 "}"); 9745 verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n" 9746 " aaaaa));"); 9747 verifyFormat("*aaa = aaaaaaa( // break\n" 9748 " bbbbbb);"); 9749 } 9750 9751 TEST_F(FormatTest, UnderstandsOverloadedOperators) { 9752 verifyFormat("bool operator<();"); 9753 verifyFormat("bool operator>();"); 9754 verifyFormat("bool operator=();"); 9755 verifyFormat("bool operator==();"); 9756 verifyFormat("bool operator!=();"); 9757 verifyFormat("int operator+();"); 9758 verifyFormat("int operator++();"); 9759 verifyFormat("int operator++(int) volatile noexcept;"); 9760 verifyFormat("bool operator,();"); 9761 verifyFormat("bool operator();"); 9762 verifyFormat("bool operator()();"); 9763 verifyFormat("bool operator[]();"); 9764 verifyFormat("operator bool();"); 9765 verifyFormat("operator int();"); 9766 verifyFormat("operator void *();"); 9767 verifyFormat("operator SomeType<int>();"); 9768 verifyFormat("operator SomeType<int, int>();"); 9769 verifyFormat("operator SomeType<SomeType<int>>();"); 9770 verifyFormat("operator< <>();"); 9771 verifyFormat("operator<< <>();"); 9772 verifyFormat("< <>"); 9773 9774 verifyFormat("void *operator new(std::size_t size);"); 9775 verifyFormat("void *operator new[](std::size_t size);"); 9776 verifyFormat("void operator delete(void *ptr);"); 9777 verifyFormat("void operator delete[](void *ptr);"); 9778 verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n" 9779 "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);"); 9780 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n" 9781 " aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;"); 9782 9783 verifyFormat( 9784 "ostream &operator<<(ostream &OutputStream,\n" 9785 " SomeReallyLongType WithSomeReallyLongValue);"); 9786 verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n" 9787 " const aaaaaaaaaaaaaaaaaaaaa &right) {\n" 9788 " return left.group < right.group;\n" 9789 "}"); 9790 verifyFormat("SomeType &operator=(const SomeType &S);"); 9791 verifyFormat("f.template operator()<int>();"); 9792 9793 verifyGoogleFormat("operator void*();"); 9794 verifyGoogleFormat("operator SomeType<SomeType<int>>();"); 9795 verifyGoogleFormat("operator ::A();"); 9796 9797 verifyFormat("using A::operator+;"); 9798 verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n" 9799 "int i;"); 9800 9801 // Calling an operator as a member function. 9802 verifyFormat("void f() { a.operator*(); }"); 9803 verifyFormat("void f() { a.operator*(b & b); }"); 9804 verifyFormat("void f() { a->operator&(a * b); }"); 9805 verifyFormat("void f() { NS::a.operator+(*b * *b); }"); 9806 // TODO: Calling an operator as a non-member function is hard to distinguish. 9807 // https://llvm.org/PR50629 9808 // verifyFormat("void f() { operator*(a & a); }"); 9809 // verifyFormat("void f() { operator&(a, b * b); }"); 9810 9811 verifyFormat("::operator delete(foo);"); 9812 verifyFormat("::operator new(n * sizeof(foo));"); 9813 verifyFormat("foo() { ::operator delete(foo); }"); 9814 verifyFormat("foo() { ::operator new(n * sizeof(foo)); }"); 9815 } 9816 9817 TEST_F(FormatTest, UnderstandsFunctionRefQualification) { 9818 verifyFormat("void A::b() && {}"); 9819 verifyFormat("void A::b() &&noexcept {}"); 9820 verifyFormat("Deleted &operator=(const Deleted &) & = default;"); 9821 verifyFormat("Deleted &operator=(const Deleted &) && = delete;"); 9822 verifyFormat("Deleted &operator=(const Deleted &) &noexcept = default;"); 9823 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;"); 9824 verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;"); 9825 verifyFormat("Deleted &operator=(const Deleted &) &;"); 9826 verifyFormat("Deleted &operator=(const Deleted &) &&;"); 9827 verifyFormat("SomeType MemberFunction(const Deleted &) &;"); 9828 verifyFormat("SomeType MemberFunction(const Deleted &) &&;"); 9829 verifyFormat("SomeType MemberFunction(const Deleted &) && {}"); 9830 verifyFormat("SomeType MemberFunction(const Deleted &) && final {}"); 9831 verifyFormat("SomeType MemberFunction(const Deleted &) && override {}"); 9832 verifyFormat("SomeType MemberFunction(const Deleted &) &&noexcept {}"); 9833 verifyFormat("void Fn(T const &) const &;"); 9834 verifyFormat("void Fn(T const volatile &&) const volatile &&;"); 9835 verifyFormat("void Fn(T const volatile &&) const volatile &&noexcept;"); 9836 verifyFormat("template <typename T>\n" 9837 "void F(T) && = delete;", 9838 getGoogleStyle()); 9839 9840 FormatStyle AlignLeft = getLLVMStyle(); 9841 AlignLeft.PointerAlignment = FormatStyle::PAS_Left; 9842 verifyFormat("void A::b() && {}", AlignLeft); 9843 verifyFormat("void A::b() && noexcept {}", AlignLeft); 9844 verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft); 9845 verifyFormat("Deleted& operator=(const Deleted&) & noexcept = default;", 9846 AlignLeft); 9847 verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;", 9848 AlignLeft); 9849 verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft); 9850 verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft); 9851 verifyFormat("auto Function(T t) & -> void {}", AlignLeft); 9852 verifyFormat("auto Function(T... t) & -> void {}", AlignLeft); 9853 verifyFormat("auto Function(T) & -> void {}", AlignLeft); 9854 verifyFormat("auto Function(T) & -> void;", AlignLeft); 9855 verifyFormat("void Fn(T const&) const&;", AlignLeft); 9856 verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft); 9857 verifyFormat("void Fn(T const volatile&&) const volatile&& noexcept;", 9858 AlignLeft); 9859 9860 FormatStyle AlignMiddle = getLLVMStyle(); 9861 AlignMiddle.PointerAlignment = FormatStyle::PAS_Middle; 9862 verifyFormat("void A::b() && {}", AlignMiddle); 9863 verifyFormat("void A::b() && noexcept {}", AlignMiddle); 9864 verifyFormat("Deleted & operator=(const Deleted &) & = default;", 9865 AlignMiddle); 9866 verifyFormat("Deleted & operator=(const Deleted &) & noexcept = default;", 9867 AlignMiddle); 9868 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", 9869 AlignMiddle); 9870 verifyFormat("Deleted & operator=(const Deleted &) &;", AlignMiddle); 9871 verifyFormat("SomeType MemberFunction(const Deleted &) &;", AlignMiddle); 9872 verifyFormat("auto Function(T t) & -> void {}", AlignMiddle); 9873 verifyFormat("auto Function(T... t) & -> void {}", AlignMiddle); 9874 verifyFormat("auto Function(T) & -> void {}", AlignMiddle); 9875 verifyFormat("auto Function(T) & -> void;", AlignMiddle); 9876 verifyFormat("void Fn(T const &) const &;", AlignMiddle); 9877 verifyFormat("void Fn(T const volatile &&) const volatile &&;", AlignMiddle); 9878 verifyFormat("void Fn(T const volatile &&) const volatile && noexcept;", 9879 AlignMiddle); 9880 9881 FormatStyle Spaces = getLLVMStyle(); 9882 Spaces.SpacesInCStyleCastParentheses = true; 9883 verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces); 9884 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces); 9885 verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces); 9886 verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces); 9887 9888 Spaces.SpacesInCStyleCastParentheses = false; 9889 Spaces.SpacesInParentheses = true; 9890 verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces); 9891 verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;", 9892 Spaces); 9893 verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces); 9894 verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces); 9895 9896 FormatStyle BreakTemplate = getLLVMStyle(); 9897 BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 9898 9899 verifyFormat("struct f {\n" 9900 " template <class T>\n" 9901 " int &foo(const std::string &str) &noexcept {}\n" 9902 "};", 9903 BreakTemplate); 9904 9905 verifyFormat("struct f {\n" 9906 " template <class T>\n" 9907 " int &foo(const std::string &str) &&noexcept {}\n" 9908 "};", 9909 BreakTemplate); 9910 9911 verifyFormat("struct f {\n" 9912 " template <class T>\n" 9913 " int &foo(const std::string &str) const &noexcept {}\n" 9914 "};", 9915 BreakTemplate); 9916 9917 verifyFormat("struct f {\n" 9918 " template <class T>\n" 9919 " int &foo(const std::string &str) const &noexcept {}\n" 9920 "};", 9921 BreakTemplate); 9922 9923 verifyFormat("struct f {\n" 9924 " template <class T>\n" 9925 " auto foo(const std::string &str) &&noexcept -> int & {}\n" 9926 "};", 9927 BreakTemplate); 9928 9929 FormatStyle AlignLeftBreakTemplate = getLLVMStyle(); 9930 AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations = 9931 FormatStyle::BTDS_Yes; 9932 AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left; 9933 9934 verifyFormat("struct f {\n" 9935 " template <class T>\n" 9936 " int& foo(const std::string& str) & noexcept {}\n" 9937 "};", 9938 AlignLeftBreakTemplate); 9939 9940 verifyFormat("struct f {\n" 9941 " template <class T>\n" 9942 " int& foo(const std::string& str) && noexcept {}\n" 9943 "};", 9944 AlignLeftBreakTemplate); 9945 9946 verifyFormat("struct f {\n" 9947 " template <class T>\n" 9948 " int& foo(const std::string& str) const& noexcept {}\n" 9949 "};", 9950 AlignLeftBreakTemplate); 9951 9952 verifyFormat("struct f {\n" 9953 " template <class T>\n" 9954 " int& foo(const std::string& str) const&& noexcept {}\n" 9955 "};", 9956 AlignLeftBreakTemplate); 9957 9958 verifyFormat("struct f {\n" 9959 " template <class T>\n" 9960 " auto foo(const std::string& str) && noexcept -> int& {}\n" 9961 "};", 9962 AlignLeftBreakTemplate); 9963 9964 // The `&` in `Type&` should not be confused with a trailing `&` of 9965 // DEPRECATED(reason) member function. 9966 verifyFormat("struct f {\n" 9967 " template <class T>\n" 9968 " DEPRECATED(reason)\n" 9969 " Type &foo(arguments) {}\n" 9970 "};", 9971 BreakTemplate); 9972 9973 verifyFormat("struct f {\n" 9974 " template <class T>\n" 9975 " DEPRECATED(reason)\n" 9976 " Type& foo(arguments) {}\n" 9977 "};", 9978 AlignLeftBreakTemplate); 9979 9980 verifyFormat("void (*foopt)(int) = &func;"); 9981 9982 FormatStyle DerivePointerAlignment = getLLVMStyle(); 9983 DerivePointerAlignment.DerivePointerAlignment = true; 9984 // There's always a space between the function and its trailing qualifiers. 9985 // This isn't evidence for PAS_Right (or for PAS_Left). 9986 std::string Prefix = "void a() &;\n" 9987 "void b() &;\n"; 9988 verifyFormat(Prefix + "int* x;", DerivePointerAlignment); 9989 verifyFormat(Prefix + "int *x;", DerivePointerAlignment); 9990 // Same if the function is an overloaded operator, and with &&. 9991 Prefix = "void operator()() &&;\n" 9992 "void operator()() &&;\n"; 9993 verifyFormat(Prefix + "int* x;", DerivePointerAlignment); 9994 verifyFormat(Prefix + "int *x;", DerivePointerAlignment); 9995 // However a space between cv-qualifiers and ref-qualifiers *is* evidence. 9996 Prefix = "void a() const &;\n" 9997 "void b() const &;\n"; 9998 EXPECT_EQ(Prefix + "int *x;", 9999 format(Prefix + "int* x;", DerivePointerAlignment)); 10000 } 10001 10002 TEST_F(FormatTest, UnderstandsNewAndDelete) { 10003 verifyFormat("void f() {\n" 10004 " A *a = new A;\n" 10005 " A *a = new (placement) A;\n" 10006 " delete a;\n" 10007 " delete (A *)a;\n" 10008 "}"); 10009 verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n" 10010 " typename aaaaaaaaaaaaaaaaaaaaaaaa();"); 10011 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 10012 " new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n" 10013 " typename aaaaaaaaaaaaaaaaaaaaaaaa();"); 10014 verifyFormat("delete[] h->p;"); 10015 verifyFormat("delete[] (void *)p;"); 10016 10017 verifyFormat("void operator delete(void *foo) ATTRIB;"); 10018 verifyFormat("void operator new(void *foo) ATTRIB;"); 10019 verifyFormat("void operator delete[](void *foo) ATTRIB;"); 10020 verifyFormat("void operator delete(void *ptr) noexcept;"); 10021 10022 EXPECT_EQ("void new(link p);\n" 10023 "void delete(link p);\n", 10024 format("void new (link p);\n" 10025 "void delete (link p);\n")); 10026 } 10027 10028 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) { 10029 verifyFormat("int *f(int *a) {}"); 10030 verifyFormat("int main(int argc, char **argv) {}"); 10031 verifyFormat("Test::Test(int b) : a(b * b) {}"); 10032 verifyIndependentOfContext("f(a, *a);"); 10033 verifyFormat("void g() { f(*a); }"); 10034 verifyIndependentOfContext("int a = b * 10;"); 10035 verifyIndependentOfContext("int a = 10 * b;"); 10036 verifyIndependentOfContext("int a = b * c;"); 10037 verifyIndependentOfContext("int a += b * c;"); 10038 verifyIndependentOfContext("int a -= b * c;"); 10039 verifyIndependentOfContext("int a *= b * c;"); 10040 verifyIndependentOfContext("int a /= b * c;"); 10041 verifyIndependentOfContext("int a = *b;"); 10042 verifyIndependentOfContext("int a = *b * c;"); 10043 verifyIndependentOfContext("int a = b * *c;"); 10044 verifyIndependentOfContext("int a = b * (10);"); 10045 verifyIndependentOfContext("S << b * (10);"); 10046 verifyIndependentOfContext("return 10 * b;"); 10047 verifyIndependentOfContext("return *b * *c;"); 10048 verifyIndependentOfContext("return a & ~b;"); 10049 verifyIndependentOfContext("f(b ? *c : *d);"); 10050 verifyIndependentOfContext("int a = b ? *c : *d;"); 10051 verifyIndependentOfContext("*b = a;"); 10052 verifyIndependentOfContext("a * ~b;"); 10053 verifyIndependentOfContext("a * !b;"); 10054 verifyIndependentOfContext("a * +b;"); 10055 verifyIndependentOfContext("a * -b;"); 10056 verifyIndependentOfContext("a * ++b;"); 10057 verifyIndependentOfContext("a * --b;"); 10058 verifyIndependentOfContext("a[4] * b;"); 10059 verifyIndependentOfContext("a[a * a] = 1;"); 10060 verifyIndependentOfContext("f() * b;"); 10061 verifyIndependentOfContext("a * [self dostuff];"); 10062 verifyIndependentOfContext("int x = a * (a + b);"); 10063 verifyIndependentOfContext("(a *)(a + b);"); 10064 verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;"); 10065 verifyIndependentOfContext("int *pa = (int *)&a;"); 10066 verifyIndependentOfContext("return sizeof(int **);"); 10067 verifyIndependentOfContext("return sizeof(int ******);"); 10068 verifyIndependentOfContext("return (int **&)a;"); 10069 verifyIndependentOfContext("f((*PointerToArray)[10]);"); 10070 verifyFormat("void f(Type (*parameter)[10]) {}"); 10071 verifyFormat("void f(Type (¶meter)[10]) {}"); 10072 verifyGoogleFormat("return sizeof(int**);"); 10073 verifyIndependentOfContext("Type **A = static_cast<Type **>(P);"); 10074 verifyGoogleFormat("Type** A = static_cast<Type**>(P);"); 10075 verifyFormat("auto a = [](int **&, int ***) {};"); 10076 verifyFormat("auto PointerBinding = [](const char *S) {};"); 10077 verifyFormat("typedef typeof(int(int, int)) *MyFunc;"); 10078 verifyFormat("[](const decltype(*a) &value) {}"); 10079 verifyFormat("[](const typeof(*a) &value) {}"); 10080 verifyFormat("[](const _Atomic(a *) &value) {}"); 10081 verifyFormat("[](const __underlying_type(a) &value) {}"); 10082 verifyFormat("decltype(a * b) F();"); 10083 verifyFormat("typeof(a * b) F();"); 10084 verifyFormat("#define MACRO() [](A *a) { return 1; }"); 10085 verifyFormat("Constructor() : member([](A *a, B *b) {}) {}"); 10086 verifyIndependentOfContext("typedef void (*f)(int *a);"); 10087 verifyIndependentOfContext("int i{a * b};"); 10088 verifyIndependentOfContext("aaa && aaa->f();"); 10089 verifyIndependentOfContext("int x = ~*p;"); 10090 verifyFormat("Constructor() : a(a), area(width * height) {}"); 10091 verifyFormat("Constructor() : a(a), area(a, width * height) {}"); 10092 verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}"); 10093 verifyFormat("void f() { f(a, c * d); }"); 10094 verifyFormat("void f() { f(new a(), c * d); }"); 10095 verifyFormat("void f(const MyOverride &override);"); 10096 verifyFormat("void f(const MyFinal &final);"); 10097 verifyIndependentOfContext("bool a = f() && override.f();"); 10098 verifyIndependentOfContext("bool a = f() && final.f();"); 10099 10100 verifyIndependentOfContext("InvalidRegions[*R] = 0;"); 10101 10102 verifyIndependentOfContext("A<int *> a;"); 10103 verifyIndependentOfContext("A<int **> a;"); 10104 verifyIndependentOfContext("A<int *, int *> a;"); 10105 verifyIndependentOfContext("A<int *[]> a;"); 10106 verifyIndependentOfContext( 10107 "const char *const p = reinterpret_cast<const char *const>(q);"); 10108 verifyIndependentOfContext("A<int **, int **> a;"); 10109 verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);"); 10110 verifyFormat("for (char **a = b; *a; ++a) {\n}"); 10111 verifyFormat("for (; a && b;) {\n}"); 10112 verifyFormat("bool foo = true && [] { return false; }();"); 10113 10114 verifyFormat( 10115 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 10116 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 10117 10118 verifyGoogleFormat("int const* a = &b;"); 10119 verifyGoogleFormat("**outparam = 1;"); 10120 verifyGoogleFormat("*outparam = a * b;"); 10121 verifyGoogleFormat("int main(int argc, char** argv) {}"); 10122 verifyGoogleFormat("A<int*> a;"); 10123 verifyGoogleFormat("A<int**> a;"); 10124 verifyGoogleFormat("A<int*, int*> a;"); 10125 verifyGoogleFormat("A<int**, int**> a;"); 10126 verifyGoogleFormat("f(b ? *c : *d);"); 10127 verifyGoogleFormat("int a = b ? *c : *d;"); 10128 verifyGoogleFormat("Type* t = **x;"); 10129 verifyGoogleFormat("Type* t = *++*x;"); 10130 verifyGoogleFormat("*++*x;"); 10131 verifyGoogleFormat("Type* t = const_cast<T*>(&*x);"); 10132 verifyGoogleFormat("Type* t = x++ * y;"); 10133 verifyGoogleFormat( 10134 "const char* const p = reinterpret_cast<const char* const>(q);"); 10135 verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);"); 10136 verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);"); 10137 verifyGoogleFormat("template <typename T>\n" 10138 "void f(int i = 0, SomeType** temps = NULL);"); 10139 10140 FormatStyle Left = getLLVMStyle(); 10141 Left.PointerAlignment = FormatStyle::PAS_Left; 10142 verifyFormat("x = *a(x) = *a(y);", Left); 10143 verifyFormat("for (;; *a = b) {\n}", Left); 10144 verifyFormat("return *this += 1;", Left); 10145 verifyFormat("throw *x;", Left); 10146 verifyFormat("delete *x;", Left); 10147 verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left); 10148 verifyFormat("[](const decltype(*a)* ptr) {}", Left); 10149 verifyFormat("[](const typeof(*a)* ptr) {}", Left); 10150 verifyFormat("[](const _Atomic(a*)* ptr) {}", Left); 10151 verifyFormat("[](const __underlying_type(a)* ptr) {}", Left); 10152 verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left); 10153 verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left); 10154 verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left); 10155 verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left); 10156 10157 verifyIndependentOfContext("a = *(x + y);"); 10158 verifyIndependentOfContext("a = &(x + y);"); 10159 verifyIndependentOfContext("*(x + y).call();"); 10160 verifyIndependentOfContext("&(x + y)->call();"); 10161 verifyFormat("void f() { &(*I).first; }"); 10162 10163 verifyIndependentOfContext("f(b * /* confusing comment */ ++c);"); 10164 verifyFormat("f(* /* confusing comment */ foo);"); 10165 verifyFormat("void (* /*deleter*/)(const Slice &key, void *value)"); 10166 verifyFormat("void foo(int * // this is the first paramters\n" 10167 " ,\n" 10168 " int second);"); 10169 verifyFormat("double term = a * // first\n" 10170 " b;"); 10171 verifyFormat( 10172 "int *MyValues = {\n" 10173 " *A, // Operator detection might be confused by the '{'\n" 10174 " *BB // Operator detection might be confused by previous comment\n" 10175 "};"); 10176 10177 verifyIndependentOfContext("if (int *a = &b)"); 10178 verifyIndependentOfContext("if (int &a = *b)"); 10179 verifyIndependentOfContext("if (a & b[i])"); 10180 verifyIndependentOfContext("if constexpr (a & b[i])"); 10181 verifyIndependentOfContext("if CONSTEXPR (a & b[i])"); 10182 verifyIndependentOfContext("if (a * (b * c))"); 10183 verifyIndependentOfContext("if constexpr (a * (b * c))"); 10184 verifyIndependentOfContext("if CONSTEXPR (a * (b * c))"); 10185 verifyIndependentOfContext("if (a::b::c::d & b[i])"); 10186 verifyIndependentOfContext("if (*b[i])"); 10187 verifyIndependentOfContext("if (int *a = (&b))"); 10188 verifyIndependentOfContext("while (int *a = &b)"); 10189 verifyIndependentOfContext("while (a * (b * c))"); 10190 verifyIndependentOfContext("size = sizeof *a;"); 10191 verifyIndependentOfContext("if (a && (b = c))"); 10192 verifyFormat("void f() {\n" 10193 " for (const int &v : Values) {\n" 10194 " }\n" 10195 "}"); 10196 verifyFormat("for (int i = a * a; i < 10; ++i) {\n}"); 10197 verifyFormat("for (int i = 0; i < a * a; ++i) {\n}"); 10198 verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}"); 10199 10200 verifyFormat("#define A (!a * b)"); 10201 verifyFormat("#define MACRO \\\n" 10202 " int *i = a * b; \\\n" 10203 " void f(a *b);", 10204 getLLVMStyleWithColumns(19)); 10205 10206 verifyIndependentOfContext("A = new SomeType *[Length];"); 10207 verifyIndependentOfContext("A = new SomeType *[Length]();"); 10208 verifyIndependentOfContext("T **t = new T *;"); 10209 verifyIndependentOfContext("T **t = new T *();"); 10210 verifyGoogleFormat("A = new SomeType*[Length]();"); 10211 verifyGoogleFormat("A = new SomeType*[Length];"); 10212 verifyGoogleFormat("T** t = new T*;"); 10213 verifyGoogleFormat("T** t = new T*();"); 10214 10215 verifyFormat("STATIC_ASSERT((a & b) == 0);"); 10216 verifyFormat("STATIC_ASSERT(0 == (a & b));"); 10217 verifyFormat("template <bool a, bool b> " 10218 "typename t::if<x && y>::type f() {}"); 10219 verifyFormat("template <int *y> f() {}"); 10220 verifyFormat("vector<int *> v;"); 10221 verifyFormat("vector<int *const> v;"); 10222 verifyFormat("vector<int *const **const *> v;"); 10223 verifyFormat("vector<int *volatile> v;"); 10224 verifyFormat("vector<a *_Nonnull> v;"); 10225 verifyFormat("vector<a *_Nullable> v;"); 10226 verifyFormat("vector<a *_Null_unspecified> v;"); 10227 verifyFormat("vector<a *__ptr32> v;"); 10228 verifyFormat("vector<a *__ptr64> v;"); 10229 verifyFormat("vector<a *__capability> v;"); 10230 FormatStyle TypeMacros = getLLVMStyle(); 10231 TypeMacros.TypenameMacros = {"LIST"}; 10232 verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros); 10233 verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros); 10234 verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros); 10235 verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros); 10236 verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication 10237 10238 FormatStyle CustomQualifier = getLLVMStyle(); 10239 // Add identifiers that should not be parsed as a qualifier by default. 10240 CustomQualifier.AttributeMacros.push_back("__my_qualifier"); 10241 CustomQualifier.AttributeMacros.push_back("_My_qualifier"); 10242 CustomQualifier.AttributeMacros.push_back("my_other_qualifier"); 10243 verifyFormat("vector<a * __my_qualifier> parse_as_multiply;"); 10244 verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier); 10245 verifyFormat("vector<a * _My_qualifier> parse_as_multiply;"); 10246 verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier); 10247 verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;"); 10248 verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier); 10249 verifyFormat("vector<a * _NotAQualifier> v;"); 10250 verifyFormat("vector<a * __not_a_qualifier> v;"); 10251 verifyFormat("vector<a * b> v;"); 10252 verifyFormat("foo<b && false>();"); 10253 verifyFormat("foo<b & 1>();"); 10254 verifyFormat("decltype(*::std::declval<const T &>()) void F();"); 10255 verifyFormat("typeof(*::std::declval<const T &>()) void F();"); 10256 verifyFormat("_Atomic(*::std::declval<const T &>()) void F();"); 10257 verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();"); 10258 verifyFormat( 10259 "template <class T, class = typename std::enable_if<\n" 10260 " std::is_integral<T>::value &&\n" 10261 " (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n" 10262 "void F();", 10263 getLLVMStyleWithColumns(70)); 10264 verifyFormat("template <class T,\n" 10265 " class = typename std::enable_if<\n" 10266 " std::is_integral<T>::value &&\n" 10267 " (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n" 10268 " class U>\n" 10269 "void F();", 10270 getLLVMStyleWithColumns(70)); 10271 verifyFormat( 10272 "template <class T,\n" 10273 " class = typename ::std::enable_if<\n" 10274 " ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n" 10275 "void F();", 10276 getGoogleStyleWithColumns(68)); 10277 10278 verifyIndependentOfContext("MACRO(int *i);"); 10279 verifyIndependentOfContext("MACRO(auto *a);"); 10280 verifyIndependentOfContext("MACRO(const A *a);"); 10281 verifyIndependentOfContext("MACRO(_Atomic(A) *a);"); 10282 verifyIndependentOfContext("MACRO(decltype(A) *a);"); 10283 verifyIndependentOfContext("MACRO(typeof(A) *a);"); 10284 verifyIndependentOfContext("MACRO(__underlying_type(A) *a);"); 10285 verifyIndependentOfContext("MACRO(A *const a);"); 10286 verifyIndependentOfContext("MACRO(A *restrict a);"); 10287 verifyIndependentOfContext("MACRO(A *__restrict__ a);"); 10288 verifyIndependentOfContext("MACRO(A *__restrict a);"); 10289 verifyIndependentOfContext("MACRO(A *volatile a);"); 10290 verifyIndependentOfContext("MACRO(A *__volatile a);"); 10291 verifyIndependentOfContext("MACRO(A *__volatile__ a);"); 10292 verifyIndependentOfContext("MACRO(A *_Nonnull a);"); 10293 verifyIndependentOfContext("MACRO(A *_Nullable a);"); 10294 verifyIndependentOfContext("MACRO(A *_Null_unspecified a);"); 10295 verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);"); 10296 verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);"); 10297 verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);"); 10298 verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);"); 10299 verifyIndependentOfContext("MACRO(A *__ptr32 a);"); 10300 verifyIndependentOfContext("MACRO(A *__ptr64 a);"); 10301 verifyIndependentOfContext("MACRO(A *__capability);"); 10302 verifyIndependentOfContext("MACRO(A &__capability);"); 10303 verifyFormat("MACRO(A *__my_qualifier);"); // type declaration 10304 verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication 10305 // If we add __my_qualifier to AttributeMacros it should always be parsed as 10306 // a type declaration: 10307 verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier); 10308 verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier); 10309 // Also check that TypenameMacros prevents parsing it as multiplication: 10310 verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication 10311 verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type 10312 10313 verifyIndependentOfContext("MACRO('0' <= c && c <= '9');"); 10314 verifyFormat("void f() { f(float{1}, a * a); }"); 10315 verifyFormat("void f() { f(float(1), a * a); }"); 10316 10317 verifyFormat("f((void (*)(int))g);"); 10318 verifyFormat("f((void (&)(int))g);"); 10319 verifyFormat("f((void (^)(int))g);"); 10320 10321 // FIXME: Is there a way to make this work? 10322 // verifyIndependentOfContext("MACRO(A *a);"); 10323 verifyFormat("MACRO(A &B);"); 10324 verifyFormat("MACRO(A *B);"); 10325 verifyFormat("void f() { MACRO(A * B); }"); 10326 verifyFormat("void f() { MACRO(A & B); }"); 10327 10328 // This lambda was mis-formatted after D88956 (treating it as a binop): 10329 verifyFormat("auto x = [](const decltype(x) &ptr) {};"); 10330 verifyFormat("auto x = [](const decltype(x) *ptr) {};"); 10331 verifyFormat("#define lambda [](const decltype(x) &ptr) {}"); 10332 verifyFormat("#define lambda [](const decltype(x) *ptr) {}"); 10333 10334 verifyFormat("DatumHandle const *operator->() const { return input_; }"); 10335 verifyFormat("return options != nullptr && operator==(*options);"); 10336 10337 EXPECT_EQ("#define OP(x) \\\n" 10338 " ostream &operator<<(ostream &s, const A &a) { \\\n" 10339 " return s << a.DebugString(); \\\n" 10340 " }", 10341 format("#define OP(x) \\\n" 10342 " ostream &operator<<(ostream &s, const A &a) { \\\n" 10343 " return s << a.DebugString(); \\\n" 10344 " }", 10345 getLLVMStyleWithColumns(50))); 10346 10347 // FIXME: We cannot handle this case yet; we might be able to figure out that 10348 // foo<x> d > v; doesn't make sense. 10349 verifyFormat("foo<a<b && c> d> v;"); 10350 10351 FormatStyle PointerMiddle = getLLVMStyle(); 10352 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle; 10353 verifyFormat("delete *x;", PointerMiddle); 10354 verifyFormat("int * x;", PointerMiddle); 10355 verifyFormat("int *[] x;", PointerMiddle); 10356 verifyFormat("template <int * y> f() {}", PointerMiddle); 10357 verifyFormat("int * f(int * a) {}", PointerMiddle); 10358 verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle); 10359 verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle); 10360 verifyFormat("A<int *> a;", PointerMiddle); 10361 verifyFormat("A<int **> a;", PointerMiddle); 10362 verifyFormat("A<int *, int *> a;", PointerMiddle); 10363 verifyFormat("A<int *[]> a;", PointerMiddle); 10364 verifyFormat("A = new SomeType *[Length]();", PointerMiddle); 10365 verifyFormat("A = new SomeType *[Length];", PointerMiddle); 10366 verifyFormat("T ** t = new T *;", PointerMiddle); 10367 10368 // Member function reference qualifiers aren't binary operators. 10369 verifyFormat("string // break\n" 10370 "operator()() & {}"); 10371 verifyFormat("string // break\n" 10372 "operator()() && {}"); 10373 verifyGoogleFormat("template <typename T>\n" 10374 "auto x() & -> int {}"); 10375 10376 // Should be binary operators when used as an argument expression (overloaded 10377 // operator invoked as a member function). 10378 verifyFormat("void f() { a.operator()(a * a); }"); 10379 verifyFormat("void f() { a->operator()(a & a); }"); 10380 verifyFormat("void f() { a.operator()(*a & *a); }"); 10381 verifyFormat("void f() { a->operator()(*a * *a); }"); 10382 10383 verifyFormat("int operator()(T (&&)[N]) { return 1; }"); 10384 verifyFormat("int operator()(T (&)[N]) { return 0; }"); 10385 } 10386 10387 TEST_F(FormatTest, UnderstandsAttributes) { 10388 verifyFormat("SomeType s __attribute__((unused)) (InitValue);"); 10389 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n" 10390 "aaaaaaaaaaaaaaaaaaaaaaa(int i);"); 10391 verifyFormat("__attribute__((nodebug)) ::qualified_type f();"); 10392 FormatStyle AfterType = getLLVMStyle(); 10393 AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 10394 verifyFormat("__attribute__((nodebug)) void\n" 10395 "foo() {}\n", 10396 AfterType); 10397 verifyFormat("__unused void\n" 10398 "foo() {}", 10399 AfterType); 10400 10401 FormatStyle CustomAttrs = getLLVMStyle(); 10402 CustomAttrs.AttributeMacros.push_back("__unused"); 10403 CustomAttrs.AttributeMacros.push_back("__attr1"); 10404 CustomAttrs.AttributeMacros.push_back("__attr2"); 10405 CustomAttrs.AttributeMacros.push_back("no_underscore_attr"); 10406 verifyFormat("vector<SomeType *__attribute((foo))> v;"); 10407 verifyFormat("vector<SomeType *__attribute__((foo))> v;"); 10408 verifyFormat("vector<SomeType * __not_attribute__((foo))> v;"); 10409 // Check that it is parsed as a multiplication without AttributeMacros and 10410 // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros. 10411 verifyFormat("vector<SomeType * __attr1> v;"); 10412 verifyFormat("vector<SomeType __attr1 *> v;"); 10413 verifyFormat("vector<SomeType __attr1 *const> v;"); 10414 verifyFormat("vector<SomeType __attr1 * __attr2> v;"); 10415 verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs); 10416 verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs); 10417 verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs); 10418 verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs); 10419 verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs); 10420 verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs); 10421 verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs); 10422 10423 // Check that these are not parsed as function declarations: 10424 CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 10425 CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman; 10426 verifyFormat("SomeType s(InitValue);", CustomAttrs); 10427 verifyFormat("SomeType s{InitValue};", CustomAttrs); 10428 verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs); 10429 verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs); 10430 verifyFormat("SomeType s __unused(InitValue);", CustomAttrs); 10431 verifyFormat("SomeType s __unused{InitValue};", CustomAttrs); 10432 verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs); 10433 verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs); 10434 } 10435 10436 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) { 10437 // Check that qualifiers on pointers don't break parsing of casts. 10438 verifyFormat("x = (foo *const)*v;"); 10439 verifyFormat("x = (foo *volatile)*v;"); 10440 verifyFormat("x = (foo *restrict)*v;"); 10441 verifyFormat("x = (foo *__attribute__((foo)))*v;"); 10442 verifyFormat("x = (foo *_Nonnull)*v;"); 10443 verifyFormat("x = (foo *_Nullable)*v;"); 10444 verifyFormat("x = (foo *_Null_unspecified)*v;"); 10445 verifyFormat("x = (foo *_Nonnull)*v;"); 10446 verifyFormat("x = (foo *[[clang::attr]])*v;"); 10447 verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;"); 10448 verifyFormat("x = (foo *__ptr32)*v;"); 10449 verifyFormat("x = (foo *__ptr64)*v;"); 10450 verifyFormat("x = (foo *__capability)*v;"); 10451 10452 // Check that we handle multiple trailing qualifiers and skip them all to 10453 // determine that the expression is a cast to a pointer type. 10454 FormatStyle LongPointerRight = getLLVMStyleWithColumns(999); 10455 FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999); 10456 LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left; 10457 StringRef AllQualifiers = 10458 "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified " 10459 "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability"; 10460 verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight); 10461 verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft); 10462 10463 // Also check that address-of is not parsed as a binary bitwise-and: 10464 verifyFormat("x = (foo *const)&v;"); 10465 verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight); 10466 verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft); 10467 10468 // Check custom qualifiers: 10469 FormatStyle CustomQualifier = getLLVMStyleWithColumns(999); 10470 CustomQualifier.AttributeMacros.push_back("__my_qualifier"); 10471 verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier. 10472 verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier); 10473 verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(), 10474 CustomQualifier); 10475 verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(), 10476 CustomQualifier); 10477 10478 // Check that unknown identifiers result in binary operator parsing: 10479 verifyFormat("x = (foo * __unknown_qualifier) * v;"); 10480 verifyFormat("x = (foo * __unknown_qualifier) & v;"); 10481 } 10482 10483 TEST_F(FormatTest, UnderstandsSquareAttributes) { 10484 verifyFormat("SomeType s [[unused]] (InitValue);"); 10485 verifyFormat("SomeType s [[gnu::unused]] (InitValue);"); 10486 verifyFormat("SomeType s [[using gnu: unused]] (InitValue);"); 10487 verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}"); 10488 verifyFormat("void f() [[deprecated(\"so sorry\")]];"); 10489 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10490 " [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);"); 10491 verifyFormat("[[nodiscard]] bool f() { return false; }"); 10492 verifyFormat("class [[nodiscard]] f {\npublic:\n f() {}\n}"); 10493 verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n f() {}\n}"); 10494 verifyFormat("class [[gnu::unused]] f {\npublic:\n f() {}\n}"); 10495 verifyFormat("[[nodiscard]] ::qualified_type f();"); 10496 10497 // Make sure we do not mistake attributes for array subscripts. 10498 verifyFormat("int a() {}\n" 10499 "[[unused]] int b() {}\n"); 10500 verifyFormat("NSArray *arr;\n" 10501 "arr[[Foo() bar]];"); 10502 10503 // On the other hand, we still need to correctly find array subscripts. 10504 verifyFormat("int a = std::vector<int>{1, 2, 3}[0];"); 10505 10506 // Make sure that we do not mistake Objective-C method inside array literals 10507 // as attributes, even if those method names are also keywords. 10508 verifyFormat("@[ [foo bar] ];"); 10509 verifyFormat("@[ [NSArray class] ];"); 10510 verifyFormat("@[ [foo enum] ];"); 10511 10512 verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }"); 10513 10514 // Make sure we do not parse attributes as lambda introducers. 10515 FormatStyle MultiLineFunctions = getLLVMStyle(); 10516 MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 10517 verifyFormat("[[unused]] int b() {\n" 10518 " return 42;\n" 10519 "}\n", 10520 MultiLineFunctions); 10521 } 10522 10523 TEST_F(FormatTest, AttributeClass) { 10524 FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp); 10525 verifyFormat("class S {\n" 10526 " S(S&&) = default;\n" 10527 "};", 10528 Style); 10529 verifyFormat("class [[nodiscard]] S {\n" 10530 " S(S&&) = default;\n" 10531 "};", 10532 Style); 10533 verifyFormat("class __attribute((maybeunused)) S {\n" 10534 " S(S&&) = default;\n" 10535 "};", 10536 Style); 10537 verifyFormat("struct S {\n" 10538 " S(S&&) = default;\n" 10539 "};", 10540 Style); 10541 verifyFormat("struct [[nodiscard]] S {\n" 10542 " S(S&&) = default;\n" 10543 "};", 10544 Style); 10545 } 10546 10547 TEST_F(FormatTest, AttributesAfterMacro) { 10548 FormatStyle Style = getLLVMStyle(); 10549 verifyFormat("MACRO;\n" 10550 "__attribute__((maybe_unused)) int foo() {\n" 10551 " //...\n" 10552 "}"); 10553 10554 verifyFormat("MACRO;\n" 10555 "[[nodiscard]] int foo() {\n" 10556 " //...\n" 10557 "}"); 10558 10559 EXPECT_EQ("MACRO\n\n" 10560 "__attribute__((maybe_unused)) int foo() {\n" 10561 " //...\n" 10562 "}", 10563 format("MACRO\n\n" 10564 "__attribute__((maybe_unused)) int foo() {\n" 10565 " //...\n" 10566 "}")); 10567 10568 EXPECT_EQ("MACRO\n\n" 10569 "[[nodiscard]] int foo() {\n" 10570 " //...\n" 10571 "}", 10572 format("MACRO\n\n" 10573 "[[nodiscard]] int foo() {\n" 10574 " //...\n" 10575 "}")); 10576 } 10577 10578 TEST_F(FormatTest, AttributePenaltyBreaking) { 10579 FormatStyle Style = getLLVMStyle(); 10580 verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n" 10581 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}", 10582 Style); 10583 verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n" 10584 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}", 10585 Style); 10586 verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const " 10587 "shared_ptr<ALongTypeName> &C d) {\n}", 10588 Style); 10589 } 10590 10591 TEST_F(FormatTest, UnderstandsEllipsis) { 10592 FormatStyle Style = getLLVMStyle(); 10593 verifyFormat("int printf(const char *fmt, ...);"); 10594 verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }"); 10595 verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}"); 10596 10597 verifyFormat("template <int *...PP> a;", Style); 10598 10599 Style.PointerAlignment = FormatStyle::PAS_Left; 10600 verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style); 10601 10602 verifyFormat("template <int*... PP> a;", Style); 10603 10604 Style.PointerAlignment = FormatStyle::PAS_Middle; 10605 verifyFormat("template <int *... PP> a;", Style); 10606 } 10607 10608 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) { 10609 EXPECT_EQ("int *a;\n" 10610 "int *a;\n" 10611 "int *a;", 10612 format("int *a;\n" 10613 "int* a;\n" 10614 "int *a;", 10615 getGoogleStyle())); 10616 EXPECT_EQ("int* a;\n" 10617 "int* a;\n" 10618 "int* a;", 10619 format("int* a;\n" 10620 "int* a;\n" 10621 "int *a;", 10622 getGoogleStyle())); 10623 EXPECT_EQ("int *a;\n" 10624 "int *a;\n" 10625 "int *a;", 10626 format("int *a;\n" 10627 "int * a;\n" 10628 "int * a;", 10629 getGoogleStyle())); 10630 EXPECT_EQ("auto x = [] {\n" 10631 " int *a;\n" 10632 " int *a;\n" 10633 " int *a;\n" 10634 "};", 10635 format("auto x=[]{int *a;\n" 10636 "int * a;\n" 10637 "int * a;};", 10638 getGoogleStyle())); 10639 } 10640 10641 TEST_F(FormatTest, UnderstandsRvalueReferences) { 10642 verifyFormat("int f(int &&a) {}"); 10643 verifyFormat("int f(int a, char &&b) {}"); 10644 verifyFormat("void f() { int &&a = b; }"); 10645 verifyGoogleFormat("int f(int a, char&& b) {}"); 10646 verifyGoogleFormat("void f() { int&& a = b; }"); 10647 10648 verifyIndependentOfContext("A<int &&> a;"); 10649 verifyIndependentOfContext("A<int &&, int &&> a;"); 10650 verifyGoogleFormat("A<int&&> a;"); 10651 verifyGoogleFormat("A<int&&, int&&> a;"); 10652 10653 // Not rvalue references: 10654 verifyFormat("template <bool B, bool C> class A {\n" 10655 " static_assert(B && C, \"Something is wrong\");\n" 10656 "};"); 10657 verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))"); 10658 verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))"); 10659 verifyFormat("#define A(a, b) (a && b)"); 10660 } 10661 10662 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) { 10663 verifyFormat("void f() {\n" 10664 " x[aaaaaaaaa -\n" 10665 " b] = 23;\n" 10666 "}", 10667 getLLVMStyleWithColumns(15)); 10668 } 10669 10670 TEST_F(FormatTest, FormatsCasts) { 10671 verifyFormat("Type *A = static_cast<Type *>(P);"); 10672 verifyFormat("static_cast<Type *>(P);"); 10673 verifyFormat("static_cast<Type &>(Fun)(Args);"); 10674 verifyFormat("static_cast<Type &>(*Fun)(Args);"); 10675 verifyFormat("if (static_cast<int>(A) + B >= 0)\n ;"); 10676 // Check that static_cast<...>(...) does not require the next token to be on 10677 // the same line. 10678 verifyFormat("some_loooong_output << something_something__ << " 10679 "static_cast<const void *>(R)\n" 10680 " << something;"); 10681 verifyFormat("a = static_cast<Type &>(*Fun)(Args);"); 10682 verifyFormat("const_cast<Type &>(*Fun)(Args);"); 10683 verifyFormat("dynamic_cast<Type &>(*Fun)(Args);"); 10684 verifyFormat("reinterpret_cast<Type &>(*Fun)(Args);"); 10685 verifyFormat("Type *A = (Type *)P;"); 10686 verifyFormat("Type *A = (vector<Type *, int *>)P;"); 10687 verifyFormat("int a = (int)(2.0f);"); 10688 verifyFormat("int a = (int)2.0f;"); 10689 verifyFormat("x[(int32)y];"); 10690 verifyFormat("x = (int32)y;"); 10691 verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)"); 10692 verifyFormat("int a = (int)*b;"); 10693 verifyFormat("int a = (int)2.0f;"); 10694 verifyFormat("int a = (int)~0;"); 10695 verifyFormat("int a = (int)++a;"); 10696 verifyFormat("int a = (int)sizeof(int);"); 10697 verifyFormat("int a = (int)+2;"); 10698 verifyFormat("my_int a = (my_int)2.0f;"); 10699 verifyFormat("my_int a = (my_int)sizeof(int);"); 10700 verifyFormat("return (my_int)aaa;"); 10701 verifyFormat("#define x ((int)-1)"); 10702 verifyFormat("#define LENGTH(x, y) (x) - (y) + 1"); 10703 verifyFormat("#define p(q) ((int *)&q)"); 10704 verifyFormat("fn(a)(b) + 1;"); 10705 10706 verifyFormat("void f() { my_int a = (my_int)*b; }"); 10707 verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }"); 10708 verifyFormat("my_int a = (my_int)~0;"); 10709 verifyFormat("my_int a = (my_int)++a;"); 10710 verifyFormat("my_int a = (my_int)-2;"); 10711 verifyFormat("my_int a = (my_int)1;"); 10712 verifyFormat("my_int a = (my_int *)1;"); 10713 verifyFormat("my_int a = (const my_int)-1;"); 10714 verifyFormat("my_int a = (const my_int *)-1;"); 10715 verifyFormat("my_int a = (my_int)(my_int)-1;"); 10716 verifyFormat("my_int a = (ns::my_int)-2;"); 10717 verifyFormat("case (my_int)ONE:"); 10718 verifyFormat("auto x = (X)this;"); 10719 // Casts in Obj-C style calls used to not be recognized as such. 10720 verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle()); 10721 10722 // FIXME: single value wrapped with paren will be treated as cast. 10723 verifyFormat("void f(int i = (kValue)*kMask) {}"); 10724 10725 verifyFormat("{ (void)F; }"); 10726 10727 // Don't break after a cast's 10728 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 10729 " (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n" 10730 " bbbbbbbbbbbbbbbbbbbbbb);"); 10731 10732 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(x)"); 10733 verifyFormat("#define CONF_BOOL(x) (bool *)(x)"); 10734 verifyFormat("#define CONF_BOOL(x) (bool)(x)"); 10735 verifyFormat("bool *y = (bool *)(void *)(x);"); 10736 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)(x)"); 10737 verifyFormat("bool *y = (bool *)(void *)(int)(x);"); 10738 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)foo(x)"); 10739 verifyFormat("bool *y = (bool *)(void *)(int)foo(x);"); 10740 10741 // These are not casts. 10742 verifyFormat("void f(int *) {}"); 10743 verifyFormat("f(foo)->b;"); 10744 verifyFormat("f(foo).b;"); 10745 verifyFormat("f(foo)(b);"); 10746 verifyFormat("f(foo)[b];"); 10747 verifyFormat("[](foo) { return 4; }(bar);"); 10748 verifyFormat("(*funptr)(foo)[4];"); 10749 verifyFormat("funptrs[4](foo)[4];"); 10750 verifyFormat("void f(int *);"); 10751 verifyFormat("void f(int *) = 0;"); 10752 verifyFormat("void f(SmallVector<int>) {}"); 10753 verifyFormat("void f(SmallVector<int>);"); 10754 verifyFormat("void f(SmallVector<int>) = 0;"); 10755 verifyFormat("void f(int i = (kA * kB) & kMask) {}"); 10756 verifyFormat("int a = sizeof(int) * b;"); 10757 verifyFormat("int a = alignof(int) * b;", getGoogleStyle()); 10758 verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;"); 10759 verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");"); 10760 verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;"); 10761 10762 // These are not casts, but at some point were confused with casts. 10763 verifyFormat("virtual void foo(int *) override;"); 10764 verifyFormat("virtual void foo(char &) const;"); 10765 verifyFormat("virtual void foo(int *a, char *) const;"); 10766 verifyFormat("int a = sizeof(int *) + b;"); 10767 verifyFormat("int a = alignof(int *) + b;", getGoogleStyle()); 10768 verifyFormat("bool b = f(g<int>) && c;"); 10769 verifyFormat("typedef void (*f)(int i) func;"); 10770 verifyFormat("void operator++(int) noexcept;"); 10771 verifyFormat("void operator++(int &) noexcept;"); 10772 verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t " 10773 "&) noexcept;"); 10774 verifyFormat( 10775 "void operator delete(std::size_t, const std::nothrow_t &) noexcept;"); 10776 verifyFormat("void operator delete(const std::nothrow_t &) noexcept;"); 10777 verifyFormat("void operator delete(std::nothrow_t &) noexcept;"); 10778 verifyFormat("void operator delete(nothrow_t &) noexcept;"); 10779 verifyFormat("void operator delete(foo &) noexcept;"); 10780 verifyFormat("void operator delete(foo) noexcept;"); 10781 verifyFormat("void operator delete(int) noexcept;"); 10782 verifyFormat("void operator delete(int &) noexcept;"); 10783 verifyFormat("void operator delete(int &) volatile noexcept;"); 10784 verifyFormat("void operator delete(int &) const"); 10785 verifyFormat("void operator delete(int &) = default"); 10786 verifyFormat("void operator delete(int &) = delete"); 10787 verifyFormat("void operator delete(int &) [[noreturn]]"); 10788 verifyFormat("void operator delete(int &) throw();"); 10789 verifyFormat("void operator delete(int &) throw(int);"); 10790 verifyFormat("auto operator delete(int &) -> int;"); 10791 verifyFormat("auto operator delete(int &) override"); 10792 verifyFormat("auto operator delete(int &) final"); 10793 10794 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n" 10795 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 10796 // FIXME: The indentation here is not ideal. 10797 verifyFormat( 10798 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10799 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n" 10800 " [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];"); 10801 } 10802 10803 TEST_F(FormatTest, FormatsFunctionTypes) { 10804 verifyFormat("A<bool()> a;"); 10805 verifyFormat("A<SomeType()> a;"); 10806 verifyFormat("A<void (*)(int, std::string)> a;"); 10807 verifyFormat("A<void *(int)>;"); 10808 verifyFormat("void *(*a)(int *, SomeType *);"); 10809 verifyFormat("int (*func)(void *);"); 10810 verifyFormat("void f() { int (*func)(void *); }"); 10811 verifyFormat("template <class CallbackClass>\n" 10812 "using MyCallback = void (CallbackClass::*)(SomeObject *Data);"); 10813 10814 verifyGoogleFormat("A<void*(int*, SomeType*)>;"); 10815 verifyGoogleFormat("void* (*a)(int);"); 10816 verifyGoogleFormat( 10817 "template <class CallbackClass>\n" 10818 "using MyCallback = void (CallbackClass::*)(SomeObject* Data);"); 10819 10820 // Other constructs can look somewhat like function types: 10821 verifyFormat("A<sizeof(*x)> a;"); 10822 verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)"); 10823 verifyFormat("some_var = function(*some_pointer_var)[0];"); 10824 verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }"); 10825 verifyFormat("int x = f(&h)();"); 10826 verifyFormat("returnsFunction(¶m1, ¶m2)(param);"); 10827 verifyFormat("std::function<\n" 10828 " LooooooooooongTemplatedType<\n" 10829 " SomeType>*(\n" 10830 " LooooooooooooooooongType type)>\n" 10831 " function;", 10832 getGoogleStyleWithColumns(40)); 10833 } 10834 10835 TEST_F(FormatTest, FormatsPointersToArrayTypes) { 10836 verifyFormat("A (*foo_)[6];"); 10837 verifyFormat("vector<int> (*foo_)[6];"); 10838 } 10839 10840 TEST_F(FormatTest, BreaksLongVariableDeclarations) { 10841 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10842 " LoooooooooooooooooooooooooooooooooooooooongVariable;"); 10843 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n" 10844 " LoooooooooooooooooooooooooooooooooooooooongVariable;"); 10845 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10846 " *LoooooooooooooooooooooooooooooooooooooooongVariable;"); 10847 10848 // Different ways of ()-initializiation. 10849 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10850 " LoooooooooooooooooooooooooooooooooooooooongVariable(1);"); 10851 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10852 " LoooooooooooooooooooooooooooooooooooooooongVariable(a);"); 10853 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10854 " LoooooooooooooooooooooooooooooooooooooooongVariable({});"); 10855 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10856 " LoooooooooooooooooooooooooooooooooooooongVariable([A a]);"); 10857 10858 // Lambdas should not confuse the variable declaration heuristic. 10859 verifyFormat("LooooooooooooooooongType\n" 10860 " variable(nullptr, [](A *a) {});", 10861 getLLVMStyleWithColumns(40)); 10862 } 10863 10864 TEST_F(FormatTest, BreaksLongDeclarations) { 10865 verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n" 10866 " AnotherNameForTheLongType;"); 10867 verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n" 10868 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 10869 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10870 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();"); 10871 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n" 10872 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();"); 10873 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10874 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10875 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n" 10876 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10877 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n" 10878 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10879 verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n" 10880 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10881 verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n" 10882 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10883 verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n" 10884 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10885 verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n" 10886 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10887 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10888 "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);"); 10889 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10890 "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}"); 10891 FormatStyle Indented = getLLVMStyle(); 10892 Indented.IndentWrappedFunctionNames = true; 10893 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10894 " LoooooooooooooooooooooooooooooooongFunctionDeclaration();", 10895 Indented); 10896 verifyFormat( 10897 "LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10898 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 10899 Indented); 10900 verifyFormat( 10901 "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n" 10902 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 10903 Indented); 10904 verifyFormat( 10905 "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n" 10906 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 10907 Indented); 10908 10909 // FIXME: Without the comment, this breaks after "(". 10910 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType // break\n" 10911 " (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();", 10912 getGoogleStyle()); 10913 10914 verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n" 10915 " int LoooooooooooooooooooongParam2) {}"); 10916 verifyFormat( 10917 "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n" 10918 " SourceLocation L, IdentifierIn *II,\n" 10919 " Type *T) {}"); 10920 verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n" 10921 "ReallyReaaallyLongFunctionName(\n" 10922 " const std::string &SomeParameter,\n" 10923 " const SomeType<string, SomeOtherTemplateParameter>\n" 10924 " &ReallyReallyLongParameterName,\n" 10925 " const SomeType<string, SomeOtherTemplateParameter>\n" 10926 " &AnotherLongParameterName) {}"); 10927 verifyFormat("template <typename A>\n" 10928 "SomeLoooooooooooooooooooooongType<\n" 10929 " typename some_namespace::SomeOtherType<A>::Type>\n" 10930 "Function() {}"); 10931 10932 verifyGoogleFormat( 10933 "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n" 10934 " aaaaaaaaaaaaaaaaaaaaaaa;"); 10935 verifyGoogleFormat( 10936 "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n" 10937 " SourceLocation L) {}"); 10938 verifyGoogleFormat( 10939 "some_namespace::LongReturnType\n" 10940 "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n" 10941 " int first_long_parameter, int second_parameter) {}"); 10942 10943 verifyGoogleFormat("template <typename T>\n" 10944 "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n" 10945 "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}"); 10946 verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 10947 " int aaaaaaaaaaaaaaaaaaaaaaa);"); 10948 10949 verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n" 10950 " const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10951 " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 10952 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 10953 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n" 10954 " aaaaaaaaaaaaaaaaaaaaaaaa);"); 10955 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 10956 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 10957 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n" 10958 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 10959 10960 verifyFormat("template <typename T> // Templates on own line.\n" 10961 "static int // Some comment.\n" 10962 "MyFunction(int a);", 10963 getLLVMStyle()); 10964 } 10965 10966 TEST_F(FormatTest, FormatsAccessModifiers) { 10967 FormatStyle Style = getLLVMStyle(); 10968 EXPECT_EQ(Style.EmptyLineBeforeAccessModifier, 10969 FormatStyle::ELBAMS_LogicalBlock); 10970 verifyFormat("struct foo {\n" 10971 "private:\n" 10972 " void f() {}\n" 10973 "\n" 10974 "private:\n" 10975 " int i;\n" 10976 "\n" 10977 "protected:\n" 10978 " int j;\n" 10979 "};\n", 10980 Style); 10981 verifyFormat("struct foo {\n" 10982 "private:\n" 10983 " void f() {}\n" 10984 "\n" 10985 "private:\n" 10986 " int i;\n" 10987 "\n" 10988 "protected:\n" 10989 " int j;\n" 10990 "};\n", 10991 "struct foo {\n" 10992 "private:\n" 10993 " void f() {}\n" 10994 "private:\n" 10995 " int i;\n" 10996 "protected:\n" 10997 " int j;\n" 10998 "};\n", 10999 Style); 11000 verifyFormat("struct foo { /* comment */\n" 11001 "private:\n" 11002 " int i;\n" 11003 " // comment\n" 11004 "private:\n" 11005 " int j;\n" 11006 "};\n", 11007 Style); 11008 verifyFormat("struct foo {\n" 11009 "#ifdef FOO\n" 11010 "#endif\n" 11011 "private:\n" 11012 " int i;\n" 11013 "#ifdef FOO\n" 11014 "private:\n" 11015 "#endif\n" 11016 " int j;\n" 11017 "};\n", 11018 Style); 11019 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11020 verifyFormat("struct foo {\n" 11021 "private:\n" 11022 " void f() {}\n" 11023 "private:\n" 11024 " int i;\n" 11025 "protected:\n" 11026 " int j;\n" 11027 "};\n", 11028 Style); 11029 verifyFormat("struct foo {\n" 11030 "private:\n" 11031 " void f() {}\n" 11032 "private:\n" 11033 " int i;\n" 11034 "protected:\n" 11035 " int j;\n" 11036 "};\n", 11037 "struct foo {\n" 11038 "\n" 11039 "private:\n" 11040 " void f() {}\n" 11041 "\n" 11042 "private:\n" 11043 " int i;\n" 11044 "\n" 11045 "protected:\n" 11046 " int j;\n" 11047 "};\n", 11048 Style); 11049 verifyFormat("struct foo { /* comment */\n" 11050 "private:\n" 11051 " int i;\n" 11052 " // comment\n" 11053 "private:\n" 11054 " int j;\n" 11055 "};\n", 11056 "struct foo { /* comment */\n" 11057 "\n" 11058 "private:\n" 11059 " int i;\n" 11060 " // comment\n" 11061 "\n" 11062 "private:\n" 11063 " int j;\n" 11064 "};\n", 11065 Style); 11066 verifyFormat("struct foo {\n" 11067 "#ifdef FOO\n" 11068 "#endif\n" 11069 "private:\n" 11070 " int i;\n" 11071 "#ifdef FOO\n" 11072 "private:\n" 11073 "#endif\n" 11074 " int j;\n" 11075 "};\n", 11076 "struct foo {\n" 11077 "#ifdef FOO\n" 11078 "#endif\n" 11079 "\n" 11080 "private:\n" 11081 " int i;\n" 11082 "#ifdef FOO\n" 11083 "\n" 11084 "private:\n" 11085 "#endif\n" 11086 " int j;\n" 11087 "};\n", 11088 Style); 11089 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11090 verifyFormat("struct foo {\n" 11091 "private:\n" 11092 " void f() {}\n" 11093 "\n" 11094 "private:\n" 11095 " int i;\n" 11096 "\n" 11097 "protected:\n" 11098 " int j;\n" 11099 "};\n", 11100 Style); 11101 verifyFormat("struct foo {\n" 11102 "private:\n" 11103 " void f() {}\n" 11104 "\n" 11105 "private:\n" 11106 " int i;\n" 11107 "\n" 11108 "protected:\n" 11109 " int j;\n" 11110 "};\n", 11111 "struct foo {\n" 11112 "private:\n" 11113 " void f() {}\n" 11114 "private:\n" 11115 " int i;\n" 11116 "protected:\n" 11117 " int j;\n" 11118 "};\n", 11119 Style); 11120 verifyFormat("struct foo { /* comment */\n" 11121 "private:\n" 11122 " int i;\n" 11123 " // comment\n" 11124 "\n" 11125 "private:\n" 11126 " int j;\n" 11127 "};\n", 11128 "struct foo { /* comment */\n" 11129 "private:\n" 11130 " int i;\n" 11131 " // comment\n" 11132 "\n" 11133 "private:\n" 11134 " int j;\n" 11135 "};\n", 11136 Style); 11137 verifyFormat("struct foo {\n" 11138 "#ifdef FOO\n" 11139 "#endif\n" 11140 "\n" 11141 "private:\n" 11142 " int i;\n" 11143 "#ifdef FOO\n" 11144 "\n" 11145 "private:\n" 11146 "#endif\n" 11147 " int j;\n" 11148 "};\n", 11149 "struct foo {\n" 11150 "#ifdef FOO\n" 11151 "#endif\n" 11152 "private:\n" 11153 " int i;\n" 11154 "#ifdef FOO\n" 11155 "private:\n" 11156 "#endif\n" 11157 " int j;\n" 11158 "};\n", 11159 Style); 11160 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11161 EXPECT_EQ("struct foo {\n" 11162 "\n" 11163 "private:\n" 11164 " void f() {}\n" 11165 "\n" 11166 "private:\n" 11167 " int i;\n" 11168 "\n" 11169 "protected:\n" 11170 " int j;\n" 11171 "};\n", 11172 format("struct foo {\n" 11173 "\n" 11174 "private:\n" 11175 " void f() {}\n" 11176 "\n" 11177 "private:\n" 11178 " int i;\n" 11179 "\n" 11180 "protected:\n" 11181 " int j;\n" 11182 "};\n", 11183 Style)); 11184 verifyFormat("struct foo {\n" 11185 "private:\n" 11186 " void f() {}\n" 11187 "private:\n" 11188 " int i;\n" 11189 "protected:\n" 11190 " int j;\n" 11191 "};\n", 11192 Style); 11193 EXPECT_EQ("struct foo { /* comment */\n" 11194 "\n" 11195 "private:\n" 11196 " int i;\n" 11197 " // comment\n" 11198 "\n" 11199 "private:\n" 11200 " int j;\n" 11201 "};\n", 11202 format("struct foo { /* comment */\n" 11203 "\n" 11204 "private:\n" 11205 " int i;\n" 11206 " // comment\n" 11207 "\n" 11208 "private:\n" 11209 " int j;\n" 11210 "};\n", 11211 Style)); 11212 verifyFormat("struct foo { /* comment */\n" 11213 "private:\n" 11214 " int i;\n" 11215 " // comment\n" 11216 "private:\n" 11217 " int j;\n" 11218 "};\n", 11219 Style); 11220 EXPECT_EQ("struct foo {\n" 11221 "#ifdef FOO\n" 11222 "#endif\n" 11223 "\n" 11224 "private:\n" 11225 " int i;\n" 11226 "#ifdef FOO\n" 11227 "\n" 11228 "private:\n" 11229 "#endif\n" 11230 " int j;\n" 11231 "};\n", 11232 format("struct foo {\n" 11233 "#ifdef FOO\n" 11234 "#endif\n" 11235 "\n" 11236 "private:\n" 11237 " int i;\n" 11238 "#ifdef FOO\n" 11239 "\n" 11240 "private:\n" 11241 "#endif\n" 11242 " int j;\n" 11243 "};\n", 11244 Style)); 11245 verifyFormat("struct foo {\n" 11246 "#ifdef FOO\n" 11247 "#endif\n" 11248 "private:\n" 11249 " int i;\n" 11250 "#ifdef FOO\n" 11251 "private:\n" 11252 "#endif\n" 11253 " int j;\n" 11254 "};\n", 11255 Style); 11256 11257 FormatStyle NoEmptyLines = getLLVMStyle(); 11258 NoEmptyLines.MaxEmptyLinesToKeep = 0; 11259 verifyFormat("struct foo {\n" 11260 "private:\n" 11261 " void f() {}\n" 11262 "\n" 11263 "private:\n" 11264 " int i;\n" 11265 "\n" 11266 "public:\n" 11267 "protected:\n" 11268 " int j;\n" 11269 "};\n", 11270 NoEmptyLines); 11271 11272 NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11273 verifyFormat("struct foo {\n" 11274 "private:\n" 11275 " void f() {}\n" 11276 "private:\n" 11277 " int i;\n" 11278 "public:\n" 11279 "protected:\n" 11280 " int j;\n" 11281 "};\n", 11282 NoEmptyLines); 11283 11284 NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11285 verifyFormat("struct foo {\n" 11286 "private:\n" 11287 " void f() {}\n" 11288 "\n" 11289 "private:\n" 11290 " int i;\n" 11291 "\n" 11292 "public:\n" 11293 "\n" 11294 "protected:\n" 11295 " int j;\n" 11296 "};\n", 11297 NoEmptyLines); 11298 } 11299 11300 TEST_F(FormatTest, FormatsAfterAccessModifiers) { 11301 11302 FormatStyle Style = getLLVMStyle(); 11303 EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never); 11304 verifyFormat("struct foo {\n" 11305 "private:\n" 11306 " void f() {}\n" 11307 "\n" 11308 "private:\n" 11309 " int i;\n" 11310 "\n" 11311 "protected:\n" 11312 " int j;\n" 11313 "};\n", 11314 Style); 11315 11316 // Check if lines are removed. 11317 verifyFormat("struct foo {\n" 11318 "private:\n" 11319 " void f() {}\n" 11320 "\n" 11321 "private:\n" 11322 " int i;\n" 11323 "\n" 11324 "protected:\n" 11325 " int j;\n" 11326 "};\n", 11327 "struct foo {\n" 11328 "private:\n" 11329 "\n" 11330 " void f() {}\n" 11331 "\n" 11332 "private:\n" 11333 "\n" 11334 " int i;\n" 11335 "\n" 11336 "protected:\n" 11337 "\n" 11338 " int j;\n" 11339 "};\n", 11340 Style); 11341 11342 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11343 verifyFormat("struct foo {\n" 11344 "private:\n" 11345 "\n" 11346 " void f() {}\n" 11347 "\n" 11348 "private:\n" 11349 "\n" 11350 " int i;\n" 11351 "\n" 11352 "protected:\n" 11353 "\n" 11354 " int j;\n" 11355 "};\n", 11356 Style); 11357 11358 // Check if lines are added. 11359 verifyFormat("struct foo {\n" 11360 "private:\n" 11361 "\n" 11362 " void f() {}\n" 11363 "\n" 11364 "private:\n" 11365 "\n" 11366 " int i;\n" 11367 "\n" 11368 "protected:\n" 11369 "\n" 11370 " int j;\n" 11371 "};\n", 11372 "struct foo {\n" 11373 "private:\n" 11374 " void f() {}\n" 11375 "\n" 11376 "private:\n" 11377 " int i;\n" 11378 "\n" 11379 "protected:\n" 11380 " int j;\n" 11381 "};\n", 11382 Style); 11383 11384 // Leave tests rely on the code layout, test::messUp can not be used. 11385 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11386 Style.MaxEmptyLinesToKeep = 0u; 11387 verifyFormat("struct foo {\n" 11388 "private:\n" 11389 " void f() {}\n" 11390 "\n" 11391 "private:\n" 11392 " int i;\n" 11393 "\n" 11394 "protected:\n" 11395 " int j;\n" 11396 "};\n", 11397 Style); 11398 11399 // Check if MaxEmptyLinesToKeep is respected. 11400 EXPECT_EQ("struct foo {\n" 11401 "private:\n" 11402 " void f() {}\n" 11403 "\n" 11404 "private:\n" 11405 " int i;\n" 11406 "\n" 11407 "protected:\n" 11408 " int j;\n" 11409 "};\n", 11410 format("struct foo {\n" 11411 "private:\n" 11412 "\n\n\n" 11413 " void f() {}\n" 11414 "\n" 11415 "private:\n" 11416 "\n\n\n" 11417 " int i;\n" 11418 "\n" 11419 "protected:\n" 11420 "\n\n\n" 11421 " int j;\n" 11422 "};\n", 11423 Style)); 11424 11425 Style.MaxEmptyLinesToKeep = 1u; 11426 EXPECT_EQ("struct foo {\n" 11427 "private:\n" 11428 "\n" 11429 " void f() {}\n" 11430 "\n" 11431 "private:\n" 11432 "\n" 11433 " int i;\n" 11434 "\n" 11435 "protected:\n" 11436 "\n" 11437 " int j;\n" 11438 "};\n", 11439 format("struct foo {\n" 11440 "private:\n" 11441 "\n" 11442 " void f() {}\n" 11443 "\n" 11444 "private:\n" 11445 "\n" 11446 " int i;\n" 11447 "\n" 11448 "protected:\n" 11449 "\n" 11450 " int j;\n" 11451 "};\n", 11452 Style)); 11453 // Check if no lines are kept. 11454 EXPECT_EQ("struct foo {\n" 11455 "private:\n" 11456 " void f() {}\n" 11457 "\n" 11458 "private:\n" 11459 " int i;\n" 11460 "\n" 11461 "protected:\n" 11462 " int j;\n" 11463 "};\n", 11464 format("struct foo {\n" 11465 "private:\n" 11466 " void f() {}\n" 11467 "\n" 11468 "private:\n" 11469 " int i;\n" 11470 "\n" 11471 "protected:\n" 11472 " int j;\n" 11473 "};\n", 11474 Style)); 11475 // Check if MaxEmptyLinesToKeep is respected. 11476 EXPECT_EQ("struct foo {\n" 11477 "private:\n" 11478 "\n" 11479 " void f() {}\n" 11480 "\n" 11481 "private:\n" 11482 "\n" 11483 " int i;\n" 11484 "\n" 11485 "protected:\n" 11486 "\n" 11487 " int j;\n" 11488 "};\n", 11489 format("struct foo {\n" 11490 "private:\n" 11491 "\n\n\n" 11492 " void f() {}\n" 11493 "\n" 11494 "private:\n" 11495 "\n\n\n" 11496 " int i;\n" 11497 "\n" 11498 "protected:\n" 11499 "\n\n\n" 11500 " int j;\n" 11501 "};\n", 11502 Style)); 11503 11504 Style.MaxEmptyLinesToKeep = 10u; 11505 EXPECT_EQ("struct foo {\n" 11506 "private:\n" 11507 "\n\n\n" 11508 " void f() {}\n" 11509 "\n" 11510 "private:\n" 11511 "\n\n\n" 11512 " int i;\n" 11513 "\n" 11514 "protected:\n" 11515 "\n\n\n" 11516 " int j;\n" 11517 "};\n", 11518 format("struct foo {\n" 11519 "private:\n" 11520 "\n\n\n" 11521 " void f() {}\n" 11522 "\n" 11523 "private:\n" 11524 "\n\n\n" 11525 " int i;\n" 11526 "\n" 11527 "protected:\n" 11528 "\n\n\n" 11529 " int j;\n" 11530 "};\n", 11531 Style)); 11532 11533 // Test with comments. 11534 Style = getLLVMStyle(); 11535 verifyFormat("struct foo {\n" 11536 "private:\n" 11537 " // comment\n" 11538 " void f() {}\n" 11539 "\n" 11540 "private: /* comment */\n" 11541 " int i;\n" 11542 "};\n", 11543 Style); 11544 verifyFormat("struct foo {\n" 11545 "private:\n" 11546 " // comment\n" 11547 " void f() {}\n" 11548 "\n" 11549 "private: /* comment */\n" 11550 " int i;\n" 11551 "};\n", 11552 "struct foo {\n" 11553 "private:\n" 11554 "\n" 11555 " // comment\n" 11556 " void f() {}\n" 11557 "\n" 11558 "private: /* comment */\n" 11559 "\n" 11560 " int i;\n" 11561 "};\n", 11562 Style); 11563 11564 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11565 verifyFormat("struct foo {\n" 11566 "private:\n" 11567 "\n" 11568 " // comment\n" 11569 " void f() {}\n" 11570 "\n" 11571 "private: /* comment */\n" 11572 "\n" 11573 " int i;\n" 11574 "};\n", 11575 "struct foo {\n" 11576 "private:\n" 11577 " // comment\n" 11578 " void f() {}\n" 11579 "\n" 11580 "private: /* comment */\n" 11581 " int i;\n" 11582 "};\n", 11583 Style); 11584 verifyFormat("struct foo {\n" 11585 "private:\n" 11586 "\n" 11587 " // comment\n" 11588 " void f() {}\n" 11589 "\n" 11590 "private: /* comment */\n" 11591 "\n" 11592 " int i;\n" 11593 "};\n", 11594 Style); 11595 11596 // Test with preprocessor defines. 11597 Style = getLLVMStyle(); 11598 verifyFormat("struct foo {\n" 11599 "private:\n" 11600 "#ifdef FOO\n" 11601 "#endif\n" 11602 " void f() {}\n" 11603 "};\n", 11604 Style); 11605 verifyFormat("struct foo {\n" 11606 "private:\n" 11607 "#ifdef FOO\n" 11608 "#endif\n" 11609 " void f() {}\n" 11610 "};\n", 11611 "struct foo {\n" 11612 "private:\n" 11613 "\n" 11614 "#ifdef FOO\n" 11615 "#endif\n" 11616 " void f() {}\n" 11617 "};\n", 11618 Style); 11619 11620 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11621 verifyFormat("struct foo {\n" 11622 "private:\n" 11623 "\n" 11624 "#ifdef FOO\n" 11625 "#endif\n" 11626 " void f() {}\n" 11627 "};\n", 11628 "struct foo {\n" 11629 "private:\n" 11630 "#ifdef FOO\n" 11631 "#endif\n" 11632 " void f() {}\n" 11633 "};\n", 11634 Style); 11635 verifyFormat("struct foo {\n" 11636 "private:\n" 11637 "\n" 11638 "#ifdef FOO\n" 11639 "#endif\n" 11640 " void f() {}\n" 11641 "};\n", 11642 Style); 11643 } 11644 11645 TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) { 11646 // Combined tests of EmptyLineAfterAccessModifier and 11647 // EmptyLineBeforeAccessModifier. 11648 FormatStyle Style = getLLVMStyle(); 11649 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11650 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11651 verifyFormat("struct foo {\n" 11652 "private:\n" 11653 "\n" 11654 "protected:\n" 11655 "};\n", 11656 Style); 11657 11658 Style.MaxEmptyLinesToKeep = 10u; 11659 // Both remove all new lines. 11660 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11661 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11662 verifyFormat("struct foo {\n" 11663 "private:\n" 11664 "protected:\n" 11665 "};\n", 11666 "struct foo {\n" 11667 "private:\n" 11668 "\n\n\n" 11669 "protected:\n" 11670 "};\n", 11671 Style); 11672 11673 // Leave tests rely on the code layout, test::messUp can not be used. 11674 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11675 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11676 Style.MaxEmptyLinesToKeep = 10u; 11677 EXPECT_EQ("struct foo {\n" 11678 "private:\n" 11679 "\n\n\n" 11680 "protected:\n" 11681 "};\n", 11682 format("struct foo {\n" 11683 "private:\n" 11684 "\n\n\n" 11685 "protected:\n" 11686 "};\n", 11687 Style)); 11688 Style.MaxEmptyLinesToKeep = 3u; 11689 EXPECT_EQ("struct foo {\n" 11690 "private:\n" 11691 "\n\n\n" 11692 "protected:\n" 11693 "};\n", 11694 format("struct foo {\n" 11695 "private:\n" 11696 "\n\n\n" 11697 "protected:\n" 11698 "};\n", 11699 Style)); 11700 Style.MaxEmptyLinesToKeep = 1u; 11701 EXPECT_EQ("struct foo {\n" 11702 "private:\n" 11703 "\n\n\n" 11704 "protected:\n" 11705 "};\n", 11706 format("struct foo {\n" 11707 "private:\n" 11708 "\n\n\n" 11709 "protected:\n" 11710 "};\n", 11711 Style)); // Based on new lines in original document and not 11712 // on the setting. 11713 11714 Style.MaxEmptyLinesToKeep = 10u; 11715 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11716 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11717 // Newlines are kept if they are greater than zero, 11718 // test::messUp removes all new lines which changes the logic 11719 EXPECT_EQ("struct foo {\n" 11720 "private:\n" 11721 "\n\n\n" 11722 "protected:\n" 11723 "};\n", 11724 format("struct foo {\n" 11725 "private:\n" 11726 "\n\n\n" 11727 "protected:\n" 11728 "};\n", 11729 Style)); 11730 11731 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11732 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11733 // test::messUp removes all new lines which changes the logic 11734 EXPECT_EQ("struct foo {\n" 11735 "private:\n" 11736 "\n\n\n" 11737 "protected:\n" 11738 "};\n", 11739 format("struct foo {\n" 11740 "private:\n" 11741 "\n\n\n" 11742 "protected:\n" 11743 "};\n", 11744 Style)); 11745 11746 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11747 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11748 EXPECT_EQ("struct foo {\n" 11749 "private:\n" 11750 "\n\n\n" 11751 "protected:\n" 11752 "};\n", 11753 format("struct foo {\n" 11754 "private:\n" 11755 "\n\n\n" 11756 "protected:\n" 11757 "};\n", 11758 Style)); // test::messUp removes all new lines which changes 11759 // the logic. 11760 11761 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11762 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11763 verifyFormat("struct foo {\n" 11764 "private:\n" 11765 "protected:\n" 11766 "};\n", 11767 "struct foo {\n" 11768 "private:\n" 11769 "\n\n\n" 11770 "protected:\n" 11771 "};\n", 11772 Style); 11773 11774 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11775 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11776 EXPECT_EQ("struct foo {\n" 11777 "private:\n" 11778 "\n\n\n" 11779 "protected:\n" 11780 "};\n", 11781 format("struct foo {\n" 11782 "private:\n" 11783 "\n\n\n" 11784 "protected:\n" 11785 "};\n", 11786 Style)); // test::messUp removes all new lines which changes 11787 // the logic. 11788 11789 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11790 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11791 verifyFormat("struct foo {\n" 11792 "private:\n" 11793 "protected:\n" 11794 "};\n", 11795 "struct foo {\n" 11796 "private:\n" 11797 "\n\n\n" 11798 "protected:\n" 11799 "};\n", 11800 Style); 11801 11802 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11803 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11804 verifyFormat("struct foo {\n" 11805 "private:\n" 11806 "protected:\n" 11807 "};\n", 11808 "struct foo {\n" 11809 "private:\n" 11810 "\n\n\n" 11811 "protected:\n" 11812 "};\n", 11813 Style); 11814 11815 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11816 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11817 verifyFormat("struct foo {\n" 11818 "private:\n" 11819 "protected:\n" 11820 "};\n", 11821 "struct foo {\n" 11822 "private:\n" 11823 "\n\n\n" 11824 "protected:\n" 11825 "};\n", 11826 Style); 11827 11828 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11829 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11830 verifyFormat("struct foo {\n" 11831 "private:\n" 11832 "protected:\n" 11833 "};\n", 11834 "struct foo {\n" 11835 "private:\n" 11836 "\n\n\n" 11837 "protected:\n" 11838 "};\n", 11839 Style); 11840 } 11841 11842 TEST_F(FormatTest, FormatsArrays) { 11843 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n" 11844 " [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;"); 11845 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n" 11846 " [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;"); 11847 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n" 11848 " aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}"); 11849 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11850 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;"); 11851 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11852 " [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;"); 11853 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11854 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n" 11855 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;"); 11856 verifyFormat( 11857 "llvm::outs() << \"aaaaaaaaaaaa: \"\n" 11858 " << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n" 11859 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];"); 11860 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n" 11861 " .aaaaaaaaaaaaaaaaaaaaaa();"); 11862 11863 verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n" 11864 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];"); 11865 verifyFormat( 11866 "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n" 11867 " .aaaaaaa[0]\n" 11868 " .aaaaaaaaaaaaaaaaaaaaaa();"); 11869 verifyFormat("a[::b::c];"); 11870 11871 verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10)); 11872 11873 FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0); 11874 verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit); 11875 } 11876 11877 TEST_F(FormatTest, LineStartsWithSpecialCharacter) { 11878 verifyFormat("(a)->b();"); 11879 verifyFormat("--a;"); 11880 } 11881 11882 TEST_F(FormatTest, HandlesIncludeDirectives) { 11883 verifyFormat("#include <string>\n" 11884 "#include <a/b/c.h>\n" 11885 "#include \"a/b/string\"\n" 11886 "#include \"string.h\"\n" 11887 "#include \"string.h\"\n" 11888 "#include <a-a>\n" 11889 "#include < path with space >\n" 11890 "#include_next <test.h>" 11891 "#include \"abc.h\" // this is included for ABC\n" 11892 "#include \"some long include\" // with a comment\n" 11893 "#include \"some very long include path\"\n" 11894 "#include <some/very/long/include/path>\n", 11895 getLLVMStyleWithColumns(35)); 11896 EXPECT_EQ("#include \"a.h\"", format("#include \"a.h\"")); 11897 EXPECT_EQ("#include <a>", format("#include<a>")); 11898 11899 verifyFormat("#import <string>"); 11900 verifyFormat("#import <a/b/c.h>"); 11901 verifyFormat("#import \"a/b/string\""); 11902 verifyFormat("#import \"string.h\""); 11903 verifyFormat("#import \"string.h\""); 11904 verifyFormat("#if __has_include(<strstream>)\n" 11905 "#include <strstream>\n" 11906 "#endif"); 11907 11908 verifyFormat("#define MY_IMPORT <a/b>"); 11909 11910 verifyFormat("#if __has_include(<a/b>)"); 11911 verifyFormat("#if __has_include_next(<a/b>)"); 11912 verifyFormat("#define F __has_include(<a/b>)"); 11913 verifyFormat("#define F __has_include_next(<a/b>)"); 11914 11915 // Protocol buffer definition or missing "#". 11916 verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";", 11917 getLLVMStyleWithColumns(30)); 11918 11919 FormatStyle Style = getLLVMStyle(); 11920 Style.AlwaysBreakBeforeMultilineStrings = true; 11921 Style.ColumnLimit = 0; 11922 verifyFormat("#import \"abc.h\"", Style); 11923 11924 // But 'import' might also be a regular C++ namespace. 11925 verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 11926 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 11927 } 11928 11929 //===----------------------------------------------------------------------===// 11930 // Error recovery tests. 11931 //===----------------------------------------------------------------------===// 11932 11933 TEST_F(FormatTest, IncompleteParameterLists) { 11934 FormatStyle NoBinPacking = getLLVMStyle(); 11935 NoBinPacking.BinPackParameters = false; 11936 verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n" 11937 " double *min_x,\n" 11938 " double *max_x,\n" 11939 " double *min_y,\n" 11940 " double *max_y,\n" 11941 " double *min_z,\n" 11942 " double *max_z, ) {}", 11943 NoBinPacking); 11944 } 11945 11946 TEST_F(FormatTest, IncorrectCodeTrailingStuff) { 11947 verifyFormat("void f() { return; }\n42"); 11948 verifyFormat("void f() {\n" 11949 " if (0)\n" 11950 " return;\n" 11951 "}\n" 11952 "42"); 11953 verifyFormat("void f() { return }\n42"); 11954 verifyFormat("void f() {\n" 11955 " if (0)\n" 11956 " return\n" 11957 "}\n" 11958 "42"); 11959 } 11960 11961 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) { 11962 EXPECT_EQ("void f() { return }", format("void f ( ) { return }")); 11963 EXPECT_EQ("void f() {\n" 11964 " if (a)\n" 11965 " return\n" 11966 "}", 11967 format("void f ( ) { if ( a ) return }")); 11968 EXPECT_EQ("namespace N {\n" 11969 "void f()\n" 11970 "}", 11971 format("namespace N { void f() }")); 11972 EXPECT_EQ("namespace N {\n" 11973 "void f() {}\n" 11974 "void g()\n" 11975 "} // namespace N", 11976 format("namespace N { void f( ) { } void g( ) }")); 11977 } 11978 11979 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) { 11980 verifyFormat("int aaaaaaaa =\n" 11981 " // Overlylongcomment\n" 11982 " b;", 11983 getLLVMStyleWithColumns(20)); 11984 verifyFormat("function(\n" 11985 " ShortArgument,\n" 11986 " LoooooooooooongArgument);\n", 11987 getLLVMStyleWithColumns(20)); 11988 } 11989 11990 TEST_F(FormatTest, IncorrectAccessSpecifier) { 11991 verifyFormat("public:"); 11992 verifyFormat("class A {\n" 11993 "public\n" 11994 " void f() {}\n" 11995 "};"); 11996 verifyFormat("public\n" 11997 "int qwerty;"); 11998 verifyFormat("public\n" 11999 "B {}"); 12000 verifyFormat("public\n" 12001 "{}"); 12002 verifyFormat("public\n" 12003 "B { int x; }"); 12004 } 12005 12006 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) { 12007 verifyFormat("{"); 12008 verifyFormat("#})"); 12009 verifyNoCrash("(/**/[:!] ?[)."); 12010 } 12011 12012 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) { 12013 // Found by oss-fuzz: 12014 // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212 12015 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp); 12016 Style.ColumnLimit = 60; 12017 verifyNoCrash( 12018 "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20" 12019 "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20" 12020 "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a", 12021 Style); 12022 } 12023 12024 TEST_F(FormatTest, IncorrectCodeDoNoWhile) { 12025 verifyFormat("do {\n}"); 12026 verifyFormat("do {\n}\n" 12027 "f();"); 12028 verifyFormat("do {\n}\n" 12029 "wheeee(fun);"); 12030 verifyFormat("do {\n" 12031 " f();\n" 12032 "}"); 12033 } 12034 12035 TEST_F(FormatTest, IncorrectCodeMissingParens) { 12036 verifyFormat("if {\n foo;\n foo();\n}"); 12037 verifyFormat("switch {\n foo;\n foo();\n}"); 12038 verifyIncompleteFormat("for {\n foo;\n foo();\n}"); 12039 verifyFormat("while {\n foo;\n foo();\n}"); 12040 verifyFormat("do {\n foo;\n foo();\n} while;"); 12041 } 12042 12043 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) { 12044 verifyIncompleteFormat("namespace {\n" 12045 "class Foo { Foo (\n" 12046 "};\n" 12047 "} // namespace"); 12048 } 12049 12050 TEST_F(FormatTest, IncorrectCodeErrorDetection) { 12051 EXPECT_EQ("{\n {}\n", format("{\n{\n}\n")); 12052 EXPECT_EQ("{\n {}\n", format("{\n {\n}\n")); 12053 EXPECT_EQ("{\n {}\n", format("{\n {\n }\n")); 12054 EXPECT_EQ("{\n {}\n}\n}\n", format("{\n {\n }\n }\n}\n")); 12055 12056 EXPECT_EQ("{\n" 12057 " {\n" 12058 " breakme(\n" 12059 " qwe);\n" 12060 " }\n", 12061 format("{\n" 12062 " {\n" 12063 " breakme(qwe);\n" 12064 "}\n", 12065 getLLVMStyleWithColumns(10))); 12066 } 12067 12068 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) { 12069 verifyFormat("int x = {\n" 12070 " avariable,\n" 12071 " b(alongervariable)};", 12072 getLLVMStyleWithColumns(25)); 12073 } 12074 12075 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) { 12076 verifyFormat("return (a)(b){1, 2, 3};"); 12077 } 12078 12079 TEST_F(FormatTest, LayoutCxx11BraceInitializers) { 12080 verifyFormat("vector<int> x{1, 2, 3, 4};"); 12081 verifyFormat("vector<int> x{\n" 12082 " 1,\n" 12083 " 2,\n" 12084 " 3,\n" 12085 " 4,\n" 12086 "};"); 12087 verifyFormat("vector<T> x{{}, {}, {}, {}};"); 12088 verifyFormat("f({1, 2});"); 12089 verifyFormat("auto v = Foo{-1};"); 12090 verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});"); 12091 verifyFormat("Class::Class : member{1, 2, 3} {}"); 12092 verifyFormat("new vector<int>{1, 2, 3};"); 12093 verifyFormat("new int[3]{1, 2, 3};"); 12094 verifyFormat("new int{1};"); 12095 verifyFormat("return {arg1, arg2};"); 12096 verifyFormat("return {arg1, SomeType{parameter}};"); 12097 verifyFormat("int count = set<int>{f(), g(), h()}.size();"); 12098 verifyFormat("new T{arg1, arg2};"); 12099 verifyFormat("f(MyMap[{composite, key}]);"); 12100 verifyFormat("class Class {\n" 12101 " T member = {arg1, arg2};\n" 12102 "};"); 12103 verifyFormat("vector<int> foo = {::SomeGlobalFunction()};"); 12104 verifyFormat("const struct A a = {.a = 1, .b = 2};"); 12105 verifyFormat("const struct A a = {[0] = 1, [1] = 2};"); 12106 verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");"); 12107 verifyFormat("int a = std::is_integral<int>{} + 0;"); 12108 12109 verifyFormat("int foo(int i) { return fo1{}(i); }"); 12110 verifyFormat("int foo(int i) { return fo1{}(i); }"); 12111 verifyFormat("auto i = decltype(x){};"); 12112 verifyFormat("auto i = typeof(x){};"); 12113 verifyFormat("auto i = _Atomic(x){};"); 12114 verifyFormat("std::vector<int> v = {1, 0 /* comment */};"); 12115 verifyFormat("Node n{1, Node{1000}, //\n" 12116 " 2};"); 12117 verifyFormat("Aaaa aaaaaaa{\n" 12118 " {\n" 12119 " aaaa,\n" 12120 " },\n" 12121 "};"); 12122 verifyFormat("class C : public D {\n" 12123 " SomeClass SC{2};\n" 12124 "};"); 12125 verifyFormat("class C : public A {\n" 12126 " class D : public B {\n" 12127 " void f() { int i{2}; }\n" 12128 " };\n" 12129 "};"); 12130 verifyFormat("#define A {a, a},"); 12131 // Don't confuse braced list initializers with compound statements. 12132 verifyFormat( 12133 "class A {\n" 12134 " A() : a{} {}\n" 12135 " A(int b) : b(b) {}\n" 12136 " A(int a, int b) : a(a), bs{{bs...}} { f(); }\n" 12137 " int a, b;\n" 12138 " explicit Expr(const Scalar<Result> &x) : u{Constant<Result>{x}} {}\n" 12139 " explicit Expr(Scalar<Result> &&x) : u{Constant<Result>{std::move(x)}} " 12140 "{}\n" 12141 "};"); 12142 12143 // Avoid breaking between equal sign and opening brace 12144 FormatStyle AvoidBreakingFirstArgument = getLLVMStyle(); 12145 AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200; 12146 verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n" 12147 " {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n" 12148 " {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n" 12149 " {\"ccccccccccccccccccccc\", 2}};", 12150 AvoidBreakingFirstArgument); 12151 12152 // Binpacking only if there is no trailing comma 12153 verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n" 12154 " cccccccccc, dddddddddd};", 12155 getLLVMStyleWithColumns(50)); 12156 verifyFormat("const Aaaaaa aaaaa = {\n" 12157 " aaaaaaaaaaa,\n" 12158 " bbbbbbbbbbb,\n" 12159 " ccccccccccc,\n" 12160 " ddddddddddd,\n" 12161 "};", 12162 getLLVMStyleWithColumns(50)); 12163 12164 // Cases where distinguising braced lists and blocks is hard. 12165 verifyFormat("vector<int> v{12} GUARDED_BY(mutex);"); 12166 verifyFormat("void f() {\n" 12167 " return; // comment\n" 12168 "}\n" 12169 "SomeType t;"); 12170 verifyFormat("void f() {\n" 12171 " if (a) {\n" 12172 " f();\n" 12173 " }\n" 12174 "}\n" 12175 "SomeType t;"); 12176 12177 // In combination with BinPackArguments = false. 12178 FormatStyle NoBinPacking = getLLVMStyle(); 12179 NoBinPacking.BinPackArguments = false; 12180 verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n" 12181 " bbbbb,\n" 12182 " ccccc,\n" 12183 " ddddd,\n" 12184 " eeeee,\n" 12185 " ffffff,\n" 12186 " ggggg,\n" 12187 " hhhhhh,\n" 12188 " iiiiii,\n" 12189 " jjjjjj,\n" 12190 " kkkkkk};", 12191 NoBinPacking); 12192 verifyFormat("const Aaaaaa aaaaa = {\n" 12193 " aaaaa,\n" 12194 " bbbbb,\n" 12195 " ccccc,\n" 12196 " ddddd,\n" 12197 " eeeee,\n" 12198 " ffffff,\n" 12199 " ggggg,\n" 12200 " hhhhhh,\n" 12201 " iiiiii,\n" 12202 " jjjjjj,\n" 12203 " kkkkkk,\n" 12204 "};", 12205 NoBinPacking); 12206 verifyFormat( 12207 "const Aaaaaa aaaaa = {\n" 12208 " aaaaa, bbbbb, ccccc, ddddd, eeeee, ffffff, ggggg, hhhhhh,\n" 12209 " iiiiii, jjjjjj, kkkkkk, aaaaa, bbbbb, ccccc, ddddd, eeeee,\n" 12210 " ffffff, ggggg, hhhhhh, iiiiii, jjjjjj, kkkkkk,\n" 12211 "};", 12212 NoBinPacking); 12213 12214 NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 12215 EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n" 12216 " CDDDP83848_BMCR_REGISTER,\n" 12217 " CDDDP83848_BMSR_REGISTER,\n" 12218 " CDDDP83848_RBR_REGISTER};", 12219 format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n" 12220 " CDDDP83848_BMSR_REGISTER,\n" 12221 " CDDDP83848_RBR_REGISTER};", 12222 NoBinPacking)); 12223 12224 // FIXME: The alignment of these trailing comments might be bad. Then again, 12225 // this might be utterly useless in real code. 12226 verifyFormat("Constructor::Constructor()\n" 12227 " : some_value{ //\n" 12228 " aaaaaaa, //\n" 12229 " bbbbbbb} {}"); 12230 12231 // In braced lists, the first comment is always assumed to belong to the 12232 // first element. Thus, it can be moved to the next or previous line as 12233 // appropriate. 12234 EXPECT_EQ("function({// First element:\n" 12235 " 1,\n" 12236 " // Second element:\n" 12237 " 2});", 12238 format("function({\n" 12239 " // First element:\n" 12240 " 1,\n" 12241 " // Second element:\n" 12242 " 2});")); 12243 EXPECT_EQ("std::vector<int> MyNumbers{\n" 12244 " // First element:\n" 12245 " 1,\n" 12246 " // Second element:\n" 12247 " 2};", 12248 format("std::vector<int> MyNumbers{// First element:\n" 12249 " 1,\n" 12250 " // Second element:\n" 12251 " 2};", 12252 getLLVMStyleWithColumns(30))); 12253 // A trailing comma should still lead to an enforced line break and no 12254 // binpacking. 12255 EXPECT_EQ("vector<int> SomeVector = {\n" 12256 " // aaa\n" 12257 " 1,\n" 12258 " 2,\n" 12259 "};", 12260 format("vector<int> SomeVector = { // aaa\n" 12261 " 1, 2, };")); 12262 12263 // C++11 brace initializer list l-braces should not be treated any differently 12264 // when breaking before lambda bodies is enabled 12265 FormatStyle BreakBeforeLambdaBody = getLLVMStyle(); 12266 BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 12267 BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 12268 BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true; 12269 verifyFormat( 12270 "std::runtime_error{\n" 12271 " \"Long string which will force a break onto the next line...\"};", 12272 BreakBeforeLambdaBody); 12273 12274 FormatStyle ExtraSpaces = getLLVMStyle(); 12275 ExtraSpaces.Cpp11BracedListStyle = false; 12276 ExtraSpaces.ColumnLimit = 75; 12277 verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces); 12278 verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces); 12279 verifyFormat("f({ 1, 2 });", ExtraSpaces); 12280 verifyFormat("auto v = Foo{ 1 };", ExtraSpaces); 12281 verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces); 12282 verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces); 12283 verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces); 12284 verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces); 12285 verifyFormat("return { arg1, arg2 };", ExtraSpaces); 12286 verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces); 12287 verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces); 12288 verifyFormat("new T{ arg1, arg2 };", ExtraSpaces); 12289 verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces); 12290 verifyFormat("class Class {\n" 12291 " T member = { arg1, arg2 };\n" 12292 "};", 12293 ExtraSpaces); 12294 verifyFormat( 12295 "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12296 " aaaaaaaaaaaaaaaaaaaa, aaaaa }\n" 12297 " : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 12298 " bbbbbbbbbbbbbbbbbbbb, bbbbb };", 12299 ExtraSpaces); 12300 verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces); 12301 verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });", 12302 ExtraSpaces); 12303 verifyFormat( 12304 "someFunction(OtherParam,\n" 12305 " BracedList{ // comment 1 (Forcing interesting break)\n" 12306 " param1, param2,\n" 12307 " // comment 2\n" 12308 " param3, param4 });", 12309 ExtraSpaces); 12310 verifyFormat( 12311 "std::this_thread::sleep_for(\n" 12312 " std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);", 12313 ExtraSpaces); 12314 verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n" 12315 " aaaaaaa,\n" 12316 " aaaaaaaaaa,\n" 12317 " aaaaa,\n" 12318 " aaaaaaaaaaaaaaa,\n" 12319 " aaa,\n" 12320 " aaaaaaaaaa,\n" 12321 " a,\n" 12322 " aaaaaaaaaaaaaaaaaaaaa,\n" 12323 " aaaaaaaaaaaa,\n" 12324 " aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n" 12325 " aaaaaaa,\n" 12326 " a};"); 12327 verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces); 12328 verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces); 12329 verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces); 12330 12331 // Avoid breaking between initializer/equal sign and opening brace 12332 ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200; 12333 verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n" 12334 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n" 12335 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n" 12336 " { \"ccccccccccccccccccccc\", 2 }\n" 12337 "};", 12338 ExtraSpaces); 12339 verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n" 12340 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n" 12341 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n" 12342 " { \"ccccccccccccccccccccc\", 2 }\n" 12343 "};", 12344 ExtraSpaces); 12345 12346 FormatStyle SpaceBeforeBrace = getLLVMStyle(); 12347 SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true; 12348 verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace); 12349 verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace); 12350 12351 FormatStyle SpaceBetweenBraces = getLLVMStyle(); 12352 SpaceBetweenBraces.SpacesInAngles = FormatStyle::SIAS_Always; 12353 SpaceBetweenBraces.SpacesInParentheses = true; 12354 SpaceBetweenBraces.SpacesInSquareBrackets = true; 12355 verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces); 12356 verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces); 12357 verifyFormat("vector< int > x{ // comment 1\n" 12358 " 1, 2, 3, 4 };", 12359 SpaceBetweenBraces); 12360 SpaceBetweenBraces.ColumnLimit = 20; 12361 EXPECT_EQ("vector< int > x{\n" 12362 " 1, 2, 3, 4 };", 12363 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces)); 12364 SpaceBetweenBraces.ColumnLimit = 24; 12365 EXPECT_EQ("vector< int > x{ 1, 2,\n" 12366 " 3, 4 };", 12367 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces)); 12368 EXPECT_EQ("vector< int > x{\n" 12369 " 1,\n" 12370 " 2,\n" 12371 " 3,\n" 12372 " 4,\n" 12373 "};", 12374 format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces)); 12375 verifyFormat("vector< int > x{};", SpaceBetweenBraces); 12376 SpaceBetweenBraces.SpaceInEmptyParentheses = true; 12377 verifyFormat("vector< int > x{ };", SpaceBetweenBraces); 12378 } 12379 12380 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) { 12381 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12382 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12383 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12384 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12385 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12386 " 1, 22, 333, 4444, 55555, 666666, 7777777};"); 12387 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n" 12388 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12389 " 1, 22, 333, 4444, 55555, //\n" 12390 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12391 " 1, 22, 333, 4444, 55555, 666666, 7777777};"); 12392 verifyFormat( 12393 "vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12394 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12395 " 1, 22, 333, 4444, 55555, 666666, // comment\n" 12396 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12397 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12398 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12399 " 7777777};"); 12400 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12401 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12402 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12403 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12404 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12405 " // Separating comment.\n" 12406 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12407 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12408 " // Leading comment\n" 12409 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12410 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12411 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12412 " 1, 1, 1, 1};", 12413 getLLVMStyleWithColumns(39)); 12414 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12415 " 1, 1, 1, 1};", 12416 getLLVMStyleWithColumns(38)); 12417 verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n" 12418 " 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};", 12419 getLLVMStyleWithColumns(43)); 12420 verifyFormat( 12421 "static unsigned SomeValues[10][3] = {\n" 12422 " {1, 4, 0}, {4, 9, 0}, {4, 5, 9}, {8, 5, 4}, {1, 8, 4},\n" 12423 " {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};"); 12424 verifyFormat("static auto fields = new vector<string>{\n" 12425 " \"aaaaaaaaaaaaa\",\n" 12426 " \"aaaaaaaaaaaaa\",\n" 12427 " \"aaaaaaaaaaaa\",\n" 12428 " \"aaaaaaaaaaaaaa\",\n" 12429 " \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n" 12430 " \"aaaaaaaaaaaa\",\n" 12431 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n" 12432 "};"); 12433 verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};"); 12434 verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n" 12435 " 2, bbbbbbbbbbbbbbbbbbbbbb,\n" 12436 " 3, cccccccccccccccccccccc};", 12437 getLLVMStyleWithColumns(60)); 12438 12439 // Trailing commas. 12440 verifyFormat("vector<int> x = {\n" 12441 " 1, 1, 1, 1, 1, 1, 1, 1,\n" 12442 "};", 12443 getLLVMStyleWithColumns(39)); 12444 verifyFormat("vector<int> x = {\n" 12445 " 1, 1, 1, 1, 1, 1, 1, 1, //\n" 12446 "};", 12447 getLLVMStyleWithColumns(39)); 12448 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12449 " 1, 1, 1, 1,\n" 12450 " /**/ /**/};", 12451 getLLVMStyleWithColumns(39)); 12452 12453 // Trailing comment in the first line. 12454 verifyFormat("vector<int> iiiiiiiiiiiiiii = { //\n" 12455 " 1111111111, 2222222222, 33333333333, 4444444444, //\n" 12456 " 111111111, 222222222, 3333333333, 444444444, //\n" 12457 " 11111111, 22222222, 333333333, 44444444};"); 12458 // Trailing comment in the last line. 12459 verifyFormat("int aaaaa[] = {\n" 12460 " 1, 2, 3, // comment\n" 12461 " 4, 5, 6 // comment\n" 12462 "};"); 12463 12464 // With nested lists, we should either format one item per line or all nested 12465 // lists one on line. 12466 // FIXME: For some nested lists, we can do better. 12467 verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n" 12468 " {aaaaaaaaaaaaaaaaaaa},\n" 12469 " {aaaaaaaaaaaaaaaaaaaaa},\n" 12470 " {aaaaaaaaaaaaaaaaa}};", 12471 getLLVMStyleWithColumns(60)); 12472 verifyFormat( 12473 "SomeStruct my_struct_array = {\n" 12474 " {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n" 12475 " aaaaaaaaaaaaa, aaaaaaa, aaa},\n" 12476 " {aaa, aaa},\n" 12477 " {aaa, aaa},\n" 12478 " {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n" 12479 " {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n" 12480 " aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};"); 12481 12482 // No column layout should be used here. 12483 verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n" 12484 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};"); 12485 12486 verifyNoCrash("a<,"); 12487 12488 // No braced initializer here. 12489 verifyFormat("void f() {\n" 12490 " struct Dummy {};\n" 12491 " f(v);\n" 12492 "}"); 12493 12494 // Long lists should be formatted in columns even if they are nested. 12495 verifyFormat( 12496 "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12497 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12498 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12499 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12500 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12501 " 1, 22, 333, 4444, 55555, 666666, 7777777});"); 12502 12503 // Allow "single-column" layout even if that violates the column limit. There 12504 // isn't going to be a better way. 12505 verifyFormat("std::vector<int> a = {\n" 12506 " aaaaaaaa,\n" 12507 " aaaaaaaa,\n" 12508 " aaaaaaaa,\n" 12509 " aaaaaaaa,\n" 12510 " aaaaaaaaaa,\n" 12511 " aaaaaaaa,\n" 12512 " aaaaaaaaaaaaaaaaaaaaaaaaaaa};", 12513 getLLVMStyleWithColumns(30)); 12514 verifyFormat("vector<int> aaaa = {\n" 12515 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12516 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12517 " aaaaaa.aaaaaaa,\n" 12518 " aaaaaa.aaaaaaa,\n" 12519 " aaaaaa.aaaaaaa,\n" 12520 " aaaaaa.aaaaaaa,\n" 12521 "};"); 12522 12523 // Don't create hanging lists. 12524 verifyFormat("someFunction(Param, {List1, List2,\n" 12525 " List3});", 12526 getLLVMStyleWithColumns(35)); 12527 verifyFormat("someFunction(Param, Param,\n" 12528 " {List1, List2,\n" 12529 " List3});", 12530 getLLVMStyleWithColumns(35)); 12531 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n" 12532 " aaaaaaaaaaaaaaaaaaaaaaa);"); 12533 } 12534 12535 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) { 12536 FormatStyle DoNotMerge = getLLVMStyle(); 12537 DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12538 12539 verifyFormat("void f() { return 42; }"); 12540 verifyFormat("void f() {\n" 12541 " return 42;\n" 12542 "}", 12543 DoNotMerge); 12544 verifyFormat("void f() {\n" 12545 " // Comment\n" 12546 "}"); 12547 verifyFormat("{\n" 12548 "#error {\n" 12549 " int a;\n" 12550 "}"); 12551 verifyFormat("{\n" 12552 " int a;\n" 12553 "#error {\n" 12554 "}"); 12555 verifyFormat("void f() {} // comment"); 12556 verifyFormat("void f() { int a; } // comment"); 12557 verifyFormat("void f() {\n" 12558 "} // comment", 12559 DoNotMerge); 12560 verifyFormat("void f() {\n" 12561 " int a;\n" 12562 "} // comment", 12563 DoNotMerge); 12564 verifyFormat("void f() {\n" 12565 "} // comment", 12566 getLLVMStyleWithColumns(15)); 12567 12568 verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23)); 12569 verifyFormat("void f() {\n return 42;\n}", getLLVMStyleWithColumns(22)); 12570 12571 verifyFormat("void f() {}", getLLVMStyleWithColumns(11)); 12572 verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10)); 12573 verifyFormat("class C {\n" 12574 " C()\n" 12575 " : iiiiiiii(nullptr),\n" 12576 " kkkkkkk(nullptr),\n" 12577 " mmmmmmm(nullptr),\n" 12578 " nnnnnnn(nullptr) {}\n" 12579 "};", 12580 getGoogleStyle()); 12581 12582 FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0); 12583 EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit)); 12584 EXPECT_EQ("class C {\n" 12585 " A() : b(0) {}\n" 12586 "};", 12587 format("class C{A():b(0){}};", NoColumnLimit)); 12588 EXPECT_EQ("A()\n" 12589 " : b(0) {\n" 12590 "}", 12591 format("A()\n:b(0)\n{\n}", NoColumnLimit)); 12592 12593 FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit; 12594 DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine = 12595 FormatStyle::SFS_None; 12596 EXPECT_EQ("A()\n" 12597 " : b(0) {\n" 12598 "}", 12599 format("A():b(0){}", DoNotMergeNoColumnLimit)); 12600 EXPECT_EQ("A()\n" 12601 " : b(0) {\n" 12602 "}", 12603 format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit)); 12604 12605 verifyFormat("#define A \\\n" 12606 " void f() { \\\n" 12607 " int i; \\\n" 12608 " }", 12609 getLLVMStyleWithColumns(20)); 12610 verifyFormat("#define A \\\n" 12611 " void f() { int i; }", 12612 getLLVMStyleWithColumns(21)); 12613 verifyFormat("#define A \\\n" 12614 " void f() { \\\n" 12615 " int i; \\\n" 12616 " } \\\n" 12617 " int j;", 12618 getLLVMStyleWithColumns(22)); 12619 verifyFormat("#define A \\\n" 12620 " void f() { int i; } \\\n" 12621 " int j;", 12622 getLLVMStyleWithColumns(23)); 12623 } 12624 12625 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) { 12626 FormatStyle MergeEmptyOnly = getLLVMStyle(); 12627 MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 12628 verifyFormat("class C {\n" 12629 " int f() {}\n" 12630 "};", 12631 MergeEmptyOnly); 12632 verifyFormat("class C {\n" 12633 " int f() {\n" 12634 " return 42;\n" 12635 " }\n" 12636 "};", 12637 MergeEmptyOnly); 12638 verifyFormat("int f() {}", MergeEmptyOnly); 12639 verifyFormat("int f() {\n" 12640 " return 42;\n" 12641 "}", 12642 MergeEmptyOnly); 12643 12644 // Also verify behavior when BraceWrapping.AfterFunction = true 12645 MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12646 MergeEmptyOnly.BraceWrapping.AfterFunction = true; 12647 verifyFormat("int f() {}", MergeEmptyOnly); 12648 verifyFormat("class C {\n" 12649 " int f() {}\n" 12650 "};", 12651 MergeEmptyOnly); 12652 } 12653 12654 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) { 12655 FormatStyle MergeInlineOnly = getLLVMStyle(); 12656 MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 12657 verifyFormat("class C {\n" 12658 " int f() { return 42; }\n" 12659 "};", 12660 MergeInlineOnly); 12661 verifyFormat("int f() {\n" 12662 " return 42;\n" 12663 "}", 12664 MergeInlineOnly); 12665 12666 // SFS_Inline implies SFS_Empty 12667 verifyFormat("class C {\n" 12668 " int f() {}\n" 12669 "};", 12670 MergeInlineOnly); 12671 verifyFormat("int f() {}", MergeInlineOnly); 12672 12673 // Also verify behavior when BraceWrapping.AfterFunction = true 12674 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12675 MergeInlineOnly.BraceWrapping.AfterFunction = true; 12676 verifyFormat("class C {\n" 12677 " int f() { return 42; }\n" 12678 "};", 12679 MergeInlineOnly); 12680 verifyFormat("int f()\n" 12681 "{\n" 12682 " return 42;\n" 12683 "}", 12684 MergeInlineOnly); 12685 12686 // SFS_Inline implies SFS_Empty 12687 verifyFormat("int f() {}", MergeInlineOnly); 12688 verifyFormat("class C {\n" 12689 " int f() {}\n" 12690 "};", 12691 MergeInlineOnly); 12692 12693 MergeInlineOnly.BraceWrapping.AfterClass = true; 12694 MergeInlineOnly.BraceWrapping.AfterStruct = true; 12695 verifyFormat("class C\n" 12696 "{\n" 12697 " int f() { return 42; }\n" 12698 "};", 12699 MergeInlineOnly); 12700 verifyFormat("struct C\n" 12701 "{\n" 12702 " int f() { return 42; }\n" 12703 "};", 12704 MergeInlineOnly); 12705 verifyFormat("int f()\n" 12706 "{\n" 12707 " return 42;\n" 12708 "}", 12709 MergeInlineOnly); 12710 verifyFormat("int f() {}", MergeInlineOnly); 12711 verifyFormat("class C\n" 12712 "{\n" 12713 " int f() { return 42; }\n" 12714 "};", 12715 MergeInlineOnly); 12716 verifyFormat("struct C\n" 12717 "{\n" 12718 " int f() { return 42; }\n" 12719 "};", 12720 MergeInlineOnly); 12721 verifyFormat("struct C\n" 12722 "// comment\n" 12723 "/* comment */\n" 12724 "// comment\n" 12725 "{\n" 12726 " int f() { return 42; }\n" 12727 "};", 12728 MergeInlineOnly); 12729 verifyFormat("/* comment */ struct C\n" 12730 "{\n" 12731 " int f() { return 42; }\n" 12732 "};", 12733 MergeInlineOnly); 12734 } 12735 12736 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) { 12737 FormatStyle MergeInlineOnly = getLLVMStyle(); 12738 MergeInlineOnly.AllowShortFunctionsOnASingleLine = 12739 FormatStyle::SFS_InlineOnly; 12740 verifyFormat("class C {\n" 12741 " int f() { return 42; }\n" 12742 "};", 12743 MergeInlineOnly); 12744 verifyFormat("int f() {\n" 12745 " return 42;\n" 12746 "}", 12747 MergeInlineOnly); 12748 12749 // SFS_InlineOnly does not imply SFS_Empty 12750 verifyFormat("class C {\n" 12751 " int f() {}\n" 12752 "};", 12753 MergeInlineOnly); 12754 verifyFormat("int f() {\n" 12755 "}", 12756 MergeInlineOnly); 12757 12758 // Also verify behavior when BraceWrapping.AfterFunction = true 12759 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12760 MergeInlineOnly.BraceWrapping.AfterFunction = true; 12761 verifyFormat("class C {\n" 12762 " int f() { return 42; }\n" 12763 "};", 12764 MergeInlineOnly); 12765 verifyFormat("int f()\n" 12766 "{\n" 12767 " return 42;\n" 12768 "}", 12769 MergeInlineOnly); 12770 12771 // SFS_InlineOnly does not imply SFS_Empty 12772 verifyFormat("int f()\n" 12773 "{\n" 12774 "}", 12775 MergeInlineOnly); 12776 verifyFormat("class C {\n" 12777 " int f() {}\n" 12778 "};", 12779 MergeInlineOnly); 12780 } 12781 12782 TEST_F(FormatTest, SplitEmptyFunction) { 12783 FormatStyle Style = getLLVMStyleWithColumns(40); 12784 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12785 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12786 Style.BraceWrapping.AfterFunction = true; 12787 Style.BraceWrapping.SplitEmptyFunction = false; 12788 12789 verifyFormat("int f()\n" 12790 "{}", 12791 Style); 12792 verifyFormat("int f()\n" 12793 "{\n" 12794 " return 42;\n" 12795 "}", 12796 Style); 12797 verifyFormat("int f()\n" 12798 "{\n" 12799 " // some comment\n" 12800 "}", 12801 Style); 12802 12803 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 12804 verifyFormat("int f() {}", Style); 12805 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12806 "{}", 12807 Style); 12808 verifyFormat("int f()\n" 12809 "{\n" 12810 " return 0;\n" 12811 "}", 12812 Style); 12813 12814 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 12815 verifyFormat("class Foo {\n" 12816 " int f() {}\n" 12817 "};\n", 12818 Style); 12819 verifyFormat("class Foo {\n" 12820 " int f() { return 0; }\n" 12821 "};\n", 12822 Style); 12823 verifyFormat("class Foo {\n" 12824 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12825 " {}\n" 12826 "};\n", 12827 Style); 12828 verifyFormat("class Foo {\n" 12829 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12830 " {\n" 12831 " return 0;\n" 12832 " }\n" 12833 "};\n", 12834 Style); 12835 12836 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 12837 verifyFormat("int f() {}", Style); 12838 verifyFormat("int f() { return 0; }", Style); 12839 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12840 "{}", 12841 Style); 12842 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12843 "{\n" 12844 " return 0;\n" 12845 "}", 12846 Style); 12847 } 12848 12849 TEST_F(FormatTest, SplitEmptyFunctionButNotRecord) { 12850 FormatStyle Style = getLLVMStyleWithColumns(40); 12851 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12852 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12853 Style.BraceWrapping.AfterFunction = true; 12854 Style.BraceWrapping.SplitEmptyFunction = true; 12855 Style.BraceWrapping.SplitEmptyRecord = false; 12856 12857 verifyFormat("class C {};", Style); 12858 verifyFormat("struct C {};", Style); 12859 verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12860 " int bbbbbbbbbbbbbbbbbbbbbbbb)\n" 12861 "{\n" 12862 "}", 12863 Style); 12864 verifyFormat("class C {\n" 12865 " C()\n" 12866 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa(),\n" 12867 " bbbbbbbbbbbbbbbbbbb()\n" 12868 " {\n" 12869 " }\n" 12870 " void\n" 12871 " m(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12872 " int bbbbbbbbbbbbbbbbbbbbbbbb)\n" 12873 " {\n" 12874 " }\n" 12875 "};", 12876 Style); 12877 } 12878 12879 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) { 12880 FormatStyle Style = getLLVMStyle(); 12881 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 12882 verifyFormat("#ifdef A\n" 12883 "int f() {}\n" 12884 "#else\n" 12885 "int g() {}\n" 12886 "#endif", 12887 Style); 12888 } 12889 12890 TEST_F(FormatTest, SplitEmptyClass) { 12891 FormatStyle Style = getLLVMStyle(); 12892 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12893 Style.BraceWrapping.AfterClass = true; 12894 Style.BraceWrapping.SplitEmptyRecord = false; 12895 12896 verifyFormat("class Foo\n" 12897 "{};", 12898 Style); 12899 verifyFormat("/* something */ class Foo\n" 12900 "{};", 12901 Style); 12902 verifyFormat("template <typename X> class Foo\n" 12903 "{};", 12904 Style); 12905 verifyFormat("class Foo\n" 12906 "{\n" 12907 " Foo();\n" 12908 "};", 12909 Style); 12910 verifyFormat("typedef class Foo\n" 12911 "{\n" 12912 "} Foo_t;", 12913 Style); 12914 12915 Style.BraceWrapping.SplitEmptyRecord = true; 12916 Style.BraceWrapping.AfterStruct = true; 12917 verifyFormat("class rep\n" 12918 "{\n" 12919 "};", 12920 Style); 12921 verifyFormat("struct rep\n" 12922 "{\n" 12923 "};", 12924 Style); 12925 verifyFormat("template <typename T> class rep\n" 12926 "{\n" 12927 "};", 12928 Style); 12929 verifyFormat("template <typename T> struct rep\n" 12930 "{\n" 12931 "};", 12932 Style); 12933 verifyFormat("class rep\n" 12934 "{\n" 12935 " int x;\n" 12936 "};", 12937 Style); 12938 verifyFormat("struct rep\n" 12939 "{\n" 12940 " int x;\n" 12941 "};", 12942 Style); 12943 verifyFormat("template <typename T> class rep\n" 12944 "{\n" 12945 " int x;\n" 12946 "};", 12947 Style); 12948 verifyFormat("template <typename T> struct rep\n" 12949 "{\n" 12950 " int x;\n" 12951 "};", 12952 Style); 12953 verifyFormat("template <typename T> class rep // Foo\n" 12954 "{\n" 12955 " int x;\n" 12956 "};", 12957 Style); 12958 verifyFormat("template <typename T> struct rep // Bar\n" 12959 "{\n" 12960 " int x;\n" 12961 "};", 12962 Style); 12963 12964 verifyFormat("template <typename T> class rep<T>\n" 12965 "{\n" 12966 " int x;\n" 12967 "};", 12968 Style); 12969 12970 verifyFormat("template <typename T> class rep<std::complex<T>>\n" 12971 "{\n" 12972 " int x;\n" 12973 "};", 12974 Style); 12975 verifyFormat("template <typename T> class rep<std::complex<T>>\n" 12976 "{\n" 12977 "};", 12978 Style); 12979 12980 verifyFormat("#include \"stdint.h\"\n" 12981 "namespace rep {}", 12982 Style); 12983 verifyFormat("#include <stdint.h>\n" 12984 "namespace rep {}", 12985 Style); 12986 verifyFormat("#include <stdint.h>\n" 12987 "namespace rep {}", 12988 "#include <stdint.h>\n" 12989 "namespace rep {\n" 12990 "\n" 12991 "\n" 12992 "}", 12993 Style); 12994 } 12995 12996 TEST_F(FormatTest, SplitEmptyStruct) { 12997 FormatStyle Style = getLLVMStyle(); 12998 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12999 Style.BraceWrapping.AfterStruct = true; 13000 Style.BraceWrapping.SplitEmptyRecord = false; 13001 13002 verifyFormat("struct Foo\n" 13003 "{};", 13004 Style); 13005 verifyFormat("/* something */ struct Foo\n" 13006 "{};", 13007 Style); 13008 verifyFormat("template <typename X> struct Foo\n" 13009 "{};", 13010 Style); 13011 verifyFormat("struct Foo\n" 13012 "{\n" 13013 " Foo();\n" 13014 "};", 13015 Style); 13016 verifyFormat("typedef struct Foo\n" 13017 "{\n" 13018 "} Foo_t;", 13019 Style); 13020 // typedef struct Bar {} Bar_t; 13021 } 13022 13023 TEST_F(FormatTest, SplitEmptyUnion) { 13024 FormatStyle Style = getLLVMStyle(); 13025 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13026 Style.BraceWrapping.AfterUnion = true; 13027 Style.BraceWrapping.SplitEmptyRecord = false; 13028 13029 verifyFormat("union Foo\n" 13030 "{};", 13031 Style); 13032 verifyFormat("/* something */ union Foo\n" 13033 "{};", 13034 Style); 13035 verifyFormat("union Foo\n" 13036 "{\n" 13037 " A,\n" 13038 "};", 13039 Style); 13040 verifyFormat("typedef union Foo\n" 13041 "{\n" 13042 "} Foo_t;", 13043 Style); 13044 } 13045 13046 TEST_F(FormatTest, SplitEmptyNamespace) { 13047 FormatStyle Style = getLLVMStyle(); 13048 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13049 Style.BraceWrapping.AfterNamespace = true; 13050 Style.BraceWrapping.SplitEmptyNamespace = false; 13051 13052 verifyFormat("namespace Foo\n" 13053 "{};", 13054 Style); 13055 verifyFormat("/* something */ namespace Foo\n" 13056 "{};", 13057 Style); 13058 verifyFormat("inline namespace Foo\n" 13059 "{};", 13060 Style); 13061 verifyFormat("/* something */ inline namespace Foo\n" 13062 "{};", 13063 Style); 13064 verifyFormat("export namespace Foo\n" 13065 "{};", 13066 Style); 13067 verifyFormat("namespace Foo\n" 13068 "{\n" 13069 "void Bar();\n" 13070 "};", 13071 Style); 13072 } 13073 13074 TEST_F(FormatTest, NeverMergeShortRecords) { 13075 FormatStyle Style = getLLVMStyle(); 13076 13077 verifyFormat("class Foo {\n" 13078 " Foo();\n" 13079 "};", 13080 Style); 13081 verifyFormat("typedef class Foo {\n" 13082 " Foo();\n" 13083 "} Foo_t;", 13084 Style); 13085 verifyFormat("struct Foo {\n" 13086 " Foo();\n" 13087 "};", 13088 Style); 13089 verifyFormat("typedef struct Foo {\n" 13090 " Foo();\n" 13091 "} Foo_t;", 13092 Style); 13093 verifyFormat("union Foo {\n" 13094 " A,\n" 13095 "};", 13096 Style); 13097 verifyFormat("typedef union Foo {\n" 13098 " A,\n" 13099 "} Foo_t;", 13100 Style); 13101 verifyFormat("namespace Foo {\n" 13102 "void Bar();\n" 13103 "};", 13104 Style); 13105 13106 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13107 Style.BraceWrapping.AfterClass = true; 13108 Style.BraceWrapping.AfterStruct = true; 13109 Style.BraceWrapping.AfterUnion = true; 13110 Style.BraceWrapping.AfterNamespace = true; 13111 verifyFormat("class Foo\n" 13112 "{\n" 13113 " Foo();\n" 13114 "};", 13115 Style); 13116 verifyFormat("typedef class Foo\n" 13117 "{\n" 13118 " Foo();\n" 13119 "} Foo_t;", 13120 Style); 13121 verifyFormat("struct Foo\n" 13122 "{\n" 13123 " Foo();\n" 13124 "};", 13125 Style); 13126 verifyFormat("typedef struct Foo\n" 13127 "{\n" 13128 " Foo();\n" 13129 "} Foo_t;", 13130 Style); 13131 verifyFormat("union Foo\n" 13132 "{\n" 13133 " A,\n" 13134 "};", 13135 Style); 13136 verifyFormat("typedef union Foo\n" 13137 "{\n" 13138 " A,\n" 13139 "} Foo_t;", 13140 Style); 13141 verifyFormat("namespace Foo\n" 13142 "{\n" 13143 "void Bar();\n" 13144 "};", 13145 Style); 13146 } 13147 13148 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) { 13149 // Elaborate type variable declarations. 13150 verifyFormat("struct foo a = {bar};\nint n;"); 13151 verifyFormat("class foo a = {bar};\nint n;"); 13152 verifyFormat("union foo a = {bar};\nint n;"); 13153 13154 // Elaborate types inside function definitions. 13155 verifyFormat("struct foo f() {}\nint n;"); 13156 verifyFormat("class foo f() {}\nint n;"); 13157 verifyFormat("union foo f() {}\nint n;"); 13158 13159 // Templates. 13160 verifyFormat("template <class X> void f() {}\nint n;"); 13161 verifyFormat("template <struct X> void f() {}\nint n;"); 13162 verifyFormat("template <union X> void f() {}\nint n;"); 13163 13164 // Actual definitions... 13165 verifyFormat("struct {\n} n;"); 13166 verifyFormat( 13167 "template <template <class T, class Y>, class Z> class X {\n} n;"); 13168 verifyFormat("union Z {\n int n;\n} x;"); 13169 verifyFormat("class MACRO Z {\n} n;"); 13170 verifyFormat("class MACRO(X) Z {\n} n;"); 13171 verifyFormat("class __attribute__(X) Z {\n} n;"); 13172 verifyFormat("class __declspec(X) Z {\n} n;"); 13173 verifyFormat("class A##B##C {\n} n;"); 13174 verifyFormat("class alignas(16) Z {\n} n;"); 13175 verifyFormat("class MACRO(X) alignas(16) Z {\n} n;"); 13176 verifyFormat("class MACROA MACRO(X) Z {\n} n;"); 13177 13178 // Redefinition from nested context: 13179 verifyFormat("class A::B::C {\n} n;"); 13180 13181 // Template definitions. 13182 verifyFormat( 13183 "template <typename F>\n" 13184 "Matcher(const Matcher<F> &Other,\n" 13185 " typename enable_if_c<is_base_of<F, T>::value &&\n" 13186 " !is_same<F, T>::value>::type * = 0)\n" 13187 " : Implementation(new ImplicitCastMatcher<F>(Other)) {}"); 13188 13189 // FIXME: This is still incorrectly handled at the formatter side. 13190 verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};"); 13191 verifyFormat("int i = SomeFunction(a<b, a> b);"); 13192 13193 // FIXME: 13194 // This now gets parsed incorrectly as class definition. 13195 // verifyFormat("class A<int> f() {\n}\nint n;"); 13196 13197 // Elaborate types where incorrectly parsing the structural element would 13198 // break the indent. 13199 verifyFormat("if (true)\n" 13200 " class X x;\n" 13201 "else\n" 13202 " f();\n"); 13203 13204 // This is simply incomplete. Formatting is not important, but must not crash. 13205 verifyFormat("class A:"); 13206 } 13207 13208 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) { 13209 EXPECT_EQ("#error Leave all white!!!!! space* alone!\n", 13210 format("#error Leave all white!!!!! space* alone!\n")); 13211 EXPECT_EQ( 13212 "#warning Leave all white!!!!! space* alone!\n", 13213 format("#warning Leave all white!!!!! space* alone!\n")); 13214 EXPECT_EQ("#error 1", format(" # error 1")); 13215 EXPECT_EQ("#warning 1", format(" # warning 1")); 13216 } 13217 13218 TEST_F(FormatTest, FormatHashIfExpressions) { 13219 verifyFormat("#if AAAA && BBBB"); 13220 verifyFormat("#if (AAAA && BBBB)"); 13221 verifyFormat("#elif (AAAA && BBBB)"); 13222 // FIXME: Come up with a better indentation for #elif. 13223 verifyFormat( 13224 "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) && \\\n" 13225 " defined(BBBBBBBB)\n" 13226 "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) && \\\n" 13227 " defined(BBBBBBBB)\n" 13228 "#endif", 13229 getLLVMStyleWithColumns(65)); 13230 } 13231 13232 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) { 13233 FormatStyle AllowsMergedIf = getGoogleStyle(); 13234 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 13235 FormatStyle::SIS_WithoutElse; 13236 verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf); 13237 verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf); 13238 verifyFormat("if (true)\n#error E\n return 42;", AllowsMergedIf); 13239 EXPECT_EQ("if (true) return 42;", 13240 format("if (true)\nreturn 42;", AllowsMergedIf)); 13241 FormatStyle ShortMergedIf = AllowsMergedIf; 13242 ShortMergedIf.ColumnLimit = 25; 13243 verifyFormat("#define A \\\n" 13244 " if (true) return 42;", 13245 ShortMergedIf); 13246 verifyFormat("#define A \\\n" 13247 " f(); \\\n" 13248 " if (true)\n" 13249 "#define B", 13250 ShortMergedIf); 13251 verifyFormat("#define A \\\n" 13252 " f(); \\\n" 13253 " if (true)\n" 13254 "g();", 13255 ShortMergedIf); 13256 verifyFormat("{\n" 13257 "#ifdef A\n" 13258 " // Comment\n" 13259 " if (true) continue;\n" 13260 "#endif\n" 13261 " // Comment\n" 13262 " if (true) continue;\n" 13263 "}", 13264 ShortMergedIf); 13265 ShortMergedIf.ColumnLimit = 33; 13266 verifyFormat("#define A \\\n" 13267 " if constexpr (true) return 42;", 13268 ShortMergedIf); 13269 verifyFormat("#define A \\\n" 13270 " if CONSTEXPR (true) return 42;", 13271 ShortMergedIf); 13272 ShortMergedIf.ColumnLimit = 29; 13273 verifyFormat("#define A \\\n" 13274 " if (aaaaaaaaaa) return 1; \\\n" 13275 " return 2;", 13276 ShortMergedIf); 13277 ShortMergedIf.ColumnLimit = 28; 13278 verifyFormat("#define A \\\n" 13279 " if (aaaaaaaaaa) \\\n" 13280 " return 1; \\\n" 13281 " return 2;", 13282 ShortMergedIf); 13283 verifyFormat("#define A \\\n" 13284 " if constexpr (aaaaaaa) \\\n" 13285 " return 1; \\\n" 13286 " return 2;", 13287 ShortMergedIf); 13288 verifyFormat("#define A \\\n" 13289 " if CONSTEXPR (aaaaaaa) \\\n" 13290 " return 1; \\\n" 13291 " return 2;", 13292 ShortMergedIf); 13293 } 13294 13295 TEST_F(FormatTest, FormatStarDependingOnContext) { 13296 verifyFormat("void f(int *a);"); 13297 verifyFormat("void f() { f(fint * b); }"); 13298 verifyFormat("class A {\n void f(int *a);\n};"); 13299 verifyFormat("class A {\n int *a;\n};"); 13300 verifyFormat("namespace a {\n" 13301 "namespace b {\n" 13302 "class A {\n" 13303 " void f() {}\n" 13304 " int *a;\n" 13305 "};\n" 13306 "} // namespace b\n" 13307 "} // namespace a"); 13308 } 13309 13310 TEST_F(FormatTest, SpecialTokensAtEndOfLine) { 13311 verifyFormat("while"); 13312 verifyFormat("operator"); 13313 } 13314 13315 TEST_F(FormatTest, SkipsDeeplyNestedLines) { 13316 // This code would be painfully slow to format if we didn't skip it. 13317 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 13318 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13319 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13320 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13321 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13322 "A(1, 1)\n" 13323 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x 13324 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13325 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13326 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13327 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13328 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13329 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13330 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13331 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13332 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n"); 13333 // Deeply nested part is untouched, rest is formatted. 13334 EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n", 13335 format(std::string("int i;\n") + Code + "int j;\n", 13336 getLLVMStyle(), SC_ExpectIncomplete)); 13337 } 13338 13339 //===----------------------------------------------------------------------===// 13340 // Objective-C tests. 13341 //===----------------------------------------------------------------------===// 13342 13343 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) { 13344 verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;"); 13345 EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;", 13346 format("-(NSUInteger)indexOfObject:(id)anObject;")); 13347 EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;")); 13348 EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;")); 13349 EXPECT_EQ("- (NSInteger)Method3:(id)anObject;", 13350 format("-(NSInteger)Method3:(id)anObject;")); 13351 EXPECT_EQ("- (NSInteger)Method4:(id)anObject;", 13352 format("-(NSInteger)Method4:(id)anObject;")); 13353 EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;", 13354 format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;")); 13355 EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;", 13356 format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;")); 13357 EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject " 13358 "forAllCells:(BOOL)flag;", 13359 format("- (void)sendAction:(SEL)aSelector to:(id)anObject " 13360 "forAllCells:(BOOL)flag;")); 13361 13362 // Very long objectiveC method declaration. 13363 verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n" 13364 " (SoooooooooooooooooooooomeType *)bbbbbbbbbb;"); 13365 verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n" 13366 " inRange:(NSRange)range\n" 13367 " outRange:(NSRange)out_range\n" 13368 " outRange1:(NSRange)out_range1\n" 13369 " outRange2:(NSRange)out_range2\n" 13370 " outRange3:(NSRange)out_range3\n" 13371 " outRange4:(NSRange)out_range4\n" 13372 " outRange5:(NSRange)out_range5\n" 13373 " outRange6:(NSRange)out_range6\n" 13374 " outRange7:(NSRange)out_range7\n" 13375 " outRange8:(NSRange)out_range8\n" 13376 " outRange9:(NSRange)out_range9;"); 13377 13378 // When the function name has to be wrapped. 13379 FormatStyle Style = getLLVMStyle(); 13380 // ObjC ignores IndentWrappedFunctionNames when wrapping methods 13381 // and always indents instead. 13382 Style.IndentWrappedFunctionNames = false; 13383 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n" 13384 " veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n" 13385 " anotherName:(NSString)bbbbbbbbbbbbbb {\n" 13386 "}", 13387 Style); 13388 Style.IndentWrappedFunctionNames = true; 13389 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n" 13390 " veryLooooooooooongName:(NSString)cccccccccccccc\n" 13391 " anotherName:(NSString)dddddddddddddd {\n" 13392 "}", 13393 Style); 13394 13395 verifyFormat("- (int)sum:(vector<int>)numbers;"); 13396 verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;"); 13397 // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC 13398 // protocol lists (but not for template classes): 13399 // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;"); 13400 13401 verifyFormat("- (int (*)())foo:(int (*)())f;"); 13402 verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;"); 13403 13404 // If there's no return type (very rare in practice!), LLVM and Google style 13405 // agree. 13406 verifyFormat("- foo;"); 13407 verifyFormat("- foo:(int)f;"); 13408 verifyGoogleFormat("- foo:(int)foo;"); 13409 } 13410 13411 TEST_F(FormatTest, BreaksStringLiterals) { 13412 EXPECT_EQ("\"some text \"\n" 13413 "\"other\";", 13414 format("\"some text other\";", getLLVMStyleWithColumns(12))); 13415 EXPECT_EQ("\"some text \"\n" 13416 "\"other\";", 13417 format("\\\n\"some text other\";", getLLVMStyleWithColumns(12))); 13418 EXPECT_EQ( 13419 "#define A \\\n" 13420 " \"some \" \\\n" 13421 " \"text \" \\\n" 13422 " \"other\";", 13423 format("#define A \"some text other\";", getLLVMStyleWithColumns(12))); 13424 EXPECT_EQ( 13425 "#define A \\\n" 13426 " \"so \" \\\n" 13427 " \"text \" \\\n" 13428 " \"other\";", 13429 format("#define A \"so text other\";", getLLVMStyleWithColumns(12))); 13430 13431 EXPECT_EQ("\"some text\"", 13432 format("\"some text\"", getLLVMStyleWithColumns(1))); 13433 EXPECT_EQ("\"some text\"", 13434 format("\"some text\"", getLLVMStyleWithColumns(11))); 13435 EXPECT_EQ("\"some \"\n" 13436 "\"text\"", 13437 format("\"some text\"", getLLVMStyleWithColumns(10))); 13438 EXPECT_EQ("\"some \"\n" 13439 "\"text\"", 13440 format("\"some text\"", getLLVMStyleWithColumns(7))); 13441 EXPECT_EQ("\"some\"\n" 13442 "\" tex\"\n" 13443 "\"t\"", 13444 format("\"some text\"", getLLVMStyleWithColumns(6))); 13445 EXPECT_EQ("\"some\"\n" 13446 "\" tex\"\n" 13447 "\" and\"", 13448 format("\"some tex and\"", getLLVMStyleWithColumns(6))); 13449 EXPECT_EQ("\"some\"\n" 13450 "\"/tex\"\n" 13451 "\"/and\"", 13452 format("\"some/tex/and\"", getLLVMStyleWithColumns(6))); 13453 13454 EXPECT_EQ("variable =\n" 13455 " \"long string \"\n" 13456 " \"literal\";", 13457 format("variable = \"long string literal\";", 13458 getLLVMStyleWithColumns(20))); 13459 13460 EXPECT_EQ("variable = f(\n" 13461 " \"long string \"\n" 13462 " \"literal\",\n" 13463 " short,\n" 13464 " loooooooooooooooooooong);", 13465 format("variable = f(\"long string literal\", short, " 13466 "loooooooooooooooooooong);", 13467 getLLVMStyleWithColumns(20))); 13468 13469 EXPECT_EQ( 13470 "f(g(\"long string \"\n" 13471 " \"literal\"),\n" 13472 " b);", 13473 format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20))); 13474 EXPECT_EQ("f(g(\"long string \"\n" 13475 " \"literal\",\n" 13476 " a),\n" 13477 " b);", 13478 format("f(g(\"long string literal\", a), b);", 13479 getLLVMStyleWithColumns(20))); 13480 EXPECT_EQ( 13481 "f(\"one two\".split(\n" 13482 " variable));", 13483 format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20))); 13484 EXPECT_EQ("f(\"one two three four five six \"\n" 13485 " \"seven\".split(\n" 13486 " really_looooong_variable));", 13487 format("f(\"one two three four five six seven\"." 13488 "split(really_looooong_variable));", 13489 getLLVMStyleWithColumns(33))); 13490 13491 EXPECT_EQ("f(\"some \"\n" 13492 " \"text\",\n" 13493 " other);", 13494 format("f(\"some text\", other);", getLLVMStyleWithColumns(10))); 13495 13496 // Only break as a last resort. 13497 verifyFormat( 13498 "aaaaaaaaaaaaaaaaaaaa(\n" 13499 " aaaaaaaaaaaaaaaaaaaa,\n" 13500 " aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));"); 13501 13502 EXPECT_EQ("\"splitmea\"\n" 13503 "\"trandomp\"\n" 13504 "\"oint\"", 13505 format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10))); 13506 13507 EXPECT_EQ("\"split/\"\n" 13508 "\"pathat/\"\n" 13509 "\"slashes\"", 13510 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10))); 13511 13512 EXPECT_EQ("\"split/\"\n" 13513 "\"pathat/\"\n" 13514 "\"slashes\"", 13515 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10))); 13516 EXPECT_EQ("\"split at \"\n" 13517 "\"spaces/at/\"\n" 13518 "\"slashes.at.any$\"\n" 13519 "\"non-alphanumeric%\"\n" 13520 "\"1111111111characte\"\n" 13521 "\"rs\"", 13522 format("\"split at " 13523 "spaces/at/" 13524 "slashes.at." 13525 "any$non-" 13526 "alphanumeric%" 13527 "1111111111characte" 13528 "rs\"", 13529 getLLVMStyleWithColumns(20))); 13530 13531 // Verify that splitting the strings understands 13532 // Style::AlwaysBreakBeforeMultilineStrings. 13533 EXPECT_EQ("aaaaaaaaaaaa(\n" 13534 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n" 13535 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");", 13536 format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa " 13537 "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa " 13538 "aaaaaaaaaaaaaaaaaaaaaa\");", 13539 getGoogleStyle())); 13540 EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13541 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";", 13542 format("return \"aaaaaaaaaaaaaaaaaaaaaa " 13543 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa " 13544 "aaaaaaaaaaaaaaaaaaaaaa\";", 13545 getGoogleStyle())); 13546 EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13547 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";", 13548 format("llvm::outs() << " 13549 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa" 13550 "aaaaaaaaaaaaaaaaaaa\";")); 13551 EXPECT_EQ("ffff(\n" 13552 " {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13553 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});", 13554 format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa " 13555 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});", 13556 getGoogleStyle())); 13557 13558 FormatStyle Style = getLLVMStyleWithColumns(12); 13559 Style.BreakStringLiterals = false; 13560 EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style)); 13561 13562 FormatStyle AlignLeft = getLLVMStyleWithColumns(12); 13563 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left; 13564 EXPECT_EQ("#define A \\\n" 13565 " \"some \" \\\n" 13566 " \"text \" \\\n" 13567 " \"other\";", 13568 format("#define A \"some text other\";", AlignLeft)); 13569 } 13570 13571 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) { 13572 EXPECT_EQ("C a = \"some more \"\n" 13573 " \"text\";", 13574 format("C a = \"some more text\";", getLLVMStyleWithColumns(18))); 13575 } 13576 13577 TEST_F(FormatTest, FullyRemoveEmptyLines) { 13578 FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80); 13579 NoEmptyLines.MaxEmptyLinesToKeep = 0; 13580 EXPECT_EQ("int i = a(b());", 13581 format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines)); 13582 } 13583 13584 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) { 13585 EXPECT_EQ( 13586 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 13587 "(\n" 13588 " \"x\t\");", 13589 format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 13590 "aaaaaaa(" 13591 "\"x\t\");")); 13592 } 13593 13594 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) { 13595 EXPECT_EQ( 13596 "u8\"utf8 string \"\n" 13597 "u8\"literal\";", 13598 format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16))); 13599 EXPECT_EQ( 13600 "u\"utf16 string \"\n" 13601 "u\"literal\";", 13602 format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16))); 13603 EXPECT_EQ( 13604 "U\"utf32 string \"\n" 13605 "U\"literal\";", 13606 format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16))); 13607 EXPECT_EQ("L\"wide string \"\n" 13608 "L\"literal\";", 13609 format("L\"wide string literal\";", getGoogleStyleWithColumns(16))); 13610 EXPECT_EQ("@\"NSString \"\n" 13611 "@\"literal\";", 13612 format("@\"NSString literal\";", getGoogleStyleWithColumns(19))); 13613 verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26)); 13614 13615 // This input makes clang-format try to split the incomplete unicode escape 13616 // sequence, which used to lead to a crasher. 13617 verifyNoCrash( 13618 "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 13619 getLLVMStyleWithColumns(60)); 13620 } 13621 13622 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) { 13623 FormatStyle Style = getGoogleStyleWithColumns(15); 13624 EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style)); 13625 EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style)); 13626 EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style)); 13627 EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style)); 13628 EXPECT_EQ("u8R\"x(raw literal)x\";", 13629 format("u8R\"x(raw literal)x\";", Style)); 13630 } 13631 13632 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) { 13633 FormatStyle Style = getLLVMStyleWithColumns(20); 13634 EXPECT_EQ( 13635 "_T(\"aaaaaaaaaaaaaa\")\n" 13636 "_T(\"aaaaaaaaaaaaaa\")\n" 13637 "_T(\"aaaaaaaaaaaa\")", 13638 format(" _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style)); 13639 EXPECT_EQ("f(x,\n" 13640 " _T(\"aaaaaaaaaaaa\")\n" 13641 " _T(\"aaa\"),\n" 13642 " z);", 13643 format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style)); 13644 13645 // FIXME: Handle embedded spaces in one iteration. 13646 // EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n" 13647 // "_T(\"aaaaaaaaaaaaa\")\n" 13648 // "_T(\"aaaaaaaaaaaaa\")\n" 13649 // "_T(\"a\")", 13650 // format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", 13651 // getLLVMStyleWithColumns(20))); 13652 EXPECT_EQ( 13653 "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", 13654 format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style)); 13655 EXPECT_EQ("f(\n" 13656 "#if !TEST\n" 13657 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n" 13658 "#endif\n" 13659 ");", 13660 format("f(\n" 13661 "#if !TEST\n" 13662 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n" 13663 "#endif\n" 13664 ");")); 13665 EXPECT_EQ("f(\n" 13666 "\n" 13667 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));", 13668 format("f(\n" 13669 "\n" 13670 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));")); 13671 // Regression test for accessing tokens past the end of a vector in the 13672 // TokenLexer. 13673 verifyNoCrash(R"(_T( 13674 " 13675 ) 13676 )"); 13677 } 13678 13679 TEST_F(FormatTest, BreaksStringLiteralOperands) { 13680 // In a function call with two operands, the second can be broken with no line 13681 // break before it. 13682 EXPECT_EQ( 13683 "func(a, \"long long \"\n" 13684 " \"long long\");", 13685 format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24))); 13686 // In a function call with three operands, the second must be broken with a 13687 // line break before it. 13688 EXPECT_EQ("func(a,\n" 13689 " \"long long long \"\n" 13690 " \"long\",\n" 13691 " c);", 13692 format("func(a, \"long long long long\", c);", 13693 getLLVMStyleWithColumns(24))); 13694 // In a function call with three operands, the third must be broken with a 13695 // line break before it. 13696 EXPECT_EQ("func(a, b,\n" 13697 " \"long long long \"\n" 13698 " \"long\");", 13699 format("func(a, b, \"long long long long\");", 13700 getLLVMStyleWithColumns(24))); 13701 // In a function call with three operands, both the second and the third must 13702 // be broken with a line break before them. 13703 EXPECT_EQ("func(a,\n" 13704 " \"long long long \"\n" 13705 " \"long\",\n" 13706 " \"long long long \"\n" 13707 " \"long\");", 13708 format("func(a, \"long long long long\", \"long long long long\");", 13709 getLLVMStyleWithColumns(24))); 13710 // In a chain of << with two operands, the second can be broken with no line 13711 // break before it. 13712 EXPECT_EQ("a << \"line line \"\n" 13713 " \"line\";", 13714 format("a << \"line line line\";", getLLVMStyleWithColumns(20))); 13715 // In a chain of << with three operands, the second can be broken with no line 13716 // break before it. 13717 EXPECT_EQ( 13718 "abcde << \"line \"\n" 13719 " \"line line\"\n" 13720 " << c;", 13721 format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20))); 13722 // In a chain of << with three operands, the third must be broken with a line 13723 // break before it. 13724 EXPECT_EQ( 13725 "a << b\n" 13726 " << \"line line \"\n" 13727 " \"line\";", 13728 format("a << b << \"line line line\";", getLLVMStyleWithColumns(20))); 13729 // In a chain of << with three operands, the second can be broken with no line 13730 // break before it and the third must be broken with a line break before it. 13731 EXPECT_EQ("abcd << \"line line \"\n" 13732 " \"line\"\n" 13733 " << \"line line \"\n" 13734 " \"line\";", 13735 format("abcd << \"line line line\" << \"line line line\";", 13736 getLLVMStyleWithColumns(20))); 13737 // In a chain of binary operators with two operands, the second can be broken 13738 // with no line break before it. 13739 EXPECT_EQ( 13740 "abcd + \"line line \"\n" 13741 " \"line line\";", 13742 format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20))); 13743 // In a chain of binary operators with three operands, the second must be 13744 // broken with a line break before it. 13745 EXPECT_EQ("abcd +\n" 13746 " \"line line \"\n" 13747 " \"line line\" +\n" 13748 " e;", 13749 format("abcd + \"line line line line\" + e;", 13750 getLLVMStyleWithColumns(20))); 13751 // In a function call with two operands, with AlignAfterOpenBracket enabled, 13752 // the first must be broken with a line break before it. 13753 FormatStyle Style = getLLVMStyleWithColumns(25); 13754 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 13755 EXPECT_EQ("someFunction(\n" 13756 " \"long long long \"\n" 13757 " \"long\",\n" 13758 " a);", 13759 format("someFunction(\"long long long long\", a);", Style)); 13760 } 13761 13762 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) { 13763 EXPECT_EQ( 13764 "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13765 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13766 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";", 13767 format("aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13768 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13769 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";")); 13770 } 13771 13772 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) { 13773 EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);", 13774 format("f(g(R\"x(raw literal)x\", a), b);", getGoogleStyle())); 13775 EXPECT_EQ("fffffffffff(g(R\"x(\n" 13776 "multiline raw string literal xxxxxxxxxxxxxx\n" 13777 ")x\",\n" 13778 " a),\n" 13779 " b);", 13780 format("fffffffffff(g(R\"x(\n" 13781 "multiline raw string literal xxxxxxxxxxxxxx\n" 13782 ")x\", a), b);", 13783 getGoogleStyleWithColumns(20))); 13784 EXPECT_EQ("fffffffffff(\n" 13785 " g(R\"x(qqq\n" 13786 "multiline raw string literal xxxxxxxxxxxxxx\n" 13787 ")x\",\n" 13788 " a),\n" 13789 " b);", 13790 format("fffffffffff(g(R\"x(qqq\n" 13791 "multiline raw string literal xxxxxxxxxxxxxx\n" 13792 ")x\", a), b);", 13793 getGoogleStyleWithColumns(20))); 13794 13795 EXPECT_EQ("fffffffffff(R\"x(\n" 13796 "multiline raw string literal xxxxxxxxxxxxxx\n" 13797 ")x\");", 13798 format("fffffffffff(R\"x(\n" 13799 "multiline raw string literal xxxxxxxxxxxxxx\n" 13800 ")x\");", 13801 getGoogleStyleWithColumns(20))); 13802 EXPECT_EQ("fffffffffff(R\"x(\n" 13803 "multiline raw string literal xxxxxxxxxxxxxx\n" 13804 ")x\" + bbbbbb);", 13805 format("fffffffffff(R\"x(\n" 13806 "multiline raw string literal xxxxxxxxxxxxxx\n" 13807 ")x\" + bbbbbb);", 13808 getGoogleStyleWithColumns(20))); 13809 EXPECT_EQ("fffffffffff(\n" 13810 " R\"x(\n" 13811 "multiline raw string literal xxxxxxxxxxxxxx\n" 13812 ")x\" +\n" 13813 " bbbbbb);", 13814 format("fffffffffff(\n" 13815 " R\"x(\n" 13816 "multiline raw string literal xxxxxxxxxxxxxx\n" 13817 ")x\" + bbbbbb);", 13818 getGoogleStyleWithColumns(20))); 13819 EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);", 13820 format("fffffffffff(\n" 13821 " R\"(single line raw string)\" + bbbbbb);")); 13822 } 13823 13824 TEST_F(FormatTest, SkipsUnknownStringLiterals) { 13825 verifyFormat("string a = \"unterminated;"); 13826 EXPECT_EQ("function(\"unterminated,\n" 13827 " OtherParameter);", 13828 format("function( \"unterminated,\n" 13829 " OtherParameter);")); 13830 } 13831 13832 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) { 13833 FormatStyle Style = getLLVMStyle(); 13834 Style.Standard = FormatStyle::LS_Cpp03; 13835 EXPECT_EQ("#define x(_a) printf(\"foo\" _a);", 13836 format("#define x(_a) printf(\"foo\"_a);", Style)); 13837 } 13838 13839 TEST_F(FormatTest, CppLexVersion) { 13840 FormatStyle Style = getLLVMStyle(); 13841 // Formatting of x * y differs if x is a type. 13842 verifyFormat("void foo() { MACRO(a * b); }", Style); 13843 verifyFormat("void foo() { MACRO(int *b); }", Style); 13844 13845 // LLVM style uses latest lexer. 13846 verifyFormat("void foo() { MACRO(char8_t *b); }", Style); 13847 Style.Standard = FormatStyle::LS_Cpp17; 13848 // But in c++17, char8_t isn't a keyword. 13849 verifyFormat("void foo() { MACRO(char8_t * b); }", Style); 13850 } 13851 13852 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); } 13853 13854 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) { 13855 EXPECT_EQ("someFunction(\"aaabbbcccd\"\n" 13856 " \"ddeeefff\");", 13857 format("someFunction(\"aaabbbcccdddeeefff\");", 13858 getLLVMStyleWithColumns(25))); 13859 EXPECT_EQ("someFunction1234567890(\n" 13860 " \"aaabbbcccdddeeefff\");", 13861 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 13862 getLLVMStyleWithColumns(26))); 13863 EXPECT_EQ("someFunction1234567890(\n" 13864 " \"aaabbbcccdddeeeff\"\n" 13865 " \"f\");", 13866 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 13867 getLLVMStyleWithColumns(25))); 13868 EXPECT_EQ("someFunction1234567890(\n" 13869 " \"aaabbbcccdddeeeff\"\n" 13870 " \"f\");", 13871 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 13872 getLLVMStyleWithColumns(24))); 13873 EXPECT_EQ("someFunction(\n" 13874 " \"aaabbbcc ddde \"\n" 13875 " \"efff\");", 13876 format("someFunction(\"aaabbbcc ddde efff\");", 13877 getLLVMStyleWithColumns(25))); 13878 EXPECT_EQ("someFunction(\"aaabbbccc \"\n" 13879 " \"ddeeefff\");", 13880 format("someFunction(\"aaabbbccc ddeeefff\");", 13881 getLLVMStyleWithColumns(25))); 13882 EXPECT_EQ("someFunction1234567890(\n" 13883 " \"aaabb \"\n" 13884 " \"cccdddeeefff\");", 13885 format("someFunction1234567890(\"aaabb cccdddeeefff\");", 13886 getLLVMStyleWithColumns(25))); 13887 EXPECT_EQ("#define A \\\n" 13888 " string s = \\\n" 13889 " \"123456789\" \\\n" 13890 " \"0\"; \\\n" 13891 " int i;", 13892 format("#define A string s = \"1234567890\"; int i;", 13893 getLLVMStyleWithColumns(20))); 13894 EXPECT_EQ("someFunction(\n" 13895 " \"aaabbbcc \"\n" 13896 " \"dddeeefff\");", 13897 format("someFunction(\"aaabbbcc dddeeefff\");", 13898 getLLVMStyleWithColumns(25))); 13899 } 13900 13901 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) { 13902 EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3))); 13903 EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2))); 13904 EXPECT_EQ("\"test\"\n" 13905 "\"\\n\"", 13906 format("\"test\\n\"", getLLVMStyleWithColumns(7))); 13907 EXPECT_EQ("\"tes\\\\\"\n" 13908 "\"n\"", 13909 format("\"tes\\\\n\"", getLLVMStyleWithColumns(7))); 13910 EXPECT_EQ("\"\\\\\\\\\"\n" 13911 "\"\\n\"", 13912 format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7))); 13913 EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7))); 13914 EXPECT_EQ("\"\\uff01\"\n" 13915 "\"test\"", 13916 format("\"\\uff01test\"", getLLVMStyleWithColumns(8))); 13917 EXPECT_EQ("\"\\Uff01ff02\"", 13918 format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11))); 13919 EXPECT_EQ("\"\\x000000000001\"\n" 13920 "\"next\"", 13921 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16))); 13922 EXPECT_EQ("\"\\x000000000001next\"", 13923 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15))); 13924 EXPECT_EQ("\"\\x000000000001\"", 13925 format("\"\\x000000000001\"", getLLVMStyleWithColumns(7))); 13926 EXPECT_EQ("\"test\"\n" 13927 "\"\\000000\"\n" 13928 "\"000001\"", 13929 format("\"test\\000000000001\"", getLLVMStyleWithColumns(9))); 13930 EXPECT_EQ("\"test\\000\"\n" 13931 "\"00000000\"\n" 13932 "\"1\"", 13933 format("\"test\\000000000001\"", getLLVMStyleWithColumns(10))); 13934 } 13935 13936 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) { 13937 verifyFormat("void f() {\n" 13938 " return g() {}\n" 13939 " void h() {}"); 13940 verifyFormat("int a[] = {void forgot_closing_brace(){f();\n" 13941 "g();\n" 13942 "}"); 13943 } 13944 13945 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) { 13946 verifyFormat( 13947 "void f() { return C{param1, param2}.SomeCall(param1, param2); }"); 13948 } 13949 13950 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) { 13951 verifyFormat("class X {\n" 13952 " void f() {\n" 13953 " }\n" 13954 "};", 13955 getLLVMStyleWithColumns(12)); 13956 } 13957 13958 TEST_F(FormatTest, ConfigurableIndentWidth) { 13959 FormatStyle EightIndent = getLLVMStyleWithColumns(18); 13960 EightIndent.IndentWidth = 8; 13961 EightIndent.ContinuationIndentWidth = 8; 13962 verifyFormat("void f() {\n" 13963 " someFunction();\n" 13964 " if (true) {\n" 13965 " f();\n" 13966 " }\n" 13967 "}", 13968 EightIndent); 13969 verifyFormat("class X {\n" 13970 " void f() {\n" 13971 " }\n" 13972 "};", 13973 EightIndent); 13974 verifyFormat("int x[] = {\n" 13975 " call(),\n" 13976 " call()};", 13977 EightIndent); 13978 } 13979 13980 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) { 13981 verifyFormat("double\n" 13982 "f();", 13983 getLLVMStyleWithColumns(8)); 13984 } 13985 13986 TEST_F(FormatTest, ConfigurableUseOfTab) { 13987 FormatStyle Tab = getLLVMStyleWithColumns(42); 13988 Tab.IndentWidth = 8; 13989 Tab.UseTab = FormatStyle::UT_Always; 13990 Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left; 13991 13992 EXPECT_EQ("if (aaaaaaaa && // q\n" 13993 " bb)\t\t// w\n" 13994 "\t;", 13995 format("if (aaaaaaaa &&// q\n" 13996 "bb)// w\n" 13997 ";", 13998 Tab)); 13999 EXPECT_EQ("if (aaa && bbb) // w\n" 14000 "\t;", 14001 format("if(aaa&&bbb)// w\n" 14002 ";", 14003 Tab)); 14004 14005 verifyFormat("class X {\n" 14006 "\tvoid f() {\n" 14007 "\t\tsomeFunction(parameter1,\n" 14008 "\t\t\t parameter2);\n" 14009 "\t}\n" 14010 "};", 14011 Tab); 14012 verifyFormat("#define A \\\n" 14013 "\tvoid f() { \\\n" 14014 "\t\tsomeFunction( \\\n" 14015 "\t\t parameter1, \\\n" 14016 "\t\t parameter2); \\\n" 14017 "\t}", 14018 Tab); 14019 verifyFormat("int a;\t // x\n" 14020 "int bbbbbbbb; // x\n", 14021 Tab); 14022 14023 Tab.TabWidth = 4; 14024 Tab.IndentWidth = 8; 14025 verifyFormat("class TabWidth4Indent8 {\n" 14026 "\t\tvoid f() {\n" 14027 "\t\t\t\tsomeFunction(parameter1,\n" 14028 "\t\t\t\t\t\t\t parameter2);\n" 14029 "\t\t}\n" 14030 "};", 14031 Tab); 14032 14033 Tab.TabWidth = 4; 14034 Tab.IndentWidth = 4; 14035 verifyFormat("class TabWidth4Indent4 {\n" 14036 "\tvoid f() {\n" 14037 "\t\tsomeFunction(parameter1,\n" 14038 "\t\t\t\t\t parameter2);\n" 14039 "\t}\n" 14040 "};", 14041 Tab); 14042 14043 Tab.TabWidth = 8; 14044 Tab.IndentWidth = 4; 14045 verifyFormat("class TabWidth8Indent4 {\n" 14046 " void f() {\n" 14047 "\tsomeFunction(parameter1,\n" 14048 "\t\t parameter2);\n" 14049 " }\n" 14050 "};", 14051 Tab); 14052 14053 Tab.TabWidth = 8; 14054 Tab.IndentWidth = 8; 14055 EXPECT_EQ("/*\n" 14056 "\t a\t\tcomment\n" 14057 "\t in multiple lines\n" 14058 " */", 14059 format(" /*\t \t \n" 14060 " \t \t a\t\tcomment\t \t\n" 14061 " \t \t in multiple lines\t\n" 14062 " \t */", 14063 Tab)); 14064 14065 Tab.UseTab = FormatStyle::UT_ForIndentation; 14066 verifyFormat("{\n" 14067 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14068 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14069 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14070 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14071 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14072 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14073 "};", 14074 Tab); 14075 verifyFormat("enum AA {\n" 14076 "\ta1, // Force multiple lines\n" 14077 "\ta2,\n" 14078 "\ta3\n" 14079 "};", 14080 Tab); 14081 EXPECT_EQ("if (aaaaaaaa && // q\n" 14082 " bb) // w\n" 14083 "\t;", 14084 format("if (aaaaaaaa &&// q\n" 14085 "bb)// w\n" 14086 ";", 14087 Tab)); 14088 verifyFormat("class X {\n" 14089 "\tvoid f() {\n" 14090 "\t\tsomeFunction(parameter1,\n" 14091 "\t\t parameter2);\n" 14092 "\t}\n" 14093 "};", 14094 Tab); 14095 verifyFormat("{\n" 14096 "\tQ(\n" 14097 "\t {\n" 14098 "\t\t int a;\n" 14099 "\t\t someFunction(aaaaaaaa,\n" 14100 "\t\t bbbbbbb);\n" 14101 "\t },\n" 14102 "\t p);\n" 14103 "}", 14104 Tab); 14105 EXPECT_EQ("{\n" 14106 "\t/* aaaa\n" 14107 "\t bbbb */\n" 14108 "}", 14109 format("{\n" 14110 "/* aaaa\n" 14111 " bbbb */\n" 14112 "}", 14113 Tab)); 14114 EXPECT_EQ("{\n" 14115 "\t/*\n" 14116 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14117 "\t bbbbbbbbbbbbb\n" 14118 "\t*/\n" 14119 "}", 14120 format("{\n" 14121 "/*\n" 14122 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14123 "*/\n" 14124 "}", 14125 Tab)); 14126 EXPECT_EQ("{\n" 14127 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14128 "\t// bbbbbbbbbbbbb\n" 14129 "}", 14130 format("{\n" 14131 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14132 "}", 14133 Tab)); 14134 EXPECT_EQ("{\n" 14135 "\t/*\n" 14136 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14137 "\t bbbbbbbbbbbbb\n" 14138 "\t*/\n" 14139 "}", 14140 format("{\n" 14141 "\t/*\n" 14142 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14143 "\t*/\n" 14144 "}", 14145 Tab)); 14146 EXPECT_EQ("{\n" 14147 "\t/*\n" 14148 "\n" 14149 "\t*/\n" 14150 "}", 14151 format("{\n" 14152 "\t/*\n" 14153 "\n" 14154 "\t*/\n" 14155 "}", 14156 Tab)); 14157 EXPECT_EQ("{\n" 14158 "\t/*\n" 14159 " asdf\n" 14160 "\t*/\n" 14161 "}", 14162 format("{\n" 14163 "\t/*\n" 14164 " asdf\n" 14165 "\t*/\n" 14166 "}", 14167 Tab)); 14168 14169 verifyFormat("void f() {\n" 14170 "\treturn true ? aaaaaaaaaaaaaaaaaa\n" 14171 "\t : bbbbbbbbbbbbbbbbbb\n" 14172 "}", 14173 Tab); 14174 FormatStyle TabNoBreak = Tab; 14175 TabNoBreak.BreakBeforeTernaryOperators = false; 14176 verifyFormat("void f() {\n" 14177 "\treturn true ? aaaaaaaaaaaaaaaaaa :\n" 14178 "\t bbbbbbbbbbbbbbbbbb\n" 14179 "}", 14180 TabNoBreak); 14181 verifyFormat("void f() {\n" 14182 "\treturn true ?\n" 14183 "\t aaaaaaaaaaaaaaaaaaaa :\n" 14184 "\t bbbbbbbbbbbbbbbbbbbb\n" 14185 "}", 14186 TabNoBreak); 14187 14188 Tab.UseTab = FormatStyle::UT_Never; 14189 EXPECT_EQ("/*\n" 14190 " a\t\tcomment\n" 14191 " in multiple lines\n" 14192 " */", 14193 format(" /*\t \t \n" 14194 " \t \t a\t\tcomment\t \t\n" 14195 " \t \t in multiple lines\t\n" 14196 " \t */", 14197 Tab)); 14198 EXPECT_EQ("/* some\n" 14199 " comment */", 14200 format(" \t \t /* some\n" 14201 " \t \t comment */", 14202 Tab)); 14203 EXPECT_EQ("int a; /* some\n" 14204 " comment */", 14205 format(" \t \t int a; /* some\n" 14206 " \t \t comment */", 14207 Tab)); 14208 14209 EXPECT_EQ("int a; /* some\n" 14210 "comment */", 14211 format(" \t \t int\ta; /* some\n" 14212 " \t \t comment */", 14213 Tab)); 14214 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14215 " comment */", 14216 format(" \t \t f(\"\t\t\"); /* some\n" 14217 " \t \t comment */", 14218 Tab)); 14219 EXPECT_EQ("{\n" 14220 " /*\n" 14221 " * Comment\n" 14222 " */\n" 14223 " int i;\n" 14224 "}", 14225 format("{\n" 14226 "\t/*\n" 14227 "\t * Comment\n" 14228 "\t */\n" 14229 "\t int i;\n" 14230 "}", 14231 Tab)); 14232 14233 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation; 14234 Tab.TabWidth = 8; 14235 Tab.IndentWidth = 8; 14236 EXPECT_EQ("if (aaaaaaaa && // q\n" 14237 " bb) // w\n" 14238 "\t;", 14239 format("if (aaaaaaaa &&// q\n" 14240 "bb)// w\n" 14241 ";", 14242 Tab)); 14243 EXPECT_EQ("if (aaa && bbb) // w\n" 14244 "\t;", 14245 format("if(aaa&&bbb)// w\n" 14246 ";", 14247 Tab)); 14248 verifyFormat("class X {\n" 14249 "\tvoid f() {\n" 14250 "\t\tsomeFunction(parameter1,\n" 14251 "\t\t\t parameter2);\n" 14252 "\t}\n" 14253 "};", 14254 Tab); 14255 verifyFormat("#define A \\\n" 14256 "\tvoid f() { \\\n" 14257 "\t\tsomeFunction( \\\n" 14258 "\t\t parameter1, \\\n" 14259 "\t\t parameter2); \\\n" 14260 "\t}", 14261 Tab); 14262 Tab.TabWidth = 4; 14263 Tab.IndentWidth = 8; 14264 verifyFormat("class TabWidth4Indent8 {\n" 14265 "\t\tvoid f() {\n" 14266 "\t\t\t\tsomeFunction(parameter1,\n" 14267 "\t\t\t\t\t\t\t parameter2);\n" 14268 "\t\t}\n" 14269 "};", 14270 Tab); 14271 Tab.TabWidth = 4; 14272 Tab.IndentWidth = 4; 14273 verifyFormat("class TabWidth4Indent4 {\n" 14274 "\tvoid f() {\n" 14275 "\t\tsomeFunction(parameter1,\n" 14276 "\t\t\t\t\t parameter2);\n" 14277 "\t}\n" 14278 "};", 14279 Tab); 14280 Tab.TabWidth = 8; 14281 Tab.IndentWidth = 4; 14282 verifyFormat("class TabWidth8Indent4 {\n" 14283 " void f() {\n" 14284 "\tsomeFunction(parameter1,\n" 14285 "\t\t parameter2);\n" 14286 " }\n" 14287 "};", 14288 Tab); 14289 Tab.TabWidth = 8; 14290 Tab.IndentWidth = 8; 14291 EXPECT_EQ("/*\n" 14292 "\t a\t\tcomment\n" 14293 "\t in multiple lines\n" 14294 " */", 14295 format(" /*\t \t \n" 14296 " \t \t a\t\tcomment\t \t\n" 14297 " \t \t in multiple lines\t\n" 14298 " \t */", 14299 Tab)); 14300 verifyFormat("{\n" 14301 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14302 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14303 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14304 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14305 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14306 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14307 "};", 14308 Tab); 14309 verifyFormat("enum AA {\n" 14310 "\ta1, // Force multiple lines\n" 14311 "\ta2,\n" 14312 "\ta3\n" 14313 "};", 14314 Tab); 14315 EXPECT_EQ("if (aaaaaaaa && // q\n" 14316 " bb) // w\n" 14317 "\t;", 14318 format("if (aaaaaaaa &&// q\n" 14319 "bb)// w\n" 14320 ";", 14321 Tab)); 14322 verifyFormat("class X {\n" 14323 "\tvoid f() {\n" 14324 "\t\tsomeFunction(parameter1,\n" 14325 "\t\t\t parameter2);\n" 14326 "\t}\n" 14327 "};", 14328 Tab); 14329 verifyFormat("{\n" 14330 "\tQ(\n" 14331 "\t {\n" 14332 "\t\t int a;\n" 14333 "\t\t someFunction(aaaaaaaa,\n" 14334 "\t\t\t\t bbbbbbb);\n" 14335 "\t },\n" 14336 "\t p);\n" 14337 "}", 14338 Tab); 14339 EXPECT_EQ("{\n" 14340 "\t/* aaaa\n" 14341 "\t bbbb */\n" 14342 "}", 14343 format("{\n" 14344 "/* aaaa\n" 14345 " bbbb */\n" 14346 "}", 14347 Tab)); 14348 EXPECT_EQ("{\n" 14349 "\t/*\n" 14350 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14351 "\t bbbbbbbbbbbbb\n" 14352 "\t*/\n" 14353 "}", 14354 format("{\n" 14355 "/*\n" 14356 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14357 "*/\n" 14358 "}", 14359 Tab)); 14360 EXPECT_EQ("{\n" 14361 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14362 "\t// bbbbbbbbbbbbb\n" 14363 "}", 14364 format("{\n" 14365 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14366 "}", 14367 Tab)); 14368 EXPECT_EQ("{\n" 14369 "\t/*\n" 14370 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14371 "\t bbbbbbbbbbbbb\n" 14372 "\t*/\n" 14373 "}", 14374 format("{\n" 14375 "\t/*\n" 14376 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14377 "\t*/\n" 14378 "}", 14379 Tab)); 14380 EXPECT_EQ("{\n" 14381 "\t/*\n" 14382 "\n" 14383 "\t*/\n" 14384 "}", 14385 format("{\n" 14386 "\t/*\n" 14387 "\n" 14388 "\t*/\n" 14389 "}", 14390 Tab)); 14391 EXPECT_EQ("{\n" 14392 "\t/*\n" 14393 " asdf\n" 14394 "\t*/\n" 14395 "}", 14396 format("{\n" 14397 "\t/*\n" 14398 " asdf\n" 14399 "\t*/\n" 14400 "}", 14401 Tab)); 14402 EXPECT_EQ("/* some\n" 14403 " comment */", 14404 format(" \t \t /* some\n" 14405 " \t \t comment */", 14406 Tab)); 14407 EXPECT_EQ("int a; /* some\n" 14408 " comment */", 14409 format(" \t \t int a; /* some\n" 14410 " \t \t comment */", 14411 Tab)); 14412 EXPECT_EQ("int a; /* some\n" 14413 "comment */", 14414 format(" \t \t int\ta; /* some\n" 14415 " \t \t comment */", 14416 Tab)); 14417 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14418 " comment */", 14419 format(" \t \t f(\"\t\t\"); /* some\n" 14420 " \t \t comment */", 14421 Tab)); 14422 EXPECT_EQ("{\n" 14423 "\t/*\n" 14424 "\t * Comment\n" 14425 "\t */\n" 14426 "\tint i;\n" 14427 "}", 14428 format("{\n" 14429 "\t/*\n" 14430 "\t * Comment\n" 14431 "\t */\n" 14432 "\t int i;\n" 14433 "}", 14434 Tab)); 14435 Tab.TabWidth = 2; 14436 Tab.IndentWidth = 2; 14437 EXPECT_EQ("{\n" 14438 "\t/* aaaa\n" 14439 "\t\t bbbb */\n" 14440 "}", 14441 format("{\n" 14442 "/* aaaa\n" 14443 "\t bbbb */\n" 14444 "}", 14445 Tab)); 14446 EXPECT_EQ("{\n" 14447 "\t/*\n" 14448 "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14449 "\t\tbbbbbbbbbbbbb\n" 14450 "\t*/\n" 14451 "}", 14452 format("{\n" 14453 "/*\n" 14454 "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14455 "*/\n" 14456 "}", 14457 Tab)); 14458 Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 14459 Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 14460 Tab.TabWidth = 4; 14461 Tab.IndentWidth = 4; 14462 verifyFormat("class Assign {\n" 14463 "\tvoid f() {\n" 14464 "\t\tint x = 123;\n" 14465 "\t\tint random = 4;\n" 14466 "\t\tstd::string alphabet =\n" 14467 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n" 14468 "\t}\n" 14469 "};", 14470 Tab); 14471 14472 Tab.UseTab = FormatStyle::UT_AlignWithSpaces; 14473 Tab.TabWidth = 8; 14474 Tab.IndentWidth = 8; 14475 EXPECT_EQ("if (aaaaaaaa && // q\n" 14476 " bb) // w\n" 14477 "\t;", 14478 format("if (aaaaaaaa &&// q\n" 14479 "bb)// w\n" 14480 ";", 14481 Tab)); 14482 EXPECT_EQ("if (aaa && bbb) // w\n" 14483 "\t;", 14484 format("if(aaa&&bbb)// w\n" 14485 ";", 14486 Tab)); 14487 verifyFormat("class X {\n" 14488 "\tvoid f() {\n" 14489 "\t\tsomeFunction(parameter1,\n" 14490 "\t\t parameter2);\n" 14491 "\t}\n" 14492 "};", 14493 Tab); 14494 verifyFormat("#define A \\\n" 14495 "\tvoid f() { \\\n" 14496 "\t\tsomeFunction( \\\n" 14497 "\t\t parameter1, \\\n" 14498 "\t\t parameter2); \\\n" 14499 "\t}", 14500 Tab); 14501 Tab.TabWidth = 4; 14502 Tab.IndentWidth = 8; 14503 verifyFormat("class TabWidth4Indent8 {\n" 14504 "\t\tvoid f() {\n" 14505 "\t\t\t\tsomeFunction(parameter1,\n" 14506 "\t\t\t\t parameter2);\n" 14507 "\t\t}\n" 14508 "};", 14509 Tab); 14510 Tab.TabWidth = 4; 14511 Tab.IndentWidth = 4; 14512 verifyFormat("class TabWidth4Indent4 {\n" 14513 "\tvoid f() {\n" 14514 "\t\tsomeFunction(parameter1,\n" 14515 "\t\t parameter2);\n" 14516 "\t}\n" 14517 "};", 14518 Tab); 14519 Tab.TabWidth = 8; 14520 Tab.IndentWidth = 4; 14521 verifyFormat("class TabWidth8Indent4 {\n" 14522 " void f() {\n" 14523 "\tsomeFunction(parameter1,\n" 14524 "\t parameter2);\n" 14525 " }\n" 14526 "};", 14527 Tab); 14528 Tab.TabWidth = 8; 14529 Tab.IndentWidth = 8; 14530 EXPECT_EQ("/*\n" 14531 " a\t\tcomment\n" 14532 " in multiple lines\n" 14533 " */", 14534 format(" /*\t \t \n" 14535 " \t \t a\t\tcomment\t \t\n" 14536 " \t \t in multiple lines\t\n" 14537 " \t */", 14538 Tab)); 14539 verifyFormat("{\n" 14540 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14541 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14542 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14543 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14544 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14545 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14546 "};", 14547 Tab); 14548 verifyFormat("enum AA {\n" 14549 "\ta1, // Force multiple lines\n" 14550 "\ta2,\n" 14551 "\ta3\n" 14552 "};", 14553 Tab); 14554 EXPECT_EQ("if (aaaaaaaa && // q\n" 14555 " bb) // w\n" 14556 "\t;", 14557 format("if (aaaaaaaa &&// q\n" 14558 "bb)// w\n" 14559 ";", 14560 Tab)); 14561 verifyFormat("class X {\n" 14562 "\tvoid f() {\n" 14563 "\t\tsomeFunction(parameter1,\n" 14564 "\t\t parameter2);\n" 14565 "\t}\n" 14566 "};", 14567 Tab); 14568 verifyFormat("{\n" 14569 "\tQ(\n" 14570 "\t {\n" 14571 "\t\t int a;\n" 14572 "\t\t someFunction(aaaaaaaa,\n" 14573 "\t\t bbbbbbb);\n" 14574 "\t },\n" 14575 "\t p);\n" 14576 "}", 14577 Tab); 14578 EXPECT_EQ("{\n" 14579 "\t/* aaaa\n" 14580 "\t bbbb */\n" 14581 "}", 14582 format("{\n" 14583 "/* aaaa\n" 14584 " bbbb */\n" 14585 "}", 14586 Tab)); 14587 EXPECT_EQ("{\n" 14588 "\t/*\n" 14589 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14590 "\t bbbbbbbbbbbbb\n" 14591 "\t*/\n" 14592 "}", 14593 format("{\n" 14594 "/*\n" 14595 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14596 "*/\n" 14597 "}", 14598 Tab)); 14599 EXPECT_EQ("{\n" 14600 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14601 "\t// bbbbbbbbbbbbb\n" 14602 "}", 14603 format("{\n" 14604 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14605 "}", 14606 Tab)); 14607 EXPECT_EQ("{\n" 14608 "\t/*\n" 14609 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14610 "\t bbbbbbbbbbbbb\n" 14611 "\t*/\n" 14612 "}", 14613 format("{\n" 14614 "\t/*\n" 14615 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14616 "\t*/\n" 14617 "}", 14618 Tab)); 14619 EXPECT_EQ("{\n" 14620 "\t/*\n" 14621 "\n" 14622 "\t*/\n" 14623 "}", 14624 format("{\n" 14625 "\t/*\n" 14626 "\n" 14627 "\t*/\n" 14628 "}", 14629 Tab)); 14630 EXPECT_EQ("{\n" 14631 "\t/*\n" 14632 " asdf\n" 14633 "\t*/\n" 14634 "}", 14635 format("{\n" 14636 "\t/*\n" 14637 " asdf\n" 14638 "\t*/\n" 14639 "}", 14640 Tab)); 14641 EXPECT_EQ("/* some\n" 14642 " comment */", 14643 format(" \t \t /* some\n" 14644 " \t \t comment */", 14645 Tab)); 14646 EXPECT_EQ("int a; /* some\n" 14647 " comment */", 14648 format(" \t \t int a; /* some\n" 14649 " \t \t comment */", 14650 Tab)); 14651 EXPECT_EQ("int a; /* some\n" 14652 "comment */", 14653 format(" \t \t int\ta; /* some\n" 14654 " \t \t comment */", 14655 Tab)); 14656 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14657 " comment */", 14658 format(" \t \t f(\"\t\t\"); /* some\n" 14659 " \t \t comment */", 14660 Tab)); 14661 EXPECT_EQ("{\n" 14662 "\t/*\n" 14663 "\t * Comment\n" 14664 "\t */\n" 14665 "\tint i;\n" 14666 "}", 14667 format("{\n" 14668 "\t/*\n" 14669 "\t * Comment\n" 14670 "\t */\n" 14671 "\t int i;\n" 14672 "}", 14673 Tab)); 14674 Tab.TabWidth = 2; 14675 Tab.IndentWidth = 2; 14676 EXPECT_EQ("{\n" 14677 "\t/* aaaa\n" 14678 "\t bbbb */\n" 14679 "}", 14680 format("{\n" 14681 "/* aaaa\n" 14682 " bbbb */\n" 14683 "}", 14684 Tab)); 14685 EXPECT_EQ("{\n" 14686 "\t/*\n" 14687 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14688 "\t bbbbbbbbbbbbb\n" 14689 "\t*/\n" 14690 "}", 14691 format("{\n" 14692 "/*\n" 14693 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14694 "*/\n" 14695 "}", 14696 Tab)); 14697 Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 14698 Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 14699 Tab.TabWidth = 4; 14700 Tab.IndentWidth = 4; 14701 verifyFormat("class Assign {\n" 14702 "\tvoid f() {\n" 14703 "\t\tint x = 123;\n" 14704 "\t\tint random = 4;\n" 14705 "\t\tstd::string alphabet =\n" 14706 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n" 14707 "\t}\n" 14708 "};", 14709 Tab); 14710 Tab.AlignOperands = FormatStyle::OAS_Align; 14711 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n" 14712 " cccccccccccccccccccc;", 14713 Tab); 14714 // no alignment 14715 verifyFormat("int aaaaaaaaaa =\n" 14716 "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 14717 Tab); 14718 verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n" 14719 " : bbbbbbbbbbbbbb ? 222222222222222\n" 14720 " : 333333333333333;", 14721 Tab); 14722 Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 14723 Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator; 14724 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n" 14725 " + cccccccccccccccccccc;", 14726 Tab); 14727 } 14728 14729 TEST_F(FormatTest, ZeroTabWidth) { 14730 FormatStyle Tab = getLLVMStyleWithColumns(42); 14731 Tab.IndentWidth = 8; 14732 Tab.UseTab = FormatStyle::UT_Never; 14733 Tab.TabWidth = 0; 14734 EXPECT_EQ("void a(){\n" 14735 " // line starts with '\t'\n" 14736 "};", 14737 format("void a(){\n" 14738 "\t// line starts with '\t'\n" 14739 "};", 14740 Tab)); 14741 14742 EXPECT_EQ("void a(){\n" 14743 " // line starts with '\t'\n" 14744 "};", 14745 format("void a(){\n" 14746 "\t\t// line starts with '\t'\n" 14747 "};", 14748 Tab)); 14749 14750 Tab.UseTab = FormatStyle::UT_ForIndentation; 14751 EXPECT_EQ("void a(){\n" 14752 " // line starts with '\t'\n" 14753 "};", 14754 format("void a(){\n" 14755 "\t// line starts with '\t'\n" 14756 "};", 14757 Tab)); 14758 14759 EXPECT_EQ("void a(){\n" 14760 " // line starts with '\t'\n" 14761 "};", 14762 format("void a(){\n" 14763 "\t\t// line starts with '\t'\n" 14764 "};", 14765 Tab)); 14766 14767 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation; 14768 EXPECT_EQ("void a(){\n" 14769 " // line starts with '\t'\n" 14770 "};", 14771 format("void a(){\n" 14772 "\t// line starts with '\t'\n" 14773 "};", 14774 Tab)); 14775 14776 EXPECT_EQ("void a(){\n" 14777 " // line starts with '\t'\n" 14778 "};", 14779 format("void a(){\n" 14780 "\t\t// line starts with '\t'\n" 14781 "};", 14782 Tab)); 14783 14784 Tab.UseTab = FormatStyle::UT_AlignWithSpaces; 14785 EXPECT_EQ("void a(){\n" 14786 " // line starts with '\t'\n" 14787 "};", 14788 format("void a(){\n" 14789 "\t// line starts with '\t'\n" 14790 "};", 14791 Tab)); 14792 14793 EXPECT_EQ("void a(){\n" 14794 " // line starts with '\t'\n" 14795 "};", 14796 format("void a(){\n" 14797 "\t\t// line starts with '\t'\n" 14798 "};", 14799 Tab)); 14800 14801 Tab.UseTab = FormatStyle::UT_Always; 14802 EXPECT_EQ("void a(){\n" 14803 "// line starts with '\t'\n" 14804 "};", 14805 format("void a(){\n" 14806 "\t// line starts with '\t'\n" 14807 "};", 14808 Tab)); 14809 14810 EXPECT_EQ("void a(){\n" 14811 "// line starts with '\t'\n" 14812 "};", 14813 format("void a(){\n" 14814 "\t\t// line starts with '\t'\n" 14815 "};", 14816 Tab)); 14817 } 14818 14819 TEST_F(FormatTest, CalculatesOriginalColumn) { 14820 EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14821 "q\"; /* some\n" 14822 " comment */", 14823 format(" \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14824 "q\"; /* some\n" 14825 " comment */", 14826 getLLVMStyle())); 14827 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n" 14828 "/* some\n" 14829 " comment */", 14830 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n" 14831 " /* some\n" 14832 " comment */", 14833 getLLVMStyle())); 14834 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14835 "qqq\n" 14836 "/* some\n" 14837 " comment */", 14838 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14839 "qqq\n" 14840 " /* some\n" 14841 " comment */", 14842 getLLVMStyle())); 14843 EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14844 "wwww; /* some\n" 14845 " comment */", 14846 format(" inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14847 "wwww; /* some\n" 14848 " comment */", 14849 getLLVMStyle())); 14850 } 14851 14852 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) { 14853 FormatStyle NoSpace = getLLVMStyle(); 14854 NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never; 14855 14856 verifyFormat("while(true)\n" 14857 " continue;", 14858 NoSpace); 14859 verifyFormat("for(;;)\n" 14860 " continue;", 14861 NoSpace); 14862 verifyFormat("if(true)\n" 14863 " f();\n" 14864 "else if(true)\n" 14865 " f();", 14866 NoSpace); 14867 verifyFormat("do {\n" 14868 " do_something();\n" 14869 "} while(something());", 14870 NoSpace); 14871 verifyFormat("switch(x) {\n" 14872 "default:\n" 14873 " break;\n" 14874 "}", 14875 NoSpace); 14876 verifyFormat("auto i = std::make_unique<int>(5);", NoSpace); 14877 verifyFormat("size_t x = sizeof(x);", NoSpace); 14878 verifyFormat("auto f(int x) -> decltype(x);", NoSpace); 14879 verifyFormat("auto f(int x) -> typeof(x);", NoSpace); 14880 verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace); 14881 verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace); 14882 verifyFormat("int f(T x) noexcept(x.create());", NoSpace); 14883 verifyFormat("alignas(128) char a[128];", NoSpace); 14884 verifyFormat("size_t x = alignof(MyType);", NoSpace); 14885 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace); 14886 verifyFormat("int f() throw(Deprecated);", NoSpace); 14887 verifyFormat("typedef void (*cb)(int);", NoSpace); 14888 verifyFormat("T A::operator()();", NoSpace); 14889 verifyFormat("X A::operator++(T);", NoSpace); 14890 verifyFormat("auto lambda = []() { return 0; };", NoSpace); 14891 14892 FormatStyle Space = getLLVMStyle(); 14893 Space.SpaceBeforeParens = FormatStyle::SBPO_Always; 14894 14895 verifyFormat("int f ();", Space); 14896 verifyFormat("void f (int a, T b) {\n" 14897 " while (true)\n" 14898 " continue;\n" 14899 "}", 14900 Space); 14901 verifyFormat("if (true)\n" 14902 " f ();\n" 14903 "else if (true)\n" 14904 " f ();", 14905 Space); 14906 verifyFormat("do {\n" 14907 " do_something ();\n" 14908 "} while (something ());", 14909 Space); 14910 verifyFormat("switch (x) {\n" 14911 "default:\n" 14912 " break;\n" 14913 "}", 14914 Space); 14915 verifyFormat("A::A () : a (1) {}", Space); 14916 verifyFormat("void f () __attribute__ ((asdf));", Space); 14917 verifyFormat("*(&a + 1);\n" 14918 "&((&a)[1]);\n" 14919 "a[(b + c) * d];\n" 14920 "(((a + 1) * 2) + 3) * 4;", 14921 Space); 14922 verifyFormat("#define A(x) x", Space); 14923 verifyFormat("#define A (x) x", Space); 14924 verifyFormat("#if defined(x)\n" 14925 "#endif", 14926 Space); 14927 verifyFormat("auto i = std::make_unique<int> (5);", Space); 14928 verifyFormat("size_t x = sizeof (x);", Space); 14929 verifyFormat("auto f (int x) -> decltype (x);", Space); 14930 verifyFormat("auto f (int x) -> typeof (x);", Space); 14931 verifyFormat("auto f (int x) -> _Atomic (x);", Space); 14932 verifyFormat("auto f (int x) -> __underlying_type (x);", Space); 14933 verifyFormat("int f (T x) noexcept (x.create ());", Space); 14934 verifyFormat("alignas (128) char a[128];", Space); 14935 verifyFormat("size_t x = alignof (MyType);", Space); 14936 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space); 14937 verifyFormat("int f () throw (Deprecated);", Space); 14938 verifyFormat("typedef void (*cb) (int);", Space); 14939 // FIXME these tests regressed behaviour. 14940 // verifyFormat("T A::operator() ();", Space); 14941 // verifyFormat("X A::operator++ (T);", Space); 14942 verifyFormat("auto lambda = [] () { return 0; };", Space); 14943 verifyFormat("int x = int (y);", Space); 14944 14945 FormatStyle SomeSpace = getLLVMStyle(); 14946 SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses; 14947 14948 verifyFormat("[]() -> float {}", SomeSpace); 14949 verifyFormat("[] (auto foo) {}", SomeSpace); 14950 verifyFormat("[foo]() -> int {}", SomeSpace); 14951 verifyFormat("int f();", SomeSpace); 14952 verifyFormat("void f (int a, T b) {\n" 14953 " while (true)\n" 14954 " continue;\n" 14955 "}", 14956 SomeSpace); 14957 verifyFormat("if (true)\n" 14958 " f();\n" 14959 "else if (true)\n" 14960 " f();", 14961 SomeSpace); 14962 verifyFormat("do {\n" 14963 " do_something();\n" 14964 "} while (something());", 14965 SomeSpace); 14966 verifyFormat("switch (x) {\n" 14967 "default:\n" 14968 " break;\n" 14969 "}", 14970 SomeSpace); 14971 verifyFormat("A::A() : a (1) {}", SomeSpace); 14972 verifyFormat("void f() __attribute__ ((asdf));", SomeSpace); 14973 verifyFormat("*(&a + 1);\n" 14974 "&((&a)[1]);\n" 14975 "a[(b + c) * d];\n" 14976 "(((a + 1) * 2) + 3) * 4;", 14977 SomeSpace); 14978 verifyFormat("#define A(x) x", SomeSpace); 14979 verifyFormat("#define A (x) x", SomeSpace); 14980 verifyFormat("#if defined(x)\n" 14981 "#endif", 14982 SomeSpace); 14983 verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace); 14984 verifyFormat("size_t x = sizeof (x);", SomeSpace); 14985 verifyFormat("auto f (int x) -> decltype (x);", SomeSpace); 14986 verifyFormat("auto f (int x) -> typeof (x);", SomeSpace); 14987 verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace); 14988 verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace); 14989 verifyFormat("int f (T x) noexcept (x.create());", SomeSpace); 14990 verifyFormat("alignas (128) char a[128];", SomeSpace); 14991 verifyFormat("size_t x = alignof (MyType);", SomeSpace); 14992 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", 14993 SomeSpace); 14994 verifyFormat("int f() throw (Deprecated);", SomeSpace); 14995 verifyFormat("typedef void (*cb) (int);", SomeSpace); 14996 verifyFormat("T A::operator()();", SomeSpace); 14997 // FIXME these tests regressed behaviour. 14998 // verifyFormat("X A::operator++ (T);", SomeSpace); 14999 verifyFormat("int x = int (y);", SomeSpace); 15000 verifyFormat("auto lambda = []() { return 0; };", SomeSpace); 15001 15002 FormatStyle SpaceControlStatements = getLLVMStyle(); 15003 SpaceControlStatements.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15004 SpaceControlStatements.SpaceBeforeParensOptions.AfterControlStatements = true; 15005 15006 verifyFormat("while (true)\n" 15007 " continue;", 15008 SpaceControlStatements); 15009 verifyFormat("if (true)\n" 15010 " f();\n" 15011 "else if (true)\n" 15012 " f();", 15013 SpaceControlStatements); 15014 verifyFormat("for (;;) {\n" 15015 " do_something();\n" 15016 "}", 15017 SpaceControlStatements); 15018 verifyFormat("do {\n" 15019 " do_something();\n" 15020 "} while (something());", 15021 SpaceControlStatements); 15022 verifyFormat("switch (x) {\n" 15023 "default:\n" 15024 " break;\n" 15025 "}", 15026 SpaceControlStatements); 15027 15028 FormatStyle SpaceFuncDecl = getLLVMStyle(); 15029 SpaceFuncDecl.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15030 SpaceFuncDecl.SpaceBeforeParensOptions.AfterFunctionDeclarationName = true; 15031 15032 verifyFormat("int f ();", SpaceFuncDecl); 15033 verifyFormat("void f(int a, T b) {}", SpaceFuncDecl); 15034 verifyFormat("A::A() : a(1) {}", SpaceFuncDecl); 15035 verifyFormat("void f () __attribute__((asdf));", SpaceFuncDecl); 15036 verifyFormat("#define A(x) x", SpaceFuncDecl); 15037 verifyFormat("#define A (x) x", SpaceFuncDecl); 15038 verifyFormat("#if defined(x)\n" 15039 "#endif", 15040 SpaceFuncDecl); 15041 verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDecl); 15042 verifyFormat("size_t x = sizeof(x);", SpaceFuncDecl); 15043 verifyFormat("auto f (int x) -> decltype(x);", SpaceFuncDecl); 15044 verifyFormat("auto f (int x) -> typeof(x);", SpaceFuncDecl); 15045 verifyFormat("auto f (int x) -> _Atomic(x);", SpaceFuncDecl); 15046 verifyFormat("auto f (int x) -> __underlying_type(x);", SpaceFuncDecl); 15047 verifyFormat("int f (T x) noexcept(x.create());", SpaceFuncDecl); 15048 verifyFormat("alignas(128) char a[128];", SpaceFuncDecl); 15049 verifyFormat("size_t x = alignof(MyType);", SpaceFuncDecl); 15050 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", 15051 SpaceFuncDecl); 15052 verifyFormat("int f () throw(Deprecated);", SpaceFuncDecl); 15053 verifyFormat("typedef void (*cb)(int);", SpaceFuncDecl); 15054 // FIXME these tests regressed behaviour. 15055 // verifyFormat("T A::operator() ();", SpaceFuncDecl); 15056 // verifyFormat("X A::operator++ (T);", SpaceFuncDecl); 15057 verifyFormat("T A::operator()() {}", SpaceFuncDecl); 15058 verifyFormat("auto lambda = []() { return 0; };", SpaceFuncDecl); 15059 verifyFormat("int x = int(y);", SpaceFuncDecl); 15060 verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}", 15061 SpaceFuncDecl); 15062 15063 FormatStyle SpaceFuncDef = getLLVMStyle(); 15064 SpaceFuncDef.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15065 SpaceFuncDef.SpaceBeforeParensOptions.AfterFunctionDefinitionName = true; 15066 15067 verifyFormat("int f();", SpaceFuncDef); 15068 verifyFormat("void f (int a, T b) {}", SpaceFuncDef); 15069 verifyFormat("A::A() : a(1) {}", SpaceFuncDef); 15070 verifyFormat("void f() __attribute__((asdf));", SpaceFuncDef); 15071 verifyFormat("#define A(x) x", SpaceFuncDef); 15072 verifyFormat("#define A (x) x", SpaceFuncDef); 15073 verifyFormat("#if defined(x)\n" 15074 "#endif", 15075 SpaceFuncDef); 15076 verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDef); 15077 verifyFormat("size_t x = sizeof(x);", SpaceFuncDef); 15078 verifyFormat("auto f(int x) -> decltype(x);", SpaceFuncDef); 15079 verifyFormat("auto f(int x) -> typeof(x);", SpaceFuncDef); 15080 verifyFormat("auto f(int x) -> _Atomic(x);", SpaceFuncDef); 15081 verifyFormat("auto f(int x) -> __underlying_type(x);", SpaceFuncDef); 15082 verifyFormat("int f(T x) noexcept(x.create());", SpaceFuncDef); 15083 verifyFormat("alignas(128) char a[128];", SpaceFuncDef); 15084 verifyFormat("size_t x = alignof(MyType);", SpaceFuncDef); 15085 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", 15086 SpaceFuncDef); 15087 verifyFormat("int f() throw(Deprecated);", SpaceFuncDef); 15088 verifyFormat("typedef void (*cb)(int);", SpaceFuncDef); 15089 verifyFormat("T A::operator()();", SpaceFuncDef); 15090 verifyFormat("X A::operator++(T);", SpaceFuncDef); 15091 // verifyFormat("T A::operator() () {}", SpaceFuncDef); 15092 verifyFormat("auto lambda = [] () { return 0; };", SpaceFuncDef); 15093 verifyFormat("int x = int(y);", SpaceFuncDef); 15094 verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}", 15095 SpaceFuncDef); 15096 15097 FormatStyle SpaceIfMacros = getLLVMStyle(); 15098 SpaceIfMacros.IfMacros.clear(); 15099 SpaceIfMacros.IfMacros.push_back("MYIF"); 15100 SpaceIfMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15101 SpaceIfMacros.SpaceBeforeParensOptions.AfterIfMacros = true; 15102 verifyFormat("MYIF (a)\n return;", SpaceIfMacros); 15103 verifyFormat("MYIF (a)\n return;\nelse MYIF (b)\n return;", SpaceIfMacros); 15104 verifyFormat("MYIF (a)\n return;\nelse\n return;", SpaceIfMacros); 15105 15106 FormatStyle SpaceForeachMacros = getLLVMStyle(); 15107 EXPECT_EQ(SpaceForeachMacros.AllowShortBlocksOnASingleLine, 15108 FormatStyle::SBS_Never); 15109 EXPECT_EQ(SpaceForeachMacros.AllowShortLoopsOnASingleLine, false); 15110 SpaceForeachMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15111 SpaceForeachMacros.SpaceBeforeParensOptions.AfterForeachMacros = true; 15112 verifyFormat("for (;;) {\n" 15113 "}", 15114 SpaceForeachMacros); 15115 verifyFormat("foreach (Item *item, itemlist) {\n" 15116 "}", 15117 SpaceForeachMacros); 15118 verifyFormat("Q_FOREACH (Item *item, itemlist) {\n" 15119 "}", 15120 SpaceForeachMacros); 15121 verifyFormat("BOOST_FOREACH (Item *item, itemlist) {\n" 15122 "}", 15123 SpaceForeachMacros); 15124 verifyFormat("UNKNOWN_FOREACH(Item *item, itemlist) {}", SpaceForeachMacros); 15125 15126 FormatStyle SomeSpace2 = getLLVMStyle(); 15127 SomeSpace2.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15128 SomeSpace2.SpaceBeforeParensOptions.BeforeNonEmptyParentheses = true; 15129 verifyFormat("[]() -> float {}", SomeSpace2); 15130 verifyFormat("[] (auto foo) {}", SomeSpace2); 15131 verifyFormat("[foo]() -> int {}", SomeSpace2); 15132 verifyFormat("int f();", SomeSpace2); 15133 verifyFormat("void f (int a, T b) {\n" 15134 " while (true)\n" 15135 " continue;\n" 15136 "}", 15137 SomeSpace2); 15138 verifyFormat("if (true)\n" 15139 " f();\n" 15140 "else if (true)\n" 15141 " f();", 15142 SomeSpace2); 15143 verifyFormat("do {\n" 15144 " do_something();\n" 15145 "} while (something());", 15146 SomeSpace2); 15147 verifyFormat("switch (x) {\n" 15148 "default:\n" 15149 " break;\n" 15150 "}", 15151 SomeSpace2); 15152 verifyFormat("A::A() : a (1) {}", SomeSpace2); 15153 verifyFormat("void f() __attribute__ ((asdf));", SomeSpace2); 15154 verifyFormat("*(&a + 1);\n" 15155 "&((&a)[1]);\n" 15156 "a[(b + c) * d];\n" 15157 "(((a + 1) * 2) + 3) * 4;", 15158 SomeSpace2); 15159 verifyFormat("#define A(x) x", SomeSpace2); 15160 verifyFormat("#define A (x) x", SomeSpace2); 15161 verifyFormat("#if defined(x)\n" 15162 "#endif", 15163 SomeSpace2); 15164 verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace2); 15165 verifyFormat("size_t x = sizeof (x);", SomeSpace2); 15166 verifyFormat("auto f (int x) -> decltype (x);", SomeSpace2); 15167 verifyFormat("auto f (int x) -> typeof (x);", SomeSpace2); 15168 verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace2); 15169 verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace2); 15170 verifyFormat("int f (T x) noexcept (x.create());", SomeSpace2); 15171 verifyFormat("alignas (128) char a[128];", SomeSpace2); 15172 verifyFormat("size_t x = alignof (MyType);", SomeSpace2); 15173 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", 15174 SomeSpace2); 15175 verifyFormat("int f() throw (Deprecated);", SomeSpace2); 15176 verifyFormat("typedef void (*cb) (int);", SomeSpace2); 15177 verifyFormat("T A::operator()();", SomeSpace2); 15178 // verifyFormat("X A::operator++ (T);", SomeSpace2); 15179 verifyFormat("int x = int (y);", SomeSpace2); 15180 verifyFormat("auto lambda = []() { return 0; };", SomeSpace2); 15181 15182 FormatStyle SpaceAfterOverloadedOperator = getLLVMStyle(); 15183 SpaceAfterOverloadedOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15184 SpaceAfterOverloadedOperator.SpaceBeforeParensOptions 15185 .AfterOverloadedOperator = true; 15186 15187 verifyFormat("auto operator++ () -> int;", SpaceAfterOverloadedOperator); 15188 verifyFormat("X A::operator++ ();", SpaceAfterOverloadedOperator); 15189 verifyFormat("some_object.operator++ ();", SpaceAfterOverloadedOperator); 15190 verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator); 15191 15192 SpaceAfterOverloadedOperator.SpaceBeforeParensOptions 15193 .AfterOverloadedOperator = false; 15194 15195 verifyFormat("auto operator++() -> int;", SpaceAfterOverloadedOperator); 15196 verifyFormat("X A::operator++();", SpaceAfterOverloadedOperator); 15197 verifyFormat("some_object.operator++();", SpaceAfterOverloadedOperator); 15198 verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator); 15199 15200 auto SpaceAfterRequires = getLLVMStyle(); 15201 SpaceAfterRequires.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15202 EXPECT_FALSE( 15203 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause); 15204 EXPECT_FALSE( 15205 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression); 15206 verifyFormat("void f(auto x)\n" 15207 " requires requires(int i) { x + i; }\n" 15208 "{}", 15209 SpaceAfterRequires); 15210 verifyFormat("void f(auto x)\n" 15211 " requires(requires(int i) { x + i; })\n" 15212 "{}", 15213 SpaceAfterRequires); 15214 verifyFormat("if (requires(int i) { x + i; })\n" 15215 " return;", 15216 SpaceAfterRequires); 15217 verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires); 15218 verifyFormat("template <typename T>\n" 15219 " requires(Foo<T>)\n" 15220 "class Bar;", 15221 SpaceAfterRequires); 15222 15223 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true; 15224 verifyFormat("void f(auto x)\n" 15225 " requires requires(int i) { x + i; }\n" 15226 "{}", 15227 SpaceAfterRequires); 15228 verifyFormat("void f(auto x)\n" 15229 " requires (requires(int i) { x + i; })\n" 15230 "{}", 15231 SpaceAfterRequires); 15232 verifyFormat("if (requires(int i) { x + i; })\n" 15233 " return;", 15234 SpaceAfterRequires); 15235 verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires); 15236 verifyFormat("template <typename T>\n" 15237 " requires (Foo<T>)\n" 15238 "class Bar;", 15239 SpaceAfterRequires); 15240 15241 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = false; 15242 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression = true; 15243 verifyFormat("void f(auto x)\n" 15244 " requires requires (int i) { x + i; }\n" 15245 "{}", 15246 SpaceAfterRequires); 15247 verifyFormat("void f(auto x)\n" 15248 " requires(requires (int i) { x + i; })\n" 15249 "{}", 15250 SpaceAfterRequires); 15251 verifyFormat("if (requires (int i) { x + i; })\n" 15252 " return;", 15253 SpaceAfterRequires); 15254 verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires); 15255 verifyFormat("template <typename T>\n" 15256 " requires(Foo<T>)\n" 15257 "class Bar;", 15258 SpaceAfterRequires); 15259 15260 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true; 15261 verifyFormat("void f(auto x)\n" 15262 " requires requires (int i) { x + i; }\n" 15263 "{}", 15264 SpaceAfterRequires); 15265 verifyFormat("void f(auto x)\n" 15266 " requires (requires (int i) { x + i; })\n" 15267 "{}", 15268 SpaceAfterRequires); 15269 verifyFormat("if (requires (int i) { x + i; })\n" 15270 " return;", 15271 SpaceAfterRequires); 15272 verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires); 15273 verifyFormat("template <typename T>\n" 15274 " requires (Foo<T>)\n" 15275 "class Bar;", 15276 SpaceAfterRequires); 15277 } 15278 15279 TEST_F(FormatTest, SpaceAfterLogicalNot) { 15280 FormatStyle Spaces = getLLVMStyle(); 15281 Spaces.SpaceAfterLogicalNot = true; 15282 15283 verifyFormat("bool x = ! y", Spaces); 15284 verifyFormat("if (! isFailure())", Spaces); 15285 verifyFormat("if (! (a && b))", Spaces); 15286 verifyFormat("\"Error!\"", Spaces); 15287 verifyFormat("! ! x", Spaces); 15288 } 15289 15290 TEST_F(FormatTest, ConfigurableSpacesInParentheses) { 15291 FormatStyle Spaces = getLLVMStyle(); 15292 15293 Spaces.SpacesInParentheses = true; 15294 verifyFormat("do_something( ::globalVar );", Spaces); 15295 verifyFormat("call( x, y, z );", Spaces); 15296 verifyFormat("call();", Spaces); 15297 verifyFormat("std::function<void( int, int )> callback;", Spaces); 15298 verifyFormat("void inFunction() { std::function<void( int, int )> fct; }", 15299 Spaces); 15300 verifyFormat("while ( (bool)1 )\n" 15301 " continue;", 15302 Spaces); 15303 verifyFormat("for ( ;; )\n" 15304 " continue;", 15305 Spaces); 15306 verifyFormat("if ( true )\n" 15307 " f();\n" 15308 "else if ( true )\n" 15309 " f();", 15310 Spaces); 15311 verifyFormat("do {\n" 15312 " do_something( (int)i );\n" 15313 "} while ( something() );", 15314 Spaces); 15315 verifyFormat("switch ( x ) {\n" 15316 "default:\n" 15317 " break;\n" 15318 "}", 15319 Spaces); 15320 15321 Spaces.SpacesInParentheses = false; 15322 Spaces.SpacesInCStyleCastParentheses = true; 15323 verifyFormat("Type *A = ( Type * )P;", Spaces); 15324 verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces); 15325 verifyFormat("x = ( int32 )y;", Spaces); 15326 verifyFormat("int a = ( int )(2.0f);", Spaces); 15327 verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces); 15328 verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces); 15329 verifyFormat("#define x (( int )-1)", Spaces); 15330 15331 // Run the first set of tests again with: 15332 Spaces.SpacesInParentheses = false; 15333 Spaces.SpaceInEmptyParentheses = true; 15334 Spaces.SpacesInCStyleCastParentheses = true; 15335 verifyFormat("call(x, y, z);", Spaces); 15336 verifyFormat("call( );", Spaces); 15337 verifyFormat("std::function<void(int, int)> callback;", Spaces); 15338 verifyFormat("while (( bool )1)\n" 15339 " continue;", 15340 Spaces); 15341 verifyFormat("for (;;)\n" 15342 " continue;", 15343 Spaces); 15344 verifyFormat("if (true)\n" 15345 " f( );\n" 15346 "else if (true)\n" 15347 " f( );", 15348 Spaces); 15349 verifyFormat("do {\n" 15350 " do_something(( int )i);\n" 15351 "} while (something( ));", 15352 Spaces); 15353 verifyFormat("switch (x) {\n" 15354 "default:\n" 15355 " break;\n" 15356 "}", 15357 Spaces); 15358 15359 // Run the first set of tests again with: 15360 Spaces.SpaceAfterCStyleCast = true; 15361 verifyFormat("call(x, y, z);", Spaces); 15362 verifyFormat("call( );", Spaces); 15363 verifyFormat("std::function<void(int, int)> callback;", Spaces); 15364 verifyFormat("while (( bool ) 1)\n" 15365 " continue;", 15366 Spaces); 15367 verifyFormat("for (;;)\n" 15368 " continue;", 15369 Spaces); 15370 verifyFormat("if (true)\n" 15371 " f( );\n" 15372 "else if (true)\n" 15373 " f( );", 15374 Spaces); 15375 verifyFormat("do {\n" 15376 " do_something(( int ) i);\n" 15377 "} while (something( ));", 15378 Spaces); 15379 verifyFormat("switch (x) {\n" 15380 "default:\n" 15381 " break;\n" 15382 "}", 15383 Spaces); 15384 verifyFormat("#define CONF_BOOL(x) ( bool * ) ( void * ) (x)", Spaces); 15385 verifyFormat("#define CONF_BOOL(x) ( bool * ) (x)", Spaces); 15386 verifyFormat("#define CONF_BOOL(x) ( bool ) (x)", Spaces); 15387 verifyFormat("bool *y = ( bool * ) ( void * ) (x);", Spaces); 15388 verifyFormat("bool *y = ( bool * ) (x);", Spaces); 15389 15390 // Run subset of tests again with: 15391 Spaces.SpacesInCStyleCastParentheses = false; 15392 Spaces.SpaceAfterCStyleCast = true; 15393 verifyFormat("while ((bool) 1)\n" 15394 " continue;", 15395 Spaces); 15396 verifyFormat("do {\n" 15397 " do_something((int) i);\n" 15398 "} while (something( ));", 15399 Spaces); 15400 15401 verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces); 15402 verifyFormat("size_t idx = (size_t) a;", Spaces); 15403 verifyFormat("size_t idx = (size_t) (a - 1);", Spaces); 15404 verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces); 15405 verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces); 15406 verifyFormat("size_t idx = (*foo)(a - 1);", Spaces); 15407 verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces); 15408 verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (x)", Spaces); 15409 verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (int) (x)", Spaces); 15410 verifyFormat("bool *y = (bool *) (void *) (x);", Spaces); 15411 verifyFormat("bool *y = (bool *) (void *) (int) (x);", Spaces); 15412 verifyFormat("bool *y = (bool *) (void *) (int) foo(x);", Spaces); 15413 Spaces.ColumnLimit = 80; 15414 Spaces.IndentWidth = 4; 15415 Spaces.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 15416 verifyFormat("void foo( ) {\n" 15417 " size_t foo = (*(function))(\n" 15418 " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, " 15419 "BarrrrrrrrrrrrLong,\n" 15420 " FoooooooooLooooong);\n" 15421 "}", 15422 Spaces); 15423 Spaces.SpaceAfterCStyleCast = false; 15424 verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces); 15425 verifyFormat("size_t idx = (size_t)a;", Spaces); 15426 verifyFormat("size_t idx = (size_t)(a - 1);", Spaces); 15427 verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces); 15428 verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces); 15429 verifyFormat("size_t idx = (*foo)(a - 1);", Spaces); 15430 verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces); 15431 15432 verifyFormat("void foo( ) {\n" 15433 " size_t foo = (*(function))(\n" 15434 " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, " 15435 "BarrrrrrrrrrrrLong,\n" 15436 " FoooooooooLooooong);\n" 15437 "}", 15438 Spaces); 15439 } 15440 15441 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) { 15442 verifyFormat("int a[5];"); 15443 verifyFormat("a[3] += 42;"); 15444 15445 FormatStyle Spaces = getLLVMStyle(); 15446 Spaces.SpacesInSquareBrackets = true; 15447 // Not lambdas. 15448 verifyFormat("int a[ 5 ];", Spaces); 15449 verifyFormat("a[ 3 ] += 42;", Spaces); 15450 verifyFormat("constexpr char hello[]{\"hello\"};", Spaces); 15451 verifyFormat("double &operator[](int i) { return 0; }\n" 15452 "int i;", 15453 Spaces); 15454 verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces); 15455 verifyFormat("int i = a[ a ][ a ]->f();", Spaces); 15456 verifyFormat("int i = (*b)[ a ]->f();", Spaces); 15457 // Lambdas. 15458 verifyFormat("int c = []() -> int { return 2; }();\n", Spaces); 15459 verifyFormat("return [ i, args... ] {};", Spaces); 15460 verifyFormat("int foo = [ &bar ]() {};", Spaces); 15461 verifyFormat("int foo = [ = ]() {};", Spaces); 15462 verifyFormat("int foo = [ & ]() {};", Spaces); 15463 verifyFormat("int foo = [ =, &bar ]() {};", Spaces); 15464 verifyFormat("int foo = [ &bar, = ]() {};", Spaces); 15465 } 15466 15467 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) { 15468 FormatStyle NoSpaceStyle = getLLVMStyle(); 15469 verifyFormat("int a[5];", NoSpaceStyle); 15470 verifyFormat("a[3] += 42;", NoSpaceStyle); 15471 15472 verifyFormat("int a[1];", NoSpaceStyle); 15473 verifyFormat("int 1 [a];", NoSpaceStyle); 15474 verifyFormat("int a[1][2];", NoSpaceStyle); 15475 verifyFormat("a[7] = 5;", NoSpaceStyle); 15476 verifyFormat("int a = (f())[23];", NoSpaceStyle); 15477 verifyFormat("f([] {})", NoSpaceStyle); 15478 15479 FormatStyle Space = getLLVMStyle(); 15480 Space.SpaceBeforeSquareBrackets = true; 15481 verifyFormat("int c = []() -> int { return 2; }();\n", Space); 15482 verifyFormat("return [i, args...] {};", Space); 15483 15484 verifyFormat("int a [5];", Space); 15485 verifyFormat("a [3] += 42;", Space); 15486 verifyFormat("constexpr char hello []{\"hello\"};", Space); 15487 verifyFormat("double &operator[](int i) { return 0; }\n" 15488 "int i;", 15489 Space); 15490 verifyFormat("std::unique_ptr<int []> foo() {}", Space); 15491 verifyFormat("int i = a [a][a]->f();", Space); 15492 verifyFormat("int i = (*b) [a]->f();", Space); 15493 15494 verifyFormat("int a [1];", Space); 15495 verifyFormat("int 1 [a];", Space); 15496 verifyFormat("int a [1][2];", Space); 15497 verifyFormat("a [7] = 5;", Space); 15498 verifyFormat("int a = (f()) [23];", Space); 15499 verifyFormat("f([] {})", Space); 15500 } 15501 15502 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) { 15503 verifyFormat("int a = 5;"); 15504 verifyFormat("a += 42;"); 15505 verifyFormat("a or_eq 8;"); 15506 15507 FormatStyle Spaces = getLLVMStyle(); 15508 Spaces.SpaceBeforeAssignmentOperators = false; 15509 verifyFormat("int a= 5;", Spaces); 15510 verifyFormat("a+= 42;", Spaces); 15511 verifyFormat("a or_eq 8;", Spaces); 15512 } 15513 15514 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) { 15515 verifyFormat("class Foo : public Bar {};"); 15516 verifyFormat("Foo::Foo() : foo(1) {}"); 15517 verifyFormat("for (auto a : b) {\n}"); 15518 verifyFormat("int x = a ? b : c;"); 15519 verifyFormat("{\n" 15520 "label0:\n" 15521 " int x = 0;\n" 15522 "}"); 15523 verifyFormat("switch (x) {\n" 15524 "case 1:\n" 15525 "default:\n" 15526 "}"); 15527 verifyFormat("switch (allBraces) {\n" 15528 "case 1: {\n" 15529 " break;\n" 15530 "}\n" 15531 "case 2: {\n" 15532 " [[fallthrough]];\n" 15533 "}\n" 15534 "default: {\n" 15535 " break;\n" 15536 "}\n" 15537 "}"); 15538 15539 FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30); 15540 CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false; 15541 verifyFormat("class Foo : public Bar {};", CtorInitializerStyle); 15542 verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle); 15543 verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle); 15544 verifyFormat("int x = a ? b : c;", CtorInitializerStyle); 15545 verifyFormat("{\n" 15546 "label1:\n" 15547 " int x = 0;\n" 15548 "}", 15549 CtorInitializerStyle); 15550 verifyFormat("switch (x) {\n" 15551 "case 1:\n" 15552 "default:\n" 15553 "}", 15554 CtorInitializerStyle); 15555 verifyFormat("switch (allBraces) {\n" 15556 "case 1: {\n" 15557 " break;\n" 15558 "}\n" 15559 "case 2: {\n" 15560 " [[fallthrough]];\n" 15561 "}\n" 15562 "default: {\n" 15563 " break;\n" 15564 "}\n" 15565 "}", 15566 CtorInitializerStyle); 15567 CtorInitializerStyle.BreakConstructorInitializers = 15568 FormatStyle::BCIS_AfterColon; 15569 verifyFormat("Fooooooooooo::Fooooooooooo():\n" 15570 " aaaaaaaaaaaaaaaa(1),\n" 15571 " bbbbbbbbbbbbbbbb(2) {}", 15572 CtorInitializerStyle); 15573 CtorInitializerStyle.BreakConstructorInitializers = 15574 FormatStyle::BCIS_BeforeComma; 15575 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15576 " : aaaaaaaaaaaaaaaa(1)\n" 15577 " , bbbbbbbbbbbbbbbb(2) {}", 15578 CtorInitializerStyle); 15579 CtorInitializerStyle.BreakConstructorInitializers = 15580 FormatStyle::BCIS_BeforeColon; 15581 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15582 " : aaaaaaaaaaaaaaaa(1),\n" 15583 " bbbbbbbbbbbbbbbb(2) {}", 15584 CtorInitializerStyle); 15585 CtorInitializerStyle.ConstructorInitializerIndentWidth = 0; 15586 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15587 ": aaaaaaaaaaaaaaaa(1),\n" 15588 " bbbbbbbbbbbbbbbb(2) {}", 15589 CtorInitializerStyle); 15590 15591 FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30); 15592 InheritanceStyle.SpaceBeforeInheritanceColon = false; 15593 verifyFormat("class Foo: public Bar {};", InheritanceStyle); 15594 verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle); 15595 verifyFormat("for (auto a : b) {\n}", InheritanceStyle); 15596 verifyFormat("int x = a ? b : c;", InheritanceStyle); 15597 verifyFormat("{\n" 15598 "label2:\n" 15599 " int x = 0;\n" 15600 "}", 15601 InheritanceStyle); 15602 verifyFormat("switch (x) {\n" 15603 "case 1:\n" 15604 "default:\n" 15605 "}", 15606 InheritanceStyle); 15607 verifyFormat("switch (allBraces) {\n" 15608 "case 1: {\n" 15609 " break;\n" 15610 "}\n" 15611 "case 2: {\n" 15612 " [[fallthrough]];\n" 15613 "}\n" 15614 "default: {\n" 15615 " break;\n" 15616 "}\n" 15617 "}", 15618 InheritanceStyle); 15619 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterComma; 15620 verifyFormat("class Foooooooooooooooooooooo\n" 15621 " : public aaaaaaaaaaaaaaaaaa,\n" 15622 " public bbbbbbbbbbbbbbbbbb {\n" 15623 "}", 15624 InheritanceStyle); 15625 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon; 15626 verifyFormat("class Foooooooooooooooooooooo:\n" 15627 " public aaaaaaaaaaaaaaaaaa,\n" 15628 " public bbbbbbbbbbbbbbbbbb {\n" 15629 "}", 15630 InheritanceStyle); 15631 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma; 15632 verifyFormat("class Foooooooooooooooooooooo\n" 15633 " : public aaaaaaaaaaaaaaaaaa\n" 15634 " , public bbbbbbbbbbbbbbbbbb {\n" 15635 "}", 15636 InheritanceStyle); 15637 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 15638 verifyFormat("class Foooooooooooooooooooooo\n" 15639 " : public aaaaaaaaaaaaaaaaaa,\n" 15640 " public bbbbbbbbbbbbbbbbbb {\n" 15641 "}", 15642 InheritanceStyle); 15643 InheritanceStyle.ConstructorInitializerIndentWidth = 0; 15644 verifyFormat("class Foooooooooooooooooooooo\n" 15645 ": public aaaaaaaaaaaaaaaaaa,\n" 15646 " public bbbbbbbbbbbbbbbbbb {}", 15647 InheritanceStyle); 15648 15649 FormatStyle ForLoopStyle = getLLVMStyle(); 15650 ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false; 15651 verifyFormat("class Foo : public Bar {};", ForLoopStyle); 15652 verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle); 15653 verifyFormat("for (auto a: b) {\n}", ForLoopStyle); 15654 verifyFormat("int x = a ? b : c;", ForLoopStyle); 15655 verifyFormat("{\n" 15656 "label2:\n" 15657 " int x = 0;\n" 15658 "}", 15659 ForLoopStyle); 15660 verifyFormat("switch (x) {\n" 15661 "case 1:\n" 15662 "default:\n" 15663 "}", 15664 ForLoopStyle); 15665 verifyFormat("switch (allBraces) {\n" 15666 "case 1: {\n" 15667 " break;\n" 15668 "}\n" 15669 "case 2: {\n" 15670 " [[fallthrough]];\n" 15671 "}\n" 15672 "default: {\n" 15673 " break;\n" 15674 "}\n" 15675 "}", 15676 ForLoopStyle); 15677 15678 FormatStyle CaseStyle = getLLVMStyle(); 15679 CaseStyle.SpaceBeforeCaseColon = true; 15680 verifyFormat("class Foo : public Bar {};", CaseStyle); 15681 verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle); 15682 verifyFormat("for (auto a : b) {\n}", CaseStyle); 15683 verifyFormat("int x = a ? b : c;", CaseStyle); 15684 verifyFormat("switch (x) {\n" 15685 "case 1 :\n" 15686 "default :\n" 15687 "}", 15688 CaseStyle); 15689 verifyFormat("switch (allBraces) {\n" 15690 "case 1 : {\n" 15691 " break;\n" 15692 "}\n" 15693 "case 2 : {\n" 15694 " [[fallthrough]];\n" 15695 "}\n" 15696 "default : {\n" 15697 " break;\n" 15698 "}\n" 15699 "}", 15700 CaseStyle); 15701 15702 FormatStyle NoSpaceStyle = getLLVMStyle(); 15703 EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false); 15704 NoSpaceStyle.SpaceBeforeCtorInitializerColon = false; 15705 NoSpaceStyle.SpaceBeforeInheritanceColon = false; 15706 NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false; 15707 verifyFormat("class Foo: public Bar {};", NoSpaceStyle); 15708 verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle); 15709 verifyFormat("for (auto a: b) {\n}", NoSpaceStyle); 15710 verifyFormat("int x = a ? b : c;", NoSpaceStyle); 15711 verifyFormat("{\n" 15712 "label3:\n" 15713 " int x = 0;\n" 15714 "}", 15715 NoSpaceStyle); 15716 verifyFormat("switch (x) {\n" 15717 "case 1:\n" 15718 "default:\n" 15719 "}", 15720 NoSpaceStyle); 15721 verifyFormat("switch (allBraces) {\n" 15722 "case 1: {\n" 15723 " break;\n" 15724 "}\n" 15725 "case 2: {\n" 15726 " [[fallthrough]];\n" 15727 "}\n" 15728 "default: {\n" 15729 " break;\n" 15730 "}\n" 15731 "}", 15732 NoSpaceStyle); 15733 15734 FormatStyle InvertedSpaceStyle = getLLVMStyle(); 15735 InvertedSpaceStyle.SpaceBeforeCaseColon = true; 15736 InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false; 15737 InvertedSpaceStyle.SpaceBeforeInheritanceColon = false; 15738 InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false; 15739 verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle); 15740 verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle); 15741 verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle); 15742 verifyFormat("int x = a ? b : c;", InvertedSpaceStyle); 15743 verifyFormat("{\n" 15744 "label3:\n" 15745 " int x = 0;\n" 15746 "}", 15747 InvertedSpaceStyle); 15748 verifyFormat("switch (x) {\n" 15749 "case 1 :\n" 15750 "case 2 : {\n" 15751 " break;\n" 15752 "}\n" 15753 "default :\n" 15754 " break;\n" 15755 "}", 15756 InvertedSpaceStyle); 15757 verifyFormat("switch (allBraces) {\n" 15758 "case 1 : {\n" 15759 " break;\n" 15760 "}\n" 15761 "case 2 : {\n" 15762 " [[fallthrough]];\n" 15763 "}\n" 15764 "default : {\n" 15765 " break;\n" 15766 "}\n" 15767 "}", 15768 InvertedSpaceStyle); 15769 } 15770 15771 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) { 15772 FormatStyle Style = getLLVMStyle(); 15773 15774 Style.PointerAlignment = FormatStyle::PAS_Left; 15775 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default; 15776 verifyFormat("void* const* x = NULL;", Style); 15777 15778 #define verifyQualifierSpaces(Code, Pointers, Qualifiers) \ 15779 do { \ 15780 Style.PointerAlignment = FormatStyle::Pointers; \ 15781 Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers; \ 15782 verifyFormat(Code, Style); \ 15783 } while (false) 15784 15785 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default); 15786 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default); 15787 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default); 15788 15789 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before); 15790 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before); 15791 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before); 15792 15793 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After); 15794 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After); 15795 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After); 15796 15797 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both); 15798 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both); 15799 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both); 15800 15801 verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default); 15802 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, 15803 SAPQ_Default); 15804 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15805 SAPQ_Default); 15806 15807 verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before); 15808 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, 15809 SAPQ_Before); 15810 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15811 SAPQ_Before); 15812 15813 verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After); 15814 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After); 15815 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15816 SAPQ_After); 15817 15818 verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both); 15819 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both); 15820 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both); 15821 15822 #undef verifyQualifierSpaces 15823 15824 FormatStyle Spaces = getLLVMStyle(); 15825 Spaces.AttributeMacros.push_back("qualified"); 15826 Spaces.PointerAlignment = FormatStyle::PAS_Right; 15827 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default; 15828 verifyFormat("SomeType *volatile *a = NULL;", Spaces); 15829 verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces); 15830 verifyFormat("std::vector<SomeType *const *> x;", Spaces); 15831 verifyFormat("std::vector<SomeType *qualified *> x;", Spaces); 15832 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15833 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before; 15834 verifyFormat("SomeType * volatile *a = NULL;", Spaces); 15835 verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces); 15836 verifyFormat("std::vector<SomeType * const *> x;", Spaces); 15837 verifyFormat("std::vector<SomeType * qualified *> x;", Spaces); 15838 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15839 15840 // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left. 15841 Spaces.PointerAlignment = FormatStyle::PAS_Left; 15842 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before; 15843 verifyFormat("SomeType* volatile* a = NULL;", Spaces); 15844 verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces); 15845 verifyFormat("std::vector<SomeType* const*> x;", Spaces); 15846 verifyFormat("std::vector<SomeType* qualified*> x;", Spaces); 15847 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15848 // However, setting it to SAPQ_After should add spaces after __attribute, etc. 15849 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After; 15850 verifyFormat("SomeType* volatile * a = NULL;", Spaces); 15851 verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces); 15852 verifyFormat("std::vector<SomeType* const *> x;", Spaces); 15853 verifyFormat("std::vector<SomeType* qualified *> x;", Spaces); 15854 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15855 15856 // PAS_Middle should not have any noticeable changes even for SAPQ_Both 15857 Spaces.PointerAlignment = FormatStyle::PAS_Middle; 15858 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After; 15859 verifyFormat("SomeType * volatile * a = NULL;", Spaces); 15860 verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces); 15861 verifyFormat("std::vector<SomeType * const *> x;", Spaces); 15862 verifyFormat("std::vector<SomeType * qualified *> x;", Spaces); 15863 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15864 } 15865 15866 TEST_F(FormatTest, AlignConsecutiveMacros) { 15867 FormatStyle Style = getLLVMStyle(); 15868 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 15869 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 15870 Style.AlignConsecutiveMacros = FormatStyle::ACS_None; 15871 15872 verifyFormat("#define a 3\n" 15873 "#define bbbb 4\n" 15874 "#define ccc (5)", 15875 Style); 15876 15877 verifyFormat("#define f(x) (x * x)\n" 15878 "#define fff(x, y, z) (x * y + z)\n" 15879 "#define ffff(x, y) (x - y)", 15880 Style); 15881 15882 verifyFormat("#define foo(x, y) (x + y)\n" 15883 "#define bar (5, 6)(2 + 2)", 15884 Style); 15885 15886 verifyFormat("#define a 3\n" 15887 "#define bbbb 4\n" 15888 "#define ccc (5)\n" 15889 "#define f(x) (x * x)\n" 15890 "#define fff(x, y, z) (x * y + z)\n" 15891 "#define ffff(x, y) (x - y)", 15892 Style); 15893 15894 Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 15895 verifyFormat("#define a 3\n" 15896 "#define bbbb 4\n" 15897 "#define ccc (5)", 15898 Style); 15899 15900 verifyFormat("#define f(x) (x * x)\n" 15901 "#define fff(x, y, z) (x * y + z)\n" 15902 "#define ffff(x, y) (x - y)", 15903 Style); 15904 15905 verifyFormat("#define foo(x, y) (x + y)\n" 15906 "#define bar (5, 6)(2 + 2)", 15907 Style); 15908 15909 verifyFormat("#define a 3\n" 15910 "#define bbbb 4\n" 15911 "#define ccc (5)\n" 15912 "#define f(x) (x * x)\n" 15913 "#define fff(x, y, z) (x * y + z)\n" 15914 "#define ffff(x, y) (x - y)", 15915 Style); 15916 15917 verifyFormat("#define a 5\n" 15918 "#define foo(x, y) (x + y)\n" 15919 "#define CCC (6)\n" 15920 "auto lambda = []() {\n" 15921 " auto ii = 0;\n" 15922 " float j = 0;\n" 15923 " return 0;\n" 15924 "};\n" 15925 "int i = 0;\n" 15926 "float i2 = 0;\n" 15927 "auto v = type{\n" 15928 " i = 1, //\n" 15929 " (i = 2), //\n" 15930 " i = 3 //\n" 15931 "};", 15932 Style); 15933 15934 Style.AlignConsecutiveMacros = FormatStyle::ACS_None; 15935 Style.ColumnLimit = 20; 15936 15937 verifyFormat("#define a \\\n" 15938 " \"aabbbbbbbbbbbb\"\n" 15939 "#define D \\\n" 15940 " \"aabbbbbbbbbbbb\" \\\n" 15941 " \"ccddeeeeeeeee\"\n" 15942 "#define B \\\n" 15943 " \"QQQQQQQQQQQQQ\" \\\n" 15944 " \"FFFFFFFFFFFFF\" \\\n" 15945 " \"LLLLLLLL\"\n", 15946 Style); 15947 15948 Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 15949 verifyFormat("#define a \\\n" 15950 " \"aabbbbbbbbbbbb\"\n" 15951 "#define D \\\n" 15952 " \"aabbbbbbbbbbbb\" \\\n" 15953 " \"ccddeeeeeeeee\"\n" 15954 "#define B \\\n" 15955 " \"QQQQQQQQQQQQQ\" \\\n" 15956 " \"FFFFFFFFFFFFF\" \\\n" 15957 " \"LLLLLLLL\"\n", 15958 Style); 15959 15960 // Test across comments 15961 Style.MaxEmptyLinesToKeep = 10; 15962 Style.ReflowComments = false; 15963 Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossComments; 15964 EXPECT_EQ("#define a 3\n" 15965 "// line comment\n" 15966 "#define bbbb 4\n" 15967 "#define ccc (5)", 15968 format("#define a 3\n" 15969 "// line comment\n" 15970 "#define bbbb 4\n" 15971 "#define ccc (5)", 15972 Style)); 15973 15974 EXPECT_EQ("#define a 3\n" 15975 "/* block comment */\n" 15976 "#define bbbb 4\n" 15977 "#define ccc (5)", 15978 format("#define a 3\n" 15979 "/* block comment */\n" 15980 "#define bbbb 4\n" 15981 "#define ccc (5)", 15982 Style)); 15983 15984 EXPECT_EQ("#define a 3\n" 15985 "/* multi-line *\n" 15986 " * block comment */\n" 15987 "#define bbbb 4\n" 15988 "#define ccc (5)", 15989 format("#define a 3\n" 15990 "/* multi-line *\n" 15991 " * block comment */\n" 15992 "#define bbbb 4\n" 15993 "#define ccc (5)", 15994 Style)); 15995 15996 EXPECT_EQ("#define a 3\n" 15997 "// multi-line line comment\n" 15998 "//\n" 15999 "#define bbbb 4\n" 16000 "#define ccc (5)", 16001 format("#define a 3\n" 16002 "// multi-line line comment\n" 16003 "//\n" 16004 "#define bbbb 4\n" 16005 "#define ccc (5)", 16006 Style)); 16007 16008 EXPECT_EQ("#define a 3\n" 16009 "// empty lines still break.\n" 16010 "\n" 16011 "#define bbbb 4\n" 16012 "#define ccc (5)", 16013 format("#define a 3\n" 16014 "// empty lines still break.\n" 16015 "\n" 16016 "#define bbbb 4\n" 16017 "#define ccc (5)", 16018 Style)); 16019 16020 // Test across empty lines 16021 Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLines; 16022 EXPECT_EQ("#define a 3\n" 16023 "\n" 16024 "#define bbbb 4\n" 16025 "#define ccc (5)", 16026 format("#define a 3\n" 16027 "\n" 16028 "#define bbbb 4\n" 16029 "#define ccc (5)", 16030 Style)); 16031 16032 EXPECT_EQ("#define a 3\n" 16033 "\n" 16034 "\n" 16035 "\n" 16036 "#define bbbb 4\n" 16037 "#define ccc (5)", 16038 format("#define a 3\n" 16039 "\n" 16040 "\n" 16041 "\n" 16042 "#define bbbb 4\n" 16043 "#define ccc (5)", 16044 Style)); 16045 16046 EXPECT_EQ("#define a 3\n" 16047 "// comments should break alignment\n" 16048 "//\n" 16049 "#define bbbb 4\n" 16050 "#define ccc (5)", 16051 format("#define a 3\n" 16052 "// comments should break alignment\n" 16053 "//\n" 16054 "#define bbbb 4\n" 16055 "#define ccc (5)", 16056 Style)); 16057 16058 // Test across empty lines and comments 16059 Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLinesAndComments; 16060 verifyFormat("#define a 3\n" 16061 "\n" 16062 "// line comment\n" 16063 "#define bbbb 4\n" 16064 "#define ccc (5)", 16065 Style); 16066 16067 EXPECT_EQ("#define a 3\n" 16068 "\n" 16069 "\n" 16070 "/* multi-line *\n" 16071 " * block comment */\n" 16072 "\n" 16073 "\n" 16074 "#define bbbb 4\n" 16075 "#define ccc (5)", 16076 format("#define a 3\n" 16077 "\n" 16078 "\n" 16079 "/* multi-line *\n" 16080 " * block comment */\n" 16081 "\n" 16082 "\n" 16083 "#define bbbb 4\n" 16084 "#define ccc (5)", 16085 Style)); 16086 16087 EXPECT_EQ("#define a 3\n" 16088 "\n" 16089 "\n" 16090 "/* multi-line *\n" 16091 " * block comment */\n" 16092 "\n" 16093 "\n" 16094 "#define bbbb 4\n" 16095 "#define ccc (5)", 16096 format("#define a 3\n" 16097 "\n" 16098 "\n" 16099 "/* multi-line *\n" 16100 " * block comment */\n" 16101 "\n" 16102 "\n" 16103 "#define bbbb 4\n" 16104 "#define ccc (5)", 16105 Style)); 16106 } 16107 16108 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) { 16109 FormatStyle Alignment = getLLVMStyle(); 16110 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 16111 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossEmptyLines; 16112 16113 Alignment.MaxEmptyLinesToKeep = 10; 16114 /* Test alignment across empty lines */ 16115 EXPECT_EQ("int a = 5;\n" 16116 "\n" 16117 "int oneTwoThree = 123;", 16118 format("int a = 5;\n" 16119 "\n" 16120 "int oneTwoThree= 123;", 16121 Alignment)); 16122 EXPECT_EQ("int a = 5;\n" 16123 "int one = 1;\n" 16124 "\n" 16125 "int oneTwoThree = 123;", 16126 format("int a = 5;\n" 16127 "int one = 1;\n" 16128 "\n" 16129 "int oneTwoThree = 123;", 16130 Alignment)); 16131 EXPECT_EQ("int a = 5;\n" 16132 "int one = 1;\n" 16133 "\n" 16134 "int oneTwoThree = 123;\n" 16135 "int oneTwo = 12;", 16136 format("int a = 5;\n" 16137 "int one = 1;\n" 16138 "\n" 16139 "int oneTwoThree = 123;\n" 16140 "int oneTwo = 12;", 16141 Alignment)); 16142 16143 /* Test across comments */ 16144 EXPECT_EQ("int a = 5;\n" 16145 "/* block comment */\n" 16146 "int oneTwoThree = 123;", 16147 format("int a = 5;\n" 16148 "/* block comment */\n" 16149 "int oneTwoThree=123;", 16150 Alignment)); 16151 16152 EXPECT_EQ("int a = 5;\n" 16153 "// line comment\n" 16154 "int oneTwoThree = 123;", 16155 format("int a = 5;\n" 16156 "// line comment\n" 16157 "int oneTwoThree=123;", 16158 Alignment)); 16159 16160 /* Test across comments and newlines */ 16161 EXPECT_EQ("int a = 5;\n" 16162 "\n" 16163 "/* block comment */\n" 16164 "int oneTwoThree = 123;", 16165 format("int a = 5;\n" 16166 "\n" 16167 "/* block comment */\n" 16168 "int oneTwoThree=123;", 16169 Alignment)); 16170 16171 EXPECT_EQ("int a = 5;\n" 16172 "\n" 16173 "// line comment\n" 16174 "int oneTwoThree = 123;", 16175 format("int a = 5;\n" 16176 "\n" 16177 "// line comment\n" 16178 "int oneTwoThree=123;", 16179 Alignment)); 16180 } 16181 16182 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) { 16183 FormatStyle Alignment = getLLVMStyle(); 16184 Alignment.AlignConsecutiveDeclarations = 16185 FormatStyle::ACS_AcrossEmptyLinesAndComments; 16186 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 16187 16188 Alignment.MaxEmptyLinesToKeep = 10; 16189 /* Test alignment across empty lines */ 16190 EXPECT_EQ("int a = 5;\n" 16191 "\n" 16192 "float const oneTwoThree = 123;", 16193 format("int a = 5;\n" 16194 "\n" 16195 "float const oneTwoThree = 123;", 16196 Alignment)); 16197 EXPECT_EQ("int a = 5;\n" 16198 "float const one = 1;\n" 16199 "\n" 16200 "int oneTwoThree = 123;", 16201 format("int a = 5;\n" 16202 "float const one = 1;\n" 16203 "\n" 16204 "int oneTwoThree = 123;", 16205 Alignment)); 16206 16207 /* Test across comments */ 16208 EXPECT_EQ("float const a = 5;\n" 16209 "/* block comment */\n" 16210 "int oneTwoThree = 123;", 16211 format("float const a = 5;\n" 16212 "/* block comment */\n" 16213 "int oneTwoThree=123;", 16214 Alignment)); 16215 16216 EXPECT_EQ("float const a = 5;\n" 16217 "// line comment\n" 16218 "int oneTwoThree = 123;", 16219 format("float const a = 5;\n" 16220 "// line comment\n" 16221 "int oneTwoThree=123;", 16222 Alignment)); 16223 16224 /* Test across comments and newlines */ 16225 EXPECT_EQ("float const a = 5;\n" 16226 "\n" 16227 "/* block comment */\n" 16228 "int oneTwoThree = 123;", 16229 format("float const a = 5;\n" 16230 "\n" 16231 "/* block comment */\n" 16232 "int oneTwoThree=123;", 16233 Alignment)); 16234 16235 EXPECT_EQ("float const a = 5;\n" 16236 "\n" 16237 "// line comment\n" 16238 "int oneTwoThree = 123;", 16239 format("float const a = 5;\n" 16240 "\n" 16241 "// line comment\n" 16242 "int oneTwoThree=123;", 16243 Alignment)); 16244 } 16245 16246 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) { 16247 FormatStyle Alignment = getLLVMStyle(); 16248 Alignment.AlignConsecutiveBitFields = 16249 FormatStyle::ACS_AcrossEmptyLinesAndComments; 16250 16251 Alignment.MaxEmptyLinesToKeep = 10; 16252 /* Test alignment across empty lines */ 16253 EXPECT_EQ("int a : 5;\n" 16254 "\n" 16255 "int longbitfield : 6;", 16256 format("int a : 5;\n" 16257 "\n" 16258 "int longbitfield : 6;", 16259 Alignment)); 16260 EXPECT_EQ("int a : 5;\n" 16261 "int one : 1;\n" 16262 "\n" 16263 "int longbitfield : 6;", 16264 format("int a : 5;\n" 16265 "int one : 1;\n" 16266 "\n" 16267 "int longbitfield : 6;", 16268 Alignment)); 16269 16270 /* Test across comments */ 16271 EXPECT_EQ("int a : 5;\n" 16272 "/* block comment */\n" 16273 "int longbitfield : 6;", 16274 format("int a : 5;\n" 16275 "/* block comment */\n" 16276 "int longbitfield : 6;", 16277 Alignment)); 16278 EXPECT_EQ("int a : 5;\n" 16279 "int one : 1;\n" 16280 "// line comment\n" 16281 "int longbitfield : 6;", 16282 format("int a : 5;\n" 16283 "int one : 1;\n" 16284 "// line comment\n" 16285 "int longbitfield : 6;", 16286 Alignment)); 16287 16288 /* Test across comments and newlines */ 16289 EXPECT_EQ("int a : 5;\n" 16290 "/* block comment */\n" 16291 "\n" 16292 "int longbitfield : 6;", 16293 format("int a : 5;\n" 16294 "/* block comment */\n" 16295 "\n" 16296 "int longbitfield : 6;", 16297 Alignment)); 16298 EXPECT_EQ("int a : 5;\n" 16299 "int one : 1;\n" 16300 "\n" 16301 "// line comment\n" 16302 "\n" 16303 "int longbitfield : 6;", 16304 format("int a : 5;\n" 16305 "int one : 1;\n" 16306 "\n" 16307 "// line comment \n" 16308 "\n" 16309 "int longbitfield : 6;", 16310 Alignment)); 16311 } 16312 16313 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) { 16314 FormatStyle Alignment = getLLVMStyle(); 16315 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 16316 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossComments; 16317 16318 Alignment.MaxEmptyLinesToKeep = 10; 16319 /* Test alignment across empty lines */ 16320 EXPECT_EQ("int a = 5;\n" 16321 "\n" 16322 "int oneTwoThree = 123;", 16323 format("int a = 5;\n" 16324 "\n" 16325 "int oneTwoThree= 123;", 16326 Alignment)); 16327 EXPECT_EQ("int a = 5;\n" 16328 "int one = 1;\n" 16329 "\n" 16330 "int oneTwoThree = 123;", 16331 format("int a = 5;\n" 16332 "int one = 1;\n" 16333 "\n" 16334 "int oneTwoThree = 123;", 16335 Alignment)); 16336 16337 /* Test across comments */ 16338 EXPECT_EQ("int a = 5;\n" 16339 "/* block comment */\n" 16340 "int oneTwoThree = 123;", 16341 format("int a = 5;\n" 16342 "/* block comment */\n" 16343 "int oneTwoThree=123;", 16344 Alignment)); 16345 16346 EXPECT_EQ("int a = 5;\n" 16347 "// line comment\n" 16348 "int oneTwoThree = 123;", 16349 format("int a = 5;\n" 16350 "// line comment\n" 16351 "int oneTwoThree=123;", 16352 Alignment)); 16353 16354 EXPECT_EQ("int a = 5;\n" 16355 "/*\n" 16356 " * multi-line block comment\n" 16357 " */\n" 16358 "int oneTwoThree = 123;", 16359 format("int a = 5;\n" 16360 "/*\n" 16361 " * multi-line block comment\n" 16362 " */\n" 16363 "int oneTwoThree=123;", 16364 Alignment)); 16365 16366 EXPECT_EQ("int a = 5;\n" 16367 "//\n" 16368 "// multi-line line comment\n" 16369 "//\n" 16370 "int oneTwoThree = 123;", 16371 format("int a = 5;\n" 16372 "//\n" 16373 "// multi-line line comment\n" 16374 "//\n" 16375 "int oneTwoThree=123;", 16376 Alignment)); 16377 16378 /* Test across comments and newlines */ 16379 EXPECT_EQ("int a = 5;\n" 16380 "\n" 16381 "/* block comment */\n" 16382 "int oneTwoThree = 123;", 16383 format("int a = 5;\n" 16384 "\n" 16385 "/* block comment */\n" 16386 "int oneTwoThree=123;", 16387 Alignment)); 16388 16389 EXPECT_EQ("int a = 5;\n" 16390 "\n" 16391 "// line comment\n" 16392 "int oneTwoThree = 123;", 16393 format("int a = 5;\n" 16394 "\n" 16395 "// line comment\n" 16396 "int oneTwoThree=123;", 16397 Alignment)); 16398 } 16399 16400 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) { 16401 FormatStyle Alignment = getLLVMStyle(); 16402 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 16403 Alignment.AlignConsecutiveAssignments = 16404 FormatStyle::ACS_AcrossEmptyLinesAndComments; 16405 verifyFormat("int a = 5;\n" 16406 "int oneTwoThree = 123;", 16407 Alignment); 16408 verifyFormat("int a = method();\n" 16409 "int oneTwoThree = 133;", 16410 Alignment); 16411 verifyFormat("a &= 5;\n" 16412 "bcd *= 5;\n" 16413 "ghtyf += 5;\n" 16414 "dvfvdb -= 5;\n" 16415 "a /= 5;\n" 16416 "vdsvsv %= 5;\n" 16417 "sfdbddfbdfbb ^= 5;\n" 16418 "dvsdsv |= 5;\n" 16419 "int dsvvdvsdvvv = 123;", 16420 Alignment); 16421 verifyFormat("int i = 1, j = 10;\n" 16422 "something = 2000;", 16423 Alignment); 16424 verifyFormat("something = 2000;\n" 16425 "int i = 1, j = 10;\n", 16426 Alignment); 16427 verifyFormat("something = 2000;\n" 16428 "another = 911;\n" 16429 "int i = 1, j = 10;\n" 16430 "oneMore = 1;\n" 16431 "i = 2;", 16432 Alignment); 16433 verifyFormat("int a = 5;\n" 16434 "int one = 1;\n" 16435 "method();\n" 16436 "int oneTwoThree = 123;\n" 16437 "int oneTwo = 12;", 16438 Alignment); 16439 verifyFormat("int oneTwoThree = 123;\n" 16440 "int oneTwo = 12;\n" 16441 "method();\n", 16442 Alignment); 16443 verifyFormat("int oneTwoThree = 123; // comment\n" 16444 "int oneTwo = 12; // comment", 16445 Alignment); 16446 16447 // Bug 25167 16448 /* Uncomment when fixed 16449 verifyFormat("#if A\n" 16450 "#else\n" 16451 "int aaaaaaaa = 12;\n" 16452 "#endif\n" 16453 "#if B\n" 16454 "#else\n" 16455 "int a = 12;\n" 16456 "#endif\n", 16457 Alignment); 16458 verifyFormat("enum foo {\n" 16459 "#if A\n" 16460 "#else\n" 16461 " aaaaaaaa = 12;\n" 16462 "#endif\n" 16463 "#if B\n" 16464 "#else\n" 16465 " a = 12;\n" 16466 "#endif\n" 16467 "};\n", 16468 Alignment); 16469 */ 16470 16471 Alignment.MaxEmptyLinesToKeep = 10; 16472 /* Test alignment across empty lines */ 16473 EXPECT_EQ("int a = 5;\n" 16474 "\n" 16475 "int oneTwoThree = 123;", 16476 format("int a = 5;\n" 16477 "\n" 16478 "int oneTwoThree= 123;", 16479 Alignment)); 16480 EXPECT_EQ("int a = 5;\n" 16481 "int one = 1;\n" 16482 "\n" 16483 "int oneTwoThree = 123;", 16484 format("int a = 5;\n" 16485 "int one = 1;\n" 16486 "\n" 16487 "int oneTwoThree = 123;", 16488 Alignment)); 16489 EXPECT_EQ("int a = 5;\n" 16490 "int one = 1;\n" 16491 "\n" 16492 "int oneTwoThree = 123;\n" 16493 "int oneTwo = 12;", 16494 format("int a = 5;\n" 16495 "int one = 1;\n" 16496 "\n" 16497 "int oneTwoThree = 123;\n" 16498 "int oneTwo = 12;", 16499 Alignment)); 16500 16501 /* Test across comments */ 16502 EXPECT_EQ("int a = 5;\n" 16503 "/* block comment */\n" 16504 "int oneTwoThree = 123;", 16505 format("int a = 5;\n" 16506 "/* block comment */\n" 16507 "int oneTwoThree=123;", 16508 Alignment)); 16509 16510 EXPECT_EQ("int a = 5;\n" 16511 "// line comment\n" 16512 "int oneTwoThree = 123;", 16513 format("int a = 5;\n" 16514 "// line comment\n" 16515 "int oneTwoThree=123;", 16516 Alignment)); 16517 16518 /* Test across comments and newlines */ 16519 EXPECT_EQ("int a = 5;\n" 16520 "\n" 16521 "/* block comment */\n" 16522 "int oneTwoThree = 123;", 16523 format("int a = 5;\n" 16524 "\n" 16525 "/* block comment */\n" 16526 "int oneTwoThree=123;", 16527 Alignment)); 16528 16529 EXPECT_EQ("int a = 5;\n" 16530 "\n" 16531 "// line comment\n" 16532 "int oneTwoThree = 123;", 16533 format("int a = 5;\n" 16534 "\n" 16535 "// line comment\n" 16536 "int oneTwoThree=123;", 16537 Alignment)); 16538 16539 EXPECT_EQ("int a = 5;\n" 16540 "//\n" 16541 "// multi-line line comment\n" 16542 "//\n" 16543 "int oneTwoThree = 123;", 16544 format("int a = 5;\n" 16545 "//\n" 16546 "// multi-line line comment\n" 16547 "//\n" 16548 "int oneTwoThree=123;", 16549 Alignment)); 16550 16551 EXPECT_EQ("int a = 5;\n" 16552 "/*\n" 16553 " * multi-line block comment\n" 16554 " */\n" 16555 "int oneTwoThree = 123;", 16556 format("int a = 5;\n" 16557 "/*\n" 16558 " * multi-line block comment\n" 16559 " */\n" 16560 "int oneTwoThree=123;", 16561 Alignment)); 16562 16563 EXPECT_EQ("int a = 5;\n" 16564 "\n" 16565 "/* block comment */\n" 16566 "\n" 16567 "\n" 16568 "\n" 16569 "int oneTwoThree = 123;", 16570 format("int a = 5;\n" 16571 "\n" 16572 "/* block comment */\n" 16573 "\n" 16574 "\n" 16575 "\n" 16576 "int oneTwoThree=123;", 16577 Alignment)); 16578 16579 EXPECT_EQ("int a = 5;\n" 16580 "\n" 16581 "// line comment\n" 16582 "\n" 16583 "\n" 16584 "\n" 16585 "int oneTwoThree = 123;", 16586 format("int a = 5;\n" 16587 "\n" 16588 "// line comment\n" 16589 "\n" 16590 "\n" 16591 "\n" 16592 "int oneTwoThree=123;", 16593 Alignment)); 16594 16595 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 16596 verifyFormat("#define A \\\n" 16597 " int aaaa = 12; \\\n" 16598 " int b = 23; \\\n" 16599 " int ccc = 234; \\\n" 16600 " int dddddddddd = 2345;", 16601 Alignment); 16602 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 16603 verifyFormat("#define A \\\n" 16604 " int aaaa = 12; \\\n" 16605 " int b = 23; \\\n" 16606 " int ccc = 234; \\\n" 16607 " int dddddddddd = 2345;", 16608 Alignment); 16609 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 16610 verifyFormat("#define A " 16611 " \\\n" 16612 " int aaaa = 12; " 16613 " \\\n" 16614 " int b = 23; " 16615 " \\\n" 16616 " int ccc = 234; " 16617 " \\\n" 16618 " int dddddddddd = 2345;", 16619 Alignment); 16620 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 16621 "k = 4, int l = 5,\n" 16622 " int m = 6) {\n" 16623 " int j = 10;\n" 16624 " otherThing = 1;\n" 16625 "}", 16626 Alignment); 16627 verifyFormat("void SomeFunction(int parameter = 0) {\n" 16628 " int i = 1;\n" 16629 " int j = 2;\n" 16630 " int big = 10000;\n" 16631 "}", 16632 Alignment); 16633 verifyFormat("class C {\n" 16634 "public:\n" 16635 " int i = 1;\n" 16636 " virtual void f() = 0;\n" 16637 "};", 16638 Alignment); 16639 verifyFormat("int i = 1;\n" 16640 "if (SomeType t = getSomething()) {\n" 16641 "}\n" 16642 "int j = 2;\n" 16643 "int big = 10000;", 16644 Alignment); 16645 verifyFormat("int j = 7;\n" 16646 "for (int k = 0; k < N; ++k) {\n" 16647 "}\n" 16648 "int j = 2;\n" 16649 "int big = 10000;\n" 16650 "}", 16651 Alignment); 16652 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 16653 verifyFormat("int i = 1;\n" 16654 "LooooooooooongType loooooooooooooooooooooongVariable\n" 16655 " = someLooooooooooooooooongFunction();\n" 16656 "int j = 2;", 16657 Alignment); 16658 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 16659 verifyFormat("int i = 1;\n" 16660 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 16661 " someLooooooooooooooooongFunction();\n" 16662 "int j = 2;", 16663 Alignment); 16664 16665 verifyFormat("auto lambda = []() {\n" 16666 " auto i = 0;\n" 16667 " return 0;\n" 16668 "};\n" 16669 "int i = 0;\n" 16670 "auto v = type{\n" 16671 " i = 1, //\n" 16672 " (i = 2), //\n" 16673 " i = 3 //\n" 16674 "};", 16675 Alignment); 16676 16677 verifyFormat( 16678 "int i = 1;\n" 16679 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 16680 " loooooooooooooooooooooongParameterB);\n" 16681 "int j = 2;", 16682 Alignment); 16683 16684 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n" 16685 " typename B = very_long_type_name_1,\n" 16686 " typename T_2 = very_long_type_name_2>\n" 16687 "auto foo() {}\n", 16688 Alignment); 16689 verifyFormat("int a, b = 1;\n" 16690 "int c = 2;\n" 16691 "int dd = 3;\n", 16692 Alignment); 16693 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 16694 "float b[1][] = {{3.f}};\n", 16695 Alignment); 16696 verifyFormat("for (int i = 0; i < 1; i++)\n" 16697 " int x = 1;\n", 16698 Alignment); 16699 verifyFormat("for (i = 0; i < 1; i++)\n" 16700 " x = 1;\n" 16701 "y = 1;\n", 16702 Alignment); 16703 16704 Alignment.ReflowComments = true; 16705 Alignment.ColumnLimit = 50; 16706 EXPECT_EQ("int x = 0;\n" 16707 "int yy = 1; /// specificlennospace\n" 16708 "int zzz = 2;\n", 16709 format("int x = 0;\n" 16710 "int yy = 1; ///specificlennospace\n" 16711 "int zzz = 2;\n", 16712 Alignment)); 16713 } 16714 16715 TEST_F(FormatTest, AlignConsecutiveAssignments) { 16716 FormatStyle Alignment = getLLVMStyle(); 16717 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 16718 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 16719 verifyFormat("int a = 5;\n" 16720 "int oneTwoThree = 123;", 16721 Alignment); 16722 verifyFormat("int a = 5;\n" 16723 "int oneTwoThree = 123;", 16724 Alignment); 16725 16726 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 16727 verifyFormat("int a = 5;\n" 16728 "int oneTwoThree = 123;", 16729 Alignment); 16730 verifyFormat("int a = method();\n" 16731 "int oneTwoThree = 133;", 16732 Alignment); 16733 verifyFormat("a &= 5;\n" 16734 "bcd *= 5;\n" 16735 "ghtyf += 5;\n" 16736 "dvfvdb -= 5;\n" 16737 "a /= 5;\n" 16738 "vdsvsv %= 5;\n" 16739 "sfdbddfbdfbb ^= 5;\n" 16740 "dvsdsv |= 5;\n" 16741 "int dsvvdvsdvvv = 123;", 16742 Alignment); 16743 verifyFormat("int i = 1, j = 10;\n" 16744 "something = 2000;", 16745 Alignment); 16746 verifyFormat("something = 2000;\n" 16747 "int i = 1, j = 10;\n", 16748 Alignment); 16749 verifyFormat("something = 2000;\n" 16750 "another = 911;\n" 16751 "int i = 1, j = 10;\n" 16752 "oneMore = 1;\n" 16753 "i = 2;", 16754 Alignment); 16755 verifyFormat("int a = 5;\n" 16756 "int one = 1;\n" 16757 "method();\n" 16758 "int oneTwoThree = 123;\n" 16759 "int oneTwo = 12;", 16760 Alignment); 16761 verifyFormat("int oneTwoThree = 123;\n" 16762 "int oneTwo = 12;\n" 16763 "method();\n", 16764 Alignment); 16765 verifyFormat("int oneTwoThree = 123; // comment\n" 16766 "int oneTwo = 12; // comment", 16767 Alignment); 16768 verifyFormat("int f() = default;\n" 16769 "int &operator() = default;\n" 16770 "int &operator=() {", 16771 Alignment); 16772 verifyFormat("int f() = delete;\n" 16773 "int &operator() = delete;\n" 16774 "int &operator=() {", 16775 Alignment); 16776 verifyFormat("int f() = default; // comment\n" 16777 "int &operator() = default; // comment\n" 16778 "int &operator=() {", 16779 Alignment); 16780 verifyFormat("int f() = default;\n" 16781 "int &operator() = default;\n" 16782 "int &operator==() {", 16783 Alignment); 16784 verifyFormat("int f() = default;\n" 16785 "int &operator() = default;\n" 16786 "int &operator<=() {", 16787 Alignment); 16788 verifyFormat("int f() = default;\n" 16789 "int &operator() = default;\n" 16790 "int &operator!=() {", 16791 Alignment); 16792 verifyFormat("int f() = default;\n" 16793 "int &operator() = default;\n" 16794 "int &operator=();", 16795 Alignment); 16796 verifyFormat("int f() = delete;\n" 16797 "int &operator() = delete;\n" 16798 "int &operator=();", 16799 Alignment); 16800 verifyFormat("/* long long padding */ int f() = default;\n" 16801 "int &operator() = default;\n" 16802 "int &operator/**/ =();", 16803 Alignment); 16804 // https://llvm.org/PR33697 16805 FormatStyle AlignmentWithPenalty = getLLVMStyle(); 16806 AlignmentWithPenalty.AlignConsecutiveAssignments = 16807 FormatStyle::ACS_Consecutive; 16808 AlignmentWithPenalty.PenaltyReturnTypeOnItsOwnLine = 5000; 16809 verifyFormat("class SSSSSSSSSSSSSSSSSSSSSSSSSSSS {\n" 16810 " void f() = delete;\n" 16811 " SSSSSSSSSSSSSSSSSSSSSSSSSSSS &operator=(\n" 16812 " const SSSSSSSSSSSSSSSSSSSSSSSSSSSS &other) = delete;\n" 16813 "};\n", 16814 AlignmentWithPenalty); 16815 16816 // Bug 25167 16817 /* Uncomment when fixed 16818 verifyFormat("#if A\n" 16819 "#else\n" 16820 "int aaaaaaaa = 12;\n" 16821 "#endif\n" 16822 "#if B\n" 16823 "#else\n" 16824 "int a = 12;\n" 16825 "#endif\n", 16826 Alignment); 16827 verifyFormat("enum foo {\n" 16828 "#if A\n" 16829 "#else\n" 16830 " aaaaaaaa = 12;\n" 16831 "#endif\n" 16832 "#if B\n" 16833 "#else\n" 16834 " a = 12;\n" 16835 "#endif\n" 16836 "};\n", 16837 Alignment); 16838 */ 16839 16840 EXPECT_EQ("int a = 5;\n" 16841 "\n" 16842 "int oneTwoThree = 123;", 16843 format("int a = 5;\n" 16844 "\n" 16845 "int oneTwoThree= 123;", 16846 Alignment)); 16847 EXPECT_EQ("int a = 5;\n" 16848 "int one = 1;\n" 16849 "\n" 16850 "int oneTwoThree = 123;", 16851 format("int a = 5;\n" 16852 "int one = 1;\n" 16853 "\n" 16854 "int oneTwoThree = 123;", 16855 Alignment)); 16856 EXPECT_EQ("int a = 5;\n" 16857 "int one = 1;\n" 16858 "\n" 16859 "int oneTwoThree = 123;\n" 16860 "int oneTwo = 12;", 16861 format("int a = 5;\n" 16862 "int one = 1;\n" 16863 "\n" 16864 "int oneTwoThree = 123;\n" 16865 "int oneTwo = 12;", 16866 Alignment)); 16867 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 16868 verifyFormat("#define A \\\n" 16869 " int aaaa = 12; \\\n" 16870 " int b = 23; \\\n" 16871 " int ccc = 234; \\\n" 16872 " int dddddddddd = 2345;", 16873 Alignment); 16874 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 16875 verifyFormat("#define A \\\n" 16876 " int aaaa = 12; \\\n" 16877 " int b = 23; \\\n" 16878 " int ccc = 234; \\\n" 16879 " int dddddddddd = 2345;", 16880 Alignment); 16881 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 16882 verifyFormat("#define A " 16883 " \\\n" 16884 " int aaaa = 12; " 16885 " \\\n" 16886 " int b = 23; " 16887 " \\\n" 16888 " int ccc = 234; " 16889 " \\\n" 16890 " int dddddddddd = 2345;", 16891 Alignment); 16892 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 16893 "k = 4, int l = 5,\n" 16894 " int m = 6) {\n" 16895 " int j = 10;\n" 16896 " otherThing = 1;\n" 16897 "}", 16898 Alignment); 16899 verifyFormat("void SomeFunction(int parameter = 0) {\n" 16900 " int i = 1;\n" 16901 " int j = 2;\n" 16902 " int big = 10000;\n" 16903 "}", 16904 Alignment); 16905 verifyFormat("class C {\n" 16906 "public:\n" 16907 " int i = 1;\n" 16908 " virtual void f() = 0;\n" 16909 "};", 16910 Alignment); 16911 verifyFormat("int i = 1;\n" 16912 "if (SomeType t = getSomething()) {\n" 16913 "}\n" 16914 "int j = 2;\n" 16915 "int big = 10000;", 16916 Alignment); 16917 verifyFormat("int j = 7;\n" 16918 "for (int k = 0; k < N; ++k) {\n" 16919 "}\n" 16920 "int j = 2;\n" 16921 "int big = 10000;\n" 16922 "}", 16923 Alignment); 16924 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 16925 verifyFormat("int i = 1;\n" 16926 "LooooooooooongType loooooooooooooooooooooongVariable\n" 16927 " = someLooooooooooooooooongFunction();\n" 16928 "int j = 2;", 16929 Alignment); 16930 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 16931 verifyFormat("int i = 1;\n" 16932 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 16933 " someLooooooooooooooooongFunction();\n" 16934 "int j = 2;", 16935 Alignment); 16936 16937 verifyFormat("auto lambda = []() {\n" 16938 " auto i = 0;\n" 16939 " return 0;\n" 16940 "};\n" 16941 "int i = 0;\n" 16942 "auto v = type{\n" 16943 " i = 1, //\n" 16944 " (i = 2), //\n" 16945 " i = 3 //\n" 16946 "};", 16947 Alignment); 16948 16949 verifyFormat( 16950 "int i = 1;\n" 16951 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 16952 " loooooooooooooooooooooongParameterB);\n" 16953 "int j = 2;", 16954 Alignment); 16955 16956 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n" 16957 " typename B = very_long_type_name_1,\n" 16958 " typename T_2 = very_long_type_name_2>\n" 16959 "auto foo() {}\n", 16960 Alignment); 16961 verifyFormat("int a, b = 1;\n" 16962 "int c = 2;\n" 16963 "int dd = 3;\n", 16964 Alignment); 16965 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 16966 "float b[1][] = {{3.f}};\n", 16967 Alignment); 16968 verifyFormat("for (int i = 0; i < 1; i++)\n" 16969 " int x = 1;\n", 16970 Alignment); 16971 verifyFormat("for (i = 0; i < 1; i++)\n" 16972 " x = 1;\n" 16973 "y = 1;\n", 16974 Alignment); 16975 16976 EXPECT_EQ(Alignment.ReflowComments, true); 16977 Alignment.ColumnLimit = 50; 16978 EXPECT_EQ("int x = 0;\n" 16979 "int yy = 1; /// specificlennospace\n" 16980 "int zzz = 2;\n", 16981 format("int x = 0;\n" 16982 "int yy = 1; ///specificlennospace\n" 16983 "int zzz = 2;\n", 16984 Alignment)); 16985 16986 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 16987 "auto b = [] {\n" 16988 " f();\n" 16989 " return;\n" 16990 "};", 16991 Alignment); 16992 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 16993 "auto b = g([] {\n" 16994 " f();\n" 16995 " return;\n" 16996 "});", 16997 Alignment); 16998 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 16999 "auto b = g(param, [] {\n" 17000 " f();\n" 17001 " return;\n" 17002 "});", 17003 Alignment); 17004 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17005 "auto b = [] {\n" 17006 " if (condition) {\n" 17007 " return;\n" 17008 " }\n" 17009 "};", 17010 Alignment); 17011 17012 verifyFormat("auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 17013 " ccc ? aaaaa : bbbbb,\n" 17014 " dddddddddddddddddddddddddd);", 17015 Alignment); 17016 // FIXME: https://llvm.org/PR53497 17017 // verifyFormat("auto aaaaaaaaaaaa = f();\n" 17018 // "auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 17019 // " ccc ? aaaaa : bbbbb,\n" 17020 // " dddddddddddddddddddddddddd);", 17021 // Alignment); 17022 } 17023 17024 TEST_F(FormatTest, AlignConsecutiveBitFields) { 17025 FormatStyle Alignment = getLLVMStyle(); 17026 Alignment.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive; 17027 verifyFormat("int const a : 5;\n" 17028 "int oneTwoThree : 23;", 17029 Alignment); 17030 17031 // Initializers are allowed starting with c++2a 17032 verifyFormat("int const a : 5 = 1;\n" 17033 "int oneTwoThree : 23 = 0;", 17034 Alignment); 17035 17036 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17037 verifyFormat("int const a : 5;\n" 17038 "int oneTwoThree : 23;", 17039 Alignment); 17040 17041 verifyFormat("int const a : 5; // comment\n" 17042 "int oneTwoThree : 23; // comment", 17043 Alignment); 17044 17045 verifyFormat("int const a : 5 = 1;\n" 17046 "int oneTwoThree : 23 = 0;", 17047 Alignment); 17048 17049 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17050 verifyFormat("int const a : 5 = 1;\n" 17051 "int oneTwoThree : 23 = 0;", 17052 Alignment); 17053 verifyFormat("int const a : 5 = {1};\n" 17054 "int oneTwoThree : 23 = 0;", 17055 Alignment); 17056 17057 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None; 17058 verifyFormat("int const a :5;\n" 17059 "int oneTwoThree:23;", 17060 Alignment); 17061 17062 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before; 17063 verifyFormat("int const a :5;\n" 17064 "int oneTwoThree :23;", 17065 Alignment); 17066 17067 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After; 17068 verifyFormat("int const a : 5;\n" 17069 "int oneTwoThree: 23;", 17070 Alignment); 17071 17072 // Known limitations: ':' is only recognized as a bitfield colon when 17073 // followed by a number. 17074 /* 17075 verifyFormat("int oneTwoThree : SOME_CONSTANT;\n" 17076 "int a : 5;", 17077 Alignment); 17078 */ 17079 } 17080 17081 TEST_F(FormatTest, AlignConsecutiveDeclarations) { 17082 FormatStyle Alignment = getLLVMStyle(); 17083 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 17084 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_None; 17085 Alignment.PointerAlignment = FormatStyle::PAS_Right; 17086 verifyFormat("float const a = 5;\n" 17087 "int oneTwoThree = 123;", 17088 Alignment); 17089 verifyFormat("int a = 5;\n" 17090 "float const oneTwoThree = 123;", 17091 Alignment); 17092 17093 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17094 verifyFormat("float const a = 5;\n" 17095 "int oneTwoThree = 123;", 17096 Alignment); 17097 verifyFormat("int a = method();\n" 17098 "float const oneTwoThree = 133;", 17099 Alignment); 17100 verifyFormat("int i = 1, j = 10;\n" 17101 "something = 2000;", 17102 Alignment); 17103 verifyFormat("something = 2000;\n" 17104 "int i = 1, j = 10;\n", 17105 Alignment); 17106 verifyFormat("float something = 2000;\n" 17107 "double another = 911;\n" 17108 "int i = 1, j = 10;\n" 17109 "const int *oneMore = 1;\n" 17110 "unsigned i = 2;", 17111 Alignment); 17112 verifyFormat("float a = 5;\n" 17113 "int one = 1;\n" 17114 "method();\n" 17115 "const double oneTwoThree = 123;\n" 17116 "const unsigned int oneTwo = 12;", 17117 Alignment); 17118 verifyFormat("int oneTwoThree{0}; // comment\n" 17119 "unsigned oneTwo; // comment", 17120 Alignment); 17121 verifyFormat("unsigned int *a;\n" 17122 "int *b;\n" 17123 "unsigned int Const *c;\n" 17124 "unsigned int const *d;\n" 17125 "unsigned int Const &e;\n" 17126 "unsigned int const &f;", 17127 Alignment); 17128 verifyFormat("Const unsigned int *c;\n" 17129 "const unsigned int *d;\n" 17130 "Const unsigned int &e;\n" 17131 "const unsigned int &f;\n" 17132 "const unsigned g;\n" 17133 "Const unsigned h;", 17134 Alignment); 17135 EXPECT_EQ("float const a = 5;\n" 17136 "\n" 17137 "int oneTwoThree = 123;", 17138 format("float const a = 5;\n" 17139 "\n" 17140 "int oneTwoThree= 123;", 17141 Alignment)); 17142 EXPECT_EQ("float a = 5;\n" 17143 "int one = 1;\n" 17144 "\n" 17145 "unsigned oneTwoThree = 123;", 17146 format("float a = 5;\n" 17147 "int one = 1;\n" 17148 "\n" 17149 "unsigned oneTwoThree = 123;", 17150 Alignment)); 17151 EXPECT_EQ("float a = 5;\n" 17152 "int one = 1;\n" 17153 "\n" 17154 "unsigned oneTwoThree = 123;\n" 17155 "int oneTwo = 12;", 17156 format("float a = 5;\n" 17157 "int one = 1;\n" 17158 "\n" 17159 "unsigned oneTwoThree = 123;\n" 17160 "int oneTwo = 12;", 17161 Alignment)); 17162 // Function prototype alignment 17163 verifyFormat("int a();\n" 17164 "double b();", 17165 Alignment); 17166 verifyFormat("int a(int x);\n" 17167 "double b();", 17168 Alignment); 17169 unsigned OldColumnLimit = Alignment.ColumnLimit; 17170 // We need to set ColumnLimit to zero, in order to stress nested alignments, 17171 // otherwise the function parameters will be re-flowed onto a single line. 17172 Alignment.ColumnLimit = 0; 17173 EXPECT_EQ("int a(int x,\n" 17174 " float y);\n" 17175 "double b(int x,\n" 17176 " double y);", 17177 format("int a(int x,\n" 17178 " float y);\n" 17179 "double b(int x,\n" 17180 " double y);", 17181 Alignment)); 17182 // This ensures that function parameters of function declarations are 17183 // correctly indented when their owning functions are indented. 17184 // The failure case here is for 'double y' to not be indented enough. 17185 EXPECT_EQ("double a(int x);\n" 17186 "int b(int y,\n" 17187 " double z);", 17188 format("double a(int x);\n" 17189 "int b(int y,\n" 17190 " double z);", 17191 Alignment)); 17192 // Set ColumnLimit low so that we induce wrapping immediately after 17193 // the function name and opening paren. 17194 Alignment.ColumnLimit = 13; 17195 verifyFormat("int function(\n" 17196 " int x,\n" 17197 " bool y);", 17198 Alignment); 17199 Alignment.ColumnLimit = OldColumnLimit; 17200 // Ensure function pointers don't screw up recursive alignment 17201 verifyFormat("int a(int x, void (*fp)(int y));\n" 17202 "double b();", 17203 Alignment); 17204 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17205 // Ensure recursive alignment is broken by function braces, so that the 17206 // "a = 1" does not align with subsequent assignments inside the function 17207 // body. 17208 verifyFormat("int func(int a = 1) {\n" 17209 " int b = 2;\n" 17210 " int cc = 3;\n" 17211 "}", 17212 Alignment); 17213 verifyFormat("float something = 2000;\n" 17214 "double another = 911;\n" 17215 "int i = 1, j = 10;\n" 17216 "const int *oneMore = 1;\n" 17217 "unsigned i = 2;", 17218 Alignment); 17219 verifyFormat("int oneTwoThree = {0}; // comment\n" 17220 "unsigned oneTwo = 0; // comment", 17221 Alignment); 17222 // Make sure that scope is correctly tracked, in the absence of braces 17223 verifyFormat("for (int i = 0; i < n; i++)\n" 17224 " j = i;\n" 17225 "double x = 1;\n", 17226 Alignment); 17227 verifyFormat("if (int i = 0)\n" 17228 " j = i;\n" 17229 "double x = 1;\n", 17230 Alignment); 17231 // Ensure operator[] and operator() are comprehended 17232 verifyFormat("struct test {\n" 17233 " long long int foo();\n" 17234 " int operator[](int a);\n" 17235 " double bar();\n" 17236 "};\n", 17237 Alignment); 17238 verifyFormat("struct test {\n" 17239 " long long int foo();\n" 17240 " int operator()(int a);\n" 17241 " double bar();\n" 17242 "};\n", 17243 Alignment); 17244 // http://llvm.org/PR52914 17245 verifyFormat("char *a[] = {\"a\", // comment\n" 17246 " \"bb\"};\n" 17247 "int bbbbbbb = 0;", 17248 Alignment); 17249 17250 // PAS_Right 17251 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17252 " int const i = 1;\n" 17253 " int *j = 2;\n" 17254 " int big = 10000;\n" 17255 "\n" 17256 " unsigned oneTwoThree = 123;\n" 17257 " int oneTwo = 12;\n" 17258 " method();\n" 17259 " float k = 2;\n" 17260 " int ll = 10000;\n" 17261 "}", 17262 format("void SomeFunction(int parameter= 0) {\n" 17263 " int const i= 1;\n" 17264 " int *j=2;\n" 17265 " int big = 10000;\n" 17266 "\n" 17267 "unsigned oneTwoThree =123;\n" 17268 "int oneTwo = 12;\n" 17269 " method();\n" 17270 "float k= 2;\n" 17271 "int ll=10000;\n" 17272 "}", 17273 Alignment)); 17274 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17275 " int const i = 1;\n" 17276 " int **j = 2, ***k;\n" 17277 " int &k = i;\n" 17278 " int &&l = i + j;\n" 17279 " int big = 10000;\n" 17280 "\n" 17281 " unsigned oneTwoThree = 123;\n" 17282 " int oneTwo = 12;\n" 17283 " method();\n" 17284 " float k = 2;\n" 17285 " int ll = 10000;\n" 17286 "}", 17287 format("void SomeFunction(int parameter= 0) {\n" 17288 " int const i= 1;\n" 17289 " int **j=2,***k;\n" 17290 "int &k=i;\n" 17291 "int &&l=i+j;\n" 17292 " int big = 10000;\n" 17293 "\n" 17294 "unsigned oneTwoThree =123;\n" 17295 "int oneTwo = 12;\n" 17296 " method();\n" 17297 "float k= 2;\n" 17298 "int ll=10000;\n" 17299 "}", 17300 Alignment)); 17301 // variables are aligned at their name, pointers are at the right most 17302 // position 17303 verifyFormat("int *a;\n" 17304 "int **b;\n" 17305 "int ***c;\n" 17306 "int foobar;\n", 17307 Alignment); 17308 17309 // PAS_Left 17310 FormatStyle AlignmentLeft = Alignment; 17311 AlignmentLeft.PointerAlignment = FormatStyle::PAS_Left; 17312 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17313 " int const i = 1;\n" 17314 " int* j = 2;\n" 17315 " int big = 10000;\n" 17316 "\n" 17317 " unsigned oneTwoThree = 123;\n" 17318 " int oneTwo = 12;\n" 17319 " method();\n" 17320 " float k = 2;\n" 17321 " int ll = 10000;\n" 17322 "}", 17323 format("void SomeFunction(int parameter= 0) {\n" 17324 " int const i= 1;\n" 17325 " int *j=2;\n" 17326 " int big = 10000;\n" 17327 "\n" 17328 "unsigned oneTwoThree =123;\n" 17329 "int oneTwo = 12;\n" 17330 " method();\n" 17331 "float k= 2;\n" 17332 "int ll=10000;\n" 17333 "}", 17334 AlignmentLeft)); 17335 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17336 " int const i = 1;\n" 17337 " int** j = 2;\n" 17338 " int& k = i;\n" 17339 " int&& l = i + j;\n" 17340 " int big = 10000;\n" 17341 "\n" 17342 " unsigned oneTwoThree = 123;\n" 17343 " int oneTwo = 12;\n" 17344 " method();\n" 17345 " float k = 2;\n" 17346 " int ll = 10000;\n" 17347 "}", 17348 format("void SomeFunction(int parameter= 0) {\n" 17349 " int const i= 1;\n" 17350 " int **j=2;\n" 17351 "int &k=i;\n" 17352 "int &&l=i+j;\n" 17353 " int big = 10000;\n" 17354 "\n" 17355 "unsigned oneTwoThree =123;\n" 17356 "int oneTwo = 12;\n" 17357 " method();\n" 17358 "float k= 2;\n" 17359 "int ll=10000;\n" 17360 "}", 17361 AlignmentLeft)); 17362 // variables are aligned at their name, pointers are at the left most position 17363 verifyFormat("int* a;\n" 17364 "int** b;\n" 17365 "int*** c;\n" 17366 "int foobar;\n", 17367 AlignmentLeft); 17368 17369 // PAS_Middle 17370 FormatStyle AlignmentMiddle = Alignment; 17371 AlignmentMiddle.PointerAlignment = FormatStyle::PAS_Middle; 17372 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17373 " int const i = 1;\n" 17374 " int * j = 2;\n" 17375 " int big = 10000;\n" 17376 "\n" 17377 " unsigned oneTwoThree = 123;\n" 17378 " int oneTwo = 12;\n" 17379 " method();\n" 17380 " float k = 2;\n" 17381 " int ll = 10000;\n" 17382 "}", 17383 format("void SomeFunction(int parameter= 0) {\n" 17384 " int const i= 1;\n" 17385 " int *j=2;\n" 17386 " int big = 10000;\n" 17387 "\n" 17388 "unsigned oneTwoThree =123;\n" 17389 "int oneTwo = 12;\n" 17390 " method();\n" 17391 "float k= 2;\n" 17392 "int ll=10000;\n" 17393 "}", 17394 AlignmentMiddle)); 17395 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17396 " int const i = 1;\n" 17397 " int ** j = 2, ***k;\n" 17398 " int & k = i;\n" 17399 " int && l = i + j;\n" 17400 " int big = 10000;\n" 17401 "\n" 17402 " unsigned oneTwoThree = 123;\n" 17403 " int oneTwo = 12;\n" 17404 " method();\n" 17405 " float k = 2;\n" 17406 " int ll = 10000;\n" 17407 "}", 17408 format("void SomeFunction(int parameter= 0) {\n" 17409 " int const i= 1;\n" 17410 " int **j=2,***k;\n" 17411 "int &k=i;\n" 17412 "int &&l=i+j;\n" 17413 " int big = 10000;\n" 17414 "\n" 17415 "unsigned oneTwoThree =123;\n" 17416 "int oneTwo = 12;\n" 17417 " method();\n" 17418 "float k= 2;\n" 17419 "int ll=10000;\n" 17420 "}", 17421 AlignmentMiddle)); 17422 // variables are aligned at their name, pointers are in the middle 17423 verifyFormat("int * a;\n" 17424 "int * b;\n" 17425 "int *** c;\n" 17426 "int foobar;\n", 17427 AlignmentMiddle); 17428 17429 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 17430 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 17431 verifyFormat("#define A \\\n" 17432 " int aaaa = 12; \\\n" 17433 " float b = 23; \\\n" 17434 " const int ccc = 234; \\\n" 17435 " unsigned dddddddddd = 2345;", 17436 Alignment); 17437 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 17438 verifyFormat("#define A \\\n" 17439 " int aaaa = 12; \\\n" 17440 " float b = 23; \\\n" 17441 " const int ccc = 234; \\\n" 17442 " unsigned dddddddddd = 2345;", 17443 Alignment); 17444 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 17445 Alignment.ColumnLimit = 30; 17446 verifyFormat("#define A \\\n" 17447 " int aaaa = 12; \\\n" 17448 " float b = 23; \\\n" 17449 " const int ccc = 234; \\\n" 17450 " int dddddddddd = 2345;", 17451 Alignment); 17452 Alignment.ColumnLimit = 80; 17453 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 17454 "k = 4, int l = 5,\n" 17455 " int m = 6) {\n" 17456 " const int j = 10;\n" 17457 " otherThing = 1;\n" 17458 "}", 17459 Alignment); 17460 verifyFormat("void SomeFunction(int parameter = 0) {\n" 17461 " int const i = 1;\n" 17462 " int *j = 2;\n" 17463 " int big = 10000;\n" 17464 "}", 17465 Alignment); 17466 verifyFormat("class C {\n" 17467 "public:\n" 17468 " int i = 1;\n" 17469 " virtual void f() = 0;\n" 17470 "};", 17471 Alignment); 17472 verifyFormat("float i = 1;\n" 17473 "if (SomeType t = getSomething()) {\n" 17474 "}\n" 17475 "const unsigned j = 2;\n" 17476 "int big = 10000;", 17477 Alignment); 17478 verifyFormat("float j = 7;\n" 17479 "for (int k = 0; k < N; ++k) {\n" 17480 "}\n" 17481 "unsigned j = 2;\n" 17482 "int big = 10000;\n" 17483 "}", 17484 Alignment); 17485 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 17486 verifyFormat("float i = 1;\n" 17487 "LooooooooooongType loooooooooooooooooooooongVariable\n" 17488 " = someLooooooooooooooooongFunction();\n" 17489 "int j = 2;", 17490 Alignment); 17491 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 17492 verifyFormat("int i = 1;\n" 17493 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 17494 " someLooooooooooooooooongFunction();\n" 17495 "int j = 2;", 17496 Alignment); 17497 17498 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17499 verifyFormat("auto lambda = []() {\n" 17500 " auto ii = 0;\n" 17501 " float j = 0;\n" 17502 " return 0;\n" 17503 "};\n" 17504 "int i = 0;\n" 17505 "float i2 = 0;\n" 17506 "auto v = type{\n" 17507 " i = 1, //\n" 17508 " (i = 2), //\n" 17509 " i = 3 //\n" 17510 "};", 17511 Alignment); 17512 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 17513 17514 verifyFormat( 17515 "int i = 1;\n" 17516 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 17517 " loooooooooooooooooooooongParameterB);\n" 17518 "int j = 2;", 17519 Alignment); 17520 17521 // Test interactions with ColumnLimit and AlignConsecutiveAssignments: 17522 // We expect declarations and assignments to align, as long as it doesn't 17523 // exceed the column limit, starting a new alignment sequence whenever it 17524 // happens. 17525 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17526 Alignment.ColumnLimit = 30; 17527 verifyFormat("float ii = 1;\n" 17528 "unsigned j = 2;\n" 17529 "int someVerylongVariable = 1;\n" 17530 "AnotherLongType ll = 123456;\n" 17531 "VeryVeryLongType k = 2;\n" 17532 "int myvar = 1;", 17533 Alignment); 17534 Alignment.ColumnLimit = 80; 17535 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 17536 17537 verifyFormat( 17538 "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n" 17539 " typename LongType, typename B>\n" 17540 "auto foo() {}\n", 17541 Alignment); 17542 verifyFormat("float a, b = 1;\n" 17543 "int c = 2;\n" 17544 "int dd = 3;\n", 17545 Alignment); 17546 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17547 "float b[1][] = {{3.f}};\n", 17548 Alignment); 17549 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17550 verifyFormat("float a, b = 1;\n" 17551 "int c = 2;\n" 17552 "int dd = 3;\n", 17553 Alignment); 17554 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17555 "float b[1][] = {{3.f}};\n", 17556 Alignment); 17557 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 17558 17559 Alignment.ColumnLimit = 30; 17560 Alignment.BinPackParameters = false; 17561 verifyFormat("void foo(float a,\n" 17562 " float b,\n" 17563 " int c,\n" 17564 " uint32_t *d) {\n" 17565 " int *e = 0;\n" 17566 " float f = 0;\n" 17567 " double g = 0;\n" 17568 "}\n" 17569 "void bar(ino_t a,\n" 17570 " int b,\n" 17571 " uint32_t *c,\n" 17572 " bool d) {}\n", 17573 Alignment); 17574 Alignment.BinPackParameters = true; 17575 Alignment.ColumnLimit = 80; 17576 17577 // Bug 33507 17578 Alignment.PointerAlignment = FormatStyle::PAS_Middle; 17579 verifyFormat( 17580 "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n" 17581 " static const Version verVs2017;\n" 17582 " return true;\n" 17583 "});\n", 17584 Alignment); 17585 Alignment.PointerAlignment = FormatStyle::PAS_Right; 17586 17587 // See llvm.org/PR35641 17588 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17589 verifyFormat("int func() { //\n" 17590 " int b;\n" 17591 " unsigned c;\n" 17592 "}", 17593 Alignment); 17594 17595 // See PR37175 17596 FormatStyle Style = getMozillaStyle(); 17597 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17598 EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n" 17599 "foo(int a);", 17600 format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style)); 17601 17602 Alignment.PointerAlignment = FormatStyle::PAS_Left; 17603 verifyFormat("unsigned int* a;\n" 17604 "int* b;\n" 17605 "unsigned int Const* c;\n" 17606 "unsigned int const* d;\n" 17607 "unsigned int Const& e;\n" 17608 "unsigned int const& f;", 17609 Alignment); 17610 verifyFormat("Const unsigned int* c;\n" 17611 "const unsigned int* d;\n" 17612 "Const unsigned int& e;\n" 17613 "const unsigned int& f;\n" 17614 "const unsigned g;\n" 17615 "Const unsigned h;", 17616 Alignment); 17617 17618 Alignment.PointerAlignment = FormatStyle::PAS_Middle; 17619 verifyFormat("unsigned int * a;\n" 17620 "int * b;\n" 17621 "unsigned int Const * c;\n" 17622 "unsigned int const * d;\n" 17623 "unsigned int Const & e;\n" 17624 "unsigned int const & f;", 17625 Alignment); 17626 verifyFormat("Const unsigned int * c;\n" 17627 "const unsigned int * d;\n" 17628 "Const unsigned int & e;\n" 17629 "const unsigned int & f;\n" 17630 "const unsigned g;\n" 17631 "Const unsigned h;", 17632 Alignment); 17633 17634 // See PR46529 17635 FormatStyle BracedAlign = getLLVMStyle(); 17636 BracedAlign.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17637 verifyFormat("const auto result{[]() {\n" 17638 " const auto something = 1;\n" 17639 " return 2;\n" 17640 "}};", 17641 BracedAlign); 17642 verifyFormat("int foo{[]() {\n" 17643 " int bar{0};\n" 17644 " return 0;\n" 17645 "}()};", 17646 BracedAlign); 17647 BracedAlign.Cpp11BracedListStyle = false; 17648 verifyFormat("const auto result{ []() {\n" 17649 " const auto something = 1;\n" 17650 " return 2;\n" 17651 "} };", 17652 BracedAlign); 17653 verifyFormat("int foo{ []() {\n" 17654 " int bar{ 0 };\n" 17655 " return 0;\n" 17656 "}() };", 17657 BracedAlign); 17658 } 17659 17660 TEST_F(FormatTest, AlignWithLineBreaks) { 17661 auto Style = getLLVMStyleWithColumns(120); 17662 17663 EXPECT_EQ(Style.AlignConsecutiveAssignments, FormatStyle::ACS_None); 17664 EXPECT_EQ(Style.AlignConsecutiveDeclarations, FormatStyle::ACS_None); 17665 verifyFormat("void foo() {\n" 17666 " int myVar = 5;\n" 17667 " double x = 3.14;\n" 17668 " auto str = \"Hello \"\n" 17669 " \"World\";\n" 17670 " auto s = \"Hello \"\n" 17671 " \"Again\";\n" 17672 "}", 17673 Style); 17674 17675 // clang-format off 17676 verifyFormat("void foo() {\n" 17677 " const int capacityBefore = Entries.capacity();\n" 17678 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17679 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17680 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17681 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17682 "}", 17683 Style); 17684 // clang-format on 17685 17686 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17687 verifyFormat("void foo() {\n" 17688 " int myVar = 5;\n" 17689 " double x = 3.14;\n" 17690 " auto str = \"Hello \"\n" 17691 " \"World\";\n" 17692 " auto s = \"Hello \"\n" 17693 " \"Again\";\n" 17694 "}", 17695 Style); 17696 17697 // clang-format off 17698 verifyFormat("void foo() {\n" 17699 " const int capacityBefore = Entries.capacity();\n" 17700 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17701 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17702 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17703 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17704 "}", 17705 Style); 17706 // clang-format on 17707 17708 Style.AlignConsecutiveAssignments = FormatStyle::ACS_None; 17709 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17710 verifyFormat("void foo() {\n" 17711 " int myVar = 5;\n" 17712 " double x = 3.14;\n" 17713 " auto str = \"Hello \"\n" 17714 " \"World\";\n" 17715 " auto s = \"Hello \"\n" 17716 " \"Again\";\n" 17717 "}", 17718 Style); 17719 17720 // clang-format off 17721 verifyFormat("void foo() {\n" 17722 " const int capacityBefore = Entries.capacity();\n" 17723 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17724 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17725 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17726 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17727 "}", 17728 Style); 17729 // clang-format on 17730 17731 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17732 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17733 17734 verifyFormat("void foo() {\n" 17735 " int myVar = 5;\n" 17736 " double x = 3.14;\n" 17737 " auto str = \"Hello \"\n" 17738 " \"World\";\n" 17739 " auto s = \"Hello \"\n" 17740 " \"Again\";\n" 17741 "}", 17742 Style); 17743 17744 // clang-format off 17745 verifyFormat("void foo() {\n" 17746 " const int capacityBefore = Entries.capacity();\n" 17747 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17748 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17749 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17750 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17751 "}", 17752 Style); 17753 // clang-format on 17754 17755 Style = getLLVMStyleWithColumns(120); 17756 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17757 Style.ContinuationIndentWidth = 4; 17758 Style.IndentWidth = 4; 17759 17760 // clang-format off 17761 verifyFormat("void SomeFunc() {\n" 17762 " newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 17763 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17764 " newWatcher.maxAge = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 17765 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17766 " newWatcher.max = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 17767 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17768 "}", 17769 Style); 17770 // clang-format on 17771 17772 Style.BinPackArguments = false; 17773 17774 // clang-format off 17775 verifyFormat("void SomeFunc() {\n" 17776 " newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(\n" 17777 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17778 " newWatcher.maxAge = ToLegacyTimestamp(GetMaxAge(\n" 17779 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17780 " newWatcher.max = ToLegacyTimestamp(GetMaxAge(\n" 17781 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17782 "}", 17783 Style); 17784 // clang-format on 17785 } 17786 17787 TEST_F(FormatTest, AlignWithInitializerPeriods) { 17788 auto Style = getLLVMStyleWithColumns(60); 17789 17790 verifyFormat("void foo1(void) {\n" 17791 " BYTE p[1] = 1;\n" 17792 " A B = {.one_foooooooooooooooo = 2,\n" 17793 " .two_fooooooooooooo = 3,\n" 17794 " .three_fooooooooooooo = 4};\n" 17795 " BYTE payload = 2;\n" 17796 "}", 17797 Style); 17798 17799 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17800 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_None; 17801 verifyFormat("void foo2(void) {\n" 17802 " BYTE p[1] = 1;\n" 17803 " A B = {.one_foooooooooooooooo = 2,\n" 17804 " .two_fooooooooooooo = 3,\n" 17805 " .three_fooooooooooooo = 4};\n" 17806 " BYTE payload = 2;\n" 17807 "}", 17808 Style); 17809 17810 Style.AlignConsecutiveAssignments = FormatStyle::ACS_None; 17811 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17812 verifyFormat("void foo3(void) {\n" 17813 " BYTE p[1] = 1;\n" 17814 " A B = {.one_foooooooooooooooo = 2,\n" 17815 " .two_fooooooooooooo = 3,\n" 17816 " .three_fooooooooooooo = 4};\n" 17817 " BYTE payload = 2;\n" 17818 "}", 17819 Style); 17820 17821 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17822 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17823 verifyFormat("void foo4(void) {\n" 17824 " BYTE p[1] = 1;\n" 17825 " A B = {.one_foooooooooooooooo = 2,\n" 17826 " .two_fooooooooooooo = 3,\n" 17827 " .three_fooooooooooooo = 4};\n" 17828 " BYTE payload = 2;\n" 17829 "}", 17830 Style); 17831 } 17832 17833 TEST_F(FormatTest, LinuxBraceBreaking) { 17834 FormatStyle LinuxBraceStyle = getLLVMStyle(); 17835 LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux; 17836 verifyFormat("namespace a\n" 17837 "{\n" 17838 "class A\n" 17839 "{\n" 17840 " void f()\n" 17841 " {\n" 17842 " if (true) {\n" 17843 " a();\n" 17844 " b();\n" 17845 " } else {\n" 17846 " a();\n" 17847 " }\n" 17848 " }\n" 17849 " void g() { return; }\n" 17850 "};\n" 17851 "struct B {\n" 17852 " int x;\n" 17853 "};\n" 17854 "} // namespace a\n", 17855 LinuxBraceStyle); 17856 verifyFormat("enum X {\n" 17857 " Y = 0,\n" 17858 "}\n", 17859 LinuxBraceStyle); 17860 verifyFormat("struct S {\n" 17861 " int Type;\n" 17862 " union {\n" 17863 " int x;\n" 17864 " double y;\n" 17865 " } Value;\n" 17866 " class C\n" 17867 " {\n" 17868 " MyFavoriteType Value;\n" 17869 " } Class;\n" 17870 "}\n", 17871 LinuxBraceStyle); 17872 } 17873 17874 TEST_F(FormatTest, MozillaBraceBreaking) { 17875 FormatStyle MozillaBraceStyle = getLLVMStyle(); 17876 MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla; 17877 MozillaBraceStyle.FixNamespaceComments = false; 17878 verifyFormat("namespace a {\n" 17879 "class A\n" 17880 "{\n" 17881 " void f()\n" 17882 " {\n" 17883 " if (true) {\n" 17884 " a();\n" 17885 " b();\n" 17886 " }\n" 17887 " }\n" 17888 " void g() { return; }\n" 17889 "};\n" 17890 "enum E\n" 17891 "{\n" 17892 " A,\n" 17893 " // foo\n" 17894 " B,\n" 17895 " C\n" 17896 "};\n" 17897 "struct B\n" 17898 "{\n" 17899 " int x;\n" 17900 "};\n" 17901 "}\n", 17902 MozillaBraceStyle); 17903 verifyFormat("struct S\n" 17904 "{\n" 17905 " int Type;\n" 17906 " union\n" 17907 " {\n" 17908 " int x;\n" 17909 " double y;\n" 17910 " } Value;\n" 17911 " class C\n" 17912 " {\n" 17913 " MyFavoriteType Value;\n" 17914 " } Class;\n" 17915 "}\n", 17916 MozillaBraceStyle); 17917 } 17918 17919 TEST_F(FormatTest, StroustrupBraceBreaking) { 17920 FormatStyle StroustrupBraceStyle = getLLVMStyle(); 17921 StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 17922 verifyFormat("namespace a {\n" 17923 "class A {\n" 17924 " void f()\n" 17925 " {\n" 17926 " if (true) {\n" 17927 " a();\n" 17928 " b();\n" 17929 " }\n" 17930 " }\n" 17931 " void g() { return; }\n" 17932 "};\n" 17933 "struct B {\n" 17934 " int x;\n" 17935 "};\n" 17936 "} // namespace a\n", 17937 StroustrupBraceStyle); 17938 17939 verifyFormat("void foo()\n" 17940 "{\n" 17941 " if (a) {\n" 17942 " a();\n" 17943 " }\n" 17944 " else {\n" 17945 " b();\n" 17946 " }\n" 17947 "}\n", 17948 StroustrupBraceStyle); 17949 17950 verifyFormat("#ifdef _DEBUG\n" 17951 "int foo(int i = 0)\n" 17952 "#else\n" 17953 "int foo(int i = 5)\n" 17954 "#endif\n" 17955 "{\n" 17956 " return i;\n" 17957 "}", 17958 StroustrupBraceStyle); 17959 17960 verifyFormat("void foo() {}\n" 17961 "void bar()\n" 17962 "#ifdef _DEBUG\n" 17963 "{\n" 17964 " foo();\n" 17965 "}\n" 17966 "#else\n" 17967 "{\n" 17968 "}\n" 17969 "#endif", 17970 StroustrupBraceStyle); 17971 17972 verifyFormat("void foobar() { int i = 5; }\n" 17973 "#ifdef _DEBUG\n" 17974 "void bar() {}\n" 17975 "#else\n" 17976 "void bar() { foobar(); }\n" 17977 "#endif", 17978 StroustrupBraceStyle); 17979 } 17980 17981 TEST_F(FormatTest, AllmanBraceBreaking) { 17982 FormatStyle AllmanBraceStyle = getLLVMStyle(); 17983 AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman; 17984 17985 EXPECT_EQ("namespace a\n" 17986 "{\n" 17987 "void f();\n" 17988 "void g();\n" 17989 "} // namespace a\n", 17990 format("namespace a\n" 17991 "{\n" 17992 "void f();\n" 17993 "void g();\n" 17994 "}\n", 17995 AllmanBraceStyle)); 17996 17997 verifyFormat("namespace a\n" 17998 "{\n" 17999 "class A\n" 18000 "{\n" 18001 " void f()\n" 18002 " {\n" 18003 " if (true)\n" 18004 " {\n" 18005 " a();\n" 18006 " b();\n" 18007 " }\n" 18008 " }\n" 18009 " void g() { return; }\n" 18010 "};\n" 18011 "struct B\n" 18012 "{\n" 18013 " int x;\n" 18014 "};\n" 18015 "union C\n" 18016 "{\n" 18017 "};\n" 18018 "} // namespace a", 18019 AllmanBraceStyle); 18020 18021 verifyFormat("void f()\n" 18022 "{\n" 18023 " if (true)\n" 18024 " {\n" 18025 " a();\n" 18026 " }\n" 18027 " else if (false)\n" 18028 " {\n" 18029 " b();\n" 18030 " }\n" 18031 " else\n" 18032 " {\n" 18033 " c();\n" 18034 " }\n" 18035 "}\n", 18036 AllmanBraceStyle); 18037 18038 verifyFormat("void f()\n" 18039 "{\n" 18040 " for (int i = 0; i < 10; ++i)\n" 18041 " {\n" 18042 " a();\n" 18043 " }\n" 18044 " while (false)\n" 18045 " {\n" 18046 " b();\n" 18047 " }\n" 18048 " do\n" 18049 " {\n" 18050 " c();\n" 18051 " } while (false)\n" 18052 "}\n", 18053 AllmanBraceStyle); 18054 18055 verifyFormat("void f(int a)\n" 18056 "{\n" 18057 " switch (a)\n" 18058 " {\n" 18059 " case 0:\n" 18060 " break;\n" 18061 " case 1:\n" 18062 " {\n" 18063 " break;\n" 18064 " }\n" 18065 " case 2:\n" 18066 " {\n" 18067 " }\n" 18068 " break;\n" 18069 " default:\n" 18070 " break;\n" 18071 " }\n" 18072 "}\n", 18073 AllmanBraceStyle); 18074 18075 verifyFormat("enum X\n" 18076 "{\n" 18077 " Y = 0,\n" 18078 "}\n", 18079 AllmanBraceStyle); 18080 verifyFormat("enum X\n" 18081 "{\n" 18082 " Y = 0\n" 18083 "}\n", 18084 AllmanBraceStyle); 18085 18086 verifyFormat("@interface BSApplicationController ()\n" 18087 "{\n" 18088 "@private\n" 18089 " id _extraIvar;\n" 18090 "}\n" 18091 "@end\n", 18092 AllmanBraceStyle); 18093 18094 verifyFormat("#ifdef _DEBUG\n" 18095 "int foo(int i = 0)\n" 18096 "#else\n" 18097 "int foo(int i = 5)\n" 18098 "#endif\n" 18099 "{\n" 18100 " return i;\n" 18101 "}", 18102 AllmanBraceStyle); 18103 18104 verifyFormat("void foo() {}\n" 18105 "void bar()\n" 18106 "#ifdef _DEBUG\n" 18107 "{\n" 18108 " foo();\n" 18109 "}\n" 18110 "#else\n" 18111 "{\n" 18112 "}\n" 18113 "#endif", 18114 AllmanBraceStyle); 18115 18116 verifyFormat("void foobar() { int i = 5; }\n" 18117 "#ifdef _DEBUG\n" 18118 "void bar() {}\n" 18119 "#else\n" 18120 "void bar() { foobar(); }\n" 18121 "#endif", 18122 AllmanBraceStyle); 18123 18124 EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine, 18125 FormatStyle::SLS_All); 18126 18127 verifyFormat("[](int i) { return i + 2; };\n" 18128 "[](int i, int j)\n" 18129 "{\n" 18130 " auto x = i + j;\n" 18131 " auto y = i * j;\n" 18132 " return x ^ y;\n" 18133 "};\n" 18134 "void foo()\n" 18135 "{\n" 18136 " auto shortLambda = [](int i) { return i + 2; };\n" 18137 " auto longLambda = [](int i, int j)\n" 18138 " {\n" 18139 " auto x = i + j;\n" 18140 " auto y = i * j;\n" 18141 " return x ^ y;\n" 18142 " };\n" 18143 "}", 18144 AllmanBraceStyle); 18145 18146 AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 18147 18148 verifyFormat("[](int i)\n" 18149 "{\n" 18150 " return i + 2;\n" 18151 "};\n" 18152 "[](int i, int j)\n" 18153 "{\n" 18154 " auto x = i + j;\n" 18155 " auto y = i * j;\n" 18156 " return x ^ y;\n" 18157 "};\n" 18158 "void foo()\n" 18159 "{\n" 18160 " auto shortLambda = [](int i)\n" 18161 " {\n" 18162 " return i + 2;\n" 18163 " };\n" 18164 " auto longLambda = [](int i, int j)\n" 18165 " {\n" 18166 " auto x = i + j;\n" 18167 " auto y = i * j;\n" 18168 " return x ^ y;\n" 18169 " };\n" 18170 "}", 18171 AllmanBraceStyle); 18172 18173 // Reset 18174 AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All; 18175 18176 // This shouldn't affect ObjC blocks.. 18177 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n" 18178 " // ...\n" 18179 " int i;\n" 18180 "}];", 18181 AllmanBraceStyle); 18182 verifyFormat("void (^block)(void) = ^{\n" 18183 " // ...\n" 18184 " int i;\n" 18185 "};", 18186 AllmanBraceStyle); 18187 // .. or dict literals. 18188 verifyFormat("void f()\n" 18189 "{\n" 18190 " // ...\n" 18191 " [object someMethod:@{@\"a\" : @\"b\"}];\n" 18192 "}", 18193 AllmanBraceStyle); 18194 verifyFormat("void f()\n" 18195 "{\n" 18196 " // ...\n" 18197 " [object someMethod:@{a : @\"b\"}];\n" 18198 "}", 18199 AllmanBraceStyle); 18200 verifyFormat("int f()\n" 18201 "{ // comment\n" 18202 " return 42;\n" 18203 "}", 18204 AllmanBraceStyle); 18205 18206 AllmanBraceStyle.ColumnLimit = 19; 18207 verifyFormat("void f() { int i; }", AllmanBraceStyle); 18208 AllmanBraceStyle.ColumnLimit = 18; 18209 verifyFormat("void f()\n" 18210 "{\n" 18211 " int i;\n" 18212 "}", 18213 AllmanBraceStyle); 18214 AllmanBraceStyle.ColumnLimit = 80; 18215 18216 FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle; 18217 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = 18218 FormatStyle::SIS_WithoutElse; 18219 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true; 18220 verifyFormat("void f(bool b)\n" 18221 "{\n" 18222 " if (b)\n" 18223 " {\n" 18224 " return;\n" 18225 " }\n" 18226 "}\n", 18227 BreakBeforeBraceShortIfs); 18228 verifyFormat("void f(bool b)\n" 18229 "{\n" 18230 " if constexpr (b)\n" 18231 " {\n" 18232 " return;\n" 18233 " }\n" 18234 "}\n", 18235 BreakBeforeBraceShortIfs); 18236 verifyFormat("void f(bool b)\n" 18237 "{\n" 18238 " if CONSTEXPR (b)\n" 18239 " {\n" 18240 " return;\n" 18241 " }\n" 18242 "}\n", 18243 BreakBeforeBraceShortIfs); 18244 verifyFormat("void f(bool b)\n" 18245 "{\n" 18246 " if (b) return;\n" 18247 "}\n", 18248 BreakBeforeBraceShortIfs); 18249 verifyFormat("void f(bool b)\n" 18250 "{\n" 18251 " if constexpr (b) return;\n" 18252 "}\n", 18253 BreakBeforeBraceShortIfs); 18254 verifyFormat("void f(bool b)\n" 18255 "{\n" 18256 " if CONSTEXPR (b) return;\n" 18257 "}\n", 18258 BreakBeforeBraceShortIfs); 18259 verifyFormat("void f(bool b)\n" 18260 "{\n" 18261 " while (b)\n" 18262 " {\n" 18263 " return;\n" 18264 " }\n" 18265 "}\n", 18266 BreakBeforeBraceShortIfs); 18267 } 18268 18269 TEST_F(FormatTest, WhitesmithsBraceBreaking) { 18270 FormatStyle WhitesmithsBraceStyle = getLLVMStyleWithColumns(0); 18271 WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 18272 18273 // Make a few changes to the style for testing purposes 18274 WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine = 18275 FormatStyle::SFS_Empty; 18276 WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 18277 18278 // FIXME: this test case can't decide whether there should be a blank line 18279 // after the ~D() line or not. It adds one if one doesn't exist in the test 18280 // and it removes the line if one exists. 18281 /* 18282 verifyFormat("class A;\n" 18283 "namespace B\n" 18284 " {\n" 18285 "class C;\n" 18286 "// Comment\n" 18287 "class D\n" 18288 " {\n" 18289 "public:\n" 18290 " D();\n" 18291 " ~D() {}\n" 18292 "private:\n" 18293 " enum E\n" 18294 " {\n" 18295 " F\n" 18296 " }\n" 18297 " };\n" 18298 " } // namespace B\n", 18299 WhitesmithsBraceStyle); 18300 */ 18301 18302 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None; 18303 verifyFormat("namespace a\n" 18304 " {\n" 18305 "class A\n" 18306 " {\n" 18307 " void f()\n" 18308 " {\n" 18309 " if (true)\n" 18310 " {\n" 18311 " a();\n" 18312 " b();\n" 18313 " }\n" 18314 " }\n" 18315 " void g()\n" 18316 " {\n" 18317 " return;\n" 18318 " }\n" 18319 " };\n" 18320 "struct B\n" 18321 " {\n" 18322 " int x;\n" 18323 " };\n" 18324 " } // namespace a", 18325 WhitesmithsBraceStyle); 18326 18327 verifyFormat("namespace a\n" 18328 " {\n" 18329 "namespace b\n" 18330 " {\n" 18331 "class A\n" 18332 " {\n" 18333 " void f()\n" 18334 " {\n" 18335 " if (true)\n" 18336 " {\n" 18337 " a();\n" 18338 " b();\n" 18339 " }\n" 18340 " }\n" 18341 " void g()\n" 18342 " {\n" 18343 " return;\n" 18344 " }\n" 18345 " };\n" 18346 "struct B\n" 18347 " {\n" 18348 " int x;\n" 18349 " };\n" 18350 " } // namespace b\n" 18351 " } // namespace a", 18352 WhitesmithsBraceStyle); 18353 18354 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner; 18355 verifyFormat("namespace a\n" 18356 " {\n" 18357 "namespace b\n" 18358 " {\n" 18359 " class A\n" 18360 " {\n" 18361 " void f()\n" 18362 " {\n" 18363 " if (true)\n" 18364 " {\n" 18365 " a();\n" 18366 " b();\n" 18367 " }\n" 18368 " }\n" 18369 " void g()\n" 18370 " {\n" 18371 " return;\n" 18372 " }\n" 18373 " };\n" 18374 " struct B\n" 18375 " {\n" 18376 " int x;\n" 18377 " };\n" 18378 " } // namespace b\n" 18379 " } // namespace a", 18380 WhitesmithsBraceStyle); 18381 18382 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All; 18383 verifyFormat("namespace a\n" 18384 " {\n" 18385 " namespace b\n" 18386 " {\n" 18387 " class A\n" 18388 " {\n" 18389 " void f()\n" 18390 " {\n" 18391 " if (true)\n" 18392 " {\n" 18393 " a();\n" 18394 " b();\n" 18395 " }\n" 18396 " }\n" 18397 " void g()\n" 18398 " {\n" 18399 " return;\n" 18400 " }\n" 18401 " };\n" 18402 " struct B\n" 18403 " {\n" 18404 " int x;\n" 18405 " };\n" 18406 " } // namespace b\n" 18407 " } // namespace a", 18408 WhitesmithsBraceStyle); 18409 18410 verifyFormat("void f()\n" 18411 " {\n" 18412 " if (true)\n" 18413 " {\n" 18414 " a();\n" 18415 " }\n" 18416 " else if (false)\n" 18417 " {\n" 18418 " b();\n" 18419 " }\n" 18420 " else\n" 18421 " {\n" 18422 " c();\n" 18423 " }\n" 18424 " }\n", 18425 WhitesmithsBraceStyle); 18426 18427 verifyFormat("void f()\n" 18428 " {\n" 18429 " for (int i = 0; i < 10; ++i)\n" 18430 " {\n" 18431 " a();\n" 18432 " }\n" 18433 " while (false)\n" 18434 " {\n" 18435 " b();\n" 18436 " }\n" 18437 " do\n" 18438 " {\n" 18439 " c();\n" 18440 " } while (false)\n" 18441 " }\n", 18442 WhitesmithsBraceStyle); 18443 18444 WhitesmithsBraceStyle.IndentCaseLabels = true; 18445 verifyFormat("void switchTest1(int a)\n" 18446 " {\n" 18447 " switch (a)\n" 18448 " {\n" 18449 " case 2:\n" 18450 " {\n" 18451 " }\n" 18452 " break;\n" 18453 " }\n" 18454 " }\n", 18455 WhitesmithsBraceStyle); 18456 18457 verifyFormat("void switchTest2(int a)\n" 18458 " {\n" 18459 " switch (a)\n" 18460 " {\n" 18461 " case 0:\n" 18462 " break;\n" 18463 " case 1:\n" 18464 " {\n" 18465 " break;\n" 18466 " }\n" 18467 " case 2:\n" 18468 " {\n" 18469 " }\n" 18470 " break;\n" 18471 " default:\n" 18472 " break;\n" 18473 " }\n" 18474 " }\n", 18475 WhitesmithsBraceStyle); 18476 18477 verifyFormat("void switchTest3(int a)\n" 18478 " {\n" 18479 " switch (a)\n" 18480 " {\n" 18481 " case 0:\n" 18482 " {\n" 18483 " foo(x);\n" 18484 " }\n" 18485 " break;\n" 18486 " default:\n" 18487 " {\n" 18488 " foo(1);\n" 18489 " }\n" 18490 " break;\n" 18491 " }\n" 18492 " }\n", 18493 WhitesmithsBraceStyle); 18494 18495 WhitesmithsBraceStyle.IndentCaseLabels = false; 18496 18497 verifyFormat("void switchTest4(int a)\n" 18498 " {\n" 18499 " switch (a)\n" 18500 " {\n" 18501 " case 2:\n" 18502 " {\n" 18503 " }\n" 18504 " break;\n" 18505 " }\n" 18506 " }\n", 18507 WhitesmithsBraceStyle); 18508 18509 verifyFormat("void switchTest5(int a)\n" 18510 " {\n" 18511 " switch (a)\n" 18512 " {\n" 18513 " case 0:\n" 18514 " break;\n" 18515 " case 1:\n" 18516 " {\n" 18517 " foo();\n" 18518 " break;\n" 18519 " }\n" 18520 " case 2:\n" 18521 " {\n" 18522 " }\n" 18523 " break;\n" 18524 " default:\n" 18525 " break;\n" 18526 " }\n" 18527 " }\n", 18528 WhitesmithsBraceStyle); 18529 18530 verifyFormat("void switchTest6(int a)\n" 18531 " {\n" 18532 " switch (a)\n" 18533 " {\n" 18534 " case 0:\n" 18535 " {\n" 18536 " foo(x);\n" 18537 " }\n" 18538 " break;\n" 18539 " default:\n" 18540 " {\n" 18541 " foo(1);\n" 18542 " }\n" 18543 " break;\n" 18544 " }\n" 18545 " }\n", 18546 WhitesmithsBraceStyle); 18547 18548 verifyFormat("enum X\n" 18549 " {\n" 18550 " Y = 0, // testing\n" 18551 " }\n", 18552 WhitesmithsBraceStyle); 18553 18554 verifyFormat("enum X\n" 18555 " {\n" 18556 " Y = 0\n" 18557 " }\n", 18558 WhitesmithsBraceStyle); 18559 verifyFormat("enum X\n" 18560 " {\n" 18561 " Y = 0,\n" 18562 " Z = 1\n" 18563 " };\n", 18564 WhitesmithsBraceStyle); 18565 18566 verifyFormat("@interface BSApplicationController ()\n" 18567 " {\n" 18568 "@private\n" 18569 " id _extraIvar;\n" 18570 " }\n" 18571 "@end\n", 18572 WhitesmithsBraceStyle); 18573 18574 verifyFormat("#ifdef _DEBUG\n" 18575 "int foo(int i = 0)\n" 18576 "#else\n" 18577 "int foo(int i = 5)\n" 18578 "#endif\n" 18579 " {\n" 18580 " return i;\n" 18581 " }", 18582 WhitesmithsBraceStyle); 18583 18584 verifyFormat("void foo() {}\n" 18585 "void bar()\n" 18586 "#ifdef _DEBUG\n" 18587 " {\n" 18588 " foo();\n" 18589 " }\n" 18590 "#else\n" 18591 " {\n" 18592 " }\n" 18593 "#endif", 18594 WhitesmithsBraceStyle); 18595 18596 verifyFormat("void foobar()\n" 18597 " {\n" 18598 " int i = 5;\n" 18599 " }\n" 18600 "#ifdef _DEBUG\n" 18601 "void bar()\n" 18602 " {\n" 18603 " }\n" 18604 "#else\n" 18605 "void bar()\n" 18606 " {\n" 18607 " foobar();\n" 18608 " }\n" 18609 "#endif", 18610 WhitesmithsBraceStyle); 18611 18612 // This shouldn't affect ObjC blocks.. 18613 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n" 18614 " // ...\n" 18615 " int i;\n" 18616 "}];", 18617 WhitesmithsBraceStyle); 18618 verifyFormat("void (^block)(void) = ^{\n" 18619 " // ...\n" 18620 " int i;\n" 18621 "};", 18622 WhitesmithsBraceStyle); 18623 // .. or dict literals. 18624 verifyFormat("void f()\n" 18625 " {\n" 18626 " [object someMethod:@{@\"a\" : @\"b\"}];\n" 18627 " }", 18628 WhitesmithsBraceStyle); 18629 18630 verifyFormat("int f()\n" 18631 " { // comment\n" 18632 " return 42;\n" 18633 " }", 18634 WhitesmithsBraceStyle); 18635 18636 FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle; 18637 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = 18638 FormatStyle::SIS_OnlyFirstIf; 18639 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true; 18640 verifyFormat("void f(bool b)\n" 18641 " {\n" 18642 " if (b)\n" 18643 " {\n" 18644 " return;\n" 18645 " }\n" 18646 " }\n", 18647 BreakBeforeBraceShortIfs); 18648 verifyFormat("void f(bool b)\n" 18649 " {\n" 18650 " if (b) return;\n" 18651 " }\n", 18652 BreakBeforeBraceShortIfs); 18653 verifyFormat("void f(bool b)\n" 18654 " {\n" 18655 " while (b)\n" 18656 " {\n" 18657 " return;\n" 18658 " }\n" 18659 " }\n", 18660 BreakBeforeBraceShortIfs); 18661 } 18662 18663 TEST_F(FormatTest, GNUBraceBreaking) { 18664 FormatStyle GNUBraceStyle = getLLVMStyle(); 18665 GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU; 18666 verifyFormat("namespace a\n" 18667 "{\n" 18668 "class A\n" 18669 "{\n" 18670 " void f()\n" 18671 " {\n" 18672 " int a;\n" 18673 " {\n" 18674 " int b;\n" 18675 " }\n" 18676 " if (true)\n" 18677 " {\n" 18678 " a();\n" 18679 " b();\n" 18680 " }\n" 18681 " }\n" 18682 " void g() { return; }\n" 18683 "}\n" 18684 "} // namespace a", 18685 GNUBraceStyle); 18686 18687 verifyFormat("void f()\n" 18688 "{\n" 18689 " if (true)\n" 18690 " {\n" 18691 " a();\n" 18692 " }\n" 18693 " else if (false)\n" 18694 " {\n" 18695 " b();\n" 18696 " }\n" 18697 " else\n" 18698 " {\n" 18699 " c();\n" 18700 " }\n" 18701 "}\n", 18702 GNUBraceStyle); 18703 18704 verifyFormat("void f()\n" 18705 "{\n" 18706 " for (int i = 0; i < 10; ++i)\n" 18707 " {\n" 18708 " a();\n" 18709 " }\n" 18710 " while (false)\n" 18711 " {\n" 18712 " b();\n" 18713 " }\n" 18714 " do\n" 18715 " {\n" 18716 " c();\n" 18717 " }\n" 18718 " while (false);\n" 18719 "}\n", 18720 GNUBraceStyle); 18721 18722 verifyFormat("void f(int a)\n" 18723 "{\n" 18724 " switch (a)\n" 18725 " {\n" 18726 " case 0:\n" 18727 " break;\n" 18728 " case 1:\n" 18729 " {\n" 18730 " break;\n" 18731 " }\n" 18732 " case 2:\n" 18733 " {\n" 18734 " }\n" 18735 " break;\n" 18736 " default:\n" 18737 " break;\n" 18738 " }\n" 18739 "}\n", 18740 GNUBraceStyle); 18741 18742 verifyFormat("enum X\n" 18743 "{\n" 18744 " Y = 0,\n" 18745 "}\n", 18746 GNUBraceStyle); 18747 18748 verifyFormat("@interface BSApplicationController ()\n" 18749 "{\n" 18750 "@private\n" 18751 " id _extraIvar;\n" 18752 "}\n" 18753 "@end\n", 18754 GNUBraceStyle); 18755 18756 verifyFormat("#ifdef _DEBUG\n" 18757 "int foo(int i = 0)\n" 18758 "#else\n" 18759 "int foo(int i = 5)\n" 18760 "#endif\n" 18761 "{\n" 18762 " return i;\n" 18763 "}", 18764 GNUBraceStyle); 18765 18766 verifyFormat("void foo() {}\n" 18767 "void bar()\n" 18768 "#ifdef _DEBUG\n" 18769 "{\n" 18770 " foo();\n" 18771 "}\n" 18772 "#else\n" 18773 "{\n" 18774 "}\n" 18775 "#endif", 18776 GNUBraceStyle); 18777 18778 verifyFormat("void foobar() { int i = 5; }\n" 18779 "#ifdef _DEBUG\n" 18780 "void bar() {}\n" 18781 "#else\n" 18782 "void bar() { foobar(); }\n" 18783 "#endif", 18784 GNUBraceStyle); 18785 } 18786 18787 TEST_F(FormatTest, WebKitBraceBreaking) { 18788 FormatStyle WebKitBraceStyle = getLLVMStyle(); 18789 WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit; 18790 WebKitBraceStyle.FixNamespaceComments = false; 18791 verifyFormat("namespace a {\n" 18792 "class A {\n" 18793 " void f()\n" 18794 " {\n" 18795 " if (true) {\n" 18796 " a();\n" 18797 " b();\n" 18798 " }\n" 18799 " }\n" 18800 " void g() { return; }\n" 18801 "};\n" 18802 "enum E {\n" 18803 " A,\n" 18804 " // foo\n" 18805 " B,\n" 18806 " C\n" 18807 "};\n" 18808 "struct B {\n" 18809 " int x;\n" 18810 "};\n" 18811 "}\n", 18812 WebKitBraceStyle); 18813 verifyFormat("struct S {\n" 18814 " int Type;\n" 18815 " union {\n" 18816 " int x;\n" 18817 " double y;\n" 18818 " } Value;\n" 18819 " class C {\n" 18820 " MyFavoriteType Value;\n" 18821 " } Class;\n" 18822 "};\n", 18823 WebKitBraceStyle); 18824 } 18825 18826 TEST_F(FormatTest, CatchExceptionReferenceBinding) { 18827 verifyFormat("void f() {\n" 18828 " try {\n" 18829 " } catch (const Exception &e) {\n" 18830 " }\n" 18831 "}\n", 18832 getLLVMStyle()); 18833 } 18834 18835 TEST_F(FormatTest, CatchAlignArrayOfStructuresRightAlignment) { 18836 auto Style = getLLVMStyle(); 18837 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 18838 Style.AlignConsecutiveAssignments = 18839 FormatStyle::AlignConsecutiveStyle::ACS_Consecutive; 18840 Style.AlignConsecutiveDeclarations = 18841 FormatStyle::AlignConsecutiveStyle::ACS_Consecutive; 18842 verifyFormat("struct test demo[] = {\n" 18843 " {56, 23, \"hello\"},\n" 18844 " {-1, 93463, \"world\"},\n" 18845 " { 7, 5, \"!!\"}\n" 18846 "};\n", 18847 Style); 18848 18849 verifyFormat("struct test demo[] = {\n" 18850 " {56, 23, \"hello\"}, // first line\n" 18851 " {-1, 93463, \"world\"}, // second line\n" 18852 " { 7, 5, \"!!\"} // third line\n" 18853 "};\n", 18854 Style); 18855 18856 verifyFormat("struct test demo[4] = {\n" 18857 " { 56, 23, 21, \"oh\"}, // first line\n" 18858 " { -1, 93463, 22, \"my\"}, // second line\n" 18859 " { 7, 5, 1, \"goodness\"} // third line\n" 18860 " {234, 5, 1, \"gracious\"} // fourth line\n" 18861 "};\n", 18862 Style); 18863 18864 verifyFormat("struct test demo[3] = {\n" 18865 " {56, 23, \"hello\"},\n" 18866 " {-1, 93463, \"world\"},\n" 18867 " { 7, 5, \"!!\"}\n" 18868 "};\n", 18869 Style); 18870 18871 verifyFormat("struct test demo[3] = {\n" 18872 " {int{56}, 23, \"hello\"},\n" 18873 " {int{-1}, 93463, \"world\"},\n" 18874 " { int{7}, 5, \"!!\"}\n" 18875 "};\n", 18876 Style); 18877 18878 verifyFormat("struct test demo[] = {\n" 18879 " {56, 23, \"hello\"},\n" 18880 " {-1, 93463, \"world\"},\n" 18881 " { 7, 5, \"!!\"},\n" 18882 "};\n", 18883 Style); 18884 18885 verifyFormat("test demo[] = {\n" 18886 " {56, 23, \"hello\"},\n" 18887 " {-1, 93463, \"world\"},\n" 18888 " { 7, 5, \"!!\"},\n" 18889 "};\n", 18890 Style); 18891 18892 verifyFormat("demo = std::array<struct test, 3>{\n" 18893 " test{56, 23, \"hello\"},\n" 18894 " test{-1, 93463, \"world\"},\n" 18895 " test{ 7, 5, \"!!\"},\n" 18896 "};\n", 18897 Style); 18898 18899 verifyFormat("test demo[] = {\n" 18900 " {56, 23, \"hello\"},\n" 18901 "#if X\n" 18902 " {-1, 93463, \"world\"},\n" 18903 "#endif\n" 18904 " { 7, 5, \"!!\"}\n" 18905 "};\n", 18906 Style); 18907 18908 verifyFormat( 18909 "test demo[] = {\n" 18910 " { 7, 23,\n" 18911 " \"hello world i am a very long line that really, in any\"\n" 18912 " \"just world, ought to be split over multiple lines\"},\n" 18913 " {-1, 93463, \"world\"},\n" 18914 " {56, 5, \"!!\"}\n" 18915 "};\n", 18916 Style); 18917 18918 verifyFormat("return GradForUnaryCwise(g, {\n" 18919 " {{\"sign\"}, \"Sign\", " 18920 " {\"x\", \"dy\"}},\n" 18921 " { {\"dx\"}, \"Mul\", {\"dy\"" 18922 ", \"sign\"}},\n" 18923 "});\n", 18924 Style); 18925 18926 Style.ColumnLimit = 0; 18927 EXPECT_EQ( 18928 "test demo[] = {\n" 18929 " {56, 23, \"hello world i am a very long line that really, " 18930 "in any just world, ought to be split over multiple lines\"},\n" 18931 " {-1, 93463, " 18932 " \"world\"},\n" 18933 " { 7, 5, " 18934 " \"!!\"},\n" 18935 "};", 18936 format("test demo[] = {{56, 23, \"hello world i am a very long line " 18937 "that really, in any just world, ought to be split over multiple " 18938 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 18939 Style)); 18940 18941 Style.ColumnLimit = 80; 18942 verifyFormat("test demo[] = {\n" 18943 " {56, 23, /* a comment */ \"hello\"},\n" 18944 " {-1, 93463, \"world\"},\n" 18945 " { 7, 5, \"!!\"}\n" 18946 "};\n", 18947 Style); 18948 18949 verifyFormat("test demo[] = {\n" 18950 " {56, 23, \"hello\"},\n" 18951 " {-1, 93463, \"world\" /* comment here */},\n" 18952 " { 7, 5, \"!!\"}\n" 18953 "};\n", 18954 Style); 18955 18956 verifyFormat("test demo[] = {\n" 18957 " {56, /* a comment */ 23, \"hello\"},\n" 18958 " {-1, 93463, \"world\"},\n" 18959 " { 7, 5, \"!!\"}\n" 18960 "};\n", 18961 Style); 18962 18963 Style.ColumnLimit = 20; 18964 EXPECT_EQ( 18965 "demo = std::array<\n" 18966 " struct test, 3>{\n" 18967 " test{\n" 18968 " 56, 23,\n" 18969 " \"hello \"\n" 18970 " \"world i \"\n" 18971 " \"am a very \"\n" 18972 " \"long line \"\n" 18973 " \"that \"\n" 18974 " \"really, \"\n" 18975 " \"in any \"\n" 18976 " \"just \"\n" 18977 " \"world, \"\n" 18978 " \"ought to \"\n" 18979 " \"be split \"\n" 18980 " \"over \"\n" 18981 " \"multiple \"\n" 18982 " \"lines\"},\n" 18983 " test{-1, 93463,\n" 18984 " \"world\"},\n" 18985 " test{ 7, 5,\n" 18986 " \"!!\" },\n" 18987 "};", 18988 format("demo = std::array<struct test, 3>{test{56, 23, \"hello world " 18989 "i am a very long line that really, in any just world, ought " 18990 "to be split over multiple lines\"},test{-1, 93463, \"world\"}," 18991 "test{7, 5, \"!!\"},};", 18992 Style)); 18993 // This caused a core dump by enabling Alignment in the LLVMStyle globally 18994 Style = getLLVMStyleWithColumns(50); 18995 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 18996 verifyFormat("static A x = {\n" 18997 " {{init1, init2, init3, init4},\n" 18998 " {init1, init2, init3, init4}}\n" 18999 "};", 19000 Style); 19001 Style.ColumnLimit = 100; 19002 EXPECT_EQ( 19003 "test demo[] = {\n" 19004 " {56, 23,\n" 19005 " \"hello world i am a very long line that really, in any just world" 19006 ", ought to be split over \"\n" 19007 " \"multiple lines\" },\n" 19008 " {-1, 93463, \"world\"},\n" 19009 " { 7, 5, \"!!\"},\n" 19010 "};", 19011 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19012 "that really, in any just world, ought to be split over multiple " 19013 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19014 Style)); 19015 19016 Style = getLLVMStyleWithColumns(50); 19017 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 19018 Style.AlignConsecutiveAssignments = 19019 FormatStyle::AlignConsecutiveStyle::ACS_Consecutive; 19020 Style.AlignConsecutiveDeclarations = 19021 FormatStyle::AlignConsecutiveStyle::ACS_Consecutive; 19022 verifyFormat("struct test demo[] = {\n" 19023 " {56, 23, \"hello\"},\n" 19024 " {-1, 93463, \"world\"},\n" 19025 " { 7, 5, \"!!\"}\n" 19026 "};\n" 19027 "static A x = {\n" 19028 " {{init1, init2, init3, init4},\n" 19029 " {init1, init2, init3, init4}}\n" 19030 "};", 19031 Style); 19032 Style.ColumnLimit = 100; 19033 Style.AlignConsecutiveAssignments = 19034 FormatStyle::AlignConsecutiveStyle::ACS_AcrossComments; 19035 Style.AlignConsecutiveDeclarations = 19036 FormatStyle::AlignConsecutiveStyle::ACS_AcrossComments; 19037 verifyFormat("struct test demo[] = {\n" 19038 " {56, 23, \"hello\"},\n" 19039 " {-1, 93463, \"world\"},\n" 19040 " { 7, 5, \"!!\"}\n" 19041 "};\n" 19042 "struct test demo[4] = {\n" 19043 " { 56, 23, 21, \"oh\"}, // first line\n" 19044 " { -1, 93463, 22, \"my\"}, // second line\n" 19045 " { 7, 5, 1, \"goodness\"} // third line\n" 19046 " {234, 5, 1, \"gracious\"} // fourth line\n" 19047 "};\n", 19048 Style); 19049 EXPECT_EQ( 19050 "test demo[] = {\n" 19051 " {56,\n" 19052 " \"hello world i am a very long line that really, in any just world" 19053 ", ought to be split over \"\n" 19054 " \"multiple lines\", 23},\n" 19055 " {-1, \"world\", 93463},\n" 19056 " { 7, \"!!\", 5},\n" 19057 "};", 19058 format("test demo[] = {{56, \"hello world i am a very long line " 19059 "that really, in any just world, ought to be split over multiple " 19060 "lines\", 23},{-1, \"world\", 93463},{7, \"!!\", 5},};", 19061 Style)); 19062 } 19063 19064 TEST_F(FormatTest, CatchAlignArrayOfStructuresLeftAlignment) { 19065 auto Style = getLLVMStyle(); 19066 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 19067 /* FIXME: This case gets misformatted. 19068 verifyFormat("auto foo = Items{\n" 19069 " Section{0, bar(), },\n" 19070 " Section{1, boo() }\n" 19071 "};\n", 19072 Style); 19073 */ 19074 verifyFormat("auto foo = Items{\n" 19075 " Section{\n" 19076 " 0, bar(),\n" 19077 " }\n" 19078 "};\n", 19079 Style); 19080 verifyFormat("struct test demo[] = {\n" 19081 " {56, 23, \"hello\"},\n" 19082 " {-1, 93463, \"world\"},\n" 19083 " {7, 5, \"!!\" }\n" 19084 "};\n", 19085 Style); 19086 verifyFormat("struct test demo[] = {\n" 19087 " {56, 23, \"hello\"}, // first line\n" 19088 " {-1, 93463, \"world\"}, // second line\n" 19089 " {7, 5, \"!!\" } // third line\n" 19090 "};\n", 19091 Style); 19092 verifyFormat("struct test demo[4] = {\n" 19093 " {56, 23, 21, \"oh\" }, // first line\n" 19094 " {-1, 93463, 22, \"my\" }, // second line\n" 19095 " {7, 5, 1, \"goodness\"} // third line\n" 19096 " {234, 5, 1, \"gracious\"} // fourth line\n" 19097 "};\n", 19098 Style); 19099 verifyFormat("struct test demo[3] = {\n" 19100 " {56, 23, \"hello\"},\n" 19101 " {-1, 93463, \"world\"},\n" 19102 " {7, 5, \"!!\" }\n" 19103 "};\n", 19104 Style); 19105 19106 verifyFormat("struct test demo[3] = {\n" 19107 " {int{56}, 23, \"hello\"},\n" 19108 " {int{-1}, 93463, \"world\"},\n" 19109 " {int{7}, 5, \"!!\" }\n" 19110 "};\n", 19111 Style); 19112 verifyFormat("struct test demo[] = {\n" 19113 " {56, 23, \"hello\"},\n" 19114 " {-1, 93463, \"world\"},\n" 19115 " {7, 5, \"!!\" },\n" 19116 "};\n", 19117 Style); 19118 verifyFormat("test demo[] = {\n" 19119 " {56, 23, \"hello\"},\n" 19120 " {-1, 93463, \"world\"},\n" 19121 " {7, 5, \"!!\" },\n" 19122 "};\n", 19123 Style); 19124 verifyFormat("demo = std::array<struct test, 3>{\n" 19125 " test{56, 23, \"hello\"},\n" 19126 " test{-1, 93463, \"world\"},\n" 19127 " test{7, 5, \"!!\" },\n" 19128 "};\n", 19129 Style); 19130 verifyFormat("test demo[] = {\n" 19131 " {56, 23, \"hello\"},\n" 19132 "#if X\n" 19133 " {-1, 93463, \"world\"},\n" 19134 "#endif\n" 19135 " {7, 5, \"!!\" }\n" 19136 "};\n", 19137 Style); 19138 verifyFormat( 19139 "test demo[] = {\n" 19140 " {7, 23,\n" 19141 " \"hello world i am a very long line that really, in any\"\n" 19142 " \"just world, ought to be split over multiple lines\"},\n" 19143 " {-1, 93463, \"world\" },\n" 19144 " {56, 5, \"!!\" }\n" 19145 "};\n", 19146 Style); 19147 19148 verifyFormat("return GradForUnaryCwise(g, {\n" 19149 " {{\"sign\"}, \"Sign\", {\"x\", " 19150 "\"dy\"} },\n" 19151 " {{\"dx\"}, \"Mul\", " 19152 "{\"dy\", \"sign\"}},\n" 19153 "});\n", 19154 Style); 19155 19156 Style.ColumnLimit = 0; 19157 EXPECT_EQ( 19158 "test demo[] = {\n" 19159 " {56, 23, \"hello world i am a very long line that really, in any " 19160 "just world, ought to be split over multiple lines\"},\n" 19161 " {-1, 93463, \"world\" " 19162 " },\n" 19163 " {7, 5, \"!!\" " 19164 " },\n" 19165 "};", 19166 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19167 "that really, in any just world, ought to be split over multiple " 19168 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19169 Style)); 19170 19171 Style.ColumnLimit = 80; 19172 verifyFormat("test demo[] = {\n" 19173 " {56, 23, /* a comment */ \"hello\"},\n" 19174 " {-1, 93463, \"world\" },\n" 19175 " {7, 5, \"!!\" }\n" 19176 "};\n", 19177 Style); 19178 19179 verifyFormat("test demo[] = {\n" 19180 " {56, 23, \"hello\" },\n" 19181 " {-1, 93463, \"world\" /* comment here */},\n" 19182 " {7, 5, \"!!\" }\n" 19183 "};\n", 19184 Style); 19185 19186 verifyFormat("test demo[] = {\n" 19187 " {56, /* a comment */ 23, \"hello\"},\n" 19188 " {-1, 93463, \"world\"},\n" 19189 " {7, 5, \"!!\" }\n" 19190 "};\n", 19191 Style); 19192 19193 Style.ColumnLimit = 20; 19194 EXPECT_EQ( 19195 "demo = std::array<\n" 19196 " struct test, 3>{\n" 19197 " test{\n" 19198 " 56, 23,\n" 19199 " \"hello \"\n" 19200 " \"world i \"\n" 19201 " \"am a very \"\n" 19202 " \"long line \"\n" 19203 " \"that \"\n" 19204 " \"really, \"\n" 19205 " \"in any \"\n" 19206 " \"just \"\n" 19207 " \"world, \"\n" 19208 " \"ought to \"\n" 19209 " \"be split \"\n" 19210 " \"over \"\n" 19211 " \"multiple \"\n" 19212 " \"lines\"},\n" 19213 " test{-1, 93463,\n" 19214 " \"world\"},\n" 19215 " test{7, 5,\n" 19216 " \"!!\" },\n" 19217 "};", 19218 format("demo = std::array<struct test, 3>{test{56, 23, \"hello world " 19219 "i am a very long line that really, in any just world, ought " 19220 "to be split over multiple lines\"},test{-1, 93463, \"world\"}," 19221 "test{7, 5, \"!!\"},};", 19222 Style)); 19223 19224 // This caused a core dump by enabling Alignment in the LLVMStyle globally 19225 Style = getLLVMStyleWithColumns(50); 19226 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 19227 verifyFormat("static A x = {\n" 19228 " {{init1, init2, init3, init4},\n" 19229 " {init1, init2, init3, init4}}\n" 19230 "};", 19231 Style); 19232 Style.ColumnLimit = 100; 19233 EXPECT_EQ( 19234 "test demo[] = {\n" 19235 " {56, 23,\n" 19236 " \"hello world i am a very long line that really, in any just world" 19237 ", ought to be split over \"\n" 19238 " \"multiple lines\" },\n" 19239 " {-1, 93463, \"world\"},\n" 19240 " {7, 5, \"!!\" },\n" 19241 "};", 19242 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19243 "that really, in any just world, ought to be split over multiple " 19244 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19245 Style)); 19246 } 19247 19248 TEST_F(FormatTest, UnderstandsPragmas) { 19249 verifyFormat("#pragma omp reduction(| : var)"); 19250 verifyFormat("#pragma omp reduction(+ : var)"); 19251 19252 EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string " 19253 "(including parentheses).", 19254 format("#pragma mark Any non-hyphenated or hyphenated string " 19255 "(including parentheses).")); 19256 } 19257 19258 TEST_F(FormatTest, UnderstandPragmaOption) { 19259 verifyFormat("#pragma option -C -A"); 19260 19261 EXPECT_EQ("#pragma option -C -A", format("#pragma option -C -A")); 19262 } 19263 19264 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) { 19265 FormatStyle Style = getLLVMStyleWithColumns(20); 19266 19267 // See PR41213 19268 EXPECT_EQ("/*\n" 19269 " *\t9012345\n" 19270 " * /8901\n" 19271 " */", 19272 format("/*\n" 19273 " *\t9012345 /8901\n" 19274 " */", 19275 Style)); 19276 EXPECT_EQ("/*\n" 19277 " *345678\n" 19278 " *\t/8901\n" 19279 " */", 19280 format("/*\n" 19281 " *345678\t/8901\n" 19282 " */", 19283 Style)); 19284 19285 verifyFormat("int a; // the\n" 19286 " // comment", 19287 Style); 19288 EXPECT_EQ("int a; /* first line\n" 19289 " * second\n" 19290 " * line third\n" 19291 " * line\n" 19292 " */", 19293 format("int a; /* first line\n" 19294 " * second\n" 19295 " * line third\n" 19296 " * line\n" 19297 " */", 19298 Style)); 19299 EXPECT_EQ("int a; // first line\n" 19300 " // second\n" 19301 " // line third\n" 19302 " // line", 19303 format("int a; // first line\n" 19304 " // second line\n" 19305 " // third line", 19306 Style)); 19307 19308 Style.PenaltyExcessCharacter = 90; 19309 verifyFormat("int a; // the comment", Style); 19310 EXPECT_EQ("int a; // the comment\n" 19311 " // aaa", 19312 format("int a; // the comment aaa", Style)); 19313 EXPECT_EQ("int a; /* first line\n" 19314 " * second line\n" 19315 " * third line\n" 19316 " */", 19317 format("int a; /* first line\n" 19318 " * second line\n" 19319 " * third line\n" 19320 " */", 19321 Style)); 19322 EXPECT_EQ("int a; // first line\n" 19323 " // second line\n" 19324 " // third line", 19325 format("int a; // first line\n" 19326 " // second line\n" 19327 " // third line", 19328 Style)); 19329 // FIXME: Investigate why this is not getting the same layout as the test 19330 // above. 19331 EXPECT_EQ("int a; /* first line\n" 19332 " * second line\n" 19333 " * third line\n" 19334 " */", 19335 format("int a; /* first line second line third line" 19336 "\n*/", 19337 Style)); 19338 19339 EXPECT_EQ("// foo bar baz bazfoo\n" 19340 "// foo bar foo bar\n", 19341 format("// foo bar baz bazfoo\n" 19342 "// foo bar foo bar\n", 19343 Style)); 19344 EXPECT_EQ("// foo bar baz bazfoo\n" 19345 "// foo bar foo bar\n", 19346 format("// foo bar baz bazfoo\n" 19347 "// foo bar foo bar\n", 19348 Style)); 19349 19350 // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the 19351 // next one. 19352 EXPECT_EQ("// foo bar baz bazfoo\n" 19353 "// bar foo bar\n", 19354 format("// foo bar baz bazfoo bar\n" 19355 "// foo bar\n", 19356 Style)); 19357 19358 EXPECT_EQ("// foo bar baz bazfoo\n" 19359 "// foo bar baz bazfoo\n" 19360 "// bar foo bar\n", 19361 format("// foo bar baz bazfoo\n" 19362 "// foo bar baz bazfoo bar\n" 19363 "// foo bar\n", 19364 Style)); 19365 19366 EXPECT_EQ("// foo bar baz bazfoo\n" 19367 "// foo bar baz bazfoo\n" 19368 "// bar foo bar\n", 19369 format("// foo bar baz bazfoo\n" 19370 "// foo bar baz bazfoo bar\n" 19371 "// foo bar\n", 19372 Style)); 19373 19374 // Make sure we do not keep protruding characters if strict mode reflow is 19375 // cheaper than keeping protruding characters. 19376 Style.ColumnLimit = 21; 19377 EXPECT_EQ( 19378 "// foo foo foo foo\n" 19379 "// foo foo foo foo\n" 19380 "// foo foo foo foo\n", 19381 format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style)); 19382 19383 EXPECT_EQ("int a = /* long block\n" 19384 " comment */\n" 19385 " 42;", 19386 format("int a = /* long block comment */ 42;", Style)); 19387 } 19388 19389 TEST_F(FormatTest, BreakPenaltyAfterLParen) { 19390 FormatStyle Style = getLLVMStyle(); 19391 Style.ColumnLimit = 8; 19392 Style.PenaltyExcessCharacter = 15; 19393 verifyFormat("int foo(\n" 19394 " int aaaaaaaaaaaaaaaaaaaaaaaa);", 19395 Style); 19396 Style.PenaltyBreakOpenParenthesis = 200; 19397 EXPECT_EQ("int foo(int aaaaaaaaaaaaaaaaaaaaaaaa);", 19398 format("int foo(\n" 19399 " int aaaaaaaaaaaaaaaaaaaaaaaa);", 19400 Style)); 19401 } 19402 19403 TEST_F(FormatTest, BreakPenaltyAfterCastLParen) { 19404 FormatStyle Style = getLLVMStyle(); 19405 Style.ColumnLimit = 5; 19406 Style.PenaltyExcessCharacter = 150; 19407 verifyFormat("foo((\n" 19408 " int)aaaaaaaaaaaaaaaaaaaaaaaa);", 19409 19410 Style); 19411 Style.PenaltyBreakOpenParenthesis = 100000; 19412 EXPECT_EQ("foo((int)\n" 19413 " aaaaaaaaaaaaaaaaaaaaaaaa);", 19414 format("foo((\n" 19415 "int)aaaaaaaaaaaaaaaaaaaaaaaa);", 19416 Style)); 19417 } 19418 19419 TEST_F(FormatTest, BreakPenaltyAfterForLoopLParen) { 19420 FormatStyle Style = getLLVMStyle(); 19421 Style.ColumnLimit = 4; 19422 Style.PenaltyExcessCharacter = 100; 19423 verifyFormat("for (\n" 19424 " int iiiiiiiiiiiiiiiii =\n" 19425 " 0;\n" 19426 " iiiiiiiiiiiiiiiii <\n" 19427 " 2;\n" 19428 " iiiiiiiiiiiiiiiii++) {\n" 19429 "}", 19430 19431 Style); 19432 Style.PenaltyBreakOpenParenthesis = 1250; 19433 EXPECT_EQ("for (int iiiiiiiiiiiiiiiii =\n" 19434 " 0;\n" 19435 " iiiiiiiiiiiiiiiii <\n" 19436 " 2;\n" 19437 " iiiiiiiiiiiiiiiii++) {\n" 19438 "}", 19439 format("for (\n" 19440 " int iiiiiiiiiiiiiiiii =\n" 19441 " 0;\n" 19442 " iiiiiiiiiiiiiiiii <\n" 19443 " 2;\n" 19444 " iiiiiiiiiiiiiiiii++) {\n" 19445 "}", 19446 Style)); 19447 } 19448 19449 #define EXPECT_ALL_STYLES_EQUAL(Styles) \ 19450 for (size_t i = 1; i < Styles.size(); ++i) \ 19451 EXPECT_EQ(Styles[0], Styles[i]) \ 19452 << "Style #" << i << " of " << Styles.size() << " differs from Style #0" 19453 19454 TEST_F(FormatTest, GetsPredefinedStyleByName) { 19455 SmallVector<FormatStyle, 3> Styles; 19456 Styles.resize(3); 19457 19458 Styles[0] = getLLVMStyle(); 19459 EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1])); 19460 EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2])); 19461 EXPECT_ALL_STYLES_EQUAL(Styles); 19462 19463 Styles[0] = getGoogleStyle(); 19464 EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1])); 19465 EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2])); 19466 EXPECT_ALL_STYLES_EQUAL(Styles); 19467 19468 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript); 19469 EXPECT_TRUE( 19470 getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1])); 19471 EXPECT_TRUE( 19472 getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2])); 19473 EXPECT_ALL_STYLES_EQUAL(Styles); 19474 19475 Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp); 19476 EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1])); 19477 EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2])); 19478 EXPECT_ALL_STYLES_EQUAL(Styles); 19479 19480 Styles[0] = getMozillaStyle(); 19481 EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1])); 19482 EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2])); 19483 EXPECT_ALL_STYLES_EQUAL(Styles); 19484 19485 Styles[0] = getWebKitStyle(); 19486 EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1])); 19487 EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2])); 19488 EXPECT_ALL_STYLES_EQUAL(Styles); 19489 19490 Styles[0] = getGNUStyle(); 19491 EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1])); 19492 EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2])); 19493 EXPECT_ALL_STYLES_EQUAL(Styles); 19494 19495 EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0])); 19496 } 19497 19498 TEST_F(FormatTest, GetsCorrectBasedOnStyle) { 19499 SmallVector<FormatStyle, 8> Styles; 19500 Styles.resize(2); 19501 19502 Styles[0] = getGoogleStyle(); 19503 Styles[1] = getLLVMStyle(); 19504 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value()); 19505 EXPECT_ALL_STYLES_EQUAL(Styles); 19506 19507 Styles.resize(5); 19508 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript); 19509 Styles[1] = getLLVMStyle(); 19510 Styles[1].Language = FormatStyle::LK_JavaScript; 19511 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value()); 19512 19513 Styles[2] = getLLVMStyle(); 19514 Styles[2].Language = FormatStyle::LK_JavaScript; 19515 EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n" 19516 "BasedOnStyle: Google", 19517 &Styles[2]) 19518 .value()); 19519 19520 Styles[3] = getLLVMStyle(); 19521 Styles[3].Language = FormatStyle::LK_JavaScript; 19522 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n" 19523 "Language: JavaScript", 19524 &Styles[3]) 19525 .value()); 19526 19527 Styles[4] = getLLVMStyle(); 19528 Styles[4].Language = FormatStyle::LK_JavaScript; 19529 EXPECT_EQ(0, parseConfiguration("---\n" 19530 "BasedOnStyle: LLVM\n" 19531 "IndentWidth: 123\n" 19532 "---\n" 19533 "BasedOnStyle: Google\n" 19534 "Language: JavaScript", 19535 &Styles[4]) 19536 .value()); 19537 EXPECT_ALL_STYLES_EQUAL(Styles); 19538 } 19539 19540 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME) \ 19541 Style.FIELD = false; \ 19542 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value()); \ 19543 EXPECT_TRUE(Style.FIELD); \ 19544 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value()); \ 19545 EXPECT_FALSE(Style.FIELD); 19546 19547 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD) 19548 19549 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME) \ 19550 Style.STRUCT.FIELD = false; \ 19551 EXPECT_EQ(0, \ 19552 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": true", &Style) \ 19553 .value()); \ 19554 EXPECT_TRUE(Style.STRUCT.FIELD); \ 19555 EXPECT_EQ(0, \ 19556 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": false", &Style) \ 19557 .value()); \ 19558 EXPECT_FALSE(Style.STRUCT.FIELD); 19559 19560 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD) \ 19561 CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD) 19562 19563 #define CHECK_PARSE(TEXT, FIELD, VALUE) \ 19564 EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!"; \ 19565 EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value()); \ 19566 EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!" 19567 19568 TEST_F(FormatTest, ParsesConfigurationBools) { 19569 FormatStyle Style = {}; 19570 Style.Language = FormatStyle::LK_Cpp; 19571 CHECK_PARSE_BOOL(AlignTrailingComments); 19572 CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine); 19573 CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine); 19574 CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine); 19575 CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine); 19576 CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine); 19577 CHECK_PARSE_BOOL(BinPackArguments); 19578 CHECK_PARSE_BOOL(BinPackParameters); 19579 CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations); 19580 CHECK_PARSE_BOOL(BreakBeforeTernaryOperators); 19581 CHECK_PARSE_BOOL(BreakStringLiterals); 19582 CHECK_PARSE_BOOL(CompactNamespaces); 19583 CHECK_PARSE_BOOL(DeriveLineEnding); 19584 CHECK_PARSE_BOOL(DerivePointerAlignment); 19585 CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding"); 19586 CHECK_PARSE_BOOL(DisableFormat); 19587 CHECK_PARSE_BOOL(IndentAccessModifiers); 19588 CHECK_PARSE_BOOL(IndentCaseLabels); 19589 CHECK_PARSE_BOOL(IndentCaseBlocks); 19590 CHECK_PARSE_BOOL(IndentGotoLabels); 19591 CHECK_PARSE_BOOL_FIELD(IndentRequiresClause, "IndentRequires"); 19592 CHECK_PARSE_BOOL(IndentRequiresClause); 19593 CHECK_PARSE_BOOL(IndentWrappedFunctionNames); 19594 CHECK_PARSE_BOOL(InsertBraces); 19595 CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks); 19596 CHECK_PARSE_BOOL(ObjCSpaceAfterProperty); 19597 CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList); 19598 CHECK_PARSE_BOOL(Cpp11BracedListStyle); 19599 CHECK_PARSE_BOOL(ReflowComments); 19600 CHECK_PARSE_BOOL(RemoveBracesLLVM); 19601 CHECK_PARSE_BOOL(SortUsingDeclarations); 19602 CHECK_PARSE_BOOL(SpacesInParentheses); 19603 CHECK_PARSE_BOOL(SpacesInSquareBrackets); 19604 CHECK_PARSE_BOOL(SpacesInConditionalStatement); 19605 CHECK_PARSE_BOOL(SpaceInEmptyBlock); 19606 CHECK_PARSE_BOOL(SpaceInEmptyParentheses); 19607 CHECK_PARSE_BOOL(SpacesInContainerLiterals); 19608 CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses); 19609 CHECK_PARSE_BOOL(SpaceAfterCStyleCast); 19610 CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword); 19611 CHECK_PARSE_BOOL(SpaceAfterLogicalNot); 19612 CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators); 19613 CHECK_PARSE_BOOL(SpaceBeforeCaseColon); 19614 CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList); 19615 CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon); 19616 CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon); 19617 CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon); 19618 CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets); 19619 CHECK_PARSE_BOOL(UseCRLF); 19620 19621 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel); 19622 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass); 19623 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum); 19624 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction); 19625 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace); 19626 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration); 19627 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct); 19628 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion); 19629 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock); 19630 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch); 19631 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse); 19632 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody); 19633 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile); 19634 CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces); 19635 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction); 19636 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord); 19637 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace); 19638 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterControlStatements); 19639 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterForeachMacros); 19640 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, 19641 AfterFunctionDeclarationName); 19642 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, 19643 AfterFunctionDefinitionName); 19644 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterIfMacros); 19645 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterOverloadedOperator); 19646 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, BeforeNonEmptyParentheses); 19647 } 19648 19649 #undef CHECK_PARSE_BOOL 19650 19651 TEST_F(FormatTest, ParsesConfiguration) { 19652 FormatStyle Style = {}; 19653 Style.Language = FormatStyle::LK_Cpp; 19654 CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234); 19655 CHECK_PARSE("ConstructorInitializerIndentWidth: 1234", 19656 ConstructorInitializerIndentWidth, 1234u); 19657 CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u); 19658 CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u); 19659 CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u); 19660 CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u); 19661 CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234", 19662 PenaltyBreakBeforeFirstCallParameter, 1234u); 19663 CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234", 19664 PenaltyBreakTemplateDeclaration, 1234u); 19665 CHECK_PARSE("PenaltyBreakOpenParenthesis: 1234", PenaltyBreakOpenParenthesis, 19666 1234u); 19667 CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u); 19668 CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234", 19669 PenaltyReturnTypeOnItsOwnLine, 1234u); 19670 CHECK_PARSE("SpacesBeforeTrailingComments: 1234", 19671 SpacesBeforeTrailingComments, 1234u); 19672 CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u); 19673 CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u); 19674 CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$"); 19675 19676 Style.QualifierAlignment = FormatStyle::QAS_Right; 19677 CHECK_PARSE("QualifierAlignment: Leave", QualifierAlignment, 19678 FormatStyle::QAS_Leave); 19679 CHECK_PARSE("QualifierAlignment: Right", QualifierAlignment, 19680 FormatStyle::QAS_Right); 19681 CHECK_PARSE("QualifierAlignment: Left", QualifierAlignment, 19682 FormatStyle::QAS_Left); 19683 CHECK_PARSE("QualifierAlignment: Custom", QualifierAlignment, 19684 FormatStyle::QAS_Custom); 19685 19686 Style.QualifierOrder.clear(); 19687 CHECK_PARSE("QualifierOrder: [ const, volatile, type ]", QualifierOrder, 19688 std::vector<std::string>({"const", "volatile", "type"})); 19689 Style.QualifierOrder.clear(); 19690 CHECK_PARSE("QualifierOrder: [const, type]", QualifierOrder, 19691 std::vector<std::string>({"const", "type"})); 19692 Style.QualifierOrder.clear(); 19693 CHECK_PARSE("QualifierOrder: [volatile, type]", QualifierOrder, 19694 std::vector<std::string>({"volatile", "type"})); 19695 19696 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 19697 CHECK_PARSE("AlignConsecutiveAssignments: None", AlignConsecutiveAssignments, 19698 FormatStyle::ACS_None); 19699 CHECK_PARSE("AlignConsecutiveAssignments: Consecutive", 19700 AlignConsecutiveAssignments, FormatStyle::ACS_Consecutive); 19701 CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLines", 19702 AlignConsecutiveAssignments, FormatStyle::ACS_AcrossEmptyLines); 19703 CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLinesAndComments", 19704 AlignConsecutiveAssignments, 19705 FormatStyle::ACS_AcrossEmptyLinesAndComments); 19706 // For backwards compability, false / true should still parse 19707 CHECK_PARSE("AlignConsecutiveAssignments: false", AlignConsecutiveAssignments, 19708 FormatStyle::ACS_None); 19709 CHECK_PARSE("AlignConsecutiveAssignments: true", AlignConsecutiveAssignments, 19710 FormatStyle::ACS_Consecutive); 19711 19712 Style.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive; 19713 CHECK_PARSE("AlignConsecutiveBitFields: None", AlignConsecutiveBitFields, 19714 FormatStyle::ACS_None); 19715 CHECK_PARSE("AlignConsecutiveBitFields: Consecutive", 19716 AlignConsecutiveBitFields, FormatStyle::ACS_Consecutive); 19717 CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLines", 19718 AlignConsecutiveBitFields, FormatStyle::ACS_AcrossEmptyLines); 19719 CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLinesAndComments", 19720 AlignConsecutiveBitFields, 19721 FormatStyle::ACS_AcrossEmptyLinesAndComments); 19722 // For backwards compability, false / true should still parse 19723 CHECK_PARSE("AlignConsecutiveBitFields: false", AlignConsecutiveBitFields, 19724 FormatStyle::ACS_None); 19725 CHECK_PARSE("AlignConsecutiveBitFields: true", AlignConsecutiveBitFields, 19726 FormatStyle::ACS_Consecutive); 19727 19728 Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 19729 CHECK_PARSE("AlignConsecutiveMacros: None", AlignConsecutiveMacros, 19730 FormatStyle::ACS_None); 19731 CHECK_PARSE("AlignConsecutiveMacros: Consecutive", AlignConsecutiveMacros, 19732 FormatStyle::ACS_Consecutive); 19733 CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLines", 19734 AlignConsecutiveMacros, FormatStyle::ACS_AcrossEmptyLines); 19735 CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLinesAndComments", 19736 AlignConsecutiveMacros, 19737 FormatStyle::ACS_AcrossEmptyLinesAndComments); 19738 // For backwards compability, false / true should still parse 19739 CHECK_PARSE("AlignConsecutiveMacros: false", AlignConsecutiveMacros, 19740 FormatStyle::ACS_None); 19741 CHECK_PARSE("AlignConsecutiveMacros: true", AlignConsecutiveMacros, 19742 FormatStyle::ACS_Consecutive); 19743 19744 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 19745 CHECK_PARSE("AlignConsecutiveDeclarations: None", 19746 AlignConsecutiveDeclarations, FormatStyle::ACS_None); 19747 CHECK_PARSE("AlignConsecutiveDeclarations: Consecutive", 19748 AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive); 19749 CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLines", 19750 AlignConsecutiveDeclarations, FormatStyle::ACS_AcrossEmptyLines); 19751 CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLinesAndComments", 19752 AlignConsecutiveDeclarations, 19753 FormatStyle::ACS_AcrossEmptyLinesAndComments); 19754 // For backwards compability, false / true should still parse 19755 CHECK_PARSE("AlignConsecutiveDeclarations: false", 19756 AlignConsecutiveDeclarations, FormatStyle::ACS_None); 19757 CHECK_PARSE("AlignConsecutiveDeclarations: true", 19758 AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive); 19759 19760 Style.PointerAlignment = FormatStyle::PAS_Middle; 19761 CHECK_PARSE("PointerAlignment: Left", PointerAlignment, 19762 FormatStyle::PAS_Left); 19763 CHECK_PARSE("PointerAlignment: Right", PointerAlignment, 19764 FormatStyle::PAS_Right); 19765 CHECK_PARSE("PointerAlignment: Middle", PointerAlignment, 19766 FormatStyle::PAS_Middle); 19767 Style.ReferenceAlignment = FormatStyle::RAS_Middle; 19768 CHECK_PARSE("ReferenceAlignment: Pointer", ReferenceAlignment, 19769 FormatStyle::RAS_Pointer); 19770 CHECK_PARSE("ReferenceAlignment: Left", ReferenceAlignment, 19771 FormatStyle::RAS_Left); 19772 CHECK_PARSE("ReferenceAlignment: Right", ReferenceAlignment, 19773 FormatStyle::RAS_Right); 19774 CHECK_PARSE("ReferenceAlignment: Middle", ReferenceAlignment, 19775 FormatStyle::RAS_Middle); 19776 // For backward compatibility: 19777 CHECK_PARSE("PointerBindsToType: Left", PointerAlignment, 19778 FormatStyle::PAS_Left); 19779 CHECK_PARSE("PointerBindsToType: Right", PointerAlignment, 19780 FormatStyle::PAS_Right); 19781 CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment, 19782 FormatStyle::PAS_Middle); 19783 19784 Style.Standard = FormatStyle::LS_Auto; 19785 CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03); 19786 CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11); 19787 CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14); 19788 CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17); 19789 CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20); 19790 CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto); 19791 CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest); 19792 // Legacy aliases: 19793 CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03); 19794 CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest); 19795 CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03); 19796 CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11); 19797 19798 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 19799 CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment", 19800 BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment); 19801 CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators, 19802 FormatStyle::BOS_None); 19803 CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators, 19804 FormatStyle::BOS_All); 19805 // For backward compatibility: 19806 CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators, 19807 FormatStyle::BOS_None); 19808 CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators, 19809 FormatStyle::BOS_All); 19810 19811 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 19812 CHECK_PARSE("BreakConstructorInitializers: BeforeComma", 19813 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma); 19814 CHECK_PARSE("BreakConstructorInitializers: AfterColon", 19815 BreakConstructorInitializers, FormatStyle::BCIS_AfterColon); 19816 CHECK_PARSE("BreakConstructorInitializers: BeforeColon", 19817 BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon); 19818 // For backward compatibility: 19819 CHECK_PARSE("BreakConstructorInitializersBeforeComma: true", 19820 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma); 19821 19822 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 19823 CHECK_PARSE("BreakInheritanceList: AfterComma", BreakInheritanceList, 19824 FormatStyle::BILS_AfterComma); 19825 CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList, 19826 FormatStyle::BILS_BeforeComma); 19827 CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList, 19828 FormatStyle::BILS_AfterColon); 19829 CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList, 19830 FormatStyle::BILS_BeforeColon); 19831 // For backward compatibility: 19832 CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList, 19833 FormatStyle::BILS_BeforeComma); 19834 19835 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 19836 CHECK_PARSE("PackConstructorInitializers: Never", PackConstructorInitializers, 19837 FormatStyle::PCIS_Never); 19838 CHECK_PARSE("PackConstructorInitializers: BinPack", 19839 PackConstructorInitializers, FormatStyle::PCIS_BinPack); 19840 CHECK_PARSE("PackConstructorInitializers: CurrentLine", 19841 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 19842 CHECK_PARSE("PackConstructorInitializers: NextLine", 19843 PackConstructorInitializers, FormatStyle::PCIS_NextLine); 19844 // For backward compatibility: 19845 CHECK_PARSE("BasedOnStyle: Google\n" 19846 "ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 19847 "AllowAllConstructorInitializersOnNextLine: false", 19848 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 19849 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 19850 CHECK_PARSE("BasedOnStyle: Google\n" 19851 "ConstructorInitializerAllOnOneLineOrOnePerLine: false", 19852 PackConstructorInitializers, FormatStyle::PCIS_BinPack); 19853 CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 19854 "AllowAllConstructorInitializersOnNextLine: true", 19855 PackConstructorInitializers, FormatStyle::PCIS_NextLine); 19856 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 19857 CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 19858 "AllowAllConstructorInitializersOnNextLine: false", 19859 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 19860 19861 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 19862 CHECK_PARSE("EmptyLineBeforeAccessModifier: Never", 19863 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never); 19864 CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave", 19865 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave); 19866 CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock", 19867 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock); 19868 CHECK_PARSE("EmptyLineBeforeAccessModifier: Always", 19869 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always); 19870 19871 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 19872 CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket, 19873 FormatStyle::BAS_Align); 19874 CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket, 19875 FormatStyle::BAS_DontAlign); 19876 CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket, 19877 FormatStyle::BAS_AlwaysBreak); 19878 CHECK_PARSE("AlignAfterOpenBracket: BlockIndent", AlignAfterOpenBracket, 19879 FormatStyle::BAS_BlockIndent); 19880 // For backward compatibility: 19881 CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket, 19882 FormatStyle::BAS_DontAlign); 19883 CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket, 19884 FormatStyle::BAS_Align); 19885 19886 Style.AlignEscapedNewlines = FormatStyle::ENAS_Left; 19887 CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines, 19888 FormatStyle::ENAS_DontAlign); 19889 CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines, 19890 FormatStyle::ENAS_Left); 19891 CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines, 19892 FormatStyle::ENAS_Right); 19893 // For backward compatibility: 19894 CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines, 19895 FormatStyle::ENAS_Left); 19896 CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines, 19897 FormatStyle::ENAS_Right); 19898 19899 Style.AlignOperands = FormatStyle::OAS_Align; 19900 CHECK_PARSE("AlignOperands: DontAlign", AlignOperands, 19901 FormatStyle::OAS_DontAlign); 19902 CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align); 19903 CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands, 19904 FormatStyle::OAS_AlignAfterOperator); 19905 // For backward compatibility: 19906 CHECK_PARSE("AlignOperands: false", AlignOperands, 19907 FormatStyle::OAS_DontAlign); 19908 CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align); 19909 19910 Style.UseTab = FormatStyle::UT_ForIndentation; 19911 CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never); 19912 CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation); 19913 CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always); 19914 CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab, 19915 FormatStyle::UT_ForContinuationAndIndentation); 19916 CHECK_PARSE("UseTab: AlignWithSpaces", UseTab, 19917 FormatStyle::UT_AlignWithSpaces); 19918 // For backward compatibility: 19919 CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never); 19920 CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always); 19921 19922 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 19923 CHECK_PARSE("AllowShortBlocksOnASingleLine: Never", 19924 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 19925 CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty", 19926 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty); 19927 CHECK_PARSE("AllowShortBlocksOnASingleLine: Always", 19928 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always); 19929 // For backward compatibility: 19930 CHECK_PARSE("AllowShortBlocksOnASingleLine: false", 19931 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 19932 CHECK_PARSE("AllowShortBlocksOnASingleLine: true", 19933 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always); 19934 19935 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 19936 CHECK_PARSE("AllowShortFunctionsOnASingleLine: None", 19937 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None); 19938 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline", 19939 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline); 19940 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty", 19941 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty); 19942 CHECK_PARSE("AllowShortFunctionsOnASingleLine: All", 19943 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All); 19944 // For backward compatibility: 19945 CHECK_PARSE("AllowShortFunctionsOnASingleLine: false", 19946 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None); 19947 CHECK_PARSE("AllowShortFunctionsOnASingleLine: true", 19948 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All); 19949 19950 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both; 19951 CHECK_PARSE("SpaceAroundPointerQualifiers: Default", 19952 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default); 19953 CHECK_PARSE("SpaceAroundPointerQualifiers: Before", 19954 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before); 19955 CHECK_PARSE("SpaceAroundPointerQualifiers: After", 19956 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After); 19957 CHECK_PARSE("SpaceAroundPointerQualifiers: Both", 19958 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both); 19959 19960 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 19961 CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens, 19962 FormatStyle::SBPO_Never); 19963 CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens, 19964 FormatStyle::SBPO_Always); 19965 CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens, 19966 FormatStyle::SBPO_ControlStatements); 19967 CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptControlMacros", 19968 SpaceBeforeParens, 19969 FormatStyle::SBPO_ControlStatementsExceptControlMacros); 19970 CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens, 19971 FormatStyle::SBPO_NonEmptyParentheses); 19972 CHECK_PARSE("SpaceBeforeParens: Custom", SpaceBeforeParens, 19973 FormatStyle::SBPO_Custom); 19974 // For backward compatibility: 19975 CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens, 19976 FormatStyle::SBPO_Never); 19977 CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens, 19978 FormatStyle::SBPO_ControlStatements); 19979 CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptForEachMacros", 19980 SpaceBeforeParens, 19981 FormatStyle::SBPO_ControlStatementsExceptControlMacros); 19982 19983 Style.ColumnLimit = 123; 19984 FormatStyle BaseStyle = getLLVMStyle(); 19985 CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit); 19986 CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u); 19987 19988 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 19989 CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces, 19990 FormatStyle::BS_Attach); 19991 CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces, 19992 FormatStyle::BS_Linux); 19993 CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces, 19994 FormatStyle::BS_Mozilla); 19995 CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces, 19996 FormatStyle::BS_Stroustrup); 19997 CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces, 19998 FormatStyle::BS_Allman); 19999 CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces, 20000 FormatStyle::BS_Whitesmiths); 20001 CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU); 20002 CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces, 20003 FormatStyle::BS_WebKit); 20004 CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces, 20005 FormatStyle::BS_Custom); 20006 20007 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never; 20008 CHECK_PARSE("BraceWrapping:\n" 20009 " AfterControlStatement: MultiLine", 20010 BraceWrapping.AfterControlStatement, 20011 FormatStyle::BWACS_MultiLine); 20012 CHECK_PARSE("BraceWrapping:\n" 20013 " AfterControlStatement: Always", 20014 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always); 20015 CHECK_PARSE("BraceWrapping:\n" 20016 " AfterControlStatement: Never", 20017 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never); 20018 // For backward compatibility: 20019 CHECK_PARSE("BraceWrapping:\n" 20020 " AfterControlStatement: true", 20021 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always); 20022 CHECK_PARSE("BraceWrapping:\n" 20023 " AfterControlStatement: false", 20024 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never); 20025 20026 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 20027 CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType, 20028 FormatStyle::RTBS_None); 20029 CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType, 20030 FormatStyle::RTBS_All); 20031 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel", 20032 AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel); 20033 CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions", 20034 AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions); 20035 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions", 20036 AlwaysBreakAfterReturnType, 20037 FormatStyle::RTBS_TopLevelDefinitions); 20038 20039 Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 20040 CHECK_PARSE("AlwaysBreakTemplateDeclarations: No", 20041 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No); 20042 CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine", 20043 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine); 20044 CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes", 20045 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes); 20046 CHECK_PARSE("AlwaysBreakTemplateDeclarations: false", 20047 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine); 20048 CHECK_PARSE("AlwaysBreakTemplateDeclarations: true", 20049 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes); 20050 20051 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All; 20052 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None", 20053 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None); 20054 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All", 20055 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All); 20056 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel", 20057 AlwaysBreakAfterDefinitionReturnType, 20058 FormatStyle::DRTBS_TopLevel); 20059 20060 Style.NamespaceIndentation = FormatStyle::NI_All; 20061 CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation, 20062 FormatStyle::NI_None); 20063 CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation, 20064 FormatStyle::NI_Inner); 20065 CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation, 20066 FormatStyle::NI_All); 20067 20068 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_OnlyFirstIf; 20069 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never", 20070 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never); 20071 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse", 20072 AllowShortIfStatementsOnASingleLine, 20073 FormatStyle::SIS_WithoutElse); 20074 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: OnlyFirstIf", 20075 AllowShortIfStatementsOnASingleLine, 20076 FormatStyle::SIS_OnlyFirstIf); 20077 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: AllIfsAndElse", 20078 AllowShortIfStatementsOnASingleLine, 20079 FormatStyle::SIS_AllIfsAndElse); 20080 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always", 20081 AllowShortIfStatementsOnASingleLine, 20082 FormatStyle::SIS_OnlyFirstIf); 20083 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false", 20084 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never); 20085 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true", 20086 AllowShortIfStatementsOnASingleLine, 20087 FormatStyle::SIS_WithoutElse); 20088 20089 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 20090 CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock, 20091 FormatStyle::IEBS_AfterExternBlock); 20092 CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock, 20093 FormatStyle::IEBS_Indent); 20094 CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock, 20095 FormatStyle::IEBS_NoIndent); 20096 CHECK_PARSE("IndentExternBlock: true", IndentExternBlock, 20097 FormatStyle::IEBS_Indent); 20098 CHECK_PARSE("IndentExternBlock: false", IndentExternBlock, 20099 FormatStyle::IEBS_NoIndent); 20100 20101 Style.BitFieldColonSpacing = FormatStyle::BFCS_None; 20102 CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing, 20103 FormatStyle::BFCS_Both); 20104 CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing, 20105 FormatStyle::BFCS_None); 20106 CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing, 20107 FormatStyle::BFCS_Before); 20108 CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing, 20109 FormatStyle::BFCS_After); 20110 20111 Style.SortJavaStaticImport = FormatStyle::SJSIO_Before; 20112 CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport, 20113 FormatStyle::SJSIO_After); 20114 CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport, 20115 FormatStyle::SJSIO_Before); 20116 20117 // FIXME: This is required because parsing a configuration simply overwrites 20118 // the first N elements of the list instead of resetting it. 20119 Style.ForEachMacros.clear(); 20120 std::vector<std::string> BoostForeach; 20121 BoostForeach.push_back("BOOST_FOREACH"); 20122 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach); 20123 std::vector<std::string> BoostAndQForeach; 20124 BoostAndQForeach.push_back("BOOST_FOREACH"); 20125 BoostAndQForeach.push_back("Q_FOREACH"); 20126 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros, 20127 BoostAndQForeach); 20128 20129 Style.IfMacros.clear(); 20130 std::vector<std::string> CustomIfs; 20131 CustomIfs.push_back("MYIF"); 20132 CHECK_PARSE("IfMacros: [MYIF]", IfMacros, CustomIfs); 20133 20134 Style.AttributeMacros.clear(); 20135 CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros, 20136 std::vector<std::string>{"__capability"}); 20137 CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros, 20138 std::vector<std::string>({"attr1", "attr2"})); 20139 20140 Style.StatementAttributeLikeMacros.clear(); 20141 CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]", 20142 StatementAttributeLikeMacros, 20143 std::vector<std::string>({"emit", "Q_EMIT"})); 20144 20145 Style.StatementMacros.clear(); 20146 CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros, 20147 std::vector<std::string>{"QUNUSED"}); 20148 CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros, 20149 std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"})); 20150 20151 Style.NamespaceMacros.clear(); 20152 CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros, 20153 std::vector<std::string>{"TESTSUITE"}); 20154 CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros, 20155 std::vector<std::string>({"TESTSUITE", "SUITE"})); 20156 20157 Style.WhitespaceSensitiveMacros.clear(); 20158 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]", 20159 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"}); 20160 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]", 20161 WhitespaceSensitiveMacros, 20162 std::vector<std::string>({"STRINGIZE", "ASSERT"})); 20163 Style.WhitespaceSensitiveMacros.clear(); 20164 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']", 20165 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"}); 20166 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']", 20167 WhitespaceSensitiveMacros, 20168 std::vector<std::string>({"STRINGIZE", "ASSERT"})); 20169 20170 Style.IncludeStyle.IncludeCategories.clear(); 20171 std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = { 20172 {"abc/.*", 2, 0, false}, {".*", 1, 0, true}}; 20173 CHECK_PARSE("IncludeCategories:\n" 20174 " - Regex: abc/.*\n" 20175 " Priority: 2\n" 20176 " - Regex: .*\n" 20177 " Priority: 1\n" 20178 " CaseSensitive: true\n", 20179 IncludeStyle.IncludeCategories, ExpectedCategories); 20180 CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex, 20181 "abc$"); 20182 CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'", 20183 IncludeStyle.IncludeIsMainSourceRegex, "abc$"); 20184 20185 Style.SortIncludes = FormatStyle::SI_Never; 20186 CHECK_PARSE("SortIncludes: true", SortIncludes, 20187 FormatStyle::SI_CaseSensitive); 20188 CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never); 20189 CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes, 20190 FormatStyle::SI_CaseInsensitive); 20191 CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes, 20192 FormatStyle::SI_CaseSensitive); 20193 CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never); 20194 20195 Style.RawStringFormats.clear(); 20196 std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = { 20197 { 20198 FormatStyle::LK_TextProto, 20199 {"pb", "proto"}, 20200 {"PARSE_TEXT_PROTO"}, 20201 /*CanonicalDelimiter=*/"", 20202 "llvm", 20203 }, 20204 { 20205 FormatStyle::LK_Cpp, 20206 {"cc", "cpp"}, 20207 {"C_CODEBLOCK", "CPPEVAL"}, 20208 /*CanonicalDelimiter=*/"cc", 20209 /*BasedOnStyle=*/"", 20210 }, 20211 }; 20212 20213 CHECK_PARSE("RawStringFormats:\n" 20214 " - Language: TextProto\n" 20215 " Delimiters:\n" 20216 " - 'pb'\n" 20217 " - 'proto'\n" 20218 " EnclosingFunctions:\n" 20219 " - 'PARSE_TEXT_PROTO'\n" 20220 " BasedOnStyle: llvm\n" 20221 " - Language: Cpp\n" 20222 " Delimiters:\n" 20223 " - 'cc'\n" 20224 " - 'cpp'\n" 20225 " EnclosingFunctions:\n" 20226 " - 'C_CODEBLOCK'\n" 20227 " - 'CPPEVAL'\n" 20228 " CanonicalDelimiter: 'cc'", 20229 RawStringFormats, ExpectedRawStringFormats); 20230 20231 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20232 " Minimum: 0\n" 20233 " Maximum: 0", 20234 SpacesInLineCommentPrefix.Minimum, 0u); 20235 EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u); 20236 Style.SpacesInLineCommentPrefix.Minimum = 1; 20237 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20238 " Minimum: 2", 20239 SpacesInLineCommentPrefix.Minimum, 0u); 20240 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20241 " Maximum: -1", 20242 SpacesInLineCommentPrefix.Maximum, -1u); 20243 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20244 " Minimum: 2", 20245 SpacesInLineCommentPrefix.Minimum, 2u); 20246 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20247 " Maximum: 1", 20248 SpacesInLineCommentPrefix.Maximum, 1u); 20249 EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u); 20250 20251 Style.SpacesInAngles = FormatStyle::SIAS_Always; 20252 CHECK_PARSE("SpacesInAngles: Never", SpacesInAngles, FormatStyle::SIAS_Never); 20253 CHECK_PARSE("SpacesInAngles: Always", SpacesInAngles, 20254 FormatStyle::SIAS_Always); 20255 CHECK_PARSE("SpacesInAngles: Leave", SpacesInAngles, FormatStyle::SIAS_Leave); 20256 // For backward compatibility: 20257 CHECK_PARSE("SpacesInAngles: false", SpacesInAngles, FormatStyle::SIAS_Never); 20258 CHECK_PARSE("SpacesInAngles: true", SpacesInAngles, FormatStyle::SIAS_Always); 20259 20260 CHECK_PARSE("RequiresClausePosition: WithPreceding", RequiresClausePosition, 20261 FormatStyle::RCPS_WithPreceding); 20262 CHECK_PARSE("RequiresClausePosition: WithFollowing", RequiresClausePosition, 20263 FormatStyle::RCPS_WithFollowing); 20264 CHECK_PARSE("RequiresClausePosition: SingleLine", RequiresClausePosition, 20265 FormatStyle::RCPS_SingleLine); 20266 CHECK_PARSE("RequiresClausePosition: OwnLine", RequiresClausePosition, 20267 FormatStyle::RCPS_OwnLine); 20268 20269 CHECK_PARSE("BreakBeforeConceptDeclarations: Never", 20270 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Never); 20271 CHECK_PARSE("BreakBeforeConceptDeclarations: Always", 20272 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always); 20273 CHECK_PARSE("BreakBeforeConceptDeclarations: Allowed", 20274 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed); 20275 // For backward compatibility: 20276 CHECK_PARSE("BreakBeforeConceptDeclarations: true", 20277 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always); 20278 CHECK_PARSE("BreakBeforeConceptDeclarations: false", 20279 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed); 20280 } 20281 20282 TEST_F(FormatTest, ParsesConfigurationWithLanguages) { 20283 FormatStyle Style = {}; 20284 Style.Language = FormatStyle::LK_Cpp; 20285 CHECK_PARSE("Language: Cpp\n" 20286 "IndentWidth: 12", 20287 IndentWidth, 12u); 20288 EXPECT_EQ(parseConfiguration("Language: JavaScript\n" 20289 "IndentWidth: 34", 20290 &Style), 20291 ParseError::Unsuitable); 20292 FormatStyle BinPackedTCS = {}; 20293 BinPackedTCS.Language = FormatStyle::LK_JavaScript; 20294 EXPECT_EQ(parseConfiguration("BinPackArguments: true\n" 20295 "InsertTrailingCommas: Wrapped", 20296 &BinPackedTCS), 20297 ParseError::BinPackTrailingCommaConflict); 20298 EXPECT_EQ(12u, Style.IndentWidth); 20299 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u); 20300 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language); 20301 20302 Style.Language = FormatStyle::LK_JavaScript; 20303 CHECK_PARSE("Language: JavaScript\n" 20304 "IndentWidth: 12", 20305 IndentWidth, 12u); 20306 CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u); 20307 EXPECT_EQ(parseConfiguration("Language: Cpp\n" 20308 "IndentWidth: 34", 20309 &Style), 20310 ParseError::Unsuitable); 20311 EXPECT_EQ(23u, Style.IndentWidth); 20312 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u); 20313 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language); 20314 20315 CHECK_PARSE("BasedOnStyle: LLVM\n" 20316 "IndentWidth: 67", 20317 IndentWidth, 67u); 20318 20319 CHECK_PARSE("---\n" 20320 "Language: JavaScript\n" 20321 "IndentWidth: 12\n" 20322 "---\n" 20323 "Language: Cpp\n" 20324 "IndentWidth: 34\n" 20325 "...\n", 20326 IndentWidth, 12u); 20327 20328 Style.Language = FormatStyle::LK_Cpp; 20329 CHECK_PARSE("---\n" 20330 "Language: JavaScript\n" 20331 "IndentWidth: 12\n" 20332 "---\n" 20333 "Language: Cpp\n" 20334 "IndentWidth: 34\n" 20335 "...\n", 20336 IndentWidth, 34u); 20337 CHECK_PARSE("---\n" 20338 "IndentWidth: 78\n" 20339 "---\n" 20340 "Language: JavaScript\n" 20341 "IndentWidth: 56\n" 20342 "...\n", 20343 IndentWidth, 78u); 20344 20345 Style.ColumnLimit = 123; 20346 Style.IndentWidth = 234; 20347 Style.BreakBeforeBraces = FormatStyle::BS_Linux; 20348 Style.TabWidth = 345; 20349 EXPECT_FALSE(parseConfiguration("---\n" 20350 "IndentWidth: 456\n" 20351 "BreakBeforeBraces: Allman\n" 20352 "---\n" 20353 "Language: JavaScript\n" 20354 "IndentWidth: 111\n" 20355 "TabWidth: 111\n" 20356 "---\n" 20357 "Language: Cpp\n" 20358 "BreakBeforeBraces: Stroustrup\n" 20359 "TabWidth: 789\n" 20360 "...\n", 20361 &Style)); 20362 EXPECT_EQ(123u, Style.ColumnLimit); 20363 EXPECT_EQ(456u, Style.IndentWidth); 20364 EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces); 20365 EXPECT_EQ(789u, Style.TabWidth); 20366 20367 EXPECT_EQ(parseConfiguration("---\n" 20368 "Language: JavaScript\n" 20369 "IndentWidth: 56\n" 20370 "---\n" 20371 "IndentWidth: 78\n" 20372 "...\n", 20373 &Style), 20374 ParseError::Error); 20375 EXPECT_EQ(parseConfiguration("---\n" 20376 "Language: JavaScript\n" 20377 "IndentWidth: 56\n" 20378 "---\n" 20379 "Language: JavaScript\n" 20380 "IndentWidth: 78\n" 20381 "...\n", 20382 &Style), 20383 ParseError::Error); 20384 20385 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language); 20386 } 20387 20388 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) { 20389 FormatStyle Style = {}; 20390 Style.Language = FormatStyle::LK_JavaScript; 20391 Style.BreakBeforeTernaryOperators = true; 20392 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value()); 20393 EXPECT_FALSE(Style.BreakBeforeTernaryOperators); 20394 20395 Style.BreakBeforeTernaryOperators = true; 20396 EXPECT_EQ(0, parseConfiguration("---\n" 20397 "BasedOnStyle: Google\n" 20398 "---\n" 20399 "Language: JavaScript\n" 20400 "IndentWidth: 76\n" 20401 "...\n", 20402 &Style) 20403 .value()); 20404 EXPECT_FALSE(Style.BreakBeforeTernaryOperators); 20405 EXPECT_EQ(76u, Style.IndentWidth); 20406 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language); 20407 } 20408 20409 TEST_F(FormatTest, ConfigurationRoundTripTest) { 20410 FormatStyle Style = getLLVMStyle(); 20411 std::string YAML = configurationAsText(Style); 20412 FormatStyle ParsedStyle = {}; 20413 ParsedStyle.Language = FormatStyle::LK_Cpp; 20414 EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value()); 20415 EXPECT_EQ(Style, ParsedStyle); 20416 } 20417 20418 TEST_F(FormatTest, WorksFor8bitEncodings) { 20419 EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n" 20420 "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n" 20421 "\"\xe7\xe8\xec\xed\xfe\xfe \"\n" 20422 "\"\xef\xee\xf0\xf3...\"", 20423 format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 " 20424 "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe " 20425 "\xef\xee\xf0\xf3...\"", 20426 getLLVMStyleWithColumns(12))); 20427 } 20428 20429 TEST_F(FormatTest, HandlesUTF8BOM) { 20430 EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf")); 20431 EXPECT_EQ("\xef\xbb\xbf#include <iostream>", 20432 format("\xef\xbb\xbf#include <iostream>")); 20433 EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>", 20434 format("\xef\xbb\xbf\n#include <iostream>")); 20435 } 20436 20437 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers. 20438 #if !defined(_MSC_VER) 20439 20440 TEST_F(FormatTest, CountsUTF8CharactersProperly) { 20441 verifyFormat("\"Однажды в студёную зимнюю пору...\"", 20442 getLLVMStyleWithColumns(35)); 20443 verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"", 20444 getLLVMStyleWithColumns(31)); 20445 verifyFormat("// Однажды в студёную зимнюю пору...", 20446 getLLVMStyleWithColumns(36)); 20447 verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32)); 20448 verifyFormat("/* Однажды в студёную зимнюю пору... */", 20449 getLLVMStyleWithColumns(39)); 20450 verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */", 20451 getLLVMStyleWithColumns(35)); 20452 } 20453 20454 TEST_F(FormatTest, SplitsUTF8Strings) { 20455 // Non-printable characters' width is currently considered to be the length in 20456 // bytes in UTF8. The characters can be displayed in very different manner 20457 // (zero-width, single width with a substitution glyph, expanded to their code 20458 // (e.g. "<8d>"), so there's no single correct way to handle them. 20459 EXPECT_EQ("\"aaaaÄ\"\n" 20460 "\"\xc2\x8d\";", 20461 format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10))); 20462 EXPECT_EQ("\"aaaaaaaÄ\"\n" 20463 "\"\xc2\x8d\";", 20464 format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10))); 20465 EXPECT_EQ("\"Однажды, в \"\n" 20466 "\"студёную \"\n" 20467 "\"зимнюю \"\n" 20468 "\"пору,\"", 20469 format("\"Однажды, в студёную зимнюю пору,\"", 20470 getLLVMStyleWithColumns(13))); 20471 EXPECT_EQ( 20472 "\"一 二 三 \"\n" 20473 "\"四 五六 \"\n" 20474 "\"七 八 九 \"\n" 20475 "\"十\"", 20476 format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11))); 20477 EXPECT_EQ("\"一\t\"\n" 20478 "\"二 \t\"\n" 20479 "\"三 四 \"\n" 20480 "\"五\t\"\n" 20481 "\"六 \t\"\n" 20482 "\"七 \"\n" 20483 "\"八九十\tqq\"", 20484 format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"", 20485 getLLVMStyleWithColumns(11))); 20486 20487 // UTF8 character in an escape sequence. 20488 EXPECT_EQ("\"aaaaaa\"\n" 20489 "\"\\\xC2\x8D\"", 20490 format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10))); 20491 } 20492 20493 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) { 20494 EXPECT_EQ("const char *sssss =\n" 20495 " \"一二三四五六七八\\\n" 20496 " 九 十\";", 20497 format("const char *sssss = \"一二三四五六七八\\\n" 20498 " 九 十\";", 20499 getLLVMStyleWithColumns(30))); 20500 } 20501 20502 TEST_F(FormatTest, SplitsUTF8LineComments) { 20503 EXPECT_EQ("// aaaaÄ\xc2\x8d", 20504 format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10))); 20505 EXPECT_EQ("// Я из лесу\n" 20506 "// вышел; был\n" 20507 "// сильный\n" 20508 "// мороз.", 20509 format("// Я из лесу вышел; был сильный мороз.", 20510 getLLVMStyleWithColumns(13))); 20511 EXPECT_EQ("// 一二三\n" 20512 "// 四五六七\n" 20513 "// 八 九\n" 20514 "// 十", 20515 format("// 一二三 四五六七 八 九 十", getLLVMStyleWithColumns(9))); 20516 } 20517 20518 TEST_F(FormatTest, SplitsUTF8BlockComments) { 20519 EXPECT_EQ("/* Гляжу,\n" 20520 " * поднимается\n" 20521 " * медленно в\n" 20522 " * гору\n" 20523 " * Лошадка,\n" 20524 " * везущая\n" 20525 " * хворосту\n" 20526 " * воз. */", 20527 format("/* Гляжу, поднимается медленно в гору\n" 20528 " * Лошадка, везущая хворосту воз. */", 20529 getLLVMStyleWithColumns(13))); 20530 EXPECT_EQ( 20531 "/* 一二三\n" 20532 " * 四五六七\n" 20533 " * 八 九\n" 20534 " * 十 */", 20535 format("/* 一二三 四五六七 八 九 十 */", getLLVMStyleWithColumns(9))); 20536 EXPECT_EQ("/* \n" 20537 " * \n" 20538 " * - */", 20539 format("/* - */", getLLVMStyleWithColumns(12))); 20540 } 20541 20542 #endif // _MSC_VER 20543 20544 TEST_F(FormatTest, ConstructorInitializerIndentWidth) { 20545 FormatStyle Style = getLLVMStyle(); 20546 20547 Style.ConstructorInitializerIndentWidth = 4; 20548 verifyFormat( 20549 "SomeClass::Constructor()\n" 20550 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20551 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20552 Style); 20553 20554 Style.ConstructorInitializerIndentWidth = 2; 20555 verifyFormat( 20556 "SomeClass::Constructor()\n" 20557 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20558 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20559 Style); 20560 20561 Style.ConstructorInitializerIndentWidth = 0; 20562 verifyFormat( 20563 "SomeClass::Constructor()\n" 20564 ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20565 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20566 Style); 20567 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 20568 verifyFormat( 20569 "SomeLongTemplateVariableName<\n" 20570 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>", 20571 Style); 20572 verifyFormat("bool smaller = 1 < " 20573 "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 20574 " " 20575 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 20576 Style); 20577 20578 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 20579 verifyFormat("SomeClass::Constructor() :\n" 20580 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n" 20581 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}", 20582 Style); 20583 } 20584 20585 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) { 20586 FormatStyle Style = getLLVMStyle(); 20587 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 20588 Style.ConstructorInitializerIndentWidth = 4; 20589 verifyFormat("SomeClass::Constructor()\n" 20590 " : a(a)\n" 20591 " , b(b)\n" 20592 " , c(c) {}", 20593 Style); 20594 verifyFormat("SomeClass::Constructor()\n" 20595 " : a(a) {}", 20596 Style); 20597 20598 Style.ColumnLimit = 0; 20599 verifyFormat("SomeClass::Constructor()\n" 20600 " : a(a) {}", 20601 Style); 20602 verifyFormat("SomeClass::Constructor() noexcept\n" 20603 " : a(a) {}", 20604 Style); 20605 verifyFormat("SomeClass::Constructor()\n" 20606 " : a(a)\n" 20607 " , b(b)\n" 20608 " , c(c) {}", 20609 Style); 20610 verifyFormat("SomeClass::Constructor()\n" 20611 " : a(a) {\n" 20612 " foo();\n" 20613 " bar();\n" 20614 "}", 20615 Style); 20616 20617 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 20618 verifyFormat("SomeClass::Constructor()\n" 20619 " : a(a)\n" 20620 " , b(b)\n" 20621 " , c(c) {\n}", 20622 Style); 20623 verifyFormat("SomeClass::Constructor()\n" 20624 " : a(a) {\n}", 20625 Style); 20626 20627 Style.ColumnLimit = 80; 20628 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 20629 Style.ConstructorInitializerIndentWidth = 2; 20630 verifyFormat("SomeClass::Constructor()\n" 20631 " : a(a)\n" 20632 " , b(b)\n" 20633 " , c(c) {}", 20634 Style); 20635 20636 Style.ConstructorInitializerIndentWidth = 0; 20637 verifyFormat("SomeClass::Constructor()\n" 20638 ": a(a)\n" 20639 ", b(b)\n" 20640 ", c(c) {}", 20641 Style); 20642 20643 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 20644 Style.ConstructorInitializerIndentWidth = 4; 20645 verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style); 20646 verifyFormat( 20647 "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n", 20648 Style); 20649 verifyFormat( 20650 "SomeClass::Constructor()\n" 20651 " : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}", 20652 Style); 20653 Style.ConstructorInitializerIndentWidth = 4; 20654 Style.ColumnLimit = 60; 20655 verifyFormat("SomeClass::Constructor()\n" 20656 " : aaaaaaaa(aaaaaaaa)\n" 20657 " , aaaaaaaa(aaaaaaaa)\n" 20658 " , aaaaaaaa(aaaaaaaa) {}", 20659 Style); 20660 } 20661 20662 TEST_F(FormatTest, ConstructorInitializersWithPreprocessorDirective) { 20663 FormatStyle Style = getLLVMStyle(); 20664 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 20665 Style.ConstructorInitializerIndentWidth = 4; 20666 verifyFormat("SomeClass::Constructor()\n" 20667 " : a{a}\n" 20668 " , b{b} {}", 20669 Style); 20670 verifyFormat("SomeClass::Constructor()\n" 20671 " : a{a}\n" 20672 "#if CONDITION\n" 20673 " , b{b}\n" 20674 "#endif\n" 20675 "{\n}", 20676 Style); 20677 Style.ConstructorInitializerIndentWidth = 2; 20678 verifyFormat("SomeClass::Constructor()\n" 20679 "#if CONDITION\n" 20680 " : a{a}\n" 20681 "#endif\n" 20682 " , b{b}\n" 20683 " , c{c} {\n}", 20684 Style); 20685 Style.ConstructorInitializerIndentWidth = 0; 20686 verifyFormat("SomeClass::Constructor()\n" 20687 ": a{a}\n" 20688 "#ifdef CONDITION\n" 20689 ", b{b}\n" 20690 "#else\n" 20691 ", c{c}\n" 20692 "#endif\n" 20693 ", d{d} {\n}", 20694 Style); 20695 Style.ConstructorInitializerIndentWidth = 4; 20696 verifyFormat("SomeClass::Constructor()\n" 20697 " : a{a}\n" 20698 "#if WINDOWS\n" 20699 "#if DEBUG\n" 20700 " , b{0}\n" 20701 "#else\n" 20702 " , b{1}\n" 20703 "#endif\n" 20704 "#else\n" 20705 "#if DEBUG\n" 20706 " , b{2}\n" 20707 "#else\n" 20708 " , b{3}\n" 20709 "#endif\n" 20710 "#endif\n" 20711 "{\n}", 20712 Style); 20713 verifyFormat("SomeClass::Constructor()\n" 20714 " : a{a}\n" 20715 "#if WINDOWS\n" 20716 " , b{0}\n" 20717 "#if DEBUG\n" 20718 " , c{0}\n" 20719 "#else\n" 20720 " , c{1}\n" 20721 "#endif\n" 20722 "#else\n" 20723 "#if DEBUG\n" 20724 " , c{2}\n" 20725 "#else\n" 20726 " , c{3}\n" 20727 "#endif\n" 20728 " , b{1}\n" 20729 "#endif\n" 20730 "{\n}", 20731 Style); 20732 } 20733 20734 TEST_F(FormatTest, Destructors) { 20735 verifyFormat("void F(int &i) { i.~int(); }"); 20736 verifyFormat("void F(int &i) { i->~int(); }"); 20737 } 20738 20739 TEST_F(FormatTest, FormatsWithWebKitStyle) { 20740 FormatStyle Style = getWebKitStyle(); 20741 20742 // Don't indent in outer namespaces. 20743 verifyFormat("namespace outer {\n" 20744 "int i;\n" 20745 "namespace inner {\n" 20746 " int i;\n" 20747 "} // namespace inner\n" 20748 "} // namespace outer\n" 20749 "namespace other_outer {\n" 20750 "int i;\n" 20751 "}", 20752 Style); 20753 20754 // Don't indent case labels. 20755 verifyFormat("switch (variable) {\n" 20756 "case 1:\n" 20757 "case 2:\n" 20758 " doSomething();\n" 20759 " break;\n" 20760 "default:\n" 20761 " ++variable;\n" 20762 "}", 20763 Style); 20764 20765 // Wrap before binary operators. 20766 EXPECT_EQ("void f()\n" 20767 "{\n" 20768 " if (aaaaaaaaaaaaaaaa\n" 20769 " && bbbbbbbbbbbbbbbbbbbbbbbb\n" 20770 " && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n" 20771 " return;\n" 20772 "}", 20773 format("void f() {\n" 20774 "if (aaaaaaaaaaaaaaaa\n" 20775 "&& bbbbbbbbbbbbbbbbbbbbbbbb\n" 20776 "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n" 20777 "return;\n" 20778 "}", 20779 Style)); 20780 20781 // Allow functions on a single line. 20782 verifyFormat("void f() { return; }", Style); 20783 20784 // Allow empty blocks on a single line and insert a space in empty blocks. 20785 EXPECT_EQ("void f() { }", format("void f() {}", Style)); 20786 EXPECT_EQ("while (true) { }", format("while (true) {}", Style)); 20787 // However, don't merge non-empty short loops. 20788 EXPECT_EQ("while (true) {\n" 20789 " continue;\n" 20790 "}", 20791 format("while (true) { continue; }", Style)); 20792 20793 // Constructor initializers are formatted one per line with the "," on the 20794 // new line. 20795 verifyFormat("Constructor()\n" 20796 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 20797 " , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n" 20798 " aaaaaaaaaaaaaa)\n" 20799 " , aaaaaaaaaaaaaaaaaaaaaaa()\n" 20800 "{\n" 20801 "}", 20802 Style); 20803 verifyFormat("SomeClass::Constructor()\n" 20804 " : a(a)\n" 20805 "{\n" 20806 "}", 20807 Style); 20808 EXPECT_EQ("SomeClass::Constructor()\n" 20809 " : a(a)\n" 20810 "{\n" 20811 "}", 20812 format("SomeClass::Constructor():a(a){}", Style)); 20813 verifyFormat("SomeClass::Constructor()\n" 20814 " : a(a)\n" 20815 " , b(b)\n" 20816 " , c(c)\n" 20817 "{\n" 20818 "}", 20819 Style); 20820 verifyFormat("SomeClass::Constructor()\n" 20821 " : a(a)\n" 20822 "{\n" 20823 " foo();\n" 20824 " bar();\n" 20825 "}", 20826 Style); 20827 20828 // Access specifiers should be aligned left. 20829 verifyFormat("class C {\n" 20830 "public:\n" 20831 " int i;\n" 20832 "};", 20833 Style); 20834 20835 // Do not align comments. 20836 verifyFormat("int a; // Do not\n" 20837 "double b; // align comments.", 20838 Style); 20839 20840 // Do not align operands. 20841 EXPECT_EQ("ASSERT(aaaa\n" 20842 " || bbbb);", 20843 format("ASSERT ( aaaa\n||bbbb);", Style)); 20844 20845 // Accept input's line breaks. 20846 EXPECT_EQ("if (aaaaaaaaaaaaaaa\n" 20847 " || bbbbbbbbbbbbbbb) {\n" 20848 " i++;\n" 20849 "}", 20850 format("if (aaaaaaaaaaaaaaa\n" 20851 "|| bbbbbbbbbbbbbbb) { i++; }", 20852 Style)); 20853 EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n" 20854 " i++;\n" 20855 "}", 20856 format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style)); 20857 20858 // Don't automatically break all macro definitions (llvm.org/PR17842). 20859 verifyFormat("#define aNumber 10", Style); 20860 // However, generally keep the line breaks that the user authored. 20861 EXPECT_EQ("#define aNumber \\\n" 20862 " 10", 20863 format("#define aNumber \\\n" 20864 " 10", 20865 Style)); 20866 20867 // Keep empty and one-element array literals on a single line. 20868 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n" 20869 " copyItems:YES];", 20870 format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n" 20871 "copyItems:YES];", 20872 Style)); 20873 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n" 20874 " copyItems:YES];", 20875 format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n" 20876 " copyItems:YES];", 20877 Style)); 20878 // FIXME: This does not seem right, there should be more indentation before 20879 // the array literal's entries. Nested blocks have the same problem. 20880 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n" 20881 " @\"a\",\n" 20882 " @\"a\"\n" 20883 "]\n" 20884 " copyItems:YES];", 20885 format("NSArray* a = [[NSArray alloc] initWithArray:@[\n" 20886 " @\"a\",\n" 20887 " @\"a\"\n" 20888 " ]\n" 20889 " copyItems:YES];", 20890 Style)); 20891 EXPECT_EQ( 20892 "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n" 20893 " copyItems:YES];", 20894 format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n" 20895 " copyItems:YES];", 20896 Style)); 20897 20898 verifyFormat("[self.a b:c c:d];", Style); 20899 EXPECT_EQ("[self.a b:c\n" 20900 " c:d];", 20901 format("[self.a b:c\n" 20902 "c:d];", 20903 Style)); 20904 } 20905 20906 TEST_F(FormatTest, FormatsLambdas) { 20907 verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n"); 20908 verifyFormat( 20909 "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n"); 20910 verifyFormat("int c = [&] { [=] { return b++; }(); }();\n"); 20911 verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n"); 20912 verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n"); 20913 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n"); 20914 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n"); 20915 verifyFormat("auto c = [a = [b = 42] {}] {};\n"); 20916 verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n"); 20917 verifyFormat("int x = f(*+[] {});"); 20918 verifyFormat("void f() {\n" 20919 " other(x.begin(), x.end(), [&](int, int) { return 1; });\n" 20920 "}\n"); 20921 verifyFormat("void f() {\n" 20922 " other(x.begin(), //\n" 20923 " x.end(), //\n" 20924 " [&](int, int) { return 1; });\n" 20925 "}\n"); 20926 verifyFormat("void f() {\n" 20927 " other.other.other.other.other(\n" 20928 " x.begin(), x.end(),\n" 20929 " [something, rather](int, int, int, int, int, int, int) { " 20930 "return 1; });\n" 20931 "}\n"); 20932 verifyFormat( 20933 "void f() {\n" 20934 " other.other.other.other.other(\n" 20935 " x.begin(), x.end(),\n" 20936 " [something, rather](int, int, int, int, int, int, int) {\n" 20937 " //\n" 20938 " });\n" 20939 "}\n"); 20940 verifyFormat("SomeFunction([]() { // A cool function...\n" 20941 " return 43;\n" 20942 "});"); 20943 EXPECT_EQ("SomeFunction([]() {\n" 20944 "#define A a\n" 20945 " return 43;\n" 20946 "});", 20947 format("SomeFunction([](){\n" 20948 "#define A a\n" 20949 "return 43;\n" 20950 "});")); 20951 verifyFormat("void f() {\n" 20952 " SomeFunction([](decltype(x), A *a) {});\n" 20953 " SomeFunction([](typeof(x), A *a) {});\n" 20954 " SomeFunction([](_Atomic(x), A *a) {});\n" 20955 " SomeFunction([](__underlying_type(x), A *a) {});\n" 20956 "}"); 20957 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 20958 " [](const aaaaaaaaaa &a) { return a; });"); 20959 verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n" 20960 " SomeOtherFunctioooooooooooooooooooooooooon();\n" 20961 "});"); 20962 verifyFormat("Constructor()\n" 20963 " : Field([] { // comment\n" 20964 " int i;\n" 20965 " }) {}"); 20966 verifyFormat("auto my_lambda = [](const string &some_parameter) {\n" 20967 " return some_parameter.size();\n" 20968 "};"); 20969 verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n" 20970 " [](const string &s) { return s; };"); 20971 verifyFormat("int i = aaaaaa ? 1 //\n" 20972 " : [] {\n" 20973 " return 2; //\n" 20974 " }();"); 20975 verifyFormat("llvm::errs() << \"number of twos is \"\n" 20976 " << std::count_if(v.begin(), v.end(), [](int x) {\n" 20977 " return x == 2; // force break\n" 20978 " });"); 20979 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 20980 " [=](int iiiiiiiiiiii) {\n" 20981 " return aaaaaaaaaaaaaaaaaaaaaaa !=\n" 20982 " aaaaaaaaaaaaaaaaaaaaaaa;\n" 20983 " });", 20984 getLLVMStyleWithColumns(60)); 20985 20986 verifyFormat("SomeFunction({[&] {\n" 20987 " // comment\n" 20988 " },\n" 20989 " [&] {\n" 20990 " // comment\n" 20991 " }});"); 20992 verifyFormat("SomeFunction({[&] {\n" 20993 " // comment\n" 20994 "}});"); 20995 verifyFormat( 20996 "virtual aaaaaaaaaaaaaaaa(\n" 20997 " std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n" 20998 " aaaaa aaaaaaaaa);"); 20999 21000 // Lambdas with return types. 21001 verifyFormat("int c = []() -> int { return 2; }();\n"); 21002 verifyFormat("int c = []() -> int * { return 2; }();\n"); 21003 verifyFormat("int c = []() -> vector<int> { return {2}; }();\n"); 21004 verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());"); 21005 verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};"); 21006 verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};"); 21007 verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};"); 21008 verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};"); 21009 verifyFormat("[a, a]() -> a<1> {};"); 21010 verifyFormat("[]() -> foo<5 + 2> { return {}; };"); 21011 verifyFormat("[]() -> foo<5 - 2> { return {}; };"); 21012 verifyFormat("[]() -> foo<5 / 2> { return {}; };"); 21013 verifyFormat("[]() -> foo<5 * 2> { return {}; };"); 21014 verifyFormat("[]() -> foo<5 % 2> { return {}; };"); 21015 verifyFormat("[]() -> foo<5 << 2> { return {}; };"); 21016 verifyFormat("[]() -> foo<!5> { return {}; };"); 21017 verifyFormat("[]() -> foo<~5> { return {}; };"); 21018 verifyFormat("[]() -> foo<5 | 2> { return {}; };"); 21019 verifyFormat("[]() -> foo<5 || 2> { return {}; };"); 21020 verifyFormat("[]() -> foo<5 & 2> { return {}; };"); 21021 verifyFormat("[]() -> foo<5 && 2> { return {}; };"); 21022 verifyFormat("[]() -> foo<5 == 2> { return {}; };"); 21023 verifyFormat("[]() -> foo<5 != 2> { return {}; };"); 21024 verifyFormat("[]() -> foo<5 >= 2> { return {}; };"); 21025 verifyFormat("[]() -> foo<5 <= 2> { return {}; };"); 21026 verifyFormat("[]() -> foo<5 < 2> { return {}; };"); 21027 verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };"); 21028 verifyFormat("namespace bar {\n" 21029 "// broken:\n" 21030 "auto foo{[]() -> foo<5 + 2> { return {}; }};\n" 21031 "} // namespace bar"); 21032 verifyFormat("namespace bar {\n" 21033 "// broken:\n" 21034 "auto foo{[]() -> foo<5 - 2> { return {}; }};\n" 21035 "} // namespace bar"); 21036 verifyFormat("namespace bar {\n" 21037 "// broken:\n" 21038 "auto foo{[]() -> foo<5 / 2> { return {}; }};\n" 21039 "} // namespace bar"); 21040 verifyFormat("namespace bar {\n" 21041 "// broken:\n" 21042 "auto foo{[]() -> foo<5 * 2> { return {}; }};\n" 21043 "} // namespace bar"); 21044 verifyFormat("namespace bar {\n" 21045 "// broken:\n" 21046 "auto foo{[]() -> foo<5 % 2> { return {}; }};\n" 21047 "} // namespace bar"); 21048 verifyFormat("namespace bar {\n" 21049 "// broken:\n" 21050 "auto foo{[]() -> foo<5 << 2> { return {}; }};\n" 21051 "} // namespace bar"); 21052 verifyFormat("namespace bar {\n" 21053 "// broken:\n" 21054 "auto foo{[]() -> foo<!5> { return {}; }};\n" 21055 "} // namespace bar"); 21056 verifyFormat("namespace bar {\n" 21057 "// broken:\n" 21058 "auto foo{[]() -> foo<~5> { return {}; }};\n" 21059 "} // namespace bar"); 21060 verifyFormat("namespace bar {\n" 21061 "// broken:\n" 21062 "auto foo{[]() -> foo<5 | 2> { return {}; }};\n" 21063 "} // namespace bar"); 21064 verifyFormat("namespace bar {\n" 21065 "// broken:\n" 21066 "auto foo{[]() -> foo<5 || 2> { return {}; }};\n" 21067 "} // namespace bar"); 21068 verifyFormat("namespace bar {\n" 21069 "// broken:\n" 21070 "auto foo{[]() -> foo<5 & 2> { return {}; }};\n" 21071 "} // namespace bar"); 21072 verifyFormat("namespace bar {\n" 21073 "// broken:\n" 21074 "auto foo{[]() -> foo<5 && 2> { return {}; }};\n" 21075 "} // namespace bar"); 21076 verifyFormat("namespace bar {\n" 21077 "// broken:\n" 21078 "auto foo{[]() -> foo<5 == 2> { return {}; }};\n" 21079 "} // namespace bar"); 21080 verifyFormat("namespace bar {\n" 21081 "// broken:\n" 21082 "auto foo{[]() -> foo<5 != 2> { return {}; }};\n" 21083 "} // namespace bar"); 21084 verifyFormat("namespace bar {\n" 21085 "// broken:\n" 21086 "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n" 21087 "} // namespace bar"); 21088 verifyFormat("namespace bar {\n" 21089 "// broken:\n" 21090 "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n" 21091 "} // namespace bar"); 21092 verifyFormat("namespace bar {\n" 21093 "// broken:\n" 21094 "auto foo{[]() -> foo<5 < 2> { return {}; }};\n" 21095 "} // namespace bar"); 21096 verifyFormat("namespace bar {\n" 21097 "// broken:\n" 21098 "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n" 21099 "} // namespace bar"); 21100 verifyFormat("[]() -> a<1> {};"); 21101 verifyFormat("[]() -> a<1> { ; };"); 21102 verifyFormat("[]() -> a<1> { ; }();"); 21103 verifyFormat("[a, a]() -> a<true> {};"); 21104 verifyFormat("[]() -> a<true> {};"); 21105 verifyFormat("[]() -> a<true> { ; };"); 21106 verifyFormat("[]() -> a<true> { ; }();"); 21107 verifyFormat("[a, a]() -> a<false> {};"); 21108 verifyFormat("[]() -> a<false> {};"); 21109 verifyFormat("[]() -> a<false> { ; };"); 21110 verifyFormat("[]() -> a<false> { ; }();"); 21111 verifyFormat("auto foo{[]() -> foo<false> { ; }};"); 21112 verifyFormat("namespace bar {\n" 21113 "auto foo{[]() -> foo<false> { ; }};\n" 21114 "} // namespace bar"); 21115 verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n" 21116 " int j) -> int {\n" 21117 " return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n" 21118 "};"); 21119 verifyFormat( 21120 "aaaaaaaaaaaaaaaaaaaaaa(\n" 21121 " [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n" 21122 " return aaaaaaaaaaaaaaaaa;\n" 21123 " });", 21124 getLLVMStyleWithColumns(70)); 21125 verifyFormat("[]() //\n" 21126 " -> int {\n" 21127 " return 1; //\n" 21128 "};"); 21129 verifyFormat("[]() -> Void<T...> {};"); 21130 verifyFormat("[a, b]() -> Tuple<T...> { return {}; };"); 21131 verifyFormat("SomeFunction({[]() -> int[] { return {}; }});"); 21132 verifyFormat("SomeFunction({[]() -> int *[] { return {}; }});"); 21133 verifyFormat("SomeFunction({[]() -> int (*)[] { return {}; }});"); 21134 verifyFormat("SomeFunction({[]() -> ns::type<int (*)[]> { return {}; }});"); 21135 verifyFormat("return int{[x = x]() { return x; }()};"); 21136 21137 // Lambdas with explicit template argument lists. 21138 verifyFormat( 21139 "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n"); 21140 verifyFormat("auto L = []<class T>(T) {\n" 21141 " {\n" 21142 " f();\n" 21143 " g();\n" 21144 " }\n" 21145 "};\n"); 21146 verifyFormat("auto L = []<class... T>(T...) {\n" 21147 " {\n" 21148 " f();\n" 21149 " g();\n" 21150 " }\n" 21151 "};\n"); 21152 verifyFormat("auto L = []<typename... T>(T...) {\n" 21153 " {\n" 21154 " f();\n" 21155 " g();\n" 21156 " }\n" 21157 "};\n"); 21158 verifyFormat("auto L = []<template <typename...> class T>(T...) {\n" 21159 " {\n" 21160 " f();\n" 21161 " g();\n" 21162 " }\n" 21163 "};\n"); 21164 verifyFormat("auto L = []</*comment*/ class... T>(T...) {\n" 21165 " {\n" 21166 " f();\n" 21167 " g();\n" 21168 " }\n" 21169 "};\n"); 21170 21171 // Multiple lambdas in the same parentheses change indentation rules. These 21172 // lambdas are forced to start on new lines. 21173 verifyFormat("SomeFunction(\n" 21174 " []() {\n" 21175 " //\n" 21176 " },\n" 21177 " []() {\n" 21178 " //\n" 21179 " });"); 21180 21181 // A lambda passed as arg0 is always pushed to the next line. 21182 verifyFormat("SomeFunction(\n" 21183 " [this] {\n" 21184 " //\n" 21185 " },\n" 21186 " 1);\n"); 21187 21188 // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like 21189 // the arg0 case above. 21190 auto Style = getGoogleStyle(); 21191 Style.BinPackArguments = false; 21192 verifyFormat("SomeFunction(\n" 21193 " a,\n" 21194 " [this] {\n" 21195 " //\n" 21196 " },\n" 21197 " b);\n", 21198 Style); 21199 verifyFormat("SomeFunction(\n" 21200 " a,\n" 21201 " [this] {\n" 21202 " //\n" 21203 " },\n" 21204 " b);\n"); 21205 21206 // A lambda with a very long line forces arg0 to be pushed out irrespective of 21207 // the BinPackArguments value (as long as the code is wide enough). 21208 verifyFormat( 21209 "something->SomeFunction(\n" 21210 " a,\n" 21211 " [this] {\n" 21212 " " 21213 "D0000000000000000000000000000000000000000000000000000000000001();\n" 21214 " },\n" 21215 " b);\n"); 21216 21217 // A multi-line lambda is pulled up as long as the introducer fits on the 21218 // previous line and there are no further args. 21219 verifyFormat("function(1, [this, that] {\n" 21220 " //\n" 21221 "});\n"); 21222 verifyFormat("function([this, that] {\n" 21223 " //\n" 21224 "});\n"); 21225 // FIXME: this format is not ideal and we should consider forcing the first 21226 // arg onto its own line. 21227 verifyFormat("function(a, b, c, //\n" 21228 " d, [this, that] {\n" 21229 " //\n" 21230 " });\n"); 21231 21232 // Multiple lambdas are treated correctly even when there is a short arg0. 21233 verifyFormat("SomeFunction(\n" 21234 " 1,\n" 21235 " [this] {\n" 21236 " //\n" 21237 " },\n" 21238 " [this] {\n" 21239 " //\n" 21240 " },\n" 21241 " 1);\n"); 21242 21243 // More complex introducers. 21244 verifyFormat("return [i, args...] {};"); 21245 21246 // Not lambdas. 21247 verifyFormat("constexpr char hello[]{\"hello\"};"); 21248 verifyFormat("double &operator[](int i) { return 0; }\n" 21249 "int i;"); 21250 verifyFormat("std::unique_ptr<int[]> foo() {}"); 21251 verifyFormat("int i = a[a][a]->f();"); 21252 verifyFormat("int i = (*b)[a]->f();"); 21253 21254 // Other corner cases. 21255 verifyFormat("void f() {\n" 21256 " bar([]() {} // Did not respect SpacesBeforeTrailingComments\n" 21257 " );\n" 21258 "}"); 21259 21260 // Lambdas created through weird macros. 21261 verifyFormat("void f() {\n" 21262 " MACRO((const AA &a) { return 1; });\n" 21263 " MACRO((AA &a) { return 1; });\n" 21264 "}"); 21265 21266 verifyFormat("if (blah_blah(whatever, whatever, [] {\n" 21267 " doo_dah();\n" 21268 " doo_dah();\n" 21269 " })) {\n" 21270 "}"); 21271 verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n" 21272 " doo_dah();\n" 21273 " doo_dah();\n" 21274 " })) {\n" 21275 "}"); 21276 verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n" 21277 " doo_dah();\n" 21278 " doo_dah();\n" 21279 " })) {\n" 21280 "}"); 21281 verifyFormat("auto lambda = []() {\n" 21282 " int a = 2\n" 21283 "#if A\n" 21284 " + 2\n" 21285 "#endif\n" 21286 " ;\n" 21287 "};"); 21288 21289 // Lambdas with complex multiline introducers. 21290 verifyFormat( 21291 "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 21292 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n" 21293 " -> ::std::unordered_set<\n" 21294 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n" 21295 " //\n" 21296 " });"); 21297 21298 FormatStyle DoNotMerge = getLLVMStyle(); 21299 DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 21300 verifyFormat("auto c = []() {\n" 21301 " return b;\n" 21302 "};", 21303 "auto c = []() { return b; };", DoNotMerge); 21304 verifyFormat("auto c = []() {\n" 21305 "};", 21306 " auto c = []() {};", DoNotMerge); 21307 21308 FormatStyle MergeEmptyOnly = getLLVMStyle(); 21309 MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty; 21310 verifyFormat("auto c = []() {\n" 21311 " return b;\n" 21312 "};", 21313 "auto c = []() {\n" 21314 " return b;\n" 21315 " };", 21316 MergeEmptyOnly); 21317 verifyFormat("auto c = []() {};", 21318 "auto c = []() {\n" 21319 "};", 21320 MergeEmptyOnly); 21321 21322 FormatStyle MergeInline = getLLVMStyle(); 21323 MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline; 21324 verifyFormat("auto c = []() {\n" 21325 " return b;\n" 21326 "};", 21327 "auto c = []() { return b; };", MergeInline); 21328 verifyFormat("function([]() { return b; })", "function([]() { return b; })", 21329 MergeInline); 21330 verifyFormat("function([]() { return b; }, a)", 21331 "function([]() { return b; }, a)", MergeInline); 21332 verifyFormat("function(a, []() { return b; })", 21333 "function(a, []() { return b; })", MergeInline); 21334 21335 // Check option "BraceWrapping.BeforeLambdaBody" and different state of 21336 // AllowShortLambdasOnASingleLine 21337 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle(); 21338 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 21339 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 21340 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21341 FormatStyle::ShortLambdaStyle::SLS_None; 21342 verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n" 21343 " []()\n" 21344 " {\n" 21345 " return 17;\n" 21346 " });", 21347 LLVMWithBeforeLambdaBody); 21348 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n" 21349 " []()\n" 21350 " {\n" 21351 " });", 21352 LLVMWithBeforeLambdaBody); 21353 verifyFormat("auto fct_SLS_None = []()\n" 21354 "{\n" 21355 " return 17;\n" 21356 "};", 21357 LLVMWithBeforeLambdaBody); 21358 verifyFormat("TwoNestedLambdas_SLS_None(\n" 21359 " []()\n" 21360 " {\n" 21361 " return Call(\n" 21362 " []()\n" 21363 " {\n" 21364 " return 17;\n" 21365 " });\n" 21366 " });", 21367 LLVMWithBeforeLambdaBody); 21368 verifyFormat("void Fct() {\n" 21369 " return {[]()\n" 21370 " {\n" 21371 " return 17;\n" 21372 " }};\n" 21373 "}", 21374 LLVMWithBeforeLambdaBody); 21375 21376 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21377 FormatStyle::ShortLambdaStyle::SLS_Empty; 21378 verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n" 21379 " []()\n" 21380 " {\n" 21381 " return 17;\n" 21382 " });", 21383 LLVMWithBeforeLambdaBody); 21384 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});", 21385 LLVMWithBeforeLambdaBody); 21386 verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL" 21387 "ongFunctionName_SLS_Empty(\n" 21388 " []() {});", 21389 LLVMWithBeforeLambdaBody); 21390 verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n" 21391 " []()\n" 21392 " {\n" 21393 " return 17;\n" 21394 " });", 21395 LLVMWithBeforeLambdaBody); 21396 verifyFormat("auto fct_SLS_Empty = []()\n" 21397 "{\n" 21398 " return 17;\n" 21399 "};", 21400 LLVMWithBeforeLambdaBody); 21401 verifyFormat("TwoNestedLambdas_SLS_Empty(\n" 21402 " []()\n" 21403 " {\n" 21404 " return Call([]() {});\n" 21405 " });", 21406 LLVMWithBeforeLambdaBody); 21407 verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n" 21408 " []()\n" 21409 " {\n" 21410 " return Call([]() {});\n" 21411 " });", 21412 LLVMWithBeforeLambdaBody); 21413 verifyFormat( 21414 "FctWithLongLineInLambda_SLS_Empty(\n" 21415 " []()\n" 21416 " {\n" 21417 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21418 " AndShouldNotBeConsiderAsInline,\n" 21419 " LambdaBodyMustBeBreak);\n" 21420 " });", 21421 LLVMWithBeforeLambdaBody); 21422 21423 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21424 FormatStyle::ShortLambdaStyle::SLS_Inline; 21425 verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });", 21426 LLVMWithBeforeLambdaBody); 21427 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});", 21428 LLVMWithBeforeLambdaBody); 21429 verifyFormat("auto fct_SLS_Inline = []()\n" 21430 "{\n" 21431 " return 17;\n" 21432 "};", 21433 LLVMWithBeforeLambdaBody); 21434 verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return " 21435 "17; }); });", 21436 LLVMWithBeforeLambdaBody); 21437 verifyFormat( 21438 "FctWithLongLineInLambda_SLS_Inline(\n" 21439 " []()\n" 21440 " {\n" 21441 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21442 " AndShouldNotBeConsiderAsInline,\n" 21443 " LambdaBodyMustBeBreak);\n" 21444 " });", 21445 LLVMWithBeforeLambdaBody); 21446 verifyFormat("FctWithMultipleParams_SLS_Inline(" 21447 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n" 21448 " []() { return 17; });", 21449 LLVMWithBeforeLambdaBody); 21450 verifyFormat( 21451 "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });", 21452 LLVMWithBeforeLambdaBody); 21453 21454 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21455 FormatStyle::ShortLambdaStyle::SLS_All; 21456 verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });", 21457 LLVMWithBeforeLambdaBody); 21458 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});", 21459 LLVMWithBeforeLambdaBody); 21460 verifyFormat("auto fct_SLS_All = []() { return 17; };", 21461 LLVMWithBeforeLambdaBody); 21462 verifyFormat("FctWithOneParam_SLS_All(\n" 21463 " []()\n" 21464 " {\n" 21465 " // A cool function...\n" 21466 " return 43;\n" 21467 " });", 21468 LLVMWithBeforeLambdaBody); 21469 verifyFormat("FctWithMultipleParams_SLS_All(" 21470 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n" 21471 " []() { return 17; });", 21472 LLVMWithBeforeLambdaBody); 21473 verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });", 21474 LLVMWithBeforeLambdaBody); 21475 verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });", 21476 LLVMWithBeforeLambdaBody); 21477 verifyFormat( 21478 "FctWithLongLineInLambda_SLS_All(\n" 21479 " []()\n" 21480 " {\n" 21481 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21482 " AndShouldNotBeConsiderAsInline,\n" 21483 " LambdaBodyMustBeBreak);\n" 21484 " });", 21485 LLVMWithBeforeLambdaBody); 21486 verifyFormat( 21487 "auto fct_SLS_All = []()\n" 21488 "{\n" 21489 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21490 " AndShouldNotBeConsiderAsInline,\n" 21491 " LambdaBodyMustBeBreak);\n" 21492 "};", 21493 LLVMWithBeforeLambdaBody); 21494 LLVMWithBeforeLambdaBody.BinPackParameters = false; 21495 verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);", 21496 LLVMWithBeforeLambdaBody); 21497 verifyFormat( 21498 "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n" 21499 " FirstParam,\n" 21500 " SecondParam,\n" 21501 " ThirdParam,\n" 21502 " FourthParam);", 21503 LLVMWithBeforeLambdaBody); 21504 verifyFormat("FctWithLongLineInLambda_SLS_All(\n" 21505 " []() { return " 21506 "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n" 21507 " FirstParam,\n" 21508 " SecondParam,\n" 21509 " ThirdParam,\n" 21510 " FourthParam);", 21511 LLVMWithBeforeLambdaBody); 21512 verifyFormat( 21513 "FctWithLongLineInLambda_SLS_All(FirstParam,\n" 21514 " SecondParam,\n" 21515 " ThirdParam,\n" 21516 " FourthParam,\n" 21517 " []() { return SomeValueNotSoLong; });", 21518 LLVMWithBeforeLambdaBody); 21519 verifyFormat("FctWithLongLineInLambda_SLS_All(\n" 21520 " []()\n" 21521 " {\n" 21522 " return " 21523 "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB" 21524 "eConsiderAsInline;\n" 21525 " });", 21526 LLVMWithBeforeLambdaBody); 21527 verifyFormat( 21528 "FctWithLongLineInLambda_SLS_All(\n" 21529 " []()\n" 21530 " {\n" 21531 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21532 " AndShouldNotBeConsiderAsInline,\n" 21533 " LambdaBodyMustBeBreak);\n" 21534 " });", 21535 LLVMWithBeforeLambdaBody); 21536 verifyFormat("FctWithTwoParams_SLS_All(\n" 21537 " []()\n" 21538 " {\n" 21539 " // A cool function...\n" 21540 " return 43;\n" 21541 " },\n" 21542 " 87);", 21543 LLVMWithBeforeLambdaBody); 21544 verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);", 21545 LLVMWithBeforeLambdaBody); 21546 verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });", 21547 LLVMWithBeforeLambdaBody); 21548 verifyFormat( 21549 "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });", 21550 LLVMWithBeforeLambdaBody); 21551 verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; " 21552 "}); }, x);", 21553 LLVMWithBeforeLambdaBody); 21554 verifyFormat("TwoNestedLambdas_SLS_All(\n" 21555 " []()\n" 21556 " {\n" 21557 " // A cool function...\n" 21558 " return Call([]() { return 17; });\n" 21559 " });", 21560 LLVMWithBeforeLambdaBody); 21561 verifyFormat("TwoNestedLambdas_SLS_All(\n" 21562 " []()\n" 21563 " {\n" 21564 " return Call(\n" 21565 " []()\n" 21566 " {\n" 21567 " // A cool function...\n" 21568 " return 17;\n" 21569 " });\n" 21570 " });", 21571 LLVMWithBeforeLambdaBody); 21572 21573 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21574 FormatStyle::ShortLambdaStyle::SLS_None; 21575 21576 verifyFormat("auto select = [this]() -> const Library::Object *\n" 21577 "{\n" 21578 " return MyAssignment::SelectFromList(this);\n" 21579 "};\n", 21580 LLVMWithBeforeLambdaBody); 21581 21582 verifyFormat("auto select = [this]() -> const Library::Object &\n" 21583 "{\n" 21584 " return MyAssignment::SelectFromList(this);\n" 21585 "};\n", 21586 LLVMWithBeforeLambdaBody); 21587 21588 verifyFormat("auto select = [this]() -> std::unique_ptr<Object>\n" 21589 "{\n" 21590 " return MyAssignment::SelectFromList(this);\n" 21591 "};\n", 21592 LLVMWithBeforeLambdaBody); 21593 21594 verifyFormat("namespace test {\n" 21595 "class Test {\n" 21596 "public:\n" 21597 " Test() = default;\n" 21598 "};\n" 21599 "} // namespace test", 21600 LLVMWithBeforeLambdaBody); 21601 21602 // Lambdas with different indentation styles. 21603 Style = getLLVMStyleWithColumns(100); 21604 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 21605 " return promise.then(\n" 21606 " [this, &someVariable, someObject = " 21607 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21608 " return someObject.startAsyncAction().then(\n" 21609 " [this, &someVariable](AsyncActionResult result) " 21610 "mutable { result.processMore(); });\n" 21611 " });\n" 21612 "}\n", 21613 format("SomeResult doSomething(SomeObject promise) {\n" 21614 " return promise.then([this, &someVariable, someObject = " 21615 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21616 " return someObject.startAsyncAction().then([this, " 21617 "&someVariable](AsyncActionResult result) mutable {\n" 21618 " result.processMore();\n" 21619 " });\n" 21620 " });\n" 21621 "}\n", 21622 Style)); 21623 Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope; 21624 verifyFormat("test() {\n" 21625 " ([]() -> {\n" 21626 " int b = 32;\n" 21627 " return 3;\n" 21628 " }).foo();\n" 21629 "}", 21630 Style); 21631 verifyFormat("test() {\n" 21632 " []() -> {\n" 21633 " int b = 32;\n" 21634 " return 3;\n" 21635 " }\n" 21636 "}", 21637 Style); 21638 verifyFormat("std::sort(v.begin(), v.end(),\n" 21639 " [](const auto &someLongArgumentName, const auto " 21640 "&someOtherLongArgumentName) {\n" 21641 " return someLongArgumentName.someMemberVariable < " 21642 "someOtherLongArgumentName.someMemberVariable;\n" 21643 "});", 21644 Style); 21645 verifyFormat("test() {\n" 21646 " (\n" 21647 " []() -> {\n" 21648 " int b = 32;\n" 21649 " return 3;\n" 21650 " },\n" 21651 " foo, bar)\n" 21652 " .foo();\n" 21653 "}", 21654 Style); 21655 verifyFormat("test() {\n" 21656 " ([]() -> {\n" 21657 " int b = 32;\n" 21658 " return 3;\n" 21659 " })\n" 21660 " .foo()\n" 21661 " .bar();\n" 21662 "}", 21663 Style); 21664 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 21665 " return promise.then(\n" 21666 " [this, &someVariable, someObject = " 21667 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21668 " return someObject.startAsyncAction().then(\n" 21669 " [this, &someVariable](AsyncActionResult result) mutable { " 21670 "result.processMore(); });\n" 21671 " });\n" 21672 "}\n", 21673 format("SomeResult doSomething(SomeObject promise) {\n" 21674 " return promise.then([this, &someVariable, someObject = " 21675 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21676 " return someObject.startAsyncAction().then([this, " 21677 "&someVariable](AsyncActionResult result) mutable {\n" 21678 " result.processMore();\n" 21679 " });\n" 21680 " });\n" 21681 "}\n", 21682 Style)); 21683 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 21684 " return promise.then([this, &someVariable] {\n" 21685 " return someObject.startAsyncAction().then(\n" 21686 " [this, &someVariable](AsyncActionResult result) mutable { " 21687 "result.processMore(); });\n" 21688 " });\n" 21689 "}\n", 21690 format("SomeResult doSomething(SomeObject promise) {\n" 21691 " return promise.then([this, &someVariable] {\n" 21692 " return someObject.startAsyncAction().then([this, " 21693 "&someVariable](AsyncActionResult result) mutable {\n" 21694 " result.processMore();\n" 21695 " });\n" 21696 " });\n" 21697 "}\n", 21698 Style)); 21699 Style = getGoogleStyle(); 21700 Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope; 21701 EXPECT_EQ("#define A \\\n" 21702 " [] { \\\n" 21703 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 21704 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n" 21705 " }", 21706 format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 21707 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }", 21708 Style)); 21709 // TODO: The current formatting has a minor issue that's not worth fixing 21710 // right now whereby the closing brace is indented relative to the signature 21711 // instead of being aligned. This only happens with macros. 21712 } 21713 21714 TEST_F(FormatTest, LambdaWithLineComments) { 21715 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle(); 21716 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 21717 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 21718 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21719 FormatStyle::ShortLambdaStyle::SLS_All; 21720 21721 verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody); 21722 verifyFormat("auto k = []() // comment\n" 21723 "{ return; }", 21724 LLVMWithBeforeLambdaBody); 21725 verifyFormat("auto k = []() /* comment */ { return; }", 21726 LLVMWithBeforeLambdaBody); 21727 verifyFormat("auto k = []() /* comment */ /* comment */ { return; }", 21728 LLVMWithBeforeLambdaBody); 21729 verifyFormat("auto k = []() // X\n" 21730 "{ return; }", 21731 LLVMWithBeforeLambdaBody); 21732 verifyFormat( 21733 "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" 21734 "{ return; }", 21735 LLVMWithBeforeLambdaBody); 21736 } 21737 21738 TEST_F(FormatTest, EmptyLinesInLambdas) { 21739 verifyFormat("auto lambda = []() {\n" 21740 " x(); //\n" 21741 "};", 21742 "auto lambda = []() {\n" 21743 "\n" 21744 " x(); //\n" 21745 "\n" 21746 "};"); 21747 } 21748 21749 TEST_F(FormatTest, FormatsBlocks) { 21750 FormatStyle ShortBlocks = getLLVMStyle(); 21751 ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 21752 verifyFormat("int (^Block)(int, int);", ShortBlocks); 21753 verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks); 21754 verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks); 21755 verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks); 21756 verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks); 21757 verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks); 21758 21759 verifyFormat("foo(^{ bar(); });", ShortBlocks); 21760 verifyFormat("foo(a, ^{ bar(); });", ShortBlocks); 21761 verifyFormat("{ void (^block)(Object *x); }", ShortBlocks); 21762 21763 verifyFormat("[operation setCompletionBlock:^{\n" 21764 " [self onOperationDone];\n" 21765 "}];"); 21766 verifyFormat("int i = {[operation setCompletionBlock:^{\n" 21767 " [self onOperationDone];\n" 21768 "}]};"); 21769 verifyFormat("[operation setCompletionBlock:^(int *i) {\n" 21770 " f();\n" 21771 "}];"); 21772 verifyFormat("int a = [operation block:^int(int *i) {\n" 21773 " return 1;\n" 21774 "}];"); 21775 verifyFormat("[myObject doSomethingWith:arg1\n" 21776 " aaa:^int(int *a) {\n" 21777 " return 1;\n" 21778 " }\n" 21779 " bbb:f(a * bbbbbbbb)];"); 21780 21781 verifyFormat("[operation setCompletionBlock:^{\n" 21782 " [self.delegate newDataAvailable];\n" 21783 "}];", 21784 getLLVMStyleWithColumns(60)); 21785 verifyFormat("dispatch_async(_fileIOQueue, ^{\n" 21786 " NSString *path = [self sessionFilePath];\n" 21787 " if (path) {\n" 21788 " // ...\n" 21789 " }\n" 21790 "});"); 21791 verifyFormat("[[SessionService sharedService]\n" 21792 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 21793 " if (window) {\n" 21794 " [self windowDidLoad:window];\n" 21795 " } else {\n" 21796 " [self errorLoadingWindow];\n" 21797 " }\n" 21798 " }];"); 21799 verifyFormat("void (^largeBlock)(void) = ^{\n" 21800 " // ...\n" 21801 "};\n", 21802 getLLVMStyleWithColumns(40)); 21803 verifyFormat("[[SessionService sharedService]\n" 21804 " loadWindowWithCompletionBlock: //\n" 21805 " ^(SessionWindow *window) {\n" 21806 " if (window) {\n" 21807 " [self windowDidLoad:window];\n" 21808 " } else {\n" 21809 " [self errorLoadingWindow];\n" 21810 " }\n" 21811 " }];", 21812 getLLVMStyleWithColumns(60)); 21813 verifyFormat("[myObject doSomethingWith:arg1\n" 21814 " firstBlock:^(Foo *a) {\n" 21815 " // ...\n" 21816 " int i;\n" 21817 " }\n" 21818 " secondBlock:^(Bar *b) {\n" 21819 " // ...\n" 21820 " int i;\n" 21821 " }\n" 21822 " thirdBlock:^Foo(Bar *b) {\n" 21823 " // ...\n" 21824 " int i;\n" 21825 " }];"); 21826 verifyFormat("[myObject doSomethingWith:arg1\n" 21827 " firstBlock:-1\n" 21828 " secondBlock:^(Bar *b) {\n" 21829 " // ...\n" 21830 " int i;\n" 21831 " }];"); 21832 21833 verifyFormat("f(^{\n" 21834 " @autoreleasepool {\n" 21835 " if (a) {\n" 21836 " g();\n" 21837 " }\n" 21838 " }\n" 21839 "});"); 21840 verifyFormat("Block b = ^int *(A *a, B *b) {}"); 21841 verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n" 21842 "};"); 21843 21844 FormatStyle FourIndent = getLLVMStyle(); 21845 FourIndent.ObjCBlockIndentWidth = 4; 21846 verifyFormat("[operation setCompletionBlock:^{\n" 21847 " [self onOperationDone];\n" 21848 "}];", 21849 FourIndent); 21850 } 21851 21852 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) { 21853 FormatStyle ZeroColumn = getLLVMStyleWithColumns(0); 21854 21855 verifyFormat("[[SessionService sharedService] " 21856 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 21857 " if (window) {\n" 21858 " [self windowDidLoad:window];\n" 21859 " } else {\n" 21860 " [self errorLoadingWindow];\n" 21861 " }\n" 21862 "}];", 21863 ZeroColumn); 21864 EXPECT_EQ("[[SessionService sharedService]\n" 21865 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 21866 " if (window) {\n" 21867 " [self windowDidLoad:window];\n" 21868 " } else {\n" 21869 " [self errorLoadingWindow];\n" 21870 " }\n" 21871 " }];", 21872 format("[[SessionService sharedService]\n" 21873 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 21874 " if (window) {\n" 21875 " [self windowDidLoad:window];\n" 21876 " } else {\n" 21877 " [self errorLoadingWindow];\n" 21878 " }\n" 21879 "}];", 21880 ZeroColumn)); 21881 verifyFormat("[myObject doSomethingWith:arg1\n" 21882 " firstBlock:^(Foo *a) {\n" 21883 " // ...\n" 21884 " int i;\n" 21885 " }\n" 21886 " secondBlock:^(Bar *b) {\n" 21887 " // ...\n" 21888 " int i;\n" 21889 " }\n" 21890 " thirdBlock:^Foo(Bar *b) {\n" 21891 " // ...\n" 21892 " int i;\n" 21893 " }];", 21894 ZeroColumn); 21895 verifyFormat("f(^{\n" 21896 " @autoreleasepool {\n" 21897 " if (a) {\n" 21898 " g();\n" 21899 " }\n" 21900 " }\n" 21901 "});", 21902 ZeroColumn); 21903 verifyFormat("void (^largeBlock)(void) = ^{\n" 21904 " // ...\n" 21905 "};", 21906 ZeroColumn); 21907 21908 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 21909 EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };", 21910 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn)); 21911 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 21912 EXPECT_EQ("void (^largeBlock)(void) = ^{\n" 21913 " int i;\n" 21914 "};", 21915 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn)); 21916 } 21917 21918 TEST_F(FormatTest, SupportsCRLF) { 21919 EXPECT_EQ("int a;\r\n" 21920 "int b;\r\n" 21921 "int c;\r\n", 21922 format("int a;\r\n" 21923 " int b;\r\n" 21924 " int c;\r\n", 21925 getLLVMStyle())); 21926 EXPECT_EQ("int a;\r\n" 21927 "int b;\r\n" 21928 "int c;\r\n", 21929 format("int a;\r\n" 21930 " int b;\n" 21931 " int c;\r\n", 21932 getLLVMStyle())); 21933 EXPECT_EQ("int a;\n" 21934 "int b;\n" 21935 "int c;\n", 21936 format("int a;\r\n" 21937 " int b;\n" 21938 " int c;\n", 21939 getLLVMStyle())); 21940 EXPECT_EQ("\"aaaaaaa \"\r\n" 21941 "\"bbbbbbb\";\r\n", 21942 format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10))); 21943 EXPECT_EQ("#define A \\\r\n" 21944 " b; \\\r\n" 21945 " c; \\\r\n" 21946 " d;\r\n", 21947 format("#define A \\\r\n" 21948 " b; \\\r\n" 21949 " c; d; \r\n", 21950 getGoogleStyle())); 21951 21952 EXPECT_EQ("/*\r\n" 21953 "multi line block comments\r\n" 21954 "should not introduce\r\n" 21955 "an extra carriage return\r\n" 21956 "*/\r\n", 21957 format("/*\r\n" 21958 "multi line block comments\r\n" 21959 "should not introduce\r\n" 21960 "an extra carriage return\r\n" 21961 "*/\r\n")); 21962 EXPECT_EQ("/*\r\n" 21963 "\r\n" 21964 "*/", 21965 format("/*\r\n" 21966 " \r\r\r\n" 21967 "*/")); 21968 21969 FormatStyle style = getLLVMStyle(); 21970 21971 style.DeriveLineEnding = true; 21972 style.UseCRLF = false; 21973 EXPECT_EQ("union FooBarBazQux {\n" 21974 " int foo;\n" 21975 " int bar;\n" 21976 " int baz;\n" 21977 "};", 21978 format("union FooBarBazQux {\r\n" 21979 " int foo;\n" 21980 " int bar;\r\n" 21981 " int baz;\n" 21982 "};", 21983 style)); 21984 style.UseCRLF = true; 21985 EXPECT_EQ("union FooBarBazQux {\r\n" 21986 " int foo;\r\n" 21987 " int bar;\r\n" 21988 " int baz;\r\n" 21989 "};", 21990 format("union FooBarBazQux {\r\n" 21991 " int foo;\n" 21992 " int bar;\r\n" 21993 " int baz;\n" 21994 "};", 21995 style)); 21996 21997 style.DeriveLineEnding = false; 21998 style.UseCRLF = false; 21999 EXPECT_EQ("union FooBarBazQux {\n" 22000 " int foo;\n" 22001 " int bar;\n" 22002 " int baz;\n" 22003 " int qux;\n" 22004 "};", 22005 format("union FooBarBazQux {\r\n" 22006 " int foo;\n" 22007 " int bar;\r\n" 22008 " int baz;\n" 22009 " int qux;\r\n" 22010 "};", 22011 style)); 22012 style.UseCRLF = true; 22013 EXPECT_EQ("union FooBarBazQux {\r\n" 22014 " int foo;\r\n" 22015 " int bar;\r\n" 22016 " int baz;\r\n" 22017 " int qux;\r\n" 22018 "};", 22019 format("union FooBarBazQux {\r\n" 22020 " int foo;\n" 22021 " int bar;\r\n" 22022 " int baz;\n" 22023 " int qux;\n" 22024 "};", 22025 style)); 22026 22027 style.DeriveLineEnding = true; 22028 style.UseCRLF = false; 22029 EXPECT_EQ("union FooBarBazQux {\r\n" 22030 " int foo;\r\n" 22031 " int bar;\r\n" 22032 " int baz;\r\n" 22033 " int qux;\r\n" 22034 "};", 22035 format("union FooBarBazQux {\r\n" 22036 " int foo;\n" 22037 " int bar;\r\n" 22038 " int baz;\n" 22039 " int qux;\r\n" 22040 "};", 22041 style)); 22042 style.UseCRLF = true; 22043 EXPECT_EQ("union FooBarBazQux {\n" 22044 " int foo;\n" 22045 " int bar;\n" 22046 " int baz;\n" 22047 " int qux;\n" 22048 "};", 22049 format("union FooBarBazQux {\r\n" 22050 " int foo;\n" 22051 " int bar;\r\n" 22052 " int baz;\n" 22053 " int qux;\n" 22054 "};", 22055 style)); 22056 } 22057 22058 TEST_F(FormatTest, MunchSemicolonAfterBlocks) { 22059 verifyFormat("MY_CLASS(C) {\n" 22060 " int i;\n" 22061 " int j;\n" 22062 "};"); 22063 } 22064 22065 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) { 22066 FormatStyle TwoIndent = getLLVMStyleWithColumns(15); 22067 TwoIndent.ContinuationIndentWidth = 2; 22068 22069 EXPECT_EQ("int i =\n" 22070 " longFunction(\n" 22071 " arg);", 22072 format("int i = longFunction(arg);", TwoIndent)); 22073 22074 FormatStyle SixIndent = getLLVMStyleWithColumns(20); 22075 SixIndent.ContinuationIndentWidth = 6; 22076 22077 EXPECT_EQ("int i =\n" 22078 " longFunction(\n" 22079 " arg);", 22080 format("int i = longFunction(arg);", SixIndent)); 22081 } 22082 22083 TEST_F(FormatTest, WrappedClosingParenthesisIndent) { 22084 FormatStyle Style = getLLVMStyle(); 22085 verifyFormat("int Foo::getter(\n" 22086 " //\n" 22087 ") const {\n" 22088 " return foo;\n" 22089 "}", 22090 Style); 22091 verifyFormat("void Foo::setter(\n" 22092 " //\n" 22093 ") {\n" 22094 " foo = 1;\n" 22095 "}", 22096 Style); 22097 } 22098 22099 TEST_F(FormatTest, SpacesInAngles) { 22100 FormatStyle Spaces = getLLVMStyle(); 22101 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22102 22103 verifyFormat("vector< ::std::string > x1;", Spaces); 22104 verifyFormat("Foo< int, Bar > x2;", Spaces); 22105 verifyFormat("Foo< ::int, ::Bar > x3;", Spaces); 22106 22107 verifyFormat("static_cast< int >(arg);", Spaces); 22108 verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces); 22109 verifyFormat("f< int, float >();", Spaces); 22110 verifyFormat("template <> g() {}", Spaces); 22111 verifyFormat("template < std::vector< int > > f() {}", Spaces); 22112 verifyFormat("std::function< void(int, int) > fct;", Spaces); 22113 verifyFormat("void inFunction() { std::function< void(int, int) > fct; }", 22114 Spaces); 22115 22116 Spaces.Standard = FormatStyle::LS_Cpp03; 22117 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22118 verifyFormat("A< A< int > >();", Spaces); 22119 22120 Spaces.SpacesInAngles = FormatStyle::SIAS_Never; 22121 verifyFormat("A<A<int> >();", Spaces); 22122 22123 Spaces.SpacesInAngles = FormatStyle::SIAS_Leave; 22124 verifyFormat("vector< ::std::string> x4;", "vector<::std::string> x4;", 22125 Spaces); 22126 verifyFormat("vector< ::std::string > x4;", "vector<::std::string > x4;", 22127 Spaces); 22128 22129 verifyFormat("A<A<int> >();", Spaces); 22130 verifyFormat("A<A<int> >();", "A<A<int>>();", Spaces); 22131 verifyFormat("A< A< int > >();", Spaces); 22132 22133 Spaces.Standard = FormatStyle::LS_Cpp11; 22134 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22135 verifyFormat("A< A< int > >();", Spaces); 22136 22137 Spaces.SpacesInAngles = FormatStyle::SIAS_Never; 22138 verifyFormat("vector<::std::string> x4;", Spaces); 22139 verifyFormat("vector<int> x5;", Spaces); 22140 verifyFormat("Foo<int, Bar> x6;", Spaces); 22141 verifyFormat("Foo<::int, ::Bar> x7;", Spaces); 22142 22143 verifyFormat("A<A<int>>();", Spaces); 22144 22145 Spaces.SpacesInAngles = FormatStyle::SIAS_Leave; 22146 verifyFormat("vector<::std::string> x4;", Spaces); 22147 verifyFormat("vector< ::std::string > x4;", Spaces); 22148 verifyFormat("vector<int> x5;", Spaces); 22149 verifyFormat("vector< int > x5;", Spaces); 22150 verifyFormat("Foo<int, Bar> x6;", Spaces); 22151 verifyFormat("Foo< int, Bar > x6;", Spaces); 22152 verifyFormat("Foo<::int, ::Bar> x7;", Spaces); 22153 verifyFormat("Foo< ::int, ::Bar > x7;", Spaces); 22154 22155 verifyFormat("A<A<int>>();", Spaces); 22156 verifyFormat("A< A< int > >();", Spaces); 22157 verifyFormat("A<A<int > >();", Spaces); 22158 verifyFormat("A< A< int>>();", Spaces); 22159 22160 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22161 verifyFormat("// clang-format off\n" 22162 "foo<<<1, 1>>>();\n" 22163 "// clang-format on\n", 22164 Spaces); 22165 verifyFormat("// clang-format off\n" 22166 "foo< < <1, 1> > >();\n" 22167 "// clang-format on\n", 22168 Spaces); 22169 } 22170 22171 TEST_F(FormatTest, SpaceAfterTemplateKeyword) { 22172 FormatStyle Style = getLLVMStyle(); 22173 Style.SpaceAfterTemplateKeyword = false; 22174 verifyFormat("template<int> void foo();", Style); 22175 } 22176 22177 TEST_F(FormatTest, TripleAngleBrackets) { 22178 verifyFormat("f<<<1, 1>>>();"); 22179 verifyFormat("f<<<1, 1, 1, s>>>();"); 22180 verifyFormat("f<<<a, b, c, d>>>();"); 22181 EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();")); 22182 verifyFormat("f<param><<<1, 1>>>();"); 22183 verifyFormat("f<1><<<1, 1>>>();"); 22184 EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();")); 22185 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 22186 "aaaaaaaaaaa<<<\n 1, 1>>>();"); 22187 verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n" 22188 " <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();"); 22189 } 22190 22191 TEST_F(FormatTest, MergeLessLessAtEnd) { 22192 verifyFormat("<<"); 22193 EXPECT_EQ("< < <", format("\\\n<<<")); 22194 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 22195 "aaallvm::outs() <<"); 22196 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 22197 "aaaallvm::outs()\n <<"); 22198 } 22199 22200 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) { 22201 std::string code = "#if A\n" 22202 "#if B\n" 22203 "a.\n" 22204 "#endif\n" 22205 " a = 1;\n" 22206 "#else\n" 22207 "#endif\n" 22208 "#if C\n" 22209 "#else\n" 22210 "#endif\n"; 22211 EXPECT_EQ(code, format(code)); 22212 } 22213 22214 TEST_F(FormatTest, HandleConflictMarkers) { 22215 // Git/SVN conflict markers. 22216 EXPECT_EQ("int a;\n" 22217 "void f() {\n" 22218 " callme(some(parameter1,\n" 22219 "<<<<<<< text by the vcs\n" 22220 " parameter2),\n" 22221 "||||||| text by the vcs\n" 22222 " parameter2),\n" 22223 " parameter3,\n" 22224 "======= text by the vcs\n" 22225 " parameter2, parameter3),\n" 22226 ">>>>>>> text by the vcs\n" 22227 " otherparameter);\n", 22228 format("int a;\n" 22229 "void f() {\n" 22230 " callme(some(parameter1,\n" 22231 "<<<<<<< text by the vcs\n" 22232 " parameter2),\n" 22233 "||||||| text by the vcs\n" 22234 " parameter2),\n" 22235 " parameter3,\n" 22236 "======= text by the vcs\n" 22237 " parameter2,\n" 22238 " parameter3),\n" 22239 ">>>>>>> text by the vcs\n" 22240 " otherparameter);\n")); 22241 22242 // Perforce markers. 22243 EXPECT_EQ("void f() {\n" 22244 " function(\n" 22245 ">>>> text by the vcs\n" 22246 " parameter,\n" 22247 "==== text by the vcs\n" 22248 " parameter,\n" 22249 "==== text by the vcs\n" 22250 " parameter,\n" 22251 "<<<< text by the vcs\n" 22252 " parameter);\n", 22253 format("void f() {\n" 22254 " function(\n" 22255 ">>>> text by the vcs\n" 22256 " parameter,\n" 22257 "==== text by the vcs\n" 22258 " parameter,\n" 22259 "==== text by the vcs\n" 22260 " parameter,\n" 22261 "<<<< text by the vcs\n" 22262 " parameter);\n")); 22263 22264 EXPECT_EQ("<<<<<<<\n" 22265 "|||||||\n" 22266 "=======\n" 22267 ">>>>>>>", 22268 format("<<<<<<<\n" 22269 "|||||||\n" 22270 "=======\n" 22271 ">>>>>>>")); 22272 22273 EXPECT_EQ("<<<<<<<\n" 22274 "|||||||\n" 22275 "int i;\n" 22276 "=======\n" 22277 ">>>>>>>", 22278 format("<<<<<<<\n" 22279 "|||||||\n" 22280 "int i;\n" 22281 "=======\n" 22282 ">>>>>>>")); 22283 22284 // FIXME: Handle parsing of macros around conflict markers correctly: 22285 EXPECT_EQ("#define Macro \\\n" 22286 "<<<<<<<\n" 22287 "Something \\\n" 22288 "|||||||\n" 22289 "Else \\\n" 22290 "=======\n" 22291 "Other \\\n" 22292 ">>>>>>>\n" 22293 " End int i;\n", 22294 format("#define Macro \\\n" 22295 "<<<<<<<\n" 22296 " Something \\\n" 22297 "|||||||\n" 22298 " Else \\\n" 22299 "=======\n" 22300 " Other \\\n" 22301 ">>>>>>>\n" 22302 " End\n" 22303 "int i;\n")); 22304 22305 verifyFormat(R"(==== 22306 #ifdef A 22307 a 22308 #else 22309 b 22310 #endif 22311 )"); 22312 } 22313 22314 TEST_F(FormatTest, DisableRegions) { 22315 EXPECT_EQ("int i;\n" 22316 "// clang-format off\n" 22317 " int j;\n" 22318 "// clang-format on\n" 22319 "int k;", 22320 format(" int i;\n" 22321 " // clang-format off\n" 22322 " int j;\n" 22323 " // clang-format on\n" 22324 " int k;")); 22325 EXPECT_EQ("int i;\n" 22326 "/* clang-format off */\n" 22327 " int j;\n" 22328 "/* clang-format on */\n" 22329 "int k;", 22330 format(" int i;\n" 22331 " /* clang-format off */\n" 22332 " int j;\n" 22333 " /* clang-format on */\n" 22334 " int k;")); 22335 22336 // Don't reflow comments within disabled regions. 22337 EXPECT_EQ("// clang-format off\n" 22338 "// long long long long long long line\n" 22339 "/* clang-format on */\n" 22340 "/* long long long\n" 22341 " * long long long\n" 22342 " * line */\n" 22343 "int i;\n" 22344 "/* clang-format off */\n" 22345 "/* long long long long long long line */\n", 22346 format("// clang-format off\n" 22347 "// long long long long long long line\n" 22348 "/* clang-format on */\n" 22349 "/* long long long long long long line */\n" 22350 "int i;\n" 22351 "/* clang-format off */\n" 22352 "/* long long long long long long line */\n", 22353 getLLVMStyleWithColumns(20))); 22354 } 22355 22356 TEST_F(FormatTest, DoNotCrashOnInvalidInput) { 22357 format("? ) ="); 22358 verifyNoCrash("#define a\\\n /**/}"); 22359 } 22360 22361 TEST_F(FormatTest, FormatsTableGenCode) { 22362 FormatStyle Style = getLLVMStyle(); 22363 Style.Language = FormatStyle::LK_TableGen; 22364 verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style); 22365 } 22366 22367 TEST_F(FormatTest, ArrayOfTemplates) { 22368 EXPECT_EQ("auto a = new unique_ptr<int>[10];", 22369 format("auto a = new unique_ptr<int > [ 10];")); 22370 22371 FormatStyle Spaces = getLLVMStyle(); 22372 Spaces.SpacesInSquareBrackets = true; 22373 EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];", 22374 format("auto a = new unique_ptr<int > [10];", Spaces)); 22375 } 22376 22377 TEST_F(FormatTest, ArrayAsTemplateType) { 22378 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;", 22379 format("auto a = unique_ptr < Foo < Bar>[ 10]> ;")); 22380 22381 FormatStyle Spaces = getLLVMStyle(); 22382 Spaces.SpacesInSquareBrackets = true; 22383 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;", 22384 format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces)); 22385 } 22386 22387 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); } 22388 22389 TEST(FormatStyle, GetStyleWithEmptyFileName) { 22390 llvm::vfs::InMemoryFileSystem FS; 22391 auto Style1 = getStyle("file", "", "Google", "", &FS); 22392 ASSERT_TRUE((bool)Style1); 22393 ASSERT_EQ(*Style1, getGoogleStyle()); 22394 } 22395 22396 TEST(FormatStyle, GetStyleOfFile) { 22397 llvm::vfs::InMemoryFileSystem FS; 22398 // Test 1: format file in the same directory. 22399 ASSERT_TRUE( 22400 FS.addFile("/a/.clang-format", 0, 22401 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM"))); 22402 ASSERT_TRUE( 22403 FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22404 auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS); 22405 ASSERT_TRUE((bool)Style1); 22406 ASSERT_EQ(*Style1, getLLVMStyle()); 22407 22408 // Test 2.1: fallback to default. 22409 ASSERT_TRUE( 22410 FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22411 auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS); 22412 ASSERT_TRUE((bool)Style2); 22413 ASSERT_EQ(*Style2, getMozillaStyle()); 22414 22415 // Test 2.2: no format on 'none' fallback style. 22416 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS); 22417 ASSERT_TRUE((bool)Style2); 22418 ASSERT_EQ(*Style2, getNoStyle()); 22419 22420 // Test 2.3: format if config is found with no based style while fallback is 22421 // 'none'. 22422 ASSERT_TRUE(FS.addFile("/b/.clang-format", 0, 22423 llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2"))); 22424 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS); 22425 ASSERT_TRUE((bool)Style2); 22426 ASSERT_EQ(*Style2, getLLVMStyle()); 22427 22428 // Test 2.4: format if yaml with no based style, while fallback is 'none'. 22429 Style2 = getStyle("{}", "a.h", "none", "", &FS); 22430 ASSERT_TRUE((bool)Style2); 22431 ASSERT_EQ(*Style2, getLLVMStyle()); 22432 22433 // Test 3: format file in parent directory. 22434 ASSERT_TRUE( 22435 FS.addFile("/c/.clang-format", 0, 22436 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 22437 ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0, 22438 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22439 auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS); 22440 ASSERT_TRUE((bool)Style3); 22441 ASSERT_EQ(*Style3, getGoogleStyle()); 22442 22443 // Test 4: error on invalid fallback style 22444 auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS); 22445 ASSERT_FALSE((bool)Style4); 22446 llvm::consumeError(Style4.takeError()); 22447 22448 // Test 5: error on invalid yaml on command line 22449 auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS); 22450 ASSERT_FALSE((bool)Style5); 22451 llvm::consumeError(Style5.takeError()); 22452 22453 // Test 6: error on invalid style 22454 auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS); 22455 ASSERT_FALSE((bool)Style6); 22456 llvm::consumeError(Style6.takeError()); 22457 22458 // Test 7: found config file, error on parsing it 22459 ASSERT_TRUE( 22460 FS.addFile("/d/.clang-format", 0, 22461 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n" 22462 "InvalidKey: InvalidValue"))); 22463 ASSERT_TRUE( 22464 FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22465 auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS); 22466 ASSERT_FALSE((bool)Style7a); 22467 llvm::consumeError(Style7a.takeError()); 22468 22469 auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true); 22470 ASSERT_TRUE((bool)Style7b); 22471 22472 // Test 8: inferred per-language defaults apply. 22473 auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS); 22474 ASSERT_TRUE((bool)StyleTd); 22475 ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen)); 22476 22477 // Test 9.1.1: overwriting a file style, when no parent file exists with no 22478 // fallback style. 22479 ASSERT_TRUE(FS.addFile( 22480 "/e/sub/.clang-format", 0, 22481 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n" 22482 "ColumnLimit: 20"))); 22483 ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0, 22484 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22485 auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS); 22486 ASSERT_TRUE(static_cast<bool>(Style9)); 22487 ASSERT_EQ(*Style9, [] { 22488 auto Style = getNoStyle(); 22489 Style.ColumnLimit = 20; 22490 return Style; 22491 }()); 22492 22493 // Test 9.1.2: propagate more than one level with no parent file. 22494 ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0, 22495 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22496 ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0, 22497 llvm::MemoryBuffer::getMemBuffer( 22498 "BasedOnStyle: InheritParentConfig\n" 22499 "WhitespaceSensitiveMacros: ['FOO', 'BAR']"))); 22500 std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"}; 22501 22502 ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros); 22503 Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS); 22504 ASSERT_TRUE(static_cast<bool>(Style9)); 22505 ASSERT_EQ(*Style9, [&NonDefaultWhiteSpaceMacros] { 22506 auto Style = getNoStyle(); 22507 Style.ColumnLimit = 20; 22508 Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros; 22509 return Style; 22510 }()); 22511 22512 // Test 9.2: with LLVM fallback style 22513 Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS); 22514 ASSERT_TRUE(static_cast<bool>(Style9)); 22515 ASSERT_EQ(*Style9, [] { 22516 auto Style = getLLVMStyle(); 22517 Style.ColumnLimit = 20; 22518 return Style; 22519 }()); 22520 22521 // Test 9.3: with a parent file 22522 ASSERT_TRUE( 22523 FS.addFile("/e/.clang-format", 0, 22524 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n" 22525 "UseTab: Always"))); 22526 Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS); 22527 ASSERT_TRUE(static_cast<bool>(Style9)); 22528 ASSERT_EQ(*Style9, [] { 22529 auto Style = getGoogleStyle(); 22530 Style.ColumnLimit = 20; 22531 Style.UseTab = FormatStyle::UT_Always; 22532 return Style; 22533 }()); 22534 22535 // Test 9.4: propagate more than one level with a parent file. 22536 const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] { 22537 auto Style = getGoogleStyle(); 22538 Style.ColumnLimit = 20; 22539 Style.UseTab = FormatStyle::UT_Always; 22540 Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros; 22541 return Style; 22542 }(); 22543 22544 ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros); 22545 Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS); 22546 ASSERT_TRUE(static_cast<bool>(Style9)); 22547 ASSERT_EQ(*Style9, SubSubStyle); 22548 22549 // Test 9.5: use InheritParentConfig as style name 22550 Style9 = 22551 getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS); 22552 ASSERT_TRUE(static_cast<bool>(Style9)); 22553 ASSERT_EQ(*Style9, SubSubStyle); 22554 22555 // Test 9.6: use command line style with inheritance 22556 Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp", 22557 "none", "", &FS); 22558 ASSERT_TRUE(static_cast<bool>(Style9)); 22559 ASSERT_EQ(*Style9, SubSubStyle); 22560 22561 // Test 9.7: use command line style with inheritance and own config 22562 Style9 = getStyle("{BasedOnStyle: InheritParentConfig, " 22563 "WhitespaceSensitiveMacros: ['FOO', 'BAR']}", 22564 "/e/sub/code.cpp", "none", "", &FS); 22565 ASSERT_TRUE(static_cast<bool>(Style9)); 22566 ASSERT_EQ(*Style9, SubSubStyle); 22567 22568 // Test 9.8: use inheritance from a file without BasedOnStyle 22569 ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0, 22570 llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123"))); 22571 ASSERT_TRUE( 22572 FS.addFile("/e/withoutbase/sub/.clang-format", 0, 22573 llvm::MemoryBuffer::getMemBuffer( 22574 "BasedOnStyle: InheritParentConfig\nIndentWidth: 7"))); 22575 // Make sure we do not use the fallback style 22576 Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS); 22577 ASSERT_TRUE(static_cast<bool>(Style9)); 22578 ASSERT_EQ(*Style9, [] { 22579 auto Style = getLLVMStyle(); 22580 Style.ColumnLimit = 123; 22581 return Style; 22582 }()); 22583 22584 Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS); 22585 ASSERT_TRUE(static_cast<bool>(Style9)); 22586 ASSERT_EQ(*Style9, [] { 22587 auto Style = getLLVMStyle(); 22588 Style.ColumnLimit = 123; 22589 Style.IndentWidth = 7; 22590 return Style; 22591 }()); 22592 22593 // Test 9.9: use inheritance from a specific config file. 22594 Style9 = getStyle("file:/e/sub/sub/.clang-format", "/e/sub/sub/code.cpp", 22595 "none", "", &FS); 22596 ASSERT_TRUE(static_cast<bool>(Style9)); 22597 ASSERT_EQ(*Style9, SubSubStyle); 22598 } 22599 22600 TEST(FormatStyle, GetStyleOfSpecificFile) { 22601 llvm::vfs::InMemoryFileSystem FS; 22602 // Specify absolute path to a format file in a parent directory. 22603 ASSERT_TRUE( 22604 FS.addFile("/e/.clang-format", 0, 22605 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM"))); 22606 ASSERT_TRUE( 22607 FS.addFile("/e/explicit.clang-format", 0, 22608 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 22609 ASSERT_TRUE(FS.addFile("/e/sub/sub/sub/test.cpp", 0, 22610 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22611 auto Style = getStyle("file:/e/explicit.clang-format", 22612 "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS); 22613 ASSERT_TRUE(static_cast<bool>(Style)); 22614 ASSERT_EQ(*Style, getGoogleStyle()); 22615 22616 // Specify relative path to a format file. 22617 ASSERT_TRUE( 22618 FS.addFile("../../e/explicit.clang-format", 0, 22619 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 22620 Style = getStyle("file:../../e/explicit.clang-format", 22621 "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS); 22622 ASSERT_TRUE(static_cast<bool>(Style)); 22623 ASSERT_EQ(*Style, getGoogleStyle()); 22624 22625 // Specify path to a format file that does not exist. 22626 Style = getStyle("file:/e/missing.clang-format", "/e/sub/sub/sub/test.cpp", 22627 "LLVM", "", &FS); 22628 ASSERT_FALSE(static_cast<bool>(Style)); 22629 llvm::consumeError(Style.takeError()); 22630 22631 // Specify path to a file on the filesystem. 22632 SmallString<128> FormatFilePath; 22633 std::error_code ECF = llvm::sys::fs::createTemporaryFile( 22634 "FormatFileTest", "tpl", FormatFilePath); 22635 EXPECT_FALSE((bool)ECF); 22636 llvm::raw_fd_ostream FormatFileTest(FormatFilePath, ECF); 22637 EXPECT_FALSE((bool)ECF); 22638 FormatFileTest << "BasedOnStyle: Google\n"; 22639 FormatFileTest.close(); 22640 22641 SmallString<128> TestFilePath; 22642 std::error_code ECT = 22643 llvm::sys::fs::createTemporaryFile("CodeFileTest", "cc", TestFilePath); 22644 EXPECT_FALSE((bool)ECT); 22645 llvm::raw_fd_ostream CodeFileTest(TestFilePath, ECT); 22646 CodeFileTest << "int i;\n"; 22647 CodeFileTest.close(); 22648 22649 std::string format_file_arg = std::string("file:") + FormatFilePath.c_str(); 22650 Style = getStyle(format_file_arg, TestFilePath, "LLVM", "", nullptr); 22651 22652 llvm::sys::fs::remove(FormatFilePath.c_str()); 22653 llvm::sys::fs::remove(TestFilePath.c_str()); 22654 ASSERT_TRUE(static_cast<bool>(Style)); 22655 ASSERT_EQ(*Style, getGoogleStyle()); 22656 } 22657 22658 TEST_F(ReplacementTest, FormatCodeAfterReplacements) { 22659 // Column limit is 20. 22660 std::string Code = "Type *a =\n" 22661 " new Type();\n" 22662 "g(iiiii, 0, jjjjj,\n" 22663 " 0, kkkkk, 0, mm);\n" 22664 "int bad = format ;"; 22665 std::string Expected = "auto a = new Type();\n" 22666 "g(iiiii, nullptr,\n" 22667 " jjjjj, nullptr,\n" 22668 " kkkkk, nullptr,\n" 22669 " mm);\n" 22670 "int bad = format ;"; 22671 FileID ID = Context.createInMemoryFile("format.cpp", Code); 22672 tooling::Replacements Replaces = toReplacements( 22673 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6, 22674 "auto "), 22675 tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1, 22676 "nullptr"), 22677 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1, 22678 "nullptr"), 22679 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1, 22680 "nullptr")}); 22681 22682 FormatStyle Style = getLLVMStyle(); 22683 Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility. 22684 auto FormattedReplaces = formatReplacements(Code, Replaces, Style); 22685 EXPECT_TRUE(static_cast<bool>(FormattedReplaces)) 22686 << llvm::toString(FormattedReplaces.takeError()) << "\n"; 22687 auto Result = applyAllReplacements(Code, *FormattedReplaces); 22688 EXPECT_TRUE(static_cast<bool>(Result)); 22689 EXPECT_EQ(Expected, *Result); 22690 } 22691 22692 TEST_F(ReplacementTest, SortIncludesAfterReplacement) { 22693 std::string Code = "#include \"a.h\"\n" 22694 "#include \"c.h\"\n" 22695 "\n" 22696 "int main() {\n" 22697 " return 0;\n" 22698 "}"; 22699 std::string Expected = "#include \"a.h\"\n" 22700 "#include \"b.h\"\n" 22701 "#include \"c.h\"\n" 22702 "\n" 22703 "int main() {\n" 22704 " return 0;\n" 22705 "}"; 22706 FileID ID = Context.createInMemoryFile("fix.cpp", Code); 22707 tooling::Replacements Replaces = toReplacements( 22708 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0, 22709 "#include \"b.h\"\n")}); 22710 22711 FormatStyle Style = getLLVMStyle(); 22712 Style.SortIncludes = FormatStyle::SI_CaseSensitive; 22713 auto FormattedReplaces = formatReplacements(Code, Replaces, Style); 22714 EXPECT_TRUE(static_cast<bool>(FormattedReplaces)) 22715 << llvm::toString(FormattedReplaces.takeError()) << "\n"; 22716 auto Result = applyAllReplacements(Code, *FormattedReplaces); 22717 EXPECT_TRUE(static_cast<bool>(Result)); 22718 EXPECT_EQ(Expected, *Result); 22719 } 22720 22721 TEST_F(FormatTest, FormatSortsUsingDeclarations) { 22722 EXPECT_EQ("using std::cin;\n" 22723 "using std::cout;", 22724 format("using std::cout;\n" 22725 "using std::cin;", 22726 getGoogleStyle())); 22727 } 22728 22729 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) { 22730 FormatStyle Style = getLLVMStyle(); 22731 Style.Standard = FormatStyle::LS_Cpp03; 22732 // cpp03 recognize this string as identifier u8 and literal character 'a' 22733 EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style)); 22734 } 22735 22736 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) { 22737 // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers 22738 // all modes, including C++11, C++14 and C++17 22739 EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';")); 22740 } 22741 22742 TEST_F(FormatTest, DoNotFormatLikelyXml) { 22743 EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle())); 22744 EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle())); 22745 } 22746 22747 TEST_F(FormatTest, StructuredBindings) { 22748 // Structured bindings is a C++17 feature. 22749 // all modes, including C++11, C++14 and C++17 22750 verifyFormat("auto [a, b] = f();"); 22751 EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();")); 22752 EXPECT_EQ("const auto [a, b] = f();", format("const auto[a, b] = f();")); 22753 EXPECT_EQ("auto const [a, b] = f();", format("auto const[a, b] = f();")); 22754 EXPECT_EQ("auto const volatile [a, b] = f();", 22755 format("auto const volatile[a, b] = f();")); 22756 EXPECT_EQ("auto [a, b, c] = f();", format("auto [ a , b,c ] = f();")); 22757 EXPECT_EQ("auto &[a, b, c] = f();", 22758 format("auto &[ a , b,c ] = f();")); 22759 EXPECT_EQ("auto &&[a, b, c] = f();", 22760 format("auto &&[ a , b,c ] = f();")); 22761 EXPECT_EQ("auto const &[a, b] = f();", format("auto const&[a, b] = f();")); 22762 EXPECT_EQ("auto const volatile &&[a, b] = f();", 22763 format("auto const volatile &&[a, b] = f();")); 22764 EXPECT_EQ("auto const &&[a, b] = f();", 22765 format("auto const && [a, b] = f();")); 22766 EXPECT_EQ("const auto &[a, b] = f();", 22767 format("const auto & [a, b] = f();")); 22768 EXPECT_EQ("const auto volatile &&[a, b] = f();", 22769 format("const auto volatile &&[a, b] = f();")); 22770 EXPECT_EQ("volatile const auto &&[a, b] = f();", 22771 format("volatile const auto &&[a, b] = f();")); 22772 EXPECT_EQ("const auto &&[a, b] = f();", 22773 format("const auto && [a, b] = f();")); 22774 22775 // Make sure we don't mistake structured bindings for lambdas. 22776 FormatStyle PointerMiddle = getLLVMStyle(); 22777 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle; 22778 verifyFormat("auto [a1, b]{A * i};", getGoogleStyle()); 22779 verifyFormat("auto [a2, b]{A * i};", getLLVMStyle()); 22780 verifyFormat("auto [a3, b]{A * i};", PointerMiddle); 22781 verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle()); 22782 verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle()); 22783 verifyFormat("auto const [a3, b]{A * i};", PointerMiddle); 22784 verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle()); 22785 verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle()); 22786 verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle); 22787 verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle()); 22788 verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle()); 22789 verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle); 22790 22791 EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}", 22792 format("for (const auto && [a, b] : some_range) {\n}")); 22793 EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}", 22794 format("for (const auto & [a, b] : some_range) {\n}")); 22795 EXPECT_EQ("for (const auto [a, b] : some_range) {\n}", 22796 format("for (const auto[a, b] : some_range) {\n}")); 22797 EXPECT_EQ("auto [x, y](expr);", format("auto[x,y] (expr);")); 22798 EXPECT_EQ("auto &[x, y](expr);", format("auto & [x,y] (expr);")); 22799 EXPECT_EQ("auto &&[x, y](expr);", format("auto && [x,y] (expr);")); 22800 EXPECT_EQ("auto const &[x, y](expr);", 22801 format("auto const & [x,y] (expr);")); 22802 EXPECT_EQ("auto const &&[x, y](expr);", 22803 format("auto const && [x,y] (expr);")); 22804 EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y] {expr};")); 22805 EXPECT_EQ("auto const &[x, y]{expr};", 22806 format("auto const & [x,y] {expr};")); 22807 EXPECT_EQ("auto const &&[x, y]{expr};", 22808 format("auto const && [x,y] {expr};")); 22809 22810 FormatStyle Spaces = getLLVMStyle(); 22811 Spaces.SpacesInSquareBrackets = true; 22812 verifyFormat("auto [ a, b ] = f();", Spaces); 22813 verifyFormat("auto &&[ a, b ] = f();", Spaces); 22814 verifyFormat("auto &[ a, b ] = f();", Spaces); 22815 verifyFormat("auto const &&[ a, b ] = f();", Spaces); 22816 verifyFormat("auto const &[ a, b ] = f();", Spaces); 22817 } 22818 22819 TEST_F(FormatTest, FileAndCode) { 22820 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", "")); 22821 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", "")); 22822 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", "")); 22823 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "")); 22824 EXPECT_EQ(FormatStyle::LK_ObjC, 22825 guessLanguage("foo.h", "@interface Foo\n@end\n")); 22826 EXPECT_EQ( 22827 FormatStyle::LK_ObjC, 22828 guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }")); 22829 EXPECT_EQ(FormatStyle::LK_ObjC, 22830 guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))")); 22831 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;")); 22832 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", "")); 22833 EXPECT_EQ(FormatStyle::LK_ObjC, 22834 guessLanguage("foo", "@interface Foo\n@end\n")); 22835 EXPECT_EQ(FormatStyle::LK_ObjC, 22836 guessLanguage("foo.h", "int DoStuff(CGRect rect);\n")); 22837 EXPECT_EQ( 22838 FormatStyle::LK_ObjC, 22839 guessLanguage("foo.h", 22840 "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n")); 22841 EXPECT_EQ( 22842 FormatStyle::LK_Cpp, 22843 guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;")); 22844 // Only one of the two preprocessor regions has ObjC-like code. 22845 EXPECT_EQ(FormatStyle::LK_ObjC, 22846 guessLanguage("foo.h", "#if A\n" 22847 "#define B() C\n" 22848 "#else\n" 22849 "#define B() [NSString a:@\"\"]\n" 22850 "#endif\n")); 22851 } 22852 22853 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) { 22854 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];")); 22855 EXPECT_EQ(FormatStyle::LK_ObjC, 22856 guessLanguage("foo.h", "array[[calculator getIndex]];")); 22857 EXPECT_EQ(FormatStyle::LK_Cpp, 22858 guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];")); 22859 EXPECT_EQ( 22860 FormatStyle::LK_Cpp, 22861 guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];")); 22862 EXPECT_EQ(FormatStyle::LK_ObjC, 22863 guessLanguage("foo.h", "[[noreturn foo] bar];")); 22864 EXPECT_EQ(FormatStyle::LK_Cpp, 22865 guessLanguage("foo.h", "[[clang::fallthrough]];")); 22866 EXPECT_EQ(FormatStyle::LK_ObjC, 22867 guessLanguage("foo.h", "[[clang:fallthrough] foo];")); 22868 EXPECT_EQ(FormatStyle::LK_Cpp, 22869 guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];")); 22870 EXPECT_EQ(FormatStyle::LK_Cpp, 22871 guessLanguage("foo.h", "[[using clang: fallthrough]];")); 22872 EXPECT_EQ(FormatStyle::LK_ObjC, 22873 guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];")); 22874 EXPECT_EQ(FormatStyle::LK_Cpp, 22875 guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];")); 22876 EXPECT_EQ( 22877 FormatStyle::LK_Cpp, 22878 guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)")); 22879 EXPECT_EQ( 22880 FormatStyle::LK_Cpp, 22881 guessLanguage("foo.h", 22882 "[[clang::callable_when(\"unconsumed\", \"unknown\")]]")); 22883 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]")); 22884 } 22885 22886 TEST_F(FormatTest, GuessLanguageWithCaret) { 22887 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);")); 22888 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);")); 22889 EXPECT_EQ(FormatStyle::LK_ObjC, 22890 guessLanguage("foo.h", "int(^)(char, float);")); 22891 EXPECT_EQ(FormatStyle::LK_ObjC, 22892 guessLanguage("foo.h", "int(^foo)(char, float);")); 22893 EXPECT_EQ(FormatStyle::LK_ObjC, 22894 guessLanguage("foo.h", "int(^foo[10])(char, float);")); 22895 EXPECT_EQ(FormatStyle::LK_ObjC, 22896 guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);")); 22897 EXPECT_EQ( 22898 FormatStyle::LK_ObjC, 22899 guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);")); 22900 } 22901 22902 TEST_F(FormatTest, GuessLanguageWithPragmas) { 22903 EXPECT_EQ(FormatStyle::LK_Cpp, 22904 guessLanguage("foo.h", "__pragma(warning(disable:))")); 22905 EXPECT_EQ(FormatStyle::LK_Cpp, 22906 guessLanguage("foo.h", "#pragma(warning(disable:))")); 22907 EXPECT_EQ(FormatStyle::LK_Cpp, 22908 guessLanguage("foo.h", "_Pragma(warning(disable:))")); 22909 } 22910 22911 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) { 22912 // ASM symbolic names are identifiers that must be surrounded by [] without 22913 // space in between: 22914 // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands 22915 22916 // Example from https://bugs.llvm.org/show_bug.cgi?id=45108. 22917 verifyFormat(R"(// 22918 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result)); 22919 )"); 22920 22921 // A list of several ASM symbolic names. 22922 verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)"); 22923 22924 // ASM symbolic names in inline ASM with inputs and outputs. 22925 verifyFormat(R"(// 22926 asm("cmoveq %1, %2, %[result]" 22927 : [result] "=r"(result) 22928 : "r"(test), "r"(new), "[result]"(old)); 22929 )"); 22930 22931 // ASM symbolic names in inline ASM with no outputs. 22932 verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)"); 22933 } 22934 22935 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) { 22936 EXPECT_EQ(FormatStyle::LK_Cpp, 22937 guessLanguage("foo.h", "void f() {\n" 22938 " asm (\"mov %[e], %[d]\"\n" 22939 " : [d] \"=rm\" (d)\n" 22940 " [e] \"rm\" (*e));\n" 22941 "}")); 22942 EXPECT_EQ(FormatStyle::LK_Cpp, 22943 guessLanguage("foo.h", "void f() {\n" 22944 " _asm (\"mov %[e], %[d]\"\n" 22945 " : [d] \"=rm\" (d)\n" 22946 " [e] \"rm\" (*e));\n" 22947 "}")); 22948 EXPECT_EQ(FormatStyle::LK_Cpp, 22949 guessLanguage("foo.h", "void f() {\n" 22950 " __asm (\"mov %[e], %[d]\"\n" 22951 " : [d] \"=rm\" (d)\n" 22952 " [e] \"rm\" (*e));\n" 22953 "}")); 22954 EXPECT_EQ(FormatStyle::LK_Cpp, 22955 guessLanguage("foo.h", "void f() {\n" 22956 " __asm__ (\"mov %[e], %[d]\"\n" 22957 " : [d] \"=rm\" (d)\n" 22958 " [e] \"rm\" (*e));\n" 22959 "}")); 22960 EXPECT_EQ(FormatStyle::LK_Cpp, 22961 guessLanguage("foo.h", "void f() {\n" 22962 " asm (\"mov %[e], %[d]\"\n" 22963 " : [d] \"=rm\" (d),\n" 22964 " [e] \"rm\" (*e));\n" 22965 "}")); 22966 EXPECT_EQ(FormatStyle::LK_Cpp, 22967 guessLanguage("foo.h", "void f() {\n" 22968 " asm volatile (\"mov %[e], %[d]\"\n" 22969 " : [d] \"=rm\" (d)\n" 22970 " [e] \"rm\" (*e));\n" 22971 "}")); 22972 } 22973 22974 TEST_F(FormatTest, GuessLanguageWithChildLines) { 22975 EXPECT_EQ(FormatStyle::LK_Cpp, 22976 guessLanguage("foo.h", "#define FOO ({ std::string s; })")); 22977 EXPECT_EQ(FormatStyle::LK_ObjC, 22978 guessLanguage("foo.h", "#define FOO ({ NSString *s; })")); 22979 EXPECT_EQ( 22980 FormatStyle::LK_Cpp, 22981 guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })")); 22982 EXPECT_EQ( 22983 FormatStyle::LK_ObjC, 22984 guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })")); 22985 } 22986 22987 TEST_F(FormatTest, TypenameMacros) { 22988 std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"}; 22989 22990 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353 22991 FormatStyle Google = getGoogleStyleWithColumns(0); 22992 Google.TypenameMacros = TypenameMacros; 22993 verifyFormat("struct foo {\n" 22994 " int bar;\n" 22995 " TAILQ_ENTRY(a) bleh;\n" 22996 "};", 22997 Google); 22998 22999 FormatStyle Macros = getLLVMStyle(); 23000 Macros.TypenameMacros = TypenameMacros; 23001 23002 verifyFormat("STACK_OF(int) a;", Macros); 23003 verifyFormat("STACK_OF(int) *a;", Macros); 23004 verifyFormat("STACK_OF(int const *) *a;", Macros); 23005 verifyFormat("STACK_OF(int *const) *a;", Macros); 23006 verifyFormat("STACK_OF(int, string) a;", Macros); 23007 verifyFormat("STACK_OF(LIST(int)) a;", Macros); 23008 verifyFormat("STACK_OF(LIST(int)) a, b;", Macros); 23009 verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros); 23010 verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros); 23011 verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros); 23012 verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros); 23013 23014 Macros.PointerAlignment = FormatStyle::PAS_Left; 23015 verifyFormat("STACK_OF(int)* a;", Macros); 23016 verifyFormat("STACK_OF(int*)* a;", Macros); 23017 verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros); 23018 verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros); 23019 verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros); 23020 } 23021 23022 TEST_F(FormatTest, AtomicQualifier) { 23023 // Check that we treate _Atomic as a type and not a function call 23024 FormatStyle Google = getGoogleStyleWithColumns(0); 23025 verifyFormat("struct foo {\n" 23026 " int a1;\n" 23027 " _Atomic(a) a2;\n" 23028 " _Atomic(_Atomic(int) *const) a3;\n" 23029 "};", 23030 Google); 23031 verifyFormat("_Atomic(uint64_t) a;"); 23032 verifyFormat("_Atomic(uint64_t) *a;"); 23033 verifyFormat("_Atomic(uint64_t const *) *a;"); 23034 verifyFormat("_Atomic(uint64_t *const) *a;"); 23035 verifyFormat("_Atomic(const uint64_t *) *a;"); 23036 verifyFormat("_Atomic(uint64_t) a;"); 23037 verifyFormat("_Atomic(_Atomic(uint64_t)) a;"); 23038 verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;"); 23039 verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}"); 23040 verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);"); 23041 23042 verifyFormat("_Atomic(uint64_t) *s(InitValue);"); 23043 verifyFormat("_Atomic(uint64_t) *s{InitValue};"); 23044 FormatStyle Style = getLLVMStyle(); 23045 Style.PointerAlignment = FormatStyle::PAS_Left; 23046 verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style); 23047 verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style); 23048 verifyFormat("_Atomic(int)* a;", Style); 23049 verifyFormat("_Atomic(int*)* a;", Style); 23050 verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style); 23051 23052 Style.SpacesInCStyleCastParentheses = true; 23053 Style.SpacesInParentheses = false; 23054 verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style); 23055 Style.SpacesInCStyleCastParentheses = false; 23056 Style.SpacesInParentheses = true; 23057 verifyFormat("x = (_Atomic( uint64_t ))*a;", Style); 23058 verifyFormat("x = (_Atomic( uint64_t ))&a;", Style); 23059 } 23060 23061 TEST_F(FormatTest, AmbersandInLamda) { 23062 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899 23063 FormatStyle AlignStyle = getLLVMStyle(); 23064 AlignStyle.PointerAlignment = FormatStyle::PAS_Left; 23065 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle); 23066 AlignStyle.PointerAlignment = FormatStyle::PAS_Right; 23067 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle); 23068 } 23069 23070 TEST_F(FormatTest, SpacesInConditionalStatement) { 23071 FormatStyle Spaces = getLLVMStyle(); 23072 Spaces.IfMacros.clear(); 23073 Spaces.IfMacros.push_back("MYIF"); 23074 Spaces.SpacesInConditionalStatement = true; 23075 verifyFormat("for ( int i = 0; i; i++ )\n continue;", Spaces); 23076 verifyFormat("if ( !a )\n return;", Spaces); 23077 verifyFormat("if ( a )\n return;", Spaces); 23078 verifyFormat("if constexpr ( a )\n return;", Spaces); 23079 verifyFormat("MYIF ( a )\n return;", Spaces); 23080 verifyFormat("MYIF ( a )\n return;\nelse MYIF ( b )\n return;", Spaces); 23081 verifyFormat("MYIF ( a )\n return;\nelse\n return;", Spaces); 23082 verifyFormat("switch ( a )\ncase 1:\n return;", Spaces); 23083 verifyFormat("while ( a )\n return;", Spaces); 23084 verifyFormat("while ( (a && b) )\n return;", Spaces); 23085 verifyFormat("do {\n} while ( 1 != 0 );", Spaces); 23086 verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces); 23087 // Check that space on the left of "::" is inserted as expected at beginning 23088 // of condition. 23089 verifyFormat("while ( ::func() )\n return;", Spaces); 23090 23091 // Check impact of ControlStatementsExceptControlMacros is honored. 23092 Spaces.SpaceBeforeParens = 23093 FormatStyle::SBPO_ControlStatementsExceptControlMacros; 23094 verifyFormat("MYIF( a )\n return;", Spaces); 23095 verifyFormat("MYIF( a )\n return;\nelse MYIF( b )\n return;", Spaces); 23096 verifyFormat("MYIF( a )\n return;\nelse\n return;", Spaces); 23097 } 23098 23099 TEST_F(FormatTest, AlternativeOperators) { 23100 // Test case for ensuring alternate operators are not 23101 // combined with their right most neighbour. 23102 verifyFormat("int a and b;"); 23103 verifyFormat("int a and_eq b;"); 23104 verifyFormat("int a bitand b;"); 23105 verifyFormat("int a bitor b;"); 23106 verifyFormat("int a compl b;"); 23107 verifyFormat("int a not b;"); 23108 verifyFormat("int a not_eq b;"); 23109 verifyFormat("int a or b;"); 23110 verifyFormat("int a xor b;"); 23111 verifyFormat("int a xor_eq b;"); 23112 verifyFormat("return this not_eq bitand other;"); 23113 verifyFormat("bool operator not_eq(const X bitand other)"); 23114 23115 verifyFormat("int a and 5;"); 23116 verifyFormat("int a and_eq 5;"); 23117 verifyFormat("int a bitand 5;"); 23118 verifyFormat("int a bitor 5;"); 23119 verifyFormat("int a compl 5;"); 23120 verifyFormat("int a not 5;"); 23121 verifyFormat("int a not_eq 5;"); 23122 verifyFormat("int a or 5;"); 23123 verifyFormat("int a xor 5;"); 23124 verifyFormat("int a xor_eq 5;"); 23125 23126 verifyFormat("int a compl(5);"); 23127 verifyFormat("int a not(5);"); 23128 23129 /* FIXME handle alternate tokens 23130 * https://en.cppreference.com/w/cpp/language/operator_alternative 23131 // alternative tokens 23132 verifyFormat("compl foo();"); // ~foo(); 23133 verifyFormat("foo() <%%>;"); // foo(); 23134 verifyFormat("void foo() <%%>;"); // void foo(){} 23135 verifyFormat("int a <:1:>;"); // int a[1];[ 23136 verifyFormat("%:define ABC abc"); // #define ABC abc 23137 verifyFormat("%:%:"); // ## 23138 */ 23139 } 23140 23141 TEST_F(FormatTest, STLWhileNotDefineChed) { 23142 verifyFormat("#if defined(while)\n" 23143 "#define while EMIT WARNING C4005\n" 23144 "#endif // while"); 23145 } 23146 23147 TEST_F(FormatTest, OperatorSpacing) { 23148 FormatStyle Style = getLLVMStyle(); 23149 Style.PointerAlignment = FormatStyle::PAS_Right; 23150 verifyFormat("Foo::operator*();", Style); 23151 verifyFormat("Foo::operator void *();", Style); 23152 verifyFormat("Foo::operator void **();", Style); 23153 verifyFormat("Foo::operator void *&();", Style); 23154 verifyFormat("Foo::operator void *&&();", Style); 23155 verifyFormat("Foo::operator void const *();", Style); 23156 verifyFormat("Foo::operator void const **();", Style); 23157 verifyFormat("Foo::operator void const *&();", Style); 23158 verifyFormat("Foo::operator void const *&&();", Style); 23159 verifyFormat("Foo::operator()(void *);", Style); 23160 verifyFormat("Foo::operator*(void *);", Style); 23161 verifyFormat("Foo::operator*();", Style); 23162 verifyFormat("Foo::operator**();", Style); 23163 verifyFormat("Foo::operator&();", Style); 23164 verifyFormat("Foo::operator<int> *();", Style); 23165 verifyFormat("Foo::operator<Foo> *();", Style); 23166 verifyFormat("Foo::operator<int> **();", Style); 23167 verifyFormat("Foo::operator<Foo> **();", Style); 23168 verifyFormat("Foo::operator<int> &();", Style); 23169 verifyFormat("Foo::operator<Foo> &();", Style); 23170 verifyFormat("Foo::operator<int> &&();", Style); 23171 verifyFormat("Foo::operator<Foo> &&();", Style); 23172 verifyFormat("Foo::operator<int> *&();", Style); 23173 verifyFormat("Foo::operator<Foo> *&();", Style); 23174 verifyFormat("Foo::operator<int> *&&();", Style); 23175 verifyFormat("Foo::operator<Foo> *&&();", Style); 23176 verifyFormat("operator*(int (*)(), class Foo);", Style); 23177 23178 verifyFormat("Foo::operator&();", Style); 23179 verifyFormat("Foo::operator void &();", Style); 23180 verifyFormat("Foo::operator void const &();", Style); 23181 verifyFormat("Foo::operator()(void &);", Style); 23182 verifyFormat("Foo::operator&(void &);", Style); 23183 verifyFormat("Foo::operator&();", Style); 23184 verifyFormat("operator&(int (&)(), class Foo);", Style); 23185 verifyFormat("operator&&(int (&)(), class Foo);", Style); 23186 23187 verifyFormat("Foo::operator&&();", Style); 23188 verifyFormat("Foo::operator**();", Style); 23189 verifyFormat("Foo::operator void &&();", Style); 23190 verifyFormat("Foo::operator void const &&();", Style); 23191 verifyFormat("Foo::operator()(void &&);", Style); 23192 verifyFormat("Foo::operator&&(void &&);", Style); 23193 verifyFormat("Foo::operator&&();", Style); 23194 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23195 verifyFormat("operator const nsTArrayRight<E> &()", Style); 23196 verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()", 23197 Style); 23198 verifyFormat("operator void **()", Style); 23199 verifyFormat("operator const FooRight<Object> &()", Style); 23200 verifyFormat("operator const FooRight<Object> *()", Style); 23201 verifyFormat("operator const FooRight<Object> **()", Style); 23202 verifyFormat("operator const FooRight<Object> *&()", Style); 23203 verifyFormat("operator const FooRight<Object> *&&()", Style); 23204 23205 Style.PointerAlignment = FormatStyle::PAS_Left; 23206 verifyFormat("Foo::operator*();", Style); 23207 verifyFormat("Foo::operator**();", Style); 23208 verifyFormat("Foo::operator void*();", Style); 23209 verifyFormat("Foo::operator void**();", Style); 23210 verifyFormat("Foo::operator void*&();", Style); 23211 verifyFormat("Foo::operator void*&&();", Style); 23212 verifyFormat("Foo::operator void const*();", Style); 23213 verifyFormat("Foo::operator void const**();", Style); 23214 verifyFormat("Foo::operator void const*&();", Style); 23215 verifyFormat("Foo::operator void const*&&();", Style); 23216 verifyFormat("Foo::operator/*comment*/ void*();", Style); 23217 verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style); 23218 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style); 23219 verifyFormat("Foo::operator()(void*);", Style); 23220 verifyFormat("Foo::operator*(void*);", Style); 23221 verifyFormat("Foo::operator*();", Style); 23222 verifyFormat("Foo::operator<int>*();", Style); 23223 verifyFormat("Foo::operator<Foo>*();", Style); 23224 verifyFormat("Foo::operator<int>**();", Style); 23225 verifyFormat("Foo::operator<Foo>**();", Style); 23226 verifyFormat("Foo::operator<Foo>*&();", Style); 23227 verifyFormat("Foo::operator<int>&();", Style); 23228 verifyFormat("Foo::operator<Foo>&();", Style); 23229 verifyFormat("Foo::operator<int>&&();", Style); 23230 verifyFormat("Foo::operator<Foo>&&();", Style); 23231 verifyFormat("Foo::operator<int>*&();", Style); 23232 verifyFormat("Foo::operator<Foo>*&();", Style); 23233 verifyFormat("operator*(int (*)(), class Foo);", Style); 23234 23235 verifyFormat("Foo::operator&();", Style); 23236 verifyFormat("Foo::operator void&();", Style); 23237 verifyFormat("Foo::operator void const&();", Style); 23238 verifyFormat("Foo::operator/*comment*/ void&();", Style); 23239 verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style); 23240 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style); 23241 verifyFormat("Foo::operator()(void&);", Style); 23242 verifyFormat("Foo::operator&(void&);", Style); 23243 verifyFormat("Foo::operator&();", Style); 23244 verifyFormat("operator&(int (&)(), class Foo);", Style); 23245 verifyFormat("operator&(int (&&)(), class Foo);", Style); 23246 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23247 23248 verifyFormat("Foo::operator&&();", Style); 23249 verifyFormat("Foo::operator void&&();", Style); 23250 verifyFormat("Foo::operator void const&&();", Style); 23251 verifyFormat("Foo::operator/*comment*/ void&&();", Style); 23252 verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style); 23253 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style); 23254 verifyFormat("Foo::operator()(void&&);", Style); 23255 verifyFormat("Foo::operator&&(void&&);", Style); 23256 verifyFormat("Foo::operator&&();", Style); 23257 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23258 verifyFormat("operator const nsTArrayLeft<E>&()", Style); 23259 verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()", 23260 Style); 23261 verifyFormat("operator void**()", Style); 23262 verifyFormat("operator const FooLeft<Object>&()", Style); 23263 verifyFormat("operator const FooLeft<Object>*()", Style); 23264 verifyFormat("operator const FooLeft<Object>**()", Style); 23265 verifyFormat("operator const FooLeft<Object>*&()", Style); 23266 verifyFormat("operator const FooLeft<Object>*&&()", Style); 23267 23268 // PR45107 23269 verifyFormat("operator Vector<String>&();", Style); 23270 verifyFormat("operator const Vector<String>&();", Style); 23271 verifyFormat("operator foo::Bar*();", Style); 23272 verifyFormat("operator const Foo<X>::Bar<Y>*();", Style); 23273 verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();", 23274 Style); 23275 23276 Style.PointerAlignment = FormatStyle::PAS_Middle; 23277 verifyFormat("Foo::operator*();", Style); 23278 verifyFormat("Foo::operator void *();", Style); 23279 verifyFormat("Foo::operator()(void *);", Style); 23280 verifyFormat("Foo::operator*(void *);", Style); 23281 verifyFormat("Foo::operator*();", Style); 23282 verifyFormat("operator*(int (*)(), class Foo);", Style); 23283 23284 verifyFormat("Foo::operator&();", Style); 23285 verifyFormat("Foo::operator void &();", Style); 23286 verifyFormat("Foo::operator void const &();", Style); 23287 verifyFormat("Foo::operator()(void &);", Style); 23288 verifyFormat("Foo::operator&(void &);", Style); 23289 verifyFormat("Foo::operator&();", Style); 23290 verifyFormat("operator&(int (&)(), class Foo);", Style); 23291 23292 verifyFormat("Foo::operator&&();", Style); 23293 verifyFormat("Foo::operator void &&();", Style); 23294 verifyFormat("Foo::operator void const &&();", Style); 23295 verifyFormat("Foo::operator()(void &&);", Style); 23296 verifyFormat("Foo::operator&&(void &&);", Style); 23297 verifyFormat("Foo::operator&&();", Style); 23298 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23299 } 23300 23301 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) { 23302 FormatStyle Style = getLLVMStyle(); 23303 // PR46157 23304 verifyFormat("foo(operator+, -42);", Style); 23305 verifyFormat("foo(operator++, -42);", Style); 23306 verifyFormat("foo(operator--, -42);", Style); 23307 verifyFormat("foo(-42, operator--);", Style); 23308 verifyFormat("foo(-42, operator, );", Style); 23309 verifyFormat("foo(operator, , -42);", Style); 23310 } 23311 23312 TEST_F(FormatTest, WhitespaceSensitiveMacros) { 23313 FormatStyle Style = getLLVMStyle(); 23314 Style.WhitespaceSensitiveMacros.push_back("FOO"); 23315 23316 // Don't use the helpers here, since 'mess up' will change the whitespace 23317 // and these are all whitespace sensitive by definition 23318 EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);", 23319 format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style)); 23320 EXPECT_EQ( 23321 "FOO(String-ized&Messy+But\\(: :Still)=Intentional);", 23322 format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style)); 23323 EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);", 23324 format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style)); 23325 EXPECT_EQ("FOO(String-ized&Messy+But,: :\n" 23326 " Still=Intentional);", 23327 format("FOO(String-ized&Messy+But,: :\n" 23328 " Still=Intentional);", 23329 Style)); 23330 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 23331 EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n" 23332 " Still=Intentional);", 23333 format("FOO(String-ized=&Messy+But,: :\n" 23334 " Still=Intentional);", 23335 Style)); 23336 23337 Style.ColumnLimit = 21; 23338 EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);", 23339 format("FOO(String-ized&Messy+But: :Still=Intentional);", Style)); 23340 } 23341 23342 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) { 23343 // These tests are not in NamespaceFixer because that doesn't 23344 // test its interaction with line wrapping 23345 FormatStyle Style = getLLVMStyleWithColumns(80); 23346 verifyFormat("namespace {\n" 23347 "int i;\n" 23348 "int j;\n" 23349 "} // namespace", 23350 Style); 23351 23352 verifyFormat("namespace AAA {\n" 23353 "int i;\n" 23354 "int j;\n" 23355 "} // namespace AAA", 23356 Style); 23357 23358 EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n" 23359 "int i;\n" 23360 "int j;\n" 23361 "} // namespace Averyveryveryverylongnamespace", 23362 format("namespace Averyveryveryverylongnamespace {\n" 23363 "int i;\n" 23364 "int j;\n" 23365 "}", 23366 Style)); 23367 23368 EXPECT_EQ( 23369 "namespace " 23370 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n" 23371 " went::mad::now {\n" 23372 "int i;\n" 23373 "int j;\n" 23374 "} // namespace\n" 23375 " // " 23376 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::" 23377 "went::mad::now", 23378 format("namespace " 23379 "would::it::save::you::a::lot::of::time::if_::i::" 23380 "just::gave::up::and_::went::mad::now {\n" 23381 "int i;\n" 23382 "int j;\n" 23383 "}", 23384 Style)); 23385 23386 // This used to duplicate the comment again and again on subsequent runs 23387 EXPECT_EQ( 23388 "namespace " 23389 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n" 23390 " went::mad::now {\n" 23391 "int i;\n" 23392 "int j;\n" 23393 "} // namespace\n" 23394 " // " 23395 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::" 23396 "went::mad::now", 23397 format("namespace " 23398 "would::it::save::you::a::lot::of::time::if_::i::" 23399 "just::gave::up::and_::went::mad::now {\n" 23400 "int i;\n" 23401 "int j;\n" 23402 "} // namespace\n" 23403 " // " 23404 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::" 23405 "and_::went::mad::now", 23406 Style)); 23407 } 23408 23409 TEST_F(FormatTest, LikelyUnlikely) { 23410 FormatStyle Style = getLLVMStyle(); 23411 23412 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23413 " return 29;\n" 23414 "}", 23415 Style); 23416 23417 verifyFormat("if (argc > 5) [[likely]] {\n" 23418 " return 29;\n" 23419 "}", 23420 Style); 23421 23422 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23423 " return 29;\n" 23424 "} else [[likely]] {\n" 23425 " return 42;\n" 23426 "}\n", 23427 Style); 23428 23429 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23430 " return 29;\n" 23431 "} else if (argc > 10) [[likely]] {\n" 23432 " return 99;\n" 23433 "} else {\n" 23434 " return 42;\n" 23435 "}\n", 23436 Style); 23437 23438 verifyFormat("if (argc > 5) [[gnu::unused]] {\n" 23439 " return 29;\n" 23440 "}", 23441 Style); 23442 23443 verifyFormat("if (argc > 5) [[unlikely]]\n" 23444 " return 29;\n", 23445 Style); 23446 verifyFormat("if (argc > 5) [[likely]]\n" 23447 " return 29;\n", 23448 Style); 23449 23450 Style.AttributeMacros.push_back("UNLIKELY"); 23451 Style.AttributeMacros.push_back("LIKELY"); 23452 verifyFormat("if (argc > 5) UNLIKELY\n" 23453 " return 29;\n", 23454 Style); 23455 23456 verifyFormat("if (argc > 5) UNLIKELY {\n" 23457 " return 29;\n" 23458 "}", 23459 Style); 23460 verifyFormat("if (argc > 5) UNLIKELY {\n" 23461 " return 29;\n" 23462 "} else [[likely]] {\n" 23463 " return 42;\n" 23464 "}\n", 23465 Style); 23466 verifyFormat("if (argc > 5) UNLIKELY {\n" 23467 " return 29;\n" 23468 "} else LIKELY {\n" 23469 " return 42;\n" 23470 "}\n", 23471 Style); 23472 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23473 " return 29;\n" 23474 "} else LIKELY {\n" 23475 " return 42;\n" 23476 "}\n", 23477 Style); 23478 } 23479 23480 TEST_F(FormatTest, PenaltyIndentedWhitespace) { 23481 verifyFormat("Constructor()\n" 23482 " : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 23483 " aaaa(aaaaaaaaaaaaaaaaaa, " 23484 "aaaaaaaaaaaaaaaaaat))"); 23485 verifyFormat("Constructor()\n" 23486 " : aaaaaaaaaaaaa(aaaaaa), " 23487 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)"); 23488 23489 FormatStyle StyleWithWhitespacePenalty = getLLVMStyle(); 23490 StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5; 23491 verifyFormat("Constructor()\n" 23492 " : aaaaaa(aaaaaa),\n" 23493 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 23494 " aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))", 23495 StyleWithWhitespacePenalty); 23496 verifyFormat("Constructor()\n" 23497 " : aaaaaaaaaaaaa(aaaaaa), " 23498 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)", 23499 StyleWithWhitespacePenalty); 23500 } 23501 23502 TEST_F(FormatTest, LLVMDefaultStyle) { 23503 FormatStyle Style = getLLVMStyle(); 23504 verifyFormat("extern \"C\" {\n" 23505 "int foo();\n" 23506 "}", 23507 Style); 23508 } 23509 TEST_F(FormatTest, GNUDefaultStyle) { 23510 FormatStyle Style = getGNUStyle(); 23511 verifyFormat("extern \"C\"\n" 23512 "{\n" 23513 " int foo ();\n" 23514 "}", 23515 Style); 23516 } 23517 TEST_F(FormatTest, MozillaDefaultStyle) { 23518 FormatStyle Style = getMozillaStyle(); 23519 verifyFormat("extern \"C\"\n" 23520 "{\n" 23521 " int foo();\n" 23522 "}", 23523 Style); 23524 } 23525 TEST_F(FormatTest, GoogleDefaultStyle) { 23526 FormatStyle Style = getGoogleStyle(); 23527 verifyFormat("extern \"C\" {\n" 23528 "int foo();\n" 23529 "}", 23530 Style); 23531 } 23532 TEST_F(FormatTest, ChromiumDefaultStyle) { 23533 FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp); 23534 verifyFormat("extern \"C\" {\n" 23535 "int foo();\n" 23536 "}", 23537 Style); 23538 } 23539 TEST_F(FormatTest, MicrosoftDefaultStyle) { 23540 FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp); 23541 verifyFormat("extern \"C\"\n" 23542 "{\n" 23543 " int foo();\n" 23544 "}", 23545 Style); 23546 } 23547 TEST_F(FormatTest, WebKitDefaultStyle) { 23548 FormatStyle Style = getWebKitStyle(); 23549 verifyFormat("extern \"C\" {\n" 23550 "int foo();\n" 23551 "}", 23552 Style); 23553 } 23554 23555 TEST_F(FormatTest, Concepts) { 23556 EXPECT_EQ(getLLVMStyle().BreakBeforeConceptDeclarations, 23557 FormatStyle::BBCDS_Always); 23558 verifyFormat("template <typename T>\n" 23559 "concept True = true;"); 23560 23561 verifyFormat("template <typename T>\n" 23562 "concept C = ((false || foo()) && C2<T>) ||\n" 23563 " (std::trait<T>::value && Baz) || sizeof(T) >= 6;", 23564 getLLVMStyleWithColumns(60)); 23565 23566 verifyFormat("template <typename T>\n" 23567 "concept DelayedCheck = true && requires(T t) { t.bar(); } && " 23568 "sizeof(T) <= 8;"); 23569 23570 verifyFormat("template <typename T>\n" 23571 "concept DelayedCheck = true && requires(T t) {\n" 23572 " t.bar();\n" 23573 " t.baz();\n" 23574 " } && sizeof(T) <= 8;"); 23575 23576 verifyFormat("template <typename T>\n" 23577 "concept DelayedCheck = true && requires(T t) { // Comment\n" 23578 " t.bar();\n" 23579 " t.baz();\n" 23580 " } && sizeof(T) <= 8;"); 23581 23582 verifyFormat("template <typename T>\n" 23583 "concept DelayedCheck = false || requires(T t) { t.bar(); } && " 23584 "sizeof(T) <= 8;"); 23585 23586 verifyFormat("template <typename T>\n" 23587 "concept DelayedCheck = !!false || requires(T t) { t.bar(); } " 23588 "&& sizeof(T) <= 8;"); 23589 23590 verifyFormat( 23591 "template <typename T>\n" 23592 "concept DelayedCheck = static_cast<bool>(0) ||\n" 23593 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 23594 23595 verifyFormat("template <typename T>\n" 23596 "concept DelayedCheck = bool(0) || requires(T t) { t.bar(); } " 23597 "&& sizeof(T) <= 8;"); 23598 23599 verifyFormat( 23600 "template <typename T>\n" 23601 "concept DelayedCheck = (bool)(0) ||\n" 23602 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 23603 23604 verifyFormat("template <typename T>\n" 23605 "concept DelayedCheck = (bool)0 || requires(T t) { t.bar(); } " 23606 "&& sizeof(T) <= 8;"); 23607 23608 verifyFormat("template <typename T>\n" 23609 "concept Size = sizeof(T) >= 5 && requires(T t) { t.bar(); } && " 23610 "sizeof(T) <= 8;"); 23611 23612 verifyFormat("template <typename T>\n" 23613 "concept Size = 2 < 5 && 2 <= 5 && 8 >= 5 && 8 > 5 &&\n" 23614 " requires(T t) {\n" 23615 " t.bar();\n" 23616 " t.baz();\n" 23617 " } && sizeof(T) <= 8 && !(4 < 3);", 23618 getLLVMStyleWithColumns(60)); 23619 23620 verifyFormat("template <typename T>\n" 23621 "concept TrueOrNot = IsAlwaysTrue || IsNeverTrue;"); 23622 23623 verifyFormat("template <typename T>\n" 23624 "concept C = foo();"); 23625 23626 verifyFormat("template <typename T>\n" 23627 "concept C = foo(T());"); 23628 23629 verifyFormat("template <typename T>\n" 23630 "concept C = foo(T{});"); 23631 23632 verifyFormat("template <typename T>\n" 23633 "concept Size = V<sizeof(T)>::Value > 5;"); 23634 23635 verifyFormat("template <typename T>\n" 23636 "concept True = S<T>::Value;"); 23637 23638 verifyFormat( 23639 "template <typename T>\n" 23640 "concept C = []() { return true; }() && requires(T t) { t.bar(); } &&\n" 23641 " sizeof(T) <= 8;"); 23642 23643 // FIXME: This is misformatted because the fake l paren starts at bool, not at 23644 // the lambda l square. 23645 verifyFormat("template <typename T>\n" 23646 "concept C = [] -> bool { return true; }() && requires(T t) { " 23647 "t.bar(); } &&\n" 23648 " sizeof(T) <= 8;"); 23649 23650 verifyFormat( 23651 "template <typename T>\n" 23652 "concept C = decltype([]() { return std::true_type{}; }())::value &&\n" 23653 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 23654 23655 verifyFormat("template <typename T>\n" 23656 "concept C = decltype([]() { return std::true_type{}; " 23657 "}())::value && requires(T t) { t.bar(); } && sizeof(T) <= 8;", 23658 getLLVMStyleWithColumns(120)); 23659 23660 verifyFormat("template <typename T>\n" 23661 "concept C = decltype([]() -> std::true_type { return {}; " 23662 "}())::value &&\n" 23663 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 23664 23665 verifyFormat("template <typename T>\n" 23666 "concept C = true;\n" 23667 "Foo Bar;"); 23668 23669 verifyFormat("template <typename T>\n" 23670 "concept Hashable = requires(T a) {\n" 23671 " { std::hash<T>{}(a) } -> " 23672 "std::convertible_to<std::size_t>;\n" 23673 " };"); 23674 23675 verifyFormat( 23676 "template <typename T>\n" 23677 "concept EqualityComparable = requires(T a, T b) {\n" 23678 " { a == b } -> std::same_as<bool>;\n" 23679 " };"); 23680 23681 verifyFormat( 23682 "template <typename T>\n" 23683 "concept EqualityComparable = requires(T a, T b) {\n" 23684 " { a == b } -> std::same_as<bool>;\n" 23685 " { a != b } -> std::same_as<bool>;\n" 23686 " };"); 23687 23688 verifyFormat("template <typename T>\n" 23689 "concept WeakEqualityComparable = requires(T a, T b) {\n" 23690 " { a == b };\n" 23691 " { a != b };\n" 23692 " };"); 23693 23694 verifyFormat("template <typename T>\n" 23695 "concept HasSizeT = requires { typename T::size_t; };"); 23696 23697 verifyFormat("template <typename T>\n" 23698 "concept Semiregular =\n" 23699 " DefaultConstructible<T> && CopyConstructible<T> && " 23700 "CopyAssignable<T> &&\n" 23701 " requires(T a, std::size_t n) {\n" 23702 " requires Same<T *, decltype(&a)>;\n" 23703 " { a.~T() } noexcept;\n" 23704 " requires Same<T *, decltype(new T)>;\n" 23705 " requires Same<T *, decltype(new T[n])>;\n" 23706 " { delete new T; };\n" 23707 " { delete new T[n]; };\n" 23708 " };"); 23709 23710 verifyFormat("template <typename T>\n" 23711 "concept Semiregular =\n" 23712 " requires(T a, std::size_t n) {\n" 23713 " requires Same<T *, decltype(&a)>;\n" 23714 " { a.~T() } noexcept;\n" 23715 " requires Same<T *, decltype(new T)>;\n" 23716 " requires Same<T *, decltype(new T[n])>;\n" 23717 " { delete new T; };\n" 23718 " { delete new T[n]; };\n" 23719 " { new T } -> std::same_as<T *>;\n" 23720 " } && DefaultConstructible<T> && CopyConstructible<T> && " 23721 "CopyAssignable<T>;"); 23722 23723 verifyFormat( 23724 "template <typename T>\n" 23725 "concept Semiregular =\n" 23726 " DefaultConstructible<T> && requires(T a, std::size_t n) {\n" 23727 " requires Same<T *, decltype(&a)>;\n" 23728 " { a.~T() } noexcept;\n" 23729 " requires Same<T *, decltype(new T)>;\n" 23730 " requires Same<T *, decltype(new " 23731 "T[n])>;\n" 23732 " { delete new T; };\n" 23733 " { delete new T[n]; };\n" 23734 " } && CopyConstructible<T> && " 23735 "CopyAssignable<T>;"); 23736 23737 verifyFormat("template <typename T>\n" 23738 "concept Two = requires(T t) {\n" 23739 " { t.foo() } -> std::same_as<Bar>;\n" 23740 " } && requires(T &&t) {\n" 23741 " { t.foo() } -> std::same_as<Bar &&>;\n" 23742 " };"); 23743 23744 verifyFormat( 23745 "template <typename T>\n" 23746 "concept C = requires(T x) {\n" 23747 " { *x } -> std::convertible_to<typename T::inner>;\n" 23748 " { x + 1 } noexcept -> std::same_as<int>;\n" 23749 " { x * 1 } -> std::convertible_to<T>;\n" 23750 " };"); 23751 23752 verifyFormat( 23753 "template <typename T, typename U = T>\n" 23754 "concept Swappable = requires(T &&t, U &&u) {\n" 23755 " swap(std::forward<T>(t), std::forward<U>(u));\n" 23756 " swap(std::forward<U>(u), std::forward<T>(t));\n" 23757 " };"); 23758 23759 verifyFormat("template <typename T, typename U>\n" 23760 "concept Common = requires(T &&t, U &&u) {\n" 23761 " typename CommonType<T, U>;\n" 23762 " { CommonType<T, U>(std::forward<T>(t)) };\n" 23763 " };"); 23764 23765 verifyFormat("template <typename T, typename U>\n" 23766 "concept Common = requires(T &&t, U &&u) {\n" 23767 " typename CommonType<T, U>;\n" 23768 " { CommonType<T, U>{std::forward<T>(t)} };\n" 23769 " };"); 23770 23771 verifyFormat( 23772 "template <typename T>\n" 23773 "concept C = requires(T t) {\n" 23774 " requires Bar<T> && Foo<T>;\n" 23775 " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n" 23776 " };"); 23777 23778 verifyFormat("template <typename T>\n" 23779 "concept HasFoo = requires(T t) {\n" 23780 " { t.foo() };\n" 23781 " t.foo();\n" 23782 " };\n" 23783 "template <typename T>\n" 23784 "concept HasBar = requires(T t) {\n" 23785 " { t.bar() };\n" 23786 " t.bar();\n" 23787 " };"); 23788 23789 verifyFormat("template <typename T>\n" 23790 "concept Large = sizeof(T) > 10;"); 23791 23792 verifyFormat("template <typename T, typename U>\n" 23793 "concept FooableWith = requires(T t, U u) {\n" 23794 " typename T::foo_type;\n" 23795 " { t.foo(u) } -> typename T::foo_type;\n" 23796 " t++;\n" 23797 " };\n" 23798 "void doFoo(FooableWith<int> auto t) { t.foo(3); }"); 23799 23800 verifyFormat("template <typename T>\n" 23801 "concept Context = is_specialization_of_v<context, T>;"); 23802 23803 verifyFormat("template <typename T>\n" 23804 "concept Node = std::is_object_v<T>;"); 23805 23806 auto Style = getLLVMStyle(); 23807 Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Allowed; 23808 23809 verifyFormat( 23810 "template <typename T>\n" 23811 "concept C = requires(T t) {\n" 23812 " requires Bar<T> && Foo<T>;\n" 23813 " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n" 23814 " };", 23815 Style); 23816 23817 verifyFormat("template <typename T>\n" 23818 "concept HasFoo = requires(T t) {\n" 23819 " { t.foo() };\n" 23820 " t.foo();\n" 23821 " };\n" 23822 "template <typename T>\n" 23823 "concept HasBar = requires(T t) {\n" 23824 " { t.bar() };\n" 23825 " t.bar();\n" 23826 " };", 23827 Style); 23828 23829 verifyFormat("template <typename T> concept True = true;", Style); 23830 23831 verifyFormat("template <typename T>\n" 23832 "concept C = decltype([]() -> std::true_type { return {}; " 23833 "}())::value &&\n" 23834 " requires(T t) { t.bar(); } && sizeof(T) <= 8;", 23835 Style); 23836 23837 verifyFormat("template <typename T>\n" 23838 "concept Semiregular =\n" 23839 " DefaultConstructible<T> && CopyConstructible<T> && " 23840 "CopyAssignable<T> &&\n" 23841 " requires(T a, std::size_t n) {\n" 23842 " requires Same<T *, decltype(&a)>;\n" 23843 " { a.~T() } noexcept;\n" 23844 " requires Same<T *, decltype(new T)>;\n" 23845 " requires Same<T *, decltype(new T[n])>;\n" 23846 " { delete new T; };\n" 23847 " { delete new T[n]; };\n" 23848 " };", 23849 Style); 23850 23851 Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Never; 23852 23853 verifyFormat("template <typename T> concept C =\n" 23854 " requires(T t) {\n" 23855 " requires Bar<T> && Foo<T>;\n" 23856 " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n" 23857 " };", 23858 Style); 23859 23860 verifyFormat("template <typename T> concept HasFoo = requires(T t) {\n" 23861 " { t.foo() };\n" 23862 " t.foo();\n" 23863 " };\n" 23864 "template <typename T> concept HasBar = requires(T t) {\n" 23865 " { t.bar() };\n" 23866 " t.bar();\n" 23867 " };", 23868 Style); 23869 23870 verifyFormat("template <typename T> concept True = true;", Style); 23871 23872 verifyFormat( 23873 "template <typename T> concept C = decltype([]() -> std::true_type {\n" 23874 " return {};\n" 23875 " }())::value\n" 23876 " && requires(T t) { t.bar(); } &&\n" 23877 " sizeof(T) <= 8;", 23878 Style); 23879 23880 verifyFormat("template <typename T> concept Semiregular =\n" 23881 " DefaultConstructible<T> && CopyConstructible<T> && " 23882 "CopyAssignable<T> &&\n" 23883 " requires(T a, std::size_t n) {\n" 23884 " requires Same<T *, decltype(&a)>;\n" 23885 " { a.~T() } noexcept;\n" 23886 " requires Same<T *, decltype(new T)>;\n" 23887 " requires Same<T *, decltype(new T[n])>;\n" 23888 " { delete new T; };\n" 23889 " { delete new T[n]; };\n" 23890 " };", 23891 Style); 23892 23893 // The following tests are invalid C++, we just want to make sure we don't 23894 // assert. 23895 verifyFormat("template <typename T>\n" 23896 "concept C = requires C2<T>;"); 23897 23898 verifyFormat("template <typename T>\n" 23899 "concept C = 5 + 4;"); 23900 23901 verifyFormat("template <typename T>\n" 23902 "concept C =\n" 23903 "class X;"); 23904 23905 verifyFormat("template <typename T>\n" 23906 "concept C = [] && true;"); 23907 23908 verifyFormat("template <typename T>\n" 23909 "concept C = [] && requires(T t) { typename T::size_type; };"); 23910 } 23911 23912 TEST_F(FormatTest, RequiresClausesPositions) { 23913 auto Style = getLLVMStyle(); 23914 EXPECT_EQ(Style.RequiresClausePosition, FormatStyle::RCPS_OwnLine); 23915 EXPECT_EQ(Style.IndentRequiresClause, true); 23916 23917 verifyFormat("template <typename T>\n" 23918 " requires(Foo<T> && std::trait<T>)\n" 23919 "struct Bar;", 23920 Style); 23921 23922 verifyFormat("template <typename T>\n" 23923 " requires(Foo<T> && std::trait<T>)\n" 23924 "class Bar {\n" 23925 "public:\n" 23926 " Bar(T t);\n" 23927 " bool baz();\n" 23928 "};", 23929 Style); 23930 23931 verifyFormat( 23932 "template <typename T>\n" 23933 " requires requires(T &&t) {\n" 23934 " typename T::I;\n" 23935 " requires(F<typename T::I> && std::trait<typename T::I>);\n" 23936 " }\n" 23937 "Bar(T) -> Bar<typename T::I>;", 23938 Style); 23939 23940 verifyFormat("template <typename T>\n" 23941 " requires(Foo<T> && std::trait<T>)\n" 23942 "constexpr T MyGlobal;", 23943 Style); 23944 23945 verifyFormat("template <typename T>\n" 23946 " requires Foo<T> && requires(T t) {\n" 23947 " { t.baz() } -> std::same_as<bool>;\n" 23948 " requires std::same_as<T::Factor, int>;\n" 23949 " }\n" 23950 "inline int bar(T t) {\n" 23951 " return t.baz() ? T::Factor : 5;\n" 23952 "}", 23953 Style); 23954 23955 verifyFormat("template <typename T>\n" 23956 "inline int bar(T t)\n" 23957 " requires Foo<T> && requires(T t) {\n" 23958 " { t.baz() } -> std::same_as<bool>;\n" 23959 " requires std::same_as<T::Factor, int>;\n" 23960 " }\n" 23961 "{\n" 23962 " return t.baz() ? T::Factor : 5;\n" 23963 "}", 23964 Style); 23965 23966 verifyFormat("template <typename T>\n" 23967 " requires F<T>\n" 23968 "int bar(T t) {\n" 23969 " return 5;\n" 23970 "}", 23971 Style); 23972 23973 verifyFormat("template <typename T>\n" 23974 "int bar(T t)\n" 23975 " requires F<T>\n" 23976 "{\n" 23977 " return 5;\n" 23978 "}", 23979 Style); 23980 23981 verifyFormat("template <typename T>\n" 23982 "int bar(T t)\n" 23983 " requires F<T>;", 23984 Style); 23985 23986 Style.IndentRequiresClause = false; 23987 verifyFormat("template <typename T>\n" 23988 "requires F<T>\n" 23989 "int bar(T t) {\n" 23990 " return 5;\n" 23991 "}", 23992 Style); 23993 23994 verifyFormat("template <typename T>\n" 23995 "int bar(T t)\n" 23996 "requires F<T>\n" 23997 "{\n" 23998 " return 5;\n" 23999 "}", 24000 Style); 24001 24002 Style.RequiresClausePosition = FormatStyle::RCPS_SingleLine; 24003 verifyFormat("template <typename T> requires Foo<T> struct Bar {};\n" 24004 "template <typename T> requires Foo<T> void bar() {}\n" 24005 "template <typename T> void bar() requires Foo<T> {}\n" 24006 "template <typename T> void bar() requires Foo<T>;\n" 24007 "template <typename T> requires Foo<T> Bar(T) -> Bar<T>;", 24008 Style); 24009 24010 auto ColumnStyle = Style; 24011 ColumnStyle.ColumnLimit = 40; 24012 verifyFormat("template <typename AAAAAAA>\n" 24013 "requires Foo<T> struct Bar {};\n" 24014 "template <typename AAAAAAA>\n" 24015 "requires Foo<T> void bar() {}\n" 24016 "template <typename AAAAAAA>\n" 24017 "void bar() requires Foo<T> {}\n" 24018 "template <typename AAAAAAA>\n" 24019 "requires Foo<T> Baz(T) -> Baz<T>;", 24020 ColumnStyle); 24021 24022 verifyFormat("template <typename T>\n" 24023 "requires Foo<AAAAAAA> struct Bar {};\n" 24024 "template <typename T>\n" 24025 "requires Foo<AAAAAAA> void bar() {}\n" 24026 "template <typename T>\n" 24027 "void bar() requires Foo<AAAAAAA> {}\n" 24028 "template <typename T>\n" 24029 "requires Foo<AAAAAAA> Bar(T) -> Bar<T>;", 24030 ColumnStyle); 24031 24032 verifyFormat("template <typename AAAAAAA>\n" 24033 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24034 "struct Bar {};\n" 24035 "template <typename AAAAAAA>\n" 24036 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24037 "void bar() {}\n" 24038 "template <typename AAAAAAA>\n" 24039 "void bar()\n" 24040 " requires Foo<AAAAAAAAAAAAAAAA> {}\n" 24041 "template <typename AAAAAAA>\n" 24042 "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n" 24043 "template <typename AAAAAAA>\n" 24044 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24045 "Bar(T) -> Bar<T>;", 24046 ColumnStyle); 24047 24048 Style.RequiresClausePosition = FormatStyle::RCPS_WithFollowing; 24049 ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithFollowing; 24050 24051 verifyFormat("template <typename T>\n" 24052 "requires Foo<T> struct Bar {};\n" 24053 "template <typename T>\n" 24054 "requires Foo<T> void bar() {}\n" 24055 "template <typename T>\n" 24056 "void bar()\n" 24057 "requires Foo<T> {}\n" 24058 "template <typename T>\n" 24059 "void bar()\n" 24060 "requires Foo<T>;\n" 24061 "template <typename T>\n" 24062 "requires Foo<T> Bar(T) -> Bar<T>;", 24063 Style); 24064 24065 verifyFormat("template <typename AAAAAAA>\n" 24066 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24067 "struct Bar {};\n" 24068 "template <typename AAAAAAA>\n" 24069 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24070 "void bar() {}\n" 24071 "template <typename AAAAAAA>\n" 24072 "void bar()\n" 24073 "requires Foo<AAAAAAAAAAAAAAAA> {}\n" 24074 "template <typename AAAAAAA>\n" 24075 "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n" 24076 "template <typename AAAAAAA>\n" 24077 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24078 "Bar(T) -> Bar<T>;", 24079 ColumnStyle); 24080 24081 Style.IndentRequiresClause = true; 24082 ColumnStyle.IndentRequiresClause = true; 24083 24084 verifyFormat("template <typename T>\n" 24085 " requires Foo<T> struct Bar {};\n" 24086 "template <typename T>\n" 24087 " requires Foo<T> void bar() {}\n" 24088 "template <typename T>\n" 24089 "void bar()\n" 24090 " requires Foo<T> {}\n" 24091 "template <typename T>\n" 24092 " requires Foo<T> Bar(T) -> Bar<T>;", 24093 Style); 24094 24095 verifyFormat("template <typename AAAAAAA>\n" 24096 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24097 "struct Bar {};\n" 24098 "template <typename AAAAAAA>\n" 24099 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24100 "void bar() {}\n" 24101 "template <typename AAAAAAA>\n" 24102 "void bar()\n" 24103 " requires Foo<AAAAAAAAAAAAAAAA> {}\n" 24104 "template <typename AAAAAAA>\n" 24105 " requires Foo<AAAAAA> Bar(T) -> Bar<T>;\n" 24106 "template <typename AAAAAAA>\n" 24107 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24108 "Bar(T) -> Bar<T>;", 24109 ColumnStyle); 24110 24111 Style.RequiresClausePosition = FormatStyle::RCPS_WithPreceding; 24112 ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithPreceding; 24113 24114 verifyFormat("template <typename T> requires Foo<T>\n" 24115 "struct Bar {};\n" 24116 "template <typename T> requires Foo<T>\n" 24117 "void bar() {}\n" 24118 "template <typename T>\n" 24119 "void bar() requires Foo<T>\n" 24120 "{}\n" 24121 "template <typename T> void bar() requires Foo<T>;\n" 24122 "template <typename T> requires Foo<T>\n" 24123 "Bar(T) -> Bar<T>;", 24124 Style); 24125 24126 verifyFormat("template <typename AAAAAAA>\n" 24127 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24128 "struct Bar {};\n" 24129 "template <typename AAAAAAA>\n" 24130 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24131 "void bar() {}\n" 24132 "template <typename AAAAAAA>\n" 24133 "void bar()\n" 24134 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24135 "{}\n" 24136 "template <typename AAAAAAA>\n" 24137 "requires Foo<AAAAAAAA>\n" 24138 "Bar(T) -> Bar<T>;\n" 24139 "template <typename AAAAAAA>\n" 24140 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24141 "Bar(T) -> Bar<T>;", 24142 ColumnStyle); 24143 } 24144 24145 TEST_F(FormatTest, RequiresClauses) { 24146 verifyFormat("struct [[nodiscard]] zero_t {\n" 24147 " template <class T>\n" 24148 " requires requires { number_zero_v<T>; }\n" 24149 " [[nodiscard]] constexpr operator T() const {\n" 24150 " return number_zero_v<T>;\n" 24151 " }\n" 24152 "};"); 24153 24154 auto Style = getLLVMStyle(); 24155 24156 verifyFormat( 24157 "template <typename T>\n" 24158 " requires is_default_constructible_v<hash<T>> and\n" 24159 " is_copy_constructible_v<hash<T>> and\n" 24160 " is_move_constructible_v<hash<T>> and\n" 24161 " is_copy_assignable_v<hash<T>> and " 24162 "is_move_assignable_v<hash<T>> and\n" 24163 " is_destructible_v<hash<T>> and is_swappable_v<hash<T>> and\n" 24164 " is_callable_v<hash<T>(T)> and\n" 24165 " is_same_v<size_t, decltype(hash<T>(declval<T>()))> and\n" 24166 " is_same_v<size_t, decltype(hash<T>(declval<T &>()))> and\n" 24167 " is_same_v<size_t, decltype(hash<T>(declval<const T &>()))>\n" 24168 "struct S {};", 24169 Style); 24170 24171 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 24172 verifyFormat( 24173 "template <typename T>\n" 24174 " requires is_default_constructible_v<hash<T>>\n" 24175 " and is_copy_constructible_v<hash<T>>\n" 24176 " and is_move_constructible_v<hash<T>>\n" 24177 " and is_copy_assignable_v<hash<T>> and " 24178 "is_move_assignable_v<hash<T>>\n" 24179 " and is_destructible_v<hash<T>> and is_swappable_v<hash<T>>\n" 24180 " and is_callable_v<hash<T>(T)>\n" 24181 " and is_same_v<size_t, decltype(hash<T>(declval<T>()))>\n" 24182 " and is_same_v<size_t, decltype(hash<T>(declval<T &>()))>\n" 24183 " and is_same_v<size_t, decltype(hash<T>(declval<const T " 24184 "&>()))>\n" 24185 "struct S {};", 24186 Style); 24187 24188 // Not a clause, but we once hit an assert. 24189 verifyFormat("#if 0\n" 24190 "#else\n" 24191 "foo();\n" 24192 "#endif\n" 24193 "bar(requires);"); 24194 } 24195 24196 TEST_F(FormatTest, StatementAttributeLikeMacros) { 24197 FormatStyle Style = getLLVMStyle(); 24198 StringRef Source = "void Foo::slot() {\n" 24199 " unsigned char MyChar = 'x';\n" 24200 " emit signal(MyChar);\n" 24201 " Q_EMIT signal(MyChar);\n" 24202 "}"; 24203 24204 EXPECT_EQ(Source, format(Source, Style)); 24205 24206 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 24207 EXPECT_EQ("void Foo::slot() {\n" 24208 " unsigned char MyChar = 'x';\n" 24209 " emit signal(MyChar);\n" 24210 " Q_EMIT signal(MyChar);\n" 24211 "}", 24212 format(Source, Style)); 24213 24214 Style.StatementAttributeLikeMacros.push_back("emit"); 24215 EXPECT_EQ(Source, format(Source, Style)); 24216 24217 Style.StatementAttributeLikeMacros = {}; 24218 EXPECT_EQ("void Foo::slot() {\n" 24219 " unsigned char MyChar = 'x';\n" 24220 " emit signal(MyChar);\n" 24221 " Q_EMIT signal(MyChar);\n" 24222 "}", 24223 format(Source, Style)); 24224 } 24225 24226 TEST_F(FormatTest, IndentAccessModifiers) { 24227 FormatStyle Style = getLLVMStyle(); 24228 Style.IndentAccessModifiers = true; 24229 // Members are *two* levels below the record; 24230 // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation. 24231 verifyFormat("class C {\n" 24232 " int i;\n" 24233 "};\n", 24234 Style); 24235 verifyFormat("union C {\n" 24236 " int i;\n" 24237 " unsigned u;\n" 24238 "};\n", 24239 Style); 24240 // Access modifiers should be indented one level below the record. 24241 verifyFormat("class C {\n" 24242 " public:\n" 24243 " int i;\n" 24244 "};\n", 24245 Style); 24246 verifyFormat("struct S {\n" 24247 " private:\n" 24248 " class C {\n" 24249 " int j;\n" 24250 "\n" 24251 " public:\n" 24252 " C();\n" 24253 " };\n" 24254 "\n" 24255 " public:\n" 24256 " int i;\n" 24257 "};\n", 24258 Style); 24259 // Enumerations are not records and should be unaffected. 24260 Style.AllowShortEnumsOnASingleLine = false; 24261 verifyFormat("enum class E {\n" 24262 " A,\n" 24263 " B\n" 24264 "};\n", 24265 Style); 24266 // Test with a different indentation width; 24267 // also proves that the result is Style.AccessModifierOffset agnostic. 24268 Style.IndentWidth = 3; 24269 verifyFormat("class C {\n" 24270 " public:\n" 24271 " int i;\n" 24272 "};\n", 24273 Style); 24274 } 24275 24276 TEST_F(FormatTest, LimitlessStringsAndComments) { 24277 auto Style = getLLVMStyleWithColumns(0); 24278 constexpr StringRef Code = 24279 "/**\n" 24280 " * This is a multiline comment with quite some long lines, at least for " 24281 "the LLVM Style.\n" 24282 " * We will redo this with strings and line comments. Just to check if " 24283 "everything is working.\n" 24284 " */\n" 24285 "bool foo() {\n" 24286 " /* Single line multi line comment. */\n" 24287 " const std::string String = \"This is a multiline string with quite " 24288 "some long lines, at least for the LLVM Style.\"\n" 24289 " \"We already did it with multi line " 24290 "comments, and we will do it with line comments. Just to check if " 24291 "everything is working.\";\n" 24292 " // This is a line comment (block) with quite some long lines, at " 24293 "least for the LLVM Style.\n" 24294 " // We already did this with multi line comments and strings. Just to " 24295 "check if everything is working.\n" 24296 " const std::string SmallString = \"Hello World\";\n" 24297 " // Small line comment\n" 24298 " return String.size() > SmallString.size();\n" 24299 "}"; 24300 EXPECT_EQ(Code, format(Code, Style)); 24301 } 24302 24303 TEST_F(FormatTest, FormatDecayCopy) { 24304 // error cases from unit tests 24305 verifyFormat("foo(auto())"); 24306 verifyFormat("foo(auto{})"); 24307 verifyFormat("foo(auto({}))"); 24308 verifyFormat("foo(auto{{}})"); 24309 24310 verifyFormat("foo(auto(1))"); 24311 verifyFormat("foo(auto{1})"); 24312 verifyFormat("foo(new auto(1))"); 24313 verifyFormat("foo(new auto{1})"); 24314 verifyFormat("decltype(auto(1)) x;"); 24315 verifyFormat("decltype(auto{1}) x;"); 24316 verifyFormat("auto(x);"); 24317 verifyFormat("auto{x};"); 24318 verifyFormat("new auto{x};"); 24319 verifyFormat("auto{x} = y;"); 24320 verifyFormat("auto(x) = y;"); // actually a declaration, but this is clearly 24321 // the user's own fault 24322 verifyFormat("integral auto(x) = y;"); // actually a declaration, but this is 24323 // clearly the user's own fault 24324 verifyFormat("auto(*p)() = f;"); // actually a declaration; TODO FIXME 24325 } 24326 24327 TEST_F(FormatTest, Cpp20ModulesSupport) { 24328 FormatStyle Style = getLLVMStyle(); 24329 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 24330 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 24331 24332 verifyFormat("export import foo;", Style); 24333 verifyFormat("export import foo:bar;", Style); 24334 verifyFormat("export import foo.bar;", Style); 24335 verifyFormat("export import foo.bar:baz;", Style); 24336 verifyFormat("export import :bar;", Style); 24337 verifyFormat("export module foo:bar;", Style); 24338 verifyFormat("export module foo;", Style); 24339 verifyFormat("export module foo.bar;", Style); 24340 verifyFormat("export module foo.bar:baz;", Style); 24341 verifyFormat("export import <string_view>;", Style); 24342 24343 verifyFormat("export type_name var;", Style); 24344 verifyFormat("template <class T> export using A = B<T>;", Style); 24345 verifyFormat("export using A = B;", Style); 24346 verifyFormat("export int func() {\n" 24347 " foo();\n" 24348 "}", 24349 Style); 24350 verifyFormat("export struct {\n" 24351 " int foo;\n" 24352 "};", 24353 Style); 24354 verifyFormat("export {\n" 24355 " int foo;\n" 24356 "};", 24357 Style); 24358 verifyFormat("export export char const *hello() { return \"hello\"; }"); 24359 24360 verifyFormat("import bar;", Style); 24361 verifyFormat("import foo.bar;", Style); 24362 verifyFormat("import foo:bar;", Style); 24363 verifyFormat("import :bar;", Style); 24364 verifyFormat("import <ctime>;", Style); 24365 verifyFormat("import \"header\";", Style); 24366 24367 verifyFormat("module foo;", Style); 24368 verifyFormat("module foo:bar;", Style); 24369 verifyFormat("module foo.bar;", Style); 24370 verifyFormat("module;", Style); 24371 24372 verifyFormat("export namespace hi {\n" 24373 "const char *sayhi();\n" 24374 "}", 24375 Style); 24376 24377 verifyFormat("module :private;", Style); 24378 verifyFormat("import <foo/bar.h>;", Style); 24379 verifyFormat("import foo...bar;", Style); 24380 verifyFormat("import ..........;", Style); 24381 verifyFormat("module foo:private;", Style); 24382 verifyFormat("import a", Style); 24383 verifyFormat("module a", Style); 24384 verifyFormat("export import a", Style); 24385 verifyFormat("export module a", Style); 24386 24387 verifyFormat("import", Style); 24388 verifyFormat("module", Style); 24389 verifyFormat("export", Style); 24390 } 24391 24392 TEST_F(FormatTest, CoroutineForCoawait) { 24393 FormatStyle Style = getLLVMStyle(); 24394 verifyFormat("for co_await (auto x : range())\n ;"); 24395 verifyFormat("for (auto i : arr) {\n" 24396 "}", 24397 Style); 24398 verifyFormat("for co_await (auto i : arr) {\n" 24399 "}", 24400 Style); 24401 verifyFormat("for co_await (auto i : foo(T{})) {\n" 24402 "}", 24403 Style); 24404 } 24405 24406 TEST_F(FormatTest, CoroutineCoAwait) { 24407 verifyFormat("int x = co_await foo();"); 24408 verifyFormat("int x = (co_await foo());"); 24409 verifyFormat("co_await (42);"); 24410 verifyFormat("void operator co_await(int);"); 24411 verifyFormat("void operator co_await(a);"); 24412 verifyFormat("co_await a;"); 24413 verifyFormat("co_await missing_await_resume{};"); 24414 verifyFormat("co_await a; // comment"); 24415 verifyFormat("void test0() { co_await a; }"); 24416 verifyFormat("co_await co_await co_await foo();"); 24417 verifyFormat("co_await foo().bar();"); 24418 verifyFormat("co_await [this]() -> Task { co_return x; }"); 24419 verifyFormat("co_await [this](int a, int b) -> Task { co_return co_await " 24420 "foo(); }(x, y);"); 24421 24422 FormatStyle Style = getLLVMStyleWithColumns(40); 24423 verifyFormat("co_await [this](int a, int b) -> Task {\n" 24424 " co_return co_await foo();\n" 24425 "}(x, y);", 24426 Style); 24427 verifyFormat("co_await;"); 24428 } 24429 24430 TEST_F(FormatTest, CoroutineCoYield) { 24431 verifyFormat("int x = co_yield foo();"); 24432 verifyFormat("int x = (co_yield foo());"); 24433 verifyFormat("co_yield (42);"); 24434 verifyFormat("co_yield {42};"); 24435 verifyFormat("co_yield 42;"); 24436 verifyFormat("co_yield n++;"); 24437 verifyFormat("co_yield ++n;"); 24438 verifyFormat("co_yield;"); 24439 } 24440 24441 TEST_F(FormatTest, CoroutineCoReturn) { 24442 verifyFormat("co_return (42);"); 24443 verifyFormat("co_return;"); 24444 verifyFormat("co_return {};"); 24445 verifyFormat("co_return x;"); 24446 verifyFormat("co_return co_await foo();"); 24447 verifyFormat("co_return co_yield foo();"); 24448 } 24449 24450 TEST_F(FormatTest, EmptyShortBlock) { 24451 auto Style = getLLVMStyle(); 24452 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 24453 24454 verifyFormat("try {\n" 24455 " doA();\n" 24456 "} catch (Exception &e) {\n" 24457 " e.printStackTrace();\n" 24458 "}\n", 24459 Style); 24460 24461 verifyFormat("try {\n" 24462 " doA();\n" 24463 "} catch (Exception &e) {}\n", 24464 Style); 24465 } 24466 24467 TEST_F(FormatTest, ShortTemplatedArgumentLists) { 24468 auto Style = getLLVMStyle(); 24469 24470 verifyFormat("template <> struct S : Template<int (*)[]> {};\n", Style); 24471 verifyFormat("template <> struct S : Template<int (*)[10]> {};\n", Style); 24472 verifyFormat("struct Y : X<[] { return 0; }> {};", Style); 24473 verifyFormat("struct Y<[] { return 0; }> {};", Style); 24474 24475 verifyFormat("struct Z : X<decltype([] { return 0; }){}> {};", Style); 24476 verifyFormat("template <int N> struct Foo<char[N]> {};", Style); 24477 } 24478 24479 TEST_F(FormatTest, InsertBraces) { 24480 FormatStyle Style = getLLVMStyle(); 24481 Style.InsertBraces = true; 24482 24483 verifyFormat("// clang-format off\n" 24484 "// comment\n" 24485 "if (a) f();\n" 24486 "// clang-format on\n" 24487 "if (b) {\n" 24488 " g();\n" 24489 "}", 24490 "// clang-format off\n" 24491 "// comment\n" 24492 "if (a) f();\n" 24493 "// clang-format on\n" 24494 "if (b) g();", 24495 Style); 24496 24497 verifyFormat("if (a) {\n" 24498 " switch (b) {\n" 24499 " case 1:\n" 24500 " c = 0;\n" 24501 " break;\n" 24502 " default:\n" 24503 " c = 1;\n" 24504 " }\n" 24505 "}", 24506 "if (a)\n" 24507 " switch (b) {\n" 24508 " case 1:\n" 24509 " c = 0;\n" 24510 " break;\n" 24511 " default:\n" 24512 " c = 1;\n" 24513 " }", 24514 Style); 24515 24516 verifyFormat("for (auto node : nodes) {\n" 24517 " if (node) {\n" 24518 " break;\n" 24519 " }\n" 24520 "}", 24521 "for (auto node : nodes)\n" 24522 " if (node)\n" 24523 " break;", 24524 Style); 24525 24526 verifyFormat("for (auto node : nodes) {\n" 24527 " if (node)\n" 24528 "}", 24529 "for (auto node : nodes)\n" 24530 " if (node)", 24531 Style); 24532 24533 verifyFormat("do {\n" 24534 " --a;\n" 24535 "} while (a);", 24536 "do\n" 24537 " --a;\n" 24538 "while (a);", 24539 Style); 24540 24541 verifyFormat("if (i) {\n" 24542 " ++i;\n" 24543 "} else {\n" 24544 " --i;\n" 24545 "}", 24546 "if (i)\n" 24547 " ++i;\n" 24548 "else {\n" 24549 " --i;\n" 24550 "}", 24551 Style); 24552 24553 verifyFormat("void f() {\n" 24554 " while (j--) {\n" 24555 " while (i) {\n" 24556 " --i;\n" 24557 " }\n" 24558 " }\n" 24559 "}", 24560 "void f() {\n" 24561 " while (j--)\n" 24562 " while (i)\n" 24563 " --i;\n" 24564 "}", 24565 Style); 24566 24567 verifyFormat("f({\n" 24568 " if (a) {\n" 24569 " g();\n" 24570 " }\n" 24571 "});", 24572 "f({\n" 24573 " if (a)\n" 24574 " g();\n" 24575 "});", 24576 Style); 24577 24578 verifyFormat("if (a) {\n" 24579 " f();\n" 24580 "} else if (b) {\n" 24581 " g();\n" 24582 "} else {\n" 24583 " h();\n" 24584 "}", 24585 "if (a)\n" 24586 " f();\n" 24587 "else if (b)\n" 24588 " g();\n" 24589 "else\n" 24590 " h();", 24591 Style); 24592 24593 verifyFormat("if (a) {\n" 24594 " f();\n" 24595 "}\n" 24596 "// comment\n" 24597 "/* comment */", 24598 "if (a)\n" 24599 " f();\n" 24600 "// comment\n" 24601 "/* comment */", 24602 Style); 24603 24604 verifyFormat("if (a) {\n" 24605 " // foo\n" 24606 " // bar\n" 24607 " f();\n" 24608 "}", 24609 "if (a)\n" 24610 " // foo\n" 24611 " // bar\n" 24612 " f();", 24613 Style); 24614 24615 verifyFormat("if (a) { // comment\n" 24616 " // comment\n" 24617 " f();\n" 24618 "}", 24619 "if (a) // comment\n" 24620 " // comment\n" 24621 " f();", 24622 Style); 24623 24624 verifyFormat("if (a) {\n" 24625 " f(); // comment\n" 24626 "}", 24627 "if (a)\n" 24628 " f(); // comment", 24629 Style); 24630 24631 verifyFormat("if (a) {\n" 24632 " f();\n" 24633 "}\n" 24634 "#undef A\n" 24635 "#undef B", 24636 "if (a)\n" 24637 " f();\n" 24638 "#undef A\n" 24639 "#undef B", 24640 Style); 24641 24642 verifyFormat("if (a)\n" 24643 "#ifdef A\n" 24644 " f();\n" 24645 "#else\n" 24646 " g();\n" 24647 "#endif", 24648 Style); 24649 24650 verifyFormat("#if 0\n" 24651 "#elif 1\n" 24652 "#endif\n" 24653 "void f() {\n" 24654 " if (a) {\n" 24655 " g();\n" 24656 " }\n" 24657 "}", 24658 "#if 0\n" 24659 "#elif 1\n" 24660 "#endif\n" 24661 "void f() {\n" 24662 " if (a) g();\n" 24663 "}", 24664 Style); 24665 24666 Style.ColumnLimit = 15; 24667 24668 verifyFormat("#define A \\\n" 24669 " if (a) \\\n" 24670 " f();", 24671 Style); 24672 24673 verifyFormat("if (a + b >\n" 24674 " c) {\n" 24675 " f();\n" 24676 "}", 24677 "if (a + b > c)\n" 24678 " f();", 24679 Style); 24680 } 24681 24682 TEST_F(FormatTest, RemoveBraces) { 24683 FormatStyle Style = getLLVMStyle(); 24684 Style.RemoveBracesLLVM = true; 24685 24686 // The following eight test cases are fully-braced versions of the examples at 24687 // "llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single- 24688 // statement-bodies-of-if-else-loop-statements". 24689 24690 // 1. Omit the braces, since the body is simple and clearly associated with 24691 // the if. 24692 verifyFormat("if (isa<FunctionDecl>(D))\n" 24693 " handleFunctionDecl(D);\n" 24694 "else if (isa<VarDecl>(D))\n" 24695 " handleVarDecl(D);", 24696 "if (isa<FunctionDecl>(D)) {\n" 24697 " handleFunctionDecl(D);\n" 24698 "} else if (isa<VarDecl>(D)) {\n" 24699 " handleVarDecl(D);\n" 24700 "}", 24701 Style); 24702 24703 // 2. Here we document the condition itself and not the body. 24704 verifyFormat("if (isa<VarDecl>(D)) {\n" 24705 " // It is necessary that we explain the situation with this\n" 24706 " // surprisingly long comment, so it would be unclear\n" 24707 " // without the braces whether the following statement is in\n" 24708 " // the scope of the `if`.\n" 24709 " // Because the condition is documented, we can't really\n" 24710 " // hoist this comment that applies to the body above the\n" 24711 " // if.\n" 24712 " handleOtherDecl(D);\n" 24713 "}", 24714 Style); 24715 24716 // 3. Use braces on the outer `if` to avoid a potential dangling else 24717 // situation. 24718 verifyFormat("if (isa<VarDecl>(D)) {\n" 24719 " for (auto *A : D.attrs())\n" 24720 " if (shouldProcessAttr(A))\n" 24721 " handleAttr(A);\n" 24722 "}", 24723 "if (isa<VarDecl>(D)) {\n" 24724 " for (auto *A : D.attrs()) {\n" 24725 " if (shouldProcessAttr(A)) {\n" 24726 " handleAttr(A);\n" 24727 " }\n" 24728 " }\n" 24729 "}", 24730 Style); 24731 24732 // 4. Use braces for the `if` block to keep it uniform with the else block. 24733 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 24734 " handleFunctionDecl(D);\n" 24735 "} else {\n" 24736 " // In this else case, it is necessary that we explain the\n" 24737 " // situation with this surprisingly long comment, so it\n" 24738 " // would be unclear without the braces whether the\n" 24739 " // following statement is in the scope of the `if`.\n" 24740 " handleOtherDecl(D);\n" 24741 "}", 24742 Style); 24743 24744 // 5. This should also omit braces. The `for` loop contains only a single 24745 // statement, so it shouldn't have braces. The `if` also only contains a 24746 // single simple statement (the for loop), so it also should omit braces. 24747 verifyFormat("if (isa<FunctionDecl>(D))\n" 24748 " for (auto *A : D.attrs())\n" 24749 " handleAttr(A);", 24750 "if (isa<FunctionDecl>(D)) {\n" 24751 " for (auto *A : D.attrs()) {\n" 24752 " handleAttr(A);\n" 24753 " }\n" 24754 "}", 24755 Style); 24756 24757 // 6. Use braces for the outer `if` since the nested `for` is braced. 24758 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 24759 " for (auto *A : D.attrs()) {\n" 24760 " // In this for loop body, it is necessary that we explain\n" 24761 " // the situation with this surprisingly long comment,\n" 24762 " // forcing braces on the `for` block.\n" 24763 " handleAttr(A);\n" 24764 " }\n" 24765 "}", 24766 Style); 24767 24768 // 7. Use braces on the outer block because there are more than two levels of 24769 // nesting. 24770 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 24771 " for (auto *A : D.attrs())\n" 24772 " for (ssize_t i : llvm::seq<ssize_t>(count))\n" 24773 " handleAttrOnDecl(D, A, i);\n" 24774 "}", 24775 "if (isa<FunctionDecl>(D)) {\n" 24776 " for (auto *A : D.attrs()) {\n" 24777 " for (ssize_t i : llvm::seq<ssize_t>(count)) {\n" 24778 " handleAttrOnDecl(D, A, i);\n" 24779 " }\n" 24780 " }\n" 24781 "}", 24782 Style); 24783 24784 // 8. Use braces on the outer block because of a nested `if`, otherwise the 24785 // compiler would warn: `add explicit braces to avoid dangling else` 24786 verifyFormat("if (auto *D = dyn_cast<FunctionDecl>(D)) {\n" 24787 " if (shouldProcess(D))\n" 24788 " handleVarDecl(D);\n" 24789 " else\n" 24790 " markAsIgnored(D);\n" 24791 "}", 24792 "if (auto *D = dyn_cast<FunctionDecl>(D)) {\n" 24793 " if (shouldProcess(D)) {\n" 24794 " handleVarDecl(D);\n" 24795 " } else {\n" 24796 " markAsIgnored(D);\n" 24797 " }\n" 24798 "}", 24799 Style); 24800 24801 verifyFormat("if (a)\n" 24802 " b; // comment\n" 24803 "else if (c)\n" 24804 " d; /* comment */\n" 24805 "else\n" 24806 " e;", 24807 "if (a) {\n" 24808 " b; // comment\n" 24809 "} else if (c) {\n" 24810 " d; /* comment */\n" 24811 "} else {\n" 24812 " e;\n" 24813 "}", 24814 Style); 24815 24816 verifyFormat("if (a) {\n" 24817 " b;\n" 24818 " c;\n" 24819 "} else if (d) {\n" 24820 " e;\n" 24821 "}", 24822 Style); 24823 24824 verifyFormat("if (a) {\n" 24825 "#undef NDEBUG\n" 24826 " b;\n" 24827 "} else {\n" 24828 " c;\n" 24829 "}", 24830 Style); 24831 24832 verifyFormat("if (a) {\n" 24833 " // comment\n" 24834 "} else if (b) {\n" 24835 " c;\n" 24836 "}", 24837 Style); 24838 24839 verifyFormat("if (a) {\n" 24840 " b;\n" 24841 "} else {\n" 24842 " { c; }\n" 24843 "}", 24844 Style); 24845 24846 verifyFormat("if (a) {\n" 24847 " if (b) // comment\n" 24848 " c;\n" 24849 "} else if (d) {\n" 24850 " e;\n" 24851 "}", 24852 "if (a) {\n" 24853 " if (b) { // comment\n" 24854 " c;\n" 24855 " }\n" 24856 "} else if (d) {\n" 24857 " e;\n" 24858 "}", 24859 Style); 24860 24861 verifyFormat("if (a) {\n" 24862 " if (b) {\n" 24863 " c;\n" 24864 " // comment\n" 24865 " } else if (d) {\n" 24866 " e;\n" 24867 " }\n" 24868 "}", 24869 Style); 24870 24871 verifyFormat("if (a) {\n" 24872 " if (b)\n" 24873 " c;\n" 24874 "}", 24875 "if (a) {\n" 24876 " if (b) {\n" 24877 " c;\n" 24878 " }\n" 24879 "}", 24880 Style); 24881 24882 verifyFormat("if (a)\n" 24883 " if (b)\n" 24884 " c;\n" 24885 " else\n" 24886 " d;\n" 24887 "else\n" 24888 " e;", 24889 "if (a) {\n" 24890 " if (b) {\n" 24891 " c;\n" 24892 " } else {\n" 24893 " d;\n" 24894 " }\n" 24895 "} else {\n" 24896 " e;\n" 24897 "}", 24898 Style); 24899 24900 verifyFormat("if (a) {\n" 24901 " // comment\n" 24902 " if (b)\n" 24903 " c;\n" 24904 " else if (d)\n" 24905 " e;\n" 24906 "} else {\n" 24907 " g;\n" 24908 "}", 24909 "if (a) {\n" 24910 " // comment\n" 24911 " if (b) {\n" 24912 " c;\n" 24913 " } else if (d) {\n" 24914 " e;\n" 24915 " }\n" 24916 "} else {\n" 24917 " g;\n" 24918 "}", 24919 Style); 24920 24921 verifyFormat("if (a)\n" 24922 " b;\n" 24923 "else if (c)\n" 24924 " d;\n" 24925 "else\n" 24926 " e;", 24927 "if (a) {\n" 24928 " b;\n" 24929 "} else {\n" 24930 " if (c) {\n" 24931 " d;\n" 24932 " } else {\n" 24933 " e;\n" 24934 " }\n" 24935 "}", 24936 Style); 24937 24938 verifyFormat("if (a) {\n" 24939 " if (b)\n" 24940 " c;\n" 24941 " else if (d)\n" 24942 " e;\n" 24943 "} else {\n" 24944 " g;\n" 24945 "}", 24946 "if (a) {\n" 24947 " if (b)\n" 24948 " c;\n" 24949 " else {\n" 24950 " if (d)\n" 24951 " e;\n" 24952 " }\n" 24953 "} else {\n" 24954 " g;\n" 24955 "}", 24956 Style); 24957 24958 verifyFormat("if (a)\n" 24959 " b;\n" 24960 "else if (c)\n" 24961 " while (d)\n" 24962 " e;\n" 24963 "// comment", 24964 "if (a)\n" 24965 "{\n" 24966 " b;\n" 24967 "} else if (c) {\n" 24968 " while (d) {\n" 24969 " e;\n" 24970 " }\n" 24971 "}\n" 24972 "// comment", 24973 Style); 24974 24975 verifyFormat("if (a) {\n" 24976 " b;\n" 24977 "} else if (c) {\n" 24978 " d;\n" 24979 "} else {\n" 24980 " e;\n" 24981 " g;\n" 24982 "}", 24983 Style); 24984 24985 verifyFormat("if (a) {\n" 24986 " b;\n" 24987 "} else if (c) {\n" 24988 " d;\n" 24989 "} else {\n" 24990 " e;\n" 24991 "} // comment", 24992 Style); 24993 24994 verifyFormat("int abs = [](int i) {\n" 24995 " if (i >= 0)\n" 24996 " return i;\n" 24997 " return -i;\n" 24998 "};", 24999 "int abs = [](int i) {\n" 25000 " if (i >= 0) {\n" 25001 " return i;\n" 25002 " }\n" 25003 " return -i;\n" 25004 "};", 25005 Style); 25006 25007 verifyFormat("if (a)\n" 25008 " foo();\n" 25009 "else\n" 25010 " bar();", 25011 "if (a)\n" 25012 "{\n" 25013 " foo();\n" 25014 "}\n" 25015 "else\n" 25016 "{\n" 25017 " bar();\n" 25018 "}", 25019 Style); 25020 25021 // FIXME: See https://github.com/llvm/llvm-project/issues/53543. 25022 #if 0 25023 Style.ColumnLimit = 65; 25024 25025 verifyFormat("if (condition) {\n" 25026 " ff(Indices,\n" 25027 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 25028 "} else {\n" 25029 " ff(Indices,\n" 25030 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 25031 "}", 25032 Style); 25033 25034 Style.ColumnLimit = 20; 25035 25036 verifyFormat("if (a) {\n" 25037 " b = c + // 1 -\n" 25038 " d;\n" 25039 "}", 25040 Style); 25041 25042 verifyFormat("if (a) {\n" 25043 " b = c >= 0 ? d\n" 25044 " : e;\n" 25045 "}", 25046 "if (a) {\n" 25047 " b = c >= 0 ? d : e;\n" 25048 "}", 25049 Style); 25050 #endif 25051 25052 Style.ColumnLimit = 20; 25053 25054 verifyFormat("if (a)\n" 25055 " b = c > 0 ? d : e;", 25056 "if (a) {\n" 25057 " b = c > 0 ? d : e;\n" 25058 "}", 25059 Style); 25060 25061 Style.ColumnLimit = 0; 25062 25063 verifyFormat("if (a)\n" 25064 " b234567890223456789032345678904234567890 = " 25065 "c234567890223456789032345678904234567890;", 25066 "if (a) {\n" 25067 " b234567890223456789032345678904234567890 = " 25068 "c234567890223456789032345678904234567890;\n" 25069 "}", 25070 Style); 25071 } 25072 25073 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndent) { 25074 auto Style = getLLVMStyle(); 25075 25076 StringRef Short = "functionCall(paramA, paramB, paramC);\n" 25077 "void functionDecl(int a, int b, int c);"; 25078 25079 StringRef Medium = "functionCall(paramA, paramB, paramC, paramD, paramE, " 25080 "paramF, paramG, paramH, paramI);\n" 25081 "void functionDecl(int argumentA, int argumentB, int " 25082 "argumentC, int argumentD, int argumentE);"; 25083 25084 verifyFormat(Short, Style); 25085 25086 StringRef NoBreak = "functionCall(paramA, paramB, paramC, paramD, paramE, " 25087 "paramF, paramG, paramH,\n" 25088 " paramI);\n" 25089 "void functionDecl(int argumentA, int argumentB, int " 25090 "argumentC, int argumentD,\n" 25091 " int argumentE);"; 25092 25093 verifyFormat(NoBreak, Medium, Style); 25094 verifyFormat(NoBreak, 25095 "functionCall(\n" 25096 " paramA,\n" 25097 " paramB,\n" 25098 " paramC,\n" 25099 " paramD,\n" 25100 " paramE,\n" 25101 " paramF,\n" 25102 " paramG,\n" 25103 " paramH,\n" 25104 " paramI\n" 25105 ");\n" 25106 "void functionDecl(\n" 25107 " int argumentA,\n" 25108 " int argumentB,\n" 25109 " int argumentC,\n" 25110 " int argumentD,\n" 25111 " int argumentE\n" 25112 ");", 25113 Style); 25114 25115 verifyFormat("outerFunctionCall(nestedFunctionCall(argument1),\n" 25116 " nestedLongFunctionCall(argument1, " 25117 "argument2, argument3,\n" 25118 " argument4, " 25119 "argument5));", 25120 Style); 25121 25122 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 25123 25124 verifyFormat(Short, Style); 25125 verifyFormat( 25126 "functionCall(\n" 25127 " paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, " 25128 "paramI\n" 25129 ");\n" 25130 "void functionDecl(\n" 25131 " int argumentA, int argumentB, int argumentC, int argumentD, int " 25132 "argumentE\n" 25133 ");", 25134 Medium, Style); 25135 25136 Style.AllowAllArgumentsOnNextLine = false; 25137 Style.AllowAllParametersOfDeclarationOnNextLine = false; 25138 25139 verifyFormat(Short, Style); 25140 verifyFormat( 25141 "functionCall(\n" 25142 " paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, " 25143 "paramI\n" 25144 ");\n" 25145 "void functionDecl(\n" 25146 " int argumentA, int argumentB, int argumentC, int argumentD, int " 25147 "argumentE\n" 25148 ");", 25149 Medium, Style); 25150 25151 Style.BinPackArguments = false; 25152 Style.BinPackParameters = false; 25153 25154 verifyFormat(Short, Style); 25155 25156 verifyFormat("functionCall(\n" 25157 " paramA,\n" 25158 " paramB,\n" 25159 " paramC,\n" 25160 " paramD,\n" 25161 " paramE,\n" 25162 " paramF,\n" 25163 " paramG,\n" 25164 " paramH,\n" 25165 " paramI\n" 25166 ");\n" 25167 "void functionDecl(\n" 25168 " int argumentA,\n" 25169 " int argumentB,\n" 25170 " int argumentC,\n" 25171 " int argumentD,\n" 25172 " int argumentE\n" 25173 ");", 25174 Medium, Style); 25175 25176 verifyFormat("outerFunctionCall(\n" 25177 " nestedFunctionCall(argument1),\n" 25178 " nestedLongFunctionCall(\n" 25179 " argument1,\n" 25180 " argument2,\n" 25181 " argument3,\n" 25182 " argument4,\n" 25183 " argument5\n" 25184 " )\n" 25185 ");", 25186 Style); 25187 25188 verifyFormat("int a = (int)b;", Style); 25189 verifyFormat("int a = (int)b;", 25190 "int a = (\n" 25191 " int\n" 25192 ") b;", 25193 Style); 25194 25195 verifyFormat("return (true);", Style); 25196 verifyFormat("return (true);", 25197 "return (\n" 25198 " true\n" 25199 ");", 25200 Style); 25201 25202 verifyFormat("void foo();", Style); 25203 verifyFormat("void foo();", 25204 "void foo(\n" 25205 ");", 25206 Style); 25207 25208 verifyFormat("void foo() {}", Style); 25209 verifyFormat("void foo() {}", 25210 "void foo(\n" 25211 ") {\n" 25212 "}", 25213 Style); 25214 25215 verifyFormat("auto string = std::string();", Style); 25216 verifyFormat("auto string = std::string();", 25217 "auto string = std::string(\n" 25218 ");", 25219 Style); 25220 25221 verifyFormat("void (*functionPointer)() = nullptr;", Style); 25222 verifyFormat("void (*functionPointer)() = nullptr;", 25223 "void (\n" 25224 " *functionPointer\n" 25225 ")\n" 25226 "(\n" 25227 ") = nullptr;", 25228 Style); 25229 } 25230 25231 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentIfStatement) { 25232 auto Style = getLLVMStyle(); 25233 25234 verifyFormat("if (foo()) {\n" 25235 " return;\n" 25236 "}", 25237 Style); 25238 25239 verifyFormat("if (quitelongarg !=\n" 25240 " (alsolongarg - 1)) { // ABC is a very longgggggggggggg " 25241 "comment\n" 25242 " return;\n" 25243 "}", 25244 Style); 25245 25246 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 25247 25248 verifyFormat("if (foo()) {\n" 25249 " return;\n" 25250 "}", 25251 Style); 25252 25253 verifyFormat("if (quitelongarg !=\n" 25254 " (alsolongarg - 1)) { // ABC is a very longgggggggggggg " 25255 "comment\n" 25256 " return;\n" 25257 "}", 25258 Style); 25259 } 25260 25261 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentForStatement) { 25262 auto Style = getLLVMStyle(); 25263 25264 verifyFormat("for (int i = 0; i < 5; ++i) {\n" 25265 " doSomething();\n" 25266 "}", 25267 Style); 25268 25269 verifyFormat("for (int myReallyLongCountVariable = 0; " 25270 "myReallyLongCountVariable < count;\n" 25271 " myReallyLongCountVariable++) {\n" 25272 " doSomething();\n" 25273 "}", 25274 Style); 25275 25276 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 25277 25278 verifyFormat("for (int i = 0; i < 5; ++i) {\n" 25279 " doSomething();\n" 25280 "}", 25281 Style); 25282 25283 verifyFormat("for (int myReallyLongCountVariable = 0; " 25284 "myReallyLongCountVariable < count;\n" 25285 " myReallyLongCountVariable++) {\n" 25286 " doSomething();\n" 25287 "}", 25288 Style); 25289 } 25290 25291 TEST_F(FormatTest, UnderstandsDigraphs) { 25292 verifyFormat("int arr<:5:> = {};"); 25293 verifyFormat("int arr[5] = <%%>;"); 25294 verifyFormat("int arr<:::qualified_variable:> = {};"); 25295 verifyFormat("int arr[::qualified_variable] = <%%>;"); 25296 verifyFormat("%:include <header>"); 25297 verifyFormat("%:define A x##y"); 25298 verifyFormat("#define A x%:%:y"); 25299 } 25300 25301 } // namespace 25302 } // namespace format 25303 } // namespace clang 25304