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 // https://llvm.org/PR54147 12673 verifyFormat("auto lambda = []() {\n" 12674 " // comment\n" 12675 " f();\n" 12676 " g();\n" 12677 "};", 12678 MergeInlineOnly); 12679 12680 // Also verify behavior when BraceWrapping.AfterFunction = true 12681 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12682 MergeInlineOnly.BraceWrapping.AfterFunction = true; 12683 verifyFormat("class C {\n" 12684 " int f() { return 42; }\n" 12685 "};", 12686 MergeInlineOnly); 12687 verifyFormat("int f()\n" 12688 "{\n" 12689 " return 42;\n" 12690 "}", 12691 MergeInlineOnly); 12692 12693 // SFS_Inline implies SFS_Empty 12694 verifyFormat("int f() {}", MergeInlineOnly); 12695 verifyFormat("class C {\n" 12696 " int f() {}\n" 12697 "};", 12698 MergeInlineOnly); 12699 12700 MergeInlineOnly.BraceWrapping.AfterClass = true; 12701 MergeInlineOnly.BraceWrapping.AfterStruct = true; 12702 verifyFormat("class C\n" 12703 "{\n" 12704 " int f() { return 42; }\n" 12705 "};", 12706 MergeInlineOnly); 12707 verifyFormat("struct C\n" 12708 "{\n" 12709 " int f() { return 42; }\n" 12710 "};", 12711 MergeInlineOnly); 12712 verifyFormat("int f()\n" 12713 "{\n" 12714 " return 42;\n" 12715 "}", 12716 MergeInlineOnly); 12717 verifyFormat("int f() {}", MergeInlineOnly); 12718 verifyFormat("class C\n" 12719 "{\n" 12720 " int f() { return 42; }\n" 12721 "};", 12722 MergeInlineOnly); 12723 verifyFormat("struct C\n" 12724 "{\n" 12725 " int f() { return 42; }\n" 12726 "};", 12727 MergeInlineOnly); 12728 verifyFormat("struct C\n" 12729 "// comment\n" 12730 "/* comment */\n" 12731 "// comment\n" 12732 "{\n" 12733 " int f() { return 42; }\n" 12734 "};", 12735 MergeInlineOnly); 12736 verifyFormat("/* comment */ struct C\n" 12737 "{\n" 12738 " int f() { return 42; }\n" 12739 "};", 12740 MergeInlineOnly); 12741 } 12742 12743 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) { 12744 FormatStyle MergeInlineOnly = getLLVMStyle(); 12745 MergeInlineOnly.AllowShortFunctionsOnASingleLine = 12746 FormatStyle::SFS_InlineOnly; 12747 verifyFormat("class C {\n" 12748 " int f() { return 42; }\n" 12749 "};", 12750 MergeInlineOnly); 12751 verifyFormat("int f() {\n" 12752 " return 42;\n" 12753 "}", 12754 MergeInlineOnly); 12755 12756 // SFS_InlineOnly does not imply SFS_Empty 12757 verifyFormat("class C {\n" 12758 " int f() {}\n" 12759 "};", 12760 MergeInlineOnly); 12761 verifyFormat("int f() {\n" 12762 "}", 12763 MergeInlineOnly); 12764 12765 // Also verify behavior when BraceWrapping.AfterFunction = true 12766 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12767 MergeInlineOnly.BraceWrapping.AfterFunction = true; 12768 verifyFormat("class C {\n" 12769 " int f() { return 42; }\n" 12770 "};", 12771 MergeInlineOnly); 12772 verifyFormat("int f()\n" 12773 "{\n" 12774 " return 42;\n" 12775 "}", 12776 MergeInlineOnly); 12777 12778 // SFS_InlineOnly does not imply SFS_Empty 12779 verifyFormat("int f()\n" 12780 "{\n" 12781 "}", 12782 MergeInlineOnly); 12783 verifyFormat("class C {\n" 12784 " int f() {}\n" 12785 "};", 12786 MergeInlineOnly); 12787 } 12788 12789 TEST_F(FormatTest, SplitEmptyFunction) { 12790 FormatStyle Style = getLLVMStyleWithColumns(40); 12791 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12792 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12793 Style.BraceWrapping.AfterFunction = true; 12794 Style.BraceWrapping.SplitEmptyFunction = false; 12795 12796 verifyFormat("int f()\n" 12797 "{}", 12798 Style); 12799 verifyFormat("int f()\n" 12800 "{\n" 12801 " return 42;\n" 12802 "}", 12803 Style); 12804 verifyFormat("int f()\n" 12805 "{\n" 12806 " // some comment\n" 12807 "}", 12808 Style); 12809 12810 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 12811 verifyFormat("int f() {}", Style); 12812 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12813 "{}", 12814 Style); 12815 verifyFormat("int f()\n" 12816 "{\n" 12817 " return 0;\n" 12818 "}", 12819 Style); 12820 12821 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 12822 verifyFormat("class Foo {\n" 12823 " int f() {}\n" 12824 "};\n", 12825 Style); 12826 verifyFormat("class Foo {\n" 12827 " int f() { return 0; }\n" 12828 "};\n", 12829 Style); 12830 verifyFormat("class Foo {\n" 12831 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12832 " {}\n" 12833 "};\n", 12834 Style); 12835 verifyFormat("class Foo {\n" 12836 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12837 " {\n" 12838 " return 0;\n" 12839 " }\n" 12840 "};\n", 12841 Style); 12842 12843 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 12844 verifyFormat("int f() {}", Style); 12845 verifyFormat("int f() { return 0; }", Style); 12846 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12847 "{}", 12848 Style); 12849 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12850 "{\n" 12851 " return 0;\n" 12852 "}", 12853 Style); 12854 } 12855 12856 TEST_F(FormatTest, SplitEmptyFunctionButNotRecord) { 12857 FormatStyle Style = getLLVMStyleWithColumns(40); 12858 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12859 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12860 Style.BraceWrapping.AfterFunction = true; 12861 Style.BraceWrapping.SplitEmptyFunction = true; 12862 Style.BraceWrapping.SplitEmptyRecord = false; 12863 12864 verifyFormat("class C {};", Style); 12865 verifyFormat("struct C {};", Style); 12866 verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12867 " int bbbbbbbbbbbbbbbbbbbbbbbb)\n" 12868 "{\n" 12869 "}", 12870 Style); 12871 verifyFormat("class C {\n" 12872 " C()\n" 12873 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa(),\n" 12874 " bbbbbbbbbbbbbbbbbbb()\n" 12875 " {\n" 12876 " }\n" 12877 " void\n" 12878 " m(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12879 " int bbbbbbbbbbbbbbbbbbbbbbbb)\n" 12880 " {\n" 12881 " }\n" 12882 "};", 12883 Style); 12884 } 12885 12886 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) { 12887 FormatStyle Style = getLLVMStyle(); 12888 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 12889 verifyFormat("#ifdef A\n" 12890 "int f() {}\n" 12891 "#else\n" 12892 "int g() {}\n" 12893 "#endif", 12894 Style); 12895 } 12896 12897 TEST_F(FormatTest, SplitEmptyClass) { 12898 FormatStyle Style = getLLVMStyle(); 12899 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12900 Style.BraceWrapping.AfterClass = true; 12901 Style.BraceWrapping.SplitEmptyRecord = false; 12902 12903 verifyFormat("class Foo\n" 12904 "{};", 12905 Style); 12906 verifyFormat("/* something */ class Foo\n" 12907 "{};", 12908 Style); 12909 verifyFormat("template <typename X> class Foo\n" 12910 "{};", 12911 Style); 12912 verifyFormat("class Foo\n" 12913 "{\n" 12914 " Foo();\n" 12915 "};", 12916 Style); 12917 verifyFormat("typedef class Foo\n" 12918 "{\n" 12919 "} Foo_t;", 12920 Style); 12921 12922 Style.BraceWrapping.SplitEmptyRecord = true; 12923 Style.BraceWrapping.AfterStruct = true; 12924 verifyFormat("class rep\n" 12925 "{\n" 12926 "};", 12927 Style); 12928 verifyFormat("struct rep\n" 12929 "{\n" 12930 "};", 12931 Style); 12932 verifyFormat("template <typename T> class rep\n" 12933 "{\n" 12934 "};", 12935 Style); 12936 verifyFormat("template <typename T> struct rep\n" 12937 "{\n" 12938 "};", 12939 Style); 12940 verifyFormat("class rep\n" 12941 "{\n" 12942 " int x;\n" 12943 "};", 12944 Style); 12945 verifyFormat("struct rep\n" 12946 "{\n" 12947 " int x;\n" 12948 "};", 12949 Style); 12950 verifyFormat("template <typename T> class rep\n" 12951 "{\n" 12952 " int x;\n" 12953 "};", 12954 Style); 12955 verifyFormat("template <typename T> struct rep\n" 12956 "{\n" 12957 " int x;\n" 12958 "};", 12959 Style); 12960 verifyFormat("template <typename T> class rep // Foo\n" 12961 "{\n" 12962 " int x;\n" 12963 "};", 12964 Style); 12965 verifyFormat("template <typename T> struct rep // Bar\n" 12966 "{\n" 12967 " int x;\n" 12968 "};", 12969 Style); 12970 12971 verifyFormat("template <typename T> class rep<T>\n" 12972 "{\n" 12973 " int x;\n" 12974 "};", 12975 Style); 12976 12977 verifyFormat("template <typename T> class rep<std::complex<T>>\n" 12978 "{\n" 12979 " int x;\n" 12980 "};", 12981 Style); 12982 verifyFormat("template <typename T> class rep<std::complex<T>>\n" 12983 "{\n" 12984 "};", 12985 Style); 12986 12987 verifyFormat("#include \"stdint.h\"\n" 12988 "namespace rep {}", 12989 Style); 12990 verifyFormat("#include <stdint.h>\n" 12991 "namespace rep {}", 12992 Style); 12993 verifyFormat("#include <stdint.h>\n" 12994 "namespace rep {}", 12995 "#include <stdint.h>\n" 12996 "namespace rep {\n" 12997 "\n" 12998 "\n" 12999 "}", 13000 Style); 13001 } 13002 13003 TEST_F(FormatTest, SplitEmptyStruct) { 13004 FormatStyle Style = getLLVMStyle(); 13005 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13006 Style.BraceWrapping.AfterStruct = true; 13007 Style.BraceWrapping.SplitEmptyRecord = false; 13008 13009 verifyFormat("struct Foo\n" 13010 "{};", 13011 Style); 13012 verifyFormat("/* something */ struct Foo\n" 13013 "{};", 13014 Style); 13015 verifyFormat("template <typename X> struct Foo\n" 13016 "{};", 13017 Style); 13018 verifyFormat("struct Foo\n" 13019 "{\n" 13020 " Foo();\n" 13021 "};", 13022 Style); 13023 verifyFormat("typedef struct Foo\n" 13024 "{\n" 13025 "} Foo_t;", 13026 Style); 13027 // typedef struct Bar {} Bar_t; 13028 } 13029 13030 TEST_F(FormatTest, SplitEmptyUnion) { 13031 FormatStyle Style = getLLVMStyle(); 13032 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13033 Style.BraceWrapping.AfterUnion = true; 13034 Style.BraceWrapping.SplitEmptyRecord = false; 13035 13036 verifyFormat("union Foo\n" 13037 "{};", 13038 Style); 13039 verifyFormat("/* something */ union Foo\n" 13040 "{};", 13041 Style); 13042 verifyFormat("union Foo\n" 13043 "{\n" 13044 " A,\n" 13045 "};", 13046 Style); 13047 verifyFormat("typedef union Foo\n" 13048 "{\n" 13049 "} Foo_t;", 13050 Style); 13051 } 13052 13053 TEST_F(FormatTest, SplitEmptyNamespace) { 13054 FormatStyle Style = getLLVMStyle(); 13055 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13056 Style.BraceWrapping.AfterNamespace = true; 13057 Style.BraceWrapping.SplitEmptyNamespace = false; 13058 13059 verifyFormat("namespace Foo\n" 13060 "{};", 13061 Style); 13062 verifyFormat("/* something */ namespace Foo\n" 13063 "{};", 13064 Style); 13065 verifyFormat("inline namespace Foo\n" 13066 "{};", 13067 Style); 13068 verifyFormat("/* something */ inline namespace Foo\n" 13069 "{};", 13070 Style); 13071 verifyFormat("export namespace Foo\n" 13072 "{};", 13073 Style); 13074 verifyFormat("namespace Foo\n" 13075 "{\n" 13076 "void Bar();\n" 13077 "};", 13078 Style); 13079 } 13080 13081 TEST_F(FormatTest, NeverMergeShortRecords) { 13082 FormatStyle Style = getLLVMStyle(); 13083 13084 verifyFormat("class Foo {\n" 13085 " Foo();\n" 13086 "};", 13087 Style); 13088 verifyFormat("typedef class Foo {\n" 13089 " Foo();\n" 13090 "} Foo_t;", 13091 Style); 13092 verifyFormat("struct Foo {\n" 13093 " Foo();\n" 13094 "};", 13095 Style); 13096 verifyFormat("typedef struct Foo {\n" 13097 " Foo();\n" 13098 "} Foo_t;", 13099 Style); 13100 verifyFormat("union Foo {\n" 13101 " A,\n" 13102 "};", 13103 Style); 13104 verifyFormat("typedef union Foo {\n" 13105 " A,\n" 13106 "} Foo_t;", 13107 Style); 13108 verifyFormat("namespace Foo {\n" 13109 "void Bar();\n" 13110 "};", 13111 Style); 13112 13113 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13114 Style.BraceWrapping.AfterClass = true; 13115 Style.BraceWrapping.AfterStruct = true; 13116 Style.BraceWrapping.AfterUnion = true; 13117 Style.BraceWrapping.AfterNamespace = true; 13118 verifyFormat("class Foo\n" 13119 "{\n" 13120 " Foo();\n" 13121 "};", 13122 Style); 13123 verifyFormat("typedef class Foo\n" 13124 "{\n" 13125 " Foo();\n" 13126 "} Foo_t;", 13127 Style); 13128 verifyFormat("struct Foo\n" 13129 "{\n" 13130 " Foo();\n" 13131 "};", 13132 Style); 13133 verifyFormat("typedef struct Foo\n" 13134 "{\n" 13135 " Foo();\n" 13136 "} Foo_t;", 13137 Style); 13138 verifyFormat("union Foo\n" 13139 "{\n" 13140 " A,\n" 13141 "};", 13142 Style); 13143 verifyFormat("typedef union Foo\n" 13144 "{\n" 13145 " A,\n" 13146 "} Foo_t;", 13147 Style); 13148 verifyFormat("namespace Foo\n" 13149 "{\n" 13150 "void Bar();\n" 13151 "};", 13152 Style); 13153 } 13154 13155 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) { 13156 // Elaborate type variable declarations. 13157 verifyFormat("struct foo a = {bar};\nint n;"); 13158 verifyFormat("class foo a = {bar};\nint n;"); 13159 verifyFormat("union foo a = {bar};\nint n;"); 13160 13161 // Elaborate types inside function definitions. 13162 verifyFormat("struct foo f() {}\nint n;"); 13163 verifyFormat("class foo f() {}\nint n;"); 13164 verifyFormat("union foo f() {}\nint n;"); 13165 13166 // Templates. 13167 verifyFormat("template <class X> void f() {}\nint n;"); 13168 verifyFormat("template <struct X> void f() {}\nint n;"); 13169 verifyFormat("template <union X> void f() {}\nint n;"); 13170 13171 // Actual definitions... 13172 verifyFormat("struct {\n} n;"); 13173 verifyFormat( 13174 "template <template <class T, class Y>, class Z> class X {\n} n;"); 13175 verifyFormat("union Z {\n int n;\n} x;"); 13176 verifyFormat("class MACRO Z {\n} n;"); 13177 verifyFormat("class MACRO(X) Z {\n} n;"); 13178 verifyFormat("class __attribute__(X) Z {\n} n;"); 13179 verifyFormat("class __declspec(X) Z {\n} n;"); 13180 verifyFormat("class A##B##C {\n} n;"); 13181 verifyFormat("class alignas(16) Z {\n} n;"); 13182 verifyFormat("class MACRO(X) alignas(16) Z {\n} n;"); 13183 verifyFormat("class MACROA MACRO(X) Z {\n} n;"); 13184 13185 // Redefinition from nested context: 13186 verifyFormat("class A::B::C {\n} n;"); 13187 13188 // Template definitions. 13189 verifyFormat( 13190 "template <typename F>\n" 13191 "Matcher(const Matcher<F> &Other,\n" 13192 " typename enable_if_c<is_base_of<F, T>::value &&\n" 13193 " !is_same<F, T>::value>::type * = 0)\n" 13194 " : Implementation(new ImplicitCastMatcher<F>(Other)) {}"); 13195 13196 // FIXME: This is still incorrectly handled at the formatter side. 13197 verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};"); 13198 verifyFormat("int i = SomeFunction(a<b, a> b);"); 13199 13200 // FIXME: 13201 // This now gets parsed incorrectly as class definition. 13202 // verifyFormat("class A<int> f() {\n}\nint n;"); 13203 13204 // Elaborate types where incorrectly parsing the structural element would 13205 // break the indent. 13206 verifyFormat("if (true)\n" 13207 " class X x;\n" 13208 "else\n" 13209 " f();\n"); 13210 13211 // This is simply incomplete. Formatting is not important, but must not crash. 13212 verifyFormat("class A:"); 13213 } 13214 13215 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) { 13216 EXPECT_EQ("#error Leave all white!!!!! space* alone!\n", 13217 format("#error Leave all white!!!!! space* alone!\n")); 13218 EXPECT_EQ( 13219 "#warning Leave all white!!!!! space* alone!\n", 13220 format("#warning Leave all white!!!!! space* alone!\n")); 13221 EXPECT_EQ("#error 1", format(" # error 1")); 13222 EXPECT_EQ("#warning 1", format(" # warning 1")); 13223 } 13224 13225 TEST_F(FormatTest, FormatHashIfExpressions) { 13226 verifyFormat("#if AAAA && BBBB"); 13227 verifyFormat("#if (AAAA && BBBB)"); 13228 verifyFormat("#elif (AAAA && BBBB)"); 13229 // FIXME: Come up with a better indentation for #elif. 13230 verifyFormat( 13231 "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) && \\\n" 13232 " defined(BBBBBBBB)\n" 13233 "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) && \\\n" 13234 " defined(BBBBBBBB)\n" 13235 "#endif", 13236 getLLVMStyleWithColumns(65)); 13237 } 13238 13239 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) { 13240 FormatStyle AllowsMergedIf = getGoogleStyle(); 13241 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 13242 FormatStyle::SIS_WithoutElse; 13243 verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf); 13244 verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf); 13245 verifyFormat("if (true)\n#error E\n return 42;", AllowsMergedIf); 13246 EXPECT_EQ("if (true) return 42;", 13247 format("if (true)\nreturn 42;", AllowsMergedIf)); 13248 FormatStyle ShortMergedIf = AllowsMergedIf; 13249 ShortMergedIf.ColumnLimit = 25; 13250 verifyFormat("#define A \\\n" 13251 " if (true) return 42;", 13252 ShortMergedIf); 13253 verifyFormat("#define A \\\n" 13254 " f(); \\\n" 13255 " if (true)\n" 13256 "#define B", 13257 ShortMergedIf); 13258 verifyFormat("#define A \\\n" 13259 " f(); \\\n" 13260 " if (true)\n" 13261 "g();", 13262 ShortMergedIf); 13263 verifyFormat("{\n" 13264 "#ifdef A\n" 13265 " // Comment\n" 13266 " if (true) continue;\n" 13267 "#endif\n" 13268 " // Comment\n" 13269 " if (true) continue;\n" 13270 "}", 13271 ShortMergedIf); 13272 ShortMergedIf.ColumnLimit = 33; 13273 verifyFormat("#define A \\\n" 13274 " if constexpr (true) return 42;", 13275 ShortMergedIf); 13276 verifyFormat("#define A \\\n" 13277 " if CONSTEXPR (true) return 42;", 13278 ShortMergedIf); 13279 ShortMergedIf.ColumnLimit = 29; 13280 verifyFormat("#define A \\\n" 13281 " if (aaaaaaaaaa) return 1; \\\n" 13282 " return 2;", 13283 ShortMergedIf); 13284 ShortMergedIf.ColumnLimit = 28; 13285 verifyFormat("#define A \\\n" 13286 " if (aaaaaaaaaa) \\\n" 13287 " return 1; \\\n" 13288 " return 2;", 13289 ShortMergedIf); 13290 verifyFormat("#define A \\\n" 13291 " if constexpr (aaaaaaa) \\\n" 13292 " return 1; \\\n" 13293 " return 2;", 13294 ShortMergedIf); 13295 verifyFormat("#define A \\\n" 13296 " if CONSTEXPR (aaaaaaa) \\\n" 13297 " return 1; \\\n" 13298 " return 2;", 13299 ShortMergedIf); 13300 } 13301 13302 TEST_F(FormatTest, FormatStarDependingOnContext) { 13303 verifyFormat("void f(int *a);"); 13304 verifyFormat("void f() { f(fint * b); }"); 13305 verifyFormat("class A {\n void f(int *a);\n};"); 13306 verifyFormat("class A {\n int *a;\n};"); 13307 verifyFormat("namespace a {\n" 13308 "namespace b {\n" 13309 "class A {\n" 13310 " void f() {}\n" 13311 " int *a;\n" 13312 "};\n" 13313 "} // namespace b\n" 13314 "} // namespace a"); 13315 } 13316 13317 TEST_F(FormatTest, SpecialTokensAtEndOfLine) { 13318 verifyFormat("while"); 13319 verifyFormat("operator"); 13320 } 13321 13322 TEST_F(FormatTest, SkipsDeeplyNestedLines) { 13323 // This code would be painfully slow to format if we didn't skip it. 13324 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 13325 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13326 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13327 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13328 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13329 "A(1, 1)\n" 13330 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x 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 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13334 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13335 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13336 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13337 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13338 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13339 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n"); 13340 // Deeply nested part is untouched, rest is formatted. 13341 EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n", 13342 format(std::string("int i;\n") + Code + "int j;\n", 13343 getLLVMStyle(), SC_ExpectIncomplete)); 13344 } 13345 13346 //===----------------------------------------------------------------------===// 13347 // Objective-C tests. 13348 //===----------------------------------------------------------------------===// 13349 13350 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) { 13351 verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;"); 13352 EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;", 13353 format("-(NSUInteger)indexOfObject:(id)anObject;")); 13354 EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;")); 13355 EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;")); 13356 EXPECT_EQ("- (NSInteger)Method3:(id)anObject;", 13357 format("-(NSInteger)Method3:(id)anObject;")); 13358 EXPECT_EQ("- (NSInteger)Method4:(id)anObject;", 13359 format("-(NSInteger)Method4:(id)anObject;")); 13360 EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;", 13361 format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;")); 13362 EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;", 13363 format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;")); 13364 EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject " 13365 "forAllCells:(BOOL)flag;", 13366 format("- (void)sendAction:(SEL)aSelector to:(id)anObject " 13367 "forAllCells:(BOOL)flag;")); 13368 13369 // Very long objectiveC method declaration. 13370 verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n" 13371 " (SoooooooooooooooooooooomeType *)bbbbbbbbbb;"); 13372 verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n" 13373 " inRange:(NSRange)range\n" 13374 " outRange:(NSRange)out_range\n" 13375 " outRange1:(NSRange)out_range1\n" 13376 " outRange2:(NSRange)out_range2\n" 13377 " outRange3:(NSRange)out_range3\n" 13378 " outRange4:(NSRange)out_range4\n" 13379 " outRange5:(NSRange)out_range5\n" 13380 " outRange6:(NSRange)out_range6\n" 13381 " outRange7:(NSRange)out_range7\n" 13382 " outRange8:(NSRange)out_range8\n" 13383 " outRange9:(NSRange)out_range9;"); 13384 13385 // When the function name has to be wrapped. 13386 FormatStyle Style = getLLVMStyle(); 13387 // ObjC ignores IndentWrappedFunctionNames when wrapping methods 13388 // and always indents instead. 13389 Style.IndentWrappedFunctionNames = false; 13390 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n" 13391 " veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n" 13392 " anotherName:(NSString)bbbbbbbbbbbbbb {\n" 13393 "}", 13394 Style); 13395 Style.IndentWrappedFunctionNames = true; 13396 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n" 13397 " veryLooooooooooongName:(NSString)cccccccccccccc\n" 13398 " anotherName:(NSString)dddddddddddddd {\n" 13399 "}", 13400 Style); 13401 13402 verifyFormat("- (int)sum:(vector<int>)numbers;"); 13403 verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;"); 13404 // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC 13405 // protocol lists (but not for template classes): 13406 // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;"); 13407 13408 verifyFormat("- (int (*)())foo:(int (*)())f;"); 13409 verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;"); 13410 13411 // If there's no return type (very rare in practice!), LLVM and Google style 13412 // agree. 13413 verifyFormat("- foo;"); 13414 verifyFormat("- foo:(int)f;"); 13415 verifyGoogleFormat("- foo:(int)foo;"); 13416 } 13417 13418 TEST_F(FormatTest, BreaksStringLiterals) { 13419 EXPECT_EQ("\"some text \"\n" 13420 "\"other\";", 13421 format("\"some text other\";", getLLVMStyleWithColumns(12))); 13422 EXPECT_EQ("\"some text \"\n" 13423 "\"other\";", 13424 format("\\\n\"some text other\";", getLLVMStyleWithColumns(12))); 13425 EXPECT_EQ( 13426 "#define A \\\n" 13427 " \"some \" \\\n" 13428 " \"text \" \\\n" 13429 " \"other\";", 13430 format("#define A \"some text other\";", getLLVMStyleWithColumns(12))); 13431 EXPECT_EQ( 13432 "#define A \\\n" 13433 " \"so \" \\\n" 13434 " \"text \" \\\n" 13435 " \"other\";", 13436 format("#define A \"so text other\";", getLLVMStyleWithColumns(12))); 13437 13438 EXPECT_EQ("\"some text\"", 13439 format("\"some text\"", getLLVMStyleWithColumns(1))); 13440 EXPECT_EQ("\"some text\"", 13441 format("\"some text\"", getLLVMStyleWithColumns(11))); 13442 EXPECT_EQ("\"some \"\n" 13443 "\"text\"", 13444 format("\"some text\"", getLLVMStyleWithColumns(10))); 13445 EXPECT_EQ("\"some \"\n" 13446 "\"text\"", 13447 format("\"some text\"", getLLVMStyleWithColumns(7))); 13448 EXPECT_EQ("\"some\"\n" 13449 "\" tex\"\n" 13450 "\"t\"", 13451 format("\"some text\"", getLLVMStyleWithColumns(6))); 13452 EXPECT_EQ("\"some\"\n" 13453 "\" tex\"\n" 13454 "\" and\"", 13455 format("\"some tex and\"", getLLVMStyleWithColumns(6))); 13456 EXPECT_EQ("\"some\"\n" 13457 "\"/tex\"\n" 13458 "\"/and\"", 13459 format("\"some/tex/and\"", getLLVMStyleWithColumns(6))); 13460 13461 EXPECT_EQ("variable =\n" 13462 " \"long string \"\n" 13463 " \"literal\";", 13464 format("variable = \"long string literal\";", 13465 getLLVMStyleWithColumns(20))); 13466 13467 EXPECT_EQ("variable = f(\n" 13468 " \"long string \"\n" 13469 " \"literal\",\n" 13470 " short,\n" 13471 " loooooooooooooooooooong);", 13472 format("variable = f(\"long string literal\", short, " 13473 "loooooooooooooooooooong);", 13474 getLLVMStyleWithColumns(20))); 13475 13476 EXPECT_EQ( 13477 "f(g(\"long string \"\n" 13478 " \"literal\"),\n" 13479 " b);", 13480 format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20))); 13481 EXPECT_EQ("f(g(\"long string \"\n" 13482 " \"literal\",\n" 13483 " a),\n" 13484 " b);", 13485 format("f(g(\"long string literal\", a), b);", 13486 getLLVMStyleWithColumns(20))); 13487 EXPECT_EQ( 13488 "f(\"one two\".split(\n" 13489 " variable));", 13490 format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20))); 13491 EXPECT_EQ("f(\"one two three four five six \"\n" 13492 " \"seven\".split(\n" 13493 " really_looooong_variable));", 13494 format("f(\"one two three four five six seven\"." 13495 "split(really_looooong_variable));", 13496 getLLVMStyleWithColumns(33))); 13497 13498 EXPECT_EQ("f(\"some \"\n" 13499 " \"text\",\n" 13500 " other);", 13501 format("f(\"some text\", other);", getLLVMStyleWithColumns(10))); 13502 13503 // Only break as a last resort. 13504 verifyFormat( 13505 "aaaaaaaaaaaaaaaaaaaa(\n" 13506 " aaaaaaaaaaaaaaaaaaaa,\n" 13507 " aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));"); 13508 13509 EXPECT_EQ("\"splitmea\"\n" 13510 "\"trandomp\"\n" 13511 "\"oint\"", 13512 format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10))); 13513 13514 EXPECT_EQ("\"split/\"\n" 13515 "\"pathat/\"\n" 13516 "\"slashes\"", 13517 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10))); 13518 13519 EXPECT_EQ("\"split/\"\n" 13520 "\"pathat/\"\n" 13521 "\"slashes\"", 13522 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10))); 13523 EXPECT_EQ("\"split at \"\n" 13524 "\"spaces/at/\"\n" 13525 "\"slashes.at.any$\"\n" 13526 "\"non-alphanumeric%\"\n" 13527 "\"1111111111characte\"\n" 13528 "\"rs\"", 13529 format("\"split at " 13530 "spaces/at/" 13531 "slashes.at." 13532 "any$non-" 13533 "alphanumeric%" 13534 "1111111111characte" 13535 "rs\"", 13536 getLLVMStyleWithColumns(20))); 13537 13538 // Verify that splitting the strings understands 13539 // Style::AlwaysBreakBeforeMultilineStrings. 13540 EXPECT_EQ("aaaaaaaaaaaa(\n" 13541 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n" 13542 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");", 13543 format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa " 13544 "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa " 13545 "aaaaaaaaaaaaaaaaaaaaaa\");", 13546 getGoogleStyle())); 13547 EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13548 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";", 13549 format("return \"aaaaaaaaaaaaaaaaaaaaaa " 13550 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa " 13551 "aaaaaaaaaaaaaaaaaaaaaa\";", 13552 getGoogleStyle())); 13553 EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13554 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";", 13555 format("llvm::outs() << " 13556 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa" 13557 "aaaaaaaaaaaaaaaaaaa\";")); 13558 EXPECT_EQ("ffff(\n" 13559 " {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13560 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});", 13561 format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa " 13562 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});", 13563 getGoogleStyle())); 13564 13565 FormatStyle Style = getLLVMStyleWithColumns(12); 13566 Style.BreakStringLiterals = false; 13567 EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style)); 13568 13569 FormatStyle AlignLeft = getLLVMStyleWithColumns(12); 13570 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left; 13571 EXPECT_EQ("#define A \\\n" 13572 " \"some \" \\\n" 13573 " \"text \" \\\n" 13574 " \"other\";", 13575 format("#define A \"some text other\";", AlignLeft)); 13576 } 13577 13578 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) { 13579 EXPECT_EQ("C a = \"some more \"\n" 13580 " \"text\";", 13581 format("C a = \"some more text\";", getLLVMStyleWithColumns(18))); 13582 } 13583 13584 TEST_F(FormatTest, FullyRemoveEmptyLines) { 13585 FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80); 13586 NoEmptyLines.MaxEmptyLinesToKeep = 0; 13587 EXPECT_EQ("int i = a(b());", 13588 format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines)); 13589 } 13590 13591 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) { 13592 EXPECT_EQ( 13593 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 13594 "(\n" 13595 " \"x\t\");", 13596 format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 13597 "aaaaaaa(" 13598 "\"x\t\");")); 13599 } 13600 13601 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) { 13602 EXPECT_EQ( 13603 "u8\"utf8 string \"\n" 13604 "u8\"literal\";", 13605 format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16))); 13606 EXPECT_EQ( 13607 "u\"utf16 string \"\n" 13608 "u\"literal\";", 13609 format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16))); 13610 EXPECT_EQ( 13611 "U\"utf32 string \"\n" 13612 "U\"literal\";", 13613 format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16))); 13614 EXPECT_EQ("L\"wide string \"\n" 13615 "L\"literal\";", 13616 format("L\"wide string literal\";", getGoogleStyleWithColumns(16))); 13617 EXPECT_EQ("@\"NSString \"\n" 13618 "@\"literal\";", 13619 format("@\"NSString literal\";", getGoogleStyleWithColumns(19))); 13620 verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26)); 13621 13622 // This input makes clang-format try to split the incomplete unicode escape 13623 // sequence, which used to lead to a crasher. 13624 verifyNoCrash( 13625 "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 13626 getLLVMStyleWithColumns(60)); 13627 } 13628 13629 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) { 13630 FormatStyle Style = getGoogleStyleWithColumns(15); 13631 EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style)); 13632 EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style)); 13633 EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style)); 13634 EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style)); 13635 EXPECT_EQ("u8R\"x(raw literal)x\";", 13636 format("u8R\"x(raw literal)x\";", Style)); 13637 } 13638 13639 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) { 13640 FormatStyle Style = getLLVMStyleWithColumns(20); 13641 EXPECT_EQ( 13642 "_T(\"aaaaaaaaaaaaaa\")\n" 13643 "_T(\"aaaaaaaaaaaaaa\")\n" 13644 "_T(\"aaaaaaaaaaaa\")", 13645 format(" _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style)); 13646 EXPECT_EQ("f(x,\n" 13647 " _T(\"aaaaaaaaaaaa\")\n" 13648 " _T(\"aaa\"),\n" 13649 " z);", 13650 format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style)); 13651 13652 // FIXME: Handle embedded spaces in one iteration. 13653 // EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n" 13654 // "_T(\"aaaaaaaaaaaaa\")\n" 13655 // "_T(\"aaaaaaaaaaaaa\")\n" 13656 // "_T(\"a\")", 13657 // format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", 13658 // getLLVMStyleWithColumns(20))); 13659 EXPECT_EQ( 13660 "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", 13661 format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style)); 13662 EXPECT_EQ("f(\n" 13663 "#if !TEST\n" 13664 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n" 13665 "#endif\n" 13666 ");", 13667 format("f(\n" 13668 "#if !TEST\n" 13669 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n" 13670 "#endif\n" 13671 ");")); 13672 EXPECT_EQ("f(\n" 13673 "\n" 13674 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));", 13675 format("f(\n" 13676 "\n" 13677 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));")); 13678 // Regression test for accessing tokens past the end of a vector in the 13679 // TokenLexer. 13680 verifyNoCrash(R"(_T( 13681 " 13682 ) 13683 )"); 13684 } 13685 13686 TEST_F(FormatTest, BreaksStringLiteralOperands) { 13687 // In a function call with two operands, the second can be broken with no line 13688 // break before it. 13689 EXPECT_EQ( 13690 "func(a, \"long long \"\n" 13691 " \"long long\");", 13692 format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24))); 13693 // In a function call with three operands, the second must be broken with a 13694 // line break before it. 13695 EXPECT_EQ("func(a,\n" 13696 " \"long long long \"\n" 13697 " \"long\",\n" 13698 " c);", 13699 format("func(a, \"long long long long\", c);", 13700 getLLVMStyleWithColumns(24))); 13701 // In a function call with three operands, the third must be broken with a 13702 // line break before it. 13703 EXPECT_EQ("func(a, b,\n" 13704 " \"long long long \"\n" 13705 " \"long\");", 13706 format("func(a, b, \"long long long long\");", 13707 getLLVMStyleWithColumns(24))); 13708 // In a function call with three operands, both the second and the third must 13709 // be broken with a line break before them. 13710 EXPECT_EQ("func(a,\n" 13711 " \"long long long \"\n" 13712 " \"long\",\n" 13713 " \"long long long \"\n" 13714 " \"long\");", 13715 format("func(a, \"long long long long\", \"long long long long\");", 13716 getLLVMStyleWithColumns(24))); 13717 // In a chain of << with two operands, the second can be broken with no line 13718 // break before it. 13719 EXPECT_EQ("a << \"line line \"\n" 13720 " \"line\";", 13721 format("a << \"line line line\";", getLLVMStyleWithColumns(20))); 13722 // In a chain of << with three operands, the second can be broken with no line 13723 // break before it. 13724 EXPECT_EQ( 13725 "abcde << \"line \"\n" 13726 " \"line line\"\n" 13727 " << c;", 13728 format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20))); 13729 // In a chain of << with three operands, the third must be broken with a line 13730 // break before it. 13731 EXPECT_EQ( 13732 "a << b\n" 13733 " << \"line line \"\n" 13734 " \"line\";", 13735 format("a << b << \"line line line\";", getLLVMStyleWithColumns(20))); 13736 // In a chain of << with three operands, the second can be broken with no line 13737 // break before it and the third must be broken with a line break before it. 13738 EXPECT_EQ("abcd << \"line line \"\n" 13739 " \"line\"\n" 13740 " << \"line line \"\n" 13741 " \"line\";", 13742 format("abcd << \"line line line\" << \"line line line\";", 13743 getLLVMStyleWithColumns(20))); 13744 // In a chain of binary operators with two operands, the second can be broken 13745 // with no line break before it. 13746 EXPECT_EQ( 13747 "abcd + \"line line \"\n" 13748 " \"line line\";", 13749 format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20))); 13750 // In a chain of binary operators with three operands, the second must be 13751 // broken with a line break before it. 13752 EXPECT_EQ("abcd +\n" 13753 " \"line line \"\n" 13754 " \"line line\" +\n" 13755 " e;", 13756 format("abcd + \"line line line line\" + e;", 13757 getLLVMStyleWithColumns(20))); 13758 // In a function call with two operands, with AlignAfterOpenBracket enabled, 13759 // the first must be broken with a line break before it. 13760 FormatStyle Style = getLLVMStyleWithColumns(25); 13761 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 13762 EXPECT_EQ("someFunction(\n" 13763 " \"long long long \"\n" 13764 " \"long\",\n" 13765 " a);", 13766 format("someFunction(\"long long long long\", a);", Style)); 13767 } 13768 13769 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) { 13770 EXPECT_EQ( 13771 "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13772 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13773 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";", 13774 format("aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13775 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13776 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";")); 13777 } 13778 13779 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) { 13780 EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);", 13781 format("f(g(R\"x(raw literal)x\", a), b);", getGoogleStyle())); 13782 EXPECT_EQ("fffffffffff(g(R\"x(\n" 13783 "multiline raw string literal xxxxxxxxxxxxxx\n" 13784 ")x\",\n" 13785 " a),\n" 13786 " b);", 13787 format("fffffffffff(g(R\"x(\n" 13788 "multiline raw string literal xxxxxxxxxxxxxx\n" 13789 ")x\", a), b);", 13790 getGoogleStyleWithColumns(20))); 13791 EXPECT_EQ("fffffffffff(\n" 13792 " g(R\"x(qqq\n" 13793 "multiline raw string literal xxxxxxxxxxxxxx\n" 13794 ")x\",\n" 13795 " a),\n" 13796 " b);", 13797 format("fffffffffff(g(R\"x(qqq\n" 13798 "multiline raw string literal xxxxxxxxxxxxxx\n" 13799 ")x\", a), b);", 13800 getGoogleStyleWithColumns(20))); 13801 13802 EXPECT_EQ("fffffffffff(R\"x(\n" 13803 "multiline raw string literal xxxxxxxxxxxxxx\n" 13804 ")x\");", 13805 format("fffffffffff(R\"x(\n" 13806 "multiline raw string literal xxxxxxxxxxxxxx\n" 13807 ")x\");", 13808 getGoogleStyleWithColumns(20))); 13809 EXPECT_EQ("fffffffffff(R\"x(\n" 13810 "multiline raw string literal xxxxxxxxxxxxxx\n" 13811 ")x\" + bbbbbb);", 13812 format("fffffffffff(R\"x(\n" 13813 "multiline raw string literal xxxxxxxxxxxxxx\n" 13814 ")x\" + bbbbbb);", 13815 getGoogleStyleWithColumns(20))); 13816 EXPECT_EQ("fffffffffff(\n" 13817 " R\"x(\n" 13818 "multiline raw string literal xxxxxxxxxxxxxx\n" 13819 ")x\" +\n" 13820 " bbbbbb);", 13821 format("fffffffffff(\n" 13822 " R\"x(\n" 13823 "multiline raw string literal xxxxxxxxxxxxxx\n" 13824 ")x\" + bbbbbb);", 13825 getGoogleStyleWithColumns(20))); 13826 EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);", 13827 format("fffffffffff(\n" 13828 " R\"(single line raw string)\" + bbbbbb);")); 13829 } 13830 13831 TEST_F(FormatTest, SkipsUnknownStringLiterals) { 13832 verifyFormat("string a = \"unterminated;"); 13833 EXPECT_EQ("function(\"unterminated,\n" 13834 " OtherParameter);", 13835 format("function( \"unterminated,\n" 13836 " OtherParameter);")); 13837 } 13838 13839 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) { 13840 FormatStyle Style = getLLVMStyle(); 13841 Style.Standard = FormatStyle::LS_Cpp03; 13842 EXPECT_EQ("#define x(_a) printf(\"foo\" _a);", 13843 format("#define x(_a) printf(\"foo\"_a);", Style)); 13844 } 13845 13846 TEST_F(FormatTest, CppLexVersion) { 13847 FormatStyle Style = getLLVMStyle(); 13848 // Formatting of x * y differs if x is a type. 13849 verifyFormat("void foo() { MACRO(a * b); }", Style); 13850 verifyFormat("void foo() { MACRO(int *b); }", Style); 13851 13852 // LLVM style uses latest lexer. 13853 verifyFormat("void foo() { MACRO(char8_t *b); }", Style); 13854 Style.Standard = FormatStyle::LS_Cpp17; 13855 // But in c++17, char8_t isn't a keyword. 13856 verifyFormat("void foo() { MACRO(char8_t * b); }", Style); 13857 } 13858 13859 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); } 13860 13861 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) { 13862 EXPECT_EQ("someFunction(\"aaabbbcccd\"\n" 13863 " \"ddeeefff\");", 13864 format("someFunction(\"aaabbbcccdddeeefff\");", 13865 getLLVMStyleWithColumns(25))); 13866 EXPECT_EQ("someFunction1234567890(\n" 13867 " \"aaabbbcccdddeeefff\");", 13868 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 13869 getLLVMStyleWithColumns(26))); 13870 EXPECT_EQ("someFunction1234567890(\n" 13871 " \"aaabbbcccdddeeeff\"\n" 13872 " \"f\");", 13873 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 13874 getLLVMStyleWithColumns(25))); 13875 EXPECT_EQ("someFunction1234567890(\n" 13876 " \"aaabbbcccdddeeeff\"\n" 13877 " \"f\");", 13878 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 13879 getLLVMStyleWithColumns(24))); 13880 EXPECT_EQ("someFunction(\n" 13881 " \"aaabbbcc ddde \"\n" 13882 " \"efff\");", 13883 format("someFunction(\"aaabbbcc ddde efff\");", 13884 getLLVMStyleWithColumns(25))); 13885 EXPECT_EQ("someFunction(\"aaabbbccc \"\n" 13886 " \"ddeeefff\");", 13887 format("someFunction(\"aaabbbccc ddeeefff\");", 13888 getLLVMStyleWithColumns(25))); 13889 EXPECT_EQ("someFunction1234567890(\n" 13890 " \"aaabb \"\n" 13891 " \"cccdddeeefff\");", 13892 format("someFunction1234567890(\"aaabb cccdddeeefff\");", 13893 getLLVMStyleWithColumns(25))); 13894 EXPECT_EQ("#define A \\\n" 13895 " string s = \\\n" 13896 " \"123456789\" \\\n" 13897 " \"0\"; \\\n" 13898 " int i;", 13899 format("#define A string s = \"1234567890\"; int i;", 13900 getLLVMStyleWithColumns(20))); 13901 EXPECT_EQ("someFunction(\n" 13902 " \"aaabbbcc \"\n" 13903 " \"dddeeefff\");", 13904 format("someFunction(\"aaabbbcc dddeeefff\");", 13905 getLLVMStyleWithColumns(25))); 13906 } 13907 13908 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) { 13909 EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3))); 13910 EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2))); 13911 EXPECT_EQ("\"test\"\n" 13912 "\"\\n\"", 13913 format("\"test\\n\"", getLLVMStyleWithColumns(7))); 13914 EXPECT_EQ("\"tes\\\\\"\n" 13915 "\"n\"", 13916 format("\"tes\\\\n\"", getLLVMStyleWithColumns(7))); 13917 EXPECT_EQ("\"\\\\\\\\\"\n" 13918 "\"\\n\"", 13919 format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7))); 13920 EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7))); 13921 EXPECT_EQ("\"\\uff01\"\n" 13922 "\"test\"", 13923 format("\"\\uff01test\"", getLLVMStyleWithColumns(8))); 13924 EXPECT_EQ("\"\\Uff01ff02\"", 13925 format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11))); 13926 EXPECT_EQ("\"\\x000000000001\"\n" 13927 "\"next\"", 13928 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16))); 13929 EXPECT_EQ("\"\\x000000000001next\"", 13930 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15))); 13931 EXPECT_EQ("\"\\x000000000001\"", 13932 format("\"\\x000000000001\"", getLLVMStyleWithColumns(7))); 13933 EXPECT_EQ("\"test\"\n" 13934 "\"\\000000\"\n" 13935 "\"000001\"", 13936 format("\"test\\000000000001\"", getLLVMStyleWithColumns(9))); 13937 EXPECT_EQ("\"test\\000\"\n" 13938 "\"00000000\"\n" 13939 "\"1\"", 13940 format("\"test\\000000000001\"", getLLVMStyleWithColumns(10))); 13941 } 13942 13943 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) { 13944 verifyFormat("void f() {\n" 13945 " return g() {}\n" 13946 " void h() {}"); 13947 verifyFormat("int a[] = {void forgot_closing_brace(){f();\n" 13948 "g();\n" 13949 "}"); 13950 } 13951 13952 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) { 13953 verifyFormat( 13954 "void f() { return C{param1, param2}.SomeCall(param1, param2); }"); 13955 } 13956 13957 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) { 13958 verifyFormat("class X {\n" 13959 " void f() {\n" 13960 " }\n" 13961 "};", 13962 getLLVMStyleWithColumns(12)); 13963 } 13964 13965 TEST_F(FormatTest, ConfigurableIndentWidth) { 13966 FormatStyle EightIndent = getLLVMStyleWithColumns(18); 13967 EightIndent.IndentWidth = 8; 13968 EightIndent.ContinuationIndentWidth = 8; 13969 verifyFormat("void f() {\n" 13970 " someFunction();\n" 13971 " if (true) {\n" 13972 " f();\n" 13973 " }\n" 13974 "}", 13975 EightIndent); 13976 verifyFormat("class X {\n" 13977 " void f() {\n" 13978 " }\n" 13979 "};", 13980 EightIndent); 13981 verifyFormat("int x[] = {\n" 13982 " call(),\n" 13983 " call()};", 13984 EightIndent); 13985 } 13986 13987 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) { 13988 verifyFormat("double\n" 13989 "f();", 13990 getLLVMStyleWithColumns(8)); 13991 } 13992 13993 TEST_F(FormatTest, ConfigurableUseOfTab) { 13994 FormatStyle Tab = getLLVMStyleWithColumns(42); 13995 Tab.IndentWidth = 8; 13996 Tab.UseTab = FormatStyle::UT_Always; 13997 Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left; 13998 13999 EXPECT_EQ("if (aaaaaaaa && // q\n" 14000 " bb)\t\t// w\n" 14001 "\t;", 14002 format("if (aaaaaaaa &&// q\n" 14003 "bb)// w\n" 14004 ";", 14005 Tab)); 14006 EXPECT_EQ("if (aaa && bbb) // w\n" 14007 "\t;", 14008 format("if(aaa&&bbb)// w\n" 14009 ";", 14010 Tab)); 14011 14012 verifyFormat("class X {\n" 14013 "\tvoid f() {\n" 14014 "\t\tsomeFunction(parameter1,\n" 14015 "\t\t\t parameter2);\n" 14016 "\t}\n" 14017 "};", 14018 Tab); 14019 verifyFormat("#define A \\\n" 14020 "\tvoid f() { \\\n" 14021 "\t\tsomeFunction( \\\n" 14022 "\t\t parameter1, \\\n" 14023 "\t\t parameter2); \\\n" 14024 "\t}", 14025 Tab); 14026 verifyFormat("int a;\t // x\n" 14027 "int bbbbbbbb; // x\n", 14028 Tab); 14029 14030 Tab.TabWidth = 4; 14031 Tab.IndentWidth = 8; 14032 verifyFormat("class TabWidth4Indent8 {\n" 14033 "\t\tvoid f() {\n" 14034 "\t\t\t\tsomeFunction(parameter1,\n" 14035 "\t\t\t\t\t\t\t parameter2);\n" 14036 "\t\t}\n" 14037 "};", 14038 Tab); 14039 14040 Tab.TabWidth = 4; 14041 Tab.IndentWidth = 4; 14042 verifyFormat("class TabWidth4Indent4 {\n" 14043 "\tvoid f() {\n" 14044 "\t\tsomeFunction(parameter1,\n" 14045 "\t\t\t\t\t parameter2);\n" 14046 "\t}\n" 14047 "};", 14048 Tab); 14049 14050 Tab.TabWidth = 8; 14051 Tab.IndentWidth = 4; 14052 verifyFormat("class TabWidth8Indent4 {\n" 14053 " void f() {\n" 14054 "\tsomeFunction(parameter1,\n" 14055 "\t\t parameter2);\n" 14056 " }\n" 14057 "};", 14058 Tab); 14059 14060 Tab.TabWidth = 8; 14061 Tab.IndentWidth = 8; 14062 EXPECT_EQ("/*\n" 14063 "\t a\t\tcomment\n" 14064 "\t in multiple lines\n" 14065 " */", 14066 format(" /*\t \t \n" 14067 " \t \t a\t\tcomment\t \t\n" 14068 " \t \t in multiple lines\t\n" 14069 " \t */", 14070 Tab)); 14071 14072 Tab.UseTab = FormatStyle::UT_ForIndentation; 14073 verifyFormat("{\n" 14074 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14075 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14076 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14077 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14078 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14079 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14080 "};", 14081 Tab); 14082 verifyFormat("enum AA {\n" 14083 "\ta1, // Force multiple lines\n" 14084 "\ta2,\n" 14085 "\ta3\n" 14086 "};", 14087 Tab); 14088 EXPECT_EQ("if (aaaaaaaa && // q\n" 14089 " bb) // w\n" 14090 "\t;", 14091 format("if (aaaaaaaa &&// q\n" 14092 "bb)// w\n" 14093 ";", 14094 Tab)); 14095 verifyFormat("class X {\n" 14096 "\tvoid f() {\n" 14097 "\t\tsomeFunction(parameter1,\n" 14098 "\t\t parameter2);\n" 14099 "\t}\n" 14100 "};", 14101 Tab); 14102 verifyFormat("{\n" 14103 "\tQ(\n" 14104 "\t {\n" 14105 "\t\t int a;\n" 14106 "\t\t someFunction(aaaaaaaa,\n" 14107 "\t\t bbbbbbb);\n" 14108 "\t },\n" 14109 "\t p);\n" 14110 "}", 14111 Tab); 14112 EXPECT_EQ("{\n" 14113 "\t/* aaaa\n" 14114 "\t bbbb */\n" 14115 "}", 14116 format("{\n" 14117 "/* aaaa\n" 14118 " bbbb */\n" 14119 "}", 14120 Tab)); 14121 EXPECT_EQ("{\n" 14122 "\t/*\n" 14123 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14124 "\t bbbbbbbbbbbbb\n" 14125 "\t*/\n" 14126 "}", 14127 format("{\n" 14128 "/*\n" 14129 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14130 "*/\n" 14131 "}", 14132 Tab)); 14133 EXPECT_EQ("{\n" 14134 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14135 "\t// bbbbbbbbbbbbb\n" 14136 "}", 14137 format("{\n" 14138 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14139 "}", 14140 Tab)); 14141 EXPECT_EQ("{\n" 14142 "\t/*\n" 14143 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14144 "\t bbbbbbbbbbbbb\n" 14145 "\t*/\n" 14146 "}", 14147 format("{\n" 14148 "\t/*\n" 14149 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14150 "\t*/\n" 14151 "}", 14152 Tab)); 14153 EXPECT_EQ("{\n" 14154 "\t/*\n" 14155 "\n" 14156 "\t*/\n" 14157 "}", 14158 format("{\n" 14159 "\t/*\n" 14160 "\n" 14161 "\t*/\n" 14162 "}", 14163 Tab)); 14164 EXPECT_EQ("{\n" 14165 "\t/*\n" 14166 " asdf\n" 14167 "\t*/\n" 14168 "}", 14169 format("{\n" 14170 "\t/*\n" 14171 " asdf\n" 14172 "\t*/\n" 14173 "}", 14174 Tab)); 14175 14176 verifyFormat("void f() {\n" 14177 "\treturn true ? aaaaaaaaaaaaaaaaaa\n" 14178 "\t : bbbbbbbbbbbbbbbbbb\n" 14179 "}", 14180 Tab); 14181 FormatStyle TabNoBreak = Tab; 14182 TabNoBreak.BreakBeforeTernaryOperators = false; 14183 verifyFormat("void f() {\n" 14184 "\treturn true ? aaaaaaaaaaaaaaaaaa :\n" 14185 "\t bbbbbbbbbbbbbbbbbb\n" 14186 "}", 14187 TabNoBreak); 14188 verifyFormat("void f() {\n" 14189 "\treturn true ?\n" 14190 "\t aaaaaaaaaaaaaaaaaaaa :\n" 14191 "\t bbbbbbbbbbbbbbbbbbbb\n" 14192 "}", 14193 TabNoBreak); 14194 14195 Tab.UseTab = FormatStyle::UT_Never; 14196 EXPECT_EQ("/*\n" 14197 " a\t\tcomment\n" 14198 " in multiple lines\n" 14199 " */", 14200 format(" /*\t \t \n" 14201 " \t \t a\t\tcomment\t \t\n" 14202 " \t \t in multiple lines\t\n" 14203 " \t */", 14204 Tab)); 14205 EXPECT_EQ("/* some\n" 14206 " comment */", 14207 format(" \t \t /* some\n" 14208 " \t \t comment */", 14209 Tab)); 14210 EXPECT_EQ("int a; /* some\n" 14211 " comment */", 14212 format(" \t \t int a; /* some\n" 14213 " \t \t comment */", 14214 Tab)); 14215 14216 EXPECT_EQ("int a; /* some\n" 14217 "comment */", 14218 format(" \t \t int\ta; /* some\n" 14219 " \t \t comment */", 14220 Tab)); 14221 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14222 " comment */", 14223 format(" \t \t f(\"\t\t\"); /* some\n" 14224 " \t \t comment */", 14225 Tab)); 14226 EXPECT_EQ("{\n" 14227 " /*\n" 14228 " * Comment\n" 14229 " */\n" 14230 " int i;\n" 14231 "}", 14232 format("{\n" 14233 "\t/*\n" 14234 "\t * Comment\n" 14235 "\t */\n" 14236 "\t int i;\n" 14237 "}", 14238 Tab)); 14239 14240 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation; 14241 Tab.TabWidth = 8; 14242 Tab.IndentWidth = 8; 14243 EXPECT_EQ("if (aaaaaaaa && // q\n" 14244 " bb) // w\n" 14245 "\t;", 14246 format("if (aaaaaaaa &&// q\n" 14247 "bb)// w\n" 14248 ";", 14249 Tab)); 14250 EXPECT_EQ("if (aaa && bbb) // w\n" 14251 "\t;", 14252 format("if(aaa&&bbb)// w\n" 14253 ";", 14254 Tab)); 14255 verifyFormat("class X {\n" 14256 "\tvoid f() {\n" 14257 "\t\tsomeFunction(parameter1,\n" 14258 "\t\t\t parameter2);\n" 14259 "\t}\n" 14260 "};", 14261 Tab); 14262 verifyFormat("#define A \\\n" 14263 "\tvoid f() { \\\n" 14264 "\t\tsomeFunction( \\\n" 14265 "\t\t parameter1, \\\n" 14266 "\t\t parameter2); \\\n" 14267 "\t}", 14268 Tab); 14269 Tab.TabWidth = 4; 14270 Tab.IndentWidth = 8; 14271 verifyFormat("class TabWidth4Indent8 {\n" 14272 "\t\tvoid f() {\n" 14273 "\t\t\t\tsomeFunction(parameter1,\n" 14274 "\t\t\t\t\t\t\t parameter2);\n" 14275 "\t\t}\n" 14276 "};", 14277 Tab); 14278 Tab.TabWidth = 4; 14279 Tab.IndentWidth = 4; 14280 verifyFormat("class TabWidth4Indent4 {\n" 14281 "\tvoid f() {\n" 14282 "\t\tsomeFunction(parameter1,\n" 14283 "\t\t\t\t\t parameter2);\n" 14284 "\t}\n" 14285 "};", 14286 Tab); 14287 Tab.TabWidth = 8; 14288 Tab.IndentWidth = 4; 14289 verifyFormat("class TabWidth8Indent4 {\n" 14290 " void f() {\n" 14291 "\tsomeFunction(parameter1,\n" 14292 "\t\t parameter2);\n" 14293 " }\n" 14294 "};", 14295 Tab); 14296 Tab.TabWidth = 8; 14297 Tab.IndentWidth = 8; 14298 EXPECT_EQ("/*\n" 14299 "\t a\t\tcomment\n" 14300 "\t in multiple lines\n" 14301 " */", 14302 format(" /*\t \t \n" 14303 " \t \t a\t\tcomment\t \t\n" 14304 " \t \t in multiple lines\t\n" 14305 " \t */", 14306 Tab)); 14307 verifyFormat("{\n" 14308 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14309 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14310 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14311 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14312 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14313 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14314 "};", 14315 Tab); 14316 verifyFormat("enum AA {\n" 14317 "\ta1, // Force multiple lines\n" 14318 "\ta2,\n" 14319 "\ta3\n" 14320 "};", 14321 Tab); 14322 EXPECT_EQ("if (aaaaaaaa && // q\n" 14323 " bb) // w\n" 14324 "\t;", 14325 format("if (aaaaaaaa &&// q\n" 14326 "bb)// w\n" 14327 ";", 14328 Tab)); 14329 verifyFormat("class X {\n" 14330 "\tvoid f() {\n" 14331 "\t\tsomeFunction(parameter1,\n" 14332 "\t\t\t parameter2);\n" 14333 "\t}\n" 14334 "};", 14335 Tab); 14336 verifyFormat("{\n" 14337 "\tQ(\n" 14338 "\t {\n" 14339 "\t\t int a;\n" 14340 "\t\t someFunction(aaaaaaaa,\n" 14341 "\t\t\t\t bbbbbbb);\n" 14342 "\t },\n" 14343 "\t p);\n" 14344 "}", 14345 Tab); 14346 EXPECT_EQ("{\n" 14347 "\t/* aaaa\n" 14348 "\t bbbb */\n" 14349 "}", 14350 format("{\n" 14351 "/* aaaa\n" 14352 " bbbb */\n" 14353 "}", 14354 Tab)); 14355 EXPECT_EQ("{\n" 14356 "\t/*\n" 14357 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14358 "\t bbbbbbbbbbbbb\n" 14359 "\t*/\n" 14360 "}", 14361 format("{\n" 14362 "/*\n" 14363 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14364 "*/\n" 14365 "}", 14366 Tab)); 14367 EXPECT_EQ("{\n" 14368 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14369 "\t// bbbbbbbbbbbbb\n" 14370 "}", 14371 format("{\n" 14372 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14373 "}", 14374 Tab)); 14375 EXPECT_EQ("{\n" 14376 "\t/*\n" 14377 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14378 "\t bbbbbbbbbbbbb\n" 14379 "\t*/\n" 14380 "}", 14381 format("{\n" 14382 "\t/*\n" 14383 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14384 "\t*/\n" 14385 "}", 14386 Tab)); 14387 EXPECT_EQ("{\n" 14388 "\t/*\n" 14389 "\n" 14390 "\t*/\n" 14391 "}", 14392 format("{\n" 14393 "\t/*\n" 14394 "\n" 14395 "\t*/\n" 14396 "}", 14397 Tab)); 14398 EXPECT_EQ("{\n" 14399 "\t/*\n" 14400 " asdf\n" 14401 "\t*/\n" 14402 "}", 14403 format("{\n" 14404 "\t/*\n" 14405 " asdf\n" 14406 "\t*/\n" 14407 "}", 14408 Tab)); 14409 EXPECT_EQ("/* some\n" 14410 " comment */", 14411 format(" \t \t /* some\n" 14412 " \t \t comment */", 14413 Tab)); 14414 EXPECT_EQ("int a; /* some\n" 14415 " comment */", 14416 format(" \t \t int a; /* some\n" 14417 " \t \t comment */", 14418 Tab)); 14419 EXPECT_EQ("int a; /* some\n" 14420 "comment */", 14421 format(" \t \t int\ta; /* some\n" 14422 " \t \t comment */", 14423 Tab)); 14424 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14425 " comment */", 14426 format(" \t \t f(\"\t\t\"); /* some\n" 14427 " \t \t comment */", 14428 Tab)); 14429 EXPECT_EQ("{\n" 14430 "\t/*\n" 14431 "\t * Comment\n" 14432 "\t */\n" 14433 "\tint i;\n" 14434 "}", 14435 format("{\n" 14436 "\t/*\n" 14437 "\t * Comment\n" 14438 "\t */\n" 14439 "\t int i;\n" 14440 "}", 14441 Tab)); 14442 Tab.TabWidth = 2; 14443 Tab.IndentWidth = 2; 14444 EXPECT_EQ("{\n" 14445 "\t/* aaaa\n" 14446 "\t\t bbbb */\n" 14447 "}", 14448 format("{\n" 14449 "/* aaaa\n" 14450 "\t bbbb */\n" 14451 "}", 14452 Tab)); 14453 EXPECT_EQ("{\n" 14454 "\t/*\n" 14455 "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14456 "\t\tbbbbbbbbbbbbb\n" 14457 "\t*/\n" 14458 "}", 14459 format("{\n" 14460 "/*\n" 14461 "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14462 "*/\n" 14463 "}", 14464 Tab)); 14465 Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 14466 Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 14467 Tab.TabWidth = 4; 14468 Tab.IndentWidth = 4; 14469 verifyFormat("class Assign {\n" 14470 "\tvoid f() {\n" 14471 "\t\tint x = 123;\n" 14472 "\t\tint random = 4;\n" 14473 "\t\tstd::string alphabet =\n" 14474 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n" 14475 "\t}\n" 14476 "};", 14477 Tab); 14478 14479 Tab.UseTab = FormatStyle::UT_AlignWithSpaces; 14480 Tab.TabWidth = 8; 14481 Tab.IndentWidth = 8; 14482 EXPECT_EQ("if (aaaaaaaa && // q\n" 14483 " bb) // w\n" 14484 "\t;", 14485 format("if (aaaaaaaa &&// q\n" 14486 "bb)// w\n" 14487 ";", 14488 Tab)); 14489 EXPECT_EQ("if (aaa && bbb) // w\n" 14490 "\t;", 14491 format("if(aaa&&bbb)// w\n" 14492 ";", 14493 Tab)); 14494 verifyFormat("class X {\n" 14495 "\tvoid f() {\n" 14496 "\t\tsomeFunction(parameter1,\n" 14497 "\t\t parameter2);\n" 14498 "\t}\n" 14499 "};", 14500 Tab); 14501 verifyFormat("#define A \\\n" 14502 "\tvoid f() { \\\n" 14503 "\t\tsomeFunction( \\\n" 14504 "\t\t parameter1, \\\n" 14505 "\t\t parameter2); \\\n" 14506 "\t}", 14507 Tab); 14508 Tab.TabWidth = 4; 14509 Tab.IndentWidth = 8; 14510 verifyFormat("class TabWidth4Indent8 {\n" 14511 "\t\tvoid f() {\n" 14512 "\t\t\t\tsomeFunction(parameter1,\n" 14513 "\t\t\t\t parameter2);\n" 14514 "\t\t}\n" 14515 "};", 14516 Tab); 14517 Tab.TabWidth = 4; 14518 Tab.IndentWidth = 4; 14519 verifyFormat("class TabWidth4Indent4 {\n" 14520 "\tvoid f() {\n" 14521 "\t\tsomeFunction(parameter1,\n" 14522 "\t\t parameter2);\n" 14523 "\t}\n" 14524 "};", 14525 Tab); 14526 Tab.TabWidth = 8; 14527 Tab.IndentWidth = 4; 14528 verifyFormat("class TabWidth8Indent4 {\n" 14529 " void f() {\n" 14530 "\tsomeFunction(parameter1,\n" 14531 "\t parameter2);\n" 14532 " }\n" 14533 "};", 14534 Tab); 14535 Tab.TabWidth = 8; 14536 Tab.IndentWidth = 8; 14537 EXPECT_EQ("/*\n" 14538 " a\t\tcomment\n" 14539 " in multiple lines\n" 14540 " */", 14541 format(" /*\t \t \n" 14542 " \t \t a\t\tcomment\t \t\n" 14543 " \t \t in multiple lines\t\n" 14544 " \t */", 14545 Tab)); 14546 verifyFormat("{\n" 14547 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14548 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14549 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14550 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14551 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14552 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14553 "};", 14554 Tab); 14555 verifyFormat("enum AA {\n" 14556 "\ta1, // Force multiple lines\n" 14557 "\ta2,\n" 14558 "\ta3\n" 14559 "};", 14560 Tab); 14561 EXPECT_EQ("if (aaaaaaaa && // q\n" 14562 " bb) // w\n" 14563 "\t;", 14564 format("if (aaaaaaaa &&// q\n" 14565 "bb)// w\n" 14566 ";", 14567 Tab)); 14568 verifyFormat("class X {\n" 14569 "\tvoid f() {\n" 14570 "\t\tsomeFunction(parameter1,\n" 14571 "\t\t parameter2);\n" 14572 "\t}\n" 14573 "};", 14574 Tab); 14575 verifyFormat("{\n" 14576 "\tQ(\n" 14577 "\t {\n" 14578 "\t\t int a;\n" 14579 "\t\t someFunction(aaaaaaaa,\n" 14580 "\t\t bbbbbbb);\n" 14581 "\t },\n" 14582 "\t p);\n" 14583 "}", 14584 Tab); 14585 EXPECT_EQ("{\n" 14586 "\t/* aaaa\n" 14587 "\t bbbb */\n" 14588 "}", 14589 format("{\n" 14590 "/* aaaa\n" 14591 " bbbb */\n" 14592 "}", 14593 Tab)); 14594 EXPECT_EQ("{\n" 14595 "\t/*\n" 14596 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14597 "\t bbbbbbbbbbbbb\n" 14598 "\t*/\n" 14599 "}", 14600 format("{\n" 14601 "/*\n" 14602 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14603 "*/\n" 14604 "}", 14605 Tab)); 14606 EXPECT_EQ("{\n" 14607 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14608 "\t// bbbbbbbbbbbbb\n" 14609 "}", 14610 format("{\n" 14611 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14612 "}", 14613 Tab)); 14614 EXPECT_EQ("{\n" 14615 "\t/*\n" 14616 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14617 "\t bbbbbbbbbbbbb\n" 14618 "\t*/\n" 14619 "}", 14620 format("{\n" 14621 "\t/*\n" 14622 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14623 "\t*/\n" 14624 "}", 14625 Tab)); 14626 EXPECT_EQ("{\n" 14627 "\t/*\n" 14628 "\n" 14629 "\t*/\n" 14630 "}", 14631 format("{\n" 14632 "\t/*\n" 14633 "\n" 14634 "\t*/\n" 14635 "}", 14636 Tab)); 14637 EXPECT_EQ("{\n" 14638 "\t/*\n" 14639 " asdf\n" 14640 "\t*/\n" 14641 "}", 14642 format("{\n" 14643 "\t/*\n" 14644 " asdf\n" 14645 "\t*/\n" 14646 "}", 14647 Tab)); 14648 EXPECT_EQ("/* some\n" 14649 " comment */", 14650 format(" \t \t /* some\n" 14651 " \t \t comment */", 14652 Tab)); 14653 EXPECT_EQ("int a; /* some\n" 14654 " comment */", 14655 format(" \t \t int a; /* some\n" 14656 " \t \t comment */", 14657 Tab)); 14658 EXPECT_EQ("int a; /* some\n" 14659 "comment */", 14660 format(" \t \t int\ta; /* some\n" 14661 " \t \t comment */", 14662 Tab)); 14663 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14664 " comment */", 14665 format(" \t \t f(\"\t\t\"); /* some\n" 14666 " \t \t comment */", 14667 Tab)); 14668 EXPECT_EQ("{\n" 14669 "\t/*\n" 14670 "\t * Comment\n" 14671 "\t */\n" 14672 "\tint i;\n" 14673 "}", 14674 format("{\n" 14675 "\t/*\n" 14676 "\t * Comment\n" 14677 "\t */\n" 14678 "\t int i;\n" 14679 "}", 14680 Tab)); 14681 Tab.TabWidth = 2; 14682 Tab.IndentWidth = 2; 14683 EXPECT_EQ("{\n" 14684 "\t/* aaaa\n" 14685 "\t bbbb */\n" 14686 "}", 14687 format("{\n" 14688 "/* aaaa\n" 14689 " bbbb */\n" 14690 "}", 14691 Tab)); 14692 EXPECT_EQ("{\n" 14693 "\t/*\n" 14694 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14695 "\t bbbbbbbbbbbbb\n" 14696 "\t*/\n" 14697 "}", 14698 format("{\n" 14699 "/*\n" 14700 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14701 "*/\n" 14702 "}", 14703 Tab)); 14704 Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 14705 Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 14706 Tab.TabWidth = 4; 14707 Tab.IndentWidth = 4; 14708 verifyFormat("class Assign {\n" 14709 "\tvoid f() {\n" 14710 "\t\tint x = 123;\n" 14711 "\t\tint random = 4;\n" 14712 "\t\tstd::string alphabet =\n" 14713 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n" 14714 "\t}\n" 14715 "};", 14716 Tab); 14717 Tab.AlignOperands = FormatStyle::OAS_Align; 14718 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n" 14719 " cccccccccccccccccccc;", 14720 Tab); 14721 // no alignment 14722 verifyFormat("int aaaaaaaaaa =\n" 14723 "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 14724 Tab); 14725 verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n" 14726 " : bbbbbbbbbbbbbb ? 222222222222222\n" 14727 " : 333333333333333;", 14728 Tab); 14729 Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 14730 Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator; 14731 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n" 14732 " + cccccccccccccccccccc;", 14733 Tab); 14734 } 14735 14736 TEST_F(FormatTest, ZeroTabWidth) { 14737 FormatStyle Tab = getLLVMStyleWithColumns(42); 14738 Tab.IndentWidth = 8; 14739 Tab.UseTab = FormatStyle::UT_Never; 14740 Tab.TabWidth = 0; 14741 EXPECT_EQ("void a(){\n" 14742 " // line starts with '\t'\n" 14743 "};", 14744 format("void a(){\n" 14745 "\t// line starts with '\t'\n" 14746 "};", 14747 Tab)); 14748 14749 EXPECT_EQ("void a(){\n" 14750 " // line starts with '\t'\n" 14751 "};", 14752 format("void a(){\n" 14753 "\t\t// line starts with '\t'\n" 14754 "};", 14755 Tab)); 14756 14757 Tab.UseTab = FormatStyle::UT_ForIndentation; 14758 EXPECT_EQ("void a(){\n" 14759 " // line starts with '\t'\n" 14760 "};", 14761 format("void a(){\n" 14762 "\t// line starts with '\t'\n" 14763 "};", 14764 Tab)); 14765 14766 EXPECT_EQ("void a(){\n" 14767 " // line starts with '\t'\n" 14768 "};", 14769 format("void a(){\n" 14770 "\t\t// line starts with '\t'\n" 14771 "};", 14772 Tab)); 14773 14774 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation; 14775 EXPECT_EQ("void a(){\n" 14776 " // line starts with '\t'\n" 14777 "};", 14778 format("void a(){\n" 14779 "\t// line starts with '\t'\n" 14780 "};", 14781 Tab)); 14782 14783 EXPECT_EQ("void a(){\n" 14784 " // line starts with '\t'\n" 14785 "};", 14786 format("void a(){\n" 14787 "\t\t// line starts with '\t'\n" 14788 "};", 14789 Tab)); 14790 14791 Tab.UseTab = FormatStyle::UT_AlignWithSpaces; 14792 EXPECT_EQ("void a(){\n" 14793 " // line starts with '\t'\n" 14794 "};", 14795 format("void a(){\n" 14796 "\t// line starts with '\t'\n" 14797 "};", 14798 Tab)); 14799 14800 EXPECT_EQ("void a(){\n" 14801 " // line starts with '\t'\n" 14802 "};", 14803 format("void a(){\n" 14804 "\t\t// line starts with '\t'\n" 14805 "};", 14806 Tab)); 14807 14808 Tab.UseTab = FormatStyle::UT_Always; 14809 EXPECT_EQ("void a(){\n" 14810 "// line starts with '\t'\n" 14811 "};", 14812 format("void a(){\n" 14813 "\t// line starts with '\t'\n" 14814 "};", 14815 Tab)); 14816 14817 EXPECT_EQ("void a(){\n" 14818 "// line starts with '\t'\n" 14819 "};", 14820 format("void a(){\n" 14821 "\t\t// line starts with '\t'\n" 14822 "};", 14823 Tab)); 14824 } 14825 14826 TEST_F(FormatTest, CalculatesOriginalColumn) { 14827 EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14828 "q\"; /* some\n" 14829 " comment */", 14830 format(" \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14831 "q\"; /* some\n" 14832 " comment */", 14833 getLLVMStyle())); 14834 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n" 14835 "/* some\n" 14836 " comment */", 14837 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n" 14838 " /* some\n" 14839 " comment */", 14840 getLLVMStyle())); 14841 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14842 "qqq\n" 14843 "/* some\n" 14844 " comment */", 14845 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14846 "qqq\n" 14847 " /* some\n" 14848 " comment */", 14849 getLLVMStyle())); 14850 EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14851 "wwww; /* some\n" 14852 " comment */", 14853 format(" inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14854 "wwww; /* some\n" 14855 " comment */", 14856 getLLVMStyle())); 14857 } 14858 14859 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) { 14860 FormatStyle NoSpace = getLLVMStyle(); 14861 NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never; 14862 14863 verifyFormat("while(true)\n" 14864 " continue;", 14865 NoSpace); 14866 verifyFormat("for(;;)\n" 14867 " continue;", 14868 NoSpace); 14869 verifyFormat("if(true)\n" 14870 " f();\n" 14871 "else if(true)\n" 14872 " f();", 14873 NoSpace); 14874 verifyFormat("do {\n" 14875 " do_something();\n" 14876 "} while(something());", 14877 NoSpace); 14878 verifyFormat("switch(x) {\n" 14879 "default:\n" 14880 " break;\n" 14881 "}", 14882 NoSpace); 14883 verifyFormat("auto i = std::make_unique<int>(5);", NoSpace); 14884 verifyFormat("size_t x = sizeof(x);", NoSpace); 14885 verifyFormat("auto f(int x) -> decltype(x);", NoSpace); 14886 verifyFormat("auto f(int x) -> typeof(x);", NoSpace); 14887 verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace); 14888 verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace); 14889 verifyFormat("int f(T x) noexcept(x.create());", NoSpace); 14890 verifyFormat("alignas(128) char a[128];", NoSpace); 14891 verifyFormat("size_t x = alignof(MyType);", NoSpace); 14892 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace); 14893 verifyFormat("int f() throw(Deprecated);", NoSpace); 14894 verifyFormat("typedef void (*cb)(int);", NoSpace); 14895 verifyFormat("T A::operator()();", NoSpace); 14896 verifyFormat("X A::operator++(T);", NoSpace); 14897 verifyFormat("auto lambda = []() { return 0; };", NoSpace); 14898 14899 FormatStyle Space = getLLVMStyle(); 14900 Space.SpaceBeforeParens = FormatStyle::SBPO_Always; 14901 14902 verifyFormat("int f ();", Space); 14903 verifyFormat("void f (int a, T b) {\n" 14904 " while (true)\n" 14905 " continue;\n" 14906 "}", 14907 Space); 14908 verifyFormat("if (true)\n" 14909 " f ();\n" 14910 "else if (true)\n" 14911 " f ();", 14912 Space); 14913 verifyFormat("do {\n" 14914 " do_something ();\n" 14915 "} while (something ());", 14916 Space); 14917 verifyFormat("switch (x) {\n" 14918 "default:\n" 14919 " break;\n" 14920 "}", 14921 Space); 14922 verifyFormat("A::A () : a (1) {}", Space); 14923 verifyFormat("void f () __attribute__ ((asdf));", Space); 14924 verifyFormat("*(&a + 1);\n" 14925 "&((&a)[1]);\n" 14926 "a[(b + c) * d];\n" 14927 "(((a + 1) * 2) + 3) * 4;", 14928 Space); 14929 verifyFormat("#define A(x) x", Space); 14930 verifyFormat("#define A (x) x", Space); 14931 verifyFormat("#if defined(x)\n" 14932 "#endif", 14933 Space); 14934 verifyFormat("auto i = std::make_unique<int> (5);", Space); 14935 verifyFormat("size_t x = sizeof (x);", Space); 14936 verifyFormat("auto f (int x) -> decltype (x);", Space); 14937 verifyFormat("auto f (int x) -> typeof (x);", Space); 14938 verifyFormat("auto f (int x) -> _Atomic (x);", Space); 14939 verifyFormat("auto f (int x) -> __underlying_type (x);", Space); 14940 verifyFormat("int f (T x) noexcept (x.create ());", Space); 14941 verifyFormat("alignas (128) char a[128];", Space); 14942 verifyFormat("size_t x = alignof (MyType);", Space); 14943 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space); 14944 verifyFormat("int f () throw (Deprecated);", Space); 14945 verifyFormat("typedef void (*cb) (int);", Space); 14946 // FIXME these tests regressed behaviour. 14947 // verifyFormat("T A::operator() ();", Space); 14948 // verifyFormat("X A::operator++ (T);", Space); 14949 verifyFormat("auto lambda = [] () { return 0; };", Space); 14950 verifyFormat("int x = int (y);", Space); 14951 14952 FormatStyle SomeSpace = getLLVMStyle(); 14953 SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses; 14954 14955 verifyFormat("[]() -> float {}", SomeSpace); 14956 verifyFormat("[] (auto foo) {}", SomeSpace); 14957 verifyFormat("[foo]() -> int {}", SomeSpace); 14958 verifyFormat("int f();", SomeSpace); 14959 verifyFormat("void f (int a, T b) {\n" 14960 " while (true)\n" 14961 " continue;\n" 14962 "}", 14963 SomeSpace); 14964 verifyFormat("if (true)\n" 14965 " f();\n" 14966 "else if (true)\n" 14967 " f();", 14968 SomeSpace); 14969 verifyFormat("do {\n" 14970 " do_something();\n" 14971 "} while (something());", 14972 SomeSpace); 14973 verifyFormat("switch (x) {\n" 14974 "default:\n" 14975 " break;\n" 14976 "}", 14977 SomeSpace); 14978 verifyFormat("A::A() : a (1) {}", SomeSpace); 14979 verifyFormat("void f() __attribute__ ((asdf));", SomeSpace); 14980 verifyFormat("*(&a + 1);\n" 14981 "&((&a)[1]);\n" 14982 "a[(b + c) * d];\n" 14983 "(((a + 1) * 2) + 3) * 4;", 14984 SomeSpace); 14985 verifyFormat("#define A(x) x", SomeSpace); 14986 verifyFormat("#define A (x) x", SomeSpace); 14987 verifyFormat("#if defined(x)\n" 14988 "#endif", 14989 SomeSpace); 14990 verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace); 14991 verifyFormat("size_t x = sizeof (x);", SomeSpace); 14992 verifyFormat("auto f (int x) -> decltype (x);", SomeSpace); 14993 verifyFormat("auto f (int x) -> typeof (x);", SomeSpace); 14994 verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace); 14995 verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace); 14996 verifyFormat("int f (T x) noexcept (x.create());", SomeSpace); 14997 verifyFormat("alignas (128) char a[128];", SomeSpace); 14998 verifyFormat("size_t x = alignof (MyType);", SomeSpace); 14999 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", 15000 SomeSpace); 15001 verifyFormat("int f() throw (Deprecated);", SomeSpace); 15002 verifyFormat("typedef void (*cb) (int);", SomeSpace); 15003 verifyFormat("T A::operator()();", SomeSpace); 15004 // FIXME these tests regressed behaviour. 15005 // verifyFormat("X A::operator++ (T);", SomeSpace); 15006 verifyFormat("int x = int (y);", SomeSpace); 15007 verifyFormat("auto lambda = []() { return 0; };", SomeSpace); 15008 15009 FormatStyle SpaceControlStatements = getLLVMStyle(); 15010 SpaceControlStatements.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15011 SpaceControlStatements.SpaceBeforeParensOptions.AfterControlStatements = true; 15012 15013 verifyFormat("while (true)\n" 15014 " continue;", 15015 SpaceControlStatements); 15016 verifyFormat("if (true)\n" 15017 " f();\n" 15018 "else if (true)\n" 15019 " f();", 15020 SpaceControlStatements); 15021 verifyFormat("for (;;) {\n" 15022 " do_something();\n" 15023 "}", 15024 SpaceControlStatements); 15025 verifyFormat("do {\n" 15026 " do_something();\n" 15027 "} while (something());", 15028 SpaceControlStatements); 15029 verifyFormat("switch (x) {\n" 15030 "default:\n" 15031 " break;\n" 15032 "}", 15033 SpaceControlStatements); 15034 15035 FormatStyle SpaceFuncDecl = getLLVMStyle(); 15036 SpaceFuncDecl.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15037 SpaceFuncDecl.SpaceBeforeParensOptions.AfterFunctionDeclarationName = true; 15038 15039 verifyFormat("int f ();", SpaceFuncDecl); 15040 verifyFormat("void f(int a, T b) {}", SpaceFuncDecl); 15041 verifyFormat("A::A() : a(1) {}", SpaceFuncDecl); 15042 verifyFormat("void f () __attribute__((asdf));", SpaceFuncDecl); 15043 verifyFormat("#define A(x) x", SpaceFuncDecl); 15044 verifyFormat("#define A (x) x", SpaceFuncDecl); 15045 verifyFormat("#if defined(x)\n" 15046 "#endif", 15047 SpaceFuncDecl); 15048 verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDecl); 15049 verifyFormat("size_t x = sizeof(x);", SpaceFuncDecl); 15050 verifyFormat("auto f (int x) -> decltype(x);", SpaceFuncDecl); 15051 verifyFormat("auto f (int x) -> typeof(x);", SpaceFuncDecl); 15052 verifyFormat("auto f (int x) -> _Atomic(x);", SpaceFuncDecl); 15053 verifyFormat("auto f (int x) -> __underlying_type(x);", SpaceFuncDecl); 15054 verifyFormat("int f (T x) noexcept(x.create());", SpaceFuncDecl); 15055 verifyFormat("alignas(128) char a[128];", SpaceFuncDecl); 15056 verifyFormat("size_t x = alignof(MyType);", SpaceFuncDecl); 15057 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", 15058 SpaceFuncDecl); 15059 verifyFormat("int f () throw(Deprecated);", SpaceFuncDecl); 15060 verifyFormat("typedef void (*cb)(int);", SpaceFuncDecl); 15061 // FIXME these tests regressed behaviour. 15062 // verifyFormat("T A::operator() ();", SpaceFuncDecl); 15063 // verifyFormat("X A::operator++ (T);", SpaceFuncDecl); 15064 verifyFormat("T A::operator()() {}", SpaceFuncDecl); 15065 verifyFormat("auto lambda = []() { return 0; };", SpaceFuncDecl); 15066 verifyFormat("int x = int(y);", SpaceFuncDecl); 15067 verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}", 15068 SpaceFuncDecl); 15069 15070 FormatStyle SpaceFuncDef = getLLVMStyle(); 15071 SpaceFuncDef.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15072 SpaceFuncDef.SpaceBeforeParensOptions.AfterFunctionDefinitionName = true; 15073 15074 verifyFormat("int f();", SpaceFuncDef); 15075 verifyFormat("void f (int a, T b) {}", SpaceFuncDef); 15076 verifyFormat("A::A() : a(1) {}", SpaceFuncDef); 15077 verifyFormat("void f() __attribute__((asdf));", SpaceFuncDef); 15078 verifyFormat("#define A(x) x", SpaceFuncDef); 15079 verifyFormat("#define A (x) x", SpaceFuncDef); 15080 verifyFormat("#if defined(x)\n" 15081 "#endif", 15082 SpaceFuncDef); 15083 verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDef); 15084 verifyFormat("size_t x = sizeof(x);", SpaceFuncDef); 15085 verifyFormat("auto f(int x) -> decltype(x);", SpaceFuncDef); 15086 verifyFormat("auto f(int x) -> typeof(x);", SpaceFuncDef); 15087 verifyFormat("auto f(int x) -> _Atomic(x);", SpaceFuncDef); 15088 verifyFormat("auto f(int x) -> __underlying_type(x);", SpaceFuncDef); 15089 verifyFormat("int f(T x) noexcept(x.create());", SpaceFuncDef); 15090 verifyFormat("alignas(128) char a[128];", SpaceFuncDef); 15091 verifyFormat("size_t x = alignof(MyType);", SpaceFuncDef); 15092 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", 15093 SpaceFuncDef); 15094 verifyFormat("int f() throw(Deprecated);", SpaceFuncDef); 15095 verifyFormat("typedef void (*cb)(int);", SpaceFuncDef); 15096 verifyFormat("T A::operator()();", SpaceFuncDef); 15097 verifyFormat("X A::operator++(T);", SpaceFuncDef); 15098 // verifyFormat("T A::operator() () {}", SpaceFuncDef); 15099 verifyFormat("auto lambda = [] () { return 0; };", SpaceFuncDef); 15100 verifyFormat("int x = int(y);", SpaceFuncDef); 15101 verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}", 15102 SpaceFuncDef); 15103 15104 FormatStyle SpaceIfMacros = getLLVMStyle(); 15105 SpaceIfMacros.IfMacros.clear(); 15106 SpaceIfMacros.IfMacros.push_back("MYIF"); 15107 SpaceIfMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15108 SpaceIfMacros.SpaceBeforeParensOptions.AfterIfMacros = true; 15109 verifyFormat("MYIF (a)\n return;", SpaceIfMacros); 15110 verifyFormat("MYIF (a)\n return;\nelse MYIF (b)\n return;", SpaceIfMacros); 15111 verifyFormat("MYIF (a)\n return;\nelse\n return;", SpaceIfMacros); 15112 15113 FormatStyle SpaceForeachMacros = getLLVMStyle(); 15114 EXPECT_EQ(SpaceForeachMacros.AllowShortBlocksOnASingleLine, 15115 FormatStyle::SBS_Never); 15116 EXPECT_EQ(SpaceForeachMacros.AllowShortLoopsOnASingleLine, false); 15117 SpaceForeachMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15118 SpaceForeachMacros.SpaceBeforeParensOptions.AfterForeachMacros = true; 15119 verifyFormat("for (;;) {\n" 15120 "}", 15121 SpaceForeachMacros); 15122 verifyFormat("foreach (Item *item, itemlist) {\n" 15123 "}", 15124 SpaceForeachMacros); 15125 verifyFormat("Q_FOREACH (Item *item, itemlist) {\n" 15126 "}", 15127 SpaceForeachMacros); 15128 verifyFormat("BOOST_FOREACH (Item *item, itemlist) {\n" 15129 "}", 15130 SpaceForeachMacros); 15131 verifyFormat("UNKNOWN_FOREACH(Item *item, itemlist) {}", SpaceForeachMacros); 15132 15133 FormatStyle SomeSpace2 = getLLVMStyle(); 15134 SomeSpace2.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15135 SomeSpace2.SpaceBeforeParensOptions.BeforeNonEmptyParentheses = true; 15136 verifyFormat("[]() -> float {}", SomeSpace2); 15137 verifyFormat("[] (auto foo) {}", SomeSpace2); 15138 verifyFormat("[foo]() -> int {}", SomeSpace2); 15139 verifyFormat("int f();", SomeSpace2); 15140 verifyFormat("void f (int a, T b) {\n" 15141 " while (true)\n" 15142 " continue;\n" 15143 "}", 15144 SomeSpace2); 15145 verifyFormat("if (true)\n" 15146 " f();\n" 15147 "else if (true)\n" 15148 " f();", 15149 SomeSpace2); 15150 verifyFormat("do {\n" 15151 " do_something();\n" 15152 "} while (something());", 15153 SomeSpace2); 15154 verifyFormat("switch (x) {\n" 15155 "default:\n" 15156 " break;\n" 15157 "}", 15158 SomeSpace2); 15159 verifyFormat("A::A() : a (1) {}", SomeSpace2); 15160 verifyFormat("void f() __attribute__ ((asdf));", SomeSpace2); 15161 verifyFormat("*(&a + 1);\n" 15162 "&((&a)[1]);\n" 15163 "a[(b + c) * d];\n" 15164 "(((a + 1) * 2) + 3) * 4;", 15165 SomeSpace2); 15166 verifyFormat("#define A(x) x", SomeSpace2); 15167 verifyFormat("#define A (x) x", SomeSpace2); 15168 verifyFormat("#if defined(x)\n" 15169 "#endif", 15170 SomeSpace2); 15171 verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace2); 15172 verifyFormat("size_t x = sizeof (x);", SomeSpace2); 15173 verifyFormat("auto f (int x) -> decltype (x);", SomeSpace2); 15174 verifyFormat("auto f (int x) -> typeof (x);", SomeSpace2); 15175 verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace2); 15176 verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace2); 15177 verifyFormat("int f (T x) noexcept (x.create());", SomeSpace2); 15178 verifyFormat("alignas (128) char a[128];", SomeSpace2); 15179 verifyFormat("size_t x = alignof (MyType);", SomeSpace2); 15180 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", 15181 SomeSpace2); 15182 verifyFormat("int f() throw (Deprecated);", SomeSpace2); 15183 verifyFormat("typedef void (*cb) (int);", SomeSpace2); 15184 verifyFormat("T A::operator()();", SomeSpace2); 15185 // verifyFormat("X A::operator++ (T);", SomeSpace2); 15186 verifyFormat("int x = int (y);", SomeSpace2); 15187 verifyFormat("auto lambda = []() { return 0; };", SomeSpace2); 15188 15189 FormatStyle SpaceAfterOverloadedOperator = getLLVMStyle(); 15190 SpaceAfterOverloadedOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15191 SpaceAfterOverloadedOperator.SpaceBeforeParensOptions 15192 .AfterOverloadedOperator = true; 15193 15194 verifyFormat("auto operator++ () -> int;", SpaceAfterOverloadedOperator); 15195 verifyFormat("X A::operator++ ();", SpaceAfterOverloadedOperator); 15196 verifyFormat("some_object.operator++ ();", SpaceAfterOverloadedOperator); 15197 verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator); 15198 15199 SpaceAfterOverloadedOperator.SpaceBeforeParensOptions 15200 .AfterOverloadedOperator = false; 15201 15202 verifyFormat("auto operator++() -> int;", SpaceAfterOverloadedOperator); 15203 verifyFormat("X A::operator++();", SpaceAfterOverloadedOperator); 15204 verifyFormat("some_object.operator++();", SpaceAfterOverloadedOperator); 15205 verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator); 15206 15207 auto SpaceAfterRequires = getLLVMStyle(); 15208 SpaceAfterRequires.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15209 EXPECT_FALSE( 15210 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause); 15211 EXPECT_FALSE( 15212 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression); 15213 verifyFormat("void f(auto x)\n" 15214 " requires requires(int i) { x + i; }\n" 15215 "{}", 15216 SpaceAfterRequires); 15217 verifyFormat("void f(auto x)\n" 15218 " requires(requires(int i) { x + i; })\n" 15219 "{}", 15220 SpaceAfterRequires); 15221 verifyFormat("if (requires(int i) { x + i; })\n" 15222 " return;", 15223 SpaceAfterRequires); 15224 verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires); 15225 verifyFormat("template <typename T>\n" 15226 " requires(Foo<T>)\n" 15227 "class Bar;", 15228 SpaceAfterRequires); 15229 15230 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true; 15231 verifyFormat("void f(auto x)\n" 15232 " requires requires(int i) { x + i; }\n" 15233 "{}", 15234 SpaceAfterRequires); 15235 verifyFormat("void f(auto x)\n" 15236 " requires (requires(int i) { x + i; })\n" 15237 "{}", 15238 SpaceAfterRequires); 15239 verifyFormat("if (requires(int i) { x + i; })\n" 15240 " return;", 15241 SpaceAfterRequires); 15242 verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires); 15243 verifyFormat("template <typename T>\n" 15244 " requires (Foo<T>)\n" 15245 "class Bar;", 15246 SpaceAfterRequires); 15247 15248 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = false; 15249 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression = true; 15250 verifyFormat("void f(auto x)\n" 15251 " requires requires (int i) { x + i; }\n" 15252 "{}", 15253 SpaceAfterRequires); 15254 verifyFormat("void f(auto x)\n" 15255 " requires(requires (int i) { x + i; })\n" 15256 "{}", 15257 SpaceAfterRequires); 15258 verifyFormat("if (requires (int i) { x + i; })\n" 15259 " return;", 15260 SpaceAfterRequires); 15261 verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires); 15262 verifyFormat("template <typename T>\n" 15263 " requires(Foo<T>)\n" 15264 "class Bar;", 15265 SpaceAfterRequires); 15266 15267 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true; 15268 verifyFormat("void f(auto x)\n" 15269 " requires requires (int i) { x + i; }\n" 15270 "{}", 15271 SpaceAfterRequires); 15272 verifyFormat("void f(auto x)\n" 15273 " requires (requires (int i) { x + i; })\n" 15274 "{}", 15275 SpaceAfterRequires); 15276 verifyFormat("if (requires (int i) { x + i; })\n" 15277 " return;", 15278 SpaceAfterRequires); 15279 verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires); 15280 verifyFormat("template <typename T>\n" 15281 " requires (Foo<T>)\n" 15282 "class Bar;", 15283 SpaceAfterRequires); 15284 } 15285 15286 TEST_F(FormatTest, SpaceAfterLogicalNot) { 15287 FormatStyle Spaces = getLLVMStyle(); 15288 Spaces.SpaceAfterLogicalNot = true; 15289 15290 verifyFormat("bool x = ! y", Spaces); 15291 verifyFormat("if (! isFailure())", Spaces); 15292 verifyFormat("if (! (a && b))", Spaces); 15293 verifyFormat("\"Error!\"", Spaces); 15294 verifyFormat("! ! x", Spaces); 15295 } 15296 15297 TEST_F(FormatTest, ConfigurableSpacesInParentheses) { 15298 FormatStyle Spaces = getLLVMStyle(); 15299 15300 Spaces.SpacesInParentheses = true; 15301 verifyFormat("do_something( ::globalVar );", Spaces); 15302 verifyFormat("call( x, y, z );", Spaces); 15303 verifyFormat("call();", Spaces); 15304 verifyFormat("std::function<void( int, int )> callback;", Spaces); 15305 verifyFormat("void inFunction() { std::function<void( int, int )> fct; }", 15306 Spaces); 15307 verifyFormat("while ( (bool)1 )\n" 15308 " continue;", 15309 Spaces); 15310 verifyFormat("for ( ;; )\n" 15311 " continue;", 15312 Spaces); 15313 verifyFormat("if ( true )\n" 15314 " f();\n" 15315 "else if ( true )\n" 15316 " f();", 15317 Spaces); 15318 verifyFormat("do {\n" 15319 " do_something( (int)i );\n" 15320 "} while ( something() );", 15321 Spaces); 15322 verifyFormat("switch ( x ) {\n" 15323 "default:\n" 15324 " break;\n" 15325 "}", 15326 Spaces); 15327 15328 Spaces.SpacesInParentheses = false; 15329 Spaces.SpacesInCStyleCastParentheses = true; 15330 verifyFormat("Type *A = ( Type * )P;", Spaces); 15331 verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces); 15332 verifyFormat("x = ( int32 )y;", Spaces); 15333 verifyFormat("int a = ( int )(2.0f);", Spaces); 15334 verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces); 15335 verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces); 15336 verifyFormat("#define x (( int )-1)", Spaces); 15337 15338 // Run the first set of tests again with: 15339 Spaces.SpacesInParentheses = false; 15340 Spaces.SpaceInEmptyParentheses = true; 15341 Spaces.SpacesInCStyleCastParentheses = true; 15342 verifyFormat("call(x, y, z);", Spaces); 15343 verifyFormat("call( );", Spaces); 15344 verifyFormat("std::function<void(int, int)> callback;", Spaces); 15345 verifyFormat("while (( bool )1)\n" 15346 " continue;", 15347 Spaces); 15348 verifyFormat("for (;;)\n" 15349 " continue;", 15350 Spaces); 15351 verifyFormat("if (true)\n" 15352 " f( );\n" 15353 "else if (true)\n" 15354 " f( );", 15355 Spaces); 15356 verifyFormat("do {\n" 15357 " do_something(( int )i);\n" 15358 "} while (something( ));", 15359 Spaces); 15360 verifyFormat("switch (x) {\n" 15361 "default:\n" 15362 " break;\n" 15363 "}", 15364 Spaces); 15365 15366 // Run the first set of tests again with: 15367 Spaces.SpaceAfterCStyleCast = true; 15368 verifyFormat("call(x, y, z);", Spaces); 15369 verifyFormat("call( );", Spaces); 15370 verifyFormat("std::function<void(int, int)> callback;", Spaces); 15371 verifyFormat("while (( bool ) 1)\n" 15372 " continue;", 15373 Spaces); 15374 verifyFormat("for (;;)\n" 15375 " continue;", 15376 Spaces); 15377 verifyFormat("if (true)\n" 15378 " f( );\n" 15379 "else if (true)\n" 15380 " f( );", 15381 Spaces); 15382 verifyFormat("do {\n" 15383 " do_something(( int ) i);\n" 15384 "} while (something( ));", 15385 Spaces); 15386 verifyFormat("switch (x) {\n" 15387 "default:\n" 15388 " break;\n" 15389 "}", 15390 Spaces); 15391 verifyFormat("#define CONF_BOOL(x) ( bool * ) ( void * ) (x)", Spaces); 15392 verifyFormat("#define CONF_BOOL(x) ( bool * ) (x)", Spaces); 15393 verifyFormat("#define CONF_BOOL(x) ( bool ) (x)", Spaces); 15394 verifyFormat("bool *y = ( bool * ) ( void * ) (x);", Spaces); 15395 verifyFormat("bool *y = ( bool * ) (x);", Spaces); 15396 15397 // Run subset of tests again with: 15398 Spaces.SpacesInCStyleCastParentheses = false; 15399 Spaces.SpaceAfterCStyleCast = true; 15400 verifyFormat("while ((bool) 1)\n" 15401 " continue;", 15402 Spaces); 15403 verifyFormat("do {\n" 15404 " do_something((int) i);\n" 15405 "} while (something( ));", 15406 Spaces); 15407 15408 verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces); 15409 verifyFormat("size_t idx = (size_t) a;", Spaces); 15410 verifyFormat("size_t idx = (size_t) (a - 1);", Spaces); 15411 verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces); 15412 verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces); 15413 verifyFormat("size_t idx = (*foo)(a - 1);", Spaces); 15414 verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces); 15415 verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (x)", Spaces); 15416 verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (int) (x)", Spaces); 15417 verifyFormat("bool *y = (bool *) (void *) (x);", Spaces); 15418 verifyFormat("bool *y = (bool *) (void *) (int) (x);", Spaces); 15419 verifyFormat("bool *y = (bool *) (void *) (int) foo(x);", Spaces); 15420 Spaces.ColumnLimit = 80; 15421 Spaces.IndentWidth = 4; 15422 Spaces.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 15423 verifyFormat("void foo( ) {\n" 15424 " size_t foo = (*(function))(\n" 15425 " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, " 15426 "BarrrrrrrrrrrrLong,\n" 15427 " FoooooooooLooooong);\n" 15428 "}", 15429 Spaces); 15430 Spaces.SpaceAfterCStyleCast = false; 15431 verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces); 15432 verifyFormat("size_t idx = (size_t)a;", Spaces); 15433 verifyFormat("size_t idx = (size_t)(a - 1);", Spaces); 15434 verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces); 15435 verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces); 15436 verifyFormat("size_t idx = (*foo)(a - 1);", Spaces); 15437 verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces); 15438 15439 verifyFormat("void foo( ) {\n" 15440 " size_t foo = (*(function))(\n" 15441 " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, " 15442 "BarrrrrrrrrrrrLong,\n" 15443 " FoooooooooLooooong);\n" 15444 "}", 15445 Spaces); 15446 } 15447 15448 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) { 15449 verifyFormat("int a[5];"); 15450 verifyFormat("a[3] += 42;"); 15451 15452 FormatStyle Spaces = getLLVMStyle(); 15453 Spaces.SpacesInSquareBrackets = true; 15454 // Not lambdas. 15455 verifyFormat("int a[ 5 ];", Spaces); 15456 verifyFormat("a[ 3 ] += 42;", Spaces); 15457 verifyFormat("constexpr char hello[]{\"hello\"};", Spaces); 15458 verifyFormat("double &operator[](int i) { return 0; }\n" 15459 "int i;", 15460 Spaces); 15461 verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces); 15462 verifyFormat("int i = a[ a ][ a ]->f();", Spaces); 15463 verifyFormat("int i = (*b)[ a ]->f();", Spaces); 15464 // Lambdas. 15465 verifyFormat("int c = []() -> int { return 2; }();\n", Spaces); 15466 verifyFormat("return [ i, args... ] {};", Spaces); 15467 verifyFormat("int foo = [ &bar ]() {};", Spaces); 15468 verifyFormat("int foo = [ = ]() {};", Spaces); 15469 verifyFormat("int foo = [ & ]() {};", Spaces); 15470 verifyFormat("int foo = [ =, &bar ]() {};", Spaces); 15471 verifyFormat("int foo = [ &bar, = ]() {};", Spaces); 15472 } 15473 15474 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) { 15475 FormatStyle NoSpaceStyle = getLLVMStyle(); 15476 verifyFormat("int a[5];", NoSpaceStyle); 15477 verifyFormat("a[3] += 42;", NoSpaceStyle); 15478 15479 verifyFormat("int a[1];", NoSpaceStyle); 15480 verifyFormat("int 1 [a];", NoSpaceStyle); 15481 verifyFormat("int a[1][2];", NoSpaceStyle); 15482 verifyFormat("a[7] = 5;", NoSpaceStyle); 15483 verifyFormat("int a = (f())[23];", NoSpaceStyle); 15484 verifyFormat("f([] {})", NoSpaceStyle); 15485 15486 FormatStyle Space = getLLVMStyle(); 15487 Space.SpaceBeforeSquareBrackets = true; 15488 verifyFormat("int c = []() -> int { return 2; }();\n", Space); 15489 verifyFormat("return [i, args...] {};", Space); 15490 15491 verifyFormat("int a [5];", Space); 15492 verifyFormat("a [3] += 42;", Space); 15493 verifyFormat("constexpr char hello []{\"hello\"};", Space); 15494 verifyFormat("double &operator[](int i) { return 0; }\n" 15495 "int i;", 15496 Space); 15497 verifyFormat("std::unique_ptr<int []> foo() {}", Space); 15498 verifyFormat("int i = a [a][a]->f();", Space); 15499 verifyFormat("int i = (*b) [a]->f();", Space); 15500 15501 verifyFormat("int a [1];", Space); 15502 verifyFormat("int 1 [a];", Space); 15503 verifyFormat("int a [1][2];", Space); 15504 verifyFormat("a [7] = 5;", Space); 15505 verifyFormat("int a = (f()) [23];", Space); 15506 verifyFormat("f([] {})", Space); 15507 } 15508 15509 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) { 15510 verifyFormat("int a = 5;"); 15511 verifyFormat("a += 42;"); 15512 verifyFormat("a or_eq 8;"); 15513 15514 FormatStyle Spaces = getLLVMStyle(); 15515 Spaces.SpaceBeforeAssignmentOperators = false; 15516 verifyFormat("int a= 5;", Spaces); 15517 verifyFormat("a+= 42;", Spaces); 15518 verifyFormat("a or_eq 8;", Spaces); 15519 } 15520 15521 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) { 15522 verifyFormat("class Foo : public Bar {};"); 15523 verifyFormat("Foo::Foo() : foo(1) {}"); 15524 verifyFormat("for (auto a : b) {\n}"); 15525 verifyFormat("int x = a ? b : c;"); 15526 verifyFormat("{\n" 15527 "label0:\n" 15528 " int x = 0;\n" 15529 "}"); 15530 verifyFormat("switch (x) {\n" 15531 "case 1:\n" 15532 "default:\n" 15533 "}"); 15534 verifyFormat("switch (allBraces) {\n" 15535 "case 1: {\n" 15536 " break;\n" 15537 "}\n" 15538 "case 2: {\n" 15539 " [[fallthrough]];\n" 15540 "}\n" 15541 "default: {\n" 15542 " break;\n" 15543 "}\n" 15544 "}"); 15545 15546 FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30); 15547 CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false; 15548 verifyFormat("class Foo : public Bar {};", CtorInitializerStyle); 15549 verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle); 15550 verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle); 15551 verifyFormat("int x = a ? b : c;", CtorInitializerStyle); 15552 verifyFormat("{\n" 15553 "label1:\n" 15554 " int x = 0;\n" 15555 "}", 15556 CtorInitializerStyle); 15557 verifyFormat("switch (x) {\n" 15558 "case 1:\n" 15559 "default:\n" 15560 "}", 15561 CtorInitializerStyle); 15562 verifyFormat("switch (allBraces) {\n" 15563 "case 1: {\n" 15564 " break;\n" 15565 "}\n" 15566 "case 2: {\n" 15567 " [[fallthrough]];\n" 15568 "}\n" 15569 "default: {\n" 15570 " break;\n" 15571 "}\n" 15572 "}", 15573 CtorInitializerStyle); 15574 CtorInitializerStyle.BreakConstructorInitializers = 15575 FormatStyle::BCIS_AfterColon; 15576 verifyFormat("Fooooooooooo::Fooooooooooo():\n" 15577 " aaaaaaaaaaaaaaaa(1),\n" 15578 " bbbbbbbbbbbbbbbb(2) {}", 15579 CtorInitializerStyle); 15580 CtorInitializerStyle.BreakConstructorInitializers = 15581 FormatStyle::BCIS_BeforeComma; 15582 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15583 " : aaaaaaaaaaaaaaaa(1)\n" 15584 " , bbbbbbbbbbbbbbbb(2) {}", 15585 CtorInitializerStyle); 15586 CtorInitializerStyle.BreakConstructorInitializers = 15587 FormatStyle::BCIS_BeforeColon; 15588 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15589 " : aaaaaaaaaaaaaaaa(1),\n" 15590 " bbbbbbbbbbbbbbbb(2) {}", 15591 CtorInitializerStyle); 15592 CtorInitializerStyle.ConstructorInitializerIndentWidth = 0; 15593 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15594 ": aaaaaaaaaaaaaaaa(1),\n" 15595 " bbbbbbbbbbbbbbbb(2) {}", 15596 CtorInitializerStyle); 15597 15598 FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30); 15599 InheritanceStyle.SpaceBeforeInheritanceColon = false; 15600 verifyFormat("class Foo: public Bar {};", InheritanceStyle); 15601 verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle); 15602 verifyFormat("for (auto a : b) {\n}", InheritanceStyle); 15603 verifyFormat("int x = a ? b : c;", InheritanceStyle); 15604 verifyFormat("{\n" 15605 "label2:\n" 15606 " int x = 0;\n" 15607 "}", 15608 InheritanceStyle); 15609 verifyFormat("switch (x) {\n" 15610 "case 1:\n" 15611 "default:\n" 15612 "}", 15613 InheritanceStyle); 15614 verifyFormat("switch (allBraces) {\n" 15615 "case 1: {\n" 15616 " break;\n" 15617 "}\n" 15618 "case 2: {\n" 15619 " [[fallthrough]];\n" 15620 "}\n" 15621 "default: {\n" 15622 " break;\n" 15623 "}\n" 15624 "}", 15625 InheritanceStyle); 15626 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterComma; 15627 verifyFormat("class Foooooooooooooooooooooo\n" 15628 " : public aaaaaaaaaaaaaaaaaa,\n" 15629 " public bbbbbbbbbbbbbbbbbb {\n" 15630 "}", 15631 InheritanceStyle); 15632 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon; 15633 verifyFormat("class Foooooooooooooooooooooo:\n" 15634 " public aaaaaaaaaaaaaaaaaa,\n" 15635 " public bbbbbbbbbbbbbbbbbb {\n" 15636 "}", 15637 InheritanceStyle); 15638 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma; 15639 verifyFormat("class Foooooooooooooooooooooo\n" 15640 " : public aaaaaaaaaaaaaaaaaa\n" 15641 " , public bbbbbbbbbbbbbbbbbb {\n" 15642 "}", 15643 InheritanceStyle); 15644 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 15645 verifyFormat("class Foooooooooooooooooooooo\n" 15646 " : public aaaaaaaaaaaaaaaaaa,\n" 15647 " public bbbbbbbbbbbbbbbbbb {\n" 15648 "}", 15649 InheritanceStyle); 15650 InheritanceStyle.ConstructorInitializerIndentWidth = 0; 15651 verifyFormat("class Foooooooooooooooooooooo\n" 15652 ": public aaaaaaaaaaaaaaaaaa,\n" 15653 " public bbbbbbbbbbbbbbbbbb {}", 15654 InheritanceStyle); 15655 15656 FormatStyle ForLoopStyle = getLLVMStyle(); 15657 ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false; 15658 verifyFormat("class Foo : public Bar {};", ForLoopStyle); 15659 verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle); 15660 verifyFormat("for (auto a: b) {\n}", ForLoopStyle); 15661 verifyFormat("int x = a ? b : c;", ForLoopStyle); 15662 verifyFormat("{\n" 15663 "label2:\n" 15664 " int x = 0;\n" 15665 "}", 15666 ForLoopStyle); 15667 verifyFormat("switch (x) {\n" 15668 "case 1:\n" 15669 "default:\n" 15670 "}", 15671 ForLoopStyle); 15672 verifyFormat("switch (allBraces) {\n" 15673 "case 1: {\n" 15674 " break;\n" 15675 "}\n" 15676 "case 2: {\n" 15677 " [[fallthrough]];\n" 15678 "}\n" 15679 "default: {\n" 15680 " break;\n" 15681 "}\n" 15682 "}", 15683 ForLoopStyle); 15684 15685 FormatStyle CaseStyle = getLLVMStyle(); 15686 CaseStyle.SpaceBeforeCaseColon = true; 15687 verifyFormat("class Foo : public Bar {};", CaseStyle); 15688 verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle); 15689 verifyFormat("for (auto a : b) {\n}", CaseStyle); 15690 verifyFormat("int x = a ? b : c;", CaseStyle); 15691 verifyFormat("switch (x) {\n" 15692 "case 1 :\n" 15693 "default :\n" 15694 "}", 15695 CaseStyle); 15696 verifyFormat("switch (allBraces) {\n" 15697 "case 1 : {\n" 15698 " break;\n" 15699 "}\n" 15700 "case 2 : {\n" 15701 " [[fallthrough]];\n" 15702 "}\n" 15703 "default : {\n" 15704 " break;\n" 15705 "}\n" 15706 "}", 15707 CaseStyle); 15708 15709 FormatStyle NoSpaceStyle = getLLVMStyle(); 15710 EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false); 15711 NoSpaceStyle.SpaceBeforeCtorInitializerColon = false; 15712 NoSpaceStyle.SpaceBeforeInheritanceColon = false; 15713 NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false; 15714 verifyFormat("class Foo: public Bar {};", NoSpaceStyle); 15715 verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle); 15716 verifyFormat("for (auto a: b) {\n}", NoSpaceStyle); 15717 verifyFormat("int x = a ? b : c;", NoSpaceStyle); 15718 verifyFormat("{\n" 15719 "label3:\n" 15720 " int x = 0;\n" 15721 "}", 15722 NoSpaceStyle); 15723 verifyFormat("switch (x) {\n" 15724 "case 1:\n" 15725 "default:\n" 15726 "}", 15727 NoSpaceStyle); 15728 verifyFormat("switch (allBraces) {\n" 15729 "case 1: {\n" 15730 " break;\n" 15731 "}\n" 15732 "case 2: {\n" 15733 " [[fallthrough]];\n" 15734 "}\n" 15735 "default: {\n" 15736 " break;\n" 15737 "}\n" 15738 "}", 15739 NoSpaceStyle); 15740 15741 FormatStyle InvertedSpaceStyle = getLLVMStyle(); 15742 InvertedSpaceStyle.SpaceBeforeCaseColon = true; 15743 InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false; 15744 InvertedSpaceStyle.SpaceBeforeInheritanceColon = false; 15745 InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false; 15746 verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle); 15747 verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle); 15748 verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle); 15749 verifyFormat("int x = a ? b : c;", InvertedSpaceStyle); 15750 verifyFormat("{\n" 15751 "label3:\n" 15752 " int x = 0;\n" 15753 "}", 15754 InvertedSpaceStyle); 15755 verifyFormat("switch (x) {\n" 15756 "case 1 :\n" 15757 "case 2 : {\n" 15758 " break;\n" 15759 "}\n" 15760 "default :\n" 15761 " break;\n" 15762 "}", 15763 InvertedSpaceStyle); 15764 verifyFormat("switch (allBraces) {\n" 15765 "case 1 : {\n" 15766 " break;\n" 15767 "}\n" 15768 "case 2 : {\n" 15769 " [[fallthrough]];\n" 15770 "}\n" 15771 "default : {\n" 15772 " break;\n" 15773 "}\n" 15774 "}", 15775 InvertedSpaceStyle); 15776 } 15777 15778 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) { 15779 FormatStyle Style = getLLVMStyle(); 15780 15781 Style.PointerAlignment = FormatStyle::PAS_Left; 15782 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default; 15783 verifyFormat("void* const* x = NULL;", Style); 15784 15785 #define verifyQualifierSpaces(Code, Pointers, Qualifiers) \ 15786 do { \ 15787 Style.PointerAlignment = FormatStyle::Pointers; \ 15788 Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers; \ 15789 verifyFormat(Code, Style); \ 15790 } while (false) 15791 15792 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default); 15793 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default); 15794 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default); 15795 15796 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before); 15797 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before); 15798 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before); 15799 15800 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After); 15801 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After); 15802 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After); 15803 15804 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both); 15805 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both); 15806 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both); 15807 15808 verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default); 15809 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, 15810 SAPQ_Default); 15811 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15812 SAPQ_Default); 15813 15814 verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before); 15815 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, 15816 SAPQ_Before); 15817 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15818 SAPQ_Before); 15819 15820 verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After); 15821 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After); 15822 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15823 SAPQ_After); 15824 15825 verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both); 15826 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both); 15827 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both); 15828 15829 #undef verifyQualifierSpaces 15830 15831 FormatStyle Spaces = getLLVMStyle(); 15832 Spaces.AttributeMacros.push_back("qualified"); 15833 Spaces.PointerAlignment = FormatStyle::PAS_Right; 15834 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default; 15835 verifyFormat("SomeType *volatile *a = NULL;", Spaces); 15836 verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces); 15837 verifyFormat("std::vector<SomeType *const *> x;", Spaces); 15838 verifyFormat("std::vector<SomeType *qualified *> x;", Spaces); 15839 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15840 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before; 15841 verifyFormat("SomeType * volatile *a = NULL;", Spaces); 15842 verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces); 15843 verifyFormat("std::vector<SomeType * const *> x;", Spaces); 15844 verifyFormat("std::vector<SomeType * qualified *> x;", Spaces); 15845 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15846 15847 // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left. 15848 Spaces.PointerAlignment = FormatStyle::PAS_Left; 15849 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before; 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 // However, setting it to SAPQ_After should add spaces after __attribute, etc. 15856 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After; 15857 verifyFormat("SomeType* volatile * a = NULL;", Spaces); 15858 verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces); 15859 verifyFormat("std::vector<SomeType* const *> x;", Spaces); 15860 verifyFormat("std::vector<SomeType* qualified *> x;", Spaces); 15861 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15862 15863 // PAS_Middle should not have any noticeable changes even for SAPQ_Both 15864 Spaces.PointerAlignment = FormatStyle::PAS_Middle; 15865 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After; 15866 verifyFormat("SomeType * volatile * a = NULL;", Spaces); 15867 verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces); 15868 verifyFormat("std::vector<SomeType * const *> x;", Spaces); 15869 verifyFormat("std::vector<SomeType * qualified *> x;", Spaces); 15870 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15871 } 15872 15873 TEST_F(FormatTest, AlignConsecutiveMacros) { 15874 FormatStyle Style = getLLVMStyle(); 15875 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 15876 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 15877 Style.AlignConsecutiveMacros = FormatStyle::ACS_None; 15878 15879 verifyFormat("#define a 3\n" 15880 "#define bbbb 4\n" 15881 "#define ccc (5)", 15882 Style); 15883 15884 verifyFormat("#define f(x) (x * x)\n" 15885 "#define fff(x, y, z) (x * y + z)\n" 15886 "#define ffff(x, y) (x - y)", 15887 Style); 15888 15889 verifyFormat("#define foo(x, y) (x + y)\n" 15890 "#define bar (5, 6)(2 + 2)", 15891 Style); 15892 15893 verifyFormat("#define a 3\n" 15894 "#define bbbb 4\n" 15895 "#define ccc (5)\n" 15896 "#define f(x) (x * x)\n" 15897 "#define fff(x, y, z) (x * y + z)\n" 15898 "#define ffff(x, y) (x - y)", 15899 Style); 15900 15901 Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 15902 verifyFormat("#define a 3\n" 15903 "#define bbbb 4\n" 15904 "#define ccc (5)", 15905 Style); 15906 15907 verifyFormat("#define f(x) (x * x)\n" 15908 "#define fff(x, y, z) (x * y + z)\n" 15909 "#define ffff(x, y) (x - y)", 15910 Style); 15911 15912 verifyFormat("#define foo(x, y) (x + y)\n" 15913 "#define bar (5, 6)(2 + 2)", 15914 Style); 15915 15916 verifyFormat("#define a 3\n" 15917 "#define bbbb 4\n" 15918 "#define ccc (5)\n" 15919 "#define f(x) (x * x)\n" 15920 "#define fff(x, y, z) (x * y + z)\n" 15921 "#define ffff(x, y) (x - y)", 15922 Style); 15923 15924 verifyFormat("#define a 5\n" 15925 "#define foo(x, y) (x + y)\n" 15926 "#define CCC (6)\n" 15927 "auto lambda = []() {\n" 15928 " auto ii = 0;\n" 15929 " float j = 0;\n" 15930 " return 0;\n" 15931 "};\n" 15932 "int i = 0;\n" 15933 "float i2 = 0;\n" 15934 "auto v = type{\n" 15935 " i = 1, //\n" 15936 " (i = 2), //\n" 15937 " i = 3 //\n" 15938 "};", 15939 Style); 15940 15941 Style.AlignConsecutiveMacros = FormatStyle::ACS_None; 15942 Style.ColumnLimit = 20; 15943 15944 verifyFormat("#define a \\\n" 15945 " \"aabbbbbbbbbbbb\"\n" 15946 "#define D \\\n" 15947 " \"aabbbbbbbbbbbb\" \\\n" 15948 " \"ccddeeeeeeeee\"\n" 15949 "#define B \\\n" 15950 " \"QQQQQQQQQQQQQ\" \\\n" 15951 " \"FFFFFFFFFFFFF\" \\\n" 15952 " \"LLLLLLLL\"\n", 15953 Style); 15954 15955 Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 15956 verifyFormat("#define a \\\n" 15957 " \"aabbbbbbbbbbbb\"\n" 15958 "#define D \\\n" 15959 " \"aabbbbbbbbbbbb\" \\\n" 15960 " \"ccddeeeeeeeee\"\n" 15961 "#define B \\\n" 15962 " \"QQQQQQQQQQQQQ\" \\\n" 15963 " \"FFFFFFFFFFFFF\" \\\n" 15964 " \"LLLLLLLL\"\n", 15965 Style); 15966 15967 // Test across comments 15968 Style.MaxEmptyLinesToKeep = 10; 15969 Style.ReflowComments = false; 15970 Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossComments; 15971 EXPECT_EQ("#define a 3\n" 15972 "// line comment\n" 15973 "#define bbbb 4\n" 15974 "#define ccc (5)", 15975 format("#define a 3\n" 15976 "// line comment\n" 15977 "#define bbbb 4\n" 15978 "#define ccc (5)", 15979 Style)); 15980 15981 EXPECT_EQ("#define a 3\n" 15982 "/* block comment */\n" 15983 "#define bbbb 4\n" 15984 "#define ccc (5)", 15985 format("#define a 3\n" 15986 "/* block comment */\n" 15987 "#define bbbb 4\n" 15988 "#define ccc (5)", 15989 Style)); 15990 15991 EXPECT_EQ("#define a 3\n" 15992 "/* multi-line *\n" 15993 " * block comment */\n" 15994 "#define bbbb 4\n" 15995 "#define ccc (5)", 15996 format("#define a 3\n" 15997 "/* multi-line *\n" 15998 " * block comment */\n" 15999 "#define bbbb 4\n" 16000 "#define ccc (5)", 16001 Style)); 16002 16003 EXPECT_EQ("#define a 3\n" 16004 "// multi-line line comment\n" 16005 "//\n" 16006 "#define bbbb 4\n" 16007 "#define ccc (5)", 16008 format("#define a 3\n" 16009 "// multi-line line comment\n" 16010 "//\n" 16011 "#define bbbb 4\n" 16012 "#define ccc (5)", 16013 Style)); 16014 16015 EXPECT_EQ("#define a 3\n" 16016 "// empty lines still break.\n" 16017 "\n" 16018 "#define bbbb 4\n" 16019 "#define ccc (5)", 16020 format("#define a 3\n" 16021 "// empty lines still break.\n" 16022 "\n" 16023 "#define bbbb 4\n" 16024 "#define ccc (5)", 16025 Style)); 16026 16027 // Test across empty lines 16028 Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLines; 16029 EXPECT_EQ("#define a 3\n" 16030 "\n" 16031 "#define bbbb 4\n" 16032 "#define ccc (5)", 16033 format("#define a 3\n" 16034 "\n" 16035 "#define bbbb 4\n" 16036 "#define ccc (5)", 16037 Style)); 16038 16039 EXPECT_EQ("#define a 3\n" 16040 "\n" 16041 "\n" 16042 "\n" 16043 "#define bbbb 4\n" 16044 "#define ccc (5)", 16045 format("#define a 3\n" 16046 "\n" 16047 "\n" 16048 "\n" 16049 "#define bbbb 4\n" 16050 "#define ccc (5)", 16051 Style)); 16052 16053 EXPECT_EQ("#define a 3\n" 16054 "// comments should break alignment\n" 16055 "//\n" 16056 "#define bbbb 4\n" 16057 "#define ccc (5)", 16058 format("#define a 3\n" 16059 "// comments should break alignment\n" 16060 "//\n" 16061 "#define bbbb 4\n" 16062 "#define ccc (5)", 16063 Style)); 16064 16065 // Test across empty lines and comments 16066 Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLinesAndComments; 16067 verifyFormat("#define a 3\n" 16068 "\n" 16069 "// line comment\n" 16070 "#define bbbb 4\n" 16071 "#define ccc (5)", 16072 Style); 16073 16074 EXPECT_EQ("#define a 3\n" 16075 "\n" 16076 "\n" 16077 "/* multi-line *\n" 16078 " * block comment */\n" 16079 "\n" 16080 "\n" 16081 "#define bbbb 4\n" 16082 "#define ccc (5)", 16083 format("#define a 3\n" 16084 "\n" 16085 "\n" 16086 "/* multi-line *\n" 16087 " * block comment */\n" 16088 "\n" 16089 "\n" 16090 "#define bbbb 4\n" 16091 "#define ccc (5)", 16092 Style)); 16093 16094 EXPECT_EQ("#define a 3\n" 16095 "\n" 16096 "\n" 16097 "/* multi-line *\n" 16098 " * block comment */\n" 16099 "\n" 16100 "\n" 16101 "#define bbbb 4\n" 16102 "#define ccc (5)", 16103 format("#define a 3\n" 16104 "\n" 16105 "\n" 16106 "/* multi-line *\n" 16107 " * block comment */\n" 16108 "\n" 16109 "\n" 16110 "#define bbbb 4\n" 16111 "#define ccc (5)", 16112 Style)); 16113 } 16114 16115 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) { 16116 FormatStyle Alignment = getLLVMStyle(); 16117 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 16118 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossEmptyLines; 16119 16120 Alignment.MaxEmptyLinesToKeep = 10; 16121 /* Test alignment across empty lines */ 16122 EXPECT_EQ("int a = 5;\n" 16123 "\n" 16124 "int oneTwoThree = 123;", 16125 format("int a = 5;\n" 16126 "\n" 16127 "int oneTwoThree= 123;", 16128 Alignment)); 16129 EXPECT_EQ("int a = 5;\n" 16130 "int one = 1;\n" 16131 "\n" 16132 "int oneTwoThree = 123;", 16133 format("int a = 5;\n" 16134 "int one = 1;\n" 16135 "\n" 16136 "int oneTwoThree = 123;", 16137 Alignment)); 16138 EXPECT_EQ("int a = 5;\n" 16139 "int one = 1;\n" 16140 "\n" 16141 "int oneTwoThree = 123;\n" 16142 "int oneTwo = 12;", 16143 format("int a = 5;\n" 16144 "int one = 1;\n" 16145 "\n" 16146 "int oneTwoThree = 123;\n" 16147 "int oneTwo = 12;", 16148 Alignment)); 16149 16150 /* Test across comments */ 16151 EXPECT_EQ("int a = 5;\n" 16152 "/* block comment */\n" 16153 "int oneTwoThree = 123;", 16154 format("int a = 5;\n" 16155 "/* block comment */\n" 16156 "int oneTwoThree=123;", 16157 Alignment)); 16158 16159 EXPECT_EQ("int a = 5;\n" 16160 "// line comment\n" 16161 "int oneTwoThree = 123;", 16162 format("int a = 5;\n" 16163 "// line comment\n" 16164 "int oneTwoThree=123;", 16165 Alignment)); 16166 16167 /* Test across comments and newlines */ 16168 EXPECT_EQ("int a = 5;\n" 16169 "\n" 16170 "/* block comment */\n" 16171 "int oneTwoThree = 123;", 16172 format("int a = 5;\n" 16173 "\n" 16174 "/* block comment */\n" 16175 "int oneTwoThree=123;", 16176 Alignment)); 16177 16178 EXPECT_EQ("int a = 5;\n" 16179 "\n" 16180 "// line comment\n" 16181 "int oneTwoThree = 123;", 16182 format("int a = 5;\n" 16183 "\n" 16184 "// line comment\n" 16185 "int oneTwoThree=123;", 16186 Alignment)); 16187 } 16188 16189 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) { 16190 FormatStyle Alignment = getLLVMStyle(); 16191 Alignment.AlignConsecutiveDeclarations = 16192 FormatStyle::ACS_AcrossEmptyLinesAndComments; 16193 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 16194 16195 Alignment.MaxEmptyLinesToKeep = 10; 16196 /* Test alignment across empty lines */ 16197 EXPECT_EQ("int a = 5;\n" 16198 "\n" 16199 "float const oneTwoThree = 123;", 16200 format("int a = 5;\n" 16201 "\n" 16202 "float const oneTwoThree = 123;", 16203 Alignment)); 16204 EXPECT_EQ("int a = 5;\n" 16205 "float const one = 1;\n" 16206 "\n" 16207 "int oneTwoThree = 123;", 16208 format("int a = 5;\n" 16209 "float const one = 1;\n" 16210 "\n" 16211 "int oneTwoThree = 123;", 16212 Alignment)); 16213 16214 /* Test across comments */ 16215 EXPECT_EQ("float const a = 5;\n" 16216 "/* block comment */\n" 16217 "int oneTwoThree = 123;", 16218 format("float const a = 5;\n" 16219 "/* block comment */\n" 16220 "int oneTwoThree=123;", 16221 Alignment)); 16222 16223 EXPECT_EQ("float const a = 5;\n" 16224 "// line comment\n" 16225 "int oneTwoThree = 123;", 16226 format("float const a = 5;\n" 16227 "// line comment\n" 16228 "int oneTwoThree=123;", 16229 Alignment)); 16230 16231 /* Test across comments and newlines */ 16232 EXPECT_EQ("float const a = 5;\n" 16233 "\n" 16234 "/* block comment */\n" 16235 "int oneTwoThree = 123;", 16236 format("float const a = 5;\n" 16237 "\n" 16238 "/* block comment */\n" 16239 "int oneTwoThree=123;", 16240 Alignment)); 16241 16242 EXPECT_EQ("float const a = 5;\n" 16243 "\n" 16244 "// line comment\n" 16245 "int oneTwoThree = 123;", 16246 format("float const a = 5;\n" 16247 "\n" 16248 "// line comment\n" 16249 "int oneTwoThree=123;", 16250 Alignment)); 16251 } 16252 16253 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) { 16254 FormatStyle Alignment = getLLVMStyle(); 16255 Alignment.AlignConsecutiveBitFields = 16256 FormatStyle::ACS_AcrossEmptyLinesAndComments; 16257 16258 Alignment.MaxEmptyLinesToKeep = 10; 16259 /* Test alignment across empty lines */ 16260 EXPECT_EQ("int a : 5;\n" 16261 "\n" 16262 "int longbitfield : 6;", 16263 format("int a : 5;\n" 16264 "\n" 16265 "int longbitfield : 6;", 16266 Alignment)); 16267 EXPECT_EQ("int a : 5;\n" 16268 "int one : 1;\n" 16269 "\n" 16270 "int longbitfield : 6;", 16271 format("int a : 5;\n" 16272 "int one : 1;\n" 16273 "\n" 16274 "int longbitfield : 6;", 16275 Alignment)); 16276 16277 /* Test across comments */ 16278 EXPECT_EQ("int a : 5;\n" 16279 "/* block comment */\n" 16280 "int longbitfield : 6;", 16281 format("int a : 5;\n" 16282 "/* block comment */\n" 16283 "int longbitfield : 6;", 16284 Alignment)); 16285 EXPECT_EQ("int a : 5;\n" 16286 "int one : 1;\n" 16287 "// line comment\n" 16288 "int longbitfield : 6;", 16289 format("int a : 5;\n" 16290 "int one : 1;\n" 16291 "// line comment\n" 16292 "int longbitfield : 6;", 16293 Alignment)); 16294 16295 /* Test across comments and newlines */ 16296 EXPECT_EQ("int a : 5;\n" 16297 "/* block comment */\n" 16298 "\n" 16299 "int longbitfield : 6;", 16300 format("int a : 5;\n" 16301 "/* block comment */\n" 16302 "\n" 16303 "int longbitfield : 6;", 16304 Alignment)); 16305 EXPECT_EQ("int a : 5;\n" 16306 "int one : 1;\n" 16307 "\n" 16308 "// line comment\n" 16309 "\n" 16310 "int longbitfield : 6;", 16311 format("int a : 5;\n" 16312 "int one : 1;\n" 16313 "\n" 16314 "// line comment \n" 16315 "\n" 16316 "int longbitfield : 6;", 16317 Alignment)); 16318 } 16319 16320 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) { 16321 FormatStyle Alignment = getLLVMStyle(); 16322 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 16323 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossComments; 16324 16325 Alignment.MaxEmptyLinesToKeep = 10; 16326 /* Test alignment across empty lines */ 16327 EXPECT_EQ("int a = 5;\n" 16328 "\n" 16329 "int oneTwoThree = 123;", 16330 format("int a = 5;\n" 16331 "\n" 16332 "int oneTwoThree= 123;", 16333 Alignment)); 16334 EXPECT_EQ("int a = 5;\n" 16335 "int one = 1;\n" 16336 "\n" 16337 "int oneTwoThree = 123;", 16338 format("int a = 5;\n" 16339 "int one = 1;\n" 16340 "\n" 16341 "int oneTwoThree = 123;", 16342 Alignment)); 16343 16344 /* Test across comments */ 16345 EXPECT_EQ("int a = 5;\n" 16346 "/* block comment */\n" 16347 "int oneTwoThree = 123;", 16348 format("int a = 5;\n" 16349 "/* block comment */\n" 16350 "int oneTwoThree=123;", 16351 Alignment)); 16352 16353 EXPECT_EQ("int a = 5;\n" 16354 "// line comment\n" 16355 "int oneTwoThree = 123;", 16356 format("int a = 5;\n" 16357 "// line comment\n" 16358 "int oneTwoThree=123;", 16359 Alignment)); 16360 16361 EXPECT_EQ("int a = 5;\n" 16362 "/*\n" 16363 " * multi-line block comment\n" 16364 " */\n" 16365 "int oneTwoThree = 123;", 16366 format("int a = 5;\n" 16367 "/*\n" 16368 " * multi-line block comment\n" 16369 " */\n" 16370 "int oneTwoThree=123;", 16371 Alignment)); 16372 16373 EXPECT_EQ("int a = 5;\n" 16374 "//\n" 16375 "// multi-line line comment\n" 16376 "//\n" 16377 "int oneTwoThree = 123;", 16378 format("int a = 5;\n" 16379 "//\n" 16380 "// multi-line line comment\n" 16381 "//\n" 16382 "int oneTwoThree=123;", 16383 Alignment)); 16384 16385 /* Test across comments and newlines */ 16386 EXPECT_EQ("int a = 5;\n" 16387 "\n" 16388 "/* block comment */\n" 16389 "int oneTwoThree = 123;", 16390 format("int a = 5;\n" 16391 "\n" 16392 "/* block comment */\n" 16393 "int oneTwoThree=123;", 16394 Alignment)); 16395 16396 EXPECT_EQ("int a = 5;\n" 16397 "\n" 16398 "// line comment\n" 16399 "int oneTwoThree = 123;", 16400 format("int a = 5;\n" 16401 "\n" 16402 "// line comment\n" 16403 "int oneTwoThree=123;", 16404 Alignment)); 16405 } 16406 16407 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) { 16408 FormatStyle Alignment = getLLVMStyle(); 16409 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 16410 Alignment.AlignConsecutiveAssignments = 16411 FormatStyle::ACS_AcrossEmptyLinesAndComments; 16412 verifyFormat("int a = 5;\n" 16413 "int oneTwoThree = 123;", 16414 Alignment); 16415 verifyFormat("int a = method();\n" 16416 "int oneTwoThree = 133;", 16417 Alignment); 16418 verifyFormat("a &= 5;\n" 16419 "bcd *= 5;\n" 16420 "ghtyf += 5;\n" 16421 "dvfvdb -= 5;\n" 16422 "a /= 5;\n" 16423 "vdsvsv %= 5;\n" 16424 "sfdbddfbdfbb ^= 5;\n" 16425 "dvsdsv |= 5;\n" 16426 "int dsvvdvsdvvv = 123;", 16427 Alignment); 16428 verifyFormat("int i = 1, j = 10;\n" 16429 "something = 2000;", 16430 Alignment); 16431 verifyFormat("something = 2000;\n" 16432 "int i = 1, j = 10;\n", 16433 Alignment); 16434 verifyFormat("something = 2000;\n" 16435 "another = 911;\n" 16436 "int i = 1, j = 10;\n" 16437 "oneMore = 1;\n" 16438 "i = 2;", 16439 Alignment); 16440 verifyFormat("int a = 5;\n" 16441 "int one = 1;\n" 16442 "method();\n" 16443 "int oneTwoThree = 123;\n" 16444 "int oneTwo = 12;", 16445 Alignment); 16446 verifyFormat("int oneTwoThree = 123;\n" 16447 "int oneTwo = 12;\n" 16448 "method();\n", 16449 Alignment); 16450 verifyFormat("int oneTwoThree = 123; // comment\n" 16451 "int oneTwo = 12; // comment", 16452 Alignment); 16453 16454 // Bug 25167 16455 /* Uncomment when fixed 16456 verifyFormat("#if A\n" 16457 "#else\n" 16458 "int aaaaaaaa = 12;\n" 16459 "#endif\n" 16460 "#if B\n" 16461 "#else\n" 16462 "int a = 12;\n" 16463 "#endif\n", 16464 Alignment); 16465 verifyFormat("enum foo {\n" 16466 "#if A\n" 16467 "#else\n" 16468 " aaaaaaaa = 12;\n" 16469 "#endif\n" 16470 "#if B\n" 16471 "#else\n" 16472 " a = 12;\n" 16473 "#endif\n" 16474 "};\n", 16475 Alignment); 16476 */ 16477 16478 Alignment.MaxEmptyLinesToKeep = 10; 16479 /* Test alignment across empty lines */ 16480 EXPECT_EQ("int a = 5;\n" 16481 "\n" 16482 "int oneTwoThree = 123;", 16483 format("int a = 5;\n" 16484 "\n" 16485 "int oneTwoThree= 123;", 16486 Alignment)); 16487 EXPECT_EQ("int a = 5;\n" 16488 "int one = 1;\n" 16489 "\n" 16490 "int oneTwoThree = 123;", 16491 format("int a = 5;\n" 16492 "int one = 1;\n" 16493 "\n" 16494 "int oneTwoThree = 123;", 16495 Alignment)); 16496 EXPECT_EQ("int a = 5;\n" 16497 "int one = 1;\n" 16498 "\n" 16499 "int oneTwoThree = 123;\n" 16500 "int oneTwo = 12;", 16501 format("int a = 5;\n" 16502 "int one = 1;\n" 16503 "\n" 16504 "int oneTwoThree = 123;\n" 16505 "int oneTwo = 12;", 16506 Alignment)); 16507 16508 /* Test across comments */ 16509 EXPECT_EQ("int a = 5;\n" 16510 "/* block comment */\n" 16511 "int oneTwoThree = 123;", 16512 format("int a = 5;\n" 16513 "/* block comment */\n" 16514 "int oneTwoThree=123;", 16515 Alignment)); 16516 16517 EXPECT_EQ("int a = 5;\n" 16518 "// line comment\n" 16519 "int oneTwoThree = 123;", 16520 format("int a = 5;\n" 16521 "// line comment\n" 16522 "int oneTwoThree=123;", 16523 Alignment)); 16524 16525 /* Test across comments and newlines */ 16526 EXPECT_EQ("int a = 5;\n" 16527 "\n" 16528 "/* block comment */\n" 16529 "int oneTwoThree = 123;", 16530 format("int a = 5;\n" 16531 "\n" 16532 "/* block comment */\n" 16533 "int oneTwoThree=123;", 16534 Alignment)); 16535 16536 EXPECT_EQ("int a = 5;\n" 16537 "\n" 16538 "// line comment\n" 16539 "int oneTwoThree = 123;", 16540 format("int a = 5;\n" 16541 "\n" 16542 "// line comment\n" 16543 "int oneTwoThree=123;", 16544 Alignment)); 16545 16546 EXPECT_EQ("int a = 5;\n" 16547 "//\n" 16548 "// multi-line line comment\n" 16549 "//\n" 16550 "int oneTwoThree = 123;", 16551 format("int a = 5;\n" 16552 "//\n" 16553 "// multi-line line comment\n" 16554 "//\n" 16555 "int oneTwoThree=123;", 16556 Alignment)); 16557 16558 EXPECT_EQ("int a = 5;\n" 16559 "/*\n" 16560 " * multi-line block comment\n" 16561 " */\n" 16562 "int oneTwoThree = 123;", 16563 format("int a = 5;\n" 16564 "/*\n" 16565 " * multi-line block comment\n" 16566 " */\n" 16567 "int oneTwoThree=123;", 16568 Alignment)); 16569 16570 EXPECT_EQ("int a = 5;\n" 16571 "\n" 16572 "/* block comment */\n" 16573 "\n" 16574 "\n" 16575 "\n" 16576 "int oneTwoThree = 123;", 16577 format("int a = 5;\n" 16578 "\n" 16579 "/* block comment */\n" 16580 "\n" 16581 "\n" 16582 "\n" 16583 "int oneTwoThree=123;", 16584 Alignment)); 16585 16586 EXPECT_EQ("int a = 5;\n" 16587 "\n" 16588 "// line comment\n" 16589 "\n" 16590 "\n" 16591 "\n" 16592 "int oneTwoThree = 123;", 16593 format("int a = 5;\n" 16594 "\n" 16595 "// line comment\n" 16596 "\n" 16597 "\n" 16598 "\n" 16599 "int oneTwoThree=123;", 16600 Alignment)); 16601 16602 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 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_Left; 16610 verifyFormat("#define A \\\n" 16611 " int aaaa = 12; \\\n" 16612 " int b = 23; \\\n" 16613 " int ccc = 234; \\\n" 16614 " int dddddddddd = 2345;", 16615 Alignment); 16616 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 16617 verifyFormat("#define A " 16618 " \\\n" 16619 " int aaaa = 12; " 16620 " \\\n" 16621 " int b = 23; " 16622 " \\\n" 16623 " int ccc = 234; " 16624 " \\\n" 16625 " int dddddddddd = 2345;", 16626 Alignment); 16627 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 16628 "k = 4, int l = 5,\n" 16629 " int m = 6) {\n" 16630 " int j = 10;\n" 16631 " otherThing = 1;\n" 16632 "}", 16633 Alignment); 16634 verifyFormat("void SomeFunction(int parameter = 0) {\n" 16635 " int i = 1;\n" 16636 " int j = 2;\n" 16637 " int big = 10000;\n" 16638 "}", 16639 Alignment); 16640 verifyFormat("class C {\n" 16641 "public:\n" 16642 " int i = 1;\n" 16643 " virtual void f() = 0;\n" 16644 "};", 16645 Alignment); 16646 verifyFormat("int i = 1;\n" 16647 "if (SomeType t = getSomething()) {\n" 16648 "}\n" 16649 "int j = 2;\n" 16650 "int big = 10000;", 16651 Alignment); 16652 verifyFormat("int j = 7;\n" 16653 "for (int k = 0; k < N; ++k) {\n" 16654 "}\n" 16655 "int j = 2;\n" 16656 "int big = 10000;\n" 16657 "}", 16658 Alignment); 16659 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 16660 verifyFormat("int i = 1;\n" 16661 "LooooooooooongType loooooooooooooooooooooongVariable\n" 16662 " = someLooooooooooooooooongFunction();\n" 16663 "int j = 2;", 16664 Alignment); 16665 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 16666 verifyFormat("int i = 1;\n" 16667 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 16668 " someLooooooooooooooooongFunction();\n" 16669 "int j = 2;", 16670 Alignment); 16671 16672 verifyFormat("auto lambda = []() {\n" 16673 " auto i = 0;\n" 16674 " return 0;\n" 16675 "};\n" 16676 "int i = 0;\n" 16677 "auto v = type{\n" 16678 " i = 1, //\n" 16679 " (i = 2), //\n" 16680 " i = 3 //\n" 16681 "};", 16682 Alignment); 16683 16684 verifyFormat( 16685 "int i = 1;\n" 16686 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 16687 " loooooooooooooooooooooongParameterB);\n" 16688 "int j = 2;", 16689 Alignment); 16690 16691 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n" 16692 " typename B = very_long_type_name_1,\n" 16693 " typename T_2 = very_long_type_name_2>\n" 16694 "auto foo() {}\n", 16695 Alignment); 16696 verifyFormat("int a, b = 1;\n" 16697 "int c = 2;\n" 16698 "int dd = 3;\n", 16699 Alignment); 16700 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 16701 "float b[1][] = {{3.f}};\n", 16702 Alignment); 16703 verifyFormat("for (int i = 0; i < 1; i++)\n" 16704 " int x = 1;\n", 16705 Alignment); 16706 verifyFormat("for (i = 0; i < 1; i++)\n" 16707 " x = 1;\n" 16708 "y = 1;\n", 16709 Alignment); 16710 16711 Alignment.ReflowComments = true; 16712 Alignment.ColumnLimit = 50; 16713 EXPECT_EQ("int x = 0;\n" 16714 "int yy = 1; /// specificlennospace\n" 16715 "int zzz = 2;\n", 16716 format("int x = 0;\n" 16717 "int yy = 1; ///specificlennospace\n" 16718 "int zzz = 2;\n", 16719 Alignment)); 16720 } 16721 16722 TEST_F(FormatTest, AlignConsecutiveAssignments) { 16723 FormatStyle Alignment = getLLVMStyle(); 16724 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 16725 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 16726 verifyFormat("int a = 5;\n" 16727 "int oneTwoThree = 123;", 16728 Alignment); 16729 verifyFormat("int a = 5;\n" 16730 "int oneTwoThree = 123;", 16731 Alignment); 16732 16733 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 16734 verifyFormat("int a = 5;\n" 16735 "int oneTwoThree = 123;", 16736 Alignment); 16737 verifyFormat("int a = method();\n" 16738 "int oneTwoThree = 133;", 16739 Alignment); 16740 verifyFormat("a &= 5;\n" 16741 "bcd *= 5;\n" 16742 "ghtyf += 5;\n" 16743 "dvfvdb -= 5;\n" 16744 "a /= 5;\n" 16745 "vdsvsv %= 5;\n" 16746 "sfdbddfbdfbb ^= 5;\n" 16747 "dvsdsv |= 5;\n" 16748 "int dsvvdvsdvvv = 123;", 16749 Alignment); 16750 verifyFormat("int i = 1, j = 10;\n" 16751 "something = 2000;", 16752 Alignment); 16753 verifyFormat("something = 2000;\n" 16754 "int i = 1, j = 10;\n", 16755 Alignment); 16756 verifyFormat("something = 2000;\n" 16757 "another = 911;\n" 16758 "int i = 1, j = 10;\n" 16759 "oneMore = 1;\n" 16760 "i = 2;", 16761 Alignment); 16762 verifyFormat("int a = 5;\n" 16763 "int one = 1;\n" 16764 "method();\n" 16765 "int oneTwoThree = 123;\n" 16766 "int oneTwo = 12;", 16767 Alignment); 16768 verifyFormat("int oneTwoThree = 123;\n" 16769 "int oneTwo = 12;\n" 16770 "method();\n", 16771 Alignment); 16772 verifyFormat("int oneTwoThree = 123; // comment\n" 16773 "int oneTwo = 12; // comment", 16774 Alignment); 16775 verifyFormat("int f() = default;\n" 16776 "int &operator() = default;\n" 16777 "int &operator=() {", 16778 Alignment); 16779 verifyFormat("int f() = delete;\n" 16780 "int &operator() = delete;\n" 16781 "int &operator=() {", 16782 Alignment); 16783 verifyFormat("int f() = default; // comment\n" 16784 "int &operator() = default; // comment\n" 16785 "int &operator=() {", 16786 Alignment); 16787 verifyFormat("int f() = default;\n" 16788 "int &operator() = default;\n" 16789 "int &operator==() {", 16790 Alignment); 16791 verifyFormat("int f() = default;\n" 16792 "int &operator() = default;\n" 16793 "int &operator<=() {", 16794 Alignment); 16795 verifyFormat("int f() = default;\n" 16796 "int &operator() = default;\n" 16797 "int &operator!=() {", 16798 Alignment); 16799 verifyFormat("int f() = default;\n" 16800 "int &operator() = default;\n" 16801 "int &operator=();", 16802 Alignment); 16803 verifyFormat("int f() = delete;\n" 16804 "int &operator() = delete;\n" 16805 "int &operator=();", 16806 Alignment); 16807 verifyFormat("/* long long padding */ int f() = default;\n" 16808 "int &operator() = default;\n" 16809 "int &operator/**/ =();", 16810 Alignment); 16811 // https://llvm.org/PR33697 16812 FormatStyle AlignmentWithPenalty = getLLVMStyle(); 16813 AlignmentWithPenalty.AlignConsecutiveAssignments = 16814 FormatStyle::ACS_Consecutive; 16815 AlignmentWithPenalty.PenaltyReturnTypeOnItsOwnLine = 5000; 16816 verifyFormat("class SSSSSSSSSSSSSSSSSSSSSSSSSSSS {\n" 16817 " void f() = delete;\n" 16818 " SSSSSSSSSSSSSSSSSSSSSSSSSSSS &operator=(\n" 16819 " const SSSSSSSSSSSSSSSSSSSSSSSSSSSS &other) = delete;\n" 16820 "};\n", 16821 AlignmentWithPenalty); 16822 16823 // Bug 25167 16824 /* Uncomment when fixed 16825 verifyFormat("#if A\n" 16826 "#else\n" 16827 "int aaaaaaaa = 12;\n" 16828 "#endif\n" 16829 "#if B\n" 16830 "#else\n" 16831 "int a = 12;\n" 16832 "#endif\n", 16833 Alignment); 16834 verifyFormat("enum foo {\n" 16835 "#if A\n" 16836 "#else\n" 16837 " aaaaaaaa = 12;\n" 16838 "#endif\n" 16839 "#if B\n" 16840 "#else\n" 16841 " a = 12;\n" 16842 "#endif\n" 16843 "};\n", 16844 Alignment); 16845 */ 16846 16847 EXPECT_EQ("int a = 5;\n" 16848 "\n" 16849 "int oneTwoThree = 123;", 16850 format("int a = 5;\n" 16851 "\n" 16852 "int oneTwoThree= 123;", 16853 Alignment)); 16854 EXPECT_EQ("int a = 5;\n" 16855 "int one = 1;\n" 16856 "\n" 16857 "int oneTwoThree = 123;", 16858 format("int a = 5;\n" 16859 "int one = 1;\n" 16860 "\n" 16861 "int oneTwoThree = 123;", 16862 Alignment)); 16863 EXPECT_EQ("int a = 5;\n" 16864 "int one = 1;\n" 16865 "\n" 16866 "int oneTwoThree = 123;\n" 16867 "int oneTwo = 12;", 16868 format("int a = 5;\n" 16869 "int one = 1;\n" 16870 "\n" 16871 "int oneTwoThree = 123;\n" 16872 "int oneTwo = 12;", 16873 Alignment)); 16874 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 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_Left; 16882 verifyFormat("#define A \\\n" 16883 " int aaaa = 12; \\\n" 16884 " int b = 23; \\\n" 16885 " int ccc = 234; \\\n" 16886 " int dddddddddd = 2345;", 16887 Alignment); 16888 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 16889 verifyFormat("#define A " 16890 " \\\n" 16891 " int aaaa = 12; " 16892 " \\\n" 16893 " int b = 23; " 16894 " \\\n" 16895 " int ccc = 234; " 16896 " \\\n" 16897 " int dddddddddd = 2345;", 16898 Alignment); 16899 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 16900 "k = 4, int l = 5,\n" 16901 " int m = 6) {\n" 16902 " int j = 10;\n" 16903 " otherThing = 1;\n" 16904 "}", 16905 Alignment); 16906 verifyFormat("void SomeFunction(int parameter = 0) {\n" 16907 " int i = 1;\n" 16908 " int j = 2;\n" 16909 " int big = 10000;\n" 16910 "}", 16911 Alignment); 16912 verifyFormat("class C {\n" 16913 "public:\n" 16914 " int i = 1;\n" 16915 " virtual void f() = 0;\n" 16916 "};", 16917 Alignment); 16918 verifyFormat("int i = 1;\n" 16919 "if (SomeType t = getSomething()) {\n" 16920 "}\n" 16921 "int j = 2;\n" 16922 "int big = 10000;", 16923 Alignment); 16924 verifyFormat("int j = 7;\n" 16925 "for (int k = 0; k < N; ++k) {\n" 16926 "}\n" 16927 "int j = 2;\n" 16928 "int big = 10000;\n" 16929 "}", 16930 Alignment); 16931 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 16932 verifyFormat("int i = 1;\n" 16933 "LooooooooooongType loooooooooooooooooooooongVariable\n" 16934 " = someLooooooooooooooooongFunction();\n" 16935 "int j = 2;", 16936 Alignment); 16937 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 16938 verifyFormat("int i = 1;\n" 16939 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 16940 " someLooooooooooooooooongFunction();\n" 16941 "int j = 2;", 16942 Alignment); 16943 16944 verifyFormat("auto lambda = []() {\n" 16945 " auto i = 0;\n" 16946 " return 0;\n" 16947 "};\n" 16948 "int i = 0;\n" 16949 "auto v = type{\n" 16950 " i = 1, //\n" 16951 " (i = 2), //\n" 16952 " i = 3 //\n" 16953 "};", 16954 Alignment); 16955 16956 verifyFormat( 16957 "int i = 1;\n" 16958 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 16959 " loooooooooooooooooooooongParameterB);\n" 16960 "int j = 2;", 16961 Alignment); 16962 16963 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n" 16964 " typename B = very_long_type_name_1,\n" 16965 " typename T_2 = very_long_type_name_2>\n" 16966 "auto foo() {}\n", 16967 Alignment); 16968 verifyFormat("int a, b = 1;\n" 16969 "int c = 2;\n" 16970 "int dd = 3;\n", 16971 Alignment); 16972 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 16973 "float b[1][] = {{3.f}};\n", 16974 Alignment); 16975 verifyFormat("for (int i = 0; i < 1; i++)\n" 16976 " int x = 1;\n", 16977 Alignment); 16978 verifyFormat("for (i = 0; i < 1; i++)\n" 16979 " x = 1;\n" 16980 "y = 1;\n", 16981 Alignment); 16982 16983 EXPECT_EQ(Alignment.ReflowComments, true); 16984 Alignment.ColumnLimit = 50; 16985 EXPECT_EQ("int x = 0;\n" 16986 "int yy = 1; /// specificlennospace\n" 16987 "int zzz = 2;\n", 16988 format("int x = 0;\n" 16989 "int yy = 1; ///specificlennospace\n" 16990 "int zzz = 2;\n", 16991 Alignment)); 16992 16993 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 16994 "auto b = [] {\n" 16995 " f();\n" 16996 " return;\n" 16997 "};", 16998 Alignment); 16999 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17000 "auto b = g([] {\n" 17001 " f();\n" 17002 " return;\n" 17003 "});", 17004 Alignment); 17005 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17006 "auto b = g(param, [] {\n" 17007 " f();\n" 17008 " return;\n" 17009 "});", 17010 Alignment); 17011 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 17012 "auto b = [] {\n" 17013 " if (condition) {\n" 17014 " return;\n" 17015 " }\n" 17016 "};", 17017 Alignment); 17018 17019 verifyFormat("auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 17020 " ccc ? aaaaa : bbbbb,\n" 17021 " dddddddddddddddddddddddddd);", 17022 Alignment); 17023 // FIXME: https://llvm.org/PR53497 17024 // verifyFormat("auto aaaaaaaaaaaa = f();\n" 17025 // "auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 17026 // " ccc ? aaaaa : bbbbb,\n" 17027 // " dddddddddddddddddddddddddd);", 17028 // Alignment); 17029 } 17030 17031 TEST_F(FormatTest, AlignConsecutiveBitFields) { 17032 FormatStyle Alignment = getLLVMStyle(); 17033 Alignment.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive; 17034 verifyFormat("int const a : 5;\n" 17035 "int oneTwoThree : 23;", 17036 Alignment); 17037 17038 // Initializers are allowed starting with c++2a 17039 verifyFormat("int const a : 5 = 1;\n" 17040 "int oneTwoThree : 23 = 0;", 17041 Alignment); 17042 17043 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17044 verifyFormat("int const a : 5;\n" 17045 "int oneTwoThree : 23;", 17046 Alignment); 17047 17048 verifyFormat("int const a : 5; // comment\n" 17049 "int oneTwoThree : 23; // comment", 17050 Alignment); 17051 17052 verifyFormat("int const a : 5 = 1;\n" 17053 "int oneTwoThree : 23 = 0;", 17054 Alignment); 17055 17056 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17057 verifyFormat("int const a : 5 = 1;\n" 17058 "int oneTwoThree : 23 = 0;", 17059 Alignment); 17060 verifyFormat("int const a : 5 = {1};\n" 17061 "int oneTwoThree : 23 = 0;", 17062 Alignment); 17063 17064 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None; 17065 verifyFormat("int const a :5;\n" 17066 "int oneTwoThree:23;", 17067 Alignment); 17068 17069 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before; 17070 verifyFormat("int const a :5;\n" 17071 "int oneTwoThree :23;", 17072 Alignment); 17073 17074 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After; 17075 verifyFormat("int const a : 5;\n" 17076 "int oneTwoThree: 23;", 17077 Alignment); 17078 17079 // Known limitations: ':' is only recognized as a bitfield colon when 17080 // followed by a number. 17081 /* 17082 verifyFormat("int oneTwoThree : SOME_CONSTANT;\n" 17083 "int a : 5;", 17084 Alignment); 17085 */ 17086 } 17087 17088 TEST_F(FormatTest, AlignConsecutiveDeclarations) { 17089 FormatStyle Alignment = getLLVMStyle(); 17090 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 17091 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_None; 17092 Alignment.PointerAlignment = FormatStyle::PAS_Right; 17093 verifyFormat("float const a = 5;\n" 17094 "int oneTwoThree = 123;", 17095 Alignment); 17096 verifyFormat("int a = 5;\n" 17097 "float const oneTwoThree = 123;", 17098 Alignment); 17099 17100 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17101 verifyFormat("float const a = 5;\n" 17102 "int oneTwoThree = 123;", 17103 Alignment); 17104 verifyFormat("int a = method();\n" 17105 "float const oneTwoThree = 133;", 17106 Alignment); 17107 verifyFormat("int i = 1, j = 10;\n" 17108 "something = 2000;", 17109 Alignment); 17110 verifyFormat("something = 2000;\n" 17111 "int i = 1, j = 10;\n", 17112 Alignment); 17113 verifyFormat("float something = 2000;\n" 17114 "double another = 911;\n" 17115 "int i = 1, j = 10;\n" 17116 "const int *oneMore = 1;\n" 17117 "unsigned i = 2;", 17118 Alignment); 17119 verifyFormat("float a = 5;\n" 17120 "int one = 1;\n" 17121 "method();\n" 17122 "const double oneTwoThree = 123;\n" 17123 "const unsigned int oneTwo = 12;", 17124 Alignment); 17125 verifyFormat("int oneTwoThree{0}; // comment\n" 17126 "unsigned oneTwo; // comment", 17127 Alignment); 17128 verifyFormat("unsigned int *a;\n" 17129 "int *b;\n" 17130 "unsigned int Const *c;\n" 17131 "unsigned int const *d;\n" 17132 "unsigned int Const &e;\n" 17133 "unsigned int const &f;", 17134 Alignment); 17135 verifyFormat("Const unsigned int *c;\n" 17136 "const unsigned int *d;\n" 17137 "Const unsigned int &e;\n" 17138 "const unsigned int &f;\n" 17139 "const unsigned g;\n" 17140 "Const unsigned h;", 17141 Alignment); 17142 EXPECT_EQ("float const a = 5;\n" 17143 "\n" 17144 "int oneTwoThree = 123;", 17145 format("float const a = 5;\n" 17146 "\n" 17147 "int oneTwoThree= 123;", 17148 Alignment)); 17149 EXPECT_EQ("float a = 5;\n" 17150 "int one = 1;\n" 17151 "\n" 17152 "unsigned oneTwoThree = 123;", 17153 format("float a = 5;\n" 17154 "int one = 1;\n" 17155 "\n" 17156 "unsigned oneTwoThree = 123;", 17157 Alignment)); 17158 EXPECT_EQ("float a = 5;\n" 17159 "int one = 1;\n" 17160 "\n" 17161 "unsigned oneTwoThree = 123;\n" 17162 "int oneTwo = 12;", 17163 format("float a = 5;\n" 17164 "int one = 1;\n" 17165 "\n" 17166 "unsigned oneTwoThree = 123;\n" 17167 "int oneTwo = 12;", 17168 Alignment)); 17169 // Function prototype alignment 17170 verifyFormat("int a();\n" 17171 "double b();", 17172 Alignment); 17173 verifyFormat("int a(int x);\n" 17174 "double b();", 17175 Alignment); 17176 unsigned OldColumnLimit = Alignment.ColumnLimit; 17177 // We need to set ColumnLimit to zero, in order to stress nested alignments, 17178 // otherwise the function parameters will be re-flowed onto a single line. 17179 Alignment.ColumnLimit = 0; 17180 EXPECT_EQ("int a(int x,\n" 17181 " float y);\n" 17182 "double b(int x,\n" 17183 " double y);", 17184 format("int a(int x,\n" 17185 " float y);\n" 17186 "double b(int x,\n" 17187 " double y);", 17188 Alignment)); 17189 // This ensures that function parameters of function declarations are 17190 // correctly indented when their owning functions are indented. 17191 // The failure case here is for 'double y' to not be indented enough. 17192 EXPECT_EQ("double a(int x);\n" 17193 "int b(int y,\n" 17194 " double z);", 17195 format("double a(int x);\n" 17196 "int b(int y,\n" 17197 " double z);", 17198 Alignment)); 17199 // Set ColumnLimit low so that we induce wrapping immediately after 17200 // the function name and opening paren. 17201 Alignment.ColumnLimit = 13; 17202 verifyFormat("int function(\n" 17203 " int x,\n" 17204 " bool y);", 17205 Alignment); 17206 Alignment.ColumnLimit = OldColumnLimit; 17207 // Ensure function pointers don't screw up recursive alignment 17208 verifyFormat("int a(int x, void (*fp)(int y));\n" 17209 "double b();", 17210 Alignment); 17211 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17212 // Ensure recursive alignment is broken by function braces, so that the 17213 // "a = 1" does not align with subsequent assignments inside the function 17214 // body. 17215 verifyFormat("int func(int a = 1) {\n" 17216 " int b = 2;\n" 17217 " int cc = 3;\n" 17218 "}", 17219 Alignment); 17220 verifyFormat("float something = 2000;\n" 17221 "double another = 911;\n" 17222 "int i = 1, j = 10;\n" 17223 "const int *oneMore = 1;\n" 17224 "unsigned i = 2;", 17225 Alignment); 17226 verifyFormat("int oneTwoThree = {0}; // comment\n" 17227 "unsigned oneTwo = 0; // comment", 17228 Alignment); 17229 // Make sure that scope is correctly tracked, in the absence of braces 17230 verifyFormat("for (int i = 0; i < n; i++)\n" 17231 " j = i;\n" 17232 "double x = 1;\n", 17233 Alignment); 17234 verifyFormat("if (int i = 0)\n" 17235 " j = i;\n" 17236 "double x = 1;\n", 17237 Alignment); 17238 // Ensure operator[] and operator() are comprehended 17239 verifyFormat("struct test {\n" 17240 " long long int foo();\n" 17241 " int operator[](int a);\n" 17242 " double bar();\n" 17243 "};\n", 17244 Alignment); 17245 verifyFormat("struct test {\n" 17246 " long long int foo();\n" 17247 " int operator()(int a);\n" 17248 " double bar();\n" 17249 "};\n", 17250 Alignment); 17251 // http://llvm.org/PR52914 17252 verifyFormat("char *a[] = {\"a\", // comment\n" 17253 " \"bb\"};\n" 17254 "int bbbbbbb = 0;", 17255 Alignment); 17256 17257 // PAS_Right 17258 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17259 " int const i = 1;\n" 17260 " int *j = 2;\n" 17261 " int big = 10000;\n" 17262 "\n" 17263 " unsigned oneTwoThree = 123;\n" 17264 " int oneTwo = 12;\n" 17265 " method();\n" 17266 " float k = 2;\n" 17267 " int ll = 10000;\n" 17268 "}", 17269 format("void SomeFunction(int parameter= 0) {\n" 17270 " int const i= 1;\n" 17271 " int *j=2;\n" 17272 " int big = 10000;\n" 17273 "\n" 17274 "unsigned oneTwoThree =123;\n" 17275 "int oneTwo = 12;\n" 17276 " method();\n" 17277 "float k= 2;\n" 17278 "int ll=10000;\n" 17279 "}", 17280 Alignment)); 17281 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17282 " int const i = 1;\n" 17283 " int **j = 2, ***k;\n" 17284 " int &k = i;\n" 17285 " int &&l = i + j;\n" 17286 " int big = 10000;\n" 17287 "\n" 17288 " unsigned oneTwoThree = 123;\n" 17289 " int oneTwo = 12;\n" 17290 " method();\n" 17291 " float k = 2;\n" 17292 " int ll = 10000;\n" 17293 "}", 17294 format("void SomeFunction(int parameter= 0) {\n" 17295 " int const i= 1;\n" 17296 " int **j=2,***k;\n" 17297 "int &k=i;\n" 17298 "int &&l=i+j;\n" 17299 " int big = 10000;\n" 17300 "\n" 17301 "unsigned oneTwoThree =123;\n" 17302 "int oneTwo = 12;\n" 17303 " method();\n" 17304 "float k= 2;\n" 17305 "int ll=10000;\n" 17306 "}", 17307 Alignment)); 17308 // variables are aligned at their name, pointers are at the right most 17309 // position 17310 verifyFormat("int *a;\n" 17311 "int **b;\n" 17312 "int ***c;\n" 17313 "int foobar;\n", 17314 Alignment); 17315 17316 // PAS_Left 17317 FormatStyle AlignmentLeft = Alignment; 17318 AlignmentLeft.PointerAlignment = FormatStyle::PAS_Left; 17319 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17320 " int const i = 1;\n" 17321 " int* j = 2;\n" 17322 " int big = 10000;\n" 17323 "\n" 17324 " unsigned oneTwoThree = 123;\n" 17325 " int oneTwo = 12;\n" 17326 " method();\n" 17327 " float k = 2;\n" 17328 " int ll = 10000;\n" 17329 "}", 17330 format("void SomeFunction(int parameter= 0) {\n" 17331 " int const i= 1;\n" 17332 " int *j=2;\n" 17333 " int big = 10000;\n" 17334 "\n" 17335 "unsigned oneTwoThree =123;\n" 17336 "int oneTwo = 12;\n" 17337 " method();\n" 17338 "float k= 2;\n" 17339 "int ll=10000;\n" 17340 "}", 17341 AlignmentLeft)); 17342 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17343 " int const i = 1;\n" 17344 " int** j = 2;\n" 17345 " int& k = i;\n" 17346 " int&& l = i + j;\n" 17347 " int big = 10000;\n" 17348 "\n" 17349 " unsigned oneTwoThree = 123;\n" 17350 " int oneTwo = 12;\n" 17351 " method();\n" 17352 " float k = 2;\n" 17353 " int ll = 10000;\n" 17354 "}", 17355 format("void SomeFunction(int parameter= 0) {\n" 17356 " int const i= 1;\n" 17357 " int **j=2;\n" 17358 "int &k=i;\n" 17359 "int &&l=i+j;\n" 17360 " int big = 10000;\n" 17361 "\n" 17362 "unsigned oneTwoThree =123;\n" 17363 "int oneTwo = 12;\n" 17364 " method();\n" 17365 "float k= 2;\n" 17366 "int ll=10000;\n" 17367 "}", 17368 AlignmentLeft)); 17369 // variables are aligned at their name, pointers are at the left most position 17370 verifyFormat("int* a;\n" 17371 "int** b;\n" 17372 "int*** c;\n" 17373 "int foobar;\n", 17374 AlignmentLeft); 17375 17376 // PAS_Middle 17377 FormatStyle AlignmentMiddle = Alignment; 17378 AlignmentMiddle.PointerAlignment = FormatStyle::PAS_Middle; 17379 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17380 " int const i = 1;\n" 17381 " int * j = 2;\n" 17382 " int big = 10000;\n" 17383 "\n" 17384 " unsigned oneTwoThree = 123;\n" 17385 " int oneTwo = 12;\n" 17386 " method();\n" 17387 " float k = 2;\n" 17388 " int ll = 10000;\n" 17389 "}", 17390 format("void SomeFunction(int parameter= 0) {\n" 17391 " int const i= 1;\n" 17392 " int *j=2;\n" 17393 " int big = 10000;\n" 17394 "\n" 17395 "unsigned oneTwoThree =123;\n" 17396 "int oneTwo = 12;\n" 17397 " method();\n" 17398 "float k= 2;\n" 17399 "int ll=10000;\n" 17400 "}", 17401 AlignmentMiddle)); 17402 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17403 " int const i = 1;\n" 17404 " int ** j = 2, ***k;\n" 17405 " int & k = i;\n" 17406 " int && l = i + j;\n" 17407 " int big = 10000;\n" 17408 "\n" 17409 " unsigned oneTwoThree = 123;\n" 17410 " int oneTwo = 12;\n" 17411 " method();\n" 17412 " float k = 2;\n" 17413 " int ll = 10000;\n" 17414 "}", 17415 format("void SomeFunction(int parameter= 0) {\n" 17416 " int const i= 1;\n" 17417 " int **j=2,***k;\n" 17418 "int &k=i;\n" 17419 "int &&l=i+j;\n" 17420 " int big = 10000;\n" 17421 "\n" 17422 "unsigned oneTwoThree =123;\n" 17423 "int oneTwo = 12;\n" 17424 " method();\n" 17425 "float k= 2;\n" 17426 "int ll=10000;\n" 17427 "}", 17428 AlignmentMiddle)); 17429 // variables are aligned at their name, pointers are in the middle 17430 verifyFormat("int * a;\n" 17431 "int * b;\n" 17432 "int *** c;\n" 17433 "int foobar;\n", 17434 AlignmentMiddle); 17435 17436 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 17437 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 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_Left; 17445 verifyFormat("#define A \\\n" 17446 " int aaaa = 12; \\\n" 17447 " float b = 23; \\\n" 17448 " const int ccc = 234; \\\n" 17449 " unsigned dddddddddd = 2345;", 17450 Alignment); 17451 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 17452 Alignment.ColumnLimit = 30; 17453 verifyFormat("#define A \\\n" 17454 " int aaaa = 12; \\\n" 17455 " float b = 23; \\\n" 17456 " const int ccc = 234; \\\n" 17457 " int dddddddddd = 2345;", 17458 Alignment); 17459 Alignment.ColumnLimit = 80; 17460 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 17461 "k = 4, int l = 5,\n" 17462 " int m = 6) {\n" 17463 " const int j = 10;\n" 17464 " otherThing = 1;\n" 17465 "}", 17466 Alignment); 17467 verifyFormat("void SomeFunction(int parameter = 0) {\n" 17468 " int const i = 1;\n" 17469 " int *j = 2;\n" 17470 " int big = 10000;\n" 17471 "}", 17472 Alignment); 17473 verifyFormat("class C {\n" 17474 "public:\n" 17475 " int i = 1;\n" 17476 " virtual void f() = 0;\n" 17477 "};", 17478 Alignment); 17479 verifyFormat("float i = 1;\n" 17480 "if (SomeType t = getSomething()) {\n" 17481 "}\n" 17482 "const unsigned j = 2;\n" 17483 "int big = 10000;", 17484 Alignment); 17485 verifyFormat("float j = 7;\n" 17486 "for (int k = 0; k < N; ++k) {\n" 17487 "}\n" 17488 "unsigned j = 2;\n" 17489 "int big = 10000;\n" 17490 "}", 17491 Alignment); 17492 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 17493 verifyFormat("float i = 1;\n" 17494 "LooooooooooongType loooooooooooooooooooooongVariable\n" 17495 " = someLooooooooooooooooongFunction();\n" 17496 "int j = 2;", 17497 Alignment); 17498 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 17499 verifyFormat("int i = 1;\n" 17500 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 17501 " someLooooooooooooooooongFunction();\n" 17502 "int j = 2;", 17503 Alignment); 17504 17505 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17506 verifyFormat("auto lambda = []() {\n" 17507 " auto ii = 0;\n" 17508 " float j = 0;\n" 17509 " return 0;\n" 17510 "};\n" 17511 "int i = 0;\n" 17512 "float i2 = 0;\n" 17513 "auto v = type{\n" 17514 " i = 1, //\n" 17515 " (i = 2), //\n" 17516 " i = 3 //\n" 17517 "};", 17518 Alignment); 17519 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 17520 17521 verifyFormat( 17522 "int i = 1;\n" 17523 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 17524 " loooooooooooooooooooooongParameterB);\n" 17525 "int j = 2;", 17526 Alignment); 17527 17528 // Test interactions with ColumnLimit and AlignConsecutiveAssignments: 17529 // We expect declarations and assignments to align, as long as it doesn't 17530 // exceed the column limit, starting a new alignment sequence whenever it 17531 // happens. 17532 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17533 Alignment.ColumnLimit = 30; 17534 verifyFormat("float ii = 1;\n" 17535 "unsigned j = 2;\n" 17536 "int someVerylongVariable = 1;\n" 17537 "AnotherLongType ll = 123456;\n" 17538 "VeryVeryLongType k = 2;\n" 17539 "int myvar = 1;", 17540 Alignment); 17541 Alignment.ColumnLimit = 80; 17542 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 17543 17544 verifyFormat( 17545 "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n" 17546 " typename LongType, typename B>\n" 17547 "auto foo() {}\n", 17548 Alignment); 17549 verifyFormat("float a, b = 1;\n" 17550 "int c = 2;\n" 17551 "int dd = 3;\n", 17552 Alignment); 17553 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17554 "float b[1][] = {{3.f}};\n", 17555 Alignment); 17556 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17557 verifyFormat("float a, b = 1;\n" 17558 "int c = 2;\n" 17559 "int dd = 3;\n", 17560 Alignment); 17561 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17562 "float b[1][] = {{3.f}};\n", 17563 Alignment); 17564 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 17565 17566 Alignment.ColumnLimit = 30; 17567 Alignment.BinPackParameters = false; 17568 verifyFormat("void foo(float a,\n" 17569 " float b,\n" 17570 " int c,\n" 17571 " uint32_t *d) {\n" 17572 " int *e = 0;\n" 17573 " float f = 0;\n" 17574 " double g = 0;\n" 17575 "}\n" 17576 "void bar(ino_t a,\n" 17577 " int b,\n" 17578 " uint32_t *c,\n" 17579 " bool d) {}\n", 17580 Alignment); 17581 Alignment.BinPackParameters = true; 17582 Alignment.ColumnLimit = 80; 17583 17584 // Bug 33507 17585 Alignment.PointerAlignment = FormatStyle::PAS_Middle; 17586 verifyFormat( 17587 "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n" 17588 " static const Version verVs2017;\n" 17589 " return true;\n" 17590 "});\n", 17591 Alignment); 17592 Alignment.PointerAlignment = FormatStyle::PAS_Right; 17593 17594 // See llvm.org/PR35641 17595 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17596 verifyFormat("int func() { //\n" 17597 " int b;\n" 17598 " unsigned c;\n" 17599 "}", 17600 Alignment); 17601 17602 // See PR37175 17603 FormatStyle Style = getMozillaStyle(); 17604 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17605 EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n" 17606 "foo(int a);", 17607 format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style)); 17608 17609 Alignment.PointerAlignment = FormatStyle::PAS_Left; 17610 verifyFormat("unsigned int* a;\n" 17611 "int* b;\n" 17612 "unsigned int Const* c;\n" 17613 "unsigned int const* d;\n" 17614 "unsigned int Const& e;\n" 17615 "unsigned int const& f;", 17616 Alignment); 17617 verifyFormat("Const unsigned int* c;\n" 17618 "const unsigned int* d;\n" 17619 "Const unsigned int& e;\n" 17620 "const unsigned int& f;\n" 17621 "const unsigned g;\n" 17622 "Const unsigned h;", 17623 Alignment); 17624 17625 Alignment.PointerAlignment = FormatStyle::PAS_Middle; 17626 verifyFormat("unsigned int * a;\n" 17627 "int * b;\n" 17628 "unsigned int Const * c;\n" 17629 "unsigned int const * d;\n" 17630 "unsigned int Const & e;\n" 17631 "unsigned int const & f;", 17632 Alignment); 17633 verifyFormat("Const unsigned int * c;\n" 17634 "const unsigned int * d;\n" 17635 "Const unsigned int & e;\n" 17636 "const unsigned int & f;\n" 17637 "const unsigned g;\n" 17638 "Const unsigned h;", 17639 Alignment); 17640 17641 // See PR46529 17642 FormatStyle BracedAlign = getLLVMStyle(); 17643 BracedAlign.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17644 verifyFormat("const auto result{[]() {\n" 17645 " const auto something = 1;\n" 17646 " return 2;\n" 17647 "}};", 17648 BracedAlign); 17649 verifyFormat("int foo{[]() {\n" 17650 " int bar{0};\n" 17651 " return 0;\n" 17652 "}()};", 17653 BracedAlign); 17654 BracedAlign.Cpp11BracedListStyle = false; 17655 verifyFormat("const auto result{ []() {\n" 17656 " const auto something = 1;\n" 17657 " return 2;\n" 17658 "} };", 17659 BracedAlign); 17660 verifyFormat("int foo{ []() {\n" 17661 " int bar{ 0 };\n" 17662 " return 0;\n" 17663 "}() };", 17664 BracedAlign); 17665 } 17666 17667 TEST_F(FormatTest, AlignWithLineBreaks) { 17668 auto Style = getLLVMStyleWithColumns(120); 17669 17670 EXPECT_EQ(Style.AlignConsecutiveAssignments, FormatStyle::ACS_None); 17671 EXPECT_EQ(Style.AlignConsecutiveDeclarations, FormatStyle::ACS_None); 17672 verifyFormat("void foo() {\n" 17673 " int myVar = 5;\n" 17674 " double x = 3.14;\n" 17675 " auto str = \"Hello \"\n" 17676 " \"World\";\n" 17677 " auto s = \"Hello \"\n" 17678 " \"Again\";\n" 17679 "}", 17680 Style); 17681 17682 // clang-format off 17683 verifyFormat("void foo() {\n" 17684 " const int capacityBefore = Entries.capacity();\n" 17685 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17686 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17687 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17688 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17689 "}", 17690 Style); 17691 // clang-format on 17692 17693 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17694 verifyFormat("void foo() {\n" 17695 " int myVar = 5;\n" 17696 " double x = 3.14;\n" 17697 " auto str = \"Hello \"\n" 17698 " \"World\";\n" 17699 " auto s = \"Hello \"\n" 17700 " \"Again\";\n" 17701 "}", 17702 Style); 17703 17704 // clang-format off 17705 verifyFormat("void foo() {\n" 17706 " const int capacityBefore = Entries.capacity();\n" 17707 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17708 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17709 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17710 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17711 "}", 17712 Style); 17713 // clang-format on 17714 17715 Style.AlignConsecutiveAssignments = FormatStyle::ACS_None; 17716 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17717 verifyFormat("void foo() {\n" 17718 " int myVar = 5;\n" 17719 " double x = 3.14;\n" 17720 " auto str = \"Hello \"\n" 17721 " \"World\";\n" 17722 " auto s = \"Hello \"\n" 17723 " \"Again\";\n" 17724 "}", 17725 Style); 17726 17727 // clang-format off 17728 verifyFormat("void foo() {\n" 17729 " const int capacityBefore = Entries.capacity();\n" 17730 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17731 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17732 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17733 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17734 "}", 17735 Style); 17736 // clang-format on 17737 17738 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17739 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17740 17741 verifyFormat("void foo() {\n" 17742 " int myVar = 5;\n" 17743 " double x = 3.14;\n" 17744 " auto str = \"Hello \"\n" 17745 " \"World\";\n" 17746 " auto s = \"Hello \"\n" 17747 " \"Again\";\n" 17748 "}", 17749 Style); 17750 17751 // clang-format off 17752 verifyFormat("void foo() {\n" 17753 " const int capacityBefore = Entries.capacity();\n" 17754 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17755 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17756 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17757 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17758 "}", 17759 Style); 17760 // clang-format on 17761 17762 Style = getLLVMStyleWithColumns(120); 17763 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17764 Style.ContinuationIndentWidth = 4; 17765 Style.IndentWidth = 4; 17766 17767 // clang-format off 17768 verifyFormat("void SomeFunc() {\n" 17769 " newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 17770 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17771 " newWatcher.maxAge = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 17772 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17773 " newWatcher.max = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 17774 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17775 "}", 17776 Style); 17777 // clang-format on 17778 17779 Style.BinPackArguments = false; 17780 17781 // clang-format off 17782 verifyFormat("void SomeFunc() {\n" 17783 " newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(\n" 17784 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17785 " newWatcher.maxAge = ToLegacyTimestamp(GetMaxAge(\n" 17786 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17787 " newWatcher.max = ToLegacyTimestamp(GetMaxAge(\n" 17788 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17789 "}", 17790 Style); 17791 // clang-format on 17792 } 17793 17794 TEST_F(FormatTest, AlignWithInitializerPeriods) { 17795 auto Style = getLLVMStyleWithColumns(60); 17796 17797 verifyFormat("void foo1(void) {\n" 17798 " BYTE p[1] = 1;\n" 17799 " A B = {.one_foooooooooooooooo = 2,\n" 17800 " .two_fooooooooooooo = 3,\n" 17801 " .three_fooooooooooooo = 4};\n" 17802 " BYTE payload = 2;\n" 17803 "}", 17804 Style); 17805 17806 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17807 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_None; 17808 verifyFormat("void foo2(void) {\n" 17809 " BYTE p[1] = 1;\n" 17810 " A B = {.one_foooooooooooooooo = 2,\n" 17811 " .two_fooooooooooooo = 3,\n" 17812 " .three_fooooooooooooo = 4};\n" 17813 " BYTE payload = 2;\n" 17814 "}", 17815 Style); 17816 17817 Style.AlignConsecutiveAssignments = FormatStyle::ACS_None; 17818 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17819 verifyFormat("void foo3(void) {\n" 17820 " BYTE p[1] = 1;\n" 17821 " A B = {.one_foooooooooooooooo = 2,\n" 17822 " .two_fooooooooooooo = 3,\n" 17823 " .three_fooooooooooooo = 4};\n" 17824 " BYTE payload = 2;\n" 17825 "}", 17826 Style); 17827 17828 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17829 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17830 verifyFormat("void foo4(void) {\n" 17831 " BYTE p[1] = 1;\n" 17832 " A B = {.one_foooooooooooooooo = 2,\n" 17833 " .two_fooooooooooooo = 3,\n" 17834 " .three_fooooooooooooo = 4};\n" 17835 " BYTE payload = 2;\n" 17836 "}", 17837 Style); 17838 } 17839 17840 TEST_F(FormatTest, LinuxBraceBreaking) { 17841 FormatStyle LinuxBraceStyle = getLLVMStyle(); 17842 LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux; 17843 verifyFormat("namespace a\n" 17844 "{\n" 17845 "class A\n" 17846 "{\n" 17847 " void f()\n" 17848 " {\n" 17849 " if (true) {\n" 17850 " a();\n" 17851 " b();\n" 17852 " } else {\n" 17853 " a();\n" 17854 " }\n" 17855 " }\n" 17856 " void g() { return; }\n" 17857 "};\n" 17858 "struct B {\n" 17859 " int x;\n" 17860 "};\n" 17861 "} // namespace a\n", 17862 LinuxBraceStyle); 17863 verifyFormat("enum X {\n" 17864 " Y = 0,\n" 17865 "}\n", 17866 LinuxBraceStyle); 17867 verifyFormat("struct S {\n" 17868 " int Type;\n" 17869 " union {\n" 17870 " int x;\n" 17871 " double y;\n" 17872 " } Value;\n" 17873 " class C\n" 17874 " {\n" 17875 " MyFavoriteType Value;\n" 17876 " } Class;\n" 17877 "}\n", 17878 LinuxBraceStyle); 17879 } 17880 17881 TEST_F(FormatTest, MozillaBraceBreaking) { 17882 FormatStyle MozillaBraceStyle = getLLVMStyle(); 17883 MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla; 17884 MozillaBraceStyle.FixNamespaceComments = false; 17885 verifyFormat("namespace a {\n" 17886 "class A\n" 17887 "{\n" 17888 " void f()\n" 17889 " {\n" 17890 " if (true) {\n" 17891 " a();\n" 17892 " b();\n" 17893 " }\n" 17894 " }\n" 17895 " void g() { return; }\n" 17896 "};\n" 17897 "enum E\n" 17898 "{\n" 17899 " A,\n" 17900 " // foo\n" 17901 " B,\n" 17902 " C\n" 17903 "};\n" 17904 "struct B\n" 17905 "{\n" 17906 " int x;\n" 17907 "};\n" 17908 "}\n", 17909 MozillaBraceStyle); 17910 verifyFormat("struct S\n" 17911 "{\n" 17912 " int Type;\n" 17913 " union\n" 17914 " {\n" 17915 " int x;\n" 17916 " double y;\n" 17917 " } Value;\n" 17918 " class C\n" 17919 " {\n" 17920 " MyFavoriteType Value;\n" 17921 " } Class;\n" 17922 "}\n", 17923 MozillaBraceStyle); 17924 } 17925 17926 TEST_F(FormatTest, StroustrupBraceBreaking) { 17927 FormatStyle StroustrupBraceStyle = getLLVMStyle(); 17928 StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 17929 verifyFormat("namespace a {\n" 17930 "class A {\n" 17931 " void f()\n" 17932 " {\n" 17933 " if (true) {\n" 17934 " a();\n" 17935 " b();\n" 17936 " }\n" 17937 " }\n" 17938 " void g() { return; }\n" 17939 "};\n" 17940 "struct B {\n" 17941 " int x;\n" 17942 "};\n" 17943 "} // namespace a\n", 17944 StroustrupBraceStyle); 17945 17946 verifyFormat("void foo()\n" 17947 "{\n" 17948 " if (a) {\n" 17949 " a();\n" 17950 " }\n" 17951 " else {\n" 17952 " b();\n" 17953 " }\n" 17954 "}\n", 17955 StroustrupBraceStyle); 17956 17957 verifyFormat("#ifdef _DEBUG\n" 17958 "int foo(int i = 0)\n" 17959 "#else\n" 17960 "int foo(int i = 5)\n" 17961 "#endif\n" 17962 "{\n" 17963 " return i;\n" 17964 "}", 17965 StroustrupBraceStyle); 17966 17967 verifyFormat("void foo() {}\n" 17968 "void bar()\n" 17969 "#ifdef _DEBUG\n" 17970 "{\n" 17971 " foo();\n" 17972 "}\n" 17973 "#else\n" 17974 "{\n" 17975 "}\n" 17976 "#endif", 17977 StroustrupBraceStyle); 17978 17979 verifyFormat("void foobar() { int i = 5; }\n" 17980 "#ifdef _DEBUG\n" 17981 "void bar() {}\n" 17982 "#else\n" 17983 "void bar() { foobar(); }\n" 17984 "#endif", 17985 StroustrupBraceStyle); 17986 } 17987 17988 TEST_F(FormatTest, AllmanBraceBreaking) { 17989 FormatStyle AllmanBraceStyle = getLLVMStyle(); 17990 AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman; 17991 17992 EXPECT_EQ("namespace a\n" 17993 "{\n" 17994 "void f();\n" 17995 "void g();\n" 17996 "} // namespace a\n", 17997 format("namespace a\n" 17998 "{\n" 17999 "void f();\n" 18000 "void g();\n" 18001 "}\n", 18002 AllmanBraceStyle)); 18003 18004 verifyFormat("namespace a\n" 18005 "{\n" 18006 "class A\n" 18007 "{\n" 18008 " void f()\n" 18009 " {\n" 18010 " if (true)\n" 18011 " {\n" 18012 " a();\n" 18013 " b();\n" 18014 " }\n" 18015 " }\n" 18016 " void g() { return; }\n" 18017 "};\n" 18018 "struct B\n" 18019 "{\n" 18020 " int x;\n" 18021 "};\n" 18022 "union C\n" 18023 "{\n" 18024 "};\n" 18025 "} // namespace a", 18026 AllmanBraceStyle); 18027 18028 verifyFormat("void f()\n" 18029 "{\n" 18030 " if (true)\n" 18031 " {\n" 18032 " a();\n" 18033 " }\n" 18034 " else if (false)\n" 18035 " {\n" 18036 " b();\n" 18037 " }\n" 18038 " else\n" 18039 " {\n" 18040 " c();\n" 18041 " }\n" 18042 "}\n", 18043 AllmanBraceStyle); 18044 18045 verifyFormat("void f()\n" 18046 "{\n" 18047 " for (int i = 0; i < 10; ++i)\n" 18048 " {\n" 18049 " a();\n" 18050 " }\n" 18051 " while (false)\n" 18052 " {\n" 18053 " b();\n" 18054 " }\n" 18055 " do\n" 18056 " {\n" 18057 " c();\n" 18058 " } while (false)\n" 18059 "}\n", 18060 AllmanBraceStyle); 18061 18062 verifyFormat("void f(int a)\n" 18063 "{\n" 18064 " switch (a)\n" 18065 " {\n" 18066 " case 0:\n" 18067 " break;\n" 18068 " case 1:\n" 18069 " {\n" 18070 " break;\n" 18071 " }\n" 18072 " case 2:\n" 18073 " {\n" 18074 " }\n" 18075 " break;\n" 18076 " default:\n" 18077 " break;\n" 18078 " }\n" 18079 "}\n", 18080 AllmanBraceStyle); 18081 18082 verifyFormat("enum X\n" 18083 "{\n" 18084 " Y = 0,\n" 18085 "}\n", 18086 AllmanBraceStyle); 18087 verifyFormat("enum X\n" 18088 "{\n" 18089 " Y = 0\n" 18090 "}\n", 18091 AllmanBraceStyle); 18092 18093 verifyFormat("@interface BSApplicationController ()\n" 18094 "{\n" 18095 "@private\n" 18096 " id _extraIvar;\n" 18097 "}\n" 18098 "@end\n", 18099 AllmanBraceStyle); 18100 18101 verifyFormat("#ifdef _DEBUG\n" 18102 "int foo(int i = 0)\n" 18103 "#else\n" 18104 "int foo(int i = 5)\n" 18105 "#endif\n" 18106 "{\n" 18107 " return i;\n" 18108 "}", 18109 AllmanBraceStyle); 18110 18111 verifyFormat("void foo() {}\n" 18112 "void bar()\n" 18113 "#ifdef _DEBUG\n" 18114 "{\n" 18115 " foo();\n" 18116 "}\n" 18117 "#else\n" 18118 "{\n" 18119 "}\n" 18120 "#endif", 18121 AllmanBraceStyle); 18122 18123 verifyFormat("void foobar() { int i = 5; }\n" 18124 "#ifdef _DEBUG\n" 18125 "void bar() {}\n" 18126 "#else\n" 18127 "void bar() { foobar(); }\n" 18128 "#endif", 18129 AllmanBraceStyle); 18130 18131 EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine, 18132 FormatStyle::SLS_All); 18133 18134 verifyFormat("[](int i) { return i + 2; };\n" 18135 "[](int i, int j)\n" 18136 "{\n" 18137 " auto x = i + j;\n" 18138 " auto y = i * j;\n" 18139 " return x ^ y;\n" 18140 "};\n" 18141 "void foo()\n" 18142 "{\n" 18143 " auto shortLambda = [](int i) { return i + 2; };\n" 18144 " auto longLambda = [](int i, int j)\n" 18145 " {\n" 18146 " auto x = i + j;\n" 18147 " auto y = i * j;\n" 18148 " return x ^ y;\n" 18149 " };\n" 18150 "}", 18151 AllmanBraceStyle); 18152 18153 AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 18154 18155 verifyFormat("[](int i)\n" 18156 "{\n" 18157 " return i + 2;\n" 18158 "};\n" 18159 "[](int i, int j)\n" 18160 "{\n" 18161 " auto x = i + j;\n" 18162 " auto y = i * j;\n" 18163 " return x ^ y;\n" 18164 "};\n" 18165 "void foo()\n" 18166 "{\n" 18167 " auto shortLambda = [](int i)\n" 18168 " {\n" 18169 " return i + 2;\n" 18170 " };\n" 18171 " auto longLambda = [](int i, int j)\n" 18172 " {\n" 18173 " auto x = i + j;\n" 18174 " auto y = i * j;\n" 18175 " return x ^ y;\n" 18176 " };\n" 18177 "}", 18178 AllmanBraceStyle); 18179 18180 // Reset 18181 AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All; 18182 18183 // This shouldn't affect ObjC blocks.. 18184 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n" 18185 " // ...\n" 18186 " int i;\n" 18187 "}];", 18188 AllmanBraceStyle); 18189 verifyFormat("void (^block)(void) = ^{\n" 18190 " // ...\n" 18191 " int i;\n" 18192 "};", 18193 AllmanBraceStyle); 18194 // .. or dict literals. 18195 verifyFormat("void f()\n" 18196 "{\n" 18197 " // ...\n" 18198 " [object someMethod:@{@\"a\" : @\"b\"}];\n" 18199 "}", 18200 AllmanBraceStyle); 18201 verifyFormat("void f()\n" 18202 "{\n" 18203 " // ...\n" 18204 " [object someMethod:@{a : @\"b\"}];\n" 18205 "}", 18206 AllmanBraceStyle); 18207 verifyFormat("int f()\n" 18208 "{ // comment\n" 18209 " return 42;\n" 18210 "}", 18211 AllmanBraceStyle); 18212 18213 AllmanBraceStyle.ColumnLimit = 19; 18214 verifyFormat("void f() { int i; }", AllmanBraceStyle); 18215 AllmanBraceStyle.ColumnLimit = 18; 18216 verifyFormat("void f()\n" 18217 "{\n" 18218 " int i;\n" 18219 "}", 18220 AllmanBraceStyle); 18221 AllmanBraceStyle.ColumnLimit = 80; 18222 18223 FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle; 18224 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = 18225 FormatStyle::SIS_WithoutElse; 18226 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true; 18227 verifyFormat("void f(bool b)\n" 18228 "{\n" 18229 " if (b)\n" 18230 " {\n" 18231 " return;\n" 18232 " }\n" 18233 "}\n", 18234 BreakBeforeBraceShortIfs); 18235 verifyFormat("void f(bool b)\n" 18236 "{\n" 18237 " if constexpr (b)\n" 18238 " {\n" 18239 " return;\n" 18240 " }\n" 18241 "}\n", 18242 BreakBeforeBraceShortIfs); 18243 verifyFormat("void f(bool b)\n" 18244 "{\n" 18245 " if CONSTEXPR (b)\n" 18246 " {\n" 18247 " return;\n" 18248 " }\n" 18249 "}\n", 18250 BreakBeforeBraceShortIfs); 18251 verifyFormat("void f(bool b)\n" 18252 "{\n" 18253 " if (b) return;\n" 18254 "}\n", 18255 BreakBeforeBraceShortIfs); 18256 verifyFormat("void f(bool b)\n" 18257 "{\n" 18258 " if constexpr (b) return;\n" 18259 "}\n", 18260 BreakBeforeBraceShortIfs); 18261 verifyFormat("void f(bool b)\n" 18262 "{\n" 18263 " if CONSTEXPR (b) return;\n" 18264 "}\n", 18265 BreakBeforeBraceShortIfs); 18266 verifyFormat("void f(bool b)\n" 18267 "{\n" 18268 " while (b)\n" 18269 " {\n" 18270 " return;\n" 18271 " }\n" 18272 "}\n", 18273 BreakBeforeBraceShortIfs); 18274 } 18275 18276 TEST_F(FormatTest, WhitesmithsBraceBreaking) { 18277 FormatStyle WhitesmithsBraceStyle = getLLVMStyleWithColumns(0); 18278 WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 18279 18280 // Make a few changes to the style for testing purposes 18281 WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine = 18282 FormatStyle::SFS_Empty; 18283 WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 18284 18285 // FIXME: this test case can't decide whether there should be a blank line 18286 // after the ~D() line or not. It adds one if one doesn't exist in the test 18287 // and it removes the line if one exists. 18288 /* 18289 verifyFormat("class A;\n" 18290 "namespace B\n" 18291 " {\n" 18292 "class C;\n" 18293 "// Comment\n" 18294 "class D\n" 18295 " {\n" 18296 "public:\n" 18297 " D();\n" 18298 " ~D() {}\n" 18299 "private:\n" 18300 " enum E\n" 18301 " {\n" 18302 " F\n" 18303 " }\n" 18304 " };\n" 18305 " } // namespace B\n", 18306 WhitesmithsBraceStyle); 18307 */ 18308 18309 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None; 18310 verifyFormat("namespace a\n" 18311 " {\n" 18312 "class A\n" 18313 " {\n" 18314 " void f()\n" 18315 " {\n" 18316 " if (true)\n" 18317 " {\n" 18318 " a();\n" 18319 " b();\n" 18320 " }\n" 18321 " }\n" 18322 " void g()\n" 18323 " {\n" 18324 " return;\n" 18325 " }\n" 18326 " };\n" 18327 "struct B\n" 18328 " {\n" 18329 " int x;\n" 18330 " };\n" 18331 " } // namespace a", 18332 WhitesmithsBraceStyle); 18333 18334 verifyFormat("namespace a\n" 18335 " {\n" 18336 "namespace b\n" 18337 " {\n" 18338 "class A\n" 18339 " {\n" 18340 " void f()\n" 18341 " {\n" 18342 " if (true)\n" 18343 " {\n" 18344 " a();\n" 18345 " b();\n" 18346 " }\n" 18347 " }\n" 18348 " void g()\n" 18349 " {\n" 18350 " return;\n" 18351 " }\n" 18352 " };\n" 18353 "struct B\n" 18354 " {\n" 18355 " int x;\n" 18356 " };\n" 18357 " } // namespace b\n" 18358 " } // namespace a", 18359 WhitesmithsBraceStyle); 18360 18361 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner; 18362 verifyFormat("namespace a\n" 18363 " {\n" 18364 "namespace b\n" 18365 " {\n" 18366 " class A\n" 18367 " {\n" 18368 " void f()\n" 18369 " {\n" 18370 " if (true)\n" 18371 " {\n" 18372 " a();\n" 18373 " b();\n" 18374 " }\n" 18375 " }\n" 18376 " void g()\n" 18377 " {\n" 18378 " return;\n" 18379 " }\n" 18380 " };\n" 18381 " struct B\n" 18382 " {\n" 18383 " int x;\n" 18384 " };\n" 18385 " } // namespace b\n" 18386 " } // namespace a", 18387 WhitesmithsBraceStyle); 18388 18389 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All; 18390 verifyFormat("namespace a\n" 18391 " {\n" 18392 " namespace b\n" 18393 " {\n" 18394 " class A\n" 18395 " {\n" 18396 " void f()\n" 18397 " {\n" 18398 " if (true)\n" 18399 " {\n" 18400 " a();\n" 18401 " b();\n" 18402 " }\n" 18403 " }\n" 18404 " void g()\n" 18405 " {\n" 18406 " return;\n" 18407 " }\n" 18408 " };\n" 18409 " struct B\n" 18410 " {\n" 18411 " int x;\n" 18412 " };\n" 18413 " } // namespace b\n" 18414 " } // namespace a", 18415 WhitesmithsBraceStyle); 18416 18417 verifyFormat("void f()\n" 18418 " {\n" 18419 " if (true)\n" 18420 " {\n" 18421 " a();\n" 18422 " }\n" 18423 " else if (false)\n" 18424 " {\n" 18425 " b();\n" 18426 " }\n" 18427 " else\n" 18428 " {\n" 18429 " c();\n" 18430 " }\n" 18431 " }\n", 18432 WhitesmithsBraceStyle); 18433 18434 verifyFormat("void f()\n" 18435 " {\n" 18436 " for (int i = 0; i < 10; ++i)\n" 18437 " {\n" 18438 " a();\n" 18439 " }\n" 18440 " while (false)\n" 18441 " {\n" 18442 " b();\n" 18443 " }\n" 18444 " do\n" 18445 " {\n" 18446 " c();\n" 18447 " } while (false)\n" 18448 " }\n", 18449 WhitesmithsBraceStyle); 18450 18451 WhitesmithsBraceStyle.IndentCaseLabels = true; 18452 verifyFormat("void switchTest1(int a)\n" 18453 " {\n" 18454 " switch (a)\n" 18455 " {\n" 18456 " case 2:\n" 18457 " {\n" 18458 " }\n" 18459 " break;\n" 18460 " }\n" 18461 " }\n", 18462 WhitesmithsBraceStyle); 18463 18464 verifyFormat("void switchTest2(int a)\n" 18465 " {\n" 18466 " switch (a)\n" 18467 " {\n" 18468 " case 0:\n" 18469 " break;\n" 18470 " case 1:\n" 18471 " {\n" 18472 " break;\n" 18473 " }\n" 18474 " case 2:\n" 18475 " {\n" 18476 " }\n" 18477 " break;\n" 18478 " default:\n" 18479 " break;\n" 18480 " }\n" 18481 " }\n", 18482 WhitesmithsBraceStyle); 18483 18484 verifyFormat("void switchTest3(int a)\n" 18485 " {\n" 18486 " switch (a)\n" 18487 " {\n" 18488 " case 0:\n" 18489 " {\n" 18490 " foo(x);\n" 18491 " }\n" 18492 " break;\n" 18493 " default:\n" 18494 " {\n" 18495 " foo(1);\n" 18496 " }\n" 18497 " break;\n" 18498 " }\n" 18499 " }\n", 18500 WhitesmithsBraceStyle); 18501 18502 WhitesmithsBraceStyle.IndentCaseLabels = false; 18503 18504 verifyFormat("void switchTest4(int a)\n" 18505 " {\n" 18506 " switch (a)\n" 18507 " {\n" 18508 " case 2:\n" 18509 " {\n" 18510 " }\n" 18511 " break;\n" 18512 " }\n" 18513 " }\n", 18514 WhitesmithsBraceStyle); 18515 18516 verifyFormat("void switchTest5(int a)\n" 18517 " {\n" 18518 " switch (a)\n" 18519 " {\n" 18520 " case 0:\n" 18521 " break;\n" 18522 " case 1:\n" 18523 " {\n" 18524 " foo();\n" 18525 " break;\n" 18526 " }\n" 18527 " case 2:\n" 18528 " {\n" 18529 " }\n" 18530 " break;\n" 18531 " default:\n" 18532 " break;\n" 18533 " }\n" 18534 " }\n", 18535 WhitesmithsBraceStyle); 18536 18537 verifyFormat("void switchTest6(int a)\n" 18538 " {\n" 18539 " switch (a)\n" 18540 " {\n" 18541 " case 0:\n" 18542 " {\n" 18543 " foo(x);\n" 18544 " }\n" 18545 " break;\n" 18546 " default:\n" 18547 " {\n" 18548 " foo(1);\n" 18549 " }\n" 18550 " break;\n" 18551 " }\n" 18552 " }\n", 18553 WhitesmithsBraceStyle); 18554 18555 verifyFormat("enum X\n" 18556 " {\n" 18557 " Y = 0, // testing\n" 18558 " }\n", 18559 WhitesmithsBraceStyle); 18560 18561 verifyFormat("enum X\n" 18562 " {\n" 18563 " Y = 0\n" 18564 " }\n", 18565 WhitesmithsBraceStyle); 18566 verifyFormat("enum X\n" 18567 " {\n" 18568 " Y = 0,\n" 18569 " Z = 1\n" 18570 " };\n", 18571 WhitesmithsBraceStyle); 18572 18573 verifyFormat("@interface BSApplicationController ()\n" 18574 " {\n" 18575 "@private\n" 18576 " id _extraIvar;\n" 18577 " }\n" 18578 "@end\n", 18579 WhitesmithsBraceStyle); 18580 18581 verifyFormat("#ifdef _DEBUG\n" 18582 "int foo(int i = 0)\n" 18583 "#else\n" 18584 "int foo(int i = 5)\n" 18585 "#endif\n" 18586 " {\n" 18587 " return i;\n" 18588 " }", 18589 WhitesmithsBraceStyle); 18590 18591 verifyFormat("void foo() {}\n" 18592 "void bar()\n" 18593 "#ifdef _DEBUG\n" 18594 " {\n" 18595 " foo();\n" 18596 " }\n" 18597 "#else\n" 18598 " {\n" 18599 " }\n" 18600 "#endif", 18601 WhitesmithsBraceStyle); 18602 18603 verifyFormat("void foobar()\n" 18604 " {\n" 18605 " int i = 5;\n" 18606 " }\n" 18607 "#ifdef _DEBUG\n" 18608 "void bar()\n" 18609 " {\n" 18610 " }\n" 18611 "#else\n" 18612 "void bar()\n" 18613 " {\n" 18614 " foobar();\n" 18615 " }\n" 18616 "#endif", 18617 WhitesmithsBraceStyle); 18618 18619 // This shouldn't affect ObjC blocks.. 18620 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n" 18621 " // ...\n" 18622 " int i;\n" 18623 "}];", 18624 WhitesmithsBraceStyle); 18625 verifyFormat("void (^block)(void) = ^{\n" 18626 " // ...\n" 18627 " int i;\n" 18628 "};", 18629 WhitesmithsBraceStyle); 18630 // .. or dict literals. 18631 verifyFormat("void f()\n" 18632 " {\n" 18633 " [object someMethod:@{@\"a\" : @\"b\"}];\n" 18634 " }", 18635 WhitesmithsBraceStyle); 18636 18637 verifyFormat("int f()\n" 18638 " { // comment\n" 18639 " return 42;\n" 18640 " }", 18641 WhitesmithsBraceStyle); 18642 18643 FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle; 18644 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = 18645 FormatStyle::SIS_OnlyFirstIf; 18646 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true; 18647 verifyFormat("void f(bool b)\n" 18648 " {\n" 18649 " if (b)\n" 18650 " {\n" 18651 " return;\n" 18652 " }\n" 18653 " }\n", 18654 BreakBeforeBraceShortIfs); 18655 verifyFormat("void f(bool b)\n" 18656 " {\n" 18657 " if (b) return;\n" 18658 " }\n", 18659 BreakBeforeBraceShortIfs); 18660 verifyFormat("void f(bool b)\n" 18661 " {\n" 18662 " while (b)\n" 18663 " {\n" 18664 " return;\n" 18665 " }\n" 18666 " }\n", 18667 BreakBeforeBraceShortIfs); 18668 } 18669 18670 TEST_F(FormatTest, GNUBraceBreaking) { 18671 FormatStyle GNUBraceStyle = getLLVMStyle(); 18672 GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU; 18673 verifyFormat("namespace a\n" 18674 "{\n" 18675 "class A\n" 18676 "{\n" 18677 " void f()\n" 18678 " {\n" 18679 " int a;\n" 18680 " {\n" 18681 " int b;\n" 18682 " }\n" 18683 " if (true)\n" 18684 " {\n" 18685 " a();\n" 18686 " b();\n" 18687 " }\n" 18688 " }\n" 18689 " void g() { return; }\n" 18690 "}\n" 18691 "} // namespace a", 18692 GNUBraceStyle); 18693 18694 verifyFormat("void f()\n" 18695 "{\n" 18696 " if (true)\n" 18697 " {\n" 18698 " a();\n" 18699 " }\n" 18700 " else if (false)\n" 18701 " {\n" 18702 " b();\n" 18703 " }\n" 18704 " else\n" 18705 " {\n" 18706 " c();\n" 18707 " }\n" 18708 "}\n", 18709 GNUBraceStyle); 18710 18711 verifyFormat("void f()\n" 18712 "{\n" 18713 " for (int i = 0; i < 10; ++i)\n" 18714 " {\n" 18715 " a();\n" 18716 " }\n" 18717 " while (false)\n" 18718 " {\n" 18719 " b();\n" 18720 " }\n" 18721 " do\n" 18722 " {\n" 18723 " c();\n" 18724 " }\n" 18725 " while (false);\n" 18726 "}\n", 18727 GNUBraceStyle); 18728 18729 verifyFormat("void f(int a)\n" 18730 "{\n" 18731 " switch (a)\n" 18732 " {\n" 18733 " case 0:\n" 18734 " break;\n" 18735 " case 1:\n" 18736 " {\n" 18737 " break;\n" 18738 " }\n" 18739 " case 2:\n" 18740 " {\n" 18741 " }\n" 18742 " break;\n" 18743 " default:\n" 18744 " break;\n" 18745 " }\n" 18746 "}\n", 18747 GNUBraceStyle); 18748 18749 verifyFormat("enum X\n" 18750 "{\n" 18751 " Y = 0,\n" 18752 "}\n", 18753 GNUBraceStyle); 18754 18755 verifyFormat("@interface BSApplicationController ()\n" 18756 "{\n" 18757 "@private\n" 18758 " id _extraIvar;\n" 18759 "}\n" 18760 "@end\n", 18761 GNUBraceStyle); 18762 18763 verifyFormat("#ifdef _DEBUG\n" 18764 "int foo(int i = 0)\n" 18765 "#else\n" 18766 "int foo(int i = 5)\n" 18767 "#endif\n" 18768 "{\n" 18769 " return i;\n" 18770 "}", 18771 GNUBraceStyle); 18772 18773 verifyFormat("void foo() {}\n" 18774 "void bar()\n" 18775 "#ifdef _DEBUG\n" 18776 "{\n" 18777 " foo();\n" 18778 "}\n" 18779 "#else\n" 18780 "{\n" 18781 "}\n" 18782 "#endif", 18783 GNUBraceStyle); 18784 18785 verifyFormat("void foobar() { int i = 5; }\n" 18786 "#ifdef _DEBUG\n" 18787 "void bar() {}\n" 18788 "#else\n" 18789 "void bar() { foobar(); }\n" 18790 "#endif", 18791 GNUBraceStyle); 18792 } 18793 18794 TEST_F(FormatTest, WebKitBraceBreaking) { 18795 FormatStyle WebKitBraceStyle = getLLVMStyle(); 18796 WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit; 18797 WebKitBraceStyle.FixNamespaceComments = false; 18798 verifyFormat("namespace a {\n" 18799 "class A {\n" 18800 " void f()\n" 18801 " {\n" 18802 " if (true) {\n" 18803 " a();\n" 18804 " b();\n" 18805 " }\n" 18806 " }\n" 18807 " void g() { return; }\n" 18808 "};\n" 18809 "enum E {\n" 18810 " A,\n" 18811 " // foo\n" 18812 " B,\n" 18813 " C\n" 18814 "};\n" 18815 "struct B {\n" 18816 " int x;\n" 18817 "};\n" 18818 "}\n", 18819 WebKitBraceStyle); 18820 verifyFormat("struct S {\n" 18821 " int Type;\n" 18822 " union {\n" 18823 " int x;\n" 18824 " double y;\n" 18825 " } Value;\n" 18826 " class C {\n" 18827 " MyFavoriteType Value;\n" 18828 " } Class;\n" 18829 "};\n", 18830 WebKitBraceStyle); 18831 } 18832 18833 TEST_F(FormatTest, CatchExceptionReferenceBinding) { 18834 verifyFormat("void f() {\n" 18835 " try {\n" 18836 " } catch (const Exception &e) {\n" 18837 " }\n" 18838 "}\n", 18839 getLLVMStyle()); 18840 } 18841 18842 TEST_F(FormatTest, CatchAlignArrayOfStructuresRightAlignment) { 18843 auto Style = getLLVMStyle(); 18844 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 18845 Style.AlignConsecutiveAssignments = 18846 FormatStyle::AlignConsecutiveStyle::ACS_Consecutive; 18847 Style.AlignConsecutiveDeclarations = 18848 FormatStyle::AlignConsecutiveStyle::ACS_Consecutive; 18849 verifyFormat("struct test demo[] = {\n" 18850 " {56, 23, \"hello\"},\n" 18851 " {-1, 93463, \"world\"},\n" 18852 " { 7, 5, \"!!\"}\n" 18853 "};\n", 18854 Style); 18855 18856 verifyFormat("struct test demo[] = {\n" 18857 " {56, 23, \"hello\"}, // first line\n" 18858 " {-1, 93463, \"world\"}, // second line\n" 18859 " { 7, 5, \"!!\"} // third line\n" 18860 "};\n", 18861 Style); 18862 18863 verifyFormat("struct test demo[4] = {\n" 18864 " { 56, 23, 21, \"oh\"}, // first line\n" 18865 " { -1, 93463, 22, \"my\"}, // second line\n" 18866 " { 7, 5, 1, \"goodness\"} // third line\n" 18867 " {234, 5, 1, \"gracious\"} // fourth line\n" 18868 "};\n", 18869 Style); 18870 18871 verifyFormat("struct test demo[3] = {\n" 18872 " {56, 23, \"hello\"},\n" 18873 " {-1, 93463, \"world\"},\n" 18874 " { 7, 5, \"!!\"}\n" 18875 "};\n", 18876 Style); 18877 18878 verifyFormat("struct test demo[3] = {\n" 18879 " {int{56}, 23, \"hello\"},\n" 18880 " {int{-1}, 93463, \"world\"},\n" 18881 " { int{7}, 5, \"!!\"}\n" 18882 "};\n", 18883 Style); 18884 18885 verifyFormat("struct test demo[] = {\n" 18886 " {56, 23, \"hello\"},\n" 18887 " {-1, 93463, \"world\"},\n" 18888 " { 7, 5, \"!!\"},\n" 18889 "};\n", 18890 Style); 18891 18892 verifyFormat("test demo[] = {\n" 18893 " {56, 23, \"hello\"},\n" 18894 " {-1, 93463, \"world\"},\n" 18895 " { 7, 5, \"!!\"},\n" 18896 "};\n", 18897 Style); 18898 18899 verifyFormat("demo = std::array<struct test, 3>{\n" 18900 " test{56, 23, \"hello\"},\n" 18901 " test{-1, 93463, \"world\"},\n" 18902 " test{ 7, 5, \"!!\"},\n" 18903 "};\n", 18904 Style); 18905 18906 verifyFormat("test demo[] = {\n" 18907 " {56, 23, \"hello\"},\n" 18908 "#if X\n" 18909 " {-1, 93463, \"world\"},\n" 18910 "#endif\n" 18911 " { 7, 5, \"!!\"}\n" 18912 "};\n", 18913 Style); 18914 18915 verifyFormat( 18916 "test demo[] = {\n" 18917 " { 7, 23,\n" 18918 " \"hello world i am a very long line that really, in any\"\n" 18919 " \"just world, ought to be split over multiple lines\"},\n" 18920 " {-1, 93463, \"world\"},\n" 18921 " {56, 5, \"!!\"}\n" 18922 "};\n", 18923 Style); 18924 18925 verifyFormat("return GradForUnaryCwise(g, {\n" 18926 " {{\"sign\"}, \"Sign\", " 18927 " {\"x\", \"dy\"}},\n" 18928 " { {\"dx\"}, \"Mul\", {\"dy\"" 18929 ", \"sign\"}},\n" 18930 "});\n", 18931 Style); 18932 18933 Style.ColumnLimit = 0; 18934 EXPECT_EQ( 18935 "test demo[] = {\n" 18936 " {56, 23, \"hello world i am a very long line that really, " 18937 "in any just world, ought to be split over multiple lines\"},\n" 18938 " {-1, 93463, " 18939 " \"world\"},\n" 18940 " { 7, 5, " 18941 " \"!!\"},\n" 18942 "};", 18943 format("test demo[] = {{56, 23, \"hello world i am a very long line " 18944 "that really, in any just world, ought to be split over multiple " 18945 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 18946 Style)); 18947 18948 Style.ColumnLimit = 80; 18949 verifyFormat("test demo[] = {\n" 18950 " {56, 23, /* a comment */ \"hello\"},\n" 18951 " {-1, 93463, \"world\"},\n" 18952 " { 7, 5, \"!!\"}\n" 18953 "};\n", 18954 Style); 18955 18956 verifyFormat("test demo[] = {\n" 18957 " {56, 23, \"hello\"},\n" 18958 " {-1, 93463, \"world\" /* comment here */},\n" 18959 " { 7, 5, \"!!\"}\n" 18960 "};\n", 18961 Style); 18962 18963 verifyFormat("test demo[] = {\n" 18964 " {56, /* a comment */ 23, \"hello\"},\n" 18965 " {-1, 93463, \"world\"},\n" 18966 " { 7, 5, \"!!\"}\n" 18967 "};\n", 18968 Style); 18969 18970 Style.ColumnLimit = 20; 18971 EXPECT_EQ( 18972 "demo = std::array<\n" 18973 " struct test, 3>{\n" 18974 " test{\n" 18975 " 56, 23,\n" 18976 " \"hello \"\n" 18977 " \"world i \"\n" 18978 " \"am a very \"\n" 18979 " \"long line \"\n" 18980 " \"that \"\n" 18981 " \"really, \"\n" 18982 " \"in any \"\n" 18983 " \"just \"\n" 18984 " \"world, \"\n" 18985 " \"ought to \"\n" 18986 " \"be split \"\n" 18987 " \"over \"\n" 18988 " \"multiple \"\n" 18989 " \"lines\"},\n" 18990 " test{-1, 93463,\n" 18991 " \"world\"},\n" 18992 " test{ 7, 5,\n" 18993 " \"!!\" },\n" 18994 "};", 18995 format("demo = std::array<struct test, 3>{test{56, 23, \"hello world " 18996 "i am a very long line that really, in any just world, ought " 18997 "to be split over multiple lines\"},test{-1, 93463, \"world\"}," 18998 "test{7, 5, \"!!\"},};", 18999 Style)); 19000 // This caused a core dump by enabling Alignment in the LLVMStyle globally 19001 Style = getLLVMStyleWithColumns(50); 19002 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 19003 verifyFormat("static A x = {\n" 19004 " {{init1, init2, init3, init4},\n" 19005 " {init1, init2, init3, init4}}\n" 19006 "};", 19007 Style); 19008 Style.ColumnLimit = 100; 19009 EXPECT_EQ( 19010 "test demo[] = {\n" 19011 " {56, 23,\n" 19012 " \"hello world i am a very long line that really, in any just world" 19013 ", ought to be split over \"\n" 19014 " \"multiple lines\" },\n" 19015 " {-1, 93463, \"world\"},\n" 19016 " { 7, 5, \"!!\"},\n" 19017 "};", 19018 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19019 "that really, in any just world, ought to be split over multiple " 19020 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19021 Style)); 19022 19023 Style = getLLVMStyleWithColumns(50); 19024 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 19025 Style.AlignConsecutiveAssignments = 19026 FormatStyle::AlignConsecutiveStyle::ACS_Consecutive; 19027 Style.AlignConsecutiveDeclarations = 19028 FormatStyle::AlignConsecutiveStyle::ACS_Consecutive; 19029 verifyFormat("struct test demo[] = {\n" 19030 " {56, 23, \"hello\"},\n" 19031 " {-1, 93463, \"world\"},\n" 19032 " { 7, 5, \"!!\"}\n" 19033 "};\n" 19034 "static A x = {\n" 19035 " {{init1, init2, init3, init4},\n" 19036 " {init1, init2, init3, init4}}\n" 19037 "};", 19038 Style); 19039 Style.ColumnLimit = 100; 19040 Style.AlignConsecutiveAssignments = 19041 FormatStyle::AlignConsecutiveStyle::ACS_AcrossComments; 19042 Style.AlignConsecutiveDeclarations = 19043 FormatStyle::AlignConsecutiveStyle::ACS_AcrossComments; 19044 verifyFormat("struct test demo[] = {\n" 19045 " {56, 23, \"hello\"},\n" 19046 " {-1, 93463, \"world\"},\n" 19047 " { 7, 5, \"!!\"}\n" 19048 "};\n" 19049 "struct test demo[4] = {\n" 19050 " { 56, 23, 21, \"oh\"}, // first line\n" 19051 " { -1, 93463, 22, \"my\"}, // second line\n" 19052 " { 7, 5, 1, \"goodness\"} // third line\n" 19053 " {234, 5, 1, \"gracious\"} // fourth line\n" 19054 "};\n", 19055 Style); 19056 EXPECT_EQ( 19057 "test demo[] = {\n" 19058 " {56,\n" 19059 " \"hello world i am a very long line that really, in any just world" 19060 ", ought to be split over \"\n" 19061 " \"multiple lines\", 23},\n" 19062 " {-1, \"world\", 93463},\n" 19063 " { 7, \"!!\", 5},\n" 19064 "};", 19065 format("test demo[] = {{56, \"hello world i am a very long line " 19066 "that really, in any just world, ought to be split over multiple " 19067 "lines\", 23},{-1, \"world\", 93463},{7, \"!!\", 5},};", 19068 Style)); 19069 } 19070 19071 TEST_F(FormatTest, CatchAlignArrayOfStructuresLeftAlignment) { 19072 auto Style = getLLVMStyle(); 19073 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 19074 /* FIXME: This case gets misformatted. 19075 verifyFormat("auto foo = Items{\n" 19076 " Section{0, bar(), },\n" 19077 " Section{1, boo() }\n" 19078 "};\n", 19079 Style); 19080 */ 19081 verifyFormat("auto foo = Items{\n" 19082 " Section{\n" 19083 " 0, bar(),\n" 19084 " }\n" 19085 "};\n", 19086 Style); 19087 verifyFormat("struct test demo[] = {\n" 19088 " {56, 23, \"hello\"},\n" 19089 " {-1, 93463, \"world\"},\n" 19090 " {7, 5, \"!!\" }\n" 19091 "};\n", 19092 Style); 19093 verifyFormat("struct test demo[] = {\n" 19094 " {56, 23, \"hello\"}, // first line\n" 19095 " {-1, 93463, \"world\"}, // second line\n" 19096 " {7, 5, \"!!\" } // third line\n" 19097 "};\n", 19098 Style); 19099 verifyFormat("struct test demo[4] = {\n" 19100 " {56, 23, 21, \"oh\" }, // first line\n" 19101 " {-1, 93463, 22, \"my\" }, // second line\n" 19102 " {7, 5, 1, \"goodness\"} // third line\n" 19103 " {234, 5, 1, \"gracious\"} // fourth line\n" 19104 "};\n", 19105 Style); 19106 verifyFormat("struct test demo[3] = {\n" 19107 " {56, 23, \"hello\"},\n" 19108 " {-1, 93463, \"world\"},\n" 19109 " {7, 5, \"!!\" }\n" 19110 "};\n", 19111 Style); 19112 19113 verifyFormat("struct test demo[3] = {\n" 19114 " {int{56}, 23, \"hello\"},\n" 19115 " {int{-1}, 93463, \"world\"},\n" 19116 " {int{7}, 5, \"!!\" }\n" 19117 "};\n", 19118 Style); 19119 verifyFormat("struct test demo[] = {\n" 19120 " {56, 23, \"hello\"},\n" 19121 " {-1, 93463, \"world\"},\n" 19122 " {7, 5, \"!!\" },\n" 19123 "};\n", 19124 Style); 19125 verifyFormat("test demo[] = {\n" 19126 " {56, 23, \"hello\"},\n" 19127 " {-1, 93463, \"world\"},\n" 19128 " {7, 5, \"!!\" },\n" 19129 "};\n", 19130 Style); 19131 verifyFormat("demo = std::array<struct test, 3>{\n" 19132 " test{56, 23, \"hello\"},\n" 19133 " test{-1, 93463, \"world\"},\n" 19134 " test{7, 5, \"!!\" },\n" 19135 "};\n", 19136 Style); 19137 verifyFormat("test demo[] = {\n" 19138 " {56, 23, \"hello\"},\n" 19139 "#if X\n" 19140 " {-1, 93463, \"world\"},\n" 19141 "#endif\n" 19142 " {7, 5, \"!!\" }\n" 19143 "};\n", 19144 Style); 19145 verifyFormat( 19146 "test demo[] = {\n" 19147 " {7, 23,\n" 19148 " \"hello world i am a very long line that really, in any\"\n" 19149 " \"just world, ought to be split over multiple lines\"},\n" 19150 " {-1, 93463, \"world\" },\n" 19151 " {56, 5, \"!!\" }\n" 19152 "};\n", 19153 Style); 19154 19155 verifyFormat("return GradForUnaryCwise(g, {\n" 19156 " {{\"sign\"}, \"Sign\", {\"x\", " 19157 "\"dy\"} },\n" 19158 " {{\"dx\"}, \"Mul\", " 19159 "{\"dy\", \"sign\"}},\n" 19160 "});\n", 19161 Style); 19162 19163 Style.ColumnLimit = 0; 19164 EXPECT_EQ( 19165 "test demo[] = {\n" 19166 " {56, 23, \"hello world i am a very long line that really, in any " 19167 "just world, ought to be split over multiple lines\"},\n" 19168 " {-1, 93463, \"world\" " 19169 " },\n" 19170 " {7, 5, \"!!\" " 19171 " },\n" 19172 "};", 19173 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19174 "that really, in any just world, ought to be split over multiple " 19175 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19176 Style)); 19177 19178 Style.ColumnLimit = 80; 19179 verifyFormat("test demo[] = {\n" 19180 " {56, 23, /* a comment */ \"hello\"},\n" 19181 " {-1, 93463, \"world\" },\n" 19182 " {7, 5, \"!!\" }\n" 19183 "};\n", 19184 Style); 19185 19186 verifyFormat("test demo[] = {\n" 19187 " {56, 23, \"hello\" },\n" 19188 " {-1, 93463, \"world\" /* comment here */},\n" 19189 " {7, 5, \"!!\" }\n" 19190 "};\n", 19191 Style); 19192 19193 verifyFormat("test demo[] = {\n" 19194 " {56, /* a comment */ 23, \"hello\"},\n" 19195 " {-1, 93463, \"world\"},\n" 19196 " {7, 5, \"!!\" }\n" 19197 "};\n", 19198 Style); 19199 19200 Style.ColumnLimit = 20; 19201 EXPECT_EQ( 19202 "demo = std::array<\n" 19203 " struct test, 3>{\n" 19204 " test{\n" 19205 " 56, 23,\n" 19206 " \"hello \"\n" 19207 " \"world i \"\n" 19208 " \"am a very \"\n" 19209 " \"long line \"\n" 19210 " \"that \"\n" 19211 " \"really, \"\n" 19212 " \"in any \"\n" 19213 " \"just \"\n" 19214 " \"world, \"\n" 19215 " \"ought to \"\n" 19216 " \"be split \"\n" 19217 " \"over \"\n" 19218 " \"multiple \"\n" 19219 " \"lines\"},\n" 19220 " test{-1, 93463,\n" 19221 " \"world\"},\n" 19222 " test{7, 5,\n" 19223 " \"!!\" },\n" 19224 "};", 19225 format("demo = std::array<struct test, 3>{test{56, 23, \"hello world " 19226 "i am a very long line that really, in any just world, ought " 19227 "to be split over multiple lines\"},test{-1, 93463, \"world\"}," 19228 "test{7, 5, \"!!\"},};", 19229 Style)); 19230 19231 // This caused a core dump by enabling Alignment in the LLVMStyle globally 19232 Style = getLLVMStyleWithColumns(50); 19233 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 19234 verifyFormat("static A x = {\n" 19235 " {{init1, init2, init3, init4},\n" 19236 " {init1, init2, init3, init4}}\n" 19237 "};", 19238 Style); 19239 Style.ColumnLimit = 100; 19240 EXPECT_EQ( 19241 "test demo[] = {\n" 19242 " {56, 23,\n" 19243 " \"hello world i am a very long line that really, in any just world" 19244 ", ought to be split over \"\n" 19245 " \"multiple lines\" },\n" 19246 " {-1, 93463, \"world\"},\n" 19247 " {7, 5, \"!!\" },\n" 19248 "};", 19249 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19250 "that really, in any just world, ought to be split over multiple " 19251 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19252 Style)); 19253 } 19254 19255 TEST_F(FormatTest, UnderstandsPragmas) { 19256 verifyFormat("#pragma omp reduction(| : var)"); 19257 verifyFormat("#pragma omp reduction(+ : var)"); 19258 19259 EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string " 19260 "(including parentheses).", 19261 format("#pragma mark Any non-hyphenated or hyphenated string " 19262 "(including parentheses).")); 19263 } 19264 19265 TEST_F(FormatTest, UnderstandPragmaOption) { 19266 verifyFormat("#pragma option -C -A"); 19267 19268 EXPECT_EQ("#pragma option -C -A", format("#pragma option -C -A")); 19269 } 19270 19271 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) { 19272 FormatStyle Style = getLLVMStyleWithColumns(20); 19273 19274 // See PR41213 19275 EXPECT_EQ("/*\n" 19276 " *\t9012345\n" 19277 " * /8901\n" 19278 " */", 19279 format("/*\n" 19280 " *\t9012345 /8901\n" 19281 " */", 19282 Style)); 19283 EXPECT_EQ("/*\n" 19284 " *345678\n" 19285 " *\t/8901\n" 19286 " */", 19287 format("/*\n" 19288 " *345678\t/8901\n" 19289 " */", 19290 Style)); 19291 19292 verifyFormat("int a; // the\n" 19293 " // comment", 19294 Style); 19295 EXPECT_EQ("int a; /* first line\n" 19296 " * second\n" 19297 " * line third\n" 19298 " * line\n" 19299 " */", 19300 format("int a; /* first line\n" 19301 " * second\n" 19302 " * line third\n" 19303 " * line\n" 19304 " */", 19305 Style)); 19306 EXPECT_EQ("int a; // first line\n" 19307 " // second\n" 19308 " // line third\n" 19309 " // line", 19310 format("int a; // first line\n" 19311 " // second line\n" 19312 " // third line", 19313 Style)); 19314 19315 Style.PenaltyExcessCharacter = 90; 19316 verifyFormat("int a; // the comment", Style); 19317 EXPECT_EQ("int a; // the comment\n" 19318 " // aaa", 19319 format("int a; // the comment aaa", Style)); 19320 EXPECT_EQ("int a; /* first line\n" 19321 " * second line\n" 19322 " * third line\n" 19323 " */", 19324 format("int a; /* first line\n" 19325 " * second line\n" 19326 " * third line\n" 19327 " */", 19328 Style)); 19329 EXPECT_EQ("int a; // first line\n" 19330 " // second line\n" 19331 " // third line", 19332 format("int a; // first line\n" 19333 " // second line\n" 19334 " // third line", 19335 Style)); 19336 // FIXME: Investigate why this is not getting the same layout as the test 19337 // above. 19338 EXPECT_EQ("int a; /* first line\n" 19339 " * second line\n" 19340 " * third line\n" 19341 " */", 19342 format("int a; /* first line second line third line" 19343 "\n*/", 19344 Style)); 19345 19346 EXPECT_EQ("// foo bar baz bazfoo\n" 19347 "// foo bar foo bar\n", 19348 format("// foo bar baz bazfoo\n" 19349 "// foo bar foo bar\n", 19350 Style)); 19351 EXPECT_EQ("// foo bar baz bazfoo\n" 19352 "// foo bar foo bar\n", 19353 format("// foo bar baz bazfoo\n" 19354 "// foo bar foo bar\n", 19355 Style)); 19356 19357 // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the 19358 // next one. 19359 EXPECT_EQ("// foo bar baz bazfoo\n" 19360 "// bar foo bar\n", 19361 format("// foo bar baz bazfoo bar\n" 19362 "// foo bar\n", 19363 Style)); 19364 19365 EXPECT_EQ("// foo bar baz bazfoo\n" 19366 "// foo bar baz bazfoo\n" 19367 "// bar foo bar\n", 19368 format("// foo bar baz bazfoo\n" 19369 "// foo bar baz bazfoo bar\n" 19370 "// foo bar\n", 19371 Style)); 19372 19373 EXPECT_EQ("// foo bar baz bazfoo\n" 19374 "// foo bar baz bazfoo\n" 19375 "// bar foo bar\n", 19376 format("// foo bar baz bazfoo\n" 19377 "// foo bar baz bazfoo bar\n" 19378 "// foo bar\n", 19379 Style)); 19380 19381 // Make sure we do not keep protruding characters if strict mode reflow is 19382 // cheaper than keeping protruding characters. 19383 Style.ColumnLimit = 21; 19384 EXPECT_EQ( 19385 "// foo foo foo foo\n" 19386 "// foo foo foo foo\n" 19387 "// foo foo foo foo\n", 19388 format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style)); 19389 19390 EXPECT_EQ("int a = /* long block\n" 19391 " comment */\n" 19392 " 42;", 19393 format("int a = /* long block comment */ 42;", Style)); 19394 } 19395 19396 TEST_F(FormatTest, BreakPenaltyAfterLParen) { 19397 FormatStyle Style = getLLVMStyle(); 19398 Style.ColumnLimit = 8; 19399 Style.PenaltyExcessCharacter = 15; 19400 verifyFormat("int foo(\n" 19401 " int aaaaaaaaaaaaaaaaaaaaaaaa);", 19402 Style); 19403 Style.PenaltyBreakOpenParenthesis = 200; 19404 EXPECT_EQ("int foo(int aaaaaaaaaaaaaaaaaaaaaaaa);", 19405 format("int foo(\n" 19406 " int aaaaaaaaaaaaaaaaaaaaaaaa);", 19407 Style)); 19408 } 19409 19410 TEST_F(FormatTest, BreakPenaltyAfterCastLParen) { 19411 FormatStyle Style = getLLVMStyle(); 19412 Style.ColumnLimit = 5; 19413 Style.PenaltyExcessCharacter = 150; 19414 verifyFormat("foo((\n" 19415 " int)aaaaaaaaaaaaaaaaaaaaaaaa);", 19416 19417 Style); 19418 Style.PenaltyBreakOpenParenthesis = 100000; 19419 EXPECT_EQ("foo((int)\n" 19420 " aaaaaaaaaaaaaaaaaaaaaaaa);", 19421 format("foo((\n" 19422 "int)aaaaaaaaaaaaaaaaaaaaaaaa);", 19423 Style)); 19424 } 19425 19426 TEST_F(FormatTest, BreakPenaltyAfterForLoopLParen) { 19427 FormatStyle Style = getLLVMStyle(); 19428 Style.ColumnLimit = 4; 19429 Style.PenaltyExcessCharacter = 100; 19430 verifyFormat("for (\n" 19431 " int iiiiiiiiiiiiiiiii =\n" 19432 " 0;\n" 19433 " iiiiiiiiiiiiiiiii <\n" 19434 " 2;\n" 19435 " iiiiiiiiiiiiiiiii++) {\n" 19436 "}", 19437 19438 Style); 19439 Style.PenaltyBreakOpenParenthesis = 1250; 19440 EXPECT_EQ("for (int iiiiiiiiiiiiiiiii =\n" 19441 " 0;\n" 19442 " iiiiiiiiiiiiiiiii <\n" 19443 " 2;\n" 19444 " iiiiiiiiiiiiiiiii++) {\n" 19445 "}", 19446 format("for (\n" 19447 " int iiiiiiiiiiiiiiiii =\n" 19448 " 0;\n" 19449 " iiiiiiiiiiiiiiiii <\n" 19450 " 2;\n" 19451 " iiiiiiiiiiiiiiiii++) {\n" 19452 "}", 19453 Style)); 19454 } 19455 19456 #define EXPECT_ALL_STYLES_EQUAL(Styles) \ 19457 for (size_t i = 1; i < Styles.size(); ++i) \ 19458 EXPECT_EQ(Styles[0], Styles[i]) \ 19459 << "Style #" << i << " of " << Styles.size() << " differs from Style #0" 19460 19461 TEST_F(FormatTest, GetsPredefinedStyleByName) { 19462 SmallVector<FormatStyle, 3> Styles; 19463 Styles.resize(3); 19464 19465 Styles[0] = getLLVMStyle(); 19466 EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1])); 19467 EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2])); 19468 EXPECT_ALL_STYLES_EQUAL(Styles); 19469 19470 Styles[0] = getGoogleStyle(); 19471 EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1])); 19472 EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2])); 19473 EXPECT_ALL_STYLES_EQUAL(Styles); 19474 19475 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript); 19476 EXPECT_TRUE( 19477 getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1])); 19478 EXPECT_TRUE( 19479 getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2])); 19480 EXPECT_ALL_STYLES_EQUAL(Styles); 19481 19482 Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp); 19483 EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1])); 19484 EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2])); 19485 EXPECT_ALL_STYLES_EQUAL(Styles); 19486 19487 Styles[0] = getMozillaStyle(); 19488 EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1])); 19489 EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2])); 19490 EXPECT_ALL_STYLES_EQUAL(Styles); 19491 19492 Styles[0] = getWebKitStyle(); 19493 EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1])); 19494 EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2])); 19495 EXPECT_ALL_STYLES_EQUAL(Styles); 19496 19497 Styles[0] = getGNUStyle(); 19498 EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1])); 19499 EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2])); 19500 EXPECT_ALL_STYLES_EQUAL(Styles); 19501 19502 EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0])); 19503 } 19504 19505 TEST_F(FormatTest, GetsCorrectBasedOnStyle) { 19506 SmallVector<FormatStyle, 8> Styles; 19507 Styles.resize(2); 19508 19509 Styles[0] = getGoogleStyle(); 19510 Styles[1] = getLLVMStyle(); 19511 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value()); 19512 EXPECT_ALL_STYLES_EQUAL(Styles); 19513 19514 Styles.resize(5); 19515 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript); 19516 Styles[1] = getLLVMStyle(); 19517 Styles[1].Language = FormatStyle::LK_JavaScript; 19518 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value()); 19519 19520 Styles[2] = getLLVMStyle(); 19521 Styles[2].Language = FormatStyle::LK_JavaScript; 19522 EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n" 19523 "BasedOnStyle: Google", 19524 &Styles[2]) 19525 .value()); 19526 19527 Styles[3] = getLLVMStyle(); 19528 Styles[3].Language = FormatStyle::LK_JavaScript; 19529 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n" 19530 "Language: JavaScript", 19531 &Styles[3]) 19532 .value()); 19533 19534 Styles[4] = getLLVMStyle(); 19535 Styles[4].Language = FormatStyle::LK_JavaScript; 19536 EXPECT_EQ(0, parseConfiguration("---\n" 19537 "BasedOnStyle: LLVM\n" 19538 "IndentWidth: 123\n" 19539 "---\n" 19540 "BasedOnStyle: Google\n" 19541 "Language: JavaScript", 19542 &Styles[4]) 19543 .value()); 19544 EXPECT_ALL_STYLES_EQUAL(Styles); 19545 } 19546 19547 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME) \ 19548 Style.FIELD = false; \ 19549 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value()); \ 19550 EXPECT_TRUE(Style.FIELD); \ 19551 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value()); \ 19552 EXPECT_FALSE(Style.FIELD); 19553 19554 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD) 19555 19556 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME) \ 19557 Style.STRUCT.FIELD = false; \ 19558 EXPECT_EQ(0, \ 19559 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": true", &Style) \ 19560 .value()); \ 19561 EXPECT_TRUE(Style.STRUCT.FIELD); \ 19562 EXPECT_EQ(0, \ 19563 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": false", &Style) \ 19564 .value()); \ 19565 EXPECT_FALSE(Style.STRUCT.FIELD); 19566 19567 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD) \ 19568 CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD) 19569 19570 #define CHECK_PARSE(TEXT, FIELD, VALUE) \ 19571 EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!"; \ 19572 EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value()); \ 19573 EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!" 19574 19575 TEST_F(FormatTest, ParsesConfigurationBools) { 19576 FormatStyle Style = {}; 19577 Style.Language = FormatStyle::LK_Cpp; 19578 CHECK_PARSE_BOOL(AlignTrailingComments); 19579 CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine); 19580 CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine); 19581 CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine); 19582 CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine); 19583 CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine); 19584 CHECK_PARSE_BOOL(BinPackArguments); 19585 CHECK_PARSE_BOOL(BinPackParameters); 19586 CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations); 19587 CHECK_PARSE_BOOL(BreakBeforeTernaryOperators); 19588 CHECK_PARSE_BOOL(BreakStringLiterals); 19589 CHECK_PARSE_BOOL(CompactNamespaces); 19590 CHECK_PARSE_BOOL(DeriveLineEnding); 19591 CHECK_PARSE_BOOL(DerivePointerAlignment); 19592 CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding"); 19593 CHECK_PARSE_BOOL(DisableFormat); 19594 CHECK_PARSE_BOOL(IndentAccessModifiers); 19595 CHECK_PARSE_BOOL(IndentCaseLabels); 19596 CHECK_PARSE_BOOL(IndentCaseBlocks); 19597 CHECK_PARSE_BOOL(IndentGotoLabels); 19598 CHECK_PARSE_BOOL_FIELD(IndentRequiresClause, "IndentRequires"); 19599 CHECK_PARSE_BOOL(IndentRequiresClause); 19600 CHECK_PARSE_BOOL(IndentWrappedFunctionNames); 19601 CHECK_PARSE_BOOL(InsertBraces); 19602 CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks); 19603 CHECK_PARSE_BOOL(ObjCSpaceAfterProperty); 19604 CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList); 19605 CHECK_PARSE_BOOL(Cpp11BracedListStyle); 19606 CHECK_PARSE_BOOL(ReflowComments); 19607 CHECK_PARSE_BOOL(RemoveBracesLLVM); 19608 CHECK_PARSE_BOOL(SortUsingDeclarations); 19609 CHECK_PARSE_BOOL(SpacesInParentheses); 19610 CHECK_PARSE_BOOL(SpacesInSquareBrackets); 19611 CHECK_PARSE_BOOL(SpacesInConditionalStatement); 19612 CHECK_PARSE_BOOL(SpaceInEmptyBlock); 19613 CHECK_PARSE_BOOL(SpaceInEmptyParentheses); 19614 CHECK_PARSE_BOOL(SpacesInContainerLiterals); 19615 CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses); 19616 CHECK_PARSE_BOOL(SpaceAfterCStyleCast); 19617 CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword); 19618 CHECK_PARSE_BOOL(SpaceAfterLogicalNot); 19619 CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators); 19620 CHECK_PARSE_BOOL(SpaceBeforeCaseColon); 19621 CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList); 19622 CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon); 19623 CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon); 19624 CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon); 19625 CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets); 19626 CHECK_PARSE_BOOL(UseCRLF); 19627 19628 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel); 19629 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass); 19630 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum); 19631 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction); 19632 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace); 19633 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration); 19634 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct); 19635 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion); 19636 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock); 19637 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch); 19638 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse); 19639 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody); 19640 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile); 19641 CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces); 19642 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction); 19643 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord); 19644 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace); 19645 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterControlStatements); 19646 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterForeachMacros); 19647 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, 19648 AfterFunctionDeclarationName); 19649 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, 19650 AfterFunctionDefinitionName); 19651 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterIfMacros); 19652 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterOverloadedOperator); 19653 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, BeforeNonEmptyParentheses); 19654 } 19655 19656 #undef CHECK_PARSE_BOOL 19657 19658 TEST_F(FormatTest, ParsesConfiguration) { 19659 FormatStyle Style = {}; 19660 Style.Language = FormatStyle::LK_Cpp; 19661 CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234); 19662 CHECK_PARSE("ConstructorInitializerIndentWidth: 1234", 19663 ConstructorInitializerIndentWidth, 1234u); 19664 CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u); 19665 CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u); 19666 CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u); 19667 CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u); 19668 CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234", 19669 PenaltyBreakBeforeFirstCallParameter, 1234u); 19670 CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234", 19671 PenaltyBreakTemplateDeclaration, 1234u); 19672 CHECK_PARSE("PenaltyBreakOpenParenthesis: 1234", PenaltyBreakOpenParenthesis, 19673 1234u); 19674 CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u); 19675 CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234", 19676 PenaltyReturnTypeOnItsOwnLine, 1234u); 19677 CHECK_PARSE("SpacesBeforeTrailingComments: 1234", 19678 SpacesBeforeTrailingComments, 1234u); 19679 CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u); 19680 CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u); 19681 CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$"); 19682 19683 Style.QualifierAlignment = FormatStyle::QAS_Right; 19684 CHECK_PARSE("QualifierAlignment: Leave", QualifierAlignment, 19685 FormatStyle::QAS_Leave); 19686 CHECK_PARSE("QualifierAlignment: Right", QualifierAlignment, 19687 FormatStyle::QAS_Right); 19688 CHECK_PARSE("QualifierAlignment: Left", QualifierAlignment, 19689 FormatStyle::QAS_Left); 19690 CHECK_PARSE("QualifierAlignment: Custom", QualifierAlignment, 19691 FormatStyle::QAS_Custom); 19692 19693 Style.QualifierOrder.clear(); 19694 CHECK_PARSE("QualifierOrder: [ const, volatile, type ]", QualifierOrder, 19695 std::vector<std::string>({"const", "volatile", "type"})); 19696 Style.QualifierOrder.clear(); 19697 CHECK_PARSE("QualifierOrder: [const, type]", QualifierOrder, 19698 std::vector<std::string>({"const", "type"})); 19699 Style.QualifierOrder.clear(); 19700 CHECK_PARSE("QualifierOrder: [volatile, type]", QualifierOrder, 19701 std::vector<std::string>({"volatile", "type"})); 19702 19703 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 19704 CHECK_PARSE("AlignConsecutiveAssignments: None", AlignConsecutiveAssignments, 19705 FormatStyle::ACS_None); 19706 CHECK_PARSE("AlignConsecutiveAssignments: Consecutive", 19707 AlignConsecutiveAssignments, FormatStyle::ACS_Consecutive); 19708 CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLines", 19709 AlignConsecutiveAssignments, FormatStyle::ACS_AcrossEmptyLines); 19710 CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLinesAndComments", 19711 AlignConsecutiveAssignments, 19712 FormatStyle::ACS_AcrossEmptyLinesAndComments); 19713 // For backwards compability, false / true should still parse 19714 CHECK_PARSE("AlignConsecutiveAssignments: false", AlignConsecutiveAssignments, 19715 FormatStyle::ACS_None); 19716 CHECK_PARSE("AlignConsecutiveAssignments: true", AlignConsecutiveAssignments, 19717 FormatStyle::ACS_Consecutive); 19718 19719 Style.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive; 19720 CHECK_PARSE("AlignConsecutiveBitFields: None", AlignConsecutiveBitFields, 19721 FormatStyle::ACS_None); 19722 CHECK_PARSE("AlignConsecutiveBitFields: Consecutive", 19723 AlignConsecutiveBitFields, FormatStyle::ACS_Consecutive); 19724 CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLines", 19725 AlignConsecutiveBitFields, FormatStyle::ACS_AcrossEmptyLines); 19726 CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLinesAndComments", 19727 AlignConsecutiveBitFields, 19728 FormatStyle::ACS_AcrossEmptyLinesAndComments); 19729 // For backwards compability, false / true should still parse 19730 CHECK_PARSE("AlignConsecutiveBitFields: false", AlignConsecutiveBitFields, 19731 FormatStyle::ACS_None); 19732 CHECK_PARSE("AlignConsecutiveBitFields: true", AlignConsecutiveBitFields, 19733 FormatStyle::ACS_Consecutive); 19734 19735 Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 19736 CHECK_PARSE("AlignConsecutiveMacros: None", AlignConsecutiveMacros, 19737 FormatStyle::ACS_None); 19738 CHECK_PARSE("AlignConsecutiveMacros: Consecutive", AlignConsecutiveMacros, 19739 FormatStyle::ACS_Consecutive); 19740 CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLines", 19741 AlignConsecutiveMacros, FormatStyle::ACS_AcrossEmptyLines); 19742 CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLinesAndComments", 19743 AlignConsecutiveMacros, 19744 FormatStyle::ACS_AcrossEmptyLinesAndComments); 19745 // For backwards compability, false / true should still parse 19746 CHECK_PARSE("AlignConsecutiveMacros: false", AlignConsecutiveMacros, 19747 FormatStyle::ACS_None); 19748 CHECK_PARSE("AlignConsecutiveMacros: true", AlignConsecutiveMacros, 19749 FormatStyle::ACS_Consecutive); 19750 19751 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 19752 CHECK_PARSE("AlignConsecutiveDeclarations: None", 19753 AlignConsecutiveDeclarations, FormatStyle::ACS_None); 19754 CHECK_PARSE("AlignConsecutiveDeclarations: Consecutive", 19755 AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive); 19756 CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLines", 19757 AlignConsecutiveDeclarations, FormatStyle::ACS_AcrossEmptyLines); 19758 CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLinesAndComments", 19759 AlignConsecutiveDeclarations, 19760 FormatStyle::ACS_AcrossEmptyLinesAndComments); 19761 // For backwards compability, false / true should still parse 19762 CHECK_PARSE("AlignConsecutiveDeclarations: false", 19763 AlignConsecutiveDeclarations, FormatStyle::ACS_None); 19764 CHECK_PARSE("AlignConsecutiveDeclarations: true", 19765 AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive); 19766 19767 Style.PointerAlignment = FormatStyle::PAS_Middle; 19768 CHECK_PARSE("PointerAlignment: Left", PointerAlignment, 19769 FormatStyle::PAS_Left); 19770 CHECK_PARSE("PointerAlignment: Right", PointerAlignment, 19771 FormatStyle::PAS_Right); 19772 CHECK_PARSE("PointerAlignment: Middle", PointerAlignment, 19773 FormatStyle::PAS_Middle); 19774 Style.ReferenceAlignment = FormatStyle::RAS_Middle; 19775 CHECK_PARSE("ReferenceAlignment: Pointer", ReferenceAlignment, 19776 FormatStyle::RAS_Pointer); 19777 CHECK_PARSE("ReferenceAlignment: Left", ReferenceAlignment, 19778 FormatStyle::RAS_Left); 19779 CHECK_PARSE("ReferenceAlignment: Right", ReferenceAlignment, 19780 FormatStyle::RAS_Right); 19781 CHECK_PARSE("ReferenceAlignment: Middle", ReferenceAlignment, 19782 FormatStyle::RAS_Middle); 19783 // For backward compatibility: 19784 CHECK_PARSE("PointerBindsToType: Left", PointerAlignment, 19785 FormatStyle::PAS_Left); 19786 CHECK_PARSE("PointerBindsToType: Right", PointerAlignment, 19787 FormatStyle::PAS_Right); 19788 CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment, 19789 FormatStyle::PAS_Middle); 19790 19791 Style.Standard = FormatStyle::LS_Auto; 19792 CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03); 19793 CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11); 19794 CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14); 19795 CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17); 19796 CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20); 19797 CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto); 19798 CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest); 19799 // Legacy aliases: 19800 CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03); 19801 CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest); 19802 CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03); 19803 CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11); 19804 19805 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 19806 CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment", 19807 BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment); 19808 CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators, 19809 FormatStyle::BOS_None); 19810 CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators, 19811 FormatStyle::BOS_All); 19812 // For backward compatibility: 19813 CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators, 19814 FormatStyle::BOS_None); 19815 CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators, 19816 FormatStyle::BOS_All); 19817 19818 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 19819 CHECK_PARSE("BreakConstructorInitializers: BeforeComma", 19820 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma); 19821 CHECK_PARSE("BreakConstructorInitializers: AfterColon", 19822 BreakConstructorInitializers, FormatStyle::BCIS_AfterColon); 19823 CHECK_PARSE("BreakConstructorInitializers: BeforeColon", 19824 BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon); 19825 // For backward compatibility: 19826 CHECK_PARSE("BreakConstructorInitializersBeforeComma: true", 19827 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma); 19828 19829 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 19830 CHECK_PARSE("BreakInheritanceList: AfterComma", BreakInheritanceList, 19831 FormatStyle::BILS_AfterComma); 19832 CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList, 19833 FormatStyle::BILS_BeforeComma); 19834 CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList, 19835 FormatStyle::BILS_AfterColon); 19836 CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList, 19837 FormatStyle::BILS_BeforeColon); 19838 // For backward compatibility: 19839 CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList, 19840 FormatStyle::BILS_BeforeComma); 19841 19842 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 19843 CHECK_PARSE("PackConstructorInitializers: Never", PackConstructorInitializers, 19844 FormatStyle::PCIS_Never); 19845 CHECK_PARSE("PackConstructorInitializers: BinPack", 19846 PackConstructorInitializers, FormatStyle::PCIS_BinPack); 19847 CHECK_PARSE("PackConstructorInitializers: CurrentLine", 19848 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 19849 CHECK_PARSE("PackConstructorInitializers: NextLine", 19850 PackConstructorInitializers, FormatStyle::PCIS_NextLine); 19851 // For backward compatibility: 19852 CHECK_PARSE("BasedOnStyle: Google\n" 19853 "ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 19854 "AllowAllConstructorInitializersOnNextLine: false", 19855 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 19856 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 19857 CHECK_PARSE("BasedOnStyle: Google\n" 19858 "ConstructorInitializerAllOnOneLineOrOnePerLine: false", 19859 PackConstructorInitializers, FormatStyle::PCIS_BinPack); 19860 CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 19861 "AllowAllConstructorInitializersOnNextLine: true", 19862 PackConstructorInitializers, FormatStyle::PCIS_NextLine); 19863 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 19864 CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 19865 "AllowAllConstructorInitializersOnNextLine: false", 19866 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 19867 19868 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 19869 CHECK_PARSE("EmptyLineBeforeAccessModifier: Never", 19870 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never); 19871 CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave", 19872 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave); 19873 CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock", 19874 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock); 19875 CHECK_PARSE("EmptyLineBeforeAccessModifier: Always", 19876 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always); 19877 19878 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 19879 CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket, 19880 FormatStyle::BAS_Align); 19881 CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket, 19882 FormatStyle::BAS_DontAlign); 19883 CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket, 19884 FormatStyle::BAS_AlwaysBreak); 19885 CHECK_PARSE("AlignAfterOpenBracket: BlockIndent", AlignAfterOpenBracket, 19886 FormatStyle::BAS_BlockIndent); 19887 // For backward compatibility: 19888 CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket, 19889 FormatStyle::BAS_DontAlign); 19890 CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket, 19891 FormatStyle::BAS_Align); 19892 19893 Style.AlignEscapedNewlines = FormatStyle::ENAS_Left; 19894 CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines, 19895 FormatStyle::ENAS_DontAlign); 19896 CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines, 19897 FormatStyle::ENAS_Left); 19898 CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines, 19899 FormatStyle::ENAS_Right); 19900 // For backward compatibility: 19901 CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines, 19902 FormatStyle::ENAS_Left); 19903 CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines, 19904 FormatStyle::ENAS_Right); 19905 19906 Style.AlignOperands = FormatStyle::OAS_Align; 19907 CHECK_PARSE("AlignOperands: DontAlign", AlignOperands, 19908 FormatStyle::OAS_DontAlign); 19909 CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align); 19910 CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands, 19911 FormatStyle::OAS_AlignAfterOperator); 19912 // For backward compatibility: 19913 CHECK_PARSE("AlignOperands: false", AlignOperands, 19914 FormatStyle::OAS_DontAlign); 19915 CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align); 19916 19917 Style.UseTab = FormatStyle::UT_ForIndentation; 19918 CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never); 19919 CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation); 19920 CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always); 19921 CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab, 19922 FormatStyle::UT_ForContinuationAndIndentation); 19923 CHECK_PARSE("UseTab: AlignWithSpaces", UseTab, 19924 FormatStyle::UT_AlignWithSpaces); 19925 // For backward compatibility: 19926 CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never); 19927 CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always); 19928 19929 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 19930 CHECK_PARSE("AllowShortBlocksOnASingleLine: Never", 19931 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 19932 CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty", 19933 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty); 19934 CHECK_PARSE("AllowShortBlocksOnASingleLine: Always", 19935 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always); 19936 // For backward compatibility: 19937 CHECK_PARSE("AllowShortBlocksOnASingleLine: false", 19938 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 19939 CHECK_PARSE("AllowShortBlocksOnASingleLine: true", 19940 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always); 19941 19942 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 19943 CHECK_PARSE("AllowShortFunctionsOnASingleLine: None", 19944 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None); 19945 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline", 19946 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline); 19947 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty", 19948 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty); 19949 CHECK_PARSE("AllowShortFunctionsOnASingleLine: All", 19950 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All); 19951 // For backward compatibility: 19952 CHECK_PARSE("AllowShortFunctionsOnASingleLine: false", 19953 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None); 19954 CHECK_PARSE("AllowShortFunctionsOnASingleLine: true", 19955 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All); 19956 19957 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both; 19958 CHECK_PARSE("SpaceAroundPointerQualifiers: Default", 19959 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default); 19960 CHECK_PARSE("SpaceAroundPointerQualifiers: Before", 19961 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before); 19962 CHECK_PARSE("SpaceAroundPointerQualifiers: After", 19963 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After); 19964 CHECK_PARSE("SpaceAroundPointerQualifiers: Both", 19965 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both); 19966 19967 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 19968 CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens, 19969 FormatStyle::SBPO_Never); 19970 CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens, 19971 FormatStyle::SBPO_Always); 19972 CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens, 19973 FormatStyle::SBPO_ControlStatements); 19974 CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptControlMacros", 19975 SpaceBeforeParens, 19976 FormatStyle::SBPO_ControlStatementsExceptControlMacros); 19977 CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens, 19978 FormatStyle::SBPO_NonEmptyParentheses); 19979 CHECK_PARSE("SpaceBeforeParens: Custom", SpaceBeforeParens, 19980 FormatStyle::SBPO_Custom); 19981 // For backward compatibility: 19982 CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens, 19983 FormatStyle::SBPO_Never); 19984 CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens, 19985 FormatStyle::SBPO_ControlStatements); 19986 CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptForEachMacros", 19987 SpaceBeforeParens, 19988 FormatStyle::SBPO_ControlStatementsExceptControlMacros); 19989 19990 Style.ColumnLimit = 123; 19991 FormatStyle BaseStyle = getLLVMStyle(); 19992 CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit); 19993 CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u); 19994 19995 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 19996 CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces, 19997 FormatStyle::BS_Attach); 19998 CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces, 19999 FormatStyle::BS_Linux); 20000 CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces, 20001 FormatStyle::BS_Mozilla); 20002 CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces, 20003 FormatStyle::BS_Stroustrup); 20004 CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces, 20005 FormatStyle::BS_Allman); 20006 CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces, 20007 FormatStyle::BS_Whitesmiths); 20008 CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU); 20009 CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces, 20010 FormatStyle::BS_WebKit); 20011 CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces, 20012 FormatStyle::BS_Custom); 20013 20014 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never; 20015 CHECK_PARSE("BraceWrapping:\n" 20016 " AfterControlStatement: MultiLine", 20017 BraceWrapping.AfterControlStatement, 20018 FormatStyle::BWACS_MultiLine); 20019 CHECK_PARSE("BraceWrapping:\n" 20020 " AfterControlStatement: Always", 20021 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always); 20022 CHECK_PARSE("BraceWrapping:\n" 20023 " AfterControlStatement: Never", 20024 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never); 20025 // For backward compatibility: 20026 CHECK_PARSE("BraceWrapping:\n" 20027 " AfterControlStatement: true", 20028 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always); 20029 CHECK_PARSE("BraceWrapping:\n" 20030 " AfterControlStatement: false", 20031 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never); 20032 20033 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 20034 CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType, 20035 FormatStyle::RTBS_None); 20036 CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType, 20037 FormatStyle::RTBS_All); 20038 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel", 20039 AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel); 20040 CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions", 20041 AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions); 20042 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions", 20043 AlwaysBreakAfterReturnType, 20044 FormatStyle::RTBS_TopLevelDefinitions); 20045 20046 Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 20047 CHECK_PARSE("AlwaysBreakTemplateDeclarations: No", 20048 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No); 20049 CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine", 20050 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine); 20051 CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes", 20052 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes); 20053 CHECK_PARSE("AlwaysBreakTemplateDeclarations: false", 20054 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine); 20055 CHECK_PARSE("AlwaysBreakTemplateDeclarations: true", 20056 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes); 20057 20058 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All; 20059 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None", 20060 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None); 20061 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All", 20062 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All); 20063 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel", 20064 AlwaysBreakAfterDefinitionReturnType, 20065 FormatStyle::DRTBS_TopLevel); 20066 20067 Style.NamespaceIndentation = FormatStyle::NI_All; 20068 CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation, 20069 FormatStyle::NI_None); 20070 CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation, 20071 FormatStyle::NI_Inner); 20072 CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation, 20073 FormatStyle::NI_All); 20074 20075 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_OnlyFirstIf; 20076 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never", 20077 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never); 20078 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse", 20079 AllowShortIfStatementsOnASingleLine, 20080 FormatStyle::SIS_WithoutElse); 20081 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: OnlyFirstIf", 20082 AllowShortIfStatementsOnASingleLine, 20083 FormatStyle::SIS_OnlyFirstIf); 20084 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: AllIfsAndElse", 20085 AllowShortIfStatementsOnASingleLine, 20086 FormatStyle::SIS_AllIfsAndElse); 20087 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always", 20088 AllowShortIfStatementsOnASingleLine, 20089 FormatStyle::SIS_OnlyFirstIf); 20090 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false", 20091 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never); 20092 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true", 20093 AllowShortIfStatementsOnASingleLine, 20094 FormatStyle::SIS_WithoutElse); 20095 20096 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 20097 CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock, 20098 FormatStyle::IEBS_AfterExternBlock); 20099 CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock, 20100 FormatStyle::IEBS_Indent); 20101 CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock, 20102 FormatStyle::IEBS_NoIndent); 20103 CHECK_PARSE("IndentExternBlock: true", IndentExternBlock, 20104 FormatStyle::IEBS_Indent); 20105 CHECK_PARSE("IndentExternBlock: false", IndentExternBlock, 20106 FormatStyle::IEBS_NoIndent); 20107 20108 Style.BitFieldColonSpacing = FormatStyle::BFCS_None; 20109 CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing, 20110 FormatStyle::BFCS_Both); 20111 CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing, 20112 FormatStyle::BFCS_None); 20113 CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing, 20114 FormatStyle::BFCS_Before); 20115 CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing, 20116 FormatStyle::BFCS_After); 20117 20118 Style.SortJavaStaticImport = FormatStyle::SJSIO_Before; 20119 CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport, 20120 FormatStyle::SJSIO_After); 20121 CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport, 20122 FormatStyle::SJSIO_Before); 20123 20124 // FIXME: This is required because parsing a configuration simply overwrites 20125 // the first N elements of the list instead of resetting it. 20126 Style.ForEachMacros.clear(); 20127 std::vector<std::string> BoostForeach; 20128 BoostForeach.push_back("BOOST_FOREACH"); 20129 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach); 20130 std::vector<std::string> BoostAndQForeach; 20131 BoostAndQForeach.push_back("BOOST_FOREACH"); 20132 BoostAndQForeach.push_back("Q_FOREACH"); 20133 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros, 20134 BoostAndQForeach); 20135 20136 Style.IfMacros.clear(); 20137 std::vector<std::string> CustomIfs; 20138 CustomIfs.push_back("MYIF"); 20139 CHECK_PARSE("IfMacros: [MYIF]", IfMacros, CustomIfs); 20140 20141 Style.AttributeMacros.clear(); 20142 CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros, 20143 std::vector<std::string>{"__capability"}); 20144 CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros, 20145 std::vector<std::string>({"attr1", "attr2"})); 20146 20147 Style.StatementAttributeLikeMacros.clear(); 20148 CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]", 20149 StatementAttributeLikeMacros, 20150 std::vector<std::string>({"emit", "Q_EMIT"})); 20151 20152 Style.StatementMacros.clear(); 20153 CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros, 20154 std::vector<std::string>{"QUNUSED"}); 20155 CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros, 20156 std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"})); 20157 20158 Style.NamespaceMacros.clear(); 20159 CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros, 20160 std::vector<std::string>{"TESTSUITE"}); 20161 CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros, 20162 std::vector<std::string>({"TESTSUITE", "SUITE"})); 20163 20164 Style.WhitespaceSensitiveMacros.clear(); 20165 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]", 20166 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"}); 20167 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]", 20168 WhitespaceSensitiveMacros, 20169 std::vector<std::string>({"STRINGIZE", "ASSERT"})); 20170 Style.WhitespaceSensitiveMacros.clear(); 20171 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']", 20172 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"}); 20173 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']", 20174 WhitespaceSensitiveMacros, 20175 std::vector<std::string>({"STRINGIZE", "ASSERT"})); 20176 20177 Style.IncludeStyle.IncludeCategories.clear(); 20178 std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = { 20179 {"abc/.*", 2, 0, false}, {".*", 1, 0, true}}; 20180 CHECK_PARSE("IncludeCategories:\n" 20181 " - Regex: abc/.*\n" 20182 " Priority: 2\n" 20183 " - Regex: .*\n" 20184 " Priority: 1\n" 20185 " CaseSensitive: true\n", 20186 IncludeStyle.IncludeCategories, ExpectedCategories); 20187 CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex, 20188 "abc$"); 20189 CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'", 20190 IncludeStyle.IncludeIsMainSourceRegex, "abc$"); 20191 20192 Style.SortIncludes = FormatStyle::SI_Never; 20193 CHECK_PARSE("SortIncludes: true", SortIncludes, 20194 FormatStyle::SI_CaseSensitive); 20195 CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never); 20196 CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes, 20197 FormatStyle::SI_CaseInsensitive); 20198 CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes, 20199 FormatStyle::SI_CaseSensitive); 20200 CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never); 20201 20202 Style.RawStringFormats.clear(); 20203 std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = { 20204 { 20205 FormatStyle::LK_TextProto, 20206 {"pb", "proto"}, 20207 {"PARSE_TEXT_PROTO"}, 20208 /*CanonicalDelimiter=*/"", 20209 "llvm", 20210 }, 20211 { 20212 FormatStyle::LK_Cpp, 20213 {"cc", "cpp"}, 20214 {"C_CODEBLOCK", "CPPEVAL"}, 20215 /*CanonicalDelimiter=*/"cc", 20216 /*BasedOnStyle=*/"", 20217 }, 20218 }; 20219 20220 CHECK_PARSE("RawStringFormats:\n" 20221 " - Language: TextProto\n" 20222 " Delimiters:\n" 20223 " - 'pb'\n" 20224 " - 'proto'\n" 20225 " EnclosingFunctions:\n" 20226 " - 'PARSE_TEXT_PROTO'\n" 20227 " BasedOnStyle: llvm\n" 20228 " - Language: Cpp\n" 20229 " Delimiters:\n" 20230 " - 'cc'\n" 20231 " - 'cpp'\n" 20232 " EnclosingFunctions:\n" 20233 " - 'C_CODEBLOCK'\n" 20234 " - 'CPPEVAL'\n" 20235 " CanonicalDelimiter: 'cc'", 20236 RawStringFormats, ExpectedRawStringFormats); 20237 20238 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20239 " Minimum: 0\n" 20240 " Maximum: 0", 20241 SpacesInLineCommentPrefix.Minimum, 0u); 20242 EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u); 20243 Style.SpacesInLineCommentPrefix.Minimum = 1; 20244 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20245 " Minimum: 2", 20246 SpacesInLineCommentPrefix.Minimum, 0u); 20247 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20248 " Maximum: -1", 20249 SpacesInLineCommentPrefix.Maximum, -1u); 20250 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20251 " Minimum: 2", 20252 SpacesInLineCommentPrefix.Minimum, 2u); 20253 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20254 " Maximum: 1", 20255 SpacesInLineCommentPrefix.Maximum, 1u); 20256 EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u); 20257 20258 Style.SpacesInAngles = FormatStyle::SIAS_Always; 20259 CHECK_PARSE("SpacesInAngles: Never", SpacesInAngles, FormatStyle::SIAS_Never); 20260 CHECK_PARSE("SpacesInAngles: Always", SpacesInAngles, 20261 FormatStyle::SIAS_Always); 20262 CHECK_PARSE("SpacesInAngles: Leave", SpacesInAngles, FormatStyle::SIAS_Leave); 20263 // For backward compatibility: 20264 CHECK_PARSE("SpacesInAngles: false", SpacesInAngles, FormatStyle::SIAS_Never); 20265 CHECK_PARSE("SpacesInAngles: true", SpacesInAngles, FormatStyle::SIAS_Always); 20266 20267 CHECK_PARSE("RequiresClausePosition: WithPreceding", RequiresClausePosition, 20268 FormatStyle::RCPS_WithPreceding); 20269 CHECK_PARSE("RequiresClausePosition: WithFollowing", RequiresClausePosition, 20270 FormatStyle::RCPS_WithFollowing); 20271 CHECK_PARSE("RequiresClausePosition: SingleLine", RequiresClausePosition, 20272 FormatStyle::RCPS_SingleLine); 20273 CHECK_PARSE("RequiresClausePosition: OwnLine", RequiresClausePosition, 20274 FormatStyle::RCPS_OwnLine); 20275 20276 CHECK_PARSE("BreakBeforeConceptDeclarations: Never", 20277 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Never); 20278 CHECK_PARSE("BreakBeforeConceptDeclarations: Always", 20279 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always); 20280 CHECK_PARSE("BreakBeforeConceptDeclarations: Allowed", 20281 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed); 20282 // For backward compatibility: 20283 CHECK_PARSE("BreakBeforeConceptDeclarations: true", 20284 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always); 20285 CHECK_PARSE("BreakBeforeConceptDeclarations: false", 20286 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed); 20287 } 20288 20289 TEST_F(FormatTest, ParsesConfigurationWithLanguages) { 20290 FormatStyle Style = {}; 20291 Style.Language = FormatStyle::LK_Cpp; 20292 CHECK_PARSE("Language: Cpp\n" 20293 "IndentWidth: 12", 20294 IndentWidth, 12u); 20295 EXPECT_EQ(parseConfiguration("Language: JavaScript\n" 20296 "IndentWidth: 34", 20297 &Style), 20298 ParseError::Unsuitable); 20299 FormatStyle BinPackedTCS = {}; 20300 BinPackedTCS.Language = FormatStyle::LK_JavaScript; 20301 EXPECT_EQ(parseConfiguration("BinPackArguments: true\n" 20302 "InsertTrailingCommas: Wrapped", 20303 &BinPackedTCS), 20304 ParseError::BinPackTrailingCommaConflict); 20305 EXPECT_EQ(12u, Style.IndentWidth); 20306 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u); 20307 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language); 20308 20309 Style.Language = FormatStyle::LK_JavaScript; 20310 CHECK_PARSE("Language: JavaScript\n" 20311 "IndentWidth: 12", 20312 IndentWidth, 12u); 20313 CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u); 20314 EXPECT_EQ(parseConfiguration("Language: Cpp\n" 20315 "IndentWidth: 34", 20316 &Style), 20317 ParseError::Unsuitable); 20318 EXPECT_EQ(23u, Style.IndentWidth); 20319 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u); 20320 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language); 20321 20322 CHECK_PARSE("BasedOnStyle: LLVM\n" 20323 "IndentWidth: 67", 20324 IndentWidth, 67u); 20325 20326 CHECK_PARSE("---\n" 20327 "Language: JavaScript\n" 20328 "IndentWidth: 12\n" 20329 "---\n" 20330 "Language: Cpp\n" 20331 "IndentWidth: 34\n" 20332 "...\n", 20333 IndentWidth, 12u); 20334 20335 Style.Language = FormatStyle::LK_Cpp; 20336 CHECK_PARSE("---\n" 20337 "Language: JavaScript\n" 20338 "IndentWidth: 12\n" 20339 "---\n" 20340 "Language: Cpp\n" 20341 "IndentWidth: 34\n" 20342 "...\n", 20343 IndentWidth, 34u); 20344 CHECK_PARSE("---\n" 20345 "IndentWidth: 78\n" 20346 "---\n" 20347 "Language: JavaScript\n" 20348 "IndentWidth: 56\n" 20349 "...\n", 20350 IndentWidth, 78u); 20351 20352 Style.ColumnLimit = 123; 20353 Style.IndentWidth = 234; 20354 Style.BreakBeforeBraces = FormatStyle::BS_Linux; 20355 Style.TabWidth = 345; 20356 EXPECT_FALSE(parseConfiguration("---\n" 20357 "IndentWidth: 456\n" 20358 "BreakBeforeBraces: Allman\n" 20359 "---\n" 20360 "Language: JavaScript\n" 20361 "IndentWidth: 111\n" 20362 "TabWidth: 111\n" 20363 "---\n" 20364 "Language: Cpp\n" 20365 "BreakBeforeBraces: Stroustrup\n" 20366 "TabWidth: 789\n" 20367 "...\n", 20368 &Style)); 20369 EXPECT_EQ(123u, Style.ColumnLimit); 20370 EXPECT_EQ(456u, Style.IndentWidth); 20371 EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces); 20372 EXPECT_EQ(789u, Style.TabWidth); 20373 20374 EXPECT_EQ(parseConfiguration("---\n" 20375 "Language: JavaScript\n" 20376 "IndentWidth: 56\n" 20377 "---\n" 20378 "IndentWidth: 78\n" 20379 "...\n", 20380 &Style), 20381 ParseError::Error); 20382 EXPECT_EQ(parseConfiguration("---\n" 20383 "Language: JavaScript\n" 20384 "IndentWidth: 56\n" 20385 "---\n" 20386 "Language: JavaScript\n" 20387 "IndentWidth: 78\n" 20388 "...\n", 20389 &Style), 20390 ParseError::Error); 20391 20392 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language); 20393 } 20394 20395 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) { 20396 FormatStyle Style = {}; 20397 Style.Language = FormatStyle::LK_JavaScript; 20398 Style.BreakBeforeTernaryOperators = true; 20399 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value()); 20400 EXPECT_FALSE(Style.BreakBeforeTernaryOperators); 20401 20402 Style.BreakBeforeTernaryOperators = true; 20403 EXPECT_EQ(0, parseConfiguration("---\n" 20404 "BasedOnStyle: Google\n" 20405 "---\n" 20406 "Language: JavaScript\n" 20407 "IndentWidth: 76\n" 20408 "...\n", 20409 &Style) 20410 .value()); 20411 EXPECT_FALSE(Style.BreakBeforeTernaryOperators); 20412 EXPECT_EQ(76u, Style.IndentWidth); 20413 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language); 20414 } 20415 20416 TEST_F(FormatTest, ConfigurationRoundTripTest) { 20417 FormatStyle Style = getLLVMStyle(); 20418 std::string YAML = configurationAsText(Style); 20419 FormatStyle ParsedStyle = {}; 20420 ParsedStyle.Language = FormatStyle::LK_Cpp; 20421 EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value()); 20422 EXPECT_EQ(Style, ParsedStyle); 20423 } 20424 20425 TEST_F(FormatTest, WorksFor8bitEncodings) { 20426 EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n" 20427 "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n" 20428 "\"\xe7\xe8\xec\xed\xfe\xfe \"\n" 20429 "\"\xef\xee\xf0\xf3...\"", 20430 format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 " 20431 "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe " 20432 "\xef\xee\xf0\xf3...\"", 20433 getLLVMStyleWithColumns(12))); 20434 } 20435 20436 TEST_F(FormatTest, HandlesUTF8BOM) { 20437 EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf")); 20438 EXPECT_EQ("\xef\xbb\xbf#include <iostream>", 20439 format("\xef\xbb\xbf#include <iostream>")); 20440 EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>", 20441 format("\xef\xbb\xbf\n#include <iostream>")); 20442 } 20443 20444 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers. 20445 #if !defined(_MSC_VER) 20446 20447 TEST_F(FormatTest, CountsUTF8CharactersProperly) { 20448 verifyFormat("\"Однажды в студёную зимнюю пору...\"", 20449 getLLVMStyleWithColumns(35)); 20450 verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"", 20451 getLLVMStyleWithColumns(31)); 20452 verifyFormat("// Однажды в студёную зимнюю пору...", 20453 getLLVMStyleWithColumns(36)); 20454 verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32)); 20455 verifyFormat("/* Однажды в студёную зимнюю пору... */", 20456 getLLVMStyleWithColumns(39)); 20457 verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */", 20458 getLLVMStyleWithColumns(35)); 20459 } 20460 20461 TEST_F(FormatTest, SplitsUTF8Strings) { 20462 // Non-printable characters' width is currently considered to be the length in 20463 // bytes in UTF8. The characters can be displayed in very different manner 20464 // (zero-width, single width with a substitution glyph, expanded to their code 20465 // (e.g. "<8d>"), so there's no single correct way to handle them. 20466 EXPECT_EQ("\"aaaaÄ\"\n" 20467 "\"\xc2\x8d\";", 20468 format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10))); 20469 EXPECT_EQ("\"aaaaaaaÄ\"\n" 20470 "\"\xc2\x8d\";", 20471 format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10))); 20472 EXPECT_EQ("\"Однажды, в \"\n" 20473 "\"студёную \"\n" 20474 "\"зимнюю \"\n" 20475 "\"пору,\"", 20476 format("\"Однажды, в студёную зимнюю пору,\"", 20477 getLLVMStyleWithColumns(13))); 20478 EXPECT_EQ( 20479 "\"一 二 三 \"\n" 20480 "\"四 五六 \"\n" 20481 "\"七 八 九 \"\n" 20482 "\"十\"", 20483 format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11))); 20484 EXPECT_EQ("\"一\t\"\n" 20485 "\"二 \t\"\n" 20486 "\"三 四 \"\n" 20487 "\"五\t\"\n" 20488 "\"六 \t\"\n" 20489 "\"七 \"\n" 20490 "\"八九十\tqq\"", 20491 format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"", 20492 getLLVMStyleWithColumns(11))); 20493 20494 // UTF8 character in an escape sequence. 20495 EXPECT_EQ("\"aaaaaa\"\n" 20496 "\"\\\xC2\x8D\"", 20497 format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10))); 20498 } 20499 20500 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) { 20501 EXPECT_EQ("const char *sssss =\n" 20502 " \"一二三四五六七八\\\n" 20503 " 九 十\";", 20504 format("const char *sssss = \"一二三四五六七八\\\n" 20505 " 九 十\";", 20506 getLLVMStyleWithColumns(30))); 20507 } 20508 20509 TEST_F(FormatTest, SplitsUTF8LineComments) { 20510 EXPECT_EQ("// aaaaÄ\xc2\x8d", 20511 format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10))); 20512 EXPECT_EQ("// Я из лесу\n" 20513 "// вышел; был\n" 20514 "// сильный\n" 20515 "// мороз.", 20516 format("// Я из лесу вышел; был сильный мороз.", 20517 getLLVMStyleWithColumns(13))); 20518 EXPECT_EQ("// 一二三\n" 20519 "// 四五六七\n" 20520 "// 八 九\n" 20521 "// 十", 20522 format("// 一二三 四五六七 八 九 十", getLLVMStyleWithColumns(9))); 20523 } 20524 20525 TEST_F(FormatTest, SplitsUTF8BlockComments) { 20526 EXPECT_EQ("/* Гляжу,\n" 20527 " * поднимается\n" 20528 " * медленно в\n" 20529 " * гору\n" 20530 " * Лошадка,\n" 20531 " * везущая\n" 20532 " * хворосту\n" 20533 " * воз. */", 20534 format("/* Гляжу, поднимается медленно в гору\n" 20535 " * Лошадка, везущая хворосту воз. */", 20536 getLLVMStyleWithColumns(13))); 20537 EXPECT_EQ( 20538 "/* 一二三\n" 20539 " * 四五六七\n" 20540 " * 八 九\n" 20541 " * 十 */", 20542 format("/* 一二三 四五六七 八 九 十 */", getLLVMStyleWithColumns(9))); 20543 EXPECT_EQ("/* \n" 20544 " * \n" 20545 " * - */", 20546 format("/* - */", getLLVMStyleWithColumns(12))); 20547 } 20548 20549 #endif // _MSC_VER 20550 20551 TEST_F(FormatTest, ConstructorInitializerIndentWidth) { 20552 FormatStyle Style = getLLVMStyle(); 20553 20554 Style.ConstructorInitializerIndentWidth = 4; 20555 verifyFormat( 20556 "SomeClass::Constructor()\n" 20557 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20558 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20559 Style); 20560 20561 Style.ConstructorInitializerIndentWidth = 2; 20562 verifyFormat( 20563 "SomeClass::Constructor()\n" 20564 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20565 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20566 Style); 20567 20568 Style.ConstructorInitializerIndentWidth = 0; 20569 verifyFormat( 20570 "SomeClass::Constructor()\n" 20571 ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20572 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20573 Style); 20574 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 20575 verifyFormat( 20576 "SomeLongTemplateVariableName<\n" 20577 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>", 20578 Style); 20579 verifyFormat("bool smaller = 1 < " 20580 "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 20581 " " 20582 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 20583 Style); 20584 20585 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 20586 verifyFormat("SomeClass::Constructor() :\n" 20587 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n" 20588 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}", 20589 Style); 20590 } 20591 20592 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) { 20593 FormatStyle Style = getLLVMStyle(); 20594 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 20595 Style.ConstructorInitializerIndentWidth = 4; 20596 verifyFormat("SomeClass::Constructor()\n" 20597 " : a(a)\n" 20598 " , b(b)\n" 20599 " , c(c) {}", 20600 Style); 20601 verifyFormat("SomeClass::Constructor()\n" 20602 " : a(a) {}", 20603 Style); 20604 20605 Style.ColumnLimit = 0; 20606 verifyFormat("SomeClass::Constructor()\n" 20607 " : a(a) {}", 20608 Style); 20609 verifyFormat("SomeClass::Constructor() noexcept\n" 20610 " : a(a) {}", 20611 Style); 20612 verifyFormat("SomeClass::Constructor()\n" 20613 " : a(a)\n" 20614 " , b(b)\n" 20615 " , c(c) {}", 20616 Style); 20617 verifyFormat("SomeClass::Constructor()\n" 20618 " : a(a) {\n" 20619 " foo();\n" 20620 " bar();\n" 20621 "}", 20622 Style); 20623 20624 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 20625 verifyFormat("SomeClass::Constructor()\n" 20626 " : a(a)\n" 20627 " , b(b)\n" 20628 " , c(c) {\n}", 20629 Style); 20630 verifyFormat("SomeClass::Constructor()\n" 20631 " : a(a) {\n}", 20632 Style); 20633 20634 Style.ColumnLimit = 80; 20635 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 20636 Style.ConstructorInitializerIndentWidth = 2; 20637 verifyFormat("SomeClass::Constructor()\n" 20638 " : a(a)\n" 20639 " , b(b)\n" 20640 " , c(c) {}", 20641 Style); 20642 20643 Style.ConstructorInitializerIndentWidth = 0; 20644 verifyFormat("SomeClass::Constructor()\n" 20645 ": a(a)\n" 20646 ", b(b)\n" 20647 ", c(c) {}", 20648 Style); 20649 20650 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 20651 Style.ConstructorInitializerIndentWidth = 4; 20652 verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style); 20653 verifyFormat( 20654 "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n", 20655 Style); 20656 verifyFormat( 20657 "SomeClass::Constructor()\n" 20658 " : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}", 20659 Style); 20660 Style.ConstructorInitializerIndentWidth = 4; 20661 Style.ColumnLimit = 60; 20662 verifyFormat("SomeClass::Constructor()\n" 20663 " : aaaaaaaa(aaaaaaaa)\n" 20664 " , aaaaaaaa(aaaaaaaa)\n" 20665 " , aaaaaaaa(aaaaaaaa) {}", 20666 Style); 20667 } 20668 20669 TEST_F(FormatTest, ConstructorInitializersWithPreprocessorDirective) { 20670 FormatStyle Style = getLLVMStyle(); 20671 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 20672 Style.ConstructorInitializerIndentWidth = 4; 20673 verifyFormat("SomeClass::Constructor()\n" 20674 " : a{a}\n" 20675 " , b{b} {}", 20676 Style); 20677 verifyFormat("SomeClass::Constructor()\n" 20678 " : a{a}\n" 20679 "#if CONDITION\n" 20680 " , b{b}\n" 20681 "#endif\n" 20682 "{\n}", 20683 Style); 20684 Style.ConstructorInitializerIndentWidth = 2; 20685 verifyFormat("SomeClass::Constructor()\n" 20686 "#if CONDITION\n" 20687 " : a{a}\n" 20688 "#endif\n" 20689 " , b{b}\n" 20690 " , c{c} {\n}", 20691 Style); 20692 Style.ConstructorInitializerIndentWidth = 0; 20693 verifyFormat("SomeClass::Constructor()\n" 20694 ": a{a}\n" 20695 "#ifdef CONDITION\n" 20696 ", b{b}\n" 20697 "#else\n" 20698 ", c{c}\n" 20699 "#endif\n" 20700 ", d{d} {\n}", 20701 Style); 20702 Style.ConstructorInitializerIndentWidth = 4; 20703 verifyFormat("SomeClass::Constructor()\n" 20704 " : a{a}\n" 20705 "#if WINDOWS\n" 20706 "#if DEBUG\n" 20707 " , b{0}\n" 20708 "#else\n" 20709 " , b{1}\n" 20710 "#endif\n" 20711 "#else\n" 20712 "#if DEBUG\n" 20713 " , b{2}\n" 20714 "#else\n" 20715 " , b{3}\n" 20716 "#endif\n" 20717 "#endif\n" 20718 "{\n}", 20719 Style); 20720 verifyFormat("SomeClass::Constructor()\n" 20721 " : a{a}\n" 20722 "#if WINDOWS\n" 20723 " , b{0}\n" 20724 "#if DEBUG\n" 20725 " , c{0}\n" 20726 "#else\n" 20727 " , c{1}\n" 20728 "#endif\n" 20729 "#else\n" 20730 "#if DEBUG\n" 20731 " , c{2}\n" 20732 "#else\n" 20733 " , c{3}\n" 20734 "#endif\n" 20735 " , b{1}\n" 20736 "#endif\n" 20737 "{\n}", 20738 Style); 20739 } 20740 20741 TEST_F(FormatTest, Destructors) { 20742 verifyFormat("void F(int &i) { i.~int(); }"); 20743 verifyFormat("void F(int &i) { i->~int(); }"); 20744 } 20745 20746 TEST_F(FormatTest, FormatsWithWebKitStyle) { 20747 FormatStyle Style = getWebKitStyle(); 20748 20749 // Don't indent in outer namespaces. 20750 verifyFormat("namespace outer {\n" 20751 "int i;\n" 20752 "namespace inner {\n" 20753 " int i;\n" 20754 "} // namespace inner\n" 20755 "} // namespace outer\n" 20756 "namespace other_outer {\n" 20757 "int i;\n" 20758 "}", 20759 Style); 20760 20761 // Don't indent case labels. 20762 verifyFormat("switch (variable) {\n" 20763 "case 1:\n" 20764 "case 2:\n" 20765 " doSomething();\n" 20766 " break;\n" 20767 "default:\n" 20768 " ++variable;\n" 20769 "}", 20770 Style); 20771 20772 // Wrap before binary operators. 20773 EXPECT_EQ("void f()\n" 20774 "{\n" 20775 " if (aaaaaaaaaaaaaaaa\n" 20776 " && bbbbbbbbbbbbbbbbbbbbbbbb\n" 20777 " && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n" 20778 " return;\n" 20779 "}", 20780 format("void f() {\n" 20781 "if (aaaaaaaaaaaaaaaa\n" 20782 "&& bbbbbbbbbbbbbbbbbbbbbbbb\n" 20783 "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n" 20784 "return;\n" 20785 "}", 20786 Style)); 20787 20788 // Allow functions on a single line. 20789 verifyFormat("void f() { return; }", Style); 20790 20791 // Allow empty blocks on a single line and insert a space in empty blocks. 20792 EXPECT_EQ("void f() { }", format("void f() {}", Style)); 20793 EXPECT_EQ("while (true) { }", format("while (true) {}", Style)); 20794 // However, don't merge non-empty short loops. 20795 EXPECT_EQ("while (true) {\n" 20796 " continue;\n" 20797 "}", 20798 format("while (true) { continue; }", Style)); 20799 20800 // Constructor initializers are formatted one per line with the "," on the 20801 // new line. 20802 verifyFormat("Constructor()\n" 20803 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 20804 " , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n" 20805 " aaaaaaaaaaaaaa)\n" 20806 " , aaaaaaaaaaaaaaaaaaaaaaa()\n" 20807 "{\n" 20808 "}", 20809 Style); 20810 verifyFormat("SomeClass::Constructor()\n" 20811 " : a(a)\n" 20812 "{\n" 20813 "}", 20814 Style); 20815 EXPECT_EQ("SomeClass::Constructor()\n" 20816 " : a(a)\n" 20817 "{\n" 20818 "}", 20819 format("SomeClass::Constructor():a(a){}", Style)); 20820 verifyFormat("SomeClass::Constructor()\n" 20821 " : a(a)\n" 20822 " , b(b)\n" 20823 " , c(c)\n" 20824 "{\n" 20825 "}", 20826 Style); 20827 verifyFormat("SomeClass::Constructor()\n" 20828 " : a(a)\n" 20829 "{\n" 20830 " foo();\n" 20831 " bar();\n" 20832 "}", 20833 Style); 20834 20835 // Access specifiers should be aligned left. 20836 verifyFormat("class C {\n" 20837 "public:\n" 20838 " int i;\n" 20839 "};", 20840 Style); 20841 20842 // Do not align comments. 20843 verifyFormat("int a; // Do not\n" 20844 "double b; // align comments.", 20845 Style); 20846 20847 // Do not align operands. 20848 EXPECT_EQ("ASSERT(aaaa\n" 20849 " || bbbb);", 20850 format("ASSERT ( aaaa\n||bbbb);", Style)); 20851 20852 // Accept input's line breaks. 20853 EXPECT_EQ("if (aaaaaaaaaaaaaaa\n" 20854 " || bbbbbbbbbbbbbbb) {\n" 20855 " i++;\n" 20856 "}", 20857 format("if (aaaaaaaaaaaaaaa\n" 20858 "|| bbbbbbbbbbbbbbb) { i++; }", 20859 Style)); 20860 EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n" 20861 " i++;\n" 20862 "}", 20863 format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style)); 20864 20865 // Don't automatically break all macro definitions (llvm.org/PR17842). 20866 verifyFormat("#define aNumber 10", Style); 20867 // However, generally keep the line breaks that the user authored. 20868 EXPECT_EQ("#define aNumber \\\n" 20869 " 10", 20870 format("#define aNumber \\\n" 20871 " 10", 20872 Style)); 20873 20874 // Keep empty and one-element array literals on a single line. 20875 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n" 20876 " copyItems:YES];", 20877 format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n" 20878 "copyItems:YES];", 20879 Style)); 20880 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n" 20881 " copyItems:YES];", 20882 format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n" 20883 " copyItems:YES];", 20884 Style)); 20885 // FIXME: This does not seem right, there should be more indentation before 20886 // the array literal's entries. Nested blocks have the same problem. 20887 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n" 20888 " @\"a\",\n" 20889 " @\"a\"\n" 20890 "]\n" 20891 " copyItems:YES];", 20892 format("NSArray* a = [[NSArray alloc] initWithArray:@[\n" 20893 " @\"a\",\n" 20894 " @\"a\"\n" 20895 " ]\n" 20896 " copyItems:YES];", 20897 Style)); 20898 EXPECT_EQ( 20899 "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n" 20900 " copyItems:YES];", 20901 format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n" 20902 " copyItems:YES];", 20903 Style)); 20904 20905 verifyFormat("[self.a b:c c:d];", Style); 20906 EXPECT_EQ("[self.a b:c\n" 20907 " c:d];", 20908 format("[self.a b:c\n" 20909 "c:d];", 20910 Style)); 20911 } 20912 20913 TEST_F(FormatTest, FormatsLambdas) { 20914 verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n"); 20915 verifyFormat( 20916 "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n"); 20917 verifyFormat("int c = [&] { [=] { return b++; }(); }();\n"); 20918 verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n"); 20919 verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n"); 20920 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n"); 20921 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n"); 20922 verifyFormat("auto c = [a = [b = 42] {}] {};\n"); 20923 verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n"); 20924 verifyFormat("int x = f(*+[] {});"); 20925 verifyFormat("void f() {\n" 20926 " other(x.begin(), x.end(), [&](int, int) { return 1; });\n" 20927 "}\n"); 20928 verifyFormat("void f() {\n" 20929 " other(x.begin(), //\n" 20930 " x.end(), //\n" 20931 " [&](int, int) { return 1; });\n" 20932 "}\n"); 20933 verifyFormat("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) { " 20937 "return 1; });\n" 20938 "}\n"); 20939 verifyFormat( 20940 "void f() {\n" 20941 " other.other.other.other.other(\n" 20942 " x.begin(), x.end(),\n" 20943 " [something, rather](int, int, int, int, int, int, int) {\n" 20944 " //\n" 20945 " });\n" 20946 "}\n"); 20947 verifyFormat("SomeFunction([]() { // A cool function...\n" 20948 " return 43;\n" 20949 "});"); 20950 EXPECT_EQ("SomeFunction([]() {\n" 20951 "#define A a\n" 20952 " return 43;\n" 20953 "});", 20954 format("SomeFunction([](){\n" 20955 "#define A a\n" 20956 "return 43;\n" 20957 "});")); 20958 verifyFormat("void f() {\n" 20959 " SomeFunction([](decltype(x), A *a) {});\n" 20960 " SomeFunction([](typeof(x), A *a) {});\n" 20961 " SomeFunction([](_Atomic(x), A *a) {});\n" 20962 " SomeFunction([](__underlying_type(x), A *a) {});\n" 20963 "}"); 20964 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 20965 " [](const aaaaaaaaaa &a) { return a; });"); 20966 verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n" 20967 " SomeOtherFunctioooooooooooooooooooooooooon();\n" 20968 "});"); 20969 verifyFormat("Constructor()\n" 20970 " : Field([] { // comment\n" 20971 " int i;\n" 20972 " }) {}"); 20973 verifyFormat("auto my_lambda = [](const string &some_parameter) {\n" 20974 " return some_parameter.size();\n" 20975 "};"); 20976 verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n" 20977 " [](const string &s) { return s; };"); 20978 verifyFormat("int i = aaaaaa ? 1 //\n" 20979 " : [] {\n" 20980 " return 2; //\n" 20981 " }();"); 20982 verifyFormat("llvm::errs() << \"number of twos is \"\n" 20983 " << std::count_if(v.begin(), v.end(), [](int x) {\n" 20984 " return x == 2; // force break\n" 20985 " });"); 20986 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 20987 " [=](int iiiiiiiiiiii) {\n" 20988 " return aaaaaaaaaaaaaaaaaaaaaaa !=\n" 20989 " aaaaaaaaaaaaaaaaaaaaaaa;\n" 20990 " });", 20991 getLLVMStyleWithColumns(60)); 20992 20993 verifyFormat("SomeFunction({[&] {\n" 20994 " // comment\n" 20995 " },\n" 20996 " [&] {\n" 20997 " // comment\n" 20998 " }});"); 20999 verifyFormat("SomeFunction({[&] {\n" 21000 " // comment\n" 21001 "}});"); 21002 verifyFormat( 21003 "virtual aaaaaaaaaaaaaaaa(\n" 21004 " std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n" 21005 " aaaaa aaaaaaaaa);"); 21006 21007 // Lambdas with return types. 21008 verifyFormat("int c = []() -> int { return 2; }();\n"); 21009 verifyFormat("int c = []() -> int * { return 2; }();\n"); 21010 verifyFormat("int c = []() -> vector<int> { return {2}; }();\n"); 21011 verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());"); 21012 verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};"); 21013 verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};"); 21014 verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};"); 21015 verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};"); 21016 verifyFormat("[a, a]() -> a<1> {};"); 21017 verifyFormat("[]() -> foo<5 + 2> { 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> { return {}; };"); 21024 verifyFormat("[]() -> foo<~5> { return {}; };"); 21025 verifyFormat("[]() -> foo<5 | 2> { return {}; };"); 21026 verifyFormat("[]() -> foo<5 || 2> { return {}; };"); 21027 verifyFormat("[]() -> foo<5 & 2> { return {}; };"); 21028 verifyFormat("[]() -> foo<5 && 2> { return {}; };"); 21029 verifyFormat("[]() -> foo<5 == 2> { return {}; };"); 21030 verifyFormat("[]() -> foo<5 != 2> { return {}; };"); 21031 verifyFormat("[]() -> foo<5 >= 2> { return {}; };"); 21032 verifyFormat("[]() -> foo<5 <= 2> { return {}; };"); 21033 verifyFormat("[]() -> foo<5 < 2> { return {}; };"); 21034 verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };"); 21035 verifyFormat("namespace bar {\n" 21036 "// broken:\n" 21037 "auto foo{[]() -> foo<5 + 2> { return {}; }};\n" 21038 "} // namespace bar"); 21039 verifyFormat("namespace bar {\n" 21040 "// broken:\n" 21041 "auto foo{[]() -> foo<5 - 2> { return {}; }};\n" 21042 "} // namespace bar"); 21043 verifyFormat("namespace bar {\n" 21044 "// broken:\n" 21045 "auto foo{[]() -> foo<5 / 2> { return {}; }};\n" 21046 "} // namespace bar"); 21047 verifyFormat("namespace bar {\n" 21048 "// broken:\n" 21049 "auto foo{[]() -> foo<5 * 2> { return {}; }};\n" 21050 "} // namespace bar"); 21051 verifyFormat("namespace bar {\n" 21052 "// broken:\n" 21053 "auto foo{[]() -> foo<5 % 2> { return {}; }};\n" 21054 "} // namespace bar"); 21055 verifyFormat("namespace bar {\n" 21056 "// broken:\n" 21057 "auto foo{[]() -> foo<5 << 2> { return {}; }};\n" 21058 "} // namespace bar"); 21059 verifyFormat("namespace bar {\n" 21060 "// broken:\n" 21061 "auto foo{[]() -> foo<!5> { return {}; }};\n" 21062 "} // namespace bar"); 21063 verifyFormat("namespace bar {\n" 21064 "// broken:\n" 21065 "auto foo{[]() -> foo<~5> { return {}; }};\n" 21066 "} // namespace bar"); 21067 verifyFormat("namespace bar {\n" 21068 "// broken:\n" 21069 "auto foo{[]() -> foo<5 | 2> { return {}; }};\n" 21070 "} // namespace bar"); 21071 verifyFormat("namespace bar {\n" 21072 "// broken:\n" 21073 "auto foo{[]() -> foo<5 || 2> { return {}; }};\n" 21074 "} // namespace bar"); 21075 verifyFormat("namespace bar {\n" 21076 "// broken:\n" 21077 "auto foo{[]() -> foo<5 & 2> { return {}; }};\n" 21078 "} // namespace bar"); 21079 verifyFormat("namespace bar {\n" 21080 "// broken:\n" 21081 "auto foo{[]() -> foo<5 && 2> { return {}; }};\n" 21082 "} // namespace bar"); 21083 verifyFormat("namespace bar {\n" 21084 "// broken:\n" 21085 "auto foo{[]() -> foo<5 == 2> { return {}; }};\n" 21086 "} // namespace bar"); 21087 verifyFormat("namespace bar {\n" 21088 "// broken:\n" 21089 "auto foo{[]() -> foo<5 != 2> { return {}; }};\n" 21090 "} // namespace bar"); 21091 verifyFormat("namespace bar {\n" 21092 "// broken:\n" 21093 "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n" 21094 "} // namespace bar"); 21095 verifyFormat("namespace bar {\n" 21096 "// broken:\n" 21097 "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n" 21098 "} // namespace bar"); 21099 verifyFormat("namespace bar {\n" 21100 "// broken:\n" 21101 "auto foo{[]() -> foo<5 < 2> { return {}; }};\n" 21102 "} // namespace bar"); 21103 verifyFormat("namespace bar {\n" 21104 "// broken:\n" 21105 "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n" 21106 "} // namespace bar"); 21107 verifyFormat("[]() -> a<1> {};"); 21108 verifyFormat("[]() -> a<1> { ; };"); 21109 verifyFormat("[]() -> a<1> { ; }();"); 21110 verifyFormat("[a, a]() -> a<true> {};"); 21111 verifyFormat("[]() -> a<true> {};"); 21112 verifyFormat("[]() -> a<true> { ; };"); 21113 verifyFormat("[]() -> a<true> { ; }();"); 21114 verifyFormat("[a, a]() -> a<false> {};"); 21115 verifyFormat("[]() -> a<false> {};"); 21116 verifyFormat("[]() -> a<false> { ; };"); 21117 verifyFormat("[]() -> a<false> { ; }();"); 21118 verifyFormat("auto foo{[]() -> foo<false> { ; }};"); 21119 verifyFormat("namespace bar {\n" 21120 "auto foo{[]() -> foo<false> { ; }};\n" 21121 "} // namespace bar"); 21122 verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n" 21123 " int j) -> int {\n" 21124 " return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n" 21125 "};"); 21126 verifyFormat( 21127 "aaaaaaaaaaaaaaaaaaaaaa(\n" 21128 " [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n" 21129 " return aaaaaaaaaaaaaaaaa;\n" 21130 " });", 21131 getLLVMStyleWithColumns(70)); 21132 verifyFormat("[]() //\n" 21133 " -> int {\n" 21134 " return 1; //\n" 21135 "};"); 21136 verifyFormat("[]() -> Void<T...> {};"); 21137 verifyFormat("[a, b]() -> Tuple<T...> { return {}; };"); 21138 verifyFormat("SomeFunction({[]() -> int[] { return {}; }});"); 21139 verifyFormat("SomeFunction({[]() -> int *[] { return {}; }});"); 21140 verifyFormat("SomeFunction({[]() -> int (*)[] { return {}; }});"); 21141 verifyFormat("SomeFunction({[]() -> ns::type<int (*)[]> { return {}; }});"); 21142 verifyFormat("return int{[x = x]() { return x; }()};"); 21143 21144 // Lambdas with explicit template argument lists. 21145 verifyFormat( 21146 "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n"); 21147 verifyFormat("auto L = []<class T>(T) {\n" 21148 " {\n" 21149 " f();\n" 21150 " g();\n" 21151 " }\n" 21152 "};\n"); 21153 verifyFormat("auto L = []<class... T>(T...) {\n" 21154 " {\n" 21155 " f();\n" 21156 " g();\n" 21157 " }\n" 21158 "};\n"); 21159 verifyFormat("auto L = []<typename... T>(T...) {\n" 21160 " {\n" 21161 " f();\n" 21162 " g();\n" 21163 " }\n" 21164 "};\n"); 21165 verifyFormat("auto L = []<template <typename...> class T>(T...) {\n" 21166 " {\n" 21167 " f();\n" 21168 " g();\n" 21169 " }\n" 21170 "};\n"); 21171 verifyFormat("auto L = []</*comment*/ class... T>(T...) {\n" 21172 " {\n" 21173 " f();\n" 21174 " g();\n" 21175 " }\n" 21176 "};\n"); 21177 21178 // Multiple lambdas in the same parentheses change indentation rules. These 21179 // lambdas are forced to start on new lines. 21180 verifyFormat("SomeFunction(\n" 21181 " []() {\n" 21182 " //\n" 21183 " },\n" 21184 " []() {\n" 21185 " //\n" 21186 " });"); 21187 21188 // A lambda passed as arg0 is always pushed to the next line. 21189 verifyFormat("SomeFunction(\n" 21190 " [this] {\n" 21191 " //\n" 21192 " },\n" 21193 " 1);\n"); 21194 21195 // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like 21196 // the arg0 case above. 21197 auto Style = getGoogleStyle(); 21198 Style.BinPackArguments = false; 21199 verifyFormat("SomeFunction(\n" 21200 " a,\n" 21201 " [this] {\n" 21202 " //\n" 21203 " },\n" 21204 " b);\n", 21205 Style); 21206 verifyFormat("SomeFunction(\n" 21207 " a,\n" 21208 " [this] {\n" 21209 " //\n" 21210 " },\n" 21211 " b);\n"); 21212 21213 // A lambda with a very long line forces arg0 to be pushed out irrespective of 21214 // the BinPackArguments value (as long as the code is wide enough). 21215 verifyFormat( 21216 "something->SomeFunction(\n" 21217 " a,\n" 21218 " [this] {\n" 21219 " " 21220 "D0000000000000000000000000000000000000000000000000000000000001();\n" 21221 " },\n" 21222 " b);\n"); 21223 21224 // A multi-line lambda is pulled up as long as the introducer fits on the 21225 // previous line and there are no further args. 21226 verifyFormat("function(1, [this, that] {\n" 21227 " //\n" 21228 "});\n"); 21229 verifyFormat("function([this, that] {\n" 21230 " //\n" 21231 "});\n"); 21232 // FIXME: this format is not ideal and we should consider forcing the first 21233 // arg onto its own line. 21234 verifyFormat("function(a, b, c, //\n" 21235 " d, [this, that] {\n" 21236 " //\n" 21237 " });\n"); 21238 21239 // Multiple lambdas are treated correctly even when there is a short arg0. 21240 verifyFormat("SomeFunction(\n" 21241 " 1,\n" 21242 " [this] {\n" 21243 " //\n" 21244 " },\n" 21245 " [this] {\n" 21246 " //\n" 21247 " },\n" 21248 " 1);\n"); 21249 21250 // More complex introducers. 21251 verifyFormat("return [i, args...] {};"); 21252 21253 // Not lambdas. 21254 verifyFormat("constexpr char hello[]{\"hello\"};"); 21255 verifyFormat("double &operator[](int i) { return 0; }\n" 21256 "int i;"); 21257 verifyFormat("std::unique_ptr<int[]> foo() {}"); 21258 verifyFormat("int i = a[a][a]->f();"); 21259 verifyFormat("int i = (*b)[a]->f();"); 21260 21261 // Other corner cases. 21262 verifyFormat("void f() {\n" 21263 " bar([]() {} // Did not respect SpacesBeforeTrailingComments\n" 21264 " );\n" 21265 "}"); 21266 21267 // Lambdas created through weird macros. 21268 verifyFormat("void f() {\n" 21269 " MACRO((const AA &a) { return 1; });\n" 21270 " MACRO((AA &a) { return 1; });\n" 21271 "}"); 21272 21273 verifyFormat("if (blah_blah(whatever, whatever, [] {\n" 21274 " doo_dah();\n" 21275 " doo_dah();\n" 21276 " })) {\n" 21277 "}"); 21278 verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n" 21279 " doo_dah();\n" 21280 " doo_dah();\n" 21281 " })) {\n" 21282 "}"); 21283 verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n" 21284 " doo_dah();\n" 21285 " doo_dah();\n" 21286 " })) {\n" 21287 "}"); 21288 verifyFormat("auto lambda = []() {\n" 21289 " int a = 2\n" 21290 "#if A\n" 21291 " + 2\n" 21292 "#endif\n" 21293 " ;\n" 21294 "};"); 21295 21296 // Lambdas with complex multiline introducers. 21297 verifyFormat( 21298 "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 21299 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n" 21300 " -> ::std::unordered_set<\n" 21301 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n" 21302 " //\n" 21303 " });"); 21304 21305 FormatStyle DoNotMerge = getLLVMStyle(); 21306 DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 21307 verifyFormat("auto c = []() {\n" 21308 " return b;\n" 21309 "};", 21310 "auto c = []() { return b; };", DoNotMerge); 21311 verifyFormat("auto c = []() {\n" 21312 "};", 21313 " auto c = []() {};", DoNotMerge); 21314 21315 FormatStyle MergeEmptyOnly = getLLVMStyle(); 21316 MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty; 21317 verifyFormat("auto c = []() {\n" 21318 " return b;\n" 21319 "};", 21320 "auto c = []() {\n" 21321 " return b;\n" 21322 " };", 21323 MergeEmptyOnly); 21324 verifyFormat("auto c = []() {};", 21325 "auto c = []() {\n" 21326 "};", 21327 MergeEmptyOnly); 21328 21329 FormatStyle MergeInline = getLLVMStyle(); 21330 MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline; 21331 verifyFormat("auto c = []() {\n" 21332 " return b;\n" 21333 "};", 21334 "auto c = []() { return b; };", MergeInline); 21335 verifyFormat("function([]() { return b; })", "function([]() { return b; })", 21336 MergeInline); 21337 verifyFormat("function([]() { return b; }, a)", 21338 "function([]() { return b; }, a)", MergeInline); 21339 verifyFormat("function(a, []() { return b; })", 21340 "function(a, []() { return b; })", MergeInline); 21341 21342 // Check option "BraceWrapping.BeforeLambdaBody" and different state of 21343 // AllowShortLambdasOnASingleLine 21344 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle(); 21345 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 21346 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 21347 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21348 FormatStyle::ShortLambdaStyle::SLS_None; 21349 verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n" 21350 " []()\n" 21351 " {\n" 21352 " return 17;\n" 21353 " });", 21354 LLVMWithBeforeLambdaBody); 21355 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n" 21356 " []()\n" 21357 " {\n" 21358 " });", 21359 LLVMWithBeforeLambdaBody); 21360 verifyFormat("auto fct_SLS_None = []()\n" 21361 "{\n" 21362 " return 17;\n" 21363 "};", 21364 LLVMWithBeforeLambdaBody); 21365 verifyFormat("TwoNestedLambdas_SLS_None(\n" 21366 " []()\n" 21367 " {\n" 21368 " return Call(\n" 21369 " []()\n" 21370 " {\n" 21371 " return 17;\n" 21372 " });\n" 21373 " });", 21374 LLVMWithBeforeLambdaBody); 21375 verifyFormat("void Fct() {\n" 21376 " return {[]()\n" 21377 " {\n" 21378 " return 17;\n" 21379 " }};\n" 21380 "}", 21381 LLVMWithBeforeLambdaBody); 21382 21383 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21384 FormatStyle::ShortLambdaStyle::SLS_Empty; 21385 verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n" 21386 " []()\n" 21387 " {\n" 21388 " return 17;\n" 21389 " });", 21390 LLVMWithBeforeLambdaBody); 21391 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});", 21392 LLVMWithBeforeLambdaBody); 21393 verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL" 21394 "ongFunctionName_SLS_Empty(\n" 21395 " []() {});", 21396 LLVMWithBeforeLambdaBody); 21397 verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n" 21398 " []()\n" 21399 " {\n" 21400 " return 17;\n" 21401 " });", 21402 LLVMWithBeforeLambdaBody); 21403 verifyFormat("auto fct_SLS_Empty = []()\n" 21404 "{\n" 21405 " return 17;\n" 21406 "};", 21407 LLVMWithBeforeLambdaBody); 21408 verifyFormat("TwoNestedLambdas_SLS_Empty(\n" 21409 " []()\n" 21410 " {\n" 21411 " return Call([]() {});\n" 21412 " });", 21413 LLVMWithBeforeLambdaBody); 21414 verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n" 21415 " []()\n" 21416 " {\n" 21417 " return Call([]() {});\n" 21418 " });", 21419 LLVMWithBeforeLambdaBody); 21420 verifyFormat( 21421 "FctWithLongLineInLambda_SLS_Empty(\n" 21422 " []()\n" 21423 " {\n" 21424 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21425 " AndShouldNotBeConsiderAsInline,\n" 21426 " LambdaBodyMustBeBreak);\n" 21427 " });", 21428 LLVMWithBeforeLambdaBody); 21429 21430 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21431 FormatStyle::ShortLambdaStyle::SLS_Inline; 21432 verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });", 21433 LLVMWithBeforeLambdaBody); 21434 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});", 21435 LLVMWithBeforeLambdaBody); 21436 verifyFormat("auto fct_SLS_Inline = []()\n" 21437 "{\n" 21438 " return 17;\n" 21439 "};", 21440 LLVMWithBeforeLambdaBody); 21441 verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return " 21442 "17; }); });", 21443 LLVMWithBeforeLambdaBody); 21444 verifyFormat( 21445 "FctWithLongLineInLambda_SLS_Inline(\n" 21446 " []()\n" 21447 " {\n" 21448 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21449 " AndShouldNotBeConsiderAsInline,\n" 21450 " LambdaBodyMustBeBreak);\n" 21451 " });", 21452 LLVMWithBeforeLambdaBody); 21453 verifyFormat("FctWithMultipleParams_SLS_Inline(" 21454 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n" 21455 " []() { return 17; });", 21456 LLVMWithBeforeLambdaBody); 21457 verifyFormat( 21458 "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });", 21459 LLVMWithBeforeLambdaBody); 21460 21461 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21462 FormatStyle::ShortLambdaStyle::SLS_All; 21463 verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });", 21464 LLVMWithBeforeLambdaBody); 21465 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});", 21466 LLVMWithBeforeLambdaBody); 21467 verifyFormat("auto fct_SLS_All = []() { return 17; };", 21468 LLVMWithBeforeLambdaBody); 21469 verifyFormat("FctWithOneParam_SLS_All(\n" 21470 " []()\n" 21471 " {\n" 21472 " // A cool function...\n" 21473 " return 43;\n" 21474 " });", 21475 LLVMWithBeforeLambdaBody); 21476 verifyFormat("FctWithMultipleParams_SLS_All(" 21477 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n" 21478 " []() { return 17; });", 21479 LLVMWithBeforeLambdaBody); 21480 verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });", 21481 LLVMWithBeforeLambdaBody); 21482 verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });", 21483 LLVMWithBeforeLambdaBody); 21484 verifyFormat( 21485 "FctWithLongLineInLambda_SLS_All(\n" 21486 " []()\n" 21487 " {\n" 21488 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21489 " AndShouldNotBeConsiderAsInline,\n" 21490 " LambdaBodyMustBeBreak);\n" 21491 " });", 21492 LLVMWithBeforeLambdaBody); 21493 verifyFormat( 21494 "auto fct_SLS_All = []()\n" 21495 "{\n" 21496 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21497 " AndShouldNotBeConsiderAsInline,\n" 21498 " LambdaBodyMustBeBreak);\n" 21499 "};", 21500 LLVMWithBeforeLambdaBody); 21501 LLVMWithBeforeLambdaBody.BinPackParameters = false; 21502 verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);", 21503 LLVMWithBeforeLambdaBody); 21504 verifyFormat( 21505 "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n" 21506 " FirstParam,\n" 21507 " SecondParam,\n" 21508 " ThirdParam,\n" 21509 " FourthParam);", 21510 LLVMWithBeforeLambdaBody); 21511 verifyFormat("FctWithLongLineInLambda_SLS_All(\n" 21512 " []() { return " 21513 "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n" 21514 " FirstParam,\n" 21515 " SecondParam,\n" 21516 " ThirdParam,\n" 21517 " FourthParam);", 21518 LLVMWithBeforeLambdaBody); 21519 verifyFormat( 21520 "FctWithLongLineInLambda_SLS_All(FirstParam,\n" 21521 " SecondParam,\n" 21522 " ThirdParam,\n" 21523 " FourthParam,\n" 21524 " []() { return SomeValueNotSoLong; });", 21525 LLVMWithBeforeLambdaBody); 21526 verifyFormat("FctWithLongLineInLambda_SLS_All(\n" 21527 " []()\n" 21528 " {\n" 21529 " return " 21530 "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB" 21531 "eConsiderAsInline;\n" 21532 " });", 21533 LLVMWithBeforeLambdaBody); 21534 verifyFormat( 21535 "FctWithLongLineInLambda_SLS_All(\n" 21536 " []()\n" 21537 " {\n" 21538 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21539 " AndShouldNotBeConsiderAsInline,\n" 21540 " LambdaBodyMustBeBreak);\n" 21541 " });", 21542 LLVMWithBeforeLambdaBody); 21543 verifyFormat("FctWithTwoParams_SLS_All(\n" 21544 " []()\n" 21545 " {\n" 21546 " // A cool function...\n" 21547 " return 43;\n" 21548 " },\n" 21549 " 87);", 21550 LLVMWithBeforeLambdaBody); 21551 verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);", 21552 LLVMWithBeforeLambdaBody); 21553 verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });", 21554 LLVMWithBeforeLambdaBody); 21555 verifyFormat( 21556 "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });", 21557 LLVMWithBeforeLambdaBody); 21558 verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; " 21559 "}); }, x);", 21560 LLVMWithBeforeLambdaBody); 21561 verifyFormat("TwoNestedLambdas_SLS_All(\n" 21562 " []()\n" 21563 " {\n" 21564 " // A cool function...\n" 21565 " return Call([]() { return 17; });\n" 21566 " });", 21567 LLVMWithBeforeLambdaBody); 21568 verifyFormat("TwoNestedLambdas_SLS_All(\n" 21569 " []()\n" 21570 " {\n" 21571 " return Call(\n" 21572 " []()\n" 21573 " {\n" 21574 " // A cool function...\n" 21575 " return 17;\n" 21576 " });\n" 21577 " });", 21578 LLVMWithBeforeLambdaBody); 21579 21580 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21581 FormatStyle::ShortLambdaStyle::SLS_None; 21582 21583 verifyFormat("auto select = [this]() -> const Library::Object *\n" 21584 "{\n" 21585 " return MyAssignment::SelectFromList(this);\n" 21586 "};\n", 21587 LLVMWithBeforeLambdaBody); 21588 21589 verifyFormat("auto select = [this]() -> const Library::Object &\n" 21590 "{\n" 21591 " return MyAssignment::SelectFromList(this);\n" 21592 "};\n", 21593 LLVMWithBeforeLambdaBody); 21594 21595 verifyFormat("auto select = [this]() -> std::unique_ptr<Object>\n" 21596 "{\n" 21597 " return MyAssignment::SelectFromList(this);\n" 21598 "};\n", 21599 LLVMWithBeforeLambdaBody); 21600 21601 verifyFormat("namespace test {\n" 21602 "class Test {\n" 21603 "public:\n" 21604 " Test() = default;\n" 21605 "};\n" 21606 "} // namespace test", 21607 LLVMWithBeforeLambdaBody); 21608 21609 // Lambdas with different indentation styles. 21610 Style = getLLVMStyleWithColumns(100); 21611 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 21612 " return promise.then(\n" 21613 " [this, &someVariable, someObject = " 21614 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21615 " return someObject.startAsyncAction().then(\n" 21616 " [this, &someVariable](AsyncActionResult result) " 21617 "mutable { result.processMore(); });\n" 21618 " });\n" 21619 "}\n", 21620 format("SomeResult doSomething(SomeObject promise) {\n" 21621 " return promise.then([this, &someVariable, someObject = " 21622 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21623 " return someObject.startAsyncAction().then([this, " 21624 "&someVariable](AsyncActionResult result) mutable {\n" 21625 " result.processMore();\n" 21626 " });\n" 21627 " });\n" 21628 "}\n", 21629 Style)); 21630 Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope; 21631 verifyFormat("test() {\n" 21632 " ([]() -> {\n" 21633 " int b = 32;\n" 21634 " return 3;\n" 21635 " }).foo();\n" 21636 "}", 21637 Style); 21638 verifyFormat("test() {\n" 21639 " []() -> {\n" 21640 " int b = 32;\n" 21641 " return 3;\n" 21642 " }\n" 21643 "}", 21644 Style); 21645 verifyFormat("std::sort(v.begin(), v.end(),\n" 21646 " [](const auto &someLongArgumentName, const auto " 21647 "&someOtherLongArgumentName) {\n" 21648 " return someLongArgumentName.someMemberVariable < " 21649 "someOtherLongArgumentName.someMemberVariable;\n" 21650 "});", 21651 Style); 21652 verifyFormat("test() {\n" 21653 " (\n" 21654 " []() -> {\n" 21655 " int b = 32;\n" 21656 " return 3;\n" 21657 " },\n" 21658 " foo, bar)\n" 21659 " .foo();\n" 21660 "}", 21661 Style); 21662 verifyFormat("test() {\n" 21663 " ([]() -> {\n" 21664 " int b = 32;\n" 21665 " return 3;\n" 21666 " })\n" 21667 " .foo()\n" 21668 " .bar();\n" 21669 "}", 21670 Style); 21671 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 21672 " return promise.then(\n" 21673 " [this, &someVariable, someObject = " 21674 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21675 " return someObject.startAsyncAction().then(\n" 21676 " [this, &someVariable](AsyncActionResult result) mutable { " 21677 "result.processMore(); });\n" 21678 " });\n" 21679 "}\n", 21680 format("SomeResult doSomething(SomeObject promise) {\n" 21681 " return promise.then([this, &someVariable, someObject = " 21682 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21683 " return someObject.startAsyncAction().then([this, " 21684 "&someVariable](AsyncActionResult result) mutable {\n" 21685 " result.processMore();\n" 21686 " });\n" 21687 " });\n" 21688 "}\n", 21689 Style)); 21690 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 21691 " return promise.then([this, &someVariable] {\n" 21692 " return someObject.startAsyncAction().then(\n" 21693 " [this, &someVariable](AsyncActionResult result) mutable { " 21694 "result.processMore(); });\n" 21695 " });\n" 21696 "}\n", 21697 format("SomeResult doSomething(SomeObject promise) {\n" 21698 " return promise.then([this, &someVariable] {\n" 21699 " return someObject.startAsyncAction().then([this, " 21700 "&someVariable](AsyncActionResult result) mutable {\n" 21701 " result.processMore();\n" 21702 " });\n" 21703 " });\n" 21704 "}\n", 21705 Style)); 21706 Style = getGoogleStyle(); 21707 Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope; 21708 EXPECT_EQ("#define A \\\n" 21709 " [] { \\\n" 21710 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 21711 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n" 21712 " }", 21713 format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 21714 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }", 21715 Style)); 21716 // TODO: The current formatting has a minor issue that's not worth fixing 21717 // right now whereby the closing brace is indented relative to the signature 21718 // instead of being aligned. This only happens with macros. 21719 } 21720 21721 TEST_F(FormatTest, LambdaWithLineComments) { 21722 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle(); 21723 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 21724 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 21725 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21726 FormatStyle::ShortLambdaStyle::SLS_All; 21727 21728 verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody); 21729 verifyFormat("auto k = []() // comment\n" 21730 "{ return; }", 21731 LLVMWithBeforeLambdaBody); 21732 verifyFormat("auto k = []() /* comment */ { return; }", 21733 LLVMWithBeforeLambdaBody); 21734 verifyFormat("auto k = []() /* comment */ /* comment */ { return; }", 21735 LLVMWithBeforeLambdaBody); 21736 verifyFormat("auto k = []() // X\n" 21737 "{ return; }", 21738 LLVMWithBeforeLambdaBody); 21739 verifyFormat( 21740 "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" 21741 "{ return; }", 21742 LLVMWithBeforeLambdaBody); 21743 } 21744 21745 TEST_F(FormatTest, EmptyLinesInLambdas) { 21746 verifyFormat("auto lambda = []() {\n" 21747 " x(); //\n" 21748 "};", 21749 "auto lambda = []() {\n" 21750 "\n" 21751 " x(); //\n" 21752 "\n" 21753 "};"); 21754 } 21755 21756 TEST_F(FormatTest, FormatsBlocks) { 21757 FormatStyle ShortBlocks = getLLVMStyle(); 21758 ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 21759 verifyFormat("int (^Block)(int, int);", ShortBlocks); 21760 verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks); 21761 verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks); 21762 verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks); 21763 verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks); 21764 verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks); 21765 21766 verifyFormat("foo(^{ bar(); });", ShortBlocks); 21767 verifyFormat("foo(a, ^{ bar(); });", ShortBlocks); 21768 verifyFormat("{ void (^block)(Object *x); }", ShortBlocks); 21769 21770 verifyFormat("[operation setCompletionBlock:^{\n" 21771 " [self onOperationDone];\n" 21772 "}];"); 21773 verifyFormat("int i = {[operation setCompletionBlock:^{\n" 21774 " [self onOperationDone];\n" 21775 "}]};"); 21776 verifyFormat("[operation setCompletionBlock:^(int *i) {\n" 21777 " f();\n" 21778 "}];"); 21779 verifyFormat("int a = [operation block:^int(int *i) {\n" 21780 " return 1;\n" 21781 "}];"); 21782 verifyFormat("[myObject doSomethingWith:arg1\n" 21783 " aaa:^int(int *a) {\n" 21784 " return 1;\n" 21785 " }\n" 21786 " bbb:f(a * bbbbbbbb)];"); 21787 21788 verifyFormat("[operation setCompletionBlock:^{\n" 21789 " [self.delegate newDataAvailable];\n" 21790 "}];", 21791 getLLVMStyleWithColumns(60)); 21792 verifyFormat("dispatch_async(_fileIOQueue, ^{\n" 21793 " NSString *path = [self sessionFilePath];\n" 21794 " if (path) {\n" 21795 " // ...\n" 21796 " }\n" 21797 "});"); 21798 verifyFormat("[[SessionService sharedService]\n" 21799 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 21800 " if (window) {\n" 21801 " [self windowDidLoad:window];\n" 21802 " } else {\n" 21803 " [self errorLoadingWindow];\n" 21804 " }\n" 21805 " }];"); 21806 verifyFormat("void (^largeBlock)(void) = ^{\n" 21807 " // ...\n" 21808 "};\n", 21809 getLLVMStyleWithColumns(40)); 21810 verifyFormat("[[SessionService sharedService]\n" 21811 " loadWindowWithCompletionBlock: //\n" 21812 " ^(SessionWindow *window) {\n" 21813 " if (window) {\n" 21814 " [self windowDidLoad:window];\n" 21815 " } else {\n" 21816 " [self errorLoadingWindow];\n" 21817 " }\n" 21818 " }];", 21819 getLLVMStyleWithColumns(60)); 21820 verifyFormat("[myObject doSomethingWith:arg1\n" 21821 " firstBlock:^(Foo *a) {\n" 21822 " // ...\n" 21823 " int i;\n" 21824 " }\n" 21825 " secondBlock:^(Bar *b) {\n" 21826 " // ...\n" 21827 " int i;\n" 21828 " }\n" 21829 " thirdBlock:^Foo(Bar *b) {\n" 21830 " // ...\n" 21831 " int i;\n" 21832 " }];"); 21833 verifyFormat("[myObject doSomethingWith:arg1\n" 21834 " firstBlock:-1\n" 21835 " secondBlock:^(Bar *b) {\n" 21836 " // ...\n" 21837 " int i;\n" 21838 " }];"); 21839 21840 verifyFormat("f(^{\n" 21841 " @autoreleasepool {\n" 21842 " if (a) {\n" 21843 " g();\n" 21844 " }\n" 21845 " }\n" 21846 "});"); 21847 verifyFormat("Block b = ^int *(A *a, B *b) {}"); 21848 verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n" 21849 "};"); 21850 21851 FormatStyle FourIndent = getLLVMStyle(); 21852 FourIndent.ObjCBlockIndentWidth = 4; 21853 verifyFormat("[operation setCompletionBlock:^{\n" 21854 " [self onOperationDone];\n" 21855 "}];", 21856 FourIndent); 21857 } 21858 21859 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) { 21860 FormatStyle ZeroColumn = getLLVMStyleWithColumns(0); 21861 21862 verifyFormat("[[SessionService sharedService] " 21863 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 21864 " if (window) {\n" 21865 " [self windowDidLoad:window];\n" 21866 " } else {\n" 21867 " [self errorLoadingWindow];\n" 21868 " }\n" 21869 "}];", 21870 ZeroColumn); 21871 EXPECT_EQ("[[SessionService sharedService]\n" 21872 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 21873 " if (window) {\n" 21874 " [self windowDidLoad:window];\n" 21875 " } else {\n" 21876 " [self errorLoadingWindow];\n" 21877 " }\n" 21878 " }];", 21879 format("[[SessionService sharedService]\n" 21880 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 21881 " if (window) {\n" 21882 " [self windowDidLoad:window];\n" 21883 " } else {\n" 21884 " [self errorLoadingWindow];\n" 21885 " }\n" 21886 "}];", 21887 ZeroColumn)); 21888 verifyFormat("[myObject doSomethingWith:arg1\n" 21889 " firstBlock:^(Foo *a) {\n" 21890 " // ...\n" 21891 " int i;\n" 21892 " }\n" 21893 " secondBlock:^(Bar *b) {\n" 21894 " // ...\n" 21895 " int i;\n" 21896 " }\n" 21897 " thirdBlock:^Foo(Bar *b) {\n" 21898 " // ...\n" 21899 " int i;\n" 21900 " }];", 21901 ZeroColumn); 21902 verifyFormat("f(^{\n" 21903 " @autoreleasepool {\n" 21904 " if (a) {\n" 21905 " g();\n" 21906 " }\n" 21907 " }\n" 21908 "});", 21909 ZeroColumn); 21910 verifyFormat("void (^largeBlock)(void) = ^{\n" 21911 " // ...\n" 21912 "};", 21913 ZeroColumn); 21914 21915 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 21916 EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };", 21917 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn)); 21918 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 21919 EXPECT_EQ("void (^largeBlock)(void) = ^{\n" 21920 " int i;\n" 21921 "};", 21922 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn)); 21923 } 21924 21925 TEST_F(FormatTest, SupportsCRLF) { 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;\r\n" 21931 " int c;\r\n", 21932 getLLVMStyle())); 21933 EXPECT_EQ("int a;\r\n" 21934 "int b;\r\n" 21935 "int c;\r\n", 21936 format("int a;\r\n" 21937 " int b;\n" 21938 " int c;\r\n", 21939 getLLVMStyle())); 21940 EXPECT_EQ("int a;\n" 21941 "int b;\n" 21942 "int c;\n", 21943 format("int a;\r\n" 21944 " int b;\n" 21945 " int c;\n", 21946 getLLVMStyle())); 21947 EXPECT_EQ("\"aaaaaaa \"\r\n" 21948 "\"bbbbbbb\";\r\n", 21949 format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10))); 21950 EXPECT_EQ("#define A \\\r\n" 21951 " b; \\\r\n" 21952 " c; \\\r\n" 21953 " d;\r\n", 21954 format("#define A \\\r\n" 21955 " b; \\\r\n" 21956 " c; d; \r\n", 21957 getGoogleStyle())); 21958 21959 EXPECT_EQ("/*\r\n" 21960 "multi line block comments\r\n" 21961 "should not introduce\r\n" 21962 "an extra carriage return\r\n" 21963 "*/\r\n", 21964 format("/*\r\n" 21965 "multi line block comments\r\n" 21966 "should not introduce\r\n" 21967 "an extra carriage return\r\n" 21968 "*/\r\n")); 21969 EXPECT_EQ("/*\r\n" 21970 "\r\n" 21971 "*/", 21972 format("/*\r\n" 21973 " \r\r\r\n" 21974 "*/")); 21975 21976 FormatStyle style = getLLVMStyle(); 21977 21978 style.DeriveLineEnding = true; 21979 style.UseCRLF = false; 21980 EXPECT_EQ("union FooBarBazQux {\n" 21981 " int foo;\n" 21982 " int bar;\n" 21983 " int baz;\n" 21984 "};", 21985 format("union FooBarBazQux {\r\n" 21986 " int foo;\n" 21987 " int bar;\r\n" 21988 " int baz;\n" 21989 "};", 21990 style)); 21991 style.UseCRLF = true; 21992 EXPECT_EQ("union FooBarBazQux {\r\n" 21993 " int foo;\r\n" 21994 " int bar;\r\n" 21995 " int baz;\r\n" 21996 "};", 21997 format("union FooBarBazQux {\r\n" 21998 " int foo;\n" 21999 " int bar;\r\n" 22000 " int baz;\n" 22001 "};", 22002 style)); 22003 22004 style.DeriveLineEnding = false; 22005 style.UseCRLF = false; 22006 EXPECT_EQ("union FooBarBazQux {\n" 22007 " int foo;\n" 22008 " int bar;\n" 22009 " int baz;\n" 22010 " int qux;\n" 22011 "};", 22012 format("union FooBarBazQux {\r\n" 22013 " int foo;\n" 22014 " int bar;\r\n" 22015 " int baz;\n" 22016 " int qux;\r\n" 22017 "};", 22018 style)); 22019 style.UseCRLF = true; 22020 EXPECT_EQ("union FooBarBazQux {\r\n" 22021 " int foo;\r\n" 22022 " int bar;\r\n" 22023 " int baz;\r\n" 22024 " int qux;\r\n" 22025 "};", 22026 format("union FooBarBazQux {\r\n" 22027 " int foo;\n" 22028 " int bar;\r\n" 22029 " int baz;\n" 22030 " int qux;\n" 22031 "};", 22032 style)); 22033 22034 style.DeriveLineEnding = true; 22035 style.UseCRLF = false; 22036 EXPECT_EQ("union FooBarBazQux {\r\n" 22037 " int foo;\r\n" 22038 " int bar;\r\n" 22039 " int baz;\r\n" 22040 " int qux;\r\n" 22041 "};", 22042 format("union FooBarBazQux {\r\n" 22043 " int foo;\n" 22044 " int bar;\r\n" 22045 " int baz;\n" 22046 " int qux;\r\n" 22047 "};", 22048 style)); 22049 style.UseCRLF = true; 22050 EXPECT_EQ("union FooBarBazQux {\n" 22051 " int foo;\n" 22052 " int bar;\n" 22053 " int baz;\n" 22054 " int qux;\n" 22055 "};", 22056 format("union FooBarBazQux {\r\n" 22057 " int foo;\n" 22058 " int bar;\r\n" 22059 " int baz;\n" 22060 " int qux;\n" 22061 "};", 22062 style)); 22063 } 22064 22065 TEST_F(FormatTest, MunchSemicolonAfterBlocks) { 22066 verifyFormat("MY_CLASS(C) {\n" 22067 " int i;\n" 22068 " int j;\n" 22069 "};"); 22070 } 22071 22072 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) { 22073 FormatStyle TwoIndent = getLLVMStyleWithColumns(15); 22074 TwoIndent.ContinuationIndentWidth = 2; 22075 22076 EXPECT_EQ("int i =\n" 22077 " longFunction(\n" 22078 " arg);", 22079 format("int i = longFunction(arg);", TwoIndent)); 22080 22081 FormatStyle SixIndent = getLLVMStyleWithColumns(20); 22082 SixIndent.ContinuationIndentWidth = 6; 22083 22084 EXPECT_EQ("int i =\n" 22085 " longFunction(\n" 22086 " arg);", 22087 format("int i = longFunction(arg);", SixIndent)); 22088 } 22089 22090 TEST_F(FormatTest, WrappedClosingParenthesisIndent) { 22091 FormatStyle Style = getLLVMStyle(); 22092 verifyFormat("int Foo::getter(\n" 22093 " //\n" 22094 ") const {\n" 22095 " return foo;\n" 22096 "}", 22097 Style); 22098 verifyFormat("void Foo::setter(\n" 22099 " //\n" 22100 ") {\n" 22101 " foo = 1;\n" 22102 "}", 22103 Style); 22104 } 22105 22106 TEST_F(FormatTest, SpacesInAngles) { 22107 FormatStyle Spaces = getLLVMStyle(); 22108 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22109 22110 verifyFormat("vector< ::std::string > x1;", Spaces); 22111 verifyFormat("Foo< int, Bar > x2;", Spaces); 22112 verifyFormat("Foo< ::int, ::Bar > x3;", Spaces); 22113 22114 verifyFormat("static_cast< int >(arg);", Spaces); 22115 verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces); 22116 verifyFormat("f< int, float >();", Spaces); 22117 verifyFormat("template <> g() {}", Spaces); 22118 verifyFormat("template < std::vector< int > > f() {}", Spaces); 22119 verifyFormat("std::function< void(int, int) > fct;", Spaces); 22120 verifyFormat("void inFunction() { std::function< void(int, int) > fct; }", 22121 Spaces); 22122 22123 Spaces.Standard = FormatStyle::LS_Cpp03; 22124 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22125 verifyFormat("A< A< int > >();", Spaces); 22126 22127 Spaces.SpacesInAngles = FormatStyle::SIAS_Never; 22128 verifyFormat("A<A<int> >();", Spaces); 22129 22130 Spaces.SpacesInAngles = FormatStyle::SIAS_Leave; 22131 verifyFormat("vector< ::std::string> x4;", "vector<::std::string> x4;", 22132 Spaces); 22133 verifyFormat("vector< ::std::string > x4;", "vector<::std::string > x4;", 22134 Spaces); 22135 22136 verifyFormat("A<A<int> >();", Spaces); 22137 verifyFormat("A<A<int> >();", "A<A<int>>();", Spaces); 22138 verifyFormat("A< A< int > >();", Spaces); 22139 22140 Spaces.Standard = FormatStyle::LS_Cpp11; 22141 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22142 verifyFormat("A< A< int > >();", Spaces); 22143 22144 Spaces.SpacesInAngles = FormatStyle::SIAS_Never; 22145 verifyFormat("vector<::std::string> x4;", Spaces); 22146 verifyFormat("vector<int> x5;", Spaces); 22147 verifyFormat("Foo<int, Bar> x6;", Spaces); 22148 verifyFormat("Foo<::int, ::Bar> x7;", Spaces); 22149 22150 verifyFormat("A<A<int>>();", Spaces); 22151 22152 Spaces.SpacesInAngles = FormatStyle::SIAS_Leave; 22153 verifyFormat("vector<::std::string> x4;", Spaces); 22154 verifyFormat("vector< ::std::string > x4;", Spaces); 22155 verifyFormat("vector<int> x5;", Spaces); 22156 verifyFormat("vector< int > x5;", Spaces); 22157 verifyFormat("Foo<int, Bar> x6;", Spaces); 22158 verifyFormat("Foo< int, Bar > x6;", Spaces); 22159 verifyFormat("Foo<::int, ::Bar> x7;", Spaces); 22160 verifyFormat("Foo< ::int, ::Bar > x7;", Spaces); 22161 22162 verifyFormat("A<A<int>>();", Spaces); 22163 verifyFormat("A< A< int > >();", Spaces); 22164 verifyFormat("A<A<int > >();", Spaces); 22165 verifyFormat("A< A< int>>();", Spaces); 22166 22167 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22168 verifyFormat("// clang-format off\n" 22169 "foo<<<1, 1>>>();\n" 22170 "// clang-format on\n", 22171 Spaces); 22172 verifyFormat("// clang-format off\n" 22173 "foo< < <1, 1> > >();\n" 22174 "// clang-format on\n", 22175 Spaces); 22176 } 22177 22178 TEST_F(FormatTest, SpaceAfterTemplateKeyword) { 22179 FormatStyle Style = getLLVMStyle(); 22180 Style.SpaceAfterTemplateKeyword = false; 22181 verifyFormat("template<int> void foo();", Style); 22182 } 22183 22184 TEST_F(FormatTest, TripleAngleBrackets) { 22185 verifyFormat("f<<<1, 1>>>();"); 22186 verifyFormat("f<<<1, 1, 1, s>>>();"); 22187 verifyFormat("f<<<a, b, c, d>>>();"); 22188 EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();")); 22189 verifyFormat("f<param><<<1, 1>>>();"); 22190 verifyFormat("f<1><<<1, 1>>>();"); 22191 EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();")); 22192 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 22193 "aaaaaaaaaaa<<<\n 1, 1>>>();"); 22194 verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n" 22195 " <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();"); 22196 } 22197 22198 TEST_F(FormatTest, MergeLessLessAtEnd) { 22199 verifyFormat("<<"); 22200 EXPECT_EQ("< < <", format("\\\n<<<")); 22201 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 22202 "aaallvm::outs() <<"); 22203 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 22204 "aaaallvm::outs()\n <<"); 22205 } 22206 22207 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) { 22208 std::string code = "#if A\n" 22209 "#if B\n" 22210 "a.\n" 22211 "#endif\n" 22212 " a = 1;\n" 22213 "#else\n" 22214 "#endif\n" 22215 "#if C\n" 22216 "#else\n" 22217 "#endif\n"; 22218 EXPECT_EQ(code, format(code)); 22219 } 22220 22221 TEST_F(FormatTest, HandleConflictMarkers) { 22222 // Git/SVN conflict markers. 22223 EXPECT_EQ("int a;\n" 22224 "void f() {\n" 22225 " callme(some(parameter1,\n" 22226 "<<<<<<< text by the vcs\n" 22227 " parameter2),\n" 22228 "||||||| text by the vcs\n" 22229 " parameter2),\n" 22230 " parameter3,\n" 22231 "======= text by the vcs\n" 22232 " parameter2, parameter3),\n" 22233 ">>>>>>> text by the vcs\n" 22234 " otherparameter);\n", 22235 format("int a;\n" 22236 "void f() {\n" 22237 " callme(some(parameter1,\n" 22238 "<<<<<<< text by the vcs\n" 22239 " parameter2),\n" 22240 "||||||| text by the vcs\n" 22241 " parameter2),\n" 22242 " parameter3,\n" 22243 "======= text by the vcs\n" 22244 " parameter2,\n" 22245 " parameter3),\n" 22246 ">>>>>>> text by the vcs\n" 22247 " otherparameter);\n")); 22248 22249 // Perforce markers. 22250 EXPECT_EQ("void f() {\n" 22251 " function(\n" 22252 ">>>> text by the vcs\n" 22253 " parameter,\n" 22254 "==== text by the vcs\n" 22255 " parameter,\n" 22256 "==== text by the vcs\n" 22257 " parameter,\n" 22258 "<<<< text by the vcs\n" 22259 " parameter);\n", 22260 format("void f() {\n" 22261 " function(\n" 22262 ">>>> text by the vcs\n" 22263 " parameter,\n" 22264 "==== text by the vcs\n" 22265 " parameter,\n" 22266 "==== text by the vcs\n" 22267 " parameter,\n" 22268 "<<<< text by the vcs\n" 22269 " parameter);\n")); 22270 22271 EXPECT_EQ("<<<<<<<\n" 22272 "|||||||\n" 22273 "=======\n" 22274 ">>>>>>>", 22275 format("<<<<<<<\n" 22276 "|||||||\n" 22277 "=======\n" 22278 ">>>>>>>")); 22279 22280 EXPECT_EQ("<<<<<<<\n" 22281 "|||||||\n" 22282 "int i;\n" 22283 "=======\n" 22284 ">>>>>>>", 22285 format("<<<<<<<\n" 22286 "|||||||\n" 22287 "int i;\n" 22288 "=======\n" 22289 ">>>>>>>")); 22290 22291 // FIXME: Handle parsing of macros around conflict markers correctly: 22292 EXPECT_EQ("#define Macro \\\n" 22293 "<<<<<<<\n" 22294 "Something \\\n" 22295 "|||||||\n" 22296 "Else \\\n" 22297 "=======\n" 22298 "Other \\\n" 22299 ">>>>>>>\n" 22300 " End int i;\n", 22301 format("#define Macro \\\n" 22302 "<<<<<<<\n" 22303 " Something \\\n" 22304 "|||||||\n" 22305 " Else \\\n" 22306 "=======\n" 22307 " Other \\\n" 22308 ">>>>>>>\n" 22309 " End\n" 22310 "int i;\n")); 22311 22312 verifyFormat(R"(==== 22313 #ifdef A 22314 a 22315 #else 22316 b 22317 #endif 22318 )"); 22319 } 22320 22321 TEST_F(FormatTest, DisableRegions) { 22322 EXPECT_EQ("int i;\n" 22323 "// clang-format off\n" 22324 " int j;\n" 22325 "// clang-format on\n" 22326 "int k;", 22327 format(" int i;\n" 22328 " // clang-format off\n" 22329 " int j;\n" 22330 " // clang-format on\n" 22331 " int k;")); 22332 EXPECT_EQ("int i;\n" 22333 "/* clang-format off */\n" 22334 " int j;\n" 22335 "/* clang-format on */\n" 22336 "int k;", 22337 format(" int i;\n" 22338 " /* clang-format off */\n" 22339 " int j;\n" 22340 " /* clang-format on */\n" 22341 " int k;")); 22342 22343 // Don't reflow comments within disabled regions. 22344 EXPECT_EQ("// clang-format off\n" 22345 "// long long long long long long line\n" 22346 "/* clang-format on */\n" 22347 "/* long long long\n" 22348 " * long long long\n" 22349 " * line */\n" 22350 "int i;\n" 22351 "/* clang-format off */\n" 22352 "/* long long long long long long line */\n", 22353 format("// clang-format off\n" 22354 "// long long long long long long line\n" 22355 "/* clang-format on */\n" 22356 "/* long long long long long long line */\n" 22357 "int i;\n" 22358 "/* clang-format off */\n" 22359 "/* long long long long long long line */\n", 22360 getLLVMStyleWithColumns(20))); 22361 } 22362 22363 TEST_F(FormatTest, DoNotCrashOnInvalidInput) { 22364 format("? ) ="); 22365 verifyNoCrash("#define a\\\n /**/}"); 22366 } 22367 22368 TEST_F(FormatTest, FormatsTableGenCode) { 22369 FormatStyle Style = getLLVMStyle(); 22370 Style.Language = FormatStyle::LK_TableGen; 22371 verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style); 22372 } 22373 22374 TEST_F(FormatTest, ArrayOfTemplates) { 22375 EXPECT_EQ("auto a = new unique_ptr<int>[10];", 22376 format("auto a = new unique_ptr<int > [ 10];")); 22377 22378 FormatStyle Spaces = getLLVMStyle(); 22379 Spaces.SpacesInSquareBrackets = true; 22380 EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];", 22381 format("auto a = new unique_ptr<int > [10];", Spaces)); 22382 } 22383 22384 TEST_F(FormatTest, ArrayAsTemplateType) { 22385 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;", 22386 format("auto a = unique_ptr < Foo < Bar>[ 10]> ;")); 22387 22388 FormatStyle Spaces = getLLVMStyle(); 22389 Spaces.SpacesInSquareBrackets = true; 22390 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;", 22391 format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces)); 22392 } 22393 22394 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); } 22395 22396 TEST(FormatStyle, GetStyleWithEmptyFileName) { 22397 llvm::vfs::InMemoryFileSystem FS; 22398 auto Style1 = getStyle("file", "", "Google", "", &FS); 22399 ASSERT_TRUE((bool)Style1); 22400 ASSERT_EQ(*Style1, getGoogleStyle()); 22401 } 22402 22403 TEST(FormatStyle, GetStyleOfFile) { 22404 llvm::vfs::InMemoryFileSystem FS; 22405 // Test 1: format file in the same directory. 22406 ASSERT_TRUE( 22407 FS.addFile("/a/.clang-format", 0, 22408 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM"))); 22409 ASSERT_TRUE( 22410 FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22411 auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS); 22412 ASSERT_TRUE((bool)Style1); 22413 ASSERT_EQ(*Style1, getLLVMStyle()); 22414 22415 // Test 2.1: fallback to default. 22416 ASSERT_TRUE( 22417 FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22418 auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS); 22419 ASSERT_TRUE((bool)Style2); 22420 ASSERT_EQ(*Style2, getMozillaStyle()); 22421 22422 // Test 2.2: no format on 'none' fallback style. 22423 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS); 22424 ASSERT_TRUE((bool)Style2); 22425 ASSERT_EQ(*Style2, getNoStyle()); 22426 22427 // Test 2.3: format if config is found with no based style while fallback is 22428 // 'none'. 22429 ASSERT_TRUE(FS.addFile("/b/.clang-format", 0, 22430 llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2"))); 22431 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS); 22432 ASSERT_TRUE((bool)Style2); 22433 ASSERT_EQ(*Style2, getLLVMStyle()); 22434 22435 // Test 2.4: format if yaml with no based style, while fallback is 'none'. 22436 Style2 = getStyle("{}", "a.h", "none", "", &FS); 22437 ASSERT_TRUE((bool)Style2); 22438 ASSERT_EQ(*Style2, getLLVMStyle()); 22439 22440 // Test 3: format file in parent directory. 22441 ASSERT_TRUE( 22442 FS.addFile("/c/.clang-format", 0, 22443 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 22444 ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0, 22445 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22446 auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS); 22447 ASSERT_TRUE((bool)Style3); 22448 ASSERT_EQ(*Style3, getGoogleStyle()); 22449 22450 // Test 4: error on invalid fallback style 22451 auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS); 22452 ASSERT_FALSE((bool)Style4); 22453 llvm::consumeError(Style4.takeError()); 22454 22455 // Test 5: error on invalid yaml on command line 22456 auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS); 22457 ASSERT_FALSE((bool)Style5); 22458 llvm::consumeError(Style5.takeError()); 22459 22460 // Test 6: error on invalid style 22461 auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS); 22462 ASSERT_FALSE((bool)Style6); 22463 llvm::consumeError(Style6.takeError()); 22464 22465 // Test 7: found config file, error on parsing it 22466 ASSERT_TRUE( 22467 FS.addFile("/d/.clang-format", 0, 22468 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n" 22469 "InvalidKey: InvalidValue"))); 22470 ASSERT_TRUE( 22471 FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22472 auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS); 22473 ASSERT_FALSE((bool)Style7a); 22474 llvm::consumeError(Style7a.takeError()); 22475 22476 auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true); 22477 ASSERT_TRUE((bool)Style7b); 22478 22479 // Test 8: inferred per-language defaults apply. 22480 auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS); 22481 ASSERT_TRUE((bool)StyleTd); 22482 ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen)); 22483 22484 // Test 9.1.1: overwriting a file style, when no parent file exists with no 22485 // fallback style. 22486 ASSERT_TRUE(FS.addFile( 22487 "/e/sub/.clang-format", 0, 22488 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n" 22489 "ColumnLimit: 20"))); 22490 ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0, 22491 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22492 auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS); 22493 ASSERT_TRUE(static_cast<bool>(Style9)); 22494 ASSERT_EQ(*Style9, [] { 22495 auto Style = getNoStyle(); 22496 Style.ColumnLimit = 20; 22497 return Style; 22498 }()); 22499 22500 // Test 9.1.2: propagate more than one level with no parent file. 22501 ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0, 22502 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22503 ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0, 22504 llvm::MemoryBuffer::getMemBuffer( 22505 "BasedOnStyle: InheritParentConfig\n" 22506 "WhitespaceSensitiveMacros: ['FOO', 'BAR']"))); 22507 std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"}; 22508 22509 ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros); 22510 Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS); 22511 ASSERT_TRUE(static_cast<bool>(Style9)); 22512 ASSERT_EQ(*Style9, [&NonDefaultWhiteSpaceMacros] { 22513 auto Style = getNoStyle(); 22514 Style.ColumnLimit = 20; 22515 Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros; 22516 return Style; 22517 }()); 22518 22519 // Test 9.2: with LLVM fallback style 22520 Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS); 22521 ASSERT_TRUE(static_cast<bool>(Style9)); 22522 ASSERT_EQ(*Style9, [] { 22523 auto Style = getLLVMStyle(); 22524 Style.ColumnLimit = 20; 22525 return Style; 22526 }()); 22527 22528 // Test 9.3: with a parent file 22529 ASSERT_TRUE( 22530 FS.addFile("/e/.clang-format", 0, 22531 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n" 22532 "UseTab: Always"))); 22533 Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS); 22534 ASSERT_TRUE(static_cast<bool>(Style9)); 22535 ASSERT_EQ(*Style9, [] { 22536 auto Style = getGoogleStyle(); 22537 Style.ColumnLimit = 20; 22538 Style.UseTab = FormatStyle::UT_Always; 22539 return Style; 22540 }()); 22541 22542 // Test 9.4: propagate more than one level with a parent file. 22543 const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] { 22544 auto Style = getGoogleStyle(); 22545 Style.ColumnLimit = 20; 22546 Style.UseTab = FormatStyle::UT_Always; 22547 Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros; 22548 return Style; 22549 }(); 22550 22551 ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros); 22552 Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS); 22553 ASSERT_TRUE(static_cast<bool>(Style9)); 22554 ASSERT_EQ(*Style9, SubSubStyle); 22555 22556 // Test 9.5: use InheritParentConfig as style name 22557 Style9 = 22558 getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS); 22559 ASSERT_TRUE(static_cast<bool>(Style9)); 22560 ASSERT_EQ(*Style9, SubSubStyle); 22561 22562 // Test 9.6: use command line style with inheritance 22563 Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp", 22564 "none", "", &FS); 22565 ASSERT_TRUE(static_cast<bool>(Style9)); 22566 ASSERT_EQ(*Style9, SubSubStyle); 22567 22568 // Test 9.7: use command line style with inheritance and own config 22569 Style9 = getStyle("{BasedOnStyle: InheritParentConfig, " 22570 "WhitespaceSensitiveMacros: ['FOO', 'BAR']}", 22571 "/e/sub/code.cpp", "none", "", &FS); 22572 ASSERT_TRUE(static_cast<bool>(Style9)); 22573 ASSERT_EQ(*Style9, SubSubStyle); 22574 22575 // Test 9.8: use inheritance from a file without BasedOnStyle 22576 ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0, 22577 llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123"))); 22578 ASSERT_TRUE( 22579 FS.addFile("/e/withoutbase/sub/.clang-format", 0, 22580 llvm::MemoryBuffer::getMemBuffer( 22581 "BasedOnStyle: InheritParentConfig\nIndentWidth: 7"))); 22582 // Make sure we do not use the fallback style 22583 Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS); 22584 ASSERT_TRUE(static_cast<bool>(Style9)); 22585 ASSERT_EQ(*Style9, [] { 22586 auto Style = getLLVMStyle(); 22587 Style.ColumnLimit = 123; 22588 return Style; 22589 }()); 22590 22591 Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS); 22592 ASSERT_TRUE(static_cast<bool>(Style9)); 22593 ASSERT_EQ(*Style9, [] { 22594 auto Style = getLLVMStyle(); 22595 Style.ColumnLimit = 123; 22596 Style.IndentWidth = 7; 22597 return Style; 22598 }()); 22599 22600 // Test 9.9: use inheritance from a specific config file. 22601 Style9 = getStyle("file:/e/sub/sub/.clang-format", "/e/sub/sub/code.cpp", 22602 "none", "", &FS); 22603 ASSERT_TRUE(static_cast<bool>(Style9)); 22604 ASSERT_EQ(*Style9, SubSubStyle); 22605 } 22606 22607 TEST(FormatStyle, GetStyleOfSpecificFile) { 22608 llvm::vfs::InMemoryFileSystem FS; 22609 // Specify absolute path to a format file in a parent directory. 22610 ASSERT_TRUE( 22611 FS.addFile("/e/.clang-format", 0, 22612 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM"))); 22613 ASSERT_TRUE( 22614 FS.addFile("/e/explicit.clang-format", 0, 22615 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 22616 ASSERT_TRUE(FS.addFile("/e/sub/sub/sub/test.cpp", 0, 22617 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22618 auto Style = getStyle("file:/e/explicit.clang-format", 22619 "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS); 22620 ASSERT_TRUE(static_cast<bool>(Style)); 22621 ASSERT_EQ(*Style, getGoogleStyle()); 22622 22623 // Specify relative path to a format file. 22624 ASSERT_TRUE( 22625 FS.addFile("../../e/explicit.clang-format", 0, 22626 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 22627 Style = getStyle("file:../../e/explicit.clang-format", 22628 "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS); 22629 ASSERT_TRUE(static_cast<bool>(Style)); 22630 ASSERT_EQ(*Style, getGoogleStyle()); 22631 22632 // Specify path to a format file that does not exist. 22633 Style = getStyle("file:/e/missing.clang-format", "/e/sub/sub/sub/test.cpp", 22634 "LLVM", "", &FS); 22635 ASSERT_FALSE(static_cast<bool>(Style)); 22636 llvm::consumeError(Style.takeError()); 22637 22638 // Specify path to a file on the filesystem. 22639 SmallString<128> FormatFilePath; 22640 std::error_code ECF = llvm::sys::fs::createTemporaryFile( 22641 "FormatFileTest", "tpl", FormatFilePath); 22642 EXPECT_FALSE((bool)ECF); 22643 llvm::raw_fd_ostream FormatFileTest(FormatFilePath, ECF); 22644 EXPECT_FALSE((bool)ECF); 22645 FormatFileTest << "BasedOnStyle: Google\n"; 22646 FormatFileTest.close(); 22647 22648 SmallString<128> TestFilePath; 22649 std::error_code ECT = 22650 llvm::sys::fs::createTemporaryFile("CodeFileTest", "cc", TestFilePath); 22651 EXPECT_FALSE((bool)ECT); 22652 llvm::raw_fd_ostream CodeFileTest(TestFilePath, ECT); 22653 CodeFileTest << "int i;\n"; 22654 CodeFileTest.close(); 22655 22656 std::string format_file_arg = std::string("file:") + FormatFilePath.c_str(); 22657 Style = getStyle(format_file_arg, TestFilePath, "LLVM", "", nullptr); 22658 22659 llvm::sys::fs::remove(FormatFilePath.c_str()); 22660 llvm::sys::fs::remove(TestFilePath.c_str()); 22661 ASSERT_TRUE(static_cast<bool>(Style)); 22662 ASSERT_EQ(*Style, getGoogleStyle()); 22663 } 22664 22665 TEST_F(ReplacementTest, FormatCodeAfterReplacements) { 22666 // Column limit is 20. 22667 std::string Code = "Type *a =\n" 22668 " new Type();\n" 22669 "g(iiiii, 0, jjjjj,\n" 22670 " 0, kkkkk, 0, mm);\n" 22671 "int bad = format ;"; 22672 std::string Expected = "auto a = new Type();\n" 22673 "g(iiiii, nullptr,\n" 22674 " jjjjj, nullptr,\n" 22675 " kkkkk, nullptr,\n" 22676 " mm);\n" 22677 "int bad = format ;"; 22678 FileID ID = Context.createInMemoryFile("format.cpp", Code); 22679 tooling::Replacements Replaces = toReplacements( 22680 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6, 22681 "auto "), 22682 tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1, 22683 "nullptr"), 22684 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1, 22685 "nullptr"), 22686 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1, 22687 "nullptr")}); 22688 22689 FormatStyle Style = getLLVMStyle(); 22690 Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility. 22691 auto FormattedReplaces = formatReplacements(Code, Replaces, Style); 22692 EXPECT_TRUE(static_cast<bool>(FormattedReplaces)) 22693 << llvm::toString(FormattedReplaces.takeError()) << "\n"; 22694 auto Result = applyAllReplacements(Code, *FormattedReplaces); 22695 EXPECT_TRUE(static_cast<bool>(Result)); 22696 EXPECT_EQ(Expected, *Result); 22697 } 22698 22699 TEST_F(ReplacementTest, SortIncludesAfterReplacement) { 22700 std::string Code = "#include \"a.h\"\n" 22701 "#include \"c.h\"\n" 22702 "\n" 22703 "int main() {\n" 22704 " return 0;\n" 22705 "}"; 22706 std::string Expected = "#include \"a.h\"\n" 22707 "#include \"b.h\"\n" 22708 "#include \"c.h\"\n" 22709 "\n" 22710 "int main() {\n" 22711 " return 0;\n" 22712 "}"; 22713 FileID ID = Context.createInMemoryFile("fix.cpp", Code); 22714 tooling::Replacements Replaces = toReplacements( 22715 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0, 22716 "#include \"b.h\"\n")}); 22717 22718 FormatStyle Style = getLLVMStyle(); 22719 Style.SortIncludes = FormatStyle::SI_CaseSensitive; 22720 auto FormattedReplaces = formatReplacements(Code, Replaces, Style); 22721 EXPECT_TRUE(static_cast<bool>(FormattedReplaces)) 22722 << llvm::toString(FormattedReplaces.takeError()) << "\n"; 22723 auto Result = applyAllReplacements(Code, *FormattedReplaces); 22724 EXPECT_TRUE(static_cast<bool>(Result)); 22725 EXPECT_EQ(Expected, *Result); 22726 } 22727 22728 TEST_F(FormatTest, FormatSortsUsingDeclarations) { 22729 EXPECT_EQ("using std::cin;\n" 22730 "using std::cout;", 22731 format("using std::cout;\n" 22732 "using std::cin;", 22733 getGoogleStyle())); 22734 } 22735 22736 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) { 22737 FormatStyle Style = getLLVMStyle(); 22738 Style.Standard = FormatStyle::LS_Cpp03; 22739 // cpp03 recognize this string as identifier u8 and literal character 'a' 22740 EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style)); 22741 } 22742 22743 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) { 22744 // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers 22745 // all modes, including C++11, C++14 and C++17 22746 EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';")); 22747 } 22748 22749 TEST_F(FormatTest, DoNotFormatLikelyXml) { 22750 EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle())); 22751 EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle())); 22752 } 22753 22754 TEST_F(FormatTest, StructuredBindings) { 22755 // Structured bindings is a C++17 feature. 22756 // all modes, including C++11, C++14 and C++17 22757 verifyFormat("auto [a, b] = f();"); 22758 EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();")); 22759 EXPECT_EQ("const auto [a, b] = f();", format("const auto[a, b] = f();")); 22760 EXPECT_EQ("auto const [a, b] = f();", format("auto const[a, b] = f();")); 22761 EXPECT_EQ("auto const volatile [a, b] = f();", 22762 format("auto const volatile[a, b] = f();")); 22763 EXPECT_EQ("auto [a, b, c] = f();", format("auto [ a , b,c ] = f();")); 22764 EXPECT_EQ("auto &[a, b, c] = f();", 22765 format("auto &[ a , b,c ] = f();")); 22766 EXPECT_EQ("auto &&[a, b, c] = f();", 22767 format("auto &&[ a , b,c ] = f();")); 22768 EXPECT_EQ("auto const &[a, b] = f();", format("auto const&[a, b] = f();")); 22769 EXPECT_EQ("auto const volatile &&[a, b] = f();", 22770 format("auto const volatile &&[a, b] = f();")); 22771 EXPECT_EQ("auto const &&[a, b] = f();", 22772 format("auto const && [a, b] = f();")); 22773 EXPECT_EQ("const auto &[a, b] = f();", 22774 format("const auto & [a, b] = f();")); 22775 EXPECT_EQ("const auto volatile &&[a, b] = f();", 22776 format("const auto volatile &&[a, b] = f();")); 22777 EXPECT_EQ("volatile const auto &&[a, b] = f();", 22778 format("volatile const auto &&[a, b] = f();")); 22779 EXPECT_EQ("const auto &&[a, b] = f();", 22780 format("const auto && [a, b] = f();")); 22781 22782 // Make sure we don't mistake structured bindings for lambdas. 22783 FormatStyle PointerMiddle = getLLVMStyle(); 22784 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle; 22785 verifyFormat("auto [a1, b]{A * i};", getGoogleStyle()); 22786 verifyFormat("auto [a2, b]{A * i};", getLLVMStyle()); 22787 verifyFormat("auto [a3, b]{A * i};", PointerMiddle); 22788 verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle()); 22789 verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle()); 22790 verifyFormat("auto const [a3, b]{A * i};", PointerMiddle); 22791 verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle()); 22792 verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle()); 22793 verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle); 22794 verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle()); 22795 verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle()); 22796 verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle); 22797 22798 EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}", 22799 format("for (const auto && [a, b] : some_range) {\n}")); 22800 EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}", 22801 format("for (const auto & [a, b] : some_range) {\n}")); 22802 EXPECT_EQ("for (const auto [a, b] : some_range) {\n}", 22803 format("for (const auto[a, b] : some_range) {\n}")); 22804 EXPECT_EQ("auto [x, y](expr);", format("auto[x,y] (expr);")); 22805 EXPECT_EQ("auto &[x, y](expr);", format("auto & [x,y] (expr);")); 22806 EXPECT_EQ("auto &&[x, y](expr);", format("auto && [x,y] (expr);")); 22807 EXPECT_EQ("auto const &[x, y](expr);", 22808 format("auto const & [x,y] (expr);")); 22809 EXPECT_EQ("auto const &&[x, y](expr);", 22810 format("auto const && [x,y] (expr);")); 22811 EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y] {expr};")); 22812 EXPECT_EQ("auto const &[x, y]{expr};", 22813 format("auto const & [x,y] {expr};")); 22814 EXPECT_EQ("auto const &&[x, y]{expr};", 22815 format("auto const && [x,y] {expr};")); 22816 22817 FormatStyle Spaces = getLLVMStyle(); 22818 Spaces.SpacesInSquareBrackets = true; 22819 verifyFormat("auto [ a, b ] = f();", Spaces); 22820 verifyFormat("auto &&[ a, b ] = f();", Spaces); 22821 verifyFormat("auto &[ a, b ] = f();", Spaces); 22822 verifyFormat("auto const &&[ a, b ] = f();", Spaces); 22823 verifyFormat("auto const &[ a, b ] = f();", Spaces); 22824 } 22825 22826 TEST_F(FormatTest, FileAndCode) { 22827 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", "")); 22828 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", "")); 22829 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", "")); 22830 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "")); 22831 EXPECT_EQ(FormatStyle::LK_ObjC, 22832 guessLanguage("foo.h", "@interface Foo\n@end\n")); 22833 EXPECT_EQ( 22834 FormatStyle::LK_ObjC, 22835 guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }")); 22836 EXPECT_EQ(FormatStyle::LK_ObjC, 22837 guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))")); 22838 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;")); 22839 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", "")); 22840 EXPECT_EQ(FormatStyle::LK_ObjC, 22841 guessLanguage("foo", "@interface Foo\n@end\n")); 22842 EXPECT_EQ(FormatStyle::LK_ObjC, 22843 guessLanguage("foo.h", "int DoStuff(CGRect rect);\n")); 22844 EXPECT_EQ( 22845 FormatStyle::LK_ObjC, 22846 guessLanguage("foo.h", 22847 "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n")); 22848 EXPECT_EQ( 22849 FormatStyle::LK_Cpp, 22850 guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;")); 22851 // Only one of the two preprocessor regions has ObjC-like code. 22852 EXPECT_EQ(FormatStyle::LK_ObjC, 22853 guessLanguage("foo.h", "#if A\n" 22854 "#define B() C\n" 22855 "#else\n" 22856 "#define B() [NSString a:@\"\"]\n" 22857 "#endif\n")); 22858 } 22859 22860 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) { 22861 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];")); 22862 EXPECT_EQ(FormatStyle::LK_ObjC, 22863 guessLanguage("foo.h", "array[[calculator getIndex]];")); 22864 EXPECT_EQ(FormatStyle::LK_Cpp, 22865 guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];")); 22866 EXPECT_EQ( 22867 FormatStyle::LK_Cpp, 22868 guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];")); 22869 EXPECT_EQ(FormatStyle::LK_ObjC, 22870 guessLanguage("foo.h", "[[noreturn foo] bar];")); 22871 EXPECT_EQ(FormatStyle::LK_Cpp, 22872 guessLanguage("foo.h", "[[clang::fallthrough]];")); 22873 EXPECT_EQ(FormatStyle::LK_ObjC, 22874 guessLanguage("foo.h", "[[clang:fallthrough] foo];")); 22875 EXPECT_EQ(FormatStyle::LK_Cpp, 22876 guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];")); 22877 EXPECT_EQ(FormatStyle::LK_Cpp, 22878 guessLanguage("foo.h", "[[using clang: fallthrough]];")); 22879 EXPECT_EQ(FormatStyle::LK_ObjC, 22880 guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];")); 22881 EXPECT_EQ(FormatStyle::LK_Cpp, 22882 guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];")); 22883 EXPECT_EQ( 22884 FormatStyle::LK_Cpp, 22885 guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)")); 22886 EXPECT_EQ( 22887 FormatStyle::LK_Cpp, 22888 guessLanguage("foo.h", 22889 "[[clang::callable_when(\"unconsumed\", \"unknown\")]]")); 22890 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]")); 22891 } 22892 22893 TEST_F(FormatTest, GuessLanguageWithCaret) { 22894 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);")); 22895 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);")); 22896 EXPECT_EQ(FormatStyle::LK_ObjC, 22897 guessLanguage("foo.h", "int(^)(char, float);")); 22898 EXPECT_EQ(FormatStyle::LK_ObjC, 22899 guessLanguage("foo.h", "int(^foo)(char, float);")); 22900 EXPECT_EQ(FormatStyle::LK_ObjC, 22901 guessLanguage("foo.h", "int(^foo[10])(char, float);")); 22902 EXPECT_EQ(FormatStyle::LK_ObjC, 22903 guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);")); 22904 EXPECT_EQ( 22905 FormatStyle::LK_ObjC, 22906 guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);")); 22907 } 22908 22909 TEST_F(FormatTest, GuessLanguageWithPragmas) { 22910 EXPECT_EQ(FormatStyle::LK_Cpp, 22911 guessLanguage("foo.h", "__pragma(warning(disable:))")); 22912 EXPECT_EQ(FormatStyle::LK_Cpp, 22913 guessLanguage("foo.h", "#pragma(warning(disable:))")); 22914 EXPECT_EQ(FormatStyle::LK_Cpp, 22915 guessLanguage("foo.h", "_Pragma(warning(disable:))")); 22916 } 22917 22918 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) { 22919 // ASM symbolic names are identifiers that must be surrounded by [] without 22920 // space in between: 22921 // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands 22922 22923 // Example from https://bugs.llvm.org/show_bug.cgi?id=45108. 22924 verifyFormat(R"(// 22925 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result)); 22926 )"); 22927 22928 // A list of several ASM symbolic names. 22929 verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)"); 22930 22931 // ASM symbolic names in inline ASM with inputs and outputs. 22932 verifyFormat(R"(// 22933 asm("cmoveq %1, %2, %[result]" 22934 : [result] "=r"(result) 22935 : "r"(test), "r"(new), "[result]"(old)); 22936 )"); 22937 22938 // ASM symbolic names in inline ASM with no outputs. 22939 verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)"); 22940 } 22941 22942 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) { 22943 EXPECT_EQ(FormatStyle::LK_Cpp, 22944 guessLanguage("foo.h", "void f() {\n" 22945 " asm (\"mov %[e], %[d]\"\n" 22946 " : [d] \"=rm\" (d)\n" 22947 " [e] \"rm\" (*e));\n" 22948 "}")); 22949 EXPECT_EQ(FormatStyle::LK_Cpp, 22950 guessLanguage("foo.h", "void f() {\n" 22951 " _asm (\"mov %[e], %[d]\"\n" 22952 " : [d] \"=rm\" (d)\n" 22953 " [e] \"rm\" (*e));\n" 22954 "}")); 22955 EXPECT_EQ(FormatStyle::LK_Cpp, 22956 guessLanguage("foo.h", "void f() {\n" 22957 " __asm (\"mov %[e], %[d]\"\n" 22958 " : [d] \"=rm\" (d)\n" 22959 " [e] \"rm\" (*e));\n" 22960 "}")); 22961 EXPECT_EQ(FormatStyle::LK_Cpp, 22962 guessLanguage("foo.h", "void f() {\n" 22963 " __asm__ (\"mov %[e], %[d]\"\n" 22964 " : [d] \"=rm\" (d)\n" 22965 " [e] \"rm\" (*e));\n" 22966 "}")); 22967 EXPECT_EQ(FormatStyle::LK_Cpp, 22968 guessLanguage("foo.h", "void f() {\n" 22969 " asm (\"mov %[e], %[d]\"\n" 22970 " : [d] \"=rm\" (d),\n" 22971 " [e] \"rm\" (*e));\n" 22972 "}")); 22973 EXPECT_EQ(FormatStyle::LK_Cpp, 22974 guessLanguage("foo.h", "void f() {\n" 22975 " asm volatile (\"mov %[e], %[d]\"\n" 22976 " : [d] \"=rm\" (d)\n" 22977 " [e] \"rm\" (*e));\n" 22978 "}")); 22979 } 22980 22981 TEST_F(FormatTest, GuessLanguageWithChildLines) { 22982 EXPECT_EQ(FormatStyle::LK_Cpp, 22983 guessLanguage("foo.h", "#define FOO ({ std::string s; })")); 22984 EXPECT_EQ(FormatStyle::LK_ObjC, 22985 guessLanguage("foo.h", "#define FOO ({ NSString *s; })")); 22986 EXPECT_EQ( 22987 FormatStyle::LK_Cpp, 22988 guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })")); 22989 EXPECT_EQ( 22990 FormatStyle::LK_ObjC, 22991 guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })")); 22992 } 22993 22994 TEST_F(FormatTest, TypenameMacros) { 22995 std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"}; 22996 22997 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353 22998 FormatStyle Google = getGoogleStyleWithColumns(0); 22999 Google.TypenameMacros = TypenameMacros; 23000 verifyFormat("struct foo {\n" 23001 " int bar;\n" 23002 " TAILQ_ENTRY(a) bleh;\n" 23003 "};", 23004 Google); 23005 23006 FormatStyle Macros = getLLVMStyle(); 23007 Macros.TypenameMacros = TypenameMacros; 23008 23009 verifyFormat("STACK_OF(int) a;", Macros); 23010 verifyFormat("STACK_OF(int) *a;", Macros); 23011 verifyFormat("STACK_OF(int const *) *a;", Macros); 23012 verifyFormat("STACK_OF(int *const) *a;", Macros); 23013 verifyFormat("STACK_OF(int, string) a;", Macros); 23014 verifyFormat("STACK_OF(LIST(int)) a;", Macros); 23015 verifyFormat("STACK_OF(LIST(int)) a, b;", Macros); 23016 verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros); 23017 verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros); 23018 verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros); 23019 verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros); 23020 23021 Macros.PointerAlignment = FormatStyle::PAS_Left; 23022 verifyFormat("STACK_OF(int)* a;", Macros); 23023 verifyFormat("STACK_OF(int*)* a;", Macros); 23024 verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros); 23025 verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros); 23026 verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros); 23027 } 23028 23029 TEST_F(FormatTest, AtomicQualifier) { 23030 // Check that we treate _Atomic as a type and not a function call 23031 FormatStyle Google = getGoogleStyleWithColumns(0); 23032 verifyFormat("struct foo {\n" 23033 " int a1;\n" 23034 " _Atomic(a) a2;\n" 23035 " _Atomic(_Atomic(int) *const) a3;\n" 23036 "};", 23037 Google); 23038 verifyFormat("_Atomic(uint64_t) a;"); 23039 verifyFormat("_Atomic(uint64_t) *a;"); 23040 verifyFormat("_Atomic(uint64_t const *) *a;"); 23041 verifyFormat("_Atomic(uint64_t *const) *a;"); 23042 verifyFormat("_Atomic(const uint64_t *) *a;"); 23043 verifyFormat("_Atomic(uint64_t) a;"); 23044 verifyFormat("_Atomic(_Atomic(uint64_t)) a;"); 23045 verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;"); 23046 verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}"); 23047 verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);"); 23048 23049 verifyFormat("_Atomic(uint64_t) *s(InitValue);"); 23050 verifyFormat("_Atomic(uint64_t) *s{InitValue};"); 23051 FormatStyle Style = getLLVMStyle(); 23052 Style.PointerAlignment = FormatStyle::PAS_Left; 23053 verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style); 23054 verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style); 23055 verifyFormat("_Atomic(int)* a;", Style); 23056 verifyFormat("_Atomic(int*)* a;", Style); 23057 verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style); 23058 23059 Style.SpacesInCStyleCastParentheses = true; 23060 Style.SpacesInParentheses = false; 23061 verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style); 23062 Style.SpacesInCStyleCastParentheses = false; 23063 Style.SpacesInParentheses = true; 23064 verifyFormat("x = (_Atomic( uint64_t ))*a;", Style); 23065 verifyFormat("x = (_Atomic( uint64_t ))&a;", Style); 23066 } 23067 23068 TEST_F(FormatTest, AmbersandInLamda) { 23069 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899 23070 FormatStyle AlignStyle = getLLVMStyle(); 23071 AlignStyle.PointerAlignment = FormatStyle::PAS_Left; 23072 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle); 23073 AlignStyle.PointerAlignment = FormatStyle::PAS_Right; 23074 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle); 23075 } 23076 23077 TEST_F(FormatTest, SpacesInConditionalStatement) { 23078 FormatStyle Spaces = getLLVMStyle(); 23079 Spaces.IfMacros.clear(); 23080 Spaces.IfMacros.push_back("MYIF"); 23081 Spaces.SpacesInConditionalStatement = true; 23082 verifyFormat("for ( int i = 0; i; i++ )\n continue;", Spaces); 23083 verifyFormat("if ( !a )\n return;", Spaces); 23084 verifyFormat("if ( a )\n return;", Spaces); 23085 verifyFormat("if constexpr ( a )\n return;", Spaces); 23086 verifyFormat("MYIF ( a )\n return;", Spaces); 23087 verifyFormat("MYIF ( a )\n return;\nelse MYIF ( b )\n return;", Spaces); 23088 verifyFormat("MYIF ( a )\n return;\nelse\n return;", Spaces); 23089 verifyFormat("switch ( a )\ncase 1:\n return;", Spaces); 23090 verifyFormat("while ( a )\n return;", Spaces); 23091 verifyFormat("while ( (a && b) )\n return;", Spaces); 23092 verifyFormat("do {\n} while ( 1 != 0 );", Spaces); 23093 verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces); 23094 // Check that space on the left of "::" is inserted as expected at beginning 23095 // of condition. 23096 verifyFormat("while ( ::func() )\n return;", Spaces); 23097 23098 // Check impact of ControlStatementsExceptControlMacros is honored. 23099 Spaces.SpaceBeforeParens = 23100 FormatStyle::SBPO_ControlStatementsExceptControlMacros; 23101 verifyFormat("MYIF( a )\n return;", Spaces); 23102 verifyFormat("MYIF( a )\n return;\nelse MYIF( b )\n return;", Spaces); 23103 verifyFormat("MYIF( a )\n return;\nelse\n return;", Spaces); 23104 } 23105 23106 TEST_F(FormatTest, AlternativeOperators) { 23107 // Test case for ensuring alternate operators are not 23108 // combined with their right most neighbour. 23109 verifyFormat("int a and b;"); 23110 verifyFormat("int a and_eq b;"); 23111 verifyFormat("int a bitand b;"); 23112 verifyFormat("int a bitor b;"); 23113 verifyFormat("int a compl b;"); 23114 verifyFormat("int a not b;"); 23115 verifyFormat("int a not_eq b;"); 23116 verifyFormat("int a or b;"); 23117 verifyFormat("int a xor b;"); 23118 verifyFormat("int a xor_eq b;"); 23119 verifyFormat("return this not_eq bitand other;"); 23120 verifyFormat("bool operator not_eq(const X bitand other)"); 23121 23122 verifyFormat("int a and 5;"); 23123 verifyFormat("int a and_eq 5;"); 23124 verifyFormat("int a bitand 5;"); 23125 verifyFormat("int a bitor 5;"); 23126 verifyFormat("int a compl 5;"); 23127 verifyFormat("int a not 5;"); 23128 verifyFormat("int a not_eq 5;"); 23129 verifyFormat("int a or 5;"); 23130 verifyFormat("int a xor 5;"); 23131 verifyFormat("int a xor_eq 5;"); 23132 23133 verifyFormat("int a compl(5);"); 23134 verifyFormat("int a not(5);"); 23135 23136 /* FIXME handle alternate tokens 23137 * https://en.cppreference.com/w/cpp/language/operator_alternative 23138 // alternative tokens 23139 verifyFormat("compl foo();"); // ~foo(); 23140 verifyFormat("foo() <%%>;"); // foo(); 23141 verifyFormat("void foo() <%%>;"); // void foo(){} 23142 verifyFormat("int a <:1:>;"); // int a[1];[ 23143 verifyFormat("%:define ABC abc"); // #define ABC abc 23144 verifyFormat("%:%:"); // ## 23145 */ 23146 } 23147 23148 TEST_F(FormatTest, STLWhileNotDefineChed) { 23149 verifyFormat("#if defined(while)\n" 23150 "#define while EMIT WARNING C4005\n" 23151 "#endif // while"); 23152 } 23153 23154 TEST_F(FormatTest, OperatorSpacing) { 23155 FormatStyle Style = getLLVMStyle(); 23156 Style.PointerAlignment = FormatStyle::PAS_Right; 23157 verifyFormat("Foo::operator*();", Style); 23158 verifyFormat("Foo::operator void *();", Style); 23159 verifyFormat("Foo::operator void **();", Style); 23160 verifyFormat("Foo::operator void *&();", Style); 23161 verifyFormat("Foo::operator void *&&();", Style); 23162 verifyFormat("Foo::operator void const *();", Style); 23163 verifyFormat("Foo::operator void const **();", Style); 23164 verifyFormat("Foo::operator void const *&();", Style); 23165 verifyFormat("Foo::operator void const *&&();", Style); 23166 verifyFormat("Foo::operator()(void *);", Style); 23167 verifyFormat("Foo::operator*(void *);", Style); 23168 verifyFormat("Foo::operator*();", Style); 23169 verifyFormat("Foo::operator**();", Style); 23170 verifyFormat("Foo::operator&();", Style); 23171 verifyFormat("Foo::operator<int> *();", Style); 23172 verifyFormat("Foo::operator<Foo> *();", Style); 23173 verifyFormat("Foo::operator<int> **();", Style); 23174 verifyFormat("Foo::operator<Foo> **();", Style); 23175 verifyFormat("Foo::operator<int> &();", Style); 23176 verifyFormat("Foo::operator<Foo> &();", Style); 23177 verifyFormat("Foo::operator<int> &&();", Style); 23178 verifyFormat("Foo::operator<Foo> &&();", Style); 23179 verifyFormat("Foo::operator<int> *&();", Style); 23180 verifyFormat("Foo::operator<Foo> *&();", Style); 23181 verifyFormat("Foo::operator<int> *&&();", Style); 23182 verifyFormat("Foo::operator<Foo> *&&();", Style); 23183 verifyFormat("operator*(int (*)(), class Foo);", Style); 23184 23185 verifyFormat("Foo::operator&();", Style); 23186 verifyFormat("Foo::operator void &();", Style); 23187 verifyFormat("Foo::operator void const &();", Style); 23188 verifyFormat("Foo::operator()(void &);", Style); 23189 verifyFormat("Foo::operator&(void &);", Style); 23190 verifyFormat("Foo::operator&();", Style); 23191 verifyFormat("operator&(int (&)(), class Foo);", Style); 23192 verifyFormat("operator&&(int (&)(), class Foo);", Style); 23193 23194 verifyFormat("Foo::operator&&();", Style); 23195 verifyFormat("Foo::operator**();", Style); 23196 verifyFormat("Foo::operator void &&();", Style); 23197 verifyFormat("Foo::operator void const &&();", Style); 23198 verifyFormat("Foo::operator()(void &&);", Style); 23199 verifyFormat("Foo::operator&&(void &&);", Style); 23200 verifyFormat("Foo::operator&&();", Style); 23201 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23202 verifyFormat("operator const nsTArrayRight<E> &()", Style); 23203 verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()", 23204 Style); 23205 verifyFormat("operator void **()", Style); 23206 verifyFormat("operator const FooRight<Object> &()", Style); 23207 verifyFormat("operator const FooRight<Object> *()", Style); 23208 verifyFormat("operator const FooRight<Object> **()", Style); 23209 verifyFormat("operator const FooRight<Object> *&()", Style); 23210 verifyFormat("operator const FooRight<Object> *&&()", Style); 23211 23212 Style.PointerAlignment = FormatStyle::PAS_Left; 23213 verifyFormat("Foo::operator*();", Style); 23214 verifyFormat("Foo::operator**();", Style); 23215 verifyFormat("Foo::operator void*();", Style); 23216 verifyFormat("Foo::operator void**();", Style); 23217 verifyFormat("Foo::operator void*&();", Style); 23218 verifyFormat("Foo::operator void*&&();", Style); 23219 verifyFormat("Foo::operator void const*();", Style); 23220 verifyFormat("Foo::operator void const**();", Style); 23221 verifyFormat("Foo::operator void const*&();", Style); 23222 verifyFormat("Foo::operator void const*&&();", Style); 23223 verifyFormat("Foo::operator/*comment*/ void*();", Style); 23224 verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style); 23225 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style); 23226 verifyFormat("Foo::operator()(void*);", Style); 23227 verifyFormat("Foo::operator*(void*);", Style); 23228 verifyFormat("Foo::operator*();", 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("Foo::operator<Foo>*&();", Style); 23234 verifyFormat("Foo::operator<int>&();", Style); 23235 verifyFormat("Foo::operator<Foo>&();", Style); 23236 verifyFormat("Foo::operator<int>&&();", Style); 23237 verifyFormat("Foo::operator<Foo>&&();", Style); 23238 verifyFormat("Foo::operator<int>*&();", Style); 23239 verifyFormat("Foo::operator<Foo>*&();", Style); 23240 verifyFormat("operator*(int (*)(), class Foo);", Style); 23241 23242 verifyFormat("Foo::operator&();", Style); 23243 verifyFormat("Foo::operator void&();", Style); 23244 verifyFormat("Foo::operator void const&();", Style); 23245 verifyFormat("Foo::operator/*comment*/ void&();", Style); 23246 verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style); 23247 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style); 23248 verifyFormat("Foo::operator()(void&);", Style); 23249 verifyFormat("Foo::operator&(void&);", Style); 23250 verifyFormat("Foo::operator&();", Style); 23251 verifyFormat("operator&(int (&)(), class Foo);", Style); 23252 verifyFormat("operator&(int (&&)(), class Foo);", Style); 23253 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23254 23255 verifyFormat("Foo::operator&&();", Style); 23256 verifyFormat("Foo::operator void&&();", Style); 23257 verifyFormat("Foo::operator void const&&();", Style); 23258 verifyFormat("Foo::operator/*comment*/ void&&();", Style); 23259 verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style); 23260 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style); 23261 verifyFormat("Foo::operator()(void&&);", Style); 23262 verifyFormat("Foo::operator&&(void&&);", Style); 23263 verifyFormat("Foo::operator&&();", Style); 23264 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23265 verifyFormat("operator const nsTArrayLeft<E>&()", Style); 23266 verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()", 23267 Style); 23268 verifyFormat("operator void**()", Style); 23269 verifyFormat("operator const FooLeft<Object>&()", Style); 23270 verifyFormat("operator const FooLeft<Object>*()", Style); 23271 verifyFormat("operator const FooLeft<Object>**()", Style); 23272 verifyFormat("operator const FooLeft<Object>*&()", Style); 23273 verifyFormat("operator const FooLeft<Object>*&&()", Style); 23274 23275 // PR45107 23276 verifyFormat("operator Vector<String>&();", Style); 23277 verifyFormat("operator const Vector<String>&();", Style); 23278 verifyFormat("operator foo::Bar*();", Style); 23279 verifyFormat("operator const Foo<X>::Bar<Y>*();", Style); 23280 verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();", 23281 Style); 23282 23283 Style.PointerAlignment = FormatStyle::PAS_Middle; 23284 verifyFormat("Foo::operator*();", Style); 23285 verifyFormat("Foo::operator void *();", Style); 23286 verifyFormat("Foo::operator()(void *);", Style); 23287 verifyFormat("Foo::operator*(void *);", Style); 23288 verifyFormat("Foo::operator*();", Style); 23289 verifyFormat("operator*(int (*)(), class Foo);", Style); 23290 23291 verifyFormat("Foo::operator&();", Style); 23292 verifyFormat("Foo::operator void &();", Style); 23293 verifyFormat("Foo::operator void const &();", Style); 23294 verifyFormat("Foo::operator()(void &);", Style); 23295 verifyFormat("Foo::operator&(void &);", Style); 23296 verifyFormat("Foo::operator&();", Style); 23297 verifyFormat("operator&(int (&)(), class Foo);", Style); 23298 23299 verifyFormat("Foo::operator&&();", Style); 23300 verifyFormat("Foo::operator void &&();", Style); 23301 verifyFormat("Foo::operator void const &&();", Style); 23302 verifyFormat("Foo::operator()(void &&);", Style); 23303 verifyFormat("Foo::operator&&(void &&);", Style); 23304 verifyFormat("Foo::operator&&();", Style); 23305 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23306 } 23307 23308 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) { 23309 FormatStyle Style = getLLVMStyle(); 23310 // PR46157 23311 verifyFormat("foo(operator+, -42);", Style); 23312 verifyFormat("foo(operator++, -42);", Style); 23313 verifyFormat("foo(operator--, -42);", Style); 23314 verifyFormat("foo(-42, operator--);", Style); 23315 verifyFormat("foo(-42, operator, );", Style); 23316 verifyFormat("foo(operator, , -42);", Style); 23317 } 23318 23319 TEST_F(FormatTest, WhitespaceSensitiveMacros) { 23320 FormatStyle Style = getLLVMStyle(); 23321 Style.WhitespaceSensitiveMacros.push_back("FOO"); 23322 23323 // Don't use the helpers here, since 'mess up' will change the whitespace 23324 // and these are all whitespace sensitive by definition 23325 EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);", 23326 format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style)); 23327 EXPECT_EQ( 23328 "FOO(String-ized&Messy+But\\(: :Still)=Intentional);", 23329 format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style)); 23330 EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);", 23331 format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style)); 23332 EXPECT_EQ("FOO(String-ized&Messy+But,: :\n" 23333 " Still=Intentional);", 23334 format("FOO(String-ized&Messy+But,: :\n" 23335 " Still=Intentional);", 23336 Style)); 23337 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 23338 EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n" 23339 " Still=Intentional);", 23340 format("FOO(String-ized=&Messy+But,: :\n" 23341 " Still=Intentional);", 23342 Style)); 23343 23344 Style.ColumnLimit = 21; 23345 EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);", 23346 format("FOO(String-ized&Messy+But: :Still=Intentional);", Style)); 23347 } 23348 23349 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) { 23350 // These tests are not in NamespaceEndCommentsFixerTest because that doesn't 23351 // test its interaction with line wrapping 23352 FormatStyle Style = getLLVMStyleWithColumns(80); 23353 verifyFormat("namespace {\n" 23354 "int i;\n" 23355 "int j;\n" 23356 "} // namespace", 23357 Style); 23358 23359 verifyFormat("namespace AAA {\n" 23360 "int i;\n" 23361 "int j;\n" 23362 "} // namespace AAA", 23363 Style); 23364 23365 EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n" 23366 "int i;\n" 23367 "int j;\n" 23368 "} // namespace Averyveryveryverylongnamespace", 23369 format("namespace Averyveryveryverylongnamespace {\n" 23370 "int i;\n" 23371 "int j;\n" 23372 "}", 23373 Style)); 23374 23375 EXPECT_EQ( 23376 "namespace " 23377 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n" 23378 " went::mad::now {\n" 23379 "int i;\n" 23380 "int j;\n" 23381 "} // namespace\n" 23382 " // " 23383 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::" 23384 "went::mad::now", 23385 format("namespace " 23386 "would::it::save::you::a::lot::of::time::if_::i::" 23387 "just::gave::up::and_::went::mad::now {\n" 23388 "int i;\n" 23389 "int j;\n" 23390 "}", 23391 Style)); 23392 23393 // This used to duplicate the comment again and again on subsequent runs 23394 EXPECT_EQ( 23395 "namespace " 23396 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n" 23397 " went::mad::now {\n" 23398 "int i;\n" 23399 "int j;\n" 23400 "} // namespace\n" 23401 " // " 23402 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::" 23403 "went::mad::now", 23404 format("namespace " 23405 "would::it::save::you::a::lot::of::time::if_::i::" 23406 "just::gave::up::and_::went::mad::now {\n" 23407 "int i;\n" 23408 "int j;\n" 23409 "} // namespace\n" 23410 " // " 23411 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::" 23412 "and_::went::mad::now", 23413 Style)); 23414 } 23415 23416 TEST_F(FormatTest, LikelyUnlikely) { 23417 FormatStyle Style = getLLVMStyle(); 23418 23419 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23420 " return 29;\n" 23421 "}", 23422 Style); 23423 23424 verifyFormat("if (argc > 5) [[likely]] {\n" 23425 " return 29;\n" 23426 "}", 23427 Style); 23428 23429 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23430 " return 29;\n" 23431 "} else [[likely]] {\n" 23432 " return 42;\n" 23433 "}\n", 23434 Style); 23435 23436 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23437 " return 29;\n" 23438 "} else if (argc > 10) [[likely]] {\n" 23439 " return 99;\n" 23440 "} else {\n" 23441 " return 42;\n" 23442 "}\n", 23443 Style); 23444 23445 verifyFormat("if (argc > 5) [[gnu::unused]] {\n" 23446 " return 29;\n" 23447 "}", 23448 Style); 23449 23450 verifyFormat("if (argc > 5) [[unlikely]]\n" 23451 " return 29;\n", 23452 Style); 23453 verifyFormat("if (argc > 5) [[likely]]\n" 23454 " return 29;\n", 23455 Style); 23456 23457 Style.AttributeMacros.push_back("UNLIKELY"); 23458 Style.AttributeMacros.push_back("LIKELY"); 23459 verifyFormat("if (argc > 5) UNLIKELY\n" 23460 " return 29;\n", 23461 Style); 23462 23463 verifyFormat("if (argc > 5) UNLIKELY {\n" 23464 " return 29;\n" 23465 "}", 23466 Style); 23467 verifyFormat("if (argc > 5) UNLIKELY {\n" 23468 " return 29;\n" 23469 "} else [[likely]] {\n" 23470 " return 42;\n" 23471 "}\n", 23472 Style); 23473 verifyFormat("if (argc > 5) UNLIKELY {\n" 23474 " return 29;\n" 23475 "} else LIKELY {\n" 23476 " return 42;\n" 23477 "}\n", 23478 Style); 23479 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23480 " return 29;\n" 23481 "} else LIKELY {\n" 23482 " return 42;\n" 23483 "}\n", 23484 Style); 23485 } 23486 23487 TEST_F(FormatTest, PenaltyIndentedWhitespace) { 23488 verifyFormat("Constructor()\n" 23489 " : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 23490 " aaaa(aaaaaaaaaaaaaaaaaa, " 23491 "aaaaaaaaaaaaaaaaaat))"); 23492 verifyFormat("Constructor()\n" 23493 " : aaaaaaaaaaaaa(aaaaaa), " 23494 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)"); 23495 23496 FormatStyle StyleWithWhitespacePenalty = getLLVMStyle(); 23497 StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5; 23498 verifyFormat("Constructor()\n" 23499 " : aaaaaa(aaaaaa),\n" 23500 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 23501 " aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))", 23502 StyleWithWhitespacePenalty); 23503 verifyFormat("Constructor()\n" 23504 " : aaaaaaaaaaaaa(aaaaaa), " 23505 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)", 23506 StyleWithWhitespacePenalty); 23507 } 23508 23509 TEST_F(FormatTest, LLVMDefaultStyle) { 23510 FormatStyle Style = getLLVMStyle(); 23511 verifyFormat("extern \"C\" {\n" 23512 "int foo();\n" 23513 "}", 23514 Style); 23515 } 23516 TEST_F(FormatTest, GNUDefaultStyle) { 23517 FormatStyle Style = getGNUStyle(); 23518 verifyFormat("extern \"C\"\n" 23519 "{\n" 23520 " int foo ();\n" 23521 "}", 23522 Style); 23523 } 23524 TEST_F(FormatTest, MozillaDefaultStyle) { 23525 FormatStyle Style = getMozillaStyle(); 23526 verifyFormat("extern \"C\"\n" 23527 "{\n" 23528 " int foo();\n" 23529 "}", 23530 Style); 23531 } 23532 TEST_F(FormatTest, GoogleDefaultStyle) { 23533 FormatStyle Style = getGoogleStyle(); 23534 verifyFormat("extern \"C\" {\n" 23535 "int foo();\n" 23536 "}", 23537 Style); 23538 } 23539 TEST_F(FormatTest, ChromiumDefaultStyle) { 23540 FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp); 23541 verifyFormat("extern \"C\" {\n" 23542 "int foo();\n" 23543 "}", 23544 Style); 23545 } 23546 TEST_F(FormatTest, MicrosoftDefaultStyle) { 23547 FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp); 23548 verifyFormat("extern \"C\"\n" 23549 "{\n" 23550 " int foo();\n" 23551 "}", 23552 Style); 23553 } 23554 TEST_F(FormatTest, WebKitDefaultStyle) { 23555 FormatStyle Style = getWebKitStyle(); 23556 verifyFormat("extern \"C\" {\n" 23557 "int foo();\n" 23558 "}", 23559 Style); 23560 } 23561 23562 TEST_F(FormatTest, Concepts) { 23563 EXPECT_EQ(getLLVMStyle().BreakBeforeConceptDeclarations, 23564 FormatStyle::BBCDS_Always); 23565 verifyFormat("template <typename T>\n" 23566 "concept True = true;"); 23567 23568 verifyFormat("template <typename T>\n" 23569 "concept C = ((false || foo()) && C2<T>) ||\n" 23570 " (std::trait<T>::value && Baz) || sizeof(T) >= 6;", 23571 getLLVMStyleWithColumns(60)); 23572 23573 verifyFormat("template <typename T>\n" 23574 "concept DelayedCheck = true && requires(T t) { t.bar(); } && " 23575 "sizeof(T) <= 8;"); 23576 23577 verifyFormat("template <typename T>\n" 23578 "concept DelayedCheck = true && requires(T t) {\n" 23579 " t.bar();\n" 23580 " t.baz();\n" 23581 " } && sizeof(T) <= 8;"); 23582 23583 verifyFormat("template <typename T>\n" 23584 "concept DelayedCheck = true && requires(T t) { // Comment\n" 23585 " t.bar();\n" 23586 " t.baz();\n" 23587 " } && sizeof(T) <= 8;"); 23588 23589 verifyFormat("template <typename T>\n" 23590 "concept DelayedCheck = false || requires(T t) { t.bar(); } && " 23591 "sizeof(T) <= 8;"); 23592 23593 verifyFormat("template <typename T>\n" 23594 "concept DelayedCheck = !!false || requires(T t) { t.bar(); } " 23595 "&& sizeof(T) <= 8;"); 23596 23597 verifyFormat( 23598 "template <typename T>\n" 23599 "concept DelayedCheck = static_cast<bool>(0) ||\n" 23600 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 23601 23602 verifyFormat("template <typename T>\n" 23603 "concept DelayedCheck = bool(0) || requires(T t) { t.bar(); } " 23604 "&& sizeof(T) <= 8;"); 23605 23606 verifyFormat( 23607 "template <typename T>\n" 23608 "concept DelayedCheck = (bool)(0) ||\n" 23609 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 23610 23611 verifyFormat("template <typename T>\n" 23612 "concept DelayedCheck = (bool)0 || requires(T t) { t.bar(); } " 23613 "&& sizeof(T) <= 8;"); 23614 23615 verifyFormat("template <typename T>\n" 23616 "concept Size = sizeof(T) >= 5 && requires(T t) { t.bar(); } && " 23617 "sizeof(T) <= 8;"); 23618 23619 verifyFormat("template <typename T>\n" 23620 "concept Size = 2 < 5 && 2 <= 5 && 8 >= 5 && 8 > 5 &&\n" 23621 " requires(T t) {\n" 23622 " t.bar();\n" 23623 " t.baz();\n" 23624 " } && sizeof(T) <= 8 && !(4 < 3);", 23625 getLLVMStyleWithColumns(60)); 23626 23627 verifyFormat("template <typename T>\n" 23628 "concept TrueOrNot = IsAlwaysTrue || IsNeverTrue;"); 23629 23630 verifyFormat("template <typename T>\n" 23631 "concept C = foo();"); 23632 23633 verifyFormat("template <typename T>\n" 23634 "concept C = foo(T());"); 23635 23636 verifyFormat("template <typename T>\n" 23637 "concept C = foo(T{});"); 23638 23639 verifyFormat("template <typename T>\n" 23640 "concept Size = V<sizeof(T)>::Value > 5;"); 23641 23642 verifyFormat("template <typename T>\n" 23643 "concept True = S<T>::Value;"); 23644 23645 verifyFormat( 23646 "template <typename T>\n" 23647 "concept C = []() { return true; }() && requires(T t) { t.bar(); } &&\n" 23648 " sizeof(T) <= 8;"); 23649 23650 // FIXME: This is misformatted because the fake l paren starts at bool, not at 23651 // the lambda l square. 23652 verifyFormat("template <typename T>\n" 23653 "concept C = [] -> bool { return true; }() && requires(T t) { " 23654 "t.bar(); } &&\n" 23655 " sizeof(T) <= 8;"); 23656 23657 verifyFormat( 23658 "template <typename T>\n" 23659 "concept C = decltype([]() { return std::true_type{}; }())::value &&\n" 23660 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 23661 23662 verifyFormat("template <typename T>\n" 23663 "concept C = decltype([]() { return std::true_type{}; " 23664 "}())::value && requires(T t) { t.bar(); } && sizeof(T) <= 8;", 23665 getLLVMStyleWithColumns(120)); 23666 23667 verifyFormat("template <typename T>\n" 23668 "concept C = decltype([]() -> std::true_type { return {}; " 23669 "}())::value &&\n" 23670 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 23671 23672 verifyFormat("template <typename T>\n" 23673 "concept C = true;\n" 23674 "Foo Bar;"); 23675 23676 verifyFormat("template <typename T>\n" 23677 "concept Hashable = requires(T a) {\n" 23678 " { std::hash<T>{}(a) } -> " 23679 "std::convertible_to<std::size_t>;\n" 23680 " };"); 23681 23682 verifyFormat( 23683 "template <typename T>\n" 23684 "concept EqualityComparable = requires(T a, T b) {\n" 23685 " { a == b } -> std::same_as<bool>;\n" 23686 " };"); 23687 23688 verifyFormat( 23689 "template <typename T>\n" 23690 "concept EqualityComparable = requires(T a, T b) {\n" 23691 " { a == b } -> std::same_as<bool>;\n" 23692 " { a != b } -> std::same_as<bool>;\n" 23693 " };"); 23694 23695 verifyFormat("template <typename T>\n" 23696 "concept WeakEqualityComparable = requires(T a, T b) {\n" 23697 " { a == b };\n" 23698 " { a != b };\n" 23699 " };"); 23700 23701 verifyFormat("template <typename T>\n" 23702 "concept HasSizeT = requires { typename T::size_t; };"); 23703 23704 verifyFormat("template <typename T>\n" 23705 "concept Semiregular =\n" 23706 " DefaultConstructible<T> && CopyConstructible<T> && " 23707 "CopyAssignable<T> &&\n" 23708 " requires(T a, std::size_t n) {\n" 23709 " requires Same<T *, decltype(&a)>;\n" 23710 " { a.~T() } noexcept;\n" 23711 " requires Same<T *, decltype(new T)>;\n" 23712 " requires Same<T *, decltype(new T[n])>;\n" 23713 " { delete new T; };\n" 23714 " { delete new T[n]; };\n" 23715 " };"); 23716 23717 verifyFormat("template <typename T>\n" 23718 "concept Semiregular =\n" 23719 " requires(T a, std::size_t n) {\n" 23720 " requires Same<T *, decltype(&a)>;\n" 23721 " { a.~T() } noexcept;\n" 23722 " requires Same<T *, decltype(new T)>;\n" 23723 " requires Same<T *, decltype(new T[n])>;\n" 23724 " { delete new T; };\n" 23725 " { delete new T[n]; };\n" 23726 " { new T } -> std::same_as<T *>;\n" 23727 " } && DefaultConstructible<T> && CopyConstructible<T> && " 23728 "CopyAssignable<T>;"); 23729 23730 verifyFormat( 23731 "template <typename T>\n" 23732 "concept Semiregular =\n" 23733 " DefaultConstructible<T> && requires(T a, std::size_t n) {\n" 23734 " requires Same<T *, decltype(&a)>;\n" 23735 " { a.~T() } noexcept;\n" 23736 " requires Same<T *, decltype(new T)>;\n" 23737 " requires Same<T *, decltype(new " 23738 "T[n])>;\n" 23739 " { delete new T; };\n" 23740 " { delete new T[n]; };\n" 23741 " } && CopyConstructible<T> && " 23742 "CopyAssignable<T>;"); 23743 23744 verifyFormat("template <typename T>\n" 23745 "concept Two = requires(T t) {\n" 23746 " { t.foo() } -> std::same_as<Bar>;\n" 23747 " } && requires(T &&t) {\n" 23748 " { t.foo() } -> std::same_as<Bar &&>;\n" 23749 " };"); 23750 23751 verifyFormat( 23752 "template <typename T>\n" 23753 "concept C = requires(T x) {\n" 23754 " { *x } -> std::convertible_to<typename T::inner>;\n" 23755 " { x + 1 } noexcept -> std::same_as<int>;\n" 23756 " { x * 1 } -> std::convertible_to<T>;\n" 23757 " };"); 23758 23759 verifyFormat( 23760 "template <typename T, typename U = T>\n" 23761 "concept Swappable = requires(T &&t, U &&u) {\n" 23762 " swap(std::forward<T>(t), std::forward<U>(u));\n" 23763 " swap(std::forward<U>(u), std::forward<T>(t));\n" 23764 " };"); 23765 23766 verifyFormat("template <typename T, typename U>\n" 23767 "concept Common = requires(T &&t, U &&u) {\n" 23768 " typename CommonType<T, U>;\n" 23769 " { CommonType<T, U>(std::forward<T>(t)) };\n" 23770 " };"); 23771 23772 verifyFormat("template <typename T, typename U>\n" 23773 "concept Common = requires(T &&t, U &&u) {\n" 23774 " typename CommonType<T, U>;\n" 23775 " { CommonType<T, U>{std::forward<T>(t)} };\n" 23776 " };"); 23777 23778 verifyFormat( 23779 "template <typename T>\n" 23780 "concept C = requires(T t) {\n" 23781 " requires Bar<T> && Foo<T>;\n" 23782 " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n" 23783 " };"); 23784 23785 verifyFormat("template <typename T>\n" 23786 "concept HasFoo = requires(T t) {\n" 23787 " { t.foo() };\n" 23788 " t.foo();\n" 23789 " };\n" 23790 "template <typename T>\n" 23791 "concept HasBar = requires(T t) {\n" 23792 " { t.bar() };\n" 23793 " t.bar();\n" 23794 " };"); 23795 23796 verifyFormat("template <typename T>\n" 23797 "concept Large = sizeof(T) > 10;"); 23798 23799 verifyFormat("template <typename T, typename U>\n" 23800 "concept FooableWith = requires(T t, U u) {\n" 23801 " typename T::foo_type;\n" 23802 " { t.foo(u) } -> typename T::foo_type;\n" 23803 " t++;\n" 23804 " };\n" 23805 "void doFoo(FooableWith<int> auto t) { t.foo(3); }"); 23806 23807 verifyFormat("template <typename T>\n" 23808 "concept Context = is_specialization_of_v<context, T>;"); 23809 23810 verifyFormat("template <typename T>\n" 23811 "concept Node = std::is_object_v<T>;"); 23812 23813 auto Style = getLLVMStyle(); 23814 Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Allowed; 23815 23816 verifyFormat( 23817 "template <typename T>\n" 23818 "concept C = requires(T t) {\n" 23819 " requires Bar<T> && Foo<T>;\n" 23820 " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n" 23821 " };", 23822 Style); 23823 23824 verifyFormat("template <typename T>\n" 23825 "concept HasFoo = requires(T t) {\n" 23826 " { t.foo() };\n" 23827 " t.foo();\n" 23828 " };\n" 23829 "template <typename T>\n" 23830 "concept HasBar = requires(T t) {\n" 23831 " { t.bar() };\n" 23832 " t.bar();\n" 23833 " };", 23834 Style); 23835 23836 verifyFormat("template <typename T> concept True = true;", Style); 23837 23838 verifyFormat("template <typename T>\n" 23839 "concept C = decltype([]() -> std::true_type { return {}; " 23840 "}())::value &&\n" 23841 " requires(T t) { t.bar(); } && sizeof(T) <= 8;", 23842 Style); 23843 23844 verifyFormat("template <typename T>\n" 23845 "concept Semiregular =\n" 23846 " DefaultConstructible<T> && CopyConstructible<T> && " 23847 "CopyAssignable<T> &&\n" 23848 " requires(T a, std::size_t n) {\n" 23849 " requires Same<T *, decltype(&a)>;\n" 23850 " { a.~T() } noexcept;\n" 23851 " requires Same<T *, decltype(new T)>;\n" 23852 " requires Same<T *, decltype(new T[n])>;\n" 23853 " { delete new T; };\n" 23854 " { delete new T[n]; };\n" 23855 " };", 23856 Style); 23857 23858 Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Never; 23859 23860 verifyFormat("template <typename T> concept C =\n" 23861 " requires(T t) {\n" 23862 " requires Bar<T> && Foo<T>;\n" 23863 " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n" 23864 " };", 23865 Style); 23866 23867 verifyFormat("template <typename T> concept HasFoo = requires(T t) {\n" 23868 " { t.foo() };\n" 23869 " t.foo();\n" 23870 " };\n" 23871 "template <typename T> concept HasBar = requires(T t) {\n" 23872 " { t.bar() };\n" 23873 " t.bar();\n" 23874 " };", 23875 Style); 23876 23877 verifyFormat("template <typename T> concept True = true;", Style); 23878 23879 verifyFormat( 23880 "template <typename T> concept C = decltype([]() -> std::true_type {\n" 23881 " return {};\n" 23882 " }())::value\n" 23883 " && requires(T t) { t.bar(); } &&\n" 23884 " sizeof(T) <= 8;", 23885 Style); 23886 23887 verifyFormat("template <typename T> concept Semiregular =\n" 23888 " DefaultConstructible<T> && CopyConstructible<T> && " 23889 "CopyAssignable<T> &&\n" 23890 " requires(T a, std::size_t n) {\n" 23891 " requires Same<T *, decltype(&a)>;\n" 23892 " { a.~T() } noexcept;\n" 23893 " requires Same<T *, decltype(new T)>;\n" 23894 " requires Same<T *, decltype(new T[n])>;\n" 23895 " { delete new T; };\n" 23896 " { delete new T[n]; };\n" 23897 " };", 23898 Style); 23899 23900 // The following tests are invalid C++, we just want to make sure we don't 23901 // assert. 23902 verifyFormat("template <typename T>\n" 23903 "concept C = requires C2<T>;"); 23904 23905 verifyFormat("template <typename T>\n" 23906 "concept C = 5 + 4;"); 23907 23908 verifyFormat("template <typename T>\n" 23909 "concept C =\n" 23910 "class X;"); 23911 23912 verifyFormat("template <typename T>\n" 23913 "concept C = [] && true;"); 23914 23915 verifyFormat("template <typename T>\n" 23916 "concept C = [] && requires(T t) { typename T::size_type; };"); 23917 } 23918 23919 TEST_F(FormatTest, RequiresClausesPositions) { 23920 auto Style = getLLVMStyle(); 23921 EXPECT_EQ(Style.RequiresClausePosition, FormatStyle::RCPS_OwnLine); 23922 EXPECT_EQ(Style.IndentRequiresClause, true); 23923 23924 verifyFormat("template <typename T>\n" 23925 " requires(Foo<T> && std::trait<T>)\n" 23926 "struct Bar;", 23927 Style); 23928 23929 verifyFormat("template <typename T>\n" 23930 " requires(Foo<T> && std::trait<T>)\n" 23931 "class Bar {\n" 23932 "public:\n" 23933 " Bar(T t);\n" 23934 " bool baz();\n" 23935 "};", 23936 Style); 23937 23938 verifyFormat( 23939 "template <typename T>\n" 23940 " requires requires(T &&t) {\n" 23941 " typename T::I;\n" 23942 " requires(F<typename T::I> && std::trait<typename T::I>);\n" 23943 " }\n" 23944 "Bar(T) -> Bar<typename T::I>;", 23945 Style); 23946 23947 verifyFormat("template <typename T>\n" 23948 " requires(Foo<T> && std::trait<T>)\n" 23949 "constexpr T MyGlobal;", 23950 Style); 23951 23952 verifyFormat("template <typename T>\n" 23953 " requires Foo<T> && requires(T t) {\n" 23954 " { t.baz() } -> std::same_as<bool>;\n" 23955 " requires std::same_as<T::Factor, int>;\n" 23956 " }\n" 23957 "inline int bar(T t) {\n" 23958 " return t.baz() ? T::Factor : 5;\n" 23959 "}", 23960 Style); 23961 23962 verifyFormat("template <typename T>\n" 23963 "inline int bar(T t)\n" 23964 " requires Foo<T> && requires(T t) {\n" 23965 " { t.baz() } -> std::same_as<bool>;\n" 23966 " requires std::same_as<T::Factor, int>;\n" 23967 " }\n" 23968 "{\n" 23969 " return t.baz() ? T::Factor : 5;\n" 23970 "}", 23971 Style); 23972 23973 verifyFormat("template <typename T>\n" 23974 " requires F<T>\n" 23975 "int bar(T t) {\n" 23976 " return 5;\n" 23977 "}", 23978 Style); 23979 23980 verifyFormat("template <typename T>\n" 23981 "int bar(T t)\n" 23982 " requires F<T>\n" 23983 "{\n" 23984 " return 5;\n" 23985 "}", 23986 Style); 23987 23988 verifyFormat("template <typename T>\n" 23989 "int bar(T t)\n" 23990 " requires F<T>;", 23991 Style); 23992 23993 Style.IndentRequiresClause = false; 23994 verifyFormat("template <typename T>\n" 23995 "requires F<T>\n" 23996 "int bar(T t) {\n" 23997 " return 5;\n" 23998 "}", 23999 Style); 24000 24001 verifyFormat("template <typename T>\n" 24002 "int bar(T t)\n" 24003 "requires F<T>\n" 24004 "{\n" 24005 " return 5;\n" 24006 "}", 24007 Style); 24008 24009 Style.RequiresClausePosition = FormatStyle::RCPS_SingleLine; 24010 verifyFormat("template <typename T> requires Foo<T> struct Bar {};\n" 24011 "template <typename T> requires Foo<T> void bar() {}\n" 24012 "template <typename T> void bar() requires Foo<T> {}\n" 24013 "template <typename T> void bar() requires Foo<T>;\n" 24014 "template <typename T> requires Foo<T> Bar(T) -> Bar<T>;", 24015 Style); 24016 24017 auto ColumnStyle = Style; 24018 ColumnStyle.ColumnLimit = 40; 24019 verifyFormat("template <typename AAAAAAA>\n" 24020 "requires Foo<T> struct Bar {};\n" 24021 "template <typename AAAAAAA>\n" 24022 "requires Foo<T> void bar() {}\n" 24023 "template <typename AAAAAAA>\n" 24024 "void bar() requires Foo<T> {}\n" 24025 "template <typename AAAAAAA>\n" 24026 "requires Foo<T> Baz(T) -> Baz<T>;", 24027 ColumnStyle); 24028 24029 verifyFormat("template <typename T>\n" 24030 "requires Foo<AAAAAAA> struct Bar {};\n" 24031 "template <typename T>\n" 24032 "requires Foo<AAAAAAA> void bar() {}\n" 24033 "template <typename T>\n" 24034 "void bar() requires Foo<AAAAAAA> {}\n" 24035 "template <typename T>\n" 24036 "requires Foo<AAAAAAA> Bar(T) -> Bar<T>;", 24037 ColumnStyle); 24038 24039 verifyFormat("template <typename AAAAAAA>\n" 24040 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24041 "struct Bar {};\n" 24042 "template <typename AAAAAAA>\n" 24043 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24044 "void bar() {}\n" 24045 "template <typename AAAAAAA>\n" 24046 "void bar()\n" 24047 " requires Foo<AAAAAAAAAAAAAAAA> {}\n" 24048 "template <typename AAAAAAA>\n" 24049 "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n" 24050 "template <typename AAAAAAA>\n" 24051 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24052 "Bar(T) -> Bar<T>;", 24053 ColumnStyle); 24054 24055 Style.RequiresClausePosition = FormatStyle::RCPS_WithFollowing; 24056 ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithFollowing; 24057 24058 verifyFormat("template <typename T>\n" 24059 "requires Foo<T> struct Bar {};\n" 24060 "template <typename T>\n" 24061 "requires Foo<T> void bar() {}\n" 24062 "template <typename T>\n" 24063 "void bar()\n" 24064 "requires Foo<T> {}\n" 24065 "template <typename T>\n" 24066 "void bar()\n" 24067 "requires Foo<T>;\n" 24068 "template <typename T>\n" 24069 "requires Foo<T> Bar(T) -> Bar<T>;", 24070 Style); 24071 24072 verifyFormat("template <typename AAAAAAA>\n" 24073 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24074 "struct Bar {};\n" 24075 "template <typename AAAAAAA>\n" 24076 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24077 "void bar() {}\n" 24078 "template <typename AAAAAAA>\n" 24079 "void bar()\n" 24080 "requires Foo<AAAAAAAAAAAAAAAA> {}\n" 24081 "template <typename AAAAAAA>\n" 24082 "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n" 24083 "template <typename AAAAAAA>\n" 24084 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24085 "Bar(T) -> Bar<T>;", 24086 ColumnStyle); 24087 24088 Style.IndentRequiresClause = true; 24089 ColumnStyle.IndentRequiresClause = true; 24090 24091 verifyFormat("template <typename T>\n" 24092 " requires Foo<T> struct Bar {};\n" 24093 "template <typename T>\n" 24094 " requires Foo<T> void bar() {}\n" 24095 "template <typename T>\n" 24096 "void bar()\n" 24097 " requires Foo<T> {}\n" 24098 "template <typename T>\n" 24099 " requires Foo<T> Bar(T) -> Bar<T>;", 24100 Style); 24101 24102 verifyFormat("template <typename AAAAAAA>\n" 24103 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24104 "struct Bar {};\n" 24105 "template <typename AAAAAAA>\n" 24106 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24107 "void bar() {}\n" 24108 "template <typename AAAAAAA>\n" 24109 "void bar()\n" 24110 " requires Foo<AAAAAAAAAAAAAAAA> {}\n" 24111 "template <typename AAAAAAA>\n" 24112 " requires Foo<AAAAAA> Bar(T) -> Bar<T>;\n" 24113 "template <typename AAAAAAA>\n" 24114 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24115 "Bar(T) -> Bar<T>;", 24116 ColumnStyle); 24117 24118 Style.RequiresClausePosition = FormatStyle::RCPS_WithPreceding; 24119 ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithPreceding; 24120 24121 verifyFormat("template <typename T> requires Foo<T>\n" 24122 "struct Bar {};\n" 24123 "template <typename T> requires Foo<T>\n" 24124 "void bar() {}\n" 24125 "template <typename T>\n" 24126 "void bar() requires Foo<T>\n" 24127 "{}\n" 24128 "template <typename T> void bar() requires Foo<T>;\n" 24129 "template <typename T> requires Foo<T>\n" 24130 "Bar(T) -> Bar<T>;", 24131 Style); 24132 24133 verifyFormat("template <typename AAAAAAA>\n" 24134 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24135 "struct Bar {};\n" 24136 "template <typename AAAAAAA>\n" 24137 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24138 "void bar() {}\n" 24139 "template <typename AAAAAAA>\n" 24140 "void bar()\n" 24141 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24142 "{}\n" 24143 "template <typename AAAAAAA>\n" 24144 "requires Foo<AAAAAAAA>\n" 24145 "Bar(T) -> Bar<T>;\n" 24146 "template <typename AAAAAAA>\n" 24147 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24148 "Bar(T) -> Bar<T>;", 24149 ColumnStyle); 24150 } 24151 24152 TEST_F(FormatTest, RequiresClauses) { 24153 verifyFormat("struct [[nodiscard]] zero_t {\n" 24154 " template <class T>\n" 24155 " requires requires { number_zero_v<T>; }\n" 24156 " [[nodiscard]] constexpr operator T() const {\n" 24157 " return number_zero_v<T>;\n" 24158 " }\n" 24159 "};"); 24160 24161 auto Style = getLLVMStyle(); 24162 24163 verifyFormat( 24164 "template <typename T>\n" 24165 " requires is_default_constructible_v<hash<T>> and\n" 24166 " is_copy_constructible_v<hash<T>> and\n" 24167 " is_move_constructible_v<hash<T>> and\n" 24168 " is_copy_assignable_v<hash<T>> and " 24169 "is_move_assignable_v<hash<T>> and\n" 24170 " is_destructible_v<hash<T>> and is_swappable_v<hash<T>> and\n" 24171 " is_callable_v<hash<T>(T)> and\n" 24172 " is_same_v<size_t, decltype(hash<T>(declval<T>()))> and\n" 24173 " is_same_v<size_t, decltype(hash<T>(declval<T &>()))> and\n" 24174 " is_same_v<size_t, decltype(hash<T>(declval<const T &>()))>\n" 24175 "struct S {};", 24176 Style); 24177 24178 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 24179 verifyFormat( 24180 "template <typename T>\n" 24181 " requires is_default_constructible_v<hash<T>>\n" 24182 " and is_copy_constructible_v<hash<T>>\n" 24183 " and is_move_constructible_v<hash<T>>\n" 24184 " and is_copy_assignable_v<hash<T>> and " 24185 "is_move_assignable_v<hash<T>>\n" 24186 " and is_destructible_v<hash<T>> and is_swappable_v<hash<T>>\n" 24187 " and is_callable_v<hash<T>(T)>\n" 24188 " and is_same_v<size_t, decltype(hash<T>(declval<T>()))>\n" 24189 " and is_same_v<size_t, decltype(hash<T>(declval<T &>()))>\n" 24190 " and is_same_v<size_t, decltype(hash<T>(declval<const T " 24191 "&>()))>\n" 24192 "struct S {};", 24193 Style); 24194 24195 // Not a clause, but we once hit an assert. 24196 verifyFormat("#if 0\n" 24197 "#else\n" 24198 "foo();\n" 24199 "#endif\n" 24200 "bar(requires);"); 24201 } 24202 24203 TEST_F(FormatTest, StatementAttributeLikeMacros) { 24204 FormatStyle Style = getLLVMStyle(); 24205 StringRef Source = "void Foo::slot() {\n" 24206 " unsigned char MyChar = 'x';\n" 24207 " emit signal(MyChar);\n" 24208 " Q_EMIT signal(MyChar);\n" 24209 "}"; 24210 24211 EXPECT_EQ(Source, format(Source, Style)); 24212 24213 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 24214 EXPECT_EQ("void Foo::slot() {\n" 24215 " unsigned char MyChar = 'x';\n" 24216 " emit signal(MyChar);\n" 24217 " Q_EMIT signal(MyChar);\n" 24218 "}", 24219 format(Source, Style)); 24220 24221 Style.StatementAttributeLikeMacros.push_back("emit"); 24222 EXPECT_EQ(Source, format(Source, Style)); 24223 24224 Style.StatementAttributeLikeMacros = {}; 24225 EXPECT_EQ("void Foo::slot() {\n" 24226 " unsigned char MyChar = 'x';\n" 24227 " emit signal(MyChar);\n" 24228 " Q_EMIT signal(MyChar);\n" 24229 "}", 24230 format(Source, Style)); 24231 } 24232 24233 TEST_F(FormatTest, IndentAccessModifiers) { 24234 FormatStyle Style = getLLVMStyle(); 24235 Style.IndentAccessModifiers = true; 24236 // Members are *two* levels below the record; 24237 // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation. 24238 verifyFormat("class C {\n" 24239 " int i;\n" 24240 "};\n", 24241 Style); 24242 verifyFormat("union C {\n" 24243 " int i;\n" 24244 " unsigned u;\n" 24245 "};\n", 24246 Style); 24247 // Access modifiers should be indented one level below the record. 24248 verifyFormat("class C {\n" 24249 " public:\n" 24250 " int i;\n" 24251 "};\n", 24252 Style); 24253 verifyFormat("struct S {\n" 24254 " private:\n" 24255 " class C {\n" 24256 " int j;\n" 24257 "\n" 24258 " public:\n" 24259 " C();\n" 24260 " };\n" 24261 "\n" 24262 " public:\n" 24263 " int i;\n" 24264 "};\n", 24265 Style); 24266 // Enumerations are not records and should be unaffected. 24267 Style.AllowShortEnumsOnASingleLine = false; 24268 verifyFormat("enum class E {\n" 24269 " A,\n" 24270 " B\n" 24271 "};\n", 24272 Style); 24273 // Test with a different indentation width; 24274 // also proves that the result is Style.AccessModifierOffset agnostic. 24275 Style.IndentWidth = 3; 24276 verifyFormat("class C {\n" 24277 " public:\n" 24278 " int i;\n" 24279 "};\n", 24280 Style); 24281 } 24282 24283 TEST_F(FormatTest, LimitlessStringsAndComments) { 24284 auto Style = getLLVMStyleWithColumns(0); 24285 constexpr StringRef Code = 24286 "/**\n" 24287 " * This is a multiline comment with quite some long lines, at least for " 24288 "the LLVM Style.\n" 24289 " * We will redo this with strings and line comments. Just to check if " 24290 "everything is working.\n" 24291 " */\n" 24292 "bool foo() {\n" 24293 " /* Single line multi line comment. */\n" 24294 " const std::string String = \"This is a multiline string with quite " 24295 "some long lines, at least for the LLVM Style.\"\n" 24296 " \"We already did it with multi line " 24297 "comments, and we will do it with line comments. Just to check if " 24298 "everything is working.\";\n" 24299 " // This is a line comment (block) with quite some long lines, at " 24300 "least for the LLVM Style.\n" 24301 " // We already did this with multi line comments and strings. Just to " 24302 "check if everything is working.\n" 24303 " const std::string SmallString = \"Hello World\";\n" 24304 " // Small line comment\n" 24305 " return String.size() > SmallString.size();\n" 24306 "}"; 24307 EXPECT_EQ(Code, format(Code, Style)); 24308 } 24309 24310 TEST_F(FormatTest, FormatDecayCopy) { 24311 // error cases from unit tests 24312 verifyFormat("foo(auto())"); 24313 verifyFormat("foo(auto{})"); 24314 verifyFormat("foo(auto({}))"); 24315 verifyFormat("foo(auto{{}})"); 24316 24317 verifyFormat("foo(auto(1))"); 24318 verifyFormat("foo(auto{1})"); 24319 verifyFormat("foo(new auto(1))"); 24320 verifyFormat("foo(new auto{1})"); 24321 verifyFormat("decltype(auto(1)) x;"); 24322 verifyFormat("decltype(auto{1}) x;"); 24323 verifyFormat("auto(x);"); 24324 verifyFormat("auto{x};"); 24325 verifyFormat("new auto{x};"); 24326 verifyFormat("auto{x} = y;"); 24327 verifyFormat("auto(x) = y;"); // actually a declaration, but this is clearly 24328 // the user's own fault 24329 verifyFormat("integral auto(x) = y;"); // actually a declaration, but this is 24330 // clearly the user's own fault 24331 verifyFormat("auto(*p)() = f;"); // actually a declaration; TODO FIXME 24332 } 24333 24334 TEST_F(FormatTest, Cpp20ModulesSupport) { 24335 FormatStyle Style = getLLVMStyle(); 24336 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 24337 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 24338 24339 verifyFormat("export import foo;", Style); 24340 verifyFormat("export import foo:bar;", Style); 24341 verifyFormat("export import foo.bar;", Style); 24342 verifyFormat("export import foo.bar:baz;", Style); 24343 verifyFormat("export import :bar;", Style); 24344 verifyFormat("export module foo:bar;", Style); 24345 verifyFormat("export module foo;", Style); 24346 verifyFormat("export module foo.bar;", Style); 24347 verifyFormat("export module foo.bar:baz;", Style); 24348 verifyFormat("export import <string_view>;", Style); 24349 24350 verifyFormat("export type_name var;", Style); 24351 verifyFormat("template <class T> export using A = B<T>;", Style); 24352 verifyFormat("export using A = B;", Style); 24353 verifyFormat("export int func() {\n" 24354 " foo();\n" 24355 "}", 24356 Style); 24357 verifyFormat("export struct {\n" 24358 " int foo;\n" 24359 "};", 24360 Style); 24361 verifyFormat("export {\n" 24362 " int foo;\n" 24363 "};", 24364 Style); 24365 verifyFormat("export export char const *hello() { return \"hello\"; }"); 24366 24367 verifyFormat("import bar;", Style); 24368 verifyFormat("import foo.bar;", Style); 24369 verifyFormat("import foo:bar;", Style); 24370 verifyFormat("import :bar;", Style); 24371 verifyFormat("import <ctime>;", Style); 24372 verifyFormat("import \"header\";", Style); 24373 24374 verifyFormat("module foo;", Style); 24375 verifyFormat("module foo:bar;", Style); 24376 verifyFormat("module foo.bar;", Style); 24377 verifyFormat("module;", Style); 24378 24379 verifyFormat("export namespace hi {\n" 24380 "const char *sayhi();\n" 24381 "}", 24382 Style); 24383 24384 verifyFormat("module :private;", Style); 24385 verifyFormat("import <foo/bar.h>;", Style); 24386 verifyFormat("import foo...bar;", Style); 24387 verifyFormat("import ..........;", Style); 24388 verifyFormat("module foo:private;", Style); 24389 verifyFormat("import a", Style); 24390 verifyFormat("module a", Style); 24391 verifyFormat("export import a", Style); 24392 verifyFormat("export module a", Style); 24393 24394 verifyFormat("import", Style); 24395 verifyFormat("module", Style); 24396 verifyFormat("export", Style); 24397 } 24398 24399 TEST_F(FormatTest, CoroutineForCoawait) { 24400 FormatStyle Style = getLLVMStyle(); 24401 verifyFormat("for co_await (auto x : range())\n ;"); 24402 verifyFormat("for (auto i : arr) {\n" 24403 "}", 24404 Style); 24405 verifyFormat("for co_await (auto i : arr) {\n" 24406 "}", 24407 Style); 24408 verifyFormat("for co_await (auto i : foo(T{})) {\n" 24409 "}", 24410 Style); 24411 } 24412 24413 TEST_F(FormatTest, CoroutineCoAwait) { 24414 verifyFormat("int x = co_await foo();"); 24415 verifyFormat("int x = (co_await foo());"); 24416 verifyFormat("co_await (42);"); 24417 verifyFormat("void operator co_await(int);"); 24418 verifyFormat("void operator co_await(a);"); 24419 verifyFormat("co_await a;"); 24420 verifyFormat("co_await missing_await_resume{};"); 24421 verifyFormat("co_await a; // comment"); 24422 verifyFormat("void test0() { co_await a; }"); 24423 verifyFormat("co_await co_await co_await foo();"); 24424 verifyFormat("co_await foo().bar();"); 24425 verifyFormat("co_await [this]() -> Task { co_return x; }"); 24426 verifyFormat("co_await [this](int a, int b) -> Task { co_return co_await " 24427 "foo(); }(x, y);"); 24428 24429 FormatStyle Style = getLLVMStyleWithColumns(40); 24430 verifyFormat("co_await [this](int a, int b) -> Task {\n" 24431 " co_return co_await foo();\n" 24432 "}(x, y);", 24433 Style); 24434 verifyFormat("co_await;"); 24435 } 24436 24437 TEST_F(FormatTest, CoroutineCoYield) { 24438 verifyFormat("int x = co_yield foo();"); 24439 verifyFormat("int x = (co_yield foo());"); 24440 verifyFormat("co_yield (42);"); 24441 verifyFormat("co_yield {42};"); 24442 verifyFormat("co_yield 42;"); 24443 verifyFormat("co_yield n++;"); 24444 verifyFormat("co_yield ++n;"); 24445 verifyFormat("co_yield;"); 24446 } 24447 24448 TEST_F(FormatTest, CoroutineCoReturn) { 24449 verifyFormat("co_return (42);"); 24450 verifyFormat("co_return;"); 24451 verifyFormat("co_return {};"); 24452 verifyFormat("co_return x;"); 24453 verifyFormat("co_return co_await foo();"); 24454 verifyFormat("co_return co_yield foo();"); 24455 } 24456 24457 TEST_F(FormatTest, EmptyShortBlock) { 24458 auto Style = getLLVMStyle(); 24459 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 24460 24461 verifyFormat("try {\n" 24462 " doA();\n" 24463 "} catch (Exception &e) {\n" 24464 " e.printStackTrace();\n" 24465 "}\n", 24466 Style); 24467 24468 verifyFormat("try {\n" 24469 " doA();\n" 24470 "} catch (Exception &e) {}\n", 24471 Style); 24472 } 24473 24474 TEST_F(FormatTest, ShortTemplatedArgumentLists) { 24475 auto Style = getLLVMStyle(); 24476 24477 verifyFormat("template <> struct S : Template<int (*)[]> {};\n", Style); 24478 verifyFormat("template <> struct S : Template<int (*)[10]> {};\n", Style); 24479 verifyFormat("struct Y : X<[] { return 0; }> {};", Style); 24480 verifyFormat("struct Y<[] { return 0; }> {};", Style); 24481 24482 verifyFormat("struct Z : X<decltype([] { return 0; }){}> {};", Style); 24483 verifyFormat("template <int N> struct Foo<char[N]> {};", Style); 24484 } 24485 24486 TEST_F(FormatTest, InsertBraces) { 24487 FormatStyle Style = getLLVMStyle(); 24488 Style.InsertBraces = true; 24489 24490 verifyFormat("// clang-format off\n" 24491 "// comment\n" 24492 "if (a) f();\n" 24493 "// clang-format on\n" 24494 "if (b) {\n" 24495 " g();\n" 24496 "}", 24497 "// clang-format off\n" 24498 "// comment\n" 24499 "if (a) f();\n" 24500 "// clang-format on\n" 24501 "if (b) g();", 24502 Style); 24503 24504 verifyFormat("if (a) {\n" 24505 " switch (b) {\n" 24506 " case 1:\n" 24507 " c = 0;\n" 24508 " break;\n" 24509 " default:\n" 24510 " c = 1;\n" 24511 " }\n" 24512 "}", 24513 "if (a)\n" 24514 " switch (b) {\n" 24515 " case 1:\n" 24516 " c = 0;\n" 24517 " break;\n" 24518 " default:\n" 24519 " c = 1;\n" 24520 " }", 24521 Style); 24522 24523 verifyFormat("for (auto node : nodes) {\n" 24524 " if (node) {\n" 24525 " break;\n" 24526 " }\n" 24527 "}", 24528 "for (auto node : nodes)\n" 24529 " if (node)\n" 24530 " break;", 24531 Style); 24532 24533 verifyFormat("for (auto node : nodes) {\n" 24534 " if (node)\n" 24535 "}", 24536 "for (auto node : nodes)\n" 24537 " if (node)", 24538 Style); 24539 24540 verifyFormat("do {\n" 24541 " --a;\n" 24542 "} while (a);", 24543 "do\n" 24544 " --a;\n" 24545 "while (a);", 24546 Style); 24547 24548 verifyFormat("if (i) {\n" 24549 " ++i;\n" 24550 "} else {\n" 24551 " --i;\n" 24552 "}", 24553 "if (i)\n" 24554 " ++i;\n" 24555 "else {\n" 24556 " --i;\n" 24557 "}", 24558 Style); 24559 24560 verifyFormat("void f() {\n" 24561 " while (j--) {\n" 24562 " while (i) {\n" 24563 " --i;\n" 24564 " }\n" 24565 " }\n" 24566 "}", 24567 "void f() {\n" 24568 " while (j--)\n" 24569 " while (i)\n" 24570 " --i;\n" 24571 "}", 24572 Style); 24573 24574 verifyFormat("f({\n" 24575 " if (a) {\n" 24576 " g();\n" 24577 " }\n" 24578 "});", 24579 "f({\n" 24580 " if (a)\n" 24581 " g();\n" 24582 "});", 24583 Style); 24584 24585 verifyFormat("if (a) {\n" 24586 " f();\n" 24587 "} else if (b) {\n" 24588 " g();\n" 24589 "} else {\n" 24590 " h();\n" 24591 "}", 24592 "if (a)\n" 24593 " f();\n" 24594 "else if (b)\n" 24595 " g();\n" 24596 "else\n" 24597 " h();", 24598 Style); 24599 24600 verifyFormat("if (a) {\n" 24601 " f();\n" 24602 "}\n" 24603 "// comment\n" 24604 "/* comment */", 24605 "if (a)\n" 24606 " f();\n" 24607 "// comment\n" 24608 "/* comment */", 24609 Style); 24610 24611 verifyFormat("if (a) {\n" 24612 " // foo\n" 24613 " // bar\n" 24614 " f();\n" 24615 "}", 24616 "if (a)\n" 24617 " // foo\n" 24618 " // bar\n" 24619 " f();", 24620 Style); 24621 24622 verifyFormat("if (a) { // comment\n" 24623 " // comment\n" 24624 " f();\n" 24625 "}", 24626 "if (a) // comment\n" 24627 " // comment\n" 24628 " f();", 24629 Style); 24630 24631 verifyFormat("if (a) {\n" 24632 " f(); // comment\n" 24633 "}", 24634 "if (a)\n" 24635 " f(); // comment", 24636 Style); 24637 24638 verifyFormat("if (a) {\n" 24639 " f();\n" 24640 "}\n" 24641 "#undef A\n" 24642 "#undef B", 24643 "if (a)\n" 24644 " f();\n" 24645 "#undef A\n" 24646 "#undef B", 24647 Style); 24648 24649 verifyFormat("if (a)\n" 24650 "#ifdef A\n" 24651 " f();\n" 24652 "#else\n" 24653 " g();\n" 24654 "#endif", 24655 Style); 24656 24657 verifyFormat("#if 0\n" 24658 "#elif 1\n" 24659 "#endif\n" 24660 "void f() {\n" 24661 " if (a) {\n" 24662 " g();\n" 24663 " }\n" 24664 "}", 24665 "#if 0\n" 24666 "#elif 1\n" 24667 "#endif\n" 24668 "void f() {\n" 24669 " if (a) g();\n" 24670 "}", 24671 Style); 24672 24673 Style.ColumnLimit = 15; 24674 24675 verifyFormat("#define A \\\n" 24676 " if (a) \\\n" 24677 " f();", 24678 Style); 24679 24680 verifyFormat("if (a + b >\n" 24681 " c) {\n" 24682 " f();\n" 24683 "}", 24684 "if (a + b > c)\n" 24685 " f();", 24686 Style); 24687 } 24688 24689 TEST_F(FormatTest, RemoveBraces) { 24690 FormatStyle Style = getLLVMStyle(); 24691 Style.RemoveBracesLLVM = true; 24692 24693 // The following eight test cases are fully-braced versions of the examples at 24694 // "llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single- 24695 // statement-bodies-of-if-else-loop-statements". 24696 24697 // 1. Omit the braces, since the body is simple and clearly associated with 24698 // the if. 24699 verifyFormat("if (isa<FunctionDecl>(D))\n" 24700 " handleFunctionDecl(D);\n" 24701 "else if (isa<VarDecl>(D))\n" 24702 " handleVarDecl(D);", 24703 "if (isa<FunctionDecl>(D)) {\n" 24704 " handleFunctionDecl(D);\n" 24705 "} else if (isa<VarDecl>(D)) {\n" 24706 " handleVarDecl(D);\n" 24707 "}", 24708 Style); 24709 24710 // 2. Here we document the condition itself and not the body. 24711 verifyFormat("if (isa<VarDecl>(D)) {\n" 24712 " // It is necessary that we explain the situation with this\n" 24713 " // surprisingly long comment, so it would be unclear\n" 24714 " // without the braces whether the following statement is in\n" 24715 " // the scope of the `if`.\n" 24716 " // Because the condition is documented, we can't really\n" 24717 " // hoist this comment that applies to the body above the\n" 24718 " // if.\n" 24719 " handleOtherDecl(D);\n" 24720 "}", 24721 Style); 24722 24723 // 3. Use braces on the outer `if` to avoid a potential dangling else 24724 // situation. 24725 verifyFormat("if (isa<VarDecl>(D)) {\n" 24726 " for (auto *A : D.attrs())\n" 24727 " if (shouldProcessAttr(A))\n" 24728 " handleAttr(A);\n" 24729 "}", 24730 "if (isa<VarDecl>(D)) {\n" 24731 " for (auto *A : D.attrs()) {\n" 24732 " if (shouldProcessAttr(A)) {\n" 24733 " handleAttr(A);\n" 24734 " }\n" 24735 " }\n" 24736 "}", 24737 Style); 24738 24739 // 4. Use braces for the `if` block to keep it uniform with the else block. 24740 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 24741 " handleFunctionDecl(D);\n" 24742 "} else {\n" 24743 " // In this else case, it is necessary that we explain the\n" 24744 " // situation with this surprisingly long comment, so it\n" 24745 " // would be unclear without the braces whether the\n" 24746 " // following statement is in the scope of the `if`.\n" 24747 " handleOtherDecl(D);\n" 24748 "}", 24749 Style); 24750 24751 // 5. This should also omit braces. The `for` loop contains only a single 24752 // statement, so it shouldn't have braces. The `if` also only contains a 24753 // single simple statement (the for loop), so it also should omit braces. 24754 verifyFormat("if (isa<FunctionDecl>(D))\n" 24755 " for (auto *A : D.attrs())\n" 24756 " handleAttr(A);", 24757 "if (isa<FunctionDecl>(D)) {\n" 24758 " for (auto *A : D.attrs()) {\n" 24759 " handleAttr(A);\n" 24760 " }\n" 24761 "}", 24762 Style); 24763 24764 // 6. Use braces for the outer `if` since the nested `for` is braced. 24765 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 24766 " for (auto *A : D.attrs()) {\n" 24767 " // In this for loop body, it is necessary that we explain\n" 24768 " // the situation with this surprisingly long comment,\n" 24769 " // forcing braces on the `for` block.\n" 24770 " handleAttr(A);\n" 24771 " }\n" 24772 "}", 24773 Style); 24774 24775 // 7. Use braces on the outer block because there are more than two levels of 24776 // nesting. 24777 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 24778 " for (auto *A : D.attrs())\n" 24779 " for (ssize_t i : llvm::seq<ssize_t>(count))\n" 24780 " handleAttrOnDecl(D, A, i);\n" 24781 "}", 24782 "if (isa<FunctionDecl>(D)) {\n" 24783 " for (auto *A : D.attrs()) {\n" 24784 " for (ssize_t i : llvm::seq<ssize_t>(count)) {\n" 24785 " handleAttrOnDecl(D, A, i);\n" 24786 " }\n" 24787 " }\n" 24788 "}", 24789 Style); 24790 24791 // 8. Use braces on the outer block because of a nested `if`, otherwise the 24792 // compiler would warn: `add explicit braces to avoid dangling else` 24793 verifyFormat("if (auto *D = dyn_cast<FunctionDecl>(D)) {\n" 24794 " if (shouldProcess(D))\n" 24795 " handleVarDecl(D);\n" 24796 " else\n" 24797 " markAsIgnored(D);\n" 24798 "}", 24799 "if (auto *D = dyn_cast<FunctionDecl>(D)) {\n" 24800 " if (shouldProcess(D)) {\n" 24801 " handleVarDecl(D);\n" 24802 " } else {\n" 24803 " markAsIgnored(D);\n" 24804 " }\n" 24805 "}", 24806 Style); 24807 24808 verifyFormat("if (a)\n" 24809 " b; // comment\n" 24810 "else if (c)\n" 24811 " d; /* comment */\n" 24812 "else\n" 24813 " e;", 24814 "if (a) {\n" 24815 " b; // comment\n" 24816 "} else if (c) {\n" 24817 " d; /* comment */\n" 24818 "} else {\n" 24819 " e;\n" 24820 "}", 24821 Style); 24822 24823 verifyFormat("if (a) {\n" 24824 " b;\n" 24825 " c;\n" 24826 "} else if (d) {\n" 24827 " e;\n" 24828 "}", 24829 Style); 24830 24831 verifyFormat("if (a) {\n" 24832 "#undef NDEBUG\n" 24833 " b;\n" 24834 "} else {\n" 24835 " c;\n" 24836 "}", 24837 Style); 24838 24839 verifyFormat("if (a) {\n" 24840 " // comment\n" 24841 "} else if (b) {\n" 24842 " c;\n" 24843 "}", 24844 Style); 24845 24846 verifyFormat("if (a) {\n" 24847 " b;\n" 24848 "} else {\n" 24849 " { c; }\n" 24850 "}", 24851 Style); 24852 24853 verifyFormat("if (a) {\n" 24854 " if (b) // comment\n" 24855 " c;\n" 24856 "} else if (d) {\n" 24857 " e;\n" 24858 "}", 24859 "if (a) {\n" 24860 " if (b) { // comment\n" 24861 " c;\n" 24862 " }\n" 24863 "} else if (d) {\n" 24864 " e;\n" 24865 "}", 24866 Style); 24867 24868 verifyFormat("if (a) {\n" 24869 " if (b) {\n" 24870 " c;\n" 24871 " // comment\n" 24872 " } else if (d) {\n" 24873 " e;\n" 24874 " }\n" 24875 "}", 24876 Style); 24877 24878 verifyFormat("if (a) {\n" 24879 " if (b)\n" 24880 " c;\n" 24881 "}", 24882 "if (a) {\n" 24883 " if (b) {\n" 24884 " c;\n" 24885 " }\n" 24886 "}", 24887 Style); 24888 24889 verifyFormat("if (a)\n" 24890 " if (b)\n" 24891 " c;\n" 24892 " else\n" 24893 " d;\n" 24894 "else\n" 24895 " e;", 24896 "if (a) {\n" 24897 " if (b) {\n" 24898 " c;\n" 24899 " } else {\n" 24900 " d;\n" 24901 " }\n" 24902 "} else {\n" 24903 " e;\n" 24904 "}", 24905 Style); 24906 24907 verifyFormat("if (a) {\n" 24908 " // comment\n" 24909 " if (b)\n" 24910 " c;\n" 24911 " else if (d)\n" 24912 " e;\n" 24913 "} else {\n" 24914 " g;\n" 24915 "}", 24916 "if (a) {\n" 24917 " // comment\n" 24918 " if (b) {\n" 24919 " c;\n" 24920 " } else if (d) {\n" 24921 " e;\n" 24922 " }\n" 24923 "} else {\n" 24924 " g;\n" 24925 "}", 24926 Style); 24927 24928 verifyFormat("if (a)\n" 24929 " b;\n" 24930 "else if (c)\n" 24931 " d;\n" 24932 "else\n" 24933 " e;", 24934 "if (a) {\n" 24935 " b;\n" 24936 "} else {\n" 24937 " if (c) {\n" 24938 " d;\n" 24939 " } else {\n" 24940 " e;\n" 24941 " }\n" 24942 "}", 24943 Style); 24944 24945 verifyFormat("if (a) {\n" 24946 " if (b)\n" 24947 " c;\n" 24948 " else if (d)\n" 24949 " e;\n" 24950 "} else {\n" 24951 " g;\n" 24952 "}", 24953 "if (a) {\n" 24954 " if (b)\n" 24955 " c;\n" 24956 " else {\n" 24957 " if (d)\n" 24958 " e;\n" 24959 " }\n" 24960 "} else {\n" 24961 " g;\n" 24962 "}", 24963 Style); 24964 24965 verifyFormat("if (a)\n" 24966 " b;\n" 24967 "else if (c)\n" 24968 " while (d)\n" 24969 " e;\n" 24970 "// comment", 24971 "if (a)\n" 24972 "{\n" 24973 " b;\n" 24974 "} else if (c) {\n" 24975 " while (d) {\n" 24976 " e;\n" 24977 " }\n" 24978 "}\n" 24979 "// comment", 24980 Style); 24981 24982 verifyFormat("if (a) {\n" 24983 " b;\n" 24984 "} else if (c) {\n" 24985 " d;\n" 24986 "} else {\n" 24987 " e;\n" 24988 " g;\n" 24989 "}", 24990 Style); 24991 24992 verifyFormat("if (a) {\n" 24993 " b;\n" 24994 "} else if (c) {\n" 24995 " d;\n" 24996 "} else {\n" 24997 " e;\n" 24998 "} // comment", 24999 Style); 25000 25001 verifyFormat("int abs = [](int i) {\n" 25002 " if (i >= 0)\n" 25003 " return i;\n" 25004 " return -i;\n" 25005 "};", 25006 "int abs = [](int i) {\n" 25007 " if (i >= 0) {\n" 25008 " return i;\n" 25009 " }\n" 25010 " return -i;\n" 25011 "};", 25012 Style); 25013 25014 verifyFormat("if (a)\n" 25015 " foo();\n" 25016 "else\n" 25017 " bar();", 25018 "if (a)\n" 25019 "{\n" 25020 " foo();\n" 25021 "}\n" 25022 "else\n" 25023 "{\n" 25024 " bar();\n" 25025 "}", 25026 Style); 25027 25028 verifyFormat("if (a) {\n" 25029 "Label:\n" 25030 "}", 25031 Style); 25032 25033 verifyFormat("if (a) {\n" 25034 "Label:\n" 25035 " f();\n" 25036 "}", 25037 Style); 25038 25039 verifyFormat("if (a) {\n" 25040 " f();\n" 25041 "Label:\n" 25042 "}", 25043 Style); 25044 25045 // FIXME: See https://github.com/llvm/llvm-project/issues/53543. 25046 #if 0 25047 Style.ColumnLimit = 65; 25048 25049 verifyFormat("if (condition) {\n" 25050 " ff(Indices,\n" 25051 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 25052 "} else {\n" 25053 " ff(Indices,\n" 25054 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 25055 "}", 25056 Style); 25057 25058 Style.ColumnLimit = 20; 25059 25060 verifyFormat("if (a) {\n" 25061 " b = c + // 1 -\n" 25062 " d;\n" 25063 "}", 25064 Style); 25065 25066 verifyFormat("if (a) {\n" 25067 " b = c >= 0 ? d\n" 25068 " : e;\n" 25069 "}", 25070 "if (a) {\n" 25071 " b = c >= 0 ? d : e;\n" 25072 "}", 25073 Style); 25074 #endif 25075 25076 Style.ColumnLimit = 20; 25077 25078 verifyFormat("if (a)\n" 25079 " b = c > 0 ? d : e;", 25080 "if (a) {\n" 25081 " b = c > 0 ? d : e;\n" 25082 "}", 25083 Style); 25084 25085 Style.ColumnLimit = 0; 25086 25087 verifyFormat("if (a)\n" 25088 " b234567890223456789032345678904234567890 = " 25089 "c234567890223456789032345678904234567890;", 25090 "if (a) {\n" 25091 " b234567890223456789032345678904234567890 = " 25092 "c234567890223456789032345678904234567890;\n" 25093 "}", 25094 Style); 25095 } 25096 25097 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndent) { 25098 auto Style = getLLVMStyle(); 25099 25100 StringRef Short = "functionCall(paramA, paramB, paramC);\n" 25101 "void functionDecl(int a, int b, int c);"; 25102 25103 StringRef Medium = "functionCall(paramA, paramB, paramC, paramD, paramE, " 25104 "paramF, paramG, paramH, paramI);\n" 25105 "void functionDecl(int argumentA, int argumentB, int " 25106 "argumentC, int argumentD, int argumentE);"; 25107 25108 verifyFormat(Short, Style); 25109 25110 StringRef NoBreak = "functionCall(paramA, paramB, paramC, paramD, paramE, " 25111 "paramF, paramG, paramH,\n" 25112 " paramI);\n" 25113 "void functionDecl(int argumentA, int argumentB, int " 25114 "argumentC, int argumentD,\n" 25115 " int argumentE);"; 25116 25117 verifyFormat(NoBreak, Medium, Style); 25118 verifyFormat(NoBreak, 25119 "functionCall(\n" 25120 " paramA,\n" 25121 " paramB,\n" 25122 " paramC,\n" 25123 " paramD,\n" 25124 " paramE,\n" 25125 " paramF,\n" 25126 " paramG,\n" 25127 " paramH,\n" 25128 " paramI\n" 25129 ");\n" 25130 "void functionDecl(\n" 25131 " int argumentA,\n" 25132 " int argumentB,\n" 25133 " int argumentC,\n" 25134 " int argumentD,\n" 25135 " int argumentE\n" 25136 ");", 25137 Style); 25138 25139 verifyFormat("outerFunctionCall(nestedFunctionCall(argument1),\n" 25140 " nestedLongFunctionCall(argument1, " 25141 "argument2, argument3,\n" 25142 " argument4, " 25143 "argument5));", 25144 Style); 25145 25146 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 25147 25148 verifyFormat(Short, Style); 25149 verifyFormat( 25150 "functionCall(\n" 25151 " paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, " 25152 "paramI\n" 25153 ");\n" 25154 "void functionDecl(\n" 25155 " int argumentA, int argumentB, int argumentC, int argumentD, int " 25156 "argumentE\n" 25157 ");", 25158 Medium, Style); 25159 25160 Style.AllowAllArgumentsOnNextLine = false; 25161 Style.AllowAllParametersOfDeclarationOnNextLine = false; 25162 25163 verifyFormat(Short, Style); 25164 verifyFormat( 25165 "functionCall(\n" 25166 " paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, " 25167 "paramI\n" 25168 ");\n" 25169 "void functionDecl(\n" 25170 " int argumentA, int argumentB, int argumentC, int argumentD, int " 25171 "argumentE\n" 25172 ");", 25173 Medium, Style); 25174 25175 Style.BinPackArguments = false; 25176 Style.BinPackParameters = false; 25177 25178 verifyFormat(Short, Style); 25179 25180 verifyFormat("functionCall(\n" 25181 " paramA,\n" 25182 " paramB,\n" 25183 " paramC,\n" 25184 " paramD,\n" 25185 " paramE,\n" 25186 " paramF,\n" 25187 " paramG,\n" 25188 " paramH,\n" 25189 " paramI\n" 25190 ");\n" 25191 "void functionDecl(\n" 25192 " int argumentA,\n" 25193 " int argumentB,\n" 25194 " int argumentC,\n" 25195 " int argumentD,\n" 25196 " int argumentE\n" 25197 ");", 25198 Medium, Style); 25199 25200 verifyFormat("outerFunctionCall(\n" 25201 " nestedFunctionCall(argument1),\n" 25202 " nestedLongFunctionCall(\n" 25203 " argument1,\n" 25204 " argument2,\n" 25205 " argument3,\n" 25206 " argument4,\n" 25207 " argument5\n" 25208 " )\n" 25209 ");", 25210 Style); 25211 25212 verifyFormat("int a = (int)b;", Style); 25213 verifyFormat("int a = (int)b;", 25214 "int a = (\n" 25215 " int\n" 25216 ") b;", 25217 Style); 25218 25219 verifyFormat("return (true);", Style); 25220 verifyFormat("return (true);", 25221 "return (\n" 25222 " true\n" 25223 ");", 25224 Style); 25225 25226 verifyFormat("void foo();", Style); 25227 verifyFormat("void foo();", 25228 "void foo(\n" 25229 ");", 25230 Style); 25231 25232 verifyFormat("void foo() {}", Style); 25233 verifyFormat("void foo() {}", 25234 "void foo(\n" 25235 ") {\n" 25236 "}", 25237 Style); 25238 25239 verifyFormat("auto string = std::string();", Style); 25240 verifyFormat("auto string = std::string();", 25241 "auto string = std::string(\n" 25242 ");", 25243 Style); 25244 25245 verifyFormat("void (*functionPointer)() = nullptr;", Style); 25246 verifyFormat("void (*functionPointer)() = nullptr;", 25247 "void (\n" 25248 " *functionPointer\n" 25249 ")\n" 25250 "(\n" 25251 ") = nullptr;", 25252 Style); 25253 } 25254 25255 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentIfStatement) { 25256 auto Style = getLLVMStyle(); 25257 25258 verifyFormat("if (foo()) {\n" 25259 " return;\n" 25260 "}", 25261 Style); 25262 25263 verifyFormat("if (quitelongarg !=\n" 25264 " (alsolongarg - 1)) { // ABC is a very longgggggggggggg " 25265 "comment\n" 25266 " return;\n" 25267 "}", 25268 Style); 25269 25270 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 25271 25272 verifyFormat("if (foo()) {\n" 25273 " return;\n" 25274 "}", 25275 Style); 25276 25277 verifyFormat("if (quitelongarg !=\n" 25278 " (alsolongarg - 1)) { // ABC is a very longgggggggggggg " 25279 "comment\n" 25280 " return;\n" 25281 "}", 25282 Style); 25283 } 25284 25285 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentForStatement) { 25286 auto Style = getLLVMStyle(); 25287 25288 verifyFormat("for (int i = 0; i < 5; ++i) {\n" 25289 " doSomething();\n" 25290 "}", 25291 Style); 25292 25293 verifyFormat("for (int myReallyLongCountVariable = 0; " 25294 "myReallyLongCountVariable < count;\n" 25295 " myReallyLongCountVariable++) {\n" 25296 " doSomething();\n" 25297 "}", 25298 Style); 25299 25300 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 25301 25302 verifyFormat("for (int i = 0; i < 5; ++i) {\n" 25303 " doSomething();\n" 25304 "}", 25305 Style); 25306 25307 verifyFormat("for (int myReallyLongCountVariable = 0; " 25308 "myReallyLongCountVariable < count;\n" 25309 " myReallyLongCountVariable++) {\n" 25310 " doSomething();\n" 25311 "}", 25312 Style); 25313 } 25314 25315 TEST_F(FormatTest, UnderstandsDigraphs) { 25316 verifyFormat("int arr<:5:> = {};"); 25317 verifyFormat("int arr[5] = <%%>;"); 25318 verifyFormat("int arr<:::qualified_variable:> = {};"); 25319 verifyFormat("int arr[::qualified_variable] = <%%>;"); 25320 verifyFormat("%:include <header>"); 25321 verifyFormat("%:define A x##y"); 25322 verifyFormat("#define A x%:%:y"); 25323 } 25324 25325 } // namespace 25326 } // namespace format 25327 } // namespace clang 25328