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 (a)\n" 587 " g();"); 588 verifyFormat("if (a) {\n" 589 " g()\n" 590 "};"); 591 verifyFormat("if (a)\n" 592 " g();\n" 593 "else\n" 594 " g();"); 595 verifyFormat("if (a) {\n" 596 " g();\n" 597 "} else\n" 598 " g();"); 599 verifyFormat("if (a)\n" 600 " g();\n" 601 "else {\n" 602 " g();\n" 603 "}"); 604 verifyFormat("if (a) {\n" 605 " g();\n" 606 "} else {\n" 607 " g();\n" 608 "}"); 609 verifyFormat("if (a)\n" 610 " g();\n" 611 "else if (b)\n" 612 " g();\n" 613 "else\n" 614 " g();"); 615 verifyFormat("if (a) {\n" 616 " g();\n" 617 "} else if (b)\n" 618 " g();\n" 619 "else\n" 620 " g();"); 621 verifyFormat("if (a)\n" 622 " g();\n" 623 "else if (b) {\n" 624 " g();\n" 625 "} else\n" 626 " g();"); 627 verifyFormat("if (a)\n" 628 " g();\n" 629 "else if (b)\n" 630 " g();\n" 631 "else {\n" 632 " g();\n" 633 "}"); 634 verifyFormat("if (a)\n" 635 " g();\n" 636 "else if (b) {\n" 637 " g();\n" 638 "} else {\n" 639 " g();\n" 640 "}"); 641 verifyFormat("if (a) {\n" 642 " g();\n" 643 "} else if (b) {\n" 644 " g();\n" 645 "} else {\n" 646 " g();\n" 647 "}"); 648 649 FormatStyle AllowsMergedIf = getLLVMStyle(); 650 AllowsMergedIf.IfMacros.push_back("MYIF"); 651 AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left; 652 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 653 FormatStyle::SIS_WithoutElse; 654 verifyFormat("if (a)\n" 655 " // comment\n" 656 " f();", 657 AllowsMergedIf); 658 verifyFormat("{\n" 659 " if (a)\n" 660 " label:\n" 661 " f();\n" 662 "}", 663 AllowsMergedIf); 664 verifyFormat("#define A \\\n" 665 " if (a) \\\n" 666 " label: \\\n" 667 " f()", 668 AllowsMergedIf); 669 verifyFormat("if (a)\n" 670 " ;", 671 AllowsMergedIf); 672 verifyFormat("if (a)\n" 673 " if (b) return;", 674 AllowsMergedIf); 675 676 verifyFormat("if (a) // Can't merge this\n" 677 " f();\n", 678 AllowsMergedIf); 679 verifyFormat("if (a) /* still don't merge */\n" 680 " f();", 681 AllowsMergedIf); 682 verifyFormat("if (a) { // Never merge this\n" 683 " f();\n" 684 "}", 685 AllowsMergedIf); 686 verifyFormat("if (a) { /* Never merge this */\n" 687 " f();\n" 688 "}", 689 AllowsMergedIf); 690 verifyFormat("MYIF (a)\n" 691 " // comment\n" 692 " f();", 693 AllowsMergedIf); 694 verifyFormat("{\n" 695 " MYIF (a)\n" 696 " label:\n" 697 " f();\n" 698 "}", 699 AllowsMergedIf); 700 verifyFormat("#define A \\\n" 701 " MYIF (a) \\\n" 702 " label: \\\n" 703 " f()", 704 AllowsMergedIf); 705 verifyFormat("MYIF (a)\n" 706 " ;", 707 AllowsMergedIf); 708 verifyFormat("MYIF (a)\n" 709 " MYIF (b) return;", 710 AllowsMergedIf); 711 712 verifyFormat("MYIF (a) // Can't merge this\n" 713 " f();\n", 714 AllowsMergedIf); 715 verifyFormat("MYIF (a) /* still don't merge */\n" 716 " f();", 717 AllowsMergedIf); 718 verifyFormat("MYIF (a) { // Never merge this\n" 719 " f();\n" 720 "}", 721 AllowsMergedIf); 722 verifyFormat("MYIF (a) { /* Never merge this */\n" 723 " f();\n" 724 "}", 725 AllowsMergedIf); 726 727 AllowsMergedIf.ColumnLimit = 14; 728 // Where line-lengths matter, a 2-letter synonym that maintains line length. 729 // Not IF to avoid any confusion that IF is somehow special. 730 AllowsMergedIf.IfMacros.push_back("FI"); 731 verifyFormat("if (a) return;", AllowsMergedIf); 732 verifyFormat("if (aaaaaaaaa)\n" 733 " return;", 734 AllowsMergedIf); 735 verifyFormat("FI (a) return;", AllowsMergedIf); 736 verifyFormat("FI (aaaaaaaaa)\n" 737 " return;", 738 AllowsMergedIf); 739 740 AllowsMergedIf.ColumnLimit = 13; 741 verifyFormat("if (a)\n return;", AllowsMergedIf); 742 verifyFormat("FI (a)\n return;", AllowsMergedIf); 743 744 FormatStyle AllowsMergedIfElse = getLLVMStyle(); 745 AllowsMergedIfElse.IfMacros.push_back("MYIF"); 746 AllowsMergedIfElse.AllowShortIfStatementsOnASingleLine = 747 FormatStyle::SIS_AllIfsAndElse; 748 verifyFormat("if (a)\n" 749 " // comment\n" 750 " f();\n" 751 "else\n" 752 " // comment\n" 753 " f();", 754 AllowsMergedIfElse); 755 verifyFormat("{\n" 756 " if (a)\n" 757 " label:\n" 758 " f();\n" 759 " else\n" 760 " label:\n" 761 " f();\n" 762 "}", 763 AllowsMergedIfElse); 764 verifyFormat("if (a)\n" 765 " ;\n" 766 "else\n" 767 " ;", 768 AllowsMergedIfElse); 769 verifyFormat("if (a) {\n" 770 "} else {\n" 771 "}", 772 AllowsMergedIfElse); 773 verifyFormat("if (a) return;\n" 774 "else if (b) return;\n" 775 "else return;", 776 AllowsMergedIfElse); 777 verifyFormat("if (a) {\n" 778 "} else return;", 779 AllowsMergedIfElse); 780 verifyFormat("if (a) {\n" 781 "} else if (b) return;\n" 782 "else return;", 783 AllowsMergedIfElse); 784 verifyFormat("if (a) return;\n" 785 "else if (b) {\n" 786 "} else return;", 787 AllowsMergedIfElse); 788 verifyFormat("if (a)\n" 789 " if (b) return;\n" 790 " else return;", 791 AllowsMergedIfElse); 792 verifyFormat("if constexpr (a)\n" 793 " if constexpr (b) return;\n" 794 " else if constexpr (c) return;\n" 795 " else return;", 796 AllowsMergedIfElse); 797 verifyFormat("MYIF (a)\n" 798 " // comment\n" 799 " f();\n" 800 "else\n" 801 " // comment\n" 802 " f();", 803 AllowsMergedIfElse); 804 verifyFormat("{\n" 805 " MYIF (a)\n" 806 " label:\n" 807 " f();\n" 808 " else\n" 809 " label:\n" 810 " f();\n" 811 "}", 812 AllowsMergedIfElse); 813 verifyFormat("MYIF (a)\n" 814 " ;\n" 815 "else\n" 816 " ;", 817 AllowsMergedIfElse); 818 verifyFormat("MYIF (a) {\n" 819 "} else {\n" 820 "}", 821 AllowsMergedIfElse); 822 verifyFormat("MYIF (a) return;\n" 823 "else MYIF (b) return;\n" 824 "else return;", 825 AllowsMergedIfElse); 826 verifyFormat("MYIF (a) {\n" 827 "} else return;", 828 AllowsMergedIfElse); 829 verifyFormat("MYIF (a) {\n" 830 "} else MYIF (b) return;\n" 831 "else return;", 832 AllowsMergedIfElse); 833 verifyFormat("MYIF (a) return;\n" 834 "else MYIF (b) {\n" 835 "} else return;", 836 AllowsMergedIfElse); 837 verifyFormat("MYIF (a)\n" 838 " MYIF (b) return;\n" 839 " else return;", 840 AllowsMergedIfElse); 841 verifyFormat("MYIF constexpr (a)\n" 842 " MYIF constexpr (b) return;\n" 843 " else MYIF constexpr (c) return;\n" 844 " else return;", 845 AllowsMergedIfElse); 846 } 847 848 TEST_F(FormatTest, FormatIfWithoutCompoundStatementButElseWith) { 849 FormatStyle AllowsMergedIf = getLLVMStyle(); 850 AllowsMergedIf.IfMacros.push_back("MYIF"); 851 AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left; 852 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 853 FormatStyle::SIS_WithoutElse; 854 verifyFormat("if (a)\n" 855 " f();\n" 856 "else {\n" 857 " g();\n" 858 "}", 859 AllowsMergedIf); 860 verifyFormat("if (a)\n" 861 " f();\n" 862 "else\n" 863 " g();\n", 864 AllowsMergedIf); 865 866 verifyFormat("if (a) g();", AllowsMergedIf); 867 verifyFormat("if (a) {\n" 868 " g()\n" 869 "};", 870 AllowsMergedIf); 871 verifyFormat("if (a)\n" 872 " g();\n" 873 "else\n" 874 " g();", 875 AllowsMergedIf); 876 verifyFormat("if (a) {\n" 877 " g();\n" 878 "} else\n" 879 " g();", 880 AllowsMergedIf); 881 verifyFormat("if (a)\n" 882 " g();\n" 883 "else {\n" 884 " g();\n" 885 "}", 886 AllowsMergedIf); 887 verifyFormat("if (a) {\n" 888 " g();\n" 889 "} else {\n" 890 " g();\n" 891 "}", 892 AllowsMergedIf); 893 verifyFormat("if (a)\n" 894 " g();\n" 895 "else if (b)\n" 896 " g();\n" 897 "else\n" 898 " g();", 899 AllowsMergedIf); 900 verifyFormat("if (a) {\n" 901 " g();\n" 902 "} else if (b)\n" 903 " g();\n" 904 "else\n" 905 " g();", 906 AllowsMergedIf); 907 verifyFormat("if (a)\n" 908 " g();\n" 909 "else if (b) {\n" 910 " g();\n" 911 "} else\n" 912 " g();", 913 AllowsMergedIf); 914 verifyFormat("if (a)\n" 915 " g();\n" 916 "else if (b)\n" 917 " g();\n" 918 "else {\n" 919 " g();\n" 920 "}", 921 AllowsMergedIf); 922 verifyFormat("if (a)\n" 923 " g();\n" 924 "else if (b) {\n" 925 " g();\n" 926 "} else {\n" 927 " g();\n" 928 "}", 929 AllowsMergedIf); 930 verifyFormat("if (a) {\n" 931 " g();\n" 932 "} else if (b) {\n" 933 " g();\n" 934 "} else {\n" 935 " g();\n" 936 "}", 937 AllowsMergedIf); 938 verifyFormat("MYIF (a)\n" 939 " f();\n" 940 "else {\n" 941 " g();\n" 942 "}", 943 AllowsMergedIf); 944 verifyFormat("MYIF (a)\n" 945 " f();\n" 946 "else\n" 947 " g();\n", 948 AllowsMergedIf); 949 950 verifyFormat("MYIF (a) g();", AllowsMergedIf); 951 verifyFormat("MYIF (a) {\n" 952 " g()\n" 953 "};", 954 AllowsMergedIf); 955 verifyFormat("MYIF (a)\n" 956 " g();\n" 957 "else\n" 958 " g();", 959 AllowsMergedIf); 960 verifyFormat("MYIF (a) {\n" 961 " g();\n" 962 "} else\n" 963 " g();", 964 AllowsMergedIf); 965 verifyFormat("MYIF (a)\n" 966 " g();\n" 967 "else {\n" 968 " g();\n" 969 "}", 970 AllowsMergedIf); 971 verifyFormat("MYIF (a) {\n" 972 " g();\n" 973 "} else {\n" 974 " g();\n" 975 "}", 976 AllowsMergedIf); 977 verifyFormat("MYIF (a)\n" 978 " g();\n" 979 "else MYIF (b)\n" 980 " g();\n" 981 "else\n" 982 " g();", 983 AllowsMergedIf); 984 verifyFormat("MYIF (a)\n" 985 " g();\n" 986 "else if (b)\n" 987 " g();\n" 988 "else\n" 989 " g();", 990 AllowsMergedIf); 991 verifyFormat("MYIF (a) {\n" 992 " g();\n" 993 "} else MYIF (b)\n" 994 " g();\n" 995 "else\n" 996 " g();", 997 AllowsMergedIf); 998 verifyFormat("MYIF (a) {\n" 999 " g();\n" 1000 "} else if (b)\n" 1001 " g();\n" 1002 "else\n" 1003 " g();", 1004 AllowsMergedIf); 1005 verifyFormat("MYIF (a)\n" 1006 " g();\n" 1007 "else MYIF (b) {\n" 1008 " g();\n" 1009 "} else\n" 1010 " g();", 1011 AllowsMergedIf); 1012 verifyFormat("MYIF (a)\n" 1013 " g();\n" 1014 "else if (b) {\n" 1015 " g();\n" 1016 "} else\n" 1017 " g();", 1018 AllowsMergedIf); 1019 verifyFormat("MYIF (a)\n" 1020 " g();\n" 1021 "else MYIF (b)\n" 1022 " g();\n" 1023 "else {\n" 1024 " g();\n" 1025 "}", 1026 AllowsMergedIf); 1027 verifyFormat("MYIF (a)\n" 1028 " g();\n" 1029 "else if (b)\n" 1030 " g();\n" 1031 "else {\n" 1032 " g();\n" 1033 "}", 1034 AllowsMergedIf); 1035 verifyFormat("MYIF (a)\n" 1036 " g();\n" 1037 "else MYIF (b) {\n" 1038 " g();\n" 1039 "} else {\n" 1040 " g();\n" 1041 "}", 1042 AllowsMergedIf); 1043 verifyFormat("MYIF (a)\n" 1044 " g();\n" 1045 "else if (b) {\n" 1046 " g();\n" 1047 "} else {\n" 1048 " g();\n" 1049 "}", 1050 AllowsMergedIf); 1051 verifyFormat("MYIF (a) {\n" 1052 " g();\n" 1053 "} else MYIF (b) {\n" 1054 " g();\n" 1055 "} else {\n" 1056 " g();\n" 1057 "}", 1058 AllowsMergedIf); 1059 verifyFormat("MYIF (a) {\n" 1060 " g();\n" 1061 "} else if (b) {\n" 1062 " g();\n" 1063 "} else {\n" 1064 " g();\n" 1065 "}", 1066 AllowsMergedIf); 1067 1068 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 1069 FormatStyle::SIS_OnlyFirstIf; 1070 1071 verifyFormat("if (a) f();\n" 1072 "else {\n" 1073 " g();\n" 1074 "}", 1075 AllowsMergedIf); 1076 verifyFormat("if (a) f();\n" 1077 "else {\n" 1078 " if (a) f();\n" 1079 " else {\n" 1080 " g();\n" 1081 " }\n" 1082 " g();\n" 1083 "}", 1084 AllowsMergedIf); 1085 1086 verifyFormat("if (a) g();", AllowsMergedIf); 1087 verifyFormat("if (a) {\n" 1088 " g()\n" 1089 "};", 1090 AllowsMergedIf); 1091 verifyFormat("if (a) g();\n" 1092 "else\n" 1093 " g();", 1094 AllowsMergedIf); 1095 verifyFormat("if (a) {\n" 1096 " g();\n" 1097 "} else\n" 1098 " g();", 1099 AllowsMergedIf); 1100 verifyFormat("if (a) g();\n" 1101 "else {\n" 1102 " g();\n" 1103 "}", 1104 AllowsMergedIf); 1105 verifyFormat("if (a) {\n" 1106 " g();\n" 1107 "} else {\n" 1108 " g();\n" 1109 "}", 1110 AllowsMergedIf); 1111 verifyFormat("if (a) g();\n" 1112 "else if (b)\n" 1113 " g();\n" 1114 "else\n" 1115 " g();", 1116 AllowsMergedIf); 1117 verifyFormat("if (a) {\n" 1118 " g();\n" 1119 "} else if (b)\n" 1120 " g();\n" 1121 "else\n" 1122 " g();", 1123 AllowsMergedIf); 1124 verifyFormat("if (a) g();\n" 1125 "else if (b) {\n" 1126 " g();\n" 1127 "} else\n" 1128 " g();", 1129 AllowsMergedIf); 1130 verifyFormat("if (a) g();\n" 1131 "else if (b)\n" 1132 " g();\n" 1133 "else {\n" 1134 " g();\n" 1135 "}", 1136 AllowsMergedIf); 1137 verifyFormat("if (a) g();\n" 1138 "else if (b) {\n" 1139 " g();\n" 1140 "} else {\n" 1141 " g();\n" 1142 "}", 1143 AllowsMergedIf); 1144 verifyFormat("if (a) {\n" 1145 " g();\n" 1146 "} else if (b) {\n" 1147 " g();\n" 1148 "} else {\n" 1149 " g();\n" 1150 "}", 1151 AllowsMergedIf); 1152 verifyFormat("MYIF (a) f();\n" 1153 "else {\n" 1154 " g();\n" 1155 "}", 1156 AllowsMergedIf); 1157 verifyFormat("MYIF (a) f();\n" 1158 "else {\n" 1159 " if (a) f();\n" 1160 " else {\n" 1161 " g();\n" 1162 " }\n" 1163 " g();\n" 1164 "}", 1165 AllowsMergedIf); 1166 1167 verifyFormat("MYIF (a) g();", AllowsMergedIf); 1168 verifyFormat("MYIF (a) {\n" 1169 " g()\n" 1170 "};", 1171 AllowsMergedIf); 1172 verifyFormat("MYIF (a) g();\n" 1173 "else\n" 1174 " g();", 1175 AllowsMergedIf); 1176 verifyFormat("MYIF (a) {\n" 1177 " g();\n" 1178 "} else\n" 1179 " g();", 1180 AllowsMergedIf); 1181 verifyFormat("MYIF (a) g();\n" 1182 "else {\n" 1183 " g();\n" 1184 "}", 1185 AllowsMergedIf); 1186 verifyFormat("MYIF (a) {\n" 1187 " g();\n" 1188 "} else {\n" 1189 " g();\n" 1190 "}", 1191 AllowsMergedIf); 1192 verifyFormat("MYIF (a) g();\n" 1193 "else MYIF (b)\n" 1194 " g();\n" 1195 "else\n" 1196 " g();", 1197 AllowsMergedIf); 1198 verifyFormat("MYIF (a) g();\n" 1199 "else if (b)\n" 1200 " g();\n" 1201 "else\n" 1202 " g();", 1203 AllowsMergedIf); 1204 verifyFormat("MYIF (a) {\n" 1205 " g();\n" 1206 "} else MYIF (b)\n" 1207 " g();\n" 1208 "else\n" 1209 " g();", 1210 AllowsMergedIf); 1211 verifyFormat("MYIF (a) {\n" 1212 " g();\n" 1213 "} else if (b)\n" 1214 " g();\n" 1215 "else\n" 1216 " g();", 1217 AllowsMergedIf); 1218 verifyFormat("MYIF (a) g();\n" 1219 "else MYIF (b) {\n" 1220 " g();\n" 1221 "} else\n" 1222 " g();", 1223 AllowsMergedIf); 1224 verifyFormat("MYIF (a) g();\n" 1225 "else if (b) {\n" 1226 " g();\n" 1227 "} else\n" 1228 " g();", 1229 AllowsMergedIf); 1230 verifyFormat("MYIF (a) g();\n" 1231 "else MYIF (b)\n" 1232 " g();\n" 1233 "else {\n" 1234 " g();\n" 1235 "}", 1236 AllowsMergedIf); 1237 verifyFormat("MYIF (a) g();\n" 1238 "else if (b)\n" 1239 " g();\n" 1240 "else {\n" 1241 " g();\n" 1242 "}", 1243 AllowsMergedIf); 1244 verifyFormat("MYIF (a) g();\n" 1245 "else MYIF (b) {\n" 1246 " g();\n" 1247 "} else {\n" 1248 " g();\n" 1249 "}", 1250 AllowsMergedIf); 1251 verifyFormat("MYIF (a) g();\n" 1252 "else if (b) {\n" 1253 " g();\n" 1254 "} else {\n" 1255 " g();\n" 1256 "}", 1257 AllowsMergedIf); 1258 verifyFormat("MYIF (a) {\n" 1259 " g();\n" 1260 "} else MYIF (b) {\n" 1261 " g();\n" 1262 "} else {\n" 1263 " g();\n" 1264 "}", 1265 AllowsMergedIf); 1266 verifyFormat("MYIF (a) {\n" 1267 " g();\n" 1268 "} else if (b) {\n" 1269 " g();\n" 1270 "} else {\n" 1271 " g();\n" 1272 "}", 1273 AllowsMergedIf); 1274 1275 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 1276 FormatStyle::SIS_AllIfsAndElse; 1277 1278 verifyFormat("if (a) f();\n" 1279 "else {\n" 1280 " g();\n" 1281 "}", 1282 AllowsMergedIf); 1283 verifyFormat("if (a) f();\n" 1284 "else {\n" 1285 " if (a) f();\n" 1286 " else {\n" 1287 " g();\n" 1288 " }\n" 1289 " g();\n" 1290 "}", 1291 AllowsMergedIf); 1292 1293 verifyFormat("if (a) g();", AllowsMergedIf); 1294 verifyFormat("if (a) {\n" 1295 " g()\n" 1296 "};", 1297 AllowsMergedIf); 1298 verifyFormat("if (a) g();\n" 1299 "else g();", 1300 AllowsMergedIf); 1301 verifyFormat("if (a) {\n" 1302 " g();\n" 1303 "} else g();", 1304 AllowsMergedIf); 1305 verifyFormat("if (a) g();\n" 1306 "else {\n" 1307 " g();\n" 1308 "}", 1309 AllowsMergedIf); 1310 verifyFormat("if (a) {\n" 1311 " g();\n" 1312 "} else {\n" 1313 " g();\n" 1314 "}", 1315 AllowsMergedIf); 1316 verifyFormat("if (a) g();\n" 1317 "else if (b) g();\n" 1318 "else g();", 1319 AllowsMergedIf); 1320 verifyFormat("if (a) {\n" 1321 " g();\n" 1322 "} else if (b) g();\n" 1323 "else g();", 1324 AllowsMergedIf); 1325 verifyFormat("if (a) g();\n" 1326 "else if (b) {\n" 1327 " g();\n" 1328 "} else g();", 1329 AllowsMergedIf); 1330 verifyFormat("if (a) g();\n" 1331 "else if (b) g();\n" 1332 "else {\n" 1333 " g();\n" 1334 "}", 1335 AllowsMergedIf); 1336 verifyFormat("if (a) g();\n" 1337 "else if (b) {\n" 1338 " g();\n" 1339 "} else {\n" 1340 " g();\n" 1341 "}", 1342 AllowsMergedIf); 1343 verifyFormat("if (a) {\n" 1344 " g();\n" 1345 "} else if (b) {\n" 1346 " g();\n" 1347 "} else {\n" 1348 " g();\n" 1349 "}", 1350 AllowsMergedIf); 1351 verifyFormat("MYIF (a) f();\n" 1352 "else {\n" 1353 " g();\n" 1354 "}", 1355 AllowsMergedIf); 1356 verifyFormat("MYIF (a) f();\n" 1357 "else {\n" 1358 " if (a) f();\n" 1359 " else {\n" 1360 " g();\n" 1361 " }\n" 1362 " g();\n" 1363 "}", 1364 AllowsMergedIf); 1365 1366 verifyFormat("MYIF (a) g();", AllowsMergedIf); 1367 verifyFormat("MYIF (a) {\n" 1368 " g()\n" 1369 "};", 1370 AllowsMergedIf); 1371 verifyFormat("MYIF (a) g();\n" 1372 "else g();", 1373 AllowsMergedIf); 1374 verifyFormat("MYIF (a) {\n" 1375 " g();\n" 1376 "} else g();", 1377 AllowsMergedIf); 1378 verifyFormat("MYIF (a) g();\n" 1379 "else {\n" 1380 " g();\n" 1381 "}", 1382 AllowsMergedIf); 1383 verifyFormat("MYIF (a) {\n" 1384 " g();\n" 1385 "} else {\n" 1386 " g();\n" 1387 "}", 1388 AllowsMergedIf); 1389 verifyFormat("MYIF (a) g();\n" 1390 "else MYIF (b) g();\n" 1391 "else g();", 1392 AllowsMergedIf); 1393 verifyFormat("MYIF (a) g();\n" 1394 "else if (b) g();\n" 1395 "else g();", 1396 AllowsMergedIf); 1397 verifyFormat("MYIF (a) {\n" 1398 " g();\n" 1399 "} else MYIF (b) g();\n" 1400 "else g();", 1401 AllowsMergedIf); 1402 verifyFormat("MYIF (a) {\n" 1403 " g();\n" 1404 "} else if (b) g();\n" 1405 "else g();", 1406 AllowsMergedIf); 1407 verifyFormat("MYIF (a) g();\n" 1408 "else MYIF (b) {\n" 1409 " g();\n" 1410 "} else g();", 1411 AllowsMergedIf); 1412 verifyFormat("MYIF (a) g();\n" 1413 "else if (b) {\n" 1414 " g();\n" 1415 "} else g();", 1416 AllowsMergedIf); 1417 verifyFormat("MYIF (a) g();\n" 1418 "else MYIF (b) g();\n" 1419 "else {\n" 1420 " g();\n" 1421 "}", 1422 AllowsMergedIf); 1423 verifyFormat("MYIF (a) g();\n" 1424 "else if (b) g();\n" 1425 "else {\n" 1426 " g();\n" 1427 "}", 1428 AllowsMergedIf); 1429 verifyFormat("MYIF (a) g();\n" 1430 "else MYIF (b) {\n" 1431 " g();\n" 1432 "} else {\n" 1433 " g();\n" 1434 "}", 1435 AllowsMergedIf); 1436 verifyFormat("MYIF (a) g();\n" 1437 "else if (b) {\n" 1438 " g();\n" 1439 "} else {\n" 1440 " g();\n" 1441 "}", 1442 AllowsMergedIf); 1443 verifyFormat("MYIF (a) {\n" 1444 " g();\n" 1445 "} else MYIF (b) {\n" 1446 " g();\n" 1447 "} else {\n" 1448 " g();\n" 1449 "}", 1450 AllowsMergedIf); 1451 verifyFormat("MYIF (a) {\n" 1452 " g();\n" 1453 "} else if (b) {\n" 1454 " g();\n" 1455 "} else {\n" 1456 " g();\n" 1457 "}", 1458 AllowsMergedIf); 1459 } 1460 1461 TEST_F(FormatTest, FormatLoopsWithoutCompoundStatement) { 1462 FormatStyle AllowsMergedLoops = getLLVMStyle(); 1463 AllowsMergedLoops.AllowShortLoopsOnASingleLine = true; 1464 verifyFormat("while (true) continue;", AllowsMergedLoops); 1465 verifyFormat("for (;;) continue;", AllowsMergedLoops); 1466 verifyFormat("for (int &v : vec) v *= 2;", AllowsMergedLoops); 1467 verifyFormat("BOOST_FOREACH (int &v, vec) v *= 2;", AllowsMergedLoops); 1468 verifyFormat("while (true)\n" 1469 " ;", 1470 AllowsMergedLoops); 1471 verifyFormat("for (;;)\n" 1472 " ;", 1473 AllowsMergedLoops); 1474 verifyFormat("for (;;)\n" 1475 " for (;;) continue;", 1476 AllowsMergedLoops); 1477 verifyFormat("for (;;)\n" 1478 " while (true) continue;", 1479 AllowsMergedLoops); 1480 verifyFormat("while (true)\n" 1481 " for (;;) continue;", 1482 AllowsMergedLoops); 1483 verifyFormat("BOOST_FOREACH (int &v, vec)\n" 1484 " for (;;) continue;", 1485 AllowsMergedLoops); 1486 verifyFormat("for (;;)\n" 1487 " BOOST_FOREACH (int &v, vec) continue;", 1488 AllowsMergedLoops); 1489 verifyFormat("for (;;) // Can't merge this\n" 1490 " continue;", 1491 AllowsMergedLoops); 1492 verifyFormat("for (;;) /* still don't merge */\n" 1493 " continue;", 1494 AllowsMergedLoops); 1495 verifyFormat("do a++;\n" 1496 "while (true);", 1497 AllowsMergedLoops); 1498 verifyFormat("do /* Don't merge */\n" 1499 " a++;\n" 1500 "while (true);", 1501 AllowsMergedLoops); 1502 verifyFormat("do // Don't merge\n" 1503 " a++;\n" 1504 "while (true);", 1505 AllowsMergedLoops); 1506 verifyFormat("do\n" 1507 " // Don't merge\n" 1508 " a++;\n" 1509 "while (true);", 1510 AllowsMergedLoops); 1511 // Without braces labels are interpreted differently. 1512 verifyFormat("{\n" 1513 " do\n" 1514 " label:\n" 1515 " a++;\n" 1516 " while (true);\n" 1517 "}", 1518 AllowsMergedLoops); 1519 } 1520 1521 TEST_F(FormatTest, FormatShortBracedStatements) { 1522 FormatStyle AllowSimpleBracedStatements = getLLVMStyle(); 1523 AllowSimpleBracedStatements.IfMacros.push_back("MYIF"); 1524 // Where line-lengths matter, a 2-letter synonym that maintains line length. 1525 // Not IF to avoid any confusion that IF is somehow special. 1526 AllowSimpleBracedStatements.IfMacros.push_back("FI"); 1527 AllowSimpleBracedStatements.ColumnLimit = 40; 1528 AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine = 1529 FormatStyle::SBS_Always; 1530 1531 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1532 FormatStyle::SIS_WithoutElse; 1533 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true; 1534 1535 AllowSimpleBracedStatements.BreakBeforeBraces = FormatStyle::BS_Custom; 1536 AllowSimpleBracedStatements.BraceWrapping.AfterFunction = true; 1537 AllowSimpleBracedStatements.BraceWrapping.SplitEmptyRecord = false; 1538 1539 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1540 verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements); 1541 verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1542 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1543 verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements); 1544 verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1545 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1546 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1547 verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements); 1548 verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements); 1549 verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1550 verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements); 1551 verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements); 1552 verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1553 verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements); 1554 verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements); 1555 verifyFormat("if (true) { fffffffffffffffffffffff(); }", 1556 AllowSimpleBracedStatements); 1557 verifyFormat("if (true) {\n" 1558 " ffffffffffffffffffffffff();\n" 1559 "}", 1560 AllowSimpleBracedStatements); 1561 verifyFormat("if (true) {\n" 1562 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1563 "}", 1564 AllowSimpleBracedStatements); 1565 verifyFormat("if (true) { //\n" 1566 " f();\n" 1567 "}", 1568 AllowSimpleBracedStatements); 1569 verifyFormat("if (true) {\n" 1570 " f();\n" 1571 " f();\n" 1572 "}", 1573 AllowSimpleBracedStatements); 1574 verifyFormat("if (true) {\n" 1575 " f();\n" 1576 "} else {\n" 1577 " f();\n" 1578 "}", 1579 AllowSimpleBracedStatements); 1580 verifyFormat("FI (true) { fffffffffffffffffffffff(); }", 1581 AllowSimpleBracedStatements); 1582 verifyFormat("MYIF (true) {\n" 1583 " ffffffffffffffffffffffff();\n" 1584 "}", 1585 AllowSimpleBracedStatements); 1586 verifyFormat("MYIF (true) {\n" 1587 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1588 "}", 1589 AllowSimpleBracedStatements); 1590 verifyFormat("MYIF (true) { //\n" 1591 " f();\n" 1592 "}", 1593 AllowSimpleBracedStatements); 1594 verifyFormat("MYIF (true) {\n" 1595 " f();\n" 1596 " f();\n" 1597 "}", 1598 AllowSimpleBracedStatements); 1599 verifyFormat("MYIF (true) {\n" 1600 " f();\n" 1601 "} else {\n" 1602 " f();\n" 1603 "}", 1604 AllowSimpleBracedStatements); 1605 1606 verifyFormat("struct A2 {\n" 1607 " int X;\n" 1608 "};", 1609 AllowSimpleBracedStatements); 1610 verifyFormat("typedef struct A2 {\n" 1611 " int X;\n" 1612 "} A2_t;", 1613 AllowSimpleBracedStatements); 1614 verifyFormat("template <int> struct A2 {\n" 1615 " struct B {};\n" 1616 "};", 1617 AllowSimpleBracedStatements); 1618 1619 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1620 FormatStyle::SIS_Never; 1621 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1622 verifyFormat("if (true) {\n" 1623 " f();\n" 1624 "}", 1625 AllowSimpleBracedStatements); 1626 verifyFormat("if (true) {\n" 1627 " f();\n" 1628 "} else {\n" 1629 " f();\n" 1630 "}", 1631 AllowSimpleBracedStatements); 1632 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1633 verifyFormat("MYIF (true) {\n" 1634 " f();\n" 1635 "}", 1636 AllowSimpleBracedStatements); 1637 verifyFormat("MYIF (true) {\n" 1638 " f();\n" 1639 "} else {\n" 1640 " f();\n" 1641 "}", 1642 AllowSimpleBracedStatements); 1643 1644 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false; 1645 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1646 verifyFormat("while (true) {\n" 1647 " f();\n" 1648 "}", 1649 AllowSimpleBracedStatements); 1650 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1651 verifyFormat("for (;;) {\n" 1652 " f();\n" 1653 "}", 1654 AllowSimpleBracedStatements); 1655 verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements); 1656 verifyFormat("BOOST_FOREACH (int v, vec) {\n" 1657 " f();\n" 1658 "}", 1659 AllowSimpleBracedStatements); 1660 1661 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1662 FormatStyle::SIS_WithoutElse; 1663 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true; 1664 AllowSimpleBracedStatements.BraceWrapping.AfterControlStatement = 1665 FormatStyle::BWACS_Always; 1666 1667 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1668 verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements); 1669 verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1670 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1671 verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements); 1672 verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1673 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1674 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1675 verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements); 1676 verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements); 1677 verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1678 verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements); 1679 verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements); 1680 verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1681 verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements); 1682 verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements); 1683 verifyFormat("if (true) { fffffffffffffffffffffff(); }", 1684 AllowSimpleBracedStatements); 1685 verifyFormat("if (true)\n" 1686 "{\n" 1687 " ffffffffffffffffffffffff();\n" 1688 "}", 1689 AllowSimpleBracedStatements); 1690 verifyFormat("if (true)\n" 1691 "{\n" 1692 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1693 "}", 1694 AllowSimpleBracedStatements); 1695 verifyFormat("if (true)\n" 1696 "{ //\n" 1697 " f();\n" 1698 "}", 1699 AllowSimpleBracedStatements); 1700 verifyFormat("if (true)\n" 1701 "{\n" 1702 " f();\n" 1703 " f();\n" 1704 "}", 1705 AllowSimpleBracedStatements); 1706 verifyFormat("if (true)\n" 1707 "{\n" 1708 " f();\n" 1709 "} else\n" 1710 "{\n" 1711 " f();\n" 1712 "}", 1713 AllowSimpleBracedStatements); 1714 verifyFormat("FI (true) { fffffffffffffffffffffff(); }", 1715 AllowSimpleBracedStatements); 1716 verifyFormat("MYIF (true)\n" 1717 "{\n" 1718 " ffffffffffffffffffffffff();\n" 1719 "}", 1720 AllowSimpleBracedStatements); 1721 verifyFormat("MYIF (true)\n" 1722 "{\n" 1723 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1724 "}", 1725 AllowSimpleBracedStatements); 1726 verifyFormat("MYIF (true)\n" 1727 "{ //\n" 1728 " f();\n" 1729 "}", 1730 AllowSimpleBracedStatements); 1731 verifyFormat("MYIF (true)\n" 1732 "{\n" 1733 " f();\n" 1734 " f();\n" 1735 "}", 1736 AllowSimpleBracedStatements); 1737 verifyFormat("MYIF (true)\n" 1738 "{\n" 1739 " f();\n" 1740 "} else\n" 1741 "{\n" 1742 " f();\n" 1743 "}", 1744 AllowSimpleBracedStatements); 1745 1746 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1747 FormatStyle::SIS_Never; 1748 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1749 verifyFormat("if (true)\n" 1750 "{\n" 1751 " f();\n" 1752 "}", 1753 AllowSimpleBracedStatements); 1754 verifyFormat("if (true)\n" 1755 "{\n" 1756 " f();\n" 1757 "} else\n" 1758 "{\n" 1759 " f();\n" 1760 "}", 1761 AllowSimpleBracedStatements); 1762 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1763 verifyFormat("MYIF (true)\n" 1764 "{\n" 1765 " f();\n" 1766 "}", 1767 AllowSimpleBracedStatements); 1768 verifyFormat("MYIF (true)\n" 1769 "{\n" 1770 " f();\n" 1771 "} else\n" 1772 "{\n" 1773 " f();\n" 1774 "}", 1775 AllowSimpleBracedStatements); 1776 1777 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false; 1778 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1779 verifyFormat("while (true)\n" 1780 "{\n" 1781 " f();\n" 1782 "}", 1783 AllowSimpleBracedStatements); 1784 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1785 verifyFormat("for (;;)\n" 1786 "{\n" 1787 " f();\n" 1788 "}", 1789 AllowSimpleBracedStatements); 1790 verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements); 1791 verifyFormat("BOOST_FOREACH (int v, vec)\n" 1792 "{\n" 1793 " f();\n" 1794 "}", 1795 AllowSimpleBracedStatements); 1796 } 1797 1798 TEST_F(FormatTest, UnderstandsMacros) { 1799 verifyFormat("#define A (parentheses)"); 1800 verifyFormat("/* comment */ #define A (parentheses)"); 1801 verifyFormat("/* comment */ /* another comment */ #define A (parentheses)"); 1802 // Even the partial code should never be merged. 1803 EXPECT_EQ("/* comment */ #define A (parentheses)\n" 1804 "#", 1805 format("/* comment */ #define A (parentheses)\n" 1806 "#")); 1807 verifyFormat("/* comment */ #define A (parentheses)\n" 1808 "#\n"); 1809 verifyFormat("/* comment */ #define A (parentheses)\n" 1810 "#define B (parentheses)"); 1811 verifyFormat("#define true ((int)1)"); 1812 verifyFormat("#define and(x)"); 1813 verifyFormat("#define if(x) x"); 1814 verifyFormat("#define return(x) (x)"); 1815 verifyFormat("#define while(x) for (; x;)"); 1816 verifyFormat("#define xor(x) (^(x))"); 1817 verifyFormat("#define __except(x)"); 1818 verifyFormat("#define __try(x)"); 1819 1820 FormatStyle Style = getLLVMStyle(); 1821 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 1822 Style.BraceWrapping.AfterFunction = true; 1823 // Test that a macro definition never gets merged with the following 1824 // definition. 1825 // FIXME: The AAA macro definition probably should not be split into 3 lines. 1826 verifyFormat("#define AAA " 1827 " \\\n" 1828 " N " 1829 " \\\n" 1830 " {\n" 1831 "#define BBB }\n", 1832 Style); 1833 // verifyFormat("#define AAA N { //\n", Style); 1834 } 1835 1836 TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) { 1837 FormatStyle Style = getLLVMStyleWithColumns(60); 1838 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 1839 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse; 1840 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 1841 EXPECT_EQ("#define A \\\n" 1842 " if (HANDLEwernufrnuLwrmviferuvnierv) \\\n" 1843 " { \\\n" 1844 " RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n" 1845 " }\n" 1846 "X;", 1847 format("#define A \\\n" 1848 " if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n" 1849 " RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n" 1850 " }\n" 1851 "X;", 1852 Style)); 1853 } 1854 1855 TEST_F(FormatTest, ParseIfElse) { 1856 verifyFormat("if (true)\n" 1857 " if (true)\n" 1858 " if (true)\n" 1859 " f();\n" 1860 " else\n" 1861 " g();\n" 1862 " else\n" 1863 " h();\n" 1864 "else\n" 1865 " i();"); 1866 verifyFormat("if (true)\n" 1867 " if (true)\n" 1868 " if (true) {\n" 1869 " if (true)\n" 1870 " f();\n" 1871 " } else {\n" 1872 " g();\n" 1873 " }\n" 1874 " else\n" 1875 " h();\n" 1876 "else {\n" 1877 " i();\n" 1878 "}"); 1879 verifyFormat("if (true)\n" 1880 " if constexpr (true)\n" 1881 " if (true) {\n" 1882 " if constexpr (true)\n" 1883 " f();\n" 1884 " } else {\n" 1885 " g();\n" 1886 " }\n" 1887 " else\n" 1888 " h();\n" 1889 "else {\n" 1890 " i();\n" 1891 "}"); 1892 verifyFormat("if (true)\n" 1893 " if CONSTEXPR (true)\n" 1894 " if (true) {\n" 1895 " if CONSTEXPR (true)\n" 1896 " f();\n" 1897 " } else {\n" 1898 " g();\n" 1899 " }\n" 1900 " else\n" 1901 " h();\n" 1902 "else {\n" 1903 " i();\n" 1904 "}"); 1905 verifyFormat("void f() {\n" 1906 " if (a) {\n" 1907 " } else {\n" 1908 " }\n" 1909 "}"); 1910 } 1911 1912 TEST_F(FormatTest, ElseIf) { 1913 verifyFormat("if (a) {\n} else if (b) {\n}"); 1914 verifyFormat("if (a)\n" 1915 " f();\n" 1916 "else if (b)\n" 1917 " g();\n" 1918 "else\n" 1919 " h();"); 1920 verifyFormat("if (a)\n" 1921 " f();\n" 1922 "else // comment\n" 1923 " if (b) {\n" 1924 " g();\n" 1925 " h();\n" 1926 " }"); 1927 verifyFormat("if constexpr (a)\n" 1928 " f();\n" 1929 "else if constexpr (b)\n" 1930 " g();\n" 1931 "else\n" 1932 " h();"); 1933 verifyFormat("if CONSTEXPR (a)\n" 1934 " f();\n" 1935 "else if CONSTEXPR (b)\n" 1936 " g();\n" 1937 "else\n" 1938 " h();"); 1939 verifyFormat("if (a) {\n" 1940 " f();\n" 1941 "}\n" 1942 "// or else ..\n" 1943 "else {\n" 1944 " g()\n" 1945 "}"); 1946 1947 verifyFormat("if (a) {\n" 1948 "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 1949 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 1950 "}"); 1951 verifyFormat("if (a) {\n" 1952 "} else if constexpr (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 1953 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 1954 "}"); 1955 verifyFormat("if (a) {\n" 1956 "} else if CONSTEXPR (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 1957 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 1958 "}"); 1959 verifyFormat("if (a) {\n" 1960 "} else if (\n" 1961 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 1962 "}", 1963 getLLVMStyleWithColumns(62)); 1964 verifyFormat("if (a) {\n" 1965 "} else if constexpr (\n" 1966 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 1967 "}", 1968 getLLVMStyleWithColumns(62)); 1969 verifyFormat("if (a) {\n" 1970 "} else if CONSTEXPR (\n" 1971 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 1972 "}", 1973 getLLVMStyleWithColumns(62)); 1974 } 1975 1976 TEST_F(FormatTest, SeparatePointerReferenceAlignment) { 1977 FormatStyle Style = getLLVMStyle(); 1978 // Check first the default LLVM style 1979 // Style.PointerAlignment = FormatStyle::PAS_Right; 1980 // Style.ReferenceAlignment = FormatStyle::RAS_Pointer; 1981 verifyFormat("int *f1(int *a, int &b, int &&c);", Style); 1982 verifyFormat("int &f2(int &&c, int *a, int &b);", Style); 1983 verifyFormat("int &&f3(int &b, int &&c, int *a);", Style); 1984 verifyFormat("int *f1(int &a) const &;", Style); 1985 verifyFormat("int *f1(int &a) const & = 0;", Style); 1986 verifyFormat("int *a = f1();", Style); 1987 verifyFormat("int &b = f2();", Style); 1988 verifyFormat("int &&c = f3();", Style); 1989 verifyFormat("for (auto a = 0, b = 0; const auto &c : {1, 2, 3})", Style); 1990 verifyFormat("for (auto a = 0, b = 0; const int &c : {1, 2, 3})", Style); 1991 verifyFormat("for (auto a = 0, b = 0; const Foo &c : {1, 2, 3})", Style); 1992 verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style); 1993 verifyFormat("for (int a = 0, b = 0; const auto &c : {1, 2, 3})", Style); 1994 verifyFormat("for (int a = 0, b = 0; const int &c : {1, 2, 3})", Style); 1995 verifyFormat("for (int a = 0, b = 0; const Foo &c : {1, 2, 3})", Style); 1996 verifyFormat("for (int a = 0, b++; const auto &c : {1, 2, 3})", Style); 1997 verifyFormat("for (int a = 0, b++; const int &c : {1, 2, 3})", Style); 1998 verifyFormat("for (int a = 0, b++; const Foo &c : {1, 2, 3})", Style); 1999 verifyFormat("for (auto x = 0; auto &c : {1, 2, 3})", Style); 2000 verifyFormat("for (auto x = 0; int &c : {1, 2, 3})", Style); 2001 verifyFormat("for (int x = 0; auto &c : {1, 2, 3})", Style); 2002 verifyFormat("for (int x = 0; int &c : {1, 2, 3})", Style); 2003 verifyFormat("for (f(); auto &c : {1, 2, 3})", Style); 2004 verifyFormat("for (f(); int &c : {1, 2, 3})", Style); 2005 2006 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 2007 verifyFormat("Const unsigned int *c;\n" 2008 "const unsigned int *d;\n" 2009 "Const unsigned int &e;\n" 2010 "const unsigned int &f;\n" 2011 "const unsigned &&g;\n" 2012 "Const unsigned h;", 2013 Style); 2014 2015 Style.PointerAlignment = FormatStyle::PAS_Left; 2016 Style.ReferenceAlignment = FormatStyle::RAS_Pointer; 2017 verifyFormat("int* f1(int* a, int& b, int&& c);", Style); 2018 verifyFormat("int& f2(int&& c, int* a, int& b);", Style); 2019 verifyFormat("int&& f3(int& b, int&& c, int* a);", Style); 2020 verifyFormat("int* f1(int& a) const& = 0;", Style); 2021 verifyFormat("int* a = f1();", Style); 2022 verifyFormat("int& b = f2();", Style); 2023 verifyFormat("int&& c = f3();", Style); 2024 verifyFormat("for (auto a = 0, b = 0; const auto& c : {1, 2, 3})", Style); 2025 verifyFormat("for (auto a = 0, b = 0; const int& c : {1, 2, 3})", Style); 2026 verifyFormat("for (auto a = 0, b = 0; const Foo& c : {1, 2, 3})", Style); 2027 verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style); 2028 verifyFormat("for (int a = 0, b = 0; const auto& c : {1, 2, 3})", Style); 2029 verifyFormat("for (int a = 0, b = 0; const int& c : {1, 2, 3})", Style); 2030 verifyFormat("for (int a = 0, b = 0; const Foo& c : {1, 2, 3})", Style); 2031 verifyFormat("for (int a = 0, b = 0; const Foo* c : {1, 2, 3})", Style); 2032 verifyFormat("for (int a = 0, b++; const auto& c : {1, 2, 3})", Style); 2033 verifyFormat("for (int a = 0, b++; const int& c : {1, 2, 3})", Style); 2034 verifyFormat("for (int a = 0, b++; const Foo& c : {1, 2, 3})", Style); 2035 verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style); 2036 verifyFormat("for (auto x = 0; auto& c : {1, 2, 3})", Style); 2037 verifyFormat("for (auto x = 0; int& c : {1, 2, 3})", Style); 2038 verifyFormat("for (int x = 0; auto& c : {1, 2, 3})", Style); 2039 verifyFormat("for (int x = 0; int& c : {1, 2, 3})", Style); 2040 verifyFormat("for (f(); auto& c : {1, 2, 3})", Style); 2041 verifyFormat("for (f(); int& c : {1, 2, 3})", Style); 2042 2043 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 2044 verifyFormat("Const unsigned int* c;\n" 2045 "const unsigned int* d;\n" 2046 "Const unsigned int& e;\n" 2047 "const unsigned int& f;\n" 2048 "const unsigned&& g;\n" 2049 "Const unsigned h;", 2050 Style); 2051 2052 Style.PointerAlignment = FormatStyle::PAS_Right; 2053 Style.ReferenceAlignment = FormatStyle::RAS_Left; 2054 verifyFormat("int *f1(int *a, int& b, int&& c);", Style); 2055 verifyFormat("int& f2(int&& c, int *a, int& b);", Style); 2056 verifyFormat("int&& f3(int& b, int&& c, int *a);", Style); 2057 verifyFormat("int *a = f1();", Style); 2058 verifyFormat("int& b = f2();", Style); 2059 verifyFormat("int&& c = f3();", Style); 2060 verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style); 2061 verifyFormat("for (int a = 0, b = 0; const Foo *c : {1, 2, 3})", Style); 2062 verifyFormat("for (int a = 0, b++; const Foo *c : {1, 2, 3})", Style); 2063 2064 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 2065 verifyFormat("Const unsigned int *c;\n" 2066 "const unsigned int *d;\n" 2067 "Const unsigned int& e;\n" 2068 "const unsigned int& f;\n" 2069 "const unsigned g;\n" 2070 "Const unsigned h;", 2071 Style); 2072 2073 Style.PointerAlignment = FormatStyle::PAS_Left; 2074 Style.ReferenceAlignment = FormatStyle::RAS_Middle; 2075 verifyFormat("int* f1(int* a, int & b, int && c);", Style); 2076 verifyFormat("int & f2(int && c, int* a, int & b);", Style); 2077 verifyFormat("int && f3(int & b, int && c, int* a);", Style); 2078 verifyFormat("int* a = f1();", Style); 2079 verifyFormat("int & b = f2();", Style); 2080 verifyFormat("int && c = f3();", Style); 2081 verifyFormat("for (auto a = 0, b = 0; const auto & c : {1, 2, 3})", Style); 2082 verifyFormat("for (auto a = 0, b = 0; const int & c : {1, 2, 3})", Style); 2083 verifyFormat("for (auto a = 0, b = 0; const Foo & c : {1, 2, 3})", Style); 2084 verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style); 2085 verifyFormat("for (int a = 0, b++; const auto & c : {1, 2, 3})", Style); 2086 verifyFormat("for (int a = 0, b++; const int & c : {1, 2, 3})", Style); 2087 verifyFormat("for (int a = 0, b++; const Foo & c : {1, 2, 3})", Style); 2088 verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style); 2089 verifyFormat("for (auto x = 0; auto & c : {1, 2, 3})", Style); 2090 verifyFormat("for (auto x = 0; int & c : {1, 2, 3})", Style); 2091 verifyFormat("for (int x = 0; auto & c : {1, 2, 3})", Style); 2092 verifyFormat("for (int x = 0; int & c : {1, 2, 3})", Style); 2093 verifyFormat("for (f(); auto & c : {1, 2, 3})", Style); 2094 verifyFormat("for (f(); int & c : {1, 2, 3})", Style); 2095 2096 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 2097 verifyFormat("Const unsigned int* c;\n" 2098 "const unsigned int* d;\n" 2099 "Const unsigned int & e;\n" 2100 "const unsigned int & f;\n" 2101 "const unsigned && g;\n" 2102 "Const unsigned h;", 2103 Style); 2104 2105 Style.PointerAlignment = FormatStyle::PAS_Middle; 2106 Style.ReferenceAlignment = FormatStyle::RAS_Right; 2107 verifyFormat("int * f1(int * a, int &b, int &&c);", Style); 2108 verifyFormat("int &f2(int &&c, int * a, int &b);", Style); 2109 verifyFormat("int &&f3(int &b, int &&c, int * a);", Style); 2110 verifyFormat("int * a = f1();", Style); 2111 verifyFormat("int &b = f2();", Style); 2112 verifyFormat("int &&c = f3();", Style); 2113 verifyFormat("for (auto a = 0, b = 0; const Foo * c : {1, 2, 3})", Style); 2114 verifyFormat("for (int a = 0, b = 0; const Foo * c : {1, 2, 3})", Style); 2115 verifyFormat("for (int a = 0, b++; const Foo * c : {1, 2, 3})", Style); 2116 2117 // FIXME: we don't handle this yet, so output may be arbitrary until it's 2118 // specifically handled 2119 // verifyFormat("int Add2(BTree * &Root, char * szToAdd)", Style); 2120 } 2121 2122 TEST_F(FormatTest, FormatsForLoop) { 2123 verifyFormat( 2124 "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n" 2125 " ++VeryVeryLongLoopVariable)\n" 2126 " ;"); 2127 verifyFormat("for (;;)\n" 2128 " f();"); 2129 verifyFormat("for (;;) {\n}"); 2130 verifyFormat("for (;;) {\n" 2131 " f();\n" 2132 "}"); 2133 verifyFormat("for (int i = 0; (i < 10); ++i) {\n}"); 2134 2135 verifyFormat( 2136 "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n" 2137 " E = UnwrappedLines.end();\n" 2138 " I != E; ++I) {\n}"); 2139 2140 verifyFormat( 2141 "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n" 2142 " ++IIIII) {\n}"); 2143 verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n" 2144 " aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n" 2145 " aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}"); 2146 verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n" 2147 " I = FD->getDeclsInPrototypeScope().begin(),\n" 2148 " E = FD->getDeclsInPrototypeScope().end();\n" 2149 " I != E; ++I) {\n}"); 2150 verifyFormat("for (SmallVectorImpl<TemplateIdAnnotationn *>::iterator\n" 2151 " I = Container.begin(),\n" 2152 " E = Container.end();\n" 2153 " I != E; ++I) {\n}", 2154 getLLVMStyleWithColumns(76)); 2155 2156 verifyFormat( 2157 "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n" 2158 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n" 2159 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2160 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 2161 " ++aaaaaaaaaaa) {\n}"); 2162 verifyFormat("for (int i = 0; i < aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 2163 " bbbbbbbbbbbbbbbbbbbb < ccccccccccccccc;\n" 2164 " ++i) {\n}"); 2165 verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n" 2166 " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n" 2167 "}"); 2168 verifyFormat("for (some_namespace::SomeIterator iter( // force break\n" 2169 " aaaaaaaaaa);\n" 2170 " iter; ++iter) {\n" 2171 "}"); 2172 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2173 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 2174 " aaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbbbbbbb;\n" 2175 " ++aaaaaaaaaaaaaaaaaaaaaaaaaaa) {"); 2176 2177 // These should not be formatted as Objective-C for-in loops. 2178 verifyFormat("for (Foo *x = 0; x != in; x++) {\n}"); 2179 verifyFormat("Foo *x;\nfor (x = 0; x != in; x++) {\n}"); 2180 verifyFormat("Foo *x;\nfor (x in y) {\n}"); 2181 verifyFormat( 2182 "for (const Foo<Bar> &baz = in.value(); !baz.at_end(); ++baz) {\n}"); 2183 2184 FormatStyle NoBinPacking = getLLVMStyle(); 2185 NoBinPacking.BinPackParameters = false; 2186 verifyFormat("for (int aaaaaaaaaaa = 1;\n" 2187 " aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n" 2188 " aaaaaaaaaaaaaaaa,\n" 2189 " aaaaaaaaaaaaaaaa,\n" 2190 " aaaaaaaaaaaaaaaa);\n" 2191 " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n" 2192 "}", 2193 NoBinPacking); 2194 verifyFormat( 2195 "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n" 2196 " E = UnwrappedLines.end();\n" 2197 " I != E;\n" 2198 " ++I) {\n}", 2199 NoBinPacking); 2200 2201 FormatStyle AlignLeft = getLLVMStyle(); 2202 AlignLeft.PointerAlignment = FormatStyle::PAS_Left; 2203 verifyFormat("for (A* a = start; a < end; ++a, ++value) {\n}", AlignLeft); 2204 } 2205 2206 TEST_F(FormatTest, RangeBasedForLoops) { 2207 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 2208 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 2209 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n" 2210 " aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}"); 2211 verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n" 2212 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 2213 verifyFormat("for (aaaaaaaaa aaaaaaaaaaaaaaaaaaaaa :\n" 2214 " aaaaaaaaaaaa.aaaaaaaaaaaa().aaaaaaaaa().a()) {\n}"); 2215 } 2216 2217 TEST_F(FormatTest, ForEachLoops) { 2218 FormatStyle Style = getLLVMStyle(); 2219 EXPECT_EQ(Style.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 2220 EXPECT_EQ(Style.AllowShortLoopsOnASingleLine, false); 2221 verifyFormat("void f() {\n" 2222 " for (;;) {\n" 2223 " }\n" 2224 " foreach (Item *item, itemlist) {\n" 2225 " }\n" 2226 " Q_FOREACH (Item *item, itemlist) {\n" 2227 " }\n" 2228 " BOOST_FOREACH (Item *item, itemlist) {\n" 2229 " }\n" 2230 " UNKNOWN_FOREACH(Item * item, itemlist) {}\n" 2231 "}", 2232 Style); 2233 verifyFormat("void f() {\n" 2234 " for (;;)\n" 2235 " int j = 1;\n" 2236 " Q_FOREACH (int v, vec)\n" 2237 " v *= 2;\n" 2238 " for (;;) {\n" 2239 " int j = 1;\n" 2240 " }\n" 2241 " Q_FOREACH (int v, vec) {\n" 2242 " v *= 2;\n" 2243 " }\n" 2244 "}", 2245 Style); 2246 2247 FormatStyle ShortBlocks = getLLVMStyle(); 2248 ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 2249 EXPECT_EQ(ShortBlocks.AllowShortLoopsOnASingleLine, false); 2250 verifyFormat("void f() {\n" 2251 " for (;;)\n" 2252 " int j = 1;\n" 2253 " Q_FOREACH (int &v, vec)\n" 2254 " v *= 2;\n" 2255 " for (;;) {\n" 2256 " int j = 1;\n" 2257 " }\n" 2258 " Q_FOREACH (int &v, vec) {\n" 2259 " int j = 1;\n" 2260 " }\n" 2261 "}", 2262 ShortBlocks); 2263 2264 FormatStyle ShortLoops = getLLVMStyle(); 2265 ShortLoops.AllowShortLoopsOnASingleLine = true; 2266 EXPECT_EQ(ShortLoops.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 2267 verifyFormat("void f() {\n" 2268 " for (;;) int j = 1;\n" 2269 " Q_FOREACH (int &v, vec) int j = 1;\n" 2270 " for (;;) {\n" 2271 " int j = 1;\n" 2272 " }\n" 2273 " Q_FOREACH (int &v, vec) {\n" 2274 " int j = 1;\n" 2275 " }\n" 2276 "}", 2277 ShortLoops); 2278 2279 FormatStyle ShortBlocksAndLoops = getLLVMStyle(); 2280 ShortBlocksAndLoops.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 2281 ShortBlocksAndLoops.AllowShortLoopsOnASingleLine = true; 2282 verifyFormat("void f() {\n" 2283 " for (;;) int j = 1;\n" 2284 " Q_FOREACH (int &v, vec) int j = 1;\n" 2285 " for (;;) { int j = 1; }\n" 2286 " Q_FOREACH (int &v, vec) { int j = 1; }\n" 2287 "}", 2288 ShortBlocksAndLoops); 2289 2290 Style.SpaceBeforeParens = 2291 FormatStyle::SBPO_ControlStatementsExceptControlMacros; 2292 verifyFormat("void f() {\n" 2293 " for (;;) {\n" 2294 " }\n" 2295 " foreach(Item *item, itemlist) {\n" 2296 " }\n" 2297 " Q_FOREACH(Item *item, itemlist) {\n" 2298 " }\n" 2299 " BOOST_FOREACH(Item *item, itemlist) {\n" 2300 " }\n" 2301 " UNKNOWN_FOREACH(Item * item, itemlist) {}\n" 2302 "}", 2303 Style); 2304 2305 // As function-like macros. 2306 verifyFormat("#define foreach(x, y)\n" 2307 "#define Q_FOREACH(x, y)\n" 2308 "#define BOOST_FOREACH(x, y)\n" 2309 "#define UNKNOWN_FOREACH(x, y)\n"); 2310 2311 // Not as function-like macros. 2312 verifyFormat("#define foreach (x, y)\n" 2313 "#define Q_FOREACH (x, y)\n" 2314 "#define BOOST_FOREACH (x, y)\n" 2315 "#define UNKNOWN_FOREACH (x, y)\n"); 2316 2317 // handle microsoft non standard extension 2318 verifyFormat("for each (char c in x->MyStringProperty)"); 2319 } 2320 2321 TEST_F(FormatTest, FormatsWhileLoop) { 2322 verifyFormat("while (true) {\n}"); 2323 verifyFormat("while (true)\n" 2324 " f();"); 2325 verifyFormat("while () {\n}"); 2326 verifyFormat("while () {\n" 2327 " f();\n" 2328 "}"); 2329 } 2330 2331 TEST_F(FormatTest, FormatsDoWhile) { 2332 verifyFormat("do {\n" 2333 " do_something();\n" 2334 "} while (something());"); 2335 verifyFormat("do\n" 2336 " do_something();\n" 2337 "while (something());"); 2338 } 2339 2340 TEST_F(FormatTest, FormatsSwitchStatement) { 2341 verifyFormat("switch (x) {\n" 2342 "case 1:\n" 2343 " f();\n" 2344 " break;\n" 2345 "case kFoo:\n" 2346 "case ns::kBar:\n" 2347 "case kBaz:\n" 2348 " break;\n" 2349 "default:\n" 2350 " g();\n" 2351 " break;\n" 2352 "}"); 2353 verifyFormat("switch (x) {\n" 2354 "case 1: {\n" 2355 " f();\n" 2356 " break;\n" 2357 "}\n" 2358 "case 2: {\n" 2359 " break;\n" 2360 "}\n" 2361 "}"); 2362 verifyFormat("switch (x) {\n" 2363 "case 1: {\n" 2364 " f();\n" 2365 " {\n" 2366 " g();\n" 2367 " h();\n" 2368 " }\n" 2369 " break;\n" 2370 "}\n" 2371 "}"); 2372 verifyFormat("switch (x) {\n" 2373 "case 1: {\n" 2374 " f();\n" 2375 " if (foo) {\n" 2376 " g();\n" 2377 " h();\n" 2378 " }\n" 2379 " break;\n" 2380 "}\n" 2381 "}"); 2382 verifyFormat("switch (x) {\n" 2383 "case 1: {\n" 2384 " f();\n" 2385 " g();\n" 2386 "} break;\n" 2387 "}"); 2388 verifyFormat("switch (test)\n" 2389 " ;"); 2390 verifyFormat("switch (x) {\n" 2391 "default: {\n" 2392 " // Do nothing.\n" 2393 "}\n" 2394 "}"); 2395 verifyFormat("switch (x) {\n" 2396 "// comment\n" 2397 "// if 1, do f()\n" 2398 "case 1:\n" 2399 " f();\n" 2400 "}"); 2401 verifyFormat("switch (x) {\n" 2402 "case 1:\n" 2403 " // Do amazing stuff\n" 2404 " {\n" 2405 " f();\n" 2406 " g();\n" 2407 " }\n" 2408 " break;\n" 2409 "}"); 2410 verifyFormat("#define A \\\n" 2411 " switch (x) { \\\n" 2412 " case a: \\\n" 2413 " foo = b; \\\n" 2414 " }", 2415 getLLVMStyleWithColumns(20)); 2416 verifyFormat("#define OPERATION_CASE(name) \\\n" 2417 " case OP_name: \\\n" 2418 " return operations::Operation##name\n", 2419 getLLVMStyleWithColumns(40)); 2420 verifyFormat("switch (x) {\n" 2421 "case 1:;\n" 2422 "default:;\n" 2423 " int i;\n" 2424 "}"); 2425 2426 verifyGoogleFormat("switch (x) {\n" 2427 " case 1:\n" 2428 " f();\n" 2429 " break;\n" 2430 " case kFoo:\n" 2431 " case ns::kBar:\n" 2432 " case kBaz:\n" 2433 " break;\n" 2434 " default:\n" 2435 " g();\n" 2436 " break;\n" 2437 "}"); 2438 verifyGoogleFormat("switch (x) {\n" 2439 " case 1: {\n" 2440 " f();\n" 2441 " break;\n" 2442 " }\n" 2443 "}"); 2444 verifyGoogleFormat("switch (test)\n" 2445 " ;"); 2446 2447 verifyGoogleFormat("#define OPERATION_CASE(name) \\\n" 2448 " case OP_name: \\\n" 2449 " return operations::Operation##name\n"); 2450 verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n" 2451 " // Get the correction operation class.\n" 2452 " switch (OpCode) {\n" 2453 " CASE(Add);\n" 2454 " CASE(Subtract);\n" 2455 " default:\n" 2456 " return operations::Unknown;\n" 2457 " }\n" 2458 "#undef OPERATION_CASE\n" 2459 "}"); 2460 verifyFormat("DEBUG({\n" 2461 " switch (x) {\n" 2462 " case A:\n" 2463 " f();\n" 2464 " break;\n" 2465 " // fallthrough\n" 2466 " case B:\n" 2467 " g();\n" 2468 " break;\n" 2469 " }\n" 2470 "});"); 2471 EXPECT_EQ("DEBUG({\n" 2472 " switch (x) {\n" 2473 " case A:\n" 2474 " f();\n" 2475 " break;\n" 2476 " // On B:\n" 2477 " case B:\n" 2478 " g();\n" 2479 " break;\n" 2480 " }\n" 2481 "});", 2482 format("DEBUG({\n" 2483 " switch (x) {\n" 2484 " case A:\n" 2485 " f();\n" 2486 " break;\n" 2487 " // On B:\n" 2488 " case B:\n" 2489 " g();\n" 2490 " break;\n" 2491 " }\n" 2492 "});", 2493 getLLVMStyle())); 2494 EXPECT_EQ("switch (n) {\n" 2495 "case 0: {\n" 2496 " return false;\n" 2497 "}\n" 2498 "default: {\n" 2499 " return true;\n" 2500 "}\n" 2501 "}", 2502 format("switch (n)\n" 2503 "{\n" 2504 "case 0: {\n" 2505 " return false;\n" 2506 "}\n" 2507 "default: {\n" 2508 " return true;\n" 2509 "}\n" 2510 "}", 2511 getLLVMStyle())); 2512 verifyFormat("switch (a) {\n" 2513 "case (b):\n" 2514 " return;\n" 2515 "}"); 2516 2517 verifyFormat("switch (a) {\n" 2518 "case some_namespace::\n" 2519 " some_constant:\n" 2520 " return;\n" 2521 "}", 2522 getLLVMStyleWithColumns(34)); 2523 2524 FormatStyle Style = getLLVMStyle(); 2525 Style.IndentCaseLabels = true; 2526 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 2527 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2528 Style.BraceWrapping.AfterCaseLabel = true; 2529 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 2530 EXPECT_EQ("switch (n)\n" 2531 "{\n" 2532 " case 0:\n" 2533 " {\n" 2534 " return false;\n" 2535 " }\n" 2536 " default:\n" 2537 " {\n" 2538 " return true;\n" 2539 " }\n" 2540 "}", 2541 format("switch (n) {\n" 2542 " case 0: {\n" 2543 " return false;\n" 2544 " }\n" 2545 " default: {\n" 2546 " return true;\n" 2547 " }\n" 2548 "}", 2549 Style)); 2550 Style.BraceWrapping.AfterCaseLabel = false; 2551 EXPECT_EQ("switch (n)\n" 2552 "{\n" 2553 " case 0: {\n" 2554 " return false;\n" 2555 " }\n" 2556 " default: {\n" 2557 " return true;\n" 2558 " }\n" 2559 "}", 2560 format("switch (n) {\n" 2561 " case 0:\n" 2562 " {\n" 2563 " return false;\n" 2564 " }\n" 2565 " default:\n" 2566 " {\n" 2567 " return true;\n" 2568 " }\n" 2569 "}", 2570 Style)); 2571 Style.IndentCaseLabels = false; 2572 Style.IndentCaseBlocks = true; 2573 EXPECT_EQ("switch (n)\n" 2574 "{\n" 2575 "case 0:\n" 2576 " {\n" 2577 " return false;\n" 2578 " }\n" 2579 "case 1:\n" 2580 " break;\n" 2581 "default:\n" 2582 " {\n" 2583 " return true;\n" 2584 " }\n" 2585 "}", 2586 format("switch (n) {\n" 2587 "case 0: {\n" 2588 " return false;\n" 2589 "}\n" 2590 "case 1:\n" 2591 " break;\n" 2592 "default: {\n" 2593 " return true;\n" 2594 "}\n" 2595 "}", 2596 Style)); 2597 Style.IndentCaseLabels = true; 2598 Style.IndentCaseBlocks = true; 2599 EXPECT_EQ("switch (n)\n" 2600 "{\n" 2601 " case 0:\n" 2602 " {\n" 2603 " return false;\n" 2604 " }\n" 2605 " case 1:\n" 2606 " break;\n" 2607 " default:\n" 2608 " {\n" 2609 " return true;\n" 2610 " }\n" 2611 "}", 2612 format("switch (n) {\n" 2613 "case 0: {\n" 2614 " return false;\n" 2615 "}\n" 2616 "case 1:\n" 2617 " break;\n" 2618 "default: {\n" 2619 " return true;\n" 2620 "}\n" 2621 "}", 2622 Style)); 2623 } 2624 2625 TEST_F(FormatTest, CaseRanges) { 2626 verifyFormat("switch (x) {\n" 2627 "case 'A' ... 'Z':\n" 2628 "case 1 ... 5:\n" 2629 "case a ... b:\n" 2630 " break;\n" 2631 "}"); 2632 } 2633 2634 TEST_F(FormatTest, ShortEnums) { 2635 FormatStyle Style = getLLVMStyle(); 2636 Style.AllowShortEnumsOnASingleLine = true; 2637 verifyFormat("enum { A, B, C } ShortEnum1, ShortEnum2;", Style); 2638 verifyFormat("typedef enum { A, B, C } ShortEnum1, ShortEnum2;", Style); 2639 Style.AllowShortEnumsOnASingleLine = false; 2640 verifyFormat("enum {\n" 2641 " A,\n" 2642 " B,\n" 2643 " C\n" 2644 "} ShortEnum1, ShortEnum2;", 2645 Style); 2646 verifyFormat("typedef enum {\n" 2647 " A,\n" 2648 " B,\n" 2649 " C\n" 2650 "} ShortEnum1, ShortEnum2;", 2651 Style); 2652 verifyFormat("enum {\n" 2653 " A,\n" 2654 "} ShortEnum1, ShortEnum2;", 2655 Style); 2656 verifyFormat("typedef enum {\n" 2657 " A,\n" 2658 "} ShortEnum1, ShortEnum2;", 2659 Style); 2660 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2661 Style.BraceWrapping.AfterEnum = true; 2662 verifyFormat("enum\n" 2663 "{\n" 2664 " A,\n" 2665 " B,\n" 2666 " C\n" 2667 "} ShortEnum1, ShortEnum2;", 2668 Style); 2669 verifyFormat("typedef enum\n" 2670 "{\n" 2671 " A,\n" 2672 " B,\n" 2673 " C\n" 2674 "} ShortEnum1, ShortEnum2;", 2675 Style); 2676 } 2677 2678 TEST_F(FormatTest, ShortCaseLabels) { 2679 FormatStyle Style = getLLVMStyle(); 2680 Style.AllowShortCaseLabelsOnASingleLine = true; 2681 verifyFormat("switch (a) {\n" 2682 "case 1: x = 1; break;\n" 2683 "case 2: return;\n" 2684 "case 3:\n" 2685 "case 4:\n" 2686 "case 5: return;\n" 2687 "case 6: // comment\n" 2688 " return;\n" 2689 "case 7:\n" 2690 " // comment\n" 2691 " return;\n" 2692 "case 8:\n" 2693 " x = 8; // comment\n" 2694 " break;\n" 2695 "default: y = 1; break;\n" 2696 "}", 2697 Style); 2698 verifyFormat("switch (a) {\n" 2699 "case 0: return; // comment\n" 2700 "case 1: break; // comment\n" 2701 "case 2: return;\n" 2702 "// comment\n" 2703 "case 3: return;\n" 2704 "// comment 1\n" 2705 "// comment 2\n" 2706 "// comment 3\n" 2707 "case 4: break; /* comment */\n" 2708 "case 5:\n" 2709 " // comment\n" 2710 " break;\n" 2711 "case 6: /* comment */ x = 1; break;\n" 2712 "case 7: x = /* comment */ 1; break;\n" 2713 "case 8:\n" 2714 " x = 1; /* comment */\n" 2715 " break;\n" 2716 "case 9:\n" 2717 " break; // comment line 1\n" 2718 " // comment line 2\n" 2719 "}", 2720 Style); 2721 EXPECT_EQ("switch (a) {\n" 2722 "case 1:\n" 2723 " x = 8;\n" 2724 " // fall through\n" 2725 "case 2: x = 8;\n" 2726 "// comment\n" 2727 "case 3:\n" 2728 " return; /* comment line 1\n" 2729 " * comment line 2 */\n" 2730 "case 4: i = 8;\n" 2731 "// something else\n" 2732 "#if FOO\n" 2733 "case 5: break;\n" 2734 "#endif\n" 2735 "}", 2736 format("switch (a) {\n" 2737 "case 1: x = 8;\n" 2738 " // fall through\n" 2739 "case 2:\n" 2740 " x = 8;\n" 2741 "// comment\n" 2742 "case 3:\n" 2743 " return; /* comment line 1\n" 2744 " * comment line 2 */\n" 2745 "case 4:\n" 2746 " i = 8;\n" 2747 "// something else\n" 2748 "#if FOO\n" 2749 "case 5: break;\n" 2750 "#endif\n" 2751 "}", 2752 Style)); 2753 EXPECT_EQ("switch (a) {\n" 2754 "case 0:\n" 2755 " return; // long long long long long long long long long long " 2756 "long long comment\n" 2757 " // line\n" 2758 "}", 2759 format("switch (a) {\n" 2760 "case 0: return; // long long long long long long long long " 2761 "long long long long comment line\n" 2762 "}", 2763 Style)); 2764 EXPECT_EQ("switch (a) {\n" 2765 "case 0:\n" 2766 " return; /* long long long long long long long long long long " 2767 "long long comment\n" 2768 " line */\n" 2769 "}", 2770 format("switch (a) {\n" 2771 "case 0: return; /* long long long long long long long long " 2772 "long long long long comment line */\n" 2773 "}", 2774 Style)); 2775 verifyFormat("switch (a) {\n" 2776 "#if FOO\n" 2777 "case 0: return 0;\n" 2778 "#endif\n" 2779 "}", 2780 Style); 2781 verifyFormat("switch (a) {\n" 2782 "case 1: {\n" 2783 "}\n" 2784 "case 2: {\n" 2785 " return;\n" 2786 "}\n" 2787 "case 3: {\n" 2788 " x = 1;\n" 2789 " return;\n" 2790 "}\n" 2791 "case 4:\n" 2792 " if (x)\n" 2793 " return;\n" 2794 "}", 2795 Style); 2796 Style.ColumnLimit = 21; 2797 verifyFormat("switch (a) {\n" 2798 "case 1: x = 1; break;\n" 2799 "case 2: return;\n" 2800 "case 3:\n" 2801 "case 4:\n" 2802 "case 5: return;\n" 2803 "default:\n" 2804 " y = 1;\n" 2805 " break;\n" 2806 "}", 2807 Style); 2808 Style.ColumnLimit = 80; 2809 Style.AllowShortCaseLabelsOnASingleLine = false; 2810 Style.IndentCaseLabels = true; 2811 EXPECT_EQ("switch (n) {\n" 2812 " default /*comments*/:\n" 2813 " return true;\n" 2814 " case 0:\n" 2815 " return false;\n" 2816 "}", 2817 format("switch (n) {\n" 2818 "default/*comments*/:\n" 2819 " return true;\n" 2820 "case 0:\n" 2821 " return false;\n" 2822 "}", 2823 Style)); 2824 Style.AllowShortCaseLabelsOnASingleLine = true; 2825 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2826 Style.BraceWrapping.AfterCaseLabel = true; 2827 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 2828 EXPECT_EQ("switch (n)\n" 2829 "{\n" 2830 " case 0:\n" 2831 " {\n" 2832 " return false;\n" 2833 " }\n" 2834 " default:\n" 2835 " {\n" 2836 " return true;\n" 2837 " }\n" 2838 "}", 2839 format("switch (n) {\n" 2840 " case 0: {\n" 2841 " return false;\n" 2842 " }\n" 2843 " default:\n" 2844 " {\n" 2845 " return true;\n" 2846 " }\n" 2847 "}", 2848 Style)); 2849 } 2850 2851 TEST_F(FormatTest, FormatsLabels) { 2852 verifyFormat("void f() {\n" 2853 " some_code();\n" 2854 "test_label:\n" 2855 " some_other_code();\n" 2856 " {\n" 2857 " some_more_code();\n" 2858 " another_label:\n" 2859 " some_more_code();\n" 2860 " }\n" 2861 "}"); 2862 verifyFormat("{\n" 2863 " some_code();\n" 2864 "test_label:\n" 2865 " some_other_code();\n" 2866 "}"); 2867 verifyFormat("{\n" 2868 " some_code();\n" 2869 "test_label:;\n" 2870 " int i = 0;\n" 2871 "}"); 2872 FormatStyle Style = getLLVMStyle(); 2873 Style.IndentGotoLabels = false; 2874 verifyFormat("void f() {\n" 2875 " some_code();\n" 2876 "test_label:\n" 2877 " some_other_code();\n" 2878 " {\n" 2879 " some_more_code();\n" 2880 "another_label:\n" 2881 " some_more_code();\n" 2882 " }\n" 2883 "}", 2884 Style); 2885 verifyFormat("{\n" 2886 " some_code();\n" 2887 "test_label:\n" 2888 " some_other_code();\n" 2889 "}", 2890 Style); 2891 verifyFormat("{\n" 2892 " some_code();\n" 2893 "test_label:;\n" 2894 " int i = 0;\n" 2895 "}"); 2896 } 2897 2898 TEST_F(FormatTest, MultiLineControlStatements) { 2899 FormatStyle Style = getLLVMStyleWithColumns(20); 2900 Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom; 2901 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine; 2902 // Short lines should keep opening brace on same line. 2903 EXPECT_EQ("if (foo) {\n" 2904 " bar();\n" 2905 "}", 2906 format("if(foo){bar();}", Style)); 2907 EXPECT_EQ("if (foo) {\n" 2908 " bar();\n" 2909 "} else {\n" 2910 " baz();\n" 2911 "}", 2912 format("if(foo){bar();}else{baz();}", Style)); 2913 EXPECT_EQ("if (foo && bar) {\n" 2914 " baz();\n" 2915 "}", 2916 format("if(foo&&bar){baz();}", Style)); 2917 EXPECT_EQ("if (foo) {\n" 2918 " bar();\n" 2919 "} else if (baz) {\n" 2920 " quux();\n" 2921 "}", 2922 format("if(foo){bar();}else if(baz){quux();}", Style)); 2923 EXPECT_EQ( 2924 "if (foo) {\n" 2925 " bar();\n" 2926 "} else if (baz) {\n" 2927 " quux();\n" 2928 "} else {\n" 2929 " foobar();\n" 2930 "}", 2931 format("if(foo){bar();}else if(baz){quux();}else{foobar();}", Style)); 2932 EXPECT_EQ("for (;;) {\n" 2933 " foo();\n" 2934 "}", 2935 format("for(;;){foo();}")); 2936 EXPECT_EQ("while (1) {\n" 2937 " foo();\n" 2938 "}", 2939 format("while(1){foo();}", Style)); 2940 EXPECT_EQ("switch (foo) {\n" 2941 "case bar:\n" 2942 " return;\n" 2943 "}", 2944 format("switch(foo){case bar:return;}", Style)); 2945 EXPECT_EQ("try {\n" 2946 " foo();\n" 2947 "} catch (...) {\n" 2948 " bar();\n" 2949 "}", 2950 format("try{foo();}catch(...){bar();}", Style)); 2951 EXPECT_EQ("do {\n" 2952 " foo();\n" 2953 "} while (bar &&\n" 2954 " baz);", 2955 format("do{foo();}while(bar&&baz);", Style)); 2956 // Long lines should put opening brace on new line. 2957 EXPECT_EQ("if (foo && bar &&\n" 2958 " baz)\n" 2959 "{\n" 2960 " quux();\n" 2961 "}", 2962 format("if(foo&&bar&&baz){quux();}", Style)); 2963 EXPECT_EQ("if (foo && bar &&\n" 2964 " baz)\n" 2965 "{\n" 2966 " quux();\n" 2967 "}", 2968 format("if (foo && bar &&\n" 2969 " baz) {\n" 2970 " quux();\n" 2971 "}", 2972 Style)); 2973 EXPECT_EQ("if (foo) {\n" 2974 " bar();\n" 2975 "} else if (baz ||\n" 2976 " quux)\n" 2977 "{\n" 2978 " foobar();\n" 2979 "}", 2980 format("if(foo){bar();}else if(baz||quux){foobar();}", Style)); 2981 EXPECT_EQ( 2982 "if (foo) {\n" 2983 " bar();\n" 2984 "} else if (baz ||\n" 2985 " quux)\n" 2986 "{\n" 2987 " foobar();\n" 2988 "} else {\n" 2989 " barbaz();\n" 2990 "}", 2991 format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}", 2992 Style)); 2993 EXPECT_EQ("for (int i = 0;\n" 2994 " i < 10; ++i)\n" 2995 "{\n" 2996 " foo();\n" 2997 "}", 2998 format("for(int i=0;i<10;++i){foo();}", Style)); 2999 EXPECT_EQ("foreach (int i,\n" 3000 " list)\n" 3001 "{\n" 3002 " foo();\n" 3003 "}", 3004 format("foreach(int i, list){foo();}", Style)); 3005 Style.ColumnLimit = 3006 40; // to concentrate at brace wrapping, not line wrap due to column limit 3007 EXPECT_EQ("foreach (int i, list) {\n" 3008 " foo();\n" 3009 "}", 3010 format("foreach(int i, list){foo();}", Style)); 3011 Style.ColumnLimit = 3012 20; // to concentrate at brace wrapping, not line wrap due to column limit 3013 EXPECT_EQ("while (foo || bar ||\n" 3014 " baz)\n" 3015 "{\n" 3016 " quux();\n" 3017 "}", 3018 format("while(foo||bar||baz){quux();}", Style)); 3019 EXPECT_EQ("switch (\n" 3020 " foo = barbaz)\n" 3021 "{\n" 3022 "case quux:\n" 3023 " return;\n" 3024 "}", 3025 format("switch(foo=barbaz){case quux:return;}", Style)); 3026 EXPECT_EQ("try {\n" 3027 " foo();\n" 3028 "} catch (\n" 3029 " Exception &bar)\n" 3030 "{\n" 3031 " baz();\n" 3032 "}", 3033 format("try{foo();}catch(Exception&bar){baz();}", Style)); 3034 Style.ColumnLimit = 3035 40; // to concentrate at brace wrapping, not line wrap due to column limit 3036 EXPECT_EQ("try {\n" 3037 " foo();\n" 3038 "} catch (Exception &bar) {\n" 3039 " baz();\n" 3040 "}", 3041 format("try{foo();}catch(Exception&bar){baz();}", Style)); 3042 Style.ColumnLimit = 3043 20; // to concentrate at brace wrapping, not line wrap due to column limit 3044 3045 Style.BraceWrapping.BeforeElse = true; 3046 EXPECT_EQ( 3047 "if (foo) {\n" 3048 " bar();\n" 3049 "}\n" 3050 "else if (baz ||\n" 3051 " quux)\n" 3052 "{\n" 3053 " foobar();\n" 3054 "}\n" 3055 "else {\n" 3056 " barbaz();\n" 3057 "}", 3058 format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}", 3059 Style)); 3060 3061 Style.BraceWrapping.BeforeCatch = true; 3062 EXPECT_EQ("try {\n" 3063 " foo();\n" 3064 "}\n" 3065 "catch (...) {\n" 3066 " baz();\n" 3067 "}", 3068 format("try{foo();}catch(...){baz();}", Style)); 3069 3070 Style.BraceWrapping.AfterFunction = true; 3071 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine; 3072 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 3073 Style.ColumnLimit = 80; 3074 verifyFormat("void shortfunction() { bar(); }", Style); 3075 3076 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 3077 verifyFormat("void shortfunction()\n" 3078 "{\n" 3079 " bar();\n" 3080 "}", 3081 Style); 3082 } 3083 3084 TEST_F(FormatTest, BeforeWhile) { 3085 FormatStyle Style = getLLVMStyle(); 3086 Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom; 3087 3088 verifyFormat("do {\n" 3089 " foo();\n" 3090 "} while (1);", 3091 Style); 3092 Style.BraceWrapping.BeforeWhile = true; 3093 verifyFormat("do {\n" 3094 " foo();\n" 3095 "}\n" 3096 "while (1);", 3097 Style); 3098 } 3099 3100 //===----------------------------------------------------------------------===// 3101 // Tests for classes, namespaces, etc. 3102 //===----------------------------------------------------------------------===// 3103 3104 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) { 3105 verifyFormat("class A {};"); 3106 } 3107 3108 TEST_F(FormatTest, UnderstandsAccessSpecifiers) { 3109 verifyFormat("class A {\n" 3110 "public:\n" 3111 "public: // comment\n" 3112 "protected:\n" 3113 "private:\n" 3114 " void f() {}\n" 3115 "};"); 3116 verifyFormat("export class A {\n" 3117 "public:\n" 3118 "public: // comment\n" 3119 "protected:\n" 3120 "private:\n" 3121 " void f() {}\n" 3122 "};"); 3123 verifyGoogleFormat("class A {\n" 3124 " public:\n" 3125 " protected:\n" 3126 " private:\n" 3127 " void f() {}\n" 3128 "};"); 3129 verifyGoogleFormat("export class A {\n" 3130 " public:\n" 3131 " protected:\n" 3132 " private:\n" 3133 " void f() {}\n" 3134 "};"); 3135 verifyFormat("class A {\n" 3136 "public slots:\n" 3137 " void f1() {}\n" 3138 "public Q_SLOTS:\n" 3139 " void f2() {}\n" 3140 "protected slots:\n" 3141 " void f3() {}\n" 3142 "protected Q_SLOTS:\n" 3143 " void f4() {}\n" 3144 "private slots:\n" 3145 " void f5() {}\n" 3146 "private Q_SLOTS:\n" 3147 " void f6() {}\n" 3148 "signals:\n" 3149 " void g1();\n" 3150 "Q_SIGNALS:\n" 3151 " void g2();\n" 3152 "};"); 3153 3154 // Don't interpret 'signals' the wrong way. 3155 verifyFormat("signals.set();"); 3156 verifyFormat("for (Signals signals : f()) {\n}"); 3157 verifyFormat("{\n" 3158 " signals.set(); // This needs indentation.\n" 3159 "}"); 3160 verifyFormat("void f() {\n" 3161 "label:\n" 3162 " signals.baz();\n" 3163 "}"); 3164 verifyFormat("private[1];"); 3165 verifyFormat("testArray[public] = 1;"); 3166 verifyFormat("public();"); 3167 verifyFormat("myFunc(public);"); 3168 verifyFormat("std::vector<int> testVec = {private};"); 3169 verifyFormat("private.p = 1;"); 3170 verifyFormat("void function(private...){};"); 3171 verifyFormat("if (private && public)\n"); 3172 verifyFormat("private &= true;"); 3173 verifyFormat("int x = private * public;"); 3174 verifyFormat("public *= private;"); 3175 verifyFormat("int x = public + private;"); 3176 verifyFormat("private++;"); 3177 verifyFormat("++private;"); 3178 verifyFormat("public += private;"); 3179 verifyFormat("public = public - private;"); 3180 verifyFormat("public->foo();"); 3181 verifyFormat("private--;"); 3182 verifyFormat("--private;"); 3183 verifyFormat("public -= 1;"); 3184 verifyFormat("if (!private && !public)\n"); 3185 verifyFormat("public != private;"); 3186 verifyFormat("int x = public / private;"); 3187 verifyFormat("public /= 2;"); 3188 verifyFormat("public = public % 2;"); 3189 verifyFormat("public %= 2;"); 3190 verifyFormat("if (public < private)\n"); 3191 verifyFormat("public << private;"); 3192 verifyFormat("public <<= private;"); 3193 verifyFormat("if (public > private)\n"); 3194 verifyFormat("public >> private;"); 3195 verifyFormat("public >>= private;"); 3196 verifyFormat("public ^ private;"); 3197 verifyFormat("public ^= private;"); 3198 verifyFormat("public | private;"); 3199 verifyFormat("public |= private;"); 3200 verifyFormat("auto x = private ? 1 : 2;"); 3201 verifyFormat("if (public == private)\n"); 3202 verifyFormat("void foo(public, private)"); 3203 verifyFormat("public::foo();"); 3204 } 3205 3206 TEST_F(FormatTest, SeparatesLogicalBlocks) { 3207 EXPECT_EQ("class A {\n" 3208 "public:\n" 3209 " void f();\n" 3210 "\n" 3211 "private:\n" 3212 " void g() {}\n" 3213 " // test\n" 3214 "protected:\n" 3215 " int h;\n" 3216 "};", 3217 format("class A {\n" 3218 "public:\n" 3219 "void f();\n" 3220 "private:\n" 3221 "void g() {}\n" 3222 "// test\n" 3223 "protected:\n" 3224 "int h;\n" 3225 "};")); 3226 EXPECT_EQ("class A {\n" 3227 "protected:\n" 3228 "public:\n" 3229 " void f();\n" 3230 "};", 3231 format("class A {\n" 3232 "protected:\n" 3233 "\n" 3234 "public:\n" 3235 "\n" 3236 " void f();\n" 3237 "};")); 3238 3239 // Even ensure proper spacing inside macros. 3240 EXPECT_EQ("#define B \\\n" 3241 " class A { \\\n" 3242 " protected: \\\n" 3243 " public: \\\n" 3244 " void f(); \\\n" 3245 " };", 3246 format("#define B \\\n" 3247 " class A { \\\n" 3248 " protected: \\\n" 3249 " \\\n" 3250 " public: \\\n" 3251 " \\\n" 3252 " void f(); \\\n" 3253 " };", 3254 getGoogleStyle())); 3255 // But don't remove empty lines after macros ending in access specifiers. 3256 EXPECT_EQ("#define A private:\n" 3257 "\n" 3258 "int i;", 3259 format("#define A private:\n" 3260 "\n" 3261 "int i;")); 3262 } 3263 3264 TEST_F(FormatTest, FormatsClasses) { 3265 verifyFormat("class A : public B {};"); 3266 verifyFormat("class A : public ::B {};"); 3267 3268 verifyFormat( 3269 "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3270 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};"); 3271 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n" 3272 " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3273 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};"); 3274 verifyFormat( 3275 "class A : public B, public C, public D, public E, public F {};"); 3276 verifyFormat("class AAAAAAAAAAAA : public B,\n" 3277 " public C,\n" 3278 " public D,\n" 3279 " public E,\n" 3280 " public F,\n" 3281 " public G {};"); 3282 3283 verifyFormat("class\n" 3284 " ReallyReallyLongClassName {\n" 3285 " int i;\n" 3286 "};", 3287 getLLVMStyleWithColumns(32)); 3288 verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n" 3289 " aaaaaaaaaaaaaaaa> {};"); 3290 verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n" 3291 " : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n" 3292 " aaaaaaaaaaaaaaaaaaaaaa> {};"); 3293 verifyFormat("template <class R, class C>\n" 3294 "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n" 3295 " : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};"); 3296 verifyFormat("class ::A::B {};"); 3297 } 3298 3299 TEST_F(FormatTest, BreakInheritanceStyle) { 3300 FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle(); 3301 StyleWithInheritanceBreakBeforeComma.BreakInheritanceList = 3302 FormatStyle::BILS_BeforeComma; 3303 verifyFormat("class MyClass : public X {};", 3304 StyleWithInheritanceBreakBeforeComma); 3305 verifyFormat("class MyClass\n" 3306 " : public X\n" 3307 " , public Y {};", 3308 StyleWithInheritanceBreakBeforeComma); 3309 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n" 3310 " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n" 3311 " , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};", 3312 StyleWithInheritanceBreakBeforeComma); 3313 verifyFormat("struct aaaaaaaaaaaaa\n" 3314 " : public aaaaaaaaaaaaaaaaaaa< // break\n" 3315 " aaaaaaaaaaaaaaaa> {};", 3316 StyleWithInheritanceBreakBeforeComma); 3317 3318 FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle(); 3319 StyleWithInheritanceBreakAfterColon.BreakInheritanceList = 3320 FormatStyle::BILS_AfterColon; 3321 verifyFormat("class MyClass : public X {};", 3322 StyleWithInheritanceBreakAfterColon); 3323 verifyFormat("class MyClass : public X, public Y {};", 3324 StyleWithInheritanceBreakAfterColon); 3325 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n" 3326 " public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3327 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};", 3328 StyleWithInheritanceBreakAfterColon); 3329 verifyFormat("struct aaaaaaaaaaaaa :\n" 3330 " public aaaaaaaaaaaaaaaaaaa< // break\n" 3331 " aaaaaaaaaaaaaaaa> {};", 3332 StyleWithInheritanceBreakAfterColon); 3333 3334 FormatStyle StyleWithInheritanceBreakAfterComma = getLLVMStyle(); 3335 StyleWithInheritanceBreakAfterComma.BreakInheritanceList = 3336 FormatStyle::BILS_AfterComma; 3337 verifyFormat("class MyClass : public X {};", 3338 StyleWithInheritanceBreakAfterComma); 3339 verifyFormat("class MyClass : public X,\n" 3340 " public Y {};", 3341 StyleWithInheritanceBreakAfterComma); 3342 verifyFormat( 3343 "class AAAAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3344 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC " 3345 "{};", 3346 StyleWithInheritanceBreakAfterComma); 3347 verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n" 3348 " aaaaaaaaaaaaaaaa> {};", 3349 StyleWithInheritanceBreakAfterComma); 3350 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n" 3351 " : public OnceBreak,\n" 3352 " public AlwaysBreak,\n" 3353 " EvenBasesFitInOneLine {};", 3354 StyleWithInheritanceBreakAfterComma); 3355 } 3356 3357 TEST_F(FormatTest, FormatsVariableDeclarationsAfterStructOrClass) { 3358 verifyFormat("class A {\n} a, b;"); 3359 verifyFormat("struct A {\n} a, b;"); 3360 verifyFormat("union A {\n} a;"); 3361 } 3362 3363 TEST_F(FormatTest, FormatsEnum) { 3364 verifyFormat("enum {\n" 3365 " Zero,\n" 3366 " One = 1,\n" 3367 " Two = One + 1,\n" 3368 " Three = (One + Two),\n" 3369 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3370 " Five = (One, Two, Three, Four, 5)\n" 3371 "};"); 3372 verifyGoogleFormat("enum {\n" 3373 " Zero,\n" 3374 " One = 1,\n" 3375 " Two = One + 1,\n" 3376 " Three = (One + Two),\n" 3377 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3378 " Five = (One, Two, Three, Four, 5)\n" 3379 "};"); 3380 verifyFormat("enum Enum {};"); 3381 verifyFormat("enum {};"); 3382 verifyFormat("enum X E {} d;"); 3383 verifyFormat("enum __attribute__((...)) E {} d;"); 3384 verifyFormat("enum __declspec__((...)) E {} d;"); 3385 verifyFormat("enum {\n" 3386 " Bar = Foo<int, int>::value\n" 3387 "};", 3388 getLLVMStyleWithColumns(30)); 3389 3390 verifyFormat("enum ShortEnum { A, B, C };"); 3391 verifyGoogleFormat("enum ShortEnum { A, B, C };"); 3392 3393 EXPECT_EQ("enum KeepEmptyLines {\n" 3394 " ONE,\n" 3395 "\n" 3396 " TWO,\n" 3397 "\n" 3398 " THREE\n" 3399 "}", 3400 format("enum KeepEmptyLines {\n" 3401 " ONE,\n" 3402 "\n" 3403 " TWO,\n" 3404 "\n" 3405 "\n" 3406 " THREE\n" 3407 "}")); 3408 verifyFormat("enum E { // comment\n" 3409 " ONE,\n" 3410 " TWO\n" 3411 "};\n" 3412 "int i;"); 3413 3414 FormatStyle EightIndent = getLLVMStyle(); 3415 EightIndent.IndentWidth = 8; 3416 verifyFormat("enum {\n" 3417 " VOID,\n" 3418 " CHAR,\n" 3419 " SHORT,\n" 3420 " INT,\n" 3421 " LONG,\n" 3422 " SIGNED,\n" 3423 " UNSIGNED,\n" 3424 " BOOL,\n" 3425 " FLOAT,\n" 3426 " DOUBLE,\n" 3427 " COMPLEX\n" 3428 "};", 3429 EightIndent); 3430 3431 // Not enums. 3432 verifyFormat("enum X f() {\n" 3433 " a();\n" 3434 " return 42;\n" 3435 "}"); 3436 verifyFormat("enum X Type::f() {\n" 3437 " a();\n" 3438 " return 42;\n" 3439 "}"); 3440 verifyFormat("enum ::X f() {\n" 3441 " a();\n" 3442 " return 42;\n" 3443 "}"); 3444 verifyFormat("enum ns::X f() {\n" 3445 " a();\n" 3446 " return 42;\n" 3447 "}"); 3448 } 3449 3450 TEST_F(FormatTest, FormatsEnumsWithErrors) { 3451 verifyFormat("enum Type {\n" 3452 " One = 0; // These semicolons should be commas.\n" 3453 " Two = 1;\n" 3454 "};"); 3455 verifyFormat("namespace n {\n" 3456 "enum Type {\n" 3457 " One,\n" 3458 " Two, // missing };\n" 3459 " int i;\n" 3460 "}\n" 3461 "void g() {}"); 3462 } 3463 3464 TEST_F(FormatTest, FormatsEnumStruct) { 3465 verifyFormat("enum struct {\n" 3466 " Zero,\n" 3467 " One = 1,\n" 3468 " Two = One + 1,\n" 3469 " Three = (One + Two),\n" 3470 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3471 " Five = (One, Two, Three, Four, 5)\n" 3472 "};"); 3473 verifyFormat("enum struct Enum {};"); 3474 verifyFormat("enum struct {};"); 3475 verifyFormat("enum struct X E {} d;"); 3476 verifyFormat("enum struct __attribute__((...)) E {} d;"); 3477 verifyFormat("enum struct __declspec__((...)) E {} d;"); 3478 verifyFormat("enum struct X f() {\n a();\n return 42;\n}"); 3479 } 3480 3481 TEST_F(FormatTest, FormatsEnumClass) { 3482 verifyFormat("enum class {\n" 3483 " Zero,\n" 3484 " One = 1,\n" 3485 " Two = One + 1,\n" 3486 " Three = (One + Two),\n" 3487 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3488 " Five = (One, Two, Three, Four, 5)\n" 3489 "};"); 3490 verifyFormat("enum class Enum {};"); 3491 verifyFormat("enum class {};"); 3492 verifyFormat("enum class X E {} d;"); 3493 verifyFormat("enum class __attribute__((...)) E {} d;"); 3494 verifyFormat("enum class __declspec__((...)) E {} d;"); 3495 verifyFormat("enum class X f() {\n a();\n return 42;\n}"); 3496 } 3497 3498 TEST_F(FormatTest, FormatsEnumTypes) { 3499 verifyFormat("enum X : int {\n" 3500 " A, // Force multiple lines.\n" 3501 " B\n" 3502 "};"); 3503 verifyFormat("enum X : int { A, B };"); 3504 verifyFormat("enum X : std::uint32_t { A, B };"); 3505 } 3506 3507 TEST_F(FormatTest, FormatsTypedefEnum) { 3508 FormatStyle Style = getLLVMStyleWithColumns(40); 3509 verifyFormat("typedef enum {} EmptyEnum;"); 3510 verifyFormat("typedef enum { A, B, C } ShortEnum;"); 3511 verifyFormat("typedef enum {\n" 3512 " ZERO = 0,\n" 3513 " ONE = 1,\n" 3514 " TWO = 2,\n" 3515 " THREE = 3\n" 3516 "} LongEnum;", 3517 Style); 3518 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 3519 Style.BraceWrapping.AfterEnum = true; 3520 verifyFormat("typedef enum {} EmptyEnum;"); 3521 verifyFormat("typedef enum { A, B, C } ShortEnum;"); 3522 verifyFormat("typedef enum\n" 3523 "{\n" 3524 " ZERO = 0,\n" 3525 " ONE = 1,\n" 3526 " TWO = 2,\n" 3527 " THREE = 3\n" 3528 "} LongEnum;", 3529 Style); 3530 } 3531 3532 TEST_F(FormatTest, FormatsNSEnums) { 3533 verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }"); 3534 verifyGoogleFormat( 3535 "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }"); 3536 verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n" 3537 " // Information about someDecentlyLongValue.\n" 3538 " someDecentlyLongValue,\n" 3539 " // Information about anotherDecentlyLongValue.\n" 3540 " anotherDecentlyLongValue,\n" 3541 " // Information about aThirdDecentlyLongValue.\n" 3542 " aThirdDecentlyLongValue\n" 3543 "};"); 3544 verifyGoogleFormat("typedef NS_CLOSED_ENUM(NSInteger, MyType) {\n" 3545 " // Information about someDecentlyLongValue.\n" 3546 " someDecentlyLongValue,\n" 3547 " // Information about anotherDecentlyLongValue.\n" 3548 " anotherDecentlyLongValue,\n" 3549 " // Information about aThirdDecentlyLongValue.\n" 3550 " aThirdDecentlyLongValue\n" 3551 "};"); 3552 verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n" 3553 " a = 1,\n" 3554 " b = 2,\n" 3555 " c = 3,\n" 3556 "};"); 3557 verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n" 3558 " a = 1,\n" 3559 " b = 2,\n" 3560 " c = 3,\n" 3561 "};"); 3562 verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n" 3563 " a = 1,\n" 3564 " b = 2,\n" 3565 " c = 3,\n" 3566 "};"); 3567 verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n" 3568 " a = 1,\n" 3569 " b = 2,\n" 3570 " c = 3,\n" 3571 "};"); 3572 } 3573 3574 TEST_F(FormatTest, FormatsBitfields) { 3575 verifyFormat("struct Bitfields {\n" 3576 " unsigned sClass : 8;\n" 3577 " unsigned ValueKind : 2;\n" 3578 "};"); 3579 verifyFormat("struct A {\n" 3580 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n" 3581 " bbbbbbbbbbbbbbbbbbbbbbbbb;\n" 3582 "};"); 3583 verifyFormat("struct MyStruct {\n" 3584 " uchar data;\n" 3585 " uchar : 8;\n" 3586 " uchar : 8;\n" 3587 " uchar other;\n" 3588 "};"); 3589 FormatStyle Style = getLLVMStyle(); 3590 Style.BitFieldColonSpacing = FormatStyle::BFCS_None; 3591 verifyFormat("struct Bitfields {\n" 3592 " unsigned sClass:8;\n" 3593 " unsigned ValueKind:2;\n" 3594 " uchar other;\n" 3595 "};", 3596 Style); 3597 verifyFormat("struct A {\n" 3598 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:1,\n" 3599 " bbbbbbbbbbbbbbbbbbbbbbbbb:2;\n" 3600 "};", 3601 Style); 3602 Style.BitFieldColonSpacing = FormatStyle::BFCS_Before; 3603 verifyFormat("struct Bitfields {\n" 3604 " unsigned sClass :8;\n" 3605 " unsigned ValueKind :2;\n" 3606 " uchar other;\n" 3607 "};", 3608 Style); 3609 Style.BitFieldColonSpacing = FormatStyle::BFCS_After; 3610 verifyFormat("struct Bitfields {\n" 3611 " unsigned sClass: 8;\n" 3612 " unsigned ValueKind: 2;\n" 3613 " uchar other;\n" 3614 "};", 3615 Style); 3616 } 3617 3618 TEST_F(FormatTest, FormatsNamespaces) { 3619 FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle(); 3620 LLVMWithNoNamespaceFix.FixNamespaceComments = false; 3621 3622 verifyFormat("namespace some_namespace {\n" 3623 "class A {};\n" 3624 "void f() { f(); }\n" 3625 "}", 3626 LLVMWithNoNamespaceFix); 3627 verifyFormat("namespace N::inline D {\n" 3628 "class A {};\n" 3629 "void f() { f(); }\n" 3630 "}", 3631 LLVMWithNoNamespaceFix); 3632 verifyFormat("namespace N::inline D::E {\n" 3633 "class A {};\n" 3634 "void f() { f(); }\n" 3635 "}", 3636 LLVMWithNoNamespaceFix); 3637 verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n" 3638 "class A {};\n" 3639 "void f() { f(); }\n" 3640 "}", 3641 LLVMWithNoNamespaceFix); 3642 verifyFormat("/* something */ namespace some_namespace {\n" 3643 "class A {};\n" 3644 "void f() { f(); }\n" 3645 "}", 3646 LLVMWithNoNamespaceFix); 3647 verifyFormat("namespace {\n" 3648 "class A {};\n" 3649 "void f() { f(); }\n" 3650 "}", 3651 LLVMWithNoNamespaceFix); 3652 verifyFormat("/* something */ namespace {\n" 3653 "class A {};\n" 3654 "void f() { f(); }\n" 3655 "}", 3656 LLVMWithNoNamespaceFix); 3657 verifyFormat("inline namespace X {\n" 3658 "class A {};\n" 3659 "void f() { f(); }\n" 3660 "}", 3661 LLVMWithNoNamespaceFix); 3662 verifyFormat("/* something */ inline namespace X {\n" 3663 "class A {};\n" 3664 "void f() { f(); }\n" 3665 "}", 3666 LLVMWithNoNamespaceFix); 3667 verifyFormat("export namespace X {\n" 3668 "class A {};\n" 3669 "void f() { f(); }\n" 3670 "}", 3671 LLVMWithNoNamespaceFix); 3672 verifyFormat("using namespace some_namespace;\n" 3673 "class A {};\n" 3674 "void f() { f(); }", 3675 LLVMWithNoNamespaceFix); 3676 3677 // This code is more common than we thought; if we 3678 // layout this correctly the semicolon will go into 3679 // its own line, which is undesirable. 3680 verifyFormat("namespace {};", LLVMWithNoNamespaceFix); 3681 verifyFormat("namespace {\n" 3682 "class A {};\n" 3683 "};", 3684 LLVMWithNoNamespaceFix); 3685 3686 verifyFormat("namespace {\n" 3687 "int SomeVariable = 0; // comment\n" 3688 "} // namespace", 3689 LLVMWithNoNamespaceFix); 3690 EXPECT_EQ("#ifndef HEADER_GUARD\n" 3691 "#define HEADER_GUARD\n" 3692 "namespace my_namespace {\n" 3693 "int i;\n" 3694 "} // my_namespace\n" 3695 "#endif // HEADER_GUARD", 3696 format("#ifndef HEADER_GUARD\n" 3697 " #define HEADER_GUARD\n" 3698 " namespace my_namespace {\n" 3699 "int i;\n" 3700 "} // my_namespace\n" 3701 "#endif // HEADER_GUARD", 3702 LLVMWithNoNamespaceFix)); 3703 3704 EXPECT_EQ("namespace A::B {\n" 3705 "class C {};\n" 3706 "}", 3707 format("namespace A::B {\n" 3708 "class C {};\n" 3709 "}", 3710 LLVMWithNoNamespaceFix)); 3711 3712 FormatStyle Style = getLLVMStyle(); 3713 Style.NamespaceIndentation = FormatStyle::NI_All; 3714 EXPECT_EQ("namespace out {\n" 3715 " int i;\n" 3716 " namespace in {\n" 3717 " int i;\n" 3718 " } // namespace in\n" 3719 "} // namespace out", 3720 format("namespace out {\n" 3721 "int i;\n" 3722 "namespace in {\n" 3723 "int i;\n" 3724 "} // namespace in\n" 3725 "} // namespace out", 3726 Style)); 3727 3728 FormatStyle ShortInlineFunctions = getLLVMStyle(); 3729 ShortInlineFunctions.NamespaceIndentation = FormatStyle::NI_All; 3730 ShortInlineFunctions.AllowShortFunctionsOnASingleLine = 3731 FormatStyle::SFS_Inline; 3732 verifyFormat("namespace {\n" 3733 " void f() {\n" 3734 " return;\n" 3735 " }\n" 3736 "} // namespace\n", 3737 ShortInlineFunctions); 3738 verifyFormat("namespace {\n" 3739 " int some_int;\n" 3740 " void f() {\n" 3741 " return;\n" 3742 " }\n" 3743 "} // namespace\n", 3744 ShortInlineFunctions); 3745 verifyFormat("namespace interface {\n" 3746 " void f() {\n" 3747 " return;\n" 3748 " }\n" 3749 "} // namespace interface\n", 3750 ShortInlineFunctions); 3751 verifyFormat("namespace {\n" 3752 " class X {\n" 3753 " void f() { return; }\n" 3754 " };\n" 3755 "} // namespace\n", 3756 ShortInlineFunctions); 3757 verifyFormat("namespace {\n" 3758 " struct X {\n" 3759 " void f() { return; }\n" 3760 " };\n" 3761 "} // namespace\n", 3762 ShortInlineFunctions); 3763 verifyFormat("namespace {\n" 3764 " union X {\n" 3765 " void f() { return; }\n" 3766 " };\n" 3767 "} // namespace\n", 3768 ShortInlineFunctions); 3769 verifyFormat("extern \"C\" {\n" 3770 "void f() {\n" 3771 " return;\n" 3772 "}\n" 3773 "} // namespace\n", 3774 ShortInlineFunctions); 3775 verifyFormat("namespace {\n" 3776 " class X {\n" 3777 " void f() { return; }\n" 3778 " } x;\n" 3779 "} // namespace\n", 3780 ShortInlineFunctions); 3781 verifyFormat("namespace {\n" 3782 " [[nodiscard]] class X {\n" 3783 " void f() { return; }\n" 3784 " };\n" 3785 "} // namespace\n", 3786 ShortInlineFunctions); 3787 verifyFormat("namespace {\n" 3788 " static class X {\n" 3789 " void f() { return; }\n" 3790 " } x;\n" 3791 "} // namespace\n", 3792 ShortInlineFunctions); 3793 verifyFormat("namespace {\n" 3794 " constexpr class X {\n" 3795 " void f() { return; }\n" 3796 " } x;\n" 3797 "} // namespace\n", 3798 ShortInlineFunctions); 3799 3800 ShortInlineFunctions.IndentExternBlock = FormatStyle::IEBS_Indent; 3801 verifyFormat("extern \"C\" {\n" 3802 " void f() {\n" 3803 " return;\n" 3804 " }\n" 3805 "} // namespace\n", 3806 ShortInlineFunctions); 3807 3808 Style.NamespaceIndentation = FormatStyle::NI_Inner; 3809 EXPECT_EQ("namespace out {\n" 3810 "int i;\n" 3811 "namespace in {\n" 3812 " int i;\n" 3813 "} // namespace in\n" 3814 "} // namespace out", 3815 format("namespace out {\n" 3816 "int i;\n" 3817 "namespace in {\n" 3818 "int i;\n" 3819 "} // namespace in\n" 3820 "} // namespace out", 3821 Style)); 3822 3823 Style.NamespaceIndentation = FormatStyle::NI_None; 3824 verifyFormat("template <class T>\n" 3825 "concept a_concept = X<>;\n" 3826 "namespace B {\n" 3827 "struct b_struct {};\n" 3828 "} // namespace B\n", 3829 Style); 3830 verifyFormat("template <int I> constexpr void foo requires(I == 42) {}\n" 3831 "namespace ns {\n" 3832 "void foo() {}\n" 3833 "} // namespace ns\n", 3834 Style); 3835 } 3836 3837 TEST_F(FormatTest, NamespaceMacros) { 3838 FormatStyle Style = getLLVMStyle(); 3839 Style.NamespaceMacros.push_back("TESTSUITE"); 3840 3841 verifyFormat("TESTSUITE(A) {\n" 3842 "int foo();\n" 3843 "} // TESTSUITE(A)", 3844 Style); 3845 3846 verifyFormat("TESTSUITE(A, B) {\n" 3847 "int foo();\n" 3848 "} // TESTSUITE(A)", 3849 Style); 3850 3851 // Properly indent according to NamespaceIndentation style 3852 Style.NamespaceIndentation = FormatStyle::NI_All; 3853 verifyFormat("TESTSUITE(A) {\n" 3854 " int foo();\n" 3855 "} // TESTSUITE(A)", 3856 Style); 3857 verifyFormat("TESTSUITE(A) {\n" 3858 " namespace B {\n" 3859 " int foo();\n" 3860 " } // namespace B\n" 3861 "} // TESTSUITE(A)", 3862 Style); 3863 verifyFormat("namespace A {\n" 3864 " TESTSUITE(B) {\n" 3865 " int foo();\n" 3866 " } // TESTSUITE(B)\n" 3867 "} // namespace A", 3868 Style); 3869 3870 Style.NamespaceIndentation = FormatStyle::NI_Inner; 3871 verifyFormat("TESTSUITE(A) {\n" 3872 "TESTSUITE(B) {\n" 3873 " int foo();\n" 3874 "} // TESTSUITE(B)\n" 3875 "} // TESTSUITE(A)", 3876 Style); 3877 verifyFormat("TESTSUITE(A) {\n" 3878 "namespace B {\n" 3879 " int foo();\n" 3880 "} // namespace B\n" 3881 "} // TESTSUITE(A)", 3882 Style); 3883 verifyFormat("namespace A {\n" 3884 "TESTSUITE(B) {\n" 3885 " int foo();\n" 3886 "} // TESTSUITE(B)\n" 3887 "} // namespace A", 3888 Style); 3889 3890 // Properly merge namespace-macros blocks in CompactNamespaces mode 3891 Style.NamespaceIndentation = FormatStyle::NI_None; 3892 Style.CompactNamespaces = true; 3893 verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n" 3894 "}} // TESTSUITE(A::B)", 3895 Style); 3896 3897 EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n" 3898 "}} // TESTSUITE(out::in)", 3899 format("TESTSUITE(out) {\n" 3900 "TESTSUITE(in) {\n" 3901 "} // TESTSUITE(in)\n" 3902 "} // TESTSUITE(out)", 3903 Style)); 3904 3905 EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n" 3906 "}} // TESTSUITE(out::in)", 3907 format("TESTSUITE(out) {\n" 3908 "TESTSUITE(in) {\n" 3909 "} // TESTSUITE(in)\n" 3910 "} // TESTSUITE(out)", 3911 Style)); 3912 3913 // Do not merge different namespaces/macros 3914 EXPECT_EQ("namespace out {\n" 3915 "TESTSUITE(in) {\n" 3916 "} // TESTSUITE(in)\n" 3917 "} // namespace out", 3918 format("namespace out {\n" 3919 "TESTSUITE(in) {\n" 3920 "} // TESTSUITE(in)\n" 3921 "} // namespace out", 3922 Style)); 3923 EXPECT_EQ("TESTSUITE(out) {\n" 3924 "namespace in {\n" 3925 "} // namespace in\n" 3926 "} // TESTSUITE(out)", 3927 format("TESTSUITE(out) {\n" 3928 "namespace in {\n" 3929 "} // namespace in\n" 3930 "} // TESTSUITE(out)", 3931 Style)); 3932 Style.NamespaceMacros.push_back("FOOBAR"); 3933 EXPECT_EQ("TESTSUITE(out) {\n" 3934 "FOOBAR(in) {\n" 3935 "} // FOOBAR(in)\n" 3936 "} // TESTSUITE(out)", 3937 format("TESTSUITE(out) {\n" 3938 "FOOBAR(in) {\n" 3939 "} // FOOBAR(in)\n" 3940 "} // TESTSUITE(out)", 3941 Style)); 3942 } 3943 3944 TEST_F(FormatTest, FormatsCompactNamespaces) { 3945 FormatStyle Style = getLLVMStyle(); 3946 Style.CompactNamespaces = true; 3947 Style.NamespaceMacros.push_back("TESTSUITE"); 3948 3949 verifyFormat("namespace A { namespace B {\n" 3950 "}} // namespace A::B", 3951 Style); 3952 3953 EXPECT_EQ("namespace out { namespace in {\n" 3954 "}} // namespace out::in", 3955 format("namespace out {\n" 3956 "namespace in {\n" 3957 "} // namespace in\n" 3958 "} // namespace out", 3959 Style)); 3960 3961 // Only namespaces which have both consecutive opening and end get compacted 3962 EXPECT_EQ("namespace out {\n" 3963 "namespace in1 {\n" 3964 "} // namespace in1\n" 3965 "namespace in2 {\n" 3966 "} // namespace in2\n" 3967 "} // namespace out", 3968 format("namespace out {\n" 3969 "namespace in1 {\n" 3970 "} // namespace in1\n" 3971 "namespace in2 {\n" 3972 "} // namespace in2\n" 3973 "} // namespace out", 3974 Style)); 3975 3976 EXPECT_EQ("namespace out {\n" 3977 "int i;\n" 3978 "namespace in {\n" 3979 "int j;\n" 3980 "} // namespace in\n" 3981 "int k;\n" 3982 "} // namespace out", 3983 format("namespace out { int i;\n" 3984 "namespace in { int j; } // namespace in\n" 3985 "int k; } // namespace out", 3986 Style)); 3987 3988 EXPECT_EQ("namespace A { namespace B { namespace C {\n" 3989 "}}} // namespace A::B::C\n", 3990 format("namespace A { namespace B {\n" 3991 "namespace C {\n" 3992 "}} // namespace B::C\n" 3993 "} // namespace A\n", 3994 Style)); 3995 3996 Style.ColumnLimit = 40; 3997 EXPECT_EQ("namespace aaaaaaaaaa {\n" 3998 "namespace bbbbbbbbbb {\n" 3999 "}} // namespace aaaaaaaaaa::bbbbbbbbbb", 4000 format("namespace aaaaaaaaaa {\n" 4001 "namespace bbbbbbbbbb {\n" 4002 "} // namespace bbbbbbbbbb\n" 4003 "} // namespace aaaaaaaaaa", 4004 Style)); 4005 4006 EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n" 4007 "namespace cccccc {\n" 4008 "}}} // namespace aaaaaa::bbbbbb::cccccc", 4009 format("namespace aaaaaa {\n" 4010 "namespace bbbbbb {\n" 4011 "namespace cccccc {\n" 4012 "} // namespace cccccc\n" 4013 "} // namespace bbbbbb\n" 4014 "} // namespace aaaaaa", 4015 Style)); 4016 Style.ColumnLimit = 80; 4017 4018 // Extra semicolon after 'inner' closing brace prevents merging 4019 EXPECT_EQ("namespace out { namespace in {\n" 4020 "}; } // namespace out::in", 4021 format("namespace out {\n" 4022 "namespace in {\n" 4023 "}; // namespace in\n" 4024 "} // namespace out", 4025 Style)); 4026 4027 // Extra semicolon after 'outer' closing brace is conserved 4028 EXPECT_EQ("namespace out { namespace in {\n" 4029 "}}; // namespace out::in", 4030 format("namespace out {\n" 4031 "namespace in {\n" 4032 "} // namespace in\n" 4033 "}; // namespace out", 4034 Style)); 4035 4036 Style.NamespaceIndentation = FormatStyle::NI_All; 4037 EXPECT_EQ("namespace out { namespace in {\n" 4038 " int i;\n" 4039 "}} // namespace out::in", 4040 format("namespace out {\n" 4041 "namespace in {\n" 4042 "int i;\n" 4043 "} // namespace in\n" 4044 "} // namespace out", 4045 Style)); 4046 EXPECT_EQ("namespace out { namespace mid {\n" 4047 " namespace in {\n" 4048 " int j;\n" 4049 " } // namespace in\n" 4050 " int k;\n" 4051 "}} // namespace out::mid", 4052 format("namespace out { namespace mid {\n" 4053 "namespace in { int j; } // namespace in\n" 4054 "int k; }} // namespace out::mid", 4055 Style)); 4056 4057 Style.NamespaceIndentation = FormatStyle::NI_Inner; 4058 EXPECT_EQ("namespace out { namespace in {\n" 4059 " int i;\n" 4060 "}} // namespace out::in", 4061 format("namespace out {\n" 4062 "namespace in {\n" 4063 "int i;\n" 4064 "} // namespace in\n" 4065 "} // namespace out", 4066 Style)); 4067 EXPECT_EQ("namespace out { namespace mid { namespace in {\n" 4068 " int i;\n" 4069 "}}} // namespace out::mid::in", 4070 format("namespace out {\n" 4071 "namespace mid {\n" 4072 "namespace in {\n" 4073 "int i;\n" 4074 "} // namespace in\n" 4075 "} // namespace mid\n" 4076 "} // namespace out", 4077 Style)); 4078 4079 Style.CompactNamespaces = true; 4080 Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 4081 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4082 Style.BraceWrapping.BeforeLambdaBody = true; 4083 verifyFormat("namespace out { namespace in {\n" 4084 "}} // namespace out::in", 4085 Style); 4086 EXPECT_EQ("namespace out { namespace in {\n" 4087 "}} // namespace out::in", 4088 format("namespace out {\n" 4089 "namespace in {\n" 4090 "} // namespace in\n" 4091 "} // namespace out", 4092 Style)); 4093 } 4094 4095 TEST_F(FormatTest, FormatsExternC) { 4096 verifyFormat("extern \"C\" {\nint a;"); 4097 verifyFormat("extern \"C\" {}"); 4098 verifyFormat("extern \"C\" {\n" 4099 "int foo();\n" 4100 "}"); 4101 verifyFormat("extern \"C\" int foo() {}"); 4102 verifyFormat("extern \"C\" int foo();"); 4103 verifyFormat("extern \"C\" int foo() {\n" 4104 " int i = 42;\n" 4105 " return i;\n" 4106 "}"); 4107 4108 FormatStyle Style = getLLVMStyle(); 4109 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4110 Style.BraceWrapping.AfterFunction = true; 4111 verifyFormat("extern \"C\" int foo() {}", Style); 4112 verifyFormat("extern \"C\" int foo();", Style); 4113 verifyFormat("extern \"C\" int foo()\n" 4114 "{\n" 4115 " int i = 42;\n" 4116 " return i;\n" 4117 "}", 4118 Style); 4119 4120 Style.BraceWrapping.AfterExternBlock = true; 4121 Style.BraceWrapping.SplitEmptyRecord = false; 4122 verifyFormat("extern \"C\"\n" 4123 "{}", 4124 Style); 4125 verifyFormat("extern \"C\"\n" 4126 "{\n" 4127 " int foo();\n" 4128 "}", 4129 Style); 4130 } 4131 4132 TEST_F(FormatTest, IndentExternBlockStyle) { 4133 FormatStyle Style = getLLVMStyle(); 4134 Style.IndentWidth = 2; 4135 4136 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4137 verifyFormat("extern \"C\" { /*9*/\n" 4138 "}", 4139 Style); 4140 verifyFormat("extern \"C\" {\n" 4141 " int foo10();\n" 4142 "}", 4143 Style); 4144 4145 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 4146 verifyFormat("extern \"C\" { /*11*/\n" 4147 "}", 4148 Style); 4149 verifyFormat("extern \"C\" {\n" 4150 "int foo12();\n" 4151 "}", 4152 Style); 4153 4154 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4155 Style.BraceWrapping.AfterExternBlock = true; 4156 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4157 verifyFormat("extern \"C\"\n" 4158 "{ /*13*/\n" 4159 "}", 4160 Style); 4161 verifyFormat("extern \"C\"\n{\n" 4162 " int foo14();\n" 4163 "}", 4164 Style); 4165 4166 Style.BraceWrapping.AfterExternBlock = false; 4167 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 4168 verifyFormat("extern \"C\" { /*15*/\n" 4169 "}", 4170 Style); 4171 verifyFormat("extern \"C\" {\n" 4172 "int foo16();\n" 4173 "}", 4174 Style); 4175 4176 Style.BraceWrapping.AfterExternBlock = true; 4177 verifyFormat("extern \"C\"\n" 4178 "{ /*13*/\n" 4179 "}", 4180 Style); 4181 verifyFormat("extern \"C\"\n" 4182 "{\n" 4183 "int foo14();\n" 4184 "}", 4185 Style); 4186 4187 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4188 verifyFormat("extern \"C\"\n" 4189 "{ /*13*/\n" 4190 "}", 4191 Style); 4192 verifyFormat("extern \"C\"\n" 4193 "{\n" 4194 " int foo14();\n" 4195 "}", 4196 Style); 4197 } 4198 4199 TEST_F(FormatTest, FormatsInlineASM) { 4200 verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));"); 4201 verifyFormat("asm(\"nop\" ::: \"memory\");"); 4202 verifyFormat( 4203 "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n" 4204 " \"cpuid\\n\\t\"\n" 4205 " \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n" 4206 " : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n" 4207 " : \"a\"(value));"); 4208 EXPECT_EQ( 4209 "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n" 4210 " __asm {\n" 4211 " mov edx,[that] // vtable in edx\n" 4212 " mov eax,methodIndex\n" 4213 " call [edx][eax*4] // stdcall\n" 4214 " }\n" 4215 "}", 4216 format("void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n" 4217 " __asm {\n" 4218 " mov edx,[that] // vtable in edx\n" 4219 " mov eax,methodIndex\n" 4220 " call [edx][eax*4] // stdcall\n" 4221 " }\n" 4222 "}")); 4223 EXPECT_EQ("_asm {\n" 4224 " xor eax, eax;\n" 4225 " cpuid;\n" 4226 "}", 4227 format("_asm {\n" 4228 " xor eax, eax;\n" 4229 " cpuid;\n" 4230 "}")); 4231 verifyFormat("void function() {\n" 4232 " // comment\n" 4233 " asm(\"\");\n" 4234 "}"); 4235 EXPECT_EQ("__asm {\n" 4236 "}\n" 4237 "int i;", 4238 format("__asm {\n" 4239 "}\n" 4240 "int i;")); 4241 } 4242 4243 TEST_F(FormatTest, FormatTryCatch) { 4244 verifyFormat("try {\n" 4245 " throw a * b;\n" 4246 "} catch (int a) {\n" 4247 " // Do nothing.\n" 4248 "} catch (...) {\n" 4249 " exit(42);\n" 4250 "}"); 4251 4252 // Function-level try statements. 4253 verifyFormat("int f() try { return 4; } catch (...) {\n" 4254 " return 5;\n" 4255 "}"); 4256 verifyFormat("class A {\n" 4257 " int a;\n" 4258 " A() try : a(0) {\n" 4259 " } catch (...) {\n" 4260 " throw;\n" 4261 " }\n" 4262 "};\n"); 4263 verifyFormat("class A {\n" 4264 " int a;\n" 4265 " A() try : a(0), b{1} {\n" 4266 " } catch (...) {\n" 4267 " throw;\n" 4268 " }\n" 4269 "};\n"); 4270 verifyFormat("class A {\n" 4271 " int a;\n" 4272 " A() try : a(0), b{1}, c{2} {\n" 4273 " } catch (...) {\n" 4274 " throw;\n" 4275 " }\n" 4276 "};\n"); 4277 verifyFormat("class A {\n" 4278 " int a;\n" 4279 " A() try : a(0), b{1}, c{2} {\n" 4280 " { // New scope.\n" 4281 " }\n" 4282 " } catch (...) {\n" 4283 " throw;\n" 4284 " }\n" 4285 "};\n"); 4286 4287 // Incomplete try-catch blocks. 4288 verifyIncompleteFormat("try {} catch ("); 4289 } 4290 4291 TEST_F(FormatTest, FormatTryAsAVariable) { 4292 verifyFormat("int try;"); 4293 verifyFormat("int try, size;"); 4294 verifyFormat("try = foo();"); 4295 verifyFormat("if (try < size) {\n return true;\n}"); 4296 4297 verifyFormat("int catch;"); 4298 verifyFormat("int catch, size;"); 4299 verifyFormat("catch = foo();"); 4300 verifyFormat("if (catch < size) {\n return true;\n}"); 4301 4302 FormatStyle Style = getLLVMStyle(); 4303 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4304 Style.BraceWrapping.AfterFunction = true; 4305 Style.BraceWrapping.BeforeCatch = true; 4306 verifyFormat("try {\n" 4307 " int bar = 1;\n" 4308 "}\n" 4309 "catch (...) {\n" 4310 " int bar = 1;\n" 4311 "}", 4312 Style); 4313 verifyFormat("#if NO_EX\n" 4314 "try\n" 4315 "#endif\n" 4316 "{\n" 4317 "}\n" 4318 "#if NO_EX\n" 4319 "catch (...) {\n" 4320 "}", 4321 Style); 4322 verifyFormat("try /* abc */ {\n" 4323 " int bar = 1;\n" 4324 "}\n" 4325 "catch (...) {\n" 4326 " int bar = 1;\n" 4327 "}", 4328 Style); 4329 verifyFormat("try\n" 4330 "// abc\n" 4331 "{\n" 4332 " int bar = 1;\n" 4333 "}\n" 4334 "catch (...) {\n" 4335 " int bar = 1;\n" 4336 "}", 4337 Style); 4338 } 4339 4340 TEST_F(FormatTest, FormatSEHTryCatch) { 4341 verifyFormat("__try {\n" 4342 " int a = b * c;\n" 4343 "} __except (EXCEPTION_EXECUTE_HANDLER) {\n" 4344 " // Do nothing.\n" 4345 "}"); 4346 4347 verifyFormat("__try {\n" 4348 " int a = b * c;\n" 4349 "} __finally {\n" 4350 " // Do nothing.\n" 4351 "}"); 4352 4353 verifyFormat("DEBUG({\n" 4354 " __try {\n" 4355 " } __finally {\n" 4356 " }\n" 4357 "});\n"); 4358 } 4359 4360 TEST_F(FormatTest, IncompleteTryCatchBlocks) { 4361 verifyFormat("try {\n" 4362 " f();\n" 4363 "} catch {\n" 4364 " g();\n" 4365 "}"); 4366 verifyFormat("try {\n" 4367 " f();\n" 4368 "} catch (A a) MACRO(x) {\n" 4369 " g();\n" 4370 "} catch (B b) MACRO(x) {\n" 4371 " g();\n" 4372 "}"); 4373 } 4374 4375 TEST_F(FormatTest, FormatTryCatchBraceStyles) { 4376 FormatStyle Style = getLLVMStyle(); 4377 for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla, 4378 FormatStyle::BS_WebKit}) { 4379 Style.BreakBeforeBraces = BraceStyle; 4380 verifyFormat("try {\n" 4381 " // something\n" 4382 "} catch (...) {\n" 4383 " // something\n" 4384 "}", 4385 Style); 4386 } 4387 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 4388 verifyFormat("try {\n" 4389 " // something\n" 4390 "}\n" 4391 "catch (...) {\n" 4392 " // something\n" 4393 "}", 4394 Style); 4395 verifyFormat("__try {\n" 4396 " // something\n" 4397 "}\n" 4398 "__finally {\n" 4399 " // something\n" 4400 "}", 4401 Style); 4402 verifyFormat("@try {\n" 4403 " // something\n" 4404 "}\n" 4405 "@finally {\n" 4406 " // something\n" 4407 "}", 4408 Style); 4409 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 4410 verifyFormat("try\n" 4411 "{\n" 4412 " // something\n" 4413 "}\n" 4414 "catch (...)\n" 4415 "{\n" 4416 " // something\n" 4417 "}", 4418 Style); 4419 Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 4420 verifyFormat("try\n" 4421 " {\n" 4422 " // something white\n" 4423 " }\n" 4424 "catch (...)\n" 4425 " {\n" 4426 " // something white\n" 4427 " }", 4428 Style); 4429 Style.BreakBeforeBraces = FormatStyle::BS_GNU; 4430 verifyFormat("try\n" 4431 " {\n" 4432 " // something\n" 4433 " }\n" 4434 "catch (...)\n" 4435 " {\n" 4436 " // something\n" 4437 " }", 4438 Style); 4439 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4440 Style.BraceWrapping.BeforeCatch = true; 4441 verifyFormat("try {\n" 4442 " // something\n" 4443 "}\n" 4444 "catch (...) {\n" 4445 " // something\n" 4446 "}", 4447 Style); 4448 } 4449 4450 TEST_F(FormatTest, StaticInitializers) { 4451 verifyFormat("static SomeClass SC = {1, 'a'};"); 4452 4453 verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n" 4454 " 100000000, " 4455 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};"); 4456 4457 // Here, everything other than the "}" would fit on a line. 4458 verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n" 4459 " 10000000000000000000000000};"); 4460 EXPECT_EQ("S s = {a,\n" 4461 "\n" 4462 " b};", 4463 format("S s = {\n" 4464 " a,\n" 4465 "\n" 4466 " b\n" 4467 "};")); 4468 4469 // FIXME: This would fit into the column limit if we'd fit "{ {" on the first 4470 // line. However, the formatting looks a bit off and this probably doesn't 4471 // happen often in practice. 4472 verifyFormat("static int Variable[1] = {\n" 4473 " {1000000000000000000000000000000000000}};", 4474 getLLVMStyleWithColumns(40)); 4475 } 4476 4477 TEST_F(FormatTest, DesignatedInitializers) { 4478 verifyFormat("const struct A a = {.a = 1, .b = 2};"); 4479 verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n" 4480 " .bbbbbbbbbb = 2,\n" 4481 " .cccccccccc = 3,\n" 4482 " .dddddddddd = 4,\n" 4483 " .eeeeeeeeee = 5};"); 4484 verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n" 4485 " .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n" 4486 " .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n" 4487 " .ccccccccccccccccccccccccccc = 3,\n" 4488 " .ddddddddddddddddddddddddddd = 4,\n" 4489 " .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};"); 4490 4491 verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};"); 4492 4493 verifyFormat("const struct A a = {[0] = 1, [1] = 2};"); 4494 verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n" 4495 " [2] = bbbbbbbbbb,\n" 4496 " [3] = cccccccccc,\n" 4497 " [4] = dddddddddd,\n" 4498 " [5] = eeeeeeeeee};"); 4499 verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n" 4500 " [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 4501 " [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 4502 " [3] = cccccccccccccccccccccccccccccccccccccc,\n" 4503 " [4] = dddddddddddddddddddddddddddddddddddddd,\n" 4504 " [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};"); 4505 } 4506 4507 TEST_F(FormatTest, NestedStaticInitializers) { 4508 verifyFormat("static A x = {{{}}};\n"); 4509 verifyFormat("static A x = {{{init1, init2, init3, init4},\n" 4510 " {init1, init2, init3, init4}}};", 4511 getLLVMStyleWithColumns(50)); 4512 4513 verifyFormat("somes Status::global_reps[3] = {\n" 4514 " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n" 4515 " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n" 4516 " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};", 4517 getLLVMStyleWithColumns(60)); 4518 verifyGoogleFormat("SomeType Status::global_reps[3] = {\n" 4519 " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n" 4520 " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n" 4521 " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};"); 4522 verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n" 4523 " {rect.fRight - rect.fLeft, rect.fBottom - " 4524 "rect.fTop}};"); 4525 4526 verifyFormat( 4527 "SomeArrayOfSomeType a = {\n" 4528 " {{1, 2, 3},\n" 4529 " {1, 2, 3},\n" 4530 " {111111111111111111111111111111, 222222222222222222222222222222,\n" 4531 " 333333333333333333333333333333},\n" 4532 " {1, 2, 3},\n" 4533 " {1, 2, 3}}};"); 4534 verifyFormat( 4535 "SomeArrayOfSomeType a = {\n" 4536 " {{1, 2, 3}},\n" 4537 " {{1, 2, 3}},\n" 4538 " {{111111111111111111111111111111, 222222222222222222222222222222,\n" 4539 " 333333333333333333333333333333}},\n" 4540 " {{1, 2, 3}},\n" 4541 " {{1, 2, 3}}};"); 4542 4543 verifyFormat("struct {\n" 4544 " unsigned bit;\n" 4545 " const char *const name;\n" 4546 "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n" 4547 " {kOsWin, \"Windows\"},\n" 4548 " {kOsLinux, \"Linux\"},\n" 4549 " {kOsCrOS, \"Chrome OS\"}};"); 4550 verifyFormat("struct {\n" 4551 " unsigned bit;\n" 4552 " const char *const name;\n" 4553 "} kBitsToOs[] = {\n" 4554 " {kOsMac, \"Mac\"},\n" 4555 " {kOsWin, \"Windows\"},\n" 4556 " {kOsLinux, \"Linux\"},\n" 4557 " {kOsCrOS, \"Chrome OS\"},\n" 4558 "};"); 4559 } 4560 4561 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) { 4562 verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro(" 4563 " \\\n" 4564 " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)"); 4565 } 4566 4567 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) { 4568 verifyFormat("virtual void write(ELFWriter *writerrr,\n" 4569 " OwningPtr<FileOutputBuffer> &buffer) = 0;"); 4570 4571 // Do break defaulted and deleted functions. 4572 verifyFormat("virtual void ~Deeeeeeeestructor() =\n" 4573 " default;", 4574 getLLVMStyleWithColumns(40)); 4575 verifyFormat("virtual void ~Deeeeeeeestructor() =\n" 4576 " delete;", 4577 getLLVMStyleWithColumns(40)); 4578 } 4579 4580 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) { 4581 verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3", 4582 getLLVMStyleWithColumns(40)); 4583 verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"", 4584 getLLVMStyleWithColumns(40)); 4585 EXPECT_EQ("#define Q \\\n" 4586 " \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\" \\\n" 4587 " \"aaaaaaaa.cpp\"", 4588 format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"", 4589 getLLVMStyleWithColumns(40))); 4590 } 4591 4592 TEST_F(FormatTest, UnderstandsLinePPDirective) { 4593 EXPECT_EQ("# 123 \"A string literal\"", 4594 format(" # 123 \"A string literal\"")); 4595 } 4596 4597 TEST_F(FormatTest, LayoutUnknownPPDirective) { 4598 EXPECT_EQ("#;", format("#;")); 4599 verifyFormat("#\n;\n;\n;"); 4600 } 4601 4602 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) { 4603 EXPECT_EQ("#line 42 \"test\"\n", 4604 format("# \\\n line \\\n 42 \\\n \"test\"\n")); 4605 EXPECT_EQ("#define A B\n", format("# \\\n define \\\n A \\\n B\n", 4606 getLLVMStyleWithColumns(12))); 4607 } 4608 4609 TEST_F(FormatTest, EndOfFileEndsPPDirective) { 4610 EXPECT_EQ("#line 42 \"test\"", 4611 format("# \\\n line \\\n 42 \\\n \"test\"")); 4612 EXPECT_EQ("#define A B", format("# \\\n define \\\n A \\\n B")); 4613 } 4614 4615 TEST_F(FormatTest, DoesntRemoveUnknownTokens) { 4616 verifyFormat("#define A \\x20"); 4617 verifyFormat("#define A \\ x20"); 4618 EXPECT_EQ("#define A \\ x20", format("#define A \\ x20")); 4619 verifyFormat("#define A ''"); 4620 verifyFormat("#define A ''qqq"); 4621 verifyFormat("#define A `qqq"); 4622 verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");"); 4623 EXPECT_EQ("const char *c = STRINGIFY(\n" 4624 "\\na : b);", 4625 format("const char * c = STRINGIFY(\n" 4626 "\\na : b);")); 4627 4628 verifyFormat("a\r\\"); 4629 verifyFormat("a\v\\"); 4630 verifyFormat("a\f\\"); 4631 } 4632 4633 TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) { 4634 FormatStyle style = getChromiumStyle(FormatStyle::LK_Cpp); 4635 style.IndentWidth = 4; 4636 style.PPIndentWidth = 1; 4637 4638 style.IndentPPDirectives = FormatStyle::PPDIS_None; 4639 verifyFormat("#ifdef __linux__\n" 4640 "void foo() {\n" 4641 " int x = 0;\n" 4642 "}\n" 4643 "#define FOO\n" 4644 "#endif\n" 4645 "void bar() {\n" 4646 " int y = 0;\n" 4647 "}\n", 4648 style); 4649 4650 style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash; 4651 verifyFormat("#ifdef __linux__\n" 4652 "void foo() {\n" 4653 " int x = 0;\n" 4654 "}\n" 4655 "# define FOO foo\n" 4656 "#endif\n" 4657 "void bar() {\n" 4658 " int y = 0;\n" 4659 "}\n", 4660 style); 4661 4662 style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash; 4663 verifyFormat("#ifdef __linux__\n" 4664 "void foo() {\n" 4665 " int x = 0;\n" 4666 "}\n" 4667 " #define FOO foo\n" 4668 "#endif\n" 4669 "void bar() {\n" 4670 " int y = 0;\n" 4671 "}\n", 4672 style); 4673 } 4674 4675 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) { 4676 verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13)); 4677 verifyFormat("#define A( \\\n BB)", getLLVMStyleWithColumns(12)); 4678 verifyFormat("#define A( \\\n A, B)", getLLVMStyleWithColumns(12)); 4679 // FIXME: We never break before the macro name. 4680 verifyFormat("#define AA( \\\n B)", getLLVMStyleWithColumns(12)); 4681 4682 verifyFormat("#define A A\n#define A A"); 4683 verifyFormat("#define A(X) A\n#define A A"); 4684 4685 verifyFormat("#define Something Other", getLLVMStyleWithColumns(23)); 4686 verifyFormat("#define Something \\\n Other", getLLVMStyleWithColumns(22)); 4687 } 4688 4689 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) { 4690 EXPECT_EQ("// somecomment\n" 4691 "#include \"a.h\"\n" 4692 "#define A( \\\n" 4693 " A, B)\n" 4694 "#include \"b.h\"\n" 4695 "// somecomment\n", 4696 format(" // somecomment\n" 4697 " #include \"a.h\"\n" 4698 "#define A(A,\\\n" 4699 " B)\n" 4700 " #include \"b.h\"\n" 4701 " // somecomment\n", 4702 getLLVMStyleWithColumns(13))); 4703 } 4704 4705 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); } 4706 4707 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) { 4708 EXPECT_EQ("#define A \\\n" 4709 " c; \\\n" 4710 " e;\n" 4711 "f;", 4712 format("#define A c; e;\n" 4713 "f;", 4714 getLLVMStyleWithColumns(14))); 4715 } 4716 4717 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); } 4718 4719 TEST_F(FormatTest, MacroDefinitionInsideStatement) { 4720 EXPECT_EQ("int x,\n" 4721 "#define A\n" 4722 " y;", 4723 format("int x,\n#define A\ny;")); 4724 } 4725 4726 TEST_F(FormatTest, HashInMacroDefinition) { 4727 EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle())); 4728 EXPECT_EQ("#define A(c) u#c", format("#define A(c) u#c", getLLVMStyle())); 4729 EXPECT_EQ("#define A(c) U#c", format("#define A(c) U#c", getLLVMStyle())); 4730 EXPECT_EQ("#define A(c) u8#c", format("#define A(c) u8#c", getLLVMStyle())); 4731 EXPECT_EQ("#define A(c) LR#c", format("#define A(c) LR#c", getLLVMStyle())); 4732 EXPECT_EQ("#define A(c) uR#c", format("#define A(c) uR#c", getLLVMStyle())); 4733 EXPECT_EQ("#define A(c) UR#c", format("#define A(c) UR#c", getLLVMStyle())); 4734 EXPECT_EQ("#define A(c) u8R#c", format("#define A(c) u8R#c", getLLVMStyle())); 4735 verifyFormat("#define A \\\n b #c;", getLLVMStyleWithColumns(11)); 4736 verifyFormat("#define A \\\n" 4737 " { \\\n" 4738 " f(#c); \\\n" 4739 " }", 4740 getLLVMStyleWithColumns(11)); 4741 4742 verifyFormat("#define A(X) \\\n" 4743 " void function##X()", 4744 getLLVMStyleWithColumns(22)); 4745 4746 verifyFormat("#define A(a, b, c) \\\n" 4747 " void a##b##c()", 4748 getLLVMStyleWithColumns(22)); 4749 4750 verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22)); 4751 } 4752 4753 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) { 4754 EXPECT_EQ("#define A (x)", format("#define A (x)")); 4755 EXPECT_EQ("#define A(x)", format("#define A(x)")); 4756 4757 FormatStyle Style = getLLVMStyle(); 4758 Style.SpaceBeforeParens = FormatStyle::SBPO_Never; 4759 verifyFormat("#define true ((foo)1)", Style); 4760 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 4761 verifyFormat("#define false((foo)0)", Style); 4762 } 4763 4764 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) { 4765 EXPECT_EQ("#define A b;", format("#define A \\\n" 4766 " \\\n" 4767 " b;", 4768 getLLVMStyleWithColumns(25))); 4769 EXPECT_EQ("#define A \\\n" 4770 " \\\n" 4771 " a; \\\n" 4772 " b;", 4773 format("#define A \\\n" 4774 " \\\n" 4775 " a; \\\n" 4776 " b;", 4777 getLLVMStyleWithColumns(11))); 4778 EXPECT_EQ("#define A \\\n" 4779 " a; \\\n" 4780 " \\\n" 4781 " b;", 4782 format("#define A \\\n" 4783 " a; \\\n" 4784 " \\\n" 4785 " b;", 4786 getLLVMStyleWithColumns(11))); 4787 } 4788 4789 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) { 4790 verifyIncompleteFormat("#define A :"); 4791 verifyFormat("#define SOMECASES \\\n" 4792 " case 1: \\\n" 4793 " case 2\n", 4794 getLLVMStyleWithColumns(20)); 4795 verifyFormat("#define MACRO(a) \\\n" 4796 " if (a) \\\n" 4797 " f(); \\\n" 4798 " else \\\n" 4799 " g()", 4800 getLLVMStyleWithColumns(18)); 4801 verifyFormat("#define A template <typename T>"); 4802 verifyIncompleteFormat("#define STR(x) #x\n" 4803 "f(STR(this_is_a_string_literal{));"); 4804 verifyFormat("#pragma omp threadprivate( \\\n" 4805 " y)), // expected-warning", 4806 getLLVMStyleWithColumns(28)); 4807 verifyFormat("#d, = };"); 4808 verifyFormat("#if \"a"); 4809 verifyIncompleteFormat("({\n" 4810 "#define b \\\n" 4811 " } \\\n" 4812 " a\n" 4813 "a", 4814 getLLVMStyleWithColumns(15)); 4815 verifyFormat("#define A \\\n" 4816 " { \\\n" 4817 " {\n" 4818 "#define B \\\n" 4819 " } \\\n" 4820 " }", 4821 getLLVMStyleWithColumns(15)); 4822 verifyNoCrash("#if a\na(\n#else\n#endif\n{a"); 4823 verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}"); 4824 verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};"); 4825 verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() { \n)}"); 4826 } 4827 4828 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) { 4829 verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline. 4830 EXPECT_EQ("class A : public QObject {\n" 4831 " Q_OBJECT\n" 4832 "\n" 4833 " A() {}\n" 4834 "};", 4835 format("class A : public QObject {\n" 4836 " Q_OBJECT\n" 4837 "\n" 4838 " A() {\n}\n" 4839 "} ;")); 4840 EXPECT_EQ("MACRO\n" 4841 "/*static*/ int i;", 4842 format("MACRO\n" 4843 " /*static*/ int i;")); 4844 EXPECT_EQ("SOME_MACRO\n" 4845 "namespace {\n" 4846 "void f();\n" 4847 "} // namespace", 4848 format("SOME_MACRO\n" 4849 " namespace {\n" 4850 "void f( );\n" 4851 "} // namespace")); 4852 // Only if the identifier contains at least 5 characters. 4853 EXPECT_EQ("HTTP f();", format("HTTP\nf();")); 4854 EXPECT_EQ("MACRO\nf();", format("MACRO\nf();")); 4855 // Only if everything is upper case. 4856 EXPECT_EQ("class A : public QObject {\n" 4857 " Q_Object A() {}\n" 4858 "};", 4859 format("class A : public QObject {\n" 4860 " Q_Object\n" 4861 " A() {\n}\n" 4862 "} ;")); 4863 4864 // Only if the next line can actually start an unwrapped line. 4865 EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;", 4866 format("SOME_WEIRD_LOG_MACRO\n" 4867 "<< SomeThing;")); 4868 4869 verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), " 4870 "(n, buffers))\n", 4871 getChromiumStyle(FormatStyle::LK_Cpp)); 4872 4873 // See PR41483 4874 EXPECT_EQ("/**/ FOO(a)\n" 4875 "FOO(b)", 4876 format("/**/ FOO(a)\n" 4877 "FOO(b)")); 4878 } 4879 4880 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) { 4881 EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n" 4882 "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n" 4883 "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n" 4884 "class X {};\n" 4885 "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n" 4886 "int *createScopDetectionPass() { return 0; }", 4887 format(" INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n" 4888 " INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n" 4889 " INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n" 4890 " class X {};\n" 4891 " INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n" 4892 " int *createScopDetectionPass() { return 0; }")); 4893 // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as 4894 // braces, so that inner block is indented one level more. 4895 EXPECT_EQ("int q() {\n" 4896 " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n" 4897 " IPC_MESSAGE_HANDLER(xxx, qqq)\n" 4898 " IPC_END_MESSAGE_MAP()\n" 4899 "}", 4900 format("int q() {\n" 4901 " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n" 4902 " IPC_MESSAGE_HANDLER(xxx, qqq)\n" 4903 " IPC_END_MESSAGE_MAP()\n" 4904 "}")); 4905 4906 // Same inside macros. 4907 EXPECT_EQ("#define LIST(L) \\\n" 4908 " L(A) \\\n" 4909 " L(B) \\\n" 4910 " L(C)", 4911 format("#define LIST(L) \\\n" 4912 " L(A) \\\n" 4913 " L(B) \\\n" 4914 " L(C)", 4915 getGoogleStyle())); 4916 4917 // These must not be recognized as macros. 4918 EXPECT_EQ("int q() {\n" 4919 " f(x);\n" 4920 " f(x) {}\n" 4921 " f(x)->g();\n" 4922 " f(x)->*g();\n" 4923 " f(x).g();\n" 4924 " f(x) = x;\n" 4925 " f(x) += x;\n" 4926 " f(x) -= x;\n" 4927 " f(x) *= x;\n" 4928 " f(x) /= x;\n" 4929 " f(x) %= x;\n" 4930 " f(x) &= x;\n" 4931 " f(x) |= x;\n" 4932 " f(x) ^= x;\n" 4933 " f(x) >>= x;\n" 4934 " f(x) <<= x;\n" 4935 " f(x)[y].z();\n" 4936 " LOG(INFO) << x;\n" 4937 " ifstream(x) >> x;\n" 4938 "}\n", 4939 format("int q() {\n" 4940 " f(x)\n;\n" 4941 " f(x)\n {}\n" 4942 " f(x)\n->g();\n" 4943 " f(x)\n->*g();\n" 4944 " f(x)\n.g();\n" 4945 " f(x)\n = x;\n" 4946 " f(x)\n += x;\n" 4947 " f(x)\n -= x;\n" 4948 " f(x)\n *= x;\n" 4949 " f(x)\n /= x;\n" 4950 " f(x)\n %= x;\n" 4951 " f(x)\n &= x;\n" 4952 " f(x)\n |= x;\n" 4953 " f(x)\n ^= x;\n" 4954 " f(x)\n >>= x;\n" 4955 " f(x)\n <<= x;\n" 4956 " f(x)\n[y].z();\n" 4957 " LOG(INFO)\n << x;\n" 4958 " ifstream(x)\n >> x;\n" 4959 "}\n")); 4960 EXPECT_EQ("int q() {\n" 4961 " F(x)\n" 4962 " if (1) {\n" 4963 " }\n" 4964 " F(x)\n" 4965 " while (1) {\n" 4966 " }\n" 4967 " F(x)\n" 4968 " G(x);\n" 4969 " F(x)\n" 4970 " try {\n" 4971 " Q();\n" 4972 " } catch (...) {\n" 4973 " }\n" 4974 "}\n", 4975 format("int q() {\n" 4976 "F(x)\n" 4977 "if (1) {}\n" 4978 "F(x)\n" 4979 "while (1) {}\n" 4980 "F(x)\n" 4981 "G(x);\n" 4982 "F(x)\n" 4983 "try { Q(); } catch (...) {}\n" 4984 "}\n")); 4985 EXPECT_EQ("class A {\n" 4986 " A() : t(0) {}\n" 4987 " A(int i) noexcept() : {}\n" 4988 " A(X x)\n" // FIXME: function-level try blocks are broken. 4989 " try : t(0) {\n" 4990 " } catch (...) {\n" 4991 " }\n" 4992 "};", 4993 format("class A {\n" 4994 " A()\n : t(0) {}\n" 4995 " A(int i)\n noexcept() : {}\n" 4996 " A(X x)\n" 4997 " try : t(0) {} catch (...) {}\n" 4998 "};")); 4999 FormatStyle Style = getLLVMStyle(); 5000 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 5001 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 5002 Style.BraceWrapping.AfterFunction = true; 5003 EXPECT_EQ("void f()\n" 5004 "try\n" 5005 "{\n" 5006 "}", 5007 format("void f() try {\n" 5008 "}", 5009 Style)); 5010 EXPECT_EQ("class SomeClass {\n" 5011 "public:\n" 5012 " SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5013 "};", 5014 format("class SomeClass {\n" 5015 "public:\n" 5016 " SomeClass()\n" 5017 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5018 "};")); 5019 EXPECT_EQ("class SomeClass {\n" 5020 "public:\n" 5021 " SomeClass()\n" 5022 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5023 "};", 5024 format("class SomeClass {\n" 5025 "public:\n" 5026 " SomeClass()\n" 5027 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5028 "};", 5029 getLLVMStyleWithColumns(40))); 5030 5031 verifyFormat("MACRO(>)"); 5032 5033 // Some macros contain an implicit semicolon. 5034 Style = getLLVMStyle(); 5035 Style.StatementMacros.push_back("FOO"); 5036 verifyFormat("FOO(a) int b = 0;"); 5037 verifyFormat("FOO(a)\n" 5038 "int b = 0;", 5039 Style); 5040 verifyFormat("FOO(a);\n" 5041 "int b = 0;", 5042 Style); 5043 verifyFormat("FOO(argc, argv, \"4.0.2\")\n" 5044 "int b = 0;", 5045 Style); 5046 verifyFormat("FOO()\n" 5047 "int b = 0;", 5048 Style); 5049 verifyFormat("FOO\n" 5050 "int b = 0;", 5051 Style); 5052 verifyFormat("void f() {\n" 5053 " FOO(a)\n" 5054 " return a;\n" 5055 "}", 5056 Style); 5057 verifyFormat("FOO(a)\n" 5058 "FOO(b)", 5059 Style); 5060 verifyFormat("int a = 0;\n" 5061 "FOO(b)\n" 5062 "int c = 0;", 5063 Style); 5064 verifyFormat("int a = 0;\n" 5065 "int x = FOO(a)\n" 5066 "int b = 0;", 5067 Style); 5068 verifyFormat("void foo(int a) { FOO(a) }\n" 5069 "uint32_t bar() {}", 5070 Style); 5071 } 5072 5073 TEST_F(FormatTest, FormatsMacrosWithZeroColumnWidth) { 5074 FormatStyle ZeroColumn = getLLVMStyleWithColumns(0); 5075 5076 verifyFormat("#define A LOOOOOOOOOOOOOOOOOOONG() LOOOOOOOOOOOOOOOOOOONG()", 5077 ZeroColumn); 5078 } 5079 5080 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) { 5081 verifyFormat("#define A \\\n" 5082 " f({ \\\n" 5083 " g(); \\\n" 5084 " });", 5085 getLLVMStyleWithColumns(11)); 5086 } 5087 5088 TEST_F(FormatTest, IndentPreprocessorDirectives) { 5089 FormatStyle Style = getLLVMStyleWithColumns(40); 5090 Style.IndentPPDirectives = FormatStyle::PPDIS_None; 5091 verifyFormat("#ifdef _WIN32\n" 5092 "#define A 0\n" 5093 "#ifdef VAR2\n" 5094 "#define B 1\n" 5095 "#include <someheader.h>\n" 5096 "#define MACRO \\\n" 5097 " some_very_long_func_aaaaaaaaaa();\n" 5098 "#endif\n" 5099 "#else\n" 5100 "#define A 1\n" 5101 "#endif", 5102 Style); 5103 Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash; 5104 verifyFormat("#ifdef _WIN32\n" 5105 "# define A 0\n" 5106 "# ifdef VAR2\n" 5107 "# define B 1\n" 5108 "# include <someheader.h>\n" 5109 "# define MACRO \\\n" 5110 " some_very_long_func_aaaaaaaaaa();\n" 5111 "# endif\n" 5112 "#else\n" 5113 "# define A 1\n" 5114 "#endif", 5115 Style); 5116 verifyFormat("#if A\n" 5117 "# define MACRO \\\n" 5118 " void a(int x) { \\\n" 5119 " b(); \\\n" 5120 " c(); \\\n" 5121 " d(); \\\n" 5122 " e(); \\\n" 5123 " f(); \\\n" 5124 " }\n" 5125 "#endif", 5126 Style); 5127 // Comments before include guard. 5128 verifyFormat("// file comment\n" 5129 "// file comment\n" 5130 "#ifndef HEADER_H\n" 5131 "#define HEADER_H\n" 5132 "code();\n" 5133 "#endif", 5134 Style); 5135 // Test with include guards. 5136 verifyFormat("#ifndef HEADER_H\n" 5137 "#define HEADER_H\n" 5138 "code();\n" 5139 "#endif", 5140 Style); 5141 // Include guards must have a #define with the same variable immediately 5142 // after #ifndef. 5143 verifyFormat("#ifndef NOT_GUARD\n" 5144 "# define FOO\n" 5145 "code();\n" 5146 "#endif", 5147 Style); 5148 5149 // Include guards must cover the entire file. 5150 verifyFormat("code();\n" 5151 "code();\n" 5152 "#ifndef NOT_GUARD\n" 5153 "# define NOT_GUARD\n" 5154 "code();\n" 5155 "#endif", 5156 Style); 5157 verifyFormat("#ifndef NOT_GUARD\n" 5158 "# define NOT_GUARD\n" 5159 "code();\n" 5160 "#endif\n" 5161 "code();", 5162 Style); 5163 // Test with trailing blank lines. 5164 verifyFormat("#ifndef HEADER_H\n" 5165 "#define HEADER_H\n" 5166 "code();\n" 5167 "#endif\n", 5168 Style); 5169 // Include guards don't have #else. 5170 verifyFormat("#ifndef NOT_GUARD\n" 5171 "# define NOT_GUARD\n" 5172 "code();\n" 5173 "#else\n" 5174 "#endif", 5175 Style); 5176 verifyFormat("#ifndef NOT_GUARD\n" 5177 "# define NOT_GUARD\n" 5178 "code();\n" 5179 "#elif FOO\n" 5180 "#endif", 5181 Style); 5182 // Non-identifier #define after potential include guard. 5183 verifyFormat("#ifndef FOO\n" 5184 "# define 1\n" 5185 "#endif\n", 5186 Style); 5187 // #if closes past last non-preprocessor line. 5188 verifyFormat("#ifndef FOO\n" 5189 "#define FOO\n" 5190 "#if 1\n" 5191 "int i;\n" 5192 "# define A 0\n" 5193 "#endif\n" 5194 "#endif\n", 5195 Style); 5196 // Don't crash if there is an #elif directive without a condition. 5197 verifyFormat("#if 1\n" 5198 "int x;\n" 5199 "#elif\n" 5200 "int y;\n" 5201 "#else\n" 5202 "int z;\n" 5203 "#endif", 5204 Style); 5205 // FIXME: This doesn't handle the case where there's code between the 5206 // #ifndef and #define but all other conditions hold. This is because when 5207 // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the 5208 // previous code line yet, so we can't detect it. 5209 EXPECT_EQ("#ifndef NOT_GUARD\n" 5210 "code();\n" 5211 "#define NOT_GUARD\n" 5212 "code();\n" 5213 "#endif", 5214 format("#ifndef NOT_GUARD\n" 5215 "code();\n" 5216 "# define NOT_GUARD\n" 5217 "code();\n" 5218 "#endif", 5219 Style)); 5220 // FIXME: This doesn't handle cases where legitimate preprocessor lines may 5221 // be outside an include guard. Examples are #pragma once and 5222 // #pragma GCC diagnostic, or anything else that does not change the meaning 5223 // of the file if it's included multiple times. 5224 EXPECT_EQ("#ifdef WIN32\n" 5225 "# pragma once\n" 5226 "#endif\n" 5227 "#ifndef HEADER_H\n" 5228 "# define HEADER_H\n" 5229 "code();\n" 5230 "#endif", 5231 format("#ifdef WIN32\n" 5232 "# pragma once\n" 5233 "#endif\n" 5234 "#ifndef HEADER_H\n" 5235 "#define HEADER_H\n" 5236 "code();\n" 5237 "#endif", 5238 Style)); 5239 // FIXME: This does not detect when there is a single non-preprocessor line 5240 // in front of an include-guard-like structure where other conditions hold 5241 // because ScopedLineState hides the line. 5242 EXPECT_EQ("code();\n" 5243 "#ifndef HEADER_H\n" 5244 "#define HEADER_H\n" 5245 "code();\n" 5246 "#endif", 5247 format("code();\n" 5248 "#ifndef HEADER_H\n" 5249 "# define HEADER_H\n" 5250 "code();\n" 5251 "#endif", 5252 Style)); 5253 // Keep comments aligned with #, otherwise indent comments normally. These 5254 // tests cannot use verifyFormat because messUp manipulates leading 5255 // whitespace. 5256 { 5257 const char *Expected = "" 5258 "void f() {\n" 5259 "#if 1\n" 5260 "// Preprocessor aligned.\n" 5261 "# define A 0\n" 5262 " // Code. Separated by blank line.\n" 5263 "\n" 5264 "# define B 0\n" 5265 " // Code. Not aligned with #\n" 5266 "# define C 0\n" 5267 "#endif"; 5268 const char *ToFormat = "" 5269 "void f() {\n" 5270 "#if 1\n" 5271 "// Preprocessor aligned.\n" 5272 "# define A 0\n" 5273 "// Code. Separated by blank line.\n" 5274 "\n" 5275 "# define B 0\n" 5276 " // Code. Not aligned with #\n" 5277 "# define C 0\n" 5278 "#endif"; 5279 EXPECT_EQ(Expected, format(ToFormat, Style)); 5280 EXPECT_EQ(Expected, format(Expected, Style)); 5281 } 5282 // Keep block quotes aligned. 5283 { 5284 const char *Expected = "" 5285 "void f() {\n" 5286 "#if 1\n" 5287 "/* Preprocessor aligned. */\n" 5288 "# define A 0\n" 5289 " /* Code. Separated by blank line. */\n" 5290 "\n" 5291 "# define B 0\n" 5292 " /* Code. Not aligned with # */\n" 5293 "# define C 0\n" 5294 "#endif"; 5295 const char *ToFormat = "" 5296 "void f() {\n" 5297 "#if 1\n" 5298 "/* Preprocessor aligned. */\n" 5299 "# define A 0\n" 5300 "/* Code. Separated by blank line. */\n" 5301 "\n" 5302 "# define B 0\n" 5303 " /* Code. Not aligned with # */\n" 5304 "# define C 0\n" 5305 "#endif"; 5306 EXPECT_EQ(Expected, format(ToFormat, Style)); 5307 EXPECT_EQ(Expected, format(Expected, Style)); 5308 } 5309 // Keep comments aligned with un-indented directives. 5310 { 5311 const char *Expected = "" 5312 "void f() {\n" 5313 "// Preprocessor aligned.\n" 5314 "#define A 0\n" 5315 " // Code. Separated by blank line.\n" 5316 "\n" 5317 "#define B 0\n" 5318 " // Code. Not aligned with #\n" 5319 "#define C 0\n"; 5320 const char *ToFormat = "" 5321 "void f() {\n" 5322 "// Preprocessor aligned.\n" 5323 "#define A 0\n" 5324 "// Code. Separated by blank line.\n" 5325 "\n" 5326 "#define B 0\n" 5327 " // Code. Not aligned with #\n" 5328 "#define C 0\n"; 5329 EXPECT_EQ(Expected, format(ToFormat, Style)); 5330 EXPECT_EQ(Expected, format(Expected, Style)); 5331 } 5332 // Test AfterHash with tabs. 5333 { 5334 FormatStyle Tabbed = Style; 5335 Tabbed.UseTab = FormatStyle::UT_Always; 5336 Tabbed.IndentWidth = 8; 5337 Tabbed.TabWidth = 8; 5338 verifyFormat("#ifdef _WIN32\n" 5339 "#\tdefine A 0\n" 5340 "#\tifdef VAR2\n" 5341 "#\t\tdefine B 1\n" 5342 "#\t\tinclude <someheader.h>\n" 5343 "#\t\tdefine MACRO \\\n" 5344 "\t\t\tsome_very_long_func_aaaaaaaaaa();\n" 5345 "#\tendif\n" 5346 "#else\n" 5347 "#\tdefine A 1\n" 5348 "#endif", 5349 Tabbed); 5350 } 5351 5352 // Regression test: Multiline-macro inside include guards. 5353 verifyFormat("#ifndef HEADER_H\n" 5354 "#define HEADER_H\n" 5355 "#define A() \\\n" 5356 " int i; \\\n" 5357 " int j;\n" 5358 "#endif // HEADER_H", 5359 getLLVMStyleWithColumns(20)); 5360 5361 Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash; 5362 // Basic before hash indent tests 5363 verifyFormat("#ifdef _WIN32\n" 5364 " #define A 0\n" 5365 " #ifdef VAR2\n" 5366 " #define B 1\n" 5367 " #include <someheader.h>\n" 5368 " #define MACRO \\\n" 5369 " some_very_long_func_aaaaaaaaaa();\n" 5370 " #endif\n" 5371 "#else\n" 5372 " #define A 1\n" 5373 "#endif", 5374 Style); 5375 verifyFormat("#if A\n" 5376 " #define MACRO \\\n" 5377 " void a(int x) { \\\n" 5378 " b(); \\\n" 5379 " c(); \\\n" 5380 " d(); \\\n" 5381 " e(); \\\n" 5382 " f(); \\\n" 5383 " }\n" 5384 "#endif", 5385 Style); 5386 // Keep comments aligned with indented directives. These 5387 // tests cannot use verifyFormat because messUp manipulates leading 5388 // whitespace. 5389 { 5390 const char *Expected = "void f() {\n" 5391 "// Aligned to preprocessor.\n" 5392 "#if 1\n" 5393 " // Aligned to code.\n" 5394 " int a;\n" 5395 " #if 1\n" 5396 " // Aligned to preprocessor.\n" 5397 " #define A 0\n" 5398 " // Aligned to code.\n" 5399 " int b;\n" 5400 " #endif\n" 5401 "#endif\n" 5402 "}"; 5403 const char *ToFormat = "void f() {\n" 5404 "// Aligned to preprocessor.\n" 5405 "#if 1\n" 5406 "// Aligned to code.\n" 5407 "int a;\n" 5408 "#if 1\n" 5409 "// Aligned to preprocessor.\n" 5410 "#define A 0\n" 5411 "// Aligned to code.\n" 5412 "int b;\n" 5413 "#endif\n" 5414 "#endif\n" 5415 "}"; 5416 EXPECT_EQ(Expected, format(ToFormat, Style)); 5417 EXPECT_EQ(Expected, format(Expected, Style)); 5418 } 5419 { 5420 const char *Expected = "void f() {\n" 5421 "/* Aligned to preprocessor. */\n" 5422 "#if 1\n" 5423 " /* Aligned to code. */\n" 5424 " int a;\n" 5425 " #if 1\n" 5426 " /* Aligned to preprocessor. */\n" 5427 " #define A 0\n" 5428 " /* Aligned to code. */\n" 5429 " int b;\n" 5430 " #endif\n" 5431 "#endif\n" 5432 "}"; 5433 const char *ToFormat = "void f() {\n" 5434 "/* Aligned to preprocessor. */\n" 5435 "#if 1\n" 5436 "/* Aligned to code. */\n" 5437 "int a;\n" 5438 "#if 1\n" 5439 "/* Aligned to preprocessor. */\n" 5440 "#define A 0\n" 5441 "/* Aligned to code. */\n" 5442 "int b;\n" 5443 "#endif\n" 5444 "#endif\n" 5445 "}"; 5446 EXPECT_EQ(Expected, format(ToFormat, Style)); 5447 EXPECT_EQ(Expected, format(Expected, Style)); 5448 } 5449 5450 // Test single comment before preprocessor 5451 verifyFormat("// Comment\n" 5452 "\n" 5453 "#if 1\n" 5454 "#endif", 5455 Style); 5456 } 5457 5458 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) { 5459 verifyFormat("{\n { a #c; }\n}"); 5460 } 5461 5462 TEST_F(FormatTest, FormatUnbalancedStructuralElements) { 5463 EXPECT_EQ("#define A \\\n { \\\n {\nint i;", 5464 format("#define A { {\nint i;", getLLVMStyleWithColumns(11))); 5465 EXPECT_EQ("#define A \\\n } \\\n }\nint i;", 5466 format("#define A } }\nint i;", getLLVMStyleWithColumns(11))); 5467 } 5468 5469 TEST_F(FormatTest, EscapedNewlines) { 5470 FormatStyle Narrow = getLLVMStyleWithColumns(11); 5471 EXPECT_EQ("#define A \\\n int i; \\\n int j;", 5472 format("#define A \\\nint i;\\\n int j;", Narrow)); 5473 EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;")); 5474 EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();")); 5475 EXPECT_EQ("/* \\ \\ \\\n */", format("\\\n/* \\ \\ \\\n */")); 5476 EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>")); 5477 5478 FormatStyle AlignLeft = getLLVMStyle(); 5479 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left; 5480 EXPECT_EQ("#define MACRO(x) \\\n" 5481 "private: \\\n" 5482 " int x(int a);\n", 5483 format("#define MACRO(x) \\\n" 5484 "private: \\\n" 5485 " int x(int a);\n", 5486 AlignLeft)); 5487 5488 // CRLF line endings 5489 EXPECT_EQ("#define A \\\r\n int i; \\\r\n int j;", 5490 format("#define A \\\r\nint i;\\\r\n int j;", Narrow)); 5491 EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;")); 5492 EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();")); 5493 EXPECT_EQ("/* \\ \\ \\\r\n */", format("\\\r\n/* \\ \\ \\\r\n */")); 5494 EXPECT_EQ("<a\r\n\\\\\r\n>", format("<a\r\n\\\\\r\n>")); 5495 EXPECT_EQ("#define MACRO(x) \\\r\n" 5496 "private: \\\r\n" 5497 " int x(int a);\r\n", 5498 format("#define MACRO(x) \\\r\n" 5499 "private: \\\r\n" 5500 " int x(int a);\r\n", 5501 AlignLeft)); 5502 5503 FormatStyle DontAlign = getLLVMStyle(); 5504 DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 5505 DontAlign.MaxEmptyLinesToKeep = 3; 5506 // FIXME: can't use verifyFormat here because the newline before 5507 // "public:" is not inserted the first time it's reformatted 5508 EXPECT_EQ("#define A \\\n" 5509 " class Foo { \\\n" 5510 " void bar(); \\\n" 5511 "\\\n" 5512 "\\\n" 5513 "\\\n" 5514 " public: \\\n" 5515 " void baz(); \\\n" 5516 " };", 5517 format("#define A \\\n" 5518 " class Foo { \\\n" 5519 " void bar(); \\\n" 5520 "\\\n" 5521 "\\\n" 5522 "\\\n" 5523 " public: \\\n" 5524 " void baz(); \\\n" 5525 " };", 5526 DontAlign)); 5527 } 5528 5529 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) { 5530 verifyFormat("#define A \\\n" 5531 " int v( \\\n" 5532 " a); \\\n" 5533 " int i;", 5534 getLLVMStyleWithColumns(11)); 5535 } 5536 5537 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) { 5538 EXPECT_EQ( 5539 "#define ALooooooooooooooooooooooooooooooooooooooongMacro(" 5540 " \\\n" 5541 " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n" 5542 "\n" 5543 "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n" 5544 " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n", 5545 format(" #define ALooooooooooooooooooooooooooooooooooooooongMacro(" 5546 "\\\n" 5547 "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n" 5548 " \n" 5549 " AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n" 5550 " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n")); 5551 } 5552 5553 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) { 5554 EXPECT_EQ("int\n" 5555 "#define A\n" 5556 " a;", 5557 format("int\n#define A\na;")); 5558 verifyFormat("functionCallTo(\n" 5559 " someOtherFunction(\n" 5560 " withSomeParameters, whichInSequence,\n" 5561 " areLongerThanALine(andAnotherCall,\n" 5562 "#define A B\n" 5563 " withMoreParamters,\n" 5564 " whichStronglyInfluenceTheLayout),\n" 5565 " andMoreParameters),\n" 5566 " trailing);", 5567 getLLVMStyleWithColumns(69)); 5568 verifyFormat("Foo::Foo()\n" 5569 "#ifdef BAR\n" 5570 " : baz(0)\n" 5571 "#endif\n" 5572 "{\n" 5573 "}"); 5574 verifyFormat("void f() {\n" 5575 " if (true)\n" 5576 "#ifdef A\n" 5577 " f(42);\n" 5578 " x();\n" 5579 "#else\n" 5580 " g();\n" 5581 " x();\n" 5582 "#endif\n" 5583 "}"); 5584 verifyFormat("void f(param1, param2,\n" 5585 " param3,\n" 5586 "#ifdef A\n" 5587 " param4(param5,\n" 5588 "#ifdef A1\n" 5589 " param6,\n" 5590 "#ifdef A2\n" 5591 " param7),\n" 5592 "#else\n" 5593 " param8),\n" 5594 " param9,\n" 5595 "#endif\n" 5596 " param10,\n" 5597 "#endif\n" 5598 " param11)\n" 5599 "#else\n" 5600 " param12)\n" 5601 "#endif\n" 5602 "{\n" 5603 " x();\n" 5604 "}", 5605 getLLVMStyleWithColumns(28)); 5606 verifyFormat("#if 1\n" 5607 "int i;"); 5608 verifyFormat("#if 1\n" 5609 "#endif\n" 5610 "#if 1\n" 5611 "#else\n" 5612 "#endif\n"); 5613 verifyFormat("DEBUG({\n" 5614 " return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5615 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n" 5616 "});\n" 5617 "#if a\n" 5618 "#else\n" 5619 "#endif"); 5620 5621 verifyIncompleteFormat("void f(\n" 5622 "#if A\n" 5623 ");\n" 5624 "#else\n" 5625 "#endif"); 5626 } 5627 5628 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) { 5629 verifyFormat("#endif\n" 5630 "#if B"); 5631 } 5632 5633 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) { 5634 FormatStyle SingleLine = getLLVMStyle(); 5635 SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse; 5636 verifyFormat("#if 0\n" 5637 "#elif 1\n" 5638 "#endif\n" 5639 "void foo() {\n" 5640 " if (test) foo2();\n" 5641 "}", 5642 SingleLine); 5643 } 5644 5645 TEST_F(FormatTest, LayoutBlockInsideParens) { 5646 verifyFormat("functionCall({ int i; });"); 5647 verifyFormat("functionCall({\n" 5648 " int i;\n" 5649 " int j;\n" 5650 "});"); 5651 verifyFormat("functionCall(\n" 5652 " {\n" 5653 " int i;\n" 5654 " int j;\n" 5655 " },\n" 5656 " aaaa, bbbb, cccc);"); 5657 verifyFormat("functionA(functionB({\n" 5658 " int i;\n" 5659 " int j;\n" 5660 " }),\n" 5661 " aaaa, bbbb, cccc);"); 5662 verifyFormat("functionCall(\n" 5663 " {\n" 5664 " int i;\n" 5665 " int j;\n" 5666 " },\n" 5667 " aaaa, bbbb, // comment\n" 5668 " cccc);"); 5669 verifyFormat("functionA(functionB({\n" 5670 " int i;\n" 5671 " int j;\n" 5672 " }),\n" 5673 " aaaa, bbbb, // comment\n" 5674 " cccc);"); 5675 verifyFormat("functionCall(aaaa, bbbb, { int i; });"); 5676 verifyFormat("functionCall(aaaa, bbbb, {\n" 5677 " int i;\n" 5678 " int j;\n" 5679 "});"); 5680 verifyFormat( 5681 "Aaa(\n" // FIXME: There shouldn't be a linebreak here. 5682 " {\n" 5683 " int i; // break\n" 5684 " },\n" 5685 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 5686 " ccccccccccccccccc));"); 5687 verifyFormat("DEBUG({\n" 5688 " if (a)\n" 5689 " f();\n" 5690 "});"); 5691 } 5692 5693 TEST_F(FormatTest, LayoutBlockInsideStatement) { 5694 EXPECT_EQ("SOME_MACRO { int i; }\n" 5695 "int i;", 5696 format(" SOME_MACRO {int i;} int i;")); 5697 } 5698 5699 TEST_F(FormatTest, LayoutNestedBlocks) { 5700 verifyFormat("void AddOsStrings(unsigned bitmask) {\n" 5701 " struct s {\n" 5702 " int i;\n" 5703 " };\n" 5704 " s kBitsToOs[] = {{10}};\n" 5705 " for (int i = 0; i < 10; ++i)\n" 5706 " return;\n" 5707 "}"); 5708 verifyFormat("call(parameter, {\n" 5709 " something();\n" 5710 " // Comment using all columns.\n" 5711 " somethingelse();\n" 5712 "});", 5713 getLLVMStyleWithColumns(40)); 5714 verifyFormat("DEBUG( //\n" 5715 " { f(); }, a);"); 5716 verifyFormat("DEBUG( //\n" 5717 " {\n" 5718 " f(); //\n" 5719 " },\n" 5720 " a);"); 5721 5722 EXPECT_EQ("call(parameter, {\n" 5723 " something();\n" 5724 " // Comment too\n" 5725 " // looooooooooong.\n" 5726 " somethingElse();\n" 5727 "});", 5728 format("call(parameter, {\n" 5729 " something();\n" 5730 " // Comment too looooooooooong.\n" 5731 " somethingElse();\n" 5732 "});", 5733 getLLVMStyleWithColumns(29))); 5734 EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int i; });")); 5735 EXPECT_EQ("DEBUG({ // comment\n" 5736 " int i;\n" 5737 "});", 5738 format("DEBUG({ // comment\n" 5739 "int i;\n" 5740 "});")); 5741 EXPECT_EQ("DEBUG({\n" 5742 " int i;\n" 5743 "\n" 5744 " // comment\n" 5745 " int j;\n" 5746 "});", 5747 format("DEBUG({\n" 5748 " int i;\n" 5749 "\n" 5750 " // comment\n" 5751 " int j;\n" 5752 "});")); 5753 5754 verifyFormat("DEBUG({\n" 5755 " if (a)\n" 5756 " return;\n" 5757 "});"); 5758 verifyGoogleFormat("DEBUG({\n" 5759 " if (a) return;\n" 5760 "});"); 5761 FormatStyle Style = getGoogleStyle(); 5762 Style.ColumnLimit = 45; 5763 verifyFormat("Debug(\n" 5764 " aaaaa,\n" 5765 " {\n" 5766 " if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n" 5767 " },\n" 5768 " a);", 5769 Style); 5770 5771 verifyFormat("SomeFunction({MACRO({ return output; }), b});"); 5772 5773 verifyNoCrash("^{v^{a}}"); 5774 } 5775 5776 TEST_F(FormatTest, FormatNestedBlocksInMacros) { 5777 EXPECT_EQ("#define MACRO() \\\n" 5778 " Debug(aaa, /* force line break */ \\\n" 5779 " { \\\n" 5780 " int i; \\\n" 5781 " int j; \\\n" 5782 " })", 5783 format("#define MACRO() Debug(aaa, /* force line break */ \\\n" 5784 " { int i; int j; })", 5785 getGoogleStyle())); 5786 5787 EXPECT_EQ("#define A \\\n" 5788 " [] { \\\n" 5789 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 5790 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n" 5791 " }", 5792 format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 5793 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }", 5794 getGoogleStyle())); 5795 } 5796 5797 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) { 5798 EXPECT_EQ("{}", format("{}")); 5799 verifyFormat("enum E {};"); 5800 verifyFormat("enum E {}"); 5801 FormatStyle Style = getLLVMStyle(); 5802 Style.SpaceInEmptyBlock = true; 5803 EXPECT_EQ("void f() { }", format("void f() {}", Style)); 5804 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 5805 EXPECT_EQ("while (true) { }", format("while (true) {}", Style)); 5806 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 5807 Style.BraceWrapping.BeforeElse = false; 5808 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 5809 verifyFormat("if (a)\n" 5810 "{\n" 5811 "} else if (b)\n" 5812 "{\n" 5813 "} else\n" 5814 "{ }", 5815 Style); 5816 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never; 5817 verifyFormat("if (a) {\n" 5818 "} else if (b) {\n" 5819 "} else {\n" 5820 "}", 5821 Style); 5822 Style.BraceWrapping.BeforeElse = true; 5823 verifyFormat("if (a) { }\n" 5824 "else if (b) { }\n" 5825 "else { }", 5826 Style); 5827 } 5828 5829 TEST_F(FormatTest, FormatBeginBlockEndMacros) { 5830 FormatStyle Style = getLLVMStyle(); 5831 Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$"; 5832 Style.MacroBlockEnd = "^[A-Z_]+_END$"; 5833 verifyFormat("FOO_BEGIN\n" 5834 " FOO_ENTRY\n" 5835 "FOO_END", 5836 Style); 5837 verifyFormat("FOO_BEGIN\n" 5838 " NESTED_FOO_BEGIN\n" 5839 " NESTED_FOO_ENTRY\n" 5840 " NESTED_FOO_END\n" 5841 "FOO_END", 5842 Style); 5843 verifyFormat("FOO_BEGIN(Foo, Bar)\n" 5844 " int x;\n" 5845 " x = 1;\n" 5846 "FOO_END(Baz)", 5847 Style); 5848 } 5849 5850 //===----------------------------------------------------------------------===// 5851 // Line break tests. 5852 //===----------------------------------------------------------------------===// 5853 5854 TEST_F(FormatTest, PreventConfusingIndents) { 5855 verifyFormat( 5856 "void f() {\n" 5857 " SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n" 5858 " parameter, parameter, parameter)),\n" 5859 " SecondLongCall(parameter));\n" 5860 "}"); 5861 verifyFormat( 5862 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5863 " aaaaaaaaaaaaaaaaaaaaaaaa(\n" 5864 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 5865 " aaaaaaaaaaaaaaaaaaaaaaaa);"); 5866 verifyFormat( 5867 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5868 " [aaaaaaaaaaaaaaaaaaaaaaaa\n" 5869 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n" 5870 " [aaaaaaaaaaaaaaaaaaaaaaaa]];"); 5871 verifyFormat( 5872 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 5873 " aaaaaaaaaaaaaaaaaaaaaaaa<\n" 5874 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n" 5875 " aaaaaaaaaaaaaaaaaaaaaaaa>;"); 5876 verifyFormat("int a = bbbb && ccc &&\n" 5877 " fffff(\n" 5878 "#define A Just forcing a new line\n" 5879 " ddd);"); 5880 } 5881 5882 TEST_F(FormatTest, LineBreakingInBinaryExpressions) { 5883 verifyFormat( 5884 "bool aaaaaaa =\n" 5885 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n" 5886 " bbbbbbbb();"); 5887 verifyFormat( 5888 "bool aaaaaaa =\n" 5889 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n" 5890 " bbbbbbbb();"); 5891 5892 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n" 5893 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n" 5894 " ccccccccc == ddddddddddd;"); 5895 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n" 5896 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n" 5897 " ccccccccc == ddddddddddd;"); 5898 verifyFormat( 5899 "bool aaaaaaaaaaaaaaaaaaaaa =\n" 5900 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n" 5901 " ccccccccc == ddddddddddd;"); 5902 5903 verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n" 5904 " aaaaaa) &&\n" 5905 " bbbbbb && cccccc;"); 5906 verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n" 5907 " aaaaaa) >>\n" 5908 " bbbbbb;"); 5909 verifyFormat("aa = Whitespaces.addUntouchableComment(\n" 5910 " SourceMgr.getSpellingColumnNumber(\n" 5911 " TheLine.Last->FormatTok.Tok.getLocation()) -\n" 5912 " 1);"); 5913 5914 verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 5915 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n" 5916 " cccccc) {\n}"); 5917 verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 5918 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n" 5919 " cccccc) {\n}"); 5920 verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 5921 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n" 5922 " cccccc) {\n}"); 5923 verifyFormat("b = a &&\n" 5924 " // Comment\n" 5925 " b.c && d;"); 5926 5927 // If the LHS of a comparison is not a binary expression itself, the 5928 // additional linebreak confuses many people. 5929 verifyFormat( 5930 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5931 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n" 5932 "}"); 5933 verifyFormat( 5934 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5935 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 5936 "}"); 5937 verifyFormat( 5938 "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n" 5939 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 5940 "}"); 5941 verifyFormat( 5942 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5943 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n" 5944 "}"); 5945 // Even explicit parentheses stress the precedence enough to make the 5946 // additional break unnecessary. 5947 verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5948 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 5949 "}"); 5950 // This cases is borderline, but with the indentation it is still readable. 5951 verifyFormat( 5952 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5953 " aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5954 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 5955 "}", 5956 getLLVMStyleWithColumns(75)); 5957 5958 // If the LHS is a binary expression, we should still use the additional break 5959 // as otherwise the formatting hides the operator precedence. 5960 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5961 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 5962 " 5) {\n" 5963 "}"); 5964 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5965 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n" 5966 " 5) {\n" 5967 "}"); 5968 5969 FormatStyle OnePerLine = getLLVMStyle(); 5970 OnePerLine.BinPackParameters = false; 5971 verifyFormat( 5972 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 5973 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 5974 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}", 5975 OnePerLine); 5976 5977 verifyFormat("int i = someFunction(aaaaaaa, 0)\n" 5978 " .aaa(aaaaaaaaaaaaa) *\n" 5979 " aaaaaaa +\n" 5980 " aaaaaaa;", 5981 getLLVMStyleWithColumns(40)); 5982 } 5983 5984 TEST_F(FormatTest, ExpressionIndentation) { 5985 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5986 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5987 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 5988 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 5989 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n" 5990 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n" 5991 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 5992 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n" 5993 " ccccccccccccccccccccccccccccccccccccccccc;"); 5994 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 5995 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5996 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 5997 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 5998 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5999 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6000 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6001 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 6002 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6003 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6004 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6005 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 6006 verifyFormat("if () {\n" 6007 "} else if (aaaaa && bbbbb > // break\n" 6008 " ccccc) {\n" 6009 "}"); 6010 verifyFormat("if () {\n" 6011 "} else if constexpr (aaaaa && bbbbb > // break\n" 6012 " ccccc) {\n" 6013 "}"); 6014 verifyFormat("if () {\n" 6015 "} else if CONSTEXPR (aaaaa && bbbbb > // break\n" 6016 " ccccc) {\n" 6017 "}"); 6018 verifyFormat("if () {\n" 6019 "} else if (aaaaa &&\n" 6020 " bbbbb > // break\n" 6021 " ccccc &&\n" 6022 " ddddd) {\n" 6023 "}"); 6024 6025 // Presence of a trailing comment used to change indentation of b. 6026 verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n" 6027 " b;\n" 6028 "return aaaaaaaaaaaaaaaaaaa +\n" 6029 " b; //", 6030 getLLVMStyleWithColumns(30)); 6031 } 6032 6033 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) { 6034 // Not sure what the best system is here. Like this, the LHS can be found 6035 // immediately above an operator (everything with the same or a higher 6036 // indent). The RHS is aligned right of the operator and so compasses 6037 // everything until something with the same indent as the operator is found. 6038 // FIXME: Is this a good system? 6039 FormatStyle Style = getLLVMStyle(); 6040 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 6041 verifyFormat( 6042 "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6043 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6044 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6045 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6046 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6047 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6048 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6049 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6050 " > ccccccccccccccccccccccccccccccccccccccccc;", 6051 Style); 6052 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6053 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6054 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6055 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6056 Style); 6057 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6058 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6059 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6060 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6061 Style); 6062 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6063 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6064 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6065 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6066 Style); 6067 verifyFormat("if () {\n" 6068 "} else if (aaaaa\n" 6069 " && bbbbb // break\n" 6070 " > ccccc) {\n" 6071 "}", 6072 Style); 6073 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6074 " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6075 Style); 6076 verifyFormat("return (a)\n" 6077 " // comment\n" 6078 " + b;", 6079 Style); 6080 verifyFormat( 6081 "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6082 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6083 " + cc;", 6084 Style); 6085 6086 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6087 " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 6088 Style); 6089 6090 // Forced by comments. 6091 verifyFormat( 6092 "unsigned ContentSize =\n" 6093 " sizeof(int16_t) // DWARF ARange version number\n" 6094 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6095 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6096 " + sizeof(int8_t); // Segment Size (in bytes)"); 6097 6098 verifyFormat("return boost::fusion::at_c<0>(iiii).second\n" 6099 " == boost::fusion::at_c<1>(iiii).second;", 6100 Style); 6101 6102 Style.ColumnLimit = 60; 6103 verifyFormat("zzzzzzzzzz\n" 6104 " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6105 " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);", 6106 Style); 6107 6108 Style.ColumnLimit = 80; 6109 Style.IndentWidth = 4; 6110 Style.TabWidth = 4; 6111 Style.UseTab = FormatStyle::UT_Always; 6112 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6113 Style.AlignOperands = FormatStyle::OAS_DontAlign; 6114 EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n" 6115 "\t&& (someOtherLongishConditionPart1\n" 6116 "\t\t|| someOtherEvenLongerNestedConditionPart2);", 6117 format("return someVeryVeryLongConditionThatBarelyFitsOnALine && " 6118 "(someOtherLongishConditionPart1 || " 6119 "someOtherEvenLongerNestedConditionPart2);", 6120 Style)); 6121 } 6122 6123 TEST_F(FormatTest, ExpressionIndentationStrictAlign) { 6124 FormatStyle Style = getLLVMStyle(); 6125 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 6126 Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator; 6127 6128 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6129 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6130 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6131 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6132 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6133 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6134 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6135 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6136 " > ccccccccccccccccccccccccccccccccccccccccc;", 6137 Style); 6138 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6139 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6140 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6141 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6142 Style); 6143 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6144 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6145 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6146 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6147 Style); 6148 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6149 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6150 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6151 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6152 Style); 6153 verifyFormat("if () {\n" 6154 "} else if (aaaaa\n" 6155 " && bbbbb // break\n" 6156 " > ccccc) {\n" 6157 "}", 6158 Style); 6159 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6160 " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6161 Style); 6162 verifyFormat("return (a)\n" 6163 " // comment\n" 6164 " + b;", 6165 Style); 6166 verifyFormat( 6167 "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6168 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6169 " + cc;", 6170 Style); 6171 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 6172 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 6173 " : 3333333333333333;", 6174 Style); 6175 verifyFormat( 6176 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 6177 " : ccccccccccccccc ? dddddddddddddddddd\n" 6178 " : eeeeeeeeeeeeeeeeee)\n" 6179 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 6180 " : 3333333333333333;", 6181 Style); 6182 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6183 " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 6184 Style); 6185 6186 verifyFormat("return boost::fusion::at_c<0>(iiii).second\n" 6187 " == boost::fusion::at_c<1>(iiii).second;", 6188 Style); 6189 6190 Style.ColumnLimit = 60; 6191 verifyFormat("zzzzzzzzzzzzz\n" 6192 " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6193 " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);", 6194 Style); 6195 6196 // Forced by comments. 6197 Style.ColumnLimit = 80; 6198 verifyFormat( 6199 "unsigned ContentSize\n" 6200 " = sizeof(int16_t) // DWARF ARange version number\n" 6201 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6202 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6203 " + sizeof(int8_t); // Segment Size (in bytes)", 6204 Style); 6205 6206 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6207 verifyFormat( 6208 "unsigned ContentSize =\n" 6209 " sizeof(int16_t) // DWARF ARange version number\n" 6210 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6211 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6212 " + sizeof(int8_t); // Segment Size (in bytes)", 6213 Style); 6214 6215 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 6216 verifyFormat( 6217 "unsigned ContentSize =\n" 6218 " sizeof(int16_t) // DWARF ARange version number\n" 6219 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6220 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6221 " + sizeof(int8_t); // Segment Size (in bytes)", 6222 Style); 6223 } 6224 6225 TEST_F(FormatTest, EnforcedOperatorWraps) { 6226 // Here we'd like to wrap after the || operators, but a comment is forcing an 6227 // earlier wrap. 6228 verifyFormat("bool x = aaaaa //\n" 6229 " || bbbbb\n" 6230 " //\n" 6231 " || cccc;"); 6232 } 6233 6234 TEST_F(FormatTest, NoOperandAlignment) { 6235 FormatStyle Style = getLLVMStyle(); 6236 Style.AlignOperands = FormatStyle::OAS_DontAlign; 6237 verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n" 6238 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6239 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 6240 Style); 6241 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6242 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6243 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6244 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6245 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6246 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6247 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6248 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6249 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6250 " > ccccccccccccccccccccccccccccccccccccccccc;", 6251 Style); 6252 6253 verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6254 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6255 " + cc;", 6256 Style); 6257 verifyFormat("int a = aa\n" 6258 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6259 " * cccccccccccccccccccccccccccccccccccc;\n", 6260 Style); 6261 6262 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6263 verifyFormat("return (a > b\n" 6264 " // comment1\n" 6265 " // comment2\n" 6266 " || c);", 6267 Style); 6268 } 6269 6270 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) { 6271 FormatStyle Style = getLLVMStyle(); 6272 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6273 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 6274 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6275 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6276 Style); 6277 } 6278 6279 TEST_F(FormatTest, AllowBinPackingInsideArguments) { 6280 FormatStyle Style = getLLVMStyleWithColumns(40); 6281 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6282 Style.BinPackArguments = false; 6283 verifyFormat("void test() {\n" 6284 " someFunction(\n" 6285 " this + argument + is + quite\n" 6286 " + long + so + it + gets + wrapped\n" 6287 " + but + remains + bin - packed);\n" 6288 "}", 6289 Style); 6290 verifyFormat("void test() {\n" 6291 " someFunction(arg1,\n" 6292 " this + argument + is\n" 6293 " + quite + long + so\n" 6294 " + it + gets + wrapped\n" 6295 " + but + remains + bin\n" 6296 " - packed,\n" 6297 " arg3);\n" 6298 "}", 6299 Style); 6300 verifyFormat("void test() {\n" 6301 " someFunction(\n" 6302 " arg1,\n" 6303 " this + argument + has\n" 6304 " + anotherFunc(nested,\n" 6305 " calls + whose\n" 6306 " + arguments\n" 6307 " + are + also\n" 6308 " + wrapped,\n" 6309 " in + addition)\n" 6310 " + to + being + bin - packed,\n" 6311 " arg3);\n" 6312 "}", 6313 Style); 6314 6315 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 6316 verifyFormat("void test() {\n" 6317 " someFunction(\n" 6318 " arg1,\n" 6319 " this + argument + has +\n" 6320 " anotherFunc(nested,\n" 6321 " calls + whose +\n" 6322 " arguments +\n" 6323 " are + also +\n" 6324 " wrapped,\n" 6325 " in + addition) +\n" 6326 " to + being + bin - packed,\n" 6327 " arg3);\n" 6328 "}", 6329 Style); 6330 } 6331 6332 TEST_F(FormatTest, ConstructorInitializers) { 6333 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}"); 6334 verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}", 6335 getLLVMStyleWithColumns(45)); 6336 verifyFormat("Constructor()\n" 6337 " : Inttializer(FitsOnTheLine) {}", 6338 getLLVMStyleWithColumns(44)); 6339 verifyFormat("Constructor()\n" 6340 " : Inttializer(FitsOnTheLine) {}", 6341 getLLVMStyleWithColumns(43)); 6342 6343 verifyFormat("template <typename T>\n" 6344 "Constructor() : Initializer(FitsOnTheLine) {}", 6345 getLLVMStyleWithColumns(45)); 6346 6347 verifyFormat( 6348 "SomeClass::Constructor()\n" 6349 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}"); 6350 6351 verifyFormat( 6352 "SomeClass::Constructor()\n" 6353 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6354 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}"); 6355 verifyFormat( 6356 "SomeClass::Constructor()\n" 6357 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6358 " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}"); 6359 verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6360 " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 6361 " : aaaaaaaaaa(aaaaaa) {}"); 6362 6363 verifyFormat("Constructor()\n" 6364 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6365 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6366 " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6367 " aaaaaaaaaaaaaaaaaaaaaaa() {}"); 6368 6369 verifyFormat("Constructor()\n" 6370 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6371 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 6372 6373 verifyFormat("Constructor(int Parameter = 0)\n" 6374 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n" 6375 " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}"); 6376 verifyFormat("Constructor()\n" 6377 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n" 6378 "}", 6379 getLLVMStyleWithColumns(60)); 6380 verifyFormat("Constructor()\n" 6381 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6382 " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}"); 6383 6384 // Here a line could be saved by splitting the second initializer onto two 6385 // lines, but that is not desirable. 6386 verifyFormat("Constructor()\n" 6387 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n" 6388 " aaaaaaaaaaa(aaaaaaaaaaa),\n" 6389 " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 6390 6391 FormatStyle OnePerLine = getLLVMStyle(); 6392 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_Never; 6393 verifyFormat("MyClass::MyClass()\n" 6394 " : a(a),\n" 6395 " b(b),\n" 6396 " c(c) {}", 6397 OnePerLine); 6398 verifyFormat("MyClass::MyClass()\n" 6399 " : a(a), // comment\n" 6400 " b(b),\n" 6401 " c(c) {}", 6402 OnePerLine); 6403 verifyFormat("MyClass::MyClass(int a)\n" 6404 " : b(a), // comment\n" 6405 " c(a + 1) { // lined up\n" 6406 "}", 6407 OnePerLine); 6408 verifyFormat("Constructor()\n" 6409 " : a(b, b, b) {}", 6410 OnePerLine); 6411 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6412 OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false; 6413 verifyFormat("SomeClass::Constructor()\n" 6414 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6415 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6416 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6417 OnePerLine); 6418 verifyFormat("SomeClass::Constructor()\n" 6419 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n" 6420 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6421 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6422 OnePerLine); 6423 verifyFormat("MyClass::MyClass(int var)\n" 6424 " : some_var_(var), // 4 space indent\n" 6425 " some_other_var_(var + 1) { // lined up\n" 6426 "}", 6427 OnePerLine); 6428 verifyFormat("Constructor()\n" 6429 " : aaaaa(aaaaaa),\n" 6430 " aaaaa(aaaaaa),\n" 6431 " aaaaa(aaaaaa),\n" 6432 " aaaaa(aaaaaa),\n" 6433 " aaaaa(aaaaaa) {}", 6434 OnePerLine); 6435 verifyFormat("Constructor()\n" 6436 " : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n" 6437 " aaaaaaaaaaaaaaaaaaaaaa) {}", 6438 OnePerLine); 6439 OnePerLine.BinPackParameters = false; 6440 verifyFormat( 6441 "Constructor()\n" 6442 " : aaaaaaaaaaaaaaaaaaaaaaaa(\n" 6443 " aaaaaaaaaaa().aaa(),\n" 6444 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6445 OnePerLine); 6446 OnePerLine.ColumnLimit = 60; 6447 verifyFormat("Constructor()\n" 6448 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6449 " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}", 6450 OnePerLine); 6451 6452 EXPECT_EQ("Constructor()\n" 6453 " : // Comment forcing unwanted break.\n" 6454 " aaaa(aaaa) {}", 6455 format("Constructor() :\n" 6456 " // Comment forcing unwanted break.\n" 6457 " aaaa(aaaa) {}")); 6458 } 6459 6460 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) { 6461 FormatStyle Style = getLLVMStyleWithColumns(60); 6462 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6463 Style.BinPackParameters = false; 6464 6465 for (int i = 0; i < 4; ++i) { 6466 // Test all combinations of parameters that should not have an effect. 6467 Style.AllowAllParametersOfDeclarationOnNextLine = i & 1; 6468 Style.AllowAllArgumentsOnNextLine = i & 2; 6469 6470 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6471 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6472 verifyFormat("Constructor()\n" 6473 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6474 Style); 6475 verifyFormat("Constructor() : a(a), b(b) {}", Style); 6476 6477 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6478 verifyFormat("Constructor()\n" 6479 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6480 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6481 Style); 6482 verifyFormat("Constructor() : a(a), b(b) {}", Style); 6483 6484 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 6485 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6486 verifyFormat("Constructor()\n" 6487 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6488 Style); 6489 6490 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6491 verifyFormat("Constructor()\n" 6492 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6493 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6494 Style); 6495 6496 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6497 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6498 verifyFormat("Constructor() :\n" 6499 " aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6500 Style); 6501 6502 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6503 verifyFormat("Constructor() :\n" 6504 " aaaaaaaaaaaaaaaaaa(a),\n" 6505 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6506 Style); 6507 } 6508 6509 // Test interactions between AllowAllParametersOfDeclarationOnNextLine and 6510 // AllowAllConstructorInitializersOnNextLine in all 6511 // BreakConstructorInitializers modes 6512 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6513 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6514 verifyFormat("SomeClassWithALongName::Constructor(\n" 6515 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n" 6516 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6517 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6518 Style); 6519 6520 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6521 verifyFormat("SomeClassWithALongName::Constructor(\n" 6522 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6523 " int bbbbbbbbbbbbb,\n" 6524 " int cccccccccccccccc)\n" 6525 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6526 Style); 6527 6528 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6529 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6530 verifyFormat("SomeClassWithALongName::Constructor(\n" 6531 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6532 " int bbbbbbbbbbbbb)\n" 6533 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6534 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6535 Style); 6536 6537 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 6538 6539 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6540 verifyFormat("SomeClassWithALongName::Constructor(\n" 6541 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n" 6542 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6543 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6544 Style); 6545 6546 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6547 verifyFormat("SomeClassWithALongName::Constructor(\n" 6548 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6549 " int bbbbbbbbbbbbb,\n" 6550 " int cccccccccccccccc)\n" 6551 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6552 Style); 6553 6554 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6555 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6556 verifyFormat("SomeClassWithALongName::Constructor(\n" 6557 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6558 " int bbbbbbbbbbbbb)\n" 6559 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6560 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6561 Style); 6562 6563 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6564 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6565 verifyFormat("SomeClassWithALongName::Constructor(\n" 6566 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n" 6567 " aaaaaaaaaaaaaaaaaaaa(a),\n" 6568 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6569 Style); 6570 6571 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6572 verifyFormat("SomeClassWithALongName::Constructor(\n" 6573 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6574 " int bbbbbbbbbbbbb,\n" 6575 " int cccccccccccccccc) :\n" 6576 " aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6577 Style); 6578 6579 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6580 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6581 verifyFormat("SomeClassWithALongName::Constructor(\n" 6582 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6583 " int bbbbbbbbbbbbb) :\n" 6584 " aaaaaaaaaaaaaaaaaaaa(a),\n" 6585 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6586 Style); 6587 } 6588 6589 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) { 6590 FormatStyle Style = getLLVMStyleWithColumns(60); 6591 Style.BinPackArguments = false; 6592 for (int i = 0; i < 4; ++i) { 6593 // Test all combinations of parameters that should not have an effect. 6594 Style.AllowAllParametersOfDeclarationOnNextLine = i & 1; 6595 Style.PackConstructorInitializers = 6596 i & 2 ? FormatStyle::PCIS_BinPack : FormatStyle::PCIS_Never; 6597 6598 Style.AllowAllArgumentsOnNextLine = true; 6599 verifyFormat("void foo() {\n" 6600 " FunctionCallWithReallyLongName(\n" 6601 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n" 6602 "}", 6603 Style); 6604 Style.AllowAllArgumentsOnNextLine = false; 6605 verifyFormat("void foo() {\n" 6606 " FunctionCallWithReallyLongName(\n" 6607 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6608 " bbbbbbbbbbbb);\n" 6609 "}", 6610 Style); 6611 6612 Style.AllowAllArgumentsOnNextLine = true; 6613 verifyFormat("void foo() {\n" 6614 " auto VariableWithReallyLongName = {\n" 6615 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n" 6616 "}", 6617 Style); 6618 Style.AllowAllArgumentsOnNextLine = false; 6619 verifyFormat("void foo() {\n" 6620 " auto VariableWithReallyLongName = {\n" 6621 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6622 " bbbbbbbbbbbb};\n" 6623 "}", 6624 Style); 6625 } 6626 6627 // This parameter should not affect declarations. 6628 Style.BinPackParameters = false; 6629 Style.AllowAllArgumentsOnNextLine = false; 6630 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6631 verifyFormat("void FunctionCallWithReallyLongName(\n" 6632 " int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);", 6633 Style); 6634 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6635 verifyFormat("void FunctionCallWithReallyLongName(\n" 6636 " int aaaaaaaaaaaaaaaaaaaaaaa,\n" 6637 " int bbbbbbbbbbbb);", 6638 Style); 6639 } 6640 6641 TEST_F(FormatTest, AllowAllArgumentsOnNextLineDontAlign) { 6642 // Check that AllowAllArgumentsOnNextLine is respected for both BAS_DontAlign 6643 // and BAS_Align. 6644 FormatStyle Style = getLLVMStyleWithColumns(35); 6645 StringRef Input = "functionCall(paramA, paramB, paramC);\n" 6646 "void functionDecl(int A, int B, int C);"; 6647 Style.AllowAllArgumentsOnNextLine = false; 6648 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6649 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6650 " paramC);\n" 6651 "void functionDecl(int A, int B,\n" 6652 " int C);"), 6653 format(Input, Style)); 6654 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 6655 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6656 " paramC);\n" 6657 "void functionDecl(int A, int B,\n" 6658 " int C);"), 6659 format(Input, Style)); 6660 // However, BAS_AlwaysBreak should take precedence over 6661 // AllowAllArgumentsOnNextLine. 6662 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 6663 EXPECT_EQ(StringRef("functionCall(\n" 6664 " paramA, paramB, paramC);\n" 6665 "void functionDecl(\n" 6666 " int A, int B, int C);"), 6667 format(Input, Style)); 6668 6669 // When AllowAllArgumentsOnNextLine is set, we prefer breaking before the 6670 // first argument. 6671 Style.AllowAllArgumentsOnNextLine = true; 6672 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 6673 EXPECT_EQ(StringRef("functionCall(\n" 6674 " paramA, paramB, paramC);\n" 6675 "void functionDecl(\n" 6676 " int A, int B, int C);"), 6677 format(Input, Style)); 6678 // It wouldn't fit on one line with aligned parameters so this setting 6679 // doesn't change anything for BAS_Align. 6680 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 6681 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6682 " paramC);\n" 6683 "void functionDecl(int A, int B,\n" 6684 " int C);"), 6685 format(Input, Style)); 6686 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6687 EXPECT_EQ(StringRef("functionCall(\n" 6688 " paramA, paramB, paramC);\n" 6689 "void functionDecl(\n" 6690 " int A, int B, int C);"), 6691 format(Input, Style)); 6692 } 6693 6694 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) { 6695 FormatStyle Style = getLLVMStyle(); 6696 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6697 6698 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}"); 6699 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}", 6700 getStyleWithColumns(Style, 45)); 6701 verifyFormat("Constructor() :\n" 6702 " Initializer(FitsOnTheLine) {}", 6703 getStyleWithColumns(Style, 44)); 6704 verifyFormat("Constructor() :\n" 6705 " Initializer(FitsOnTheLine) {}", 6706 getStyleWithColumns(Style, 43)); 6707 6708 verifyFormat("template <typename T>\n" 6709 "Constructor() : Initializer(FitsOnTheLine) {}", 6710 getStyleWithColumns(Style, 50)); 6711 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6712 verifyFormat( 6713 "SomeClass::Constructor() :\n" 6714 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 6715 Style); 6716 6717 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 6718 verifyFormat( 6719 "SomeClass::Constructor() :\n" 6720 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 6721 Style); 6722 6723 verifyFormat( 6724 "SomeClass::Constructor() :\n" 6725 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6726 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6727 Style); 6728 verifyFormat( 6729 "SomeClass::Constructor() :\n" 6730 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6731 " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 6732 Style); 6733 verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6734 " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 6735 " aaaaaaaaaa(aaaaaa) {}", 6736 Style); 6737 6738 verifyFormat("Constructor() :\n" 6739 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6740 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6741 " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6742 " aaaaaaaaaaaaaaaaaaaaaaa() {}", 6743 Style); 6744 6745 verifyFormat("Constructor() :\n" 6746 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6747 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6748 Style); 6749 6750 verifyFormat("Constructor(int Parameter = 0) :\n" 6751 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n" 6752 " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}", 6753 Style); 6754 verifyFormat("Constructor() :\n" 6755 " aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n" 6756 "}", 6757 getStyleWithColumns(Style, 60)); 6758 verifyFormat("Constructor() :\n" 6759 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6760 " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}", 6761 Style); 6762 6763 // Here a line could be saved by splitting the second initializer onto two 6764 // lines, but that is not desirable. 6765 verifyFormat("Constructor() :\n" 6766 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n" 6767 " aaaaaaaaaaa(aaaaaaaaaaa),\n" 6768 " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6769 Style); 6770 6771 FormatStyle OnePerLine = Style; 6772 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6773 verifyFormat("SomeClass::Constructor() :\n" 6774 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6775 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6776 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6777 OnePerLine); 6778 verifyFormat("SomeClass::Constructor() :\n" 6779 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n" 6780 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6781 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6782 OnePerLine); 6783 verifyFormat("MyClass::MyClass(int var) :\n" 6784 " some_var_(var), // 4 space indent\n" 6785 " some_other_var_(var + 1) { // lined up\n" 6786 "}", 6787 OnePerLine); 6788 verifyFormat("Constructor() :\n" 6789 " aaaaa(aaaaaa),\n" 6790 " aaaaa(aaaaaa),\n" 6791 " aaaaa(aaaaaa),\n" 6792 " aaaaa(aaaaaa),\n" 6793 " aaaaa(aaaaaa) {}", 6794 OnePerLine); 6795 verifyFormat("Constructor() :\n" 6796 " aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n" 6797 " aaaaaaaaaaaaaaaaaaaaaa) {}", 6798 OnePerLine); 6799 OnePerLine.BinPackParameters = false; 6800 verifyFormat("Constructor() :\n" 6801 " aaaaaaaaaaaaaaaaaaaaaaaa(\n" 6802 " aaaaaaaaaaa().aaa(),\n" 6803 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6804 OnePerLine); 6805 OnePerLine.ColumnLimit = 60; 6806 verifyFormat("Constructor() :\n" 6807 " aaaaaaaaaaaaaaaaaaaa(a),\n" 6808 " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}", 6809 OnePerLine); 6810 6811 EXPECT_EQ("Constructor() :\n" 6812 " // Comment forcing unwanted break.\n" 6813 " aaaa(aaaa) {}", 6814 format("Constructor() :\n" 6815 " // Comment forcing unwanted break.\n" 6816 " aaaa(aaaa) {}", 6817 Style)); 6818 6819 Style.ColumnLimit = 0; 6820 verifyFormat("SomeClass::Constructor() :\n" 6821 " a(a) {}", 6822 Style); 6823 verifyFormat("SomeClass::Constructor() noexcept :\n" 6824 " a(a) {}", 6825 Style); 6826 verifyFormat("SomeClass::Constructor() :\n" 6827 " a(a), b(b), c(c) {}", 6828 Style); 6829 verifyFormat("SomeClass::Constructor() :\n" 6830 " a(a) {\n" 6831 " foo();\n" 6832 " bar();\n" 6833 "}", 6834 Style); 6835 6836 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 6837 verifyFormat("SomeClass::Constructor() :\n" 6838 " a(a), b(b), c(c) {\n" 6839 "}", 6840 Style); 6841 verifyFormat("SomeClass::Constructor() :\n" 6842 " a(a) {\n" 6843 "}", 6844 Style); 6845 6846 Style.ColumnLimit = 80; 6847 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 6848 Style.ConstructorInitializerIndentWidth = 2; 6849 verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style); 6850 verifyFormat("SomeClass::Constructor() :\n" 6851 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6852 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}", 6853 Style); 6854 6855 // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as 6856 // well 6857 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 6858 verifyFormat( 6859 "class SomeClass\n" 6860 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6861 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 6862 Style); 6863 Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma; 6864 verifyFormat( 6865 "class SomeClass\n" 6866 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6867 " , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 6868 Style); 6869 Style.BreakInheritanceList = FormatStyle::BILS_AfterColon; 6870 verifyFormat( 6871 "class SomeClass :\n" 6872 " public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6873 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 6874 Style); 6875 Style.BreakInheritanceList = FormatStyle::BILS_AfterComma; 6876 verifyFormat( 6877 "class SomeClass\n" 6878 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6879 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 6880 Style); 6881 } 6882 6883 #ifndef EXPENSIVE_CHECKS 6884 // Expensive checks enables libstdc++ checking which includes validating the 6885 // state of ranges used in std::priority_queue - this blows out the 6886 // runtime/scalability of the function and makes this test unacceptably slow. 6887 TEST_F(FormatTest, MemoizationTests) { 6888 // This breaks if the memoization lookup does not take \c Indent and 6889 // \c LastSpace into account. 6890 verifyFormat( 6891 "extern CFRunLoopTimerRef\n" 6892 "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n" 6893 " CFTimeInterval interval, CFOptionFlags flags,\n" 6894 " CFIndex order, CFRunLoopTimerCallBack callout,\n" 6895 " CFRunLoopTimerContext *context) {}"); 6896 6897 // Deep nesting somewhat works around our memoization. 6898 verifyFormat( 6899 "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 6900 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 6901 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 6902 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 6903 " aaaaa())))))))))))))))))))))))))))))))))))))));", 6904 getLLVMStyleWithColumns(65)); 6905 verifyFormat( 6906 "aaaaa(\n" 6907 " aaaaa,\n" 6908 " aaaaa(\n" 6909 " aaaaa,\n" 6910 " aaaaa(\n" 6911 " aaaaa,\n" 6912 " aaaaa(\n" 6913 " aaaaa,\n" 6914 " aaaaa(\n" 6915 " aaaaa,\n" 6916 " aaaaa(\n" 6917 " aaaaa,\n" 6918 " aaaaa(\n" 6919 " aaaaa,\n" 6920 " aaaaa(\n" 6921 " aaaaa,\n" 6922 " aaaaa(\n" 6923 " aaaaa,\n" 6924 " aaaaa(\n" 6925 " aaaaa,\n" 6926 " aaaaa(\n" 6927 " aaaaa,\n" 6928 " aaaaa(\n" 6929 " aaaaa,\n" 6930 " aaaaa))))))))))));", 6931 getLLVMStyleWithColumns(65)); 6932 verifyFormat( 6933 "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" 6934 " a),\n" 6935 " a),\n" 6936 " a),\n" 6937 " a),\n" 6938 " a),\n" 6939 " a),\n" 6940 " a),\n" 6941 " a),\n" 6942 " a),\n" 6943 " a),\n" 6944 " a),\n" 6945 " a),\n" 6946 " a),\n" 6947 " a),\n" 6948 " a),\n" 6949 " a),\n" 6950 " a)", 6951 getLLVMStyleWithColumns(65)); 6952 6953 // This test takes VERY long when memoization is broken. 6954 FormatStyle OnePerLine = getLLVMStyle(); 6955 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6956 OnePerLine.BinPackParameters = false; 6957 std::string input = "Constructor()\n" 6958 " : aaaa(a,\n"; 6959 for (unsigned i = 0, e = 80; i != e; ++i) { 6960 input += " a,\n"; 6961 } 6962 input += " a) {}"; 6963 verifyFormat(input, OnePerLine); 6964 } 6965 #endif 6966 6967 TEST_F(FormatTest, BreaksAsHighAsPossible) { 6968 verifyFormat( 6969 "void f() {\n" 6970 " if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n" 6971 " (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n" 6972 " f();\n" 6973 "}"); 6974 verifyFormat("if (Intervals[i].getRange().getFirst() <\n" 6975 " Intervals[i - 1].getRange().getLast()) {\n}"); 6976 } 6977 6978 TEST_F(FormatTest, BreaksFunctionDeclarations) { 6979 // Principially, we break function declarations in a certain order: 6980 // 1) break amongst arguments. 6981 verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n" 6982 " Cccccccccccccc cccccccccccccc);"); 6983 verifyFormat("template <class TemplateIt>\n" 6984 "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n" 6985 " TemplateIt *stop) {}"); 6986 6987 // 2) break after return type. 6988 verifyFormat( 6989 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6990 "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);", 6991 getGoogleStyle()); 6992 6993 // 3) break after (. 6994 verifyFormat( 6995 "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n" 6996 " Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);", 6997 getGoogleStyle()); 6998 6999 // 4) break before after nested name specifiers. 7000 verifyFormat( 7001 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7002 "SomeClasssssssssssssssssssssssssssssssssssssss::\n" 7003 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);", 7004 getGoogleStyle()); 7005 7006 // However, there are exceptions, if a sufficient amount of lines can be 7007 // saved. 7008 // FIXME: The precise cut-offs wrt. the number of saved lines might need some 7009 // more adjusting. 7010 verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n" 7011 " Cccccccccccccc cccccccccc,\n" 7012 " Cccccccccccccc cccccccccc,\n" 7013 " Cccccccccccccc cccccccccc,\n" 7014 " Cccccccccccccc cccccccccc);"); 7015 verifyFormat( 7016 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7017 "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7018 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7019 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);", 7020 getGoogleStyle()); 7021 verifyFormat( 7022 "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n" 7023 " Cccccccccccccc cccccccccc,\n" 7024 " Cccccccccccccc cccccccccc,\n" 7025 " Cccccccccccccc cccccccccc,\n" 7026 " Cccccccccccccc cccccccccc,\n" 7027 " Cccccccccccccc cccccccccc,\n" 7028 " Cccccccccccccc cccccccccc);"); 7029 verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7030 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7031 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7032 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7033 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);"); 7034 7035 // Break after multi-line parameters. 7036 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7037 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7038 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7039 " bbbb bbbb);"); 7040 verifyFormat("void SomeLoooooooooooongFunction(\n" 7041 " std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n" 7042 " aaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7043 " int bbbbbbbbbbbbb);"); 7044 7045 // Treat overloaded operators like other functions. 7046 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 7047 "operator>(const SomeLoooooooooooooooooooooooooogType &other);"); 7048 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 7049 "operator>>(const SomeLooooooooooooooooooooooooogType &other);"); 7050 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 7051 "operator<<(const SomeLooooooooooooooooooooooooogType &other);"); 7052 verifyGoogleFormat( 7053 "SomeLoooooooooooooooooooooooooooooogType operator>>(\n" 7054 " const SomeLooooooooogType &a, const SomeLooooooooogType &b);"); 7055 verifyGoogleFormat( 7056 "SomeLoooooooooooooooooooooooooooooogType operator<<(\n" 7057 " const SomeLooooooooogType &a, const SomeLooooooooogType &b);"); 7058 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7059 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);"); 7060 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n" 7061 "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);"); 7062 verifyGoogleFormat( 7063 "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n" 7064 "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7065 " bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}"); 7066 verifyGoogleFormat("template <typename T>\n" 7067 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7068 "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n" 7069 " aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);"); 7070 7071 FormatStyle Style = getLLVMStyle(); 7072 Style.PointerAlignment = FormatStyle::PAS_Left; 7073 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7074 " aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}", 7075 Style); 7076 verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n" 7077 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7078 Style); 7079 } 7080 7081 TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) { 7082 // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516: 7083 // Prefer keeping `::` followed by `operator` together. 7084 EXPECT_EQ("const aaaa::bbbbbbb &\n" 7085 "ccccccccc::operator++() {\n" 7086 " stuff();\n" 7087 "}", 7088 format("const aaaa::bbbbbbb\n" 7089 "&ccccccccc::operator++() { stuff(); }", 7090 getLLVMStyleWithColumns(40))); 7091 } 7092 7093 TEST_F(FormatTest, TrailingReturnType) { 7094 verifyFormat("auto foo() -> int;\n"); 7095 // correct trailing return type spacing 7096 verifyFormat("auto operator->() -> int;\n"); 7097 verifyFormat("auto operator++(int) -> int;\n"); 7098 7099 verifyFormat("struct S {\n" 7100 " auto bar() const -> int;\n" 7101 "};"); 7102 verifyFormat("template <size_t Order, typename T>\n" 7103 "auto load_img(const std::string &filename)\n" 7104 " -> alias::tensor<Order, T, mem::tag::cpu> {}"); 7105 verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n" 7106 " -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}"); 7107 verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}"); 7108 verifyFormat("template <typename T>\n" 7109 "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n" 7110 " -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());"); 7111 7112 // Not trailing return types. 7113 verifyFormat("void f() { auto a = b->c(); }"); 7114 verifyFormat("auto a = p->foo();"); 7115 verifyFormat("int a = p->foo();"); 7116 verifyFormat("auto lmbd = [] NOEXCEPT -> int { return 0; };"); 7117 } 7118 7119 TEST_F(FormatTest, DeductionGuides) { 7120 verifyFormat("template <class T> A(const T &, const T &) -> A<T &>;"); 7121 verifyFormat("template <class T> explicit A(T &, T &&) -> A<T>;"); 7122 verifyFormat("template <class... Ts> S(Ts...) -> S<Ts...>;"); 7123 verifyFormat( 7124 "template <class... T>\n" 7125 "array(T &&...t) -> array<std::common_type_t<T...>, sizeof...(T)>;"); 7126 verifyFormat("template <class T> A() -> A<decltype(p->foo<3>())>;"); 7127 verifyFormat("template <class T> A() -> A<decltype(foo<traits<1>>)>;"); 7128 verifyFormat("template <class T> A() -> A<sizeof(p->foo<1>)>;"); 7129 verifyFormat("template <class T> A() -> A<(3 < 2)>;"); 7130 verifyFormat("template <class T> A() -> A<((3) < (2))>;"); 7131 verifyFormat("template <class T> x() -> x<1>;"); 7132 verifyFormat("template <class T> explicit x(T &) -> x<1>;"); 7133 7134 // Ensure not deduction guides. 7135 verifyFormat("c()->f<int>();"); 7136 verifyFormat("x()->foo<1>;"); 7137 verifyFormat("x = p->foo<3>();"); 7138 verifyFormat("x()->x<1>();"); 7139 verifyFormat("x()->x<1>;"); 7140 } 7141 7142 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) { 7143 // Avoid breaking before trailing 'const' or other trailing annotations, if 7144 // they are not function-like. 7145 FormatStyle Style = getGoogleStyleWithColumns(47); 7146 verifyFormat("void someLongFunction(\n" 7147 " int someLoooooooooooooongParameter) const {\n}", 7148 getLLVMStyleWithColumns(47)); 7149 verifyFormat("LoooooongReturnType\n" 7150 "someLoooooooongFunction() const {}", 7151 getLLVMStyleWithColumns(47)); 7152 verifyFormat("LoooooongReturnType someLoooooooongFunction()\n" 7153 " const {}", 7154 Style); 7155 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7156 " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;"); 7157 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7158 " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;"); 7159 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7160 " aaaaa aaaaaaaaaaaaaaaaaaaa) override final;"); 7161 verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n" 7162 " aaaaaaaaaaa aaaaa) const override;"); 7163 verifyGoogleFormat( 7164 "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7165 " const override;"); 7166 7167 // Even if the first parameter has to be wrapped. 7168 verifyFormat("void someLongFunction(\n" 7169 " int someLongParameter) const {}", 7170 getLLVMStyleWithColumns(46)); 7171 verifyFormat("void someLongFunction(\n" 7172 " int someLongParameter) const {}", 7173 Style); 7174 verifyFormat("void someLongFunction(\n" 7175 " int someLongParameter) override {}", 7176 Style); 7177 verifyFormat("void someLongFunction(\n" 7178 " int someLongParameter) OVERRIDE {}", 7179 Style); 7180 verifyFormat("void someLongFunction(\n" 7181 " int someLongParameter) final {}", 7182 Style); 7183 verifyFormat("void someLongFunction(\n" 7184 " int someLongParameter) FINAL {}", 7185 Style); 7186 verifyFormat("void someLongFunction(\n" 7187 " int parameter) const override {}", 7188 Style); 7189 7190 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 7191 verifyFormat("void someLongFunction(\n" 7192 " int someLongParameter) const\n" 7193 "{\n" 7194 "}", 7195 Style); 7196 7197 Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 7198 verifyFormat("void someLongFunction(\n" 7199 " int someLongParameter) const\n" 7200 " {\n" 7201 " }", 7202 Style); 7203 7204 // Unless these are unknown annotations. 7205 verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n" 7206 " aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7207 " LONG_AND_UGLY_ANNOTATION;"); 7208 7209 // Breaking before function-like trailing annotations is fine to keep them 7210 // close to their arguments. 7211 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7212 " LOCKS_EXCLUDED(aaaaaaaaaaaaa);"); 7213 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n" 7214 " LOCKS_EXCLUDED(aaaaaaaaaaaaa);"); 7215 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n" 7216 " LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}"); 7217 verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n" 7218 " AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);"); 7219 verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});"); 7220 7221 verifyFormat( 7222 "void aaaaaaaaaaaaaaaaaa()\n" 7223 " __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n" 7224 " aaaaaaaaaaaaaaaaaaaaaaaaa));"); 7225 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7226 " __attribute__((unused));"); 7227 verifyGoogleFormat( 7228 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7229 " GUARDED_BY(aaaaaaaaaaaa);"); 7230 verifyGoogleFormat( 7231 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7232 " GUARDED_BY(aaaaaaaaaaaa);"); 7233 verifyGoogleFormat( 7234 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n" 7235 " aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7236 verifyGoogleFormat( 7237 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n" 7238 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7239 } 7240 7241 TEST_F(FormatTest, FunctionAnnotations) { 7242 verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7243 "int OldFunction(const string ¶meter) {}"); 7244 verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7245 "string OldFunction(const string ¶meter) {}"); 7246 verifyFormat("template <typename T>\n" 7247 "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7248 "string OldFunction(const string ¶meter) {}"); 7249 7250 // Not function annotations. 7251 verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7252 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"); 7253 verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n" 7254 " ThisIsATestWithAReallyReallyReallyReallyLongName) {}"); 7255 verifyFormat("MACRO(abc).function() // wrap\n" 7256 " << abc;"); 7257 verifyFormat("MACRO(abc)->function() // wrap\n" 7258 " << abc;"); 7259 verifyFormat("MACRO(abc)::function() // wrap\n" 7260 " << abc;"); 7261 } 7262 7263 TEST_F(FormatTest, BreaksDesireably) { 7264 verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n" 7265 " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n" 7266 " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}"); 7267 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7268 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 7269 "}"); 7270 7271 verifyFormat( 7272 "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7273 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 7274 7275 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7276 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7277 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7278 7279 verifyFormat( 7280 "aaaaaaaa(aaaaaaaaaaaaa,\n" 7281 " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7282 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n" 7283 " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7284 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));"); 7285 7286 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 7287 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7288 7289 verifyFormat( 7290 "void f() {\n" 7291 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n" 7292 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 7293 "}"); 7294 verifyFormat( 7295 "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7296 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7297 verifyFormat( 7298 "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7299 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7300 verifyFormat( 7301 "aaaaaa(aaa,\n" 7302 " new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7303 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7304 " aaaa);"); 7305 verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7306 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7307 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7308 7309 // Indent consistently independent of call expression and unary operator. 7310 verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7311 " dddddddddddddddddddddddddddddd));"); 7312 verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7313 " dddddddddddddddddddddddddddddd));"); 7314 verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n" 7315 " dddddddddddddddddddddddddddddd));"); 7316 7317 // This test case breaks on an incorrect memoization, i.e. an optimization not 7318 // taking into account the StopAt value. 7319 verifyFormat( 7320 "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7321 " aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7322 " aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7323 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7324 7325 verifyFormat("{\n {\n {\n" 7326 " Annotation.SpaceRequiredBefore =\n" 7327 " Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n" 7328 " Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n" 7329 " }\n }\n}"); 7330 7331 // Break on an outer level if there was a break on an inner level. 7332 EXPECT_EQ("f(g(h(a, // comment\n" 7333 " b, c),\n" 7334 " d, e),\n" 7335 " x, y);", 7336 format("f(g(h(a, // comment\n" 7337 " b, c), d, e), x, y);")); 7338 7339 // Prefer breaking similar line breaks. 7340 verifyFormat( 7341 "const int kTrackingOptions = NSTrackingMouseMoved |\n" 7342 " NSTrackingMouseEnteredAndExited |\n" 7343 " NSTrackingActiveAlways;"); 7344 } 7345 7346 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) { 7347 FormatStyle NoBinPacking = getGoogleStyle(); 7348 NoBinPacking.BinPackParameters = false; 7349 NoBinPacking.BinPackArguments = true; 7350 verifyFormat("void f() {\n" 7351 " f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n" 7352 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 7353 "}", 7354 NoBinPacking); 7355 verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n" 7356 " int aaaaaaaaaaaaaaaaaaaa,\n" 7357 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7358 NoBinPacking); 7359 7360 NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false; 7361 verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7362 " vector<int> bbbbbbbbbbbbbbb);", 7363 NoBinPacking); 7364 // FIXME: This behavior difference is probably not wanted. However, currently 7365 // we cannot distinguish BreakBeforeParameter being set because of the wrapped 7366 // template arguments from BreakBeforeParameter being set because of the 7367 // one-per-line formatting. 7368 verifyFormat( 7369 "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n" 7370 " aaaaaaaaaa> aaaaaaaaaa);", 7371 NoBinPacking); 7372 verifyFormat( 7373 "void fffffffffff(\n" 7374 " aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n" 7375 " aaaaaaaaaa);"); 7376 } 7377 7378 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) { 7379 FormatStyle NoBinPacking = getGoogleStyle(); 7380 NoBinPacking.BinPackParameters = false; 7381 NoBinPacking.BinPackArguments = false; 7382 verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n" 7383 " aaaaaaaaaaaaaaaaaaaa,\n" 7384 " aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);", 7385 NoBinPacking); 7386 verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n" 7387 " aaaaaaaaaaaaa,\n" 7388 " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));", 7389 NoBinPacking); 7390 verifyFormat( 7391 "aaaaaaaa(aaaaaaaaaaaaa,\n" 7392 " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7393 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n" 7394 " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7395 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));", 7396 NoBinPacking); 7397 verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n" 7398 " .aaaaaaaaaaaaaaaaaa();", 7399 NoBinPacking); 7400 verifyFormat("void f() {\n" 7401 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7402 " aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n" 7403 "}", 7404 NoBinPacking); 7405 7406 verifyFormat( 7407 "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7408 " aaaaaaaaaaaa,\n" 7409 " aaaaaaaaaaaa);", 7410 NoBinPacking); 7411 verifyFormat( 7412 "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n" 7413 " ddddddddddddddddddddddddddddd),\n" 7414 " test);", 7415 NoBinPacking); 7416 7417 verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n" 7418 " aaaaaaaaaaaaaaaaaaaaaaa,\n" 7419 " aaaaaaaaaaaaaaaaaaaaaaa>\n" 7420 " aaaaaaaaaaaaaaaaaa;", 7421 NoBinPacking); 7422 verifyFormat("a(\"a\"\n" 7423 " \"a\",\n" 7424 " a);"); 7425 7426 NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false; 7427 verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n" 7428 " aaaaaaaaa,\n" 7429 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7430 NoBinPacking); 7431 verifyFormat( 7432 "void f() {\n" 7433 " aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n" 7434 " .aaaaaaa();\n" 7435 "}", 7436 NoBinPacking); 7437 verifyFormat( 7438 "template <class SomeType, class SomeOtherType>\n" 7439 "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}", 7440 NoBinPacking); 7441 } 7442 7443 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) { 7444 FormatStyle Style = getLLVMStyleWithColumns(15); 7445 Style.ExperimentalAutoDetectBinPacking = true; 7446 EXPECT_EQ("aaa(aaaa,\n" 7447 " aaaa,\n" 7448 " aaaa);\n" 7449 "aaa(aaaa,\n" 7450 " aaaa,\n" 7451 " aaaa);", 7452 format("aaa(aaaa,\n" // one-per-line 7453 " aaaa,\n" 7454 " aaaa );\n" 7455 "aaa(aaaa, aaaa, aaaa);", // inconclusive 7456 Style)); 7457 EXPECT_EQ("aaa(aaaa, aaaa,\n" 7458 " aaaa);\n" 7459 "aaa(aaaa, aaaa,\n" 7460 " aaaa);", 7461 format("aaa(aaaa, aaaa,\n" // bin-packed 7462 " aaaa );\n" 7463 "aaa(aaaa, aaaa, aaaa);", // inconclusive 7464 Style)); 7465 } 7466 7467 TEST_F(FormatTest, FormatsBuilderPattern) { 7468 verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n" 7469 " .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n" 7470 " .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n" 7471 " .StartsWith(\".init\", ORDER_INIT)\n" 7472 " .StartsWith(\".fini\", ORDER_FINI)\n" 7473 " .StartsWith(\".hash\", ORDER_HASH)\n" 7474 " .Default(ORDER_TEXT);\n"); 7475 7476 verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n" 7477 " aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();"); 7478 verifyFormat("aaaaaaa->aaaaaaa\n" 7479 " ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7480 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7481 " ->aaaaaaaa(aaaaaaaaaaaaaaa);"); 7482 verifyFormat( 7483 "aaaaaaa->aaaaaaa\n" 7484 " ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7485 " ->aaaaaaaa(aaaaaaaaaaaaaaa);"); 7486 verifyFormat( 7487 "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n" 7488 " aaaaaaaaaaaaaa);"); 7489 verifyFormat( 7490 "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n" 7491 " aaaaaa->aaaaaaaaaaaa()\n" 7492 " ->aaaaaaaaaaaaaaaa(\n" 7493 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7494 " ->aaaaaaaaaaaaaaaaa();"); 7495 verifyGoogleFormat( 7496 "void f() {\n" 7497 " someo->Add((new util::filetools::Handler(dir))\n" 7498 " ->OnEvent1(NewPermanentCallback(\n" 7499 " this, &HandlerHolderClass::EventHandlerCBA))\n" 7500 " ->OnEvent2(NewPermanentCallback(\n" 7501 " this, &HandlerHolderClass::EventHandlerCBB))\n" 7502 " ->OnEvent3(NewPermanentCallback(\n" 7503 " this, &HandlerHolderClass::EventHandlerCBC))\n" 7504 " ->OnEvent5(NewPermanentCallback(\n" 7505 " this, &HandlerHolderClass::EventHandlerCBD))\n" 7506 " ->OnEvent6(NewPermanentCallback(\n" 7507 " this, &HandlerHolderClass::EventHandlerCBE)));\n" 7508 "}"); 7509 7510 verifyFormat( 7511 "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();"); 7512 verifyFormat("aaaaaaaaaaaaaaa()\n" 7513 " .aaaaaaaaaaaaaaa()\n" 7514 " .aaaaaaaaaaaaaaa()\n" 7515 " .aaaaaaaaaaaaaaa()\n" 7516 " .aaaaaaaaaaaaaaa();"); 7517 verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7518 " .aaaaaaaaaaaaaaa()\n" 7519 " .aaaaaaaaaaaaaaa()\n" 7520 " .aaaaaaaaaaaaaaa();"); 7521 verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7522 " .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7523 " .aaaaaaaaaaaaaaa();"); 7524 verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n" 7525 " ->aaaaaaaaaaaaaae(0)\n" 7526 " ->aaaaaaaaaaaaaaa();"); 7527 7528 // Don't linewrap after very short segments. 7529 verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7530 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7531 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7532 verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7533 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7534 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7535 verifyFormat("aaa()\n" 7536 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7537 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7538 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7539 7540 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n" 7541 " .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7542 " .has<bbbbbbbbbbbbbbbbbbbbb>();"); 7543 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n" 7544 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 7545 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();"); 7546 7547 // Prefer not to break after empty parentheses. 7548 verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n" 7549 " First->LastNewlineOffset);"); 7550 7551 // Prefer not to create "hanging" indents. 7552 verifyFormat( 7553 "return !soooooooooooooome_map\n" 7554 " .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7555 " .second;"); 7556 verifyFormat( 7557 "return aaaaaaaaaaaaaaaa\n" 7558 " .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n" 7559 " .aaaa(aaaaaaaaaaaaaa);"); 7560 // No hanging indent here. 7561 verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n" 7562 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7563 verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n" 7564 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7565 verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n" 7566 " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7567 getLLVMStyleWithColumns(60)); 7568 verifyFormat("aaaaaaaaaaaaaaaaaa\n" 7569 " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n" 7570 " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7571 getLLVMStyleWithColumns(59)); 7572 verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7573 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7574 " .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7575 7576 // Dont break if only closing statements before member call 7577 verifyFormat("test() {\n" 7578 " ([]() -> {\n" 7579 " int b = 32;\n" 7580 " return 3;\n" 7581 " }).foo();\n" 7582 "}"); 7583 verifyFormat("test() {\n" 7584 " (\n" 7585 " []() -> {\n" 7586 " int b = 32;\n" 7587 " return 3;\n" 7588 " },\n" 7589 " foo, bar)\n" 7590 " .foo();\n" 7591 "}"); 7592 verifyFormat("test() {\n" 7593 " ([]() -> {\n" 7594 " int b = 32;\n" 7595 " return 3;\n" 7596 " })\n" 7597 " .foo()\n" 7598 " .bar();\n" 7599 "}"); 7600 verifyFormat("test() {\n" 7601 " ([]() -> {\n" 7602 " int b = 32;\n" 7603 " return 3;\n" 7604 " })\n" 7605 " .foo(\"aaaaaaaaaaaaaaaaa\"\n" 7606 " \"bbbb\");\n" 7607 "}", 7608 getLLVMStyleWithColumns(30)); 7609 } 7610 7611 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) { 7612 verifyFormat( 7613 "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 7614 " bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}"); 7615 verifyFormat( 7616 "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n" 7617 " bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}"); 7618 7619 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" 7620 " ccccccccccccccccccccccccc) {\n}"); 7621 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n" 7622 " ccccccccccccccccccccccccc) {\n}"); 7623 7624 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" 7625 " ccccccccccccccccccccccccc) {\n}"); 7626 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n" 7627 " ccccccccccccccccccccccccc) {\n}"); 7628 7629 verifyFormat( 7630 "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n" 7631 " ccccccccccccccccccccccccc) {\n}"); 7632 verifyFormat( 7633 "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n" 7634 " ccccccccccccccccccccccccc) {\n}"); 7635 7636 verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n" 7637 " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n" 7638 " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n" 7639 " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;"); 7640 verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n" 7641 " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n" 7642 " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n" 7643 " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;"); 7644 7645 verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n" 7646 " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n" 7647 " aaaaaaaaaaaaaaa != aa) {\n}"); 7648 verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n" 7649 " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n" 7650 " aaaaaaaaaaaaaaa != aa) {\n}"); 7651 } 7652 7653 TEST_F(FormatTest, BreaksAfterAssignments) { 7654 verifyFormat( 7655 "unsigned Cost =\n" 7656 " TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n" 7657 " SI->getPointerAddressSpaceee());\n"); 7658 verifyFormat( 7659 "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n" 7660 " Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());"); 7661 7662 verifyFormat( 7663 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n" 7664 " aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);"); 7665 verifyFormat("unsigned OriginalStartColumn =\n" 7666 " SourceMgr.getSpellingColumnNumber(\n" 7667 " Current.FormatTok.getStartOfNonWhitespace()) -\n" 7668 " 1;"); 7669 } 7670 7671 TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) { 7672 FormatStyle Style = getLLVMStyle(); 7673 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 7674 " bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;", 7675 Style); 7676 7677 Style.PenaltyBreakAssignment = 20; 7678 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n" 7679 " cccccccccccccccccccccccccc;", 7680 Style); 7681 } 7682 7683 TEST_F(FormatTest, AlignsAfterAssignments) { 7684 verifyFormat( 7685 "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7686 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7687 verifyFormat( 7688 "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7689 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7690 verifyFormat( 7691 "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7692 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7693 verifyFormat( 7694 "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7695 " aaaaaaaaaaaaaaaaaaaaaaaaa);"); 7696 verifyFormat( 7697 "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n" 7698 " aaaaaaaaaaaaaaaaaaaaaaaa +\n" 7699 " aaaaaaaaaaaaaaaaaaaaaaaa;"); 7700 } 7701 7702 TEST_F(FormatTest, AlignsAfterReturn) { 7703 verifyFormat( 7704 "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7705 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7706 verifyFormat( 7707 "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7708 " aaaaaaaaaaaaaaaaaaaaaaaaa);"); 7709 verifyFormat( 7710 "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n" 7711 " aaaaaaaaaaaaaaaaaaaaaa();"); 7712 verifyFormat( 7713 "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n" 7714 " aaaaaaaaaaaaaaaaaaaaaa());"); 7715 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7716 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7717 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7718 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n" 7719 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7720 verifyFormat("return\n" 7721 " // true if code is one of a or b.\n" 7722 " code == a || code == b;"); 7723 } 7724 7725 TEST_F(FormatTest, AlignsAfterOpenBracket) { 7726 verifyFormat( 7727 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n" 7728 " aaaaaaaaa aaaaaaa) {}"); 7729 verifyFormat( 7730 "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n" 7731 " aaaaaaaaaaa aaaaaaaaa);"); 7732 verifyFormat( 7733 "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n" 7734 " aaaaaaaaaaaaaaaaaaaaa));"); 7735 FormatStyle Style = getLLVMStyle(); 7736 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 7737 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7738 " aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}", 7739 Style); 7740 verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n" 7741 " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);", 7742 Style); 7743 verifyFormat("SomeLongVariableName->someFunction(\n" 7744 " foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));", 7745 Style); 7746 verifyFormat( 7747 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n" 7748 " aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7749 Style); 7750 verifyFormat( 7751 "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n" 7752 " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7753 Style); 7754 verifyFormat( 7755 "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n" 7756 " aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));", 7757 Style); 7758 7759 verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n" 7760 " ccccccc(aaaaaaaaaaaaaaaaa, //\n" 7761 " b));", 7762 Style); 7763 7764 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 7765 Style.BinPackArguments = false; 7766 Style.BinPackParameters = false; 7767 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7768 " aaaaaaaaaaa aaaaaaaa,\n" 7769 " aaaaaaaaa aaaaaaa,\n" 7770 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7771 Style); 7772 verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n" 7773 " aaaaaaaaaaa aaaaaaaaa,\n" 7774 " aaaaaaaaaaa aaaaaaaaa,\n" 7775 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7776 Style); 7777 verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n" 7778 " aaaaaaaaaaaaaaa,\n" 7779 " aaaaaaaaaaaaaaaaaaaaa,\n" 7780 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));", 7781 Style); 7782 verifyFormat( 7783 "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n" 7784 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));", 7785 Style); 7786 verifyFormat( 7787 "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n" 7788 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));", 7789 Style); 7790 verifyFormat( 7791 "aaaaaaaaaaaaaaaaaaaaaaaa(\n" 7792 " aaaaaaaaaaaaaaaaaaaaa(\n" 7793 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n" 7794 " aaaaaaaaaaaaaaaa);", 7795 Style); 7796 verifyFormat( 7797 "aaaaaaaaaaaaaaaaaaaaaaaa(\n" 7798 " aaaaaaaaaaaaaaaaaaaaa(\n" 7799 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n" 7800 " aaaaaaaaaaaaaaaa);", 7801 Style); 7802 } 7803 7804 TEST_F(FormatTest, ParenthesesAndOperandAlignment) { 7805 FormatStyle Style = getLLVMStyleWithColumns(40); 7806 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 7807 " bbbbbbbbbbbbbbbbbbbbbb);", 7808 Style); 7809 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 7810 Style.AlignOperands = FormatStyle::OAS_DontAlign; 7811 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 7812 " bbbbbbbbbbbbbbbbbbbbbb);", 7813 Style); 7814 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 7815 Style.AlignOperands = FormatStyle::OAS_Align; 7816 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 7817 " bbbbbbbbbbbbbbbbbbbbbb);", 7818 Style); 7819 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 7820 Style.AlignOperands = FormatStyle::OAS_DontAlign; 7821 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 7822 " bbbbbbbbbbbbbbbbbbbbbb);", 7823 Style); 7824 } 7825 7826 TEST_F(FormatTest, BreaksConditionalExpressions) { 7827 verifyFormat( 7828 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7829 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7830 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7831 verifyFormat( 7832 "aaaa(aaaaaaaaaa, aaaaaaaa,\n" 7833 " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7834 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7835 verifyFormat( 7836 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7837 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7838 verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n" 7839 " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7840 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7841 verifyFormat( 7842 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n" 7843 " : aaaaaaaaaaaaa);"); 7844 verifyFormat( 7845 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7846 " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7847 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7848 " aaaaaaaaaaaaa);"); 7849 verifyFormat( 7850 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7851 " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7852 " aaaaaaaaaaaaa);"); 7853 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7854 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7855 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7856 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7857 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7858 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7859 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7860 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7861 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7862 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7863 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7864 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7865 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7866 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7867 " ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7868 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7869 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7870 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7871 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7872 " : aaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7873 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n" 7874 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7875 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7876 " : aaaaaaaaaaaaaaaa;"); 7877 verifyFormat( 7878 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7879 " ? aaaaaaaaaaaaaaa\n" 7880 " : aaaaaaaaaaaaaaa;"); 7881 verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n" 7882 " aaaaaaaaa\n" 7883 " ? b\n" 7884 " : c);"); 7885 verifyFormat("return aaaa == bbbb\n" 7886 " // comment\n" 7887 " ? aaaa\n" 7888 " : bbbb;"); 7889 verifyFormat("unsigned Indent =\n" 7890 " format(TheLine.First,\n" 7891 " IndentForLevel[TheLine.Level] >= 0\n" 7892 " ? IndentForLevel[TheLine.Level]\n" 7893 " : TheLine * 2,\n" 7894 " TheLine.InPPDirective, PreviousEndOfLineColumn);", 7895 getLLVMStyleWithColumns(60)); 7896 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n" 7897 " ? aaaaaaaaaaaaaaa\n" 7898 " : bbbbbbbbbbbbbbb //\n" 7899 " ? ccccccccccccccc\n" 7900 " : ddddddddddddddd;"); 7901 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n" 7902 " ? aaaaaaaaaaaaaaa\n" 7903 " : (bbbbbbbbbbbbbbb //\n" 7904 " ? ccccccccccccccc\n" 7905 " : ddddddddddddddd);"); 7906 verifyFormat( 7907 "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7908 " ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7909 " aaaaaaaaaaaaaaaaaaaaa +\n" 7910 " aaaaaaaaaaaaaaaaaaaaa\n" 7911 " : aaaaaaaaaa;"); 7912 verifyFormat( 7913 "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7914 " : aaaaaaaaaaaaaaaaaaaaaa\n" 7915 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7916 7917 FormatStyle NoBinPacking = getLLVMStyle(); 7918 NoBinPacking.BinPackArguments = false; 7919 verifyFormat( 7920 "void f() {\n" 7921 " g(aaa,\n" 7922 " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n" 7923 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7924 " ? aaaaaaaaaaaaaaa\n" 7925 " : aaaaaaaaaaaaaaa);\n" 7926 "}", 7927 NoBinPacking); 7928 verifyFormat( 7929 "void f() {\n" 7930 " g(aaa,\n" 7931 " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n" 7932 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7933 " ?: aaaaaaaaaaaaaaa);\n" 7934 "}", 7935 NoBinPacking); 7936 7937 verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n" 7938 " // comment.\n" 7939 " ccccccccccccccccccccccccccccccccccccccc\n" 7940 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7941 " : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);"); 7942 7943 // Assignments in conditional expressions. Apparently not uncommon :-(. 7944 verifyFormat("return a != b\n" 7945 " // comment\n" 7946 " ? a = b\n" 7947 " : a = b;"); 7948 verifyFormat("return a != b\n" 7949 " // comment\n" 7950 " ? a = a != b\n" 7951 " // comment\n" 7952 " ? a = b\n" 7953 " : a\n" 7954 " : a;\n"); 7955 verifyFormat("return a != b\n" 7956 " // comment\n" 7957 " ? a\n" 7958 " : a = a != b\n" 7959 " // comment\n" 7960 " ? a = b\n" 7961 " : a;"); 7962 7963 // Chained conditionals 7964 FormatStyle Style = getLLVMStyleWithColumns(70); 7965 Style.AlignOperands = FormatStyle::OAS_Align; 7966 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 7967 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7968 " : 3333333333333333;", 7969 Style); 7970 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 7971 " : bbbbbbbbbb ? 2222222222222222\n" 7972 " : 3333333333333333;", 7973 Style); 7974 verifyFormat("return aaaaaaaaaa ? 1111111111111111\n" 7975 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 7976 " : 3333333333333333;", 7977 Style); 7978 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 7979 " : bbbbbbbbbbbbbb ? 222222\n" 7980 " : 333333;", 7981 Style); 7982 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 7983 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7984 " : cccccccccccccc ? 3333333333333333\n" 7985 " : 4444444444444444;", 7986 Style); 7987 verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc)\n" 7988 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7989 " : 3333333333333333;", 7990 Style); 7991 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 7992 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7993 " : (aaa ? bbb : ccc);", 7994 Style); 7995 verifyFormat( 7996 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 7997 " : cccccccccccccccccc)\n" 7998 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7999 " : 3333333333333333;", 8000 Style); 8001 verifyFormat( 8002 "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8003 " : cccccccccccccccccc)\n" 8004 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8005 " : 3333333333333333;", 8006 Style); 8007 verifyFormat( 8008 "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8009 " : dddddddddddddddddd)\n" 8010 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8011 " : 3333333333333333;", 8012 Style); 8013 verifyFormat( 8014 "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8015 " : dddddddddddddddddd)\n" 8016 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8017 " : 3333333333333333;", 8018 Style); 8019 verifyFormat( 8020 "return aaaaaaaaa ? 1111111111111111\n" 8021 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8022 " : a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8023 " : dddddddddddddddddd)\n", 8024 Style); 8025 verifyFormat( 8026 "return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8027 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8028 " : (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8029 " : cccccccccccccccccc);", 8030 Style); 8031 verifyFormat( 8032 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8033 " : ccccccccccccccc ? dddddddddddddddddd\n" 8034 " : eeeeeeeeeeeeeeeeee)\n" 8035 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8036 " : 3333333333333333;", 8037 Style); 8038 verifyFormat( 8039 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8040 " : ccccccccccccccc ? dddddddddddddddddd\n" 8041 " : eeeeeeeeeeeeeeeeee)\n" 8042 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8043 " : 3333333333333333;", 8044 Style); 8045 verifyFormat( 8046 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8047 " : cccccccccccc ? dddddddddddddddddd\n" 8048 " : eeeeeeeeeeeeeeeeee)\n" 8049 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8050 " : 3333333333333333;", 8051 Style); 8052 verifyFormat( 8053 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8054 " : cccccccccccccccccc\n" 8055 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8056 " : 3333333333333333;", 8057 Style); 8058 verifyFormat( 8059 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8060 " : cccccccccccccccc ? dddddddddddddddddd\n" 8061 " : eeeeeeeeeeeeeeeeee\n" 8062 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8063 " : 3333333333333333;", 8064 Style); 8065 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa\n" 8066 " ? (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8067 " : cccccccccccccccccc ? dddddddddddddddddd\n" 8068 " : eeeeeeeeeeeeeeeeee)\n" 8069 " : bbbbbbbbbbbbbbbbbbb ? 2222222222222222\n" 8070 " : 3333333333333333;", 8071 Style); 8072 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaa\n" 8073 " ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8074 " : cccccccccccccccc ? dddddddddddddddddd\n" 8075 " : eeeeeeeeeeeeeeeeee\n" 8076 " : bbbbbbbbbbbbbbbbbbbbbbb ? 2222222222222222\n" 8077 " : 3333333333333333;", 8078 Style); 8079 8080 Style.AlignOperands = FormatStyle::OAS_DontAlign; 8081 Style.BreakBeforeTernaryOperators = false; 8082 // FIXME: Aligning the question marks is weird given DontAlign. 8083 // Consider disabling this alignment in this case. Also check whether this 8084 // will render the adjustment from https://reviews.llvm.org/D82199 8085 // unnecessary. 8086 verifyFormat("int x = aaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa :\n" 8087 " bbbb ? cccccccccccccccccc :\n" 8088 " ddddd;\n", 8089 Style); 8090 8091 EXPECT_EQ( 8092 "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n" 8093 " /*\n" 8094 " */\n" 8095 " function() {\n" 8096 " try {\n" 8097 " return JJJJJJJJJJJJJJ(\n" 8098 " pppppppppppppppppppppppppppppppppppppppppppppppppp);\n" 8099 " }\n" 8100 " } :\n" 8101 " function() {};", 8102 format( 8103 "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n" 8104 " /*\n" 8105 " */\n" 8106 " function() {\n" 8107 " try {\n" 8108 " return JJJJJJJJJJJJJJ(\n" 8109 " pppppppppppppppppppppppppppppppppppppppppppppppppp);\n" 8110 " }\n" 8111 " } :\n" 8112 " function() {};", 8113 getGoogleStyle(FormatStyle::LK_JavaScript))); 8114 } 8115 8116 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) { 8117 FormatStyle Style = getLLVMStyleWithColumns(70); 8118 Style.BreakBeforeTernaryOperators = false; 8119 verifyFormat( 8120 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8121 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8122 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8123 Style); 8124 verifyFormat( 8125 "aaaa(aaaaaaaaaa, aaaaaaaa,\n" 8126 " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8127 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8128 Style); 8129 verifyFormat( 8130 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8131 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8132 Style); 8133 verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n" 8134 " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8135 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8136 Style); 8137 verifyFormat( 8138 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n" 8139 " aaaaaaaaaaaaa);", 8140 Style); 8141 verifyFormat( 8142 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8143 " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8144 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8145 " aaaaaaaaaaaaa);", 8146 Style); 8147 verifyFormat( 8148 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8149 " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8150 " aaaaaaaaaaaaa);", 8151 Style); 8152 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8153 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8154 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 8155 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8156 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8157 Style); 8158 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8159 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8160 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8161 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 8162 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8163 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8164 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8165 Style); 8166 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8167 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n" 8168 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8169 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8170 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8171 Style); 8172 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8173 " aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8174 " aaaaaaaaaaaaaaaaaaaaaaaaaaa;", 8175 Style); 8176 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n" 8177 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8178 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8179 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 8180 Style); 8181 verifyFormat( 8182 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8183 " aaaaaaaaaaaaaaa :\n" 8184 " aaaaaaaaaaaaaaa;", 8185 Style); 8186 verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n" 8187 " aaaaaaaaa ?\n" 8188 " b :\n" 8189 " c);", 8190 Style); 8191 verifyFormat("unsigned Indent =\n" 8192 " format(TheLine.First,\n" 8193 " IndentForLevel[TheLine.Level] >= 0 ?\n" 8194 " IndentForLevel[TheLine.Level] :\n" 8195 " TheLine * 2,\n" 8196 " TheLine.InPPDirective, PreviousEndOfLineColumn);", 8197 Style); 8198 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n" 8199 " aaaaaaaaaaaaaaa :\n" 8200 " bbbbbbbbbbbbbbb ? //\n" 8201 " ccccccccccccccc :\n" 8202 " ddddddddddddddd;", 8203 Style); 8204 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n" 8205 " aaaaaaaaaaaaaaa :\n" 8206 " (bbbbbbbbbbbbbbb ? //\n" 8207 " ccccccccccccccc :\n" 8208 " ddddddddddddddd);", 8209 Style); 8210 verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8211 " /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n" 8212 " ccccccccccccccccccccccccccc;", 8213 Style); 8214 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8215 " aaaaa :\n" 8216 " bbbbbbbbbbbbbbb + cccccccccccccccc;", 8217 Style); 8218 8219 // Chained conditionals 8220 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8221 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8222 " 3333333333333333;", 8223 Style); 8224 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8225 " bbbbbbbbbb ? 2222222222222222 :\n" 8226 " 3333333333333333;", 8227 Style); 8228 verifyFormat("return aaaaaaaaaa ? 1111111111111111 :\n" 8229 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8230 " 3333333333333333;", 8231 Style); 8232 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8233 " bbbbbbbbbbbbbbbb ? 222222 :\n" 8234 " 333333;", 8235 Style); 8236 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8237 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8238 " cccccccccccccccc ? 3333333333333333 :\n" 8239 " 4444444444444444;", 8240 Style); 8241 verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc) :\n" 8242 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8243 " 3333333333333333;", 8244 Style); 8245 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8246 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8247 " (aaa ? bbb : ccc);", 8248 Style); 8249 verifyFormat( 8250 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8251 " cccccccccccccccccc) :\n" 8252 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8253 " 3333333333333333;", 8254 Style); 8255 verifyFormat( 8256 "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8257 " cccccccccccccccccc) :\n" 8258 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8259 " 3333333333333333;", 8260 Style); 8261 verifyFormat( 8262 "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8263 " dddddddddddddddddd) :\n" 8264 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8265 " 3333333333333333;", 8266 Style); 8267 verifyFormat( 8268 "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8269 " dddddddddddddddddd) :\n" 8270 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8271 " 3333333333333333;", 8272 Style); 8273 verifyFormat( 8274 "return aaaaaaaaa ? 1111111111111111 :\n" 8275 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8276 " a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8277 " dddddddddddddddddd)\n", 8278 Style); 8279 verifyFormat( 8280 "return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8281 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8282 " (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8283 " cccccccccccccccccc);", 8284 Style); 8285 verifyFormat( 8286 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8287 " ccccccccccccccccc ? dddddddddddddddddd :\n" 8288 " eeeeeeeeeeeeeeeeee) :\n" 8289 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8290 " 3333333333333333;", 8291 Style); 8292 verifyFormat( 8293 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8294 " ccccccccccccc ? dddddddddddddddddd :\n" 8295 " eeeeeeeeeeeeeeeeee) :\n" 8296 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8297 " 3333333333333333;", 8298 Style); 8299 verifyFormat( 8300 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8301 " ccccccccccccccccc ? dddddddddddddddddd :\n" 8302 " eeeeeeeeeeeeeeeeee) :\n" 8303 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8304 " 3333333333333333;", 8305 Style); 8306 verifyFormat( 8307 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8308 " cccccccccccccccccc :\n" 8309 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8310 " 3333333333333333;", 8311 Style); 8312 verifyFormat( 8313 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8314 " cccccccccccccccccc ? dddddddddddddddddd :\n" 8315 " eeeeeeeeeeeeeeeeee :\n" 8316 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8317 " 3333333333333333;", 8318 Style); 8319 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n" 8320 " (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8321 " cccccccccccccccccc ? dddddddddddddddddd :\n" 8322 " eeeeeeeeeeeeeeeeee) :\n" 8323 " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8324 " 3333333333333333;", 8325 Style); 8326 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n" 8327 " aaaaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8328 " cccccccccccccccccccc ? dddddddddddddddddd :\n" 8329 " eeeeeeeeeeeeeeeeee :\n" 8330 " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8331 " 3333333333333333;", 8332 Style); 8333 } 8334 8335 TEST_F(FormatTest, DeclarationsOfMultipleVariables) { 8336 verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n" 8337 " aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();"); 8338 verifyFormat("bool a = true, b = false;"); 8339 8340 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n" 8341 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n" 8342 " bbbbbbbbbbbbbbbbbbbbbbbbb =\n" 8343 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);"); 8344 verifyFormat( 8345 "bool aaaaaaaaaaaaaaaaaaaaa =\n" 8346 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n" 8347 " d = e && f;"); 8348 verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n" 8349 " c = cccccccccccccccccccc, d = dddddddddddddddddddd;"); 8350 verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n" 8351 " *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;"); 8352 verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n" 8353 " ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;"); 8354 8355 FormatStyle Style = getGoogleStyle(); 8356 Style.PointerAlignment = FormatStyle::PAS_Left; 8357 Style.DerivePointerAlignment = false; 8358 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8359 " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n" 8360 " *b = bbbbbbbbbbbbbbbbbbb;", 8361 Style); 8362 verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n" 8363 " *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;", 8364 Style); 8365 verifyFormat("vector<int*> a, b;", Style); 8366 verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style); 8367 } 8368 8369 TEST_F(FormatTest, ConditionalExpressionsInBrackets) { 8370 verifyFormat("arr[foo ? bar : baz];"); 8371 verifyFormat("f()[foo ? bar : baz];"); 8372 verifyFormat("(a + b)[foo ? bar : baz];"); 8373 verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];"); 8374 } 8375 8376 TEST_F(FormatTest, AlignsStringLiterals) { 8377 verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n" 8378 " \"short literal\");"); 8379 verifyFormat( 8380 "looooooooooooooooooooooooongFunction(\n" 8381 " \"short literal\"\n" 8382 " \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");"); 8383 verifyFormat("someFunction(\"Always break between multi-line\"\n" 8384 " \" string literals\",\n" 8385 " and, other, parameters);"); 8386 EXPECT_EQ("fun + \"1243\" /* comment */\n" 8387 " \"5678\";", 8388 format("fun + \"1243\" /* comment */\n" 8389 " \"5678\";", 8390 getLLVMStyleWithColumns(28))); 8391 EXPECT_EQ( 8392 "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 8393 " \"aaaaaaaaaaaaaaaaaaaaa\"\n" 8394 " \"aaaaaaaaaaaaaaaa\";", 8395 format("aaaaaa =" 8396 "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa " 8397 "aaaaaaaaaaaaaaaaaaaaa\" " 8398 "\"aaaaaaaaaaaaaaaa\";")); 8399 verifyFormat("a = a + \"a\"\n" 8400 " \"a\"\n" 8401 " \"a\";"); 8402 verifyFormat("f(\"a\", \"b\"\n" 8403 " \"c\");"); 8404 8405 verifyFormat( 8406 "#define LL_FORMAT \"ll\"\n" 8407 "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n" 8408 " \"d, ddddddddd: %\" LL_FORMAT \"d\");"); 8409 8410 verifyFormat("#define A(X) \\\n" 8411 " \"aaaaa\" #X \"bbbbbb\" \\\n" 8412 " \"ccccc\"", 8413 getLLVMStyleWithColumns(23)); 8414 verifyFormat("#define A \"def\"\n" 8415 "f(\"abc\" A \"ghi\"\n" 8416 " \"jkl\");"); 8417 8418 verifyFormat("f(L\"a\"\n" 8419 " L\"b\");"); 8420 verifyFormat("#define A(X) \\\n" 8421 " L\"aaaaa\" #X L\"bbbbbb\" \\\n" 8422 " L\"ccccc\"", 8423 getLLVMStyleWithColumns(25)); 8424 8425 verifyFormat("f(@\"a\"\n" 8426 " @\"b\");"); 8427 verifyFormat("NSString s = @\"a\"\n" 8428 " @\"b\"\n" 8429 " @\"c\";"); 8430 verifyFormat("NSString s = @\"a\"\n" 8431 " \"b\"\n" 8432 " \"c\";"); 8433 } 8434 8435 TEST_F(FormatTest, ReturnTypeBreakingStyle) { 8436 FormatStyle Style = getLLVMStyle(); 8437 // No declarations or definitions should be moved to own line. 8438 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None; 8439 verifyFormat("class A {\n" 8440 " int f() { return 1; }\n" 8441 " int g();\n" 8442 "};\n" 8443 "int f() { return 1; }\n" 8444 "int g();\n", 8445 Style); 8446 8447 // All declarations and definitions should have the return type moved to its 8448 // own line. 8449 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 8450 Style.TypenameMacros = {"LIST"}; 8451 verifyFormat("SomeType\n" 8452 "funcdecl(LIST(uint64_t));", 8453 Style); 8454 verifyFormat("class E {\n" 8455 " int\n" 8456 " f() {\n" 8457 " return 1;\n" 8458 " }\n" 8459 " int\n" 8460 " g();\n" 8461 "};\n" 8462 "int\n" 8463 "f() {\n" 8464 " return 1;\n" 8465 "}\n" 8466 "int\n" 8467 "g();\n", 8468 Style); 8469 8470 // Top-level definitions, and no kinds of declarations should have the 8471 // return type moved to its own line. 8472 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions; 8473 verifyFormat("class B {\n" 8474 " int f() { return 1; }\n" 8475 " int g();\n" 8476 "};\n" 8477 "int\n" 8478 "f() {\n" 8479 " return 1;\n" 8480 "}\n" 8481 "int g();\n", 8482 Style); 8483 8484 // Top-level definitions and declarations should have the return type moved 8485 // to its own line. 8486 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel; 8487 verifyFormat("class C {\n" 8488 " int f() { return 1; }\n" 8489 " int g();\n" 8490 "};\n" 8491 "int\n" 8492 "f() {\n" 8493 " return 1;\n" 8494 "}\n" 8495 "int\n" 8496 "g();\n", 8497 Style); 8498 8499 // All definitions should have the return type moved to its own line, but no 8500 // kinds of declarations. 8501 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions; 8502 verifyFormat("class D {\n" 8503 " int\n" 8504 " f() {\n" 8505 " return 1;\n" 8506 " }\n" 8507 " int g();\n" 8508 "};\n" 8509 "int\n" 8510 "f() {\n" 8511 " return 1;\n" 8512 "}\n" 8513 "int g();\n", 8514 Style); 8515 verifyFormat("const char *\n" 8516 "f(void) {\n" // Break here. 8517 " return \"\";\n" 8518 "}\n" 8519 "const char *bar(void);\n", // No break here. 8520 Style); 8521 verifyFormat("template <class T>\n" 8522 "T *\n" 8523 "f(T &c) {\n" // Break here. 8524 " return NULL;\n" 8525 "}\n" 8526 "template <class T> T *f(T &c);\n", // No break here. 8527 Style); 8528 verifyFormat("class C {\n" 8529 " int\n" 8530 " operator+() {\n" 8531 " return 1;\n" 8532 " }\n" 8533 " int\n" 8534 " operator()() {\n" 8535 " return 1;\n" 8536 " }\n" 8537 "};\n", 8538 Style); 8539 verifyFormat("void\n" 8540 "A::operator()() {}\n" 8541 "void\n" 8542 "A::operator>>() {}\n" 8543 "void\n" 8544 "A::operator+() {}\n" 8545 "void\n" 8546 "A::operator*() {}\n" 8547 "void\n" 8548 "A::operator->() {}\n" 8549 "void\n" 8550 "A::operator void *() {}\n" 8551 "void\n" 8552 "A::operator void &() {}\n" 8553 "void\n" 8554 "A::operator void &&() {}\n" 8555 "void\n" 8556 "A::operator char *() {}\n" 8557 "void\n" 8558 "A::operator[]() {}\n" 8559 "void\n" 8560 "A::operator!() {}\n" 8561 "void\n" 8562 "A::operator**() {}\n" 8563 "void\n" 8564 "A::operator<Foo> *() {}\n" 8565 "void\n" 8566 "A::operator<Foo> **() {}\n" 8567 "void\n" 8568 "A::operator<Foo> &() {}\n" 8569 "void\n" 8570 "A::operator void **() {}\n", 8571 Style); 8572 verifyFormat("constexpr auto\n" 8573 "operator()() const -> reference {}\n" 8574 "constexpr auto\n" 8575 "operator>>() const -> reference {}\n" 8576 "constexpr auto\n" 8577 "operator+() const -> reference {}\n" 8578 "constexpr auto\n" 8579 "operator*() const -> reference {}\n" 8580 "constexpr auto\n" 8581 "operator->() const -> reference {}\n" 8582 "constexpr auto\n" 8583 "operator++() const -> reference {}\n" 8584 "constexpr auto\n" 8585 "operator void *() const -> reference {}\n" 8586 "constexpr auto\n" 8587 "operator void **() const -> reference {}\n" 8588 "constexpr auto\n" 8589 "operator void *() const -> reference {}\n" 8590 "constexpr auto\n" 8591 "operator void &() const -> reference {}\n" 8592 "constexpr auto\n" 8593 "operator void &&() const -> reference {}\n" 8594 "constexpr auto\n" 8595 "operator char *() const -> reference {}\n" 8596 "constexpr auto\n" 8597 "operator!() const -> reference {}\n" 8598 "constexpr auto\n" 8599 "operator[]() const -> reference {}\n", 8600 Style); 8601 verifyFormat("void *operator new(std::size_t s);", // No break here. 8602 Style); 8603 verifyFormat("void *\n" 8604 "operator new(std::size_t s) {}", 8605 Style); 8606 verifyFormat("void *\n" 8607 "operator delete[](void *ptr) {}", 8608 Style); 8609 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 8610 verifyFormat("const char *\n" 8611 "f(void)\n" // Break here. 8612 "{\n" 8613 " return \"\";\n" 8614 "}\n" 8615 "const char *bar(void);\n", // No break here. 8616 Style); 8617 verifyFormat("template <class T>\n" 8618 "T *\n" // Problem here: no line break 8619 "f(T &c)\n" // Break here. 8620 "{\n" 8621 " return NULL;\n" 8622 "}\n" 8623 "template <class T> T *f(T &c);\n", // No break here. 8624 Style); 8625 verifyFormat("int\n" 8626 "foo(A<bool> a)\n" 8627 "{\n" 8628 " return a;\n" 8629 "}\n", 8630 Style); 8631 verifyFormat("int\n" 8632 "foo(A<8> a)\n" 8633 "{\n" 8634 " return a;\n" 8635 "}\n", 8636 Style); 8637 verifyFormat("int\n" 8638 "foo(A<B<bool>, 8> a)\n" 8639 "{\n" 8640 " return a;\n" 8641 "}\n", 8642 Style); 8643 verifyFormat("int\n" 8644 "foo(A<B<8>, bool> a)\n" 8645 "{\n" 8646 " return a;\n" 8647 "}\n", 8648 Style); 8649 verifyFormat("int\n" 8650 "foo(A<B<bool>, bool> a)\n" 8651 "{\n" 8652 " return a;\n" 8653 "}\n", 8654 Style); 8655 verifyFormat("int\n" 8656 "foo(A<B<8>, 8> a)\n" 8657 "{\n" 8658 " return a;\n" 8659 "}\n", 8660 Style); 8661 8662 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 8663 Style.BraceWrapping.AfterFunction = true; 8664 verifyFormat("int f(i);\n" // No break here. 8665 "int\n" // Break here. 8666 "f(i)\n" 8667 "{\n" 8668 " return i + 1;\n" 8669 "}\n" 8670 "int\n" // Break here. 8671 "f(i)\n" 8672 "{\n" 8673 " return i + 1;\n" 8674 "};", 8675 Style); 8676 verifyFormat("int f(a, b, c);\n" // No break here. 8677 "int\n" // Break here. 8678 "f(a, b, c)\n" // Break here. 8679 "short a, b;\n" 8680 "float c;\n" 8681 "{\n" 8682 " return a + b < c;\n" 8683 "}\n" 8684 "int\n" // Break here. 8685 "f(a, b, c)\n" // Break here. 8686 "short a, b;\n" 8687 "float c;\n" 8688 "{\n" 8689 " return a + b < c;\n" 8690 "};", 8691 Style); 8692 verifyFormat("byte *\n" // Break here. 8693 "f(a)\n" // Break here. 8694 "byte a[];\n" 8695 "{\n" 8696 " return a;\n" 8697 "}", 8698 Style); 8699 verifyFormat("bool f(int a, int) override;\n" 8700 "Bar g(int a, Bar) final;\n" 8701 "Bar h(a, Bar) final;", 8702 Style); 8703 verifyFormat("int\n" 8704 "f(a)", 8705 Style); 8706 verifyFormat("bool\n" 8707 "f(size_t = 0, bool b = false)\n" 8708 "{\n" 8709 " return !b;\n" 8710 "}", 8711 Style); 8712 8713 // The return breaking style doesn't affect: 8714 // * function and object definitions with attribute-like macros 8715 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 8716 " ABSL_GUARDED_BY(mutex) = {};", 8717 getGoogleStyleWithColumns(40)); 8718 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 8719 " ABSL_GUARDED_BY(mutex); // comment", 8720 getGoogleStyleWithColumns(40)); 8721 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 8722 " ABSL_GUARDED_BY(mutex1)\n" 8723 " ABSL_GUARDED_BY(mutex2);", 8724 getGoogleStyleWithColumns(40)); 8725 verifyFormat("Tttttt f(int a, int b)\n" 8726 " ABSL_GUARDED_BY(mutex1)\n" 8727 " ABSL_GUARDED_BY(mutex2);", 8728 getGoogleStyleWithColumns(40)); 8729 // * typedefs 8730 verifyFormat("typedef ATTR(X) char x;", getGoogleStyle()); 8731 8732 Style = getGNUStyle(); 8733 8734 // Test for comments at the end of function declarations. 8735 verifyFormat("void\n" 8736 "foo (int a, /*abc*/ int b) // def\n" 8737 "{\n" 8738 "}\n", 8739 Style); 8740 8741 verifyFormat("void\n" 8742 "foo (int a, /* abc */ int b) /* def */\n" 8743 "{\n" 8744 "}\n", 8745 Style); 8746 8747 // Definitions that should not break after return type 8748 verifyFormat("void foo (int a, int b); // def\n", Style); 8749 verifyFormat("void foo (int a, int b); /* def */\n", Style); 8750 verifyFormat("void foo (int a, int b);\n", Style); 8751 } 8752 8753 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) { 8754 FormatStyle NoBreak = getLLVMStyle(); 8755 NoBreak.AlwaysBreakBeforeMultilineStrings = false; 8756 FormatStyle Break = getLLVMStyle(); 8757 Break.AlwaysBreakBeforeMultilineStrings = true; 8758 verifyFormat("aaaa = \"bbbb\"\n" 8759 " \"cccc\";", 8760 NoBreak); 8761 verifyFormat("aaaa =\n" 8762 " \"bbbb\"\n" 8763 " \"cccc\";", 8764 Break); 8765 verifyFormat("aaaa(\"bbbb\"\n" 8766 " \"cccc\");", 8767 NoBreak); 8768 verifyFormat("aaaa(\n" 8769 " \"bbbb\"\n" 8770 " \"cccc\");", 8771 Break); 8772 verifyFormat("aaaa(qqq, \"bbbb\"\n" 8773 " \"cccc\");", 8774 NoBreak); 8775 verifyFormat("aaaa(qqq,\n" 8776 " \"bbbb\"\n" 8777 " \"cccc\");", 8778 Break); 8779 verifyFormat("aaaa(qqq,\n" 8780 " L\"bbbb\"\n" 8781 " L\"cccc\");", 8782 Break); 8783 verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n" 8784 " \"bbbb\"));", 8785 Break); 8786 verifyFormat("string s = someFunction(\n" 8787 " \"abc\"\n" 8788 " \"abc\");", 8789 Break); 8790 8791 // As we break before unary operators, breaking right after them is bad. 8792 verifyFormat("string foo = abc ? \"x\"\n" 8793 " \"blah blah blah blah blah blah\"\n" 8794 " : \"y\";", 8795 Break); 8796 8797 // Don't break if there is no column gain. 8798 verifyFormat("f(\"aaaa\"\n" 8799 " \"bbbb\");", 8800 Break); 8801 8802 // Treat literals with escaped newlines like multi-line string literals. 8803 EXPECT_EQ("x = \"a\\\n" 8804 "b\\\n" 8805 "c\";", 8806 format("x = \"a\\\n" 8807 "b\\\n" 8808 "c\";", 8809 NoBreak)); 8810 EXPECT_EQ("xxxx =\n" 8811 " \"a\\\n" 8812 "b\\\n" 8813 "c\";", 8814 format("xxxx = \"a\\\n" 8815 "b\\\n" 8816 "c\";", 8817 Break)); 8818 8819 EXPECT_EQ("NSString *const kString =\n" 8820 " @\"aaaa\"\n" 8821 " @\"bbbb\";", 8822 format("NSString *const kString = @\"aaaa\"\n" 8823 "@\"bbbb\";", 8824 Break)); 8825 8826 Break.ColumnLimit = 0; 8827 verifyFormat("const char *hello = \"hello llvm\";", Break); 8828 } 8829 8830 TEST_F(FormatTest, AlignsPipes) { 8831 verifyFormat( 8832 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8833 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8834 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8835 verifyFormat( 8836 "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n" 8837 " << aaaaaaaaaaaaaaaaaaaa;"); 8838 verifyFormat( 8839 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8840 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8841 verifyFormat( 8842 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 8843 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8844 verifyFormat( 8845 "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n" 8846 " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n" 8847 " << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";"); 8848 verifyFormat( 8849 "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8850 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8851 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8852 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8853 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8854 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8855 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 8856 verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n" 8857 " << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);"); 8858 verifyFormat( 8859 "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8860 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8861 verifyFormat( 8862 "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n" 8863 " aaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8864 8865 verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n" 8866 " << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();"); 8867 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8868 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8869 " aaaaaaaaaaaaaaaaaaaaa)\n" 8870 " << aaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8871 verifyFormat("LOG_IF(aaa == //\n" 8872 " bbb)\n" 8873 " << a << b;"); 8874 8875 // But sometimes, breaking before the first "<<" is desirable. 8876 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 8877 " << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);"); 8878 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n" 8879 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8880 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8881 verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n" 8882 " << BEF << IsTemplate << Description << E->getType();"); 8883 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 8884 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8885 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8886 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 8887 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8888 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8889 " << aaa;"); 8890 8891 verifyFormat( 8892 "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8893 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 8894 8895 // Incomplete string literal. 8896 EXPECT_EQ("llvm::errs() << \"\n" 8897 " << a;", 8898 format("llvm::errs() << \"\n<<a;")); 8899 8900 verifyFormat("void f() {\n" 8901 " CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n" 8902 " << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n" 8903 "}"); 8904 8905 // Handle 'endl'. 8906 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n" 8907 " << bbbbbbbbbbbbbbbbbbbbbb << endl;"); 8908 verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;"); 8909 8910 // Handle '\n'. 8911 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n" 8912 " << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";"); 8913 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n" 8914 " << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';"); 8915 verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n" 8916 " << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";"); 8917 verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";"); 8918 } 8919 8920 TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) { 8921 verifyFormat("return out << \"somepacket = {\\n\"\n" 8922 " << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n" 8923 " << \" bbbb = \" << pkt.bbbb << \"\\n\"\n" 8924 " << \" cccccc = \" << pkt.cccccc << \"\\n\"\n" 8925 " << \" ddd = [\" << pkt.ddd << \"]\\n\"\n" 8926 " << \"}\";"); 8927 8928 verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n" 8929 " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n" 8930 " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;"); 8931 verifyFormat( 8932 "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n" 8933 " << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n" 8934 " << \"ccccccccccccccccc = \" << ccccccccccccccccc\n" 8935 " << \"ddddddddddddddddd = \" << ddddddddddddddddd\n" 8936 " << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;"); 8937 verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n" 8938 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 8939 verifyFormat( 8940 "void f() {\n" 8941 " llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n" 8942 " << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 8943 "}"); 8944 8945 // Breaking before the first "<<" is generally not desirable. 8946 verifyFormat( 8947 "llvm::errs()\n" 8948 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8949 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8950 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8951 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 8952 getLLVMStyleWithColumns(70)); 8953 verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n" 8954 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8955 " << \"aaaaaaaaaaaaaaaaaaa: \"\n" 8956 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8957 " << \"aaaaaaaaaaaaaaaaaaa: \"\n" 8958 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 8959 getLLVMStyleWithColumns(70)); 8960 8961 verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n" 8962 " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n" 8963 " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;"); 8964 verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n" 8965 " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n" 8966 " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);"); 8967 verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n" 8968 " (aaaa + aaaa);", 8969 getLLVMStyleWithColumns(40)); 8970 verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n" 8971 " (aaaaaaa + aaaaa));", 8972 getLLVMStyleWithColumns(40)); 8973 verifyFormat( 8974 "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n" 8975 " SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n" 8976 " bbbbbbbbbbbbbbbbbbbbbbb);"); 8977 } 8978 8979 TEST_F(FormatTest, UnderstandsEquals) { 8980 verifyFormat( 8981 "aaaaaaaaaaaaaaaaa =\n" 8982 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8983 verifyFormat( 8984 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 8985 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 8986 verifyFormat( 8987 "if (a) {\n" 8988 " f();\n" 8989 "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 8990 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 8991 "}"); 8992 8993 verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 8994 " 100000000 + 10000000) {\n}"); 8995 } 8996 8997 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) { 8998 verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n" 8999 " .looooooooooooooooooooooooooooooooooooooongFunction();"); 9000 9001 verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n" 9002 " ->looooooooooooooooooooooooooooooooooooooongFunction();"); 9003 9004 verifyFormat( 9005 "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n" 9006 " Parameter2);"); 9007 9008 verifyFormat( 9009 "ShortObject->shortFunction(\n" 9010 " LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n" 9011 " LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);"); 9012 9013 verifyFormat("loooooooooooooongFunction(\n" 9014 " LoooooooooooooongObject->looooooooooooooooongFunction());"); 9015 9016 verifyFormat( 9017 "function(LoooooooooooooooooooooooooooooooooooongObject\n" 9018 " ->loooooooooooooooooooooooooooooooooooooooongFunction());"); 9019 9020 verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n" 9021 " .WillRepeatedly(Return(SomeValue));"); 9022 verifyFormat("void f() {\n" 9023 " EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n" 9024 " .Times(2)\n" 9025 " .WillRepeatedly(Return(SomeValue));\n" 9026 "}"); 9027 verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n" 9028 " ccccccccccccccccccccccc);"); 9029 verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9030 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9031 " .aaaaa(aaaaa),\n" 9032 " aaaaaaaaaaaaaaaaaaaaa);"); 9033 verifyFormat("void f() {\n" 9034 " aaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9035 " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n" 9036 "}"); 9037 verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9038 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9039 " .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9040 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9041 " aaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 9042 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9043 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9044 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9045 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n" 9046 "}"); 9047 9048 // Here, it is not necessary to wrap at "." or "->". 9049 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n" 9050 " aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 9051 verifyFormat( 9052 "aaaaaaaaaaa->aaaaaaaaa(\n" 9053 " aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9054 " aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n"); 9055 9056 verifyFormat( 9057 "aaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9058 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());"); 9059 verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n" 9060 " aaaaaaaaa()->aaaaaa()->aaaaa());"); 9061 verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n" 9062 " aaaaaaaaa()->aaaaaa()->aaaaa());"); 9063 9064 verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9065 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9066 " .a();"); 9067 9068 FormatStyle NoBinPacking = getLLVMStyle(); 9069 NoBinPacking.BinPackParameters = false; 9070 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n" 9071 " .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n" 9072 " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n" 9073 " aaaaaaaaaaaaaaaaaaa,\n" 9074 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 9075 NoBinPacking); 9076 9077 // If there is a subsequent call, change to hanging indentation. 9078 verifyFormat( 9079 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9080 " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n" 9081 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9082 verifyFormat( 9083 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9084 " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));"); 9085 verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9086 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9087 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9088 verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9089 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9090 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());"); 9091 } 9092 9093 TEST_F(FormatTest, WrapsTemplateDeclarations) { 9094 verifyFormat("template <typename T>\n" 9095 "virtual void loooooooooooongFunction(int Param1, int Param2);"); 9096 verifyFormat("template <typename T>\n" 9097 "// T should be one of {A, B}.\n" 9098 "virtual void loooooooooooongFunction(int Param1, int Param2);"); 9099 verifyFormat( 9100 "template <typename T>\n" 9101 "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;"); 9102 verifyFormat("template <typename T>\n" 9103 "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n" 9104 " int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);"); 9105 verifyFormat( 9106 "template <typename T>\n" 9107 "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n" 9108 " int Paaaaaaaaaaaaaaaaaaaaram2);"); 9109 verifyFormat( 9110 "template <typename T>\n" 9111 "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n" 9112 " aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n" 9113 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9114 verifyFormat("template <typename T>\n" 9115 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9116 " int aaaaaaaaaaaaaaaaaaaaaa);"); 9117 verifyFormat( 9118 "template <typename T1, typename T2 = char, typename T3 = char,\n" 9119 " typename T4 = char>\n" 9120 "void f();"); 9121 verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n" 9122 " template <typename> class cccccccccccccccccccccc,\n" 9123 " typename ddddddddddddd>\n" 9124 "class C {};"); 9125 verifyFormat( 9126 "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n" 9127 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9128 9129 verifyFormat("void f() {\n" 9130 " a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n" 9131 " a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n" 9132 "}"); 9133 9134 verifyFormat("template <typename T> class C {};"); 9135 verifyFormat("template <typename T> void f();"); 9136 verifyFormat("template <typename T> void f() {}"); 9137 verifyFormat( 9138 "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n" 9139 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9140 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n" 9141 " new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n" 9142 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9143 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n" 9144 " bbbbbbbbbbbbbbbbbbbbbbbb);", 9145 getLLVMStyleWithColumns(72)); 9146 EXPECT_EQ("static_cast<A< //\n" 9147 " B> *>(\n" 9148 "\n" 9149 ");", 9150 format("static_cast<A<//\n" 9151 " B>*>(\n" 9152 "\n" 9153 " );")); 9154 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9155 " const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);"); 9156 9157 FormatStyle AlwaysBreak = getLLVMStyle(); 9158 AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 9159 verifyFormat("template <typename T>\nclass C {};", AlwaysBreak); 9160 verifyFormat("template <typename T>\nvoid f();", AlwaysBreak); 9161 verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak); 9162 verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9163 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n" 9164 " ccccccccccccccccccccccccccccccccccccccccccccccc);"); 9165 verifyFormat("template <template <typename> class Fooooooo,\n" 9166 " template <typename> class Baaaaaaar>\n" 9167 "struct C {};", 9168 AlwaysBreak); 9169 verifyFormat("template <typename T> // T can be A, B or C.\n" 9170 "struct C {};", 9171 AlwaysBreak); 9172 verifyFormat("template <enum E> class A {\n" 9173 "public:\n" 9174 " E *f();\n" 9175 "};"); 9176 9177 FormatStyle NeverBreak = getLLVMStyle(); 9178 NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No; 9179 verifyFormat("template <typename T> class C {};", NeverBreak); 9180 verifyFormat("template <typename T> void f();", NeverBreak); 9181 verifyFormat("template <typename T> void f() {}", NeverBreak); 9182 verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa " 9183 "bbbbbbbbbbbbbbbbbbbb) {}", 9184 NeverBreak); 9185 verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9186 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n" 9187 " ccccccccccccccccccccccccccccccccccccccccccccccc);", 9188 NeverBreak); 9189 verifyFormat("template <template <typename> class Fooooooo,\n" 9190 " template <typename> class Baaaaaaar>\n" 9191 "struct C {};", 9192 NeverBreak); 9193 verifyFormat("template <typename T> // T can be A, B or C.\n" 9194 "struct C {};", 9195 NeverBreak); 9196 verifyFormat("template <enum E> class A {\n" 9197 "public:\n" 9198 " E *f();\n" 9199 "};", 9200 NeverBreak); 9201 NeverBreak.PenaltyBreakTemplateDeclaration = 100; 9202 verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa " 9203 "bbbbbbbbbbbbbbbbbbbb) {}", 9204 NeverBreak); 9205 } 9206 9207 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) { 9208 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp); 9209 Style.ColumnLimit = 60; 9210 EXPECT_EQ("// Baseline - no comments.\n" 9211 "template <\n" 9212 " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n" 9213 "void f() {}", 9214 format("// Baseline - no comments.\n" 9215 "template <\n" 9216 " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n" 9217 "void f() {}", 9218 Style)); 9219 9220 EXPECT_EQ("template <\n" 9221 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9222 "void f() {}", 9223 format("template <\n" 9224 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9225 "void f() {}", 9226 Style)); 9227 9228 EXPECT_EQ( 9229 "template <\n" 9230 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n" 9231 "void f() {}", 9232 format("template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n" 9233 "void f() {}", 9234 Style)); 9235 9236 EXPECT_EQ( 9237 "template <\n" 9238 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9239 " // multiline\n" 9240 "void f() {}", 9241 format("template <\n" 9242 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9243 " // multiline\n" 9244 "void f() {}", 9245 Style)); 9246 9247 EXPECT_EQ( 9248 "template <typename aaaaaaaaaa<\n" 9249 " bbbbbbbbbbbb>::value> // trailing loooong\n" 9250 "void f() {}", 9251 format( 9252 "template <\n" 9253 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n" 9254 "void f() {}", 9255 Style)); 9256 } 9257 9258 TEST_F(FormatTest, WrapsTemplateParameters) { 9259 FormatStyle Style = getLLVMStyle(); 9260 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 9261 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 9262 verifyFormat( 9263 "template <typename... a> struct q {};\n" 9264 "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n" 9265 " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n" 9266 " y;", 9267 Style); 9268 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 9269 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 9270 verifyFormat( 9271 "template <typename... a> struct r {};\n" 9272 "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n" 9273 " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n" 9274 " y;", 9275 Style); 9276 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 9277 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 9278 verifyFormat("template <typename... a> struct s {};\n" 9279 "extern s<\n" 9280 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9281 "aaaaaaaaaaaaaaaaaaaaaa,\n" 9282 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9283 "aaaaaaaaaaaaaaaaaaaaaa>\n" 9284 " y;", 9285 Style); 9286 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 9287 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 9288 verifyFormat("template <typename... a> struct t {};\n" 9289 "extern t<\n" 9290 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9291 "aaaaaaaaaaaaaaaaaaaaaa,\n" 9292 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9293 "aaaaaaaaaaaaaaaaaaaaaa>\n" 9294 " y;", 9295 Style); 9296 } 9297 9298 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) { 9299 verifyFormat( 9300 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9301 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9302 verifyFormat( 9303 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9304 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9305 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());"); 9306 9307 // FIXME: Should we have the extra indent after the second break? 9308 verifyFormat( 9309 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9310 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9311 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9312 9313 verifyFormat( 9314 "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n" 9315 " cccccccccccccccccccccccccccccccccccccccccccccc());"); 9316 9317 // Breaking at nested name specifiers is generally not desirable. 9318 verifyFormat( 9319 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9320 " aaaaaaaaaaaaaaaaaaaaaaa);"); 9321 9322 verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n" 9323 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9324 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9325 " aaaaaaaaaaaaaaaaaaaaa);", 9326 getLLVMStyleWithColumns(74)); 9327 9328 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9329 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9330 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9331 } 9332 9333 TEST_F(FormatTest, UnderstandsTemplateParameters) { 9334 verifyFormat("A<int> a;"); 9335 verifyFormat("A<A<A<int>>> a;"); 9336 verifyFormat("A<A<A<int, 2>, 3>, 4> a;"); 9337 verifyFormat("bool x = a < 1 || 2 > a;"); 9338 verifyFormat("bool x = 5 < f<int>();"); 9339 verifyFormat("bool x = f<int>() > 5;"); 9340 verifyFormat("bool x = 5 < a<int>::x;"); 9341 verifyFormat("bool x = a < 4 ? a > 2 : false;"); 9342 verifyFormat("bool x = f() ? a < 2 : a > 2;"); 9343 9344 verifyGoogleFormat("A<A<int>> a;"); 9345 verifyGoogleFormat("A<A<A<int>>> a;"); 9346 verifyGoogleFormat("A<A<A<A<int>>>> a;"); 9347 verifyGoogleFormat("A<A<int> > a;"); 9348 verifyGoogleFormat("A<A<A<int> > > a;"); 9349 verifyGoogleFormat("A<A<A<A<int> > > > a;"); 9350 verifyGoogleFormat("A<::A<int>> a;"); 9351 verifyGoogleFormat("A<::A> a;"); 9352 verifyGoogleFormat("A< ::A> a;"); 9353 verifyGoogleFormat("A< ::A<int> > a;"); 9354 EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle())); 9355 EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle())); 9356 EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle())); 9357 EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle())); 9358 EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };", 9359 format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle())); 9360 9361 verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp)); 9362 9363 // template closer followed by a token that starts with > or = 9364 verifyFormat("bool b = a<1> > 1;"); 9365 verifyFormat("bool b = a<1> >= 1;"); 9366 verifyFormat("int i = a<1> >> 1;"); 9367 FormatStyle Style = getLLVMStyle(); 9368 Style.SpaceBeforeAssignmentOperators = false; 9369 verifyFormat("bool b= a<1> == 1;", Style); 9370 verifyFormat("a<int> = 1;", Style); 9371 verifyFormat("a<int> >>= 1;", Style); 9372 9373 verifyFormat("test < a | b >> c;"); 9374 verifyFormat("test<test<a | b>> c;"); 9375 verifyFormat("test >> a >> b;"); 9376 verifyFormat("test << a >> b;"); 9377 9378 verifyFormat("f<int>();"); 9379 verifyFormat("template <typename T> void f() {}"); 9380 verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;"); 9381 verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : " 9382 "sizeof(char)>::type>;"); 9383 verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};"); 9384 verifyFormat("f(a.operator()<A>());"); 9385 verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9386 " .template operator()<A>());", 9387 getLLVMStyleWithColumns(35)); 9388 9389 // Not template parameters. 9390 verifyFormat("return a < b && c > d;"); 9391 verifyFormat("void f() {\n" 9392 " while (a < b && c > d) {\n" 9393 " }\n" 9394 "}"); 9395 verifyFormat("template <typename... Types>\n" 9396 "typename enable_if<0 < sizeof...(Types)>::type Foo() {}"); 9397 9398 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9399 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);", 9400 getLLVMStyleWithColumns(60)); 9401 verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");"); 9402 verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}"); 9403 verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <"); 9404 verifyFormat("some_templated_type<decltype([](int i) { return i; })>"); 9405 } 9406 9407 TEST_F(FormatTest, UnderstandsShiftOperators) { 9408 verifyFormat("if (i < x >> 1)"); 9409 verifyFormat("while (i < x >> 1)"); 9410 verifyFormat("for (unsigned i = 0; i < i; ++i, v = v >> 1)"); 9411 verifyFormat("for (unsigned i = 0; i < x >> 1; ++i, v = v >> 1)"); 9412 verifyFormat( 9413 "for (std::vector<int>::iterator i = 0; i < x >> 1; ++i, v = v >> 1)"); 9414 verifyFormat("Foo.call<Bar<Function>>()"); 9415 verifyFormat("if (Foo.call<Bar<Function>>() == 0)"); 9416 verifyFormat("for (std::vector<std::pair<int>>::iterator i = 0; i < x >> 1; " 9417 "++i, v = v >> 1)"); 9418 verifyFormat("if (w<u<v<x>>, 1>::t)"); 9419 } 9420 9421 TEST_F(FormatTest, BitshiftOperatorWidth) { 9422 EXPECT_EQ("int a = 1 << 2; /* foo\n" 9423 " bar */", 9424 format("int a=1<<2; /* foo\n" 9425 " bar */")); 9426 9427 EXPECT_EQ("int b = 256 >> 1; /* foo\n" 9428 " bar */", 9429 format("int b =256>>1 ; /* foo\n" 9430 " bar */")); 9431 } 9432 9433 TEST_F(FormatTest, UnderstandsBinaryOperators) { 9434 verifyFormat("COMPARE(a, ==, b);"); 9435 verifyFormat("auto s = sizeof...(Ts) - 1;"); 9436 } 9437 9438 TEST_F(FormatTest, UnderstandsPointersToMembers) { 9439 verifyFormat("int A::*x;"); 9440 verifyFormat("int (S::*func)(void *);"); 9441 verifyFormat("void f() { int (S::*func)(void *); }"); 9442 verifyFormat("typedef bool *(Class::*Member)() const;"); 9443 verifyFormat("void f() {\n" 9444 " (a->*f)();\n" 9445 " a->*x;\n" 9446 " (a.*f)();\n" 9447 " ((*a).*f)();\n" 9448 " a.*x;\n" 9449 "}"); 9450 verifyFormat("void f() {\n" 9451 " (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n" 9452 " aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n" 9453 "}"); 9454 verifyFormat( 9455 "(aaaaaaaaaa->*bbbbbbb)(\n" 9456 " aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 9457 FormatStyle Style = getLLVMStyle(); 9458 Style.PointerAlignment = FormatStyle::PAS_Left; 9459 verifyFormat("typedef bool* (Class::*Member)() const;", Style); 9460 } 9461 9462 TEST_F(FormatTest, UnderstandsUnaryOperators) { 9463 verifyFormat("int a = -2;"); 9464 verifyFormat("f(-1, -2, -3);"); 9465 verifyFormat("a[-1] = 5;"); 9466 verifyFormat("int a = 5 + -2;"); 9467 verifyFormat("if (i == -1) {\n}"); 9468 verifyFormat("if (i != -1) {\n}"); 9469 verifyFormat("if (i > -1) {\n}"); 9470 verifyFormat("if (i < -1) {\n}"); 9471 verifyFormat("++(a->f());"); 9472 verifyFormat("--(a->f());"); 9473 verifyFormat("(a->f())++;"); 9474 verifyFormat("a[42]++;"); 9475 verifyFormat("if (!(a->f())) {\n}"); 9476 verifyFormat("if (!+i) {\n}"); 9477 verifyFormat("~&a;"); 9478 9479 verifyFormat("a-- > b;"); 9480 verifyFormat("b ? -a : c;"); 9481 verifyFormat("n * sizeof char16;"); 9482 verifyFormat("n * alignof char16;", getGoogleStyle()); 9483 verifyFormat("sizeof(char);"); 9484 verifyFormat("alignof(char);", getGoogleStyle()); 9485 9486 verifyFormat("return -1;"); 9487 verifyFormat("throw -1;"); 9488 verifyFormat("switch (a) {\n" 9489 "case -1:\n" 9490 " break;\n" 9491 "}"); 9492 verifyFormat("#define X -1"); 9493 verifyFormat("#define X -kConstant"); 9494 9495 verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};"); 9496 verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};"); 9497 9498 verifyFormat("int a = /* confusing comment */ -1;"); 9499 // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case. 9500 verifyFormat("int a = i /* confusing comment */++;"); 9501 9502 verifyFormat("co_yield -1;"); 9503 verifyFormat("co_return -1;"); 9504 9505 // Check that * is not treated as a binary operator when we set 9506 // PointerAlignment as PAS_Left after a keyword and not a declaration. 9507 FormatStyle PASLeftStyle = getLLVMStyle(); 9508 PASLeftStyle.PointerAlignment = FormatStyle::PAS_Left; 9509 verifyFormat("co_return *a;", PASLeftStyle); 9510 verifyFormat("co_await *a;", PASLeftStyle); 9511 verifyFormat("co_yield *a", PASLeftStyle); 9512 verifyFormat("return *a;", PASLeftStyle); 9513 } 9514 9515 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) { 9516 verifyFormat("if (!aaaaaaaaaa( // break\n" 9517 " aaaaa)) {\n" 9518 "}"); 9519 verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n" 9520 " aaaaa));"); 9521 verifyFormat("*aaa = aaaaaaa( // break\n" 9522 " bbbbbb);"); 9523 } 9524 9525 TEST_F(FormatTest, UnderstandsOverloadedOperators) { 9526 verifyFormat("bool operator<();"); 9527 verifyFormat("bool operator>();"); 9528 verifyFormat("bool operator=();"); 9529 verifyFormat("bool operator==();"); 9530 verifyFormat("bool operator!=();"); 9531 verifyFormat("int operator+();"); 9532 verifyFormat("int operator++();"); 9533 verifyFormat("int operator++(int) volatile noexcept;"); 9534 verifyFormat("bool operator,();"); 9535 verifyFormat("bool operator();"); 9536 verifyFormat("bool operator()();"); 9537 verifyFormat("bool operator[]();"); 9538 verifyFormat("operator bool();"); 9539 verifyFormat("operator int();"); 9540 verifyFormat("operator void *();"); 9541 verifyFormat("operator SomeType<int>();"); 9542 verifyFormat("operator SomeType<int, int>();"); 9543 verifyFormat("operator SomeType<SomeType<int>>();"); 9544 verifyFormat("operator< <>();"); 9545 verifyFormat("operator<< <>();"); 9546 verifyFormat("< <>"); 9547 9548 verifyFormat("void *operator new(std::size_t size);"); 9549 verifyFormat("void *operator new[](std::size_t size);"); 9550 verifyFormat("void operator delete(void *ptr);"); 9551 verifyFormat("void operator delete[](void *ptr);"); 9552 verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n" 9553 "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);"); 9554 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n" 9555 " aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;"); 9556 9557 verifyFormat( 9558 "ostream &operator<<(ostream &OutputStream,\n" 9559 " SomeReallyLongType WithSomeReallyLongValue);"); 9560 verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n" 9561 " const aaaaaaaaaaaaaaaaaaaaa &right) {\n" 9562 " return left.group < right.group;\n" 9563 "}"); 9564 verifyFormat("SomeType &operator=(const SomeType &S);"); 9565 verifyFormat("f.template operator()<int>();"); 9566 9567 verifyGoogleFormat("operator void*();"); 9568 verifyGoogleFormat("operator SomeType<SomeType<int>>();"); 9569 verifyGoogleFormat("operator ::A();"); 9570 9571 verifyFormat("using A::operator+;"); 9572 verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n" 9573 "int i;"); 9574 9575 // Calling an operator as a member function. 9576 verifyFormat("void f() { a.operator*(); }"); 9577 verifyFormat("void f() { a.operator*(b & b); }"); 9578 verifyFormat("void f() { a->operator&(a * b); }"); 9579 verifyFormat("void f() { NS::a.operator+(*b * *b); }"); 9580 // TODO: Calling an operator as a non-member function is hard to distinguish. 9581 // https://llvm.org/PR50629 9582 // verifyFormat("void f() { operator*(a & a); }"); 9583 // verifyFormat("void f() { operator&(a, b * b); }"); 9584 9585 verifyFormat("::operator delete(foo);"); 9586 verifyFormat("::operator new(n * sizeof(foo));"); 9587 verifyFormat("foo() { ::operator delete(foo); }"); 9588 verifyFormat("foo() { ::operator new(n * sizeof(foo)); }"); 9589 } 9590 9591 TEST_F(FormatTest, UnderstandsFunctionRefQualification) { 9592 verifyFormat("Deleted &operator=(const Deleted &) & = default;"); 9593 verifyFormat("Deleted &operator=(const Deleted &) && = delete;"); 9594 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;"); 9595 verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;"); 9596 verifyFormat("Deleted &operator=(const Deleted &) &;"); 9597 verifyFormat("Deleted &operator=(const Deleted &) &&;"); 9598 verifyFormat("SomeType MemberFunction(const Deleted &) &;"); 9599 verifyFormat("SomeType MemberFunction(const Deleted &) &&;"); 9600 verifyFormat("SomeType MemberFunction(const Deleted &) && {}"); 9601 verifyFormat("SomeType MemberFunction(const Deleted &) && final {}"); 9602 verifyFormat("SomeType MemberFunction(const Deleted &) && override {}"); 9603 verifyFormat("void Fn(T const &) const &;"); 9604 verifyFormat("void Fn(T const volatile &&) const volatile &&;"); 9605 verifyFormat("template <typename T>\n" 9606 "void F(T) && = delete;", 9607 getGoogleStyle()); 9608 9609 FormatStyle AlignLeft = getLLVMStyle(); 9610 AlignLeft.PointerAlignment = FormatStyle::PAS_Left; 9611 verifyFormat("void A::b() && {}", AlignLeft); 9612 verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft); 9613 verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;", 9614 AlignLeft); 9615 verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft); 9616 verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft); 9617 verifyFormat("auto Function(T t) & -> void {}", AlignLeft); 9618 verifyFormat("auto Function(T... t) & -> void {}", AlignLeft); 9619 verifyFormat("auto Function(T) & -> void {}", AlignLeft); 9620 verifyFormat("auto Function(T) & -> void;", AlignLeft); 9621 verifyFormat("void Fn(T const&) const&;", AlignLeft); 9622 verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft); 9623 9624 FormatStyle Spaces = getLLVMStyle(); 9625 Spaces.SpacesInCStyleCastParentheses = true; 9626 verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces); 9627 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces); 9628 verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces); 9629 verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces); 9630 9631 Spaces.SpacesInCStyleCastParentheses = false; 9632 Spaces.SpacesInParentheses = true; 9633 verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces); 9634 verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;", 9635 Spaces); 9636 verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces); 9637 verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces); 9638 9639 FormatStyle BreakTemplate = getLLVMStyle(); 9640 BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 9641 9642 verifyFormat("struct f {\n" 9643 " template <class T>\n" 9644 " int &foo(const std::string &str) &noexcept {}\n" 9645 "};", 9646 BreakTemplate); 9647 9648 verifyFormat("struct f {\n" 9649 " template <class T>\n" 9650 " int &foo(const std::string &str) &&noexcept {}\n" 9651 "};", 9652 BreakTemplate); 9653 9654 verifyFormat("struct f {\n" 9655 " template <class T>\n" 9656 " int &foo(const std::string &str) const &noexcept {}\n" 9657 "};", 9658 BreakTemplate); 9659 9660 verifyFormat("struct f {\n" 9661 " template <class T>\n" 9662 " int &foo(const std::string &str) const &noexcept {}\n" 9663 "};", 9664 BreakTemplate); 9665 9666 verifyFormat("struct f {\n" 9667 " template <class T>\n" 9668 " auto foo(const std::string &str) &&noexcept -> int & {}\n" 9669 "};", 9670 BreakTemplate); 9671 9672 FormatStyle AlignLeftBreakTemplate = getLLVMStyle(); 9673 AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations = 9674 FormatStyle::BTDS_Yes; 9675 AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left; 9676 9677 verifyFormat("struct f {\n" 9678 " template <class T>\n" 9679 " int& foo(const std::string& str) & noexcept {}\n" 9680 "};", 9681 AlignLeftBreakTemplate); 9682 9683 verifyFormat("struct f {\n" 9684 " template <class T>\n" 9685 " int& foo(const std::string& str) && noexcept {}\n" 9686 "};", 9687 AlignLeftBreakTemplate); 9688 9689 verifyFormat("struct f {\n" 9690 " template <class T>\n" 9691 " int& foo(const std::string& str) const& noexcept {}\n" 9692 "};", 9693 AlignLeftBreakTemplate); 9694 9695 verifyFormat("struct f {\n" 9696 " template <class T>\n" 9697 " int& foo(const std::string& str) const&& noexcept {}\n" 9698 "};", 9699 AlignLeftBreakTemplate); 9700 9701 verifyFormat("struct f {\n" 9702 " template <class T>\n" 9703 " auto foo(const std::string& str) && noexcept -> int& {}\n" 9704 "};", 9705 AlignLeftBreakTemplate); 9706 9707 // The `&` in `Type&` should not be confused with a trailing `&` of 9708 // DEPRECATED(reason) member function. 9709 verifyFormat("struct f {\n" 9710 " template <class T>\n" 9711 " DEPRECATED(reason)\n" 9712 " Type &foo(arguments) {}\n" 9713 "};", 9714 BreakTemplate); 9715 9716 verifyFormat("struct f {\n" 9717 " template <class T>\n" 9718 " DEPRECATED(reason)\n" 9719 " Type& foo(arguments) {}\n" 9720 "};", 9721 AlignLeftBreakTemplate); 9722 9723 verifyFormat("void (*foopt)(int) = &func;"); 9724 9725 FormatStyle DerivePointerAlignment = getLLVMStyle(); 9726 DerivePointerAlignment.DerivePointerAlignment = true; 9727 // There's always a space between the function and its trailing qualifiers. 9728 // This isn't evidence for PAS_Right (or for PAS_Left). 9729 std::string Prefix = "void a() &;\n" 9730 "void b() &;\n"; 9731 verifyFormat(Prefix + "int* x;", DerivePointerAlignment); 9732 verifyFormat(Prefix + "int *x;", DerivePointerAlignment); 9733 // Same if the function is an overloaded operator, and with &&. 9734 Prefix = "void operator()() &&;\n" 9735 "void operator()() &&;\n"; 9736 verifyFormat(Prefix + "int* x;", DerivePointerAlignment); 9737 verifyFormat(Prefix + "int *x;", DerivePointerAlignment); 9738 // However a space between cv-qualifiers and ref-qualifiers *is* evidence. 9739 Prefix = "void a() const &;\n" 9740 "void b() const &;\n"; 9741 EXPECT_EQ(Prefix + "int *x;", 9742 format(Prefix + "int* x;", DerivePointerAlignment)); 9743 } 9744 9745 TEST_F(FormatTest, UnderstandsNewAndDelete) { 9746 verifyFormat("void f() {\n" 9747 " A *a = new A;\n" 9748 " A *a = new (placement) A;\n" 9749 " delete a;\n" 9750 " delete (A *)a;\n" 9751 "}"); 9752 verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n" 9753 " typename aaaaaaaaaaaaaaaaaaaaaaaa();"); 9754 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9755 " new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n" 9756 " typename aaaaaaaaaaaaaaaaaaaaaaaa();"); 9757 verifyFormat("delete[] h->p;"); 9758 verifyFormat("delete[] (void *)p;"); 9759 9760 verifyFormat("void operator delete(void *foo) ATTRIB;"); 9761 verifyFormat("void operator new(void *foo) ATTRIB;"); 9762 verifyFormat("void operator delete[](void *foo) ATTRIB;"); 9763 verifyFormat("void operator delete(void *ptr) noexcept;"); 9764 } 9765 9766 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) { 9767 verifyFormat("int *f(int *a) {}"); 9768 verifyFormat("int main(int argc, char **argv) {}"); 9769 verifyFormat("Test::Test(int b) : a(b * b) {}"); 9770 verifyIndependentOfContext("f(a, *a);"); 9771 verifyFormat("void g() { f(*a); }"); 9772 verifyIndependentOfContext("int a = b * 10;"); 9773 verifyIndependentOfContext("int a = 10 * b;"); 9774 verifyIndependentOfContext("int a = b * c;"); 9775 verifyIndependentOfContext("int a += b * c;"); 9776 verifyIndependentOfContext("int a -= b * c;"); 9777 verifyIndependentOfContext("int a *= b * c;"); 9778 verifyIndependentOfContext("int a /= b * c;"); 9779 verifyIndependentOfContext("int a = *b;"); 9780 verifyIndependentOfContext("int a = *b * c;"); 9781 verifyIndependentOfContext("int a = b * *c;"); 9782 verifyIndependentOfContext("int a = b * (10);"); 9783 verifyIndependentOfContext("S << b * (10);"); 9784 verifyIndependentOfContext("return 10 * b;"); 9785 verifyIndependentOfContext("return *b * *c;"); 9786 verifyIndependentOfContext("return a & ~b;"); 9787 verifyIndependentOfContext("f(b ? *c : *d);"); 9788 verifyIndependentOfContext("int a = b ? *c : *d;"); 9789 verifyIndependentOfContext("*b = a;"); 9790 verifyIndependentOfContext("a * ~b;"); 9791 verifyIndependentOfContext("a * !b;"); 9792 verifyIndependentOfContext("a * +b;"); 9793 verifyIndependentOfContext("a * -b;"); 9794 verifyIndependentOfContext("a * ++b;"); 9795 verifyIndependentOfContext("a * --b;"); 9796 verifyIndependentOfContext("a[4] * b;"); 9797 verifyIndependentOfContext("a[a * a] = 1;"); 9798 verifyIndependentOfContext("f() * b;"); 9799 verifyIndependentOfContext("a * [self dostuff];"); 9800 verifyIndependentOfContext("int x = a * (a + b);"); 9801 verifyIndependentOfContext("(a *)(a + b);"); 9802 verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;"); 9803 verifyIndependentOfContext("int *pa = (int *)&a;"); 9804 verifyIndependentOfContext("return sizeof(int **);"); 9805 verifyIndependentOfContext("return sizeof(int ******);"); 9806 verifyIndependentOfContext("return (int **&)a;"); 9807 verifyIndependentOfContext("f((*PointerToArray)[10]);"); 9808 verifyFormat("void f(Type (*parameter)[10]) {}"); 9809 verifyFormat("void f(Type (¶meter)[10]) {}"); 9810 verifyGoogleFormat("return sizeof(int**);"); 9811 verifyIndependentOfContext("Type **A = static_cast<Type **>(P);"); 9812 verifyGoogleFormat("Type** A = static_cast<Type**>(P);"); 9813 verifyFormat("auto a = [](int **&, int ***) {};"); 9814 verifyFormat("auto PointerBinding = [](const char *S) {};"); 9815 verifyFormat("typedef typeof(int(int, int)) *MyFunc;"); 9816 verifyFormat("[](const decltype(*a) &value) {}"); 9817 verifyFormat("[](const typeof(*a) &value) {}"); 9818 verifyFormat("[](const _Atomic(a *) &value) {}"); 9819 verifyFormat("[](const __underlying_type(a) &value) {}"); 9820 verifyFormat("decltype(a * b) F();"); 9821 verifyFormat("typeof(a * b) F();"); 9822 verifyFormat("#define MACRO() [](A *a) { return 1; }"); 9823 verifyFormat("Constructor() : member([](A *a, B *b) {}) {}"); 9824 verifyIndependentOfContext("typedef void (*f)(int *a);"); 9825 verifyIndependentOfContext("int i{a * b};"); 9826 verifyIndependentOfContext("aaa && aaa->f();"); 9827 verifyIndependentOfContext("int x = ~*p;"); 9828 verifyFormat("Constructor() : a(a), area(width * height) {}"); 9829 verifyFormat("Constructor() : a(a), area(a, width * height) {}"); 9830 verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}"); 9831 verifyFormat("void f() { f(a, c * d); }"); 9832 verifyFormat("void f() { f(new a(), c * d); }"); 9833 verifyFormat("void f(const MyOverride &override);"); 9834 verifyFormat("void f(const MyFinal &final);"); 9835 verifyIndependentOfContext("bool a = f() && override.f();"); 9836 verifyIndependentOfContext("bool a = f() && final.f();"); 9837 9838 verifyIndependentOfContext("InvalidRegions[*R] = 0;"); 9839 9840 verifyIndependentOfContext("A<int *> a;"); 9841 verifyIndependentOfContext("A<int **> a;"); 9842 verifyIndependentOfContext("A<int *, int *> a;"); 9843 verifyIndependentOfContext("A<int *[]> a;"); 9844 verifyIndependentOfContext( 9845 "const char *const p = reinterpret_cast<const char *const>(q);"); 9846 verifyIndependentOfContext("A<int **, int **> a;"); 9847 verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);"); 9848 verifyFormat("for (char **a = b; *a; ++a) {\n}"); 9849 verifyFormat("for (; a && b;) {\n}"); 9850 verifyFormat("bool foo = true && [] { return false; }();"); 9851 9852 verifyFormat( 9853 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9854 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9855 9856 verifyGoogleFormat("int const* a = &b;"); 9857 verifyGoogleFormat("**outparam = 1;"); 9858 verifyGoogleFormat("*outparam = a * b;"); 9859 verifyGoogleFormat("int main(int argc, char** argv) {}"); 9860 verifyGoogleFormat("A<int*> a;"); 9861 verifyGoogleFormat("A<int**> a;"); 9862 verifyGoogleFormat("A<int*, int*> a;"); 9863 verifyGoogleFormat("A<int**, int**> a;"); 9864 verifyGoogleFormat("f(b ? *c : *d);"); 9865 verifyGoogleFormat("int a = b ? *c : *d;"); 9866 verifyGoogleFormat("Type* t = **x;"); 9867 verifyGoogleFormat("Type* t = *++*x;"); 9868 verifyGoogleFormat("*++*x;"); 9869 verifyGoogleFormat("Type* t = const_cast<T*>(&*x);"); 9870 verifyGoogleFormat("Type* t = x++ * y;"); 9871 verifyGoogleFormat( 9872 "const char* const p = reinterpret_cast<const char* const>(q);"); 9873 verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);"); 9874 verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);"); 9875 verifyGoogleFormat("template <typename T>\n" 9876 "void f(int i = 0, SomeType** temps = NULL);"); 9877 9878 FormatStyle Left = getLLVMStyle(); 9879 Left.PointerAlignment = FormatStyle::PAS_Left; 9880 verifyFormat("x = *a(x) = *a(y);", Left); 9881 verifyFormat("for (;; *a = b) {\n}", Left); 9882 verifyFormat("return *this += 1;", Left); 9883 verifyFormat("throw *x;", Left); 9884 verifyFormat("delete *x;", Left); 9885 verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left); 9886 verifyFormat("[](const decltype(*a)* ptr) {}", Left); 9887 verifyFormat("[](const typeof(*a)* ptr) {}", Left); 9888 verifyFormat("[](const _Atomic(a*)* ptr) {}", Left); 9889 verifyFormat("[](const __underlying_type(a)* ptr) {}", Left); 9890 verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left); 9891 verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left); 9892 verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left); 9893 verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left); 9894 9895 verifyIndependentOfContext("a = *(x + y);"); 9896 verifyIndependentOfContext("a = &(x + y);"); 9897 verifyIndependentOfContext("*(x + y).call();"); 9898 verifyIndependentOfContext("&(x + y)->call();"); 9899 verifyFormat("void f() { &(*I).first; }"); 9900 9901 verifyIndependentOfContext("f(b * /* confusing comment */ ++c);"); 9902 verifyFormat("f(* /* confusing comment */ foo);"); 9903 verifyFormat("void (* /*deleter*/)(const Slice &key, void *value)"); 9904 verifyFormat("void foo(int * // this is the first paramters\n" 9905 " ,\n" 9906 " int second);"); 9907 verifyFormat("double term = a * // first\n" 9908 " b;"); 9909 verifyFormat( 9910 "int *MyValues = {\n" 9911 " *A, // Operator detection might be confused by the '{'\n" 9912 " *BB // Operator detection might be confused by previous comment\n" 9913 "};"); 9914 9915 verifyIndependentOfContext("if (int *a = &b)"); 9916 verifyIndependentOfContext("if (int &a = *b)"); 9917 verifyIndependentOfContext("if (a & b[i])"); 9918 verifyIndependentOfContext("if constexpr (a & b[i])"); 9919 verifyIndependentOfContext("if CONSTEXPR (a & b[i])"); 9920 verifyIndependentOfContext("if (a * (b * c))"); 9921 verifyIndependentOfContext("if constexpr (a * (b * c))"); 9922 verifyIndependentOfContext("if CONSTEXPR (a * (b * c))"); 9923 verifyIndependentOfContext("if (a::b::c::d & b[i])"); 9924 verifyIndependentOfContext("if (*b[i])"); 9925 verifyIndependentOfContext("if (int *a = (&b))"); 9926 verifyIndependentOfContext("while (int *a = &b)"); 9927 verifyIndependentOfContext("while (a * (b * c))"); 9928 verifyIndependentOfContext("size = sizeof *a;"); 9929 verifyIndependentOfContext("if (a && (b = c))"); 9930 verifyFormat("void f() {\n" 9931 " for (const int &v : Values) {\n" 9932 " }\n" 9933 "}"); 9934 verifyFormat("for (int i = a * a; i < 10; ++i) {\n}"); 9935 verifyFormat("for (int i = 0; i < a * a; ++i) {\n}"); 9936 verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}"); 9937 9938 verifyFormat("#define A (!a * b)"); 9939 verifyFormat("#define MACRO \\\n" 9940 " int *i = a * b; \\\n" 9941 " void f(a *b);", 9942 getLLVMStyleWithColumns(19)); 9943 9944 verifyIndependentOfContext("A = new SomeType *[Length];"); 9945 verifyIndependentOfContext("A = new SomeType *[Length]();"); 9946 verifyIndependentOfContext("T **t = new T *;"); 9947 verifyIndependentOfContext("T **t = new T *();"); 9948 verifyGoogleFormat("A = new SomeType*[Length]();"); 9949 verifyGoogleFormat("A = new SomeType*[Length];"); 9950 verifyGoogleFormat("T** t = new T*;"); 9951 verifyGoogleFormat("T** t = new T*();"); 9952 9953 verifyFormat("STATIC_ASSERT((a & b) == 0);"); 9954 verifyFormat("STATIC_ASSERT(0 == (a & b));"); 9955 verifyFormat("template <bool a, bool b> " 9956 "typename t::if<x && y>::type f() {}"); 9957 verifyFormat("template <int *y> f() {}"); 9958 verifyFormat("vector<int *> v;"); 9959 verifyFormat("vector<int *const> v;"); 9960 verifyFormat("vector<int *const **const *> v;"); 9961 verifyFormat("vector<int *volatile> v;"); 9962 verifyFormat("vector<a *_Nonnull> v;"); 9963 verifyFormat("vector<a *_Nullable> v;"); 9964 verifyFormat("vector<a *_Null_unspecified> v;"); 9965 verifyFormat("vector<a *__ptr32> v;"); 9966 verifyFormat("vector<a *__ptr64> v;"); 9967 verifyFormat("vector<a *__capability> v;"); 9968 FormatStyle TypeMacros = getLLVMStyle(); 9969 TypeMacros.TypenameMacros = {"LIST"}; 9970 verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros); 9971 verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros); 9972 verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros); 9973 verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros); 9974 verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication 9975 9976 FormatStyle CustomQualifier = getLLVMStyle(); 9977 // Add identifiers that should not be parsed as a qualifier by default. 9978 CustomQualifier.AttributeMacros.push_back("__my_qualifier"); 9979 CustomQualifier.AttributeMacros.push_back("_My_qualifier"); 9980 CustomQualifier.AttributeMacros.push_back("my_other_qualifier"); 9981 verifyFormat("vector<a * __my_qualifier> parse_as_multiply;"); 9982 verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier); 9983 verifyFormat("vector<a * _My_qualifier> parse_as_multiply;"); 9984 verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier); 9985 verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;"); 9986 verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier); 9987 verifyFormat("vector<a * _NotAQualifier> v;"); 9988 verifyFormat("vector<a * __not_a_qualifier> v;"); 9989 verifyFormat("vector<a * b> v;"); 9990 verifyFormat("foo<b && false>();"); 9991 verifyFormat("foo<b & 1>();"); 9992 verifyFormat("decltype(*::std::declval<const T &>()) void F();"); 9993 verifyFormat("typeof(*::std::declval<const T &>()) void F();"); 9994 verifyFormat("_Atomic(*::std::declval<const T &>()) void F();"); 9995 verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();"); 9996 verifyFormat( 9997 "template <class T, class = typename std::enable_if<\n" 9998 " std::is_integral<T>::value &&\n" 9999 " (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n" 10000 "void F();", 10001 getLLVMStyleWithColumns(70)); 10002 verifyFormat("template <class T,\n" 10003 " class = typename std::enable_if<\n" 10004 " std::is_integral<T>::value &&\n" 10005 " (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n" 10006 " class U>\n" 10007 "void F();", 10008 getLLVMStyleWithColumns(70)); 10009 verifyFormat( 10010 "template <class T,\n" 10011 " class = typename ::std::enable_if<\n" 10012 " ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n" 10013 "void F();", 10014 getGoogleStyleWithColumns(68)); 10015 10016 verifyIndependentOfContext("MACRO(int *i);"); 10017 verifyIndependentOfContext("MACRO(auto *a);"); 10018 verifyIndependentOfContext("MACRO(const A *a);"); 10019 verifyIndependentOfContext("MACRO(_Atomic(A) *a);"); 10020 verifyIndependentOfContext("MACRO(decltype(A) *a);"); 10021 verifyIndependentOfContext("MACRO(typeof(A) *a);"); 10022 verifyIndependentOfContext("MACRO(__underlying_type(A) *a);"); 10023 verifyIndependentOfContext("MACRO(A *const a);"); 10024 verifyIndependentOfContext("MACRO(A *restrict a);"); 10025 verifyIndependentOfContext("MACRO(A *__restrict__ a);"); 10026 verifyIndependentOfContext("MACRO(A *__restrict a);"); 10027 verifyIndependentOfContext("MACRO(A *volatile a);"); 10028 verifyIndependentOfContext("MACRO(A *__volatile a);"); 10029 verifyIndependentOfContext("MACRO(A *__volatile__ a);"); 10030 verifyIndependentOfContext("MACRO(A *_Nonnull a);"); 10031 verifyIndependentOfContext("MACRO(A *_Nullable a);"); 10032 verifyIndependentOfContext("MACRO(A *_Null_unspecified a);"); 10033 verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);"); 10034 verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);"); 10035 verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);"); 10036 verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);"); 10037 verifyIndependentOfContext("MACRO(A *__ptr32 a);"); 10038 verifyIndependentOfContext("MACRO(A *__ptr64 a);"); 10039 verifyIndependentOfContext("MACRO(A *__capability);"); 10040 verifyIndependentOfContext("MACRO(A &__capability);"); 10041 verifyFormat("MACRO(A *__my_qualifier);"); // type declaration 10042 verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication 10043 // If we add __my_qualifier to AttributeMacros it should always be parsed as 10044 // a type declaration: 10045 verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier); 10046 verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier); 10047 // Also check that TypenameMacros prevents parsing it as multiplication: 10048 verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication 10049 verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type 10050 10051 verifyIndependentOfContext("MACRO('0' <= c && c <= '9');"); 10052 verifyFormat("void f() { f(float{1}, a * a); }"); 10053 verifyFormat("void f() { f(float(1), a * a); }"); 10054 10055 verifyFormat("f((void (*)(int))g);"); 10056 verifyFormat("f((void (&)(int))g);"); 10057 verifyFormat("f((void (^)(int))g);"); 10058 10059 // FIXME: Is there a way to make this work? 10060 // verifyIndependentOfContext("MACRO(A *a);"); 10061 verifyFormat("MACRO(A &B);"); 10062 verifyFormat("MACRO(A *B);"); 10063 verifyFormat("void f() { MACRO(A * B); }"); 10064 verifyFormat("void f() { MACRO(A & B); }"); 10065 10066 // This lambda was mis-formatted after D88956 (treating it as a binop): 10067 verifyFormat("auto x = [](const decltype(x) &ptr) {};"); 10068 verifyFormat("auto x = [](const decltype(x) *ptr) {};"); 10069 verifyFormat("#define lambda [](const decltype(x) &ptr) {}"); 10070 verifyFormat("#define lambda [](const decltype(x) *ptr) {}"); 10071 10072 verifyFormat("DatumHandle const *operator->() const { return input_; }"); 10073 verifyFormat("return options != nullptr && operator==(*options);"); 10074 10075 EXPECT_EQ("#define OP(x) \\\n" 10076 " ostream &operator<<(ostream &s, const A &a) { \\\n" 10077 " return s << a.DebugString(); \\\n" 10078 " }", 10079 format("#define OP(x) \\\n" 10080 " ostream &operator<<(ostream &s, const A &a) { \\\n" 10081 " return s << a.DebugString(); \\\n" 10082 " }", 10083 getLLVMStyleWithColumns(50))); 10084 10085 // FIXME: We cannot handle this case yet; we might be able to figure out that 10086 // foo<x> d > v; doesn't make sense. 10087 verifyFormat("foo<a<b && c> d> v;"); 10088 10089 FormatStyle PointerMiddle = getLLVMStyle(); 10090 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle; 10091 verifyFormat("delete *x;", PointerMiddle); 10092 verifyFormat("int * x;", PointerMiddle); 10093 verifyFormat("int *[] x;", PointerMiddle); 10094 verifyFormat("template <int * y> f() {}", PointerMiddle); 10095 verifyFormat("int * f(int * a) {}", PointerMiddle); 10096 verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle); 10097 verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle); 10098 verifyFormat("A<int *> a;", PointerMiddle); 10099 verifyFormat("A<int **> a;", PointerMiddle); 10100 verifyFormat("A<int *, int *> a;", PointerMiddle); 10101 verifyFormat("A<int *[]> a;", PointerMiddle); 10102 verifyFormat("A = new SomeType *[Length]();", PointerMiddle); 10103 verifyFormat("A = new SomeType *[Length];", PointerMiddle); 10104 verifyFormat("T ** t = new T *;", PointerMiddle); 10105 10106 // Member function reference qualifiers aren't binary operators. 10107 verifyFormat("string // break\n" 10108 "operator()() & {}"); 10109 verifyFormat("string // break\n" 10110 "operator()() && {}"); 10111 verifyGoogleFormat("template <typename T>\n" 10112 "auto x() & -> int {}"); 10113 10114 // Should be binary operators when used as an argument expression (overloaded 10115 // operator invoked as a member function). 10116 verifyFormat("void f() { a.operator()(a * a); }"); 10117 verifyFormat("void f() { a->operator()(a & a); }"); 10118 verifyFormat("void f() { a.operator()(*a & *a); }"); 10119 verifyFormat("void f() { a->operator()(*a * *a); }"); 10120 10121 verifyFormat("int operator()(T (&&)[N]) { return 1; }"); 10122 verifyFormat("int operator()(T (&)[N]) { return 0; }"); 10123 } 10124 10125 TEST_F(FormatTest, UnderstandsAttributes) { 10126 verifyFormat("SomeType s __attribute__((unused)) (InitValue);"); 10127 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n" 10128 "aaaaaaaaaaaaaaaaaaaaaaa(int i);"); 10129 verifyFormat("__attribute__((nodebug)) ::qualified_type f();"); 10130 FormatStyle AfterType = getLLVMStyle(); 10131 AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 10132 verifyFormat("__attribute__((nodebug)) void\n" 10133 "foo() {}\n", 10134 AfterType); 10135 verifyFormat("__unused void\n" 10136 "foo() {}", 10137 AfterType); 10138 10139 FormatStyle CustomAttrs = getLLVMStyle(); 10140 CustomAttrs.AttributeMacros.push_back("__unused"); 10141 CustomAttrs.AttributeMacros.push_back("__attr1"); 10142 CustomAttrs.AttributeMacros.push_back("__attr2"); 10143 CustomAttrs.AttributeMacros.push_back("no_underscore_attr"); 10144 verifyFormat("vector<SomeType *__attribute((foo))> v;"); 10145 verifyFormat("vector<SomeType *__attribute__((foo))> v;"); 10146 verifyFormat("vector<SomeType * __not_attribute__((foo))> v;"); 10147 // Check that it is parsed as a multiplication without AttributeMacros and 10148 // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros. 10149 verifyFormat("vector<SomeType * __attr1> v;"); 10150 verifyFormat("vector<SomeType __attr1 *> v;"); 10151 verifyFormat("vector<SomeType __attr1 *const> v;"); 10152 verifyFormat("vector<SomeType __attr1 * __attr2> v;"); 10153 verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs); 10154 verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs); 10155 verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs); 10156 verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs); 10157 verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs); 10158 verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs); 10159 verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs); 10160 10161 // Check that these are not parsed as function declarations: 10162 CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 10163 CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman; 10164 verifyFormat("SomeType s(InitValue);", CustomAttrs); 10165 verifyFormat("SomeType s{InitValue};", CustomAttrs); 10166 verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs); 10167 verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs); 10168 verifyFormat("SomeType s __unused(InitValue);", CustomAttrs); 10169 verifyFormat("SomeType s __unused{InitValue};", CustomAttrs); 10170 verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs); 10171 verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs); 10172 } 10173 10174 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) { 10175 // Check that qualifiers on pointers don't break parsing of casts. 10176 verifyFormat("x = (foo *const)*v;"); 10177 verifyFormat("x = (foo *volatile)*v;"); 10178 verifyFormat("x = (foo *restrict)*v;"); 10179 verifyFormat("x = (foo *__attribute__((foo)))*v;"); 10180 verifyFormat("x = (foo *_Nonnull)*v;"); 10181 verifyFormat("x = (foo *_Nullable)*v;"); 10182 verifyFormat("x = (foo *_Null_unspecified)*v;"); 10183 verifyFormat("x = (foo *_Nonnull)*v;"); 10184 verifyFormat("x = (foo *[[clang::attr]])*v;"); 10185 verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;"); 10186 verifyFormat("x = (foo *__ptr32)*v;"); 10187 verifyFormat("x = (foo *__ptr64)*v;"); 10188 verifyFormat("x = (foo *__capability)*v;"); 10189 10190 // Check that we handle multiple trailing qualifiers and skip them all to 10191 // determine that the expression is a cast to a pointer type. 10192 FormatStyle LongPointerRight = getLLVMStyleWithColumns(999); 10193 FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999); 10194 LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left; 10195 StringRef AllQualifiers = 10196 "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified " 10197 "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability"; 10198 verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight); 10199 verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft); 10200 10201 // Also check that address-of is not parsed as a binary bitwise-and: 10202 verifyFormat("x = (foo *const)&v;"); 10203 verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight); 10204 verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft); 10205 10206 // Check custom qualifiers: 10207 FormatStyle CustomQualifier = getLLVMStyleWithColumns(999); 10208 CustomQualifier.AttributeMacros.push_back("__my_qualifier"); 10209 verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier. 10210 verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier); 10211 verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(), 10212 CustomQualifier); 10213 verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(), 10214 CustomQualifier); 10215 10216 // Check that unknown identifiers result in binary operator parsing: 10217 verifyFormat("x = (foo * __unknown_qualifier) * v;"); 10218 verifyFormat("x = (foo * __unknown_qualifier) & v;"); 10219 } 10220 10221 TEST_F(FormatTest, UnderstandsSquareAttributes) { 10222 verifyFormat("SomeType s [[unused]] (InitValue);"); 10223 verifyFormat("SomeType s [[gnu::unused]] (InitValue);"); 10224 verifyFormat("SomeType s [[using gnu: unused]] (InitValue);"); 10225 verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}"); 10226 verifyFormat("void f() [[deprecated(\"so sorry\")]];"); 10227 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10228 " [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);"); 10229 verifyFormat("[[nodiscard]] bool f() { return false; }"); 10230 verifyFormat("class [[nodiscard]] f {\npublic:\n f() {}\n}"); 10231 verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n f() {}\n}"); 10232 verifyFormat("class [[gnu::unused]] f {\npublic:\n f() {}\n}"); 10233 verifyFormat("[[nodiscard]] ::qualified_type f();"); 10234 10235 // Make sure we do not mistake attributes for array subscripts. 10236 verifyFormat("int a() {}\n" 10237 "[[unused]] int b() {}\n"); 10238 verifyFormat("NSArray *arr;\n" 10239 "arr[[Foo() bar]];"); 10240 10241 // On the other hand, we still need to correctly find array subscripts. 10242 verifyFormat("int a = std::vector<int>{1, 2, 3}[0];"); 10243 10244 // Make sure that we do not mistake Objective-C method inside array literals 10245 // as attributes, even if those method names are also keywords. 10246 verifyFormat("@[ [foo bar] ];"); 10247 verifyFormat("@[ [NSArray class] ];"); 10248 verifyFormat("@[ [foo enum] ];"); 10249 10250 verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }"); 10251 10252 // Make sure we do not parse attributes as lambda introducers. 10253 FormatStyle MultiLineFunctions = getLLVMStyle(); 10254 MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 10255 verifyFormat("[[unused]] int b() {\n" 10256 " return 42;\n" 10257 "}\n", 10258 MultiLineFunctions); 10259 } 10260 10261 TEST_F(FormatTest, AttributeClass) { 10262 FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp); 10263 verifyFormat("class S {\n" 10264 " S(S&&) = default;\n" 10265 "};", 10266 Style); 10267 verifyFormat("class [[nodiscard]] S {\n" 10268 " S(S&&) = default;\n" 10269 "};", 10270 Style); 10271 verifyFormat("class __attribute((maybeunused)) S {\n" 10272 " S(S&&) = default;\n" 10273 "};", 10274 Style); 10275 verifyFormat("struct S {\n" 10276 " S(S&&) = default;\n" 10277 "};", 10278 Style); 10279 verifyFormat("struct [[nodiscard]] S {\n" 10280 " S(S&&) = default;\n" 10281 "};", 10282 Style); 10283 } 10284 10285 TEST_F(FormatTest, AttributesAfterMacro) { 10286 FormatStyle Style = getLLVMStyle(); 10287 verifyFormat("MACRO;\n" 10288 "__attribute__((maybe_unused)) int foo() {\n" 10289 " //...\n" 10290 "}"); 10291 10292 verifyFormat("MACRO;\n" 10293 "[[nodiscard]] int foo() {\n" 10294 " //...\n" 10295 "}"); 10296 10297 EXPECT_EQ("MACRO\n\n" 10298 "__attribute__((maybe_unused)) int foo() {\n" 10299 " //...\n" 10300 "}", 10301 format("MACRO\n\n" 10302 "__attribute__((maybe_unused)) int foo() {\n" 10303 " //...\n" 10304 "}")); 10305 10306 EXPECT_EQ("MACRO\n\n" 10307 "[[nodiscard]] int foo() {\n" 10308 " //...\n" 10309 "}", 10310 format("MACRO\n\n" 10311 "[[nodiscard]] int foo() {\n" 10312 " //...\n" 10313 "}")); 10314 } 10315 10316 TEST_F(FormatTest, AttributePenaltyBreaking) { 10317 FormatStyle Style = getLLVMStyle(); 10318 verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n" 10319 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}", 10320 Style); 10321 verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n" 10322 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}", 10323 Style); 10324 verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const " 10325 "shared_ptr<ALongTypeName> &C d) {\n}", 10326 Style); 10327 } 10328 10329 TEST_F(FormatTest, UnderstandsEllipsis) { 10330 FormatStyle Style = getLLVMStyle(); 10331 verifyFormat("int printf(const char *fmt, ...);"); 10332 verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }"); 10333 verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}"); 10334 10335 verifyFormat("template <int *...PP> a;", Style); 10336 10337 Style.PointerAlignment = FormatStyle::PAS_Left; 10338 verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style); 10339 10340 verifyFormat("template <int*... PP> a;", Style); 10341 10342 Style.PointerAlignment = FormatStyle::PAS_Middle; 10343 verifyFormat("template <int *... PP> a;", Style); 10344 } 10345 10346 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) { 10347 EXPECT_EQ("int *a;\n" 10348 "int *a;\n" 10349 "int *a;", 10350 format("int *a;\n" 10351 "int* a;\n" 10352 "int *a;", 10353 getGoogleStyle())); 10354 EXPECT_EQ("int* a;\n" 10355 "int* a;\n" 10356 "int* a;", 10357 format("int* a;\n" 10358 "int* a;\n" 10359 "int *a;", 10360 getGoogleStyle())); 10361 EXPECT_EQ("int *a;\n" 10362 "int *a;\n" 10363 "int *a;", 10364 format("int *a;\n" 10365 "int * a;\n" 10366 "int * a;", 10367 getGoogleStyle())); 10368 EXPECT_EQ("auto x = [] {\n" 10369 " int *a;\n" 10370 " int *a;\n" 10371 " int *a;\n" 10372 "};", 10373 format("auto x=[]{int *a;\n" 10374 "int * a;\n" 10375 "int * a;};", 10376 getGoogleStyle())); 10377 } 10378 10379 TEST_F(FormatTest, UnderstandsRvalueReferences) { 10380 verifyFormat("int f(int &&a) {}"); 10381 verifyFormat("int f(int a, char &&b) {}"); 10382 verifyFormat("void f() { int &&a = b; }"); 10383 verifyGoogleFormat("int f(int a, char&& b) {}"); 10384 verifyGoogleFormat("void f() { int&& a = b; }"); 10385 10386 verifyIndependentOfContext("A<int &&> a;"); 10387 verifyIndependentOfContext("A<int &&, int &&> a;"); 10388 verifyGoogleFormat("A<int&&> a;"); 10389 verifyGoogleFormat("A<int&&, int&&> a;"); 10390 10391 // Not rvalue references: 10392 verifyFormat("template <bool B, bool C> class A {\n" 10393 " static_assert(B && C, \"Something is wrong\");\n" 10394 "};"); 10395 verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))"); 10396 verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))"); 10397 verifyFormat("#define A(a, b) (a && b)"); 10398 } 10399 10400 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) { 10401 verifyFormat("void f() {\n" 10402 " x[aaaaaaaaa -\n" 10403 " b] = 23;\n" 10404 "}", 10405 getLLVMStyleWithColumns(15)); 10406 } 10407 10408 TEST_F(FormatTest, FormatsCasts) { 10409 verifyFormat("Type *A = static_cast<Type *>(P);"); 10410 verifyFormat("Type *A = (Type *)P;"); 10411 verifyFormat("Type *A = (vector<Type *, int *>)P;"); 10412 verifyFormat("int a = (int)(2.0f);"); 10413 verifyFormat("int a = (int)2.0f;"); 10414 verifyFormat("x[(int32)y];"); 10415 verifyFormat("x = (int32)y;"); 10416 verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)"); 10417 verifyFormat("int a = (int)*b;"); 10418 verifyFormat("int a = (int)2.0f;"); 10419 verifyFormat("int a = (int)~0;"); 10420 verifyFormat("int a = (int)++a;"); 10421 verifyFormat("int a = (int)sizeof(int);"); 10422 verifyFormat("int a = (int)+2;"); 10423 verifyFormat("my_int a = (my_int)2.0f;"); 10424 verifyFormat("my_int a = (my_int)sizeof(int);"); 10425 verifyFormat("return (my_int)aaa;"); 10426 verifyFormat("#define x ((int)-1)"); 10427 verifyFormat("#define LENGTH(x, y) (x) - (y) + 1"); 10428 verifyFormat("#define p(q) ((int *)&q)"); 10429 verifyFormat("fn(a)(b) + 1;"); 10430 10431 verifyFormat("void f() { my_int a = (my_int)*b; }"); 10432 verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }"); 10433 verifyFormat("my_int a = (my_int)~0;"); 10434 verifyFormat("my_int a = (my_int)++a;"); 10435 verifyFormat("my_int a = (my_int)-2;"); 10436 verifyFormat("my_int a = (my_int)1;"); 10437 verifyFormat("my_int a = (my_int *)1;"); 10438 verifyFormat("my_int a = (const my_int)-1;"); 10439 verifyFormat("my_int a = (const my_int *)-1;"); 10440 verifyFormat("my_int a = (my_int)(my_int)-1;"); 10441 verifyFormat("my_int a = (ns::my_int)-2;"); 10442 verifyFormat("case (my_int)ONE:"); 10443 verifyFormat("auto x = (X)this;"); 10444 // Casts in Obj-C style calls used to not be recognized as such. 10445 verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle()); 10446 10447 // FIXME: single value wrapped with paren will be treated as cast. 10448 verifyFormat("void f(int i = (kValue)*kMask) {}"); 10449 10450 verifyFormat("{ (void)F; }"); 10451 10452 // Don't break after a cast's 10453 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 10454 " (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n" 10455 " bbbbbbbbbbbbbbbbbbbbbb);"); 10456 10457 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(x)"); 10458 verifyFormat("#define CONF_BOOL(x) (bool *)(x)"); 10459 verifyFormat("#define CONF_BOOL(x) (bool)(x)"); 10460 verifyFormat("bool *y = (bool *)(void *)(x);"); 10461 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)(x)"); 10462 verifyFormat("bool *y = (bool *)(void *)(int)(x);"); 10463 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)foo(x)"); 10464 verifyFormat("bool *y = (bool *)(void *)(int)foo(x);"); 10465 10466 // These are not casts. 10467 verifyFormat("void f(int *) {}"); 10468 verifyFormat("f(foo)->b;"); 10469 verifyFormat("f(foo).b;"); 10470 verifyFormat("f(foo)(b);"); 10471 verifyFormat("f(foo)[b];"); 10472 verifyFormat("[](foo) { return 4; }(bar);"); 10473 verifyFormat("(*funptr)(foo)[4];"); 10474 verifyFormat("funptrs[4](foo)[4];"); 10475 verifyFormat("void f(int *);"); 10476 verifyFormat("void f(int *) = 0;"); 10477 verifyFormat("void f(SmallVector<int>) {}"); 10478 verifyFormat("void f(SmallVector<int>);"); 10479 verifyFormat("void f(SmallVector<int>) = 0;"); 10480 verifyFormat("void f(int i = (kA * kB) & kMask) {}"); 10481 verifyFormat("int a = sizeof(int) * b;"); 10482 verifyFormat("int a = alignof(int) * b;", getGoogleStyle()); 10483 verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;"); 10484 verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");"); 10485 verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;"); 10486 10487 // These are not casts, but at some point were confused with casts. 10488 verifyFormat("virtual void foo(int *) override;"); 10489 verifyFormat("virtual void foo(char &) const;"); 10490 verifyFormat("virtual void foo(int *a, char *) const;"); 10491 verifyFormat("int a = sizeof(int *) + b;"); 10492 verifyFormat("int a = alignof(int *) + b;", getGoogleStyle()); 10493 verifyFormat("bool b = f(g<int>) && c;"); 10494 verifyFormat("typedef void (*f)(int i) func;"); 10495 verifyFormat("void operator++(int) noexcept;"); 10496 verifyFormat("void operator++(int &) noexcept;"); 10497 verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t " 10498 "&) noexcept;"); 10499 verifyFormat( 10500 "void operator delete(std::size_t, const std::nothrow_t &) noexcept;"); 10501 verifyFormat("void operator delete(const std::nothrow_t &) noexcept;"); 10502 verifyFormat("void operator delete(std::nothrow_t &) noexcept;"); 10503 verifyFormat("void operator delete(nothrow_t &) noexcept;"); 10504 verifyFormat("void operator delete(foo &) noexcept;"); 10505 verifyFormat("void operator delete(foo) noexcept;"); 10506 verifyFormat("void operator delete(int) noexcept;"); 10507 verifyFormat("void operator delete(int &) noexcept;"); 10508 verifyFormat("void operator delete(int &) volatile noexcept;"); 10509 verifyFormat("void operator delete(int &) const"); 10510 verifyFormat("void operator delete(int &) = default"); 10511 verifyFormat("void operator delete(int &) = delete"); 10512 verifyFormat("void operator delete(int &) [[noreturn]]"); 10513 verifyFormat("void operator delete(int &) throw();"); 10514 verifyFormat("void operator delete(int &) throw(int);"); 10515 verifyFormat("auto operator delete(int &) -> int;"); 10516 verifyFormat("auto operator delete(int &) override"); 10517 verifyFormat("auto operator delete(int &) final"); 10518 10519 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n" 10520 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 10521 // FIXME: The indentation here is not ideal. 10522 verifyFormat( 10523 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10524 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n" 10525 " [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];"); 10526 } 10527 10528 TEST_F(FormatTest, FormatsFunctionTypes) { 10529 verifyFormat("A<bool()> a;"); 10530 verifyFormat("A<SomeType()> a;"); 10531 verifyFormat("A<void (*)(int, std::string)> a;"); 10532 verifyFormat("A<void *(int)>;"); 10533 verifyFormat("void *(*a)(int *, SomeType *);"); 10534 verifyFormat("int (*func)(void *);"); 10535 verifyFormat("void f() { int (*func)(void *); }"); 10536 verifyFormat("template <class CallbackClass>\n" 10537 "using MyCallback = void (CallbackClass::*)(SomeObject *Data);"); 10538 10539 verifyGoogleFormat("A<void*(int*, SomeType*)>;"); 10540 verifyGoogleFormat("void* (*a)(int);"); 10541 verifyGoogleFormat( 10542 "template <class CallbackClass>\n" 10543 "using MyCallback = void (CallbackClass::*)(SomeObject* Data);"); 10544 10545 // Other constructs can look somewhat like function types: 10546 verifyFormat("A<sizeof(*x)> a;"); 10547 verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)"); 10548 verifyFormat("some_var = function(*some_pointer_var)[0];"); 10549 verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }"); 10550 verifyFormat("int x = f(&h)();"); 10551 verifyFormat("returnsFunction(¶m1, ¶m2)(param);"); 10552 verifyFormat("std::function<\n" 10553 " LooooooooooongTemplatedType<\n" 10554 " SomeType>*(\n" 10555 " LooooooooooooooooongType type)>\n" 10556 " function;", 10557 getGoogleStyleWithColumns(40)); 10558 } 10559 10560 TEST_F(FormatTest, FormatsPointersToArrayTypes) { 10561 verifyFormat("A (*foo_)[6];"); 10562 verifyFormat("vector<int> (*foo_)[6];"); 10563 } 10564 10565 TEST_F(FormatTest, BreaksLongVariableDeclarations) { 10566 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10567 " LoooooooooooooooooooooooooooooooooooooooongVariable;"); 10568 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n" 10569 " LoooooooooooooooooooooooooooooooooooooooongVariable;"); 10570 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10571 " *LoooooooooooooooooooooooooooooooooooooooongVariable;"); 10572 10573 // Different ways of ()-initializiation. 10574 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10575 " LoooooooooooooooooooooooooooooooooooooooongVariable(1);"); 10576 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10577 " LoooooooooooooooooooooooooooooooooooooooongVariable(a);"); 10578 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10579 " LoooooooooooooooooooooooooooooooooooooooongVariable({});"); 10580 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10581 " LoooooooooooooooooooooooooooooooooooooongVariable([A a]);"); 10582 10583 // Lambdas should not confuse the variable declaration heuristic. 10584 verifyFormat("LooooooooooooooooongType\n" 10585 " variable(nullptr, [](A *a) {});", 10586 getLLVMStyleWithColumns(40)); 10587 } 10588 10589 TEST_F(FormatTest, BreaksLongDeclarations) { 10590 verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n" 10591 " AnotherNameForTheLongType;"); 10592 verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n" 10593 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 10594 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10595 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();"); 10596 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n" 10597 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();"); 10598 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10599 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10600 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n" 10601 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10602 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n" 10603 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10604 verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n" 10605 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10606 verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n" 10607 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10608 verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n" 10609 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10610 verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n" 10611 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10612 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10613 "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);"); 10614 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10615 "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}"); 10616 FormatStyle Indented = getLLVMStyle(); 10617 Indented.IndentWrappedFunctionNames = true; 10618 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10619 " LoooooooooooooooooooooooooooooooongFunctionDeclaration();", 10620 Indented); 10621 verifyFormat( 10622 "LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10623 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 10624 Indented); 10625 verifyFormat( 10626 "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n" 10627 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 10628 Indented); 10629 verifyFormat( 10630 "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n" 10631 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 10632 Indented); 10633 10634 // FIXME: Without the comment, this breaks after "(". 10635 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType // break\n" 10636 " (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();", 10637 getGoogleStyle()); 10638 10639 verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n" 10640 " int LoooooooooooooooooooongParam2) {}"); 10641 verifyFormat( 10642 "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n" 10643 " SourceLocation L, IdentifierIn *II,\n" 10644 " Type *T) {}"); 10645 verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n" 10646 "ReallyReaaallyLongFunctionName(\n" 10647 " const std::string &SomeParameter,\n" 10648 " const SomeType<string, SomeOtherTemplateParameter>\n" 10649 " &ReallyReallyLongParameterName,\n" 10650 " const SomeType<string, SomeOtherTemplateParameter>\n" 10651 " &AnotherLongParameterName) {}"); 10652 verifyFormat("template <typename A>\n" 10653 "SomeLoooooooooooooooooooooongType<\n" 10654 " typename some_namespace::SomeOtherType<A>::Type>\n" 10655 "Function() {}"); 10656 10657 verifyGoogleFormat( 10658 "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n" 10659 " aaaaaaaaaaaaaaaaaaaaaaa;"); 10660 verifyGoogleFormat( 10661 "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n" 10662 " SourceLocation L) {}"); 10663 verifyGoogleFormat( 10664 "some_namespace::LongReturnType\n" 10665 "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n" 10666 " int first_long_parameter, int second_parameter) {}"); 10667 10668 verifyGoogleFormat("template <typename T>\n" 10669 "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n" 10670 "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}"); 10671 verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 10672 " int aaaaaaaaaaaaaaaaaaaaaaa);"); 10673 10674 verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n" 10675 " const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10676 " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 10677 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 10678 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n" 10679 " aaaaaaaaaaaaaaaaaaaaaaaa);"); 10680 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 10681 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 10682 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n" 10683 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 10684 10685 verifyFormat("template <typename T> // Templates on own line.\n" 10686 "static int // Some comment.\n" 10687 "MyFunction(int a);", 10688 getLLVMStyle()); 10689 } 10690 10691 TEST_F(FormatTest, FormatsAccessModifiers) { 10692 FormatStyle Style = getLLVMStyle(); 10693 EXPECT_EQ(Style.EmptyLineBeforeAccessModifier, 10694 FormatStyle::ELBAMS_LogicalBlock); 10695 verifyFormat("struct foo {\n" 10696 "private:\n" 10697 " void f() {}\n" 10698 "\n" 10699 "private:\n" 10700 " int i;\n" 10701 "\n" 10702 "protected:\n" 10703 " int j;\n" 10704 "};\n", 10705 Style); 10706 verifyFormat("struct foo {\n" 10707 "private:\n" 10708 " void f() {}\n" 10709 "\n" 10710 "private:\n" 10711 " int i;\n" 10712 "\n" 10713 "protected:\n" 10714 " int j;\n" 10715 "};\n", 10716 "struct foo {\n" 10717 "private:\n" 10718 " void f() {}\n" 10719 "private:\n" 10720 " int i;\n" 10721 "protected:\n" 10722 " int j;\n" 10723 "};\n", 10724 Style); 10725 verifyFormat("struct foo { /* comment */\n" 10726 "private:\n" 10727 " int i;\n" 10728 " // comment\n" 10729 "private:\n" 10730 " int j;\n" 10731 "};\n", 10732 Style); 10733 verifyFormat("struct foo {\n" 10734 "#ifdef FOO\n" 10735 "#endif\n" 10736 "private:\n" 10737 " int i;\n" 10738 "#ifdef FOO\n" 10739 "private:\n" 10740 "#endif\n" 10741 " int j;\n" 10742 "};\n", 10743 Style); 10744 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 10745 verifyFormat("struct foo {\n" 10746 "private:\n" 10747 " void f() {}\n" 10748 "private:\n" 10749 " int i;\n" 10750 "protected:\n" 10751 " int j;\n" 10752 "};\n", 10753 Style); 10754 verifyFormat("struct foo {\n" 10755 "private:\n" 10756 " void f() {}\n" 10757 "private:\n" 10758 " int i;\n" 10759 "protected:\n" 10760 " int j;\n" 10761 "};\n", 10762 "struct foo {\n" 10763 "\n" 10764 "private:\n" 10765 " void f() {}\n" 10766 "\n" 10767 "private:\n" 10768 " int i;\n" 10769 "\n" 10770 "protected:\n" 10771 " int j;\n" 10772 "};\n", 10773 Style); 10774 verifyFormat("struct foo { /* comment */\n" 10775 "private:\n" 10776 " int i;\n" 10777 " // comment\n" 10778 "private:\n" 10779 " int j;\n" 10780 "};\n", 10781 "struct foo { /* comment */\n" 10782 "\n" 10783 "private:\n" 10784 " int i;\n" 10785 " // comment\n" 10786 "\n" 10787 "private:\n" 10788 " int j;\n" 10789 "};\n", 10790 Style); 10791 verifyFormat("struct foo {\n" 10792 "#ifdef FOO\n" 10793 "#endif\n" 10794 "private:\n" 10795 " int i;\n" 10796 "#ifdef FOO\n" 10797 "private:\n" 10798 "#endif\n" 10799 " int j;\n" 10800 "};\n", 10801 "struct foo {\n" 10802 "#ifdef FOO\n" 10803 "#endif\n" 10804 "\n" 10805 "private:\n" 10806 " int i;\n" 10807 "#ifdef FOO\n" 10808 "\n" 10809 "private:\n" 10810 "#endif\n" 10811 " int j;\n" 10812 "};\n", 10813 Style); 10814 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 10815 verifyFormat("struct foo {\n" 10816 "private:\n" 10817 " void f() {}\n" 10818 "\n" 10819 "private:\n" 10820 " int i;\n" 10821 "\n" 10822 "protected:\n" 10823 " int j;\n" 10824 "};\n", 10825 Style); 10826 verifyFormat("struct foo {\n" 10827 "private:\n" 10828 " void f() {}\n" 10829 "\n" 10830 "private:\n" 10831 " int i;\n" 10832 "\n" 10833 "protected:\n" 10834 " int j;\n" 10835 "};\n", 10836 "struct foo {\n" 10837 "private:\n" 10838 " void f() {}\n" 10839 "private:\n" 10840 " int i;\n" 10841 "protected:\n" 10842 " int j;\n" 10843 "};\n", 10844 Style); 10845 verifyFormat("struct foo { /* comment */\n" 10846 "private:\n" 10847 " int i;\n" 10848 " // comment\n" 10849 "\n" 10850 "private:\n" 10851 " int j;\n" 10852 "};\n", 10853 "struct foo { /* comment */\n" 10854 "private:\n" 10855 " int i;\n" 10856 " // comment\n" 10857 "\n" 10858 "private:\n" 10859 " int j;\n" 10860 "};\n", 10861 Style); 10862 verifyFormat("struct foo {\n" 10863 "#ifdef FOO\n" 10864 "#endif\n" 10865 "\n" 10866 "private:\n" 10867 " int i;\n" 10868 "#ifdef FOO\n" 10869 "\n" 10870 "private:\n" 10871 "#endif\n" 10872 " int j;\n" 10873 "};\n", 10874 "struct foo {\n" 10875 "#ifdef FOO\n" 10876 "#endif\n" 10877 "private:\n" 10878 " int i;\n" 10879 "#ifdef FOO\n" 10880 "private:\n" 10881 "#endif\n" 10882 " int j;\n" 10883 "};\n", 10884 Style); 10885 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 10886 EXPECT_EQ("struct foo {\n" 10887 "\n" 10888 "private:\n" 10889 " void f() {}\n" 10890 "\n" 10891 "private:\n" 10892 " int i;\n" 10893 "\n" 10894 "protected:\n" 10895 " int j;\n" 10896 "};\n", 10897 format("struct foo {\n" 10898 "\n" 10899 "private:\n" 10900 " void f() {}\n" 10901 "\n" 10902 "private:\n" 10903 " int i;\n" 10904 "\n" 10905 "protected:\n" 10906 " int j;\n" 10907 "};\n", 10908 Style)); 10909 verifyFormat("struct foo {\n" 10910 "private:\n" 10911 " void f() {}\n" 10912 "private:\n" 10913 " int i;\n" 10914 "protected:\n" 10915 " int j;\n" 10916 "};\n", 10917 Style); 10918 EXPECT_EQ("struct foo { /* comment */\n" 10919 "\n" 10920 "private:\n" 10921 " int i;\n" 10922 " // comment\n" 10923 "\n" 10924 "private:\n" 10925 " int j;\n" 10926 "};\n", 10927 format("struct foo { /* comment */\n" 10928 "\n" 10929 "private:\n" 10930 " int i;\n" 10931 " // comment\n" 10932 "\n" 10933 "private:\n" 10934 " int j;\n" 10935 "};\n", 10936 Style)); 10937 verifyFormat("struct foo { /* comment */\n" 10938 "private:\n" 10939 " int i;\n" 10940 " // comment\n" 10941 "private:\n" 10942 " int j;\n" 10943 "};\n", 10944 Style); 10945 EXPECT_EQ("struct foo {\n" 10946 "#ifdef FOO\n" 10947 "#endif\n" 10948 "\n" 10949 "private:\n" 10950 " int i;\n" 10951 "#ifdef FOO\n" 10952 "\n" 10953 "private:\n" 10954 "#endif\n" 10955 " int j;\n" 10956 "};\n", 10957 format("struct foo {\n" 10958 "#ifdef FOO\n" 10959 "#endif\n" 10960 "\n" 10961 "private:\n" 10962 " int i;\n" 10963 "#ifdef FOO\n" 10964 "\n" 10965 "private:\n" 10966 "#endif\n" 10967 " int j;\n" 10968 "};\n", 10969 Style)); 10970 verifyFormat("struct foo {\n" 10971 "#ifdef FOO\n" 10972 "#endif\n" 10973 "private:\n" 10974 " int i;\n" 10975 "#ifdef FOO\n" 10976 "private:\n" 10977 "#endif\n" 10978 " int j;\n" 10979 "};\n", 10980 Style); 10981 10982 FormatStyle NoEmptyLines = getLLVMStyle(); 10983 NoEmptyLines.MaxEmptyLinesToKeep = 0; 10984 verifyFormat("struct foo {\n" 10985 "private:\n" 10986 " void f() {}\n" 10987 "\n" 10988 "private:\n" 10989 " int i;\n" 10990 "\n" 10991 "public:\n" 10992 "protected:\n" 10993 " int j;\n" 10994 "};\n", 10995 NoEmptyLines); 10996 10997 NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 10998 verifyFormat("struct foo {\n" 10999 "private:\n" 11000 " void f() {}\n" 11001 "private:\n" 11002 " int i;\n" 11003 "public:\n" 11004 "protected:\n" 11005 " int j;\n" 11006 "};\n", 11007 NoEmptyLines); 11008 11009 NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11010 verifyFormat("struct foo {\n" 11011 "private:\n" 11012 " void f() {}\n" 11013 "\n" 11014 "private:\n" 11015 " int i;\n" 11016 "\n" 11017 "public:\n" 11018 "\n" 11019 "protected:\n" 11020 " int j;\n" 11021 "};\n", 11022 NoEmptyLines); 11023 } 11024 11025 TEST_F(FormatTest, FormatsAfterAccessModifiers) { 11026 11027 FormatStyle Style = getLLVMStyle(); 11028 EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never); 11029 verifyFormat("struct foo {\n" 11030 "private:\n" 11031 " void f() {}\n" 11032 "\n" 11033 "private:\n" 11034 " int i;\n" 11035 "\n" 11036 "protected:\n" 11037 " int j;\n" 11038 "};\n", 11039 Style); 11040 11041 // Check if lines are removed. 11042 verifyFormat("struct foo {\n" 11043 "private:\n" 11044 " void f() {}\n" 11045 "\n" 11046 "private:\n" 11047 " int i;\n" 11048 "\n" 11049 "protected:\n" 11050 " int j;\n" 11051 "};\n", 11052 "struct foo {\n" 11053 "private:\n" 11054 "\n" 11055 " void f() {}\n" 11056 "\n" 11057 "private:\n" 11058 "\n" 11059 " int i;\n" 11060 "\n" 11061 "protected:\n" 11062 "\n" 11063 " int j;\n" 11064 "};\n", 11065 Style); 11066 11067 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11068 verifyFormat("struct foo {\n" 11069 "private:\n" 11070 "\n" 11071 " void f() {}\n" 11072 "\n" 11073 "private:\n" 11074 "\n" 11075 " int i;\n" 11076 "\n" 11077 "protected:\n" 11078 "\n" 11079 " int j;\n" 11080 "};\n", 11081 Style); 11082 11083 // Check if lines are added. 11084 verifyFormat("struct foo {\n" 11085 "private:\n" 11086 "\n" 11087 " void f() {}\n" 11088 "\n" 11089 "private:\n" 11090 "\n" 11091 " int i;\n" 11092 "\n" 11093 "protected:\n" 11094 "\n" 11095 " int j;\n" 11096 "};\n", 11097 "struct foo {\n" 11098 "private:\n" 11099 " void f() {}\n" 11100 "\n" 11101 "private:\n" 11102 " int i;\n" 11103 "\n" 11104 "protected:\n" 11105 " int j;\n" 11106 "};\n", 11107 Style); 11108 11109 // Leave tests rely on the code layout, test::messUp can not be used. 11110 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11111 Style.MaxEmptyLinesToKeep = 0u; 11112 verifyFormat("struct foo {\n" 11113 "private:\n" 11114 " void f() {}\n" 11115 "\n" 11116 "private:\n" 11117 " int i;\n" 11118 "\n" 11119 "protected:\n" 11120 " int j;\n" 11121 "};\n", 11122 Style); 11123 11124 // Check if MaxEmptyLinesToKeep is respected. 11125 EXPECT_EQ("struct foo {\n" 11126 "private:\n" 11127 " void f() {}\n" 11128 "\n" 11129 "private:\n" 11130 " int i;\n" 11131 "\n" 11132 "protected:\n" 11133 " int j;\n" 11134 "};\n", 11135 format("struct foo {\n" 11136 "private:\n" 11137 "\n\n\n" 11138 " void f() {}\n" 11139 "\n" 11140 "private:\n" 11141 "\n\n\n" 11142 " int i;\n" 11143 "\n" 11144 "protected:\n" 11145 "\n\n\n" 11146 " int j;\n" 11147 "};\n", 11148 Style)); 11149 11150 Style.MaxEmptyLinesToKeep = 1u; 11151 EXPECT_EQ("struct foo {\n" 11152 "private:\n" 11153 "\n" 11154 " void f() {}\n" 11155 "\n" 11156 "private:\n" 11157 "\n" 11158 " int i;\n" 11159 "\n" 11160 "protected:\n" 11161 "\n" 11162 " int j;\n" 11163 "};\n", 11164 format("struct foo {\n" 11165 "private:\n" 11166 "\n" 11167 " void f() {}\n" 11168 "\n" 11169 "private:\n" 11170 "\n" 11171 " int i;\n" 11172 "\n" 11173 "protected:\n" 11174 "\n" 11175 " int j;\n" 11176 "};\n", 11177 Style)); 11178 // Check if no lines are kept. 11179 EXPECT_EQ("struct foo {\n" 11180 "private:\n" 11181 " void f() {}\n" 11182 "\n" 11183 "private:\n" 11184 " int i;\n" 11185 "\n" 11186 "protected:\n" 11187 " int j;\n" 11188 "};\n", 11189 format("struct foo {\n" 11190 "private:\n" 11191 " void f() {}\n" 11192 "\n" 11193 "private:\n" 11194 " int i;\n" 11195 "\n" 11196 "protected:\n" 11197 " int j;\n" 11198 "};\n", 11199 Style)); 11200 // Check if MaxEmptyLinesToKeep is respected. 11201 EXPECT_EQ("struct foo {\n" 11202 "private:\n" 11203 "\n" 11204 " void f() {}\n" 11205 "\n" 11206 "private:\n" 11207 "\n" 11208 " int i;\n" 11209 "\n" 11210 "protected:\n" 11211 "\n" 11212 " int j;\n" 11213 "};\n", 11214 format("struct foo {\n" 11215 "private:\n" 11216 "\n\n\n" 11217 " void f() {}\n" 11218 "\n" 11219 "private:\n" 11220 "\n\n\n" 11221 " int i;\n" 11222 "\n" 11223 "protected:\n" 11224 "\n\n\n" 11225 " int j;\n" 11226 "};\n", 11227 Style)); 11228 11229 Style.MaxEmptyLinesToKeep = 10u; 11230 EXPECT_EQ("struct foo {\n" 11231 "private:\n" 11232 "\n\n\n" 11233 " void f() {}\n" 11234 "\n" 11235 "private:\n" 11236 "\n\n\n" 11237 " int i;\n" 11238 "\n" 11239 "protected:\n" 11240 "\n\n\n" 11241 " int j;\n" 11242 "};\n", 11243 format("struct foo {\n" 11244 "private:\n" 11245 "\n\n\n" 11246 " void f() {}\n" 11247 "\n" 11248 "private:\n" 11249 "\n\n\n" 11250 " int i;\n" 11251 "\n" 11252 "protected:\n" 11253 "\n\n\n" 11254 " int j;\n" 11255 "};\n", 11256 Style)); 11257 11258 // Test with comments. 11259 Style = getLLVMStyle(); 11260 verifyFormat("struct foo {\n" 11261 "private:\n" 11262 " // comment\n" 11263 " void f() {}\n" 11264 "\n" 11265 "private: /* comment */\n" 11266 " int i;\n" 11267 "};\n", 11268 Style); 11269 verifyFormat("struct foo {\n" 11270 "private:\n" 11271 " // comment\n" 11272 " void f() {}\n" 11273 "\n" 11274 "private: /* comment */\n" 11275 " int i;\n" 11276 "};\n", 11277 "struct foo {\n" 11278 "private:\n" 11279 "\n" 11280 " // comment\n" 11281 " void f() {}\n" 11282 "\n" 11283 "private: /* comment */\n" 11284 "\n" 11285 " int i;\n" 11286 "};\n", 11287 Style); 11288 11289 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11290 verifyFormat("struct foo {\n" 11291 "private:\n" 11292 "\n" 11293 " // comment\n" 11294 " void f() {}\n" 11295 "\n" 11296 "private: /* comment */\n" 11297 "\n" 11298 " int i;\n" 11299 "};\n", 11300 "struct foo {\n" 11301 "private:\n" 11302 " // comment\n" 11303 " void f() {}\n" 11304 "\n" 11305 "private: /* comment */\n" 11306 " int i;\n" 11307 "};\n", 11308 Style); 11309 verifyFormat("struct foo {\n" 11310 "private:\n" 11311 "\n" 11312 " // comment\n" 11313 " void f() {}\n" 11314 "\n" 11315 "private: /* comment */\n" 11316 "\n" 11317 " int i;\n" 11318 "};\n", 11319 Style); 11320 11321 // Test with preprocessor defines. 11322 Style = getLLVMStyle(); 11323 verifyFormat("struct foo {\n" 11324 "private:\n" 11325 "#ifdef FOO\n" 11326 "#endif\n" 11327 " void f() {}\n" 11328 "};\n", 11329 Style); 11330 verifyFormat("struct foo {\n" 11331 "private:\n" 11332 "#ifdef FOO\n" 11333 "#endif\n" 11334 " void f() {}\n" 11335 "};\n", 11336 "struct foo {\n" 11337 "private:\n" 11338 "\n" 11339 "#ifdef FOO\n" 11340 "#endif\n" 11341 " void f() {}\n" 11342 "};\n", 11343 Style); 11344 11345 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11346 verifyFormat("struct foo {\n" 11347 "private:\n" 11348 "\n" 11349 "#ifdef FOO\n" 11350 "#endif\n" 11351 " void f() {}\n" 11352 "};\n", 11353 "struct foo {\n" 11354 "private:\n" 11355 "#ifdef FOO\n" 11356 "#endif\n" 11357 " void f() {}\n" 11358 "};\n", 11359 Style); 11360 verifyFormat("struct foo {\n" 11361 "private:\n" 11362 "\n" 11363 "#ifdef FOO\n" 11364 "#endif\n" 11365 " void f() {}\n" 11366 "};\n", 11367 Style); 11368 } 11369 11370 TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) { 11371 // Combined tests of EmptyLineAfterAccessModifier and 11372 // EmptyLineBeforeAccessModifier. 11373 FormatStyle Style = getLLVMStyle(); 11374 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11375 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11376 verifyFormat("struct foo {\n" 11377 "private:\n" 11378 "\n" 11379 "protected:\n" 11380 "};\n", 11381 Style); 11382 11383 Style.MaxEmptyLinesToKeep = 10u; 11384 // Both remove all new lines. 11385 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11386 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11387 verifyFormat("struct foo {\n" 11388 "private:\n" 11389 "protected:\n" 11390 "};\n", 11391 "struct foo {\n" 11392 "private:\n" 11393 "\n\n\n" 11394 "protected:\n" 11395 "};\n", 11396 Style); 11397 11398 // Leave tests rely on the code layout, test::messUp can not be used. 11399 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11400 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11401 Style.MaxEmptyLinesToKeep = 10u; 11402 EXPECT_EQ("struct foo {\n" 11403 "private:\n" 11404 "\n\n\n" 11405 "protected:\n" 11406 "};\n", 11407 format("struct foo {\n" 11408 "private:\n" 11409 "\n\n\n" 11410 "protected:\n" 11411 "};\n", 11412 Style)); 11413 Style.MaxEmptyLinesToKeep = 3u; 11414 EXPECT_EQ("struct foo {\n" 11415 "private:\n" 11416 "\n\n\n" 11417 "protected:\n" 11418 "};\n", 11419 format("struct foo {\n" 11420 "private:\n" 11421 "\n\n\n" 11422 "protected:\n" 11423 "};\n", 11424 Style)); 11425 Style.MaxEmptyLinesToKeep = 1u; 11426 EXPECT_EQ("struct foo {\n" 11427 "private:\n" 11428 "\n\n\n" 11429 "protected:\n" 11430 "};\n", 11431 format("struct foo {\n" 11432 "private:\n" 11433 "\n\n\n" 11434 "protected:\n" 11435 "};\n", 11436 Style)); // Based on new lines in original document and not 11437 // on the setting. 11438 11439 Style.MaxEmptyLinesToKeep = 10u; 11440 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11441 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11442 // Newlines are kept if they are greater than zero, 11443 // test::messUp removes all new lines which changes the logic 11444 EXPECT_EQ("struct foo {\n" 11445 "private:\n" 11446 "\n\n\n" 11447 "protected:\n" 11448 "};\n", 11449 format("struct foo {\n" 11450 "private:\n" 11451 "\n\n\n" 11452 "protected:\n" 11453 "};\n", 11454 Style)); 11455 11456 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11457 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11458 // test::messUp removes all new lines which changes the logic 11459 EXPECT_EQ("struct foo {\n" 11460 "private:\n" 11461 "\n\n\n" 11462 "protected:\n" 11463 "};\n", 11464 format("struct foo {\n" 11465 "private:\n" 11466 "\n\n\n" 11467 "protected:\n" 11468 "};\n", 11469 Style)); 11470 11471 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11472 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11473 EXPECT_EQ("struct foo {\n" 11474 "private:\n" 11475 "\n\n\n" 11476 "protected:\n" 11477 "};\n", 11478 format("struct foo {\n" 11479 "private:\n" 11480 "\n\n\n" 11481 "protected:\n" 11482 "};\n", 11483 Style)); // test::messUp removes all new lines which changes 11484 // the logic. 11485 11486 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11487 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11488 verifyFormat("struct foo {\n" 11489 "private:\n" 11490 "protected:\n" 11491 "};\n", 11492 "struct foo {\n" 11493 "private:\n" 11494 "\n\n\n" 11495 "protected:\n" 11496 "};\n", 11497 Style); 11498 11499 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11500 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11501 EXPECT_EQ("struct foo {\n" 11502 "private:\n" 11503 "\n\n\n" 11504 "protected:\n" 11505 "};\n", 11506 format("struct foo {\n" 11507 "private:\n" 11508 "\n\n\n" 11509 "protected:\n" 11510 "};\n", 11511 Style)); // test::messUp removes all new lines which changes 11512 // the logic. 11513 11514 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11515 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11516 verifyFormat("struct foo {\n" 11517 "private:\n" 11518 "protected:\n" 11519 "};\n", 11520 "struct foo {\n" 11521 "private:\n" 11522 "\n\n\n" 11523 "protected:\n" 11524 "};\n", 11525 Style); 11526 11527 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11528 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11529 verifyFormat("struct foo {\n" 11530 "private:\n" 11531 "protected:\n" 11532 "};\n", 11533 "struct foo {\n" 11534 "private:\n" 11535 "\n\n\n" 11536 "protected:\n" 11537 "};\n", 11538 Style); 11539 11540 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11541 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11542 verifyFormat("struct foo {\n" 11543 "private:\n" 11544 "protected:\n" 11545 "};\n", 11546 "struct foo {\n" 11547 "private:\n" 11548 "\n\n\n" 11549 "protected:\n" 11550 "};\n", 11551 Style); 11552 11553 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11554 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11555 verifyFormat("struct foo {\n" 11556 "private:\n" 11557 "protected:\n" 11558 "};\n", 11559 "struct foo {\n" 11560 "private:\n" 11561 "\n\n\n" 11562 "protected:\n" 11563 "};\n", 11564 Style); 11565 } 11566 11567 TEST_F(FormatTest, FormatsArrays) { 11568 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n" 11569 " [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;"); 11570 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n" 11571 " [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;"); 11572 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n" 11573 " aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}"); 11574 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11575 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;"); 11576 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11577 " [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;"); 11578 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11579 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n" 11580 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;"); 11581 verifyFormat( 11582 "llvm::outs() << \"aaaaaaaaaaaa: \"\n" 11583 " << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n" 11584 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];"); 11585 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n" 11586 " .aaaaaaaaaaaaaaaaaaaaaa();"); 11587 11588 verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n" 11589 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];"); 11590 verifyFormat( 11591 "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n" 11592 " .aaaaaaa[0]\n" 11593 " .aaaaaaaaaaaaaaaaaaaaaa();"); 11594 verifyFormat("a[::b::c];"); 11595 11596 verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10)); 11597 11598 FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0); 11599 verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit); 11600 } 11601 11602 TEST_F(FormatTest, LineStartsWithSpecialCharacter) { 11603 verifyFormat("(a)->b();"); 11604 verifyFormat("--a;"); 11605 } 11606 11607 TEST_F(FormatTest, HandlesIncludeDirectives) { 11608 verifyFormat("#include <string>\n" 11609 "#include <a/b/c.h>\n" 11610 "#include \"a/b/string\"\n" 11611 "#include \"string.h\"\n" 11612 "#include \"string.h\"\n" 11613 "#include <a-a>\n" 11614 "#include < path with space >\n" 11615 "#include_next <test.h>" 11616 "#include \"abc.h\" // this is included for ABC\n" 11617 "#include \"some long include\" // with a comment\n" 11618 "#include \"some very long include path\"\n" 11619 "#include <some/very/long/include/path>\n", 11620 getLLVMStyleWithColumns(35)); 11621 EXPECT_EQ("#include \"a.h\"", format("#include \"a.h\"")); 11622 EXPECT_EQ("#include <a>", format("#include<a>")); 11623 11624 verifyFormat("#import <string>"); 11625 verifyFormat("#import <a/b/c.h>"); 11626 verifyFormat("#import \"a/b/string\""); 11627 verifyFormat("#import \"string.h\""); 11628 verifyFormat("#import \"string.h\""); 11629 verifyFormat("#if __has_include(<strstream>)\n" 11630 "#include <strstream>\n" 11631 "#endif"); 11632 11633 verifyFormat("#define MY_IMPORT <a/b>"); 11634 11635 verifyFormat("#if __has_include(<a/b>)"); 11636 verifyFormat("#if __has_include_next(<a/b>)"); 11637 verifyFormat("#define F __has_include(<a/b>)"); 11638 verifyFormat("#define F __has_include_next(<a/b>)"); 11639 11640 // Protocol buffer definition or missing "#". 11641 verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";", 11642 getLLVMStyleWithColumns(30)); 11643 11644 FormatStyle Style = getLLVMStyle(); 11645 Style.AlwaysBreakBeforeMultilineStrings = true; 11646 Style.ColumnLimit = 0; 11647 verifyFormat("#import \"abc.h\"", Style); 11648 11649 // But 'import' might also be a regular C++ namespace. 11650 verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 11651 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 11652 } 11653 11654 //===----------------------------------------------------------------------===// 11655 // Error recovery tests. 11656 //===----------------------------------------------------------------------===// 11657 11658 TEST_F(FormatTest, IncompleteParameterLists) { 11659 FormatStyle NoBinPacking = getLLVMStyle(); 11660 NoBinPacking.BinPackParameters = false; 11661 verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n" 11662 " double *min_x,\n" 11663 " double *max_x,\n" 11664 " double *min_y,\n" 11665 " double *max_y,\n" 11666 " double *min_z,\n" 11667 " double *max_z, ) {}", 11668 NoBinPacking); 11669 } 11670 11671 TEST_F(FormatTest, IncorrectCodeTrailingStuff) { 11672 verifyFormat("void f() { return; }\n42"); 11673 verifyFormat("void f() {\n" 11674 " if (0)\n" 11675 " return;\n" 11676 "}\n" 11677 "42"); 11678 verifyFormat("void f() { return }\n42"); 11679 verifyFormat("void f() {\n" 11680 " if (0)\n" 11681 " return\n" 11682 "}\n" 11683 "42"); 11684 } 11685 11686 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) { 11687 EXPECT_EQ("void f() { return }", format("void f ( ) { return }")); 11688 EXPECT_EQ("void f() {\n" 11689 " if (a)\n" 11690 " return\n" 11691 "}", 11692 format("void f ( ) { if ( a ) return }")); 11693 EXPECT_EQ("namespace N {\n" 11694 "void f()\n" 11695 "}", 11696 format("namespace N { void f() }")); 11697 EXPECT_EQ("namespace N {\n" 11698 "void f() {}\n" 11699 "void g()\n" 11700 "} // namespace N", 11701 format("namespace N { void f( ) { } void g( ) }")); 11702 } 11703 11704 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) { 11705 verifyFormat("int aaaaaaaa =\n" 11706 " // Overlylongcomment\n" 11707 " b;", 11708 getLLVMStyleWithColumns(20)); 11709 verifyFormat("function(\n" 11710 " ShortArgument,\n" 11711 " LoooooooooooongArgument);\n", 11712 getLLVMStyleWithColumns(20)); 11713 } 11714 11715 TEST_F(FormatTest, IncorrectAccessSpecifier) { 11716 verifyFormat("public:"); 11717 verifyFormat("class A {\n" 11718 "public\n" 11719 " void f() {}\n" 11720 "};"); 11721 verifyFormat("public\n" 11722 "int qwerty;"); 11723 verifyFormat("public\n" 11724 "B {}"); 11725 verifyFormat("public\n" 11726 "{}"); 11727 verifyFormat("public\n" 11728 "B { int x; }"); 11729 } 11730 11731 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) { 11732 verifyFormat("{"); 11733 verifyFormat("#})"); 11734 verifyNoCrash("(/**/[:!] ?[)."); 11735 } 11736 11737 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) { 11738 // Found by oss-fuzz: 11739 // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212 11740 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp); 11741 Style.ColumnLimit = 60; 11742 verifyNoCrash( 11743 "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20" 11744 "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20" 11745 "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a", 11746 Style); 11747 } 11748 11749 TEST_F(FormatTest, IncorrectCodeDoNoWhile) { 11750 verifyFormat("do {\n}"); 11751 verifyFormat("do {\n}\n" 11752 "f();"); 11753 verifyFormat("do {\n}\n" 11754 "wheeee(fun);"); 11755 verifyFormat("do {\n" 11756 " f();\n" 11757 "}"); 11758 } 11759 11760 TEST_F(FormatTest, IncorrectCodeMissingParens) { 11761 verifyFormat("if {\n foo;\n foo();\n}"); 11762 verifyFormat("switch {\n foo;\n foo();\n}"); 11763 verifyIncompleteFormat("for {\n foo;\n foo();\n}"); 11764 verifyFormat("while {\n foo;\n foo();\n}"); 11765 verifyFormat("do {\n foo;\n foo();\n} while;"); 11766 } 11767 11768 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) { 11769 verifyIncompleteFormat("namespace {\n" 11770 "class Foo { Foo (\n" 11771 "};\n" 11772 "} // namespace"); 11773 } 11774 11775 TEST_F(FormatTest, IncorrectCodeErrorDetection) { 11776 EXPECT_EQ("{\n {}\n", format("{\n{\n}\n")); 11777 EXPECT_EQ("{\n {}\n", format("{\n {\n}\n")); 11778 EXPECT_EQ("{\n {}\n", format("{\n {\n }\n")); 11779 EXPECT_EQ("{\n {}\n}\n}\n", format("{\n {\n }\n }\n}\n")); 11780 11781 EXPECT_EQ("{\n" 11782 " {\n" 11783 " breakme(\n" 11784 " qwe);\n" 11785 " }\n", 11786 format("{\n" 11787 " {\n" 11788 " breakme(qwe);\n" 11789 "}\n", 11790 getLLVMStyleWithColumns(10))); 11791 } 11792 11793 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) { 11794 verifyFormat("int x = {\n" 11795 " avariable,\n" 11796 " b(alongervariable)};", 11797 getLLVMStyleWithColumns(25)); 11798 } 11799 11800 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) { 11801 verifyFormat("return (a)(b){1, 2, 3};"); 11802 } 11803 11804 TEST_F(FormatTest, LayoutCxx11BraceInitializers) { 11805 verifyFormat("vector<int> x{1, 2, 3, 4};"); 11806 verifyFormat("vector<int> x{\n" 11807 " 1,\n" 11808 " 2,\n" 11809 " 3,\n" 11810 " 4,\n" 11811 "};"); 11812 verifyFormat("vector<T> x{{}, {}, {}, {}};"); 11813 verifyFormat("f({1, 2});"); 11814 verifyFormat("auto v = Foo{-1};"); 11815 verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});"); 11816 verifyFormat("Class::Class : member{1, 2, 3} {}"); 11817 verifyFormat("new vector<int>{1, 2, 3};"); 11818 verifyFormat("new int[3]{1, 2, 3};"); 11819 verifyFormat("new int{1};"); 11820 verifyFormat("return {arg1, arg2};"); 11821 verifyFormat("return {arg1, SomeType{parameter}};"); 11822 verifyFormat("int count = set<int>{f(), g(), h()}.size();"); 11823 verifyFormat("new T{arg1, arg2};"); 11824 verifyFormat("f(MyMap[{composite, key}]);"); 11825 verifyFormat("class Class {\n" 11826 " T member = {arg1, arg2};\n" 11827 "};"); 11828 verifyFormat("vector<int> foo = {::SomeGlobalFunction()};"); 11829 verifyFormat("const struct A a = {.a = 1, .b = 2};"); 11830 verifyFormat("const struct A a = {[0] = 1, [1] = 2};"); 11831 verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");"); 11832 verifyFormat("int a = std::is_integral<int>{} + 0;"); 11833 11834 verifyFormat("int foo(int i) { return fo1{}(i); }"); 11835 verifyFormat("int foo(int i) { return fo1{}(i); }"); 11836 verifyFormat("auto i = decltype(x){};"); 11837 verifyFormat("auto i = typeof(x){};"); 11838 verifyFormat("auto i = _Atomic(x){};"); 11839 verifyFormat("std::vector<int> v = {1, 0 /* comment */};"); 11840 verifyFormat("Node n{1, Node{1000}, //\n" 11841 " 2};"); 11842 verifyFormat("Aaaa aaaaaaa{\n" 11843 " {\n" 11844 " aaaa,\n" 11845 " },\n" 11846 "};"); 11847 verifyFormat("class C : public D {\n" 11848 " SomeClass SC{2};\n" 11849 "};"); 11850 verifyFormat("class C : public A {\n" 11851 " class D : public B {\n" 11852 " void f() { int i{2}; }\n" 11853 " };\n" 11854 "};"); 11855 verifyFormat("#define A {a, a},"); 11856 // Don't confuse braced list initializers with compound statements. 11857 verifyFormat( 11858 "class A {\n" 11859 " A() : a{} {}\n" 11860 " A(int b) : b(b) {}\n" 11861 " A(int a, int b) : a(a), bs{{bs...}} { f(); }\n" 11862 " int a, b;\n" 11863 " explicit Expr(const Scalar<Result> &x) : u{Constant<Result>{x}} {}\n" 11864 " explicit Expr(Scalar<Result> &&x) : u{Constant<Result>{std::move(x)}} " 11865 "{}\n" 11866 "};"); 11867 11868 // Avoid breaking between equal sign and opening brace 11869 FormatStyle AvoidBreakingFirstArgument = getLLVMStyle(); 11870 AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200; 11871 verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n" 11872 " {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n" 11873 " {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n" 11874 " {\"ccccccccccccccccccccc\", 2}};", 11875 AvoidBreakingFirstArgument); 11876 11877 // Binpacking only if there is no trailing comma 11878 verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n" 11879 " cccccccccc, dddddddddd};", 11880 getLLVMStyleWithColumns(50)); 11881 verifyFormat("const Aaaaaa aaaaa = {\n" 11882 " aaaaaaaaaaa,\n" 11883 " bbbbbbbbbbb,\n" 11884 " ccccccccccc,\n" 11885 " ddddddddddd,\n" 11886 "};", 11887 getLLVMStyleWithColumns(50)); 11888 11889 // Cases where distinguising braced lists and blocks is hard. 11890 verifyFormat("vector<int> v{12} GUARDED_BY(mutex);"); 11891 verifyFormat("void f() {\n" 11892 " return; // comment\n" 11893 "}\n" 11894 "SomeType t;"); 11895 verifyFormat("void f() {\n" 11896 " if (a) {\n" 11897 " f();\n" 11898 " }\n" 11899 "}\n" 11900 "SomeType t;"); 11901 11902 // In combination with BinPackArguments = false. 11903 FormatStyle NoBinPacking = getLLVMStyle(); 11904 NoBinPacking.BinPackArguments = false; 11905 verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n" 11906 " bbbbb,\n" 11907 " ccccc,\n" 11908 " ddddd,\n" 11909 " eeeee,\n" 11910 " ffffff,\n" 11911 " ggggg,\n" 11912 " hhhhhh,\n" 11913 " iiiiii,\n" 11914 " jjjjjj,\n" 11915 " kkkkkk};", 11916 NoBinPacking); 11917 verifyFormat("const Aaaaaa aaaaa = {\n" 11918 " aaaaa,\n" 11919 " bbbbb,\n" 11920 " ccccc,\n" 11921 " ddddd,\n" 11922 " eeeee,\n" 11923 " ffffff,\n" 11924 " ggggg,\n" 11925 " hhhhhh,\n" 11926 " iiiiii,\n" 11927 " jjjjjj,\n" 11928 " kkkkkk,\n" 11929 "};", 11930 NoBinPacking); 11931 verifyFormat( 11932 "const Aaaaaa aaaaa = {\n" 11933 " aaaaa, bbbbb, ccccc, ddddd, eeeee, ffffff, ggggg, hhhhhh,\n" 11934 " iiiiii, jjjjjj, kkkkkk, aaaaa, bbbbb, ccccc, ddddd, eeeee,\n" 11935 " ffffff, ggggg, hhhhhh, iiiiii, jjjjjj, kkkkkk,\n" 11936 "};", 11937 NoBinPacking); 11938 11939 NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 11940 EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n" 11941 " CDDDP83848_BMCR_REGISTER,\n" 11942 " CDDDP83848_BMSR_REGISTER,\n" 11943 " CDDDP83848_RBR_REGISTER};", 11944 format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n" 11945 " CDDDP83848_BMSR_REGISTER,\n" 11946 " CDDDP83848_RBR_REGISTER};", 11947 NoBinPacking)); 11948 11949 // FIXME: The alignment of these trailing comments might be bad. Then again, 11950 // this might be utterly useless in real code. 11951 verifyFormat("Constructor::Constructor()\n" 11952 " : some_value{ //\n" 11953 " aaaaaaa, //\n" 11954 " bbbbbbb} {}"); 11955 11956 // In braced lists, the first comment is always assumed to belong to the 11957 // first element. Thus, it can be moved to the next or previous line as 11958 // appropriate. 11959 EXPECT_EQ("function({// First element:\n" 11960 " 1,\n" 11961 " // Second element:\n" 11962 " 2});", 11963 format("function({\n" 11964 " // First element:\n" 11965 " 1,\n" 11966 " // Second element:\n" 11967 " 2});")); 11968 EXPECT_EQ("std::vector<int> MyNumbers{\n" 11969 " // First element:\n" 11970 " 1,\n" 11971 " // Second element:\n" 11972 " 2};", 11973 format("std::vector<int> MyNumbers{// First element:\n" 11974 " 1,\n" 11975 " // Second element:\n" 11976 " 2};", 11977 getLLVMStyleWithColumns(30))); 11978 // A trailing comma should still lead to an enforced line break and no 11979 // binpacking. 11980 EXPECT_EQ("vector<int> SomeVector = {\n" 11981 " // aaa\n" 11982 " 1,\n" 11983 " 2,\n" 11984 "};", 11985 format("vector<int> SomeVector = { // aaa\n" 11986 " 1, 2, };")); 11987 11988 // C++11 brace initializer list l-braces should not be treated any differently 11989 // when breaking before lambda bodies is enabled 11990 FormatStyle BreakBeforeLambdaBody = getLLVMStyle(); 11991 BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 11992 BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 11993 BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true; 11994 verifyFormat( 11995 "std::runtime_error{\n" 11996 " \"Long string which will force a break onto the next line...\"};", 11997 BreakBeforeLambdaBody); 11998 11999 FormatStyle ExtraSpaces = getLLVMStyle(); 12000 ExtraSpaces.Cpp11BracedListStyle = false; 12001 ExtraSpaces.ColumnLimit = 75; 12002 verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces); 12003 verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces); 12004 verifyFormat("f({ 1, 2 });", ExtraSpaces); 12005 verifyFormat("auto v = Foo{ 1 };", ExtraSpaces); 12006 verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces); 12007 verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces); 12008 verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces); 12009 verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces); 12010 verifyFormat("return { arg1, arg2 };", ExtraSpaces); 12011 verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces); 12012 verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces); 12013 verifyFormat("new T{ arg1, arg2 };", ExtraSpaces); 12014 verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces); 12015 verifyFormat("class Class {\n" 12016 " T member = { arg1, arg2 };\n" 12017 "};", 12018 ExtraSpaces); 12019 verifyFormat( 12020 "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12021 " aaaaaaaaaaaaaaaaaaaa, aaaaa }\n" 12022 " : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 12023 " bbbbbbbbbbbbbbbbbbbb, bbbbb };", 12024 ExtraSpaces); 12025 verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces); 12026 verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });", 12027 ExtraSpaces); 12028 verifyFormat( 12029 "someFunction(OtherParam,\n" 12030 " BracedList{ // comment 1 (Forcing interesting break)\n" 12031 " param1, param2,\n" 12032 " // comment 2\n" 12033 " param3, param4 });", 12034 ExtraSpaces); 12035 verifyFormat( 12036 "std::this_thread::sleep_for(\n" 12037 " std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);", 12038 ExtraSpaces); 12039 verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n" 12040 " aaaaaaa,\n" 12041 " aaaaaaaaaa,\n" 12042 " aaaaa,\n" 12043 " aaaaaaaaaaaaaaa,\n" 12044 " aaa,\n" 12045 " aaaaaaaaaa,\n" 12046 " a,\n" 12047 " aaaaaaaaaaaaaaaaaaaaa,\n" 12048 " aaaaaaaaaaaa,\n" 12049 " aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n" 12050 " aaaaaaa,\n" 12051 " a};"); 12052 verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces); 12053 verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces); 12054 verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces); 12055 12056 // Avoid breaking between initializer/equal sign and opening brace 12057 ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200; 12058 verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n" 12059 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n" 12060 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n" 12061 " { \"ccccccccccccccccccccc\", 2 }\n" 12062 "};", 12063 ExtraSpaces); 12064 verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n" 12065 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n" 12066 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n" 12067 " { \"ccccccccccccccccccccc\", 2 }\n" 12068 "};", 12069 ExtraSpaces); 12070 12071 FormatStyle SpaceBeforeBrace = getLLVMStyle(); 12072 SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true; 12073 verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace); 12074 verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace); 12075 12076 FormatStyle SpaceBetweenBraces = getLLVMStyle(); 12077 SpaceBetweenBraces.SpacesInAngles = FormatStyle::SIAS_Always; 12078 SpaceBetweenBraces.SpacesInParentheses = true; 12079 SpaceBetweenBraces.SpacesInSquareBrackets = true; 12080 verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces); 12081 verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces); 12082 verifyFormat("vector< int > x{ // comment 1\n" 12083 " 1, 2, 3, 4 };", 12084 SpaceBetweenBraces); 12085 SpaceBetweenBraces.ColumnLimit = 20; 12086 EXPECT_EQ("vector< int > x{\n" 12087 " 1, 2, 3, 4 };", 12088 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces)); 12089 SpaceBetweenBraces.ColumnLimit = 24; 12090 EXPECT_EQ("vector< int > x{ 1, 2,\n" 12091 " 3, 4 };", 12092 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces)); 12093 EXPECT_EQ("vector< int > x{\n" 12094 " 1,\n" 12095 " 2,\n" 12096 " 3,\n" 12097 " 4,\n" 12098 "};", 12099 format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces)); 12100 verifyFormat("vector< int > x{};", SpaceBetweenBraces); 12101 SpaceBetweenBraces.SpaceInEmptyParentheses = true; 12102 verifyFormat("vector< int > x{ };", SpaceBetweenBraces); 12103 } 12104 12105 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) { 12106 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12107 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12108 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12109 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12110 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12111 " 1, 22, 333, 4444, 55555, 666666, 7777777};"); 12112 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n" 12113 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12114 " 1, 22, 333, 4444, 55555, //\n" 12115 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12116 " 1, 22, 333, 4444, 55555, 666666, 7777777};"); 12117 verifyFormat( 12118 "vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12119 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12120 " 1, 22, 333, 4444, 55555, 666666, // comment\n" 12121 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12122 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12123 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12124 " 7777777};"); 12125 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12126 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12127 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12128 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12129 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12130 " // Separating comment.\n" 12131 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12132 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12133 " // Leading comment\n" 12134 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12135 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12136 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12137 " 1, 1, 1, 1};", 12138 getLLVMStyleWithColumns(39)); 12139 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12140 " 1, 1, 1, 1};", 12141 getLLVMStyleWithColumns(38)); 12142 verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n" 12143 " 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};", 12144 getLLVMStyleWithColumns(43)); 12145 verifyFormat( 12146 "static unsigned SomeValues[10][3] = {\n" 12147 " {1, 4, 0}, {4, 9, 0}, {4, 5, 9}, {8, 5, 4}, {1, 8, 4},\n" 12148 " {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};"); 12149 verifyFormat("static auto fields = new vector<string>{\n" 12150 " \"aaaaaaaaaaaaa\",\n" 12151 " \"aaaaaaaaaaaaa\",\n" 12152 " \"aaaaaaaaaaaa\",\n" 12153 " \"aaaaaaaaaaaaaa\",\n" 12154 " \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n" 12155 " \"aaaaaaaaaaaa\",\n" 12156 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n" 12157 "};"); 12158 verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};"); 12159 verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n" 12160 " 2, bbbbbbbbbbbbbbbbbbbbbb,\n" 12161 " 3, cccccccccccccccccccccc};", 12162 getLLVMStyleWithColumns(60)); 12163 12164 // Trailing commas. 12165 verifyFormat("vector<int> x = {\n" 12166 " 1, 1, 1, 1, 1, 1, 1, 1,\n" 12167 "};", 12168 getLLVMStyleWithColumns(39)); 12169 verifyFormat("vector<int> x = {\n" 12170 " 1, 1, 1, 1, 1, 1, 1, 1, //\n" 12171 "};", 12172 getLLVMStyleWithColumns(39)); 12173 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12174 " 1, 1, 1, 1,\n" 12175 " /**/ /**/};", 12176 getLLVMStyleWithColumns(39)); 12177 12178 // Trailing comment in the first line. 12179 verifyFormat("vector<int> iiiiiiiiiiiiiii = { //\n" 12180 " 1111111111, 2222222222, 33333333333, 4444444444, //\n" 12181 " 111111111, 222222222, 3333333333, 444444444, //\n" 12182 " 11111111, 22222222, 333333333, 44444444};"); 12183 // Trailing comment in the last line. 12184 verifyFormat("int aaaaa[] = {\n" 12185 " 1, 2, 3, // comment\n" 12186 " 4, 5, 6 // comment\n" 12187 "};"); 12188 12189 // With nested lists, we should either format one item per line or all nested 12190 // lists one on line. 12191 // FIXME: For some nested lists, we can do better. 12192 verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n" 12193 " {aaaaaaaaaaaaaaaaaaa},\n" 12194 " {aaaaaaaaaaaaaaaaaaaaa},\n" 12195 " {aaaaaaaaaaaaaaaaa}};", 12196 getLLVMStyleWithColumns(60)); 12197 verifyFormat( 12198 "SomeStruct my_struct_array = {\n" 12199 " {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n" 12200 " aaaaaaaaaaaaa, aaaaaaa, aaa},\n" 12201 " {aaa, aaa},\n" 12202 " {aaa, aaa},\n" 12203 " {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n" 12204 " {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n" 12205 " aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};"); 12206 12207 // No column layout should be used here. 12208 verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n" 12209 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};"); 12210 12211 verifyNoCrash("a<,"); 12212 12213 // No braced initializer here. 12214 verifyFormat("void f() {\n" 12215 " struct Dummy {};\n" 12216 " f(v);\n" 12217 "}"); 12218 12219 // Long lists should be formatted in columns even if they are nested. 12220 verifyFormat( 12221 "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12222 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12223 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12224 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12225 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12226 " 1, 22, 333, 4444, 55555, 666666, 7777777});"); 12227 12228 // Allow "single-column" layout even if that violates the column limit. There 12229 // isn't going to be a better way. 12230 verifyFormat("std::vector<int> a = {\n" 12231 " aaaaaaaa,\n" 12232 " aaaaaaaa,\n" 12233 " aaaaaaaa,\n" 12234 " aaaaaaaa,\n" 12235 " aaaaaaaaaa,\n" 12236 " aaaaaaaa,\n" 12237 " aaaaaaaaaaaaaaaaaaaaaaaaaaa};", 12238 getLLVMStyleWithColumns(30)); 12239 verifyFormat("vector<int> aaaa = {\n" 12240 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12241 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12242 " aaaaaa.aaaaaaa,\n" 12243 " aaaaaa.aaaaaaa,\n" 12244 " aaaaaa.aaaaaaa,\n" 12245 " aaaaaa.aaaaaaa,\n" 12246 "};"); 12247 12248 // Don't create hanging lists. 12249 verifyFormat("someFunction(Param, {List1, List2,\n" 12250 " List3});", 12251 getLLVMStyleWithColumns(35)); 12252 verifyFormat("someFunction(Param, Param,\n" 12253 " {List1, List2,\n" 12254 " List3});", 12255 getLLVMStyleWithColumns(35)); 12256 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n" 12257 " aaaaaaaaaaaaaaaaaaaaaaa);"); 12258 } 12259 12260 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) { 12261 FormatStyle DoNotMerge = getLLVMStyle(); 12262 DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12263 12264 verifyFormat("void f() { return 42; }"); 12265 verifyFormat("void f() {\n" 12266 " return 42;\n" 12267 "}", 12268 DoNotMerge); 12269 verifyFormat("void f() {\n" 12270 " // Comment\n" 12271 "}"); 12272 verifyFormat("{\n" 12273 "#error {\n" 12274 " int a;\n" 12275 "}"); 12276 verifyFormat("{\n" 12277 " int a;\n" 12278 "#error {\n" 12279 "}"); 12280 verifyFormat("void f() {} // comment"); 12281 verifyFormat("void f() { int a; } // comment"); 12282 verifyFormat("void f() {\n" 12283 "} // comment", 12284 DoNotMerge); 12285 verifyFormat("void f() {\n" 12286 " int a;\n" 12287 "} // comment", 12288 DoNotMerge); 12289 verifyFormat("void f() {\n" 12290 "} // comment", 12291 getLLVMStyleWithColumns(15)); 12292 12293 verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23)); 12294 verifyFormat("void f() {\n return 42;\n}", getLLVMStyleWithColumns(22)); 12295 12296 verifyFormat("void f() {}", getLLVMStyleWithColumns(11)); 12297 verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10)); 12298 verifyFormat("class C {\n" 12299 " C()\n" 12300 " : iiiiiiii(nullptr),\n" 12301 " kkkkkkk(nullptr),\n" 12302 " mmmmmmm(nullptr),\n" 12303 " nnnnnnn(nullptr) {}\n" 12304 "};", 12305 getGoogleStyle()); 12306 12307 FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0); 12308 EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit)); 12309 EXPECT_EQ("class C {\n" 12310 " A() : b(0) {}\n" 12311 "};", 12312 format("class C{A():b(0){}};", NoColumnLimit)); 12313 EXPECT_EQ("A()\n" 12314 " : b(0) {\n" 12315 "}", 12316 format("A()\n:b(0)\n{\n}", NoColumnLimit)); 12317 12318 FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit; 12319 DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine = 12320 FormatStyle::SFS_None; 12321 EXPECT_EQ("A()\n" 12322 " : b(0) {\n" 12323 "}", 12324 format("A():b(0){}", DoNotMergeNoColumnLimit)); 12325 EXPECT_EQ("A()\n" 12326 " : b(0) {\n" 12327 "}", 12328 format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit)); 12329 12330 verifyFormat("#define A \\\n" 12331 " void f() { \\\n" 12332 " int i; \\\n" 12333 " }", 12334 getLLVMStyleWithColumns(20)); 12335 verifyFormat("#define A \\\n" 12336 " void f() { int i; }", 12337 getLLVMStyleWithColumns(21)); 12338 verifyFormat("#define A \\\n" 12339 " void f() { \\\n" 12340 " int i; \\\n" 12341 " } \\\n" 12342 " int j;", 12343 getLLVMStyleWithColumns(22)); 12344 verifyFormat("#define A \\\n" 12345 " void f() { int i; } \\\n" 12346 " int j;", 12347 getLLVMStyleWithColumns(23)); 12348 } 12349 12350 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) { 12351 FormatStyle MergeEmptyOnly = getLLVMStyle(); 12352 MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 12353 verifyFormat("class C {\n" 12354 " int f() {}\n" 12355 "};", 12356 MergeEmptyOnly); 12357 verifyFormat("class C {\n" 12358 " int f() {\n" 12359 " return 42;\n" 12360 " }\n" 12361 "};", 12362 MergeEmptyOnly); 12363 verifyFormat("int f() {}", MergeEmptyOnly); 12364 verifyFormat("int f() {\n" 12365 " return 42;\n" 12366 "}", 12367 MergeEmptyOnly); 12368 12369 // Also verify behavior when BraceWrapping.AfterFunction = true 12370 MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12371 MergeEmptyOnly.BraceWrapping.AfterFunction = true; 12372 verifyFormat("int f() {}", MergeEmptyOnly); 12373 verifyFormat("class C {\n" 12374 " int f() {}\n" 12375 "};", 12376 MergeEmptyOnly); 12377 } 12378 12379 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) { 12380 FormatStyle MergeInlineOnly = getLLVMStyle(); 12381 MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 12382 verifyFormat("class C {\n" 12383 " int f() { return 42; }\n" 12384 "};", 12385 MergeInlineOnly); 12386 verifyFormat("int f() {\n" 12387 " return 42;\n" 12388 "}", 12389 MergeInlineOnly); 12390 12391 // SFS_Inline implies SFS_Empty 12392 verifyFormat("class C {\n" 12393 " int f() {}\n" 12394 "};", 12395 MergeInlineOnly); 12396 verifyFormat("int f() {}", MergeInlineOnly); 12397 12398 // Also verify behavior when BraceWrapping.AfterFunction = true 12399 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12400 MergeInlineOnly.BraceWrapping.AfterFunction = true; 12401 verifyFormat("class C {\n" 12402 " int f() { return 42; }\n" 12403 "};", 12404 MergeInlineOnly); 12405 verifyFormat("int f()\n" 12406 "{\n" 12407 " return 42;\n" 12408 "}", 12409 MergeInlineOnly); 12410 12411 // SFS_Inline implies SFS_Empty 12412 verifyFormat("int f() {}", MergeInlineOnly); 12413 verifyFormat("class C {\n" 12414 " int f() {}\n" 12415 "};", 12416 MergeInlineOnly); 12417 12418 MergeInlineOnly.BraceWrapping.AfterClass = true; 12419 MergeInlineOnly.BraceWrapping.AfterStruct = true; 12420 verifyFormat("class C\n" 12421 "{\n" 12422 " int f() { return 42; }\n" 12423 "};", 12424 MergeInlineOnly); 12425 verifyFormat("struct C\n" 12426 "{\n" 12427 " int f() { return 42; }\n" 12428 "};", 12429 MergeInlineOnly); 12430 verifyFormat("int f()\n" 12431 "{\n" 12432 " return 42;\n" 12433 "}", 12434 MergeInlineOnly); 12435 verifyFormat("int f() {}", MergeInlineOnly); 12436 verifyFormat("class C\n" 12437 "{\n" 12438 " int f() { return 42; }\n" 12439 "};", 12440 MergeInlineOnly); 12441 verifyFormat("struct C\n" 12442 "{\n" 12443 " int f() { return 42; }\n" 12444 "};", 12445 MergeInlineOnly); 12446 verifyFormat("struct C\n" 12447 "// comment\n" 12448 "/* comment */\n" 12449 "// comment\n" 12450 "{\n" 12451 " int f() { return 42; }\n" 12452 "};", 12453 MergeInlineOnly); 12454 verifyFormat("/* comment */ struct C\n" 12455 "{\n" 12456 " int f() { return 42; }\n" 12457 "};", 12458 MergeInlineOnly); 12459 } 12460 12461 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) { 12462 FormatStyle MergeInlineOnly = getLLVMStyle(); 12463 MergeInlineOnly.AllowShortFunctionsOnASingleLine = 12464 FormatStyle::SFS_InlineOnly; 12465 verifyFormat("class C {\n" 12466 " int f() { return 42; }\n" 12467 "};", 12468 MergeInlineOnly); 12469 verifyFormat("int f() {\n" 12470 " return 42;\n" 12471 "}", 12472 MergeInlineOnly); 12473 12474 // SFS_InlineOnly does not imply SFS_Empty 12475 verifyFormat("class C {\n" 12476 " int f() {}\n" 12477 "};", 12478 MergeInlineOnly); 12479 verifyFormat("int f() {\n" 12480 "}", 12481 MergeInlineOnly); 12482 12483 // Also verify behavior when BraceWrapping.AfterFunction = true 12484 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12485 MergeInlineOnly.BraceWrapping.AfterFunction = true; 12486 verifyFormat("class C {\n" 12487 " int f() { return 42; }\n" 12488 "};", 12489 MergeInlineOnly); 12490 verifyFormat("int f()\n" 12491 "{\n" 12492 " return 42;\n" 12493 "}", 12494 MergeInlineOnly); 12495 12496 // SFS_InlineOnly does not imply SFS_Empty 12497 verifyFormat("int f()\n" 12498 "{\n" 12499 "}", 12500 MergeInlineOnly); 12501 verifyFormat("class C {\n" 12502 " int f() {}\n" 12503 "};", 12504 MergeInlineOnly); 12505 } 12506 12507 TEST_F(FormatTest, SplitEmptyFunction) { 12508 FormatStyle Style = getLLVMStyleWithColumns(40); 12509 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12510 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12511 Style.BraceWrapping.AfterFunction = true; 12512 Style.BraceWrapping.SplitEmptyFunction = false; 12513 12514 verifyFormat("int f()\n" 12515 "{}", 12516 Style); 12517 verifyFormat("int f()\n" 12518 "{\n" 12519 " return 42;\n" 12520 "}", 12521 Style); 12522 verifyFormat("int f()\n" 12523 "{\n" 12524 " // some comment\n" 12525 "}", 12526 Style); 12527 12528 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 12529 verifyFormat("int f() {}", Style); 12530 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12531 "{}", 12532 Style); 12533 verifyFormat("int f()\n" 12534 "{\n" 12535 " return 0;\n" 12536 "}", 12537 Style); 12538 12539 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 12540 verifyFormat("class Foo {\n" 12541 " int f() {}\n" 12542 "};\n", 12543 Style); 12544 verifyFormat("class Foo {\n" 12545 " int f() { return 0; }\n" 12546 "};\n", 12547 Style); 12548 verifyFormat("class Foo {\n" 12549 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12550 " {}\n" 12551 "};\n", 12552 Style); 12553 verifyFormat("class Foo {\n" 12554 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12555 " {\n" 12556 " return 0;\n" 12557 " }\n" 12558 "};\n", 12559 Style); 12560 12561 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 12562 verifyFormat("int f() {}", Style); 12563 verifyFormat("int f() { return 0; }", Style); 12564 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12565 "{}", 12566 Style); 12567 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12568 "{\n" 12569 " return 0;\n" 12570 "}", 12571 Style); 12572 } 12573 12574 TEST_F(FormatTest, SplitEmptyFunctionButNotRecord) { 12575 FormatStyle Style = getLLVMStyleWithColumns(40); 12576 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12577 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12578 Style.BraceWrapping.AfterFunction = true; 12579 Style.BraceWrapping.SplitEmptyFunction = true; 12580 Style.BraceWrapping.SplitEmptyRecord = false; 12581 12582 verifyFormat("class C {};", Style); 12583 verifyFormat("struct C {};", Style); 12584 verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12585 " int bbbbbbbbbbbbbbbbbbbbbbbb)\n" 12586 "{\n" 12587 "}", 12588 Style); 12589 verifyFormat("class C {\n" 12590 " C()\n" 12591 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa(),\n" 12592 " bbbbbbbbbbbbbbbbbbb()\n" 12593 " {\n" 12594 " }\n" 12595 " void\n" 12596 " m(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12597 " int bbbbbbbbbbbbbbbbbbbbbbbb)\n" 12598 " {\n" 12599 " }\n" 12600 "};", 12601 Style); 12602 } 12603 12604 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) { 12605 FormatStyle Style = getLLVMStyle(); 12606 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 12607 verifyFormat("#ifdef A\n" 12608 "int f() {}\n" 12609 "#else\n" 12610 "int g() {}\n" 12611 "#endif", 12612 Style); 12613 } 12614 12615 TEST_F(FormatTest, SplitEmptyClass) { 12616 FormatStyle Style = getLLVMStyle(); 12617 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12618 Style.BraceWrapping.AfterClass = true; 12619 Style.BraceWrapping.SplitEmptyRecord = false; 12620 12621 verifyFormat("class Foo\n" 12622 "{};", 12623 Style); 12624 verifyFormat("/* something */ class Foo\n" 12625 "{};", 12626 Style); 12627 verifyFormat("template <typename X> class Foo\n" 12628 "{};", 12629 Style); 12630 verifyFormat("class Foo\n" 12631 "{\n" 12632 " Foo();\n" 12633 "};", 12634 Style); 12635 verifyFormat("typedef class Foo\n" 12636 "{\n" 12637 "} Foo_t;", 12638 Style); 12639 12640 Style.BraceWrapping.SplitEmptyRecord = true; 12641 Style.BraceWrapping.AfterStruct = true; 12642 verifyFormat("class rep\n" 12643 "{\n" 12644 "};", 12645 Style); 12646 verifyFormat("struct rep\n" 12647 "{\n" 12648 "};", 12649 Style); 12650 verifyFormat("template <typename T> class rep\n" 12651 "{\n" 12652 "};", 12653 Style); 12654 verifyFormat("template <typename T> struct rep\n" 12655 "{\n" 12656 "};", 12657 Style); 12658 verifyFormat("class rep\n" 12659 "{\n" 12660 " int x;\n" 12661 "};", 12662 Style); 12663 verifyFormat("struct rep\n" 12664 "{\n" 12665 " int x;\n" 12666 "};", 12667 Style); 12668 verifyFormat("template <typename T> class rep\n" 12669 "{\n" 12670 " int x;\n" 12671 "};", 12672 Style); 12673 verifyFormat("template <typename T> struct rep\n" 12674 "{\n" 12675 " int x;\n" 12676 "};", 12677 Style); 12678 verifyFormat("template <typename T> class rep // Foo\n" 12679 "{\n" 12680 " int x;\n" 12681 "};", 12682 Style); 12683 verifyFormat("template <typename T> struct rep // Bar\n" 12684 "{\n" 12685 " int x;\n" 12686 "};", 12687 Style); 12688 12689 verifyFormat("template <typename T> class rep<T>\n" 12690 "{\n" 12691 " int x;\n" 12692 "};", 12693 Style); 12694 12695 verifyFormat("template <typename T> class rep<std::complex<T>>\n" 12696 "{\n" 12697 " int x;\n" 12698 "};", 12699 Style); 12700 verifyFormat("template <typename T> class rep<std::complex<T>>\n" 12701 "{\n" 12702 "};", 12703 Style); 12704 12705 verifyFormat("#include \"stdint.h\"\n" 12706 "namespace rep {}", 12707 Style); 12708 verifyFormat("#include <stdint.h>\n" 12709 "namespace rep {}", 12710 Style); 12711 verifyFormat("#include <stdint.h>\n" 12712 "namespace rep {}", 12713 "#include <stdint.h>\n" 12714 "namespace rep {\n" 12715 "\n" 12716 "\n" 12717 "}", 12718 Style); 12719 } 12720 12721 TEST_F(FormatTest, SplitEmptyStruct) { 12722 FormatStyle Style = getLLVMStyle(); 12723 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12724 Style.BraceWrapping.AfterStruct = true; 12725 Style.BraceWrapping.SplitEmptyRecord = false; 12726 12727 verifyFormat("struct Foo\n" 12728 "{};", 12729 Style); 12730 verifyFormat("/* something */ struct Foo\n" 12731 "{};", 12732 Style); 12733 verifyFormat("template <typename X> struct Foo\n" 12734 "{};", 12735 Style); 12736 verifyFormat("struct Foo\n" 12737 "{\n" 12738 " Foo();\n" 12739 "};", 12740 Style); 12741 verifyFormat("typedef struct Foo\n" 12742 "{\n" 12743 "} Foo_t;", 12744 Style); 12745 // typedef struct Bar {} Bar_t; 12746 } 12747 12748 TEST_F(FormatTest, SplitEmptyUnion) { 12749 FormatStyle Style = getLLVMStyle(); 12750 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12751 Style.BraceWrapping.AfterUnion = true; 12752 Style.BraceWrapping.SplitEmptyRecord = false; 12753 12754 verifyFormat("union Foo\n" 12755 "{};", 12756 Style); 12757 verifyFormat("/* something */ union Foo\n" 12758 "{};", 12759 Style); 12760 verifyFormat("union Foo\n" 12761 "{\n" 12762 " A,\n" 12763 "};", 12764 Style); 12765 verifyFormat("typedef union Foo\n" 12766 "{\n" 12767 "} Foo_t;", 12768 Style); 12769 } 12770 12771 TEST_F(FormatTest, SplitEmptyNamespace) { 12772 FormatStyle Style = getLLVMStyle(); 12773 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12774 Style.BraceWrapping.AfterNamespace = true; 12775 Style.BraceWrapping.SplitEmptyNamespace = false; 12776 12777 verifyFormat("namespace Foo\n" 12778 "{};", 12779 Style); 12780 verifyFormat("/* something */ namespace Foo\n" 12781 "{};", 12782 Style); 12783 verifyFormat("inline namespace Foo\n" 12784 "{};", 12785 Style); 12786 verifyFormat("/* something */ inline namespace Foo\n" 12787 "{};", 12788 Style); 12789 verifyFormat("export namespace Foo\n" 12790 "{};", 12791 Style); 12792 verifyFormat("namespace Foo\n" 12793 "{\n" 12794 "void Bar();\n" 12795 "};", 12796 Style); 12797 } 12798 12799 TEST_F(FormatTest, NeverMergeShortRecords) { 12800 FormatStyle Style = getLLVMStyle(); 12801 12802 verifyFormat("class Foo {\n" 12803 " Foo();\n" 12804 "};", 12805 Style); 12806 verifyFormat("typedef class Foo {\n" 12807 " Foo();\n" 12808 "} Foo_t;", 12809 Style); 12810 verifyFormat("struct Foo {\n" 12811 " Foo();\n" 12812 "};", 12813 Style); 12814 verifyFormat("typedef struct Foo {\n" 12815 " Foo();\n" 12816 "} Foo_t;", 12817 Style); 12818 verifyFormat("union Foo {\n" 12819 " A,\n" 12820 "};", 12821 Style); 12822 verifyFormat("typedef union Foo {\n" 12823 " A,\n" 12824 "} Foo_t;", 12825 Style); 12826 verifyFormat("namespace Foo {\n" 12827 "void Bar();\n" 12828 "};", 12829 Style); 12830 12831 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12832 Style.BraceWrapping.AfterClass = true; 12833 Style.BraceWrapping.AfterStruct = true; 12834 Style.BraceWrapping.AfterUnion = true; 12835 Style.BraceWrapping.AfterNamespace = true; 12836 verifyFormat("class Foo\n" 12837 "{\n" 12838 " Foo();\n" 12839 "};", 12840 Style); 12841 verifyFormat("typedef class Foo\n" 12842 "{\n" 12843 " Foo();\n" 12844 "} Foo_t;", 12845 Style); 12846 verifyFormat("struct Foo\n" 12847 "{\n" 12848 " Foo();\n" 12849 "};", 12850 Style); 12851 verifyFormat("typedef struct Foo\n" 12852 "{\n" 12853 " Foo();\n" 12854 "} Foo_t;", 12855 Style); 12856 verifyFormat("union Foo\n" 12857 "{\n" 12858 " A,\n" 12859 "};", 12860 Style); 12861 verifyFormat("typedef union Foo\n" 12862 "{\n" 12863 " A,\n" 12864 "} Foo_t;", 12865 Style); 12866 verifyFormat("namespace Foo\n" 12867 "{\n" 12868 "void Bar();\n" 12869 "};", 12870 Style); 12871 } 12872 12873 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) { 12874 // Elaborate type variable declarations. 12875 verifyFormat("struct foo a = {bar};\nint n;"); 12876 verifyFormat("class foo a = {bar};\nint n;"); 12877 verifyFormat("union foo a = {bar};\nint n;"); 12878 12879 // Elaborate types inside function definitions. 12880 verifyFormat("struct foo f() {}\nint n;"); 12881 verifyFormat("class foo f() {}\nint n;"); 12882 verifyFormat("union foo f() {}\nint n;"); 12883 12884 // Templates. 12885 verifyFormat("template <class X> void f() {}\nint n;"); 12886 verifyFormat("template <struct X> void f() {}\nint n;"); 12887 verifyFormat("template <union X> void f() {}\nint n;"); 12888 12889 // Actual definitions... 12890 verifyFormat("struct {\n} n;"); 12891 verifyFormat( 12892 "template <template <class T, class Y>, class Z> class X {\n} n;"); 12893 verifyFormat("union Z {\n int n;\n} x;"); 12894 verifyFormat("class MACRO Z {\n} n;"); 12895 verifyFormat("class MACRO(X) Z {\n} n;"); 12896 verifyFormat("class __attribute__(X) Z {\n} n;"); 12897 verifyFormat("class __declspec(X) Z {\n} n;"); 12898 verifyFormat("class A##B##C {\n} n;"); 12899 verifyFormat("class alignas(16) Z {\n} n;"); 12900 verifyFormat("class MACRO(X) alignas(16) Z {\n} n;"); 12901 verifyFormat("class MACROA MACRO(X) Z {\n} n;"); 12902 12903 // Redefinition from nested context: 12904 verifyFormat("class A::B::C {\n} n;"); 12905 12906 // Template definitions. 12907 verifyFormat( 12908 "template <typename F>\n" 12909 "Matcher(const Matcher<F> &Other,\n" 12910 " typename enable_if_c<is_base_of<F, T>::value &&\n" 12911 " !is_same<F, T>::value>::type * = 0)\n" 12912 " : Implementation(new ImplicitCastMatcher<F>(Other)) {}"); 12913 12914 // FIXME: This is still incorrectly handled at the formatter side. 12915 verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};"); 12916 verifyFormat("int i = SomeFunction(a<b, a> b);"); 12917 12918 // FIXME: 12919 // This now gets parsed incorrectly as class definition. 12920 // verifyFormat("class A<int> f() {\n}\nint n;"); 12921 12922 // Elaborate types where incorrectly parsing the structural element would 12923 // break the indent. 12924 verifyFormat("if (true)\n" 12925 " class X x;\n" 12926 "else\n" 12927 " f();\n"); 12928 12929 // This is simply incomplete. Formatting is not important, but must not crash. 12930 verifyFormat("class A:"); 12931 } 12932 12933 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) { 12934 EXPECT_EQ("#error Leave all white!!!!! space* alone!\n", 12935 format("#error Leave all white!!!!! space* alone!\n")); 12936 EXPECT_EQ( 12937 "#warning Leave all white!!!!! space* alone!\n", 12938 format("#warning Leave all white!!!!! space* alone!\n")); 12939 EXPECT_EQ("#error 1", format(" # error 1")); 12940 EXPECT_EQ("#warning 1", format(" # warning 1")); 12941 } 12942 12943 TEST_F(FormatTest, FormatHashIfExpressions) { 12944 verifyFormat("#if AAAA && BBBB"); 12945 verifyFormat("#if (AAAA && BBBB)"); 12946 verifyFormat("#elif (AAAA && BBBB)"); 12947 // FIXME: Come up with a better indentation for #elif. 12948 verifyFormat( 12949 "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) && \\\n" 12950 " defined(BBBBBBBB)\n" 12951 "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) && \\\n" 12952 " defined(BBBBBBBB)\n" 12953 "#endif", 12954 getLLVMStyleWithColumns(65)); 12955 } 12956 12957 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) { 12958 FormatStyle AllowsMergedIf = getGoogleStyle(); 12959 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 12960 FormatStyle::SIS_WithoutElse; 12961 verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf); 12962 verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf); 12963 verifyFormat("if (true)\n#error E\n return 42;", AllowsMergedIf); 12964 EXPECT_EQ("if (true) return 42;", 12965 format("if (true)\nreturn 42;", AllowsMergedIf)); 12966 FormatStyle ShortMergedIf = AllowsMergedIf; 12967 ShortMergedIf.ColumnLimit = 25; 12968 verifyFormat("#define A \\\n" 12969 " if (true) return 42;", 12970 ShortMergedIf); 12971 verifyFormat("#define A \\\n" 12972 " f(); \\\n" 12973 " if (true)\n" 12974 "#define B", 12975 ShortMergedIf); 12976 verifyFormat("#define A \\\n" 12977 " f(); \\\n" 12978 " if (true)\n" 12979 "g();", 12980 ShortMergedIf); 12981 verifyFormat("{\n" 12982 "#ifdef A\n" 12983 " // Comment\n" 12984 " if (true) continue;\n" 12985 "#endif\n" 12986 " // Comment\n" 12987 " if (true) continue;\n" 12988 "}", 12989 ShortMergedIf); 12990 ShortMergedIf.ColumnLimit = 33; 12991 verifyFormat("#define A \\\n" 12992 " if constexpr (true) return 42;", 12993 ShortMergedIf); 12994 verifyFormat("#define A \\\n" 12995 " if CONSTEXPR (true) return 42;", 12996 ShortMergedIf); 12997 ShortMergedIf.ColumnLimit = 29; 12998 verifyFormat("#define A \\\n" 12999 " if (aaaaaaaaaa) return 1; \\\n" 13000 " return 2;", 13001 ShortMergedIf); 13002 ShortMergedIf.ColumnLimit = 28; 13003 verifyFormat("#define A \\\n" 13004 " if (aaaaaaaaaa) \\\n" 13005 " return 1; \\\n" 13006 " return 2;", 13007 ShortMergedIf); 13008 verifyFormat("#define A \\\n" 13009 " if constexpr (aaaaaaa) \\\n" 13010 " return 1; \\\n" 13011 " return 2;", 13012 ShortMergedIf); 13013 verifyFormat("#define A \\\n" 13014 " if CONSTEXPR (aaaaaaa) \\\n" 13015 " return 1; \\\n" 13016 " return 2;", 13017 ShortMergedIf); 13018 } 13019 13020 TEST_F(FormatTest, FormatStarDependingOnContext) { 13021 verifyFormat("void f(int *a);"); 13022 verifyFormat("void f() { f(fint * b); }"); 13023 verifyFormat("class A {\n void f(int *a);\n};"); 13024 verifyFormat("class A {\n int *a;\n};"); 13025 verifyFormat("namespace a {\n" 13026 "namespace b {\n" 13027 "class A {\n" 13028 " void f() {}\n" 13029 " int *a;\n" 13030 "};\n" 13031 "} // namespace b\n" 13032 "} // namespace a"); 13033 } 13034 13035 TEST_F(FormatTest, SpecialTokensAtEndOfLine) { 13036 verifyFormat("while"); 13037 verifyFormat("operator"); 13038 } 13039 13040 TEST_F(FormatTest, SkipsDeeplyNestedLines) { 13041 // This code would be painfully slow to format if we didn't skip it. 13042 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 13043 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13044 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13045 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13046 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13047 "A(1, 1)\n" 13048 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x 13049 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13050 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13051 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13052 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13053 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13054 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13055 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13056 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13057 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n"); 13058 // Deeply nested part is untouched, rest is formatted. 13059 EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n", 13060 format(std::string("int i;\n") + Code + "int j;\n", 13061 getLLVMStyle(), SC_ExpectIncomplete)); 13062 } 13063 13064 //===----------------------------------------------------------------------===// 13065 // Objective-C tests. 13066 //===----------------------------------------------------------------------===// 13067 13068 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) { 13069 verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;"); 13070 EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;", 13071 format("-(NSUInteger)indexOfObject:(id)anObject;")); 13072 EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;")); 13073 EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;")); 13074 EXPECT_EQ("- (NSInteger)Method3:(id)anObject;", 13075 format("-(NSInteger)Method3:(id)anObject;")); 13076 EXPECT_EQ("- (NSInteger)Method4:(id)anObject;", 13077 format("-(NSInteger)Method4:(id)anObject;")); 13078 EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;", 13079 format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;")); 13080 EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;", 13081 format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;")); 13082 EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject " 13083 "forAllCells:(BOOL)flag;", 13084 format("- (void)sendAction:(SEL)aSelector to:(id)anObject " 13085 "forAllCells:(BOOL)flag;")); 13086 13087 // Very long objectiveC method declaration. 13088 verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n" 13089 " (SoooooooooooooooooooooomeType *)bbbbbbbbbb;"); 13090 verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n" 13091 " inRange:(NSRange)range\n" 13092 " outRange:(NSRange)out_range\n" 13093 " outRange1:(NSRange)out_range1\n" 13094 " outRange2:(NSRange)out_range2\n" 13095 " outRange3:(NSRange)out_range3\n" 13096 " outRange4:(NSRange)out_range4\n" 13097 " outRange5:(NSRange)out_range5\n" 13098 " outRange6:(NSRange)out_range6\n" 13099 " outRange7:(NSRange)out_range7\n" 13100 " outRange8:(NSRange)out_range8\n" 13101 " outRange9:(NSRange)out_range9;"); 13102 13103 // When the function name has to be wrapped. 13104 FormatStyle Style = getLLVMStyle(); 13105 // ObjC ignores IndentWrappedFunctionNames when wrapping methods 13106 // and always indents instead. 13107 Style.IndentWrappedFunctionNames = false; 13108 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n" 13109 " veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n" 13110 " anotherName:(NSString)bbbbbbbbbbbbbb {\n" 13111 "}", 13112 Style); 13113 Style.IndentWrappedFunctionNames = true; 13114 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n" 13115 " veryLooooooooooongName:(NSString)cccccccccccccc\n" 13116 " anotherName:(NSString)dddddddddddddd {\n" 13117 "}", 13118 Style); 13119 13120 verifyFormat("- (int)sum:(vector<int>)numbers;"); 13121 verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;"); 13122 // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC 13123 // protocol lists (but not for template classes): 13124 // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;"); 13125 13126 verifyFormat("- (int (*)())foo:(int (*)())f;"); 13127 verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;"); 13128 13129 // If there's no return type (very rare in practice!), LLVM and Google style 13130 // agree. 13131 verifyFormat("- foo;"); 13132 verifyFormat("- foo:(int)f;"); 13133 verifyGoogleFormat("- foo:(int)foo;"); 13134 } 13135 13136 TEST_F(FormatTest, BreaksStringLiterals) { 13137 EXPECT_EQ("\"some text \"\n" 13138 "\"other\";", 13139 format("\"some text other\";", getLLVMStyleWithColumns(12))); 13140 EXPECT_EQ("\"some text \"\n" 13141 "\"other\";", 13142 format("\\\n\"some text other\";", getLLVMStyleWithColumns(12))); 13143 EXPECT_EQ( 13144 "#define A \\\n" 13145 " \"some \" \\\n" 13146 " \"text \" \\\n" 13147 " \"other\";", 13148 format("#define A \"some text other\";", getLLVMStyleWithColumns(12))); 13149 EXPECT_EQ( 13150 "#define A \\\n" 13151 " \"so \" \\\n" 13152 " \"text \" \\\n" 13153 " \"other\";", 13154 format("#define A \"so text other\";", getLLVMStyleWithColumns(12))); 13155 13156 EXPECT_EQ("\"some text\"", 13157 format("\"some text\"", getLLVMStyleWithColumns(1))); 13158 EXPECT_EQ("\"some text\"", 13159 format("\"some text\"", getLLVMStyleWithColumns(11))); 13160 EXPECT_EQ("\"some \"\n" 13161 "\"text\"", 13162 format("\"some text\"", getLLVMStyleWithColumns(10))); 13163 EXPECT_EQ("\"some \"\n" 13164 "\"text\"", 13165 format("\"some text\"", getLLVMStyleWithColumns(7))); 13166 EXPECT_EQ("\"some\"\n" 13167 "\" tex\"\n" 13168 "\"t\"", 13169 format("\"some text\"", getLLVMStyleWithColumns(6))); 13170 EXPECT_EQ("\"some\"\n" 13171 "\" tex\"\n" 13172 "\" and\"", 13173 format("\"some tex and\"", getLLVMStyleWithColumns(6))); 13174 EXPECT_EQ("\"some\"\n" 13175 "\"/tex\"\n" 13176 "\"/and\"", 13177 format("\"some/tex/and\"", getLLVMStyleWithColumns(6))); 13178 13179 EXPECT_EQ("variable =\n" 13180 " \"long string \"\n" 13181 " \"literal\";", 13182 format("variable = \"long string literal\";", 13183 getLLVMStyleWithColumns(20))); 13184 13185 EXPECT_EQ("variable = f(\n" 13186 " \"long string \"\n" 13187 " \"literal\",\n" 13188 " short,\n" 13189 " loooooooooooooooooooong);", 13190 format("variable = f(\"long string literal\", short, " 13191 "loooooooooooooooooooong);", 13192 getLLVMStyleWithColumns(20))); 13193 13194 EXPECT_EQ( 13195 "f(g(\"long string \"\n" 13196 " \"literal\"),\n" 13197 " b);", 13198 format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20))); 13199 EXPECT_EQ("f(g(\"long string \"\n" 13200 " \"literal\",\n" 13201 " a),\n" 13202 " b);", 13203 format("f(g(\"long string literal\", a), b);", 13204 getLLVMStyleWithColumns(20))); 13205 EXPECT_EQ( 13206 "f(\"one two\".split(\n" 13207 " variable));", 13208 format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20))); 13209 EXPECT_EQ("f(\"one two three four five six \"\n" 13210 " \"seven\".split(\n" 13211 " really_looooong_variable));", 13212 format("f(\"one two three four five six seven\"." 13213 "split(really_looooong_variable));", 13214 getLLVMStyleWithColumns(33))); 13215 13216 EXPECT_EQ("f(\"some \"\n" 13217 " \"text\",\n" 13218 " other);", 13219 format("f(\"some text\", other);", getLLVMStyleWithColumns(10))); 13220 13221 // Only break as a last resort. 13222 verifyFormat( 13223 "aaaaaaaaaaaaaaaaaaaa(\n" 13224 " aaaaaaaaaaaaaaaaaaaa,\n" 13225 " aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));"); 13226 13227 EXPECT_EQ("\"splitmea\"\n" 13228 "\"trandomp\"\n" 13229 "\"oint\"", 13230 format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10))); 13231 13232 EXPECT_EQ("\"split/\"\n" 13233 "\"pathat/\"\n" 13234 "\"slashes\"", 13235 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10))); 13236 13237 EXPECT_EQ("\"split/\"\n" 13238 "\"pathat/\"\n" 13239 "\"slashes\"", 13240 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10))); 13241 EXPECT_EQ("\"split at \"\n" 13242 "\"spaces/at/\"\n" 13243 "\"slashes.at.any$\"\n" 13244 "\"non-alphanumeric%\"\n" 13245 "\"1111111111characte\"\n" 13246 "\"rs\"", 13247 format("\"split at " 13248 "spaces/at/" 13249 "slashes.at." 13250 "any$non-" 13251 "alphanumeric%" 13252 "1111111111characte" 13253 "rs\"", 13254 getLLVMStyleWithColumns(20))); 13255 13256 // Verify that splitting the strings understands 13257 // Style::AlwaysBreakBeforeMultilineStrings. 13258 EXPECT_EQ("aaaaaaaaaaaa(\n" 13259 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n" 13260 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");", 13261 format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa " 13262 "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa " 13263 "aaaaaaaaaaaaaaaaaaaaaa\");", 13264 getGoogleStyle())); 13265 EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13266 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";", 13267 format("return \"aaaaaaaaaaaaaaaaaaaaaa " 13268 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa " 13269 "aaaaaaaaaaaaaaaaaaaaaa\";", 13270 getGoogleStyle())); 13271 EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13272 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";", 13273 format("llvm::outs() << " 13274 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa" 13275 "aaaaaaaaaaaaaaaaaaa\";")); 13276 EXPECT_EQ("ffff(\n" 13277 " {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13278 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});", 13279 format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa " 13280 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});", 13281 getGoogleStyle())); 13282 13283 FormatStyle Style = getLLVMStyleWithColumns(12); 13284 Style.BreakStringLiterals = false; 13285 EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style)); 13286 13287 FormatStyle AlignLeft = getLLVMStyleWithColumns(12); 13288 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left; 13289 EXPECT_EQ("#define A \\\n" 13290 " \"some \" \\\n" 13291 " \"text \" \\\n" 13292 " \"other\";", 13293 format("#define A \"some text other\";", AlignLeft)); 13294 } 13295 13296 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) { 13297 EXPECT_EQ("C a = \"some more \"\n" 13298 " \"text\";", 13299 format("C a = \"some more text\";", getLLVMStyleWithColumns(18))); 13300 } 13301 13302 TEST_F(FormatTest, FullyRemoveEmptyLines) { 13303 FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80); 13304 NoEmptyLines.MaxEmptyLinesToKeep = 0; 13305 EXPECT_EQ("int i = a(b());", 13306 format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines)); 13307 } 13308 13309 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) { 13310 EXPECT_EQ( 13311 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 13312 "(\n" 13313 " \"x\t\");", 13314 format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 13315 "aaaaaaa(" 13316 "\"x\t\");")); 13317 } 13318 13319 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) { 13320 EXPECT_EQ( 13321 "u8\"utf8 string \"\n" 13322 "u8\"literal\";", 13323 format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16))); 13324 EXPECT_EQ( 13325 "u\"utf16 string \"\n" 13326 "u\"literal\";", 13327 format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16))); 13328 EXPECT_EQ( 13329 "U\"utf32 string \"\n" 13330 "U\"literal\";", 13331 format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16))); 13332 EXPECT_EQ("L\"wide string \"\n" 13333 "L\"literal\";", 13334 format("L\"wide string literal\";", getGoogleStyleWithColumns(16))); 13335 EXPECT_EQ("@\"NSString \"\n" 13336 "@\"literal\";", 13337 format("@\"NSString literal\";", getGoogleStyleWithColumns(19))); 13338 verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26)); 13339 13340 // This input makes clang-format try to split the incomplete unicode escape 13341 // sequence, which used to lead to a crasher. 13342 verifyNoCrash( 13343 "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 13344 getLLVMStyleWithColumns(60)); 13345 } 13346 13347 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) { 13348 FormatStyle Style = getGoogleStyleWithColumns(15); 13349 EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style)); 13350 EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style)); 13351 EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style)); 13352 EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style)); 13353 EXPECT_EQ("u8R\"x(raw literal)x\";", 13354 format("u8R\"x(raw literal)x\";", Style)); 13355 } 13356 13357 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) { 13358 FormatStyle Style = getLLVMStyleWithColumns(20); 13359 EXPECT_EQ( 13360 "_T(\"aaaaaaaaaaaaaa\")\n" 13361 "_T(\"aaaaaaaaaaaaaa\")\n" 13362 "_T(\"aaaaaaaaaaaa\")", 13363 format(" _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style)); 13364 EXPECT_EQ("f(x,\n" 13365 " _T(\"aaaaaaaaaaaa\")\n" 13366 " _T(\"aaa\"),\n" 13367 " z);", 13368 format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style)); 13369 13370 // FIXME: Handle embedded spaces in one iteration. 13371 // EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n" 13372 // "_T(\"aaaaaaaaaaaaa\")\n" 13373 // "_T(\"aaaaaaaaaaaaa\")\n" 13374 // "_T(\"a\")", 13375 // format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", 13376 // getLLVMStyleWithColumns(20))); 13377 EXPECT_EQ( 13378 "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", 13379 format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style)); 13380 EXPECT_EQ("f(\n" 13381 "#if !TEST\n" 13382 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n" 13383 "#endif\n" 13384 ");", 13385 format("f(\n" 13386 "#if !TEST\n" 13387 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n" 13388 "#endif\n" 13389 ");")); 13390 EXPECT_EQ("f(\n" 13391 "\n" 13392 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));", 13393 format("f(\n" 13394 "\n" 13395 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));")); 13396 // Regression test for accessing tokens past the end of a vector in the 13397 // TokenLexer. 13398 verifyNoCrash(R"(_T( 13399 " 13400 ) 13401 )"); 13402 } 13403 13404 TEST_F(FormatTest, BreaksStringLiteralOperands) { 13405 // In a function call with two operands, the second can be broken with no line 13406 // break before it. 13407 EXPECT_EQ( 13408 "func(a, \"long long \"\n" 13409 " \"long long\");", 13410 format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24))); 13411 // In a function call with three operands, the second must be broken with a 13412 // line break before it. 13413 EXPECT_EQ("func(a,\n" 13414 " \"long long long \"\n" 13415 " \"long\",\n" 13416 " c);", 13417 format("func(a, \"long long long long\", c);", 13418 getLLVMStyleWithColumns(24))); 13419 // In a function call with three operands, the third must be broken with a 13420 // line break before it. 13421 EXPECT_EQ("func(a, b,\n" 13422 " \"long long long \"\n" 13423 " \"long\");", 13424 format("func(a, b, \"long long long long\");", 13425 getLLVMStyleWithColumns(24))); 13426 // In a function call with three operands, both the second and the third must 13427 // be broken with a line break before them. 13428 EXPECT_EQ("func(a,\n" 13429 " \"long long long \"\n" 13430 " \"long\",\n" 13431 " \"long long long \"\n" 13432 " \"long\");", 13433 format("func(a, \"long long long long\", \"long long long long\");", 13434 getLLVMStyleWithColumns(24))); 13435 // In a chain of << with two operands, the second can be broken with no line 13436 // break before it. 13437 EXPECT_EQ("a << \"line line \"\n" 13438 " \"line\";", 13439 format("a << \"line line line\";", getLLVMStyleWithColumns(20))); 13440 // In a chain of << with three operands, the second can be broken with no line 13441 // break before it. 13442 EXPECT_EQ( 13443 "abcde << \"line \"\n" 13444 " \"line line\"\n" 13445 " << c;", 13446 format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20))); 13447 // In a chain of << with three operands, the third must be broken with a line 13448 // break before it. 13449 EXPECT_EQ( 13450 "a << b\n" 13451 " << \"line line \"\n" 13452 " \"line\";", 13453 format("a << b << \"line line line\";", getLLVMStyleWithColumns(20))); 13454 // In a chain of << with three operands, the second can be broken with no line 13455 // break before it and the third must be broken with a line break before it. 13456 EXPECT_EQ("abcd << \"line line \"\n" 13457 " \"line\"\n" 13458 " << \"line line \"\n" 13459 " \"line\";", 13460 format("abcd << \"line line line\" << \"line line line\";", 13461 getLLVMStyleWithColumns(20))); 13462 // In a chain of binary operators with two operands, the second can be broken 13463 // with no line break before it. 13464 EXPECT_EQ( 13465 "abcd + \"line line \"\n" 13466 " \"line line\";", 13467 format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20))); 13468 // In a chain of binary operators with three operands, the second must be 13469 // broken with a line break before it. 13470 EXPECT_EQ("abcd +\n" 13471 " \"line line \"\n" 13472 " \"line line\" +\n" 13473 " e;", 13474 format("abcd + \"line line line line\" + e;", 13475 getLLVMStyleWithColumns(20))); 13476 // In a function call with two operands, with AlignAfterOpenBracket enabled, 13477 // the first must be broken with a line break before it. 13478 FormatStyle Style = getLLVMStyleWithColumns(25); 13479 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 13480 EXPECT_EQ("someFunction(\n" 13481 " \"long long long \"\n" 13482 " \"long\",\n" 13483 " a);", 13484 format("someFunction(\"long long long long\", a);", Style)); 13485 } 13486 13487 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) { 13488 EXPECT_EQ( 13489 "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13490 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13491 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";", 13492 format("aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13493 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13494 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";")); 13495 } 13496 13497 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) { 13498 EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);", 13499 format("f(g(R\"x(raw literal)x\", a), b);", getGoogleStyle())); 13500 EXPECT_EQ("fffffffffff(g(R\"x(\n" 13501 "multiline raw string literal xxxxxxxxxxxxxx\n" 13502 ")x\",\n" 13503 " a),\n" 13504 " b);", 13505 format("fffffffffff(g(R\"x(\n" 13506 "multiline raw string literal xxxxxxxxxxxxxx\n" 13507 ")x\", a), b);", 13508 getGoogleStyleWithColumns(20))); 13509 EXPECT_EQ("fffffffffff(\n" 13510 " g(R\"x(qqq\n" 13511 "multiline raw string literal xxxxxxxxxxxxxx\n" 13512 ")x\",\n" 13513 " a),\n" 13514 " b);", 13515 format("fffffffffff(g(R\"x(qqq\n" 13516 "multiline raw string literal xxxxxxxxxxxxxx\n" 13517 ")x\", a), b);", 13518 getGoogleStyleWithColumns(20))); 13519 13520 EXPECT_EQ("fffffffffff(R\"x(\n" 13521 "multiline raw string literal xxxxxxxxxxxxxx\n" 13522 ")x\");", 13523 format("fffffffffff(R\"x(\n" 13524 "multiline raw string literal xxxxxxxxxxxxxx\n" 13525 ")x\");", 13526 getGoogleStyleWithColumns(20))); 13527 EXPECT_EQ("fffffffffff(R\"x(\n" 13528 "multiline raw string literal xxxxxxxxxxxxxx\n" 13529 ")x\" + bbbbbb);", 13530 format("fffffffffff(R\"x(\n" 13531 "multiline raw string literal xxxxxxxxxxxxxx\n" 13532 ")x\" + bbbbbb);", 13533 getGoogleStyleWithColumns(20))); 13534 EXPECT_EQ("fffffffffff(\n" 13535 " R\"x(\n" 13536 "multiline raw string literal xxxxxxxxxxxxxx\n" 13537 ")x\" +\n" 13538 " bbbbbb);", 13539 format("fffffffffff(\n" 13540 " R\"x(\n" 13541 "multiline raw string literal xxxxxxxxxxxxxx\n" 13542 ")x\" + bbbbbb);", 13543 getGoogleStyleWithColumns(20))); 13544 EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);", 13545 format("fffffffffff(\n" 13546 " R\"(single line raw string)\" + bbbbbb);")); 13547 } 13548 13549 TEST_F(FormatTest, SkipsUnknownStringLiterals) { 13550 verifyFormat("string a = \"unterminated;"); 13551 EXPECT_EQ("function(\"unterminated,\n" 13552 " OtherParameter);", 13553 format("function( \"unterminated,\n" 13554 " OtherParameter);")); 13555 } 13556 13557 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) { 13558 FormatStyle Style = getLLVMStyle(); 13559 Style.Standard = FormatStyle::LS_Cpp03; 13560 EXPECT_EQ("#define x(_a) printf(\"foo\" _a);", 13561 format("#define x(_a) printf(\"foo\"_a);", Style)); 13562 } 13563 13564 TEST_F(FormatTest, CppLexVersion) { 13565 FormatStyle Style = getLLVMStyle(); 13566 // Formatting of x * y differs if x is a type. 13567 verifyFormat("void foo() { MACRO(a * b); }", Style); 13568 verifyFormat("void foo() { MACRO(int *b); }", Style); 13569 13570 // LLVM style uses latest lexer. 13571 verifyFormat("void foo() { MACRO(char8_t *b); }", Style); 13572 Style.Standard = FormatStyle::LS_Cpp17; 13573 // But in c++17, char8_t isn't a keyword. 13574 verifyFormat("void foo() { MACRO(char8_t * b); }", Style); 13575 } 13576 13577 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); } 13578 13579 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) { 13580 EXPECT_EQ("someFunction(\"aaabbbcccd\"\n" 13581 " \"ddeeefff\");", 13582 format("someFunction(\"aaabbbcccdddeeefff\");", 13583 getLLVMStyleWithColumns(25))); 13584 EXPECT_EQ("someFunction1234567890(\n" 13585 " \"aaabbbcccdddeeefff\");", 13586 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 13587 getLLVMStyleWithColumns(26))); 13588 EXPECT_EQ("someFunction1234567890(\n" 13589 " \"aaabbbcccdddeeeff\"\n" 13590 " \"f\");", 13591 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 13592 getLLVMStyleWithColumns(25))); 13593 EXPECT_EQ("someFunction1234567890(\n" 13594 " \"aaabbbcccdddeeeff\"\n" 13595 " \"f\");", 13596 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 13597 getLLVMStyleWithColumns(24))); 13598 EXPECT_EQ("someFunction(\n" 13599 " \"aaabbbcc ddde \"\n" 13600 " \"efff\");", 13601 format("someFunction(\"aaabbbcc ddde efff\");", 13602 getLLVMStyleWithColumns(25))); 13603 EXPECT_EQ("someFunction(\"aaabbbccc \"\n" 13604 " \"ddeeefff\");", 13605 format("someFunction(\"aaabbbccc ddeeefff\");", 13606 getLLVMStyleWithColumns(25))); 13607 EXPECT_EQ("someFunction1234567890(\n" 13608 " \"aaabb \"\n" 13609 " \"cccdddeeefff\");", 13610 format("someFunction1234567890(\"aaabb cccdddeeefff\");", 13611 getLLVMStyleWithColumns(25))); 13612 EXPECT_EQ("#define A \\\n" 13613 " string s = \\\n" 13614 " \"123456789\" \\\n" 13615 " \"0\"; \\\n" 13616 " int i;", 13617 format("#define A string s = \"1234567890\"; int i;", 13618 getLLVMStyleWithColumns(20))); 13619 EXPECT_EQ("someFunction(\n" 13620 " \"aaabbbcc \"\n" 13621 " \"dddeeefff\");", 13622 format("someFunction(\"aaabbbcc dddeeefff\");", 13623 getLLVMStyleWithColumns(25))); 13624 } 13625 13626 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) { 13627 EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3))); 13628 EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2))); 13629 EXPECT_EQ("\"test\"\n" 13630 "\"\\n\"", 13631 format("\"test\\n\"", getLLVMStyleWithColumns(7))); 13632 EXPECT_EQ("\"tes\\\\\"\n" 13633 "\"n\"", 13634 format("\"tes\\\\n\"", getLLVMStyleWithColumns(7))); 13635 EXPECT_EQ("\"\\\\\\\\\"\n" 13636 "\"\\n\"", 13637 format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7))); 13638 EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7))); 13639 EXPECT_EQ("\"\\uff01\"\n" 13640 "\"test\"", 13641 format("\"\\uff01test\"", getLLVMStyleWithColumns(8))); 13642 EXPECT_EQ("\"\\Uff01ff02\"", 13643 format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11))); 13644 EXPECT_EQ("\"\\x000000000001\"\n" 13645 "\"next\"", 13646 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16))); 13647 EXPECT_EQ("\"\\x000000000001next\"", 13648 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15))); 13649 EXPECT_EQ("\"\\x000000000001\"", 13650 format("\"\\x000000000001\"", getLLVMStyleWithColumns(7))); 13651 EXPECT_EQ("\"test\"\n" 13652 "\"\\000000\"\n" 13653 "\"000001\"", 13654 format("\"test\\000000000001\"", getLLVMStyleWithColumns(9))); 13655 EXPECT_EQ("\"test\\000\"\n" 13656 "\"00000000\"\n" 13657 "\"1\"", 13658 format("\"test\\000000000001\"", getLLVMStyleWithColumns(10))); 13659 } 13660 13661 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) { 13662 verifyFormat("void f() {\n" 13663 " return g() {}\n" 13664 " void h() {}"); 13665 verifyFormat("int a[] = {void forgot_closing_brace(){f();\n" 13666 "g();\n" 13667 "}"); 13668 } 13669 13670 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) { 13671 verifyFormat( 13672 "void f() { return C{param1, param2}.SomeCall(param1, param2); }"); 13673 } 13674 13675 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) { 13676 verifyFormat("class X {\n" 13677 " void f() {\n" 13678 " }\n" 13679 "};", 13680 getLLVMStyleWithColumns(12)); 13681 } 13682 13683 TEST_F(FormatTest, ConfigurableIndentWidth) { 13684 FormatStyle EightIndent = getLLVMStyleWithColumns(18); 13685 EightIndent.IndentWidth = 8; 13686 EightIndent.ContinuationIndentWidth = 8; 13687 verifyFormat("void f() {\n" 13688 " someFunction();\n" 13689 " if (true) {\n" 13690 " f();\n" 13691 " }\n" 13692 "}", 13693 EightIndent); 13694 verifyFormat("class X {\n" 13695 " void f() {\n" 13696 " }\n" 13697 "};", 13698 EightIndent); 13699 verifyFormat("int x[] = {\n" 13700 " call(),\n" 13701 " call()};", 13702 EightIndent); 13703 } 13704 13705 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) { 13706 verifyFormat("double\n" 13707 "f();", 13708 getLLVMStyleWithColumns(8)); 13709 } 13710 13711 TEST_F(FormatTest, ConfigurableUseOfTab) { 13712 FormatStyle Tab = getLLVMStyleWithColumns(42); 13713 Tab.IndentWidth = 8; 13714 Tab.UseTab = FormatStyle::UT_Always; 13715 Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left; 13716 13717 EXPECT_EQ("if (aaaaaaaa && // q\n" 13718 " bb)\t\t// w\n" 13719 "\t;", 13720 format("if (aaaaaaaa &&// q\n" 13721 "bb)// w\n" 13722 ";", 13723 Tab)); 13724 EXPECT_EQ("if (aaa && bbb) // w\n" 13725 "\t;", 13726 format("if(aaa&&bbb)// w\n" 13727 ";", 13728 Tab)); 13729 13730 verifyFormat("class X {\n" 13731 "\tvoid f() {\n" 13732 "\t\tsomeFunction(parameter1,\n" 13733 "\t\t\t parameter2);\n" 13734 "\t}\n" 13735 "};", 13736 Tab); 13737 verifyFormat("#define A \\\n" 13738 "\tvoid f() { \\\n" 13739 "\t\tsomeFunction( \\\n" 13740 "\t\t parameter1, \\\n" 13741 "\t\t parameter2); \\\n" 13742 "\t}", 13743 Tab); 13744 verifyFormat("int a;\t // x\n" 13745 "int bbbbbbbb; // x\n", 13746 Tab); 13747 13748 Tab.TabWidth = 4; 13749 Tab.IndentWidth = 8; 13750 verifyFormat("class TabWidth4Indent8 {\n" 13751 "\t\tvoid f() {\n" 13752 "\t\t\t\tsomeFunction(parameter1,\n" 13753 "\t\t\t\t\t\t\t parameter2);\n" 13754 "\t\t}\n" 13755 "};", 13756 Tab); 13757 13758 Tab.TabWidth = 4; 13759 Tab.IndentWidth = 4; 13760 verifyFormat("class TabWidth4Indent4 {\n" 13761 "\tvoid f() {\n" 13762 "\t\tsomeFunction(parameter1,\n" 13763 "\t\t\t\t\t parameter2);\n" 13764 "\t}\n" 13765 "};", 13766 Tab); 13767 13768 Tab.TabWidth = 8; 13769 Tab.IndentWidth = 4; 13770 verifyFormat("class TabWidth8Indent4 {\n" 13771 " void f() {\n" 13772 "\tsomeFunction(parameter1,\n" 13773 "\t\t parameter2);\n" 13774 " }\n" 13775 "};", 13776 Tab); 13777 13778 Tab.TabWidth = 8; 13779 Tab.IndentWidth = 8; 13780 EXPECT_EQ("/*\n" 13781 "\t a\t\tcomment\n" 13782 "\t in multiple lines\n" 13783 " */", 13784 format(" /*\t \t \n" 13785 " \t \t a\t\tcomment\t \t\n" 13786 " \t \t in multiple lines\t\n" 13787 " \t */", 13788 Tab)); 13789 13790 Tab.UseTab = FormatStyle::UT_ForIndentation; 13791 verifyFormat("{\n" 13792 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13793 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13794 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13795 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13796 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13797 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13798 "};", 13799 Tab); 13800 verifyFormat("enum AA {\n" 13801 "\ta1, // Force multiple lines\n" 13802 "\ta2,\n" 13803 "\ta3\n" 13804 "};", 13805 Tab); 13806 EXPECT_EQ("if (aaaaaaaa && // q\n" 13807 " bb) // w\n" 13808 "\t;", 13809 format("if (aaaaaaaa &&// q\n" 13810 "bb)// w\n" 13811 ";", 13812 Tab)); 13813 verifyFormat("class X {\n" 13814 "\tvoid f() {\n" 13815 "\t\tsomeFunction(parameter1,\n" 13816 "\t\t parameter2);\n" 13817 "\t}\n" 13818 "};", 13819 Tab); 13820 verifyFormat("{\n" 13821 "\tQ(\n" 13822 "\t {\n" 13823 "\t\t int a;\n" 13824 "\t\t someFunction(aaaaaaaa,\n" 13825 "\t\t bbbbbbb);\n" 13826 "\t },\n" 13827 "\t p);\n" 13828 "}", 13829 Tab); 13830 EXPECT_EQ("{\n" 13831 "\t/* aaaa\n" 13832 "\t bbbb */\n" 13833 "}", 13834 format("{\n" 13835 "/* aaaa\n" 13836 " bbbb */\n" 13837 "}", 13838 Tab)); 13839 EXPECT_EQ("{\n" 13840 "\t/*\n" 13841 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 13842 "\t bbbbbbbbbbbbb\n" 13843 "\t*/\n" 13844 "}", 13845 format("{\n" 13846 "/*\n" 13847 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 13848 "*/\n" 13849 "}", 13850 Tab)); 13851 EXPECT_EQ("{\n" 13852 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 13853 "\t// bbbbbbbbbbbbb\n" 13854 "}", 13855 format("{\n" 13856 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 13857 "}", 13858 Tab)); 13859 EXPECT_EQ("{\n" 13860 "\t/*\n" 13861 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 13862 "\t bbbbbbbbbbbbb\n" 13863 "\t*/\n" 13864 "}", 13865 format("{\n" 13866 "\t/*\n" 13867 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 13868 "\t*/\n" 13869 "}", 13870 Tab)); 13871 EXPECT_EQ("{\n" 13872 "\t/*\n" 13873 "\n" 13874 "\t*/\n" 13875 "}", 13876 format("{\n" 13877 "\t/*\n" 13878 "\n" 13879 "\t*/\n" 13880 "}", 13881 Tab)); 13882 EXPECT_EQ("{\n" 13883 "\t/*\n" 13884 " asdf\n" 13885 "\t*/\n" 13886 "}", 13887 format("{\n" 13888 "\t/*\n" 13889 " asdf\n" 13890 "\t*/\n" 13891 "}", 13892 Tab)); 13893 13894 verifyFormat("void f() {\n" 13895 "\treturn true ? aaaaaaaaaaaaaaaaaa\n" 13896 "\t : bbbbbbbbbbbbbbbbbb\n" 13897 "}", 13898 Tab); 13899 FormatStyle TabNoBreak = Tab; 13900 TabNoBreak.BreakBeforeTernaryOperators = false; 13901 verifyFormat("void f() {\n" 13902 "\treturn true ? aaaaaaaaaaaaaaaaaa :\n" 13903 "\t bbbbbbbbbbbbbbbbbb\n" 13904 "}", 13905 TabNoBreak); 13906 verifyFormat("void f() {\n" 13907 "\treturn true ?\n" 13908 "\t aaaaaaaaaaaaaaaaaaaa :\n" 13909 "\t bbbbbbbbbbbbbbbbbbbb\n" 13910 "}", 13911 TabNoBreak); 13912 13913 Tab.UseTab = FormatStyle::UT_Never; 13914 EXPECT_EQ("/*\n" 13915 " a\t\tcomment\n" 13916 " in multiple lines\n" 13917 " */", 13918 format(" /*\t \t \n" 13919 " \t \t a\t\tcomment\t \t\n" 13920 " \t \t in multiple lines\t\n" 13921 " \t */", 13922 Tab)); 13923 EXPECT_EQ("/* some\n" 13924 " comment */", 13925 format(" \t \t /* some\n" 13926 " \t \t comment */", 13927 Tab)); 13928 EXPECT_EQ("int a; /* some\n" 13929 " comment */", 13930 format(" \t \t int a; /* some\n" 13931 " \t \t comment */", 13932 Tab)); 13933 13934 EXPECT_EQ("int a; /* some\n" 13935 "comment */", 13936 format(" \t \t int\ta; /* some\n" 13937 " \t \t comment */", 13938 Tab)); 13939 EXPECT_EQ("f(\"\t\t\"); /* some\n" 13940 " comment */", 13941 format(" \t \t f(\"\t\t\"); /* some\n" 13942 " \t \t comment */", 13943 Tab)); 13944 EXPECT_EQ("{\n" 13945 " /*\n" 13946 " * Comment\n" 13947 " */\n" 13948 " int i;\n" 13949 "}", 13950 format("{\n" 13951 "\t/*\n" 13952 "\t * Comment\n" 13953 "\t */\n" 13954 "\t int i;\n" 13955 "}", 13956 Tab)); 13957 13958 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation; 13959 Tab.TabWidth = 8; 13960 Tab.IndentWidth = 8; 13961 EXPECT_EQ("if (aaaaaaaa && // q\n" 13962 " bb) // w\n" 13963 "\t;", 13964 format("if (aaaaaaaa &&// q\n" 13965 "bb)// w\n" 13966 ";", 13967 Tab)); 13968 EXPECT_EQ("if (aaa && bbb) // w\n" 13969 "\t;", 13970 format("if(aaa&&bbb)// w\n" 13971 ";", 13972 Tab)); 13973 verifyFormat("class X {\n" 13974 "\tvoid f() {\n" 13975 "\t\tsomeFunction(parameter1,\n" 13976 "\t\t\t parameter2);\n" 13977 "\t}\n" 13978 "};", 13979 Tab); 13980 verifyFormat("#define A \\\n" 13981 "\tvoid f() { \\\n" 13982 "\t\tsomeFunction( \\\n" 13983 "\t\t parameter1, \\\n" 13984 "\t\t parameter2); \\\n" 13985 "\t}", 13986 Tab); 13987 Tab.TabWidth = 4; 13988 Tab.IndentWidth = 8; 13989 verifyFormat("class TabWidth4Indent8 {\n" 13990 "\t\tvoid f() {\n" 13991 "\t\t\t\tsomeFunction(parameter1,\n" 13992 "\t\t\t\t\t\t\t parameter2);\n" 13993 "\t\t}\n" 13994 "};", 13995 Tab); 13996 Tab.TabWidth = 4; 13997 Tab.IndentWidth = 4; 13998 verifyFormat("class TabWidth4Indent4 {\n" 13999 "\tvoid f() {\n" 14000 "\t\tsomeFunction(parameter1,\n" 14001 "\t\t\t\t\t parameter2);\n" 14002 "\t}\n" 14003 "};", 14004 Tab); 14005 Tab.TabWidth = 8; 14006 Tab.IndentWidth = 4; 14007 verifyFormat("class TabWidth8Indent4 {\n" 14008 " void f() {\n" 14009 "\tsomeFunction(parameter1,\n" 14010 "\t\t parameter2);\n" 14011 " }\n" 14012 "};", 14013 Tab); 14014 Tab.TabWidth = 8; 14015 Tab.IndentWidth = 8; 14016 EXPECT_EQ("/*\n" 14017 "\t a\t\tcomment\n" 14018 "\t in multiple lines\n" 14019 " */", 14020 format(" /*\t \t \n" 14021 " \t \t a\t\tcomment\t \t\n" 14022 " \t \t in multiple lines\t\n" 14023 " \t */", 14024 Tab)); 14025 verifyFormat("{\n" 14026 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14027 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14028 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14029 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14030 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14031 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14032 "};", 14033 Tab); 14034 verifyFormat("enum AA {\n" 14035 "\ta1, // Force multiple lines\n" 14036 "\ta2,\n" 14037 "\ta3\n" 14038 "};", 14039 Tab); 14040 EXPECT_EQ("if (aaaaaaaa && // q\n" 14041 " bb) // w\n" 14042 "\t;", 14043 format("if (aaaaaaaa &&// q\n" 14044 "bb)// w\n" 14045 ";", 14046 Tab)); 14047 verifyFormat("class X {\n" 14048 "\tvoid f() {\n" 14049 "\t\tsomeFunction(parameter1,\n" 14050 "\t\t\t parameter2);\n" 14051 "\t}\n" 14052 "};", 14053 Tab); 14054 verifyFormat("{\n" 14055 "\tQ(\n" 14056 "\t {\n" 14057 "\t\t int a;\n" 14058 "\t\t someFunction(aaaaaaaa,\n" 14059 "\t\t\t\t bbbbbbb);\n" 14060 "\t },\n" 14061 "\t p);\n" 14062 "}", 14063 Tab); 14064 EXPECT_EQ("{\n" 14065 "\t/* aaaa\n" 14066 "\t bbbb */\n" 14067 "}", 14068 format("{\n" 14069 "/* aaaa\n" 14070 " bbbb */\n" 14071 "}", 14072 Tab)); 14073 EXPECT_EQ("{\n" 14074 "\t/*\n" 14075 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14076 "\t bbbbbbbbbbbbb\n" 14077 "\t*/\n" 14078 "}", 14079 format("{\n" 14080 "/*\n" 14081 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14082 "*/\n" 14083 "}", 14084 Tab)); 14085 EXPECT_EQ("{\n" 14086 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14087 "\t// bbbbbbbbbbbbb\n" 14088 "}", 14089 format("{\n" 14090 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14091 "}", 14092 Tab)); 14093 EXPECT_EQ("{\n" 14094 "\t/*\n" 14095 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14096 "\t bbbbbbbbbbbbb\n" 14097 "\t*/\n" 14098 "}", 14099 format("{\n" 14100 "\t/*\n" 14101 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14102 "\t*/\n" 14103 "}", 14104 Tab)); 14105 EXPECT_EQ("{\n" 14106 "\t/*\n" 14107 "\n" 14108 "\t*/\n" 14109 "}", 14110 format("{\n" 14111 "\t/*\n" 14112 "\n" 14113 "\t*/\n" 14114 "}", 14115 Tab)); 14116 EXPECT_EQ("{\n" 14117 "\t/*\n" 14118 " asdf\n" 14119 "\t*/\n" 14120 "}", 14121 format("{\n" 14122 "\t/*\n" 14123 " asdf\n" 14124 "\t*/\n" 14125 "}", 14126 Tab)); 14127 EXPECT_EQ("/* some\n" 14128 " comment */", 14129 format(" \t \t /* some\n" 14130 " \t \t comment */", 14131 Tab)); 14132 EXPECT_EQ("int a; /* some\n" 14133 " comment */", 14134 format(" \t \t int a; /* some\n" 14135 " \t \t comment */", 14136 Tab)); 14137 EXPECT_EQ("int a; /* some\n" 14138 "comment */", 14139 format(" \t \t int\ta; /* some\n" 14140 " \t \t comment */", 14141 Tab)); 14142 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14143 " comment */", 14144 format(" \t \t f(\"\t\t\"); /* some\n" 14145 " \t \t comment */", 14146 Tab)); 14147 EXPECT_EQ("{\n" 14148 "\t/*\n" 14149 "\t * Comment\n" 14150 "\t */\n" 14151 "\tint i;\n" 14152 "}", 14153 format("{\n" 14154 "\t/*\n" 14155 "\t * Comment\n" 14156 "\t */\n" 14157 "\t int i;\n" 14158 "}", 14159 Tab)); 14160 Tab.TabWidth = 2; 14161 Tab.IndentWidth = 2; 14162 EXPECT_EQ("{\n" 14163 "\t/* aaaa\n" 14164 "\t\t bbbb */\n" 14165 "}", 14166 format("{\n" 14167 "/* aaaa\n" 14168 "\t bbbb */\n" 14169 "}", 14170 Tab)); 14171 EXPECT_EQ("{\n" 14172 "\t/*\n" 14173 "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14174 "\t\tbbbbbbbbbbbbb\n" 14175 "\t*/\n" 14176 "}", 14177 format("{\n" 14178 "/*\n" 14179 "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14180 "*/\n" 14181 "}", 14182 Tab)); 14183 Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 14184 Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 14185 Tab.TabWidth = 4; 14186 Tab.IndentWidth = 4; 14187 verifyFormat("class Assign {\n" 14188 "\tvoid f() {\n" 14189 "\t\tint x = 123;\n" 14190 "\t\tint random = 4;\n" 14191 "\t\tstd::string alphabet =\n" 14192 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n" 14193 "\t}\n" 14194 "};", 14195 Tab); 14196 14197 Tab.UseTab = FormatStyle::UT_AlignWithSpaces; 14198 Tab.TabWidth = 8; 14199 Tab.IndentWidth = 8; 14200 EXPECT_EQ("if (aaaaaaaa && // q\n" 14201 " bb) // w\n" 14202 "\t;", 14203 format("if (aaaaaaaa &&// q\n" 14204 "bb)// w\n" 14205 ";", 14206 Tab)); 14207 EXPECT_EQ("if (aaa && bbb) // w\n" 14208 "\t;", 14209 format("if(aaa&&bbb)// w\n" 14210 ";", 14211 Tab)); 14212 verifyFormat("class X {\n" 14213 "\tvoid f() {\n" 14214 "\t\tsomeFunction(parameter1,\n" 14215 "\t\t parameter2);\n" 14216 "\t}\n" 14217 "};", 14218 Tab); 14219 verifyFormat("#define A \\\n" 14220 "\tvoid f() { \\\n" 14221 "\t\tsomeFunction( \\\n" 14222 "\t\t parameter1, \\\n" 14223 "\t\t parameter2); \\\n" 14224 "\t}", 14225 Tab); 14226 Tab.TabWidth = 4; 14227 Tab.IndentWidth = 8; 14228 verifyFormat("class TabWidth4Indent8 {\n" 14229 "\t\tvoid f() {\n" 14230 "\t\t\t\tsomeFunction(parameter1,\n" 14231 "\t\t\t\t parameter2);\n" 14232 "\t\t}\n" 14233 "};", 14234 Tab); 14235 Tab.TabWidth = 4; 14236 Tab.IndentWidth = 4; 14237 verifyFormat("class TabWidth4Indent4 {\n" 14238 "\tvoid f() {\n" 14239 "\t\tsomeFunction(parameter1,\n" 14240 "\t\t parameter2);\n" 14241 "\t}\n" 14242 "};", 14243 Tab); 14244 Tab.TabWidth = 8; 14245 Tab.IndentWidth = 4; 14246 verifyFormat("class TabWidth8Indent4 {\n" 14247 " void f() {\n" 14248 "\tsomeFunction(parameter1,\n" 14249 "\t parameter2);\n" 14250 " }\n" 14251 "};", 14252 Tab); 14253 Tab.TabWidth = 8; 14254 Tab.IndentWidth = 8; 14255 EXPECT_EQ("/*\n" 14256 " a\t\tcomment\n" 14257 " in multiple lines\n" 14258 " */", 14259 format(" /*\t \t \n" 14260 " \t \t a\t\tcomment\t \t\n" 14261 " \t \t in multiple lines\t\n" 14262 " \t */", 14263 Tab)); 14264 verifyFormat("{\n" 14265 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14266 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14267 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14268 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14269 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14270 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14271 "};", 14272 Tab); 14273 verifyFormat("enum AA {\n" 14274 "\ta1, // Force multiple lines\n" 14275 "\ta2,\n" 14276 "\ta3\n" 14277 "};", 14278 Tab); 14279 EXPECT_EQ("if (aaaaaaaa && // q\n" 14280 " bb) // w\n" 14281 "\t;", 14282 format("if (aaaaaaaa &&// q\n" 14283 "bb)// w\n" 14284 ";", 14285 Tab)); 14286 verifyFormat("class X {\n" 14287 "\tvoid f() {\n" 14288 "\t\tsomeFunction(parameter1,\n" 14289 "\t\t parameter2);\n" 14290 "\t}\n" 14291 "};", 14292 Tab); 14293 verifyFormat("{\n" 14294 "\tQ(\n" 14295 "\t {\n" 14296 "\t\t int a;\n" 14297 "\t\t someFunction(aaaaaaaa,\n" 14298 "\t\t bbbbbbb);\n" 14299 "\t },\n" 14300 "\t p);\n" 14301 "}", 14302 Tab); 14303 EXPECT_EQ("{\n" 14304 "\t/* aaaa\n" 14305 "\t bbbb */\n" 14306 "}", 14307 format("{\n" 14308 "/* aaaa\n" 14309 " bbbb */\n" 14310 "}", 14311 Tab)); 14312 EXPECT_EQ("{\n" 14313 "\t/*\n" 14314 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14315 "\t bbbbbbbbbbbbb\n" 14316 "\t*/\n" 14317 "}", 14318 format("{\n" 14319 "/*\n" 14320 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14321 "*/\n" 14322 "}", 14323 Tab)); 14324 EXPECT_EQ("{\n" 14325 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14326 "\t// bbbbbbbbbbbbb\n" 14327 "}", 14328 format("{\n" 14329 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14330 "}", 14331 Tab)); 14332 EXPECT_EQ("{\n" 14333 "\t/*\n" 14334 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14335 "\t bbbbbbbbbbbbb\n" 14336 "\t*/\n" 14337 "}", 14338 format("{\n" 14339 "\t/*\n" 14340 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14341 "\t*/\n" 14342 "}", 14343 Tab)); 14344 EXPECT_EQ("{\n" 14345 "\t/*\n" 14346 "\n" 14347 "\t*/\n" 14348 "}", 14349 format("{\n" 14350 "\t/*\n" 14351 "\n" 14352 "\t*/\n" 14353 "}", 14354 Tab)); 14355 EXPECT_EQ("{\n" 14356 "\t/*\n" 14357 " asdf\n" 14358 "\t*/\n" 14359 "}", 14360 format("{\n" 14361 "\t/*\n" 14362 " asdf\n" 14363 "\t*/\n" 14364 "}", 14365 Tab)); 14366 EXPECT_EQ("/* some\n" 14367 " comment */", 14368 format(" \t \t /* some\n" 14369 " \t \t comment */", 14370 Tab)); 14371 EXPECT_EQ("int a; /* some\n" 14372 " comment */", 14373 format(" \t \t int a; /* some\n" 14374 " \t \t comment */", 14375 Tab)); 14376 EXPECT_EQ("int a; /* some\n" 14377 "comment */", 14378 format(" \t \t int\ta; /* some\n" 14379 " \t \t comment */", 14380 Tab)); 14381 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14382 " comment */", 14383 format(" \t \t f(\"\t\t\"); /* some\n" 14384 " \t \t comment */", 14385 Tab)); 14386 EXPECT_EQ("{\n" 14387 "\t/*\n" 14388 "\t * Comment\n" 14389 "\t */\n" 14390 "\tint i;\n" 14391 "}", 14392 format("{\n" 14393 "\t/*\n" 14394 "\t * Comment\n" 14395 "\t */\n" 14396 "\t int i;\n" 14397 "}", 14398 Tab)); 14399 Tab.TabWidth = 2; 14400 Tab.IndentWidth = 2; 14401 EXPECT_EQ("{\n" 14402 "\t/* aaaa\n" 14403 "\t bbbb */\n" 14404 "}", 14405 format("{\n" 14406 "/* aaaa\n" 14407 " bbbb */\n" 14408 "}", 14409 Tab)); 14410 EXPECT_EQ("{\n" 14411 "\t/*\n" 14412 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14413 "\t bbbbbbbbbbbbb\n" 14414 "\t*/\n" 14415 "}", 14416 format("{\n" 14417 "/*\n" 14418 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14419 "*/\n" 14420 "}", 14421 Tab)); 14422 Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 14423 Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 14424 Tab.TabWidth = 4; 14425 Tab.IndentWidth = 4; 14426 verifyFormat("class Assign {\n" 14427 "\tvoid f() {\n" 14428 "\t\tint x = 123;\n" 14429 "\t\tint random = 4;\n" 14430 "\t\tstd::string alphabet =\n" 14431 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n" 14432 "\t}\n" 14433 "};", 14434 Tab); 14435 Tab.AlignOperands = FormatStyle::OAS_Align; 14436 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n" 14437 " cccccccccccccccccccc;", 14438 Tab); 14439 // no alignment 14440 verifyFormat("int aaaaaaaaaa =\n" 14441 "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 14442 Tab); 14443 verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n" 14444 " : bbbbbbbbbbbbbb ? 222222222222222\n" 14445 " : 333333333333333;", 14446 Tab); 14447 Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 14448 Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator; 14449 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n" 14450 " + cccccccccccccccccccc;", 14451 Tab); 14452 } 14453 14454 TEST_F(FormatTest, ZeroTabWidth) { 14455 FormatStyle Tab = getLLVMStyleWithColumns(42); 14456 Tab.IndentWidth = 8; 14457 Tab.UseTab = FormatStyle::UT_Never; 14458 Tab.TabWidth = 0; 14459 EXPECT_EQ("void a(){\n" 14460 " // line starts with '\t'\n" 14461 "};", 14462 format("void a(){\n" 14463 "\t// line starts with '\t'\n" 14464 "};", 14465 Tab)); 14466 14467 EXPECT_EQ("void a(){\n" 14468 " // line starts with '\t'\n" 14469 "};", 14470 format("void a(){\n" 14471 "\t\t// line starts with '\t'\n" 14472 "};", 14473 Tab)); 14474 14475 Tab.UseTab = FormatStyle::UT_ForIndentation; 14476 EXPECT_EQ("void a(){\n" 14477 " // line starts with '\t'\n" 14478 "};", 14479 format("void a(){\n" 14480 "\t// line starts with '\t'\n" 14481 "};", 14482 Tab)); 14483 14484 EXPECT_EQ("void a(){\n" 14485 " // line starts with '\t'\n" 14486 "};", 14487 format("void a(){\n" 14488 "\t\t// line starts with '\t'\n" 14489 "};", 14490 Tab)); 14491 14492 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation; 14493 EXPECT_EQ("void a(){\n" 14494 " // line starts with '\t'\n" 14495 "};", 14496 format("void a(){\n" 14497 "\t// line starts with '\t'\n" 14498 "};", 14499 Tab)); 14500 14501 EXPECT_EQ("void a(){\n" 14502 " // line starts with '\t'\n" 14503 "};", 14504 format("void a(){\n" 14505 "\t\t// line starts with '\t'\n" 14506 "};", 14507 Tab)); 14508 14509 Tab.UseTab = FormatStyle::UT_AlignWithSpaces; 14510 EXPECT_EQ("void a(){\n" 14511 " // line starts with '\t'\n" 14512 "};", 14513 format("void a(){\n" 14514 "\t// line starts with '\t'\n" 14515 "};", 14516 Tab)); 14517 14518 EXPECT_EQ("void a(){\n" 14519 " // line starts with '\t'\n" 14520 "};", 14521 format("void a(){\n" 14522 "\t\t// line starts with '\t'\n" 14523 "};", 14524 Tab)); 14525 14526 Tab.UseTab = FormatStyle::UT_Always; 14527 EXPECT_EQ("void a(){\n" 14528 "// line starts with '\t'\n" 14529 "};", 14530 format("void a(){\n" 14531 "\t// line starts with '\t'\n" 14532 "};", 14533 Tab)); 14534 14535 EXPECT_EQ("void a(){\n" 14536 "// line starts with '\t'\n" 14537 "};", 14538 format("void a(){\n" 14539 "\t\t// line starts with '\t'\n" 14540 "};", 14541 Tab)); 14542 } 14543 14544 TEST_F(FormatTest, CalculatesOriginalColumn) { 14545 EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14546 "q\"; /* some\n" 14547 " comment */", 14548 format(" \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14549 "q\"; /* some\n" 14550 " comment */", 14551 getLLVMStyle())); 14552 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n" 14553 "/* some\n" 14554 " comment */", 14555 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n" 14556 " /* some\n" 14557 " comment */", 14558 getLLVMStyle())); 14559 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14560 "qqq\n" 14561 "/* some\n" 14562 " comment */", 14563 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14564 "qqq\n" 14565 " /* some\n" 14566 " comment */", 14567 getLLVMStyle())); 14568 EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14569 "wwww; /* some\n" 14570 " comment */", 14571 format(" inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14572 "wwww; /* some\n" 14573 " comment */", 14574 getLLVMStyle())); 14575 } 14576 14577 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) { 14578 FormatStyle NoSpace = getLLVMStyle(); 14579 NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never; 14580 14581 verifyFormat("while(true)\n" 14582 " continue;", 14583 NoSpace); 14584 verifyFormat("for(;;)\n" 14585 " continue;", 14586 NoSpace); 14587 verifyFormat("if(true)\n" 14588 " f();\n" 14589 "else if(true)\n" 14590 " f();", 14591 NoSpace); 14592 verifyFormat("do {\n" 14593 " do_something();\n" 14594 "} while(something());", 14595 NoSpace); 14596 verifyFormat("switch(x) {\n" 14597 "default:\n" 14598 " break;\n" 14599 "}", 14600 NoSpace); 14601 verifyFormat("auto i = std::make_unique<int>(5);", NoSpace); 14602 verifyFormat("size_t x = sizeof(x);", NoSpace); 14603 verifyFormat("auto f(int x) -> decltype(x);", NoSpace); 14604 verifyFormat("auto f(int x) -> typeof(x);", NoSpace); 14605 verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace); 14606 verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace); 14607 verifyFormat("int f(T x) noexcept(x.create());", NoSpace); 14608 verifyFormat("alignas(128) char a[128];", NoSpace); 14609 verifyFormat("size_t x = alignof(MyType);", NoSpace); 14610 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace); 14611 verifyFormat("int f() throw(Deprecated);", NoSpace); 14612 verifyFormat("typedef void (*cb)(int);", NoSpace); 14613 verifyFormat("T A::operator()();", NoSpace); 14614 verifyFormat("X A::operator++(T);", NoSpace); 14615 verifyFormat("auto lambda = []() { return 0; };", NoSpace); 14616 14617 FormatStyle Space = getLLVMStyle(); 14618 Space.SpaceBeforeParens = FormatStyle::SBPO_Always; 14619 14620 verifyFormat("int f ();", Space); 14621 verifyFormat("void f (int a, T b) {\n" 14622 " while (true)\n" 14623 " continue;\n" 14624 "}", 14625 Space); 14626 verifyFormat("if (true)\n" 14627 " f ();\n" 14628 "else if (true)\n" 14629 " f ();", 14630 Space); 14631 verifyFormat("do {\n" 14632 " do_something ();\n" 14633 "} while (something ());", 14634 Space); 14635 verifyFormat("switch (x) {\n" 14636 "default:\n" 14637 " break;\n" 14638 "}", 14639 Space); 14640 verifyFormat("A::A () : a (1) {}", Space); 14641 verifyFormat("void f () __attribute__ ((asdf));", Space); 14642 verifyFormat("*(&a + 1);\n" 14643 "&((&a)[1]);\n" 14644 "a[(b + c) * d];\n" 14645 "(((a + 1) * 2) + 3) * 4;", 14646 Space); 14647 verifyFormat("#define A(x) x", Space); 14648 verifyFormat("#define A (x) x", Space); 14649 verifyFormat("#if defined(x)\n" 14650 "#endif", 14651 Space); 14652 verifyFormat("auto i = std::make_unique<int> (5);", Space); 14653 verifyFormat("size_t x = sizeof (x);", Space); 14654 verifyFormat("auto f (int x) -> decltype (x);", Space); 14655 verifyFormat("auto f (int x) -> typeof (x);", Space); 14656 verifyFormat("auto f (int x) -> _Atomic (x);", Space); 14657 verifyFormat("auto f (int x) -> __underlying_type (x);", Space); 14658 verifyFormat("int f (T x) noexcept (x.create ());", Space); 14659 verifyFormat("alignas (128) char a[128];", Space); 14660 verifyFormat("size_t x = alignof (MyType);", Space); 14661 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space); 14662 verifyFormat("int f () throw (Deprecated);", Space); 14663 verifyFormat("typedef void (*cb) (int);", Space); 14664 // FIXME these tests regressed behaviour. 14665 // verifyFormat("T A::operator() ();", Space); 14666 // verifyFormat("X A::operator++ (T);", Space); 14667 verifyFormat("auto lambda = [] () { return 0; };", Space); 14668 verifyFormat("int x = int (y);", Space); 14669 14670 FormatStyle SomeSpace = getLLVMStyle(); 14671 SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses; 14672 14673 verifyFormat("[]() -> float {}", SomeSpace); 14674 verifyFormat("[] (auto foo) {}", SomeSpace); 14675 verifyFormat("[foo]() -> int {}", SomeSpace); 14676 verifyFormat("int f();", SomeSpace); 14677 verifyFormat("void f (int a, T b) {\n" 14678 " while (true)\n" 14679 " continue;\n" 14680 "}", 14681 SomeSpace); 14682 verifyFormat("if (true)\n" 14683 " f();\n" 14684 "else if (true)\n" 14685 " f();", 14686 SomeSpace); 14687 verifyFormat("do {\n" 14688 " do_something();\n" 14689 "} while (something());", 14690 SomeSpace); 14691 verifyFormat("switch (x) {\n" 14692 "default:\n" 14693 " break;\n" 14694 "}", 14695 SomeSpace); 14696 verifyFormat("A::A() : a (1) {}", SomeSpace); 14697 verifyFormat("void f() __attribute__ ((asdf));", SomeSpace); 14698 verifyFormat("*(&a + 1);\n" 14699 "&((&a)[1]);\n" 14700 "a[(b + c) * d];\n" 14701 "(((a + 1) * 2) + 3) * 4;", 14702 SomeSpace); 14703 verifyFormat("#define A(x) x", SomeSpace); 14704 verifyFormat("#define A (x) x", SomeSpace); 14705 verifyFormat("#if defined(x)\n" 14706 "#endif", 14707 SomeSpace); 14708 verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace); 14709 verifyFormat("size_t x = sizeof (x);", SomeSpace); 14710 verifyFormat("auto f (int x) -> decltype (x);", SomeSpace); 14711 verifyFormat("auto f (int x) -> typeof (x);", SomeSpace); 14712 verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace); 14713 verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace); 14714 verifyFormat("int f (T x) noexcept (x.create());", SomeSpace); 14715 verifyFormat("alignas (128) char a[128];", SomeSpace); 14716 verifyFormat("size_t x = alignof (MyType);", SomeSpace); 14717 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", 14718 SomeSpace); 14719 verifyFormat("int f() throw (Deprecated);", SomeSpace); 14720 verifyFormat("typedef void (*cb) (int);", SomeSpace); 14721 verifyFormat("T A::operator()();", SomeSpace); 14722 // FIXME these tests regressed behaviour. 14723 // verifyFormat("X A::operator++ (T);", SomeSpace); 14724 verifyFormat("int x = int (y);", SomeSpace); 14725 verifyFormat("auto lambda = []() { return 0; };", SomeSpace); 14726 14727 FormatStyle SpaceControlStatements = getLLVMStyle(); 14728 SpaceControlStatements.SpaceBeforeParens = FormatStyle::SBPO_Custom; 14729 SpaceControlStatements.SpaceBeforeParensOptions.AfterControlStatements = true; 14730 14731 verifyFormat("while (true)\n" 14732 " continue;", 14733 SpaceControlStatements); 14734 verifyFormat("if (true)\n" 14735 " f();\n" 14736 "else if (true)\n" 14737 " f();", 14738 SpaceControlStatements); 14739 verifyFormat("for (;;) {\n" 14740 " do_something();\n" 14741 "}", 14742 SpaceControlStatements); 14743 verifyFormat("do {\n" 14744 " do_something();\n" 14745 "} while (something());", 14746 SpaceControlStatements); 14747 verifyFormat("switch (x) {\n" 14748 "default:\n" 14749 " break;\n" 14750 "}", 14751 SpaceControlStatements); 14752 14753 FormatStyle SpaceFuncDecl = getLLVMStyle(); 14754 SpaceFuncDecl.SpaceBeforeParens = FormatStyle::SBPO_Custom; 14755 SpaceFuncDecl.SpaceBeforeParensOptions.AfterFunctionDeclarationName = true; 14756 14757 verifyFormat("int f ();", SpaceFuncDecl); 14758 verifyFormat("void f(int a, T b) {}", SpaceFuncDecl); 14759 verifyFormat("A::A() : a(1) {}", SpaceFuncDecl); 14760 verifyFormat("void f () __attribute__((asdf));", SpaceFuncDecl); 14761 verifyFormat("#define A(x) x", SpaceFuncDecl); 14762 verifyFormat("#define A (x) x", SpaceFuncDecl); 14763 verifyFormat("#if defined(x)\n" 14764 "#endif", 14765 SpaceFuncDecl); 14766 verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDecl); 14767 verifyFormat("size_t x = sizeof(x);", SpaceFuncDecl); 14768 verifyFormat("auto f (int x) -> decltype(x);", SpaceFuncDecl); 14769 verifyFormat("auto f (int x) -> typeof(x);", SpaceFuncDecl); 14770 verifyFormat("auto f (int x) -> _Atomic(x);", SpaceFuncDecl); 14771 verifyFormat("auto f (int x) -> __underlying_type(x);", SpaceFuncDecl); 14772 verifyFormat("int f (T x) noexcept(x.create());", SpaceFuncDecl); 14773 verifyFormat("alignas(128) char a[128];", SpaceFuncDecl); 14774 verifyFormat("size_t x = alignof(MyType);", SpaceFuncDecl); 14775 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", 14776 SpaceFuncDecl); 14777 verifyFormat("int f () throw(Deprecated);", SpaceFuncDecl); 14778 verifyFormat("typedef void (*cb)(int);", SpaceFuncDecl); 14779 // FIXME these tests regressed behaviour. 14780 // verifyFormat("T A::operator() ();", SpaceFuncDecl); 14781 // verifyFormat("X A::operator++ (T);", SpaceFuncDecl); 14782 verifyFormat("T A::operator()() {}", SpaceFuncDecl); 14783 verifyFormat("auto lambda = []() { return 0; };", SpaceFuncDecl); 14784 verifyFormat("int x = int(y);", SpaceFuncDecl); 14785 verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}", 14786 SpaceFuncDecl); 14787 14788 FormatStyle SpaceFuncDef = getLLVMStyle(); 14789 SpaceFuncDef.SpaceBeforeParens = FormatStyle::SBPO_Custom; 14790 SpaceFuncDef.SpaceBeforeParensOptions.AfterFunctionDefinitionName = true; 14791 14792 verifyFormat("int f();", SpaceFuncDef); 14793 verifyFormat("void f (int a, T b) {}", SpaceFuncDef); 14794 verifyFormat("A::A() : a(1) {}", SpaceFuncDef); 14795 verifyFormat("void f() __attribute__((asdf));", SpaceFuncDef); 14796 verifyFormat("#define A(x) x", SpaceFuncDef); 14797 verifyFormat("#define A (x) x", SpaceFuncDef); 14798 verifyFormat("#if defined(x)\n" 14799 "#endif", 14800 SpaceFuncDef); 14801 verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDef); 14802 verifyFormat("size_t x = sizeof(x);", SpaceFuncDef); 14803 verifyFormat("auto f(int x) -> decltype(x);", SpaceFuncDef); 14804 verifyFormat("auto f(int x) -> typeof(x);", SpaceFuncDef); 14805 verifyFormat("auto f(int x) -> _Atomic(x);", SpaceFuncDef); 14806 verifyFormat("auto f(int x) -> __underlying_type(x);", SpaceFuncDef); 14807 verifyFormat("int f(T x) noexcept(x.create());", SpaceFuncDef); 14808 verifyFormat("alignas(128) char a[128];", SpaceFuncDef); 14809 verifyFormat("size_t x = alignof(MyType);", SpaceFuncDef); 14810 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", 14811 SpaceFuncDef); 14812 verifyFormat("int f() throw(Deprecated);", SpaceFuncDef); 14813 verifyFormat("typedef void (*cb)(int);", SpaceFuncDef); 14814 verifyFormat("T A::operator()();", SpaceFuncDef); 14815 verifyFormat("X A::operator++(T);", SpaceFuncDef); 14816 // verifyFormat("T A::operator() () {}", SpaceFuncDef); 14817 verifyFormat("auto lambda = [] () { return 0; };", SpaceFuncDef); 14818 verifyFormat("int x = int(y);", SpaceFuncDef); 14819 verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}", 14820 SpaceFuncDef); 14821 14822 FormatStyle SpaceIfMacros = getLLVMStyle(); 14823 SpaceIfMacros.IfMacros.clear(); 14824 SpaceIfMacros.IfMacros.push_back("MYIF"); 14825 SpaceIfMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom; 14826 SpaceIfMacros.SpaceBeforeParensOptions.AfterIfMacros = true; 14827 verifyFormat("MYIF (a)\n return;", SpaceIfMacros); 14828 verifyFormat("MYIF (a)\n return;\nelse MYIF (b)\n return;", SpaceIfMacros); 14829 verifyFormat("MYIF (a)\n return;\nelse\n return;", SpaceIfMacros); 14830 14831 FormatStyle SpaceForeachMacros = getLLVMStyle(); 14832 EXPECT_EQ(SpaceForeachMacros.AllowShortBlocksOnASingleLine, 14833 FormatStyle::SBS_Never); 14834 EXPECT_EQ(SpaceForeachMacros.AllowShortLoopsOnASingleLine, false); 14835 SpaceForeachMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom; 14836 SpaceForeachMacros.SpaceBeforeParensOptions.AfterForeachMacros = true; 14837 verifyFormat("for (;;) {\n" 14838 "}", 14839 SpaceForeachMacros); 14840 verifyFormat("foreach (Item *item, itemlist) {\n" 14841 "}", 14842 SpaceForeachMacros); 14843 verifyFormat("Q_FOREACH (Item *item, itemlist) {\n" 14844 "}", 14845 SpaceForeachMacros); 14846 verifyFormat("BOOST_FOREACH (Item *item, itemlist) {\n" 14847 "}", 14848 SpaceForeachMacros); 14849 verifyFormat("UNKNOWN_FOREACH(Item *item, itemlist) {}", SpaceForeachMacros); 14850 14851 FormatStyle SomeSpace2 = getLLVMStyle(); 14852 SomeSpace2.SpaceBeforeParens = FormatStyle::SBPO_Custom; 14853 SomeSpace2.SpaceBeforeParensOptions.BeforeNonEmptyParentheses = true; 14854 verifyFormat("[]() -> float {}", SomeSpace2); 14855 verifyFormat("[] (auto foo) {}", SomeSpace2); 14856 verifyFormat("[foo]() -> int {}", SomeSpace2); 14857 verifyFormat("int f();", SomeSpace2); 14858 verifyFormat("void f (int a, T b) {\n" 14859 " while (true)\n" 14860 " continue;\n" 14861 "}", 14862 SomeSpace2); 14863 verifyFormat("if (true)\n" 14864 " f();\n" 14865 "else if (true)\n" 14866 " f();", 14867 SomeSpace2); 14868 verifyFormat("do {\n" 14869 " do_something();\n" 14870 "} while (something());", 14871 SomeSpace2); 14872 verifyFormat("switch (x) {\n" 14873 "default:\n" 14874 " break;\n" 14875 "}", 14876 SomeSpace2); 14877 verifyFormat("A::A() : a (1) {}", SomeSpace2); 14878 verifyFormat("void f() __attribute__ ((asdf));", SomeSpace2); 14879 verifyFormat("*(&a + 1);\n" 14880 "&((&a)[1]);\n" 14881 "a[(b + c) * d];\n" 14882 "(((a + 1) * 2) + 3) * 4;", 14883 SomeSpace2); 14884 verifyFormat("#define A(x) x", SomeSpace2); 14885 verifyFormat("#define A (x) x", SomeSpace2); 14886 verifyFormat("#if defined(x)\n" 14887 "#endif", 14888 SomeSpace2); 14889 verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace2); 14890 verifyFormat("size_t x = sizeof (x);", SomeSpace2); 14891 verifyFormat("auto f (int x) -> decltype (x);", SomeSpace2); 14892 verifyFormat("auto f (int x) -> typeof (x);", SomeSpace2); 14893 verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace2); 14894 verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace2); 14895 verifyFormat("int f (T x) noexcept (x.create());", SomeSpace2); 14896 verifyFormat("alignas (128) char a[128];", SomeSpace2); 14897 verifyFormat("size_t x = alignof (MyType);", SomeSpace2); 14898 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", 14899 SomeSpace2); 14900 verifyFormat("int f() throw (Deprecated);", SomeSpace2); 14901 verifyFormat("typedef void (*cb) (int);", SomeSpace2); 14902 verifyFormat("T A::operator()();", SomeSpace2); 14903 // verifyFormat("X A::operator++ (T);", SomeSpace2); 14904 verifyFormat("int x = int (y);", SomeSpace2); 14905 verifyFormat("auto lambda = []() { return 0; };", SomeSpace2); 14906 14907 FormatStyle SpaceAfterOverloadedOperator = getLLVMStyle(); 14908 SpaceAfterOverloadedOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom; 14909 SpaceAfterOverloadedOperator.SpaceBeforeParensOptions 14910 .AfterOverloadedOperator = true; 14911 14912 verifyFormat("auto operator++ () -> int;", SpaceAfterOverloadedOperator); 14913 verifyFormat("X A::operator++ ();", SpaceAfterOverloadedOperator); 14914 verifyFormat("some_object.operator++ ();", SpaceAfterOverloadedOperator); 14915 verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator); 14916 14917 SpaceAfterOverloadedOperator.SpaceBeforeParensOptions 14918 .AfterOverloadedOperator = false; 14919 14920 verifyFormat("auto operator++() -> int;", SpaceAfterOverloadedOperator); 14921 verifyFormat("X A::operator++();", SpaceAfterOverloadedOperator); 14922 verifyFormat("some_object.operator++();", SpaceAfterOverloadedOperator); 14923 verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator); 14924 } 14925 14926 TEST_F(FormatTest, SpaceAfterLogicalNot) { 14927 FormatStyle Spaces = getLLVMStyle(); 14928 Spaces.SpaceAfterLogicalNot = true; 14929 14930 verifyFormat("bool x = ! y", Spaces); 14931 verifyFormat("if (! isFailure())", Spaces); 14932 verifyFormat("if (! (a && b))", Spaces); 14933 verifyFormat("\"Error!\"", Spaces); 14934 verifyFormat("! ! x", Spaces); 14935 } 14936 14937 TEST_F(FormatTest, ConfigurableSpacesInParentheses) { 14938 FormatStyle Spaces = getLLVMStyle(); 14939 14940 Spaces.SpacesInParentheses = true; 14941 verifyFormat("do_something( ::globalVar );", Spaces); 14942 verifyFormat("call( x, y, z );", Spaces); 14943 verifyFormat("call();", Spaces); 14944 verifyFormat("std::function<void( int, int )> callback;", Spaces); 14945 verifyFormat("void inFunction() { std::function<void( int, int )> fct; }", 14946 Spaces); 14947 verifyFormat("while ( (bool)1 )\n" 14948 " continue;", 14949 Spaces); 14950 verifyFormat("for ( ;; )\n" 14951 " continue;", 14952 Spaces); 14953 verifyFormat("if ( true )\n" 14954 " f();\n" 14955 "else if ( true )\n" 14956 " f();", 14957 Spaces); 14958 verifyFormat("do {\n" 14959 " do_something( (int)i );\n" 14960 "} while ( something() );", 14961 Spaces); 14962 verifyFormat("switch ( x ) {\n" 14963 "default:\n" 14964 " break;\n" 14965 "}", 14966 Spaces); 14967 14968 Spaces.SpacesInParentheses = false; 14969 Spaces.SpacesInCStyleCastParentheses = true; 14970 verifyFormat("Type *A = ( Type * )P;", Spaces); 14971 verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces); 14972 verifyFormat("x = ( int32 )y;", Spaces); 14973 verifyFormat("int a = ( int )(2.0f);", Spaces); 14974 verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces); 14975 verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces); 14976 verifyFormat("#define x (( int )-1)", Spaces); 14977 14978 // Run the first set of tests again with: 14979 Spaces.SpacesInParentheses = false; 14980 Spaces.SpaceInEmptyParentheses = true; 14981 Spaces.SpacesInCStyleCastParentheses = true; 14982 verifyFormat("call(x, y, z);", Spaces); 14983 verifyFormat("call( );", Spaces); 14984 verifyFormat("std::function<void(int, int)> callback;", Spaces); 14985 verifyFormat("while (( bool )1)\n" 14986 " continue;", 14987 Spaces); 14988 verifyFormat("for (;;)\n" 14989 " continue;", 14990 Spaces); 14991 verifyFormat("if (true)\n" 14992 " f( );\n" 14993 "else if (true)\n" 14994 " f( );", 14995 Spaces); 14996 verifyFormat("do {\n" 14997 " do_something(( int )i);\n" 14998 "} while (something( ));", 14999 Spaces); 15000 verifyFormat("switch (x) {\n" 15001 "default:\n" 15002 " break;\n" 15003 "}", 15004 Spaces); 15005 15006 // Run the first set of tests again with: 15007 Spaces.SpaceAfterCStyleCast = true; 15008 verifyFormat("call(x, y, z);", Spaces); 15009 verifyFormat("call( );", Spaces); 15010 verifyFormat("std::function<void(int, int)> callback;", Spaces); 15011 verifyFormat("while (( bool ) 1)\n" 15012 " continue;", 15013 Spaces); 15014 verifyFormat("for (;;)\n" 15015 " continue;", 15016 Spaces); 15017 verifyFormat("if (true)\n" 15018 " f( );\n" 15019 "else if (true)\n" 15020 " f( );", 15021 Spaces); 15022 verifyFormat("do {\n" 15023 " do_something(( int ) i);\n" 15024 "} while (something( ));", 15025 Spaces); 15026 verifyFormat("switch (x) {\n" 15027 "default:\n" 15028 " break;\n" 15029 "}", 15030 Spaces); 15031 verifyFormat("#define CONF_BOOL(x) ( bool * ) ( void * ) (x)", Spaces); 15032 verifyFormat("#define CONF_BOOL(x) ( bool * ) (x)", Spaces); 15033 verifyFormat("#define CONF_BOOL(x) ( bool ) (x)", Spaces); 15034 verifyFormat("bool *y = ( bool * ) ( void * ) (x);", Spaces); 15035 verifyFormat("bool *y = ( bool * ) (x);", Spaces); 15036 15037 // Run subset of tests again with: 15038 Spaces.SpacesInCStyleCastParentheses = false; 15039 Spaces.SpaceAfterCStyleCast = true; 15040 verifyFormat("while ((bool) 1)\n" 15041 " continue;", 15042 Spaces); 15043 verifyFormat("do {\n" 15044 " do_something((int) i);\n" 15045 "} while (something( ));", 15046 Spaces); 15047 15048 verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces); 15049 verifyFormat("size_t idx = (size_t) a;", Spaces); 15050 verifyFormat("size_t idx = (size_t) (a - 1);", Spaces); 15051 verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces); 15052 verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces); 15053 verifyFormat("size_t idx = (*foo)(a - 1);", Spaces); 15054 verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces); 15055 verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (x)", Spaces); 15056 verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (int) (x)", Spaces); 15057 verifyFormat("bool *y = (bool *) (void *) (x);", Spaces); 15058 verifyFormat("bool *y = (bool *) (void *) (int) (x);", Spaces); 15059 verifyFormat("bool *y = (bool *) (void *) (int) foo(x);", Spaces); 15060 Spaces.ColumnLimit = 80; 15061 Spaces.IndentWidth = 4; 15062 Spaces.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 15063 verifyFormat("void foo( ) {\n" 15064 " size_t foo = (*(function))(\n" 15065 " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, " 15066 "BarrrrrrrrrrrrLong,\n" 15067 " FoooooooooLooooong);\n" 15068 "}", 15069 Spaces); 15070 Spaces.SpaceAfterCStyleCast = false; 15071 verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces); 15072 verifyFormat("size_t idx = (size_t)a;", Spaces); 15073 verifyFormat("size_t idx = (size_t)(a - 1);", Spaces); 15074 verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces); 15075 verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces); 15076 verifyFormat("size_t idx = (*foo)(a - 1);", Spaces); 15077 verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces); 15078 15079 verifyFormat("void foo( ) {\n" 15080 " size_t foo = (*(function))(\n" 15081 " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, " 15082 "BarrrrrrrrrrrrLong,\n" 15083 " FoooooooooLooooong);\n" 15084 "}", 15085 Spaces); 15086 } 15087 15088 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) { 15089 verifyFormat("int a[5];"); 15090 verifyFormat("a[3] += 42;"); 15091 15092 FormatStyle Spaces = getLLVMStyle(); 15093 Spaces.SpacesInSquareBrackets = true; 15094 // Not lambdas. 15095 verifyFormat("int a[ 5 ];", Spaces); 15096 verifyFormat("a[ 3 ] += 42;", Spaces); 15097 verifyFormat("constexpr char hello[]{\"hello\"};", Spaces); 15098 verifyFormat("double &operator[](int i) { return 0; }\n" 15099 "int i;", 15100 Spaces); 15101 verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces); 15102 verifyFormat("int i = a[ a ][ a ]->f();", Spaces); 15103 verifyFormat("int i = (*b)[ a ]->f();", Spaces); 15104 // Lambdas. 15105 verifyFormat("int c = []() -> int { return 2; }();\n", Spaces); 15106 verifyFormat("return [ i, args... ] {};", Spaces); 15107 verifyFormat("int foo = [ &bar ]() {};", Spaces); 15108 verifyFormat("int foo = [ = ]() {};", Spaces); 15109 verifyFormat("int foo = [ & ]() {};", Spaces); 15110 verifyFormat("int foo = [ =, &bar ]() {};", Spaces); 15111 verifyFormat("int foo = [ &bar, = ]() {};", Spaces); 15112 } 15113 15114 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) { 15115 FormatStyle NoSpaceStyle = getLLVMStyle(); 15116 verifyFormat("int a[5];", NoSpaceStyle); 15117 verifyFormat("a[3] += 42;", NoSpaceStyle); 15118 15119 verifyFormat("int a[1];", NoSpaceStyle); 15120 verifyFormat("int 1 [a];", NoSpaceStyle); 15121 verifyFormat("int a[1][2];", NoSpaceStyle); 15122 verifyFormat("a[7] = 5;", NoSpaceStyle); 15123 verifyFormat("int a = (f())[23];", NoSpaceStyle); 15124 verifyFormat("f([] {})", NoSpaceStyle); 15125 15126 FormatStyle Space = getLLVMStyle(); 15127 Space.SpaceBeforeSquareBrackets = true; 15128 verifyFormat("int c = []() -> int { return 2; }();\n", Space); 15129 verifyFormat("return [i, args...] {};", Space); 15130 15131 verifyFormat("int a [5];", Space); 15132 verifyFormat("a [3] += 42;", Space); 15133 verifyFormat("constexpr char hello []{\"hello\"};", Space); 15134 verifyFormat("double &operator[](int i) { return 0; }\n" 15135 "int i;", 15136 Space); 15137 verifyFormat("std::unique_ptr<int []> foo() {}", Space); 15138 verifyFormat("int i = a [a][a]->f();", Space); 15139 verifyFormat("int i = (*b) [a]->f();", Space); 15140 15141 verifyFormat("int a [1];", Space); 15142 verifyFormat("int 1 [a];", Space); 15143 verifyFormat("int a [1][2];", Space); 15144 verifyFormat("a [7] = 5;", Space); 15145 verifyFormat("int a = (f()) [23];", Space); 15146 verifyFormat("f([] {})", Space); 15147 } 15148 15149 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) { 15150 verifyFormat("int a = 5;"); 15151 verifyFormat("a += 42;"); 15152 verifyFormat("a or_eq 8;"); 15153 15154 FormatStyle Spaces = getLLVMStyle(); 15155 Spaces.SpaceBeforeAssignmentOperators = false; 15156 verifyFormat("int a= 5;", Spaces); 15157 verifyFormat("a+= 42;", Spaces); 15158 verifyFormat("a or_eq 8;", Spaces); 15159 } 15160 15161 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) { 15162 verifyFormat("class Foo : public Bar {};"); 15163 verifyFormat("Foo::Foo() : foo(1) {}"); 15164 verifyFormat("for (auto a : b) {\n}"); 15165 verifyFormat("int x = a ? b : c;"); 15166 verifyFormat("{\n" 15167 "label0:\n" 15168 " int x = 0;\n" 15169 "}"); 15170 verifyFormat("switch (x) {\n" 15171 "case 1:\n" 15172 "default:\n" 15173 "}"); 15174 verifyFormat("switch (allBraces) {\n" 15175 "case 1: {\n" 15176 " break;\n" 15177 "}\n" 15178 "case 2: {\n" 15179 " [[fallthrough]];\n" 15180 "}\n" 15181 "default: {\n" 15182 " break;\n" 15183 "}\n" 15184 "}"); 15185 15186 FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30); 15187 CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false; 15188 verifyFormat("class Foo : public Bar {};", CtorInitializerStyle); 15189 verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle); 15190 verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle); 15191 verifyFormat("int x = a ? b : c;", CtorInitializerStyle); 15192 verifyFormat("{\n" 15193 "label1:\n" 15194 " int x = 0;\n" 15195 "}", 15196 CtorInitializerStyle); 15197 verifyFormat("switch (x) {\n" 15198 "case 1:\n" 15199 "default:\n" 15200 "}", 15201 CtorInitializerStyle); 15202 verifyFormat("switch (allBraces) {\n" 15203 "case 1: {\n" 15204 " break;\n" 15205 "}\n" 15206 "case 2: {\n" 15207 " [[fallthrough]];\n" 15208 "}\n" 15209 "default: {\n" 15210 " break;\n" 15211 "}\n" 15212 "}", 15213 CtorInitializerStyle); 15214 CtorInitializerStyle.BreakConstructorInitializers = 15215 FormatStyle::BCIS_AfterColon; 15216 verifyFormat("Fooooooooooo::Fooooooooooo():\n" 15217 " aaaaaaaaaaaaaaaa(1),\n" 15218 " bbbbbbbbbbbbbbbb(2) {}", 15219 CtorInitializerStyle); 15220 CtorInitializerStyle.BreakConstructorInitializers = 15221 FormatStyle::BCIS_BeforeComma; 15222 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15223 " : aaaaaaaaaaaaaaaa(1)\n" 15224 " , bbbbbbbbbbbbbbbb(2) {}", 15225 CtorInitializerStyle); 15226 CtorInitializerStyle.BreakConstructorInitializers = 15227 FormatStyle::BCIS_BeforeColon; 15228 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15229 " : aaaaaaaaaaaaaaaa(1),\n" 15230 " bbbbbbbbbbbbbbbb(2) {}", 15231 CtorInitializerStyle); 15232 CtorInitializerStyle.ConstructorInitializerIndentWidth = 0; 15233 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15234 ": aaaaaaaaaaaaaaaa(1),\n" 15235 " bbbbbbbbbbbbbbbb(2) {}", 15236 CtorInitializerStyle); 15237 15238 FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30); 15239 InheritanceStyle.SpaceBeforeInheritanceColon = false; 15240 verifyFormat("class Foo: public Bar {};", InheritanceStyle); 15241 verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle); 15242 verifyFormat("for (auto a : b) {\n}", InheritanceStyle); 15243 verifyFormat("int x = a ? b : c;", InheritanceStyle); 15244 verifyFormat("{\n" 15245 "label2:\n" 15246 " int x = 0;\n" 15247 "}", 15248 InheritanceStyle); 15249 verifyFormat("switch (x) {\n" 15250 "case 1:\n" 15251 "default:\n" 15252 "}", 15253 InheritanceStyle); 15254 verifyFormat("switch (allBraces) {\n" 15255 "case 1: {\n" 15256 " break;\n" 15257 "}\n" 15258 "case 2: {\n" 15259 " [[fallthrough]];\n" 15260 "}\n" 15261 "default: {\n" 15262 " break;\n" 15263 "}\n" 15264 "}", 15265 InheritanceStyle); 15266 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterComma; 15267 verifyFormat("class Foooooooooooooooooooooo\n" 15268 " : public aaaaaaaaaaaaaaaaaa,\n" 15269 " public bbbbbbbbbbbbbbbbbb {\n" 15270 "}", 15271 InheritanceStyle); 15272 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon; 15273 verifyFormat("class Foooooooooooooooooooooo:\n" 15274 " public aaaaaaaaaaaaaaaaaa,\n" 15275 " public bbbbbbbbbbbbbbbbbb {\n" 15276 "}", 15277 InheritanceStyle); 15278 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma; 15279 verifyFormat("class Foooooooooooooooooooooo\n" 15280 " : public aaaaaaaaaaaaaaaaaa\n" 15281 " , public bbbbbbbbbbbbbbbbbb {\n" 15282 "}", 15283 InheritanceStyle); 15284 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 15285 verifyFormat("class Foooooooooooooooooooooo\n" 15286 " : public aaaaaaaaaaaaaaaaaa,\n" 15287 " public bbbbbbbbbbbbbbbbbb {\n" 15288 "}", 15289 InheritanceStyle); 15290 InheritanceStyle.ConstructorInitializerIndentWidth = 0; 15291 verifyFormat("class Foooooooooooooooooooooo\n" 15292 ": public aaaaaaaaaaaaaaaaaa,\n" 15293 " public bbbbbbbbbbbbbbbbbb {}", 15294 InheritanceStyle); 15295 15296 FormatStyle ForLoopStyle = getLLVMStyle(); 15297 ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false; 15298 verifyFormat("class Foo : public Bar {};", ForLoopStyle); 15299 verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle); 15300 verifyFormat("for (auto a: b) {\n}", ForLoopStyle); 15301 verifyFormat("int x = a ? b : c;", ForLoopStyle); 15302 verifyFormat("{\n" 15303 "label2:\n" 15304 " int x = 0;\n" 15305 "}", 15306 ForLoopStyle); 15307 verifyFormat("switch (x) {\n" 15308 "case 1:\n" 15309 "default:\n" 15310 "}", 15311 ForLoopStyle); 15312 verifyFormat("switch (allBraces) {\n" 15313 "case 1: {\n" 15314 " break;\n" 15315 "}\n" 15316 "case 2: {\n" 15317 " [[fallthrough]];\n" 15318 "}\n" 15319 "default: {\n" 15320 " break;\n" 15321 "}\n" 15322 "}", 15323 ForLoopStyle); 15324 15325 FormatStyle CaseStyle = getLLVMStyle(); 15326 CaseStyle.SpaceBeforeCaseColon = true; 15327 verifyFormat("class Foo : public Bar {};", CaseStyle); 15328 verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle); 15329 verifyFormat("for (auto a : b) {\n}", CaseStyle); 15330 verifyFormat("int x = a ? b : c;", CaseStyle); 15331 verifyFormat("switch (x) {\n" 15332 "case 1 :\n" 15333 "default :\n" 15334 "}", 15335 CaseStyle); 15336 verifyFormat("switch (allBraces) {\n" 15337 "case 1 : {\n" 15338 " break;\n" 15339 "}\n" 15340 "case 2 : {\n" 15341 " [[fallthrough]];\n" 15342 "}\n" 15343 "default : {\n" 15344 " break;\n" 15345 "}\n" 15346 "}", 15347 CaseStyle); 15348 15349 FormatStyle NoSpaceStyle = getLLVMStyle(); 15350 EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false); 15351 NoSpaceStyle.SpaceBeforeCtorInitializerColon = false; 15352 NoSpaceStyle.SpaceBeforeInheritanceColon = false; 15353 NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false; 15354 verifyFormat("class Foo: public Bar {};", NoSpaceStyle); 15355 verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle); 15356 verifyFormat("for (auto a: b) {\n}", NoSpaceStyle); 15357 verifyFormat("int x = a ? b : c;", NoSpaceStyle); 15358 verifyFormat("{\n" 15359 "label3:\n" 15360 " int x = 0;\n" 15361 "}", 15362 NoSpaceStyle); 15363 verifyFormat("switch (x) {\n" 15364 "case 1:\n" 15365 "default:\n" 15366 "}", 15367 NoSpaceStyle); 15368 verifyFormat("switch (allBraces) {\n" 15369 "case 1: {\n" 15370 " break;\n" 15371 "}\n" 15372 "case 2: {\n" 15373 " [[fallthrough]];\n" 15374 "}\n" 15375 "default: {\n" 15376 " break;\n" 15377 "}\n" 15378 "}", 15379 NoSpaceStyle); 15380 15381 FormatStyle InvertedSpaceStyle = getLLVMStyle(); 15382 InvertedSpaceStyle.SpaceBeforeCaseColon = true; 15383 InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false; 15384 InvertedSpaceStyle.SpaceBeforeInheritanceColon = false; 15385 InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false; 15386 verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle); 15387 verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle); 15388 verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle); 15389 verifyFormat("int x = a ? b : c;", InvertedSpaceStyle); 15390 verifyFormat("{\n" 15391 "label3:\n" 15392 " int x = 0;\n" 15393 "}", 15394 InvertedSpaceStyle); 15395 verifyFormat("switch (x) {\n" 15396 "case 1 :\n" 15397 "case 2 : {\n" 15398 " break;\n" 15399 "}\n" 15400 "default :\n" 15401 " break;\n" 15402 "}", 15403 InvertedSpaceStyle); 15404 verifyFormat("switch (allBraces) {\n" 15405 "case 1 : {\n" 15406 " break;\n" 15407 "}\n" 15408 "case 2 : {\n" 15409 " [[fallthrough]];\n" 15410 "}\n" 15411 "default : {\n" 15412 " break;\n" 15413 "}\n" 15414 "}", 15415 InvertedSpaceStyle); 15416 } 15417 15418 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) { 15419 FormatStyle Style = getLLVMStyle(); 15420 15421 Style.PointerAlignment = FormatStyle::PAS_Left; 15422 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default; 15423 verifyFormat("void* const* x = NULL;", Style); 15424 15425 #define verifyQualifierSpaces(Code, Pointers, Qualifiers) \ 15426 do { \ 15427 Style.PointerAlignment = FormatStyle::Pointers; \ 15428 Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers; \ 15429 verifyFormat(Code, Style); \ 15430 } while (false) 15431 15432 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default); 15433 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default); 15434 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default); 15435 15436 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before); 15437 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before); 15438 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before); 15439 15440 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After); 15441 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After); 15442 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After); 15443 15444 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both); 15445 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both); 15446 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both); 15447 15448 verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default); 15449 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, 15450 SAPQ_Default); 15451 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15452 SAPQ_Default); 15453 15454 verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before); 15455 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, 15456 SAPQ_Before); 15457 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15458 SAPQ_Before); 15459 15460 verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After); 15461 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After); 15462 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15463 SAPQ_After); 15464 15465 verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both); 15466 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both); 15467 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both); 15468 15469 #undef verifyQualifierSpaces 15470 15471 FormatStyle Spaces = getLLVMStyle(); 15472 Spaces.AttributeMacros.push_back("qualified"); 15473 Spaces.PointerAlignment = FormatStyle::PAS_Right; 15474 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default; 15475 verifyFormat("SomeType *volatile *a = NULL;", Spaces); 15476 verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces); 15477 verifyFormat("std::vector<SomeType *const *> x;", Spaces); 15478 verifyFormat("std::vector<SomeType *qualified *> x;", Spaces); 15479 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15480 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before; 15481 verifyFormat("SomeType * volatile *a = NULL;", Spaces); 15482 verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces); 15483 verifyFormat("std::vector<SomeType * const *> x;", Spaces); 15484 verifyFormat("std::vector<SomeType * qualified *> x;", Spaces); 15485 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15486 15487 // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left. 15488 Spaces.PointerAlignment = FormatStyle::PAS_Left; 15489 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before; 15490 verifyFormat("SomeType* volatile* a = NULL;", Spaces); 15491 verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces); 15492 verifyFormat("std::vector<SomeType* const*> x;", Spaces); 15493 verifyFormat("std::vector<SomeType* qualified*> x;", Spaces); 15494 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15495 // However, setting it to SAPQ_After should add spaces after __attribute, etc. 15496 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After; 15497 verifyFormat("SomeType* volatile * a = NULL;", Spaces); 15498 verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces); 15499 verifyFormat("std::vector<SomeType* const *> x;", Spaces); 15500 verifyFormat("std::vector<SomeType* qualified *> x;", Spaces); 15501 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15502 15503 // PAS_Middle should not have any noticeable changes even for SAPQ_Both 15504 Spaces.PointerAlignment = FormatStyle::PAS_Middle; 15505 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After; 15506 verifyFormat("SomeType * volatile * a = NULL;", Spaces); 15507 verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces); 15508 verifyFormat("std::vector<SomeType * const *> x;", Spaces); 15509 verifyFormat("std::vector<SomeType * qualified *> x;", Spaces); 15510 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15511 } 15512 15513 TEST_F(FormatTest, AlignConsecutiveMacros) { 15514 FormatStyle Style = getLLVMStyle(); 15515 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 15516 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 15517 Style.AlignConsecutiveMacros = FormatStyle::ACS_None; 15518 15519 verifyFormat("#define a 3\n" 15520 "#define bbbb 4\n" 15521 "#define ccc (5)", 15522 Style); 15523 15524 verifyFormat("#define f(x) (x * x)\n" 15525 "#define fff(x, y, z) (x * y + z)\n" 15526 "#define ffff(x, y) (x - y)", 15527 Style); 15528 15529 verifyFormat("#define foo(x, y) (x + y)\n" 15530 "#define bar (5, 6)(2 + 2)", 15531 Style); 15532 15533 verifyFormat("#define a 3\n" 15534 "#define bbbb 4\n" 15535 "#define ccc (5)\n" 15536 "#define f(x) (x * x)\n" 15537 "#define fff(x, y, z) (x * y + z)\n" 15538 "#define ffff(x, y) (x - y)", 15539 Style); 15540 15541 Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 15542 verifyFormat("#define a 3\n" 15543 "#define bbbb 4\n" 15544 "#define ccc (5)", 15545 Style); 15546 15547 verifyFormat("#define f(x) (x * x)\n" 15548 "#define fff(x, y, z) (x * y + z)\n" 15549 "#define ffff(x, y) (x - y)", 15550 Style); 15551 15552 verifyFormat("#define foo(x, y) (x + y)\n" 15553 "#define bar (5, 6)(2 + 2)", 15554 Style); 15555 15556 verifyFormat("#define a 3\n" 15557 "#define bbbb 4\n" 15558 "#define ccc (5)\n" 15559 "#define f(x) (x * x)\n" 15560 "#define fff(x, y, z) (x * y + z)\n" 15561 "#define ffff(x, y) (x - y)", 15562 Style); 15563 15564 verifyFormat("#define a 5\n" 15565 "#define foo(x, y) (x + y)\n" 15566 "#define CCC (6)\n" 15567 "auto lambda = []() {\n" 15568 " auto ii = 0;\n" 15569 " float j = 0;\n" 15570 " return 0;\n" 15571 "};\n" 15572 "int i = 0;\n" 15573 "float i2 = 0;\n" 15574 "auto v = type{\n" 15575 " i = 1, //\n" 15576 " (i = 2), //\n" 15577 " i = 3 //\n" 15578 "};", 15579 Style); 15580 15581 Style.AlignConsecutiveMacros = FormatStyle::ACS_None; 15582 Style.ColumnLimit = 20; 15583 15584 verifyFormat("#define a \\\n" 15585 " \"aabbbbbbbbbbbb\"\n" 15586 "#define D \\\n" 15587 " \"aabbbbbbbbbbbb\" \\\n" 15588 " \"ccddeeeeeeeee\"\n" 15589 "#define B \\\n" 15590 " \"QQQQQQQQQQQQQ\" \\\n" 15591 " \"FFFFFFFFFFFFF\" \\\n" 15592 " \"LLLLLLLL\"\n", 15593 Style); 15594 15595 Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 15596 verifyFormat("#define a \\\n" 15597 " \"aabbbbbbbbbbbb\"\n" 15598 "#define D \\\n" 15599 " \"aabbbbbbbbbbbb\" \\\n" 15600 " \"ccddeeeeeeeee\"\n" 15601 "#define B \\\n" 15602 " \"QQQQQQQQQQQQQ\" \\\n" 15603 " \"FFFFFFFFFFFFF\" \\\n" 15604 " \"LLLLLLLL\"\n", 15605 Style); 15606 15607 // Test across comments 15608 Style.MaxEmptyLinesToKeep = 10; 15609 Style.ReflowComments = false; 15610 Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossComments; 15611 EXPECT_EQ("#define a 3\n" 15612 "// line comment\n" 15613 "#define bbbb 4\n" 15614 "#define ccc (5)", 15615 format("#define a 3\n" 15616 "// line comment\n" 15617 "#define bbbb 4\n" 15618 "#define ccc (5)", 15619 Style)); 15620 15621 EXPECT_EQ("#define a 3\n" 15622 "/* block comment */\n" 15623 "#define bbbb 4\n" 15624 "#define ccc (5)", 15625 format("#define a 3\n" 15626 "/* block comment */\n" 15627 "#define bbbb 4\n" 15628 "#define ccc (5)", 15629 Style)); 15630 15631 EXPECT_EQ("#define a 3\n" 15632 "/* multi-line *\n" 15633 " * block comment */\n" 15634 "#define bbbb 4\n" 15635 "#define ccc (5)", 15636 format("#define a 3\n" 15637 "/* multi-line *\n" 15638 " * block comment */\n" 15639 "#define bbbb 4\n" 15640 "#define ccc (5)", 15641 Style)); 15642 15643 EXPECT_EQ("#define a 3\n" 15644 "// multi-line line comment\n" 15645 "//\n" 15646 "#define bbbb 4\n" 15647 "#define ccc (5)", 15648 format("#define a 3\n" 15649 "// multi-line line comment\n" 15650 "//\n" 15651 "#define bbbb 4\n" 15652 "#define ccc (5)", 15653 Style)); 15654 15655 EXPECT_EQ("#define a 3\n" 15656 "// empty lines still break.\n" 15657 "\n" 15658 "#define bbbb 4\n" 15659 "#define ccc (5)", 15660 format("#define a 3\n" 15661 "// empty lines still break.\n" 15662 "\n" 15663 "#define bbbb 4\n" 15664 "#define ccc (5)", 15665 Style)); 15666 15667 // Test across empty lines 15668 Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLines; 15669 EXPECT_EQ("#define a 3\n" 15670 "\n" 15671 "#define bbbb 4\n" 15672 "#define ccc (5)", 15673 format("#define a 3\n" 15674 "\n" 15675 "#define bbbb 4\n" 15676 "#define ccc (5)", 15677 Style)); 15678 15679 EXPECT_EQ("#define a 3\n" 15680 "\n" 15681 "\n" 15682 "\n" 15683 "#define bbbb 4\n" 15684 "#define ccc (5)", 15685 format("#define a 3\n" 15686 "\n" 15687 "\n" 15688 "\n" 15689 "#define bbbb 4\n" 15690 "#define ccc (5)", 15691 Style)); 15692 15693 EXPECT_EQ("#define a 3\n" 15694 "// comments should break alignment\n" 15695 "//\n" 15696 "#define bbbb 4\n" 15697 "#define ccc (5)", 15698 format("#define a 3\n" 15699 "// comments should break alignment\n" 15700 "//\n" 15701 "#define bbbb 4\n" 15702 "#define ccc (5)", 15703 Style)); 15704 15705 // Test across empty lines and comments 15706 Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLinesAndComments; 15707 verifyFormat("#define a 3\n" 15708 "\n" 15709 "// line comment\n" 15710 "#define bbbb 4\n" 15711 "#define ccc (5)", 15712 Style); 15713 15714 EXPECT_EQ("#define a 3\n" 15715 "\n" 15716 "\n" 15717 "/* multi-line *\n" 15718 " * block comment */\n" 15719 "\n" 15720 "\n" 15721 "#define bbbb 4\n" 15722 "#define ccc (5)", 15723 format("#define a 3\n" 15724 "\n" 15725 "\n" 15726 "/* multi-line *\n" 15727 " * block comment */\n" 15728 "\n" 15729 "\n" 15730 "#define bbbb 4\n" 15731 "#define ccc (5)", 15732 Style)); 15733 15734 EXPECT_EQ("#define a 3\n" 15735 "\n" 15736 "\n" 15737 "/* multi-line *\n" 15738 " * block comment */\n" 15739 "\n" 15740 "\n" 15741 "#define bbbb 4\n" 15742 "#define ccc (5)", 15743 format("#define a 3\n" 15744 "\n" 15745 "\n" 15746 "/* multi-line *\n" 15747 " * block comment */\n" 15748 "\n" 15749 "\n" 15750 "#define bbbb 4\n" 15751 "#define ccc (5)", 15752 Style)); 15753 } 15754 15755 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) { 15756 FormatStyle Alignment = getLLVMStyle(); 15757 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 15758 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossEmptyLines; 15759 15760 Alignment.MaxEmptyLinesToKeep = 10; 15761 /* Test alignment across empty lines */ 15762 EXPECT_EQ("int a = 5;\n" 15763 "\n" 15764 "int oneTwoThree = 123;", 15765 format("int a = 5;\n" 15766 "\n" 15767 "int oneTwoThree= 123;", 15768 Alignment)); 15769 EXPECT_EQ("int a = 5;\n" 15770 "int one = 1;\n" 15771 "\n" 15772 "int oneTwoThree = 123;", 15773 format("int a = 5;\n" 15774 "int one = 1;\n" 15775 "\n" 15776 "int oneTwoThree = 123;", 15777 Alignment)); 15778 EXPECT_EQ("int a = 5;\n" 15779 "int one = 1;\n" 15780 "\n" 15781 "int oneTwoThree = 123;\n" 15782 "int oneTwo = 12;", 15783 format("int a = 5;\n" 15784 "int one = 1;\n" 15785 "\n" 15786 "int oneTwoThree = 123;\n" 15787 "int oneTwo = 12;", 15788 Alignment)); 15789 15790 /* Test across comments */ 15791 EXPECT_EQ("int a = 5;\n" 15792 "/* block comment */\n" 15793 "int oneTwoThree = 123;", 15794 format("int a = 5;\n" 15795 "/* block comment */\n" 15796 "int oneTwoThree=123;", 15797 Alignment)); 15798 15799 EXPECT_EQ("int a = 5;\n" 15800 "// line comment\n" 15801 "int oneTwoThree = 123;", 15802 format("int a = 5;\n" 15803 "// line comment\n" 15804 "int oneTwoThree=123;", 15805 Alignment)); 15806 15807 /* Test across comments and newlines */ 15808 EXPECT_EQ("int a = 5;\n" 15809 "\n" 15810 "/* block comment */\n" 15811 "int oneTwoThree = 123;", 15812 format("int a = 5;\n" 15813 "\n" 15814 "/* block comment */\n" 15815 "int oneTwoThree=123;", 15816 Alignment)); 15817 15818 EXPECT_EQ("int a = 5;\n" 15819 "\n" 15820 "// line comment\n" 15821 "int oneTwoThree = 123;", 15822 format("int a = 5;\n" 15823 "\n" 15824 "// line comment\n" 15825 "int oneTwoThree=123;", 15826 Alignment)); 15827 } 15828 15829 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) { 15830 FormatStyle Alignment = getLLVMStyle(); 15831 Alignment.AlignConsecutiveDeclarations = 15832 FormatStyle::ACS_AcrossEmptyLinesAndComments; 15833 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 15834 15835 Alignment.MaxEmptyLinesToKeep = 10; 15836 /* Test alignment across empty lines */ 15837 EXPECT_EQ("int a = 5;\n" 15838 "\n" 15839 "float const oneTwoThree = 123;", 15840 format("int a = 5;\n" 15841 "\n" 15842 "float const oneTwoThree = 123;", 15843 Alignment)); 15844 EXPECT_EQ("int a = 5;\n" 15845 "float const one = 1;\n" 15846 "\n" 15847 "int oneTwoThree = 123;", 15848 format("int a = 5;\n" 15849 "float const one = 1;\n" 15850 "\n" 15851 "int oneTwoThree = 123;", 15852 Alignment)); 15853 15854 /* Test across comments */ 15855 EXPECT_EQ("float const a = 5;\n" 15856 "/* block comment */\n" 15857 "int oneTwoThree = 123;", 15858 format("float const a = 5;\n" 15859 "/* block comment */\n" 15860 "int oneTwoThree=123;", 15861 Alignment)); 15862 15863 EXPECT_EQ("float const a = 5;\n" 15864 "// line comment\n" 15865 "int oneTwoThree = 123;", 15866 format("float const a = 5;\n" 15867 "// line comment\n" 15868 "int oneTwoThree=123;", 15869 Alignment)); 15870 15871 /* Test across comments and newlines */ 15872 EXPECT_EQ("float const a = 5;\n" 15873 "\n" 15874 "/* block comment */\n" 15875 "int oneTwoThree = 123;", 15876 format("float const a = 5;\n" 15877 "\n" 15878 "/* block comment */\n" 15879 "int oneTwoThree=123;", 15880 Alignment)); 15881 15882 EXPECT_EQ("float const a = 5;\n" 15883 "\n" 15884 "// line comment\n" 15885 "int oneTwoThree = 123;", 15886 format("float const a = 5;\n" 15887 "\n" 15888 "// line comment\n" 15889 "int oneTwoThree=123;", 15890 Alignment)); 15891 } 15892 15893 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) { 15894 FormatStyle Alignment = getLLVMStyle(); 15895 Alignment.AlignConsecutiveBitFields = 15896 FormatStyle::ACS_AcrossEmptyLinesAndComments; 15897 15898 Alignment.MaxEmptyLinesToKeep = 10; 15899 /* Test alignment across empty lines */ 15900 EXPECT_EQ("int a : 5;\n" 15901 "\n" 15902 "int longbitfield : 6;", 15903 format("int a : 5;\n" 15904 "\n" 15905 "int longbitfield : 6;", 15906 Alignment)); 15907 EXPECT_EQ("int a : 5;\n" 15908 "int one : 1;\n" 15909 "\n" 15910 "int longbitfield : 6;", 15911 format("int a : 5;\n" 15912 "int one : 1;\n" 15913 "\n" 15914 "int longbitfield : 6;", 15915 Alignment)); 15916 15917 /* Test across comments */ 15918 EXPECT_EQ("int a : 5;\n" 15919 "/* block comment */\n" 15920 "int longbitfield : 6;", 15921 format("int a : 5;\n" 15922 "/* block comment */\n" 15923 "int longbitfield : 6;", 15924 Alignment)); 15925 EXPECT_EQ("int a : 5;\n" 15926 "int one : 1;\n" 15927 "// line comment\n" 15928 "int longbitfield : 6;", 15929 format("int a : 5;\n" 15930 "int one : 1;\n" 15931 "// line comment\n" 15932 "int longbitfield : 6;", 15933 Alignment)); 15934 15935 /* Test across comments and newlines */ 15936 EXPECT_EQ("int a : 5;\n" 15937 "/* block comment */\n" 15938 "\n" 15939 "int longbitfield : 6;", 15940 format("int a : 5;\n" 15941 "/* block comment */\n" 15942 "\n" 15943 "int longbitfield : 6;", 15944 Alignment)); 15945 EXPECT_EQ("int a : 5;\n" 15946 "int one : 1;\n" 15947 "\n" 15948 "// line comment\n" 15949 "\n" 15950 "int longbitfield : 6;", 15951 format("int a : 5;\n" 15952 "int one : 1;\n" 15953 "\n" 15954 "// line comment \n" 15955 "\n" 15956 "int longbitfield : 6;", 15957 Alignment)); 15958 } 15959 15960 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) { 15961 FormatStyle Alignment = getLLVMStyle(); 15962 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 15963 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossComments; 15964 15965 Alignment.MaxEmptyLinesToKeep = 10; 15966 /* Test alignment across empty lines */ 15967 EXPECT_EQ("int a = 5;\n" 15968 "\n" 15969 "int oneTwoThree = 123;", 15970 format("int a = 5;\n" 15971 "\n" 15972 "int oneTwoThree= 123;", 15973 Alignment)); 15974 EXPECT_EQ("int a = 5;\n" 15975 "int one = 1;\n" 15976 "\n" 15977 "int oneTwoThree = 123;", 15978 format("int a = 5;\n" 15979 "int one = 1;\n" 15980 "\n" 15981 "int oneTwoThree = 123;", 15982 Alignment)); 15983 15984 /* Test across comments */ 15985 EXPECT_EQ("int a = 5;\n" 15986 "/* block comment */\n" 15987 "int oneTwoThree = 123;", 15988 format("int a = 5;\n" 15989 "/* block comment */\n" 15990 "int oneTwoThree=123;", 15991 Alignment)); 15992 15993 EXPECT_EQ("int a = 5;\n" 15994 "// line comment\n" 15995 "int oneTwoThree = 123;", 15996 format("int a = 5;\n" 15997 "// line comment\n" 15998 "int oneTwoThree=123;", 15999 Alignment)); 16000 16001 EXPECT_EQ("int a = 5;\n" 16002 "/*\n" 16003 " * multi-line block comment\n" 16004 " */\n" 16005 "int oneTwoThree = 123;", 16006 format("int a = 5;\n" 16007 "/*\n" 16008 " * multi-line block comment\n" 16009 " */\n" 16010 "int oneTwoThree=123;", 16011 Alignment)); 16012 16013 EXPECT_EQ("int a = 5;\n" 16014 "//\n" 16015 "// multi-line line comment\n" 16016 "//\n" 16017 "int oneTwoThree = 123;", 16018 format("int a = 5;\n" 16019 "//\n" 16020 "// multi-line line comment\n" 16021 "//\n" 16022 "int oneTwoThree=123;", 16023 Alignment)); 16024 16025 /* Test across comments and newlines */ 16026 EXPECT_EQ("int a = 5;\n" 16027 "\n" 16028 "/* block comment */\n" 16029 "int oneTwoThree = 123;", 16030 format("int a = 5;\n" 16031 "\n" 16032 "/* block comment */\n" 16033 "int oneTwoThree=123;", 16034 Alignment)); 16035 16036 EXPECT_EQ("int a = 5;\n" 16037 "\n" 16038 "// line comment\n" 16039 "int oneTwoThree = 123;", 16040 format("int a = 5;\n" 16041 "\n" 16042 "// line comment\n" 16043 "int oneTwoThree=123;", 16044 Alignment)); 16045 } 16046 16047 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) { 16048 FormatStyle Alignment = getLLVMStyle(); 16049 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 16050 Alignment.AlignConsecutiveAssignments = 16051 FormatStyle::ACS_AcrossEmptyLinesAndComments; 16052 verifyFormat("int a = 5;\n" 16053 "int oneTwoThree = 123;", 16054 Alignment); 16055 verifyFormat("int a = method();\n" 16056 "int oneTwoThree = 133;", 16057 Alignment); 16058 verifyFormat("a &= 5;\n" 16059 "bcd *= 5;\n" 16060 "ghtyf += 5;\n" 16061 "dvfvdb -= 5;\n" 16062 "a /= 5;\n" 16063 "vdsvsv %= 5;\n" 16064 "sfdbddfbdfbb ^= 5;\n" 16065 "dvsdsv |= 5;\n" 16066 "int dsvvdvsdvvv = 123;", 16067 Alignment); 16068 verifyFormat("int i = 1, j = 10;\n" 16069 "something = 2000;", 16070 Alignment); 16071 verifyFormat("something = 2000;\n" 16072 "int i = 1, j = 10;\n", 16073 Alignment); 16074 verifyFormat("something = 2000;\n" 16075 "another = 911;\n" 16076 "int i = 1, j = 10;\n" 16077 "oneMore = 1;\n" 16078 "i = 2;", 16079 Alignment); 16080 verifyFormat("int a = 5;\n" 16081 "int one = 1;\n" 16082 "method();\n" 16083 "int oneTwoThree = 123;\n" 16084 "int oneTwo = 12;", 16085 Alignment); 16086 verifyFormat("int oneTwoThree = 123;\n" 16087 "int oneTwo = 12;\n" 16088 "method();\n", 16089 Alignment); 16090 verifyFormat("int oneTwoThree = 123; // comment\n" 16091 "int oneTwo = 12; // comment", 16092 Alignment); 16093 16094 // Bug 25167 16095 /* Uncomment when fixed 16096 verifyFormat("#if A\n" 16097 "#else\n" 16098 "int aaaaaaaa = 12;\n" 16099 "#endif\n" 16100 "#if B\n" 16101 "#else\n" 16102 "int a = 12;\n" 16103 "#endif\n", 16104 Alignment); 16105 verifyFormat("enum foo {\n" 16106 "#if A\n" 16107 "#else\n" 16108 " aaaaaaaa = 12;\n" 16109 "#endif\n" 16110 "#if B\n" 16111 "#else\n" 16112 " a = 12;\n" 16113 "#endif\n" 16114 "};\n", 16115 Alignment); 16116 */ 16117 16118 Alignment.MaxEmptyLinesToKeep = 10; 16119 /* Test alignment across empty lines */ 16120 EXPECT_EQ("int a = 5;\n" 16121 "\n" 16122 "int oneTwoThree = 123;", 16123 format("int a = 5;\n" 16124 "\n" 16125 "int oneTwoThree= 123;", 16126 Alignment)); 16127 EXPECT_EQ("int a = 5;\n" 16128 "int one = 1;\n" 16129 "\n" 16130 "int oneTwoThree = 123;", 16131 format("int a = 5;\n" 16132 "int one = 1;\n" 16133 "\n" 16134 "int oneTwoThree = 123;", 16135 Alignment)); 16136 EXPECT_EQ("int a = 5;\n" 16137 "int one = 1;\n" 16138 "\n" 16139 "int oneTwoThree = 123;\n" 16140 "int oneTwo = 12;", 16141 format("int a = 5;\n" 16142 "int one = 1;\n" 16143 "\n" 16144 "int oneTwoThree = 123;\n" 16145 "int oneTwo = 12;", 16146 Alignment)); 16147 16148 /* Test across comments */ 16149 EXPECT_EQ("int a = 5;\n" 16150 "/* block comment */\n" 16151 "int oneTwoThree = 123;", 16152 format("int a = 5;\n" 16153 "/* block comment */\n" 16154 "int oneTwoThree=123;", 16155 Alignment)); 16156 16157 EXPECT_EQ("int a = 5;\n" 16158 "// line comment\n" 16159 "int oneTwoThree = 123;", 16160 format("int a = 5;\n" 16161 "// line comment\n" 16162 "int oneTwoThree=123;", 16163 Alignment)); 16164 16165 /* Test across comments and newlines */ 16166 EXPECT_EQ("int a = 5;\n" 16167 "\n" 16168 "/* block comment */\n" 16169 "int oneTwoThree = 123;", 16170 format("int a = 5;\n" 16171 "\n" 16172 "/* block comment */\n" 16173 "int oneTwoThree=123;", 16174 Alignment)); 16175 16176 EXPECT_EQ("int a = 5;\n" 16177 "\n" 16178 "// line comment\n" 16179 "int oneTwoThree = 123;", 16180 format("int a = 5;\n" 16181 "\n" 16182 "// line comment\n" 16183 "int oneTwoThree=123;", 16184 Alignment)); 16185 16186 EXPECT_EQ("int a = 5;\n" 16187 "//\n" 16188 "// multi-line line comment\n" 16189 "//\n" 16190 "int oneTwoThree = 123;", 16191 format("int a = 5;\n" 16192 "//\n" 16193 "// multi-line line comment\n" 16194 "//\n" 16195 "int oneTwoThree=123;", 16196 Alignment)); 16197 16198 EXPECT_EQ("int a = 5;\n" 16199 "/*\n" 16200 " * multi-line block comment\n" 16201 " */\n" 16202 "int oneTwoThree = 123;", 16203 format("int a = 5;\n" 16204 "/*\n" 16205 " * multi-line block comment\n" 16206 " */\n" 16207 "int oneTwoThree=123;", 16208 Alignment)); 16209 16210 EXPECT_EQ("int a = 5;\n" 16211 "\n" 16212 "/* block comment */\n" 16213 "\n" 16214 "\n" 16215 "\n" 16216 "int oneTwoThree = 123;", 16217 format("int a = 5;\n" 16218 "\n" 16219 "/* block comment */\n" 16220 "\n" 16221 "\n" 16222 "\n" 16223 "int oneTwoThree=123;", 16224 Alignment)); 16225 16226 EXPECT_EQ("int a = 5;\n" 16227 "\n" 16228 "// line comment\n" 16229 "\n" 16230 "\n" 16231 "\n" 16232 "int oneTwoThree = 123;", 16233 format("int a = 5;\n" 16234 "\n" 16235 "// line comment\n" 16236 "\n" 16237 "\n" 16238 "\n" 16239 "int oneTwoThree=123;", 16240 Alignment)); 16241 16242 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 16243 verifyFormat("#define A \\\n" 16244 " int aaaa = 12; \\\n" 16245 " int b = 23; \\\n" 16246 " int ccc = 234; \\\n" 16247 " int dddddddddd = 2345;", 16248 Alignment); 16249 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 16250 verifyFormat("#define A \\\n" 16251 " int aaaa = 12; \\\n" 16252 " int b = 23; \\\n" 16253 " int ccc = 234; \\\n" 16254 " int dddddddddd = 2345;", 16255 Alignment); 16256 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 16257 verifyFormat("#define A " 16258 " \\\n" 16259 " int aaaa = 12; " 16260 " \\\n" 16261 " int b = 23; " 16262 " \\\n" 16263 " int ccc = 234; " 16264 " \\\n" 16265 " int dddddddddd = 2345;", 16266 Alignment); 16267 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 16268 "k = 4, int l = 5,\n" 16269 " int m = 6) {\n" 16270 " int j = 10;\n" 16271 " otherThing = 1;\n" 16272 "}", 16273 Alignment); 16274 verifyFormat("void SomeFunction(int parameter = 0) {\n" 16275 " int i = 1;\n" 16276 " int j = 2;\n" 16277 " int big = 10000;\n" 16278 "}", 16279 Alignment); 16280 verifyFormat("class C {\n" 16281 "public:\n" 16282 " int i = 1;\n" 16283 " virtual void f() = 0;\n" 16284 "};", 16285 Alignment); 16286 verifyFormat("int i = 1;\n" 16287 "if (SomeType t = getSomething()) {\n" 16288 "}\n" 16289 "int j = 2;\n" 16290 "int big = 10000;", 16291 Alignment); 16292 verifyFormat("int j = 7;\n" 16293 "for (int k = 0; k < N; ++k) {\n" 16294 "}\n" 16295 "int j = 2;\n" 16296 "int big = 10000;\n" 16297 "}", 16298 Alignment); 16299 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 16300 verifyFormat("int i = 1;\n" 16301 "LooooooooooongType loooooooooooooooooooooongVariable\n" 16302 " = someLooooooooooooooooongFunction();\n" 16303 "int j = 2;", 16304 Alignment); 16305 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 16306 verifyFormat("int i = 1;\n" 16307 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 16308 " someLooooooooooooooooongFunction();\n" 16309 "int j = 2;", 16310 Alignment); 16311 16312 verifyFormat("auto lambda = []() {\n" 16313 " auto i = 0;\n" 16314 " return 0;\n" 16315 "};\n" 16316 "int i = 0;\n" 16317 "auto v = type{\n" 16318 " i = 1, //\n" 16319 " (i = 2), //\n" 16320 " i = 3 //\n" 16321 "};", 16322 Alignment); 16323 16324 verifyFormat( 16325 "int i = 1;\n" 16326 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 16327 " loooooooooooooooooooooongParameterB);\n" 16328 "int j = 2;", 16329 Alignment); 16330 16331 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n" 16332 " typename B = very_long_type_name_1,\n" 16333 " typename T_2 = very_long_type_name_2>\n" 16334 "auto foo() {}\n", 16335 Alignment); 16336 verifyFormat("int a, b = 1;\n" 16337 "int c = 2;\n" 16338 "int dd = 3;\n", 16339 Alignment); 16340 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 16341 "float b[1][] = {{3.f}};\n", 16342 Alignment); 16343 verifyFormat("for (int i = 0; i < 1; i++)\n" 16344 " int x = 1;\n", 16345 Alignment); 16346 verifyFormat("for (i = 0; i < 1; i++)\n" 16347 " x = 1;\n" 16348 "y = 1;\n", 16349 Alignment); 16350 16351 Alignment.ReflowComments = true; 16352 Alignment.ColumnLimit = 50; 16353 EXPECT_EQ("int x = 0;\n" 16354 "int yy = 1; /// specificlennospace\n" 16355 "int zzz = 2;\n", 16356 format("int x = 0;\n" 16357 "int yy = 1; ///specificlennospace\n" 16358 "int zzz = 2;\n", 16359 Alignment)); 16360 } 16361 16362 TEST_F(FormatTest, AlignConsecutiveAssignments) { 16363 FormatStyle Alignment = getLLVMStyle(); 16364 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 16365 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 16366 verifyFormat("int a = 5;\n" 16367 "int oneTwoThree = 123;", 16368 Alignment); 16369 verifyFormat("int a = 5;\n" 16370 "int oneTwoThree = 123;", 16371 Alignment); 16372 16373 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 16374 verifyFormat("int a = 5;\n" 16375 "int oneTwoThree = 123;", 16376 Alignment); 16377 verifyFormat("int a = method();\n" 16378 "int oneTwoThree = 133;", 16379 Alignment); 16380 verifyFormat("a &= 5;\n" 16381 "bcd *= 5;\n" 16382 "ghtyf += 5;\n" 16383 "dvfvdb -= 5;\n" 16384 "a /= 5;\n" 16385 "vdsvsv %= 5;\n" 16386 "sfdbddfbdfbb ^= 5;\n" 16387 "dvsdsv |= 5;\n" 16388 "int dsvvdvsdvvv = 123;", 16389 Alignment); 16390 verifyFormat("int i = 1, j = 10;\n" 16391 "something = 2000;", 16392 Alignment); 16393 verifyFormat("something = 2000;\n" 16394 "int i = 1, j = 10;\n", 16395 Alignment); 16396 verifyFormat("something = 2000;\n" 16397 "another = 911;\n" 16398 "int i = 1, j = 10;\n" 16399 "oneMore = 1;\n" 16400 "i = 2;", 16401 Alignment); 16402 verifyFormat("int a = 5;\n" 16403 "int one = 1;\n" 16404 "method();\n" 16405 "int oneTwoThree = 123;\n" 16406 "int oneTwo = 12;", 16407 Alignment); 16408 verifyFormat("int oneTwoThree = 123;\n" 16409 "int oneTwo = 12;\n" 16410 "method();\n", 16411 Alignment); 16412 verifyFormat("int oneTwoThree = 123; // comment\n" 16413 "int oneTwo = 12; // comment", 16414 Alignment); 16415 verifyFormat("int f() = default;\n" 16416 "int &operator() = default;\n" 16417 "int &operator=() {", 16418 Alignment); 16419 verifyFormat("int f() = delete;\n" 16420 "int &operator() = delete;\n" 16421 "int &operator=() {", 16422 Alignment); 16423 verifyFormat("int f() = default; // comment\n" 16424 "int &operator() = default; // comment\n" 16425 "int &operator=() {", 16426 Alignment); 16427 verifyFormat("int f() = default;\n" 16428 "int &operator() = default;\n" 16429 "int &operator==() {", 16430 Alignment); 16431 verifyFormat("int f() = default;\n" 16432 "int &operator() = default;\n" 16433 "int &operator<=() {", 16434 Alignment); 16435 verifyFormat("int f() = default;\n" 16436 "int &operator() = default;\n" 16437 "int &operator!=() {", 16438 Alignment); 16439 verifyFormat("int f() = default;\n" 16440 "int &operator() = default;\n" 16441 "int &operator=();", 16442 Alignment); 16443 verifyFormat("int f() = delete;\n" 16444 "int &operator() = delete;\n" 16445 "int &operator=();", 16446 Alignment); 16447 verifyFormat("/* long long padding */ int f() = default;\n" 16448 "int &operator() = default;\n" 16449 "int &operator/**/ =();", 16450 Alignment); 16451 // https://llvm.org/PR33697 16452 FormatStyle AlignmentWithPenalty = getLLVMStyle(); 16453 AlignmentWithPenalty.AlignConsecutiveAssignments = 16454 FormatStyle::ACS_Consecutive; 16455 AlignmentWithPenalty.PenaltyReturnTypeOnItsOwnLine = 5000; 16456 verifyFormat("class SSSSSSSSSSSSSSSSSSSSSSSSSSSS {\n" 16457 " void f() = delete;\n" 16458 " SSSSSSSSSSSSSSSSSSSSSSSSSSSS &operator=(\n" 16459 " const SSSSSSSSSSSSSSSSSSSSSSSSSSSS &other) = delete;\n" 16460 "};\n", 16461 AlignmentWithPenalty); 16462 16463 // Bug 25167 16464 /* Uncomment when fixed 16465 verifyFormat("#if A\n" 16466 "#else\n" 16467 "int aaaaaaaa = 12;\n" 16468 "#endif\n" 16469 "#if B\n" 16470 "#else\n" 16471 "int a = 12;\n" 16472 "#endif\n", 16473 Alignment); 16474 verifyFormat("enum foo {\n" 16475 "#if A\n" 16476 "#else\n" 16477 " aaaaaaaa = 12;\n" 16478 "#endif\n" 16479 "#if B\n" 16480 "#else\n" 16481 " a = 12;\n" 16482 "#endif\n" 16483 "};\n", 16484 Alignment); 16485 */ 16486 16487 EXPECT_EQ("int a = 5;\n" 16488 "\n" 16489 "int oneTwoThree = 123;", 16490 format("int a = 5;\n" 16491 "\n" 16492 "int oneTwoThree= 123;", 16493 Alignment)); 16494 EXPECT_EQ("int a = 5;\n" 16495 "int one = 1;\n" 16496 "\n" 16497 "int oneTwoThree = 123;", 16498 format("int a = 5;\n" 16499 "int one = 1;\n" 16500 "\n" 16501 "int oneTwoThree = 123;", 16502 Alignment)); 16503 EXPECT_EQ("int a = 5;\n" 16504 "int one = 1;\n" 16505 "\n" 16506 "int oneTwoThree = 123;\n" 16507 "int oneTwo = 12;", 16508 format("int a = 5;\n" 16509 "int one = 1;\n" 16510 "\n" 16511 "int oneTwoThree = 123;\n" 16512 "int oneTwo = 12;", 16513 Alignment)); 16514 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 16515 verifyFormat("#define A \\\n" 16516 " int aaaa = 12; \\\n" 16517 " int b = 23; \\\n" 16518 " int ccc = 234; \\\n" 16519 " int dddddddddd = 2345;", 16520 Alignment); 16521 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 16522 verifyFormat("#define A \\\n" 16523 " int aaaa = 12; \\\n" 16524 " int b = 23; \\\n" 16525 " int ccc = 234; \\\n" 16526 " int dddddddddd = 2345;", 16527 Alignment); 16528 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 16529 verifyFormat("#define A " 16530 " \\\n" 16531 " int aaaa = 12; " 16532 " \\\n" 16533 " int b = 23; " 16534 " \\\n" 16535 " int ccc = 234; " 16536 " \\\n" 16537 " int dddddddddd = 2345;", 16538 Alignment); 16539 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 16540 "k = 4, int l = 5,\n" 16541 " int m = 6) {\n" 16542 " int j = 10;\n" 16543 " otherThing = 1;\n" 16544 "}", 16545 Alignment); 16546 verifyFormat("void SomeFunction(int parameter = 0) {\n" 16547 " int i = 1;\n" 16548 " int j = 2;\n" 16549 " int big = 10000;\n" 16550 "}", 16551 Alignment); 16552 verifyFormat("class C {\n" 16553 "public:\n" 16554 " int i = 1;\n" 16555 " virtual void f() = 0;\n" 16556 "};", 16557 Alignment); 16558 verifyFormat("int i = 1;\n" 16559 "if (SomeType t = getSomething()) {\n" 16560 "}\n" 16561 "int j = 2;\n" 16562 "int big = 10000;", 16563 Alignment); 16564 verifyFormat("int j = 7;\n" 16565 "for (int k = 0; k < N; ++k) {\n" 16566 "}\n" 16567 "int j = 2;\n" 16568 "int big = 10000;\n" 16569 "}", 16570 Alignment); 16571 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 16572 verifyFormat("int i = 1;\n" 16573 "LooooooooooongType loooooooooooooooooooooongVariable\n" 16574 " = someLooooooooooooooooongFunction();\n" 16575 "int j = 2;", 16576 Alignment); 16577 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 16578 verifyFormat("int i = 1;\n" 16579 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 16580 " someLooooooooooooooooongFunction();\n" 16581 "int j = 2;", 16582 Alignment); 16583 16584 verifyFormat("auto lambda = []() {\n" 16585 " auto i = 0;\n" 16586 " return 0;\n" 16587 "};\n" 16588 "int i = 0;\n" 16589 "auto v = type{\n" 16590 " i = 1, //\n" 16591 " (i = 2), //\n" 16592 " i = 3 //\n" 16593 "};", 16594 Alignment); 16595 16596 verifyFormat( 16597 "int i = 1;\n" 16598 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 16599 " loooooooooooooooooooooongParameterB);\n" 16600 "int j = 2;", 16601 Alignment); 16602 16603 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n" 16604 " typename B = very_long_type_name_1,\n" 16605 " typename T_2 = very_long_type_name_2>\n" 16606 "auto foo() {}\n", 16607 Alignment); 16608 verifyFormat("int a, b = 1;\n" 16609 "int c = 2;\n" 16610 "int dd = 3;\n", 16611 Alignment); 16612 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 16613 "float b[1][] = {{3.f}};\n", 16614 Alignment); 16615 verifyFormat("for (int i = 0; i < 1; i++)\n" 16616 " int x = 1;\n", 16617 Alignment); 16618 verifyFormat("for (i = 0; i < 1; i++)\n" 16619 " x = 1;\n" 16620 "y = 1;\n", 16621 Alignment); 16622 16623 EXPECT_EQ(Alignment.ReflowComments, true); 16624 Alignment.ColumnLimit = 50; 16625 EXPECT_EQ("int x = 0;\n" 16626 "int yy = 1; /// specificlennospace\n" 16627 "int zzz = 2;\n", 16628 format("int x = 0;\n" 16629 "int yy = 1; ///specificlennospace\n" 16630 "int zzz = 2;\n", 16631 Alignment)); 16632 16633 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 16634 "auto b = [] {\n" 16635 " f();\n" 16636 " return;\n" 16637 "};", 16638 Alignment); 16639 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 16640 "auto b = g([] {\n" 16641 " f();\n" 16642 " return;\n" 16643 "});", 16644 Alignment); 16645 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 16646 "auto b = g(param, [] {\n" 16647 " f();\n" 16648 " return;\n" 16649 "});", 16650 Alignment); 16651 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 16652 "auto b = [] {\n" 16653 " if (condition) {\n" 16654 " return;\n" 16655 " }\n" 16656 "};", 16657 Alignment); 16658 16659 verifyFormat("auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 16660 " ccc ? aaaaa : bbbbb,\n" 16661 " dddddddddddddddddddddddddd);", 16662 Alignment); 16663 // FIXME: https://llvm.org/PR53497 16664 // verifyFormat("auto aaaaaaaaaaaa = f();\n" 16665 // "auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 16666 // " ccc ? aaaaa : bbbbb,\n" 16667 // " dddddddddddddddddddddddddd);", 16668 // Alignment); 16669 } 16670 16671 TEST_F(FormatTest, AlignConsecutiveBitFields) { 16672 FormatStyle Alignment = getLLVMStyle(); 16673 Alignment.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive; 16674 verifyFormat("int const a : 5;\n" 16675 "int oneTwoThree : 23;", 16676 Alignment); 16677 16678 // Initializers are allowed starting with c++2a 16679 verifyFormat("int const a : 5 = 1;\n" 16680 "int oneTwoThree : 23 = 0;", 16681 Alignment); 16682 16683 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 16684 verifyFormat("int const a : 5;\n" 16685 "int oneTwoThree : 23;", 16686 Alignment); 16687 16688 verifyFormat("int const a : 5; // comment\n" 16689 "int oneTwoThree : 23; // comment", 16690 Alignment); 16691 16692 verifyFormat("int const a : 5 = 1;\n" 16693 "int oneTwoThree : 23 = 0;", 16694 Alignment); 16695 16696 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 16697 verifyFormat("int const a : 5 = 1;\n" 16698 "int oneTwoThree : 23 = 0;", 16699 Alignment); 16700 verifyFormat("int const a : 5 = {1};\n" 16701 "int oneTwoThree : 23 = 0;", 16702 Alignment); 16703 16704 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None; 16705 verifyFormat("int const a :5;\n" 16706 "int oneTwoThree:23;", 16707 Alignment); 16708 16709 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before; 16710 verifyFormat("int const a :5;\n" 16711 "int oneTwoThree :23;", 16712 Alignment); 16713 16714 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After; 16715 verifyFormat("int const a : 5;\n" 16716 "int oneTwoThree: 23;", 16717 Alignment); 16718 16719 // Known limitations: ':' is only recognized as a bitfield colon when 16720 // followed by a number. 16721 /* 16722 verifyFormat("int oneTwoThree : SOME_CONSTANT;\n" 16723 "int a : 5;", 16724 Alignment); 16725 */ 16726 } 16727 16728 TEST_F(FormatTest, AlignConsecutiveDeclarations) { 16729 FormatStyle Alignment = getLLVMStyle(); 16730 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 16731 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_None; 16732 Alignment.PointerAlignment = FormatStyle::PAS_Right; 16733 verifyFormat("float const a = 5;\n" 16734 "int oneTwoThree = 123;", 16735 Alignment); 16736 verifyFormat("int a = 5;\n" 16737 "float const oneTwoThree = 123;", 16738 Alignment); 16739 16740 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 16741 verifyFormat("float const a = 5;\n" 16742 "int oneTwoThree = 123;", 16743 Alignment); 16744 verifyFormat("int a = method();\n" 16745 "float const oneTwoThree = 133;", 16746 Alignment); 16747 verifyFormat("int i = 1, j = 10;\n" 16748 "something = 2000;", 16749 Alignment); 16750 verifyFormat("something = 2000;\n" 16751 "int i = 1, j = 10;\n", 16752 Alignment); 16753 verifyFormat("float something = 2000;\n" 16754 "double another = 911;\n" 16755 "int i = 1, j = 10;\n" 16756 "const int *oneMore = 1;\n" 16757 "unsigned i = 2;", 16758 Alignment); 16759 verifyFormat("float a = 5;\n" 16760 "int one = 1;\n" 16761 "method();\n" 16762 "const double oneTwoThree = 123;\n" 16763 "const unsigned int oneTwo = 12;", 16764 Alignment); 16765 verifyFormat("int oneTwoThree{0}; // comment\n" 16766 "unsigned oneTwo; // comment", 16767 Alignment); 16768 verifyFormat("unsigned int *a;\n" 16769 "int *b;\n" 16770 "unsigned int Const *c;\n" 16771 "unsigned int const *d;\n" 16772 "unsigned int Const &e;\n" 16773 "unsigned int const &f;", 16774 Alignment); 16775 verifyFormat("Const unsigned int *c;\n" 16776 "const unsigned int *d;\n" 16777 "Const unsigned int &e;\n" 16778 "const unsigned int &f;\n" 16779 "const unsigned g;\n" 16780 "Const unsigned h;", 16781 Alignment); 16782 EXPECT_EQ("float const a = 5;\n" 16783 "\n" 16784 "int oneTwoThree = 123;", 16785 format("float const a = 5;\n" 16786 "\n" 16787 "int oneTwoThree= 123;", 16788 Alignment)); 16789 EXPECT_EQ("float a = 5;\n" 16790 "int one = 1;\n" 16791 "\n" 16792 "unsigned oneTwoThree = 123;", 16793 format("float a = 5;\n" 16794 "int one = 1;\n" 16795 "\n" 16796 "unsigned oneTwoThree = 123;", 16797 Alignment)); 16798 EXPECT_EQ("float a = 5;\n" 16799 "int one = 1;\n" 16800 "\n" 16801 "unsigned oneTwoThree = 123;\n" 16802 "int oneTwo = 12;", 16803 format("float a = 5;\n" 16804 "int one = 1;\n" 16805 "\n" 16806 "unsigned oneTwoThree = 123;\n" 16807 "int oneTwo = 12;", 16808 Alignment)); 16809 // Function prototype alignment 16810 verifyFormat("int a();\n" 16811 "double b();", 16812 Alignment); 16813 verifyFormat("int a(int x);\n" 16814 "double b();", 16815 Alignment); 16816 unsigned OldColumnLimit = Alignment.ColumnLimit; 16817 // We need to set ColumnLimit to zero, in order to stress nested alignments, 16818 // otherwise the function parameters will be re-flowed onto a single line. 16819 Alignment.ColumnLimit = 0; 16820 EXPECT_EQ("int a(int x,\n" 16821 " float y);\n" 16822 "double b(int x,\n" 16823 " double y);", 16824 format("int a(int x,\n" 16825 " float y);\n" 16826 "double b(int x,\n" 16827 " double y);", 16828 Alignment)); 16829 // This ensures that function parameters of function declarations are 16830 // correctly indented when their owning functions are indented. 16831 // The failure case here is for 'double y' to not be indented enough. 16832 EXPECT_EQ("double a(int x);\n" 16833 "int b(int y,\n" 16834 " double z);", 16835 format("double a(int x);\n" 16836 "int b(int y,\n" 16837 " double z);", 16838 Alignment)); 16839 // Set ColumnLimit low so that we induce wrapping immediately after 16840 // the function name and opening paren. 16841 Alignment.ColumnLimit = 13; 16842 verifyFormat("int function(\n" 16843 " int x,\n" 16844 " bool y);", 16845 Alignment); 16846 Alignment.ColumnLimit = OldColumnLimit; 16847 // Ensure function pointers don't screw up recursive alignment 16848 verifyFormat("int a(int x, void (*fp)(int y));\n" 16849 "double b();", 16850 Alignment); 16851 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 16852 // Ensure recursive alignment is broken by function braces, so that the 16853 // "a = 1" does not align with subsequent assignments inside the function 16854 // body. 16855 verifyFormat("int func(int a = 1) {\n" 16856 " int b = 2;\n" 16857 " int cc = 3;\n" 16858 "}", 16859 Alignment); 16860 verifyFormat("float something = 2000;\n" 16861 "double another = 911;\n" 16862 "int i = 1, j = 10;\n" 16863 "const int *oneMore = 1;\n" 16864 "unsigned i = 2;", 16865 Alignment); 16866 verifyFormat("int oneTwoThree = {0}; // comment\n" 16867 "unsigned oneTwo = 0; // comment", 16868 Alignment); 16869 // Make sure that scope is correctly tracked, in the absence of braces 16870 verifyFormat("for (int i = 0; i < n; i++)\n" 16871 " j = i;\n" 16872 "double x = 1;\n", 16873 Alignment); 16874 verifyFormat("if (int i = 0)\n" 16875 " j = i;\n" 16876 "double x = 1;\n", 16877 Alignment); 16878 // Ensure operator[] and operator() are comprehended 16879 verifyFormat("struct test {\n" 16880 " long long int foo();\n" 16881 " int operator[](int a);\n" 16882 " double bar();\n" 16883 "};\n", 16884 Alignment); 16885 verifyFormat("struct test {\n" 16886 " long long int foo();\n" 16887 " int operator()(int a);\n" 16888 " double bar();\n" 16889 "};\n", 16890 Alignment); 16891 // http://llvm.org/PR52914 16892 verifyFormat("char *a[] = {\"a\", // comment\n" 16893 " \"bb\"};\n" 16894 "int bbbbbbb = 0;", 16895 Alignment); 16896 16897 // PAS_Right 16898 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 16899 " int const i = 1;\n" 16900 " int *j = 2;\n" 16901 " int big = 10000;\n" 16902 "\n" 16903 " unsigned oneTwoThree = 123;\n" 16904 " int oneTwo = 12;\n" 16905 " method();\n" 16906 " float k = 2;\n" 16907 " int ll = 10000;\n" 16908 "}", 16909 format("void SomeFunction(int parameter= 0) {\n" 16910 " int const i= 1;\n" 16911 " int *j=2;\n" 16912 " int big = 10000;\n" 16913 "\n" 16914 "unsigned oneTwoThree =123;\n" 16915 "int oneTwo = 12;\n" 16916 " method();\n" 16917 "float k= 2;\n" 16918 "int ll=10000;\n" 16919 "}", 16920 Alignment)); 16921 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 16922 " int const i = 1;\n" 16923 " int **j = 2, ***k;\n" 16924 " int &k = i;\n" 16925 " int &&l = i + j;\n" 16926 " int big = 10000;\n" 16927 "\n" 16928 " unsigned oneTwoThree = 123;\n" 16929 " int oneTwo = 12;\n" 16930 " method();\n" 16931 " float k = 2;\n" 16932 " int ll = 10000;\n" 16933 "}", 16934 format("void SomeFunction(int parameter= 0) {\n" 16935 " int const i= 1;\n" 16936 " int **j=2,***k;\n" 16937 "int &k=i;\n" 16938 "int &&l=i+j;\n" 16939 " int big = 10000;\n" 16940 "\n" 16941 "unsigned oneTwoThree =123;\n" 16942 "int oneTwo = 12;\n" 16943 " method();\n" 16944 "float k= 2;\n" 16945 "int ll=10000;\n" 16946 "}", 16947 Alignment)); 16948 // variables are aligned at their name, pointers are at the right most 16949 // position 16950 verifyFormat("int *a;\n" 16951 "int **b;\n" 16952 "int ***c;\n" 16953 "int foobar;\n", 16954 Alignment); 16955 16956 // PAS_Left 16957 FormatStyle AlignmentLeft = Alignment; 16958 AlignmentLeft.PointerAlignment = FormatStyle::PAS_Left; 16959 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 16960 " int const i = 1;\n" 16961 " int* j = 2;\n" 16962 " int big = 10000;\n" 16963 "\n" 16964 " unsigned oneTwoThree = 123;\n" 16965 " int oneTwo = 12;\n" 16966 " method();\n" 16967 " float k = 2;\n" 16968 " int ll = 10000;\n" 16969 "}", 16970 format("void SomeFunction(int parameter= 0) {\n" 16971 " int const i= 1;\n" 16972 " int *j=2;\n" 16973 " int big = 10000;\n" 16974 "\n" 16975 "unsigned oneTwoThree =123;\n" 16976 "int oneTwo = 12;\n" 16977 " method();\n" 16978 "float k= 2;\n" 16979 "int ll=10000;\n" 16980 "}", 16981 AlignmentLeft)); 16982 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 16983 " int const i = 1;\n" 16984 " int** j = 2;\n" 16985 " int& k = i;\n" 16986 " int&& l = i + j;\n" 16987 " int big = 10000;\n" 16988 "\n" 16989 " unsigned oneTwoThree = 123;\n" 16990 " int oneTwo = 12;\n" 16991 " method();\n" 16992 " float k = 2;\n" 16993 " int ll = 10000;\n" 16994 "}", 16995 format("void SomeFunction(int parameter= 0) {\n" 16996 " int const i= 1;\n" 16997 " int **j=2;\n" 16998 "int &k=i;\n" 16999 "int &&l=i+j;\n" 17000 " int big = 10000;\n" 17001 "\n" 17002 "unsigned oneTwoThree =123;\n" 17003 "int oneTwo = 12;\n" 17004 " method();\n" 17005 "float k= 2;\n" 17006 "int ll=10000;\n" 17007 "}", 17008 AlignmentLeft)); 17009 // variables are aligned at their name, pointers are at the left most position 17010 verifyFormat("int* a;\n" 17011 "int** b;\n" 17012 "int*** c;\n" 17013 "int foobar;\n", 17014 AlignmentLeft); 17015 17016 // PAS_Middle 17017 FormatStyle AlignmentMiddle = Alignment; 17018 AlignmentMiddle.PointerAlignment = FormatStyle::PAS_Middle; 17019 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17020 " int const i = 1;\n" 17021 " int * j = 2;\n" 17022 " int big = 10000;\n" 17023 "\n" 17024 " unsigned oneTwoThree = 123;\n" 17025 " int oneTwo = 12;\n" 17026 " method();\n" 17027 " float k = 2;\n" 17028 " int ll = 10000;\n" 17029 "}", 17030 format("void SomeFunction(int parameter= 0) {\n" 17031 " int const i= 1;\n" 17032 " int *j=2;\n" 17033 " int big = 10000;\n" 17034 "\n" 17035 "unsigned oneTwoThree =123;\n" 17036 "int oneTwo = 12;\n" 17037 " method();\n" 17038 "float k= 2;\n" 17039 "int ll=10000;\n" 17040 "}", 17041 AlignmentMiddle)); 17042 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17043 " int const i = 1;\n" 17044 " int ** j = 2, ***k;\n" 17045 " int & k = i;\n" 17046 " int && l = i + j;\n" 17047 " int big = 10000;\n" 17048 "\n" 17049 " unsigned oneTwoThree = 123;\n" 17050 " int oneTwo = 12;\n" 17051 " method();\n" 17052 " float k = 2;\n" 17053 " int ll = 10000;\n" 17054 "}", 17055 format("void SomeFunction(int parameter= 0) {\n" 17056 " int const i= 1;\n" 17057 " int **j=2,***k;\n" 17058 "int &k=i;\n" 17059 "int &&l=i+j;\n" 17060 " int big = 10000;\n" 17061 "\n" 17062 "unsigned oneTwoThree =123;\n" 17063 "int oneTwo = 12;\n" 17064 " method();\n" 17065 "float k= 2;\n" 17066 "int ll=10000;\n" 17067 "}", 17068 AlignmentMiddle)); 17069 // variables are aligned at their name, pointers are in the middle 17070 verifyFormat("int * a;\n" 17071 "int * b;\n" 17072 "int *** c;\n" 17073 "int foobar;\n", 17074 AlignmentMiddle); 17075 17076 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 17077 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 17078 verifyFormat("#define A \\\n" 17079 " int aaaa = 12; \\\n" 17080 " float b = 23; \\\n" 17081 " const int ccc = 234; \\\n" 17082 " unsigned dddddddddd = 2345;", 17083 Alignment); 17084 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 17085 verifyFormat("#define A \\\n" 17086 " int aaaa = 12; \\\n" 17087 " float b = 23; \\\n" 17088 " const int ccc = 234; \\\n" 17089 " unsigned dddddddddd = 2345;", 17090 Alignment); 17091 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 17092 Alignment.ColumnLimit = 30; 17093 verifyFormat("#define A \\\n" 17094 " int aaaa = 12; \\\n" 17095 " float b = 23; \\\n" 17096 " const int ccc = 234; \\\n" 17097 " int dddddddddd = 2345;", 17098 Alignment); 17099 Alignment.ColumnLimit = 80; 17100 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 17101 "k = 4, int l = 5,\n" 17102 " int m = 6) {\n" 17103 " const int j = 10;\n" 17104 " otherThing = 1;\n" 17105 "}", 17106 Alignment); 17107 verifyFormat("void SomeFunction(int parameter = 0) {\n" 17108 " int const i = 1;\n" 17109 " int *j = 2;\n" 17110 " int big = 10000;\n" 17111 "}", 17112 Alignment); 17113 verifyFormat("class C {\n" 17114 "public:\n" 17115 " int i = 1;\n" 17116 " virtual void f() = 0;\n" 17117 "};", 17118 Alignment); 17119 verifyFormat("float i = 1;\n" 17120 "if (SomeType t = getSomething()) {\n" 17121 "}\n" 17122 "const unsigned j = 2;\n" 17123 "int big = 10000;", 17124 Alignment); 17125 verifyFormat("float j = 7;\n" 17126 "for (int k = 0; k < N; ++k) {\n" 17127 "}\n" 17128 "unsigned j = 2;\n" 17129 "int big = 10000;\n" 17130 "}", 17131 Alignment); 17132 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 17133 verifyFormat("float i = 1;\n" 17134 "LooooooooooongType loooooooooooooooooooooongVariable\n" 17135 " = someLooooooooooooooooongFunction();\n" 17136 "int j = 2;", 17137 Alignment); 17138 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 17139 verifyFormat("int i = 1;\n" 17140 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 17141 " someLooooooooooooooooongFunction();\n" 17142 "int j = 2;", 17143 Alignment); 17144 17145 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17146 verifyFormat("auto lambda = []() {\n" 17147 " auto ii = 0;\n" 17148 " float j = 0;\n" 17149 " return 0;\n" 17150 "};\n" 17151 "int i = 0;\n" 17152 "float i2 = 0;\n" 17153 "auto v = type{\n" 17154 " i = 1, //\n" 17155 " (i = 2), //\n" 17156 " i = 3 //\n" 17157 "};", 17158 Alignment); 17159 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 17160 17161 verifyFormat( 17162 "int i = 1;\n" 17163 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 17164 " loooooooooooooooooooooongParameterB);\n" 17165 "int j = 2;", 17166 Alignment); 17167 17168 // Test interactions with ColumnLimit and AlignConsecutiveAssignments: 17169 // We expect declarations and assignments to align, as long as it doesn't 17170 // exceed the column limit, starting a new alignment sequence whenever it 17171 // happens. 17172 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17173 Alignment.ColumnLimit = 30; 17174 verifyFormat("float ii = 1;\n" 17175 "unsigned j = 2;\n" 17176 "int someVerylongVariable = 1;\n" 17177 "AnotherLongType ll = 123456;\n" 17178 "VeryVeryLongType k = 2;\n" 17179 "int myvar = 1;", 17180 Alignment); 17181 Alignment.ColumnLimit = 80; 17182 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 17183 17184 verifyFormat( 17185 "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n" 17186 " typename LongType, typename B>\n" 17187 "auto foo() {}\n", 17188 Alignment); 17189 verifyFormat("float a, b = 1;\n" 17190 "int c = 2;\n" 17191 "int dd = 3;\n", 17192 Alignment); 17193 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17194 "float b[1][] = {{3.f}};\n", 17195 Alignment); 17196 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17197 verifyFormat("float a, b = 1;\n" 17198 "int c = 2;\n" 17199 "int dd = 3;\n", 17200 Alignment); 17201 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17202 "float b[1][] = {{3.f}};\n", 17203 Alignment); 17204 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 17205 17206 Alignment.ColumnLimit = 30; 17207 Alignment.BinPackParameters = false; 17208 verifyFormat("void foo(float a,\n" 17209 " float b,\n" 17210 " int c,\n" 17211 " uint32_t *d) {\n" 17212 " int *e = 0;\n" 17213 " float f = 0;\n" 17214 " double g = 0;\n" 17215 "}\n" 17216 "void bar(ino_t a,\n" 17217 " int b,\n" 17218 " uint32_t *c,\n" 17219 " bool d) {}\n", 17220 Alignment); 17221 Alignment.BinPackParameters = true; 17222 Alignment.ColumnLimit = 80; 17223 17224 // Bug 33507 17225 Alignment.PointerAlignment = FormatStyle::PAS_Middle; 17226 verifyFormat( 17227 "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n" 17228 " static const Version verVs2017;\n" 17229 " return true;\n" 17230 "});\n", 17231 Alignment); 17232 Alignment.PointerAlignment = FormatStyle::PAS_Right; 17233 17234 // See llvm.org/PR35641 17235 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17236 verifyFormat("int func() { //\n" 17237 " int b;\n" 17238 " unsigned c;\n" 17239 "}", 17240 Alignment); 17241 17242 // See PR37175 17243 FormatStyle Style = getMozillaStyle(); 17244 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17245 EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n" 17246 "foo(int a);", 17247 format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style)); 17248 17249 Alignment.PointerAlignment = FormatStyle::PAS_Left; 17250 verifyFormat("unsigned int* a;\n" 17251 "int* b;\n" 17252 "unsigned int Const* c;\n" 17253 "unsigned int const* d;\n" 17254 "unsigned int Const& e;\n" 17255 "unsigned int const& f;", 17256 Alignment); 17257 verifyFormat("Const unsigned int* c;\n" 17258 "const unsigned int* d;\n" 17259 "Const unsigned int& e;\n" 17260 "const unsigned int& f;\n" 17261 "const unsigned g;\n" 17262 "Const unsigned h;", 17263 Alignment); 17264 17265 Alignment.PointerAlignment = FormatStyle::PAS_Middle; 17266 verifyFormat("unsigned int * a;\n" 17267 "int * b;\n" 17268 "unsigned int Const * c;\n" 17269 "unsigned int const * d;\n" 17270 "unsigned int Const & e;\n" 17271 "unsigned int const & f;", 17272 Alignment); 17273 verifyFormat("Const unsigned int * c;\n" 17274 "const unsigned int * d;\n" 17275 "Const unsigned int & e;\n" 17276 "const unsigned int & f;\n" 17277 "const unsigned g;\n" 17278 "Const unsigned h;", 17279 Alignment); 17280 17281 // See PR46529 17282 FormatStyle BracedAlign = getLLVMStyle(); 17283 BracedAlign.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17284 verifyFormat("const auto result{[]() {\n" 17285 " const auto something = 1;\n" 17286 " return 2;\n" 17287 "}};", 17288 BracedAlign); 17289 verifyFormat("int foo{[]() {\n" 17290 " int bar{0};\n" 17291 " return 0;\n" 17292 "}()};", 17293 BracedAlign); 17294 BracedAlign.Cpp11BracedListStyle = false; 17295 verifyFormat("const auto result{ []() {\n" 17296 " const auto something = 1;\n" 17297 " return 2;\n" 17298 "} };", 17299 BracedAlign); 17300 verifyFormat("int foo{ []() {\n" 17301 " int bar{ 0 };\n" 17302 " return 0;\n" 17303 "}() };", 17304 BracedAlign); 17305 } 17306 17307 TEST_F(FormatTest, AlignWithLineBreaks) { 17308 auto Style = getLLVMStyleWithColumns(120); 17309 17310 EXPECT_EQ(Style.AlignConsecutiveAssignments, FormatStyle::ACS_None); 17311 EXPECT_EQ(Style.AlignConsecutiveDeclarations, FormatStyle::ACS_None); 17312 verifyFormat("void foo() {\n" 17313 " int myVar = 5;\n" 17314 " double x = 3.14;\n" 17315 " auto str = \"Hello \"\n" 17316 " \"World\";\n" 17317 " auto s = \"Hello \"\n" 17318 " \"Again\";\n" 17319 "}", 17320 Style); 17321 17322 // clang-format off 17323 verifyFormat("void foo() {\n" 17324 " const int capacityBefore = Entries.capacity();\n" 17325 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17326 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17327 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17328 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17329 "}", 17330 Style); 17331 // clang-format on 17332 17333 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17334 verifyFormat("void foo() {\n" 17335 " int myVar = 5;\n" 17336 " double x = 3.14;\n" 17337 " auto str = \"Hello \"\n" 17338 " \"World\";\n" 17339 " auto s = \"Hello \"\n" 17340 " \"Again\";\n" 17341 "}", 17342 Style); 17343 17344 // clang-format off 17345 verifyFormat("void foo() {\n" 17346 " const int capacityBefore = Entries.capacity();\n" 17347 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17348 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17349 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17350 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17351 "}", 17352 Style); 17353 // clang-format on 17354 17355 Style.AlignConsecutiveAssignments = FormatStyle::ACS_None; 17356 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17357 verifyFormat("void foo() {\n" 17358 " int myVar = 5;\n" 17359 " double x = 3.14;\n" 17360 " auto str = \"Hello \"\n" 17361 " \"World\";\n" 17362 " auto s = \"Hello \"\n" 17363 " \"Again\";\n" 17364 "}", 17365 Style); 17366 17367 // clang-format off 17368 verifyFormat("void foo() {\n" 17369 " const int capacityBefore = Entries.capacity();\n" 17370 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17371 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17372 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17373 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17374 "}", 17375 Style); 17376 // clang-format on 17377 17378 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17379 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17380 17381 verifyFormat("void foo() {\n" 17382 " int myVar = 5;\n" 17383 " double x = 3.14;\n" 17384 " auto str = \"Hello \"\n" 17385 " \"World\";\n" 17386 " auto s = \"Hello \"\n" 17387 " \"Again\";\n" 17388 "}", 17389 Style); 17390 17391 // clang-format off 17392 verifyFormat("void foo() {\n" 17393 " const int capacityBefore = Entries.capacity();\n" 17394 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17395 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17396 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17397 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17398 "}", 17399 Style); 17400 // clang-format on 17401 17402 Style = getLLVMStyleWithColumns(120); 17403 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17404 Style.ContinuationIndentWidth = 4; 17405 Style.IndentWidth = 4; 17406 17407 // clang-format off 17408 verifyFormat("void SomeFunc() {\n" 17409 " newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 17410 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17411 " newWatcher.maxAge = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 17412 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17413 " newWatcher.max = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 17414 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17415 "}", 17416 Style); 17417 // clang-format on 17418 17419 Style.BinPackArguments = false; 17420 17421 // clang-format off 17422 verifyFormat("void SomeFunc() {\n" 17423 " newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(\n" 17424 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17425 " newWatcher.maxAge = ToLegacyTimestamp(GetMaxAge(\n" 17426 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17427 " newWatcher.max = ToLegacyTimestamp(GetMaxAge(\n" 17428 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17429 "}", 17430 Style); 17431 // clang-format on 17432 } 17433 17434 TEST_F(FormatTest, AlignWithInitializerPeriods) { 17435 auto Style = getLLVMStyleWithColumns(60); 17436 17437 verifyFormat("void foo1(void) {\n" 17438 " BYTE p[1] = 1;\n" 17439 " A B = {.one_foooooooooooooooo = 2,\n" 17440 " .two_fooooooooooooo = 3,\n" 17441 " .three_fooooooooooooo = 4};\n" 17442 " BYTE payload = 2;\n" 17443 "}", 17444 Style); 17445 17446 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17447 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_None; 17448 verifyFormat("void foo2(void) {\n" 17449 " BYTE p[1] = 1;\n" 17450 " A B = {.one_foooooooooooooooo = 2,\n" 17451 " .two_fooooooooooooo = 3,\n" 17452 " .three_fooooooooooooo = 4};\n" 17453 " BYTE payload = 2;\n" 17454 "}", 17455 Style); 17456 17457 Style.AlignConsecutiveAssignments = FormatStyle::ACS_None; 17458 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17459 verifyFormat("void foo3(void) {\n" 17460 " BYTE p[1] = 1;\n" 17461 " A B = {.one_foooooooooooooooo = 2,\n" 17462 " .two_fooooooooooooo = 3,\n" 17463 " .three_fooooooooooooo = 4};\n" 17464 " BYTE payload = 2;\n" 17465 "}", 17466 Style); 17467 17468 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17469 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17470 verifyFormat("void foo4(void) {\n" 17471 " BYTE p[1] = 1;\n" 17472 " A B = {.one_foooooooooooooooo = 2,\n" 17473 " .two_fooooooooooooo = 3,\n" 17474 " .three_fooooooooooooo = 4};\n" 17475 " BYTE payload = 2;\n" 17476 "}", 17477 Style); 17478 } 17479 17480 TEST_F(FormatTest, LinuxBraceBreaking) { 17481 FormatStyle LinuxBraceStyle = getLLVMStyle(); 17482 LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux; 17483 verifyFormat("namespace a\n" 17484 "{\n" 17485 "class A\n" 17486 "{\n" 17487 " void f()\n" 17488 " {\n" 17489 " if (true) {\n" 17490 " a();\n" 17491 " b();\n" 17492 " } else {\n" 17493 " a();\n" 17494 " }\n" 17495 " }\n" 17496 " void g() { return; }\n" 17497 "};\n" 17498 "struct B {\n" 17499 " int x;\n" 17500 "};\n" 17501 "} // namespace a\n", 17502 LinuxBraceStyle); 17503 verifyFormat("enum X {\n" 17504 " Y = 0,\n" 17505 "}\n", 17506 LinuxBraceStyle); 17507 verifyFormat("struct S {\n" 17508 " int Type;\n" 17509 " union {\n" 17510 " int x;\n" 17511 " double y;\n" 17512 " } Value;\n" 17513 " class C\n" 17514 " {\n" 17515 " MyFavoriteType Value;\n" 17516 " } Class;\n" 17517 "}\n", 17518 LinuxBraceStyle); 17519 } 17520 17521 TEST_F(FormatTest, MozillaBraceBreaking) { 17522 FormatStyle MozillaBraceStyle = getLLVMStyle(); 17523 MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla; 17524 MozillaBraceStyle.FixNamespaceComments = false; 17525 verifyFormat("namespace a {\n" 17526 "class A\n" 17527 "{\n" 17528 " void f()\n" 17529 " {\n" 17530 " if (true) {\n" 17531 " a();\n" 17532 " b();\n" 17533 " }\n" 17534 " }\n" 17535 " void g() { return; }\n" 17536 "};\n" 17537 "enum E\n" 17538 "{\n" 17539 " A,\n" 17540 " // foo\n" 17541 " B,\n" 17542 " C\n" 17543 "};\n" 17544 "struct B\n" 17545 "{\n" 17546 " int x;\n" 17547 "};\n" 17548 "}\n", 17549 MozillaBraceStyle); 17550 verifyFormat("struct S\n" 17551 "{\n" 17552 " int Type;\n" 17553 " union\n" 17554 " {\n" 17555 " int x;\n" 17556 " double y;\n" 17557 " } Value;\n" 17558 " class C\n" 17559 " {\n" 17560 " MyFavoriteType Value;\n" 17561 " } Class;\n" 17562 "}\n", 17563 MozillaBraceStyle); 17564 } 17565 17566 TEST_F(FormatTest, StroustrupBraceBreaking) { 17567 FormatStyle StroustrupBraceStyle = getLLVMStyle(); 17568 StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 17569 verifyFormat("namespace a {\n" 17570 "class A {\n" 17571 " void f()\n" 17572 " {\n" 17573 " if (true) {\n" 17574 " a();\n" 17575 " b();\n" 17576 " }\n" 17577 " }\n" 17578 " void g() { return; }\n" 17579 "};\n" 17580 "struct B {\n" 17581 " int x;\n" 17582 "};\n" 17583 "} // namespace a\n", 17584 StroustrupBraceStyle); 17585 17586 verifyFormat("void foo()\n" 17587 "{\n" 17588 " if (a) {\n" 17589 " a();\n" 17590 " }\n" 17591 " else {\n" 17592 " b();\n" 17593 " }\n" 17594 "}\n", 17595 StroustrupBraceStyle); 17596 17597 verifyFormat("#ifdef _DEBUG\n" 17598 "int foo(int i = 0)\n" 17599 "#else\n" 17600 "int foo(int i = 5)\n" 17601 "#endif\n" 17602 "{\n" 17603 " return i;\n" 17604 "}", 17605 StroustrupBraceStyle); 17606 17607 verifyFormat("void foo() {}\n" 17608 "void bar()\n" 17609 "#ifdef _DEBUG\n" 17610 "{\n" 17611 " foo();\n" 17612 "}\n" 17613 "#else\n" 17614 "{\n" 17615 "}\n" 17616 "#endif", 17617 StroustrupBraceStyle); 17618 17619 verifyFormat("void foobar() { int i = 5; }\n" 17620 "#ifdef _DEBUG\n" 17621 "void bar() {}\n" 17622 "#else\n" 17623 "void bar() { foobar(); }\n" 17624 "#endif", 17625 StroustrupBraceStyle); 17626 } 17627 17628 TEST_F(FormatTest, AllmanBraceBreaking) { 17629 FormatStyle AllmanBraceStyle = getLLVMStyle(); 17630 AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman; 17631 17632 EXPECT_EQ("namespace a\n" 17633 "{\n" 17634 "void f();\n" 17635 "void g();\n" 17636 "} // namespace a\n", 17637 format("namespace a\n" 17638 "{\n" 17639 "void f();\n" 17640 "void g();\n" 17641 "}\n", 17642 AllmanBraceStyle)); 17643 17644 verifyFormat("namespace a\n" 17645 "{\n" 17646 "class A\n" 17647 "{\n" 17648 " void f()\n" 17649 " {\n" 17650 " if (true)\n" 17651 " {\n" 17652 " a();\n" 17653 " b();\n" 17654 " }\n" 17655 " }\n" 17656 " void g() { return; }\n" 17657 "};\n" 17658 "struct B\n" 17659 "{\n" 17660 " int x;\n" 17661 "};\n" 17662 "union C\n" 17663 "{\n" 17664 "};\n" 17665 "} // namespace a", 17666 AllmanBraceStyle); 17667 17668 verifyFormat("void f()\n" 17669 "{\n" 17670 " if (true)\n" 17671 " {\n" 17672 " a();\n" 17673 " }\n" 17674 " else if (false)\n" 17675 " {\n" 17676 " b();\n" 17677 " }\n" 17678 " else\n" 17679 " {\n" 17680 " c();\n" 17681 " }\n" 17682 "}\n", 17683 AllmanBraceStyle); 17684 17685 verifyFormat("void f()\n" 17686 "{\n" 17687 " for (int i = 0; i < 10; ++i)\n" 17688 " {\n" 17689 " a();\n" 17690 " }\n" 17691 " while (false)\n" 17692 " {\n" 17693 " b();\n" 17694 " }\n" 17695 " do\n" 17696 " {\n" 17697 " c();\n" 17698 " } while (false)\n" 17699 "}\n", 17700 AllmanBraceStyle); 17701 17702 verifyFormat("void f(int a)\n" 17703 "{\n" 17704 " switch (a)\n" 17705 " {\n" 17706 " case 0:\n" 17707 " break;\n" 17708 " case 1:\n" 17709 " {\n" 17710 " break;\n" 17711 " }\n" 17712 " case 2:\n" 17713 " {\n" 17714 " }\n" 17715 " break;\n" 17716 " default:\n" 17717 " break;\n" 17718 " }\n" 17719 "}\n", 17720 AllmanBraceStyle); 17721 17722 verifyFormat("enum X\n" 17723 "{\n" 17724 " Y = 0,\n" 17725 "}\n", 17726 AllmanBraceStyle); 17727 verifyFormat("enum X\n" 17728 "{\n" 17729 " Y = 0\n" 17730 "}\n", 17731 AllmanBraceStyle); 17732 17733 verifyFormat("@interface BSApplicationController ()\n" 17734 "{\n" 17735 "@private\n" 17736 " id _extraIvar;\n" 17737 "}\n" 17738 "@end\n", 17739 AllmanBraceStyle); 17740 17741 verifyFormat("#ifdef _DEBUG\n" 17742 "int foo(int i = 0)\n" 17743 "#else\n" 17744 "int foo(int i = 5)\n" 17745 "#endif\n" 17746 "{\n" 17747 " return i;\n" 17748 "}", 17749 AllmanBraceStyle); 17750 17751 verifyFormat("void foo() {}\n" 17752 "void bar()\n" 17753 "#ifdef _DEBUG\n" 17754 "{\n" 17755 " foo();\n" 17756 "}\n" 17757 "#else\n" 17758 "{\n" 17759 "}\n" 17760 "#endif", 17761 AllmanBraceStyle); 17762 17763 verifyFormat("void foobar() { int i = 5; }\n" 17764 "#ifdef _DEBUG\n" 17765 "void bar() {}\n" 17766 "#else\n" 17767 "void bar() { foobar(); }\n" 17768 "#endif", 17769 AllmanBraceStyle); 17770 17771 EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine, 17772 FormatStyle::SLS_All); 17773 17774 verifyFormat("[](int i) { return i + 2; };\n" 17775 "[](int i, int j)\n" 17776 "{\n" 17777 " auto x = i + j;\n" 17778 " auto y = i * j;\n" 17779 " return x ^ y;\n" 17780 "};\n" 17781 "void foo()\n" 17782 "{\n" 17783 " auto shortLambda = [](int i) { return i + 2; };\n" 17784 " auto longLambda = [](int i, int j)\n" 17785 " {\n" 17786 " auto x = i + j;\n" 17787 " auto y = i * j;\n" 17788 " return x ^ y;\n" 17789 " };\n" 17790 "}", 17791 AllmanBraceStyle); 17792 17793 AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 17794 17795 verifyFormat("[](int i)\n" 17796 "{\n" 17797 " return i + 2;\n" 17798 "};\n" 17799 "[](int i, int j)\n" 17800 "{\n" 17801 " auto x = i + j;\n" 17802 " auto y = i * j;\n" 17803 " return x ^ y;\n" 17804 "};\n" 17805 "void foo()\n" 17806 "{\n" 17807 " auto shortLambda = [](int i)\n" 17808 " {\n" 17809 " return i + 2;\n" 17810 " };\n" 17811 " auto longLambda = [](int i, int j)\n" 17812 " {\n" 17813 " auto x = i + j;\n" 17814 " auto y = i * j;\n" 17815 " return x ^ y;\n" 17816 " };\n" 17817 "}", 17818 AllmanBraceStyle); 17819 17820 // Reset 17821 AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All; 17822 17823 // This shouldn't affect ObjC blocks.. 17824 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n" 17825 " // ...\n" 17826 " int i;\n" 17827 "}];", 17828 AllmanBraceStyle); 17829 verifyFormat("void (^block)(void) = ^{\n" 17830 " // ...\n" 17831 " int i;\n" 17832 "};", 17833 AllmanBraceStyle); 17834 // .. or dict literals. 17835 verifyFormat("void f()\n" 17836 "{\n" 17837 " // ...\n" 17838 " [object someMethod:@{@\"a\" : @\"b\"}];\n" 17839 "}", 17840 AllmanBraceStyle); 17841 verifyFormat("void f()\n" 17842 "{\n" 17843 " // ...\n" 17844 " [object someMethod:@{a : @\"b\"}];\n" 17845 "}", 17846 AllmanBraceStyle); 17847 verifyFormat("int f()\n" 17848 "{ // comment\n" 17849 " return 42;\n" 17850 "}", 17851 AllmanBraceStyle); 17852 17853 AllmanBraceStyle.ColumnLimit = 19; 17854 verifyFormat("void f() { int i; }", AllmanBraceStyle); 17855 AllmanBraceStyle.ColumnLimit = 18; 17856 verifyFormat("void f()\n" 17857 "{\n" 17858 " int i;\n" 17859 "}", 17860 AllmanBraceStyle); 17861 AllmanBraceStyle.ColumnLimit = 80; 17862 17863 FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle; 17864 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = 17865 FormatStyle::SIS_WithoutElse; 17866 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true; 17867 verifyFormat("void f(bool b)\n" 17868 "{\n" 17869 " if (b)\n" 17870 " {\n" 17871 " return;\n" 17872 " }\n" 17873 "}\n", 17874 BreakBeforeBraceShortIfs); 17875 verifyFormat("void f(bool b)\n" 17876 "{\n" 17877 " if constexpr (b)\n" 17878 " {\n" 17879 " return;\n" 17880 " }\n" 17881 "}\n", 17882 BreakBeforeBraceShortIfs); 17883 verifyFormat("void f(bool b)\n" 17884 "{\n" 17885 " if CONSTEXPR (b)\n" 17886 " {\n" 17887 " return;\n" 17888 " }\n" 17889 "}\n", 17890 BreakBeforeBraceShortIfs); 17891 verifyFormat("void f(bool b)\n" 17892 "{\n" 17893 " if (b) return;\n" 17894 "}\n", 17895 BreakBeforeBraceShortIfs); 17896 verifyFormat("void f(bool b)\n" 17897 "{\n" 17898 " if constexpr (b) return;\n" 17899 "}\n", 17900 BreakBeforeBraceShortIfs); 17901 verifyFormat("void f(bool b)\n" 17902 "{\n" 17903 " if CONSTEXPR (b) return;\n" 17904 "}\n", 17905 BreakBeforeBraceShortIfs); 17906 verifyFormat("void f(bool b)\n" 17907 "{\n" 17908 " while (b)\n" 17909 " {\n" 17910 " return;\n" 17911 " }\n" 17912 "}\n", 17913 BreakBeforeBraceShortIfs); 17914 } 17915 17916 TEST_F(FormatTest, WhitesmithsBraceBreaking) { 17917 FormatStyle WhitesmithsBraceStyle = getLLVMStyleWithColumns(0); 17918 WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 17919 17920 // Make a few changes to the style for testing purposes 17921 WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine = 17922 FormatStyle::SFS_Empty; 17923 WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 17924 17925 // FIXME: this test case can't decide whether there should be a blank line 17926 // after the ~D() line or not. It adds one if one doesn't exist in the test 17927 // and it removes the line if one exists. 17928 /* 17929 verifyFormat("class A;\n" 17930 "namespace B\n" 17931 " {\n" 17932 "class C;\n" 17933 "// Comment\n" 17934 "class D\n" 17935 " {\n" 17936 "public:\n" 17937 " D();\n" 17938 " ~D() {}\n" 17939 "private:\n" 17940 " enum E\n" 17941 " {\n" 17942 " F\n" 17943 " }\n" 17944 " };\n" 17945 " } // namespace B\n", 17946 WhitesmithsBraceStyle); 17947 */ 17948 17949 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None; 17950 verifyFormat("namespace a\n" 17951 " {\n" 17952 "class A\n" 17953 " {\n" 17954 " void f()\n" 17955 " {\n" 17956 " if (true)\n" 17957 " {\n" 17958 " a();\n" 17959 " b();\n" 17960 " }\n" 17961 " }\n" 17962 " void g()\n" 17963 " {\n" 17964 " return;\n" 17965 " }\n" 17966 " };\n" 17967 "struct B\n" 17968 " {\n" 17969 " int x;\n" 17970 " };\n" 17971 " } // namespace a", 17972 WhitesmithsBraceStyle); 17973 17974 verifyFormat("namespace a\n" 17975 " {\n" 17976 "namespace b\n" 17977 " {\n" 17978 "class A\n" 17979 " {\n" 17980 " void f()\n" 17981 " {\n" 17982 " if (true)\n" 17983 " {\n" 17984 " a();\n" 17985 " b();\n" 17986 " }\n" 17987 " }\n" 17988 " void g()\n" 17989 " {\n" 17990 " return;\n" 17991 " }\n" 17992 " };\n" 17993 "struct B\n" 17994 " {\n" 17995 " int x;\n" 17996 " };\n" 17997 " } // namespace b\n" 17998 " } // namespace a", 17999 WhitesmithsBraceStyle); 18000 18001 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner; 18002 verifyFormat("namespace a\n" 18003 " {\n" 18004 "namespace b\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()\n" 18017 " {\n" 18018 " return;\n" 18019 " }\n" 18020 " };\n" 18021 " struct B\n" 18022 " {\n" 18023 " int x;\n" 18024 " };\n" 18025 " } // namespace b\n" 18026 " } // namespace a", 18027 WhitesmithsBraceStyle); 18028 18029 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All; 18030 verifyFormat("namespace a\n" 18031 " {\n" 18032 " namespace b\n" 18033 " {\n" 18034 " class A\n" 18035 " {\n" 18036 " void f()\n" 18037 " {\n" 18038 " if (true)\n" 18039 " {\n" 18040 " a();\n" 18041 " b();\n" 18042 " }\n" 18043 " }\n" 18044 " void g()\n" 18045 " {\n" 18046 " return;\n" 18047 " }\n" 18048 " };\n" 18049 " struct B\n" 18050 " {\n" 18051 " int x;\n" 18052 " };\n" 18053 " } // namespace b\n" 18054 " } // namespace a", 18055 WhitesmithsBraceStyle); 18056 18057 verifyFormat("void f()\n" 18058 " {\n" 18059 " if (true)\n" 18060 " {\n" 18061 " a();\n" 18062 " }\n" 18063 " else if (false)\n" 18064 " {\n" 18065 " b();\n" 18066 " }\n" 18067 " else\n" 18068 " {\n" 18069 " c();\n" 18070 " }\n" 18071 " }\n", 18072 WhitesmithsBraceStyle); 18073 18074 verifyFormat("void f()\n" 18075 " {\n" 18076 " for (int i = 0; i < 10; ++i)\n" 18077 " {\n" 18078 " a();\n" 18079 " }\n" 18080 " while (false)\n" 18081 " {\n" 18082 " b();\n" 18083 " }\n" 18084 " do\n" 18085 " {\n" 18086 " c();\n" 18087 " } while (false)\n" 18088 " }\n", 18089 WhitesmithsBraceStyle); 18090 18091 WhitesmithsBraceStyle.IndentCaseLabels = true; 18092 verifyFormat("void switchTest1(int a)\n" 18093 " {\n" 18094 " switch (a)\n" 18095 " {\n" 18096 " case 2:\n" 18097 " {\n" 18098 " }\n" 18099 " break;\n" 18100 " }\n" 18101 " }\n", 18102 WhitesmithsBraceStyle); 18103 18104 verifyFormat("void switchTest2(int a)\n" 18105 " {\n" 18106 " switch (a)\n" 18107 " {\n" 18108 " case 0:\n" 18109 " break;\n" 18110 " case 1:\n" 18111 " {\n" 18112 " break;\n" 18113 " }\n" 18114 " case 2:\n" 18115 " {\n" 18116 " }\n" 18117 " break;\n" 18118 " default:\n" 18119 " break;\n" 18120 " }\n" 18121 " }\n", 18122 WhitesmithsBraceStyle); 18123 18124 verifyFormat("void switchTest3(int a)\n" 18125 " {\n" 18126 " switch (a)\n" 18127 " {\n" 18128 " case 0:\n" 18129 " {\n" 18130 " foo(x);\n" 18131 " }\n" 18132 " break;\n" 18133 " default:\n" 18134 " {\n" 18135 " foo(1);\n" 18136 " }\n" 18137 " break;\n" 18138 " }\n" 18139 " }\n", 18140 WhitesmithsBraceStyle); 18141 18142 WhitesmithsBraceStyle.IndentCaseLabels = false; 18143 18144 verifyFormat("void switchTest4(int a)\n" 18145 " {\n" 18146 " switch (a)\n" 18147 " {\n" 18148 " case 2:\n" 18149 " {\n" 18150 " }\n" 18151 " break;\n" 18152 " }\n" 18153 " }\n", 18154 WhitesmithsBraceStyle); 18155 18156 verifyFormat("void switchTest5(int a)\n" 18157 " {\n" 18158 " switch (a)\n" 18159 " {\n" 18160 " case 0:\n" 18161 " break;\n" 18162 " case 1:\n" 18163 " {\n" 18164 " foo();\n" 18165 " break;\n" 18166 " }\n" 18167 " case 2:\n" 18168 " {\n" 18169 " }\n" 18170 " break;\n" 18171 " default:\n" 18172 " break;\n" 18173 " }\n" 18174 " }\n", 18175 WhitesmithsBraceStyle); 18176 18177 verifyFormat("void switchTest6(int a)\n" 18178 " {\n" 18179 " switch (a)\n" 18180 " {\n" 18181 " case 0:\n" 18182 " {\n" 18183 " foo(x);\n" 18184 " }\n" 18185 " break;\n" 18186 " default:\n" 18187 " {\n" 18188 " foo(1);\n" 18189 " }\n" 18190 " break;\n" 18191 " }\n" 18192 " }\n", 18193 WhitesmithsBraceStyle); 18194 18195 verifyFormat("enum X\n" 18196 " {\n" 18197 " Y = 0, // testing\n" 18198 " }\n", 18199 WhitesmithsBraceStyle); 18200 18201 verifyFormat("enum X\n" 18202 " {\n" 18203 " Y = 0\n" 18204 " }\n", 18205 WhitesmithsBraceStyle); 18206 verifyFormat("enum X\n" 18207 " {\n" 18208 " Y = 0,\n" 18209 " Z = 1\n" 18210 " };\n", 18211 WhitesmithsBraceStyle); 18212 18213 verifyFormat("@interface BSApplicationController ()\n" 18214 " {\n" 18215 "@private\n" 18216 " id _extraIvar;\n" 18217 " }\n" 18218 "@end\n", 18219 WhitesmithsBraceStyle); 18220 18221 verifyFormat("#ifdef _DEBUG\n" 18222 "int foo(int i = 0)\n" 18223 "#else\n" 18224 "int foo(int i = 5)\n" 18225 "#endif\n" 18226 " {\n" 18227 " return i;\n" 18228 " }", 18229 WhitesmithsBraceStyle); 18230 18231 verifyFormat("void foo() {}\n" 18232 "void bar()\n" 18233 "#ifdef _DEBUG\n" 18234 " {\n" 18235 " foo();\n" 18236 " }\n" 18237 "#else\n" 18238 " {\n" 18239 " }\n" 18240 "#endif", 18241 WhitesmithsBraceStyle); 18242 18243 verifyFormat("void foobar()\n" 18244 " {\n" 18245 " int i = 5;\n" 18246 " }\n" 18247 "#ifdef _DEBUG\n" 18248 "void bar()\n" 18249 " {\n" 18250 " }\n" 18251 "#else\n" 18252 "void bar()\n" 18253 " {\n" 18254 " foobar();\n" 18255 " }\n" 18256 "#endif", 18257 WhitesmithsBraceStyle); 18258 18259 // This shouldn't affect ObjC blocks.. 18260 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n" 18261 " // ...\n" 18262 " int i;\n" 18263 "}];", 18264 WhitesmithsBraceStyle); 18265 verifyFormat("void (^block)(void) = ^{\n" 18266 " // ...\n" 18267 " int i;\n" 18268 "};", 18269 WhitesmithsBraceStyle); 18270 // .. or dict literals. 18271 verifyFormat("void f()\n" 18272 " {\n" 18273 " [object someMethod:@{@\"a\" : @\"b\"}];\n" 18274 " }", 18275 WhitesmithsBraceStyle); 18276 18277 verifyFormat("int f()\n" 18278 " { // comment\n" 18279 " return 42;\n" 18280 " }", 18281 WhitesmithsBraceStyle); 18282 18283 FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle; 18284 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = 18285 FormatStyle::SIS_OnlyFirstIf; 18286 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true; 18287 verifyFormat("void f(bool b)\n" 18288 " {\n" 18289 " if (b)\n" 18290 " {\n" 18291 " return;\n" 18292 " }\n" 18293 " }\n", 18294 BreakBeforeBraceShortIfs); 18295 verifyFormat("void f(bool b)\n" 18296 " {\n" 18297 " if (b) return;\n" 18298 " }\n", 18299 BreakBeforeBraceShortIfs); 18300 verifyFormat("void f(bool b)\n" 18301 " {\n" 18302 " while (b)\n" 18303 " {\n" 18304 " return;\n" 18305 " }\n" 18306 " }\n", 18307 BreakBeforeBraceShortIfs); 18308 } 18309 18310 TEST_F(FormatTest, GNUBraceBreaking) { 18311 FormatStyle GNUBraceStyle = getLLVMStyle(); 18312 GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU; 18313 verifyFormat("namespace a\n" 18314 "{\n" 18315 "class A\n" 18316 "{\n" 18317 " void f()\n" 18318 " {\n" 18319 " int a;\n" 18320 " {\n" 18321 " int b;\n" 18322 " }\n" 18323 " if (true)\n" 18324 " {\n" 18325 " a();\n" 18326 " b();\n" 18327 " }\n" 18328 " }\n" 18329 " void g() { return; }\n" 18330 "}\n" 18331 "} // namespace a", 18332 GNUBraceStyle); 18333 18334 verifyFormat("void f()\n" 18335 "{\n" 18336 " if (true)\n" 18337 " {\n" 18338 " a();\n" 18339 " }\n" 18340 " else if (false)\n" 18341 " {\n" 18342 " b();\n" 18343 " }\n" 18344 " else\n" 18345 " {\n" 18346 " c();\n" 18347 " }\n" 18348 "}\n", 18349 GNUBraceStyle); 18350 18351 verifyFormat("void f()\n" 18352 "{\n" 18353 " for (int i = 0; i < 10; ++i)\n" 18354 " {\n" 18355 " a();\n" 18356 " }\n" 18357 " while (false)\n" 18358 " {\n" 18359 " b();\n" 18360 " }\n" 18361 " do\n" 18362 " {\n" 18363 " c();\n" 18364 " }\n" 18365 " while (false);\n" 18366 "}\n", 18367 GNUBraceStyle); 18368 18369 verifyFormat("void f(int a)\n" 18370 "{\n" 18371 " switch (a)\n" 18372 " {\n" 18373 " case 0:\n" 18374 " break;\n" 18375 " case 1:\n" 18376 " {\n" 18377 " break;\n" 18378 " }\n" 18379 " case 2:\n" 18380 " {\n" 18381 " }\n" 18382 " break;\n" 18383 " default:\n" 18384 " break;\n" 18385 " }\n" 18386 "}\n", 18387 GNUBraceStyle); 18388 18389 verifyFormat("enum X\n" 18390 "{\n" 18391 " Y = 0,\n" 18392 "}\n", 18393 GNUBraceStyle); 18394 18395 verifyFormat("@interface BSApplicationController ()\n" 18396 "{\n" 18397 "@private\n" 18398 " id _extraIvar;\n" 18399 "}\n" 18400 "@end\n", 18401 GNUBraceStyle); 18402 18403 verifyFormat("#ifdef _DEBUG\n" 18404 "int foo(int i = 0)\n" 18405 "#else\n" 18406 "int foo(int i = 5)\n" 18407 "#endif\n" 18408 "{\n" 18409 " return i;\n" 18410 "}", 18411 GNUBraceStyle); 18412 18413 verifyFormat("void foo() {}\n" 18414 "void bar()\n" 18415 "#ifdef _DEBUG\n" 18416 "{\n" 18417 " foo();\n" 18418 "}\n" 18419 "#else\n" 18420 "{\n" 18421 "}\n" 18422 "#endif", 18423 GNUBraceStyle); 18424 18425 verifyFormat("void foobar() { int i = 5; }\n" 18426 "#ifdef _DEBUG\n" 18427 "void bar() {}\n" 18428 "#else\n" 18429 "void bar() { foobar(); }\n" 18430 "#endif", 18431 GNUBraceStyle); 18432 } 18433 18434 TEST_F(FormatTest, WebKitBraceBreaking) { 18435 FormatStyle WebKitBraceStyle = getLLVMStyle(); 18436 WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit; 18437 WebKitBraceStyle.FixNamespaceComments = false; 18438 verifyFormat("namespace a {\n" 18439 "class A {\n" 18440 " void f()\n" 18441 " {\n" 18442 " if (true) {\n" 18443 " a();\n" 18444 " b();\n" 18445 " }\n" 18446 " }\n" 18447 " void g() { return; }\n" 18448 "};\n" 18449 "enum E {\n" 18450 " A,\n" 18451 " // foo\n" 18452 " B,\n" 18453 " C\n" 18454 "};\n" 18455 "struct B {\n" 18456 " int x;\n" 18457 "};\n" 18458 "}\n", 18459 WebKitBraceStyle); 18460 verifyFormat("struct S {\n" 18461 " int Type;\n" 18462 " union {\n" 18463 " int x;\n" 18464 " double y;\n" 18465 " } Value;\n" 18466 " class C {\n" 18467 " MyFavoriteType Value;\n" 18468 " } Class;\n" 18469 "};\n", 18470 WebKitBraceStyle); 18471 } 18472 18473 TEST_F(FormatTest, CatchExceptionReferenceBinding) { 18474 verifyFormat("void f() {\n" 18475 " try {\n" 18476 " } catch (const Exception &e) {\n" 18477 " }\n" 18478 "}\n", 18479 getLLVMStyle()); 18480 } 18481 18482 TEST_F(FormatTest, CatchAlignArrayOfStructuresRightAlignment) { 18483 auto Style = getLLVMStyle(); 18484 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 18485 Style.AlignConsecutiveAssignments = 18486 FormatStyle::AlignConsecutiveStyle::ACS_Consecutive; 18487 Style.AlignConsecutiveDeclarations = 18488 FormatStyle::AlignConsecutiveStyle::ACS_Consecutive; 18489 verifyFormat("struct test demo[] = {\n" 18490 " {56, 23, \"hello\"},\n" 18491 " {-1, 93463, \"world\"},\n" 18492 " { 7, 5, \"!!\"}\n" 18493 "};\n", 18494 Style); 18495 18496 verifyFormat("struct test demo[] = {\n" 18497 " {56, 23, \"hello\"}, // first line\n" 18498 " {-1, 93463, \"world\"}, // second line\n" 18499 " { 7, 5, \"!!\"} // third line\n" 18500 "};\n", 18501 Style); 18502 18503 verifyFormat("struct test demo[4] = {\n" 18504 " { 56, 23, 21, \"oh\"}, // first line\n" 18505 " { -1, 93463, 22, \"my\"}, // second line\n" 18506 " { 7, 5, 1, \"goodness\"} // third line\n" 18507 " {234, 5, 1, \"gracious\"} // fourth line\n" 18508 "};\n", 18509 Style); 18510 18511 verifyFormat("struct test demo[3] = {\n" 18512 " {56, 23, \"hello\"},\n" 18513 " {-1, 93463, \"world\"},\n" 18514 " { 7, 5, \"!!\"}\n" 18515 "};\n", 18516 Style); 18517 18518 verifyFormat("struct test demo[3] = {\n" 18519 " {int{56}, 23, \"hello\"},\n" 18520 " {int{-1}, 93463, \"world\"},\n" 18521 " { int{7}, 5, \"!!\"}\n" 18522 "};\n", 18523 Style); 18524 18525 verifyFormat("struct test demo[] = {\n" 18526 " {56, 23, \"hello\"},\n" 18527 " {-1, 93463, \"world\"},\n" 18528 " { 7, 5, \"!!\"},\n" 18529 "};\n", 18530 Style); 18531 18532 verifyFormat("test demo[] = {\n" 18533 " {56, 23, \"hello\"},\n" 18534 " {-1, 93463, \"world\"},\n" 18535 " { 7, 5, \"!!\"},\n" 18536 "};\n", 18537 Style); 18538 18539 verifyFormat("demo = std::array<struct test, 3>{\n" 18540 " test{56, 23, \"hello\"},\n" 18541 " test{-1, 93463, \"world\"},\n" 18542 " test{ 7, 5, \"!!\"},\n" 18543 "};\n", 18544 Style); 18545 18546 verifyFormat("test demo[] = {\n" 18547 " {56, 23, \"hello\"},\n" 18548 "#if X\n" 18549 " {-1, 93463, \"world\"},\n" 18550 "#endif\n" 18551 " { 7, 5, \"!!\"}\n" 18552 "};\n", 18553 Style); 18554 18555 verifyFormat( 18556 "test demo[] = {\n" 18557 " { 7, 23,\n" 18558 " \"hello world i am a very long line that really, in any\"\n" 18559 " \"just world, ought to be split over multiple lines\"},\n" 18560 " {-1, 93463, \"world\"},\n" 18561 " {56, 5, \"!!\"}\n" 18562 "};\n", 18563 Style); 18564 18565 verifyFormat("return GradForUnaryCwise(g, {\n" 18566 " {{\"sign\"}, \"Sign\", " 18567 " {\"x\", \"dy\"}},\n" 18568 " { {\"dx\"}, \"Mul\", {\"dy\"" 18569 ", \"sign\"}},\n" 18570 "});\n", 18571 Style); 18572 18573 Style.ColumnLimit = 0; 18574 EXPECT_EQ( 18575 "test demo[] = {\n" 18576 " {56, 23, \"hello world i am a very long line that really, " 18577 "in any just world, ought to be split over multiple lines\"},\n" 18578 " {-1, 93463, " 18579 " \"world\"},\n" 18580 " { 7, 5, " 18581 " \"!!\"},\n" 18582 "};", 18583 format("test demo[] = {{56, 23, \"hello world i am a very long line " 18584 "that really, in any just world, ought to be split over multiple " 18585 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 18586 Style)); 18587 18588 Style.ColumnLimit = 80; 18589 verifyFormat("test demo[] = {\n" 18590 " {56, 23, /* a comment */ \"hello\"},\n" 18591 " {-1, 93463, \"world\"},\n" 18592 " { 7, 5, \"!!\"}\n" 18593 "};\n", 18594 Style); 18595 18596 verifyFormat("test demo[] = {\n" 18597 " {56, 23, \"hello\"},\n" 18598 " {-1, 93463, \"world\" /* comment here */},\n" 18599 " { 7, 5, \"!!\"}\n" 18600 "};\n", 18601 Style); 18602 18603 verifyFormat("test demo[] = {\n" 18604 " {56, /* a comment */ 23, \"hello\"},\n" 18605 " {-1, 93463, \"world\"},\n" 18606 " { 7, 5, \"!!\"}\n" 18607 "};\n", 18608 Style); 18609 18610 Style.ColumnLimit = 20; 18611 EXPECT_EQ( 18612 "demo = std::array<\n" 18613 " struct test, 3>{\n" 18614 " test{\n" 18615 " 56, 23,\n" 18616 " \"hello \"\n" 18617 " \"world i \"\n" 18618 " \"am a very \"\n" 18619 " \"long line \"\n" 18620 " \"that \"\n" 18621 " \"really, \"\n" 18622 " \"in any \"\n" 18623 " \"just \"\n" 18624 " \"world, \"\n" 18625 " \"ought to \"\n" 18626 " \"be split \"\n" 18627 " \"over \"\n" 18628 " \"multiple \"\n" 18629 " \"lines\"},\n" 18630 " test{-1, 93463,\n" 18631 " \"world\"},\n" 18632 " test{ 7, 5,\n" 18633 " \"!!\" },\n" 18634 "};", 18635 format("demo = std::array<struct test, 3>{test{56, 23, \"hello world " 18636 "i am a very long line that really, in any just world, ought " 18637 "to be split over multiple lines\"},test{-1, 93463, \"world\"}," 18638 "test{7, 5, \"!!\"},};", 18639 Style)); 18640 // This caused a core dump by enabling Alignment in the LLVMStyle globally 18641 Style = getLLVMStyleWithColumns(50); 18642 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 18643 verifyFormat("static A x = {\n" 18644 " {{init1, init2, init3, init4},\n" 18645 " {init1, init2, init3, init4}}\n" 18646 "};", 18647 Style); 18648 Style.ColumnLimit = 100; 18649 EXPECT_EQ( 18650 "test demo[] = {\n" 18651 " {56, 23,\n" 18652 " \"hello world i am a very long line that really, in any just world" 18653 ", ought to be split over \"\n" 18654 " \"multiple lines\" },\n" 18655 " {-1, 93463, \"world\"},\n" 18656 " { 7, 5, \"!!\"},\n" 18657 "};", 18658 format("test demo[] = {{56, 23, \"hello world i am a very long line " 18659 "that really, in any just world, ought to be split over multiple " 18660 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 18661 Style)); 18662 18663 Style = getLLVMStyleWithColumns(50); 18664 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 18665 Style.AlignConsecutiveAssignments = 18666 FormatStyle::AlignConsecutiveStyle::ACS_Consecutive; 18667 Style.AlignConsecutiveDeclarations = 18668 FormatStyle::AlignConsecutiveStyle::ACS_Consecutive; 18669 verifyFormat("struct test demo[] = {\n" 18670 " {56, 23, \"hello\"},\n" 18671 " {-1, 93463, \"world\"},\n" 18672 " { 7, 5, \"!!\"}\n" 18673 "};\n" 18674 "static A x = {\n" 18675 " {{init1, init2, init3, init4},\n" 18676 " {init1, init2, init3, init4}}\n" 18677 "};", 18678 Style); 18679 Style.ColumnLimit = 100; 18680 Style.AlignConsecutiveAssignments = 18681 FormatStyle::AlignConsecutiveStyle::ACS_AcrossComments; 18682 Style.AlignConsecutiveDeclarations = 18683 FormatStyle::AlignConsecutiveStyle::ACS_AcrossComments; 18684 verifyFormat("struct test demo[] = {\n" 18685 " {56, 23, \"hello\"},\n" 18686 " {-1, 93463, \"world\"},\n" 18687 " { 7, 5, \"!!\"}\n" 18688 "};\n" 18689 "struct test demo[4] = {\n" 18690 " { 56, 23, 21, \"oh\"}, // first line\n" 18691 " { -1, 93463, 22, \"my\"}, // second line\n" 18692 " { 7, 5, 1, \"goodness\"} // third line\n" 18693 " {234, 5, 1, \"gracious\"} // fourth line\n" 18694 "};\n", 18695 Style); 18696 EXPECT_EQ( 18697 "test demo[] = {\n" 18698 " {56,\n" 18699 " \"hello world i am a very long line that really, in any just world" 18700 ", ought to be split over \"\n" 18701 " \"multiple lines\", 23},\n" 18702 " {-1, \"world\", 93463},\n" 18703 " { 7, \"!!\", 5},\n" 18704 "};", 18705 format("test demo[] = {{56, \"hello world i am a very long line " 18706 "that really, in any just world, ought to be split over multiple " 18707 "lines\", 23},{-1, \"world\", 93463},{7, \"!!\", 5},};", 18708 Style)); 18709 } 18710 18711 TEST_F(FormatTest, CatchAlignArrayOfStructuresLeftAlignment) { 18712 auto Style = getLLVMStyle(); 18713 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 18714 /* FIXME: This case gets misformatted. 18715 verifyFormat("auto foo = Items{\n" 18716 " Section{0, bar(), },\n" 18717 " Section{1, boo() }\n" 18718 "};\n", 18719 Style); 18720 */ 18721 verifyFormat("auto foo = Items{\n" 18722 " Section{\n" 18723 " 0, bar(),\n" 18724 " }\n" 18725 "};\n", 18726 Style); 18727 verifyFormat("struct test demo[] = {\n" 18728 " {56, 23, \"hello\"},\n" 18729 " {-1, 93463, \"world\"},\n" 18730 " {7, 5, \"!!\" }\n" 18731 "};\n", 18732 Style); 18733 verifyFormat("struct test demo[] = {\n" 18734 " {56, 23, \"hello\"}, // first line\n" 18735 " {-1, 93463, \"world\"}, // second line\n" 18736 " {7, 5, \"!!\" } // third line\n" 18737 "};\n", 18738 Style); 18739 verifyFormat("struct test demo[4] = {\n" 18740 " {56, 23, 21, \"oh\" }, // first line\n" 18741 " {-1, 93463, 22, \"my\" }, // second line\n" 18742 " {7, 5, 1, \"goodness\"} // third line\n" 18743 " {234, 5, 1, \"gracious\"} // fourth line\n" 18744 "};\n", 18745 Style); 18746 verifyFormat("struct test demo[3] = {\n" 18747 " {56, 23, \"hello\"},\n" 18748 " {-1, 93463, \"world\"},\n" 18749 " {7, 5, \"!!\" }\n" 18750 "};\n", 18751 Style); 18752 18753 verifyFormat("struct test demo[3] = {\n" 18754 " {int{56}, 23, \"hello\"},\n" 18755 " {int{-1}, 93463, \"world\"},\n" 18756 " {int{7}, 5, \"!!\" }\n" 18757 "};\n", 18758 Style); 18759 verifyFormat("struct test demo[] = {\n" 18760 " {56, 23, \"hello\"},\n" 18761 " {-1, 93463, \"world\"},\n" 18762 " {7, 5, \"!!\" },\n" 18763 "};\n", 18764 Style); 18765 verifyFormat("test demo[] = {\n" 18766 " {56, 23, \"hello\"},\n" 18767 " {-1, 93463, \"world\"},\n" 18768 " {7, 5, \"!!\" },\n" 18769 "};\n", 18770 Style); 18771 verifyFormat("demo = std::array<struct test, 3>{\n" 18772 " test{56, 23, \"hello\"},\n" 18773 " test{-1, 93463, \"world\"},\n" 18774 " test{7, 5, \"!!\" },\n" 18775 "};\n", 18776 Style); 18777 verifyFormat("test demo[] = {\n" 18778 " {56, 23, \"hello\"},\n" 18779 "#if X\n" 18780 " {-1, 93463, \"world\"},\n" 18781 "#endif\n" 18782 " {7, 5, \"!!\" }\n" 18783 "};\n", 18784 Style); 18785 verifyFormat( 18786 "test demo[] = {\n" 18787 " {7, 23,\n" 18788 " \"hello world i am a very long line that really, in any\"\n" 18789 " \"just world, ought to be split over multiple lines\"},\n" 18790 " {-1, 93463, \"world\" },\n" 18791 " {56, 5, \"!!\" }\n" 18792 "};\n", 18793 Style); 18794 18795 verifyFormat("return GradForUnaryCwise(g, {\n" 18796 " {{\"sign\"}, \"Sign\", {\"x\", " 18797 "\"dy\"} },\n" 18798 " {{\"dx\"}, \"Mul\", " 18799 "{\"dy\", \"sign\"}},\n" 18800 "});\n", 18801 Style); 18802 18803 Style.ColumnLimit = 0; 18804 EXPECT_EQ( 18805 "test demo[] = {\n" 18806 " {56, 23, \"hello world i am a very long line that really, in any " 18807 "just world, ought to be split over multiple lines\"},\n" 18808 " {-1, 93463, \"world\" " 18809 " },\n" 18810 " {7, 5, \"!!\" " 18811 " },\n" 18812 "};", 18813 format("test demo[] = {{56, 23, \"hello world i am a very long line " 18814 "that really, in any just world, ought to be split over multiple " 18815 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 18816 Style)); 18817 18818 Style.ColumnLimit = 80; 18819 verifyFormat("test demo[] = {\n" 18820 " {56, 23, /* a comment */ \"hello\"},\n" 18821 " {-1, 93463, \"world\" },\n" 18822 " {7, 5, \"!!\" }\n" 18823 "};\n", 18824 Style); 18825 18826 verifyFormat("test demo[] = {\n" 18827 " {56, 23, \"hello\" },\n" 18828 " {-1, 93463, \"world\" /* comment here */},\n" 18829 " {7, 5, \"!!\" }\n" 18830 "};\n", 18831 Style); 18832 18833 verifyFormat("test demo[] = {\n" 18834 " {56, /* a comment */ 23, \"hello\"},\n" 18835 " {-1, 93463, \"world\"},\n" 18836 " {7, 5, \"!!\" }\n" 18837 "};\n", 18838 Style); 18839 18840 Style.ColumnLimit = 20; 18841 EXPECT_EQ( 18842 "demo = std::array<\n" 18843 " struct test, 3>{\n" 18844 " test{\n" 18845 " 56, 23,\n" 18846 " \"hello \"\n" 18847 " \"world i \"\n" 18848 " \"am a very \"\n" 18849 " \"long line \"\n" 18850 " \"that \"\n" 18851 " \"really, \"\n" 18852 " \"in any \"\n" 18853 " \"just \"\n" 18854 " \"world, \"\n" 18855 " \"ought to \"\n" 18856 " \"be split \"\n" 18857 " \"over \"\n" 18858 " \"multiple \"\n" 18859 " \"lines\"},\n" 18860 " test{-1, 93463,\n" 18861 " \"world\"},\n" 18862 " test{7, 5,\n" 18863 " \"!!\" },\n" 18864 "};", 18865 format("demo = std::array<struct test, 3>{test{56, 23, \"hello world " 18866 "i am a very long line that really, in any just world, ought " 18867 "to be split over multiple lines\"},test{-1, 93463, \"world\"}," 18868 "test{7, 5, \"!!\"},};", 18869 Style)); 18870 18871 // This caused a core dump by enabling Alignment in the LLVMStyle globally 18872 Style = getLLVMStyleWithColumns(50); 18873 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 18874 verifyFormat("static A x = {\n" 18875 " {{init1, init2, init3, init4},\n" 18876 " {init1, init2, init3, init4}}\n" 18877 "};", 18878 Style); 18879 Style.ColumnLimit = 100; 18880 EXPECT_EQ( 18881 "test demo[] = {\n" 18882 " {56, 23,\n" 18883 " \"hello world i am a very long line that really, in any just world" 18884 ", ought to be split over \"\n" 18885 " \"multiple lines\" },\n" 18886 " {-1, 93463, \"world\"},\n" 18887 " {7, 5, \"!!\" },\n" 18888 "};", 18889 format("test demo[] = {{56, 23, \"hello world i am a very long line " 18890 "that really, in any just world, ought to be split over multiple " 18891 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 18892 Style)); 18893 } 18894 18895 TEST_F(FormatTest, UnderstandsPragmas) { 18896 verifyFormat("#pragma omp reduction(| : var)"); 18897 verifyFormat("#pragma omp reduction(+ : var)"); 18898 18899 EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string " 18900 "(including parentheses).", 18901 format("#pragma mark Any non-hyphenated or hyphenated string " 18902 "(including parentheses).")); 18903 } 18904 18905 TEST_F(FormatTest, UnderstandPragmaOption) { 18906 verifyFormat("#pragma option -C -A"); 18907 18908 EXPECT_EQ("#pragma option -C -A", format("#pragma option -C -A")); 18909 } 18910 18911 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) { 18912 FormatStyle Style = getLLVMStyleWithColumns(20); 18913 18914 // See PR41213 18915 EXPECT_EQ("/*\n" 18916 " *\t9012345\n" 18917 " * /8901\n" 18918 " */", 18919 format("/*\n" 18920 " *\t9012345 /8901\n" 18921 " */", 18922 Style)); 18923 EXPECT_EQ("/*\n" 18924 " *345678\n" 18925 " *\t/8901\n" 18926 " */", 18927 format("/*\n" 18928 " *345678\t/8901\n" 18929 " */", 18930 Style)); 18931 18932 verifyFormat("int a; // the\n" 18933 " // comment", 18934 Style); 18935 EXPECT_EQ("int a; /* first line\n" 18936 " * second\n" 18937 " * line third\n" 18938 " * line\n" 18939 " */", 18940 format("int a; /* first line\n" 18941 " * second\n" 18942 " * line third\n" 18943 " * line\n" 18944 " */", 18945 Style)); 18946 EXPECT_EQ("int a; // first line\n" 18947 " // second\n" 18948 " // line third\n" 18949 " // line", 18950 format("int a; // first line\n" 18951 " // second line\n" 18952 " // third line", 18953 Style)); 18954 18955 Style.PenaltyExcessCharacter = 90; 18956 verifyFormat("int a; // the comment", Style); 18957 EXPECT_EQ("int a; // the comment\n" 18958 " // aaa", 18959 format("int a; // the comment aaa", Style)); 18960 EXPECT_EQ("int a; /* first line\n" 18961 " * second line\n" 18962 " * third line\n" 18963 " */", 18964 format("int a; /* first line\n" 18965 " * second line\n" 18966 " * third line\n" 18967 " */", 18968 Style)); 18969 EXPECT_EQ("int a; // first line\n" 18970 " // second line\n" 18971 " // third line", 18972 format("int a; // first line\n" 18973 " // second line\n" 18974 " // third line", 18975 Style)); 18976 // FIXME: Investigate why this is not getting the same layout as the test 18977 // above. 18978 EXPECT_EQ("int a; /* first line\n" 18979 " * second line\n" 18980 " * third line\n" 18981 " */", 18982 format("int a; /* first line second line third line" 18983 "\n*/", 18984 Style)); 18985 18986 EXPECT_EQ("// foo bar baz bazfoo\n" 18987 "// foo bar foo bar\n", 18988 format("// foo bar baz bazfoo\n" 18989 "// foo bar foo bar\n", 18990 Style)); 18991 EXPECT_EQ("// foo bar baz bazfoo\n" 18992 "// foo bar foo bar\n", 18993 format("// foo bar baz bazfoo\n" 18994 "// foo bar foo bar\n", 18995 Style)); 18996 18997 // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the 18998 // next one. 18999 EXPECT_EQ("// foo bar baz bazfoo\n" 19000 "// bar foo bar\n", 19001 format("// foo bar baz bazfoo bar\n" 19002 "// foo bar\n", 19003 Style)); 19004 19005 EXPECT_EQ("// foo bar baz bazfoo\n" 19006 "// foo bar baz bazfoo\n" 19007 "// bar foo bar\n", 19008 format("// foo bar baz bazfoo\n" 19009 "// foo bar baz bazfoo bar\n" 19010 "// foo bar\n", 19011 Style)); 19012 19013 EXPECT_EQ("// foo bar baz bazfoo\n" 19014 "// foo bar baz bazfoo\n" 19015 "// bar foo bar\n", 19016 format("// foo bar baz bazfoo\n" 19017 "// foo bar baz bazfoo bar\n" 19018 "// foo bar\n", 19019 Style)); 19020 19021 // Make sure we do not keep protruding characters if strict mode reflow is 19022 // cheaper than keeping protruding characters. 19023 Style.ColumnLimit = 21; 19024 EXPECT_EQ( 19025 "// foo foo foo foo\n" 19026 "// foo foo foo foo\n" 19027 "// foo foo foo foo\n", 19028 format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style)); 19029 19030 EXPECT_EQ("int a = /* long block\n" 19031 " comment */\n" 19032 " 42;", 19033 format("int a = /* long block comment */ 42;", Style)); 19034 } 19035 19036 TEST_F(FormatTest, BreakPenaltyAfterLParen) { 19037 FormatStyle Style = getLLVMStyle(); 19038 Style.ColumnLimit = 8; 19039 Style.PenaltyExcessCharacter = 15; 19040 verifyFormat("int foo(\n" 19041 " int aaaaaaaaaaaaaaaaaaaaaaaa);", 19042 Style); 19043 Style.PenaltyBreakOpenParenthesis = 200; 19044 EXPECT_EQ("int foo(int aaaaaaaaaaaaaaaaaaaaaaaa);", 19045 format("int foo(\n" 19046 " int aaaaaaaaaaaaaaaaaaaaaaaa);", 19047 Style)); 19048 } 19049 19050 TEST_F(FormatTest, BreakPenaltyAfterCastLParen) { 19051 FormatStyle Style = getLLVMStyle(); 19052 Style.ColumnLimit = 5; 19053 Style.PenaltyExcessCharacter = 150; 19054 verifyFormat("foo((\n" 19055 " int)aaaaaaaaaaaaaaaaaaaaaaaa);", 19056 19057 Style); 19058 Style.PenaltyBreakOpenParenthesis = 100000; 19059 EXPECT_EQ("foo((int)\n" 19060 " aaaaaaaaaaaaaaaaaaaaaaaa);", 19061 format("foo((\n" 19062 "int)aaaaaaaaaaaaaaaaaaaaaaaa);", 19063 Style)); 19064 } 19065 19066 TEST_F(FormatTest, BreakPenaltyAfterForLoopLParen) { 19067 FormatStyle Style = getLLVMStyle(); 19068 Style.ColumnLimit = 4; 19069 Style.PenaltyExcessCharacter = 100; 19070 verifyFormat("for (\n" 19071 " int iiiiiiiiiiiiiiiii =\n" 19072 " 0;\n" 19073 " iiiiiiiiiiiiiiiii <\n" 19074 " 2;\n" 19075 " iiiiiiiiiiiiiiiii++) {\n" 19076 "}", 19077 19078 Style); 19079 Style.PenaltyBreakOpenParenthesis = 1250; 19080 EXPECT_EQ("for (int iiiiiiiiiiiiiiiii =\n" 19081 " 0;\n" 19082 " iiiiiiiiiiiiiiiii <\n" 19083 " 2;\n" 19084 " iiiiiiiiiiiiiiiii++) {\n" 19085 "}", 19086 format("for (\n" 19087 " int iiiiiiiiiiiiiiiii =\n" 19088 " 0;\n" 19089 " iiiiiiiiiiiiiiiii <\n" 19090 " 2;\n" 19091 " iiiiiiiiiiiiiiiii++) {\n" 19092 "}", 19093 Style)); 19094 } 19095 19096 #define EXPECT_ALL_STYLES_EQUAL(Styles) \ 19097 for (size_t i = 1; i < Styles.size(); ++i) \ 19098 EXPECT_EQ(Styles[0], Styles[i]) \ 19099 << "Style #" << i << " of " << Styles.size() << " differs from Style #0" 19100 19101 TEST_F(FormatTest, GetsPredefinedStyleByName) { 19102 SmallVector<FormatStyle, 3> Styles; 19103 Styles.resize(3); 19104 19105 Styles[0] = getLLVMStyle(); 19106 EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1])); 19107 EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2])); 19108 EXPECT_ALL_STYLES_EQUAL(Styles); 19109 19110 Styles[0] = getGoogleStyle(); 19111 EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1])); 19112 EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2])); 19113 EXPECT_ALL_STYLES_EQUAL(Styles); 19114 19115 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript); 19116 EXPECT_TRUE( 19117 getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1])); 19118 EXPECT_TRUE( 19119 getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2])); 19120 EXPECT_ALL_STYLES_EQUAL(Styles); 19121 19122 Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp); 19123 EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1])); 19124 EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2])); 19125 EXPECT_ALL_STYLES_EQUAL(Styles); 19126 19127 Styles[0] = getMozillaStyle(); 19128 EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1])); 19129 EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2])); 19130 EXPECT_ALL_STYLES_EQUAL(Styles); 19131 19132 Styles[0] = getWebKitStyle(); 19133 EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1])); 19134 EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2])); 19135 EXPECT_ALL_STYLES_EQUAL(Styles); 19136 19137 Styles[0] = getGNUStyle(); 19138 EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1])); 19139 EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2])); 19140 EXPECT_ALL_STYLES_EQUAL(Styles); 19141 19142 EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0])); 19143 } 19144 19145 TEST_F(FormatTest, GetsCorrectBasedOnStyle) { 19146 SmallVector<FormatStyle, 8> Styles; 19147 Styles.resize(2); 19148 19149 Styles[0] = getGoogleStyle(); 19150 Styles[1] = getLLVMStyle(); 19151 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value()); 19152 EXPECT_ALL_STYLES_EQUAL(Styles); 19153 19154 Styles.resize(5); 19155 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript); 19156 Styles[1] = getLLVMStyle(); 19157 Styles[1].Language = FormatStyle::LK_JavaScript; 19158 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value()); 19159 19160 Styles[2] = getLLVMStyle(); 19161 Styles[2].Language = FormatStyle::LK_JavaScript; 19162 EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n" 19163 "BasedOnStyle: Google", 19164 &Styles[2]) 19165 .value()); 19166 19167 Styles[3] = getLLVMStyle(); 19168 Styles[3].Language = FormatStyle::LK_JavaScript; 19169 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n" 19170 "Language: JavaScript", 19171 &Styles[3]) 19172 .value()); 19173 19174 Styles[4] = getLLVMStyle(); 19175 Styles[4].Language = FormatStyle::LK_JavaScript; 19176 EXPECT_EQ(0, parseConfiguration("---\n" 19177 "BasedOnStyle: LLVM\n" 19178 "IndentWidth: 123\n" 19179 "---\n" 19180 "BasedOnStyle: Google\n" 19181 "Language: JavaScript", 19182 &Styles[4]) 19183 .value()); 19184 EXPECT_ALL_STYLES_EQUAL(Styles); 19185 } 19186 19187 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME) \ 19188 Style.FIELD = false; \ 19189 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value()); \ 19190 EXPECT_TRUE(Style.FIELD); \ 19191 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value()); \ 19192 EXPECT_FALSE(Style.FIELD); 19193 19194 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD) 19195 19196 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME) \ 19197 Style.STRUCT.FIELD = false; \ 19198 EXPECT_EQ(0, \ 19199 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": true", &Style) \ 19200 .value()); \ 19201 EXPECT_TRUE(Style.STRUCT.FIELD); \ 19202 EXPECT_EQ(0, \ 19203 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": false", &Style) \ 19204 .value()); \ 19205 EXPECT_FALSE(Style.STRUCT.FIELD); 19206 19207 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD) \ 19208 CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD) 19209 19210 #define CHECK_PARSE(TEXT, FIELD, VALUE) \ 19211 EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!"; \ 19212 EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value()); \ 19213 EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!" 19214 19215 TEST_F(FormatTest, ParsesConfigurationBools) { 19216 FormatStyle Style = {}; 19217 Style.Language = FormatStyle::LK_Cpp; 19218 CHECK_PARSE_BOOL(AlignTrailingComments); 19219 CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine); 19220 CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine); 19221 CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine); 19222 CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine); 19223 CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine); 19224 CHECK_PARSE_BOOL(BinPackArguments); 19225 CHECK_PARSE_BOOL(BinPackParameters); 19226 CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations); 19227 CHECK_PARSE_BOOL(BreakBeforeConceptDeclarations); 19228 CHECK_PARSE_BOOL(BreakBeforeTernaryOperators); 19229 CHECK_PARSE_BOOL(BreakStringLiterals); 19230 CHECK_PARSE_BOOL(CompactNamespaces); 19231 CHECK_PARSE_BOOL(DeriveLineEnding); 19232 CHECK_PARSE_BOOL(DerivePointerAlignment); 19233 CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding"); 19234 CHECK_PARSE_BOOL(DisableFormat); 19235 CHECK_PARSE_BOOL(IndentAccessModifiers); 19236 CHECK_PARSE_BOOL(IndentCaseLabels); 19237 CHECK_PARSE_BOOL(IndentCaseBlocks); 19238 CHECK_PARSE_BOOL(IndentGotoLabels); 19239 CHECK_PARSE_BOOL(IndentRequires); 19240 CHECK_PARSE_BOOL(IndentWrappedFunctionNames); 19241 CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks); 19242 CHECK_PARSE_BOOL(ObjCSpaceAfterProperty); 19243 CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList); 19244 CHECK_PARSE_BOOL(Cpp11BracedListStyle); 19245 CHECK_PARSE_BOOL(ReflowComments); 19246 CHECK_PARSE_BOOL(RemoveBracesLLVM); 19247 CHECK_PARSE_BOOL(SortUsingDeclarations); 19248 CHECK_PARSE_BOOL(SpacesInParentheses); 19249 CHECK_PARSE_BOOL(SpacesInSquareBrackets); 19250 CHECK_PARSE_BOOL(SpacesInConditionalStatement); 19251 CHECK_PARSE_BOOL(SpaceInEmptyBlock); 19252 CHECK_PARSE_BOOL(SpaceInEmptyParentheses); 19253 CHECK_PARSE_BOOL(SpacesInContainerLiterals); 19254 CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses); 19255 CHECK_PARSE_BOOL(SpaceAfterCStyleCast); 19256 CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword); 19257 CHECK_PARSE_BOOL(SpaceAfterLogicalNot); 19258 CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators); 19259 CHECK_PARSE_BOOL(SpaceBeforeCaseColon); 19260 CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList); 19261 CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon); 19262 CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon); 19263 CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon); 19264 CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets); 19265 CHECK_PARSE_BOOL(UseCRLF); 19266 19267 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel); 19268 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass); 19269 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum); 19270 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction); 19271 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace); 19272 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration); 19273 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct); 19274 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion); 19275 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock); 19276 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch); 19277 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse); 19278 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody); 19279 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile); 19280 CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces); 19281 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction); 19282 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord); 19283 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace); 19284 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterControlStatements); 19285 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterForeachMacros); 19286 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, 19287 AfterFunctionDeclarationName); 19288 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, 19289 AfterFunctionDefinitionName); 19290 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterIfMacros); 19291 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterOverloadedOperator); 19292 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, BeforeNonEmptyParentheses); 19293 } 19294 19295 #undef CHECK_PARSE_BOOL 19296 19297 TEST_F(FormatTest, ParsesConfiguration) { 19298 FormatStyle Style = {}; 19299 Style.Language = FormatStyle::LK_Cpp; 19300 CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234); 19301 CHECK_PARSE("ConstructorInitializerIndentWidth: 1234", 19302 ConstructorInitializerIndentWidth, 1234u); 19303 CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u); 19304 CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u); 19305 CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u); 19306 CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u); 19307 CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234", 19308 PenaltyBreakBeforeFirstCallParameter, 1234u); 19309 CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234", 19310 PenaltyBreakTemplateDeclaration, 1234u); 19311 CHECK_PARSE("PenaltyBreakOpenParenthesis: 1234", PenaltyBreakOpenParenthesis, 19312 1234u); 19313 CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u); 19314 CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234", 19315 PenaltyReturnTypeOnItsOwnLine, 1234u); 19316 CHECK_PARSE("SpacesBeforeTrailingComments: 1234", 19317 SpacesBeforeTrailingComments, 1234u); 19318 CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u); 19319 CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u); 19320 CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$"); 19321 19322 Style.QualifierAlignment = FormatStyle::QAS_Right; 19323 CHECK_PARSE("QualifierAlignment: Leave", QualifierAlignment, 19324 FormatStyle::QAS_Leave); 19325 CHECK_PARSE("QualifierAlignment: Right", QualifierAlignment, 19326 FormatStyle::QAS_Right); 19327 CHECK_PARSE("QualifierAlignment: Left", QualifierAlignment, 19328 FormatStyle::QAS_Left); 19329 CHECK_PARSE("QualifierAlignment: Custom", QualifierAlignment, 19330 FormatStyle::QAS_Custom); 19331 19332 Style.QualifierOrder.clear(); 19333 CHECK_PARSE("QualifierOrder: [ const, volatile, type ]", QualifierOrder, 19334 std::vector<std::string>({"const", "volatile", "type"})); 19335 Style.QualifierOrder.clear(); 19336 CHECK_PARSE("QualifierOrder: [const, type]", QualifierOrder, 19337 std::vector<std::string>({"const", "type"})); 19338 Style.QualifierOrder.clear(); 19339 CHECK_PARSE("QualifierOrder: [volatile, type]", QualifierOrder, 19340 std::vector<std::string>({"volatile", "type"})); 19341 19342 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 19343 CHECK_PARSE("AlignConsecutiveAssignments: None", AlignConsecutiveAssignments, 19344 FormatStyle::ACS_None); 19345 CHECK_PARSE("AlignConsecutiveAssignments: Consecutive", 19346 AlignConsecutiveAssignments, FormatStyle::ACS_Consecutive); 19347 CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLines", 19348 AlignConsecutiveAssignments, FormatStyle::ACS_AcrossEmptyLines); 19349 CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLinesAndComments", 19350 AlignConsecutiveAssignments, 19351 FormatStyle::ACS_AcrossEmptyLinesAndComments); 19352 // For backwards compability, false / true should still parse 19353 CHECK_PARSE("AlignConsecutiveAssignments: false", AlignConsecutiveAssignments, 19354 FormatStyle::ACS_None); 19355 CHECK_PARSE("AlignConsecutiveAssignments: true", AlignConsecutiveAssignments, 19356 FormatStyle::ACS_Consecutive); 19357 19358 Style.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive; 19359 CHECK_PARSE("AlignConsecutiveBitFields: None", AlignConsecutiveBitFields, 19360 FormatStyle::ACS_None); 19361 CHECK_PARSE("AlignConsecutiveBitFields: Consecutive", 19362 AlignConsecutiveBitFields, FormatStyle::ACS_Consecutive); 19363 CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLines", 19364 AlignConsecutiveBitFields, FormatStyle::ACS_AcrossEmptyLines); 19365 CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLinesAndComments", 19366 AlignConsecutiveBitFields, 19367 FormatStyle::ACS_AcrossEmptyLinesAndComments); 19368 // For backwards compability, false / true should still parse 19369 CHECK_PARSE("AlignConsecutiveBitFields: false", AlignConsecutiveBitFields, 19370 FormatStyle::ACS_None); 19371 CHECK_PARSE("AlignConsecutiveBitFields: true", AlignConsecutiveBitFields, 19372 FormatStyle::ACS_Consecutive); 19373 19374 Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 19375 CHECK_PARSE("AlignConsecutiveMacros: None", AlignConsecutiveMacros, 19376 FormatStyle::ACS_None); 19377 CHECK_PARSE("AlignConsecutiveMacros: Consecutive", AlignConsecutiveMacros, 19378 FormatStyle::ACS_Consecutive); 19379 CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLines", 19380 AlignConsecutiveMacros, FormatStyle::ACS_AcrossEmptyLines); 19381 CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLinesAndComments", 19382 AlignConsecutiveMacros, 19383 FormatStyle::ACS_AcrossEmptyLinesAndComments); 19384 // For backwards compability, false / true should still parse 19385 CHECK_PARSE("AlignConsecutiveMacros: false", AlignConsecutiveMacros, 19386 FormatStyle::ACS_None); 19387 CHECK_PARSE("AlignConsecutiveMacros: true", AlignConsecutiveMacros, 19388 FormatStyle::ACS_Consecutive); 19389 19390 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 19391 CHECK_PARSE("AlignConsecutiveDeclarations: None", 19392 AlignConsecutiveDeclarations, FormatStyle::ACS_None); 19393 CHECK_PARSE("AlignConsecutiveDeclarations: Consecutive", 19394 AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive); 19395 CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLines", 19396 AlignConsecutiveDeclarations, FormatStyle::ACS_AcrossEmptyLines); 19397 CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLinesAndComments", 19398 AlignConsecutiveDeclarations, 19399 FormatStyle::ACS_AcrossEmptyLinesAndComments); 19400 // For backwards compability, false / true should still parse 19401 CHECK_PARSE("AlignConsecutiveDeclarations: false", 19402 AlignConsecutiveDeclarations, FormatStyle::ACS_None); 19403 CHECK_PARSE("AlignConsecutiveDeclarations: true", 19404 AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive); 19405 19406 Style.PointerAlignment = FormatStyle::PAS_Middle; 19407 CHECK_PARSE("PointerAlignment: Left", PointerAlignment, 19408 FormatStyle::PAS_Left); 19409 CHECK_PARSE("PointerAlignment: Right", PointerAlignment, 19410 FormatStyle::PAS_Right); 19411 CHECK_PARSE("PointerAlignment: Middle", PointerAlignment, 19412 FormatStyle::PAS_Middle); 19413 Style.ReferenceAlignment = FormatStyle::RAS_Middle; 19414 CHECK_PARSE("ReferenceAlignment: Pointer", ReferenceAlignment, 19415 FormatStyle::RAS_Pointer); 19416 CHECK_PARSE("ReferenceAlignment: Left", ReferenceAlignment, 19417 FormatStyle::RAS_Left); 19418 CHECK_PARSE("ReferenceAlignment: Right", ReferenceAlignment, 19419 FormatStyle::RAS_Right); 19420 CHECK_PARSE("ReferenceAlignment: Middle", ReferenceAlignment, 19421 FormatStyle::RAS_Middle); 19422 // For backward compatibility: 19423 CHECK_PARSE("PointerBindsToType: Left", PointerAlignment, 19424 FormatStyle::PAS_Left); 19425 CHECK_PARSE("PointerBindsToType: Right", PointerAlignment, 19426 FormatStyle::PAS_Right); 19427 CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment, 19428 FormatStyle::PAS_Middle); 19429 19430 Style.Standard = FormatStyle::LS_Auto; 19431 CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03); 19432 CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11); 19433 CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14); 19434 CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17); 19435 CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20); 19436 CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto); 19437 CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest); 19438 // Legacy aliases: 19439 CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03); 19440 CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest); 19441 CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03); 19442 CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11); 19443 19444 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 19445 CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment", 19446 BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment); 19447 CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators, 19448 FormatStyle::BOS_None); 19449 CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators, 19450 FormatStyle::BOS_All); 19451 // For backward compatibility: 19452 CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators, 19453 FormatStyle::BOS_None); 19454 CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators, 19455 FormatStyle::BOS_All); 19456 19457 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 19458 CHECK_PARSE("BreakConstructorInitializers: BeforeComma", 19459 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma); 19460 CHECK_PARSE("BreakConstructorInitializers: AfterColon", 19461 BreakConstructorInitializers, FormatStyle::BCIS_AfterColon); 19462 CHECK_PARSE("BreakConstructorInitializers: BeforeColon", 19463 BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon); 19464 // For backward compatibility: 19465 CHECK_PARSE("BreakConstructorInitializersBeforeComma: true", 19466 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma); 19467 19468 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 19469 CHECK_PARSE("BreakInheritanceList: AfterComma", BreakInheritanceList, 19470 FormatStyle::BILS_AfterComma); 19471 CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList, 19472 FormatStyle::BILS_BeforeComma); 19473 CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList, 19474 FormatStyle::BILS_AfterColon); 19475 CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList, 19476 FormatStyle::BILS_BeforeColon); 19477 // For backward compatibility: 19478 CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList, 19479 FormatStyle::BILS_BeforeComma); 19480 19481 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 19482 CHECK_PARSE("PackConstructorInitializers: Never", PackConstructorInitializers, 19483 FormatStyle::PCIS_Never); 19484 CHECK_PARSE("PackConstructorInitializers: BinPack", 19485 PackConstructorInitializers, FormatStyle::PCIS_BinPack); 19486 CHECK_PARSE("PackConstructorInitializers: CurrentLine", 19487 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 19488 CHECK_PARSE("PackConstructorInitializers: NextLine", 19489 PackConstructorInitializers, FormatStyle::PCIS_NextLine); 19490 // For backward compatibility: 19491 CHECK_PARSE("BasedOnStyle: Google\n" 19492 "ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 19493 "AllowAllConstructorInitializersOnNextLine: false", 19494 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 19495 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 19496 CHECK_PARSE("BasedOnStyle: Google\n" 19497 "ConstructorInitializerAllOnOneLineOrOnePerLine: false", 19498 PackConstructorInitializers, FormatStyle::PCIS_BinPack); 19499 CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 19500 "AllowAllConstructorInitializersOnNextLine: true", 19501 PackConstructorInitializers, FormatStyle::PCIS_NextLine); 19502 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 19503 CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 19504 "AllowAllConstructorInitializersOnNextLine: false", 19505 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 19506 19507 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 19508 CHECK_PARSE("EmptyLineBeforeAccessModifier: Never", 19509 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never); 19510 CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave", 19511 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave); 19512 CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock", 19513 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock); 19514 CHECK_PARSE("EmptyLineBeforeAccessModifier: Always", 19515 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always); 19516 19517 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 19518 CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket, 19519 FormatStyle::BAS_Align); 19520 CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket, 19521 FormatStyle::BAS_DontAlign); 19522 CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket, 19523 FormatStyle::BAS_AlwaysBreak); 19524 CHECK_PARSE("AlignAfterOpenBracket: BlockIndent", AlignAfterOpenBracket, 19525 FormatStyle::BAS_BlockIndent); 19526 // For backward compatibility: 19527 CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket, 19528 FormatStyle::BAS_DontAlign); 19529 CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket, 19530 FormatStyle::BAS_Align); 19531 19532 Style.AlignEscapedNewlines = FormatStyle::ENAS_Left; 19533 CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines, 19534 FormatStyle::ENAS_DontAlign); 19535 CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines, 19536 FormatStyle::ENAS_Left); 19537 CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines, 19538 FormatStyle::ENAS_Right); 19539 // For backward compatibility: 19540 CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines, 19541 FormatStyle::ENAS_Left); 19542 CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines, 19543 FormatStyle::ENAS_Right); 19544 19545 Style.AlignOperands = FormatStyle::OAS_Align; 19546 CHECK_PARSE("AlignOperands: DontAlign", AlignOperands, 19547 FormatStyle::OAS_DontAlign); 19548 CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align); 19549 CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands, 19550 FormatStyle::OAS_AlignAfterOperator); 19551 // For backward compatibility: 19552 CHECK_PARSE("AlignOperands: false", AlignOperands, 19553 FormatStyle::OAS_DontAlign); 19554 CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align); 19555 19556 Style.UseTab = FormatStyle::UT_ForIndentation; 19557 CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never); 19558 CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation); 19559 CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always); 19560 CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab, 19561 FormatStyle::UT_ForContinuationAndIndentation); 19562 CHECK_PARSE("UseTab: AlignWithSpaces", UseTab, 19563 FormatStyle::UT_AlignWithSpaces); 19564 // For backward compatibility: 19565 CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never); 19566 CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always); 19567 19568 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 19569 CHECK_PARSE("AllowShortBlocksOnASingleLine: Never", 19570 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 19571 CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty", 19572 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty); 19573 CHECK_PARSE("AllowShortBlocksOnASingleLine: Always", 19574 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always); 19575 // For backward compatibility: 19576 CHECK_PARSE("AllowShortBlocksOnASingleLine: false", 19577 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 19578 CHECK_PARSE("AllowShortBlocksOnASingleLine: true", 19579 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always); 19580 19581 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 19582 CHECK_PARSE("AllowShortFunctionsOnASingleLine: None", 19583 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None); 19584 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline", 19585 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline); 19586 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty", 19587 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty); 19588 CHECK_PARSE("AllowShortFunctionsOnASingleLine: All", 19589 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All); 19590 // For backward compatibility: 19591 CHECK_PARSE("AllowShortFunctionsOnASingleLine: false", 19592 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None); 19593 CHECK_PARSE("AllowShortFunctionsOnASingleLine: true", 19594 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All); 19595 19596 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both; 19597 CHECK_PARSE("SpaceAroundPointerQualifiers: Default", 19598 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default); 19599 CHECK_PARSE("SpaceAroundPointerQualifiers: Before", 19600 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before); 19601 CHECK_PARSE("SpaceAroundPointerQualifiers: After", 19602 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After); 19603 CHECK_PARSE("SpaceAroundPointerQualifiers: Both", 19604 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both); 19605 19606 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 19607 CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens, 19608 FormatStyle::SBPO_Never); 19609 CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens, 19610 FormatStyle::SBPO_Always); 19611 CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens, 19612 FormatStyle::SBPO_ControlStatements); 19613 CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptControlMacros", 19614 SpaceBeforeParens, 19615 FormatStyle::SBPO_ControlStatementsExceptControlMacros); 19616 CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens, 19617 FormatStyle::SBPO_NonEmptyParentheses); 19618 CHECK_PARSE("SpaceBeforeParens: Custom", SpaceBeforeParens, 19619 FormatStyle::SBPO_Custom); 19620 // For backward compatibility: 19621 CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens, 19622 FormatStyle::SBPO_Never); 19623 CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens, 19624 FormatStyle::SBPO_ControlStatements); 19625 CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptForEachMacros", 19626 SpaceBeforeParens, 19627 FormatStyle::SBPO_ControlStatementsExceptControlMacros); 19628 19629 Style.ColumnLimit = 123; 19630 FormatStyle BaseStyle = getLLVMStyle(); 19631 CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit); 19632 CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u); 19633 19634 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 19635 CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces, 19636 FormatStyle::BS_Attach); 19637 CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces, 19638 FormatStyle::BS_Linux); 19639 CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces, 19640 FormatStyle::BS_Mozilla); 19641 CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces, 19642 FormatStyle::BS_Stroustrup); 19643 CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces, 19644 FormatStyle::BS_Allman); 19645 CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces, 19646 FormatStyle::BS_Whitesmiths); 19647 CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU); 19648 CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces, 19649 FormatStyle::BS_WebKit); 19650 CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces, 19651 FormatStyle::BS_Custom); 19652 19653 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never; 19654 CHECK_PARSE("BraceWrapping:\n" 19655 " AfterControlStatement: MultiLine", 19656 BraceWrapping.AfterControlStatement, 19657 FormatStyle::BWACS_MultiLine); 19658 CHECK_PARSE("BraceWrapping:\n" 19659 " AfterControlStatement: Always", 19660 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always); 19661 CHECK_PARSE("BraceWrapping:\n" 19662 " AfterControlStatement: Never", 19663 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never); 19664 // For backward compatibility: 19665 CHECK_PARSE("BraceWrapping:\n" 19666 " AfterControlStatement: true", 19667 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always); 19668 CHECK_PARSE("BraceWrapping:\n" 19669 " AfterControlStatement: false", 19670 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never); 19671 19672 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 19673 CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType, 19674 FormatStyle::RTBS_None); 19675 CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType, 19676 FormatStyle::RTBS_All); 19677 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel", 19678 AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel); 19679 CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions", 19680 AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions); 19681 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions", 19682 AlwaysBreakAfterReturnType, 19683 FormatStyle::RTBS_TopLevelDefinitions); 19684 19685 Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 19686 CHECK_PARSE("AlwaysBreakTemplateDeclarations: No", 19687 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No); 19688 CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine", 19689 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine); 19690 CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes", 19691 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes); 19692 CHECK_PARSE("AlwaysBreakTemplateDeclarations: false", 19693 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine); 19694 CHECK_PARSE("AlwaysBreakTemplateDeclarations: true", 19695 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes); 19696 19697 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All; 19698 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None", 19699 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None); 19700 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All", 19701 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All); 19702 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel", 19703 AlwaysBreakAfterDefinitionReturnType, 19704 FormatStyle::DRTBS_TopLevel); 19705 19706 Style.NamespaceIndentation = FormatStyle::NI_All; 19707 CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation, 19708 FormatStyle::NI_None); 19709 CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation, 19710 FormatStyle::NI_Inner); 19711 CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation, 19712 FormatStyle::NI_All); 19713 19714 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_OnlyFirstIf; 19715 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never", 19716 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never); 19717 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse", 19718 AllowShortIfStatementsOnASingleLine, 19719 FormatStyle::SIS_WithoutElse); 19720 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: OnlyFirstIf", 19721 AllowShortIfStatementsOnASingleLine, 19722 FormatStyle::SIS_OnlyFirstIf); 19723 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: AllIfsAndElse", 19724 AllowShortIfStatementsOnASingleLine, 19725 FormatStyle::SIS_AllIfsAndElse); 19726 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always", 19727 AllowShortIfStatementsOnASingleLine, 19728 FormatStyle::SIS_OnlyFirstIf); 19729 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false", 19730 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never); 19731 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true", 19732 AllowShortIfStatementsOnASingleLine, 19733 FormatStyle::SIS_WithoutElse); 19734 19735 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 19736 CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock, 19737 FormatStyle::IEBS_AfterExternBlock); 19738 CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock, 19739 FormatStyle::IEBS_Indent); 19740 CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock, 19741 FormatStyle::IEBS_NoIndent); 19742 CHECK_PARSE("IndentExternBlock: true", IndentExternBlock, 19743 FormatStyle::IEBS_Indent); 19744 CHECK_PARSE("IndentExternBlock: false", IndentExternBlock, 19745 FormatStyle::IEBS_NoIndent); 19746 19747 Style.BitFieldColonSpacing = FormatStyle::BFCS_None; 19748 CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing, 19749 FormatStyle::BFCS_Both); 19750 CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing, 19751 FormatStyle::BFCS_None); 19752 CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing, 19753 FormatStyle::BFCS_Before); 19754 CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing, 19755 FormatStyle::BFCS_After); 19756 19757 Style.SortJavaStaticImport = FormatStyle::SJSIO_Before; 19758 CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport, 19759 FormatStyle::SJSIO_After); 19760 CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport, 19761 FormatStyle::SJSIO_Before); 19762 19763 // FIXME: This is required because parsing a configuration simply overwrites 19764 // the first N elements of the list instead of resetting it. 19765 Style.ForEachMacros.clear(); 19766 std::vector<std::string> BoostForeach; 19767 BoostForeach.push_back("BOOST_FOREACH"); 19768 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach); 19769 std::vector<std::string> BoostAndQForeach; 19770 BoostAndQForeach.push_back("BOOST_FOREACH"); 19771 BoostAndQForeach.push_back("Q_FOREACH"); 19772 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros, 19773 BoostAndQForeach); 19774 19775 Style.IfMacros.clear(); 19776 std::vector<std::string> CustomIfs; 19777 CustomIfs.push_back("MYIF"); 19778 CHECK_PARSE("IfMacros: [MYIF]", IfMacros, CustomIfs); 19779 19780 Style.AttributeMacros.clear(); 19781 CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros, 19782 std::vector<std::string>{"__capability"}); 19783 CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros, 19784 std::vector<std::string>({"attr1", "attr2"})); 19785 19786 Style.StatementAttributeLikeMacros.clear(); 19787 CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]", 19788 StatementAttributeLikeMacros, 19789 std::vector<std::string>({"emit", "Q_EMIT"})); 19790 19791 Style.StatementMacros.clear(); 19792 CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros, 19793 std::vector<std::string>{"QUNUSED"}); 19794 CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros, 19795 std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"})); 19796 19797 Style.NamespaceMacros.clear(); 19798 CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros, 19799 std::vector<std::string>{"TESTSUITE"}); 19800 CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros, 19801 std::vector<std::string>({"TESTSUITE", "SUITE"})); 19802 19803 Style.WhitespaceSensitiveMacros.clear(); 19804 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]", 19805 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"}); 19806 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]", 19807 WhitespaceSensitiveMacros, 19808 std::vector<std::string>({"STRINGIZE", "ASSERT"})); 19809 Style.WhitespaceSensitiveMacros.clear(); 19810 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']", 19811 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"}); 19812 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']", 19813 WhitespaceSensitiveMacros, 19814 std::vector<std::string>({"STRINGIZE", "ASSERT"})); 19815 19816 Style.IncludeStyle.IncludeCategories.clear(); 19817 std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = { 19818 {"abc/.*", 2, 0, false}, {".*", 1, 0, true}}; 19819 CHECK_PARSE("IncludeCategories:\n" 19820 " - Regex: abc/.*\n" 19821 " Priority: 2\n" 19822 " - Regex: .*\n" 19823 " Priority: 1\n" 19824 " CaseSensitive: true\n", 19825 IncludeStyle.IncludeCategories, ExpectedCategories); 19826 CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex, 19827 "abc$"); 19828 CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'", 19829 IncludeStyle.IncludeIsMainSourceRegex, "abc$"); 19830 19831 Style.SortIncludes = FormatStyle::SI_Never; 19832 CHECK_PARSE("SortIncludes: true", SortIncludes, 19833 FormatStyle::SI_CaseSensitive); 19834 CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never); 19835 CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes, 19836 FormatStyle::SI_CaseInsensitive); 19837 CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes, 19838 FormatStyle::SI_CaseSensitive); 19839 CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never); 19840 19841 Style.RawStringFormats.clear(); 19842 std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = { 19843 { 19844 FormatStyle::LK_TextProto, 19845 {"pb", "proto"}, 19846 {"PARSE_TEXT_PROTO"}, 19847 /*CanonicalDelimiter=*/"", 19848 "llvm", 19849 }, 19850 { 19851 FormatStyle::LK_Cpp, 19852 {"cc", "cpp"}, 19853 {"C_CODEBLOCK", "CPPEVAL"}, 19854 /*CanonicalDelimiter=*/"cc", 19855 /*BasedOnStyle=*/"", 19856 }, 19857 }; 19858 19859 CHECK_PARSE("RawStringFormats:\n" 19860 " - Language: TextProto\n" 19861 " Delimiters:\n" 19862 " - 'pb'\n" 19863 " - 'proto'\n" 19864 " EnclosingFunctions:\n" 19865 " - 'PARSE_TEXT_PROTO'\n" 19866 " BasedOnStyle: llvm\n" 19867 " - Language: Cpp\n" 19868 " Delimiters:\n" 19869 " - 'cc'\n" 19870 " - 'cpp'\n" 19871 " EnclosingFunctions:\n" 19872 " - 'C_CODEBLOCK'\n" 19873 " - 'CPPEVAL'\n" 19874 " CanonicalDelimiter: 'cc'", 19875 RawStringFormats, ExpectedRawStringFormats); 19876 19877 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 19878 " Minimum: 0\n" 19879 " Maximum: 0", 19880 SpacesInLineCommentPrefix.Minimum, 0u); 19881 EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u); 19882 Style.SpacesInLineCommentPrefix.Minimum = 1; 19883 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 19884 " Minimum: 2", 19885 SpacesInLineCommentPrefix.Minimum, 0u); 19886 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 19887 " Maximum: -1", 19888 SpacesInLineCommentPrefix.Maximum, -1u); 19889 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 19890 " Minimum: 2", 19891 SpacesInLineCommentPrefix.Minimum, 2u); 19892 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 19893 " Maximum: 1", 19894 SpacesInLineCommentPrefix.Maximum, 1u); 19895 EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u); 19896 19897 Style.SpacesInAngles = FormatStyle::SIAS_Always; 19898 CHECK_PARSE("SpacesInAngles: Never", SpacesInAngles, FormatStyle::SIAS_Never); 19899 CHECK_PARSE("SpacesInAngles: Always", SpacesInAngles, 19900 FormatStyle::SIAS_Always); 19901 CHECK_PARSE("SpacesInAngles: Leave", SpacesInAngles, FormatStyle::SIAS_Leave); 19902 // For backward compatibility: 19903 CHECK_PARSE("SpacesInAngles: false", SpacesInAngles, FormatStyle::SIAS_Never); 19904 CHECK_PARSE("SpacesInAngles: true", SpacesInAngles, FormatStyle::SIAS_Always); 19905 } 19906 19907 TEST_F(FormatTest, ParsesConfigurationWithLanguages) { 19908 FormatStyle Style = {}; 19909 Style.Language = FormatStyle::LK_Cpp; 19910 CHECK_PARSE("Language: Cpp\n" 19911 "IndentWidth: 12", 19912 IndentWidth, 12u); 19913 EXPECT_EQ(parseConfiguration("Language: JavaScript\n" 19914 "IndentWidth: 34", 19915 &Style), 19916 ParseError::Unsuitable); 19917 FormatStyle BinPackedTCS = {}; 19918 BinPackedTCS.Language = FormatStyle::LK_JavaScript; 19919 EXPECT_EQ(parseConfiguration("BinPackArguments: true\n" 19920 "InsertTrailingCommas: Wrapped", 19921 &BinPackedTCS), 19922 ParseError::BinPackTrailingCommaConflict); 19923 EXPECT_EQ(12u, Style.IndentWidth); 19924 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u); 19925 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language); 19926 19927 Style.Language = FormatStyle::LK_JavaScript; 19928 CHECK_PARSE("Language: JavaScript\n" 19929 "IndentWidth: 12", 19930 IndentWidth, 12u); 19931 CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u); 19932 EXPECT_EQ(parseConfiguration("Language: Cpp\n" 19933 "IndentWidth: 34", 19934 &Style), 19935 ParseError::Unsuitable); 19936 EXPECT_EQ(23u, Style.IndentWidth); 19937 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u); 19938 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language); 19939 19940 CHECK_PARSE("BasedOnStyle: LLVM\n" 19941 "IndentWidth: 67", 19942 IndentWidth, 67u); 19943 19944 CHECK_PARSE("---\n" 19945 "Language: JavaScript\n" 19946 "IndentWidth: 12\n" 19947 "---\n" 19948 "Language: Cpp\n" 19949 "IndentWidth: 34\n" 19950 "...\n", 19951 IndentWidth, 12u); 19952 19953 Style.Language = FormatStyle::LK_Cpp; 19954 CHECK_PARSE("---\n" 19955 "Language: JavaScript\n" 19956 "IndentWidth: 12\n" 19957 "---\n" 19958 "Language: Cpp\n" 19959 "IndentWidth: 34\n" 19960 "...\n", 19961 IndentWidth, 34u); 19962 CHECK_PARSE("---\n" 19963 "IndentWidth: 78\n" 19964 "---\n" 19965 "Language: JavaScript\n" 19966 "IndentWidth: 56\n" 19967 "...\n", 19968 IndentWidth, 78u); 19969 19970 Style.ColumnLimit = 123; 19971 Style.IndentWidth = 234; 19972 Style.BreakBeforeBraces = FormatStyle::BS_Linux; 19973 Style.TabWidth = 345; 19974 EXPECT_FALSE(parseConfiguration("---\n" 19975 "IndentWidth: 456\n" 19976 "BreakBeforeBraces: Allman\n" 19977 "---\n" 19978 "Language: JavaScript\n" 19979 "IndentWidth: 111\n" 19980 "TabWidth: 111\n" 19981 "---\n" 19982 "Language: Cpp\n" 19983 "BreakBeforeBraces: Stroustrup\n" 19984 "TabWidth: 789\n" 19985 "...\n", 19986 &Style)); 19987 EXPECT_EQ(123u, Style.ColumnLimit); 19988 EXPECT_EQ(456u, Style.IndentWidth); 19989 EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces); 19990 EXPECT_EQ(789u, Style.TabWidth); 19991 19992 EXPECT_EQ(parseConfiguration("---\n" 19993 "Language: JavaScript\n" 19994 "IndentWidth: 56\n" 19995 "---\n" 19996 "IndentWidth: 78\n" 19997 "...\n", 19998 &Style), 19999 ParseError::Error); 20000 EXPECT_EQ(parseConfiguration("---\n" 20001 "Language: JavaScript\n" 20002 "IndentWidth: 56\n" 20003 "---\n" 20004 "Language: JavaScript\n" 20005 "IndentWidth: 78\n" 20006 "...\n", 20007 &Style), 20008 ParseError::Error); 20009 20010 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language); 20011 } 20012 20013 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) { 20014 FormatStyle Style = {}; 20015 Style.Language = FormatStyle::LK_JavaScript; 20016 Style.BreakBeforeTernaryOperators = true; 20017 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value()); 20018 EXPECT_FALSE(Style.BreakBeforeTernaryOperators); 20019 20020 Style.BreakBeforeTernaryOperators = true; 20021 EXPECT_EQ(0, parseConfiguration("---\n" 20022 "BasedOnStyle: Google\n" 20023 "---\n" 20024 "Language: JavaScript\n" 20025 "IndentWidth: 76\n" 20026 "...\n", 20027 &Style) 20028 .value()); 20029 EXPECT_FALSE(Style.BreakBeforeTernaryOperators); 20030 EXPECT_EQ(76u, Style.IndentWidth); 20031 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language); 20032 } 20033 20034 TEST_F(FormatTest, ConfigurationRoundTripTest) { 20035 FormatStyle Style = getLLVMStyle(); 20036 std::string YAML = configurationAsText(Style); 20037 FormatStyle ParsedStyle = {}; 20038 ParsedStyle.Language = FormatStyle::LK_Cpp; 20039 EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value()); 20040 EXPECT_EQ(Style, ParsedStyle); 20041 } 20042 20043 TEST_F(FormatTest, WorksFor8bitEncodings) { 20044 EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n" 20045 "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n" 20046 "\"\xe7\xe8\xec\xed\xfe\xfe \"\n" 20047 "\"\xef\xee\xf0\xf3...\"", 20048 format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 " 20049 "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe " 20050 "\xef\xee\xf0\xf3...\"", 20051 getLLVMStyleWithColumns(12))); 20052 } 20053 20054 TEST_F(FormatTest, HandlesUTF8BOM) { 20055 EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf")); 20056 EXPECT_EQ("\xef\xbb\xbf#include <iostream>", 20057 format("\xef\xbb\xbf#include <iostream>")); 20058 EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>", 20059 format("\xef\xbb\xbf\n#include <iostream>")); 20060 } 20061 20062 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers. 20063 #if !defined(_MSC_VER) 20064 20065 TEST_F(FormatTest, CountsUTF8CharactersProperly) { 20066 verifyFormat("\"Однажды в студёную зимнюю пору...\"", 20067 getLLVMStyleWithColumns(35)); 20068 verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"", 20069 getLLVMStyleWithColumns(31)); 20070 verifyFormat("// Однажды в студёную зимнюю пору...", 20071 getLLVMStyleWithColumns(36)); 20072 verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32)); 20073 verifyFormat("/* Однажды в студёную зимнюю пору... */", 20074 getLLVMStyleWithColumns(39)); 20075 verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */", 20076 getLLVMStyleWithColumns(35)); 20077 } 20078 20079 TEST_F(FormatTest, SplitsUTF8Strings) { 20080 // Non-printable characters' width is currently considered to be the length in 20081 // bytes in UTF8. The characters can be displayed in very different manner 20082 // (zero-width, single width with a substitution glyph, expanded to their code 20083 // (e.g. "<8d>"), so there's no single correct way to handle them. 20084 EXPECT_EQ("\"aaaaÄ\"\n" 20085 "\"\xc2\x8d\";", 20086 format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10))); 20087 EXPECT_EQ("\"aaaaaaaÄ\"\n" 20088 "\"\xc2\x8d\";", 20089 format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10))); 20090 EXPECT_EQ("\"Однажды, в \"\n" 20091 "\"студёную \"\n" 20092 "\"зимнюю \"\n" 20093 "\"пору,\"", 20094 format("\"Однажды, в студёную зимнюю пору,\"", 20095 getLLVMStyleWithColumns(13))); 20096 EXPECT_EQ( 20097 "\"一 二 三 \"\n" 20098 "\"四 五六 \"\n" 20099 "\"七 八 九 \"\n" 20100 "\"十\"", 20101 format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11))); 20102 EXPECT_EQ("\"一\t\"\n" 20103 "\"二 \t\"\n" 20104 "\"三 四 \"\n" 20105 "\"五\t\"\n" 20106 "\"六 \t\"\n" 20107 "\"七 \"\n" 20108 "\"八九十\tqq\"", 20109 format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"", 20110 getLLVMStyleWithColumns(11))); 20111 20112 // UTF8 character in an escape sequence. 20113 EXPECT_EQ("\"aaaaaa\"\n" 20114 "\"\\\xC2\x8D\"", 20115 format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10))); 20116 } 20117 20118 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) { 20119 EXPECT_EQ("const char *sssss =\n" 20120 " \"一二三四五六七八\\\n" 20121 " 九 十\";", 20122 format("const char *sssss = \"一二三四五六七八\\\n" 20123 " 九 十\";", 20124 getLLVMStyleWithColumns(30))); 20125 } 20126 20127 TEST_F(FormatTest, SplitsUTF8LineComments) { 20128 EXPECT_EQ("// aaaaÄ\xc2\x8d", 20129 format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10))); 20130 EXPECT_EQ("// Я из лесу\n" 20131 "// вышел; был\n" 20132 "// сильный\n" 20133 "// мороз.", 20134 format("// Я из лесу вышел; был сильный мороз.", 20135 getLLVMStyleWithColumns(13))); 20136 EXPECT_EQ("// 一二三\n" 20137 "// 四五六七\n" 20138 "// 八 九\n" 20139 "// 十", 20140 format("// 一二三 四五六七 八 九 十", getLLVMStyleWithColumns(9))); 20141 } 20142 20143 TEST_F(FormatTest, SplitsUTF8BlockComments) { 20144 EXPECT_EQ("/* Гляжу,\n" 20145 " * поднимается\n" 20146 " * медленно в\n" 20147 " * гору\n" 20148 " * Лошадка,\n" 20149 " * везущая\n" 20150 " * хворосту\n" 20151 " * воз. */", 20152 format("/* Гляжу, поднимается медленно в гору\n" 20153 " * Лошадка, везущая хворосту воз. */", 20154 getLLVMStyleWithColumns(13))); 20155 EXPECT_EQ( 20156 "/* 一二三\n" 20157 " * 四五六七\n" 20158 " * 八 九\n" 20159 " * 十 */", 20160 format("/* 一二三 四五六七 八 九 十 */", getLLVMStyleWithColumns(9))); 20161 EXPECT_EQ("/* \n" 20162 " * \n" 20163 " * - */", 20164 format("/* - */", getLLVMStyleWithColumns(12))); 20165 } 20166 20167 #endif // _MSC_VER 20168 20169 TEST_F(FormatTest, ConstructorInitializerIndentWidth) { 20170 FormatStyle Style = getLLVMStyle(); 20171 20172 Style.ConstructorInitializerIndentWidth = 4; 20173 verifyFormat( 20174 "SomeClass::Constructor()\n" 20175 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20176 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20177 Style); 20178 20179 Style.ConstructorInitializerIndentWidth = 2; 20180 verifyFormat( 20181 "SomeClass::Constructor()\n" 20182 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20183 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20184 Style); 20185 20186 Style.ConstructorInitializerIndentWidth = 0; 20187 verifyFormat( 20188 "SomeClass::Constructor()\n" 20189 ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20190 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20191 Style); 20192 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 20193 verifyFormat( 20194 "SomeLongTemplateVariableName<\n" 20195 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>", 20196 Style); 20197 verifyFormat("bool smaller = 1 < " 20198 "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 20199 " " 20200 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 20201 Style); 20202 20203 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 20204 verifyFormat("SomeClass::Constructor() :\n" 20205 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n" 20206 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}", 20207 Style); 20208 } 20209 20210 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) { 20211 FormatStyle Style = getLLVMStyle(); 20212 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 20213 Style.ConstructorInitializerIndentWidth = 4; 20214 verifyFormat("SomeClass::Constructor()\n" 20215 " : a(a)\n" 20216 " , b(b)\n" 20217 " , c(c) {}", 20218 Style); 20219 verifyFormat("SomeClass::Constructor()\n" 20220 " : a(a) {}", 20221 Style); 20222 20223 Style.ColumnLimit = 0; 20224 verifyFormat("SomeClass::Constructor()\n" 20225 " : a(a) {}", 20226 Style); 20227 verifyFormat("SomeClass::Constructor() noexcept\n" 20228 " : a(a) {}", 20229 Style); 20230 verifyFormat("SomeClass::Constructor()\n" 20231 " : a(a)\n" 20232 " , b(b)\n" 20233 " , c(c) {}", 20234 Style); 20235 verifyFormat("SomeClass::Constructor()\n" 20236 " : a(a) {\n" 20237 " foo();\n" 20238 " bar();\n" 20239 "}", 20240 Style); 20241 20242 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 20243 verifyFormat("SomeClass::Constructor()\n" 20244 " : a(a)\n" 20245 " , b(b)\n" 20246 " , c(c) {\n}", 20247 Style); 20248 verifyFormat("SomeClass::Constructor()\n" 20249 " : a(a) {\n}", 20250 Style); 20251 20252 Style.ColumnLimit = 80; 20253 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 20254 Style.ConstructorInitializerIndentWidth = 2; 20255 verifyFormat("SomeClass::Constructor()\n" 20256 " : a(a)\n" 20257 " , b(b)\n" 20258 " , c(c) {}", 20259 Style); 20260 20261 Style.ConstructorInitializerIndentWidth = 0; 20262 verifyFormat("SomeClass::Constructor()\n" 20263 ": a(a)\n" 20264 ", b(b)\n" 20265 ", c(c) {}", 20266 Style); 20267 20268 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 20269 Style.ConstructorInitializerIndentWidth = 4; 20270 verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style); 20271 verifyFormat( 20272 "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n", 20273 Style); 20274 verifyFormat( 20275 "SomeClass::Constructor()\n" 20276 " : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}", 20277 Style); 20278 Style.ConstructorInitializerIndentWidth = 4; 20279 Style.ColumnLimit = 60; 20280 verifyFormat("SomeClass::Constructor()\n" 20281 " : aaaaaaaa(aaaaaaaa)\n" 20282 " , aaaaaaaa(aaaaaaaa)\n" 20283 " , aaaaaaaa(aaaaaaaa) {}", 20284 Style); 20285 } 20286 20287 TEST_F(FormatTest, ConstructorInitializersWithPreprocessorDirective) { 20288 FormatStyle Style = getLLVMStyle(); 20289 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 20290 Style.ConstructorInitializerIndentWidth = 4; 20291 verifyFormat("SomeClass::Constructor()\n" 20292 " : a{a}\n" 20293 " , b{b} {}", 20294 Style); 20295 verifyFormat("SomeClass::Constructor()\n" 20296 " : a{a}\n" 20297 "#if CONDITION\n" 20298 " , b{b}\n" 20299 "#endif\n" 20300 "{\n}", 20301 Style); 20302 Style.ConstructorInitializerIndentWidth = 2; 20303 verifyFormat("SomeClass::Constructor()\n" 20304 "#if CONDITION\n" 20305 " : a{a}\n" 20306 "#endif\n" 20307 " , b{b}\n" 20308 " , c{c} {\n}", 20309 Style); 20310 Style.ConstructorInitializerIndentWidth = 0; 20311 verifyFormat("SomeClass::Constructor()\n" 20312 ": a{a}\n" 20313 "#ifdef CONDITION\n" 20314 ", b{b}\n" 20315 "#else\n" 20316 ", c{c}\n" 20317 "#endif\n" 20318 ", d{d} {\n}", 20319 Style); 20320 Style.ConstructorInitializerIndentWidth = 4; 20321 verifyFormat("SomeClass::Constructor()\n" 20322 " : a{a}\n" 20323 "#if WINDOWS\n" 20324 "#if DEBUG\n" 20325 " , b{0}\n" 20326 "#else\n" 20327 " , b{1}\n" 20328 "#endif\n" 20329 "#else\n" 20330 "#if DEBUG\n" 20331 " , b{2}\n" 20332 "#else\n" 20333 " , b{3}\n" 20334 "#endif\n" 20335 "#endif\n" 20336 "{\n}", 20337 Style); 20338 verifyFormat("SomeClass::Constructor()\n" 20339 " : a{a}\n" 20340 "#if WINDOWS\n" 20341 " , b{0}\n" 20342 "#if DEBUG\n" 20343 " , c{0}\n" 20344 "#else\n" 20345 " , c{1}\n" 20346 "#endif\n" 20347 "#else\n" 20348 "#if DEBUG\n" 20349 " , c{2}\n" 20350 "#else\n" 20351 " , c{3}\n" 20352 "#endif\n" 20353 " , b{1}\n" 20354 "#endif\n" 20355 "{\n}", 20356 Style); 20357 } 20358 20359 TEST_F(FormatTest, Destructors) { 20360 verifyFormat("void F(int &i) { i.~int(); }"); 20361 verifyFormat("void F(int &i) { i->~int(); }"); 20362 } 20363 20364 TEST_F(FormatTest, FormatsWithWebKitStyle) { 20365 FormatStyle Style = getWebKitStyle(); 20366 20367 // Don't indent in outer namespaces. 20368 verifyFormat("namespace outer {\n" 20369 "int i;\n" 20370 "namespace inner {\n" 20371 " int i;\n" 20372 "} // namespace inner\n" 20373 "} // namespace outer\n" 20374 "namespace other_outer {\n" 20375 "int i;\n" 20376 "}", 20377 Style); 20378 20379 // Don't indent case labels. 20380 verifyFormat("switch (variable) {\n" 20381 "case 1:\n" 20382 "case 2:\n" 20383 " doSomething();\n" 20384 " break;\n" 20385 "default:\n" 20386 " ++variable;\n" 20387 "}", 20388 Style); 20389 20390 // Wrap before binary operators. 20391 EXPECT_EQ("void f()\n" 20392 "{\n" 20393 " if (aaaaaaaaaaaaaaaa\n" 20394 " && bbbbbbbbbbbbbbbbbbbbbbbb\n" 20395 " && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n" 20396 " return;\n" 20397 "}", 20398 format("void f() {\n" 20399 "if (aaaaaaaaaaaaaaaa\n" 20400 "&& bbbbbbbbbbbbbbbbbbbbbbbb\n" 20401 "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n" 20402 "return;\n" 20403 "}", 20404 Style)); 20405 20406 // Allow functions on a single line. 20407 verifyFormat("void f() { return; }", Style); 20408 20409 // Allow empty blocks on a single line and insert a space in empty blocks. 20410 EXPECT_EQ("void f() { }", format("void f() {}", Style)); 20411 EXPECT_EQ("while (true) { }", format("while (true) {}", Style)); 20412 // However, don't merge non-empty short loops. 20413 EXPECT_EQ("while (true) {\n" 20414 " continue;\n" 20415 "}", 20416 format("while (true) { continue; }", Style)); 20417 20418 // Constructor initializers are formatted one per line with the "," on the 20419 // new line. 20420 verifyFormat("Constructor()\n" 20421 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 20422 " , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n" 20423 " aaaaaaaaaaaaaa)\n" 20424 " , aaaaaaaaaaaaaaaaaaaaaaa()\n" 20425 "{\n" 20426 "}", 20427 Style); 20428 verifyFormat("SomeClass::Constructor()\n" 20429 " : a(a)\n" 20430 "{\n" 20431 "}", 20432 Style); 20433 EXPECT_EQ("SomeClass::Constructor()\n" 20434 " : a(a)\n" 20435 "{\n" 20436 "}", 20437 format("SomeClass::Constructor():a(a){}", Style)); 20438 verifyFormat("SomeClass::Constructor()\n" 20439 " : a(a)\n" 20440 " , b(b)\n" 20441 " , c(c)\n" 20442 "{\n" 20443 "}", 20444 Style); 20445 verifyFormat("SomeClass::Constructor()\n" 20446 " : a(a)\n" 20447 "{\n" 20448 " foo();\n" 20449 " bar();\n" 20450 "}", 20451 Style); 20452 20453 // Access specifiers should be aligned left. 20454 verifyFormat("class C {\n" 20455 "public:\n" 20456 " int i;\n" 20457 "};", 20458 Style); 20459 20460 // Do not align comments. 20461 verifyFormat("int a; // Do not\n" 20462 "double b; // align comments.", 20463 Style); 20464 20465 // Do not align operands. 20466 EXPECT_EQ("ASSERT(aaaa\n" 20467 " || bbbb);", 20468 format("ASSERT ( aaaa\n||bbbb);", Style)); 20469 20470 // Accept input's line breaks. 20471 EXPECT_EQ("if (aaaaaaaaaaaaaaa\n" 20472 " || bbbbbbbbbbbbbbb) {\n" 20473 " i++;\n" 20474 "}", 20475 format("if (aaaaaaaaaaaaaaa\n" 20476 "|| bbbbbbbbbbbbbbb) { i++; }", 20477 Style)); 20478 EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n" 20479 " i++;\n" 20480 "}", 20481 format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style)); 20482 20483 // Don't automatically break all macro definitions (llvm.org/PR17842). 20484 verifyFormat("#define aNumber 10", Style); 20485 // However, generally keep the line breaks that the user authored. 20486 EXPECT_EQ("#define aNumber \\\n" 20487 " 10", 20488 format("#define aNumber \\\n" 20489 " 10", 20490 Style)); 20491 20492 // Keep empty and one-element array literals on a single line. 20493 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n" 20494 " copyItems:YES];", 20495 format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n" 20496 "copyItems:YES];", 20497 Style)); 20498 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n" 20499 " copyItems:YES];", 20500 format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n" 20501 " copyItems:YES];", 20502 Style)); 20503 // FIXME: This does not seem right, there should be more indentation before 20504 // the array literal's entries. Nested blocks have the same problem. 20505 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n" 20506 " @\"a\",\n" 20507 " @\"a\"\n" 20508 "]\n" 20509 " copyItems:YES];", 20510 format("NSArray* a = [[NSArray alloc] initWithArray:@[\n" 20511 " @\"a\",\n" 20512 " @\"a\"\n" 20513 " ]\n" 20514 " copyItems:YES];", 20515 Style)); 20516 EXPECT_EQ( 20517 "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n" 20518 " copyItems:YES];", 20519 format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n" 20520 " copyItems:YES];", 20521 Style)); 20522 20523 verifyFormat("[self.a b:c c:d];", Style); 20524 EXPECT_EQ("[self.a b:c\n" 20525 " c:d];", 20526 format("[self.a b:c\n" 20527 "c:d];", 20528 Style)); 20529 } 20530 20531 TEST_F(FormatTest, FormatsLambdas) { 20532 verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n"); 20533 verifyFormat( 20534 "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n"); 20535 verifyFormat("int c = [&] { [=] { return b++; }(); }();\n"); 20536 verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n"); 20537 verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n"); 20538 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n"); 20539 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n"); 20540 verifyFormat("auto c = [a = [b = 42] {}] {};\n"); 20541 verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n"); 20542 verifyFormat("int x = f(*+[] {});"); 20543 verifyFormat("void f() {\n" 20544 " other(x.begin(), x.end(), [&](int, int) { return 1; });\n" 20545 "}\n"); 20546 verifyFormat("void f() {\n" 20547 " other(x.begin(), //\n" 20548 " x.end(), //\n" 20549 " [&](int, int) { return 1; });\n" 20550 "}\n"); 20551 verifyFormat("void f() {\n" 20552 " other.other.other.other.other(\n" 20553 " x.begin(), x.end(),\n" 20554 " [something, rather](int, int, int, int, int, int, int) { " 20555 "return 1; });\n" 20556 "}\n"); 20557 verifyFormat( 20558 "void f() {\n" 20559 " other.other.other.other.other(\n" 20560 " x.begin(), x.end(),\n" 20561 " [something, rather](int, int, int, int, int, int, int) {\n" 20562 " //\n" 20563 " });\n" 20564 "}\n"); 20565 verifyFormat("SomeFunction([]() { // A cool function...\n" 20566 " return 43;\n" 20567 "});"); 20568 EXPECT_EQ("SomeFunction([]() {\n" 20569 "#define A a\n" 20570 " return 43;\n" 20571 "});", 20572 format("SomeFunction([](){\n" 20573 "#define A a\n" 20574 "return 43;\n" 20575 "});")); 20576 verifyFormat("void f() {\n" 20577 " SomeFunction([](decltype(x), A *a) {});\n" 20578 " SomeFunction([](typeof(x), A *a) {});\n" 20579 " SomeFunction([](_Atomic(x), A *a) {});\n" 20580 " SomeFunction([](__underlying_type(x), A *a) {});\n" 20581 "}"); 20582 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 20583 " [](const aaaaaaaaaa &a) { return a; });"); 20584 verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n" 20585 " SomeOtherFunctioooooooooooooooooooooooooon();\n" 20586 "});"); 20587 verifyFormat("Constructor()\n" 20588 " : Field([] { // comment\n" 20589 " int i;\n" 20590 " }) {}"); 20591 verifyFormat("auto my_lambda = [](const string &some_parameter) {\n" 20592 " return some_parameter.size();\n" 20593 "};"); 20594 verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n" 20595 " [](const string &s) { return s; };"); 20596 verifyFormat("int i = aaaaaa ? 1 //\n" 20597 " : [] {\n" 20598 " return 2; //\n" 20599 " }();"); 20600 verifyFormat("llvm::errs() << \"number of twos is \"\n" 20601 " << std::count_if(v.begin(), v.end(), [](int x) {\n" 20602 " return x == 2; // force break\n" 20603 " });"); 20604 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 20605 " [=](int iiiiiiiiiiii) {\n" 20606 " return aaaaaaaaaaaaaaaaaaaaaaa !=\n" 20607 " aaaaaaaaaaaaaaaaaaaaaaa;\n" 20608 " });", 20609 getLLVMStyleWithColumns(60)); 20610 20611 verifyFormat("SomeFunction({[&] {\n" 20612 " // comment\n" 20613 " },\n" 20614 " [&] {\n" 20615 " // comment\n" 20616 " }});"); 20617 verifyFormat("SomeFunction({[&] {\n" 20618 " // comment\n" 20619 "}});"); 20620 verifyFormat( 20621 "virtual aaaaaaaaaaaaaaaa(\n" 20622 " std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n" 20623 " aaaaa aaaaaaaaa);"); 20624 20625 // Lambdas with return types. 20626 verifyFormat("int c = []() -> int { return 2; }();\n"); 20627 verifyFormat("int c = []() -> int * { return 2; }();\n"); 20628 verifyFormat("int c = []() -> vector<int> { return {2}; }();\n"); 20629 verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());"); 20630 verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};"); 20631 verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};"); 20632 verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};"); 20633 verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};"); 20634 verifyFormat("[a, a]() -> a<1> {};"); 20635 verifyFormat("[]() -> foo<5 + 2> { return {}; };"); 20636 verifyFormat("[]() -> foo<5 - 2> { return {}; };"); 20637 verifyFormat("[]() -> foo<5 / 2> { return {}; };"); 20638 verifyFormat("[]() -> foo<5 * 2> { return {}; };"); 20639 verifyFormat("[]() -> foo<5 % 2> { return {}; };"); 20640 verifyFormat("[]() -> foo<5 << 2> { return {}; };"); 20641 verifyFormat("[]() -> foo<!5> { return {}; };"); 20642 verifyFormat("[]() -> foo<~5> { return {}; };"); 20643 verifyFormat("[]() -> foo<5 | 2> { return {}; };"); 20644 verifyFormat("[]() -> foo<5 || 2> { return {}; };"); 20645 verifyFormat("[]() -> foo<5 & 2> { return {}; };"); 20646 verifyFormat("[]() -> foo<5 && 2> { return {}; };"); 20647 verifyFormat("[]() -> foo<5 == 2> { return {}; };"); 20648 verifyFormat("[]() -> foo<5 != 2> { return {}; };"); 20649 verifyFormat("[]() -> foo<5 >= 2> { return {}; };"); 20650 verifyFormat("[]() -> foo<5 <= 2> { return {}; };"); 20651 verifyFormat("[]() -> foo<5 < 2> { return {}; };"); 20652 verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };"); 20653 verifyFormat("namespace bar {\n" 20654 "// broken:\n" 20655 "auto foo{[]() -> foo<5 + 2> { return {}; }};\n" 20656 "} // namespace bar"); 20657 verifyFormat("namespace bar {\n" 20658 "// broken:\n" 20659 "auto foo{[]() -> foo<5 - 2> { return {}; }};\n" 20660 "} // namespace bar"); 20661 verifyFormat("namespace bar {\n" 20662 "// broken:\n" 20663 "auto foo{[]() -> foo<5 / 2> { return {}; }};\n" 20664 "} // namespace bar"); 20665 verifyFormat("namespace bar {\n" 20666 "// broken:\n" 20667 "auto foo{[]() -> foo<5 * 2> { return {}; }};\n" 20668 "} // namespace bar"); 20669 verifyFormat("namespace bar {\n" 20670 "// broken:\n" 20671 "auto foo{[]() -> foo<5 % 2> { return {}; }};\n" 20672 "} // namespace bar"); 20673 verifyFormat("namespace bar {\n" 20674 "// broken:\n" 20675 "auto foo{[]() -> foo<5 << 2> { return {}; }};\n" 20676 "} // namespace bar"); 20677 verifyFormat("namespace bar {\n" 20678 "// broken:\n" 20679 "auto foo{[]() -> foo<!5> { return {}; }};\n" 20680 "} // namespace bar"); 20681 verifyFormat("namespace bar {\n" 20682 "// broken:\n" 20683 "auto foo{[]() -> foo<~5> { return {}; }};\n" 20684 "} // namespace bar"); 20685 verifyFormat("namespace bar {\n" 20686 "// broken:\n" 20687 "auto foo{[]() -> foo<5 | 2> { return {}; }};\n" 20688 "} // namespace bar"); 20689 verifyFormat("namespace bar {\n" 20690 "// broken:\n" 20691 "auto foo{[]() -> foo<5 || 2> { return {}; }};\n" 20692 "} // namespace bar"); 20693 verifyFormat("namespace bar {\n" 20694 "// broken:\n" 20695 "auto foo{[]() -> foo<5 & 2> { return {}; }};\n" 20696 "} // namespace bar"); 20697 verifyFormat("namespace bar {\n" 20698 "// broken:\n" 20699 "auto foo{[]() -> foo<5 && 2> { return {}; }};\n" 20700 "} // namespace bar"); 20701 verifyFormat("namespace bar {\n" 20702 "// broken:\n" 20703 "auto foo{[]() -> foo<5 == 2> { return {}; }};\n" 20704 "} // namespace bar"); 20705 verifyFormat("namespace bar {\n" 20706 "// broken:\n" 20707 "auto foo{[]() -> foo<5 != 2> { return {}; }};\n" 20708 "} // namespace bar"); 20709 verifyFormat("namespace bar {\n" 20710 "// broken:\n" 20711 "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n" 20712 "} // namespace bar"); 20713 verifyFormat("namespace bar {\n" 20714 "// broken:\n" 20715 "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n" 20716 "} // namespace bar"); 20717 verifyFormat("namespace bar {\n" 20718 "// broken:\n" 20719 "auto foo{[]() -> foo<5 < 2> { return {}; }};\n" 20720 "} // namespace bar"); 20721 verifyFormat("namespace bar {\n" 20722 "// broken:\n" 20723 "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n" 20724 "} // namespace bar"); 20725 verifyFormat("[]() -> a<1> {};"); 20726 verifyFormat("[]() -> a<1> { ; };"); 20727 verifyFormat("[]() -> a<1> { ; }();"); 20728 verifyFormat("[a, a]() -> a<true> {};"); 20729 verifyFormat("[]() -> a<true> {};"); 20730 verifyFormat("[]() -> a<true> { ; };"); 20731 verifyFormat("[]() -> a<true> { ; }();"); 20732 verifyFormat("[a, a]() -> a<false> {};"); 20733 verifyFormat("[]() -> a<false> {};"); 20734 verifyFormat("[]() -> a<false> { ; };"); 20735 verifyFormat("[]() -> a<false> { ; }();"); 20736 verifyFormat("auto foo{[]() -> foo<false> { ; }};"); 20737 verifyFormat("namespace bar {\n" 20738 "auto foo{[]() -> foo<false> { ; }};\n" 20739 "} // namespace bar"); 20740 verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n" 20741 " int j) -> int {\n" 20742 " return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n" 20743 "};"); 20744 verifyFormat( 20745 "aaaaaaaaaaaaaaaaaaaaaa(\n" 20746 " [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n" 20747 " return aaaaaaaaaaaaaaaaa;\n" 20748 " });", 20749 getLLVMStyleWithColumns(70)); 20750 verifyFormat("[]() //\n" 20751 " -> int {\n" 20752 " return 1; //\n" 20753 "};"); 20754 verifyFormat("[]() -> Void<T...> {};"); 20755 verifyFormat("[a, b]() -> Tuple<T...> { return {}; };"); 20756 verifyFormat("SomeFunction({[]() -> int[] { return {}; }});"); 20757 verifyFormat("SomeFunction({[]() -> int *[] { return {}; }});"); 20758 verifyFormat("SomeFunction({[]() -> int (*)[] { return {}; }});"); 20759 verifyFormat("SomeFunction({[]() -> ns::type<int (*)[]> { return {}; }});"); 20760 verifyFormat("return int{[x = x]() { return x; }()};"); 20761 20762 // Lambdas with explicit template argument lists. 20763 verifyFormat( 20764 "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n"); 20765 verifyFormat("auto L = []<class T>(T) {\n" 20766 " {\n" 20767 " f();\n" 20768 " g();\n" 20769 " }\n" 20770 "};\n"); 20771 verifyFormat("auto L = []<class... T>(T...) {\n" 20772 " {\n" 20773 " f();\n" 20774 " g();\n" 20775 " }\n" 20776 "};\n"); 20777 verifyFormat("auto L = []<typename... T>(T...) {\n" 20778 " {\n" 20779 " f();\n" 20780 " g();\n" 20781 " }\n" 20782 "};\n"); 20783 verifyFormat("auto L = []<template <typename...> class T>(T...) {\n" 20784 " {\n" 20785 " f();\n" 20786 " g();\n" 20787 " }\n" 20788 "};\n"); 20789 verifyFormat("auto L = []</*comment*/ class... T>(T...) {\n" 20790 " {\n" 20791 " f();\n" 20792 " g();\n" 20793 " }\n" 20794 "};\n"); 20795 20796 // Multiple lambdas in the same parentheses change indentation rules. These 20797 // lambdas are forced to start on new lines. 20798 verifyFormat("SomeFunction(\n" 20799 " []() {\n" 20800 " //\n" 20801 " },\n" 20802 " []() {\n" 20803 " //\n" 20804 " });"); 20805 20806 // A lambda passed as arg0 is always pushed to the next line. 20807 verifyFormat("SomeFunction(\n" 20808 " [this] {\n" 20809 " //\n" 20810 " },\n" 20811 " 1);\n"); 20812 20813 // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like 20814 // the arg0 case above. 20815 auto Style = getGoogleStyle(); 20816 Style.BinPackArguments = false; 20817 verifyFormat("SomeFunction(\n" 20818 " a,\n" 20819 " [this] {\n" 20820 " //\n" 20821 " },\n" 20822 " b);\n", 20823 Style); 20824 verifyFormat("SomeFunction(\n" 20825 " a,\n" 20826 " [this] {\n" 20827 " //\n" 20828 " },\n" 20829 " b);\n"); 20830 20831 // A lambda with a very long line forces arg0 to be pushed out irrespective of 20832 // the BinPackArguments value (as long as the code is wide enough). 20833 verifyFormat( 20834 "something->SomeFunction(\n" 20835 " a,\n" 20836 " [this] {\n" 20837 " " 20838 "D0000000000000000000000000000000000000000000000000000000000001();\n" 20839 " },\n" 20840 " b);\n"); 20841 20842 // A multi-line lambda is pulled up as long as the introducer fits on the 20843 // previous line and there are no further args. 20844 verifyFormat("function(1, [this, that] {\n" 20845 " //\n" 20846 "});\n"); 20847 verifyFormat("function([this, that] {\n" 20848 " //\n" 20849 "});\n"); 20850 // FIXME: this format is not ideal and we should consider forcing the first 20851 // arg onto its own line. 20852 verifyFormat("function(a, b, c, //\n" 20853 " d, [this, that] {\n" 20854 " //\n" 20855 " });\n"); 20856 20857 // Multiple lambdas are treated correctly even when there is a short arg0. 20858 verifyFormat("SomeFunction(\n" 20859 " 1,\n" 20860 " [this] {\n" 20861 " //\n" 20862 " },\n" 20863 " [this] {\n" 20864 " //\n" 20865 " },\n" 20866 " 1);\n"); 20867 20868 // More complex introducers. 20869 verifyFormat("return [i, args...] {};"); 20870 20871 // Not lambdas. 20872 verifyFormat("constexpr char hello[]{\"hello\"};"); 20873 verifyFormat("double &operator[](int i) { return 0; }\n" 20874 "int i;"); 20875 verifyFormat("std::unique_ptr<int[]> foo() {}"); 20876 verifyFormat("int i = a[a][a]->f();"); 20877 verifyFormat("int i = (*b)[a]->f();"); 20878 20879 // Other corner cases. 20880 verifyFormat("void f() {\n" 20881 " bar([]() {} // Did not respect SpacesBeforeTrailingComments\n" 20882 " );\n" 20883 "}"); 20884 20885 // Lambdas created through weird macros. 20886 verifyFormat("void f() {\n" 20887 " MACRO((const AA &a) { return 1; });\n" 20888 " MACRO((AA &a) { return 1; });\n" 20889 "}"); 20890 20891 verifyFormat("if (blah_blah(whatever, whatever, [] {\n" 20892 " doo_dah();\n" 20893 " doo_dah();\n" 20894 " })) {\n" 20895 "}"); 20896 verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n" 20897 " doo_dah();\n" 20898 " doo_dah();\n" 20899 " })) {\n" 20900 "}"); 20901 verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n" 20902 " doo_dah();\n" 20903 " doo_dah();\n" 20904 " })) {\n" 20905 "}"); 20906 verifyFormat("auto lambda = []() {\n" 20907 " int a = 2\n" 20908 "#if A\n" 20909 " + 2\n" 20910 "#endif\n" 20911 " ;\n" 20912 "};"); 20913 20914 // Lambdas with complex multiline introducers. 20915 verifyFormat( 20916 "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 20917 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n" 20918 " -> ::std::unordered_set<\n" 20919 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n" 20920 " //\n" 20921 " });"); 20922 20923 FormatStyle DoNotMerge = getLLVMStyle(); 20924 DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 20925 verifyFormat("auto c = []() {\n" 20926 " return b;\n" 20927 "};", 20928 "auto c = []() { return b; };", DoNotMerge); 20929 verifyFormat("auto c = []() {\n" 20930 "};", 20931 " auto c = []() {};", DoNotMerge); 20932 20933 FormatStyle MergeEmptyOnly = getLLVMStyle(); 20934 MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty; 20935 verifyFormat("auto c = []() {\n" 20936 " return b;\n" 20937 "};", 20938 "auto c = []() {\n" 20939 " return b;\n" 20940 " };", 20941 MergeEmptyOnly); 20942 verifyFormat("auto c = []() {};", 20943 "auto c = []() {\n" 20944 "};", 20945 MergeEmptyOnly); 20946 20947 FormatStyle MergeInline = getLLVMStyle(); 20948 MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline; 20949 verifyFormat("auto c = []() {\n" 20950 " return b;\n" 20951 "};", 20952 "auto c = []() { return b; };", MergeInline); 20953 verifyFormat("function([]() { return b; })", "function([]() { return b; })", 20954 MergeInline); 20955 verifyFormat("function([]() { return b; }, a)", 20956 "function([]() { return b; }, a)", MergeInline); 20957 verifyFormat("function(a, []() { return b; })", 20958 "function(a, []() { return b; })", MergeInline); 20959 20960 // Check option "BraceWrapping.BeforeLambdaBody" and different state of 20961 // AllowShortLambdasOnASingleLine 20962 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle(); 20963 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 20964 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 20965 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 20966 FormatStyle::ShortLambdaStyle::SLS_None; 20967 verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n" 20968 " []()\n" 20969 " {\n" 20970 " return 17;\n" 20971 " });", 20972 LLVMWithBeforeLambdaBody); 20973 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n" 20974 " []()\n" 20975 " {\n" 20976 " });", 20977 LLVMWithBeforeLambdaBody); 20978 verifyFormat("auto fct_SLS_None = []()\n" 20979 "{\n" 20980 " return 17;\n" 20981 "};", 20982 LLVMWithBeforeLambdaBody); 20983 verifyFormat("TwoNestedLambdas_SLS_None(\n" 20984 " []()\n" 20985 " {\n" 20986 " return Call(\n" 20987 " []()\n" 20988 " {\n" 20989 " return 17;\n" 20990 " });\n" 20991 " });", 20992 LLVMWithBeforeLambdaBody); 20993 verifyFormat("void Fct() {\n" 20994 " return {[]()\n" 20995 " {\n" 20996 " return 17;\n" 20997 " }};\n" 20998 "}", 20999 LLVMWithBeforeLambdaBody); 21000 21001 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21002 FormatStyle::ShortLambdaStyle::SLS_Empty; 21003 verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n" 21004 " []()\n" 21005 " {\n" 21006 " return 17;\n" 21007 " });", 21008 LLVMWithBeforeLambdaBody); 21009 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});", 21010 LLVMWithBeforeLambdaBody); 21011 verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL" 21012 "ongFunctionName_SLS_Empty(\n" 21013 " []() {});", 21014 LLVMWithBeforeLambdaBody); 21015 verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n" 21016 " []()\n" 21017 " {\n" 21018 " return 17;\n" 21019 " });", 21020 LLVMWithBeforeLambdaBody); 21021 verifyFormat("auto fct_SLS_Empty = []()\n" 21022 "{\n" 21023 " return 17;\n" 21024 "};", 21025 LLVMWithBeforeLambdaBody); 21026 verifyFormat("TwoNestedLambdas_SLS_Empty(\n" 21027 " []()\n" 21028 " {\n" 21029 " return Call([]() {});\n" 21030 " });", 21031 LLVMWithBeforeLambdaBody); 21032 verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n" 21033 " []()\n" 21034 " {\n" 21035 " return Call([]() {});\n" 21036 " });", 21037 LLVMWithBeforeLambdaBody); 21038 verifyFormat( 21039 "FctWithLongLineInLambda_SLS_Empty(\n" 21040 " []()\n" 21041 " {\n" 21042 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21043 " AndShouldNotBeConsiderAsInline,\n" 21044 " LambdaBodyMustBeBreak);\n" 21045 " });", 21046 LLVMWithBeforeLambdaBody); 21047 21048 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21049 FormatStyle::ShortLambdaStyle::SLS_Inline; 21050 verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });", 21051 LLVMWithBeforeLambdaBody); 21052 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});", 21053 LLVMWithBeforeLambdaBody); 21054 verifyFormat("auto fct_SLS_Inline = []()\n" 21055 "{\n" 21056 " return 17;\n" 21057 "};", 21058 LLVMWithBeforeLambdaBody); 21059 verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return " 21060 "17; }); });", 21061 LLVMWithBeforeLambdaBody); 21062 verifyFormat( 21063 "FctWithLongLineInLambda_SLS_Inline(\n" 21064 " []()\n" 21065 " {\n" 21066 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21067 " AndShouldNotBeConsiderAsInline,\n" 21068 " LambdaBodyMustBeBreak);\n" 21069 " });", 21070 LLVMWithBeforeLambdaBody); 21071 verifyFormat("FctWithMultipleParams_SLS_Inline(" 21072 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n" 21073 " []() { return 17; });", 21074 LLVMWithBeforeLambdaBody); 21075 verifyFormat( 21076 "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });", 21077 LLVMWithBeforeLambdaBody); 21078 21079 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21080 FormatStyle::ShortLambdaStyle::SLS_All; 21081 verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });", 21082 LLVMWithBeforeLambdaBody); 21083 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});", 21084 LLVMWithBeforeLambdaBody); 21085 verifyFormat("auto fct_SLS_All = []() { return 17; };", 21086 LLVMWithBeforeLambdaBody); 21087 verifyFormat("FctWithOneParam_SLS_All(\n" 21088 " []()\n" 21089 " {\n" 21090 " // A cool function...\n" 21091 " return 43;\n" 21092 " });", 21093 LLVMWithBeforeLambdaBody); 21094 verifyFormat("FctWithMultipleParams_SLS_All(" 21095 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n" 21096 " []() { return 17; });", 21097 LLVMWithBeforeLambdaBody); 21098 verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });", 21099 LLVMWithBeforeLambdaBody); 21100 verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });", 21101 LLVMWithBeforeLambdaBody); 21102 verifyFormat( 21103 "FctWithLongLineInLambda_SLS_All(\n" 21104 " []()\n" 21105 " {\n" 21106 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21107 " AndShouldNotBeConsiderAsInline,\n" 21108 " LambdaBodyMustBeBreak);\n" 21109 " });", 21110 LLVMWithBeforeLambdaBody); 21111 verifyFormat( 21112 "auto fct_SLS_All = []()\n" 21113 "{\n" 21114 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21115 " AndShouldNotBeConsiderAsInline,\n" 21116 " LambdaBodyMustBeBreak);\n" 21117 "};", 21118 LLVMWithBeforeLambdaBody); 21119 LLVMWithBeforeLambdaBody.BinPackParameters = false; 21120 verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);", 21121 LLVMWithBeforeLambdaBody); 21122 verifyFormat( 21123 "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n" 21124 " FirstParam,\n" 21125 " SecondParam,\n" 21126 " ThirdParam,\n" 21127 " FourthParam);", 21128 LLVMWithBeforeLambdaBody); 21129 verifyFormat("FctWithLongLineInLambda_SLS_All(\n" 21130 " []() { return " 21131 "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n" 21132 " FirstParam,\n" 21133 " SecondParam,\n" 21134 " ThirdParam,\n" 21135 " FourthParam);", 21136 LLVMWithBeforeLambdaBody); 21137 verifyFormat( 21138 "FctWithLongLineInLambda_SLS_All(FirstParam,\n" 21139 " SecondParam,\n" 21140 " ThirdParam,\n" 21141 " FourthParam,\n" 21142 " []() { return SomeValueNotSoLong; });", 21143 LLVMWithBeforeLambdaBody); 21144 verifyFormat("FctWithLongLineInLambda_SLS_All(\n" 21145 " []()\n" 21146 " {\n" 21147 " return " 21148 "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB" 21149 "eConsiderAsInline;\n" 21150 " });", 21151 LLVMWithBeforeLambdaBody); 21152 verifyFormat( 21153 "FctWithLongLineInLambda_SLS_All(\n" 21154 " []()\n" 21155 " {\n" 21156 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21157 " AndShouldNotBeConsiderAsInline,\n" 21158 " LambdaBodyMustBeBreak);\n" 21159 " });", 21160 LLVMWithBeforeLambdaBody); 21161 verifyFormat("FctWithTwoParams_SLS_All(\n" 21162 " []()\n" 21163 " {\n" 21164 " // A cool function...\n" 21165 " return 43;\n" 21166 " },\n" 21167 " 87);", 21168 LLVMWithBeforeLambdaBody); 21169 verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);", 21170 LLVMWithBeforeLambdaBody); 21171 verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });", 21172 LLVMWithBeforeLambdaBody); 21173 verifyFormat( 21174 "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });", 21175 LLVMWithBeforeLambdaBody); 21176 verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; " 21177 "}); }, x);", 21178 LLVMWithBeforeLambdaBody); 21179 verifyFormat("TwoNestedLambdas_SLS_All(\n" 21180 " []()\n" 21181 " {\n" 21182 " // A cool function...\n" 21183 " return Call([]() { return 17; });\n" 21184 " });", 21185 LLVMWithBeforeLambdaBody); 21186 verifyFormat("TwoNestedLambdas_SLS_All(\n" 21187 " []()\n" 21188 " {\n" 21189 " return Call(\n" 21190 " []()\n" 21191 " {\n" 21192 " // A cool function...\n" 21193 " return 17;\n" 21194 " });\n" 21195 " });", 21196 LLVMWithBeforeLambdaBody); 21197 21198 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21199 FormatStyle::ShortLambdaStyle::SLS_None; 21200 21201 verifyFormat("auto select = [this]() -> const Library::Object *\n" 21202 "{\n" 21203 " return MyAssignment::SelectFromList(this);\n" 21204 "};\n", 21205 LLVMWithBeforeLambdaBody); 21206 21207 verifyFormat("auto select = [this]() -> const Library::Object &\n" 21208 "{\n" 21209 " return MyAssignment::SelectFromList(this);\n" 21210 "};\n", 21211 LLVMWithBeforeLambdaBody); 21212 21213 verifyFormat("auto select = [this]() -> std::unique_ptr<Object>\n" 21214 "{\n" 21215 " return MyAssignment::SelectFromList(this);\n" 21216 "};\n", 21217 LLVMWithBeforeLambdaBody); 21218 21219 verifyFormat("namespace test {\n" 21220 "class Test {\n" 21221 "public:\n" 21222 " Test() = default;\n" 21223 "};\n" 21224 "} // namespace test", 21225 LLVMWithBeforeLambdaBody); 21226 21227 // Lambdas with different indentation styles. 21228 Style = getLLVMStyleWithColumns(100); 21229 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 21230 " return promise.then(\n" 21231 " [this, &someVariable, someObject = " 21232 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21233 " return someObject.startAsyncAction().then(\n" 21234 " [this, &someVariable](AsyncActionResult result) " 21235 "mutable { result.processMore(); });\n" 21236 " });\n" 21237 "}\n", 21238 format("SomeResult doSomething(SomeObject promise) {\n" 21239 " return promise.then([this, &someVariable, someObject = " 21240 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21241 " return someObject.startAsyncAction().then([this, " 21242 "&someVariable](AsyncActionResult result) mutable {\n" 21243 " result.processMore();\n" 21244 " });\n" 21245 " });\n" 21246 "}\n", 21247 Style)); 21248 Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope; 21249 verifyFormat("test() {\n" 21250 " ([]() -> {\n" 21251 " int b = 32;\n" 21252 " return 3;\n" 21253 " }).foo();\n" 21254 "}", 21255 Style); 21256 verifyFormat("test() {\n" 21257 " []() -> {\n" 21258 " int b = 32;\n" 21259 " return 3;\n" 21260 " }\n" 21261 "}", 21262 Style); 21263 verifyFormat("std::sort(v.begin(), v.end(),\n" 21264 " [](const auto &someLongArgumentName, const auto " 21265 "&someOtherLongArgumentName) {\n" 21266 " return someLongArgumentName.someMemberVariable < " 21267 "someOtherLongArgumentName.someMemberVariable;\n" 21268 "});", 21269 Style); 21270 verifyFormat("test() {\n" 21271 " (\n" 21272 " []() -> {\n" 21273 " int b = 32;\n" 21274 " return 3;\n" 21275 " },\n" 21276 " foo, bar)\n" 21277 " .foo();\n" 21278 "}", 21279 Style); 21280 verifyFormat("test() {\n" 21281 " ([]() -> {\n" 21282 " int b = 32;\n" 21283 " return 3;\n" 21284 " })\n" 21285 " .foo()\n" 21286 " .bar();\n" 21287 "}", 21288 Style); 21289 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 21290 " return promise.then(\n" 21291 " [this, &someVariable, someObject = " 21292 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21293 " return someObject.startAsyncAction().then(\n" 21294 " [this, &someVariable](AsyncActionResult result) mutable { " 21295 "result.processMore(); });\n" 21296 " });\n" 21297 "}\n", 21298 format("SomeResult doSomething(SomeObject promise) {\n" 21299 " return promise.then([this, &someVariable, someObject = " 21300 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21301 " return someObject.startAsyncAction().then([this, " 21302 "&someVariable](AsyncActionResult result) mutable {\n" 21303 " result.processMore();\n" 21304 " });\n" 21305 " });\n" 21306 "}\n", 21307 Style)); 21308 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 21309 " return promise.then([this, &someVariable] {\n" 21310 " return someObject.startAsyncAction().then(\n" 21311 " [this, &someVariable](AsyncActionResult result) mutable { " 21312 "result.processMore(); });\n" 21313 " });\n" 21314 "}\n", 21315 format("SomeResult doSomething(SomeObject promise) {\n" 21316 " return promise.then([this, &someVariable] {\n" 21317 " return someObject.startAsyncAction().then([this, " 21318 "&someVariable](AsyncActionResult result) mutable {\n" 21319 " result.processMore();\n" 21320 " });\n" 21321 " });\n" 21322 "}\n", 21323 Style)); 21324 Style = getGoogleStyle(); 21325 Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope; 21326 EXPECT_EQ("#define A \\\n" 21327 " [] { \\\n" 21328 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 21329 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n" 21330 " }", 21331 format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 21332 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }", 21333 Style)); 21334 // TODO: The current formatting has a minor issue that's not worth fixing 21335 // right now whereby the closing brace is indented relative to the signature 21336 // instead of being aligned. This only happens with macros. 21337 } 21338 21339 TEST_F(FormatTest, LambdaWithLineComments) { 21340 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle(); 21341 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 21342 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 21343 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21344 FormatStyle::ShortLambdaStyle::SLS_All; 21345 21346 verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody); 21347 verifyFormat("auto k = []() // comment\n" 21348 "{ return; }", 21349 LLVMWithBeforeLambdaBody); 21350 verifyFormat("auto k = []() /* comment */ { return; }", 21351 LLVMWithBeforeLambdaBody); 21352 verifyFormat("auto k = []() /* comment */ /* comment */ { return; }", 21353 LLVMWithBeforeLambdaBody); 21354 verifyFormat("auto k = []() // X\n" 21355 "{ return; }", 21356 LLVMWithBeforeLambdaBody); 21357 verifyFormat( 21358 "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" 21359 "{ return; }", 21360 LLVMWithBeforeLambdaBody); 21361 } 21362 21363 TEST_F(FormatTest, EmptyLinesInLambdas) { 21364 verifyFormat("auto lambda = []() {\n" 21365 " x(); //\n" 21366 "};", 21367 "auto lambda = []() {\n" 21368 "\n" 21369 " x(); //\n" 21370 "\n" 21371 "};"); 21372 } 21373 21374 TEST_F(FormatTest, FormatsBlocks) { 21375 FormatStyle ShortBlocks = getLLVMStyle(); 21376 ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 21377 verifyFormat("int (^Block)(int, int);", ShortBlocks); 21378 verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks); 21379 verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks); 21380 verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks); 21381 verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks); 21382 verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks); 21383 21384 verifyFormat("foo(^{ bar(); });", ShortBlocks); 21385 verifyFormat("foo(a, ^{ bar(); });", ShortBlocks); 21386 verifyFormat("{ void (^block)(Object *x); }", ShortBlocks); 21387 21388 verifyFormat("[operation setCompletionBlock:^{\n" 21389 " [self onOperationDone];\n" 21390 "}];"); 21391 verifyFormat("int i = {[operation setCompletionBlock:^{\n" 21392 " [self onOperationDone];\n" 21393 "}]};"); 21394 verifyFormat("[operation setCompletionBlock:^(int *i) {\n" 21395 " f();\n" 21396 "}];"); 21397 verifyFormat("int a = [operation block:^int(int *i) {\n" 21398 " return 1;\n" 21399 "}];"); 21400 verifyFormat("[myObject doSomethingWith:arg1\n" 21401 " aaa:^int(int *a) {\n" 21402 " return 1;\n" 21403 " }\n" 21404 " bbb:f(a * bbbbbbbb)];"); 21405 21406 verifyFormat("[operation setCompletionBlock:^{\n" 21407 " [self.delegate newDataAvailable];\n" 21408 "}];", 21409 getLLVMStyleWithColumns(60)); 21410 verifyFormat("dispatch_async(_fileIOQueue, ^{\n" 21411 " NSString *path = [self sessionFilePath];\n" 21412 " if (path) {\n" 21413 " // ...\n" 21414 " }\n" 21415 "});"); 21416 verifyFormat("[[SessionService sharedService]\n" 21417 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 21418 " if (window) {\n" 21419 " [self windowDidLoad:window];\n" 21420 " } else {\n" 21421 " [self errorLoadingWindow];\n" 21422 " }\n" 21423 " }];"); 21424 verifyFormat("void (^largeBlock)(void) = ^{\n" 21425 " // ...\n" 21426 "};\n", 21427 getLLVMStyleWithColumns(40)); 21428 verifyFormat("[[SessionService sharedService]\n" 21429 " loadWindowWithCompletionBlock: //\n" 21430 " ^(SessionWindow *window) {\n" 21431 " if (window) {\n" 21432 " [self windowDidLoad:window];\n" 21433 " } else {\n" 21434 " [self errorLoadingWindow];\n" 21435 " }\n" 21436 " }];", 21437 getLLVMStyleWithColumns(60)); 21438 verifyFormat("[myObject doSomethingWith:arg1\n" 21439 " firstBlock:^(Foo *a) {\n" 21440 " // ...\n" 21441 " int i;\n" 21442 " }\n" 21443 " secondBlock:^(Bar *b) {\n" 21444 " // ...\n" 21445 " int i;\n" 21446 " }\n" 21447 " thirdBlock:^Foo(Bar *b) {\n" 21448 " // ...\n" 21449 " int i;\n" 21450 " }];"); 21451 verifyFormat("[myObject doSomethingWith:arg1\n" 21452 " firstBlock:-1\n" 21453 " secondBlock:^(Bar *b) {\n" 21454 " // ...\n" 21455 " int i;\n" 21456 " }];"); 21457 21458 verifyFormat("f(^{\n" 21459 " @autoreleasepool {\n" 21460 " if (a) {\n" 21461 " g();\n" 21462 " }\n" 21463 " }\n" 21464 "});"); 21465 verifyFormat("Block b = ^int *(A *a, B *b) {}"); 21466 verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n" 21467 "};"); 21468 21469 FormatStyle FourIndent = getLLVMStyle(); 21470 FourIndent.ObjCBlockIndentWidth = 4; 21471 verifyFormat("[operation setCompletionBlock:^{\n" 21472 " [self onOperationDone];\n" 21473 "}];", 21474 FourIndent); 21475 } 21476 21477 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) { 21478 FormatStyle ZeroColumn = getLLVMStyleWithColumns(0); 21479 21480 verifyFormat("[[SessionService sharedService] " 21481 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 21482 " if (window) {\n" 21483 " [self windowDidLoad:window];\n" 21484 " } else {\n" 21485 " [self errorLoadingWindow];\n" 21486 " }\n" 21487 "}];", 21488 ZeroColumn); 21489 EXPECT_EQ("[[SessionService sharedService]\n" 21490 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 21491 " if (window) {\n" 21492 " [self windowDidLoad:window];\n" 21493 " } else {\n" 21494 " [self errorLoadingWindow];\n" 21495 " }\n" 21496 " }];", 21497 format("[[SessionService sharedService]\n" 21498 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 21499 " if (window) {\n" 21500 " [self windowDidLoad:window];\n" 21501 " } else {\n" 21502 " [self errorLoadingWindow];\n" 21503 " }\n" 21504 "}];", 21505 ZeroColumn)); 21506 verifyFormat("[myObject doSomethingWith:arg1\n" 21507 " firstBlock:^(Foo *a) {\n" 21508 " // ...\n" 21509 " int i;\n" 21510 " }\n" 21511 " secondBlock:^(Bar *b) {\n" 21512 " // ...\n" 21513 " int i;\n" 21514 " }\n" 21515 " thirdBlock:^Foo(Bar *b) {\n" 21516 " // ...\n" 21517 " int i;\n" 21518 " }];", 21519 ZeroColumn); 21520 verifyFormat("f(^{\n" 21521 " @autoreleasepool {\n" 21522 " if (a) {\n" 21523 " g();\n" 21524 " }\n" 21525 " }\n" 21526 "});", 21527 ZeroColumn); 21528 verifyFormat("void (^largeBlock)(void) = ^{\n" 21529 " // ...\n" 21530 "};", 21531 ZeroColumn); 21532 21533 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 21534 EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };", 21535 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn)); 21536 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 21537 EXPECT_EQ("void (^largeBlock)(void) = ^{\n" 21538 " int i;\n" 21539 "};", 21540 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn)); 21541 } 21542 21543 TEST_F(FormatTest, SupportsCRLF) { 21544 EXPECT_EQ("int a;\r\n" 21545 "int b;\r\n" 21546 "int c;\r\n", 21547 format("int a;\r\n" 21548 " int b;\r\n" 21549 " int c;\r\n", 21550 getLLVMStyle())); 21551 EXPECT_EQ("int a;\r\n" 21552 "int b;\r\n" 21553 "int c;\r\n", 21554 format("int a;\r\n" 21555 " int b;\n" 21556 " int c;\r\n", 21557 getLLVMStyle())); 21558 EXPECT_EQ("int a;\n" 21559 "int b;\n" 21560 "int c;\n", 21561 format("int a;\r\n" 21562 " int b;\n" 21563 " int c;\n", 21564 getLLVMStyle())); 21565 EXPECT_EQ("\"aaaaaaa \"\r\n" 21566 "\"bbbbbbb\";\r\n", 21567 format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10))); 21568 EXPECT_EQ("#define A \\\r\n" 21569 " b; \\\r\n" 21570 " c; \\\r\n" 21571 " d;\r\n", 21572 format("#define A \\\r\n" 21573 " b; \\\r\n" 21574 " c; d; \r\n", 21575 getGoogleStyle())); 21576 21577 EXPECT_EQ("/*\r\n" 21578 "multi line block comments\r\n" 21579 "should not introduce\r\n" 21580 "an extra carriage return\r\n" 21581 "*/\r\n", 21582 format("/*\r\n" 21583 "multi line block comments\r\n" 21584 "should not introduce\r\n" 21585 "an extra carriage return\r\n" 21586 "*/\r\n")); 21587 EXPECT_EQ("/*\r\n" 21588 "\r\n" 21589 "*/", 21590 format("/*\r\n" 21591 " \r\r\r\n" 21592 "*/")); 21593 21594 FormatStyle style = getLLVMStyle(); 21595 21596 style.DeriveLineEnding = true; 21597 style.UseCRLF = false; 21598 EXPECT_EQ("union FooBarBazQux {\n" 21599 " int foo;\n" 21600 " int bar;\n" 21601 " int baz;\n" 21602 "};", 21603 format("union FooBarBazQux {\r\n" 21604 " int foo;\n" 21605 " int bar;\r\n" 21606 " int baz;\n" 21607 "};", 21608 style)); 21609 style.UseCRLF = true; 21610 EXPECT_EQ("union FooBarBazQux {\r\n" 21611 " int foo;\r\n" 21612 " int bar;\r\n" 21613 " int baz;\r\n" 21614 "};", 21615 format("union FooBarBazQux {\r\n" 21616 " int foo;\n" 21617 " int bar;\r\n" 21618 " int baz;\n" 21619 "};", 21620 style)); 21621 21622 style.DeriveLineEnding = false; 21623 style.UseCRLF = false; 21624 EXPECT_EQ("union FooBarBazQux {\n" 21625 " int foo;\n" 21626 " int bar;\n" 21627 " int baz;\n" 21628 " int qux;\n" 21629 "};", 21630 format("union FooBarBazQux {\r\n" 21631 " int foo;\n" 21632 " int bar;\r\n" 21633 " int baz;\n" 21634 " int qux;\r\n" 21635 "};", 21636 style)); 21637 style.UseCRLF = true; 21638 EXPECT_EQ("union FooBarBazQux {\r\n" 21639 " int foo;\r\n" 21640 " int bar;\r\n" 21641 " int baz;\r\n" 21642 " int qux;\r\n" 21643 "};", 21644 format("union FooBarBazQux {\r\n" 21645 " int foo;\n" 21646 " int bar;\r\n" 21647 " int baz;\n" 21648 " int qux;\n" 21649 "};", 21650 style)); 21651 21652 style.DeriveLineEnding = true; 21653 style.UseCRLF = false; 21654 EXPECT_EQ("union FooBarBazQux {\r\n" 21655 " int foo;\r\n" 21656 " int bar;\r\n" 21657 " int baz;\r\n" 21658 " int qux;\r\n" 21659 "};", 21660 format("union FooBarBazQux {\r\n" 21661 " int foo;\n" 21662 " int bar;\r\n" 21663 " int baz;\n" 21664 " int qux;\r\n" 21665 "};", 21666 style)); 21667 style.UseCRLF = true; 21668 EXPECT_EQ("union FooBarBazQux {\n" 21669 " int foo;\n" 21670 " int bar;\n" 21671 " int baz;\n" 21672 " int qux;\n" 21673 "};", 21674 format("union FooBarBazQux {\r\n" 21675 " int foo;\n" 21676 " int bar;\r\n" 21677 " int baz;\n" 21678 " int qux;\n" 21679 "};", 21680 style)); 21681 } 21682 21683 TEST_F(FormatTest, MunchSemicolonAfterBlocks) { 21684 verifyFormat("MY_CLASS(C) {\n" 21685 " int i;\n" 21686 " int j;\n" 21687 "};"); 21688 } 21689 21690 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) { 21691 FormatStyle TwoIndent = getLLVMStyleWithColumns(15); 21692 TwoIndent.ContinuationIndentWidth = 2; 21693 21694 EXPECT_EQ("int i =\n" 21695 " longFunction(\n" 21696 " arg);", 21697 format("int i = longFunction(arg);", TwoIndent)); 21698 21699 FormatStyle SixIndent = getLLVMStyleWithColumns(20); 21700 SixIndent.ContinuationIndentWidth = 6; 21701 21702 EXPECT_EQ("int i =\n" 21703 " longFunction(\n" 21704 " arg);", 21705 format("int i = longFunction(arg);", SixIndent)); 21706 } 21707 21708 TEST_F(FormatTest, WrappedClosingParenthesisIndent) { 21709 FormatStyle Style = getLLVMStyle(); 21710 verifyFormat("int Foo::getter(\n" 21711 " //\n" 21712 ") const {\n" 21713 " return foo;\n" 21714 "}", 21715 Style); 21716 verifyFormat("void Foo::setter(\n" 21717 " //\n" 21718 ") {\n" 21719 " foo = 1;\n" 21720 "}", 21721 Style); 21722 } 21723 21724 TEST_F(FormatTest, SpacesInAngles) { 21725 FormatStyle Spaces = getLLVMStyle(); 21726 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 21727 21728 verifyFormat("vector< ::std::string > x1;", Spaces); 21729 verifyFormat("Foo< int, Bar > x2;", Spaces); 21730 verifyFormat("Foo< ::int, ::Bar > x3;", Spaces); 21731 21732 verifyFormat("static_cast< int >(arg);", Spaces); 21733 verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces); 21734 verifyFormat("f< int, float >();", Spaces); 21735 verifyFormat("template <> g() {}", Spaces); 21736 verifyFormat("template < std::vector< int > > f() {}", Spaces); 21737 verifyFormat("std::function< void(int, int) > fct;", Spaces); 21738 verifyFormat("void inFunction() { std::function< void(int, int) > fct; }", 21739 Spaces); 21740 21741 Spaces.Standard = FormatStyle::LS_Cpp03; 21742 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 21743 verifyFormat("A< A< int > >();", Spaces); 21744 21745 Spaces.SpacesInAngles = FormatStyle::SIAS_Never; 21746 verifyFormat("A<A<int> >();", Spaces); 21747 21748 Spaces.SpacesInAngles = FormatStyle::SIAS_Leave; 21749 verifyFormat("vector< ::std::string> x4;", "vector<::std::string> x4;", 21750 Spaces); 21751 verifyFormat("vector< ::std::string > x4;", "vector<::std::string > x4;", 21752 Spaces); 21753 21754 verifyFormat("A<A<int> >();", Spaces); 21755 verifyFormat("A<A<int> >();", "A<A<int>>();", Spaces); 21756 verifyFormat("A< A< int > >();", Spaces); 21757 21758 Spaces.Standard = FormatStyle::LS_Cpp11; 21759 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 21760 verifyFormat("A< A< int > >();", Spaces); 21761 21762 Spaces.SpacesInAngles = FormatStyle::SIAS_Never; 21763 verifyFormat("vector<::std::string> x4;", Spaces); 21764 verifyFormat("vector<int> x5;", Spaces); 21765 verifyFormat("Foo<int, Bar> x6;", Spaces); 21766 verifyFormat("Foo<::int, ::Bar> x7;", Spaces); 21767 21768 verifyFormat("A<A<int>>();", Spaces); 21769 21770 Spaces.SpacesInAngles = FormatStyle::SIAS_Leave; 21771 verifyFormat("vector<::std::string> x4;", Spaces); 21772 verifyFormat("vector< ::std::string > x4;", Spaces); 21773 verifyFormat("vector<int> x5;", Spaces); 21774 verifyFormat("vector< int > x5;", Spaces); 21775 verifyFormat("Foo<int, Bar> x6;", Spaces); 21776 verifyFormat("Foo< int, Bar > x6;", Spaces); 21777 verifyFormat("Foo<::int, ::Bar> x7;", Spaces); 21778 verifyFormat("Foo< ::int, ::Bar > x7;", Spaces); 21779 21780 verifyFormat("A<A<int>>();", Spaces); 21781 verifyFormat("A< A< int > >();", Spaces); 21782 verifyFormat("A<A<int > >();", Spaces); 21783 verifyFormat("A< A< int>>();", Spaces); 21784 21785 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 21786 verifyFormat("// clang-format off\n" 21787 "foo<<<1, 1>>>();\n" 21788 "// clang-format on\n", 21789 Spaces); 21790 verifyFormat("// clang-format off\n" 21791 "foo< < <1, 1> > >();\n" 21792 "// clang-format on\n", 21793 Spaces); 21794 } 21795 21796 TEST_F(FormatTest, SpaceAfterTemplateKeyword) { 21797 FormatStyle Style = getLLVMStyle(); 21798 Style.SpaceAfterTemplateKeyword = false; 21799 verifyFormat("template<int> void foo();", Style); 21800 } 21801 21802 TEST_F(FormatTest, TripleAngleBrackets) { 21803 verifyFormat("f<<<1, 1>>>();"); 21804 verifyFormat("f<<<1, 1, 1, s>>>();"); 21805 verifyFormat("f<<<a, b, c, d>>>();"); 21806 EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();")); 21807 verifyFormat("f<param><<<1, 1>>>();"); 21808 verifyFormat("f<1><<<1, 1>>>();"); 21809 EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();")); 21810 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 21811 "aaaaaaaaaaa<<<\n 1, 1>>>();"); 21812 verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n" 21813 " <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();"); 21814 } 21815 21816 TEST_F(FormatTest, MergeLessLessAtEnd) { 21817 verifyFormat("<<"); 21818 EXPECT_EQ("< < <", format("\\\n<<<")); 21819 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 21820 "aaallvm::outs() <<"); 21821 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 21822 "aaaallvm::outs()\n <<"); 21823 } 21824 21825 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) { 21826 std::string code = "#if A\n" 21827 "#if B\n" 21828 "a.\n" 21829 "#endif\n" 21830 " a = 1;\n" 21831 "#else\n" 21832 "#endif\n" 21833 "#if C\n" 21834 "#else\n" 21835 "#endif\n"; 21836 EXPECT_EQ(code, format(code)); 21837 } 21838 21839 TEST_F(FormatTest, HandleConflictMarkers) { 21840 // Git/SVN conflict markers. 21841 EXPECT_EQ("int a;\n" 21842 "void f() {\n" 21843 " callme(some(parameter1,\n" 21844 "<<<<<<< text by the vcs\n" 21845 " parameter2),\n" 21846 "||||||| text by the vcs\n" 21847 " parameter2),\n" 21848 " parameter3,\n" 21849 "======= text by the vcs\n" 21850 " parameter2, parameter3),\n" 21851 ">>>>>>> text by the vcs\n" 21852 " otherparameter);\n", 21853 format("int a;\n" 21854 "void f() {\n" 21855 " callme(some(parameter1,\n" 21856 "<<<<<<< text by the vcs\n" 21857 " parameter2),\n" 21858 "||||||| text by the vcs\n" 21859 " parameter2),\n" 21860 " parameter3,\n" 21861 "======= text by the vcs\n" 21862 " parameter2,\n" 21863 " parameter3),\n" 21864 ">>>>>>> text by the vcs\n" 21865 " otherparameter);\n")); 21866 21867 // Perforce markers. 21868 EXPECT_EQ("void f() {\n" 21869 " function(\n" 21870 ">>>> text by the vcs\n" 21871 " parameter,\n" 21872 "==== text by the vcs\n" 21873 " parameter,\n" 21874 "==== text by the vcs\n" 21875 " parameter,\n" 21876 "<<<< text by the vcs\n" 21877 " parameter);\n", 21878 format("void f() {\n" 21879 " function(\n" 21880 ">>>> text by the vcs\n" 21881 " parameter,\n" 21882 "==== text by the vcs\n" 21883 " parameter,\n" 21884 "==== text by the vcs\n" 21885 " parameter,\n" 21886 "<<<< text by the vcs\n" 21887 " parameter);\n")); 21888 21889 EXPECT_EQ("<<<<<<<\n" 21890 "|||||||\n" 21891 "=======\n" 21892 ">>>>>>>", 21893 format("<<<<<<<\n" 21894 "|||||||\n" 21895 "=======\n" 21896 ">>>>>>>")); 21897 21898 EXPECT_EQ("<<<<<<<\n" 21899 "|||||||\n" 21900 "int i;\n" 21901 "=======\n" 21902 ">>>>>>>", 21903 format("<<<<<<<\n" 21904 "|||||||\n" 21905 "int i;\n" 21906 "=======\n" 21907 ">>>>>>>")); 21908 21909 // FIXME: Handle parsing of macros around conflict markers correctly: 21910 EXPECT_EQ("#define Macro \\\n" 21911 "<<<<<<<\n" 21912 "Something \\\n" 21913 "|||||||\n" 21914 "Else \\\n" 21915 "=======\n" 21916 "Other \\\n" 21917 ">>>>>>>\n" 21918 " End int i;\n", 21919 format("#define Macro \\\n" 21920 "<<<<<<<\n" 21921 " Something \\\n" 21922 "|||||||\n" 21923 " Else \\\n" 21924 "=======\n" 21925 " Other \\\n" 21926 ">>>>>>>\n" 21927 " End\n" 21928 "int i;\n")); 21929 21930 verifyFormat(R"(==== 21931 #ifdef A 21932 a 21933 #else 21934 b 21935 #endif 21936 )"); 21937 } 21938 21939 TEST_F(FormatTest, DisableRegions) { 21940 EXPECT_EQ("int i;\n" 21941 "// clang-format off\n" 21942 " int j;\n" 21943 "// clang-format on\n" 21944 "int k;", 21945 format(" int i;\n" 21946 " // clang-format off\n" 21947 " int j;\n" 21948 " // clang-format on\n" 21949 " int k;")); 21950 EXPECT_EQ("int i;\n" 21951 "/* clang-format off */\n" 21952 " int j;\n" 21953 "/* clang-format on */\n" 21954 "int k;", 21955 format(" int i;\n" 21956 " /* clang-format off */\n" 21957 " int j;\n" 21958 " /* clang-format on */\n" 21959 " int k;")); 21960 21961 // Don't reflow comments within disabled regions. 21962 EXPECT_EQ("// clang-format off\n" 21963 "// long long long long long long line\n" 21964 "/* clang-format on */\n" 21965 "/* long long long\n" 21966 " * long long long\n" 21967 " * line */\n" 21968 "int i;\n" 21969 "/* clang-format off */\n" 21970 "/* long long long long long long line */\n", 21971 format("// clang-format off\n" 21972 "// long long long long long long line\n" 21973 "/* clang-format on */\n" 21974 "/* long long long long long long line */\n" 21975 "int i;\n" 21976 "/* clang-format off */\n" 21977 "/* long long long long long long line */\n", 21978 getLLVMStyleWithColumns(20))); 21979 } 21980 21981 TEST_F(FormatTest, DoNotCrashOnInvalidInput) { 21982 format("? ) ="); 21983 verifyNoCrash("#define a\\\n /**/}"); 21984 } 21985 21986 TEST_F(FormatTest, FormatsTableGenCode) { 21987 FormatStyle Style = getLLVMStyle(); 21988 Style.Language = FormatStyle::LK_TableGen; 21989 verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style); 21990 } 21991 21992 TEST_F(FormatTest, ArrayOfTemplates) { 21993 EXPECT_EQ("auto a = new unique_ptr<int>[10];", 21994 format("auto a = new unique_ptr<int > [ 10];")); 21995 21996 FormatStyle Spaces = getLLVMStyle(); 21997 Spaces.SpacesInSquareBrackets = true; 21998 EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];", 21999 format("auto a = new unique_ptr<int > [10];", Spaces)); 22000 } 22001 22002 TEST_F(FormatTest, ArrayAsTemplateType) { 22003 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;", 22004 format("auto a = unique_ptr < Foo < Bar>[ 10]> ;")); 22005 22006 FormatStyle Spaces = getLLVMStyle(); 22007 Spaces.SpacesInSquareBrackets = true; 22008 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;", 22009 format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces)); 22010 } 22011 22012 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); } 22013 22014 TEST(FormatStyle, GetStyleWithEmptyFileName) { 22015 llvm::vfs::InMemoryFileSystem FS; 22016 auto Style1 = getStyle("file", "", "Google", "", &FS); 22017 ASSERT_TRUE((bool)Style1); 22018 ASSERT_EQ(*Style1, getGoogleStyle()); 22019 } 22020 22021 TEST(FormatStyle, GetStyleOfFile) { 22022 llvm::vfs::InMemoryFileSystem FS; 22023 // Test 1: format file in the same directory. 22024 ASSERT_TRUE( 22025 FS.addFile("/a/.clang-format", 0, 22026 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM"))); 22027 ASSERT_TRUE( 22028 FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22029 auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS); 22030 ASSERT_TRUE((bool)Style1); 22031 ASSERT_EQ(*Style1, getLLVMStyle()); 22032 22033 // Test 2.1: fallback to default. 22034 ASSERT_TRUE( 22035 FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22036 auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS); 22037 ASSERT_TRUE((bool)Style2); 22038 ASSERT_EQ(*Style2, getMozillaStyle()); 22039 22040 // Test 2.2: no format on 'none' fallback style. 22041 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS); 22042 ASSERT_TRUE((bool)Style2); 22043 ASSERT_EQ(*Style2, getNoStyle()); 22044 22045 // Test 2.3: format if config is found with no based style while fallback is 22046 // 'none'. 22047 ASSERT_TRUE(FS.addFile("/b/.clang-format", 0, 22048 llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2"))); 22049 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS); 22050 ASSERT_TRUE((bool)Style2); 22051 ASSERT_EQ(*Style2, getLLVMStyle()); 22052 22053 // Test 2.4: format if yaml with no based style, while fallback is 'none'. 22054 Style2 = getStyle("{}", "a.h", "none", "", &FS); 22055 ASSERT_TRUE((bool)Style2); 22056 ASSERT_EQ(*Style2, getLLVMStyle()); 22057 22058 // Test 3: format file in parent directory. 22059 ASSERT_TRUE( 22060 FS.addFile("/c/.clang-format", 0, 22061 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 22062 ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0, 22063 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22064 auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS); 22065 ASSERT_TRUE((bool)Style3); 22066 ASSERT_EQ(*Style3, getGoogleStyle()); 22067 22068 // Test 4: error on invalid fallback style 22069 auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS); 22070 ASSERT_FALSE((bool)Style4); 22071 llvm::consumeError(Style4.takeError()); 22072 22073 // Test 5: error on invalid yaml on command line 22074 auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS); 22075 ASSERT_FALSE((bool)Style5); 22076 llvm::consumeError(Style5.takeError()); 22077 22078 // Test 6: error on invalid style 22079 auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS); 22080 ASSERT_FALSE((bool)Style6); 22081 llvm::consumeError(Style6.takeError()); 22082 22083 // Test 7: found config file, error on parsing it 22084 ASSERT_TRUE( 22085 FS.addFile("/d/.clang-format", 0, 22086 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n" 22087 "InvalidKey: InvalidValue"))); 22088 ASSERT_TRUE( 22089 FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22090 auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS); 22091 ASSERT_FALSE((bool)Style7a); 22092 llvm::consumeError(Style7a.takeError()); 22093 22094 auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true); 22095 ASSERT_TRUE((bool)Style7b); 22096 22097 // Test 8: inferred per-language defaults apply. 22098 auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS); 22099 ASSERT_TRUE((bool)StyleTd); 22100 ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen)); 22101 22102 // Test 9.1.1: overwriting a file style, when no parent file exists with no 22103 // fallback style. 22104 ASSERT_TRUE(FS.addFile( 22105 "/e/sub/.clang-format", 0, 22106 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n" 22107 "ColumnLimit: 20"))); 22108 ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0, 22109 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22110 auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS); 22111 ASSERT_TRUE(static_cast<bool>(Style9)); 22112 ASSERT_EQ(*Style9, [] { 22113 auto Style = getNoStyle(); 22114 Style.ColumnLimit = 20; 22115 return Style; 22116 }()); 22117 22118 // Test 9.1.2: propagate more than one level with no parent file. 22119 ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0, 22120 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22121 ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0, 22122 llvm::MemoryBuffer::getMemBuffer( 22123 "BasedOnStyle: InheritParentConfig\n" 22124 "WhitespaceSensitiveMacros: ['FOO', 'BAR']"))); 22125 std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"}; 22126 22127 ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros); 22128 Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS); 22129 ASSERT_TRUE(static_cast<bool>(Style9)); 22130 ASSERT_EQ(*Style9, [&NonDefaultWhiteSpaceMacros] { 22131 auto Style = getNoStyle(); 22132 Style.ColumnLimit = 20; 22133 Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros; 22134 return Style; 22135 }()); 22136 22137 // Test 9.2: with LLVM fallback style 22138 Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS); 22139 ASSERT_TRUE(static_cast<bool>(Style9)); 22140 ASSERT_EQ(*Style9, [] { 22141 auto Style = getLLVMStyle(); 22142 Style.ColumnLimit = 20; 22143 return Style; 22144 }()); 22145 22146 // Test 9.3: with a parent file 22147 ASSERT_TRUE( 22148 FS.addFile("/e/.clang-format", 0, 22149 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n" 22150 "UseTab: Always"))); 22151 Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS); 22152 ASSERT_TRUE(static_cast<bool>(Style9)); 22153 ASSERT_EQ(*Style9, [] { 22154 auto Style = getGoogleStyle(); 22155 Style.ColumnLimit = 20; 22156 Style.UseTab = FormatStyle::UT_Always; 22157 return Style; 22158 }()); 22159 22160 // Test 9.4: propagate more than one level with a parent file. 22161 const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] { 22162 auto Style = getGoogleStyle(); 22163 Style.ColumnLimit = 20; 22164 Style.UseTab = FormatStyle::UT_Always; 22165 Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros; 22166 return Style; 22167 }(); 22168 22169 ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros); 22170 Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS); 22171 ASSERT_TRUE(static_cast<bool>(Style9)); 22172 ASSERT_EQ(*Style9, SubSubStyle); 22173 22174 // Test 9.5: use InheritParentConfig as style name 22175 Style9 = 22176 getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS); 22177 ASSERT_TRUE(static_cast<bool>(Style9)); 22178 ASSERT_EQ(*Style9, SubSubStyle); 22179 22180 // Test 9.6: use command line style with inheritance 22181 Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp", 22182 "none", "", &FS); 22183 ASSERT_TRUE(static_cast<bool>(Style9)); 22184 ASSERT_EQ(*Style9, SubSubStyle); 22185 22186 // Test 9.7: use command line style with inheritance and own config 22187 Style9 = getStyle("{BasedOnStyle: InheritParentConfig, " 22188 "WhitespaceSensitiveMacros: ['FOO', 'BAR']}", 22189 "/e/sub/code.cpp", "none", "", &FS); 22190 ASSERT_TRUE(static_cast<bool>(Style9)); 22191 ASSERT_EQ(*Style9, SubSubStyle); 22192 22193 // Test 9.8: use inheritance from a file without BasedOnStyle 22194 ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0, 22195 llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123"))); 22196 ASSERT_TRUE( 22197 FS.addFile("/e/withoutbase/sub/.clang-format", 0, 22198 llvm::MemoryBuffer::getMemBuffer( 22199 "BasedOnStyle: InheritParentConfig\nIndentWidth: 7"))); 22200 // Make sure we do not use the fallback style 22201 Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS); 22202 ASSERT_TRUE(static_cast<bool>(Style9)); 22203 ASSERT_EQ(*Style9, [] { 22204 auto Style = getLLVMStyle(); 22205 Style.ColumnLimit = 123; 22206 return Style; 22207 }()); 22208 22209 Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS); 22210 ASSERT_TRUE(static_cast<bool>(Style9)); 22211 ASSERT_EQ(*Style9, [] { 22212 auto Style = getLLVMStyle(); 22213 Style.ColumnLimit = 123; 22214 Style.IndentWidth = 7; 22215 return Style; 22216 }()); 22217 22218 // Test 9.9: use inheritance from a specific config file. 22219 Style9 = getStyle("file:/e/sub/sub/.clang-format", "/e/sub/sub/code.cpp", 22220 "none", "", &FS); 22221 ASSERT_TRUE(static_cast<bool>(Style9)); 22222 ASSERT_EQ(*Style9, SubSubStyle); 22223 } 22224 22225 TEST(FormatStyle, GetStyleOfSpecificFile) { 22226 llvm::vfs::InMemoryFileSystem FS; 22227 // Specify absolute path to a format file in a parent directory. 22228 ASSERT_TRUE( 22229 FS.addFile("/e/.clang-format", 0, 22230 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM"))); 22231 ASSERT_TRUE( 22232 FS.addFile("/e/explicit.clang-format", 0, 22233 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 22234 ASSERT_TRUE(FS.addFile("/e/sub/sub/sub/test.cpp", 0, 22235 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22236 auto Style = getStyle("file:/e/explicit.clang-format", 22237 "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS); 22238 ASSERT_TRUE(static_cast<bool>(Style)); 22239 ASSERT_EQ(*Style, getGoogleStyle()); 22240 22241 // Specify relative path to a format file. 22242 ASSERT_TRUE( 22243 FS.addFile("../../e/explicit.clang-format", 0, 22244 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 22245 Style = getStyle("file:../../e/explicit.clang-format", 22246 "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS); 22247 ASSERT_TRUE(static_cast<bool>(Style)); 22248 ASSERT_EQ(*Style, getGoogleStyle()); 22249 22250 // Specify path to a format file that does not exist. 22251 Style = getStyle("file:/e/missing.clang-format", "/e/sub/sub/sub/test.cpp", 22252 "LLVM", "", &FS); 22253 ASSERT_FALSE(static_cast<bool>(Style)); 22254 llvm::consumeError(Style.takeError()); 22255 22256 // Specify path to a file on the filesystem. 22257 SmallString<128> FormatFilePath; 22258 std::error_code ECF = llvm::sys::fs::createTemporaryFile( 22259 "FormatFileTest", "tpl", FormatFilePath); 22260 EXPECT_FALSE((bool)ECF); 22261 llvm::raw_fd_ostream FormatFileTest(FormatFilePath, ECF); 22262 EXPECT_FALSE((bool)ECF); 22263 FormatFileTest << "BasedOnStyle: Google\n"; 22264 FormatFileTest.close(); 22265 22266 SmallString<128> TestFilePath; 22267 std::error_code ECT = 22268 llvm::sys::fs::createTemporaryFile("CodeFileTest", "cc", TestFilePath); 22269 EXPECT_FALSE((bool)ECT); 22270 llvm::raw_fd_ostream CodeFileTest(TestFilePath, ECT); 22271 CodeFileTest << "int i;\n"; 22272 CodeFileTest.close(); 22273 22274 std::string format_file_arg = std::string("file:") + FormatFilePath.c_str(); 22275 Style = getStyle(format_file_arg, TestFilePath, "LLVM", "", nullptr); 22276 22277 llvm::sys::fs::remove(FormatFilePath.c_str()); 22278 llvm::sys::fs::remove(TestFilePath.c_str()); 22279 ASSERT_TRUE(static_cast<bool>(Style)); 22280 ASSERT_EQ(*Style, getGoogleStyle()); 22281 } 22282 22283 TEST_F(ReplacementTest, FormatCodeAfterReplacements) { 22284 // Column limit is 20. 22285 std::string Code = "Type *a =\n" 22286 " new Type();\n" 22287 "g(iiiii, 0, jjjjj,\n" 22288 " 0, kkkkk, 0, mm);\n" 22289 "int bad = format ;"; 22290 std::string Expected = "auto a = new Type();\n" 22291 "g(iiiii, nullptr,\n" 22292 " jjjjj, nullptr,\n" 22293 " kkkkk, nullptr,\n" 22294 " mm);\n" 22295 "int bad = format ;"; 22296 FileID ID = Context.createInMemoryFile("format.cpp", Code); 22297 tooling::Replacements Replaces = toReplacements( 22298 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6, 22299 "auto "), 22300 tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1, 22301 "nullptr"), 22302 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1, 22303 "nullptr"), 22304 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1, 22305 "nullptr")}); 22306 22307 FormatStyle Style = getLLVMStyle(); 22308 Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility. 22309 auto FormattedReplaces = formatReplacements(Code, Replaces, Style); 22310 EXPECT_TRUE(static_cast<bool>(FormattedReplaces)) 22311 << llvm::toString(FormattedReplaces.takeError()) << "\n"; 22312 auto Result = applyAllReplacements(Code, *FormattedReplaces); 22313 EXPECT_TRUE(static_cast<bool>(Result)); 22314 EXPECT_EQ(Expected, *Result); 22315 } 22316 22317 TEST_F(ReplacementTest, SortIncludesAfterReplacement) { 22318 std::string Code = "#include \"a.h\"\n" 22319 "#include \"c.h\"\n" 22320 "\n" 22321 "int main() {\n" 22322 " return 0;\n" 22323 "}"; 22324 std::string Expected = "#include \"a.h\"\n" 22325 "#include \"b.h\"\n" 22326 "#include \"c.h\"\n" 22327 "\n" 22328 "int main() {\n" 22329 " return 0;\n" 22330 "}"; 22331 FileID ID = Context.createInMemoryFile("fix.cpp", Code); 22332 tooling::Replacements Replaces = toReplacements( 22333 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0, 22334 "#include \"b.h\"\n")}); 22335 22336 FormatStyle Style = getLLVMStyle(); 22337 Style.SortIncludes = FormatStyle::SI_CaseSensitive; 22338 auto FormattedReplaces = formatReplacements(Code, Replaces, Style); 22339 EXPECT_TRUE(static_cast<bool>(FormattedReplaces)) 22340 << llvm::toString(FormattedReplaces.takeError()) << "\n"; 22341 auto Result = applyAllReplacements(Code, *FormattedReplaces); 22342 EXPECT_TRUE(static_cast<bool>(Result)); 22343 EXPECT_EQ(Expected, *Result); 22344 } 22345 22346 TEST_F(FormatTest, FormatSortsUsingDeclarations) { 22347 EXPECT_EQ("using std::cin;\n" 22348 "using std::cout;", 22349 format("using std::cout;\n" 22350 "using std::cin;", 22351 getGoogleStyle())); 22352 } 22353 22354 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) { 22355 FormatStyle Style = getLLVMStyle(); 22356 Style.Standard = FormatStyle::LS_Cpp03; 22357 // cpp03 recognize this string as identifier u8 and literal character 'a' 22358 EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style)); 22359 } 22360 22361 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) { 22362 // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers 22363 // all modes, including C++11, C++14 and C++17 22364 EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';")); 22365 } 22366 22367 TEST_F(FormatTest, DoNotFormatLikelyXml) { 22368 EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle())); 22369 EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle())); 22370 } 22371 22372 TEST_F(FormatTest, StructuredBindings) { 22373 // Structured bindings is a C++17 feature. 22374 // all modes, including C++11, C++14 and C++17 22375 verifyFormat("auto [a, b] = f();"); 22376 EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();")); 22377 EXPECT_EQ("const auto [a, b] = f();", format("const auto[a, b] = f();")); 22378 EXPECT_EQ("auto const [a, b] = f();", format("auto const[a, b] = f();")); 22379 EXPECT_EQ("auto const volatile [a, b] = f();", 22380 format("auto const volatile[a, b] = f();")); 22381 EXPECT_EQ("auto [a, b, c] = f();", format("auto [ a , b,c ] = f();")); 22382 EXPECT_EQ("auto &[a, b, c] = f();", 22383 format("auto &[ a , b,c ] = f();")); 22384 EXPECT_EQ("auto &&[a, b, c] = f();", 22385 format("auto &&[ a , b,c ] = f();")); 22386 EXPECT_EQ("auto const &[a, b] = f();", format("auto const&[a, b] = f();")); 22387 EXPECT_EQ("auto const volatile &&[a, b] = f();", 22388 format("auto const volatile &&[a, b] = f();")); 22389 EXPECT_EQ("auto const &&[a, b] = f();", 22390 format("auto const && [a, b] = f();")); 22391 EXPECT_EQ("const auto &[a, b] = f();", 22392 format("const auto & [a, b] = f();")); 22393 EXPECT_EQ("const auto volatile &&[a, b] = f();", 22394 format("const auto volatile &&[a, b] = f();")); 22395 EXPECT_EQ("volatile const auto &&[a, b] = f();", 22396 format("volatile const auto &&[a, b] = f();")); 22397 EXPECT_EQ("const auto &&[a, b] = f();", 22398 format("const auto && [a, b] = f();")); 22399 22400 // Make sure we don't mistake structured bindings for lambdas. 22401 FormatStyle PointerMiddle = getLLVMStyle(); 22402 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle; 22403 verifyFormat("auto [a1, b]{A * i};", getGoogleStyle()); 22404 verifyFormat("auto [a2, b]{A * i};", getLLVMStyle()); 22405 verifyFormat("auto [a3, b]{A * i};", PointerMiddle); 22406 verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle()); 22407 verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle()); 22408 verifyFormat("auto const [a3, b]{A * i};", PointerMiddle); 22409 verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle()); 22410 verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle()); 22411 verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle); 22412 verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle()); 22413 verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle()); 22414 verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle); 22415 22416 EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}", 22417 format("for (const auto && [a, b] : some_range) {\n}")); 22418 EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}", 22419 format("for (const auto & [a, b] : some_range) {\n}")); 22420 EXPECT_EQ("for (const auto [a, b] : some_range) {\n}", 22421 format("for (const auto[a, b] : some_range) {\n}")); 22422 EXPECT_EQ("auto [x, y](expr);", format("auto[x,y] (expr);")); 22423 EXPECT_EQ("auto &[x, y](expr);", format("auto & [x,y] (expr);")); 22424 EXPECT_EQ("auto &&[x, y](expr);", format("auto && [x,y] (expr);")); 22425 EXPECT_EQ("auto const &[x, y](expr);", 22426 format("auto const & [x,y] (expr);")); 22427 EXPECT_EQ("auto const &&[x, y](expr);", 22428 format("auto const && [x,y] (expr);")); 22429 EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y] {expr};")); 22430 EXPECT_EQ("auto const &[x, y]{expr};", 22431 format("auto const & [x,y] {expr};")); 22432 EXPECT_EQ("auto const &&[x, y]{expr};", 22433 format("auto const && [x,y] {expr};")); 22434 22435 FormatStyle Spaces = getLLVMStyle(); 22436 Spaces.SpacesInSquareBrackets = true; 22437 verifyFormat("auto [ a, b ] = f();", Spaces); 22438 verifyFormat("auto &&[ a, b ] = f();", Spaces); 22439 verifyFormat("auto &[ a, b ] = f();", Spaces); 22440 verifyFormat("auto const &&[ a, b ] = f();", Spaces); 22441 verifyFormat("auto const &[ a, b ] = f();", Spaces); 22442 } 22443 22444 TEST_F(FormatTest, FileAndCode) { 22445 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", "")); 22446 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", "")); 22447 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", "")); 22448 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "")); 22449 EXPECT_EQ(FormatStyle::LK_ObjC, 22450 guessLanguage("foo.h", "@interface Foo\n@end\n")); 22451 EXPECT_EQ( 22452 FormatStyle::LK_ObjC, 22453 guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }")); 22454 EXPECT_EQ(FormatStyle::LK_ObjC, 22455 guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))")); 22456 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;")); 22457 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", "")); 22458 EXPECT_EQ(FormatStyle::LK_ObjC, 22459 guessLanguage("foo", "@interface Foo\n@end\n")); 22460 EXPECT_EQ(FormatStyle::LK_ObjC, 22461 guessLanguage("foo.h", "int DoStuff(CGRect rect);\n")); 22462 EXPECT_EQ( 22463 FormatStyle::LK_ObjC, 22464 guessLanguage("foo.h", 22465 "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n")); 22466 EXPECT_EQ( 22467 FormatStyle::LK_Cpp, 22468 guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;")); 22469 } 22470 22471 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) { 22472 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];")); 22473 EXPECT_EQ(FormatStyle::LK_ObjC, 22474 guessLanguage("foo.h", "array[[calculator getIndex]];")); 22475 EXPECT_EQ(FormatStyle::LK_Cpp, 22476 guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];")); 22477 EXPECT_EQ( 22478 FormatStyle::LK_Cpp, 22479 guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];")); 22480 EXPECT_EQ(FormatStyle::LK_ObjC, 22481 guessLanguage("foo.h", "[[noreturn foo] bar];")); 22482 EXPECT_EQ(FormatStyle::LK_Cpp, 22483 guessLanguage("foo.h", "[[clang::fallthrough]];")); 22484 EXPECT_EQ(FormatStyle::LK_ObjC, 22485 guessLanguage("foo.h", "[[clang:fallthrough] foo];")); 22486 EXPECT_EQ(FormatStyle::LK_Cpp, 22487 guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];")); 22488 EXPECT_EQ(FormatStyle::LK_Cpp, 22489 guessLanguage("foo.h", "[[using clang: fallthrough]];")); 22490 EXPECT_EQ(FormatStyle::LK_ObjC, 22491 guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];")); 22492 EXPECT_EQ(FormatStyle::LK_Cpp, 22493 guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];")); 22494 EXPECT_EQ( 22495 FormatStyle::LK_Cpp, 22496 guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)")); 22497 EXPECT_EQ( 22498 FormatStyle::LK_Cpp, 22499 guessLanguage("foo.h", 22500 "[[clang::callable_when(\"unconsumed\", \"unknown\")]]")); 22501 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]")); 22502 } 22503 22504 TEST_F(FormatTest, GuessLanguageWithCaret) { 22505 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);")); 22506 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);")); 22507 EXPECT_EQ(FormatStyle::LK_ObjC, 22508 guessLanguage("foo.h", "int(^)(char, float);")); 22509 EXPECT_EQ(FormatStyle::LK_ObjC, 22510 guessLanguage("foo.h", "int(^foo)(char, float);")); 22511 EXPECT_EQ(FormatStyle::LK_ObjC, 22512 guessLanguage("foo.h", "int(^foo[10])(char, float);")); 22513 EXPECT_EQ(FormatStyle::LK_ObjC, 22514 guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);")); 22515 EXPECT_EQ( 22516 FormatStyle::LK_ObjC, 22517 guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);")); 22518 } 22519 22520 TEST_F(FormatTest, GuessLanguageWithPragmas) { 22521 EXPECT_EQ(FormatStyle::LK_Cpp, 22522 guessLanguage("foo.h", "__pragma(warning(disable:))")); 22523 EXPECT_EQ(FormatStyle::LK_Cpp, 22524 guessLanguage("foo.h", "#pragma(warning(disable:))")); 22525 EXPECT_EQ(FormatStyle::LK_Cpp, 22526 guessLanguage("foo.h", "_Pragma(warning(disable:))")); 22527 } 22528 22529 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) { 22530 // ASM symbolic names are identifiers that must be surrounded by [] without 22531 // space in between: 22532 // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands 22533 22534 // Example from https://bugs.llvm.org/show_bug.cgi?id=45108. 22535 verifyFormat(R"(// 22536 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result)); 22537 )"); 22538 22539 // A list of several ASM symbolic names. 22540 verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)"); 22541 22542 // ASM symbolic names in inline ASM with inputs and outputs. 22543 verifyFormat(R"(// 22544 asm("cmoveq %1, %2, %[result]" 22545 : [result] "=r"(result) 22546 : "r"(test), "r"(new), "[result]"(old)); 22547 )"); 22548 22549 // ASM symbolic names in inline ASM with no outputs. 22550 verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)"); 22551 } 22552 22553 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) { 22554 EXPECT_EQ(FormatStyle::LK_Cpp, 22555 guessLanguage("foo.h", "void f() {\n" 22556 " asm (\"mov %[e], %[d]\"\n" 22557 " : [d] \"=rm\" (d)\n" 22558 " [e] \"rm\" (*e));\n" 22559 "}")); 22560 EXPECT_EQ(FormatStyle::LK_Cpp, 22561 guessLanguage("foo.h", "void f() {\n" 22562 " _asm (\"mov %[e], %[d]\"\n" 22563 " : [d] \"=rm\" (d)\n" 22564 " [e] \"rm\" (*e));\n" 22565 "}")); 22566 EXPECT_EQ(FormatStyle::LK_Cpp, 22567 guessLanguage("foo.h", "void f() {\n" 22568 " __asm (\"mov %[e], %[d]\"\n" 22569 " : [d] \"=rm\" (d)\n" 22570 " [e] \"rm\" (*e));\n" 22571 "}")); 22572 EXPECT_EQ(FormatStyle::LK_Cpp, 22573 guessLanguage("foo.h", "void f() {\n" 22574 " __asm__ (\"mov %[e], %[d]\"\n" 22575 " : [d] \"=rm\" (d)\n" 22576 " [e] \"rm\" (*e));\n" 22577 "}")); 22578 EXPECT_EQ(FormatStyle::LK_Cpp, 22579 guessLanguage("foo.h", "void f() {\n" 22580 " asm (\"mov %[e], %[d]\"\n" 22581 " : [d] \"=rm\" (d),\n" 22582 " [e] \"rm\" (*e));\n" 22583 "}")); 22584 EXPECT_EQ(FormatStyle::LK_Cpp, 22585 guessLanguage("foo.h", "void f() {\n" 22586 " asm volatile (\"mov %[e], %[d]\"\n" 22587 " : [d] \"=rm\" (d)\n" 22588 " [e] \"rm\" (*e));\n" 22589 "}")); 22590 } 22591 22592 TEST_F(FormatTest, GuessLanguageWithChildLines) { 22593 EXPECT_EQ(FormatStyle::LK_Cpp, 22594 guessLanguage("foo.h", "#define FOO ({ std::string s; })")); 22595 EXPECT_EQ(FormatStyle::LK_ObjC, 22596 guessLanguage("foo.h", "#define FOO ({ NSString *s; })")); 22597 EXPECT_EQ( 22598 FormatStyle::LK_Cpp, 22599 guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })")); 22600 EXPECT_EQ( 22601 FormatStyle::LK_ObjC, 22602 guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })")); 22603 } 22604 22605 TEST_F(FormatTest, TypenameMacros) { 22606 std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"}; 22607 22608 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353 22609 FormatStyle Google = getGoogleStyleWithColumns(0); 22610 Google.TypenameMacros = TypenameMacros; 22611 verifyFormat("struct foo {\n" 22612 " int bar;\n" 22613 " TAILQ_ENTRY(a) bleh;\n" 22614 "};", 22615 Google); 22616 22617 FormatStyle Macros = getLLVMStyle(); 22618 Macros.TypenameMacros = TypenameMacros; 22619 22620 verifyFormat("STACK_OF(int) a;", Macros); 22621 verifyFormat("STACK_OF(int) *a;", Macros); 22622 verifyFormat("STACK_OF(int const *) *a;", Macros); 22623 verifyFormat("STACK_OF(int *const) *a;", Macros); 22624 verifyFormat("STACK_OF(int, string) a;", Macros); 22625 verifyFormat("STACK_OF(LIST(int)) a;", Macros); 22626 verifyFormat("STACK_OF(LIST(int)) a, b;", Macros); 22627 verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros); 22628 verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros); 22629 verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros); 22630 verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros); 22631 22632 Macros.PointerAlignment = FormatStyle::PAS_Left; 22633 verifyFormat("STACK_OF(int)* a;", Macros); 22634 verifyFormat("STACK_OF(int*)* a;", Macros); 22635 verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros); 22636 verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros); 22637 verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros); 22638 } 22639 22640 TEST_F(FormatTest, AtomicQualifier) { 22641 // Check that we treate _Atomic as a type and not a function call 22642 FormatStyle Google = getGoogleStyleWithColumns(0); 22643 verifyFormat("struct foo {\n" 22644 " int a1;\n" 22645 " _Atomic(a) a2;\n" 22646 " _Atomic(_Atomic(int) *const) a3;\n" 22647 "};", 22648 Google); 22649 verifyFormat("_Atomic(uint64_t) a;"); 22650 verifyFormat("_Atomic(uint64_t) *a;"); 22651 verifyFormat("_Atomic(uint64_t const *) *a;"); 22652 verifyFormat("_Atomic(uint64_t *const) *a;"); 22653 verifyFormat("_Atomic(const uint64_t *) *a;"); 22654 verifyFormat("_Atomic(uint64_t) a;"); 22655 verifyFormat("_Atomic(_Atomic(uint64_t)) a;"); 22656 verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;"); 22657 verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}"); 22658 verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);"); 22659 22660 verifyFormat("_Atomic(uint64_t) *s(InitValue);"); 22661 verifyFormat("_Atomic(uint64_t) *s{InitValue};"); 22662 FormatStyle Style = getLLVMStyle(); 22663 Style.PointerAlignment = FormatStyle::PAS_Left; 22664 verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style); 22665 verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style); 22666 verifyFormat("_Atomic(int)* a;", Style); 22667 verifyFormat("_Atomic(int*)* a;", Style); 22668 verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style); 22669 22670 Style.SpacesInCStyleCastParentheses = true; 22671 Style.SpacesInParentheses = false; 22672 verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style); 22673 Style.SpacesInCStyleCastParentheses = false; 22674 Style.SpacesInParentheses = true; 22675 verifyFormat("x = (_Atomic( uint64_t ))*a;", Style); 22676 verifyFormat("x = (_Atomic( uint64_t ))&a;", Style); 22677 } 22678 22679 TEST_F(FormatTest, AmbersandInLamda) { 22680 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899 22681 FormatStyle AlignStyle = getLLVMStyle(); 22682 AlignStyle.PointerAlignment = FormatStyle::PAS_Left; 22683 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle); 22684 AlignStyle.PointerAlignment = FormatStyle::PAS_Right; 22685 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle); 22686 } 22687 22688 TEST_F(FormatTest, SpacesInConditionalStatement) { 22689 FormatStyle Spaces = getLLVMStyle(); 22690 Spaces.IfMacros.clear(); 22691 Spaces.IfMacros.push_back("MYIF"); 22692 Spaces.SpacesInConditionalStatement = true; 22693 verifyFormat("for ( int i = 0; i; i++ )\n continue;", Spaces); 22694 verifyFormat("if ( !a )\n return;", Spaces); 22695 verifyFormat("if ( a )\n return;", Spaces); 22696 verifyFormat("if constexpr ( a )\n return;", Spaces); 22697 verifyFormat("MYIF ( a )\n return;", Spaces); 22698 verifyFormat("MYIF ( a )\n return;\nelse MYIF ( b )\n return;", Spaces); 22699 verifyFormat("MYIF ( a )\n return;\nelse\n return;", Spaces); 22700 verifyFormat("switch ( a )\ncase 1:\n return;", Spaces); 22701 verifyFormat("while ( a )\n return;", Spaces); 22702 verifyFormat("while ( (a && b) )\n return;", Spaces); 22703 verifyFormat("do {\n} while ( 1 != 0 );", Spaces); 22704 verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces); 22705 // Check that space on the left of "::" is inserted as expected at beginning 22706 // of condition. 22707 verifyFormat("while ( ::func() )\n return;", Spaces); 22708 22709 // Check impact of ControlStatementsExceptControlMacros is honored. 22710 Spaces.SpaceBeforeParens = 22711 FormatStyle::SBPO_ControlStatementsExceptControlMacros; 22712 verifyFormat("MYIF( a )\n return;", Spaces); 22713 verifyFormat("MYIF( a )\n return;\nelse MYIF( b )\n return;", Spaces); 22714 verifyFormat("MYIF( a )\n return;\nelse\n return;", Spaces); 22715 } 22716 22717 TEST_F(FormatTest, AlternativeOperators) { 22718 // Test case for ensuring alternate operators are not 22719 // combined with their right most neighbour. 22720 verifyFormat("int a and b;"); 22721 verifyFormat("int a and_eq b;"); 22722 verifyFormat("int a bitand b;"); 22723 verifyFormat("int a bitor b;"); 22724 verifyFormat("int a compl b;"); 22725 verifyFormat("int a not b;"); 22726 verifyFormat("int a not_eq b;"); 22727 verifyFormat("int a or b;"); 22728 verifyFormat("int a xor b;"); 22729 verifyFormat("int a xor_eq b;"); 22730 verifyFormat("return this not_eq bitand other;"); 22731 verifyFormat("bool operator not_eq(const X bitand other)"); 22732 22733 verifyFormat("int a and 5;"); 22734 verifyFormat("int a and_eq 5;"); 22735 verifyFormat("int a bitand 5;"); 22736 verifyFormat("int a bitor 5;"); 22737 verifyFormat("int a compl 5;"); 22738 verifyFormat("int a not 5;"); 22739 verifyFormat("int a not_eq 5;"); 22740 verifyFormat("int a or 5;"); 22741 verifyFormat("int a xor 5;"); 22742 verifyFormat("int a xor_eq 5;"); 22743 22744 verifyFormat("int a compl(5);"); 22745 verifyFormat("int a not(5);"); 22746 22747 /* FIXME handle alternate tokens 22748 * https://en.cppreference.com/w/cpp/language/operator_alternative 22749 // alternative tokens 22750 verifyFormat("compl foo();"); // ~foo(); 22751 verifyFormat("foo() <%%>;"); // foo(); 22752 verifyFormat("void foo() <%%>;"); // void foo(){} 22753 verifyFormat("int a <:1:>;"); // int a[1];[ 22754 verifyFormat("%:define ABC abc"); // #define ABC abc 22755 verifyFormat("%:%:"); // ## 22756 */ 22757 } 22758 22759 TEST_F(FormatTest, STLWhileNotDefineChed) { 22760 verifyFormat("#if defined(while)\n" 22761 "#define while EMIT WARNING C4005\n" 22762 "#endif // while"); 22763 } 22764 22765 TEST_F(FormatTest, OperatorSpacing) { 22766 FormatStyle Style = getLLVMStyle(); 22767 Style.PointerAlignment = FormatStyle::PAS_Right; 22768 verifyFormat("Foo::operator*();", Style); 22769 verifyFormat("Foo::operator void *();", Style); 22770 verifyFormat("Foo::operator void **();", Style); 22771 verifyFormat("Foo::operator void *&();", Style); 22772 verifyFormat("Foo::operator void *&&();", Style); 22773 verifyFormat("Foo::operator void const *();", Style); 22774 verifyFormat("Foo::operator void const **();", Style); 22775 verifyFormat("Foo::operator void const *&();", Style); 22776 verifyFormat("Foo::operator void const *&&();", Style); 22777 verifyFormat("Foo::operator()(void *);", Style); 22778 verifyFormat("Foo::operator*(void *);", Style); 22779 verifyFormat("Foo::operator*();", Style); 22780 verifyFormat("Foo::operator**();", Style); 22781 verifyFormat("Foo::operator&();", Style); 22782 verifyFormat("Foo::operator<int> *();", Style); 22783 verifyFormat("Foo::operator<Foo> *();", Style); 22784 verifyFormat("Foo::operator<int> **();", Style); 22785 verifyFormat("Foo::operator<Foo> **();", Style); 22786 verifyFormat("Foo::operator<int> &();", Style); 22787 verifyFormat("Foo::operator<Foo> &();", Style); 22788 verifyFormat("Foo::operator<int> &&();", Style); 22789 verifyFormat("Foo::operator<Foo> &&();", Style); 22790 verifyFormat("Foo::operator<int> *&();", Style); 22791 verifyFormat("Foo::operator<Foo> *&();", Style); 22792 verifyFormat("Foo::operator<int> *&&();", Style); 22793 verifyFormat("Foo::operator<Foo> *&&();", Style); 22794 verifyFormat("operator*(int (*)(), class Foo);", Style); 22795 22796 verifyFormat("Foo::operator&();", Style); 22797 verifyFormat("Foo::operator void &();", Style); 22798 verifyFormat("Foo::operator void const &();", Style); 22799 verifyFormat("Foo::operator()(void &);", Style); 22800 verifyFormat("Foo::operator&(void &);", Style); 22801 verifyFormat("Foo::operator&();", Style); 22802 verifyFormat("operator&(int (&)(), class Foo);", Style); 22803 verifyFormat("operator&&(int (&)(), class Foo);", Style); 22804 22805 verifyFormat("Foo::operator&&();", Style); 22806 verifyFormat("Foo::operator**();", Style); 22807 verifyFormat("Foo::operator void &&();", Style); 22808 verifyFormat("Foo::operator void const &&();", Style); 22809 verifyFormat("Foo::operator()(void &&);", Style); 22810 verifyFormat("Foo::operator&&(void &&);", Style); 22811 verifyFormat("Foo::operator&&();", Style); 22812 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 22813 verifyFormat("operator const nsTArrayRight<E> &()", Style); 22814 verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()", 22815 Style); 22816 verifyFormat("operator void **()", Style); 22817 verifyFormat("operator const FooRight<Object> &()", Style); 22818 verifyFormat("operator const FooRight<Object> *()", Style); 22819 verifyFormat("operator const FooRight<Object> **()", Style); 22820 verifyFormat("operator const FooRight<Object> *&()", Style); 22821 verifyFormat("operator const FooRight<Object> *&&()", Style); 22822 22823 Style.PointerAlignment = FormatStyle::PAS_Left; 22824 verifyFormat("Foo::operator*();", Style); 22825 verifyFormat("Foo::operator**();", Style); 22826 verifyFormat("Foo::operator void*();", Style); 22827 verifyFormat("Foo::operator void**();", Style); 22828 verifyFormat("Foo::operator void*&();", Style); 22829 verifyFormat("Foo::operator void*&&();", Style); 22830 verifyFormat("Foo::operator void const*();", Style); 22831 verifyFormat("Foo::operator void const**();", Style); 22832 verifyFormat("Foo::operator void const*&();", Style); 22833 verifyFormat("Foo::operator void const*&&();", Style); 22834 verifyFormat("Foo::operator/*comment*/ void*();", Style); 22835 verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style); 22836 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style); 22837 verifyFormat("Foo::operator()(void*);", Style); 22838 verifyFormat("Foo::operator*(void*);", Style); 22839 verifyFormat("Foo::operator*();", Style); 22840 verifyFormat("Foo::operator<int>*();", Style); 22841 verifyFormat("Foo::operator<Foo>*();", Style); 22842 verifyFormat("Foo::operator<int>**();", Style); 22843 verifyFormat("Foo::operator<Foo>**();", Style); 22844 verifyFormat("Foo::operator<Foo>*&();", Style); 22845 verifyFormat("Foo::operator<int>&();", Style); 22846 verifyFormat("Foo::operator<Foo>&();", Style); 22847 verifyFormat("Foo::operator<int>&&();", Style); 22848 verifyFormat("Foo::operator<Foo>&&();", Style); 22849 verifyFormat("Foo::operator<int>*&();", Style); 22850 verifyFormat("Foo::operator<Foo>*&();", Style); 22851 verifyFormat("operator*(int (*)(), class Foo);", Style); 22852 22853 verifyFormat("Foo::operator&();", Style); 22854 verifyFormat("Foo::operator void&();", Style); 22855 verifyFormat("Foo::operator void const&();", Style); 22856 verifyFormat("Foo::operator/*comment*/ void&();", Style); 22857 verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style); 22858 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style); 22859 verifyFormat("Foo::operator()(void&);", Style); 22860 verifyFormat("Foo::operator&(void&);", Style); 22861 verifyFormat("Foo::operator&();", Style); 22862 verifyFormat("operator&(int (&)(), class Foo);", Style); 22863 verifyFormat("operator&(int (&&)(), class Foo);", Style); 22864 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 22865 22866 verifyFormat("Foo::operator&&();", Style); 22867 verifyFormat("Foo::operator void&&();", Style); 22868 verifyFormat("Foo::operator void const&&();", Style); 22869 verifyFormat("Foo::operator/*comment*/ void&&();", Style); 22870 verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style); 22871 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style); 22872 verifyFormat("Foo::operator()(void&&);", Style); 22873 verifyFormat("Foo::operator&&(void&&);", Style); 22874 verifyFormat("Foo::operator&&();", Style); 22875 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 22876 verifyFormat("operator const nsTArrayLeft<E>&()", Style); 22877 verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()", 22878 Style); 22879 verifyFormat("operator void**()", Style); 22880 verifyFormat("operator const FooLeft<Object>&()", Style); 22881 verifyFormat("operator const FooLeft<Object>*()", Style); 22882 verifyFormat("operator const FooLeft<Object>**()", Style); 22883 verifyFormat("operator const FooLeft<Object>*&()", Style); 22884 verifyFormat("operator const FooLeft<Object>*&&()", Style); 22885 22886 // PR45107 22887 verifyFormat("operator Vector<String>&();", Style); 22888 verifyFormat("operator const Vector<String>&();", Style); 22889 verifyFormat("operator foo::Bar*();", Style); 22890 verifyFormat("operator const Foo<X>::Bar<Y>*();", Style); 22891 verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();", 22892 Style); 22893 22894 Style.PointerAlignment = FormatStyle::PAS_Middle; 22895 verifyFormat("Foo::operator*();", Style); 22896 verifyFormat("Foo::operator void *();", Style); 22897 verifyFormat("Foo::operator()(void *);", Style); 22898 verifyFormat("Foo::operator*(void *);", Style); 22899 verifyFormat("Foo::operator*();", Style); 22900 verifyFormat("operator*(int (*)(), class Foo);", Style); 22901 22902 verifyFormat("Foo::operator&();", Style); 22903 verifyFormat("Foo::operator void &();", Style); 22904 verifyFormat("Foo::operator void const &();", Style); 22905 verifyFormat("Foo::operator()(void &);", Style); 22906 verifyFormat("Foo::operator&(void &);", Style); 22907 verifyFormat("Foo::operator&();", Style); 22908 verifyFormat("operator&(int (&)(), class Foo);", Style); 22909 22910 verifyFormat("Foo::operator&&();", Style); 22911 verifyFormat("Foo::operator void &&();", Style); 22912 verifyFormat("Foo::operator void const &&();", Style); 22913 verifyFormat("Foo::operator()(void &&);", Style); 22914 verifyFormat("Foo::operator&&(void &&);", Style); 22915 verifyFormat("Foo::operator&&();", Style); 22916 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 22917 } 22918 22919 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) { 22920 FormatStyle Style = getLLVMStyle(); 22921 // PR46157 22922 verifyFormat("foo(operator+, -42);", Style); 22923 verifyFormat("foo(operator++, -42);", Style); 22924 verifyFormat("foo(operator--, -42);", Style); 22925 verifyFormat("foo(-42, operator--);", Style); 22926 verifyFormat("foo(-42, operator, );", Style); 22927 verifyFormat("foo(operator, , -42);", Style); 22928 } 22929 22930 TEST_F(FormatTest, WhitespaceSensitiveMacros) { 22931 FormatStyle Style = getLLVMStyle(); 22932 Style.WhitespaceSensitiveMacros.push_back("FOO"); 22933 22934 // Don't use the helpers here, since 'mess up' will change the whitespace 22935 // and these are all whitespace sensitive by definition 22936 EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);", 22937 format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style)); 22938 EXPECT_EQ( 22939 "FOO(String-ized&Messy+But\\(: :Still)=Intentional);", 22940 format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style)); 22941 EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);", 22942 format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style)); 22943 EXPECT_EQ("FOO(String-ized&Messy+But,: :\n" 22944 " Still=Intentional);", 22945 format("FOO(String-ized&Messy+But,: :\n" 22946 " Still=Intentional);", 22947 Style)); 22948 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 22949 EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n" 22950 " Still=Intentional);", 22951 format("FOO(String-ized=&Messy+But,: :\n" 22952 " Still=Intentional);", 22953 Style)); 22954 22955 Style.ColumnLimit = 21; 22956 EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);", 22957 format("FOO(String-ized&Messy+But: :Still=Intentional);", Style)); 22958 } 22959 22960 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) { 22961 // These tests are not in NamespaceFixer because that doesn't 22962 // test its interaction with line wrapping 22963 FormatStyle Style = getLLVMStyleWithColumns(80); 22964 verifyFormat("namespace {\n" 22965 "int i;\n" 22966 "int j;\n" 22967 "} // namespace", 22968 Style); 22969 22970 verifyFormat("namespace AAA {\n" 22971 "int i;\n" 22972 "int j;\n" 22973 "} // namespace AAA", 22974 Style); 22975 22976 EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n" 22977 "int i;\n" 22978 "int j;\n" 22979 "} // namespace Averyveryveryverylongnamespace", 22980 format("namespace Averyveryveryverylongnamespace {\n" 22981 "int i;\n" 22982 "int j;\n" 22983 "}", 22984 Style)); 22985 22986 EXPECT_EQ( 22987 "namespace " 22988 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n" 22989 " went::mad::now {\n" 22990 "int i;\n" 22991 "int j;\n" 22992 "} // namespace\n" 22993 " // " 22994 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::" 22995 "went::mad::now", 22996 format("namespace " 22997 "would::it::save::you::a::lot::of::time::if_::i::" 22998 "just::gave::up::and_::went::mad::now {\n" 22999 "int i;\n" 23000 "int j;\n" 23001 "}", 23002 Style)); 23003 23004 // This used to duplicate the comment again and again on subsequent runs 23005 EXPECT_EQ( 23006 "namespace " 23007 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n" 23008 " went::mad::now {\n" 23009 "int i;\n" 23010 "int j;\n" 23011 "} // namespace\n" 23012 " // " 23013 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::" 23014 "went::mad::now", 23015 format("namespace " 23016 "would::it::save::you::a::lot::of::time::if_::i::" 23017 "just::gave::up::and_::went::mad::now {\n" 23018 "int i;\n" 23019 "int j;\n" 23020 "} // namespace\n" 23021 " // " 23022 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::" 23023 "and_::went::mad::now", 23024 Style)); 23025 } 23026 23027 TEST_F(FormatTest, LikelyUnlikely) { 23028 FormatStyle Style = getLLVMStyle(); 23029 23030 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23031 " return 29;\n" 23032 "}", 23033 Style); 23034 23035 verifyFormat("if (argc > 5) [[likely]] {\n" 23036 " return 29;\n" 23037 "}", 23038 Style); 23039 23040 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23041 " return 29;\n" 23042 "} else [[likely]] {\n" 23043 " return 42;\n" 23044 "}\n", 23045 Style); 23046 23047 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23048 " return 29;\n" 23049 "} else if (argc > 10) [[likely]] {\n" 23050 " return 99;\n" 23051 "} else {\n" 23052 " return 42;\n" 23053 "}\n", 23054 Style); 23055 23056 verifyFormat("if (argc > 5) [[gnu::unused]] {\n" 23057 " return 29;\n" 23058 "}", 23059 Style); 23060 23061 verifyFormat("if (argc > 5) [[unlikely]]\n" 23062 " return 29;\n", 23063 Style); 23064 verifyFormat("if (argc > 5) [[likely]]\n" 23065 " return 29;\n", 23066 Style); 23067 23068 Style.AttributeMacros.push_back("UNLIKELY"); 23069 Style.AttributeMacros.push_back("LIKELY"); 23070 verifyFormat("if (argc > 5) UNLIKELY\n" 23071 " return 29;\n", 23072 Style); 23073 23074 verifyFormat("if (argc > 5) UNLIKELY {\n" 23075 " return 29;\n" 23076 "}", 23077 Style); 23078 verifyFormat("if (argc > 5) UNLIKELY {\n" 23079 " return 29;\n" 23080 "} else [[likely]] {\n" 23081 " return 42;\n" 23082 "}\n", 23083 Style); 23084 verifyFormat("if (argc > 5) UNLIKELY {\n" 23085 " return 29;\n" 23086 "} else LIKELY {\n" 23087 " return 42;\n" 23088 "}\n", 23089 Style); 23090 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23091 " return 29;\n" 23092 "} else LIKELY {\n" 23093 " return 42;\n" 23094 "}\n", 23095 Style); 23096 } 23097 23098 TEST_F(FormatTest, PenaltyIndentedWhitespace) { 23099 verifyFormat("Constructor()\n" 23100 " : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 23101 " aaaa(aaaaaaaaaaaaaaaaaa, " 23102 "aaaaaaaaaaaaaaaaaat))"); 23103 verifyFormat("Constructor()\n" 23104 " : aaaaaaaaaaaaa(aaaaaa), " 23105 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)"); 23106 23107 FormatStyle StyleWithWhitespacePenalty = getLLVMStyle(); 23108 StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5; 23109 verifyFormat("Constructor()\n" 23110 " : aaaaaa(aaaaaa),\n" 23111 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 23112 " aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))", 23113 StyleWithWhitespacePenalty); 23114 verifyFormat("Constructor()\n" 23115 " : aaaaaaaaaaaaa(aaaaaa), " 23116 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)", 23117 StyleWithWhitespacePenalty); 23118 } 23119 23120 TEST_F(FormatTest, LLVMDefaultStyle) { 23121 FormatStyle Style = getLLVMStyle(); 23122 verifyFormat("extern \"C\" {\n" 23123 "int foo();\n" 23124 "}", 23125 Style); 23126 } 23127 TEST_F(FormatTest, GNUDefaultStyle) { 23128 FormatStyle Style = getGNUStyle(); 23129 verifyFormat("extern \"C\"\n" 23130 "{\n" 23131 " int foo ();\n" 23132 "}", 23133 Style); 23134 } 23135 TEST_F(FormatTest, MozillaDefaultStyle) { 23136 FormatStyle Style = getMozillaStyle(); 23137 verifyFormat("extern \"C\"\n" 23138 "{\n" 23139 " int foo();\n" 23140 "}", 23141 Style); 23142 } 23143 TEST_F(FormatTest, GoogleDefaultStyle) { 23144 FormatStyle Style = getGoogleStyle(); 23145 verifyFormat("extern \"C\" {\n" 23146 "int foo();\n" 23147 "}", 23148 Style); 23149 } 23150 TEST_F(FormatTest, ChromiumDefaultStyle) { 23151 FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp); 23152 verifyFormat("extern \"C\" {\n" 23153 "int foo();\n" 23154 "}", 23155 Style); 23156 } 23157 TEST_F(FormatTest, MicrosoftDefaultStyle) { 23158 FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp); 23159 verifyFormat("extern \"C\"\n" 23160 "{\n" 23161 " int foo();\n" 23162 "}", 23163 Style); 23164 } 23165 TEST_F(FormatTest, WebKitDefaultStyle) { 23166 FormatStyle Style = getWebKitStyle(); 23167 verifyFormat("extern \"C\" {\n" 23168 "int foo();\n" 23169 "}", 23170 Style); 23171 } 23172 23173 TEST_F(FormatTest, ConceptsAndRequires) { 23174 FormatStyle Style = getLLVMStyle(); 23175 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 23176 23177 verifyFormat("template <typename T>\n" 23178 "concept Hashable = requires(T a) {\n" 23179 " { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;\n" 23180 "};", 23181 Style); 23182 verifyFormat("template <typename T>\n" 23183 "concept EqualityComparable = requires(T a, T b) {\n" 23184 " { a == b } -> bool;\n" 23185 "};", 23186 Style); 23187 verifyFormat("template <typename T>\n" 23188 "concept EqualityComparable = requires(T a, T b) {\n" 23189 " { a == b } -> bool;\n" 23190 " { a != b } -> bool;\n" 23191 "};", 23192 Style); 23193 verifyFormat("template <typename T>\n" 23194 "concept EqualityComparable = requires(T a, T b) {\n" 23195 " { a == b } -> bool;\n" 23196 " { a != b } -> bool;\n" 23197 "};", 23198 Style); 23199 23200 verifyFormat("template <typename It>\n" 23201 "requires Iterator<It>\n" 23202 "void sort(It begin, It end) {\n" 23203 " //....\n" 23204 "}", 23205 Style); 23206 23207 verifyFormat("template <typename T>\n" 23208 "concept Large = sizeof(T) > 10;", 23209 Style); 23210 23211 verifyFormat("template <typename T, typename U>\n" 23212 "concept FooableWith = requires(T t, U u) {\n" 23213 " typename T::foo_type;\n" 23214 " { t.foo(u) } -> typename T::foo_type;\n" 23215 " t++;\n" 23216 "};\n" 23217 "void doFoo(FooableWith<int> auto t) {\n" 23218 " t.foo(3);\n" 23219 "}", 23220 Style); 23221 verifyFormat("template <typename T>\n" 23222 "concept Context = sizeof(T) == 1;", 23223 Style); 23224 verifyFormat("template <typename T>\n" 23225 "concept Context = is_specialization_of_v<context, T>;", 23226 Style); 23227 verifyFormat("template <typename T>\n" 23228 "concept Node = std::is_object_v<T>;", 23229 Style); 23230 verifyFormat("template <typename T>\n" 23231 "concept Tree = true;", 23232 Style); 23233 23234 verifyFormat("template <typename T> int g(T i) requires Concept1<I> {\n" 23235 " //...\n" 23236 "}", 23237 Style); 23238 23239 verifyFormat( 23240 "template <typename T> int g(T i) requires Concept1<I> && Concept2<I> {\n" 23241 " //...\n" 23242 "}", 23243 Style); 23244 23245 verifyFormat( 23246 "template <typename T> int g(T i) requires Concept1<I> || Concept2<I> {\n" 23247 " //...\n" 23248 "}", 23249 Style); 23250 23251 verifyFormat("template <typename T>\n" 23252 "veryveryvery_long_return_type g(T i) requires Concept1<I> || " 23253 "Concept2<I> {\n" 23254 " //...\n" 23255 "}", 23256 Style); 23257 23258 verifyFormat("template <typename T>\n" 23259 "veryveryvery_long_return_type g(T i) requires Concept1<I> && " 23260 "Concept2<I> {\n" 23261 " //...\n" 23262 "}", 23263 Style); 23264 23265 verifyFormat( 23266 "template <typename T>\n" 23267 "veryveryvery_long_return_type g(T i) requires Concept1 && Concept2 {\n" 23268 " //...\n" 23269 "}", 23270 Style); 23271 23272 verifyFormat( 23273 "template <typename T>\n" 23274 "veryveryvery_long_return_type g(T i) requires Concept1 || Concept2 {\n" 23275 " //...\n" 23276 "}", 23277 Style); 23278 23279 verifyFormat("template <typename It>\n" 23280 "requires Foo<It>() && Bar<It> {\n" 23281 " //....\n" 23282 "}", 23283 Style); 23284 23285 verifyFormat("template <typename It>\n" 23286 "requires Foo<Bar<It>>() && Bar<Foo<It, It>> {\n" 23287 " //....\n" 23288 "}", 23289 Style); 23290 23291 verifyFormat("template <typename It>\n" 23292 "requires Foo<Bar<It, It>>() && Bar<Foo<It, It>> {\n" 23293 " //....\n" 23294 "}", 23295 Style); 23296 23297 verifyFormat( 23298 "template <typename It>\n" 23299 "requires Foo<Bar<It>, Baz<It>>() && Bar<Foo<It>, Baz<It, It>> {\n" 23300 " //....\n" 23301 "}", 23302 Style); 23303 23304 Style.IndentRequires = true; 23305 verifyFormat("template <typename It>\n" 23306 " requires Iterator<It>\n" 23307 "void sort(It begin, It end) {\n" 23308 " //....\n" 23309 "}", 23310 Style); 23311 verifyFormat("template <std::size index_>\n" 23312 " requires(index_ < sizeof...(Children_))\n" 23313 "Tree auto &child() {\n" 23314 " // ...\n" 23315 "}", 23316 Style); 23317 23318 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 23319 verifyFormat("template <typename T>\n" 23320 "concept Hashable = requires (T a) {\n" 23321 " { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;\n" 23322 "};", 23323 Style); 23324 23325 verifyFormat("template <class T = void>\n" 23326 " requires EqualityComparable<T> || Same<T, void>\n" 23327 "struct equal_to;", 23328 Style); 23329 23330 verifyFormat("template <class T>\n" 23331 " requires requires {\n" 23332 " T{};\n" 23333 " T (int);\n" 23334 " }\n", 23335 Style); 23336 23337 Style.ColumnLimit = 78; 23338 verifyFormat("template <typename T>\n" 23339 "concept Context = Traits<typename T::traits_type> and\n" 23340 " Interface<typename T::interface_type> and\n" 23341 " Request<typename T::request_type> and\n" 23342 " Response<typename T::response_type> and\n" 23343 " ContextExtension<typename T::extension_type> and\n" 23344 " ::std::is_copy_constructable<T> and " 23345 "::std::is_move_constructable<T> and\n" 23346 " requires (T c) {\n" 23347 " { c.response; } -> Response;\n" 23348 "} and requires (T c) {\n" 23349 " { c.request; } -> Request;\n" 23350 "}\n", 23351 Style); 23352 23353 verifyFormat("template <typename T>\n" 23354 "concept Context = Traits<typename T::traits_type> or\n" 23355 " Interface<typename T::interface_type> or\n" 23356 " Request<typename T::request_type> or\n" 23357 " Response<typename T::response_type> or\n" 23358 " ContextExtension<typename T::extension_type> or\n" 23359 " ::std::is_copy_constructable<T> or " 23360 "::std::is_move_constructable<T> or\n" 23361 " requires (T c) {\n" 23362 " { c.response; } -> Response;\n" 23363 "} or requires (T c) {\n" 23364 " { c.request; } -> Request;\n" 23365 "}\n", 23366 Style); 23367 23368 verifyFormat("template <typename T>\n" 23369 "concept Context = Traits<typename T::traits_type> &&\n" 23370 " Interface<typename T::interface_type> &&\n" 23371 " Request<typename T::request_type> &&\n" 23372 " Response<typename T::response_type> &&\n" 23373 " ContextExtension<typename T::extension_type> &&\n" 23374 " ::std::is_copy_constructable<T> && " 23375 "::std::is_move_constructable<T> &&\n" 23376 " requires (T c) {\n" 23377 " { c.response; } -> Response;\n" 23378 "} && requires (T c) {\n" 23379 " { c.request; } -> Request;\n" 23380 "}\n", 23381 Style); 23382 23383 verifyFormat("template <typename T>\nconcept someConcept = Constraint1<T> && " 23384 "Constraint2<T>;"); 23385 23386 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 23387 Style.BraceWrapping.AfterFunction = true; 23388 Style.BraceWrapping.AfterClass = true; 23389 Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 23390 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 23391 verifyFormat("void Foo () requires (std::copyable<T>)\n" 23392 "{\n" 23393 " return\n" 23394 "}\n", 23395 Style); 23396 23397 verifyFormat("void Foo () requires std::copyable<T>\n" 23398 "{\n" 23399 " return\n" 23400 "}\n", 23401 Style); 23402 23403 verifyFormat("template <std::semiregular F, std::semiregular... Args>\n" 23404 " requires (std::invocable<F, std::invoke_result_t<Args>...>)\n" 23405 "struct constant;", 23406 Style); 23407 23408 verifyFormat("template <std::semiregular F, std::semiregular... Args>\n" 23409 " requires std::invocable<F, std::invoke_result_t<Args>...>\n" 23410 "struct constant;", 23411 Style); 23412 23413 verifyFormat("template <class T>\n" 23414 "class plane_with_very_very_very_long_name\n" 23415 "{\n" 23416 " constexpr plane_with_very_very_very_long_name () requires " 23417 "std::copyable<T>\n" 23418 " : plane_with_very_very_very_long_name (1)\n" 23419 " {\n" 23420 " }\n" 23421 "}\n", 23422 Style); 23423 23424 verifyFormat("template <class T>\n" 23425 "class plane_with_long_name\n" 23426 "{\n" 23427 " constexpr plane_with_long_name () requires std::copyable<T>\n" 23428 " : plane_with_long_name (1)\n" 23429 " {\n" 23430 " }\n" 23431 "}\n", 23432 Style); 23433 23434 Style.BreakBeforeConceptDeclarations = false; 23435 verifyFormat("template <typename T> concept Tree = true;", Style); 23436 23437 Style.IndentRequires = false; 23438 verifyFormat("template <std::semiregular F, std::semiregular... Args>\n" 23439 "requires (std::invocable<F, std::invoke_result_t<Args>...>) " 23440 "struct constant;", 23441 Style); 23442 } 23443 23444 TEST_F(FormatTest, StatementAttributeLikeMacros) { 23445 FormatStyle Style = getLLVMStyle(); 23446 StringRef Source = "void Foo::slot() {\n" 23447 " unsigned char MyChar = 'x';\n" 23448 " emit signal(MyChar);\n" 23449 " Q_EMIT signal(MyChar);\n" 23450 "}"; 23451 23452 EXPECT_EQ(Source, format(Source, Style)); 23453 23454 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 23455 EXPECT_EQ("void Foo::slot() {\n" 23456 " unsigned char MyChar = 'x';\n" 23457 " emit signal(MyChar);\n" 23458 " Q_EMIT signal(MyChar);\n" 23459 "}", 23460 format(Source, Style)); 23461 23462 Style.StatementAttributeLikeMacros.push_back("emit"); 23463 EXPECT_EQ(Source, format(Source, Style)); 23464 23465 Style.StatementAttributeLikeMacros = {}; 23466 EXPECT_EQ("void Foo::slot() {\n" 23467 " unsigned char MyChar = 'x';\n" 23468 " emit signal(MyChar);\n" 23469 " Q_EMIT signal(MyChar);\n" 23470 "}", 23471 format(Source, Style)); 23472 } 23473 23474 TEST_F(FormatTest, IndentAccessModifiers) { 23475 FormatStyle Style = getLLVMStyle(); 23476 Style.IndentAccessModifiers = true; 23477 // Members are *two* levels below the record; 23478 // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation. 23479 verifyFormat("class C {\n" 23480 " int i;\n" 23481 "};\n", 23482 Style); 23483 verifyFormat("union C {\n" 23484 " int i;\n" 23485 " unsigned u;\n" 23486 "};\n", 23487 Style); 23488 // Access modifiers should be indented one level below the record. 23489 verifyFormat("class C {\n" 23490 " public:\n" 23491 " int i;\n" 23492 "};\n", 23493 Style); 23494 verifyFormat("struct S {\n" 23495 " private:\n" 23496 " class C {\n" 23497 " int j;\n" 23498 "\n" 23499 " public:\n" 23500 " C();\n" 23501 " };\n" 23502 "\n" 23503 " public:\n" 23504 " int i;\n" 23505 "};\n", 23506 Style); 23507 // Enumerations are not records and should be unaffected. 23508 Style.AllowShortEnumsOnASingleLine = false; 23509 verifyFormat("enum class E {\n" 23510 " A,\n" 23511 " B\n" 23512 "};\n", 23513 Style); 23514 // Test with a different indentation width; 23515 // also proves that the result is Style.AccessModifierOffset agnostic. 23516 Style.IndentWidth = 3; 23517 verifyFormat("class C {\n" 23518 " public:\n" 23519 " int i;\n" 23520 "};\n", 23521 Style); 23522 } 23523 23524 TEST_F(FormatTest, LimitlessStringsAndComments) { 23525 auto Style = getLLVMStyleWithColumns(0); 23526 constexpr StringRef Code = 23527 "/**\n" 23528 " * This is a multiline comment with quite some long lines, at least for " 23529 "the LLVM Style.\n" 23530 " * We will redo this with strings and line comments. Just to check if " 23531 "everything is working.\n" 23532 " */\n" 23533 "bool foo() {\n" 23534 " /* Single line multi line comment. */\n" 23535 " const std::string String = \"This is a multiline string with quite " 23536 "some long lines, at least for the LLVM Style.\"\n" 23537 " \"We already did it with multi line " 23538 "comments, and we will do it with line comments. Just to check if " 23539 "everything is working.\";\n" 23540 " // This is a line comment (block) with quite some long lines, at " 23541 "least for the LLVM Style.\n" 23542 " // We already did this with multi line comments and strings. Just to " 23543 "check if everything is working.\n" 23544 " const std::string SmallString = \"Hello World\";\n" 23545 " // Small line comment\n" 23546 " return String.size() > SmallString.size();\n" 23547 "}"; 23548 EXPECT_EQ(Code, format(Code, Style)); 23549 } 23550 23551 TEST_F(FormatTest, FormatDecayCopy) { 23552 // error cases from unit tests 23553 verifyFormat("foo(auto())"); 23554 verifyFormat("foo(auto{})"); 23555 verifyFormat("foo(auto({}))"); 23556 verifyFormat("foo(auto{{}})"); 23557 23558 verifyFormat("foo(auto(1))"); 23559 verifyFormat("foo(auto{1})"); 23560 verifyFormat("foo(new auto(1))"); 23561 verifyFormat("foo(new auto{1})"); 23562 verifyFormat("decltype(auto(1)) x;"); 23563 verifyFormat("decltype(auto{1}) x;"); 23564 verifyFormat("auto(x);"); 23565 verifyFormat("auto{x};"); 23566 verifyFormat("new auto{x};"); 23567 verifyFormat("auto{x} = y;"); 23568 verifyFormat("auto(x) = y;"); // actually a declaration, but this is clearly 23569 // the user's own fault 23570 verifyFormat("integral auto(x) = y;"); // actually a declaration, but this is 23571 // clearly the user's own fault 23572 verifyFormat("auto(*p)() = f;"); // actually a declaration; TODO FIXME 23573 } 23574 23575 TEST_F(FormatTest, Cpp20ModulesSupport) { 23576 FormatStyle Style = getLLVMStyle(); 23577 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 23578 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 23579 23580 verifyFormat("export import foo;", Style); 23581 verifyFormat("export import foo:bar;", Style); 23582 verifyFormat("export import foo.bar;", Style); 23583 verifyFormat("export import foo.bar:baz;", Style); 23584 verifyFormat("export import :bar;", Style); 23585 verifyFormat("export module foo:bar;", Style); 23586 verifyFormat("export module foo;", Style); 23587 verifyFormat("export module foo.bar;", Style); 23588 verifyFormat("export module foo.bar:baz;", Style); 23589 verifyFormat("export import <string_view>;", Style); 23590 23591 verifyFormat("export type_name var;", Style); 23592 verifyFormat("template <class T> export using A = B<T>;", Style); 23593 verifyFormat("export using A = B;", Style); 23594 verifyFormat("export int func() {\n" 23595 " foo();\n" 23596 "}", 23597 Style); 23598 verifyFormat("export struct {\n" 23599 " int foo;\n" 23600 "};", 23601 Style); 23602 verifyFormat("export {\n" 23603 " int foo;\n" 23604 "};", 23605 Style); 23606 verifyFormat("export export char const *hello() { return \"hello\"; }"); 23607 23608 verifyFormat("import bar;", Style); 23609 verifyFormat("import foo.bar;", Style); 23610 verifyFormat("import foo:bar;", Style); 23611 verifyFormat("import :bar;", Style); 23612 verifyFormat("import <ctime>;", Style); 23613 verifyFormat("import \"header\";", Style); 23614 23615 verifyFormat("module foo;", Style); 23616 verifyFormat("module foo:bar;", Style); 23617 verifyFormat("module foo.bar;", Style); 23618 verifyFormat("module;", Style); 23619 23620 verifyFormat("export namespace hi {\n" 23621 "const char *sayhi();\n" 23622 "}", 23623 Style); 23624 23625 verifyFormat("module :private;", Style); 23626 verifyFormat("import <foo/bar.h>;", Style); 23627 verifyFormat("import foo...bar;", Style); 23628 verifyFormat("import ..........;", Style); 23629 verifyFormat("module foo:private;", Style); 23630 verifyFormat("import a", Style); 23631 verifyFormat("module a", Style); 23632 verifyFormat("export import a", Style); 23633 verifyFormat("export module a", Style); 23634 23635 verifyFormat("import", Style); 23636 verifyFormat("module", Style); 23637 verifyFormat("export", Style); 23638 } 23639 23640 TEST_F(FormatTest, CoroutineForCoawait) { 23641 FormatStyle Style = getLLVMStyle(); 23642 verifyFormat("for co_await (auto x : range())\n ;"); 23643 verifyFormat("for (auto i : arr) {\n" 23644 "}", 23645 Style); 23646 verifyFormat("for co_await (auto i : arr) {\n" 23647 "}", 23648 Style); 23649 verifyFormat("for co_await (auto i : foo(T{})) {\n" 23650 "}", 23651 Style); 23652 } 23653 23654 TEST_F(FormatTest, CoroutineCoAwait) { 23655 verifyFormat("int x = co_await foo();"); 23656 verifyFormat("int x = (co_await foo());"); 23657 verifyFormat("co_await (42);"); 23658 verifyFormat("void operator co_await(int);"); 23659 verifyFormat("void operator co_await(a);"); 23660 verifyFormat("co_await a;"); 23661 verifyFormat("co_await missing_await_resume{};"); 23662 verifyFormat("co_await a; // comment"); 23663 verifyFormat("void test0() { co_await a; }"); 23664 verifyFormat("co_await co_await co_await foo();"); 23665 verifyFormat("co_await foo().bar();"); 23666 verifyFormat("co_await [this]() -> Task { co_return x; }"); 23667 verifyFormat("co_await [this](int a, int b) -> Task { co_return co_await " 23668 "foo(); }(x, y);"); 23669 23670 FormatStyle Style = getLLVMStyleWithColumns(40); 23671 verifyFormat("co_await [this](int a, int b) -> Task {\n" 23672 " co_return co_await foo();\n" 23673 "}(x, y);", 23674 Style); 23675 verifyFormat("co_await;"); 23676 } 23677 23678 TEST_F(FormatTest, CoroutineCoYield) { 23679 verifyFormat("int x = co_yield foo();"); 23680 verifyFormat("int x = (co_yield foo());"); 23681 verifyFormat("co_yield (42);"); 23682 verifyFormat("co_yield {42};"); 23683 verifyFormat("co_yield 42;"); 23684 verifyFormat("co_yield n++;"); 23685 verifyFormat("co_yield ++n;"); 23686 verifyFormat("co_yield;"); 23687 } 23688 23689 TEST_F(FormatTest, CoroutineCoReturn) { 23690 verifyFormat("co_return (42);"); 23691 verifyFormat("co_return;"); 23692 verifyFormat("co_return {};"); 23693 verifyFormat("co_return x;"); 23694 verifyFormat("co_return co_await foo();"); 23695 verifyFormat("co_return co_yield foo();"); 23696 } 23697 23698 TEST_F(FormatTest, EmptyShortBlock) { 23699 auto Style = getLLVMStyle(); 23700 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 23701 23702 verifyFormat("try {\n" 23703 " doA();\n" 23704 "} catch (Exception &e) {\n" 23705 " e.printStackTrace();\n" 23706 "}\n", 23707 Style); 23708 23709 verifyFormat("try {\n" 23710 " doA();\n" 23711 "} catch (Exception &e) {}\n", 23712 Style); 23713 } 23714 23715 TEST_F(FormatTest, ShortTemplatedArgumentLists) { 23716 auto Style = getLLVMStyle(); 23717 23718 verifyFormat("template <> struct S : Template<int (*)[]> {};\n", Style); 23719 verifyFormat("template <> struct S : Template<int (*)[10]> {};\n", Style); 23720 verifyFormat("struct Y : X<[] { return 0; }> {};", Style); 23721 verifyFormat("struct Y<[] { return 0; }> {};", Style); 23722 23723 verifyFormat("struct Z : X<decltype([] { return 0; }){}> {};", Style); 23724 verifyFormat("template <int N> struct Foo<char[N]> {};", Style); 23725 } 23726 23727 TEST_F(FormatTest, RemoveBraces) { 23728 FormatStyle Style = getLLVMStyle(); 23729 Style.RemoveBracesLLVM = true; 23730 23731 // The following eight test cases are fully-braced versions of the examples at 23732 // "llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single- 23733 // statement-bodies-of-if-else-loop-statements". 23734 23735 // 1. Omit the braces, since the body is simple and clearly associated with 23736 // the if. 23737 verifyFormat("if (isa<FunctionDecl>(D))\n" 23738 " handleFunctionDecl(D);\n" 23739 "else if (isa<VarDecl>(D))\n" 23740 " handleVarDecl(D);", 23741 "if (isa<FunctionDecl>(D)) {\n" 23742 " handleFunctionDecl(D);\n" 23743 "} else if (isa<VarDecl>(D)) {\n" 23744 " handleVarDecl(D);\n" 23745 "}", 23746 Style); 23747 23748 // 2. Here we document the condition itself and not the body. 23749 verifyFormat("if (isa<VarDecl>(D)) {\n" 23750 " // It is necessary that we explain the situation with this\n" 23751 " // surprisingly long comment, so it would be unclear\n" 23752 " // without the braces whether the following statement is in\n" 23753 " // the scope of the `if`.\n" 23754 " // Because the condition is documented, we can't really\n" 23755 " // hoist this comment that applies to the body above the\n" 23756 " // if.\n" 23757 " handleOtherDecl(D);\n" 23758 "}", 23759 Style); 23760 23761 // 3. Use braces on the outer `if` to avoid a potential dangling else 23762 // situation. 23763 verifyFormat("if (isa<VarDecl>(D)) {\n" 23764 " for (auto *A : D.attrs())\n" 23765 " if (shouldProcessAttr(A))\n" 23766 " handleAttr(A);\n" 23767 "}", 23768 "if (isa<VarDecl>(D)) {\n" 23769 " for (auto *A : D.attrs()) {\n" 23770 " if (shouldProcessAttr(A)) {\n" 23771 " handleAttr(A);\n" 23772 " }\n" 23773 " }\n" 23774 "}", 23775 Style); 23776 23777 // 4. Use braces for the `if` block to keep it uniform with the else block. 23778 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 23779 " handleFunctionDecl(D);\n" 23780 "} else {\n" 23781 " // In this else case, it is necessary that we explain the\n" 23782 " // situation with this surprisingly long comment, so it\n" 23783 " // would be unclear without the braces whether the\n" 23784 " // following statement is in the scope of the `if`.\n" 23785 " handleOtherDecl(D);\n" 23786 "}", 23787 Style); 23788 23789 // 5. This should also omit braces. The `for` loop contains only a single 23790 // statement, so it shouldn't have braces. The `if` also only contains a 23791 // single simple statement (the for loop), so it also should omit braces. 23792 verifyFormat("if (isa<FunctionDecl>(D))\n" 23793 " for (auto *A : D.attrs())\n" 23794 " handleAttr(A);", 23795 "if (isa<FunctionDecl>(D)) {\n" 23796 " for (auto *A : D.attrs()) {\n" 23797 " handleAttr(A);\n" 23798 " }\n" 23799 "}", 23800 Style); 23801 23802 // 6. Use braces for the outer `if` since the nested `for` is braced. 23803 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 23804 " for (auto *A : D.attrs()) {\n" 23805 " // In this for loop body, it is necessary that we explain\n" 23806 " // the situation with this surprisingly long comment,\n" 23807 " // forcing braces on the `for` block.\n" 23808 " handleAttr(A);\n" 23809 " }\n" 23810 "}", 23811 Style); 23812 23813 // 7. Use braces on the outer block because there are more than two levels of 23814 // nesting. 23815 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 23816 " for (auto *A : D.attrs())\n" 23817 " for (ssize_t i : llvm::seq<ssize_t>(count))\n" 23818 " handleAttrOnDecl(D, A, i);\n" 23819 "}", 23820 "if (isa<FunctionDecl>(D)) {\n" 23821 " for (auto *A : D.attrs()) {\n" 23822 " for (ssize_t i : llvm::seq<ssize_t>(count)) {\n" 23823 " handleAttrOnDecl(D, A, i);\n" 23824 " }\n" 23825 " }\n" 23826 "}", 23827 Style); 23828 23829 // 8. Use braces on the outer block because of a nested `if`, otherwise the 23830 // compiler would warn: `add explicit braces to avoid dangling else` 23831 verifyFormat("if (auto *D = dyn_cast<FunctionDecl>(D)) {\n" 23832 " if (shouldProcess(D))\n" 23833 " handleVarDecl(D);\n" 23834 " else\n" 23835 " markAsIgnored(D);\n" 23836 "}", 23837 "if (auto *D = dyn_cast<FunctionDecl>(D)) {\n" 23838 " if (shouldProcess(D)) {\n" 23839 " handleVarDecl(D);\n" 23840 " } else {\n" 23841 " markAsIgnored(D);\n" 23842 " }\n" 23843 "}", 23844 Style); 23845 23846 verifyFormat("if (a)\n" 23847 " b; // comment\n" 23848 "else if (c)\n" 23849 " d; /* comment */\n" 23850 "else\n" 23851 " e;", 23852 "if (a) {\n" 23853 " b; // comment\n" 23854 "} else if (c) {\n" 23855 " d; /* comment */\n" 23856 "} else {\n" 23857 " e;\n" 23858 "}", 23859 Style); 23860 23861 verifyFormat("if (a) {\n" 23862 " b;\n" 23863 " c;\n" 23864 "} else if (d) {\n" 23865 " e;\n" 23866 "}", 23867 Style); 23868 23869 verifyFormat("if (a) {\n" 23870 "#undef NDEBUG\n" 23871 " b;\n" 23872 "} else {\n" 23873 " c;\n" 23874 "}", 23875 Style); 23876 23877 verifyFormat("if (a) {\n" 23878 " // comment\n" 23879 "} else if (b) {\n" 23880 " c;\n" 23881 "}", 23882 Style); 23883 23884 verifyFormat("if (a) {\n" 23885 " b;\n" 23886 "} else {\n" 23887 " { c; }\n" 23888 "}", 23889 Style); 23890 23891 verifyFormat("if (a) {\n" 23892 " if (b) // comment\n" 23893 " c;\n" 23894 "} else if (d) {\n" 23895 " e;\n" 23896 "}", 23897 "if (a) {\n" 23898 " if (b) { // comment\n" 23899 " c;\n" 23900 " }\n" 23901 "} else if (d) {\n" 23902 " e;\n" 23903 "}", 23904 Style); 23905 23906 verifyFormat("if (a) {\n" 23907 " if (b) {\n" 23908 " c;\n" 23909 " // comment\n" 23910 " } else if (d) {\n" 23911 " e;\n" 23912 " }\n" 23913 "}", 23914 Style); 23915 23916 verifyFormat("if (a) {\n" 23917 " if (b)\n" 23918 " c;\n" 23919 "}", 23920 "if (a) {\n" 23921 " if (b) {\n" 23922 " c;\n" 23923 " }\n" 23924 "}", 23925 Style); 23926 23927 verifyFormat("if (a)\n" 23928 " if (b)\n" 23929 " c;\n" 23930 " else\n" 23931 " d;\n" 23932 "else\n" 23933 " e;", 23934 "if (a) {\n" 23935 " if (b) {\n" 23936 " c;\n" 23937 " } else {\n" 23938 " d;\n" 23939 " }\n" 23940 "} else {\n" 23941 " e;\n" 23942 "}", 23943 Style); 23944 23945 verifyFormat("if (a) {\n" 23946 " // comment\n" 23947 " if (b)\n" 23948 " c;\n" 23949 " else if (d)\n" 23950 " e;\n" 23951 "} else {\n" 23952 " g;\n" 23953 "}", 23954 "if (a) {\n" 23955 " // comment\n" 23956 " if (b) {\n" 23957 " c;\n" 23958 " } else if (d) {\n" 23959 " e;\n" 23960 " }\n" 23961 "} else {\n" 23962 " g;\n" 23963 "}", 23964 Style); 23965 23966 verifyFormat("if (a)\n" 23967 " b;\n" 23968 "else if (c)\n" 23969 " d;\n" 23970 "else\n" 23971 " e;", 23972 "if (a) {\n" 23973 " b;\n" 23974 "} else {\n" 23975 " if (c) {\n" 23976 " d;\n" 23977 " } else {\n" 23978 " e;\n" 23979 " }\n" 23980 "}", 23981 Style); 23982 23983 verifyFormat("if (a) {\n" 23984 " if (b)\n" 23985 " c;\n" 23986 " else if (d)\n" 23987 " e;\n" 23988 "} else {\n" 23989 " g;\n" 23990 "}", 23991 "if (a) {\n" 23992 " if (b)\n" 23993 " c;\n" 23994 " else {\n" 23995 " if (d)\n" 23996 " e;\n" 23997 " }\n" 23998 "} else {\n" 23999 " g;\n" 24000 "}", 24001 Style); 24002 24003 verifyFormat("if (a)\n" 24004 " b;\n" 24005 "else if (c)\n" 24006 " while (d)\n" 24007 " e;\n" 24008 "// comment", 24009 "if (a)\n" 24010 "{\n" 24011 " b;\n" 24012 "} else if (c) {\n" 24013 " while (d) {\n" 24014 " e;\n" 24015 " }\n" 24016 "}\n" 24017 "// comment", 24018 Style); 24019 24020 verifyFormat("if (a) {\n" 24021 " b;\n" 24022 "} else if (c) {\n" 24023 " d;\n" 24024 "} else {\n" 24025 " e;\n" 24026 " g;\n" 24027 "}", 24028 Style); 24029 24030 verifyFormat("if (a) {\n" 24031 " b;\n" 24032 "} else if (c) {\n" 24033 " d;\n" 24034 "} else {\n" 24035 " e;\n" 24036 "} // comment", 24037 Style); 24038 24039 verifyFormat("int abs = [](int i) {\n" 24040 " if (i >= 0)\n" 24041 " return i;\n" 24042 " return -i;\n" 24043 "};", 24044 "int abs = [](int i) {\n" 24045 " if (i >= 0) {\n" 24046 " return i;\n" 24047 " }\n" 24048 " return -i;\n" 24049 "};", 24050 Style); 24051 24052 // FIXME: See https://github.com/llvm/llvm-project/issues/53543. 24053 #if 0 24054 Style.ColumnLimit = 65; 24055 24056 verifyFormat("if (condition) {\n" 24057 " ff(Indices,\n" 24058 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 24059 "} else {\n" 24060 " ff(Indices,\n" 24061 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 24062 "}", 24063 Style); 24064 24065 Style.ColumnLimit = 20; 24066 24067 verifyFormat("if (a) {\n" 24068 " b = c + // 1 -\n" 24069 " d;\n" 24070 "}", 24071 Style); 24072 24073 verifyFormat("if (a) {\n" 24074 " b = c >= 0 ? d\n" 24075 " : e;\n" 24076 "}", 24077 "if (a) {\n" 24078 " b = c >= 0 ? d : e;\n" 24079 "}", 24080 Style); 24081 #endif 24082 24083 Style.ColumnLimit = 20; 24084 24085 verifyFormat("if (a)\n" 24086 " b = c > 0 ? d : e;", 24087 "if (a) {\n" 24088 " b = c > 0 ? d : e;\n" 24089 "}", 24090 Style); 24091 24092 Style.ColumnLimit = 0; 24093 24094 verifyFormat("if (a)\n" 24095 " b234567890223456789032345678904234567890 = " 24096 "c234567890223456789032345678904234567890;", 24097 "if (a) {\n" 24098 " b234567890223456789032345678904234567890 = " 24099 "c234567890223456789032345678904234567890;\n" 24100 "}", 24101 Style); 24102 } 24103 24104 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndent) { 24105 auto Style = getLLVMStyle(); 24106 24107 StringRef Short = "functionCall(paramA, paramB, paramC);\n" 24108 "void functionDecl(int a, int b, int c);"; 24109 24110 StringRef Medium = "functionCall(paramA, paramB, paramC, paramD, paramE, " 24111 "paramF, paramG, paramH, paramI);\n" 24112 "void functionDecl(int argumentA, int argumentB, int " 24113 "argumentC, int argumentD, int argumentE);"; 24114 24115 verifyFormat(Short, Style); 24116 24117 StringRef NoBreak = "functionCall(paramA, paramB, paramC, paramD, paramE, " 24118 "paramF, paramG, paramH,\n" 24119 " paramI);\n" 24120 "void functionDecl(int argumentA, int argumentB, int " 24121 "argumentC, int argumentD,\n" 24122 " int argumentE);"; 24123 24124 verifyFormat(NoBreak, Medium, Style); 24125 verifyFormat(NoBreak, 24126 "functionCall(\n" 24127 " paramA,\n" 24128 " paramB,\n" 24129 " paramC,\n" 24130 " paramD,\n" 24131 " paramE,\n" 24132 " paramF,\n" 24133 " paramG,\n" 24134 " paramH,\n" 24135 " paramI\n" 24136 ");\n" 24137 "void functionDecl(\n" 24138 " int argumentA,\n" 24139 " int argumentB,\n" 24140 " int argumentC,\n" 24141 " int argumentD,\n" 24142 " int argumentE\n" 24143 ");", 24144 Style); 24145 24146 verifyFormat("outerFunctionCall(nestedFunctionCall(argument1),\n" 24147 " nestedLongFunctionCall(argument1, " 24148 "argument2, argument3,\n" 24149 " argument4, " 24150 "argument5));", 24151 Style); 24152 24153 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 24154 24155 verifyFormat(Short, Style); 24156 verifyFormat( 24157 "functionCall(\n" 24158 " paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, " 24159 "paramI\n" 24160 ");\n" 24161 "void functionDecl(\n" 24162 " int argumentA, int argumentB, int argumentC, int argumentD, int " 24163 "argumentE\n" 24164 ");", 24165 Medium, Style); 24166 24167 Style.AllowAllArgumentsOnNextLine = false; 24168 Style.AllowAllParametersOfDeclarationOnNextLine = false; 24169 24170 verifyFormat(Short, Style); 24171 verifyFormat( 24172 "functionCall(\n" 24173 " paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, " 24174 "paramI\n" 24175 ");\n" 24176 "void functionDecl(\n" 24177 " int argumentA, int argumentB, int argumentC, int argumentD, int " 24178 "argumentE\n" 24179 ");", 24180 Medium, Style); 24181 24182 Style.BinPackArguments = false; 24183 Style.BinPackParameters = false; 24184 24185 verifyFormat(Short, Style); 24186 24187 verifyFormat("functionCall(\n" 24188 " paramA,\n" 24189 " paramB,\n" 24190 " paramC,\n" 24191 " paramD,\n" 24192 " paramE,\n" 24193 " paramF,\n" 24194 " paramG,\n" 24195 " paramH,\n" 24196 " paramI\n" 24197 ");\n" 24198 "void functionDecl(\n" 24199 " int argumentA,\n" 24200 " int argumentB,\n" 24201 " int argumentC,\n" 24202 " int argumentD,\n" 24203 " int argumentE\n" 24204 ");", 24205 Medium, Style); 24206 24207 verifyFormat("outerFunctionCall(\n" 24208 " nestedFunctionCall(argument1),\n" 24209 " nestedLongFunctionCall(\n" 24210 " argument1,\n" 24211 " argument2,\n" 24212 " argument3,\n" 24213 " argument4,\n" 24214 " argument5\n" 24215 " )\n" 24216 ");", 24217 Style); 24218 24219 verifyFormat("int a = (int)b;", Style); 24220 verifyFormat("int a = (int)b;", 24221 "int a = (\n" 24222 " int\n" 24223 ") b;", 24224 Style); 24225 24226 verifyFormat("return (true);", Style); 24227 verifyFormat("return (true);", 24228 "return (\n" 24229 " true\n" 24230 ");", 24231 Style); 24232 24233 verifyFormat("void foo();", Style); 24234 verifyFormat("void foo();", 24235 "void foo(\n" 24236 ");", 24237 Style); 24238 24239 verifyFormat("void foo() {}", Style); 24240 verifyFormat("void foo() {}", 24241 "void foo(\n" 24242 ") {\n" 24243 "}", 24244 Style); 24245 24246 verifyFormat("auto string = std::string();", Style); 24247 verifyFormat("auto string = std::string();", 24248 "auto string = std::string(\n" 24249 ");", 24250 Style); 24251 24252 verifyFormat("void (*functionPointer)() = nullptr;", Style); 24253 verifyFormat("void (*functionPointer)() = nullptr;", 24254 "void (\n" 24255 " *functionPointer\n" 24256 ")\n" 24257 "(\n" 24258 ") = nullptr;", 24259 Style); 24260 } 24261 24262 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentIfStatement) { 24263 auto Style = getLLVMStyle(); 24264 24265 verifyFormat("if (foo()) {\n" 24266 " return;\n" 24267 "}", 24268 Style); 24269 24270 verifyFormat("if (quitelongarg !=\n" 24271 " (alsolongarg - 1)) { // ABC is a very longgggggggggggg " 24272 "comment\n" 24273 " return;\n" 24274 "}", 24275 Style); 24276 24277 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 24278 24279 verifyFormat("if (foo()) {\n" 24280 " return;\n" 24281 "}", 24282 Style); 24283 24284 verifyFormat("if (quitelongarg !=\n" 24285 " (alsolongarg - 1)) { // ABC is a very longgggggggggggg " 24286 "comment\n" 24287 " return;\n" 24288 "}", 24289 Style); 24290 } 24291 24292 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentForStatement) { 24293 auto Style = getLLVMStyle(); 24294 24295 verifyFormat("for (int i = 0; i < 5; ++i) {\n" 24296 " doSomething();\n" 24297 "}", 24298 Style); 24299 24300 verifyFormat("for (int myReallyLongCountVariable = 0; " 24301 "myReallyLongCountVariable < count;\n" 24302 " myReallyLongCountVariable++) {\n" 24303 " doSomething();\n" 24304 "}", 24305 Style); 24306 24307 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 24308 24309 verifyFormat("for (int i = 0; i < 5; ++i) {\n" 24310 " doSomething();\n" 24311 "}", 24312 Style); 24313 24314 verifyFormat("for (int myReallyLongCountVariable = 0; " 24315 "myReallyLongCountVariable < count;\n" 24316 " myReallyLongCountVariable++) {\n" 24317 " doSomething();\n" 24318 "}", 24319 Style); 24320 } 24321 24322 TEST_F(FormatTest, UnderstandsDigraphs) { 24323 verifyFormat("int arr<:5:> = {};"); 24324 verifyFormat("int arr[5] = <%%>;"); 24325 verifyFormat("int arr<:::qualified_variable:> = {};"); 24326 verifyFormat("int arr[::qualified_variable] = <%%>;"); 24327 verifyFormat("%:include <header>"); 24328 verifyFormat("%:define A x##y"); 24329 verifyFormat("#define A x%:%:y"); 24330 } 24331 24332 } // namespace 24333 } // namespace format 24334 } // namespace clang 24335