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, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) { 1799 FormatStyle Style = getLLVMStyleWithColumns(60); 1800 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 1801 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse; 1802 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 1803 EXPECT_EQ("#define A \\\n" 1804 " if (HANDLEwernufrnuLwrmviferuvnierv) \\\n" 1805 " { \\\n" 1806 " RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n" 1807 " }\n" 1808 "X;", 1809 format("#define A \\\n" 1810 " if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n" 1811 " RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n" 1812 " }\n" 1813 "X;", 1814 Style)); 1815 } 1816 1817 TEST_F(FormatTest, ParseIfElse) { 1818 verifyFormat("if (true)\n" 1819 " if (true)\n" 1820 " if (true)\n" 1821 " f();\n" 1822 " else\n" 1823 " g();\n" 1824 " else\n" 1825 " h();\n" 1826 "else\n" 1827 " i();"); 1828 verifyFormat("if (true)\n" 1829 " if (true)\n" 1830 " if (true) {\n" 1831 " if (true)\n" 1832 " f();\n" 1833 " } else {\n" 1834 " g();\n" 1835 " }\n" 1836 " else\n" 1837 " h();\n" 1838 "else {\n" 1839 " i();\n" 1840 "}"); 1841 verifyFormat("if (true)\n" 1842 " if constexpr (true)\n" 1843 " if (true) {\n" 1844 " if constexpr (true)\n" 1845 " f();\n" 1846 " } else {\n" 1847 " g();\n" 1848 " }\n" 1849 " else\n" 1850 " h();\n" 1851 "else {\n" 1852 " i();\n" 1853 "}"); 1854 verifyFormat("if (true)\n" 1855 " if CONSTEXPR (true)\n" 1856 " if (true) {\n" 1857 " if CONSTEXPR (true)\n" 1858 " f();\n" 1859 " } else {\n" 1860 " g();\n" 1861 " }\n" 1862 " else\n" 1863 " h();\n" 1864 "else {\n" 1865 " i();\n" 1866 "}"); 1867 verifyFormat("void f() {\n" 1868 " if (a) {\n" 1869 " } else {\n" 1870 " }\n" 1871 "}"); 1872 } 1873 1874 TEST_F(FormatTest, ElseIf) { 1875 verifyFormat("if (a) {\n} else if (b) {\n}"); 1876 verifyFormat("if (a)\n" 1877 " f();\n" 1878 "else if (b)\n" 1879 " g();\n" 1880 "else\n" 1881 " h();"); 1882 verifyFormat("if (a)\n" 1883 " f();\n" 1884 "else // comment\n" 1885 " if (b) {\n" 1886 " g();\n" 1887 " h();\n" 1888 " }"); 1889 verifyFormat("if constexpr (a)\n" 1890 " f();\n" 1891 "else if constexpr (b)\n" 1892 " g();\n" 1893 "else\n" 1894 " h();"); 1895 verifyFormat("if CONSTEXPR (a)\n" 1896 " f();\n" 1897 "else if CONSTEXPR (b)\n" 1898 " g();\n" 1899 "else\n" 1900 " h();"); 1901 verifyFormat("if (a) {\n" 1902 " f();\n" 1903 "}\n" 1904 "// or else ..\n" 1905 "else {\n" 1906 " g()\n" 1907 "}"); 1908 1909 verifyFormat("if (a) {\n" 1910 "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 1911 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 1912 "}"); 1913 verifyFormat("if (a) {\n" 1914 "} else if constexpr (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 1915 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 1916 "}"); 1917 verifyFormat("if (a) {\n" 1918 "} else if CONSTEXPR (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 1919 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 1920 "}"); 1921 verifyFormat("if (a) {\n" 1922 "} else if (\n" 1923 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 1924 "}", 1925 getLLVMStyleWithColumns(62)); 1926 verifyFormat("if (a) {\n" 1927 "} else if constexpr (\n" 1928 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 1929 "}", 1930 getLLVMStyleWithColumns(62)); 1931 verifyFormat("if (a) {\n" 1932 "} else if CONSTEXPR (\n" 1933 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 1934 "}", 1935 getLLVMStyleWithColumns(62)); 1936 } 1937 1938 TEST_F(FormatTest, SeparatePointerReferenceAlignment) { 1939 FormatStyle Style = getLLVMStyle(); 1940 // Check first the default LLVM style 1941 // Style.PointerAlignment = FormatStyle::PAS_Right; 1942 // Style.ReferenceAlignment = FormatStyle::RAS_Pointer; 1943 verifyFormat("int *f1(int *a, int &b, int &&c);", Style); 1944 verifyFormat("int &f2(int &&c, int *a, int &b);", Style); 1945 verifyFormat("int &&f3(int &b, int &&c, int *a);", Style); 1946 verifyFormat("int *f1(int &a) const &;", Style); 1947 verifyFormat("int *f1(int &a) const & = 0;", Style); 1948 verifyFormat("int *a = f1();", Style); 1949 verifyFormat("int &b = f2();", Style); 1950 verifyFormat("int &&c = f3();", Style); 1951 verifyFormat("for (auto a = 0, b = 0; const auto &c : {1, 2, 3})", Style); 1952 verifyFormat("for (auto a = 0, b = 0; const int &c : {1, 2, 3})", Style); 1953 verifyFormat("for (auto a = 0, b = 0; const Foo &c : {1, 2, 3})", Style); 1954 verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style); 1955 verifyFormat("for (int a = 0, b = 0; const auto &c : {1, 2, 3})", Style); 1956 verifyFormat("for (int a = 0, b = 0; const int &c : {1, 2, 3})", Style); 1957 verifyFormat("for (int a = 0, b = 0; const Foo &c : {1, 2, 3})", Style); 1958 verifyFormat("for (int a = 0, b++; const auto &c : {1, 2, 3})", Style); 1959 verifyFormat("for (int a = 0, b++; const int &c : {1, 2, 3})", Style); 1960 verifyFormat("for (int a = 0, b++; const Foo &c : {1, 2, 3})", Style); 1961 verifyFormat("for (auto x = 0; auto &c : {1, 2, 3})", Style); 1962 verifyFormat("for (auto x = 0; int &c : {1, 2, 3})", Style); 1963 verifyFormat("for (int x = 0; auto &c : {1, 2, 3})", Style); 1964 verifyFormat("for (int x = 0; int &c : {1, 2, 3})", Style); 1965 verifyFormat("for (f(); auto &c : {1, 2, 3})", Style); 1966 verifyFormat("for (f(); int &c : {1, 2, 3})", Style); 1967 1968 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 1969 verifyFormat("Const unsigned int *c;\n" 1970 "const unsigned int *d;\n" 1971 "Const unsigned int &e;\n" 1972 "const unsigned int &f;\n" 1973 "const unsigned &&g;\n" 1974 "Const unsigned h;", 1975 Style); 1976 1977 Style.PointerAlignment = FormatStyle::PAS_Left; 1978 Style.ReferenceAlignment = FormatStyle::RAS_Pointer; 1979 verifyFormat("int* f1(int* a, int& b, int&& c);", Style); 1980 verifyFormat("int& f2(int&& c, int* a, int& b);", Style); 1981 verifyFormat("int&& f3(int& b, int&& c, int* a);", Style); 1982 verifyFormat("int* f1(int& a) const& = 0;", Style); 1983 verifyFormat("int* a = f1();", Style); 1984 verifyFormat("int& b = f2();", Style); 1985 verifyFormat("int&& c = f3();", Style); 1986 verifyFormat("for (auto a = 0, b = 0; const auto& c : {1, 2, 3})", Style); 1987 verifyFormat("for (auto a = 0, b = 0; const int& c : {1, 2, 3})", Style); 1988 verifyFormat("for (auto a = 0, b = 0; const Foo& c : {1, 2, 3})", Style); 1989 verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style); 1990 verifyFormat("for (int a = 0, b = 0; const auto& c : {1, 2, 3})", Style); 1991 verifyFormat("for (int a = 0, b = 0; const int& c : {1, 2, 3})", Style); 1992 verifyFormat("for (int a = 0, b = 0; const Foo& c : {1, 2, 3})", Style); 1993 verifyFormat("for (int a = 0, b = 0; const Foo* c : {1, 2, 3})", Style); 1994 verifyFormat("for (int a = 0, b++; const auto& c : {1, 2, 3})", Style); 1995 verifyFormat("for (int a = 0, b++; const int& c : {1, 2, 3})", Style); 1996 verifyFormat("for (int a = 0, b++; const Foo& c : {1, 2, 3})", Style); 1997 verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style); 1998 verifyFormat("for (auto x = 0; auto& c : {1, 2, 3})", Style); 1999 verifyFormat("for (auto x = 0; int& c : {1, 2, 3})", Style); 2000 verifyFormat("for (int x = 0; auto& c : {1, 2, 3})", Style); 2001 verifyFormat("for (int x = 0; int& c : {1, 2, 3})", Style); 2002 verifyFormat("for (f(); auto& c : {1, 2, 3})", Style); 2003 verifyFormat("for (f(); int& c : {1, 2, 3})", Style); 2004 2005 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 2006 verifyFormat("Const unsigned int* c;\n" 2007 "const unsigned int* d;\n" 2008 "Const unsigned int& e;\n" 2009 "const unsigned int& f;\n" 2010 "const unsigned&& g;\n" 2011 "Const unsigned h;", 2012 Style); 2013 2014 Style.PointerAlignment = FormatStyle::PAS_Right; 2015 Style.ReferenceAlignment = FormatStyle::RAS_Left; 2016 verifyFormat("int *f1(int *a, int& b, int&& c);", Style); 2017 verifyFormat("int& f2(int&& c, int *a, int& b);", Style); 2018 verifyFormat("int&& f3(int& b, int&& c, int *a);", Style); 2019 verifyFormat("int *a = f1();", Style); 2020 verifyFormat("int& b = f2();", Style); 2021 verifyFormat("int&& c = f3();", Style); 2022 verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style); 2023 verifyFormat("for (int a = 0, b = 0; const Foo *c : {1, 2, 3})", Style); 2024 verifyFormat("for (int a = 0, b++; const Foo *c : {1, 2, 3})", Style); 2025 2026 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 2027 verifyFormat("Const unsigned int *c;\n" 2028 "const unsigned int *d;\n" 2029 "Const unsigned int& e;\n" 2030 "const unsigned int& f;\n" 2031 "const unsigned g;\n" 2032 "Const unsigned h;", 2033 Style); 2034 2035 Style.PointerAlignment = FormatStyle::PAS_Left; 2036 Style.ReferenceAlignment = FormatStyle::RAS_Middle; 2037 verifyFormat("int* f1(int* a, int & b, int && c);", Style); 2038 verifyFormat("int & f2(int && c, int* a, int & b);", Style); 2039 verifyFormat("int && f3(int & b, int && c, int* a);", Style); 2040 verifyFormat("int* a = f1();", Style); 2041 verifyFormat("int & b = f2();", Style); 2042 verifyFormat("int && c = f3();", Style); 2043 verifyFormat("for (auto a = 0, b = 0; const auto & c : {1, 2, 3})", Style); 2044 verifyFormat("for (auto a = 0, b = 0; const int & c : {1, 2, 3})", Style); 2045 verifyFormat("for (auto a = 0, b = 0; const Foo & c : {1, 2, 3})", Style); 2046 verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style); 2047 verifyFormat("for (int a = 0, b++; const auto & c : {1, 2, 3})", Style); 2048 verifyFormat("for (int a = 0, b++; const int & c : {1, 2, 3})", Style); 2049 verifyFormat("for (int a = 0, b++; const Foo & c : {1, 2, 3})", Style); 2050 verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style); 2051 verifyFormat("for (auto x = 0; auto & c : {1, 2, 3})", Style); 2052 verifyFormat("for (auto x = 0; int & c : {1, 2, 3})", Style); 2053 verifyFormat("for (int x = 0; auto & c : {1, 2, 3})", Style); 2054 verifyFormat("for (int x = 0; int & c : {1, 2, 3})", Style); 2055 verifyFormat("for (f(); auto & c : {1, 2, 3})", Style); 2056 verifyFormat("for (f(); int & c : {1, 2, 3})", Style); 2057 2058 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 2059 verifyFormat("Const unsigned int* c;\n" 2060 "const unsigned int* d;\n" 2061 "Const unsigned int & e;\n" 2062 "const unsigned int & f;\n" 2063 "const unsigned && g;\n" 2064 "Const unsigned h;", 2065 Style); 2066 2067 Style.PointerAlignment = FormatStyle::PAS_Middle; 2068 Style.ReferenceAlignment = FormatStyle::RAS_Right; 2069 verifyFormat("int * f1(int * a, int &b, int &&c);", Style); 2070 verifyFormat("int &f2(int &&c, int * a, int &b);", Style); 2071 verifyFormat("int &&f3(int &b, int &&c, int * a);", Style); 2072 verifyFormat("int * a = f1();", Style); 2073 verifyFormat("int &b = f2();", Style); 2074 verifyFormat("int &&c = f3();", Style); 2075 verifyFormat("for (auto a = 0, b = 0; const Foo * c : {1, 2, 3})", Style); 2076 verifyFormat("for (int a = 0, b = 0; const Foo * c : {1, 2, 3})", Style); 2077 verifyFormat("for (int a = 0, b++; const Foo * c : {1, 2, 3})", Style); 2078 2079 // FIXME: we don't handle this yet, so output may be arbitrary until it's 2080 // specifically handled 2081 // verifyFormat("int Add2(BTree * &Root, char * szToAdd)", Style); 2082 } 2083 2084 TEST_F(FormatTest, FormatsForLoop) { 2085 verifyFormat( 2086 "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n" 2087 " ++VeryVeryLongLoopVariable)\n" 2088 " ;"); 2089 verifyFormat("for (;;)\n" 2090 " f();"); 2091 verifyFormat("for (;;) {\n}"); 2092 verifyFormat("for (;;) {\n" 2093 " f();\n" 2094 "}"); 2095 verifyFormat("for (int i = 0; (i < 10); ++i) {\n}"); 2096 2097 verifyFormat( 2098 "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n" 2099 " E = UnwrappedLines.end();\n" 2100 " I != E; ++I) {\n}"); 2101 2102 verifyFormat( 2103 "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n" 2104 " ++IIIII) {\n}"); 2105 verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n" 2106 " aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n" 2107 " aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}"); 2108 verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n" 2109 " I = FD->getDeclsInPrototypeScope().begin(),\n" 2110 " E = FD->getDeclsInPrototypeScope().end();\n" 2111 " I != E; ++I) {\n}"); 2112 verifyFormat("for (SmallVectorImpl<TemplateIdAnnotationn *>::iterator\n" 2113 " I = Container.begin(),\n" 2114 " E = Container.end();\n" 2115 " I != E; ++I) {\n}", 2116 getLLVMStyleWithColumns(76)); 2117 2118 verifyFormat( 2119 "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n" 2120 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n" 2121 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2122 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 2123 " ++aaaaaaaaaaa) {\n}"); 2124 verifyFormat("for (int i = 0; i < aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 2125 " bbbbbbbbbbbbbbbbbbbb < ccccccccccccccc;\n" 2126 " ++i) {\n}"); 2127 verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n" 2128 " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n" 2129 "}"); 2130 verifyFormat("for (some_namespace::SomeIterator iter( // force break\n" 2131 " aaaaaaaaaa);\n" 2132 " iter; ++iter) {\n" 2133 "}"); 2134 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2135 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 2136 " aaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbbbbbbb;\n" 2137 " ++aaaaaaaaaaaaaaaaaaaaaaaaaaa) {"); 2138 2139 // These should not be formatted as Objective-C for-in loops. 2140 verifyFormat("for (Foo *x = 0; x != in; x++) {\n}"); 2141 verifyFormat("Foo *x;\nfor (x = 0; x != in; x++) {\n}"); 2142 verifyFormat("Foo *x;\nfor (x in y) {\n}"); 2143 verifyFormat( 2144 "for (const Foo<Bar> &baz = in.value(); !baz.at_end(); ++baz) {\n}"); 2145 2146 FormatStyle NoBinPacking = getLLVMStyle(); 2147 NoBinPacking.BinPackParameters = false; 2148 verifyFormat("for (int aaaaaaaaaaa = 1;\n" 2149 " aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n" 2150 " aaaaaaaaaaaaaaaa,\n" 2151 " aaaaaaaaaaaaaaaa,\n" 2152 " aaaaaaaaaaaaaaaa);\n" 2153 " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n" 2154 "}", 2155 NoBinPacking); 2156 verifyFormat( 2157 "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n" 2158 " E = UnwrappedLines.end();\n" 2159 " I != E;\n" 2160 " ++I) {\n}", 2161 NoBinPacking); 2162 2163 FormatStyle AlignLeft = getLLVMStyle(); 2164 AlignLeft.PointerAlignment = FormatStyle::PAS_Left; 2165 verifyFormat("for (A* a = start; a < end; ++a, ++value) {\n}", AlignLeft); 2166 } 2167 2168 TEST_F(FormatTest, RangeBasedForLoops) { 2169 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 2170 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 2171 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n" 2172 " aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}"); 2173 verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n" 2174 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 2175 verifyFormat("for (aaaaaaaaa aaaaaaaaaaaaaaaaaaaaa :\n" 2176 " aaaaaaaaaaaa.aaaaaaaaaaaa().aaaaaaaaa().a()) {\n}"); 2177 } 2178 2179 TEST_F(FormatTest, ForEachLoops) { 2180 FormatStyle Style = getLLVMStyle(); 2181 EXPECT_EQ(Style.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 2182 EXPECT_EQ(Style.AllowShortLoopsOnASingleLine, false); 2183 verifyFormat("void f() {\n" 2184 " for (;;) {\n" 2185 " }\n" 2186 " foreach (Item *item, itemlist) {\n" 2187 " }\n" 2188 " Q_FOREACH (Item *item, itemlist) {\n" 2189 " }\n" 2190 " BOOST_FOREACH (Item *item, itemlist) {\n" 2191 " }\n" 2192 " UNKNOWN_FOREACH(Item * item, itemlist) {}\n" 2193 "}", 2194 Style); 2195 verifyFormat("void f() {\n" 2196 " for (;;)\n" 2197 " int j = 1;\n" 2198 " Q_FOREACH (int v, vec)\n" 2199 " v *= 2;\n" 2200 " for (;;) {\n" 2201 " int j = 1;\n" 2202 " }\n" 2203 " Q_FOREACH (int v, vec) {\n" 2204 " v *= 2;\n" 2205 " }\n" 2206 "}", 2207 Style); 2208 2209 FormatStyle ShortBlocks = getLLVMStyle(); 2210 ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 2211 EXPECT_EQ(ShortBlocks.AllowShortLoopsOnASingleLine, false); 2212 verifyFormat("void f() {\n" 2213 " for (;;)\n" 2214 " int j = 1;\n" 2215 " Q_FOREACH (int &v, vec)\n" 2216 " v *= 2;\n" 2217 " for (;;) {\n" 2218 " int j = 1;\n" 2219 " }\n" 2220 " Q_FOREACH (int &v, vec) {\n" 2221 " int j = 1;\n" 2222 " }\n" 2223 "}", 2224 ShortBlocks); 2225 2226 FormatStyle ShortLoops = getLLVMStyle(); 2227 ShortLoops.AllowShortLoopsOnASingleLine = true; 2228 EXPECT_EQ(ShortLoops.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 2229 verifyFormat("void f() {\n" 2230 " for (;;) int j = 1;\n" 2231 " Q_FOREACH (int &v, vec) int j = 1;\n" 2232 " for (;;) {\n" 2233 " int j = 1;\n" 2234 " }\n" 2235 " Q_FOREACH (int &v, vec) {\n" 2236 " int j = 1;\n" 2237 " }\n" 2238 "}", 2239 ShortLoops); 2240 2241 FormatStyle ShortBlocksAndLoops = getLLVMStyle(); 2242 ShortBlocksAndLoops.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 2243 ShortBlocksAndLoops.AllowShortLoopsOnASingleLine = true; 2244 verifyFormat("void f() {\n" 2245 " for (;;) int j = 1;\n" 2246 " Q_FOREACH (int &v, vec) int j = 1;\n" 2247 " for (;;) { int j = 1; }\n" 2248 " Q_FOREACH (int &v, vec) { int j = 1; }\n" 2249 "}", 2250 ShortBlocksAndLoops); 2251 2252 Style.SpaceBeforeParens = 2253 FormatStyle::SBPO_ControlStatementsExceptControlMacros; 2254 verifyFormat("void f() {\n" 2255 " for (;;) {\n" 2256 " }\n" 2257 " foreach(Item *item, itemlist) {\n" 2258 " }\n" 2259 " Q_FOREACH(Item *item, itemlist) {\n" 2260 " }\n" 2261 " BOOST_FOREACH(Item *item, itemlist) {\n" 2262 " }\n" 2263 " UNKNOWN_FOREACH(Item * item, itemlist) {}\n" 2264 "}", 2265 Style); 2266 2267 // As function-like macros. 2268 verifyFormat("#define foreach(x, y)\n" 2269 "#define Q_FOREACH(x, y)\n" 2270 "#define BOOST_FOREACH(x, y)\n" 2271 "#define UNKNOWN_FOREACH(x, y)\n"); 2272 2273 // Not as function-like macros. 2274 verifyFormat("#define foreach (x, y)\n" 2275 "#define Q_FOREACH (x, y)\n" 2276 "#define BOOST_FOREACH (x, y)\n" 2277 "#define UNKNOWN_FOREACH (x, y)\n"); 2278 2279 // handle microsoft non standard extension 2280 verifyFormat("for each (char c in x->MyStringProperty)"); 2281 } 2282 2283 TEST_F(FormatTest, FormatsWhileLoop) { 2284 verifyFormat("while (true) {\n}"); 2285 verifyFormat("while (true)\n" 2286 " f();"); 2287 verifyFormat("while () {\n}"); 2288 verifyFormat("while () {\n" 2289 " f();\n" 2290 "}"); 2291 } 2292 2293 TEST_F(FormatTest, FormatsDoWhile) { 2294 verifyFormat("do {\n" 2295 " do_something();\n" 2296 "} while (something());"); 2297 verifyFormat("do\n" 2298 " do_something();\n" 2299 "while (something());"); 2300 } 2301 2302 TEST_F(FormatTest, FormatsSwitchStatement) { 2303 verifyFormat("switch (x) {\n" 2304 "case 1:\n" 2305 " f();\n" 2306 " break;\n" 2307 "case kFoo:\n" 2308 "case ns::kBar:\n" 2309 "case kBaz:\n" 2310 " break;\n" 2311 "default:\n" 2312 " g();\n" 2313 " break;\n" 2314 "}"); 2315 verifyFormat("switch (x) {\n" 2316 "case 1: {\n" 2317 " f();\n" 2318 " break;\n" 2319 "}\n" 2320 "case 2: {\n" 2321 " break;\n" 2322 "}\n" 2323 "}"); 2324 verifyFormat("switch (x) {\n" 2325 "case 1: {\n" 2326 " f();\n" 2327 " {\n" 2328 " g();\n" 2329 " h();\n" 2330 " }\n" 2331 " break;\n" 2332 "}\n" 2333 "}"); 2334 verifyFormat("switch (x) {\n" 2335 "case 1: {\n" 2336 " f();\n" 2337 " if (foo) {\n" 2338 " g();\n" 2339 " h();\n" 2340 " }\n" 2341 " break;\n" 2342 "}\n" 2343 "}"); 2344 verifyFormat("switch (x) {\n" 2345 "case 1: {\n" 2346 " f();\n" 2347 " g();\n" 2348 "} break;\n" 2349 "}"); 2350 verifyFormat("switch (test)\n" 2351 " ;"); 2352 verifyFormat("switch (x) {\n" 2353 "default: {\n" 2354 " // Do nothing.\n" 2355 "}\n" 2356 "}"); 2357 verifyFormat("switch (x) {\n" 2358 "// comment\n" 2359 "// if 1, do f()\n" 2360 "case 1:\n" 2361 " f();\n" 2362 "}"); 2363 verifyFormat("switch (x) {\n" 2364 "case 1:\n" 2365 " // Do amazing stuff\n" 2366 " {\n" 2367 " f();\n" 2368 " g();\n" 2369 " }\n" 2370 " break;\n" 2371 "}"); 2372 verifyFormat("#define A \\\n" 2373 " switch (x) { \\\n" 2374 " case a: \\\n" 2375 " foo = b; \\\n" 2376 " }", 2377 getLLVMStyleWithColumns(20)); 2378 verifyFormat("#define OPERATION_CASE(name) \\\n" 2379 " case OP_name: \\\n" 2380 " return operations::Operation##name\n", 2381 getLLVMStyleWithColumns(40)); 2382 verifyFormat("switch (x) {\n" 2383 "case 1:;\n" 2384 "default:;\n" 2385 " int i;\n" 2386 "}"); 2387 2388 verifyGoogleFormat("switch (x) {\n" 2389 " case 1:\n" 2390 " f();\n" 2391 " break;\n" 2392 " case kFoo:\n" 2393 " case ns::kBar:\n" 2394 " case kBaz:\n" 2395 " break;\n" 2396 " default:\n" 2397 " g();\n" 2398 " break;\n" 2399 "}"); 2400 verifyGoogleFormat("switch (x) {\n" 2401 " case 1: {\n" 2402 " f();\n" 2403 " break;\n" 2404 " }\n" 2405 "}"); 2406 verifyGoogleFormat("switch (test)\n" 2407 " ;"); 2408 2409 verifyGoogleFormat("#define OPERATION_CASE(name) \\\n" 2410 " case OP_name: \\\n" 2411 " return operations::Operation##name\n"); 2412 verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n" 2413 " // Get the correction operation class.\n" 2414 " switch (OpCode) {\n" 2415 " CASE(Add);\n" 2416 " CASE(Subtract);\n" 2417 " default:\n" 2418 " return operations::Unknown;\n" 2419 " }\n" 2420 "#undef OPERATION_CASE\n" 2421 "}"); 2422 verifyFormat("DEBUG({\n" 2423 " switch (x) {\n" 2424 " case A:\n" 2425 " f();\n" 2426 " break;\n" 2427 " // fallthrough\n" 2428 " case B:\n" 2429 " g();\n" 2430 " break;\n" 2431 " }\n" 2432 "});"); 2433 EXPECT_EQ("DEBUG({\n" 2434 " switch (x) {\n" 2435 " case A:\n" 2436 " f();\n" 2437 " break;\n" 2438 " // On B:\n" 2439 " case B:\n" 2440 " g();\n" 2441 " break;\n" 2442 " }\n" 2443 "});", 2444 format("DEBUG({\n" 2445 " switch (x) {\n" 2446 " case A:\n" 2447 " f();\n" 2448 " break;\n" 2449 " // On B:\n" 2450 " case B:\n" 2451 " g();\n" 2452 " break;\n" 2453 " }\n" 2454 "});", 2455 getLLVMStyle())); 2456 EXPECT_EQ("switch (n) {\n" 2457 "case 0: {\n" 2458 " return false;\n" 2459 "}\n" 2460 "default: {\n" 2461 " return true;\n" 2462 "}\n" 2463 "}", 2464 format("switch (n)\n" 2465 "{\n" 2466 "case 0: {\n" 2467 " return false;\n" 2468 "}\n" 2469 "default: {\n" 2470 " return true;\n" 2471 "}\n" 2472 "}", 2473 getLLVMStyle())); 2474 verifyFormat("switch (a) {\n" 2475 "case (b):\n" 2476 " return;\n" 2477 "}"); 2478 2479 verifyFormat("switch (a) {\n" 2480 "case some_namespace::\n" 2481 " some_constant:\n" 2482 " return;\n" 2483 "}", 2484 getLLVMStyleWithColumns(34)); 2485 2486 FormatStyle Style = getLLVMStyle(); 2487 Style.IndentCaseLabels = true; 2488 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 2489 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2490 Style.BraceWrapping.AfterCaseLabel = true; 2491 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 2492 EXPECT_EQ("switch (n)\n" 2493 "{\n" 2494 " case 0:\n" 2495 " {\n" 2496 " return false;\n" 2497 " }\n" 2498 " default:\n" 2499 " {\n" 2500 " return true;\n" 2501 " }\n" 2502 "}", 2503 format("switch (n) {\n" 2504 " case 0: {\n" 2505 " return false;\n" 2506 " }\n" 2507 " default: {\n" 2508 " return true;\n" 2509 " }\n" 2510 "}", 2511 Style)); 2512 Style.BraceWrapping.AfterCaseLabel = false; 2513 EXPECT_EQ("switch (n)\n" 2514 "{\n" 2515 " case 0: {\n" 2516 " return false;\n" 2517 " }\n" 2518 " default: {\n" 2519 " return true;\n" 2520 " }\n" 2521 "}", 2522 format("switch (n) {\n" 2523 " case 0:\n" 2524 " {\n" 2525 " return false;\n" 2526 " }\n" 2527 " default:\n" 2528 " {\n" 2529 " return true;\n" 2530 " }\n" 2531 "}", 2532 Style)); 2533 Style.IndentCaseLabels = false; 2534 Style.IndentCaseBlocks = true; 2535 EXPECT_EQ("switch (n)\n" 2536 "{\n" 2537 "case 0:\n" 2538 " {\n" 2539 " return false;\n" 2540 " }\n" 2541 "case 1:\n" 2542 " break;\n" 2543 "default:\n" 2544 " {\n" 2545 " return true;\n" 2546 " }\n" 2547 "}", 2548 format("switch (n) {\n" 2549 "case 0: {\n" 2550 " return false;\n" 2551 "}\n" 2552 "case 1:\n" 2553 " break;\n" 2554 "default: {\n" 2555 " return true;\n" 2556 "}\n" 2557 "}", 2558 Style)); 2559 Style.IndentCaseLabels = true; 2560 Style.IndentCaseBlocks = true; 2561 EXPECT_EQ("switch (n)\n" 2562 "{\n" 2563 " case 0:\n" 2564 " {\n" 2565 " return false;\n" 2566 " }\n" 2567 " case 1:\n" 2568 " break;\n" 2569 " default:\n" 2570 " {\n" 2571 " return true;\n" 2572 " }\n" 2573 "}", 2574 format("switch (n) {\n" 2575 "case 0: {\n" 2576 " return false;\n" 2577 "}\n" 2578 "case 1:\n" 2579 " break;\n" 2580 "default: {\n" 2581 " return true;\n" 2582 "}\n" 2583 "}", 2584 Style)); 2585 } 2586 2587 TEST_F(FormatTest, CaseRanges) { 2588 verifyFormat("switch (x) {\n" 2589 "case 'A' ... 'Z':\n" 2590 "case 1 ... 5:\n" 2591 "case a ... b:\n" 2592 " break;\n" 2593 "}"); 2594 } 2595 2596 TEST_F(FormatTest, ShortEnums) { 2597 FormatStyle Style = getLLVMStyle(); 2598 Style.AllowShortEnumsOnASingleLine = true; 2599 verifyFormat("enum { A, B, C } ShortEnum1, ShortEnum2;", Style); 2600 verifyFormat("typedef enum { A, B, C } ShortEnum1, ShortEnum2;", Style); 2601 Style.AllowShortEnumsOnASingleLine = false; 2602 verifyFormat("enum {\n" 2603 " A,\n" 2604 " B,\n" 2605 " C\n" 2606 "} ShortEnum1, ShortEnum2;", 2607 Style); 2608 verifyFormat("typedef enum {\n" 2609 " A,\n" 2610 " B,\n" 2611 " C\n" 2612 "} ShortEnum1, ShortEnum2;", 2613 Style); 2614 verifyFormat("enum {\n" 2615 " A,\n" 2616 "} ShortEnum1, ShortEnum2;", 2617 Style); 2618 verifyFormat("typedef enum {\n" 2619 " A,\n" 2620 "} ShortEnum1, ShortEnum2;", 2621 Style); 2622 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2623 Style.BraceWrapping.AfterEnum = true; 2624 verifyFormat("enum\n" 2625 "{\n" 2626 " A,\n" 2627 " B,\n" 2628 " C\n" 2629 "} ShortEnum1, ShortEnum2;", 2630 Style); 2631 verifyFormat("typedef enum\n" 2632 "{\n" 2633 " A,\n" 2634 " B,\n" 2635 " C\n" 2636 "} ShortEnum1, ShortEnum2;", 2637 Style); 2638 } 2639 2640 TEST_F(FormatTest, ShortCaseLabels) { 2641 FormatStyle Style = getLLVMStyle(); 2642 Style.AllowShortCaseLabelsOnASingleLine = true; 2643 verifyFormat("switch (a) {\n" 2644 "case 1: x = 1; break;\n" 2645 "case 2: return;\n" 2646 "case 3:\n" 2647 "case 4:\n" 2648 "case 5: return;\n" 2649 "case 6: // comment\n" 2650 " return;\n" 2651 "case 7:\n" 2652 " // comment\n" 2653 " return;\n" 2654 "case 8:\n" 2655 " x = 8; // comment\n" 2656 " break;\n" 2657 "default: y = 1; break;\n" 2658 "}", 2659 Style); 2660 verifyFormat("switch (a) {\n" 2661 "case 0: return; // comment\n" 2662 "case 1: break; // comment\n" 2663 "case 2: return;\n" 2664 "// comment\n" 2665 "case 3: return;\n" 2666 "// comment 1\n" 2667 "// comment 2\n" 2668 "// comment 3\n" 2669 "case 4: break; /* comment */\n" 2670 "case 5:\n" 2671 " // comment\n" 2672 " break;\n" 2673 "case 6: /* comment */ x = 1; break;\n" 2674 "case 7: x = /* comment */ 1; break;\n" 2675 "case 8:\n" 2676 " x = 1; /* comment */\n" 2677 " break;\n" 2678 "case 9:\n" 2679 " break; // comment line 1\n" 2680 " // comment line 2\n" 2681 "}", 2682 Style); 2683 EXPECT_EQ("switch (a) {\n" 2684 "case 1:\n" 2685 " x = 8;\n" 2686 " // fall through\n" 2687 "case 2: x = 8;\n" 2688 "// comment\n" 2689 "case 3:\n" 2690 " return; /* comment line 1\n" 2691 " * comment line 2 */\n" 2692 "case 4: i = 8;\n" 2693 "// something else\n" 2694 "#if FOO\n" 2695 "case 5: break;\n" 2696 "#endif\n" 2697 "}", 2698 format("switch (a) {\n" 2699 "case 1: x = 8;\n" 2700 " // fall through\n" 2701 "case 2:\n" 2702 " x = 8;\n" 2703 "// comment\n" 2704 "case 3:\n" 2705 " return; /* comment line 1\n" 2706 " * comment line 2 */\n" 2707 "case 4:\n" 2708 " i = 8;\n" 2709 "// something else\n" 2710 "#if FOO\n" 2711 "case 5: break;\n" 2712 "#endif\n" 2713 "}", 2714 Style)); 2715 EXPECT_EQ("switch (a) {\n" 2716 "case 0:\n" 2717 " return; // long long long long long long long long long long " 2718 "long long comment\n" 2719 " // line\n" 2720 "}", 2721 format("switch (a) {\n" 2722 "case 0: return; // long long long long long long long long " 2723 "long long long long comment line\n" 2724 "}", 2725 Style)); 2726 EXPECT_EQ("switch (a) {\n" 2727 "case 0:\n" 2728 " return; /* long long long long long long long long long long " 2729 "long long comment\n" 2730 " line */\n" 2731 "}", 2732 format("switch (a) {\n" 2733 "case 0: return; /* long long long long long long long long " 2734 "long long long long comment line */\n" 2735 "}", 2736 Style)); 2737 verifyFormat("switch (a) {\n" 2738 "#if FOO\n" 2739 "case 0: return 0;\n" 2740 "#endif\n" 2741 "}", 2742 Style); 2743 verifyFormat("switch (a) {\n" 2744 "case 1: {\n" 2745 "}\n" 2746 "case 2: {\n" 2747 " return;\n" 2748 "}\n" 2749 "case 3: {\n" 2750 " x = 1;\n" 2751 " return;\n" 2752 "}\n" 2753 "case 4:\n" 2754 " if (x)\n" 2755 " return;\n" 2756 "}", 2757 Style); 2758 Style.ColumnLimit = 21; 2759 verifyFormat("switch (a) {\n" 2760 "case 1: x = 1; break;\n" 2761 "case 2: return;\n" 2762 "case 3:\n" 2763 "case 4:\n" 2764 "case 5: return;\n" 2765 "default:\n" 2766 " y = 1;\n" 2767 " break;\n" 2768 "}", 2769 Style); 2770 Style.ColumnLimit = 80; 2771 Style.AllowShortCaseLabelsOnASingleLine = false; 2772 Style.IndentCaseLabels = true; 2773 EXPECT_EQ("switch (n) {\n" 2774 " default /*comments*/:\n" 2775 " return true;\n" 2776 " case 0:\n" 2777 " return false;\n" 2778 "}", 2779 format("switch (n) {\n" 2780 "default/*comments*/:\n" 2781 " return true;\n" 2782 "case 0:\n" 2783 " return false;\n" 2784 "}", 2785 Style)); 2786 Style.AllowShortCaseLabelsOnASingleLine = true; 2787 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2788 Style.BraceWrapping.AfterCaseLabel = true; 2789 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 2790 EXPECT_EQ("switch (n)\n" 2791 "{\n" 2792 " case 0:\n" 2793 " {\n" 2794 " return false;\n" 2795 " }\n" 2796 " default:\n" 2797 " {\n" 2798 " return true;\n" 2799 " }\n" 2800 "}", 2801 format("switch (n) {\n" 2802 " case 0: {\n" 2803 " return false;\n" 2804 " }\n" 2805 " default:\n" 2806 " {\n" 2807 " return true;\n" 2808 " }\n" 2809 "}", 2810 Style)); 2811 } 2812 2813 TEST_F(FormatTest, FormatsLabels) { 2814 verifyFormat("void f() {\n" 2815 " some_code();\n" 2816 "test_label:\n" 2817 " some_other_code();\n" 2818 " {\n" 2819 " some_more_code();\n" 2820 " another_label:\n" 2821 " some_more_code();\n" 2822 " }\n" 2823 "}"); 2824 verifyFormat("{\n" 2825 " some_code();\n" 2826 "test_label:\n" 2827 " some_other_code();\n" 2828 "}"); 2829 verifyFormat("{\n" 2830 " some_code();\n" 2831 "test_label:;\n" 2832 " int i = 0;\n" 2833 "}"); 2834 FormatStyle Style = getLLVMStyle(); 2835 Style.IndentGotoLabels = false; 2836 verifyFormat("void f() {\n" 2837 " some_code();\n" 2838 "test_label:\n" 2839 " some_other_code();\n" 2840 " {\n" 2841 " some_more_code();\n" 2842 "another_label:\n" 2843 " some_more_code();\n" 2844 " }\n" 2845 "}", 2846 Style); 2847 verifyFormat("{\n" 2848 " some_code();\n" 2849 "test_label:\n" 2850 " some_other_code();\n" 2851 "}", 2852 Style); 2853 verifyFormat("{\n" 2854 " some_code();\n" 2855 "test_label:;\n" 2856 " int i = 0;\n" 2857 "}"); 2858 } 2859 2860 TEST_F(FormatTest, MultiLineControlStatements) { 2861 FormatStyle Style = getLLVMStyleWithColumns(20); 2862 Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom; 2863 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine; 2864 // Short lines should keep opening brace on same line. 2865 EXPECT_EQ("if (foo) {\n" 2866 " bar();\n" 2867 "}", 2868 format("if(foo){bar();}", Style)); 2869 EXPECT_EQ("if (foo) {\n" 2870 " bar();\n" 2871 "} else {\n" 2872 " baz();\n" 2873 "}", 2874 format("if(foo){bar();}else{baz();}", Style)); 2875 EXPECT_EQ("if (foo && bar) {\n" 2876 " baz();\n" 2877 "}", 2878 format("if(foo&&bar){baz();}", Style)); 2879 EXPECT_EQ("if (foo) {\n" 2880 " bar();\n" 2881 "} else if (baz) {\n" 2882 " quux();\n" 2883 "}", 2884 format("if(foo){bar();}else if(baz){quux();}", Style)); 2885 EXPECT_EQ( 2886 "if (foo) {\n" 2887 " bar();\n" 2888 "} else if (baz) {\n" 2889 " quux();\n" 2890 "} else {\n" 2891 " foobar();\n" 2892 "}", 2893 format("if(foo){bar();}else if(baz){quux();}else{foobar();}", Style)); 2894 EXPECT_EQ("for (;;) {\n" 2895 " foo();\n" 2896 "}", 2897 format("for(;;){foo();}")); 2898 EXPECT_EQ("while (1) {\n" 2899 " foo();\n" 2900 "}", 2901 format("while(1){foo();}", Style)); 2902 EXPECT_EQ("switch (foo) {\n" 2903 "case bar:\n" 2904 " return;\n" 2905 "}", 2906 format("switch(foo){case bar:return;}", Style)); 2907 EXPECT_EQ("try {\n" 2908 " foo();\n" 2909 "} catch (...) {\n" 2910 " bar();\n" 2911 "}", 2912 format("try{foo();}catch(...){bar();}", Style)); 2913 EXPECT_EQ("do {\n" 2914 " foo();\n" 2915 "} while (bar &&\n" 2916 " baz);", 2917 format("do{foo();}while(bar&&baz);", Style)); 2918 // Long lines should put opening brace on new line. 2919 EXPECT_EQ("if (foo && bar &&\n" 2920 " baz)\n" 2921 "{\n" 2922 " quux();\n" 2923 "}", 2924 format("if(foo&&bar&&baz){quux();}", Style)); 2925 EXPECT_EQ("if (foo && bar &&\n" 2926 " baz)\n" 2927 "{\n" 2928 " quux();\n" 2929 "}", 2930 format("if (foo && bar &&\n" 2931 " baz) {\n" 2932 " quux();\n" 2933 "}", 2934 Style)); 2935 EXPECT_EQ("if (foo) {\n" 2936 " bar();\n" 2937 "} else if (baz ||\n" 2938 " quux)\n" 2939 "{\n" 2940 " foobar();\n" 2941 "}", 2942 format("if(foo){bar();}else if(baz||quux){foobar();}", Style)); 2943 EXPECT_EQ( 2944 "if (foo) {\n" 2945 " bar();\n" 2946 "} else if (baz ||\n" 2947 " quux)\n" 2948 "{\n" 2949 " foobar();\n" 2950 "} else {\n" 2951 " barbaz();\n" 2952 "}", 2953 format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}", 2954 Style)); 2955 EXPECT_EQ("for (int i = 0;\n" 2956 " i < 10; ++i)\n" 2957 "{\n" 2958 " foo();\n" 2959 "}", 2960 format("for(int i=0;i<10;++i){foo();}", Style)); 2961 EXPECT_EQ("foreach (int i,\n" 2962 " list)\n" 2963 "{\n" 2964 " foo();\n" 2965 "}", 2966 format("foreach(int i, list){foo();}", Style)); 2967 Style.ColumnLimit = 2968 40; // to concentrate at brace wrapping, not line wrap due to column limit 2969 EXPECT_EQ("foreach (int i, list) {\n" 2970 " foo();\n" 2971 "}", 2972 format("foreach(int i, list){foo();}", Style)); 2973 Style.ColumnLimit = 2974 20; // to concentrate at brace wrapping, not line wrap due to column limit 2975 EXPECT_EQ("while (foo || bar ||\n" 2976 " baz)\n" 2977 "{\n" 2978 " quux();\n" 2979 "}", 2980 format("while(foo||bar||baz){quux();}", Style)); 2981 EXPECT_EQ("switch (\n" 2982 " foo = barbaz)\n" 2983 "{\n" 2984 "case quux:\n" 2985 " return;\n" 2986 "}", 2987 format("switch(foo=barbaz){case quux:return;}", Style)); 2988 EXPECT_EQ("try {\n" 2989 " foo();\n" 2990 "} catch (\n" 2991 " Exception &bar)\n" 2992 "{\n" 2993 " baz();\n" 2994 "}", 2995 format("try{foo();}catch(Exception&bar){baz();}", Style)); 2996 Style.ColumnLimit = 2997 40; // to concentrate at brace wrapping, not line wrap due to column limit 2998 EXPECT_EQ("try {\n" 2999 " foo();\n" 3000 "} catch (Exception &bar) {\n" 3001 " baz();\n" 3002 "}", 3003 format("try{foo();}catch(Exception&bar){baz();}", Style)); 3004 Style.ColumnLimit = 3005 20; // to concentrate at brace wrapping, not line wrap due to column limit 3006 3007 Style.BraceWrapping.BeforeElse = true; 3008 EXPECT_EQ( 3009 "if (foo) {\n" 3010 " bar();\n" 3011 "}\n" 3012 "else if (baz ||\n" 3013 " quux)\n" 3014 "{\n" 3015 " foobar();\n" 3016 "}\n" 3017 "else {\n" 3018 " barbaz();\n" 3019 "}", 3020 format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}", 3021 Style)); 3022 3023 Style.BraceWrapping.BeforeCatch = true; 3024 EXPECT_EQ("try {\n" 3025 " foo();\n" 3026 "}\n" 3027 "catch (...) {\n" 3028 " baz();\n" 3029 "}", 3030 format("try{foo();}catch(...){baz();}", Style)); 3031 3032 Style.BraceWrapping.AfterFunction = true; 3033 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine; 3034 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 3035 Style.ColumnLimit = 80; 3036 verifyFormat("void shortfunction() { bar(); }", Style); 3037 3038 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 3039 verifyFormat("void shortfunction()\n" 3040 "{\n" 3041 " bar();\n" 3042 "}", 3043 Style); 3044 } 3045 3046 TEST_F(FormatTest, BeforeWhile) { 3047 FormatStyle Style = getLLVMStyle(); 3048 Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom; 3049 3050 verifyFormat("do {\n" 3051 " foo();\n" 3052 "} while (1);", 3053 Style); 3054 Style.BraceWrapping.BeforeWhile = true; 3055 verifyFormat("do {\n" 3056 " foo();\n" 3057 "}\n" 3058 "while (1);", 3059 Style); 3060 } 3061 3062 //===----------------------------------------------------------------------===// 3063 // Tests for classes, namespaces, etc. 3064 //===----------------------------------------------------------------------===// 3065 3066 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) { 3067 verifyFormat("class A {};"); 3068 } 3069 3070 TEST_F(FormatTest, UnderstandsAccessSpecifiers) { 3071 verifyFormat("class A {\n" 3072 "public:\n" 3073 "public: // comment\n" 3074 "protected:\n" 3075 "private:\n" 3076 " void f() {}\n" 3077 "};"); 3078 verifyFormat("export class A {\n" 3079 "public:\n" 3080 "public: // comment\n" 3081 "protected:\n" 3082 "private:\n" 3083 " void f() {}\n" 3084 "};"); 3085 verifyGoogleFormat("class A {\n" 3086 " public:\n" 3087 " protected:\n" 3088 " private:\n" 3089 " void f() {}\n" 3090 "};"); 3091 verifyGoogleFormat("export class A {\n" 3092 " public:\n" 3093 " protected:\n" 3094 " private:\n" 3095 " void f() {}\n" 3096 "};"); 3097 verifyFormat("class A {\n" 3098 "public slots:\n" 3099 " void f1() {}\n" 3100 "public Q_SLOTS:\n" 3101 " void f2() {}\n" 3102 "protected slots:\n" 3103 " void f3() {}\n" 3104 "protected Q_SLOTS:\n" 3105 " void f4() {}\n" 3106 "private slots:\n" 3107 " void f5() {}\n" 3108 "private Q_SLOTS:\n" 3109 " void f6() {}\n" 3110 "signals:\n" 3111 " void g1();\n" 3112 "Q_SIGNALS:\n" 3113 " void g2();\n" 3114 "};"); 3115 3116 // Don't interpret 'signals' the wrong way. 3117 verifyFormat("signals.set();"); 3118 verifyFormat("for (Signals signals : f()) {\n}"); 3119 verifyFormat("{\n" 3120 " signals.set(); // This needs indentation.\n" 3121 "}"); 3122 verifyFormat("void f() {\n" 3123 "label:\n" 3124 " signals.baz();\n" 3125 "}"); 3126 } 3127 3128 TEST_F(FormatTest, SeparatesLogicalBlocks) { 3129 EXPECT_EQ("class A {\n" 3130 "public:\n" 3131 " void f();\n" 3132 "\n" 3133 "private:\n" 3134 " void g() {}\n" 3135 " // test\n" 3136 "protected:\n" 3137 " int h;\n" 3138 "};", 3139 format("class A {\n" 3140 "public:\n" 3141 "void f();\n" 3142 "private:\n" 3143 "void g() {}\n" 3144 "// test\n" 3145 "protected:\n" 3146 "int h;\n" 3147 "};")); 3148 EXPECT_EQ("class A {\n" 3149 "protected:\n" 3150 "public:\n" 3151 " void f();\n" 3152 "};", 3153 format("class A {\n" 3154 "protected:\n" 3155 "\n" 3156 "public:\n" 3157 "\n" 3158 " void f();\n" 3159 "};")); 3160 3161 // Even ensure proper spacing inside macros. 3162 EXPECT_EQ("#define B \\\n" 3163 " class A { \\\n" 3164 " protected: \\\n" 3165 " public: \\\n" 3166 " void f(); \\\n" 3167 " };", 3168 format("#define B \\\n" 3169 " class A { \\\n" 3170 " protected: \\\n" 3171 " \\\n" 3172 " public: \\\n" 3173 " \\\n" 3174 " void f(); \\\n" 3175 " };", 3176 getGoogleStyle())); 3177 // But don't remove empty lines after macros ending in access specifiers. 3178 EXPECT_EQ("#define A private:\n" 3179 "\n" 3180 "int i;", 3181 format("#define A private:\n" 3182 "\n" 3183 "int i;")); 3184 } 3185 3186 TEST_F(FormatTest, FormatsClasses) { 3187 verifyFormat("class A : public B {};"); 3188 verifyFormat("class A : public ::B {};"); 3189 3190 verifyFormat( 3191 "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3192 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};"); 3193 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n" 3194 " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3195 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};"); 3196 verifyFormat( 3197 "class A : public B, public C, public D, public E, public F {};"); 3198 verifyFormat("class AAAAAAAAAAAA : public B,\n" 3199 " public C,\n" 3200 " public D,\n" 3201 " public E,\n" 3202 " public F,\n" 3203 " public G {};"); 3204 3205 verifyFormat("class\n" 3206 " ReallyReallyLongClassName {\n" 3207 " int i;\n" 3208 "};", 3209 getLLVMStyleWithColumns(32)); 3210 verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n" 3211 " aaaaaaaaaaaaaaaa> {};"); 3212 verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n" 3213 " : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n" 3214 " aaaaaaaaaaaaaaaaaaaaaa> {};"); 3215 verifyFormat("template <class R, class C>\n" 3216 "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n" 3217 " : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};"); 3218 verifyFormat("class ::A::B {};"); 3219 } 3220 3221 TEST_F(FormatTest, BreakInheritanceStyle) { 3222 FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle(); 3223 StyleWithInheritanceBreakBeforeComma.BreakInheritanceList = 3224 FormatStyle::BILS_BeforeComma; 3225 verifyFormat("class MyClass : public X {};", 3226 StyleWithInheritanceBreakBeforeComma); 3227 verifyFormat("class MyClass\n" 3228 " : public X\n" 3229 " , public Y {};", 3230 StyleWithInheritanceBreakBeforeComma); 3231 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n" 3232 " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n" 3233 " , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};", 3234 StyleWithInheritanceBreakBeforeComma); 3235 verifyFormat("struct aaaaaaaaaaaaa\n" 3236 " : public aaaaaaaaaaaaaaaaaaa< // break\n" 3237 " aaaaaaaaaaaaaaaa> {};", 3238 StyleWithInheritanceBreakBeforeComma); 3239 3240 FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle(); 3241 StyleWithInheritanceBreakAfterColon.BreakInheritanceList = 3242 FormatStyle::BILS_AfterColon; 3243 verifyFormat("class MyClass : public X {};", 3244 StyleWithInheritanceBreakAfterColon); 3245 verifyFormat("class MyClass : public X, public Y {};", 3246 StyleWithInheritanceBreakAfterColon); 3247 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n" 3248 " public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3249 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};", 3250 StyleWithInheritanceBreakAfterColon); 3251 verifyFormat("struct aaaaaaaaaaaaa :\n" 3252 " public aaaaaaaaaaaaaaaaaaa< // break\n" 3253 " aaaaaaaaaaaaaaaa> {};", 3254 StyleWithInheritanceBreakAfterColon); 3255 3256 FormatStyle StyleWithInheritanceBreakAfterComma = getLLVMStyle(); 3257 StyleWithInheritanceBreakAfterComma.BreakInheritanceList = 3258 FormatStyle::BILS_AfterComma; 3259 verifyFormat("class MyClass : public X {};", 3260 StyleWithInheritanceBreakAfterComma); 3261 verifyFormat("class MyClass : public X,\n" 3262 " public Y {};", 3263 StyleWithInheritanceBreakAfterComma); 3264 verifyFormat( 3265 "class AAAAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3266 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC " 3267 "{};", 3268 StyleWithInheritanceBreakAfterComma); 3269 verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n" 3270 " aaaaaaaaaaaaaaaa> {};", 3271 StyleWithInheritanceBreakAfterComma); 3272 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n" 3273 " : public OnceBreak,\n" 3274 " public AlwaysBreak,\n" 3275 " EvenBasesFitInOneLine {};", 3276 StyleWithInheritanceBreakAfterComma); 3277 } 3278 3279 TEST_F(FormatTest, FormatsVariableDeclarationsAfterStructOrClass) { 3280 verifyFormat("class A {\n} a, b;"); 3281 verifyFormat("struct A {\n} a, b;"); 3282 verifyFormat("union A {\n} a;"); 3283 } 3284 3285 TEST_F(FormatTest, FormatsEnum) { 3286 verifyFormat("enum {\n" 3287 " Zero,\n" 3288 " One = 1,\n" 3289 " Two = One + 1,\n" 3290 " Three = (One + Two),\n" 3291 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3292 " Five = (One, Two, Three, Four, 5)\n" 3293 "};"); 3294 verifyGoogleFormat("enum {\n" 3295 " Zero,\n" 3296 " One = 1,\n" 3297 " Two = One + 1,\n" 3298 " Three = (One + Two),\n" 3299 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3300 " Five = (One, Two, Three, Four, 5)\n" 3301 "};"); 3302 verifyFormat("enum Enum {};"); 3303 verifyFormat("enum {};"); 3304 verifyFormat("enum X E {} d;"); 3305 verifyFormat("enum __attribute__((...)) E {} d;"); 3306 verifyFormat("enum __declspec__((...)) E {} d;"); 3307 verifyFormat("enum {\n" 3308 " Bar = Foo<int, int>::value\n" 3309 "};", 3310 getLLVMStyleWithColumns(30)); 3311 3312 verifyFormat("enum ShortEnum { A, B, C };"); 3313 verifyGoogleFormat("enum ShortEnum { A, B, C };"); 3314 3315 EXPECT_EQ("enum KeepEmptyLines {\n" 3316 " ONE,\n" 3317 "\n" 3318 " TWO,\n" 3319 "\n" 3320 " THREE\n" 3321 "}", 3322 format("enum KeepEmptyLines {\n" 3323 " ONE,\n" 3324 "\n" 3325 " TWO,\n" 3326 "\n" 3327 "\n" 3328 " THREE\n" 3329 "}")); 3330 verifyFormat("enum E { // comment\n" 3331 " ONE,\n" 3332 " TWO\n" 3333 "};\n" 3334 "int i;"); 3335 3336 FormatStyle EightIndent = getLLVMStyle(); 3337 EightIndent.IndentWidth = 8; 3338 verifyFormat("enum {\n" 3339 " VOID,\n" 3340 " CHAR,\n" 3341 " SHORT,\n" 3342 " INT,\n" 3343 " LONG,\n" 3344 " SIGNED,\n" 3345 " UNSIGNED,\n" 3346 " BOOL,\n" 3347 " FLOAT,\n" 3348 " DOUBLE,\n" 3349 " COMPLEX\n" 3350 "};", 3351 EightIndent); 3352 3353 // Not enums. 3354 verifyFormat("enum X f() {\n" 3355 " a();\n" 3356 " return 42;\n" 3357 "}"); 3358 verifyFormat("enum X Type::f() {\n" 3359 " a();\n" 3360 " return 42;\n" 3361 "}"); 3362 verifyFormat("enum ::X f() {\n" 3363 " a();\n" 3364 " return 42;\n" 3365 "}"); 3366 verifyFormat("enum ns::X f() {\n" 3367 " a();\n" 3368 " return 42;\n" 3369 "}"); 3370 } 3371 3372 TEST_F(FormatTest, FormatsEnumsWithErrors) { 3373 verifyFormat("enum Type {\n" 3374 " One = 0; // These semicolons should be commas.\n" 3375 " Two = 1;\n" 3376 "};"); 3377 verifyFormat("namespace n {\n" 3378 "enum Type {\n" 3379 " One,\n" 3380 " Two, // missing };\n" 3381 " int i;\n" 3382 "}\n" 3383 "void g() {}"); 3384 } 3385 3386 TEST_F(FormatTest, FormatsEnumStruct) { 3387 verifyFormat("enum struct {\n" 3388 " Zero,\n" 3389 " One = 1,\n" 3390 " Two = One + 1,\n" 3391 " Three = (One + Two),\n" 3392 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3393 " Five = (One, Two, Three, Four, 5)\n" 3394 "};"); 3395 verifyFormat("enum struct Enum {};"); 3396 verifyFormat("enum struct {};"); 3397 verifyFormat("enum struct X E {} d;"); 3398 verifyFormat("enum struct __attribute__((...)) E {} d;"); 3399 verifyFormat("enum struct __declspec__((...)) E {} d;"); 3400 verifyFormat("enum struct X f() {\n a();\n return 42;\n}"); 3401 } 3402 3403 TEST_F(FormatTest, FormatsEnumClass) { 3404 verifyFormat("enum class {\n" 3405 " Zero,\n" 3406 " One = 1,\n" 3407 " Two = One + 1,\n" 3408 " Three = (One + Two),\n" 3409 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3410 " Five = (One, Two, Three, Four, 5)\n" 3411 "};"); 3412 verifyFormat("enum class Enum {};"); 3413 verifyFormat("enum class {};"); 3414 verifyFormat("enum class X E {} d;"); 3415 verifyFormat("enum class __attribute__((...)) E {} d;"); 3416 verifyFormat("enum class __declspec__((...)) E {} d;"); 3417 verifyFormat("enum class X f() {\n a();\n return 42;\n}"); 3418 } 3419 3420 TEST_F(FormatTest, FormatsEnumTypes) { 3421 verifyFormat("enum X : int {\n" 3422 " A, // Force multiple lines.\n" 3423 " B\n" 3424 "};"); 3425 verifyFormat("enum X : int { A, B };"); 3426 verifyFormat("enum X : std::uint32_t { A, B };"); 3427 } 3428 3429 TEST_F(FormatTest, FormatsTypedefEnum) { 3430 FormatStyle Style = getLLVMStyleWithColumns(40); 3431 verifyFormat("typedef enum {} EmptyEnum;"); 3432 verifyFormat("typedef enum { A, B, C } ShortEnum;"); 3433 verifyFormat("typedef enum {\n" 3434 " ZERO = 0,\n" 3435 " ONE = 1,\n" 3436 " TWO = 2,\n" 3437 " THREE = 3\n" 3438 "} LongEnum;", 3439 Style); 3440 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 3441 Style.BraceWrapping.AfterEnum = true; 3442 verifyFormat("typedef enum {} EmptyEnum;"); 3443 verifyFormat("typedef enum { A, B, C } ShortEnum;"); 3444 verifyFormat("typedef enum\n" 3445 "{\n" 3446 " ZERO = 0,\n" 3447 " ONE = 1,\n" 3448 " TWO = 2,\n" 3449 " THREE = 3\n" 3450 "} LongEnum;", 3451 Style); 3452 } 3453 3454 TEST_F(FormatTest, FormatsNSEnums) { 3455 verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }"); 3456 verifyGoogleFormat( 3457 "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }"); 3458 verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n" 3459 " // Information about someDecentlyLongValue.\n" 3460 " someDecentlyLongValue,\n" 3461 " // Information about anotherDecentlyLongValue.\n" 3462 " anotherDecentlyLongValue,\n" 3463 " // Information about aThirdDecentlyLongValue.\n" 3464 " aThirdDecentlyLongValue\n" 3465 "};"); 3466 verifyGoogleFormat("typedef NS_CLOSED_ENUM(NSInteger, MyType) {\n" 3467 " // Information about someDecentlyLongValue.\n" 3468 " someDecentlyLongValue,\n" 3469 " // Information about anotherDecentlyLongValue.\n" 3470 " anotherDecentlyLongValue,\n" 3471 " // Information about aThirdDecentlyLongValue.\n" 3472 " aThirdDecentlyLongValue\n" 3473 "};"); 3474 verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n" 3475 " a = 1,\n" 3476 " b = 2,\n" 3477 " c = 3,\n" 3478 "};"); 3479 verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n" 3480 " a = 1,\n" 3481 " b = 2,\n" 3482 " c = 3,\n" 3483 "};"); 3484 verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n" 3485 " a = 1,\n" 3486 " b = 2,\n" 3487 " c = 3,\n" 3488 "};"); 3489 verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n" 3490 " a = 1,\n" 3491 " b = 2,\n" 3492 " c = 3,\n" 3493 "};"); 3494 } 3495 3496 TEST_F(FormatTest, FormatsBitfields) { 3497 verifyFormat("struct Bitfields {\n" 3498 " unsigned sClass : 8;\n" 3499 " unsigned ValueKind : 2;\n" 3500 "};"); 3501 verifyFormat("struct A {\n" 3502 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n" 3503 " bbbbbbbbbbbbbbbbbbbbbbbbb;\n" 3504 "};"); 3505 verifyFormat("struct MyStruct {\n" 3506 " uchar data;\n" 3507 " uchar : 8;\n" 3508 " uchar : 8;\n" 3509 " uchar other;\n" 3510 "};"); 3511 FormatStyle Style = getLLVMStyle(); 3512 Style.BitFieldColonSpacing = FormatStyle::BFCS_None; 3513 verifyFormat("struct Bitfields {\n" 3514 " unsigned sClass:8;\n" 3515 " unsigned ValueKind:2;\n" 3516 " uchar other;\n" 3517 "};", 3518 Style); 3519 verifyFormat("struct A {\n" 3520 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:1,\n" 3521 " bbbbbbbbbbbbbbbbbbbbbbbbb:2;\n" 3522 "};", 3523 Style); 3524 Style.BitFieldColonSpacing = FormatStyle::BFCS_Before; 3525 verifyFormat("struct Bitfields {\n" 3526 " unsigned sClass :8;\n" 3527 " unsigned ValueKind :2;\n" 3528 " uchar other;\n" 3529 "};", 3530 Style); 3531 Style.BitFieldColonSpacing = FormatStyle::BFCS_After; 3532 verifyFormat("struct Bitfields {\n" 3533 " unsigned sClass: 8;\n" 3534 " unsigned ValueKind: 2;\n" 3535 " uchar other;\n" 3536 "};", 3537 Style); 3538 } 3539 3540 TEST_F(FormatTest, FormatsNamespaces) { 3541 FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle(); 3542 LLVMWithNoNamespaceFix.FixNamespaceComments = false; 3543 3544 verifyFormat("namespace some_namespace {\n" 3545 "class A {};\n" 3546 "void f() { f(); }\n" 3547 "}", 3548 LLVMWithNoNamespaceFix); 3549 verifyFormat("namespace N::inline D {\n" 3550 "class A {};\n" 3551 "void f() { f(); }\n" 3552 "}", 3553 LLVMWithNoNamespaceFix); 3554 verifyFormat("namespace N::inline D::E {\n" 3555 "class A {};\n" 3556 "void f() { f(); }\n" 3557 "}", 3558 LLVMWithNoNamespaceFix); 3559 verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n" 3560 "class A {};\n" 3561 "void f() { f(); }\n" 3562 "}", 3563 LLVMWithNoNamespaceFix); 3564 verifyFormat("/* something */ namespace some_namespace {\n" 3565 "class A {};\n" 3566 "void f() { f(); }\n" 3567 "}", 3568 LLVMWithNoNamespaceFix); 3569 verifyFormat("namespace {\n" 3570 "class A {};\n" 3571 "void f() { f(); }\n" 3572 "}", 3573 LLVMWithNoNamespaceFix); 3574 verifyFormat("/* something */ namespace {\n" 3575 "class A {};\n" 3576 "void f() { f(); }\n" 3577 "}", 3578 LLVMWithNoNamespaceFix); 3579 verifyFormat("inline namespace X {\n" 3580 "class A {};\n" 3581 "void f() { f(); }\n" 3582 "}", 3583 LLVMWithNoNamespaceFix); 3584 verifyFormat("/* something */ inline namespace X {\n" 3585 "class A {};\n" 3586 "void f() { f(); }\n" 3587 "}", 3588 LLVMWithNoNamespaceFix); 3589 verifyFormat("export namespace X {\n" 3590 "class A {};\n" 3591 "void f() { f(); }\n" 3592 "}", 3593 LLVMWithNoNamespaceFix); 3594 verifyFormat("using namespace some_namespace;\n" 3595 "class A {};\n" 3596 "void f() { f(); }", 3597 LLVMWithNoNamespaceFix); 3598 3599 // This code is more common than we thought; if we 3600 // layout this correctly the semicolon will go into 3601 // its own line, which is undesirable. 3602 verifyFormat("namespace {};", LLVMWithNoNamespaceFix); 3603 verifyFormat("namespace {\n" 3604 "class A {};\n" 3605 "};", 3606 LLVMWithNoNamespaceFix); 3607 3608 verifyFormat("namespace {\n" 3609 "int SomeVariable = 0; // comment\n" 3610 "} // namespace", 3611 LLVMWithNoNamespaceFix); 3612 EXPECT_EQ("#ifndef HEADER_GUARD\n" 3613 "#define HEADER_GUARD\n" 3614 "namespace my_namespace {\n" 3615 "int i;\n" 3616 "} // my_namespace\n" 3617 "#endif // HEADER_GUARD", 3618 format("#ifndef HEADER_GUARD\n" 3619 " #define HEADER_GUARD\n" 3620 " namespace my_namespace {\n" 3621 "int i;\n" 3622 "} // my_namespace\n" 3623 "#endif // HEADER_GUARD", 3624 LLVMWithNoNamespaceFix)); 3625 3626 EXPECT_EQ("namespace A::B {\n" 3627 "class C {};\n" 3628 "}", 3629 format("namespace A::B {\n" 3630 "class C {};\n" 3631 "}", 3632 LLVMWithNoNamespaceFix)); 3633 3634 FormatStyle Style = getLLVMStyle(); 3635 Style.NamespaceIndentation = FormatStyle::NI_All; 3636 EXPECT_EQ("namespace out {\n" 3637 " int i;\n" 3638 " namespace in {\n" 3639 " int i;\n" 3640 " } // namespace in\n" 3641 "} // namespace out", 3642 format("namespace out {\n" 3643 "int i;\n" 3644 "namespace in {\n" 3645 "int i;\n" 3646 "} // namespace in\n" 3647 "} // namespace out", 3648 Style)); 3649 3650 FormatStyle ShortInlineFunctions = getLLVMStyle(); 3651 ShortInlineFunctions.NamespaceIndentation = FormatStyle::NI_All; 3652 ShortInlineFunctions.AllowShortFunctionsOnASingleLine = 3653 FormatStyle::SFS_Inline; 3654 verifyFormat("namespace {\n" 3655 " void f() {\n" 3656 " return;\n" 3657 " }\n" 3658 "} // namespace\n", 3659 ShortInlineFunctions); 3660 verifyFormat("namespace {\n" 3661 " int some_int;\n" 3662 " void f() {\n" 3663 " return;\n" 3664 " }\n" 3665 "} // namespace\n", 3666 ShortInlineFunctions); 3667 verifyFormat("namespace interface {\n" 3668 " void f() {\n" 3669 " return;\n" 3670 " }\n" 3671 "} // namespace interface\n", 3672 ShortInlineFunctions); 3673 verifyFormat("namespace {\n" 3674 " class X {\n" 3675 " void f() { return; }\n" 3676 " };\n" 3677 "} // namespace\n", 3678 ShortInlineFunctions); 3679 verifyFormat("namespace {\n" 3680 " struct X {\n" 3681 " void f() { return; }\n" 3682 " };\n" 3683 "} // namespace\n", 3684 ShortInlineFunctions); 3685 verifyFormat("namespace {\n" 3686 " union X {\n" 3687 " void f() { return; }\n" 3688 " };\n" 3689 "} // namespace\n", 3690 ShortInlineFunctions); 3691 verifyFormat("extern \"C\" {\n" 3692 "void f() {\n" 3693 " return;\n" 3694 "}\n" 3695 "} // namespace\n", 3696 ShortInlineFunctions); 3697 verifyFormat("namespace {\n" 3698 " class X {\n" 3699 " void f() { return; }\n" 3700 " } x;\n" 3701 "} // namespace\n", 3702 ShortInlineFunctions); 3703 verifyFormat("namespace {\n" 3704 " [[nodiscard]] class X {\n" 3705 " void f() { return; }\n" 3706 " };\n" 3707 "} // namespace\n", 3708 ShortInlineFunctions); 3709 verifyFormat("namespace {\n" 3710 " static class X {\n" 3711 " void f() { return; }\n" 3712 " } x;\n" 3713 "} // namespace\n", 3714 ShortInlineFunctions); 3715 verifyFormat("namespace {\n" 3716 " constexpr class X {\n" 3717 " void f() { return; }\n" 3718 " } x;\n" 3719 "} // namespace\n", 3720 ShortInlineFunctions); 3721 3722 ShortInlineFunctions.IndentExternBlock = FormatStyle::IEBS_Indent; 3723 verifyFormat("extern \"C\" {\n" 3724 " void f() {\n" 3725 " return;\n" 3726 " }\n" 3727 "} // namespace\n", 3728 ShortInlineFunctions); 3729 3730 Style.NamespaceIndentation = FormatStyle::NI_Inner; 3731 EXPECT_EQ("namespace out {\n" 3732 "int i;\n" 3733 "namespace in {\n" 3734 " int i;\n" 3735 "} // namespace in\n" 3736 "} // namespace out", 3737 format("namespace out {\n" 3738 "int i;\n" 3739 "namespace in {\n" 3740 "int i;\n" 3741 "} // namespace in\n" 3742 "} // namespace out", 3743 Style)); 3744 3745 Style.NamespaceIndentation = FormatStyle::NI_None; 3746 verifyFormat("template <class T>\n" 3747 "concept a_concept = X<>;\n" 3748 "namespace B {\n" 3749 "struct b_struct {};\n" 3750 "} // namespace B\n", 3751 Style); 3752 verifyFormat("template <int I> constexpr void foo requires(I == 42) {}\n" 3753 "namespace ns {\n" 3754 "void foo() {}\n" 3755 "} // namespace ns\n", 3756 Style); 3757 } 3758 3759 TEST_F(FormatTest, NamespaceMacros) { 3760 FormatStyle Style = getLLVMStyle(); 3761 Style.NamespaceMacros.push_back("TESTSUITE"); 3762 3763 verifyFormat("TESTSUITE(A) {\n" 3764 "int foo();\n" 3765 "} // TESTSUITE(A)", 3766 Style); 3767 3768 verifyFormat("TESTSUITE(A, B) {\n" 3769 "int foo();\n" 3770 "} // TESTSUITE(A)", 3771 Style); 3772 3773 // Properly indent according to NamespaceIndentation style 3774 Style.NamespaceIndentation = FormatStyle::NI_All; 3775 verifyFormat("TESTSUITE(A) {\n" 3776 " int foo();\n" 3777 "} // TESTSUITE(A)", 3778 Style); 3779 verifyFormat("TESTSUITE(A) {\n" 3780 " namespace B {\n" 3781 " int foo();\n" 3782 " } // namespace B\n" 3783 "} // TESTSUITE(A)", 3784 Style); 3785 verifyFormat("namespace A {\n" 3786 " TESTSUITE(B) {\n" 3787 " int foo();\n" 3788 " } // TESTSUITE(B)\n" 3789 "} // namespace A", 3790 Style); 3791 3792 Style.NamespaceIndentation = FormatStyle::NI_Inner; 3793 verifyFormat("TESTSUITE(A) {\n" 3794 "TESTSUITE(B) {\n" 3795 " int foo();\n" 3796 "} // TESTSUITE(B)\n" 3797 "} // TESTSUITE(A)", 3798 Style); 3799 verifyFormat("TESTSUITE(A) {\n" 3800 "namespace B {\n" 3801 " int foo();\n" 3802 "} // namespace B\n" 3803 "} // TESTSUITE(A)", 3804 Style); 3805 verifyFormat("namespace A {\n" 3806 "TESTSUITE(B) {\n" 3807 " int foo();\n" 3808 "} // TESTSUITE(B)\n" 3809 "} // namespace A", 3810 Style); 3811 3812 // Properly merge namespace-macros blocks in CompactNamespaces mode 3813 Style.NamespaceIndentation = FormatStyle::NI_None; 3814 Style.CompactNamespaces = true; 3815 verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n" 3816 "}} // TESTSUITE(A::B)", 3817 Style); 3818 3819 EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n" 3820 "}} // TESTSUITE(out::in)", 3821 format("TESTSUITE(out) {\n" 3822 "TESTSUITE(in) {\n" 3823 "} // TESTSUITE(in)\n" 3824 "} // TESTSUITE(out)", 3825 Style)); 3826 3827 EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n" 3828 "}} // TESTSUITE(out::in)", 3829 format("TESTSUITE(out) {\n" 3830 "TESTSUITE(in) {\n" 3831 "} // TESTSUITE(in)\n" 3832 "} // TESTSUITE(out)", 3833 Style)); 3834 3835 // Do not merge different namespaces/macros 3836 EXPECT_EQ("namespace out {\n" 3837 "TESTSUITE(in) {\n" 3838 "} // TESTSUITE(in)\n" 3839 "} // namespace out", 3840 format("namespace out {\n" 3841 "TESTSUITE(in) {\n" 3842 "} // TESTSUITE(in)\n" 3843 "} // namespace out", 3844 Style)); 3845 EXPECT_EQ("TESTSUITE(out) {\n" 3846 "namespace in {\n" 3847 "} // namespace in\n" 3848 "} // TESTSUITE(out)", 3849 format("TESTSUITE(out) {\n" 3850 "namespace in {\n" 3851 "} // namespace in\n" 3852 "} // TESTSUITE(out)", 3853 Style)); 3854 Style.NamespaceMacros.push_back("FOOBAR"); 3855 EXPECT_EQ("TESTSUITE(out) {\n" 3856 "FOOBAR(in) {\n" 3857 "} // FOOBAR(in)\n" 3858 "} // TESTSUITE(out)", 3859 format("TESTSUITE(out) {\n" 3860 "FOOBAR(in) {\n" 3861 "} // FOOBAR(in)\n" 3862 "} // TESTSUITE(out)", 3863 Style)); 3864 } 3865 3866 TEST_F(FormatTest, FormatsCompactNamespaces) { 3867 FormatStyle Style = getLLVMStyle(); 3868 Style.CompactNamespaces = true; 3869 Style.NamespaceMacros.push_back("TESTSUITE"); 3870 3871 verifyFormat("namespace A { namespace B {\n" 3872 "}} // namespace A::B", 3873 Style); 3874 3875 EXPECT_EQ("namespace out { namespace in {\n" 3876 "}} // namespace out::in", 3877 format("namespace out {\n" 3878 "namespace in {\n" 3879 "} // namespace in\n" 3880 "} // namespace out", 3881 Style)); 3882 3883 // Only namespaces which have both consecutive opening and end get compacted 3884 EXPECT_EQ("namespace out {\n" 3885 "namespace in1 {\n" 3886 "} // namespace in1\n" 3887 "namespace in2 {\n" 3888 "} // namespace in2\n" 3889 "} // namespace out", 3890 format("namespace out {\n" 3891 "namespace in1 {\n" 3892 "} // namespace in1\n" 3893 "namespace in2 {\n" 3894 "} // namespace in2\n" 3895 "} // namespace out", 3896 Style)); 3897 3898 EXPECT_EQ("namespace out {\n" 3899 "int i;\n" 3900 "namespace in {\n" 3901 "int j;\n" 3902 "} // namespace in\n" 3903 "int k;\n" 3904 "} // namespace out", 3905 format("namespace out { int i;\n" 3906 "namespace in { int j; } // namespace in\n" 3907 "int k; } // namespace out", 3908 Style)); 3909 3910 EXPECT_EQ("namespace A { namespace B { namespace C {\n" 3911 "}}} // namespace A::B::C\n", 3912 format("namespace A { namespace B {\n" 3913 "namespace C {\n" 3914 "}} // namespace B::C\n" 3915 "} // namespace A\n", 3916 Style)); 3917 3918 Style.ColumnLimit = 40; 3919 EXPECT_EQ("namespace aaaaaaaaaa {\n" 3920 "namespace bbbbbbbbbb {\n" 3921 "}} // namespace aaaaaaaaaa::bbbbbbbbbb", 3922 format("namespace aaaaaaaaaa {\n" 3923 "namespace bbbbbbbbbb {\n" 3924 "} // namespace bbbbbbbbbb\n" 3925 "} // namespace aaaaaaaaaa", 3926 Style)); 3927 3928 EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n" 3929 "namespace cccccc {\n" 3930 "}}} // namespace aaaaaa::bbbbbb::cccccc", 3931 format("namespace aaaaaa {\n" 3932 "namespace bbbbbb {\n" 3933 "namespace cccccc {\n" 3934 "} // namespace cccccc\n" 3935 "} // namespace bbbbbb\n" 3936 "} // namespace aaaaaa", 3937 Style)); 3938 Style.ColumnLimit = 80; 3939 3940 // Extra semicolon after 'inner' closing brace prevents merging 3941 EXPECT_EQ("namespace out { namespace in {\n" 3942 "}; } // namespace out::in", 3943 format("namespace out {\n" 3944 "namespace in {\n" 3945 "}; // namespace in\n" 3946 "} // namespace out", 3947 Style)); 3948 3949 // Extra semicolon after 'outer' closing brace is conserved 3950 EXPECT_EQ("namespace out { namespace in {\n" 3951 "}}; // namespace out::in", 3952 format("namespace out {\n" 3953 "namespace in {\n" 3954 "} // namespace in\n" 3955 "}; // namespace out", 3956 Style)); 3957 3958 Style.NamespaceIndentation = FormatStyle::NI_All; 3959 EXPECT_EQ("namespace out { namespace in {\n" 3960 " int i;\n" 3961 "}} // namespace out::in", 3962 format("namespace out {\n" 3963 "namespace in {\n" 3964 "int i;\n" 3965 "} // namespace in\n" 3966 "} // namespace out", 3967 Style)); 3968 EXPECT_EQ("namespace out { namespace mid {\n" 3969 " namespace in {\n" 3970 " int j;\n" 3971 " } // namespace in\n" 3972 " int k;\n" 3973 "}} // namespace out::mid", 3974 format("namespace out { namespace mid {\n" 3975 "namespace in { int j; } // namespace in\n" 3976 "int k; }} // namespace out::mid", 3977 Style)); 3978 3979 Style.NamespaceIndentation = FormatStyle::NI_Inner; 3980 EXPECT_EQ("namespace out { namespace in {\n" 3981 " int i;\n" 3982 "}} // namespace out::in", 3983 format("namespace out {\n" 3984 "namespace in {\n" 3985 "int i;\n" 3986 "} // namespace in\n" 3987 "} // namespace out", 3988 Style)); 3989 EXPECT_EQ("namespace out { namespace mid { namespace in {\n" 3990 " int i;\n" 3991 "}}} // namespace out::mid::in", 3992 format("namespace out {\n" 3993 "namespace mid {\n" 3994 "namespace in {\n" 3995 "int i;\n" 3996 "} // namespace in\n" 3997 "} // namespace mid\n" 3998 "} // namespace out", 3999 Style)); 4000 4001 Style.CompactNamespaces = true; 4002 Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 4003 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4004 Style.BraceWrapping.BeforeLambdaBody = true; 4005 verifyFormat("namespace out { namespace in {\n" 4006 "}} // namespace out::in", 4007 Style); 4008 EXPECT_EQ("namespace out { namespace in {\n" 4009 "}} // namespace out::in", 4010 format("namespace out {\n" 4011 "namespace in {\n" 4012 "} // namespace in\n" 4013 "} // namespace out", 4014 Style)); 4015 } 4016 4017 TEST_F(FormatTest, FormatsExternC) { 4018 verifyFormat("extern \"C\" {\nint a;"); 4019 verifyFormat("extern \"C\" {}"); 4020 verifyFormat("extern \"C\" {\n" 4021 "int foo();\n" 4022 "}"); 4023 verifyFormat("extern \"C\" int foo() {}"); 4024 verifyFormat("extern \"C\" int foo();"); 4025 verifyFormat("extern \"C\" int foo() {\n" 4026 " int i = 42;\n" 4027 " return i;\n" 4028 "}"); 4029 4030 FormatStyle Style = getLLVMStyle(); 4031 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4032 Style.BraceWrapping.AfterFunction = true; 4033 verifyFormat("extern \"C\" int foo() {}", Style); 4034 verifyFormat("extern \"C\" int foo();", Style); 4035 verifyFormat("extern \"C\" int foo()\n" 4036 "{\n" 4037 " int i = 42;\n" 4038 " return i;\n" 4039 "}", 4040 Style); 4041 4042 Style.BraceWrapping.AfterExternBlock = true; 4043 Style.BraceWrapping.SplitEmptyRecord = false; 4044 verifyFormat("extern \"C\"\n" 4045 "{}", 4046 Style); 4047 verifyFormat("extern \"C\"\n" 4048 "{\n" 4049 " int foo();\n" 4050 "}", 4051 Style); 4052 } 4053 4054 TEST_F(FormatTest, IndentExternBlockStyle) { 4055 FormatStyle Style = getLLVMStyle(); 4056 Style.IndentWidth = 2; 4057 4058 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4059 verifyFormat("extern \"C\" { /*9*/\n" 4060 "}", 4061 Style); 4062 verifyFormat("extern \"C\" {\n" 4063 " int foo10();\n" 4064 "}", 4065 Style); 4066 4067 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 4068 verifyFormat("extern \"C\" { /*11*/\n" 4069 "}", 4070 Style); 4071 verifyFormat("extern \"C\" {\n" 4072 "int foo12();\n" 4073 "}", 4074 Style); 4075 4076 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4077 Style.BraceWrapping.AfterExternBlock = true; 4078 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4079 verifyFormat("extern \"C\"\n" 4080 "{ /*13*/\n" 4081 "}", 4082 Style); 4083 verifyFormat("extern \"C\"\n{\n" 4084 " int foo14();\n" 4085 "}", 4086 Style); 4087 4088 Style.BraceWrapping.AfterExternBlock = false; 4089 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 4090 verifyFormat("extern \"C\" { /*15*/\n" 4091 "}", 4092 Style); 4093 verifyFormat("extern \"C\" {\n" 4094 "int foo16();\n" 4095 "}", 4096 Style); 4097 4098 Style.BraceWrapping.AfterExternBlock = true; 4099 verifyFormat("extern \"C\"\n" 4100 "{ /*13*/\n" 4101 "}", 4102 Style); 4103 verifyFormat("extern \"C\"\n" 4104 "{\n" 4105 "int foo14();\n" 4106 "}", 4107 Style); 4108 4109 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4110 verifyFormat("extern \"C\"\n" 4111 "{ /*13*/\n" 4112 "}", 4113 Style); 4114 verifyFormat("extern \"C\"\n" 4115 "{\n" 4116 " int foo14();\n" 4117 "}", 4118 Style); 4119 } 4120 4121 TEST_F(FormatTest, FormatsInlineASM) { 4122 verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));"); 4123 verifyFormat("asm(\"nop\" ::: \"memory\");"); 4124 verifyFormat( 4125 "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n" 4126 " \"cpuid\\n\\t\"\n" 4127 " \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n" 4128 " : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n" 4129 " : \"a\"(value));"); 4130 EXPECT_EQ( 4131 "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n" 4132 " __asm {\n" 4133 " mov edx,[that] // vtable in edx\n" 4134 " mov eax,methodIndex\n" 4135 " call [edx][eax*4] // stdcall\n" 4136 " }\n" 4137 "}", 4138 format("void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n" 4139 " __asm {\n" 4140 " mov edx,[that] // vtable in edx\n" 4141 " mov eax,methodIndex\n" 4142 " call [edx][eax*4] // stdcall\n" 4143 " }\n" 4144 "}")); 4145 EXPECT_EQ("_asm {\n" 4146 " xor eax, eax;\n" 4147 " cpuid;\n" 4148 "}", 4149 format("_asm {\n" 4150 " xor eax, eax;\n" 4151 " cpuid;\n" 4152 "}")); 4153 verifyFormat("void function() {\n" 4154 " // comment\n" 4155 " asm(\"\");\n" 4156 "}"); 4157 EXPECT_EQ("__asm {\n" 4158 "}\n" 4159 "int i;", 4160 format("__asm {\n" 4161 "}\n" 4162 "int i;")); 4163 } 4164 4165 TEST_F(FormatTest, FormatTryCatch) { 4166 verifyFormat("try {\n" 4167 " throw a * b;\n" 4168 "} catch (int a) {\n" 4169 " // Do nothing.\n" 4170 "} catch (...) {\n" 4171 " exit(42);\n" 4172 "}"); 4173 4174 // Function-level try statements. 4175 verifyFormat("int f() try { return 4; } catch (...) {\n" 4176 " return 5;\n" 4177 "}"); 4178 verifyFormat("class A {\n" 4179 " int a;\n" 4180 " A() try : a(0) {\n" 4181 " } catch (...) {\n" 4182 " throw;\n" 4183 " }\n" 4184 "};\n"); 4185 verifyFormat("class A {\n" 4186 " int a;\n" 4187 " A() try : a(0), b{1} {\n" 4188 " } catch (...) {\n" 4189 " throw;\n" 4190 " }\n" 4191 "};\n"); 4192 verifyFormat("class A {\n" 4193 " int a;\n" 4194 " A() try : a(0), b{1}, c{2} {\n" 4195 " } catch (...) {\n" 4196 " throw;\n" 4197 " }\n" 4198 "};\n"); 4199 verifyFormat("class A {\n" 4200 " int a;\n" 4201 " A() try : a(0), b{1}, c{2} {\n" 4202 " { // New scope.\n" 4203 " }\n" 4204 " } catch (...) {\n" 4205 " throw;\n" 4206 " }\n" 4207 "};\n"); 4208 4209 // Incomplete try-catch blocks. 4210 verifyIncompleteFormat("try {} catch ("); 4211 } 4212 4213 TEST_F(FormatTest, FormatTryAsAVariable) { 4214 verifyFormat("int try;"); 4215 verifyFormat("int try, size;"); 4216 verifyFormat("try = foo();"); 4217 verifyFormat("if (try < size) {\n return true;\n}"); 4218 4219 verifyFormat("int catch;"); 4220 verifyFormat("int catch, size;"); 4221 verifyFormat("catch = foo();"); 4222 verifyFormat("if (catch < size) {\n return true;\n}"); 4223 4224 FormatStyle Style = getLLVMStyle(); 4225 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4226 Style.BraceWrapping.AfterFunction = true; 4227 Style.BraceWrapping.BeforeCatch = true; 4228 verifyFormat("try {\n" 4229 " int bar = 1;\n" 4230 "}\n" 4231 "catch (...) {\n" 4232 " int bar = 1;\n" 4233 "}", 4234 Style); 4235 verifyFormat("#if NO_EX\n" 4236 "try\n" 4237 "#endif\n" 4238 "{\n" 4239 "}\n" 4240 "#if NO_EX\n" 4241 "catch (...) {\n" 4242 "}", 4243 Style); 4244 verifyFormat("try /* abc */ {\n" 4245 " int bar = 1;\n" 4246 "}\n" 4247 "catch (...) {\n" 4248 " int bar = 1;\n" 4249 "}", 4250 Style); 4251 verifyFormat("try\n" 4252 "// abc\n" 4253 "{\n" 4254 " int bar = 1;\n" 4255 "}\n" 4256 "catch (...) {\n" 4257 " int bar = 1;\n" 4258 "}", 4259 Style); 4260 } 4261 4262 TEST_F(FormatTest, FormatSEHTryCatch) { 4263 verifyFormat("__try {\n" 4264 " int a = b * c;\n" 4265 "} __except (EXCEPTION_EXECUTE_HANDLER) {\n" 4266 " // Do nothing.\n" 4267 "}"); 4268 4269 verifyFormat("__try {\n" 4270 " int a = b * c;\n" 4271 "} __finally {\n" 4272 " // Do nothing.\n" 4273 "}"); 4274 4275 verifyFormat("DEBUG({\n" 4276 " __try {\n" 4277 " } __finally {\n" 4278 " }\n" 4279 "});\n"); 4280 } 4281 4282 TEST_F(FormatTest, IncompleteTryCatchBlocks) { 4283 verifyFormat("try {\n" 4284 " f();\n" 4285 "} catch {\n" 4286 " g();\n" 4287 "}"); 4288 verifyFormat("try {\n" 4289 " f();\n" 4290 "} catch (A a) MACRO(x) {\n" 4291 " g();\n" 4292 "} catch (B b) MACRO(x) {\n" 4293 " g();\n" 4294 "}"); 4295 } 4296 4297 TEST_F(FormatTest, FormatTryCatchBraceStyles) { 4298 FormatStyle Style = getLLVMStyle(); 4299 for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla, 4300 FormatStyle::BS_WebKit}) { 4301 Style.BreakBeforeBraces = BraceStyle; 4302 verifyFormat("try {\n" 4303 " // something\n" 4304 "} catch (...) {\n" 4305 " // something\n" 4306 "}", 4307 Style); 4308 } 4309 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 4310 verifyFormat("try {\n" 4311 " // something\n" 4312 "}\n" 4313 "catch (...) {\n" 4314 " // something\n" 4315 "}", 4316 Style); 4317 verifyFormat("__try {\n" 4318 " // something\n" 4319 "}\n" 4320 "__finally {\n" 4321 " // something\n" 4322 "}", 4323 Style); 4324 verifyFormat("@try {\n" 4325 " // something\n" 4326 "}\n" 4327 "@finally {\n" 4328 " // something\n" 4329 "}", 4330 Style); 4331 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 4332 verifyFormat("try\n" 4333 "{\n" 4334 " // something\n" 4335 "}\n" 4336 "catch (...)\n" 4337 "{\n" 4338 " // something\n" 4339 "}", 4340 Style); 4341 Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 4342 verifyFormat("try\n" 4343 " {\n" 4344 " // something white\n" 4345 " }\n" 4346 "catch (...)\n" 4347 " {\n" 4348 " // something white\n" 4349 " }", 4350 Style); 4351 Style.BreakBeforeBraces = FormatStyle::BS_GNU; 4352 verifyFormat("try\n" 4353 " {\n" 4354 " // something\n" 4355 " }\n" 4356 "catch (...)\n" 4357 " {\n" 4358 " // something\n" 4359 " }", 4360 Style); 4361 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4362 Style.BraceWrapping.BeforeCatch = true; 4363 verifyFormat("try {\n" 4364 " // something\n" 4365 "}\n" 4366 "catch (...) {\n" 4367 " // something\n" 4368 "}", 4369 Style); 4370 } 4371 4372 TEST_F(FormatTest, StaticInitializers) { 4373 verifyFormat("static SomeClass SC = {1, 'a'};"); 4374 4375 verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n" 4376 " 100000000, " 4377 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};"); 4378 4379 // Here, everything other than the "}" would fit on a line. 4380 verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n" 4381 " 10000000000000000000000000};"); 4382 EXPECT_EQ("S s = {a,\n" 4383 "\n" 4384 " b};", 4385 format("S s = {\n" 4386 " a,\n" 4387 "\n" 4388 " b\n" 4389 "};")); 4390 4391 // FIXME: This would fit into the column limit if we'd fit "{ {" on the first 4392 // line. However, the formatting looks a bit off and this probably doesn't 4393 // happen often in practice. 4394 verifyFormat("static int Variable[1] = {\n" 4395 " {1000000000000000000000000000000000000}};", 4396 getLLVMStyleWithColumns(40)); 4397 } 4398 4399 TEST_F(FormatTest, DesignatedInitializers) { 4400 verifyFormat("const struct A a = {.a = 1, .b = 2};"); 4401 verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n" 4402 " .bbbbbbbbbb = 2,\n" 4403 " .cccccccccc = 3,\n" 4404 " .dddddddddd = 4,\n" 4405 " .eeeeeeeeee = 5};"); 4406 verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n" 4407 " .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n" 4408 " .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n" 4409 " .ccccccccccccccccccccccccccc = 3,\n" 4410 " .ddddddddddddddddddddddddddd = 4,\n" 4411 " .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};"); 4412 4413 verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};"); 4414 4415 verifyFormat("const struct A a = {[0] = 1, [1] = 2};"); 4416 verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n" 4417 " [2] = bbbbbbbbbb,\n" 4418 " [3] = cccccccccc,\n" 4419 " [4] = dddddddddd,\n" 4420 " [5] = eeeeeeeeee};"); 4421 verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n" 4422 " [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 4423 " [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 4424 " [3] = cccccccccccccccccccccccccccccccccccccc,\n" 4425 " [4] = dddddddddddddddddddddddddddddddddddddd,\n" 4426 " [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};"); 4427 } 4428 4429 TEST_F(FormatTest, NestedStaticInitializers) { 4430 verifyFormat("static A x = {{{}}};\n"); 4431 verifyFormat("static A x = {{{init1, init2, init3, init4},\n" 4432 " {init1, init2, init3, init4}}};", 4433 getLLVMStyleWithColumns(50)); 4434 4435 verifyFormat("somes Status::global_reps[3] = {\n" 4436 " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n" 4437 " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n" 4438 " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};", 4439 getLLVMStyleWithColumns(60)); 4440 verifyGoogleFormat("SomeType Status::global_reps[3] = {\n" 4441 " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n" 4442 " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n" 4443 " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};"); 4444 verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n" 4445 " {rect.fRight - rect.fLeft, rect.fBottom - " 4446 "rect.fTop}};"); 4447 4448 verifyFormat( 4449 "SomeArrayOfSomeType a = {\n" 4450 " {{1, 2, 3},\n" 4451 " {1, 2, 3},\n" 4452 " {111111111111111111111111111111, 222222222222222222222222222222,\n" 4453 " 333333333333333333333333333333},\n" 4454 " {1, 2, 3},\n" 4455 " {1, 2, 3}}};"); 4456 verifyFormat( 4457 "SomeArrayOfSomeType a = {\n" 4458 " {{1, 2, 3}},\n" 4459 " {{1, 2, 3}},\n" 4460 " {{111111111111111111111111111111, 222222222222222222222222222222,\n" 4461 " 333333333333333333333333333333}},\n" 4462 " {{1, 2, 3}},\n" 4463 " {{1, 2, 3}}};"); 4464 4465 verifyFormat("struct {\n" 4466 " unsigned bit;\n" 4467 " const char *const name;\n" 4468 "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n" 4469 " {kOsWin, \"Windows\"},\n" 4470 " {kOsLinux, \"Linux\"},\n" 4471 " {kOsCrOS, \"Chrome OS\"}};"); 4472 verifyFormat("struct {\n" 4473 " unsigned bit;\n" 4474 " const char *const name;\n" 4475 "} kBitsToOs[] = {\n" 4476 " {kOsMac, \"Mac\"},\n" 4477 " {kOsWin, \"Windows\"},\n" 4478 " {kOsLinux, \"Linux\"},\n" 4479 " {kOsCrOS, \"Chrome OS\"},\n" 4480 "};"); 4481 } 4482 4483 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) { 4484 verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro(" 4485 " \\\n" 4486 " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)"); 4487 } 4488 4489 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) { 4490 verifyFormat("virtual void write(ELFWriter *writerrr,\n" 4491 " OwningPtr<FileOutputBuffer> &buffer) = 0;"); 4492 4493 // Do break defaulted and deleted functions. 4494 verifyFormat("virtual void ~Deeeeeeeestructor() =\n" 4495 " default;", 4496 getLLVMStyleWithColumns(40)); 4497 verifyFormat("virtual void ~Deeeeeeeestructor() =\n" 4498 " delete;", 4499 getLLVMStyleWithColumns(40)); 4500 } 4501 4502 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) { 4503 verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3", 4504 getLLVMStyleWithColumns(40)); 4505 verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"", 4506 getLLVMStyleWithColumns(40)); 4507 EXPECT_EQ("#define Q \\\n" 4508 " \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\" \\\n" 4509 " \"aaaaaaaa.cpp\"", 4510 format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"", 4511 getLLVMStyleWithColumns(40))); 4512 } 4513 4514 TEST_F(FormatTest, UnderstandsLinePPDirective) { 4515 EXPECT_EQ("# 123 \"A string literal\"", 4516 format(" # 123 \"A string literal\"")); 4517 } 4518 4519 TEST_F(FormatTest, LayoutUnknownPPDirective) { 4520 EXPECT_EQ("#;", format("#;")); 4521 verifyFormat("#\n;\n;\n;"); 4522 } 4523 4524 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) { 4525 EXPECT_EQ("#line 42 \"test\"\n", 4526 format("# \\\n line \\\n 42 \\\n \"test\"\n")); 4527 EXPECT_EQ("#define A B\n", format("# \\\n define \\\n A \\\n B\n", 4528 getLLVMStyleWithColumns(12))); 4529 } 4530 4531 TEST_F(FormatTest, EndOfFileEndsPPDirective) { 4532 EXPECT_EQ("#line 42 \"test\"", 4533 format("# \\\n line \\\n 42 \\\n \"test\"")); 4534 EXPECT_EQ("#define A B", format("# \\\n define \\\n A \\\n B")); 4535 } 4536 4537 TEST_F(FormatTest, DoesntRemoveUnknownTokens) { 4538 verifyFormat("#define A \\x20"); 4539 verifyFormat("#define A \\ x20"); 4540 EXPECT_EQ("#define A \\ x20", format("#define A \\ x20")); 4541 verifyFormat("#define A ''"); 4542 verifyFormat("#define A ''qqq"); 4543 verifyFormat("#define A `qqq"); 4544 verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");"); 4545 EXPECT_EQ("const char *c = STRINGIFY(\n" 4546 "\\na : b);", 4547 format("const char * c = STRINGIFY(\n" 4548 "\\na : b);")); 4549 4550 verifyFormat("a\r\\"); 4551 verifyFormat("a\v\\"); 4552 verifyFormat("a\f\\"); 4553 } 4554 4555 TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) { 4556 FormatStyle style = getChromiumStyle(FormatStyle::LK_Cpp); 4557 style.IndentWidth = 4; 4558 style.PPIndentWidth = 1; 4559 4560 style.IndentPPDirectives = FormatStyle::PPDIS_None; 4561 verifyFormat("#ifdef __linux__\n" 4562 "void foo() {\n" 4563 " int x = 0;\n" 4564 "}\n" 4565 "#define FOO\n" 4566 "#endif\n" 4567 "void bar() {\n" 4568 " int y = 0;\n" 4569 "}\n", 4570 style); 4571 4572 style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash; 4573 verifyFormat("#ifdef __linux__\n" 4574 "void foo() {\n" 4575 " int x = 0;\n" 4576 "}\n" 4577 "# define FOO foo\n" 4578 "#endif\n" 4579 "void bar() {\n" 4580 " int y = 0;\n" 4581 "}\n", 4582 style); 4583 4584 style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash; 4585 verifyFormat("#ifdef __linux__\n" 4586 "void foo() {\n" 4587 " int x = 0;\n" 4588 "}\n" 4589 " #define FOO foo\n" 4590 "#endif\n" 4591 "void bar() {\n" 4592 " int y = 0;\n" 4593 "}\n", 4594 style); 4595 } 4596 4597 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) { 4598 verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13)); 4599 verifyFormat("#define A( \\\n BB)", getLLVMStyleWithColumns(12)); 4600 verifyFormat("#define A( \\\n A, B)", getLLVMStyleWithColumns(12)); 4601 // FIXME: We never break before the macro name. 4602 verifyFormat("#define AA( \\\n B)", getLLVMStyleWithColumns(12)); 4603 4604 verifyFormat("#define A A\n#define A A"); 4605 verifyFormat("#define A(X) A\n#define A A"); 4606 4607 verifyFormat("#define Something Other", getLLVMStyleWithColumns(23)); 4608 verifyFormat("#define Something \\\n Other", getLLVMStyleWithColumns(22)); 4609 } 4610 4611 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) { 4612 EXPECT_EQ("// somecomment\n" 4613 "#include \"a.h\"\n" 4614 "#define A( \\\n" 4615 " A, B)\n" 4616 "#include \"b.h\"\n" 4617 "// somecomment\n", 4618 format(" // somecomment\n" 4619 " #include \"a.h\"\n" 4620 "#define A(A,\\\n" 4621 " B)\n" 4622 " #include \"b.h\"\n" 4623 " // somecomment\n", 4624 getLLVMStyleWithColumns(13))); 4625 } 4626 4627 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); } 4628 4629 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) { 4630 EXPECT_EQ("#define A \\\n" 4631 " c; \\\n" 4632 " e;\n" 4633 "f;", 4634 format("#define A c; e;\n" 4635 "f;", 4636 getLLVMStyleWithColumns(14))); 4637 } 4638 4639 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); } 4640 4641 TEST_F(FormatTest, MacroDefinitionInsideStatement) { 4642 EXPECT_EQ("int x,\n" 4643 "#define A\n" 4644 " y;", 4645 format("int x,\n#define A\ny;")); 4646 } 4647 4648 TEST_F(FormatTest, HashInMacroDefinition) { 4649 EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle())); 4650 EXPECT_EQ("#define A(c) u#c", format("#define A(c) u#c", getLLVMStyle())); 4651 EXPECT_EQ("#define A(c) U#c", format("#define A(c) U#c", getLLVMStyle())); 4652 EXPECT_EQ("#define A(c) u8#c", format("#define A(c) u8#c", getLLVMStyle())); 4653 EXPECT_EQ("#define A(c) LR#c", format("#define A(c) LR#c", getLLVMStyle())); 4654 EXPECT_EQ("#define A(c) uR#c", format("#define A(c) uR#c", getLLVMStyle())); 4655 EXPECT_EQ("#define A(c) UR#c", format("#define A(c) UR#c", getLLVMStyle())); 4656 EXPECT_EQ("#define A(c) u8R#c", format("#define A(c) u8R#c", getLLVMStyle())); 4657 verifyFormat("#define A \\\n b #c;", getLLVMStyleWithColumns(11)); 4658 verifyFormat("#define A \\\n" 4659 " { \\\n" 4660 " f(#c); \\\n" 4661 " }", 4662 getLLVMStyleWithColumns(11)); 4663 4664 verifyFormat("#define A(X) \\\n" 4665 " void function##X()", 4666 getLLVMStyleWithColumns(22)); 4667 4668 verifyFormat("#define A(a, b, c) \\\n" 4669 " void a##b##c()", 4670 getLLVMStyleWithColumns(22)); 4671 4672 verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22)); 4673 } 4674 4675 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) { 4676 EXPECT_EQ("#define A (x)", format("#define A (x)")); 4677 EXPECT_EQ("#define A(x)", format("#define A(x)")); 4678 4679 FormatStyle Style = getLLVMStyle(); 4680 Style.SpaceBeforeParens = FormatStyle::SBPO_Never; 4681 verifyFormat("#define true ((foo)1)", Style); 4682 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 4683 verifyFormat("#define false((foo)0)", Style); 4684 } 4685 4686 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) { 4687 EXPECT_EQ("#define A b;", format("#define A \\\n" 4688 " \\\n" 4689 " b;", 4690 getLLVMStyleWithColumns(25))); 4691 EXPECT_EQ("#define A \\\n" 4692 " \\\n" 4693 " a; \\\n" 4694 " b;", 4695 format("#define A \\\n" 4696 " \\\n" 4697 " a; \\\n" 4698 " b;", 4699 getLLVMStyleWithColumns(11))); 4700 EXPECT_EQ("#define A \\\n" 4701 " a; \\\n" 4702 " \\\n" 4703 " b;", 4704 format("#define A \\\n" 4705 " a; \\\n" 4706 " \\\n" 4707 " b;", 4708 getLLVMStyleWithColumns(11))); 4709 } 4710 4711 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) { 4712 verifyIncompleteFormat("#define A :"); 4713 verifyFormat("#define SOMECASES \\\n" 4714 " case 1: \\\n" 4715 " case 2\n", 4716 getLLVMStyleWithColumns(20)); 4717 verifyFormat("#define MACRO(a) \\\n" 4718 " if (a) \\\n" 4719 " f(); \\\n" 4720 " else \\\n" 4721 " g()", 4722 getLLVMStyleWithColumns(18)); 4723 verifyFormat("#define A template <typename T>"); 4724 verifyIncompleteFormat("#define STR(x) #x\n" 4725 "f(STR(this_is_a_string_literal{));"); 4726 verifyFormat("#pragma omp threadprivate( \\\n" 4727 " y)), // expected-warning", 4728 getLLVMStyleWithColumns(28)); 4729 verifyFormat("#d, = };"); 4730 verifyFormat("#if \"a"); 4731 verifyIncompleteFormat("({\n" 4732 "#define b \\\n" 4733 " } \\\n" 4734 " a\n" 4735 "a", 4736 getLLVMStyleWithColumns(15)); 4737 verifyFormat("#define A \\\n" 4738 " { \\\n" 4739 " {\n" 4740 "#define B \\\n" 4741 " } \\\n" 4742 " }", 4743 getLLVMStyleWithColumns(15)); 4744 verifyNoCrash("#if a\na(\n#else\n#endif\n{a"); 4745 verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}"); 4746 verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};"); 4747 verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() { \n)}"); 4748 } 4749 4750 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) { 4751 verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline. 4752 EXPECT_EQ("class A : public QObject {\n" 4753 " Q_OBJECT\n" 4754 "\n" 4755 " A() {}\n" 4756 "};", 4757 format("class A : public QObject {\n" 4758 " Q_OBJECT\n" 4759 "\n" 4760 " A() {\n}\n" 4761 "} ;")); 4762 EXPECT_EQ("MACRO\n" 4763 "/*static*/ int i;", 4764 format("MACRO\n" 4765 " /*static*/ int i;")); 4766 EXPECT_EQ("SOME_MACRO\n" 4767 "namespace {\n" 4768 "void f();\n" 4769 "} // namespace", 4770 format("SOME_MACRO\n" 4771 " namespace {\n" 4772 "void f( );\n" 4773 "} // namespace")); 4774 // Only if the identifier contains at least 5 characters. 4775 EXPECT_EQ("HTTP f();", format("HTTP\nf();")); 4776 EXPECT_EQ("MACRO\nf();", format("MACRO\nf();")); 4777 // Only if everything is upper case. 4778 EXPECT_EQ("class A : public QObject {\n" 4779 " Q_Object A() {}\n" 4780 "};", 4781 format("class A : public QObject {\n" 4782 " Q_Object\n" 4783 " A() {\n}\n" 4784 "} ;")); 4785 4786 // Only if the next line can actually start an unwrapped line. 4787 EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;", 4788 format("SOME_WEIRD_LOG_MACRO\n" 4789 "<< SomeThing;")); 4790 4791 verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), " 4792 "(n, buffers))\n", 4793 getChromiumStyle(FormatStyle::LK_Cpp)); 4794 4795 // See PR41483 4796 EXPECT_EQ("/**/ FOO(a)\n" 4797 "FOO(b)", 4798 format("/**/ FOO(a)\n" 4799 "FOO(b)")); 4800 } 4801 4802 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) { 4803 EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n" 4804 "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n" 4805 "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n" 4806 "class X {};\n" 4807 "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n" 4808 "int *createScopDetectionPass() { return 0; }", 4809 format(" INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n" 4810 " INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n" 4811 " INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n" 4812 " class X {};\n" 4813 " INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n" 4814 " int *createScopDetectionPass() { return 0; }")); 4815 // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as 4816 // braces, so that inner block is indented one level more. 4817 EXPECT_EQ("int q() {\n" 4818 " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n" 4819 " IPC_MESSAGE_HANDLER(xxx, qqq)\n" 4820 " IPC_END_MESSAGE_MAP()\n" 4821 "}", 4822 format("int q() {\n" 4823 " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n" 4824 " IPC_MESSAGE_HANDLER(xxx, qqq)\n" 4825 " IPC_END_MESSAGE_MAP()\n" 4826 "}")); 4827 4828 // Same inside macros. 4829 EXPECT_EQ("#define LIST(L) \\\n" 4830 " L(A) \\\n" 4831 " L(B) \\\n" 4832 " L(C)", 4833 format("#define LIST(L) \\\n" 4834 " L(A) \\\n" 4835 " L(B) \\\n" 4836 " L(C)", 4837 getGoogleStyle())); 4838 4839 // These must not be recognized as macros. 4840 EXPECT_EQ("int q() {\n" 4841 " f(x);\n" 4842 " f(x) {}\n" 4843 " f(x)->g();\n" 4844 " f(x)->*g();\n" 4845 " f(x).g();\n" 4846 " f(x) = x;\n" 4847 " f(x) += x;\n" 4848 " f(x) -= x;\n" 4849 " f(x) *= x;\n" 4850 " f(x) /= x;\n" 4851 " f(x) %= x;\n" 4852 " f(x) &= x;\n" 4853 " f(x) |= x;\n" 4854 " f(x) ^= x;\n" 4855 " f(x) >>= x;\n" 4856 " f(x) <<= x;\n" 4857 " f(x)[y].z();\n" 4858 " LOG(INFO) << x;\n" 4859 " ifstream(x) >> x;\n" 4860 "}\n", 4861 format("int q() {\n" 4862 " f(x)\n;\n" 4863 " f(x)\n {}\n" 4864 " f(x)\n->g();\n" 4865 " f(x)\n->*g();\n" 4866 " f(x)\n.g();\n" 4867 " f(x)\n = x;\n" 4868 " f(x)\n += x;\n" 4869 " f(x)\n -= x;\n" 4870 " f(x)\n *= x;\n" 4871 " f(x)\n /= x;\n" 4872 " f(x)\n %= x;\n" 4873 " f(x)\n &= x;\n" 4874 " f(x)\n |= x;\n" 4875 " f(x)\n ^= x;\n" 4876 " f(x)\n >>= x;\n" 4877 " f(x)\n <<= x;\n" 4878 " f(x)\n[y].z();\n" 4879 " LOG(INFO)\n << x;\n" 4880 " ifstream(x)\n >> x;\n" 4881 "}\n")); 4882 EXPECT_EQ("int q() {\n" 4883 " F(x)\n" 4884 " if (1) {\n" 4885 " }\n" 4886 " F(x)\n" 4887 " while (1) {\n" 4888 " }\n" 4889 " F(x)\n" 4890 " G(x);\n" 4891 " F(x)\n" 4892 " try {\n" 4893 " Q();\n" 4894 " } catch (...) {\n" 4895 " }\n" 4896 "}\n", 4897 format("int q() {\n" 4898 "F(x)\n" 4899 "if (1) {}\n" 4900 "F(x)\n" 4901 "while (1) {}\n" 4902 "F(x)\n" 4903 "G(x);\n" 4904 "F(x)\n" 4905 "try { Q(); } catch (...) {}\n" 4906 "}\n")); 4907 EXPECT_EQ("class A {\n" 4908 " A() : t(0) {}\n" 4909 " A(int i) noexcept() : {}\n" 4910 " A(X x)\n" // FIXME: function-level try blocks are broken. 4911 " try : t(0) {\n" 4912 " } catch (...) {\n" 4913 " }\n" 4914 "};", 4915 format("class A {\n" 4916 " A()\n : t(0) {}\n" 4917 " A(int i)\n noexcept() : {}\n" 4918 " A(X x)\n" 4919 " try : t(0) {} catch (...) {}\n" 4920 "};")); 4921 FormatStyle Style = getLLVMStyle(); 4922 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4923 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 4924 Style.BraceWrapping.AfterFunction = true; 4925 EXPECT_EQ("void f()\n" 4926 "try\n" 4927 "{\n" 4928 "}", 4929 format("void f() try {\n" 4930 "}", 4931 Style)); 4932 EXPECT_EQ("class SomeClass {\n" 4933 "public:\n" 4934 " SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 4935 "};", 4936 format("class SomeClass {\n" 4937 "public:\n" 4938 " SomeClass()\n" 4939 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 4940 "};")); 4941 EXPECT_EQ("class SomeClass {\n" 4942 "public:\n" 4943 " SomeClass()\n" 4944 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 4945 "};", 4946 format("class SomeClass {\n" 4947 "public:\n" 4948 " SomeClass()\n" 4949 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 4950 "};", 4951 getLLVMStyleWithColumns(40))); 4952 4953 verifyFormat("MACRO(>)"); 4954 4955 // Some macros contain an implicit semicolon. 4956 Style = getLLVMStyle(); 4957 Style.StatementMacros.push_back("FOO"); 4958 verifyFormat("FOO(a) int b = 0;"); 4959 verifyFormat("FOO(a)\n" 4960 "int b = 0;", 4961 Style); 4962 verifyFormat("FOO(a);\n" 4963 "int b = 0;", 4964 Style); 4965 verifyFormat("FOO(argc, argv, \"4.0.2\")\n" 4966 "int b = 0;", 4967 Style); 4968 verifyFormat("FOO()\n" 4969 "int b = 0;", 4970 Style); 4971 verifyFormat("FOO\n" 4972 "int b = 0;", 4973 Style); 4974 verifyFormat("void f() {\n" 4975 " FOO(a)\n" 4976 " return a;\n" 4977 "}", 4978 Style); 4979 verifyFormat("FOO(a)\n" 4980 "FOO(b)", 4981 Style); 4982 verifyFormat("int a = 0;\n" 4983 "FOO(b)\n" 4984 "int c = 0;", 4985 Style); 4986 verifyFormat("int a = 0;\n" 4987 "int x = FOO(a)\n" 4988 "int b = 0;", 4989 Style); 4990 verifyFormat("void foo(int a) { FOO(a) }\n" 4991 "uint32_t bar() {}", 4992 Style); 4993 } 4994 4995 TEST_F(FormatTest, FormatsMacrosWithZeroColumnWidth) { 4996 FormatStyle ZeroColumn = getLLVMStyleWithColumns(0); 4997 4998 verifyFormat("#define A LOOOOOOOOOOOOOOOOOOONG() LOOOOOOOOOOOOOOOOOOONG()", 4999 ZeroColumn); 5000 } 5001 5002 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) { 5003 verifyFormat("#define A \\\n" 5004 " f({ \\\n" 5005 " g(); \\\n" 5006 " });", 5007 getLLVMStyleWithColumns(11)); 5008 } 5009 5010 TEST_F(FormatTest, IndentPreprocessorDirectives) { 5011 FormatStyle Style = getLLVMStyleWithColumns(40); 5012 Style.IndentPPDirectives = FormatStyle::PPDIS_None; 5013 verifyFormat("#ifdef _WIN32\n" 5014 "#define A 0\n" 5015 "#ifdef VAR2\n" 5016 "#define B 1\n" 5017 "#include <someheader.h>\n" 5018 "#define MACRO \\\n" 5019 " some_very_long_func_aaaaaaaaaa();\n" 5020 "#endif\n" 5021 "#else\n" 5022 "#define A 1\n" 5023 "#endif", 5024 Style); 5025 Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash; 5026 verifyFormat("#ifdef _WIN32\n" 5027 "# define A 0\n" 5028 "# ifdef VAR2\n" 5029 "# define B 1\n" 5030 "# include <someheader.h>\n" 5031 "# define MACRO \\\n" 5032 " some_very_long_func_aaaaaaaaaa();\n" 5033 "# endif\n" 5034 "#else\n" 5035 "# define A 1\n" 5036 "#endif", 5037 Style); 5038 verifyFormat("#if A\n" 5039 "# define MACRO \\\n" 5040 " void a(int x) { \\\n" 5041 " b(); \\\n" 5042 " c(); \\\n" 5043 " d(); \\\n" 5044 " e(); \\\n" 5045 " f(); \\\n" 5046 " }\n" 5047 "#endif", 5048 Style); 5049 // Comments before include guard. 5050 verifyFormat("// file comment\n" 5051 "// file comment\n" 5052 "#ifndef HEADER_H\n" 5053 "#define HEADER_H\n" 5054 "code();\n" 5055 "#endif", 5056 Style); 5057 // Test with include guards. 5058 verifyFormat("#ifndef HEADER_H\n" 5059 "#define HEADER_H\n" 5060 "code();\n" 5061 "#endif", 5062 Style); 5063 // Include guards must have a #define with the same variable immediately 5064 // after #ifndef. 5065 verifyFormat("#ifndef NOT_GUARD\n" 5066 "# define FOO\n" 5067 "code();\n" 5068 "#endif", 5069 Style); 5070 5071 // Include guards must cover the entire file. 5072 verifyFormat("code();\n" 5073 "code();\n" 5074 "#ifndef NOT_GUARD\n" 5075 "# define NOT_GUARD\n" 5076 "code();\n" 5077 "#endif", 5078 Style); 5079 verifyFormat("#ifndef NOT_GUARD\n" 5080 "# define NOT_GUARD\n" 5081 "code();\n" 5082 "#endif\n" 5083 "code();", 5084 Style); 5085 // Test with trailing blank lines. 5086 verifyFormat("#ifndef HEADER_H\n" 5087 "#define HEADER_H\n" 5088 "code();\n" 5089 "#endif\n", 5090 Style); 5091 // Include guards don't have #else. 5092 verifyFormat("#ifndef NOT_GUARD\n" 5093 "# define NOT_GUARD\n" 5094 "code();\n" 5095 "#else\n" 5096 "#endif", 5097 Style); 5098 verifyFormat("#ifndef NOT_GUARD\n" 5099 "# define NOT_GUARD\n" 5100 "code();\n" 5101 "#elif FOO\n" 5102 "#endif", 5103 Style); 5104 // Non-identifier #define after potential include guard. 5105 verifyFormat("#ifndef FOO\n" 5106 "# define 1\n" 5107 "#endif\n", 5108 Style); 5109 // #if closes past last non-preprocessor line. 5110 verifyFormat("#ifndef FOO\n" 5111 "#define FOO\n" 5112 "#if 1\n" 5113 "int i;\n" 5114 "# define A 0\n" 5115 "#endif\n" 5116 "#endif\n", 5117 Style); 5118 // Don't crash if there is an #elif directive without a condition. 5119 verifyFormat("#if 1\n" 5120 "int x;\n" 5121 "#elif\n" 5122 "int y;\n" 5123 "#else\n" 5124 "int z;\n" 5125 "#endif", 5126 Style); 5127 // FIXME: This doesn't handle the case where there's code between the 5128 // #ifndef and #define but all other conditions hold. This is because when 5129 // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the 5130 // previous code line yet, so we can't detect it. 5131 EXPECT_EQ("#ifndef NOT_GUARD\n" 5132 "code();\n" 5133 "#define NOT_GUARD\n" 5134 "code();\n" 5135 "#endif", 5136 format("#ifndef NOT_GUARD\n" 5137 "code();\n" 5138 "# define NOT_GUARD\n" 5139 "code();\n" 5140 "#endif", 5141 Style)); 5142 // FIXME: This doesn't handle cases where legitimate preprocessor lines may 5143 // be outside an include guard. Examples are #pragma once and 5144 // #pragma GCC diagnostic, or anything else that does not change the meaning 5145 // of the file if it's included multiple times. 5146 EXPECT_EQ("#ifdef WIN32\n" 5147 "# pragma once\n" 5148 "#endif\n" 5149 "#ifndef HEADER_H\n" 5150 "# define HEADER_H\n" 5151 "code();\n" 5152 "#endif", 5153 format("#ifdef WIN32\n" 5154 "# pragma once\n" 5155 "#endif\n" 5156 "#ifndef HEADER_H\n" 5157 "#define HEADER_H\n" 5158 "code();\n" 5159 "#endif", 5160 Style)); 5161 // FIXME: This does not detect when there is a single non-preprocessor line 5162 // in front of an include-guard-like structure where other conditions hold 5163 // because ScopedLineState hides the line. 5164 EXPECT_EQ("code();\n" 5165 "#ifndef HEADER_H\n" 5166 "#define HEADER_H\n" 5167 "code();\n" 5168 "#endif", 5169 format("code();\n" 5170 "#ifndef HEADER_H\n" 5171 "# define HEADER_H\n" 5172 "code();\n" 5173 "#endif", 5174 Style)); 5175 // Keep comments aligned with #, otherwise indent comments normally. These 5176 // tests cannot use verifyFormat because messUp manipulates leading 5177 // whitespace. 5178 { 5179 const char *Expected = "" 5180 "void f() {\n" 5181 "#if 1\n" 5182 "// Preprocessor aligned.\n" 5183 "# define A 0\n" 5184 " // Code. Separated by blank line.\n" 5185 "\n" 5186 "# define B 0\n" 5187 " // Code. Not aligned with #\n" 5188 "# define C 0\n" 5189 "#endif"; 5190 const char *ToFormat = "" 5191 "void f() {\n" 5192 "#if 1\n" 5193 "// Preprocessor aligned.\n" 5194 "# define A 0\n" 5195 "// Code. Separated by blank line.\n" 5196 "\n" 5197 "# define B 0\n" 5198 " // Code. Not aligned with #\n" 5199 "# define C 0\n" 5200 "#endif"; 5201 EXPECT_EQ(Expected, format(ToFormat, Style)); 5202 EXPECT_EQ(Expected, format(Expected, Style)); 5203 } 5204 // Keep block quotes aligned. 5205 { 5206 const char *Expected = "" 5207 "void f() {\n" 5208 "#if 1\n" 5209 "/* Preprocessor aligned. */\n" 5210 "# define A 0\n" 5211 " /* Code. Separated by blank line. */\n" 5212 "\n" 5213 "# define B 0\n" 5214 " /* Code. Not aligned with # */\n" 5215 "# define C 0\n" 5216 "#endif"; 5217 const char *ToFormat = "" 5218 "void f() {\n" 5219 "#if 1\n" 5220 "/* Preprocessor aligned. */\n" 5221 "# define A 0\n" 5222 "/* Code. Separated by blank line. */\n" 5223 "\n" 5224 "# define B 0\n" 5225 " /* Code. Not aligned with # */\n" 5226 "# define C 0\n" 5227 "#endif"; 5228 EXPECT_EQ(Expected, format(ToFormat, Style)); 5229 EXPECT_EQ(Expected, format(Expected, Style)); 5230 } 5231 // Keep comments aligned with un-indented directives. 5232 { 5233 const char *Expected = "" 5234 "void f() {\n" 5235 "// Preprocessor aligned.\n" 5236 "#define A 0\n" 5237 " // Code. Separated by blank line.\n" 5238 "\n" 5239 "#define B 0\n" 5240 " // Code. Not aligned with #\n" 5241 "#define C 0\n"; 5242 const char *ToFormat = "" 5243 "void f() {\n" 5244 "// Preprocessor aligned.\n" 5245 "#define A 0\n" 5246 "// Code. Separated by blank line.\n" 5247 "\n" 5248 "#define B 0\n" 5249 " // Code. Not aligned with #\n" 5250 "#define C 0\n"; 5251 EXPECT_EQ(Expected, format(ToFormat, Style)); 5252 EXPECT_EQ(Expected, format(Expected, Style)); 5253 } 5254 // Test AfterHash with tabs. 5255 { 5256 FormatStyle Tabbed = Style; 5257 Tabbed.UseTab = FormatStyle::UT_Always; 5258 Tabbed.IndentWidth = 8; 5259 Tabbed.TabWidth = 8; 5260 verifyFormat("#ifdef _WIN32\n" 5261 "#\tdefine A 0\n" 5262 "#\tifdef VAR2\n" 5263 "#\t\tdefine B 1\n" 5264 "#\t\tinclude <someheader.h>\n" 5265 "#\t\tdefine MACRO \\\n" 5266 "\t\t\tsome_very_long_func_aaaaaaaaaa();\n" 5267 "#\tendif\n" 5268 "#else\n" 5269 "#\tdefine A 1\n" 5270 "#endif", 5271 Tabbed); 5272 } 5273 5274 // Regression test: Multiline-macro inside include guards. 5275 verifyFormat("#ifndef HEADER_H\n" 5276 "#define HEADER_H\n" 5277 "#define A() \\\n" 5278 " int i; \\\n" 5279 " int j;\n" 5280 "#endif // HEADER_H", 5281 getLLVMStyleWithColumns(20)); 5282 5283 Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash; 5284 // Basic before hash indent tests 5285 verifyFormat("#ifdef _WIN32\n" 5286 " #define A 0\n" 5287 " #ifdef VAR2\n" 5288 " #define B 1\n" 5289 " #include <someheader.h>\n" 5290 " #define MACRO \\\n" 5291 " some_very_long_func_aaaaaaaaaa();\n" 5292 " #endif\n" 5293 "#else\n" 5294 " #define A 1\n" 5295 "#endif", 5296 Style); 5297 verifyFormat("#if A\n" 5298 " #define MACRO \\\n" 5299 " void a(int x) { \\\n" 5300 " b(); \\\n" 5301 " c(); \\\n" 5302 " d(); \\\n" 5303 " e(); \\\n" 5304 " f(); \\\n" 5305 " }\n" 5306 "#endif", 5307 Style); 5308 // Keep comments aligned with indented directives. These 5309 // tests cannot use verifyFormat because messUp manipulates leading 5310 // whitespace. 5311 { 5312 const char *Expected = "void f() {\n" 5313 "// Aligned to preprocessor.\n" 5314 "#if 1\n" 5315 " // Aligned to code.\n" 5316 " int a;\n" 5317 " #if 1\n" 5318 " // Aligned to preprocessor.\n" 5319 " #define A 0\n" 5320 " // Aligned to code.\n" 5321 " int b;\n" 5322 " #endif\n" 5323 "#endif\n" 5324 "}"; 5325 const char *ToFormat = "void f() {\n" 5326 "// Aligned to preprocessor.\n" 5327 "#if 1\n" 5328 "// Aligned to code.\n" 5329 "int a;\n" 5330 "#if 1\n" 5331 "// Aligned to preprocessor.\n" 5332 "#define A 0\n" 5333 "// Aligned to code.\n" 5334 "int b;\n" 5335 "#endif\n" 5336 "#endif\n" 5337 "}"; 5338 EXPECT_EQ(Expected, format(ToFormat, Style)); 5339 EXPECT_EQ(Expected, format(Expected, Style)); 5340 } 5341 { 5342 const char *Expected = "void f() {\n" 5343 "/* Aligned to preprocessor. */\n" 5344 "#if 1\n" 5345 " /* Aligned to code. */\n" 5346 " int a;\n" 5347 " #if 1\n" 5348 " /* Aligned to preprocessor. */\n" 5349 " #define A 0\n" 5350 " /* Aligned to code. */\n" 5351 " int b;\n" 5352 " #endif\n" 5353 "#endif\n" 5354 "}"; 5355 const char *ToFormat = "void f() {\n" 5356 "/* Aligned to preprocessor. */\n" 5357 "#if 1\n" 5358 "/* Aligned to code. */\n" 5359 "int a;\n" 5360 "#if 1\n" 5361 "/* Aligned to preprocessor. */\n" 5362 "#define A 0\n" 5363 "/* Aligned to code. */\n" 5364 "int b;\n" 5365 "#endif\n" 5366 "#endif\n" 5367 "}"; 5368 EXPECT_EQ(Expected, format(ToFormat, Style)); 5369 EXPECT_EQ(Expected, format(Expected, Style)); 5370 } 5371 5372 // Test single comment before preprocessor 5373 verifyFormat("// Comment\n" 5374 "\n" 5375 "#if 1\n" 5376 "#endif", 5377 Style); 5378 } 5379 5380 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) { 5381 verifyFormat("{\n { a #c; }\n}"); 5382 } 5383 5384 TEST_F(FormatTest, FormatUnbalancedStructuralElements) { 5385 EXPECT_EQ("#define A \\\n { \\\n {\nint i;", 5386 format("#define A { {\nint i;", getLLVMStyleWithColumns(11))); 5387 EXPECT_EQ("#define A \\\n } \\\n }\nint i;", 5388 format("#define A } }\nint i;", getLLVMStyleWithColumns(11))); 5389 } 5390 5391 TEST_F(FormatTest, EscapedNewlines) { 5392 FormatStyle Narrow = getLLVMStyleWithColumns(11); 5393 EXPECT_EQ("#define A \\\n int i; \\\n int j;", 5394 format("#define A \\\nint i;\\\n int j;", Narrow)); 5395 EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;")); 5396 EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();")); 5397 EXPECT_EQ("/* \\ \\ \\\n */", format("\\\n/* \\ \\ \\\n */")); 5398 EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>")); 5399 5400 FormatStyle AlignLeft = getLLVMStyle(); 5401 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left; 5402 EXPECT_EQ("#define MACRO(x) \\\n" 5403 "private: \\\n" 5404 " int x(int a);\n", 5405 format("#define MACRO(x) \\\n" 5406 "private: \\\n" 5407 " int x(int a);\n", 5408 AlignLeft)); 5409 5410 // CRLF line endings 5411 EXPECT_EQ("#define A \\\r\n int i; \\\r\n int j;", 5412 format("#define A \\\r\nint i;\\\r\n int j;", Narrow)); 5413 EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;")); 5414 EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();")); 5415 EXPECT_EQ("/* \\ \\ \\\r\n */", format("\\\r\n/* \\ \\ \\\r\n */")); 5416 EXPECT_EQ("<a\r\n\\\\\r\n>", format("<a\r\n\\\\\r\n>")); 5417 EXPECT_EQ("#define MACRO(x) \\\r\n" 5418 "private: \\\r\n" 5419 " int x(int a);\r\n", 5420 format("#define MACRO(x) \\\r\n" 5421 "private: \\\r\n" 5422 " int x(int a);\r\n", 5423 AlignLeft)); 5424 5425 FormatStyle DontAlign = getLLVMStyle(); 5426 DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 5427 DontAlign.MaxEmptyLinesToKeep = 3; 5428 // FIXME: can't use verifyFormat here because the newline before 5429 // "public:" is not inserted the first time it's reformatted 5430 EXPECT_EQ("#define A \\\n" 5431 " class Foo { \\\n" 5432 " void bar(); \\\n" 5433 "\\\n" 5434 "\\\n" 5435 "\\\n" 5436 " public: \\\n" 5437 " void baz(); \\\n" 5438 " };", 5439 format("#define A \\\n" 5440 " class Foo { \\\n" 5441 " void bar(); \\\n" 5442 "\\\n" 5443 "\\\n" 5444 "\\\n" 5445 " public: \\\n" 5446 " void baz(); \\\n" 5447 " };", 5448 DontAlign)); 5449 } 5450 5451 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) { 5452 verifyFormat("#define A \\\n" 5453 " int v( \\\n" 5454 " a); \\\n" 5455 " int i;", 5456 getLLVMStyleWithColumns(11)); 5457 } 5458 5459 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) { 5460 EXPECT_EQ( 5461 "#define ALooooooooooooooooooooooooooooooooooooooongMacro(" 5462 " \\\n" 5463 " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n" 5464 "\n" 5465 "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n" 5466 " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n", 5467 format(" #define ALooooooooooooooooooooooooooooooooooooooongMacro(" 5468 "\\\n" 5469 "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n" 5470 " \n" 5471 " AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n" 5472 " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n")); 5473 } 5474 5475 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) { 5476 EXPECT_EQ("int\n" 5477 "#define A\n" 5478 " a;", 5479 format("int\n#define A\na;")); 5480 verifyFormat("functionCallTo(\n" 5481 " someOtherFunction(\n" 5482 " withSomeParameters, whichInSequence,\n" 5483 " areLongerThanALine(andAnotherCall,\n" 5484 "#define A B\n" 5485 " withMoreParamters,\n" 5486 " whichStronglyInfluenceTheLayout),\n" 5487 " andMoreParameters),\n" 5488 " trailing);", 5489 getLLVMStyleWithColumns(69)); 5490 verifyFormat("Foo::Foo()\n" 5491 "#ifdef BAR\n" 5492 " : baz(0)\n" 5493 "#endif\n" 5494 "{\n" 5495 "}"); 5496 verifyFormat("void f() {\n" 5497 " if (true)\n" 5498 "#ifdef A\n" 5499 " f(42);\n" 5500 " x();\n" 5501 "#else\n" 5502 " g();\n" 5503 " x();\n" 5504 "#endif\n" 5505 "}"); 5506 verifyFormat("void f(param1, param2,\n" 5507 " param3,\n" 5508 "#ifdef A\n" 5509 " param4(param5,\n" 5510 "#ifdef A1\n" 5511 " param6,\n" 5512 "#ifdef A2\n" 5513 " param7),\n" 5514 "#else\n" 5515 " param8),\n" 5516 " param9,\n" 5517 "#endif\n" 5518 " param10,\n" 5519 "#endif\n" 5520 " param11)\n" 5521 "#else\n" 5522 " param12)\n" 5523 "#endif\n" 5524 "{\n" 5525 " x();\n" 5526 "}", 5527 getLLVMStyleWithColumns(28)); 5528 verifyFormat("#if 1\n" 5529 "int i;"); 5530 verifyFormat("#if 1\n" 5531 "#endif\n" 5532 "#if 1\n" 5533 "#else\n" 5534 "#endif\n"); 5535 verifyFormat("DEBUG({\n" 5536 " return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5537 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n" 5538 "});\n" 5539 "#if a\n" 5540 "#else\n" 5541 "#endif"); 5542 5543 verifyIncompleteFormat("void f(\n" 5544 "#if A\n" 5545 ");\n" 5546 "#else\n" 5547 "#endif"); 5548 } 5549 5550 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) { 5551 verifyFormat("#endif\n" 5552 "#if B"); 5553 } 5554 5555 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) { 5556 FormatStyle SingleLine = getLLVMStyle(); 5557 SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse; 5558 verifyFormat("#if 0\n" 5559 "#elif 1\n" 5560 "#endif\n" 5561 "void foo() {\n" 5562 " if (test) foo2();\n" 5563 "}", 5564 SingleLine); 5565 } 5566 5567 TEST_F(FormatTest, LayoutBlockInsideParens) { 5568 verifyFormat("functionCall({ int i; });"); 5569 verifyFormat("functionCall({\n" 5570 " int i;\n" 5571 " int j;\n" 5572 "});"); 5573 verifyFormat("functionCall(\n" 5574 " {\n" 5575 " int i;\n" 5576 " int j;\n" 5577 " },\n" 5578 " aaaa, bbbb, cccc);"); 5579 verifyFormat("functionA(functionB({\n" 5580 " int i;\n" 5581 " int j;\n" 5582 " }),\n" 5583 " aaaa, bbbb, cccc);"); 5584 verifyFormat("functionCall(\n" 5585 " {\n" 5586 " int i;\n" 5587 " int j;\n" 5588 " },\n" 5589 " aaaa, bbbb, // comment\n" 5590 " cccc);"); 5591 verifyFormat("functionA(functionB({\n" 5592 " int i;\n" 5593 " int j;\n" 5594 " }),\n" 5595 " aaaa, bbbb, // comment\n" 5596 " cccc);"); 5597 verifyFormat("functionCall(aaaa, bbbb, { int i; });"); 5598 verifyFormat("functionCall(aaaa, bbbb, {\n" 5599 " int i;\n" 5600 " int j;\n" 5601 "});"); 5602 verifyFormat( 5603 "Aaa(\n" // FIXME: There shouldn't be a linebreak here. 5604 " {\n" 5605 " int i; // break\n" 5606 " },\n" 5607 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 5608 " ccccccccccccccccc));"); 5609 verifyFormat("DEBUG({\n" 5610 " if (a)\n" 5611 " f();\n" 5612 "});"); 5613 } 5614 5615 TEST_F(FormatTest, LayoutBlockInsideStatement) { 5616 EXPECT_EQ("SOME_MACRO { int i; }\n" 5617 "int i;", 5618 format(" SOME_MACRO {int i;} int i;")); 5619 } 5620 5621 TEST_F(FormatTest, LayoutNestedBlocks) { 5622 verifyFormat("void AddOsStrings(unsigned bitmask) {\n" 5623 " struct s {\n" 5624 " int i;\n" 5625 " };\n" 5626 " s kBitsToOs[] = {{10}};\n" 5627 " for (int i = 0; i < 10; ++i)\n" 5628 " return;\n" 5629 "}"); 5630 verifyFormat("call(parameter, {\n" 5631 " something();\n" 5632 " // Comment using all columns.\n" 5633 " somethingelse();\n" 5634 "});", 5635 getLLVMStyleWithColumns(40)); 5636 verifyFormat("DEBUG( //\n" 5637 " { f(); }, a);"); 5638 verifyFormat("DEBUG( //\n" 5639 " {\n" 5640 " f(); //\n" 5641 " },\n" 5642 " a);"); 5643 5644 EXPECT_EQ("call(parameter, {\n" 5645 " something();\n" 5646 " // Comment too\n" 5647 " // looooooooooong.\n" 5648 " somethingElse();\n" 5649 "});", 5650 format("call(parameter, {\n" 5651 " something();\n" 5652 " // Comment too looooooooooong.\n" 5653 " somethingElse();\n" 5654 "});", 5655 getLLVMStyleWithColumns(29))); 5656 EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int i; });")); 5657 EXPECT_EQ("DEBUG({ // comment\n" 5658 " int i;\n" 5659 "});", 5660 format("DEBUG({ // comment\n" 5661 "int i;\n" 5662 "});")); 5663 EXPECT_EQ("DEBUG({\n" 5664 " int i;\n" 5665 "\n" 5666 " // comment\n" 5667 " int j;\n" 5668 "});", 5669 format("DEBUG({\n" 5670 " int i;\n" 5671 "\n" 5672 " // comment\n" 5673 " int j;\n" 5674 "});")); 5675 5676 verifyFormat("DEBUG({\n" 5677 " if (a)\n" 5678 " return;\n" 5679 "});"); 5680 verifyGoogleFormat("DEBUG({\n" 5681 " if (a) return;\n" 5682 "});"); 5683 FormatStyle Style = getGoogleStyle(); 5684 Style.ColumnLimit = 45; 5685 verifyFormat("Debug(\n" 5686 " aaaaa,\n" 5687 " {\n" 5688 " if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n" 5689 " },\n" 5690 " a);", 5691 Style); 5692 5693 verifyFormat("SomeFunction({MACRO({ return output; }), b});"); 5694 5695 verifyNoCrash("^{v^{a}}"); 5696 } 5697 5698 TEST_F(FormatTest, FormatNestedBlocksInMacros) { 5699 EXPECT_EQ("#define MACRO() \\\n" 5700 " Debug(aaa, /* force line break */ \\\n" 5701 " { \\\n" 5702 " int i; \\\n" 5703 " int j; \\\n" 5704 " })", 5705 format("#define MACRO() Debug(aaa, /* force line break */ \\\n" 5706 " { int i; int j; })", 5707 getGoogleStyle())); 5708 5709 EXPECT_EQ("#define A \\\n" 5710 " [] { \\\n" 5711 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 5712 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n" 5713 " }", 5714 format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 5715 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }", 5716 getGoogleStyle())); 5717 } 5718 5719 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) { 5720 EXPECT_EQ("{}", format("{}")); 5721 verifyFormat("enum E {};"); 5722 verifyFormat("enum E {}"); 5723 FormatStyle Style = getLLVMStyle(); 5724 Style.SpaceInEmptyBlock = true; 5725 EXPECT_EQ("void f() { }", format("void f() {}", Style)); 5726 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 5727 EXPECT_EQ("while (true) { }", format("while (true) {}", Style)); 5728 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 5729 Style.BraceWrapping.BeforeElse = false; 5730 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 5731 verifyFormat("if (a)\n" 5732 "{\n" 5733 "} else if (b)\n" 5734 "{\n" 5735 "} else\n" 5736 "{ }", 5737 Style); 5738 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never; 5739 verifyFormat("if (a) {\n" 5740 "} else if (b) {\n" 5741 "} else {\n" 5742 "}", 5743 Style); 5744 Style.BraceWrapping.BeforeElse = true; 5745 verifyFormat("if (a) { }\n" 5746 "else if (b) { }\n" 5747 "else { }", 5748 Style); 5749 } 5750 5751 TEST_F(FormatTest, FormatBeginBlockEndMacros) { 5752 FormatStyle Style = getLLVMStyle(); 5753 Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$"; 5754 Style.MacroBlockEnd = "^[A-Z_]+_END$"; 5755 verifyFormat("FOO_BEGIN\n" 5756 " FOO_ENTRY\n" 5757 "FOO_END", 5758 Style); 5759 verifyFormat("FOO_BEGIN\n" 5760 " NESTED_FOO_BEGIN\n" 5761 " NESTED_FOO_ENTRY\n" 5762 " NESTED_FOO_END\n" 5763 "FOO_END", 5764 Style); 5765 verifyFormat("FOO_BEGIN(Foo, Bar)\n" 5766 " int x;\n" 5767 " x = 1;\n" 5768 "FOO_END(Baz)", 5769 Style); 5770 } 5771 5772 //===----------------------------------------------------------------------===// 5773 // Line break tests. 5774 //===----------------------------------------------------------------------===// 5775 5776 TEST_F(FormatTest, PreventConfusingIndents) { 5777 verifyFormat( 5778 "void f() {\n" 5779 " SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n" 5780 " parameter, parameter, parameter)),\n" 5781 " SecondLongCall(parameter));\n" 5782 "}"); 5783 verifyFormat( 5784 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5785 " aaaaaaaaaaaaaaaaaaaaaaaa(\n" 5786 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 5787 " aaaaaaaaaaaaaaaaaaaaaaaa);"); 5788 verifyFormat( 5789 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5790 " [aaaaaaaaaaaaaaaaaaaaaaaa\n" 5791 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n" 5792 " [aaaaaaaaaaaaaaaaaaaaaaaa]];"); 5793 verifyFormat( 5794 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 5795 " aaaaaaaaaaaaaaaaaaaaaaaa<\n" 5796 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n" 5797 " aaaaaaaaaaaaaaaaaaaaaaaa>;"); 5798 verifyFormat("int a = bbbb && ccc &&\n" 5799 " fffff(\n" 5800 "#define A Just forcing a new line\n" 5801 " ddd);"); 5802 } 5803 5804 TEST_F(FormatTest, LineBreakingInBinaryExpressions) { 5805 verifyFormat( 5806 "bool aaaaaaa =\n" 5807 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n" 5808 " bbbbbbbb();"); 5809 verifyFormat( 5810 "bool aaaaaaa =\n" 5811 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n" 5812 " bbbbbbbb();"); 5813 5814 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n" 5815 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n" 5816 " ccccccccc == ddddddddddd;"); 5817 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n" 5818 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n" 5819 " ccccccccc == ddddddddddd;"); 5820 verifyFormat( 5821 "bool aaaaaaaaaaaaaaaaaaaaa =\n" 5822 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n" 5823 " ccccccccc == ddddddddddd;"); 5824 5825 verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n" 5826 " aaaaaa) &&\n" 5827 " bbbbbb && cccccc;"); 5828 verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n" 5829 " aaaaaa) >>\n" 5830 " bbbbbb;"); 5831 verifyFormat("aa = Whitespaces.addUntouchableComment(\n" 5832 " SourceMgr.getSpellingColumnNumber(\n" 5833 " TheLine.Last->FormatTok.Tok.getLocation()) -\n" 5834 " 1);"); 5835 5836 verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 5837 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n" 5838 " cccccc) {\n}"); 5839 verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 5840 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n" 5841 " cccccc) {\n}"); 5842 verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 5843 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n" 5844 " cccccc) {\n}"); 5845 verifyFormat("b = a &&\n" 5846 " // Comment\n" 5847 " b.c && d;"); 5848 5849 // If the LHS of a comparison is not a binary expression itself, the 5850 // additional linebreak confuses many people. 5851 verifyFormat( 5852 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5853 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n" 5854 "}"); 5855 verifyFormat( 5856 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5857 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 5858 "}"); 5859 verifyFormat( 5860 "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n" 5861 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 5862 "}"); 5863 verifyFormat( 5864 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5865 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n" 5866 "}"); 5867 // Even explicit parentheses stress the precedence enough to make the 5868 // additional break unnecessary. 5869 verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5870 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 5871 "}"); 5872 // This cases is borderline, but with the indentation it is still readable. 5873 verifyFormat( 5874 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5875 " aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5876 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 5877 "}", 5878 getLLVMStyleWithColumns(75)); 5879 5880 // If the LHS is a binary expression, we should still use the additional break 5881 // as otherwise the formatting hides the operator precedence. 5882 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5883 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 5884 " 5) {\n" 5885 "}"); 5886 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5887 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n" 5888 " 5) {\n" 5889 "}"); 5890 5891 FormatStyle OnePerLine = getLLVMStyle(); 5892 OnePerLine.BinPackParameters = false; 5893 verifyFormat( 5894 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 5895 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 5896 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}", 5897 OnePerLine); 5898 5899 verifyFormat("int i = someFunction(aaaaaaa, 0)\n" 5900 " .aaa(aaaaaaaaaaaaa) *\n" 5901 " aaaaaaa +\n" 5902 " aaaaaaa;", 5903 getLLVMStyleWithColumns(40)); 5904 } 5905 5906 TEST_F(FormatTest, ExpressionIndentation) { 5907 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5908 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5909 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 5910 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 5911 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n" 5912 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n" 5913 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 5914 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n" 5915 " ccccccccccccccccccccccccccccccccccccccccc;"); 5916 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 5917 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5918 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 5919 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 5920 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5921 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 5922 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 5923 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 5924 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 5925 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 5926 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5927 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 5928 verifyFormat("if () {\n" 5929 "} else if (aaaaa && bbbbb > // break\n" 5930 " ccccc) {\n" 5931 "}"); 5932 verifyFormat("if () {\n" 5933 "} else if constexpr (aaaaa && bbbbb > // break\n" 5934 " ccccc) {\n" 5935 "}"); 5936 verifyFormat("if () {\n" 5937 "} else if CONSTEXPR (aaaaa && bbbbb > // break\n" 5938 " ccccc) {\n" 5939 "}"); 5940 verifyFormat("if () {\n" 5941 "} else if (aaaaa &&\n" 5942 " bbbbb > // break\n" 5943 " ccccc &&\n" 5944 " ddddd) {\n" 5945 "}"); 5946 5947 // Presence of a trailing comment used to change indentation of b. 5948 verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n" 5949 " b;\n" 5950 "return aaaaaaaaaaaaaaaaaaa +\n" 5951 " b; //", 5952 getLLVMStyleWithColumns(30)); 5953 } 5954 5955 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) { 5956 // Not sure what the best system is here. Like this, the LHS can be found 5957 // immediately above an operator (everything with the same or a higher 5958 // indent). The RHS is aligned right of the operator and so compasses 5959 // everything until something with the same indent as the operator is found. 5960 // FIXME: Is this a good system? 5961 FormatStyle Style = getLLVMStyle(); 5962 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 5963 verifyFormat( 5964 "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5965 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5966 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5967 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5968 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 5969 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 5970 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5971 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5972 " > ccccccccccccccccccccccccccccccccccccccccc;", 5973 Style); 5974 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5975 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5976 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5977 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 5978 Style); 5979 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5980 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5981 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5982 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 5983 Style); 5984 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5985 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5986 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5987 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 5988 Style); 5989 verifyFormat("if () {\n" 5990 "} else if (aaaaa\n" 5991 " && bbbbb // break\n" 5992 " > ccccc) {\n" 5993 "}", 5994 Style); 5995 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5996 " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 5997 Style); 5998 verifyFormat("return (a)\n" 5999 " // comment\n" 6000 " + b;", 6001 Style); 6002 verifyFormat( 6003 "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6004 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6005 " + cc;", 6006 Style); 6007 6008 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6009 " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 6010 Style); 6011 6012 // Forced by comments. 6013 verifyFormat( 6014 "unsigned ContentSize =\n" 6015 " sizeof(int16_t) // DWARF ARange version number\n" 6016 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6017 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6018 " + sizeof(int8_t); // Segment Size (in bytes)"); 6019 6020 verifyFormat("return boost::fusion::at_c<0>(iiii).second\n" 6021 " == boost::fusion::at_c<1>(iiii).second;", 6022 Style); 6023 6024 Style.ColumnLimit = 60; 6025 verifyFormat("zzzzzzzzzz\n" 6026 " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6027 " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);", 6028 Style); 6029 6030 Style.ColumnLimit = 80; 6031 Style.IndentWidth = 4; 6032 Style.TabWidth = 4; 6033 Style.UseTab = FormatStyle::UT_Always; 6034 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6035 Style.AlignOperands = FormatStyle::OAS_DontAlign; 6036 EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n" 6037 "\t&& (someOtherLongishConditionPart1\n" 6038 "\t\t|| someOtherEvenLongerNestedConditionPart2);", 6039 format("return someVeryVeryLongConditionThatBarelyFitsOnALine && " 6040 "(someOtherLongishConditionPart1 || " 6041 "someOtherEvenLongerNestedConditionPart2);", 6042 Style)); 6043 } 6044 6045 TEST_F(FormatTest, ExpressionIndentationStrictAlign) { 6046 FormatStyle Style = getLLVMStyle(); 6047 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 6048 Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator; 6049 6050 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6051 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6052 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6053 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6054 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6055 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6056 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6057 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6058 " > ccccccccccccccccccccccccccccccccccccccccc;", 6059 Style); 6060 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6061 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6062 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6063 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6064 Style); 6065 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6066 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6067 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6068 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6069 Style); 6070 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6071 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6072 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6073 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6074 Style); 6075 verifyFormat("if () {\n" 6076 "} else if (aaaaa\n" 6077 " && bbbbb // break\n" 6078 " > ccccc) {\n" 6079 "}", 6080 Style); 6081 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6082 " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6083 Style); 6084 verifyFormat("return (a)\n" 6085 " // comment\n" 6086 " + b;", 6087 Style); 6088 verifyFormat( 6089 "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6090 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6091 " + cc;", 6092 Style); 6093 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 6094 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 6095 " : 3333333333333333;", 6096 Style); 6097 verifyFormat( 6098 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 6099 " : ccccccccccccccc ? dddddddddddddddddd\n" 6100 " : eeeeeeeeeeeeeeeeee)\n" 6101 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 6102 " : 3333333333333333;", 6103 Style); 6104 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6105 " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 6106 Style); 6107 6108 verifyFormat("return boost::fusion::at_c<0>(iiii).second\n" 6109 " == boost::fusion::at_c<1>(iiii).second;", 6110 Style); 6111 6112 Style.ColumnLimit = 60; 6113 verifyFormat("zzzzzzzzzzzzz\n" 6114 " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6115 " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);", 6116 Style); 6117 6118 // Forced by comments. 6119 Style.ColumnLimit = 80; 6120 verifyFormat( 6121 "unsigned ContentSize\n" 6122 " = sizeof(int16_t) // DWARF ARange version number\n" 6123 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6124 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6125 " + sizeof(int8_t); // Segment Size (in bytes)", 6126 Style); 6127 6128 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6129 verifyFormat( 6130 "unsigned ContentSize =\n" 6131 " sizeof(int16_t) // DWARF ARange version number\n" 6132 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6133 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6134 " + sizeof(int8_t); // Segment Size (in bytes)", 6135 Style); 6136 6137 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 6138 verifyFormat( 6139 "unsigned ContentSize =\n" 6140 " sizeof(int16_t) // DWARF ARange version number\n" 6141 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6142 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6143 " + sizeof(int8_t); // Segment Size (in bytes)", 6144 Style); 6145 } 6146 6147 TEST_F(FormatTest, EnforcedOperatorWraps) { 6148 // Here we'd like to wrap after the || operators, but a comment is forcing an 6149 // earlier wrap. 6150 verifyFormat("bool x = aaaaa //\n" 6151 " || bbbbb\n" 6152 " //\n" 6153 " || cccc;"); 6154 } 6155 6156 TEST_F(FormatTest, NoOperandAlignment) { 6157 FormatStyle Style = getLLVMStyle(); 6158 Style.AlignOperands = FormatStyle::OAS_DontAlign; 6159 verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n" 6160 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6161 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 6162 Style); 6163 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6164 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6165 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6166 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6167 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6168 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6169 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6170 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6171 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6172 " > ccccccccccccccccccccccccccccccccccccccccc;", 6173 Style); 6174 6175 verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6176 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6177 " + cc;", 6178 Style); 6179 verifyFormat("int a = aa\n" 6180 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6181 " * cccccccccccccccccccccccccccccccccccc;\n", 6182 Style); 6183 6184 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6185 verifyFormat("return (a > b\n" 6186 " // comment1\n" 6187 " // comment2\n" 6188 " || c);", 6189 Style); 6190 } 6191 6192 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) { 6193 FormatStyle Style = getLLVMStyle(); 6194 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6195 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 6196 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6197 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6198 Style); 6199 } 6200 6201 TEST_F(FormatTest, AllowBinPackingInsideArguments) { 6202 FormatStyle Style = getLLVMStyleWithColumns(40); 6203 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6204 Style.BinPackArguments = false; 6205 verifyFormat("void test() {\n" 6206 " someFunction(\n" 6207 " this + argument + is + quite\n" 6208 " + long + so + it + gets + wrapped\n" 6209 " + but + remains + bin - packed);\n" 6210 "}", 6211 Style); 6212 verifyFormat("void test() {\n" 6213 " someFunction(arg1,\n" 6214 " this + argument + is\n" 6215 " + quite + long + so\n" 6216 " + it + gets + wrapped\n" 6217 " + but + remains + bin\n" 6218 " - packed,\n" 6219 " arg3);\n" 6220 "}", 6221 Style); 6222 verifyFormat("void test() {\n" 6223 " someFunction(\n" 6224 " arg1,\n" 6225 " this + argument + has\n" 6226 " + anotherFunc(nested,\n" 6227 " calls + whose\n" 6228 " + arguments\n" 6229 " + are + also\n" 6230 " + wrapped,\n" 6231 " in + addition)\n" 6232 " + to + being + bin - packed,\n" 6233 " arg3);\n" 6234 "}", 6235 Style); 6236 6237 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 6238 verifyFormat("void test() {\n" 6239 " someFunction(\n" 6240 " arg1,\n" 6241 " this + argument + has +\n" 6242 " anotherFunc(nested,\n" 6243 " calls + whose +\n" 6244 " arguments +\n" 6245 " are + also +\n" 6246 " wrapped,\n" 6247 " in + addition) +\n" 6248 " to + being + bin - packed,\n" 6249 " arg3);\n" 6250 "}", 6251 Style); 6252 } 6253 6254 TEST_F(FormatTest, ConstructorInitializers) { 6255 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}"); 6256 verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}", 6257 getLLVMStyleWithColumns(45)); 6258 verifyFormat("Constructor()\n" 6259 " : Inttializer(FitsOnTheLine) {}", 6260 getLLVMStyleWithColumns(44)); 6261 verifyFormat("Constructor()\n" 6262 " : Inttializer(FitsOnTheLine) {}", 6263 getLLVMStyleWithColumns(43)); 6264 6265 verifyFormat("template <typename T>\n" 6266 "Constructor() : Initializer(FitsOnTheLine) {}", 6267 getLLVMStyleWithColumns(45)); 6268 6269 verifyFormat( 6270 "SomeClass::Constructor()\n" 6271 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}"); 6272 6273 verifyFormat( 6274 "SomeClass::Constructor()\n" 6275 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6276 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}"); 6277 verifyFormat( 6278 "SomeClass::Constructor()\n" 6279 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6280 " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}"); 6281 verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6282 " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 6283 " : aaaaaaaaaa(aaaaaa) {}"); 6284 6285 verifyFormat("Constructor()\n" 6286 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6287 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6288 " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6289 " aaaaaaaaaaaaaaaaaaaaaaa() {}"); 6290 6291 verifyFormat("Constructor()\n" 6292 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6293 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 6294 6295 verifyFormat("Constructor(int Parameter = 0)\n" 6296 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n" 6297 " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}"); 6298 verifyFormat("Constructor()\n" 6299 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n" 6300 "}", 6301 getLLVMStyleWithColumns(60)); 6302 verifyFormat("Constructor()\n" 6303 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6304 " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}"); 6305 6306 // Here a line could be saved by splitting the second initializer onto two 6307 // lines, but that is not desirable. 6308 verifyFormat("Constructor()\n" 6309 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n" 6310 " aaaaaaaaaaa(aaaaaaaaaaa),\n" 6311 " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 6312 6313 FormatStyle OnePerLine = getLLVMStyle(); 6314 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_Never; 6315 verifyFormat("MyClass::MyClass()\n" 6316 " : a(a),\n" 6317 " b(b),\n" 6318 " c(c) {}", 6319 OnePerLine); 6320 verifyFormat("MyClass::MyClass()\n" 6321 " : a(a), // comment\n" 6322 " b(b),\n" 6323 " c(c) {}", 6324 OnePerLine); 6325 verifyFormat("MyClass::MyClass(int a)\n" 6326 " : b(a), // comment\n" 6327 " c(a + 1) { // lined up\n" 6328 "}", 6329 OnePerLine); 6330 verifyFormat("Constructor()\n" 6331 " : a(b, b, b) {}", 6332 OnePerLine); 6333 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6334 OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false; 6335 verifyFormat("SomeClass::Constructor()\n" 6336 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6337 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6338 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6339 OnePerLine); 6340 verifyFormat("SomeClass::Constructor()\n" 6341 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n" 6342 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6343 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6344 OnePerLine); 6345 verifyFormat("MyClass::MyClass(int var)\n" 6346 " : some_var_(var), // 4 space indent\n" 6347 " some_other_var_(var + 1) { // lined up\n" 6348 "}", 6349 OnePerLine); 6350 verifyFormat("Constructor()\n" 6351 " : aaaaa(aaaaaa),\n" 6352 " aaaaa(aaaaaa),\n" 6353 " aaaaa(aaaaaa),\n" 6354 " aaaaa(aaaaaa),\n" 6355 " aaaaa(aaaaaa) {}", 6356 OnePerLine); 6357 verifyFormat("Constructor()\n" 6358 " : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n" 6359 " aaaaaaaaaaaaaaaaaaaaaa) {}", 6360 OnePerLine); 6361 OnePerLine.BinPackParameters = false; 6362 verifyFormat( 6363 "Constructor()\n" 6364 " : aaaaaaaaaaaaaaaaaaaaaaaa(\n" 6365 " aaaaaaaaaaa().aaa(),\n" 6366 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6367 OnePerLine); 6368 OnePerLine.ColumnLimit = 60; 6369 verifyFormat("Constructor()\n" 6370 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6371 " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}", 6372 OnePerLine); 6373 6374 EXPECT_EQ("Constructor()\n" 6375 " : // Comment forcing unwanted break.\n" 6376 " aaaa(aaaa) {}", 6377 format("Constructor() :\n" 6378 " // Comment forcing unwanted break.\n" 6379 " aaaa(aaaa) {}")); 6380 } 6381 6382 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) { 6383 FormatStyle Style = getLLVMStyleWithColumns(60); 6384 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6385 Style.BinPackParameters = false; 6386 6387 for (int i = 0; i < 4; ++i) { 6388 // Test all combinations of parameters that should not have an effect. 6389 Style.AllowAllParametersOfDeclarationOnNextLine = i & 1; 6390 Style.AllowAllArgumentsOnNextLine = i & 2; 6391 6392 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6393 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6394 verifyFormat("Constructor()\n" 6395 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6396 Style); 6397 verifyFormat("Constructor() : a(a), b(b) {}", Style); 6398 6399 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6400 verifyFormat("Constructor()\n" 6401 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6402 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6403 Style); 6404 verifyFormat("Constructor() : a(a), b(b) {}", Style); 6405 6406 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 6407 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6408 verifyFormat("Constructor()\n" 6409 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6410 Style); 6411 6412 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6413 verifyFormat("Constructor()\n" 6414 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6415 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6416 Style); 6417 6418 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6419 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6420 verifyFormat("Constructor() :\n" 6421 " aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6422 Style); 6423 6424 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6425 verifyFormat("Constructor() :\n" 6426 " aaaaaaaaaaaaaaaaaa(a),\n" 6427 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6428 Style); 6429 } 6430 6431 // Test interactions between AllowAllParametersOfDeclarationOnNextLine and 6432 // AllowAllConstructorInitializersOnNextLine in all 6433 // BreakConstructorInitializers modes 6434 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6435 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6436 verifyFormat("SomeClassWithALongName::Constructor(\n" 6437 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n" 6438 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6439 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6440 Style); 6441 6442 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6443 verifyFormat("SomeClassWithALongName::Constructor(\n" 6444 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6445 " int bbbbbbbbbbbbb,\n" 6446 " int cccccccccccccccc)\n" 6447 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6448 Style); 6449 6450 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6451 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6452 verifyFormat("SomeClassWithALongName::Constructor(\n" 6453 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6454 " int bbbbbbbbbbbbb)\n" 6455 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6456 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6457 Style); 6458 6459 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 6460 6461 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6462 verifyFormat("SomeClassWithALongName::Constructor(\n" 6463 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n" 6464 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6465 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6466 Style); 6467 6468 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6469 verifyFormat("SomeClassWithALongName::Constructor(\n" 6470 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6471 " int bbbbbbbbbbbbb,\n" 6472 " int cccccccccccccccc)\n" 6473 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6474 Style); 6475 6476 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6477 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6478 verifyFormat("SomeClassWithALongName::Constructor(\n" 6479 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6480 " int bbbbbbbbbbbbb)\n" 6481 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6482 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6483 Style); 6484 6485 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6486 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6487 verifyFormat("SomeClassWithALongName::Constructor(\n" 6488 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n" 6489 " aaaaaaaaaaaaaaaaaaaa(a),\n" 6490 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6491 Style); 6492 6493 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6494 verifyFormat("SomeClassWithALongName::Constructor(\n" 6495 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6496 " int bbbbbbbbbbbbb,\n" 6497 " int cccccccccccccccc) :\n" 6498 " aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6499 Style); 6500 6501 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6502 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6503 verifyFormat("SomeClassWithALongName::Constructor(\n" 6504 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6505 " int bbbbbbbbbbbbb) :\n" 6506 " aaaaaaaaaaaaaaaaaaaa(a),\n" 6507 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6508 Style); 6509 } 6510 6511 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) { 6512 FormatStyle Style = getLLVMStyleWithColumns(60); 6513 Style.BinPackArguments = false; 6514 for (int i = 0; i < 4; ++i) { 6515 // Test all combinations of parameters that should not have an effect. 6516 Style.AllowAllParametersOfDeclarationOnNextLine = i & 1; 6517 Style.PackConstructorInitializers = 6518 i & 2 ? FormatStyle::PCIS_BinPack : FormatStyle::PCIS_Never; 6519 6520 Style.AllowAllArgumentsOnNextLine = true; 6521 verifyFormat("void foo() {\n" 6522 " FunctionCallWithReallyLongName(\n" 6523 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n" 6524 "}", 6525 Style); 6526 Style.AllowAllArgumentsOnNextLine = false; 6527 verifyFormat("void foo() {\n" 6528 " FunctionCallWithReallyLongName(\n" 6529 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6530 " bbbbbbbbbbbb);\n" 6531 "}", 6532 Style); 6533 6534 Style.AllowAllArgumentsOnNextLine = true; 6535 verifyFormat("void foo() {\n" 6536 " auto VariableWithReallyLongName = {\n" 6537 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n" 6538 "}", 6539 Style); 6540 Style.AllowAllArgumentsOnNextLine = false; 6541 verifyFormat("void foo() {\n" 6542 " auto VariableWithReallyLongName = {\n" 6543 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6544 " bbbbbbbbbbbb};\n" 6545 "}", 6546 Style); 6547 } 6548 6549 // This parameter should not affect declarations. 6550 Style.BinPackParameters = false; 6551 Style.AllowAllArgumentsOnNextLine = false; 6552 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6553 verifyFormat("void FunctionCallWithReallyLongName(\n" 6554 " int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);", 6555 Style); 6556 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6557 verifyFormat("void FunctionCallWithReallyLongName(\n" 6558 " int aaaaaaaaaaaaaaaaaaaaaaa,\n" 6559 " int bbbbbbbbbbbb);", 6560 Style); 6561 } 6562 6563 TEST_F(FormatTest, AllowAllArgumentsOnNextLineDontAlign) { 6564 // Check that AllowAllArgumentsOnNextLine is respected for both BAS_DontAlign 6565 // and BAS_Align. 6566 FormatStyle Style = getLLVMStyleWithColumns(35); 6567 StringRef Input = "functionCall(paramA, paramB, paramC);\n" 6568 "void functionDecl(int A, int B, int C);"; 6569 Style.AllowAllArgumentsOnNextLine = false; 6570 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6571 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6572 " paramC);\n" 6573 "void functionDecl(int A, int B,\n" 6574 " int C);"), 6575 format(Input, Style)); 6576 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 6577 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6578 " paramC);\n" 6579 "void functionDecl(int A, int B,\n" 6580 " int C);"), 6581 format(Input, Style)); 6582 // However, BAS_AlwaysBreak should take precedence over 6583 // AllowAllArgumentsOnNextLine. 6584 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 6585 EXPECT_EQ(StringRef("functionCall(\n" 6586 " paramA, paramB, paramC);\n" 6587 "void functionDecl(\n" 6588 " int A, int B, int C);"), 6589 format(Input, Style)); 6590 6591 // When AllowAllArgumentsOnNextLine is set, we prefer breaking before the 6592 // first argument. 6593 Style.AllowAllArgumentsOnNextLine = true; 6594 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 6595 EXPECT_EQ(StringRef("functionCall(\n" 6596 " paramA, paramB, paramC);\n" 6597 "void functionDecl(\n" 6598 " int A, int B, int C);"), 6599 format(Input, Style)); 6600 // It wouldn't fit on one line with aligned parameters so this setting 6601 // doesn't change anything for BAS_Align. 6602 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 6603 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6604 " paramC);\n" 6605 "void functionDecl(int A, int B,\n" 6606 " int C);"), 6607 format(Input, Style)); 6608 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6609 EXPECT_EQ(StringRef("functionCall(\n" 6610 " paramA, paramB, paramC);\n" 6611 "void functionDecl(\n" 6612 " int A, int B, int C);"), 6613 format(Input, Style)); 6614 } 6615 6616 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) { 6617 FormatStyle Style = getLLVMStyle(); 6618 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6619 6620 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}"); 6621 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}", 6622 getStyleWithColumns(Style, 45)); 6623 verifyFormat("Constructor() :\n" 6624 " Initializer(FitsOnTheLine) {}", 6625 getStyleWithColumns(Style, 44)); 6626 verifyFormat("Constructor() :\n" 6627 " Initializer(FitsOnTheLine) {}", 6628 getStyleWithColumns(Style, 43)); 6629 6630 verifyFormat("template <typename T>\n" 6631 "Constructor() : Initializer(FitsOnTheLine) {}", 6632 getStyleWithColumns(Style, 50)); 6633 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6634 verifyFormat( 6635 "SomeClass::Constructor() :\n" 6636 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 6637 Style); 6638 6639 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 6640 verifyFormat( 6641 "SomeClass::Constructor() :\n" 6642 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 6643 Style); 6644 6645 verifyFormat( 6646 "SomeClass::Constructor() :\n" 6647 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6648 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6649 Style); 6650 verifyFormat( 6651 "SomeClass::Constructor() :\n" 6652 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6653 " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 6654 Style); 6655 verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6656 " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 6657 " aaaaaaaaaa(aaaaaa) {}", 6658 Style); 6659 6660 verifyFormat("Constructor() :\n" 6661 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6662 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6663 " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6664 " aaaaaaaaaaaaaaaaaaaaaaa() {}", 6665 Style); 6666 6667 verifyFormat("Constructor() :\n" 6668 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6669 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6670 Style); 6671 6672 verifyFormat("Constructor(int Parameter = 0) :\n" 6673 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n" 6674 " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}", 6675 Style); 6676 verifyFormat("Constructor() :\n" 6677 " aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n" 6678 "}", 6679 getStyleWithColumns(Style, 60)); 6680 verifyFormat("Constructor() :\n" 6681 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6682 " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}", 6683 Style); 6684 6685 // Here a line could be saved by splitting the second initializer onto two 6686 // lines, but that is not desirable. 6687 verifyFormat("Constructor() :\n" 6688 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n" 6689 " aaaaaaaaaaa(aaaaaaaaaaa),\n" 6690 " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6691 Style); 6692 6693 FormatStyle OnePerLine = Style; 6694 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6695 verifyFormat("SomeClass::Constructor() :\n" 6696 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6697 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6698 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6699 OnePerLine); 6700 verifyFormat("SomeClass::Constructor() :\n" 6701 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n" 6702 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6703 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6704 OnePerLine); 6705 verifyFormat("MyClass::MyClass(int var) :\n" 6706 " some_var_(var), // 4 space indent\n" 6707 " some_other_var_(var + 1) { // lined up\n" 6708 "}", 6709 OnePerLine); 6710 verifyFormat("Constructor() :\n" 6711 " aaaaa(aaaaaa),\n" 6712 " aaaaa(aaaaaa),\n" 6713 " aaaaa(aaaaaa),\n" 6714 " aaaaa(aaaaaa),\n" 6715 " aaaaa(aaaaaa) {}", 6716 OnePerLine); 6717 verifyFormat("Constructor() :\n" 6718 " aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n" 6719 " aaaaaaaaaaaaaaaaaaaaaa) {}", 6720 OnePerLine); 6721 OnePerLine.BinPackParameters = false; 6722 verifyFormat("Constructor() :\n" 6723 " aaaaaaaaaaaaaaaaaaaaaaaa(\n" 6724 " aaaaaaaaaaa().aaa(),\n" 6725 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6726 OnePerLine); 6727 OnePerLine.ColumnLimit = 60; 6728 verifyFormat("Constructor() :\n" 6729 " aaaaaaaaaaaaaaaaaaaa(a),\n" 6730 " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}", 6731 OnePerLine); 6732 6733 EXPECT_EQ("Constructor() :\n" 6734 " // Comment forcing unwanted break.\n" 6735 " aaaa(aaaa) {}", 6736 format("Constructor() :\n" 6737 " // Comment forcing unwanted break.\n" 6738 " aaaa(aaaa) {}", 6739 Style)); 6740 6741 Style.ColumnLimit = 0; 6742 verifyFormat("SomeClass::Constructor() :\n" 6743 " a(a) {}", 6744 Style); 6745 verifyFormat("SomeClass::Constructor() noexcept :\n" 6746 " a(a) {}", 6747 Style); 6748 verifyFormat("SomeClass::Constructor() :\n" 6749 " a(a), b(b), c(c) {}", 6750 Style); 6751 verifyFormat("SomeClass::Constructor() :\n" 6752 " a(a) {\n" 6753 " foo();\n" 6754 " bar();\n" 6755 "}", 6756 Style); 6757 6758 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 6759 verifyFormat("SomeClass::Constructor() :\n" 6760 " a(a), b(b), c(c) {\n" 6761 "}", 6762 Style); 6763 verifyFormat("SomeClass::Constructor() :\n" 6764 " a(a) {\n" 6765 "}", 6766 Style); 6767 6768 Style.ColumnLimit = 80; 6769 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 6770 Style.ConstructorInitializerIndentWidth = 2; 6771 verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style); 6772 verifyFormat("SomeClass::Constructor() :\n" 6773 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6774 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}", 6775 Style); 6776 6777 // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as 6778 // well 6779 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 6780 verifyFormat( 6781 "class SomeClass\n" 6782 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6783 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 6784 Style); 6785 Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma; 6786 verifyFormat( 6787 "class SomeClass\n" 6788 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6789 " , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 6790 Style); 6791 Style.BreakInheritanceList = FormatStyle::BILS_AfterColon; 6792 verifyFormat( 6793 "class SomeClass :\n" 6794 " public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6795 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 6796 Style); 6797 Style.BreakInheritanceList = FormatStyle::BILS_AfterComma; 6798 verifyFormat( 6799 "class SomeClass\n" 6800 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6801 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 6802 Style); 6803 } 6804 6805 #ifndef EXPENSIVE_CHECKS 6806 // Expensive checks enables libstdc++ checking which includes validating the 6807 // state of ranges used in std::priority_queue - this blows out the 6808 // runtime/scalability of the function and makes this test unacceptably slow. 6809 TEST_F(FormatTest, MemoizationTests) { 6810 // This breaks if the memoization lookup does not take \c Indent and 6811 // \c LastSpace into account. 6812 verifyFormat( 6813 "extern CFRunLoopTimerRef\n" 6814 "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n" 6815 " CFTimeInterval interval, CFOptionFlags flags,\n" 6816 " CFIndex order, CFRunLoopTimerCallBack callout,\n" 6817 " CFRunLoopTimerContext *context) {}"); 6818 6819 // Deep nesting somewhat works around our memoization. 6820 verifyFormat( 6821 "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 6822 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 6823 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 6824 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 6825 " aaaaa())))))))))))))))))))))))))))))))))))))));", 6826 getLLVMStyleWithColumns(65)); 6827 verifyFormat( 6828 "aaaaa(\n" 6829 " aaaaa,\n" 6830 " aaaaa(\n" 6831 " aaaaa,\n" 6832 " aaaaa(\n" 6833 " aaaaa,\n" 6834 " aaaaa(\n" 6835 " aaaaa,\n" 6836 " aaaaa(\n" 6837 " aaaaa,\n" 6838 " aaaaa(\n" 6839 " aaaaa,\n" 6840 " aaaaa(\n" 6841 " aaaaa,\n" 6842 " aaaaa(\n" 6843 " aaaaa,\n" 6844 " aaaaa(\n" 6845 " aaaaa,\n" 6846 " aaaaa(\n" 6847 " aaaaa,\n" 6848 " aaaaa(\n" 6849 " aaaaa,\n" 6850 " aaaaa(\n" 6851 " aaaaa,\n" 6852 " aaaaa))))))))))));", 6853 getLLVMStyleWithColumns(65)); 6854 verifyFormat( 6855 "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" 6856 " a),\n" 6857 " a),\n" 6858 " a),\n" 6859 " a),\n" 6860 " a),\n" 6861 " a),\n" 6862 " a),\n" 6863 " a),\n" 6864 " a),\n" 6865 " a),\n" 6866 " a),\n" 6867 " a),\n" 6868 " a),\n" 6869 " a),\n" 6870 " a),\n" 6871 " a),\n" 6872 " a)", 6873 getLLVMStyleWithColumns(65)); 6874 6875 // This test takes VERY long when memoization is broken. 6876 FormatStyle OnePerLine = getLLVMStyle(); 6877 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6878 OnePerLine.BinPackParameters = false; 6879 std::string input = "Constructor()\n" 6880 " : aaaa(a,\n"; 6881 for (unsigned i = 0, e = 80; i != e; ++i) { 6882 input += " a,\n"; 6883 } 6884 input += " a) {}"; 6885 verifyFormat(input, OnePerLine); 6886 } 6887 #endif 6888 6889 TEST_F(FormatTest, BreaksAsHighAsPossible) { 6890 verifyFormat( 6891 "void f() {\n" 6892 " if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n" 6893 " (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n" 6894 " f();\n" 6895 "}"); 6896 verifyFormat("if (Intervals[i].getRange().getFirst() <\n" 6897 " Intervals[i - 1].getRange().getLast()) {\n}"); 6898 } 6899 6900 TEST_F(FormatTest, BreaksFunctionDeclarations) { 6901 // Principially, we break function declarations in a certain order: 6902 // 1) break amongst arguments. 6903 verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n" 6904 " Cccccccccccccc cccccccccccccc);"); 6905 verifyFormat("template <class TemplateIt>\n" 6906 "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n" 6907 " TemplateIt *stop) {}"); 6908 6909 // 2) break after return type. 6910 verifyFormat( 6911 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6912 "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);", 6913 getGoogleStyle()); 6914 6915 // 3) break after (. 6916 verifyFormat( 6917 "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n" 6918 " Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);", 6919 getGoogleStyle()); 6920 6921 // 4) break before after nested name specifiers. 6922 verifyFormat( 6923 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6924 "SomeClasssssssssssssssssssssssssssssssssssssss::\n" 6925 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);", 6926 getGoogleStyle()); 6927 6928 // However, there are exceptions, if a sufficient amount of lines can be 6929 // saved. 6930 // FIXME: The precise cut-offs wrt. the number of saved lines might need some 6931 // more adjusting. 6932 verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n" 6933 " Cccccccccccccc cccccccccc,\n" 6934 " Cccccccccccccc cccccccccc,\n" 6935 " Cccccccccccccc cccccccccc,\n" 6936 " Cccccccccccccc cccccccccc);"); 6937 verifyFormat( 6938 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6939 "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 6940 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 6941 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);", 6942 getGoogleStyle()); 6943 verifyFormat( 6944 "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n" 6945 " Cccccccccccccc cccccccccc,\n" 6946 " Cccccccccccccc cccccccccc,\n" 6947 " Cccccccccccccc cccccccccc,\n" 6948 " Cccccccccccccc cccccccccc,\n" 6949 " Cccccccccccccc cccccccccc,\n" 6950 " Cccccccccccccc cccccccccc);"); 6951 verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 6952 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 6953 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 6954 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 6955 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);"); 6956 6957 // Break after multi-line parameters. 6958 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6959 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6960 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6961 " bbbb bbbb);"); 6962 verifyFormat("void SomeLoooooooooooongFunction(\n" 6963 " std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n" 6964 " aaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6965 " int bbbbbbbbbbbbb);"); 6966 6967 // Treat overloaded operators like other functions. 6968 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 6969 "operator>(const SomeLoooooooooooooooooooooooooogType &other);"); 6970 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 6971 "operator>>(const SomeLooooooooooooooooooooooooogType &other);"); 6972 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 6973 "operator<<(const SomeLooooooooooooooooooooooooogType &other);"); 6974 verifyGoogleFormat( 6975 "SomeLoooooooooooooooooooooooooooooogType operator>>(\n" 6976 " const SomeLooooooooogType &a, const SomeLooooooooogType &b);"); 6977 verifyGoogleFormat( 6978 "SomeLoooooooooooooooooooooooooooooogType operator<<(\n" 6979 " const SomeLooooooooogType &a, const SomeLooooooooogType &b);"); 6980 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6981 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);"); 6982 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n" 6983 "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);"); 6984 verifyGoogleFormat( 6985 "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n" 6986 "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6987 " bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}"); 6988 verifyGoogleFormat("template <typename T>\n" 6989 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6990 "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n" 6991 " aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);"); 6992 6993 FormatStyle Style = getLLVMStyle(); 6994 Style.PointerAlignment = FormatStyle::PAS_Left; 6995 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6996 " aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}", 6997 Style); 6998 verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n" 6999 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7000 Style); 7001 } 7002 7003 TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) { 7004 // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516: 7005 // Prefer keeping `::` followed by `operator` together. 7006 EXPECT_EQ("const aaaa::bbbbbbb &\n" 7007 "ccccccccc::operator++() {\n" 7008 " stuff();\n" 7009 "}", 7010 format("const aaaa::bbbbbbb\n" 7011 "&ccccccccc::operator++() { stuff(); }", 7012 getLLVMStyleWithColumns(40))); 7013 } 7014 7015 TEST_F(FormatTest, TrailingReturnType) { 7016 verifyFormat("auto foo() -> int;\n"); 7017 // correct trailing return type spacing 7018 verifyFormat("auto operator->() -> int;\n"); 7019 verifyFormat("auto operator++(int) -> int;\n"); 7020 7021 verifyFormat("struct S {\n" 7022 " auto bar() const -> int;\n" 7023 "};"); 7024 verifyFormat("template <size_t Order, typename T>\n" 7025 "auto load_img(const std::string &filename)\n" 7026 " -> alias::tensor<Order, T, mem::tag::cpu> {}"); 7027 verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n" 7028 " -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}"); 7029 verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}"); 7030 verifyFormat("template <typename T>\n" 7031 "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n" 7032 " -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());"); 7033 7034 // Not trailing return types. 7035 verifyFormat("void f() { auto a = b->c(); }"); 7036 verifyFormat("auto a = p->foo();"); 7037 verifyFormat("int a = p->foo();"); 7038 verifyFormat("auto lmbd = [] NOEXCEPT -> int { return 0; };"); 7039 } 7040 7041 TEST_F(FormatTest, DeductionGuides) { 7042 verifyFormat("template <class T> A(const T &, const T &) -> A<T &>;"); 7043 verifyFormat("template <class T> explicit A(T &, T &&) -> A<T>;"); 7044 verifyFormat("template <class... Ts> S(Ts...) -> S<Ts...>;"); 7045 verifyFormat( 7046 "template <class... T>\n" 7047 "array(T &&...t) -> array<std::common_type_t<T...>, sizeof...(T)>;"); 7048 verifyFormat("template <class T> A() -> A<decltype(p->foo<3>())>;"); 7049 verifyFormat("template <class T> A() -> A<decltype(foo<traits<1>>)>;"); 7050 verifyFormat("template <class T> A() -> A<sizeof(p->foo<1>)>;"); 7051 verifyFormat("template <class T> A() -> A<(3 < 2)>;"); 7052 verifyFormat("template <class T> A() -> A<((3) < (2))>;"); 7053 verifyFormat("template <class T> x() -> x<1>;"); 7054 verifyFormat("template <class T> explicit x(T &) -> x<1>;"); 7055 7056 // Ensure not deduction guides. 7057 verifyFormat("c()->f<int>();"); 7058 verifyFormat("x()->foo<1>;"); 7059 verifyFormat("x = p->foo<3>();"); 7060 verifyFormat("x()->x<1>();"); 7061 verifyFormat("x()->x<1>;"); 7062 } 7063 7064 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) { 7065 // Avoid breaking before trailing 'const' or other trailing annotations, if 7066 // they are not function-like. 7067 FormatStyle Style = getGoogleStyleWithColumns(47); 7068 verifyFormat("void someLongFunction(\n" 7069 " int someLoooooooooooooongParameter) const {\n}", 7070 getLLVMStyleWithColumns(47)); 7071 verifyFormat("LoooooongReturnType\n" 7072 "someLoooooooongFunction() const {}", 7073 getLLVMStyleWithColumns(47)); 7074 verifyFormat("LoooooongReturnType someLoooooooongFunction()\n" 7075 " const {}", 7076 Style); 7077 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7078 " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;"); 7079 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7080 " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;"); 7081 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7082 " aaaaa aaaaaaaaaaaaaaaaaaaa) override final;"); 7083 verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n" 7084 " aaaaaaaaaaa aaaaa) const override;"); 7085 verifyGoogleFormat( 7086 "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7087 " const override;"); 7088 7089 // Even if the first parameter has to be wrapped. 7090 verifyFormat("void someLongFunction(\n" 7091 " int someLongParameter) const {}", 7092 getLLVMStyleWithColumns(46)); 7093 verifyFormat("void someLongFunction(\n" 7094 " int someLongParameter) const {}", 7095 Style); 7096 verifyFormat("void someLongFunction(\n" 7097 " int someLongParameter) override {}", 7098 Style); 7099 verifyFormat("void someLongFunction(\n" 7100 " int someLongParameter) OVERRIDE {}", 7101 Style); 7102 verifyFormat("void someLongFunction(\n" 7103 " int someLongParameter) final {}", 7104 Style); 7105 verifyFormat("void someLongFunction(\n" 7106 " int someLongParameter) FINAL {}", 7107 Style); 7108 verifyFormat("void someLongFunction(\n" 7109 " int parameter) const override {}", 7110 Style); 7111 7112 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 7113 verifyFormat("void someLongFunction(\n" 7114 " int someLongParameter) const\n" 7115 "{\n" 7116 "}", 7117 Style); 7118 7119 Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 7120 verifyFormat("void someLongFunction(\n" 7121 " int someLongParameter) const\n" 7122 " {\n" 7123 " }", 7124 Style); 7125 7126 // Unless these are unknown annotations. 7127 verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n" 7128 " aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7129 " LONG_AND_UGLY_ANNOTATION;"); 7130 7131 // Breaking before function-like trailing annotations is fine to keep them 7132 // close to their arguments. 7133 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7134 " LOCKS_EXCLUDED(aaaaaaaaaaaaa);"); 7135 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n" 7136 " LOCKS_EXCLUDED(aaaaaaaaaaaaa);"); 7137 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n" 7138 " LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}"); 7139 verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n" 7140 " AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);"); 7141 verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});"); 7142 7143 verifyFormat( 7144 "void aaaaaaaaaaaaaaaaaa()\n" 7145 " __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n" 7146 " aaaaaaaaaaaaaaaaaaaaaaaaa));"); 7147 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7148 " __attribute__((unused));"); 7149 verifyGoogleFormat( 7150 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7151 " GUARDED_BY(aaaaaaaaaaaa);"); 7152 verifyGoogleFormat( 7153 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7154 " GUARDED_BY(aaaaaaaaaaaa);"); 7155 verifyGoogleFormat( 7156 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n" 7157 " aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7158 verifyGoogleFormat( 7159 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n" 7160 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7161 } 7162 7163 TEST_F(FormatTest, FunctionAnnotations) { 7164 verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7165 "int OldFunction(const string ¶meter) {}"); 7166 verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7167 "string OldFunction(const string ¶meter) {}"); 7168 verifyFormat("template <typename T>\n" 7169 "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7170 "string OldFunction(const string ¶meter) {}"); 7171 7172 // Not function annotations. 7173 verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7174 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"); 7175 verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n" 7176 " ThisIsATestWithAReallyReallyReallyReallyLongName) {}"); 7177 verifyFormat("MACRO(abc).function() // wrap\n" 7178 " << abc;"); 7179 verifyFormat("MACRO(abc)->function() // wrap\n" 7180 " << abc;"); 7181 verifyFormat("MACRO(abc)::function() // wrap\n" 7182 " << abc;"); 7183 } 7184 7185 TEST_F(FormatTest, BreaksDesireably) { 7186 verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n" 7187 " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n" 7188 " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}"); 7189 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7190 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 7191 "}"); 7192 7193 verifyFormat( 7194 "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7195 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 7196 7197 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7198 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7199 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7200 7201 verifyFormat( 7202 "aaaaaaaa(aaaaaaaaaaaaa,\n" 7203 " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7204 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n" 7205 " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7206 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));"); 7207 7208 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 7209 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7210 7211 verifyFormat( 7212 "void f() {\n" 7213 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n" 7214 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 7215 "}"); 7216 verifyFormat( 7217 "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7218 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7219 verifyFormat( 7220 "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7221 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7222 verifyFormat( 7223 "aaaaaa(aaa,\n" 7224 " new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7225 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7226 " aaaa);"); 7227 verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7228 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7229 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7230 7231 // Indent consistently independent of call expression and unary operator. 7232 verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7233 " dddddddddddddddddddddddddddddd));"); 7234 verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7235 " dddddddddddddddddddddddddddddd));"); 7236 verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n" 7237 " dddddddddddddddddddddddddddddd));"); 7238 7239 // This test case breaks on an incorrect memoization, i.e. an optimization not 7240 // taking into account the StopAt value. 7241 verifyFormat( 7242 "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7243 " aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7244 " aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7245 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7246 7247 verifyFormat("{\n {\n {\n" 7248 " Annotation.SpaceRequiredBefore =\n" 7249 " Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n" 7250 " Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n" 7251 " }\n }\n}"); 7252 7253 // Break on an outer level if there was a break on an inner level. 7254 EXPECT_EQ("f(g(h(a, // comment\n" 7255 " b, c),\n" 7256 " d, e),\n" 7257 " x, y);", 7258 format("f(g(h(a, // comment\n" 7259 " b, c), d, e), x, y);")); 7260 7261 // Prefer breaking similar line breaks. 7262 verifyFormat( 7263 "const int kTrackingOptions = NSTrackingMouseMoved |\n" 7264 " NSTrackingMouseEnteredAndExited |\n" 7265 " NSTrackingActiveAlways;"); 7266 } 7267 7268 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) { 7269 FormatStyle NoBinPacking = getGoogleStyle(); 7270 NoBinPacking.BinPackParameters = false; 7271 NoBinPacking.BinPackArguments = true; 7272 verifyFormat("void f() {\n" 7273 " f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n" 7274 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 7275 "}", 7276 NoBinPacking); 7277 verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n" 7278 " int aaaaaaaaaaaaaaaaaaaa,\n" 7279 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7280 NoBinPacking); 7281 7282 NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false; 7283 verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7284 " vector<int> bbbbbbbbbbbbbbb);", 7285 NoBinPacking); 7286 // FIXME: This behavior difference is probably not wanted. However, currently 7287 // we cannot distinguish BreakBeforeParameter being set because of the wrapped 7288 // template arguments from BreakBeforeParameter being set because of the 7289 // one-per-line formatting. 7290 verifyFormat( 7291 "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n" 7292 " aaaaaaaaaa> aaaaaaaaaa);", 7293 NoBinPacking); 7294 verifyFormat( 7295 "void fffffffffff(\n" 7296 " aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n" 7297 " aaaaaaaaaa);"); 7298 } 7299 7300 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) { 7301 FormatStyle NoBinPacking = getGoogleStyle(); 7302 NoBinPacking.BinPackParameters = false; 7303 NoBinPacking.BinPackArguments = false; 7304 verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n" 7305 " aaaaaaaaaaaaaaaaaaaa,\n" 7306 " aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);", 7307 NoBinPacking); 7308 verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n" 7309 " aaaaaaaaaaaaa,\n" 7310 " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));", 7311 NoBinPacking); 7312 verifyFormat( 7313 "aaaaaaaa(aaaaaaaaaaaaa,\n" 7314 " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7315 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n" 7316 " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7317 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));", 7318 NoBinPacking); 7319 verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n" 7320 " .aaaaaaaaaaaaaaaaaa();", 7321 NoBinPacking); 7322 verifyFormat("void f() {\n" 7323 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7324 " aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n" 7325 "}", 7326 NoBinPacking); 7327 7328 verifyFormat( 7329 "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7330 " aaaaaaaaaaaa,\n" 7331 " aaaaaaaaaaaa);", 7332 NoBinPacking); 7333 verifyFormat( 7334 "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n" 7335 " ddddddddddddddddddddddddddddd),\n" 7336 " test);", 7337 NoBinPacking); 7338 7339 verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n" 7340 " aaaaaaaaaaaaaaaaaaaaaaa,\n" 7341 " aaaaaaaaaaaaaaaaaaaaaaa>\n" 7342 " aaaaaaaaaaaaaaaaaa;", 7343 NoBinPacking); 7344 verifyFormat("a(\"a\"\n" 7345 " \"a\",\n" 7346 " a);"); 7347 7348 NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false; 7349 verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n" 7350 " aaaaaaaaa,\n" 7351 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7352 NoBinPacking); 7353 verifyFormat( 7354 "void f() {\n" 7355 " aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n" 7356 " .aaaaaaa();\n" 7357 "}", 7358 NoBinPacking); 7359 verifyFormat( 7360 "template <class SomeType, class SomeOtherType>\n" 7361 "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}", 7362 NoBinPacking); 7363 } 7364 7365 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) { 7366 FormatStyle Style = getLLVMStyleWithColumns(15); 7367 Style.ExperimentalAutoDetectBinPacking = true; 7368 EXPECT_EQ("aaa(aaaa,\n" 7369 " aaaa,\n" 7370 " aaaa);\n" 7371 "aaa(aaaa,\n" 7372 " aaaa,\n" 7373 " aaaa);", 7374 format("aaa(aaaa,\n" // one-per-line 7375 " aaaa,\n" 7376 " aaaa );\n" 7377 "aaa(aaaa, aaaa, aaaa);", // inconclusive 7378 Style)); 7379 EXPECT_EQ("aaa(aaaa, aaaa,\n" 7380 " aaaa);\n" 7381 "aaa(aaaa, aaaa,\n" 7382 " aaaa);", 7383 format("aaa(aaaa, aaaa,\n" // bin-packed 7384 " aaaa );\n" 7385 "aaa(aaaa, aaaa, aaaa);", // inconclusive 7386 Style)); 7387 } 7388 7389 TEST_F(FormatTest, FormatsBuilderPattern) { 7390 verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n" 7391 " .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n" 7392 " .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n" 7393 " .StartsWith(\".init\", ORDER_INIT)\n" 7394 " .StartsWith(\".fini\", ORDER_FINI)\n" 7395 " .StartsWith(\".hash\", ORDER_HASH)\n" 7396 " .Default(ORDER_TEXT);\n"); 7397 7398 verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n" 7399 " aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();"); 7400 verifyFormat("aaaaaaa->aaaaaaa\n" 7401 " ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7402 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7403 " ->aaaaaaaa(aaaaaaaaaaaaaaa);"); 7404 verifyFormat( 7405 "aaaaaaa->aaaaaaa\n" 7406 " ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7407 " ->aaaaaaaa(aaaaaaaaaaaaaaa);"); 7408 verifyFormat( 7409 "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n" 7410 " aaaaaaaaaaaaaa);"); 7411 verifyFormat( 7412 "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n" 7413 " aaaaaa->aaaaaaaaaaaa()\n" 7414 " ->aaaaaaaaaaaaaaaa(\n" 7415 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7416 " ->aaaaaaaaaaaaaaaaa();"); 7417 verifyGoogleFormat( 7418 "void f() {\n" 7419 " someo->Add((new util::filetools::Handler(dir))\n" 7420 " ->OnEvent1(NewPermanentCallback(\n" 7421 " this, &HandlerHolderClass::EventHandlerCBA))\n" 7422 " ->OnEvent2(NewPermanentCallback(\n" 7423 " this, &HandlerHolderClass::EventHandlerCBB))\n" 7424 " ->OnEvent3(NewPermanentCallback(\n" 7425 " this, &HandlerHolderClass::EventHandlerCBC))\n" 7426 " ->OnEvent5(NewPermanentCallback(\n" 7427 " this, &HandlerHolderClass::EventHandlerCBD))\n" 7428 " ->OnEvent6(NewPermanentCallback(\n" 7429 " this, &HandlerHolderClass::EventHandlerCBE)));\n" 7430 "}"); 7431 7432 verifyFormat( 7433 "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();"); 7434 verifyFormat("aaaaaaaaaaaaaaa()\n" 7435 " .aaaaaaaaaaaaaaa()\n" 7436 " .aaaaaaaaaaaaaaa()\n" 7437 " .aaaaaaaaaaaaaaa()\n" 7438 " .aaaaaaaaaaaaaaa();"); 7439 verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7440 " .aaaaaaaaaaaaaaa()\n" 7441 " .aaaaaaaaaaaaaaa()\n" 7442 " .aaaaaaaaaaaaaaa();"); 7443 verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7444 " .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7445 " .aaaaaaaaaaaaaaa();"); 7446 verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n" 7447 " ->aaaaaaaaaaaaaae(0)\n" 7448 " ->aaaaaaaaaaaaaaa();"); 7449 7450 // Don't linewrap after very short segments. 7451 verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7452 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7453 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7454 verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7455 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7456 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7457 verifyFormat("aaa()\n" 7458 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7459 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7460 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7461 7462 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n" 7463 " .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7464 " .has<bbbbbbbbbbbbbbbbbbbbb>();"); 7465 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n" 7466 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 7467 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();"); 7468 7469 // Prefer not to break after empty parentheses. 7470 verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n" 7471 " First->LastNewlineOffset);"); 7472 7473 // Prefer not to create "hanging" indents. 7474 verifyFormat( 7475 "return !soooooooooooooome_map\n" 7476 " .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7477 " .second;"); 7478 verifyFormat( 7479 "return aaaaaaaaaaaaaaaa\n" 7480 " .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n" 7481 " .aaaa(aaaaaaaaaaaaaa);"); 7482 // No hanging indent here. 7483 verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n" 7484 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7485 verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n" 7486 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7487 verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n" 7488 " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7489 getLLVMStyleWithColumns(60)); 7490 verifyFormat("aaaaaaaaaaaaaaaaaa\n" 7491 " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n" 7492 " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7493 getLLVMStyleWithColumns(59)); 7494 verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7495 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7496 " .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7497 7498 // Dont break if only closing statements before member call 7499 verifyFormat("test() {\n" 7500 " ([]() -> {\n" 7501 " int b = 32;\n" 7502 " return 3;\n" 7503 " }).foo();\n" 7504 "}"); 7505 verifyFormat("test() {\n" 7506 " (\n" 7507 " []() -> {\n" 7508 " int b = 32;\n" 7509 " return 3;\n" 7510 " },\n" 7511 " foo, bar)\n" 7512 " .foo();\n" 7513 "}"); 7514 verifyFormat("test() {\n" 7515 " ([]() -> {\n" 7516 " int b = 32;\n" 7517 " return 3;\n" 7518 " })\n" 7519 " .foo()\n" 7520 " .bar();\n" 7521 "}"); 7522 verifyFormat("test() {\n" 7523 " ([]() -> {\n" 7524 " int b = 32;\n" 7525 " return 3;\n" 7526 " })\n" 7527 " .foo(\"aaaaaaaaaaaaaaaaa\"\n" 7528 " \"bbbb\");\n" 7529 "}", 7530 getLLVMStyleWithColumns(30)); 7531 } 7532 7533 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) { 7534 verifyFormat( 7535 "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 7536 " bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}"); 7537 verifyFormat( 7538 "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n" 7539 " bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}"); 7540 7541 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" 7542 " ccccccccccccccccccccccccc) {\n}"); 7543 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n" 7544 " ccccccccccccccccccccccccc) {\n}"); 7545 7546 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" 7547 " ccccccccccccccccccccccccc) {\n}"); 7548 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n" 7549 " ccccccccccccccccccccccccc) {\n}"); 7550 7551 verifyFormat( 7552 "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n" 7553 " ccccccccccccccccccccccccc) {\n}"); 7554 verifyFormat( 7555 "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n" 7556 " ccccccccccccccccccccccccc) {\n}"); 7557 7558 verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n" 7559 " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n" 7560 " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n" 7561 " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;"); 7562 verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n" 7563 " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n" 7564 " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n" 7565 " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;"); 7566 7567 verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n" 7568 " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n" 7569 " aaaaaaaaaaaaaaa != aa) {\n}"); 7570 verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n" 7571 " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n" 7572 " aaaaaaaaaaaaaaa != aa) {\n}"); 7573 } 7574 7575 TEST_F(FormatTest, BreaksAfterAssignments) { 7576 verifyFormat( 7577 "unsigned Cost =\n" 7578 " TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n" 7579 " SI->getPointerAddressSpaceee());\n"); 7580 verifyFormat( 7581 "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n" 7582 " Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());"); 7583 7584 verifyFormat( 7585 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n" 7586 " aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);"); 7587 verifyFormat("unsigned OriginalStartColumn =\n" 7588 " SourceMgr.getSpellingColumnNumber(\n" 7589 " Current.FormatTok.getStartOfNonWhitespace()) -\n" 7590 " 1;"); 7591 } 7592 7593 TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) { 7594 FormatStyle Style = getLLVMStyle(); 7595 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 7596 " bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;", 7597 Style); 7598 7599 Style.PenaltyBreakAssignment = 20; 7600 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n" 7601 " cccccccccccccccccccccccccc;", 7602 Style); 7603 } 7604 7605 TEST_F(FormatTest, AlignsAfterAssignments) { 7606 verifyFormat( 7607 "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7608 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7609 verifyFormat( 7610 "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7611 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7612 verifyFormat( 7613 "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7614 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7615 verifyFormat( 7616 "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7617 " aaaaaaaaaaaaaaaaaaaaaaaaa);"); 7618 verifyFormat( 7619 "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n" 7620 " aaaaaaaaaaaaaaaaaaaaaaaa +\n" 7621 " aaaaaaaaaaaaaaaaaaaaaaaa;"); 7622 } 7623 7624 TEST_F(FormatTest, AlignsAfterReturn) { 7625 verifyFormat( 7626 "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7627 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7628 verifyFormat( 7629 "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7630 " aaaaaaaaaaaaaaaaaaaaaaaaa);"); 7631 verifyFormat( 7632 "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n" 7633 " aaaaaaaaaaaaaaaaaaaaaa();"); 7634 verifyFormat( 7635 "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n" 7636 " aaaaaaaaaaaaaaaaaaaaaa());"); 7637 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7638 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7639 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7640 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n" 7641 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7642 verifyFormat("return\n" 7643 " // true if code is one of a or b.\n" 7644 " code == a || code == b;"); 7645 } 7646 7647 TEST_F(FormatTest, AlignsAfterOpenBracket) { 7648 verifyFormat( 7649 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n" 7650 " aaaaaaaaa aaaaaaa) {}"); 7651 verifyFormat( 7652 "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n" 7653 " aaaaaaaaaaa aaaaaaaaa);"); 7654 verifyFormat( 7655 "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n" 7656 " aaaaaaaaaaaaaaaaaaaaa));"); 7657 FormatStyle Style = getLLVMStyle(); 7658 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 7659 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7660 " aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}", 7661 Style); 7662 verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n" 7663 " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);", 7664 Style); 7665 verifyFormat("SomeLongVariableName->someFunction(\n" 7666 " foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));", 7667 Style); 7668 verifyFormat( 7669 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n" 7670 " aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7671 Style); 7672 verifyFormat( 7673 "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n" 7674 " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7675 Style); 7676 verifyFormat( 7677 "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n" 7678 " aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));", 7679 Style); 7680 7681 verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n" 7682 " ccccccc(aaaaaaaaaaaaaaaaa, //\n" 7683 " b));", 7684 Style); 7685 7686 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 7687 Style.BinPackArguments = false; 7688 Style.BinPackParameters = false; 7689 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7690 " aaaaaaaaaaa aaaaaaaa,\n" 7691 " aaaaaaaaa aaaaaaa,\n" 7692 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7693 Style); 7694 verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n" 7695 " aaaaaaaaaaa aaaaaaaaa,\n" 7696 " aaaaaaaaaaa aaaaaaaaa,\n" 7697 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7698 Style); 7699 verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n" 7700 " aaaaaaaaaaaaaaa,\n" 7701 " aaaaaaaaaaaaaaaaaaaaa,\n" 7702 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));", 7703 Style); 7704 verifyFormat( 7705 "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n" 7706 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));", 7707 Style); 7708 verifyFormat( 7709 "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n" 7710 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));", 7711 Style); 7712 verifyFormat( 7713 "aaaaaaaaaaaaaaaaaaaaaaaa(\n" 7714 " aaaaaaaaaaaaaaaaaaaaa(\n" 7715 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n" 7716 " aaaaaaaaaaaaaaaa);", 7717 Style); 7718 verifyFormat( 7719 "aaaaaaaaaaaaaaaaaaaaaaaa(\n" 7720 " aaaaaaaaaaaaaaaaaaaaa(\n" 7721 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n" 7722 " aaaaaaaaaaaaaaaa);", 7723 Style); 7724 } 7725 7726 TEST_F(FormatTest, ParenthesesAndOperandAlignment) { 7727 FormatStyle Style = getLLVMStyleWithColumns(40); 7728 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 7729 " bbbbbbbbbbbbbbbbbbbbbb);", 7730 Style); 7731 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 7732 Style.AlignOperands = FormatStyle::OAS_DontAlign; 7733 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 7734 " bbbbbbbbbbbbbbbbbbbbbb);", 7735 Style); 7736 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 7737 Style.AlignOperands = FormatStyle::OAS_Align; 7738 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 7739 " bbbbbbbbbbbbbbbbbbbbbb);", 7740 Style); 7741 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 7742 Style.AlignOperands = FormatStyle::OAS_DontAlign; 7743 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 7744 " bbbbbbbbbbbbbbbbbbbbbb);", 7745 Style); 7746 } 7747 7748 TEST_F(FormatTest, BreaksConditionalExpressions) { 7749 verifyFormat( 7750 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7751 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7752 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7753 verifyFormat( 7754 "aaaa(aaaaaaaaaa, aaaaaaaa,\n" 7755 " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7756 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7757 verifyFormat( 7758 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7759 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7760 verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n" 7761 " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7762 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7763 verifyFormat( 7764 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n" 7765 " : aaaaaaaaaaaaa);"); 7766 verifyFormat( 7767 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7768 " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7769 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7770 " aaaaaaaaaaaaa);"); 7771 verifyFormat( 7772 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7773 " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7774 " aaaaaaaaaaaaa);"); 7775 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7776 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7777 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7778 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7779 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7780 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7781 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7782 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7783 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7784 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7785 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7786 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7787 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7788 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7789 " ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7790 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7791 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7792 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7793 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7794 " : aaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7795 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n" 7796 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7797 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7798 " : aaaaaaaaaaaaaaaa;"); 7799 verifyFormat( 7800 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7801 " ? aaaaaaaaaaaaaaa\n" 7802 " : aaaaaaaaaaaaaaa;"); 7803 verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n" 7804 " aaaaaaaaa\n" 7805 " ? b\n" 7806 " : c);"); 7807 verifyFormat("return aaaa == bbbb\n" 7808 " // comment\n" 7809 " ? aaaa\n" 7810 " : bbbb;"); 7811 verifyFormat("unsigned Indent =\n" 7812 " format(TheLine.First,\n" 7813 " IndentForLevel[TheLine.Level] >= 0\n" 7814 " ? IndentForLevel[TheLine.Level]\n" 7815 " : TheLine * 2,\n" 7816 " TheLine.InPPDirective, PreviousEndOfLineColumn);", 7817 getLLVMStyleWithColumns(60)); 7818 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n" 7819 " ? aaaaaaaaaaaaaaa\n" 7820 " : bbbbbbbbbbbbbbb //\n" 7821 " ? ccccccccccccccc\n" 7822 " : ddddddddddddddd;"); 7823 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n" 7824 " ? aaaaaaaaaaaaaaa\n" 7825 " : (bbbbbbbbbbbbbbb //\n" 7826 " ? ccccccccccccccc\n" 7827 " : ddddddddddddddd);"); 7828 verifyFormat( 7829 "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7830 " ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7831 " aaaaaaaaaaaaaaaaaaaaa +\n" 7832 " aaaaaaaaaaaaaaaaaaaaa\n" 7833 " : aaaaaaaaaa;"); 7834 verifyFormat( 7835 "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7836 " : aaaaaaaaaaaaaaaaaaaaaa\n" 7837 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7838 7839 FormatStyle NoBinPacking = getLLVMStyle(); 7840 NoBinPacking.BinPackArguments = false; 7841 verifyFormat( 7842 "void f() {\n" 7843 " g(aaa,\n" 7844 " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n" 7845 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7846 " ? aaaaaaaaaaaaaaa\n" 7847 " : aaaaaaaaaaaaaaa);\n" 7848 "}", 7849 NoBinPacking); 7850 verifyFormat( 7851 "void f() {\n" 7852 " g(aaa,\n" 7853 " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n" 7854 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7855 " ?: aaaaaaaaaaaaaaa);\n" 7856 "}", 7857 NoBinPacking); 7858 7859 verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n" 7860 " // comment.\n" 7861 " ccccccccccccccccccccccccccccccccccccccc\n" 7862 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7863 " : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);"); 7864 7865 // Assignments in conditional expressions. Apparently not uncommon :-(. 7866 verifyFormat("return a != b\n" 7867 " // comment\n" 7868 " ? a = b\n" 7869 " : a = b;"); 7870 verifyFormat("return a != b\n" 7871 " // comment\n" 7872 " ? a = a != b\n" 7873 " // comment\n" 7874 " ? a = b\n" 7875 " : a\n" 7876 " : a;\n"); 7877 verifyFormat("return a != b\n" 7878 " // comment\n" 7879 " ? a\n" 7880 " : a = a != b\n" 7881 " // comment\n" 7882 " ? a = b\n" 7883 " : a;"); 7884 7885 // Chained conditionals 7886 FormatStyle Style = getLLVMStyleWithColumns(70); 7887 Style.AlignOperands = FormatStyle::OAS_Align; 7888 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 7889 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7890 " : 3333333333333333;", 7891 Style); 7892 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 7893 " : bbbbbbbbbb ? 2222222222222222\n" 7894 " : 3333333333333333;", 7895 Style); 7896 verifyFormat("return aaaaaaaaaa ? 1111111111111111\n" 7897 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 7898 " : 3333333333333333;", 7899 Style); 7900 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 7901 " : bbbbbbbbbbbbbb ? 222222\n" 7902 " : 333333;", 7903 Style); 7904 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 7905 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7906 " : cccccccccccccc ? 3333333333333333\n" 7907 " : 4444444444444444;", 7908 Style); 7909 verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc)\n" 7910 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7911 " : 3333333333333333;", 7912 Style); 7913 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 7914 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7915 " : (aaa ? bbb : ccc);", 7916 Style); 7917 verifyFormat( 7918 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 7919 " : cccccccccccccccccc)\n" 7920 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7921 " : 3333333333333333;", 7922 Style); 7923 verifyFormat( 7924 "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 7925 " : cccccccccccccccccc)\n" 7926 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7927 " : 3333333333333333;", 7928 Style); 7929 verifyFormat( 7930 "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 7931 " : dddddddddddddddddd)\n" 7932 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7933 " : 3333333333333333;", 7934 Style); 7935 verifyFormat( 7936 "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 7937 " : dddddddddddddddddd)\n" 7938 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7939 " : 3333333333333333;", 7940 Style); 7941 verifyFormat( 7942 "return aaaaaaaaa ? 1111111111111111\n" 7943 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7944 " : a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 7945 " : dddddddddddddddddd)\n", 7946 Style); 7947 verifyFormat( 7948 "return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 7949 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7950 " : (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 7951 " : cccccccccccccccccc);", 7952 Style); 7953 verifyFormat( 7954 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 7955 " : ccccccccccccccc ? dddddddddddddddddd\n" 7956 " : eeeeeeeeeeeeeeeeee)\n" 7957 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7958 " : 3333333333333333;", 7959 Style); 7960 verifyFormat( 7961 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 7962 " : ccccccccccccccc ? dddddddddddddddddd\n" 7963 " : eeeeeeeeeeeeeeeeee)\n" 7964 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7965 " : 3333333333333333;", 7966 Style); 7967 verifyFormat( 7968 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 7969 " : cccccccccccc ? dddddddddddddddddd\n" 7970 " : eeeeeeeeeeeeeeeeee)\n" 7971 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7972 " : 3333333333333333;", 7973 Style); 7974 verifyFormat( 7975 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 7976 " : cccccccccccccccccc\n" 7977 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7978 " : 3333333333333333;", 7979 Style); 7980 verifyFormat( 7981 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 7982 " : cccccccccccccccc ? dddddddddddddddddd\n" 7983 " : eeeeeeeeeeeeeeeeee\n" 7984 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7985 " : 3333333333333333;", 7986 Style); 7987 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa\n" 7988 " ? (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 7989 " : cccccccccccccccccc ? dddddddddddddddddd\n" 7990 " : eeeeeeeeeeeeeeeeee)\n" 7991 " : bbbbbbbbbbbbbbbbbbb ? 2222222222222222\n" 7992 " : 3333333333333333;", 7993 Style); 7994 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaa\n" 7995 " ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 7996 " : cccccccccccccccc ? dddddddddddddddddd\n" 7997 " : eeeeeeeeeeeeeeeeee\n" 7998 " : bbbbbbbbbbbbbbbbbbbbbbb ? 2222222222222222\n" 7999 " : 3333333333333333;", 8000 Style); 8001 8002 Style.AlignOperands = FormatStyle::OAS_DontAlign; 8003 Style.BreakBeforeTernaryOperators = false; 8004 // FIXME: Aligning the question marks is weird given DontAlign. 8005 // Consider disabling this alignment in this case. Also check whether this 8006 // will render the adjustment from https://reviews.llvm.org/D82199 8007 // unnecessary. 8008 verifyFormat("int x = aaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa :\n" 8009 " bbbb ? cccccccccccccccccc :\n" 8010 " ddddd;\n", 8011 Style); 8012 8013 EXPECT_EQ( 8014 "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n" 8015 " /*\n" 8016 " */\n" 8017 " function() {\n" 8018 " try {\n" 8019 " return JJJJJJJJJJJJJJ(\n" 8020 " pppppppppppppppppppppppppppppppppppppppppppppppppp);\n" 8021 " }\n" 8022 " } :\n" 8023 " function() {};", 8024 format( 8025 "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n" 8026 " /*\n" 8027 " */\n" 8028 " function() {\n" 8029 " try {\n" 8030 " return JJJJJJJJJJJJJJ(\n" 8031 " pppppppppppppppppppppppppppppppppppppppppppppppppp);\n" 8032 " }\n" 8033 " } :\n" 8034 " function() {};", 8035 getGoogleStyle(FormatStyle::LK_JavaScript))); 8036 } 8037 8038 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) { 8039 FormatStyle Style = getLLVMStyleWithColumns(70); 8040 Style.BreakBeforeTernaryOperators = false; 8041 verifyFormat( 8042 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8043 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8044 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8045 Style); 8046 verifyFormat( 8047 "aaaa(aaaaaaaaaa, aaaaaaaa,\n" 8048 " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8049 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8050 Style); 8051 verifyFormat( 8052 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8053 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8054 Style); 8055 verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n" 8056 " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8057 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8058 Style); 8059 verifyFormat( 8060 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n" 8061 " aaaaaaaaaaaaa);", 8062 Style); 8063 verifyFormat( 8064 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8065 " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8066 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8067 " aaaaaaaaaaaaa);", 8068 Style); 8069 verifyFormat( 8070 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8071 " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8072 " aaaaaaaaaaaaa);", 8073 Style); 8074 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8075 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8076 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 8077 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8078 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8079 Style); 8080 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8081 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8082 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8083 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 8084 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8085 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8086 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8087 Style); 8088 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8089 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n" 8090 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8091 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8092 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8093 Style); 8094 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8095 " aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8096 " aaaaaaaaaaaaaaaaaaaaaaaaaaa;", 8097 Style); 8098 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n" 8099 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8100 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8101 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 8102 Style); 8103 verifyFormat( 8104 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8105 " aaaaaaaaaaaaaaa :\n" 8106 " aaaaaaaaaaaaaaa;", 8107 Style); 8108 verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n" 8109 " aaaaaaaaa ?\n" 8110 " b :\n" 8111 " c);", 8112 Style); 8113 verifyFormat("unsigned Indent =\n" 8114 " format(TheLine.First,\n" 8115 " IndentForLevel[TheLine.Level] >= 0 ?\n" 8116 " IndentForLevel[TheLine.Level] :\n" 8117 " TheLine * 2,\n" 8118 " TheLine.InPPDirective, PreviousEndOfLineColumn);", 8119 Style); 8120 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n" 8121 " aaaaaaaaaaaaaaa :\n" 8122 " bbbbbbbbbbbbbbb ? //\n" 8123 " ccccccccccccccc :\n" 8124 " ddddddddddddddd;", 8125 Style); 8126 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n" 8127 " aaaaaaaaaaaaaaa :\n" 8128 " (bbbbbbbbbbbbbbb ? //\n" 8129 " ccccccccccccccc :\n" 8130 " ddddddddddddddd);", 8131 Style); 8132 verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8133 " /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n" 8134 " ccccccccccccccccccccccccccc;", 8135 Style); 8136 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8137 " aaaaa :\n" 8138 " bbbbbbbbbbbbbbb + cccccccccccccccc;", 8139 Style); 8140 8141 // Chained conditionals 8142 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8143 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8144 " 3333333333333333;", 8145 Style); 8146 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8147 " bbbbbbbbbb ? 2222222222222222 :\n" 8148 " 3333333333333333;", 8149 Style); 8150 verifyFormat("return aaaaaaaaaa ? 1111111111111111 :\n" 8151 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8152 " 3333333333333333;", 8153 Style); 8154 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8155 " bbbbbbbbbbbbbbbb ? 222222 :\n" 8156 " 333333;", 8157 Style); 8158 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8159 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8160 " cccccccccccccccc ? 3333333333333333 :\n" 8161 " 4444444444444444;", 8162 Style); 8163 verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc) :\n" 8164 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8165 " 3333333333333333;", 8166 Style); 8167 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8168 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8169 " (aaa ? bbb : ccc);", 8170 Style); 8171 verifyFormat( 8172 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8173 " cccccccccccccccccc) :\n" 8174 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8175 " 3333333333333333;", 8176 Style); 8177 verifyFormat( 8178 "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8179 " cccccccccccccccccc) :\n" 8180 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8181 " 3333333333333333;", 8182 Style); 8183 verifyFormat( 8184 "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8185 " dddddddddddddddddd) :\n" 8186 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8187 " 3333333333333333;", 8188 Style); 8189 verifyFormat( 8190 "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8191 " dddddddddddddddddd) :\n" 8192 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8193 " 3333333333333333;", 8194 Style); 8195 verifyFormat( 8196 "return aaaaaaaaa ? 1111111111111111 :\n" 8197 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8198 " a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8199 " dddddddddddddddddd)\n", 8200 Style); 8201 verifyFormat( 8202 "return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8203 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8204 " (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8205 " cccccccccccccccccc);", 8206 Style); 8207 verifyFormat( 8208 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8209 " ccccccccccccccccc ? dddddddddddddddddd :\n" 8210 " eeeeeeeeeeeeeeeeee) :\n" 8211 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8212 " 3333333333333333;", 8213 Style); 8214 verifyFormat( 8215 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8216 " ccccccccccccc ? dddddddddddddddddd :\n" 8217 " eeeeeeeeeeeeeeeeee) :\n" 8218 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8219 " 3333333333333333;", 8220 Style); 8221 verifyFormat( 8222 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8223 " ccccccccccccccccc ? dddddddddddddddddd :\n" 8224 " eeeeeeeeeeeeeeeeee) :\n" 8225 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8226 " 3333333333333333;", 8227 Style); 8228 verifyFormat( 8229 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8230 " cccccccccccccccccc :\n" 8231 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8232 " 3333333333333333;", 8233 Style); 8234 verifyFormat( 8235 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8236 " cccccccccccccccccc ? dddddddddddddddddd :\n" 8237 " eeeeeeeeeeeeeeeeee :\n" 8238 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8239 " 3333333333333333;", 8240 Style); 8241 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n" 8242 " (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8243 " cccccccccccccccccc ? dddddddddddddddddd :\n" 8244 " eeeeeeeeeeeeeeeeee) :\n" 8245 " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8246 " 3333333333333333;", 8247 Style); 8248 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n" 8249 " aaaaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8250 " cccccccccccccccccccc ? dddddddddddddddddd :\n" 8251 " eeeeeeeeeeeeeeeeee :\n" 8252 " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8253 " 3333333333333333;", 8254 Style); 8255 } 8256 8257 TEST_F(FormatTest, DeclarationsOfMultipleVariables) { 8258 verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n" 8259 " aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();"); 8260 verifyFormat("bool a = true, b = false;"); 8261 8262 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n" 8263 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n" 8264 " bbbbbbbbbbbbbbbbbbbbbbbbb =\n" 8265 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);"); 8266 verifyFormat( 8267 "bool aaaaaaaaaaaaaaaaaaaaa =\n" 8268 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n" 8269 " d = e && f;"); 8270 verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n" 8271 " c = cccccccccccccccccccc, d = dddddddddddddddddddd;"); 8272 verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n" 8273 " *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;"); 8274 verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n" 8275 " ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;"); 8276 8277 FormatStyle Style = getGoogleStyle(); 8278 Style.PointerAlignment = FormatStyle::PAS_Left; 8279 Style.DerivePointerAlignment = false; 8280 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8281 " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n" 8282 " *b = bbbbbbbbbbbbbbbbbbb;", 8283 Style); 8284 verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n" 8285 " *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;", 8286 Style); 8287 verifyFormat("vector<int*> a, b;", Style); 8288 verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style); 8289 } 8290 8291 TEST_F(FormatTest, ConditionalExpressionsInBrackets) { 8292 verifyFormat("arr[foo ? bar : baz];"); 8293 verifyFormat("f()[foo ? bar : baz];"); 8294 verifyFormat("(a + b)[foo ? bar : baz];"); 8295 verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];"); 8296 } 8297 8298 TEST_F(FormatTest, AlignsStringLiterals) { 8299 verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n" 8300 " \"short literal\");"); 8301 verifyFormat( 8302 "looooooooooooooooooooooooongFunction(\n" 8303 " \"short literal\"\n" 8304 " \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");"); 8305 verifyFormat("someFunction(\"Always break between multi-line\"\n" 8306 " \" string literals\",\n" 8307 " and, other, parameters);"); 8308 EXPECT_EQ("fun + \"1243\" /* comment */\n" 8309 " \"5678\";", 8310 format("fun + \"1243\" /* comment */\n" 8311 " \"5678\";", 8312 getLLVMStyleWithColumns(28))); 8313 EXPECT_EQ( 8314 "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 8315 " \"aaaaaaaaaaaaaaaaaaaaa\"\n" 8316 " \"aaaaaaaaaaaaaaaa\";", 8317 format("aaaaaa =" 8318 "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa " 8319 "aaaaaaaaaaaaaaaaaaaaa\" " 8320 "\"aaaaaaaaaaaaaaaa\";")); 8321 verifyFormat("a = a + \"a\"\n" 8322 " \"a\"\n" 8323 " \"a\";"); 8324 verifyFormat("f(\"a\", \"b\"\n" 8325 " \"c\");"); 8326 8327 verifyFormat( 8328 "#define LL_FORMAT \"ll\"\n" 8329 "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n" 8330 " \"d, ddddddddd: %\" LL_FORMAT \"d\");"); 8331 8332 verifyFormat("#define A(X) \\\n" 8333 " \"aaaaa\" #X \"bbbbbb\" \\\n" 8334 " \"ccccc\"", 8335 getLLVMStyleWithColumns(23)); 8336 verifyFormat("#define A \"def\"\n" 8337 "f(\"abc\" A \"ghi\"\n" 8338 " \"jkl\");"); 8339 8340 verifyFormat("f(L\"a\"\n" 8341 " L\"b\");"); 8342 verifyFormat("#define A(X) \\\n" 8343 " L\"aaaaa\" #X L\"bbbbbb\" \\\n" 8344 " L\"ccccc\"", 8345 getLLVMStyleWithColumns(25)); 8346 8347 verifyFormat("f(@\"a\"\n" 8348 " @\"b\");"); 8349 verifyFormat("NSString s = @\"a\"\n" 8350 " @\"b\"\n" 8351 " @\"c\";"); 8352 verifyFormat("NSString s = @\"a\"\n" 8353 " \"b\"\n" 8354 " \"c\";"); 8355 } 8356 8357 TEST_F(FormatTest, ReturnTypeBreakingStyle) { 8358 FormatStyle Style = getLLVMStyle(); 8359 // No declarations or definitions should be moved to own line. 8360 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None; 8361 verifyFormat("class A {\n" 8362 " int f() { return 1; }\n" 8363 " int g();\n" 8364 "};\n" 8365 "int f() { return 1; }\n" 8366 "int g();\n", 8367 Style); 8368 8369 // All declarations and definitions should have the return type moved to its 8370 // own line. 8371 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 8372 Style.TypenameMacros = {"LIST"}; 8373 verifyFormat("SomeType\n" 8374 "funcdecl(LIST(uint64_t));", 8375 Style); 8376 verifyFormat("class E {\n" 8377 " int\n" 8378 " f() {\n" 8379 " return 1;\n" 8380 " }\n" 8381 " int\n" 8382 " g();\n" 8383 "};\n" 8384 "int\n" 8385 "f() {\n" 8386 " return 1;\n" 8387 "}\n" 8388 "int\n" 8389 "g();\n", 8390 Style); 8391 8392 // Top-level definitions, and no kinds of declarations should have the 8393 // return type moved to its own line. 8394 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions; 8395 verifyFormat("class B {\n" 8396 " int f() { return 1; }\n" 8397 " int g();\n" 8398 "};\n" 8399 "int\n" 8400 "f() {\n" 8401 " return 1;\n" 8402 "}\n" 8403 "int g();\n", 8404 Style); 8405 8406 // Top-level definitions and declarations should have the return type moved 8407 // to its own line. 8408 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel; 8409 verifyFormat("class C {\n" 8410 " int f() { return 1; }\n" 8411 " int g();\n" 8412 "};\n" 8413 "int\n" 8414 "f() {\n" 8415 " return 1;\n" 8416 "}\n" 8417 "int\n" 8418 "g();\n", 8419 Style); 8420 8421 // All definitions should have the return type moved to its own line, but no 8422 // kinds of declarations. 8423 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions; 8424 verifyFormat("class D {\n" 8425 " int\n" 8426 " f() {\n" 8427 " return 1;\n" 8428 " }\n" 8429 " int g();\n" 8430 "};\n" 8431 "int\n" 8432 "f() {\n" 8433 " return 1;\n" 8434 "}\n" 8435 "int g();\n", 8436 Style); 8437 verifyFormat("const char *\n" 8438 "f(void) {\n" // Break here. 8439 " return \"\";\n" 8440 "}\n" 8441 "const char *bar(void);\n", // No break here. 8442 Style); 8443 verifyFormat("template <class T>\n" 8444 "T *\n" 8445 "f(T &c) {\n" // Break here. 8446 " return NULL;\n" 8447 "}\n" 8448 "template <class T> T *f(T &c);\n", // No break here. 8449 Style); 8450 verifyFormat("class C {\n" 8451 " int\n" 8452 " operator+() {\n" 8453 " return 1;\n" 8454 " }\n" 8455 " int\n" 8456 " operator()() {\n" 8457 " return 1;\n" 8458 " }\n" 8459 "};\n", 8460 Style); 8461 verifyFormat("void\n" 8462 "A::operator()() {}\n" 8463 "void\n" 8464 "A::operator>>() {}\n" 8465 "void\n" 8466 "A::operator+() {}\n" 8467 "void\n" 8468 "A::operator*() {}\n" 8469 "void\n" 8470 "A::operator->() {}\n" 8471 "void\n" 8472 "A::operator void *() {}\n" 8473 "void\n" 8474 "A::operator void &() {}\n" 8475 "void\n" 8476 "A::operator void &&() {}\n" 8477 "void\n" 8478 "A::operator char *() {}\n" 8479 "void\n" 8480 "A::operator[]() {}\n" 8481 "void\n" 8482 "A::operator!() {}\n" 8483 "void\n" 8484 "A::operator**() {}\n" 8485 "void\n" 8486 "A::operator<Foo> *() {}\n" 8487 "void\n" 8488 "A::operator<Foo> **() {}\n" 8489 "void\n" 8490 "A::operator<Foo> &() {}\n" 8491 "void\n" 8492 "A::operator void **() {}\n", 8493 Style); 8494 verifyFormat("constexpr auto\n" 8495 "operator()() const -> reference {}\n" 8496 "constexpr auto\n" 8497 "operator>>() const -> reference {}\n" 8498 "constexpr auto\n" 8499 "operator+() const -> reference {}\n" 8500 "constexpr auto\n" 8501 "operator*() const -> reference {}\n" 8502 "constexpr auto\n" 8503 "operator->() const -> reference {}\n" 8504 "constexpr auto\n" 8505 "operator++() const -> reference {}\n" 8506 "constexpr auto\n" 8507 "operator void *() const -> reference {}\n" 8508 "constexpr auto\n" 8509 "operator void **() const -> reference {}\n" 8510 "constexpr auto\n" 8511 "operator void *() const -> reference {}\n" 8512 "constexpr auto\n" 8513 "operator void &() const -> reference {}\n" 8514 "constexpr auto\n" 8515 "operator void &&() const -> reference {}\n" 8516 "constexpr auto\n" 8517 "operator char *() const -> reference {}\n" 8518 "constexpr auto\n" 8519 "operator!() const -> reference {}\n" 8520 "constexpr auto\n" 8521 "operator[]() const -> reference {}\n", 8522 Style); 8523 verifyFormat("void *operator new(std::size_t s);", // No break here. 8524 Style); 8525 verifyFormat("void *\n" 8526 "operator new(std::size_t s) {}", 8527 Style); 8528 verifyFormat("void *\n" 8529 "operator delete[](void *ptr) {}", 8530 Style); 8531 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 8532 verifyFormat("const char *\n" 8533 "f(void)\n" // Break here. 8534 "{\n" 8535 " return \"\";\n" 8536 "}\n" 8537 "const char *bar(void);\n", // No break here. 8538 Style); 8539 verifyFormat("template <class T>\n" 8540 "T *\n" // Problem here: no line break 8541 "f(T &c)\n" // Break here. 8542 "{\n" 8543 " return NULL;\n" 8544 "}\n" 8545 "template <class T> T *f(T &c);\n", // No break here. 8546 Style); 8547 verifyFormat("int\n" 8548 "foo(A<bool> a)\n" 8549 "{\n" 8550 " return a;\n" 8551 "}\n", 8552 Style); 8553 verifyFormat("int\n" 8554 "foo(A<8> a)\n" 8555 "{\n" 8556 " return a;\n" 8557 "}\n", 8558 Style); 8559 verifyFormat("int\n" 8560 "foo(A<B<bool>, 8> a)\n" 8561 "{\n" 8562 " return a;\n" 8563 "}\n", 8564 Style); 8565 verifyFormat("int\n" 8566 "foo(A<B<8>, bool> a)\n" 8567 "{\n" 8568 " return a;\n" 8569 "}\n", 8570 Style); 8571 verifyFormat("int\n" 8572 "foo(A<B<bool>, bool> a)\n" 8573 "{\n" 8574 " return a;\n" 8575 "}\n", 8576 Style); 8577 verifyFormat("int\n" 8578 "foo(A<B<8>, 8> a)\n" 8579 "{\n" 8580 " return a;\n" 8581 "}\n", 8582 Style); 8583 8584 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 8585 Style.BraceWrapping.AfterFunction = true; 8586 verifyFormat("int f(i);\n" // No break here. 8587 "int\n" // Break here. 8588 "f(i)\n" 8589 "{\n" 8590 " return i + 1;\n" 8591 "}\n" 8592 "int\n" // Break here. 8593 "f(i)\n" 8594 "{\n" 8595 " return i + 1;\n" 8596 "};", 8597 Style); 8598 verifyFormat("int f(a, b, c);\n" // No break here. 8599 "int\n" // Break here. 8600 "f(a, b, c)\n" // Break here. 8601 "short a, b;\n" 8602 "float c;\n" 8603 "{\n" 8604 " return a + b < c;\n" 8605 "}\n" 8606 "int\n" // Break here. 8607 "f(a, b, c)\n" // Break here. 8608 "short a, b;\n" 8609 "float c;\n" 8610 "{\n" 8611 " return a + b < c;\n" 8612 "};", 8613 Style); 8614 verifyFormat("byte *\n" // Break here. 8615 "f(a)\n" // Break here. 8616 "byte a[];\n" 8617 "{\n" 8618 " return a;\n" 8619 "}", 8620 Style); 8621 verifyFormat("bool f(int a, int) override;\n" 8622 "Bar g(int a, Bar) final;\n" 8623 "Bar h(a, Bar) final;", 8624 Style); 8625 verifyFormat("int\n" 8626 "f(a)", 8627 Style); 8628 verifyFormat("bool\n" 8629 "f(size_t = 0, bool b = false)\n" 8630 "{\n" 8631 " return !b;\n" 8632 "}", 8633 Style); 8634 8635 // The return breaking style doesn't affect: 8636 // * function and object definitions with attribute-like macros 8637 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 8638 " ABSL_GUARDED_BY(mutex) = {};", 8639 getGoogleStyleWithColumns(40)); 8640 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 8641 " ABSL_GUARDED_BY(mutex); // comment", 8642 getGoogleStyleWithColumns(40)); 8643 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 8644 " ABSL_GUARDED_BY(mutex1)\n" 8645 " ABSL_GUARDED_BY(mutex2);", 8646 getGoogleStyleWithColumns(40)); 8647 verifyFormat("Tttttt f(int a, int b)\n" 8648 " ABSL_GUARDED_BY(mutex1)\n" 8649 " ABSL_GUARDED_BY(mutex2);", 8650 getGoogleStyleWithColumns(40)); 8651 // * typedefs 8652 verifyFormat("typedef ATTR(X) char x;", getGoogleStyle()); 8653 8654 Style = getGNUStyle(); 8655 8656 // Test for comments at the end of function declarations. 8657 verifyFormat("void\n" 8658 "foo (int a, /*abc*/ int b) // def\n" 8659 "{\n" 8660 "}\n", 8661 Style); 8662 8663 verifyFormat("void\n" 8664 "foo (int a, /* abc */ int b) /* def */\n" 8665 "{\n" 8666 "}\n", 8667 Style); 8668 8669 // Definitions that should not break after return type 8670 verifyFormat("void foo (int a, int b); // def\n", Style); 8671 verifyFormat("void foo (int a, int b); /* def */\n", Style); 8672 verifyFormat("void foo (int a, int b);\n", Style); 8673 } 8674 8675 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) { 8676 FormatStyle NoBreak = getLLVMStyle(); 8677 NoBreak.AlwaysBreakBeforeMultilineStrings = false; 8678 FormatStyle Break = getLLVMStyle(); 8679 Break.AlwaysBreakBeforeMultilineStrings = true; 8680 verifyFormat("aaaa = \"bbbb\"\n" 8681 " \"cccc\";", 8682 NoBreak); 8683 verifyFormat("aaaa =\n" 8684 " \"bbbb\"\n" 8685 " \"cccc\";", 8686 Break); 8687 verifyFormat("aaaa(\"bbbb\"\n" 8688 " \"cccc\");", 8689 NoBreak); 8690 verifyFormat("aaaa(\n" 8691 " \"bbbb\"\n" 8692 " \"cccc\");", 8693 Break); 8694 verifyFormat("aaaa(qqq, \"bbbb\"\n" 8695 " \"cccc\");", 8696 NoBreak); 8697 verifyFormat("aaaa(qqq,\n" 8698 " \"bbbb\"\n" 8699 " \"cccc\");", 8700 Break); 8701 verifyFormat("aaaa(qqq,\n" 8702 " L\"bbbb\"\n" 8703 " L\"cccc\");", 8704 Break); 8705 verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n" 8706 " \"bbbb\"));", 8707 Break); 8708 verifyFormat("string s = someFunction(\n" 8709 " \"abc\"\n" 8710 " \"abc\");", 8711 Break); 8712 8713 // As we break before unary operators, breaking right after them is bad. 8714 verifyFormat("string foo = abc ? \"x\"\n" 8715 " \"blah blah blah blah blah blah\"\n" 8716 " : \"y\";", 8717 Break); 8718 8719 // Don't break if there is no column gain. 8720 verifyFormat("f(\"aaaa\"\n" 8721 " \"bbbb\");", 8722 Break); 8723 8724 // Treat literals with escaped newlines like multi-line string literals. 8725 EXPECT_EQ("x = \"a\\\n" 8726 "b\\\n" 8727 "c\";", 8728 format("x = \"a\\\n" 8729 "b\\\n" 8730 "c\";", 8731 NoBreak)); 8732 EXPECT_EQ("xxxx =\n" 8733 " \"a\\\n" 8734 "b\\\n" 8735 "c\";", 8736 format("xxxx = \"a\\\n" 8737 "b\\\n" 8738 "c\";", 8739 Break)); 8740 8741 EXPECT_EQ("NSString *const kString =\n" 8742 " @\"aaaa\"\n" 8743 " @\"bbbb\";", 8744 format("NSString *const kString = @\"aaaa\"\n" 8745 "@\"bbbb\";", 8746 Break)); 8747 8748 Break.ColumnLimit = 0; 8749 verifyFormat("const char *hello = \"hello llvm\";", Break); 8750 } 8751 8752 TEST_F(FormatTest, AlignsPipes) { 8753 verifyFormat( 8754 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8755 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8756 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8757 verifyFormat( 8758 "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n" 8759 " << aaaaaaaaaaaaaaaaaaaa;"); 8760 verifyFormat( 8761 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8762 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8763 verifyFormat( 8764 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 8765 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8766 verifyFormat( 8767 "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n" 8768 " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n" 8769 " << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";"); 8770 verifyFormat( 8771 "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8772 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8773 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8774 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8775 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8776 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8777 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 8778 verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n" 8779 " << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);"); 8780 verifyFormat( 8781 "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8782 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8783 verifyFormat( 8784 "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n" 8785 " aaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8786 8787 verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n" 8788 " << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();"); 8789 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8790 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8791 " aaaaaaaaaaaaaaaaaaaaa)\n" 8792 " << aaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8793 verifyFormat("LOG_IF(aaa == //\n" 8794 " bbb)\n" 8795 " << a << b;"); 8796 8797 // But sometimes, breaking before the first "<<" is desirable. 8798 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 8799 " << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);"); 8800 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n" 8801 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8802 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8803 verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n" 8804 " << BEF << IsTemplate << Description << E->getType();"); 8805 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 8806 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8807 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8808 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 8809 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8810 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8811 " << aaa;"); 8812 8813 verifyFormat( 8814 "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8815 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 8816 8817 // Incomplete string literal. 8818 EXPECT_EQ("llvm::errs() << \"\n" 8819 " << a;", 8820 format("llvm::errs() << \"\n<<a;")); 8821 8822 verifyFormat("void f() {\n" 8823 " CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n" 8824 " << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n" 8825 "}"); 8826 8827 // Handle 'endl'. 8828 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n" 8829 " << bbbbbbbbbbbbbbbbbbbbbb << endl;"); 8830 verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;"); 8831 8832 // Handle '\n'. 8833 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n" 8834 " << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";"); 8835 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n" 8836 " << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';"); 8837 verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n" 8838 " << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";"); 8839 verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";"); 8840 } 8841 8842 TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) { 8843 verifyFormat("return out << \"somepacket = {\\n\"\n" 8844 " << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n" 8845 " << \" bbbb = \" << pkt.bbbb << \"\\n\"\n" 8846 " << \" cccccc = \" << pkt.cccccc << \"\\n\"\n" 8847 " << \" ddd = [\" << pkt.ddd << \"]\\n\"\n" 8848 " << \"}\";"); 8849 8850 verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n" 8851 " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n" 8852 " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;"); 8853 verifyFormat( 8854 "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n" 8855 " << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n" 8856 " << \"ccccccccccccccccc = \" << ccccccccccccccccc\n" 8857 " << \"ddddddddddddddddd = \" << ddddddddddddddddd\n" 8858 " << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;"); 8859 verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n" 8860 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 8861 verifyFormat( 8862 "void f() {\n" 8863 " llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n" 8864 " << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 8865 "}"); 8866 8867 // Breaking before the first "<<" is generally not desirable. 8868 verifyFormat( 8869 "llvm::errs()\n" 8870 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8871 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8872 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8873 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 8874 getLLVMStyleWithColumns(70)); 8875 verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n" 8876 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8877 " << \"aaaaaaaaaaaaaaaaaaa: \"\n" 8878 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8879 " << \"aaaaaaaaaaaaaaaaaaa: \"\n" 8880 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 8881 getLLVMStyleWithColumns(70)); 8882 8883 verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n" 8884 " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n" 8885 " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;"); 8886 verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n" 8887 " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n" 8888 " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);"); 8889 verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n" 8890 " (aaaa + aaaa);", 8891 getLLVMStyleWithColumns(40)); 8892 verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n" 8893 " (aaaaaaa + aaaaa));", 8894 getLLVMStyleWithColumns(40)); 8895 verifyFormat( 8896 "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n" 8897 " SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n" 8898 " bbbbbbbbbbbbbbbbbbbbbbb);"); 8899 } 8900 8901 TEST_F(FormatTest, UnderstandsEquals) { 8902 verifyFormat( 8903 "aaaaaaaaaaaaaaaaa =\n" 8904 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8905 verifyFormat( 8906 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 8907 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 8908 verifyFormat( 8909 "if (a) {\n" 8910 " f();\n" 8911 "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 8912 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 8913 "}"); 8914 8915 verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 8916 " 100000000 + 10000000) {\n}"); 8917 } 8918 8919 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) { 8920 verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n" 8921 " .looooooooooooooooooooooooooooooooooooooongFunction();"); 8922 8923 verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n" 8924 " ->looooooooooooooooooooooooooooooooooooooongFunction();"); 8925 8926 verifyFormat( 8927 "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n" 8928 " Parameter2);"); 8929 8930 verifyFormat( 8931 "ShortObject->shortFunction(\n" 8932 " LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n" 8933 " LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);"); 8934 8935 verifyFormat("loooooooooooooongFunction(\n" 8936 " LoooooooooooooongObject->looooooooooooooooongFunction());"); 8937 8938 verifyFormat( 8939 "function(LoooooooooooooooooooooooooooooooooooongObject\n" 8940 " ->loooooooooooooooooooooooooooooooooooooooongFunction());"); 8941 8942 verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n" 8943 " .WillRepeatedly(Return(SomeValue));"); 8944 verifyFormat("void f() {\n" 8945 " EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n" 8946 " .Times(2)\n" 8947 " .WillRepeatedly(Return(SomeValue));\n" 8948 "}"); 8949 verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n" 8950 " ccccccccccccccccccccccc);"); 8951 verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8952 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8953 " .aaaaa(aaaaa),\n" 8954 " aaaaaaaaaaaaaaaaaaaaa);"); 8955 verifyFormat("void f() {\n" 8956 " aaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8957 " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n" 8958 "}"); 8959 verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8960 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8961 " .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8962 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8963 " aaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 8964 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8965 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8966 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8967 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n" 8968 "}"); 8969 8970 // Here, it is not necessary to wrap at "." or "->". 8971 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n" 8972 " aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 8973 verifyFormat( 8974 "aaaaaaaaaaa->aaaaaaaaa(\n" 8975 " aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8976 " aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n"); 8977 8978 verifyFormat( 8979 "aaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8980 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());"); 8981 verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n" 8982 " aaaaaaaaa()->aaaaaa()->aaaaa());"); 8983 verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n" 8984 " aaaaaaaaa()->aaaaaa()->aaaaa());"); 8985 8986 verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8987 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8988 " .a();"); 8989 8990 FormatStyle NoBinPacking = getLLVMStyle(); 8991 NoBinPacking.BinPackParameters = false; 8992 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n" 8993 " .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n" 8994 " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n" 8995 " aaaaaaaaaaaaaaaaaaa,\n" 8996 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8997 NoBinPacking); 8998 8999 // If there is a subsequent call, change to hanging indentation. 9000 verifyFormat( 9001 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9002 " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n" 9003 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9004 verifyFormat( 9005 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9006 " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));"); 9007 verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9008 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9009 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9010 verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9011 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9012 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());"); 9013 } 9014 9015 TEST_F(FormatTest, WrapsTemplateDeclarations) { 9016 verifyFormat("template <typename T>\n" 9017 "virtual void loooooooooooongFunction(int Param1, int Param2);"); 9018 verifyFormat("template <typename T>\n" 9019 "// T should be one of {A, B}.\n" 9020 "virtual void loooooooooooongFunction(int Param1, int Param2);"); 9021 verifyFormat( 9022 "template <typename T>\n" 9023 "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;"); 9024 verifyFormat("template <typename T>\n" 9025 "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n" 9026 " int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);"); 9027 verifyFormat( 9028 "template <typename T>\n" 9029 "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n" 9030 " int Paaaaaaaaaaaaaaaaaaaaram2);"); 9031 verifyFormat( 9032 "template <typename T>\n" 9033 "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n" 9034 " aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n" 9035 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9036 verifyFormat("template <typename T>\n" 9037 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9038 " int aaaaaaaaaaaaaaaaaaaaaa);"); 9039 verifyFormat( 9040 "template <typename T1, typename T2 = char, typename T3 = char,\n" 9041 " typename T4 = char>\n" 9042 "void f();"); 9043 verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n" 9044 " template <typename> class cccccccccccccccccccccc,\n" 9045 " typename ddddddddddddd>\n" 9046 "class C {};"); 9047 verifyFormat( 9048 "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n" 9049 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9050 9051 verifyFormat("void f() {\n" 9052 " a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n" 9053 " a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n" 9054 "}"); 9055 9056 verifyFormat("template <typename T> class C {};"); 9057 verifyFormat("template <typename T> void f();"); 9058 verifyFormat("template <typename T> void f() {}"); 9059 verifyFormat( 9060 "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n" 9061 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9062 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n" 9063 " new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n" 9064 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9065 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n" 9066 " bbbbbbbbbbbbbbbbbbbbbbbb);", 9067 getLLVMStyleWithColumns(72)); 9068 EXPECT_EQ("static_cast<A< //\n" 9069 " B> *>(\n" 9070 "\n" 9071 ");", 9072 format("static_cast<A<//\n" 9073 " B>*>(\n" 9074 "\n" 9075 " );")); 9076 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9077 " const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);"); 9078 9079 FormatStyle AlwaysBreak = getLLVMStyle(); 9080 AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 9081 verifyFormat("template <typename T>\nclass C {};", AlwaysBreak); 9082 verifyFormat("template <typename T>\nvoid f();", AlwaysBreak); 9083 verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak); 9084 verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9085 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n" 9086 " ccccccccccccccccccccccccccccccccccccccccccccccc);"); 9087 verifyFormat("template <template <typename> class Fooooooo,\n" 9088 " template <typename> class Baaaaaaar>\n" 9089 "struct C {};", 9090 AlwaysBreak); 9091 verifyFormat("template <typename T> // T can be A, B or C.\n" 9092 "struct C {};", 9093 AlwaysBreak); 9094 verifyFormat("template <enum E> class A {\n" 9095 "public:\n" 9096 " E *f();\n" 9097 "};"); 9098 9099 FormatStyle NeverBreak = getLLVMStyle(); 9100 NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No; 9101 verifyFormat("template <typename T> class C {};", NeverBreak); 9102 verifyFormat("template <typename T> void f();", NeverBreak); 9103 verifyFormat("template <typename T> void f() {}", NeverBreak); 9104 verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa " 9105 "bbbbbbbbbbbbbbbbbbbb) {}", 9106 NeverBreak); 9107 verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9108 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n" 9109 " ccccccccccccccccccccccccccccccccccccccccccccccc);", 9110 NeverBreak); 9111 verifyFormat("template <template <typename> class Fooooooo,\n" 9112 " template <typename> class Baaaaaaar>\n" 9113 "struct C {};", 9114 NeverBreak); 9115 verifyFormat("template <typename T> // T can be A, B or C.\n" 9116 "struct C {};", 9117 NeverBreak); 9118 verifyFormat("template <enum E> class A {\n" 9119 "public:\n" 9120 " E *f();\n" 9121 "};", 9122 NeverBreak); 9123 NeverBreak.PenaltyBreakTemplateDeclaration = 100; 9124 verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa " 9125 "bbbbbbbbbbbbbbbbbbbb) {}", 9126 NeverBreak); 9127 } 9128 9129 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) { 9130 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp); 9131 Style.ColumnLimit = 60; 9132 EXPECT_EQ("// Baseline - no comments.\n" 9133 "template <\n" 9134 " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n" 9135 "void f() {}", 9136 format("// Baseline - no comments.\n" 9137 "template <\n" 9138 " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n" 9139 "void f() {}", 9140 Style)); 9141 9142 EXPECT_EQ("template <\n" 9143 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9144 "void f() {}", 9145 format("template <\n" 9146 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9147 "void f() {}", 9148 Style)); 9149 9150 EXPECT_EQ( 9151 "template <\n" 9152 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n" 9153 "void f() {}", 9154 format("template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n" 9155 "void f() {}", 9156 Style)); 9157 9158 EXPECT_EQ( 9159 "template <\n" 9160 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9161 " // multiline\n" 9162 "void f() {}", 9163 format("template <\n" 9164 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9165 " // multiline\n" 9166 "void f() {}", 9167 Style)); 9168 9169 EXPECT_EQ( 9170 "template <typename aaaaaaaaaa<\n" 9171 " bbbbbbbbbbbb>::value> // trailing loooong\n" 9172 "void f() {}", 9173 format( 9174 "template <\n" 9175 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n" 9176 "void f() {}", 9177 Style)); 9178 } 9179 9180 TEST_F(FormatTest, WrapsTemplateParameters) { 9181 FormatStyle Style = getLLVMStyle(); 9182 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 9183 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 9184 verifyFormat( 9185 "template <typename... a> struct q {};\n" 9186 "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n" 9187 " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n" 9188 " y;", 9189 Style); 9190 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 9191 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 9192 verifyFormat( 9193 "template <typename... a> struct r {};\n" 9194 "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n" 9195 " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n" 9196 " y;", 9197 Style); 9198 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 9199 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 9200 verifyFormat("template <typename... a> struct s {};\n" 9201 "extern s<\n" 9202 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9203 "aaaaaaaaaaaaaaaaaaaaaa,\n" 9204 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9205 "aaaaaaaaaaaaaaaaaaaaaa>\n" 9206 " y;", 9207 Style); 9208 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 9209 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 9210 verifyFormat("template <typename... a> struct t {};\n" 9211 "extern t<\n" 9212 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9213 "aaaaaaaaaaaaaaaaaaaaaa,\n" 9214 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9215 "aaaaaaaaaaaaaaaaaaaaaa>\n" 9216 " y;", 9217 Style); 9218 } 9219 9220 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) { 9221 verifyFormat( 9222 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9223 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9224 verifyFormat( 9225 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9226 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9227 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());"); 9228 9229 // FIXME: Should we have the extra indent after the second break? 9230 verifyFormat( 9231 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9232 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9233 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9234 9235 verifyFormat( 9236 "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n" 9237 " cccccccccccccccccccccccccccccccccccccccccccccc());"); 9238 9239 // Breaking at nested name specifiers is generally not desirable. 9240 verifyFormat( 9241 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9242 " aaaaaaaaaaaaaaaaaaaaaaa);"); 9243 9244 verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n" 9245 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9246 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9247 " aaaaaaaaaaaaaaaaaaaaa);", 9248 getLLVMStyleWithColumns(74)); 9249 9250 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9251 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9252 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9253 } 9254 9255 TEST_F(FormatTest, UnderstandsTemplateParameters) { 9256 verifyFormat("A<int> a;"); 9257 verifyFormat("A<A<A<int>>> a;"); 9258 verifyFormat("A<A<A<int, 2>, 3>, 4> a;"); 9259 verifyFormat("bool x = a < 1 || 2 > a;"); 9260 verifyFormat("bool x = 5 < f<int>();"); 9261 verifyFormat("bool x = f<int>() > 5;"); 9262 verifyFormat("bool x = 5 < a<int>::x;"); 9263 verifyFormat("bool x = a < 4 ? a > 2 : false;"); 9264 verifyFormat("bool x = f() ? a < 2 : a > 2;"); 9265 9266 verifyGoogleFormat("A<A<int>> a;"); 9267 verifyGoogleFormat("A<A<A<int>>> a;"); 9268 verifyGoogleFormat("A<A<A<A<int>>>> a;"); 9269 verifyGoogleFormat("A<A<int> > a;"); 9270 verifyGoogleFormat("A<A<A<int> > > a;"); 9271 verifyGoogleFormat("A<A<A<A<int> > > > a;"); 9272 verifyGoogleFormat("A<::A<int>> a;"); 9273 verifyGoogleFormat("A<::A> a;"); 9274 verifyGoogleFormat("A< ::A> a;"); 9275 verifyGoogleFormat("A< ::A<int> > a;"); 9276 EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle())); 9277 EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle())); 9278 EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle())); 9279 EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle())); 9280 EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };", 9281 format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle())); 9282 9283 verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp)); 9284 9285 // template closer followed by a token that starts with > or = 9286 verifyFormat("bool b = a<1> > 1;"); 9287 verifyFormat("bool b = a<1> >= 1;"); 9288 verifyFormat("int i = a<1> >> 1;"); 9289 FormatStyle Style = getLLVMStyle(); 9290 Style.SpaceBeforeAssignmentOperators = false; 9291 verifyFormat("bool b= a<1> == 1;", Style); 9292 verifyFormat("a<int> = 1;", Style); 9293 verifyFormat("a<int> >>= 1;", Style); 9294 9295 verifyFormat("test < a | b >> c;"); 9296 verifyFormat("test<test<a | b>> c;"); 9297 verifyFormat("test >> a >> b;"); 9298 verifyFormat("test << a >> b;"); 9299 9300 verifyFormat("f<int>();"); 9301 verifyFormat("template <typename T> void f() {}"); 9302 verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;"); 9303 verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : " 9304 "sizeof(char)>::type>;"); 9305 verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};"); 9306 verifyFormat("f(a.operator()<A>());"); 9307 verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9308 " .template operator()<A>());", 9309 getLLVMStyleWithColumns(35)); 9310 9311 // Not template parameters. 9312 verifyFormat("return a < b && c > d;"); 9313 verifyFormat("void f() {\n" 9314 " while (a < b && c > d) {\n" 9315 " }\n" 9316 "}"); 9317 verifyFormat("template <typename... Types>\n" 9318 "typename enable_if<0 < sizeof...(Types)>::type Foo() {}"); 9319 9320 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9321 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);", 9322 getLLVMStyleWithColumns(60)); 9323 verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");"); 9324 verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}"); 9325 verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <"); 9326 verifyFormat("some_templated_type<decltype([](int i) { return i; })>"); 9327 } 9328 9329 TEST_F(FormatTest, UnderstandsShiftOperators) { 9330 verifyFormat("if (i < x >> 1)"); 9331 verifyFormat("while (i < x >> 1)"); 9332 verifyFormat("for (unsigned i = 0; i < i; ++i, v = v >> 1)"); 9333 verifyFormat("for (unsigned i = 0; i < x >> 1; ++i, v = v >> 1)"); 9334 verifyFormat( 9335 "for (std::vector<int>::iterator i = 0; i < x >> 1; ++i, v = v >> 1)"); 9336 verifyFormat("Foo.call<Bar<Function>>()"); 9337 verifyFormat("if (Foo.call<Bar<Function>>() == 0)"); 9338 verifyFormat("for (std::vector<std::pair<int>>::iterator i = 0; i < x >> 1; " 9339 "++i, v = v >> 1)"); 9340 verifyFormat("if (w<u<v<x>>, 1>::t)"); 9341 } 9342 9343 TEST_F(FormatTest, BitshiftOperatorWidth) { 9344 EXPECT_EQ("int a = 1 << 2; /* foo\n" 9345 " bar */", 9346 format("int a=1<<2; /* foo\n" 9347 " bar */")); 9348 9349 EXPECT_EQ("int b = 256 >> 1; /* foo\n" 9350 " bar */", 9351 format("int b =256>>1 ; /* foo\n" 9352 " bar */")); 9353 } 9354 9355 TEST_F(FormatTest, UnderstandsBinaryOperators) { 9356 verifyFormat("COMPARE(a, ==, b);"); 9357 verifyFormat("auto s = sizeof...(Ts) - 1;"); 9358 } 9359 9360 TEST_F(FormatTest, UnderstandsPointersToMembers) { 9361 verifyFormat("int A::*x;"); 9362 verifyFormat("int (S::*func)(void *);"); 9363 verifyFormat("void f() { int (S::*func)(void *); }"); 9364 verifyFormat("typedef bool *(Class::*Member)() const;"); 9365 verifyFormat("void f() {\n" 9366 " (a->*f)();\n" 9367 " a->*x;\n" 9368 " (a.*f)();\n" 9369 " ((*a).*f)();\n" 9370 " a.*x;\n" 9371 "}"); 9372 verifyFormat("void f() {\n" 9373 " (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n" 9374 " aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n" 9375 "}"); 9376 verifyFormat( 9377 "(aaaaaaaaaa->*bbbbbbb)(\n" 9378 " aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 9379 FormatStyle Style = getLLVMStyle(); 9380 Style.PointerAlignment = FormatStyle::PAS_Left; 9381 verifyFormat("typedef bool* (Class::*Member)() const;", Style); 9382 } 9383 9384 TEST_F(FormatTest, UnderstandsUnaryOperators) { 9385 verifyFormat("int a = -2;"); 9386 verifyFormat("f(-1, -2, -3);"); 9387 verifyFormat("a[-1] = 5;"); 9388 verifyFormat("int a = 5 + -2;"); 9389 verifyFormat("if (i == -1) {\n}"); 9390 verifyFormat("if (i != -1) {\n}"); 9391 verifyFormat("if (i > -1) {\n}"); 9392 verifyFormat("if (i < -1) {\n}"); 9393 verifyFormat("++(a->f());"); 9394 verifyFormat("--(a->f());"); 9395 verifyFormat("(a->f())++;"); 9396 verifyFormat("a[42]++;"); 9397 verifyFormat("if (!(a->f())) {\n}"); 9398 verifyFormat("if (!+i) {\n}"); 9399 verifyFormat("~&a;"); 9400 9401 verifyFormat("a-- > b;"); 9402 verifyFormat("b ? -a : c;"); 9403 verifyFormat("n * sizeof char16;"); 9404 verifyFormat("n * alignof char16;", getGoogleStyle()); 9405 verifyFormat("sizeof(char);"); 9406 verifyFormat("alignof(char);", getGoogleStyle()); 9407 9408 verifyFormat("return -1;"); 9409 verifyFormat("throw -1;"); 9410 verifyFormat("switch (a) {\n" 9411 "case -1:\n" 9412 " break;\n" 9413 "}"); 9414 verifyFormat("#define X -1"); 9415 verifyFormat("#define X -kConstant"); 9416 9417 verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};"); 9418 verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};"); 9419 9420 verifyFormat("int a = /* confusing comment */ -1;"); 9421 // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case. 9422 verifyFormat("int a = i /* confusing comment */++;"); 9423 9424 verifyFormat("co_yield -1;"); 9425 verifyFormat("co_return -1;"); 9426 9427 // Check that * is not treated as a binary operator when we set 9428 // PointerAlignment as PAS_Left after a keyword and not a declaration. 9429 FormatStyle PASLeftStyle = getLLVMStyle(); 9430 PASLeftStyle.PointerAlignment = FormatStyle::PAS_Left; 9431 verifyFormat("co_return *a;", PASLeftStyle); 9432 verifyFormat("co_await *a;", PASLeftStyle); 9433 verifyFormat("co_yield *a", PASLeftStyle); 9434 verifyFormat("return *a;", PASLeftStyle); 9435 } 9436 9437 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) { 9438 verifyFormat("if (!aaaaaaaaaa( // break\n" 9439 " aaaaa)) {\n" 9440 "}"); 9441 verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n" 9442 " aaaaa));"); 9443 verifyFormat("*aaa = aaaaaaa( // break\n" 9444 " bbbbbb);"); 9445 } 9446 9447 TEST_F(FormatTest, UnderstandsOverloadedOperators) { 9448 verifyFormat("bool operator<();"); 9449 verifyFormat("bool operator>();"); 9450 verifyFormat("bool operator=();"); 9451 verifyFormat("bool operator==();"); 9452 verifyFormat("bool operator!=();"); 9453 verifyFormat("int operator+();"); 9454 verifyFormat("int operator++();"); 9455 verifyFormat("int operator++(int) volatile noexcept;"); 9456 verifyFormat("bool operator,();"); 9457 verifyFormat("bool operator();"); 9458 verifyFormat("bool operator()();"); 9459 verifyFormat("bool operator[]();"); 9460 verifyFormat("operator bool();"); 9461 verifyFormat("operator int();"); 9462 verifyFormat("operator void *();"); 9463 verifyFormat("operator SomeType<int>();"); 9464 verifyFormat("operator SomeType<int, int>();"); 9465 verifyFormat("operator SomeType<SomeType<int>>();"); 9466 verifyFormat("operator< <>();"); 9467 verifyFormat("operator<< <>();"); 9468 verifyFormat("< <>"); 9469 9470 verifyFormat("void *operator new(std::size_t size);"); 9471 verifyFormat("void *operator new[](std::size_t size);"); 9472 verifyFormat("void operator delete(void *ptr);"); 9473 verifyFormat("void operator delete[](void *ptr);"); 9474 verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n" 9475 "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);"); 9476 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n" 9477 " aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;"); 9478 9479 verifyFormat( 9480 "ostream &operator<<(ostream &OutputStream,\n" 9481 " SomeReallyLongType WithSomeReallyLongValue);"); 9482 verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n" 9483 " const aaaaaaaaaaaaaaaaaaaaa &right) {\n" 9484 " return left.group < right.group;\n" 9485 "}"); 9486 verifyFormat("SomeType &operator=(const SomeType &S);"); 9487 verifyFormat("f.template operator()<int>();"); 9488 9489 verifyGoogleFormat("operator void*();"); 9490 verifyGoogleFormat("operator SomeType<SomeType<int>>();"); 9491 verifyGoogleFormat("operator ::A();"); 9492 9493 verifyFormat("using A::operator+;"); 9494 verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n" 9495 "int i;"); 9496 9497 // Calling an operator as a member function. 9498 verifyFormat("void f() { a.operator*(); }"); 9499 verifyFormat("void f() { a.operator*(b & b); }"); 9500 verifyFormat("void f() { a->operator&(a * b); }"); 9501 verifyFormat("void f() { NS::a.operator+(*b * *b); }"); 9502 // TODO: Calling an operator as a non-member function is hard to distinguish. 9503 // https://llvm.org/PR50629 9504 // verifyFormat("void f() { operator*(a & a); }"); 9505 // verifyFormat("void f() { operator&(a, b * b); }"); 9506 9507 verifyFormat("::operator delete(foo);"); 9508 verifyFormat("::operator new(n * sizeof(foo));"); 9509 verifyFormat("foo() { ::operator delete(foo); }"); 9510 verifyFormat("foo() { ::operator new(n * sizeof(foo)); }"); 9511 } 9512 9513 TEST_F(FormatTest, UnderstandsFunctionRefQualification) { 9514 verifyFormat("Deleted &operator=(const Deleted &) & = default;"); 9515 verifyFormat("Deleted &operator=(const Deleted &) && = delete;"); 9516 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;"); 9517 verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;"); 9518 verifyFormat("Deleted &operator=(const Deleted &) &;"); 9519 verifyFormat("Deleted &operator=(const Deleted &) &&;"); 9520 verifyFormat("SomeType MemberFunction(const Deleted &) &;"); 9521 verifyFormat("SomeType MemberFunction(const Deleted &) &&;"); 9522 verifyFormat("SomeType MemberFunction(const Deleted &) && {}"); 9523 verifyFormat("SomeType MemberFunction(const Deleted &) && final {}"); 9524 verifyFormat("SomeType MemberFunction(const Deleted &) && override {}"); 9525 verifyFormat("void Fn(T const &) const &;"); 9526 verifyFormat("void Fn(T const volatile &&) const volatile &&;"); 9527 verifyFormat("template <typename T>\n" 9528 "void F(T) && = delete;", 9529 getGoogleStyle()); 9530 9531 FormatStyle AlignLeft = getLLVMStyle(); 9532 AlignLeft.PointerAlignment = FormatStyle::PAS_Left; 9533 verifyFormat("void A::b() && {}", AlignLeft); 9534 verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft); 9535 verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;", 9536 AlignLeft); 9537 verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft); 9538 verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft); 9539 verifyFormat("auto Function(T t) & -> void {}", AlignLeft); 9540 verifyFormat("auto Function(T... t) & -> void {}", AlignLeft); 9541 verifyFormat("auto Function(T) & -> void {}", AlignLeft); 9542 verifyFormat("auto Function(T) & -> void;", AlignLeft); 9543 verifyFormat("void Fn(T const&) const&;", AlignLeft); 9544 verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft); 9545 9546 FormatStyle Spaces = getLLVMStyle(); 9547 Spaces.SpacesInCStyleCastParentheses = true; 9548 verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces); 9549 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces); 9550 verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces); 9551 verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces); 9552 9553 Spaces.SpacesInCStyleCastParentheses = false; 9554 Spaces.SpacesInParentheses = true; 9555 verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces); 9556 verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;", 9557 Spaces); 9558 verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces); 9559 verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces); 9560 9561 FormatStyle BreakTemplate = getLLVMStyle(); 9562 BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 9563 9564 verifyFormat("struct f {\n" 9565 " template <class T>\n" 9566 " int &foo(const std::string &str) &noexcept {}\n" 9567 "};", 9568 BreakTemplate); 9569 9570 verifyFormat("struct f {\n" 9571 " template <class T>\n" 9572 " int &foo(const std::string &str) &&noexcept {}\n" 9573 "};", 9574 BreakTemplate); 9575 9576 verifyFormat("struct f {\n" 9577 " template <class T>\n" 9578 " int &foo(const std::string &str) const &noexcept {}\n" 9579 "};", 9580 BreakTemplate); 9581 9582 verifyFormat("struct f {\n" 9583 " template <class T>\n" 9584 " int &foo(const std::string &str) const &noexcept {}\n" 9585 "};", 9586 BreakTemplate); 9587 9588 verifyFormat("struct f {\n" 9589 " template <class T>\n" 9590 " auto foo(const std::string &str) &&noexcept -> int & {}\n" 9591 "};", 9592 BreakTemplate); 9593 9594 FormatStyle AlignLeftBreakTemplate = getLLVMStyle(); 9595 AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations = 9596 FormatStyle::BTDS_Yes; 9597 AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left; 9598 9599 verifyFormat("struct f {\n" 9600 " template <class T>\n" 9601 " int& foo(const std::string& str) & noexcept {}\n" 9602 "};", 9603 AlignLeftBreakTemplate); 9604 9605 verifyFormat("struct f {\n" 9606 " template <class T>\n" 9607 " int& foo(const std::string& str) && noexcept {}\n" 9608 "};", 9609 AlignLeftBreakTemplate); 9610 9611 verifyFormat("struct f {\n" 9612 " template <class T>\n" 9613 " int& foo(const std::string& str) const& noexcept {}\n" 9614 "};", 9615 AlignLeftBreakTemplate); 9616 9617 verifyFormat("struct f {\n" 9618 " template <class T>\n" 9619 " int& foo(const std::string& str) const&& noexcept {}\n" 9620 "};", 9621 AlignLeftBreakTemplate); 9622 9623 verifyFormat("struct f {\n" 9624 " template <class T>\n" 9625 " auto foo(const std::string& str) && noexcept -> int& {}\n" 9626 "};", 9627 AlignLeftBreakTemplate); 9628 9629 // The `&` in `Type&` should not be confused with a trailing `&` of 9630 // DEPRECATED(reason) member function. 9631 verifyFormat("struct f {\n" 9632 " template <class T>\n" 9633 " DEPRECATED(reason)\n" 9634 " Type &foo(arguments) {}\n" 9635 "};", 9636 BreakTemplate); 9637 9638 verifyFormat("struct f {\n" 9639 " template <class T>\n" 9640 " DEPRECATED(reason)\n" 9641 " Type& foo(arguments) {}\n" 9642 "};", 9643 AlignLeftBreakTemplate); 9644 9645 verifyFormat("void (*foopt)(int) = &func;"); 9646 } 9647 9648 TEST_F(FormatTest, UnderstandsNewAndDelete) { 9649 verifyFormat("void f() {\n" 9650 " A *a = new A;\n" 9651 " A *a = new (placement) A;\n" 9652 " delete a;\n" 9653 " delete (A *)a;\n" 9654 "}"); 9655 verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n" 9656 " typename aaaaaaaaaaaaaaaaaaaaaaaa();"); 9657 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9658 " new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n" 9659 " typename aaaaaaaaaaaaaaaaaaaaaaaa();"); 9660 verifyFormat("delete[] h->p;"); 9661 9662 verifyFormat("void operator delete(void *foo) ATTRIB;"); 9663 verifyFormat("void operator new(void *foo) ATTRIB;"); 9664 verifyFormat("void operator delete[](void *foo) ATTRIB;"); 9665 verifyFormat("void operator delete(void *ptr) noexcept;"); 9666 } 9667 9668 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) { 9669 verifyFormat("int *f(int *a) {}"); 9670 verifyFormat("int main(int argc, char **argv) {}"); 9671 verifyFormat("Test::Test(int b) : a(b * b) {}"); 9672 verifyIndependentOfContext("f(a, *a);"); 9673 verifyFormat("void g() { f(*a); }"); 9674 verifyIndependentOfContext("int a = b * 10;"); 9675 verifyIndependentOfContext("int a = 10 * b;"); 9676 verifyIndependentOfContext("int a = b * c;"); 9677 verifyIndependentOfContext("int a += b * c;"); 9678 verifyIndependentOfContext("int a -= b * c;"); 9679 verifyIndependentOfContext("int a *= b * c;"); 9680 verifyIndependentOfContext("int a /= b * c;"); 9681 verifyIndependentOfContext("int a = *b;"); 9682 verifyIndependentOfContext("int a = *b * c;"); 9683 verifyIndependentOfContext("int a = b * *c;"); 9684 verifyIndependentOfContext("int a = b * (10);"); 9685 verifyIndependentOfContext("S << b * (10);"); 9686 verifyIndependentOfContext("return 10 * b;"); 9687 verifyIndependentOfContext("return *b * *c;"); 9688 verifyIndependentOfContext("return a & ~b;"); 9689 verifyIndependentOfContext("f(b ? *c : *d);"); 9690 verifyIndependentOfContext("int a = b ? *c : *d;"); 9691 verifyIndependentOfContext("*b = a;"); 9692 verifyIndependentOfContext("a * ~b;"); 9693 verifyIndependentOfContext("a * !b;"); 9694 verifyIndependentOfContext("a * +b;"); 9695 verifyIndependentOfContext("a * -b;"); 9696 verifyIndependentOfContext("a * ++b;"); 9697 verifyIndependentOfContext("a * --b;"); 9698 verifyIndependentOfContext("a[4] * b;"); 9699 verifyIndependentOfContext("a[a * a] = 1;"); 9700 verifyIndependentOfContext("f() * b;"); 9701 verifyIndependentOfContext("a * [self dostuff];"); 9702 verifyIndependentOfContext("int x = a * (a + b);"); 9703 verifyIndependentOfContext("(a *)(a + b);"); 9704 verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;"); 9705 verifyIndependentOfContext("int *pa = (int *)&a;"); 9706 verifyIndependentOfContext("return sizeof(int **);"); 9707 verifyIndependentOfContext("return sizeof(int ******);"); 9708 verifyIndependentOfContext("return (int **&)a;"); 9709 verifyIndependentOfContext("f((*PointerToArray)[10]);"); 9710 verifyFormat("void f(Type (*parameter)[10]) {}"); 9711 verifyFormat("void f(Type (¶meter)[10]) {}"); 9712 verifyGoogleFormat("return sizeof(int**);"); 9713 verifyIndependentOfContext("Type **A = static_cast<Type **>(P);"); 9714 verifyGoogleFormat("Type** A = static_cast<Type**>(P);"); 9715 verifyFormat("auto a = [](int **&, int ***) {};"); 9716 verifyFormat("auto PointerBinding = [](const char *S) {};"); 9717 verifyFormat("typedef typeof(int(int, int)) *MyFunc;"); 9718 verifyFormat("[](const decltype(*a) &value) {}"); 9719 verifyFormat("[](const typeof(*a) &value) {}"); 9720 verifyFormat("[](const _Atomic(a *) &value) {}"); 9721 verifyFormat("[](const __underlying_type(a) &value) {}"); 9722 verifyFormat("decltype(a * b) F();"); 9723 verifyFormat("typeof(a * b) F();"); 9724 verifyFormat("#define MACRO() [](A *a) { return 1; }"); 9725 verifyFormat("Constructor() : member([](A *a, B *b) {}) {}"); 9726 verifyIndependentOfContext("typedef void (*f)(int *a);"); 9727 verifyIndependentOfContext("int i{a * b};"); 9728 verifyIndependentOfContext("aaa && aaa->f();"); 9729 verifyIndependentOfContext("int x = ~*p;"); 9730 verifyFormat("Constructor() : a(a), area(width * height) {}"); 9731 verifyFormat("Constructor() : a(a), area(a, width * height) {}"); 9732 verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}"); 9733 verifyFormat("void f() { f(a, c * d); }"); 9734 verifyFormat("void f() { f(new a(), c * d); }"); 9735 verifyFormat("void f(const MyOverride &override);"); 9736 verifyFormat("void f(const MyFinal &final);"); 9737 verifyIndependentOfContext("bool a = f() && override.f();"); 9738 verifyIndependentOfContext("bool a = f() && final.f();"); 9739 9740 verifyIndependentOfContext("InvalidRegions[*R] = 0;"); 9741 9742 verifyIndependentOfContext("A<int *> a;"); 9743 verifyIndependentOfContext("A<int **> a;"); 9744 verifyIndependentOfContext("A<int *, int *> a;"); 9745 verifyIndependentOfContext("A<int *[]> a;"); 9746 verifyIndependentOfContext( 9747 "const char *const p = reinterpret_cast<const char *const>(q);"); 9748 verifyIndependentOfContext("A<int **, int **> a;"); 9749 verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);"); 9750 verifyFormat("for (char **a = b; *a; ++a) {\n}"); 9751 verifyFormat("for (; a && b;) {\n}"); 9752 verifyFormat("bool foo = true && [] { return false; }();"); 9753 9754 verifyFormat( 9755 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9756 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9757 9758 verifyGoogleFormat("int const* a = &b;"); 9759 verifyGoogleFormat("**outparam = 1;"); 9760 verifyGoogleFormat("*outparam = a * b;"); 9761 verifyGoogleFormat("int main(int argc, char** argv) {}"); 9762 verifyGoogleFormat("A<int*> a;"); 9763 verifyGoogleFormat("A<int**> a;"); 9764 verifyGoogleFormat("A<int*, int*> a;"); 9765 verifyGoogleFormat("A<int**, int**> a;"); 9766 verifyGoogleFormat("f(b ? *c : *d);"); 9767 verifyGoogleFormat("int a = b ? *c : *d;"); 9768 verifyGoogleFormat("Type* t = **x;"); 9769 verifyGoogleFormat("Type* t = *++*x;"); 9770 verifyGoogleFormat("*++*x;"); 9771 verifyGoogleFormat("Type* t = const_cast<T*>(&*x);"); 9772 verifyGoogleFormat("Type* t = x++ * y;"); 9773 verifyGoogleFormat( 9774 "const char* const p = reinterpret_cast<const char* const>(q);"); 9775 verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);"); 9776 verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);"); 9777 verifyGoogleFormat("template <typename T>\n" 9778 "void f(int i = 0, SomeType** temps = NULL);"); 9779 9780 FormatStyle Left = getLLVMStyle(); 9781 Left.PointerAlignment = FormatStyle::PAS_Left; 9782 verifyFormat("x = *a(x) = *a(y);", Left); 9783 verifyFormat("for (;; *a = b) {\n}", Left); 9784 verifyFormat("return *this += 1;", Left); 9785 verifyFormat("throw *x;", Left); 9786 verifyFormat("delete *x;", Left); 9787 verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left); 9788 verifyFormat("[](const decltype(*a)* ptr) {}", Left); 9789 verifyFormat("[](const typeof(*a)* ptr) {}", Left); 9790 verifyFormat("[](const _Atomic(a*)* ptr) {}", Left); 9791 verifyFormat("[](const __underlying_type(a)* ptr) {}", Left); 9792 verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left); 9793 verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left); 9794 verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left); 9795 verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left); 9796 9797 verifyIndependentOfContext("a = *(x + y);"); 9798 verifyIndependentOfContext("a = &(x + y);"); 9799 verifyIndependentOfContext("*(x + y).call();"); 9800 verifyIndependentOfContext("&(x + y)->call();"); 9801 verifyFormat("void f() { &(*I).first; }"); 9802 9803 verifyIndependentOfContext("f(b * /* confusing comment */ ++c);"); 9804 verifyFormat("f(* /* confusing comment */ foo);"); 9805 verifyFormat("void (* /*deleter*/)(const Slice &key, void *value)"); 9806 verifyFormat("void foo(int * // this is the first paramters\n" 9807 " ,\n" 9808 " int second);"); 9809 verifyFormat("double term = a * // first\n" 9810 " b;"); 9811 verifyFormat( 9812 "int *MyValues = {\n" 9813 " *A, // Operator detection might be confused by the '{'\n" 9814 " *BB // Operator detection might be confused by previous comment\n" 9815 "};"); 9816 9817 verifyIndependentOfContext("if (int *a = &b)"); 9818 verifyIndependentOfContext("if (int &a = *b)"); 9819 verifyIndependentOfContext("if (a & b[i])"); 9820 verifyIndependentOfContext("if constexpr (a & b[i])"); 9821 verifyIndependentOfContext("if CONSTEXPR (a & b[i])"); 9822 verifyIndependentOfContext("if (a * (b * c))"); 9823 verifyIndependentOfContext("if constexpr (a * (b * c))"); 9824 verifyIndependentOfContext("if CONSTEXPR (a * (b * c))"); 9825 verifyIndependentOfContext("if (a::b::c::d & b[i])"); 9826 verifyIndependentOfContext("if (*b[i])"); 9827 verifyIndependentOfContext("if (int *a = (&b))"); 9828 verifyIndependentOfContext("while (int *a = &b)"); 9829 verifyIndependentOfContext("while (a * (b * c))"); 9830 verifyIndependentOfContext("size = sizeof *a;"); 9831 verifyIndependentOfContext("if (a && (b = c))"); 9832 verifyFormat("void f() {\n" 9833 " for (const int &v : Values) {\n" 9834 " }\n" 9835 "}"); 9836 verifyFormat("for (int i = a * a; i < 10; ++i) {\n}"); 9837 verifyFormat("for (int i = 0; i < a * a; ++i) {\n}"); 9838 verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}"); 9839 9840 verifyFormat("#define A (!a * b)"); 9841 verifyFormat("#define MACRO \\\n" 9842 " int *i = a * b; \\\n" 9843 " void f(a *b);", 9844 getLLVMStyleWithColumns(19)); 9845 9846 verifyIndependentOfContext("A = new SomeType *[Length];"); 9847 verifyIndependentOfContext("A = new SomeType *[Length]();"); 9848 verifyIndependentOfContext("T **t = new T *;"); 9849 verifyIndependentOfContext("T **t = new T *();"); 9850 verifyGoogleFormat("A = new SomeType*[Length]();"); 9851 verifyGoogleFormat("A = new SomeType*[Length];"); 9852 verifyGoogleFormat("T** t = new T*;"); 9853 verifyGoogleFormat("T** t = new T*();"); 9854 9855 verifyFormat("STATIC_ASSERT((a & b) == 0);"); 9856 verifyFormat("STATIC_ASSERT(0 == (a & b));"); 9857 verifyFormat("template <bool a, bool b> " 9858 "typename t::if<x && y>::type f() {}"); 9859 verifyFormat("template <int *y> f() {}"); 9860 verifyFormat("vector<int *> v;"); 9861 verifyFormat("vector<int *const> v;"); 9862 verifyFormat("vector<int *const **const *> v;"); 9863 verifyFormat("vector<int *volatile> v;"); 9864 verifyFormat("vector<a *_Nonnull> v;"); 9865 verifyFormat("vector<a *_Nullable> v;"); 9866 verifyFormat("vector<a *_Null_unspecified> v;"); 9867 verifyFormat("vector<a *__ptr32> v;"); 9868 verifyFormat("vector<a *__ptr64> v;"); 9869 verifyFormat("vector<a *__capability> v;"); 9870 FormatStyle TypeMacros = getLLVMStyle(); 9871 TypeMacros.TypenameMacros = {"LIST"}; 9872 verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros); 9873 verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros); 9874 verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros); 9875 verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros); 9876 verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication 9877 9878 FormatStyle CustomQualifier = getLLVMStyle(); 9879 // Add identifiers that should not be parsed as a qualifier by default. 9880 CustomQualifier.AttributeMacros.push_back("__my_qualifier"); 9881 CustomQualifier.AttributeMacros.push_back("_My_qualifier"); 9882 CustomQualifier.AttributeMacros.push_back("my_other_qualifier"); 9883 verifyFormat("vector<a * __my_qualifier> parse_as_multiply;"); 9884 verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier); 9885 verifyFormat("vector<a * _My_qualifier> parse_as_multiply;"); 9886 verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier); 9887 verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;"); 9888 verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier); 9889 verifyFormat("vector<a * _NotAQualifier> v;"); 9890 verifyFormat("vector<a * __not_a_qualifier> v;"); 9891 verifyFormat("vector<a * b> v;"); 9892 verifyFormat("foo<b && false>();"); 9893 verifyFormat("foo<b & 1>();"); 9894 verifyFormat("decltype(*::std::declval<const T &>()) void F();"); 9895 verifyFormat("typeof(*::std::declval<const T &>()) void F();"); 9896 verifyFormat("_Atomic(*::std::declval<const T &>()) void F();"); 9897 verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();"); 9898 verifyFormat( 9899 "template <class T, class = typename std::enable_if<\n" 9900 " std::is_integral<T>::value &&\n" 9901 " (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n" 9902 "void F();", 9903 getLLVMStyleWithColumns(70)); 9904 verifyFormat("template <class T,\n" 9905 " class = typename std::enable_if<\n" 9906 " std::is_integral<T>::value &&\n" 9907 " (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n" 9908 " class U>\n" 9909 "void F();", 9910 getLLVMStyleWithColumns(70)); 9911 verifyFormat( 9912 "template <class T,\n" 9913 " class = typename ::std::enable_if<\n" 9914 " ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n" 9915 "void F();", 9916 getGoogleStyleWithColumns(68)); 9917 9918 verifyIndependentOfContext("MACRO(int *i);"); 9919 verifyIndependentOfContext("MACRO(auto *a);"); 9920 verifyIndependentOfContext("MACRO(const A *a);"); 9921 verifyIndependentOfContext("MACRO(_Atomic(A) *a);"); 9922 verifyIndependentOfContext("MACRO(decltype(A) *a);"); 9923 verifyIndependentOfContext("MACRO(typeof(A) *a);"); 9924 verifyIndependentOfContext("MACRO(__underlying_type(A) *a);"); 9925 verifyIndependentOfContext("MACRO(A *const a);"); 9926 verifyIndependentOfContext("MACRO(A *restrict a);"); 9927 verifyIndependentOfContext("MACRO(A *__restrict__ a);"); 9928 verifyIndependentOfContext("MACRO(A *__restrict a);"); 9929 verifyIndependentOfContext("MACRO(A *volatile a);"); 9930 verifyIndependentOfContext("MACRO(A *__volatile a);"); 9931 verifyIndependentOfContext("MACRO(A *__volatile__ a);"); 9932 verifyIndependentOfContext("MACRO(A *_Nonnull a);"); 9933 verifyIndependentOfContext("MACRO(A *_Nullable a);"); 9934 verifyIndependentOfContext("MACRO(A *_Null_unspecified a);"); 9935 verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);"); 9936 verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);"); 9937 verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);"); 9938 verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);"); 9939 verifyIndependentOfContext("MACRO(A *__ptr32 a);"); 9940 verifyIndependentOfContext("MACRO(A *__ptr64 a);"); 9941 verifyIndependentOfContext("MACRO(A *__capability);"); 9942 verifyIndependentOfContext("MACRO(A &__capability);"); 9943 verifyFormat("MACRO(A *__my_qualifier);"); // type declaration 9944 verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication 9945 // If we add __my_qualifier to AttributeMacros it should always be parsed as 9946 // a type declaration: 9947 verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier); 9948 verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier); 9949 // Also check that TypenameMacros prevents parsing it as multiplication: 9950 verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication 9951 verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type 9952 9953 verifyIndependentOfContext("MACRO('0' <= c && c <= '9');"); 9954 verifyFormat("void f() { f(float{1}, a * a); }"); 9955 verifyFormat("void f() { f(float(1), a * a); }"); 9956 9957 verifyFormat("f((void (*)(int))g);"); 9958 verifyFormat("f((void (&)(int))g);"); 9959 verifyFormat("f((void (^)(int))g);"); 9960 9961 // FIXME: Is there a way to make this work? 9962 // verifyIndependentOfContext("MACRO(A *a);"); 9963 verifyFormat("MACRO(A &B);"); 9964 verifyFormat("MACRO(A *B);"); 9965 verifyFormat("void f() { MACRO(A * B); }"); 9966 verifyFormat("void f() { MACRO(A & B); }"); 9967 9968 // This lambda was mis-formatted after D88956 (treating it as a binop): 9969 verifyFormat("auto x = [](const decltype(x) &ptr) {};"); 9970 verifyFormat("auto x = [](const decltype(x) *ptr) {};"); 9971 verifyFormat("#define lambda [](const decltype(x) &ptr) {}"); 9972 verifyFormat("#define lambda [](const decltype(x) *ptr) {}"); 9973 9974 verifyFormat("DatumHandle const *operator->() const { return input_; }"); 9975 verifyFormat("return options != nullptr && operator==(*options);"); 9976 9977 EXPECT_EQ("#define OP(x) \\\n" 9978 " ostream &operator<<(ostream &s, const A &a) { \\\n" 9979 " return s << a.DebugString(); \\\n" 9980 " }", 9981 format("#define OP(x) \\\n" 9982 " ostream &operator<<(ostream &s, const A &a) { \\\n" 9983 " return s << a.DebugString(); \\\n" 9984 " }", 9985 getLLVMStyleWithColumns(50))); 9986 9987 // FIXME: We cannot handle this case yet; we might be able to figure out that 9988 // foo<x> d > v; doesn't make sense. 9989 verifyFormat("foo<a<b && c> d> v;"); 9990 9991 FormatStyle PointerMiddle = getLLVMStyle(); 9992 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle; 9993 verifyFormat("delete *x;", PointerMiddle); 9994 verifyFormat("int * x;", PointerMiddle); 9995 verifyFormat("int *[] x;", PointerMiddle); 9996 verifyFormat("template <int * y> f() {}", PointerMiddle); 9997 verifyFormat("int * f(int * a) {}", PointerMiddle); 9998 verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle); 9999 verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle); 10000 verifyFormat("A<int *> a;", PointerMiddle); 10001 verifyFormat("A<int **> a;", PointerMiddle); 10002 verifyFormat("A<int *, int *> a;", PointerMiddle); 10003 verifyFormat("A<int *[]> a;", PointerMiddle); 10004 verifyFormat("A = new SomeType *[Length]();", PointerMiddle); 10005 verifyFormat("A = new SomeType *[Length];", PointerMiddle); 10006 verifyFormat("T ** t = new T *;", PointerMiddle); 10007 10008 // Member function reference qualifiers aren't binary operators. 10009 verifyFormat("string // break\n" 10010 "operator()() & {}"); 10011 verifyFormat("string // break\n" 10012 "operator()() && {}"); 10013 verifyGoogleFormat("template <typename T>\n" 10014 "auto x() & -> int {}"); 10015 10016 // Should be binary operators when used as an argument expression (overloaded 10017 // operator invoked as a member function). 10018 verifyFormat("void f() { a.operator()(a * a); }"); 10019 verifyFormat("void f() { a->operator()(a & a); }"); 10020 verifyFormat("void f() { a.operator()(*a & *a); }"); 10021 verifyFormat("void f() { a->operator()(*a * *a); }"); 10022 10023 verifyFormat("int operator()(T (&&)[N]) { return 1; }"); 10024 verifyFormat("int operator()(T (&)[N]) { return 0; }"); 10025 } 10026 10027 TEST_F(FormatTest, UnderstandsAttributes) { 10028 verifyFormat("SomeType s __attribute__((unused)) (InitValue);"); 10029 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n" 10030 "aaaaaaaaaaaaaaaaaaaaaaa(int i);"); 10031 FormatStyle AfterType = getLLVMStyle(); 10032 AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 10033 verifyFormat("__attribute__((nodebug)) void\n" 10034 "foo() {}\n", 10035 AfterType); 10036 verifyFormat("__unused void\n" 10037 "foo() {}", 10038 AfterType); 10039 10040 FormatStyle CustomAttrs = getLLVMStyle(); 10041 CustomAttrs.AttributeMacros.push_back("__unused"); 10042 CustomAttrs.AttributeMacros.push_back("__attr1"); 10043 CustomAttrs.AttributeMacros.push_back("__attr2"); 10044 CustomAttrs.AttributeMacros.push_back("no_underscore_attr"); 10045 verifyFormat("vector<SomeType *__attribute((foo))> v;"); 10046 verifyFormat("vector<SomeType *__attribute__((foo))> v;"); 10047 verifyFormat("vector<SomeType * __not_attribute__((foo))> v;"); 10048 // Check that it is parsed as a multiplication without AttributeMacros and 10049 // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros. 10050 verifyFormat("vector<SomeType * __attr1> v;"); 10051 verifyFormat("vector<SomeType __attr1 *> v;"); 10052 verifyFormat("vector<SomeType __attr1 *const> v;"); 10053 verifyFormat("vector<SomeType __attr1 * __attr2> v;"); 10054 verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs); 10055 verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs); 10056 verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs); 10057 verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs); 10058 verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs); 10059 verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs); 10060 verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs); 10061 10062 // Check that these are not parsed as function declarations: 10063 CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 10064 CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman; 10065 verifyFormat("SomeType s(InitValue);", CustomAttrs); 10066 verifyFormat("SomeType s{InitValue};", CustomAttrs); 10067 verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs); 10068 verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs); 10069 verifyFormat("SomeType s __unused(InitValue);", CustomAttrs); 10070 verifyFormat("SomeType s __unused{InitValue};", CustomAttrs); 10071 verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs); 10072 verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs); 10073 } 10074 10075 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) { 10076 // Check that qualifiers on pointers don't break parsing of casts. 10077 verifyFormat("x = (foo *const)*v;"); 10078 verifyFormat("x = (foo *volatile)*v;"); 10079 verifyFormat("x = (foo *restrict)*v;"); 10080 verifyFormat("x = (foo *__attribute__((foo)))*v;"); 10081 verifyFormat("x = (foo *_Nonnull)*v;"); 10082 verifyFormat("x = (foo *_Nullable)*v;"); 10083 verifyFormat("x = (foo *_Null_unspecified)*v;"); 10084 verifyFormat("x = (foo *_Nonnull)*v;"); 10085 verifyFormat("x = (foo *[[clang::attr]])*v;"); 10086 verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;"); 10087 verifyFormat("x = (foo *__ptr32)*v;"); 10088 verifyFormat("x = (foo *__ptr64)*v;"); 10089 verifyFormat("x = (foo *__capability)*v;"); 10090 10091 // Check that we handle multiple trailing qualifiers and skip them all to 10092 // determine that the expression is a cast to a pointer type. 10093 FormatStyle LongPointerRight = getLLVMStyleWithColumns(999); 10094 FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999); 10095 LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left; 10096 StringRef AllQualifiers = 10097 "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified " 10098 "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability"; 10099 verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight); 10100 verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft); 10101 10102 // Also check that address-of is not parsed as a binary bitwise-and: 10103 verifyFormat("x = (foo *const)&v;"); 10104 verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight); 10105 verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft); 10106 10107 // Check custom qualifiers: 10108 FormatStyle CustomQualifier = getLLVMStyleWithColumns(999); 10109 CustomQualifier.AttributeMacros.push_back("__my_qualifier"); 10110 verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier. 10111 verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier); 10112 verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(), 10113 CustomQualifier); 10114 verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(), 10115 CustomQualifier); 10116 10117 // Check that unknown identifiers result in binary operator parsing: 10118 verifyFormat("x = (foo * __unknown_qualifier) * v;"); 10119 verifyFormat("x = (foo * __unknown_qualifier) & v;"); 10120 } 10121 10122 TEST_F(FormatTest, UnderstandsSquareAttributes) { 10123 verifyFormat("SomeType s [[unused]] (InitValue);"); 10124 verifyFormat("SomeType s [[gnu::unused]] (InitValue);"); 10125 verifyFormat("SomeType s [[using gnu: unused]] (InitValue);"); 10126 verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}"); 10127 verifyFormat("void f() [[deprecated(\"so sorry\")]];"); 10128 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10129 " [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);"); 10130 verifyFormat("[[nodiscard]] bool f() { return false; }"); 10131 verifyFormat("class [[nodiscard]] f {\npublic:\n f() {}\n}"); 10132 verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n f() {}\n}"); 10133 verifyFormat("class [[gnu::unused]] f {\npublic:\n f() {}\n}"); 10134 10135 // Make sure we do not mistake attributes for array subscripts. 10136 verifyFormat("int a() {}\n" 10137 "[[unused]] int b() {}\n"); 10138 verifyFormat("NSArray *arr;\n" 10139 "arr[[Foo() bar]];"); 10140 10141 // On the other hand, we still need to correctly find array subscripts. 10142 verifyFormat("int a = std::vector<int>{1, 2, 3}[0];"); 10143 10144 // Make sure that we do not mistake Objective-C method inside array literals 10145 // as attributes, even if those method names are also keywords. 10146 verifyFormat("@[ [foo bar] ];"); 10147 verifyFormat("@[ [NSArray class] ];"); 10148 verifyFormat("@[ [foo enum] ];"); 10149 10150 verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }"); 10151 10152 // Make sure we do not parse attributes as lambda introducers. 10153 FormatStyle MultiLineFunctions = getLLVMStyle(); 10154 MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 10155 verifyFormat("[[unused]] int b() {\n" 10156 " return 42;\n" 10157 "}\n", 10158 MultiLineFunctions); 10159 } 10160 10161 TEST_F(FormatTest, AttributeClass) { 10162 FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp); 10163 verifyFormat("class S {\n" 10164 " S(S&&) = default;\n" 10165 "};", 10166 Style); 10167 verifyFormat("class [[nodiscard]] S {\n" 10168 " S(S&&) = default;\n" 10169 "};", 10170 Style); 10171 verifyFormat("class __attribute((maybeunused)) S {\n" 10172 " S(S&&) = default;\n" 10173 "};", 10174 Style); 10175 verifyFormat("struct S {\n" 10176 " S(S&&) = default;\n" 10177 "};", 10178 Style); 10179 verifyFormat("struct [[nodiscard]] S {\n" 10180 " S(S&&) = default;\n" 10181 "};", 10182 Style); 10183 } 10184 10185 TEST_F(FormatTest, AttributesAfterMacro) { 10186 FormatStyle Style = getLLVMStyle(); 10187 verifyFormat("MACRO;\n" 10188 "__attribute__((maybe_unused)) int foo() {\n" 10189 " //...\n" 10190 "}"); 10191 10192 verifyFormat("MACRO;\n" 10193 "[[nodiscard]] int foo() {\n" 10194 " //...\n" 10195 "}"); 10196 10197 EXPECT_EQ("MACRO\n\n" 10198 "__attribute__((maybe_unused)) int foo() {\n" 10199 " //...\n" 10200 "}", 10201 format("MACRO\n\n" 10202 "__attribute__((maybe_unused)) int foo() {\n" 10203 " //...\n" 10204 "}")); 10205 10206 EXPECT_EQ("MACRO\n\n" 10207 "[[nodiscard]] int foo() {\n" 10208 " //...\n" 10209 "}", 10210 format("MACRO\n\n" 10211 "[[nodiscard]] int foo() {\n" 10212 " //...\n" 10213 "}")); 10214 } 10215 10216 TEST_F(FormatTest, AttributePenaltyBreaking) { 10217 FormatStyle Style = getLLVMStyle(); 10218 verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n" 10219 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}", 10220 Style); 10221 verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n" 10222 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}", 10223 Style); 10224 verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const " 10225 "shared_ptr<ALongTypeName> &C d) {\n}", 10226 Style); 10227 } 10228 10229 TEST_F(FormatTest, UnderstandsEllipsis) { 10230 FormatStyle Style = getLLVMStyle(); 10231 verifyFormat("int printf(const char *fmt, ...);"); 10232 verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }"); 10233 verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}"); 10234 10235 verifyFormat("template <int *...PP> a;", Style); 10236 10237 Style.PointerAlignment = FormatStyle::PAS_Left; 10238 verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style); 10239 10240 verifyFormat("template <int*... PP> a;", Style); 10241 10242 Style.PointerAlignment = FormatStyle::PAS_Middle; 10243 verifyFormat("template <int *... PP> a;", Style); 10244 } 10245 10246 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) { 10247 EXPECT_EQ("int *a;\n" 10248 "int *a;\n" 10249 "int *a;", 10250 format("int *a;\n" 10251 "int* a;\n" 10252 "int *a;", 10253 getGoogleStyle())); 10254 EXPECT_EQ("int* a;\n" 10255 "int* a;\n" 10256 "int* a;", 10257 format("int* a;\n" 10258 "int* a;\n" 10259 "int *a;", 10260 getGoogleStyle())); 10261 EXPECT_EQ("int *a;\n" 10262 "int *a;\n" 10263 "int *a;", 10264 format("int *a;\n" 10265 "int * a;\n" 10266 "int * a;", 10267 getGoogleStyle())); 10268 EXPECT_EQ("auto x = [] {\n" 10269 " int *a;\n" 10270 " int *a;\n" 10271 " int *a;\n" 10272 "};", 10273 format("auto x=[]{int *a;\n" 10274 "int * a;\n" 10275 "int * a;};", 10276 getGoogleStyle())); 10277 } 10278 10279 TEST_F(FormatTest, UnderstandsRvalueReferences) { 10280 verifyFormat("int f(int &&a) {}"); 10281 verifyFormat("int f(int a, char &&b) {}"); 10282 verifyFormat("void f() { int &&a = b; }"); 10283 verifyGoogleFormat("int f(int a, char&& b) {}"); 10284 verifyGoogleFormat("void f() { int&& a = b; }"); 10285 10286 verifyIndependentOfContext("A<int &&> a;"); 10287 verifyIndependentOfContext("A<int &&, int &&> a;"); 10288 verifyGoogleFormat("A<int&&> a;"); 10289 verifyGoogleFormat("A<int&&, int&&> a;"); 10290 10291 // Not rvalue references: 10292 verifyFormat("template <bool B, bool C> class A {\n" 10293 " static_assert(B && C, \"Something is wrong\");\n" 10294 "};"); 10295 verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))"); 10296 verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))"); 10297 verifyFormat("#define A(a, b) (a && b)"); 10298 } 10299 10300 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) { 10301 verifyFormat("void f() {\n" 10302 " x[aaaaaaaaa -\n" 10303 " b] = 23;\n" 10304 "}", 10305 getLLVMStyleWithColumns(15)); 10306 } 10307 10308 TEST_F(FormatTest, FormatsCasts) { 10309 verifyFormat("Type *A = static_cast<Type *>(P);"); 10310 verifyFormat("Type *A = (Type *)P;"); 10311 verifyFormat("Type *A = (vector<Type *, int *>)P;"); 10312 verifyFormat("int a = (int)(2.0f);"); 10313 verifyFormat("int a = (int)2.0f;"); 10314 verifyFormat("x[(int32)y];"); 10315 verifyFormat("x = (int32)y;"); 10316 verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)"); 10317 verifyFormat("int a = (int)*b;"); 10318 verifyFormat("int a = (int)2.0f;"); 10319 verifyFormat("int a = (int)~0;"); 10320 verifyFormat("int a = (int)++a;"); 10321 verifyFormat("int a = (int)sizeof(int);"); 10322 verifyFormat("int a = (int)+2;"); 10323 verifyFormat("my_int a = (my_int)2.0f;"); 10324 verifyFormat("my_int a = (my_int)sizeof(int);"); 10325 verifyFormat("return (my_int)aaa;"); 10326 verifyFormat("#define x ((int)-1)"); 10327 verifyFormat("#define LENGTH(x, y) (x) - (y) + 1"); 10328 verifyFormat("#define p(q) ((int *)&q)"); 10329 verifyFormat("fn(a)(b) + 1;"); 10330 10331 verifyFormat("void f() { my_int a = (my_int)*b; }"); 10332 verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }"); 10333 verifyFormat("my_int a = (my_int)~0;"); 10334 verifyFormat("my_int a = (my_int)++a;"); 10335 verifyFormat("my_int a = (my_int)-2;"); 10336 verifyFormat("my_int a = (my_int)1;"); 10337 verifyFormat("my_int a = (my_int *)1;"); 10338 verifyFormat("my_int a = (const my_int)-1;"); 10339 verifyFormat("my_int a = (const my_int *)-1;"); 10340 verifyFormat("my_int a = (my_int)(my_int)-1;"); 10341 verifyFormat("my_int a = (ns::my_int)-2;"); 10342 verifyFormat("case (my_int)ONE:"); 10343 verifyFormat("auto x = (X)this;"); 10344 // Casts in Obj-C style calls used to not be recognized as such. 10345 verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle()); 10346 10347 // FIXME: single value wrapped with paren will be treated as cast. 10348 verifyFormat("void f(int i = (kValue)*kMask) {}"); 10349 10350 verifyFormat("{ (void)F; }"); 10351 10352 // Don't break after a cast's 10353 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 10354 " (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n" 10355 " bbbbbbbbbbbbbbbbbbbbbb);"); 10356 10357 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(x)"); 10358 verifyFormat("#define CONF_BOOL(x) (bool *)(x)"); 10359 verifyFormat("#define CONF_BOOL(x) (bool)(x)"); 10360 verifyFormat("bool *y = (bool *)(void *)(x);"); 10361 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)(x)"); 10362 verifyFormat("bool *y = (bool *)(void *)(int)(x);"); 10363 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)foo(x)"); 10364 verifyFormat("bool *y = (bool *)(void *)(int)foo(x);"); 10365 10366 // These are not casts. 10367 verifyFormat("void f(int *) {}"); 10368 verifyFormat("f(foo)->b;"); 10369 verifyFormat("f(foo).b;"); 10370 verifyFormat("f(foo)(b);"); 10371 verifyFormat("f(foo)[b];"); 10372 verifyFormat("[](foo) { return 4; }(bar);"); 10373 verifyFormat("(*funptr)(foo)[4];"); 10374 verifyFormat("funptrs[4](foo)[4];"); 10375 verifyFormat("void f(int *);"); 10376 verifyFormat("void f(int *) = 0;"); 10377 verifyFormat("void f(SmallVector<int>) {}"); 10378 verifyFormat("void f(SmallVector<int>);"); 10379 verifyFormat("void f(SmallVector<int>) = 0;"); 10380 verifyFormat("void f(int i = (kA * kB) & kMask) {}"); 10381 verifyFormat("int a = sizeof(int) * b;"); 10382 verifyFormat("int a = alignof(int) * b;", getGoogleStyle()); 10383 verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;"); 10384 verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");"); 10385 verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;"); 10386 10387 // These are not casts, but at some point were confused with casts. 10388 verifyFormat("virtual void foo(int *) override;"); 10389 verifyFormat("virtual void foo(char &) const;"); 10390 verifyFormat("virtual void foo(int *a, char *) const;"); 10391 verifyFormat("int a = sizeof(int *) + b;"); 10392 verifyFormat("int a = alignof(int *) + b;", getGoogleStyle()); 10393 verifyFormat("bool b = f(g<int>) && c;"); 10394 verifyFormat("typedef void (*f)(int i) func;"); 10395 verifyFormat("void operator++(int) noexcept;"); 10396 verifyFormat("void operator++(int &) noexcept;"); 10397 verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t " 10398 "&) noexcept;"); 10399 verifyFormat( 10400 "void operator delete(std::size_t, const std::nothrow_t &) noexcept;"); 10401 verifyFormat("void operator delete(const std::nothrow_t &) noexcept;"); 10402 verifyFormat("void operator delete(std::nothrow_t &) noexcept;"); 10403 verifyFormat("void operator delete(nothrow_t &) noexcept;"); 10404 verifyFormat("void operator delete(foo &) noexcept;"); 10405 verifyFormat("void operator delete(foo) noexcept;"); 10406 verifyFormat("void operator delete(int) noexcept;"); 10407 verifyFormat("void operator delete(int &) noexcept;"); 10408 verifyFormat("void operator delete(int &) volatile noexcept;"); 10409 verifyFormat("void operator delete(int &) const"); 10410 verifyFormat("void operator delete(int &) = default"); 10411 verifyFormat("void operator delete(int &) = delete"); 10412 verifyFormat("void operator delete(int &) [[noreturn]]"); 10413 verifyFormat("void operator delete(int &) throw();"); 10414 verifyFormat("void operator delete(int &) throw(int);"); 10415 verifyFormat("auto operator delete(int &) -> int;"); 10416 verifyFormat("auto operator delete(int &) override"); 10417 verifyFormat("auto operator delete(int &) final"); 10418 10419 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n" 10420 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 10421 // FIXME: The indentation here is not ideal. 10422 verifyFormat( 10423 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10424 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n" 10425 " [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];"); 10426 } 10427 10428 TEST_F(FormatTest, FormatsFunctionTypes) { 10429 verifyFormat("A<bool()> a;"); 10430 verifyFormat("A<SomeType()> a;"); 10431 verifyFormat("A<void (*)(int, std::string)> a;"); 10432 verifyFormat("A<void *(int)>;"); 10433 verifyFormat("void *(*a)(int *, SomeType *);"); 10434 verifyFormat("int (*func)(void *);"); 10435 verifyFormat("void f() { int (*func)(void *); }"); 10436 verifyFormat("template <class CallbackClass>\n" 10437 "using MyCallback = void (CallbackClass::*)(SomeObject *Data);"); 10438 10439 verifyGoogleFormat("A<void*(int*, SomeType*)>;"); 10440 verifyGoogleFormat("void* (*a)(int);"); 10441 verifyGoogleFormat( 10442 "template <class CallbackClass>\n" 10443 "using MyCallback = void (CallbackClass::*)(SomeObject* Data);"); 10444 10445 // Other constructs can look somewhat like function types: 10446 verifyFormat("A<sizeof(*x)> a;"); 10447 verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)"); 10448 verifyFormat("some_var = function(*some_pointer_var)[0];"); 10449 verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }"); 10450 verifyFormat("int x = f(&h)();"); 10451 verifyFormat("returnsFunction(¶m1, ¶m2)(param);"); 10452 verifyFormat("std::function<\n" 10453 " LooooooooooongTemplatedType<\n" 10454 " SomeType>*(\n" 10455 " LooooooooooooooooongType type)>\n" 10456 " function;", 10457 getGoogleStyleWithColumns(40)); 10458 } 10459 10460 TEST_F(FormatTest, FormatsPointersToArrayTypes) { 10461 verifyFormat("A (*foo_)[6];"); 10462 verifyFormat("vector<int> (*foo_)[6];"); 10463 } 10464 10465 TEST_F(FormatTest, BreaksLongVariableDeclarations) { 10466 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10467 " LoooooooooooooooooooooooooooooooooooooooongVariable;"); 10468 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n" 10469 " LoooooooooooooooooooooooooooooooooooooooongVariable;"); 10470 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10471 " *LoooooooooooooooooooooooooooooooooooooooongVariable;"); 10472 10473 // Different ways of ()-initializiation. 10474 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10475 " LoooooooooooooooooooooooooooooooooooooooongVariable(1);"); 10476 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10477 " LoooooooooooooooooooooooooooooooooooooooongVariable(a);"); 10478 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10479 " LoooooooooooooooooooooooooooooooooooooooongVariable({});"); 10480 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10481 " LoooooooooooooooooooooooooooooooooooooongVariable([A a]);"); 10482 10483 // Lambdas should not confuse the variable declaration heuristic. 10484 verifyFormat("LooooooooooooooooongType\n" 10485 " variable(nullptr, [](A *a) {});", 10486 getLLVMStyleWithColumns(40)); 10487 } 10488 10489 TEST_F(FormatTest, BreaksLongDeclarations) { 10490 verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n" 10491 " AnotherNameForTheLongType;"); 10492 verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n" 10493 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 10494 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10495 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();"); 10496 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n" 10497 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();"); 10498 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10499 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10500 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n" 10501 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10502 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n" 10503 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10504 verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n" 10505 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10506 verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n" 10507 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10508 verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n" 10509 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10510 verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n" 10511 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10512 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10513 "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);"); 10514 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10515 "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}"); 10516 FormatStyle Indented = getLLVMStyle(); 10517 Indented.IndentWrappedFunctionNames = true; 10518 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10519 " LoooooooooooooooooooooooooooooooongFunctionDeclaration();", 10520 Indented); 10521 verifyFormat( 10522 "LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10523 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 10524 Indented); 10525 verifyFormat( 10526 "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n" 10527 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 10528 Indented); 10529 verifyFormat( 10530 "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n" 10531 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 10532 Indented); 10533 10534 // FIXME: Without the comment, this breaks after "(". 10535 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType // break\n" 10536 " (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();", 10537 getGoogleStyle()); 10538 10539 verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n" 10540 " int LoooooooooooooooooooongParam2) {}"); 10541 verifyFormat( 10542 "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n" 10543 " SourceLocation L, IdentifierIn *II,\n" 10544 " Type *T) {}"); 10545 verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n" 10546 "ReallyReaaallyLongFunctionName(\n" 10547 " const std::string &SomeParameter,\n" 10548 " const SomeType<string, SomeOtherTemplateParameter>\n" 10549 " &ReallyReallyLongParameterName,\n" 10550 " const SomeType<string, SomeOtherTemplateParameter>\n" 10551 " &AnotherLongParameterName) {}"); 10552 verifyFormat("template <typename A>\n" 10553 "SomeLoooooooooooooooooooooongType<\n" 10554 " typename some_namespace::SomeOtherType<A>::Type>\n" 10555 "Function() {}"); 10556 10557 verifyGoogleFormat( 10558 "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n" 10559 " aaaaaaaaaaaaaaaaaaaaaaa;"); 10560 verifyGoogleFormat( 10561 "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n" 10562 " SourceLocation L) {}"); 10563 verifyGoogleFormat( 10564 "some_namespace::LongReturnType\n" 10565 "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n" 10566 " int first_long_parameter, int second_parameter) {}"); 10567 10568 verifyGoogleFormat("template <typename T>\n" 10569 "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n" 10570 "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}"); 10571 verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 10572 " int aaaaaaaaaaaaaaaaaaaaaaa);"); 10573 10574 verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n" 10575 " const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10576 " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 10577 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 10578 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n" 10579 " aaaaaaaaaaaaaaaaaaaaaaaa);"); 10580 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 10581 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 10582 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n" 10583 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 10584 10585 verifyFormat("template <typename T> // Templates on own line.\n" 10586 "static int // Some comment.\n" 10587 "MyFunction(int a);", 10588 getLLVMStyle()); 10589 } 10590 10591 TEST_F(FormatTest, FormatsAccessModifiers) { 10592 FormatStyle Style = getLLVMStyle(); 10593 EXPECT_EQ(Style.EmptyLineBeforeAccessModifier, 10594 FormatStyle::ELBAMS_LogicalBlock); 10595 verifyFormat("struct foo {\n" 10596 "private:\n" 10597 " void f() {}\n" 10598 "\n" 10599 "private:\n" 10600 " int i;\n" 10601 "\n" 10602 "protected:\n" 10603 " int j;\n" 10604 "};\n", 10605 Style); 10606 verifyFormat("struct foo {\n" 10607 "private:\n" 10608 " void f() {}\n" 10609 "\n" 10610 "private:\n" 10611 " int i;\n" 10612 "\n" 10613 "protected:\n" 10614 " int j;\n" 10615 "};\n", 10616 "struct foo {\n" 10617 "private:\n" 10618 " void f() {}\n" 10619 "private:\n" 10620 " int i;\n" 10621 "protected:\n" 10622 " int j;\n" 10623 "};\n", 10624 Style); 10625 verifyFormat("struct foo { /* comment */\n" 10626 "private:\n" 10627 " int i;\n" 10628 " // comment\n" 10629 "private:\n" 10630 " int j;\n" 10631 "};\n", 10632 Style); 10633 verifyFormat("struct foo {\n" 10634 "#ifdef FOO\n" 10635 "#endif\n" 10636 "private:\n" 10637 " int i;\n" 10638 "#ifdef FOO\n" 10639 "private:\n" 10640 "#endif\n" 10641 " int j;\n" 10642 "};\n", 10643 Style); 10644 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 10645 verifyFormat("struct foo {\n" 10646 "private:\n" 10647 " void f() {}\n" 10648 "private:\n" 10649 " int i;\n" 10650 "protected:\n" 10651 " int j;\n" 10652 "};\n", 10653 Style); 10654 verifyFormat("struct foo {\n" 10655 "private:\n" 10656 " void f() {}\n" 10657 "private:\n" 10658 " int i;\n" 10659 "protected:\n" 10660 " int j;\n" 10661 "};\n", 10662 "struct foo {\n" 10663 "\n" 10664 "private:\n" 10665 " void f() {}\n" 10666 "\n" 10667 "private:\n" 10668 " int i;\n" 10669 "\n" 10670 "protected:\n" 10671 " int j;\n" 10672 "};\n", 10673 Style); 10674 verifyFormat("struct foo { /* comment */\n" 10675 "private:\n" 10676 " int i;\n" 10677 " // comment\n" 10678 "private:\n" 10679 " int j;\n" 10680 "};\n", 10681 "struct foo { /* comment */\n" 10682 "\n" 10683 "private:\n" 10684 " int i;\n" 10685 " // comment\n" 10686 "\n" 10687 "private:\n" 10688 " int j;\n" 10689 "};\n", 10690 Style); 10691 verifyFormat("struct foo {\n" 10692 "#ifdef FOO\n" 10693 "#endif\n" 10694 "private:\n" 10695 " int i;\n" 10696 "#ifdef FOO\n" 10697 "private:\n" 10698 "#endif\n" 10699 " int j;\n" 10700 "};\n", 10701 "struct foo {\n" 10702 "#ifdef FOO\n" 10703 "#endif\n" 10704 "\n" 10705 "private:\n" 10706 " int i;\n" 10707 "#ifdef FOO\n" 10708 "\n" 10709 "private:\n" 10710 "#endif\n" 10711 " int j;\n" 10712 "};\n", 10713 Style); 10714 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 10715 verifyFormat("struct foo {\n" 10716 "private:\n" 10717 " void f() {}\n" 10718 "\n" 10719 "private:\n" 10720 " int i;\n" 10721 "\n" 10722 "protected:\n" 10723 " int j;\n" 10724 "};\n", 10725 Style); 10726 verifyFormat("struct foo {\n" 10727 "private:\n" 10728 " void f() {}\n" 10729 "\n" 10730 "private:\n" 10731 " int i;\n" 10732 "\n" 10733 "protected:\n" 10734 " int j;\n" 10735 "};\n", 10736 "struct foo {\n" 10737 "private:\n" 10738 " void f() {}\n" 10739 "private:\n" 10740 " int i;\n" 10741 "protected:\n" 10742 " int j;\n" 10743 "};\n", 10744 Style); 10745 verifyFormat("struct foo { /* comment */\n" 10746 "private:\n" 10747 " int i;\n" 10748 " // comment\n" 10749 "\n" 10750 "private:\n" 10751 " int j;\n" 10752 "};\n", 10753 "struct foo { /* comment */\n" 10754 "private:\n" 10755 " int i;\n" 10756 " // comment\n" 10757 "\n" 10758 "private:\n" 10759 " int j;\n" 10760 "};\n", 10761 Style); 10762 verifyFormat("struct foo {\n" 10763 "#ifdef FOO\n" 10764 "#endif\n" 10765 "\n" 10766 "private:\n" 10767 " int i;\n" 10768 "#ifdef FOO\n" 10769 "\n" 10770 "private:\n" 10771 "#endif\n" 10772 " int j;\n" 10773 "};\n", 10774 "struct foo {\n" 10775 "#ifdef FOO\n" 10776 "#endif\n" 10777 "private:\n" 10778 " int i;\n" 10779 "#ifdef FOO\n" 10780 "private:\n" 10781 "#endif\n" 10782 " int j;\n" 10783 "};\n", 10784 Style); 10785 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 10786 EXPECT_EQ("struct foo {\n" 10787 "\n" 10788 "private:\n" 10789 " void f() {}\n" 10790 "\n" 10791 "private:\n" 10792 " int i;\n" 10793 "\n" 10794 "protected:\n" 10795 " int j;\n" 10796 "};\n", 10797 format("struct foo {\n" 10798 "\n" 10799 "private:\n" 10800 " void f() {}\n" 10801 "\n" 10802 "private:\n" 10803 " int i;\n" 10804 "\n" 10805 "protected:\n" 10806 " int j;\n" 10807 "};\n", 10808 Style)); 10809 verifyFormat("struct foo {\n" 10810 "private:\n" 10811 " void f() {}\n" 10812 "private:\n" 10813 " int i;\n" 10814 "protected:\n" 10815 " int j;\n" 10816 "};\n", 10817 Style); 10818 EXPECT_EQ("struct foo { /* comment */\n" 10819 "\n" 10820 "private:\n" 10821 " int i;\n" 10822 " // comment\n" 10823 "\n" 10824 "private:\n" 10825 " int j;\n" 10826 "};\n", 10827 format("struct foo { /* comment */\n" 10828 "\n" 10829 "private:\n" 10830 " int i;\n" 10831 " // comment\n" 10832 "\n" 10833 "private:\n" 10834 " int j;\n" 10835 "};\n", 10836 Style)); 10837 verifyFormat("struct foo { /* comment */\n" 10838 "private:\n" 10839 " int i;\n" 10840 " // comment\n" 10841 "private:\n" 10842 " int j;\n" 10843 "};\n", 10844 Style); 10845 EXPECT_EQ("struct foo {\n" 10846 "#ifdef FOO\n" 10847 "#endif\n" 10848 "\n" 10849 "private:\n" 10850 " int i;\n" 10851 "#ifdef FOO\n" 10852 "\n" 10853 "private:\n" 10854 "#endif\n" 10855 " int j;\n" 10856 "};\n", 10857 format("struct foo {\n" 10858 "#ifdef FOO\n" 10859 "#endif\n" 10860 "\n" 10861 "private:\n" 10862 " int i;\n" 10863 "#ifdef FOO\n" 10864 "\n" 10865 "private:\n" 10866 "#endif\n" 10867 " int j;\n" 10868 "};\n", 10869 Style)); 10870 verifyFormat("struct foo {\n" 10871 "#ifdef FOO\n" 10872 "#endif\n" 10873 "private:\n" 10874 " int i;\n" 10875 "#ifdef FOO\n" 10876 "private:\n" 10877 "#endif\n" 10878 " int j;\n" 10879 "};\n", 10880 Style); 10881 10882 FormatStyle NoEmptyLines = getLLVMStyle(); 10883 NoEmptyLines.MaxEmptyLinesToKeep = 0; 10884 verifyFormat("struct foo {\n" 10885 "private:\n" 10886 " void f() {}\n" 10887 "\n" 10888 "private:\n" 10889 " int i;\n" 10890 "\n" 10891 "public:\n" 10892 "protected:\n" 10893 " int j;\n" 10894 "};\n", 10895 NoEmptyLines); 10896 10897 NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 10898 verifyFormat("struct foo {\n" 10899 "private:\n" 10900 " void f() {}\n" 10901 "private:\n" 10902 " int i;\n" 10903 "public:\n" 10904 "protected:\n" 10905 " int j;\n" 10906 "};\n", 10907 NoEmptyLines); 10908 10909 NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 10910 verifyFormat("struct foo {\n" 10911 "private:\n" 10912 " void f() {}\n" 10913 "\n" 10914 "private:\n" 10915 " int i;\n" 10916 "\n" 10917 "public:\n" 10918 "\n" 10919 "protected:\n" 10920 " int j;\n" 10921 "};\n", 10922 NoEmptyLines); 10923 } 10924 10925 TEST_F(FormatTest, FormatsAfterAccessModifiers) { 10926 10927 FormatStyle Style = getLLVMStyle(); 10928 EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never); 10929 verifyFormat("struct foo {\n" 10930 "private:\n" 10931 " void f() {}\n" 10932 "\n" 10933 "private:\n" 10934 " int i;\n" 10935 "\n" 10936 "protected:\n" 10937 " int j;\n" 10938 "};\n", 10939 Style); 10940 10941 // Check if lines are removed. 10942 verifyFormat("struct foo {\n" 10943 "private:\n" 10944 " void f() {}\n" 10945 "\n" 10946 "private:\n" 10947 " int i;\n" 10948 "\n" 10949 "protected:\n" 10950 " int j;\n" 10951 "};\n", 10952 "struct foo {\n" 10953 "private:\n" 10954 "\n" 10955 " void f() {}\n" 10956 "\n" 10957 "private:\n" 10958 "\n" 10959 " int i;\n" 10960 "\n" 10961 "protected:\n" 10962 "\n" 10963 " int j;\n" 10964 "};\n", 10965 Style); 10966 10967 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 10968 verifyFormat("struct foo {\n" 10969 "private:\n" 10970 "\n" 10971 " void f() {}\n" 10972 "\n" 10973 "private:\n" 10974 "\n" 10975 " int i;\n" 10976 "\n" 10977 "protected:\n" 10978 "\n" 10979 " int j;\n" 10980 "};\n", 10981 Style); 10982 10983 // Check if lines are added. 10984 verifyFormat("struct foo {\n" 10985 "private:\n" 10986 "\n" 10987 " void f() {}\n" 10988 "\n" 10989 "private:\n" 10990 "\n" 10991 " int i;\n" 10992 "\n" 10993 "protected:\n" 10994 "\n" 10995 " int j;\n" 10996 "};\n", 10997 "struct foo {\n" 10998 "private:\n" 10999 " void f() {}\n" 11000 "\n" 11001 "private:\n" 11002 " int i;\n" 11003 "\n" 11004 "protected:\n" 11005 " int j;\n" 11006 "};\n", 11007 Style); 11008 11009 // Leave tests rely on the code layout, test::messUp can not be used. 11010 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11011 Style.MaxEmptyLinesToKeep = 0u; 11012 verifyFormat("struct foo {\n" 11013 "private:\n" 11014 " void f() {}\n" 11015 "\n" 11016 "private:\n" 11017 " int i;\n" 11018 "\n" 11019 "protected:\n" 11020 " int j;\n" 11021 "};\n", 11022 Style); 11023 11024 // Check if MaxEmptyLinesToKeep is respected. 11025 EXPECT_EQ("struct foo {\n" 11026 "private:\n" 11027 " void f() {}\n" 11028 "\n" 11029 "private:\n" 11030 " int i;\n" 11031 "\n" 11032 "protected:\n" 11033 " int j;\n" 11034 "};\n", 11035 format("struct foo {\n" 11036 "private:\n" 11037 "\n\n\n" 11038 " void f() {}\n" 11039 "\n" 11040 "private:\n" 11041 "\n\n\n" 11042 " int i;\n" 11043 "\n" 11044 "protected:\n" 11045 "\n\n\n" 11046 " int j;\n" 11047 "};\n", 11048 Style)); 11049 11050 Style.MaxEmptyLinesToKeep = 1u; 11051 EXPECT_EQ("struct foo {\n" 11052 "private:\n" 11053 "\n" 11054 " void f() {}\n" 11055 "\n" 11056 "private:\n" 11057 "\n" 11058 " int i;\n" 11059 "\n" 11060 "protected:\n" 11061 "\n" 11062 " int j;\n" 11063 "};\n", 11064 format("struct foo {\n" 11065 "private:\n" 11066 "\n" 11067 " void f() {}\n" 11068 "\n" 11069 "private:\n" 11070 "\n" 11071 " int i;\n" 11072 "\n" 11073 "protected:\n" 11074 "\n" 11075 " int j;\n" 11076 "};\n", 11077 Style)); 11078 // Check if no lines are kept. 11079 EXPECT_EQ("struct foo {\n" 11080 "private:\n" 11081 " void f() {}\n" 11082 "\n" 11083 "private:\n" 11084 " int i;\n" 11085 "\n" 11086 "protected:\n" 11087 " int j;\n" 11088 "};\n", 11089 format("struct foo {\n" 11090 "private:\n" 11091 " void f() {}\n" 11092 "\n" 11093 "private:\n" 11094 " int i;\n" 11095 "\n" 11096 "protected:\n" 11097 " int j;\n" 11098 "};\n", 11099 Style)); 11100 // Check if MaxEmptyLinesToKeep is respected. 11101 EXPECT_EQ("struct foo {\n" 11102 "private:\n" 11103 "\n" 11104 " void f() {}\n" 11105 "\n" 11106 "private:\n" 11107 "\n" 11108 " int i;\n" 11109 "\n" 11110 "protected:\n" 11111 "\n" 11112 " int j;\n" 11113 "};\n", 11114 format("struct foo {\n" 11115 "private:\n" 11116 "\n\n\n" 11117 " void f() {}\n" 11118 "\n" 11119 "private:\n" 11120 "\n\n\n" 11121 " int i;\n" 11122 "\n" 11123 "protected:\n" 11124 "\n\n\n" 11125 " int j;\n" 11126 "};\n", 11127 Style)); 11128 11129 Style.MaxEmptyLinesToKeep = 10u; 11130 EXPECT_EQ("struct foo {\n" 11131 "private:\n" 11132 "\n\n\n" 11133 " void f() {}\n" 11134 "\n" 11135 "private:\n" 11136 "\n\n\n" 11137 " int i;\n" 11138 "\n" 11139 "protected:\n" 11140 "\n\n\n" 11141 " int j;\n" 11142 "};\n", 11143 format("struct foo {\n" 11144 "private:\n" 11145 "\n\n\n" 11146 " void f() {}\n" 11147 "\n" 11148 "private:\n" 11149 "\n\n\n" 11150 " int i;\n" 11151 "\n" 11152 "protected:\n" 11153 "\n\n\n" 11154 " int j;\n" 11155 "};\n", 11156 Style)); 11157 11158 // Test with comments. 11159 Style = getLLVMStyle(); 11160 verifyFormat("struct foo {\n" 11161 "private:\n" 11162 " // comment\n" 11163 " void f() {}\n" 11164 "\n" 11165 "private: /* comment */\n" 11166 " int i;\n" 11167 "};\n", 11168 Style); 11169 verifyFormat("struct foo {\n" 11170 "private:\n" 11171 " // comment\n" 11172 " void f() {}\n" 11173 "\n" 11174 "private: /* comment */\n" 11175 " int i;\n" 11176 "};\n", 11177 "struct foo {\n" 11178 "private:\n" 11179 "\n" 11180 " // comment\n" 11181 " void f() {}\n" 11182 "\n" 11183 "private: /* comment */\n" 11184 "\n" 11185 " int i;\n" 11186 "};\n", 11187 Style); 11188 11189 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11190 verifyFormat("struct foo {\n" 11191 "private:\n" 11192 "\n" 11193 " // comment\n" 11194 " void f() {}\n" 11195 "\n" 11196 "private: /* comment */\n" 11197 "\n" 11198 " int i;\n" 11199 "};\n", 11200 "struct foo {\n" 11201 "private:\n" 11202 " // comment\n" 11203 " void f() {}\n" 11204 "\n" 11205 "private: /* comment */\n" 11206 " int i;\n" 11207 "};\n", 11208 Style); 11209 verifyFormat("struct foo {\n" 11210 "private:\n" 11211 "\n" 11212 " // comment\n" 11213 " void f() {}\n" 11214 "\n" 11215 "private: /* comment */\n" 11216 "\n" 11217 " int i;\n" 11218 "};\n", 11219 Style); 11220 11221 // Test with preprocessor defines. 11222 Style = getLLVMStyle(); 11223 verifyFormat("struct foo {\n" 11224 "private:\n" 11225 "#ifdef FOO\n" 11226 "#endif\n" 11227 " void f() {}\n" 11228 "};\n", 11229 Style); 11230 verifyFormat("struct foo {\n" 11231 "private:\n" 11232 "#ifdef FOO\n" 11233 "#endif\n" 11234 " void f() {}\n" 11235 "};\n", 11236 "struct foo {\n" 11237 "private:\n" 11238 "\n" 11239 "#ifdef FOO\n" 11240 "#endif\n" 11241 " void f() {}\n" 11242 "};\n", 11243 Style); 11244 11245 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11246 verifyFormat("struct foo {\n" 11247 "private:\n" 11248 "\n" 11249 "#ifdef FOO\n" 11250 "#endif\n" 11251 " void f() {}\n" 11252 "};\n", 11253 "struct foo {\n" 11254 "private:\n" 11255 "#ifdef FOO\n" 11256 "#endif\n" 11257 " void f() {}\n" 11258 "};\n", 11259 Style); 11260 verifyFormat("struct foo {\n" 11261 "private:\n" 11262 "\n" 11263 "#ifdef FOO\n" 11264 "#endif\n" 11265 " void f() {}\n" 11266 "};\n", 11267 Style); 11268 } 11269 11270 TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) { 11271 // Combined tests of EmptyLineAfterAccessModifier and 11272 // EmptyLineBeforeAccessModifier. 11273 FormatStyle Style = getLLVMStyle(); 11274 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11275 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11276 verifyFormat("struct foo {\n" 11277 "private:\n" 11278 "\n" 11279 "protected:\n" 11280 "};\n", 11281 Style); 11282 11283 Style.MaxEmptyLinesToKeep = 10u; 11284 // Both remove all new lines. 11285 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11286 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11287 verifyFormat("struct foo {\n" 11288 "private:\n" 11289 "protected:\n" 11290 "};\n", 11291 "struct foo {\n" 11292 "private:\n" 11293 "\n\n\n" 11294 "protected:\n" 11295 "};\n", 11296 Style); 11297 11298 // Leave tests rely on the code layout, test::messUp can not be used. 11299 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11300 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11301 Style.MaxEmptyLinesToKeep = 10u; 11302 EXPECT_EQ("struct foo {\n" 11303 "private:\n" 11304 "\n\n\n" 11305 "protected:\n" 11306 "};\n", 11307 format("struct foo {\n" 11308 "private:\n" 11309 "\n\n\n" 11310 "protected:\n" 11311 "};\n", 11312 Style)); 11313 Style.MaxEmptyLinesToKeep = 3u; 11314 EXPECT_EQ("struct foo {\n" 11315 "private:\n" 11316 "\n\n\n" 11317 "protected:\n" 11318 "};\n", 11319 format("struct foo {\n" 11320 "private:\n" 11321 "\n\n\n" 11322 "protected:\n" 11323 "};\n", 11324 Style)); 11325 Style.MaxEmptyLinesToKeep = 1u; 11326 EXPECT_EQ("struct foo {\n" 11327 "private:\n" 11328 "\n\n\n" 11329 "protected:\n" 11330 "};\n", 11331 format("struct foo {\n" 11332 "private:\n" 11333 "\n\n\n" 11334 "protected:\n" 11335 "};\n", 11336 Style)); // Based on new lines in original document and not 11337 // on the setting. 11338 11339 Style.MaxEmptyLinesToKeep = 10u; 11340 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11341 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11342 // Newlines are kept if they are greater than zero, 11343 // test::messUp removes all new lines which changes the logic 11344 EXPECT_EQ("struct foo {\n" 11345 "private:\n" 11346 "\n\n\n" 11347 "protected:\n" 11348 "};\n", 11349 format("struct foo {\n" 11350 "private:\n" 11351 "\n\n\n" 11352 "protected:\n" 11353 "};\n", 11354 Style)); 11355 11356 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11357 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11358 // test::messUp removes all new lines which changes the logic 11359 EXPECT_EQ("struct foo {\n" 11360 "private:\n" 11361 "\n\n\n" 11362 "protected:\n" 11363 "};\n", 11364 format("struct foo {\n" 11365 "private:\n" 11366 "\n\n\n" 11367 "protected:\n" 11368 "};\n", 11369 Style)); 11370 11371 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11372 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11373 EXPECT_EQ("struct foo {\n" 11374 "private:\n" 11375 "\n\n\n" 11376 "protected:\n" 11377 "};\n", 11378 format("struct foo {\n" 11379 "private:\n" 11380 "\n\n\n" 11381 "protected:\n" 11382 "};\n", 11383 Style)); // test::messUp removes all new lines which changes 11384 // the logic. 11385 11386 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11387 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11388 verifyFormat("struct foo {\n" 11389 "private:\n" 11390 "protected:\n" 11391 "};\n", 11392 "struct foo {\n" 11393 "private:\n" 11394 "\n\n\n" 11395 "protected:\n" 11396 "};\n", 11397 Style); 11398 11399 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11400 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11401 EXPECT_EQ("struct foo {\n" 11402 "private:\n" 11403 "\n\n\n" 11404 "protected:\n" 11405 "};\n", 11406 format("struct foo {\n" 11407 "private:\n" 11408 "\n\n\n" 11409 "protected:\n" 11410 "};\n", 11411 Style)); // test::messUp removes all new lines which changes 11412 // the logic. 11413 11414 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11415 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11416 verifyFormat("struct foo {\n" 11417 "private:\n" 11418 "protected:\n" 11419 "};\n", 11420 "struct foo {\n" 11421 "private:\n" 11422 "\n\n\n" 11423 "protected:\n" 11424 "};\n", 11425 Style); 11426 11427 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11428 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11429 verifyFormat("struct foo {\n" 11430 "private:\n" 11431 "protected:\n" 11432 "};\n", 11433 "struct foo {\n" 11434 "private:\n" 11435 "\n\n\n" 11436 "protected:\n" 11437 "};\n", 11438 Style); 11439 11440 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11441 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11442 verifyFormat("struct foo {\n" 11443 "private:\n" 11444 "protected:\n" 11445 "};\n", 11446 "struct foo {\n" 11447 "private:\n" 11448 "\n\n\n" 11449 "protected:\n" 11450 "};\n", 11451 Style); 11452 11453 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11454 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11455 verifyFormat("struct foo {\n" 11456 "private:\n" 11457 "protected:\n" 11458 "};\n", 11459 "struct foo {\n" 11460 "private:\n" 11461 "\n\n\n" 11462 "protected:\n" 11463 "};\n", 11464 Style); 11465 } 11466 11467 TEST_F(FormatTest, FormatsArrays) { 11468 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n" 11469 " [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;"); 11470 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n" 11471 " [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;"); 11472 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n" 11473 " aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}"); 11474 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11475 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;"); 11476 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11477 " [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;"); 11478 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11479 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n" 11480 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;"); 11481 verifyFormat( 11482 "llvm::outs() << \"aaaaaaaaaaaa: \"\n" 11483 " << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n" 11484 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];"); 11485 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n" 11486 " .aaaaaaaaaaaaaaaaaaaaaa();"); 11487 11488 verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n" 11489 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];"); 11490 verifyFormat( 11491 "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n" 11492 " .aaaaaaa[0]\n" 11493 " .aaaaaaaaaaaaaaaaaaaaaa();"); 11494 verifyFormat("a[::b::c];"); 11495 11496 verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10)); 11497 11498 FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0); 11499 verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit); 11500 } 11501 11502 TEST_F(FormatTest, LineStartsWithSpecialCharacter) { 11503 verifyFormat("(a)->b();"); 11504 verifyFormat("--a;"); 11505 } 11506 11507 TEST_F(FormatTest, HandlesIncludeDirectives) { 11508 verifyFormat("#include <string>\n" 11509 "#include <a/b/c.h>\n" 11510 "#include \"a/b/string\"\n" 11511 "#include \"string.h\"\n" 11512 "#include \"string.h\"\n" 11513 "#include <a-a>\n" 11514 "#include < path with space >\n" 11515 "#include_next <test.h>" 11516 "#include \"abc.h\" // this is included for ABC\n" 11517 "#include \"some long include\" // with a comment\n" 11518 "#include \"some very long include path\"\n" 11519 "#include <some/very/long/include/path>\n", 11520 getLLVMStyleWithColumns(35)); 11521 EXPECT_EQ("#include \"a.h\"", format("#include \"a.h\"")); 11522 EXPECT_EQ("#include <a>", format("#include<a>")); 11523 11524 verifyFormat("#import <string>"); 11525 verifyFormat("#import <a/b/c.h>"); 11526 verifyFormat("#import \"a/b/string\""); 11527 verifyFormat("#import \"string.h\""); 11528 verifyFormat("#import \"string.h\""); 11529 verifyFormat("#if __has_include(<strstream>)\n" 11530 "#include <strstream>\n" 11531 "#endif"); 11532 11533 verifyFormat("#define MY_IMPORT <a/b>"); 11534 11535 verifyFormat("#if __has_include(<a/b>)"); 11536 verifyFormat("#if __has_include_next(<a/b>)"); 11537 verifyFormat("#define F __has_include(<a/b>)"); 11538 verifyFormat("#define F __has_include_next(<a/b>)"); 11539 11540 // Protocol buffer definition or missing "#". 11541 verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";", 11542 getLLVMStyleWithColumns(30)); 11543 11544 FormatStyle Style = getLLVMStyle(); 11545 Style.AlwaysBreakBeforeMultilineStrings = true; 11546 Style.ColumnLimit = 0; 11547 verifyFormat("#import \"abc.h\"", Style); 11548 11549 // But 'import' might also be a regular C++ namespace. 11550 verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 11551 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 11552 } 11553 11554 //===----------------------------------------------------------------------===// 11555 // Error recovery tests. 11556 //===----------------------------------------------------------------------===// 11557 11558 TEST_F(FormatTest, IncompleteParameterLists) { 11559 FormatStyle NoBinPacking = getLLVMStyle(); 11560 NoBinPacking.BinPackParameters = false; 11561 verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n" 11562 " double *min_x,\n" 11563 " double *max_x,\n" 11564 " double *min_y,\n" 11565 " double *max_y,\n" 11566 " double *min_z,\n" 11567 " double *max_z, ) {}", 11568 NoBinPacking); 11569 } 11570 11571 TEST_F(FormatTest, IncorrectCodeTrailingStuff) { 11572 verifyFormat("void f() { return; }\n42"); 11573 verifyFormat("void f() {\n" 11574 " if (0)\n" 11575 " return;\n" 11576 "}\n" 11577 "42"); 11578 verifyFormat("void f() { return }\n42"); 11579 verifyFormat("void f() {\n" 11580 " if (0)\n" 11581 " return\n" 11582 "}\n" 11583 "42"); 11584 } 11585 11586 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) { 11587 EXPECT_EQ("void f() { return }", format("void f ( ) { return }")); 11588 EXPECT_EQ("void f() {\n" 11589 " if (a)\n" 11590 " return\n" 11591 "}", 11592 format("void f ( ) { if ( a ) return }")); 11593 EXPECT_EQ("namespace N {\n" 11594 "void f()\n" 11595 "}", 11596 format("namespace N { void f() }")); 11597 EXPECT_EQ("namespace N {\n" 11598 "void f() {}\n" 11599 "void g()\n" 11600 "} // namespace N", 11601 format("namespace N { void f( ) { } void g( ) }")); 11602 } 11603 11604 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) { 11605 verifyFormat("int aaaaaaaa =\n" 11606 " // Overlylongcomment\n" 11607 " b;", 11608 getLLVMStyleWithColumns(20)); 11609 verifyFormat("function(\n" 11610 " ShortArgument,\n" 11611 " LoooooooooooongArgument);\n", 11612 getLLVMStyleWithColumns(20)); 11613 } 11614 11615 TEST_F(FormatTest, IncorrectAccessSpecifier) { 11616 verifyFormat("public:"); 11617 verifyFormat("class A {\n" 11618 "public\n" 11619 " void f() {}\n" 11620 "};"); 11621 verifyFormat("public\n" 11622 "int qwerty;"); 11623 verifyFormat("public\n" 11624 "B {}"); 11625 verifyFormat("public\n" 11626 "{}"); 11627 verifyFormat("public\n" 11628 "B { int x; }"); 11629 } 11630 11631 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) { 11632 verifyFormat("{"); 11633 verifyFormat("#})"); 11634 verifyNoCrash("(/**/[:!] ?[)."); 11635 } 11636 11637 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) { 11638 // Found by oss-fuzz: 11639 // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212 11640 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp); 11641 Style.ColumnLimit = 60; 11642 verifyNoCrash( 11643 "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20" 11644 "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20" 11645 "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a", 11646 Style); 11647 } 11648 11649 TEST_F(FormatTest, IncorrectCodeDoNoWhile) { 11650 verifyFormat("do {\n}"); 11651 verifyFormat("do {\n}\n" 11652 "f();"); 11653 verifyFormat("do {\n}\n" 11654 "wheeee(fun);"); 11655 verifyFormat("do {\n" 11656 " f();\n" 11657 "}"); 11658 } 11659 11660 TEST_F(FormatTest, IncorrectCodeMissingParens) { 11661 verifyFormat("if {\n foo;\n foo();\n}"); 11662 verifyFormat("switch {\n foo;\n foo();\n}"); 11663 verifyIncompleteFormat("for {\n foo;\n foo();\n}"); 11664 verifyFormat("while {\n foo;\n foo();\n}"); 11665 verifyFormat("do {\n foo;\n foo();\n} while;"); 11666 } 11667 11668 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) { 11669 verifyIncompleteFormat("namespace {\n" 11670 "class Foo { Foo (\n" 11671 "};\n" 11672 "} // namespace"); 11673 } 11674 11675 TEST_F(FormatTest, IncorrectCodeErrorDetection) { 11676 EXPECT_EQ("{\n {}\n", format("{\n{\n}\n")); 11677 EXPECT_EQ("{\n {}\n", format("{\n {\n}\n")); 11678 EXPECT_EQ("{\n {}\n", format("{\n {\n }\n")); 11679 EXPECT_EQ("{\n {}\n}\n}\n", format("{\n {\n }\n }\n}\n")); 11680 11681 EXPECT_EQ("{\n" 11682 " {\n" 11683 " breakme(\n" 11684 " qwe);\n" 11685 " }\n", 11686 format("{\n" 11687 " {\n" 11688 " breakme(qwe);\n" 11689 "}\n", 11690 getLLVMStyleWithColumns(10))); 11691 } 11692 11693 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) { 11694 verifyFormat("int x = {\n" 11695 " avariable,\n" 11696 " b(alongervariable)};", 11697 getLLVMStyleWithColumns(25)); 11698 } 11699 11700 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) { 11701 verifyFormat("return (a)(b){1, 2, 3};"); 11702 } 11703 11704 TEST_F(FormatTest, LayoutCxx11BraceInitializers) { 11705 verifyFormat("vector<int> x{1, 2, 3, 4};"); 11706 verifyFormat("vector<int> x{\n" 11707 " 1,\n" 11708 " 2,\n" 11709 " 3,\n" 11710 " 4,\n" 11711 "};"); 11712 verifyFormat("vector<T> x{{}, {}, {}, {}};"); 11713 verifyFormat("f({1, 2});"); 11714 verifyFormat("auto v = Foo{-1};"); 11715 verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});"); 11716 verifyFormat("Class::Class : member{1, 2, 3} {}"); 11717 verifyFormat("new vector<int>{1, 2, 3};"); 11718 verifyFormat("new int[3]{1, 2, 3};"); 11719 verifyFormat("new int{1};"); 11720 verifyFormat("return {arg1, arg2};"); 11721 verifyFormat("return {arg1, SomeType{parameter}};"); 11722 verifyFormat("int count = set<int>{f(), g(), h()}.size();"); 11723 verifyFormat("new T{arg1, arg2};"); 11724 verifyFormat("f(MyMap[{composite, key}]);"); 11725 verifyFormat("class Class {\n" 11726 " T member = {arg1, arg2};\n" 11727 "};"); 11728 verifyFormat("vector<int> foo = {::SomeGlobalFunction()};"); 11729 verifyFormat("const struct A a = {.a = 1, .b = 2};"); 11730 verifyFormat("const struct A a = {[0] = 1, [1] = 2};"); 11731 verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");"); 11732 verifyFormat("int a = std::is_integral<int>{} + 0;"); 11733 11734 verifyFormat("int foo(int i) { return fo1{}(i); }"); 11735 verifyFormat("int foo(int i) { return fo1{}(i); }"); 11736 verifyFormat("auto i = decltype(x){};"); 11737 verifyFormat("auto i = typeof(x){};"); 11738 verifyFormat("auto i = _Atomic(x){};"); 11739 verifyFormat("std::vector<int> v = {1, 0 /* comment */};"); 11740 verifyFormat("Node n{1, Node{1000}, //\n" 11741 " 2};"); 11742 verifyFormat("Aaaa aaaaaaa{\n" 11743 " {\n" 11744 " aaaa,\n" 11745 " },\n" 11746 "};"); 11747 verifyFormat("class C : public D {\n" 11748 " SomeClass SC{2};\n" 11749 "};"); 11750 verifyFormat("class C : public A {\n" 11751 " class D : public B {\n" 11752 " void f() { int i{2}; }\n" 11753 " };\n" 11754 "};"); 11755 verifyFormat("#define A {a, a},"); 11756 // Don't confuse braced list initializers with compound statements. 11757 verifyFormat( 11758 "class A {\n" 11759 " A() : a{} {}\n" 11760 " A(int b) : b(b) {}\n" 11761 " A(int a, int b) : a(a), bs{{bs...}} { f(); }\n" 11762 " int a, b;\n" 11763 " explicit Expr(const Scalar<Result> &x) : u{Constant<Result>{x}} {}\n" 11764 " explicit Expr(Scalar<Result> &&x) : u{Constant<Result>{std::move(x)}} " 11765 "{}\n" 11766 "};"); 11767 11768 // Avoid breaking between equal sign and opening brace 11769 FormatStyle AvoidBreakingFirstArgument = getLLVMStyle(); 11770 AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200; 11771 verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n" 11772 " {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n" 11773 " {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n" 11774 " {\"ccccccccccccccccccccc\", 2}};", 11775 AvoidBreakingFirstArgument); 11776 11777 // Binpacking only if there is no trailing comma 11778 verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n" 11779 " cccccccccc, dddddddddd};", 11780 getLLVMStyleWithColumns(50)); 11781 verifyFormat("const Aaaaaa aaaaa = {\n" 11782 " aaaaaaaaaaa,\n" 11783 " bbbbbbbbbbb,\n" 11784 " ccccccccccc,\n" 11785 " ddddddddddd,\n" 11786 "};", 11787 getLLVMStyleWithColumns(50)); 11788 11789 // Cases where distinguising braced lists and blocks is hard. 11790 verifyFormat("vector<int> v{12} GUARDED_BY(mutex);"); 11791 verifyFormat("void f() {\n" 11792 " return; // comment\n" 11793 "}\n" 11794 "SomeType t;"); 11795 verifyFormat("void f() {\n" 11796 " if (a) {\n" 11797 " f();\n" 11798 " }\n" 11799 "}\n" 11800 "SomeType t;"); 11801 11802 // In combination with BinPackArguments = false. 11803 FormatStyle NoBinPacking = getLLVMStyle(); 11804 NoBinPacking.BinPackArguments = false; 11805 verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n" 11806 " bbbbb,\n" 11807 " ccccc,\n" 11808 " ddddd,\n" 11809 " eeeee,\n" 11810 " ffffff,\n" 11811 " ggggg,\n" 11812 " hhhhhh,\n" 11813 " iiiiii,\n" 11814 " jjjjjj,\n" 11815 " kkkkkk};", 11816 NoBinPacking); 11817 verifyFormat("const Aaaaaa aaaaa = {\n" 11818 " aaaaa,\n" 11819 " bbbbb,\n" 11820 " ccccc,\n" 11821 " ddddd,\n" 11822 " eeeee,\n" 11823 " ffffff,\n" 11824 " ggggg,\n" 11825 " hhhhhh,\n" 11826 " iiiiii,\n" 11827 " jjjjjj,\n" 11828 " kkkkkk,\n" 11829 "};", 11830 NoBinPacking); 11831 verifyFormat( 11832 "const Aaaaaa aaaaa = {\n" 11833 " aaaaa, bbbbb, ccccc, ddddd, eeeee, ffffff, ggggg, hhhhhh,\n" 11834 " iiiiii, jjjjjj, kkkkkk, aaaaa, bbbbb, ccccc, ddddd, eeeee,\n" 11835 " ffffff, ggggg, hhhhhh, iiiiii, jjjjjj, kkkkkk,\n" 11836 "};", 11837 NoBinPacking); 11838 11839 NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 11840 EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n" 11841 " CDDDP83848_BMCR_REGISTER,\n" 11842 " CDDDP83848_BMSR_REGISTER,\n" 11843 " CDDDP83848_RBR_REGISTER};", 11844 format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n" 11845 " CDDDP83848_BMSR_REGISTER,\n" 11846 " CDDDP83848_RBR_REGISTER};", 11847 NoBinPacking)); 11848 11849 // FIXME: The alignment of these trailing comments might be bad. Then again, 11850 // this might be utterly useless in real code. 11851 verifyFormat("Constructor::Constructor()\n" 11852 " : some_value{ //\n" 11853 " aaaaaaa, //\n" 11854 " bbbbbbb} {}"); 11855 11856 // In braced lists, the first comment is always assumed to belong to the 11857 // first element. Thus, it can be moved to the next or previous line as 11858 // appropriate. 11859 EXPECT_EQ("function({// First element:\n" 11860 " 1,\n" 11861 " // Second element:\n" 11862 " 2});", 11863 format("function({\n" 11864 " // First element:\n" 11865 " 1,\n" 11866 " // Second element:\n" 11867 " 2});")); 11868 EXPECT_EQ("std::vector<int> MyNumbers{\n" 11869 " // First element:\n" 11870 " 1,\n" 11871 " // Second element:\n" 11872 " 2};", 11873 format("std::vector<int> MyNumbers{// First element:\n" 11874 " 1,\n" 11875 " // Second element:\n" 11876 " 2};", 11877 getLLVMStyleWithColumns(30))); 11878 // A trailing comma should still lead to an enforced line break and no 11879 // binpacking. 11880 EXPECT_EQ("vector<int> SomeVector = {\n" 11881 " // aaa\n" 11882 " 1,\n" 11883 " 2,\n" 11884 "};", 11885 format("vector<int> SomeVector = { // aaa\n" 11886 " 1, 2, };")); 11887 11888 // C++11 brace initializer list l-braces should not be treated any differently 11889 // when breaking before lambda bodies is enabled 11890 FormatStyle BreakBeforeLambdaBody = getLLVMStyle(); 11891 BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 11892 BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 11893 BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true; 11894 verifyFormat( 11895 "std::runtime_error{\n" 11896 " \"Long string which will force a break onto the next line...\"};", 11897 BreakBeforeLambdaBody); 11898 11899 FormatStyle ExtraSpaces = getLLVMStyle(); 11900 ExtraSpaces.Cpp11BracedListStyle = false; 11901 ExtraSpaces.ColumnLimit = 75; 11902 verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces); 11903 verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces); 11904 verifyFormat("f({ 1, 2 });", ExtraSpaces); 11905 verifyFormat("auto v = Foo{ 1 };", ExtraSpaces); 11906 verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces); 11907 verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces); 11908 verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces); 11909 verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces); 11910 verifyFormat("return { arg1, arg2 };", ExtraSpaces); 11911 verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces); 11912 verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces); 11913 verifyFormat("new T{ arg1, arg2 };", ExtraSpaces); 11914 verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces); 11915 verifyFormat("class Class {\n" 11916 " T member = { arg1, arg2 };\n" 11917 "};", 11918 ExtraSpaces); 11919 verifyFormat( 11920 "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 11921 " aaaaaaaaaaaaaaaaaaaa, aaaaa }\n" 11922 " : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 11923 " bbbbbbbbbbbbbbbbbbbb, bbbbb };", 11924 ExtraSpaces); 11925 verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces); 11926 verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });", 11927 ExtraSpaces); 11928 verifyFormat( 11929 "someFunction(OtherParam,\n" 11930 " BracedList{ // comment 1 (Forcing interesting break)\n" 11931 " param1, param2,\n" 11932 " // comment 2\n" 11933 " param3, param4 });", 11934 ExtraSpaces); 11935 verifyFormat( 11936 "std::this_thread::sleep_for(\n" 11937 " std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);", 11938 ExtraSpaces); 11939 verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n" 11940 " aaaaaaa,\n" 11941 " aaaaaaaaaa,\n" 11942 " aaaaa,\n" 11943 " aaaaaaaaaaaaaaa,\n" 11944 " aaa,\n" 11945 " aaaaaaaaaa,\n" 11946 " a,\n" 11947 " aaaaaaaaaaaaaaaaaaaaa,\n" 11948 " aaaaaaaaaaaa,\n" 11949 " aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n" 11950 " aaaaaaa,\n" 11951 " a};"); 11952 verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces); 11953 verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces); 11954 verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces); 11955 11956 // Avoid breaking between initializer/equal sign and opening brace 11957 ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200; 11958 verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n" 11959 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n" 11960 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n" 11961 " { \"ccccccccccccccccccccc\", 2 }\n" 11962 "};", 11963 ExtraSpaces); 11964 verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n" 11965 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n" 11966 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n" 11967 " { \"ccccccccccccccccccccc\", 2 }\n" 11968 "};", 11969 ExtraSpaces); 11970 11971 FormatStyle SpaceBeforeBrace = getLLVMStyle(); 11972 SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true; 11973 verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace); 11974 verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace); 11975 11976 FormatStyle SpaceBetweenBraces = getLLVMStyle(); 11977 SpaceBetweenBraces.SpacesInAngles = FormatStyle::SIAS_Always; 11978 SpaceBetweenBraces.SpacesInParentheses = true; 11979 SpaceBetweenBraces.SpacesInSquareBrackets = true; 11980 verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces); 11981 verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces); 11982 verifyFormat("vector< int > x{ // comment 1\n" 11983 " 1, 2, 3, 4 };", 11984 SpaceBetweenBraces); 11985 SpaceBetweenBraces.ColumnLimit = 20; 11986 EXPECT_EQ("vector< int > x{\n" 11987 " 1, 2, 3, 4 };", 11988 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces)); 11989 SpaceBetweenBraces.ColumnLimit = 24; 11990 EXPECT_EQ("vector< int > x{ 1, 2,\n" 11991 " 3, 4 };", 11992 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces)); 11993 EXPECT_EQ("vector< int > x{\n" 11994 " 1,\n" 11995 " 2,\n" 11996 " 3,\n" 11997 " 4,\n" 11998 "};", 11999 format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces)); 12000 verifyFormat("vector< int > x{};", SpaceBetweenBraces); 12001 SpaceBetweenBraces.SpaceInEmptyParentheses = true; 12002 verifyFormat("vector< int > x{ };", SpaceBetweenBraces); 12003 } 12004 12005 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) { 12006 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12007 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12008 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12009 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12010 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12011 " 1, 22, 333, 4444, 55555, 666666, 7777777};"); 12012 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n" 12013 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12014 " 1, 22, 333, 4444, 55555, //\n" 12015 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12016 " 1, 22, 333, 4444, 55555, 666666, 7777777};"); 12017 verifyFormat( 12018 "vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12019 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12020 " 1, 22, 333, 4444, 55555, 666666, // comment\n" 12021 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12022 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12023 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12024 " 7777777};"); 12025 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12026 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12027 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12028 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12029 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12030 " // Separating comment.\n" 12031 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12032 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12033 " // Leading comment\n" 12034 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12035 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12036 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12037 " 1, 1, 1, 1};", 12038 getLLVMStyleWithColumns(39)); 12039 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12040 " 1, 1, 1, 1};", 12041 getLLVMStyleWithColumns(38)); 12042 verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n" 12043 " 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};", 12044 getLLVMStyleWithColumns(43)); 12045 verifyFormat( 12046 "static unsigned SomeValues[10][3] = {\n" 12047 " {1, 4, 0}, {4, 9, 0}, {4, 5, 9}, {8, 5, 4}, {1, 8, 4},\n" 12048 " {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};"); 12049 verifyFormat("static auto fields = new vector<string>{\n" 12050 " \"aaaaaaaaaaaaa\",\n" 12051 " \"aaaaaaaaaaaaa\",\n" 12052 " \"aaaaaaaaaaaa\",\n" 12053 " \"aaaaaaaaaaaaaa\",\n" 12054 " \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n" 12055 " \"aaaaaaaaaaaa\",\n" 12056 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n" 12057 "};"); 12058 verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};"); 12059 verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n" 12060 " 2, bbbbbbbbbbbbbbbbbbbbbb,\n" 12061 " 3, cccccccccccccccccccccc};", 12062 getLLVMStyleWithColumns(60)); 12063 12064 // Trailing commas. 12065 verifyFormat("vector<int> x = {\n" 12066 " 1, 1, 1, 1, 1, 1, 1, 1,\n" 12067 "};", 12068 getLLVMStyleWithColumns(39)); 12069 verifyFormat("vector<int> x = {\n" 12070 " 1, 1, 1, 1, 1, 1, 1, 1, //\n" 12071 "};", 12072 getLLVMStyleWithColumns(39)); 12073 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12074 " 1, 1, 1, 1,\n" 12075 " /**/ /**/};", 12076 getLLVMStyleWithColumns(39)); 12077 12078 // Trailing comment in the first line. 12079 verifyFormat("vector<int> iiiiiiiiiiiiiii = { //\n" 12080 " 1111111111, 2222222222, 33333333333, 4444444444, //\n" 12081 " 111111111, 222222222, 3333333333, 444444444, //\n" 12082 " 11111111, 22222222, 333333333, 44444444};"); 12083 // Trailing comment in the last line. 12084 verifyFormat("int aaaaa[] = {\n" 12085 " 1, 2, 3, // comment\n" 12086 " 4, 5, 6 // comment\n" 12087 "};"); 12088 12089 // With nested lists, we should either format one item per line or all nested 12090 // lists one on line. 12091 // FIXME: For some nested lists, we can do better. 12092 verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n" 12093 " {aaaaaaaaaaaaaaaaaaa},\n" 12094 " {aaaaaaaaaaaaaaaaaaaaa},\n" 12095 " {aaaaaaaaaaaaaaaaa}};", 12096 getLLVMStyleWithColumns(60)); 12097 verifyFormat( 12098 "SomeStruct my_struct_array = {\n" 12099 " {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n" 12100 " aaaaaaaaaaaaa, aaaaaaa, aaa},\n" 12101 " {aaa, aaa},\n" 12102 " {aaa, aaa},\n" 12103 " {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n" 12104 " {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n" 12105 " aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};"); 12106 12107 // No column layout should be used here. 12108 verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n" 12109 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};"); 12110 12111 verifyNoCrash("a<,"); 12112 12113 // No braced initializer here. 12114 verifyFormat("void f() {\n" 12115 " struct Dummy {};\n" 12116 " f(v);\n" 12117 "}"); 12118 12119 // Long lists should be formatted in columns even if they are nested. 12120 verifyFormat( 12121 "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12122 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12123 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12124 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12125 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12126 " 1, 22, 333, 4444, 55555, 666666, 7777777});"); 12127 12128 // Allow "single-column" layout even if that violates the column limit. There 12129 // isn't going to be a better way. 12130 verifyFormat("std::vector<int> a = {\n" 12131 " aaaaaaaa,\n" 12132 " aaaaaaaa,\n" 12133 " aaaaaaaa,\n" 12134 " aaaaaaaa,\n" 12135 " aaaaaaaaaa,\n" 12136 " aaaaaaaa,\n" 12137 " aaaaaaaaaaaaaaaaaaaaaaaaaaa};", 12138 getLLVMStyleWithColumns(30)); 12139 verifyFormat("vector<int> aaaa = {\n" 12140 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12141 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12142 " aaaaaa.aaaaaaa,\n" 12143 " aaaaaa.aaaaaaa,\n" 12144 " aaaaaa.aaaaaaa,\n" 12145 " aaaaaa.aaaaaaa,\n" 12146 "};"); 12147 12148 // Don't create hanging lists. 12149 verifyFormat("someFunction(Param, {List1, List2,\n" 12150 " List3});", 12151 getLLVMStyleWithColumns(35)); 12152 verifyFormat("someFunction(Param, Param,\n" 12153 " {List1, List2,\n" 12154 " List3});", 12155 getLLVMStyleWithColumns(35)); 12156 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n" 12157 " aaaaaaaaaaaaaaaaaaaaaaa);"); 12158 } 12159 12160 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) { 12161 FormatStyle DoNotMerge = getLLVMStyle(); 12162 DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12163 12164 verifyFormat("void f() { return 42; }"); 12165 verifyFormat("void f() {\n" 12166 " return 42;\n" 12167 "}", 12168 DoNotMerge); 12169 verifyFormat("void f() {\n" 12170 " // Comment\n" 12171 "}"); 12172 verifyFormat("{\n" 12173 "#error {\n" 12174 " int a;\n" 12175 "}"); 12176 verifyFormat("{\n" 12177 " int a;\n" 12178 "#error {\n" 12179 "}"); 12180 verifyFormat("void f() {} // comment"); 12181 verifyFormat("void f() { int a; } // comment"); 12182 verifyFormat("void f() {\n" 12183 "} // comment", 12184 DoNotMerge); 12185 verifyFormat("void f() {\n" 12186 " int a;\n" 12187 "} // comment", 12188 DoNotMerge); 12189 verifyFormat("void f() {\n" 12190 "} // comment", 12191 getLLVMStyleWithColumns(15)); 12192 12193 verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23)); 12194 verifyFormat("void f() {\n return 42;\n}", getLLVMStyleWithColumns(22)); 12195 12196 verifyFormat("void f() {}", getLLVMStyleWithColumns(11)); 12197 verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10)); 12198 verifyFormat("class C {\n" 12199 " C()\n" 12200 " : iiiiiiii(nullptr),\n" 12201 " kkkkkkk(nullptr),\n" 12202 " mmmmmmm(nullptr),\n" 12203 " nnnnnnn(nullptr) {}\n" 12204 "};", 12205 getGoogleStyle()); 12206 12207 FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0); 12208 EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit)); 12209 EXPECT_EQ("class C {\n" 12210 " A() : b(0) {}\n" 12211 "};", 12212 format("class C{A():b(0){}};", NoColumnLimit)); 12213 EXPECT_EQ("A()\n" 12214 " : b(0) {\n" 12215 "}", 12216 format("A()\n:b(0)\n{\n}", NoColumnLimit)); 12217 12218 FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit; 12219 DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine = 12220 FormatStyle::SFS_None; 12221 EXPECT_EQ("A()\n" 12222 " : b(0) {\n" 12223 "}", 12224 format("A():b(0){}", DoNotMergeNoColumnLimit)); 12225 EXPECT_EQ("A()\n" 12226 " : b(0) {\n" 12227 "}", 12228 format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit)); 12229 12230 verifyFormat("#define A \\\n" 12231 " void f() { \\\n" 12232 " int i; \\\n" 12233 " }", 12234 getLLVMStyleWithColumns(20)); 12235 verifyFormat("#define A \\\n" 12236 " void f() { int i; }", 12237 getLLVMStyleWithColumns(21)); 12238 verifyFormat("#define A \\\n" 12239 " void f() { \\\n" 12240 " int i; \\\n" 12241 " } \\\n" 12242 " int j;", 12243 getLLVMStyleWithColumns(22)); 12244 verifyFormat("#define A \\\n" 12245 " void f() { int i; } \\\n" 12246 " int j;", 12247 getLLVMStyleWithColumns(23)); 12248 } 12249 12250 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) { 12251 FormatStyle MergeEmptyOnly = getLLVMStyle(); 12252 MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 12253 verifyFormat("class C {\n" 12254 " int f() {}\n" 12255 "};", 12256 MergeEmptyOnly); 12257 verifyFormat("class C {\n" 12258 " int f() {\n" 12259 " return 42;\n" 12260 " }\n" 12261 "};", 12262 MergeEmptyOnly); 12263 verifyFormat("int f() {}", MergeEmptyOnly); 12264 verifyFormat("int f() {\n" 12265 " return 42;\n" 12266 "}", 12267 MergeEmptyOnly); 12268 12269 // Also verify behavior when BraceWrapping.AfterFunction = true 12270 MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12271 MergeEmptyOnly.BraceWrapping.AfterFunction = true; 12272 verifyFormat("int f() {}", MergeEmptyOnly); 12273 verifyFormat("class C {\n" 12274 " int f() {}\n" 12275 "};", 12276 MergeEmptyOnly); 12277 } 12278 12279 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) { 12280 FormatStyle MergeInlineOnly = getLLVMStyle(); 12281 MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 12282 verifyFormat("class C {\n" 12283 " int f() { return 42; }\n" 12284 "};", 12285 MergeInlineOnly); 12286 verifyFormat("int f() {\n" 12287 " return 42;\n" 12288 "}", 12289 MergeInlineOnly); 12290 12291 // SFS_Inline implies SFS_Empty 12292 verifyFormat("class C {\n" 12293 " int f() {}\n" 12294 "};", 12295 MergeInlineOnly); 12296 verifyFormat("int f() {}", MergeInlineOnly); 12297 12298 // Also verify behavior when BraceWrapping.AfterFunction = true 12299 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12300 MergeInlineOnly.BraceWrapping.AfterFunction = true; 12301 verifyFormat("class C {\n" 12302 " int f() { return 42; }\n" 12303 "};", 12304 MergeInlineOnly); 12305 verifyFormat("int f()\n" 12306 "{\n" 12307 " return 42;\n" 12308 "}", 12309 MergeInlineOnly); 12310 12311 // SFS_Inline implies SFS_Empty 12312 verifyFormat("int f() {}", MergeInlineOnly); 12313 verifyFormat("class C {\n" 12314 " int f() {}\n" 12315 "};", 12316 MergeInlineOnly); 12317 } 12318 12319 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) { 12320 FormatStyle MergeInlineOnly = getLLVMStyle(); 12321 MergeInlineOnly.AllowShortFunctionsOnASingleLine = 12322 FormatStyle::SFS_InlineOnly; 12323 verifyFormat("class C {\n" 12324 " int f() { return 42; }\n" 12325 "};", 12326 MergeInlineOnly); 12327 verifyFormat("int f() {\n" 12328 " return 42;\n" 12329 "}", 12330 MergeInlineOnly); 12331 12332 // SFS_InlineOnly does not imply SFS_Empty 12333 verifyFormat("class C {\n" 12334 " int f() {}\n" 12335 "};", 12336 MergeInlineOnly); 12337 verifyFormat("int f() {\n" 12338 "}", 12339 MergeInlineOnly); 12340 12341 // Also verify behavior when BraceWrapping.AfterFunction = true 12342 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12343 MergeInlineOnly.BraceWrapping.AfterFunction = true; 12344 verifyFormat("class C {\n" 12345 " int f() { return 42; }\n" 12346 "};", 12347 MergeInlineOnly); 12348 verifyFormat("int f()\n" 12349 "{\n" 12350 " return 42;\n" 12351 "}", 12352 MergeInlineOnly); 12353 12354 // SFS_InlineOnly does not imply SFS_Empty 12355 verifyFormat("int f()\n" 12356 "{\n" 12357 "}", 12358 MergeInlineOnly); 12359 verifyFormat("class C {\n" 12360 " int f() {}\n" 12361 "};", 12362 MergeInlineOnly); 12363 } 12364 12365 TEST_F(FormatTest, SplitEmptyFunction) { 12366 FormatStyle Style = getLLVMStyleWithColumns(40); 12367 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12368 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12369 Style.BraceWrapping.AfterFunction = true; 12370 Style.BraceWrapping.SplitEmptyFunction = false; 12371 12372 verifyFormat("int f()\n" 12373 "{}", 12374 Style); 12375 verifyFormat("int f()\n" 12376 "{\n" 12377 " return 42;\n" 12378 "}", 12379 Style); 12380 verifyFormat("int f()\n" 12381 "{\n" 12382 " // some comment\n" 12383 "}", 12384 Style); 12385 12386 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 12387 verifyFormat("int f() {}", Style); 12388 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12389 "{}", 12390 Style); 12391 verifyFormat("int f()\n" 12392 "{\n" 12393 " return 0;\n" 12394 "}", 12395 Style); 12396 12397 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 12398 verifyFormat("class Foo {\n" 12399 " int f() {}\n" 12400 "};\n", 12401 Style); 12402 verifyFormat("class Foo {\n" 12403 " int f() { return 0; }\n" 12404 "};\n", 12405 Style); 12406 verifyFormat("class Foo {\n" 12407 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12408 " {}\n" 12409 "};\n", 12410 Style); 12411 verifyFormat("class Foo {\n" 12412 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12413 " {\n" 12414 " return 0;\n" 12415 " }\n" 12416 "};\n", 12417 Style); 12418 12419 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 12420 verifyFormat("int f() {}", Style); 12421 verifyFormat("int f() { return 0; }", Style); 12422 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12423 "{}", 12424 Style); 12425 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12426 "{\n" 12427 " return 0;\n" 12428 "}", 12429 Style); 12430 } 12431 12432 TEST_F(FormatTest, SplitEmptyFunctionButNotRecord) { 12433 FormatStyle Style = getLLVMStyleWithColumns(40); 12434 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12435 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12436 Style.BraceWrapping.AfterFunction = true; 12437 Style.BraceWrapping.SplitEmptyFunction = true; 12438 Style.BraceWrapping.SplitEmptyRecord = false; 12439 12440 verifyFormat("class C {};", Style); 12441 verifyFormat("struct C {};", Style); 12442 verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12443 " int bbbbbbbbbbbbbbbbbbbbbbbb)\n" 12444 "{\n" 12445 "}", 12446 Style); 12447 verifyFormat("class C {\n" 12448 " C()\n" 12449 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa(),\n" 12450 " bbbbbbbbbbbbbbbbbbb()\n" 12451 " {\n" 12452 " }\n" 12453 " void\n" 12454 " m(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12455 " int bbbbbbbbbbbbbbbbbbbbbbbb)\n" 12456 " {\n" 12457 " }\n" 12458 "};", 12459 Style); 12460 } 12461 12462 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) { 12463 FormatStyle Style = getLLVMStyle(); 12464 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 12465 verifyFormat("#ifdef A\n" 12466 "int f() {}\n" 12467 "#else\n" 12468 "int g() {}\n" 12469 "#endif", 12470 Style); 12471 } 12472 12473 TEST_F(FormatTest, SplitEmptyClass) { 12474 FormatStyle Style = getLLVMStyle(); 12475 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12476 Style.BraceWrapping.AfterClass = true; 12477 Style.BraceWrapping.SplitEmptyRecord = false; 12478 12479 verifyFormat("class Foo\n" 12480 "{};", 12481 Style); 12482 verifyFormat("/* something */ class Foo\n" 12483 "{};", 12484 Style); 12485 verifyFormat("template <typename X> class Foo\n" 12486 "{};", 12487 Style); 12488 verifyFormat("class Foo\n" 12489 "{\n" 12490 " Foo();\n" 12491 "};", 12492 Style); 12493 verifyFormat("typedef class Foo\n" 12494 "{\n" 12495 "} Foo_t;", 12496 Style); 12497 12498 Style.BraceWrapping.SplitEmptyRecord = true; 12499 Style.BraceWrapping.AfterStruct = true; 12500 verifyFormat("class rep\n" 12501 "{\n" 12502 "};", 12503 Style); 12504 verifyFormat("struct rep\n" 12505 "{\n" 12506 "};", 12507 Style); 12508 verifyFormat("template <typename T> class rep\n" 12509 "{\n" 12510 "};", 12511 Style); 12512 verifyFormat("template <typename T> struct rep\n" 12513 "{\n" 12514 "};", 12515 Style); 12516 verifyFormat("class rep\n" 12517 "{\n" 12518 " int x;\n" 12519 "};", 12520 Style); 12521 verifyFormat("struct rep\n" 12522 "{\n" 12523 " int x;\n" 12524 "};", 12525 Style); 12526 verifyFormat("template <typename T> class rep\n" 12527 "{\n" 12528 " int x;\n" 12529 "};", 12530 Style); 12531 verifyFormat("template <typename T> struct rep\n" 12532 "{\n" 12533 " int x;\n" 12534 "};", 12535 Style); 12536 verifyFormat("template <typename T> class rep // Foo\n" 12537 "{\n" 12538 " int x;\n" 12539 "};", 12540 Style); 12541 verifyFormat("template <typename T> struct rep // Bar\n" 12542 "{\n" 12543 " int x;\n" 12544 "};", 12545 Style); 12546 12547 verifyFormat("template <typename T> class rep<T>\n" 12548 "{\n" 12549 " int x;\n" 12550 "};", 12551 Style); 12552 12553 verifyFormat("template <typename T> class rep<std::complex<T>>\n" 12554 "{\n" 12555 " int x;\n" 12556 "};", 12557 Style); 12558 verifyFormat("template <typename T> class rep<std::complex<T>>\n" 12559 "{\n" 12560 "};", 12561 Style); 12562 12563 verifyFormat("#include \"stdint.h\"\n" 12564 "namespace rep {}", 12565 Style); 12566 verifyFormat("#include <stdint.h>\n" 12567 "namespace rep {}", 12568 Style); 12569 verifyFormat("#include <stdint.h>\n" 12570 "namespace rep {}", 12571 "#include <stdint.h>\n" 12572 "namespace rep {\n" 12573 "\n" 12574 "\n" 12575 "}", 12576 Style); 12577 } 12578 12579 TEST_F(FormatTest, SplitEmptyStruct) { 12580 FormatStyle Style = getLLVMStyle(); 12581 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12582 Style.BraceWrapping.AfterStruct = true; 12583 Style.BraceWrapping.SplitEmptyRecord = false; 12584 12585 verifyFormat("struct Foo\n" 12586 "{};", 12587 Style); 12588 verifyFormat("/* something */ struct Foo\n" 12589 "{};", 12590 Style); 12591 verifyFormat("template <typename X> struct Foo\n" 12592 "{};", 12593 Style); 12594 verifyFormat("struct Foo\n" 12595 "{\n" 12596 " Foo();\n" 12597 "};", 12598 Style); 12599 verifyFormat("typedef struct Foo\n" 12600 "{\n" 12601 "} Foo_t;", 12602 Style); 12603 // typedef struct Bar {} Bar_t; 12604 } 12605 12606 TEST_F(FormatTest, SplitEmptyUnion) { 12607 FormatStyle Style = getLLVMStyle(); 12608 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12609 Style.BraceWrapping.AfterUnion = true; 12610 Style.BraceWrapping.SplitEmptyRecord = false; 12611 12612 verifyFormat("union Foo\n" 12613 "{};", 12614 Style); 12615 verifyFormat("/* something */ union Foo\n" 12616 "{};", 12617 Style); 12618 verifyFormat("union Foo\n" 12619 "{\n" 12620 " A,\n" 12621 "};", 12622 Style); 12623 verifyFormat("typedef union Foo\n" 12624 "{\n" 12625 "} Foo_t;", 12626 Style); 12627 } 12628 12629 TEST_F(FormatTest, SplitEmptyNamespace) { 12630 FormatStyle Style = getLLVMStyle(); 12631 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12632 Style.BraceWrapping.AfterNamespace = true; 12633 Style.BraceWrapping.SplitEmptyNamespace = false; 12634 12635 verifyFormat("namespace Foo\n" 12636 "{};", 12637 Style); 12638 verifyFormat("/* something */ namespace Foo\n" 12639 "{};", 12640 Style); 12641 verifyFormat("inline namespace Foo\n" 12642 "{};", 12643 Style); 12644 verifyFormat("/* something */ inline namespace Foo\n" 12645 "{};", 12646 Style); 12647 verifyFormat("export namespace Foo\n" 12648 "{};", 12649 Style); 12650 verifyFormat("namespace Foo\n" 12651 "{\n" 12652 "void Bar();\n" 12653 "};", 12654 Style); 12655 } 12656 12657 TEST_F(FormatTest, NeverMergeShortRecords) { 12658 FormatStyle Style = getLLVMStyle(); 12659 12660 verifyFormat("class Foo {\n" 12661 " Foo();\n" 12662 "};", 12663 Style); 12664 verifyFormat("typedef class Foo {\n" 12665 " Foo();\n" 12666 "} Foo_t;", 12667 Style); 12668 verifyFormat("struct Foo {\n" 12669 " Foo();\n" 12670 "};", 12671 Style); 12672 verifyFormat("typedef struct Foo {\n" 12673 " Foo();\n" 12674 "} Foo_t;", 12675 Style); 12676 verifyFormat("union Foo {\n" 12677 " A,\n" 12678 "};", 12679 Style); 12680 verifyFormat("typedef union Foo {\n" 12681 " A,\n" 12682 "} Foo_t;", 12683 Style); 12684 verifyFormat("namespace Foo {\n" 12685 "void Bar();\n" 12686 "};", 12687 Style); 12688 12689 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12690 Style.BraceWrapping.AfterClass = true; 12691 Style.BraceWrapping.AfterStruct = true; 12692 Style.BraceWrapping.AfterUnion = true; 12693 Style.BraceWrapping.AfterNamespace = true; 12694 verifyFormat("class Foo\n" 12695 "{\n" 12696 " Foo();\n" 12697 "};", 12698 Style); 12699 verifyFormat("typedef class Foo\n" 12700 "{\n" 12701 " Foo();\n" 12702 "} Foo_t;", 12703 Style); 12704 verifyFormat("struct Foo\n" 12705 "{\n" 12706 " Foo();\n" 12707 "};", 12708 Style); 12709 verifyFormat("typedef struct Foo\n" 12710 "{\n" 12711 " Foo();\n" 12712 "} Foo_t;", 12713 Style); 12714 verifyFormat("union Foo\n" 12715 "{\n" 12716 " A,\n" 12717 "};", 12718 Style); 12719 verifyFormat("typedef union Foo\n" 12720 "{\n" 12721 " A,\n" 12722 "} Foo_t;", 12723 Style); 12724 verifyFormat("namespace Foo\n" 12725 "{\n" 12726 "void Bar();\n" 12727 "};", 12728 Style); 12729 } 12730 12731 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) { 12732 // Elaborate type variable declarations. 12733 verifyFormat("struct foo a = {bar};\nint n;"); 12734 verifyFormat("class foo a = {bar};\nint n;"); 12735 verifyFormat("union foo a = {bar};\nint n;"); 12736 12737 // Elaborate types inside function definitions. 12738 verifyFormat("struct foo f() {}\nint n;"); 12739 verifyFormat("class foo f() {}\nint n;"); 12740 verifyFormat("union foo f() {}\nint n;"); 12741 12742 // Templates. 12743 verifyFormat("template <class X> void f() {}\nint n;"); 12744 verifyFormat("template <struct X> void f() {}\nint n;"); 12745 verifyFormat("template <union X> void f() {}\nint n;"); 12746 12747 // Actual definitions... 12748 verifyFormat("struct {\n} n;"); 12749 verifyFormat( 12750 "template <template <class T, class Y>, class Z> class X {\n} n;"); 12751 verifyFormat("union Z {\n int n;\n} x;"); 12752 verifyFormat("class MACRO Z {\n} n;"); 12753 verifyFormat("class MACRO(X) Z {\n} n;"); 12754 verifyFormat("class __attribute__(X) Z {\n} n;"); 12755 verifyFormat("class __declspec(X) Z {\n} n;"); 12756 verifyFormat("class A##B##C {\n} n;"); 12757 verifyFormat("class alignas(16) Z {\n} n;"); 12758 verifyFormat("class MACRO(X) alignas(16) Z {\n} n;"); 12759 verifyFormat("class MACROA MACRO(X) Z {\n} n;"); 12760 12761 // Redefinition from nested context: 12762 verifyFormat("class A::B::C {\n} n;"); 12763 12764 // Template definitions. 12765 verifyFormat( 12766 "template <typename F>\n" 12767 "Matcher(const Matcher<F> &Other,\n" 12768 " typename enable_if_c<is_base_of<F, T>::value &&\n" 12769 " !is_same<F, T>::value>::type * = 0)\n" 12770 " : Implementation(new ImplicitCastMatcher<F>(Other)) {}"); 12771 12772 // FIXME: This is still incorrectly handled at the formatter side. 12773 verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};"); 12774 verifyFormat("int i = SomeFunction(a<b, a> b);"); 12775 12776 // FIXME: 12777 // This now gets parsed incorrectly as class definition. 12778 // verifyFormat("class A<int> f() {\n}\nint n;"); 12779 12780 // Elaborate types where incorrectly parsing the structural element would 12781 // break the indent. 12782 verifyFormat("if (true)\n" 12783 " class X x;\n" 12784 "else\n" 12785 " f();\n"); 12786 12787 // This is simply incomplete. Formatting is not important, but must not crash. 12788 verifyFormat("class A:"); 12789 } 12790 12791 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) { 12792 EXPECT_EQ("#error Leave all white!!!!! space* alone!\n", 12793 format("#error Leave all white!!!!! space* alone!\n")); 12794 EXPECT_EQ( 12795 "#warning Leave all white!!!!! space* alone!\n", 12796 format("#warning Leave all white!!!!! space* alone!\n")); 12797 EXPECT_EQ("#error 1", format(" # error 1")); 12798 EXPECT_EQ("#warning 1", format(" # warning 1")); 12799 } 12800 12801 TEST_F(FormatTest, FormatHashIfExpressions) { 12802 verifyFormat("#if AAAA && BBBB"); 12803 verifyFormat("#if (AAAA && BBBB)"); 12804 verifyFormat("#elif (AAAA && BBBB)"); 12805 // FIXME: Come up with a better indentation for #elif. 12806 verifyFormat( 12807 "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) && \\\n" 12808 " defined(BBBBBBBB)\n" 12809 "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) && \\\n" 12810 " defined(BBBBBBBB)\n" 12811 "#endif", 12812 getLLVMStyleWithColumns(65)); 12813 } 12814 12815 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) { 12816 FormatStyle AllowsMergedIf = getGoogleStyle(); 12817 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 12818 FormatStyle::SIS_WithoutElse; 12819 verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf); 12820 verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf); 12821 verifyFormat("if (true)\n#error E\n return 42;", AllowsMergedIf); 12822 EXPECT_EQ("if (true) return 42;", 12823 format("if (true)\nreturn 42;", AllowsMergedIf)); 12824 FormatStyle ShortMergedIf = AllowsMergedIf; 12825 ShortMergedIf.ColumnLimit = 25; 12826 verifyFormat("#define A \\\n" 12827 " if (true) return 42;", 12828 ShortMergedIf); 12829 verifyFormat("#define A \\\n" 12830 " f(); \\\n" 12831 " if (true)\n" 12832 "#define B", 12833 ShortMergedIf); 12834 verifyFormat("#define A \\\n" 12835 " f(); \\\n" 12836 " if (true)\n" 12837 "g();", 12838 ShortMergedIf); 12839 verifyFormat("{\n" 12840 "#ifdef A\n" 12841 " // Comment\n" 12842 " if (true) continue;\n" 12843 "#endif\n" 12844 " // Comment\n" 12845 " if (true) continue;\n" 12846 "}", 12847 ShortMergedIf); 12848 ShortMergedIf.ColumnLimit = 33; 12849 verifyFormat("#define A \\\n" 12850 " if constexpr (true) return 42;", 12851 ShortMergedIf); 12852 verifyFormat("#define A \\\n" 12853 " if CONSTEXPR (true) return 42;", 12854 ShortMergedIf); 12855 ShortMergedIf.ColumnLimit = 29; 12856 verifyFormat("#define A \\\n" 12857 " if (aaaaaaaaaa) return 1; \\\n" 12858 " return 2;", 12859 ShortMergedIf); 12860 ShortMergedIf.ColumnLimit = 28; 12861 verifyFormat("#define A \\\n" 12862 " if (aaaaaaaaaa) \\\n" 12863 " return 1; \\\n" 12864 " return 2;", 12865 ShortMergedIf); 12866 verifyFormat("#define A \\\n" 12867 " if constexpr (aaaaaaa) \\\n" 12868 " return 1; \\\n" 12869 " return 2;", 12870 ShortMergedIf); 12871 verifyFormat("#define A \\\n" 12872 " if CONSTEXPR (aaaaaaa) \\\n" 12873 " return 1; \\\n" 12874 " return 2;", 12875 ShortMergedIf); 12876 } 12877 12878 TEST_F(FormatTest, FormatStarDependingOnContext) { 12879 verifyFormat("void f(int *a);"); 12880 verifyFormat("void f() { f(fint * b); }"); 12881 verifyFormat("class A {\n void f(int *a);\n};"); 12882 verifyFormat("class A {\n int *a;\n};"); 12883 verifyFormat("namespace a {\n" 12884 "namespace b {\n" 12885 "class A {\n" 12886 " void f() {}\n" 12887 " int *a;\n" 12888 "};\n" 12889 "} // namespace b\n" 12890 "} // namespace a"); 12891 } 12892 12893 TEST_F(FormatTest, SpecialTokensAtEndOfLine) { 12894 verifyFormat("while"); 12895 verifyFormat("operator"); 12896 } 12897 12898 TEST_F(FormatTest, SkipsDeeplyNestedLines) { 12899 // This code would be painfully slow to format if we didn't skip it. 12900 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 12901 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 12902 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 12903 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 12904 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 12905 "A(1, 1)\n" 12906 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x 12907 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 12908 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 12909 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 12910 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 12911 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 12912 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 12913 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 12914 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 12915 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n"); 12916 // Deeply nested part is untouched, rest is formatted. 12917 EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n", 12918 format(std::string("int i;\n") + Code + "int j;\n", 12919 getLLVMStyle(), SC_ExpectIncomplete)); 12920 } 12921 12922 //===----------------------------------------------------------------------===// 12923 // Objective-C tests. 12924 //===----------------------------------------------------------------------===// 12925 12926 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) { 12927 verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;"); 12928 EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;", 12929 format("-(NSUInteger)indexOfObject:(id)anObject;")); 12930 EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;")); 12931 EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;")); 12932 EXPECT_EQ("- (NSInteger)Method3:(id)anObject;", 12933 format("-(NSInteger)Method3:(id)anObject;")); 12934 EXPECT_EQ("- (NSInteger)Method4:(id)anObject;", 12935 format("-(NSInteger)Method4:(id)anObject;")); 12936 EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;", 12937 format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;")); 12938 EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;", 12939 format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;")); 12940 EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject " 12941 "forAllCells:(BOOL)flag;", 12942 format("- (void)sendAction:(SEL)aSelector to:(id)anObject " 12943 "forAllCells:(BOOL)flag;")); 12944 12945 // Very long objectiveC method declaration. 12946 verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n" 12947 " (SoooooooooooooooooooooomeType *)bbbbbbbbbb;"); 12948 verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n" 12949 " inRange:(NSRange)range\n" 12950 " outRange:(NSRange)out_range\n" 12951 " outRange1:(NSRange)out_range1\n" 12952 " outRange2:(NSRange)out_range2\n" 12953 " outRange3:(NSRange)out_range3\n" 12954 " outRange4:(NSRange)out_range4\n" 12955 " outRange5:(NSRange)out_range5\n" 12956 " outRange6:(NSRange)out_range6\n" 12957 " outRange7:(NSRange)out_range7\n" 12958 " outRange8:(NSRange)out_range8\n" 12959 " outRange9:(NSRange)out_range9;"); 12960 12961 // When the function name has to be wrapped. 12962 FormatStyle Style = getLLVMStyle(); 12963 // ObjC ignores IndentWrappedFunctionNames when wrapping methods 12964 // and always indents instead. 12965 Style.IndentWrappedFunctionNames = false; 12966 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n" 12967 " veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n" 12968 " anotherName:(NSString)bbbbbbbbbbbbbb {\n" 12969 "}", 12970 Style); 12971 Style.IndentWrappedFunctionNames = true; 12972 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n" 12973 " veryLooooooooooongName:(NSString)cccccccccccccc\n" 12974 " anotherName:(NSString)dddddddddddddd {\n" 12975 "}", 12976 Style); 12977 12978 verifyFormat("- (int)sum:(vector<int>)numbers;"); 12979 verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;"); 12980 // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC 12981 // protocol lists (but not for template classes): 12982 // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;"); 12983 12984 verifyFormat("- (int (*)())foo:(int (*)())f;"); 12985 verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;"); 12986 12987 // If there's no return type (very rare in practice!), LLVM and Google style 12988 // agree. 12989 verifyFormat("- foo;"); 12990 verifyFormat("- foo:(int)f;"); 12991 verifyGoogleFormat("- foo:(int)foo;"); 12992 } 12993 12994 TEST_F(FormatTest, BreaksStringLiterals) { 12995 EXPECT_EQ("\"some text \"\n" 12996 "\"other\";", 12997 format("\"some text other\";", getLLVMStyleWithColumns(12))); 12998 EXPECT_EQ("\"some text \"\n" 12999 "\"other\";", 13000 format("\\\n\"some text other\";", getLLVMStyleWithColumns(12))); 13001 EXPECT_EQ( 13002 "#define A \\\n" 13003 " \"some \" \\\n" 13004 " \"text \" \\\n" 13005 " \"other\";", 13006 format("#define A \"some text other\";", getLLVMStyleWithColumns(12))); 13007 EXPECT_EQ( 13008 "#define A \\\n" 13009 " \"so \" \\\n" 13010 " \"text \" \\\n" 13011 " \"other\";", 13012 format("#define A \"so text other\";", getLLVMStyleWithColumns(12))); 13013 13014 EXPECT_EQ("\"some text\"", 13015 format("\"some text\"", getLLVMStyleWithColumns(1))); 13016 EXPECT_EQ("\"some text\"", 13017 format("\"some text\"", getLLVMStyleWithColumns(11))); 13018 EXPECT_EQ("\"some \"\n" 13019 "\"text\"", 13020 format("\"some text\"", getLLVMStyleWithColumns(10))); 13021 EXPECT_EQ("\"some \"\n" 13022 "\"text\"", 13023 format("\"some text\"", getLLVMStyleWithColumns(7))); 13024 EXPECT_EQ("\"some\"\n" 13025 "\" tex\"\n" 13026 "\"t\"", 13027 format("\"some text\"", getLLVMStyleWithColumns(6))); 13028 EXPECT_EQ("\"some\"\n" 13029 "\" tex\"\n" 13030 "\" and\"", 13031 format("\"some tex and\"", getLLVMStyleWithColumns(6))); 13032 EXPECT_EQ("\"some\"\n" 13033 "\"/tex\"\n" 13034 "\"/and\"", 13035 format("\"some/tex/and\"", getLLVMStyleWithColumns(6))); 13036 13037 EXPECT_EQ("variable =\n" 13038 " \"long string \"\n" 13039 " \"literal\";", 13040 format("variable = \"long string literal\";", 13041 getLLVMStyleWithColumns(20))); 13042 13043 EXPECT_EQ("variable = f(\n" 13044 " \"long string \"\n" 13045 " \"literal\",\n" 13046 " short,\n" 13047 " loooooooooooooooooooong);", 13048 format("variable = f(\"long string literal\", short, " 13049 "loooooooooooooooooooong);", 13050 getLLVMStyleWithColumns(20))); 13051 13052 EXPECT_EQ( 13053 "f(g(\"long string \"\n" 13054 " \"literal\"),\n" 13055 " b);", 13056 format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20))); 13057 EXPECT_EQ("f(g(\"long string \"\n" 13058 " \"literal\",\n" 13059 " a),\n" 13060 " b);", 13061 format("f(g(\"long string literal\", a), b);", 13062 getLLVMStyleWithColumns(20))); 13063 EXPECT_EQ( 13064 "f(\"one two\".split(\n" 13065 " variable));", 13066 format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20))); 13067 EXPECT_EQ("f(\"one two three four five six \"\n" 13068 " \"seven\".split(\n" 13069 " really_looooong_variable));", 13070 format("f(\"one two three four five six seven\"." 13071 "split(really_looooong_variable));", 13072 getLLVMStyleWithColumns(33))); 13073 13074 EXPECT_EQ("f(\"some \"\n" 13075 " \"text\",\n" 13076 " other);", 13077 format("f(\"some text\", other);", getLLVMStyleWithColumns(10))); 13078 13079 // Only break as a last resort. 13080 verifyFormat( 13081 "aaaaaaaaaaaaaaaaaaaa(\n" 13082 " aaaaaaaaaaaaaaaaaaaa,\n" 13083 " aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));"); 13084 13085 EXPECT_EQ("\"splitmea\"\n" 13086 "\"trandomp\"\n" 13087 "\"oint\"", 13088 format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10))); 13089 13090 EXPECT_EQ("\"split/\"\n" 13091 "\"pathat/\"\n" 13092 "\"slashes\"", 13093 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10))); 13094 13095 EXPECT_EQ("\"split/\"\n" 13096 "\"pathat/\"\n" 13097 "\"slashes\"", 13098 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10))); 13099 EXPECT_EQ("\"split at \"\n" 13100 "\"spaces/at/\"\n" 13101 "\"slashes.at.any$\"\n" 13102 "\"non-alphanumeric%\"\n" 13103 "\"1111111111characte\"\n" 13104 "\"rs\"", 13105 format("\"split at " 13106 "spaces/at/" 13107 "slashes.at." 13108 "any$non-" 13109 "alphanumeric%" 13110 "1111111111characte" 13111 "rs\"", 13112 getLLVMStyleWithColumns(20))); 13113 13114 // Verify that splitting the strings understands 13115 // Style::AlwaysBreakBeforeMultilineStrings. 13116 EXPECT_EQ("aaaaaaaaaaaa(\n" 13117 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n" 13118 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");", 13119 format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa " 13120 "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa " 13121 "aaaaaaaaaaaaaaaaaaaaaa\");", 13122 getGoogleStyle())); 13123 EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13124 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";", 13125 format("return \"aaaaaaaaaaaaaaaaaaaaaa " 13126 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa " 13127 "aaaaaaaaaaaaaaaaaaaaaa\";", 13128 getGoogleStyle())); 13129 EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13130 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";", 13131 format("llvm::outs() << " 13132 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa" 13133 "aaaaaaaaaaaaaaaaaaa\";")); 13134 EXPECT_EQ("ffff(\n" 13135 " {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13136 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});", 13137 format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa " 13138 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});", 13139 getGoogleStyle())); 13140 13141 FormatStyle Style = getLLVMStyleWithColumns(12); 13142 Style.BreakStringLiterals = false; 13143 EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style)); 13144 13145 FormatStyle AlignLeft = getLLVMStyleWithColumns(12); 13146 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left; 13147 EXPECT_EQ("#define A \\\n" 13148 " \"some \" \\\n" 13149 " \"text \" \\\n" 13150 " \"other\";", 13151 format("#define A \"some text other\";", AlignLeft)); 13152 } 13153 13154 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) { 13155 EXPECT_EQ("C a = \"some more \"\n" 13156 " \"text\";", 13157 format("C a = \"some more text\";", getLLVMStyleWithColumns(18))); 13158 } 13159 13160 TEST_F(FormatTest, FullyRemoveEmptyLines) { 13161 FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80); 13162 NoEmptyLines.MaxEmptyLinesToKeep = 0; 13163 EXPECT_EQ("int i = a(b());", 13164 format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines)); 13165 } 13166 13167 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) { 13168 EXPECT_EQ( 13169 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 13170 "(\n" 13171 " \"x\t\");", 13172 format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 13173 "aaaaaaa(" 13174 "\"x\t\");")); 13175 } 13176 13177 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) { 13178 EXPECT_EQ( 13179 "u8\"utf8 string \"\n" 13180 "u8\"literal\";", 13181 format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16))); 13182 EXPECT_EQ( 13183 "u\"utf16 string \"\n" 13184 "u\"literal\";", 13185 format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16))); 13186 EXPECT_EQ( 13187 "U\"utf32 string \"\n" 13188 "U\"literal\";", 13189 format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16))); 13190 EXPECT_EQ("L\"wide string \"\n" 13191 "L\"literal\";", 13192 format("L\"wide string literal\";", getGoogleStyleWithColumns(16))); 13193 EXPECT_EQ("@\"NSString \"\n" 13194 "@\"literal\";", 13195 format("@\"NSString literal\";", getGoogleStyleWithColumns(19))); 13196 verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26)); 13197 13198 // This input makes clang-format try to split the incomplete unicode escape 13199 // sequence, which used to lead to a crasher. 13200 verifyNoCrash( 13201 "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 13202 getLLVMStyleWithColumns(60)); 13203 } 13204 13205 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) { 13206 FormatStyle Style = getGoogleStyleWithColumns(15); 13207 EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style)); 13208 EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style)); 13209 EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style)); 13210 EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style)); 13211 EXPECT_EQ("u8R\"x(raw literal)x\";", 13212 format("u8R\"x(raw literal)x\";", Style)); 13213 } 13214 13215 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) { 13216 FormatStyle Style = getLLVMStyleWithColumns(20); 13217 EXPECT_EQ( 13218 "_T(\"aaaaaaaaaaaaaa\")\n" 13219 "_T(\"aaaaaaaaaaaaaa\")\n" 13220 "_T(\"aaaaaaaaaaaa\")", 13221 format(" _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style)); 13222 EXPECT_EQ("f(x,\n" 13223 " _T(\"aaaaaaaaaaaa\")\n" 13224 " _T(\"aaa\"),\n" 13225 " z);", 13226 format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style)); 13227 13228 // FIXME: Handle embedded spaces in one iteration. 13229 // EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n" 13230 // "_T(\"aaaaaaaaaaaaa\")\n" 13231 // "_T(\"aaaaaaaaaaaaa\")\n" 13232 // "_T(\"a\")", 13233 // format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", 13234 // getLLVMStyleWithColumns(20))); 13235 EXPECT_EQ( 13236 "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", 13237 format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style)); 13238 EXPECT_EQ("f(\n" 13239 "#if !TEST\n" 13240 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n" 13241 "#endif\n" 13242 ");", 13243 format("f(\n" 13244 "#if !TEST\n" 13245 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n" 13246 "#endif\n" 13247 ");")); 13248 EXPECT_EQ("f(\n" 13249 "\n" 13250 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));", 13251 format("f(\n" 13252 "\n" 13253 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));")); 13254 // Regression test for accessing tokens past the end of a vector in the 13255 // TokenLexer. 13256 verifyNoCrash(R"(_T( 13257 " 13258 ) 13259 )"); 13260 } 13261 13262 TEST_F(FormatTest, BreaksStringLiteralOperands) { 13263 // In a function call with two operands, the second can be broken with no line 13264 // break before it. 13265 EXPECT_EQ( 13266 "func(a, \"long long \"\n" 13267 " \"long long\");", 13268 format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24))); 13269 // In a function call with three operands, the second must be broken with a 13270 // line break before it. 13271 EXPECT_EQ("func(a,\n" 13272 " \"long long long \"\n" 13273 " \"long\",\n" 13274 " c);", 13275 format("func(a, \"long long long long\", c);", 13276 getLLVMStyleWithColumns(24))); 13277 // In a function call with three operands, the third must be broken with a 13278 // line break before it. 13279 EXPECT_EQ("func(a, b,\n" 13280 " \"long long long \"\n" 13281 " \"long\");", 13282 format("func(a, b, \"long long long long\");", 13283 getLLVMStyleWithColumns(24))); 13284 // In a function call with three operands, both the second and the third must 13285 // be broken with a line break before them. 13286 EXPECT_EQ("func(a,\n" 13287 " \"long long long \"\n" 13288 " \"long\",\n" 13289 " \"long long long \"\n" 13290 " \"long\");", 13291 format("func(a, \"long long long long\", \"long long long long\");", 13292 getLLVMStyleWithColumns(24))); 13293 // In a chain of << with two operands, the second can be broken with no line 13294 // break before it. 13295 EXPECT_EQ("a << \"line line \"\n" 13296 " \"line\";", 13297 format("a << \"line line line\";", getLLVMStyleWithColumns(20))); 13298 // In a chain of << with three operands, the second can be broken with no line 13299 // break before it. 13300 EXPECT_EQ( 13301 "abcde << \"line \"\n" 13302 " \"line line\"\n" 13303 " << c;", 13304 format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20))); 13305 // In a chain of << with three operands, the third must be broken with a line 13306 // break before it. 13307 EXPECT_EQ( 13308 "a << b\n" 13309 " << \"line line \"\n" 13310 " \"line\";", 13311 format("a << b << \"line line line\";", getLLVMStyleWithColumns(20))); 13312 // In a chain of << with three operands, the second can be broken with no line 13313 // break before it and the third must be broken with a line break before it. 13314 EXPECT_EQ("abcd << \"line line \"\n" 13315 " \"line\"\n" 13316 " << \"line line \"\n" 13317 " \"line\";", 13318 format("abcd << \"line line line\" << \"line line line\";", 13319 getLLVMStyleWithColumns(20))); 13320 // In a chain of binary operators with two operands, the second can be broken 13321 // with no line break before it. 13322 EXPECT_EQ( 13323 "abcd + \"line line \"\n" 13324 " \"line line\";", 13325 format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20))); 13326 // In a chain of binary operators with three operands, the second must be 13327 // broken with a line break before it. 13328 EXPECT_EQ("abcd +\n" 13329 " \"line line \"\n" 13330 " \"line line\" +\n" 13331 " e;", 13332 format("abcd + \"line line line line\" + e;", 13333 getLLVMStyleWithColumns(20))); 13334 // In a function call with two operands, with AlignAfterOpenBracket enabled, 13335 // the first must be broken with a line break before it. 13336 FormatStyle Style = getLLVMStyleWithColumns(25); 13337 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 13338 EXPECT_EQ("someFunction(\n" 13339 " \"long long long \"\n" 13340 " \"long\",\n" 13341 " a);", 13342 format("someFunction(\"long long long long\", a);", Style)); 13343 } 13344 13345 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) { 13346 EXPECT_EQ( 13347 "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13348 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13349 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";", 13350 format("aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13351 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13352 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";")); 13353 } 13354 13355 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) { 13356 EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);", 13357 format("f(g(R\"x(raw literal)x\", a), b);", getGoogleStyle())); 13358 EXPECT_EQ("fffffffffff(g(R\"x(\n" 13359 "multiline raw string literal xxxxxxxxxxxxxx\n" 13360 ")x\",\n" 13361 " a),\n" 13362 " b);", 13363 format("fffffffffff(g(R\"x(\n" 13364 "multiline raw string literal xxxxxxxxxxxxxx\n" 13365 ")x\", a), b);", 13366 getGoogleStyleWithColumns(20))); 13367 EXPECT_EQ("fffffffffff(\n" 13368 " g(R\"x(qqq\n" 13369 "multiline raw string literal xxxxxxxxxxxxxx\n" 13370 ")x\",\n" 13371 " a),\n" 13372 " b);", 13373 format("fffffffffff(g(R\"x(qqq\n" 13374 "multiline raw string literal xxxxxxxxxxxxxx\n" 13375 ")x\", a), b);", 13376 getGoogleStyleWithColumns(20))); 13377 13378 EXPECT_EQ("fffffffffff(R\"x(\n" 13379 "multiline raw string literal xxxxxxxxxxxxxx\n" 13380 ")x\");", 13381 format("fffffffffff(R\"x(\n" 13382 "multiline raw string literal xxxxxxxxxxxxxx\n" 13383 ")x\");", 13384 getGoogleStyleWithColumns(20))); 13385 EXPECT_EQ("fffffffffff(R\"x(\n" 13386 "multiline raw string literal xxxxxxxxxxxxxx\n" 13387 ")x\" + bbbbbb);", 13388 format("fffffffffff(R\"x(\n" 13389 "multiline raw string literal xxxxxxxxxxxxxx\n" 13390 ")x\" + bbbbbb);", 13391 getGoogleStyleWithColumns(20))); 13392 EXPECT_EQ("fffffffffff(\n" 13393 " R\"x(\n" 13394 "multiline raw string literal xxxxxxxxxxxxxx\n" 13395 ")x\" +\n" 13396 " bbbbbb);", 13397 format("fffffffffff(\n" 13398 " R\"x(\n" 13399 "multiline raw string literal xxxxxxxxxxxxxx\n" 13400 ")x\" + bbbbbb);", 13401 getGoogleStyleWithColumns(20))); 13402 EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);", 13403 format("fffffffffff(\n" 13404 " R\"(single line raw string)\" + bbbbbb);")); 13405 } 13406 13407 TEST_F(FormatTest, SkipsUnknownStringLiterals) { 13408 verifyFormat("string a = \"unterminated;"); 13409 EXPECT_EQ("function(\"unterminated,\n" 13410 " OtherParameter);", 13411 format("function( \"unterminated,\n" 13412 " OtherParameter);")); 13413 } 13414 13415 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) { 13416 FormatStyle Style = getLLVMStyle(); 13417 Style.Standard = FormatStyle::LS_Cpp03; 13418 EXPECT_EQ("#define x(_a) printf(\"foo\" _a);", 13419 format("#define x(_a) printf(\"foo\"_a);", Style)); 13420 } 13421 13422 TEST_F(FormatTest, CppLexVersion) { 13423 FormatStyle Style = getLLVMStyle(); 13424 // Formatting of x * y differs if x is a type. 13425 verifyFormat("void foo() { MACRO(a * b); }", Style); 13426 verifyFormat("void foo() { MACRO(int *b); }", Style); 13427 13428 // LLVM style uses latest lexer. 13429 verifyFormat("void foo() { MACRO(char8_t *b); }", Style); 13430 Style.Standard = FormatStyle::LS_Cpp17; 13431 // But in c++17, char8_t isn't a keyword. 13432 verifyFormat("void foo() { MACRO(char8_t * b); }", Style); 13433 } 13434 13435 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); } 13436 13437 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) { 13438 EXPECT_EQ("someFunction(\"aaabbbcccd\"\n" 13439 " \"ddeeefff\");", 13440 format("someFunction(\"aaabbbcccdddeeefff\");", 13441 getLLVMStyleWithColumns(25))); 13442 EXPECT_EQ("someFunction1234567890(\n" 13443 " \"aaabbbcccdddeeefff\");", 13444 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 13445 getLLVMStyleWithColumns(26))); 13446 EXPECT_EQ("someFunction1234567890(\n" 13447 " \"aaabbbcccdddeeeff\"\n" 13448 " \"f\");", 13449 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 13450 getLLVMStyleWithColumns(25))); 13451 EXPECT_EQ("someFunction1234567890(\n" 13452 " \"aaabbbcccdddeeeff\"\n" 13453 " \"f\");", 13454 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 13455 getLLVMStyleWithColumns(24))); 13456 EXPECT_EQ("someFunction(\n" 13457 " \"aaabbbcc ddde \"\n" 13458 " \"efff\");", 13459 format("someFunction(\"aaabbbcc ddde efff\");", 13460 getLLVMStyleWithColumns(25))); 13461 EXPECT_EQ("someFunction(\"aaabbbccc \"\n" 13462 " \"ddeeefff\");", 13463 format("someFunction(\"aaabbbccc ddeeefff\");", 13464 getLLVMStyleWithColumns(25))); 13465 EXPECT_EQ("someFunction1234567890(\n" 13466 " \"aaabb \"\n" 13467 " \"cccdddeeefff\");", 13468 format("someFunction1234567890(\"aaabb cccdddeeefff\");", 13469 getLLVMStyleWithColumns(25))); 13470 EXPECT_EQ("#define A \\\n" 13471 " string s = \\\n" 13472 " \"123456789\" \\\n" 13473 " \"0\"; \\\n" 13474 " int i;", 13475 format("#define A string s = \"1234567890\"; int i;", 13476 getLLVMStyleWithColumns(20))); 13477 EXPECT_EQ("someFunction(\n" 13478 " \"aaabbbcc \"\n" 13479 " \"dddeeefff\");", 13480 format("someFunction(\"aaabbbcc dddeeefff\");", 13481 getLLVMStyleWithColumns(25))); 13482 } 13483 13484 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) { 13485 EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3))); 13486 EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2))); 13487 EXPECT_EQ("\"test\"\n" 13488 "\"\\n\"", 13489 format("\"test\\n\"", getLLVMStyleWithColumns(7))); 13490 EXPECT_EQ("\"tes\\\\\"\n" 13491 "\"n\"", 13492 format("\"tes\\\\n\"", getLLVMStyleWithColumns(7))); 13493 EXPECT_EQ("\"\\\\\\\\\"\n" 13494 "\"\\n\"", 13495 format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7))); 13496 EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7))); 13497 EXPECT_EQ("\"\\uff01\"\n" 13498 "\"test\"", 13499 format("\"\\uff01test\"", getLLVMStyleWithColumns(8))); 13500 EXPECT_EQ("\"\\Uff01ff02\"", 13501 format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11))); 13502 EXPECT_EQ("\"\\x000000000001\"\n" 13503 "\"next\"", 13504 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16))); 13505 EXPECT_EQ("\"\\x000000000001next\"", 13506 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15))); 13507 EXPECT_EQ("\"\\x000000000001\"", 13508 format("\"\\x000000000001\"", getLLVMStyleWithColumns(7))); 13509 EXPECT_EQ("\"test\"\n" 13510 "\"\\000000\"\n" 13511 "\"000001\"", 13512 format("\"test\\000000000001\"", getLLVMStyleWithColumns(9))); 13513 EXPECT_EQ("\"test\\000\"\n" 13514 "\"00000000\"\n" 13515 "\"1\"", 13516 format("\"test\\000000000001\"", getLLVMStyleWithColumns(10))); 13517 } 13518 13519 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) { 13520 verifyFormat("void f() {\n" 13521 " return g() {}\n" 13522 " void h() {}"); 13523 verifyFormat("int a[] = {void forgot_closing_brace(){f();\n" 13524 "g();\n" 13525 "}"); 13526 } 13527 13528 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) { 13529 verifyFormat( 13530 "void f() { return C{param1, param2}.SomeCall(param1, param2); }"); 13531 } 13532 13533 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) { 13534 verifyFormat("class X {\n" 13535 " void f() {\n" 13536 " }\n" 13537 "};", 13538 getLLVMStyleWithColumns(12)); 13539 } 13540 13541 TEST_F(FormatTest, ConfigurableIndentWidth) { 13542 FormatStyle EightIndent = getLLVMStyleWithColumns(18); 13543 EightIndent.IndentWidth = 8; 13544 EightIndent.ContinuationIndentWidth = 8; 13545 verifyFormat("void f() {\n" 13546 " someFunction();\n" 13547 " if (true) {\n" 13548 " f();\n" 13549 " }\n" 13550 "}", 13551 EightIndent); 13552 verifyFormat("class X {\n" 13553 " void f() {\n" 13554 " }\n" 13555 "};", 13556 EightIndent); 13557 verifyFormat("int x[] = {\n" 13558 " call(),\n" 13559 " call()};", 13560 EightIndent); 13561 } 13562 13563 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) { 13564 verifyFormat("double\n" 13565 "f();", 13566 getLLVMStyleWithColumns(8)); 13567 } 13568 13569 TEST_F(FormatTest, ConfigurableUseOfTab) { 13570 FormatStyle Tab = getLLVMStyleWithColumns(42); 13571 Tab.IndentWidth = 8; 13572 Tab.UseTab = FormatStyle::UT_Always; 13573 Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left; 13574 13575 EXPECT_EQ("if (aaaaaaaa && // q\n" 13576 " bb)\t\t// w\n" 13577 "\t;", 13578 format("if (aaaaaaaa &&// q\n" 13579 "bb)// w\n" 13580 ";", 13581 Tab)); 13582 EXPECT_EQ("if (aaa && bbb) // w\n" 13583 "\t;", 13584 format("if(aaa&&bbb)// w\n" 13585 ";", 13586 Tab)); 13587 13588 verifyFormat("class X {\n" 13589 "\tvoid f() {\n" 13590 "\t\tsomeFunction(parameter1,\n" 13591 "\t\t\t parameter2);\n" 13592 "\t}\n" 13593 "};", 13594 Tab); 13595 verifyFormat("#define A \\\n" 13596 "\tvoid f() { \\\n" 13597 "\t\tsomeFunction( \\\n" 13598 "\t\t parameter1, \\\n" 13599 "\t\t parameter2); \\\n" 13600 "\t}", 13601 Tab); 13602 verifyFormat("int a;\t // x\n" 13603 "int bbbbbbbb; // x\n", 13604 Tab); 13605 13606 Tab.TabWidth = 4; 13607 Tab.IndentWidth = 8; 13608 verifyFormat("class TabWidth4Indent8 {\n" 13609 "\t\tvoid f() {\n" 13610 "\t\t\t\tsomeFunction(parameter1,\n" 13611 "\t\t\t\t\t\t\t parameter2);\n" 13612 "\t\t}\n" 13613 "};", 13614 Tab); 13615 13616 Tab.TabWidth = 4; 13617 Tab.IndentWidth = 4; 13618 verifyFormat("class TabWidth4Indent4 {\n" 13619 "\tvoid f() {\n" 13620 "\t\tsomeFunction(parameter1,\n" 13621 "\t\t\t\t\t parameter2);\n" 13622 "\t}\n" 13623 "};", 13624 Tab); 13625 13626 Tab.TabWidth = 8; 13627 Tab.IndentWidth = 4; 13628 verifyFormat("class TabWidth8Indent4 {\n" 13629 " void f() {\n" 13630 "\tsomeFunction(parameter1,\n" 13631 "\t\t parameter2);\n" 13632 " }\n" 13633 "};", 13634 Tab); 13635 13636 Tab.TabWidth = 8; 13637 Tab.IndentWidth = 8; 13638 EXPECT_EQ("/*\n" 13639 "\t a\t\tcomment\n" 13640 "\t in multiple lines\n" 13641 " */", 13642 format(" /*\t \t \n" 13643 " \t \t a\t\tcomment\t \t\n" 13644 " \t \t in multiple lines\t\n" 13645 " \t */", 13646 Tab)); 13647 13648 Tab.UseTab = FormatStyle::UT_ForIndentation; 13649 verifyFormat("{\n" 13650 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13651 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13652 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13653 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13654 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13655 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13656 "};", 13657 Tab); 13658 verifyFormat("enum AA {\n" 13659 "\ta1, // Force multiple lines\n" 13660 "\ta2,\n" 13661 "\ta3\n" 13662 "};", 13663 Tab); 13664 EXPECT_EQ("if (aaaaaaaa && // q\n" 13665 " bb) // w\n" 13666 "\t;", 13667 format("if (aaaaaaaa &&// q\n" 13668 "bb)// w\n" 13669 ";", 13670 Tab)); 13671 verifyFormat("class X {\n" 13672 "\tvoid f() {\n" 13673 "\t\tsomeFunction(parameter1,\n" 13674 "\t\t parameter2);\n" 13675 "\t}\n" 13676 "};", 13677 Tab); 13678 verifyFormat("{\n" 13679 "\tQ(\n" 13680 "\t {\n" 13681 "\t\t int a;\n" 13682 "\t\t someFunction(aaaaaaaa,\n" 13683 "\t\t bbbbbbb);\n" 13684 "\t },\n" 13685 "\t p);\n" 13686 "}", 13687 Tab); 13688 EXPECT_EQ("{\n" 13689 "\t/* aaaa\n" 13690 "\t bbbb */\n" 13691 "}", 13692 format("{\n" 13693 "/* aaaa\n" 13694 " bbbb */\n" 13695 "}", 13696 Tab)); 13697 EXPECT_EQ("{\n" 13698 "\t/*\n" 13699 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 13700 "\t bbbbbbbbbbbbb\n" 13701 "\t*/\n" 13702 "}", 13703 format("{\n" 13704 "/*\n" 13705 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 13706 "*/\n" 13707 "}", 13708 Tab)); 13709 EXPECT_EQ("{\n" 13710 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 13711 "\t// bbbbbbbbbbbbb\n" 13712 "}", 13713 format("{\n" 13714 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 13715 "}", 13716 Tab)); 13717 EXPECT_EQ("{\n" 13718 "\t/*\n" 13719 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 13720 "\t bbbbbbbbbbbbb\n" 13721 "\t*/\n" 13722 "}", 13723 format("{\n" 13724 "\t/*\n" 13725 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 13726 "\t*/\n" 13727 "}", 13728 Tab)); 13729 EXPECT_EQ("{\n" 13730 "\t/*\n" 13731 "\n" 13732 "\t*/\n" 13733 "}", 13734 format("{\n" 13735 "\t/*\n" 13736 "\n" 13737 "\t*/\n" 13738 "}", 13739 Tab)); 13740 EXPECT_EQ("{\n" 13741 "\t/*\n" 13742 " asdf\n" 13743 "\t*/\n" 13744 "}", 13745 format("{\n" 13746 "\t/*\n" 13747 " asdf\n" 13748 "\t*/\n" 13749 "}", 13750 Tab)); 13751 13752 verifyFormat("void f() {\n" 13753 "\treturn true ? aaaaaaaaaaaaaaaaaa\n" 13754 "\t : bbbbbbbbbbbbbbbbbb\n" 13755 "}", 13756 Tab); 13757 FormatStyle TabNoBreak = Tab; 13758 TabNoBreak.BreakBeforeTernaryOperators = false; 13759 verifyFormat("void f() {\n" 13760 "\treturn true ? aaaaaaaaaaaaaaaaaa :\n" 13761 "\t bbbbbbbbbbbbbbbbbb\n" 13762 "}", 13763 TabNoBreak); 13764 verifyFormat("void f() {\n" 13765 "\treturn true ?\n" 13766 "\t aaaaaaaaaaaaaaaaaaaa :\n" 13767 "\t bbbbbbbbbbbbbbbbbbbb\n" 13768 "}", 13769 TabNoBreak); 13770 13771 Tab.UseTab = FormatStyle::UT_Never; 13772 EXPECT_EQ("/*\n" 13773 " a\t\tcomment\n" 13774 " in multiple lines\n" 13775 " */", 13776 format(" /*\t \t \n" 13777 " \t \t a\t\tcomment\t \t\n" 13778 " \t \t in multiple lines\t\n" 13779 " \t */", 13780 Tab)); 13781 EXPECT_EQ("/* some\n" 13782 " comment */", 13783 format(" \t \t /* some\n" 13784 " \t \t comment */", 13785 Tab)); 13786 EXPECT_EQ("int a; /* some\n" 13787 " comment */", 13788 format(" \t \t int a; /* some\n" 13789 " \t \t comment */", 13790 Tab)); 13791 13792 EXPECT_EQ("int a; /* some\n" 13793 "comment */", 13794 format(" \t \t int\ta; /* some\n" 13795 " \t \t comment */", 13796 Tab)); 13797 EXPECT_EQ("f(\"\t\t\"); /* some\n" 13798 " comment */", 13799 format(" \t \t f(\"\t\t\"); /* some\n" 13800 " \t \t comment */", 13801 Tab)); 13802 EXPECT_EQ("{\n" 13803 " /*\n" 13804 " * Comment\n" 13805 " */\n" 13806 " int i;\n" 13807 "}", 13808 format("{\n" 13809 "\t/*\n" 13810 "\t * Comment\n" 13811 "\t */\n" 13812 "\t int i;\n" 13813 "}", 13814 Tab)); 13815 13816 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation; 13817 Tab.TabWidth = 8; 13818 Tab.IndentWidth = 8; 13819 EXPECT_EQ("if (aaaaaaaa && // q\n" 13820 " bb) // w\n" 13821 "\t;", 13822 format("if (aaaaaaaa &&// q\n" 13823 "bb)// w\n" 13824 ";", 13825 Tab)); 13826 EXPECT_EQ("if (aaa && bbb) // w\n" 13827 "\t;", 13828 format("if(aaa&&bbb)// w\n" 13829 ";", 13830 Tab)); 13831 verifyFormat("class X {\n" 13832 "\tvoid f() {\n" 13833 "\t\tsomeFunction(parameter1,\n" 13834 "\t\t\t parameter2);\n" 13835 "\t}\n" 13836 "};", 13837 Tab); 13838 verifyFormat("#define A \\\n" 13839 "\tvoid f() { \\\n" 13840 "\t\tsomeFunction( \\\n" 13841 "\t\t parameter1, \\\n" 13842 "\t\t parameter2); \\\n" 13843 "\t}", 13844 Tab); 13845 Tab.TabWidth = 4; 13846 Tab.IndentWidth = 8; 13847 verifyFormat("class TabWidth4Indent8 {\n" 13848 "\t\tvoid f() {\n" 13849 "\t\t\t\tsomeFunction(parameter1,\n" 13850 "\t\t\t\t\t\t\t parameter2);\n" 13851 "\t\t}\n" 13852 "};", 13853 Tab); 13854 Tab.TabWidth = 4; 13855 Tab.IndentWidth = 4; 13856 verifyFormat("class TabWidth4Indent4 {\n" 13857 "\tvoid f() {\n" 13858 "\t\tsomeFunction(parameter1,\n" 13859 "\t\t\t\t\t parameter2);\n" 13860 "\t}\n" 13861 "};", 13862 Tab); 13863 Tab.TabWidth = 8; 13864 Tab.IndentWidth = 4; 13865 verifyFormat("class TabWidth8Indent4 {\n" 13866 " void f() {\n" 13867 "\tsomeFunction(parameter1,\n" 13868 "\t\t parameter2);\n" 13869 " }\n" 13870 "};", 13871 Tab); 13872 Tab.TabWidth = 8; 13873 Tab.IndentWidth = 8; 13874 EXPECT_EQ("/*\n" 13875 "\t a\t\tcomment\n" 13876 "\t in multiple lines\n" 13877 " */", 13878 format(" /*\t \t \n" 13879 " \t \t a\t\tcomment\t \t\n" 13880 " \t \t in multiple lines\t\n" 13881 " \t */", 13882 Tab)); 13883 verifyFormat("{\n" 13884 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13885 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13886 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13887 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13888 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13889 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13890 "};", 13891 Tab); 13892 verifyFormat("enum AA {\n" 13893 "\ta1, // Force multiple lines\n" 13894 "\ta2,\n" 13895 "\ta3\n" 13896 "};", 13897 Tab); 13898 EXPECT_EQ("if (aaaaaaaa && // q\n" 13899 " bb) // w\n" 13900 "\t;", 13901 format("if (aaaaaaaa &&// q\n" 13902 "bb)// w\n" 13903 ";", 13904 Tab)); 13905 verifyFormat("class X {\n" 13906 "\tvoid f() {\n" 13907 "\t\tsomeFunction(parameter1,\n" 13908 "\t\t\t parameter2);\n" 13909 "\t}\n" 13910 "};", 13911 Tab); 13912 verifyFormat("{\n" 13913 "\tQ(\n" 13914 "\t {\n" 13915 "\t\t int a;\n" 13916 "\t\t someFunction(aaaaaaaa,\n" 13917 "\t\t\t\t bbbbbbb);\n" 13918 "\t },\n" 13919 "\t p);\n" 13920 "}", 13921 Tab); 13922 EXPECT_EQ("{\n" 13923 "\t/* aaaa\n" 13924 "\t bbbb */\n" 13925 "}", 13926 format("{\n" 13927 "/* aaaa\n" 13928 " bbbb */\n" 13929 "}", 13930 Tab)); 13931 EXPECT_EQ("{\n" 13932 "\t/*\n" 13933 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 13934 "\t bbbbbbbbbbbbb\n" 13935 "\t*/\n" 13936 "}", 13937 format("{\n" 13938 "/*\n" 13939 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 13940 "*/\n" 13941 "}", 13942 Tab)); 13943 EXPECT_EQ("{\n" 13944 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 13945 "\t// bbbbbbbbbbbbb\n" 13946 "}", 13947 format("{\n" 13948 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 13949 "}", 13950 Tab)); 13951 EXPECT_EQ("{\n" 13952 "\t/*\n" 13953 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 13954 "\t bbbbbbbbbbbbb\n" 13955 "\t*/\n" 13956 "}", 13957 format("{\n" 13958 "\t/*\n" 13959 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 13960 "\t*/\n" 13961 "}", 13962 Tab)); 13963 EXPECT_EQ("{\n" 13964 "\t/*\n" 13965 "\n" 13966 "\t*/\n" 13967 "}", 13968 format("{\n" 13969 "\t/*\n" 13970 "\n" 13971 "\t*/\n" 13972 "}", 13973 Tab)); 13974 EXPECT_EQ("{\n" 13975 "\t/*\n" 13976 " asdf\n" 13977 "\t*/\n" 13978 "}", 13979 format("{\n" 13980 "\t/*\n" 13981 " asdf\n" 13982 "\t*/\n" 13983 "}", 13984 Tab)); 13985 EXPECT_EQ("/* some\n" 13986 " comment */", 13987 format(" \t \t /* some\n" 13988 " \t \t comment */", 13989 Tab)); 13990 EXPECT_EQ("int a; /* some\n" 13991 " comment */", 13992 format(" \t \t int a; /* some\n" 13993 " \t \t comment */", 13994 Tab)); 13995 EXPECT_EQ("int a; /* some\n" 13996 "comment */", 13997 format(" \t \t int\ta; /* some\n" 13998 " \t \t comment */", 13999 Tab)); 14000 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14001 " comment */", 14002 format(" \t \t f(\"\t\t\"); /* some\n" 14003 " \t \t comment */", 14004 Tab)); 14005 EXPECT_EQ("{\n" 14006 "\t/*\n" 14007 "\t * Comment\n" 14008 "\t */\n" 14009 "\tint i;\n" 14010 "}", 14011 format("{\n" 14012 "\t/*\n" 14013 "\t * Comment\n" 14014 "\t */\n" 14015 "\t int i;\n" 14016 "}", 14017 Tab)); 14018 Tab.TabWidth = 2; 14019 Tab.IndentWidth = 2; 14020 EXPECT_EQ("{\n" 14021 "\t/* aaaa\n" 14022 "\t\t bbbb */\n" 14023 "}", 14024 format("{\n" 14025 "/* aaaa\n" 14026 "\t bbbb */\n" 14027 "}", 14028 Tab)); 14029 EXPECT_EQ("{\n" 14030 "\t/*\n" 14031 "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14032 "\t\tbbbbbbbbbbbbb\n" 14033 "\t*/\n" 14034 "}", 14035 format("{\n" 14036 "/*\n" 14037 "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14038 "*/\n" 14039 "}", 14040 Tab)); 14041 Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 14042 Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 14043 Tab.TabWidth = 4; 14044 Tab.IndentWidth = 4; 14045 verifyFormat("class Assign {\n" 14046 "\tvoid f() {\n" 14047 "\t\tint x = 123;\n" 14048 "\t\tint random = 4;\n" 14049 "\t\tstd::string alphabet =\n" 14050 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n" 14051 "\t}\n" 14052 "};", 14053 Tab); 14054 14055 Tab.UseTab = FormatStyle::UT_AlignWithSpaces; 14056 Tab.TabWidth = 8; 14057 Tab.IndentWidth = 8; 14058 EXPECT_EQ("if (aaaaaaaa && // q\n" 14059 " bb) // w\n" 14060 "\t;", 14061 format("if (aaaaaaaa &&// q\n" 14062 "bb)// w\n" 14063 ";", 14064 Tab)); 14065 EXPECT_EQ("if (aaa && bbb) // w\n" 14066 "\t;", 14067 format("if(aaa&&bbb)// w\n" 14068 ";", 14069 Tab)); 14070 verifyFormat("class X {\n" 14071 "\tvoid f() {\n" 14072 "\t\tsomeFunction(parameter1,\n" 14073 "\t\t parameter2);\n" 14074 "\t}\n" 14075 "};", 14076 Tab); 14077 verifyFormat("#define A \\\n" 14078 "\tvoid f() { \\\n" 14079 "\t\tsomeFunction( \\\n" 14080 "\t\t parameter1, \\\n" 14081 "\t\t parameter2); \\\n" 14082 "\t}", 14083 Tab); 14084 Tab.TabWidth = 4; 14085 Tab.IndentWidth = 8; 14086 verifyFormat("class TabWidth4Indent8 {\n" 14087 "\t\tvoid f() {\n" 14088 "\t\t\t\tsomeFunction(parameter1,\n" 14089 "\t\t\t\t parameter2);\n" 14090 "\t\t}\n" 14091 "};", 14092 Tab); 14093 Tab.TabWidth = 4; 14094 Tab.IndentWidth = 4; 14095 verifyFormat("class TabWidth4Indent4 {\n" 14096 "\tvoid f() {\n" 14097 "\t\tsomeFunction(parameter1,\n" 14098 "\t\t parameter2);\n" 14099 "\t}\n" 14100 "};", 14101 Tab); 14102 Tab.TabWidth = 8; 14103 Tab.IndentWidth = 4; 14104 verifyFormat("class TabWidth8Indent4 {\n" 14105 " void f() {\n" 14106 "\tsomeFunction(parameter1,\n" 14107 "\t parameter2);\n" 14108 " }\n" 14109 "};", 14110 Tab); 14111 Tab.TabWidth = 8; 14112 Tab.IndentWidth = 8; 14113 EXPECT_EQ("/*\n" 14114 " a\t\tcomment\n" 14115 " in multiple lines\n" 14116 " */", 14117 format(" /*\t \t \n" 14118 " \t \t a\t\tcomment\t \t\n" 14119 " \t \t in multiple lines\t\n" 14120 " \t */", 14121 Tab)); 14122 verifyFormat("{\n" 14123 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14124 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14125 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14126 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14127 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14128 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14129 "};", 14130 Tab); 14131 verifyFormat("enum AA {\n" 14132 "\ta1, // Force multiple lines\n" 14133 "\ta2,\n" 14134 "\ta3\n" 14135 "};", 14136 Tab); 14137 EXPECT_EQ("if (aaaaaaaa && // q\n" 14138 " bb) // w\n" 14139 "\t;", 14140 format("if (aaaaaaaa &&// q\n" 14141 "bb)// w\n" 14142 ";", 14143 Tab)); 14144 verifyFormat("class X {\n" 14145 "\tvoid f() {\n" 14146 "\t\tsomeFunction(parameter1,\n" 14147 "\t\t parameter2);\n" 14148 "\t}\n" 14149 "};", 14150 Tab); 14151 verifyFormat("{\n" 14152 "\tQ(\n" 14153 "\t {\n" 14154 "\t\t int a;\n" 14155 "\t\t someFunction(aaaaaaaa,\n" 14156 "\t\t bbbbbbb);\n" 14157 "\t },\n" 14158 "\t p);\n" 14159 "}", 14160 Tab); 14161 EXPECT_EQ("{\n" 14162 "\t/* aaaa\n" 14163 "\t bbbb */\n" 14164 "}", 14165 format("{\n" 14166 "/* aaaa\n" 14167 " bbbb */\n" 14168 "}", 14169 Tab)); 14170 EXPECT_EQ("{\n" 14171 "\t/*\n" 14172 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14173 "\t bbbbbbbbbbbbb\n" 14174 "\t*/\n" 14175 "}", 14176 format("{\n" 14177 "/*\n" 14178 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14179 "*/\n" 14180 "}", 14181 Tab)); 14182 EXPECT_EQ("{\n" 14183 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14184 "\t// bbbbbbbbbbbbb\n" 14185 "}", 14186 format("{\n" 14187 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14188 "}", 14189 Tab)); 14190 EXPECT_EQ("{\n" 14191 "\t/*\n" 14192 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14193 "\t bbbbbbbbbbbbb\n" 14194 "\t*/\n" 14195 "}", 14196 format("{\n" 14197 "\t/*\n" 14198 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14199 "\t*/\n" 14200 "}", 14201 Tab)); 14202 EXPECT_EQ("{\n" 14203 "\t/*\n" 14204 "\n" 14205 "\t*/\n" 14206 "}", 14207 format("{\n" 14208 "\t/*\n" 14209 "\n" 14210 "\t*/\n" 14211 "}", 14212 Tab)); 14213 EXPECT_EQ("{\n" 14214 "\t/*\n" 14215 " asdf\n" 14216 "\t*/\n" 14217 "}", 14218 format("{\n" 14219 "\t/*\n" 14220 " asdf\n" 14221 "\t*/\n" 14222 "}", 14223 Tab)); 14224 EXPECT_EQ("/* some\n" 14225 " comment */", 14226 format(" \t \t /* some\n" 14227 " \t \t comment */", 14228 Tab)); 14229 EXPECT_EQ("int a; /* some\n" 14230 " comment */", 14231 format(" \t \t int a; /* some\n" 14232 " \t \t comment */", 14233 Tab)); 14234 EXPECT_EQ("int a; /* some\n" 14235 "comment */", 14236 format(" \t \t int\ta; /* some\n" 14237 " \t \t comment */", 14238 Tab)); 14239 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14240 " comment */", 14241 format(" \t \t f(\"\t\t\"); /* some\n" 14242 " \t \t comment */", 14243 Tab)); 14244 EXPECT_EQ("{\n" 14245 "\t/*\n" 14246 "\t * Comment\n" 14247 "\t */\n" 14248 "\tint i;\n" 14249 "}", 14250 format("{\n" 14251 "\t/*\n" 14252 "\t * Comment\n" 14253 "\t */\n" 14254 "\t int i;\n" 14255 "}", 14256 Tab)); 14257 Tab.TabWidth = 2; 14258 Tab.IndentWidth = 2; 14259 EXPECT_EQ("{\n" 14260 "\t/* aaaa\n" 14261 "\t bbbb */\n" 14262 "}", 14263 format("{\n" 14264 "/* aaaa\n" 14265 " bbbb */\n" 14266 "}", 14267 Tab)); 14268 EXPECT_EQ("{\n" 14269 "\t/*\n" 14270 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14271 "\t bbbbbbbbbbbbb\n" 14272 "\t*/\n" 14273 "}", 14274 format("{\n" 14275 "/*\n" 14276 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14277 "*/\n" 14278 "}", 14279 Tab)); 14280 Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 14281 Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 14282 Tab.TabWidth = 4; 14283 Tab.IndentWidth = 4; 14284 verifyFormat("class Assign {\n" 14285 "\tvoid f() {\n" 14286 "\t\tint x = 123;\n" 14287 "\t\tint random = 4;\n" 14288 "\t\tstd::string alphabet =\n" 14289 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n" 14290 "\t}\n" 14291 "};", 14292 Tab); 14293 Tab.AlignOperands = FormatStyle::OAS_Align; 14294 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n" 14295 " cccccccccccccccccccc;", 14296 Tab); 14297 // no alignment 14298 verifyFormat("int aaaaaaaaaa =\n" 14299 "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 14300 Tab); 14301 verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n" 14302 " : bbbbbbbbbbbbbb ? 222222222222222\n" 14303 " : 333333333333333;", 14304 Tab); 14305 Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 14306 Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator; 14307 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n" 14308 " + cccccccccccccccccccc;", 14309 Tab); 14310 } 14311 14312 TEST_F(FormatTest, ZeroTabWidth) { 14313 FormatStyle Tab = getLLVMStyleWithColumns(42); 14314 Tab.IndentWidth = 8; 14315 Tab.UseTab = FormatStyle::UT_Never; 14316 Tab.TabWidth = 0; 14317 EXPECT_EQ("void a(){\n" 14318 " // line starts with '\t'\n" 14319 "};", 14320 format("void a(){\n" 14321 "\t// line starts with '\t'\n" 14322 "};", 14323 Tab)); 14324 14325 EXPECT_EQ("void a(){\n" 14326 " // line starts with '\t'\n" 14327 "};", 14328 format("void a(){\n" 14329 "\t\t// line starts with '\t'\n" 14330 "};", 14331 Tab)); 14332 14333 Tab.UseTab = FormatStyle::UT_ForIndentation; 14334 EXPECT_EQ("void a(){\n" 14335 " // line starts with '\t'\n" 14336 "};", 14337 format("void a(){\n" 14338 "\t// line starts with '\t'\n" 14339 "};", 14340 Tab)); 14341 14342 EXPECT_EQ("void a(){\n" 14343 " // line starts with '\t'\n" 14344 "};", 14345 format("void a(){\n" 14346 "\t\t// line starts with '\t'\n" 14347 "};", 14348 Tab)); 14349 14350 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation; 14351 EXPECT_EQ("void a(){\n" 14352 " // line starts with '\t'\n" 14353 "};", 14354 format("void a(){\n" 14355 "\t// line starts with '\t'\n" 14356 "};", 14357 Tab)); 14358 14359 EXPECT_EQ("void a(){\n" 14360 " // line starts with '\t'\n" 14361 "};", 14362 format("void a(){\n" 14363 "\t\t// line starts with '\t'\n" 14364 "};", 14365 Tab)); 14366 14367 Tab.UseTab = FormatStyle::UT_AlignWithSpaces; 14368 EXPECT_EQ("void a(){\n" 14369 " // line starts with '\t'\n" 14370 "};", 14371 format("void a(){\n" 14372 "\t// line starts with '\t'\n" 14373 "};", 14374 Tab)); 14375 14376 EXPECT_EQ("void a(){\n" 14377 " // line starts with '\t'\n" 14378 "};", 14379 format("void a(){\n" 14380 "\t\t// line starts with '\t'\n" 14381 "};", 14382 Tab)); 14383 14384 Tab.UseTab = FormatStyle::UT_Always; 14385 EXPECT_EQ("void a(){\n" 14386 "// line starts with '\t'\n" 14387 "};", 14388 format("void a(){\n" 14389 "\t// line starts with '\t'\n" 14390 "};", 14391 Tab)); 14392 14393 EXPECT_EQ("void a(){\n" 14394 "// line starts with '\t'\n" 14395 "};", 14396 format("void a(){\n" 14397 "\t\t// line starts with '\t'\n" 14398 "};", 14399 Tab)); 14400 } 14401 14402 TEST_F(FormatTest, CalculatesOriginalColumn) { 14403 EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14404 "q\"; /* some\n" 14405 " comment */", 14406 format(" \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14407 "q\"; /* some\n" 14408 " comment */", 14409 getLLVMStyle())); 14410 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n" 14411 "/* some\n" 14412 " comment */", 14413 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n" 14414 " /* some\n" 14415 " comment */", 14416 getLLVMStyle())); 14417 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14418 "qqq\n" 14419 "/* some\n" 14420 " comment */", 14421 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14422 "qqq\n" 14423 " /* some\n" 14424 " comment */", 14425 getLLVMStyle())); 14426 EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14427 "wwww; /* some\n" 14428 " comment */", 14429 format(" inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14430 "wwww; /* some\n" 14431 " comment */", 14432 getLLVMStyle())); 14433 } 14434 14435 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) { 14436 FormatStyle NoSpace = getLLVMStyle(); 14437 NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never; 14438 14439 verifyFormat("while(true)\n" 14440 " continue;", 14441 NoSpace); 14442 verifyFormat("for(;;)\n" 14443 " continue;", 14444 NoSpace); 14445 verifyFormat("if(true)\n" 14446 " f();\n" 14447 "else if(true)\n" 14448 " f();", 14449 NoSpace); 14450 verifyFormat("do {\n" 14451 " do_something();\n" 14452 "} while(something());", 14453 NoSpace); 14454 verifyFormat("switch(x) {\n" 14455 "default:\n" 14456 " break;\n" 14457 "}", 14458 NoSpace); 14459 verifyFormat("auto i = std::make_unique<int>(5);", NoSpace); 14460 verifyFormat("size_t x = sizeof(x);", NoSpace); 14461 verifyFormat("auto f(int x) -> decltype(x);", NoSpace); 14462 verifyFormat("auto f(int x) -> typeof(x);", NoSpace); 14463 verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace); 14464 verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace); 14465 verifyFormat("int f(T x) noexcept(x.create());", NoSpace); 14466 verifyFormat("alignas(128) char a[128];", NoSpace); 14467 verifyFormat("size_t x = alignof(MyType);", NoSpace); 14468 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace); 14469 verifyFormat("int f() throw(Deprecated);", NoSpace); 14470 verifyFormat("typedef void (*cb)(int);", NoSpace); 14471 verifyFormat("T A::operator()();", NoSpace); 14472 verifyFormat("X A::operator++(T);", NoSpace); 14473 verifyFormat("auto lambda = []() { return 0; };", NoSpace); 14474 14475 FormatStyle Space = getLLVMStyle(); 14476 Space.SpaceBeforeParens = FormatStyle::SBPO_Always; 14477 14478 verifyFormat("int f ();", Space); 14479 verifyFormat("void f (int a, T b) {\n" 14480 " while (true)\n" 14481 " continue;\n" 14482 "}", 14483 Space); 14484 verifyFormat("if (true)\n" 14485 " f ();\n" 14486 "else if (true)\n" 14487 " f ();", 14488 Space); 14489 verifyFormat("do {\n" 14490 " do_something ();\n" 14491 "} while (something ());", 14492 Space); 14493 verifyFormat("switch (x) {\n" 14494 "default:\n" 14495 " break;\n" 14496 "}", 14497 Space); 14498 verifyFormat("A::A () : a (1) {}", Space); 14499 verifyFormat("void f () __attribute__ ((asdf));", Space); 14500 verifyFormat("*(&a + 1);\n" 14501 "&((&a)[1]);\n" 14502 "a[(b + c) * d];\n" 14503 "(((a + 1) * 2) + 3) * 4;", 14504 Space); 14505 verifyFormat("#define A(x) x", Space); 14506 verifyFormat("#define A (x) x", Space); 14507 verifyFormat("#if defined(x)\n" 14508 "#endif", 14509 Space); 14510 verifyFormat("auto i = std::make_unique<int> (5);", Space); 14511 verifyFormat("size_t x = sizeof (x);", Space); 14512 verifyFormat("auto f (int x) -> decltype (x);", Space); 14513 verifyFormat("auto f (int x) -> typeof (x);", Space); 14514 verifyFormat("auto f (int x) -> _Atomic (x);", Space); 14515 verifyFormat("auto f (int x) -> __underlying_type (x);", Space); 14516 verifyFormat("int f (T x) noexcept (x.create ());", Space); 14517 verifyFormat("alignas (128) char a[128];", Space); 14518 verifyFormat("size_t x = alignof (MyType);", Space); 14519 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space); 14520 verifyFormat("int f () throw (Deprecated);", Space); 14521 verifyFormat("typedef void (*cb) (int);", Space); 14522 // FIXME these tests regressed behaviour. 14523 // verifyFormat("T A::operator() ();", Space); 14524 // verifyFormat("X A::operator++ (T);", Space); 14525 verifyFormat("auto lambda = [] () { return 0; };", Space); 14526 verifyFormat("int x = int (y);", Space); 14527 14528 FormatStyle SomeSpace = getLLVMStyle(); 14529 SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses; 14530 14531 verifyFormat("[]() -> float {}", SomeSpace); 14532 verifyFormat("[] (auto foo) {}", SomeSpace); 14533 verifyFormat("[foo]() -> int {}", SomeSpace); 14534 verifyFormat("int f();", SomeSpace); 14535 verifyFormat("void f (int a, T b) {\n" 14536 " while (true)\n" 14537 " continue;\n" 14538 "}", 14539 SomeSpace); 14540 verifyFormat("if (true)\n" 14541 " f();\n" 14542 "else if (true)\n" 14543 " f();", 14544 SomeSpace); 14545 verifyFormat("do {\n" 14546 " do_something();\n" 14547 "} while (something());", 14548 SomeSpace); 14549 verifyFormat("switch (x) {\n" 14550 "default:\n" 14551 " break;\n" 14552 "}", 14553 SomeSpace); 14554 verifyFormat("A::A() : a (1) {}", SomeSpace); 14555 verifyFormat("void f() __attribute__ ((asdf));", SomeSpace); 14556 verifyFormat("*(&a + 1);\n" 14557 "&((&a)[1]);\n" 14558 "a[(b + c) * d];\n" 14559 "(((a + 1) * 2) + 3) * 4;", 14560 SomeSpace); 14561 verifyFormat("#define A(x) x", SomeSpace); 14562 verifyFormat("#define A (x) x", SomeSpace); 14563 verifyFormat("#if defined(x)\n" 14564 "#endif", 14565 SomeSpace); 14566 verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace); 14567 verifyFormat("size_t x = sizeof (x);", SomeSpace); 14568 verifyFormat("auto f (int x) -> decltype (x);", SomeSpace); 14569 verifyFormat("auto f (int x) -> typeof (x);", SomeSpace); 14570 verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace); 14571 verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace); 14572 verifyFormat("int f (T x) noexcept (x.create());", SomeSpace); 14573 verifyFormat("alignas (128) char a[128];", SomeSpace); 14574 verifyFormat("size_t x = alignof (MyType);", SomeSpace); 14575 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", 14576 SomeSpace); 14577 verifyFormat("int f() throw (Deprecated);", SomeSpace); 14578 verifyFormat("typedef void (*cb) (int);", SomeSpace); 14579 verifyFormat("T A::operator()();", SomeSpace); 14580 // FIXME these tests regressed behaviour. 14581 // verifyFormat("X A::operator++ (T);", SomeSpace); 14582 verifyFormat("int x = int (y);", SomeSpace); 14583 verifyFormat("auto lambda = []() { return 0; };", SomeSpace); 14584 14585 FormatStyle SpaceControlStatements = getLLVMStyle(); 14586 SpaceControlStatements.SpaceBeforeParens = FormatStyle::SBPO_Custom; 14587 SpaceControlStatements.SpaceBeforeParensOptions.AfterControlStatements = true; 14588 14589 verifyFormat("while (true)\n" 14590 " continue;", 14591 SpaceControlStatements); 14592 verifyFormat("if (true)\n" 14593 " f();\n" 14594 "else if (true)\n" 14595 " f();", 14596 SpaceControlStatements); 14597 verifyFormat("for (;;) {\n" 14598 " do_something();\n" 14599 "}", 14600 SpaceControlStatements); 14601 verifyFormat("do {\n" 14602 " do_something();\n" 14603 "} while (something());", 14604 SpaceControlStatements); 14605 verifyFormat("switch (x) {\n" 14606 "default:\n" 14607 " break;\n" 14608 "}", 14609 SpaceControlStatements); 14610 14611 FormatStyle SpaceFuncDecl = getLLVMStyle(); 14612 SpaceFuncDecl.SpaceBeforeParens = FormatStyle::SBPO_Custom; 14613 SpaceFuncDecl.SpaceBeforeParensOptions.AfterFunctionDeclarationName = true; 14614 14615 verifyFormat("int f ();", SpaceFuncDecl); 14616 verifyFormat("void f(int a, T b) {}", SpaceFuncDecl); 14617 verifyFormat("A::A() : a(1) {}", SpaceFuncDecl); 14618 verifyFormat("void f () __attribute__((asdf));", SpaceFuncDecl); 14619 verifyFormat("#define A(x) x", SpaceFuncDecl); 14620 verifyFormat("#define A (x) x", SpaceFuncDecl); 14621 verifyFormat("#if defined(x)\n" 14622 "#endif", 14623 SpaceFuncDecl); 14624 verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDecl); 14625 verifyFormat("size_t x = sizeof(x);", SpaceFuncDecl); 14626 verifyFormat("auto f (int x) -> decltype(x);", SpaceFuncDecl); 14627 verifyFormat("auto f (int x) -> typeof(x);", SpaceFuncDecl); 14628 verifyFormat("auto f (int x) -> _Atomic(x);", SpaceFuncDecl); 14629 verifyFormat("auto f (int x) -> __underlying_type(x);", SpaceFuncDecl); 14630 verifyFormat("int f (T x) noexcept(x.create());", SpaceFuncDecl); 14631 verifyFormat("alignas(128) char a[128];", SpaceFuncDecl); 14632 verifyFormat("size_t x = alignof(MyType);", SpaceFuncDecl); 14633 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", 14634 SpaceFuncDecl); 14635 verifyFormat("int f () throw(Deprecated);", SpaceFuncDecl); 14636 verifyFormat("typedef void (*cb)(int);", SpaceFuncDecl); 14637 // FIXME these tests regressed behaviour. 14638 // verifyFormat("T A::operator() ();", SpaceFuncDecl); 14639 // verifyFormat("X A::operator++ (T);", SpaceFuncDecl); 14640 verifyFormat("T A::operator()() {}", SpaceFuncDecl); 14641 verifyFormat("auto lambda = []() { return 0; };", SpaceFuncDecl); 14642 verifyFormat("int x = int(y);", SpaceFuncDecl); 14643 verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}", 14644 SpaceFuncDecl); 14645 14646 FormatStyle SpaceFuncDef = getLLVMStyle(); 14647 SpaceFuncDef.SpaceBeforeParens = FormatStyle::SBPO_Custom; 14648 SpaceFuncDef.SpaceBeforeParensOptions.AfterFunctionDefinitionName = true; 14649 14650 verifyFormat("int f();", SpaceFuncDef); 14651 verifyFormat("void f (int a, T b) {}", SpaceFuncDef); 14652 verifyFormat("A::A() : a(1) {}", SpaceFuncDef); 14653 verifyFormat("void f() __attribute__((asdf));", SpaceFuncDef); 14654 verifyFormat("#define A(x) x", SpaceFuncDef); 14655 verifyFormat("#define A (x) x", SpaceFuncDef); 14656 verifyFormat("#if defined(x)\n" 14657 "#endif", 14658 SpaceFuncDef); 14659 verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDef); 14660 verifyFormat("size_t x = sizeof(x);", SpaceFuncDef); 14661 verifyFormat("auto f(int x) -> decltype(x);", SpaceFuncDef); 14662 verifyFormat("auto f(int x) -> typeof(x);", SpaceFuncDef); 14663 verifyFormat("auto f(int x) -> _Atomic(x);", SpaceFuncDef); 14664 verifyFormat("auto f(int x) -> __underlying_type(x);", SpaceFuncDef); 14665 verifyFormat("int f(T x) noexcept(x.create());", SpaceFuncDef); 14666 verifyFormat("alignas(128) char a[128];", SpaceFuncDef); 14667 verifyFormat("size_t x = alignof(MyType);", SpaceFuncDef); 14668 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", 14669 SpaceFuncDef); 14670 verifyFormat("int f() throw(Deprecated);", SpaceFuncDef); 14671 verifyFormat("typedef void (*cb)(int);", SpaceFuncDef); 14672 verifyFormat("T A::operator()();", SpaceFuncDef); 14673 verifyFormat("X A::operator++(T);", SpaceFuncDef); 14674 // verifyFormat("T A::operator() () {}", SpaceFuncDef); 14675 verifyFormat("auto lambda = [] () { return 0; };", SpaceFuncDef); 14676 verifyFormat("int x = int(y);", SpaceFuncDef); 14677 verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}", 14678 SpaceFuncDef); 14679 14680 FormatStyle SpaceIfMacros = getLLVMStyle(); 14681 SpaceIfMacros.IfMacros.clear(); 14682 SpaceIfMacros.IfMacros.push_back("MYIF"); 14683 SpaceIfMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom; 14684 SpaceIfMacros.SpaceBeforeParensOptions.AfterIfMacros = true; 14685 verifyFormat("MYIF (a)\n return;", SpaceIfMacros); 14686 verifyFormat("MYIF (a)\n return;\nelse MYIF (b)\n return;", SpaceIfMacros); 14687 verifyFormat("MYIF (a)\n return;\nelse\n return;", SpaceIfMacros); 14688 14689 FormatStyle SpaceForeachMacros = getLLVMStyle(); 14690 EXPECT_EQ(SpaceForeachMacros.AllowShortBlocksOnASingleLine, 14691 FormatStyle::SBS_Never); 14692 EXPECT_EQ(SpaceForeachMacros.AllowShortLoopsOnASingleLine, false); 14693 SpaceForeachMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom; 14694 SpaceForeachMacros.SpaceBeforeParensOptions.AfterForeachMacros = true; 14695 verifyFormat("for (;;) {\n" 14696 "}", 14697 SpaceForeachMacros); 14698 verifyFormat("foreach (Item *item, itemlist) {\n" 14699 "}", 14700 SpaceForeachMacros); 14701 verifyFormat("Q_FOREACH (Item *item, itemlist) {\n" 14702 "}", 14703 SpaceForeachMacros); 14704 verifyFormat("BOOST_FOREACH (Item *item, itemlist) {\n" 14705 "}", 14706 SpaceForeachMacros); 14707 verifyFormat("UNKNOWN_FOREACH(Item *item, itemlist) {}", SpaceForeachMacros); 14708 14709 FormatStyle SomeSpace2 = getLLVMStyle(); 14710 SomeSpace2.SpaceBeforeParens = FormatStyle::SBPO_Custom; 14711 SomeSpace2.SpaceBeforeParensOptions.BeforeNonEmptyParentheses = true; 14712 verifyFormat("[]() -> float {}", SomeSpace2); 14713 verifyFormat("[] (auto foo) {}", SomeSpace2); 14714 verifyFormat("[foo]() -> int {}", SomeSpace2); 14715 verifyFormat("int f();", SomeSpace2); 14716 verifyFormat("void f (int a, T b) {\n" 14717 " while (true)\n" 14718 " continue;\n" 14719 "}", 14720 SomeSpace2); 14721 verifyFormat("if (true)\n" 14722 " f();\n" 14723 "else if (true)\n" 14724 " f();", 14725 SomeSpace2); 14726 verifyFormat("do {\n" 14727 " do_something();\n" 14728 "} while (something());", 14729 SomeSpace2); 14730 verifyFormat("switch (x) {\n" 14731 "default:\n" 14732 " break;\n" 14733 "}", 14734 SomeSpace2); 14735 verifyFormat("A::A() : a (1) {}", SomeSpace2); 14736 verifyFormat("void f() __attribute__ ((asdf));", SomeSpace2); 14737 verifyFormat("*(&a + 1);\n" 14738 "&((&a)[1]);\n" 14739 "a[(b + c) * d];\n" 14740 "(((a + 1) * 2) + 3) * 4;", 14741 SomeSpace2); 14742 verifyFormat("#define A(x) x", SomeSpace2); 14743 verifyFormat("#define A (x) x", SomeSpace2); 14744 verifyFormat("#if defined(x)\n" 14745 "#endif", 14746 SomeSpace2); 14747 verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace2); 14748 verifyFormat("size_t x = sizeof (x);", SomeSpace2); 14749 verifyFormat("auto f (int x) -> decltype (x);", SomeSpace2); 14750 verifyFormat("auto f (int x) -> typeof (x);", SomeSpace2); 14751 verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace2); 14752 verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace2); 14753 verifyFormat("int f (T x) noexcept (x.create());", SomeSpace2); 14754 verifyFormat("alignas (128) char a[128];", SomeSpace2); 14755 verifyFormat("size_t x = alignof (MyType);", SomeSpace2); 14756 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", 14757 SomeSpace2); 14758 verifyFormat("int f() throw (Deprecated);", SomeSpace2); 14759 verifyFormat("typedef void (*cb) (int);", SomeSpace2); 14760 verifyFormat("T A::operator()();", SomeSpace2); 14761 // verifyFormat("X A::operator++ (T);", SomeSpace2); 14762 verifyFormat("int x = int (y);", SomeSpace2); 14763 verifyFormat("auto lambda = []() { return 0; };", SomeSpace2); 14764 14765 FormatStyle SpaceAfterOverloadedOperator = getLLVMStyle(); 14766 SpaceAfterOverloadedOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom; 14767 SpaceAfterOverloadedOperator.SpaceBeforeParensOptions 14768 .AfterOverloadedOperator = true; 14769 14770 verifyFormat("auto operator++ () -> int;", SpaceAfterOverloadedOperator); 14771 verifyFormat("X A::operator++ ();", SpaceAfterOverloadedOperator); 14772 verifyFormat("some_object.operator++ ();", SpaceAfterOverloadedOperator); 14773 verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator); 14774 14775 SpaceAfterOverloadedOperator.SpaceBeforeParensOptions 14776 .AfterOverloadedOperator = false; 14777 14778 verifyFormat("auto operator++() -> int;", SpaceAfterOverloadedOperator); 14779 verifyFormat("X A::operator++();", SpaceAfterOverloadedOperator); 14780 verifyFormat("some_object.operator++();", SpaceAfterOverloadedOperator); 14781 verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator); 14782 } 14783 14784 TEST_F(FormatTest, SpaceAfterLogicalNot) { 14785 FormatStyle Spaces = getLLVMStyle(); 14786 Spaces.SpaceAfterLogicalNot = true; 14787 14788 verifyFormat("bool x = ! y", Spaces); 14789 verifyFormat("if (! isFailure())", Spaces); 14790 verifyFormat("if (! (a && b))", Spaces); 14791 verifyFormat("\"Error!\"", Spaces); 14792 verifyFormat("! ! x", Spaces); 14793 } 14794 14795 TEST_F(FormatTest, ConfigurableSpacesInParentheses) { 14796 FormatStyle Spaces = getLLVMStyle(); 14797 14798 Spaces.SpacesInParentheses = true; 14799 verifyFormat("do_something( ::globalVar );", Spaces); 14800 verifyFormat("call( x, y, z );", Spaces); 14801 verifyFormat("call();", Spaces); 14802 verifyFormat("std::function<void( int, int )> callback;", Spaces); 14803 verifyFormat("void inFunction() { std::function<void( int, int )> fct; }", 14804 Spaces); 14805 verifyFormat("while ( (bool)1 )\n" 14806 " continue;", 14807 Spaces); 14808 verifyFormat("for ( ;; )\n" 14809 " continue;", 14810 Spaces); 14811 verifyFormat("if ( true )\n" 14812 " f();\n" 14813 "else if ( true )\n" 14814 " f();", 14815 Spaces); 14816 verifyFormat("do {\n" 14817 " do_something( (int)i );\n" 14818 "} while ( something() );", 14819 Spaces); 14820 verifyFormat("switch ( x ) {\n" 14821 "default:\n" 14822 " break;\n" 14823 "}", 14824 Spaces); 14825 14826 Spaces.SpacesInParentheses = false; 14827 Spaces.SpacesInCStyleCastParentheses = true; 14828 verifyFormat("Type *A = ( Type * )P;", Spaces); 14829 verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces); 14830 verifyFormat("x = ( int32 )y;", Spaces); 14831 verifyFormat("int a = ( int )(2.0f);", Spaces); 14832 verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces); 14833 verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces); 14834 verifyFormat("#define x (( int )-1)", Spaces); 14835 14836 // Run the first set of tests again with: 14837 Spaces.SpacesInParentheses = false; 14838 Spaces.SpaceInEmptyParentheses = true; 14839 Spaces.SpacesInCStyleCastParentheses = true; 14840 verifyFormat("call(x, y, z);", Spaces); 14841 verifyFormat("call( );", Spaces); 14842 verifyFormat("std::function<void(int, int)> callback;", Spaces); 14843 verifyFormat("while (( bool )1)\n" 14844 " continue;", 14845 Spaces); 14846 verifyFormat("for (;;)\n" 14847 " continue;", 14848 Spaces); 14849 verifyFormat("if (true)\n" 14850 " f( );\n" 14851 "else if (true)\n" 14852 " f( );", 14853 Spaces); 14854 verifyFormat("do {\n" 14855 " do_something(( int )i);\n" 14856 "} while (something( ));", 14857 Spaces); 14858 verifyFormat("switch (x) {\n" 14859 "default:\n" 14860 " break;\n" 14861 "}", 14862 Spaces); 14863 14864 // Run the first set of tests again with: 14865 Spaces.SpaceAfterCStyleCast = true; 14866 verifyFormat("call(x, y, z);", Spaces); 14867 verifyFormat("call( );", Spaces); 14868 verifyFormat("std::function<void(int, int)> callback;", Spaces); 14869 verifyFormat("while (( bool ) 1)\n" 14870 " continue;", 14871 Spaces); 14872 verifyFormat("for (;;)\n" 14873 " continue;", 14874 Spaces); 14875 verifyFormat("if (true)\n" 14876 " f( );\n" 14877 "else if (true)\n" 14878 " f( );", 14879 Spaces); 14880 verifyFormat("do {\n" 14881 " do_something(( int ) i);\n" 14882 "} while (something( ));", 14883 Spaces); 14884 verifyFormat("switch (x) {\n" 14885 "default:\n" 14886 " break;\n" 14887 "}", 14888 Spaces); 14889 verifyFormat("#define CONF_BOOL(x) ( bool * ) ( void * ) (x)", Spaces); 14890 verifyFormat("#define CONF_BOOL(x) ( bool * ) (x)", Spaces); 14891 verifyFormat("#define CONF_BOOL(x) ( bool ) (x)", Spaces); 14892 verifyFormat("bool *y = ( bool * ) ( void * ) (x);", Spaces); 14893 verifyFormat("bool *y = ( bool * ) (x);", Spaces); 14894 14895 // Run subset of tests again with: 14896 Spaces.SpacesInCStyleCastParentheses = false; 14897 Spaces.SpaceAfterCStyleCast = true; 14898 verifyFormat("while ((bool) 1)\n" 14899 " continue;", 14900 Spaces); 14901 verifyFormat("do {\n" 14902 " do_something((int) i);\n" 14903 "} while (something( ));", 14904 Spaces); 14905 14906 verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces); 14907 verifyFormat("size_t idx = (size_t) a;", Spaces); 14908 verifyFormat("size_t idx = (size_t) (a - 1);", Spaces); 14909 verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces); 14910 verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces); 14911 verifyFormat("size_t idx = (*foo)(a - 1);", Spaces); 14912 verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces); 14913 verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (x)", Spaces); 14914 verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (int) (x)", Spaces); 14915 verifyFormat("bool *y = (bool *) (void *) (x);", Spaces); 14916 verifyFormat("bool *y = (bool *) (void *) (int) (x);", Spaces); 14917 verifyFormat("bool *y = (bool *) (void *) (int) foo(x);", Spaces); 14918 Spaces.ColumnLimit = 80; 14919 Spaces.IndentWidth = 4; 14920 Spaces.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 14921 verifyFormat("void foo( ) {\n" 14922 " size_t foo = (*(function))(\n" 14923 " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, " 14924 "BarrrrrrrrrrrrLong,\n" 14925 " FoooooooooLooooong);\n" 14926 "}", 14927 Spaces); 14928 Spaces.SpaceAfterCStyleCast = false; 14929 verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces); 14930 verifyFormat("size_t idx = (size_t)a;", Spaces); 14931 verifyFormat("size_t idx = (size_t)(a - 1);", Spaces); 14932 verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces); 14933 verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces); 14934 verifyFormat("size_t idx = (*foo)(a - 1);", Spaces); 14935 verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces); 14936 14937 verifyFormat("void foo( ) {\n" 14938 " size_t foo = (*(function))(\n" 14939 " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, " 14940 "BarrrrrrrrrrrrLong,\n" 14941 " FoooooooooLooooong);\n" 14942 "}", 14943 Spaces); 14944 } 14945 14946 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) { 14947 verifyFormat("int a[5];"); 14948 verifyFormat("a[3] += 42;"); 14949 14950 FormatStyle Spaces = getLLVMStyle(); 14951 Spaces.SpacesInSquareBrackets = true; 14952 // Not lambdas. 14953 verifyFormat("int a[ 5 ];", Spaces); 14954 verifyFormat("a[ 3 ] += 42;", Spaces); 14955 verifyFormat("constexpr char hello[]{\"hello\"};", Spaces); 14956 verifyFormat("double &operator[](int i) { return 0; }\n" 14957 "int i;", 14958 Spaces); 14959 verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces); 14960 verifyFormat("int i = a[ a ][ a ]->f();", Spaces); 14961 verifyFormat("int i = (*b)[ a ]->f();", Spaces); 14962 // Lambdas. 14963 verifyFormat("int c = []() -> int { return 2; }();\n", Spaces); 14964 verifyFormat("return [ i, args... ] {};", Spaces); 14965 verifyFormat("int foo = [ &bar ]() {};", Spaces); 14966 verifyFormat("int foo = [ = ]() {};", Spaces); 14967 verifyFormat("int foo = [ & ]() {};", Spaces); 14968 verifyFormat("int foo = [ =, &bar ]() {};", Spaces); 14969 verifyFormat("int foo = [ &bar, = ]() {};", Spaces); 14970 } 14971 14972 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) { 14973 FormatStyle NoSpaceStyle = getLLVMStyle(); 14974 verifyFormat("int a[5];", NoSpaceStyle); 14975 verifyFormat("a[3] += 42;", NoSpaceStyle); 14976 14977 verifyFormat("int a[1];", NoSpaceStyle); 14978 verifyFormat("int 1 [a];", NoSpaceStyle); 14979 verifyFormat("int a[1][2];", NoSpaceStyle); 14980 verifyFormat("a[7] = 5;", NoSpaceStyle); 14981 verifyFormat("int a = (f())[23];", NoSpaceStyle); 14982 verifyFormat("f([] {})", NoSpaceStyle); 14983 14984 FormatStyle Space = getLLVMStyle(); 14985 Space.SpaceBeforeSquareBrackets = true; 14986 verifyFormat("int c = []() -> int { return 2; }();\n", Space); 14987 verifyFormat("return [i, args...] {};", Space); 14988 14989 verifyFormat("int a [5];", Space); 14990 verifyFormat("a [3] += 42;", Space); 14991 verifyFormat("constexpr char hello []{\"hello\"};", Space); 14992 verifyFormat("double &operator[](int i) { return 0; }\n" 14993 "int i;", 14994 Space); 14995 verifyFormat("std::unique_ptr<int []> foo() {}", Space); 14996 verifyFormat("int i = a [a][a]->f();", Space); 14997 verifyFormat("int i = (*b) [a]->f();", Space); 14998 14999 verifyFormat("int a [1];", Space); 15000 verifyFormat("int 1 [a];", Space); 15001 verifyFormat("int a [1][2];", Space); 15002 verifyFormat("a [7] = 5;", Space); 15003 verifyFormat("int a = (f()) [23];", Space); 15004 verifyFormat("f([] {})", Space); 15005 } 15006 15007 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) { 15008 verifyFormat("int a = 5;"); 15009 verifyFormat("a += 42;"); 15010 verifyFormat("a or_eq 8;"); 15011 15012 FormatStyle Spaces = getLLVMStyle(); 15013 Spaces.SpaceBeforeAssignmentOperators = false; 15014 verifyFormat("int a= 5;", Spaces); 15015 verifyFormat("a+= 42;", Spaces); 15016 verifyFormat("a or_eq 8;", Spaces); 15017 } 15018 15019 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) { 15020 verifyFormat("class Foo : public Bar {};"); 15021 verifyFormat("Foo::Foo() : foo(1) {}"); 15022 verifyFormat("for (auto a : b) {\n}"); 15023 verifyFormat("int x = a ? b : c;"); 15024 verifyFormat("{\n" 15025 "label0:\n" 15026 " int x = 0;\n" 15027 "}"); 15028 verifyFormat("switch (x) {\n" 15029 "case 1:\n" 15030 "default:\n" 15031 "}"); 15032 verifyFormat("switch (allBraces) {\n" 15033 "case 1: {\n" 15034 " break;\n" 15035 "}\n" 15036 "case 2: {\n" 15037 " [[fallthrough]];\n" 15038 "}\n" 15039 "default: {\n" 15040 " break;\n" 15041 "}\n" 15042 "}"); 15043 15044 FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30); 15045 CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false; 15046 verifyFormat("class Foo : public Bar {};", CtorInitializerStyle); 15047 verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle); 15048 verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle); 15049 verifyFormat("int x = a ? b : c;", CtorInitializerStyle); 15050 verifyFormat("{\n" 15051 "label1:\n" 15052 " int x = 0;\n" 15053 "}", 15054 CtorInitializerStyle); 15055 verifyFormat("switch (x) {\n" 15056 "case 1:\n" 15057 "default:\n" 15058 "}", 15059 CtorInitializerStyle); 15060 verifyFormat("switch (allBraces) {\n" 15061 "case 1: {\n" 15062 " break;\n" 15063 "}\n" 15064 "case 2: {\n" 15065 " [[fallthrough]];\n" 15066 "}\n" 15067 "default: {\n" 15068 " break;\n" 15069 "}\n" 15070 "}", 15071 CtorInitializerStyle); 15072 CtorInitializerStyle.BreakConstructorInitializers = 15073 FormatStyle::BCIS_AfterColon; 15074 verifyFormat("Fooooooooooo::Fooooooooooo():\n" 15075 " aaaaaaaaaaaaaaaa(1),\n" 15076 " bbbbbbbbbbbbbbbb(2) {}", 15077 CtorInitializerStyle); 15078 CtorInitializerStyle.BreakConstructorInitializers = 15079 FormatStyle::BCIS_BeforeComma; 15080 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15081 " : aaaaaaaaaaaaaaaa(1)\n" 15082 " , bbbbbbbbbbbbbbbb(2) {}", 15083 CtorInitializerStyle); 15084 CtorInitializerStyle.BreakConstructorInitializers = 15085 FormatStyle::BCIS_BeforeColon; 15086 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15087 " : aaaaaaaaaaaaaaaa(1),\n" 15088 " bbbbbbbbbbbbbbbb(2) {}", 15089 CtorInitializerStyle); 15090 CtorInitializerStyle.ConstructorInitializerIndentWidth = 0; 15091 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15092 ": aaaaaaaaaaaaaaaa(1),\n" 15093 " bbbbbbbbbbbbbbbb(2) {}", 15094 CtorInitializerStyle); 15095 15096 FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30); 15097 InheritanceStyle.SpaceBeforeInheritanceColon = false; 15098 verifyFormat("class Foo: public Bar {};", InheritanceStyle); 15099 verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle); 15100 verifyFormat("for (auto a : b) {\n}", InheritanceStyle); 15101 verifyFormat("int x = a ? b : c;", InheritanceStyle); 15102 verifyFormat("{\n" 15103 "label2:\n" 15104 " int x = 0;\n" 15105 "}", 15106 InheritanceStyle); 15107 verifyFormat("switch (x) {\n" 15108 "case 1:\n" 15109 "default:\n" 15110 "}", 15111 InheritanceStyle); 15112 verifyFormat("switch (allBraces) {\n" 15113 "case 1: {\n" 15114 " break;\n" 15115 "}\n" 15116 "case 2: {\n" 15117 " [[fallthrough]];\n" 15118 "}\n" 15119 "default: {\n" 15120 " break;\n" 15121 "}\n" 15122 "}", 15123 InheritanceStyle); 15124 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterComma; 15125 verifyFormat("class Foooooooooooooooooooooo\n" 15126 " : public aaaaaaaaaaaaaaaaaa,\n" 15127 " public bbbbbbbbbbbbbbbbbb {\n" 15128 "}", 15129 InheritanceStyle); 15130 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon; 15131 verifyFormat("class Foooooooooooooooooooooo:\n" 15132 " public aaaaaaaaaaaaaaaaaa,\n" 15133 " public bbbbbbbbbbbbbbbbbb {\n" 15134 "}", 15135 InheritanceStyle); 15136 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma; 15137 verifyFormat("class Foooooooooooooooooooooo\n" 15138 " : public aaaaaaaaaaaaaaaaaa\n" 15139 " , public bbbbbbbbbbbbbbbbbb {\n" 15140 "}", 15141 InheritanceStyle); 15142 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 15143 verifyFormat("class Foooooooooooooooooooooo\n" 15144 " : public aaaaaaaaaaaaaaaaaa,\n" 15145 " public bbbbbbbbbbbbbbbbbb {\n" 15146 "}", 15147 InheritanceStyle); 15148 InheritanceStyle.ConstructorInitializerIndentWidth = 0; 15149 verifyFormat("class Foooooooooooooooooooooo\n" 15150 ": public aaaaaaaaaaaaaaaaaa,\n" 15151 " public bbbbbbbbbbbbbbbbbb {}", 15152 InheritanceStyle); 15153 15154 FormatStyle ForLoopStyle = getLLVMStyle(); 15155 ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false; 15156 verifyFormat("class Foo : public Bar {};", ForLoopStyle); 15157 verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle); 15158 verifyFormat("for (auto a: b) {\n}", ForLoopStyle); 15159 verifyFormat("int x = a ? b : c;", ForLoopStyle); 15160 verifyFormat("{\n" 15161 "label2:\n" 15162 " int x = 0;\n" 15163 "}", 15164 ForLoopStyle); 15165 verifyFormat("switch (x) {\n" 15166 "case 1:\n" 15167 "default:\n" 15168 "}", 15169 ForLoopStyle); 15170 verifyFormat("switch (allBraces) {\n" 15171 "case 1: {\n" 15172 " break;\n" 15173 "}\n" 15174 "case 2: {\n" 15175 " [[fallthrough]];\n" 15176 "}\n" 15177 "default: {\n" 15178 " break;\n" 15179 "}\n" 15180 "}", 15181 ForLoopStyle); 15182 15183 FormatStyle CaseStyle = getLLVMStyle(); 15184 CaseStyle.SpaceBeforeCaseColon = true; 15185 verifyFormat("class Foo : public Bar {};", CaseStyle); 15186 verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle); 15187 verifyFormat("for (auto a : b) {\n}", CaseStyle); 15188 verifyFormat("int x = a ? b : c;", CaseStyle); 15189 verifyFormat("switch (x) {\n" 15190 "case 1 :\n" 15191 "default :\n" 15192 "}", 15193 CaseStyle); 15194 verifyFormat("switch (allBraces) {\n" 15195 "case 1 : {\n" 15196 " break;\n" 15197 "}\n" 15198 "case 2 : {\n" 15199 " [[fallthrough]];\n" 15200 "}\n" 15201 "default : {\n" 15202 " break;\n" 15203 "}\n" 15204 "}", 15205 CaseStyle); 15206 15207 FormatStyle NoSpaceStyle = getLLVMStyle(); 15208 EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false); 15209 NoSpaceStyle.SpaceBeforeCtorInitializerColon = false; 15210 NoSpaceStyle.SpaceBeforeInheritanceColon = false; 15211 NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false; 15212 verifyFormat("class Foo: public Bar {};", NoSpaceStyle); 15213 verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle); 15214 verifyFormat("for (auto a: b) {\n}", NoSpaceStyle); 15215 verifyFormat("int x = a ? b : c;", NoSpaceStyle); 15216 verifyFormat("{\n" 15217 "label3:\n" 15218 " int x = 0;\n" 15219 "}", 15220 NoSpaceStyle); 15221 verifyFormat("switch (x) {\n" 15222 "case 1:\n" 15223 "default:\n" 15224 "}", 15225 NoSpaceStyle); 15226 verifyFormat("switch (allBraces) {\n" 15227 "case 1: {\n" 15228 " break;\n" 15229 "}\n" 15230 "case 2: {\n" 15231 " [[fallthrough]];\n" 15232 "}\n" 15233 "default: {\n" 15234 " break;\n" 15235 "}\n" 15236 "}", 15237 NoSpaceStyle); 15238 15239 FormatStyle InvertedSpaceStyle = getLLVMStyle(); 15240 InvertedSpaceStyle.SpaceBeforeCaseColon = true; 15241 InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false; 15242 InvertedSpaceStyle.SpaceBeforeInheritanceColon = false; 15243 InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false; 15244 verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle); 15245 verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle); 15246 verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle); 15247 verifyFormat("int x = a ? b : c;", InvertedSpaceStyle); 15248 verifyFormat("{\n" 15249 "label3:\n" 15250 " int x = 0;\n" 15251 "}", 15252 InvertedSpaceStyle); 15253 verifyFormat("switch (x) {\n" 15254 "case 1 :\n" 15255 "case 2 : {\n" 15256 " break;\n" 15257 "}\n" 15258 "default :\n" 15259 " break;\n" 15260 "}", 15261 InvertedSpaceStyle); 15262 verifyFormat("switch (allBraces) {\n" 15263 "case 1 : {\n" 15264 " break;\n" 15265 "}\n" 15266 "case 2 : {\n" 15267 " [[fallthrough]];\n" 15268 "}\n" 15269 "default : {\n" 15270 " break;\n" 15271 "}\n" 15272 "}", 15273 InvertedSpaceStyle); 15274 } 15275 15276 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) { 15277 FormatStyle Style = getLLVMStyle(); 15278 15279 Style.PointerAlignment = FormatStyle::PAS_Left; 15280 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default; 15281 verifyFormat("void* const* x = NULL;", Style); 15282 15283 #define verifyQualifierSpaces(Code, Pointers, Qualifiers) \ 15284 do { \ 15285 Style.PointerAlignment = FormatStyle::Pointers; \ 15286 Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers; \ 15287 verifyFormat(Code, Style); \ 15288 } while (false) 15289 15290 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default); 15291 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default); 15292 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default); 15293 15294 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before); 15295 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before); 15296 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before); 15297 15298 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After); 15299 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After); 15300 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After); 15301 15302 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both); 15303 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both); 15304 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both); 15305 15306 verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default); 15307 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, 15308 SAPQ_Default); 15309 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15310 SAPQ_Default); 15311 15312 verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before); 15313 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, 15314 SAPQ_Before); 15315 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15316 SAPQ_Before); 15317 15318 verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After); 15319 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After); 15320 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15321 SAPQ_After); 15322 15323 verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both); 15324 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both); 15325 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both); 15326 15327 #undef verifyQualifierSpaces 15328 15329 FormatStyle Spaces = getLLVMStyle(); 15330 Spaces.AttributeMacros.push_back("qualified"); 15331 Spaces.PointerAlignment = FormatStyle::PAS_Right; 15332 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default; 15333 verifyFormat("SomeType *volatile *a = NULL;", Spaces); 15334 verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces); 15335 verifyFormat("std::vector<SomeType *const *> x;", Spaces); 15336 verifyFormat("std::vector<SomeType *qualified *> x;", Spaces); 15337 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15338 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before; 15339 verifyFormat("SomeType * volatile *a = NULL;", Spaces); 15340 verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces); 15341 verifyFormat("std::vector<SomeType * const *> x;", Spaces); 15342 verifyFormat("std::vector<SomeType * qualified *> x;", Spaces); 15343 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15344 15345 // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left. 15346 Spaces.PointerAlignment = FormatStyle::PAS_Left; 15347 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before; 15348 verifyFormat("SomeType* volatile* a = NULL;", Spaces); 15349 verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces); 15350 verifyFormat("std::vector<SomeType* const*> x;", Spaces); 15351 verifyFormat("std::vector<SomeType* qualified*> x;", Spaces); 15352 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15353 // However, setting it to SAPQ_After should add spaces after __attribute, etc. 15354 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After; 15355 verifyFormat("SomeType* volatile * a = NULL;", Spaces); 15356 verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces); 15357 verifyFormat("std::vector<SomeType* const *> x;", Spaces); 15358 verifyFormat("std::vector<SomeType* qualified *> x;", Spaces); 15359 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15360 15361 // PAS_Middle should not have any noticeable changes even for SAPQ_Both 15362 Spaces.PointerAlignment = FormatStyle::PAS_Middle; 15363 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After; 15364 verifyFormat("SomeType * volatile * a = NULL;", Spaces); 15365 verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces); 15366 verifyFormat("std::vector<SomeType * const *> x;", Spaces); 15367 verifyFormat("std::vector<SomeType * qualified *> x;", Spaces); 15368 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15369 } 15370 15371 TEST_F(FormatTest, AlignConsecutiveMacros) { 15372 FormatStyle Style = getLLVMStyle(); 15373 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 15374 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 15375 Style.AlignConsecutiveMacros = FormatStyle::ACS_None; 15376 15377 verifyFormat("#define a 3\n" 15378 "#define bbbb 4\n" 15379 "#define ccc (5)", 15380 Style); 15381 15382 verifyFormat("#define f(x) (x * x)\n" 15383 "#define fff(x, y, z) (x * y + z)\n" 15384 "#define ffff(x, y) (x - y)", 15385 Style); 15386 15387 verifyFormat("#define foo(x, y) (x + y)\n" 15388 "#define bar (5, 6)(2 + 2)", 15389 Style); 15390 15391 verifyFormat("#define a 3\n" 15392 "#define bbbb 4\n" 15393 "#define ccc (5)\n" 15394 "#define f(x) (x * x)\n" 15395 "#define fff(x, y, z) (x * y + z)\n" 15396 "#define ffff(x, y) (x - y)", 15397 Style); 15398 15399 Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 15400 verifyFormat("#define a 3\n" 15401 "#define bbbb 4\n" 15402 "#define ccc (5)", 15403 Style); 15404 15405 verifyFormat("#define f(x) (x * x)\n" 15406 "#define fff(x, y, z) (x * y + z)\n" 15407 "#define ffff(x, y) (x - y)", 15408 Style); 15409 15410 verifyFormat("#define foo(x, y) (x + y)\n" 15411 "#define bar (5, 6)(2 + 2)", 15412 Style); 15413 15414 verifyFormat("#define a 3\n" 15415 "#define bbbb 4\n" 15416 "#define ccc (5)\n" 15417 "#define f(x) (x * x)\n" 15418 "#define fff(x, y, z) (x * y + z)\n" 15419 "#define ffff(x, y) (x - y)", 15420 Style); 15421 15422 verifyFormat("#define a 5\n" 15423 "#define foo(x, y) (x + y)\n" 15424 "#define CCC (6)\n" 15425 "auto lambda = []() {\n" 15426 " auto ii = 0;\n" 15427 " float j = 0;\n" 15428 " return 0;\n" 15429 "};\n" 15430 "int i = 0;\n" 15431 "float i2 = 0;\n" 15432 "auto v = type{\n" 15433 " i = 1, //\n" 15434 " (i = 2), //\n" 15435 " i = 3 //\n" 15436 "};", 15437 Style); 15438 15439 Style.AlignConsecutiveMacros = FormatStyle::ACS_None; 15440 Style.ColumnLimit = 20; 15441 15442 verifyFormat("#define a \\\n" 15443 " \"aabbbbbbbbbbbb\"\n" 15444 "#define D \\\n" 15445 " \"aabbbbbbbbbbbb\" \\\n" 15446 " \"ccddeeeeeeeee\"\n" 15447 "#define B \\\n" 15448 " \"QQQQQQQQQQQQQ\" \\\n" 15449 " \"FFFFFFFFFFFFF\" \\\n" 15450 " \"LLLLLLLL\"\n", 15451 Style); 15452 15453 Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 15454 verifyFormat("#define a \\\n" 15455 " \"aabbbbbbbbbbbb\"\n" 15456 "#define D \\\n" 15457 " \"aabbbbbbbbbbbb\" \\\n" 15458 " \"ccddeeeeeeeee\"\n" 15459 "#define B \\\n" 15460 " \"QQQQQQQQQQQQQ\" \\\n" 15461 " \"FFFFFFFFFFFFF\" \\\n" 15462 " \"LLLLLLLL\"\n", 15463 Style); 15464 15465 // Test across comments 15466 Style.MaxEmptyLinesToKeep = 10; 15467 Style.ReflowComments = false; 15468 Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossComments; 15469 EXPECT_EQ("#define a 3\n" 15470 "// line comment\n" 15471 "#define bbbb 4\n" 15472 "#define ccc (5)", 15473 format("#define a 3\n" 15474 "// line comment\n" 15475 "#define bbbb 4\n" 15476 "#define ccc (5)", 15477 Style)); 15478 15479 EXPECT_EQ("#define a 3\n" 15480 "/* block comment */\n" 15481 "#define bbbb 4\n" 15482 "#define ccc (5)", 15483 format("#define a 3\n" 15484 "/* block comment */\n" 15485 "#define bbbb 4\n" 15486 "#define ccc (5)", 15487 Style)); 15488 15489 EXPECT_EQ("#define a 3\n" 15490 "/* multi-line *\n" 15491 " * block comment */\n" 15492 "#define bbbb 4\n" 15493 "#define ccc (5)", 15494 format("#define a 3\n" 15495 "/* multi-line *\n" 15496 " * block comment */\n" 15497 "#define bbbb 4\n" 15498 "#define ccc (5)", 15499 Style)); 15500 15501 EXPECT_EQ("#define a 3\n" 15502 "// multi-line line comment\n" 15503 "//\n" 15504 "#define bbbb 4\n" 15505 "#define ccc (5)", 15506 format("#define a 3\n" 15507 "// multi-line line comment\n" 15508 "//\n" 15509 "#define bbbb 4\n" 15510 "#define ccc (5)", 15511 Style)); 15512 15513 EXPECT_EQ("#define a 3\n" 15514 "// empty lines still break.\n" 15515 "\n" 15516 "#define bbbb 4\n" 15517 "#define ccc (5)", 15518 format("#define a 3\n" 15519 "// empty lines still break.\n" 15520 "\n" 15521 "#define bbbb 4\n" 15522 "#define ccc (5)", 15523 Style)); 15524 15525 // Test across empty lines 15526 Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLines; 15527 EXPECT_EQ("#define a 3\n" 15528 "\n" 15529 "#define bbbb 4\n" 15530 "#define ccc (5)", 15531 format("#define a 3\n" 15532 "\n" 15533 "#define bbbb 4\n" 15534 "#define ccc (5)", 15535 Style)); 15536 15537 EXPECT_EQ("#define a 3\n" 15538 "\n" 15539 "\n" 15540 "\n" 15541 "#define bbbb 4\n" 15542 "#define ccc (5)", 15543 format("#define a 3\n" 15544 "\n" 15545 "\n" 15546 "\n" 15547 "#define bbbb 4\n" 15548 "#define ccc (5)", 15549 Style)); 15550 15551 EXPECT_EQ("#define a 3\n" 15552 "// comments should break alignment\n" 15553 "//\n" 15554 "#define bbbb 4\n" 15555 "#define ccc (5)", 15556 format("#define a 3\n" 15557 "// comments should break alignment\n" 15558 "//\n" 15559 "#define bbbb 4\n" 15560 "#define ccc (5)", 15561 Style)); 15562 15563 // Test across empty lines and comments 15564 Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLinesAndComments; 15565 verifyFormat("#define a 3\n" 15566 "\n" 15567 "// line comment\n" 15568 "#define bbbb 4\n" 15569 "#define ccc (5)", 15570 Style); 15571 15572 EXPECT_EQ("#define a 3\n" 15573 "\n" 15574 "\n" 15575 "/* multi-line *\n" 15576 " * block comment */\n" 15577 "\n" 15578 "\n" 15579 "#define bbbb 4\n" 15580 "#define ccc (5)", 15581 format("#define a 3\n" 15582 "\n" 15583 "\n" 15584 "/* multi-line *\n" 15585 " * block comment */\n" 15586 "\n" 15587 "\n" 15588 "#define bbbb 4\n" 15589 "#define ccc (5)", 15590 Style)); 15591 15592 EXPECT_EQ("#define a 3\n" 15593 "\n" 15594 "\n" 15595 "/* multi-line *\n" 15596 " * block comment */\n" 15597 "\n" 15598 "\n" 15599 "#define bbbb 4\n" 15600 "#define ccc (5)", 15601 format("#define a 3\n" 15602 "\n" 15603 "\n" 15604 "/* multi-line *\n" 15605 " * block comment */\n" 15606 "\n" 15607 "\n" 15608 "#define bbbb 4\n" 15609 "#define ccc (5)", 15610 Style)); 15611 } 15612 15613 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) { 15614 FormatStyle Alignment = getLLVMStyle(); 15615 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 15616 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossEmptyLines; 15617 15618 Alignment.MaxEmptyLinesToKeep = 10; 15619 /* Test alignment across empty lines */ 15620 EXPECT_EQ("int a = 5;\n" 15621 "\n" 15622 "int oneTwoThree = 123;", 15623 format("int a = 5;\n" 15624 "\n" 15625 "int oneTwoThree= 123;", 15626 Alignment)); 15627 EXPECT_EQ("int a = 5;\n" 15628 "int one = 1;\n" 15629 "\n" 15630 "int oneTwoThree = 123;", 15631 format("int a = 5;\n" 15632 "int one = 1;\n" 15633 "\n" 15634 "int oneTwoThree = 123;", 15635 Alignment)); 15636 EXPECT_EQ("int a = 5;\n" 15637 "int one = 1;\n" 15638 "\n" 15639 "int oneTwoThree = 123;\n" 15640 "int oneTwo = 12;", 15641 format("int a = 5;\n" 15642 "int one = 1;\n" 15643 "\n" 15644 "int oneTwoThree = 123;\n" 15645 "int oneTwo = 12;", 15646 Alignment)); 15647 15648 /* Test across comments */ 15649 EXPECT_EQ("int a = 5;\n" 15650 "/* block comment */\n" 15651 "int oneTwoThree = 123;", 15652 format("int a = 5;\n" 15653 "/* block comment */\n" 15654 "int oneTwoThree=123;", 15655 Alignment)); 15656 15657 EXPECT_EQ("int a = 5;\n" 15658 "// line comment\n" 15659 "int oneTwoThree = 123;", 15660 format("int a = 5;\n" 15661 "// line comment\n" 15662 "int oneTwoThree=123;", 15663 Alignment)); 15664 15665 /* Test across comments and newlines */ 15666 EXPECT_EQ("int a = 5;\n" 15667 "\n" 15668 "/* block comment */\n" 15669 "int oneTwoThree = 123;", 15670 format("int a = 5;\n" 15671 "\n" 15672 "/* block comment */\n" 15673 "int oneTwoThree=123;", 15674 Alignment)); 15675 15676 EXPECT_EQ("int a = 5;\n" 15677 "\n" 15678 "// line comment\n" 15679 "int oneTwoThree = 123;", 15680 format("int a = 5;\n" 15681 "\n" 15682 "// line comment\n" 15683 "int oneTwoThree=123;", 15684 Alignment)); 15685 } 15686 15687 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) { 15688 FormatStyle Alignment = getLLVMStyle(); 15689 Alignment.AlignConsecutiveDeclarations = 15690 FormatStyle::ACS_AcrossEmptyLinesAndComments; 15691 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 15692 15693 Alignment.MaxEmptyLinesToKeep = 10; 15694 /* Test alignment across empty lines */ 15695 EXPECT_EQ("int a = 5;\n" 15696 "\n" 15697 "float const oneTwoThree = 123;", 15698 format("int a = 5;\n" 15699 "\n" 15700 "float const oneTwoThree = 123;", 15701 Alignment)); 15702 EXPECT_EQ("int a = 5;\n" 15703 "float const one = 1;\n" 15704 "\n" 15705 "int oneTwoThree = 123;", 15706 format("int a = 5;\n" 15707 "float const one = 1;\n" 15708 "\n" 15709 "int oneTwoThree = 123;", 15710 Alignment)); 15711 15712 /* Test across comments */ 15713 EXPECT_EQ("float const a = 5;\n" 15714 "/* block comment */\n" 15715 "int oneTwoThree = 123;", 15716 format("float const a = 5;\n" 15717 "/* block comment */\n" 15718 "int oneTwoThree=123;", 15719 Alignment)); 15720 15721 EXPECT_EQ("float const a = 5;\n" 15722 "// line comment\n" 15723 "int oneTwoThree = 123;", 15724 format("float const a = 5;\n" 15725 "// line comment\n" 15726 "int oneTwoThree=123;", 15727 Alignment)); 15728 15729 /* Test across comments and newlines */ 15730 EXPECT_EQ("float const a = 5;\n" 15731 "\n" 15732 "/* block comment */\n" 15733 "int oneTwoThree = 123;", 15734 format("float const a = 5;\n" 15735 "\n" 15736 "/* block comment */\n" 15737 "int oneTwoThree=123;", 15738 Alignment)); 15739 15740 EXPECT_EQ("float const a = 5;\n" 15741 "\n" 15742 "// line comment\n" 15743 "int oneTwoThree = 123;", 15744 format("float const a = 5;\n" 15745 "\n" 15746 "// line comment\n" 15747 "int oneTwoThree=123;", 15748 Alignment)); 15749 } 15750 15751 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) { 15752 FormatStyle Alignment = getLLVMStyle(); 15753 Alignment.AlignConsecutiveBitFields = 15754 FormatStyle::ACS_AcrossEmptyLinesAndComments; 15755 15756 Alignment.MaxEmptyLinesToKeep = 10; 15757 /* Test alignment across empty lines */ 15758 EXPECT_EQ("int a : 5;\n" 15759 "\n" 15760 "int longbitfield : 6;", 15761 format("int a : 5;\n" 15762 "\n" 15763 "int longbitfield : 6;", 15764 Alignment)); 15765 EXPECT_EQ("int a : 5;\n" 15766 "int one : 1;\n" 15767 "\n" 15768 "int longbitfield : 6;", 15769 format("int a : 5;\n" 15770 "int one : 1;\n" 15771 "\n" 15772 "int longbitfield : 6;", 15773 Alignment)); 15774 15775 /* Test across comments */ 15776 EXPECT_EQ("int a : 5;\n" 15777 "/* block comment */\n" 15778 "int longbitfield : 6;", 15779 format("int a : 5;\n" 15780 "/* block comment */\n" 15781 "int longbitfield : 6;", 15782 Alignment)); 15783 EXPECT_EQ("int a : 5;\n" 15784 "int one : 1;\n" 15785 "// line comment\n" 15786 "int longbitfield : 6;", 15787 format("int a : 5;\n" 15788 "int one : 1;\n" 15789 "// line comment\n" 15790 "int longbitfield : 6;", 15791 Alignment)); 15792 15793 /* Test across comments and newlines */ 15794 EXPECT_EQ("int a : 5;\n" 15795 "/* block comment */\n" 15796 "\n" 15797 "int longbitfield : 6;", 15798 format("int a : 5;\n" 15799 "/* block comment */\n" 15800 "\n" 15801 "int longbitfield : 6;", 15802 Alignment)); 15803 EXPECT_EQ("int a : 5;\n" 15804 "int one : 1;\n" 15805 "\n" 15806 "// line comment\n" 15807 "\n" 15808 "int longbitfield : 6;", 15809 format("int a : 5;\n" 15810 "int one : 1;\n" 15811 "\n" 15812 "// line comment \n" 15813 "\n" 15814 "int longbitfield : 6;", 15815 Alignment)); 15816 } 15817 15818 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) { 15819 FormatStyle Alignment = getLLVMStyle(); 15820 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 15821 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossComments; 15822 15823 Alignment.MaxEmptyLinesToKeep = 10; 15824 /* Test alignment across empty lines */ 15825 EXPECT_EQ("int a = 5;\n" 15826 "\n" 15827 "int oneTwoThree = 123;", 15828 format("int a = 5;\n" 15829 "\n" 15830 "int oneTwoThree= 123;", 15831 Alignment)); 15832 EXPECT_EQ("int a = 5;\n" 15833 "int one = 1;\n" 15834 "\n" 15835 "int oneTwoThree = 123;", 15836 format("int a = 5;\n" 15837 "int one = 1;\n" 15838 "\n" 15839 "int oneTwoThree = 123;", 15840 Alignment)); 15841 15842 /* Test across comments */ 15843 EXPECT_EQ("int a = 5;\n" 15844 "/* block comment */\n" 15845 "int oneTwoThree = 123;", 15846 format("int a = 5;\n" 15847 "/* block comment */\n" 15848 "int oneTwoThree=123;", 15849 Alignment)); 15850 15851 EXPECT_EQ("int a = 5;\n" 15852 "// line comment\n" 15853 "int oneTwoThree = 123;", 15854 format("int a = 5;\n" 15855 "// line comment\n" 15856 "int oneTwoThree=123;", 15857 Alignment)); 15858 15859 EXPECT_EQ("int a = 5;\n" 15860 "/*\n" 15861 " * multi-line block comment\n" 15862 " */\n" 15863 "int oneTwoThree = 123;", 15864 format("int a = 5;\n" 15865 "/*\n" 15866 " * multi-line block comment\n" 15867 " */\n" 15868 "int oneTwoThree=123;", 15869 Alignment)); 15870 15871 EXPECT_EQ("int a = 5;\n" 15872 "//\n" 15873 "// multi-line line comment\n" 15874 "//\n" 15875 "int oneTwoThree = 123;", 15876 format("int a = 5;\n" 15877 "//\n" 15878 "// multi-line line comment\n" 15879 "//\n" 15880 "int oneTwoThree=123;", 15881 Alignment)); 15882 15883 /* Test across comments and newlines */ 15884 EXPECT_EQ("int a = 5;\n" 15885 "\n" 15886 "/* block comment */\n" 15887 "int oneTwoThree = 123;", 15888 format("int a = 5;\n" 15889 "\n" 15890 "/* block comment */\n" 15891 "int oneTwoThree=123;", 15892 Alignment)); 15893 15894 EXPECT_EQ("int a = 5;\n" 15895 "\n" 15896 "// line comment\n" 15897 "int oneTwoThree = 123;", 15898 format("int a = 5;\n" 15899 "\n" 15900 "// line comment\n" 15901 "int oneTwoThree=123;", 15902 Alignment)); 15903 } 15904 15905 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) { 15906 FormatStyle Alignment = getLLVMStyle(); 15907 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 15908 Alignment.AlignConsecutiveAssignments = 15909 FormatStyle::ACS_AcrossEmptyLinesAndComments; 15910 verifyFormat("int a = 5;\n" 15911 "int oneTwoThree = 123;", 15912 Alignment); 15913 verifyFormat("int a = method();\n" 15914 "int oneTwoThree = 133;", 15915 Alignment); 15916 verifyFormat("a &= 5;\n" 15917 "bcd *= 5;\n" 15918 "ghtyf += 5;\n" 15919 "dvfvdb -= 5;\n" 15920 "a /= 5;\n" 15921 "vdsvsv %= 5;\n" 15922 "sfdbddfbdfbb ^= 5;\n" 15923 "dvsdsv |= 5;\n" 15924 "int dsvvdvsdvvv = 123;", 15925 Alignment); 15926 verifyFormat("int i = 1, j = 10;\n" 15927 "something = 2000;", 15928 Alignment); 15929 verifyFormat("something = 2000;\n" 15930 "int i = 1, j = 10;\n", 15931 Alignment); 15932 verifyFormat("something = 2000;\n" 15933 "another = 911;\n" 15934 "int i = 1, j = 10;\n" 15935 "oneMore = 1;\n" 15936 "i = 2;", 15937 Alignment); 15938 verifyFormat("int a = 5;\n" 15939 "int one = 1;\n" 15940 "method();\n" 15941 "int oneTwoThree = 123;\n" 15942 "int oneTwo = 12;", 15943 Alignment); 15944 verifyFormat("int oneTwoThree = 123;\n" 15945 "int oneTwo = 12;\n" 15946 "method();\n", 15947 Alignment); 15948 verifyFormat("int oneTwoThree = 123; // comment\n" 15949 "int oneTwo = 12; // comment", 15950 Alignment); 15951 15952 // Bug 25167 15953 /* Uncomment when fixed 15954 verifyFormat("#if A\n" 15955 "#else\n" 15956 "int aaaaaaaa = 12;\n" 15957 "#endif\n" 15958 "#if B\n" 15959 "#else\n" 15960 "int a = 12;\n" 15961 "#endif\n", 15962 Alignment); 15963 verifyFormat("enum foo {\n" 15964 "#if A\n" 15965 "#else\n" 15966 " aaaaaaaa = 12;\n" 15967 "#endif\n" 15968 "#if B\n" 15969 "#else\n" 15970 " a = 12;\n" 15971 "#endif\n" 15972 "};\n", 15973 Alignment); 15974 */ 15975 15976 Alignment.MaxEmptyLinesToKeep = 10; 15977 /* Test alignment across empty lines */ 15978 EXPECT_EQ("int a = 5;\n" 15979 "\n" 15980 "int oneTwoThree = 123;", 15981 format("int a = 5;\n" 15982 "\n" 15983 "int oneTwoThree= 123;", 15984 Alignment)); 15985 EXPECT_EQ("int a = 5;\n" 15986 "int one = 1;\n" 15987 "\n" 15988 "int oneTwoThree = 123;", 15989 format("int a = 5;\n" 15990 "int one = 1;\n" 15991 "\n" 15992 "int oneTwoThree = 123;", 15993 Alignment)); 15994 EXPECT_EQ("int a = 5;\n" 15995 "int one = 1;\n" 15996 "\n" 15997 "int oneTwoThree = 123;\n" 15998 "int oneTwo = 12;", 15999 format("int a = 5;\n" 16000 "int one = 1;\n" 16001 "\n" 16002 "int oneTwoThree = 123;\n" 16003 "int oneTwo = 12;", 16004 Alignment)); 16005 16006 /* Test across comments */ 16007 EXPECT_EQ("int a = 5;\n" 16008 "/* block comment */\n" 16009 "int oneTwoThree = 123;", 16010 format("int a = 5;\n" 16011 "/* block comment */\n" 16012 "int oneTwoThree=123;", 16013 Alignment)); 16014 16015 EXPECT_EQ("int a = 5;\n" 16016 "// line comment\n" 16017 "int oneTwoThree = 123;", 16018 format("int a = 5;\n" 16019 "// line comment\n" 16020 "int oneTwoThree=123;", 16021 Alignment)); 16022 16023 /* Test across comments and newlines */ 16024 EXPECT_EQ("int a = 5;\n" 16025 "\n" 16026 "/* block comment */\n" 16027 "int oneTwoThree = 123;", 16028 format("int a = 5;\n" 16029 "\n" 16030 "/* block comment */\n" 16031 "int oneTwoThree=123;", 16032 Alignment)); 16033 16034 EXPECT_EQ("int a = 5;\n" 16035 "\n" 16036 "// line comment\n" 16037 "int oneTwoThree = 123;", 16038 format("int a = 5;\n" 16039 "\n" 16040 "// line comment\n" 16041 "int oneTwoThree=123;", 16042 Alignment)); 16043 16044 EXPECT_EQ("int a = 5;\n" 16045 "//\n" 16046 "// multi-line line comment\n" 16047 "//\n" 16048 "int oneTwoThree = 123;", 16049 format("int a = 5;\n" 16050 "//\n" 16051 "// multi-line line comment\n" 16052 "//\n" 16053 "int oneTwoThree=123;", 16054 Alignment)); 16055 16056 EXPECT_EQ("int a = 5;\n" 16057 "/*\n" 16058 " * multi-line block comment\n" 16059 " */\n" 16060 "int oneTwoThree = 123;", 16061 format("int a = 5;\n" 16062 "/*\n" 16063 " * multi-line block comment\n" 16064 " */\n" 16065 "int oneTwoThree=123;", 16066 Alignment)); 16067 16068 EXPECT_EQ("int a = 5;\n" 16069 "\n" 16070 "/* block comment */\n" 16071 "\n" 16072 "\n" 16073 "\n" 16074 "int oneTwoThree = 123;", 16075 format("int a = 5;\n" 16076 "\n" 16077 "/* block comment */\n" 16078 "\n" 16079 "\n" 16080 "\n" 16081 "int oneTwoThree=123;", 16082 Alignment)); 16083 16084 EXPECT_EQ("int a = 5;\n" 16085 "\n" 16086 "// line comment\n" 16087 "\n" 16088 "\n" 16089 "\n" 16090 "int oneTwoThree = 123;", 16091 format("int a = 5;\n" 16092 "\n" 16093 "// line comment\n" 16094 "\n" 16095 "\n" 16096 "\n" 16097 "int oneTwoThree=123;", 16098 Alignment)); 16099 16100 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 16101 verifyFormat("#define A \\\n" 16102 " int aaaa = 12; \\\n" 16103 " int b = 23; \\\n" 16104 " int ccc = 234; \\\n" 16105 " int dddddddddd = 2345;", 16106 Alignment); 16107 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 16108 verifyFormat("#define A \\\n" 16109 " int aaaa = 12; \\\n" 16110 " int b = 23; \\\n" 16111 " int ccc = 234; \\\n" 16112 " int dddddddddd = 2345;", 16113 Alignment); 16114 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 16115 verifyFormat("#define A " 16116 " \\\n" 16117 " int aaaa = 12; " 16118 " \\\n" 16119 " int b = 23; " 16120 " \\\n" 16121 " int ccc = 234; " 16122 " \\\n" 16123 " int dddddddddd = 2345;", 16124 Alignment); 16125 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 16126 "k = 4, int l = 5,\n" 16127 " int m = 6) {\n" 16128 " int j = 10;\n" 16129 " otherThing = 1;\n" 16130 "}", 16131 Alignment); 16132 verifyFormat("void SomeFunction(int parameter = 0) {\n" 16133 " int i = 1;\n" 16134 " int j = 2;\n" 16135 " int big = 10000;\n" 16136 "}", 16137 Alignment); 16138 verifyFormat("class C {\n" 16139 "public:\n" 16140 " int i = 1;\n" 16141 " virtual void f() = 0;\n" 16142 "};", 16143 Alignment); 16144 verifyFormat("int i = 1;\n" 16145 "if (SomeType t = getSomething()) {\n" 16146 "}\n" 16147 "int j = 2;\n" 16148 "int big = 10000;", 16149 Alignment); 16150 verifyFormat("int j = 7;\n" 16151 "for (int k = 0; k < N; ++k) {\n" 16152 "}\n" 16153 "int j = 2;\n" 16154 "int big = 10000;\n" 16155 "}", 16156 Alignment); 16157 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 16158 verifyFormat("int i = 1;\n" 16159 "LooooooooooongType loooooooooooooooooooooongVariable\n" 16160 " = someLooooooooooooooooongFunction();\n" 16161 "int j = 2;", 16162 Alignment); 16163 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 16164 verifyFormat("int i = 1;\n" 16165 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 16166 " someLooooooooooooooooongFunction();\n" 16167 "int j = 2;", 16168 Alignment); 16169 16170 verifyFormat("auto lambda = []() {\n" 16171 " auto i = 0;\n" 16172 " return 0;\n" 16173 "};\n" 16174 "int i = 0;\n" 16175 "auto v = type{\n" 16176 " i = 1, //\n" 16177 " (i = 2), //\n" 16178 " i = 3 //\n" 16179 "};", 16180 Alignment); 16181 16182 verifyFormat( 16183 "int i = 1;\n" 16184 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 16185 " loooooooooooooooooooooongParameterB);\n" 16186 "int j = 2;", 16187 Alignment); 16188 16189 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n" 16190 " typename B = very_long_type_name_1,\n" 16191 " typename T_2 = very_long_type_name_2>\n" 16192 "auto foo() {}\n", 16193 Alignment); 16194 verifyFormat("int a, b = 1;\n" 16195 "int c = 2;\n" 16196 "int dd = 3;\n", 16197 Alignment); 16198 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 16199 "float b[1][] = {{3.f}};\n", 16200 Alignment); 16201 verifyFormat("for (int i = 0; i < 1; i++)\n" 16202 " int x = 1;\n", 16203 Alignment); 16204 verifyFormat("for (i = 0; i < 1; i++)\n" 16205 " x = 1;\n" 16206 "y = 1;\n", 16207 Alignment); 16208 16209 Alignment.ReflowComments = true; 16210 Alignment.ColumnLimit = 50; 16211 EXPECT_EQ("int x = 0;\n" 16212 "int yy = 1; /// specificlennospace\n" 16213 "int zzz = 2;\n", 16214 format("int x = 0;\n" 16215 "int yy = 1; ///specificlennospace\n" 16216 "int zzz = 2;\n", 16217 Alignment)); 16218 } 16219 16220 TEST_F(FormatTest, AlignConsecutiveAssignments) { 16221 FormatStyle Alignment = getLLVMStyle(); 16222 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 16223 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 16224 verifyFormat("int a = 5;\n" 16225 "int oneTwoThree = 123;", 16226 Alignment); 16227 verifyFormat("int a = 5;\n" 16228 "int oneTwoThree = 123;", 16229 Alignment); 16230 16231 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 16232 verifyFormat("int a = 5;\n" 16233 "int oneTwoThree = 123;", 16234 Alignment); 16235 verifyFormat("int a = method();\n" 16236 "int oneTwoThree = 133;", 16237 Alignment); 16238 verifyFormat("a &= 5;\n" 16239 "bcd *= 5;\n" 16240 "ghtyf += 5;\n" 16241 "dvfvdb -= 5;\n" 16242 "a /= 5;\n" 16243 "vdsvsv %= 5;\n" 16244 "sfdbddfbdfbb ^= 5;\n" 16245 "dvsdsv |= 5;\n" 16246 "int dsvvdvsdvvv = 123;", 16247 Alignment); 16248 verifyFormat("int i = 1, j = 10;\n" 16249 "something = 2000;", 16250 Alignment); 16251 verifyFormat("something = 2000;\n" 16252 "int i = 1, j = 10;\n", 16253 Alignment); 16254 verifyFormat("something = 2000;\n" 16255 "another = 911;\n" 16256 "int i = 1, j = 10;\n" 16257 "oneMore = 1;\n" 16258 "i = 2;", 16259 Alignment); 16260 verifyFormat("int a = 5;\n" 16261 "int one = 1;\n" 16262 "method();\n" 16263 "int oneTwoThree = 123;\n" 16264 "int oneTwo = 12;", 16265 Alignment); 16266 verifyFormat("int oneTwoThree = 123;\n" 16267 "int oneTwo = 12;\n" 16268 "method();\n", 16269 Alignment); 16270 verifyFormat("int oneTwoThree = 123; // comment\n" 16271 "int oneTwo = 12; // comment", 16272 Alignment); 16273 verifyFormat("int f() = default;\n" 16274 "int &operator() = default;\n" 16275 "int &operator=() {", 16276 Alignment); 16277 verifyFormat("int f() = default; // comment\n" 16278 "int &operator() = default; // comment\n" 16279 "int &operator=() {", 16280 Alignment); 16281 verifyFormat("int f() = default;\n" 16282 "int &operator() = default;\n" 16283 "int &operator==() {", 16284 Alignment); 16285 verifyFormat("int f() = default;\n" 16286 "int &operator() = default;\n" 16287 "int &operator<=() {", 16288 Alignment); 16289 verifyFormat("int f() = default;\n" 16290 "int &operator() = default;\n" 16291 "int &operator!=() {", 16292 Alignment); 16293 verifyFormat("int f() = default;\n" 16294 "int &operator() = default;\n" 16295 "int &operator=();", 16296 Alignment); 16297 verifyFormat("/* long long padding */ int f() = default;\n" 16298 "int &operator() = default;\n" 16299 "int &operator/**/ =();", 16300 Alignment); 16301 16302 // Bug 25167 16303 /* Uncomment when fixed 16304 verifyFormat("#if A\n" 16305 "#else\n" 16306 "int aaaaaaaa = 12;\n" 16307 "#endif\n" 16308 "#if B\n" 16309 "#else\n" 16310 "int a = 12;\n" 16311 "#endif\n", 16312 Alignment); 16313 verifyFormat("enum foo {\n" 16314 "#if A\n" 16315 "#else\n" 16316 " aaaaaaaa = 12;\n" 16317 "#endif\n" 16318 "#if B\n" 16319 "#else\n" 16320 " a = 12;\n" 16321 "#endif\n" 16322 "};\n", 16323 Alignment); 16324 */ 16325 16326 EXPECT_EQ("int a = 5;\n" 16327 "\n" 16328 "int oneTwoThree = 123;", 16329 format("int a = 5;\n" 16330 "\n" 16331 "int oneTwoThree= 123;", 16332 Alignment)); 16333 EXPECT_EQ("int a = 5;\n" 16334 "int one = 1;\n" 16335 "\n" 16336 "int oneTwoThree = 123;", 16337 format("int a = 5;\n" 16338 "int one = 1;\n" 16339 "\n" 16340 "int oneTwoThree = 123;", 16341 Alignment)); 16342 EXPECT_EQ("int a = 5;\n" 16343 "int one = 1;\n" 16344 "\n" 16345 "int oneTwoThree = 123;\n" 16346 "int oneTwo = 12;", 16347 format("int a = 5;\n" 16348 "int one = 1;\n" 16349 "\n" 16350 "int oneTwoThree = 123;\n" 16351 "int oneTwo = 12;", 16352 Alignment)); 16353 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 16354 verifyFormat("#define A \\\n" 16355 " int aaaa = 12; \\\n" 16356 " int b = 23; \\\n" 16357 " int ccc = 234; \\\n" 16358 " int dddddddddd = 2345;", 16359 Alignment); 16360 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 16361 verifyFormat("#define A \\\n" 16362 " int aaaa = 12; \\\n" 16363 " int b = 23; \\\n" 16364 " int ccc = 234; \\\n" 16365 " int dddddddddd = 2345;", 16366 Alignment); 16367 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 16368 verifyFormat("#define A " 16369 " \\\n" 16370 " int aaaa = 12; " 16371 " \\\n" 16372 " int b = 23; " 16373 " \\\n" 16374 " int ccc = 234; " 16375 " \\\n" 16376 " int dddddddddd = 2345;", 16377 Alignment); 16378 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 16379 "k = 4, int l = 5,\n" 16380 " int m = 6) {\n" 16381 " int j = 10;\n" 16382 " otherThing = 1;\n" 16383 "}", 16384 Alignment); 16385 verifyFormat("void SomeFunction(int parameter = 0) {\n" 16386 " int i = 1;\n" 16387 " int j = 2;\n" 16388 " int big = 10000;\n" 16389 "}", 16390 Alignment); 16391 verifyFormat("class C {\n" 16392 "public:\n" 16393 " int i = 1;\n" 16394 " virtual void f() = 0;\n" 16395 "};", 16396 Alignment); 16397 verifyFormat("int i = 1;\n" 16398 "if (SomeType t = getSomething()) {\n" 16399 "}\n" 16400 "int j = 2;\n" 16401 "int big = 10000;", 16402 Alignment); 16403 verifyFormat("int j = 7;\n" 16404 "for (int k = 0; k < N; ++k) {\n" 16405 "}\n" 16406 "int j = 2;\n" 16407 "int big = 10000;\n" 16408 "}", 16409 Alignment); 16410 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 16411 verifyFormat("int i = 1;\n" 16412 "LooooooooooongType loooooooooooooooooooooongVariable\n" 16413 " = someLooooooooooooooooongFunction();\n" 16414 "int j = 2;", 16415 Alignment); 16416 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 16417 verifyFormat("int i = 1;\n" 16418 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 16419 " someLooooooooooooooooongFunction();\n" 16420 "int j = 2;", 16421 Alignment); 16422 16423 verifyFormat("auto lambda = []() {\n" 16424 " auto i = 0;\n" 16425 " return 0;\n" 16426 "};\n" 16427 "int i = 0;\n" 16428 "auto v = type{\n" 16429 " i = 1, //\n" 16430 " (i = 2), //\n" 16431 " i = 3 //\n" 16432 "};", 16433 Alignment); 16434 16435 verifyFormat( 16436 "int i = 1;\n" 16437 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 16438 " loooooooooooooooooooooongParameterB);\n" 16439 "int j = 2;", 16440 Alignment); 16441 16442 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n" 16443 " typename B = very_long_type_name_1,\n" 16444 " typename T_2 = very_long_type_name_2>\n" 16445 "auto foo() {}\n", 16446 Alignment); 16447 verifyFormat("int a, b = 1;\n" 16448 "int c = 2;\n" 16449 "int dd = 3;\n", 16450 Alignment); 16451 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 16452 "float b[1][] = {{3.f}};\n", 16453 Alignment); 16454 verifyFormat("for (int i = 0; i < 1; i++)\n" 16455 " int x = 1;\n", 16456 Alignment); 16457 verifyFormat("for (i = 0; i < 1; i++)\n" 16458 " x = 1;\n" 16459 "y = 1;\n", 16460 Alignment); 16461 16462 Alignment.ReflowComments = true; 16463 Alignment.ColumnLimit = 50; 16464 EXPECT_EQ("int x = 0;\n" 16465 "int yy = 1; /// specificlennospace\n" 16466 "int zzz = 2;\n", 16467 format("int x = 0;\n" 16468 "int yy = 1; ///specificlennospace\n" 16469 "int zzz = 2;\n", 16470 Alignment)); 16471 } 16472 16473 TEST_F(FormatTest, AlignConsecutiveBitFields) { 16474 FormatStyle Alignment = getLLVMStyle(); 16475 Alignment.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive; 16476 verifyFormat("int const a : 5;\n" 16477 "int oneTwoThree : 23;", 16478 Alignment); 16479 16480 // Initializers are allowed starting with c++2a 16481 verifyFormat("int const a : 5 = 1;\n" 16482 "int oneTwoThree : 23 = 0;", 16483 Alignment); 16484 16485 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 16486 verifyFormat("int const a : 5;\n" 16487 "int oneTwoThree : 23;", 16488 Alignment); 16489 16490 verifyFormat("int const a : 5; // comment\n" 16491 "int oneTwoThree : 23; // comment", 16492 Alignment); 16493 16494 verifyFormat("int const a : 5 = 1;\n" 16495 "int oneTwoThree : 23 = 0;", 16496 Alignment); 16497 16498 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 16499 verifyFormat("int const a : 5 = 1;\n" 16500 "int oneTwoThree : 23 = 0;", 16501 Alignment); 16502 verifyFormat("int const a : 5 = {1};\n" 16503 "int oneTwoThree : 23 = 0;", 16504 Alignment); 16505 16506 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None; 16507 verifyFormat("int const a :5;\n" 16508 "int oneTwoThree:23;", 16509 Alignment); 16510 16511 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before; 16512 verifyFormat("int const a :5;\n" 16513 "int oneTwoThree :23;", 16514 Alignment); 16515 16516 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After; 16517 verifyFormat("int const a : 5;\n" 16518 "int oneTwoThree: 23;", 16519 Alignment); 16520 16521 // Known limitations: ':' is only recognized as a bitfield colon when 16522 // followed by a number. 16523 /* 16524 verifyFormat("int oneTwoThree : SOME_CONSTANT;\n" 16525 "int a : 5;", 16526 Alignment); 16527 */ 16528 } 16529 16530 TEST_F(FormatTest, AlignConsecutiveDeclarations) { 16531 FormatStyle Alignment = getLLVMStyle(); 16532 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 16533 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_None; 16534 Alignment.PointerAlignment = FormatStyle::PAS_Right; 16535 verifyFormat("float const a = 5;\n" 16536 "int oneTwoThree = 123;", 16537 Alignment); 16538 verifyFormat("int a = 5;\n" 16539 "float const oneTwoThree = 123;", 16540 Alignment); 16541 16542 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 16543 verifyFormat("float const a = 5;\n" 16544 "int oneTwoThree = 123;", 16545 Alignment); 16546 verifyFormat("int a = method();\n" 16547 "float const oneTwoThree = 133;", 16548 Alignment); 16549 verifyFormat("int i = 1, j = 10;\n" 16550 "something = 2000;", 16551 Alignment); 16552 verifyFormat("something = 2000;\n" 16553 "int i = 1, j = 10;\n", 16554 Alignment); 16555 verifyFormat("float something = 2000;\n" 16556 "double another = 911;\n" 16557 "int i = 1, j = 10;\n" 16558 "const int *oneMore = 1;\n" 16559 "unsigned i = 2;", 16560 Alignment); 16561 verifyFormat("float a = 5;\n" 16562 "int one = 1;\n" 16563 "method();\n" 16564 "const double oneTwoThree = 123;\n" 16565 "const unsigned int oneTwo = 12;", 16566 Alignment); 16567 verifyFormat("int oneTwoThree{0}; // comment\n" 16568 "unsigned oneTwo; // comment", 16569 Alignment); 16570 verifyFormat("unsigned int *a;\n" 16571 "int *b;\n" 16572 "unsigned int Const *c;\n" 16573 "unsigned int const *d;\n" 16574 "unsigned int Const &e;\n" 16575 "unsigned int const &f;", 16576 Alignment); 16577 verifyFormat("Const unsigned int *c;\n" 16578 "const unsigned int *d;\n" 16579 "Const unsigned int &e;\n" 16580 "const unsigned int &f;\n" 16581 "const unsigned g;\n" 16582 "Const unsigned h;", 16583 Alignment); 16584 EXPECT_EQ("float const a = 5;\n" 16585 "\n" 16586 "int oneTwoThree = 123;", 16587 format("float const a = 5;\n" 16588 "\n" 16589 "int oneTwoThree= 123;", 16590 Alignment)); 16591 EXPECT_EQ("float a = 5;\n" 16592 "int one = 1;\n" 16593 "\n" 16594 "unsigned oneTwoThree = 123;", 16595 format("float a = 5;\n" 16596 "int one = 1;\n" 16597 "\n" 16598 "unsigned oneTwoThree = 123;", 16599 Alignment)); 16600 EXPECT_EQ("float a = 5;\n" 16601 "int one = 1;\n" 16602 "\n" 16603 "unsigned oneTwoThree = 123;\n" 16604 "int oneTwo = 12;", 16605 format("float a = 5;\n" 16606 "int one = 1;\n" 16607 "\n" 16608 "unsigned oneTwoThree = 123;\n" 16609 "int oneTwo = 12;", 16610 Alignment)); 16611 // Function prototype alignment 16612 verifyFormat("int a();\n" 16613 "double b();", 16614 Alignment); 16615 verifyFormat("int a(int x);\n" 16616 "double b();", 16617 Alignment); 16618 unsigned OldColumnLimit = Alignment.ColumnLimit; 16619 // We need to set ColumnLimit to zero, in order to stress nested alignments, 16620 // otherwise the function parameters will be re-flowed onto a single line. 16621 Alignment.ColumnLimit = 0; 16622 EXPECT_EQ("int a(int x,\n" 16623 " float y);\n" 16624 "double b(int x,\n" 16625 " double y);", 16626 format("int a(int x,\n" 16627 " float y);\n" 16628 "double b(int x,\n" 16629 " double y);", 16630 Alignment)); 16631 // This ensures that function parameters of function declarations are 16632 // correctly indented when their owning functions are indented. 16633 // The failure case here is for 'double y' to not be indented enough. 16634 EXPECT_EQ("double a(int x);\n" 16635 "int b(int y,\n" 16636 " double z);", 16637 format("double a(int x);\n" 16638 "int b(int y,\n" 16639 " double z);", 16640 Alignment)); 16641 // Set ColumnLimit low so that we induce wrapping immediately after 16642 // the function name and opening paren. 16643 Alignment.ColumnLimit = 13; 16644 verifyFormat("int function(\n" 16645 " int x,\n" 16646 " bool y);", 16647 Alignment); 16648 Alignment.ColumnLimit = OldColumnLimit; 16649 // Ensure function pointers don't screw up recursive alignment 16650 verifyFormat("int a(int x, void (*fp)(int y));\n" 16651 "double b();", 16652 Alignment); 16653 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 16654 // Ensure recursive alignment is broken by function braces, so that the 16655 // "a = 1" does not align with subsequent assignments inside the function 16656 // body. 16657 verifyFormat("int func(int a = 1) {\n" 16658 " int b = 2;\n" 16659 " int cc = 3;\n" 16660 "}", 16661 Alignment); 16662 verifyFormat("float something = 2000;\n" 16663 "double another = 911;\n" 16664 "int i = 1, j = 10;\n" 16665 "const int *oneMore = 1;\n" 16666 "unsigned i = 2;", 16667 Alignment); 16668 verifyFormat("int oneTwoThree = {0}; // comment\n" 16669 "unsigned oneTwo = 0; // comment", 16670 Alignment); 16671 // Make sure that scope is correctly tracked, in the absence of braces 16672 verifyFormat("for (int i = 0; i < n; i++)\n" 16673 " j = i;\n" 16674 "double x = 1;\n", 16675 Alignment); 16676 verifyFormat("if (int i = 0)\n" 16677 " j = i;\n" 16678 "double x = 1;\n", 16679 Alignment); 16680 // Ensure operator[] and operator() are comprehended 16681 verifyFormat("struct test {\n" 16682 " long long int foo();\n" 16683 " int operator[](int a);\n" 16684 " double bar();\n" 16685 "};\n", 16686 Alignment); 16687 verifyFormat("struct test {\n" 16688 " long long int foo();\n" 16689 " int operator()(int a);\n" 16690 " double bar();\n" 16691 "};\n", 16692 Alignment); 16693 // http://llvm.org/PR52914 16694 verifyFormat("char *a[] = {\"a\", // comment\n" 16695 " \"bb\"};\n" 16696 "int bbbbbbb = 0;", 16697 Alignment); 16698 16699 // PAS_Right 16700 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 16701 " int const i = 1;\n" 16702 " int *j = 2;\n" 16703 " int big = 10000;\n" 16704 "\n" 16705 " unsigned oneTwoThree = 123;\n" 16706 " int oneTwo = 12;\n" 16707 " method();\n" 16708 " float k = 2;\n" 16709 " int ll = 10000;\n" 16710 "}", 16711 format("void SomeFunction(int parameter= 0) {\n" 16712 " int const i= 1;\n" 16713 " int *j=2;\n" 16714 " int big = 10000;\n" 16715 "\n" 16716 "unsigned oneTwoThree =123;\n" 16717 "int oneTwo = 12;\n" 16718 " method();\n" 16719 "float k= 2;\n" 16720 "int ll=10000;\n" 16721 "}", 16722 Alignment)); 16723 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 16724 " int const i = 1;\n" 16725 " int **j = 2, ***k;\n" 16726 " int &k = i;\n" 16727 " int &&l = i + j;\n" 16728 " int big = 10000;\n" 16729 "\n" 16730 " unsigned oneTwoThree = 123;\n" 16731 " int oneTwo = 12;\n" 16732 " method();\n" 16733 " float k = 2;\n" 16734 " int ll = 10000;\n" 16735 "}", 16736 format("void SomeFunction(int parameter= 0) {\n" 16737 " int const i= 1;\n" 16738 " int **j=2,***k;\n" 16739 "int &k=i;\n" 16740 "int &&l=i+j;\n" 16741 " int big = 10000;\n" 16742 "\n" 16743 "unsigned oneTwoThree =123;\n" 16744 "int oneTwo = 12;\n" 16745 " method();\n" 16746 "float k= 2;\n" 16747 "int ll=10000;\n" 16748 "}", 16749 Alignment)); 16750 // variables are aligned at their name, pointers are at the right most 16751 // position 16752 verifyFormat("int *a;\n" 16753 "int **b;\n" 16754 "int ***c;\n" 16755 "int foobar;\n", 16756 Alignment); 16757 16758 // PAS_Left 16759 FormatStyle AlignmentLeft = Alignment; 16760 AlignmentLeft.PointerAlignment = FormatStyle::PAS_Left; 16761 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 16762 " int const i = 1;\n" 16763 " int* j = 2;\n" 16764 " int big = 10000;\n" 16765 "\n" 16766 " unsigned oneTwoThree = 123;\n" 16767 " int oneTwo = 12;\n" 16768 " method();\n" 16769 " float k = 2;\n" 16770 " int ll = 10000;\n" 16771 "}", 16772 format("void SomeFunction(int parameter= 0) {\n" 16773 " int const i= 1;\n" 16774 " int *j=2;\n" 16775 " int big = 10000;\n" 16776 "\n" 16777 "unsigned oneTwoThree =123;\n" 16778 "int oneTwo = 12;\n" 16779 " method();\n" 16780 "float k= 2;\n" 16781 "int ll=10000;\n" 16782 "}", 16783 AlignmentLeft)); 16784 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 16785 " int const i = 1;\n" 16786 " int** j = 2;\n" 16787 " int& k = i;\n" 16788 " int&& l = i + j;\n" 16789 " int big = 10000;\n" 16790 "\n" 16791 " unsigned oneTwoThree = 123;\n" 16792 " int oneTwo = 12;\n" 16793 " method();\n" 16794 " float k = 2;\n" 16795 " int ll = 10000;\n" 16796 "}", 16797 format("void SomeFunction(int parameter= 0) {\n" 16798 " int const i= 1;\n" 16799 " int **j=2;\n" 16800 "int &k=i;\n" 16801 "int &&l=i+j;\n" 16802 " int big = 10000;\n" 16803 "\n" 16804 "unsigned oneTwoThree =123;\n" 16805 "int oneTwo = 12;\n" 16806 " method();\n" 16807 "float k= 2;\n" 16808 "int ll=10000;\n" 16809 "}", 16810 AlignmentLeft)); 16811 // variables are aligned at their name, pointers are at the left most position 16812 verifyFormat("int* a;\n" 16813 "int** b;\n" 16814 "int*** c;\n" 16815 "int foobar;\n", 16816 AlignmentLeft); 16817 16818 // PAS_Middle 16819 FormatStyle AlignmentMiddle = Alignment; 16820 AlignmentMiddle.PointerAlignment = FormatStyle::PAS_Middle; 16821 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 16822 " int const i = 1;\n" 16823 " int * j = 2;\n" 16824 " int big = 10000;\n" 16825 "\n" 16826 " unsigned oneTwoThree = 123;\n" 16827 " int oneTwo = 12;\n" 16828 " method();\n" 16829 " float k = 2;\n" 16830 " int ll = 10000;\n" 16831 "}", 16832 format("void SomeFunction(int parameter= 0) {\n" 16833 " int const i= 1;\n" 16834 " int *j=2;\n" 16835 " int big = 10000;\n" 16836 "\n" 16837 "unsigned oneTwoThree =123;\n" 16838 "int oneTwo = 12;\n" 16839 " method();\n" 16840 "float k= 2;\n" 16841 "int ll=10000;\n" 16842 "}", 16843 AlignmentMiddle)); 16844 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 16845 " int const i = 1;\n" 16846 " int ** j = 2, ***k;\n" 16847 " int & k = i;\n" 16848 " int && l = i + j;\n" 16849 " int big = 10000;\n" 16850 "\n" 16851 " unsigned oneTwoThree = 123;\n" 16852 " int oneTwo = 12;\n" 16853 " method();\n" 16854 " float k = 2;\n" 16855 " int ll = 10000;\n" 16856 "}", 16857 format("void SomeFunction(int parameter= 0) {\n" 16858 " int const i= 1;\n" 16859 " int **j=2,***k;\n" 16860 "int &k=i;\n" 16861 "int &&l=i+j;\n" 16862 " int big = 10000;\n" 16863 "\n" 16864 "unsigned oneTwoThree =123;\n" 16865 "int oneTwo = 12;\n" 16866 " method();\n" 16867 "float k= 2;\n" 16868 "int ll=10000;\n" 16869 "}", 16870 AlignmentMiddle)); 16871 // variables are aligned at their name, pointers are in the middle 16872 verifyFormat("int * a;\n" 16873 "int * b;\n" 16874 "int *** c;\n" 16875 "int foobar;\n", 16876 AlignmentMiddle); 16877 16878 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 16879 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 16880 verifyFormat("#define A \\\n" 16881 " int aaaa = 12; \\\n" 16882 " float b = 23; \\\n" 16883 " const int ccc = 234; \\\n" 16884 " unsigned dddddddddd = 2345;", 16885 Alignment); 16886 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 16887 verifyFormat("#define A \\\n" 16888 " int aaaa = 12; \\\n" 16889 " float b = 23; \\\n" 16890 " const int ccc = 234; \\\n" 16891 " unsigned dddddddddd = 2345;", 16892 Alignment); 16893 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 16894 Alignment.ColumnLimit = 30; 16895 verifyFormat("#define A \\\n" 16896 " int aaaa = 12; \\\n" 16897 " float b = 23; \\\n" 16898 " const int ccc = 234; \\\n" 16899 " int dddddddddd = 2345;", 16900 Alignment); 16901 Alignment.ColumnLimit = 80; 16902 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 16903 "k = 4, int l = 5,\n" 16904 " int m = 6) {\n" 16905 " const int j = 10;\n" 16906 " otherThing = 1;\n" 16907 "}", 16908 Alignment); 16909 verifyFormat("void SomeFunction(int parameter = 0) {\n" 16910 " int const i = 1;\n" 16911 " int *j = 2;\n" 16912 " int big = 10000;\n" 16913 "}", 16914 Alignment); 16915 verifyFormat("class C {\n" 16916 "public:\n" 16917 " int i = 1;\n" 16918 " virtual void f() = 0;\n" 16919 "};", 16920 Alignment); 16921 verifyFormat("float i = 1;\n" 16922 "if (SomeType t = getSomething()) {\n" 16923 "}\n" 16924 "const unsigned j = 2;\n" 16925 "int big = 10000;", 16926 Alignment); 16927 verifyFormat("float j = 7;\n" 16928 "for (int k = 0; k < N; ++k) {\n" 16929 "}\n" 16930 "unsigned j = 2;\n" 16931 "int big = 10000;\n" 16932 "}", 16933 Alignment); 16934 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 16935 verifyFormat("float i = 1;\n" 16936 "LooooooooooongType loooooooooooooooooooooongVariable\n" 16937 " = someLooooooooooooooooongFunction();\n" 16938 "int j = 2;", 16939 Alignment); 16940 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 16941 verifyFormat("int i = 1;\n" 16942 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 16943 " someLooooooooooooooooongFunction();\n" 16944 "int j = 2;", 16945 Alignment); 16946 16947 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 16948 verifyFormat("auto lambda = []() {\n" 16949 " auto ii = 0;\n" 16950 " float j = 0;\n" 16951 " return 0;\n" 16952 "};\n" 16953 "int i = 0;\n" 16954 "float i2 = 0;\n" 16955 "auto v = type{\n" 16956 " i = 1, //\n" 16957 " (i = 2), //\n" 16958 " i = 3 //\n" 16959 "};", 16960 Alignment); 16961 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 16962 16963 verifyFormat( 16964 "int i = 1;\n" 16965 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 16966 " loooooooooooooooooooooongParameterB);\n" 16967 "int j = 2;", 16968 Alignment); 16969 16970 // Test interactions with ColumnLimit and AlignConsecutiveAssignments: 16971 // We expect declarations and assignments to align, as long as it doesn't 16972 // exceed the column limit, starting a new alignment sequence whenever it 16973 // happens. 16974 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 16975 Alignment.ColumnLimit = 30; 16976 verifyFormat("float ii = 1;\n" 16977 "unsigned j = 2;\n" 16978 "int someVerylongVariable = 1;\n" 16979 "AnotherLongType ll = 123456;\n" 16980 "VeryVeryLongType k = 2;\n" 16981 "int myvar = 1;", 16982 Alignment); 16983 Alignment.ColumnLimit = 80; 16984 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 16985 16986 verifyFormat( 16987 "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n" 16988 " typename LongType, typename B>\n" 16989 "auto foo() {}\n", 16990 Alignment); 16991 verifyFormat("float a, b = 1;\n" 16992 "int c = 2;\n" 16993 "int dd = 3;\n", 16994 Alignment); 16995 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 16996 "float b[1][] = {{3.f}};\n", 16997 Alignment); 16998 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 16999 verifyFormat("float a, b = 1;\n" 17000 "int c = 2;\n" 17001 "int dd = 3;\n", 17002 Alignment); 17003 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17004 "float b[1][] = {{3.f}};\n", 17005 Alignment); 17006 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 17007 17008 Alignment.ColumnLimit = 30; 17009 Alignment.BinPackParameters = false; 17010 verifyFormat("void foo(float a,\n" 17011 " float b,\n" 17012 " int c,\n" 17013 " uint32_t *d) {\n" 17014 " int *e = 0;\n" 17015 " float f = 0;\n" 17016 " double g = 0;\n" 17017 "}\n" 17018 "void bar(ino_t a,\n" 17019 " int b,\n" 17020 " uint32_t *c,\n" 17021 " bool d) {}\n", 17022 Alignment); 17023 Alignment.BinPackParameters = true; 17024 Alignment.ColumnLimit = 80; 17025 17026 // Bug 33507 17027 Alignment.PointerAlignment = FormatStyle::PAS_Middle; 17028 verifyFormat( 17029 "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n" 17030 " static const Version verVs2017;\n" 17031 " return true;\n" 17032 "});\n", 17033 Alignment); 17034 Alignment.PointerAlignment = FormatStyle::PAS_Right; 17035 17036 // See llvm.org/PR35641 17037 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17038 verifyFormat("int func() { //\n" 17039 " int b;\n" 17040 " unsigned c;\n" 17041 "}", 17042 Alignment); 17043 17044 // See PR37175 17045 FormatStyle Style = getMozillaStyle(); 17046 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17047 EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n" 17048 "foo(int a);", 17049 format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style)); 17050 17051 Alignment.PointerAlignment = FormatStyle::PAS_Left; 17052 verifyFormat("unsigned int* a;\n" 17053 "int* b;\n" 17054 "unsigned int Const* c;\n" 17055 "unsigned int const* d;\n" 17056 "unsigned int Const& e;\n" 17057 "unsigned int const& f;", 17058 Alignment); 17059 verifyFormat("Const unsigned int* c;\n" 17060 "const unsigned int* d;\n" 17061 "Const unsigned int& e;\n" 17062 "const unsigned int& f;\n" 17063 "const unsigned g;\n" 17064 "Const unsigned h;", 17065 Alignment); 17066 17067 Alignment.PointerAlignment = FormatStyle::PAS_Middle; 17068 verifyFormat("unsigned int * a;\n" 17069 "int * b;\n" 17070 "unsigned int Const * c;\n" 17071 "unsigned int const * d;\n" 17072 "unsigned int Const & e;\n" 17073 "unsigned int const & f;", 17074 Alignment); 17075 verifyFormat("Const unsigned int * c;\n" 17076 "const unsigned int * d;\n" 17077 "Const unsigned int & e;\n" 17078 "const unsigned int & f;\n" 17079 "const unsigned g;\n" 17080 "Const unsigned h;", 17081 Alignment); 17082 } 17083 17084 TEST_F(FormatTest, AlignWithLineBreaks) { 17085 auto Style = getLLVMStyleWithColumns(120); 17086 17087 EXPECT_EQ(Style.AlignConsecutiveAssignments, FormatStyle::ACS_None); 17088 EXPECT_EQ(Style.AlignConsecutiveDeclarations, FormatStyle::ACS_None); 17089 verifyFormat("void foo() {\n" 17090 " int myVar = 5;\n" 17091 " double x = 3.14;\n" 17092 " auto str = \"Hello \"\n" 17093 " \"World\";\n" 17094 " auto s = \"Hello \"\n" 17095 " \"Again\";\n" 17096 "}", 17097 Style); 17098 17099 // clang-format off 17100 verifyFormat("void foo() {\n" 17101 " const int capacityBefore = Entries.capacity();\n" 17102 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17103 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17104 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17105 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17106 "}", 17107 Style); 17108 // clang-format on 17109 17110 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17111 verifyFormat("void foo() {\n" 17112 " int myVar = 5;\n" 17113 " double x = 3.14;\n" 17114 " auto str = \"Hello \"\n" 17115 " \"World\";\n" 17116 " auto s = \"Hello \"\n" 17117 " \"Again\";\n" 17118 "}", 17119 Style); 17120 17121 // clang-format off 17122 verifyFormat("void foo() {\n" 17123 " const int capacityBefore = Entries.capacity();\n" 17124 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17125 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17126 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17127 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17128 "}", 17129 Style); 17130 // clang-format on 17131 17132 Style.AlignConsecutiveAssignments = FormatStyle::ACS_None; 17133 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17134 verifyFormat("void foo() {\n" 17135 " int myVar = 5;\n" 17136 " double x = 3.14;\n" 17137 " auto str = \"Hello \"\n" 17138 " \"World\";\n" 17139 " auto s = \"Hello \"\n" 17140 " \"Again\";\n" 17141 "}", 17142 Style); 17143 17144 // clang-format off 17145 verifyFormat("void foo() {\n" 17146 " const int capacityBefore = Entries.capacity();\n" 17147 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17148 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17149 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17150 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17151 "}", 17152 Style); 17153 // clang-format on 17154 17155 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17156 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17157 17158 verifyFormat("void foo() {\n" 17159 " int myVar = 5;\n" 17160 " double x = 3.14;\n" 17161 " auto str = \"Hello \"\n" 17162 " \"World\";\n" 17163 " auto s = \"Hello \"\n" 17164 " \"Again\";\n" 17165 "}", 17166 Style); 17167 17168 // clang-format off 17169 verifyFormat("void foo() {\n" 17170 " const int capacityBefore = Entries.capacity();\n" 17171 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17172 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17173 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17174 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17175 "}", 17176 Style); 17177 // clang-format on 17178 17179 Style = getLLVMStyleWithColumns(120); 17180 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17181 Style.ContinuationIndentWidth = 4; 17182 Style.IndentWidth = 4; 17183 17184 // clang-format off 17185 verifyFormat("void SomeFunc() {\n" 17186 " newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 17187 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17188 " newWatcher.maxAge = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 17189 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17190 " newWatcher.max = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 17191 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17192 "}", 17193 Style); 17194 // clang-format on 17195 17196 Style.BinPackArguments = false; 17197 17198 // clang-format off 17199 verifyFormat("void SomeFunc() {\n" 17200 " newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(\n" 17201 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17202 " newWatcher.maxAge = ToLegacyTimestamp(GetMaxAge(\n" 17203 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17204 " newWatcher.max = ToLegacyTimestamp(GetMaxAge(\n" 17205 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17206 "}", 17207 Style); 17208 // clang-format on 17209 } 17210 17211 TEST_F(FormatTest, AlignWithInitializerPeriods) { 17212 auto Style = getLLVMStyleWithColumns(60); 17213 17214 verifyFormat("void foo1(void) {\n" 17215 " BYTE p[1] = 1;\n" 17216 " A B = {.one_foooooooooooooooo = 2,\n" 17217 " .two_fooooooooooooo = 3,\n" 17218 " .three_fooooooooooooo = 4};\n" 17219 " BYTE payload = 2;\n" 17220 "}", 17221 Style); 17222 17223 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17224 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_None; 17225 verifyFormat("void foo2(void) {\n" 17226 " BYTE p[1] = 1;\n" 17227 " A B = {.one_foooooooooooooooo = 2,\n" 17228 " .two_fooooooooooooo = 3,\n" 17229 " .three_fooooooooooooo = 4};\n" 17230 " BYTE payload = 2;\n" 17231 "}", 17232 Style); 17233 17234 Style.AlignConsecutiveAssignments = FormatStyle::ACS_None; 17235 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17236 verifyFormat("void foo3(void) {\n" 17237 " BYTE p[1] = 1;\n" 17238 " A B = {.one_foooooooooooooooo = 2,\n" 17239 " .two_fooooooooooooo = 3,\n" 17240 " .three_fooooooooooooo = 4};\n" 17241 " BYTE payload = 2;\n" 17242 "}", 17243 Style); 17244 17245 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17246 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17247 verifyFormat("void foo4(void) {\n" 17248 " BYTE p[1] = 1;\n" 17249 " A B = {.one_foooooooooooooooo = 2,\n" 17250 " .two_fooooooooooooo = 3,\n" 17251 " .three_fooooooooooooo = 4};\n" 17252 " BYTE payload = 2;\n" 17253 "}", 17254 Style); 17255 } 17256 17257 TEST_F(FormatTest, LinuxBraceBreaking) { 17258 FormatStyle LinuxBraceStyle = getLLVMStyle(); 17259 LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux; 17260 verifyFormat("namespace a\n" 17261 "{\n" 17262 "class A\n" 17263 "{\n" 17264 " void f()\n" 17265 " {\n" 17266 " if (true) {\n" 17267 " a();\n" 17268 " b();\n" 17269 " } else {\n" 17270 " a();\n" 17271 " }\n" 17272 " }\n" 17273 " void g() { return; }\n" 17274 "};\n" 17275 "struct B {\n" 17276 " int x;\n" 17277 "};\n" 17278 "} // namespace a\n", 17279 LinuxBraceStyle); 17280 verifyFormat("enum X {\n" 17281 " Y = 0,\n" 17282 "}\n", 17283 LinuxBraceStyle); 17284 verifyFormat("struct S {\n" 17285 " int Type;\n" 17286 " union {\n" 17287 " int x;\n" 17288 " double y;\n" 17289 " } Value;\n" 17290 " class C\n" 17291 " {\n" 17292 " MyFavoriteType Value;\n" 17293 " } Class;\n" 17294 "}\n", 17295 LinuxBraceStyle); 17296 } 17297 17298 TEST_F(FormatTest, MozillaBraceBreaking) { 17299 FormatStyle MozillaBraceStyle = getLLVMStyle(); 17300 MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla; 17301 MozillaBraceStyle.FixNamespaceComments = false; 17302 verifyFormat("namespace a {\n" 17303 "class A\n" 17304 "{\n" 17305 " void f()\n" 17306 " {\n" 17307 " if (true) {\n" 17308 " a();\n" 17309 " b();\n" 17310 " }\n" 17311 " }\n" 17312 " void g() { return; }\n" 17313 "};\n" 17314 "enum E\n" 17315 "{\n" 17316 " A,\n" 17317 " // foo\n" 17318 " B,\n" 17319 " C\n" 17320 "};\n" 17321 "struct B\n" 17322 "{\n" 17323 " int x;\n" 17324 "};\n" 17325 "}\n", 17326 MozillaBraceStyle); 17327 verifyFormat("struct S\n" 17328 "{\n" 17329 " int Type;\n" 17330 " union\n" 17331 " {\n" 17332 " int x;\n" 17333 " double y;\n" 17334 " } Value;\n" 17335 " class C\n" 17336 " {\n" 17337 " MyFavoriteType Value;\n" 17338 " } Class;\n" 17339 "}\n", 17340 MozillaBraceStyle); 17341 } 17342 17343 TEST_F(FormatTest, StroustrupBraceBreaking) { 17344 FormatStyle StroustrupBraceStyle = getLLVMStyle(); 17345 StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 17346 verifyFormat("namespace a {\n" 17347 "class A {\n" 17348 " void f()\n" 17349 " {\n" 17350 " if (true) {\n" 17351 " a();\n" 17352 " b();\n" 17353 " }\n" 17354 " }\n" 17355 " void g() { return; }\n" 17356 "};\n" 17357 "struct B {\n" 17358 " int x;\n" 17359 "};\n" 17360 "} // namespace a\n", 17361 StroustrupBraceStyle); 17362 17363 verifyFormat("void foo()\n" 17364 "{\n" 17365 " if (a) {\n" 17366 " a();\n" 17367 " }\n" 17368 " else {\n" 17369 " b();\n" 17370 " }\n" 17371 "}\n", 17372 StroustrupBraceStyle); 17373 17374 verifyFormat("#ifdef _DEBUG\n" 17375 "int foo(int i = 0)\n" 17376 "#else\n" 17377 "int foo(int i = 5)\n" 17378 "#endif\n" 17379 "{\n" 17380 " return i;\n" 17381 "}", 17382 StroustrupBraceStyle); 17383 17384 verifyFormat("void foo() {}\n" 17385 "void bar()\n" 17386 "#ifdef _DEBUG\n" 17387 "{\n" 17388 " foo();\n" 17389 "}\n" 17390 "#else\n" 17391 "{\n" 17392 "}\n" 17393 "#endif", 17394 StroustrupBraceStyle); 17395 17396 verifyFormat("void foobar() { int i = 5; }\n" 17397 "#ifdef _DEBUG\n" 17398 "void bar() {}\n" 17399 "#else\n" 17400 "void bar() { foobar(); }\n" 17401 "#endif", 17402 StroustrupBraceStyle); 17403 } 17404 17405 TEST_F(FormatTest, AllmanBraceBreaking) { 17406 FormatStyle AllmanBraceStyle = getLLVMStyle(); 17407 AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman; 17408 17409 EXPECT_EQ("namespace a\n" 17410 "{\n" 17411 "void f();\n" 17412 "void g();\n" 17413 "} // namespace a\n", 17414 format("namespace a\n" 17415 "{\n" 17416 "void f();\n" 17417 "void g();\n" 17418 "}\n", 17419 AllmanBraceStyle)); 17420 17421 verifyFormat("namespace a\n" 17422 "{\n" 17423 "class A\n" 17424 "{\n" 17425 " void f()\n" 17426 " {\n" 17427 " if (true)\n" 17428 " {\n" 17429 " a();\n" 17430 " b();\n" 17431 " }\n" 17432 " }\n" 17433 " void g() { return; }\n" 17434 "};\n" 17435 "struct B\n" 17436 "{\n" 17437 " int x;\n" 17438 "};\n" 17439 "union C\n" 17440 "{\n" 17441 "};\n" 17442 "} // namespace a", 17443 AllmanBraceStyle); 17444 17445 verifyFormat("void f()\n" 17446 "{\n" 17447 " if (true)\n" 17448 " {\n" 17449 " a();\n" 17450 " }\n" 17451 " else if (false)\n" 17452 " {\n" 17453 " b();\n" 17454 " }\n" 17455 " else\n" 17456 " {\n" 17457 " c();\n" 17458 " }\n" 17459 "}\n", 17460 AllmanBraceStyle); 17461 17462 verifyFormat("void f()\n" 17463 "{\n" 17464 " for (int i = 0; i < 10; ++i)\n" 17465 " {\n" 17466 " a();\n" 17467 " }\n" 17468 " while (false)\n" 17469 " {\n" 17470 " b();\n" 17471 " }\n" 17472 " do\n" 17473 " {\n" 17474 " c();\n" 17475 " } while (false)\n" 17476 "}\n", 17477 AllmanBraceStyle); 17478 17479 verifyFormat("void f(int a)\n" 17480 "{\n" 17481 " switch (a)\n" 17482 " {\n" 17483 " case 0:\n" 17484 " break;\n" 17485 " case 1:\n" 17486 " {\n" 17487 " break;\n" 17488 " }\n" 17489 " case 2:\n" 17490 " {\n" 17491 " }\n" 17492 " break;\n" 17493 " default:\n" 17494 " break;\n" 17495 " }\n" 17496 "}\n", 17497 AllmanBraceStyle); 17498 17499 verifyFormat("enum X\n" 17500 "{\n" 17501 " Y = 0,\n" 17502 "}\n", 17503 AllmanBraceStyle); 17504 verifyFormat("enum X\n" 17505 "{\n" 17506 " Y = 0\n" 17507 "}\n", 17508 AllmanBraceStyle); 17509 17510 verifyFormat("@interface BSApplicationController ()\n" 17511 "{\n" 17512 "@private\n" 17513 " id _extraIvar;\n" 17514 "}\n" 17515 "@end\n", 17516 AllmanBraceStyle); 17517 17518 verifyFormat("#ifdef _DEBUG\n" 17519 "int foo(int i = 0)\n" 17520 "#else\n" 17521 "int foo(int i = 5)\n" 17522 "#endif\n" 17523 "{\n" 17524 " return i;\n" 17525 "}", 17526 AllmanBraceStyle); 17527 17528 verifyFormat("void foo() {}\n" 17529 "void bar()\n" 17530 "#ifdef _DEBUG\n" 17531 "{\n" 17532 " foo();\n" 17533 "}\n" 17534 "#else\n" 17535 "{\n" 17536 "}\n" 17537 "#endif", 17538 AllmanBraceStyle); 17539 17540 verifyFormat("void foobar() { int i = 5; }\n" 17541 "#ifdef _DEBUG\n" 17542 "void bar() {}\n" 17543 "#else\n" 17544 "void bar() { foobar(); }\n" 17545 "#endif", 17546 AllmanBraceStyle); 17547 17548 EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine, 17549 FormatStyle::SLS_All); 17550 17551 verifyFormat("[](int i) { return i + 2; };\n" 17552 "[](int i, int j)\n" 17553 "{\n" 17554 " auto x = i + j;\n" 17555 " auto y = i * j;\n" 17556 " return x ^ y;\n" 17557 "};\n" 17558 "void foo()\n" 17559 "{\n" 17560 " auto shortLambda = [](int i) { return i + 2; };\n" 17561 " auto longLambda = [](int i, int j)\n" 17562 " {\n" 17563 " auto x = i + j;\n" 17564 " auto y = i * j;\n" 17565 " return x ^ y;\n" 17566 " };\n" 17567 "}", 17568 AllmanBraceStyle); 17569 17570 AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 17571 17572 verifyFormat("[](int i)\n" 17573 "{\n" 17574 " return i + 2;\n" 17575 "};\n" 17576 "[](int i, int j)\n" 17577 "{\n" 17578 " auto x = i + j;\n" 17579 " auto y = i * j;\n" 17580 " return x ^ y;\n" 17581 "};\n" 17582 "void foo()\n" 17583 "{\n" 17584 " auto shortLambda = [](int i)\n" 17585 " {\n" 17586 " return i + 2;\n" 17587 " };\n" 17588 " auto longLambda = [](int i, int j)\n" 17589 " {\n" 17590 " auto x = i + j;\n" 17591 " auto y = i * j;\n" 17592 " return x ^ y;\n" 17593 " };\n" 17594 "}", 17595 AllmanBraceStyle); 17596 17597 // Reset 17598 AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All; 17599 17600 // This shouldn't affect ObjC blocks.. 17601 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n" 17602 " // ...\n" 17603 " int i;\n" 17604 "}];", 17605 AllmanBraceStyle); 17606 verifyFormat("void (^block)(void) = ^{\n" 17607 " // ...\n" 17608 " int i;\n" 17609 "};", 17610 AllmanBraceStyle); 17611 // .. or dict literals. 17612 verifyFormat("void f()\n" 17613 "{\n" 17614 " // ...\n" 17615 " [object someMethod:@{@\"a\" : @\"b\"}];\n" 17616 "}", 17617 AllmanBraceStyle); 17618 verifyFormat("void f()\n" 17619 "{\n" 17620 " // ...\n" 17621 " [object someMethod:@{a : @\"b\"}];\n" 17622 "}", 17623 AllmanBraceStyle); 17624 verifyFormat("int f()\n" 17625 "{ // comment\n" 17626 " return 42;\n" 17627 "}", 17628 AllmanBraceStyle); 17629 17630 AllmanBraceStyle.ColumnLimit = 19; 17631 verifyFormat("void f() { int i; }", AllmanBraceStyle); 17632 AllmanBraceStyle.ColumnLimit = 18; 17633 verifyFormat("void f()\n" 17634 "{\n" 17635 " int i;\n" 17636 "}", 17637 AllmanBraceStyle); 17638 AllmanBraceStyle.ColumnLimit = 80; 17639 17640 FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle; 17641 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = 17642 FormatStyle::SIS_WithoutElse; 17643 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true; 17644 verifyFormat("void f(bool b)\n" 17645 "{\n" 17646 " if (b)\n" 17647 " {\n" 17648 " return;\n" 17649 " }\n" 17650 "}\n", 17651 BreakBeforeBraceShortIfs); 17652 verifyFormat("void f(bool b)\n" 17653 "{\n" 17654 " if constexpr (b)\n" 17655 " {\n" 17656 " return;\n" 17657 " }\n" 17658 "}\n", 17659 BreakBeforeBraceShortIfs); 17660 verifyFormat("void f(bool b)\n" 17661 "{\n" 17662 " if CONSTEXPR (b)\n" 17663 " {\n" 17664 " return;\n" 17665 " }\n" 17666 "}\n", 17667 BreakBeforeBraceShortIfs); 17668 verifyFormat("void f(bool b)\n" 17669 "{\n" 17670 " if (b) return;\n" 17671 "}\n", 17672 BreakBeforeBraceShortIfs); 17673 verifyFormat("void f(bool b)\n" 17674 "{\n" 17675 " if constexpr (b) return;\n" 17676 "}\n", 17677 BreakBeforeBraceShortIfs); 17678 verifyFormat("void f(bool b)\n" 17679 "{\n" 17680 " if CONSTEXPR (b) return;\n" 17681 "}\n", 17682 BreakBeforeBraceShortIfs); 17683 verifyFormat("void f(bool b)\n" 17684 "{\n" 17685 " while (b)\n" 17686 " {\n" 17687 " return;\n" 17688 " }\n" 17689 "}\n", 17690 BreakBeforeBraceShortIfs); 17691 } 17692 17693 TEST_F(FormatTest, WhitesmithsBraceBreaking) { 17694 FormatStyle WhitesmithsBraceStyle = getLLVMStyleWithColumns(0); 17695 WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 17696 17697 // Make a few changes to the style for testing purposes 17698 WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine = 17699 FormatStyle::SFS_Empty; 17700 WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 17701 17702 // FIXME: this test case can't decide whether there should be a blank line 17703 // after the ~D() line or not. It adds one if one doesn't exist in the test 17704 // and it removes the line if one exists. 17705 /* 17706 verifyFormat("class A;\n" 17707 "namespace B\n" 17708 " {\n" 17709 "class C;\n" 17710 "// Comment\n" 17711 "class D\n" 17712 " {\n" 17713 "public:\n" 17714 " D();\n" 17715 " ~D() {}\n" 17716 "private:\n" 17717 " enum E\n" 17718 " {\n" 17719 " F\n" 17720 " }\n" 17721 " };\n" 17722 " } // namespace B\n", 17723 WhitesmithsBraceStyle); 17724 */ 17725 17726 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None; 17727 verifyFormat("namespace a\n" 17728 " {\n" 17729 "class A\n" 17730 " {\n" 17731 " void f()\n" 17732 " {\n" 17733 " if (true)\n" 17734 " {\n" 17735 " a();\n" 17736 " b();\n" 17737 " }\n" 17738 " }\n" 17739 " void g()\n" 17740 " {\n" 17741 " return;\n" 17742 " }\n" 17743 " };\n" 17744 "struct B\n" 17745 " {\n" 17746 " int x;\n" 17747 " };\n" 17748 " } // namespace a", 17749 WhitesmithsBraceStyle); 17750 17751 verifyFormat("namespace a\n" 17752 " {\n" 17753 "namespace b\n" 17754 " {\n" 17755 "class A\n" 17756 " {\n" 17757 " void f()\n" 17758 " {\n" 17759 " if (true)\n" 17760 " {\n" 17761 " a();\n" 17762 " b();\n" 17763 " }\n" 17764 " }\n" 17765 " void g()\n" 17766 " {\n" 17767 " return;\n" 17768 " }\n" 17769 " };\n" 17770 "struct B\n" 17771 " {\n" 17772 " int x;\n" 17773 " };\n" 17774 " } // namespace b\n" 17775 " } // namespace a", 17776 WhitesmithsBraceStyle); 17777 17778 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner; 17779 verifyFormat("namespace a\n" 17780 " {\n" 17781 "namespace b\n" 17782 " {\n" 17783 " class A\n" 17784 " {\n" 17785 " void f()\n" 17786 " {\n" 17787 " if (true)\n" 17788 " {\n" 17789 " a();\n" 17790 " b();\n" 17791 " }\n" 17792 " }\n" 17793 " void g()\n" 17794 " {\n" 17795 " return;\n" 17796 " }\n" 17797 " };\n" 17798 " struct B\n" 17799 " {\n" 17800 " int x;\n" 17801 " };\n" 17802 " } // namespace b\n" 17803 " } // namespace a", 17804 WhitesmithsBraceStyle); 17805 17806 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All; 17807 verifyFormat("namespace a\n" 17808 " {\n" 17809 " namespace b\n" 17810 " {\n" 17811 " class A\n" 17812 " {\n" 17813 " void f()\n" 17814 " {\n" 17815 " if (true)\n" 17816 " {\n" 17817 " a();\n" 17818 " b();\n" 17819 " }\n" 17820 " }\n" 17821 " void g()\n" 17822 " {\n" 17823 " return;\n" 17824 " }\n" 17825 " };\n" 17826 " struct B\n" 17827 " {\n" 17828 " int x;\n" 17829 " };\n" 17830 " } // namespace b\n" 17831 " } // namespace a", 17832 WhitesmithsBraceStyle); 17833 17834 verifyFormat("void f()\n" 17835 " {\n" 17836 " if (true)\n" 17837 " {\n" 17838 " a();\n" 17839 " }\n" 17840 " else if (false)\n" 17841 " {\n" 17842 " b();\n" 17843 " }\n" 17844 " else\n" 17845 " {\n" 17846 " c();\n" 17847 " }\n" 17848 " }\n", 17849 WhitesmithsBraceStyle); 17850 17851 verifyFormat("void f()\n" 17852 " {\n" 17853 " for (int i = 0; i < 10; ++i)\n" 17854 " {\n" 17855 " a();\n" 17856 " }\n" 17857 " while (false)\n" 17858 " {\n" 17859 " b();\n" 17860 " }\n" 17861 " do\n" 17862 " {\n" 17863 " c();\n" 17864 " } while (false)\n" 17865 " }\n", 17866 WhitesmithsBraceStyle); 17867 17868 WhitesmithsBraceStyle.IndentCaseLabels = true; 17869 verifyFormat("void switchTest1(int a)\n" 17870 " {\n" 17871 " switch (a)\n" 17872 " {\n" 17873 " case 2:\n" 17874 " {\n" 17875 " }\n" 17876 " break;\n" 17877 " }\n" 17878 " }\n", 17879 WhitesmithsBraceStyle); 17880 17881 verifyFormat("void switchTest2(int a)\n" 17882 " {\n" 17883 " switch (a)\n" 17884 " {\n" 17885 " case 0:\n" 17886 " break;\n" 17887 " case 1:\n" 17888 " {\n" 17889 " break;\n" 17890 " }\n" 17891 " case 2:\n" 17892 " {\n" 17893 " }\n" 17894 " break;\n" 17895 " default:\n" 17896 " break;\n" 17897 " }\n" 17898 " }\n", 17899 WhitesmithsBraceStyle); 17900 17901 verifyFormat("void switchTest3(int a)\n" 17902 " {\n" 17903 " switch (a)\n" 17904 " {\n" 17905 " case 0:\n" 17906 " {\n" 17907 " foo(x);\n" 17908 " }\n" 17909 " break;\n" 17910 " default:\n" 17911 " {\n" 17912 " foo(1);\n" 17913 " }\n" 17914 " break;\n" 17915 " }\n" 17916 " }\n", 17917 WhitesmithsBraceStyle); 17918 17919 WhitesmithsBraceStyle.IndentCaseLabels = false; 17920 17921 verifyFormat("void switchTest4(int a)\n" 17922 " {\n" 17923 " switch (a)\n" 17924 " {\n" 17925 " case 2:\n" 17926 " {\n" 17927 " }\n" 17928 " break;\n" 17929 " }\n" 17930 " }\n", 17931 WhitesmithsBraceStyle); 17932 17933 verifyFormat("void switchTest5(int a)\n" 17934 " {\n" 17935 " switch (a)\n" 17936 " {\n" 17937 " case 0:\n" 17938 " break;\n" 17939 " case 1:\n" 17940 " {\n" 17941 " foo();\n" 17942 " break;\n" 17943 " }\n" 17944 " case 2:\n" 17945 " {\n" 17946 " }\n" 17947 " break;\n" 17948 " default:\n" 17949 " break;\n" 17950 " }\n" 17951 " }\n", 17952 WhitesmithsBraceStyle); 17953 17954 verifyFormat("void switchTest6(int a)\n" 17955 " {\n" 17956 " switch (a)\n" 17957 " {\n" 17958 " case 0:\n" 17959 " {\n" 17960 " foo(x);\n" 17961 " }\n" 17962 " break;\n" 17963 " default:\n" 17964 " {\n" 17965 " foo(1);\n" 17966 " }\n" 17967 " break;\n" 17968 " }\n" 17969 " }\n", 17970 WhitesmithsBraceStyle); 17971 17972 verifyFormat("enum X\n" 17973 " {\n" 17974 " Y = 0, // testing\n" 17975 " }\n", 17976 WhitesmithsBraceStyle); 17977 17978 verifyFormat("enum X\n" 17979 " {\n" 17980 " Y = 0\n" 17981 " }\n", 17982 WhitesmithsBraceStyle); 17983 verifyFormat("enum X\n" 17984 " {\n" 17985 " Y = 0,\n" 17986 " Z = 1\n" 17987 " };\n", 17988 WhitesmithsBraceStyle); 17989 17990 verifyFormat("@interface BSApplicationController ()\n" 17991 " {\n" 17992 "@private\n" 17993 " id _extraIvar;\n" 17994 " }\n" 17995 "@end\n", 17996 WhitesmithsBraceStyle); 17997 17998 verifyFormat("#ifdef _DEBUG\n" 17999 "int foo(int i = 0)\n" 18000 "#else\n" 18001 "int foo(int i = 5)\n" 18002 "#endif\n" 18003 " {\n" 18004 " return i;\n" 18005 " }", 18006 WhitesmithsBraceStyle); 18007 18008 verifyFormat("void foo() {}\n" 18009 "void bar()\n" 18010 "#ifdef _DEBUG\n" 18011 " {\n" 18012 " foo();\n" 18013 " }\n" 18014 "#else\n" 18015 " {\n" 18016 " }\n" 18017 "#endif", 18018 WhitesmithsBraceStyle); 18019 18020 verifyFormat("void foobar()\n" 18021 " {\n" 18022 " int i = 5;\n" 18023 " }\n" 18024 "#ifdef _DEBUG\n" 18025 "void bar()\n" 18026 " {\n" 18027 " }\n" 18028 "#else\n" 18029 "void bar()\n" 18030 " {\n" 18031 " foobar();\n" 18032 " }\n" 18033 "#endif", 18034 WhitesmithsBraceStyle); 18035 18036 // This shouldn't affect ObjC blocks.. 18037 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n" 18038 " // ...\n" 18039 " int i;\n" 18040 "}];", 18041 WhitesmithsBraceStyle); 18042 verifyFormat("void (^block)(void) = ^{\n" 18043 " // ...\n" 18044 " int i;\n" 18045 "};", 18046 WhitesmithsBraceStyle); 18047 // .. or dict literals. 18048 verifyFormat("void f()\n" 18049 " {\n" 18050 " [object someMethod:@{@\"a\" : @\"b\"}];\n" 18051 " }", 18052 WhitesmithsBraceStyle); 18053 18054 verifyFormat("int f()\n" 18055 " { // comment\n" 18056 " return 42;\n" 18057 " }", 18058 WhitesmithsBraceStyle); 18059 18060 FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle; 18061 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = 18062 FormatStyle::SIS_OnlyFirstIf; 18063 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true; 18064 verifyFormat("void f(bool b)\n" 18065 " {\n" 18066 " if (b)\n" 18067 " {\n" 18068 " return;\n" 18069 " }\n" 18070 " }\n", 18071 BreakBeforeBraceShortIfs); 18072 verifyFormat("void f(bool b)\n" 18073 " {\n" 18074 " if (b) return;\n" 18075 " }\n", 18076 BreakBeforeBraceShortIfs); 18077 verifyFormat("void f(bool b)\n" 18078 " {\n" 18079 " while (b)\n" 18080 " {\n" 18081 " return;\n" 18082 " }\n" 18083 " }\n", 18084 BreakBeforeBraceShortIfs); 18085 } 18086 18087 TEST_F(FormatTest, GNUBraceBreaking) { 18088 FormatStyle GNUBraceStyle = getLLVMStyle(); 18089 GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU; 18090 verifyFormat("namespace a\n" 18091 "{\n" 18092 "class A\n" 18093 "{\n" 18094 " void f()\n" 18095 " {\n" 18096 " int a;\n" 18097 " {\n" 18098 " int b;\n" 18099 " }\n" 18100 " if (true)\n" 18101 " {\n" 18102 " a();\n" 18103 " b();\n" 18104 " }\n" 18105 " }\n" 18106 " void g() { return; }\n" 18107 "}\n" 18108 "} // namespace a", 18109 GNUBraceStyle); 18110 18111 verifyFormat("void f()\n" 18112 "{\n" 18113 " if (true)\n" 18114 " {\n" 18115 " a();\n" 18116 " }\n" 18117 " else if (false)\n" 18118 " {\n" 18119 " b();\n" 18120 " }\n" 18121 " else\n" 18122 " {\n" 18123 " c();\n" 18124 " }\n" 18125 "}\n", 18126 GNUBraceStyle); 18127 18128 verifyFormat("void f()\n" 18129 "{\n" 18130 " for (int i = 0; i < 10; ++i)\n" 18131 " {\n" 18132 " a();\n" 18133 " }\n" 18134 " while (false)\n" 18135 " {\n" 18136 " b();\n" 18137 " }\n" 18138 " do\n" 18139 " {\n" 18140 " c();\n" 18141 " }\n" 18142 " while (false);\n" 18143 "}\n", 18144 GNUBraceStyle); 18145 18146 verifyFormat("void f(int a)\n" 18147 "{\n" 18148 " switch (a)\n" 18149 " {\n" 18150 " case 0:\n" 18151 " break;\n" 18152 " case 1:\n" 18153 " {\n" 18154 " break;\n" 18155 " }\n" 18156 " case 2:\n" 18157 " {\n" 18158 " }\n" 18159 " break;\n" 18160 " default:\n" 18161 " break;\n" 18162 " }\n" 18163 "}\n", 18164 GNUBraceStyle); 18165 18166 verifyFormat("enum X\n" 18167 "{\n" 18168 " Y = 0,\n" 18169 "}\n", 18170 GNUBraceStyle); 18171 18172 verifyFormat("@interface BSApplicationController ()\n" 18173 "{\n" 18174 "@private\n" 18175 " id _extraIvar;\n" 18176 "}\n" 18177 "@end\n", 18178 GNUBraceStyle); 18179 18180 verifyFormat("#ifdef _DEBUG\n" 18181 "int foo(int i = 0)\n" 18182 "#else\n" 18183 "int foo(int i = 5)\n" 18184 "#endif\n" 18185 "{\n" 18186 " return i;\n" 18187 "}", 18188 GNUBraceStyle); 18189 18190 verifyFormat("void foo() {}\n" 18191 "void bar()\n" 18192 "#ifdef _DEBUG\n" 18193 "{\n" 18194 " foo();\n" 18195 "}\n" 18196 "#else\n" 18197 "{\n" 18198 "}\n" 18199 "#endif", 18200 GNUBraceStyle); 18201 18202 verifyFormat("void foobar() { int i = 5; }\n" 18203 "#ifdef _DEBUG\n" 18204 "void bar() {}\n" 18205 "#else\n" 18206 "void bar() { foobar(); }\n" 18207 "#endif", 18208 GNUBraceStyle); 18209 } 18210 18211 TEST_F(FormatTest, WebKitBraceBreaking) { 18212 FormatStyle WebKitBraceStyle = getLLVMStyle(); 18213 WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit; 18214 WebKitBraceStyle.FixNamespaceComments = false; 18215 verifyFormat("namespace a {\n" 18216 "class A {\n" 18217 " void f()\n" 18218 " {\n" 18219 " if (true) {\n" 18220 " a();\n" 18221 " b();\n" 18222 " }\n" 18223 " }\n" 18224 " void g() { return; }\n" 18225 "};\n" 18226 "enum E {\n" 18227 " A,\n" 18228 " // foo\n" 18229 " B,\n" 18230 " C\n" 18231 "};\n" 18232 "struct B {\n" 18233 " int x;\n" 18234 "};\n" 18235 "}\n", 18236 WebKitBraceStyle); 18237 verifyFormat("struct S {\n" 18238 " int Type;\n" 18239 " union {\n" 18240 " int x;\n" 18241 " double y;\n" 18242 " } Value;\n" 18243 " class C {\n" 18244 " MyFavoriteType Value;\n" 18245 " } Class;\n" 18246 "};\n", 18247 WebKitBraceStyle); 18248 } 18249 18250 TEST_F(FormatTest, CatchExceptionReferenceBinding) { 18251 verifyFormat("void f() {\n" 18252 " try {\n" 18253 " } catch (const Exception &e) {\n" 18254 " }\n" 18255 "}\n", 18256 getLLVMStyle()); 18257 } 18258 18259 TEST_F(FormatTest, CatchAlignArrayOfStructuresRightAlignment) { 18260 auto Style = getLLVMStyle(); 18261 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 18262 Style.AlignConsecutiveAssignments = 18263 FormatStyle::AlignConsecutiveStyle::ACS_Consecutive; 18264 Style.AlignConsecutiveDeclarations = 18265 FormatStyle::AlignConsecutiveStyle::ACS_Consecutive; 18266 verifyFormat("struct test demo[] = {\n" 18267 " {56, 23, \"hello\"},\n" 18268 " {-1, 93463, \"world\"},\n" 18269 " { 7, 5, \"!!\"}\n" 18270 "};\n", 18271 Style); 18272 18273 verifyFormat("struct test demo[] = {\n" 18274 " {56, 23, \"hello\"}, // first line\n" 18275 " {-1, 93463, \"world\"}, // second line\n" 18276 " { 7, 5, \"!!\"} // third line\n" 18277 "};\n", 18278 Style); 18279 18280 verifyFormat("struct test demo[4] = {\n" 18281 " { 56, 23, 21, \"oh\"}, // first line\n" 18282 " { -1, 93463, 22, \"my\"}, // second line\n" 18283 " { 7, 5, 1, \"goodness\"} // third line\n" 18284 " {234, 5, 1, \"gracious\"} // fourth line\n" 18285 "};\n", 18286 Style); 18287 18288 verifyFormat("struct test demo[3] = {\n" 18289 " {56, 23, \"hello\"},\n" 18290 " {-1, 93463, \"world\"},\n" 18291 " { 7, 5, \"!!\"}\n" 18292 "};\n", 18293 Style); 18294 18295 verifyFormat("struct test demo[3] = {\n" 18296 " {int{56}, 23, \"hello\"},\n" 18297 " {int{-1}, 93463, \"world\"},\n" 18298 " { int{7}, 5, \"!!\"}\n" 18299 "};\n", 18300 Style); 18301 18302 verifyFormat("struct test demo[] = {\n" 18303 " {56, 23, \"hello\"},\n" 18304 " {-1, 93463, \"world\"},\n" 18305 " { 7, 5, \"!!\"},\n" 18306 "};\n", 18307 Style); 18308 18309 verifyFormat("test demo[] = {\n" 18310 " {56, 23, \"hello\"},\n" 18311 " {-1, 93463, \"world\"},\n" 18312 " { 7, 5, \"!!\"},\n" 18313 "};\n", 18314 Style); 18315 18316 verifyFormat("demo = std::array<struct test, 3>{\n" 18317 " test{56, 23, \"hello\"},\n" 18318 " test{-1, 93463, \"world\"},\n" 18319 " test{ 7, 5, \"!!\"},\n" 18320 "};\n", 18321 Style); 18322 18323 verifyFormat("test demo[] = {\n" 18324 " {56, 23, \"hello\"},\n" 18325 "#if X\n" 18326 " {-1, 93463, \"world\"},\n" 18327 "#endif\n" 18328 " { 7, 5, \"!!\"}\n" 18329 "};\n", 18330 Style); 18331 18332 verifyFormat( 18333 "test demo[] = {\n" 18334 " { 7, 23,\n" 18335 " \"hello world i am a very long line that really, in any\"\n" 18336 " \"just world, ought to be split over multiple lines\"},\n" 18337 " {-1, 93463, \"world\"},\n" 18338 " {56, 5, \"!!\"}\n" 18339 "};\n", 18340 Style); 18341 18342 verifyFormat("return GradForUnaryCwise(g, {\n" 18343 " {{\"sign\"}, \"Sign\", " 18344 " {\"x\", \"dy\"}},\n" 18345 " { {\"dx\"}, \"Mul\", {\"dy\"" 18346 ", \"sign\"}},\n" 18347 "});\n", 18348 Style); 18349 18350 Style.ColumnLimit = 0; 18351 EXPECT_EQ( 18352 "test demo[] = {\n" 18353 " {56, 23, \"hello world i am a very long line that really, " 18354 "in any just world, ought to be split over multiple lines\"},\n" 18355 " {-1, 93463, " 18356 " \"world\"},\n" 18357 " { 7, 5, " 18358 " \"!!\"},\n" 18359 "};", 18360 format("test demo[] = {{56, 23, \"hello world i am a very long line " 18361 "that really, in any just world, ought to be split over multiple " 18362 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 18363 Style)); 18364 18365 Style.ColumnLimit = 80; 18366 verifyFormat("test demo[] = {\n" 18367 " {56, 23, /* a comment */ \"hello\"},\n" 18368 " {-1, 93463, \"world\"},\n" 18369 " { 7, 5, \"!!\"}\n" 18370 "};\n", 18371 Style); 18372 18373 verifyFormat("test demo[] = {\n" 18374 " {56, 23, \"hello\"},\n" 18375 " {-1, 93463, \"world\" /* comment here */},\n" 18376 " { 7, 5, \"!!\"}\n" 18377 "};\n", 18378 Style); 18379 18380 verifyFormat("test demo[] = {\n" 18381 " {56, /* a comment */ 23, \"hello\"},\n" 18382 " {-1, 93463, \"world\"},\n" 18383 " { 7, 5, \"!!\"}\n" 18384 "};\n", 18385 Style); 18386 18387 Style.ColumnLimit = 20; 18388 EXPECT_EQ( 18389 "demo = std::array<\n" 18390 " struct test, 3>{\n" 18391 " test{\n" 18392 " 56, 23,\n" 18393 " \"hello \"\n" 18394 " \"world i \"\n" 18395 " \"am a very \"\n" 18396 " \"long line \"\n" 18397 " \"that \"\n" 18398 " \"really, \"\n" 18399 " \"in any \"\n" 18400 " \"just \"\n" 18401 " \"world, \"\n" 18402 " \"ought to \"\n" 18403 " \"be split \"\n" 18404 " \"over \"\n" 18405 " \"multiple \"\n" 18406 " \"lines\"},\n" 18407 " test{-1, 93463,\n" 18408 " \"world\"},\n" 18409 " test{ 7, 5,\n" 18410 " \"!!\" },\n" 18411 "};", 18412 format("demo = std::array<struct test, 3>{test{56, 23, \"hello world " 18413 "i am a very long line that really, in any just world, ought " 18414 "to be split over multiple lines\"},test{-1, 93463, \"world\"}," 18415 "test{7, 5, \"!!\"},};", 18416 Style)); 18417 // This caused a core dump by enabling Alignment in the LLVMStyle globally 18418 Style = getLLVMStyleWithColumns(50); 18419 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 18420 verifyFormat("static A x = {\n" 18421 " {{init1, init2, init3, init4},\n" 18422 " {init1, init2, init3, init4}}\n" 18423 "};", 18424 Style); 18425 Style.ColumnLimit = 100; 18426 EXPECT_EQ( 18427 "test demo[] = {\n" 18428 " {56, 23,\n" 18429 " \"hello world i am a very long line that really, in any just world" 18430 ", ought to be split over \"\n" 18431 " \"multiple lines\" },\n" 18432 " {-1, 93463, \"world\"},\n" 18433 " { 7, 5, \"!!\"},\n" 18434 "};", 18435 format("test demo[] = {{56, 23, \"hello world i am a very long line " 18436 "that really, in any just world, ought to be split over multiple " 18437 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 18438 Style)); 18439 18440 Style = getLLVMStyleWithColumns(50); 18441 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 18442 Style.AlignConsecutiveAssignments = 18443 FormatStyle::AlignConsecutiveStyle::ACS_Consecutive; 18444 Style.AlignConsecutiveDeclarations = 18445 FormatStyle::AlignConsecutiveStyle::ACS_Consecutive; 18446 verifyFormat("struct test demo[] = {\n" 18447 " {56, 23, \"hello\"},\n" 18448 " {-1, 93463, \"world\"},\n" 18449 " { 7, 5, \"!!\"}\n" 18450 "};\n" 18451 "static A x = {\n" 18452 " {{init1, init2, init3, init4},\n" 18453 " {init1, init2, init3, init4}}\n" 18454 "};", 18455 Style); 18456 Style.ColumnLimit = 100; 18457 Style.AlignConsecutiveAssignments = 18458 FormatStyle::AlignConsecutiveStyle::ACS_AcrossComments; 18459 Style.AlignConsecutiveDeclarations = 18460 FormatStyle::AlignConsecutiveStyle::ACS_AcrossComments; 18461 verifyFormat("struct test demo[] = {\n" 18462 " {56, 23, \"hello\"},\n" 18463 " {-1, 93463, \"world\"},\n" 18464 " { 7, 5, \"!!\"}\n" 18465 "};\n" 18466 "struct test demo[4] = {\n" 18467 " { 56, 23, 21, \"oh\"}, // first line\n" 18468 " { -1, 93463, 22, \"my\"}, // second line\n" 18469 " { 7, 5, 1, \"goodness\"} // third line\n" 18470 " {234, 5, 1, \"gracious\"} // fourth line\n" 18471 "};\n", 18472 Style); 18473 EXPECT_EQ( 18474 "test demo[] = {\n" 18475 " {56,\n" 18476 " \"hello world i am a very long line that really, in any just world" 18477 ", ought to be split over \"\n" 18478 " \"multiple lines\", 23},\n" 18479 " {-1, \"world\", 93463},\n" 18480 " { 7, \"!!\", 5},\n" 18481 "};", 18482 format("test demo[] = {{56, \"hello world i am a very long line " 18483 "that really, in any just world, ought to be split over multiple " 18484 "lines\", 23},{-1, \"world\", 93463},{7, \"!!\", 5},};", 18485 Style)); 18486 } 18487 18488 TEST_F(FormatTest, CatchAlignArrayOfStructuresLeftAlignment) { 18489 auto Style = getLLVMStyle(); 18490 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 18491 /* FIXME: This case gets misformatted. 18492 verifyFormat("auto foo = Items{\n" 18493 " Section{0, bar(), },\n" 18494 " Section{1, boo() }\n" 18495 "};\n", 18496 Style); 18497 */ 18498 verifyFormat("auto foo = Items{\n" 18499 " Section{\n" 18500 " 0, bar(),\n" 18501 " }\n" 18502 "};\n", 18503 Style); 18504 verifyFormat("struct test demo[] = {\n" 18505 " {56, 23, \"hello\"},\n" 18506 " {-1, 93463, \"world\"},\n" 18507 " {7, 5, \"!!\" }\n" 18508 "};\n", 18509 Style); 18510 verifyFormat("struct test demo[] = {\n" 18511 " {56, 23, \"hello\"}, // first line\n" 18512 " {-1, 93463, \"world\"}, // second line\n" 18513 " {7, 5, \"!!\" } // third line\n" 18514 "};\n", 18515 Style); 18516 verifyFormat("struct test demo[4] = {\n" 18517 " {56, 23, 21, \"oh\" }, // first line\n" 18518 " {-1, 93463, 22, \"my\" }, // second line\n" 18519 " {7, 5, 1, \"goodness\"} // third line\n" 18520 " {234, 5, 1, \"gracious\"} // fourth line\n" 18521 "};\n", 18522 Style); 18523 verifyFormat("struct test demo[3] = {\n" 18524 " {56, 23, \"hello\"},\n" 18525 " {-1, 93463, \"world\"},\n" 18526 " {7, 5, \"!!\" }\n" 18527 "};\n", 18528 Style); 18529 18530 verifyFormat("struct test demo[3] = {\n" 18531 " {int{56}, 23, \"hello\"},\n" 18532 " {int{-1}, 93463, \"world\"},\n" 18533 " {int{7}, 5, \"!!\" }\n" 18534 "};\n", 18535 Style); 18536 verifyFormat("struct test demo[] = {\n" 18537 " {56, 23, \"hello\"},\n" 18538 " {-1, 93463, \"world\"},\n" 18539 " {7, 5, \"!!\" },\n" 18540 "};\n", 18541 Style); 18542 verifyFormat("test demo[] = {\n" 18543 " {56, 23, \"hello\"},\n" 18544 " {-1, 93463, \"world\"},\n" 18545 " {7, 5, \"!!\" },\n" 18546 "};\n", 18547 Style); 18548 verifyFormat("demo = std::array<struct test, 3>{\n" 18549 " test{56, 23, \"hello\"},\n" 18550 " test{-1, 93463, \"world\"},\n" 18551 " test{7, 5, \"!!\" },\n" 18552 "};\n", 18553 Style); 18554 verifyFormat("test demo[] = {\n" 18555 " {56, 23, \"hello\"},\n" 18556 "#if X\n" 18557 " {-1, 93463, \"world\"},\n" 18558 "#endif\n" 18559 " {7, 5, \"!!\" }\n" 18560 "};\n", 18561 Style); 18562 verifyFormat( 18563 "test demo[] = {\n" 18564 " {7, 23,\n" 18565 " \"hello world i am a very long line that really, in any\"\n" 18566 " \"just world, ought to be split over multiple lines\"},\n" 18567 " {-1, 93463, \"world\" },\n" 18568 " {56, 5, \"!!\" }\n" 18569 "};\n", 18570 Style); 18571 18572 verifyFormat("return GradForUnaryCwise(g, {\n" 18573 " {{\"sign\"}, \"Sign\", {\"x\", " 18574 "\"dy\"} },\n" 18575 " {{\"dx\"}, \"Mul\", " 18576 "{\"dy\", \"sign\"}},\n" 18577 "});\n", 18578 Style); 18579 18580 Style.ColumnLimit = 0; 18581 EXPECT_EQ( 18582 "test demo[] = {\n" 18583 " {56, 23, \"hello world i am a very long line that really, in any " 18584 "just world, ought to be split over multiple lines\"},\n" 18585 " {-1, 93463, \"world\" " 18586 " },\n" 18587 " {7, 5, \"!!\" " 18588 " },\n" 18589 "};", 18590 format("test demo[] = {{56, 23, \"hello world i am a very long line " 18591 "that really, in any just world, ought to be split over multiple " 18592 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 18593 Style)); 18594 18595 Style.ColumnLimit = 80; 18596 verifyFormat("test demo[] = {\n" 18597 " {56, 23, /* a comment */ \"hello\"},\n" 18598 " {-1, 93463, \"world\" },\n" 18599 " {7, 5, \"!!\" }\n" 18600 "};\n", 18601 Style); 18602 18603 verifyFormat("test demo[] = {\n" 18604 " {56, 23, \"hello\" },\n" 18605 " {-1, 93463, \"world\" /* comment here */},\n" 18606 " {7, 5, \"!!\" }\n" 18607 "};\n", 18608 Style); 18609 18610 verifyFormat("test demo[] = {\n" 18611 " {56, /* a comment */ 23, \"hello\"},\n" 18612 " {-1, 93463, \"world\"},\n" 18613 " {7, 5, \"!!\" }\n" 18614 "};\n", 18615 Style); 18616 18617 Style.ColumnLimit = 20; 18618 EXPECT_EQ( 18619 "demo = std::array<\n" 18620 " struct test, 3>{\n" 18621 " test{\n" 18622 " 56, 23,\n" 18623 " \"hello \"\n" 18624 " \"world i \"\n" 18625 " \"am a very \"\n" 18626 " \"long line \"\n" 18627 " \"that \"\n" 18628 " \"really, \"\n" 18629 " \"in any \"\n" 18630 " \"just \"\n" 18631 " \"world, \"\n" 18632 " \"ought to \"\n" 18633 " \"be split \"\n" 18634 " \"over \"\n" 18635 " \"multiple \"\n" 18636 " \"lines\"},\n" 18637 " test{-1, 93463,\n" 18638 " \"world\"},\n" 18639 " test{7, 5,\n" 18640 " \"!!\" },\n" 18641 "};", 18642 format("demo = std::array<struct test, 3>{test{56, 23, \"hello world " 18643 "i am a very long line that really, in any just world, ought " 18644 "to be split over multiple lines\"},test{-1, 93463, \"world\"}," 18645 "test{7, 5, \"!!\"},};", 18646 Style)); 18647 18648 // This caused a core dump by enabling Alignment in the LLVMStyle globally 18649 Style = getLLVMStyleWithColumns(50); 18650 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 18651 verifyFormat("static A x = {\n" 18652 " {{init1, init2, init3, init4},\n" 18653 " {init1, init2, init3, init4}}\n" 18654 "};", 18655 Style); 18656 Style.ColumnLimit = 100; 18657 EXPECT_EQ( 18658 "test demo[] = {\n" 18659 " {56, 23,\n" 18660 " \"hello world i am a very long line that really, in any just world" 18661 ", ought to be split over \"\n" 18662 " \"multiple lines\" },\n" 18663 " {-1, 93463, \"world\"},\n" 18664 " {7, 5, \"!!\" },\n" 18665 "};", 18666 format("test demo[] = {{56, 23, \"hello world i am a very long line " 18667 "that really, in any just world, ought to be split over multiple " 18668 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 18669 Style)); 18670 } 18671 18672 TEST_F(FormatTest, UnderstandsPragmas) { 18673 verifyFormat("#pragma omp reduction(| : var)"); 18674 verifyFormat("#pragma omp reduction(+ : var)"); 18675 18676 EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string " 18677 "(including parentheses).", 18678 format("#pragma mark Any non-hyphenated or hyphenated string " 18679 "(including parentheses).")); 18680 } 18681 18682 TEST_F(FormatTest, UnderstandPragmaOption) { 18683 verifyFormat("#pragma option -C -A"); 18684 18685 EXPECT_EQ("#pragma option -C -A", format("#pragma option -C -A")); 18686 } 18687 18688 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) { 18689 FormatStyle Style = getLLVMStyleWithColumns(20); 18690 18691 // See PR41213 18692 EXPECT_EQ("/*\n" 18693 " *\t9012345\n" 18694 " * /8901\n" 18695 " */", 18696 format("/*\n" 18697 " *\t9012345 /8901\n" 18698 " */", 18699 Style)); 18700 EXPECT_EQ("/*\n" 18701 " *345678\n" 18702 " *\t/8901\n" 18703 " */", 18704 format("/*\n" 18705 " *345678\t/8901\n" 18706 " */", 18707 Style)); 18708 18709 verifyFormat("int a; // the\n" 18710 " // comment", 18711 Style); 18712 EXPECT_EQ("int a; /* first line\n" 18713 " * second\n" 18714 " * line third\n" 18715 " * line\n" 18716 " */", 18717 format("int a; /* first line\n" 18718 " * second\n" 18719 " * line third\n" 18720 " * line\n" 18721 " */", 18722 Style)); 18723 EXPECT_EQ("int a; // first line\n" 18724 " // second\n" 18725 " // line third\n" 18726 " // line", 18727 format("int a; // first line\n" 18728 " // second line\n" 18729 " // third line", 18730 Style)); 18731 18732 Style.PenaltyExcessCharacter = 90; 18733 verifyFormat("int a; // the comment", Style); 18734 EXPECT_EQ("int a; // the comment\n" 18735 " // aaa", 18736 format("int a; // the comment aaa", Style)); 18737 EXPECT_EQ("int a; /* first line\n" 18738 " * second line\n" 18739 " * third line\n" 18740 " */", 18741 format("int a; /* first line\n" 18742 " * second line\n" 18743 " * third line\n" 18744 " */", 18745 Style)); 18746 EXPECT_EQ("int a; // first line\n" 18747 " // second line\n" 18748 " // third line", 18749 format("int a; // first line\n" 18750 " // second line\n" 18751 " // third line", 18752 Style)); 18753 // FIXME: Investigate why this is not getting the same layout as the test 18754 // above. 18755 EXPECT_EQ("int a; /* first line\n" 18756 " * second line\n" 18757 " * third line\n" 18758 " */", 18759 format("int a; /* first line second line third line" 18760 "\n*/", 18761 Style)); 18762 18763 EXPECT_EQ("// foo bar baz bazfoo\n" 18764 "// foo bar foo bar\n", 18765 format("// foo bar baz bazfoo\n" 18766 "// foo bar foo bar\n", 18767 Style)); 18768 EXPECT_EQ("// foo bar baz bazfoo\n" 18769 "// foo bar foo bar\n", 18770 format("// foo bar baz bazfoo\n" 18771 "// foo bar foo bar\n", 18772 Style)); 18773 18774 // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the 18775 // next one. 18776 EXPECT_EQ("// foo bar baz bazfoo\n" 18777 "// bar foo bar\n", 18778 format("// foo bar baz bazfoo bar\n" 18779 "// foo bar\n", 18780 Style)); 18781 18782 EXPECT_EQ("// foo bar baz bazfoo\n" 18783 "// foo bar baz bazfoo\n" 18784 "// bar foo bar\n", 18785 format("// foo bar baz bazfoo\n" 18786 "// foo bar baz bazfoo bar\n" 18787 "// foo bar\n", 18788 Style)); 18789 18790 EXPECT_EQ("// foo bar baz bazfoo\n" 18791 "// foo bar baz bazfoo\n" 18792 "// bar foo bar\n", 18793 format("// foo bar baz bazfoo\n" 18794 "// foo bar baz bazfoo bar\n" 18795 "// foo bar\n", 18796 Style)); 18797 18798 // Make sure we do not keep protruding characters if strict mode reflow is 18799 // cheaper than keeping protruding characters. 18800 Style.ColumnLimit = 21; 18801 EXPECT_EQ( 18802 "// foo foo foo foo\n" 18803 "// foo foo foo foo\n" 18804 "// foo foo foo foo\n", 18805 format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style)); 18806 18807 EXPECT_EQ("int a = /* long block\n" 18808 " comment */\n" 18809 " 42;", 18810 format("int a = /* long block comment */ 42;", Style)); 18811 } 18812 18813 TEST_F(FormatTest, BreakPenaltyAfterLParen) { 18814 FormatStyle Style = getLLVMStyle(); 18815 Style.ColumnLimit = 8; 18816 Style.PenaltyExcessCharacter = 15; 18817 verifyFormat("int foo(\n" 18818 " int aaaaaaaaaaaaaaaaaaaaaaaa);", 18819 Style); 18820 Style.PenaltyBreakOpenParenthesis = 200; 18821 EXPECT_EQ("int foo(int aaaaaaaaaaaaaaaaaaaaaaaa);", 18822 format("int foo(\n" 18823 " int aaaaaaaaaaaaaaaaaaaaaaaa);", 18824 Style)); 18825 } 18826 18827 TEST_F(FormatTest, BreakPenaltyAfterCastLParen) { 18828 FormatStyle Style = getLLVMStyle(); 18829 Style.ColumnLimit = 5; 18830 Style.PenaltyExcessCharacter = 150; 18831 verifyFormat("foo((\n" 18832 " int)aaaaaaaaaaaaaaaaaaaaaaaa);", 18833 18834 Style); 18835 Style.PenaltyBreakOpenParenthesis = 100000; 18836 EXPECT_EQ("foo((int)\n" 18837 " aaaaaaaaaaaaaaaaaaaaaaaa);", 18838 format("foo((\n" 18839 "int)aaaaaaaaaaaaaaaaaaaaaaaa);", 18840 Style)); 18841 } 18842 18843 TEST_F(FormatTest, BreakPenaltyAfterForLoopLParen) { 18844 FormatStyle Style = getLLVMStyle(); 18845 Style.ColumnLimit = 4; 18846 Style.PenaltyExcessCharacter = 100; 18847 verifyFormat("for (\n" 18848 " int iiiiiiiiiiiiiiiii =\n" 18849 " 0;\n" 18850 " iiiiiiiiiiiiiiiii <\n" 18851 " 2;\n" 18852 " iiiiiiiiiiiiiiiii++) {\n" 18853 "}", 18854 18855 Style); 18856 Style.PenaltyBreakOpenParenthesis = 1250; 18857 EXPECT_EQ("for (int iiiiiiiiiiiiiiiii =\n" 18858 " 0;\n" 18859 " iiiiiiiiiiiiiiiii <\n" 18860 " 2;\n" 18861 " iiiiiiiiiiiiiiiii++) {\n" 18862 "}", 18863 format("for (\n" 18864 " int iiiiiiiiiiiiiiiii =\n" 18865 " 0;\n" 18866 " iiiiiiiiiiiiiiiii <\n" 18867 " 2;\n" 18868 " iiiiiiiiiiiiiiiii++) {\n" 18869 "}", 18870 Style)); 18871 } 18872 18873 #define EXPECT_ALL_STYLES_EQUAL(Styles) \ 18874 for (size_t i = 1; i < Styles.size(); ++i) \ 18875 EXPECT_EQ(Styles[0], Styles[i]) \ 18876 << "Style #" << i << " of " << Styles.size() << " differs from Style #0" 18877 18878 TEST_F(FormatTest, GetsPredefinedStyleByName) { 18879 SmallVector<FormatStyle, 3> Styles; 18880 Styles.resize(3); 18881 18882 Styles[0] = getLLVMStyle(); 18883 EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1])); 18884 EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2])); 18885 EXPECT_ALL_STYLES_EQUAL(Styles); 18886 18887 Styles[0] = getGoogleStyle(); 18888 EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1])); 18889 EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2])); 18890 EXPECT_ALL_STYLES_EQUAL(Styles); 18891 18892 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript); 18893 EXPECT_TRUE( 18894 getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1])); 18895 EXPECT_TRUE( 18896 getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2])); 18897 EXPECT_ALL_STYLES_EQUAL(Styles); 18898 18899 Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp); 18900 EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1])); 18901 EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2])); 18902 EXPECT_ALL_STYLES_EQUAL(Styles); 18903 18904 Styles[0] = getMozillaStyle(); 18905 EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1])); 18906 EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2])); 18907 EXPECT_ALL_STYLES_EQUAL(Styles); 18908 18909 Styles[0] = getWebKitStyle(); 18910 EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1])); 18911 EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2])); 18912 EXPECT_ALL_STYLES_EQUAL(Styles); 18913 18914 Styles[0] = getGNUStyle(); 18915 EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1])); 18916 EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2])); 18917 EXPECT_ALL_STYLES_EQUAL(Styles); 18918 18919 EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0])); 18920 } 18921 18922 TEST_F(FormatTest, GetsCorrectBasedOnStyle) { 18923 SmallVector<FormatStyle, 8> Styles; 18924 Styles.resize(2); 18925 18926 Styles[0] = getGoogleStyle(); 18927 Styles[1] = getLLVMStyle(); 18928 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value()); 18929 EXPECT_ALL_STYLES_EQUAL(Styles); 18930 18931 Styles.resize(5); 18932 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript); 18933 Styles[1] = getLLVMStyle(); 18934 Styles[1].Language = FormatStyle::LK_JavaScript; 18935 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value()); 18936 18937 Styles[2] = getLLVMStyle(); 18938 Styles[2].Language = FormatStyle::LK_JavaScript; 18939 EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n" 18940 "BasedOnStyle: Google", 18941 &Styles[2]) 18942 .value()); 18943 18944 Styles[3] = getLLVMStyle(); 18945 Styles[3].Language = FormatStyle::LK_JavaScript; 18946 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n" 18947 "Language: JavaScript", 18948 &Styles[3]) 18949 .value()); 18950 18951 Styles[4] = getLLVMStyle(); 18952 Styles[4].Language = FormatStyle::LK_JavaScript; 18953 EXPECT_EQ(0, parseConfiguration("---\n" 18954 "BasedOnStyle: LLVM\n" 18955 "IndentWidth: 123\n" 18956 "---\n" 18957 "BasedOnStyle: Google\n" 18958 "Language: JavaScript", 18959 &Styles[4]) 18960 .value()); 18961 EXPECT_ALL_STYLES_EQUAL(Styles); 18962 } 18963 18964 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME) \ 18965 Style.FIELD = false; \ 18966 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value()); \ 18967 EXPECT_TRUE(Style.FIELD); \ 18968 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value()); \ 18969 EXPECT_FALSE(Style.FIELD); 18970 18971 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD) 18972 18973 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME) \ 18974 Style.STRUCT.FIELD = false; \ 18975 EXPECT_EQ(0, \ 18976 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": true", &Style) \ 18977 .value()); \ 18978 EXPECT_TRUE(Style.STRUCT.FIELD); \ 18979 EXPECT_EQ(0, \ 18980 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": false", &Style) \ 18981 .value()); \ 18982 EXPECT_FALSE(Style.STRUCT.FIELD); 18983 18984 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD) \ 18985 CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD) 18986 18987 #define CHECK_PARSE(TEXT, FIELD, VALUE) \ 18988 EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!"; \ 18989 EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value()); \ 18990 EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!" 18991 18992 TEST_F(FormatTest, ParsesConfigurationBools) { 18993 FormatStyle Style = {}; 18994 Style.Language = FormatStyle::LK_Cpp; 18995 CHECK_PARSE_BOOL(AlignTrailingComments); 18996 CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine); 18997 CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine); 18998 CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine); 18999 CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine); 19000 CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine); 19001 CHECK_PARSE_BOOL(BinPackArguments); 19002 CHECK_PARSE_BOOL(BinPackParameters); 19003 CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations); 19004 CHECK_PARSE_BOOL(BreakBeforeConceptDeclarations); 19005 CHECK_PARSE_BOOL(BreakBeforeTernaryOperators); 19006 CHECK_PARSE_BOOL(BreakStringLiterals); 19007 CHECK_PARSE_BOOL(CompactNamespaces); 19008 CHECK_PARSE_BOOL(DeriveLineEnding); 19009 CHECK_PARSE_BOOL(DerivePointerAlignment); 19010 CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding"); 19011 CHECK_PARSE_BOOL(DisableFormat); 19012 CHECK_PARSE_BOOL(IndentAccessModifiers); 19013 CHECK_PARSE_BOOL(IndentCaseLabels); 19014 CHECK_PARSE_BOOL(IndentCaseBlocks); 19015 CHECK_PARSE_BOOL(IndentGotoLabels); 19016 CHECK_PARSE_BOOL(IndentRequires); 19017 CHECK_PARSE_BOOL(IndentWrappedFunctionNames); 19018 CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks); 19019 CHECK_PARSE_BOOL(ObjCSpaceAfterProperty); 19020 CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList); 19021 CHECK_PARSE_BOOL(Cpp11BracedListStyle); 19022 CHECK_PARSE_BOOL(ReflowComments); 19023 CHECK_PARSE_BOOL(RemoveBracesLLVM); 19024 CHECK_PARSE_BOOL(SortUsingDeclarations); 19025 CHECK_PARSE_BOOL(SpacesInParentheses); 19026 CHECK_PARSE_BOOL(SpacesInSquareBrackets); 19027 CHECK_PARSE_BOOL(SpacesInConditionalStatement); 19028 CHECK_PARSE_BOOL(SpaceInEmptyBlock); 19029 CHECK_PARSE_BOOL(SpaceInEmptyParentheses); 19030 CHECK_PARSE_BOOL(SpacesInContainerLiterals); 19031 CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses); 19032 CHECK_PARSE_BOOL(SpaceAfterCStyleCast); 19033 CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword); 19034 CHECK_PARSE_BOOL(SpaceAfterLogicalNot); 19035 CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators); 19036 CHECK_PARSE_BOOL(SpaceBeforeCaseColon); 19037 CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList); 19038 CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon); 19039 CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon); 19040 CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon); 19041 CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets); 19042 CHECK_PARSE_BOOL(UseCRLF); 19043 19044 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel); 19045 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass); 19046 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum); 19047 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction); 19048 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace); 19049 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration); 19050 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct); 19051 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion); 19052 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock); 19053 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch); 19054 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse); 19055 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody); 19056 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile); 19057 CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces); 19058 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction); 19059 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord); 19060 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace); 19061 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterControlStatements); 19062 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterForeachMacros); 19063 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, 19064 AfterFunctionDeclarationName); 19065 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, 19066 AfterFunctionDefinitionName); 19067 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterIfMacros); 19068 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterOverloadedOperator); 19069 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, BeforeNonEmptyParentheses); 19070 } 19071 19072 #undef CHECK_PARSE_BOOL 19073 19074 TEST_F(FormatTest, ParsesConfiguration) { 19075 FormatStyle Style = {}; 19076 Style.Language = FormatStyle::LK_Cpp; 19077 CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234); 19078 CHECK_PARSE("ConstructorInitializerIndentWidth: 1234", 19079 ConstructorInitializerIndentWidth, 1234u); 19080 CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u); 19081 CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u); 19082 CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u); 19083 CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u); 19084 CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234", 19085 PenaltyBreakBeforeFirstCallParameter, 1234u); 19086 CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234", 19087 PenaltyBreakTemplateDeclaration, 1234u); 19088 CHECK_PARSE("PenaltyBreakOpenParenthesis: 1234", PenaltyBreakOpenParenthesis, 19089 1234u); 19090 CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u); 19091 CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234", 19092 PenaltyReturnTypeOnItsOwnLine, 1234u); 19093 CHECK_PARSE("SpacesBeforeTrailingComments: 1234", 19094 SpacesBeforeTrailingComments, 1234u); 19095 CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u); 19096 CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u); 19097 CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$"); 19098 19099 Style.QualifierAlignment = FormatStyle::QAS_Right; 19100 CHECK_PARSE("QualifierAlignment: Leave", QualifierAlignment, 19101 FormatStyle::QAS_Leave); 19102 CHECK_PARSE("QualifierAlignment: Right", QualifierAlignment, 19103 FormatStyle::QAS_Right); 19104 CHECK_PARSE("QualifierAlignment: Left", QualifierAlignment, 19105 FormatStyle::QAS_Left); 19106 CHECK_PARSE("QualifierAlignment: Custom", QualifierAlignment, 19107 FormatStyle::QAS_Custom); 19108 19109 Style.QualifierOrder.clear(); 19110 CHECK_PARSE("QualifierOrder: [ const, volatile, type ]", QualifierOrder, 19111 std::vector<std::string>({"const", "volatile", "type"})); 19112 Style.QualifierOrder.clear(); 19113 CHECK_PARSE("QualifierOrder: [const, type]", QualifierOrder, 19114 std::vector<std::string>({"const", "type"})); 19115 Style.QualifierOrder.clear(); 19116 CHECK_PARSE("QualifierOrder: [volatile, type]", QualifierOrder, 19117 std::vector<std::string>({"volatile", "type"})); 19118 19119 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 19120 CHECK_PARSE("AlignConsecutiveAssignments: None", AlignConsecutiveAssignments, 19121 FormatStyle::ACS_None); 19122 CHECK_PARSE("AlignConsecutiveAssignments: Consecutive", 19123 AlignConsecutiveAssignments, FormatStyle::ACS_Consecutive); 19124 CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLines", 19125 AlignConsecutiveAssignments, FormatStyle::ACS_AcrossEmptyLines); 19126 CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLinesAndComments", 19127 AlignConsecutiveAssignments, 19128 FormatStyle::ACS_AcrossEmptyLinesAndComments); 19129 // For backwards compability, false / true should still parse 19130 CHECK_PARSE("AlignConsecutiveAssignments: false", AlignConsecutiveAssignments, 19131 FormatStyle::ACS_None); 19132 CHECK_PARSE("AlignConsecutiveAssignments: true", AlignConsecutiveAssignments, 19133 FormatStyle::ACS_Consecutive); 19134 19135 Style.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive; 19136 CHECK_PARSE("AlignConsecutiveBitFields: None", AlignConsecutiveBitFields, 19137 FormatStyle::ACS_None); 19138 CHECK_PARSE("AlignConsecutiveBitFields: Consecutive", 19139 AlignConsecutiveBitFields, FormatStyle::ACS_Consecutive); 19140 CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLines", 19141 AlignConsecutiveBitFields, FormatStyle::ACS_AcrossEmptyLines); 19142 CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLinesAndComments", 19143 AlignConsecutiveBitFields, 19144 FormatStyle::ACS_AcrossEmptyLinesAndComments); 19145 // For backwards compability, false / true should still parse 19146 CHECK_PARSE("AlignConsecutiveBitFields: false", AlignConsecutiveBitFields, 19147 FormatStyle::ACS_None); 19148 CHECK_PARSE("AlignConsecutiveBitFields: true", AlignConsecutiveBitFields, 19149 FormatStyle::ACS_Consecutive); 19150 19151 Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 19152 CHECK_PARSE("AlignConsecutiveMacros: None", AlignConsecutiveMacros, 19153 FormatStyle::ACS_None); 19154 CHECK_PARSE("AlignConsecutiveMacros: Consecutive", AlignConsecutiveMacros, 19155 FormatStyle::ACS_Consecutive); 19156 CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLines", 19157 AlignConsecutiveMacros, FormatStyle::ACS_AcrossEmptyLines); 19158 CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLinesAndComments", 19159 AlignConsecutiveMacros, 19160 FormatStyle::ACS_AcrossEmptyLinesAndComments); 19161 // For backwards compability, false / true should still parse 19162 CHECK_PARSE("AlignConsecutiveMacros: false", AlignConsecutiveMacros, 19163 FormatStyle::ACS_None); 19164 CHECK_PARSE("AlignConsecutiveMacros: true", AlignConsecutiveMacros, 19165 FormatStyle::ACS_Consecutive); 19166 19167 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 19168 CHECK_PARSE("AlignConsecutiveDeclarations: None", 19169 AlignConsecutiveDeclarations, FormatStyle::ACS_None); 19170 CHECK_PARSE("AlignConsecutiveDeclarations: Consecutive", 19171 AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive); 19172 CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLines", 19173 AlignConsecutiveDeclarations, FormatStyle::ACS_AcrossEmptyLines); 19174 CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLinesAndComments", 19175 AlignConsecutiveDeclarations, 19176 FormatStyle::ACS_AcrossEmptyLinesAndComments); 19177 // For backwards compability, false / true should still parse 19178 CHECK_PARSE("AlignConsecutiveDeclarations: false", 19179 AlignConsecutiveDeclarations, FormatStyle::ACS_None); 19180 CHECK_PARSE("AlignConsecutiveDeclarations: true", 19181 AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive); 19182 19183 Style.PointerAlignment = FormatStyle::PAS_Middle; 19184 CHECK_PARSE("PointerAlignment: Left", PointerAlignment, 19185 FormatStyle::PAS_Left); 19186 CHECK_PARSE("PointerAlignment: Right", PointerAlignment, 19187 FormatStyle::PAS_Right); 19188 CHECK_PARSE("PointerAlignment: Middle", PointerAlignment, 19189 FormatStyle::PAS_Middle); 19190 Style.ReferenceAlignment = FormatStyle::RAS_Middle; 19191 CHECK_PARSE("ReferenceAlignment: Pointer", ReferenceAlignment, 19192 FormatStyle::RAS_Pointer); 19193 CHECK_PARSE("ReferenceAlignment: Left", ReferenceAlignment, 19194 FormatStyle::RAS_Left); 19195 CHECK_PARSE("ReferenceAlignment: Right", ReferenceAlignment, 19196 FormatStyle::RAS_Right); 19197 CHECK_PARSE("ReferenceAlignment: Middle", ReferenceAlignment, 19198 FormatStyle::RAS_Middle); 19199 // For backward compatibility: 19200 CHECK_PARSE("PointerBindsToType: Left", PointerAlignment, 19201 FormatStyle::PAS_Left); 19202 CHECK_PARSE("PointerBindsToType: Right", PointerAlignment, 19203 FormatStyle::PAS_Right); 19204 CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment, 19205 FormatStyle::PAS_Middle); 19206 19207 Style.Standard = FormatStyle::LS_Auto; 19208 CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03); 19209 CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11); 19210 CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14); 19211 CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17); 19212 CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20); 19213 CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto); 19214 CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest); 19215 // Legacy aliases: 19216 CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03); 19217 CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest); 19218 CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03); 19219 CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11); 19220 19221 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 19222 CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment", 19223 BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment); 19224 CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators, 19225 FormatStyle::BOS_None); 19226 CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators, 19227 FormatStyle::BOS_All); 19228 // For backward compatibility: 19229 CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators, 19230 FormatStyle::BOS_None); 19231 CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators, 19232 FormatStyle::BOS_All); 19233 19234 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 19235 CHECK_PARSE("BreakConstructorInitializers: BeforeComma", 19236 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma); 19237 CHECK_PARSE("BreakConstructorInitializers: AfterColon", 19238 BreakConstructorInitializers, FormatStyle::BCIS_AfterColon); 19239 CHECK_PARSE("BreakConstructorInitializers: BeforeColon", 19240 BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon); 19241 // For backward compatibility: 19242 CHECK_PARSE("BreakConstructorInitializersBeforeComma: true", 19243 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma); 19244 19245 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 19246 CHECK_PARSE("BreakInheritanceList: AfterComma", BreakInheritanceList, 19247 FormatStyle::BILS_AfterComma); 19248 CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList, 19249 FormatStyle::BILS_BeforeComma); 19250 CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList, 19251 FormatStyle::BILS_AfterColon); 19252 CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList, 19253 FormatStyle::BILS_BeforeColon); 19254 // For backward compatibility: 19255 CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList, 19256 FormatStyle::BILS_BeforeComma); 19257 19258 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 19259 CHECK_PARSE("PackConstructorInitializers: Never", PackConstructorInitializers, 19260 FormatStyle::PCIS_Never); 19261 CHECK_PARSE("PackConstructorInitializers: BinPack", 19262 PackConstructorInitializers, FormatStyle::PCIS_BinPack); 19263 CHECK_PARSE("PackConstructorInitializers: CurrentLine", 19264 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 19265 CHECK_PARSE("PackConstructorInitializers: NextLine", 19266 PackConstructorInitializers, FormatStyle::PCIS_NextLine); 19267 // For backward compatibility: 19268 CHECK_PARSE("BasedOnStyle: Google\n" 19269 "ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 19270 "AllowAllConstructorInitializersOnNextLine: false", 19271 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 19272 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 19273 CHECK_PARSE("BasedOnStyle: Google\n" 19274 "ConstructorInitializerAllOnOneLineOrOnePerLine: false", 19275 PackConstructorInitializers, FormatStyle::PCIS_BinPack); 19276 CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 19277 "AllowAllConstructorInitializersOnNextLine: true", 19278 PackConstructorInitializers, FormatStyle::PCIS_NextLine); 19279 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 19280 CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 19281 "AllowAllConstructorInitializersOnNextLine: false", 19282 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 19283 19284 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 19285 CHECK_PARSE("EmptyLineBeforeAccessModifier: Never", 19286 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never); 19287 CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave", 19288 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave); 19289 CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock", 19290 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock); 19291 CHECK_PARSE("EmptyLineBeforeAccessModifier: Always", 19292 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always); 19293 19294 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 19295 CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket, 19296 FormatStyle::BAS_Align); 19297 CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket, 19298 FormatStyle::BAS_DontAlign); 19299 CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket, 19300 FormatStyle::BAS_AlwaysBreak); 19301 CHECK_PARSE("AlignAfterOpenBracket: BlockIndent", AlignAfterOpenBracket, 19302 FormatStyle::BAS_BlockIndent); 19303 // For backward compatibility: 19304 CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket, 19305 FormatStyle::BAS_DontAlign); 19306 CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket, 19307 FormatStyle::BAS_Align); 19308 19309 Style.AlignEscapedNewlines = FormatStyle::ENAS_Left; 19310 CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines, 19311 FormatStyle::ENAS_DontAlign); 19312 CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines, 19313 FormatStyle::ENAS_Left); 19314 CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines, 19315 FormatStyle::ENAS_Right); 19316 // For backward compatibility: 19317 CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines, 19318 FormatStyle::ENAS_Left); 19319 CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines, 19320 FormatStyle::ENAS_Right); 19321 19322 Style.AlignOperands = FormatStyle::OAS_Align; 19323 CHECK_PARSE("AlignOperands: DontAlign", AlignOperands, 19324 FormatStyle::OAS_DontAlign); 19325 CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align); 19326 CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands, 19327 FormatStyle::OAS_AlignAfterOperator); 19328 // For backward compatibility: 19329 CHECK_PARSE("AlignOperands: false", AlignOperands, 19330 FormatStyle::OAS_DontAlign); 19331 CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align); 19332 19333 Style.UseTab = FormatStyle::UT_ForIndentation; 19334 CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never); 19335 CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation); 19336 CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always); 19337 CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab, 19338 FormatStyle::UT_ForContinuationAndIndentation); 19339 CHECK_PARSE("UseTab: AlignWithSpaces", UseTab, 19340 FormatStyle::UT_AlignWithSpaces); 19341 // For backward compatibility: 19342 CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never); 19343 CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always); 19344 19345 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 19346 CHECK_PARSE("AllowShortBlocksOnASingleLine: Never", 19347 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 19348 CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty", 19349 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty); 19350 CHECK_PARSE("AllowShortBlocksOnASingleLine: Always", 19351 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always); 19352 // For backward compatibility: 19353 CHECK_PARSE("AllowShortBlocksOnASingleLine: false", 19354 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 19355 CHECK_PARSE("AllowShortBlocksOnASingleLine: true", 19356 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always); 19357 19358 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 19359 CHECK_PARSE("AllowShortFunctionsOnASingleLine: None", 19360 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None); 19361 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline", 19362 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline); 19363 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty", 19364 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty); 19365 CHECK_PARSE("AllowShortFunctionsOnASingleLine: All", 19366 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All); 19367 // For backward compatibility: 19368 CHECK_PARSE("AllowShortFunctionsOnASingleLine: false", 19369 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None); 19370 CHECK_PARSE("AllowShortFunctionsOnASingleLine: true", 19371 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All); 19372 19373 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both; 19374 CHECK_PARSE("SpaceAroundPointerQualifiers: Default", 19375 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default); 19376 CHECK_PARSE("SpaceAroundPointerQualifiers: Before", 19377 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before); 19378 CHECK_PARSE("SpaceAroundPointerQualifiers: After", 19379 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After); 19380 CHECK_PARSE("SpaceAroundPointerQualifiers: Both", 19381 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both); 19382 19383 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 19384 CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens, 19385 FormatStyle::SBPO_Never); 19386 CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens, 19387 FormatStyle::SBPO_Always); 19388 CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens, 19389 FormatStyle::SBPO_ControlStatements); 19390 CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptControlMacros", 19391 SpaceBeforeParens, 19392 FormatStyle::SBPO_ControlStatementsExceptControlMacros); 19393 CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens, 19394 FormatStyle::SBPO_NonEmptyParentheses); 19395 CHECK_PARSE("SpaceBeforeParens: Custom", SpaceBeforeParens, 19396 FormatStyle::SBPO_Custom); 19397 // For backward compatibility: 19398 CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens, 19399 FormatStyle::SBPO_Never); 19400 CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens, 19401 FormatStyle::SBPO_ControlStatements); 19402 CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptForEachMacros", 19403 SpaceBeforeParens, 19404 FormatStyle::SBPO_ControlStatementsExceptControlMacros); 19405 19406 Style.ColumnLimit = 123; 19407 FormatStyle BaseStyle = getLLVMStyle(); 19408 CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit); 19409 CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u); 19410 19411 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 19412 CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces, 19413 FormatStyle::BS_Attach); 19414 CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces, 19415 FormatStyle::BS_Linux); 19416 CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces, 19417 FormatStyle::BS_Mozilla); 19418 CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces, 19419 FormatStyle::BS_Stroustrup); 19420 CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces, 19421 FormatStyle::BS_Allman); 19422 CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces, 19423 FormatStyle::BS_Whitesmiths); 19424 CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU); 19425 CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces, 19426 FormatStyle::BS_WebKit); 19427 CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces, 19428 FormatStyle::BS_Custom); 19429 19430 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never; 19431 CHECK_PARSE("BraceWrapping:\n" 19432 " AfterControlStatement: MultiLine", 19433 BraceWrapping.AfterControlStatement, 19434 FormatStyle::BWACS_MultiLine); 19435 CHECK_PARSE("BraceWrapping:\n" 19436 " AfterControlStatement: Always", 19437 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always); 19438 CHECK_PARSE("BraceWrapping:\n" 19439 " AfterControlStatement: Never", 19440 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never); 19441 // For backward compatibility: 19442 CHECK_PARSE("BraceWrapping:\n" 19443 " AfterControlStatement: true", 19444 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always); 19445 CHECK_PARSE("BraceWrapping:\n" 19446 " AfterControlStatement: false", 19447 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never); 19448 19449 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 19450 CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType, 19451 FormatStyle::RTBS_None); 19452 CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType, 19453 FormatStyle::RTBS_All); 19454 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel", 19455 AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel); 19456 CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions", 19457 AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions); 19458 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions", 19459 AlwaysBreakAfterReturnType, 19460 FormatStyle::RTBS_TopLevelDefinitions); 19461 19462 Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 19463 CHECK_PARSE("AlwaysBreakTemplateDeclarations: No", 19464 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No); 19465 CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine", 19466 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine); 19467 CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes", 19468 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes); 19469 CHECK_PARSE("AlwaysBreakTemplateDeclarations: false", 19470 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine); 19471 CHECK_PARSE("AlwaysBreakTemplateDeclarations: true", 19472 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes); 19473 19474 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All; 19475 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None", 19476 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None); 19477 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All", 19478 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All); 19479 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel", 19480 AlwaysBreakAfterDefinitionReturnType, 19481 FormatStyle::DRTBS_TopLevel); 19482 19483 Style.NamespaceIndentation = FormatStyle::NI_All; 19484 CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation, 19485 FormatStyle::NI_None); 19486 CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation, 19487 FormatStyle::NI_Inner); 19488 CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation, 19489 FormatStyle::NI_All); 19490 19491 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_OnlyFirstIf; 19492 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never", 19493 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never); 19494 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse", 19495 AllowShortIfStatementsOnASingleLine, 19496 FormatStyle::SIS_WithoutElse); 19497 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: OnlyFirstIf", 19498 AllowShortIfStatementsOnASingleLine, 19499 FormatStyle::SIS_OnlyFirstIf); 19500 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: AllIfsAndElse", 19501 AllowShortIfStatementsOnASingleLine, 19502 FormatStyle::SIS_AllIfsAndElse); 19503 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always", 19504 AllowShortIfStatementsOnASingleLine, 19505 FormatStyle::SIS_OnlyFirstIf); 19506 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false", 19507 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never); 19508 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true", 19509 AllowShortIfStatementsOnASingleLine, 19510 FormatStyle::SIS_WithoutElse); 19511 19512 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 19513 CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock, 19514 FormatStyle::IEBS_AfterExternBlock); 19515 CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock, 19516 FormatStyle::IEBS_Indent); 19517 CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock, 19518 FormatStyle::IEBS_NoIndent); 19519 CHECK_PARSE("IndentExternBlock: true", IndentExternBlock, 19520 FormatStyle::IEBS_Indent); 19521 CHECK_PARSE("IndentExternBlock: false", IndentExternBlock, 19522 FormatStyle::IEBS_NoIndent); 19523 19524 Style.BitFieldColonSpacing = FormatStyle::BFCS_None; 19525 CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing, 19526 FormatStyle::BFCS_Both); 19527 CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing, 19528 FormatStyle::BFCS_None); 19529 CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing, 19530 FormatStyle::BFCS_Before); 19531 CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing, 19532 FormatStyle::BFCS_After); 19533 19534 Style.SortJavaStaticImport = FormatStyle::SJSIO_Before; 19535 CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport, 19536 FormatStyle::SJSIO_After); 19537 CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport, 19538 FormatStyle::SJSIO_Before); 19539 19540 // FIXME: This is required because parsing a configuration simply overwrites 19541 // the first N elements of the list instead of resetting it. 19542 Style.ForEachMacros.clear(); 19543 std::vector<std::string> BoostForeach; 19544 BoostForeach.push_back("BOOST_FOREACH"); 19545 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach); 19546 std::vector<std::string> BoostAndQForeach; 19547 BoostAndQForeach.push_back("BOOST_FOREACH"); 19548 BoostAndQForeach.push_back("Q_FOREACH"); 19549 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros, 19550 BoostAndQForeach); 19551 19552 Style.IfMacros.clear(); 19553 std::vector<std::string> CustomIfs; 19554 CustomIfs.push_back("MYIF"); 19555 CHECK_PARSE("IfMacros: [MYIF]", IfMacros, CustomIfs); 19556 19557 Style.AttributeMacros.clear(); 19558 CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros, 19559 std::vector<std::string>{"__capability"}); 19560 CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros, 19561 std::vector<std::string>({"attr1", "attr2"})); 19562 19563 Style.StatementAttributeLikeMacros.clear(); 19564 CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]", 19565 StatementAttributeLikeMacros, 19566 std::vector<std::string>({"emit", "Q_EMIT"})); 19567 19568 Style.StatementMacros.clear(); 19569 CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros, 19570 std::vector<std::string>{"QUNUSED"}); 19571 CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros, 19572 std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"})); 19573 19574 Style.NamespaceMacros.clear(); 19575 CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros, 19576 std::vector<std::string>{"TESTSUITE"}); 19577 CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros, 19578 std::vector<std::string>({"TESTSUITE", "SUITE"})); 19579 19580 Style.WhitespaceSensitiveMacros.clear(); 19581 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]", 19582 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"}); 19583 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]", 19584 WhitespaceSensitiveMacros, 19585 std::vector<std::string>({"STRINGIZE", "ASSERT"})); 19586 Style.WhitespaceSensitiveMacros.clear(); 19587 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']", 19588 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"}); 19589 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']", 19590 WhitespaceSensitiveMacros, 19591 std::vector<std::string>({"STRINGIZE", "ASSERT"})); 19592 19593 Style.IncludeStyle.IncludeCategories.clear(); 19594 std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = { 19595 {"abc/.*", 2, 0, false}, {".*", 1, 0, true}}; 19596 CHECK_PARSE("IncludeCategories:\n" 19597 " - Regex: abc/.*\n" 19598 " Priority: 2\n" 19599 " - Regex: .*\n" 19600 " Priority: 1\n" 19601 " CaseSensitive: true\n", 19602 IncludeStyle.IncludeCategories, ExpectedCategories); 19603 CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex, 19604 "abc$"); 19605 CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'", 19606 IncludeStyle.IncludeIsMainSourceRegex, "abc$"); 19607 19608 Style.SortIncludes = FormatStyle::SI_Never; 19609 CHECK_PARSE("SortIncludes: true", SortIncludes, 19610 FormatStyle::SI_CaseSensitive); 19611 CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never); 19612 CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes, 19613 FormatStyle::SI_CaseInsensitive); 19614 CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes, 19615 FormatStyle::SI_CaseSensitive); 19616 CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never); 19617 19618 Style.RawStringFormats.clear(); 19619 std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = { 19620 { 19621 FormatStyle::LK_TextProto, 19622 {"pb", "proto"}, 19623 {"PARSE_TEXT_PROTO"}, 19624 /*CanonicalDelimiter=*/"", 19625 "llvm", 19626 }, 19627 { 19628 FormatStyle::LK_Cpp, 19629 {"cc", "cpp"}, 19630 {"C_CODEBLOCK", "CPPEVAL"}, 19631 /*CanonicalDelimiter=*/"cc", 19632 /*BasedOnStyle=*/"", 19633 }, 19634 }; 19635 19636 CHECK_PARSE("RawStringFormats:\n" 19637 " - Language: TextProto\n" 19638 " Delimiters:\n" 19639 " - 'pb'\n" 19640 " - 'proto'\n" 19641 " EnclosingFunctions:\n" 19642 " - 'PARSE_TEXT_PROTO'\n" 19643 " BasedOnStyle: llvm\n" 19644 " - Language: Cpp\n" 19645 " Delimiters:\n" 19646 " - 'cc'\n" 19647 " - 'cpp'\n" 19648 " EnclosingFunctions:\n" 19649 " - 'C_CODEBLOCK'\n" 19650 " - 'CPPEVAL'\n" 19651 " CanonicalDelimiter: 'cc'", 19652 RawStringFormats, ExpectedRawStringFormats); 19653 19654 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 19655 " Minimum: 0\n" 19656 " Maximum: 0", 19657 SpacesInLineCommentPrefix.Minimum, 0u); 19658 EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u); 19659 Style.SpacesInLineCommentPrefix.Minimum = 1; 19660 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 19661 " Minimum: 2", 19662 SpacesInLineCommentPrefix.Minimum, 0u); 19663 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 19664 " Maximum: -1", 19665 SpacesInLineCommentPrefix.Maximum, -1u); 19666 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 19667 " Minimum: 2", 19668 SpacesInLineCommentPrefix.Minimum, 2u); 19669 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 19670 " Maximum: 1", 19671 SpacesInLineCommentPrefix.Maximum, 1u); 19672 EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u); 19673 19674 Style.SpacesInAngles = FormatStyle::SIAS_Always; 19675 CHECK_PARSE("SpacesInAngles: Never", SpacesInAngles, FormatStyle::SIAS_Never); 19676 CHECK_PARSE("SpacesInAngles: Always", SpacesInAngles, 19677 FormatStyle::SIAS_Always); 19678 CHECK_PARSE("SpacesInAngles: Leave", SpacesInAngles, FormatStyle::SIAS_Leave); 19679 // For backward compatibility: 19680 CHECK_PARSE("SpacesInAngles: false", SpacesInAngles, FormatStyle::SIAS_Never); 19681 CHECK_PARSE("SpacesInAngles: true", SpacesInAngles, FormatStyle::SIAS_Always); 19682 } 19683 19684 TEST_F(FormatTest, ParsesConfigurationWithLanguages) { 19685 FormatStyle Style = {}; 19686 Style.Language = FormatStyle::LK_Cpp; 19687 CHECK_PARSE("Language: Cpp\n" 19688 "IndentWidth: 12", 19689 IndentWidth, 12u); 19690 EXPECT_EQ(parseConfiguration("Language: JavaScript\n" 19691 "IndentWidth: 34", 19692 &Style), 19693 ParseError::Unsuitable); 19694 FormatStyle BinPackedTCS = {}; 19695 BinPackedTCS.Language = FormatStyle::LK_JavaScript; 19696 EXPECT_EQ(parseConfiguration("BinPackArguments: true\n" 19697 "InsertTrailingCommas: Wrapped", 19698 &BinPackedTCS), 19699 ParseError::BinPackTrailingCommaConflict); 19700 EXPECT_EQ(12u, Style.IndentWidth); 19701 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u); 19702 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language); 19703 19704 Style.Language = FormatStyle::LK_JavaScript; 19705 CHECK_PARSE("Language: JavaScript\n" 19706 "IndentWidth: 12", 19707 IndentWidth, 12u); 19708 CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u); 19709 EXPECT_EQ(parseConfiguration("Language: Cpp\n" 19710 "IndentWidth: 34", 19711 &Style), 19712 ParseError::Unsuitable); 19713 EXPECT_EQ(23u, Style.IndentWidth); 19714 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u); 19715 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language); 19716 19717 CHECK_PARSE("BasedOnStyle: LLVM\n" 19718 "IndentWidth: 67", 19719 IndentWidth, 67u); 19720 19721 CHECK_PARSE("---\n" 19722 "Language: JavaScript\n" 19723 "IndentWidth: 12\n" 19724 "---\n" 19725 "Language: Cpp\n" 19726 "IndentWidth: 34\n" 19727 "...\n", 19728 IndentWidth, 12u); 19729 19730 Style.Language = FormatStyle::LK_Cpp; 19731 CHECK_PARSE("---\n" 19732 "Language: JavaScript\n" 19733 "IndentWidth: 12\n" 19734 "---\n" 19735 "Language: Cpp\n" 19736 "IndentWidth: 34\n" 19737 "...\n", 19738 IndentWidth, 34u); 19739 CHECK_PARSE("---\n" 19740 "IndentWidth: 78\n" 19741 "---\n" 19742 "Language: JavaScript\n" 19743 "IndentWidth: 56\n" 19744 "...\n", 19745 IndentWidth, 78u); 19746 19747 Style.ColumnLimit = 123; 19748 Style.IndentWidth = 234; 19749 Style.BreakBeforeBraces = FormatStyle::BS_Linux; 19750 Style.TabWidth = 345; 19751 EXPECT_FALSE(parseConfiguration("---\n" 19752 "IndentWidth: 456\n" 19753 "BreakBeforeBraces: Allman\n" 19754 "---\n" 19755 "Language: JavaScript\n" 19756 "IndentWidth: 111\n" 19757 "TabWidth: 111\n" 19758 "---\n" 19759 "Language: Cpp\n" 19760 "BreakBeforeBraces: Stroustrup\n" 19761 "TabWidth: 789\n" 19762 "...\n", 19763 &Style)); 19764 EXPECT_EQ(123u, Style.ColumnLimit); 19765 EXPECT_EQ(456u, Style.IndentWidth); 19766 EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces); 19767 EXPECT_EQ(789u, Style.TabWidth); 19768 19769 EXPECT_EQ(parseConfiguration("---\n" 19770 "Language: JavaScript\n" 19771 "IndentWidth: 56\n" 19772 "---\n" 19773 "IndentWidth: 78\n" 19774 "...\n", 19775 &Style), 19776 ParseError::Error); 19777 EXPECT_EQ(parseConfiguration("---\n" 19778 "Language: JavaScript\n" 19779 "IndentWidth: 56\n" 19780 "---\n" 19781 "Language: JavaScript\n" 19782 "IndentWidth: 78\n" 19783 "...\n", 19784 &Style), 19785 ParseError::Error); 19786 19787 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language); 19788 } 19789 19790 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) { 19791 FormatStyle Style = {}; 19792 Style.Language = FormatStyle::LK_JavaScript; 19793 Style.BreakBeforeTernaryOperators = true; 19794 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value()); 19795 EXPECT_FALSE(Style.BreakBeforeTernaryOperators); 19796 19797 Style.BreakBeforeTernaryOperators = true; 19798 EXPECT_EQ(0, parseConfiguration("---\n" 19799 "BasedOnStyle: Google\n" 19800 "---\n" 19801 "Language: JavaScript\n" 19802 "IndentWidth: 76\n" 19803 "...\n", 19804 &Style) 19805 .value()); 19806 EXPECT_FALSE(Style.BreakBeforeTernaryOperators); 19807 EXPECT_EQ(76u, Style.IndentWidth); 19808 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language); 19809 } 19810 19811 TEST_F(FormatTest, ConfigurationRoundTripTest) { 19812 FormatStyle Style = getLLVMStyle(); 19813 std::string YAML = configurationAsText(Style); 19814 FormatStyle ParsedStyle = {}; 19815 ParsedStyle.Language = FormatStyle::LK_Cpp; 19816 EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value()); 19817 EXPECT_EQ(Style, ParsedStyle); 19818 } 19819 19820 TEST_F(FormatTest, WorksFor8bitEncodings) { 19821 EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n" 19822 "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n" 19823 "\"\xe7\xe8\xec\xed\xfe\xfe \"\n" 19824 "\"\xef\xee\xf0\xf3...\"", 19825 format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 " 19826 "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe " 19827 "\xef\xee\xf0\xf3...\"", 19828 getLLVMStyleWithColumns(12))); 19829 } 19830 19831 TEST_F(FormatTest, HandlesUTF8BOM) { 19832 EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf")); 19833 EXPECT_EQ("\xef\xbb\xbf#include <iostream>", 19834 format("\xef\xbb\xbf#include <iostream>")); 19835 EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>", 19836 format("\xef\xbb\xbf\n#include <iostream>")); 19837 } 19838 19839 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers. 19840 #if !defined(_MSC_VER) 19841 19842 TEST_F(FormatTest, CountsUTF8CharactersProperly) { 19843 verifyFormat("\"Однажды в студёную зимнюю пору...\"", 19844 getLLVMStyleWithColumns(35)); 19845 verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"", 19846 getLLVMStyleWithColumns(31)); 19847 verifyFormat("// Однажды в студёную зимнюю пору...", 19848 getLLVMStyleWithColumns(36)); 19849 verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32)); 19850 verifyFormat("/* Однажды в студёную зимнюю пору... */", 19851 getLLVMStyleWithColumns(39)); 19852 verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */", 19853 getLLVMStyleWithColumns(35)); 19854 } 19855 19856 TEST_F(FormatTest, SplitsUTF8Strings) { 19857 // Non-printable characters' width is currently considered to be the length in 19858 // bytes in UTF8. The characters can be displayed in very different manner 19859 // (zero-width, single width with a substitution glyph, expanded to their code 19860 // (e.g. "<8d>"), so there's no single correct way to handle them. 19861 EXPECT_EQ("\"aaaaÄ\"\n" 19862 "\"\xc2\x8d\";", 19863 format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10))); 19864 EXPECT_EQ("\"aaaaaaaÄ\"\n" 19865 "\"\xc2\x8d\";", 19866 format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10))); 19867 EXPECT_EQ("\"Однажды, в \"\n" 19868 "\"студёную \"\n" 19869 "\"зимнюю \"\n" 19870 "\"пору,\"", 19871 format("\"Однажды, в студёную зимнюю пору,\"", 19872 getLLVMStyleWithColumns(13))); 19873 EXPECT_EQ( 19874 "\"一 二 三 \"\n" 19875 "\"四 五六 \"\n" 19876 "\"七 八 九 \"\n" 19877 "\"十\"", 19878 format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11))); 19879 EXPECT_EQ("\"一\t\"\n" 19880 "\"二 \t\"\n" 19881 "\"三 四 \"\n" 19882 "\"五\t\"\n" 19883 "\"六 \t\"\n" 19884 "\"七 \"\n" 19885 "\"八九十\tqq\"", 19886 format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"", 19887 getLLVMStyleWithColumns(11))); 19888 19889 // UTF8 character in an escape sequence. 19890 EXPECT_EQ("\"aaaaaa\"\n" 19891 "\"\\\xC2\x8D\"", 19892 format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10))); 19893 } 19894 19895 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) { 19896 EXPECT_EQ("const char *sssss =\n" 19897 " \"一二三四五六七八\\\n" 19898 " 九 十\";", 19899 format("const char *sssss = \"一二三四五六七八\\\n" 19900 " 九 十\";", 19901 getLLVMStyleWithColumns(30))); 19902 } 19903 19904 TEST_F(FormatTest, SplitsUTF8LineComments) { 19905 EXPECT_EQ("// aaaaÄ\xc2\x8d", 19906 format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10))); 19907 EXPECT_EQ("// Я из лесу\n" 19908 "// вышел; был\n" 19909 "// сильный\n" 19910 "// мороз.", 19911 format("// Я из лесу вышел; был сильный мороз.", 19912 getLLVMStyleWithColumns(13))); 19913 EXPECT_EQ("// 一二三\n" 19914 "// 四五六七\n" 19915 "// 八 九\n" 19916 "// 十", 19917 format("// 一二三 四五六七 八 九 十", getLLVMStyleWithColumns(9))); 19918 } 19919 19920 TEST_F(FormatTest, SplitsUTF8BlockComments) { 19921 EXPECT_EQ("/* Гляжу,\n" 19922 " * поднимается\n" 19923 " * медленно в\n" 19924 " * гору\n" 19925 " * Лошадка,\n" 19926 " * везущая\n" 19927 " * хворосту\n" 19928 " * воз. */", 19929 format("/* Гляжу, поднимается медленно в гору\n" 19930 " * Лошадка, везущая хворосту воз. */", 19931 getLLVMStyleWithColumns(13))); 19932 EXPECT_EQ( 19933 "/* 一二三\n" 19934 " * 四五六七\n" 19935 " * 八 九\n" 19936 " * 十 */", 19937 format("/* 一二三 四五六七 八 九 十 */", getLLVMStyleWithColumns(9))); 19938 EXPECT_EQ("/* \n" 19939 " * \n" 19940 " * - */", 19941 format("/* - */", getLLVMStyleWithColumns(12))); 19942 } 19943 19944 #endif // _MSC_VER 19945 19946 TEST_F(FormatTest, ConstructorInitializerIndentWidth) { 19947 FormatStyle Style = getLLVMStyle(); 19948 19949 Style.ConstructorInitializerIndentWidth = 4; 19950 verifyFormat( 19951 "SomeClass::Constructor()\n" 19952 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 19953 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 19954 Style); 19955 19956 Style.ConstructorInitializerIndentWidth = 2; 19957 verifyFormat( 19958 "SomeClass::Constructor()\n" 19959 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 19960 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 19961 Style); 19962 19963 Style.ConstructorInitializerIndentWidth = 0; 19964 verifyFormat( 19965 "SomeClass::Constructor()\n" 19966 ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 19967 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 19968 Style); 19969 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 19970 verifyFormat( 19971 "SomeLongTemplateVariableName<\n" 19972 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>", 19973 Style); 19974 verifyFormat("bool smaller = 1 < " 19975 "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 19976 " " 19977 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 19978 Style); 19979 19980 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 19981 verifyFormat("SomeClass::Constructor() :\n" 19982 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n" 19983 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}", 19984 Style); 19985 } 19986 19987 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) { 19988 FormatStyle Style = getLLVMStyle(); 19989 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 19990 Style.ConstructorInitializerIndentWidth = 4; 19991 verifyFormat("SomeClass::Constructor()\n" 19992 " : a(a)\n" 19993 " , b(b)\n" 19994 " , c(c) {}", 19995 Style); 19996 verifyFormat("SomeClass::Constructor()\n" 19997 " : a(a) {}", 19998 Style); 19999 20000 Style.ColumnLimit = 0; 20001 verifyFormat("SomeClass::Constructor()\n" 20002 " : a(a) {}", 20003 Style); 20004 verifyFormat("SomeClass::Constructor() noexcept\n" 20005 " : a(a) {}", 20006 Style); 20007 verifyFormat("SomeClass::Constructor()\n" 20008 " : a(a)\n" 20009 " , b(b)\n" 20010 " , c(c) {}", 20011 Style); 20012 verifyFormat("SomeClass::Constructor()\n" 20013 " : a(a) {\n" 20014 " foo();\n" 20015 " bar();\n" 20016 "}", 20017 Style); 20018 20019 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 20020 verifyFormat("SomeClass::Constructor()\n" 20021 " : a(a)\n" 20022 " , b(b)\n" 20023 " , c(c) {\n}", 20024 Style); 20025 verifyFormat("SomeClass::Constructor()\n" 20026 " : a(a) {\n}", 20027 Style); 20028 20029 Style.ColumnLimit = 80; 20030 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 20031 Style.ConstructorInitializerIndentWidth = 2; 20032 verifyFormat("SomeClass::Constructor()\n" 20033 " : a(a)\n" 20034 " , b(b)\n" 20035 " , c(c) {}", 20036 Style); 20037 20038 Style.ConstructorInitializerIndentWidth = 0; 20039 verifyFormat("SomeClass::Constructor()\n" 20040 ": a(a)\n" 20041 ", b(b)\n" 20042 ", c(c) {}", 20043 Style); 20044 20045 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 20046 Style.ConstructorInitializerIndentWidth = 4; 20047 verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style); 20048 verifyFormat( 20049 "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n", 20050 Style); 20051 verifyFormat( 20052 "SomeClass::Constructor()\n" 20053 " : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}", 20054 Style); 20055 Style.ConstructorInitializerIndentWidth = 4; 20056 Style.ColumnLimit = 60; 20057 verifyFormat("SomeClass::Constructor()\n" 20058 " : aaaaaaaa(aaaaaaaa)\n" 20059 " , aaaaaaaa(aaaaaaaa)\n" 20060 " , aaaaaaaa(aaaaaaaa) {}", 20061 Style); 20062 } 20063 20064 TEST_F(FormatTest, ConstructorInitializersWithPreprocessorDirective) { 20065 FormatStyle Style = getLLVMStyle(); 20066 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 20067 Style.ConstructorInitializerIndentWidth = 4; 20068 verifyFormat("SomeClass::Constructor()\n" 20069 " : a{a}\n" 20070 " , b{b} {}", 20071 Style); 20072 verifyFormat("SomeClass::Constructor()\n" 20073 " : a{a}\n" 20074 "#if CONDITION\n" 20075 " , b{b}\n" 20076 "#endif\n" 20077 "{\n}", 20078 Style); 20079 Style.ConstructorInitializerIndentWidth = 2; 20080 verifyFormat("SomeClass::Constructor()\n" 20081 "#if CONDITION\n" 20082 " : a{a}\n" 20083 "#endif\n" 20084 " , b{b}\n" 20085 " , c{c} {\n}", 20086 Style); 20087 Style.ConstructorInitializerIndentWidth = 0; 20088 verifyFormat("SomeClass::Constructor()\n" 20089 ": a{a}\n" 20090 "#ifdef CONDITION\n" 20091 ", b{b}\n" 20092 "#else\n" 20093 ", c{c}\n" 20094 "#endif\n" 20095 ", d{d} {\n}", 20096 Style); 20097 Style.ConstructorInitializerIndentWidth = 4; 20098 verifyFormat("SomeClass::Constructor()\n" 20099 " : a{a}\n" 20100 "#if WINDOWS\n" 20101 "#if DEBUG\n" 20102 " , b{0}\n" 20103 "#else\n" 20104 " , b{1}\n" 20105 "#endif\n" 20106 "#else\n" 20107 "#if DEBUG\n" 20108 " , b{2}\n" 20109 "#else\n" 20110 " , b{3}\n" 20111 "#endif\n" 20112 "#endif\n" 20113 "{\n}", 20114 Style); 20115 verifyFormat("SomeClass::Constructor()\n" 20116 " : a{a}\n" 20117 "#if WINDOWS\n" 20118 " , b{0}\n" 20119 "#if DEBUG\n" 20120 " , c{0}\n" 20121 "#else\n" 20122 " , c{1}\n" 20123 "#endif\n" 20124 "#else\n" 20125 "#if DEBUG\n" 20126 " , c{2}\n" 20127 "#else\n" 20128 " , c{3}\n" 20129 "#endif\n" 20130 " , b{1}\n" 20131 "#endif\n" 20132 "{\n}", 20133 Style); 20134 } 20135 20136 TEST_F(FormatTest, Destructors) { 20137 verifyFormat("void F(int &i) { i.~int(); }"); 20138 verifyFormat("void F(int &i) { i->~int(); }"); 20139 } 20140 20141 TEST_F(FormatTest, FormatsWithWebKitStyle) { 20142 FormatStyle Style = getWebKitStyle(); 20143 20144 // Don't indent in outer namespaces. 20145 verifyFormat("namespace outer {\n" 20146 "int i;\n" 20147 "namespace inner {\n" 20148 " int i;\n" 20149 "} // namespace inner\n" 20150 "} // namespace outer\n" 20151 "namespace other_outer {\n" 20152 "int i;\n" 20153 "}", 20154 Style); 20155 20156 // Don't indent case labels. 20157 verifyFormat("switch (variable) {\n" 20158 "case 1:\n" 20159 "case 2:\n" 20160 " doSomething();\n" 20161 " break;\n" 20162 "default:\n" 20163 " ++variable;\n" 20164 "}", 20165 Style); 20166 20167 // Wrap before binary operators. 20168 EXPECT_EQ("void f()\n" 20169 "{\n" 20170 " if (aaaaaaaaaaaaaaaa\n" 20171 " && bbbbbbbbbbbbbbbbbbbbbbbb\n" 20172 " && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n" 20173 " return;\n" 20174 "}", 20175 format("void f() {\n" 20176 "if (aaaaaaaaaaaaaaaa\n" 20177 "&& bbbbbbbbbbbbbbbbbbbbbbbb\n" 20178 "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n" 20179 "return;\n" 20180 "}", 20181 Style)); 20182 20183 // Allow functions on a single line. 20184 verifyFormat("void f() { return; }", Style); 20185 20186 // Allow empty blocks on a single line and insert a space in empty blocks. 20187 EXPECT_EQ("void f() { }", format("void f() {}", Style)); 20188 EXPECT_EQ("while (true) { }", format("while (true) {}", Style)); 20189 // However, don't merge non-empty short loops. 20190 EXPECT_EQ("while (true) {\n" 20191 " continue;\n" 20192 "}", 20193 format("while (true) { continue; }", Style)); 20194 20195 // Constructor initializers are formatted one per line with the "," on the 20196 // new line. 20197 verifyFormat("Constructor()\n" 20198 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 20199 " , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n" 20200 " aaaaaaaaaaaaaa)\n" 20201 " , aaaaaaaaaaaaaaaaaaaaaaa()\n" 20202 "{\n" 20203 "}", 20204 Style); 20205 verifyFormat("SomeClass::Constructor()\n" 20206 " : a(a)\n" 20207 "{\n" 20208 "}", 20209 Style); 20210 EXPECT_EQ("SomeClass::Constructor()\n" 20211 " : a(a)\n" 20212 "{\n" 20213 "}", 20214 format("SomeClass::Constructor():a(a){}", Style)); 20215 verifyFormat("SomeClass::Constructor()\n" 20216 " : a(a)\n" 20217 " , b(b)\n" 20218 " , c(c)\n" 20219 "{\n" 20220 "}", 20221 Style); 20222 verifyFormat("SomeClass::Constructor()\n" 20223 " : a(a)\n" 20224 "{\n" 20225 " foo();\n" 20226 " bar();\n" 20227 "}", 20228 Style); 20229 20230 // Access specifiers should be aligned left. 20231 verifyFormat("class C {\n" 20232 "public:\n" 20233 " int i;\n" 20234 "};", 20235 Style); 20236 20237 // Do not align comments. 20238 verifyFormat("int a; // Do not\n" 20239 "double b; // align comments.", 20240 Style); 20241 20242 // Do not align operands. 20243 EXPECT_EQ("ASSERT(aaaa\n" 20244 " || bbbb);", 20245 format("ASSERT ( aaaa\n||bbbb);", Style)); 20246 20247 // Accept input's line breaks. 20248 EXPECT_EQ("if (aaaaaaaaaaaaaaa\n" 20249 " || bbbbbbbbbbbbbbb) {\n" 20250 " i++;\n" 20251 "}", 20252 format("if (aaaaaaaaaaaaaaa\n" 20253 "|| bbbbbbbbbbbbbbb) { i++; }", 20254 Style)); 20255 EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n" 20256 " i++;\n" 20257 "}", 20258 format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style)); 20259 20260 // Don't automatically break all macro definitions (llvm.org/PR17842). 20261 verifyFormat("#define aNumber 10", Style); 20262 // However, generally keep the line breaks that the user authored. 20263 EXPECT_EQ("#define aNumber \\\n" 20264 " 10", 20265 format("#define aNumber \\\n" 20266 " 10", 20267 Style)); 20268 20269 // Keep empty and one-element array literals on a single line. 20270 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n" 20271 " copyItems:YES];", 20272 format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n" 20273 "copyItems:YES];", 20274 Style)); 20275 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n" 20276 " copyItems:YES];", 20277 format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n" 20278 " copyItems:YES];", 20279 Style)); 20280 // FIXME: This does not seem right, there should be more indentation before 20281 // the array literal's entries. Nested blocks have the same problem. 20282 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n" 20283 " @\"a\",\n" 20284 " @\"a\"\n" 20285 "]\n" 20286 " copyItems:YES];", 20287 format("NSArray* a = [[NSArray alloc] initWithArray:@[\n" 20288 " @\"a\",\n" 20289 " @\"a\"\n" 20290 " ]\n" 20291 " copyItems:YES];", 20292 Style)); 20293 EXPECT_EQ( 20294 "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n" 20295 " copyItems:YES];", 20296 format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n" 20297 " copyItems:YES];", 20298 Style)); 20299 20300 verifyFormat("[self.a b:c c:d];", Style); 20301 EXPECT_EQ("[self.a b:c\n" 20302 " c:d];", 20303 format("[self.a b:c\n" 20304 "c:d];", 20305 Style)); 20306 } 20307 20308 TEST_F(FormatTest, FormatsLambdas) { 20309 verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n"); 20310 verifyFormat( 20311 "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n"); 20312 verifyFormat("int c = [&] { [=] { return b++; }(); }();\n"); 20313 verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n"); 20314 verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n"); 20315 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n"); 20316 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n"); 20317 verifyFormat("auto c = [a = [b = 42] {}] {};\n"); 20318 verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n"); 20319 verifyFormat("int x = f(*+[] {});"); 20320 verifyFormat("void f() {\n" 20321 " other(x.begin(), x.end(), [&](int, int) { return 1; });\n" 20322 "}\n"); 20323 verifyFormat("void f() {\n" 20324 " other(x.begin(), //\n" 20325 " x.end(), //\n" 20326 " [&](int, int) { return 1; });\n" 20327 "}\n"); 20328 verifyFormat("void f() {\n" 20329 " other.other.other.other.other(\n" 20330 " x.begin(), x.end(),\n" 20331 " [something, rather](int, int, int, int, int, int, int) { " 20332 "return 1; });\n" 20333 "}\n"); 20334 verifyFormat( 20335 "void f() {\n" 20336 " other.other.other.other.other(\n" 20337 " x.begin(), x.end(),\n" 20338 " [something, rather](int, int, int, int, int, int, int) {\n" 20339 " //\n" 20340 " });\n" 20341 "}\n"); 20342 verifyFormat("SomeFunction([]() { // A cool function...\n" 20343 " return 43;\n" 20344 "});"); 20345 EXPECT_EQ("SomeFunction([]() {\n" 20346 "#define A a\n" 20347 " return 43;\n" 20348 "});", 20349 format("SomeFunction([](){\n" 20350 "#define A a\n" 20351 "return 43;\n" 20352 "});")); 20353 verifyFormat("void f() {\n" 20354 " SomeFunction([](decltype(x), A *a) {});\n" 20355 " SomeFunction([](typeof(x), A *a) {});\n" 20356 " SomeFunction([](_Atomic(x), A *a) {});\n" 20357 " SomeFunction([](__underlying_type(x), A *a) {});\n" 20358 "}"); 20359 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 20360 " [](const aaaaaaaaaa &a) { return a; });"); 20361 verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n" 20362 " SomeOtherFunctioooooooooooooooooooooooooon();\n" 20363 "});"); 20364 verifyFormat("Constructor()\n" 20365 " : Field([] { // comment\n" 20366 " int i;\n" 20367 " }) {}"); 20368 verifyFormat("auto my_lambda = [](const string &some_parameter) {\n" 20369 " return some_parameter.size();\n" 20370 "};"); 20371 verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n" 20372 " [](const string &s) { return s; };"); 20373 verifyFormat("int i = aaaaaa ? 1 //\n" 20374 " : [] {\n" 20375 " return 2; //\n" 20376 " }();"); 20377 verifyFormat("llvm::errs() << \"number of twos is \"\n" 20378 " << std::count_if(v.begin(), v.end(), [](int x) {\n" 20379 " return x == 2; // force break\n" 20380 " });"); 20381 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 20382 " [=](int iiiiiiiiiiii) {\n" 20383 " return aaaaaaaaaaaaaaaaaaaaaaa !=\n" 20384 " aaaaaaaaaaaaaaaaaaaaaaa;\n" 20385 " });", 20386 getLLVMStyleWithColumns(60)); 20387 20388 verifyFormat("SomeFunction({[&] {\n" 20389 " // comment\n" 20390 " },\n" 20391 " [&] {\n" 20392 " // comment\n" 20393 " }});"); 20394 verifyFormat("SomeFunction({[&] {\n" 20395 " // comment\n" 20396 "}});"); 20397 verifyFormat( 20398 "virtual aaaaaaaaaaaaaaaa(\n" 20399 " std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n" 20400 " aaaaa aaaaaaaaa);"); 20401 20402 // Lambdas with return types. 20403 verifyFormat("int c = []() -> int { return 2; }();\n"); 20404 verifyFormat("int c = []() -> int * { return 2; }();\n"); 20405 verifyFormat("int c = []() -> vector<int> { return {2}; }();\n"); 20406 verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());"); 20407 verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};"); 20408 verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};"); 20409 verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};"); 20410 verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};"); 20411 verifyFormat("[a, a]() -> a<1> {};"); 20412 verifyFormat("[]() -> foo<5 + 2> { return {}; };"); 20413 verifyFormat("[]() -> foo<5 - 2> { return {}; };"); 20414 verifyFormat("[]() -> foo<5 / 2> { return {}; };"); 20415 verifyFormat("[]() -> foo<5 * 2> { return {}; };"); 20416 verifyFormat("[]() -> foo<5 % 2> { return {}; };"); 20417 verifyFormat("[]() -> foo<5 << 2> { return {}; };"); 20418 verifyFormat("[]() -> foo<!5> { return {}; };"); 20419 verifyFormat("[]() -> foo<~5> { return {}; };"); 20420 verifyFormat("[]() -> foo<5 | 2> { return {}; };"); 20421 verifyFormat("[]() -> foo<5 || 2> { return {}; };"); 20422 verifyFormat("[]() -> foo<5 & 2> { return {}; };"); 20423 verifyFormat("[]() -> foo<5 && 2> { return {}; };"); 20424 verifyFormat("[]() -> foo<5 == 2> { return {}; };"); 20425 verifyFormat("[]() -> foo<5 != 2> { return {}; };"); 20426 verifyFormat("[]() -> foo<5 >= 2> { return {}; };"); 20427 verifyFormat("[]() -> foo<5 <= 2> { return {}; };"); 20428 verifyFormat("[]() -> foo<5 < 2> { return {}; };"); 20429 verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };"); 20430 verifyFormat("namespace bar {\n" 20431 "// broken:\n" 20432 "auto foo{[]() -> foo<5 + 2> { return {}; }};\n" 20433 "} // namespace bar"); 20434 verifyFormat("namespace bar {\n" 20435 "// broken:\n" 20436 "auto foo{[]() -> foo<5 - 2> { return {}; }};\n" 20437 "} // namespace bar"); 20438 verifyFormat("namespace bar {\n" 20439 "// broken:\n" 20440 "auto foo{[]() -> foo<5 / 2> { return {}; }};\n" 20441 "} // namespace bar"); 20442 verifyFormat("namespace bar {\n" 20443 "// broken:\n" 20444 "auto foo{[]() -> foo<5 * 2> { return {}; }};\n" 20445 "} // namespace bar"); 20446 verifyFormat("namespace bar {\n" 20447 "// broken:\n" 20448 "auto foo{[]() -> foo<5 % 2> { return {}; }};\n" 20449 "} // namespace bar"); 20450 verifyFormat("namespace bar {\n" 20451 "// broken:\n" 20452 "auto foo{[]() -> foo<5 << 2> { return {}; }};\n" 20453 "} // namespace bar"); 20454 verifyFormat("namespace bar {\n" 20455 "// broken:\n" 20456 "auto foo{[]() -> foo<!5> { return {}; }};\n" 20457 "} // namespace bar"); 20458 verifyFormat("namespace bar {\n" 20459 "// broken:\n" 20460 "auto foo{[]() -> foo<~5> { return {}; }};\n" 20461 "} // namespace bar"); 20462 verifyFormat("namespace bar {\n" 20463 "// broken:\n" 20464 "auto foo{[]() -> foo<5 | 2> { return {}; }};\n" 20465 "} // namespace bar"); 20466 verifyFormat("namespace bar {\n" 20467 "// broken:\n" 20468 "auto foo{[]() -> foo<5 || 2> { return {}; }};\n" 20469 "} // namespace bar"); 20470 verifyFormat("namespace bar {\n" 20471 "// broken:\n" 20472 "auto foo{[]() -> foo<5 & 2> { return {}; }};\n" 20473 "} // namespace bar"); 20474 verifyFormat("namespace bar {\n" 20475 "// broken:\n" 20476 "auto foo{[]() -> foo<5 && 2> { return {}; }};\n" 20477 "} // namespace bar"); 20478 verifyFormat("namespace bar {\n" 20479 "// broken:\n" 20480 "auto foo{[]() -> foo<5 == 2> { return {}; }};\n" 20481 "} // namespace bar"); 20482 verifyFormat("namespace bar {\n" 20483 "// broken:\n" 20484 "auto foo{[]() -> foo<5 != 2> { return {}; }};\n" 20485 "} // namespace bar"); 20486 verifyFormat("namespace bar {\n" 20487 "// broken:\n" 20488 "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n" 20489 "} // namespace bar"); 20490 verifyFormat("namespace bar {\n" 20491 "// broken:\n" 20492 "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n" 20493 "} // namespace bar"); 20494 verifyFormat("namespace bar {\n" 20495 "// broken:\n" 20496 "auto foo{[]() -> foo<5 < 2> { return {}; }};\n" 20497 "} // namespace bar"); 20498 verifyFormat("namespace bar {\n" 20499 "// broken:\n" 20500 "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n" 20501 "} // namespace bar"); 20502 verifyFormat("[]() -> a<1> {};"); 20503 verifyFormat("[]() -> a<1> { ; };"); 20504 verifyFormat("[]() -> a<1> { ; }();"); 20505 verifyFormat("[a, a]() -> a<true> {};"); 20506 verifyFormat("[]() -> a<true> {};"); 20507 verifyFormat("[]() -> a<true> { ; };"); 20508 verifyFormat("[]() -> a<true> { ; }();"); 20509 verifyFormat("[a, a]() -> a<false> {};"); 20510 verifyFormat("[]() -> a<false> {};"); 20511 verifyFormat("[]() -> a<false> { ; };"); 20512 verifyFormat("[]() -> a<false> { ; }();"); 20513 verifyFormat("auto foo{[]() -> foo<false> { ; }};"); 20514 verifyFormat("namespace bar {\n" 20515 "auto foo{[]() -> foo<false> { ; }};\n" 20516 "} // namespace bar"); 20517 verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n" 20518 " int j) -> int {\n" 20519 " return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n" 20520 "};"); 20521 verifyFormat( 20522 "aaaaaaaaaaaaaaaaaaaaaa(\n" 20523 " [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n" 20524 " return aaaaaaaaaaaaaaaaa;\n" 20525 " });", 20526 getLLVMStyleWithColumns(70)); 20527 verifyFormat("[]() //\n" 20528 " -> int {\n" 20529 " return 1; //\n" 20530 "};"); 20531 verifyFormat("[]() -> Void<T...> {};"); 20532 verifyFormat("[a, b]() -> Tuple<T...> { return {}; };"); 20533 verifyFormat("SomeFunction({[]() -> int[] { return {}; }});"); 20534 verifyFormat("SomeFunction({[]() -> int *[] { return {}; }});"); 20535 verifyFormat("SomeFunction({[]() -> int (*)[] { return {}; }});"); 20536 verifyFormat("SomeFunction({[]() -> ns::type<int (*)[]> { return {}; }});"); 20537 verifyFormat("return int{[x = x]() { return x; }()};"); 20538 20539 // Lambdas with explicit template argument lists. 20540 verifyFormat( 20541 "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n"); 20542 20543 // Multiple lambdas in the same parentheses change indentation rules. These 20544 // lambdas are forced to start on new lines. 20545 verifyFormat("SomeFunction(\n" 20546 " []() {\n" 20547 " //\n" 20548 " },\n" 20549 " []() {\n" 20550 " //\n" 20551 " });"); 20552 20553 // A lambda passed as arg0 is always pushed to the next line. 20554 verifyFormat("SomeFunction(\n" 20555 " [this] {\n" 20556 " //\n" 20557 " },\n" 20558 " 1);\n"); 20559 20560 // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like 20561 // the arg0 case above. 20562 auto Style = getGoogleStyle(); 20563 Style.BinPackArguments = false; 20564 verifyFormat("SomeFunction(\n" 20565 " a,\n" 20566 " [this] {\n" 20567 " //\n" 20568 " },\n" 20569 " b);\n", 20570 Style); 20571 verifyFormat("SomeFunction(\n" 20572 " a,\n" 20573 " [this] {\n" 20574 " //\n" 20575 " },\n" 20576 " b);\n"); 20577 20578 // A lambda with a very long line forces arg0 to be pushed out irrespective of 20579 // the BinPackArguments value (as long as the code is wide enough). 20580 verifyFormat( 20581 "something->SomeFunction(\n" 20582 " a,\n" 20583 " [this] {\n" 20584 " " 20585 "D0000000000000000000000000000000000000000000000000000000000001();\n" 20586 " },\n" 20587 " b);\n"); 20588 20589 // A multi-line lambda is pulled up as long as the introducer fits on the 20590 // previous line and there are no further args. 20591 verifyFormat("function(1, [this, that] {\n" 20592 " //\n" 20593 "});\n"); 20594 verifyFormat("function([this, that] {\n" 20595 " //\n" 20596 "});\n"); 20597 // FIXME: this format is not ideal and we should consider forcing the first 20598 // arg onto its own line. 20599 verifyFormat("function(a, b, c, //\n" 20600 " d, [this, that] {\n" 20601 " //\n" 20602 " });\n"); 20603 20604 // Multiple lambdas are treated correctly even when there is a short arg0. 20605 verifyFormat("SomeFunction(\n" 20606 " 1,\n" 20607 " [this] {\n" 20608 " //\n" 20609 " },\n" 20610 " [this] {\n" 20611 " //\n" 20612 " },\n" 20613 " 1);\n"); 20614 20615 // More complex introducers. 20616 verifyFormat("return [i, args...] {};"); 20617 20618 // Not lambdas. 20619 verifyFormat("constexpr char hello[]{\"hello\"};"); 20620 verifyFormat("double &operator[](int i) { return 0; }\n" 20621 "int i;"); 20622 verifyFormat("std::unique_ptr<int[]> foo() {}"); 20623 verifyFormat("int i = a[a][a]->f();"); 20624 verifyFormat("int i = (*b)[a]->f();"); 20625 20626 // Other corner cases. 20627 verifyFormat("void f() {\n" 20628 " bar([]() {} // Did not respect SpacesBeforeTrailingComments\n" 20629 " );\n" 20630 "}"); 20631 20632 // Lambdas created through weird macros. 20633 verifyFormat("void f() {\n" 20634 " MACRO((const AA &a) { return 1; });\n" 20635 " MACRO((AA &a) { return 1; });\n" 20636 "}"); 20637 20638 verifyFormat("if (blah_blah(whatever, whatever, [] {\n" 20639 " doo_dah();\n" 20640 " doo_dah();\n" 20641 " })) {\n" 20642 "}"); 20643 verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n" 20644 " doo_dah();\n" 20645 " doo_dah();\n" 20646 " })) {\n" 20647 "}"); 20648 verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n" 20649 " doo_dah();\n" 20650 " doo_dah();\n" 20651 " })) {\n" 20652 "}"); 20653 verifyFormat("auto lambda = []() {\n" 20654 " int a = 2\n" 20655 "#if A\n" 20656 " + 2\n" 20657 "#endif\n" 20658 " ;\n" 20659 "};"); 20660 20661 // Lambdas with complex multiline introducers. 20662 verifyFormat( 20663 "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 20664 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n" 20665 " -> ::std::unordered_set<\n" 20666 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n" 20667 " //\n" 20668 " });"); 20669 20670 FormatStyle DoNotMerge = getLLVMStyle(); 20671 DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 20672 verifyFormat("auto c = []() {\n" 20673 " return b;\n" 20674 "};", 20675 "auto c = []() { return b; };", DoNotMerge); 20676 verifyFormat("auto c = []() {\n" 20677 "};", 20678 " auto c = []() {};", DoNotMerge); 20679 20680 FormatStyle MergeEmptyOnly = getLLVMStyle(); 20681 MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty; 20682 verifyFormat("auto c = []() {\n" 20683 " return b;\n" 20684 "};", 20685 "auto c = []() {\n" 20686 " return b;\n" 20687 " };", 20688 MergeEmptyOnly); 20689 verifyFormat("auto c = []() {};", 20690 "auto c = []() {\n" 20691 "};", 20692 MergeEmptyOnly); 20693 20694 FormatStyle MergeInline = getLLVMStyle(); 20695 MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline; 20696 verifyFormat("auto c = []() {\n" 20697 " return b;\n" 20698 "};", 20699 "auto c = []() { return b; };", MergeInline); 20700 verifyFormat("function([]() { return b; })", "function([]() { return b; })", 20701 MergeInline); 20702 verifyFormat("function([]() { return b; }, a)", 20703 "function([]() { return b; }, a)", MergeInline); 20704 verifyFormat("function(a, []() { return b; })", 20705 "function(a, []() { return b; })", MergeInline); 20706 20707 // Check option "BraceWrapping.BeforeLambdaBody" and different state of 20708 // AllowShortLambdasOnASingleLine 20709 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle(); 20710 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 20711 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 20712 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 20713 FormatStyle::ShortLambdaStyle::SLS_None; 20714 verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n" 20715 " []()\n" 20716 " {\n" 20717 " return 17;\n" 20718 " });", 20719 LLVMWithBeforeLambdaBody); 20720 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n" 20721 " []()\n" 20722 " {\n" 20723 " });", 20724 LLVMWithBeforeLambdaBody); 20725 verifyFormat("auto fct_SLS_None = []()\n" 20726 "{\n" 20727 " return 17;\n" 20728 "};", 20729 LLVMWithBeforeLambdaBody); 20730 verifyFormat("TwoNestedLambdas_SLS_None(\n" 20731 " []()\n" 20732 " {\n" 20733 " return Call(\n" 20734 " []()\n" 20735 " {\n" 20736 " return 17;\n" 20737 " });\n" 20738 " });", 20739 LLVMWithBeforeLambdaBody); 20740 verifyFormat("void Fct() {\n" 20741 " return {[]()\n" 20742 " {\n" 20743 " return 17;\n" 20744 " }};\n" 20745 "}", 20746 LLVMWithBeforeLambdaBody); 20747 20748 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 20749 FormatStyle::ShortLambdaStyle::SLS_Empty; 20750 verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n" 20751 " []()\n" 20752 " {\n" 20753 " return 17;\n" 20754 " });", 20755 LLVMWithBeforeLambdaBody); 20756 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});", 20757 LLVMWithBeforeLambdaBody); 20758 verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL" 20759 "ongFunctionName_SLS_Empty(\n" 20760 " []() {});", 20761 LLVMWithBeforeLambdaBody); 20762 verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n" 20763 " []()\n" 20764 " {\n" 20765 " return 17;\n" 20766 " });", 20767 LLVMWithBeforeLambdaBody); 20768 verifyFormat("auto fct_SLS_Empty = []()\n" 20769 "{\n" 20770 " return 17;\n" 20771 "};", 20772 LLVMWithBeforeLambdaBody); 20773 verifyFormat("TwoNestedLambdas_SLS_Empty(\n" 20774 " []()\n" 20775 " {\n" 20776 " return Call([]() {});\n" 20777 " });", 20778 LLVMWithBeforeLambdaBody); 20779 verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n" 20780 " []()\n" 20781 " {\n" 20782 " return Call([]() {});\n" 20783 " });", 20784 LLVMWithBeforeLambdaBody); 20785 verifyFormat( 20786 "FctWithLongLineInLambda_SLS_Empty(\n" 20787 " []()\n" 20788 " {\n" 20789 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 20790 " AndShouldNotBeConsiderAsInline,\n" 20791 " LambdaBodyMustBeBreak);\n" 20792 " });", 20793 LLVMWithBeforeLambdaBody); 20794 20795 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 20796 FormatStyle::ShortLambdaStyle::SLS_Inline; 20797 verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });", 20798 LLVMWithBeforeLambdaBody); 20799 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});", 20800 LLVMWithBeforeLambdaBody); 20801 verifyFormat("auto fct_SLS_Inline = []()\n" 20802 "{\n" 20803 " return 17;\n" 20804 "};", 20805 LLVMWithBeforeLambdaBody); 20806 verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return " 20807 "17; }); });", 20808 LLVMWithBeforeLambdaBody); 20809 verifyFormat( 20810 "FctWithLongLineInLambda_SLS_Inline(\n" 20811 " []()\n" 20812 " {\n" 20813 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 20814 " AndShouldNotBeConsiderAsInline,\n" 20815 " LambdaBodyMustBeBreak);\n" 20816 " });", 20817 LLVMWithBeforeLambdaBody); 20818 verifyFormat("FctWithMultipleParams_SLS_Inline(" 20819 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n" 20820 " []() { return 17; });", 20821 LLVMWithBeforeLambdaBody); 20822 verifyFormat( 20823 "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });", 20824 LLVMWithBeforeLambdaBody); 20825 20826 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 20827 FormatStyle::ShortLambdaStyle::SLS_All; 20828 verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });", 20829 LLVMWithBeforeLambdaBody); 20830 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});", 20831 LLVMWithBeforeLambdaBody); 20832 verifyFormat("auto fct_SLS_All = []() { return 17; };", 20833 LLVMWithBeforeLambdaBody); 20834 verifyFormat("FctWithOneParam_SLS_All(\n" 20835 " []()\n" 20836 " {\n" 20837 " // A cool function...\n" 20838 " return 43;\n" 20839 " });", 20840 LLVMWithBeforeLambdaBody); 20841 verifyFormat("FctWithMultipleParams_SLS_All(" 20842 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n" 20843 " []() { return 17; });", 20844 LLVMWithBeforeLambdaBody); 20845 verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });", 20846 LLVMWithBeforeLambdaBody); 20847 verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });", 20848 LLVMWithBeforeLambdaBody); 20849 verifyFormat( 20850 "FctWithLongLineInLambda_SLS_All(\n" 20851 " []()\n" 20852 " {\n" 20853 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 20854 " AndShouldNotBeConsiderAsInline,\n" 20855 " LambdaBodyMustBeBreak);\n" 20856 " });", 20857 LLVMWithBeforeLambdaBody); 20858 verifyFormat( 20859 "auto fct_SLS_All = []()\n" 20860 "{\n" 20861 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 20862 " AndShouldNotBeConsiderAsInline,\n" 20863 " LambdaBodyMustBeBreak);\n" 20864 "};", 20865 LLVMWithBeforeLambdaBody); 20866 LLVMWithBeforeLambdaBody.BinPackParameters = false; 20867 verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);", 20868 LLVMWithBeforeLambdaBody); 20869 verifyFormat( 20870 "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n" 20871 " FirstParam,\n" 20872 " SecondParam,\n" 20873 " ThirdParam,\n" 20874 " FourthParam);", 20875 LLVMWithBeforeLambdaBody); 20876 verifyFormat("FctWithLongLineInLambda_SLS_All(\n" 20877 " []() { return " 20878 "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n" 20879 " FirstParam,\n" 20880 " SecondParam,\n" 20881 " ThirdParam,\n" 20882 " FourthParam);", 20883 LLVMWithBeforeLambdaBody); 20884 verifyFormat( 20885 "FctWithLongLineInLambda_SLS_All(FirstParam,\n" 20886 " SecondParam,\n" 20887 " ThirdParam,\n" 20888 " FourthParam,\n" 20889 " []() { return SomeValueNotSoLong; });", 20890 LLVMWithBeforeLambdaBody); 20891 verifyFormat("FctWithLongLineInLambda_SLS_All(\n" 20892 " []()\n" 20893 " {\n" 20894 " return " 20895 "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB" 20896 "eConsiderAsInline;\n" 20897 " });", 20898 LLVMWithBeforeLambdaBody); 20899 verifyFormat( 20900 "FctWithLongLineInLambda_SLS_All(\n" 20901 " []()\n" 20902 " {\n" 20903 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 20904 " AndShouldNotBeConsiderAsInline,\n" 20905 " LambdaBodyMustBeBreak);\n" 20906 " });", 20907 LLVMWithBeforeLambdaBody); 20908 verifyFormat("FctWithTwoParams_SLS_All(\n" 20909 " []()\n" 20910 " {\n" 20911 " // A cool function...\n" 20912 " return 43;\n" 20913 " },\n" 20914 " 87);", 20915 LLVMWithBeforeLambdaBody); 20916 verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);", 20917 LLVMWithBeforeLambdaBody); 20918 verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });", 20919 LLVMWithBeforeLambdaBody); 20920 verifyFormat( 20921 "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });", 20922 LLVMWithBeforeLambdaBody); 20923 verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; " 20924 "}); }, x);", 20925 LLVMWithBeforeLambdaBody); 20926 verifyFormat("TwoNestedLambdas_SLS_All(\n" 20927 " []()\n" 20928 " {\n" 20929 " // A cool function...\n" 20930 " return Call([]() { return 17; });\n" 20931 " });", 20932 LLVMWithBeforeLambdaBody); 20933 verifyFormat("TwoNestedLambdas_SLS_All(\n" 20934 " []()\n" 20935 " {\n" 20936 " return Call(\n" 20937 " []()\n" 20938 " {\n" 20939 " // A cool function...\n" 20940 " return 17;\n" 20941 " });\n" 20942 " });", 20943 LLVMWithBeforeLambdaBody); 20944 20945 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 20946 FormatStyle::ShortLambdaStyle::SLS_None; 20947 20948 verifyFormat("auto select = [this]() -> const Library::Object *\n" 20949 "{\n" 20950 " return MyAssignment::SelectFromList(this);\n" 20951 "};\n", 20952 LLVMWithBeforeLambdaBody); 20953 20954 verifyFormat("auto select = [this]() -> const Library::Object &\n" 20955 "{\n" 20956 " return MyAssignment::SelectFromList(this);\n" 20957 "};\n", 20958 LLVMWithBeforeLambdaBody); 20959 20960 verifyFormat("auto select = [this]() -> std::unique_ptr<Object>\n" 20961 "{\n" 20962 " return MyAssignment::SelectFromList(this);\n" 20963 "};\n", 20964 LLVMWithBeforeLambdaBody); 20965 20966 verifyFormat("namespace test {\n" 20967 "class Test {\n" 20968 "public:\n" 20969 " Test() = default;\n" 20970 "};\n" 20971 "} // namespace test", 20972 LLVMWithBeforeLambdaBody); 20973 20974 // Lambdas with different indentation styles. 20975 Style = getLLVMStyleWithColumns(100); 20976 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 20977 " return promise.then(\n" 20978 " [this, &someVariable, someObject = " 20979 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 20980 " return someObject.startAsyncAction().then(\n" 20981 " [this, &someVariable](AsyncActionResult result) " 20982 "mutable { result.processMore(); });\n" 20983 " });\n" 20984 "}\n", 20985 format("SomeResult doSomething(SomeObject promise) {\n" 20986 " return promise.then([this, &someVariable, someObject = " 20987 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 20988 " return someObject.startAsyncAction().then([this, " 20989 "&someVariable](AsyncActionResult result) mutable {\n" 20990 " result.processMore();\n" 20991 " });\n" 20992 " });\n" 20993 "}\n", 20994 Style)); 20995 Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope; 20996 verifyFormat("test() {\n" 20997 " ([]() -> {\n" 20998 " int b = 32;\n" 20999 " return 3;\n" 21000 " }).foo();\n" 21001 "}", 21002 Style); 21003 verifyFormat("test() {\n" 21004 " []() -> {\n" 21005 " int b = 32;\n" 21006 " return 3;\n" 21007 " }\n" 21008 "}", 21009 Style); 21010 verifyFormat("std::sort(v.begin(), v.end(),\n" 21011 " [](const auto &someLongArgumentName, const auto " 21012 "&someOtherLongArgumentName) {\n" 21013 " return someLongArgumentName.someMemberVariable < " 21014 "someOtherLongArgumentName.someMemberVariable;\n" 21015 "});", 21016 Style); 21017 verifyFormat("test() {\n" 21018 " (\n" 21019 " []() -> {\n" 21020 " int b = 32;\n" 21021 " return 3;\n" 21022 " },\n" 21023 " foo, bar)\n" 21024 " .foo();\n" 21025 "}", 21026 Style); 21027 verifyFormat("test() {\n" 21028 " ([]() -> {\n" 21029 " int b = 32;\n" 21030 " return 3;\n" 21031 " })\n" 21032 " .foo()\n" 21033 " .bar();\n" 21034 "}", 21035 Style); 21036 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 21037 " return promise.then(\n" 21038 " [this, &someVariable, someObject = " 21039 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21040 " return someObject.startAsyncAction().then(\n" 21041 " [this, &someVariable](AsyncActionResult result) mutable { " 21042 "result.processMore(); });\n" 21043 " });\n" 21044 "}\n", 21045 format("SomeResult doSomething(SomeObject promise) {\n" 21046 " return promise.then([this, &someVariable, someObject = " 21047 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21048 " return someObject.startAsyncAction().then([this, " 21049 "&someVariable](AsyncActionResult result) mutable {\n" 21050 " result.processMore();\n" 21051 " });\n" 21052 " });\n" 21053 "}\n", 21054 Style)); 21055 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 21056 " return promise.then([this, &someVariable] {\n" 21057 " return someObject.startAsyncAction().then(\n" 21058 " [this, &someVariable](AsyncActionResult result) mutable { " 21059 "result.processMore(); });\n" 21060 " });\n" 21061 "}\n", 21062 format("SomeResult doSomething(SomeObject promise) {\n" 21063 " return promise.then([this, &someVariable] {\n" 21064 " return someObject.startAsyncAction().then([this, " 21065 "&someVariable](AsyncActionResult result) mutable {\n" 21066 " result.processMore();\n" 21067 " });\n" 21068 " });\n" 21069 "}\n", 21070 Style)); 21071 Style = getGoogleStyle(); 21072 Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope; 21073 EXPECT_EQ("#define A \\\n" 21074 " [] { \\\n" 21075 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 21076 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n" 21077 " }", 21078 format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 21079 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }", 21080 Style)); 21081 // TODO: The current formatting has a minor issue that's not worth fixing 21082 // right now whereby the closing brace is indented relative to the signature 21083 // instead of being aligned. This only happens with macros. 21084 } 21085 21086 TEST_F(FormatTest, LambdaWithLineComments) { 21087 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle(); 21088 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 21089 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 21090 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21091 FormatStyle::ShortLambdaStyle::SLS_All; 21092 21093 verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody); 21094 verifyFormat("auto k = []() // comment\n" 21095 "{ return; }", 21096 LLVMWithBeforeLambdaBody); 21097 verifyFormat("auto k = []() /* comment */ { return; }", 21098 LLVMWithBeforeLambdaBody); 21099 verifyFormat("auto k = []() /* comment */ /* comment */ { return; }", 21100 LLVMWithBeforeLambdaBody); 21101 verifyFormat("auto k = []() // X\n" 21102 "{ return; }", 21103 LLVMWithBeforeLambdaBody); 21104 verifyFormat( 21105 "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" 21106 "{ return; }", 21107 LLVMWithBeforeLambdaBody); 21108 } 21109 21110 TEST_F(FormatTest, EmptyLinesInLambdas) { 21111 verifyFormat("auto lambda = []() {\n" 21112 " x(); //\n" 21113 "};", 21114 "auto lambda = []() {\n" 21115 "\n" 21116 " x(); //\n" 21117 "\n" 21118 "};"); 21119 } 21120 21121 TEST_F(FormatTest, FormatsBlocks) { 21122 FormatStyle ShortBlocks = getLLVMStyle(); 21123 ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 21124 verifyFormat("int (^Block)(int, int);", ShortBlocks); 21125 verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks); 21126 verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks); 21127 verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks); 21128 verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks); 21129 verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks); 21130 21131 verifyFormat("foo(^{ bar(); });", ShortBlocks); 21132 verifyFormat("foo(a, ^{ bar(); });", ShortBlocks); 21133 verifyFormat("{ void (^block)(Object *x); }", ShortBlocks); 21134 21135 verifyFormat("[operation setCompletionBlock:^{\n" 21136 " [self onOperationDone];\n" 21137 "}];"); 21138 verifyFormat("int i = {[operation setCompletionBlock:^{\n" 21139 " [self onOperationDone];\n" 21140 "}]};"); 21141 verifyFormat("[operation setCompletionBlock:^(int *i) {\n" 21142 " f();\n" 21143 "}];"); 21144 verifyFormat("int a = [operation block:^int(int *i) {\n" 21145 " return 1;\n" 21146 "}];"); 21147 verifyFormat("[myObject doSomethingWith:arg1\n" 21148 " aaa:^int(int *a) {\n" 21149 " return 1;\n" 21150 " }\n" 21151 " bbb:f(a * bbbbbbbb)];"); 21152 21153 verifyFormat("[operation setCompletionBlock:^{\n" 21154 " [self.delegate newDataAvailable];\n" 21155 "}];", 21156 getLLVMStyleWithColumns(60)); 21157 verifyFormat("dispatch_async(_fileIOQueue, ^{\n" 21158 " NSString *path = [self sessionFilePath];\n" 21159 " if (path) {\n" 21160 " // ...\n" 21161 " }\n" 21162 "});"); 21163 verifyFormat("[[SessionService sharedService]\n" 21164 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 21165 " if (window) {\n" 21166 " [self windowDidLoad:window];\n" 21167 " } else {\n" 21168 " [self errorLoadingWindow];\n" 21169 " }\n" 21170 " }];"); 21171 verifyFormat("void (^largeBlock)(void) = ^{\n" 21172 " // ...\n" 21173 "};\n", 21174 getLLVMStyleWithColumns(40)); 21175 verifyFormat("[[SessionService sharedService]\n" 21176 " loadWindowWithCompletionBlock: //\n" 21177 " ^(SessionWindow *window) {\n" 21178 " if (window) {\n" 21179 " [self windowDidLoad:window];\n" 21180 " } else {\n" 21181 " [self errorLoadingWindow];\n" 21182 " }\n" 21183 " }];", 21184 getLLVMStyleWithColumns(60)); 21185 verifyFormat("[myObject doSomethingWith:arg1\n" 21186 " firstBlock:^(Foo *a) {\n" 21187 " // ...\n" 21188 " int i;\n" 21189 " }\n" 21190 " secondBlock:^(Bar *b) {\n" 21191 " // ...\n" 21192 " int i;\n" 21193 " }\n" 21194 " thirdBlock:^Foo(Bar *b) {\n" 21195 " // ...\n" 21196 " int i;\n" 21197 " }];"); 21198 verifyFormat("[myObject doSomethingWith:arg1\n" 21199 " firstBlock:-1\n" 21200 " secondBlock:^(Bar *b) {\n" 21201 " // ...\n" 21202 " int i;\n" 21203 " }];"); 21204 21205 verifyFormat("f(^{\n" 21206 " @autoreleasepool {\n" 21207 " if (a) {\n" 21208 " g();\n" 21209 " }\n" 21210 " }\n" 21211 "});"); 21212 verifyFormat("Block b = ^int *(A *a, B *b) {}"); 21213 verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n" 21214 "};"); 21215 21216 FormatStyle FourIndent = getLLVMStyle(); 21217 FourIndent.ObjCBlockIndentWidth = 4; 21218 verifyFormat("[operation setCompletionBlock:^{\n" 21219 " [self onOperationDone];\n" 21220 "}];", 21221 FourIndent); 21222 } 21223 21224 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) { 21225 FormatStyle ZeroColumn = getLLVMStyleWithColumns(0); 21226 21227 verifyFormat("[[SessionService sharedService] " 21228 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 21229 " if (window) {\n" 21230 " [self windowDidLoad:window];\n" 21231 " } else {\n" 21232 " [self errorLoadingWindow];\n" 21233 " }\n" 21234 "}];", 21235 ZeroColumn); 21236 EXPECT_EQ("[[SessionService sharedService]\n" 21237 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 21238 " if (window) {\n" 21239 " [self windowDidLoad:window];\n" 21240 " } else {\n" 21241 " [self errorLoadingWindow];\n" 21242 " }\n" 21243 " }];", 21244 format("[[SessionService sharedService]\n" 21245 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 21246 " if (window) {\n" 21247 " [self windowDidLoad:window];\n" 21248 " } else {\n" 21249 " [self errorLoadingWindow];\n" 21250 " }\n" 21251 "}];", 21252 ZeroColumn)); 21253 verifyFormat("[myObject doSomethingWith:arg1\n" 21254 " firstBlock:^(Foo *a) {\n" 21255 " // ...\n" 21256 " int i;\n" 21257 " }\n" 21258 " secondBlock:^(Bar *b) {\n" 21259 " // ...\n" 21260 " int i;\n" 21261 " }\n" 21262 " thirdBlock:^Foo(Bar *b) {\n" 21263 " // ...\n" 21264 " int i;\n" 21265 " }];", 21266 ZeroColumn); 21267 verifyFormat("f(^{\n" 21268 " @autoreleasepool {\n" 21269 " if (a) {\n" 21270 " g();\n" 21271 " }\n" 21272 " }\n" 21273 "});", 21274 ZeroColumn); 21275 verifyFormat("void (^largeBlock)(void) = ^{\n" 21276 " // ...\n" 21277 "};", 21278 ZeroColumn); 21279 21280 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 21281 EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };", 21282 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn)); 21283 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 21284 EXPECT_EQ("void (^largeBlock)(void) = ^{\n" 21285 " int i;\n" 21286 "};", 21287 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn)); 21288 } 21289 21290 TEST_F(FormatTest, SupportsCRLF) { 21291 EXPECT_EQ("int a;\r\n" 21292 "int b;\r\n" 21293 "int c;\r\n", 21294 format("int a;\r\n" 21295 " int b;\r\n" 21296 " int c;\r\n", 21297 getLLVMStyle())); 21298 EXPECT_EQ("int a;\r\n" 21299 "int b;\r\n" 21300 "int c;\r\n", 21301 format("int a;\r\n" 21302 " int b;\n" 21303 " int c;\r\n", 21304 getLLVMStyle())); 21305 EXPECT_EQ("int a;\n" 21306 "int b;\n" 21307 "int c;\n", 21308 format("int a;\r\n" 21309 " int b;\n" 21310 " int c;\n", 21311 getLLVMStyle())); 21312 EXPECT_EQ("\"aaaaaaa \"\r\n" 21313 "\"bbbbbbb\";\r\n", 21314 format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10))); 21315 EXPECT_EQ("#define A \\\r\n" 21316 " b; \\\r\n" 21317 " c; \\\r\n" 21318 " d;\r\n", 21319 format("#define A \\\r\n" 21320 " b; \\\r\n" 21321 " c; d; \r\n", 21322 getGoogleStyle())); 21323 21324 EXPECT_EQ("/*\r\n" 21325 "multi line block comments\r\n" 21326 "should not introduce\r\n" 21327 "an extra carriage return\r\n" 21328 "*/\r\n", 21329 format("/*\r\n" 21330 "multi line block comments\r\n" 21331 "should not introduce\r\n" 21332 "an extra carriage return\r\n" 21333 "*/\r\n")); 21334 EXPECT_EQ("/*\r\n" 21335 "\r\n" 21336 "*/", 21337 format("/*\r\n" 21338 " \r\r\r\n" 21339 "*/")); 21340 21341 FormatStyle style = getLLVMStyle(); 21342 21343 style.DeriveLineEnding = true; 21344 style.UseCRLF = false; 21345 EXPECT_EQ("union FooBarBazQux {\n" 21346 " int foo;\n" 21347 " int bar;\n" 21348 " int baz;\n" 21349 "};", 21350 format("union FooBarBazQux {\r\n" 21351 " int foo;\n" 21352 " int bar;\r\n" 21353 " int baz;\n" 21354 "};", 21355 style)); 21356 style.UseCRLF = true; 21357 EXPECT_EQ("union FooBarBazQux {\r\n" 21358 " int foo;\r\n" 21359 " int bar;\r\n" 21360 " int baz;\r\n" 21361 "};", 21362 format("union FooBarBazQux {\r\n" 21363 " int foo;\n" 21364 " int bar;\r\n" 21365 " int baz;\n" 21366 "};", 21367 style)); 21368 21369 style.DeriveLineEnding = false; 21370 style.UseCRLF = false; 21371 EXPECT_EQ("union FooBarBazQux {\n" 21372 " int foo;\n" 21373 " int bar;\n" 21374 " int baz;\n" 21375 " int qux;\n" 21376 "};", 21377 format("union FooBarBazQux {\r\n" 21378 " int foo;\n" 21379 " int bar;\r\n" 21380 " int baz;\n" 21381 " int qux;\r\n" 21382 "};", 21383 style)); 21384 style.UseCRLF = true; 21385 EXPECT_EQ("union FooBarBazQux {\r\n" 21386 " int foo;\r\n" 21387 " int bar;\r\n" 21388 " int baz;\r\n" 21389 " int qux;\r\n" 21390 "};", 21391 format("union FooBarBazQux {\r\n" 21392 " int foo;\n" 21393 " int bar;\r\n" 21394 " int baz;\n" 21395 " int qux;\n" 21396 "};", 21397 style)); 21398 21399 style.DeriveLineEnding = true; 21400 style.UseCRLF = false; 21401 EXPECT_EQ("union FooBarBazQux {\r\n" 21402 " int foo;\r\n" 21403 " int bar;\r\n" 21404 " int baz;\r\n" 21405 " int qux;\r\n" 21406 "};", 21407 format("union FooBarBazQux {\r\n" 21408 " int foo;\n" 21409 " int bar;\r\n" 21410 " int baz;\n" 21411 " int qux;\r\n" 21412 "};", 21413 style)); 21414 style.UseCRLF = true; 21415 EXPECT_EQ("union FooBarBazQux {\n" 21416 " int foo;\n" 21417 " int bar;\n" 21418 " int baz;\n" 21419 " int qux;\n" 21420 "};", 21421 format("union FooBarBazQux {\r\n" 21422 " int foo;\n" 21423 " int bar;\r\n" 21424 " int baz;\n" 21425 " int qux;\n" 21426 "};", 21427 style)); 21428 } 21429 21430 TEST_F(FormatTest, MunchSemicolonAfterBlocks) { 21431 verifyFormat("MY_CLASS(C) {\n" 21432 " int i;\n" 21433 " int j;\n" 21434 "};"); 21435 } 21436 21437 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) { 21438 FormatStyle TwoIndent = getLLVMStyleWithColumns(15); 21439 TwoIndent.ContinuationIndentWidth = 2; 21440 21441 EXPECT_EQ("int i =\n" 21442 " longFunction(\n" 21443 " arg);", 21444 format("int i = longFunction(arg);", TwoIndent)); 21445 21446 FormatStyle SixIndent = getLLVMStyleWithColumns(20); 21447 SixIndent.ContinuationIndentWidth = 6; 21448 21449 EXPECT_EQ("int i =\n" 21450 " longFunction(\n" 21451 " arg);", 21452 format("int i = longFunction(arg);", SixIndent)); 21453 } 21454 21455 TEST_F(FormatTest, WrappedClosingParenthesisIndent) { 21456 FormatStyle Style = getLLVMStyle(); 21457 verifyFormat("int Foo::getter(\n" 21458 " //\n" 21459 ") const {\n" 21460 " return foo;\n" 21461 "}", 21462 Style); 21463 verifyFormat("void Foo::setter(\n" 21464 " //\n" 21465 ") {\n" 21466 " foo = 1;\n" 21467 "}", 21468 Style); 21469 } 21470 21471 TEST_F(FormatTest, SpacesInAngles) { 21472 FormatStyle Spaces = getLLVMStyle(); 21473 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 21474 21475 verifyFormat("vector< ::std::string > x1;", Spaces); 21476 verifyFormat("Foo< int, Bar > x2;", Spaces); 21477 verifyFormat("Foo< ::int, ::Bar > x3;", Spaces); 21478 21479 verifyFormat("static_cast< int >(arg);", Spaces); 21480 verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces); 21481 verifyFormat("f< int, float >();", Spaces); 21482 verifyFormat("template <> g() {}", Spaces); 21483 verifyFormat("template < std::vector< int > > f() {}", Spaces); 21484 verifyFormat("std::function< void(int, int) > fct;", Spaces); 21485 verifyFormat("void inFunction() { std::function< void(int, int) > fct; }", 21486 Spaces); 21487 21488 Spaces.Standard = FormatStyle::LS_Cpp03; 21489 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 21490 verifyFormat("A< A< int > >();", Spaces); 21491 21492 Spaces.SpacesInAngles = FormatStyle::SIAS_Never; 21493 verifyFormat("A<A<int> >();", Spaces); 21494 21495 Spaces.SpacesInAngles = FormatStyle::SIAS_Leave; 21496 verifyFormat("vector< ::std::string> x4;", "vector<::std::string> x4;", 21497 Spaces); 21498 verifyFormat("vector< ::std::string > x4;", "vector<::std::string > x4;", 21499 Spaces); 21500 21501 verifyFormat("A<A<int> >();", Spaces); 21502 verifyFormat("A<A<int> >();", "A<A<int>>();", Spaces); 21503 verifyFormat("A< A< int > >();", Spaces); 21504 21505 Spaces.Standard = FormatStyle::LS_Cpp11; 21506 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 21507 verifyFormat("A< A< int > >();", Spaces); 21508 21509 Spaces.SpacesInAngles = FormatStyle::SIAS_Never; 21510 verifyFormat("vector<::std::string> x4;", Spaces); 21511 verifyFormat("vector<int> x5;", Spaces); 21512 verifyFormat("Foo<int, Bar> x6;", Spaces); 21513 verifyFormat("Foo<::int, ::Bar> x7;", Spaces); 21514 21515 verifyFormat("A<A<int>>();", Spaces); 21516 21517 Spaces.SpacesInAngles = FormatStyle::SIAS_Leave; 21518 verifyFormat("vector<::std::string> x4;", Spaces); 21519 verifyFormat("vector< ::std::string > x4;", Spaces); 21520 verifyFormat("vector<int> x5;", Spaces); 21521 verifyFormat("vector< int > x5;", Spaces); 21522 verifyFormat("Foo<int, Bar> x6;", Spaces); 21523 verifyFormat("Foo< int, Bar > x6;", Spaces); 21524 verifyFormat("Foo<::int, ::Bar> x7;", Spaces); 21525 verifyFormat("Foo< ::int, ::Bar > x7;", Spaces); 21526 21527 verifyFormat("A<A<int>>();", Spaces); 21528 verifyFormat("A< A< int > >();", Spaces); 21529 verifyFormat("A<A<int > >();", Spaces); 21530 verifyFormat("A< A< int>>();", Spaces); 21531 21532 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 21533 verifyFormat("// clang-format off\n" 21534 "foo<<<1, 1>>>();\n" 21535 "// clang-format on\n", 21536 Spaces); 21537 verifyFormat("// clang-format off\n" 21538 "foo< < <1, 1> > >();\n" 21539 "// clang-format on\n", 21540 Spaces); 21541 } 21542 21543 TEST_F(FormatTest, SpaceAfterTemplateKeyword) { 21544 FormatStyle Style = getLLVMStyle(); 21545 Style.SpaceAfterTemplateKeyword = false; 21546 verifyFormat("template<int> void foo();", Style); 21547 } 21548 21549 TEST_F(FormatTest, TripleAngleBrackets) { 21550 verifyFormat("f<<<1, 1>>>();"); 21551 verifyFormat("f<<<1, 1, 1, s>>>();"); 21552 verifyFormat("f<<<a, b, c, d>>>();"); 21553 EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();")); 21554 verifyFormat("f<param><<<1, 1>>>();"); 21555 verifyFormat("f<1><<<1, 1>>>();"); 21556 EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();")); 21557 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 21558 "aaaaaaaaaaa<<<\n 1, 1>>>();"); 21559 verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n" 21560 " <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();"); 21561 } 21562 21563 TEST_F(FormatTest, MergeLessLessAtEnd) { 21564 verifyFormat("<<"); 21565 EXPECT_EQ("< < <", format("\\\n<<<")); 21566 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 21567 "aaallvm::outs() <<"); 21568 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 21569 "aaaallvm::outs()\n <<"); 21570 } 21571 21572 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) { 21573 std::string code = "#if A\n" 21574 "#if B\n" 21575 "a.\n" 21576 "#endif\n" 21577 " a = 1;\n" 21578 "#else\n" 21579 "#endif\n" 21580 "#if C\n" 21581 "#else\n" 21582 "#endif\n"; 21583 EXPECT_EQ(code, format(code)); 21584 } 21585 21586 TEST_F(FormatTest, HandleConflictMarkers) { 21587 // Git/SVN conflict markers. 21588 EXPECT_EQ("int a;\n" 21589 "void f() {\n" 21590 " callme(some(parameter1,\n" 21591 "<<<<<<< text by the vcs\n" 21592 " parameter2),\n" 21593 "||||||| text by the vcs\n" 21594 " parameter2),\n" 21595 " parameter3,\n" 21596 "======= text by the vcs\n" 21597 " parameter2, parameter3),\n" 21598 ">>>>>>> text by the vcs\n" 21599 " otherparameter);\n", 21600 format("int a;\n" 21601 "void f() {\n" 21602 " callme(some(parameter1,\n" 21603 "<<<<<<< text by the vcs\n" 21604 " parameter2),\n" 21605 "||||||| text by the vcs\n" 21606 " parameter2),\n" 21607 " parameter3,\n" 21608 "======= text by the vcs\n" 21609 " parameter2,\n" 21610 " parameter3),\n" 21611 ">>>>>>> text by the vcs\n" 21612 " otherparameter);\n")); 21613 21614 // Perforce markers. 21615 EXPECT_EQ("void f() {\n" 21616 " function(\n" 21617 ">>>> text by the vcs\n" 21618 " parameter,\n" 21619 "==== text by the vcs\n" 21620 " parameter,\n" 21621 "==== text by the vcs\n" 21622 " parameter,\n" 21623 "<<<< text by the vcs\n" 21624 " parameter);\n", 21625 format("void f() {\n" 21626 " function(\n" 21627 ">>>> text by the vcs\n" 21628 " parameter,\n" 21629 "==== text by the vcs\n" 21630 " parameter,\n" 21631 "==== text by the vcs\n" 21632 " parameter,\n" 21633 "<<<< text by the vcs\n" 21634 " parameter);\n")); 21635 21636 EXPECT_EQ("<<<<<<<\n" 21637 "|||||||\n" 21638 "=======\n" 21639 ">>>>>>>", 21640 format("<<<<<<<\n" 21641 "|||||||\n" 21642 "=======\n" 21643 ">>>>>>>")); 21644 21645 EXPECT_EQ("<<<<<<<\n" 21646 "|||||||\n" 21647 "int i;\n" 21648 "=======\n" 21649 ">>>>>>>", 21650 format("<<<<<<<\n" 21651 "|||||||\n" 21652 "int i;\n" 21653 "=======\n" 21654 ">>>>>>>")); 21655 21656 // FIXME: Handle parsing of macros around conflict markers correctly: 21657 EXPECT_EQ("#define Macro \\\n" 21658 "<<<<<<<\n" 21659 "Something \\\n" 21660 "|||||||\n" 21661 "Else \\\n" 21662 "=======\n" 21663 "Other \\\n" 21664 ">>>>>>>\n" 21665 " End int i;\n", 21666 format("#define Macro \\\n" 21667 "<<<<<<<\n" 21668 " Something \\\n" 21669 "|||||||\n" 21670 " Else \\\n" 21671 "=======\n" 21672 " Other \\\n" 21673 ">>>>>>>\n" 21674 " End\n" 21675 "int i;\n")); 21676 21677 verifyFormat(R"(==== 21678 #ifdef A 21679 a 21680 #else 21681 b 21682 #endif 21683 )"); 21684 } 21685 21686 TEST_F(FormatTest, DisableRegions) { 21687 EXPECT_EQ("int i;\n" 21688 "// clang-format off\n" 21689 " int j;\n" 21690 "// clang-format on\n" 21691 "int k;", 21692 format(" int i;\n" 21693 " // clang-format off\n" 21694 " int j;\n" 21695 " // clang-format on\n" 21696 " int k;")); 21697 EXPECT_EQ("int i;\n" 21698 "/* clang-format off */\n" 21699 " int j;\n" 21700 "/* clang-format on */\n" 21701 "int k;", 21702 format(" int i;\n" 21703 " /* clang-format off */\n" 21704 " int j;\n" 21705 " /* clang-format on */\n" 21706 " int k;")); 21707 21708 // Don't reflow comments within disabled regions. 21709 EXPECT_EQ("// clang-format off\n" 21710 "// long long long long long long line\n" 21711 "/* clang-format on */\n" 21712 "/* long long long\n" 21713 " * long long long\n" 21714 " * line */\n" 21715 "int i;\n" 21716 "/* clang-format off */\n" 21717 "/* long long long long long long line */\n", 21718 format("// clang-format off\n" 21719 "// long long long long long long line\n" 21720 "/* clang-format on */\n" 21721 "/* long long long long long long line */\n" 21722 "int i;\n" 21723 "/* clang-format off */\n" 21724 "/* long long long long long long line */\n", 21725 getLLVMStyleWithColumns(20))); 21726 } 21727 21728 TEST_F(FormatTest, DoNotCrashOnInvalidInput) { 21729 format("? ) ="); 21730 verifyNoCrash("#define a\\\n /**/}"); 21731 } 21732 21733 TEST_F(FormatTest, FormatsTableGenCode) { 21734 FormatStyle Style = getLLVMStyle(); 21735 Style.Language = FormatStyle::LK_TableGen; 21736 verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style); 21737 } 21738 21739 TEST_F(FormatTest, ArrayOfTemplates) { 21740 EXPECT_EQ("auto a = new unique_ptr<int>[10];", 21741 format("auto a = new unique_ptr<int > [ 10];")); 21742 21743 FormatStyle Spaces = getLLVMStyle(); 21744 Spaces.SpacesInSquareBrackets = true; 21745 EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];", 21746 format("auto a = new unique_ptr<int > [10];", Spaces)); 21747 } 21748 21749 TEST_F(FormatTest, ArrayAsTemplateType) { 21750 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;", 21751 format("auto a = unique_ptr < Foo < Bar>[ 10]> ;")); 21752 21753 FormatStyle Spaces = getLLVMStyle(); 21754 Spaces.SpacesInSquareBrackets = true; 21755 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;", 21756 format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces)); 21757 } 21758 21759 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); } 21760 21761 TEST(FormatStyle, GetStyleWithEmptyFileName) { 21762 llvm::vfs::InMemoryFileSystem FS; 21763 auto Style1 = getStyle("file", "", "Google", "", &FS); 21764 ASSERT_TRUE((bool)Style1); 21765 ASSERT_EQ(*Style1, getGoogleStyle()); 21766 } 21767 21768 TEST(FormatStyle, GetStyleOfFile) { 21769 llvm::vfs::InMemoryFileSystem FS; 21770 // Test 1: format file in the same directory. 21771 ASSERT_TRUE( 21772 FS.addFile("/a/.clang-format", 0, 21773 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM"))); 21774 ASSERT_TRUE( 21775 FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 21776 auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS); 21777 ASSERT_TRUE((bool)Style1); 21778 ASSERT_EQ(*Style1, getLLVMStyle()); 21779 21780 // Test 2.1: fallback to default. 21781 ASSERT_TRUE( 21782 FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 21783 auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS); 21784 ASSERT_TRUE((bool)Style2); 21785 ASSERT_EQ(*Style2, getMozillaStyle()); 21786 21787 // Test 2.2: no format on 'none' fallback style. 21788 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS); 21789 ASSERT_TRUE((bool)Style2); 21790 ASSERT_EQ(*Style2, getNoStyle()); 21791 21792 // Test 2.3: format if config is found with no based style while fallback is 21793 // 'none'. 21794 ASSERT_TRUE(FS.addFile("/b/.clang-format", 0, 21795 llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2"))); 21796 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS); 21797 ASSERT_TRUE((bool)Style2); 21798 ASSERT_EQ(*Style2, getLLVMStyle()); 21799 21800 // Test 2.4: format if yaml with no based style, while fallback is 'none'. 21801 Style2 = getStyle("{}", "a.h", "none", "", &FS); 21802 ASSERT_TRUE((bool)Style2); 21803 ASSERT_EQ(*Style2, getLLVMStyle()); 21804 21805 // Test 3: format file in parent directory. 21806 ASSERT_TRUE( 21807 FS.addFile("/c/.clang-format", 0, 21808 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 21809 ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0, 21810 llvm::MemoryBuffer::getMemBuffer("int i;"))); 21811 auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS); 21812 ASSERT_TRUE((bool)Style3); 21813 ASSERT_EQ(*Style3, getGoogleStyle()); 21814 21815 // Test 4: error on invalid fallback style 21816 auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS); 21817 ASSERT_FALSE((bool)Style4); 21818 llvm::consumeError(Style4.takeError()); 21819 21820 // Test 5: error on invalid yaml on command line 21821 auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS); 21822 ASSERT_FALSE((bool)Style5); 21823 llvm::consumeError(Style5.takeError()); 21824 21825 // Test 6: error on invalid style 21826 auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS); 21827 ASSERT_FALSE((bool)Style6); 21828 llvm::consumeError(Style6.takeError()); 21829 21830 // Test 7: found config file, error on parsing it 21831 ASSERT_TRUE( 21832 FS.addFile("/d/.clang-format", 0, 21833 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n" 21834 "InvalidKey: InvalidValue"))); 21835 ASSERT_TRUE( 21836 FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 21837 auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS); 21838 ASSERT_FALSE((bool)Style7a); 21839 llvm::consumeError(Style7a.takeError()); 21840 21841 auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true); 21842 ASSERT_TRUE((bool)Style7b); 21843 21844 // Test 8: inferred per-language defaults apply. 21845 auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS); 21846 ASSERT_TRUE((bool)StyleTd); 21847 ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen)); 21848 21849 // Test 9.1.1: overwriting a file style, when no parent file exists with no 21850 // fallback style. 21851 ASSERT_TRUE(FS.addFile( 21852 "/e/sub/.clang-format", 0, 21853 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n" 21854 "ColumnLimit: 20"))); 21855 ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0, 21856 llvm::MemoryBuffer::getMemBuffer("int i;"))); 21857 auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS); 21858 ASSERT_TRUE(static_cast<bool>(Style9)); 21859 ASSERT_EQ(*Style9, [] { 21860 auto Style = getNoStyle(); 21861 Style.ColumnLimit = 20; 21862 return Style; 21863 }()); 21864 21865 // Test 9.1.2: propagate more than one level with no parent file. 21866 ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0, 21867 llvm::MemoryBuffer::getMemBuffer("int i;"))); 21868 ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0, 21869 llvm::MemoryBuffer::getMemBuffer( 21870 "BasedOnStyle: InheritParentConfig\n" 21871 "WhitespaceSensitiveMacros: ['FOO', 'BAR']"))); 21872 std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"}; 21873 21874 ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros); 21875 Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS); 21876 ASSERT_TRUE(static_cast<bool>(Style9)); 21877 ASSERT_EQ(*Style9, [&NonDefaultWhiteSpaceMacros] { 21878 auto Style = getNoStyle(); 21879 Style.ColumnLimit = 20; 21880 Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros; 21881 return Style; 21882 }()); 21883 21884 // Test 9.2: with LLVM fallback style 21885 Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS); 21886 ASSERT_TRUE(static_cast<bool>(Style9)); 21887 ASSERT_EQ(*Style9, [] { 21888 auto Style = getLLVMStyle(); 21889 Style.ColumnLimit = 20; 21890 return Style; 21891 }()); 21892 21893 // Test 9.3: with a parent file 21894 ASSERT_TRUE( 21895 FS.addFile("/e/.clang-format", 0, 21896 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n" 21897 "UseTab: Always"))); 21898 Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS); 21899 ASSERT_TRUE(static_cast<bool>(Style9)); 21900 ASSERT_EQ(*Style9, [] { 21901 auto Style = getGoogleStyle(); 21902 Style.ColumnLimit = 20; 21903 Style.UseTab = FormatStyle::UT_Always; 21904 return Style; 21905 }()); 21906 21907 // Test 9.4: propagate more than one level with a parent file. 21908 const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] { 21909 auto Style = getGoogleStyle(); 21910 Style.ColumnLimit = 20; 21911 Style.UseTab = FormatStyle::UT_Always; 21912 Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros; 21913 return Style; 21914 }(); 21915 21916 ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros); 21917 Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS); 21918 ASSERT_TRUE(static_cast<bool>(Style9)); 21919 ASSERT_EQ(*Style9, SubSubStyle); 21920 21921 // Test 9.5: use InheritParentConfig as style name 21922 Style9 = 21923 getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS); 21924 ASSERT_TRUE(static_cast<bool>(Style9)); 21925 ASSERT_EQ(*Style9, SubSubStyle); 21926 21927 // Test 9.6: use command line style with inheritance 21928 Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp", 21929 "none", "", &FS); 21930 ASSERT_TRUE(static_cast<bool>(Style9)); 21931 ASSERT_EQ(*Style9, SubSubStyle); 21932 21933 // Test 9.7: use command line style with inheritance and own config 21934 Style9 = getStyle("{BasedOnStyle: InheritParentConfig, " 21935 "WhitespaceSensitiveMacros: ['FOO', 'BAR']}", 21936 "/e/sub/code.cpp", "none", "", &FS); 21937 ASSERT_TRUE(static_cast<bool>(Style9)); 21938 ASSERT_EQ(*Style9, SubSubStyle); 21939 21940 // Test 9.8: use inheritance from a file without BasedOnStyle 21941 ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0, 21942 llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123"))); 21943 ASSERT_TRUE( 21944 FS.addFile("/e/withoutbase/sub/.clang-format", 0, 21945 llvm::MemoryBuffer::getMemBuffer( 21946 "BasedOnStyle: InheritParentConfig\nIndentWidth: 7"))); 21947 // Make sure we do not use the fallback style 21948 Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS); 21949 ASSERT_TRUE(static_cast<bool>(Style9)); 21950 ASSERT_EQ(*Style9, [] { 21951 auto Style = getLLVMStyle(); 21952 Style.ColumnLimit = 123; 21953 return Style; 21954 }()); 21955 21956 Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS); 21957 ASSERT_TRUE(static_cast<bool>(Style9)); 21958 ASSERT_EQ(*Style9, [] { 21959 auto Style = getLLVMStyle(); 21960 Style.ColumnLimit = 123; 21961 Style.IndentWidth = 7; 21962 return Style; 21963 }()); 21964 21965 // Test 9.9: use inheritance from a specific config file. 21966 Style9 = getStyle("file:/e/sub/sub/.clang-format", "/e/sub/sub/code.cpp", 21967 "none", "", &FS); 21968 ASSERT_TRUE(static_cast<bool>(Style9)); 21969 ASSERT_EQ(*Style9, SubSubStyle); 21970 } 21971 21972 TEST(FormatStyle, GetStyleOfSpecificFile) { 21973 llvm::vfs::InMemoryFileSystem FS; 21974 // Specify absolute path to a format file in a parent directory. 21975 ASSERT_TRUE( 21976 FS.addFile("/e/.clang-format", 0, 21977 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM"))); 21978 ASSERT_TRUE( 21979 FS.addFile("/e/explicit.clang-format", 0, 21980 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 21981 ASSERT_TRUE(FS.addFile("/e/sub/sub/sub/test.cpp", 0, 21982 llvm::MemoryBuffer::getMemBuffer("int i;"))); 21983 auto Style = getStyle("file:/e/explicit.clang-format", 21984 "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS); 21985 ASSERT_TRUE(static_cast<bool>(Style)); 21986 ASSERT_EQ(*Style, getGoogleStyle()); 21987 21988 // Specify relative path to a format file. 21989 ASSERT_TRUE( 21990 FS.addFile("../../e/explicit.clang-format", 0, 21991 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 21992 Style = getStyle("file:../../e/explicit.clang-format", 21993 "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS); 21994 ASSERT_TRUE(static_cast<bool>(Style)); 21995 ASSERT_EQ(*Style, getGoogleStyle()); 21996 21997 // Specify path to a format file that does not exist. 21998 Style = getStyle("file:/e/missing.clang-format", "/e/sub/sub/sub/test.cpp", 21999 "LLVM", "", &FS); 22000 ASSERT_FALSE(static_cast<bool>(Style)); 22001 llvm::consumeError(Style.takeError()); 22002 22003 // Specify path to a file on the filesystem. 22004 SmallString<128> FormatFilePath; 22005 std::error_code ECF = llvm::sys::fs::createTemporaryFile( 22006 "FormatFileTest", "tpl", FormatFilePath); 22007 EXPECT_FALSE((bool)ECF); 22008 llvm::raw_fd_ostream FormatFileTest(FormatFilePath, ECF); 22009 EXPECT_FALSE((bool)ECF); 22010 FormatFileTest << "BasedOnStyle: Google\n"; 22011 FormatFileTest.close(); 22012 22013 SmallString<128> TestFilePath; 22014 std::error_code ECT = 22015 llvm::sys::fs::createTemporaryFile("CodeFileTest", "cc", TestFilePath); 22016 EXPECT_FALSE((bool)ECT); 22017 llvm::raw_fd_ostream CodeFileTest(TestFilePath, ECT); 22018 CodeFileTest << "int i;\n"; 22019 CodeFileTest.close(); 22020 22021 std::string format_file_arg = std::string("file:") + FormatFilePath.c_str(); 22022 Style = getStyle(format_file_arg, TestFilePath, "LLVM", "", nullptr); 22023 22024 llvm::sys::fs::remove(FormatFilePath.c_str()); 22025 llvm::sys::fs::remove(TestFilePath.c_str()); 22026 ASSERT_TRUE(static_cast<bool>(Style)); 22027 ASSERT_EQ(*Style, getGoogleStyle()); 22028 } 22029 22030 TEST_F(ReplacementTest, FormatCodeAfterReplacements) { 22031 // Column limit is 20. 22032 std::string Code = "Type *a =\n" 22033 " new Type();\n" 22034 "g(iiiii, 0, jjjjj,\n" 22035 " 0, kkkkk, 0, mm);\n" 22036 "int bad = format ;"; 22037 std::string Expected = "auto a = new Type();\n" 22038 "g(iiiii, nullptr,\n" 22039 " jjjjj, nullptr,\n" 22040 " kkkkk, nullptr,\n" 22041 " mm);\n" 22042 "int bad = format ;"; 22043 FileID ID = Context.createInMemoryFile("format.cpp", Code); 22044 tooling::Replacements Replaces = toReplacements( 22045 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6, 22046 "auto "), 22047 tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1, 22048 "nullptr"), 22049 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1, 22050 "nullptr"), 22051 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1, 22052 "nullptr")}); 22053 22054 FormatStyle Style = getLLVMStyle(); 22055 Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility. 22056 auto FormattedReplaces = formatReplacements(Code, Replaces, Style); 22057 EXPECT_TRUE(static_cast<bool>(FormattedReplaces)) 22058 << llvm::toString(FormattedReplaces.takeError()) << "\n"; 22059 auto Result = applyAllReplacements(Code, *FormattedReplaces); 22060 EXPECT_TRUE(static_cast<bool>(Result)); 22061 EXPECT_EQ(Expected, *Result); 22062 } 22063 22064 TEST_F(ReplacementTest, SortIncludesAfterReplacement) { 22065 std::string Code = "#include \"a.h\"\n" 22066 "#include \"c.h\"\n" 22067 "\n" 22068 "int main() {\n" 22069 " return 0;\n" 22070 "}"; 22071 std::string Expected = "#include \"a.h\"\n" 22072 "#include \"b.h\"\n" 22073 "#include \"c.h\"\n" 22074 "\n" 22075 "int main() {\n" 22076 " return 0;\n" 22077 "}"; 22078 FileID ID = Context.createInMemoryFile("fix.cpp", Code); 22079 tooling::Replacements Replaces = toReplacements( 22080 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0, 22081 "#include \"b.h\"\n")}); 22082 22083 FormatStyle Style = getLLVMStyle(); 22084 Style.SortIncludes = FormatStyle::SI_CaseSensitive; 22085 auto FormattedReplaces = formatReplacements(Code, Replaces, Style); 22086 EXPECT_TRUE(static_cast<bool>(FormattedReplaces)) 22087 << llvm::toString(FormattedReplaces.takeError()) << "\n"; 22088 auto Result = applyAllReplacements(Code, *FormattedReplaces); 22089 EXPECT_TRUE(static_cast<bool>(Result)); 22090 EXPECT_EQ(Expected, *Result); 22091 } 22092 22093 TEST_F(FormatTest, FormatSortsUsingDeclarations) { 22094 EXPECT_EQ("using std::cin;\n" 22095 "using std::cout;", 22096 format("using std::cout;\n" 22097 "using std::cin;", 22098 getGoogleStyle())); 22099 } 22100 22101 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) { 22102 FormatStyle Style = getLLVMStyle(); 22103 Style.Standard = FormatStyle::LS_Cpp03; 22104 // cpp03 recognize this string as identifier u8 and literal character 'a' 22105 EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style)); 22106 } 22107 22108 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) { 22109 // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers 22110 // all modes, including C++11, C++14 and C++17 22111 EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';")); 22112 } 22113 22114 TEST_F(FormatTest, DoNotFormatLikelyXml) { 22115 EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle())); 22116 EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle())); 22117 } 22118 22119 TEST_F(FormatTest, StructuredBindings) { 22120 // Structured bindings is a C++17 feature. 22121 // all modes, including C++11, C++14 and C++17 22122 verifyFormat("auto [a, b] = f();"); 22123 EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();")); 22124 EXPECT_EQ("const auto [a, b] = f();", format("const auto[a, b] = f();")); 22125 EXPECT_EQ("auto const [a, b] = f();", format("auto const[a, b] = f();")); 22126 EXPECT_EQ("auto const volatile [a, b] = f();", 22127 format("auto const volatile[a, b] = f();")); 22128 EXPECT_EQ("auto [a, b, c] = f();", format("auto [ a , b,c ] = f();")); 22129 EXPECT_EQ("auto &[a, b, c] = f();", 22130 format("auto &[ a , b,c ] = f();")); 22131 EXPECT_EQ("auto &&[a, b, c] = f();", 22132 format("auto &&[ a , b,c ] = f();")); 22133 EXPECT_EQ("auto const &[a, b] = f();", format("auto const&[a, b] = f();")); 22134 EXPECT_EQ("auto const volatile &&[a, b] = f();", 22135 format("auto const volatile &&[a, b] = f();")); 22136 EXPECT_EQ("auto const &&[a, b] = f();", 22137 format("auto const && [a, b] = f();")); 22138 EXPECT_EQ("const auto &[a, b] = f();", 22139 format("const auto & [a, b] = f();")); 22140 EXPECT_EQ("const auto volatile &&[a, b] = f();", 22141 format("const auto volatile &&[a, b] = f();")); 22142 EXPECT_EQ("volatile const auto &&[a, b] = f();", 22143 format("volatile const auto &&[a, b] = f();")); 22144 EXPECT_EQ("const auto &&[a, b] = f();", 22145 format("const auto && [a, b] = f();")); 22146 22147 // Make sure we don't mistake structured bindings for lambdas. 22148 FormatStyle PointerMiddle = getLLVMStyle(); 22149 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle; 22150 verifyFormat("auto [a1, b]{A * i};", getGoogleStyle()); 22151 verifyFormat("auto [a2, b]{A * i};", getLLVMStyle()); 22152 verifyFormat("auto [a3, b]{A * i};", PointerMiddle); 22153 verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle()); 22154 verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle()); 22155 verifyFormat("auto const [a3, b]{A * i};", PointerMiddle); 22156 verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle()); 22157 verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle()); 22158 verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle); 22159 verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle()); 22160 verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle()); 22161 verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle); 22162 22163 EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}", 22164 format("for (const auto && [a, b] : some_range) {\n}")); 22165 EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}", 22166 format("for (const auto & [a, b] : some_range) {\n}")); 22167 EXPECT_EQ("for (const auto [a, b] : some_range) {\n}", 22168 format("for (const auto[a, b] : some_range) {\n}")); 22169 EXPECT_EQ("auto [x, y](expr);", format("auto[x,y] (expr);")); 22170 EXPECT_EQ("auto &[x, y](expr);", format("auto & [x,y] (expr);")); 22171 EXPECT_EQ("auto &&[x, y](expr);", format("auto && [x,y] (expr);")); 22172 EXPECT_EQ("auto const &[x, y](expr);", 22173 format("auto const & [x,y] (expr);")); 22174 EXPECT_EQ("auto const &&[x, y](expr);", 22175 format("auto const && [x,y] (expr);")); 22176 EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y] {expr};")); 22177 EXPECT_EQ("auto const &[x, y]{expr};", 22178 format("auto const & [x,y] {expr};")); 22179 EXPECT_EQ("auto const &&[x, y]{expr};", 22180 format("auto const && [x,y] {expr};")); 22181 22182 FormatStyle Spaces = getLLVMStyle(); 22183 Spaces.SpacesInSquareBrackets = true; 22184 verifyFormat("auto [ a, b ] = f();", Spaces); 22185 verifyFormat("auto &&[ a, b ] = f();", Spaces); 22186 verifyFormat("auto &[ a, b ] = f();", Spaces); 22187 verifyFormat("auto const &&[ a, b ] = f();", Spaces); 22188 verifyFormat("auto const &[ a, b ] = f();", Spaces); 22189 } 22190 22191 TEST_F(FormatTest, FileAndCode) { 22192 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", "")); 22193 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", "")); 22194 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", "")); 22195 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "")); 22196 EXPECT_EQ(FormatStyle::LK_ObjC, 22197 guessLanguage("foo.h", "@interface Foo\n@end\n")); 22198 EXPECT_EQ( 22199 FormatStyle::LK_ObjC, 22200 guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }")); 22201 EXPECT_EQ(FormatStyle::LK_ObjC, 22202 guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))")); 22203 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;")); 22204 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", "")); 22205 EXPECT_EQ(FormatStyle::LK_ObjC, 22206 guessLanguage("foo", "@interface Foo\n@end\n")); 22207 EXPECT_EQ(FormatStyle::LK_ObjC, 22208 guessLanguage("foo.h", "int DoStuff(CGRect rect);\n")); 22209 EXPECT_EQ( 22210 FormatStyle::LK_ObjC, 22211 guessLanguage("foo.h", 22212 "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n")); 22213 EXPECT_EQ( 22214 FormatStyle::LK_Cpp, 22215 guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;")); 22216 } 22217 22218 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) { 22219 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];")); 22220 EXPECT_EQ(FormatStyle::LK_ObjC, 22221 guessLanguage("foo.h", "array[[calculator getIndex]];")); 22222 EXPECT_EQ(FormatStyle::LK_Cpp, 22223 guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];")); 22224 EXPECT_EQ( 22225 FormatStyle::LK_Cpp, 22226 guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];")); 22227 EXPECT_EQ(FormatStyle::LK_ObjC, 22228 guessLanguage("foo.h", "[[noreturn foo] bar];")); 22229 EXPECT_EQ(FormatStyle::LK_Cpp, 22230 guessLanguage("foo.h", "[[clang::fallthrough]];")); 22231 EXPECT_EQ(FormatStyle::LK_ObjC, 22232 guessLanguage("foo.h", "[[clang:fallthrough] foo];")); 22233 EXPECT_EQ(FormatStyle::LK_Cpp, 22234 guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];")); 22235 EXPECT_EQ(FormatStyle::LK_Cpp, 22236 guessLanguage("foo.h", "[[using clang: fallthrough]];")); 22237 EXPECT_EQ(FormatStyle::LK_ObjC, 22238 guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];")); 22239 EXPECT_EQ(FormatStyle::LK_Cpp, 22240 guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];")); 22241 EXPECT_EQ( 22242 FormatStyle::LK_Cpp, 22243 guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)")); 22244 EXPECT_EQ( 22245 FormatStyle::LK_Cpp, 22246 guessLanguage("foo.h", 22247 "[[clang::callable_when(\"unconsumed\", \"unknown\")]]")); 22248 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]")); 22249 } 22250 22251 TEST_F(FormatTest, GuessLanguageWithCaret) { 22252 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);")); 22253 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);")); 22254 EXPECT_EQ(FormatStyle::LK_ObjC, 22255 guessLanguage("foo.h", "int(^)(char, float);")); 22256 EXPECT_EQ(FormatStyle::LK_ObjC, 22257 guessLanguage("foo.h", "int(^foo)(char, float);")); 22258 EXPECT_EQ(FormatStyle::LK_ObjC, 22259 guessLanguage("foo.h", "int(^foo[10])(char, float);")); 22260 EXPECT_EQ(FormatStyle::LK_ObjC, 22261 guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);")); 22262 EXPECT_EQ( 22263 FormatStyle::LK_ObjC, 22264 guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);")); 22265 } 22266 22267 TEST_F(FormatTest, GuessLanguageWithPragmas) { 22268 EXPECT_EQ(FormatStyle::LK_Cpp, 22269 guessLanguage("foo.h", "__pragma(warning(disable:))")); 22270 EXPECT_EQ(FormatStyle::LK_Cpp, 22271 guessLanguage("foo.h", "#pragma(warning(disable:))")); 22272 EXPECT_EQ(FormatStyle::LK_Cpp, 22273 guessLanguage("foo.h", "_Pragma(warning(disable:))")); 22274 } 22275 22276 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) { 22277 // ASM symbolic names are identifiers that must be surrounded by [] without 22278 // space in between: 22279 // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands 22280 22281 // Example from https://bugs.llvm.org/show_bug.cgi?id=45108. 22282 verifyFormat(R"(// 22283 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result)); 22284 )"); 22285 22286 // A list of several ASM symbolic names. 22287 verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)"); 22288 22289 // ASM symbolic names in inline ASM with inputs and outputs. 22290 verifyFormat(R"(// 22291 asm("cmoveq %1, %2, %[result]" 22292 : [result] "=r"(result) 22293 : "r"(test), "r"(new), "[result]"(old)); 22294 )"); 22295 22296 // ASM symbolic names in inline ASM with no outputs. 22297 verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)"); 22298 } 22299 22300 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) { 22301 EXPECT_EQ(FormatStyle::LK_Cpp, 22302 guessLanguage("foo.h", "void f() {\n" 22303 " asm (\"mov %[e], %[d]\"\n" 22304 " : [d] \"=rm\" (d)\n" 22305 " [e] \"rm\" (*e));\n" 22306 "}")); 22307 EXPECT_EQ(FormatStyle::LK_Cpp, 22308 guessLanguage("foo.h", "void f() {\n" 22309 " _asm (\"mov %[e], %[d]\"\n" 22310 " : [d] \"=rm\" (d)\n" 22311 " [e] \"rm\" (*e));\n" 22312 "}")); 22313 EXPECT_EQ(FormatStyle::LK_Cpp, 22314 guessLanguage("foo.h", "void f() {\n" 22315 " __asm (\"mov %[e], %[d]\"\n" 22316 " : [d] \"=rm\" (d)\n" 22317 " [e] \"rm\" (*e));\n" 22318 "}")); 22319 EXPECT_EQ(FormatStyle::LK_Cpp, 22320 guessLanguage("foo.h", "void f() {\n" 22321 " __asm__ (\"mov %[e], %[d]\"\n" 22322 " : [d] \"=rm\" (d)\n" 22323 " [e] \"rm\" (*e));\n" 22324 "}")); 22325 EXPECT_EQ(FormatStyle::LK_Cpp, 22326 guessLanguage("foo.h", "void f() {\n" 22327 " asm (\"mov %[e], %[d]\"\n" 22328 " : [d] \"=rm\" (d),\n" 22329 " [e] \"rm\" (*e));\n" 22330 "}")); 22331 EXPECT_EQ(FormatStyle::LK_Cpp, 22332 guessLanguage("foo.h", "void f() {\n" 22333 " asm volatile (\"mov %[e], %[d]\"\n" 22334 " : [d] \"=rm\" (d)\n" 22335 " [e] \"rm\" (*e));\n" 22336 "}")); 22337 } 22338 22339 TEST_F(FormatTest, GuessLanguageWithChildLines) { 22340 EXPECT_EQ(FormatStyle::LK_Cpp, 22341 guessLanguage("foo.h", "#define FOO ({ std::string s; })")); 22342 EXPECT_EQ(FormatStyle::LK_ObjC, 22343 guessLanguage("foo.h", "#define FOO ({ NSString *s; })")); 22344 EXPECT_EQ( 22345 FormatStyle::LK_Cpp, 22346 guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })")); 22347 EXPECT_EQ( 22348 FormatStyle::LK_ObjC, 22349 guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })")); 22350 } 22351 22352 TEST_F(FormatTest, TypenameMacros) { 22353 std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"}; 22354 22355 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353 22356 FormatStyle Google = getGoogleStyleWithColumns(0); 22357 Google.TypenameMacros = TypenameMacros; 22358 verifyFormat("struct foo {\n" 22359 " int bar;\n" 22360 " TAILQ_ENTRY(a) bleh;\n" 22361 "};", 22362 Google); 22363 22364 FormatStyle Macros = getLLVMStyle(); 22365 Macros.TypenameMacros = TypenameMacros; 22366 22367 verifyFormat("STACK_OF(int) a;", Macros); 22368 verifyFormat("STACK_OF(int) *a;", Macros); 22369 verifyFormat("STACK_OF(int const *) *a;", Macros); 22370 verifyFormat("STACK_OF(int *const) *a;", Macros); 22371 verifyFormat("STACK_OF(int, string) a;", Macros); 22372 verifyFormat("STACK_OF(LIST(int)) a;", Macros); 22373 verifyFormat("STACK_OF(LIST(int)) a, b;", Macros); 22374 verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros); 22375 verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros); 22376 verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros); 22377 verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros); 22378 22379 Macros.PointerAlignment = FormatStyle::PAS_Left; 22380 verifyFormat("STACK_OF(int)* a;", Macros); 22381 verifyFormat("STACK_OF(int*)* a;", Macros); 22382 verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros); 22383 verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros); 22384 verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros); 22385 } 22386 22387 TEST_F(FormatTest, AtomicQualifier) { 22388 // Check that we treate _Atomic as a type and not a function call 22389 FormatStyle Google = getGoogleStyleWithColumns(0); 22390 verifyFormat("struct foo {\n" 22391 " int a1;\n" 22392 " _Atomic(a) a2;\n" 22393 " _Atomic(_Atomic(int) *const) a3;\n" 22394 "};", 22395 Google); 22396 verifyFormat("_Atomic(uint64_t) a;"); 22397 verifyFormat("_Atomic(uint64_t) *a;"); 22398 verifyFormat("_Atomic(uint64_t const *) *a;"); 22399 verifyFormat("_Atomic(uint64_t *const) *a;"); 22400 verifyFormat("_Atomic(const uint64_t *) *a;"); 22401 verifyFormat("_Atomic(uint64_t) a;"); 22402 verifyFormat("_Atomic(_Atomic(uint64_t)) a;"); 22403 verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;"); 22404 verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}"); 22405 verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);"); 22406 22407 verifyFormat("_Atomic(uint64_t) *s(InitValue);"); 22408 verifyFormat("_Atomic(uint64_t) *s{InitValue};"); 22409 FormatStyle Style = getLLVMStyle(); 22410 Style.PointerAlignment = FormatStyle::PAS_Left; 22411 verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style); 22412 verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style); 22413 verifyFormat("_Atomic(int)* a;", Style); 22414 verifyFormat("_Atomic(int*)* a;", Style); 22415 verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style); 22416 22417 Style.SpacesInCStyleCastParentheses = true; 22418 Style.SpacesInParentheses = false; 22419 verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style); 22420 Style.SpacesInCStyleCastParentheses = false; 22421 Style.SpacesInParentheses = true; 22422 verifyFormat("x = (_Atomic( uint64_t ))*a;", Style); 22423 verifyFormat("x = (_Atomic( uint64_t ))&a;", Style); 22424 } 22425 22426 TEST_F(FormatTest, AmbersandInLamda) { 22427 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899 22428 FormatStyle AlignStyle = getLLVMStyle(); 22429 AlignStyle.PointerAlignment = FormatStyle::PAS_Left; 22430 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle); 22431 AlignStyle.PointerAlignment = FormatStyle::PAS_Right; 22432 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle); 22433 } 22434 22435 TEST_F(FormatTest, SpacesInConditionalStatement) { 22436 FormatStyle Spaces = getLLVMStyle(); 22437 Spaces.IfMacros.clear(); 22438 Spaces.IfMacros.push_back("MYIF"); 22439 Spaces.SpacesInConditionalStatement = true; 22440 verifyFormat("for ( int i = 0; i; i++ )\n continue;", Spaces); 22441 verifyFormat("if ( !a )\n return;", Spaces); 22442 verifyFormat("if ( a )\n return;", Spaces); 22443 verifyFormat("if constexpr ( a )\n return;", Spaces); 22444 verifyFormat("MYIF ( a )\n return;", Spaces); 22445 verifyFormat("MYIF ( a )\n return;\nelse MYIF ( b )\n return;", Spaces); 22446 verifyFormat("MYIF ( a )\n return;\nelse\n return;", Spaces); 22447 verifyFormat("switch ( a )\ncase 1:\n return;", Spaces); 22448 verifyFormat("while ( a )\n return;", Spaces); 22449 verifyFormat("while ( (a && b) )\n return;", Spaces); 22450 verifyFormat("do {\n} while ( 1 != 0 );", Spaces); 22451 verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces); 22452 // Check that space on the left of "::" is inserted as expected at beginning 22453 // of condition. 22454 verifyFormat("while ( ::func() )\n return;", Spaces); 22455 22456 // Check impact of ControlStatementsExceptControlMacros is honored. 22457 Spaces.SpaceBeforeParens = 22458 FormatStyle::SBPO_ControlStatementsExceptControlMacros; 22459 verifyFormat("MYIF( a )\n return;", Spaces); 22460 verifyFormat("MYIF( a )\n return;\nelse MYIF( b )\n return;", Spaces); 22461 verifyFormat("MYIF( a )\n return;\nelse\n return;", Spaces); 22462 } 22463 22464 TEST_F(FormatTest, AlternativeOperators) { 22465 // Test case for ensuring alternate operators are not 22466 // combined with their right most neighbour. 22467 verifyFormat("int a and b;"); 22468 verifyFormat("int a and_eq b;"); 22469 verifyFormat("int a bitand b;"); 22470 verifyFormat("int a bitor b;"); 22471 verifyFormat("int a compl b;"); 22472 verifyFormat("int a not b;"); 22473 verifyFormat("int a not_eq b;"); 22474 verifyFormat("int a or b;"); 22475 verifyFormat("int a xor b;"); 22476 verifyFormat("int a xor_eq b;"); 22477 verifyFormat("return this not_eq bitand other;"); 22478 verifyFormat("bool operator not_eq(const X bitand other)"); 22479 22480 verifyFormat("int a and 5;"); 22481 verifyFormat("int a and_eq 5;"); 22482 verifyFormat("int a bitand 5;"); 22483 verifyFormat("int a bitor 5;"); 22484 verifyFormat("int a compl 5;"); 22485 verifyFormat("int a not 5;"); 22486 verifyFormat("int a not_eq 5;"); 22487 verifyFormat("int a or 5;"); 22488 verifyFormat("int a xor 5;"); 22489 verifyFormat("int a xor_eq 5;"); 22490 22491 verifyFormat("int a compl(5);"); 22492 verifyFormat("int a not(5);"); 22493 22494 /* FIXME handle alternate tokens 22495 * https://en.cppreference.com/w/cpp/language/operator_alternative 22496 // alternative tokens 22497 verifyFormat("compl foo();"); // ~foo(); 22498 verifyFormat("foo() <%%>;"); // foo(); 22499 verifyFormat("void foo() <%%>;"); // void foo(){} 22500 verifyFormat("int a <:1:>;"); // int a[1];[ 22501 verifyFormat("%:define ABC abc"); // #define ABC abc 22502 verifyFormat("%:%:"); // ## 22503 */ 22504 } 22505 22506 TEST_F(FormatTest, STLWhileNotDefineChed) { 22507 verifyFormat("#if defined(while)\n" 22508 "#define while EMIT WARNING C4005\n" 22509 "#endif // while"); 22510 } 22511 22512 TEST_F(FormatTest, OperatorSpacing) { 22513 FormatStyle Style = getLLVMStyle(); 22514 Style.PointerAlignment = FormatStyle::PAS_Right; 22515 verifyFormat("Foo::operator*();", Style); 22516 verifyFormat("Foo::operator void *();", Style); 22517 verifyFormat("Foo::operator void **();", Style); 22518 verifyFormat("Foo::operator void *&();", Style); 22519 verifyFormat("Foo::operator void *&&();", Style); 22520 verifyFormat("Foo::operator void const *();", Style); 22521 verifyFormat("Foo::operator void const **();", Style); 22522 verifyFormat("Foo::operator void const *&();", Style); 22523 verifyFormat("Foo::operator void const *&&();", Style); 22524 verifyFormat("Foo::operator()(void *);", Style); 22525 verifyFormat("Foo::operator*(void *);", Style); 22526 verifyFormat("Foo::operator*();", Style); 22527 verifyFormat("Foo::operator**();", Style); 22528 verifyFormat("Foo::operator&();", Style); 22529 verifyFormat("Foo::operator<int> *();", Style); 22530 verifyFormat("Foo::operator<Foo> *();", Style); 22531 verifyFormat("Foo::operator<int> **();", Style); 22532 verifyFormat("Foo::operator<Foo> **();", Style); 22533 verifyFormat("Foo::operator<int> &();", Style); 22534 verifyFormat("Foo::operator<Foo> &();", Style); 22535 verifyFormat("Foo::operator<int> &&();", Style); 22536 verifyFormat("Foo::operator<Foo> &&();", Style); 22537 verifyFormat("Foo::operator<int> *&();", Style); 22538 verifyFormat("Foo::operator<Foo> *&();", Style); 22539 verifyFormat("Foo::operator<int> *&&();", Style); 22540 verifyFormat("Foo::operator<Foo> *&&();", Style); 22541 verifyFormat("operator*(int (*)(), class Foo);", Style); 22542 22543 verifyFormat("Foo::operator&();", Style); 22544 verifyFormat("Foo::operator void &();", Style); 22545 verifyFormat("Foo::operator void const &();", Style); 22546 verifyFormat("Foo::operator()(void &);", Style); 22547 verifyFormat("Foo::operator&(void &);", Style); 22548 verifyFormat("Foo::operator&();", Style); 22549 verifyFormat("operator&(int (&)(), class Foo);", Style); 22550 verifyFormat("operator&&(int (&)(), class Foo);", Style); 22551 22552 verifyFormat("Foo::operator&&();", Style); 22553 verifyFormat("Foo::operator**();", Style); 22554 verifyFormat("Foo::operator void &&();", Style); 22555 verifyFormat("Foo::operator void const &&();", Style); 22556 verifyFormat("Foo::operator()(void &&);", Style); 22557 verifyFormat("Foo::operator&&(void &&);", Style); 22558 verifyFormat("Foo::operator&&();", Style); 22559 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 22560 verifyFormat("operator const nsTArrayRight<E> &()", Style); 22561 verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()", 22562 Style); 22563 verifyFormat("operator void **()", Style); 22564 verifyFormat("operator const FooRight<Object> &()", Style); 22565 verifyFormat("operator const FooRight<Object> *()", Style); 22566 verifyFormat("operator const FooRight<Object> **()", Style); 22567 verifyFormat("operator const FooRight<Object> *&()", Style); 22568 verifyFormat("operator const FooRight<Object> *&&()", Style); 22569 22570 Style.PointerAlignment = FormatStyle::PAS_Left; 22571 verifyFormat("Foo::operator*();", Style); 22572 verifyFormat("Foo::operator**();", Style); 22573 verifyFormat("Foo::operator void*();", Style); 22574 verifyFormat("Foo::operator void**();", Style); 22575 verifyFormat("Foo::operator void*&();", Style); 22576 verifyFormat("Foo::operator void*&&();", Style); 22577 verifyFormat("Foo::operator void const*();", Style); 22578 verifyFormat("Foo::operator void const**();", Style); 22579 verifyFormat("Foo::operator void const*&();", Style); 22580 verifyFormat("Foo::operator void const*&&();", Style); 22581 verifyFormat("Foo::operator/*comment*/ void*();", Style); 22582 verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style); 22583 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style); 22584 verifyFormat("Foo::operator()(void*);", Style); 22585 verifyFormat("Foo::operator*(void*);", Style); 22586 verifyFormat("Foo::operator*();", Style); 22587 verifyFormat("Foo::operator<int>*();", Style); 22588 verifyFormat("Foo::operator<Foo>*();", Style); 22589 verifyFormat("Foo::operator<int>**();", Style); 22590 verifyFormat("Foo::operator<Foo>**();", Style); 22591 verifyFormat("Foo::operator<Foo>*&();", Style); 22592 verifyFormat("Foo::operator<int>&();", Style); 22593 verifyFormat("Foo::operator<Foo>&();", Style); 22594 verifyFormat("Foo::operator<int>&&();", Style); 22595 verifyFormat("Foo::operator<Foo>&&();", Style); 22596 verifyFormat("Foo::operator<int>*&();", Style); 22597 verifyFormat("Foo::operator<Foo>*&();", Style); 22598 verifyFormat("operator*(int (*)(), class Foo);", Style); 22599 22600 verifyFormat("Foo::operator&();", Style); 22601 verifyFormat("Foo::operator void&();", Style); 22602 verifyFormat("Foo::operator void const&();", Style); 22603 verifyFormat("Foo::operator/*comment*/ void&();", Style); 22604 verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style); 22605 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style); 22606 verifyFormat("Foo::operator()(void&);", Style); 22607 verifyFormat("Foo::operator&(void&);", Style); 22608 verifyFormat("Foo::operator&();", Style); 22609 verifyFormat("operator&(int (&)(), class Foo);", Style); 22610 verifyFormat("operator&(int (&&)(), class Foo);", Style); 22611 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 22612 22613 verifyFormat("Foo::operator&&();", Style); 22614 verifyFormat("Foo::operator void&&();", Style); 22615 verifyFormat("Foo::operator void const&&();", Style); 22616 verifyFormat("Foo::operator/*comment*/ void&&();", Style); 22617 verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style); 22618 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style); 22619 verifyFormat("Foo::operator()(void&&);", Style); 22620 verifyFormat("Foo::operator&&(void&&);", Style); 22621 verifyFormat("Foo::operator&&();", Style); 22622 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 22623 verifyFormat("operator const nsTArrayLeft<E>&()", Style); 22624 verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()", 22625 Style); 22626 verifyFormat("operator void**()", Style); 22627 verifyFormat("operator const FooLeft<Object>&()", Style); 22628 verifyFormat("operator const FooLeft<Object>*()", Style); 22629 verifyFormat("operator const FooLeft<Object>**()", Style); 22630 verifyFormat("operator const FooLeft<Object>*&()", Style); 22631 verifyFormat("operator const FooLeft<Object>*&&()", Style); 22632 22633 // PR45107 22634 verifyFormat("operator Vector<String>&();", Style); 22635 verifyFormat("operator const Vector<String>&();", Style); 22636 verifyFormat("operator foo::Bar*();", Style); 22637 verifyFormat("operator const Foo<X>::Bar<Y>*();", Style); 22638 verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();", 22639 Style); 22640 22641 Style.PointerAlignment = FormatStyle::PAS_Middle; 22642 verifyFormat("Foo::operator*();", Style); 22643 verifyFormat("Foo::operator void *();", Style); 22644 verifyFormat("Foo::operator()(void *);", Style); 22645 verifyFormat("Foo::operator*(void *);", Style); 22646 verifyFormat("Foo::operator*();", Style); 22647 verifyFormat("operator*(int (*)(), class Foo);", Style); 22648 22649 verifyFormat("Foo::operator&();", Style); 22650 verifyFormat("Foo::operator void &();", Style); 22651 verifyFormat("Foo::operator void const &();", Style); 22652 verifyFormat("Foo::operator()(void &);", Style); 22653 verifyFormat("Foo::operator&(void &);", Style); 22654 verifyFormat("Foo::operator&();", Style); 22655 verifyFormat("operator&(int (&)(), class Foo);", Style); 22656 22657 verifyFormat("Foo::operator&&();", Style); 22658 verifyFormat("Foo::operator void &&();", Style); 22659 verifyFormat("Foo::operator void const &&();", Style); 22660 verifyFormat("Foo::operator()(void &&);", Style); 22661 verifyFormat("Foo::operator&&(void &&);", Style); 22662 verifyFormat("Foo::operator&&();", Style); 22663 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 22664 } 22665 22666 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) { 22667 FormatStyle Style = getLLVMStyle(); 22668 // PR46157 22669 verifyFormat("foo(operator+, -42);", Style); 22670 verifyFormat("foo(operator++, -42);", Style); 22671 verifyFormat("foo(operator--, -42);", Style); 22672 verifyFormat("foo(-42, operator--);", Style); 22673 verifyFormat("foo(-42, operator, );", Style); 22674 verifyFormat("foo(operator, , -42);", Style); 22675 } 22676 22677 TEST_F(FormatTest, WhitespaceSensitiveMacros) { 22678 FormatStyle Style = getLLVMStyle(); 22679 Style.WhitespaceSensitiveMacros.push_back("FOO"); 22680 22681 // Don't use the helpers here, since 'mess up' will change the whitespace 22682 // and these are all whitespace sensitive by definition 22683 EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);", 22684 format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style)); 22685 EXPECT_EQ( 22686 "FOO(String-ized&Messy+But\\(: :Still)=Intentional);", 22687 format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style)); 22688 EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);", 22689 format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style)); 22690 EXPECT_EQ("FOO(String-ized&Messy+But,: :\n" 22691 " Still=Intentional);", 22692 format("FOO(String-ized&Messy+But,: :\n" 22693 " Still=Intentional);", 22694 Style)); 22695 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 22696 EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n" 22697 " Still=Intentional);", 22698 format("FOO(String-ized=&Messy+But,: :\n" 22699 " Still=Intentional);", 22700 Style)); 22701 22702 Style.ColumnLimit = 21; 22703 EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);", 22704 format("FOO(String-ized&Messy+But: :Still=Intentional);", Style)); 22705 } 22706 22707 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) { 22708 // These tests are not in NamespaceFixer because that doesn't 22709 // test its interaction with line wrapping 22710 FormatStyle Style = getLLVMStyleWithColumns(80); 22711 verifyFormat("namespace {\n" 22712 "int i;\n" 22713 "int j;\n" 22714 "} // namespace", 22715 Style); 22716 22717 verifyFormat("namespace AAA {\n" 22718 "int i;\n" 22719 "int j;\n" 22720 "} // namespace AAA", 22721 Style); 22722 22723 EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n" 22724 "int i;\n" 22725 "int j;\n" 22726 "} // namespace Averyveryveryverylongnamespace", 22727 format("namespace Averyveryveryverylongnamespace {\n" 22728 "int i;\n" 22729 "int j;\n" 22730 "}", 22731 Style)); 22732 22733 EXPECT_EQ( 22734 "namespace " 22735 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n" 22736 " went::mad::now {\n" 22737 "int i;\n" 22738 "int j;\n" 22739 "} // namespace\n" 22740 " // " 22741 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::" 22742 "went::mad::now", 22743 format("namespace " 22744 "would::it::save::you::a::lot::of::time::if_::i::" 22745 "just::gave::up::and_::went::mad::now {\n" 22746 "int i;\n" 22747 "int j;\n" 22748 "}", 22749 Style)); 22750 22751 // This used to duplicate the comment again and again on subsequent runs 22752 EXPECT_EQ( 22753 "namespace " 22754 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n" 22755 " went::mad::now {\n" 22756 "int i;\n" 22757 "int j;\n" 22758 "} // namespace\n" 22759 " // " 22760 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::" 22761 "went::mad::now", 22762 format("namespace " 22763 "would::it::save::you::a::lot::of::time::if_::i::" 22764 "just::gave::up::and_::went::mad::now {\n" 22765 "int i;\n" 22766 "int j;\n" 22767 "} // namespace\n" 22768 " // " 22769 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::" 22770 "and_::went::mad::now", 22771 Style)); 22772 } 22773 22774 TEST_F(FormatTest, LikelyUnlikely) { 22775 FormatStyle Style = getLLVMStyle(); 22776 22777 verifyFormat("if (argc > 5) [[unlikely]] {\n" 22778 " return 29;\n" 22779 "}", 22780 Style); 22781 22782 verifyFormat("if (argc > 5) [[likely]] {\n" 22783 " return 29;\n" 22784 "}", 22785 Style); 22786 22787 verifyFormat("if (argc > 5) [[unlikely]] {\n" 22788 " return 29;\n" 22789 "} else [[likely]] {\n" 22790 " return 42;\n" 22791 "}\n", 22792 Style); 22793 22794 verifyFormat("if (argc > 5) [[unlikely]] {\n" 22795 " return 29;\n" 22796 "} else if (argc > 10) [[likely]] {\n" 22797 " return 99;\n" 22798 "} else {\n" 22799 " return 42;\n" 22800 "}\n", 22801 Style); 22802 22803 verifyFormat("if (argc > 5) [[gnu::unused]] {\n" 22804 " return 29;\n" 22805 "}", 22806 Style); 22807 22808 verifyFormat("if (argc > 5) [[unlikely]]\n" 22809 " return 29;\n", 22810 Style); 22811 verifyFormat("if (argc > 5) [[likely]]\n" 22812 " return 29;\n", 22813 Style); 22814 22815 Style.AttributeMacros.push_back("UNLIKELY"); 22816 Style.AttributeMacros.push_back("LIKELY"); 22817 verifyFormat("if (argc > 5) UNLIKELY\n" 22818 " return 29;\n", 22819 Style); 22820 22821 verifyFormat("if (argc > 5) UNLIKELY {\n" 22822 " return 29;\n" 22823 "}", 22824 Style); 22825 verifyFormat("if (argc > 5) UNLIKELY {\n" 22826 " return 29;\n" 22827 "} else [[likely]] {\n" 22828 " return 42;\n" 22829 "}\n", 22830 Style); 22831 verifyFormat("if (argc > 5) UNLIKELY {\n" 22832 " return 29;\n" 22833 "} else LIKELY {\n" 22834 " return 42;\n" 22835 "}\n", 22836 Style); 22837 verifyFormat("if (argc > 5) [[unlikely]] {\n" 22838 " return 29;\n" 22839 "} else LIKELY {\n" 22840 " return 42;\n" 22841 "}\n", 22842 Style); 22843 } 22844 22845 TEST_F(FormatTest, PenaltyIndentedWhitespace) { 22846 verifyFormat("Constructor()\n" 22847 " : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 22848 " aaaa(aaaaaaaaaaaaaaaaaa, " 22849 "aaaaaaaaaaaaaaaaaat))"); 22850 verifyFormat("Constructor()\n" 22851 " : aaaaaaaaaaaaa(aaaaaa), " 22852 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)"); 22853 22854 FormatStyle StyleWithWhitespacePenalty = getLLVMStyle(); 22855 StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5; 22856 verifyFormat("Constructor()\n" 22857 " : aaaaaa(aaaaaa),\n" 22858 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 22859 " aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))", 22860 StyleWithWhitespacePenalty); 22861 verifyFormat("Constructor()\n" 22862 " : aaaaaaaaaaaaa(aaaaaa), " 22863 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)", 22864 StyleWithWhitespacePenalty); 22865 } 22866 22867 TEST_F(FormatTest, LLVMDefaultStyle) { 22868 FormatStyle Style = getLLVMStyle(); 22869 verifyFormat("extern \"C\" {\n" 22870 "int foo();\n" 22871 "}", 22872 Style); 22873 } 22874 TEST_F(FormatTest, GNUDefaultStyle) { 22875 FormatStyle Style = getGNUStyle(); 22876 verifyFormat("extern \"C\"\n" 22877 "{\n" 22878 " int foo ();\n" 22879 "}", 22880 Style); 22881 } 22882 TEST_F(FormatTest, MozillaDefaultStyle) { 22883 FormatStyle Style = getMozillaStyle(); 22884 verifyFormat("extern \"C\"\n" 22885 "{\n" 22886 " int foo();\n" 22887 "}", 22888 Style); 22889 } 22890 TEST_F(FormatTest, GoogleDefaultStyle) { 22891 FormatStyle Style = getGoogleStyle(); 22892 verifyFormat("extern \"C\" {\n" 22893 "int foo();\n" 22894 "}", 22895 Style); 22896 } 22897 TEST_F(FormatTest, ChromiumDefaultStyle) { 22898 FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp); 22899 verifyFormat("extern \"C\" {\n" 22900 "int foo();\n" 22901 "}", 22902 Style); 22903 } 22904 TEST_F(FormatTest, MicrosoftDefaultStyle) { 22905 FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp); 22906 verifyFormat("extern \"C\"\n" 22907 "{\n" 22908 " int foo();\n" 22909 "}", 22910 Style); 22911 } 22912 TEST_F(FormatTest, WebKitDefaultStyle) { 22913 FormatStyle Style = getWebKitStyle(); 22914 verifyFormat("extern \"C\" {\n" 22915 "int foo();\n" 22916 "}", 22917 Style); 22918 } 22919 22920 TEST_F(FormatTest, ConceptsAndRequires) { 22921 FormatStyle Style = getLLVMStyle(); 22922 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 22923 22924 verifyFormat("template <typename T>\n" 22925 "concept Hashable = requires(T a) {\n" 22926 " { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;\n" 22927 "};", 22928 Style); 22929 verifyFormat("template <typename T>\n" 22930 "concept EqualityComparable = requires(T a, T b) {\n" 22931 " { a == b } -> bool;\n" 22932 "};", 22933 Style); 22934 verifyFormat("template <typename T>\n" 22935 "concept EqualityComparable = requires(T a, T b) {\n" 22936 " { a == b } -> bool;\n" 22937 " { a != b } -> bool;\n" 22938 "};", 22939 Style); 22940 verifyFormat("template <typename T>\n" 22941 "concept EqualityComparable = requires(T a, T b) {\n" 22942 " { a == b } -> bool;\n" 22943 " { a != b } -> bool;\n" 22944 "};", 22945 Style); 22946 22947 verifyFormat("template <typename It>\n" 22948 "requires Iterator<It>\n" 22949 "void sort(It begin, It end) {\n" 22950 " //....\n" 22951 "}", 22952 Style); 22953 22954 verifyFormat("template <typename T>\n" 22955 "concept Large = sizeof(T) > 10;", 22956 Style); 22957 22958 verifyFormat("template <typename T, typename U>\n" 22959 "concept FooableWith = requires(T t, U u) {\n" 22960 " typename T::foo_type;\n" 22961 " { t.foo(u) } -> typename T::foo_type;\n" 22962 " t++;\n" 22963 "};\n" 22964 "void doFoo(FooableWith<int> auto t) {\n" 22965 " t.foo(3);\n" 22966 "}", 22967 Style); 22968 verifyFormat("template <typename T>\n" 22969 "concept Context = sizeof(T) == 1;", 22970 Style); 22971 verifyFormat("template <typename T>\n" 22972 "concept Context = is_specialization_of_v<context, T>;", 22973 Style); 22974 verifyFormat("template <typename T>\n" 22975 "concept Node = std::is_object_v<T>;", 22976 Style); 22977 verifyFormat("template <typename T>\n" 22978 "concept Tree = true;", 22979 Style); 22980 22981 verifyFormat("template <typename T> int g(T i) requires Concept1<I> {\n" 22982 " //...\n" 22983 "}", 22984 Style); 22985 22986 verifyFormat( 22987 "template <typename T> int g(T i) requires Concept1<I> && Concept2<I> {\n" 22988 " //...\n" 22989 "}", 22990 Style); 22991 22992 verifyFormat( 22993 "template <typename T> int g(T i) requires Concept1<I> || Concept2<I> {\n" 22994 " //...\n" 22995 "}", 22996 Style); 22997 22998 verifyFormat("template <typename T>\n" 22999 "veryveryvery_long_return_type g(T i) requires Concept1<I> || " 23000 "Concept2<I> {\n" 23001 " //...\n" 23002 "}", 23003 Style); 23004 23005 verifyFormat("template <typename T>\n" 23006 "veryveryvery_long_return_type g(T i) requires Concept1<I> && " 23007 "Concept2<I> {\n" 23008 " //...\n" 23009 "}", 23010 Style); 23011 23012 verifyFormat( 23013 "template <typename T>\n" 23014 "veryveryvery_long_return_type g(T i) requires Concept1 && Concept2 {\n" 23015 " //...\n" 23016 "}", 23017 Style); 23018 23019 verifyFormat( 23020 "template <typename T>\n" 23021 "veryveryvery_long_return_type g(T i) requires Concept1 || Concept2 {\n" 23022 " //...\n" 23023 "}", 23024 Style); 23025 23026 verifyFormat("template <typename It>\n" 23027 "requires Foo<It>() && Bar<It> {\n" 23028 " //....\n" 23029 "}", 23030 Style); 23031 23032 verifyFormat("template <typename It>\n" 23033 "requires Foo<Bar<It>>() && Bar<Foo<It, It>> {\n" 23034 " //....\n" 23035 "}", 23036 Style); 23037 23038 verifyFormat("template <typename It>\n" 23039 "requires Foo<Bar<It, It>>() && Bar<Foo<It, It>> {\n" 23040 " //....\n" 23041 "}", 23042 Style); 23043 23044 verifyFormat( 23045 "template <typename It>\n" 23046 "requires Foo<Bar<It>, Baz<It>>() && Bar<Foo<It>, Baz<It, It>> {\n" 23047 " //....\n" 23048 "}", 23049 Style); 23050 23051 Style.IndentRequires = true; 23052 verifyFormat("template <typename It>\n" 23053 " requires Iterator<It>\n" 23054 "void sort(It begin, It end) {\n" 23055 " //....\n" 23056 "}", 23057 Style); 23058 verifyFormat("template <std::size index_>\n" 23059 " requires(index_ < sizeof...(Children_))\n" 23060 "Tree auto &child() {\n" 23061 " // ...\n" 23062 "}", 23063 Style); 23064 23065 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 23066 verifyFormat("template <typename T>\n" 23067 "concept Hashable = requires (T a) {\n" 23068 " { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;\n" 23069 "};", 23070 Style); 23071 23072 verifyFormat("template <class T = void>\n" 23073 " requires EqualityComparable<T> || Same<T, void>\n" 23074 "struct equal_to;", 23075 Style); 23076 23077 verifyFormat("template <class T>\n" 23078 " requires requires {\n" 23079 " T{};\n" 23080 " T (int);\n" 23081 " }\n", 23082 Style); 23083 23084 Style.ColumnLimit = 78; 23085 verifyFormat("template <typename T>\n" 23086 "concept Context = Traits<typename T::traits_type> and\n" 23087 " Interface<typename T::interface_type> and\n" 23088 " Request<typename T::request_type> and\n" 23089 " Response<typename T::response_type> and\n" 23090 " ContextExtension<typename T::extension_type> and\n" 23091 " ::std::is_copy_constructable<T> and " 23092 "::std::is_move_constructable<T> and\n" 23093 " requires (T c) {\n" 23094 " { c.response; } -> Response;\n" 23095 "} and requires (T c) {\n" 23096 " { c.request; } -> Request;\n" 23097 "}\n", 23098 Style); 23099 23100 verifyFormat("template <typename T>\n" 23101 "concept Context = Traits<typename T::traits_type> or\n" 23102 " Interface<typename T::interface_type> or\n" 23103 " Request<typename T::request_type> or\n" 23104 " Response<typename T::response_type> or\n" 23105 " ContextExtension<typename T::extension_type> or\n" 23106 " ::std::is_copy_constructable<T> or " 23107 "::std::is_move_constructable<T> or\n" 23108 " requires (T c) {\n" 23109 " { c.response; } -> Response;\n" 23110 "} or requires (T c) {\n" 23111 " { c.request; } -> Request;\n" 23112 "}\n", 23113 Style); 23114 23115 verifyFormat("template <typename T>\n" 23116 "concept Context = Traits<typename T::traits_type> &&\n" 23117 " Interface<typename T::interface_type> &&\n" 23118 " Request<typename T::request_type> &&\n" 23119 " Response<typename T::response_type> &&\n" 23120 " ContextExtension<typename T::extension_type> &&\n" 23121 " ::std::is_copy_constructable<T> && " 23122 "::std::is_move_constructable<T> &&\n" 23123 " requires (T c) {\n" 23124 " { c.response; } -> Response;\n" 23125 "} && requires (T c) {\n" 23126 " { c.request; } -> Request;\n" 23127 "}\n", 23128 Style); 23129 23130 verifyFormat("template <typename T>\nconcept someConcept = Constraint1<T> && " 23131 "Constraint2<T>;"); 23132 23133 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 23134 Style.BraceWrapping.AfterFunction = true; 23135 Style.BraceWrapping.AfterClass = true; 23136 Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 23137 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 23138 verifyFormat("void Foo () requires (std::copyable<T>)\n" 23139 "{\n" 23140 " return\n" 23141 "}\n", 23142 Style); 23143 23144 verifyFormat("void Foo () requires std::copyable<T>\n" 23145 "{\n" 23146 " return\n" 23147 "}\n", 23148 Style); 23149 23150 verifyFormat("template <std::semiregular F, std::semiregular... Args>\n" 23151 " requires (std::invocable<F, std::invoke_result_t<Args>...>)\n" 23152 "struct constant;", 23153 Style); 23154 23155 verifyFormat("template <std::semiregular F, std::semiregular... Args>\n" 23156 " requires std::invocable<F, std::invoke_result_t<Args>...>\n" 23157 "struct constant;", 23158 Style); 23159 23160 verifyFormat("template <class T>\n" 23161 "class plane_with_very_very_very_long_name\n" 23162 "{\n" 23163 " constexpr plane_with_very_very_very_long_name () requires " 23164 "std::copyable<T>\n" 23165 " : plane_with_very_very_very_long_name (1)\n" 23166 " {\n" 23167 " }\n" 23168 "}\n", 23169 Style); 23170 23171 verifyFormat("template <class T>\n" 23172 "class plane_with_long_name\n" 23173 "{\n" 23174 " constexpr plane_with_long_name () requires std::copyable<T>\n" 23175 " : plane_with_long_name (1)\n" 23176 " {\n" 23177 " }\n" 23178 "}\n", 23179 Style); 23180 23181 Style.BreakBeforeConceptDeclarations = false; 23182 verifyFormat("template <typename T> concept Tree = true;", Style); 23183 23184 Style.IndentRequires = false; 23185 verifyFormat("template <std::semiregular F, std::semiregular... Args>\n" 23186 "requires (std::invocable<F, std::invoke_result_t<Args>...>) " 23187 "struct constant;", 23188 Style); 23189 } 23190 23191 TEST_F(FormatTest, StatementAttributeLikeMacros) { 23192 FormatStyle Style = getLLVMStyle(); 23193 StringRef Source = "void Foo::slot() {\n" 23194 " unsigned char MyChar = 'x';\n" 23195 " emit signal(MyChar);\n" 23196 " Q_EMIT signal(MyChar);\n" 23197 "}"; 23198 23199 EXPECT_EQ(Source, format(Source, Style)); 23200 23201 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 23202 EXPECT_EQ("void Foo::slot() {\n" 23203 " unsigned char MyChar = 'x';\n" 23204 " emit signal(MyChar);\n" 23205 " Q_EMIT signal(MyChar);\n" 23206 "}", 23207 format(Source, Style)); 23208 23209 Style.StatementAttributeLikeMacros.push_back("emit"); 23210 EXPECT_EQ(Source, format(Source, Style)); 23211 23212 Style.StatementAttributeLikeMacros = {}; 23213 EXPECT_EQ("void Foo::slot() {\n" 23214 " unsigned char MyChar = 'x';\n" 23215 " emit signal(MyChar);\n" 23216 " Q_EMIT signal(MyChar);\n" 23217 "}", 23218 format(Source, Style)); 23219 } 23220 23221 TEST_F(FormatTest, IndentAccessModifiers) { 23222 FormatStyle Style = getLLVMStyle(); 23223 Style.IndentAccessModifiers = true; 23224 // Members are *two* levels below the record; 23225 // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation. 23226 verifyFormat("class C {\n" 23227 " int i;\n" 23228 "};\n", 23229 Style); 23230 verifyFormat("union C {\n" 23231 " int i;\n" 23232 " unsigned u;\n" 23233 "};\n", 23234 Style); 23235 // Access modifiers should be indented one level below the record. 23236 verifyFormat("class C {\n" 23237 " public:\n" 23238 " int i;\n" 23239 "};\n", 23240 Style); 23241 verifyFormat("struct S {\n" 23242 " private:\n" 23243 " class C {\n" 23244 " int j;\n" 23245 "\n" 23246 " public:\n" 23247 " C();\n" 23248 " };\n" 23249 "\n" 23250 " public:\n" 23251 " int i;\n" 23252 "};\n", 23253 Style); 23254 // Enumerations are not records and should be unaffected. 23255 Style.AllowShortEnumsOnASingleLine = false; 23256 verifyFormat("enum class E {\n" 23257 " A,\n" 23258 " B\n" 23259 "};\n", 23260 Style); 23261 // Test with a different indentation width; 23262 // also proves that the result is Style.AccessModifierOffset agnostic. 23263 Style.IndentWidth = 3; 23264 verifyFormat("class C {\n" 23265 " public:\n" 23266 " int i;\n" 23267 "};\n", 23268 Style); 23269 } 23270 23271 TEST_F(FormatTest, LimitlessStringsAndComments) { 23272 auto Style = getLLVMStyleWithColumns(0); 23273 constexpr StringRef Code = 23274 "/**\n" 23275 " * This is a multiline comment with quite some long lines, at least for " 23276 "the LLVM Style.\n" 23277 " * We will redo this with strings and line comments. Just to check if " 23278 "everything is working.\n" 23279 " */\n" 23280 "bool foo() {\n" 23281 " /* Single line multi line comment. */\n" 23282 " const std::string String = \"This is a multiline string with quite " 23283 "some long lines, at least for the LLVM Style.\"\n" 23284 " \"We already did it with multi line " 23285 "comments, and we will do it with line comments. Just to check if " 23286 "everything is working.\";\n" 23287 " // This is a line comment (block) with quite some long lines, at " 23288 "least for the LLVM Style.\n" 23289 " // We already did this with multi line comments and strings. Just to " 23290 "check if everything is working.\n" 23291 " const std::string SmallString = \"Hello World\";\n" 23292 " // Small line comment\n" 23293 " return String.size() > SmallString.size();\n" 23294 "}"; 23295 EXPECT_EQ(Code, format(Code, Style)); 23296 } 23297 23298 TEST_F(FormatTest, FormatDecayCopy) { 23299 // error cases from unit tests 23300 verifyFormat("foo(auto())"); 23301 verifyFormat("foo(auto{})"); 23302 verifyFormat("foo(auto({}))"); 23303 verifyFormat("foo(auto{{}})"); 23304 23305 verifyFormat("foo(auto(1))"); 23306 verifyFormat("foo(auto{1})"); 23307 verifyFormat("foo(new auto(1))"); 23308 verifyFormat("foo(new auto{1})"); 23309 verifyFormat("decltype(auto(1)) x;"); 23310 verifyFormat("decltype(auto{1}) x;"); 23311 verifyFormat("auto(x);"); 23312 verifyFormat("auto{x};"); 23313 verifyFormat("new auto{x};"); 23314 verifyFormat("auto{x} = y;"); 23315 verifyFormat("auto(x) = y;"); // actually a declaration, but this is clearly 23316 // the user's own fault 23317 verifyFormat("integral auto(x) = y;"); // actually a declaration, but this is 23318 // clearly the user's own fault 23319 verifyFormat("auto(*p)() = f;"); // actually a declaration; TODO FIXME 23320 } 23321 23322 TEST_F(FormatTest, Cpp20ModulesSupport) { 23323 FormatStyle Style = getLLVMStyle(); 23324 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 23325 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 23326 23327 verifyFormat("export import foo;", Style); 23328 verifyFormat("export import foo:bar;", Style); 23329 verifyFormat("export import foo.bar;", Style); 23330 verifyFormat("export import foo.bar:baz;", Style); 23331 verifyFormat("export import :bar;", Style); 23332 verifyFormat("export module foo:bar;", Style); 23333 verifyFormat("export module foo;", Style); 23334 verifyFormat("export module foo.bar;", Style); 23335 verifyFormat("export module foo.bar:baz;", Style); 23336 verifyFormat("export import <string_view>;", Style); 23337 23338 verifyFormat("export type_name var;", Style); 23339 verifyFormat("template <class T> export using A = B<T>;", Style); 23340 verifyFormat("export using A = B;", Style); 23341 verifyFormat("export int func() {\n" 23342 " foo();\n" 23343 "}", 23344 Style); 23345 verifyFormat("export struct {\n" 23346 " int foo;\n" 23347 "};", 23348 Style); 23349 verifyFormat("export {\n" 23350 " int foo;\n" 23351 "};", 23352 Style); 23353 verifyFormat("export export char const *hello() { return \"hello\"; }"); 23354 23355 verifyFormat("import bar;", Style); 23356 verifyFormat("import foo.bar;", Style); 23357 verifyFormat("import foo:bar;", Style); 23358 verifyFormat("import :bar;", Style); 23359 verifyFormat("import <ctime>;", Style); 23360 verifyFormat("import \"header\";", Style); 23361 23362 verifyFormat("module foo;", Style); 23363 verifyFormat("module foo:bar;", Style); 23364 verifyFormat("module foo.bar;", Style); 23365 verifyFormat("module;", Style); 23366 23367 verifyFormat("export namespace hi {\n" 23368 "const char *sayhi();\n" 23369 "}", 23370 Style); 23371 23372 verifyFormat("module :private;", Style); 23373 verifyFormat("import <foo/bar.h>;", Style); 23374 verifyFormat("import foo...bar;", Style); 23375 verifyFormat("import ..........;", Style); 23376 verifyFormat("module foo:private;", Style); 23377 verifyFormat("import a", Style); 23378 verifyFormat("module a", Style); 23379 verifyFormat("export import a", Style); 23380 verifyFormat("export module a", Style); 23381 23382 verifyFormat("import", Style); 23383 verifyFormat("module", Style); 23384 verifyFormat("export", Style); 23385 } 23386 23387 TEST_F(FormatTest, CoroutineForCoawait) { 23388 FormatStyle Style = getLLVMStyle(); 23389 verifyFormat("for co_await (auto x : range())\n ;"); 23390 verifyFormat("for (auto i : arr) {\n" 23391 "}", 23392 Style); 23393 verifyFormat("for co_await (auto i : arr) {\n" 23394 "}", 23395 Style); 23396 verifyFormat("for co_await (auto i : foo(T{})) {\n" 23397 "}", 23398 Style); 23399 } 23400 23401 TEST_F(FormatTest, CoroutineCoAwait) { 23402 verifyFormat("int x = co_await foo();"); 23403 verifyFormat("int x = (co_await foo());"); 23404 verifyFormat("co_await (42);"); 23405 verifyFormat("void operator co_await(int);"); 23406 verifyFormat("void operator co_await(a);"); 23407 verifyFormat("co_await a;"); 23408 verifyFormat("co_await missing_await_resume{};"); 23409 verifyFormat("co_await a; // comment"); 23410 verifyFormat("void test0() { co_await a; }"); 23411 verifyFormat("co_await co_await co_await foo();"); 23412 verifyFormat("co_await foo().bar();"); 23413 verifyFormat("co_await [this]() -> Task { co_return x; }"); 23414 verifyFormat("co_await [this](int a, int b) -> Task { co_return co_await " 23415 "foo(); }(x, y);"); 23416 23417 FormatStyle Style = getLLVMStyleWithColumns(40); 23418 verifyFormat("co_await [this](int a, int b) -> Task {\n" 23419 " co_return co_await foo();\n" 23420 "}(x, y);", 23421 Style); 23422 verifyFormat("co_await;"); 23423 } 23424 23425 TEST_F(FormatTest, CoroutineCoYield) { 23426 verifyFormat("int x = co_yield foo();"); 23427 verifyFormat("int x = (co_yield foo());"); 23428 verifyFormat("co_yield (42);"); 23429 verifyFormat("co_yield {42};"); 23430 verifyFormat("co_yield 42;"); 23431 verifyFormat("co_yield n++;"); 23432 verifyFormat("co_yield ++n;"); 23433 verifyFormat("co_yield;"); 23434 } 23435 23436 TEST_F(FormatTest, CoroutineCoReturn) { 23437 verifyFormat("co_return (42);"); 23438 verifyFormat("co_return;"); 23439 verifyFormat("co_return {};"); 23440 verifyFormat("co_return x;"); 23441 verifyFormat("co_return co_await foo();"); 23442 verifyFormat("co_return co_yield foo();"); 23443 } 23444 23445 TEST_F(FormatTest, EmptyShortBlock) { 23446 auto Style = getLLVMStyle(); 23447 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 23448 23449 verifyFormat("try {\n" 23450 " doA();\n" 23451 "} catch (Exception &e) {\n" 23452 " e.printStackTrace();\n" 23453 "}\n", 23454 Style); 23455 23456 verifyFormat("try {\n" 23457 " doA();\n" 23458 "} catch (Exception &e) {}\n", 23459 Style); 23460 } 23461 23462 TEST_F(FormatTest, ShortTemplatedArgumentLists) { 23463 auto Style = getLLVMStyle(); 23464 23465 verifyFormat("struct Y : X<[] { return 0; }> {};", Style); 23466 verifyFormat("struct Y<[] { return 0; }> {};", Style); 23467 23468 verifyFormat("struct Z : X<decltype([] { return 0; }){}> {};", Style); 23469 } 23470 23471 TEST_F(FormatTest, RemoveBraces) { 23472 FormatStyle Style = getLLVMStyle(); 23473 Style.RemoveBracesLLVM = true; 23474 23475 // The following eight test cases are fully-braced versions of the examples at 23476 // "llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single- 23477 // statement-bodies-of-if-else-loop-statements". 23478 23479 // 1. Omit the braces, since the body is simple and clearly associated with 23480 // the if. 23481 verifyFormat("if (isa<FunctionDecl>(D))\n" 23482 " handleFunctionDecl(D);\n" 23483 "else if (isa<VarDecl>(D))\n" 23484 " handleVarDecl(D);", 23485 "if (isa<FunctionDecl>(D)) {\n" 23486 " handleFunctionDecl(D);\n" 23487 "} else if (isa<VarDecl>(D)) {\n" 23488 " handleVarDecl(D);\n" 23489 "}", 23490 Style); 23491 23492 // 2. Here we document the condition itself and not the body. 23493 verifyFormat("if (isa<VarDecl>(D)) {\n" 23494 " // It is necessary that we explain the situation with this\n" 23495 " // surprisingly long comment, so it would be unclear\n" 23496 " // without the braces whether the following statement is in\n" 23497 " // the scope of the `if`.\n" 23498 " // Because the condition is documented, we can't really\n" 23499 " // hoist this comment that applies to the body above the\n" 23500 " // if.\n" 23501 " handleOtherDecl(D);\n" 23502 "}", 23503 Style); 23504 23505 // 3. Use braces on the outer `if` to avoid a potential dangling else 23506 // situation. 23507 verifyFormat("if (isa<VarDecl>(D)) {\n" 23508 " for (auto *A : D.attrs())\n" 23509 " if (shouldProcessAttr(A))\n" 23510 " handleAttr(A);\n" 23511 "}", 23512 "if (isa<VarDecl>(D)) {\n" 23513 " for (auto *A : D.attrs()) {\n" 23514 " if (shouldProcessAttr(A)) {\n" 23515 " handleAttr(A);\n" 23516 " }\n" 23517 " }\n" 23518 "}", 23519 Style); 23520 23521 // 4. Use braces for the `if` block to keep it uniform with the else block. 23522 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 23523 " handleFunctionDecl(D);\n" 23524 "} else {\n" 23525 " // In this else case, it is necessary that we explain the\n" 23526 " // situation with this surprisingly long comment, so it\n" 23527 " // would be unclear without the braces whether the\n" 23528 " // following statement is in the scope of the `if`.\n" 23529 " handleOtherDecl(D);\n" 23530 "}", 23531 Style); 23532 23533 // 5. This should also omit braces. The `for` loop contains only a single 23534 // statement, so it shouldn't have braces. The `if` also only contains a 23535 // single simple statement (the for loop), so it also should omit braces. 23536 verifyFormat("if (isa<FunctionDecl>(D))\n" 23537 " for (auto *A : D.attrs())\n" 23538 " handleAttr(A);", 23539 "if (isa<FunctionDecl>(D)) {\n" 23540 " for (auto *A : D.attrs()) {\n" 23541 " handleAttr(A);\n" 23542 " }\n" 23543 "}", 23544 Style); 23545 23546 // 6. Use braces for the outer `if` since the nested `for` is braced. 23547 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 23548 " for (auto *A : D.attrs()) {\n" 23549 " // In this for loop body, it is necessary that we explain\n" 23550 " // the situation with this surprisingly long comment,\n" 23551 " // forcing braces on the `for` block.\n" 23552 " handleAttr(A);\n" 23553 " }\n" 23554 "}", 23555 Style); 23556 23557 // 7. Use braces on the outer block because there are more than two levels of 23558 // nesting. 23559 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 23560 " for (auto *A : D.attrs())\n" 23561 " for (ssize_t i : llvm::seq<ssize_t>(count))\n" 23562 " handleAttrOnDecl(D, A, i);\n" 23563 "}", 23564 "if (isa<FunctionDecl>(D)) {\n" 23565 " for (auto *A : D.attrs()) {\n" 23566 " for (ssize_t i : llvm::seq<ssize_t>(count)) {\n" 23567 " handleAttrOnDecl(D, A, i);\n" 23568 " }\n" 23569 " }\n" 23570 "}", 23571 Style); 23572 23573 // 8. Use braces on the outer block because of a nested `if`, otherwise the 23574 // compiler would warn: `add explicit braces to avoid dangling else` 23575 verifyFormat("if (auto *D = dyn_cast<FunctionDecl>(D)) {\n" 23576 " if (shouldProcess(D))\n" 23577 " handleVarDecl(D);\n" 23578 " else\n" 23579 " markAsIgnored(D);\n" 23580 "}", 23581 "if (auto *D = dyn_cast<FunctionDecl>(D)) {\n" 23582 " if (shouldProcess(D)) {\n" 23583 " handleVarDecl(D);\n" 23584 " } else {\n" 23585 " markAsIgnored(D);\n" 23586 " }\n" 23587 "}", 23588 Style); 23589 23590 verifyFormat("if (a)\n" 23591 " b; // comment\n" 23592 "else if (c)\n" 23593 " d; /* comment */\n" 23594 "else\n" 23595 " e;", 23596 "if (a) {\n" 23597 " b; // comment\n" 23598 "} else if (c) {\n" 23599 " d; /* comment */\n" 23600 "} else {\n" 23601 " e;\n" 23602 "}", 23603 Style); 23604 23605 verifyFormat("if (a) {\n" 23606 " b;\n" 23607 " c;\n" 23608 "} else if (d) {\n" 23609 " e;\n" 23610 "}", 23611 Style); 23612 23613 verifyFormat("if (a) {\n" 23614 "#undef NDEBUG\n" 23615 " b;\n" 23616 "} else {\n" 23617 " c;\n" 23618 "}", 23619 Style); 23620 23621 verifyFormat("if (a) {\n" 23622 " // comment\n" 23623 "} else if (b) {\n" 23624 " c;\n" 23625 "}", 23626 Style); 23627 23628 verifyFormat("if (a) {\n" 23629 " b;\n" 23630 "} else {\n" 23631 " { c; }\n" 23632 "}", 23633 Style); 23634 23635 verifyFormat("if (a) {\n" 23636 " if (b) // comment\n" 23637 " c;\n" 23638 "} else if (d) {\n" 23639 " e;\n" 23640 "}", 23641 "if (a) {\n" 23642 " if (b) { // comment\n" 23643 " c;\n" 23644 " }\n" 23645 "} else if (d) {\n" 23646 " e;\n" 23647 "}", 23648 Style); 23649 23650 verifyFormat("if (a) {\n" 23651 " if (b) {\n" 23652 " c;\n" 23653 " // comment\n" 23654 " } else if (d) {\n" 23655 " e;\n" 23656 " }\n" 23657 "}", 23658 Style); 23659 23660 verifyFormat("if (a) {\n" 23661 " if (b)\n" 23662 " c;\n" 23663 "}", 23664 "if (a) {\n" 23665 " if (b) {\n" 23666 " c;\n" 23667 " }\n" 23668 "}", 23669 Style); 23670 23671 verifyFormat("if (a)\n" 23672 " if (b)\n" 23673 " c;\n" 23674 " else\n" 23675 " d;\n" 23676 "else\n" 23677 " e;", 23678 "if (a) {\n" 23679 " if (b) {\n" 23680 " c;\n" 23681 " } else {\n" 23682 " d;\n" 23683 " }\n" 23684 "} else {\n" 23685 " e;\n" 23686 "}", 23687 Style); 23688 23689 verifyFormat("if (a) {\n" 23690 " // comment\n" 23691 " if (b)\n" 23692 " c;\n" 23693 " else if (d)\n" 23694 " e;\n" 23695 "} else {\n" 23696 " g;\n" 23697 "}", 23698 "if (a) {\n" 23699 " // comment\n" 23700 " if (b) {\n" 23701 " c;\n" 23702 " } else if (d) {\n" 23703 " e;\n" 23704 " }\n" 23705 "} else {\n" 23706 " g;\n" 23707 "}", 23708 Style); 23709 23710 verifyFormat("if (a)\n" 23711 " b;\n" 23712 "else if (c)\n" 23713 " d;\n" 23714 "else\n" 23715 " e;", 23716 "if (a) {\n" 23717 " b;\n" 23718 "} else {\n" 23719 " if (c) {\n" 23720 " d;\n" 23721 " } else {\n" 23722 " e;\n" 23723 " }\n" 23724 "}", 23725 Style); 23726 23727 verifyFormat("if (a) {\n" 23728 " if (b)\n" 23729 " c;\n" 23730 " else if (d)\n" 23731 " e;\n" 23732 "} else {\n" 23733 " g;\n" 23734 "}", 23735 "if (a) {\n" 23736 " if (b)\n" 23737 " c;\n" 23738 " else {\n" 23739 " if (d)\n" 23740 " e;\n" 23741 " }\n" 23742 "} else {\n" 23743 " g;\n" 23744 "}", 23745 Style); 23746 23747 verifyFormat("if (a)\n" 23748 " b;\n" 23749 "else if (c)\n" 23750 " while (d)\n" 23751 " e;\n" 23752 "// comment", 23753 "if (a)\n" 23754 "{\n" 23755 " b;\n" 23756 "} else if (c) {\n" 23757 " while (d) {\n" 23758 " e;\n" 23759 " }\n" 23760 "}\n" 23761 "// comment", 23762 Style); 23763 23764 verifyFormat("if (a) {\n" 23765 " b;\n" 23766 "} else if (c) {\n" 23767 " d;\n" 23768 "} else {\n" 23769 " e;\n" 23770 " g;\n" 23771 "}", 23772 Style); 23773 23774 verifyFormat("if (a) {\n" 23775 " b;\n" 23776 "} else if (c) {\n" 23777 " d;\n" 23778 "} else {\n" 23779 " e;\n" 23780 "} // comment", 23781 Style); 23782 23783 verifyFormat("int abs = [](int i) {\n" 23784 " if (i >= 0)\n" 23785 " return i;\n" 23786 " return -i;\n" 23787 "};", 23788 "int abs = [](int i) {\n" 23789 " if (i >= 0) {\n" 23790 " return i;\n" 23791 " }\n" 23792 " return -i;\n" 23793 "};", 23794 Style); 23795 23796 Style.ColumnLimit = 20; 23797 23798 verifyFormat("if (a) {\n" 23799 " b = c + // 1 -\n" 23800 " d;\n" 23801 "}", 23802 Style); 23803 23804 verifyFormat("if (a) {\n" 23805 " b = c >= 0 ? d\n" 23806 " : e;\n" 23807 "}", 23808 "if (a) {\n" 23809 " b = c >= 0 ? d : e;\n" 23810 "}", 23811 Style); 23812 23813 verifyFormat("if (a)\n" 23814 " b = c > 0 ? d : e;", 23815 "if (a) {\n" 23816 " b = c > 0 ? d : e;\n" 23817 "}", 23818 Style); 23819 23820 Style.ColumnLimit = 0; 23821 23822 verifyFormat("if (a)\n" 23823 " b234567890223456789032345678904234567890 = " 23824 "c234567890223456789032345678904234567890;", 23825 "if (a) {\n" 23826 " b234567890223456789032345678904234567890 = " 23827 "c234567890223456789032345678904234567890;\n" 23828 "}", 23829 Style); 23830 } 23831 23832 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndent) { 23833 auto Style = getLLVMStyle(); 23834 23835 StringRef Short = "functionCall(paramA, paramB, paramC);\n" 23836 "void functionDecl(int a, int b, int c);"; 23837 23838 StringRef Medium = "functionCall(paramA, paramB, paramC, paramD, paramE, " 23839 "paramF, paramG, paramH, paramI);\n" 23840 "void functionDecl(int argumentA, int argumentB, int " 23841 "argumentC, int argumentD, int argumentE);"; 23842 23843 verifyFormat(Short, Style); 23844 23845 StringRef NoBreak = "functionCall(paramA, paramB, paramC, paramD, paramE, " 23846 "paramF, paramG, paramH,\n" 23847 " paramI);\n" 23848 "void functionDecl(int argumentA, int argumentB, int " 23849 "argumentC, int argumentD,\n" 23850 " int argumentE);"; 23851 23852 verifyFormat(NoBreak, Medium, Style); 23853 verifyFormat(NoBreak, 23854 "functionCall(\n" 23855 " paramA,\n" 23856 " paramB,\n" 23857 " paramC,\n" 23858 " paramD,\n" 23859 " paramE,\n" 23860 " paramF,\n" 23861 " paramG,\n" 23862 " paramH,\n" 23863 " paramI\n" 23864 ");\n" 23865 "void functionDecl(\n" 23866 " int argumentA,\n" 23867 " int argumentB,\n" 23868 " int argumentC,\n" 23869 " int argumentD,\n" 23870 " int argumentE\n" 23871 ");", 23872 Style); 23873 23874 verifyFormat("outerFunctionCall(nestedFunctionCall(argument1),\n" 23875 " nestedLongFunctionCall(argument1, " 23876 "argument2, argument3,\n" 23877 " argument4, " 23878 "argument5));", 23879 Style); 23880 23881 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 23882 23883 verifyFormat(Short, Style); 23884 verifyFormat( 23885 "functionCall(\n" 23886 " paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, " 23887 "paramI\n" 23888 ");\n" 23889 "void functionDecl(\n" 23890 " int argumentA, int argumentB, int argumentC, int argumentD, int " 23891 "argumentE\n" 23892 ");", 23893 Medium, Style); 23894 23895 Style.AllowAllArgumentsOnNextLine = false; 23896 Style.AllowAllParametersOfDeclarationOnNextLine = false; 23897 23898 verifyFormat(Short, Style); 23899 verifyFormat( 23900 "functionCall(\n" 23901 " paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, " 23902 "paramI\n" 23903 ");\n" 23904 "void functionDecl(\n" 23905 " int argumentA, int argumentB, int argumentC, int argumentD, int " 23906 "argumentE\n" 23907 ");", 23908 Medium, Style); 23909 23910 Style.BinPackArguments = false; 23911 Style.BinPackParameters = false; 23912 23913 verifyFormat(Short, Style); 23914 23915 verifyFormat("functionCall(\n" 23916 " paramA,\n" 23917 " paramB,\n" 23918 " paramC,\n" 23919 " paramD,\n" 23920 " paramE,\n" 23921 " paramF,\n" 23922 " paramG,\n" 23923 " paramH,\n" 23924 " paramI\n" 23925 ");\n" 23926 "void functionDecl(\n" 23927 " int argumentA,\n" 23928 " int argumentB,\n" 23929 " int argumentC,\n" 23930 " int argumentD,\n" 23931 " int argumentE\n" 23932 ");", 23933 Medium, Style); 23934 23935 verifyFormat("outerFunctionCall(\n" 23936 " nestedFunctionCall(argument1),\n" 23937 " nestedLongFunctionCall(\n" 23938 " argument1,\n" 23939 " argument2,\n" 23940 " argument3,\n" 23941 " argument4,\n" 23942 " argument5\n" 23943 " )\n" 23944 ");", 23945 Style); 23946 23947 verifyFormat("int a = (int)b;", Style); 23948 verifyFormat("int a = (int)b;", 23949 "int a = (\n" 23950 " int\n" 23951 ") b;", 23952 Style); 23953 23954 verifyFormat("return (true);", Style); 23955 verifyFormat("return (true);", 23956 "return (\n" 23957 " true\n" 23958 ");", 23959 Style); 23960 23961 verifyFormat("void foo();", Style); 23962 verifyFormat("void foo();", 23963 "void foo(\n" 23964 ");", 23965 Style); 23966 23967 verifyFormat("void foo() {}", Style); 23968 verifyFormat("void foo() {}", 23969 "void foo(\n" 23970 ") {\n" 23971 "}", 23972 Style); 23973 23974 verifyFormat("auto string = std::string();", Style); 23975 verifyFormat("auto string = std::string();", 23976 "auto string = std::string(\n" 23977 ");", 23978 Style); 23979 23980 verifyFormat("void (*functionPointer)() = nullptr;", Style); 23981 verifyFormat("void (*functionPointer)() = nullptr;", 23982 "void (\n" 23983 " *functionPointer\n" 23984 ")\n" 23985 "(\n" 23986 ") = nullptr;", 23987 Style); 23988 } 23989 23990 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentIfStatement) { 23991 auto Style = getLLVMStyle(); 23992 23993 verifyFormat("if (foo()) {\n" 23994 " return;\n" 23995 "}", 23996 Style); 23997 23998 verifyFormat("if (quitelongarg !=\n" 23999 " (alsolongarg - 1)) { // ABC is a very longgggggggggggg " 24000 "comment\n" 24001 " return;\n" 24002 "}", 24003 Style); 24004 24005 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 24006 24007 verifyFormat("if (foo()) {\n" 24008 " return;\n" 24009 "}", 24010 Style); 24011 24012 verifyFormat("if (quitelongarg !=\n" 24013 " (alsolongarg - 1)) { // ABC is a very longgggggggggggg " 24014 "comment\n" 24015 " return;\n" 24016 "}", 24017 Style); 24018 } 24019 24020 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentForStatement) { 24021 auto Style = getLLVMStyle(); 24022 24023 verifyFormat("for (int i = 0; i < 5; ++i) {\n" 24024 " doSomething();\n" 24025 "}", 24026 Style); 24027 24028 verifyFormat("for (int myReallyLongCountVariable = 0; " 24029 "myReallyLongCountVariable < count;\n" 24030 " myReallyLongCountVariable++) {\n" 24031 " doSomething();\n" 24032 "}", 24033 Style); 24034 24035 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 24036 24037 verifyFormat("for (int i = 0; i < 5; ++i) {\n" 24038 " doSomething();\n" 24039 "}", 24040 Style); 24041 24042 verifyFormat("for (int myReallyLongCountVariable = 0; " 24043 "myReallyLongCountVariable < count;\n" 24044 " myReallyLongCountVariable++) {\n" 24045 " doSomething();\n" 24046 "}", 24047 Style); 24048 } 24049 24050 } // namespace 24051 } // namespace format 24052 } // namespace clang 24053