1 //===- unittest/Format/FormatTest.cpp - Formatting unit tests -------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "clang/Format/Format.h" 10 11 #include "../Tooling/ReplacementTest.h" 12 #include "FormatTestUtils.h" 13 14 #include "llvm/Support/Debug.h" 15 #include "llvm/Support/MemoryBuffer.h" 16 #include "gtest/gtest.h" 17 18 #define DEBUG_TYPE "format-test" 19 20 using clang::tooling::ReplacementTest; 21 using clang::tooling::toReplacements; 22 using testing::ScopedTrace; 23 24 namespace clang { 25 namespace format { 26 namespace { 27 28 FormatStyle getGoogleStyle() { return getGoogleStyle(FormatStyle::LK_Cpp); } 29 30 class FormatTest : public ::testing::Test { 31 protected: 32 enum StatusCheck { SC_ExpectComplete, SC_ExpectIncomplete, SC_DoNotCheck }; 33 34 std::string format(llvm::StringRef Code, 35 const FormatStyle &Style = getLLVMStyle(), 36 StatusCheck CheckComplete = SC_ExpectComplete) { 37 LLVM_DEBUG(llvm::errs() << "---\n"); 38 LLVM_DEBUG(llvm::errs() << Code << "\n\n"); 39 std::vector<tooling::Range> Ranges(1, tooling::Range(0, Code.size())); 40 FormattingAttemptStatus Status; 41 tooling::Replacements Replaces = 42 reformat(Style, Code, Ranges, "<stdin>", &Status); 43 if (CheckComplete != SC_DoNotCheck) { 44 bool ExpectedCompleteFormat = CheckComplete == SC_ExpectComplete; 45 EXPECT_EQ(ExpectedCompleteFormat, Status.FormatComplete) 46 << Code << "\n\n"; 47 } 48 ReplacementCount = Replaces.size(); 49 auto Result = applyAllReplacements(Code, Replaces); 50 EXPECT_TRUE(static_cast<bool>(Result)); 51 LLVM_DEBUG(llvm::errs() << "\n" << *Result << "\n\n"); 52 return *Result; 53 } 54 55 FormatStyle getStyleWithColumns(FormatStyle Style, unsigned ColumnLimit) { 56 Style.ColumnLimit = ColumnLimit; 57 return Style; 58 } 59 60 FormatStyle getLLVMStyleWithColumns(unsigned ColumnLimit) { 61 return getStyleWithColumns(getLLVMStyle(), ColumnLimit); 62 } 63 64 FormatStyle getGoogleStyleWithColumns(unsigned ColumnLimit) { 65 return getStyleWithColumns(getGoogleStyle(), ColumnLimit); 66 } 67 68 void _verifyFormat(const char *File, int Line, llvm::StringRef Expected, 69 llvm::StringRef Code, 70 const FormatStyle &Style = getLLVMStyle()) { 71 ScopedTrace t(File, Line, ::testing::Message() << Code.str()); 72 EXPECT_EQ(Expected.str(), format(Expected, Style)) 73 << "Expected code is not stable"; 74 EXPECT_EQ(Expected.str(), format(Code, Style)); 75 if (Style.Language == FormatStyle::LK_Cpp) { 76 // Objective-C++ is a superset of C++, so everything checked for C++ 77 // needs to be checked for Objective-C++ as well. 78 FormatStyle ObjCStyle = Style; 79 ObjCStyle.Language = FormatStyle::LK_ObjC; 80 EXPECT_EQ(Expected.str(), format(test::messUp(Code), ObjCStyle)); 81 } 82 } 83 84 void _verifyFormat(const char *File, int Line, llvm::StringRef Code, 85 const FormatStyle &Style = getLLVMStyle()) { 86 _verifyFormat(File, Line, Code, test::messUp(Code), Style); 87 } 88 89 void _verifyIncompleteFormat(const char *File, int Line, llvm::StringRef Code, 90 const FormatStyle &Style = getLLVMStyle()) { 91 ScopedTrace t(File, Line, ::testing::Message() << Code.str()); 92 EXPECT_EQ(Code.str(), 93 format(test::messUp(Code), Style, SC_ExpectIncomplete)); 94 } 95 96 void _verifyIndependentOfContext(const char *File, int Line, 97 llvm::StringRef Text, 98 const FormatStyle &Style = getLLVMStyle()) { 99 _verifyFormat(File, Line, Text, Style); 100 _verifyFormat(File, Line, llvm::Twine("void f() { " + Text + " }").str(), 101 Style); 102 } 103 104 /// \brief Verify that clang-format does not crash on the given input. 105 void verifyNoCrash(llvm::StringRef Code, 106 const FormatStyle &Style = getLLVMStyle()) { 107 format(Code, Style, SC_DoNotCheck); 108 } 109 110 int ReplacementCount; 111 }; 112 113 #define verifyIndependentOfContext(...) \ 114 _verifyIndependentOfContext(__FILE__, __LINE__, __VA_ARGS__) 115 #define verifyIncompleteFormat(...) \ 116 _verifyIncompleteFormat(__FILE__, __LINE__, __VA_ARGS__) 117 #define verifyFormat(...) _verifyFormat(__FILE__, __LINE__, __VA_ARGS__) 118 #define verifyGoogleFormat(Code) verifyFormat(Code, getGoogleStyle()) 119 120 TEST_F(FormatTest, MessUp) { 121 EXPECT_EQ("1 2 3", test::messUp("1 2 3")); 122 EXPECT_EQ("1 2 3\n", test::messUp("1\n2\n3\n")); 123 EXPECT_EQ("a\n//b\nc", test::messUp("a\n//b\nc")); 124 EXPECT_EQ("a\n#b\nc", test::messUp("a\n#b\nc")); 125 EXPECT_EQ("a\n#b c d\ne", test::messUp("a\n#b\\\nc\\\nd\ne")); 126 } 127 128 TEST_F(FormatTest, DefaultLLVMStyleIsCpp) { 129 EXPECT_EQ(FormatStyle::LK_Cpp, getLLVMStyle().Language); 130 } 131 132 TEST_F(FormatTest, LLVMStyleOverride) { 133 EXPECT_EQ(FormatStyle::LK_Proto, 134 getLLVMStyle(FormatStyle::LK_Proto).Language); 135 } 136 137 //===----------------------------------------------------------------------===// 138 // Basic function tests. 139 //===----------------------------------------------------------------------===// 140 141 TEST_F(FormatTest, DoesNotChangeCorrectlyFormattedCode) { 142 EXPECT_EQ(";", format(";")); 143 } 144 145 TEST_F(FormatTest, FormatsGlobalStatementsAt0) { 146 EXPECT_EQ("int i;", format(" int i;")); 147 EXPECT_EQ("\nint i;", format(" \n\t \v \f int i;")); 148 EXPECT_EQ("int i;\nint j;", format(" int i; int j;")); 149 EXPECT_EQ("int i;\nint j;", format(" int i;\n int j;")); 150 } 151 152 TEST_F(FormatTest, FormatsUnwrappedLinesAtFirstFormat) { 153 EXPECT_EQ("int i;", format("int\ni;")); 154 } 155 156 TEST_F(FormatTest, FormatsNestedBlockStatements) { 157 EXPECT_EQ("{\n {\n {}\n }\n}", format("{{{}}}")); 158 } 159 160 TEST_F(FormatTest, FormatsNestedCall) { 161 verifyFormat("Method(f1, f2(f3));"); 162 verifyFormat("Method(f1(f2, f3()));"); 163 verifyFormat("Method(f1(f2, (f3())));"); 164 } 165 166 TEST_F(FormatTest, NestedNameSpecifiers) { 167 verifyFormat("vector<::Type> v;"); 168 verifyFormat("::ns::SomeFunction(::ns::SomeOtherFunction())"); 169 verifyFormat("static constexpr bool Bar = decltype(bar())::value;"); 170 verifyFormat("static constexpr bool Bar = typeof(bar())::value;"); 171 verifyFormat("static constexpr bool Bar = __underlying_type(bar())::value;"); 172 verifyFormat("static constexpr bool Bar = _Atomic(bar())::value;"); 173 verifyFormat("bool a = 2 < ::SomeFunction();"); 174 verifyFormat("ALWAYS_INLINE ::std::string getName();"); 175 verifyFormat("some::string getName();"); 176 } 177 178 TEST_F(FormatTest, OnlyGeneratesNecessaryReplacements) { 179 EXPECT_EQ("if (a) {\n" 180 " f();\n" 181 "}", 182 format("if(a){f();}")); 183 EXPECT_EQ(4, ReplacementCount); 184 EXPECT_EQ("if (a) {\n" 185 " f();\n" 186 "}", 187 format("if (a) {\n" 188 " f();\n" 189 "}")); 190 EXPECT_EQ(0, ReplacementCount); 191 EXPECT_EQ("/*\r\n" 192 "\r\n" 193 "*/\r\n", 194 format("/*\r\n" 195 "\r\n" 196 "*/\r\n")); 197 EXPECT_EQ(0, ReplacementCount); 198 } 199 200 TEST_F(FormatTest, RemovesEmptyLines) { 201 EXPECT_EQ("class C {\n" 202 " int i;\n" 203 "};", 204 format("class C {\n" 205 " int i;\n" 206 "\n" 207 "};")); 208 209 // Don't remove empty lines at the start of namespaces or extern "C" blocks. 210 EXPECT_EQ("namespace N {\n" 211 "\n" 212 "int i;\n" 213 "}", 214 format("namespace N {\n" 215 "\n" 216 "int i;\n" 217 "}", 218 getGoogleStyle())); 219 EXPECT_EQ("/* something */ namespace N {\n" 220 "\n" 221 "int i;\n" 222 "}", 223 format("/* something */ namespace N {\n" 224 "\n" 225 "int i;\n" 226 "}", 227 getGoogleStyle())); 228 EXPECT_EQ("inline namespace N {\n" 229 "\n" 230 "int i;\n" 231 "}", 232 format("inline namespace N {\n" 233 "\n" 234 "int i;\n" 235 "}", 236 getGoogleStyle())); 237 EXPECT_EQ("/* something */ inline namespace N {\n" 238 "\n" 239 "int i;\n" 240 "}", 241 format("/* something */ inline namespace N {\n" 242 "\n" 243 "int i;\n" 244 "}", 245 getGoogleStyle())); 246 EXPECT_EQ("export namespace N {\n" 247 "\n" 248 "int i;\n" 249 "}", 250 format("export namespace N {\n" 251 "\n" 252 "int i;\n" 253 "}", 254 getGoogleStyle())); 255 EXPECT_EQ("extern /**/ \"C\" /**/ {\n" 256 "\n" 257 "int i;\n" 258 "}", 259 format("extern /**/ \"C\" /**/ {\n" 260 "\n" 261 "int i;\n" 262 "}", 263 getGoogleStyle())); 264 265 auto CustomStyle = getLLVMStyle(); 266 CustomStyle.BreakBeforeBraces = FormatStyle::BS_Custom; 267 CustomStyle.BraceWrapping.AfterNamespace = true; 268 CustomStyle.KeepEmptyLinesAtTheStartOfBlocks = false; 269 EXPECT_EQ("namespace N\n" 270 "{\n" 271 "\n" 272 "int i;\n" 273 "}", 274 format("namespace N\n" 275 "{\n" 276 "\n" 277 "\n" 278 "int i;\n" 279 "}", 280 CustomStyle)); 281 EXPECT_EQ("/* something */ namespace N\n" 282 "{\n" 283 "\n" 284 "int i;\n" 285 "}", 286 format("/* something */ namespace N {\n" 287 "\n" 288 "\n" 289 "int i;\n" 290 "}", 291 CustomStyle)); 292 EXPECT_EQ("inline namespace N\n" 293 "{\n" 294 "\n" 295 "int i;\n" 296 "}", 297 format("inline namespace N\n" 298 "{\n" 299 "\n" 300 "\n" 301 "int i;\n" 302 "}", 303 CustomStyle)); 304 EXPECT_EQ("/* something */ inline namespace N\n" 305 "{\n" 306 "\n" 307 "int i;\n" 308 "}", 309 format("/* something */ inline namespace N\n" 310 "{\n" 311 "\n" 312 "int i;\n" 313 "}", 314 CustomStyle)); 315 EXPECT_EQ("export namespace N\n" 316 "{\n" 317 "\n" 318 "int i;\n" 319 "}", 320 format("export namespace N\n" 321 "{\n" 322 "\n" 323 "int i;\n" 324 "}", 325 CustomStyle)); 326 EXPECT_EQ("namespace a\n" 327 "{\n" 328 "namespace b\n" 329 "{\n" 330 "\n" 331 "class AA {};\n" 332 "\n" 333 "} // namespace b\n" 334 "} // namespace a\n", 335 format("namespace a\n" 336 "{\n" 337 "namespace b\n" 338 "{\n" 339 "\n" 340 "\n" 341 "class AA {};\n" 342 "\n" 343 "\n" 344 "}\n" 345 "}\n", 346 CustomStyle)); 347 EXPECT_EQ("namespace A /* comment */\n" 348 "{\n" 349 "class B {}\n" 350 "} // namespace A", 351 format("namespace A /* comment */ { class B {} }", CustomStyle)); 352 EXPECT_EQ("namespace A\n" 353 "{ /* comment */\n" 354 "class B {}\n" 355 "} // namespace A", 356 format("namespace A {/* comment */ class B {} }", CustomStyle)); 357 EXPECT_EQ("namespace A\n" 358 "{ /* comment */\n" 359 "\n" 360 "class B {}\n" 361 "\n" 362 "" 363 "} // namespace A", 364 format("namespace A { /* comment */\n" 365 "\n" 366 "\n" 367 "class B {}\n" 368 "\n" 369 "\n" 370 "}", 371 CustomStyle)); 372 EXPECT_EQ("namespace A /* comment */\n" 373 "{\n" 374 "\n" 375 "class B {}\n" 376 "\n" 377 "} // namespace A", 378 format("namespace A/* comment */ {\n" 379 "\n" 380 "\n" 381 "class B {}\n" 382 "\n" 383 "\n" 384 "}", 385 CustomStyle)); 386 387 // ...but do keep inlining and removing empty lines for non-block extern "C" 388 // functions. 389 verifyFormat("extern \"C\" int f() { return 42; }", getGoogleStyle()); 390 EXPECT_EQ("extern \"C\" int f() {\n" 391 " int i = 42;\n" 392 " return i;\n" 393 "}", 394 format("extern \"C\" int f() {\n" 395 "\n" 396 " int i = 42;\n" 397 " return i;\n" 398 "}", 399 getGoogleStyle())); 400 401 // Remove empty lines at the beginning and end of blocks. 402 EXPECT_EQ("void f() {\n" 403 "\n" 404 " if (a) {\n" 405 "\n" 406 " f();\n" 407 " }\n" 408 "}", 409 format("void f() {\n" 410 "\n" 411 " if (a) {\n" 412 "\n" 413 " f();\n" 414 "\n" 415 " }\n" 416 "\n" 417 "}", 418 getLLVMStyle())); 419 EXPECT_EQ("void f() {\n" 420 " if (a) {\n" 421 " f();\n" 422 " }\n" 423 "}", 424 format("void f() {\n" 425 "\n" 426 " if (a) {\n" 427 "\n" 428 " f();\n" 429 "\n" 430 " }\n" 431 "\n" 432 "}", 433 getGoogleStyle())); 434 435 // Don't remove empty lines in more complex control statements. 436 EXPECT_EQ("void f() {\n" 437 " if (a) {\n" 438 " f();\n" 439 "\n" 440 " } else if (b) {\n" 441 " f();\n" 442 " }\n" 443 "}", 444 format("void f() {\n" 445 " if (a) {\n" 446 " f();\n" 447 "\n" 448 " } else if (b) {\n" 449 " f();\n" 450 "\n" 451 " }\n" 452 "\n" 453 "}")); 454 455 // Don't remove empty lines before namespace endings. 456 FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle(); 457 LLVMWithNoNamespaceFix.FixNamespaceComments = false; 458 EXPECT_EQ("namespace {\n" 459 "int i;\n" 460 "\n" 461 "}", 462 format("namespace {\n" 463 "int i;\n" 464 "\n" 465 "}", 466 LLVMWithNoNamespaceFix)); 467 EXPECT_EQ("namespace {\n" 468 "int i;\n" 469 "}", 470 format("namespace {\n" 471 "int i;\n" 472 "}", 473 LLVMWithNoNamespaceFix)); 474 EXPECT_EQ("namespace {\n" 475 "int i;\n" 476 "\n" 477 "};", 478 format("namespace {\n" 479 "int i;\n" 480 "\n" 481 "};", 482 LLVMWithNoNamespaceFix)); 483 EXPECT_EQ("namespace {\n" 484 "int i;\n" 485 "};", 486 format("namespace {\n" 487 "int i;\n" 488 "};", 489 LLVMWithNoNamespaceFix)); 490 EXPECT_EQ("namespace {\n" 491 "int i;\n" 492 "\n" 493 "}", 494 format("namespace {\n" 495 "int i;\n" 496 "\n" 497 "}")); 498 EXPECT_EQ("namespace {\n" 499 "int i;\n" 500 "\n" 501 "} // namespace", 502 format("namespace {\n" 503 "int i;\n" 504 "\n" 505 "} // namespace")); 506 507 FormatStyle Style = getLLVMStyle(); 508 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 509 Style.MaxEmptyLinesToKeep = 2; 510 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 511 Style.BraceWrapping.AfterClass = true; 512 Style.BraceWrapping.AfterFunction = true; 513 Style.KeepEmptyLinesAtTheStartOfBlocks = false; 514 515 EXPECT_EQ("class Foo\n" 516 "{\n" 517 " Foo() {}\n" 518 "\n" 519 " void funk() {}\n" 520 "};", 521 format("class Foo\n" 522 "{\n" 523 " Foo()\n" 524 " {\n" 525 " }\n" 526 "\n" 527 " void funk() {}\n" 528 "};", 529 Style)); 530 } 531 532 TEST_F(FormatTest, RecognizesBinaryOperatorKeywords) { 533 verifyFormat("x = (a) and (b);"); 534 verifyFormat("x = (a) or (b);"); 535 verifyFormat("x = (a) bitand (b);"); 536 verifyFormat("x = (a) bitor (b);"); 537 verifyFormat("x = (a) not_eq (b);"); 538 verifyFormat("x = (a) and_eq (b);"); 539 verifyFormat("x = (a) or_eq (b);"); 540 verifyFormat("x = (a) xor (b);"); 541 } 542 543 TEST_F(FormatTest, RecognizesUnaryOperatorKeywords) { 544 verifyFormat("x = compl(a);"); 545 verifyFormat("x = not(a);"); 546 verifyFormat("x = bitand(a);"); 547 // Unary operator must not be merged with the next identifier 548 verifyFormat("x = compl a;"); 549 verifyFormat("x = not a;"); 550 verifyFormat("x = bitand a;"); 551 } 552 553 //===----------------------------------------------------------------------===// 554 // Tests for control statements. 555 //===----------------------------------------------------------------------===// 556 557 TEST_F(FormatTest, FormatIfWithoutCompoundStatement) { 558 verifyFormat("if (true)\n f();\ng();"); 559 verifyFormat("if (a)\n if (b)\n if (c)\n g();\nh();"); 560 verifyFormat("if (a)\n if (b) {\n f();\n }\ng();"); 561 verifyFormat("if constexpr (true)\n" 562 " f();\ng();"); 563 verifyFormat("if CONSTEXPR (true)\n" 564 " f();\ng();"); 565 verifyFormat("if constexpr (a)\n" 566 " if constexpr (b)\n" 567 " if constexpr (c)\n" 568 " g();\n" 569 "h();"); 570 verifyFormat("if CONSTEXPR (a)\n" 571 " if CONSTEXPR (b)\n" 572 " if CONSTEXPR (c)\n" 573 " g();\n" 574 "h();"); 575 verifyFormat("if constexpr (a)\n" 576 " if constexpr (b) {\n" 577 " f();\n" 578 " }\n" 579 "g();"); 580 verifyFormat("if CONSTEXPR (a)\n" 581 " if CONSTEXPR (b) {\n" 582 " f();\n" 583 " }\n" 584 "g();"); 585 586 verifyFormat("if (a)\n" 587 " g();"); 588 verifyFormat("if (a) {\n" 589 " g()\n" 590 "};"); 591 verifyFormat("if (a)\n" 592 " g();\n" 593 "else\n" 594 " g();"); 595 verifyFormat("if (a) {\n" 596 " g();\n" 597 "} else\n" 598 " g();"); 599 verifyFormat("if (a)\n" 600 " g();\n" 601 "else {\n" 602 " g();\n" 603 "}"); 604 verifyFormat("if (a) {\n" 605 " g();\n" 606 "} else {\n" 607 " g();\n" 608 "}"); 609 verifyFormat("if (a)\n" 610 " g();\n" 611 "else if (b)\n" 612 " g();\n" 613 "else\n" 614 " g();"); 615 verifyFormat("if (a) {\n" 616 " g();\n" 617 "} else if (b)\n" 618 " g();\n" 619 "else\n" 620 " g();"); 621 verifyFormat("if (a)\n" 622 " g();\n" 623 "else if (b) {\n" 624 " g();\n" 625 "} else\n" 626 " g();"); 627 verifyFormat("if (a)\n" 628 " g();\n" 629 "else if (b)\n" 630 " g();\n" 631 "else {\n" 632 " g();\n" 633 "}"); 634 verifyFormat("if (a)\n" 635 " g();\n" 636 "else if (b) {\n" 637 " g();\n" 638 "} else {\n" 639 " g();\n" 640 "}"); 641 verifyFormat("if (a) {\n" 642 " g();\n" 643 "} else if (b) {\n" 644 " g();\n" 645 "} else {\n" 646 " g();\n" 647 "}"); 648 649 FormatStyle AllowsMergedIf = getLLVMStyle(); 650 AllowsMergedIf.IfMacros.push_back("MYIF"); 651 AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left; 652 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 653 FormatStyle::SIS_WithoutElse; 654 verifyFormat("if (a)\n" 655 " // comment\n" 656 " f();", 657 AllowsMergedIf); 658 verifyFormat("{\n" 659 " if (a)\n" 660 " label:\n" 661 " f();\n" 662 "}", 663 AllowsMergedIf); 664 verifyFormat("#define A \\\n" 665 " if (a) \\\n" 666 " label: \\\n" 667 " f()", 668 AllowsMergedIf); 669 verifyFormat("if (a)\n" 670 " ;", 671 AllowsMergedIf); 672 verifyFormat("if (a)\n" 673 " if (b) return;", 674 AllowsMergedIf); 675 676 verifyFormat("if (a) // Can't merge this\n" 677 " f();\n", 678 AllowsMergedIf); 679 verifyFormat("if (a) /* still don't merge */\n" 680 " f();", 681 AllowsMergedIf); 682 verifyFormat("if (a) { // Never merge this\n" 683 " f();\n" 684 "}", 685 AllowsMergedIf); 686 verifyFormat("if (a) { /* Never merge this */\n" 687 " f();\n" 688 "}", 689 AllowsMergedIf); 690 verifyFormat("MYIF (a)\n" 691 " // comment\n" 692 " f();", 693 AllowsMergedIf); 694 verifyFormat("{\n" 695 " MYIF (a)\n" 696 " label:\n" 697 " f();\n" 698 "}", 699 AllowsMergedIf); 700 verifyFormat("#define A \\\n" 701 " MYIF (a) \\\n" 702 " label: \\\n" 703 " f()", 704 AllowsMergedIf); 705 verifyFormat("MYIF (a)\n" 706 " ;", 707 AllowsMergedIf); 708 verifyFormat("MYIF (a)\n" 709 " MYIF (b) return;", 710 AllowsMergedIf); 711 712 verifyFormat("MYIF (a) // Can't merge this\n" 713 " f();\n", 714 AllowsMergedIf); 715 verifyFormat("MYIF (a) /* still don't merge */\n" 716 " f();", 717 AllowsMergedIf); 718 verifyFormat("MYIF (a) { // Never merge this\n" 719 " f();\n" 720 "}", 721 AllowsMergedIf); 722 verifyFormat("MYIF (a) { /* Never merge this */\n" 723 " f();\n" 724 "}", 725 AllowsMergedIf); 726 727 AllowsMergedIf.ColumnLimit = 14; 728 // Where line-lengths matter, a 2-letter synonym that maintains line length. 729 // Not IF to avoid any confusion that IF is somehow special. 730 AllowsMergedIf.IfMacros.push_back("FI"); 731 verifyFormat("if (a) return;", AllowsMergedIf); 732 verifyFormat("if (aaaaaaaaa)\n" 733 " return;", 734 AllowsMergedIf); 735 verifyFormat("FI (a) return;", AllowsMergedIf); 736 verifyFormat("FI (aaaaaaaaa)\n" 737 " return;", 738 AllowsMergedIf); 739 740 AllowsMergedIf.ColumnLimit = 13; 741 verifyFormat("if (a)\n return;", AllowsMergedIf); 742 verifyFormat("FI (a)\n return;", AllowsMergedIf); 743 744 FormatStyle AllowsMergedIfElse = getLLVMStyle(); 745 AllowsMergedIfElse.IfMacros.push_back("MYIF"); 746 AllowsMergedIfElse.AllowShortIfStatementsOnASingleLine = 747 FormatStyle::SIS_AllIfsAndElse; 748 verifyFormat("if (a)\n" 749 " // comment\n" 750 " f();\n" 751 "else\n" 752 " // comment\n" 753 " f();", 754 AllowsMergedIfElse); 755 verifyFormat("{\n" 756 " if (a)\n" 757 " label:\n" 758 " f();\n" 759 " else\n" 760 " label:\n" 761 " f();\n" 762 "}", 763 AllowsMergedIfElse); 764 verifyFormat("if (a)\n" 765 " ;\n" 766 "else\n" 767 " ;", 768 AllowsMergedIfElse); 769 verifyFormat("if (a) {\n" 770 "} else {\n" 771 "}", 772 AllowsMergedIfElse); 773 verifyFormat("if (a) return;\n" 774 "else if (b) return;\n" 775 "else return;", 776 AllowsMergedIfElse); 777 verifyFormat("if (a) {\n" 778 "} else return;", 779 AllowsMergedIfElse); 780 verifyFormat("if (a) {\n" 781 "} else if (b) return;\n" 782 "else return;", 783 AllowsMergedIfElse); 784 verifyFormat("if (a) return;\n" 785 "else if (b) {\n" 786 "} else return;", 787 AllowsMergedIfElse); 788 verifyFormat("if (a)\n" 789 " if (b) return;\n" 790 " else return;", 791 AllowsMergedIfElse); 792 verifyFormat("if constexpr (a)\n" 793 " if constexpr (b) return;\n" 794 " else if constexpr (c) return;\n" 795 " else return;", 796 AllowsMergedIfElse); 797 verifyFormat("MYIF (a)\n" 798 " // comment\n" 799 " f();\n" 800 "else\n" 801 " // comment\n" 802 " f();", 803 AllowsMergedIfElse); 804 verifyFormat("{\n" 805 " MYIF (a)\n" 806 " label:\n" 807 " f();\n" 808 " else\n" 809 " label:\n" 810 " f();\n" 811 "}", 812 AllowsMergedIfElse); 813 verifyFormat("MYIF (a)\n" 814 " ;\n" 815 "else\n" 816 " ;", 817 AllowsMergedIfElse); 818 verifyFormat("MYIF (a) {\n" 819 "} else {\n" 820 "}", 821 AllowsMergedIfElse); 822 verifyFormat("MYIF (a) return;\n" 823 "else MYIF (b) return;\n" 824 "else return;", 825 AllowsMergedIfElse); 826 verifyFormat("MYIF (a) {\n" 827 "} else return;", 828 AllowsMergedIfElse); 829 verifyFormat("MYIF (a) {\n" 830 "} else MYIF (b) return;\n" 831 "else return;", 832 AllowsMergedIfElse); 833 verifyFormat("MYIF (a) return;\n" 834 "else MYIF (b) {\n" 835 "} else return;", 836 AllowsMergedIfElse); 837 verifyFormat("MYIF (a)\n" 838 " MYIF (b) return;\n" 839 " else return;", 840 AllowsMergedIfElse); 841 verifyFormat("MYIF constexpr (a)\n" 842 " MYIF constexpr (b) return;\n" 843 " else MYIF constexpr (c) return;\n" 844 " else return;", 845 AllowsMergedIfElse); 846 } 847 848 TEST_F(FormatTest, FormatIfWithoutCompoundStatementButElseWith) { 849 FormatStyle AllowsMergedIf = getLLVMStyle(); 850 AllowsMergedIf.IfMacros.push_back("MYIF"); 851 AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left; 852 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 853 FormatStyle::SIS_WithoutElse; 854 verifyFormat("if (a)\n" 855 " f();\n" 856 "else {\n" 857 " g();\n" 858 "}", 859 AllowsMergedIf); 860 verifyFormat("if (a)\n" 861 " f();\n" 862 "else\n" 863 " g();\n", 864 AllowsMergedIf); 865 866 verifyFormat("if (a) g();", AllowsMergedIf); 867 verifyFormat("if (a) {\n" 868 " g()\n" 869 "};", 870 AllowsMergedIf); 871 verifyFormat("if (a)\n" 872 " g();\n" 873 "else\n" 874 " g();", 875 AllowsMergedIf); 876 verifyFormat("if (a) {\n" 877 " g();\n" 878 "} else\n" 879 " g();", 880 AllowsMergedIf); 881 verifyFormat("if (a)\n" 882 " g();\n" 883 "else {\n" 884 " g();\n" 885 "}", 886 AllowsMergedIf); 887 verifyFormat("if (a) {\n" 888 " g();\n" 889 "} else {\n" 890 " g();\n" 891 "}", 892 AllowsMergedIf); 893 verifyFormat("if (a)\n" 894 " g();\n" 895 "else if (b)\n" 896 " g();\n" 897 "else\n" 898 " g();", 899 AllowsMergedIf); 900 verifyFormat("if (a) {\n" 901 " g();\n" 902 "} else if (b)\n" 903 " g();\n" 904 "else\n" 905 " g();", 906 AllowsMergedIf); 907 verifyFormat("if (a)\n" 908 " g();\n" 909 "else if (b) {\n" 910 " g();\n" 911 "} else\n" 912 " g();", 913 AllowsMergedIf); 914 verifyFormat("if (a)\n" 915 " g();\n" 916 "else if (b)\n" 917 " g();\n" 918 "else {\n" 919 " g();\n" 920 "}", 921 AllowsMergedIf); 922 verifyFormat("if (a)\n" 923 " g();\n" 924 "else if (b) {\n" 925 " g();\n" 926 "} else {\n" 927 " g();\n" 928 "}", 929 AllowsMergedIf); 930 verifyFormat("if (a) {\n" 931 " g();\n" 932 "} else if (b) {\n" 933 " g();\n" 934 "} else {\n" 935 " g();\n" 936 "}", 937 AllowsMergedIf); 938 verifyFormat("MYIF (a)\n" 939 " f();\n" 940 "else {\n" 941 " g();\n" 942 "}", 943 AllowsMergedIf); 944 verifyFormat("MYIF (a)\n" 945 " f();\n" 946 "else\n" 947 " g();\n", 948 AllowsMergedIf); 949 950 verifyFormat("MYIF (a) g();", AllowsMergedIf); 951 verifyFormat("MYIF (a) {\n" 952 " g()\n" 953 "};", 954 AllowsMergedIf); 955 verifyFormat("MYIF (a)\n" 956 " g();\n" 957 "else\n" 958 " g();", 959 AllowsMergedIf); 960 verifyFormat("MYIF (a) {\n" 961 " g();\n" 962 "} else\n" 963 " g();", 964 AllowsMergedIf); 965 verifyFormat("MYIF (a)\n" 966 " g();\n" 967 "else {\n" 968 " g();\n" 969 "}", 970 AllowsMergedIf); 971 verifyFormat("MYIF (a) {\n" 972 " g();\n" 973 "} else {\n" 974 " g();\n" 975 "}", 976 AllowsMergedIf); 977 verifyFormat("MYIF (a)\n" 978 " g();\n" 979 "else MYIF (b)\n" 980 " g();\n" 981 "else\n" 982 " g();", 983 AllowsMergedIf); 984 verifyFormat("MYIF (a)\n" 985 " g();\n" 986 "else if (b)\n" 987 " g();\n" 988 "else\n" 989 " g();", 990 AllowsMergedIf); 991 verifyFormat("MYIF (a) {\n" 992 " g();\n" 993 "} else MYIF (b)\n" 994 " g();\n" 995 "else\n" 996 " g();", 997 AllowsMergedIf); 998 verifyFormat("MYIF (a) {\n" 999 " g();\n" 1000 "} else if (b)\n" 1001 " g();\n" 1002 "else\n" 1003 " g();", 1004 AllowsMergedIf); 1005 verifyFormat("MYIF (a)\n" 1006 " g();\n" 1007 "else MYIF (b) {\n" 1008 " g();\n" 1009 "} else\n" 1010 " g();", 1011 AllowsMergedIf); 1012 verifyFormat("MYIF (a)\n" 1013 " g();\n" 1014 "else if (b) {\n" 1015 " g();\n" 1016 "} else\n" 1017 " g();", 1018 AllowsMergedIf); 1019 verifyFormat("MYIF (a)\n" 1020 " g();\n" 1021 "else MYIF (b)\n" 1022 " g();\n" 1023 "else {\n" 1024 " g();\n" 1025 "}", 1026 AllowsMergedIf); 1027 verifyFormat("MYIF (a)\n" 1028 " g();\n" 1029 "else if (b)\n" 1030 " g();\n" 1031 "else {\n" 1032 " g();\n" 1033 "}", 1034 AllowsMergedIf); 1035 verifyFormat("MYIF (a)\n" 1036 " g();\n" 1037 "else MYIF (b) {\n" 1038 " g();\n" 1039 "} else {\n" 1040 " g();\n" 1041 "}", 1042 AllowsMergedIf); 1043 verifyFormat("MYIF (a)\n" 1044 " g();\n" 1045 "else if (b) {\n" 1046 " g();\n" 1047 "} else {\n" 1048 " g();\n" 1049 "}", 1050 AllowsMergedIf); 1051 verifyFormat("MYIF (a) {\n" 1052 " g();\n" 1053 "} else MYIF (b) {\n" 1054 " g();\n" 1055 "} else {\n" 1056 " g();\n" 1057 "}", 1058 AllowsMergedIf); 1059 verifyFormat("MYIF (a) {\n" 1060 " g();\n" 1061 "} else if (b) {\n" 1062 " g();\n" 1063 "} else {\n" 1064 " g();\n" 1065 "}", 1066 AllowsMergedIf); 1067 1068 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 1069 FormatStyle::SIS_OnlyFirstIf; 1070 1071 verifyFormat("if (a) f();\n" 1072 "else {\n" 1073 " g();\n" 1074 "}", 1075 AllowsMergedIf); 1076 verifyFormat("if (a) f();\n" 1077 "else {\n" 1078 " if (a) f();\n" 1079 " else {\n" 1080 " g();\n" 1081 " }\n" 1082 " g();\n" 1083 "}", 1084 AllowsMergedIf); 1085 1086 verifyFormat("if (a) g();", AllowsMergedIf); 1087 verifyFormat("if (a) {\n" 1088 " g()\n" 1089 "};", 1090 AllowsMergedIf); 1091 verifyFormat("if (a) g();\n" 1092 "else\n" 1093 " g();", 1094 AllowsMergedIf); 1095 verifyFormat("if (a) {\n" 1096 " g();\n" 1097 "} else\n" 1098 " g();", 1099 AllowsMergedIf); 1100 verifyFormat("if (a) g();\n" 1101 "else {\n" 1102 " g();\n" 1103 "}", 1104 AllowsMergedIf); 1105 verifyFormat("if (a) {\n" 1106 " g();\n" 1107 "} else {\n" 1108 " g();\n" 1109 "}", 1110 AllowsMergedIf); 1111 verifyFormat("if (a) g();\n" 1112 "else if (b)\n" 1113 " g();\n" 1114 "else\n" 1115 " g();", 1116 AllowsMergedIf); 1117 verifyFormat("if (a) {\n" 1118 " g();\n" 1119 "} else if (b)\n" 1120 " g();\n" 1121 "else\n" 1122 " g();", 1123 AllowsMergedIf); 1124 verifyFormat("if (a) g();\n" 1125 "else if (b) {\n" 1126 " g();\n" 1127 "} else\n" 1128 " g();", 1129 AllowsMergedIf); 1130 verifyFormat("if (a) g();\n" 1131 "else if (b)\n" 1132 " g();\n" 1133 "else {\n" 1134 " g();\n" 1135 "}", 1136 AllowsMergedIf); 1137 verifyFormat("if (a) g();\n" 1138 "else if (b) {\n" 1139 " g();\n" 1140 "} else {\n" 1141 " g();\n" 1142 "}", 1143 AllowsMergedIf); 1144 verifyFormat("if (a) {\n" 1145 " g();\n" 1146 "} else if (b) {\n" 1147 " g();\n" 1148 "} else {\n" 1149 " g();\n" 1150 "}", 1151 AllowsMergedIf); 1152 verifyFormat("MYIF (a) f();\n" 1153 "else {\n" 1154 " g();\n" 1155 "}", 1156 AllowsMergedIf); 1157 verifyFormat("MYIF (a) f();\n" 1158 "else {\n" 1159 " if (a) f();\n" 1160 " else {\n" 1161 " g();\n" 1162 " }\n" 1163 " g();\n" 1164 "}", 1165 AllowsMergedIf); 1166 1167 verifyFormat("MYIF (a) g();", AllowsMergedIf); 1168 verifyFormat("MYIF (a) {\n" 1169 " g()\n" 1170 "};", 1171 AllowsMergedIf); 1172 verifyFormat("MYIF (a) g();\n" 1173 "else\n" 1174 " g();", 1175 AllowsMergedIf); 1176 verifyFormat("MYIF (a) {\n" 1177 " g();\n" 1178 "} else\n" 1179 " g();", 1180 AllowsMergedIf); 1181 verifyFormat("MYIF (a) g();\n" 1182 "else {\n" 1183 " g();\n" 1184 "}", 1185 AllowsMergedIf); 1186 verifyFormat("MYIF (a) {\n" 1187 " g();\n" 1188 "} else {\n" 1189 " g();\n" 1190 "}", 1191 AllowsMergedIf); 1192 verifyFormat("MYIF (a) g();\n" 1193 "else MYIF (b)\n" 1194 " g();\n" 1195 "else\n" 1196 " g();", 1197 AllowsMergedIf); 1198 verifyFormat("MYIF (a) g();\n" 1199 "else if (b)\n" 1200 " g();\n" 1201 "else\n" 1202 " g();", 1203 AllowsMergedIf); 1204 verifyFormat("MYIF (a) {\n" 1205 " g();\n" 1206 "} else MYIF (b)\n" 1207 " g();\n" 1208 "else\n" 1209 " g();", 1210 AllowsMergedIf); 1211 verifyFormat("MYIF (a) {\n" 1212 " g();\n" 1213 "} else if (b)\n" 1214 " g();\n" 1215 "else\n" 1216 " g();", 1217 AllowsMergedIf); 1218 verifyFormat("MYIF (a) g();\n" 1219 "else MYIF (b) {\n" 1220 " g();\n" 1221 "} else\n" 1222 " g();", 1223 AllowsMergedIf); 1224 verifyFormat("MYIF (a) g();\n" 1225 "else if (b) {\n" 1226 " g();\n" 1227 "} else\n" 1228 " g();", 1229 AllowsMergedIf); 1230 verifyFormat("MYIF (a) g();\n" 1231 "else MYIF (b)\n" 1232 " g();\n" 1233 "else {\n" 1234 " g();\n" 1235 "}", 1236 AllowsMergedIf); 1237 verifyFormat("MYIF (a) g();\n" 1238 "else if (b)\n" 1239 " g();\n" 1240 "else {\n" 1241 " g();\n" 1242 "}", 1243 AllowsMergedIf); 1244 verifyFormat("MYIF (a) g();\n" 1245 "else MYIF (b) {\n" 1246 " g();\n" 1247 "} else {\n" 1248 " g();\n" 1249 "}", 1250 AllowsMergedIf); 1251 verifyFormat("MYIF (a) g();\n" 1252 "else if (b) {\n" 1253 " g();\n" 1254 "} else {\n" 1255 " g();\n" 1256 "}", 1257 AllowsMergedIf); 1258 verifyFormat("MYIF (a) {\n" 1259 " g();\n" 1260 "} else MYIF (b) {\n" 1261 " g();\n" 1262 "} else {\n" 1263 " g();\n" 1264 "}", 1265 AllowsMergedIf); 1266 verifyFormat("MYIF (a) {\n" 1267 " g();\n" 1268 "} else if (b) {\n" 1269 " g();\n" 1270 "} else {\n" 1271 " g();\n" 1272 "}", 1273 AllowsMergedIf); 1274 1275 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 1276 FormatStyle::SIS_AllIfsAndElse; 1277 1278 verifyFormat("if (a) f();\n" 1279 "else {\n" 1280 " g();\n" 1281 "}", 1282 AllowsMergedIf); 1283 verifyFormat("if (a) f();\n" 1284 "else {\n" 1285 " if (a) f();\n" 1286 " else {\n" 1287 " g();\n" 1288 " }\n" 1289 " g();\n" 1290 "}", 1291 AllowsMergedIf); 1292 1293 verifyFormat("if (a) g();", AllowsMergedIf); 1294 verifyFormat("if (a) {\n" 1295 " g()\n" 1296 "};", 1297 AllowsMergedIf); 1298 verifyFormat("if (a) g();\n" 1299 "else g();", 1300 AllowsMergedIf); 1301 verifyFormat("if (a) {\n" 1302 " g();\n" 1303 "} else g();", 1304 AllowsMergedIf); 1305 verifyFormat("if (a) g();\n" 1306 "else {\n" 1307 " g();\n" 1308 "}", 1309 AllowsMergedIf); 1310 verifyFormat("if (a) {\n" 1311 " g();\n" 1312 "} else {\n" 1313 " g();\n" 1314 "}", 1315 AllowsMergedIf); 1316 verifyFormat("if (a) g();\n" 1317 "else if (b) g();\n" 1318 "else g();", 1319 AllowsMergedIf); 1320 verifyFormat("if (a) {\n" 1321 " g();\n" 1322 "} else if (b) g();\n" 1323 "else g();", 1324 AllowsMergedIf); 1325 verifyFormat("if (a) g();\n" 1326 "else if (b) {\n" 1327 " g();\n" 1328 "} else g();", 1329 AllowsMergedIf); 1330 verifyFormat("if (a) g();\n" 1331 "else if (b) g();\n" 1332 "else {\n" 1333 " g();\n" 1334 "}", 1335 AllowsMergedIf); 1336 verifyFormat("if (a) g();\n" 1337 "else if (b) {\n" 1338 " g();\n" 1339 "} else {\n" 1340 " g();\n" 1341 "}", 1342 AllowsMergedIf); 1343 verifyFormat("if (a) {\n" 1344 " g();\n" 1345 "} else if (b) {\n" 1346 " g();\n" 1347 "} else {\n" 1348 " g();\n" 1349 "}", 1350 AllowsMergedIf); 1351 verifyFormat("MYIF (a) f();\n" 1352 "else {\n" 1353 " g();\n" 1354 "}", 1355 AllowsMergedIf); 1356 verifyFormat("MYIF (a) f();\n" 1357 "else {\n" 1358 " if (a) f();\n" 1359 " else {\n" 1360 " g();\n" 1361 " }\n" 1362 " g();\n" 1363 "}", 1364 AllowsMergedIf); 1365 1366 verifyFormat("MYIF (a) g();", AllowsMergedIf); 1367 verifyFormat("MYIF (a) {\n" 1368 " g()\n" 1369 "};", 1370 AllowsMergedIf); 1371 verifyFormat("MYIF (a) g();\n" 1372 "else g();", 1373 AllowsMergedIf); 1374 verifyFormat("MYIF (a) {\n" 1375 " g();\n" 1376 "} else g();", 1377 AllowsMergedIf); 1378 verifyFormat("MYIF (a) g();\n" 1379 "else {\n" 1380 " g();\n" 1381 "}", 1382 AllowsMergedIf); 1383 verifyFormat("MYIF (a) {\n" 1384 " g();\n" 1385 "} else {\n" 1386 " g();\n" 1387 "}", 1388 AllowsMergedIf); 1389 verifyFormat("MYIF (a) g();\n" 1390 "else MYIF (b) g();\n" 1391 "else g();", 1392 AllowsMergedIf); 1393 verifyFormat("MYIF (a) g();\n" 1394 "else if (b) g();\n" 1395 "else g();", 1396 AllowsMergedIf); 1397 verifyFormat("MYIF (a) {\n" 1398 " g();\n" 1399 "} else MYIF (b) g();\n" 1400 "else g();", 1401 AllowsMergedIf); 1402 verifyFormat("MYIF (a) {\n" 1403 " g();\n" 1404 "} else if (b) g();\n" 1405 "else g();", 1406 AllowsMergedIf); 1407 verifyFormat("MYIF (a) g();\n" 1408 "else MYIF (b) {\n" 1409 " g();\n" 1410 "} else g();", 1411 AllowsMergedIf); 1412 verifyFormat("MYIF (a) g();\n" 1413 "else if (b) {\n" 1414 " g();\n" 1415 "} else g();", 1416 AllowsMergedIf); 1417 verifyFormat("MYIF (a) g();\n" 1418 "else MYIF (b) g();\n" 1419 "else {\n" 1420 " g();\n" 1421 "}", 1422 AllowsMergedIf); 1423 verifyFormat("MYIF (a) g();\n" 1424 "else if (b) g();\n" 1425 "else {\n" 1426 " g();\n" 1427 "}", 1428 AllowsMergedIf); 1429 verifyFormat("MYIF (a) g();\n" 1430 "else MYIF (b) {\n" 1431 " g();\n" 1432 "} else {\n" 1433 " g();\n" 1434 "}", 1435 AllowsMergedIf); 1436 verifyFormat("MYIF (a) g();\n" 1437 "else if (b) {\n" 1438 " g();\n" 1439 "} else {\n" 1440 " g();\n" 1441 "}", 1442 AllowsMergedIf); 1443 verifyFormat("MYIF (a) {\n" 1444 " g();\n" 1445 "} else MYIF (b) {\n" 1446 " g();\n" 1447 "} else {\n" 1448 " g();\n" 1449 "}", 1450 AllowsMergedIf); 1451 verifyFormat("MYIF (a) {\n" 1452 " g();\n" 1453 "} else if (b) {\n" 1454 " g();\n" 1455 "} else {\n" 1456 " g();\n" 1457 "}", 1458 AllowsMergedIf); 1459 } 1460 1461 TEST_F(FormatTest, FormatLoopsWithoutCompoundStatement) { 1462 FormatStyle AllowsMergedLoops = getLLVMStyle(); 1463 AllowsMergedLoops.AllowShortLoopsOnASingleLine = true; 1464 verifyFormat("while (true) continue;", AllowsMergedLoops); 1465 verifyFormat("for (;;) continue;", AllowsMergedLoops); 1466 verifyFormat("for (int &v : vec) v *= 2;", AllowsMergedLoops); 1467 verifyFormat("BOOST_FOREACH (int &v, vec) v *= 2;", AllowsMergedLoops); 1468 verifyFormat("while (true)\n" 1469 " ;", 1470 AllowsMergedLoops); 1471 verifyFormat("for (;;)\n" 1472 " ;", 1473 AllowsMergedLoops); 1474 verifyFormat("for (;;)\n" 1475 " for (;;) continue;", 1476 AllowsMergedLoops); 1477 verifyFormat("for (;;)\n" 1478 " while (true) continue;", 1479 AllowsMergedLoops); 1480 verifyFormat("while (true)\n" 1481 " for (;;) continue;", 1482 AllowsMergedLoops); 1483 verifyFormat("BOOST_FOREACH (int &v, vec)\n" 1484 " for (;;) continue;", 1485 AllowsMergedLoops); 1486 verifyFormat("for (;;)\n" 1487 " BOOST_FOREACH (int &v, vec) continue;", 1488 AllowsMergedLoops); 1489 verifyFormat("for (;;) // Can't merge this\n" 1490 " continue;", 1491 AllowsMergedLoops); 1492 verifyFormat("for (;;) /* still don't merge */\n" 1493 " continue;", 1494 AllowsMergedLoops); 1495 verifyFormat("do a++;\n" 1496 "while (true);", 1497 AllowsMergedLoops); 1498 verifyFormat("do /* Don't merge */\n" 1499 " a++;\n" 1500 "while (true);", 1501 AllowsMergedLoops); 1502 verifyFormat("do // Don't merge\n" 1503 " a++;\n" 1504 "while (true);", 1505 AllowsMergedLoops); 1506 verifyFormat("do\n" 1507 " // Don't merge\n" 1508 " a++;\n" 1509 "while (true);", 1510 AllowsMergedLoops); 1511 // Without braces labels are interpreted differently. 1512 verifyFormat("{\n" 1513 " do\n" 1514 " label:\n" 1515 " a++;\n" 1516 " while (true);\n" 1517 "}", 1518 AllowsMergedLoops); 1519 } 1520 1521 TEST_F(FormatTest, FormatShortBracedStatements) { 1522 FormatStyle AllowSimpleBracedStatements = getLLVMStyle(); 1523 AllowSimpleBracedStatements.IfMacros.push_back("MYIF"); 1524 // Where line-lengths matter, a 2-letter synonym that maintains line length. 1525 // Not IF to avoid any confusion that IF is somehow special. 1526 AllowSimpleBracedStatements.IfMacros.push_back("FI"); 1527 AllowSimpleBracedStatements.ColumnLimit = 40; 1528 AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine = 1529 FormatStyle::SBS_Always; 1530 1531 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1532 FormatStyle::SIS_WithoutElse; 1533 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true; 1534 1535 AllowSimpleBracedStatements.BreakBeforeBraces = FormatStyle::BS_Custom; 1536 AllowSimpleBracedStatements.BraceWrapping.AfterFunction = true; 1537 AllowSimpleBracedStatements.BraceWrapping.SplitEmptyRecord = false; 1538 1539 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1540 verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements); 1541 verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1542 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1543 verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements); 1544 verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1545 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1546 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1547 verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements); 1548 verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements); 1549 verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1550 verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements); 1551 verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements); 1552 verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1553 verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements); 1554 verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements); 1555 verifyFormat("if (true) { fffffffffffffffffffffff(); }", 1556 AllowSimpleBracedStatements); 1557 verifyFormat("if (true) {\n" 1558 " ffffffffffffffffffffffff();\n" 1559 "}", 1560 AllowSimpleBracedStatements); 1561 verifyFormat("if (true) {\n" 1562 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1563 "}", 1564 AllowSimpleBracedStatements); 1565 verifyFormat("if (true) { //\n" 1566 " f();\n" 1567 "}", 1568 AllowSimpleBracedStatements); 1569 verifyFormat("if (true) {\n" 1570 " f();\n" 1571 " f();\n" 1572 "}", 1573 AllowSimpleBracedStatements); 1574 verifyFormat("if (true) {\n" 1575 " f();\n" 1576 "} else {\n" 1577 " f();\n" 1578 "}", 1579 AllowSimpleBracedStatements); 1580 verifyFormat("FI (true) { fffffffffffffffffffffff(); }", 1581 AllowSimpleBracedStatements); 1582 verifyFormat("MYIF (true) {\n" 1583 " ffffffffffffffffffffffff();\n" 1584 "}", 1585 AllowSimpleBracedStatements); 1586 verifyFormat("MYIF (true) {\n" 1587 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1588 "}", 1589 AllowSimpleBracedStatements); 1590 verifyFormat("MYIF (true) { //\n" 1591 " f();\n" 1592 "}", 1593 AllowSimpleBracedStatements); 1594 verifyFormat("MYIF (true) {\n" 1595 " f();\n" 1596 " f();\n" 1597 "}", 1598 AllowSimpleBracedStatements); 1599 verifyFormat("MYIF (true) {\n" 1600 " f();\n" 1601 "} else {\n" 1602 " f();\n" 1603 "}", 1604 AllowSimpleBracedStatements); 1605 1606 verifyFormat("struct A2 {\n" 1607 " int X;\n" 1608 "};", 1609 AllowSimpleBracedStatements); 1610 verifyFormat("typedef struct A2 {\n" 1611 " int X;\n" 1612 "} A2_t;", 1613 AllowSimpleBracedStatements); 1614 verifyFormat("template <int> struct A2 {\n" 1615 " struct B {};\n" 1616 "};", 1617 AllowSimpleBracedStatements); 1618 1619 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1620 FormatStyle::SIS_Never; 1621 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1622 verifyFormat("if (true) {\n" 1623 " f();\n" 1624 "}", 1625 AllowSimpleBracedStatements); 1626 verifyFormat("if (true) {\n" 1627 " f();\n" 1628 "} else {\n" 1629 " f();\n" 1630 "}", 1631 AllowSimpleBracedStatements); 1632 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1633 verifyFormat("MYIF (true) {\n" 1634 " f();\n" 1635 "}", 1636 AllowSimpleBracedStatements); 1637 verifyFormat("MYIF (true) {\n" 1638 " f();\n" 1639 "} else {\n" 1640 " f();\n" 1641 "}", 1642 AllowSimpleBracedStatements); 1643 1644 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false; 1645 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1646 verifyFormat("while (true) {\n" 1647 " f();\n" 1648 "}", 1649 AllowSimpleBracedStatements); 1650 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1651 verifyFormat("for (;;) {\n" 1652 " f();\n" 1653 "}", 1654 AllowSimpleBracedStatements); 1655 verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements); 1656 verifyFormat("BOOST_FOREACH (int v, vec) {\n" 1657 " f();\n" 1658 "}", 1659 AllowSimpleBracedStatements); 1660 1661 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1662 FormatStyle::SIS_WithoutElse; 1663 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true; 1664 AllowSimpleBracedStatements.BraceWrapping.AfterControlStatement = 1665 FormatStyle::BWACS_Always; 1666 1667 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1668 verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements); 1669 verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1670 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1671 verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements); 1672 verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1673 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1674 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1675 verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements); 1676 verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements); 1677 verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1678 verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements); 1679 verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements); 1680 verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1681 verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements); 1682 verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements); 1683 verifyFormat("if (true) { fffffffffffffffffffffff(); }", 1684 AllowSimpleBracedStatements); 1685 verifyFormat("if (true)\n" 1686 "{\n" 1687 " ffffffffffffffffffffffff();\n" 1688 "}", 1689 AllowSimpleBracedStatements); 1690 verifyFormat("if (true)\n" 1691 "{\n" 1692 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1693 "}", 1694 AllowSimpleBracedStatements); 1695 verifyFormat("if (true)\n" 1696 "{ //\n" 1697 " f();\n" 1698 "}", 1699 AllowSimpleBracedStatements); 1700 verifyFormat("if (true)\n" 1701 "{\n" 1702 " f();\n" 1703 " f();\n" 1704 "}", 1705 AllowSimpleBracedStatements); 1706 verifyFormat("if (true)\n" 1707 "{\n" 1708 " f();\n" 1709 "} else\n" 1710 "{\n" 1711 " f();\n" 1712 "}", 1713 AllowSimpleBracedStatements); 1714 verifyFormat("FI (true) { fffffffffffffffffffffff(); }", 1715 AllowSimpleBracedStatements); 1716 verifyFormat("MYIF (true)\n" 1717 "{\n" 1718 " ffffffffffffffffffffffff();\n" 1719 "}", 1720 AllowSimpleBracedStatements); 1721 verifyFormat("MYIF (true)\n" 1722 "{\n" 1723 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1724 "}", 1725 AllowSimpleBracedStatements); 1726 verifyFormat("MYIF (true)\n" 1727 "{ //\n" 1728 " f();\n" 1729 "}", 1730 AllowSimpleBracedStatements); 1731 verifyFormat("MYIF (true)\n" 1732 "{\n" 1733 " f();\n" 1734 " f();\n" 1735 "}", 1736 AllowSimpleBracedStatements); 1737 verifyFormat("MYIF (true)\n" 1738 "{\n" 1739 " f();\n" 1740 "} else\n" 1741 "{\n" 1742 " f();\n" 1743 "}", 1744 AllowSimpleBracedStatements); 1745 1746 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1747 FormatStyle::SIS_Never; 1748 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1749 verifyFormat("if (true)\n" 1750 "{\n" 1751 " f();\n" 1752 "}", 1753 AllowSimpleBracedStatements); 1754 verifyFormat("if (true)\n" 1755 "{\n" 1756 " f();\n" 1757 "} else\n" 1758 "{\n" 1759 " f();\n" 1760 "}", 1761 AllowSimpleBracedStatements); 1762 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1763 verifyFormat("MYIF (true)\n" 1764 "{\n" 1765 " f();\n" 1766 "}", 1767 AllowSimpleBracedStatements); 1768 verifyFormat("MYIF (true)\n" 1769 "{\n" 1770 " f();\n" 1771 "} else\n" 1772 "{\n" 1773 " f();\n" 1774 "}", 1775 AllowSimpleBracedStatements); 1776 1777 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false; 1778 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1779 verifyFormat("while (true)\n" 1780 "{\n" 1781 " f();\n" 1782 "}", 1783 AllowSimpleBracedStatements); 1784 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1785 verifyFormat("for (;;)\n" 1786 "{\n" 1787 " f();\n" 1788 "}", 1789 AllowSimpleBracedStatements); 1790 verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements); 1791 verifyFormat("BOOST_FOREACH (int v, vec)\n" 1792 "{\n" 1793 " f();\n" 1794 "}", 1795 AllowSimpleBracedStatements); 1796 } 1797 1798 TEST_F(FormatTest, UnderstandsMacros) { 1799 verifyFormat("#define A (parentheses)"); 1800 verifyFormat("/* comment */ #define A (parentheses)"); 1801 verifyFormat("/* comment */ /* another comment */ #define A (parentheses)"); 1802 // Even the partial code should never be merged. 1803 EXPECT_EQ("/* comment */ #define A (parentheses)\n" 1804 "#", 1805 format("/* comment */ #define A (parentheses)\n" 1806 "#")); 1807 verifyFormat("/* comment */ #define A (parentheses)\n" 1808 "#\n"); 1809 verifyFormat("/* comment */ #define A (parentheses)\n" 1810 "#define B (parentheses)"); 1811 verifyFormat("#define true ((int)1)"); 1812 verifyFormat("#define and(x)"); 1813 verifyFormat("#define if(x) x"); 1814 verifyFormat("#define return(x) (x)"); 1815 verifyFormat("#define while(x) for (; x;)"); 1816 verifyFormat("#define xor(x) (^(x))"); 1817 verifyFormat("#define __except(x)"); 1818 verifyFormat("#define __try(x)"); 1819 1820 FormatStyle Style = getLLVMStyle(); 1821 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 1822 Style.BraceWrapping.AfterFunction = true; 1823 // Test that a macro definition never gets merged with the following 1824 // definition. 1825 // FIXME: The AAA macro definition probably should not be split into 3 lines. 1826 verifyFormat("#define AAA " 1827 " \\\n" 1828 " N " 1829 " \\\n" 1830 " {\n" 1831 "#define BBB }\n", 1832 Style); 1833 // verifyFormat("#define AAA N { //\n", Style); 1834 } 1835 1836 TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) { 1837 FormatStyle Style = getLLVMStyleWithColumns(60); 1838 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 1839 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse; 1840 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 1841 EXPECT_EQ("#define A \\\n" 1842 " if (HANDLEwernufrnuLwrmviferuvnierv) \\\n" 1843 " { \\\n" 1844 " RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n" 1845 " }\n" 1846 "X;", 1847 format("#define A \\\n" 1848 " if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n" 1849 " RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n" 1850 " }\n" 1851 "X;", 1852 Style)); 1853 } 1854 1855 TEST_F(FormatTest, ParseIfElse) { 1856 verifyFormat("if (true)\n" 1857 " if (true)\n" 1858 " if (true)\n" 1859 " f();\n" 1860 " else\n" 1861 " g();\n" 1862 " else\n" 1863 " h();\n" 1864 "else\n" 1865 " i();"); 1866 verifyFormat("if (true)\n" 1867 " if (true)\n" 1868 " if (true) {\n" 1869 " if (true)\n" 1870 " f();\n" 1871 " } else {\n" 1872 " g();\n" 1873 " }\n" 1874 " else\n" 1875 " h();\n" 1876 "else {\n" 1877 " i();\n" 1878 "}"); 1879 verifyFormat("if (true)\n" 1880 " if constexpr (true)\n" 1881 " if (true) {\n" 1882 " if constexpr (true)\n" 1883 " f();\n" 1884 " } else {\n" 1885 " g();\n" 1886 " }\n" 1887 " else\n" 1888 " h();\n" 1889 "else {\n" 1890 " i();\n" 1891 "}"); 1892 verifyFormat("if (true)\n" 1893 " if CONSTEXPR (true)\n" 1894 " if (true) {\n" 1895 " if CONSTEXPR (true)\n" 1896 " f();\n" 1897 " } else {\n" 1898 " g();\n" 1899 " }\n" 1900 " else\n" 1901 " h();\n" 1902 "else {\n" 1903 " i();\n" 1904 "}"); 1905 verifyFormat("void f() {\n" 1906 " if (a) {\n" 1907 " } else {\n" 1908 " }\n" 1909 "}"); 1910 } 1911 1912 TEST_F(FormatTest, ElseIf) { 1913 verifyFormat("if (a) {\n} else if (b) {\n}"); 1914 verifyFormat("if (a)\n" 1915 " f();\n" 1916 "else if (b)\n" 1917 " g();\n" 1918 "else\n" 1919 " h();"); 1920 verifyFormat("if (a)\n" 1921 " f();\n" 1922 "else // comment\n" 1923 " if (b) {\n" 1924 " g();\n" 1925 " h();\n" 1926 " }"); 1927 verifyFormat("if constexpr (a)\n" 1928 " f();\n" 1929 "else if constexpr (b)\n" 1930 " g();\n" 1931 "else\n" 1932 " h();"); 1933 verifyFormat("if CONSTEXPR (a)\n" 1934 " f();\n" 1935 "else if CONSTEXPR (b)\n" 1936 " g();\n" 1937 "else\n" 1938 " h();"); 1939 verifyFormat("if (a) {\n" 1940 " f();\n" 1941 "}\n" 1942 "// or else ..\n" 1943 "else {\n" 1944 " g()\n" 1945 "}"); 1946 1947 verifyFormat("if (a) {\n" 1948 "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 1949 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 1950 "}"); 1951 verifyFormat("if (a) {\n" 1952 "} else if constexpr (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 1953 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 1954 "}"); 1955 verifyFormat("if (a) {\n" 1956 "} else if CONSTEXPR (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 1957 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 1958 "}"); 1959 verifyFormat("if (a) {\n" 1960 "} else if (\n" 1961 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 1962 "}", 1963 getLLVMStyleWithColumns(62)); 1964 verifyFormat("if (a) {\n" 1965 "} else if constexpr (\n" 1966 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 1967 "}", 1968 getLLVMStyleWithColumns(62)); 1969 verifyFormat("if (a) {\n" 1970 "} else if CONSTEXPR (\n" 1971 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 1972 "}", 1973 getLLVMStyleWithColumns(62)); 1974 } 1975 1976 TEST_F(FormatTest, SeparatePointerReferenceAlignment) { 1977 FormatStyle Style = getLLVMStyle(); 1978 // Check first the default LLVM style 1979 // Style.PointerAlignment = FormatStyle::PAS_Right; 1980 // Style.ReferenceAlignment = FormatStyle::RAS_Pointer; 1981 verifyFormat("int *f1(int *a, int &b, int &&c);", Style); 1982 verifyFormat("int &f2(int &&c, int *a, int &b);", Style); 1983 verifyFormat("int &&f3(int &b, int &&c, int *a);", Style); 1984 verifyFormat("int *f1(int &a) const &;", Style); 1985 verifyFormat("int *f1(int &a) const & = 0;", Style); 1986 verifyFormat("int *a = f1();", Style); 1987 verifyFormat("int &b = f2();", Style); 1988 verifyFormat("int &&c = f3();", Style); 1989 verifyFormat("for (auto a = 0, b = 0; const auto &c : {1, 2, 3})", Style); 1990 verifyFormat("for (auto a = 0, b = 0; const int &c : {1, 2, 3})", Style); 1991 verifyFormat("for (auto a = 0, b = 0; const Foo &c : {1, 2, 3})", Style); 1992 verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style); 1993 verifyFormat("for (int a = 0, b = 0; const auto &c : {1, 2, 3})", Style); 1994 verifyFormat("for (int a = 0, b = 0; const int &c : {1, 2, 3})", Style); 1995 verifyFormat("for (int a = 0, b = 0; const Foo &c : {1, 2, 3})", Style); 1996 verifyFormat("for (int a = 0, b++; const auto &c : {1, 2, 3})", Style); 1997 verifyFormat("for (int a = 0, b++; const int &c : {1, 2, 3})", Style); 1998 verifyFormat("for (int a = 0, b++; const Foo &c : {1, 2, 3})", Style); 1999 verifyFormat("for (auto x = 0; auto &c : {1, 2, 3})", Style); 2000 verifyFormat("for (auto x = 0; int &c : {1, 2, 3})", Style); 2001 verifyFormat("for (int x = 0; auto &c : {1, 2, 3})", Style); 2002 verifyFormat("for (int x = 0; int &c : {1, 2, 3})", Style); 2003 verifyFormat("for (f(); auto &c : {1, 2, 3})", Style); 2004 verifyFormat("for (f(); int &c : {1, 2, 3})", Style); 2005 2006 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 2007 verifyFormat("Const unsigned int *c;\n" 2008 "const unsigned int *d;\n" 2009 "Const unsigned int &e;\n" 2010 "const unsigned int &f;\n" 2011 "const unsigned &&g;\n" 2012 "Const unsigned h;", 2013 Style); 2014 2015 Style.PointerAlignment = FormatStyle::PAS_Left; 2016 Style.ReferenceAlignment = FormatStyle::RAS_Pointer; 2017 verifyFormat("int* f1(int* a, int& b, int&& c);", Style); 2018 verifyFormat("int& f2(int&& c, int* a, int& b);", Style); 2019 verifyFormat("int&& f3(int& b, int&& c, int* a);", Style); 2020 verifyFormat("int* f1(int& a) const& = 0;", Style); 2021 verifyFormat("int* a = f1();", Style); 2022 verifyFormat("int& b = f2();", Style); 2023 verifyFormat("int&& c = f3();", Style); 2024 verifyFormat("for (auto a = 0, b = 0; const auto& c : {1, 2, 3})", Style); 2025 verifyFormat("for (auto a = 0, b = 0; const int& c : {1, 2, 3})", Style); 2026 verifyFormat("for (auto a = 0, b = 0; const Foo& c : {1, 2, 3})", Style); 2027 verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style); 2028 verifyFormat("for (int a = 0, b = 0; const auto& c : {1, 2, 3})", Style); 2029 verifyFormat("for (int a = 0, b = 0; const int& c : {1, 2, 3})", Style); 2030 verifyFormat("for (int a = 0, b = 0; const Foo& c : {1, 2, 3})", Style); 2031 verifyFormat("for (int a = 0, b = 0; const Foo* c : {1, 2, 3})", Style); 2032 verifyFormat("for (int a = 0, b++; const auto& c : {1, 2, 3})", Style); 2033 verifyFormat("for (int a = 0, b++; const int& c : {1, 2, 3})", Style); 2034 verifyFormat("for (int a = 0, b++; const Foo& c : {1, 2, 3})", Style); 2035 verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style); 2036 verifyFormat("for (auto x = 0; auto& c : {1, 2, 3})", Style); 2037 verifyFormat("for (auto x = 0; int& c : {1, 2, 3})", Style); 2038 verifyFormat("for (int x = 0; auto& c : {1, 2, 3})", Style); 2039 verifyFormat("for (int x = 0; int& c : {1, 2, 3})", Style); 2040 verifyFormat("for (f(); auto& c : {1, 2, 3})", Style); 2041 verifyFormat("for (f(); int& c : {1, 2, 3})", Style); 2042 2043 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 2044 verifyFormat("Const unsigned int* c;\n" 2045 "const unsigned int* d;\n" 2046 "Const unsigned int& e;\n" 2047 "const unsigned int& f;\n" 2048 "const unsigned&& g;\n" 2049 "Const unsigned h;", 2050 Style); 2051 2052 Style.PointerAlignment = FormatStyle::PAS_Right; 2053 Style.ReferenceAlignment = FormatStyle::RAS_Left; 2054 verifyFormat("int *f1(int *a, int& b, int&& c);", Style); 2055 verifyFormat("int& f2(int&& c, int *a, int& b);", Style); 2056 verifyFormat("int&& f3(int& b, int&& c, int *a);", Style); 2057 verifyFormat("int *a = f1();", Style); 2058 verifyFormat("int& b = f2();", Style); 2059 verifyFormat("int&& c = f3();", Style); 2060 verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style); 2061 verifyFormat("for (int a = 0, b = 0; const Foo *c : {1, 2, 3})", Style); 2062 verifyFormat("for (int a = 0, b++; const Foo *c : {1, 2, 3})", Style); 2063 2064 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 2065 verifyFormat("Const unsigned int *c;\n" 2066 "const unsigned int *d;\n" 2067 "Const unsigned int& e;\n" 2068 "const unsigned int& f;\n" 2069 "const unsigned g;\n" 2070 "Const unsigned h;", 2071 Style); 2072 2073 Style.PointerAlignment = FormatStyle::PAS_Left; 2074 Style.ReferenceAlignment = FormatStyle::RAS_Middle; 2075 verifyFormat("int* f1(int* a, int & b, int && c);", Style); 2076 verifyFormat("int & f2(int && c, int* a, int & b);", Style); 2077 verifyFormat("int && f3(int & b, int && c, int* a);", Style); 2078 verifyFormat("int* a = f1();", Style); 2079 verifyFormat("int & b = f2();", Style); 2080 verifyFormat("int && c = f3();", Style); 2081 verifyFormat("for (auto a = 0, b = 0; const auto & c : {1, 2, 3})", Style); 2082 verifyFormat("for (auto a = 0, b = 0; const int & c : {1, 2, 3})", Style); 2083 verifyFormat("for (auto a = 0, b = 0; const Foo & c : {1, 2, 3})", Style); 2084 verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style); 2085 verifyFormat("for (int a = 0, b++; const auto & c : {1, 2, 3})", Style); 2086 verifyFormat("for (int a = 0, b++; const int & c : {1, 2, 3})", Style); 2087 verifyFormat("for (int a = 0, b++; const Foo & c : {1, 2, 3})", Style); 2088 verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style); 2089 verifyFormat("for (auto x = 0; auto & c : {1, 2, 3})", Style); 2090 verifyFormat("for (auto x = 0; int & c : {1, 2, 3})", Style); 2091 verifyFormat("for (int x = 0; auto & c : {1, 2, 3})", Style); 2092 verifyFormat("for (int x = 0; int & c : {1, 2, 3})", Style); 2093 verifyFormat("for (f(); auto & c : {1, 2, 3})", Style); 2094 verifyFormat("for (f(); int & c : {1, 2, 3})", Style); 2095 2096 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 2097 verifyFormat("Const unsigned int* c;\n" 2098 "const unsigned int* d;\n" 2099 "Const unsigned int & e;\n" 2100 "const unsigned int & f;\n" 2101 "const unsigned && g;\n" 2102 "Const unsigned h;", 2103 Style); 2104 2105 Style.PointerAlignment = FormatStyle::PAS_Middle; 2106 Style.ReferenceAlignment = FormatStyle::RAS_Right; 2107 verifyFormat("int * f1(int * a, int &b, int &&c);", Style); 2108 verifyFormat("int &f2(int &&c, int * a, int &b);", Style); 2109 verifyFormat("int &&f3(int &b, int &&c, int * a);", Style); 2110 verifyFormat("int * a = f1();", Style); 2111 verifyFormat("int &b = f2();", Style); 2112 verifyFormat("int &&c = f3();", Style); 2113 verifyFormat("for (auto a = 0, b = 0; const Foo * c : {1, 2, 3})", Style); 2114 verifyFormat("for (int a = 0, b = 0; const Foo * c : {1, 2, 3})", Style); 2115 verifyFormat("for (int a = 0, b++; const Foo * c : {1, 2, 3})", Style); 2116 2117 // FIXME: we don't handle this yet, so output may be arbitrary until it's 2118 // specifically handled 2119 // verifyFormat("int Add2(BTree * &Root, char * szToAdd)", Style); 2120 } 2121 2122 TEST_F(FormatTest, FormatsForLoop) { 2123 verifyFormat( 2124 "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n" 2125 " ++VeryVeryLongLoopVariable)\n" 2126 " ;"); 2127 verifyFormat("for (;;)\n" 2128 " f();"); 2129 verifyFormat("for (;;) {\n}"); 2130 verifyFormat("for (;;) {\n" 2131 " f();\n" 2132 "}"); 2133 verifyFormat("for (int i = 0; (i < 10); ++i) {\n}"); 2134 2135 verifyFormat( 2136 "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n" 2137 " E = UnwrappedLines.end();\n" 2138 " I != E; ++I) {\n}"); 2139 2140 verifyFormat( 2141 "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n" 2142 " ++IIIII) {\n}"); 2143 verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n" 2144 " aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n" 2145 " aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}"); 2146 verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n" 2147 " I = FD->getDeclsInPrototypeScope().begin(),\n" 2148 " E = FD->getDeclsInPrototypeScope().end();\n" 2149 " I != E; ++I) {\n}"); 2150 verifyFormat("for (SmallVectorImpl<TemplateIdAnnotationn *>::iterator\n" 2151 " I = Container.begin(),\n" 2152 " E = Container.end();\n" 2153 " I != E; ++I) {\n}", 2154 getLLVMStyleWithColumns(76)); 2155 2156 verifyFormat( 2157 "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n" 2158 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n" 2159 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2160 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 2161 " ++aaaaaaaaaaa) {\n}"); 2162 verifyFormat("for (int i = 0; i < aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 2163 " bbbbbbbbbbbbbbbbbbbb < ccccccccccccccc;\n" 2164 " ++i) {\n}"); 2165 verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n" 2166 " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n" 2167 "}"); 2168 verifyFormat("for (some_namespace::SomeIterator iter( // force break\n" 2169 " aaaaaaaaaa);\n" 2170 " iter; ++iter) {\n" 2171 "}"); 2172 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2173 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 2174 " aaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbbbbbbb;\n" 2175 " ++aaaaaaaaaaaaaaaaaaaaaaaaaaa) {"); 2176 2177 // These should not be formatted as Objective-C for-in loops. 2178 verifyFormat("for (Foo *x = 0; x != in; x++) {\n}"); 2179 verifyFormat("Foo *x;\nfor (x = 0; x != in; x++) {\n}"); 2180 verifyFormat("Foo *x;\nfor (x in y) {\n}"); 2181 verifyFormat( 2182 "for (const Foo<Bar> &baz = in.value(); !baz.at_end(); ++baz) {\n}"); 2183 2184 FormatStyle NoBinPacking = getLLVMStyle(); 2185 NoBinPacking.BinPackParameters = false; 2186 verifyFormat("for (int aaaaaaaaaaa = 1;\n" 2187 " aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n" 2188 " aaaaaaaaaaaaaaaa,\n" 2189 " aaaaaaaaaaaaaaaa,\n" 2190 " aaaaaaaaaaaaaaaa);\n" 2191 " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n" 2192 "}", 2193 NoBinPacking); 2194 verifyFormat( 2195 "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n" 2196 " E = UnwrappedLines.end();\n" 2197 " I != E;\n" 2198 " ++I) {\n}", 2199 NoBinPacking); 2200 2201 FormatStyle AlignLeft = getLLVMStyle(); 2202 AlignLeft.PointerAlignment = FormatStyle::PAS_Left; 2203 verifyFormat("for (A* a = start; a < end; ++a, ++value) {\n}", AlignLeft); 2204 } 2205 2206 TEST_F(FormatTest, RangeBasedForLoops) { 2207 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 2208 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 2209 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n" 2210 " aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}"); 2211 verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n" 2212 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 2213 verifyFormat("for (aaaaaaaaa aaaaaaaaaaaaaaaaaaaaa :\n" 2214 " aaaaaaaaaaaa.aaaaaaaaaaaa().aaaaaaaaa().a()) {\n}"); 2215 } 2216 2217 TEST_F(FormatTest, ForEachLoops) { 2218 FormatStyle Style = getLLVMStyle(); 2219 EXPECT_EQ(Style.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 2220 EXPECT_EQ(Style.AllowShortLoopsOnASingleLine, false); 2221 verifyFormat("void f() {\n" 2222 " for (;;) {\n" 2223 " }\n" 2224 " foreach (Item *item, itemlist) {\n" 2225 " }\n" 2226 " Q_FOREACH (Item *item, itemlist) {\n" 2227 " }\n" 2228 " BOOST_FOREACH (Item *item, itemlist) {\n" 2229 " }\n" 2230 " UNKNOWN_FOREACH(Item * item, itemlist) {}\n" 2231 "}", 2232 Style); 2233 verifyFormat("void f() {\n" 2234 " for (;;)\n" 2235 " int j = 1;\n" 2236 " Q_FOREACH (int v, vec)\n" 2237 " v *= 2;\n" 2238 " for (;;) {\n" 2239 " int j = 1;\n" 2240 " }\n" 2241 " Q_FOREACH (int v, vec) {\n" 2242 " v *= 2;\n" 2243 " }\n" 2244 "}", 2245 Style); 2246 2247 FormatStyle ShortBlocks = getLLVMStyle(); 2248 ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 2249 EXPECT_EQ(ShortBlocks.AllowShortLoopsOnASingleLine, false); 2250 verifyFormat("void f() {\n" 2251 " for (;;)\n" 2252 " int j = 1;\n" 2253 " Q_FOREACH (int &v, vec)\n" 2254 " v *= 2;\n" 2255 " for (;;) {\n" 2256 " int j = 1;\n" 2257 " }\n" 2258 " Q_FOREACH (int &v, vec) {\n" 2259 " int j = 1;\n" 2260 " }\n" 2261 "}", 2262 ShortBlocks); 2263 2264 FormatStyle ShortLoops = getLLVMStyle(); 2265 ShortLoops.AllowShortLoopsOnASingleLine = true; 2266 EXPECT_EQ(ShortLoops.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 2267 verifyFormat("void f() {\n" 2268 " for (;;) int j = 1;\n" 2269 " Q_FOREACH (int &v, vec) int j = 1;\n" 2270 " for (;;) {\n" 2271 " int j = 1;\n" 2272 " }\n" 2273 " Q_FOREACH (int &v, vec) {\n" 2274 " int j = 1;\n" 2275 " }\n" 2276 "}", 2277 ShortLoops); 2278 2279 FormatStyle ShortBlocksAndLoops = getLLVMStyle(); 2280 ShortBlocksAndLoops.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 2281 ShortBlocksAndLoops.AllowShortLoopsOnASingleLine = true; 2282 verifyFormat("void f() {\n" 2283 " for (;;) int j = 1;\n" 2284 " Q_FOREACH (int &v, vec) int j = 1;\n" 2285 " for (;;) { int j = 1; }\n" 2286 " Q_FOREACH (int &v, vec) { int j = 1; }\n" 2287 "}", 2288 ShortBlocksAndLoops); 2289 2290 Style.SpaceBeforeParens = 2291 FormatStyle::SBPO_ControlStatementsExceptControlMacros; 2292 verifyFormat("void f() {\n" 2293 " for (;;) {\n" 2294 " }\n" 2295 " foreach(Item *item, itemlist) {\n" 2296 " }\n" 2297 " Q_FOREACH(Item *item, itemlist) {\n" 2298 " }\n" 2299 " BOOST_FOREACH(Item *item, itemlist) {\n" 2300 " }\n" 2301 " UNKNOWN_FOREACH(Item * item, itemlist) {}\n" 2302 "}", 2303 Style); 2304 2305 // As function-like macros. 2306 verifyFormat("#define foreach(x, y)\n" 2307 "#define Q_FOREACH(x, y)\n" 2308 "#define BOOST_FOREACH(x, y)\n" 2309 "#define UNKNOWN_FOREACH(x, y)\n"); 2310 2311 // Not as function-like macros. 2312 verifyFormat("#define foreach (x, y)\n" 2313 "#define Q_FOREACH (x, y)\n" 2314 "#define BOOST_FOREACH (x, y)\n" 2315 "#define UNKNOWN_FOREACH (x, y)\n"); 2316 2317 // handle microsoft non standard extension 2318 verifyFormat("for each (char c in x->MyStringProperty)"); 2319 } 2320 2321 TEST_F(FormatTest, FormatsWhileLoop) { 2322 verifyFormat("while (true) {\n}"); 2323 verifyFormat("while (true)\n" 2324 " f();"); 2325 verifyFormat("while () {\n}"); 2326 verifyFormat("while () {\n" 2327 " f();\n" 2328 "}"); 2329 } 2330 2331 TEST_F(FormatTest, FormatsDoWhile) { 2332 verifyFormat("do {\n" 2333 " do_something();\n" 2334 "} while (something());"); 2335 verifyFormat("do\n" 2336 " do_something();\n" 2337 "while (something());"); 2338 } 2339 2340 TEST_F(FormatTest, FormatsSwitchStatement) { 2341 verifyFormat("switch (x) {\n" 2342 "case 1:\n" 2343 " f();\n" 2344 " break;\n" 2345 "case kFoo:\n" 2346 "case ns::kBar:\n" 2347 "case kBaz:\n" 2348 " break;\n" 2349 "default:\n" 2350 " g();\n" 2351 " break;\n" 2352 "}"); 2353 verifyFormat("switch (x) {\n" 2354 "case 1: {\n" 2355 " f();\n" 2356 " break;\n" 2357 "}\n" 2358 "case 2: {\n" 2359 " break;\n" 2360 "}\n" 2361 "}"); 2362 verifyFormat("switch (x) {\n" 2363 "case 1: {\n" 2364 " f();\n" 2365 " {\n" 2366 " g();\n" 2367 " h();\n" 2368 " }\n" 2369 " break;\n" 2370 "}\n" 2371 "}"); 2372 verifyFormat("switch (x) {\n" 2373 "case 1: {\n" 2374 " f();\n" 2375 " if (foo) {\n" 2376 " g();\n" 2377 " h();\n" 2378 " }\n" 2379 " break;\n" 2380 "}\n" 2381 "}"); 2382 verifyFormat("switch (x) {\n" 2383 "case 1: {\n" 2384 " f();\n" 2385 " g();\n" 2386 "} break;\n" 2387 "}"); 2388 verifyFormat("switch (test)\n" 2389 " ;"); 2390 verifyFormat("switch (x) {\n" 2391 "default: {\n" 2392 " // Do nothing.\n" 2393 "}\n" 2394 "}"); 2395 verifyFormat("switch (x) {\n" 2396 "// comment\n" 2397 "// if 1, do f()\n" 2398 "case 1:\n" 2399 " f();\n" 2400 "}"); 2401 verifyFormat("switch (x) {\n" 2402 "case 1:\n" 2403 " // Do amazing stuff\n" 2404 " {\n" 2405 " f();\n" 2406 " g();\n" 2407 " }\n" 2408 " break;\n" 2409 "}"); 2410 verifyFormat("#define A \\\n" 2411 " switch (x) { \\\n" 2412 " case a: \\\n" 2413 " foo = b; \\\n" 2414 " }", 2415 getLLVMStyleWithColumns(20)); 2416 verifyFormat("#define OPERATION_CASE(name) \\\n" 2417 " case OP_name: \\\n" 2418 " return operations::Operation##name\n", 2419 getLLVMStyleWithColumns(40)); 2420 verifyFormat("switch (x) {\n" 2421 "case 1:;\n" 2422 "default:;\n" 2423 " int i;\n" 2424 "}"); 2425 2426 verifyGoogleFormat("switch (x) {\n" 2427 " case 1:\n" 2428 " f();\n" 2429 " break;\n" 2430 " case kFoo:\n" 2431 " case ns::kBar:\n" 2432 " case kBaz:\n" 2433 " break;\n" 2434 " default:\n" 2435 " g();\n" 2436 " break;\n" 2437 "}"); 2438 verifyGoogleFormat("switch (x) {\n" 2439 " case 1: {\n" 2440 " f();\n" 2441 " break;\n" 2442 " }\n" 2443 "}"); 2444 verifyGoogleFormat("switch (test)\n" 2445 " ;"); 2446 2447 verifyGoogleFormat("#define OPERATION_CASE(name) \\\n" 2448 " case OP_name: \\\n" 2449 " return operations::Operation##name\n"); 2450 verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n" 2451 " // Get the correction operation class.\n" 2452 " switch (OpCode) {\n" 2453 " CASE(Add);\n" 2454 " CASE(Subtract);\n" 2455 " default:\n" 2456 " return operations::Unknown;\n" 2457 " }\n" 2458 "#undef OPERATION_CASE\n" 2459 "}"); 2460 verifyFormat("DEBUG({\n" 2461 " switch (x) {\n" 2462 " case A:\n" 2463 " f();\n" 2464 " break;\n" 2465 " // fallthrough\n" 2466 " case B:\n" 2467 " g();\n" 2468 " break;\n" 2469 " }\n" 2470 "});"); 2471 EXPECT_EQ("DEBUG({\n" 2472 " switch (x) {\n" 2473 " case A:\n" 2474 " f();\n" 2475 " break;\n" 2476 " // On B:\n" 2477 " case B:\n" 2478 " g();\n" 2479 " break;\n" 2480 " }\n" 2481 "});", 2482 format("DEBUG({\n" 2483 " switch (x) {\n" 2484 " case A:\n" 2485 " f();\n" 2486 " break;\n" 2487 " // On B:\n" 2488 " case B:\n" 2489 " g();\n" 2490 " break;\n" 2491 " }\n" 2492 "});", 2493 getLLVMStyle())); 2494 EXPECT_EQ("switch (n) {\n" 2495 "case 0: {\n" 2496 " return false;\n" 2497 "}\n" 2498 "default: {\n" 2499 " return true;\n" 2500 "}\n" 2501 "}", 2502 format("switch (n)\n" 2503 "{\n" 2504 "case 0: {\n" 2505 " return false;\n" 2506 "}\n" 2507 "default: {\n" 2508 " return true;\n" 2509 "}\n" 2510 "}", 2511 getLLVMStyle())); 2512 verifyFormat("switch (a) {\n" 2513 "case (b):\n" 2514 " return;\n" 2515 "}"); 2516 2517 verifyFormat("switch (a) {\n" 2518 "case some_namespace::\n" 2519 " some_constant:\n" 2520 " return;\n" 2521 "}", 2522 getLLVMStyleWithColumns(34)); 2523 2524 FormatStyle Style = getLLVMStyle(); 2525 Style.IndentCaseLabels = true; 2526 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 2527 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2528 Style.BraceWrapping.AfterCaseLabel = true; 2529 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 2530 EXPECT_EQ("switch (n)\n" 2531 "{\n" 2532 " case 0:\n" 2533 " {\n" 2534 " return false;\n" 2535 " }\n" 2536 " default:\n" 2537 " {\n" 2538 " return true;\n" 2539 " }\n" 2540 "}", 2541 format("switch (n) {\n" 2542 " case 0: {\n" 2543 " return false;\n" 2544 " }\n" 2545 " default: {\n" 2546 " return true;\n" 2547 " }\n" 2548 "}", 2549 Style)); 2550 Style.BraceWrapping.AfterCaseLabel = false; 2551 EXPECT_EQ("switch (n)\n" 2552 "{\n" 2553 " case 0: {\n" 2554 " return false;\n" 2555 " }\n" 2556 " default: {\n" 2557 " return true;\n" 2558 " }\n" 2559 "}", 2560 format("switch (n) {\n" 2561 " case 0:\n" 2562 " {\n" 2563 " return false;\n" 2564 " }\n" 2565 " default:\n" 2566 " {\n" 2567 " return true;\n" 2568 " }\n" 2569 "}", 2570 Style)); 2571 Style.IndentCaseLabels = false; 2572 Style.IndentCaseBlocks = true; 2573 EXPECT_EQ("switch (n)\n" 2574 "{\n" 2575 "case 0:\n" 2576 " {\n" 2577 " return false;\n" 2578 " }\n" 2579 "case 1:\n" 2580 " break;\n" 2581 "default:\n" 2582 " {\n" 2583 " return true;\n" 2584 " }\n" 2585 "}", 2586 format("switch (n) {\n" 2587 "case 0: {\n" 2588 " return false;\n" 2589 "}\n" 2590 "case 1:\n" 2591 " break;\n" 2592 "default: {\n" 2593 " return true;\n" 2594 "}\n" 2595 "}", 2596 Style)); 2597 Style.IndentCaseLabels = true; 2598 Style.IndentCaseBlocks = true; 2599 EXPECT_EQ("switch (n)\n" 2600 "{\n" 2601 " case 0:\n" 2602 " {\n" 2603 " return false;\n" 2604 " }\n" 2605 " case 1:\n" 2606 " break;\n" 2607 " default:\n" 2608 " {\n" 2609 " return true;\n" 2610 " }\n" 2611 "}", 2612 format("switch (n) {\n" 2613 "case 0: {\n" 2614 " return false;\n" 2615 "}\n" 2616 "case 1:\n" 2617 " break;\n" 2618 "default: {\n" 2619 " return true;\n" 2620 "}\n" 2621 "}", 2622 Style)); 2623 } 2624 2625 TEST_F(FormatTest, CaseRanges) { 2626 verifyFormat("switch (x) {\n" 2627 "case 'A' ... 'Z':\n" 2628 "case 1 ... 5:\n" 2629 "case a ... b:\n" 2630 " break;\n" 2631 "}"); 2632 } 2633 2634 TEST_F(FormatTest, ShortEnums) { 2635 FormatStyle Style = getLLVMStyle(); 2636 Style.AllowShortEnumsOnASingleLine = true; 2637 verifyFormat("enum { A, B, C } ShortEnum1, ShortEnum2;", Style); 2638 verifyFormat("typedef enum { A, B, C } ShortEnum1, ShortEnum2;", Style); 2639 Style.AllowShortEnumsOnASingleLine = false; 2640 verifyFormat("enum {\n" 2641 " A,\n" 2642 " B,\n" 2643 " C\n" 2644 "} ShortEnum1, ShortEnum2;", 2645 Style); 2646 verifyFormat("typedef enum {\n" 2647 " A,\n" 2648 " B,\n" 2649 " C\n" 2650 "} ShortEnum1, ShortEnum2;", 2651 Style); 2652 verifyFormat("enum {\n" 2653 " A,\n" 2654 "} ShortEnum1, ShortEnum2;", 2655 Style); 2656 verifyFormat("typedef enum {\n" 2657 " A,\n" 2658 "} ShortEnum1, ShortEnum2;", 2659 Style); 2660 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2661 Style.BraceWrapping.AfterEnum = true; 2662 verifyFormat("enum\n" 2663 "{\n" 2664 " A,\n" 2665 " B,\n" 2666 " C\n" 2667 "} ShortEnum1, ShortEnum2;", 2668 Style); 2669 verifyFormat("typedef enum\n" 2670 "{\n" 2671 " A,\n" 2672 " B,\n" 2673 " C\n" 2674 "} ShortEnum1, ShortEnum2;", 2675 Style); 2676 } 2677 2678 TEST_F(FormatTest, ShortCaseLabels) { 2679 FormatStyle Style = getLLVMStyle(); 2680 Style.AllowShortCaseLabelsOnASingleLine = true; 2681 verifyFormat("switch (a) {\n" 2682 "case 1: x = 1; break;\n" 2683 "case 2: return;\n" 2684 "case 3:\n" 2685 "case 4:\n" 2686 "case 5: return;\n" 2687 "case 6: // comment\n" 2688 " return;\n" 2689 "case 7:\n" 2690 " // comment\n" 2691 " return;\n" 2692 "case 8:\n" 2693 " x = 8; // comment\n" 2694 " break;\n" 2695 "default: y = 1; break;\n" 2696 "}", 2697 Style); 2698 verifyFormat("switch (a) {\n" 2699 "case 0: return; // comment\n" 2700 "case 1: break; // comment\n" 2701 "case 2: return;\n" 2702 "// comment\n" 2703 "case 3: return;\n" 2704 "// comment 1\n" 2705 "// comment 2\n" 2706 "// comment 3\n" 2707 "case 4: break; /* comment */\n" 2708 "case 5:\n" 2709 " // comment\n" 2710 " break;\n" 2711 "case 6: /* comment */ x = 1; break;\n" 2712 "case 7: x = /* comment */ 1; break;\n" 2713 "case 8:\n" 2714 " x = 1; /* comment */\n" 2715 " break;\n" 2716 "case 9:\n" 2717 " break; // comment line 1\n" 2718 " // comment line 2\n" 2719 "}", 2720 Style); 2721 EXPECT_EQ("switch (a) {\n" 2722 "case 1:\n" 2723 " x = 8;\n" 2724 " // fall through\n" 2725 "case 2: x = 8;\n" 2726 "// comment\n" 2727 "case 3:\n" 2728 " return; /* comment line 1\n" 2729 " * comment line 2 */\n" 2730 "case 4: i = 8;\n" 2731 "// something else\n" 2732 "#if FOO\n" 2733 "case 5: break;\n" 2734 "#endif\n" 2735 "}", 2736 format("switch (a) {\n" 2737 "case 1: x = 8;\n" 2738 " // fall through\n" 2739 "case 2:\n" 2740 " x = 8;\n" 2741 "// comment\n" 2742 "case 3:\n" 2743 " return; /* comment line 1\n" 2744 " * comment line 2 */\n" 2745 "case 4:\n" 2746 " i = 8;\n" 2747 "// something else\n" 2748 "#if FOO\n" 2749 "case 5: break;\n" 2750 "#endif\n" 2751 "}", 2752 Style)); 2753 EXPECT_EQ("switch (a) {\n" 2754 "case 0:\n" 2755 " return; // long long long long long long long long long long " 2756 "long long comment\n" 2757 " // line\n" 2758 "}", 2759 format("switch (a) {\n" 2760 "case 0: return; // long long long long long long long long " 2761 "long long long long comment line\n" 2762 "}", 2763 Style)); 2764 EXPECT_EQ("switch (a) {\n" 2765 "case 0:\n" 2766 " return; /* long long long long long long long long long long " 2767 "long long comment\n" 2768 " line */\n" 2769 "}", 2770 format("switch (a) {\n" 2771 "case 0: return; /* long long long long long long long long " 2772 "long long long long comment line */\n" 2773 "}", 2774 Style)); 2775 verifyFormat("switch (a) {\n" 2776 "#if FOO\n" 2777 "case 0: return 0;\n" 2778 "#endif\n" 2779 "}", 2780 Style); 2781 verifyFormat("switch (a) {\n" 2782 "case 1: {\n" 2783 "}\n" 2784 "case 2: {\n" 2785 " return;\n" 2786 "}\n" 2787 "case 3: {\n" 2788 " x = 1;\n" 2789 " return;\n" 2790 "}\n" 2791 "case 4:\n" 2792 " if (x)\n" 2793 " return;\n" 2794 "}", 2795 Style); 2796 Style.ColumnLimit = 21; 2797 verifyFormat("switch (a) {\n" 2798 "case 1: x = 1; break;\n" 2799 "case 2: return;\n" 2800 "case 3:\n" 2801 "case 4:\n" 2802 "case 5: return;\n" 2803 "default:\n" 2804 " y = 1;\n" 2805 " break;\n" 2806 "}", 2807 Style); 2808 Style.ColumnLimit = 80; 2809 Style.AllowShortCaseLabelsOnASingleLine = false; 2810 Style.IndentCaseLabels = true; 2811 EXPECT_EQ("switch (n) {\n" 2812 " default /*comments*/:\n" 2813 " return true;\n" 2814 " case 0:\n" 2815 " return false;\n" 2816 "}", 2817 format("switch (n) {\n" 2818 "default/*comments*/:\n" 2819 " return true;\n" 2820 "case 0:\n" 2821 " return false;\n" 2822 "}", 2823 Style)); 2824 Style.AllowShortCaseLabelsOnASingleLine = true; 2825 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2826 Style.BraceWrapping.AfterCaseLabel = true; 2827 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 2828 EXPECT_EQ("switch (n)\n" 2829 "{\n" 2830 " case 0:\n" 2831 " {\n" 2832 " return false;\n" 2833 " }\n" 2834 " default:\n" 2835 " {\n" 2836 " return true;\n" 2837 " }\n" 2838 "}", 2839 format("switch (n) {\n" 2840 " case 0: {\n" 2841 " return false;\n" 2842 " }\n" 2843 " default:\n" 2844 " {\n" 2845 " return true;\n" 2846 " }\n" 2847 "}", 2848 Style)); 2849 } 2850 2851 TEST_F(FormatTest, FormatsLabels) { 2852 verifyFormat("void f() {\n" 2853 " some_code();\n" 2854 "test_label:\n" 2855 " some_other_code();\n" 2856 " {\n" 2857 " some_more_code();\n" 2858 " another_label:\n" 2859 " some_more_code();\n" 2860 " }\n" 2861 "}"); 2862 verifyFormat("{\n" 2863 " some_code();\n" 2864 "test_label:\n" 2865 " some_other_code();\n" 2866 "}"); 2867 verifyFormat("{\n" 2868 " some_code();\n" 2869 "test_label:;\n" 2870 " int i = 0;\n" 2871 "}"); 2872 FormatStyle Style = getLLVMStyle(); 2873 Style.IndentGotoLabels = false; 2874 verifyFormat("void f() {\n" 2875 " some_code();\n" 2876 "test_label:\n" 2877 " some_other_code();\n" 2878 " {\n" 2879 " some_more_code();\n" 2880 "another_label:\n" 2881 " some_more_code();\n" 2882 " }\n" 2883 "}", 2884 Style); 2885 verifyFormat("{\n" 2886 " some_code();\n" 2887 "test_label:\n" 2888 " some_other_code();\n" 2889 "}", 2890 Style); 2891 verifyFormat("{\n" 2892 " some_code();\n" 2893 "test_label:;\n" 2894 " int i = 0;\n" 2895 "}"); 2896 } 2897 2898 TEST_F(FormatTest, MultiLineControlStatements) { 2899 FormatStyle Style = getLLVMStyleWithColumns(20); 2900 Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom; 2901 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine; 2902 // Short lines should keep opening brace on same line. 2903 EXPECT_EQ("if (foo) {\n" 2904 " bar();\n" 2905 "}", 2906 format("if(foo){bar();}", Style)); 2907 EXPECT_EQ("if (foo) {\n" 2908 " bar();\n" 2909 "} else {\n" 2910 " baz();\n" 2911 "}", 2912 format("if(foo){bar();}else{baz();}", Style)); 2913 EXPECT_EQ("if (foo && bar) {\n" 2914 " baz();\n" 2915 "}", 2916 format("if(foo&&bar){baz();}", Style)); 2917 EXPECT_EQ("if (foo) {\n" 2918 " bar();\n" 2919 "} else if (baz) {\n" 2920 " quux();\n" 2921 "}", 2922 format("if(foo){bar();}else if(baz){quux();}", Style)); 2923 EXPECT_EQ( 2924 "if (foo) {\n" 2925 " bar();\n" 2926 "} else if (baz) {\n" 2927 " quux();\n" 2928 "} else {\n" 2929 " foobar();\n" 2930 "}", 2931 format("if(foo){bar();}else if(baz){quux();}else{foobar();}", Style)); 2932 EXPECT_EQ("for (;;) {\n" 2933 " foo();\n" 2934 "}", 2935 format("for(;;){foo();}")); 2936 EXPECT_EQ("while (1) {\n" 2937 " foo();\n" 2938 "}", 2939 format("while(1){foo();}", Style)); 2940 EXPECT_EQ("switch (foo) {\n" 2941 "case bar:\n" 2942 " return;\n" 2943 "}", 2944 format("switch(foo){case bar:return;}", Style)); 2945 EXPECT_EQ("try {\n" 2946 " foo();\n" 2947 "} catch (...) {\n" 2948 " bar();\n" 2949 "}", 2950 format("try{foo();}catch(...){bar();}", Style)); 2951 EXPECT_EQ("do {\n" 2952 " foo();\n" 2953 "} while (bar &&\n" 2954 " baz);", 2955 format("do{foo();}while(bar&&baz);", Style)); 2956 // Long lines should put opening brace on new line. 2957 EXPECT_EQ("if (foo && bar &&\n" 2958 " baz)\n" 2959 "{\n" 2960 " quux();\n" 2961 "}", 2962 format("if(foo&&bar&&baz){quux();}", Style)); 2963 EXPECT_EQ("if (foo && bar &&\n" 2964 " baz)\n" 2965 "{\n" 2966 " quux();\n" 2967 "}", 2968 format("if (foo && bar &&\n" 2969 " baz) {\n" 2970 " quux();\n" 2971 "}", 2972 Style)); 2973 EXPECT_EQ("if (foo) {\n" 2974 " bar();\n" 2975 "} else if (baz ||\n" 2976 " quux)\n" 2977 "{\n" 2978 " foobar();\n" 2979 "}", 2980 format("if(foo){bar();}else if(baz||quux){foobar();}", Style)); 2981 EXPECT_EQ( 2982 "if (foo) {\n" 2983 " bar();\n" 2984 "} else if (baz ||\n" 2985 " quux)\n" 2986 "{\n" 2987 " foobar();\n" 2988 "} else {\n" 2989 " barbaz();\n" 2990 "}", 2991 format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}", 2992 Style)); 2993 EXPECT_EQ("for (int i = 0;\n" 2994 " i < 10; ++i)\n" 2995 "{\n" 2996 " foo();\n" 2997 "}", 2998 format("for(int i=0;i<10;++i){foo();}", Style)); 2999 EXPECT_EQ("foreach (int i,\n" 3000 " list)\n" 3001 "{\n" 3002 " foo();\n" 3003 "}", 3004 format("foreach(int i, list){foo();}", Style)); 3005 Style.ColumnLimit = 3006 40; // to concentrate at brace wrapping, not line wrap due to column limit 3007 EXPECT_EQ("foreach (int i, list) {\n" 3008 " foo();\n" 3009 "}", 3010 format("foreach(int i, list){foo();}", Style)); 3011 Style.ColumnLimit = 3012 20; // to concentrate at brace wrapping, not line wrap due to column limit 3013 EXPECT_EQ("while (foo || bar ||\n" 3014 " baz)\n" 3015 "{\n" 3016 " quux();\n" 3017 "}", 3018 format("while(foo||bar||baz){quux();}", Style)); 3019 EXPECT_EQ("switch (\n" 3020 " foo = barbaz)\n" 3021 "{\n" 3022 "case quux:\n" 3023 " return;\n" 3024 "}", 3025 format("switch(foo=barbaz){case quux:return;}", Style)); 3026 EXPECT_EQ("try {\n" 3027 " foo();\n" 3028 "} catch (\n" 3029 " Exception &bar)\n" 3030 "{\n" 3031 " baz();\n" 3032 "}", 3033 format("try{foo();}catch(Exception&bar){baz();}", Style)); 3034 Style.ColumnLimit = 3035 40; // to concentrate at brace wrapping, not line wrap due to column limit 3036 EXPECT_EQ("try {\n" 3037 " foo();\n" 3038 "} catch (Exception &bar) {\n" 3039 " baz();\n" 3040 "}", 3041 format("try{foo();}catch(Exception&bar){baz();}", Style)); 3042 Style.ColumnLimit = 3043 20; // to concentrate at brace wrapping, not line wrap due to column limit 3044 3045 Style.BraceWrapping.BeforeElse = true; 3046 EXPECT_EQ( 3047 "if (foo) {\n" 3048 " bar();\n" 3049 "}\n" 3050 "else if (baz ||\n" 3051 " quux)\n" 3052 "{\n" 3053 " foobar();\n" 3054 "}\n" 3055 "else {\n" 3056 " barbaz();\n" 3057 "}", 3058 format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}", 3059 Style)); 3060 3061 Style.BraceWrapping.BeforeCatch = true; 3062 EXPECT_EQ("try {\n" 3063 " foo();\n" 3064 "}\n" 3065 "catch (...) {\n" 3066 " baz();\n" 3067 "}", 3068 format("try{foo();}catch(...){baz();}", Style)); 3069 3070 Style.BraceWrapping.AfterFunction = true; 3071 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine; 3072 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 3073 Style.ColumnLimit = 80; 3074 verifyFormat("void shortfunction() { bar(); }", Style); 3075 3076 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 3077 verifyFormat("void shortfunction()\n" 3078 "{\n" 3079 " bar();\n" 3080 "}", 3081 Style); 3082 } 3083 3084 TEST_F(FormatTest, BeforeWhile) { 3085 FormatStyle Style = getLLVMStyle(); 3086 Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom; 3087 3088 verifyFormat("do {\n" 3089 " foo();\n" 3090 "} while (1);", 3091 Style); 3092 Style.BraceWrapping.BeforeWhile = true; 3093 verifyFormat("do {\n" 3094 " foo();\n" 3095 "}\n" 3096 "while (1);", 3097 Style); 3098 } 3099 3100 //===----------------------------------------------------------------------===// 3101 // Tests for classes, namespaces, etc. 3102 //===----------------------------------------------------------------------===// 3103 3104 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) { 3105 verifyFormat("class A {};"); 3106 } 3107 3108 TEST_F(FormatTest, UnderstandsAccessSpecifiers) { 3109 verifyFormat("class A {\n" 3110 "public:\n" 3111 "public: // comment\n" 3112 "protected:\n" 3113 "private:\n" 3114 " void f() {}\n" 3115 "};"); 3116 verifyFormat("export class A {\n" 3117 "public:\n" 3118 "public: // comment\n" 3119 "protected:\n" 3120 "private:\n" 3121 " void f() {}\n" 3122 "};"); 3123 verifyGoogleFormat("class A {\n" 3124 " public:\n" 3125 " protected:\n" 3126 " private:\n" 3127 " void f() {}\n" 3128 "};"); 3129 verifyGoogleFormat("export class A {\n" 3130 " public:\n" 3131 " protected:\n" 3132 " private:\n" 3133 " void f() {}\n" 3134 "};"); 3135 verifyFormat("class A {\n" 3136 "public slots:\n" 3137 " void f1() {}\n" 3138 "public Q_SLOTS:\n" 3139 " void f2() {}\n" 3140 "protected slots:\n" 3141 " void f3() {}\n" 3142 "protected Q_SLOTS:\n" 3143 " void f4() {}\n" 3144 "private slots:\n" 3145 " void f5() {}\n" 3146 "private Q_SLOTS:\n" 3147 " void f6() {}\n" 3148 "signals:\n" 3149 " void g1();\n" 3150 "Q_SIGNALS:\n" 3151 " void g2();\n" 3152 "};"); 3153 3154 // Don't interpret 'signals' the wrong way. 3155 verifyFormat("signals.set();"); 3156 verifyFormat("for (Signals signals : f()) {\n}"); 3157 verifyFormat("{\n" 3158 " signals.set(); // This needs indentation.\n" 3159 "}"); 3160 verifyFormat("void f() {\n" 3161 "label:\n" 3162 " signals.baz();\n" 3163 "}"); 3164 verifyFormat("private[1];"); 3165 verifyFormat("testArray[public] = 1;"); 3166 verifyFormat("public();"); 3167 verifyFormat("myFunc(public);"); 3168 verifyFormat("std::vector<int> testVec = {private};"); 3169 verifyFormat("private.p = 1;"); 3170 verifyFormat("void function(private...){};"); 3171 verifyFormat("if (private && public)\n"); 3172 verifyFormat("private &= true;"); 3173 verifyFormat("int x = private * public;"); 3174 verifyFormat("public *= private;"); 3175 verifyFormat("int x = public + private;"); 3176 verifyFormat("private++;"); 3177 verifyFormat("++private;"); 3178 verifyFormat("public += private;"); 3179 verifyFormat("public = public - private;"); 3180 verifyFormat("public->foo();"); 3181 verifyFormat("private--;"); 3182 verifyFormat("--private;"); 3183 verifyFormat("public -= 1;"); 3184 verifyFormat("if (!private && !public)\n"); 3185 verifyFormat("public != private;"); 3186 verifyFormat("int x = public / private;"); 3187 verifyFormat("public /= 2;"); 3188 verifyFormat("public = public % 2;"); 3189 verifyFormat("public %= 2;"); 3190 verifyFormat("if (public < private)\n"); 3191 verifyFormat("public << private;"); 3192 verifyFormat("public <<= private;"); 3193 verifyFormat("if (public > private)\n"); 3194 verifyFormat("public >> private;"); 3195 verifyFormat("public >>= private;"); 3196 verifyFormat("public ^ private;"); 3197 verifyFormat("public ^= private;"); 3198 verifyFormat("public | private;"); 3199 verifyFormat("public |= private;"); 3200 verifyFormat("auto x = private ? 1 : 2;"); 3201 verifyFormat("if (public == private)\n"); 3202 verifyFormat("void foo(public, private)"); 3203 verifyFormat("public::foo();"); 3204 } 3205 3206 TEST_F(FormatTest, SeparatesLogicalBlocks) { 3207 EXPECT_EQ("class A {\n" 3208 "public:\n" 3209 " void f();\n" 3210 "\n" 3211 "private:\n" 3212 " void g() {}\n" 3213 " // test\n" 3214 "protected:\n" 3215 " int h;\n" 3216 "};", 3217 format("class A {\n" 3218 "public:\n" 3219 "void f();\n" 3220 "private:\n" 3221 "void g() {}\n" 3222 "// test\n" 3223 "protected:\n" 3224 "int h;\n" 3225 "};")); 3226 EXPECT_EQ("class A {\n" 3227 "protected:\n" 3228 "public:\n" 3229 " void f();\n" 3230 "};", 3231 format("class A {\n" 3232 "protected:\n" 3233 "\n" 3234 "public:\n" 3235 "\n" 3236 " void f();\n" 3237 "};")); 3238 3239 // Even ensure proper spacing inside macros. 3240 EXPECT_EQ("#define B \\\n" 3241 " class A { \\\n" 3242 " protected: \\\n" 3243 " public: \\\n" 3244 " void f(); \\\n" 3245 " };", 3246 format("#define B \\\n" 3247 " class A { \\\n" 3248 " protected: \\\n" 3249 " \\\n" 3250 " public: \\\n" 3251 " \\\n" 3252 " void f(); \\\n" 3253 " };", 3254 getGoogleStyle())); 3255 // But don't remove empty lines after macros ending in access specifiers. 3256 EXPECT_EQ("#define A private:\n" 3257 "\n" 3258 "int i;", 3259 format("#define A private:\n" 3260 "\n" 3261 "int i;")); 3262 } 3263 3264 TEST_F(FormatTest, FormatsClasses) { 3265 verifyFormat("class A : public B {};"); 3266 verifyFormat("class A : public ::B {};"); 3267 3268 verifyFormat( 3269 "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3270 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};"); 3271 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n" 3272 " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3273 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};"); 3274 verifyFormat( 3275 "class A : public B, public C, public D, public E, public F {};"); 3276 verifyFormat("class AAAAAAAAAAAA : public B,\n" 3277 " public C,\n" 3278 " public D,\n" 3279 " public E,\n" 3280 " public F,\n" 3281 " public G {};"); 3282 3283 verifyFormat("class\n" 3284 " ReallyReallyLongClassName {\n" 3285 " int i;\n" 3286 "};", 3287 getLLVMStyleWithColumns(32)); 3288 verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n" 3289 " aaaaaaaaaaaaaaaa> {};"); 3290 verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n" 3291 " : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n" 3292 " aaaaaaaaaaaaaaaaaaaaaa> {};"); 3293 verifyFormat("template <class R, class C>\n" 3294 "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n" 3295 " : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};"); 3296 verifyFormat("class ::A::B {};"); 3297 } 3298 3299 TEST_F(FormatTest, BreakInheritanceStyle) { 3300 FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle(); 3301 StyleWithInheritanceBreakBeforeComma.BreakInheritanceList = 3302 FormatStyle::BILS_BeforeComma; 3303 verifyFormat("class MyClass : public X {};", 3304 StyleWithInheritanceBreakBeforeComma); 3305 verifyFormat("class MyClass\n" 3306 " : public X\n" 3307 " , public Y {};", 3308 StyleWithInheritanceBreakBeforeComma); 3309 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n" 3310 " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n" 3311 " , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};", 3312 StyleWithInheritanceBreakBeforeComma); 3313 verifyFormat("struct aaaaaaaaaaaaa\n" 3314 " : public aaaaaaaaaaaaaaaaaaa< // break\n" 3315 " aaaaaaaaaaaaaaaa> {};", 3316 StyleWithInheritanceBreakBeforeComma); 3317 3318 FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle(); 3319 StyleWithInheritanceBreakAfterColon.BreakInheritanceList = 3320 FormatStyle::BILS_AfterColon; 3321 verifyFormat("class MyClass : public X {};", 3322 StyleWithInheritanceBreakAfterColon); 3323 verifyFormat("class MyClass : public X, public Y {};", 3324 StyleWithInheritanceBreakAfterColon); 3325 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n" 3326 " public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3327 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};", 3328 StyleWithInheritanceBreakAfterColon); 3329 verifyFormat("struct aaaaaaaaaaaaa :\n" 3330 " public aaaaaaaaaaaaaaaaaaa< // break\n" 3331 " aaaaaaaaaaaaaaaa> {};", 3332 StyleWithInheritanceBreakAfterColon); 3333 3334 FormatStyle StyleWithInheritanceBreakAfterComma = getLLVMStyle(); 3335 StyleWithInheritanceBreakAfterComma.BreakInheritanceList = 3336 FormatStyle::BILS_AfterComma; 3337 verifyFormat("class MyClass : public X {};", 3338 StyleWithInheritanceBreakAfterComma); 3339 verifyFormat("class MyClass : public X,\n" 3340 " public Y {};", 3341 StyleWithInheritanceBreakAfterComma); 3342 verifyFormat( 3343 "class AAAAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3344 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC " 3345 "{};", 3346 StyleWithInheritanceBreakAfterComma); 3347 verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n" 3348 " aaaaaaaaaaaaaaaa> {};", 3349 StyleWithInheritanceBreakAfterComma); 3350 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n" 3351 " : public OnceBreak,\n" 3352 " public AlwaysBreak,\n" 3353 " EvenBasesFitInOneLine {};", 3354 StyleWithInheritanceBreakAfterComma); 3355 } 3356 3357 TEST_F(FormatTest, FormatsVariableDeclarationsAfterStructOrClass) { 3358 verifyFormat("class A {\n} a, b;"); 3359 verifyFormat("struct A {\n} a, b;"); 3360 verifyFormat("union A {\n} a;"); 3361 } 3362 3363 TEST_F(FormatTest, FormatsEnum) { 3364 verifyFormat("enum {\n" 3365 " Zero,\n" 3366 " One = 1,\n" 3367 " Two = One + 1,\n" 3368 " Three = (One + Two),\n" 3369 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3370 " Five = (One, Two, Three, Four, 5)\n" 3371 "};"); 3372 verifyGoogleFormat("enum {\n" 3373 " Zero,\n" 3374 " One = 1,\n" 3375 " Two = One + 1,\n" 3376 " Three = (One + Two),\n" 3377 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3378 " Five = (One, Two, Three, Four, 5)\n" 3379 "};"); 3380 verifyFormat("enum Enum {};"); 3381 verifyFormat("enum {};"); 3382 verifyFormat("enum X E {} d;"); 3383 verifyFormat("enum __attribute__((...)) E {} d;"); 3384 verifyFormat("enum __declspec__((...)) E {} d;"); 3385 verifyFormat("enum {\n" 3386 " Bar = Foo<int, int>::value\n" 3387 "};", 3388 getLLVMStyleWithColumns(30)); 3389 3390 verifyFormat("enum ShortEnum { A, B, C };"); 3391 verifyGoogleFormat("enum ShortEnum { A, B, C };"); 3392 3393 EXPECT_EQ("enum KeepEmptyLines {\n" 3394 " ONE,\n" 3395 "\n" 3396 " TWO,\n" 3397 "\n" 3398 " THREE\n" 3399 "}", 3400 format("enum KeepEmptyLines {\n" 3401 " ONE,\n" 3402 "\n" 3403 " TWO,\n" 3404 "\n" 3405 "\n" 3406 " THREE\n" 3407 "}")); 3408 verifyFormat("enum E { // comment\n" 3409 " ONE,\n" 3410 " TWO\n" 3411 "};\n" 3412 "int i;"); 3413 3414 FormatStyle EightIndent = getLLVMStyle(); 3415 EightIndent.IndentWidth = 8; 3416 verifyFormat("enum {\n" 3417 " VOID,\n" 3418 " CHAR,\n" 3419 " SHORT,\n" 3420 " INT,\n" 3421 " LONG,\n" 3422 " SIGNED,\n" 3423 " UNSIGNED,\n" 3424 " BOOL,\n" 3425 " FLOAT,\n" 3426 " DOUBLE,\n" 3427 " COMPLEX\n" 3428 "};", 3429 EightIndent); 3430 3431 // Not enums. 3432 verifyFormat("enum X f() {\n" 3433 " a();\n" 3434 " return 42;\n" 3435 "}"); 3436 verifyFormat("enum X Type::f() {\n" 3437 " a();\n" 3438 " return 42;\n" 3439 "}"); 3440 verifyFormat("enum ::X f() {\n" 3441 " a();\n" 3442 " return 42;\n" 3443 "}"); 3444 verifyFormat("enum ns::X f() {\n" 3445 " a();\n" 3446 " return 42;\n" 3447 "}"); 3448 } 3449 3450 TEST_F(FormatTest, FormatsEnumsWithErrors) { 3451 verifyFormat("enum Type {\n" 3452 " One = 0; // These semicolons should be commas.\n" 3453 " Two = 1;\n" 3454 "};"); 3455 verifyFormat("namespace n {\n" 3456 "enum Type {\n" 3457 " One,\n" 3458 " Two, // missing };\n" 3459 " int i;\n" 3460 "}\n" 3461 "void g() {}"); 3462 } 3463 3464 TEST_F(FormatTest, FormatsEnumStruct) { 3465 verifyFormat("enum struct {\n" 3466 " Zero,\n" 3467 " One = 1,\n" 3468 " Two = One + 1,\n" 3469 " Three = (One + Two),\n" 3470 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3471 " Five = (One, Two, Three, Four, 5)\n" 3472 "};"); 3473 verifyFormat("enum struct Enum {};"); 3474 verifyFormat("enum struct {};"); 3475 verifyFormat("enum struct X E {} d;"); 3476 verifyFormat("enum struct __attribute__((...)) E {} d;"); 3477 verifyFormat("enum struct __declspec__((...)) E {} d;"); 3478 verifyFormat("enum struct X f() {\n a();\n return 42;\n}"); 3479 } 3480 3481 TEST_F(FormatTest, FormatsEnumClass) { 3482 verifyFormat("enum class {\n" 3483 " Zero,\n" 3484 " One = 1,\n" 3485 " Two = One + 1,\n" 3486 " Three = (One + Two),\n" 3487 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3488 " Five = (One, Two, Three, Four, 5)\n" 3489 "};"); 3490 verifyFormat("enum class Enum {};"); 3491 verifyFormat("enum class {};"); 3492 verifyFormat("enum class X E {} d;"); 3493 verifyFormat("enum class __attribute__((...)) E {} d;"); 3494 verifyFormat("enum class __declspec__((...)) E {} d;"); 3495 verifyFormat("enum class X f() {\n a();\n return 42;\n}"); 3496 } 3497 3498 TEST_F(FormatTest, FormatsEnumTypes) { 3499 verifyFormat("enum X : int {\n" 3500 " A, // Force multiple lines.\n" 3501 " B\n" 3502 "};"); 3503 verifyFormat("enum X : int { A, B };"); 3504 verifyFormat("enum X : std::uint32_t { A, B };"); 3505 } 3506 3507 TEST_F(FormatTest, FormatsTypedefEnum) { 3508 FormatStyle Style = getLLVMStyleWithColumns(40); 3509 verifyFormat("typedef enum {} EmptyEnum;"); 3510 verifyFormat("typedef enum { A, B, C } ShortEnum;"); 3511 verifyFormat("typedef enum {\n" 3512 " ZERO = 0,\n" 3513 " ONE = 1,\n" 3514 " TWO = 2,\n" 3515 " THREE = 3\n" 3516 "} LongEnum;", 3517 Style); 3518 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 3519 Style.BraceWrapping.AfterEnum = true; 3520 verifyFormat("typedef enum {} EmptyEnum;"); 3521 verifyFormat("typedef enum { A, B, C } ShortEnum;"); 3522 verifyFormat("typedef enum\n" 3523 "{\n" 3524 " ZERO = 0,\n" 3525 " ONE = 1,\n" 3526 " TWO = 2,\n" 3527 " THREE = 3\n" 3528 "} LongEnum;", 3529 Style); 3530 } 3531 3532 TEST_F(FormatTest, FormatsNSEnums) { 3533 verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }"); 3534 verifyGoogleFormat( 3535 "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }"); 3536 verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n" 3537 " // Information about someDecentlyLongValue.\n" 3538 " someDecentlyLongValue,\n" 3539 " // Information about anotherDecentlyLongValue.\n" 3540 " anotherDecentlyLongValue,\n" 3541 " // Information about aThirdDecentlyLongValue.\n" 3542 " aThirdDecentlyLongValue\n" 3543 "};"); 3544 verifyGoogleFormat("typedef NS_CLOSED_ENUM(NSInteger, MyType) {\n" 3545 " // Information about someDecentlyLongValue.\n" 3546 " someDecentlyLongValue,\n" 3547 " // Information about anotherDecentlyLongValue.\n" 3548 " anotherDecentlyLongValue,\n" 3549 " // Information about aThirdDecentlyLongValue.\n" 3550 " aThirdDecentlyLongValue\n" 3551 "};"); 3552 verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n" 3553 " a = 1,\n" 3554 " b = 2,\n" 3555 " c = 3,\n" 3556 "};"); 3557 verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n" 3558 " a = 1,\n" 3559 " b = 2,\n" 3560 " c = 3,\n" 3561 "};"); 3562 verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n" 3563 " a = 1,\n" 3564 " b = 2,\n" 3565 " c = 3,\n" 3566 "};"); 3567 verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n" 3568 " a = 1,\n" 3569 " b = 2,\n" 3570 " c = 3,\n" 3571 "};"); 3572 } 3573 3574 TEST_F(FormatTest, FormatsBitfields) { 3575 verifyFormat("struct Bitfields {\n" 3576 " unsigned sClass : 8;\n" 3577 " unsigned ValueKind : 2;\n" 3578 "};"); 3579 verifyFormat("struct A {\n" 3580 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n" 3581 " bbbbbbbbbbbbbbbbbbbbbbbbb;\n" 3582 "};"); 3583 verifyFormat("struct MyStruct {\n" 3584 " uchar data;\n" 3585 " uchar : 8;\n" 3586 " uchar : 8;\n" 3587 " uchar other;\n" 3588 "};"); 3589 FormatStyle Style = getLLVMStyle(); 3590 Style.BitFieldColonSpacing = FormatStyle::BFCS_None; 3591 verifyFormat("struct Bitfields {\n" 3592 " unsigned sClass:8;\n" 3593 " unsigned ValueKind:2;\n" 3594 " uchar other;\n" 3595 "};", 3596 Style); 3597 verifyFormat("struct A {\n" 3598 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:1,\n" 3599 " bbbbbbbbbbbbbbbbbbbbbbbbb:2;\n" 3600 "};", 3601 Style); 3602 Style.BitFieldColonSpacing = FormatStyle::BFCS_Before; 3603 verifyFormat("struct Bitfields {\n" 3604 " unsigned sClass :8;\n" 3605 " unsigned ValueKind :2;\n" 3606 " uchar other;\n" 3607 "};", 3608 Style); 3609 Style.BitFieldColonSpacing = FormatStyle::BFCS_After; 3610 verifyFormat("struct Bitfields {\n" 3611 " unsigned sClass: 8;\n" 3612 " unsigned ValueKind: 2;\n" 3613 " uchar other;\n" 3614 "};", 3615 Style); 3616 } 3617 3618 TEST_F(FormatTest, FormatsNamespaces) { 3619 FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle(); 3620 LLVMWithNoNamespaceFix.FixNamespaceComments = false; 3621 3622 verifyFormat("namespace some_namespace {\n" 3623 "class A {};\n" 3624 "void f() { f(); }\n" 3625 "}", 3626 LLVMWithNoNamespaceFix); 3627 verifyFormat("namespace N::inline D {\n" 3628 "class A {};\n" 3629 "void f() { f(); }\n" 3630 "}", 3631 LLVMWithNoNamespaceFix); 3632 verifyFormat("namespace N::inline D::E {\n" 3633 "class A {};\n" 3634 "void f() { f(); }\n" 3635 "}", 3636 LLVMWithNoNamespaceFix); 3637 verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n" 3638 "class A {};\n" 3639 "void f() { f(); }\n" 3640 "}", 3641 LLVMWithNoNamespaceFix); 3642 verifyFormat("/* something */ namespace some_namespace {\n" 3643 "class A {};\n" 3644 "void f() { f(); }\n" 3645 "}", 3646 LLVMWithNoNamespaceFix); 3647 verifyFormat("namespace {\n" 3648 "class A {};\n" 3649 "void f() { f(); }\n" 3650 "}", 3651 LLVMWithNoNamespaceFix); 3652 verifyFormat("/* something */ namespace {\n" 3653 "class A {};\n" 3654 "void f() { f(); }\n" 3655 "}", 3656 LLVMWithNoNamespaceFix); 3657 verifyFormat("inline namespace X {\n" 3658 "class A {};\n" 3659 "void f() { f(); }\n" 3660 "}", 3661 LLVMWithNoNamespaceFix); 3662 verifyFormat("/* something */ inline namespace X {\n" 3663 "class A {};\n" 3664 "void f() { f(); }\n" 3665 "}", 3666 LLVMWithNoNamespaceFix); 3667 verifyFormat("export namespace X {\n" 3668 "class A {};\n" 3669 "void f() { f(); }\n" 3670 "}", 3671 LLVMWithNoNamespaceFix); 3672 verifyFormat("using namespace some_namespace;\n" 3673 "class A {};\n" 3674 "void f() { f(); }", 3675 LLVMWithNoNamespaceFix); 3676 3677 // This code is more common than we thought; if we 3678 // layout this correctly the semicolon will go into 3679 // its own line, which is undesirable. 3680 verifyFormat("namespace {};", LLVMWithNoNamespaceFix); 3681 verifyFormat("namespace {\n" 3682 "class A {};\n" 3683 "};", 3684 LLVMWithNoNamespaceFix); 3685 3686 verifyFormat("namespace {\n" 3687 "int SomeVariable = 0; // comment\n" 3688 "} // namespace", 3689 LLVMWithNoNamespaceFix); 3690 EXPECT_EQ("#ifndef HEADER_GUARD\n" 3691 "#define HEADER_GUARD\n" 3692 "namespace my_namespace {\n" 3693 "int i;\n" 3694 "} // my_namespace\n" 3695 "#endif // HEADER_GUARD", 3696 format("#ifndef HEADER_GUARD\n" 3697 " #define HEADER_GUARD\n" 3698 " namespace my_namespace {\n" 3699 "int i;\n" 3700 "} // my_namespace\n" 3701 "#endif // HEADER_GUARD", 3702 LLVMWithNoNamespaceFix)); 3703 3704 EXPECT_EQ("namespace A::B {\n" 3705 "class C {};\n" 3706 "}", 3707 format("namespace A::B {\n" 3708 "class C {};\n" 3709 "}", 3710 LLVMWithNoNamespaceFix)); 3711 3712 FormatStyle Style = getLLVMStyle(); 3713 Style.NamespaceIndentation = FormatStyle::NI_All; 3714 EXPECT_EQ("namespace out {\n" 3715 " int i;\n" 3716 " namespace in {\n" 3717 " int i;\n" 3718 " } // namespace in\n" 3719 "} // namespace out", 3720 format("namespace out {\n" 3721 "int i;\n" 3722 "namespace in {\n" 3723 "int i;\n" 3724 "} // namespace in\n" 3725 "} // namespace out", 3726 Style)); 3727 3728 FormatStyle ShortInlineFunctions = getLLVMStyle(); 3729 ShortInlineFunctions.NamespaceIndentation = FormatStyle::NI_All; 3730 ShortInlineFunctions.AllowShortFunctionsOnASingleLine = 3731 FormatStyle::SFS_Inline; 3732 verifyFormat("namespace {\n" 3733 " void f() {\n" 3734 " return;\n" 3735 " }\n" 3736 "} // namespace\n", 3737 ShortInlineFunctions); 3738 verifyFormat("namespace {\n" 3739 " int some_int;\n" 3740 " void f() {\n" 3741 " return;\n" 3742 " }\n" 3743 "} // namespace\n", 3744 ShortInlineFunctions); 3745 verifyFormat("namespace interface {\n" 3746 " void f() {\n" 3747 " return;\n" 3748 " }\n" 3749 "} // namespace interface\n", 3750 ShortInlineFunctions); 3751 verifyFormat("namespace {\n" 3752 " class X {\n" 3753 " void f() { return; }\n" 3754 " };\n" 3755 "} // namespace\n", 3756 ShortInlineFunctions); 3757 verifyFormat("namespace {\n" 3758 " struct X {\n" 3759 " void f() { return; }\n" 3760 " };\n" 3761 "} // namespace\n", 3762 ShortInlineFunctions); 3763 verifyFormat("namespace {\n" 3764 " union X {\n" 3765 " void f() { return; }\n" 3766 " };\n" 3767 "} // namespace\n", 3768 ShortInlineFunctions); 3769 verifyFormat("extern \"C\" {\n" 3770 "void f() {\n" 3771 " return;\n" 3772 "}\n" 3773 "} // namespace\n", 3774 ShortInlineFunctions); 3775 verifyFormat("namespace {\n" 3776 " class X {\n" 3777 " void f() { return; }\n" 3778 " } x;\n" 3779 "} // namespace\n", 3780 ShortInlineFunctions); 3781 verifyFormat("namespace {\n" 3782 " [[nodiscard]] class X {\n" 3783 " void f() { return; }\n" 3784 " };\n" 3785 "} // namespace\n", 3786 ShortInlineFunctions); 3787 verifyFormat("namespace {\n" 3788 " static class X {\n" 3789 " void f() { return; }\n" 3790 " } x;\n" 3791 "} // namespace\n", 3792 ShortInlineFunctions); 3793 verifyFormat("namespace {\n" 3794 " constexpr class X {\n" 3795 " void f() { return; }\n" 3796 " } x;\n" 3797 "} // namespace\n", 3798 ShortInlineFunctions); 3799 3800 ShortInlineFunctions.IndentExternBlock = FormatStyle::IEBS_Indent; 3801 verifyFormat("extern \"C\" {\n" 3802 " void f() {\n" 3803 " return;\n" 3804 " }\n" 3805 "} // namespace\n", 3806 ShortInlineFunctions); 3807 3808 Style.NamespaceIndentation = FormatStyle::NI_Inner; 3809 EXPECT_EQ("namespace out {\n" 3810 "int i;\n" 3811 "namespace in {\n" 3812 " int i;\n" 3813 "} // namespace in\n" 3814 "} // namespace out", 3815 format("namespace out {\n" 3816 "int i;\n" 3817 "namespace in {\n" 3818 "int i;\n" 3819 "} // namespace in\n" 3820 "} // namespace out", 3821 Style)); 3822 3823 Style.NamespaceIndentation = FormatStyle::NI_None; 3824 verifyFormat("template <class T>\n" 3825 "concept a_concept = X<>;\n" 3826 "namespace B {\n" 3827 "struct b_struct {};\n" 3828 "} // namespace B\n", 3829 Style); 3830 verifyFormat("template <int I> constexpr void foo requires(I == 42) {}\n" 3831 "namespace ns {\n" 3832 "void foo() {}\n" 3833 "} // namespace ns\n", 3834 Style); 3835 } 3836 3837 TEST_F(FormatTest, NamespaceMacros) { 3838 FormatStyle Style = getLLVMStyle(); 3839 Style.NamespaceMacros.push_back("TESTSUITE"); 3840 3841 verifyFormat("TESTSUITE(A) {\n" 3842 "int foo();\n" 3843 "} // TESTSUITE(A)", 3844 Style); 3845 3846 verifyFormat("TESTSUITE(A, B) {\n" 3847 "int foo();\n" 3848 "} // TESTSUITE(A)", 3849 Style); 3850 3851 // Properly indent according to NamespaceIndentation style 3852 Style.NamespaceIndentation = FormatStyle::NI_All; 3853 verifyFormat("TESTSUITE(A) {\n" 3854 " int foo();\n" 3855 "} // TESTSUITE(A)", 3856 Style); 3857 verifyFormat("TESTSUITE(A) {\n" 3858 " namespace B {\n" 3859 " int foo();\n" 3860 " } // namespace B\n" 3861 "} // TESTSUITE(A)", 3862 Style); 3863 verifyFormat("namespace A {\n" 3864 " TESTSUITE(B) {\n" 3865 " int foo();\n" 3866 " } // TESTSUITE(B)\n" 3867 "} // namespace A", 3868 Style); 3869 3870 Style.NamespaceIndentation = FormatStyle::NI_Inner; 3871 verifyFormat("TESTSUITE(A) {\n" 3872 "TESTSUITE(B) {\n" 3873 " int foo();\n" 3874 "} // TESTSUITE(B)\n" 3875 "} // TESTSUITE(A)", 3876 Style); 3877 verifyFormat("TESTSUITE(A) {\n" 3878 "namespace B {\n" 3879 " int foo();\n" 3880 "} // namespace B\n" 3881 "} // TESTSUITE(A)", 3882 Style); 3883 verifyFormat("namespace A {\n" 3884 "TESTSUITE(B) {\n" 3885 " int foo();\n" 3886 "} // TESTSUITE(B)\n" 3887 "} // namespace A", 3888 Style); 3889 3890 // Properly merge namespace-macros blocks in CompactNamespaces mode 3891 Style.NamespaceIndentation = FormatStyle::NI_None; 3892 Style.CompactNamespaces = true; 3893 verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n" 3894 "}} // TESTSUITE(A::B)", 3895 Style); 3896 3897 EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n" 3898 "}} // TESTSUITE(out::in)", 3899 format("TESTSUITE(out) {\n" 3900 "TESTSUITE(in) {\n" 3901 "} // TESTSUITE(in)\n" 3902 "} // TESTSUITE(out)", 3903 Style)); 3904 3905 EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n" 3906 "}} // TESTSUITE(out::in)", 3907 format("TESTSUITE(out) {\n" 3908 "TESTSUITE(in) {\n" 3909 "} // TESTSUITE(in)\n" 3910 "} // TESTSUITE(out)", 3911 Style)); 3912 3913 // Do not merge different namespaces/macros 3914 EXPECT_EQ("namespace out {\n" 3915 "TESTSUITE(in) {\n" 3916 "} // TESTSUITE(in)\n" 3917 "} // namespace out", 3918 format("namespace out {\n" 3919 "TESTSUITE(in) {\n" 3920 "} // TESTSUITE(in)\n" 3921 "} // namespace out", 3922 Style)); 3923 EXPECT_EQ("TESTSUITE(out) {\n" 3924 "namespace in {\n" 3925 "} // namespace in\n" 3926 "} // TESTSUITE(out)", 3927 format("TESTSUITE(out) {\n" 3928 "namespace in {\n" 3929 "} // namespace in\n" 3930 "} // TESTSUITE(out)", 3931 Style)); 3932 Style.NamespaceMacros.push_back("FOOBAR"); 3933 EXPECT_EQ("TESTSUITE(out) {\n" 3934 "FOOBAR(in) {\n" 3935 "} // FOOBAR(in)\n" 3936 "} // TESTSUITE(out)", 3937 format("TESTSUITE(out) {\n" 3938 "FOOBAR(in) {\n" 3939 "} // FOOBAR(in)\n" 3940 "} // TESTSUITE(out)", 3941 Style)); 3942 } 3943 3944 TEST_F(FormatTest, FormatsCompactNamespaces) { 3945 FormatStyle Style = getLLVMStyle(); 3946 Style.CompactNamespaces = true; 3947 Style.NamespaceMacros.push_back("TESTSUITE"); 3948 3949 verifyFormat("namespace A { namespace B {\n" 3950 "}} // namespace A::B", 3951 Style); 3952 3953 EXPECT_EQ("namespace out { namespace in {\n" 3954 "}} // namespace out::in", 3955 format("namespace out {\n" 3956 "namespace in {\n" 3957 "} // namespace in\n" 3958 "} // namespace out", 3959 Style)); 3960 3961 // Only namespaces which have both consecutive opening and end get compacted 3962 EXPECT_EQ("namespace out {\n" 3963 "namespace in1 {\n" 3964 "} // namespace in1\n" 3965 "namespace in2 {\n" 3966 "} // namespace in2\n" 3967 "} // namespace out", 3968 format("namespace out {\n" 3969 "namespace in1 {\n" 3970 "} // namespace in1\n" 3971 "namespace in2 {\n" 3972 "} // namespace in2\n" 3973 "} // namespace out", 3974 Style)); 3975 3976 EXPECT_EQ("namespace out {\n" 3977 "int i;\n" 3978 "namespace in {\n" 3979 "int j;\n" 3980 "} // namespace in\n" 3981 "int k;\n" 3982 "} // namespace out", 3983 format("namespace out { int i;\n" 3984 "namespace in { int j; } // namespace in\n" 3985 "int k; } // namespace out", 3986 Style)); 3987 3988 EXPECT_EQ("namespace A { namespace B { namespace C {\n" 3989 "}}} // namespace A::B::C\n", 3990 format("namespace A { namespace B {\n" 3991 "namespace C {\n" 3992 "}} // namespace B::C\n" 3993 "} // namespace A\n", 3994 Style)); 3995 3996 Style.ColumnLimit = 40; 3997 EXPECT_EQ("namespace aaaaaaaaaa {\n" 3998 "namespace bbbbbbbbbb {\n" 3999 "}} // namespace aaaaaaaaaa::bbbbbbbbbb", 4000 format("namespace aaaaaaaaaa {\n" 4001 "namespace bbbbbbbbbb {\n" 4002 "} // namespace bbbbbbbbbb\n" 4003 "} // namespace aaaaaaaaaa", 4004 Style)); 4005 4006 EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n" 4007 "namespace cccccc {\n" 4008 "}}} // namespace aaaaaa::bbbbbb::cccccc", 4009 format("namespace aaaaaa {\n" 4010 "namespace bbbbbb {\n" 4011 "namespace cccccc {\n" 4012 "} // namespace cccccc\n" 4013 "} // namespace bbbbbb\n" 4014 "} // namespace aaaaaa", 4015 Style)); 4016 Style.ColumnLimit = 80; 4017 4018 // Extra semicolon after 'inner' closing brace prevents merging 4019 EXPECT_EQ("namespace out { namespace in {\n" 4020 "}; } // namespace out::in", 4021 format("namespace out {\n" 4022 "namespace in {\n" 4023 "}; // namespace in\n" 4024 "} // namespace out", 4025 Style)); 4026 4027 // Extra semicolon after 'outer' closing brace is conserved 4028 EXPECT_EQ("namespace out { namespace in {\n" 4029 "}}; // namespace out::in", 4030 format("namespace out {\n" 4031 "namespace in {\n" 4032 "} // namespace in\n" 4033 "}; // namespace out", 4034 Style)); 4035 4036 Style.NamespaceIndentation = FormatStyle::NI_All; 4037 EXPECT_EQ("namespace out { namespace in {\n" 4038 " int i;\n" 4039 "}} // namespace out::in", 4040 format("namespace out {\n" 4041 "namespace in {\n" 4042 "int i;\n" 4043 "} // namespace in\n" 4044 "} // namespace out", 4045 Style)); 4046 EXPECT_EQ("namespace out { namespace mid {\n" 4047 " namespace in {\n" 4048 " int j;\n" 4049 " } // namespace in\n" 4050 " int k;\n" 4051 "}} // namespace out::mid", 4052 format("namespace out { namespace mid {\n" 4053 "namespace in { int j; } // namespace in\n" 4054 "int k; }} // namespace out::mid", 4055 Style)); 4056 4057 Style.NamespaceIndentation = FormatStyle::NI_Inner; 4058 EXPECT_EQ("namespace out { namespace in {\n" 4059 " int i;\n" 4060 "}} // namespace out::in", 4061 format("namespace out {\n" 4062 "namespace in {\n" 4063 "int i;\n" 4064 "} // namespace in\n" 4065 "} // namespace out", 4066 Style)); 4067 EXPECT_EQ("namespace out { namespace mid { namespace in {\n" 4068 " int i;\n" 4069 "}}} // namespace out::mid::in", 4070 format("namespace out {\n" 4071 "namespace mid {\n" 4072 "namespace in {\n" 4073 "int i;\n" 4074 "} // namespace in\n" 4075 "} // namespace mid\n" 4076 "} // namespace out", 4077 Style)); 4078 4079 Style.CompactNamespaces = true; 4080 Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 4081 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4082 Style.BraceWrapping.BeforeLambdaBody = true; 4083 verifyFormat("namespace out { namespace in {\n" 4084 "}} // namespace out::in", 4085 Style); 4086 EXPECT_EQ("namespace out { namespace in {\n" 4087 "}} // namespace out::in", 4088 format("namespace out {\n" 4089 "namespace in {\n" 4090 "} // namespace in\n" 4091 "} // namespace out", 4092 Style)); 4093 } 4094 4095 TEST_F(FormatTest, FormatsExternC) { 4096 verifyFormat("extern \"C\" {\nint a;"); 4097 verifyFormat("extern \"C\" {}"); 4098 verifyFormat("extern \"C\" {\n" 4099 "int foo();\n" 4100 "}"); 4101 verifyFormat("extern \"C\" int foo() {}"); 4102 verifyFormat("extern \"C\" int foo();"); 4103 verifyFormat("extern \"C\" int foo() {\n" 4104 " int i = 42;\n" 4105 " return i;\n" 4106 "}"); 4107 4108 FormatStyle Style = getLLVMStyle(); 4109 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4110 Style.BraceWrapping.AfterFunction = true; 4111 verifyFormat("extern \"C\" int foo() {}", Style); 4112 verifyFormat("extern \"C\" int foo();", Style); 4113 verifyFormat("extern \"C\" int foo()\n" 4114 "{\n" 4115 " int i = 42;\n" 4116 " return i;\n" 4117 "}", 4118 Style); 4119 4120 Style.BraceWrapping.AfterExternBlock = true; 4121 Style.BraceWrapping.SplitEmptyRecord = false; 4122 verifyFormat("extern \"C\"\n" 4123 "{}", 4124 Style); 4125 verifyFormat("extern \"C\"\n" 4126 "{\n" 4127 " int foo();\n" 4128 "}", 4129 Style); 4130 } 4131 4132 TEST_F(FormatTest, IndentExternBlockStyle) { 4133 FormatStyle Style = getLLVMStyle(); 4134 Style.IndentWidth = 2; 4135 4136 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4137 verifyFormat("extern \"C\" { /*9*/\n" 4138 "}", 4139 Style); 4140 verifyFormat("extern \"C\" {\n" 4141 " int foo10();\n" 4142 "}", 4143 Style); 4144 4145 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 4146 verifyFormat("extern \"C\" { /*11*/\n" 4147 "}", 4148 Style); 4149 verifyFormat("extern \"C\" {\n" 4150 "int foo12();\n" 4151 "}", 4152 Style); 4153 4154 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4155 Style.BraceWrapping.AfterExternBlock = true; 4156 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4157 verifyFormat("extern \"C\"\n" 4158 "{ /*13*/\n" 4159 "}", 4160 Style); 4161 verifyFormat("extern \"C\"\n{\n" 4162 " int foo14();\n" 4163 "}", 4164 Style); 4165 4166 Style.BraceWrapping.AfterExternBlock = false; 4167 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 4168 verifyFormat("extern \"C\" { /*15*/\n" 4169 "}", 4170 Style); 4171 verifyFormat("extern \"C\" {\n" 4172 "int foo16();\n" 4173 "}", 4174 Style); 4175 4176 Style.BraceWrapping.AfterExternBlock = true; 4177 verifyFormat("extern \"C\"\n" 4178 "{ /*13*/\n" 4179 "}", 4180 Style); 4181 verifyFormat("extern \"C\"\n" 4182 "{\n" 4183 "int foo14();\n" 4184 "}", 4185 Style); 4186 4187 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4188 verifyFormat("extern \"C\"\n" 4189 "{ /*13*/\n" 4190 "}", 4191 Style); 4192 verifyFormat("extern \"C\"\n" 4193 "{\n" 4194 " int foo14();\n" 4195 "}", 4196 Style); 4197 } 4198 4199 TEST_F(FormatTest, FormatsInlineASM) { 4200 verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));"); 4201 verifyFormat("asm(\"nop\" ::: \"memory\");"); 4202 verifyFormat( 4203 "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n" 4204 " \"cpuid\\n\\t\"\n" 4205 " \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n" 4206 " : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n" 4207 " : \"a\"(value));"); 4208 EXPECT_EQ( 4209 "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n" 4210 " __asm {\n" 4211 " mov edx,[that] // vtable in edx\n" 4212 " mov eax,methodIndex\n" 4213 " call [edx][eax*4] // stdcall\n" 4214 " }\n" 4215 "}", 4216 format("void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n" 4217 " __asm {\n" 4218 " mov edx,[that] // vtable in edx\n" 4219 " mov eax,methodIndex\n" 4220 " call [edx][eax*4] // stdcall\n" 4221 " }\n" 4222 "}")); 4223 EXPECT_EQ("_asm {\n" 4224 " xor eax, eax;\n" 4225 " cpuid;\n" 4226 "}", 4227 format("_asm {\n" 4228 " xor eax, eax;\n" 4229 " cpuid;\n" 4230 "}")); 4231 verifyFormat("void function() {\n" 4232 " // comment\n" 4233 " asm(\"\");\n" 4234 "}"); 4235 EXPECT_EQ("__asm {\n" 4236 "}\n" 4237 "int i;", 4238 format("__asm {\n" 4239 "}\n" 4240 "int i;")); 4241 } 4242 4243 TEST_F(FormatTest, FormatTryCatch) { 4244 verifyFormat("try {\n" 4245 " throw a * b;\n" 4246 "} catch (int a) {\n" 4247 " // Do nothing.\n" 4248 "} catch (...) {\n" 4249 " exit(42);\n" 4250 "}"); 4251 4252 // Function-level try statements. 4253 verifyFormat("int f() try { return 4; } catch (...) {\n" 4254 " return 5;\n" 4255 "}"); 4256 verifyFormat("class A {\n" 4257 " int a;\n" 4258 " A() try : a(0) {\n" 4259 " } catch (...) {\n" 4260 " throw;\n" 4261 " }\n" 4262 "};\n"); 4263 verifyFormat("class A {\n" 4264 " int a;\n" 4265 " A() try : a(0), b{1} {\n" 4266 " } catch (...) {\n" 4267 " throw;\n" 4268 " }\n" 4269 "};\n"); 4270 verifyFormat("class A {\n" 4271 " int a;\n" 4272 " A() try : a(0), b{1}, c{2} {\n" 4273 " } catch (...) {\n" 4274 " throw;\n" 4275 " }\n" 4276 "};\n"); 4277 verifyFormat("class A {\n" 4278 " int a;\n" 4279 " A() try : a(0), b{1}, c{2} {\n" 4280 " { // New scope.\n" 4281 " }\n" 4282 " } catch (...) {\n" 4283 " throw;\n" 4284 " }\n" 4285 "};\n"); 4286 4287 // Incomplete try-catch blocks. 4288 verifyIncompleteFormat("try {} catch ("); 4289 } 4290 4291 TEST_F(FormatTest, FormatTryAsAVariable) { 4292 verifyFormat("int try;"); 4293 verifyFormat("int try, size;"); 4294 verifyFormat("try = foo();"); 4295 verifyFormat("if (try < size) {\n return true;\n}"); 4296 4297 verifyFormat("int catch;"); 4298 verifyFormat("int catch, size;"); 4299 verifyFormat("catch = foo();"); 4300 verifyFormat("if (catch < size) {\n return true;\n}"); 4301 4302 FormatStyle Style = getLLVMStyle(); 4303 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4304 Style.BraceWrapping.AfterFunction = true; 4305 Style.BraceWrapping.BeforeCatch = true; 4306 verifyFormat("try {\n" 4307 " int bar = 1;\n" 4308 "}\n" 4309 "catch (...) {\n" 4310 " int bar = 1;\n" 4311 "}", 4312 Style); 4313 verifyFormat("#if NO_EX\n" 4314 "try\n" 4315 "#endif\n" 4316 "{\n" 4317 "}\n" 4318 "#if NO_EX\n" 4319 "catch (...) {\n" 4320 "}", 4321 Style); 4322 verifyFormat("try /* abc */ {\n" 4323 " int bar = 1;\n" 4324 "}\n" 4325 "catch (...) {\n" 4326 " int bar = 1;\n" 4327 "}", 4328 Style); 4329 verifyFormat("try\n" 4330 "// abc\n" 4331 "{\n" 4332 " int bar = 1;\n" 4333 "}\n" 4334 "catch (...) {\n" 4335 " int bar = 1;\n" 4336 "}", 4337 Style); 4338 } 4339 4340 TEST_F(FormatTest, FormatSEHTryCatch) { 4341 verifyFormat("__try {\n" 4342 " int a = b * c;\n" 4343 "} __except (EXCEPTION_EXECUTE_HANDLER) {\n" 4344 " // Do nothing.\n" 4345 "}"); 4346 4347 verifyFormat("__try {\n" 4348 " int a = b * c;\n" 4349 "} __finally {\n" 4350 " // Do nothing.\n" 4351 "}"); 4352 4353 verifyFormat("DEBUG({\n" 4354 " __try {\n" 4355 " } __finally {\n" 4356 " }\n" 4357 "});\n"); 4358 } 4359 4360 TEST_F(FormatTest, IncompleteTryCatchBlocks) { 4361 verifyFormat("try {\n" 4362 " f();\n" 4363 "} catch {\n" 4364 " g();\n" 4365 "}"); 4366 verifyFormat("try {\n" 4367 " f();\n" 4368 "} catch (A a) MACRO(x) {\n" 4369 " g();\n" 4370 "} catch (B b) MACRO(x) {\n" 4371 " g();\n" 4372 "}"); 4373 } 4374 4375 TEST_F(FormatTest, FormatTryCatchBraceStyles) { 4376 FormatStyle Style = getLLVMStyle(); 4377 for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla, 4378 FormatStyle::BS_WebKit}) { 4379 Style.BreakBeforeBraces = BraceStyle; 4380 verifyFormat("try {\n" 4381 " // something\n" 4382 "} catch (...) {\n" 4383 " // something\n" 4384 "}", 4385 Style); 4386 } 4387 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 4388 verifyFormat("try {\n" 4389 " // something\n" 4390 "}\n" 4391 "catch (...) {\n" 4392 " // something\n" 4393 "}", 4394 Style); 4395 verifyFormat("__try {\n" 4396 " // something\n" 4397 "}\n" 4398 "__finally {\n" 4399 " // something\n" 4400 "}", 4401 Style); 4402 verifyFormat("@try {\n" 4403 " // something\n" 4404 "}\n" 4405 "@finally {\n" 4406 " // something\n" 4407 "}", 4408 Style); 4409 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 4410 verifyFormat("try\n" 4411 "{\n" 4412 " // something\n" 4413 "}\n" 4414 "catch (...)\n" 4415 "{\n" 4416 " // something\n" 4417 "}", 4418 Style); 4419 Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 4420 verifyFormat("try\n" 4421 " {\n" 4422 " // something white\n" 4423 " }\n" 4424 "catch (...)\n" 4425 " {\n" 4426 " // something white\n" 4427 " }", 4428 Style); 4429 Style.BreakBeforeBraces = FormatStyle::BS_GNU; 4430 verifyFormat("try\n" 4431 " {\n" 4432 " // something\n" 4433 " }\n" 4434 "catch (...)\n" 4435 " {\n" 4436 " // something\n" 4437 " }", 4438 Style); 4439 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4440 Style.BraceWrapping.BeforeCatch = true; 4441 verifyFormat("try {\n" 4442 " // something\n" 4443 "}\n" 4444 "catch (...) {\n" 4445 " // something\n" 4446 "}", 4447 Style); 4448 } 4449 4450 TEST_F(FormatTest, StaticInitializers) { 4451 verifyFormat("static SomeClass SC = {1, 'a'};"); 4452 4453 verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n" 4454 " 100000000, " 4455 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};"); 4456 4457 // Here, everything other than the "}" would fit on a line. 4458 verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n" 4459 " 10000000000000000000000000};"); 4460 EXPECT_EQ("S s = {a,\n" 4461 "\n" 4462 " b};", 4463 format("S s = {\n" 4464 " a,\n" 4465 "\n" 4466 " b\n" 4467 "};")); 4468 4469 // FIXME: This would fit into the column limit if we'd fit "{ {" on the first 4470 // line. However, the formatting looks a bit off and this probably doesn't 4471 // happen often in practice. 4472 verifyFormat("static int Variable[1] = {\n" 4473 " {1000000000000000000000000000000000000}};", 4474 getLLVMStyleWithColumns(40)); 4475 } 4476 4477 TEST_F(FormatTest, DesignatedInitializers) { 4478 verifyFormat("const struct A a = {.a = 1, .b = 2};"); 4479 verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n" 4480 " .bbbbbbbbbb = 2,\n" 4481 " .cccccccccc = 3,\n" 4482 " .dddddddddd = 4,\n" 4483 " .eeeeeeeeee = 5};"); 4484 verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n" 4485 " .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n" 4486 " .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n" 4487 " .ccccccccccccccccccccccccccc = 3,\n" 4488 " .ddddddddddddddddddddddddddd = 4,\n" 4489 " .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};"); 4490 4491 verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};"); 4492 4493 verifyFormat("const struct A a = {[0] = 1, [1] = 2};"); 4494 verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n" 4495 " [2] = bbbbbbbbbb,\n" 4496 " [3] = cccccccccc,\n" 4497 " [4] = dddddddddd,\n" 4498 " [5] = eeeeeeeeee};"); 4499 verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n" 4500 " [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 4501 " [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 4502 " [3] = cccccccccccccccccccccccccccccccccccccc,\n" 4503 " [4] = dddddddddddddddddddddddddddddddddddddd,\n" 4504 " [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};"); 4505 } 4506 4507 TEST_F(FormatTest, NestedStaticInitializers) { 4508 verifyFormat("static A x = {{{}}};\n"); 4509 verifyFormat("static A x = {{{init1, init2, init3, init4},\n" 4510 " {init1, init2, init3, init4}}};", 4511 getLLVMStyleWithColumns(50)); 4512 4513 verifyFormat("somes Status::global_reps[3] = {\n" 4514 " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n" 4515 " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n" 4516 " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};", 4517 getLLVMStyleWithColumns(60)); 4518 verifyGoogleFormat("SomeType Status::global_reps[3] = {\n" 4519 " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n" 4520 " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n" 4521 " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};"); 4522 verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n" 4523 " {rect.fRight - rect.fLeft, rect.fBottom - " 4524 "rect.fTop}};"); 4525 4526 verifyFormat( 4527 "SomeArrayOfSomeType a = {\n" 4528 " {{1, 2, 3},\n" 4529 " {1, 2, 3},\n" 4530 " {111111111111111111111111111111, 222222222222222222222222222222,\n" 4531 " 333333333333333333333333333333},\n" 4532 " {1, 2, 3},\n" 4533 " {1, 2, 3}}};"); 4534 verifyFormat( 4535 "SomeArrayOfSomeType a = {\n" 4536 " {{1, 2, 3}},\n" 4537 " {{1, 2, 3}},\n" 4538 " {{111111111111111111111111111111, 222222222222222222222222222222,\n" 4539 " 333333333333333333333333333333}},\n" 4540 " {{1, 2, 3}},\n" 4541 " {{1, 2, 3}}};"); 4542 4543 verifyFormat("struct {\n" 4544 " unsigned bit;\n" 4545 " const char *const name;\n" 4546 "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n" 4547 " {kOsWin, \"Windows\"},\n" 4548 " {kOsLinux, \"Linux\"},\n" 4549 " {kOsCrOS, \"Chrome OS\"}};"); 4550 verifyFormat("struct {\n" 4551 " unsigned bit;\n" 4552 " const char *const name;\n" 4553 "} kBitsToOs[] = {\n" 4554 " {kOsMac, \"Mac\"},\n" 4555 " {kOsWin, \"Windows\"},\n" 4556 " {kOsLinux, \"Linux\"},\n" 4557 " {kOsCrOS, \"Chrome OS\"},\n" 4558 "};"); 4559 } 4560 4561 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) { 4562 verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro(" 4563 " \\\n" 4564 " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)"); 4565 } 4566 4567 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) { 4568 verifyFormat("virtual void write(ELFWriter *writerrr,\n" 4569 " OwningPtr<FileOutputBuffer> &buffer) = 0;"); 4570 4571 // Do break defaulted and deleted functions. 4572 verifyFormat("virtual void ~Deeeeeeeestructor() =\n" 4573 " default;", 4574 getLLVMStyleWithColumns(40)); 4575 verifyFormat("virtual void ~Deeeeeeeestructor() =\n" 4576 " delete;", 4577 getLLVMStyleWithColumns(40)); 4578 } 4579 4580 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) { 4581 verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3", 4582 getLLVMStyleWithColumns(40)); 4583 verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"", 4584 getLLVMStyleWithColumns(40)); 4585 EXPECT_EQ("#define Q \\\n" 4586 " \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\" \\\n" 4587 " \"aaaaaaaa.cpp\"", 4588 format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"", 4589 getLLVMStyleWithColumns(40))); 4590 } 4591 4592 TEST_F(FormatTest, UnderstandsLinePPDirective) { 4593 EXPECT_EQ("# 123 \"A string literal\"", 4594 format(" # 123 \"A string literal\"")); 4595 } 4596 4597 TEST_F(FormatTest, LayoutUnknownPPDirective) { 4598 EXPECT_EQ("#;", format("#;")); 4599 verifyFormat("#\n;\n;\n;"); 4600 } 4601 4602 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) { 4603 EXPECT_EQ("#line 42 \"test\"\n", 4604 format("# \\\n line \\\n 42 \\\n \"test\"\n")); 4605 EXPECT_EQ("#define A B\n", format("# \\\n define \\\n A \\\n B\n", 4606 getLLVMStyleWithColumns(12))); 4607 } 4608 4609 TEST_F(FormatTest, EndOfFileEndsPPDirective) { 4610 EXPECT_EQ("#line 42 \"test\"", 4611 format("# \\\n line \\\n 42 \\\n \"test\"")); 4612 EXPECT_EQ("#define A B", format("# \\\n define \\\n A \\\n B")); 4613 } 4614 4615 TEST_F(FormatTest, DoesntRemoveUnknownTokens) { 4616 verifyFormat("#define A \\x20"); 4617 verifyFormat("#define A \\ x20"); 4618 EXPECT_EQ("#define A \\ x20", format("#define A \\ x20")); 4619 verifyFormat("#define A ''"); 4620 verifyFormat("#define A ''qqq"); 4621 verifyFormat("#define A `qqq"); 4622 verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");"); 4623 EXPECT_EQ("const char *c = STRINGIFY(\n" 4624 "\\na : b);", 4625 format("const char * c = STRINGIFY(\n" 4626 "\\na : b);")); 4627 4628 verifyFormat("a\r\\"); 4629 verifyFormat("a\v\\"); 4630 verifyFormat("a\f\\"); 4631 } 4632 4633 TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) { 4634 FormatStyle style = getChromiumStyle(FormatStyle::LK_Cpp); 4635 style.IndentWidth = 4; 4636 style.PPIndentWidth = 1; 4637 4638 style.IndentPPDirectives = FormatStyle::PPDIS_None; 4639 verifyFormat("#ifdef __linux__\n" 4640 "void foo() {\n" 4641 " int x = 0;\n" 4642 "}\n" 4643 "#define FOO\n" 4644 "#endif\n" 4645 "void bar() {\n" 4646 " int y = 0;\n" 4647 "}\n", 4648 style); 4649 4650 style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash; 4651 verifyFormat("#ifdef __linux__\n" 4652 "void foo() {\n" 4653 " int x = 0;\n" 4654 "}\n" 4655 "# define FOO foo\n" 4656 "#endif\n" 4657 "void bar() {\n" 4658 " int y = 0;\n" 4659 "}\n", 4660 style); 4661 4662 style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash; 4663 verifyFormat("#ifdef __linux__\n" 4664 "void foo() {\n" 4665 " int x = 0;\n" 4666 "}\n" 4667 " #define FOO foo\n" 4668 "#endif\n" 4669 "void bar() {\n" 4670 " int y = 0;\n" 4671 "}\n", 4672 style); 4673 } 4674 4675 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) { 4676 verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13)); 4677 verifyFormat("#define A( \\\n BB)", getLLVMStyleWithColumns(12)); 4678 verifyFormat("#define A( \\\n A, B)", getLLVMStyleWithColumns(12)); 4679 // FIXME: We never break before the macro name. 4680 verifyFormat("#define AA( \\\n B)", getLLVMStyleWithColumns(12)); 4681 4682 verifyFormat("#define A A\n#define A A"); 4683 verifyFormat("#define A(X) A\n#define A A"); 4684 4685 verifyFormat("#define Something Other", getLLVMStyleWithColumns(23)); 4686 verifyFormat("#define Something \\\n Other", getLLVMStyleWithColumns(22)); 4687 } 4688 4689 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) { 4690 EXPECT_EQ("// somecomment\n" 4691 "#include \"a.h\"\n" 4692 "#define A( \\\n" 4693 " A, B)\n" 4694 "#include \"b.h\"\n" 4695 "// somecomment\n", 4696 format(" // somecomment\n" 4697 " #include \"a.h\"\n" 4698 "#define A(A,\\\n" 4699 " B)\n" 4700 " #include \"b.h\"\n" 4701 " // somecomment\n", 4702 getLLVMStyleWithColumns(13))); 4703 } 4704 4705 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); } 4706 4707 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) { 4708 EXPECT_EQ("#define A \\\n" 4709 " c; \\\n" 4710 " e;\n" 4711 "f;", 4712 format("#define A c; e;\n" 4713 "f;", 4714 getLLVMStyleWithColumns(14))); 4715 } 4716 4717 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); } 4718 4719 TEST_F(FormatTest, MacroDefinitionInsideStatement) { 4720 EXPECT_EQ("int x,\n" 4721 "#define A\n" 4722 " y;", 4723 format("int x,\n#define A\ny;")); 4724 } 4725 4726 TEST_F(FormatTest, HashInMacroDefinition) { 4727 EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle())); 4728 EXPECT_EQ("#define A(c) u#c", format("#define A(c) u#c", getLLVMStyle())); 4729 EXPECT_EQ("#define A(c) U#c", format("#define A(c) U#c", getLLVMStyle())); 4730 EXPECT_EQ("#define A(c) u8#c", format("#define A(c) u8#c", getLLVMStyle())); 4731 EXPECT_EQ("#define A(c) LR#c", format("#define A(c) LR#c", getLLVMStyle())); 4732 EXPECT_EQ("#define A(c) uR#c", format("#define A(c) uR#c", getLLVMStyle())); 4733 EXPECT_EQ("#define A(c) UR#c", format("#define A(c) UR#c", getLLVMStyle())); 4734 EXPECT_EQ("#define A(c) u8R#c", format("#define A(c) u8R#c", getLLVMStyle())); 4735 verifyFormat("#define A \\\n b #c;", getLLVMStyleWithColumns(11)); 4736 verifyFormat("#define A \\\n" 4737 " { \\\n" 4738 " f(#c); \\\n" 4739 " }", 4740 getLLVMStyleWithColumns(11)); 4741 4742 verifyFormat("#define A(X) \\\n" 4743 " void function##X()", 4744 getLLVMStyleWithColumns(22)); 4745 4746 verifyFormat("#define A(a, b, c) \\\n" 4747 " void a##b##c()", 4748 getLLVMStyleWithColumns(22)); 4749 4750 verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22)); 4751 } 4752 4753 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) { 4754 EXPECT_EQ("#define A (x)", format("#define A (x)")); 4755 EXPECT_EQ("#define A(x)", format("#define A(x)")); 4756 4757 FormatStyle Style = getLLVMStyle(); 4758 Style.SpaceBeforeParens = FormatStyle::SBPO_Never; 4759 verifyFormat("#define true ((foo)1)", Style); 4760 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 4761 verifyFormat("#define false((foo)0)", Style); 4762 } 4763 4764 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) { 4765 EXPECT_EQ("#define A b;", format("#define A \\\n" 4766 " \\\n" 4767 " b;", 4768 getLLVMStyleWithColumns(25))); 4769 EXPECT_EQ("#define A \\\n" 4770 " \\\n" 4771 " a; \\\n" 4772 " b;", 4773 format("#define A \\\n" 4774 " \\\n" 4775 " a; \\\n" 4776 " b;", 4777 getLLVMStyleWithColumns(11))); 4778 EXPECT_EQ("#define A \\\n" 4779 " a; \\\n" 4780 " \\\n" 4781 " b;", 4782 format("#define A \\\n" 4783 " a; \\\n" 4784 " \\\n" 4785 " b;", 4786 getLLVMStyleWithColumns(11))); 4787 } 4788 4789 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) { 4790 verifyIncompleteFormat("#define A :"); 4791 verifyFormat("#define SOMECASES \\\n" 4792 " case 1: \\\n" 4793 " case 2\n", 4794 getLLVMStyleWithColumns(20)); 4795 verifyFormat("#define MACRO(a) \\\n" 4796 " if (a) \\\n" 4797 " f(); \\\n" 4798 " else \\\n" 4799 " g()", 4800 getLLVMStyleWithColumns(18)); 4801 verifyFormat("#define A template <typename T>"); 4802 verifyIncompleteFormat("#define STR(x) #x\n" 4803 "f(STR(this_is_a_string_literal{));"); 4804 verifyFormat("#pragma omp threadprivate( \\\n" 4805 " y)), // expected-warning", 4806 getLLVMStyleWithColumns(28)); 4807 verifyFormat("#d, = };"); 4808 verifyFormat("#if \"a"); 4809 verifyIncompleteFormat("({\n" 4810 "#define b \\\n" 4811 " } \\\n" 4812 " a\n" 4813 "a", 4814 getLLVMStyleWithColumns(15)); 4815 verifyFormat("#define A \\\n" 4816 " { \\\n" 4817 " {\n" 4818 "#define B \\\n" 4819 " } \\\n" 4820 " }", 4821 getLLVMStyleWithColumns(15)); 4822 verifyNoCrash("#if a\na(\n#else\n#endif\n{a"); 4823 verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}"); 4824 verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};"); 4825 verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() { \n)}"); 4826 } 4827 4828 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) { 4829 verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline. 4830 EXPECT_EQ("class A : public QObject {\n" 4831 " Q_OBJECT\n" 4832 "\n" 4833 " A() {}\n" 4834 "};", 4835 format("class A : public QObject {\n" 4836 " Q_OBJECT\n" 4837 "\n" 4838 " A() {\n}\n" 4839 "} ;")); 4840 EXPECT_EQ("MACRO\n" 4841 "/*static*/ int i;", 4842 format("MACRO\n" 4843 " /*static*/ int i;")); 4844 EXPECT_EQ("SOME_MACRO\n" 4845 "namespace {\n" 4846 "void f();\n" 4847 "} // namespace", 4848 format("SOME_MACRO\n" 4849 " namespace {\n" 4850 "void f( );\n" 4851 "} // namespace")); 4852 // Only if the identifier contains at least 5 characters. 4853 EXPECT_EQ("HTTP f();", format("HTTP\nf();")); 4854 EXPECT_EQ("MACRO\nf();", format("MACRO\nf();")); 4855 // Only if everything is upper case. 4856 EXPECT_EQ("class A : public QObject {\n" 4857 " Q_Object A() {}\n" 4858 "};", 4859 format("class A : public QObject {\n" 4860 " Q_Object\n" 4861 " A() {\n}\n" 4862 "} ;")); 4863 4864 // Only if the next line can actually start an unwrapped line. 4865 EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;", 4866 format("SOME_WEIRD_LOG_MACRO\n" 4867 "<< SomeThing;")); 4868 4869 verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), " 4870 "(n, buffers))\n", 4871 getChromiumStyle(FormatStyle::LK_Cpp)); 4872 4873 // See PR41483 4874 EXPECT_EQ("/**/ FOO(a)\n" 4875 "FOO(b)", 4876 format("/**/ FOO(a)\n" 4877 "FOO(b)")); 4878 } 4879 4880 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) { 4881 EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n" 4882 "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n" 4883 "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n" 4884 "class X {};\n" 4885 "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n" 4886 "int *createScopDetectionPass() { return 0; }", 4887 format(" INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n" 4888 " INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n" 4889 " INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n" 4890 " class X {};\n" 4891 " INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n" 4892 " int *createScopDetectionPass() { return 0; }")); 4893 // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as 4894 // braces, so that inner block is indented one level more. 4895 EXPECT_EQ("int q() {\n" 4896 " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n" 4897 " IPC_MESSAGE_HANDLER(xxx, qqq)\n" 4898 " IPC_END_MESSAGE_MAP()\n" 4899 "}", 4900 format("int q() {\n" 4901 " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n" 4902 " IPC_MESSAGE_HANDLER(xxx, qqq)\n" 4903 " IPC_END_MESSAGE_MAP()\n" 4904 "}")); 4905 4906 // Same inside macros. 4907 EXPECT_EQ("#define LIST(L) \\\n" 4908 " L(A) \\\n" 4909 " L(B) \\\n" 4910 " L(C)", 4911 format("#define LIST(L) \\\n" 4912 " L(A) \\\n" 4913 " L(B) \\\n" 4914 " L(C)", 4915 getGoogleStyle())); 4916 4917 // These must not be recognized as macros. 4918 EXPECT_EQ("int q() {\n" 4919 " f(x);\n" 4920 " f(x) {}\n" 4921 " f(x)->g();\n" 4922 " f(x)->*g();\n" 4923 " f(x).g();\n" 4924 " f(x) = x;\n" 4925 " f(x) += x;\n" 4926 " f(x) -= x;\n" 4927 " f(x) *= x;\n" 4928 " f(x) /= x;\n" 4929 " f(x) %= x;\n" 4930 " f(x) &= x;\n" 4931 " f(x) |= x;\n" 4932 " f(x) ^= x;\n" 4933 " f(x) >>= x;\n" 4934 " f(x) <<= x;\n" 4935 " f(x)[y].z();\n" 4936 " LOG(INFO) << x;\n" 4937 " ifstream(x) >> x;\n" 4938 "}\n", 4939 format("int q() {\n" 4940 " f(x)\n;\n" 4941 " f(x)\n {}\n" 4942 " f(x)\n->g();\n" 4943 " f(x)\n->*g();\n" 4944 " f(x)\n.g();\n" 4945 " f(x)\n = x;\n" 4946 " f(x)\n += x;\n" 4947 " f(x)\n -= x;\n" 4948 " f(x)\n *= x;\n" 4949 " f(x)\n /= x;\n" 4950 " f(x)\n %= x;\n" 4951 " f(x)\n &= x;\n" 4952 " f(x)\n |= x;\n" 4953 " f(x)\n ^= x;\n" 4954 " f(x)\n >>= x;\n" 4955 " f(x)\n <<= x;\n" 4956 " f(x)\n[y].z();\n" 4957 " LOG(INFO)\n << x;\n" 4958 " ifstream(x)\n >> x;\n" 4959 "}\n")); 4960 EXPECT_EQ("int q() {\n" 4961 " F(x)\n" 4962 " if (1) {\n" 4963 " }\n" 4964 " F(x)\n" 4965 " while (1) {\n" 4966 " }\n" 4967 " F(x)\n" 4968 " G(x);\n" 4969 " F(x)\n" 4970 " try {\n" 4971 " Q();\n" 4972 " } catch (...) {\n" 4973 " }\n" 4974 "}\n", 4975 format("int q() {\n" 4976 "F(x)\n" 4977 "if (1) {}\n" 4978 "F(x)\n" 4979 "while (1) {}\n" 4980 "F(x)\n" 4981 "G(x);\n" 4982 "F(x)\n" 4983 "try { Q(); } catch (...) {}\n" 4984 "}\n")); 4985 EXPECT_EQ("class A {\n" 4986 " A() : t(0) {}\n" 4987 " A(int i) noexcept() : {}\n" 4988 " A(X x)\n" // FIXME: function-level try blocks are broken. 4989 " try : t(0) {\n" 4990 " } catch (...) {\n" 4991 " }\n" 4992 "};", 4993 format("class A {\n" 4994 " A()\n : t(0) {}\n" 4995 " A(int i)\n noexcept() : {}\n" 4996 " A(X x)\n" 4997 " try : t(0) {} catch (...) {}\n" 4998 "};")); 4999 FormatStyle Style = getLLVMStyle(); 5000 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 5001 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 5002 Style.BraceWrapping.AfterFunction = true; 5003 EXPECT_EQ("void f()\n" 5004 "try\n" 5005 "{\n" 5006 "}", 5007 format("void f() try {\n" 5008 "}", 5009 Style)); 5010 EXPECT_EQ("class SomeClass {\n" 5011 "public:\n" 5012 " SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5013 "};", 5014 format("class SomeClass {\n" 5015 "public:\n" 5016 " SomeClass()\n" 5017 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5018 "};")); 5019 EXPECT_EQ("class SomeClass {\n" 5020 "public:\n" 5021 " SomeClass()\n" 5022 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5023 "};", 5024 format("class SomeClass {\n" 5025 "public:\n" 5026 " SomeClass()\n" 5027 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5028 "};", 5029 getLLVMStyleWithColumns(40))); 5030 5031 verifyFormat("MACRO(>)"); 5032 5033 // Some macros contain an implicit semicolon. 5034 Style = getLLVMStyle(); 5035 Style.StatementMacros.push_back("FOO"); 5036 verifyFormat("FOO(a) int b = 0;"); 5037 verifyFormat("FOO(a)\n" 5038 "int b = 0;", 5039 Style); 5040 verifyFormat("FOO(a);\n" 5041 "int b = 0;", 5042 Style); 5043 verifyFormat("FOO(argc, argv, \"4.0.2\")\n" 5044 "int b = 0;", 5045 Style); 5046 verifyFormat("FOO()\n" 5047 "int b = 0;", 5048 Style); 5049 verifyFormat("FOO\n" 5050 "int b = 0;", 5051 Style); 5052 verifyFormat("void f() {\n" 5053 " FOO(a)\n" 5054 " return a;\n" 5055 "}", 5056 Style); 5057 verifyFormat("FOO(a)\n" 5058 "FOO(b)", 5059 Style); 5060 verifyFormat("int a = 0;\n" 5061 "FOO(b)\n" 5062 "int c = 0;", 5063 Style); 5064 verifyFormat("int a = 0;\n" 5065 "int x = FOO(a)\n" 5066 "int b = 0;", 5067 Style); 5068 verifyFormat("void foo(int a) { FOO(a) }\n" 5069 "uint32_t bar() {}", 5070 Style); 5071 } 5072 5073 TEST_F(FormatTest, FormatsMacrosWithZeroColumnWidth) { 5074 FormatStyle ZeroColumn = getLLVMStyleWithColumns(0); 5075 5076 verifyFormat("#define A LOOOOOOOOOOOOOOOOOOONG() LOOOOOOOOOOOOOOOOOOONG()", 5077 ZeroColumn); 5078 } 5079 5080 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) { 5081 verifyFormat("#define A \\\n" 5082 " f({ \\\n" 5083 " g(); \\\n" 5084 " });", 5085 getLLVMStyleWithColumns(11)); 5086 } 5087 5088 TEST_F(FormatTest, IndentPreprocessorDirectives) { 5089 FormatStyle Style = getLLVMStyleWithColumns(40); 5090 Style.IndentPPDirectives = FormatStyle::PPDIS_None; 5091 verifyFormat("#ifdef _WIN32\n" 5092 "#define A 0\n" 5093 "#ifdef VAR2\n" 5094 "#define B 1\n" 5095 "#include <someheader.h>\n" 5096 "#define MACRO \\\n" 5097 " some_very_long_func_aaaaaaaaaa();\n" 5098 "#endif\n" 5099 "#else\n" 5100 "#define A 1\n" 5101 "#endif", 5102 Style); 5103 Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash; 5104 verifyFormat("#ifdef _WIN32\n" 5105 "# define A 0\n" 5106 "# ifdef VAR2\n" 5107 "# define B 1\n" 5108 "# include <someheader.h>\n" 5109 "# define MACRO \\\n" 5110 " some_very_long_func_aaaaaaaaaa();\n" 5111 "# endif\n" 5112 "#else\n" 5113 "# define A 1\n" 5114 "#endif", 5115 Style); 5116 verifyFormat("#if A\n" 5117 "# define MACRO \\\n" 5118 " void a(int x) { \\\n" 5119 " b(); \\\n" 5120 " c(); \\\n" 5121 " d(); \\\n" 5122 " e(); \\\n" 5123 " f(); \\\n" 5124 " }\n" 5125 "#endif", 5126 Style); 5127 // Comments before include guard. 5128 verifyFormat("// file comment\n" 5129 "// file comment\n" 5130 "#ifndef HEADER_H\n" 5131 "#define HEADER_H\n" 5132 "code();\n" 5133 "#endif", 5134 Style); 5135 // Test with include guards. 5136 verifyFormat("#ifndef HEADER_H\n" 5137 "#define HEADER_H\n" 5138 "code();\n" 5139 "#endif", 5140 Style); 5141 // Include guards must have a #define with the same variable immediately 5142 // after #ifndef. 5143 verifyFormat("#ifndef NOT_GUARD\n" 5144 "# define FOO\n" 5145 "code();\n" 5146 "#endif", 5147 Style); 5148 5149 // Include guards must cover the entire file. 5150 verifyFormat("code();\n" 5151 "code();\n" 5152 "#ifndef NOT_GUARD\n" 5153 "# define NOT_GUARD\n" 5154 "code();\n" 5155 "#endif", 5156 Style); 5157 verifyFormat("#ifndef NOT_GUARD\n" 5158 "# define NOT_GUARD\n" 5159 "code();\n" 5160 "#endif\n" 5161 "code();", 5162 Style); 5163 // Test with trailing blank lines. 5164 verifyFormat("#ifndef HEADER_H\n" 5165 "#define HEADER_H\n" 5166 "code();\n" 5167 "#endif\n", 5168 Style); 5169 // Include guards don't have #else. 5170 verifyFormat("#ifndef NOT_GUARD\n" 5171 "# define NOT_GUARD\n" 5172 "code();\n" 5173 "#else\n" 5174 "#endif", 5175 Style); 5176 verifyFormat("#ifndef NOT_GUARD\n" 5177 "# define NOT_GUARD\n" 5178 "code();\n" 5179 "#elif FOO\n" 5180 "#endif", 5181 Style); 5182 // Non-identifier #define after potential include guard. 5183 verifyFormat("#ifndef FOO\n" 5184 "# define 1\n" 5185 "#endif\n", 5186 Style); 5187 // #if closes past last non-preprocessor line. 5188 verifyFormat("#ifndef FOO\n" 5189 "#define FOO\n" 5190 "#if 1\n" 5191 "int i;\n" 5192 "# define A 0\n" 5193 "#endif\n" 5194 "#endif\n", 5195 Style); 5196 // Don't crash if there is an #elif directive without a condition. 5197 verifyFormat("#if 1\n" 5198 "int x;\n" 5199 "#elif\n" 5200 "int y;\n" 5201 "#else\n" 5202 "int z;\n" 5203 "#endif", 5204 Style); 5205 // FIXME: This doesn't handle the case where there's code between the 5206 // #ifndef and #define but all other conditions hold. This is because when 5207 // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the 5208 // previous code line yet, so we can't detect it. 5209 EXPECT_EQ("#ifndef NOT_GUARD\n" 5210 "code();\n" 5211 "#define NOT_GUARD\n" 5212 "code();\n" 5213 "#endif", 5214 format("#ifndef NOT_GUARD\n" 5215 "code();\n" 5216 "# define NOT_GUARD\n" 5217 "code();\n" 5218 "#endif", 5219 Style)); 5220 // FIXME: This doesn't handle cases where legitimate preprocessor lines may 5221 // be outside an include guard. Examples are #pragma once and 5222 // #pragma GCC diagnostic, or anything else that does not change the meaning 5223 // of the file if it's included multiple times. 5224 EXPECT_EQ("#ifdef WIN32\n" 5225 "# pragma once\n" 5226 "#endif\n" 5227 "#ifndef HEADER_H\n" 5228 "# define HEADER_H\n" 5229 "code();\n" 5230 "#endif", 5231 format("#ifdef WIN32\n" 5232 "# pragma once\n" 5233 "#endif\n" 5234 "#ifndef HEADER_H\n" 5235 "#define HEADER_H\n" 5236 "code();\n" 5237 "#endif", 5238 Style)); 5239 // FIXME: This does not detect when there is a single non-preprocessor line 5240 // in front of an include-guard-like structure where other conditions hold 5241 // because ScopedLineState hides the line. 5242 EXPECT_EQ("code();\n" 5243 "#ifndef HEADER_H\n" 5244 "#define HEADER_H\n" 5245 "code();\n" 5246 "#endif", 5247 format("code();\n" 5248 "#ifndef HEADER_H\n" 5249 "# define HEADER_H\n" 5250 "code();\n" 5251 "#endif", 5252 Style)); 5253 // Keep comments aligned with #, otherwise indent comments normally. These 5254 // tests cannot use verifyFormat because messUp manipulates leading 5255 // whitespace. 5256 { 5257 const char *Expected = "" 5258 "void f() {\n" 5259 "#if 1\n" 5260 "// Preprocessor aligned.\n" 5261 "# define A 0\n" 5262 " // Code. Separated by blank line.\n" 5263 "\n" 5264 "# define B 0\n" 5265 " // Code. Not aligned with #\n" 5266 "# define C 0\n" 5267 "#endif"; 5268 const char *ToFormat = "" 5269 "void f() {\n" 5270 "#if 1\n" 5271 "// Preprocessor aligned.\n" 5272 "# define A 0\n" 5273 "// Code. Separated by blank line.\n" 5274 "\n" 5275 "# define B 0\n" 5276 " // Code. Not aligned with #\n" 5277 "# define C 0\n" 5278 "#endif"; 5279 EXPECT_EQ(Expected, format(ToFormat, Style)); 5280 EXPECT_EQ(Expected, format(Expected, Style)); 5281 } 5282 // Keep block quotes aligned. 5283 { 5284 const char *Expected = "" 5285 "void f() {\n" 5286 "#if 1\n" 5287 "/* Preprocessor aligned. */\n" 5288 "# define A 0\n" 5289 " /* Code. Separated by blank line. */\n" 5290 "\n" 5291 "# define B 0\n" 5292 " /* Code. Not aligned with # */\n" 5293 "# define C 0\n" 5294 "#endif"; 5295 const char *ToFormat = "" 5296 "void f() {\n" 5297 "#if 1\n" 5298 "/* Preprocessor aligned. */\n" 5299 "# define A 0\n" 5300 "/* Code. Separated by blank line. */\n" 5301 "\n" 5302 "# define B 0\n" 5303 " /* Code. Not aligned with # */\n" 5304 "# define C 0\n" 5305 "#endif"; 5306 EXPECT_EQ(Expected, format(ToFormat, Style)); 5307 EXPECT_EQ(Expected, format(Expected, Style)); 5308 } 5309 // Keep comments aligned with un-indented directives. 5310 { 5311 const char *Expected = "" 5312 "void f() {\n" 5313 "// Preprocessor aligned.\n" 5314 "#define A 0\n" 5315 " // Code. Separated by blank line.\n" 5316 "\n" 5317 "#define B 0\n" 5318 " // Code. Not aligned with #\n" 5319 "#define C 0\n"; 5320 const char *ToFormat = "" 5321 "void f() {\n" 5322 "// Preprocessor aligned.\n" 5323 "#define A 0\n" 5324 "// Code. Separated by blank line.\n" 5325 "\n" 5326 "#define B 0\n" 5327 " // Code. Not aligned with #\n" 5328 "#define C 0\n"; 5329 EXPECT_EQ(Expected, format(ToFormat, Style)); 5330 EXPECT_EQ(Expected, format(Expected, Style)); 5331 } 5332 // Test AfterHash with tabs. 5333 { 5334 FormatStyle Tabbed = Style; 5335 Tabbed.UseTab = FormatStyle::UT_Always; 5336 Tabbed.IndentWidth = 8; 5337 Tabbed.TabWidth = 8; 5338 verifyFormat("#ifdef _WIN32\n" 5339 "#\tdefine A 0\n" 5340 "#\tifdef VAR2\n" 5341 "#\t\tdefine B 1\n" 5342 "#\t\tinclude <someheader.h>\n" 5343 "#\t\tdefine MACRO \\\n" 5344 "\t\t\tsome_very_long_func_aaaaaaaaaa();\n" 5345 "#\tendif\n" 5346 "#else\n" 5347 "#\tdefine A 1\n" 5348 "#endif", 5349 Tabbed); 5350 } 5351 5352 // Regression test: Multiline-macro inside include guards. 5353 verifyFormat("#ifndef HEADER_H\n" 5354 "#define HEADER_H\n" 5355 "#define A() \\\n" 5356 " int i; \\\n" 5357 " int j;\n" 5358 "#endif // HEADER_H", 5359 getLLVMStyleWithColumns(20)); 5360 5361 Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash; 5362 // Basic before hash indent tests 5363 verifyFormat("#ifdef _WIN32\n" 5364 " #define A 0\n" 5365 " #ifdef VAR2\n" 5366 " #define B 1\n" 5367 " #include <someheader.h>\n" 5368 " #define MACRO \\\n" 5369 " some_very_long_func_aaaaaaaaaa();\n" 5370 " #endif\n" 5371 "#else\n" 5372 " #define A 1\n" 5373 "#endif", 5374 Style); 5375 verifyFormat("#if A\n" 5376 " #define MACRO \\\n" 5377 " void a(int x) { \\\n" 5378 " b(); \\\n" 5379 " c(); \\\n" 5380 " d(); \\\n" 5381 " e(); \\\n" 5382 " f(); \\\n" 5383 " }\n" 5384 "#endif", 5385 Style); 5386 // Keep comments aligned with indented directives. These 5387 // tests cannot use verifyFormat because messUp manipulates leading 5388 // whitespace. 5389 { 5390 const char *Expected = "void f() {\n" 5391 "// Aligned to preprocessor.\n" 5392 "#if 1\n" 5393 " // Aligned to code.\n" 5394 " int a;\n" 5395 " #if 1\n" 5396 " // Aligned to preprocessor.\n" 5397 " #define A 0\n" 5398 " // Aligned to code.\n" 5399 " int b;\n" 5400 " #endif\n" 5401 "#endif\n" 5402 "}"; 5403 const char *ToFormat = "void f() {\n" 5404 "// Aligned to preprocessor.\n" 5405 "#if 1\n" 5406 "// Aligned to code.\n" 5407 "int a;\n" 5408 "#if 1\n" 5409 "// Aligned to preprocessor.\n" 5410 "#define A 0\n" 5411 "// Aligned to code.\n" 5412 "int b;\n" 5413 "#endif\n" 5414 "#endif\n" 5415 "}"; 5416 EXPECT_EQ(Expected, format(ToFormat, Style)); 5417 EXPECT_EQ(Expected, format(Expected, Style)); 5418 } 5419 { 5420 const char *Expected = "void f() {\n" 5421 "/* Aligned to preprocessor. */\n" 5422 "#if 1\n" 5423 " /* Aligned to code. */\n" 5424 " int a;\n" 5425 " #if 1\n" 5426 " /* Aligned to preprocessor. */\n" 5427 " #define A 0\n" 5428 " /* Aligned to code. */\n" 5429 " int b;\n" 5430 " #endif\n" 5431 "#endif\n" 5432 "}"; 5433 const char *ToFormat = "void f() {\n" 5434 "/* Aligned to preprocessor. */\n" 5435 "#if 1\n" 5436 "/* Aligned to code. */\n" 5437 "int a;\n" 5438 "#if 1\n" 5439 "/* Aligned to preprocessor. */\n" 5440 "#define A 0\n" 5441 "/* Aligned to code. */\n" 5442 "int b;\n" 5443 "#endif\n" 5444 "#endif\n" 5445 "}"; 5446 EXPECT_EQ(Expected, format(ToFormat, Style)); 5447 EXPECT_EQ(Expected, format(Expected, Style)); 5448 } 5449 5450 // Test single comment before preprocessor 5451 verifyFormat("// Comment\n" 5452 "\n" 5453 "#if 1\n" 5454 "#endif", 5455 Style); 5456 } 5457 5458 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) { 5459 verifyFormat("{\n { a #c; }\n}"); 5460 } 5461 5462 TEST_F(FormatTest, FormatUnbalancedStructuralElements) { 5463 EXPECT_EQ("#define A \\\n { \\\n {\nint i;", 5464 format("#define A { {\nint i;", getLLVMStyleWithColumns(11))); 5465 EXPECT_EQ("#define A \\\n } \\\n }\nint i;", 5466 format("#define A } }\nint i;", getLLVMStyleWithColumns(11))); 5467 } 5468 5469 TEST_F(FormatTest, EscapedNewlines) { 5470 FormatStyle Narrow = getLLVMStyleWithColumns(11); 5471 EXPECT_EQ("#define A \\\n int i; \\\n int j;", 5472 format("#define A \\\nint i;\\\n int j;", Narrow)); 5473 EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;")); 5474 EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();")); 5475 EXPECT_EQ("/* \\ \\ \\\n */", format("\\\n/* \\ \\ \\\n */")); 5476 EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>")); 5477 5478 FormatStyle AlignLeft = getLLVMStyle(); 5479 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left; 5480 EXPECT_EQ("#define MACRO(x) \\\n" 5481 "private: \\\n" 5482 " int x(int a);\n", 5483 format("#define MACRO(x) \\\n" 5484 "private: \\\n" 5485 " int x(int a);\n", 5486 AlignLeft)); 5487 5488 // CRLF line endings 5489 EXPECT_EQ("#define A \\\r\n int i; \\\r\n int j;", 5490 format("#define A \\\r\nint i;\\\r\n int j;", Narrow)); 5491 EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;")); 5492 EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();")); 5493 EXPECT_EQ("/* \\ \\ \\\r\n */", format("\\\r\n/* \\ \\ \\\r\n */")); 5494 EXPECT_EQ("<a\r\n\\\\\r\n>", format("<a\r\n\\\\\r\n>")); 5495 EXPECT_EQ("#define MACRO(x) \\\r\n" 5496 "private: \\\r\n" 5497 " int x(int a);\r\n", 5498 format("#define MACRO(x) \\\r\n" 5499 "private: \\\r\n" 5500 " int x(int a);\r\n", 5501 AlignLeft)); 5502 5503 FormatStyle DontAlign = getLLVMStyle(); 5504 DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 5505 DontAlign.MaxEmptyLinesToKeep = 3; 5506 // FIXME: can't use verifyFormat here because the newline before 5507 // "public:" is not inserted the first time it's reformatted 5508 EXPECT_EQ("#define A \\\n" 5509 " class Foo { \\\n" 5510 " void bar(); \\\n" 5511 "\\\n" 5512 "\\\n" 5513 "\\\n" 5514 " public: \\\n" 5515 " void baz(); \\\n" 5516 " };", 5517 format("#define A \\\n" 5518 " class Foo { \\\n" 5519 " void bar(); \\\n" 5520 "\\\n" 5521 "\\\n" 5522 "\\\n" 5523 " public: \\\n" 5524 " void baz(); \\\n" 5525 " };", 5526 DontAlign)); 5527 } 5528 5529 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) { 5530 verifyFormat("#define A \\\n" 5531 " int v( \\\n" 5532 " a); \\\n" 5533 " int i;", 5534 getLLVMStyleWithColumns(11)); 5535 } 5536 5537 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) { 5538 EXPECT_EQ( 5539 "#define ALooooooooooooooooooooooooooooooooooooooongMacro(" 5540 " \\\n" 5541 " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n" 5542 "\n" 5543 "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n" 5544 " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n", 5545 format(" #define ALooooooooooooooooooooooooooooooooooooooongMacro(" 5546 "\\\n" 5547 "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n" 5548 " \n" 5549 " AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n" 5550 " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n")); 5551 } 5552 5553 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) { 5554 EXPECT_EQ("int\n" 5555 "#define A\n" 5556 " a;", 5557 format("int\n#define A\na;")); 5558 verifyFormat("functionCallTo(\n" 5559 " someOtherFunction(\n" 5560 " withSomeParameters, whichInSequence,\n" 5561 " areLongerThanALine(andAnotherCall,\n" 5562 "#define A B\n" 5563 " withMoreParamters,\n" 5564 " whichStronglyInfluenceTheLayout),\n" 5565 " andMoreParameters),\n" 5566 " trailing);", 5567 getLLVMStyleWithColumns(69)); 5568 verifyFormat("Foo::Foo()\n" 5569 "#ifdef BAR\n" 5570 " : baz(0)\n" 5571 "#endif\n" 5572 "{\n" 5573 "}"); 5574 verifyFormat("void f() {\n" 5575 " if (true)\n" 5576 "#ifdef A\n" 5577 " f(42);\n" 5578 " x();\n" 5579 "#else\n" 5580 " g();\n" 5581 " x();\n" 5582 "#endif\n" 5583 "}"); 5584 verifyFormat("void f(param1, param2,\n" 5585 " param3,\n" 5586 "#ifdef A\n" 5587 " param4(param5,\n" 5588 "#ifdef A1\n" 5589 " param6,\n" 5590 "#ifdef A2\n" 5591 " param7),\n" 5592 "#else\n" 5593 " param8),\n" 5594 " param9,\n" 5595 "#endif\n" 5596 " param10,\n" 5597 "#endif\n" 5598 " param11)\n" 5599 "#else\n" 5600 " param12)\n" 5601 "#endif\n" 5602 "{\n" 5603 " x();\n" 5604 "}", 5605 getLLVMStyleWithColumns(28)); 5606 verifyFormat("#if 1\n" 5607 "int i;"); 5608 verifyFormat("#if 1\n" 5609 "#endif\n" 5610 "#if 1\n" 5611 "#else\n" 5612 "#endif\n"); 5613 verifyFormat("DEBUG({\n" 5614 " return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5615 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n" 5616 "});\n" 5617 "#if a\n" 5618 "#else\n" 5619 "#endif"); 5620 5621 verifyIncompleteFormat("void f(\n" 5622 "#if A\n" 5623 ");\n" 5624 "#else\n" 5625 "#endif"); 5626 } 5627 5628 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) { 5629 verifyFormat("#endif\n" 5630 "#if B"); 5631 } 5632 5633 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) { 5634 FormatStyle SingleLine = getLLVMStyle(); 5635 SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse; 5636 verifyFormat("#if 0\n" 5637 "#elif 1\n" 5638 "#endif\n" 5639 "void foo() {\n" 5640 " if (test) foo2();\n" 5641 "}", 5642 SingleLine); 5643 } 5644 5645 TEST_F(FormatTest, LayoutBlockInsideParens) { 5646 verifyFormat("functionCall({ int i; });"); 5647 verifyFormat("functionCall({\n" 5648 " int i;\n" 5649 " int j;\n" 5650 "});"); 5651 verifyFormat("functionCall(\n" 5652 " {\n" 5653 " int i;\n" 5654 " int j;\n" 5655 " },\n" 5656 " aaaa, bbbb, cccc);"); 5657 verifyFormat("functionA(functionB({\n" 5658 " int i;\n" 5659 " int j;\n" 5660 " }),\n" 5661 " aaaa, bbbb, cccc);"); 5662 verifyFormat("functionCall(\n" 5663 " {\n" 5664 " int i;\n" 5665 " int j;\n" 5666 " },\n" 5667 " aaaa, bbbb, // comment\n" 5668 " cccc);"); 5669 verifyFormat("functionA(functionB({\n" 5670 " int i;\n" 5671 " int j;\n" 5672 " }),\n" 5673 " aaaa, bbbb, // comment\n" 5674 " cccc);"); 5675 verifyFormat("functionCall(aaaa, bbbb, { int i; });"); 5676 verifyFormat("functionCall(aaaa, bbbb, {\n" 5677 " int i;\n" 5678 " int j;\n" 5679 "});"); 5680 verifyFormat( 5681 "Aaa(\n" // FIXME: There shouldn't be a linebreak here. 5682 " {\n" 5683 " int i; // break\n" 5684 " },\n" 5685 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 5686 " ccccccccccccccccc));"); 5687 verifyFormat("DEBUG({\n" 5688 " if (a)\n" 5689 " f();\n" 5690 "});"); 5691 } 5692 5693 TEST_F(FormatTest, LayoutBlockInsideStatement) { 5694 EXPECT_EQ("SOME_MACRO { int i; }\n" 5695 "int i;", 5696 format(" SOME_MACRO {int i;} int i;")); 5697 } 5698 5699 TEST_F(FormatTest, LayoutNestedBlocks) { 5700 verifyFormat("void AddOsStrings(unsigned bitmask) {\n" 5701 " struct s {\n" 5702 " int i;\n" 5703 " };\n" 5704 " s kBitsToOs[] = {{10}};\n" 5705 " for (int i = 0; i < 10; ++i)\n" 5706 " return;\n" 5707 "}"); 5708 verifyFormat("call(parameter, {\n" 5709 " something();\n" 5710 " // Comment using all columns.\n" 5711 " somethingelse();\n" 5712 "});", 5713 getLLVMStyleWithColumns(40)); 5714 verifyFormat("DEBUG( //\n" 5715 " { f(); }, a);"); 5716 verifyFormat("DEBUG( //\n" 5717 " {\n" 5718 " f(); //\n" 5719 " },\n" 5720 " a);"); 5721 5722 EXPECT_EQ("call(parameter, {\n" 5723 " something();\n" 5724 " // Comment too\n" 5725 " // looooooooooong.\n" 5726 " somethingElse();\n" 5727 "});", 5728 format("call(parameter, {\n" 5729 " something();\n" 5730 " // Comment too looooooooooong.\n" 5731 " somethingElse();\n" 5732 "});", 5733 getLLVMStyleWithColumns(29))); 5734 EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int i; });")); 5735 EXPECT_EQ("DEBUG({ // comment\n" 5736 " int i;\n" 5737 "});", 5738 format("DEBUG({ // comment\n" 5739 "int i;\n" 5740 "});")); 5741 EXPECT_EQ("DEBUG({\n" 5742 " int i;\n" 5743 "\n" 5744 " // comment\n" 5745 " int j;\n" 5746 "});", 5747 format("DEBUG({\n" 5748 " int i;\n" 5749 "\n" 5750 " // comment\n" 5751 " int j;\n" 5752 "});")); 5753 5754 verifyFormat("DEBUG({\n" 5755 " if (a)\n" 5756 " return;\n" 5757 "});"); 5758 verifyGoogleFormat("DEBUG({\n" 5759 " if (a) return;\n" 5760 "});"); 5761 FormatStyle Style = getGoogleStyle(); 5762 Style.ColumnLimit = 45; 5763 verifyFormat("Debug(\n" 5764 " aaaaa,\n" 5765 " {\n" 5766 " if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n" 5767 " },\n" 5768 " a);", 5769 Style); 5770 5771 verifyFormat("SomeFunction({MACRO({ return output; }), b});"); 5772 5773 verifyNoCrash("^{v^{a}}"); 5774 } 5775 5776 TEST_F(FormatTest, FormatNestedBlocksInMacros) { 5777 EXPECT_EQ("#define MACRO() \\\n" 5778 " Debug(aaa, /* force line break */ \\\n" 5779 " { \\\n" 5780 " int i; \\\n" 5781 " int j; \\\n" 5782 " })", 5783 format("#define MACRO() Debug(aaa, /* force line break */ \\\n" 5784 " { int i; int j; })", 5785 getGoogleStyle())); 5786 5787 EXPECT_EQ("#define A \\\n" 5788 " [] { \\\n" 5789 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 5790 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n" 5791 " }", 5792 format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 5793 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }", 5794 getGoogleStyle())); 5795 } 5796 5797 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) { 5798 EXPECT_EQ("{}", format("{}")); 5799 verifyFormat("enum E {};"); 5800 verifyFormat("enum E {}"); 5801 FormatStyle Style = getLLVMStyle(); 5802 Style.SpaceInEmptyBlock = true; 5803 EXPECT_EQ("void f() { }", format("void f() {}", Style)); 5804 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 5805 EXPECT_EQ("while (true) { }", format("while (true) {}", Style)); 5806 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 5807 Style.BraceWrapping.BeforeElse = false; 5808 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 5809 verifyFormat("if (a)\n" 5810 "{\n" 5811 "} else if (b)\n" 5812 "{\n" 5813 "} else\n" 5814 "{ }", 5815 Style); 5816 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never; 5817 verifyFormat("if (a) {\n" 5818 "} else if (b) {\n" 5819 "} else {\n" 5820 "}", 5821 Style); 5822 Style.BraceWrapping.BeforeElse = true; 5823 verifyFormat("if (a) { }\n" 5824 "else if (b) { }\n" 5825 "else { }", 5826 Style); 5827 } 5828 5829 TEST_F(FormatTest, FormatBeginBlockEndMacros) { 5830 FormatStyle Style = getLLVMStyle(); 5831 Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$"; 5832 Style.MacroBlockEnd = "^[A-Z_]+_END$"; 5833 verifyFormat("FOO_BEGIN\n" 5834 " FOO_ENTRY\n" 5835 "FOO_END", 5836 Style); 5837 verifyFormat("FOO_BEGIN\n" 5838 " NESTED_FOO_BEGIN\n" 5839 " NESTED_FOO_ENTRY\n" 5840 " NESTED_FOO_END\n" 5841 "FOO_END", 5842 Style); 5843 verifyFormat("FOO_BEGIN(Foo, Bar)\n" 5844 " int x;\n" 5845 " x = 1;\n" 5846 "FOO_END(Baz)", 5847 Style); 5848 } 5849 5850 //===----------------------------------------------------------------------===// 5851 // Line break tests. 5852 //===----------------------------------------------------------------------===// 5853 5854 TEST_F(FormatTest, PreventConfusingIndents) { 5855 verifyFormat( 5856 "void f() {\n" 5857 " SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n" 5858 " parameter, parameter, parameter)),\n" 5859 " SecondLongCall(parameter));\n" 5860 "}"); 5861 verifyFormat( 5862 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5863 " aaaaaaaaaaaaaaaaaaaaaaaa(\n" 5864 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 5865 " aaaaaaaaaaaaaaaaaaaaaaaa);"); 5866 verifyFormat( 5867 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5868 " [aaaaaaaaaaaaaaaaaaaaaaaa\n" 5869 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n" 5870 " [aaaaaaaaaaaaaaaaaaaaaaaa]];"); 5871 verifyFormat( 5872 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 5873 " aaaaaaaaaaaaaaaaaaaaaaaa<\n" 5874 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n" 5875 " aaaaaaaaaaaaaaaaaaaaaaaa>;"); 5876 verifyFormat("int a = bbbb && ccc &&\n" 5877 " fffff(\n" 5878 "#define A Just forcing a new line\n" 5879 " ddd);"); 5880 } 5881 5882 TEST_F(FormatTest, LineBreakingInBinaryExpressions) { 5883 verifyFormat( 5884 "bool aaaaaaa =\n" 5885 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n" 5886 " bbbbbbbb();"); 5887 verifyFormat( 5888 "bool aaaaaaa =\n" 5889 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n" 5890 " bbbbbbbb();"); 5891 5892 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n" 5893 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n" 5894 " ccccccccc == ddddddddddd;"); 5895 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n" 5896 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n" 5897 " ccccccccc == ddddddddddd;"); 5898 verifyFormat( 5899 "bool aaaaaaaaaaaaaaaaaaaaa =\n" 5900 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n" 5901 " ccccccccc == ddddddddddd;"); 5902 5903 verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n" 5904 " aaaaaa) &&\n" 5905 " bbbbbb && cccccc;"); 5906 verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n" 5907 " aaaaaa) >>\n" 5908 " bbbbbb;"); 5909 verifyFormat("aa = Whitespaces.addUntouchableComment(\n" 5910 " SourceMgr.getSpellingColumnNumber(\n" 5911 " TheLine.Last->FormatTok.Tok.getLocation()) -\n" 5912 " 1);"); 5913 5914 verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 5915 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n" 5916 " cccccc) {\n}"); 5917 verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 5918 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n" 5919 " cccccc) {\n}"); 5920 verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 5921 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n" 5922 " cccccc) {\n}"); 5923 verifyFormat("b = a &&\n" 5924 " // Comment\n" 5925 " b.c && d;"); 5926 5927 // If the LHS of a comparison is not a binary expression itself, the 5928 // additional linebreak confuses many people. 5929 verifyFormat( 5930 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5931 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n" 5932 "}"); 5933 verifyFormat( 5934 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5935 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 5936 "}"); 5937 verifyFormat( 5938 "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n" 5939 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 5940 "}"); 5941 verifyFormat( 5942 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5943 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n" 5944 "}"); 5945 // Even explicit parentheses stress the precedence enough to make the 5946 // additional break unnecessary. 5947 verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5948 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 5949 "}"); 5950 // This cases is borderline, but with the indentation it is still readable. 5951 verifyFormat( 5952 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5953 " aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5954 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 5955 "}", 5956 getLLVMStyleWithColumns(75)); 5957 5958 // If the LHS is a binary expression, we should still use the additional break 5959 // as otherwise the formatting hides the operator precedence. 5960 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5961 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 5962 " 5) {\n" 5963 "}"); 5964 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5965 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n" 5966 " 5) {\n" 5967 "}"); 5968 5969 FormatStyle OnePerLine = getLLVMStyle(); 5970 OnePerLine.BinPackParameters = false; 5971 verifyFormat( 5972 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 5973 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 5974 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}", 5975 OnePerLine); 5976 5977 verifyFormat("int i = someFunction(aaaaaaa, 0)\n" 5978 " .aaa(aaaaaaaaaaaaa) *\n" 5979 " aaaaaaa +\n" 5980 " aaaaaaa;", 5981 getLLVMStyleWithColumns(40)); 5982 } 5983 5984 TEST_F(FormatTest, ExpressionIndentation) { 5985 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5986 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5987 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 5988 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 5989 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n" 5990 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n" 5991 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 5992 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n" 5993 " ccccccccccccccccccccccccccccccccccccccccc;"); 5994 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 5995 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5996 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 5997 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 5998 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5999 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6000 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6001 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 6002 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6003 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6004 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6005 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 6006 verifyFormat("if () {\n" 6007 "} else if (aaaaa && bbbbb > // break\n" 6008 " ccccc) {\n" 6009 "}"); 6010 verifyFormat("if () {\n" 6011 "} else if constexpr (aaaaa && bbbbb > // break\n" 6012 " ccccc) {\n" 6013 "}"); 6014 verifyFormat("if () {\n" 6015 "} else if CONSTEXPR (aaaaa && bbbbb > // break\n" 6016 " ccccc) {\n" 6017 "}"); 6018 verifyFormat("if () {\n" 6019 "} else if (aaaaa &&\n" 6020 " bbbbb > // break\n" 6021 " ccccc &&\n" 6022 " ddddd) {\n" 6023 "}"); 6024 6025 // Presence of a trailing comment used to change indentation of b. 6026 verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n" 6027 " b;\n" 6028 "return aaaaaaaaaaaaaaaaaaa +\n" 6029 " b; //", 6030 getLLVMStyleWithColumns(30)); 6031 } 6032 6033 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) { 6034 // Not sure what the best system is here. Like this, the LHS can be found 6035 // immediately above an operator (everything with the same or a higher 6036 // indent). The RHS is aligned right of the operator and so compasses 6037 // everything until something with the same indent as the operator is found. 6038 // FIXME: Is this a good system? 6039 FormatStyle Style = getLLVMStyle(); 6040 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 6041 verifyFormat( 6042 "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6043 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6044 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6045 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6046 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6047 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6048 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6049 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6050 " > ccccccccccccccccccccccccccccccccccccccccc;", 6051 Style); 6052 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6053 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6054 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6055 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6056 Style); 6057 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6058 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6059 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6060 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6061 Style); 6062 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6063 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6064 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6065 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6066 Style); 6067 verifyFormat("if () {\n" 6068 "} else if (aaaaa\n" 6069 " && bbbbb // break\n" 6070 " > ccccc) {\n" 6071 "}", 6072 Style); 6073 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6074 " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6075 Style); 6076 verifyFormat("return (a)\n" 6077 " // comment\n" 6078 " + b;", 6079 Style); 6080 verifyFormat( 6081 "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6082 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6083 " + cc;", 6084 Style); 6085 6086 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6087 " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 6088 Style); 6089 6090 // Forced by comments. 6091 verifyFormat( 6092 "unsigned ContentSize =\n" 6093 " sizeof(int16_t) // DWARF ARange version number\n" 6094 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6095 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6096 " + sizeof(int8_t); // Segment Size (in bytes)"); 6097 6098 verifyFormat("return boost::fusion::at_c<0>(iiii).second\n" 6099 " == boost::fusion::at_c<1>(iiii).second;", 6100 Style); 6101 6102 Style.ColumnLimit = 60; 6103 verifyFormat("zzzzzzzzzz\n" 6104 " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6105 " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);", 6106 Style); 6107 6108 Style.ColumnLimit = 80; 6109 Style.IndentWidth = 4; 6110 Style.TabWidth = 4; 6111 Style.UseTab = FormatStyle::UT_Always; 6112 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6113 Style.AlignOperands = FormatStyle::OAS_DontAlign; 6114 EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n" 6115 "\t&& (someOtherLongishConditionPart1\n" 6116 "\t\t|| someOtherEvenLongerNestedConditionPart2);", 6117 format("return someVeryVeryLongConditionThatBarelyFitsOnALine && " 6118 "(someOtherLongishConditionPart1 || " 6119 "someOtherEvenLongerNestedConditionPart2);", 6120 Style)); 6121 } 6122 6123 TEST_F(FormatTest, ExpressionIndentationStrictAlign) { 6124 FormatStyle Style = getLLVMStyle(); 6125 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 6126 Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator; 6127 6128 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6129 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6130 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6131 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6132 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6133 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6134 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6135 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6136 " > ccccccccccccccccccccccccccccccccccccccccc;", 6137 Style); 6138 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6139 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6140 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6141 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6142 Style); 6143 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6144 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6145 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6146 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6147 Style); 6148 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6149 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6150 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6151 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6152 Style); 6153 verifyFormat("if () {\n" 6154 "} else if (aaaaa\n" 6155 " && bbbbb // break\n" 6156 " > ccccc) {\n" 6157 "}", 6158 Style); 6159 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6160 " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6161 Style); 6162 verifyFormat("return (a)\n" 6163 " // comment\n" 6164 " + b;", 6165 Style); 6166 verifyFormat( 6167 "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6168 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6169 " + cc;", 6170 Style); 6171 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 6172 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 6173 " : 3333333333333333;", 6174 Style); 6175 verifyFormat( 6176 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 6177 " : ccccccccccccccc ? dddddddddddddddddd\n" 6178 " : eeeeeeeeeeeeeeeeee)\n" 6179 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 6180 " : 3333333333333333;", 6181 Style); 6182 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6183 " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 6184 Style); 6185 6186 verifyFormat("return boost::fusion::at_c<0>(iiii).second\n" 6187 " == boost::fusion::at_c<1>(iiii).second;", 6188 Style); 6189 6190 Style.ColumnLimit = 60; 6191 verifyFormat("zzzzzzzzzzzzz\n" 6192 " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6193 " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);", 6194 Style); 6195 6196 // Forced by comments. 6197 Style.ColumnLimit = 80; 6198 verifyFormat( 6199 "unsigned ContentSize\n" 6200 " = sizeof(int16_t) // DWARF ARange version number\n" 6201 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6202 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6203 " + sizeof(int8_t); // Segment Size (in bytes)", 6204 Style); 6205 6206 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6207 verifyFormat( 6208 "unsigned ContentSize =\n" 6209 " sizeof(int16_t) // DWARF ARange version number\n" 6210 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6211 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6212 " + sizeof(int8_t); // Segment Size (in bytes)", 6213 Style); 6214 6215 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 6216 verifyFormat( 6217 "unsigned ContentSize =\n" 6218 " sizeof(int16_t) // DWARF ARange version number\n" 6219 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6220 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6221 " + sizeof(int8_t); // Segment Size (in bytes)", 6222 Style); 6223 } 6224 6225 TEST_F(FormatTest, EnforcedOperatorWraps) { 6226 // Here we'd like to wrap after the || operators, but a comment is forcing an 6227 // earlier wrap. 6228 verifyFormat("bool x = aaaaa //\n" 6229 " || bbbbb\n" 6230 " //\n" 6231 " || cccc;"); 6232 } 6233 6234 TEST_F(FormatTest, NoOperandAlignment) { 6235 FormatStyle Style = getLLVMStyle(); 6236 Style.AlignOperands = FormatStyle::OAS_DontAlign; 6237 verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n" 6238 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6239 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 6240 Style); 6241 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6242 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6243 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6244 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6245 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6246 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6247 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6248 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6249 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6250 " > ccccccccccccccccccccccccccccccccccccccccc;", 6251 Style); 6252 6253 verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6254 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6255 " + cc;", 6256 Style); 6257 verifyFormat("int a = aa\n" 6258 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6259 " * cccccccccccccccccccccccccccccccccccc;\n", 6260 Style); 6261 6262 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6263 verifyFormat("return (a > b\n" 6264 " // comment1\n" 6265 " // comment2\n" 6266 " || c);", 6267 Style); 6268 } 6269 6270 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) { 6271 FormatStyle Style = getLLVMStyle(); 6272 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6273 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 6274 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6275 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6276 Style); 6277 } 6278 6279 TEST_F(FormatTest, AllowBinPackingInsideArguments) { 6280 FormatStyle Style = getLLVMStyleWithColumns(40); 6281 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6282 Style.BinPackArguments = false; 6283 verifyFormat("void test() {\n" 6284 " someFunction(\n" 6285 " this + argument + is + quite\n" 6286 " + long + so + it + gets + wrapped\n" 6287 " + but + remains + bin - packed);\n" 6288 "}", 6289 Style); 6290 verifyFormat("void test() {\n" 6291 " someFunction(arg1,\n" 6292 " this + argument + is\n" 6293 " + quite + long + so\n" 6294 " + it + gets + wrapped\n" 6295 " + but + remains + bin\n" 6296 " - packed,\n" 6297 " arg3);\n" 6298 "}", 6299 Style); 6300 verifyFormat("void test() {\n" 6301 " someFunction(\n" 6302 " arg1,\n" 6303 " this + argument + has\n" 6304 " + anotherFunc(nested,\n" 6305 " calls + whose\n" 6306 " + arguments\n" 6307 " + are + also\n" 6308 " + wrapped,\n" 6309 " in + addition)\n" 6310 " + to + being + bin - packed,\n" 6311 " arg3);\n" 6312 "}", 6313 Style); 6314 6315 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 6316 verifyFormat("void test() {\n" 6317 " someFunction(\n" 6318 " arg1,\n" 6319 " this + argument + has +\n" 6320 " anotherFunc(nested,\n" 6321 " calls + whose +\n" 6322 " arguments +\n" 6323 " are + also +\n" 6324 " wrapped,\n" 6325 " in + addition) +\n" 6326 " to + being + bin - packed,\n" 6327 " arg3);\n" 6328 "}", 6329 Style); 6330 } 6331 6332 TEST_F(FormatTest, ConstructorInitializers) { 6333 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}"); 6334 verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}", 6335 getLLVMStyleWithColumns(45)); 6336 verifyFormat("Constructor()\n" 6337 " : Inttializer(FitsOnTheLine) {}", 6338 getLLVMStyleWithColumns(44)); 6339 verifyFormat("Constructor()\n" 6340 " : Inttializer(FitsOnTheLine) {}", 6341 getLLVMStyleWithColumns(43)); 6342 6343 verifyFormat("template <typename T>\n" 6344 "Constructor() : Initializer(FitsOnTheLine) {}", 6345 getLLVMStyleWithColumns(45)); 6346 6347 verifyFormat( 6348 "SomeClass::Constructor()\n" 6349 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}"); 6350 6351 verifyFormat( 6352 "SomeClass::Constructor()\n" 6353 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6354 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}"); 6355 verifyFormat( 6356 "SomeClass::Constructor()\n" 6357 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6358 " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}"); 6359 verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6360 " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 6361 " : aaaaaaaaaa(aaaaaa) {}"); 6362 6363 verifyFormat("Constructor()\n" 6364 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6365 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6366 " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6367 " aaaaaaaaaaaaaaaaaaaaaaa() {}"); 6368 6369 verifyFormat("Constructor()\n" 6370 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6371 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 6372 6373 verifyFormat("Constructor(int Parameter = 0)\n" 6374 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n" 6375 " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}"); 6376 verifyFormat("Constructor()\n" 6377 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n" 6378 "}", 6379 getLLVMStyleWithColumns(60)); 6380 verifyFormat("Constructor()\n" 6381 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6382 " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}"); 6383 6384 // Here a line could be saved by splitting the second initializer onto two 6385 // lines, but that is not desirable. 6386 verifyFormat("Constructor()\n" 6387 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n" 6388 " aaaaaaaaaaa(aaaaaaaaaaa),\n" 6389 " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 6390 6391 FormatStyle OnePerLine = getLLVMStyle(); 6392 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_Never; 6393 verifyFormat("MyClass::MyClass()\n" 6394 " : a(a),\n" 6395 " b(b),\n" 6396 " c(c) {}", 6397 OnePerLine); 6398 verifyFormat("MyClass::MyClass()\n" 6399 " : a(a), // comment\n" 6400 " b(b),\n" 6401 " c(c) {}", 6402 OnePerLine); 6403 verifyFormat("MyClass::MyClass(int a)\n" 6404 " : b(a), // comment\n" 6405 " c(a + 1) { // lined up\n" 6406 "}", 6407 OnePerLine); 6408 verifyFormat("Constructor()\n" 6409 " : a(b, b, b) {}", 6410 OnePerLine); 6411 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6412 OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false; 6413 verifyFormat("SomeClass::Constructor()\n" 6414 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6415 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6416 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6417 OnePerLine); 6418 verifyFormat("SomeClass::Constructor()\n" 6419 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n" 6420 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6421 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6422 OnePerLine); 6423 verifyFormat("MyClass::MyClass(int var)\n" 6424 " : some_var_(var), // 4 space indent\n" 6425 " some_other_var_(var + 1) { // lined up\n" 6426 "}", 6427 OnePerLine); 6428 verifyFormat("Constructor()\n" 6429 " : aaaaa(aaaaaa),\n" 6430 " aaaaa(aaaaaa),\n" 6431 " aaaaa(aaaaaa),\n" 6432 " aaaaa(aaaaaa),\n" 6433 " aaaaa(aaaaaa) {}", 6434 OnePerLine); 6435 verifyFormat("Constructor()\n" 6436 " : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n" 6437 " aaaaaaaaaaaaaaaaaaaaaa) {}", 6438 OnePerLine); 6439 OnePerLine.BinPackParameters = false; 6440 verifyFormat( 6441 "Constructor()\n" 6442 " : aaaaaaaaaaaaaaaaaaaaaaaa(\n" 6443 " aaaaaaaaaaa().aaa(),\n" 6444 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6445 OnePerLine); 6446 OnePerLine.ColumnLimit = 60; 6447 verifyFormat("Constructor()\n" 6448 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6449 " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}", 6450 OnePerLine); 6451 6452 EXPECT_EQ("Constructor()\n" 6453 " : // Comment forcing unwanted break.\n" 6454 " aaaa(aaaa) {}", 6455 format("Constructor() :\n" 6456 " // Comment forcing unwanted break.\n" 6457 " aaaa(aaaa) {}")); 6458 } 6459 6460 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) { 6461 FormatStyle Style = getLLVMStyleWithColumns(60); 6462 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6463 Style.BinPackParameters = false; 6464 6465 for (int i = 0; i < 4; ++i) { 6466 // Test all combinations of parameters that should not have an effect. 6467 Style.AllowAllParametersOfDeclarationOnNextLine = i & 1; 6468 Style.AllowAllArgumentsOnNextLine = i & 2; 6469 6470 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6471 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6472 verifyFormat("Constructor()\n" 6473 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6474 Style); 6475 verifyFormat("Constructor() : a(a), b(b) {}", Style); 6476 6477 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6478 verifyFormat("Constructor()\n" 6479 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6480 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6481 Style); 6482 verifyFormat("Constructor() : a(a), b(b) {}", Style); 6483 6484 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 6485 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6486 verifyFormat("Constructor()\n" 6487 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6488 Style); 6489 6490 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6491 verifyFormat("Constructor()\n" 6492 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6493 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6494 Style); 6495 6496 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6497 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6498 verifyFormat("Constructor() :\n" 6499 " aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6500 Style); 6501 6502 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6503 verifyFormat("Constructor() :\n" 6504 " aaaaaaaaaaaaaaaaaa(a),\n" 6505 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6506 Style); 6507 } 6508 6509 // Test interactions between AllowAllParametersOfDeclarationOnNextLine and 6510 // AllowAllConstructorInitializersOnNextLine in all 6511 // BreakConstructorInitializers modes 6512 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6513 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6514 verifyFormat("SomeClassWithALongName::Constructor(\n" 6515 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n" 6516 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6517 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6518 Style); 6519 6520 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6521 verifyFormat("SomeClassWithALongName::Constructor(\n" 6522 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6523 " int bbbbbbbbbbbbb,\n" 6524 " int cccccccccccccccc)\n" 6525 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6526 Style); 6527 6528 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6529 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6530 verifyFormat("SomeClassWithALongName::Constructor(\n" 6531 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6532 " int bbbbbbbbbbbbb)\n" 6533 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6534 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6535 Style); 6536 6537 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 6538 6539 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6540 verifyFormat("SomeClassWithALongName::Constructor(\n" 6541 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n" 6542 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6543 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6544 Style); 6545 6546 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6547 verifyFormat("SomeClassWithALongName::Constructor(\n" 6548 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6549 " int bbbbbbbbbbbbb,\n" 6550 " int cccccccccccccccc)\n" 6551 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6552 Style); 6553 6554 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6555 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6556 verifyFormat("SomeClassWithALongName::Constructor(\n" 6557 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6558 " int bbbbbbbbbbbbb)\n" 6559 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6560 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6561 Style); 6562 6563 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6564 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6565 verifyFormat("SomeClassWithALongName::Constructor(\n" 6566 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n" 6567 " aaaaaaaaaaaaaaaaaaaa(a),\n" 6568 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6569 Style); 6570 6571 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6572 verifyFormat("SomeClassWithALongName::Constructor(\n" 6573 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6574 " int bbbbbbbbbbbbb,\n" 6575 " int cccccccccccccccc) :\n" 6576 " aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6577 Style); 6578 6579 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6580 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6581 verifyFormat("SomeClassWithALongName::Constructor(\n" 6582 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6583 " int bbbbbbbbbbbbb) :\n" 6584 " aaaaaaaaaaaaaaaaaaaa(a),\n" 6585 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6586 Style); 6587 } 6588 6589 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) { 6590 FormatStyle Style = getLLVMStyleWithColumns(60); 6591 Style.BinPackArguments = false; 6592 for (int i = 0; i < 4; ++i) { 6593 // Test all combinations of parameters that should not have an effect. 6594 Style.AllowAllParametersOfDeclarationOnNextLine = i & 1; 6595 Style.PackConstructorInitializers = 6596 i & 2 ? FormatStyle::PCIS_BinPack : FormatStyle::PCIS_Never; 6597 6598 Style.AllowAllArgumentsOnNextLine = true; 6599 verifyFormat("void foo() {\n" 6600 " FunctionCallWithReallyLongName(\n" 6601 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n" 6602 "}", 6603 Style); 6604 Style.AllowAllArgumentsOnNextLine = false; 6605 verifyFormat("void foo() {\n" 6606 " FunctionCallWithReallyLongName(\n" 6607 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6608 " bbbbbbbbbbbb);\n" 6609 "}", 6610 Style); 6611 6612 Style.AllowAllArgumentsOnNextLine = true; 6613 verifyFormat("void foo() {\n" 6614 " auto VariableWithReallyLongName = {\n" 6615 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n" 6616 "}", 6617 Style); 6618 Style.AllowAllArgumentsOnNextLine = false; 6619 verifyFormat("void foo() {\n" 6620 " auto VariableWithReallyLongName = {\n" 6621 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6622 " bbbbbbbbbbbb};\n" 6623 "}", 6624 Style); 6625 } 6626 6627 // This parameter should not affect declarations. 6628 Style.BinPackParameters = false; 6629 Style.AllowAllArgumentsOnNextLine = false; 6630 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6631 verifyFormat("void FunctionCallWithReallyLongName(\n" 6632 " int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);", 6633 Style); 6634 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6635 verifyFormat("void FunctionCallWithReallyLongName(\n" 6636 " int aaaaaaaaaaaaaaaaaaaaaaa,\n" 6637 " int bbbbbbbbbbbb);", 6638 Style); 6639 } 6640 6641 TEST_F(FormatTest, AllowAllArgumentsOnNextLineDontAlign) { 6642 // Check that AllowAllArgumentsOnNextLine is respected for both BAS_DontAlign 6643 // and BAS_Align. 6644 FormatStyle Style = getLLVMStyleWithColumns(35); 6645 StringRef Input = "functionCall(paramA, paramB, paramC);\n" 6646 "void functionDecl(int A, int B, int C);"; 6647 Style.AllowAllArgumentsOnNextLine = false; 6648 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6649 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6650 " paramC);\n" 6651 "void functionDecl(int A, int B,\n" 6652 " int C);"), 6653 format(Input, Style)); 6654 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 6655 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6656 " paramC);\n" 6657 "void functionDecl(int A, int B,\n" 6658 " int C);"), 6659 format(Input, Style)); 6660 // However, BAS_AlwaysBreak should take precedence over 6661 // AllowAllArgumentsOnNextLine. 6662 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 6663 EXPECT_EQ(StringRef("functionCall(\n" 6664 " paramA, paramB, paramC);\n" 6665 "void functionDecl(\n" 6666 " int A, int B, int C);"), 6667 format(Input, Style)); 6668 6669 // When AllowAllArgumentsOnNextLine is set, we prefer breaking before the 6670 // first argument. 6671 Style.AllowAllArgumentsOnNextLine = true; 6672 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 6673 EXPECT_EQ(StringRef("functionCall(\n" 6674 " paramA, paramB, paramC);\n" 6675 "void functionDecl(\n" 6676 " int A, int B, int C);"), 6677 format(Input, Style)); 6678 // It wouldn't fit on one line with aligned parameters so this setting 6679 // doesn't change anything for BAS_Align. 6680 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 6681 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6682 " paramC);\n" 6683 "void functionDecl(int A, int B,\n" 6684 " int C);"), 6685 format(Input, Style)); 6686 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6687 EXPECT_EQ(StringRef("functionCall(\n" 6688 " paramA, paramB, paramC);\n" 6689 "void functionDecl(\n" 6690 " int A, int B, int C);"), 6691 format(Input, Style)); 6692 } 6693 6694 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) { 6695 FormatStyle Style = getLLVMStyle(); 6696 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6697 6698 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}"); 6699 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}", 6700 getStyleWithColumns(Style, 45)); 6701 verifyFormat("Constructor() :\n" 6702 " Initializer(FitsOnTheLine) {}", 6703 getStyleWithColumns(Style, 44)); 6704 verifyFormat("Constructor() :\n" 6705 " Initializer(FitsOnTheLine) {}", 6706 getStyleWithColumns(Style, 43)); 6707 6708 verifyFormat("template <typename T>\n" 6709 "Constructor() : Initializer(FitsOnTheLine) {}", 6710 getStyleWithColumns(Style, 50)); 6711 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6712 verifyFormat( 6713 "SomeClass::Constructor() :\n" 6714 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 6715 Style); 6716 6717 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 6718 verifyFormat( 6719 "SomeClass::Constructor() :\n" 6720 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 6721 Style); 6722 6723 verifyFormat( 6724 "SomeClass::Constructor() :\n" 6725 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6726 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6727 Style); 6728 verifyFormat( 6729 "SomeClass::Constructor() :\n" 6730 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6731 " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 6732 Style); 6733 verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6734 " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 6735 " aaaaaaaaaa(aaaaaa) {}", 6736 Style); 6737 6738 verifyFormat("Constructor() :\n" 6739 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6740 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6741 " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6742 " aaaaaaaaaaaaaaaaaaaaaaa() {}", 6743 Style); 6744 6745 verifyFormat("Constructor() :\n" 6746 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6747 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6748 Style); 6749 6750 verifyFormat("Constructor(int Parameter = 0) :\n" 6751 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n" 6752 " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}", 6753 Style); 6754 verifyFormat("Constructor() :\n" 6755 " aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n" 6756 "}", 6757 getStyleWithColumns(Style, 60)); 6758 verifyFormat("Constructor() :\n" 6759 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6760 " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}", 6761 Style); 6762 6763 // Here a line could be saved by splitting the second initializer onto two 6764 // lines, but that is not desirable. 6765 verifyFormat("Constructor() :\n" 6766 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n" 6767 " aaaaaaaaaaa(aaaaaaaaaaa),\n" 6768 " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6769 Style); 6770 6771 FormatStyle OnePerLine = Style; 6772 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6773 verifyFormat("SomeClass::Constructor() :\n" 6774 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6775 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6776 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6777 OnePerLine); 6778 verifyFormat("SomeClass::Constructor() :\n" 6779 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n" 6780 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6781 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6782 OnePerLine); 6783 verifyFormat("MyClass::MyClass(int var) :\n" 6784 " some_var_(var), // 4 space indent\n" 6785 " some_other_var_(var + 1) { // lined up\n" 6786 "}", 6787 OnePerLine); 6788 verifyFormat("Constructor() :\n" 6789 " aaaaa(aaaaaa),\n" 6790 " aaaaa(aaaaaa),\n" 6791 " aaaaa(aaaaaa),\n" 6792 " aaaaa(aaaaaa),\n" 6793 " aaaaa(aaaaaa) {}", 6794 OnePerLine); 6795 verifyFormat("Constructor() :\n" 6796 " aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n" 6797 " aaaaaaaaaaaaaaaaaaaaaa) {}", 6798 OnePerLine); 6799 OnePerLine.BinPackParameters = false; 6800 verifyFormat("Constructor() :\n" 6801 " aaaaaaaaaaaaaaaaaaaaaaaa(\n" 6802 " aaaaaaaaaaa().aaa(),\n" 6803 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6804 OnePerLine); 6805 OnePerLine.ColumnLimit = 60; 6806 verifyFormat("Constructor() :\n" 6807 " aaaaaaaaaaaaaaaaaaaa(a),\n" 6808 " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}", 6809 OnePerLine); 6810 6811 EXPECT_EQ("Constructor() :\n" 6812 " // Comment forcing unwanted break.\n" 6813 " aaaa(aaaa) {}", 6814 format("Constructor() :\n" 6815 " // Comment forcing unwanted break.\n" 6816 " aaaa(aaaa) {}", 6817 Style)); 6818 6819 Style.ColumnLimit = 0; 6820 verifyFormat("SomeClass::Constructor() :\n" 6821 " a(a) {}", 6822 Style); 6823 verifyFormat("SomeClass::Constructor() noexcept :\n" 6824 " a(a) {}", 6825 Style); 6826 verifyFormat("SomeClass::Constructor() :\n" 6827 " a(a), b(b), c(c) {}", 6828 Style); 6829 verifyFormat("SomeClass::Constructor() :\n" 6830 " a(a) {\n" 6831 " foo();\n" 6832 " bar();\n" 6833 "}", 6834 Style); 6835 6836 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 6837 verifyFormat("SomeClass::Constructor() :\n" 6838 " a(a), b(b), c(c) {\n" 6839 "}", 6840 Style); 6841 verifyFormat("SomeClass::Constructor() :\n" 6842 " a(a) {\n" 6843 "}", 6844 Style); 6845 6846 Style.ColumnLimit = 80; 6847 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 6848 Style.ConstructorInitializerIndentWidth = 2; 6849 verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style); 6850 verifyFormat("SomeClass::Constructor() :\n" 6851 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6852 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}", 6853 Style); 6854 6855 // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as 6856 // well 6857 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 6858 verifyFormat( 6859 "class SomeClass\n" 6860 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6861 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 6862 Style); 6863 Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma; 6864 verifyFormat( 6865 "class SomeClass\n" 6866 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6867 " , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 6868 Style); 6869 Style.BreakInheritanceList = FormatStyle::BILS_AfterColon; 6870 verifyFormat( 6871 "class SomeClass :\n" 6872 " public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6873 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 6874 Style); 6875 Style.BreakInheritanceList = FormatStyle::BILS_AfterComma; 6876 verifyFormat( 6877 "class SomeClass\n" 6878 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6879 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 6880 Style); 6881 } 6882 6883 #ifndef EXPENSIVE_CHECKS 6884 // Expensive checks enables libstdc++ checking which includes validating the 6885 // state of ranges used in std::priority_queue - this blows out the 6886 // runtime/scalability of the function and makes this test unacceptably slow. 6887 TEST_F(FormatTest, MemoizationTests) { 6888 // This breaks if the memoization lookup does not take \c Indent and 6889 // \c LastSpace into account. 6890 verifyFormat( 6891 "extern CFRunLoopTimerRef\n" 6892 "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n" 6893 " CFTimeInterval interval, CFOptionFlags flags,\n" 6894 " CFIndex order, CFRunLoopTimerCallBack callout,\n" 6895 " CFRunLoopTimerContext *context) {}"); 6896 6897 // Deep nesting somewhat works around our memoization. 6898 verifyFormat( 6899 "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 6900 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 6901 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 6902 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 6903 " aaaaa())))))))))))))))))))))))))))))))))))))));", 6904 getLLVMStyleWithColumns(65)); 6905 verifyFormat( 6906 "aaaaa(\n" 6907 " aaaaa,\n" 6908 " aaaaa(\n" 6909 " aaaaa,\n" 6910 " aaaaa(\n" 6911 " aaaaa,\n" 6912 " aaaaa(\n" 6913 " aaaaa,\n" 6914 " aaaaa(\n" 6915 " aaaaa,\n" 6916 " aaaaa(\n" 6917 " aaaaa,\n" 6918 " aaaaa(\n" 6919 " aaaaa,\n" 6920 " aaaaa(\n" 6921 " aaaaa,\n" 6922 " aaaaa(\n" 6923 " aaaaa,\n" 6924 " aaaaa(\n" 6925 " aaaaa,\n" 6926 " aaaaa(\n" 6927 " aaaaa,\n" 6928 " aaaaa(\n" 6929 " aaaaa,\n" 6930 " aaaaa))))))))))));", 6931 getLLVMStyleWithColumns(65)); 6932 verifyFormat( 6933 "a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(), a), a), a), a),\n" 6934 " a),\n" 6935 " a),\n" 6936 " a),\n" 6937 " a),\n" 6938 " a),\n" 6939 " a),\n" 6940 " a),\n" 6941 " a),\n" 6942 " a),\n" 6943 " a),\n" 6944 " a),\n" 6945 " a),\n" 6946 " a),\n" 6947 " a),\n" 6948 " a),\n" 6949 " a),\n" 6950 " a)", 6951 getLLVMStyleWithColumns(65)); 6952 6953 // This test takes VERY long when memoization is broken. 6954 FormatStyle OnePerLine = getLLVMStyle(); 6955 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6956 OnePerLine.BinPackParameters = false; 6957 std::string input = "Constructor()\n" 6958 " : aaaa(a,\n"; 6959 for (unsigned i = 0, e = 80; i != e; ++i) { 6960 input += " a,\n"; 6961 } 6962 input += " a) {}"; 6963 verifyFormat(input, OnePerLine); 6964 } 6965 #endif 6966 6967 TEST_F(FormatTest, BreaksAsHighAsPossible) { 6968 verifyFormat( 6969 "void f() {\n" 6970 " if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n" 6971 " (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n" 6972 " f();\n" 6973 "}"); 6974 verifyFormat("if (Intervals[i].getRange().getFirst() <\n" 6975 " Intervals[i - 1].getRange().getLast()) {\n}"); 6976 } 6977 6978 TEST_F(FormatTest, BreaksFunctionDeclarations) { 6979 // Principially, we break function declarations in a certain order: 6980 // 1) break amongst arguments. 6981 verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n" 6982 " Cccccccccccccc cccccccccccccc);"); 6983 verifyFormat("template <class TemplateIt>\n" 6984 "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n" 6985 " TemplateIt *stop) {}"); 6986 6987 // 2) break after return type. 6988 verifyFormat( 6989 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6990 "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);", 6991 getGoogleStyle()); 6992 6993 // 3) break after (. 6994 verifyFormat( 6995 "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n" 6996 " Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);", 6997 getGoogleStyle()); 6998 6999 // 4) break before after nested name specifiers. 7000 verifyFormat( 7001 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7002 "SomeClasssssssssssssssssssssssssssssssssssssss::\n" 7003 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);", 7004 getGoogleStyle()); 7005 7006 // However, there are exceptions, if a sufficient amount of lines can be 7007 // saved. 7008 // FIXME: The precise cut-offs wrt. the number of saved lines might need some 7009 // more adjusting. 7010 verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n" 7011 " Cccccccccccccc cccccccccc,\n" 7012 " Cccccccccccccc cccccccccc,\n" 7013 " Cccccccccccccc cccccccccc,\n" 7014 " Cccccccccccccc cccccccccc);"); 7015 verifyFormat( 7016 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7017 "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7018 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7019 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);", 7020 getGoogleStyle()); 7021 verifyFormat( 7022 "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n" 7023 " Cccccccccccccc cccccccccc,\n" 7024 " Cccccccccccccc cccccccccc,\n" 7025 " Cccccccccccccc cccccccccc,\n" 7026 " Cccccccccccccc cccccccccc,\n" 7027 " Cccccccccccccc cccccccccc,\n" 7028 " Cccccccccccccc cccccccccc);"); 7029 verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7030 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7031 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7032 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7033 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);"); 7034 7035 // Break after multi-line parameters. 7036 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7037 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7038 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7039 " bbbb bbbb);"); 7040 verifyFormat("void SomeLoooooooooooongFunction(\n" 7041 " std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n" 7042 " aaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7043 " int bbbbbbbbbbbbb);"); 7044 7045 // Treat overloaded operators like other functions. 7046 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 7047 "operator>(const SomeLoooooooooooooooooooooooooogType &other);"); 7048 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 7049 "operator>>(const SomeLooooooooooooooooooooooooogType &other);"); 7050 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 7051 "operator<<(const SomeLooooooooooooooooooooooooogType &other);"); 7052 verifyGoogleFormat( 7053 "SomeLoooooooooooooooooooooooooooooogType operator>>(\n" 7054 " const SomeLooooooooogType &a, const SomeLooooooooogType &b);"); 7055 verifyGoogleFormat( 7056 "SomeLoooooooooooooooooooooooooooooogType operator<<(\n" 7057 " const SomeLooooooooogType &a, const SomeLooooooooogType &b);"); 7058 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7059 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);"); 7060 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n" 7061 "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);"); 7062 verifyGoogleFormat( 7063 "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n" 7064 "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7065 " bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}"); 7066 verifyGoogleFormat("template <typename T>\n" 7067 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7068 "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n" 7069 " aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);"); 7070 7071 FormatStyle Style = getLLVMStyle(); 7072 Style.PointerAlignment = FormatStyle::PAS_Left; 7073 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7074 " aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}", 7075 Style); 7076 verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n" 7077 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7078 Style); 7079 } 7080 7081 TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) { 7082 // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516: 7083 // Prefer keeping `::` followed by `operator` together. 7084 EXPECT_EQ("const aaaa::bbbbbbb &\n" 7085 "ccccccccc::operator++() {\n" 7086 " stuff();\n" 7087 "}", 7088 format("const aaaa::bbbbbbb\n" 7089 "&ccccccccc::operator++() { stuff(); }", 7090 getLLVMStyleWithColumns(40))); 7091 } 7092 7093 TEST_F(FormatTest, TrailingReturnType) { 7094 verifyFormat("auto foo() -> int;\n"); 7095 // correct trailing return type spacing 7096 verifyFormat("auto operator->() -> int;\n"); 7097 verifyFormat("auto operator++(int) -> int;\n"); 7098 7099 verifyFormat("struct S {\n" 7100 " auto bar() const -> int;\n" 7101 "};"); 7102 verifyFormat("template <size_t Order, typename T>\n" 7103 "auto load_img(const std::string &filename)\n" 7104 " -> alias::tensor<Order, T, mem::tag::cpu> {}"); 7105 verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n" 7106 " -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}"); 7107 verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}"); 7108 verifyFormat("template <typename T>\n" 7109 "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n" 7110 " -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());"); 7111 7112 // Not trailing return types. 7113 verifyFormat("void f() { auto a = b->c(); }"); 7114 verifyFormat("auto a = p->foo();"); 7115 verifyFormat("int a = p->foo();"); 7116 verifyFormat("auto lmbd = [] NOEXCEPT -> int { return 0; };"); 7117 } 7118 7119 TEST_F(FormatTest, DeductionGuides) { 7120 verifyFormat("template <class T> A(const T &, const T &) -> A<T &>;"); 7121 verifyFormat("template <class T> explicit A(T &, T &&) -> A<T>;"); 7122 verifyFormat("template <class... Ts> S(Ts...) -> S<Ts...>;"); 7123 verifyFormat( 7124 "template <class... T>\n" 7125 "array(T &&...t) -> array<std::common_type_t<T...>, sizeof...(T)>;"); 7126 verifyFormat("template <class T> A() -> A<decltype(p->foo<3>())>;"); 7127 verifyFormat("template <class T> A() -> A<decltype(foo<traits<1>>)>;"); 7128 verifyFormat("template <class T> A() -> A<sizeof(p->foo<1>)>;"); 7129 verifyFormat("template <class T> A() -> A<(3 < 2)>;"); 7130 verifyFormat("template <class T> A() -> A<((3) < (2))>;"); 7131 verifyFormat("template <class T> x() -> x<1>;"); 7132 verifyFormat("template <class T> explicit x(T &) -> x<1>;"); 7133 7134 // Ensure not deduction guides. 7135 verifyFormat("c()->f<int>();"); 7136 verifyFormat("x()->foo<1>;"); 7137 verifyFormat("x = p->foo<3>();"); 7138 verifyFormat("x()->x<1>();"); 7139 verifyFormat("x()->x<1>;"); 7140 } 7141 7142 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) { 7143 // Avoid breaking before trailing 'const' or other trailing annotations, if 7144 // they are not function-like. 7145 FormatStyle Style = getGoogleStyleWithColumns(47); 7146 verifyFormat("void someLongFunction(\n" 7147 " int someLoooooooooooooongParameter) const {\n}", 7148 getLLVMStyleWithColumns(47)); 7149 verifyFormat("LoooooongReturnType\n" 7150 "someLoooooooongFunction() const {}", 7151 getLLVMStyleWithColumns(47)); 7152 verifyFormat("LoooooongReturnType someLoooooooongFunction()\n" 7153 " const {}", 7154 Style); 7155 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7156 " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;"); 7157 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7158 " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;"); 7159 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7160 " aaaaa aaaaaaaaaaaaaaaaaaaa) override final;"); 7161 verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n" 7162 " aaaaaaaaaaa aaaaa) const override;"); 7163 verifyGoogleFormat( 7164 "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7165 " const override;"); 7166 7167 // Even if the first parameter has to be wrapped. 7168 verifyFormat("void someLongFunction(\n" 7169 " int someLongParameter) const {}", 7170 getLLVMStyleWithColumns(46)); 7171 verifyFormat("void someLongFunction(\n" 7172 " int someLongParameter) const {}", 7173 Style); 7174 verifyFormat("void someLongFunction(\n" 7175 " int someLongParameter) override {}", 7176 Style); 7177 verifyFormat("void someLongFunction(\n" 7178 " int someLongParameter) OVERRIDE {}", 7179 Style); 7180 verifyFormat("void someLongFunction(\n" 7181 " int someLongParameter) final {}", 7182 Style); 7183 verifyFormat("void someLongFunction(\n" 7184 " int someLongParameter) FINAL {}", 7185 Style); 7186 verifyFormat("void someLongFunction(\n" 7187 " int parameter) const override {}", 7188 Style); 7189 7190 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 7191 verifyFormat("void someLongFunction(\n" 7192 " int someLongParameter) const\n" 7193 "{\n" 7194 "}", 7195 Style); 7196 7197 Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 7198 verifyFormat("void someLongFunction(\n" 7199 " int someLongParameter) const\n" 7200 " {\n" 7201 " }", 7202 Style); 7203 7204 // Unless these are unknown annotations. 7205 verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n" 7206 " aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7207 " LONG_AND_UGLY_ANNOTATION;"); 7208 7209 // Breaking before function-like trailing annotations is fine to keep them 7210 // close to their arguments. 7211 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7212 " LOCKS_EXCLUDED(aaaaaaaaaaaaa);"); 7213 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n" 7214 " LOCKS_EXCLUDED(aaaaaaaaaaaaa);"); 7215 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n" 7216 " LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}"); 7217 verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n" 7218 " AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);"); 7219 verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});"); 7220 7221 verifyFormat( 7222 "void aaaaaaaaaaaaaaaaaa()\n" 7223 " __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n" 7224 " aaaaaaaaaaaaaaaaaaaaaaaaa));"); 7225 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7226 " __attribute__((unused));"); 7227 verifyGoogleFormat( 7228 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7229 " GUARDED_BY(aaaaaaaaaaaa);"); 7230 verifyGoogleFormat( 7231 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7232 " GUARDED_BY(aaaaaaaaaaaa);"); 7233 verifyGoogleFormat( 7234 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n" 7235 " aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7236 verifyGoogleFormat( 7237 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n" 7238 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7239 } 7240 7241 TEST_F(FormatTest, FunctionAnnotations) { 7242 verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7243 "int OldFunction(const string ¶meter) {}"); 7244 verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7245 "string OldFunction(const string ¶meter) {}"); 7246 verifyFormat("template <typename T>\n" 7247 "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7248 "string OldFunction(const string ¶meter) {}"); 7249 7250 // Not function annotations. 7251 verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7252 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"); 7253 verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n" 7254 " ThisIsATestWithAReallyReallyReallyReallyLongName) {}"); 7255 verifyFormat("MACRO(abc).function() // wrap\n" 7256 " << abc;"); 7257 verifyFormat("MACRO(abc)->function() // wrap\n" 7258 " << abc;"); 7259 verifyFormat("MACRO(abc)::function() // wrap\n" 7260 " << abc;"); 7261 } 7262 7263 TEST_F(FormatTest, BreaksDesireably) { 7264 verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n" 7265 " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n" 7266 " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}"); 7267 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7268 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 7269 "}"); 7270 7271 verifyFormat( 7272 "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7273 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 7274 7275 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7276 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7277 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7278 7279 verifyFormat( 7280 "aaaaaaaa(aaaaaaaaaaaaa,\n" 7281 " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7282 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n" 7283 " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7284 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));"); 7285 7286 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 7287 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7288 7289 verifyFormat( 7290 "void f() {\n" 7291 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n" 7292 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 7293 "}"); 7294 verifyFormat( 7295 "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7296 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7297 verifyFormat( 7298 "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7299 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7300 verifyFormat( 7301 "aaaaaa(aaa,\n" 7302 " new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7303 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7304 " aaaa);"); 7305 verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7306 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7307 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7308 7309 // Indent consistently independent of call expression and unary operator. 7310 verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7311 " dddddddddddddddddddddddddddddd));"); 7312 verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7313 " dddddddddddddddddddddddddddddd));"); 7314 verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n" 7315 " dddddddddddddddddddddddddddddd));"); 7316 7317 // This test case breaks on an incorrect memoization, i.e. an optimization not 7318 // taking into account the StopAt value. 7319 verifyFormat( 7320 "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7321 " aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7322 " aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7323 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7324 7325 verifyFormat("{\n {\n {\n" 7326 " Annotation.SpaceRequiredBefore =\n" 7327 " Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n" 7328 " Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n" 7329 " }\n }\n}"); 7330 7331 // Break on an outer level if there was a break on an inner level. 7332 EXPECT_EQ("f(g(h(a, // comment\n" 7333 " b, c),\n" 7334 " d, e),\n" 7335 " x, y);", 7336 format("f(g(h(a, // comment\n" 7337 " b, c), d, e), x, y);")); 7338 7339 // Prefer breaking similar line breaks. 7340 verifyFormat( 7341 "const int kTrackingOptions = NSTrackingMouseMoved |\n" 7342 " NSTrackingMouseEnteredAndExited |\n" 7343 " NSTrackingActiveAlways;"); 7344 } 7345 7346 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) { 7347 FormatStyle NoBinPacking = getGoogleStyle(); 7348 NoBinPacking.BinPackParameters = false; 7349 NoBinPacking.BinPackArguments = true; 7350 verifyFormat("void f() {\n" 7351 " f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n" 7352 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 7353 "}", 7354 NoBinPacking); 7355 verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n" 7356 " int aaaaaaaaaaaaaaaaaaaa,\n" 7357 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7358 NoBinPacking); 7359 7360 NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false; 7361 verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7362 " vector<int> bbbbbbbbbbbbbbb);", 7363 NoBinPacking); 7364 // FIXME: This behavior difference is probably not wanted. However, currently 7365 // we cannot distinguish BreakBeforeParameter being set because of the wrapped 7366 // template arguments from BreakBeforeParameter being set because of the 7367 // one-per-line formatting. 7368 verifyFormat( 7369 "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n" 7370 " aaaaaaaaaa> aaaaaaaaaa);", 7371 NoBinPacking); 7372 verifyFormat( 7373 "void fffffffffff(\n" 7374 " aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n" 7375 " aaaaaaaaaa);"); 7376 } 7377 7378 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) { 7379 FormatStyle NoBinPacking = getGoogleStyle(); 7380 NoBinPacking.BinPackParameters = false; 7381 NoBinPacking.BinPackArguments = false; 7382 verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n" 7383 " aaaaaaaaaaaaaaaaaaaa,\n" 7384 " aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);", 7385 NoBinPacking); 7386 verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n" 7387 " aaaaaaaaaaaaa,\n" 7388 " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));", 7389 NoBinPacking); 7390 verifyFormat( 7391 "aaaaaaaa(aaaaaaaaaaaaa,\n" 7392 " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7393 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n" 7394 " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7395 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));", 7396 NoBinPacking); 7397 verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n" 7398 " .aaaaaaaaaaaaaaaaaa();", 7399 NoBinPacking); 7400 verifyFormat("void f() {\n" 7401 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7402 " aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n" 7403 "}", 7404 NoBinPacking); 7405 7406 verifyFormat( 7407 "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7408 " aaaaaaaaaaaa,\n" 7409 " aaaaaaaaaaaa);", 7410 NoBinPacking); 7411 verifyFormat( 7412 "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n" 7413 " ddddddddddddddddddddddddddddd),\n" 7414 " test);", 7415 NoBinPacking); 7416 7417 verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n" 7418 " aaaaaaaaaaaaaaaaaaaaaaa,\n" 7419 " aaaaaaaaaaaaaaaaaaaaaaa>\n" 7420 " aaaaaaaaaaaaaaaaaa;", 7421 NoBinPacking); 7422 verifyFormat("a(\"a\"\n" 7423 " \"a\",\n" 7424 " a);"); 7425 7426 NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false; 7427 verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n" 7428 " aaaaaaaaa,\n" 7429 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7430 NoBinPacking); 7431 verifyFormat( 7432 "void f() {\n" 7433 " aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n" 7434 " .aaaaaaa();\n" 7435 "}", 7436 NoBinPacking); 7437 verifyFormat( 7438 "template <class SomeType, class SomeOtherType>\n" 7439 "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}", 7440 NoBinPacking); 7441 } 7442 7443 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) { 7444 FormatStyle Style = getLLVMStyleWithColumns(15); 7445 Style.ExperimentalAutoDetectBinPacking = true; 7446 EXPECT_EQ("aaa(aaaa,\n" 7447 " aaaa,\n" 7448 " aaaa);\n" 7449 "aaa(aaaa,\n" 7450 " aaaa,\n" 7451 " aaaa);", 7452 format("aaa(aaaa,\n" // one-per-line 7453 " aaaa,\n" 7454 " aaaa );\n" 7455 "aaa(aaaa, aaaa, aaaa);", // inconclusive 7456 Style)); 7457 EXPECT_EQ("aaa(aaaa, aaaa,\n" 7458 " aaaa);\n" 7459 "aaa(aaaa, aaaa,\n" 7460 " aaaa);", 7461 format("aaa(aaaa, aaaa,\n" // bin-packed 7462 " aaaa );\n" 7463 "aaa(aaaa, aaaa, aaaa);", // inconclusive 7464 Style)); 7465 } 7466 7467 TEST_F(FormatTest, FormatsBuilderPattern) { 7468 verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n" 7469 " .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n" 7470 " .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n" 7471 " .StartsWith(\".init\", ORDER_INIT)\n" 7472 " .StartsWith(\".fini\", ORDER_FINI)\n" 7473 " .StartsWith(\".hash\", ORDER_HASH)\n" 7474 " .Default(ORDER_TEXT);\n"); 7475 7476 verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n" 7477 " aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();"); 7478 verifyFormat("aaaaaaa->aaaaaaa\n" 7479 " ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7480 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7481 " ->aaaaaaaa(aaaaaaaaaaaaaaa);"); 7482 verifyFormat( 7483 "aaaaaaa->aaaaaaa\n" 7484 " ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7485 " ->aaaaaaaa(aaaaaaaaaaaaaaa);"); 7486 verifyFormat( 7487 "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n" 7488 " aaaaaaaaaaaaaa);"); 7489 verifyFormat( 7490 "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n" 7491 " aaaaaa->aaaaaaaaaaaa()\n" 7492 " ->aaaaaaaaaaaaaaaa(\n" 7493 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7494 " ->aaaaaaaaaaaaaaaaa();"); 7495 verifyGoogleFormat( 7496 "void f() {\n" 7497 " someo->Add((new util::filetools::Handler(dir))\n" 7498 " ->OnEvent1(NewPermanentCallback(\n" 7499 " this, &HandlerHolderClass::EventHandlerCBA))\n" 7500 " ->OnEvent2(NewPermanentCallback(\n" 7501 " this, &HandlerHolderClass::EventHandlerCBB))\n" 7502 " ->OnEvent3(NewPermanentCallback(\n" 7503 " this, &HandlerHolderClass::EventHandlerCBC))\n" 7504 " ->OnEvent5(NewPermanentCallback(\n" 7505 " this, &HandlerHolderClass::EventHandlerCBD))\n" 7506 " ->OnEvent6(NewPermanentCallback(\n" 7507 " this, &HandlerHolderClass::EventHandlerCBE)));\n" 7508 "}"); 7509 7510 verifyFormat( 7511 "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();"); 7512 verifyFormat("aaaaaaaaaaaaaaa()\n" 7513 " .aaaaaaaaaaaaaaa()\n" 7514 " .aaaaaaaaaaaaaaa()\n" 7515 " .aaaaaaaaaaaaaaa()\n" 7516 " .aaaaaaaaaaaaaaa();"); 7517 verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7518 " .aaaaaaaaaaaaaaa()\n" 7519 " .aaaaaaaaaaaaaaa()\n" 7520 " .aaaaaaaaaaaaaaa();"); 7521 verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7522 " .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7523 " .aaaaaaaaaaaaaaa();"); 7524 verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n" 7525 " ->aaaaaaaaaaaaaae(0)\n" 7526 " ->aaaaaaaaaaaaaaa();"); 7527 7528 // Don't linewrap after very short segments. 7529 verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7530 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7531 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7532 verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7533 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7534 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7535 verifyFormat("aaa()\n" 7536 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7537 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7538 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7539 7540 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n" 7541 " .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7542 " .has<bbbbbbbbbbbbbbbbbbbbb>();"); 7543 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n" 7544 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 7545 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();"); 7546 7547 // Prefer not to break after empty parentheses. 7548 verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n" 7549 " First->LastNewlineOffset);"); 7550 7551 // Prefer not to create "hanging" indents. 7552 verifyFormat( 7553 "return !soooooooooooooome_map\n" 7554 " .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7555 " .second;"); 7556 verifyFormat( 7557 "return aaaaaaaaaaaaaaaa\n" 7558 " .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n" 7559 " .aaaa(aaaaaaaaaaaaaa);"); 7560 // No hanging indent here. 7561 verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n" 7562 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7563 verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n" 7564 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7565 verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n" 7566 " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7567 getLLVMStyleWithColumns(60)); 7568 verifyFormat("aaaaaaaaaaaaaaaaaa\n" 7569 " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n" 7570 " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7571 getLLVMStyleWithColumns(59)); 7572 verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7573 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7574 " .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7575 7576 // Dont break if only closing statements before member call 7577 verifyFormat("test() {\n" 7578 " ([]() -> {\n" 7579 " int b = 32;\n" 7580 " return 3;\n" 7581 " }).foo();\n" 7582 "}"); 7583 verifyFormat("test() {\n" 7584 " (\n" 7585 " []() -> {\n" 7586 " int b = 32;\n" 7587 " return 3;\n" 7588 " },\n" 7589 " foo, bar)\n" 7590 " .foo();\n" 7591 "}"); 7592 verifyFormat("test() {\n" 7593 " ([]() -> {\n" 7594 " int b = 32;\n" 7595 " return 3;\n" 7596 " })\n" 7597 " .foo()\n" 7598 " .bar();\n" 7599 "}"); 7600 verifyFormat("test() {\n" 7601 " ([]() -> {\n" 7602 " int b = 32;\n" 7603 " return 3;\n" 7604 " })\n" 7605 " .foo(\"aaaaaaaaaaaaaaaaa\"\n" 7606 " \"bbbb\");\n" 7607 "}", 7608 getLLVMStyleWithColumns(30)); 7609 } 7610 7611 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) { 7612 verifyFormat( 7613 "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 7614 " bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}"); 7615 verifyFormat( 7616 "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n" 7617 " bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}"); 7618 7619 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" 7620 " ccccccccccccccccccccccccc) {\n}"); 7621 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n" 7622 " ccccccccccccccccccccccccc) {\n}"); 7623 7624 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" 7625 " ccccccccccccccccccccccccc) {\n}"); 7626 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n" 7627 " ccccccccccccccccccccccccc) {\n}"); 7628 7629 verifyFormat( 7630 "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n" 7631 " ccccccccccccccccccccccccc) {\n}"); 7632 verifyFormat( 7633 "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n" 7634 " ccccccccccccccccccccccccc) {\n}"); 7635 7636 verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n" 7637 " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n" 7638 " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n" 7639 " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;"); 7640 verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n" 7641 " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n" 7642 " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n" 7643 " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;"); 7644 7645 verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n" 7646 " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n" 7647 " aaaaaaaaaaaaaaa != aa) {\n}"); 7648 verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n" 7649 " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n" 7650 " aaaaaaaaaaaaaaa != aa) {\n}"); 7651 } 7652 7653 TEST_F(FormatTest, BreaksAfterAssignments) { 7654 verifyFormat( 7655 "unsigned Cost =\n" 7656 " TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n" 7657 " SI->getPointerAddressSpaceee());\n"); 7658 verifyFormat( 7659 "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n" 7660 " Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());"); 7661 7662 verifyFormat( 7663 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n" 7664 " aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);"); 7665 verifyFormat("unsigned OriginalStartColumn =\n" 7666 " SourceMgr.getSpellingColumnNumber(\n" 7667 " Current.FormatTok.getStartOfNonWhitespace()) -\n" 7668 " 1;"); 7669 } 7670 7671 TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) { 7672 FormatStyle Style = getLLVMStyle(); 7673 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 7674 " bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;", 7675 Style); 7676 7677 Style.PenaltyBreakAssignment = 20; 7678 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n" 7679 " cccccccccccccccccccccccccc;", 7680 Style); 7681 } 7682 7683 TEST_F(FormatTest, AlignsAfterAssignments) { 7684 verifyFormat( 7685 "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7686 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7687 verifyFormat( 7688 "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7689 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7690 verifyFormat( 7691 "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7692 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7693 verifyFormat( 7694 "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7695 " aaaaaaaaaaaaaaaaaaaaaaaaa);"); 7696 verifyFormat( 7697 "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n" 7698 " aaaaaaaaaaaaaaaaaaaaaaaa +\n" 7699 " aaaaaaaaaaaaaaaaaaaaaaaa;"); 7700 } 7701 7702 TEST_F(FormatTest, AlignsAfterReturn) { 7703 verifyFormat( 7704 "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7705 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7706 verifyFormat( 7707 "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7708 " aaaaaaaaaaaaaaaaaaaaaaaaa);"); 7709 verifyFormat( 7710 "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n" 7711 " aaaaaaaaaaaaaaaaaaaaaa();"); 7712 verifyFormat( 7713 "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n" 7714 " aaaaaaaaaaaaaaaaaaaaaa());"); 7715 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7716 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7717 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7718 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n" 7719 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7720 verifyFormat("return\n" 7721 " // true if code is one of a or b.\n" 7722 " code == a || code == b;"); 7723 } 7724 7725 TEST_F(FormatTest, AlignsAfterOpenBracket) { 7726 verifyFormat( 7727 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n" 7728 " aaaaaaaaa aaaaaaa) {}"); 7729 verifyFormat( 7730 "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n" 7731 " aaaaaaaaaaa aaaaaaaaa);"); 7732 verifyFormat( 7733 "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n" 7734 " aaaaaaaaaaaaaaaaaaaaa));"); 7735 FormatStyle Style = getLLVMStyle(); 7736 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 7737 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7738 " aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}", 7739 Style); 7740 verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n" 7741 " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);", 7742 Style); 7743 verifyFormat("SomeLongVariableName->someFunction(\n" 7744 " foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));", 7745 Style); 7746 verifyFormat( 7747 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n" 7748 " aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7749 Style); 7750 verifyFormat( 7751 "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n" 7752 " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7753 Style); 7754 verifyFormat( 7755 "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n" 7756 " aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));", 7757 Style); 7758 7759 verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n" 7760 " ccccccc(aaaaaaaaaaaaaaaaa, //\n" 7761 " b));", 7762 Style); 7763 7764 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 7765 Style.BinPackArguments = false; 7766 Style.BinPackParameters = false; 7767 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7768 " aaaaaaaaaaa aaaaaaaa,\n" 7769 " aaaaaaaaa aaaaaaa,\n" 7770 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7771 Style); 7772 verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n" 7773 " aaaaaaaaaaa aaaaaaaaa,\n" 7774 " aaaaaaaaaaa aaaaaaaaa,\n" 7775 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7776 Style); 7777 verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n" 7778 " aaaaaaaaaaaaaaa,\n" 7779 " aaaaaaaaaaaaaaaaaaaaa,\n" 7780 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));", 7781 Style); 7782 verifyFormat( 7783 "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n" 7784 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));", 7785 Style); 7786 verifyFormat( 7787 "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n" 7788 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));", 7789 Style); 7790 verifyFormat( 7791 "aaaaaaaaaaaaaaaaaaaaaaaa(\n" 7792 " aaaaaaaaaaaaaaaaaaaaa(\n" 7793 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n" 7794 " aaaaaaaaaaaaaaaa);", 7795 Style); 7796 verifyFormat( 7797 "aaaaaaaaaaaaaaaaaaaaaaaa(\n" 7798 " aaaaaaaaaaaaaaaaaaaaa(\n" 7799 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n" 7800 " aaaaaaaaaaaaaaaa);", 7801 Style); 7802 } 7803 7804 TEST_F(FormatTest, ParenthesesAndOperandAlignment) { 7805 FormatStyle Style = getLLVMStyleWithColumns(40); 7806 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 7807 " bbbbbbbbbbbbbbbbbbbbbb);", 7808 Style); 7809 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 7810 Style.AlignOperands = FormatStyle::OAS_DontAlign; 7811 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 7812 " bbbbbbbbbbbbbbbbbbbbbb);", 7813 Style); 7814 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 7815 Style.AlignOperands = FormatStyle::OAS_Align; 7816 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 7817 " bbbbbbbbbbbbbbbbbbbbbb);", 7818 Style); 7819 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 7820 Style.AlignOperands = FormatStyle::OAS_DontAlign; 7821 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 7822 " bbbbbbbbbbbbbbbbbbbbbb);", 7823 Style); 7824 } 7825 7826 TEST_F(FormatTest, BreaksConditionalExpressions) { 7827 verifyFormat( 7828 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7829 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7830 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7831 verifyFormat( 7832 "aaaa(aaaaaaaaaa, aaaaaaaa,\n" 7833 " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7834 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7835 verifyFormat( 7836 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7837 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7838 verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n" 7839 " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7840 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7841 verifyFormat( 7842 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n" 7843 " : aaaaaaaaaaaaa);"); 7844 verifyFormat( 7845 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7846 " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7847 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7848 " aaaaaaaaaaaaa);"); 7849 verifyFormat( 7850 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7851 " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7852 " aaaaaaaaaaaaa);"); 7853 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7854 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7855 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7856 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7857 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7858 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7859 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7860 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7861 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7862 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7863 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7864 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7865 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7866 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7867 " ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7868 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7869 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7870 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7871 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7872 " : aaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7873 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n" 7874 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7875 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7876 " : aaaaaaaaaaaaaaaa;"); 7877 verifyFormat( 7878 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7879 " ? aaaaaaaaaaaaaaa\n" 7880 " : aaaaaaaaaaaaaaa;"); 7881 verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n" 7882 " aaaaaaaaa\n" 7883 " ? b\n" 7884 " : c);"); 7885 verifyFormat("return aaaa == bbbb\n" 7886 " // comment\n" 7887 " ? aaaa\n" 7888 " : bbbb;"); 7889 verifyFormat("unsigned Indent =\n" 7890 " format(TheLine.First,\n" 7891 " IndentForLevel[TheLine.Level] >= 0\n" 7892 " ? IndentForLevel[TheLine.Level]\n" 7893 " : TheLine * 2,\n" 7894 " TheLine.InPPDirective, PreviousEndOfLineColumn);", 7895 getLLVMStyleWithColumns(60)); 7896 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n" 7897 " ? aaaaaaaaaaaaaaa\n" 7898 " : bbbbbbbbbbbbbbb //\n" 7899 " ? ccccccccccccccc\n" 7900 " : ddddddddddddddd;"); 7901 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n" 7902 " ? aaaaaaaaaaaaaaa\n" 7903 " : (bbbbbbbbbbbbbbb //\n" 7904 " ? ccccccccccccccc\n" 7905 " : ddddddddddddddd);"); 7906 verifyFormat( 7907 "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7908 " ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7909 " aaaaaaaaaaaaaaaaaaaaa +\n" 7910 " aaaaaaaaaaaaaaaaaaaaa\n" 7911 " : aaaaaaaaaa;"); 7912 verifyFormat( 7913 "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7914 " : aaaaaaaaaaaaaaaaaaaaaa\n" 7915 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7916 7917 FormatStyle NoBinPacking = getLLVMStyle(); 7918 NoBinPacking.BinPackArguments = false; 7919 verifyFormat( 7920 "void f() {\n" 7921 " g(aaa,\n" 7922 " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n" 7923 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7924 " ? aaaaaaaaaaaaaaa\n" 7925 " : aaaaaaaaaaaaaaa);\n" 7926 "}", 7927 NoBinPacking); 7928 verifyFormat( 7929 "void f() {\n" 7930 " g(aaa,\n" 7931 " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n" 7932 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7933 " ?: aaaaaaaaaaaaaaa);\n" 7934 "}", 7935 NoBinPacking); 7936 7937 verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n" 7938 " // comment.\n" 7939 " ccccccccccccccccccccccccccccccccccccccc\n" 7940 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7941 " : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);"); 7942 7943 // Assignments in conditional expressions. Apparently not uncommon :-(. 7944 verifyFormat("return a != b\n" 7945 " // comment\n" 7946 " ? a = b\n" 7947 " : a = b;"); 7948 verifyFormat("return a != b\n" 7949 " // comment\n" 7950 " ? a = a != b\n" 7951 " // comment\n" 7952 " ? a = b\n" 7953 " : a\n" 7954 " : a;\n"); 7955 verifyFormat("return a != b\n" 7956 " // comment\n" 7957 " ? a\n" 7958 " : a = a != b\n" 7959 " // comment\n" 7960 " ? a = b\n" 7961 " : a;"); 7962 7963 // Chained conditionals 7964 FormatStyle Style = getLLVMStyleWithColumns(70); 7965 Style.AlignOperands = FormatStyle::OAS_Align; 7966 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 7967 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7968 " : 3333333333333333;", 7969 Style); 7970 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 7971 " : bbbbbbbbbb ? 2222222222222222\n" 7972 " : 3333333333333333;", 7973 Style); 7974 verifyFormat("return aaaaaaaaaa ? 1111111111111111\n" 7975 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 7976 " : 3333333333333333;", 7977 Style); 7978 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 7979 " : bbbbbbbbbbbbbb ? 222222\n" 7980 " : 333333;", 7981 Style); 7982 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 7983 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7984 " : cccccccccccccc ? 3333333333333333\n" 7985 " : 4444444444444444;", 7986 Style); 7987 verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc)\n" 7988 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7989 " : 3333333333333333;", 7990 Style); 7991 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 7992 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7993 " : (aaa ? bbb : ccc);", 7994 Style); 7995 verifyFormat( 7996 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 7997 " : cccccccccccccccccc)\n" 7998 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7999 " : 3333333333333333;", 8000 Style); 8001 verifyFormat( 8002 "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8003 " : cccccccccccccccccc)\n" 8004 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8005 " : 3333333333333333;", 8006 Style); 8007 verifyFormat( 8008 "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8009 " : dddddddddddddddddd)\n" 8010 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8011 " : 3333333333333333;", 8012 Style); 8013 verifyFormat( 8014 "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8015 " : dddddddddddddddddd)\n" 8016 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8017 " : 3333333333333333;", 8018 Style); 8019 verifyFormat( 8020 "return aaaaaaaaa ? 1111111111111111\n" 8021 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8022 " : a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8023 " : dddddddddddddddddd)\n", 8024 Style); 8025 verifyFormat( 8026 "return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8027 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8028 " : (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8029 " : cccccccccccccccccc);", 8030 Style); 8031 verifyFormat( 8032 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8033 " : ccccccccccccccc ? dddddddddddddddddd\n" 8034 " : eeeeeeeeeeeeeeeeee)\n" 8035 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8036 " : 3333333333333333;", 8037 Style); 8038 verifyFormat( 8039 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8040 " : ccccccccccccccc ? dddddddddddddddddd\n" 8041 " : eeeeeeeeeeeeeeeeee)\n" 8042 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8043 " : 3333333333333333;", 8044 Style); 8045 verifyFormat( 8046 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8047 " : cccccccccccc ? dddddddddddddddddd\n" 8048 " : eeeeeeeeeeeeeeeeee)\n" 8049 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8050 " : 3333333333333333;", 8051 Style); 8052 verifyFormat( 8053 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8054 " : cccccccccccccccccc\n" 8055 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8056 " : 3333333333333333;", 8057 Style); 8058 verifyFormat( 8059 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8060 " : cccccccccccccccc ? dddddddddddddddddd\n" 8061 " : eeeeeeeeeeeeeeeeee\n" 8062 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8063 " : 3333333333333333;", 8064 Style); 8065 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa\n" 8066 " ? (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8067 " : cccccccccccccccccc ? dddddddddddddddddd\n" 8068 " : eeeeeeeeeeeeeeeeee)\n" 8069 " : bbbbbbbbbbbbbbbbbbb ? 2222222222222222\n" 8070 " : 3333333333333333;", 8071 Style); 8072 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaa\n" 8073 " ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8074 " : cccccccccccccccc ? dddddddddddddddddd\n" 8075 " : eeeeeeeeeeeeeeeeee\n" 8076 " : bbbbbbbbbbbbbbbbbbbbbbb ? 2222222222222222\n" 8077 " : 3333333333333333;", 8078 Style); 8079 8080 Style.AlignOperands = FormatStyle::OAS_DontAlign; 8081 Style.BreakBeforeTernaryOperators = false; 8082 // FIXME: Aligning the question marks is weird given DontAlign. 8083 // Consider disabling this alignment in this case. Also check whether this 8084 // will render the adjustment from https://reviews.llvm.org/D82199 8085 // unnecessary. 8086 verifyFormat("int x = aaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa :\n" 8087 " bbbb ? cccccccccccccccccc :\n" 8088 " ddddd;\n", 8089 Style); 8090 8091 EXPECT_EQ( 8092 "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n" 8093 " /*\n" 8094 " */\n" 8095 " function() {\n" 8096 " try {\n" 8097 " return JJJJJJJJJJJJJJ(\n" 8098 " pppppppppppppppppppppppppppppppppppppppppppppppppp);\n" 8099 " }\n" 8100 " } :\n" 8101 " function() {};", 8102 format( 8103 "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n" 8104 " /*\n" 8105 " */\n" 8106 " function() {\n" 8107 " try {\n" 8108 " return JJJJJJJJJJJJJJ(\n" 8109 " pppppppppppppppppppppppppppppppppppppppppppppppppp);\n" 8110 " }\n" 8111 " } :\n" 8112 " function() {};", 8113 getGoogleStyle(FormatStyle::LK_JavaScript))); 8114 } 8115 8116 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) { 8117 FormatStyle Style = getLLVMStyleWithColumns(70); 8118 Style.BreakBeforeTernaryOperators = false; 8119 verifyFormat( 8120 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8121 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8122 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8123 Style); 8124 verifyFormat( 8125 "aaaa(aaaaaaaaaa, aaaaaaaa,\n" 8126 " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8127 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8128 Style); 8129 verifyFormat( 8130 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8131 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8132 Style); 8133 verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n" 8134 " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8135 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8136 Style); 8137 verifyFormat( 8138 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n" 8139 " aaaaaaaaaaaaa);", 8140 Style); 8141 verifyFormat( 8142 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8143 " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8144 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8145 " aaaaaaaaaaaaa);", 8146 Style); 8147 verifyFormat( 8148 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8149 " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8150 " aaaaaaaaaaaaa);", 8151 Style); 8152 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8153 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8154 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 8155 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8156 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8157 Style); 8158 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8159 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8160 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8161 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 8162 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8163 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8164 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8165 Style); 8166 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8167 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n" 8168 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8169 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8170 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8171 Style); 8172 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8173 " aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8174 " aaaaaaaaaaaaaaaaaaaaaaaaaaa;", 8175 Style); 8176 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n" 8177 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8178 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8179 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 8180 Style); 8181 verifyFormat( 8182 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8183 " aaaaaaaaaaaaaaa :\n" 8184 " aaaaaaaaaaaaaaa;", 8185 Style); 8186 verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n" 8187 " aaaaaaaaa ?\n" 8188 " b :\n" 8189 " c);", 8190 Style); 8191 verifyFormat("unsigned Indent =\n" 8192 " format(TheLine.First,\n" 8193 " IndentForLevel[TheLine.Level] >= 0 ?\n" 8194 " IndentForLevel[TheLine.Level] :\n" 8195 " TheLine * 2,\n" 8196 " TheLine.InPPDirective, PreviousEndOfLineColumn);", 8197 Style); 8198 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n" 8199 " aaaaaaaaaaaaaaa :\n" 8200 " bbbbbbbbbbbbbbb ? //\n" 8201 " ccccccccccccccc :\n" 8202 " ddddddddddddddd;", 8203 Style); 8204 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n" 8205 " aaaaaaaaaaaaaaa :\n" 8206 " (bbbbbbbbbbbbbbb ? //\n" 8207 " ccccccccccccccc :\n" 8208 " ddddddddddddddd);", 8209 Style); 8210 verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8211 " /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n" 8212 " ccccccccccccccccccccccccccc;", 8213 Style); 8214 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8215 " aaaaa :\n" 8216 " bbbbbbbbbbbbbbb + cccccccccccccccc;", 8217 Style); 8218 8219 // Chained conditionals 8220 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8221 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8222 " 3333333333333333;", 8223 Style); 8224 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8225 " bbbbbbbbbb ? 2222222222222222 :\n" 8226 " 3333333333333333;", 8227 Style); 8228 verifyFormat("return aaaaaaaaaa ? 1111111111111111 :\n" 8229 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8230 " 3333333333333333;", 8231 Style); 8232 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8233 " bbbbbbbbbbbbbbbb ? 222222 :\n" 8234 " 333333;", 8235 Style); 8236 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8237 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8238 " cccccccccccccccc ? 3333333333333333 :\n" 8239 " 4444444444444444;", 8240 Style); 8241 verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc) :\n" 8242 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8243 " 3333333333333333;", 8244 Style); 8245 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8246 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8247 " (aaa ? bbb : ccc);", 8248 Style); 8249 verifyFormat( 8250 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8251 " cccccccccccccccccc) :\n" 8252 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8253 " 3333333333333333;", 8254 Style); 8255 verifyFormat( 8256 "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8257 " cccccccccccccccccc) :\n" 8258 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8259 " 3333333333333333;", 8260 Style); 8261 verifyFormat( 8262 "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8263 " dddddddddddddddddd) :\n" 8264 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8265 " 3333333333333333;", 8266 Style); 8267 verifyFormat( 8268 "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8269 " dddddddddddddddddd) :\n" 8270 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8271 " 3333333333333333;", 8272 Style); 8273 verifyFormat( 8274 "return aaaaaaaaa ? 1111111111111111 :\n" 8275 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8276 " a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8277 " dddddddddddddddddd)\n", 8278 Style); 8279 verifyFormat( 8280 "return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8281 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8282 " (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8283 " cccccccccccccccccc);", 8284 Style); 8285 verifyFormat( 8286 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8287 " ccccccccccccccccc ? dddddddddddddddddd :\n" 8288 " eeeeeeeeeeeeeeeeee) :\n" 8289 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8290 " 3333333333333333;", 8291 Style); 8292 verifyFormat( 8293 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8294 " ccccccccccccc ? dddddddddddddddddd :\n" 8295 " eeeeeeeeeeeeeeeeee) :\n" 8296 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8297 " 3333333333333333;", 8298 Style); 8299 verifyFormat( 8300 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8301 " ccccccccccccccccc ? dddddddddddddddddd :\n" 8302 " eeeeeeeeeeeeeeeeee) :\n" 8303 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8304 " 3333333333333333;", 8305 Style); 8306 verifyFormat( 8307 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8308 " cccccccccccccccccc :\n" 8309 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8310 " 3333333333333333;", 8311 Style); 8312 verifyFormat( 8313 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8314 " cccccccccccccccccc ? dddddddddddddddddd :\n" 8315 " eeeeeeeeeeeeeeeeee :\n" 8316 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8317 " 3333333333333333;", 8318 Style); 8319 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n" 8320 " (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8321 " cccccccccccccccccc ? dddddddddddddddddd :\n" 8322 " eeeeeeeeeeeeeeeeee) :\n" 8323 " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8324 " 3333333333333333;", 8325 Style); 8326 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n" 8327 " aaaaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8328 " cccccccccccccccccccc ? dddddddddddddddddd :\n" 8329 " eeeeeeeeeeeeeeeeee :\n" 8330 " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8331 " 3333333333333333;", 8332 Style); 8333 } 8334 8335 TEST_F(FormatTest, DeclarationsOfMultipleVariables) { 8336 verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n" 8337 " aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();"); 8338 verifyFormat("bool a = true, b = false;"); 8339 8340 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n" 8341 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n" 8342 " bbbbbbbbbbbbbbbbbbbbbbbbb =\n" 8343 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);"); 8344 verifyFormat( 8345 "bool aaaaaaaaaaaaaaaaaaaaa =\n" 8346 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n" 8347 " d = e && f;"); 8348 verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n" 8349 " c = cccccccccccccccccccc, d = dddddddddddddddddddd;"); 8350 verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n" 8351 " *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;"); 8352 verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n" 8353 " ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;"); 8354 8355 FormatStyle Style = getGoogleStyle(); 8356 Style.PointerAlignment = FormatStyle::PAS_Left; 8357 Style.DerivePointerAlignment = false; 8358 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8359 " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n" 8360 " *b = bbbbbbbbbbbbbbbbbbb;", 8361 Style); 8362 verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n" 8363 " *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;", 8364 Style); 8365 verifyFormat("vector<int*> a, b;", Style); 8366 verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style); 8367 } 8368 8369 TEST_F(FormatTest, ConditionalExpressionsInBrackets) { 8370 verifyFormat("arr[foo ? bar : baz];"); 8371 verifyFormat("f()[foo ? bar : baz];"); 8372 verifyFormat("(a + b)[foo ? bar : baz];"); 8373 verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];"); 8374 } 8375 8376 TEST_F(FormatTest, AlignsStringLiterals) { 8377 verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n" 8378 " \"short literal\");"); 8379 verifyFormat( 8380 "looooooooooooooooooooooooongFunction(\n" 8381 " \"short literal\"\n" 8382 " \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");"); 8383 verifyFormat("someFunction(\"Always break between multi-line\"\n" 8384 " \" string literals\",\n" 8385 " and, other, parameters);"); 8386 EXPECT_EQ("fun + \"1243\" /* comment */\n" 8387 " \"5678\";", 8388 format("fun + \"1243\" /* comment */\n" 8389 " \"5678\";", 8390 getLLVMStyleWithColumns(28))); 8391 EXPECT_EQ( 8392 "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 8393 " \"aaaaaaaaaaaaaaaaaaaaa\"\n" 8394 " \"aaaaaaaaaaaaaaaa\";", 8395 format("aaaaaa =" 8396 "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa " 8397 "aaaaaaaaaaaaaaaaaaaaa\" " 8398 "\"aaaaaaaaaaaaaaaa\";")); 8399 verifyFormat("a = a + \"a\"\n" 8400 " \"a\"\n" 8401 " \"a\";"); 8402 verifyFormat("f(\"a\", \"b\"\n" 8403 " \"c\");"); 8404 8405 verifyFormat( 8406 "#define LL_FORMAT \"ll\"\n" 8407 "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n" 8408 " \"d, ddddddddd: %\" LL_FORMAT \"d\");"); 8409 8410 verifyFormat("#define A(X) \\\n" 8411 " \"aaaaa\" #X \"bbbbbb\" \\\n" 8412 " \"ccccc\"", 8413 getLLVMStyleWithColumns(23)); 8414 verifyFormat("#define A \"def\"\n" 8415 "f(\"abc\" A \"ghi\"\n" 8416 " \"jkl\");"); 8417 8418 verifyFormat("f(L\"a\"\n" 8419 " L\"b\");"); 8420 verifyFormat("#define A(X) \\\n" 8421 " L\"aaaaa\" #X L\"bbbbbb\" \\\n" 8422 " L\"ccccc\"", 8423 getLLVMStyleWithColumns(25)); 8424 8425 verifyFormat("f(@\"a\"\n" 8426 " @\"b\");"); 8427 verifyFormat("NSString s = @\"a\"\n" 8428 " @\"b\"\n" 8429 " @\"c\";"); 8430 verifyFormat("NSString s = @\"a\"\n" 8431 " \"b\"\n" 8432 " \"c\";"); 8433 } 8434 8435 TEST_F(FormatTest, ReturnTypeBreakingStyle) { 8436 FormatStyle Style = getLLVMStyle(); 8437 // No declarations or definitions should be moved to own line. 8438 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None; 8439 verifyFormat("class A {\n" 8440 " int f() { return 1; }\n" 8441 " int g();\n" 8442 "};\n" 8443 "int f() { return 1; }\n" 8444 "int g();\n", 8445 Style); 8446 8447 // All declarations and definitions should have the return type moved to its 8448 // own line. 8449 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 8450 Style.TypenameMacros = {"LIST"}; 8451 verifyFormat("SomeType\n" 8452 "funcdecl(LIST(uint64_t));", 8453 Style); 8454 verifyFormat("class E {\n" 8455 " int\n" 8456 " f() {\n" 8457 " return 1;\n" 8458 " }\n" 8459 " int\n" 8460 " g();\n" 8461 "};\n" 8462 "int\n" 8463 "f() {\n" 8464 " return 1;\n" 8465 "}\n" 8466 "int\n" 8467 "g();\n", 8468 Style); 8469 8470 // Top-level definitions, and no kinds of declarations should have the 8471 // return type moved to its own line. 8472 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions; 8473 verifyFormat("class B {\n" 8474 " int f() { return 1; }\n" 8475 " int g();\n" 8476 "};\n" 8477 "int\n" 8478 "f() {\n" 8479 " return 1;\n" 8480 "}\n" 8481 "int g();\n", 8482 Style); 8483 8484 // Top-level definitions and declarations should have the return type moved 8485 // to its own line. 8486 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel; 8487 verifyFormat("class C {\n" 8488 " int f() { return 1; }\n" 8489 " int g();\n" 8490 "};\n" 8491 "int\n" 8492 "f() {\n" 8493 " return 1;\n" 8494 "}\n" 8495 "int\n" 8496 "g();\n", 8497 Style); 8498 8499 // All definitions should have the return type moved to its own line, but no 8500 // kinds of declarations. 8501 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions; 8502 verifyFormat("class D {\n" 8503 " int\n" 8504 " f() {\n" 8505 " return 1;\n" 8506 " }\n" 8507 " int g();\n" 8508 "};\n" 8509 "int\n" 8510 "f() {\n" 8511 " return 1;\n" 8512 "}\n" 8513 "int g();\n", 8514 Style); 8515 verifyFormat("const char *\n" 8516 "f(void) {\n" // Break here. 8517 " return \"\";\n" 8518 "}\n" 8519 "const char *bar(void);\n", // No break here. 8520 Style); 8521 verifyFormat("template <class T>\n" 8522 "T *\n" 8523 "f(T &c) {\n" // Break here. 8524 " return NULL;\n" 8525 "}\n" 8526 "template <class T> T *f(T &c);\n", // No break here. 8527 Style); 8528 verifyFormat("class C {\n" 8529 " int\n" 8530 " operator+() {\n" 8531 " return 1;\n" 8532 " }\n" 8533 " int\n" 8534 " operator()() {\n" 8535 " return 1;\n" 8536 " }\n" 8537 "};\n", 8538 Style); 8539 verifyFormat("void\n" 8540 "A::operator()() {}\n" 8541 "void\n" 8542 "A::operator>>() {}\n" 8543 "void\n" 8544 "A::operator+() {}\n" 8545 "void\n" 8546 "A::operator*() {}\n" 8547 "void\n" 8548 "A::operator->() {}\n" 8549 "void\n" 8550 "A::operator void *() {}\n" 8551 "void\n" 8552 "A::operator void &() {}\n" 8553 "void\n" 8554 "A::operator void &&() {}\n" 8555 "void\n" 8556 "A::operator char *() {}\n" 8557 "void\n" 8558 "A::operator[]() {}\n" 8559 "void\n" 8560 "A::operator!() {}\n" 8561 "void\n" 8562 "A::operator**() {}\n" 8563 "void\n" 8564 "A::operator<Foo> *() {}\n" 8565 "void\n" 8566 "A::operator<Foo> **() {}\n" 8567 "void\n" 8568 "A::operator<Foo> &() {}\n" 8569 "void\n" 8570 "A::operator void **() {}\n", 8571 Style); 8572 verifyFormat("constexpr auto\n" 8573 "operator()() const -> reference {}\n" 8574 "constexpr auto\n" 8575 "operator>>() const -> reference {}\n" 8576 "constexpr auto\n" 8577 "operator+() const -> reference {}\n" 8578 "constexpr auto\n" 8579 "operator*() const -> reference {}\n" 8580 "constexpr auto\n" 8581 "operator->() const -> reference {}\n" 8582 "constexpr auto\n" 8583 "operator++() const -> reference {}\n" 8584 "constexpr auto\n" 8585 "operator void *() const -> reference {}\n" 8586 "constexpr auto\n" 8587 "operator void **() const -> reference {}\n" 8588 "constexpr auto\n" 8589 "operator void *() const -> reference {}\n" 8590 "constexpr auto\n" 8591 "operator void &() const -> reference {}\n" 8592 "constexpr auto\n" 8593 "operator void &&() const -> reference {}\n" 8594 "constexpr auto\n" 8595 "operator char *() const -> reference {}\n" 8596 "constexpr auto\n" 8597 "operator!() const -> reference {}\n" 8598 "constexpr auto\n" 8599 "operator[]() const -> reference {}\n", 8600 Style); 8601 verifyFormat("void *operator new(std::size_t s);", // No break here. 8602 Style); 8603 verifyFormat("void *\n" 8604 "operator new(std::size_t s) {}", 8605 Style); 8606 verifyFormat("void *\n" 8607 "operator delete[](void *ptr) {}", 8608 Style); 8609 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 8610 verifyFormat("const char *\n" 8611 "f(void)\n" // Break here. 8612 "{\n" 8613 " return \"\";\n" 8614 "}\n" 8615 "const char *bar(void);\n", // No break here. 8616 Style); 8617 verifyFormat("template <class T>\n" 8618 "T *\n" // Problem here: no line break 8619 "f(T &c)\n" // Break here. 8620 "{\n" 8621 " return NULL;\n" 8622 "}\n" 8623 "template <class T> T *f(T &c);\n", // No break here. 8624 Style); 8625 verifyFormat("int\n" 8626 "foo(A<bool> a)\n" 8627 "{\n" 8628 " return a;\n" 8629 "}\n", 8630 Style); 8631 verifyFormat("int\n" 8632 "foo(A<8> a)\n" 8633 "{\n" 8634 " return a;\n" 8635 "}\n", 8636 Style); 8637 verifyFormat("int\n" 8638 "foo(A<B<bool>, 8> a)\n" 8639 "{\n" 8640 " return a;\n" 8641 "}\n", 8642 Style); 8643 verifyFormat("int\n" 8644 "foo(A<B<8>, bool> a)\n" 8645 "{\n" 8646 " return a;\n" 8647 "}\n", 8648 Style); 8649 verifyFormat("int\n" 8650 "foo(A<B<bool>, bool> a)\n" 8651 "{\n" 8652 " return a;\n" 8653 "}\n", 8654 Style); 8655 verifyFormat("int\n" 8656 "foo(A<B<8>, 8> a)\n" 8657 "{\n" 8658 " return a;\n" 8659 "}\n", 8660 Style); 8661 8662 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 8663 Style.BraceWrapping.AfterFunction = true; 8664 verifyFormat("int f(i);\n" // No break here. 8665 "int\n" // Break here. 8666 "f(i)\n" 8667 "{\n" 8668 " return i + 1;\n" 8669 "}\n" 8670 "int\n" // Break here. 8671 "f(i)\n" 8672 "{\n" 8673 " return i + 1;\n" 8674 "};", 8675 Style); 8676 verifyFormat("int f(a, b, c);\n" // No break here. 8677 "int\n" // Break here. 8678 "f(a, b, c)\n" // Break here. 8679 "short a, b;\n" 8680 "float c;\n" 8681 "{\n" 8682 " return a + b < c;\n" 8683 "}\n" 8684 "int\n" // Break here. 8685 "f(a, b, c)\n" // Break here. 8686 "short a, b;\n" 8687 "float c;\n" 8688 "{\n" 8689 " return a + b < c;\n" 8690 "};", 8691 Style); 8692 verifyFormat("byte *\n" // Break here. 8693 "f(a)\n" // Break here. 8694 "byte a[];\n" 8695 "{\n" 8696 " return a;\n" 8697 "}", 8698 Style); 8699 verifyFormat("bool f(int a, int) override;\n" 8700 "Bar g(int a, Bar) final;\n" 8701 "Bar h(a, Bar) final;", 8702 Style); 8703 verifyFormat("int\n" 8704 "f(a)", 8705 Style); 8706 verifyFormat("bool\n" 8707 "f(size_t = 0, bool b = false)\n" 8708 "{\n" 8709 " return !b;\n" 8710 "}", 8711 Style); 8712 8713 // The return breaking style doesn't affect: 8714 // * function and object definitions with attribute-like macros 8715 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 8716 " ABSL_GUARDED_BY(mutex) = {};", 8717 getGoogleStyleWithColumns(40)); 8718 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 8719 " ABSL_GUARDED_BY(mutex); // comment", 8720 getGoogleStyleWithColumns(40)); 8721 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 8722 " ABSL_GUARDED_BY(mutex1)\n" 8723 " ABSL_GUARDED_BY(mutex2);", 8724 getGoogleStyleWithColumns(40)); 8725 verifyFormat("Tttttt f(int a, int b)\n" 8726 " ABSL_GUARDED_BY(mutex1)\n" 8727 " ABSL_GUARDED_BY(mutex2);", 8728 getGoogleStyleWithColumns(40)); 8729 // * typedefs 8730 verifyFormat("typedef ATTR(X) char x;", getGoogleStyle()); 8731 8732 Style = getGNUStyle(); 8733 8734 // Test for comments at the end of function declarations. 8735 verifyFormat("void\n" 8736 "foo (int a, /*abc*/ int b) // def\n" 8737 "{\n" 8738 "}\n", 8739 Style); 8740 8741 verifyFormat("void\n" 8742 "foo (int a, /* abc */ int b) /* def */\n" 8743 "{\n" 8744 "}\n", 8745 Style); 8746 8747 // Definitions that should not break after return type 8748 verifyFormat("void foo (int a, int b); // def\n", Style); 8749 verifyFormat("void foo (int a, int b); /* def */\n", Style); 8750 verifyFormat("void foo (int a, int b);\n", Style); 8751 } 8752 8753 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) { 8754 FormatStyle NoBreak = getLLVMStyle(); 8755 NoBreak.AlwaysBreakBeforeMultilineStrings = false; 8756 FormatStyle Break = getLLVMStyle(); 8757 Break.AlwaysBreakBeforeMultilineStrings = true; 8758 verifyFormat("aaaa = \"bbbb\"\n" 8759 " \"cccc\";", 8760 NoBreak); 8761 verifyFormat("aaaa =\n" 8762 " \"bbbb\"\n" 8763 " \"cccc\";", 8764 Break); 8765 verifyFormat("aaaa(\"bbbb\"\n" 8766 " \"cccc\");", 8767 NoBreak); 8768 verifyFormat("aaaa(\n" 8769 " \"bbbb\"\n" 8770 " \"cccc\");", 8771 Break); 8772 verifyFormat("aaaa(qqq, \"bbbb\"\n" 8773 " \"cccc\");", 8774 NoBreak); 8775 verifyFormat("aaaa(qqq,\n" 8776 " \"bbbb\"\n" 8777 " \"cccc\");", 8778 Break); 8779 verifyFormat("aaaa(qqq,\n" 8780 " L\"bbbb\"\n" 8781 " L\"cccc\");", 8782 Break); 8783 verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n" 8784 " \"bbbb\"));", 8785 Break); 8786 verifyFormat("string s = someFunction(\n" 8787 " \"abc\"\n" 8788 " \"abc\");", 8789 Break); 8790 8791 // As we break before unary operators, breaking right after them is bad. 8792 verifyFormat("string foo = abc ? \"x\"\n" 8793 " \"blah blah blah blah blah blah\"\n" 8794 " : \"y\";", 8795 Break); 8796 8797 // Don't break if there is no column gain. 8798 verifyFormat("f(\"aaaa\"\n" 8799 " \"bbbb\");", 8800 Break); 8801 8802 // Treat literals with escaped newlines like multi-line string literals. 8803 EXPECT_EQ("x = \"a\\\n" 8804 "b\\\n" 8805 "c\";", 8806 format("x = \"a\\\n" 8807 "b\\\n" 8808 "c\";", 8809 NoBreak)); 8810 EXPECT_EQ("xxxx =\n" 8811 " \"a\\\n" 8812 "b\\\n" 8813 "c\";", 8814 format("xxxx = \"a\\\n" 8815 "b\\\n" 8816 "c\";", 8817 Break)); 8818 8819 EXPECT_EQ("NSString *const kString =\n" 8820 " @\"aaaa\"\n" 8821 " @\"bbbb\";", 8822 format("NSString *const kString = @\"aaaa\"\n" 8823 "@\"bbbb\";", 8824 Break)); 8825 8826 Break.ColumnLimit = 0; 8827 verifyFormat("const char *hello = \"hello llvm\";", Break); 8828 } 8829 8830 TEST_F(FormatTest, AlignsPipes) { 8831 verifyFormat( 8832 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8833 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8834 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8835 verifyFormat( 8836 "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n" 8837 " << aaaaaaaaaaaaaaaaaaaa;"); 8838 verifyFormat( 8839 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8840 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8841 verifyFormat( 8842 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 8843 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8844 verifyFormat( 8845 "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n" 8846 " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n" 8847 " << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";"); 8848 verifyFormat( 8849 "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8850 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8851 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8852 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8853 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8854 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8855 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 8856 verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n" 8857 " << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);"); 8858 verifyFormat( 8859 "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8860 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8861 verifyFormat( 8862 "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n" 8863 " aaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8864 8865 verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n" 8866 " << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();"); 8867 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8868 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8869 " aaaaaaaaaaaaaaaaaaaaa)\n" 8870 " << aaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8871 verifyFormat("LOG_IF(aaa == //\n" 8872 " bbb)\n" 8873 " << a << b;"); 8874 8875 // But sometimes, breaking before the first "<<" is desirable. 8876 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 8877 " << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);"); 8878 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n" 8879 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8880 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8881 verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n" 8882 " << BEF << IsTemplate << Description << E->getType();"); 8883 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 8884 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8885 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8886 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 8887 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8888 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8889 " << aaa;"); 8890 8891 verifyFormat( 8892 "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8893 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 8894 8895 // Incomplete string literal. 8896 EXPECT_EQ("llvm::errs() << \"\n" 8897 " << a;", 8898 format("llvm::errs() << \"\n<<a;")); 8899 8900 verifyFormat("void f() {\n" 8901 " CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n" 8902 " << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n" 8903 "}"); 8904 8905 // Handle 'endl'. 8906 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n" 8907 " << bbbbbbbbbbbbbbbbbbbbbb << endl;"); 8908 verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;"); 8909 8910 // Handle '\n'. 8911 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n" 8912 " << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";"); 8913 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n" 8914 " << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';"); 8915 verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n" 8916 " << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";"); 8917 verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";"); 8918 } 8919 8920 TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) { 8921 verifyFormat("return out << \"somepacket = {\\n\"\n" 8922 " << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n" 8923 " << \" bbbb = \" << pkt.bbbb << \"\\n\"\n" 8924 " << \" cccccc = \" << pkt.cccccc << \"\\n\"\n" 8925 " << \" ddd = [\" << pkt.ddd << \"]\\n\"\n" 8926 " << \"}\";"); 8927 8928 verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n" 8929 " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n" 8930 " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;"); 8931 verifyFormat( 8932 "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n" 8933 " << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n" 8934 " << \"ccccccccccccccccc = \" << ccccccccccccccccc\n" 8935 " << \"ddddddddddddddddd = \" << ddddddddddddddddd\n" 8936 " << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;"); 8937 verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n" 8938 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 8939 verifyFormat( 8940 "void f() {\n" 8941 " llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n" 8942 " << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 8943 "}"); 8944 8945 // Breaking before the first "<<" is generally not desirable. 8946 verifyFormat( 8947 "llvm::errs()\n" 8948 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8949 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8950 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8951 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 8952 getLLVMStyleWithColumns(70)); 8953 verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n" 8954 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8955 " << \"aaaaaaaaaaaaaaaaaaa: \"\n" 8956 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8957 " << \"aaaaaaaaaaaaaaaaaaa: \"\n" 8958 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 8959 getLLVMStyleWithColumns(70)); 8960 8961 verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n" 8962 " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n" 8963 " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;"); 8964 verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n" 8965 " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n" 8966 " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);"); 8967 verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n" 8968 " (aaaa + aaaa);", 8969 getLLVMStyleWithColumns(40)); 8970 verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n" 8971 " (aaaaaaa + aaaaa));", 8972 getLLVMStyleWithColumns(40)); 8973 verifyFormat( 8974 "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n" 8975 " SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n" 8976 " bbbbbbbbbbbbbbbbbbbbbbb);"); 8977 } 8978 8979 TEST_F(FormatTest, UnderstandsEquals) { 8980 verifyFormat( 8981 "aaaaaaaaaaaaaaaaa =\n" 8982 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8983 verifyFormat( 8984 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 8985 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 8986 verifyFormat( 8987 "if (a) {\n" 8988 " f();\n" 8989 "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 8990 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 8991 "}"); 8992 8993 verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 8994 " 100000000 + 10000000) {\n}"); 8995 } 8996 8997 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) { 8998 verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n" 8999 " .looooooooooooooooooooooooooooooooooooooongFunction();"); 9000 9001 verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n" 9002 " ->looooooooooooooooooooooooooooooooooooooongFunction();"); 9003 9004 verifyFormat( 9005 "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n" 9006 " Parameter2);"); 9007 9008 verifyFormat( 9009 "ShortObject->shortFunction(\n" 9010 " LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n" 9011 " LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);"); 9012 9013 verifyFormat("loooooooooooooongFunction(\n" 9014 " LoooooooooooooongObject->looooooooooooooooongFunction());"); 9015 9016 verifyFormat( 9017 "function(LoooooooooooooooooooooooooooooooooooongObject\n" 9018 " ->loooooooooooooooooooooooooooooooooooooooongFunction());"); 9019 9020 verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n" 9021 " .WillRepeatedly(Return(SomeValue));"); 9022 verifyFormat("void f() {\n" 9023 " EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n" 9024 " .Times(2)\n" 9025 " .WillRepeatedly(Return(SomeValue));\n" 9026 "}"); 9027 verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n" 9028 " ccccccccccccccccccccccc);"); 9029 verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9030 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9031 " .aaaaa(aaaaa),\n" 9032 " aaaaaaaaaaaaaaaaaaaaa);"); 9033 verifyFormat("void f() {\n" 9034 " aaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9035 " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n" 9036 "}"); 9037 verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9038 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9039 " .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9040 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9041 " aaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 9042 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9043 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9044 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9045 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n" 9046 "}"); 9047 9048 // Here, it is not necessary to wrap at "." or "->". 9049 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n" 9050 " aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 9051 verifyFormat( 9052 "aaaaaaaaaaa->aaaaaaaaa(\n" 9053 " aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9054 " aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n"); 9055 9056 verifyFormat( 9057 "aaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9058 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());"); 9059 verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n" 9060 " aaaaaaaaa()->aaaaaa()->aaaaa());"); 9061 verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n" 9062 " aaaaaaaaa()->aaaaaa()->aaaaa());"); 9063 9064 verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9065 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9066 " .a();"); 9067 9068 FormatStyle NoBinPacking = getLLVMStyle(); 9069 NoBinPacking.BinPackParameters = false; 9070 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n" 9071 " .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n" 9072 " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n" 9073 " aaaaaaaaaaaaaaaaaaa,\n" 9074 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 9075 NoBinPacking); 9076 9077 // If there is a subsequent call, change to hanging indentation. 9078 verifyFormat( 9079 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9080 " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n" 9081 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9082 verifyFormat( 9083 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9084 " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));"); 9085 verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9086 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9087 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9088 verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9089 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9090 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());"); 9091 } 9092 9093 TEST_F(FormatTest, WrapsTemplateDeclarations) { 9094 verifyFormat("template <typename T>\n" 9095 "virtual void loooooooooooongFunction(int Param1, int Param2);"); 9096 verifyFormat("template <typename T>\n" 9097 "// T should be one of {A, B}.\n" 9098 "virtual void loooooooooooongFunction(int Param1, int Param2);"); 9099 verifyFormat( 9100 "template <typename T>\n" 9101 "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;"); 9102 verifyFormat("template <typename T>\n" 9103 "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n" 9104 " int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);"); 9105 verifyFormat( 9106 "template <typename T>\n" 9107 "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n" 9108 " int Paaaaaaaaaaaaaaaaaaaaram2);"); 9109 verifyFormat( 9110 "template <typename T>\n" 9111 "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n" 9112 " aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n" 9113 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9114 verifyFormat("template <typename T>\n" 9115 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9116 " int aaaaaaaaaaaaaaaaaaaaaa);"); 9117 verifyFormat( 9118 "template <typename T1, typename T2 = char, typename T3 = char,\n" 9119 " typename T4 = char>\n" 9120 "void f();"); 9121 verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n" 9122 " template <typename> class cccccccccccccccccccccc,\n" 9123 " typename ddddddddddddd>\n" 9124 "class C {};"); 9125 verifyFormat( 9126 "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n" 9127 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9128 9129 verifyFormat("void f() {\n" 9130 " a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n" 9131 " a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n" 9132 "}"); 9133 9134 verifyFormat("template <typename T> class C {};"); 9135 verifyFormat("template <typename T> void f();"); 9136 verifyFormat("template <typename T> void f() {}"); 9137 verifyFormat( 9138 "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n" 9139 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9140 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n" 9141 " new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n" 9142 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9143 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n" 9144 " bbbbbbbbbbbbbbbbbbbbbbbb);", 9145 getLLVMStyleWithColumns(72)); 9146 EXPECT_EQ("static_cast<A< //\n" 9147 " B> *>(\n" 9148 "\n" 9149 ");", 9150 format("static_cast<A<//\n" 9151 " B>*>(\n" 9152 "\n" 9153 " );")); 9154 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9155 " const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);"); 9156 9157 FormatStyle AlwaysBreak = getLLVMStyle(); 9158 AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 9159 verifyFormat("template <typename T>\nclass C {};", AlwaysBreak); 9160 verifyFormat("template <typename T>\nvoid f();", AlwaysBreak); 9161 verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak); 9162 verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9163 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n" 9164 " ccccccccccccccccccccccccccccccccccccccccccccccc);"); 9165 verifyFormat("template <template <typename> class Fooooooo,\n" 9166 " template <typename> class Baaaaaaar>\n" 9167 "struct C {};", 9168 AlwaysBreak); 9169 verifyFormat("template <typename T> // T can be A, B or C.\n" 9170 "struct C {};", 9171 AlwaysBreak); 9172 verifyFormat("template <enum E> class A {\n" 9173 "public:\n" 9174 " E *f();\n" 9175 "};"); 9176 9177 FormatStyle NeverBreak = getLLVMStyle(); 9178 NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No; 9179 verifyFormat("template <typename T> class C {};", NeverBreak); 9180 verifyFormat("template <typename T> void f();", NeverBreak); 9181 verifyFormat("template <typename T> void f() {}", NeverBreak); 9182 verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa " 9183 "bbbbbbbbbbbbbbbbbbbb) {}", 9184 NeverBreak); 9185 verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9186 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n" 9187 " ccccccccccccccccccccccccccccccccccccccccccccccc);", 9188 NeverBreak); 9189 verifyFormat("template <template <typename> class Fooooooo,\n" 9190 " template <typename> class Baaaaaaar>\n" 9191 "struct C {};", 9192 NeverBreak); 9193 verifyFormat("template <typename T> // T can be A, B or C.\n" 9194 "struct C {};", 9195 NeverBreak); 9196 verifyFormat("template <enum E> class A {\n" 9197 "public:\n" 9198 " E *f();\n" 9199 "};", 9200 NeverBreak); 9201 NeverBreak.PenaltyBreakTemplateDeclaration = 100; 9202 verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa " 9203 "bbbbbbbbbbbbbbbbbbbb) {}", 9204 NeverBreak); 9205 } 9206 9207 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) { 9208 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp); 9209 Style.ColumnLimit = 60; 9210 EXPECT_EQ("// Baseline - no comments.\n" 9211 "template <\n" 9212 " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n" 9213 "void f() {}", 9214 format("// Baseline - no comments.\n" 9215 "template <\n" 9216 " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n" 9217 "void f() {}", 9218 Style)); 9219 9220 EXPECT_EQ("template <\n" 9221 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9222 "void f() {}", 9223 format("template <\n" 9224 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9225 "void f() {}", 9226 Style)); 9227 9228 EXPECT_EQ( 9229 "template <\n" 9230 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n" 9231 "void f() {}", 9232 format("template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n" 9233 "void f() {}", 9234 Style)); 9235 9236 EXPECT_EQ( 9237 "template <\n" 9238 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9239 " // multiline\n" 9240 "void f() {}", 9241 format("template <\n" 9242 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9243 " // multiline\n" 9244 "void f() {}", 9245 Style)); 9246 9247 EXPECT_EQ( 9248 "template <typename aaaaaaaaaa<\n" 9249 " bbbbbbbbbbbb>::value> // trailing loooong\n" 9250 "void f() {}", 9251 format( 9252 "template <\n" 9253 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n" 9254 "void f() {}", 9255 Style)); 9256 } 9257 9258 TEST_F(FormatTest, WrapsTemplateParameters) { 9259 FormatStyle Style = getLLVMStyle(); 9260 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 9261 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 9262 verifyFormat( 9263 "template <typename... a> struct q {};\n" 9264 "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n" 9265 " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n" 9266 " y;", 9267 Style); 9268 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 9269 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 9270 verifyFormat( 9271 "template <typename... a> struct r {};\n" 9272 "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n" 9273 " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n" 9274 " y;", 9275 Style); 9276 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 9277 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 9278 verifyFormat("template <typename... a> struct s {};\n" 9279 "extern s<\n" 9280 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9281 "aaaaaaaaaaaaaaaaaaaaaa,\n" 9282 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9283 "aaaaaaaaaaaaaaaaaaaaaa>\n" 9284 " y;", 9285 Style); 9286 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 9287 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 9288 verifyFormat("template <typename... a> struct t {};\n" 9289 "extern t<\n" 9290 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9291 "aaaaaaaaaaaaaaaaaaaaaa,\n" 9292 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9293 "aaaaaaaaaaaaaaaaaaaaaa>\n" 9294 " y;", 9295 Style); 9296 } 9297 9298 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) { 9299 verifyFormat( 9300 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9301 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9302 verifyFormat( 9303 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9304 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9305 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());"); 9306 9307 // FIXME: Should we have the extra indent after the second break? 9308 verifyFormat( 9309 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9310 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9311 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9312 9313 verifyFormat( 9314 "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n" 9315 " cccccccccccccccccccccccccccccccccccccccccccccc());"); 9316 9317 // Breaking at nested name specifiers is generally not desirable. 9318 verifyFormat( 9319 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9320 " aaaaaaaaaaaaaaaaaaaaaaa);"); 9321 9322 verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n" 9323 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9324 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9325 " aaaaaaaaaaaaaaaaaaaaa);", 9326 getLLVMStyleWithColumns(74)); 9327 9328 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9329 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9330 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9331 } 9332 9333 TEST_F(FormatTest, UnderstandsTemplateParameters) { 9334 verifyFormat("A<int> a;"); 9335 verifyFormat("A<A<A<int>>> a;"); 9336 verifyFormat("A<A<A<int, 2>, 3>, 4> a;"); 9337 verifyFormat("bool x = a < 1 || 2 > a;"); 9338 verifyFormat("bool x = 5 < f<int>();"); 9339 verifyFormat("bool x = f<int>() > 5;"); 9340 verifyFormat("bool x = 5 < a<int>::x;"); 9341 verifyFormat("bool x = a < 4 ? a > 2 : false;"); 9342 verifyFormat("bool x = f() ? a < 2 : a > 2;"); 9343 9344 verifyGoogleFormat("A<A<int>> a;"); 9345 verifyGoogleFormat("A<A<A<int>>> a;"); 9346 verifyGoogleFormat("A<A<A<A<int>>>> a;"); 9347 verifyGoogleFormat("A<A<int> > a;"); 9348 verifyGoogleFormat("A<A<A<int> > > a;"); 9349 verifyGoogleFormat("A<A<A<A<int> > > > a;"); 9350 verifyGoogleFormat("A<::A<int>> a;"); 9351 verifyGoogleFormat("A<::A> a;"); 9352 verifyGoogleFormat("A< ::A> a;"); 9353 verifyGoogleFormat("A< ::A<int> > a;"); 9354 EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle())); 9355 EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle())); 9356 EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle())); 9357 EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle())); 9358 EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };", 9359 format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle())); 9360 9361 verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp)); 9362 9363 // template closer followed by a token that starts with > or = 9364 verifyFormat("bool b = a<1> > 1;"); 9365 verifyFormat("bool b = a<1> >= 1;"); 9366 verifyFormat("int i = a<1> >> 1;"); 9367 FormatStyle Style = getLLVMStyle(); 9368 Style.SpaceBeforeAssignmentOperators = false; 9369 verifyFormat("bool b= a<1> == 1;", Style); 9370 verifyFormat("a<int> = 1;", Style); 9371 verifyFormat("a<int> >>= 1;", Style); 9372 9373 verifyFormat("test < a | b >> c;"); 9374 verifyFormat("test<test<a | b>> c;"); 9375 verifyFormat("test >> a >> b;"); 9376 verifyFormat("test << a >> b;"); 9377 9378 verifyFormat("f<int>();"); 9379 verifyFormat("template <typename T> void f() {}"); 9380 verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;"); 9381 verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : " 9382 "sizeof(char)>::type>;"); 9383 verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};"); 9384 verifyFormat("f(a.operator()<A>());"); 9385 verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9386 " .template operator()<A>());", 9387 getLLVMStyleWithColumns(35)); 9388 9389 // Not template parameters. 9390 verifyFormat("return a < b && c > d;"); 9391 verifyFormat("void f() {\n" 9392 " while (a < b && c > d) {\n" 9393 " }\n" 9394 "}"); 9395 verifyFormat("template <typename... Types>\n" 9396 "typename enable_if<0 < sizeof...(Types)>::type Foo() {}"); 9397 9398 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9399 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);", 9400 getLLVMStyleWithColumns(60)); 9401 verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");"); 9402 verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}"); 9403 verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <"); 9404 verifyFormat("some_templated_type<decltype([](int i) { return i; })>"); 9405 } 9406 9407 TEST_F(FormatTest, UnderstandsShiftOperators) { 9408 verifyFormat("if (i < x >> 1)"); 9409 verifyFormat("while (i < x >> 1)"); 9410 verifyFormat("for (unsigned i = 0; i < i; ++i, v = v >> 1)"); 9411 verifyFormat("for (unsigned i = 0; i < x >> 1; ++i, v = v >> 1)"); 9412 verifyFormat( 9413 "for (std::vector<int>::iterator i = 0; i < x >> 1; ++i, v = v >> 1)"); 9414 verifyFormat("Foo.call<Bar<Function>>()"); 9415 verifyFormat("if (Foo.call<Bar<Function>>() == 0)"); 9416 verifyFormat("for (std::vector<std::pair<int>>::iterator i = 0; i < x >> 1; " 9417 "++i, v = v >> 1)"); 9418 verifyFormat("if (w<u<v<x>>, 1>::t)"); 9419 } 9420 9421 TEST_F(FormatTest, BitshiftOperatorWidth) { 9422 EXPECT_EQ("int a = 1 << 2; /* foo\n" 9423 " bar */", 9424 format("int a=1<<2; /* foo\n" 9425 " bar */")); 9426 9427 EXPECT_EQ("int b = 256 >> 1; /* foo\n" 9428 " bar */", 9429 format("int b =256>>1 ; /* foo\n" 9430 " bar */")); 9431 } 9432 9433 TEST_F(FormatTest, UnderstandsBinaryOperators) { 9434 verifyFormat("COMPARE(a, ==, b);"); 9435 verifyFormat("auto s = sizeof...(Ts) - 1;"); 9436 } 9437 9438 TEST_F(FormatTest, UnderstandsPointersToMembers) { 9439 verifyFormat("int A::*x;"); 9440 verifyFormat("int (S::*func)(void *);"); 9441 verifyFormat("void f() { int (S::*func)(void *); }"); 9442 verifyFormat("typedef bool *(Class::*Member)() const;"); 9443 verifyFormat("void f() {\n" 9444 " (a->*f)();\n" 9445 " a->*x;\n" 9446 " (a.*f)();\n" 9447 " ((*a).*f)();\n" 9448 " a.*x;\n" 9449 "}"); 9450 verifyFormat("void f() {\n" 9451 " (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n" 9452 " aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n" 9453 "}"); 9454 verifyFormat( 9455 "(aaaaaaaaaa->*bbbbbbb)(\n" 9456 " aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 9457 FormatStyle Style = getLLVMStyle(); 9458 Style.PointerAlignment = FormatStyle::PAS_Left; 9459 verifyFormat("typedef bool* (Class::*Member)() const;", Style); 9460 } 9461 9462 TEST_F(FormatTest, UnderstandsUnaryOperators) { 9463 verifyFormat("int a = -2;"); 9464 verifyFormat("f(-1, -2, -3);"); 9465 verifyFormat("a[-1] = 5;"); 9466 verifyFormat("int a = 5 + -2;"); 9467 verifyFormat("if (i == -1) {\n}"); 9468 verifyFormat("if (i != -1) {\n}"); 9469 verifyFormat("if (i > -1) {\n}"); 9470 verifyFormat("if (i < -1) {\n}"); 9471 verifyFormat("++(a->f());"); 9472 verifyFormat("--(a->f());"); 9473 verifyFormat("(a->f())++;"); 9474 verifyFormat("a[42]++;"); 9475 verifyFormat("if (!(a->f())) {\n}"); 9476 verifyFormat("if (!+i) {\n}"); 9477 verifyFormat("~&a;"); 9478 9479 verifyFormat("a-- > b;"); 9480 verifyFormat("b ? -a : c;"); 9481 verifyFormat("n * sizeof char16;"); 9482 verifyFormat("n * alignof char16;", getGoogleStyle()); 9483 verifyFormat("sizeof(char);"); 9484 verifyFormat("alignof(char);", getGoogleStyle()); 9485 9486 verifyFormat("return -1;"); 9487 verifyFormat("throw -1;"); 9488 verifyFormat("switch (a) {\n" 9489 "case -1:\n" 9490 " break;\n" 9491 "}"); 9492 verifyFormat("#define X -1"); 9493 verifyFormat("#define X -kConstant"); 9494 9495 verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};"); 9496 verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};"); 9497 9498 verifyFormat("int a = /* confusing comment */ -1;"); 9499 // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case. 9500 verifyFormat("int a = i /* confusing comment */++;"); 9501 9502 verifyFormat("co_yield -1;"); 9503 verifyFormat("co_return -1;"); 9504 9505 // Check that * is not treated as a binary operator when we set 9506 // PointerAlignment as PAS_Left after a keyword and not a declaration. 9507 FormatStyle PASLeftStyle = getLLVMStyle(); 9508 PASLeftStyle.PointerAlignment = FormatStyle::PAS_Left; 9509 verifyFormat("co_return *a;", PASLeftStyle); 9510 verifyFormat("co_await *a;", PASLeftStyle); 9511 verifyFormat("co_yield *a", PASLeftStyle); 9512 verifyFormat("return *a;", PASLeftStyle); 9513 } 9514 9515 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) { 9516 verifyFormat("if (!aaaaaaaaaa( // break\n" 9517 " aaaaa)) {\n" 9518 "}"); 9519 verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n" 9520 " aaaaa));"); 9521 verifyFormat("*aaa = aaaaaaa( // break\n" 9522 " bbbbbb);"); 9523 } 9524 9525 TEST_F(FormatTest, UnderstandsOverloadedOperators) { 9526 verifyFormat("bool operator<();"); 9527 verifyFormat("bool operator>();"); 9528 verifyFormat("bool operator=();"); 9529 verifyFormat("bool operator==();"); 9530 verifyFormat("bool operator!=();"); 9531 verifyFormat("int operator+();"); 9532 verifyFormat("int operator++();"); 9533 verifyFormat("int operator++(int) volatile noexcept;"); 9534 verifyFormat("bool operator,();"); 9535 verifyFormat("bool operator();"); 9536 verifyFormat("bool operator()();"); 9537 verifyFormat("bool operator[]();"); 9538 verifyFormat("operator bool();"); 9539 verifyFormat("operator int();"); 9540 verifyFormat("operator void *();"); 9541 verifyFormat("operator SomeType<int>();"); 9542 verifyFormat("operator SomeType<int, int>();"); 9543 verifyFormat("operator SomeType<SomeType<int>>();"); 9544 verifyFormat("operator< <>();"); 9545 verifyFormat("operator<< <>();"); 9546 verifyFormat("< <>"); 9547 9548 verifyFormat("void *operator new(std::size_t size);"); 9549 verifyFormat("void *operator new[](std::size_t size);"); 9550 verifyFormat("void operator delete(void *ptr);"); 9551 verifyFormat("void operator delete[](void *ptr);"); 9552 verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n" 9553 "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);"); 9554 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n" 9555 " aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;"); 9556 9557 verifyFormat( 9558 "ostream &operator<<(ostream &OutputStream,\n" 9559 " SomeReallyLongType WithSomeReallyLongValue);"); 9560 verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n" 9561 " const aaaaaaaaaaaaaaaaaaaaa &right) {\n" 9562 " return left.group < right.group;\n" 9563 "}"); 9564 verifyFormat("SomeType &operator=(const SomeType &S);"); 9565 verifyFormat("f.template operator()<int>();"); 9566 9567 verifyGoogleFormat("operator void*();"); 9568 verifyGoogleFormat("operator SomeType<SomeType<int>>();"); 9569 verifyGoogleFormat("operator ::A();"); 9570 9571 verifyFormat("using A::operator+;"); 9572 verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n" 9573 "int i;"); 9574 9575 // Calling an operator as a member function. 9576 verifyFormat("void f() { a.operator*(); }"); 9577 verifyFormat("void f() { a.operator*(b & b); }"); 9578 verifyFormat("void f() { a->operator&(a * b); }"); 9579 verifyFormat("void f() { NS::a.operator+(*b * *b); }"); 9580 // TODO: Calling an operator as a non-member function is hard to distinguish. 9581 // https://llvm.org/PR50629 9582 // verifyFormat("void f() { operator*(a & a); }"); 9583 // verifyFormat("void f() { operator&(a, b * b); }"); 9584 9585 verifyFormat("::operator delete(foo);"); 9586 verifyFormat("::operator new(n * sizeof(foo));"); 9587 verifyFormat("foo() { ::operator delete(foo); }"); 9588 verifyFormat("foo() { ::operator new(n * sizeof(foo)); }"); 9589 } 9590 9591 TEST_F(FormatTest, UnderstandsFunctionRefQualification) { 9592 verifyFormat("Deleted &operator=(const Deleted &) & = default;"); 9593 verifyFormat("Deleted &operator=(const Deleted &) && = delete;"); 9594 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;"); 9595 verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;"); 9596 verifyFormat("Deleted &operator=(const Deleted &) &;"); 9597 verifyFormat("Deleted &operator=(const Deleted &) &&;"); 9598 verifyFormat("SomeType MemberFunction(const Deleted &) &;"); 9599 verifyFormat("SomeType MemberFunction(const Deleted &) &&;"); 9600 verifyFormat("SomeType MemberFunction(const Deleted &) && {}"); 9601 verifyFormat("SomeType MemberFunction(const Deleted &) && final {}"); 9602 verifyFormat("SomeType MemberFunction(const Deleted &) && override {}"); 9603 verifyFormat("void Fn(T const &) const &;"); 9604 verifyFormat("void Fn(T const volatile &&) const volatile &&;"); 9605 verifyFormat("template <typename T>\n" 9606 "void F(T) && = delete;", 9607 getGoogleStyle()); 9608 9609 FormatStyle AlignLeft = getLLVMStyle(); 9610 AlignLeft.PointerAlignment = FormatStyle::PAS_Left; 9611 verifyFormat("void A::b() && {}", AlignLeft); 9612 verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft); 9613 verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;", 9614 AlignLeft); 9615 verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft); 9616 verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft); 9617 verifyFormat("auto Function(T t) & -> void {}", AlignLeft); 9618 verifyFormat("auto Function(T... t) & -> void {}", AlignLeft); 9619 verifyFormat("auto Function(T) & -> void {}", AlignLeft); 9620 verifyFormat("auto Function(T) & -> void;", AlignLeft); 9621 verifyFormat("void Fn(T const&) const&;", AlignLeft); 9622 verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft); 9623 9624 FormatStyle Spaces = getLLVMStyle(); 9625 Spaces.SpacesInCStyleCastParentheses = true; 9626 verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces); 9627 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces); 9628 verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces); 9629 verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces); 9630 9631 Spaces.SpacesInCStyleCastParentheses = false; 9632 Spaces.SpacesInParentheses = true; 9633 verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces); 9634 verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;", 9635 Spaces); 9636 verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces); 9637 verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces); 9638 9639 FormatStyle BreakTemplate = getLLVMStyle(); 9640 BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 9641 9642 verifyFormat("struct f {\n" 9643 " template <class T>\n" 9644 " int &foo(const std::string &str) &noexcept {}\n" 9645 "};", 9646 BreakTemplate); 9647 9648 verifyFormat("struct f {\n" 9649 " template <class T>\n" 9650 " int &foo(const std::string &str) &&noexcept {}\n" 9651 "};", 9652 BreakTemplate); 9653 9654 verifyFormat("struct f {\n" 9655 " template <class T>\n" 9656 " int &foo(const std::string &str) const &noexcept {}\n" 9657 "};", 9658 BreakTemplate); 9659 9660 verifyFormat("struct f {\n" 9661 " template <class T>\n" 9662 " int &foo(const std::string &str) const &noexcept {}\n" 9663 "};", 9664 BreakTemplate); 9665 9666 verifyFormat("struct f {\n" 9667 " template <class T>\n" 9668 " auto foo(const std::string &str) &&noexcept -> int & {}\n" 9669 "};", 9670 BreakTemplate); 9671 9672 FormatStyle AlignLeftBreakTemplate = getLLVMStyle(); 9673 AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations = 9674 FormatStyle::BTDS_Yes; 9675 AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left; 9676 9677 verifyFormat("struct f {\n" 9678 " template <class T>\n" 9679 " int& foo(const std::string& str) & noexcept {}\n" 9680 "};", 9681 AlignLeftBreakTemplate); 9682 9683 verifyFormat("struct f {\n" 9684 " template <class T>\n" 9685 " int& foo(const std::string& str) && noexcept {}\n" 9686 "};", 9687 AlignLeftBreakTemplate); 9688 9689 verifyFormat("struct f {\n" 9690 " template <class T>\n" 9691 " int& foo(const std::string& str) const& noexcept {}\n" 9692 "};", 9693 AlignLeftBreakTemplate); 9694 9695 verifyFormat("struct f {\n" 9696 " template <class T>\n" 9697 " int& foo(const std::string& str) const&& noexcept {}\n" 9698 "};", 9699 AlignLeftBreakTemplate); 9700 9701 verifyFormat("struct f {\n" 9702 " template <class T>\n" 9703 " auto foo(const std::string& str) && noexcept -> int& {}\n" 9704 "};", 9705 AlignLeftBreakTemplate); 9706 9707 // The `&` in `Type&` should not be confused with a trailing `&` of 9708 // DEPRECATED(reason) member function. 9709 verifyFormat("struct f {\n" 9710 " template <class T>\n" 9711 " DEPRECATED(reason)\n" 9712 " Type &foo(arguments) {}\n" 9713 "};", 9714 BreakTemplate); 9715 9716 verifyFormat("struct f {\n" 9717 " template <class T>\n" 9718 " DEPRECATED(reason)\n" 9719 " Type& foo(arguments) {}\n" 9720 "};", 9721 AlignLeftBreakTemplate); 9722 9723 verifyFormat("void (*foopt)(int) = &func;"); 9724 9725 FormatStyle DerivePointerAlignment = getLLVMStyle(); 9726 DerivePointerAlignment.DerivePointerAlignment = true; 9727 // There's always a space between the function and its trailing qualifiers. 9728 // This isn't evidence for PAS_Right (or for PAS_Left). 9729 std::string Prefix = "void a() &;\n" 9730 "void b() &;\n"; 9731 verifyFormat(Prefix + "int* x;", DerivePointerAlignment); 9732 verifyFormat(Prefix + "int *x;", DerivePointerAlignment); 9733 // Same if the function is an overloaded operator, and with &&. 9734 Prefix = "void operator()() &&;\n" 9735 "void operator()() &&;\n"; 9736 verifyFormat(Prefix + "int* x;", DerivePointerAlignment); 9737 verifyFormat(Prefix + "int *x;", DerivePointerAlignment); 9738 // However a space between cv-qualifiers and ref-qualifiers *is* evidence. 9739 Prefix = "void a() const &;\n" 9740 "void b() const &;\n"; 9741 EXPECT_EQ(Prefix + "int *x;", 9742 format(Prefix + "int* x;", DerivePointerAlignment)); 9743 } 9744 9745 TEST_F(FormatTest, UnderstandsNewAndDelete) { 9746 verifyFormat("void f() {\n" 9747 " A *a = new A;\n" 9748 " A *a = new (placement) A;\n" 9749 " delete a;\n" 9750 " delete (A *)a;\n" 9751 "}"); 9752 verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n" 9753 " typename aaaaaaaaaaaaaaaaaaaaaaaa();"); 9754 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9755 " new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n" 9756 " typename aaaaaaaaaaaaaaaaaaaaaaaa();"); 9757 verifyFormat("delete[] h->p;"); 9758 verifyFormat("delete[] (void *)p;"); 9759 9760 verifyFormat("void operator delete(void *foo) ATTRIB;"); 9761 verifyFormat("void operator new(void *foo) ATTRIB;"); 9762 verifyFormat("void operator delete[](void *foo) ATTRIB;"); 9763 verifyFormat("void operator delete(void *ptr) noexcept;"); 9764 } 9765 9766 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) { 9767 verifyFormat("int *f(int *a) {}"); 9768 verifyFormat("int main(int argc, char **argv) {}"); 9769 verifyFormat("Test::Test(int b) : a(b * b) {}"); 9770 verifyIndependentOfContext("f(a, *a);"); 9771 verifyFormat("void g() { f(*a); }"); 9772 verifyIndependentOfContext("int a = b * 10;"); 9773 verifyIndependentOfContext("int a = 10 * b;"); 9774 verifyIndependentOfContext("int a = b * c;"); 9775 verifyIndependentOfContext("int a += b * c;"); 9776 verifyIndependentOfContext("int a -= b * c;"); 9777 verifyIndependentOfContext("int a *= b * c;"); 9778 verifyIndependentOfContext("int a /= b * c;"); 9779 verifyIndependentOfContext("int a = *b;"); 9780 verifyIndependentOfContext("int a = *b * c;"); 9781 verifyIndependentOfContext("int a = b * *c;"); 9782 verifyIndependentOfContext("int a = b * (10);"); 9783 verifyIndependentOfContext("S << b * (10);"); 9784 verifyIndependentOfContext("return 10 * b;"); 9785 verifyIndependentOfContext("return *b * *c;"); 9786 verifyIndependentOfContext("return a & ~b;"); 9787 verifyIndependentOfContext("f(b ? *c : *d);"); 9788 verifyIndependentOfContext("int a = b ? *c : *d;"); 9789 verifyIndependentOfContext("*b = a;"); 9790 verifyIndependentOfContext("a * ~b;"); 9791 verifyIndependentOfContext("a * !b;"); 9792 verifyIndependentOfContext("a * +b;"); 9793 verifyIndependentOfContext("a * -b;"); 9794 verifyIndependentOfContext("a * ++b;"); 9795 verifyIndependentOfContext("a * --b;"); 9796 verifyIndependentOfContext("a[4] * b;"); 9797 verifyIndependentOfContext("a[a * a] = 1;"); 9798 verifyIndependentOfContext("f() * b;"); 9799 verifyIndependentOfContext("a * [self dostuff];"); 9800 verifyIndependentOfContext("int x = a * (a + b);"); 9801 verifyIndependentOfContext("(a *)(a + b);"); 9802 verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;"); 9803 verifyIndependentOfContext("int *pa = (int *)&a;"); 9804 verifyIndependentOfContext("return sizeof(int **);"); 9805 verifyIndependentOfContext("return sizeof(int ******);"); 9806 verifyIndependentOfContext("return (int **&)a;"); 9807 verifyIndependentOfContext("f((*PointerToArray)[10]);"); 9808 verifyFormat("void f(Type (*parameter)[10]) {}"); 9809 verifyFormat("void f(Type (¶meter)[10]) {}"); 9810 verifyGoogleFormat("return sizeof(int**);"); 9811 verifyIndependentOfContext("Type **A = static_cast<Type **>(P);"); 9812 verifyGoogleFormat("Type** A = static_cast<Type**>(P);"); 9813 verifyFormat("auto a = [](int **&, int ***) {};"); 9814 verifyFormat("auto PointerBinding = [](const char *S) {};"); 9815 verifyFormat("typedef typeof(int(int, int)) *MyFunc;"); 9816 verifyFormat("[](const decltype(*a) &value) {}"); 9817 verifyFormat("[](const typeof(*a) &value) {}"); 9818 verifyFormat("[](const _Atomic(a *) &value) {}"); 9819 verifyFormat("[](const __underlying_type(a) &value) {}"); 9820 verifyFormat("decltype(a * b) F();"); 9821 verifyFormat("typeof(a * b) F();"); 9822 verifyFormat("#define MACRO() [](A *a) { return 1; }"); 9823 verifyFormat("Constructor() : member([](A *a, B *b) {}) {}"); 9824 verifyIndependentOfContext("typedef void (*f)(int *a);"); 9825 verifyIndependentOfContext("int i{a * b};"); 9826 verifyIndependentOfContext("aaa && aaa->f();"); 9827 verifyIndependentOfContext("int x = ~*p;"); 9828 verifyFormat("Constructor() : a(a), area(width * height) {}"); 9829 verifyFormat("Constructor() : a(a), area(a, width * height) {}"); 9830 verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}"); 9831 verifyFormat("void f() { f(a, c * d); }"); 9832 verifyFormat("void f() { f(new a(), c * d); }"); 9833 verifyFormat("void f(const MyOverride &override);"); 9834 verifyFormat("void f(const MyFinal &final);"); 9835 verifyIndependentOfContext("bool a = f() && override.f();"); 9836 verifyIndependentOfContext("bool a = f() && final.f();"); 9837 9838 verifyIndependentOfContext("InvalidRegions[*R] = 0;"); 9839 9840 verifyIndependentOfContext("A<int *> a;"); 9841 verifyIndependentOfContext("A<int **> a;"); 9842 verifyIndependentOfContext("A<int *, int *> a;"); 9843 verifyIndependentOfContext("A<int *[]> a;"); 9844 verifyIndependentOfContext( 9845 "const char *const p = reinterpret_cast<const char *const>(q);"); 9846 verifyIndependentOfContext("A<int **, int **> a;"); 9847 verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);"); 9848 verifyFormat("for (char **a = b; *a; ++a) {\n}"); 9849 verifyFormat("for (; a && b;) {\n}"); 9850 verifyFormat("bool foo = true && [] { return false; }();"); 9851 9852 verifyFormat( 9853 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9854 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9855 9856 verifyGoogleFormat("int const* a = &b;"); 9857 verifyGoogleFormat("**outparam = 1;"); 9858 verifyGoogleFormat("*outparam = a * b;"); 9859 verifyGoogleFormat("int main(int argc, char** argv) {}"); 9860 verifyGoogleFormat("A<int*> a;"); 9861 verifyGoogleFormat("A<int**> a;"); 9862 verifyGoogleFormat("A<int*, int*> a;"); 9863 verifyGoogleFormat("A<int**, int**> a;"); 9864 verifyGoogleFormat("f(b ? *c : *d);"); 9865 verifyGoogleFormat("int a = b ? *c : *d;"); 9866 verifyGoogleFormat("Type* t = **x;"); 9867 verifyGoogleFormat("Type* t = *++*x;"); 9868 verifyGoogleFormat("*++*x;"); 9869 verifyGoogleFormat("Type* t = const_cast<T*>(&*x);"); 9870 verifyGoogleFormat("Type* t = x++ * y;"); 9871 verifyGoogleFormat( 9872 "const char* const p = reinterpret_cast<const char* const>(q);"); 9873 verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);"); 9874 verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);"); 9875 verifyGoogleFormat("template <typename T>\n" 9876 "void f(int i = 0, SomeType** temps = NULL);"); 9877 9878 FormatStyle Left = getLLVMStyle(); 9879 Left.PointerAlignment = FormatStyle::PAS_Left; 9880 verifyFormat("x = *a(x) = *a(y);", Left); 9881 verifyFormat("for (;; *a = b) {\n}", Left); 9882 verifyFormat("return *this += 1;", Left); 9883 verifyFormat("throw *x;", Left); 9884 verifyFormat("delete *x;", Left); 9885 verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left); 9886 verifyFormat("[](const decltype(*a)* ptr) {}", Left); 9887 verifyFormat("[](const typeof(*a)* ptr) {}", Left); 9888 verifyFormat("[](const _Atomic(a*)* ptr) {}", Left); 9889 verifyFormat("[](const __underlying_type(a)* ptr) {}", Left); 9890 verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left); 9891 verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left); 9892 verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left); 9893 verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left); 9894 9895 verifyIndependentOfContext("a = *(x + y);"); 9896 verifyIndependentOfContext("a = &(x + y);"); 9897 verifyIndependentOfContext("*(x + y).call();"); 9898 verifyIndependentOfContext("&(x + y)->call();"); 9899 verifyFormat("void f() { &(*I).first; }"); 9900 9901 verifyIndependentOfContext("f(b * /* confusing comment */ ++c);"); 9902 verifyFormat("f(* /* confusing comment */ foo);"); 9903 verifyFormat("void (* /*deleter*/)(const Slice &key, void *value)"); 9904 verifyFormat("void foo(int * // this is the first paramters\n" 9905 " ,\n" 9906 " int second);"); 9907 verifyFormat("double term = a * // first\n" 9908 " b;"); 9909 verifyFormat( 9910 "int *MyValues = {\n" 9911 " *A, // Operator detection might be confused by the '{'\n" 9912 " *BB // Operator detection might be confused by previous comment\n" 9913 "};"); 9914 9915 verifyIndependentOfContext("if (int *a = &b)"); 9916 verifyIndependentOfContext("if (int &a = *b)"); 9917 verifyIndependentOfContext("if (a & b[i])"); 9918 verifyIndependentOfContext("if constexpr (a & b[i])"); 9919 verifyIndependentOfContext("if CONSTEXPR (a & b[i])"); 9920 verifyIndependentOfContext("if (a * (b * c))"); 9921 verifyIndependentOfContext("if constexpr (a * (b * c))"); 9922 verifyIndependentOfContext("if CONSTEXPR (a * (b * c))"); 9923 verifyIndependentOfContext("if (a::b::c::d & b[i])"); 9924 verifyIndependentOfContext("if (*b[i])"); 9925 verifyIndependentOfContext("if (int *a = (&b))"); 9926 verifyIndependentOfContext("while (int *a = &b)"); 9927 verifyIndependentOfContext("while (a * (b * c))"); 9928 verifyIndependentOfContext("size = sizeof *a;"); 9929 verifyIndependentOfContext("if (a && (b = c))"); 9930 verifyFormat("void f() {\n" 9931 " for (const int &v : Values) {\n" 9932 " }\n" 9933 "}"); 9934 verifyFormat("for (int i = a * a; i < 10; ++i) {\n}"); 9935 verifyFormat("for (int i = 0; i < a * a; ++i) {\n}"); 9936 verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}"); 9937 9938 verifyFormat("#define A (!a * b)"); 9939 verifyFormat("#define MACRO \\\n" 9940 " int *i = a * b; \\\n" 9941 " void f(a *b);", 9942 getLLVMStyleWithColumns(19)); 9943 9944 verifyIndependentOfContext("A = new SomeType *[Length];"); 9945 verifyIndependentOfContext("A = new SomeType *[Length]();"); 9946 verifyIndependentOfContext("T **t = new T *;"); 9947 verifyIndependentOfContext("T **t = new T *();"); 9948 verifyGoogleFormat("A = new SomeType*[Length]();"); 9949 verifyGoogleFormat("A = new SomeType*[Length];"); 9950 verifyGoogleFormat("T** t = new T*;"); 9951 verifyGoogleFormat("T** t = new T*();"); 9952 9953 verifyFormat("STATIC_ASSERT((a & b) == 0);"); 9954 verifyFormat("STATIC_ASSERT(0 == (a & b));"); 9955 verifyFormat("template <bool a, bool b> " 9956 "typename t::if<x && y>::type f() {}"); 9957 verifyFormat("template <int *y> f() {}"); 9958 verifyFormat("vector<int *> v;"); 9959 verifyFormat("vector<int *const> v;"); 9960 verifyFormat("vector<int *const **const *> v;"); 9961 verifyFormat("vector<int *volatile> v;"); 9962 verifyFormat("vector<a *_Nonnull> v;"); 9963 verifyFormat("vector<a *_Nullable> v;"); 9964 verifyFormat("vector<a *_Null_unspecified> v;"); 9965 verifyFormat("vector<a *__ptr32> v;"); 9966 verifyFormat("vector<a *__ptr64> v;"); 9967 verifyFormat("vector<a *__capability> v;"); 9968 FormatStyle TypeMacros = getLLVMStyle(); 9969 TypeMacros.TypenameMacros = {"LIST"}; 9970 verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros); 9971 verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros); 9972 verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros); 9973 verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros); 9974 verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication 9975 9976 FormatStyle CustomQualifier = getLLVMStyle(); 9977 // Add identifiers that should not be parsed as a qualifier by default. 9978 CustomQualifier.AttributeMacros.push_back("__my_qualifier"); 9979 CustomQualifier.AttributeMacros.push_back("_My_qualifier"); 9980 CustomQualifier.AttributeMacros.push_back("my_other_qualifier"); 9981 verifyFormat("vector<a * __my_qualifier> parse_as_multiply;"); 9982 verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier); 9983 verifyFormat("vector<a * _My_qualifier> parse_as_multiply;"); 9984 verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier); 9985 verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;"); 9986 verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier); 9987 verifyFormat("vector<a * _NotAQualifier> v;"); 9988 verifyFormat("vector<a * __not_a_qualifier> v;"); 9989 verifyFormat("vector<a * b> v;"); 9990 verifyFormat("foo<b && false>();"); 9991 verifyFormat("foo<b & 1>();"); 9992 verifyFormat("decltype(*::std::declval<const T &>()) void F();"); 9993 verifyFormat("typeof(*::std::declval<const T &>()) void F();"); 9994 verifyFormat("_Atomic(*::std::declval<const T &>()) void F();"); 9995 verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();"); 9996 verifyFormat( 9997 "template <class T, class = typename std::enable_if<\n" 9998 " std::is_integral<T>::value &&\n" 9999 " (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n" 10000 "void F();", 10001 getLLVMStyleWithColumns(70)); 10002 verifyFormat("template <class T,\n" 10003 " class = typename std::enable_if<\n" 10004 " std::is_integral<T>::value &&\n" 10005 " (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n" 10006 " class U>\n" 10007 "void F();", 10008 getLLVMStyleWithColumns(70)); 10009 verifyFormat( 10010 "template <class T,\n" 10011 " class = typename ::std::enable_if<\n" 10012 " ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n" 10013 "void F();", 10014 getGoogleStyleWithColumns(68)); 10015 10016 verifyIndependentOfContext("MACRO(int *i);"); 10017 verifyIndependentOfContext("MACRO(auto *a);"); 10018 verifyIndependentOfContext("MACRO(const A *a);"); 10019 verifyIndependentOfContext("MACRO(_Atomic(A) *a);"); 10020 verifyIndependentOfContext("MACRO(decltype(A) *a);"); 10021 verifyIndependentOfContext("MACRO(typeof(A) *a);"); 10022 verifyIndependentOfContext("MACRO(__underlying_type(A) *a);"); 10023 verifyIndependentOfContext("MACRO(A *const a);"); 10024 verifyIndependentOfContext("MACRO(A *restrict a);"); 10025 verifyIndependentOfContext("MACRO(A *__restrict__ a);"); 10026 verifyIndependentOfContext("MACRO(A *__restrict a);"); 10027 verifyIndependentOfContext("MACRO(A *volatile a);"); 10028 verifyIndependentOfContext("MACRO(A *__volatile a);"); 10029 verifyIndependentOfContext("MACRO(A *__volatile__ a);"); 10030 verifyIndependentOfContext("MACRO(A *_Nonnull a);"); 10031 verifyIndependentOfContext("MACRO(A *_Nullable a);"); 10032 verifyIndependentOfContext("MACRO(A *_Null_unspecified a);"); 10033 verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);"); 10034 verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);"); 10035 verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);"); 10036 verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);"); 10037 verifyIndependentOfContext("MACRO(A *__ptr32 a);"); 10038 verifyIndependentOfContext("MACRO(A *__ptr64 a);"); 10039 verifyIndependentOfContext("MACRO(A *__capability);"); 10040 verifyIndependentOfContext("MACRO(A &__capability);"); 10041 verifyFormat("MACRO(A *__my_qualifier);"); // type declaration 10042 verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication 10043 // If we add __my_qualifier to AttributeMacros it should always be parsed as 10044 // a type declaration: 10045 verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier); 10046 verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier); 10047 // Also check that TypenameMacros prevents parsing it as multiplication: 10048 verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication 10049 verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type 10050 10051 verifyIndependentOfContext("MACRO('0' <= c && c <= '9');"); 10052 verifyFormat("void f() { f(float{1}, a * a); }"); 10053 verifyFormat("void f() { f(float(1), a * a); }"); 10054 10055 verifyFormat("f((void (*)(int))g);"); 10056 verifyFormat("f((void (&)(int))g);"); 10057 verifyFormat("f((void (^)(int))g);"); 10058 10059 // FIXME: Is there a way to make this work? 10060 // verifyIndependentOfContext("MACRO(A *a);"); 10061 verifyFormat("MACRO(A &B);"); 10062 verifyFormat("MACRO(A *B);"); 10063 verifyFormat("void f() { MACRO(A * B); }"); 10064 verifyFormat("void f() { MACRO(A & B); }"); 10065 10066 // This lambda was mis-formatted after D88956 (treating it as a binop): 10067 verifyFormat("auto x = [](const decltype(x) &ptr) {};"); 10068 verifyFormat("auto x = [](const decltype(x) *ptr) {};"); 10069 verifyFormat("#define lambda [](const decltype(x) &ptr) {}"); 10070 verifyFormat("#define lambda [](const decltype(x) *ptr) {}"); 10071 10072 verifyFormat("DatumHandle const *operator->() const { return input_; }"); 10073 verifyFormat("return options != nullptr && operator==(*options);"); 10074 10075 EXPECT_EQ("#define OP(x) \\\n" 10076 " ostream &operator<<(ostream &s, const A &a) { \\\n" 10077 " return s << a.DebugString(); \\\n" 10078 " }", 10079 format("#define OP(x) \\\n" 10080 " ostream &operator<<(ostream &s, const A &a) { \\\n" 10081 " return s << a.DebugString(); \\\n" 10082 " }", 10083 getLLVMStyleWithColumns(50))); 10084 10085 // FIXME: We cannot handle this case yet; we might be able to figure out that 10086 // foo<x> d > v; doesn't make sense. 10087 verifyFormat("foo<a<b && c> d> v;"); 10088 10089 FormatStyle PointerMiddle = getLLVMStyle(); 10090 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle; 10091 verifyFormat("delete *x;", PointerMiddle); 10092 verifyFormat("int * x;", PointerMiddle); 10093 verifyFormat("int *[] x;", PointerMiddle); 10094 verifyFormat("template <int * y> f() {}", PointerMiddle); 10095 verifyFormat("int * f(int * a) {}", PointerMiddle); 10096 verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle); 10097 verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle); 10098 verifyFormat("A<int *> a;", PointerMiddle); 10099 verifyFormat("A<int **> a;", PointerMiddle); 10100 verifyFormat("A<int *, int *> a;", PointerMiddle); 10101 verifyFormat("A<int *[]> a;", PointerMiddle); 10102 verifyFormat("A = new SomeType *[Length]();", PointerMiddle); 10103 verifyFormat("A = new SomeType *[Length];", PointerMiddle); 10104 verifyFormat("T ** t = new T *;", PointerMiddle); 10105 10106 // Member function reference qualifiers aren't binary operators. 10107 verifyFormat("string // break\n" 10108 "operator()() & {}"); 10109 verifyFormat("string // break\n" 10110 "operator()() && {}"); 10111 verifyGoogleFormat("template <typename T>\n" 10112 "auto x() & -> int {}"); 10113 10114 // Should be binary operators when used as an argument expression (overloaded 10115 // operator invoked as a member function). 10116 verifyFormat("void f() { a.operator()(a * a); }"); 10117 verifyFormat("void f() { a->operator()(a & a); }"); 10118 verifyFormat("void f() { a.operator()(*a & *a); }"); 10119 verifyFormat("void f() { a->operator()(*a * *a); }"); 10120 10121 verifyFormat("int operator()(T (&&)[N]) { return 1; }"); 10122 verifyFormat("int operator()(T (&)[N]) { return 0; }"); 10123 } 10124 10125 TEST_F(FormatTest, UnderstandsAttributes) { 10126 verifyFormat("SomeType s __attribute__((unused)) (InitValue);"); 10127 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n" 10128 "aaaaaaaaaaaaaaaaaaaaaaa(int i);"); 10129 verifyFormat("__attribute__((nodebug)) ::qualified_type f();"); 10130 FormatStyle AfterType = getLLVMStyle(); 10131 AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 10132 verifyFormat("__attribute__((nodebug)) void\n" 10133 "foo() {}\n", 10134 AfterType); 10135 verifyFormat("__unused void\n" 10136 "foo() {}", 10137 AfterType); 10138 10139 FormatStyle CustomAttrs = getLLVMStyle(); 10140 CustomAttrs.AttributeMacros.push_back("__unused"); 10141 CustomAttrs.AttributeMacros.push_back("__attr1"); 10142 CustomAttrs.AttributeMacros.push_back("__attr2"); 10143 CustomAttrs.AttributeMacros.push_back("no_underscore_attr"); 10144 verifyFormat("vector<SomeType *__attribute((foo))> v;"); 10145 verifyFormat("vector<SomeType *__attribute__((foo))> v;"); 10146 verifyFormat("vector<SomeType * __not_attribute__((foo))> v;"); 10147 // Check that it is parsed as a multiplication without AttributeMacros and 10148 // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros. 10149 verifyFormat("vector<SomeType * __attr1> v;"); 10150 verifyFormat("vector<SomeType __attr1 *> v;"); 10151 verifyFormat("vector<SomeType __attr1 *const> v;"); 10152 verifyFormat("vector<SomeType __attr1 * __attr2> v;"); 10153 verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs); 10154 verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs); 10155 verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs); 10156 verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs); 10157 verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs); 10158 verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs); 10159 verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs); 10160 10161 // Check that these are not parsed as function declarations: 10162 CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 10163 CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman; 10164 verifyFormat("SomeType s(InitValue);", CustomAttrs); 10165 verifyFormat("SomeType s{InitValue};", CustomAttrs); 10166 verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs); 10167 verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs); 10168 verifyFormat("SomeType s __unused(InitValue);", CustomAttrs); 10169 verifyFormat("SomeType s __unused{InitValue};", CustomAttrs); 10170 verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs); 10171 verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs); 10172 } 10173 10174 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) { 10175 // Check that qualifiers on pointers don't break parsing of casts. 10176 verifyFormat("x = (foo *const)*v;"); 10177 verifyFormat("x = (foo *volatile)*v;"); 10178 verifyFormat("x = (foo *restrict)*v;"); 10179 verifyFormat("x = (foo *__attribute__((foo)))*v;"); 10180 verifyFormat("x = (foo *_Nonnull)*v;"); 10181 verifyFormat("x = (foo *_Nullable)*v;"); 10182 verifyFormat("x = (foo *_Null_unspecified)*v;"); 10183 verifyFormat("x = (foo *_Nonnull)*v;"); 10184 verifyFormat("x = (foo *[[clang::attr]])*v;"); 10185 verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;"); 10186 verifyFormat("x = (foo *__ptr32)*v;"); 10187 verifyFormat("x = (foo *__ptr64)*v;"); 10188 verifyFormat("x = (foo *__capability)*v;"); 10189 10190 // Check that we handle multiple trailing qualifiers and skip them all to 10191 // determine that the expression is a cast to a pointer type. 10192 FormatStyle LongPointerRight = getLLVMStyleWithColumns(999); 10193 FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999); 10194 LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left; 10195 StringRef AllQualifiers = 10196 "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified " 10197 "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability"; 10198 verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight); 10199 verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft); 10200 10201 // Also check that address-of is not parsed as a binary bitwise-and: 10202 verifyFormat("x = (foo *const)&v;"); 10203 verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight); 10204 verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft); 10205 10206 // Check custom qualifiers: 10207 FormatStyle CustomQualifier = getLLVMStyleWithColumns(999); 10208 CustomQualifier.AttributeMacros.push_back("__my_qualifier"); 10209 verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier. 10210 verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier); 10211 verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(), 10212 CustomQualifier); 10213 verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(), 10214 CustomQualifier); 10215 10216 // Check that unknown identifiers result in binary operator parsing: 10217 verifyFormat("x = (foo * __unknown_qualifier) * v;"); 10218 verifyFormat("x = (foo * __unknown_qualifier) & v;"); 10219 } 10220 10221 TEST_F(FormatTest, UnderstandsSquareAttributes) { 10222 verifyFormat("SomeType s [[unused]] (InitValue);"); 10223 verifyFormat("SomeType s [[gnu::unused]] (InitValue);"); 10224 verifyFormat("SomeType s [[using gnu: unused]] (InitValue);"); 10225 verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}"); 10226 verifyFormat("void f() [[deprecated(\"so sorry\")]];"); 10227 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10228 " [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);"); 10229 verifyFormat("[[nodiscard]] bool f() { return false; }"); 10230 verifyFormat("class [[nodiscard]] f {\npublic:\n f() {}\n}"); 10231 verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n f() {}\n}"); 10232 verifyFormat("class [[gnu::unused]] f {\npublic:\n f() {}\n}"); 10233 verifyFormat("[[nodiscard]] ::qualified_type f();"); 10234 10235 // Make sure we do not mistake attributes for array subscripts. 10236 verifyFormat("int a() {}\n" 10237 "[[unused]] int b() {}\n"); 10238 verifyFormat("NSArray *arr;\n" 10239 "arr[[Foo() bar]];"); 10240 10241 // On the other hand, we still need to correctly find array subscripts. 10242 verifyFormat("int a = std::vector<int>{1, 2, 3}[0];"); 10243 10244 // Make sure that we do not mistake Objective-C method inside array literals 10245 // as attributes, even if those method names are also keywords. 10246 verifyFormat("@[ [foo bar] ];"); 10247 verifyFormat("@[ [NSArray class] ];"); 10248 verifyFormat("@[ [foo enum] ];"); 10249 10250 verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }"); 10251 10252 // Make sure we do not parse attributes as lambda introducers. 10253 FormatStyle MultiLineFunctions = getLLVMStyle(); 10254 MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 10255 verifyFormat("[[unused]] int b() {\n" 10256 " return 42;\n" 10257 "}\n", 10258 MultiLineFunctions); 10259 } 10260 10261 TEST_F(FormatTest, AttributeClass) { 10262 FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp); 10263 verifyFormat("class S {\n" 10264 " S(S&&) = default;\n" 10265 "};", 10266 Style); 10267 verifyFormat("class [[nodiscard]] S {\n" 10268 " S(S&&) = default;\n" 10269 "};", 10270 Style); 10271 verifyFormat("class __attribute((maybeunused)) S {\n" 10272 " S(S&&) = default;\n" 10273 "};", 10274 Style); 10275 verifyFormat("struct S {\n" 10276 " S(S&&) = default;\n" 10277 "};", 10278 Style); 10279 verifyFormat("struct [[nodiscard]] S {\n" 10280 " S(S&&) = default;\n" 10281 "};", 10282 Style); 10283 } 10284 10285 TEST_F(FormatTest, AttributesAfterMacro) { 10286 FormatStyle Style = getLLVMStyle(); 10287 verifyFormat("MACRO;\n" 10288 "__attribute__((maybe_unused)) int foo() {\n" 10289 " //...\n" 10290 "}"); 10291 10292 verifyFormat("MACRO;\n" 10293 "[[nodiscard]] int foo() {\n" 10294 " //...\n" 10295 "}"); 10296 10297 EXPECT_EQ("MACRO\n\n" 10298 "__attribute__((maybe_unused)) int foo() {\n" 10299 " //...\n" 10300 "}", 10301 format("MACRO\n\n" 10302 "__attribute__((maybe_unused)) int foo() {\n" 10303 " //...\n" 10304 "}")); 10305 10306 EXPECT_EQ("MACRO\n\n" 10307 "[[nodiscard]] int foo() {\n" 10308 " //...\n" 10309 "}", 10310 format("MACRO\n\n" 10311 "[[nodiscard]] int foo() {\n" 10312 " //...\n" 10313 "}")); 10314 } 10315 10316 TEST_F(FormatTest, AttributePenaltyBreaking) { 10317 FormatStyle Style = getLLVMStyle(); 10318 verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n" 10319 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}", 10320 Style); 10321 verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n" 10322 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}", 10323 Style); 10324 verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const " 10325 "shared_ptr<ALongTypeName> &C d) {\n}", 10326 Style); 10327 } 10328 10329 TEST_F(FormatTest, UnderstandsEllipsis) { 10330 FormatStyle Style = getLLVMStyle(); 10331 verifyFormat("int printf(const char *fmt, ...);"); 10332 verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }"); 10333 verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}"); 10334 10335 verifyFormat("template <int *...PP> a;", Style); 10336 10337 Style.PointerAlignment = FormatStyle::PAS_Left; 10338 verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style); 10339 10340 verifyFormat("template <int*... PP> a;", Style); 10341 10342 Style.PointerAlignment = FormatStyle::PAS_Middle; 10343 verifyFormat("template <int *... PP> a;", Style); 10344 } 10345 10346 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) { 10347 EXPECT_EQ("int *a;\n" 10348 "int *a;\n" 10349 "int *a;", 10350 format("int *a;\n" 10351 "int* a;\n" 10352 "int *a;", 10353 getGoogleStyle())); 10354 EXPECT_EQ("int* a;\n" 10355 "int* a;\n" 10356 "int* a;", 10357 format("int* a;\n" 10358 "int* a;\n" 10359 "int *a;", 10360 getGoogleStyle())); 10361 EXPECT_EQ("int *a;\n" 10362 "int *a;\n" 10363 "int *a;", 10364 format("int *a;\n" 10365 "int * a;\n" 10366 "int * a;", 10367 getGoogleStyle())); 10368 EXPECT_EQ("auto x = [] {\n" 10369 " int *a;\n" 10370 " int *a;\n" 10371 " int *a;\n" 10372 "};", 10373 format("auto x=[]{int *a;\n" 10374 "int * a;\n" 10375 "int * a;};", 10376 getGoogleStyle())); 10377 } 10378 10379 TEST_F(FormatTest, UnderstandsRvalueReferences) { 10380 verifyFormat("int f(int &&a) {}"); 10381 verifyFormat("int f(int a, char &&b) {}"); 10382 verifyFormat("void f() { int &&a = b; }"); 10383 verifyGoogleFormat("int f(int a, char&& b) {}"); 10384 verifyGoogleFormat("void f() { int&& a = b; }"); 10385 10386 verifyIndependentOfContext("A<int &&> a;"); 10387 verifyIndependentOfContext("A<int &&, int &&> a;"); 10388 verifyGoogleFormat("A<int&&> a;"); 10389 verifyGoogleFormat("A<int&&, int&&> a;"); 10390 10391 // Not rvalue references: 10392 verifyFormat("template <bool B, bool C> class A {\n" 10393 " static_assert(B && C, \"Something is wrong\");\n" 10394 "};"); 10395 verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))"); 10396 verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))"); 10397 verifyFormat("#define A(a, b) (a && b)"); 10398 } 10399 10400 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) { 10401 verifyFormat("void f() {\n" 10402 " x[aaaaaaaaa -\n" 10403 " b] = 23;\n" 10404 "}", 10405 getLLVMStyleWithColumns(15)); 10406 } 10407 10408 TEST_F(FormatTest, FormatsCasts) { 10409 verifyFormat("Type *A = static_cast<Type *>(P);"); 10410 verifyFormat("Type *A = (Type *)P;"); 10411 verifyFormat("Type *A = (vector<Type *, int *>)P;"); 10412 verifyFormat("int a = (int)(2.0f);"); 10413 verifyFormat("int a = (int)2.0f;"); 10414 verifyFormat("x[(int32)y];"); 10415 verifyFormat("x = (int32)y;"); 10416 verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)"); 10417 verifyFormat("int a = (int)*b;"); 10418 verifyFormat("int a = (int)2.0f;"); 10419 verifyFormat("int a = (int)~0;"); 10420 verifyFormat("int a = (int)++a;"); 10421 verifyFormat("int a = (int)sizeof(int);"); 10422 verifyFormat("int a = (int)+2;"); 10423 verifyFormat("my_int a = (my_int)2.0f;"); 10424 verifyFormat("my_int a = (my_int)sizeof(int);"); 10425 verifyFormat("return (my_int)aaa;"); 10426 verifyFormat("#define x ((int)-1)"); 10427 verifyFormat("#define LENGTH(x, y) (x) - (y) + 1"); 10428 verifyFormat("#define p(q) ((int *)&q)"); 10429 verifyFormat("fn(a)(b) + 1;"); 10430 10431 verifyFormat("void f() { my_int a = (my_int)*b; }"); 10432 verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }"); 10433 verifyFormat("my_int a = (my_int)~0;"); 10434 verifyFormat("my_int a = (my_int)++a;"); 10435 verifyFormat("my_int a = (my_int)-2;"); 10436 verifyFormat("my_int a = (my_int)1;"); 10437 verifyFormat("my_int a = (my_int *)1;"); 10438 verifyFormat("my_int a = (const my_int)-1;"); 10439 verifyFormat("my_int a = (const my_int *)-1;"); 10440 verifyFormat("my_int a = (my_int)(my_int)-1;"); 10441 verifyFormat("my_int a = (ns::my_int)-2;"); 10442 verifyFormat("case (my_int)ONE:"); 10443 verifyFormat("auto x = (X)this;"); 10444 // Casts in Obj-C style calls used to not be recognized as such. 10445 verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle()); 10446 10447 // FIXME: single value wrapped with paren will be treated as cast. 10448 verifyFormat("void f(int i = (kValue)*kMask) {}"); 10449 10450 verifyFormat("{ (void)F; }"); 10451 10452 // Don't break after a cast's 10453 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 10454 " (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n" 10455 " bbbbbbbbbbbbbbbbbbbbbb);"); 10456 10457 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(x)"); 10458 verifyFormat("#define CONF_BOOL(x) (bool *)(x)"); 10459 verifyFormat("#define CONF_BOOL(x) (bool)(x)"); 10460 verifyFormat("bool *y = (bool *)(void *)(x);"); 10461 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)(x)"); 10462 verifyFormat("bool *y = (bool *)(void *)(int)(x);"); 10463 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)foo(x)"); 10464 verifyFormat("bool *y = (bool *)(void *)(int)foo(x);"); 10465 10466 // These are not casts. 10467 verifyFormat("void f(int *) {}"); 10468 verifyFormat("f(foo)->b;"); 10469 verifyFormat("f(foo).b;"); 10470 verifyFormat("f(foo)(b);"); 10471 verifyFormat("f(foo)[b];"); 10472 verifyFormat("[](foo) { return 4; }(bar);"); 10473 verifyFormat("(*funptr)(foo)[4];"); 10474 verifyFormat("funptrs[4](foo)[4];"); 10475 verifyFormat("void f(int *);"); 10476 verifyFormat("void f(int *) = 0;"); 10477 verifyFormat("void f(SmallVector<int>) {}"); 10478 verifyFormat("void f(SmallVector<int>);"); 10479 verifyFormat("void f(SmallVector<int>) = 0;"); 10480 verifyFormat("void f(int i = (kA * kB) & kMask) {}"); 10481 verifyFormat("int a = sizeof(int) * b;"); 10482 verifyFormat("int a = alignof(int) * b;", getGoogleStyle()); 10483 verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;"); 10484 verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");"); 10485 verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;"); 10486 10487 // These are not casts, but at some point were confused with casts. 10488 verifyFormat("virtual void foo(int *) override;"); 10489 verifyFormat("virtual void foo(char &) const;"); 10490 verifyFormat("virtual void foo(int *a, char *) const;"); 10491 verifyFormat("int a = sizeof(int *) + b;"); 10492 verifyFormat("int a = alignof(int *) + b;", getGoogleStyle()); 10493 verifyFormat("bool b = f(g<int>) && c;"); 10494 verifyFormat("typedef void (*f)(int i) func;"); 10495 verifyFormat("void operator++(int) noexcept;"); 10496 verifyFormat("void operator++(int &) noexcept;"); 10497 verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t " 10498 "&) noexcept;"); 10499 verifyFormat( 10500 "void operator delete(std::size_t, const std::nothrow_t &) noexcept;"); 10501 verifyFormat("void operator delete(const std::nothrow_t &) noexcept;"); 10502 verifyFormat("void operator delete(std::nothrow_t &) noexcept;"); 10503 verifyFormat("void operator delete(nothrow_t &) noexcept;"); 10504 verifyFormat("void operator delete(foo &) noexcept;"); 10505 verifyFormat("void operator delete(foo) noexcept;"); 10506 verifyFormat("void operator delete(int) noexcept;"); 10507 verifyFormat("void operator delete(int &) noexcept;"); 10508 verifyFormat("void operator delete(int &) volatile noexcept;"); 10509 verifyFormat("void operator delete(int &) const"); 10510 verifyFormat("void operator delete(int &) = default"); 10511 verifyFormat("void operator delete(int &) = delete"); 10512 verifyFormat("void operator delete(int &) [[noreturn]]"); 10513 verifyFormat("void operator delete(int &) throw();"); 10514 verifyFormat("void operator delete(int &) throw(int);"); 10515 verifyFormat("auto operator delete(int &) -> int;"); 10516 verifyFormat("auto operator delete(int &) override"); 10517 verifyFormat("auto operator delete(int &) final"); 10518 10519 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n" 10520 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 10521 // FIXME: The indentation here is not ideal. 10522 verifyFormat( 10523 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10524 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n" 10525 " [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];"); 10526 } 10527 10528 TEST_F(FormatTest, FormatsFunctionTypes) { 10529 verifyFormat("A<bool()> a;"); 10530 verifyFormat("A<SomeType()> a;"); 10531 verifyFormat("A<void (*)(int, std::string)> a;"); 10532 verifyFormat("A<void *(int)>;"); 10533 verifyFormat("void *(*a)(int *, SomeType *);"); 10534 verifyFormat("int (*func)(void *);"); 10535 verifyFormat("void f() { int (*func)(void *); }"); 10536 verifyFormat("template <class CallbackClass>\n" 10537 "using MyCallback = void (CallbackClass::*)(SomeObject *Data);"); 10538 10539 verifyGoogleFormat("A<void*(int*, SomeType*)>;"); 10540 verifyGoogleFormat("void* (*a)(int);"); 10541 verifyGoogleFormat( 10542 "template <class CallbackClass>\n" 10543 "using MyCallback = void (CallbackClass::*)(SomeObject* Data);"); 10544 10545 // Other constructs can look somewhat like function types: 10546 verifyFormat("A<sizeof(*x)> a;"); 10547 verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)"); 10548 verifyFormat("some_var = function(*some_pointer_var)[0];"); 10549 verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }"); 10550 verifyFormat("int x = f(&h)();"); 10551 verifyFormat("returnsFunction(¶m1, ¶m2)(param);"); 10552 verifyFormat("std::function<\n" 10553 " LooooooooooongTemplatedType<\n" 10554 " SomeType>*(\n" 10555 " LooooooooooooooooongType type)>\n" 10556 " function;", 10557 getGoogleStyleWithColumns(40)); 10558 } 10559 10560 TEST_F(FormatTest, FormatsPointersToArrayTypes) { 10561 verifyFormat("A (*foo_)[6];"); 10562 verifyFormat("vector<int> (*foo_)[6];"); 10563 } 10564 10565 TEST_F(FormatTest, BreaksLongVariableDeclarations) { 10566 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10567 " LoooooooooooooooooooooooooooooooooooooooongVariable;"); 10568 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n" 10569 " LoooooooooooooooooooooooooooooooooooooooongVariable;"); 10570 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10571 " *LoooooooooooooooooooooooooooooooooooooooongVariable;"); 10572 10573 // Different ways of ()-initializiation. 10574 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10575 " LoooooooooooooooooooooooooooooooooooooooongVariable(1);"); 10576 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10577 " LoooooooooooooooooooooooooooooooooooooooongVariable(a);"); 10578 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10579 " LoooooooooooooooooooooooooooooooooooooooongVariable({});"); 10580 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10581 " LoooooooooooooooooooooooooooooooooooooongVariable([A a]);"); 10582 10583 // Lambdas should not confuse the variable declaration heuristic. 10584 verifyFormat("LooooooooooooooooongType\n" 10585 " variable(nullptr, [](A *a) {});", 10586 getLLVMStyleWithColumns(40)); 10587 } 10588 10589 TEST_F(FormatTest, BreaksLongDeclarations) { 10590 verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n" 10591 " AnotherNameForTheLongType;"); 10592 verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n" 10593 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 10594 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10595 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();"); 10596 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n" 10597 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();"); 10598 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10599 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10600 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n" 10601 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10602 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n" 10603 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10604 verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n" 10605 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10606 verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n" 10607 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10608 verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n" 10609 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10610 verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n" 10611 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10612 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10613 "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);"); 10614 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10615 "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}"); 10616 FormatStyle Indented = getLLVMStyle(); 10617 Indented.IndentWrappedFunctionNames = true; 10618 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10619 " LoooooooooooooooooooooooooooooooongFunctionDeclaration();", 10620 Indented); 10621 verifyFormat( 10622 "LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10623 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 10624 Indented); 10625 verifyFormat( 10626 "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n" 10627 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 10628 Indented); 10629 verifyFormat( 10630 "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n" 10631 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 10632 Indented); 10633 10634 // FIXME: Without the comment, this breaks after "(". 10635 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType // break\n" 10636 " (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();", 10637 getGoogleStyle()); 10638 10639 verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n" 10640 " int LoooooooooooooooooooongParam2) {}"); 10641 verifyFormat( 10642 "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n" 10643 " SourceLocation L, IdentifierIn *II,\n" 10644 " Type *T) {}"); 10645 verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n" 10646 "ReallyReaaallyLongFunctionName(\n" 10647 " const std::string &SomeParameter,\n" 10648 " const SomeType<string, SomeOtherTemplateParameter>\n" 10649 " &ReallyReallyLongParameterName,\n" 10650 " const SomeType<string, SomeOtherTemplateParameter>\n" 10651 " &AnotherLongParameterName) {}"); 10652 verifyFormat("template <typename A>\n" 10653 "SomeLoooooooooooooooooooooongType<\n" 10654 " typename some_namespace::SomeOtherType<A>::Type>\n" 10655 "Function() {}"); 10656 10657 verifyGoogleFormat( 10658 "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n" 10659 " aaaaaaaaaaaaaaaaaaaaaaa;"); 10660 verifyGoogleFormat( 10661 "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n" 10662 " SourceLocation L) {}"); 10663 verifyGoogleFormat( 10664 "some_namespace::LongReturnType\n" 10665 "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n" 10666 " int first_long_parameter, int second_parameter) {}"); 10667 10668 verifyGoogleFormat("template <typename T>\n" 10669 "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n" 10670 "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}"); 10671 verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 10672 " int aaaaaaaaaaaaaaaaaaaaaaa);"); 10673 10674 verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n" 10675 " const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10676 " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 10677 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 10678 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n" 10679 " aaaaaaaaaaaaaaaaaaaaaaaa);"); 10680 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 10681 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 10682 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n" 10683 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 10684 10685 verifyFormat("template <typename T> // Templates on own line.\n" 10686 "static int // Some comment.\n" 10687 "MyFunction(int a);", 10688 getLLVMStyle()); 10689 } 10690 10691 TEST_F(FormatTest, FormatsAccessModifiers) { 10692 FormatStyle Style = getLLVMStyle(); 10693 EXPECT_EQ(Style.EmptyLineBeforeAccessModifier, 10694 FormatStyle::ELBAMS_LogicalBlock); 10695 verifyFormat("struct foo {\n" 10696 "private:\n" 10697 " void f() {}\n" 10698 "\n" 10699 "private:\n" 10700 " int i;\n" 10701 "\n" 10702 "protected:\n" 10703 " int j;\n" 10704 "};\n", 10705 Style); 10706 verifyFormat("struct foo {\n" 10707 "private:\n" 10708 " void f() {}\n" 10709 "\n" 10710 "private:\n" 10711 " int i;\n" 10712 "\n" 10713 "protected:\n" 10714 " int j;\n" 10715 "};\n", 10716 "struct foo {\n" 10717 "private:\n" 10718 " void f() {}\n" 10719 "private:\n" 10720 " int i;\n" 10721 "protected:\n" 10722 " int j;\n" 10723 "};\n", 10724 Style); 10725 verifyFormat("struct foo { /* comment */\n" 10726 "private:\n" 10727 " int i;\n" 10728 " // comment\n" 10729 "private:\n" 10730 " int j;\n" 10731 "};\n", 10732 Style); 10733 verifyFormat("struct foo {\n" 10734 "#ifdef FOO\n" 10735 "#endif\n" 10736 "private:\n" 10737 " int i;\n" 10738 "#ifdef FOO\n" 10739 "private:\n" 10740 "#endif\n" 10741 " int j;\n" 10742 "};\n", 10743 Style); 10744 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 10745 verifyFormat("struct foo {\n" 10746 "private:\n" 10747 " void f() {}\n" 10748 "private:\n" 10749 " int i;\n" 10750 "protected:\n" 10751 " int j;\n" 10752 "};\n", 10753 Style); 10754 verifyFormat("struct foo {\n" 10755 "private:\n" 10756 " void f() {}\n" 10757 "private:\n" 10758 " int i;\n" 10759 "protected:\n" 10760 " int j;\n" 10761 "};\n", 10762 "struct foo {\n" 10763 "\n" 10764 "private:\n" 10765 " void f() {}\n" 10766 "\n" 10767 "private:\n" 10768 " int i;\n" 10769 "\n" 10770 "protected:\n" 10771 " int j;\n" 10772 "};\n", 10773 Style); 10774 verifyFormat("struct foo { /* comment */\n" 10775 "private:\n" 10776 " int i;\n" 10777 " // comment\n" 10778 "private:\n" 10779 " int j;\n" 10780 "};\n", 10781 "struct foo { /* comment */\n" 10782 "\n" 10783 "private:\n" 10784 " int i;\n" 10785 " // comment\n" 10786 "\n" 10787 "private:\n" 10788 " int j;\n" 10789 "};\n", 10790 Style); 10791 verifyFormat("struct foo {\n" 10792 "#ifdef FOO\n" 10793 "#endif\n" 10794 "private:\n" 10795 " int i;\n" 10796 "#ifdef FOO\n" 10797 "private:\n" 10798 "#endif\n" 10799 " int j;\n" 10800 "};\n", 10801 "struct foo {\n" 10802 "#ifdef FOO\n" 10803 "#endif\n" 10804 "\n" 10805 "private:\n" 10806 " int i;\n" 10807 "#ifdef FOO\n" 10808 "\n" 10809 "private:\n" 10810 "#endif\n" 10811 " int j;\n" 10812 "};\n", 10813 Style); 10814 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 10815 verifyFormat("struct foo {\n" 10816 "private:\n" 10817 " void f() {}\n" 10818 "\n" 10819 "private:\n" 10820 " int i;\n" 10821 "\n" 10822 "protected:\n" 10823 " int j;\n" 10824 "};\n", 10825 Style); 10826 verifyFormat("struct foo {\n" 10827 "private:\n" 10828 " void f() {}\n" 10829 "\n" 10830 "private:\n" 10831 " int i;\n" 10832 "\n" 10833 "protected:\n" 10834 " int j;\n" 10835 "};\n", 10836 "struct foo {\n" 10837 "private:\n" 10838 " void f() {}\n" 10839 "private:\n" 10840 " int i;\n" 10841 "protected:\n" 10842 " int j;\n" 10843 "};\n", 10844 Style); 10845 verifyFormat("struct foo { /* comment */\n" 10846 "private:\n" 10847 " int i;\n" 10848 " // comment\n" 10849 "\n" 10850 "private:\n" 10851 " int j;\n" 10852 "};\n", 10853 "struct foo { /* comment */\n" 10854 "private:\n" 10855 " int i;\n" 10856 " // comment\n" 10857 "\n" 10858 "private:\n" 10859 " int j;\n" 10860 "};\n", 10861 Style); 10862 verifyFormat("struct foo {\n" 10863 "#ifdef FOO\n" 10864 "#endif\n" 10865 "\n" 10866 "private:\n" 10867 " int i;\n" 10868 "#ifdef FOO\n" 10869 "\n" 10870 "private:\n" 10871 "#endif\n" 10872 " int j;\n" 10873 "};\n", 10874 "struct foo {\n" 10875 "#ifdef FOO\n" 10876 "#endif\n" 10877 "private:\n" 10878 " int i;\n" 10879 "#ifdef FOO\n" 10880 "private:\n" 10881 "#endif\n" 10882 " int j;\n" 10883 "};\n", 10884 Style); 10885 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 10886 EXPECT_EQ("struct foo {\n" 10887 "\n" 10888 "private:\n" 10889 " void f() {}\n" 10890 "\n" 10891 "private:\n" 10892 " int i;\n" 10893 "\n" 10894 "protected:\n" 10895 " int j;\n" 10896 "};\n", 10897 format("struct foo {\n" 10898 "\n" 10899 "private:\n" 10900 " void f() {}\n" 10901 "\n" 10902 "private:\n" 10903 " int i;\n" 10904 "\n" 10905 "protected:\n" 10906 " int j;\n" 10907 "};\n", 10908 Style)); 10909 verifyFormat("struct foo {\n" 10910 "private:\n" 10911 " void f() {}\n" 10912 "private:\n" 10913 " int i;\n" 10914 "protected:\n" 10915 " int j;\n" 10916 "};\n", 10917 Style); 10918 EXPECT_EQ("struct foo { /* comment */\n" 10919 "\n" 10920 "private:\n" 10921 " int i;\n" 10922 " // comment\n" 10923 "\n" 10924 "private:\n" 10925 " int j;\n" 10926 "};\n", 10927 format("struct foo { /* comment */\n" 10928 "\n" 10929 "private:\n" 10930 " int i;\n" 10931 " // comment\n" 10932 "\n" 10933 "private:\n" 10934 " int j;\n" 10935 "};\n", 10936 Style)); 10937 verifyFormat("struct foo { /* comment */\n" 10938 "private:\n" 10939 " int i;\n" 10940 " // comment\n" 10941 "private:\n" 10942 " int j;\n" 10943 "};\n", 10944 Style); 10945 EXPECT_EQ("struct foo {\n" 10946 "#ifdef FOO\n" 10947 "#endif\n" 10948 "\n" 10949 "private:\n" 10950 " int i;\n" 10951 "#ifdef FOO\n" 10952 "\n" 10953 "private:\n" 10954 "#endif\n" 10955 " int j;\n" 10956 "};\n", 10957 format("struct foo {\n" 10958 "#ifdef FOO\n" 10959 "#endif\n" 10960 "\n" 10961 "private:\n" 10962 " int i;\n" 10963 "#ifdef FOO\n" 10964 "\n" 10965 "private:\n" 10966 "#endif\n" 10967 " int j;\n" 10968 "};\n", 10969 Style)); 10970 verifyFormat("struct foo {\n" 10971 "#ifdef FOO\n" 10972 "#endif\n" 10973 "private:\n" 10974 " int i;\n" 10975 "#ifdef FOO\n" 10976 "private:\n" 10977 "#endif\n" 10978 " int j;\n" 10979 "};\n", 10980 Style); 10981 10982 FormatStyle NoEmptyLines = getLLVMStyle(); 10983 NoEmptyLines.MaxEmptyLinesToKeep = 0; 10984 verifyFormat("struct foo {\n" 10985 "private:\n" 10986 " void f() {}\n" 10987 "\n" 10988 "private:\n" 10989 " int i;\n" 10990 "\n" 10991 "public:\n" 10992 "protected:\n" 10993 " int j;\n" 10994 "};\n", 10995 NoEmptyLines); 10996 10997 NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 10998 verifyFormat("struct foo {\n" 10999 "private:\n" 11000 " void f() {}\n" 11001 "private:\n" 11002 " int i;\n" 11003 "public:\n" 11004 "protected:\n" 11005 " int j;\n" 11006 "};\n", 11007 NoEmptyLines); 11008 11009 NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11010 verifyFormat("struct foo {\n" 11011 "private:\n" 11012 " void f() {}\n" 11013 "\n" 11014 "private:\n" 11015 " int i;\n" 11016 "\n" 11017 "public:\n" 11018 "\n" 11019 "protected:\n" 11020 " int j;\n" 11021 "};\n", 11022 NoEmptyLines); 11023 } 11024 11025 TEST_F(FormatTest, FormatsAfterAccessModifiers) { 11026 11027 FormatStyle Style = getLLVMStyle(); 11028 EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never); 11029 verifyFormat("struct foo {\n" 11030 "private:\n" 11031 " void f() {}\n" 11032 "\n" 11033 "private:\n" 11034 " int i;\n" 11035 "\n" 11036 "protected:\n" 11037 " int j;\n" 11038 "};\n", 11039 Style); 11040 11041 // Check if lines are removed. 11042 verifyFormat("struct foo {\n" 11043 "private:\n" 11044 " void f() {}\n" 11045 "\n" 11046 "private:\n" 11047 " int i;\n" 11048 "\n" 11049 "protected:\n" 11050 " int j;\n" 11051 "};\n", 11052 "struct foo {\n" 11053 "private:\n" 11054 "\n" 11055 " void f() {}\n" 11056 "\n" 11057 "private:\n" 11058 "\n" 11059 " int i;\n" 11060 "\n" 11061 "protected:\n" 11062 "\n" 11063 " int j;\n" 11064 "};\n", 11065 Style); 11066 11067 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11068 verifyFormat("struct foo {\n" 11069 "private:\n" 11070 "\n" 11071 " void f() {}\n" 11072 "\n" 11073 "private:\n" 11074 "\n" 11075 " int i;\n" 11076 "\n" 11077 "protected:\n" 11078 "\n" 11079 " int j;\n" 11080 "};\n", 11081 Style); 11082 11083 // Check if lines are added. 11084 verifyFormat("struct foo {\n" 11085 "private:\n" 11086 "\n" 11087 " void f() {}\n" 11088 "\n" 11089 "private:\n" 11090 "\n" 11091 " int i;\n" 11092 "\n" 11093 "protected:\n" 11094 "\n" 11095 " int j;\n" 11096 "};\n", 11097 "struct foo {\n" 11098 "private:\n" 11099 " void f() {}\n" 11100 "\n" 11101 "private:\n" 11102 " int i;\n" 11103 "\n" 11104 "protected:\n" 11105 " int j;\n" 11106 "};\n", 11107 Style); 11108 11109 // Leave tests rely on the code layout, test::messUp can not be used. 11110 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11111 Style.MaxEmptyLinesToKeep = 0u; 11112 verifyFormat("struct foo {\n" 11113 "private:\n" 11114 " void f() {}\n" 11115 "\n" 11116 "private:\n" 11117 " int i;\n" 11118 "\n" 11119 "protected:\n" 11120 " int j;\n" 11121 "};\n", 11122 Style); 11123 11124 // Check if MaxEmptyLinesToKeep is respected. 11125 EXPECT_EQ("struct foo {\n" 11126 "private:\n" 11127 " void f() {}\n" 11128 "\n" 11129 "private:\n" 11130 " int i;\n" 11131 "\n" 11132 "protected:\n" 11133 " int j;\n" 11134 "};\n", 11135 format("struct foo {\n" 11136 "private:\n" 11137 "\n\n\n" 11138 " void f() {}\n" 11139 "\n" 11140 "private:\n" 11141 "\n\n\n" 11142 " int i;\n" 11143 "\n" 11144 "protected:\n" 11145 "\n\n\n" 11146 " int j;\n" 11147 "};\n", 11148 Style)); 11149 11150 Style.MaxEmptyLinesToKeep = 1u; 11151 EXPECT_EQ("struct foo {\n" 11152 "private:\n" 11153 "\n" 11154 " void f() {}\n" 11155 "\n" 11156 "private:\n" 11157 "\n" 11158 " int i;\n" 11159 "\n" 11160 "protected:\n" 11161 "\n" 11162 " int j;\n" 11163 "};\n", 11164 format("struct foo {\n" 11165 "private:\n" 11166 "\n" 11167 " void f() {}\n" 11168 "\n" 11169 "private:\n" 11170 "\n" 11171 " int i;\n" 11172 "\n" 11173 "protected:\n" 11174 "\n" 11175 " int j;\n" 11176 "};\n", 11177 Style)); 11178 // Check if no lines are kept. 11179 EXPECT_EQ("struct foo {\n" 11180 "private:\n" 11181 " void f() {}\n" 11182 "\n" 11183 "private:\n" 11184 " int i;\n" 11185 "\n" 11186 "protected:\n" 11187 " int j;\n" 11188 "};\n", 11189 format("struct foo {\n" 11190 "private:\n" 11191 " void f() {}\n" 11192 "\n" 11193 "private:\n" 11194 " int i;\n" 11195 "\n" 11196 "protected:\n" 11197 " int j;\n" 11198 "};\n", 11199 Style)); 11200 // Check if MaxEmptyLinesToKeep is respected. 11201 EXPECT_EQ("struct foo {\n" 11202 "private:\n" 11203 "\n" 11204 " void f() {}\n" 11205 "\n" 11206 "private:\n" 11207 "\n" 11208 " int i;\n" 11209 "\n" 11210 "protected:\n" 11211 "\n" 11212 " int j;\n" 11213 "};\n", 11214 format("struct foo {\n" 11215 "private:\n" 11216 "\n\n\n" 11217 " void f() {}\n" 11218 "\n" 11219 "private:\n" 11220 "\n\n\n" 11221 " int i;\n" 11222 "\n" 11223 "protected:\n" 11224 "\n\n\n" 11225 " int j;\n" 11226 "};\n", 11227 Style)); 11228 11229 Style.MaxEmptyLinesToKeep = 10u; 11230 EXPECT_EQ("struct foo {\n" 11231 "private:\n" 11232 "\n\n\n" 11233 " void f() {}\n" 11234 "\n" 11235 "private:\n" 11236 "\n\n\n" 11237 " int i;\n" 11238 "\n" 11239 "protected:\n" 11240 "\n\n\n" 11241 " int j;\n" 11242 "};\n", 11243 format("struct foo {\n" 11244 "private:\n" 11245 "\n\n\n" 11246 " void f() {}\n" 11247 "\n" 11248 "private:\n" 11249 "\n\n\n" 11250 " int i;\n" 11251 "\n" 11252 "protected:\n" 11253 "\n\n\n" 11254 " int j;\n" 11255 "};\n", 11256 Style)); 11257 11258 // Test with comments. 11259 Style = getLLVMStyle(); 11260 verifyFormat("struct foo {\n" 11261 "private:\n" 11262 " // comment\n" 11263 " void f() {}\n" 11264 "\n" 11265 "private: /* comment */\n" 11266 " int i;\n" 11267 "};\n", 11268 Style); 11269 verifyFormat("struct foo {\n" 11270 "private:\n" 11271 " // comment\n" 11272 " void f() {}\n" 11273 "\n" 11274 "private: /* comment */\n" 11275 " int i;\n" 11276 "};\n", 11277 "struct foo {\n" 11278 "private:\n" 11279 "\n" 11280 " // comment\n" 11281 " void f() {}\n" 11282 "\n" 11283 "private: /* comment */\n" 11284 "\n" 11285 " int i;\n" 11286 "};\n", 11287 Style); 11288 11289 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11290 verifyFormat("struct foo {\n" 11291 "private:\n" 11292 "\n" 11293 " // comment\n" 11294 " void f() {}\n" 11295 "\n" 11296 "private: /* comment */\n" 11297 "\n" 11298 " int i;\n" 11299 "};\n", 11300 "struct foo {\n" 11301 "private:\n" 11302 " // comment\n" 11303 " void f() {}\n" 11304 "\n" 11305 "private: /* comment */\n" 11306 " int i;\n" 11307 "};\n", 11308 Style); 11309 verifyFormat("struct foo {\n" 11310 "private:\n" 11311 "\n" 11312 " // comment\n" 11313 " void f() {}\n" 11314 "\n" 11315 "private: /* comment */\n" 11316 "\n" 11317 " int i;\n" 11318 "};\n", 11319 Style); 11320 11321 // Test with preprocessor defines. 11322 Style = getLLVMStyle(); 11323 verifyFormat("struct foo {\n" 11324 "private:\n" 11325 "#ifdef FOO\n" 11326 "#endif\n" 11327 " void f() {}\n" 11328 "};\n", 11329 Style); 11330 verifyFormat("struct foo {\n" 11331 "private:\n" 11332 "#ifdef FOO\n" 11333 "#endif\n" 11334 " void f() {}\n" 11335 "};\n", 11336 "struct foo {\n" 11337 "private:\n" 11338 "\n" 11339 "#ifdef FOO\n" 11340 "#endif\n" 11341 " void f() {}\n" 11342 "};\n", 11343 Style); 11344 11345 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11346 verifyFormat("struct foo {\n" 11347 "private:\n" 11348 "\n" 11349 "#ifdef FOO\n" 11350 "#endif\n" 11351 " void f() {}\n" 11352 "};\n", 11353 "struct foo {\n" 11354 "private:\n" 11355 "#ifdef FOO\n" 11356 "#endif\n" 11357 " void f() {}\n" 11358 "};\n", 11359 Style); 11360 verifyFormat("struct foo {\n" 11361 "private:\n" 11362 "\n" 11363 "#ifdef FOO\n" 11364 "#endif\n" 11365 " void f() {}\n" 11366 "};\n", 11367 Style); 11368 } 11369 11370 TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) { 11371 // Combined tests of EmptyLineAfterAccessModifier and 11372 // EmptyLineBeforeAccessModifier. 11373 FormatStyle Style = getLLVMStyle(); 11374 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11375 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11376 verifyFormat("struct foo {\n" 11377 "private:\n" 11378 "\n" 11379 "protected:\n" 11380 "};\n", 11381 Style); 11382 11383 Style.MaxEmptyLinesToKeep = 10u; 11384 // Both remove all new lines. 11385 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11386 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11387 verifyFormat("struct foo {\n" 11388 "private:\n" 11389 "protected:\n" 11390 "};\n", 11391 "struct foo {\n" 11392 "private:\n" 11393 "\n\n\n" 11394 "protected:\n" 11395 "};\n", 11396 Style); 11397 11398 // Leave tests rely on the code layout, test::messUp can not be used. 11399 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11400 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11401 Style.MaxEmptyLinesToKeep = 10u; 11402 EXPECT_EQ("struct foo {\n" 11403 "private:\n" 11404 "\n\n\n" 11405 "protected:\n" 11406 "};\n", 11407 format("struct foo {\n" 11408 "private:\n" 11409 "\n\n\n" 11410 "protected:\n" 11411 "};\n", 11412 Style)); 11413 Style.MaxEmptyLinesToKeep = 3u; 11414 EXPECT_EQ("struct foo {\n" 11415 "private:\n" 11416 "\n\n\n" 11417 "protected:\n" 11418 "};\n", 11419 format("struct foo {\n" 11420 "private:\n" 11421 "\n\n\n" 11422 "protected:\n" 11423 "};\n", 11424 Style)); 11425 Style.MaxEmptyLinesToKeep = 1u; 11426 EXPECT_EQ("struct foo {\n" 11427 "private:\n" 11428 "\n\n\n" 11429 "protected:\n" 11430 "};\n", 11431 format("struct foo {\n" 11432 "private:\n" 11433 "\n\n\n" 11434 "protected:\n" 11435 "};\n", 11436 Style)); // Based on new lines in original document and not 11437 // on the setting. 11438 11439 Style.MaxEmptyLinesToKeep = 10u; 11440 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11441 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11442 // Newlines are kept if they are greater than zero, 11443 // test::messUp removes all new lines which changes the logic 11444 EXPECT_EQ("struct foo {\n" 11445 "private:\n" 11446 "\n\n\n" 11447 "protected:\n" 11448 "};\n", 11449 format("struct foo {\n" 11450 "private:\n" 11451 "\n\n\n" 11452 "protected:\n" 11453 "};\n", 11454 Style)); 11455 11456 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11457 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11458 // test::messUp removes all new lines which changes the logic 11459 EXPECT_EQ("struct foo {\n" 11460 "private:\n" 11461 "\n\n\n" 11462 "protected:\n" 11463 "};\n", 11464 format("struct foo {\n" 11465 "private:\n" 11466 "\n\n\n" 11467 "protected:\n" 11468 "};\n", 11469 Style)); 11470 11471 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11472 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11473 EXPECT_EQ("struct foo {\n" 11474 "private:\n" 11475 "\n\n\n" 11476 "protected:\n" 11477 "};\n", 11478 format("struct foo {\n" 11479 "private:\n" 11480 "\n\n\n" 11481 "protected:\n" 11482 "};\n", 11483 Style)); // test::messUp removes all new lines which changes 11484 // the logic. 11485 11486 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11487 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11488 verifyFormat("struct foo {\n" 11489 "private:\n" 11490 "protected:\n" 11491 "};\n", 11492 "struct foo {\n" 11493 "private:\n" 11494 "\n\n\n" 11495 "protected:\n" 11496 "};\n", 11497 Style); 11498 11499 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11500 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11501 EXPECT_EQ("struct foo {\n" 11502 "private:\n" 11503 "\n\n\n" 11504 "protected:\n" 11505 "};\n", 11506 format("struct foo {\n" 11507 "private:\n" 11508 "\n\n\n" 11509 "protected:\n" 11510 "};\n", 11511 Style)); // test::messUp removes all new lines which changes 11512 // the logic. 11513 11514 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11515 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11516 verifyFormat("struct foo {\n" 11517 "private:\n" 11518 "protected:\n" 11519 "};\n", 11520 "struct foo {\n" 11521 "private:\n" 11522 "\n\n\n" 11523 "protected:\n" 11524 "};\n", 11525 Style); 11526 11527 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11528 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11529 verifyFormat("struct foo {\n" 11530 "private:\n" 11531 "protected:\n" 11532 "};\n", 11533 "struct foo {\n" 11534 "private:\n" 11535 "\n\n\n" 11536 "protected:\n" 11537 "};\n", 11538 Style); 11539 11540 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11541 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11542 verifyFormat("struct foo {\n" 11543 "private:\n" 11544 "protected:\n" 11545 "};\n", 11546 "struct foo {\n" 11547 "private:\n" 11548 "\n\n\n" 11549 "protected:\n" 11550 "};\n", 11551 Style); 11552 11553 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11554 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11555 verifyFormat("struct foo {\n" 11556 "private:\n" 11557 "protected:\n" 11558 "};\n", 11559 "struct foo {\n" 11560 "private:\n" 11561 "\n\n\n" 11562 "protected:\n" 11563 "};\n", 11564 Style); 11565 } 11566 11567 TEST_F(FormatTest, FormatsArrays) { 11568 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n" 11569 " [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;"); 11570 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n" 11571 " [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;"); 11572 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n" 11573 " aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}"); 11574 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11575 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;"); 11576 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11577 " [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;"); 11578 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11579 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n" 11580 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;"); 11581 verifyFormat( 11582 "llvm::outs() << \"aaaaaaaaaaaa: \"\n" 11583 " << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n" 11584 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];"); 11585 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n" 11586 " .aaaaaaaaaaaaaaaaaaaaaa();"); 11587 11588 verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n" 11589 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];"); 11590 verifyFormat( 11591 "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n" 11592 " .aaaaaaa[0]\n" 11593 " .aaaaaaaaaaaaaaaaaaaaaa();"); 11594 verifyFormat("a[::b::c];"); 11595 11596 verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10)); 11597 11598 FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0); 11599 verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit); 11600 } 11601 11602 TEST_F(FormatTest, LineStartsWithSpecialCharacter) { 11603 verifyFormat("(a)->b();"); 11604 verifyFormat("--a;"); 11605 } 11606 11607 TEST_F(FormatTest, HandlesIncludeDirectives) { 11608 verifyFormat("#include <string>\n" 11609 "#include <a/b/c.h>\n" 11610 "#include \"a/b/string\"\n" 11611 "#include \"string.h\"\n" 11612 "#include \"string.h\"\n" 11613 "#include <a-a>\n" 11614 "#include < path with space >\n" 11615 "#include_next <test.h>" 11616 "#include \"abc.h\" // this is included for ABC\n" 11617 "#include \"some long include\" // with a comment\n" 11618 "#include \"some very long include path\"\n" 11619 "#include <some/very/long/include/path>\n", 11620 getLLVMStyleWithColumns(35)); 11621 EXPECT_EQ("#include \"a.h\"", format("#include \"a.h\"")); 11622 EXPECT_EQ("#include <a>", format("#include<a>")); 11623 11624 verifyFormat("#import <string>"); 11625 verifyFormat("#import <a/b/c.h>"); 11626 verifyFormat("#import \"a/b/string\""); 11627 verifyFormat("#import \"string.h\""); 11628 verifyFormat("#import \"string.h\""); 11629 verifyFormat("#if __has_include(<strstream>)\n" 11630 "#include <strstream>\n" 11631 "#endif"); 11632 11633 verifyFormat("#define MY_IMPORT <a/b>"); 11634 11635 verifyFormat("#if __has_include(<a/b>)"); 11636 verifyFormat("#if __has_include_next(<a/b>)"); 11637 verifyFormat("#define F __has_include(<a/b>)"); 11638 verifyFormat("#define F __has_include_next(<a/b>)"); 11639 11640 // Protocol buffer definition or missing "#". 11641 verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";", 11642 getLLVMStyleWithColumns(30)); 11643 11644 FormatStyle Style = getLLVMStyle(); 11645 Style.AlwaysBreakBeforeMultilineStrings = true; 11646 Style.ColumnLimit = 0; 11647 verifyFormat("#import \"abc.h\"", Style); 11648 11649 // But 'import' might also be a regular C++ namespace. 11650 verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 11651 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 11652 } 11653 11654 //===----------------------------------------------------------------------===// 11655 // Error recovery tests. 11656 //===----------------------------------------------------------------------===// 11657 11658 TEST_F(FormatTest, IncompleteParameterLists) { 11659 FormatStyle NoBinPacking = getLLVMStyle(); 11660 NoBinPacking.BinPackParameters = false; 11661 verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n" 11662 " double *min_x,\n" 11663 " double *max_x,\n" 11664 " double *min_y,\n" 11665 " double *max_y,\n" 11666 " double *min_z,\n" 11667 " double *max_z, ) {}", 11668 NoBinPacking); 11669 } 11670 11671 TEST_F(FormatTest, IncorrectCodeTrailingStuff) { 11672 verifyFormat("void f() { return; }\n42"); 11673 verifyFormat("void f() {\n" 11674 " if (0)\n" 11675 " return;\n" 11676 "}\n" 11677 "42"); 11678 verifyFormat("void f() { return }\n42"); 11679 verifyFormat("void f() {\n" 11680 " if (0)\n" 11681 " return\n" 11682 "}\n" 11683 "42"); 11684 } 11685 11686 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) { 11687 EXPECT_EQ("void f() { return }", format("void f ( ) { return }")); 11688 EXPECT_EQ("void f() {\n" 11689 " if (a)\n" 11690 " return\n" 11691 "}", 11692 format("void f ( ) { if ( a ) return }")); 11693 EXPECT_EQ("namespace N {\n" 11694 "void f()\n" 11695 "}", 11696 format("namespace N { void f() }")); 11697 EXPECT_EQ("namespace N {\n" 11698 "void f() {}\n" 11699 "void g()\n" 11700 "} // namespace N", 11701 format("namespace N { void f( ) { } void g( ) }")); 11702 } 11703 11704 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) { 11705 verifyFormat("int aaaaaaaa =\n" 11706 " // Overlylongcomment\n" 11707 " b;", 11708 getLLVMStyleWithColumns(20)); 11709 verifyFormat("function(\n" 11710 " ShortArgument,\n" 11711 " LoooooooooooongArgument);\n", 11712 getLLVMStyleWithColumns(20)); 11713 } 11714 11715 TEST_F(FormatTest, IncorrectAccessSpecifier) { 11716 verifyFormat("public:"); 11717 verifyFormat("class A {\n" 11718 "public\n" 11719 " void f() {}\n" 11720 "};"); 11721 verifyFormat("public\n" 11722 "int qwerty;"); 11723 verifyFormat("public\n" 11724 "B {}"); 11725 verifyFormat("public\n" 11726 "{}"); 11727 verifyFormat("public\n" 11728 "B { int x; }"); 11729 } 11730 11731 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) { 11732 verifyFormat("{"); 11733 verifyFormat("#})"); 11734 verifyNoCrash("(/**/[:!] ?[)."); 11735 } 11736 11737 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) { 11738 // Found by oss-fuzz: 11739 // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212 11740 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp); 11741 Style.ColumnLimit = 60; 11742 verifyNoCrash( 11743 "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20" 11744 "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20" 11745 "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a", 11746 Style); 11747 } 11748 11749 TEST_F(FormatTest, IncorrectCodeDoNoWhile) { 11750 verifyFormat("do {\n}"); 11751 verifyFormat("do {\n}\n" 11752 "f();"); 11753 verifyFormat("do {\n}\n" 11754 "wheeee(fun);"); 11755 verifyFormat("do {\n" 11756 " f();\n" 11757 "}"); 11758 } 11759 11760 TEST_F(FormatTest, IncorrectCodeMissingParens) { 11761 verifyFormat("if {\n foo;\n foo();\n}"); 11762 verifyFormat("switch {\n foo;\n foo();\n}"); 11763 verifyIncompleteFormat("for {\n foo;\n foo();\n}"); 11764 verifyFormat("while {\n foo;\n foo();\n}"); 11765 verifyFormat("do {\n foo;\n foo();\n} while;"); 11766 } 11767 11768 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) { 11769 verifyIncompleteFormat("namespace {\n" 11770 "class Foo { Foo (\n" 11771 "};\n" 11772 "} // namespace"); 11773 } 11774 11775 TEST_F(FormatTest, IncorrectCodeErrorDetection) { 11776 EXPECT_EQ("{\n {}\n", format("{\n{\n}\n")); 11777 EXPECT_EQ("{\n {}\n", format("{\n {\n}\n")); 11778 EXPECT_EQ("{\n {}\n", format("{\n {\n }\n")); 11779 EXPECT_EQ("{\n {}\n}\n}\n", format("{\n {\n }\n }\n}\n")); 11780 11781 EXPECT_EQ("{\n" 11782 " {\n" 11783 " breakme(\n" 11784 " qwe);\n" 11785 " }\n", 11786 format("{\n" 11787 " {\n" 11788 " breakme(qwe);\n" 11789 "}\n", 11790 getLLVMStyleWithColumns(10))); 11791 } 11792 11793 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) { 11794 verifyFormat("int x = {\n" 11795 " avariable,\n" 11796 " b(alongervariable)};", 11797 getLLVMStyleWithColumns(25)); 11798 } 11799 11800 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) { 11801 verifyFormat("return (a)(b){1, 2, 3};"); 11802 } 11803 11804 TEST_F(FormatTest, LayoutCxx11BraceInitializers) { 11805 verifyFormat("vector<int> x{1, 2, 3, 4};"); 11806 verifyFormat("vector<int> x{\n" 11807 " 1,\n" 11808 " 2,\n" 11809 " 3,\n" 11810 " 4,\n" 11811 "};"); 11812 verifyFormat("vector<T> x{{}, {}, {}, {}};"); 11813 verifyFormat("f({1, 2});"); 11814 verifyFormat("auto v = Foo{-1};"); 11815 verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});"); 11816 verifyFormat("Class::Class : member{1, 2, 3} {}"); 11817 verifyFormat("new vector<int>{1, 2, 3};"); 11818 verifyFormat("new int[3]{1, 2, 3};"); 11819 verifyFormat("new int{1};"); 11820 verifyFormat("return {arg1, arg2};"); 11821 verifyFormat("return {arg1, SomeType{parameter}};"); 11822 verifyFormat("int count = set<int>{f(), g(), h()}.size();"); 11823 verifyFormat("new T{arg1, arg2};"); 11824 verifyFormat("f(MyMap[{composite, key}]);"); 11825 verifyFormat("class Class {\n" 11826 " T member = {arg1, arg2};\n" 11827 "};"); 11828 verifyFormat("vector<int> foo = {::SomeGlobalFunction()};"); 11829 verifyFormat("const struct A a = {.a = 1, .b = 2};"); 11830 verifyFormat("const struct A a = {[0] = 1, [1] = 2};"); 11831 verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");"); 11832 verifyFormat("int a = std::is_integral<int>{} + 0;"); 11833 11834 verifyFormat("int foo(int i) { return fo1{}(i); }"); 11835 verifyFormat("int foo(int i) { return fo1{}(i); }"); 11836 verifyFormat("auto i = decltype(x){};"); 11837 verifyFormat("auto i = typeof(x){};"); 11838 verifyFormat("auto i = _Atomic(x){};"); 11839 verifyFormat("std::vector<int> v = {1, 0 /* comment */};"); 11840 verifyFormat("Node n{1, Node{1000}, //\n" 11841 " 2};"); 11842 verifyFormat("Aaaa aaaaaaa{\n" 11843 " {\n" 11844 " aaaa,\n" 11845 " },\n" 11846 "};"); 11847 verifyFormat("class C : public D {\n" 11848 " SomeClass SC{2};\n" 11849 "};"); 11850 verifyFormat("class C : public A {\n" 11851 " class D : public B {\n" 11852 " void f() { int i{2}; }\n" 11853 " };\n" 11854 "};"); 11855 verifyFormat("#define A {a, a},"); 11856 // Don't confuse braced list initializers with compound statements. 11857 verifyFormat( 11858 "class A {\n" 11859 " A() : a{} {}\n" 11860 " A(int b) : b(b) {}\n" 11861 " A(int a, int b) : a(a), bs{{bs...}} { f(); }\n" 11862 " int a, b;\n" 11863 " explicit Expr(const Scalar<Result> &x) : u{Constant<Result>{x}} {}\n" 11864 " explicit Expr(Scalar<Result> &&x) : u{Constant<Result>{std::move(x)}} " 11865 "{}\n" 11866 "};"); 11867 11868 // Avoid breaking between equal sign and opening brace 11869 FormatStyle AvoidBreakingFirstArgument = getLLVMStyle(); 11870 AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200; 11871 verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n" 11872 " {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n" 11873 " {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n" 11874 " {\"ccccccccccccccccccccc\", 2}};", 11875 AvoidBreakingFirstArgument); 11876 11877 // Binpacking only if there is no trailing comma 11878 verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n" 11879 " cccccccccc, dddddddddd};", 11880 getLLVMStyleWithColumns(50)); 11881 verifyFormat("const Aaaaaa aaaaa = {\n" 11882 " aaaaaaaaaaa,\n" 11883 " bbbbbbbbbbb,\n" 11884 " ccccccccccc,\n" 11885 " ddddddddddd,\n" 11886 "};", 11887 getLLVMStyleWithColumns(50)); 11888 11889 // Cases where distinguising braced lists and blocks is hard. 11890 verifyFormat("vector<int> v{12} GUARDED_BY(mutex);"); 11891 verifyFormat("void f() {\n" 11892 " return; // comment\n" 11893 "}\n" 11894 "SomeType t;"); 11895 verifyFormat("void f() {\n" 11896 " if (a) {\n" 11897 " f();\n" 11898 " }\n" 11899 "}\n" 11900 "SomeType t;"); 11901 11902 // In combination with BinPackArguments = false. 11903 FormatStyle NoBinPacking = getLLVMStyle(); 11904 NoBinPacking.BinPackArguments = false; 11905 verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n" 11906 " bbbbb,\n" 11907 " ccccc,\n" 11908 " ddddd,\n" 11909 " eeeee,\n" 11910 " ffffff,\n" 11911 " ggggg,\n" 11912 " hhhhhh,\n" 11913 " iiiiii,\n" 11914 " jjjjjj,\n" 11915 " kkkkkk};", 11916 NoBinPacking); 11917 verifyFormat("const Aaaaaa aaaaa = {\n" 11918 " aaaaa,\n" 11919 " bbbbb,\n" 11920 " ccccc,\n" 11921 " ddddd,\n" 11922 " eeeee,\n" 11923 " ffffff,\n" 11924 " ggggg,\n" 11925 " hhhhhh,\n" 11926 " iiiiii,\n" 11927 " jjjjjj,\n" 11928 " kkkkkk,\n" 11929 "};", 11930 NoBinPacking); 11931 verifyFormat( 11932 "const Aaaaaa aaaaa = {\n" 11933 " aaaaa, bbbbb, ccccc, ddddd, eeeee, ffffff, ggggg, hhhhhh,\n" 11934 " iiiiii, jjjjjj, kkkkkk, aaaaa, bbbbb, ccccc, ddddd, eeeee,\n" 11935 " ffffff, ggggg, hhhhhh, iiiiii, jjjjjj, kkkkkk,\n" 11936 "};", 11937 NoBinPacking); 11938 11939 NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 11940 EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n" 11941 " CDDDP83848_BMCR_REGISTER,\n" 11942 " CDDDP83848_BMSR_REGISTER,\n" 11943 " CDDDP83848_RBR_REGISTER};", 11944 format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n" 11945 " CDDDP83848_BMSR_REGISTER,\n" 11946 " CDDDP83848_RBR_REGISTER};", 11947 NoBinPacking)); 11948 11949 // FIXME: The alignment of these trailing comments might be bad. Then again, 11950 // this might be utterly useless in real code. 11951 verifyFormat("Constructor::Constructor()\n" 11952 " : some_value{ //\n" 11953 " aaaaaaa, //\n" 11954 " bbbbbbb} {}"); 11955 11956 // In braced lists, the first comment is always assumed to belong to the 11957 // first element. Thus, it can be moved to the next or previous line as 11958 // appropriate. 11959 EXPECT_EQ("function({// First element:\n" 11960 " 1,\n" 11961 " // Second element:\n" 11962 " 2});", 11963 format("function({\n" 11964 " // First element:\n" 11965 " 1,\n" 11966 " // Second element:\n" 11967 " 2});")); 11968 EXPECT_EQ("std::vector<int> MyNumbers{\n" 11969 " // First element:\n" 11970 " 1,\n" 11971 " // Second element:\n" 11972 " 2};", 11973 format("std::vector<int> MyNumbers{// First element:\n" 11974 " 1,\n" 11975 " // Second element:\n" 11976 " 2};", 11977 getLLVMStyleWithColumns(30))); 11978 // A trailing comma should still lead to an enforced line break and no 11979 // binpacking. 11980 EXPECT_EQ("vector<int> SomeVector = {\n" 11981 " // aaa\n" 11982 " 1,\n" 11983 " 2,\n" 11984 "};", 11985 format("vector<int> SomeVector = { // aaa\n" 11986 " 1, 2, };")); 11987 11988 // C++11 brace initializer list l-braces should not be treated any differently 11989 // when breaking before lambda bodies is enabled 11990 FormatStyle BreakBeforeLambdaBody = getLLVMStyle(); 11991 BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 11992 BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 11993 BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true; 11994 verifyFormat( 11995 "std::runtime_error{\n" 11996 " \"Long string which will force a break onto the next line...\"};", 11997 BreakBeforeLambdaBody); 11998 11999 FormatStyle ExtraSpaces = getLLVMStyle(); 12000 ExtraSpaces.Cpp11BracedListStyle = false; 12001 ExtraSpaces.ColumnLimit = 75; 12002 verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces); 12003 verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces); 12004 verifyFormat("f({ 1, 2 });", ExtraSpaces); 12005 verifyFormat("auto v = Foo{ 1 };", ExtraSpaces); 12006 verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces); 12007 verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces); 12008 verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces); 12009 verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces); 12010 verifyFormat("return { arg1, arg2 };", ExtraSpaces); 12011 verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces); 12012 verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces); 12013 verifyFormat("new T{ arg1, arg2 };", ExtraSpaces); 12014 verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces); 12015 verifyFormat("class Class {\n" 12016 " T member = { arg1, arg2 };\n" 12017 "};", 12018 ExtraSpaces); 12019 verifyFormat( 12020 "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12021 " aaaaaaaaaaaaaaaaaaaa, aaaaa }\n" 12022 " : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 12023 " bbbbbbbbbbbbbbbbbbbb, bbbbb };", 12024 ExtraSpaces); 12025 verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces); 12026 verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });", 12027 ExtraSpaces); 12028 verifyFormat( 12029 "someFunction(OtherParam,\n" 12030 " BracedList{ // comment 1 (Forcing interesting break)\n" 12031 " param1, param2,\n" 12032 " // comment 2\n" 12033 " param3, param4 });", 12034 ExtraSpaces); 12035 verifyFormat( 12036 "std::this_thread::sleep_for(\n" 12037 " std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);", 12038 ExtraSpaces); 12039 verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n" 12040 " aaaaaaa,\n" 12041 " aaaaaaaaaa,\n" 12042 " aaaaa,\n" 12043 " aaaaaaaaaaaaaaa,\n" 12044 " aaa,\n" 12045 " aaaaaaaaaa,\n" 12046 " a,\n" 12047 " aaaaaaaaaaaaaaaaaaaaa,\n" 12048 " aaaaaaaaaaaa,\n" 12049 " aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n" 12050 " aaaaaaa,\n" 12051 " a};"); 12052 verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces); 12053 verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces); 12054 verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces); 12055 12056 // Avoid breaking between initializer/equal sign and opening brace 12057 ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200; 12058 verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n" 12059 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n" 12060 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n" 12061 " { \"ccccccccccccccccccccc\", 2 }\n" 12062 "};", 12063 ExtraSpaces); 12064 verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n" 12065 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n" 12066 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n" 12067 " { \"ccccccccccccccccccccc\", 2 }\n" 12068 "};", 12069 ExtraSpaces); 12070 12071 FormatStyle SpaceBeforeBrace = getLLVMStyle(); 12072 SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true; 12073 verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace); 12074 verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace); 12075 12076 FormatStyle SpaceBetweenBraces = getLLVMStyle(); 12077 SpaceBetweenBraces.SpacesInAngles = FormatStyle::SIAS_Always; 12078 SpaceBetweenBraces.SpacesInParentheses = true; 12079 SpaceBetweenBraces.SpacesInSquareBrackets = true; 12080 verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces); 12081 verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces); 12082 verifyFormat("vector< int > x{ // comment 1\n" 12083 " 1, 2, 3, 4 };", 12084 SpaceBetweenBraces); 12085 SpaceBetweenBraces.ColumnLimit = 20; 12086 EXPECT_EQ("vector< int > x{\n" 12087 " 1, 2, 3, 4 };", 12088 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces)); 12089 SpaceBetweenBraces.ColumnLimit = 24; 12090 EXPECT_EQ("vector< int > x{ 1, 2,\n" 12091 " 3, 4 };", 12092 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces)); 12093 EXPECT_EQ("vector< int > x{\n" 12094 " 1,\n" 12095 " 2,\n" 12096 " 3,\n" 12097 " 4,\n" 12098 "};", 12099 format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces)); 12100 verifyFormat("vector< int > x{};", SpaceBetweenBraces); 12101 SpaceBetweenBraces.SpaceInEmptyParentheses = true; 12102 verifyFormat("vector< int > x{ };", SpaceBetweenBraces); 12103 } 12104 12105 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) { 12106 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12107 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12108 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12109 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12110 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12111 " 1, 22, 333, 4444, 55555, 666666, 7777777};"); 12112 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n" 12113 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12114 " 1, 22, 333, 4444, 55555, //\n" 12115 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12116 " 1, 22, 333, 4444, 55555, 666666, 7777777};"); 12117 verifyFormat( 12118 "vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12119 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12120 " 1, 22, 333, 4444, 55555, 666666, // comment\n" 12121 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12122 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12123 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12124 " 7777777};"); 12125 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12126 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12127 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12128 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12129 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12130 " // Separating comment.\n" 12131 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12132 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12133 " // Leading comment\n" 12134 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12135 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12136 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12137 " 1, 1, 1, 1};", 12138 getLLVMStyleWithColumns(39)); 12139 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12140 " 1, 1, 1, 1};", 12141 getLLVMStyleWithColumns(38)); 12142 verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n" 12143 " 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};", 12144 getLLVMStyleWithColumns(43)); 12145 verifyFormat( 12146 "static unsigned SomeValues[10][3] = {\n" 12147 " {1, 4, 0}, {4, 9, 0}, {4, 5, 9}, {8, 5, 4}, {1, 8, 4},\n" 12148 " {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};"); 12149 verifyFormat("static auto fields = new vector<string>{\n" 12150 " \"aaaaaaaaaaaaa\",\n" 12151 " \"aaaaaaaaaaaaa\",\n" 12152 " \"aaaaaaaaaaaa\",\n" 12153 " \"aaaaaaaaaaaaaa\",\n" 12154 " \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n" 12155 " \"aaaaaaaaaaaa\",\n" 12156 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n" 12157 "};"); 12158 verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};"); 12159 verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n" 12160 " 2, bbbbbbbbbbbbbbbbbbbbbb,\n" 12161 " 3, cccccccccccccccccccccc};", 12162 getLLVMStyleWithColumns(60)); 12163 12164 // Trailing commas. 12165 verifyFormat("vector<int> x = {\n" 12166 " 1, 1, 1, 1, 1, 1, 1, 1,\n" 12167 "};", 12168 getLLVMStyleWithColumns(39)); 12169 verifyFormat("vector<int> x = {\n" 12170 " 1, 1, 1, 1, 1, 1, 1, 1, //\n" 12171 "};", 12172 getLLVMStyleWithColumns(39)); 12173 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12174 " 1, 1, 1, 1,\n" 12175 " /**/ /**/};", 12176 getLLVMStyleWithColumns(39)); 12177 12178 // Trailing comment in the first line. 12179 verifyFormat("vector<int> iiiiiiiiiiiiiii = { //\n" 12180 " 1111111111, 2222222222, 33333333333, 4444444444, //\n" 12181 " 111111111, 222222222, 3333333333, 444444444, //\n" 12182 " 11111111, 22222222, 333333333, 44444444};"); 12183 // Trailing comment in the last line. 12184 verifyFormat("int aaaaa[] = {\n" 12185 " 1, 2, 3, // comment\n" 12186 " 4, 5, 6 // comment\n" 12187 "};"); 12188 12189 // With nested lists, we should either format one item per line or all nested 12190 // lists one on line. 12191 // FIXME: For some nested lists, we can do better. 12192 verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n" 12193 " {aaaaaaaaaaaaaaaaaaa},\n" 12194 " {aaaaaaaaaaaaaaaaaaaaa},\n" 12195 " {aaaaaaaaaaaaaaaaa}};", 12196 getLLVMStyleWithColumns(60)); 12197 verifyFormat( 12198 "SomeStruct my_struct_array = {\n" 12199 " {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n" 12200 " aaaaaaaaaaaaa, aaaaaaa, aaa},\n" 12201 " {aaa, aaa},\n" 12202 " {aaa, aaa},\n" 12203 " {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n" 12204 " {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n" 12205 " aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};"); 12206 12207 // No column layout should be used here. 12208 verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n" 12209 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};"); 12210 12211 verifyNoCrash("a<,"); 12212 12213 // No braced initializer here. 12214 verifyFormat("void f() {\n" 12215 " struct Dummy {};\n" 12216 " f(v);\n" 12217 "}"); 12218 12219 // Long lists should be formatted in columns even if they are nested. 12220 verifyFormat( 12221 "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12222 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12223 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12224 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12225 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12226 " 1, 22, 333, 4444, 55555, 666666, 7777777});"); 12227 12228 // Allow "single-column" layout even if that violates the column limit. There 12229 // isn't going to be a better way. 12230 verifyFormat("std::vector<int> a = {\n" 12231 " aaaaaaaa,\n" 12232 " aaaaaaaa,\n" 12233 " aaaaaaaa,\n" 12234 " aaaaaaaa,\n" 12235 " aaaaaaaaaa,\n" 12236 " aaaaaaaa,\n" 12237 " aaaaaaaaaaaaaaaaaaaaaaaaaaa};", 12238 getLLVMStyleWithColumns(30)); 12239 verifyFormat("vector<int> aaaa = {\n" 12240 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12241 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12242 " aaaaaa.aaaaaaa,\n" 12243 " aaaaaa.aaaaaaa,\n" 12244 " aaaaaa.aaaaaaa,\n" 12245 " aaaaaa.aaaaaaa,\n" 12246 "};"); 12247 12248 // Don't create hanging lists. 12249 verifyFormat("someFunction(Param, {List1, List2,\n" 12250 " List3});", 12251 getLLVMStyleWithColumns(35)); 12252 verifyFormat("someFunction(Param, Param,\n" 12253 " {List1, List2,\n" 12254 " List3});", 12255 getLLVMStyleWithColumns(35)); 12256 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n" 12257 " aaaaaaaaaaaaaaaaaaaaaaa);"); 12258 } 12259 12260 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) { 12261 FormatStyle DoNotMerge = getLLVMStyle(); 12262 DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12263 12264 verifyFormat("void f() { return 42; }"); 12265 verifyFormat("void f() {\n" 12266 " return 42;\n" 12267 "}", 12268 DoNotMerge); 12269 verifyFormat("void f() {\n" 12270 " // Comment\n" 12271 "}"); 12272 verifyFormat("{\n" 12273 "#error {\n" 12274 " int a;\n" 12275 "}"); 12276 verifyFormat("{\n" 12277 " int a;\n" 12278 "#error {\n" 12279 "}"); 12280 verifyFormat("void f() {} // comment"); 12281 verifyFormat("void f() { int a; } // comment"); 12282 verifyFormat("void f() {\n" 12283 "} // comment", 12284 DoNotMerge); 12285 verifyFormat("void f() {\n" 12286 " int a;\n" 12287 "} // comment", 12288 DoNotMerge); 12289 verifyFormat("void f() {\n" 12290 "} // comment", 12291 getLLVMStyleWithColumns(15)); 12292 12293 verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23)); 12294 verifyFormat("void f() {\n return 42;\n}", getLLVMStyleWithColumns(22)); 12295 12296 verifyFormat("void f() {}", getLLVMStyleWithColumns(11)); 12297 verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10)); 12298 verifyFormat("class C {\n" 12299 " C()\n" 12300 " : iiiiiiii(nullptr),\n" 12301 " kkkkkkk(nullptr),\n" 12302 " mmmmmmm(nullptr),\n" 12303 " nnnnnnn(nullptr) {}\n" 12304 "};", 12305 getGoogleStyle()); 12306 12307 FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0); 12308 EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit)); 12309 EXPECT_EQ("class C {\n" 12310 " A() : b(0) {}\n" 12311 "};", 12312 format("class C{A():b(0){}};", NoColumnLimit)); 12313 EXPECT_EQ("A()\n" 12314 " : b(0) {\n" 12315 "}", 12316 format("A()\n:b(0)\n{\n}", NoColumnLimit)); 12317 12318 FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit; 12319 DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine = 12320 FormatStyle::SFS_None; 12321 EXPECT_EQ("A()\n" 12322 " : b(0) {\n" 12323 "}", 12324 format("A():b(0){}", DoNotMergeNoColumnLimit)); 12325 EXPECT_EQ("A()\n" 12326 " : b(0) {\n" 12327 "}", 12328 format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit)); 12329 12330 verifyFormat("#define A \\\n" 12331 " void f() { \\\n" 12332 " int i; \\\n" 12333 " }", 12334 getLLVMStyleWithColumns(20)); 12335 verifyFormat("#define A \\\n" 12336 " void f() { int i; }", 12337 getLLVMStyleWithColumns(21)); 12338 verifyFormat("#define A \\\n" 12339 " void f() { \\\n" 12340 " int i; \\\n" 12341 " } \\\n" 12342 " int j;", 12343 getLLVMStyleWithColumns(22)); 12344 verifyFormat("#define A \\\n" 12345 " void f() { int i; } \\\n" 12346 " int j;", 12347 getLLVMStyleWithColumns(23)); 12348 } 12349 12350 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) { 12351 FormatStyle MergeEmptyOnly = getLLVMStyle(); 12352 MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 12353 verifyFormat("class C {\n" 12354 " int f() {}\n" 12355 "};", 12356 MergeEmptyOnly); 12357 verifyFormat("class C {\n" 12358 " int f() {\n" 12359 " return 42;\n" 12360 " }\n" 12361 "};", 12362 MergeEmptyOnly); 12363 verifyFormat("int f() {}", MergeEmptyOnly); 12364 verifyFormat("int f() {\n" 12365 " return 42;\n" 12366 "}", 12367 MergeEmptyOnly); 12368 12369 // Also verify behavior when BraceWrapping.AfterFunction = true 12370 MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12371 MergeEmptyOnly.BraceWrapping.AfterFunction = true; 12372 verifyFormat("int f() {}", MergeEmptyOnly); 12373 verifyFormat("class C {\n" 12374 " int f() {}\n" 12375 "};", 12376 MergeEmptyOnly); 12377 } 12378 12379 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) { 12380 FormatStyle MergeInlineOnly = getLLVMStyle(); 12381 MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 12382 verifyFormat("class C {\n" 12383 " int f() { return 42; }\n" 12384 "};", 12385 MergeInlineOnly); 12386 verifyFormat("int f() {\n" 12387 " return 42;\n" 12388 "}", 12389 MergeInlineOnly); 12390 12391 // SFS_Inline implies SFS_Empty 12392 verifyFormat("class C {\n" 12393 " int f() {}\n" 12394 "};", 12395 MergeInlineOnly); 12396 verifyFormat("int f() {}", MergeInlineOnly); 12397 12398 // Also verify behavior when BraceWrapping.AfterFunction = true 12399 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12400 MergeInlineOnly.BraceWrapping.AfterFunction = true; 12401 verifyFormat("class C {\n" 12402 " int f() { return 42; }\n" 12403 "};", 12404 MergeInlineOnly); 12405 verifyFormat("int f()\n" 12406 "{\n" 12407 " return 42;\n" 12408 "}", 12409 MergeInlineOnly); 12410 12411 // SFS_Inline implies SFS_Empty 12412 verifyFormat("int f() {}", MergeInlineOnly); 12413 verifyFormat("class C {\n" 12414 " int f() {}\n" 12415 "};", 12416 MergeInlineOnly); 12417 12418 MergeInlineOnly.BraceWrapping.AfterClass = true; 12419 MergeInlineOnly.BraceWrapping.AfterStruct = true; 12420 verifyFormat("class C\n" 12421 "{\n" 12422 " int f() { return 42; }\n" 12423 "};", 12424 MergeInlineOnly); 12425 verifyFormat("struct C\n" 12426 "{\n" 12427 " int f() { return 42; }\n" 12428 "};", 12429 MergeInlineOnly); 12430 verifyFormat("int f()\n" 12431 "{\n" 12432 " return 42;\n" 12433 "}", 12434 MergeInlineOnly); 12435 verifyFormat("int f() {}", MergeInlineOnly); 12436 verifyFormat("class C\n" 12437 "{\n" 12438 " int f() { return 42; }\n" 12439 "};", 12440 MergeInlineOnly); 12441 verifyFormat("struct C\n" 12442 "{\n" 12443 " int f() { return 42; }\n" 12444 "};", 12445 MergeInlineOnly); 12446 verifyFormat("struct C\n" 12447 "// comment\n" 12448 "/* comment */\n" 12449 "// comment\n" 12450 "{\n" 12451 " int f() { return 42; }\n" 12452 "};", 12453 MergeInlineOnly); 12454 verifyFormat("/* comment */ struct C\n" 12455 "{\n" 12456 " int f() { return 42; }\n" 12457 "};", 12458 MergeInlineOnly); 12459 } 12460 12461 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) { 12462 FormatStyle MergeInlineOnly = getLLVMStyle(); 12463 MergeInlineOnly.AllowShortFunctionsOnASingleLine = 12464 FormatStyle::SFS_InlineOnly; 12465 verifyFormat("class C {\n" 12466 " int f() { return 42; }\n" 12467 "};", 12468 MergeInlineOnly); 12469 verifyFormat("int f() {\n" 12470 " return 42;\n" 12471 "}", 12472 MergeInlineOnly); 12473 12474 // SFS_InlineOnly does not imply SFS_Empty 12475 verifyFormat("class C {\n" 12476 " int f() {}\n" 12477 "};", 12478 MergeInlineOnly); 12479 verifyFormat("int f() {\n" 12480 "}", 12481 MergeInlineOnly); 12482 12483 // Also verify behavior when BraceWrapping.AfterFunction = true 12484 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12485 MergeInlineOnly.BraceWrapping.AfterFunction = true; 12486 verifyFormat("class C {\n" 12487 " int f() { return 42; }\n" 12488 "};", 12489 MergeInlineOnly); 12490 verifyFormat("int f()\n" 12491 "{\n" 12492 " return 42;\n" 12493 "}", 12494 MergeInlineOnly); 12495 12496 // SFS_InlineOnly does not imply SFS_Empty 12497 verifyFormat("int f()\n" 12498 "{\n" 12499 "}", 12500 MergeInlineOnly); 12501 verifyFormat("class C {\n" 12502 " int f() {}\n" 12503 "};", 12504 MergeInlineOnly); 12505 } 12506 12507 TEST_F(FormatTest, SplitEmptyFunction) { 12508 FormatStyle Style = getLLVMStyleWithColumns(40); 12509 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12510 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12511 Style.BraceWrapping.AfterFunction = true; 12512 Style.BraceWrapping.SplitEmptyFunction = false; 12513 12514 verifyFormat("int f()\n" 12515 "{}", 12516 Style); 12517 verifyFormat("int f()\n" 12518 "{\n" 12519 " return 42;\n" 12520 "}", 12521 Style); 12522 verifyFormat("int f()\n" 12523 "{\n" 12524 " // some comment\n" 12525 "}", 12526 Style); 12527 12528 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 12529 verifyFormat("int f() {}", Style); 12530 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12531 "{}", 12532 Style); 12533 verifyFormat("int f()\n" 12534 "{\n" 12535 " return 0;\n" 12536 "}", 12537 Style); 12538 12539 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 12540 verifyFormat("class Foo {\n" 12541 " int f() {}\n" 12542 "};\n", 12543 Style); 12544 verifyFormat("class Foo {\n" 12545 " int f() { return 0; }\n" 12546 "};\n", 12547 Style); 12548 verifyFormat("class Foo {\n" 12549 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12550 " {}\n" 12551 "};\n", 12552 Style); 12553 verifyFormat("class Foo {\n" 12554 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12555 " {\n" 12556 " return 0;\n" 12557 " }\n" 12558 "};\n", 12559 Style); 12560 12561 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 12562 verifyFormat("int f() {}", Style); 12563 verifyFormat("int f() { return 0; }", Style); 12564 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12565 "{}", 12566 Style); 12567 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12568 "{\n" 12569 " return 0;\n" 12570 "}", 12571 Style); 12572 } 12573 12574 TEST_F(FormatTest, SplitEmptyFunctionButNotRecord) { 12575 FormatStyle Style = getLLVMStyleWithColumns(40); 12576 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12577 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12578 Style.BraceWrapping.AfterFunction = true; 12579 Style.BraceWrapping.SplitEmptyFunction = true; 12580 Style.BraceWrapping.SplitEmptyRecord = false; 12581 12582 verifyFormat("class C {};", Style); 12583 verifyFormat("struct C {};", Style); 12584 verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12585 " int bbbbbbbbbbbbbbbbbbbbbbbb)\n" 12586 "{\n" 12587 "}", 12588 Style); 12589 verifyFormat("class C {\n" 12590 " C()\n" 12591 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa(),\n" 12592 " bbbbbbbbbbbbbbbbbbb()\n" 12593 " {\n" 12594 " }\n" 12595 " void\n" 12596 " m(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12597 " int bbbbbbbbbbbbbbbbbbbbbbbb)\n" 12598 " {\n" 12599 " }\n" 12600 "};", 12601 Style); 12602 } 12603 12604 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) { 12605 FormatStyle Style = getLLVMStyle(); 12606 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 12607 verifyFormat("#ifdef A\n" 12608 "int f() {}\n" 12609 "#else\n" 12610 "int g() {}\n" 12611 "#endif", 12612 Style); 12613 } 12614 12615 TEST_F(FormatTest, SplitEmptyClass) { 12616 FormatStyle Style = getLLVMStyle(); 12617 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12618 Style.BraceWrapping.AfterClass = true; 12619 Style.BraceWrapping.SplitEmptyRecord = false; 12620 12621 verifyFormat("class Foo\n" 12622 "{};", 12623 Style); 12624 verifyFormat("/* something */ class Foo\n" 12625 "{};", 12626 Style); 12627 verifyFormat("template <typename X> class Foo\n" 12628 "{};", 12629 Style); 12630 verifyFormat("class Foo\n" 12631 "{\n" 12632 " Foo();\n" 12633 "};", 12634 Style); 12635 verifyFormat("typedef class Foo\n" 12636 "{\n" 12637 "} Foo_t;", 12638 Style); 12639 12640 Style.BraceWrapping.SplitEmptyRecord = true; 12641 Style.BraceWrapping.AfterStruct = true; 12642 verifyFormat("class rep\n" 12643 "{\n" 12644 "};", 12645 Style); 12646 verifyFormat("struct rep\n" 12647 "{\n" 12648 "};", 12649 Style); 12650 verifyFormat("template <typename T> class rep\n" 12651 "{\n" 12652 "};", 12653 Style); 12654 verifyFormat("template <typename T> struct rep\n" 12655 "{\n" 12656 "};", 12657 Style); 12658 verifyFormat("class rep\n" 12659 "{\n" 12660 " int x;\n" 12661 "};", 12662 Style); 12663 verifyFormat("struct rep\n" 12664 "{\n" 12665 " int x;\n" 12666 "};", 12667 Style); 12668 verifyFormat("template <typename T> class rep\n" 12669 "{\n" 12670 " int x;\n" 12671 "};", 12672 Style); 12673 verifyFormat("template <typename T> struct rep\n" 12674 "{\n" 12675 " int x;\n" 12676 "};", 12677 Style); 12678 verifyFormat("template <typename T> class rep // Foo\n" 12679 "{\n" 12680 " int x;\n" 12681 "};", 12682 Style); 12683 verifyFormat("template <typename T> struct rep // Bar\n" 12684 "{\n" 12685 " int x;\n" 12686 "};", 12687 Style); 12688 12689 verifyFormat("template <typename T> class rep<T>\n" 12690 "{\n" 12691 " int x;\n" 12692 "};", 12693 Style); 12694 12695 verifyFormat("template <typename T> class rep<std::complex<T>>\n" 12696 "{\n" 12697 " int x;\n" 12698 "};", 12699 Style); 12700 verifyFormat("template <typename T> class rep<std::complex<T>>\n" 12701 "{\n" 12702 "};", 12703 Style); 12704 12705 verifyFormat("#include \"stdint.h\"\n" 12706 "namespace rep {}", 12707 Style); 12708 verifyFormat("#include <stdint.h>\n" 12709 "namespace rep {}", 12710 Style); 12711 verifyFormat("#include <stdint.h>\n" 12712 "namespace rep {}", 12713 "#include <stdint.h>\n" 12714 "namespace rep {\n" 12715 "\n" 12716 "\n" 12717 "}", 12718 Style); 12719 } 12720 12721 TEST_F(FormatTest, SplitEmptyStruct) { 12722 FormatStyle Style = getLLVMStyle(); 12723 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12724 Style.BraceWrapping.AfterStruct = true; 12725 Style.BraceWrapping.SplitEmptyRecord = false; 12726 12727 verifyFormat("struct Foo\n" 12728 "{};", 12729 Style); 12730 verifyFormat("/* something */ struct Foo\n" 12731 "{};", 12732 Style); 12733 verifyFormat("template <typename X> struct Foo\n" 12734 "{};", 12735 Style); 12736 verifyFormat("struct Foo\n" 12737 "{\n" 12738 " Foo();\n" 12739 "};", 12740 Style); 12741 verifyFormat("typedef struct Foo\n" 12742 "{\n" 12743 "} Foo_t;", 12744 Style); 12745 // typedef struct Bar {} Bar_t; 12746 } 12747 12748 TEST_F(FormatTest, SplitEmptyUnion) { 12749 FormatStyle Style = getLLVMStyle(); 12750 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12751 Style.BraceWrapping.AfterUnion = true; 12752 Style.BraceWrapping.SplitEmptyRecord = false; 12753 12754 verifyFormat("union Foo\n" 12755 "{};", 12756 Style); 12757 verifyFormat("/* something */ union Foo\n" 12758 "{};", 12759 Style); 12760 verifyFormat("union Foo\n" 12761 "{\n" 12762 " A,\n" 12763 "};", 12764 Style); 12765 verifyFormat("typedef union Foo\n" 12766 "{\n" 12767 "} Foo_t;", 12768 Style); 12769 } 12770 12771 TEST_F(FormatTest, SplitEmptyNamespace) { 12772 FormatStyle Style = getLLVMStyle(); 12773 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12774 Style.BraceWrapping.AfterNamespace = true; 12775 Style.BraceWrapping.SplitEmptyNamespace = false; 12776 12777 verifyFormat("namespace Foo\n" 12778 "{};", 12779 Style); 12780 verifyFormat("/* something */ namespace Foo\n" 12781 "{};", 12782 Style); 12783 verifyFormat("inline namespace Foo\n" 12784 "{};", 12785 Style); 12786 verifyFormat("/* something */ inline namespace Foo\n" 12787 "{};", 12788 Style); 12789 verifyFormat("export namespace Foo\n" 12790 "{};", 12791 Style); 12792 verifyFormat("namespace Foo\n" 12793 "{\n" 12794 "void Bar();\n" 12795 "};", 12796 Style); 12797 } 12798 12799 TEST_F(FormatTest, NeverMergeShortRecords) { 12800 FormatStyle Style = getLLVMStyle(); 12801 12802 verifyFormat("class Foo {\n" 12803 " Foo();\n" 12804 "};", 12805 Style); 12806 verifyFormat("typedef class Foo {\n" 12807 " Foo();\n" 12808 "} Foo_t;", 12809 Style); 12810 verifyFormat("struct Foo {\n" 12811 " Foo();\n" 12812 "};", 12813 Style); 12814 verifyFormat("typedef struct Foo {\n" 12815 " Foo();\n" 12816 "} Foo_t;", 12817 Style); 12818 verifyFormat("union Foo {\n" 12819 " A,\n" 12820 "};", 12821 Style); 12822 verifyFormat("typedef union Foo {\n" 12823 " A,\n" 12824 "} Foo_t;", 12825 Style); 12826 verifyFormat("namespace Foo {\n" 12827 "void Bar();\n" 12828 "};", 12829 Style); 12830 12831 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12832 Style.BraceWrapping.AfterClass = true; 12833 Style.BraceWrapping.AfterStruct = true; 12834 Style.BraceWrapping.AfterUnion = true; 12835 Style.BraceWrapping.AfterNamespace = true; 12836 verifyFormat("class Foo\n" 12837 "{\n" 12838 " Foo();\n" 12839 "};", 12840 Style); 12841 verifyFormat("typedef class Foo\n" 12842 "{\n" 12843 " Foo();\n" 12844 "} Foo_t;", 12845 Style); 12846 verifyFormat("struct Foo\n" 12847 "{\n" 12848 " Foo();\n" 12849 "};", 12850 Style); 12851 verifyFormat("typedef struct Foo\n" 12852 "{\n" 12853 " Foo();\n" 12854 "} Foo_t;", 12855 Style); 12856 verifyFormat("union Foo\n" 12857 "{\n" 12858 " A,\n" 12859 "};", 12860 Style); 12861 verifyFormat("typedef union Foo\n" 12862 "{\n" 12863 " A,\n" 12864 "} Foo_t;", 12865 Style); 12866 verifyFormat("namespace Foo\n" 12867 "{\n" 12868 "void Bar();\n" 12869 "};", 12870 Style); 12871 } 12872 12873 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) { 12874 // Elaborate type variable declarations. 12875 verifyFormat("struct foo a = {bar};\nint n;"); 12876 verifyFormat("class foo a = {bar};\nint n;"); 12877 verifyFormat("union foo a = {bar};\nint n;"); 12878 12879 // Elaborate types inside function definitions. 12880 verifyFormat("struct foo f() {}\nint n;"); 12881 verifyFormat("class foo f() {}\nint n;"); 12882 verifyFormat("union foo f() {}\nint n;"); 12883 12884 // Templates. 12885 verifyFormat("template <class X> void f() {}\nint n;"); 12886 verifyFormat("template <struct X> void f() {}\nint n;"); 12887 verifyFormat("template <union X> void f() {}\nint n;"); 12888 12889 // Actual definitions... 12890 verifyFormat("struct {\n} n;"); 12891 verifyFormat( 12892 "template <template <class T, class Y>, class Z> class X {\n} n;"); 12893 verifyFormat("union Z {\n int n;\n} x;"); 12894 verifyFormat("class MACRO Z {\n} n;"); 12895 verifyFormat("class MACRO(X) Z {\n} n;"); 12896 verifyFormat("class __attribute__(X) Z {\n} n;"); 12897 verifyFormat("class __declspec(X) Z {\n} n;"); 12898 verifyFormat("class A##B##C {\n} n;"); 12899 verifyFormat("class alignas(16) Z {\n} n;"); 12900 verifyFormat("class MACRO(X) alignas(16) Z {\n} n;"); 12901 verifyFormat("class MACROA MACRO(X) Z {\n} n;"); 12902 12903 // Redefinition from nested context: 12904 verifyFormat("class A::B::C {\n} n;"); 12905 12906 // Template definitions. 12907 verifyFormat( 12908 "template <typename F>\n" 12909 "Matcher(const Matcher<F> &Other,\n" 12910 " typename enable_if_c<is_base_of<F, T>::value &&\n" 12911 " !is_same<F, T>::value>::type * = 0)\n" 12912 " : Implementation(new ImplicitCastMatcher<F>(Other)) {}"); 12913 12914 // FIXME: This is still incorrectly handled at the formatter side. 12915 verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};"); 12916 verifyFormat("int i = SomeFunction(a<b, a> b);"); 12917 12918 // FIXME: 12919 // This now gets parsed incorrectly as class definition. 12920 // verifyFormat("class A<int> f() {\n}\nint n;"); 12921 12922 // Elaborate types where incorrectly parsing the structural element would 12923 // break the indent. 12924 verifyFormat("if (true)\n" 12925 " class X x;\n" 12926 "else\n" 12927 " f();\n"); 12928 12929 // This is simply incomplete. Formatting is not important, but must not crash. 12930 verifyFormat("class A:"); 12931 } 12932 12933 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) { 12934 EXPECT_EQ("#error Leave all white!!!!! space* alone!\n", 12935 format("#error Leave all white!!!!! space* alone!\n")); 12936 EXPECT_EQ( 12937 "#warning Leave all white!!!!! space* alone!\n", 12938 format("#warning Leave all white!!!!! space* alone!\n")); 12939 EXPECT_EQ("#error 1", format(" # error 1")); 12940 EXPECT_EQ("#warning 1", format(" # warning 1")); 12941 } 12942 12943 TEST_F(FormatTest, FormatHashIfExpressions) { 12944 verifyFormat("#if AAAA && BBBB"); 12945 verifyFormat("#if (AAAA && BBBB)"); 12946 verifyFormat("#elif (AAAA && BBBB)"); 12947 // FIXME: Come up with a better indentation for #elif. 12948 verifyFormat( 12949 "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) && \\\n" 12950 " defined(BBBBBBBB)\n" 12951 "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) && \\\n" 12952 " defined(BBBBBBBB)\n" 12953 "#endif", 12954 getLLVMStyleWithColumns(65)); 12955 } 12956 12957 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) { 12958 FormatStyle AllowsMergedIf = getGoogleStyle(); 12959 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 12960 FormatStyle::SIS_WithoutElse; 12961 verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf); 12962 verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf); 12963 verifyFormat("if (true)\n#error E\n return 42;", AllowsMergedIf); 12964 EXPECT_EQ("if (true) return 42;", 12965 format("if (true)\nreturn 42;", AllowsMergedIf)); 12966 FormatStyle ShortMergedIf = AllowsMergedIf; 12967 ShortMergedIf.ColumnLimit = 25; 12968 verifyFormat("#define A \\\n" 12969 " if (true) return 42;", 12970 ShortMergedIf); 12971 verifyFormat("#define A \\\n" 12972 " f(); \\\n" 12973 " if (true)\n" 12974 "#define B", 12975 ShortMergedIf); 12976 verifyFormat("#define A \\\n" 12977 " f(); \\\n" 12978 " if (true)\n" 12979 "g();", 12980 ShortMergedIf); 12981 verifyFormat("{\n" 12982 "#ifdef A\n" 12983 " // Comment\n" 12984 " if (true) continue;\n" 12985 "#endif\n" 12986 " // Comment\n" 12987 " if (true) continue;\n" 12988 "}", 12989 ShortMergedIf); 12990 ShortMergedIf.ColumnLimit = 33; 12991 verifyFormat("#define A \\\n" 12992 " if constexpr (true) return 42;", 12993 ShortMergedIf); 12994 verifyFormat("#define A \\\n" 12995 " if CONSTEXPR (true) return 42;", 12996 ShortMergedIf); 12997 ShortMergedIf.ColumnLimit = 29; 12998 verifyFormat("#define A \\\n" 12999 " if (aaaaaaaaaa) return 1; \\\n" 13000 " return 2;", 13001 ShortMergedIf); 13002 ShortMergedIf.ColumnLimit = 28; 13003 verifyFormat("#define A \\\n" 13004 " if (aaaaaaaaaa) \\\n" 13005 " return 1; \\\n" 13006 " return 2;", 13007 ShortMergedIf); 13008 verifyFormat("#define A \\\n" 13009 " if constexpr (aaaaaaa) \\\n" 13010 " return 1; \\\n" 13011 " return 2;", 13012 ShortMergedIf); 13013 verifyFormat("#define A \\\n" 13014 " if CONSTEXPR (aaaaaaa) \\\n" 13015 " return 1; \\\n" 13016 " return 2;", 13017 ShortMergedIf); 13018 } 13019 13020 TEST_F(FormatTest, FormatStarDependingOnContext) { 13021 verifyFormat("void f(int *a);"); 13022 verifyFormat("void f() { f(fint * b); }"); 13023 verifyFormat("class A {\n void f(int *a);\n};"); 13024 verifyFormat("class A {\n int *a;\n};"); 13025 verifyFormat("namespace a {\n" 13026 "namespace b {\n" 13027 "class A {\n" 13028 " void f() {}\n" 13029 " int *a;\n" 13030 "};\n" 13031 "} // namespace b\n" 13032 "} // namespace a"); 13033 } 13034 13035 TEST_F(FormatTest, SpecialTokensAtEndOfLine) { 13036 verifyFormat("while"); 13037 verifyFormat("operator"); 13038 } 13039 13040 TEST_F(FormatTest, SkipsDeeplyNestedLines) { 13041 // This code would be painfully slow to format if we didn't skip it. 13042 std::string Code("A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" // 20x 13043 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13044 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13045 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13046 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13047 "A(1, 1)\n" 13048 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x 13049 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13050 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13051 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13052 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13053 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13054 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13055 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13056 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13057 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n"); 13058 // Deeply nested part is untouched, rest is formatted. 13059 EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n", 13060 format(std::string("int i;\n") + Code + "int j;\n", 13061 getLLVMStyle(), SC_ExpectIncomplete)); 13062 } 13063 13064 //===----------------------------------------------------------------------===// 13065 // Objective-C tests. 13066 //===----------------------------------------------------------------------===// 13067 13068 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) { 13069 verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;"); 13070 EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;", 13071 format("-(NSUInteger)indexOfObject:(id)anObject;")); 13072 EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;")); 13073 EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;")); 13074 EXPECT_EQ("- (NSInteger)Method3:(id)anObject;", 13075 format("-(NSInteger)Method3:(id)anObject;")); 13076 EXPECT_EQ("- (NSInteger)Method4:(id)anObject;", 13077 format("-(NSInteger)Method4:(id)anObject;")); 13078 EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;", 13079 format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;")); 13080 EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;", 13081 format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;")); 13082 EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject " 13083 "forAllCells:(BOOL)flag;", 13084 format("- (void)sendAction:(SEL)aSelector to:(id)anObject " 13085 "forAllCells:(BOOL)flag;")); 13086 13087 // Very long objectiveC method declaration. 13088 verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n" 13089 " (SoooooooooooooooooooooomeType *)bbbbbbbbbb;"); 13090 verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n" 13091 " inRange:(NSRange)range\n" 13092 " outRange:(NSRange)out_range\n" 13093 " outRange1:(NSRange)out_range1\n" 13094 " outRange2:(NSRange)out_range2\n" 13095 " outRange3:(NSRange)out_range3\n" 13096 " outRange4:(NSRange)out_range4\n" 13097 " outRange5:(NSRange)out_range5\n" 13098 " outRange6:(NSRange)out_range6\n" 13099 " outRange7:(NSRange)out_range7\n" 13100 " outRange8:(NSRange)out_range8\n" 13101 " outRange9:(NSRange)out_range9;"); 13102 13103 // When the function name has to be wrapped. 13104 FormatStyle Style = getLLVMStyle(); 13105 // ObjC ignores IndentWrappedFunctionNames when wrapping methods 13106 // and always indents instead. 13107 Style.IndentWrappedFunctionNames = false; 13108 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n" 13109 " veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n" 13110 " anotherName:(NSString)bbbbbbbbbbbbbb {\n" 13111 "}", 13112 Style); 13113 Style.IndentWrappedFunctionNames = true; 13114 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n" 13115 " veryLooooooooooongName:(NSString)cccccccccccccc\n" 13116 " anotherName:(NSString)dddddddddddddd {\n" 13117 "}", 13118 Style); 13119 13120 verifyFormat("- (int)sum:(vector<int>)numbers;"); 13121 verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;"); 13122 // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC 13123 // protocol lists (but not for template classes): 13124 // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;"); 13125 13126 verifyFormat("- (int (*)())foo:(int (*)())f;"); 13127 verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;"); 13128 13129 // If there's no return type (very rare in practice!), LLVM and Google style 13130 // agree. 13131 verifyFormat("- foo;"); 13132 verifyFormat("- foo:(int)f;"); 13133 verifyGoogleFormat("- foo:(int)foo;"); 13134 } 13135 13136 TEST_F(FormatTest, BreaksStringLiterals) { 13137 EXPECT_EQ("\"some text \"\n" 13138 "\"other\";", 13139 format("\"some text other\";", getLLVMStyleWithColumns(12))); 13140 EXPECT_EQ("\"some text \"\n" 13141 "\"other\";", 13142 format("\\\n\"some text other\";", getLLVMStyleWithColumns(12))); 13143 EXPECT_EQ( 13144 "#define A \\\n" 13145 " \"some \" \\\n" 13146 " \"text \" \\\n" 13147 " \"other\";", 13148 format("#define A \"some text other\";", getLLVMStyleWithColumns(12))); 13149 EXPECT_EQ( 13150 "#define A \\\n" 13151 " \"so \" \\\n" 13152 " \"text \" \\\n" 13153 " \"other\";", 13154 format("#define A \"so text other\";", getLLVMStyleWithColumns(12))); 13155 13156 EXPECT_EQ("\"some text\"", 13157 format("\"some text\"", getLLVMStyleWithColumns(1))); 13158 EXPECT_EQ("\"some text\"", 13159 format("\"some text\"", getLLVMStyleWithColumns(11))); 13160 EXPECT_EQ("\"some \"\n" 13161 "\"text\"", 13162 format("\"some text\"", getLLVMStyleWithColumns(10))); 13163 EXPECT_EQ("\"some \"\n" 13164 "\"text\"", 13165 format("\"some text\"", getLLVMStyleWithColumns(7))); 13166 EXPECT_EQ("\"some\"\n" 13167 "\" tex\"\n" 13168 "\"t\"", 13169 format("\"some text\"", getLLVMStyleWithColumns(6))); 13170 EXPECT_EQ("\"some\"\n" 13171 "\" tex\"\n" 13172 "\" and\"", 13173 format("\"some tex and\"", getLLVMStyleWithColumns(6))); 13174 EXPECT_EQ("\"some\"\n" 13175 "\"/tex\"\n" 13176 "\"/and\"", 13177 format("\"some/tex/and\"", getLLVMStyleWithColumns(6))); 13178 13179 EXPECT_EQ("variable =\n" 13180 " \"long string \"\n" 13181 " \"literal\";", 13182 format("variable = \"long string literal\";", 13183 getLLVMStyleWithColumns(20))); 13184 13185 EXPECT_EQ("variable = f(\n" 13186 " \"long string \"\n" 13187 " \"literal\",\n" 13188 " short,\n" 13189 " loooooooooooooooooooong);", 13190 format("variable = f(\"long string literal\", short, " 13191 "loooooooooooooooooooong);", 13192 getLLVMStyleWithColumns(20))); 13193 13194 EXPECT_EQ( 13195 "f(g(\"long string \"\n" 13196 " \"literal\"),\n" 13197 " b);", 13198 format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20))); 13199 EXPECT_EQ("f(g(\"long string \"\n" 13200 " \"literal\",\n" 13201 " a),\n" 13202 " b);", 13203 format("f(g(\"long string literal\", a), b);", 13204 getLLVMStyleWithColumns(20))); 13205 EXPECT_EQ( 13206 "f(\"one two\".split(\n" 13207 " variable));", 13208 format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20))); 13209 EXPECT_EQ("f(\"one two three four five six \"\n" 13210 " \"seven\".split(\n" 13211 " really_looooong_variable));", 13212 format("f(\"one two three four five six seven\"." 13213 "split(really_looooong_variable));", 13214 getLLVMStyleWithColumns(33))); 13215 13216 EXPECT_EQ("f(\"some \"\n" 13217 " \"text\",\n" 13218 " other);", 13219 format("f(\"some text\", other);", getLLVMStyleWithColumns(10))); 13220 13221 // Only break as a last resort. 13222 verifyFormat( 13223 "aaaaaaaaaaaaaaaaaaaa(\n" 13224 " aaaaaaaaaaaaaaaaaaaa,\n" 13225 " aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));"); 13226 13227 EXPECT_EQ("\"splitmea\"\n" 13228 "\"trandomp\"\n" 13229 "\"oint\"", 13230 format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10))); 13231 13232 EXPECT_EQ("\"split/\"\n" 13233 "\"pathat/\"\n" 13234 "\"slashes\"", 13235 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10))); 13236 13237 EXPECT_EQ("\"split/\"\n" 13238 "\"pathat/\"\n" 13239 "\"slashes\"", 13240 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10))); 13241 EXPECT_EQ("\"split at \"\n" 13242 "\"spaces/at/\"\n" 13243 "\"slashes.at.any$\"\n" 13244 "\"non-alphanumeric%\"\n" 13245 "\"1111111111characte\"\n" 13246 "\"rs\"", 13247 format("\"split at " 13248 "spaces/at/" 13249 "slashes.at." 13250 "any$non-" 13251 "alphanumeric%" 13252 "1111111111characte" 13253 "rs\"", 13254 getLLVMStyleWithColumns(20))); 13255 13256 // Verify that splitting the strings understands 13257 // Style::AlwaysBreakBeforeMultilineStrings. 13258 EXPECT_EQ("aaaaaaaaaaaa(\n" 13259 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n" 13260 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");", 13261 format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa " 13262 "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa " 13263 "aaaaaaaaaaaaaaaaaaaaaa\");", 13264 getGoogleStyle())); 13265 EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13266 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";", 13267 format("return \"aaaaaaaaaaaaaaaaaaaaaa " 13268 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa " 13269 "aaaaaaaaaaaaaaaaaaaaaa\";", 13270 getGoogleStyle())); 13271 EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13272 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";", 13273 format("llvm::outs() << " 13274 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa" 13275 "aaaaaaaaaaaaaaaaaaa\";")); 13276 EXPECT_EQ("ffff(\n" 13277 " {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13278 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});", 13279 format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa " 13280 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});", 13281 getGoogleStyle())); 13282 13283 FormatStyle Style = getLLVMStyleWithColumns(12); 13284 Style.BreakStringLiterals = false; 13285 EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style)); 13286 13287 FormatStyle AlignLeft = getLLVMStyleWithColumns(12); 13288 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left; 13289 EXPECT_EQ("#define A \\\n" 13290 " \"some \" \\\n" 13291 " \"text \" \\\n" 13292 " \"other\";", 13293 format("#define A \"some text other\";", AlignLeft)); 13294 } 13295 13296 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) { 13297 EXPECT_EQ("C a = \"some more \"\n" 13298 " \"text\";", 13299 format("C a = \"some more text\";", getLLVMStyleWithColumns(18))); 13300 } 13301 13302 TEST_F(FormatTest, FullyRemoveEmptyLines) { 13303 FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80); 13304 NoEmptyLines.MaxEmptyLinesToKeep = 0; 13305 EXPECT_EQ("int i = a(b());", 13306 format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines)); 13307 } 13308 13309 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) { 13310 EXPECT_EQ( 13311 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 13312 "(\n" 13313 " \"x\t\");", 13314 format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 13315 "aaaaaaa(" 13316 "\"x\t\");")); 13317 } 13318 13319 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) { 13320 EXPECT_EQ( 13321 "u8\"utf8 string \"\n" 13322 "u8\"literal\";", 13323 format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16))); 13324 EXPECT_EQ( 13325 "u\"utf16 string \"\n" 13326 "u\"literal\";", 13327 format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16))); 13328 EXPECT_EQ( 13329 "U\"utf32 string \"\n" 13330 "U\"literal\";", 13331 format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16))); 13332 EXPECT_EQ("L\"wide string \"\n" 13333 "L\"literal\";", 13334 format("L\"wide string literal\";", getGoogleStyleWithColumns(16))); 13335 EXPECT_EQ("@\"NSString \"\n" 13336 "@\"literal\";", 13337 format("@\"NSString literal\";", getGoogleStyleWithColumns(19))); 13338 verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26)); 13339 13340 // This input makes clang-format try to split the incomplete unicode escape 13341 // sequence, which used to lead to a crasher. 13342 verifyNoCrash( 13343 "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 13344 getLLVMStyleWithColumns(60)); 13345 } 13346 13347 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) { 13348 FormatStyle Style = getGoogleStyleWithColumns(15); 13349 EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style)); 13350 EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style)); 13351 EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style)); 13352 EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style)); 13353 EXPECT_EQ("u8R\"x(raw literal)x\";", 13354 format("u8R\"x(raw literal)x\";", Style)); 13355 } 13356 13357 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) { 13358 FormatStyle Style = getLLVMStyleWithColumns(20); 13359 EXPECT_EQ( 13360 "_T(\"aaaaaaaaaaaaaa\")\n" 13361 "_T(\"aaaaaaaaaaaaaa\")\n" 13362 "_T(\"aaaaaaaaaaaa\")", 13363 format(" _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style)); 13364 EXPECT_EQ("f(x,\n" 13365 " _T(\"aaaaaaaaaaaa\")\n" 13366 " _T(\"aaa\"),\n" 13367 " z);", 13368 format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style)); 13369 13370 // FIXME: Handle embedded spaces in one iteration. 13371 // EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n" 13372 // "_T(\"aaaaaaaaaaaaa\")\n" 13373 // "_T(\"aaaaaaaaaaaaa\")\n" 13374 // "_T(\"a\")", 13375 // format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", 13376 // getLLVMStyleWithColumns(20))); 13377 EXPECT_EQ( 13378 "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", 13379 format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style)); 13380 EXPECT_EQ("f(\n" 13381 "#if !TEST\n" 13382 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n" 13383 "#endif\n" 13384 ");", 13385 format("f(\n" 13386 "#if !TEST\n" 13387 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n" 13388 "#endif\n" 13389 ");")); 13390 EXPECT_EQ("f(\n" 13391 "\n" 13392 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));", 13393 format("f(\n" 13394 "\n" 13395 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));")); 13396 // Regression test for accessing tokens past the end of a vector in the 13397 // TokenLexer. 13398 verifyNoCrash(R"(_T( 13399 " 13400 ) 13401 )"); 13402 } 13403 13404 TEST_F(FormatTest, BreaksStringLiteralOperands) { 13405 // In a function call with two operands, the second can be broken with no line 13406 // break before it. 13407 EXPECT_EQ( 13408 "func(a, \"long long \"\n" 13409 " \"long long\");", 13410 format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24))); 13411 // In a function call with three operands, the second must be broken with a 13412 // line break before it. 13413 EXPECT_EQ("func(a,\n" 13414 " \"long long long \"\n" 13415 " \"long\",\n" 13416 " c);", 13417 format("func(a, \"long long long long\", c);", 13418 getLLVMStyleWithColumns(24))); 13419 // In a function call with three operands, the third must be broken with a 13420 // line break before it. 13421 EXPECT_EQ("func(a, b,\n" 13422 " \"long long long \"\n" 13423 " \"long\");", 13424 format("func(a, b, \"long long long long\");", 13425 getLLVMStyleWithColumns(24))); 13426 // In a function call with three operands, both the second and the third must 13427 // be broken with a line break before them. 13428 EXPECT_EQ("func(a,\n" 13429 " \"long long long \"\n" 13430 " \"long\",\n" 13431 " \"long long long \"\n" 13432 " \"long\");", 13433 format("func(a, \"long long long long\", \"long long long long\");", 13434 getLLVMStyleWithColumns(24))); 13435 // In a chain of << with two operands, the second can be broken with no line 13436 // break before it. 13437 EXPECT_EQ("a << \"line line \"\n" 13438 " \"line\";", 13439 format("a << \"line line line\";", getLLVMStyleWithColumns(20))); 13440 // In a chain of << with three operands, the second can be broken with no line 13441 // break before it. 13442 EXPECT_EQ( 13443 "abcde << \"line \"\n" 13444 " \"line line\"\n" 13445 " << c;", 13446 format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20))); 13447 // In a chain of << with three operands, the third must be broken with a line 13448 // break before it. 13449 EXPECT_EQ( 13450 "a << b\n" 13451 " << \"line line \"\n" 13452 " \"line\";", 13453 format("a << b << \"line line line\";", getLLVMStyleWithColumns(20))); 13454 // In a chain of << with three operands, the second can be broken with no line 13455 // break before it and the third must be broken with a line break before it. 13456 EXPECT_EQ("abcd << \"line line \"\n" 13457 " \"line\"\n" 13458 " << \"line line \"\n" 13459 " \"line\";", 13460 format("abcd << \"line line line\" << \"line line line\";", 13461 getLLVMStyleWithColumns(20))); 13462 // In a chain of binary operators with two operands, the second can be broken 13463 // with no line break before it. 13464 EXPECT_EQ( 13465 "abcd + \"line line \"\n" 13466 " \"line line\";", 13467 format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20))); 13468 // In a chain of binary operators with three operands, the second must be 13469 // broken with a line break before it. 13470 EXPECT_EQ("abcd +\n" 13471 " \"line line \"\n" 13472 " \"line line\" +\n" 13473 " e;", 13474 format("abcd + \"line line line line\" + e;", 13475 getLLVMStyleWithColumns(20))); 13476 // In a function call with two operands, with AlignAfterOpenBracket enabled, 13477 // the first must be broken with a line break before it. 13478 FormatStyle Style = getLLVMStyleWithColumns(25); 13479 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 13480 EXPECT_EQ("someFunction(\n" 13481 " \"long long long \"\n" 13482 " \"long\",\n" 13483 " a);", 13484 format("someFunction(\"long long long long\", a);", Style)); 13485 } 13486 13487 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) { 13488 EXPECT_EQ( 13489 "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13490 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13491 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";", 13492 format("aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13493 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13494 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";")); 13495 } 13496 13497 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) { 13498 EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);", 13499 format("f(g(R\"x(raw literal)x\", a), b);", getGoogleStyle())); 13500 EXPECT_EQ("fffffffffff(g(R\"x(\n" 13501 "multiline raw string literal xxxxxxxxxxxxxx\n" 13502 ")x\",\n" 13503 " a),\n" 13504 " b);", 13505 format("fffffffffff(g(R\"x(\n" 13506 "multiline raw string literal xxxxxxxxxxxxxx\n" 13507 ")x\", a), b);", 13508 getGoogleStyleWithColumns(20))); 13509 EXPECT_EQ("fffffffffff(\n" 13510 " g(R\"x(qqq\n" 13511 "multiline raw string literal xxxxxxxxxxxxxx\n" 13512 ")x\",\n" 13513 " a),\n" 13514 " b);", 13515 format("fffffffffff(g(R\"x(qqq\n" 13516 "multiline raw string literal xxxxxxxxxxxxxx\n" 13517 ")x\", a), b);", 13518 getGoogleStyleWithColumns(20))); 13519 13520 EXPECT_EQ("fffffffffff(R\"x(\n" 13521 "multiline raw string literal xxxxxxxxxxxxxx\n" 13522 ")x\");", 13523 format("fffffffffff(R\"x(\n" 13524 "multiline raw string literal xxxxxxxxxxxxxx\n" 13525 ")x\");", 13526 getGoogleStyleWithColumns(20))); 13527 EXPECT_EQ("fffffffffff(R\"x(\n" 13528 "multiline raw string literal xxxxxxxxxxxxxx\n" 13529 ")x\" + bbbbbb);", 13530 format("fffffffffff(R\"x(\n" 13531 "multiline raw string literal xxxxxxxxxxxxxx\n" 13532 ")x\" + bbbbbb);", 13533 getGoogleStyleWithColumns(20))); 13534 EXPECT_EQ("fffffffffff(\n" 13535 " R\"x(\n" 13536 "multiline raw string literal xxxxxxxxxxxxxx\n" 13537 ")x\" +\n" 13538 " bbbbbb);", 13539 format("fffffffffff(\n" 13540 " R\"x(\n" 13541 "multiline raw string literal xxxxxxxxxxxxxx\n" 13542 ")x\" + bbbbbb);", 13543 getGoogleStyleWithColumns(20))); 13544 EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);", 13545 format("fffffffffff(\n" 13546 " R\"(single line raw string)\" + bbbbbb);")); 13547 } 13548 13549 TEST_F(FormatTest, SkipsUnknownStringLiterals) { 13550 verifyFormat("string a = \"unterminated;"); 13551 EXPECT_EQ("function(\"unterminated,\n" 13552 " OtherParameter);", 13553 format("function( \"unterminated,\n" 13554 " OtherParameter);")); 13555 } 13556 13557 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) { 13558 FormatStyle Style = getLLVMStyle(); 13559 Style.Standard = FormatStyle::LS_Cpp03; 13560 EXPECT_EQ("#define x(_a) printf(\"foo\" _a);", 13561 format("#define x(_a) printf(\"foo\"_a);", Style)); 13562 } 13563 13564 TEST_F(FormatTest, CppLexVersion) { 13565 FormatStyle Style = getLLVMStyle(); 13566 // Formatting of x * y differs if x is a type. 13567 verifyFormat("void foo() { MACRO(a * b); }", Style); 13568 verifyFormat("void foo() { MACRO(int *b); }", Style); 13569 13570 // LLVM style uses latest lexer. 13571 verifyFormat("void foo() { MACRO(char8_t *b); }", Style); 13572 Style.Standard = FormatStyle::LS_Cpp17; 13573 // But in c++17, char8_t isn't a keyword. 13574 verifyFormat("void foo() { MACRO(char8_t * b); }", Style); 13575 } 13576 13577 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); } 13578 13579 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) { 13580 EXPECT_EQ("someFunction(\"aaabbbcccd\"\n" 13581 " \"ddeeefff\");", 13582 format("someFunction(\"aaabbbcccdddeeefff\");", 13583 getLLVMStyleWithColumns(25))); 13584 EXPECT_EQ("someFunction1234567890(\n" 13585 " \"aaabbbcccdddeeefff\");", 13586 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 13587 getLLVMStyleWithColumns(26))); 13588 EXPECT_EQ("someFunction1234567890(\n" 13589 " \"aaabbbcccdddeeeff\"\n" 13590 " \"f\");", 13591 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 13592 getLLVMStyleWithColumns(25))); 13593 EXPECT_EQ("someFunction1234567890(\n" 13594 " \"aaabbbcccdddeeeff\"\n" 13595 " \"f\");", 13596 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 13597 getLLVMStyleWithColumns(24))); 13598 EXPECT_EQ("someFunction(\n" 13599 " \"aaabbbcc ddde \"\n" 13600 " \"efff\");", 13601 format("someFunction(\"aaabbbcc ddde efff\");", 13602 getLLVMStyleWithColumns(25))); 13603 EXPECT_EQ("someFunction(\"aaabbbccc \"\n" 13604 " \"ddeeefff\");", 13605 format("someFunction(\"aaabbbccc ddeeefff\");", 13606 getLLVMStyleWithColumns(25))); 13607 EXPECT_EQ("someFunction1234567890(\n" 13608 " \"aaabb \"\n" 13609 " \"cccdddeeefff\");", 13610 format("someFunction1234567890(\"aaabb cccdddeeefff\");", 13611 getLLVMStyleWithColumns(25))); 13612 EXPECT_EQ("#define A \\\n" 13613 " string s = \\\n" 13614 " \"123456789\" \\\n" 13615 " \"0\"; \\\n" 13616 " int i;", 13617 format("#define A string s = \"1234567890\"; int i;", 13618 getLLVMStyleWithColumns(20))); 13619 EXPECT_EQ("someFunction(\n" 13620 " \"aaabbbcc \"\n" 13621 " \"dddeeefff\");", 13622 format("someFunction(\"aaabbbcc dddeeefff\");", 13623 getLLVMStyleWithColumns(25))); 13624 } 13625 13626 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) { 13627 EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3))); 13628 EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2))); 13629 EXPECT_EQ("\"test\"\n" 13630 "\"\\n\"", 13631 format("\"test\\n\"", getLLVMStyleWithColumns(7))); 13632 EXPECT_EQ("\"tes\\\\\"\n" 13633 "\"n\"", 13634 format("\"tes\\\\n\"", getLLVMStyleWithColumns(7))); 13635 EXPECT_EQ("\"\\\\\\\\\"\n" 13636 "\"\\n\"", 13637 format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7))); 13638 EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7))); 13639 EXPECT_EQ("\"\\uff01\"\n" 13640 "\"test\"", 13641 format("\"\\uff01test\"", getLLVMStyleWithColumns(8))); 13642 EXPECT_EQ("\"\\Uff01ff02\"", 13643 format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11))); 13644 EXPECT_EQ("\"\\x000000000001\"\n" 13645 "\"next\"", 13646 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16))); 13647 EXPECT_EQ("\"\\x000000000001next\"", 13648 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15))); 13649 EXPECT_EQ("\"\\x000000000001\"", 13650 format("\"\\x000000000001\"", getLLVMStyleWithColumns(7))); 13651 EXPECT_EQ("\"test\"\n" 13652 "\"\\000000\"\n" 13653 "\"000001\"", 13654 format("\"test\\000000000001\"", getLLVMStyleWithColumns(9))); 13655 EXPECT_EQ("\"test\\000\"\n" 13656 "\"00000000\"\n" 13657 "\"1\"", 13658 format("\"test\\000000000001\"", getLLVMStyleWithColumns(10))); 13659 } 13660 13661 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) { 13662 verifyFormat("void f() {\n" 13663 " return g() {}\n" 13664 " void h() {}"); 13665 verifyFormat("int a[] = {void forgot_closing_brace(){f();\n" 13666 "g();\n" 13667 "}"); 13668 } 13669 13670 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) { 13671 verifyFormat( 13672 "void f() { return C{param1, param2}.SomeCall(param1, param2); }"); 13673 } 13674 13675 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) { 13676 verifyFormat("class X {\n" 13677 " void f() {\n" 13678 " }\n" 13679 "};", 13680 getLLVMStyleWithColumns(12)); 13681 } 13682 13683 TEST_F(FormatTest, ConfigurableIndentWidth) { 13684 FormatStyle EightIndent = getLLVMStyleWithColumns(18); 13685 EightIndent.IndentWidth = 8; 13686 EightIndent.ContinuationIndentWidth = 8; 13687 verifyFormat("void f() {\n" 13688 " someFunction();\n" 13689 " if (true) {\n" 13690 " f();\n" 13691 " }\n" 13692 "}", 13693 EightIndent); 13694 verifyFormat("class X {\n" 13695 " void f() {\n" 13696 " }\n" 13697 "};", 13698 EightIndent); 13699 verifyFormat("int x[] = {\n" 13700 " call(),\n" 13701 " call()};", 13702 EightIndent); 13703 } 13704 13705 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) { 13706 verifyFormat("double\n" 13707 "f();", 13708 getLLVMStyleWithColumns(8)); 13709 } 13710 13711 TEST_F(FormatTest, ConfigurableUseOfTab) { 13712 FormatStyle Tab = getLLVMStyleWithColumns(42); 13713 Tab.IndentWidth = 8; 13714 Tab.UseTab = FormatStyle::UT_Always; 13715 Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left; 13716 13717 EXPECT_EQ("if (aaaaaaaa && // q\n" 13718 " bb)\t\t// w\n" 13719 "\t;", 13720 format("if (aaaaaaaa &&// q\n" 13721 "bb)// w\n" 13722 ";", 13723 Tab)); 13724 EXPECT_EQ("if (aaa && bbb) // w\n" 13725 "\t;", 13726 format("if(aaa&&bbb)// w\n" 13727 ";", 13728 Tab)); 13729 13730 verifyFormat("class X {\n" 13731 "\tvoid f() {\n" 13732 "\t\tsomeFunction(parameter1,\n" 13733 "\t\t\t parameter2);\n" 13734 "\t}\n" 13735 "};", 13736 Tab); 13737 verifyFormat("#define A \\\n" 13738 "\tvoid f() { \\\n" 13739 "\t\tsomeFunction( \\\n" 13740 "\t\t parameter1, \\\n" 13741 "\t\t parameter2); \\\n" 13742 "\t}", 13743 Tab); 13744 verifyFormat("int a;\t // x\n" 13745 "int bbbbbbbb; // x\n", 13746 Tab); 13747 13748 Tab.TabWidth = 4; 13749 Tab.IndentWidth = 8; 13750 verifyFormat("class TabWidth4Indent8 {\n" 13751 "\t\tvoid f() {\n" 13752 "\t\t\t\tsomeFunction(parameter1,\n" 13753 "\t\t\t\t\t\t\t parameter2);\n" 13754 "\t\t}\n" 13755 "};", 13756 Tab); 13757 13758 Tab.TabWidth = 4; 13759 Tab.IndentWidth = 4; 13760 verifyFormat("class TabWidth4Indent4 {\n" 13761 "\tvoid f() {\n" 13762 "\t\tsomeFunction(parameter1,\n" 13763 "\t\t\t\t\t parameter2);\n" 13764 "\t}\n" 13765 "};", 13766 Tab); 13767 13768 Tab.TabWidth = 8; 13769 Tab.IndentWidth = 4; 13770 verifyFormat("class TabWidth8Indent4 {\n" 13771 " void f() {\n" 13772 "\tsomeFunction(parameter1,\n" 13773 "\t\t parameter2);\n" 13774 " }\n" 13775 "};", 13776 Tab); 13777 13778 Tab.TabWidth = 8; 13779 Tab.IndentWidth = 8; 13780 EXPECT_EQ("/*\n" 13781 "\t a\t\tcomment\n" 13782 "\t in multiple lines\n" 13783 " */", 13784 format(" /*\t \t \n" 13785 " \t \t a\t\tcomment\t \t\n" 13786 " \t \t in multiple lines\t\n" 13787 " \t */", 13788 Tab)); 13789 13790 Tab.UseTab = FormatStyle::UT_ForIndentation; 13791 verifyFormat("{\n" 13792 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13793 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13794 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13795 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13796 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13797 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13798 "};", 13799 Tab); 13800 verifyFormat("enum AA {\n" 13801 "\ta1, // Force multiple lines\n" 13802 "\ta2,\n" 13803 "\ta3\n" 13804 "};", 13805 Tab); 13806 EXPECT_EQ("if (aaaaaaaa && // q\n" 13807 " bb) // w\n" 13808 "\t;", 13809 format("if (aaaaaaaa &&// q\n" 13810 "bb)// w\n" 13811 ";", 13812 Tab)); 13813 verifyFormat("class X {\n" 13814 "\tvoid f() {\n" 13815 "\t\tsomeFunction(parameter1,\n" 13816 "\t\t parameter2);\n" 13817 "\t}\n" 13818 "};", 13819 Tab); 13820 verifyFormat("{\n" 13821 "\tQ(\n" 13822 "\t {\n" 13823 "\t\t int a;\n" 13824 "\t\t someFunction(aaaaaaaa,\n" 13825 "\t\t bbbbbbb);\n" 13826 "\t },\n" 13827 "\t p);\n" 13828 "}", 13829 Tab); 13830 EXPECT_EQ("{\n" 13831 "\t/* aaaa\n" 13832 "\t bbbb */\n" 13833 "}", 13834 format("{\n" 13835 "/* aaaa\n" 13836 " bbbb */\n" 13837 "}", 13838 Tab)); 13839 EXPECT_EQ("{\n" 13840 "\t/*\n" 13841 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 13842 "\t bbbbbbbbbbbbb\n" 13843 "\t*/\n" 13844 "}", 13845 format("{\n" 13846 "/*\n" 13847 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 13848 "*/\n" 13849 "}", 13850 Tab)); 13851 EXPECT_EQ("{\n" 13852 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 13853 "\t// bbbbbbbbbbbbb\n" 13854 "}", 13855 format("{\n" 13856 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 13857 "}", 13858 Tab)); 13859 EXPECT_EQ("{\n" 13860 "\t/*\n" 13861 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 13862 "\t bbbbbbbbbbbbb\n" 13863 "\t*/\n" 13864 "}", 13865 format("{\n" 13866 "\t/*\n" 13867 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 13868 "\t*/\n" 13869 "}", 13870 Tab)); 13871 EXPECT_EQ("{\n" 13872 "\t/*\n" 13873 "\n" 13874 "\t*/\n" 13875 "}", 13876 format("{\n" 13877 "\t/*\n" 13878 "\n" 13879 "\t*/\n" 13880 "}", 13881 Tab)); 13882 EXPECT_EQ("{\n" 13883 "\t/*\n" 13884 " asdf\n" 13885 "\t*/\n" 13886 "}", 13887 format("{\n" 13888 "\t/*\n" 13889 " asdf\n" 13890 "\t*/\n" 13891 "}", 13892 Tab)); 13893 13894 verifyFormat("void f() {\n" 13895 "\treturn true ? aaaaaaaaaaaaaaaaaa\n" 13896 "\t : bbbbbbbbbbbbbbbbbb\n" 13897 "}", 13898 Tab); 13899 FormatStyle TabNoBreak = Tab; 13900 TabNoBreak.BreakBeforeTernaryOperators = false; 13901 verifyFormat("void f() {\n" 13902 "\treturn true ? aaaaaaaaaaaaaaaaaa :\n" 13903 "\t bbbbbbbbbbbbbbbbbb\n" 13904 "}", 13905 TabNoBreak); 13906 verifyFormat("void f() {\n" 13907 "\treturn true ?\n" 13908 "\t aaaaaaaaaaaaaaaaaaaa :\n" 13909 "\t bbbbbbbbbbbbbbbbbbbb\n" 13910 "}", 13911 TabNoBreak); 13912 13913 Tab.UseTab = FormatStyle::UT_Never; 13914 EXPECT_EQ("/*\n" 13915 " a\t\tcomment\n" 13916 " in multiple lines\n" 13917 " */", 13918 format(" /*\t \t \n" 13919 " \t \t a\t\tcomment\t \t\n" 13920 " \t \t in multiple lines\t\n" 13921 " \t */", 13922 Tab)); 13923 EXPECT_EQ("/* some\n" 13924 " comment */", 13925 format(" \t \t /* some\n" 13926 " \t \t comment */", 13927 Tab)); 13928 EXPECT_EQ("int a; /* some\n" 13929 " comment */", 13930 format(" \t \t int a; /* some\n" 13931 " \t \t comment */", 13932 Tab)); 13933 13934 EXPECT_EQ("int a; /* some\n" 13935 "comment */", 13936 format(" \t \t int\ta; /* some\n" 13937 " \t \t comment */", 13938 Tab)); 13939 EXPECT_EQ("f(\"\t\t\"); /* some\n" 13940 " comment */", 13941 format(" \t \t f(\"\t\t\"); /* some\n" 13942 " \t \t comment */", 13943 Tab)); 13944 EXPECT_EQ("{\n" 13945 " /*\n" 13946 " * Comment\n" 13947 " */\n" 13948 " int i;\n" 13949 "}", 13950 format("{\n" 13951 "\t/*\n" 13952 "\t * Comment\n" 13953 "\t */\n" 13954 "\t int i;\n" 13955 "}", 13956 Tab)); 13957 13958 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation; 13959 Tab.TabWidth = 8; 13960 Tab.IndentWidth = 8; 13961 EXPECT_EQ("if (aaaaaaaa && // q\n" 13962 " bb) // w\n" 13963 "\t;", 13964 format("if (aaaaaaaa &&// q\n" 13965 "bb)// w\n" 13966 ";", 13967 Tab)); 13968 EXPECT_EQ("if (aaa && bbb) // w\n" 13969 "\t;", 13970 format("if(aaa&&bbb)// w\n" 13971 ";", 13972 Tab)); 13973 verifyFormat("class X {\n" 13974 "\tvoid f() {\n" 13975 "\t\tsomeFunction(parameter1,\n" 13976 "\t\t\t parameter2);\n" 13977 "\t}\n" 13978 "};", 13979 Tab); 13980 verifyFormat("#define A \\\n" 13981 "\tvoid f() { \\\n" 13982 "\t\tsomeFunction( \\\n" 13983 "\t\t parameter1, \\\n" 13984 "\t\t parameter2); \\\n" 13985 "\t}", 13986 Tab); 13987 Tab.TabWidth = 4; 13988 Tab.IndentWidth = 8; 13989 verifyFormat("class TabWidth4Indent8 {\n" 13990 "\t\tvoid f() {\n" 13991 "\t\t\t\tsomeFunction(parameter1,\n" 13992 "\t\t\t\t\t\t\t parameter2);\n" 13993 "\t\t}\n" 13994 "};", 13995 Tab); 13996 Tab.TabWidth = 4; 13997 Tab.IndentWidth = 4; 13998 verifyFormat("class TabWidth4Indent4 {\n" 13999 "\tvoid f() {\n" 14000 "\t\tsomeFunction(parameter1,\n" 14001 "\t\t\t\t\t parameter2);\n" 14002 "\t}\n" 14003 "};", 14004 Tab); 14005 Tab.TabWidth = 8; 14006 Tab.IndentWidth = 4; 14007 verifyFormat("class TabWidth8Indent4 {\n" 14008 " void f() {\n" 14009 "\tsomeFunction(parameter1,\n" 14010 "\t\t parameter2);\n" 14011 " }\n" 14012 "};", 14013 Tab); 14014 Tab.TabWidth = 8; 14015 Tab.IndentWidth = 8; 14016 EXPECT_EQ("/*\n" 14017 "\t a\t\tcomment\n" 14018 "\t in multiple lines\n" 14019 " */", 14020 format(" /*\t \t \n" 14021 " \t \t a\t\tcomment\t \t\n" 14022 " \t \t in multiple lines\t\n" 14023 " \t */", 14024 Tab)); 14025 verifyFormat("{\n" 14026 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14027 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14028 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14029 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14030 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14031 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14032 "};", 14033 Tab); 14034 verifyFormat("enum AA {\n" 14035 "\ta1, // Force multiple lines\n" 14036 "\ta2,\n" 14037 "\ta3\n" 14038 "};", 14039 Tab); 14040 EXPECT_EQ("if (aaaaaaaa && // q\n" 14041 " bb) // w\n" 14042 "\t;", 14043 format("if (aaaaaaaa &&// q\n" 14044 "bb)// w\n" 14045 ";", 14046 Tab)); 14047 verifyFormat("class X {\n" 14048 "\tvoid f() {\n" 14049 "\t\tsomeFunction(parameter1,\n" 14050 "\t\t\t parameter2);\n" 14051 "\t}\n" 14052 "};", 14053 Tab); 14054 verifyFormat("{\n" 14055 "\tQ(\n" 14056 "\t {\n" 14057 "\t\t int a;\n" 14058 "\t\t someFunction(aaaaaaaa,\n" 14059 "\t\t\t\t bbbbbbb);\n" 14060 "\t },\n" 14061 "\t p);\n" 14062 "}", 14063 Tab); 14064 EXPECT_EQ("{\n" 14065 "\t/* aaaa\n" 14066 "\t bbbb */\n" 14067 "}", 14068 format("{\n" 14069 "/* aaaa\n" 14070 " bbbb */\n" 14071 "}", 14072 Tab)); 14073 EXPECT_EQ("{\n" 14074 "\t/*\n" 14075 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14076 "\t bbbbbbbbbbbbb\n" 14077 "\t*/\n" 14078 "}", 14079 format("{\n" 14080 "/*\n" 14081 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14082 "*/\n" 14083 "}", 14084 Tab)); 14085 EXPECT_EQ("{\n" 14086 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14087 "\t// bbbbbbbbbbbbb\n" 14088 "}", 14089 format("{\n" 14090 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14091 "}", 14092 Tab)); 14093 EXPECT_EQ("{\n" 14094 "\t/*\n" 14095 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14096 "\t bbbbbbbbbbbbb\n" 14097 "\t*/\n" 14098 "}", 14099 format("{\n" 14100 "\t/*\n" 14101 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14102 "\t*/\n" 14103 "}", 14104 Tab)); 14105 EXPECT_EQ("{\n" 14106 "\t/*\n" 14107 "\n" 14108 "\t*/\n" 14109 "}", 14110 format("{\n" 14111 "\t/*\n" 14112 "\n" 14113 "\t*/\n" 14114 "}", 14115 Tab)); 14116 EXPECT_EQ("{\n" 14117 "\t/*\n" 14118 " asdf\n" 14119 "\t*/\n" 14120 "}", 14121 format("{\n" 14122 "\t/*\n" 14123 " asdf\n" 14124 "\t*/\n" 14125 "}", 14126 Tab)); 14127 EXPECT_EQ("/* some\n" 14128 " comment */", 14129 format(" \t \t /* some\n" 14130 " \t \t comment */", 14131 Tab)); 14132 EXPECT_EQ("int a; /* some\n" 14133 " comment */", 14134 format(" \t \t int a; /* some\n" 14135 " \t \t comment */", 14136 Tab)); 14137 EXPECT_EQ("int a; /* some\n" 14138 "comment */", 14139 format(" \t \t int\ta; /* some\n" 14140 " \t \t comment */", 14141 Tab)); 14142 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14143 " comment */", 14144 format(" \t \t f(\"\t\t\"); /* some\n" 14145 " \t \t comment */", 14146 Tab)); 14147 EXPECT_EQ("{\n" 14148 "\t/*\n" 14149 "\t * Comment\n" 14150 "\t */\n" 14151 "\tint i;\n" 14152 "}", 14153 format("{\n" 14154 "\t/*\n" 14155 "\t * Comment\n" 14156 "\t */\n" 14157 "\t int i;\n" 14158 "}", 14159 Tab)); 14160 Tab.TabWidth = 2; 14161 Tab.IndentWidth = 2; 14162 EXPECT_EQ("{\n" 14163 "\t/* aaaa\n" 14164 "\t\t bbbb */\n" 14165 "}", 14166 format("{\n" 14167 "/* aaaa\n" 14168 "\t bbbb */\n" 14169 "}", 14170 Tab)); 14171 EXPECT_EQ("{\n" 14172 "\t/*\n" 14173 "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14174 "\t\tbbbbbbbbbbbbb\n" 14175 "\t*/\n" 14176 "}", 14177 format("{\n" 14178 "/*\n" 14179 "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14180 "*/\n" 14181 "}", 14182 Tab)); 14183 Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 14184 Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 14185 Tab.TabWidth = 4; 14186 Tab.IndentWidth = 4; 14187 verifyFormat("class Assign {\n" 14188 "\tvoid f() {\n" 14189 "\t\tint x = 123;\n" 14190 "\t\tint random = 4;\n" 14191 "\t\tstd::string alphabet =\n" 14192 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n" 14193 "\t}\n" 14194 "};", 14195 Tab); 14196 14197 Tab.UseTab = FormatStyle::UT_AlignWithSpaces; 14198 Tab.TabWidth = 8; 14199 Tab.IndentWidth = 8; 14200 EXPECT_EQ("if (aaaaaaaa && // q\n" 14201 " bb) // w\n" 14202 "\t;", 14203 format("if (aaaaaaaa &&// q\n" 14204 "bb)// w\n" 14205 ";", 14206 Tab)); 14207 EXPECT_EQ("if (aaa && bbb) // w\n" 14208 "\t;", 14209 format("if(aaa&&bbb)// w\n" 14210 ";", 14211 Tab)); 14212 verifyFormat("class X {\n" 14213 "\tvoid f() {\n" 14214 "\t\tsomeFunction(parameter1,\n" 14215 "\t\t parameter2);\n" 14216 "\t}\n" 14217 "};", 14218 Tab); 14219 verifyFormat("#define A \\\n" 14220 "\tvoid f() { \\\n" 14221 "\t\tsomeFunction( \\\n" 14222 "\t\t parameter1, \\\n" 14223 "\t\t parameter2); \\\n" 14224 "\t}", 14225 Tab); 14226 Tab.TabWidth = 4; 14227 Tab.IndentWidth = 8; 14228 verifyFormat("class TabWidth4Indent8 {\n" 14229 "\t\tvoid f() {\n" 14230 "\t\t\t\tsomeFunction(parameter1,\n" 14231 "\t\t\t\t parameter2);\n" 14232 "\t\t}\n" 14233 "};", 14234 Tab); 14235 Tab.TabWidth = 4; 14236 Tab.IndentWidth = 4; 14237 verifyFormat("class TabWidth4Indent4 {\n" 14238 "\tvoid f() {\n" 14239 "\t\tsomeFunction(parameter1,\n" 14240 "\t\t parameter2);\n" 14241 "\t}\n" 14242 "};", 14243 Tab); 14244 Tab.TabWidth = 8; 14245 Tab.IndentWidth = 4; 14246 verifyFormat("class TabWidth8Indent4 {\n" 14247 " void f() {\n" 14248 "\tsomeFunction(parameter1,\n" 14249 "\t parameter2);\n" 14250 " }\n" 14251 "};", 14252 Tab); 14253 Tab.TabWidth = 8; 14254 Tab.IndentWidth = 8; 14255 EXPECT_EQ("/*\n" 14256 " a\t\tcomment\n" 14257 " in multiple lines\n" 14258 " */", 14259 format(" /*\t \t \n" 14260 " \t \t a\t\tcomment\t \t\n" 14261 " \t \t in multiple lines\t\n" 14262 " \t */", 14263 Tab)); 14264 verifyFormat("{\n" 14265 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14266 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14267 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14268 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14269 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14270 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14271 "};", 14272 Tab); 14273 verifyFormat("enum AA {\n" 14274 "\ta1, // Force multiple lines\n" 14275 "\ta2,\n" 14276 "\ta3\n" 14277 "};", 14278 Tab); 14279 EXPECT_EQ("if (aaaaaaaa && // q\n" 14280 " bb) // w\n" 14281 "\t;", 14282 format("if (aaaaaaaa &&// q\n" 14283 "bb)// w\n" 14284 ";", 14285 Tab)); 14286 verifyFormat("class X {\n" 14287 "\tvoid f() {\n" 14288 "\t\tsomeFunction(parameter1,\n" 14289 "\t\t parameter2);\n" 14290 "\t}\n" 14291 "};", 14292 Tab); 14293 verifyFormat("{\n" 14294 "\tQ(\n" 14295 "\t {\n" 14296 "\t\t int a;\n" 14297 "\t\t someFunction(aaaaaaaa,\n" 14298 "\t\t bbbbbbb);\n" 14299 "\t },\n" 14300 "\t p);\n" 14301 "}", 14302 Tab); 14303 EXPECT_EQ("{\n" 14304 "\t/* aaaa\n" 14305 "\t bbbb */\n" 14306 "}", 14307 format("{\n" 14308 "/* aaaa\n" 14309 " bbbb */\n" 14310 "}", 14311 Tab)); 14312 EXPECT_EQ("{\n" 14313 "\t/*\n" 14314 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14315 "\t bbbbbbbbbbbbb\n" 14316 "\t*/\n" 14317 "}", 14318 format("{\n" 14319 "/*\n" 14320 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14321 "*/\n" 14322 "}", 14323 Tab)); 14324 EXPECT_EQ("{\n" 14325 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14326 "\t// bbbbbbbbbbbbb\n" 14327 "}", 14328 format("{\n" 14329 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14330 "}", 14331 Tab)); 14332 EXPECT_EQ("{\n" 14333 "\t/*\n" 14334 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14335 "\t bbbbbbbbbbbbb\n" 14336 "\t*/\n" 14337 "}", 14338 format("{\n" 14339 "\t/*\n" 14340 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14341 "\t*/\n" 14342 "}", 14343 Tab)); 14344 EXPECT_EQ("{\n" 14345 "\t/*\n" 14346 "\n" 14347 "\t*/\n" 14348 "}", 14349 format("{\n" 14350 "\t/*\n" 14351 "\n" 14352 "\t*/\n" 14353 "}", 14354 Tab)); 14355 EXPECT_EQ("{\n" 14356 "\t/*\n" 14357 " asdf\n" 14358 "\t*/\n" 14359 "}", 14360 format("{\n" 14361 "\t/*\n" 14362 " asdf\n" 14363 "\t*/\n" 14364 "}", 14365 Tab)); 14366 EXPECT_EQ("/* some\n" 14367 " comment */", 14368 format(" \t \t /* some\n" 14369 " \t \t comment */", 14370 Tab)); 14371 EXPECT_EQ("int a; /* some\n" 14372 " comment */", 14373 format(" \t \t int a; /* some\n" 14374 " \t \t comment */", 14375 Tab)); 14376 EXPECT_EQ("int a; /* some\n" 14377 "comment */", 14378 format(" \t \t int\ta; /* some\n" 14379 " \t \t comment */", 14380 Tab)); 14381 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14382 " comment */", 14383 format(" \t \t f(\"\t\t\"); /* some\n" 14384 " \t \t comment */", 14385 Tab)); 14386 EXPECT_EQ("{\n" 14387 "\t/*\n" 14388 "\t * Comment\n" 14389 "\t */\n" 14390 "\tint i;\n" 14391 "}", 14392 format("{\n" 14393 "\t/*\n" 14394 "\t * Comment\n" 14395 "\t */\n" 14396 "\t int i;\n" 14397 "}", 14398 Tab)); 14399 Tab.TabWidth = 2; 14400 Tab.IndentWidth = 2; 14401 EXPECT_EQ("{\n" 14402 "\t/* aaaa\n" 14403 "\t bbbb */\n" 14404 "}", 14405 format("{\n" 14406 "/* aaaa\n" 14407 " bbbb */\n" 14408 "}", 14409 Tab)); 14410 EXPECT_EQ("{\n" 14411 "\t/*\n" 14412 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14413 "\t bbbbbbbbbbbbb\n" 14414 "\t*/\n" 14415 "}", 14416 format("{\n" 14417 "/*\n" 14418 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14419 "*/\n" 14420 "}", 14421 Tab)); 14422 Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 14423 Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 14424 Tab.TabWidth = 4; 14425 Tab.IndentWidth = 4; 14426 verifyFormat("class Assign {\n" 14427 "\tvoid f() {\n" 14428 "\t\tint x = 123;\n" 14429 "\t\tint random = 4;\n" 14430 "\t\tstd::string alphabet =\n" 14431 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n" 14432 "\t}\n" 14433 "};", 14434 Tab); 14435 Tab.AlignOperands = FormatStyle::OAS_Align; 14436 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n" 14437 " cccccccccccccccccccc;", 14438 Tab); 14439 // no alignment 14440 verifyFormat("int aaaaaaaaaa =\n" 14441 "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 14442 Tab); 14443 verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n" 14444 " : bbbbbbbbbbbbbb ? 222222222222222\n" 14445 " : 333333333333333;", 14446 Tab); 14447 Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 14448 Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator; 14449 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n" 14450 " + cccccccccccccccccccc;", 14451 Tab); 14452 } 14453 14454 TEST_F(FormatTest, ZeroTabWidth) { 14455 FormatStyle Tab = getLLVMStyleWithColumns(42); 14456 Tab.IndentWidth = 8; 14457 Tab.UseTab = FormatStyle::UT_Never; 14458 Tab.TabWidth = 0; 14459 EXPECT_EQ("void a(){\n" 14460 " // line starts with '\t'\n" 14461 "};", 14462 format("void a(){\n" 14463 "\t// line starts with '\t'\n" 14464 "};", 14465 Tab)); 14466 14467 EXPECT_EQ("void a(){\n" 14468 " // line starts with '\t'\n" 14469 "};", 14470 format("void a(){\n" 14471 "\t\t// line starts with '\t'\n" 14472 "};", 14473 Tab)); 14474 14475 Tab.UseTab = FormatStyle::UT_ForIndentation; 14476 EXPECT_EQ("void a(){\n" 14477 " // line starts with '\t'\n" 14478 "};", 14479 format("void a(){\n" 14480 "\t// line starts with '\t'\n" 14481 "};", 14482 Tab)); 14483 14484 EXPECT_EQ("void a(){\n" 14485 " // line starts with '\t'\n" 14486 "};", 14487 format("void a(){\n" 14488 "\t\t// line starts with '\t'\n" 14489 "};", 14490 Tab)); 14491 14492 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation; 14493 EXPECT_EQ("void a(){\n" 14494 " // line starts with '\t'\n" 14495 "};", 14496 format("void a(){\n" 14497 "\t// line starts with '\t'\n" 14498 "};", 14499 Tab)); 14500 14501 EXPECT_EQ("void a(){\n" 14502 " // line starts with '\t'\n" 14503 "};", 14504 format("void a(){\n" 14505 "\t\t// line starts with '\t'\n" 14506 "};", 14507 Tab)); 14508 14509 Tab.UseTab = FormatStyle::UT_AlignWithSpaces; 14510 EXPECT_EQ("void a(){\n" 14511 " // line starts with '\t'\n" 14512 "};", 14513 format("void a(){\n" 14514 "\t// line starts with '\t'\n" 14515 "};", 14516 Tab)); 14517 14518 EXPECT_EQ("void a(){\n" 14519 " // line starts with '\t'\n" 14520 "};", 14521 format("void a(){\n" 14522 "\t\t// line starts with '\t'\n" 14523 "};", 14524 Tab)); 14525 14526 Tab.UseTab = FormatStyle::UT_Always; 14527 EXPECT_EQ("void a(){\n" 14528 "// line starts with '\t'\n" 14529 "};", 14530 format("void a(){\n" 14531 "\t// line starts with '\t'\n" 14532 "};", 14533 Tab)); 14534 14535 EXPECT_EQ("void a(){\n" 14536 "// line starts with '\t'\n" 14537 "};", 14538 format("void a(){\n" 14539 "\t\t// line starts with '\t'\n" 14540 "};", 14541 Tab)); 14542 } 14543 14544 TEST_F(FormatTest, CalculatesOriginalColumn) { 14545 EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14546 "q\"; /* some\n" 14547 " comment */", 14548 format(" \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14549 "q\"; /* some\n" 14550 " comment */", 14551 getLLVMStyle())); 14552 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n" 14553 "/* some\n" 14554 " comment */", 14555 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n" 14556 " /* some\n" 14557 " comment */", 14558 getLLVMStyle())); 14559 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14560 "qqq\n" 14561 "/* some\n" 14562 " comment */", 14563 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14564 "qqq\n" 14565 " /* some\n" 14566 " comment */", 14567 getLLVMStyle())); 14568 EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14569 "wwww; /* some\n" 14570 " comment */", 14571 format(" inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14572 "wwww; /* some\n" 14573 " comment */", 14574 getLLVMStyle())); 14575 } 14576 14577 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) { 14578 FormatStyle NoSpace = getLLVMStyle(); 14579 NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never; 14580 14581 verifyFormat("while(true)\n" 14582 " continue;", 14583 NoSpace); 14584 verifyFormat("for(;;)\n" 14585 " continue;", 14586 NoSpace); 14587 verifyFormat("if(true)\n" 14588 " f();\n" 14589 "else if(true)\n" 14590 " f();", 14591 NoSpace); 14592 verifyFormat("do {\n" 14593 " do_something();\n" 14594 "} while(something());", 14595 NoSpace); 14596 verifyFormat("switch(x) {\n" 14597 "default:\n" 14598 " break;\n" 14599 "}", 14600 NoSpace); 14601 verifyFormat("auto i = std::make_unique<int>(5);", NoSpace); 14602 verifyFormat("size_t x = sizeof(x);", NoSpace); 14603 verifyFormat("auto f(int x) -> decltype(x);", NoSpace); 14604 verifyFormat("auto f(int x) -> typeof(x);", NoSpace); 14605 verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace); 14606 verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace); 14607 verifyFormat("int f(T x) noexcept(x.create());", NoSpace); 14608 verifyFormat("alignas(128) char a[128];", NoSpace); 14609 verifyFormat("size_t x = alignof(MyType);", NoSpace); 14610 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace); 14611 verifyFormat("int f() throw(Deprecated);", NoSpace); 14612 verifyFormat("typedef void (*cb)(int);", NoSpace); 14613 verifyFormat("T A::operator()();", NoSpace); 14614 verifyFormat("X A::operator++(T);", NoSpace); 14615 verifyFormat("auto lambda = []() { return 0; };", NoSpace); 14616 14617 FormatStyle Space = getLLVMStyle(); 14618 Space.SpaceBeforeParens = FormatStyle::SBPO_Always; 14619 14620 verifyFormat("int f ();", Space); 14621 verifyFormat("void f (int a, T b) {\n" 14622 " while (true)\n" 14623 " continue;\n" 14624 "}", 14625 Space); 14626 verifyFormat("if (true)\n" 14627 " f ();\n" 14628 "else if (true)\n" 14629 " f ();", 14630 Space); 14631 verifyFormat("do {\n" 14632 " do_something ();\n" 14633 "} while (something ());", 14634 Space); 14635 verifyFormat("switch (x) {\n" 14636 "default:\n" 14637 " break;\n" 14638 "}", 14639 Space); 14640 verifyFormat("A::A () : a (1) {}", Space); 14641 verifyFormat("void f () __attribute__ ((asdf));", Space); 14642 verifyFormat("*(&a + 1);\n" 14643 "&((&a)[1]);\n" 14644 "a[(b + c) * d];\n" 14645 "(((a + 1) * 2) + 3) * 4;", 14646 Space); 14647 verifyFormat("#define A(x) x", Space); 14648 verifyFormat("#define A (x) x", Space); 14649 verifyFormat("#if defined(x)\n" 14650 "#endif", 14651 Space); 14652 verifyFormat("auto i = std::make_unique<int> (5);", Space); 14653 verifyFormat("size_t x = sizeof (x);", Space); 14654 verifyFormat("auto f (int x) -> decltype (x);", Space); 14655 verifyFormat("auto f (int x) -> typeof (x);", Space); 14656 verifyFormat("auto f (int x) -> _Atomic (x);", Space); 14657 verifyFormat("auto f (int x) -> __underlying_type (x);", Space); 14658 verifyFormat("int f (T x) noexcept (x.create ());", Space); 14659 verifyFormat("alignas (128) char a[128];", Space); 14660 verifyFormat("size_t x = alignof (MyType);", Space); 14661 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space); 14662 verifyFormat("int f () throw (Deprecated);", Space); 14663 verifyFormat("typedef void (*cb) (int);", Space); 14664 // FIXME these tests regressed behaviour. 14665 // verifyFormat("T A::operator() ();", Space); 14666 // verifyFormat("X A::operator++ (T);", Space); 14667 verifyFormat("auto lambda = [] () { return 0; };", Space); 14668 verifyFormat("int x = int (y);", Space); 14669 14670 FormatStyle SomeSpace = getLLVMStyle(); 14671 SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses; 14672 14673 verifyFormat("[]() -> float {}", SomeSpace); 14674 verifyFormat("[] (auto foo) {}", SomeSpace); 14675 verifyFormat("[foo]() -> int {}", SomeSpace); 14676 verifyFormat("int f();", SomeSpace); 14677 verifyFormat("void f (int a, T b) {\n" 14678 " while (true)\n" 14679 " continue;\n" 14680 "}", 14681 SomeSpace); 14682 verifyFormat("if (true)\n" 14683 " f();\n" 14684 "else if (true)\n" 14685 " f();", 14686 SomeSpace); 14687 verifyFormat("do {\n" 14688 " do_something();\n" 14689 "} while (something());", 14690 SomeSpace); 14691 verifyFormat("switch (x) {\n" 14692 "default:\n" 14693 " break;\n" 14694 "}", 14695 SomeSpace); 14696 verifyFormat("A::A() : a (1) {}", SomeSpace); 14697 verifyFormat("void f() __attribute__ ((asdf));", SomeSpace); 14698 verifyFormat("*(&a + 1);\n" 14699 "&((&a)[1]);\n" 14700 "a[(b + c) * d];\n" 14701 "(((a + 1) * 2) + 3) * 4;", 14702 SomeSpace); 14703 verifyFormat("#define A(x) x", SomeSpace); 14704 verifyFormat("#define A (x) x", SomeSpace); 14705 verifyFormat("#if defined(x)\n" 14706 "#endif", 14707 SomeSpace); 14708 verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace); 14709 verifyFormat("size_t x = sizeof (x);", SomeSpace); 14710 verifyFormat("auto f (int x) -> decltype (x);", SomeSpace); 14711 verifyFormat("auto f (int x) -> typeof (x);", SomeSpace); 14712 verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace); 14713 verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace); 14714 verifyFormat("int f (T x) noexcept (x.create());", SomeSpace); 14715 verifyFormat("alignas (128) char a[128];", SomeSpace); 14716 verifyFormat("size_t x = alignof (MyType);", SomeSpace); 14717 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", 14718 SomeSpace); 14719 verifyFormat("int f() throw (Deprecated);", SomeSpace); 14720 verifyFormat("typedef void (*cb) (int);", SomeSpace); 14721 verifyFormat("T A::operator()();", SomeSpace); 14722 // FIXME these tests regressed behaviour. 14723 // verifyFormat("X A::operator++ (T);", SomeSpace); 14724 verifyFormat("int x = int (y);", SomeSpace); 14725 verifyFormat("auto lambda = []() { return 0; };", SomeSpace); 14726 14727 FormatStyle SpaceControlStatements = getLLVMStyle(); 14728 SpaceControlStatements.SpaceBeforeParens = FormatStyle::SBPO_Custom; 14729 SpaceControlStatements.SpaceBeforeParensOptions.AfterControlStatements = true; 14730 14731 verifyFormat("while (true)\n" 14732 " continue;", 14733 SpaceControlStatements); 14734 verifyFormat("if (true)\n" 14735 " f();\n" 14736 "else if (true)\n" 14737 " f();", 14738 SpaceControlStatements); 14739 verifyFormat("for (;;) {\n" 14740 " do_something();\n" 14741 "}", 14742 SpaceControlStatements); 14743 verifyFormat("do {\n" 14744 " do_something();\n" 14745 "} while (something());", 14746 SpaceControlStatements); 14747 verifyFormat("switch (x) {\n" 14748 "default:\n" 14749 " break;\n" 14750 "}", 14751 SpaceControlStatements); 14752 14753 FormatStyle SpaceFuncDecl = getLLVMStyle(); 14754 SpaceFuncDecl.SpaceBeforeParens = FormatStyle::SBPO_Custom; 14755 SpaceFuncDecl.SpaceBeforeParensOptions.AfterFunctionDeclarationName = true; 14756 14757 verifyFormat("int f ();", SpaceFuncDecl); 14758 verifyFormat("void f(int a, T b) {}", SpaceFuncDecl); 14759 verifyFormat("A::A() : a(1) {}", SpaceFuncDecl); 14760 verifyFormat("void f () __attribute__((asdf));", SpaceFuncDecl); 14761 verifyFormat("#define A(x) x", SpaceFuncDecl); 14762 verifyFormat("#define A (x) x", SpaceFuncDecl); 14763 verifyFormat("#if defined(x)\n" 14764 "#endif", 14765 SpaceFuncDecl); 14766 verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDecl); 14767 verifyFormat("size_t x = sizeof(x);", SpaceFuncDecl); 14768 verifyFormat("auto f (int x) -> decltype(x);", SpaceFuncDecl); 14769 verifyFormat("auto f (int x) -> typeof(x);", SpaceFuncDecl); 14770 verifyFormat("auto f (int x) -> _Atomic(x);", SpaceFuncDecl); 14771 verifyFormat("auto f (int x) -> __underlying_type(x);", SpaceFuncDecl); 14772 verifyFormat("int f (T x) noexcept(x.create());", SpaceFuncDecl); 14773 verifyFormat("alignas(128) char a[128];", SpaceFuncDecl); 14774 verifyFormat("size_t x = alignof(MyType);", SpaceFuncDecl); 14775 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", 14776 SpaceFuncDecl); 14777 verifyFormat("int f () throw(Deprecated);", SpaceFuncDecl); 14778 verifyFormat("typedef void (*cb)(int);", SpaceFuncDecl); 14779 // FIXME these tests regressed behaviour. 14780 // verifyFormat("T A::operator() ();", SpaceFuncDecl); 14781 // verifyFormat("X A::operator++ (T);", SpaceFuncDecl); 14782 verifyFormat("T A::operator()() {}", SpaceFuncDecl); 14783 verifyFormat("auto lambda = []() { return 0; };", SpaceFuncDecl); 14784 verifyFormat("int x = int(y);", SpaceFuncDecl); 14785 verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}", 14786 SpaceFuncDecl); 14787 14788 FormatStyle SpaceFuncDef = getLLVMStyle(); 14789 SpaceFuncDef.SpaceBeforeParens = FormatStyle::SBPO_Custom; 14790 SpaceFuncDef.SpaceBeforeParensOptions.AfterFunctionDefinitionName = true; 14791 14792 verifyFormat("int f();", SpaceFuncDef); 14793 verifyFormat("void f (int a, T b) {}", SpaceFuncDef); 14794 verifyFormat("A::A() : a(1) {}", SpaceFuncDef); 14795 verifyFormat("void f() __attribute__((asdf));", SpaceFuncDef); 14796 verifyFormat("#define A(x) x", SpaceFuncDef); 14797 verifyFormat("#define A (x) x", SpaceFuncDef); 14798 verifyFormat("#if defined(x)\n" 14799 "#endif", 14800 SpaceFuncDef); 14801 verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDef); 14802 verifyFormat("size_t x = sizeof(x);", SpaceFuncDef); 14803 verifyFormat("auto f(int x) -> decltype(x);", SpaceFuncDef); 14804 verifyFormat("auto f(int x) -> typeof(x);", SpaceFuncDef); 14805 verifyFormat("auto f(int x) -> _Atomic(x);", SpaceFuncDef); 14806 verifyFormat("auto f(int x) -> __underlying_type(x);", SpaceFuncDef); 14807 verifyFormat("int f(T x) noexcept(x.create());", SpaceFuncDef); 14808 verifyFormat("alignas(128) char a[128];", SpaceFuncDef); 14809 verifyFormat("size_t x = alignof(MyType);", SpaceFuncDef); 14810 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", 14811 SpaceFuncDef); 14812 verifyFormat("int f() throw(Deprecated);", SpaceFuncDef); 14813 verifyFormat("typedef void (*cb)(int);", SpaceFuncDef); 14814 verifyFormat("T A::operator()();", SpaceFuncDef); 14815 verifyFormat("X A::operator++(T);", SpaceFuncDef); 14816 // verifyFormat("T A::operator() () {}", SpaceFuncDef); 14817 verifyFormat("auto lambda = [] () { return 0; };", SpaceFuncDef); 14818 verifyFormat("int x = int(y);", SpaceFuncDef); 14819 verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}", 14820 SpaceFuncDef); 14821 14822 FormatStyle SpaceIfMacros = getLLVMStyle(); 14823 SpaceIfMacros.IfMacros.clear(); 14824 SpaceIfMacros.IfMacros.push_back("MYIF"); 14825 SpaceIfMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom; 14826 SpaceIfMacros.SpaceBeforeParensOptions.AfterIfMacros = true; 14827 verifyFormat("MYIF (a)\n return;", SpaceIfMacros); 14828 verifyFormat("MYIF (a)\n return;\nelse MYIF (b)\n return;", SpaceIfMacros); 14829 verifyFormat("MYIF (a)\n return;\nelse\n return;", SpaceIfMacros); 14830 14831 FormatStyle SpaceForeachMacros = getLLVMStyle(); 14832 EXPECT_EQ(SpaceForeachMacros.AllowShortBlocksOnASingleLine, 14833 FormatStyle::SBS_Never); 14834 EXPECT_EQ(SpaceForeachMacros.AllowShortLoopsOnASingleLine, false); 14835 SpaceForeachMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom; 14836 SpaceForeachMacros.SpaceBeforeParensOptions.AfterForeachMacros = true; 14837 verifyFormat("for (;;) {\n" 14838 "}", 14839 SpaceForeachMacros); 14840 verifyFormat("foreach (Item *item, itemlist) {\n" 14841 "}", 14842 SpaceForeachMacros); 14843 verifyFormat("Q_FOREACH (Item *item, itemlist) {\n" 14844 "}", 14845 SpaceForeachMacros); 14846 verifyFormat("BOOST_FOREACH (Item *item, itemlist) {\n" 14847 "}", 14848 SpaceForeachMacros); 14849 verifyFormat("UNKNOWN_FOREACH(Item *item, itemlist) {}", SpaceForeachMacros); 14850 14851 FormatStyle SomeSpace2 = getLLVMStyle(); 14852 SomeSpace2.SpaceBeforeParens = FormatStyle::SBPO_Custom; 14853 SomeSpace2.SpaceBeforeParensOptions.BeforeNonEmptyParentheses = true; 14854 verifyFormat("[]() -> float {}", SomeSpace2); 14855 verifyFormat("[] (auto foo) {}", SomeSpace2); 14856 verifyFormat("[foo]() -> int {}", SomeSpace2); 14857 verifyFormat("int f();", SomeSpace2); 14858 verifyFormat("void f (int a, T b) {\n" 14859 " while (true)\n" 14860 " continue;\n" 14861 "}", 14862 SomeSpace2); 14863 verifyFormat("if (true)\n" 14864 " f();\n" 14865 "else if (true)\n" 14866 " f();", 14867 SomeSpace2); 14868 verifyFormat("do {\n" 14869 " do_something();\n" 14870 "} while (something());", 14871 SomeSpace2); 14872 verifyFormat("switch (x) {\n" 14873 "default:\n" 14874 " break;\n" 14875 "}", 14876 SomeSpace2); 14877 verifyFormat("A::A() : a (1) {}", SomeSpace2); 14878 verifyFormat("void f() __attribute__ ((asdf));", SomeSpace2); 14879 verifyFormat("*(&a + 1);\n" 14880 "&((&a)[1]);\n" 14881 "a[(b + c) * d];\n" 14882 "(((a + 1) * 2) + 3) * 4;", 14883 SomeSpace2); 14884 verifyFormat("#define A(x) x", SomeSpace2); 14885 verifyFormat("#define A (x) x", SomeSpace2); 14886 verifyFormat("#if defined(x)\n" 14887 "#endif", 14888 SomeSpace2); 14889 verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace2); 14890 verifyFormat("size_t x = sizeof (x);", SomeSpace2); 14891 verifyFormat("auto f (int x) -> decltype (x);", SomeSpace2); 14892 verifyFormat("auto f (int x) -> typeof (x);", SomeSpace2); 14893 verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace2); 14894 verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace2); 14895 verifyFormat("int f (T x) noexcept (x.create());", SomeSpace2); 14896 verifyFormat("alignas (128) char a[128];", SomeSpace2); 14897 verifyFormat("size_t x = alignof (MyType);", SomeSpace2); 14898 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", 14899 SomeSpace2); 14900 verifyFormat("int f() throw (Deprecated);", SomeSpace2); 14901 verifyFormat("typedef void (*cb) (int);", SomeSpace2); 14902 verifyFormat("T A::operator()();", SomeSpace2); 14903 // verifyFormat("X A::operator++ (T);", SomeSpace2); 14904 verifyFormat("int x = int (y);", SomeSpace2); 14905 verifyFormat("auto lambda = []() { return 0; };", SomeSpace2); 14906 14907 FormatStyle SpaceAfterOverloadedOperator = getLLVMStyle(); 14908 SpaceAfterOverloadedOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom; 14909 SpaceAfterOverloadedOperator.SpaceBeforeParensOptions 14910 .AfterOverloadedOperator = true; 14911 14912 verifyFormat("auto operator++ () -> int;", SpaceAfterOverloadedOperator); 14913 verifyFormat("X A::operator++ ();", SpaceAfterOverloadedOperator); 14914 verifyFormat("some_object.operator++ ();", SpaceAfterOverloadedOperator); 14915 verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator); 14916 14917 SpaceAfterOverloadedOperator.SpaceBeforeParensOptions 14918 .AfterOverloadedOperator = false; 14919 14920 verifyFormat("auto operator++() -> int;", SpaceAfterOverloadedOperator); 14921 verifyFormat("X A::operator++();", SpaceAfterOverloadedOperator); 14922 verifyFormat("some_object.operator++();", SpaceAfterOverloadedOperator); 14923 verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator); 14924 } 14925 14926 TEST_F(FormatTest, SpaceAfterLogicalNot) { 14927 FormatStyle Spaces = getLLVMStyle(); 14928 Spaces.SpaceAfterLogicalNot = true; 14929 14930 verifyFormat("bool x = ! y", Spaces); 14931 verifyFormat("if (! isFailure())", Spaces); 14932 verifyFormat("if (! (a && b))", Spaces); 14933 verifyFormat("\"Error!\"", Spaces); 14934 verifyFormat("! ! x", Spaces); 14935 } 14936 14937 TEST_F(FormatTest, ConfigurableSpacesInParentheses) { 14938 FormatStyle Spaces = getLLVMStyle(); 14939 14940 Spaces.SpacesInParentheses = true; 14941 verifyFormat("do_something( ::globalVar );", Spaces); 14942 verifyFormat("call( x, y, z );", Spaces); 14943 verifyFormat("call();", Spaces); 14944 verifyFormat("std::function<void( int, int )> callback;", Spaces); 14945 verifyFormat("void inFunction() { std::function<void( int, int )> fct; }", 14946 Spaces); 14947 verifyFormat("while ( (bool)1 )\n" 14948 " continue;", 14949 Spaces); 14950 verifyFormat("for ( ;; )\n" 14951 " continue;", 14952 Spaces); 14953 verifyFormat("if ( true )\n" 14954 " f();\n" 14955 "else if ( true )\n" 14956 " f();", 14957 Spaces); 14958 verifyFormat("do {\n" 14959 " do_something( (int)i );\n" 14960 "} while ( something() );", 14961 Spaces); 14962 verifyFormat("switch ( x ) {\n" 14963 "default:\n" 14964 " break;\n" 14965 "}", 14966 Spaces); 14967 14968 Spaces.SpacesInParentheses = false; 14969 Spaces.SpacesInCStyleCastParentheses = true; 14970 verifyFormat("Type *A = ( Type * )P;", Spaces); 14971 verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces); 14972 verifyFormat("x = ( int32 )y;", Spaces); 14973 verifyFormat("int a = ( int )(2.0f);", Spaces); 14974 verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces); 14975 verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces); 14976 verifyFormat("#define x (( int )-1)", Spaces); 14977 14978 // Run the first set of tests again with: 14979 Spaces.SpacesInParentheses = false; 14980 Spaces.SpaceInEmptyParentheses = true; 14981 Spaces.SpacesInCStyleCastParentheses = true; 14982 verifyFormat("call(x, y, z);", Spaces); 14983 verifyFormat("call( );", Spaces); 14984 verifyFormat("std::function<void(int, int)> callback;", Spaces); 14985 verifyFormat("while (( bool )1)\n" 14986 " continue;", 14987 Spaces); 14988 verifyFormat("for (;;)\n" 14989 " continue;", 14990 Spaces); 14991 verifyFormat("if (true)\n" 14992 " f( );\n" 14993 "else if (true)\n" 14994 " f( );", 14995 Spaces); 14996 verifyFormat("do {\n" 14997 " do_something(( int )i);\n" 14998 "} while (something( ));", 14999 Spaces); 15000 verifyFormat("switch (x) {\n" 15001 "default:\n" 15002 " break;\n" 15003 "}", 15004 Spaces); 15005 15006 // Run the first set of tests again with: 15007 Spaces.SpaceAfterCStyleCast = true; 15008 verifyFormat("call(x, y, z);", Spaces); 15009 verifyFormat("call( );", Spaces); 15010 verifyFormat("std::function<void(int, int)> callback;", Spaces); 15011 verifyFormat("while (( bool ) 1)\n" 15012 " continue;", 15013 Spaces); 15014 verifyFormat("for (;;)\n" 15015 " continue;", 15016 Spaces); 15017 verifyFormat("if (true)\n" 15018 " f( );\n" 15019 "else if (true)\n" 15020 " f( );", 15021 Spaces); 15022 verifyFormat("do {\n" 15023 " do_something(( int ) i);\n" 15024 "} while (something( ));", 15025 Spaces); 15026 verifyFormat("switch (x) {\n" 15027 "default:\n" 15028 " break;\n" 15029 "}", 15030 Spaces); 15031 verifyFormat("#define CONF_BOOL(x) ( bool * ) ( void * ) (x)", Spaces); 15032 verifyFormat("#define CONF_BOOL(x) ( bool * ) (x)", Spaces); 15033 verifyFormat("#define CONF_BOOL(x) ( bool ) (x)", Spaces); 15034 verifyFormat("bool *y = ( bool * ) ( void * ) (x);", Spaces); 15035 verifyFormat("bool *y = ( bool * ) (x);", Spaces); 15036 15037 // Run subset of tests again with: 15038 Spaces.SpacesInCStyleCastParentheses = false; 15039 Spaces.SpaceAfterCStyleCast = true; 15040 verifyFormat("while ((bool) 1)\n" 15041 " continue;", 15042 Spaces); 15043 verifyFormat("do {\n" 15044 " do_something((int) i);\n" 15045 "} while (something( ));", 15046 Spaces); 15047 15048 verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces); 15049 verifyFormat("size_t idx = (size_t) a;", Spaces); 15050 verifyFormat("size_t idx = (size_t) (a - 1);", Spaces); 15051 verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces); 15052 verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces); 15053 verifyFormat("size_t idx = (*foo)(a - 1);", Spaces); 15054 verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces); 15055 verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (x)", Spaces); 15056 verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (int) (x)", Spaces); 15057 verifyFormat("bool *y = (bool *) (void *) (x);", Spaces); 15058 verifyFormat("bool *y = (bool *) (void *) (int) (x);", Spaces); 15059 verifyFormat("bool *y = (bool *) (void *) (int) foo(x);", Spaces); 15060 Spaces.ColumnLimit = 80; 15061 Spaces.IndentWidth = 4; 15062 Spaces.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 15063 verifyFormat("void foo( ) {\n" 15064 " size_t foo = (*(function))(\n" 15065 " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, " 15066 "BarrrrrrrrrrrrLong,\n" 15067 " FoooooooooLooooong);\n" 15068 "}", 15069 Spaces); 15070 Spaces.SpaceAfterCStyleCast = false; 15071 verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces); 15072 verifyFormat("size_t idx = (size_t)a;", Spaces); 15073 verifyFormat("size_t idx = (size_t)(a - 1);", Spaces); 15074 verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces); 15075 verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces); 15076 verifyFormat("size_t idx = (*foo)(a - 1);", Spaces); 15077 verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces); 15078 15079 verifyFormat("void foo( ) {\n" 15080 " size_t foo = (*(function))(\n" 15081 " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, " 15082 "BarrrrrrrrrrrrLong,\n" 15083 " FoooooooooLooooong);\n" 15084 "}", 15085 Spaces); 15086 } 15087 15088 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) { 15089 verifyFormat("int a[5];"); 15090 verifyFormat("a[3] += 42;"); 15091 15092 FormatStyle Spaces = getLLVMStyle(); 15093 Spaces.SpacesInSquareBrackets = true; 15094 // Not lambdas. 15095 verifyFormat("int a[ 5 ];", Spaces); 15096 verifyFormat("a[ 3 ] += 42;", Spaces); 15097 verifyFormat("constexpr char hello[]{\"hello\"};", Spaces); 15098 verifyFormat("double &operator[](int i) { return 0; }\n" 15099 "int i;", 15100 Spaces); 15101 verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces); 15102 verifyFormat("int i = a[ a ][ a ]->f();", Spaces); 15103 verifyFormat("int i = (*b)[ a ]->f();", Spaces); 15104 // Lambdas. 15105 verifyFormat("int c = []() -> int { return 2; }();\n", Spaces); 15106 verifyFormat("return [ i, args... ] {};", Spaces); 15107 verifyFormat("int foo = [ &bar ]() {};", Spaces); 15108 verifyFormat("int foo = [ = ]() {};", Spaces); 15109 verifyFormat("int foo = [ & ]() {};", Spaces); 15110 verifyFormat("int foo = [ =, &bar ]() {};", Spaces); 15111 verifyFormat("int foo = [ &bar, = ]() {};", Spaces); 15112 } 15113 15114 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) { 15115 FormatStyle NoSpaceStyle = getLLVMStyle(); 15116 verifyFormat("int a[5];", NoSpaceStyle); 15117 verifyFormat("a[3] += 42;", NoSpaceStyle); 15118 15119 verifyFormat("int a[1];", NoSpaceStyle); 15120 verifyFormat("int 1 [a];", NoSpaceStyle); 15121 verifyFormat("int a[1][2];", NoSpaceStyle); 15122 verifyFormat("a[7] = 5;", NoSpaceStyle); 15123 verifyFormat("int a = (f())[23];", NoSpaceStyle); 15124 verifyFormat("f([] {})", NoSpaceStyle); 15125 15126 FormatStyle Space = getLLVMStyle(); 15127 Space.SpaceBeforeSquareBrackets = true; 15128 verifyFormat("int c = []() -> int { return 2; }();\n", Space); 15129 verifyFormat("return [i, args...] {};", Space); 15130 15131 verifyFormat("int a [5];", Space); 15132 verifyFormat("a [3] += 42;", Space); 15133 verifyFormat("constexpr char hello []{\"hello\"};", Space); 15134 verifyFormat("double &operator[](int i) { return 0; }\n" 15135 "int i;", 15136 Space); 15137 verifyFormat("std::unique_ptr<int []> foo() {}", Space); 15138 verifyFormat("int i = a [a][a]->f();", Space); 15139 verifyFormat("int i = (*b) [a]->f();", Space); 15140 15141 verifyFormat("int a [1];", Space); 15142 verifyFormat("int 1 [a];", Space); 15143 verifyFormat("int a [1][2];", Space); 15144 verifyFormat("a [7] = 5;", Space); 15145 verifyFormat("int a = (f()) [23];", Space); 15146 verifyFormat("f([] {})", Space); 15147 } 15148 15149 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) { 15150 verifyFormat("int a = 5;"); 15151 verifyFormat("a += 42;"); 15152 verifyFormat("a or_eq 8;"); 15153 15154 FormatStyle Spaces = getLLVMStyle(); 15155 Spaces.SpaceBeforeAssignmentOperators = false; 15156 verifyFormat("int a= 5;", Spaces); 15157 verifyFormat("a+= 42;", Spaces); 15158 verifyFormat("a or_eq 8;", Spaces); 15159 } 15160 15161 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) { 15162 verifyFormat("class Foo : public Bar {};"); 15163 verifyFormat("Foo::Foo() : foo(1) {}"); 15164 verifyFormat("for (auto a : b) {\n}"); 15165 verifyFormat("int x = a ? b : c;"); 15166 verifyFormat("{\n" 15167 "label0:\n" 15168 " int x = 0;\n" 15169 "}"); 15170 verifyFormat("switch (x) {\n" 15171 "case 1:\n" 15172 "default:\n" 15173 "}"); 15174 verifyFormat("switch (allBraces) {\n" 15175 "case 1: {\n" 15176 " break;\n" 15177 "}\n" 15178 "case 2: {\n" 15179 " [[fallthrough]];\n" 15180 "}\n" 15181 "default: {\n" 15182 " break;\n" 15183 "}\n" 15184 "}"); 15185 15186 FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30); 15187 CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false; 15188 verifyFormat("class Foo : public Bar {};", CtorInitializerStyle); 15189 verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle); 15190 verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle); 15191 verifyFormat("int x = a ? b : c;", CtorInitializerStyle); 15192 verifyFormat("{\n" 15193 "label1:\n" 15194 " int x = 0;\n" 15195 "}", 15196 CtorInitializerStyle); 15197 verifyFormat("switch (x) {\n" 15198 "case 1:\n" 15199 "default:\n" 15200 "}", 15201 CtorInitializerStyle); 15202 verifyFormat("switch (allBraces) {\n" 15203 "case 1: {\n" 15204 " break;\n" 15205 "}\n" 15206 "case 2: {\n" 15207 " [[fallthrough]];\n" 15208 "}\n" 15209 "default: {\n" 15210 " break;\n" 15211 "}\n" 15212 "}", 15213 CtorInitializerStyle); 15214 CtorInitializerStyle.BreakConstructorInitializers = 15215 FormatStyle::BCIS_AfterColon; 15216 verifyFormat("Fooooooooooo::Fooooooooooo():\n" 15217 " aaaaaaaaaaaaaaaa(1),\n" 15218 " bbbbbbbbbbbbbbbb(2) {}", 15219 CtorInitializerStyle); 15220 CtorInitializerStyle.BreakConstructorInitializers = 15221 FormatStyle::BCIS_BeforeComma; 15222 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15223 " : aaaaaaaaaaaaaaaa(1)\n" 15224 " , bbbbbbbbbbbbbbbb(2) {}", 15225 CtorInitializerStyle); 15226 CtorInitializerStyle.BreakConstructorInitializers = 15227 FormatStyle::BCIS_BeforeColon; 15228 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15229 " : aaaaaaaaaaaaaaaa(1),\n" 15230 " bbbbbbbbbbbbbbbb(2) {}", 15231 CtorInitializerStyle); 15232 CtorInitializerStyle.ConstructorInitializerIndentWidth = 0; 15233 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15234 ": aaaaaaaaaaaaaaaa(1),\n" 15235 " bbbbbbbbbbbbbbbb(2) {}", 15236 CtorInitializerStyle); 15237 15238 FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30); 15239 InheritanceStyle.SpaceBeforeInheritanceColon = false; 15240 verifyFormat("class Foo: public Bar {};", InheritanceStyle); 15241 verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle); 15242 verifyFormat("for (auto a : b) {\n}", InheritanceStyle); 15243 verifyFormat("int x = a ? b : c;", InheritanceStyle); 15244 verifyFormat("{\n" 15245 "label2:\n" 15246 " int x = 0;\n" 15247 "}", 15248 InheritanceStyle); 15249 verifyFormat("switch (x) {\n" 15250 "case 1:\n" 15251 "default:\n" 15252 "}", 15253 InheritanceStyle); 15254 verifyFormat("switch (allBraces) {\n" 15255 "case 1: {\n" 15256 " break;\n" 15257 "}\n" 15258 "case 2: {\n" 15259 " [[fallthrough]];\n" 15260 "}\n" 15261 "default: {\n" 15262 " break;\n" 15263 "}\n" 15264 "}", 15265 InheritanceStyle); 15266 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterComma; 15267 verifyFormat("class Foooooooooooooooooooooo\n" 15268 " : public aaaaaaaaaaaaaaaaaa,\n" 15269 " public bbbbbbbbbbbbbbbbbb {\n" 15270 "}", 15271 InheritanceStyle); 15272 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon; 15273 verifyFormat("class Foooooooooooooooooooooo:\n" 15274 " public aaaaaaaaaaaaaaaaaa,\n" 15275 " public bbbbbbbbbbbbbbbbbb {\n" 15276 "}", 15277 InheritanceStyle); 15278 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma; 15279 verifyFormat("class Foooooooooooooooooooooo\n" 15280 " : public aaaaaaaaaaaaaaaaaa\n" 15281 " , public bbbbbbbbbbbbbbbbbb {\n" 15282 "}", 15283 InheritanceStyle); 15284 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 15285 verifyFormat("class Foooooooooooooooooooooo\n" 15286 " : public aaaaaaaaaaaaaaaaaa,\n" 15287 " public bbbbbbbbbbbbbbbbbb {\n" 15288 "}", 15289 InheritanceStyle); 15290 InheritanceStyle.ConstructorInitializerIndentWidth = 0; 15291 verifyFormat("class Foooooooooooooooooooooo\n" 15292 ": public aaaaaaaaaaaaaaaaaa,\n" 15293 " public bbbbbbbbbbbbbbbbbb {}", 15294 InheritanceStyle); 15295 15296 FormatStyle ForLoopStyle = getLLVMStyle(); 15297 ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false; 15298 verifyFormat("class Foo : public Bar {};", ForLoopStyle); 15299 verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle); 15300 verifyFormat("for (auto a: b) {\n}", ForLoopStyle); 15301 verifyFormat("int x = a ? b : c;", ForLoopStyle); 15302 verifyFormat("{\n" 15303 "label2:\n" 15304 " int x = 0;\n" 15305 "}", 15306 ForLoopStyle); 15307 verifyFormat("switch (x) {\n" 15308 "case 1:\n" 15309 "default:\n" 15310 "}", 15311 ForLoopStyle); 15312 verifyFormat("switch (allBraces) {\n" 15313 "case 1: {\n" 15314 " break;\n" 15315 "}\n" 15316 "case 2: {\n" 15317 " [[fallthrough]];\n" 15318 "}\n" 15319 "default: {\n" 15320 " break;\n" 15321 "}\n" 15322 "}", 15323 ForLoopStyle); 15324 15325 FormatStyle CaseStyle = getLLVMStyle(); 15326 CaseStyle.SpaceBeforeCaseColon = true; 15327 verifyFormat("class Foo : public Bar {};", CaseStyle); 15328 verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle); 15329 verifyFormat("for (auto a : b) {\n}", CaseStyle); 15330 verifyFormat("int x = a ? b : c;", CaseStyle); 15331 verifyFormat("switch (x) {\n" 15332 "case 1 :\n" 15333 "default :\n" 15334 "}", 15335 CaseStyle); 15336 verifyFormat("switch (allBraces) {\n" 15337 "case 1 : {\n" 15338 " break;\n" 15339 "}\n" 15340 "case 2 : {\n" 15341 " [[fallthrough]];\n" 15342 "}\n" 15343 "default : {\n" 15344 " break;\n" 15345 "}\n" 15346 "}", 15347 CaseStyle); 15348 15349 FormatStyle NoSpaceStyle = getLLVMStyle(); 15350 EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false); 15351 NoSpaceStyle.SpaceBeforeCtorInitializerColon = false; 15352 NoSpaceStyle.SpaceBeforeInheritanceColon = false; 15353 NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false; 15354 verifyFormat("class Foo: public Bar {};", NoSpaceStyle); 15355 verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle); 15356 verifyFormat("for (auto a: b) {\n}", NoSpaceStyle); 15357 verifyFormat("int x = a ? b : c;", NoSpaceStyle); 15358 verifyFormat("{\n" 15359 "label3:\n" 15360 " int x = 0;\n" 15361 "}", 15362 NoSpaceStyle); 15363 verifyFormat("switch (x) {\n" 15364 "case 1:\n" 15365 "default:\n" 15366 "}", 15367 NoSpaceStyle); 15368 verifyFormat("switch (allBraces) {\n" 15369 "case 1: {\n" 15370 " break;\n" 15371 "}\n" 15372 "case 2: {\n" 15373 " [[fallthrough]];\n" 15374 "}\n" 15375 "default: {\n" 15376 " break;\n" 15377 "}\n" 15378 "}", 15379 NoSpaceStyle); 15380 15381 FormatStyle InvertedSpaceStyle = getLLVMStyle(); 15382 InvertedSpaceStyle.SpaceBeforeCaseColon = true; 15383 InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false; 15384 InvertedSpaceStyle.SpaceBeforeInheritanceColon = false; 15385 InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false; 15386 verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle); 15387 verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle); 15388 verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle); 15389 verifyFormat("int x = a ? b : c;", InvertedSpaceStyle); 15390 verifyFormat("{\n" 15391 "label3:\n" 15392 " int x = 0;\n" 15393 "}", 15394 InvertedSpaceStyle); 15395 verifyFormat("switch (x) {\n" 15396 "case 1 :\n" 15397 "case 2 : {\n" 15398 " break;\n" 15399 "}\n" 15400 "default :\n" 15401 " break;\n" 15402 "}", 15403 InvertedSpaceStyle); 15404 verifyFormat("switch (allBraces) {\n" 15405 "case 1 : {\n" 15406 " break;\n" 15407 "}\n" 15408 "case 2 : {\n" 15409 " [[fallthrough]];\n" 15410 "}\n" 15411 "default : {\n" 15412 " break;\n" 15413 "}\n" 15414 "}", 15415 InvertedSpaceStyle); 15416 } 15417 15418 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) { 15419 FormatStyle Style = getLLVMStyle(); 15420 15421 Style.PointerAlignment = FormatStyle::PAS_Left; 15422 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default; 15423 verifyFormat("void* const* x = NULL;", Style); 15424 15425 #define verifyQualifierSpaces(Code, Pointers, Qualifiers) \ 15426 do { \ 15427 Style.PointerAlignment = FormatStyle::Pointers; \ 15428 Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers; \ 15429 verifyFormat(Code, Style); \ 15430 } while (false) 15431 15432 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default); 15433 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default); 15434 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default); 15435 15436 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before); 15437 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before); 15438 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before); 15439 15440 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After); 15441 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After); 15442 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After); 15443 15444 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both); 15445 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both); 15446 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both); 15447 15448 verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default); 15449 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, 15450 SAPQ_Default); 15451 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15452 SAPQ_Default); 15453 15454 verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before); 15455 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, 15456 SAPQ_Before); 15457 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15458 SAPQ_Before); 15459 15460 verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After); 15461 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After); 15462 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15463 SAPQ_After); 15464 15465 verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both); 15466 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both); 15467 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both); 15468 15469 #undef verifyQualifierSpaces 15470 15471 FormatStyle Spaces = getLLVMStyle(); 15472 Spaces.AttributeMacros.push_back("qualified"); 15473 Spaces.PointerAlignment = FormatStyle::PAS_Right; 15474 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default; 15475 verifyFormat("SomeType *volatile *a = NULL;", Spaces); 15476 verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces); 15477 verifyFormat("std::vector<SomeType *const *> x;", Spaces); 15478 verifyFormat("std::vector<SomeType *qualified *> x;", Spaces); 15479 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15480 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before; 15481 verifyFormat("SomeType * volatile *a = NULL;", Spaces); 15482 verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces); 15483 verifyFormat("std::vector<SomeType * const *> x;", Spaces); 15484 verifyFormat("std::vector<SomeType * qualified *> x;", Spaces); 15485 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15486 15487 // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left. 15488 Spaces.PointerAlignment = FormatStyle::PAS_Left; 15489 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before; 15490 verifyFormat("SomeType* volatile* a = NULL;", Spaces); 15491 verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces); 15492 verifyFormat("std::vector<SomeType* const*> x;", Spaces); 15493 verifyFormat("std::vector<SomeType* qualified*> x;", Spaces); 15494 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15495 // However, setting it to SAPQ_After should add spaces after __attribute, etc. 15496 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After; 15497 verifyFormat("SomeType* volatile * a = NULL;", Spaces); 15498 verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces); 15499 verifyFormat("std::vector<SomeType* const *> x;", Spaces); 15500 verifyFormat("std::vector<SomeType* qualified *> x;", Spaces); 15501 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15502 15503 // PAS_Middle should not have any noticeable changes even for SAPQ_Both 15504 Spaces.PointerAlignment = FormatStyle::PAS_Middle; 15505 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After; 15506 verifyFormat("SomeType * volatile * a = NULL;", Spaces); 15507 verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces); 15508 verifyFormat("std::vector<SomeType * const *> x;", Spaces); 15509 verifyFormat("std::vector<SomeType * qualified *> x;", Spaces); 15510 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15511 } 15512 15513 TEST_F(FormatTest, AlignConsecutiveMacros) { 15514 FormatStyle Style = getLLVMStyle(); 15515 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 15516 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 15517 Style.AlignConsecutiveMacros = FormatStyle::ACS_None; 15518 15519 verifyFormat("#define a 3\n" 15520 "#define bbbb 4\n" 15521 "#define ccc (5)", 15522 Style); 15523 15524 verifyFormat("#define f(x) (x * x)\n" 15525 "#define fff(x, y, z) (x * y + z)\n" 15526 "#define ffff(x, y) (x - y)", 15527 Style); 15528 15529 verifyFormat("#define foo(x, y) (x + y)\n" 15530 "#define bar (5, 6)(2 + 2)", 15531 Style); 15532 15533 verifyFormat("#define a 3\n" 15534 "#define bbbb 4\n" 15535 "#define ccc (5)\n" 15536 "#define f(x) (x * x)\n" 15537 "#define fff(x, y, z) (x * y + z)\n" 15538 "#define ffff(x, y) (x - y)", 15539 Style); 15540 15541 Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 15542 verifyFormat("#define a 3\n" 15543 "#define bbbb 4\n" 15544 "#define ccc (5)", 15545 Style); 15546 15547 verifyFormat("#define f(x) (x * x)\n" 15548 "#define fff(x, y, z) (x * y + z)\n" 15549 "#define ffff(x, y) (x - y)", 15550 Style); 15551 15552 verifyFormat("#define foo(x, y) (x + y)\n" 15553 "#define bar (5, 6)(2 + 2)", 15554 Style); 15555 15556 verifyFormat("#define a 3\n" 15557 "#define bbbb 4\n" 15558 "#define ccc (5)\n" 15559 "#define f(x) (x * x)\n" 15560 "#define fff(x, y, z) (x * y + z)\n" 15561 "#define ffff(x, y) (x - y)", 15562 Style); 15563 15564 verifyFormat("#define a 5\n" 15565 "#define foo(x, y) (x + y)\n" 15566 "#define CCC (6)\n" 15567 "auto lambda = []() {\n" 15568 " auto ii = 0;\n" 15569 " float j = 0;\n" 15570 " return 0;\n" 15571 "};\n" 15572 "int i = 0;\n" 15573 "float i2 = 0;\n" 15574 "auto v = type{\n" 15575 " i = 1, //\n" 15576 " (i = 2), //\n" 15577 " i = 3 //\n" 15578 "};", 15579 Style); 15580 15581 Style.AlignConsecutiveMacros = FormatStyle::ACS_None; 15582 Style.ColumnLimit = 20; 15583 15584 verifyFormat("#define a \\\n" 15585 " \"aabbbbbbbbbbbb\"\n" 15586 "#define D \\\n" 15587 " \"aabbbbbbbbbbbb\" \\\n" 15588 " \"ccddeeeeeeeee\"\n" 15589 "#define B \\\n" 15590 " \"QQQQQQQQQQQQQ\" \\\n" 15591 " \"FFFFFFFFFFFFF\" \\\n" 15592 " \"LLLLLLLL\"\n", 15593 Style); 15594 15595 Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 15596 verifyFormat("#define a \\\n" 15597 " \"aabbbbbbbbbbbb\"\n" 15598 "#define D \\\n" 15599 " \"aabbbbbbbbbbbb\" \\\n" 15600 " \"ccddeeeeeeeee\"\n" 15601 "#define B \\\n" 15602 " \"QQQQQQQQQQQQQ\" \\\n" 15603 " \"FFFFFFFFFFFFF\" \\\n" 15604 " \"LLLLLLLL\"\n", 15605 Style); 15606 15607 // Test across comments 15608 Style.MaxEmptyLinesToKeep = 10; 15609 Style.ReflowComments = false; 15610 Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossComments; 15611 EXPECT_EQ("#define a 3\n" 15612 "// line comment\n" 15613 "#define bbbb 4\n" 15614 "#define ccc (5)", 15615 format("#define a 3\n" 15616 "// line comment\n" 15617 "#define bbbb 4\n" 15618 "#define ccc (5)", 15619 Style)); 15620 15621 EXPECT_EQ("#define a 3\n" 15622 "/* block comment */\n" 15623 "#define bbbb 4\n" 15624 "#define ccc (5)", 15625 format("#define a 3\n" 15626 "/* block comment */\n" 15627 "#define bbbb 4\n" 15628 "#define ccc (5)", 15629 Style)); 15630 15631 EXPECT_EQ("#define a 3\n" 15632 "/* multi-line *\n" 15633 " * block comment */\n" 15634 "#define bbbb 4\n" 15635 "#define ccc (5)", 15636 format("#define a 3\n" 15637 "/* multi-line *\n" 15638 " * block comment */\n" 15639 "#define bbbb 4\n" 15640 "#define ccc (5)", 15641 Style)); 15642 15643 EXPECT_EQ("#define a 3\n" 15644 "// multi-line line comment\n" 15645 "//\n" 15646 "#define bbbb 4\n" 15647 "#define ccc (5)", 15648 format("#define a 3\n" 15649 "// multi-line line comment\n" 15650 "//\n" 15651 "#define bbbb 4\n" 15652 "#define ccc (5)", 15653 Style)); 15654 15655 EXPECT_EQ("#define a 3\n" 15656 "// empty lines still break.\n" 15657 "\n" 15658 "#define bbbb 4\n" 15659 "#define ccc (5)", 15660 format("#define a 3\n" 15661 "// empty lines still break.\n" 15662 "\n" 15663 "#define bbbb 4\n" 15664 "#define ccc (5)", 15665 Style)); 15666 15667 // Test across empty lines 15668 Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLines; 15669 EXPECT_EQ("#define a 3\n" 15670 "\n" 15671 "#define bbbb 4\n" 15672 "#define ccc (5)", 15673 format("#define a 3\n" 15674 "\n" 15675 "#define bbbb 4\n" 15676 "#define ccc (5)", 15677 Style)); 15678 15679 EXPECT_EQ("#define a 3\n" 15680 "\n" 15681 "\n" 15682 "\n" 15683 "#define bbbb 4\n" 15684 "#define ccc (5)", 15685 format("#define a 3\n" 15686 "\n" 15687 "\n" 15688 "\n" 15689 "#define bbbb 4\n" 15690 "#define ccc (5)", 15691 Style)); 15692 15693 EXPECT_EQ("#define a 3\n" 15694 "// comments should break alignment\n" 15695 "//\n" 15696 "#define bbbb 4\n" 15697 "#define ccc (5)", 15698 format("#define a 3\n" 15699 "// comments should break alignment\n" 15700 "//\n" 15701 "#define bbbb 4\n" 15702 "#define ccc (5)", 15703 Style)); 15704 15705 // Test across empty lines and comments 15706 Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLinesAndComments; 15707 verifyFormat("#define a 3\n" 15708 "\n" 15709 "// line comment\n" 15710 "#define bbbb 4\n" 15711 "#define ccc (5)", 15712 Style); 15713 15714 EXPECT_EQ("#define a 3\n" 15715 "\n" 15716 "\n" 15717 "/* multi-line *\n" 15718 " * block comment */\n" 15719 "\n" 15720 "\n" 15721 "#define bbbb 4\n" 15722 "#define ccc (5)", 15723 format("#define a 3\n" 15724 "\n" 15725 "\n" 15726 "/* multi-line *\n" 15727 " * block comment */\n" 15728 "\n" 15729 "\n" 15730 "#define bbbb 4\n" 15731 "#define ccc (5)", 15732 Style)); 15733 15734 EXPECT_EQ("#define a 3\n" 15735 "\n" 15736 "\n" 15737 "/* multi-line *\n" 15738 " * block comment */\n" 15739 "\n" 15740 "\n" 15741 "#define bbbb 4\n" 15742 "#define ccc (5)", 15743 format("#define a 3\n" 15744 "\n" 15745 "\n" 15746 "/* multi-line *\n" 15747 " * block comment */\n" 15748 "\n" 15749 "\n" 15750 "#define bbbb 4\n" 15751 "#define ccc (5)", 15752 Style)); 15753 } 15754 15755 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) { 15756 FormatStyle Alignment = getLLVMStyle(); 15757 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 15758 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossEmptyLines; 15759 15760 Alignment.MaxEmptyLinesToKeep = 10; 15761 /* Test alignment across empty lines */ 15762 EXPECT_EQ("int a = 5;\n" 15763 "\n" 15764 "int oneTwoThree = 123;", 15765 format("int a = 5;\n" 15766 "\n" 15767 "int oneTwoThree= 123;", 15768 Alignment)); 15769 EXPECT_EQ("int a = 5;\n" 15770 "int one = 1;\n" 15771 "\n" 15772 "int oneTwoThree = 123;", 15773 format("int a = 5;\n" 15774 "int one = 1;\n" 15775 "\n" 15776 "int oneTwoThree = 123;", 15777 Alignment)); 15778 EXPECT_EQ("int a = 5;\n" 15779 "int one = 1;\n" 15780 "\n" 15781 "int oneTwoThree = 123;\n" 15782 "int oneTwo = 12;", 15783 format("int a = 5;\n" 15784 "int one = 1;\n" 15785 "\n" 15786 "int oneTwoThree = 123;\n" 15787 "int oneTwo = 12;", 15788 Alignment)); 15789 15790 /* Test across comments */ 15791 EXPECT_EQ("int a = 5;\n" 15792 "/* block comment */\n" 15793 "int oneTwoThree = 123;", 15794 format("int a = 5;\n" 15795 "/* block comment */\n" 15796 "int oneTwoThree=123;", 15797 Alignment)); 15798 15799 EXPECT_EQ("int a = 5;\n" 15800 "// line comment\n" 15801 "int oneTwoThree = 123;", 15802 format("int a = 5;\n" 15803 "// line comment\n" 15804 "int oneTwoThree=123;", 15805 Alignment)); 15806 15807 /* Test across comments and newlines */ 15808 EXPECT_EQ("int a = 5;\n" 15809 "\n" 15810 "/* block comment */\n" 15811 "int oneTwoThree = 123;", 15812 format("int a = 5;\n" 15813 "\n" 15814 "/* block comment */\n" 15815 "int oneTwoThree=123;", 15816 Alignment)); 15817 15818 EXPECT_EQ("int a = 5;\n" 15819 "\n" 15820 "// line comment\n" 15821 "int oneTwoThree = 123;", 15822 format("int a = 5;\n" 15823 "\n" 15824 "// line comment\n" 15825 "int oneTwoThree=123;", 15826 Alignment)); 15827 } 15828 15829 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) { 15830 FormatStyle Alignment = getLLVMStyle(); 15831 Alignment.AlignConsecutiveDeclarations = 15832 FormatStyle::ACS_AcrossEmptyLinesAndComments; 15833 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 15834 15835 Alignment.MaxEmptyLinesToKeep = 10; 15836 /* Test alignment across empty lines */ 15837 EXPECT_EQ("int a = 5;\n" 15838 "\n" 15839 "float const oneTwoThree = 123;", 15840 format("int a = 5;\n" 15841 "\n" 15842 "float const oneTwoThree = 123;", 15843 Alignment)); 15844 EXPECT_EQ("int a = 5;\n" 15845 "float const one = 1;\n" 15846 "\n" 15847 "int oneTwoThree = 123;", 15848 format("int a = 5;\n" 15849 "float const one = 1;\n" 15850 "\n" 15851 "int oneTwoThree = 123;", 15852 Alignment)); 15853 15854 /* Test across comments */ 15855 EXPECT_EQ("float const a = 5;\n" 15856 "/* block comment */\n" 15857 "int oneTwoThree = 123;", 15858 format("float const a = 5;\n" 15859 "/* block comment */\n" 15860 "int oneTwoThree=123;", 15861 Alignment)); 15862 15863 EXPECT_EQ("float const a = 5;\n" 15864 "// line comment\n" 15865 "int oneTwoThree = 123;", 15866 format("float const a = 5;\n" 15867 "// line comment\n" 15868 "int oneTwoThree=123;", 15869 Alignment)); 15870 15871 /* Test across comments and newlines */ 15872 EXPECT_EQ("float const a = 5;\n" 15873 "\n" 15874 "/* block comment */\n" 15875 "int oneTwoThree = 123;", 15876 format("float const a = 5;\n" 15877 "\n" 15878 "/* block comment */\n" 15879 "int oneTwoThree=123;", 15880 Alignment)); 15881 15882 EXPECT_EQ("float const a = 5;\n" 15883 "\n" 15884 "// line comment\n" 15885 "int oneTwoThree = 123;", 15886 format("float const a = 5;\n" 15887 "\n" 15888 "// line comment\n" 15889 "int oneTwoThree=123;", 15890 Alignment)); 15891 } 15892 15893 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) { 15894 FormatStyle Alignment = getLLVMStyle(); 15895 Alignment.AlignConsecutiveBitFields = 15896 FormatStyle::ACS_AcrossEmptyLinesAndComments; 15897 15898 Alignment.MaxEmptyLinesToKeep = 10; 15899 /* Test alignment across empty lines */ 15900 EXPECT_EQ("int a : 5;\n" 15901 "\n" 15902 "int longbitfield : 6;", 15903 format("int a : 5;\n" 15904 "\n" 15905 "int longbitfield : 6;", 15906 Alignment)); 15907 EXPECT_EQ("int a : 5;\n" 15908 "int one : 1;\n" 15909 "\n" 15910 "int longbitfield : 6;", 15911 format("int a : 5;\n" 15912 "int one : 1;\n" 15913 "\n" 15914 "int longbitfield : 6;", 15915 Alignment)); 15916 15917 /* Test across comments */ 15918 EXPECT_EQ("int a : 5;\n" 15919 "/* block comment */\n" 15920 "int longbitfield : 6;", 15921 format("int a : 5;\n" 15922 "/* block comment */\n" 15923 "int longbitfield : 6;", 15924 Alignment)); 15925 EXPECT_EQ("int a : 5;\n" 15926 "int one : 1;\n" 15927 "// line comment\n" 15928 "int longbitfield : 6;", 15929 format("int a : 5;\n" 15930 "int one : 1;\n" 15931 "// line comment\n" 15932 "int longbitfield : 6;", 15933 Alignment)); 15934 15935 /* Test across comments and newlines */ 15936 EXPECT_EQ("int a : 5;\n" 15937 "/* block comment */\n" 15938 "\n" 15939 "int longbitfield : 6;", 15940 format("int a : 5;\n" 15941 "/* block comment */\n" 15942 "\n" 15943 "int longbitfield : 6;", 15944 Alignment)); 15945 EXPECT_EQ("int a : 5;\n" 15946 "int one : 1;\n" 15947 "\n" 15948 "// line comment\n" 15949 "\n" 15950 "int longbitfield : 6;", 15951 format("int a : 5;\n" 15952 "int one : 1;\n" 15953 "\n" 15954 "// line comment \n" 15955 "\n" 15956 "int longbitfield : 6;", 15957 Alignment)); 15958 } 15959 15960 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) { 15961 FormatStyle Alignment = getLLVMStyle(); 15962 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 15963 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossComments; 15964 15965 Alignment.MaxEmptyLinesToKeep = 10; 15966 /* Test alignment across empty lines */ 15967 EXPECT_EQ("int a = 5;\n" 15968 "\n" 15969 "int oneTwoThree = 123;", 15970 format("int a = 5;\n" 15971 "\n" 15972 "int oneTwoThree= 123;", 15973 Alignment)); 15974 EXPECT_EQ("int a = 5;\n" 15975 "int one = 1;\n" 15976 "\n" 15977 "int oneTwoThree = 123;", 15978 format("int a = 5;\n" 15979 "int one = 1;\n" 15980 "\n" 15981 "int oneTwoThree = 123;", 15982 Alignment)); 15983 15984 /* Test across comments */ 15985 EXPECT_EQ("int a = 5;\n" 15986 "/* block comment */\n" 15987 "int oneTwoThree = 123;", 15988 format("int a = 5;\n" 15989 "/* block comment */\n" 15990 "int oneTwoThree=123;", 15991 Alignment)); 15992 15993 EXPECT_EQ("int a = 5;\n" 15994 "// line comment\n" 15995 "int oneTwoThree = 123;", 15996 format("int a = 5;\n" 15997 "// line comment\n" 15998 "int oneTwoThree=123;", 15999 Alignment)); 16000 16001 EXPECT_EQ("int a = 5;\n" 16002 "/*\n" 16003 " * multi-line block comment\n" 16004 " */\n" 16005 "int oneTwoThree = 123;", 16006 format("int a = 5;\n" 16007 "/*\n" 16008 " * multi-line block comment\n" 16009 " */\n" 16010 "int oneTwoThree=123;", 16011 Alignment)); 16012 16013 EXPECT_EQ("int a = 5;\n" 16014 "//\n" 16015 "// multi-line line comment\n" 16016 "//\n" 16017 "int oneTwoThree = 123;", 16018 format("int a = 5;\n" 16019 "//\n" 16020 "// multi-line line comment\n" 16021 "//\n" 16022 "int oneTwoThree=123;", 16023 Alignment)); 16024 16025 /* Test across comments and newlines */ 16026 EXPECT_EQ("int a = 5;\n" 16027 "\n" 16028 "/* block comment */\n" 16029 "int oneTwoThree = 123;", 16030 format("int a = 5;\n" 16031 "\n" 16032 "/* block comment */\n" 16033 "int oneTwoThree=123;", 16034 Alignment)); 16035 16036 EXPECT_EQ("int a = 5;\n" 16037 "\n" 16038 "// line comment\n" 16039 "int oneTwoThree = 123;", 16040 format("int a = 5;\n" 16041 "\n" 16042 "// line comment\n" 16043 "int oneTwoThree=123;", 16044 Alignment)); 16045 } 16046 16047 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) { 16048 FormatStyle Alignment = getLLVMStyle(); 16049 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 16050 Alignment.AlignConsecutiveAssignments = 16051 FormatStyle::ACS_AcrossEmptyLinesAndComments; 16052 verifyFormat("int a = 5;\n" 16053 "int oneTwoThree = 123;", 16054 Alignment); 16055 verifyFormat("int a = method();\n" 16056 "int oneTwoThree = 133;", 16057 Alignment); 16058 verifyFormat("a &= 5;\n" 16059 "bcd *= 5;\n" 16060 "ghtyf += 5;\n" 16061 "dvfvdb -= 5;\n" 16062 "a /= 5;\n" 16063 "vdsvsv %= 5;\n" 16064 "sfdbddfbdfbb ^= 5;\n" 16065 "dvsdsv |= 5;\n" 16066 "int dsvvdvsdvvv = 123;", 16067 Alignment); 16068 verifyFormat("int i = 1, j = 10;\n" 16069 "something = 2000;", 16070 Alignment); 16071 verifyFormat("something = 2000;\n" 16072 "int i = 1, j = 10;\n", 16073 Alignment); 16074 verifyFormat("something = 2000;\n" 16075 "another = 911;\n" 16076 "int i = 1, j = 10;\n" 16077 "oneMore = 1;\n" 16078 "i = 2;", 16079 Alignment); 16080 verifyFormat("int a = 5;\n" 16081 "int one = 1;\n" 16082 "method();\n" 16083 "int oneTwoThree = 123;\n" 16084 "int oneTwo = 12;", 16085 Alignment); 16086 verifyFormat("int oneTwoThree = 123;\n" 16087 "int oneTwo = 12;\n" 16088 "method();\n", 16089 Alignment); 16090 verifyFormat("int oneTwoThree = 123; // comment\n" 16091 "int oneTwo = 12; // comment", 16092 Alignment); 16093 16094 // Bug 25167 16095 /* Uncomment when fixed 16096 verifyFormat("#if A\n" 16097 "#else\n" 16098 "int aaaaaaaa = 12;\n" 16099 "#endif\n" 16100 "#if B\n" 16101 "#else\n" 16102 "int a = 12;\n" 16103 "#endif\n", 16104 Alignment); 16105 verifyFormat("enum foo {\n" 16106 "#if A\n" 16107 "#else\n" 16108 " aaaaaaaa = 12;\n" 16109 "#endif\n" 16110 "#if B\n" 16111 "#else\n" 16112 " a = 12;\n" 16113 "#endif\n" 16114 "};\n", 16115 Alignment); 16116 */ 16117 16118 Alignment.MaxEmptyLinesToKeep = 10; 16119 /* Test alignment across empty lines */ 16120 EXPECT_EQ("int a = 5;\n" 16121 "\n" 16122 "int oneTwoThree = 123;", 16123 format("int a = 5;\n" 16124 "\n" 16125 "int oneTwoThree= 123;", 16126 Alignment)); 16127 EXPECT_EQ("int a = 5;\n" 16128 "int one = 1;\n" 16129 "\n" 16130 "int oneTwoThree = 123;", 16131 format("int a = 5;\n" 16132 "int one = 1;\n" 16133 "\n" 16134 "int oneTwoThree = 123;", 16135 Alignment)); 16136 EXPECT_EQ("int a = 5;\n" 16137 "int one = 1;\n" 16138 "\n" 16139 "int oneTwoThree = 123;\n" 16140 "int oneTwo = 12;", 16141 format("int a = 5;\n" 16142 "int one = 1;\n" 16143 "\n" 16144 "int oneTwoThree = 123;\n" 16145 "int oneTwo = 12;", 16146 Alignment)); 16147 16148 /* Test across comments */ 16149 EXPECT_EQ("int a = 5;\n" 16150 "/* block comment */\n" 16151 "int oneTwoThree = 123;", 16152 format("int a = 5;\n" 16153 "/* block comment */\n" 16154 "int oneTwoThree=123;", 16155 Alignment)); 16156 16157 EXPECT_EQ("int a = 5;\n" 16158 "// line comment\n" 16159 "int oneTwoThree = 123;", 16160 format("int a = 5;\n" 16161 "// line comment\n" 16162 "int oneTwoThree=123;", 16163 Alignment)); 16164 16165 /* Test across comments and newlines */ 16166 EXPECT_EQ("int a = 5;\n" 16167 "\n" 16168 "/* block comment */\n" 16169 "int oneTwoThree = 123;", 16170 format("int a = 5;\n" 16171 "\n" 16172 "/* block comment */\n" 16173 "int oneTwoThree=123;", 16174 Alignment)); 16175 16176 EXPECT_EQ("int a = 5;\n" 16177 "\n" 16178 "// line comment\n" 16179 "int oneTwoThree = 123;", 16180 format("int a = 5;\n" 16181 "\n" 16182 "// line comment\n" 16183 "int oneTwoThree=123;", 16184 Alignment)); 16185 16186 EXPECT_EQ("int a = 5;\n" 16187 "//\n" 16188 "// multi-line line comment\n" 16189 "//\n" 16190 "int oneTwoThree = 123;", 16191 format("int a = 5;\n" 16192 "//\n" 16193 "// multi-line line comment\n" 16194 "//\n" 16195 "int oneTwoThree=123;", 16196 Alignment)); 16197 16198 EXPECT_EQ("int a = 5;\n" 16199 "/*\n" 16200 " * multi-line block comment\n" 16201 " */\n" 16202 "int oneTwoThree = 123;", 16203 format("int a = 5;\n" 16204 "/*\n" 16205 " * multi-line block comment\n" 16206 " */\n" 16207 "int oneTwoThree=123;", 16208 Alignment)); 16209 16210 EXPECT_EQ("int a = 5;\n" 16211 "\n" 16212 "/* block comment */\n" 16213 "\n" 16214 "\n" 16215 "\n" 16216 "int oneTwoThree = 123;", 16217 format("int a = 5;\n" 16218 "\n" 16219 "/* block comment */\n" 16220 "\n" 16221 "\n" 16222 "\n" 16223 "int oneTwoThree=123;", 16224 Alignment)); 16225 16226 EXPECT_EQ("int a = 5;\n" 16227 "\n" 16228 "// line comment\n" 16229 "\n" 16230 "\n" 16231 "\n" 16232 "int oneTwoThree = 123;", 16233 format("int a = 5;\n" 16234 "\n" 16235 "// line comment\n" 16236 "\n" 16237 "\n" 16238 "\n" 16239 "int oneTwoThree=123;", 16240 Alignment)); 16241 16242 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 16243 verifyFormat("#define A \\\n" 16244 " int aaaa = 12; \\\n" 16245 " int b = 23; \\\n" 16246 " int ccc = 234; \\\n" 16247 " int dddddddddd = 2345;", 16248 Alignment); 16249 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 16250 verifyFormat("#define A \\\n" 16251 " int aaaa = 12; \\\n" 16252 " int b = 23; \\\n" 16253 " int ccc = 234; \\\n" 16254 " int dddddddddd = 2345;", 16255 Alignment); 16256 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 16257 verifyFormat("#define A " 16258 " \\\n" 16259 " int aaaa = 12; " 16260 " \\\n" 16261 " int b = 23; " 16262 " \\\n" 16263 " int ccc = 234; " 16264 " \\\n" 16265 " int dddddddddd = 2345;", 16266 Alignment); 16267 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 16268 "k = 4, int l = 5,\n" 16269 " int m = 6) {\n" 16270 " int j = 10;\n" 16271 " otherThing = 1;\n" 16272 "}", 16273 Alignment); 16274 verifyFormat("void SomeFunction(int parameter = 0) {\n" 16275 " int i = 1;\n" 16276 " int j = 2;\n" 16277 " int big = 10000;\n" 16278 "}", 16279 Alignment); 16280 verifyFormat("class C {\n" 16281 "public:\n" 16282 " int i = 1;\n" 16283 " virtual void f() = 0;\n" 16284 "};", 16285 Alignment); 16286 verifyFormat("int i = 1;\n" 16287 "if (SomeType t = getSomething()) {\n" 16288 "}\n" 16289 "int j = 2;\n" 16290 "int big = 10000;", 16291 Alignment); 16292 verifyFormat("int j = 7;\n" 16293 "for (int k = 0; k < N; ++k) {\n" 16294 "}\n" 16295 "int j = 2;\n" 16296 "int big = 10000;\n" 16297 "}", 16298 Alignment); 16299 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 16300 verifyFormat("int i = 1;\n" 16301 "LooooooooooongType loooooooooooooooooooooongVariable\n" 16302 " = someLooooooooooooooooongFunction();\n" 16303 "int j = 2;", 16304 Alignment); 16305 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 16306 verifyFormat("int i = 1;\n" 16307 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 16308 " someLooooooooooooooooongFunction();\n" 16309 "int j = 2;", 16310 Alignment); 16311 16312 verifyFormat("auto lambda = []() {\n" 16313 " auto i = 0;\n" 16314 " return 0;\n" 16315 "};\n" 16316 "int i = 0;\n" 16317 "auto v = type{\n" 16318 " i = 1, //\n" 16319 " (i = 2), //\n" 16320 " i = 3 //\n" 16321 "};", 16322 Alignment); 16323 16324 verifyFormat( 16325 "int i = 1;\n" 16326 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 16327 " loooooooooooooooooooooongParameterB);\n" 16328 "int j = 2;", 16329 Alignment); 16330 16331 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n" 16332 " typename B = very_long_type_name_1,\n" 16333 " typename T_2 = very_long_type_name_2>\n" 16334 "auto foo() {}\n", 16335 Alignment); 16336 verifyFormat("int a, b = 1;\n" 16337 "int c = 2;\n" 16338 "int dd = 3;\n", 16339 Alignment); 16340 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 16341 "float b[1][] = {{3.f}};\n", 16342 Alignment); 16343 verifyFormat("for (int i = 0; i < 1; i++)\n" 16344 " int x = 1;\n", 16345 Alignment); 16346 verifyFormat("for (i = 0; i < 1; i++)\n" 16347 " x = 1;\n" 16348 "y = 1;\n", 16349 Alignment); 16350 16351 Alignment.ReflowComments = true; 16352 Alignment.ColumnLimit = 50; 16353 EXPECT_EQ("int x = 0;\n" 16354 "int yy = 1; /// specificlennospace\n" 16355 "int zzz = 2;\n", 16356 format("int x = 0;\n" 16357 "int yy = 1; ///specificlennospace\n" 16358 "int zzz = 2;\n", 16359 Alignment)); 16360 } 16361 16362 TEST_F(FormatTest, AlignConsecutiveAssignments) { 16363 FormatStyle Alignment = getLLVMStyle(); 16364 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 16365 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 16366 verifyFormat("int a = 5;\n" 16367 "int oneTwoThree = 123;", 16368 Alignment); 16369 verifyFormat("int a = 5;\n" 16370 "int oneTwoThree = 123;", 16371 Alignment); 16372 16373 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 16374 verifyFormat("int a = 5;\n" 16375 "int oneTwoThree = 123;", 16376 Alignment); 16377 verifyFormat("int a = method();\n" 16378 "int oneTwoThree = 133;", 16379 Alignment); 16380 verifyFormat("a &= 5;\n" 16381 "bcd *= 5;\n" 16382 "ghtyf += 5;\n" 16383 "dvfvdb -= 5;\n" 16384 "a /= 5;\n" 16385 "vdsvsv %= 5;\n" 16386 "sfdbddfbdfbb ^= 5;\n" 16387 "dvsdsv |= 5;\n" 16388 "int dsvvdvsdvvv = 123;", 16389 Alignment); 16390 verifyFormat("int i = 1, j = 10;\n" 16391 "something = 2000;", 16392 Alignment); 16393 verifyFormat("something = 2000;\n" 16394 "int i = 1, j = 10;\n", 16395 Alignment); 16396 verifyFormat("something = 2000;\n" 16397 "another = 911;\n" 16398 "int i = 1, j = 10;\n" 16399 "oneMore = 1;\n" 16400 "i = 2;", 16401 Alignment); 16402 verifyFormat("int a = 5;\n" 16403 "int one = 1;\n" 16404 "method();\n" 16405 "int oneTwoThree = 123;\n" 16406 "int oneTwo = 12;", 16407 Alignment); 16408 verifyFormat("int oneTwoThree = 123;\n" 16409 "int oneTwo = 12;\n" 16410 "method();\n", 16411 Alignment); 16412 verifyFormat("int oneTwoThree = 123; // comment\n" 16413 "int oneTwo = 12; // comment", 16414 Alignment); 16415 verifyFormat("int f() = default;\n" 16416 "int &operator() = default;\n" 16417 "int &operator=() {", 16418 Alignment); 16419 verifyFormat("int f() = delete;\n" 16420 "int &operator() = delete;\n" 16421 "int &operator=() {", 16422 Alignment); 16423 verifyFormat("int f() = default; // comment\n" 16424 "int &operator() = default; // comment\n" 16425 "int &operator=() {", 16426 Alignment); 16427 verifyFormat("int f() = default;\n" 16428 "int &operator() = default;\n" 16429 "int &operator==() {", 16430 Alignment); 16431 verifyFormat("int f() = default;\n" 16432 "int &operator() = default;\n" 16433 "int &operator<=() {", 16434 Alignment); 16435 verifyFormat("int f() = default;\n" 16436 "int &operator() = default;\n" 16437 "int &operator!=() {", 16438 Alignment); 16439 verifyFormat("int f() = default;\n" 16440 "int &operator() = default;\n" 16441 "int &operator=();", 16442 Alignment); 16443 verifyFormat("int f() = delete;\n" 16444 "int &operator() = delete;\n" 16445 "int &operator=();", 16446 Alignment); 16447 verifyFormat("/* long long padding */ int f() = default;\n" 16448 "int &operator() = default;\n" 16449 "int &operator/**/ =();", 16450 Alignment); 16451 // https://llvm.org/PR33697 16452 FormatStyle AlignmentWithPenalty = getLLVMStyle(); 16453 AlignmentWithPenalty.AlignConsecutiveAssignments = 16454 FormatStyle::ACS_Consecutive; 16455 AlignmentWithPenalty.PenaltyReturnTypeOnItsOwnLine = 5000; 16456 verifyFormat("class SSSSSSSSSSSSSSSSSSSSSSSSSSSS {\n" 16457 " void f() = delete;\n" 16458 " SSSSSSSSSSSSSSSSSSSSSSSSSSSS &operator=(\n" 16459 " const SSSSSSSSSSSSSSSSSSSSSSSSSSSS &other) = delete;\n" 16460 "};\n", 16461 AlignmentWithPenalty); 16462 16463 // Bug 25167 16464 /* Uncomment when fixed 16465 verifyFormat("#if A\n" 16466 "#else\n" 16467 "int aaaaaaaa = 12;\n" 16468 "#endif\n" 16469 "#if B\n" 16470 "#else\n" 16471 "int a = 12;\n" 16472 "#endif\n", 16473 Alignment); 16474 verifyFormat("enum foo {\n" 16475 "#if A\n" 16476 "#else\n" 16477 " aaaaaaaa = 12;\n" 16478 "#endif\n" 16479 "#if B\n" 16480 "#else\n" 16481 " a = 12;\n" 16482 "#endif\n" 16483 "};\n", 16484 Alignment); 16485 */ 16486 16487 EXPECT_EQ("int a = 5;\n" 16488 "\n" 16489 "int oneTwoThree = 123;", 16490 format("int a = 5;\n" 16491 "\n" 16492 "int oneTwoThree= 123;", 16493 Alignment)); 16494 EXPECT_EQ("int a = 5;\n" 16495 "int one = 1;\n" 16496 "\n" 16497 "int oneTwoThree = 123;", 16498 format("int a = 5;\n" 16499 "int one = 1;\n" 16500 "\n" 16501 "int oneTwoThree = 123;", 16502 Alignment)); 16503 EXPECT_EQ("int a = 5;\n" 16504 "int one = 1;\n" 16505 "\n" 16506 "int oneTwoThree = 123;\n" 16507 "int oneTwo = 12;", 16508 format("int a = 5;\n" 16509 "int one = 1;\n" 16510 "\n" 16511 "int oneTwoThree = 123;\n" 16512 "int oneTwo = 12;", 16513 Alignment)); 16514 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 16515 verifyFormat("#define A \\\n" 16516 " int aaaa = 12; \\\n" 16517 " int b = 23; \\\n" 16518 " int ccc = 234; \\\n" 16519 " int dddddddddd = 2345;", 16520 Alignment); 16521 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 16522 verifyFormat("#define A \\\n" 16523 " int aaaa = 12; \\\n" 16524 " int b = 23; \\\n" 16525 " int ccc = 234; \\\n" 16526 " int dddddddddd = 2345;", 16527 Alignment); 16528 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 16529 verifyFormat("#define A " 16530 " \\\n" 16531 " int aaaa = 12; " 16532 " \\\n" 16533 " int b = 23; " 16534 " \\\n" 16535 " int ccc = 234; " 16536 " \\\n" 16537 " int dddddddddd = 2345;", 16538 Alignment); 16539 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 16540 "k = 4, int l = 5,\n" 16541 " int m = 6) {\n" 16542 " int j = 10;\n" 16543 " otherThing = 1;\n" 16544 "}", 16545 Alignment); 16546 verifyFormat("void SomeFunction(int parameter = 0) {\n" 16547 " int i = 1;\n" 16548 " int j = 2;\n" 16549 " int big = 10000;\n" 16550 "}", 16551 Alignment); 16552 verifyFormat("class C {\n" 16553 "public:\n" 16554 " int i = 1;\n" 16555 " virtual void f() = 0;\n" 16556 "};", 16557 Alignment); 16558 verifyFormat("int i = 1;\n" 16559 "if (SomeType t = getSomething()) {\n" 16560 "}\n" 16561 "int j = 2;\n" 16562 "int big = 10000;", 16563 Alignment); 16564 verifyFormat("int j = 7;\n" 16565 "for (int k = 0; k < N; ++k) {\n" 16566 "}\n" 16567 "int j = 2;\n" 16568 "int big = 10000;\n" 16569 "}", 16570 Alignment); 16571 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 16572 verifyFormat("int i = 1;\n" 16573 "LooooooooooongType loooooooooooooooooooooongVariable\n" 16574 " = someLooooooooooooooooongFunction();\n" 16575 "int j = 2;", 16576 Alignment); 16577 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 16578 verifyFormat("int i = 1;\n" 16579 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 16580 " someLooooooooooooooooongFunction();\n" 16581 "int j = 2;", 16582 Alignment); 16583 16584 verifyFormat("auto lambda = []() {\n" 16585 " auto i = 0;\n" 16586 " return 0;\n" 16587 "};\n" 16588 "int i = 0;\n" 16589 "auto v = type{\n" 16590 " i = 1, //\n" 16591 " (i = 2), //\n" 16592 " i = 3 //\n" 16593 "};", 16594 Alignment); 16595 16596 verifyFormat( 16597 "int i = 1;\n" 16598 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 16599 " loooooooooooooooooooooongParameterB);\n" 16600 "int j = 2;", 16601 Alignment); 16602 16603 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n" 16604 " typename B = very_long_type_name_1,\n" 16605 " typename T_2 = very_long_type_name_2>\n" 16606 "auto foo() {}\n", 16607 Alignment); 16608 verifyFormat("int a, b = 1;\n" 16609 "int c = 2;\n" 16610 "int dd = 3;\n", 16611 Alignment); 16612 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 16613 "float b[1][] = {{3.f}};\n", 16614 Alignment); 16615 verifyFormat("for (int i = 0; i < 1; i++)\n" 16616 " int x = 1;\n", 16617 Alignment); 16618 verifyFormat("for (i = 0; i < 1; i++)\n" 16619 " x = 1;\n" 16620 "y = 1;\n", 16621 Alignment); 16622 16623 EXPECT_EQ(Alignment.ReflowComments, true); 16624 Alignment.ColumnLimit = 50; 16625 EXPECT_EQ("int x = 0;\n" 16626 "int yy = 1; /// specificlennospace\n" 16627 "int zzz = 2;\n", 16628 format("int x = 0;\n" 16629 "int yy = 1; ///specificlennospace\n" 16630 "int zzz = 2;\n", 16631 Alignment)); 16632 16633 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 16634 "auto b = [] {\n" 16635 " f();\n" 16636 " return;\n" 16637 "};", 16638 Alignment); 16639 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 16640 "auto b = g([] {\n" 16641 " f();\n" 16642 " return;\n" 16643 "});", 16644 Alignment); 16645 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 16646 "auto b = g(param, [] {\n" 16647 " f();\n" 16648 " return;\n" 16649 "});", 16650 Alignment); 16651 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 16652 "auto b = [] {\n" 16653 " if (condition) {\n" 16654 " return;\n" 16655 " }\n" 16656 "};", 16657 Alignment); 16658 16659 verifyFormat("auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 16660 " ccc ? aaaaa : bbbbb,\n" 16661 " dddddddddddddddddddddddddd);", 16662 Alignment); 16663 // FIXME: https://llvm.org/PR53497 16664 // verifyFormat("auto aaaaaaaaaaaa = f();\n" 16665 // "auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 16666 // " ccc ? aaaaa : bbbbb,\n" 16667 // " dddddddddddddddddddddddddd);", 16668 // Alignment); 16669 } 16670 16671 TEST_F(FormatTest, AlignConsecutiveBitFields) { 16672 FormatStyle Alignment = getLLVMStyle(); 16673 Alignment.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive; 16674 verifyFormat("int const a : 5;\n" 16675 "int oneTwoThree : 23;", 16676 Alignment); 16677 16678 // Initializers are allowed starting with c++2a 16679 verifyFormat("int const a : 5 = 1;\n" 16680 "int oneTwoThree : 23 = 0;", 16681 Alignment); 16682 16683 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 16684 verifyFormat("int const a : 5;\n" 16685 "int oneTwoThree : 23;", 16686 Alignment); 16687 16688 verifyFormat("int const a : 5; // comment\n" 16689 "int oneTwoThree : 23; // comment", 16690 Alignment); 16691 16692 verifyFormat("int const a : 5 = 1;\n" 16693 "int oneTwoThree : 23 = 0;", 16694 Alignment); 16695 16696 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 16697 verifyFormat("int const a : 5 = 1;\n" 16698 "int oneTwoThree : 23 = 0;", 16699 Alignment); 16700 verifyFormat("int const a : 5 = {1};\n" 16701 "int oneTwoThree : 23 = 0;", 16702 Alignment); 16703 16704 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None; 16705 verifyFormat("int const a :5;\n" 16706 "int oneTwoThree:23;", 16707 Alignment); 16708 16709 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before; 16710 verifyFormat("int const a :5;\n" 16711 "int oneTwoThree :23;", 16712 Alignment); 16713 16714 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After; 16715 verifyFormat("int const a : 5;\n" 16716 "int oneTwoThree: 23;", 16717 Alignment); 16718 16719 // Known limitations: ':' is only recognized as a bitfield colon when 16720 // followed by a number. 16721 /* 16722 verifyFormat("int oneTwoThree : SOME_CONSTANT;\n" 16723 "int a : 5;", 16724 Alignment); 16725 */ 16726 } 16727 16728 TEST_F(FormatTest, AlignConsecutiveDeclarations) { 16729 FormatStyle Alignment = getLLVMStyle(); 16730 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 16731 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_None; 16732 Alignment.PointerAlignment = FormatStyle::PAS_Right; 16733 verifyFormat("float const a = 5;\n" 16734 "int oneTwoThree = 123;", 16735 Alignment); 16736 verifyFormat("int a = 5;\n" 16737 "float const oneTwoThree = 123;", 16738 Alignment); 16739 16740 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 16741 verifyFormat("float const a = 5;\n" 16742 "int oneTwoThree = 123;", 16743 Alignment); 16744 verifyFormat("int a = method();\n" 16745 "float const oneTwoThree = 133;", 16746 Alignment); 16747 verifyFormat("int i = 1, j = 10;\n" 16748 "something = 2000;", 16749 Alignment); 16750 verifyFormat("something = 2000;\n" 16751 "int i = 1, j = 10;\n", 16752 Alignment); 16753 verifyFormat("float something = 2000;\n" 16754 "double another = 911;\n" 16755 "int i = 1, j = 10;\n" 16756 "const int *oneMore = 1;\n" 16757 "unsigned i = 2;", 16758 Alignment); 16759 verifyFormat("float a = 5;\n" 16760 "int one = 1;\n" 16761 "method();\n" 16762 "const double oneTwoThree = 123;\n" 16763 "const unsigned int oneTwo = 12;", 16764 Alignment); 16765 verifyFormat("int oneTwoThree{0}; // comment\n" 16766 "unsigned oneTwo; // comment", 16767 Alignment); 16768 verifyFormat("unsigned int *a;\n" 16769 "int *b;\n" 16770 "unsigned int Const *c;\n" 16771 "unsigned int const *d;\n" 16772 "unsigned int Const &e;\n" 16773 "unsigned int const &f;", 16774 Alignment); 16775 verifyFormat("Const unsigned int *c;\n" 16776 "const unsigned int *d;\n" 16777 "Const unsigned int &e;\n" 16778 "const unsigned int &f;\n" 16779 "const unsigned g;\n" 16780 "Const unsigned h;", 16781 Alignment); 16782 EXPECT_EQ("float const a = 5;\n" 16783 "\n" 16784 "int oneTwoThree = 123;", 16785 format("float const a = 5;\n" 16786 "\n" 16787 "int oneTwoThree= 123;", 16788 Alignment)); 16789 EXPECT_EQ("float a = 5;\n" 16790 "int one = 1;\n" 16791 "\n" 16792 "unsigned oneTwoThree = 123;", 16793 format("float a = 5;\n" 16794 "int one = 1;\n" 16795 "\n" 16796 "unsigned oneTwoThree = 123;", 16797 Alignment)); 16798 EXPECT_EQ("float a = 5;\n" 16799 "int one = 1;\n" 16800 "\n" 16801 "unsigned oneTwoThree = 123;\n" 16802 "int oneTwo = 12;", 16803 format("float a = 5;\n" 16804 "int one = 1;\n" 16805 "\n" 16806 "unsigned oneTwoThree = 123;\n" 16807 "int oneTwo = 12;", 16808 Alignment)); 16809 // Function prototype alignment 16810 verifyFormat("int a();\n" 16811 "double b();", 16812 Alignment); 16813 verifyFormat("int a(int x);\n" 16814 "double b();", 16815 Alignment); 16816 unsigned OldColumnLimit = Alignment.ColumnLimit; 16817 // We need to set ColumnLimit to zero, in order to stress nested alignments, 16818 // otherwise the function parameters will be re-flowed onto a single line. 16819 Alignment.ColumnLimit = 0; 16820 EXPECT_EQ("int a(int x,\n" 16821 " float y);\n" 16822 "double b(int x,\n" 16823 " double y);", 16824 format("int a(int x,\n" 16825 " float y);\n" 16826 "double b(int x,\n" 16827 " double y);", 16828 Alignment)); 16829 // This ensures that function parameters of function declarations are 16830 // correctly indented when their owning functions are indented. 16831 // The failure case here is for 'double y' to not be indented enough. 16832 EXPECT_EQ("double a(int x);\n" 16833 "int b(int y,\n" 16834 " double z);", 16835 format("double a(int x);\n" 16836 "int b(int y,\n" 16837 " double z);", 16838 Alignment)); 16839 // Set ColumnLimit low so that we induce wrapping immediately after 16840 // the function name and opening paren. 16841 Alignment.ColumnLimit = 13; 16842 verifyFormat("int function(\n" 16843 " int x,\n" 16844 " bool y);", 16845 Alignment); 16846 Alignment.ColumnLimit = OldColumnLimit; 16847 // Ensure function pointers don't screw up recursive alignment 16848 verifyFormat("int a(int x, void (*fp)(int y));\n" 16849 "double b();", 16850 Alignment); 16851 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 16852 // Ensure recursive alignment is broken by function braces, so that the 16853 // "a = 1" does not align with subsequent assignments inside the function 16854 // body. 16855 verifyFormat("int func(int a = 1) {\n" 16856 " int b = 2;\n" 16857 " int cc = 3;\n" 16858 "}", 16859 Alignment); 16860 verifyFormat("float something = 2000;\n" 16861 "double another = 911;\n" 16862 "int i = 1, j = 10;\n" 16863 "const int *oneMore = 1;\n" 16864 "unsigned i = 2;", 16865 Alignment); 16866 verifyFormat("int oneTwoThree = {0}; // comment\n" 16867 "unsigned oneTwo = 0; // comment", 16868 Alignment); 16869 // Make sure that scope is correctly tracked, in the absence of braces 16870 verifyFormat("for (int i = 0; i < n; i++)\n" 16871 " j = i;\n" 16872 "double x = 1;\n", 16873 Alignment); 16874 verifyFormat("if (int i = 0)\n" 16875 " j = i;\n" 16876 "double x = 1;\n", 16877 Alignment); 16878 // Ensure operator[] and operator() are comprehended 16879 verifyFormat("struct test {\n" 16880 " long long int foo();\n" 16881 " int operator[](int a);\n" 16882 " double bar();\n" 16883 "};\n", 16884 Alignment); 16885 verifyFormat("struct test {\n" 16886 " long long int foo();\n" 16887 " int operator()(int a);\n" 16888 " double bar();\n" 16889 "};\n", 16890 Alignment); 16891 // http://llvm.org/PR52914 16892 verifyFormat("char *a[] = {\"a\", // comment\n" 16893 " \"bb\"};\n" 16894 "int bbbbbbb = 0;", 16895 Alignment); 16896 16897 // PAS_Right 16898 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 16899 " int const i = 1;\n" 16900 " int *j = 2;\n" 16901 " int big = 10000;\n" 16902 "\n" 16903 " unsigned oneTwoThree = 123;\n" 16904 " int oneTwo = 12;\n" 16905 " method();\n" 16906 " float k = 2;\n" 16907 " int ll = 10000;\n" 16908 "}", 16909 format("void SomeFunction(int parameter= 0) {\n" 16910 " int const i= 1;\n" 16911 " int *j=2;\n" 16912 " int big = 10000;\n" 16913 "\n" 16914 "unsigned oneTwoThree =123;\n" 16915 "int oneTwo = 12;\n" 16916 " method();\n" 16917 "float k= 2;\n" 16918 "int ll=10000;\n" 16919 "}", 16920 Alignment)); 16921 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 16922 " int const i = 1;\n" 16923 " int **j = 2, ***k;\n" 16924 " int &k = i;\n" 16925 " int &&l = i + j;\n" 16926 " int big = 10000;\n" 16927 "\n" 16928 " unsigned oneTwoThree = 123;\n" 16929 " int oneTwo = 12;\n" 16930 " method();\n" 16931 " float k = 2;\n" 16932 " int ll = 10000;\n" 16933 "}", 16934 format("void SomeFunction(int parameter= 0) {\n" 16935 " int const i= 1;\n" 16936 " int **j=2,***k;\n" 16937 "int &k=i;\n" 16938 "int &&l=i+j;\n" 16939 " int big = 10000;\n" 16940 "\n" 16941 "unsigned oneTwoThree =123;\n" 16942 "int oneTwo = 12;\n" 16943 " method();\n" 16944 "float k= 2;\n" 16945 "int ll=10000;\n" 16946 "}", 16947 Alignment)); 16948 // variables are aligned at their name, pointers are at the right most 16949 // position 16950 verifyFormat("int *a;\n" 16951 "int **b;\n" 16952 "int ***c;\n" 16953 "int foobar;\n", 16954 Alignment); 16955 16956 // PAS_Left 16957 FormatStyle AlignmentLeft = Alignment; 16958 AlignmentLeft.PointerAlignment = FormatStyle::PAS_Left; 16959 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 16960 " int const i = 1;\n" 16961 " int* j = 2;\n" 16962 " int big = 10000;\n" 16963 "\n" 16964 " unsigned oneTwoThree = 123;\n" 16965 " int oneTwo = 12;\n" 16966 " method();\n" 16967 " float k = 2;\n" 16968 " int ll = 10000;\n" 16969 "}", 16970 format("void SomeFunction(int parameter= 0) {\n" 16971 " int const i= 1;\n" 16972 " int *j=2;\n" 16973 " int big = 10000;\n" 16974 "\n" 16975 "unsigned oneTwoThree =123;\n" 16976 "int oneTwo = 12;\n" 16977 " method();\n" 16978 "float k= 2;\n" 16979 "int ll=10000;\n" 16980 "}", 16981 AlignmentLeft)); 16982 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 16983 " int const i = 1;\n" 16984 " int** j = 2;\n" 16985 " int& k = i;\n" 16986 " int&& l = i + j;\n" 16987 " int big = 10000;\n" 16988 "\n" 16989 " unsigned oneTwoThree = 123;\n" 16990 " int oneTwo = 12;\n" 16991 " method();\n" 16992 " float k = 2;\n" 16993 " int ll = 10000;\n" 16994 "}", 16995 format("void SomeFunction(int parameter= 0) {\n" 16996 " int const i= 1;\n" 16997 " int **j=2;\n" 16998 "int &k=i;\n" 16999 "int &&l=i+j;\n" 17000 " int big = 10000;\n" 17001 "\n" 17002 "unsigned oneTwoThree =123;\n" 17003 "int oneTwo = 12;\n" 17004 " method();\n" 17005 "float k= 2;\n" 17006 "int ll=10000;\n" 17007 "}", 17008 AlignmentLeft)); 17009 // variables are aligned at their name, pointers are at the left most position 17010 verifyFormat("int* a;\n" 17011 "int** b;\n" 17012 "int*** c;\n" 17013 "int foobar;\n", 17014 AlignmentLeft); 17015 17016 // PAS_Middle 17017 FormatStyle AlignmentMiddle = Alignment; 17018 AlignmentMiddle.PointerAlignment = FormatStyle::PAS_Middle; 17019 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17020 " int const i = 1;\n" 17021 " int * j = 2;\n" 17022 " int big = 10000;\n" 17023 "\n" 17024 " unsigned oneTwoThree = 123;\n" 17025 " int oneTwo = 12;\n" 17026 " method();\n" 17027 " float k = 2;\n" 17028 " int ll = 10000;\n" 17029 "}", 17030 format("void SomeFunction(int parameter= 0) {\n" 17031 " int const i= 1;\n" 17032 " int *j=2;\n" 17033 " int big = 10000;\n" 17034 "\n" 17035 "unsigned oneTwoThree =123;\n" 17036 "int oneTwo = 12;\n" 17037 " method();\n" 17038 "float k= 2;\n" 17039 "int ll=10000;\n" 17040 "}", 17041 AlignmentMiddle)); 17042 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17043 " int const i = 1;\n" 17044 " int ** j = 2, ***k;\n" 17045 " int & k = i;\n" 17046 " int && l = i + j;\n" 17047 " int big = 10000;\n" 17048 "\n" 17049 " unsigned oneTwoThree = 123;\n" 17050 " int oneTwo = 12;\n" 17051 " method();\n" 17052 " float k = 2;\n" 17053 " int ll = 10000;\n" 17054 "}", 17055 format("void SomeFunction(int parameter= 0) {\n" 17056 " int const i= 1;\n" 17057 " int **j=2,***k;\n" 17058 "int &k=i;\n" 17059 "int &&l=i+j;\n" 17060 " int big = 10000;\n" 17061 "\n" 17062 "unsigned oneTwoThree =123;\n" 17063 "int oneTwo = 12;\n" 17064 " method();\n" 17065 "float k= 2;\n" 17066 "int ll=10000;\n" 17067 "}", 17068 AlignmentMiddle)); 17069 // variables are aligned at their name, pointers are in the middle 17070 verifyFormat("int * a;\n" 17071 "int * b;\n" 17072 "int *** c;\n" 17073 "int foobar;\n", 17074 AlignmentMiddle); 17075 17076 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 17077 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 17078 verifyFormat("#define A \\\n" 17079 " int aaaa = 12; \\\n" 17080 " float b = 23; \\\n" 17081 " const int ccc = 234; \\\n" 17082 " unsigned dddddddddd = 2345;", 17083 Alignment); 17084 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 17085 verifyFormat("#define A \\\n" 17086 " int aaaa = 12; \\\n" 17087 " float b = 23; \\\n" 17088 " const int ccc = 234; \\\n" 17089 " unsigned dddddddddd = 2345;", 17090 Alignment); 17091 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 17092 Alignment.ColumnLimit = 30; 17093 verifyFormat("#define A \\\n" 17094 " int aaaa = 12; \\\n" 17095 " float b = 23; \\\n" 17096 " const int ccc = 234; \\\n" 17097 " int dddddddddd = 2345;", 17098 Alignment); 17099 Alignment.ColumnLimit = 80; 17100 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 17101 "k = 4, int l = 5,\n" 17102 " int m = 6) {\n" 17103 " const int j = 10;\n" 17104 " otherThing = 1;\n" 17105 "}", 17106 Alignment); 17107 verifyFormat("void SomeFunction(int parameter = 0) {\n" 17108 " int const i = 1;\n" 17109 " int *j = 2;\n" 17110 " int big = 10000;\n" 17111 "}", 17112 Alignment); 17113 verifyFormat("class C {\n" 17114 "public:\n" 17115 " int i = 1;\n" 17116 " virtual void f() = 0;\n" 17117 "};", 17118 Alignment); 17119 verifyFormat("float i = 1;\n" 17120 "if (SomeType t = getSomething()) {\n" 17121 "}\n" 17122 "const unsigned j = 2;\n" 17123 "int big = 10000;", 17124 Alignment); 17125 verifyFormat("float j = 7;\n" 17126 "for (int k = 0; k < N; ++k) {\n" 17127 "}\n" 17128 "unsigned j = 2;\n" 17129 "int big = 10000;\n" 17130 "}", 17131 Alignment); 17132 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 17133 verifyFormat("float i = 1;\n" 17134 "LooooooooooongType loooooooooooooooooooooongVariable\n" 17135 " = someLooooooooooooooooongFunction();\n" 17136 "int j = 2;", 17137 Alignment); 17138 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 17139 verifyFormat("int i = 1;\n" 17140 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 17141 " someLooooooooooooooooongFunction();\n" 17142 "int j = 2;", 17143 Alignment); 17144 17145 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17146 verifyFormat("auto lambda = []() {\n" 17147 " auto ii = 0;\n" 17148 " float j = 0;\n" 17149 " return 0;\n" 17150 "};\n" 17151 "int i = 0;\n" 17152 "float i2 = 0;\n" 17153 "auto v = type{\n" 17154 " i = 1, //\n" 17155 " (i = 2), //\n" 17156 " i = 3 //\n" 17157 "};", 17158 Alignment); 17159 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 17160 17161 verifyFormat( 17162 "int i = 1;\n" 17163 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 17164 " loooooooooooooooooooooongParameterB);\n" 17165 "int j = 2;", 17166 Alignment); 17167 17168 // Test interactions with ColumnLimit and AlignConsecutiveAssignments: 17169 // We expect declarations and assignments to align, as long as it doesn't 17170 // exceed the column limit, starting a new alignment sequence whenever it 17171 // happens. 17172 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17173 Alignment.ColumnLimit = 30; 17174 verifyFormat("float ii = 1;\n" 17175 "unsigned j = 2;\n" 17176 "int someVerylongVariable = 1;\n" 17177 "AnotherLongType ll = 123456;\n" 17178 "VeryVeryLongType k = 2;\n" 17179 "int myvar = 1;", 17180 Alignment); 17181 Alignment.ColumnLimit = 80; 17182 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 17183 17184 verifyFormat( 17185 "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n" 17186 " typename LongType, typename B>\n" 17187 "auto foo() {}\n", 17188 Alignment); 17189 verifyFormat("float a, b = 1;\n" 17190 "int c = 2;\n" 17191 "int dd = 3;\n", 17192 Alignment); 17193 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17194 "float b[1][] = {{3.f}};\n", 17195 Alignment); 17196 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17197 verifyFormat("float a, b = 1;\n" 17198 "int c = 2;\n" 17199 "int dd = 3;\n", 17200 Alignment); 17201 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17202 "float b[1][] = {{3.f}};\n", 17203 Alignment); 17204 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 17205 17206 Alignment.ColumnLimit = 30; 17207 Alignment.BinPackParameters = false; 17208 verifyFormat("void foo(float a,\n" 17209 " float b,\n" 17210 " int c,\n" 17211 " uint32_t *d) {\n" 17212 " int *e = 0;\n" 17213 " float f = 0;\n" 17214 " double g = 0;\n" 17215 "}\n" 17216 "void bar(ino_t a,\n" 17217 " int b,\n" 17218 " uint32_t *c,\n" 17219 " bool d) {}\n", 17220 Alignment); 17221 Alignment.BinPackParameters = true; 17222 Alignment.ColumnLimit = 80; 17223 17224 // Bug 33507 17225 Alignment.PointerAlignment = FormatStyle::PAS_Middle; 17226 verifyFormat( 17227 "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n" 17228 " static const Version verVs2017;\n" 17229 " return true;\n" 17230 "});\n", 17231 Alignment); 17232 Alignment.PointerAlignment = FormatStyle::PAS_Right; 17233 17234 // See llvm.org/PR35641 17235 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17236 verifyFormat("int func() { //\n" 17237 " int b;\n" 17238 " unsigned c;\n" 17239 "}", 17240 Alignment); 17241 17242 // See PR37175 17243 FormatStyle Style = getMozillaStyle(); 17244 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17245 EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n" 17246 "foo(int a);", 17247 format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style)); 17248 17249 Alignment.PointerAlignment = FormatStyle::PAS_Left; 17250 verifyFormat("unsigned int* a;\n" 17251 "int* b;\n" 17252 "unsigned int Const* c;\n" 17253 "unsigned int const* d;\n" 17254 "unsigned int Const& e;\n" 17255 "unsigned int const& f;", 17256 Alignment); 17257 verifyFormat("Const unsigned int* c;\n" 17258 "const unsigned int* d;\n" 17259 "Const unsigned int& e;\n" 17260 "const unsigned int& f;\n" 17261 "const unsigned g;\n" 17262 "Const unsigned h;", 17263 Alignment); 17264 17265 Alignment.PointerAlignment = FormatStyle::PAS_Middle; 17266 verifyFormat("unsigned int * a;\n" 17267 "int * b;\n" 17268 "unsigned int Const * c;\n" 17269 "unsigned int const * d;\n" 17270 "unsigned int Const & e;\n" 17271 "unsigned int const & f;", 17272 Alignment); 17273 verifyFormat("Const unsigned int * c;\n" 17274 "const unsigned int * d;\n" 17275 "Const unsigned int & e;\n" 17276 "const unsigned int & f;\n" 17277 "const unsigned g;\n" 17278 "Const unsigned h;", 17279 Alignment); 17280 } 17281 17282 TEST_F(FormatTest, AlignWithLineBreaks) { 17283 auto Style = getLLVMStyleWithColumns(120); 17284 17285 EXPECT_EQ(Style.AlignConsecutiveAssignments, FormatStyle::ACS_None); 17286 EXPECT_EQ(Style.AlignConsecutiveDeclarations, FormatStyle::ACS_None); 17287 verifyFormat("void foo() {\n" 17288 " int myVar = 5;\n" 17289 " double x = 3.14;\n" 17290 " auto str = \"Hello \"\n" 17291 " \"World\";\n" 17292 " auto s = \"Hello \"\n" 17293 " \"Again\";\n" 17294 "}", 17295 Style); 17296 17297 // clang-format off 17298 verifyFormat("void foo() {\n" 17299 " const int capacityBefore = Entries.capacity();\n" 17300 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17301 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17302 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17303 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17304 "}", 17305 Style); 17306 // clang-format on 17307 17308 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17309 verifyFormat("void foo() {\n" 17310 " int myVar = 5;\n" 17311 " double x = 3.14;\n" 17312 " auto str = \"Hello \"\n" 17313 " \"World\";\n" 17314 " auto s = \"Hello \"\n" 17315 " \"Again\";\n" 17316 "}", 17317 Style); 17318 17319 // clang-format off 17320 verifyFormat("void foo() {\n" 17321 " const int capacityBefore = Entries.capacity();\n" 17322 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17323 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17324 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17325 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17326 "}", 17327 Style); 17328 // clang-format on 17329 17330 Style.AlignConsecutiveAssignments = FormatStyle::ACS_None; 17331 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17332 verifyFormat("void foo() {\n" 17333 " int myVar = 5;\n" 17334 " double x = 3.14;\n" 17335 " auto str = \"Hello \"\n" 17336 " \"World\";\n" 17337 " auto s = \"Hello \"\n" 17338 " \"Again\";\n" 17339 "}", 17340 Style); 17341 17342 // clang-format off 17343 verifyFormat("void foo() {\n" 17344 " const int capacityBefore = Entries.capacity();\n" 17345 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17346 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17347 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17348 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17349 "}", 17350 Style); 17351 // clang-format on 17352 17353 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17354 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17355 17356 verifyFormat("void foo() {\n" 17357 " int myVar = 5;\n" 17358 " double x = 3.14;\n" 17359 " auto str = \"Hello \"\n" 17360 " \"World\";\n" 17361 " auto s = \"Hello \"\n" 17362 " \"Again\";\n" 17363 "}", 17364 Style); 17365 17366 // clang-format off 17367 verifyFormat("void foo() {\n" 17368 " const int capacityBefore = Entries.capacity();\n" 17369 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17370 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17371 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17372 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17373 "}", 17374 Style); 17375 // clang-format on 17376 17377 Style = getLLVMStyleWithColumns(120); 17378 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17379 Style.ContinuationIndentWidth = 4; 17380 Style.IndentWidth = 4; 17381 17382 // clang-format off 17383 verifyFormat("void SomeFunc() {\n" 17384 " newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 17385 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17386 " newWatcher.maxAge = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 17387 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17388 " newWatcher.max = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 17389 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17390 "}", 17391 Style); 17392 // clang-format on 17393 17394 Style.BinPackArguments = false; 17395 17396 // clang-format off 17397 verifyFormat("void SomeFunc() {\n" 17398 " newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(\n" 17399 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17400 " newWatcher.maxAge = ToLegacyTimestamp(GetMaxAge(\n" 17401 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17402 " newWatcher.max = ToLegacyTimestamp(GetMaxAge(\n" 17403 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17404 "}", 17405 Style); 17406 // clang-format on 17407 } 17408 17409 TEST_F(FormatTest, AlignWithInitializerPeriods) { 17410 auto Style = getLLVMStyleWithColumns(60); 17411 17412 verifyFormat("void foo1(void) {\n" 17413 " BYTE p[1] = 1;\n" 17414 " A B = {.one_foooooooooooooooo = 2,\n" 17415 " .two_fooooooooooooo = 3,\n" 17416 " .three_fooooooooooooo = 4};\n" 17417 " BYTE payload = 2;\n" 17418 "}", 17419 Style); 17420 17421 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17422 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_None; 17423 verifyFormat("void foo2(void) {\n" 17424 " BYTE p[1] = 1;\n" 17425 " A B = {.one_foooooooooooooooo = 2,\n" 17426 " .two_fooooooooooooo = 3,\n" 17427 " .three_fooooooooooooo = 4};\n" 17428 " BYTE payload = 2;\n" 17429 "}", 17430 Style); 17431 17432 Style.AlignConsecutiveAssignments = FormatStyle::ACS_None; 17433 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17434 verifyFormat("void foo3(void) {\n" 17435 " BYTE p[1] = 1;\n" 17436 " A B = {.one_foooooooooooooooo = 2,\n" 17437 " .two_fooooooooooooo = 3,\n" 17438 " .three_fooooooooooooo = 4};\n" 17439 " BYTE payload = 2;\n" 17440 "}", 17441 Style); 17442 17443 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17444 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17445 verifyFormat("void foo4(void) {\n" 17446 " BYTE p[1] = 1;\n" 17447 " A B = {.one_foooooooooooooooo = 2,\n" 17448 " .two_fooooooooooooo = 3,\n" 17449 " .three_fooooooooooooo = 4};\n" 17450 " BYTE payload = 2;\n" 17451 "}", 17452 Style); 17453 } 17454 17455 TEST_F(FormatTest, LinuxBraceBreaking) { 17456 FormatStyle LinuxBraceStyle = getLLVMStyle(); 17457 LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux; 17458 verifyFormat("namespace a\n" 17459 "{\n" 17460 "class A\n" 17461 "{\n" 17462 " void f()\n" 17463 " {\n" 17464 " if (true) {\n" 17465 " a();\n" 17466 " b();\n" 17467 " } else {\n" 17468 " a();\n" 17469 " }\n" 17470 " }\n" 17471 " void g() { return; }\n" 17472 "};\n" 17473 "struct B {\n" 17474 " int x;\n" 17475 "};\n" 17476 "} // namespace a\n", 17477 LinuxBraceStyle); 17478 verifyFormat("enum X {\n" 17479 " Y = 0,\n" 17480 "}\n", 17481 LinuxBraceStyle); 17482 verifyFormat("struct S {\n" 17483 " int Type;\n" 17484 " union {\n" 17485 " int x;\n" 17486 " double y;\n" 17487 " } Value;\n" 17488 " class C\n" 17489 " {\n" 17490 " MyFavoriteType Value;\n" 17491 " } Class;\n" 17492 "}\n", 17493 LinuxBraceStyle); 17494 } 17495 17496 TEST_F(FormatTest, MozillaBraceBreaking) { 17497 FormatStyle MozillaBraceStyle = getLLVMStyle(); 17498 MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla; 17499 MozillaBraceStyle.FixNamespaceComments = false; 17500 verifyFormat("namespace a {\n" 17501 "class A\n" 17502 "{\n" 17503 " void f()\n" 17504 " {\n" 17505 " if (true) {\n" 17506 " a();\n" 17507 " b();\n" 17508 " }\n" 17509 " }\n" 17510 " void g() { return; }\n" 17511 "};\n" 17512 "enum E\n" 17513 "{\n" 17514 " A,\n" 17515 " // foo\n" 17516 " B,\n" 17517 " C\n" 17518 "};\n" 17519 "struct B\n" 17520 "{\n" 17521 " int x;\n" 17522 "};\n" 17523 "}\n", 17524 MozillaBraceStyle); 17525 verifyFormat("struct S\n" 17526 "{\n" 17527 " int Type;\n" 17528 " union\n" 17529 " {\n" 17530 " int x;\n" 17531 " double y;\n" 17532 " } Value;\n" 17533 " class C\n" 17534 " {\n" 17535 " MyFavoriteType Value;\n" 17536 " } Class;\n" 17537 "}\n", 17538 MozillaBraceStyle); 17539 } 17540 17541 TEST_F(FormatTest, StroustrupBraceBreaking) { 17542 FormatStyle StroustrupBraceStyle = getLLVMStyle(); 17543 StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 17544 verifyFormat("namespace a {\n" 17545 "class A {\n" 17546 " void f()\n" 17547 " {\n" 17548 " if (true) {\n" 17549 " a();\n" 17550 " b();\n" 17551 " }\n" 17552 " }\n" 17553 " void g() { return; }\n" 17554 "};\n" 17555 "struct B {\n" 17556 " int x;\n" 17557 "};\n" 17558 "} // namespace a\n", 17559 StroustrupBraceStyle); 17560 17561 verifyFormat("void foo()\n" 17562 "{\n" 17563 " if (a) {\n" 17564 " a();\n" 17565 " }\n" 17566 " else {\n" 17567 " b();\n" 17568 " }\n" 17569 "}\n", 17570 StroustrupBraceStyle); 17571 17572 verifyFormat("#ifdef _DEBUG\n" 17573 "int foo(int i = 0)\n" 17574 "#else\n" 17575 "int foo(int i = 5)\n" 17576 "#endif\n" 17577 "{\n" 17578 " return i;\n" 17579 "}", 17580 StroustrupBraceStyle); 17581 17582 verifyFormat("void foo() {}\n" 17583 "void bar()\n" 17584 "#ifdef _DEBUG\n" 17585 "{\n" 17586 " foo();\n" 17587 "}\n" 17588 "#else\n" 17589 "{\n" 17590 "}\n" 17591 "#endif", 17592 StroustrupBraceStyle); 17593 17594 verifyFormat("void foobar() { int i = 5; }\n" 17595 "#ifdef _DEBUG\n" 17596 "void bar() {}\n" 17597 "#else\n" 17598 "void bar() { foobar(); }\n" 17599 "#endif", 17600 StroustrupBraceStyle); 17601 } 17602 17603 TEST_F(FormatTest, AllmanBraceBreaking) { 17604 FormatStyle AllmanBraceStyle = getLLVMStyle(); 17605 AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman; 17606 17607 EXPECT_EQ("namespace a\n" 17608 "{\n" 17609 "void f();\n" 17610 "void g();\n" 17611 "} // namespace a\n", 17612 format("namespace a\n" 17613 "{\n" 17614 "void f();\n" 17615 "void g();\n" 17616 "}\n", 17617 AllmanBraceStyle)); 17618 17619 verifyFormat("namespace a\n" 17620 "{\n" 17621 "class A\n" 17622 "{\n" 17623 " void f()\n" 17624 " {\n" 17625 " if (true)\n" 17626 " {\n" 17627 " a();\n" 17628 " b();\n" 17629 " }\n" 17630 " }\n" 17631 " void g() { return; }\n" 17632 "};\n" 17633 "struct B\n" 17634 "{\n" 17635 " int x;\n" 17636 "};\n" 17637 "union C\n" 17638 "{\n" 17639 "};\n" 17640 "} // namespace a", 17641 AllmanBraceStyle); 17642 17643 verifyFormat("void f()\n" 17644 "{\n" 17645 " if (true)\n" 17646 " {\n" 17647 " a();\n" 17648 " }\n" 17649 " else if (false)\n" 17650 " {\n" 17651 " b();\n" 17652 " }\n" 17653 " else\n" 17654 " {\n" 17655 " c();\n" 17656 " }\n" 17657 "}\n", 17658 AllmanBraceStyle); 17659 17660 verifyFormat("void f()\n" 17661 "{\n" 17662 " for (int i = 0; i < 10; ++i)\n" 17663 " {\n" 17664 " a();\n" 17665 " }\n" 17666 " while (false)\n" 17667 " {\n" 17668 " b();\n" 17669 " }\n" 17670 " do\n" 17671 " {\n" 17672 " c();\n" 17673 " } while (false)\n" 17674 "}\n", 17675 AllmanBraceStyle); 17676 17677 verifyFormat("void f(int a)\n" 17678 "{\n" 17679 " switch (a)\n" 17680 " {\n" 17681 " case 0:\n" 17682 " break;\n" 17683 " case 1:\n" 17684 " {\n" 17685 " break;\n" 17686 " }\n" 17687 " case 2:\n" 17688 " {\n" 17689 " }\n" 17690 " break;\n" 17691 " default:\n" 17692 " break;\n" 17693 " }\n" 17694 "}\n", 17695 AllmanBraceStyle); 17696 17697 verifyFormat("enum X\n" 17698 "{\n" 17699 " Y = 0,\n" 17700 "}\n", 17701 AllmanBraceStyle); 17702 verifyFormat("enum X\n" 17703 "{\n" 17704 " Y = 0\n" 17705 "}\n", 17706 AllmanBraceStyle); 17707 17708 verifyFormat("@interface BSApplicationController ()\n" 17709 "{\n" 17710 "@private\n" 17711 " id _extraIvar;\n" 17712 "}\n" 17713 "@end\n", 17714 AllmanBraceStyle); 17715 17716 verifyFormat("#ifdef _DEBUG\n" 17717 "int foo(int i = 0)\n" 17718 "#else\n" 17719 "int foo(int i = 5)\n" 17720 "#endif\n" 17721 "{\n" 17722 " return i;\n" 17723 "}", 17724 AllmanBraceStyle); 17725 17726 verifyFormat("void foo() {}\n" 17727 "void bar()\n" 17728 "#ifdef _DEBUG\n" 17729 "{\n" 17730 " foo();\n" 17731 "}\n" 17732 "#else\n" 17733 "{\n" 17734 "}\n" 17735 "#endif", 17736 AllmanBraceStyle); 17737 17738 verifyFormat("void foobar() { int i = 5; }\n" 17739 "#ifdef _DEBUG\n" 17740 "void bar() {}\n" 17741 "#else\n" 17742 "void bar() { foobar(); }\n" 17743 "#endif", 17744 AllmanBraceStyle); 17745 17746 EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine, 17747 FormatStyle::SLS_All); 17748 17749 verifyFormat("[](int i) { return i + 2; };\n" 17750 "[](int i, int j)\n" 17751 "{\n" 17752 " auto x = i + j;\n" 17753 " auto y = i * j;\n" 17754 " return x ^ y;\n" 17755 "};\n" 17756 "void foo()\n" 17757 "{\n" 17758 " auto shortLambda = [](int i) { return i + 2; };\n" 17759 " auto longLambda = [](int i, int j)\n" 17760 " {\n" 17761 " auto x = i + j;\n" 17762 " auto y = i * j;\n" 17763 " return x ^ y;\n" 17764 " };\n" 17765 "}", 17766 AllmanBraceStyle); 17767 17768 AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 17769 17770 verifyFormat("[](int i)\n" 17771 "{\n" 17772 " return i + 2;\n" 17773 "};\n" 17774 "[](int i, int j)\n" 17775 "{\n" 17776 " auto x = i + j;\n" 17777 " auto y = i * j;\n" 17778 " return x ^ y;\n" 17779 "};\n" 17780 "void foo()\n" 17781 "{\n" 17782 " auto shortLambda = [](int i)\n" 17783 " {\n" 17784 " return i + 2;\n" 17785 " };\n" 17786 " auto longLambda = [](int i, int j)\n" 17787 " {\n" 17788 " auto x = i + j;\n" 17789 " auto y = i * j;\n" 17790 " return x ^ y;\n" 17791 " };\n" 17792 "}", 17793 AllmanBraceStyle); 17794 17795 // Reset 17796 AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All; 17797 17798 // This shouldn't affect ObjC blocks.. 17799 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n" 17800 " // ...\n" 17801 " int i;\n" 17802 "}];", 17803 AllmanBraceStyle); 17804 verifyFormat("void (^block)(void) = ^{\n" 17805 " // ...\n" 17806 " int i;\n" 17807 "};", 17808 AllmanBraceStyle); 17809 // .. or dict literals. 17810 verifyFormat("void f()\n" 17811 "{\n" 17812 " // ...\n" 17813 " [object someMethod:@{@\"a\" : @\"b\"}];\n" 17814 "}", 17815 AllmanBraceStyle); 17816 verifyFormat("void f()\n" 17817 "{\n" 17818 " // ...\n" 17819 " [object someMethod:@{a : @\"b\"}];\n" 17820 "}", 17821 AllmanBraceStyle); 17822 verifyFormat("int f()\n" 17823 "{ // comment\n" 17824 " return 42;\n" 17825 "}", 17826 AllmanBraceStyle); 17827 17828 AllmanBraceStyle.ColumnLimit = 19; 17829 verifyFormat("void f() { int i; }", AllmanBraceStyle); 17830 AllmanBraceStyle.ColumnLimit = 18; 17831 verifyFormat("void f()\n" 17832 "{\n" 17833 " int i;\n" 17834 "}", 17835 AllmanBraceStyle); 17836 AllmanBraceStyle.ColumnLimit = 80; 17837 17838 FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle; 17839 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = 17840 FormatStyle::SIS_WithoutElse; 17841 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true; 17842 verifyFormat("void f(bool b)\n" 17843 "{\n" 17844 " if (b)\n" 17845 " {\n" 17846 " return;\n" 17847 " }\n" 17848 "}\n", 17849 BreakBeforeBraceShortIfs); 17850 verifyFormat("void f(bool b)\n" 17851 "{\n" 17852 " if constexpr (b)\n" 17853 " {\n" 17854 " return;\n" 17855 " }\n" 17856 "}\n", 17857 BreakBeforeBraceShortIfs); 17858 verifyFormat("void f(bool b)\n" 17859 "{\n" 17860 " if CONSTEXPR (b)\n" 17861 " {\n" 17862 " return;\n" 17863 " }\n" 17864 "}\n", 17865 BreakBeforeBraceShortIfs); 17866 verifyFormat("void f(bool b)\n" 17867 "{\n" 17868 " if (b) return;\n" 17869 "}\n", 17870 BreakBeforeBraceShortIfs); 17871 verifyFormat("void f(bool b)\n" 17872 "{\n" 17873 " if constexpr (b) return;\n" 17874 "}\n", 17875 BreakBeforeBraceShortIfs); 17876 verifyFormat("void f(bool b)\n" 17877 "{\n" 17878 " if CONSTEXPR (b) return;\n" 17879 "}\n", 17880 BreakBeforeBraceShortIfs); 17881 verifyFormat("void f(bool b)\n" 17882 "{\n" 17883 " while (b)\n" 17884 " {\n" 17885 " return;\n" 17886 " }\n" 17887 "}\n", 17888 BreakBeforeBraceShortIfs); 17889 } 17890 17891 TEST_F(FormatTest, WhitesmithsBraceBreaking) { 17892 FormatStyle WhitesmithsBraceStyle = getLLVMStyleWithColumns(0); 17893 WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 17894 17895 // Make a few changes to the style for testing purposes 17896 WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine = 17897 FormatStyle::SFS_Empty; 17898 WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 17899 17900 // FIXME: this test case can't decide whether there should be a blank line 17901 // after the ~D() line or not. It adds one if one doesn't exist in the test 17902 // and it removes the line if one exists. 17903 /* 17904 verifyFormat("class A;\n" 17905 "namespace B\n" 17906 " {\n" 17907 "class C;\n" 17908 "// Comment\n" 17909 "class D\n" 17910 " {\n" 17911 "public:\n" 17912 " D();\n" 17913 " ~D() {}\n" 17914 "private:\n" 17915 " enum E\n" 17916 " {\n" 17917 " F\n" 17918 " }\n" 17919 " };\n" 17920 " } // namespace B\n", 17921 WhitesmithsBraceStyle); 17922 */ 17923 17924 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None; 17925 verifyFormat("namespace a\n" 17926 " {\n" 17927 "class A\n" 17928 " {\n" 17929 " void f()\n" 17930 " {\n" 17931 " if (true)\n" 17932 " {\n" 17933 " a();\n" 17934 " b();\n" 17935 " }\n" 17936 " }\n" 17937 " void g()\n" 17938 " {\n" 17939 " return;\n" 17940 " }\n" 17941 " };\n" 17942 "struct B\n" 17943 " {\n" 17944 " int x;\n" 17945 " };\n" 17946 " } // namespace a", 17947 WhitesmithsBraceStyle); 17948 17949 verifyFormat("namespace a\n" 17950 " {\n" 17951 "namespace b\n" 17952 " {\n" 17953 "class A\n" 17954 " {\n" 17955 " void f()\n" 17956 " {\n" 17957 " if (true)\n" 17958 " {\n" 17959 " a();\n" 17960 " b();\n" 17961 " }\n" 17962 " }\n" 17963 " void g()\n" 17964 " {\n" 17965 " return;\n" 17966 " }\n" 17967 " };\n" 17968 "struct B\n" 17969 " {\n" 17970 " int x;\n" 17971 " };\n" 17972 " } // namespace b\n" 17973 " } // namespace a", 17974 WhitesmithsBraceStyle); 17975 17976 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner; 17977 verifyFormat("namespace a\n" 17978 " {\n" 17979 "namespace b\n" 17980 " {\n" 17981 " class A\n" 17982 " {\n" 17983 " void f()\n" 17984 " {\n" 17985 " if (true)\n" 17986 " {\n" 17987 " a();\n" 17988 " b();\n" 17989 " }\n" 17990 " }\n" 17991 " void g()\n" 17992 " {\n" 17993 " return;\n" 17994 " }\n" 17995 " };\n" 17996 " struct B\n" 17997 " {\n" 17998 " int x;\n" 17999 " };\n" 18000 " } // namespace b\n" 18001 " } // namespace a", 18002 WhitesmithsBraceStyle); 18003 18004 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All; 18005 verifyFormat("namespace a\n" 18006 " {\n" 18007 " namespace b\n" 18008 " {\n" 18009 " class A\n" 18010 " {\n" 18011 " void f()\n" 18012 " {\n" 18013 " if (true)\n" 18014 " {\n" 18015 " a();\n" 18016 " b();\n" 18017 " }\n" 18018 " }\n" 18019 " void g()\n" 18020 " {\n" 18021 " return;\n" 18022 " }\n" 18023 " };\n" 18024 " struct B\n" 18025 " {\n" 18026 " int x;\n" 18027 " };\n" 18028 " } // namespace b\n" 18029 " } // namespace a", 18030 WhitesmithsBraceStyle); 18031 18032 verifyFormat("void f()\n" 18033 " {\n" 18034 " if (true)\n" 18035 " {\n" 18036 " a();\n" 18037 " }\n" 18038 " else if (false)\n" 18039 " {\n" 18040 " b();\n" 18041 " }\n" 18042 " else\n" 18043 " {\n" 18044 " c();\n" 18045 " }\n" 18046 " }\n", 18047 WhitesmithsBraceStyle); 18048 18049 verifyFormat("void f()\n" 18050 " {\n" 18051 " for (int i = 0; i < 10; ++i)\n" 18052 " {\n" 18053 " a();\n" 18054 " }\n" 18055 " while (false)\n" 18056 " {\n" 18057 " b();\n" 18058 " }\n" 18059 " do\n" 18060 " {\n" 18061 " c();\n" 18062 " } while (false)\n" 18063 " }\n", 18064 WhitesmithsBraceStyle); 18065 18066 WhitesmithsBraceStyle.IndentCaseLabels = true; 18067 verifyFormat("void switchTest1(int a)\n" 18068 " {\n" 18069 " switch (a)\n" 18070 " {\n" 18071 " case 2:\n" 18072 " {\n" 18073 " }\n" 18074 " break;\n" 18075 " }\n" 18076 " }\n", 18077 WhitesmithsBraceStyle); 18078 18079 verifyFormat("void switchTest2(int a)\n" 18080 " {\n" 18081 " switch (a)\n" 18082 " {\n" 18083 " case 0:\n" 18084 " break;\n" 18085 " case 1:\n" 18086 " {\n" 18087 " break;\n" 18088 " }\n" 18089 " case 2:\n" 18090 " {\n" 18091 " }\n" 18092 " break;\n" 18093 " default:\n" 18094 " break;\n" 18095 " }\n" 18096 " }\n", 18097 WhitesmithsBraceStyle); 18098 18099 verifyFormat("void switchTest3(int a)\n" 18100 " {\n" 18101 " switch (a)\n" 18102 " {\n" 18103 " case 0:\n" 18104 " {\n" 18105 " foo(x);\n" 18106 " }\n" 18107 " break;\n" 18108 " default:\n" 18109 " {\n" 18110 " foo(1);\n" 18111 " }\n" 18112 " break;\n" 18113 " }\n" 18114 " }\n", 18115 WhitesmithsBraceStyle); 18116 18117 WhitesmithsBraceStyle.IndentCaseLabels = false; 18118 18119 verifyFormat("void switchTest4(int a)\n" 18120 " {\n" 18121 " switch (a)\n" 18122 " {\n" 18123 " case 2:\n" 18124 " {\n" 18125 " }\n" 18126 " break;\n" 18127 " }\n" 18128 " }\n", 18129 WhitesmithsBraceStyle); 18130 18131 verifyFormat("void switchTest5(int a)\n" 18132 " {\n" 18133 " switch (a)\n" 18134 " {\n" 18135 " case 0:\n" 18136 " break;\n" 18137 " case 1:\n" 18138 " {\n" 18139 " foo();\n" 18140 " break;\n" 18141 " }\n" 18142 " case 2:\n" 18143 " {\n" 18144 " }\n" 18145 " break;\n" 18146 " default:\n" 18147 " break;\n" 18148 " }\n" 18149 " }\n", 18150 WhitesmithsBraceStyle); 18151 18152 verifyFormat("void switchTest6(int a)\n" 18153 " {\n" 18154 " switch (a)\n" 18155 " {\n" 18156 " case 0:\n" 18157 " {\n" 18158 " foo(x);\n" 18159 " }\n" 18160 " break;\n" 18161 " default:\n" 18162 " {\n" 18163 " foo(1);\n" 18164 " }\n" 18165 " break;\n" 18166 " }\n" 18167 " }\n", 18168 WhitesmithsBraceStyle); 18169 18170 verifyFormat("enum X\n" 18171 " {\n" 18172 " Y = 0, // testing\n" 18173 " }\n", 18174 WhitesmithsBraceStyle); 18175 18176 verifyFormat("enum X\n" 18177 " {\n" 18178 " Y = 0\n" 18179 " }\n", 18180 WhitesmithsBraceStyle); 18181 verifyFormat("enum X\n" 18182 " {\n" 18183 " Y = 0,\n" 18184 " Z = 1\n" 18185 " };\n", 18186 WhitesmithsBraceStyle); 18187 18188 verifyFormat("@interface BSApplicationController ()\n" 18189 " {\n" 18190 "@private\n" 18191 " id _extraIvar;\n" 18192 " }\n" 18193 "@end\n", 18194 WhitesmithsBraceStyle); 18195 18196 verifyFormat("#ifdef _DEBUG\n" 18197 "int foo(int i = 0)\n" 18198 "#else\n" 18199 "int foo(int i = 5)\n" 18200 "#endif\n" 18201 " {\n" 18202 " return i;\n" 18203 " }", 18204 WhitesmithsBraceStyle); 18205 18206 verifyFormat("void foo() {}\n" 18207 "void bar()\n" 18208 "#ifdef _DEBUG\n" 18209 " {\n" 18210 " foo();\n" 18211 " }\n" 18212 "#else\n" 18213 " {\n" 18214 " }\n" 18215 "#endif", 18216 WhitesmithsBraceStyle); 18217 18218 verifyFormat("void foobar()\n" 18219 " {\n" 18220 " int i = 5;\n" 18221 " }\n" 18222 "#ifdef _DEBUG\n" 18223 "void bar()\n" 18224 " {\n" 18225 " }\n" 18226 "#else\n" 18227 "void bar()\n" 18228 " {\n" 18229 " foobar();\n" 18230 " }\n" 18231 "#endif", 18232 WhitesmithsBraceStyle); 18233 18234 // This shouldn't affect ObjC blocks.. 18235 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n" 18236 " // ...\n" 18237 " int i;\n" 18238 "}];", 18239 WhitesmithsBraceStyle); 18240 verifyFormat("void (^block)(void) = ^{\n" 18241 " // ...\n" 18242 " int i;\n" 18243 "};", 18244 WhitesmithsBraceStyle); 18245 // .. or dict literals. 18246 verifyFormat("void f()\n" 18247 " {\n" 18248 " [object someMethod:@{@\"a\" : @\"b\"}];\n" 18249 " }", 18250 WhitesmithsBraceStyle); 18251 18252 verifyFormat("int f()\n" 18253 " { // comment\n" 18254 " return 42;\n" 18255 " }", 18256 WhitesmithsBraceStyle); 18257 18258 FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle; 18259 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = 18260 FormatStyle::SIS_OnlyFirstIf; 18261 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true; 18262 verifyFormat("void f(bool b)\n" 18263 " {\n" 18264 " if (b)\n" 18265 " {\n" 18266 " return;\n" 18267 " }\n" 18268 " }\n", 18269 BreakBeforeBraceShortIfs); 18270 verifyFormat("void f(bool b)\n" 18271 " {\n" 18272 " if (b) return;\n" 18273 " }\n", 18274 BreakBeforeBraceShortIfs); 18275 verifyFormat("void f(bool b)\n" 18276 " {\n" 18277 " while (b)\n" 18278 " {\n" 18279 " return;\n" 18280 " }\n" 18281 " }\n", 18282 BreakBeforeBraceShortIfs); 18283 } 18284 18285 TEST_F(FormatTest, GNUBraceBreaking) { 18286 FormatStyle GNUBraceStyle = getLLVMStyle(); 18287 GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU; 18288 verifyFormat("namespace a\n" 18289 "{\n" 18290 "class A\n" 18291 "{\n" 18292 " void f()\n" 18293 " {\n" 18294 " int a;\n" 18295 " {\n" 18296 " int b;\n" 18297 " }\n" 18298 " if (true)\n" 18299 " {\n" 18300 " a();\n" 18301 " b();\n" 18302 " }\n" 18303 " }\n" 18304 " void g() { return; }\n" 18305 "}\n" 18306 "} // namespace a", 18307 GNUBraceStyle); 18308 18309 verifyFormat("void f()\n" 18310 "{\n" 18311 " if (true)\n" 18312 " {\n" 18313 " a();\n" 18314 " }\n" 18315 " else if (false)\n" 18316 " {\n" 18317 " b();\n" 18318 " }\n" 18319 " else\n" 18320 " {\n" 18321 " c();\n" 18322 " }\n" 18323 "}\n", 18324 GNUBraceStyle); 18325 18326 verifyFormat("void f()\n" 18327 "{\n" 18328 " for (int i = 0; i < 10; ++i)\n" 18329 " {\n" 18330 " a();\n" 18331 " }\n" 18332 " while (false)\n" 18333 " {\n" 18334 " b();\n" 18335 " }\n" 18336 " do\n" 18337 " {\n" 18338 " c();\n" 18339 " }\n" 18340 " while (false);\n" 18341 "}\n", 18342 GNUBraceStyle); 18343 18344 verifyFormat("void f(int a)\n" 18345 "{\n" 18346 " switch (a)\n" 18347 " {\n" 18348 " case 0:\n" 18349 " break;\n" 18350 " case 1:\n" 18351 " {\n" 18352 " break;\n" 18353 " }\n" 18354 " case 2:\n" 18355 " {\n" 18356 " }\n" 18357 " break;\n" 18358 " default:\n" 18359 " break;\n" 18360 " }\n" 18361 "}\n", 18362 GNUBraceStyle); 18363 18364 verifyFormat("enum X\n" 18365 "{\n" 18366 " Y = 0,\n" 18367 "}\n", 18368 GNUBraceStyle); 18369 18370 verifyFormat("@interface BSApplicationController ()\n" 18371 "{\n" 18372 "@private\n" 18373 " id _extraIvar;\n" 18374 "}\n" 18375 "@end\n", 18376 GNUBraceStyle); 18377 18378 verifyFormat("#ifdef _DEBUG\n" 18379 "int foo(int i = 0)\n" 18380 "#else\n" 18381 "int foo(int i = 5)\n" 18382 "#endif\n" 18383 "{\n" 18384 " return i;\n" 18385 "}", 18386 GNUBraceStyle); 18387 18388 verifyFormat("void foo() {}\n" 18389 "void bar()\n" 18390 "#ifdef _DEBUG\n" 18391 "{\n" 18392 " foo();\n" 18393 "}\n" 18394 "#else\n" 18395 "{\n" 18396 "}\n" 18397 "#endif", 18398 GNUBraceStyle); 18399 18400 verifyFormat("void foobar() { int i = 5; }\n" 18401 "#ifdef _DEBUG\n" 18402 "void bar() {}\n" 18403 "#else\n" 18404 "void bar() { foobar(); }\n" 18405 "#endif", 18406 GNUBraceStyle); 18407 } 18408 18409 TEST_F(FormatTest, WebKitBraceBreaking) { 18410 FormatStyle WebKitBraceStyle = getLLVMStyle(); 18411 WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit; 18412 WebKitBraceStyle.FixNamespaceComments = false; 18413 verifyFormat("namespace a {\n" 18414 "class A {\n" 18415 " void f()\n" 18416 " {\n" 18417 " if (true) {\n" 18418 " a();\n" 18419 " b();\n" 18420 " }\n" 18421 " }\n" 18422 " void g() { return; }\n" 18423 "};\n" 18424 "enum E {\n" 18425 " A,\n" 18426 " // foo\n" 18427 " B,\n" 18428 " C\n" 18429 "};\n" 18430 "struct B {\n" 18431 " int x;\n" 18432 "};\n" 18433 "}\n", 18434 WebKitBraceStyle); 18435 verifyFormat("struct S {\n" 18436 " int Type;\n" 18437 " union {\n" 18438 " int x;\n" 18439 " double y;\n" 18440 " } Value;\n" 18441 " class C {\n" 18442 " MyFavoriteType Value;\n" 18443 " } Class;\n" 18444 "};\n", 18445 WebKitBraceStyle); 18446 } 18447 18448 TEST_F(FormatTest, CatchExceptionReferenceBinding) { 18449 verifyFormat("void f() {\n" 18450 " try {\n" 18451 " } catch (const Exception &e) {\n" 18452 " }\n" 18453 "}\n", 18454 getLLVMStyle()); 18455 } 18456 18457 TEST_F(FormatTest, CatchAlignArrayOfStructuresRightAlignment) { 18458 auto Style = getLLVMStyle(); 18459 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 18460 Style.AlignConsecutiveAssignments = 18461 FormatStyle::AlignConsecutiveStyle::ACS_Consecutive; 18462 Style.AlignConsecutiveDeclarations = 18463 FormatStyle::AlignConsecutiveStyle::ACS_Consecutive; 18464 verifyFormat("struct test demo[] = {\n" 18465 " {56, 23, \"hello\"},\n" 18466 " {-1, 93463, \"world\"},\n" 18467 " { 7, 5, \"!!\"}\n" 18468 "};\n", 18469 Style); 18470 18471 verifyFormat("struct test demo[] = {\n" 18472 " {56, 23, \"hello\"}, // first line\n" 18473 " {-1, 93463, \"world\"}, // second line\n" 18474 " { 7, 5, \"!!\"} // third line\n" 18475 "};\n", 18476 Style); 18477 18478 verifyFormat("struct test demo[4] = {\n" 18479 " { 56, 23, 21, \"oh\"}, // first line\n" 18480 " { -1, 93463, 22, \"my\"}, // second line\n" 18481 " { 7, 5, 1, \"goodness\"} // third line\n" 18482 " {234, 5, 1, \"gracious\"} // fourth line\n" 18483 "};\n", 18484 Style); 18485 18486 verifyFormat("struct test demo[3] = {\n" 18487 " {56, 23, \"hello\"},\n" 18488 " {-1, 93463, \"world\"},\n" 18489 " { 7, 5, \"!!\"}\n" 18490 "};\n", 18491 Style); 18492 18493 verifyFormat("struct test demo[3] = {\n" 18494 " {int{56}, 23, \"hello\"},\n" 18495 " {int{-1}, 93463, \"world\"},\n" 18496 " { int{7}, 5, \"!!\"}\n" 18497 "};\n", 18498 Style); 18499 18500 verifyFormat("struct test demo[] = {\n" 18501 " {56, 23, \"hello\"},\n" 18502 " {-1, 93463, \"world\"},\n" 18503 " { 7, 5, \"!!\"},\n" 18504 "};\n", 18505 Style); 18506 18507 verifyFormat("test demo[] = {\n" 18508 " {56, 23, \"hello\"},\n" 18509 " {-1, 93463, \"world\"},\n" 18510 " { 7, 5, \"!!\"},\n" 18511 "};\n", 18512 Style); 18513 18514 verifyFormat("demo = std::array<struct test, 3>{\n" 18515 " test{56, 23, \"hello\"},\n" 18516 " test{-1, 93463, \"world\"},\n" 18517 " test{ 7, 5, \"!!\"},\n" 18518 "};\n", 18519 Style); 18520 18521 verifyFormat("test demo[] = {\n" 18522 " {56, 23, \"hello\"},\n" 18523 "#if X\n" 18524 " {-1, 93463, \"world\"},\n" 18525 "#endif\n" 18526 " { 7, 5, \"!!\"}\n" 18527 "};\n", 18528 Style); 18529 18530 verifyFormat( 18531 "test demo[] = {\n" 18532 " { 7, 23,\n" 18533 " \"hello world i am a very long line that really, in any\"\n" 18534 " \"just world, ought to be split over multiple lines\"},\n" 18535 " {-1, 93463, \"world\"},\n" 18536 " {56, 5, \"!!\"}\n" 18537 "};\n", 18538 Style); 18539 18540 verifyFormat("return GradForUnaryCwise(g, {\n" 18541 " {{\"sign\"}, \"Sign\", " 18542 " {\"x\", \"dy\"}},\n" 18543 " { {\"dx\"}, \"Mul\", {\"dy\"" 18544 ", \"sign\"}},\n" 18545 "});\n", 18546 Style); 18547 18548 Style.ColumnLimit = 0; 18549 EXPECT_EQ( 18550 "test demo[] = {\n" 18551 " {56, 23, \"hello world i am a very long line that really, " 18552 "in any just world, ought to be split over multiple lines\"},\n" 18553 " {-1, 93463, " 18554 " \"world\"},\n" 18555 " { 7, 5, " 18556 " \"!!\"},\n" 18557 "};", 18558 format("test demo[] = {{56, 23, \"hello world i am a very long line " 18559 "that really, in any just world, ought to be split over multiple " 18560 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 18561 Style)); 18562 18563 Style.ColumnLimit = 80; 18564 verifyFormat("test demo[] = {\n" 18565 " {56, 23, /* a comment */ \"hello\"},\n" 18566 " {-1, 93463, \"world\"},\n" 18567 " { 7, 5, \"!!\"}\n" 18568 "};\n", 18569 Style); 18570 18571 verifyFormat("test demo[] = {\n" 18572 " {56, 23, \"hello\"},\n" 18573 " {-1, 93463, \"world\" /* comment here */},\n" 18574 " { 7, 5, \"!!\"}\n" 18575 "};\n", 18576 Style); 18577 18578 verifyFormat("test demo[] = {\n" 18579 " {56, /* a comment */ 23, \"hello\"},\n" 18580 " {-1, 93463, \"world\"},\n" 18581 " { 7, 5, \"!!\"}\n" 18582 "};\n", 18583 Style); 18584 18585 Style.ColumnLimit = 20; 18586 EXPECT_EQ( 18587 "demo = std::array<\n" 18588 " struct test, 3>{\n" 18589 " test{\n" 18590 " 56, 23,\n" 18591 " \"hello \"\n" 18592 " \"world i \"\n" 18593 " \"am a very \"\n" 18594 " \"long line \"\n" 18595 " \"that \"\n" 18596 " \"really, \"\n" 18597 " \"in any \"\n" 18598 " \"just \"\n" 18599 " \"world, \"\n" 18600 " \"ought to \"\n" 18601 " \"be split \"\n" 18602 " \"over \"\n" 18603 " \"multiple \"\n" 18604 " \"lines\"},\n" 18605 " test{-1, 93463,\n" 18606 " \"world\"},\n" 18607 " test{ 7, 5,\n" 18608 " \"!!\" },\n" 18609 "};", 18610 format("demo = std::array<struct test, 3>{test{56, 23, \"hello world " 18611 "i am a very long line that really, in any just world, ought " 18612 "to be split over multiple lines\"},test{-1, 93463, \"world\"}," 18613 "test{7, 5, \"!!\"},};", 18614 Style)); 18615 // This caused a core dump by enabling Alignment in the LLVMStyle globally 18616 Style = getLLVMStyleWithColumns(50); 18617 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 18618 verifyFormat("static A x = {\n" 18619 " {{init1, init2, init3, init4},\n" 18620 " {init1, init2, init3, init4}}\n" 18621 "};", 18622 Style); 18623 Style.ColumnLimit = 100; 18624 EXPECT_EQ( 18625 "test demo[] = {\n" 18626 " {56, 23,\n" 18627 " \"hello world i am a very long line that really, in any just world" 18628 ", ought to be split over \"\n" 18629 " \"multiple lines\" },\n" 18630 " {-1, 93463, \"world\"},\n" 18631 " { 7, 5, \"!!\"},\n" 18632 "};", 18633 format("test demo[] = {{56, 23, \"hello world i am a very long line " 18634 "that really, in any just world, ought to be split over multiple " 18635 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 18636 Style)); 18637 18638 Style = getLLVMStyleWithColumns(50); 18639 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 18640 Style.AlignConsecutiveAssignments = 18641 FormatStyle::AlignConsecutiveStyle::ACS_Consecutive; 18642 Style.AlignConsecutiveDeclarations = 18643 FormatStyle::AlignConsecutiveStyle::ACS_Consecutive; 18644 verifyFormat("struct test demo[] = {\n" 18645 " {56, 23, \"hello\"},\n" 18646 " {-1, 93463, \"world\"},\n" 18647 " { 7, 5, \"!!\"}\n" 18648 "};\n" 18649 "static A x = {\n" 18650 " {{init1, init2, init3, init4},\n" 18651 " {init1, init2, init3, init4}}\n" 18652 "};", 18653 Style); 18654 Style.ColumnLimit = 100; 18655 Style.AlignConsecutiveAssignments = 18656 FormatStyle::AlignConsecutiveStyle::ACS_AcrossComments; 18657 Style.AlignConsecutiveDeclarations = 18658 FormatStyle::AlignConsecutiveStyle::ACS_AcrossComments; 18659 verifyFormat("struct test demo[] = {\n" 18660 " {56, 23, \"hello\"},\n" 18661 " {-1, 93463, \"world\"},\n" 18662 " { 7, 5, \"!!\"}\n" 18663 "};\n" 18664 "struct test demo[4] = {\n" 18665 " { 56, 23, 21, \"oh\"}, // first line\n" 18666 " { -1, 93463, 22, \"my\"}, // second line\n" 18667 " { 7, 5, 1, \"goodness\"} // third line\n" 18668 " {234, 5, 1, \"gracious\"} // fourth line\n" 18669 "};\n", 18670 Style); 18671 EXPECT_EQ( 18672 "test demo[] = {\n" 18673 " {56,\n" 18674 " \"hello world i am a very long line that really, in any just world" 18675 ", ought to be split over \"\n" 18676 " \"multiple lines\", 23},\n" 18677 " {-1, \"world\", 93463},\n" 18678 " { 7, \"!!\", 5},\n" 18679 "};", 18680 format("test demo[] = {{56, \"hello world i am a very long line " 18681 "that really, in any just world, ought to be split over multiple " 18682 "lines\", 23},{-1, \"world\", 93463},{7, \"!!\", 5},};", 18683 Style)); 18684 } 18685 18686 TEST_F(FormatTest, CatchAlignArrayOfStructuresLeftAlignment) { 18687 auto Style = getLLVMStyle(); 18688 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 18689 /* FIXME: This case gets misformatted. 18690 verifyFormat("auto foo = Items{\n" 18691 " Section{0, bar(), },\n" 18692 " Section{1, boo() }\n" 18693 "};\n", 18694 Style); 18695 */ 18696 verifyFormat("auto foo = Items{\n" 18697 " Section{\n" 18698 " 0, bar(),\n" 18699 " }\n" 18700 "};\n", 18701 Style); 18702 verifyFormat("struct test demo[] = {\n" 18703 " {56, 23, \"hello\"},\n" 18704 " {-1, 93463, \"world\"},\n" 18705 " {7, 5, \"!!\" }\n" 18706 "};\n", 18707 Style); 18708 verifyFormat("struct test demo[] = {\n" 18709 " {56, 23, \"hello\"}, // first line\n" 18710 " {-1, 93463, \"world\"}, // second line\n" 18711 " {7, 5, \"!!\" } // third line\n" 18712 "};\n", 18713 Style); 18714 verifyFormat("struct test demo[4] = {\n" 18715 " {56, 23, 21, \"oh\" }, // first line\n" 18716 " {-1, 93463, 22, \"my\" }, // second line\n" 18717 " {7, 5, 1, \"goodness\"} // third line\n" 18718 " {234, 5, 1, \"gracious\"} // fourth line\n" 18719 "};\n", 18720 Style); 18721 verifyFormat("struct test demo[3] = {\n" 18722 " {56, 23, \"hello\"},\n" 18723 " {-1, 93463, \"world\"},\n" 18724 " {7, 5, \"!!\" }\n" 18725 "};\n", 18726 Style); 18727 18728 verifyFormat("struct test demo[3] = {\n" 18729 " {int{56}, 23, \"hello\"},\n" 18730 " {int{-1}, 93463, \"world\"},\n" 18731 " {int{7}, 5, \"!!\" }\n" 18732 "};\n", 18733 Style); 18734 verifyFormat("struct test demo[] = {\n" 18735 " {56, 23, \"hello\"},\n" 18736 " {-1, 93463, \"world\"},\n" 18737 " {7, 5, \"!!\" },\n" 18738 "};\n", 18739 Style); 18740 verifyFormat("test demo[] = {\n" 18741 " {56, 23, \"hello\"},\n" 18742 " {-1, 93463, \"world\"},\n" 18743 " {7, 5, \"!!\" },\n" 18744 "};\n", 18745 Style); 18746 verifyFormat("demo = std::array<struct test, 3>{\n" 18747 " test{56, 23, \"hello\"},\n" 18748 " test{-1, 93463, \"world\"},\n" 18749 " test{7, 5, \"!!\" },\n" 18750 "};\n", 18751 Style); 18752 verifyFormat("test demo[] = {\n" 18753 " {56, 23, \"hello\"},\n" 18754 "#if X\n" 18755 " {-1, 93463, \"world\"},\n" 18756 "#endif\n" 18757 " {7, 5, \"!!\" }\n" 18758 "};\n", 18759 Style); 18760 verifyFormat( 18761 "test demo[] = {\n" 18762 " {7, 23,\n" 18763 " \"hello world i am a very long line that really, in any\"\n" 18764 " \"just world, ought to be split over multiple lines\"},\n" 18765 " {-1, 93463, \"world\" },\n" 18766 " {56, 5, \"!!\" }\n" 18767 "};\n", 18768 Style); 18769 18770 verifyFormat("return GradForUnaryCwise(g, {\n" 18771 " {{\"sign\"}, \"Sign\", {\"x\", " 18772 "\"dy\"} },\n" 18773 " {{\"dx\"}, \"Mul\", " 18774 "{\"dy\", \"sign\"}},\n" 18775 "});\n", 18776 Style); 18777 18778 Style.ColumnLimit = 0; 18779 EXPECT_EQ( 18780 "test demo[] = {\n" 18781 " {56, 23, \"hello world i am a very long line that really, in any " 18782 "just world, ought to be split over multiple lines\"},\n" 18783 " {-1, 93463, \"world\" " 18784 " },\n" 18785 " {7, 5, \"!!\" " 18786 " },\n" 18787 "};", 18788 format("test demo[] = {{56, 23, \"hello world i am a very long line " 18789 "that really, in any just world, ought to be split over multiple " 18790 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 18791 Style)); 18792 18793 Style.ColumnLimit = 80; 18794 verifyFormat("test demo[] = {\n" 18795 " {56, 23, /* a comment */ \"hello\"},\n" 18796 " {-1, 93463, \"world\" },\n" 18797 " {7, 5, \"!!\" }\n" 18798 "};\n", 18799 Style); 18800 18801 verifyFormat("test demo[] = {\n" 18802 " {56, 23, \"hello\" },\n" 18803 " {-1, 93463, \"world\" /* comment here */},\n" 18804 " {7, 5, \"!!\" }\n" 18805 "};\n", 18806 Style); 18807 18808 verifyFormat("test demo[] = {\n" 18809 " {56, /* a comment */ 23, \"hello\"},\n" 18810 " {-1, 93463, \"world\"},\n" 18811 " {7, 5, \"!!\" }\n" 18812 "};\n", 18813 Style); 18814 18815 Style.ColumnLimit = 20; 18816 EXPECT_EQ( 18817 "demo = std::array<\n" 18818 " struct test, 3>{\n" 18819 " test{\n" 18820 " 56, 23,\n" 18821 " \"hello \"\n" 18822 " \"world i \"\n" 18823 " \"am a very \"\n" 18824 " \"long line \"\n" 18825 " \"that \"\n" 18826 " \"really, \"\n" 18827 " \"in any \"\n" 18828 " \"just \"\n" 18829 " \"world, \"\n" 18830 " \"ought to \"\n" 18831 " \"be split \"\n" 18832 " \"over \"\n" 18833 " \"multiple \"\n" 18834 " \"lines\"},\n" 18835 " test{-1, 93463,\n" 18836 " \"world\"},\n" 18837 " test{7, 5,\n" 18838 " \"!!\" },\n" 18839 "};", 18840 format("demo = std::array<struct test, 3>{test{56, 23, \"hello world " 18841 "i am a very long line that really, in any just world, ought " 18842 "to be split over multiple lines\"},test{-1, 93463, \"world\"}," 18843 "test{7, 5, \"!!\"},};", 18844 Style)); 18845 18846 // This caused a core dump by enabling Alignment in the LLVMStyle globally 18847 Style = getLLVMStyleWithColumns(50); 18848 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 18849 verifyFormat("static A x = {\n" 18850 " {{init1, init2, init3, init4},\n" 18851 " {init1, init2, init3, init4}}\n" 18852 "};", 18853 Style); 18854 Style.ColumnLimit = 100; 18855 EXPECT_EQ( 18856 "test demo[] = {\n" 18857 " {56, 23,\n" 18858 " \"hello world i am a very long line that really, in any just world" 18859 ", ought to be split over \"\n" 18860 " \"multiple lines\" },\n" 18861 " {-1, 93463, \"world\"},\n" 18862 " {7, 5, \"!!\" },\n" 18863 "};", 18864 format("test demo[] = {{56, 23, \"hello world i am a very long line " 18865 "that really, in any just world, ought to be split over multiple " 18866 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 18867 Style)); 18868 } 18869 18870 TEST_F(FormatTest, UnderstandsPragmas) { 18871 verifyFormat("#pragma omp reduction(| : var)"); 18872 verifyFormat("#pragma omp reduction(+ : var)"); 18873 18874 EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string " 18875 "(including parentheses).", 18876 format("#pragma mark Any non-hyphenated or hyphenated string " 18877 "(including parentheses).")); 18878 } 18879 18880 TEST_F(FormatTest, UnderstandPragmaOption) { 18881 verifyFormat("#pragma option -C -A"); 18882 18883 EXPECT_EQ("#pragma option -C -A", format("#pragma option -C -A")); 18884 } 18885 18886 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) { 18887 FormatStyle Style = getLLVMStyleWithColumns(20); 18888 18889 // See PR41213 18890 EXPECT_EQ("/*\n" 18891 " *\t9012345\n" 18892 " * /8901\n" 18893 " */", 18894 format("/*\n" 18895 " *\t9012345 /8901\n" 18896 " */", 18897 Style)); 18898 EXPECT_EQ("/*\n" 18899 " *345678\n" 18900 " *\t/8901\n" 18901 " */", 18902 format("/*\n" 18903 " *345678\t/8901\n" 18904 " */", 18905 Style)); 18906 18907 verifyFormat("int a; // the\n" 18908 " // comment", 18909 Style); 18910 EXPECT_EQ("int a; /* first line\n" 18911 " * second\n" 18912 " * line third\n" 18913 " * line\n" 18914 " */", 18915 format("int a; /* first line\n" 18916 " * second\n" 18917 " * line third\n" 18918 " * line\n" 18919 " */", 18920 Style)); 18921 EXPECT_EQ("int a; // first line\n" 18922 " // second\n" 18923 " // line third\n" 18924 " // line", 18925 format("int a; // first line\n" 18926 " // second line\n" 18927 " // third line", 18928 Style)); 18929 18930 Style.PenaltyExcessCharacter = 90; 18931 verifyFormat("int a; // the comment", Style); 18932 EXPECT_EQ("int a; // the comment\n" 18933 " // aaa", 18934 format("int a; // the comment aaa", Style)); 18935 EXPECT_EQ("int a; /* first line\n" 18936 " * second line\n" 18937 " * third line\n" 18938 " */", 18939 format("int a; /* first line\n" 18940 " * second line\n" 18941 " * third line\n" 18942 " */", 18943 Style)); 18944 EXPECT_EQ("int a; // first line\n" 18945 " // second line\n" 18946 " // third line", 18947 format("int a; // first line\n" 18948 " // second line\n" 18949 " // third line", 18950 Style)); 18951 // FIXME: Investigate why this is not getting the same layout as the test 18952 // above. 18953 EXPECT_EQ("int a; /* first line\n" 18954 " * second line\n" 18955 " * third line\n" 18956 " */", 18957 format("int a; /* first line second line third line" 18958 "\n*/", 18959 Style)); 18960 18961 EXPECT_EQ("// foo bar baz bazfoo\n" 18962 "// foo bar foo bar\n", 18963 format("// foo bar baz bazfoo\n" 18964 "// foo bar foo bar\n", 18965 Style)); 18966 EXPECT_EQ("// foo bar baz bazfoo\n" 18967 "// foo bar foo bar\n", 18968 format("// foo bar baz bazfoo\n" 18969 "// foo bar foo bar\n", 18970 Style)); 18971 18972 // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the 18973 // next one. 18974 EXPECT_EQ("// foo bar baz bazfoo\n" 18975 "// bar foo bar\n", 18976 format("// foo bar baz bazfoo bar\n" 18977 "// foo bar\n", 18978 Style)); 18979 18980 EXPECT_EQ("// foo bar baz bazfoo\n" 18981 "// foo bar baz bazfoo\n" 18982 "// bar foo bar\n", 18983 format("// foo bar baz bazfoo\n" 18984 "// foo bar baz bazfoo bar\n" 18985 "// foo bar\n", 18986 Style)); 18987 18988 EXPECT_EQ("// foo bar baz bazfoo\n" 18989 "// foo bar baz bazfoo\n" 18990 "// bar foo bar\n", 18991 format("// foo bar baz bazfoo\n" 18992 "// foo bar baz bazfoo bar\n" 18993 "// foo bar\n", 18994 Style)); 18995 18996 // Make sure we do not keep protruding characters if strict mode reflow is 18997 // cheaper than keeping protruding characters. 18998 Style.ColumnLimit = 21; 18999 EXPECT_EQ( 19000 "// foo foo foo foo\n" 19001 "// foo foo foo foo\n" 19002 "// foo foo foo foo\n", 19003 format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style)); 19004 19005 EXPECT_EQ("int a = /* long block\n" 19006 " comment */\n" 19007 " 42;", 19008 format("int a = /* long block comment */ 42;", Style)); 19009 } 19010 19011 TEST_F(FormatTest, BreakPenaltyAfterLParen) { 19012 FormatStyle Style = getLLVMStyle(); 19013 Style.ColumnLimit = 8; 19014 Style.PenaltyExcessCharacter = 15; 19015 verifyFormat("int foo(\n" 19016 " int aaaaaaaaaaaaaaaaaaaaaaaa);", 19017 Style); 19018 Style.PenaltyBreakOpenParenthesis = 200; 19019 EXPECT_EQ("int foo(int aaaaaaaaaaaaaaaaaaaaaaaa);", 19020 format("int foo(\n" 19021 " int aaaaaaaaaaaaaaaaaaaaaaaa);", 19022 Style)); 19023 } 19024 19025 TEST_F(FormatTest, BreakPenaltyAfterCastLParen) { 19026 FormatStyle Style = getLLVMStyle(); 19027 Style.ColumnLimit = 5; 19028 Style.PenaltyExcessCharacter = 150; 19029 verifyFormat("foo((\n" 19030 " int)aaaaaaaaaaaaaaaaaaaaaaaa);", 19031 19032 Style); 19033 Style.PenaltyBreakOpenParenthesis = 100000; 19034 EXPECT_EQ("foo((int)\n" 19035 " aaaaaaaaaaaaaaaaaaaaaaaa);", 19036 format("foo((\n" 19037 "int)aaaaaaaaaaaaaaaaaaaaaaaa);", 19038 Style)); 19039 } 19040 19041 TEST_F(FormatTest, BreakPenaltyAfterForLoopLParen) { 19042 FormatStyle Style = getLLVMStyle(); 19043 Style.ColumnLimit = 4; 19044 Style.PenaltyExcessCharacter = 100; 19045 verifyFormat("for (\n" 19046 " int iiiiiiiiiiiiiiiii =\n" 19047 " 0;\n" 19048 " iiiiiiiiiiiiiiiii <\n" 19049 " 2;\n" 19050 " iiiiiiiiiiiiiiiii++) {\n" 19051 "}", 19052 19053 Style); 19054 Style.PenaltyBreakOpenParenthesis = 1250; 19055 EXPECT_EQ("for (int iiiiiiiiiiiiiiiii =\n" 19056 " 0;\n" 19057 " iiiiiiiiiiiiiiiii <\n" 19058 " 2;\n" 19059 " iiiiiiiiiiiiiiiii++) {\n" 19060 "}", 19061 format("for (\n" 19062 " int iiiiiiiiiiiiiiiii =\n" 19063 " 0;\n" 19064 " iiiiiiiiiiiiiiiii <\n" 19065 " 2;\n" 19066 " iiiiiiiiiiiiiiiii++) {\n" 19067 "}", 19068 Style)); 19069 } 19070 19071 #define EXPECT_ALL_STYLES_EQUAL(Styles) \ 19072 for (size_t i = 1; i < Styles.size(); ++i) \ 19073 EXPECT_EQ(Styles[0], Styles[i]) \ 19074 << "Style #" << i << " of " << Styles.size() << " differs from Style #0" 19075 19076 TEST_F(FormatTest, GetsPredefinedStyleByName) { 19077 SmallVector<FormatStyle, 3> Styles; 19078 Styles.resize(3); 19079 19080 Styles[0] = getLLVMStyle(); 19081 EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1])); 19082 EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2])); 19083 EXPECT_ALL_STYLES_EQUAL(Styles); 19084 19085 Styles[0] = getGoogleStyle(); 19086 EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1])); 19087 EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2])); 19088 EXPECT_ALL_STYLES_EQUAL(Styles); 19089 19090 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript); 19091 EXPECT_TRUE( 19092 getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1])); 19093 EXPECT_TRUE( 19094 getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2])); 19095 EXPECT_ALL_STYLES_EQUAL(Styles); 19096 19097 Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp); 19098 EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1])); 19099 EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2])); 19100 EXPECT_ALL_STYLES_EQUAL(Styles); 19101 19102 Styles[0] = getMozillaStyle(); 19103 EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1])); 19104 EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2])); 19105 EXPECT_ALL_STYLES_EQUAL(Styles); 19106 19107 Styles[0] = getWebKitStyle(); 19108 EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1])); 19109 EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2])); 19110 EXPECT_ALL_STYLES_EQUAL(Styles); 19111 19112 Styles[0] = getGNUStyle(); 19113 EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1])); 19114 EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2])); 19115 EXPECT_ALL_STYLES_EQUAL(Styles); 19116 19117 EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0])); 19118 } 19119 19120 TEST_F(FormatTest, GetsCorrectBasedOnStyle) { 19121 SmallVector<FormatStyle, 8> Styles; 19122 Styles.resize(2); 19123 19124 Styles[0] = getGoogleStyle(); 19125 Styles[1] = getLLVMStyle(); 19126 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value()); 19127 EXPECT_ALL_STYLES_EQUAL(Styles); 19128 19129 Styles.resize(5); 19130 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript); 19131 Styles[1] = getLLVMStyle(); 19132 Styles[1].Language = FormatStyle::LK_JavaScript; 19133 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value()); 19134 19135 Styles[2] = getLLVMStyle(); 19136 Styles[2].Language = FormatStyle::LK_JavaScript; 19137 EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n" 19138 "BasedOnStyle: Google", 19139 &Styles[2]) 19140 .value()); 19141 19142 Styles[3] = getLLVMStyle(); 19143 Styles[3].Language = FormatStyle::LK_JavaScript; 19144 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n" 19145 "Language: JavaScript", 19146 &Styles[3]) 19147 .value()); 19148 19149 Styles[4] = getLLVMStyle(); 19150 Styles[4].Language = FormatStyle::LK_JavaScript; 19151 EXPECT_EQ(0, parseConfiguration("---\n" 19152 "BasedOnStyle: LLVM\n" 19153 "IndentWidth: 123\n" 19154 "---\n" 19155 "BasedOnStyle: Google\n" 19156 "Language: JavaScript", 19157 &Styles[4]) 19158 .value()); 19159 EXPECT_ALL_STYLES_EQUAL(Styles); 19160 } 19161 19162 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME) \ 19163 Style.FIELD = false; \ 19164 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value()); \ 19165 EXPECT_TRUE(Style.FIELD); \ 19166 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value()); \ 19167 EXPECT_FALSE(Style.FIELD); 19168 19169 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD) 19170 19171 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME) \ 19172 Style.STRUCT.FIELD = false; \ 19173 EXPECT_EQ(0, \ 19174 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": true", &Style) \ 19175 .value()); \ 19176 EXPECT_TRUE(Style.STRUCT.FIELD); \ 19177 EXPECT_EQ(0, \ 19178 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": false", &Style) \ 19179 .value()); \ 19180 EXPECT_FALSE(Style.STRUCT.FIELD); 19181 19182 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD) \ 19183 CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD) 19184 19185 #define CHECK_PARSE(TEXT, FIELD, VALUE) \ 19186 EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!"; \ 19187 EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value()); \ 19188 EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!" 19189 19190 TEST_F(FormatTest, ParsesConfigurationBools) { 19191 FormatStyle Style = {}; 19192 Style.Language = FormatStyle::LK_Cpp; 19193 CHECK_PARSE_BOOL(AlignTrailingComments); 19194 CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine); 19195 CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine); 19196 CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine); 19197 CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine); 19198 CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine); 19199 CHECK_PARSE_BOOL(BinPackArguments); 19200 CHECK_PARSE_BOOL(BinPackParameters); 19201 CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations); 19202 CHECK_PARSE_BOOL(BreakBeforeConceptDeclarations); 19203 CHECK_PARSE_BOOL(BreakBeforeTernaryOperators); 19204 CHECK_PARSE_BOOL(BreakStringLiterals); 19205 CHECK_PARSE_BOOL(CompactNamespaces); 19206 CHECK_PARSE_BOOL(DeriveLineEnding); 19207 CHECK_PARSE_BOOL(DerivePointerAlignment); 19208 CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding"); 19209 CHECK_PARSE_BOOL(DisableFormat); 19210 CHECK_PARSE_BOOL(IndentAccessModifiers); 19211 CHECK_PARSE_BOOL(IndentCaseLabels); 19212 CHECK_PARSE_BOOL(IndentCaseBlocks); 19213 CHECK_PARSE_BOOL(IndentGotoLabels); 19214 CHECK_PARSE_BOOL(IndentRequires); 19215 CHECK_PARSE_BOOL(IndentWrappedFunctionNames); 19216 CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks); 19217 CHECK_PARSE_BOOL(ObjCSpaceAfterProperty); 19218 CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList); 19219 CHECK_PARSE_BOOL(Cpp11BracedListStyle); 19220 CHECK_PARSE_BOOL(ReflowComments); 19221 CHECK_PARSE_BOOL(RemoveBracesLLVM); 19222 CHECK_PARSE_BOOL(SortUsingDeclarations); 19223 CHECK_PARSE_BOOL(SpacesInParentheses); 19224 CHECK_PARSE_BOOL(SpacesInSquareBrackets); 19225 CHECK_PARSE_BOOL(SpacesInConditionalStatement); 19226 CHECK_PARSE_BOOL(SpaceInEmptyBlock); 19227 CHECK_PARSE_BOOL(SpaceInEmptyParentheses); 19228 CHECK_PARSE_BOOL(SpacesInContainerLiterals); 19229 CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses); 19230 CHECK_PARSE_BOOL(SpaceAfterCStyleCast); 19231 CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword); 19232 CHECK_PARSE_BOOL(SpaceAfterLogicalNot); 19233 CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators); 19234 CHECK_PARSE_BOOL(SpaceBeforeCaseColon); 19235 CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList); 19236 CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon); 19237 CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon); 19238 CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon); 19239 CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets); 19240 CHECK_PARSE_BOOL(UseCRLF); 19241 19242 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel); 19243 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass); 19244 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum); 19245 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction); 19246 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace); 19247 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration); 19248 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct); 19249 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion); 19250 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock); 19251 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch); 19252 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse); 19253 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody); 19254 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile); 19255 CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces); 19256 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction); 19257 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord); 19258 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace); 19259 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterControlStatements); 19260 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterForeachMacros); 19261 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, 19262 AfterFunctionDeclarationName); 19263 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, 19264 AfterFunctionDefinitionName); 19265 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterIfMacros); 19266 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterOverloadedOperator); 19267 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, BeforeNonEmptyParentheses); 19268 } 19269 19270 #undef CHECK_PARSE_BOOL 19271 19272 TEST_F(FormatTest, ParsesConfiguration) { 19273 FormatStyle Style = {}; 19274 Style.Language = FormatStyle::LK_Cpp; 19275 CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234); 19276 CHECK_PARSE("ConstructorInitializerIndentWidth: 1234", 19277 ConstructorInitializerIndentWidth, 1234u); 19278 CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u); 19279 CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u); 19280 CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u); 19281 CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u); 19282 CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234", 19283 PenaltyBreakBeforeFirstCallParameter, 1234u); 19284 CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234", 19285 PenaltyBreakTemplateDeclaration, 1234u); 19286 CHECK_PARSE("PenaltyBreakOpenParenthesis: 1234", PenaltyBreakOpenParenthesis, 19287 1234u); 19288 CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u); 19289 CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234", 19290 PenaltyReturnTypeOnItsOwnLine, 1234u); 19291 CHECK_PARSE("SpacesBeforeTrailingComments: 1234", 19292 SpacesBeforeTrailingComments, 1234u); 19293 CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u); 19294 CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u); 19295 CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$"); 19296 19297 Style.QualifierAlignment = FormatStyle::QAS_Right; 19298 CHECK_PARSE("QualifierAlignment: Leave", QualifierAlignment, 19299 FormatStyle::QAS_Leave); 19300 CHECK_PARSE("QualifierAlignment: Right", QualifierAlignment, 19301 FormatStyle::QAS_Right); 19302 CHECK_PARSE("QualifierAlignment: Left", QualifierAlignment, 19303 FormatStyle::QAS_Left); 19304 CHECK_PARSE("QualifierAlignment: Custom", QualifierAlignment, 19305 FormatStyle::QAS_Custom); 19306 19307 Style.QualifierOrder.clear(); 19308 CHECK_PARSE("QualifierOrder: [ const, volatile, type ]", QualifierOrder, 19309 std::vector<std::string>({"const", "volatile", "type"})); 19310 Style.QualifierOrder.clear(); 19311 CHECK_PARSE("QualifierOrder: [const, type]", QualifierOrder, 19312 std::vector<std::string>({"const", "type"})); 19313 Style.QualifierOrder.clear(); 19314 CHECK_PARSE("QualifierOrder: [volatile, type]", QualifierOrder, 19315 std::vector<std::string>({"volatile", "type"})); 19316 19317 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 19318 CHECK_PARSE("AlignConsecutiveAssignments: None", AlignConsecutiveAssignments, 19319 FormatStyle::ACS_None); 19320 CHECK_PARSE("AlignConsecutiveAssignments: Consecutive", 19321 AlignConsecutiveAssignments, FormatStyle::ACS_Consecutive); 19322 CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLines", 19323 AlignConsecutiveAssignments, FormatStyle::ACS_AcrossEmptyLines); 19324 CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLinesAndComments", 19325 AlignConsecutiveAssignments, 19326 FormatStyle::ACS_AcrossEmptyLinesAndComments); 19327 // For backwards compability, false / true should still parse 19328 CHECK_PARSE("AlignConsecutiveAssignments: false", AlignConsecutiveAssignments, 19329 FormatStyle::ACS_None); 19330 CHECK_PARSE("AlignConsecutiveAssignments: true", AlignConsecutiveAssignments, 19331 FormatStyle::ACS_Consecutive); 19332 19333 Style.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive; 19334 CHECK_PARSE("AlignConsecutiveBitFields: None", AlignConsecutiveBitFields, 19335 FormatStyle::ACS_None); 19336 CHECK_PARSE("AlignConsecutiveBitFields: Consecutive", 19337 AlignConsecutiveBitFields, FormatStyle::ACS_Consecutive); 19338 CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLines", 19339 AlignConsecutiveBitFields, FormatStyle::ACS_AcrossEmptyLines); 19340 CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLinesAndComments", 19341 AlignConsecutiveBitFields, 19342 FormatStyle::ACS_AcrossEmptyLinesAndComments); 19343 // For backwards compability, false / true should still parse 19344 CHECK_PARSE("AlignConsecutiveBitFields: false", AlignConsecutiveBitFields, 19345 FormatStyle::ACS_None); 19346 CHECK_PARSE("AlignConsecutiveBitFields: true", AlignConsecutiveBitFields, 19347 FormatStyle::ACS_Consecutive); 19348 19349 Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 19350 CHECK_PARSE("AlignConsecutiveMacros: None", AlignConsecutiveMacros, 19351 FormatStyle::ACS_None); 19352 CHECK_PARSE("AlignConsecutiveMacros: Consecutive", AlignConsecutiveMacros, 19353 FormatStyle::ACS_Consecutive); 19354 CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLines", 19355 AlignConsecutiveMacros, FormatStyle::ACS_AcrossEmptyLines); 19356 CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLinesAndComments", 19357 AlignConsecutiveMacros, 19358 FormatStyle::ACS_AcrossEmptyLinesAndComments); 19359 // For backwards compability, false / true should still parse 19360 CHECK_PARSE("AlignConsecutiveMacros: false", AlignConsecutiveMacros, 19361 FormatStyle::ACS_None); 19362 CHECK_PARSE("AlignConsecutiveMacros: true", AlignConsecutiveMacros, 19363 FormatStyle::ACS_Consecutive); 19364 19365 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 19366 CHECK_PARSE("AlignConsecutiveDeclarations: None", 19367 AlignConsecutiveDeclarations, FormatStyle::ACS_None); 19368 CHECK_PARSE("AlignConsecutiveDeclarations: Consecutive", 19369 AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive); 19370 CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLines", 19371 AlignConsecutiveDeclarations, FormatStyle::ACS_AcrossEmptyLines); 19372 CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLinesAndComments", 19373 AlignConsecutiveDeclarations, 19374 FormatStyle::ACS_AcrossEmptyLinesAndComments); 19375 // For backwards compability, false / true should still parse 19376 CHECK_PARSE("AlignConsecutiveDeclarations: false", 19377 AlignConsecutiveDeclarations, FormatStyle::ACS_None); 19378 CHECK_PARSE("AlignConsecutiveDeclarations: true", 19379 AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive); 19380 19381 Style.PointerAlignment = FormatStyle::PAS_Middle; 19382 CHECK_PARSE("PointerAlignment: Left", PointerAlignment, 19383 FormatStyle::PAS_Left); 19384 CHECK_PARSE("PointerAlignment: Right", PointerAlignment, 19385 FormatStyle::PAS_Right); 19386 CHECK_PARSE("PointerAlignment: Middle", PointerAlignment, 19387 FormatStyle::PAS_Middle); 19388 Style.ReferenceAlignment = FormatStyle::RAS_Middle; 19389 CHECK_PARSE("ReferenceAlignment: Pointer", ReferenceAlignment, 19390 FormatStyle::RAS_Pointer); 19391 CHECK_PARSE("ReferenceAlignment: Left", ReferenceAlignment, 19392 FormatStyle::RAS_Left); 19393 CHECK_PARSE("ReferenceAlignment: Right", ReferenceAlignment, 19394 FormatStyle::RAS_Right); 19395 CHECK_PARSE("ReferenceAlignment: Middle", ReferenceAlignment, 19396 FormatStyle::RAS_Middle); 19397 // For backward compatibility: 19398 CHECK_PARSE("PointerBindsToType: Left", PointerAlignment, 19399 FormatStyle::PAS_Left); 19400 CHECK_PARSE("PointerBindsToType: Right", PointerAlignment, 19401 FormatStyle::PAS_Right); 19402 CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment, 19403 FormatStyle::PAS_Middle); 19404 19405 Style.Standard = FormatStyle::LS_Auto; 19406 CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03); 19407 CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11); 19408 CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14); 19409 CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17); 19410 CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20); 19411 CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto); 19412 CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest); 19413 // Legacy aliases: 19414 CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03); 19415 CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest); 19416 CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03); 19417 CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11); 19418 19419 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 19420 CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment", 19421 BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment); 19422 CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators, 19423 FormatStyle::BOS_None); 19424 CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators, 19425 FormatStyle::BOS_All); 19426 // For backward compatibility: 19427 CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators, 19428 FormatStyle::BOS_None); 19429 CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators, 19430 FormatStyle::BOS_All); 19431 19432 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 19433 CHECK_PARSE("BreakConstructorInitializers: BeforeComma", 19434 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma); 19435 CHECK_PARSE("BreakConstructorInitializers: AfterColon", 19436 BreakConstructorInitializers, FormatStyle::BCIS_AfterColon); 19437 CHECK_PARSE("BreakConstructorInitializers: BeforeColon", 19438 BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon); 19439 // For backward compatibility: 19440 CHECK_PARSE("BreakConstructorInitializersBeforeComma: true", 19441 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma); 19442 19443 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 19444 CHECK_PARSE("BreakInheritanceList: AfterComma", BreakInheritanceList, 19445 FormatStyle::BILS_AfterComma); 19446 CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList, 19447 FormatStyle::BILS_BeforeComma); 19448 CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList, 19449 FormatStyle::BILS_AfterColon); 19450 CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList, 19451 FormatStyle::BILS_BeforeColon); 19452 // For backward compatibility: 19453 CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList, 19454 FormatStyle::BILS_BeforeComma); 19455 19456 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 19457 CHECK_PARSE("PackConstructorInitializers: Never", PackConstructorInitializers, 19458 FormatStyle::PCIS_Never); 19459 CHECK_PARSE("PackConstructorInitializers: BinPack", 19460 PackConstructorInitializers, FormatStyle::PCIS_BinPack); 19461 CHECK_PARSE("PackConstructorInitializers: CurrentLine", 19462 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 19463 CHECK_PARSE("PackConstructorInitializers: NextLine", 19464 PackConstructorInitializers, FormatStyle::PCIS_NextLine); 19465 // For backward compatibility: 19466 CHECK_PARSE("BasedOnStyle: Google\n" 19467 "ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 19468 "AllowAllConstructorInitializersOnNextLine: false", 19469 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 19470 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 19471 CHECK_PARSE("BasedOnStyle: Google\n" 19472 "ConstructorInitializerAllOnOneLineOrOnePerLine: false", 19473 PackConstructorInitializers, FormatStyle::PCIS_BinPack); 19474 CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 19475 "AllowAllConstructorInitializersOnNextLine: true", 19476 PackConstructorInitializers, FormatStyle::PCIS_NextLine); 19477 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 19478 CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 19479 "AllowAllConstructorInitializersOnNextLine: false", 19480 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 19481 19482 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 19483 CHECK_PARSE("EmptyLineBeforeAccessModifier: Never", 19484 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never); 19485 CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave", 19486 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave); 19487 CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock", 19488 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock); 19489 CHECK_PARSE("EmptyLineBeforeAccessModifier: Always", 19490 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always); 19491 19492 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 19493 CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket, 19494 FormatStyle::BAS_Align); 19495 CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket, 19496 FormatStyle::BAS_DontAlign); 19497 CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket, 19498 FormatStyle::BAS_AlwaysBreak); 19499 CHECK_PARSE("AlignAfterOpenBracket: BlockIndent", AlignAfterOpenBracket, 19500 FormatStyle::BAS_BlockIndent); 19501 // For backward compatibility: 19502 CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket, 19503 FormatStyle::BAS_DontAlign); 19504 CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket, 19505 FormatStyle::BAS_Align); 19506 19507 Style.AlignEscapedNewlines = FormatStyle::ENAS_Left; 19508 CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines, 19509 FormatStyle::ENAS_DontAlign); 19510 CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines, 19511 FormatStyle::ENAS_Left); 19512 CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines, 19513 FormatStyle::ENAS_Right); 19514 // For backward compatibility: 19515 CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines, 19516 FormatStyle::ENAS_Left); 19517 CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines, 19518 FormatStyle::ENAS_Right); 19519 19520 Style.AlignOperands = FormatStyle::OAS_Align; 19521 CHECK_PARSE("AlignOperands: DontAlign", AlignOperands, 19522 FormatStyle::OAS_DontAlign); 19523 CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align); 19524 CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands, 19525 FormatStyle::OAS_AlignAfterOperator); 19526 // For backward compatibility: 19527 CHECK_PARSE("AlignOperands: false", AlignOperands, 19528 FormatStyle::OAS_DontAlign); 19529 CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align); 19530 19531 Style.UseTab = FormatStyle::UT_ForIndentation; 19532 CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never); 19533 CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation); 19534 CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always); 19535 CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab, 19536 FormatStyle::UT_ForContinuationAndIndentation); 19537 CHECK_PARSE("UseTab: AlignWithSpaces", UseTab, 19538 FormatStyle::UT_AlignWithSpaces); 19539 // For backward compatibility: 19540 CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never); 19541 CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always); 19542 19543 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 19544 CHECK_PARSE("AllowShortBlocksOnASingleLine: Never", 19545 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 19546 CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty", 19547 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty); 19548 CHECK_PARSE("AllowShortBlocksOnASingleLine: Always", 19549 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always); 19550 // For backward compatibility: 19551 CHECK_PARSE("AllowShortBlocksOnASingleLine: false", 19552 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 19553 CHECK_PARSE("AllowShortBlocksOnASingleLine: true", 19554 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always); 19555 19556 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 19557 CHECK_PARSE("AllowShortFunctionsOnASingleLine: None", 19558 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None); 19559 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline", 19560 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline); 19561 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty", 19562 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty); 19563 CHECK_PARSE("AllowShortFunctionsOnASingleLine: All", 19564 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All); 19565 // For backward compatibility: 19566 CHECK_PARSE("AllowShortFunctionsOnASingleLine: false", 19567 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None); 19568 CHECK_PARSE("AllowShortFunctionsOnASingleLine: true", 19569 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All); 19570 19571 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both; 19572 CHECK_PARSE("SpaceAroundPointerQualifiers: Default", 19573 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default); 19574 CHECK_PARSE("SpaceAroundPointerQualifiers: Before", 19575 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before); 19576 CHECK_PARSE("SpaceAroundPointerQualifiers: After", 19577 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After); 19578 CHECK_PARSE("SpaceAroundPointerQualifiers: Both", 19579 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both); 19580 19581 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 19582 CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens, 19583 FormatStyle::SBPO_Never); 19584 CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens, 19585 FormatStyle::SBPO_Always); 19586 CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens, 19587 FormatStyle::SBPO_ControlStatements); 19588 CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptControlMacros", 19589 SpaceBeforeParens, 19590 FormatStyle::SBPO_ControlStatementsExceptControlMacros); 19591 CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens, 19592 FormatStyle::SBPO_NonEmptyParentheses); 19593 CHECK_PARSE("SpaceBeforeParens: Custom", SpaceBeforeParens, 19594 FormatStyle::SBPO_Custom); 19595 // For backward compatibility: 19596 CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens, 19597 FormatStyle::SBPO_Never); 19598 CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens, 19599 FormatStyle::SBPO_ControlStatements); 19600 CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptForEachMacros", 19601 SpaceBeforeParens, 19602 FormatStyle::SBPO_ControlStatementsExceptControlMacros); 19603 19604 Style.ColumnLimit = 123; 19605 FormatStyle BaseStyle = getLLVMStyle(); 19606 CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit); 19607 CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u); 19608 19609 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 19610 CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces, 19611 FormatStyle::BS_Attach); 19612 CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces, 19613 FormatStyle::BS_Linux); 19614 CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces, 19615 FormatStyle::BS_Mozilla); 19616 CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces, 19617 FormatStyle::BS_Stroustrup); 19618 CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces, 19619 FormatStyle::BS_Allman); 19620 CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces, 19621 FormatStyle::BS_Whitesmiths); 19622 CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU); 19623 CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces, 19624 FormatStyle::BS_WebKit); 19625 CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces, 19626 FormatStyle::BS_Custom); 19627 19628 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never; 19629 CHECK_PARSE("BraceWrapping:\n" 19630 " AfterControlStatement: MultiLine", 19631 BraceWrapping.AfterControlStatement, 19632 FormatStyle::BWACS_MultiLine); 19633 CHECK_PARSE("BraceWrapping:\n" 19634 " AfterControlStatement: Always", 19635 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always); 19636 CHECK_PARSE("BraceWrapping:\n" 19637 " AfterControlStatement: Never", 19638 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never); 19639 // For backward compatibility: 19640 CHECK_PARSE("BraceWrapping:\n" 19641 " AfterControlStatement: true", 19642 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always); 19643 CHECK_PARSE("BraceWrapping:\n" 19644 " AfterControlStatement: false", 19645 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never); 19646 19647 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 19648 CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType, 19649 FormatStyle::RTBS_None); 19650 CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType, 19651 FormatStyle::RTBS_All); 19652 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel", 19653 AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel); 19654 CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions", 19655 AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions); 19656 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions", 19657 AlwaysBreakAfterReturnType, 19658 FormatStyle::RTBS_TopLevelDefinitions); 19659 19660 Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 19661 CHECK_PARSE("AlwaysBreakTemplateDeclarations: No", 19662 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No); 19663 CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine", 19664 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine); 19665 CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes", 19666 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes); 19667 CHECK_PARSE("AlwaysBreakTemplateDeclarations: false", 19668 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine); 19669 CHECK_PARSE("AlwaysBreakTemplateDeclarations: true", 19670 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes); 19671 19672 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All; 19673 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None", 19674 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None); 19675 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All", 19676 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All); 19677 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel", 19678 AlwaysBreakAfterDefinitionReturnType, 19679 FormatStyle::DRTBS_TopLevel); 19680 19681 Style.NamespaceIndentation = FormatStyle::NI_All; 19682 CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation, 19683 FormatStyle::NI_None); 19684 CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation, 19685 FormatStyle::NI_Inner); 19686 CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation, 19687 FormatStyle::NI_All); 19688 19689 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_OnlyFirstIf; 19690 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never", 19691 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never); 19692 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse", 19693 AllowShortIfStatementsOnASingleLine, 19694 FormatStyle::SIS_WithoutElse); 19695 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: OnlyFirstIf", 19696 AllowShortIfStatementsOnASingleLine, 19697 FormatStyle::SIS_OnlyFirstIf); 19698 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: AllIfsAndElse", 19699 AllowShortIfStatementsOnASingleLine, 19700 FormatStyle::SIS_AllIfsAndElse); 19701 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always", 19702 AllowShortIfStatementsOnASingleLine, 19703 FormatStyle::SIS_OnlyFirstIf); 19704 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false", 19705 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never); 19706 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true", 19707 AllowShortIfStatementsOnASingleLine, 19708 FormatStyle::SIS_WithoutElse); 19709 19710 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 19711 CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock, 19712 FormatStyle::IEBS_AfterExternBlock); 19713 CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock, 19714 FormatStyle::IEBS_Indent); 19715 CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock, 19716 FormatStyle::IEBS_NoIndent); 19717 CHECK_PARSE("IndentExternBlock: true", IndentExternBlock, 19718 FormatStyle::IEBS_Indent); 19719 CHECK_PARSE("IndentExternBlock: false", IndentExternBlock, 19720 FormatStyle::IEBS_NoIndent); 19721 19722 Style.BitFieldColonSpacing = FormatStyle::BFCS_None; 19723 CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing, 19724 FormatStyle::BFCS_Both); 19725 CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing, 19726 FormatStyle::BFCS_None); 19727 CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing, 19728 FormatStyle::BFCS_Before); 19729 CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing, 19730 FormatStyle::BFCS_After); 19731 19732 Style.SortJavaStaticImport = FormatStyle::SJSIO_Before; 19733 CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport, 19734 FormatStyle::SJSIO_After); 19735 CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport, 19736 FormatStyle::SJSIO_Before); 19737 19738 // FIXME: This is required because parsing a configuration simply overwrites 19739 // the first N elements of the list instead of resetting it. 19740 Style.ForEachMacros.clear(); 19741 std::vector<std::string> BoostForeach; 19742 BoostForeach.push_back("BOOST_FOREACH"); 19743 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach); 19744 std::vector<std::string> BoostAndQForeach; 19745 BoostAndQForeach.push_back("BOOST_FOREACH"); 19746 BoostAndQForeach.push_back("Q_FOREACH"); 19747 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros, 19748 BoostAndQForeach); 19749 19750 Style.IfMacros.clear(); 19751 std::vector<std::string> CustomIfs; 19752 CustomIfs.push_back("MYIF"); 19753 CHECK_PARSE("IfMacros: [MYIF]", IfMacros, CustomIfs); 19754 19755 Style.AttributeMacros.clear(); 19756 CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros, 19757 std::vector<std::string>{"__capability"}); 19758 CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros, 19759 std::vector<std::string>({"attr1", "attr2"})); 19760 19761 Style.StatementAttributeLikeMacros.clear(); 19762 CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]", 19763 StatementAttributeLikeMacros, 19764 std::vector<std::string>({"emit", "Q_EMIT"})); 19765 19766 Style.StatementMacros.clear(); 19767 CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros, 19768 std::vector<std::string>{"QUNUSED"}); 19769 CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros, 19770 std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"})); 19771 19772 Style.NamespaceMacros.clear(); 19773 CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros, 19774 std::vector<std::string>{"TESTSUITE"}); 19775 CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros, 19776 std::vector<std::string>({"TESTSUITE", "SUITE"})); 19777 19778 Style.WhitespaceSensitiveMacros.clear(); 19779 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]", 19780 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"}); 19781 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]", 19782 WhitespaceSensitiveMacros, 19783 std::vector<std::string>({"STRINGIZE", "ASSERT"})); 19784 Style.WhitespaceSensitiveMacros.clear(); 19785 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']", 19786 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"}); 19787 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']", 19788 WhitespaceSensitiveMacros, 19789 std::vector<std::string>({"STRINGIZE", "ASSERT"})); 19790 19791 Style.IncludeStyle.IncludeCategories.clear(); 19792 std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = { 19793 {"abc/.*", 2, 0, false}, {".*", 1, 0, true}}; 19794 CHECK_PARSE("IncludeCategories:\n" 19795 " - Regex: abc/.*\n" 19796 " Priority: 2\n" 19797 " - Regex: .*\n" 19798 " Priority: 1\n" 19799 " CaseSensitive: true\n", 19800 IncludeStyle.IncludeCategories, ExpectedCategories); 19801 CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex, 19802 "abc$"); 19803 CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'", 19804 IncludeStyle.IncludeIsMainSourceRegex, "abc$"); 19805 19806 Style.SortIncludes = FormatStyle::SI_Never; 19807 CHECK_PARSE("SortIncludes: true", SortIncludes, 19808 FormatStyle::SI_CaseSensitive); 19809 CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never); 19810 CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes, 19811 FormatStyle::SI_CaseInsensitive); 19812 CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes, 19813 FormatStyle::SI_CaseSensitive); 19814 CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never); 19815 19816 Style.RawStringFormats.clear(); 19817 std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = { 19818 { 19819 FormatStyle::LK_TextProto, 19820 {"pb", "proto"}, 19821 {"PARSE_TEXT_PROTO"}, 19822 /*CanonicalDelimiter=*/"", 19823 "llvm", 19824 }, 19825 { 19826 FormatStyle::LK_Cpp, 19827 {"cc", "cpp"}, 19828 {"C_CODEBLOCK", "CPPEVAL"}, 19829 /*CanonicalDelimiter=*/"cc", 19830 /*BasedOnStyle=*/"", 19831 }, 19832 }; 19833 19834 CHECK_PARSE("RawStringFormats:\n" 19835 " - Language: TextProto\n" 19836 " Delimiters:\n" 19837 " - 'pb'\n" 19838 " - 'proto'\n" 19839 " EnclosingFunctions:\n" 19840 " - 'PARSE_TEXT_PROTO'\n" 19841 " BasedOnStyle: llvm\n" 19842 " - Language: Cpp\n" 19843 " Delimiters:\n" 19844 " - 'cc'\n" 19845 " - 'cpp'\n" 19846 " EnclosingFunctions:\n" 19847 " - 'C_CODEBLOCK'\n" 19848 " - 'CPPEVAL'\n" 19849 " CanonicalDelimiter: 'cc'", 19850 RawStringFormats, ExpectedRawStringFormats); 19851 19852 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 19853 " Minimum: 0\n" 19854 " Maximum: 0", 19855 SpacesInLineCommentPrefix.Minimum, 0u); 19856 EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u); 19857 Style.SpacesInLineCommentPrefix.Minimum = 1; 19858 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 19859 " Minimum: 2", 19860 SpacesInLineCommentPrefix.Minimum, 0u); 19861 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 19862 " Maximum: -1", 19863 SpacesInLineCommentPrefix.Maximum, -1u); 19864 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 19865 " Minimum: 2", 19866 SpacesInLineCommentPrefix.Minimum, 2u); 19867 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 19868 " Maximum: 1", 19869 SpacesInLineCommentPrefix.Maximum, 1u); 19870 EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u); 19871 19872 Style.SpacesInAngles = FormatStyle::SIAS_Always; 19873 CHECK_PARSE("SpacesInAngles: Never", SpacesInAngles, FormatStyle::SIAS_Never); 19874 CHECK_PARSE("SpacesInAngles: Always", SpacesInAngles, 19875 FormatStyle::SIAS_Always); 19876 CHECK_PARSE("SpacesInAngles: Leave", SpacesInAngles, FormatStyle::SIAS_Leave); 19877 // For backward compatibility: 19878 CHECK_PARSE("SpacesInAngles: false", SpacesInAngles, FormatStyle::SIAS_Never); 19879 CHECK_PARSE("SpacesInAngles: true", SpacesInAngles, FormatStyle::SIAS_Always); 19880 } 19881 19882 TEST_F(FormatTest, ParsesConfigurationWithLanguages) { 19883 FormatStyle Style = {}; 19884 Style.Language = FormatStyle::LK_Cpp; 19885 CHECK_PARSE("Language: Cpp\n" 19886 "IndentWidth: 12", 19887 IndentWidth, 12u); 19888 EXPECT_EQ(parseConfiguration("Language: JavaScript\n" 19889 "IndentWidth: 34", 19890 &Style), 19891 ParseError::Unsuitable); 19892 FormatStyle BinPackedTCS = {}; 19893 BinPackedTCS.Language = FormatStyle::LK_JavaScript; 19894 EXPECT_EQ(parseConfiguration("BinPackArguments: true\n" 19895 "InsertTrailingCommas: Wrapped", 19896 &BinPackedTCS), 19897 ParseError::BinPackTrailingCommaConflict); 19898 EXPECT_EQ(12u, Style.IndentWidth); 19899 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u); 19900 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language); 19901 19902 Style.Language = FormatStyle::LK_JavaScript; 19903 CHECK_PARSE("Language: JavaScript\n" 19904 "IndentWidth: 12", 19905 IndentWidth, 12u); 19906 CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u); 19907 EXPECT_EQ(parseConfiguration("Language: Cpp\n" 19908 "IndentWidth: 34", 19909 &Style), 19910 ParseError::Unsuitable); 19911 EXPECT_EQ(23u, Style.IndentWidth); 19912 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u); 19913 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language); 19914 19915 CHECK_PARSE("BasedOnStyle: LLVM\n" 19916 "IndentWidth: 67", 19917 IndentWidth, 67u); 19918 19919 CHECK_PARSE("---\n" 19920 "Language: JavaScript\n" 19921 "IndentWidth: 12\n" 19922 "---\n" 19923 "Language: Cpp\n" 19924 "IndentWidth: 34\n" 19925 "...\n", 19926 IndentWidth, 12u); 19927 19928 Style.Language = FormatStyle::LK_Cpp; 19929 CHECK_PARSE("---\n" 19930 "Language: JavaScript\n" 19931 "IndentWidth: 12\n" 19932 "---\n" 19933 "Language: Cpp\n" 19934 "IndentWidth: 34\n" 19935 "...\n", 19936 IndentWidth, 34u); 19937 CHECK_PARSE("---\n" 19938 "IndentWidth: 78\n" 19939 "---\n" 19940 "Language: JavaScript\n" 19941 "IndentWidth: 56\n" 19942 "...\n", 19943 IndentWidth, 78u); 19944 19945 Style.ColumnLimit = 123; 19946 Style.IndentWidth = 234; 19947 Style.BreakBeforeBraces = FormatStyle::BS_Linux; 19948 Style.TabWidth = 345; 19949 EXPECT_FALSE(parseConfiguration("---\n" 19950 "IndentWidth: 456\n" 19951 "BreakBeforeBraces: Allman\n" 19952 "---\n" 19953 "Language: JavaScript\n" 19954 "IndentWidth: 111\n" 19955 "TabWidth: 111\n" 19956 "---\n" 19957 "Language: Cpp\n" 19958 "BreakBeforeBraces: Stroustrup\n" 19959 "TabWidth: 789\n" 19960 "...\n", 19961 &Style)); 19962 EXPECT_EQ(123u, Style.ColumnLimit); 19963 EXPECT_EQ(456u, Style.IndentWidth); 19964 EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces); 19965 EXPECT_EQ(789u, Style.TabWidth); 19966 19967 EXPECT_EQ(parseConfiguration("---\n" 19968 "Language: JavaScript\n" 19969 "IndentWidth: 56\n" 19970 "---\n" 19971 "IndentWidth: 78\n" 19972 "...\n", 19973 &Style), 19974 ParseError::Error); 19975 EXPECT_EQ(parseConfiguration("---\n" 19976 "Language: JavaScript\n" 19977 "IndentWidth: 56\n" 19978 "---\n" 19979 "Language: JavaScript\n" 19980 "IndentWidth: 78\n" 19981 "...\n", 19982 &Style), 19983 ParseError::Error); 19984 19985 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language); 19986 } 19987 19988 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) { 19989 FormatStyle Style = {}; 19990 Style.Language = FormatStyle::LK_JavaScript; 19991 Style.BreakBeforeTernaryOperators = true; 19992 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value()); 19993 EXPECT_FALSE(Style.BreakBeforeTernaryOperators); 19994 19995 Style.BreakBeforeTernaryOperators = true; 19996 EXPECT_EQ(0, parseConfiguration("---\n" 19997 "BasedOnStyle: Google\n" 19998 "---\n" 19999 "Language: JavaScript\n" 20000 "IndentWidth: 76\n" 20001 "...\n", 20002 &Style) 20003 .value()); 20004 EXPECT_FALSE(Style.BreakBeforeTernaryOperators); 20005 EXPECT_EQ(76u, Style.IndentWidth); 20006 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language); 20007 } 20008 20009 TEST_F(FormatTest, ConfigurationRoundTripTest) { 20010 FormatStyle Style = getLLVMStyle(); 20011 std::string YAML = configurationAsText(Style); 20012 FormatStyle ParsedStyle = {}; 20013 ParsedStyle.Language = FormatStyle::LK_Cpp; 20014 EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value()); 20015 EXPECT_EQ(Style, ParsedStyle); 20016 } 20017 20018 TEST_F(FormatTest, WorksFor8bitEncodings) { 20019 EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n" 20020 "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n" 20021 "\"\xe7\xe8\xec\xed\xfe\xfe \"\n" 20022 "\"\xef\xee\xf0\xf3...\"", 20023 format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 " 20024 "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe " 20025 "\xef\xee\xf0\xf3...\"", 20026 getLLVMStyleWithColumns(12))); 20027 } 20028 20029 TEST_F(FormatTest, HandlesUTF8BOM) { 20030 EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf")); 20031 EXPECT_EQ("\xef\xbb\xbf#include <iostream>", 20032 format("\xef\xbb\xbf#include <iostream>")); 20033 EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>", 20034 format("\xef\xbb\xbf\n#include <iostream>")); 20035 } 20036 20037 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers. 20038 #if !defined(_MSC_VER) 20039 20040 TEST_F(FormatTest, CountsUTF8CharactersProperly) { 20041 verifyFormat("\"Однажды в студёную зимнюю пору...\"", 20042 getLLVMStyleWithColumns(35)); 20043 verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"", 20044 getLLVMStyleWithColumns(31)); 20045 verifyFormat("// Однажды в студёную зимнюю пору...", 20046 getLLVMStyleWithColumns(36)); 20047 verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32)); 20048 verifyFormat("/* Однажды в студёную зимнюю пору... */", 20049 getLLVMStyleWithColumns(39)); 20050 verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */", 20051 getLLVMStyleWithColumns(35)); 20052 } 20053 20054 TEST_F(FormatTest, SplitsUTF8Strings) { 20055 // Non-printable characters' width is currently considered to be the length in 20056 // bytes in UTF8. The characters can be displayed in very different manner 20057 // (zero-width, single width with a substitution glyph, expanded to their code 20058 // (e.g. "<8d>"), so there's no single correct way to handle them. 20059 EXPECT_EQ("\"aaaaÄ\"\n" 20060 "\"\xc2\x8d\";", 20061 format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10))); 20062 EXPECT_EQ("\"aaaaaaaÄ\"\n" 20063 "\"\xc2\x8d\";", 20064 format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10))); 20065 EXPECT_EQ("\"Однажды, в \"\n" 20066 "\"студёную \"\n" 20067 "\"зимнюю \"\n" 20068 "\"пору,\"", 20069 format("\"Однажды, в студёную зимнюю пору,\"", 20070 getLLVMStyleWithColumns(13))); 20071 EXPECT_EQ( 20072 "\"一 二 三 \"\n" 20073 "\"四 五六 \"\n" 20074 "\"七 八 九 \"\n" 20075 "\"十\"", 20076 format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11))); 20077 EXPECT_EQ("\"一\t\"\n" 20078 "\"二 \t\"\n" 20079 "\"三 四 \"\n" 20080 "\"五\t\"\n" 20081 "\"六 \t\"\n" 20082 "\"七 \"\n" 20083 "\"八九十\tqq\"", 20084 format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"", 20085 getLLVMStyleWithColumns(11))); 20086 20087 // UTF8 character in an escape sequence. 20088 EXPECT_EQ("\"aaaaaa\"\n" 20089 "\"\\\xC2\x8D\"", 20090 format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10))); 20091 } 20092 20093 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) { 20094 EXPECT_EQ("const char *sssss =\n" 20095 " \"一二三四五六七八\\\n" 20096 " 九 十\";", 20097 format("const char *sssss = \"一二三四五六七八\\\n" 20098 " 九 十\";", 20099 getLLVMStyleWithColumns(30))); 20100 } 20101 20102 TEST_F(FormatTest, SplitsUTF8LineComments) { 20103 EXPECT_EQ("// aaaaÄ\xc2\x8d", 20104 format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10))); 20105 EXPECT_EQ("// Я из лесу\n" 20106 "// вышел; был\n" 20107 "// сильный\n" 20108 "// мороз.", 20109 format("// Я из лесу вышел; был сильный мороз.", 20110 getLLVMStyleWithColumns(13))); 20111 EXPECT_EQ("// 一二三\n" 20112 "// 四五六七\n" 20113 "// 八 九\n" 20114 "// 十", 20115 format("// 一二三 四五六七 八 九 十", getLLVMStyleWithColumns(9))); 20116 } 20117 20118 TEST_F(FormatTest, SplitsUTF8BlockComments) { 20119 EXPECT_EQ("/* Гляжу,\n" 20120 " * поднимается\n" 20121 " * медленно в\n" 20122 " * гору\n" 20123 " * Лошадка,\n" 20124 " * везущая\n" 20125 " * хворосту\n" 20126 " * воз. */", 20127 format("/* Гляжу, поднимается медленно в гору\n" 20128 " * Лошадка, везущая хворосту воз. */", 20129 getLLVMStyleWithColumns(13))); 20130 EXPECT_EQ( 20131 "/* 一二三\n" 20132 " * 四五六七\n" 20133 " * 八 九\n" 20134 " * 十 */", 20135 format("/* 一二三 四五六七 八 九 十 */", getLLVMStyleWithColumns(9))); 20136 EXPECT_EQ("/* \n" 20137 " * \n" 20138 " * - */", 20139 format("/* - */", getLLVMStyleWithColumns(12))); 20140 } 20141 20142 #endif // _MSC_VER 20143 20144 TEST_F(FormatTest, ConstructorInitializerIndentWidth) { 20145 FormatStyle Style = getLLVMStyle(); 20146 20147 Style.ConstructorInitializerIndentWidth = 4; 20148 verifyFormat( 20149 "SomeClass::Constructor()\n" 20150 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20151 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20152 Style); 20153 20154 Style.ConstructorInitializerIndentWidth = 2; 20155 verifyFormat( 20156 "SomeClass::Constructor()\n" 20157 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20158 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20159 Style); 20160 20161 Style.ConstructorInitializerIndentWidth = 0; 20162 verifyFormat( 20163 "SomeClass::Constructor()\n" 20164 ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20165 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20166 Style); 20167 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 20168 verifyFormat( 20169 "SomeLongTemplateVariableName<\n" 20170 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>", 20171 Style); 20172 verifyFormat("bool smaller = 1 < " 20173 "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 20174 " " 20175 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 20176 Style); 20177 20178 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 20179 verifyFormat("SomeClass::Constructor() :\n" 20180 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n" 20181 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}", 20182 Style); 20183 } 20184 20185 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) { 20186 FormatStyle Style = getLLVMStyle(); 20187 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 20188 Style.ConstructorInitializerIndentWidth = 4; 20189 verifyFormat("SomeClass::Constructor()\n" 20190 " : a(a)\n" 20191 " , b(b)\n" 20192 " , c(c) {}", 20193 Style); 20194 verifyFormat("SomeClass::Constructor()\n" 20195 " : a(a) {}", 20196 Style); 20197 20198 Style.ColumnLimit = 0; 20199 verifyFormat("SomeClass::Constructor()\n" 20200 " : a(a) {}", 20201 Style); 20202 verifyFormat("SomeClass::Constructor() noexcept\n" 20203 " : a(a) {}", 20204 Style); 20205 verifyFormat("SomeClass::Constructor()\n" 20206 " : a(a)\n" 20207 " , b(b)\n" 20208 " , c(c) {}", 20209 Style); 20210 verifyFormat("SomeClass::Constructor()\n" 20211 " : a(a) {\n" 20212 " foo();\n" 20213 " bar();\n" 20214 "}", 20215 Style); 20216 20217 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 20218 verifyFormat("SomeClass::Constructor()\n" 20219 " : a(a)\n" 20220 " , b(b)\n" 20221 " , c(c) {\n}", 20222 Style); 20223 verifyFormat("SomeClass::Constructor()\n" 20224 " : a(a) {\n}", 20225 Style); 20226 20227 Style.ColumnLimit = 80; 20228 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 20229 Style.ConstructorInitializerIndentWidth = 2; 20230 verifyFormat("SomeClass::Constructor()\n" 20231 " : a(a)\n" 20232 " , b(b)\n" 20233 " , c(c) {}", 20234 Style); 20235 20236 Style.ConstructorInitializerIndentWidth = 0; 20237 verifyFormat("SomeClass::Constructor()\n" 20238 ": a(a)\n" 20239 ", b(b)\n" 20240 ", c(c) {}", 20241 Style); 20242 20243 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 20244 Style.ConstructorInitializerIndentWidth = 4; 20245 verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style); 20246 verifyFormat( 20247 "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n", 20248 Style); 20249 verifyFormat( 20250 "SomeClass::Constructor()\n" 20251 " : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}", 20252 Style); 20253 Style.ConstructorInitializerIndentWidth = 4; 20254 Style.ColumnLimit = 60; 20255 verifyFormat("SomeClass::Constructor()\n" 20256 " : aaaaaaaa(aaaaaaaa)\n" 20257 " , aaaaaaaa(aaaaaaaa)\n" 20258 " , aaaaaaaa(aaaaaaaa) {}", 20259 Style); 20260 } 20261 20262 TEST_F(FormatTest, ConstructorInitializersWithPreprocessorDirective) { 20263 FormatStyle Style = getLLVMStyle(); 20264 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 20265 Style.ConstructorInitializerIndentWidth = 4; 20266 verifyFormat("SomeClass::Constructor()\n" 20267 " : a{a}\n" 20268 " , b{b} {}", 20269 Style); 20270 verifyFormat("SomeClass::Constructor()\n" 20271 " : a{a}\n" 20272 "#if CONDITION\n" 20273 " , b{b}\n" 20274 "#endif\n" 20275 "{\n}", 20276 Style); 20277 Style.ConstructorInitializerIndentWidth = 2; 20278 verifyFormat("SomeClass::Constructor()\n" 20279 "#if CONDITION\n" 20280 " : a{a}\n" 20281 "#endif\n" 20282 " , b{b}\n" 20283 " , c{c} {\n}", 20284 Style); 20285 Style.ConstructorInitializerIndentWidth = 0; 20286 verifyFormat("SomeClass::Constructor()\n" 20287 ": a{a}\n" 20288 "#ifdef CONDITION\n" 20289 ", b{b}\n" 20290 "#else\n" 20291 ", c{c}\n" 20292 "#endif\n" 20293 ", d{d} {\n}", 20294 Style); 20295 Style.ConstructorInitializerIndentWidth = 4; 20296 verifyFormat("SomeClass::Constructor()\n" 20297 " : a{a}\n" 20298 "#if WINDOWS\n" 20299 "#if DEBUG\n" 20300 " , b{0}\n" 20301 "#else\n" 20302 " , b{1}\n" 20303 "#endif\n" 20304 "#else\n" 20305 "#if DEBUG\n" 20306 " , b{2}\n" 20307 "#else\n" 20308 " , b{3}\n" 20309 "#endif\n" 20310 "#endif\n" 20311 "{\n}", 20312 Style); 20313 verifyFormat("SomeClass::Constructor()\n" 20314 " : a{a}\n" 20315 "#if WINDOWS\n" 20316 " , b{0}\n" 20317 "#if DEBUG\n" 20318 " , c{0}\n" 20319 "#else\n" 20320 " , c{1}\n" 20321 "#endif\n" 20322 "#else\n" 20323 "#if DEBUG\n" 20324 " , c{2}\n" 20325 "#else\n" 20326 " , c{3}\n" 20327 "#endif\n" 20328 " , b{1}\n" 20329 "#endif\n" 20330 "{\n}", 20331 Style); 20332 } 20333 20334 TEST_F(FormatTest, Destructors) { 20335 verifyFormat("void F(int &i) { i.~int(); }"); 20336 verifyFormat("void F(int &i) { i->~int(); }"); 20337 } 20338 20339 TEST_F(FormatTest, FormatsWithWebKitStyle) { 20340 FormatStyle Style = getWebKitStyle(); 20341 20342 // Don't indent in outer namespaces. 20343 verifyFormat("namespace outer {\n" 20344 "int i;\n" 20345 "namespace inner {\n" 20346 " int i;\n" 20347 "} // namespace inner\n" 20348 "} // namespace outer\n" 20349 "namespace other_outer {\n" 20350 "int i;\n" 20351 "}", 20352 Style); 20353 20354 // Don't indent case labels. 20355 verifyFormat("switch (variable) {\n" 20356 "case 1:\n" 20357 "case 2:\n" 20358 " doSomething();\n" 20359 " break;\n" 20360 "default:\n" 20361 " ++variable;\n" 20362 "}", 20363 Style); 20364 20365 // Wrap before binary operators. 20366 EXPECT_EQ("void f()\n" 20367 "{\n" 20368 " if (aaaaaaaaaaaaaaaa\n" 20369 " && bbbbbbbbbbbbbbbbbbbbbbbb\n" 20370 " && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n" 20371 " return;\n" 20372 "}", 20373 format("void f() {\n" 20374 "if (aaaaaaaaaaaaaaaa\n" 20375 "&& bbbbbbbbbbbbbbbbbbbbbbbb\n" 20376 "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n" 20377 "return;\n" 20378 "}", 20379 Style)); 20380 20381 // Allow functions on a single line. 20382 verifyFormat("void f() { return; }", Style); 20383 20384 // Allow empty blocks on a single line and insert a space in empty blocks. 20385 EXPECT_EQ("void f() { }", format("void f() {}", Style)); 20386 EXPECT_EQ("while (true) { }", format("while (true) {}", Style)); 20387 // However, don't merge non-empty short loops. 20388 EXPECT_EQ("while (true) {\n" 20389 " continue;\n" 20390 "}", 20391 format("while (true) { continue; }", Style)); 20392 20393 // Constructor initializers are formatted one per line with the "," on the 20394 // new line. 20395 verifyFormat("Constructor()\n" 20396 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 20397 " , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n" 20398 " aaaaaaaaaaaaaa)\n" 20399 " , aaaaaaaaaaaaaaaaaaaaaaa()\n" 20400 "{\n" 20401 "}", 20402 Style); 20403 verifyFormat("SomeClass::Constructor()\n" 20404 " : a(a)\n" 20405 "{\n" 20406 "}", 20407 Style); 20408 EXPECT_EQ("SomeClass::Constructor()\n" 20409 " : a(a)\n" 20410 "{\n" 20411 "}", 20412 format("SomeClass::Constructor():a(a){}", Style)); 20413 verifyFormat("SomeClass::Constructor()\n" 20414 " : a(a)\n" 20415 " , b(b)\n" 20416 " , c(c)\n" 20417 "{\n" 20418 "}", 20419 Style); 20420 verifyFormat("SomeClass::Constructor()\n" 20421 " : a(a)\n" 20422 "{\n" 20423 " foo();\n" 20424 " bar();\n" 20425 "}", 20426 Style); 20427 20428 // Access specifiers should be aligned left. 20429 verifyFormat("class C {\n" 20430 "public:\n" 20431 " int i;\n" 20432 "};", 20433 Style); 20434 20435 // Do not align comments. 20436 verifyFormat("int a; // Do not\n" 20437 "double b; // align comments.", 20438 Style); 20439 20440 // Do not align operands. 20441 EXPECT_EQ("ASSERT(aaaa\n" 20442 " || bbbb);", 20443 format("ASSERT ( aaaa\n||bbbb);", Style)); 20444 20445 // Accept input's line breaks. 20446 EXPECT_EQ("if (aaaaaaaaaaaaaaa\n" 20447 " || bbbbbbbbbbbbbbb) {\n" 20448 " i++;\n" 20449 "}", 20450 format("if (aaaaaaaaaaaaaaa\n" 20451 "|| bbbbbbbbbbbbbbb) { i++; }", 20452 Style)); 20453 EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n" 20454 " i++;\n" 20455 "}", 20456 format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style)); 20457 20458 // Don't automatically break all macro definitions (llvm.org/PR17842). 20459 verifyFormat("#define aNumber 10", Style); 20460 // However, generally keep the line breaks that the user authored. 20461 EXPECT_EQ("#define aNumber \\\n" 20462 " 10", 20463 format("#define aNumber \\\n" 20464 " 10", 20465 Style)); 20466 20467 // Keep empty and one-element array literals on a single line. 20468 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n" 20469 " copyItems:YES];", 20470 format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n" 20471 "copyItems:YES];", 20472 Style)); 20473 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n" 20474 " copyItems:YES];", 20475 format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n" 20476 " copyItems:YES];", 20477 Style)); 20478 // FIXME: This does not seem right, there should be more indentation before 20479 // the array literal's entries. Nested blocks have the same problem. 20480 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n" 20481 " @\"a\",\n" 20482 " @\"a\"\n" 20483 "]\n" 20484 " copyItems:YES];", 20485 format("NSArray* a = [[NSArray alloc] initWithArray:@[\n" 20486 " @\"a\",\n" 20487 " @\"a\"\n" 20488 " ]\n" 20489 " copyItems:YES];", 20490 Style)); 20491 EXPECT_EQ( 20492 "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n" 20493 " copyItems:YES];", 20494 format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n" 20495 " copyItems:YES];", 20496 Style)); 20497 20498 verifyFormat("[self.a b:c c:d];", Style); 20499 EXPECT_EQ("[self.a b:c\n" 20500 " c:d];", 20501 format("[self.a b:c\n" 20502 "c:d];", 20503 Style)); 20504 } 20505 20506 TEST_F(FormatTest, FormatsLambdas) { 20507 verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n"); 20508 verifyFormat( 20509 "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n"); 20510 verifyFormat("int c = [&] { [=] { return b++; }(); }();\n"); 20511 verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n"); 20512 verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n"); 20513 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n"); 20514 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n"); 20515 verifyFormat("auto c = [a = [b = 42] {}] {};\n"); 20516 verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n"); 20517 verifyFormat("int x = f(*+[] {});"); 20518 verifyFormat("void f() {\n" 20519 " other(x.begin(), x.end(), [&](int, int) { return 1; });\n" 20520 "}\n"); 20521 verifyFormat("void f() {\n" 20522 " other(x.begin(), //\n" 20523 " x.end(), //\n" 20524 " [&](int, int) { return 1; });\n" 20525 "}\n"); 20526 verifyFormat("void f() {\n" 20527 " other.other.other.other.other(\n" 20528 " x.begin(), x.end(),\n" 20529 " [something, rather](int, int, int, int, int, int, int) { " 20530 "return 1; });\n" 20531 "}\n"); 20532 verifyFormat( 20533 "void f() {\n" 20534 " other.other.other.other.other(\n" 20535 " x.begin(), x.end(),\n" 20536 " [something, rather](int, int, int, int, int, int, int) {\n" 20537 " //\n" 20538 " });\n" 20539 "}\n"); 20540 verifyFormat("SomeFunction([]() { // A cool function...\n" 20541 " return 43;\n" 20542 "});"); 20543 EXPECT_EQ("SomeFunction([]() {\n" 20544 "#define A a\n" 20545 " return 43;\n" 20546 "});", 20547 format("SomeFunction([](){\n" 20548 "#define A a\n" 20549 "return 43;\n" 20550 "});")); 20551 verifyFormat("void f() {\n" 20552 " SomeFunction([](decltype(x), A *a) {});\n" 20553 " SomeFunction([](typeof(x), A *a) {});\n" 20554 " SomeFunction([](_Atomic(x), A *a) {});\n" 20555 " SomeFunction([](__underlying_type(x), A *a) {});\n" 20556 "}"); 20557 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 20558 " [](const aaaaaaaaaa &a) { return a; });"); 20559 verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n" 20560 " SomeOtherFunctioooooooooooooooooooooooooon();\n" 20561 "});"); 20562 verifyFormat("Constructor()\n" 20563 " : Field([] { // comment\n" 20564 " int i;\n" 20565 " }) {}"); 20566 verifyFormat("auto my_lambda = [](const string &some_parameter) {\n" 20567 " return some_parameter.size();\n" 20568 "};"); 20569 verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n" 20570 " [](const string &s) { return s; };"); 20571 verifyFormat("int i = aaaaaa ? 1 //\n" 20572 " : [] {\n" 20573 " return 2; //\n" 20574 " }();"); 20575 verifyFormat("llvm::errs() << \"number of twos is \"\n" 20576 " << std::count_if(v.begin(), v.end(), [](int x) {\n" 20577 " return x == 2; // force break\n" 20578 " });"); 20579 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 20580 " [=](int iiiiiiiiiiii) {\n" 20581 " return aaaaaaaaaaaaaaaaaaaaaaa !=\n" 20582 " aaaaaaaaaaaaaaaaaaaaaaa;\n" 20583 " });", 20584 getLLVMStyleWithColumns(60)); 20585 20586 verifyFormat("SomeFunction({[&] {\n" 20587 " // comment\n" 20588 " },\n" 20589 " [&] {\n" 20590 " // comment\n" 20591 " }});"); 20592 verifyFormat("SomeFunction({[&] {\n" 20593 " // comment\n" 20594 "}});"); 20595 verifyFormat( 20596 "virtual aaaaaaaaaaaaaaaa(\n" 20597 " std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n" 20598 " aaaaa aaaaaaaaa);"); 20599 20600 // Lambdas with return types. 20601 verifyFormat("int c = []() -> int { return 2; }();\n"); 20602 verifyFormat("int c = []() -> int * { return 2; }();\n"); 20603 verifyFormat("int c = []() -> vector<int> { return {2}; }();\n"); 20604 verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());"); 20605 verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};"); 20606 verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};"); 20607 verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};"); 20608 verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};"); 20609 verifyFormat("[a, a]() -> a<1> {};"); 20610 verifyFormat("[]() -> foo<5 + 2> { return {}; };"); 20611 verifyFormat("[]() -> foo<5 - 2> { return {}; };"); 20612 verifyFormat("[]() -> foo<5 / 2> { return {}; };"); 20613 verifyFormat("[]() -> foo<5 * 2> { return {}; };"); 20614 verifyFormat("[]() -> foo<5 % 2> { return {}; };"); 20615 verifyFormat("[]() -> foo<5 << 2> { return {}; };"); 20616 verifyFormat("[]() -> foo<!5> { return {}; };"); 20617 verifyFormat("[]() -> foo<~5> { return {}; };"); 20618 verifyFormat("[]() -> foo<5 | 2> { return {}; };"); 20619 verifyFormat("[]() -> foo<5 || 2> { return {}; };"); 20620 verifyFormat("[]() -> foo<5 & 2> { return {}; };"); 20621 verifyFormat("[]() -> foo<5 && 2> { return {}; };"); 20622 verifyFormat("[]() -> foo<5 == 2> { return {}; };"); 20623 verifyFormat("[]() -> foo<5 != 2> { return {}; };"); 20624 verifyFormat("[]() -> foo<5 >= 2> { return {}; };"); 20625 verifyFormat("[]() -> foo<5 <= 2> { return {}; };"); 20626 verifyFormat("[]() -> foo<5 < 2> { return {}; };"); 20627 verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };"); 20628 verifyFormat("namespace bar {\n" 20629 "// broken:\n" 20630 "auto foo{[]() -> foo<5 + 2> { return {}; }};\n" 20631 "} // namespace bar"); 20632 verifyFormat("namespace bar {\n" 20633 "// broken:\n" 20634 "auto foo{[]() -> foo<5 - 2> { return {}; }};\n" 20635 "} // namespace bar"); 20636 verifyFormat("namespace bar {\n" 20637 "// broken:\n" 20638 "auto foo{[]() -> foo<5 / 2> { return {}; }};\n" 20639 "} // namespace bar"); 20640 verifyFormat("namespace bar {\n" 20641 "// broken:\n" 20642 "auto foo{[]() -> foo<5 * 2> { return {}; }};\n" 20643 "} // namespace bar"); 20644 verifyFormat("namespace bar {\n" 20645 "// broken:\n" 20646 "auto foo{[]() -> foo<5 % 2> { return {}; }};\n" 20647 "} // namespace bar"); 20648 verifyFormat("namespace bar {\n" 20649 "// broken:\n" 20650 "auto foo{[]() -> foo<5 << 2> { return {}; }};\n" 20651 "} // namespace bar"); 20652 verifyFormat("namespace bar {\n" 20653 "// broken:\n" 20654 "auto foo{[]() -> foo<!5> { return {}; }};\n" 20655 "} // namespace bar"); 20656 verifyFormat("namespace bar {\n" 20657 "// broken:\n" 20658 "auto foo{[]() -> foo<~5> { return {}; }};\n" 20659 "} // namespace bar"); 20660 verifyFormat("namespace bar {\n" 20661 "// broken:\n" 20662 "auto foo{[]() -> foo<5 | 2> { return {}; }};\n" 20663 "} // namespace bar"); 20664 verifyFormat("namespace bar {\n" 20665 "// broken:\n" 20666 "auto foo{[]() -> foo<5 || 2> { return {}; }};\n" 20667 "} // namespace bar"); 20668 verifyFormat("namespace bar {\n" 20669 "// broken:\n" 20670 "auto foo{[]() -> foo<5 & 2> { return {}; }};\n" 20671 "} // namespace bar"); 20672 verifyFormat("namespace bar {\n" 20673 "// broken:\n" 20674 "auto foo{[]() -> foo<5 && 2> { return {}; }};\n" 20675 "} // namespace bar"); 20676 verifyFormat("namespace bar {\n" 20677 "// broken:\n" 20678 "auto foo{[]() -> foo<5 == 2> { return {}; }};\n" 20679 "} // namespace bar"); 20680 verifyFormat("namespace bar {\n" 20681 "// broken:\n" 20682 "auto foo{[]() -> foo<5 != 2> { return {}; }};\n" 20683 "} // namespace bar"); 20684 verifyFormat("namespace bar {\n" 20685 "// broken:\n" 20686 "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n" 20687 "} // namespace bar"); 20688 verifyFormat("namespace bar {\n" 20689 "// broken:\n" 20690 "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n" 20691 "} // namespace bar"); 20692 verifyFormat("namespace bar {\n" 20693 "// broken:\n" 20694 "auto foo{[]() -> foo<5 < 2> { return {}; }};\n" 20695 "} // namespace bar"); 20696 verifyFormat("namespace bar {\n" 20697 "// broken:\n" 20698 "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n" 20699 "} // namespace bar"); 20700 verifyFormat("[]() -> a<1> {};"); 20701 verifyFormat("[]() -> a<1> { ; };"); 20702 verifyFormat("[]() -> a<1> { ; }();"); 20703 verifyFormat("[a, a]() -> a<true> {};"); 20704 verifyFormat("[]() -> a<true> {};"); 20705 verifyFormat("[]() -> a<true> { ; };"); 20706 verifyFormat("[]() -> a<true> { ; }();"); 20707 verifyFormat("[a, a]() -> a<false> {};"); 20708 verifyFormat("[]() -> a<false> {};"); 20709 verifyFormat("[]() -> a<false> { ; };"); 20710 verifyFormat("[]() -> a<false> { ; }();"); 20711 verifyFormat("auto foo{[]() -> foo<false> { ; }};"); 20712 verifyFormat("namespace bar {\n" 20713 "auto foo{[]() -> foo<false> { ; }};\n" 20714 "} // namespace bar"); 20715 verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n" 20716 " int j) -> int {\n" 20717 " return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n" 20718 "};"); 20719 verifyFormat( 20720 "aaaaaaaaaaaaaaaaaaaaaa(\n" 20721 " [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n" 20722 " return aaaaaaaaaaaaaaaaa;\n" 20723 " });", 20724 getLLVMStyleWithColumns(70)); 20725 verifyFormat("[]() //\n" 20726 " -> int {\n" 20727 " return 1; //\n" 20728 "};"); 20729 verifyFormat("[]() -> Void<T...> {};"); 20730 verifyFormat("[a, b]() -> Tuple<T...> { return {}; };"); 20731 verifyFormat("SomeFunction({[]() -> int[] { return {}; }});"); 20732 verifyFormat("SomeFunction({[]() -> int *[] { return {}; }});"); 20733 verifyFormat("SomeFunction({[]() -> int (*)[] { return {}; }});"); 20734 verifyFormat("SomeFunction({[]() -> ns::type<int (*)[]> { return {}; }});"); 20735 verifyFormat("return int{[x = x]() { return x; }()};"); 20736 20737 // Lambdas with explicit template argument lists. 20738 verifyFormat( 20739 "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n"); 20740 verifyFormat("auto L = []<class T>(T) {\n" 20741 " {\n" 20742 " f();\n" 20743 " g();\n" 20744 " }\n" 20745 "};\n"); 20746 verifyFormat("auto L = []<class... T>(T...) {\n" 20747 " {\n" 20748 " f();\n" 20749 " g();\n" 20750 " }\n" 20751 "};\n"); 20752 verifyFormat("auto L = []<typename... T>(T...) {\n" 20753 " {\n" 20754 " f();\n" 20755 " g();\n" 20756 " }\n" 20757 "};\n"); 20758 verifyFormat("auto L = []<template <typename...> class T>(T...) {\n" 20759 " {\n" 20760 " f();\n" 20761 " g();\n" 20762 " }\n" 20763 "};\n"); 20764 verifyFormat("auto L = []</*comment*/ class... T>(T...) {\n" 20765 " {\n" 20766 " f();\n" 20767 " g();\n" 20768 " }\n" 20769 "};\n"); 20770 20771 // Multiple lambdas in the same parentheses change indentation rules. These 20772 // lambdas are forced to start on new lines. 20773 verifyFormat("SomeFunction(\n" 20774 " []() {\n" 20775 " //\n" 20776 " },\n" 20777 " []() {\n" 20778 " //\n" 20779 " });"); 20780 20781 // A lambda passed as arg0 is always pushed to the next line. 20782 verifyFormat("SomeFunction(\n" 20783 " [this] {\n" 20784 " //\n" 20785 " },\n" 20786 " 1);\n"); 20787 20788 // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like 20789 // the arg0 case above. 20790 auto Style = getGoogleStyle(); 20791 Style.BinPackArguments = false; 20792 verifyFormat("SomeFunction(\n" 20793 " a,\n" 20794 " [this] {\n" 20795 " //\n" 20796 " },\n" 20797 " b);\n", 20798 Style); 20799 verifyFormat("SomeFunction(\n" 20800 " a,\n" 20801 " [this] {\n" 20802 " //\n" 20803 " },\n" 20804 " b);\n"); 20805 20806 // A lambda with a very long line forces arg0 to be pushed out irrespective of 20807 // the BinPackArguments value (as long as the code is wide enough). 20808 verifyFormat( 20809 "something->SomeFunction(\n" 20810 " a,\n" 20811 " [this] {\n" 20812 " " 20813 "D0000000000000000000000000000000000000000000000000000000000001();\n" 20814 " },\n" 20815 " b);\n"); 20816 20817 // A multi-line lambda is pulled up as long as the introducer fits on the 20818 // previous line and there are no further args. 20819 verifyFormat("function(1, [this, that] {\n" 20820 " //\n" 20821 "});\n"); 20822 verifyFormat("function([this, that] {\n" 20823 " //\n" 20824 "});\n"); 20825 // FIXME: this format is not ideal and we should consider forcing the first 20826 // arg onto its own line. 20827 verifyFormat("function(a, b, c, //\n" 20828 " d, [this, that] {\n" 20829 " //\n" 20830 " });\n"); 20831 20832 // Multiple lambdas are treated correctly even when there is a short arg0. 20833 verifyFormat("SomeFunction(\n" 20834 " 1,\n" 20835 " [this] {\n" 20836 " //\n" 20837 " },\n" 20838 " [this] {\n" 20839 " //\n" 20840 " },\n" 20841 " 1);\n"); 20842 20843 // More complex introducers. 20844 verifyFormat("return [i, args...] {};"); 20845 20846 // Not lambdas. 20847 verifyFormat("constexpr char hello[]{\"hello\"};"); 20848 verifyFormat("double &operator[](int i) { return 0; }\n" 20849 "int i;"); 20850 verifyFormat("std::unique_ptr<int[]> foo() {}"); 20851 verifyFormat("int i = a[a][a]->f();"); 20852 verifyFormat("int i = (*b)[a]->f();"); 20853 20854 // Other corner cases. 20855 verifyFormat("void f() {\n" 20856 " bar([]() {} // Did not respect SpacesBeforeTrailingComments\n" 20857 " );\n" 20858 "}"); 20859 20860 // Lambdas created through weird macros. 20861 verifyFormat("void f() {\n" 20862 " MACRO((const AA &a) { return 1; });\n" 20863 " MACRO((AA &a) { return 1; });\n" 20864 "}"); 20865 20866 verifyFormat("if (blah_blah(whatever, whatever, [] {\n" 20867 " doo_dah();\n" 20868 " doo_dah();\n" 20869 " })) {\n" 20870 "}"); 20871 verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n" 20872 " doo_dah();\n" 20873 " doo_dah();\n" 20874 " })) {\n" 20875 "}"); 20876 verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n" 20877 " doo_dah();\n" 20878 " doo_dah();\n" 20879 " })) {\n" 20880 "}"); 20881 verifyFormat("auto lambda = []() {\n" 20882 " int a = 2\n" 20883 "#if A\n" 20884 " + 2\n" 20885 "#endif\n" 20886 " ;\n" 20887 "};"); 20888 20889 // Lambdas with complex multiline introducers. 20890 verifyFormat( 20891 "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 20892 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n" 20893 " -> ::std::unordered_set<\n" 20894 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n" 20895 " //\n" 20896 " });"); 20897 20898 FormatStyle DoNotMerge = getLLVMStyle(); 20899 DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 20900 verifyFormat("auto c = []() {\n" 20901 " return b;\n" 20902 "};", 20903 "auto c = []() { return b; };", DoNotMerge); 20904 verifyFormat("auto c = []() {\n" 20905 "};", 20906 " auto c = []() {};", DoNotMerge); 20907 20908 FormatStyle MergeEmptyOnly = getLLVMStyle(); 20909 MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty; 20910 verifyFormat("auto c = []() {\n" 20911 " return b;\n" 20912 "};", 20913 "auto c = []() {\n" 20914 " return b;\n" 20915 " };", 20916 MergeEmptyOnly); 20917 verifyFormat("auto c = []() {};", 20918 "auto c = []() {\n" 20919 "};", 20920 MergeEmptyOnly); 20921 20922 FormatStyle MergeInline = getLLVMStyle(); 20923 MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline; 20924 verifyFormat("auto c = []() {\n" 20925 " return b;\n" 20926 "};", 20927 "auto c = []() { return b; };", MergeInline); 20928 verifyFormat("function([]() { return b; })", "function([]() { return b; })", 20929 MergeInline); 20930 verifyFormat("function([]() { return b; }, a)", 20931 "function([]() { return b; }, a)", MergeInline); 20932 verifyFormat("function(a, []() { return b; })", 20933 "function(a, []() { return b; })", MergeInline); 20934 20935 // Check option "BraceWrapping.BeforeLambdaBody" and different state of 20936 // AllowShortLambdasOnASingleLine 20937 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle(); 20938 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 20939 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 20940 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 20941 FormatStyle::ShortLambdaStyle::SLS_None; 20942 verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n" 20943 " []()\n" 20944 " {\n" 20945 " return 17;\n" 20946 " });", 20947 LLVMWithBeforeLambdaBody); 20948 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n" 20949 " []()\n" 20950 " {\n" 20951 " });", 20952 LLVMWithBeforeLambdaBody); 20953 verifyFormat("auto fct_SLS_None = []()\n" 20954 "{\n" 20955 " return 17;\n" 20956 "};", 20957 LLVMWithBeforeLambdaBody); 20958 verifyFormat("TwoNestedLambdas_SLS_None(\n" 20959 " []()\n" 20960 " {\n" 20961 " return Call(\n" 20962 " []()\n" 20963 " {\n" 20964 " return 17;\n" 20965 " });\n" 20966 " });", 20967 LLVMWithBeforeLambdaBody); 20968 verifyFormat("void Fct() {\n" 20969 " return {[]()\n" 20970 " {\n" 20971 " return 17;\n" 20972 " }};\n" 20973 "}", 20974 LLVMWithBeforeLambdaBody); 20975 20976 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 20977 FormatStyle::ShortLambdaStyle::SLS_Empty; 20978 verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n" 20979 " []()\n" 20980 " {\n" 20981 " return 17;\n" 20982 " });", 20983 LLVMWithBeforeLambdaBody); 20984 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});", 20985 LLVMWithBeforeLambdaBody); 20986 verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL" 20987 "ongFunctionName_SLS_Empty(\n" 20988 " []() {});", 20989 LLVMWithBeforeLambdaBody); 20990 verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n" 20991 " []()\n" 20992 " {\n" 20993 " return 17;\n" 20994 " });", 20995 LLVMWithBeforeLambdaBody); 20996 verifyFormat("auto fct_SLS_Empty = []()\n" 20997 "{\n" 20998 " return 17;\n" 20999 "};", 21000 LLVMWithBeforeLambdaBody); 21001 verifyFormat("TwoNestedLambdas_SLS_Empty(\n" 21002 " []()\n" 21003 " {\n" 21004 " return Call([]() {});\n" 21005 " });", 21006 LLVMWithBeforeLambdaBody); 21007 verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n" 21008 " []()\n" 21009 " {\n" 21010 " return Call([]() {});\n" 21011 " });", 21012 LLVMWithBeforeLambdaBody); 21013 verifyFormat( 21014 "FctWithLongLineInLambda_SLS_Empty(\n" 21015 " []()\n" 21016 " {\n" 21017 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21018 " AndShouldNotBeConsiderAsInline,\n" 21019 " LambdaBodyMustBeBreak);\n" 21020 " });", 21021 LLVMWithBeforeLambdaBody); 21022 21023 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21024 FormatStyle::ShortLambdaStyle::SLS_Inline; 21025 verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });", 21026 LLVMWithBeforeLambdaBody); 21027 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});", 21028 LLVMWithBeforeLambdaBody); 21029 verifyFormat("auto fct_SLS_Inline = []()\n" 21030 "{\n" 21031 " return 17;\n" 21032 "};", 21033 LLVMWithBeforeLambdaBody); 21034 verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return " 21035 "17; }); });", 21036 LLVMWithBeforeLambdaBody); 21037 verifyFormat( 21038 "FctWithLongLineInLambda_SLS_Inline(\n" 21039 " []()\n" 21040 " {\n" 21041 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21042 " AndShouldNotBeConsiderAsInline,\n" 21043 " LambdaBodyMustBeBreak);\n" 21044 " });", 21045 LLVMWithBeforeLambdaBody); 21046 verifyFormat("FctWithMultipleParams_SLS_Inline(" 21047 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n" 21048 " []() { return 17; });", 21049 LLVMWithBeforeLambdaBody); 21050 verifyFormat( 21051 "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });", 21052 LLVMWithBeforeLambdaBody); 21053 21054 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21055 FormatStyle::ShortLambdaStyle::SLS_All; 21056 verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });", 21057 LLVMWithBeforeLambdaBody); 21058 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});", 21059 LLVMWithBeforeLambdaBody); 21060 verifyFormat("auto fct_SLS_All = []() { return 17; };", 21061 LLVMWithBeforeLambdaBody); 21062 verifyFormat("FctWithOneParam_SLS_All(\n" 21063 " []()\n" 21064 " {\n" 21065 " // A cool function...\n" 21066 " return 43;\n" 21067 " });", 21068 LLVMWithBeforeLambdaBody); 21069 verifyFormat("FctWithMultipleParams_SLS_All(" 21070 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n" 21071 " []() { return 17; });", 21072 LLVMWithBeforeLambdaBody); 21073 verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });", 21074 LLVMWithBeforeLambdaBody); 21075 verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });", 21076 LLVMWithBeforeLambdaBody); 21077 verifyFormat( 21078 "FctWithLongLineInLambda_SLS_All(\n" 21079 " []()\n" 21080 " {\n" 21081 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21082 " AndShouldNotBeConsiderAsInline,\n" 21083 " LambdaBodyMustBeBreak);\n" 21084 " });", 21085 LLVMWithBeforeLambdaBody); 21086 verifyFormat( 21087 "auto fct_SLS_All = []()\n" 21088 "{\n" 21089 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21090 " AndShouldNotBeConsiderAsInline,\n" 21091 " LambdaBodyMustBeBreak);\n" 21092 "};", 21093 LLVMWithBeforeLambdaBody); 21094 LLVMWithBeforeLambdaBody.BinPackParameters = false; 21095 verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);", 21096 LLVMWithBeforeLambdaBody); 21097 verifyFormat( 21098 "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n" 21099 " FirstParam,\n" 21100 " SecondParam,\n" 21101 " ThirdParam,\n" 21102 " FourthParam);", 21103 LLVMWithBeforeLambdaBody); 21104 verifyFormat("FctWithLongLineInLambda_SLS_All(\n" 21105 " []() { return " 21106 "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n" 21107 " FirstParam,\n" 21108 " SecondParam,\n" 21109 " ThirdParam,\n" 21110 " FourthParam);", 21111 LLVMWithBeforeLambdaBody); 21112 verifyFormat( 21113 "FctWithLongLineInLambda_SLS_All(FirstParam,\n" 21114 " SecondParam,\n" 21115 " ThirdParam,\n" 21116 " FourthParam,\n" 21117 " []() { return SomeValueNotSoLong; });", 21118 LLVMWithBeforeLambdaBody); 21119 verifyFormat("FctWithLongLineInLambda_SLS_All(\n" 21120 " []()\n" 21121 " {\n" 21122 " return " 21123 "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB" 21124 "eConsiderAsInline;\n" 21125 " });", 21126 LLVMWithBeforeLambdaBody); 21127 verifyFormat( 21128 "FctWithLongLineInLambda_SLS_All(\n" 21129 " []()\n" 21130 " {\n" 21131 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21132 " AndShouldNotBeConsiderAsInline,\n" 21133 " LambdaBodyMustBeBreak);\n" 21134 " });", 21135 LLVMWithBeforeLambdaBody); 21136 verifyFormat("FctWithTwoParams_SLS_All(\n" 21137 " []()\n" 21138 " {\n" 21139 " // A cool function...\n" 21140 " return 43;\n" 21141 " },\n" 21142 " 87);", 21143 LLVMWithBeforeLambdaBody); 21144 verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);", 21145 LLVMWithBeforeLambdaBody); 21146 verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });", 21147 LLVMWithBeforeLambdaBody); 21148 verifyFormat( 21149 "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });", 21150 LLVMWithBeforeLambdaBody); 21151 verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; " 21152 "}); }, x);", 21153 LLVMWithBeforeLambdaBody); 21154 verifyFormat("TwoNestedLambdas_SLS_All(\n" 21155 " []()\n" 21156 " {\n" 21157 " // A cool function...\n" 21158 " return Call([]() { return 17; });\n" 21159 " });", 21160 LLVMWithBeforeLambdaBody); 21161 verifyFormat("TwoNestedLambdas_SLS_All(\n" 21162 " []()\n" 21163 " {\n" 21164 " return Call(\n" 21165 " []()\n" 21166 " {\n" 21167 " // A cool function...\n" 21168 " return 17;\n" 21169 " });\n" 21170 " });", 21171 LLVMWithBeforeLambdaBody); 21172 21173 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21174 FormatStyle::ShortLambdaStyle::SLS_None; 21175 21176 verifyFormat("auto select = [this]() -> const Library::Object *\n" 21177 "{\n" 21178 " return MyAssignment::SelectFromList(this);\n" 21179 "};\n", 21180 LLVMWithBeforeLambdaBody); 21181 21182 verifyFormat("auto select = [this]() -> const Library::Object &\n" 21183 "{\n" 21184 " return MyAssignment::SelectFromList(this);\n" 21185 "};\n", 21186 LLVMWithBeforeLambdaBody); 21187 21188 verifyFormat("auto select = [this]() -> std::unique_ptr<Object>\n" 21189 "{\n" 21190 " return MyAssignment::SelectFromList(this);\n" 21191 "};\n", 21192 LLVMWithBeforeLambdaBody); 21193 21194 verifyFormat("namespace test {\n" 21195 "class Test {\n" 21196 "public:\n" 21197 " Test() = default;\n" 21198 "};\n" 21199 "} // namespace test", 21200 LLVMWithBeforeLambdaBody); 21201 21202 // Lambdas with different indentation styles. 21203 Style = getLLVMStyleWithColumns(100); 21204 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 21205 " return promise.then(\n" 21206 " [this, &someVariable, someObject = " 21207 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21208 " return someObject.startAsyncAction().then(\n" 21209 " [this, &someVariable](AsyncActionResult result) " 21210 "mutable { result.processMore(); });\n" 21211 " });\n" 21212 "}\n", 21213 format("SomeResult doSomething(SomeObject promise) {\n" 21214 " return promise.then([this, &someVariable, someObject = " 21215 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21216 " return someObject.startAsyncAction().then([this, " 21217 "&someVariable](AsyncActionResult result) mutable {\n" 21218 " result.processMore();\n" 21219 " });\n" 21220 " });\n" 21221 "}\n", 21222 Style)); 21223 Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope; 21224 verifyFormat("test() {\n" 21225 " ([]() -> {\n" 21226 " int b = 32;\n" 21227 " return 3;\n" 21228 " }).foo();\n" 21229 "}", 21230 Style); 21231 verifyFormat("test() {\n" 21232 " []() -> {\n" 21233 " int b = 32;\n" 21234 " return 3;\n" 21235 " }\n" 21236 "}", 21237 Style); 21238 verifyFormat("std::sort(v.begin(), v.end(),\n" 21239 " [](const auto &someLongArgumentName, const auto " 21240 "&someOtherLongArgumentName) {\n" 21241 " return someLongArgumentName.someMemberVariable < " 21242 "someOtherLongArgumentName.someMemberVariable;\n" 21243 "});", 21244 Style); 21245 verifyFormat("test() {\n" 21246 " (\n" 21247 " []() -> {\n" 21248 " int b = 32;\n" 21249 " return 3;\n" 21250 " },\n" 21251 " foo, bar)\n" 21252 " .foo();\n" 21253 "}", 21254 Style); 21255 verifyFormat("test() {\n" 21256 " ([]() -> {\n" 21257 " int b = 32;\n" 21258 " return 3;\n" 21259 " })\n" 21260 " .foo()\n" 21261 " .bar();\n" 21262 "}", 21263 Style); 21264 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 21265 " return promise.then(\n" 21266 " [this, &someVariable, someObject = " 21267 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21268 " return someObject.startAsyncAction().then(\n" 21269 " [this, &someVariable](AsyncActionResult result) mutable { " 21270 "result.processMore(); });\n" 21271 " });\n" 21272 "}\n", 21273 format("SomeResult doSomething(SomeObject promise) {\n" 21274 " return promise.then([this, &someVariable, someObject = " 21275 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21276 " return someObject.startAsyncAction().then([this, " 21277 "&someVariable](AsyncActionResult result) mutable {\n" 21278 " result.processMore();\n" 21279 " });\n" 21280 " });\n" 21281 "}\n", 21282 Style)); 21283 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 21284 " return promise.then([this, &someVariable] {\n" 21285 " return someObject.startAsyncAction().then(\n" 21286 " [this, &someVariable](AsyncActionResult result) mutable { " 21287 "result.processMore(); });\n" 21288 " });\n" 21289 "}\n", 21290 format("SomeResult doSomething(SomeObject promise) {\n" 21291 " return promise.then([this, &someVariable] {\n" 21292 " return someObject.startAsyncAction().then([this, " 21293 "&someVariable](AsyncActionResult result) mutable {\n" 21294 " result.processMore();\n" 21295 " });\n" 21296 " });\n" 21297 "}\n", 21298 Style)); 21299 Style = getGoogleStyle(); 21300 Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope; 21301 EXPECT_EQ("#define A \\\n" 21302 " [] { \\\n" 21303 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 21304 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n" 21305 " }", 21306 format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 21307 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }", 21308 Style)); 21309 // TODO: The current formatting has a minor issue that's not worth fixing 21310 // right now whereby the closing brace is indented relative to the signature 21311 // instead of being aligned. This only happens with macros. 21312 } 21313 21314 TEST_F(FormatTest, LambdaWithLineComments) { 21315 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle(); 21316 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 21317 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 21318 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21319 FormatStyle::ShortLambdaStyle::SLS_All; 21320 21321 verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody); 21322 verifyFormat("auto k = []() // comment\n" 21323 "{ return; }", 21324 LLVMWithBeforeLambdaBody); 21325 verifyFormat("auto k = []() /* comment */ { return; }", 21326 LLVMWithBeforeLambdaBody); 21327 verifyFormat("auto k = []() /* comment */ /* comment */ { return; }", 21328 LLVMWithBeforeLambdaBody); 21329 verifyFormat("auto k = []() // X\n" 21330 "{ return; }", 21331 LLVMWithBeforeLambdaBody); 21332 verifyFormat( 21333 "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" 21334 "{ return; }", 21335 LLVMWithBeforeLambdaBody); 21336 } 21337 21338 TEST_F(FormatTest, EmptyLinesInLambdas) { 21339 verifyFormat("auto lambda = []() {\n" 21340 " x(); //\n" 21341 "};", 21342 "auto lambda = []() {\n" 21343 "\n" 21344 " x(); //\n" 21345 "\n" 21346 "};"); 21347 } 21348 21349 TEST_F(FormatTest, FormatsBlocks) { 21350 FormatStyle ShortBlocks = getLLVMStyle(); 21351 ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 21352 verifyFormat("int (^Block)(int, int);", ShortBlocks); 21353 verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks); 21354 verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks); 21355 verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks); 21356 verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks); 21357 verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks); 21358 21359 verifyFormat("foo(^{ bar(); });", ShortBlocks); 21360 verifyFormat("foo(a, ^{ bar(); });", ShortBlocks); 21361 verifyFormat("{ void (^block)(Object *x); }", ShortBlocks); 21362 21363 verifyFormat("[operation setCompletionBlock:^{\n" 21364 " [self onOperationDone];\n" 21365 "}];"); 21366 verifyFormat("int i = {[operation setCompletionBlock:^{\n" 21367 " [self onOperationDone];\n" 21368 "}]};"); 21369 verifyFormat("[operation setCompletionBlock:^(int *i) {\n" 21370 " f();\n" 21371 "}];"); 21372 verifyFormat("int a = [operation block:^int(int *i) {\n" 21373 " return 1;\n" 21374 "}];"); 21375 verifyFormat("[myObject doSomethingWith:arg1\n" 21376 " aaa:^int(int *a) {\n" 21377 " return 1;\n" 21378 " }\n" 21379 " bbb:f(a * bbbbbbbb)];"); 21380 21381 verifyFormat("[operation setCompletionBlock:^{\n" 21382 " [self.delegate newDataAvailable];\n" 21383 "}];", 21384 getLLVMStyleWithColumns(60)); 21385 verifyFormat("dispatch_async(_fileIOQueue, ^{\n" 21386 " NSString *path = [self sessionFilePath];\n" 21387 " if (path) {\n" 21388 " // ...\n" 21389 " }\n" 21390 "});"); 21391 verifyFormat("[[SessionService sharedService]\n" 21392 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 21393 " if (window) {\n" 21394 " [self windowDidLoad:window];\n" 21395 " } else {\n" 21396 " [self errorLoadingWindow];\n" 21397 " }\n" 21398 " }];"); 21399 verifyFormat("void (^largeBlock)(void) = ^{\n" 21400 " // ...\n" 21401 "};\n", 21402 getLLVMStyleWithColumns(40)); 21403 verifyFormat("[[SessionService sharedService]\n" 21404 " loadWindowWithCompletionBlock: //\n" 21405 " ^(SessionWindow *window) {\n" 21406 " if (window) {\n" 21407 " [self windowDidLoad:window];\n" 21408 " } else {\n" 21409 " [self errorLoadingWindow];\n" 21410 " }\n" 21411 " }];", 21412 getLLVMStyleWithColumns(60)); 21413 verifyFormat("[myObject doSomethingWith:arg1\n" 21414 " firstBlock:^(Foo *a) {\n" 21415 " // ...\n" 21416 " int i;\n" 21417 " }\n" 21418 " secondBlock:^(Bar *b) {\n" 21419 " // ...\n" 21420 " int i;\n" 21421 " }\n" 21422 " thirdBlock:^Foo(Bar *b) {\n" 21423 " // ...\n" 21424 " int i;\n" 21425 " }];"); 21426 verifyFormat("[myObject doSomethingWith:arg1\n" 21427 " firstBlock:-1\n" 21428 " secondBlock:^(Bar *b) {\n" 21429 " // ...\n" 21430 " int i;\n" 21431 " }];"); 21432 21433 verifyFormat("f(^{\n" 21434 " @autoreleasepool {\n" 21435 " if (a) {\n" 21436 " g();\n" 21437 " }\n" 21438 " }\n" 21439 "});"); 21440 verifyFormat("Block b = ^int *(A *a, B *b) {}"); 21441 verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n" 21442 "};"); 21443 21444 FormatStyle FourIndent = getLLVMStyle(); 21445 FourIndent.ObjCBlockIndentWidth = 4; 21446 verifyFormat("[operation setCompletionBlock:^{\n" 21447 " [self onOperationDone];\n" 21448 "}];", 21449 FourIndent); 21450 } 21451 21452 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) { 21453 FormatStyle ZeroColumn = getLLVMStyleWithColumns(0); 21454 21455 verifyFormat("[[SessionService sharedService] " 21456 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 21457 " if (window) {\n" 21458 " [self windowDidLoad:window];\n" 21459 " } else {\n" 21460 " [self errorLoadingWindow];\n" 21461 " }\n" 21462 "}];", 21463 ZeroColumn); 21464 EXPECT_EQ("[[SessionService sharedService]\n" 21465 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 21466 " if (window) {\n" 21467 " [self windowDidLoad:window];\n" 21468 " } else {\n" 21469 " [self errorLoadingWindow];\n" 21470 " }\n" 21471 " }];", 21472 format("[[SessionService sharedService]\n" 21473 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 21474 " if (window) {\n" 21475 " [self windowDidLoad:window];\n" 21476 " } else {\n" 21477 " [self errorLoadingWindow];\n" 21478 " }\n" 21479 "}];", 21480 ZeroColumn)); 21481 verifyFormat("[myObject doSomethingWith:arg1\n" 21482 " firstBlock:^(Foo *a) {\n" 21483 " // ...\n" 21484 " int i;\n" 21485 " }\n" 21486 " secondBlock:^(Bar *b) {\n" 21487 " // ...\n" 21488 " int i;\n" 21489 " }\n" 21490 " thirdBlock:^Foo(Bar *b) {\n" 21491 " // ...\n" 21492 " int i;\n" 21493 " }];", 21494 ZeroColumn); 21495 verifyFormat("f(^{\n" 21496 " @autoreleasepool {\n" 21497 " if (a) {\n" 21498 " g();\n" 21499 " }\n" 21500 " }\n" 21501 "});", 21502 ZeroColumn); 21503 verifyFormat("void (^largeBlock)(void) = ^{\n" 21504 " // ...\n" 21505 "};", 21506 ZeroColumn); 21507 21508 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 21509 EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };", 21510 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn)); 21511 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 21512 EXPECT_EQ("void (^largeBlock)(void) = ^{\n" 21513 " int i;\n" 21514 "};", 21515 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn)); 21516 } 21517 21518 TEST_F(FormatTest, SupportsCRLF) { 21519 EXPECT_EQ("int a;\r\n" 21520 "int b;\r\n" 21521 "int c;\r\n", 21522 format("int a;\r\n" 21523 " int b;\r\n" 21524 " int c;\r\n", 21525 getLLVMStyle())); 21526 EXPECT_EQ("int a;\r\n" 21527 "int b;\r\n" 21528 "int c;\r\n", 21529 format("int a;\r\n" 21530 " int b;\n" 21531 " int c;\r\n", 21532 getLLVMStyle())); 21533 EXPECT_EQ("int a;\n" 21534 "int b;\n" 21535 "int c;\n", 21536 format("int a;\r\n" 21537 " int b;\n" 21538 " int c;\n", 21539 getLLVMStyle())); 21540 EXPECT_EQ("\"aaaaaaa \"\r\n" 21541 "\"bbbbbbb\";\r\n", 21542 format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10))); 21543 EXPECT_EQ("#define A \\\r\n" 21544 " b; \\\r\n" 21545 " c; \\\r\n" 21546 " d;\r\n", 21547 format("#define A \\\r\n" 21548 " b; \\\r\n" 21549 " c; d; \r\n", 21550 getGoogleStyle())); 21551 21552 EXPECT_EQ("/*\r\n" 21553 "multi line block comments\r\n" 21554 "should not introduce\r\n" 21555 "an extra carriage return\r\n" 21556 "*/\r\n", 21557 format("/*\r\n" 21558 "multi line block comments\r\n" 21559 "should not introduce\r\n" 21560 "an extra carriage return\r\n" 21561 "*/\r\n")); 21562 EXPECT_EQ("/*\r\n" 21563 "\r\n" 21564 "*/", 21565 format("/*\r\n" 21566 " \r\r\r\n" 21567 "*/")); 21568 21569 FormatStyle style = getLLVMStyle(); 21570 21571 style.DeriveLineEnding = true; 21572 style.UseCRLF = false; 21573 EXPECT_EQ("union FooBarBazQux {\n" 21574 " int foo;\n" 21575 " int bar;\n" 21576 " int baz;\n" 21577 "};", 21578 format("union FooBarBazQux {\r\n" 21579 " int foo;\n" 21580 " int bar;\r\n" 21581 " int baz;\n" 21582 "};", 21583 style)); 21584 style.UseCRLF = true; 21585 EXPECT_EQ("union FooBarBazQux {\r\n" 21586 " int foo;\r\n" 21587 " int bar;\r\n" 21588 " int baz;\r\n" 21589 "};", 21590 format("union FooBarBazQux {\r\n" 21591 " int foo;\n" 21592 " int bar;\r\n" 21593 " int baz;\n" 21594 "};", 21595 style)); 21596 21597 style.DeriveLineEnding = false; 21598 style.UseCRLF = false; 21599 EXPECT_EQ("union FooBarBazQux {\n" 21600 " int foo;\n" 21601 " int bar;\n" 21602 " int baz;\n" 21603 " int qux;\n" 21604 "};", 21605 format("union FooBarBazQux {\r\n" 21606 " int foo;\n" 21607 " int bar;\r\n" 21608 " int baz;\n" 21609 " int qux;\r\n" 21610 "};", 21611 style)); 21612 style.UseCRLF = true; 21613 EXPECT_EQ("union FooBarBazQux {\r\n" 21614 " int foo;\r\n" 21615 " int bar;\r\n" 21616 " int baz;\r\n" 21617 " int qux;\r\n" 21618 "};", 21619 format("union FooBarBazQux {\r\n" 21620 " int foo;\n" 21621 " int bar;\r\n" 21622 " int baz;\n" 21623 " int qux;\n" 21624 "};", 21625 style)); 21626 21627 style.DeriveLineEnding = true; 21628 style.UseCRLF = false; 21629 EXPECT_EQ("union FooBarBazQux {\r\n" 21630 " int foo;\r\n" 21631 " int bar;\r\n" 21632 " int baz;\r\n" 21633 " int qux;\r\n" 21634 "};", 21635 format("union FooBarBazQux {\r\n" 21636 " int foo;\n" 21637 " int bar;\r\n" 21638 " int baz;\n" 21639 " int qux;\r\n" 21640 "};", 21641 style)); 21642 style.UseCRLF = true; 21643 EXPECT_EQ("union FooBarBazQux {\n" 21644 " int foo;\n" 21645 " int bar;\n" 21646 " int baz;\n" 21647 " int qux;\n" 21648 "};", 21649 format("union FooBarBazQux {\r\n" 21650 " int foo;\n" 21651 " int bar;\r\n" 21652 " int baz;\n" 21653 " int qux;\n" 21654 "};", 21655 style)); 21656 } 21657 21658 TEST_F(FormatTest, MunchSemicolonAfterBlocks) { 21659 verifyFormat("MY_CLASS(C) {\n" 21660 " int i;\n" 21661 " int j;\n" 21662 "};"); 21663 } 21664 21665 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) { 21666 FormatStyle TwoIndent = getLLVMStyleWithColumns(15); 21667 TwoIndent.ContinuationIndentWidth = 2; 21668 21669 EXPECT_EQ("int i =\n" 21670 " longFunction(\n" 21671 " arg);", 21672 format("int i = longFunction(arg);", TwoIndent)); 21673 21674 FormatStyle SixIndent = getLLVMStyleWithColumns(20); 21675 SixIndent.ContinuationIndentWidth = 6; 21676 21677 EXPECT_EQ("int i =\n" 21678 " longFunction(\n" 21679 " arg);", 21680 format("int i = longFunction(arg);", SixIndent)); 21681 } 21682 21683 TEST_F(FormatTest, WrappedClosingParenthesisIndent) { 21684 FormatStyle Style = getLLVMStyle(); 21685 verifyFormat("int Foo::getter(\n" 21686 " //\n" 21687 ") const {\n" 21688 " return foo;\n" 21689 "}", 21690 Style); 21691 verifyFormat("void Foo::setter(\n" 21692 " //\n" 21693 ") {\n" 21694 " foo = 1;\n" 21695 "}", 21696 Style); 21697 } 21698 21699 TEST_F(FormatTest, SpacesInAngles) { 21700 FormatStyle Spaces = getLLVMStyle(); 21701 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 21702 21703 verifyFormat("vector< ::std::string > x1;", Spaces); 21704 verifyFormat("Foo< int, Bar > x2;", Spaces); 21705 verifyFormat("Foo< ::int, ::Bar > x3;", Spaces); 21706 21707 verifyFormat("static_cast< int >(arg);", Spaces); 21708 verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces); 21709 verifyFormat("f< int, float >();", Spaces); 21710 verifyFormat("template <> g() {}", Spaces); 21711 verifyFormat("template < std::vector< int > > f() {}", Spaces); 21712 verifyFormat("std::function< void(int, int) > fct;", Spaces); 21713 verifyFormat("void inFunction() { std::function< void(int, int) > fct; }", 21714 Spaces); 21715 21716 Spaces.Standard = FormatStyle::LS_Cpp03; 21717 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 21718 verifyFormat("A< A< int > >();", Spaces); 21719 21720 Spaces.SpacesInAngles = FormatStyle::SIAS_Never; 21721 verifyFormat("A<A<int> >();", Spaces); 21722 21723 Spaces.SpacesInAngles = FormatStyle::SIAS_Leave; 21724 verifyFormat("vector< ::std::string> x4;", "vector<::std::string> x4;", 21725 Spaces); 21726 verifyFormat("vector< ::std::string > x4;", "vector<::std::string > x4;", 21727 Spaces); 21728 21729 verifyFormat("A<A<int> >();", Spaces); 21730 verifyFormat("A<A<int> >();", "A<A<int>>();", Spaces); 21731 verifyFormat("A< A< int > >();", Spaces); 21732 21733 Spaces.Standard = FormatStyle::LS_Cpp11; 21734 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 21735 verifyFormat("A< A< int > >();", Spaces); 21736 21737 Spaces.SpacesInAngles = FormatStyle::SIAS_Never; 21738 verifyFormat("vector<::std::string> x4;", Spaces); 21739 verifyFormat("vector<int> x5;", Spaces); 21740 verifyFormat("Foo<int, Bar> x6;", Spaces); 21741 verifyFormat("Foo<::int, ::Bar> x7;", Spaces); 21742 21743 verifyFormat("A<A<int>>();", Spaces); 21744 21745 Spaces.SpacesInAngles = FormatStyle::SIAS_Leave; 21746 verifyFormat("vector<::std::string> x4;", Spaces); 21747 verifyFormat("vector< ::std::string > x4;", Spaces); 21748 verifyFormat("vector<int> x5;", Spaces); 21749 verifyFormat("vector< int > x5;", Spaces); 21750 verifyFormat("Foo<int, Bar> x6;", Spaces); 21751 verifyFormat("Foo< int, Bar > x6;", Spaces); 21752 verifyFormat("Foo<::int, ::Bar> x7;", Spaces); 21753 verifyFormat("Foo< ::int, ::Bar > x7;", Spaces); 21754 21755 verifyFormat("A<A<int>>();", Spaces); 21756 verifyFormat("A< A< int > >();", Spaces); 21757 verifyFormat("A<A<int > >();", Spaces); 21758 verifyFormat("A< A< int>>();", Spaces); 21759 21760 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 21761 verifyFormat("// clang-format off\n" 21762 "foo<<<1, 1>>>();\n" 21763 "// clang-format on\n", 21764 Spaces); 21765 verifyFormat("// clang-format off\n" 21766 "foo< < <1, 1> > >();\n" 21767 "// clang-format on\n", 21768 Spaces); 21769 } 21770 21771 TEST_F(FormatTest, SpaceAfterTemplateKeyword) { 21772 FormatStyle Style = getLLVMStyle(); 21773 Style.SpaceAfterTemplateKeyword = false; 21774 verifyFormat("template<int> void foo();", Style); 21775 } 21776 21777 TEST_F(FormatTest, TripleAngleBrackets) { 21778 verifyFormat("f<<<1, 1>>>();"); 21779 verifyFormat("f<<<1, 1, 1, s>>>();"); 21780 verifyFormat("f<<<a, b, c, d>>>();"); 21781 EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();")); 21782 verifyFormat("f<param><<<1, 1>>>();"); 21783 verifyFormat("f<1><<<1, 1>>>();"); 21784 EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();")); 21785 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 21786 "aaaaaaaaaaa<<<\n 1, 1>>>();"); 21787 verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n" 21788 " <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();"); 21789 } 21790 21791 TEST_F(FormatTest, MergeLessLessAtEnd) { 21792 verifyFormat("<<"); 21793 EXPECT_EQ("< < <", format("\\\n<<<")); 21794 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 21795 "aaallvm::outs() <<"); 21796 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 21797 "aaaallvm::outs()\n <<"); 21798 } 21799 21800 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) { 21801 std::string code = "#if A\n" 21802 "#if B\n" 21803 "a.\n" 21804 "#endif\n" 21805 " a = 1;\n" 21806 "#else\n" 21807 "#endif\n" 21808 "#if C\n" 21809 "#else\n" 21810 "#endif\n"; 21811 EXPECT_EQ(code, format(code)); 21812 } 21813 21814 TEST_F(FormatTest, HandleConflictMarkers) { 21815 // Git/SVN conflict markers. 21816 EXPECT_EQ("int a;\n" 21817 "void f() {\n" 21818 " callme(some(parameter1,\n" 21819 "<<<<<<< text by the vcs\n" 21820 " parameter2),\n" 21821 "||||||| text by the vcs\n" 21822 " parameter2),\n" 21823 " parameter3,\n" 21824 "======= text by the vcs\n" 21825 " parameter2, parameter3),\n" 21826 ">>>>>>> text by the vcs\n" 21827 " otherparameter);\n", 21828 format("int a;\n" 21829 "void f() {\n" 21830 " callme(some(parameter1,\n" 21831 "<<<<<<< text by the vcs\n" 21832 " parameter2),\n" 21833 "||||||| text by the vcs\n" 21834 " parameter2),\n" 21835 " parameter3,\n" 21836 "======= text by the vcs\n" 21837 " parameter2,\n" 21838 " parameter3),\n" 21839 ">>>>>>> text by the vcs\n" 21840 " otherparameter);\n")); 21841 21842 // Perforce markers. 21843 EXPECT_EQ("void f() {\n" 21844 " function(\n" 21845 ">>>> text by the vcs\n" 21846 " parameter,\n" 21847 "==== text by the vcs\n" 21848 " parameter,\n" 21849 "==== text by the vcs\n" 21850 " parameter,\n" 21851 "<<<< text by the vcs\n" 21852 " parameter);\n", 21853 format("void f() {\n" 21854 " function(\n" 21855 ">>>> text by the vcs\n" 21856 " parameter,\n" 21857 "==== text by the vcs\n" 21858 " parameter,\n" 21859 "==== text by the vcs\n" 21860 " parameter,\n" 21861 "<<<< text by the vcs\n" 21862 " parameter);\n")); 21863 21864 EXPECT_EQ("<<<<<<<\n" 21865 "|||||||\n" 21866 "=======\n" 21867 ">>>>>>>", 21868 format("<<<<<<<\n" 21869 "|||||||\n" 21870 "=======\n" 21871 ">>>>>>>")); 21872 21873 EXPECT_EQ("<<<<<<<\n" 21874 "|||||||\n" 21875 "int i;\n" 21876 "=======\n" 21877 ">>>>>>>", 21878 format("<<<<<<<\n" 21879 "|||||||\n" 21880 "int i;\n" 21881 "=======\n" 21882 ">>>>>>>")); 21883 21884 // FIXME: Handle parsing of macros around conflict markers correctly: 21885 EXPECT_EQ("#define Macro \\\n" 21886 "<<<<<<<\n" 21887 "Something \\\n" 21888 "|||||||\n" 21889 "Else \\\n" 21890 "=======\n" 21891 "Other \\\n" 21892 ">>>>>>>\n" 21893 " End int i;\n", 21894 format("#define Macro \\\n" 21895 "<<<<<<<\n" 21896 " Something \\\n" 21897 "|||||||\n" 21898 " Else \\\n" 21899 "=======\n" 21900 " Other \\\n" 21901 ">>>>>>>\n" 21902 " End\n" 21903 "int i;\n")); 21904 21905 verifyFormat(R"(==== 21906 #ifdef A 21907 a 21908 #else 21909 b 21910 #endif 21911 )"); 21912 } 21913 21914 TEST_F(FormatTest, DisableRegions) { 21915 EXPECT_EQ("int i;\n" 21916 "// clang-format off\n" 21917 " int j;\n" 21918 "// clang-format on\n" 21919 "int k;", 21920 format(" int i;\n" 21921 " // clang-format off\n" 21922 " int j;\n" 21923 " // clang-format on\n" 21924 " int k;")); 21925 EXPECT_EQ("int i;\n" 21926 "/* clang-format off */\n" 21927 " int j;\n" 21928 "/* clang-format on */\n" 21929 "int k;", 21930 format(" int i;\n" 21931 " /* clang-format off */\n" 21932 " int j;\n" 21933 " /* clang-format on */\n" 21934 " int k;")); 21935 21936 // Don't reflow comments within disabled regions. 21937 EXPECT_EQ("// clang-format off\n" 21938 "// long long long long long long line\n" 21939 "/* clang-format on */\n" 21940 "/* long long long\n" 21941 " * long long long\n" 21942 " * line */\n" 21943 "int i;\n" 21944 "/* clang-format off */\n" 21945 "/* long long long long long long line */\n", 21946 format("// clang-format off\n" 21947 "// long long long long long long line\n" 21948 "/* clang-format on */\n" 21949 "/* long long long long long long line */\n" 21950 "int i;\n" 21951 "/* clang-format off */\n" 21952 "/* long long long long long long line */\n", 21953 getLLVMStyleWithColumns(20))); 21954 } 21955 21956 TEST_F(FormatTest, DoNotCrashOnInvalidInput) { 21957 format("? ) ="); 21958 verifyNoCrash("#define a\\\n /**/}"); 21959 } 21960 21961 TEST_F(FormatTest, FormatsTableGenCode) { 21962 FormatStyle Style = getLLVMStyle(); 21963 Style.Language = FormatStyle::LK_TableGen; 21964 verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style); 21965 } 21966 21967 TEST_F(FormatTest, ArrayOfTemplates) { 21968 EXPECT_EQ("auto a = new unique_ptr<int>[10];", 21969 format("auto a = new unique_ptr<int > [ 10];")); 21970 21971 FormatStyle Spaces = getLLVMStyle(); 21972 Spaces.SpacesInSquareBrackets = true; 21973 EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];", 21974 format("auto a = new unique_ptr<int > [10];", Spaces)); 21975 } 21976 21977 TEST_F(FormatTest, ArrayAsTemplateType) { 21978 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;", 21979 format("auto a = unique_ptr < Foo < Bar>[ 10]> ;")); 21980 21981 FormatStyle Spaces = getLLVMStyle(); 21982 Spaces.SpacesInSquareBrackets = true; 21983 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;", 21984 format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces)); 21985 } 21986 21987 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); } 21988 21989 TEST(FormatStyle, GetStyleWithEmptyFileName) { 21990 llvm::vfs::InMemoryFileSystem FS; 21991 auto Style1 = getStyle("file", "", "Google", "", &FS); 21992 ASSERT_TRUE((bool)Style1); 21993 ASSERT_EQ(*Style1, getGoogleStyle()); 21994 } 21995 21996 TEST(FormatStyle, GetStyleOfFile) { 21997 llvm::vfs::InMemoryFileSystem FS; 21998 // Test 1: format file in the same directory. 21999 ASSERT_TRUE( 22000 FS.addFile("/a/.clang-format", 0, 22001 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM"))); 22002 ASSERT_TRUE( 22003 FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22004 auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS); 22005 ASSERT_TRUE((bool)Style1); 22006 ASSERT_EQ(*Style1, getLLVMStyle()); 22007 22008 // Test 2.1: fallback to default. 22009 ASSERT_TRUE( 22010 FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22011 auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS); 22012 ASSERT_TRUE((bool)Style2); 22013 ASSERT_EQ(*Style2, getMozillaStyle()); 22014 22015 // Test 2.2: no format on 'none' fallback style. 22016 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS); 22017 ASSERT_TRUE((bool)Style2); 22018 ASSERT_EQ(*Style2, getNoStyle()); 22019 22020 // Test 2.3: format if config is found with no based style while fallback is 22021 // 'none'. 22022 ASSERT_TRUE(FS.addFile("/b/.clang-format", 0, 22023 llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2"))); 22024 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS); 22025 ASSERT_TRUE((bool)Style2); 22026 ASSERT_EQ(*Style2, getLLVMStyle()); 22027 22028 // Test 2.4: format if yaml with no based style, while fallback is 'none'. 22029 Style2 = getStyle("{}", "a.h", "none", "", &FS); 22030 ASSERT_TRUE((bool)Style2); 22031 ASSERT_EQ(*Style2, getLLVMStyle()); 22032 22033 // Test 3: format file in parent directory. 22034 ASSERT_TRUE( 22035 FS.addFile("/c/.clang-format", 0, 22036 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 22037 ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0, 22038 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22039 auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS); 22040 ASSERT_TRUE((bool)Style3); 22041 ASSERT_EQ(*Style3, getGoogleStyle()); 22042 22043 // Test 4: error on invalid fallback style 22044 auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS); 22045 ASSERT_FALSE((bool)Style4); 22046 llvm::consumeError(Style4.takeError()); 22047 22048 // Test 5: error on invalid yaml on command line 22049 auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS); 22050 ASSERT_FALSE((bool)Style5); 22051 llvm::consumeError(Style5.takeError()); 22052 22053 // Test 6: error on invalid style 22054 auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS); 22055 ASSERT_FALSE((bool)Style6); 22056 llvm::consumeError(Style6.takeError()); 22057 22058 // Test 7: found config file, error on parsing it 22059 ASSERT_TRUE( 22060 FS.addFile("/d/.clang-format", 0, 22061 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n" 22062 "InvalidKey: InvalidValue"))); 22063 ASSERT_TRUE( 22064 FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22065 auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS); 22066 ASSERT_FALSE((bool)Style7a); 22067 llvm::consumeError(Style7a.takeError()); 22068 22069 auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true); 22070 ASSERT_TRUE((bool)Style7b); 22071 22072 // Test 8: inferred per-language defaults apply. 22073 auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS); 22074 ASSERT_TRUE((bool)StyleTd); 22075 ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen)); 22076 22077 // Test 9.1.1: overwriting a file style, when no parent file exists with no 22078 // fallback style. 22079 ASSERT_TRUE(FS.addFile( 22080 "/e/sub/.clang-format", 0, 22081 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n" 22082 "ColumnLimit: 20"))); 22083 ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0, 22084 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22085 auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS); 22086 ASSERT_TRUE(static_cast<bool>(Style9)); 22087 ASSERT_EQ(*Style9, [] { 22088 auto Style = getNoStyle(); 22089 Style.ColumnLimit = 20; 22090 return Style; 22091 }()); 22092 22093 // Test 9.1.2: propagate more than one level with no parent file. 22094 ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0, 22095 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22096 ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0, 22097 llvm::MemoryBuffer::getMemBuffer( 22098 "BasedOnStyle: InheritParentConfig\n" 22099 "WhitespaceSensitiveMacros: ['FOO', 'BAR']"))); 22100 std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"}; 22101 22102 ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros); 22103 Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS); 22104 ASSERT_TRUE(static_cast<bool>(Style9)); 22105 ASSERT_EQ(*Style9, [&NonDefaultWhiteSpaceMacros] { 22106 auto Style = getNoStyle(); 22107 Style.ColumnLimit = 20; 22108 Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros; 22109 return Style; 22110 }()); 22111 22112 // Test 9.2: with LLVM fallback style 22113 Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS); 22114 ASSERT_TRUE(static_cast<bool>(Style9)); 22115 ASSERT_EQ(*Style9, [] { 22116 auto Style = getLLVMStyle(); 22117 Style.ColumnLimit = 20; 22118 return Style; 22119 }()); 22120 22121 // Test 9.3: with a parent file 22122 ASSERT_TRUE( 22123 FS.addFile("/e/.clang-format", 0, 22124 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n" 22125 "UseTab: Always"))); 22126 Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS); 22127 ASSERT_TRUE(static_cast<bool>(Style9)); 22128 ASSERT_EQ(*Style9, [] { 22129 auto Style = getGoogleStyle(); 22130 Style.ColumnLimit = 20; 22131 Style.UseTab = FormatStyle::UT_Always; 22132 return Style; 22133 }()); 22134 22135 // Test 9.4: propagate more than one level with a parent file. 22136 const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] { 22137 auto Style = getGoogleStyle(); 22138 Style.ColumnLimit = 20; 22139 Style.UseTab = FormatStyle::UT_Always; 22140 Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros; 22141 return Style; 22142 }(); 22143 22144 ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros); 22145 Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS); 22146 ASSERT_TRUE(static_cast<bool>(Style9)); 22147 ASSERT_EQ(*Style9, SubSubStyle); 22148 22149 // Test 9.5: use InheritParentConfig as style name 22150 Style9 = 22151 getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS); 22152 ASSERT_TRUE(static_cast<bool>(Style9)); 22153 ASSERT_EQ(*Style9, SubSubStyle); 22154 22155 // Test 9.6: use command line style with inheritance 22156 Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp", 22157 "none", "", &FS); 22158 ASSERT_TRUE(static_cast<bool>(Style9)); 22159 ASSERT_EQ(*Style9, SubSubStyle); 22160 22161 // Test 9.7: use command line style with inheritance and own config 22162 Style9 = getStyle("{BasedOnStyle: InheritParentConfig, " 22163 "WhitespaceSensitiveMacros: ['FOO', 'BAR']}", 22164 "/e/sub/code.cpp", "none", "", &FS); 22165 ASSERT_TRUE(static_cast<bool>(Style9)); 22166 ASSERT_EQ(*Style9, SubSubStyle); 22167 22168 // Test 9.8: use inheritance from a file without BasedOnStyle 22169 ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0, 22170 llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123"))); 22171 ASSERT_TRUE( 22172 FS.addFile("/e/withoutbase/sub/.clang-format", 0, 22173 llvm::MemoryBuffer::getMemBuffer( 22174 "BasedOnStyle: InheritParentConfig\nIndentWidth: 7"))); 22175 // Make sure we do not use the fallback style 22176 Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS); 22177 ASSERT_TRUE(static_cast<bool>(Style9)); 22178 ASSERT_EQ(*Style9, [] { 22179 auto Style = getLLVMStyle(); 22180 Style.ColumnLimit = 123; 22181 return Style; 22182 }()); 22183 22184 Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS); 22185 ASSERT_TRUE(static_cast<bool>(Style9)); 22186 ASSERT_EQ(*Style9, [] { 22187 auto Style = getLLVMStyle(); 22188 Style.ColumnLimit = 123; 22189 Style.IndentWidth = 7; 22190 return Style; 22191 }()); 22192 22193 // Test 9.9: use inheritance from a specific config file. 22194 Style9 = getStyle("file:/e/sub/sub/.clang-format", "/e/sub/sub/code.cpp", 22195 "none", "", &FS); 22196 ASSERT_TRUE(static_cast<bool>(Style9)); 22197 ASSERT_EQ(*Style9, SubSubStyle); 22198 } 22199 22200 TEST(FormatStyle, GetStyleOfSpecificFile) { 22201 llvm::vfs::InMemoryFileSystem FS; 22202 // Specify absolute path to a format file in a parent directory. 22203 ASSERT_TRUE( 22204 FS.addFile("/e/.clang-format", 0, 22205 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM"))); 22206 ASSERT_TRUE( 22207 FS.addFile("/e/explicit.clang-format", 0, 22208 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 22209 ASSERT_TRUE(FS.addFile("/e/sub/sub/sub/test.cpp", 0, 22210 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22211 auto Style = getStyle("file:/e/explicit.clang-format", 22212 "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS); 22213 ASSERT_TRUE(static_cast<bool>(Style)); 22214 ASSERT_EQ(*Style, getGoogleStyle()); 22215 22216 // Specify relative path to a format file. 22217 ASSERT_TRUE( 22218 FS.addFile("../../e/explicit.clang-format", 0, 22219 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 22220 Style = getStyle("file:../../e/explicit.clang-format", 22221 "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS); 22222 ASSERT_TRUE(static_cast<bool>(Style)); 22223 ASSERT_EQ(*Style, getGoogleStyle()); 22224 22225 // Specify path to a format file that does not exist. 22226 Style = getStyle("file:/e/missing.clang-format", "/e/sub/sub/sub/test.cpp", 22227 "LLVM", "", &FS); 22228 ASSERT_FALSE(static_cast<bool>(Style)); 22229 llvm::consumeError(Style.takeError()); 22230 22231 // Specify path to a file on the filesystem. 22232 SmallString<128> FormatFilePath; 22233 std::error_code ECF = llvm::sys::fs::createTemporaryFile( 22234 "FormatFileTest", "tpl", FormatFilePath); 22235 EXPECT_FALSE((bool)ECF); 22236 llvm::raw_fd_ostream FormatFileTest(FormatFilePath, ECF); 22237 EXPECT_FALSE((bool)ECF); 22238 FormatFileTest << "BasedOnStyle: Google\n"; 22239 FormatFileTest.close(); 22240 22241 SmallString<128> TestFilePath; 22242 std::error_code ECT = 22243 llvm::sys::fs::createTemporaryFile("CodeFileTest", "cc", TestFilePath); 22244 EXPECT_FALSE((bool)ECT); 22245 llvm::raw_fd_ostream CodeFileTest(TestFilePath, ECT); 22246 CodeFileTest << "int i;\n"; 22247 CodeFileTest.close(); 22248 22249 std::string format_file_arg = std::string("file:") + FormatFilePath.c_str(); 22250 Style = getStyle(format_file_arg, TestFilePath, "LLVM", "", nullptr); 22251 22252 llvm::sys::fs::remove(FormatFilePath.c_str()); 22253 llvm::sys::fs::remove(TestFilePath.c_str()); 22254 ASSERT_TRUE(static_cast<bool>(Style)); 22255 ASSERT_EQ(*Style, getGoogleStyle()); 22256 } 22257 22258 TEST_F(ReplacementTest, FormatCodeAfterReplacements) { 22259 // Column limit is 20. 22260 std::string Code = "Type *a =\n" 22261 " new Type();\n" 22262 "g(iiiii, 0, jjjjj,\n" 22263 " 0, kkkkk, 0, mm);\n" 22264 "int bad = format ;"; 22265 std::string Expected = "auto a = new Type();\n" 22266 "g(iiiii, nullptr,\n" 22267 " jjjjj, nullptr,\n" 22268 " kkkkk, nullptr,\n" 22269 " mm);\n" 22270 "int bad = format ;"; 22271 FileID ID = Context.createInMemoryFile("format.cpp", Code); 22272 tooling::Replacements Replaces = toReplacements( 22273 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6, 22274 "auto "), 22275 tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1, 22276 "nullptr"), 22277 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1, 22278 "nullptr"), 22279 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1, 22280 "nullptr")}); 22281 22282 FormatStyle Style = getLLVMStyle(); 22283 Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility. 22284 auto FormattedReplaces = formatReplacements(Code, Replaces, Style); 22285 EXPECT_TRUE(static_cast<bool>(FormattedReplaces)) 22286 << llvm::toString(FormattedReplaces.takeError()) << "\n"; 22287 auto Result = applyAllReplacements(Code, *FormattedReplaces); 22288 EXPECT_TRUE(static_cast<bool>(Result)); 22289 EXPECT_EQ(Expected, *Result); 22290 } 22291 22292 TEST_F(ReplacementTest, SortIncludesAfterReplacement) { 22293 std::string Code = "#include \"a.h\"\n" 22294 "#include \"c.h\"\n" 22295 "\n" 22296 "int main() {\n" 22297 " return 0;\n" 22298 "}"; 22299 std::string Expected = "#include \"a.h\"\n" 22300 "#include \"b.h\"\n" 22301 "#include \"c.h\"\n" 22302 "\n" 22303 "int main() {\n" 22304 " return 0;\n" 22305 "}"; 22306 FileID ID = Context.createInMemoryFile("fix.cpp", Code); 22307 tooling::Replacements Replaces = toReplacements( 22308 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0, 22309 "#include \"b.h\"\n")}); 22310 22311 FormatStyle Style = getLLVMStyle(); 22312 Style.SortIncludes = FormatStyle::SI_CaseSensitive; 22313 auto FormattedReplaces = formatReplacements(Code, Replaces, Style); 22314 EXPECT_TRUE(static_cast<bool>(FormattedReplaces)) 22315 << llvm::toString(FormattedReplaces.takeError()) << "\n"; 22316 auto Result = applyAllReplacements(Code, *FormattedReplaces); 22317 EXPECT_TRUE(static_cast<bool>(Result)); 22318 EXPECT_EQ(Expected, *Result); 22319 } 22320 22321 TEST_F(FormatTest, FormatSortsUsingDeclarations) { 22322 EXPECT_EQ("using std::cin;\n" 22323 "using std::cout;", 22324 format("using std::cout;\n" 22325 "using std::cin;", 22326 getGoogleStyle())); 22327 } 22328 22329 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) { 22330 FormatStyle Style = getLLVMStyle(); 22331 Style.Standard = FormatStyle::LS_Cpp03; 22332 // cpp03 recognize this string as identifier u8 and literal character 'a' 22333 EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style)); 22334 } 22335 22336 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) { 22337 // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers 22338 // all modes, including C++11, C++14 and C++17 22339 EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';")); 22340 } 22341 22342 TEST_F(FormatTest, DoNotFormatLikelyXml) { 22343 EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle())); 22344 EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle())); 22345 } 22346 22347 TEST_F(FormatTest, StructuredBindings) { 22348 // Structured bindings is a C++17 feature. 22349 // all modes, including C++11, C++14 and C++17 22350 verifyFormat("auto [a, b] = f();"); 22351 EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();")); 22352 EXPECT_EQ("const auto [a, b] = f();", format("const auto[a, b] = f();")); 22353 EXPECT_EQ("auto const [a, b] = f();", format("auto const[a, b] = f();")); 22354 EXPECT_EQ("auto const volatile [a, b] = f();", 22355 format("auto const volatile[a, b] = f();")); 22356 EXPECT_EQ("auto [a, b, c] = f();", format("auto [ a , b,c ] = f();")); 22357 EXPECT_EQ("auto &[a, b, c] = f();", 22358 format("auto &[ a , b,c ] = f();")); 22359 EXPECT_EQ("auto &&[a, b, c] = f();", 22360 format("auto &&[ a , b,c ] = f();")); 22361 EXPECT_EQ("auto const &[a, b] = f();", format("auto const&[a, b] = f();")); 22362 EXPECT_EQ("auto const volatile &&[a, b] = f();", 22363 format("auto const volatile &&[a, b] = f();")); 22364 EXPECT_EQ("auto const &&[a, b] = f();", 22365 format("auto const && [a, b] = f();")); 22366 EXPECT_EQ("const auto &[a, b] = f();", 22367 format("const auto & [a, b] = f();")); 22368 EXPECT_EQ("const auto volatile &&[a, b] = f();", 22369 format("const auto volatile &&[a, b] = f();")); 22370 EXPECT_EQ("volatile const auto &&[a, b] = f();", 22371 format("volatile const auto &&[a, b] = f();")); 22372 EXPECT_EQ("const auto &&[a, b] = f();", 22373 format("const auto && [a, b] = f();")); 22374 22375 // Make sure we don't mistake structured bindings for lambdas. 22376 FormatStyle PointerMiddle = getLLVMStyle(); 22377 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle; 22378 verifyFormat("auto [a1, b]{A * i};", getGoogleStyle()); 22379 verifyFormat("auto [a2, b]{A * i};", getLLVMStyle()); 22380 verifyFormat("auto [a3, b]{A * i};", PointerMiddle); 22381 verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle()); 22382 verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle()); 22383 verifyFormat("auto const [a3, b]{A * i};", PointerMiddle); 22384 verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle()); 22385 verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle()); 22386 verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle); 22387 verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle()); 22388 verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle()); 22389 verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle); 22390 22391 EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}", 22392 format("for (const auto && [a, b] : some_range) {\n}")); 22393 EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}", 22394 format("for (const auto & [a, b] : some_range) {\n}")); 22395 EXPECT_EQ("for (const auto [a, b] : some_range) {\n}", 22396 format("for (const auto[a, b] : some_range) {\n}")); 22397 EXPECT_EQ("auto [x, y](expr);", format("auto[x,y] (expr);")); 22398 EXPECT_EQ("auto &[x, y](expr);", format("auto & [x,y] (expr);")); 22399 EXPECT_EQ("auto &&[x, y](expr);", format("auto && [x,y] (expr);")); 22400 EXPECT_EQ("auto const &[x, y](expr);", 22401 format("auto const & [x,y] (expr);")); 22402 EXPECT_EQ("auto const &&[x, y](expr);", 22403 format("auto const && [x,y] (expr);")); 22404 EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y] {expr};")); 22405 EXPECT_EQ("auto const &[x, y]{expr};", 22406 format("auto const & [x,y] {expr};")); 22407 EXPECT_EQ("auto const &&[x, y]{expr};", 22408 format("auto const && [x,y] {expr};")); 22409 22410 FormatStyle Spaces = getLLVMStyle(); 22411 Spaces.SpacesInSquareBrackets = true; 22412 verifyFormat("auto [ a, b ] = f();", Spaces); 22413 verifyFormat("auto &&[ a, b ] = f();", Spaces); 22414 verifyFormat("auto &[ a, b ] = f();", Spaces); 22415 verifyFormat("auto const &&[ a, b ] = f();", Spaces); 22416 verifyFormat("auto const &[ a, b ] = f();", Spaces); 22417 } 22418 22419 TEST_F(FormatTest, FileAndCode) { 22420 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", "")); 22421 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", "")); 22422 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", "")); 22423 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "")); 22424 EXPECT_EQ(FormatStyle::LK_ObjC, 22425 guessLanguage("foo.h", "@interface Foo\n@end\n")); 22426 EXPECT_EQ( 22427 FormatStyle::LK_ObjC, 22428 guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }")); 22429 EXPECT_EQ(FormatStyle::LK_ObjC, 22430 guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))")); 22431 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;")); 22432 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", "")); 22433 EXPECT_EQ(FormatStyle::LK_ObjC, 22434 guessLanguage("foo", "@interface Foo\n@end\n")); 22435 EXPECT_EQ(FormatStyle::LK_ObjC, 22436 guessLanguage("foo.h", "int DoStuff(CGRect rect);\n")); 22437 EXPECT_EQ( 22438 FormatStyle::LK_ObjC, 22439 guessLanguage("foo.h", 22440 "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n")); 22441 EXPECT_EQ( 22442 FormatStyle::LK_Cpp, 22443 guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;")); 22444 } 22445 22446 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) { 22447 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];")); 22448 EXPECT_EQ(FormatStyle::LK_ObjC, 22449 guessLanguage("foo.h", "array[[calculator getIndex]];")); 22450 EXPECT_EQ(FormatStyle::LK_Cpp, 22451 guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];")); 22452 EXPECT_EQ( 22453 FormatStyle::LK_Cpp, 22454 guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];")); 22455 EXPECT_EQ(FormatStyle::LK_ObjC, 22456 guessLanguage("foo.h", "[[noreturn foo] bar];")); 22457 EXPECT_EQ(FormatStyle::LK_Cpp, 22458 guessLanguage("foo.h", "[[clang::fallthrough]];")); 22459 EXPECT_EQ(FormatStyle::LK_ObjC, 22460 guessLanguage("foo.h", "[[clang:fallthrough] foo];")); 22461 EXPECT_EQ(FormatStyle::LK_Cpp, 22462 guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];")); 22463 EXPECT_EQ(FormatStyle::LK_Cpp, 22464 guessLanguage("foo.h", "[[using clang: fallthrough]];")); 22465 EXPECT_EQ(FormatStyle::LK_ObjC, 22466 guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];")); 22467 EXPECT_EQ(FormatStyle::LK_Cpp, 22468 guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];")); 22469 EXPECT_EQ( 22470 FormatStyle::LK_Cpp, 22471 guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)")); 22472 EXPECT_EQ( 22473 FormatStyle::LK_Cpp, 22474 guessLanguage("foo.h", 22475 "[[clang::callable_when(\"unconsumed\", \"unknown\")]]")); 22476 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]")); 22477 } 22478 22479 TEST_F(FormatTest, GuessLanguageWithCaret) { 22480 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);")); 22481 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);")); 22482 EXPECT_EQ(FormatStyle::LK_ObjC, 22483 guessLanguage("foo.h", "int(^)(char, float);")); 22484 EXPECT_EQ(FormatStyle::LK_ObjC, 22485 guessLanguage("foo.h", "int(^foo)(char, float);")); 22486 EXPECT_EQ(FormatStyle::LK_ObjC, 22487 guessLanguage("foo.h", "int(^foo[10])(char, float);")); 22488 EXPECT_EQ(FormatStyle::LK_ObjC, 22489 guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);")); 22490 EXPECT_EQ( 22491 FormatStyle::LK_ObjC, 22492 guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);")); 22493 } 22494 22495 TEST_F(FormatTest, GuessLanguageWithPragmas) { 22496 EXPECT_EQ(FormatStyle::LK_Cpp, 22497 guessLanguage("foo.h", "__pragma(warning(disable:))")); 22498 EXPECT_EQ(FormatStyle::LK_Cpp, 22499 guessLanguage("foo.h", "#pragma(warning(disable:))")); 22500 EXPECT_EQ(FormatStyle::LK_Cpp, 22501 guessLanguage("foo.h", "_Pragma(warning(disable:))")); 22502 } 22503 22504 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) { 22505 // ASM symbolic names are identifiers that must be surrounded by [] without 22506 // space in between: 22507 // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands 22508 22509 // Example from https://bugs.llvm.org/show_bug.cgi?id=45108. 22510 verifyFormat(R"(// 22511 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result)); 22512 )"); 22513 22514 // A list of several ASM symbolic names. 22515 verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)"); 22516 22517 // ASM symbolic names in inline ASM with inputs and outputs. 22518 verifyFormat(R"(// 22519 asm("cmoveq %1, %2, %[result]" 22520 : [result] "=r"(result) 22521 : "r"(test), "r"(new), "[result]"(old)); 22522 )"); 22523 22524 // ASM symbolic names in inline ASM with no outputs. 22525 verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)"); 22526 } 22527 22528 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) { 22529 EXPECT_EQ(FormatStyle::LK_Cpp, 22530 guessLanguage("foo.h", "void f() {\n" 22531 " asm (\"mov %[e], %[d]\"\n" 22532 " : [d] \"=rm\" (d)\n" 22533 " [e] \"rm\" (*e));\n" 22534 "}")); 22535 EXPECT_EQ(FormatStyle::LK_Cpp, 22536 guessLanguage("foo.h", "void f() {\n" 22537 " _asm (\"mov %[e], %[d]\"\n" 22538 " : [d] \"=rm\" (d)\n" 22539 " [e] \"rm\" (*e));\n" 22540 "}")); 22541 EXPECT_EQ(FormatStyle::LK_Cpp, 22542 guessLanguage("foo.h", "void f() {\n" 22543 " __asm (\"mov %[e], %[d]\"\n" 22544 " : [d] \"=rm\" (d)\n" 22545 " [e] \"rm\" (*e));\n" 22546 "}")); 22547 EXPECT_EQ(FormatStyle::LK_Cpp, 22548 guessLanguage("foo.h", "void f() {\n" 22549 " __asm__ (\"mov %[e], %[d]\"\n" 22550 " : [d] \"=rm\" (d)\n" 22551 " [e] \"rm\" (*e));\n" 22552 "}")); 22553 EXPECT_EQ(FormatStyle::LK_Cpp, 22554 guessLanguage("foo.h", "void f() {\n" 22555 " asm (\"mov %[e], %[d]\"\n" 22556 " : [d] \"=rm\" (d),\n" 22557 " [e] \"rm\" (*e));\n" 22558 "}")); 22559 EXPECT_EQ(FormatStyle::LK_Cpp, 22560 guessLanguage("foo.h", "void f() {\n" 22561 " asm volatile (\"mov %[e], %[d]\"\n" 22562 " : [d] \"=rm\" (d)\n" 22563 " [e] \"rm\" (*e));\n" 22564 "}")); 22565 } 22566 22567 TEST_F(FormatTest, GuessLanguageWithChildLines) { 22568 EXPECT_EQ(FormatStyle::LK_Cpp, 22569 guessLanguage("foo.h", "#define FOO ({ std::string s; })")); 22570 EXPECT_EQ(FormatStyle::LK_ObjC, 22571 guessLanguage("foo.h", "#define FOO ({ NSString *s; })")); 22572 EXPECT_EQ( 22573 FormatStyle::LK_Cpp, 22574 guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })")); 22575 EXPECT_EQ( 22576 FormatStyle::LK_ObjC, 22577 guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })")); 22578 } 22579 22580 TEST_F(FormatTest, TypenameMacros) { 22581 std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"}; 22582 22583 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353 22584 FormatStyle Google = getGoogleStyleWithColumns(0); 22585 Google.TypenameMacros = TypenameMacros; 22586 verifyFormat("struct foo {\n" 22587 " int bar;\n" 22588 " TAILQ_ENTRY(a) bleh;\n" 22589 "};", 22590 Google); 22591 22592 FormatStyle Macros = getLLVMStyle(); 22593 Macros.TypenameMacros = TypenameMacros; 22594 22595 verifyFormat("STACK_OF(int) a;", Macros); 22596 verifyFormat("STACK_OF(int) *a;", Macros); 22597 verifyFormat("STACK_OF(int const *) *a;", Macros); 22598 verifyFormat("STACK_OF(int *const) *a;", Macros); 22599 verifyFormat("STACK_OF(int, string) a;", Macros); 22600 verifyFormat("STACK_OF(LIST(int)) a;", Macros); 22601 verifyFormat("STACK_OF(LIST(int)) a, b;", Macros); 22602 verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros); 22603 verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros); 22604 verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros); 22605 verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros); 22606 22607 Macros.PointerAlignment = FormatStyle::PAS_Left; 22608 verifyFormat("STACK_OF(int)* a;", Macros); 22609 verifyFormat("STACK_OF(int*)* a;", Macros); 22610 verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros); 22611 verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros); 22612 verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros); 22613 } 22614 22615 TEST_F(FormatTest, AtomicQualifier) { 22616 // Check that we treate _Atomic as a type and not a function call 22617 FormatStyle Google = getGoogleStyleWithColumns(0); 22618 verifyFormat("struct foo {\n" 22619 " int a1;\n" 22620 " _Atomic(a) a2;\n" 22621 " _Atomic(_Atomic(int) *const) a3;\n" 22622 "};", 22623 Google); 22624 verifyFormat("_Atomic(uint64_t) a;"); 22625 verifyFormat("_Atomic(uint64_t) *a;"); 22626 verifyFormat("_Atomic(uint64_t const *) *a;"); 22627 verifyFormat("_Atomic(uint64_t *const) *a;"); 22628 verifyFormat("_Atomic(const uint64_t *) *a;"); 22629 verifyFormat("_Atomic(uint64_t) a;"); 22630 verifyFormat("_Atomic(_Atomic(uint64_t)) a;"); 22631 verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;"); 22632 verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}"); 22633 verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);"); 22634 22635 verifyFormat("_Atomic(uint64_t) *s(InitValue);"); 22636 verifyFormat("_Atomic(uint64_t) *s{InitValue};"); 22637 FormatStyle Style = getLLVMStyle(); 22638 Style.PointerAlignment = FormatStyle::PAS_Left; 22639 verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style); 22640 verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style); 22641 verifyFormat("_Atomic(int)* a;", Style); 22642 verifyFormat("_Atomic(int*)* a;", Style); 22643 verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style); 22644 22645 Style.SpacesInCStyleCastParentheses = true; 22646 Style.SpacesInParentheses = false; 22647 verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style); 22648 Style.SpacesInCStyleCastParentheses = false; 22649 Style.SpacesInParentheses = true; 22650 verifyFormat("x = (_Atomic( uint64_t ))*a;", Style); 22651 verifyFormat("x = (_Atomic( uint64_t ))&a;", Style); 22652 } 22653 22654 TEST_F(FormatTest, AmbersandInLamda) { 22655 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899 22656 FormatStyle AlignStyle = getLLVMStyle(); 22657 AlignStyle.PointerAlignment = FormatStyle::PAS_Left; 22658 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle); 22659 AlignStyle.PointerAlignment = FormatStyle::PAS_Right; 22660 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle); 22661 } 22662 22663 TEST_F(FormatTest, SpacesInConditionalStatement) { 22664 FormatStyle Spaces = getLLVMStyle(); 22665 Spaces.IfMacros.clear(); 22666 Spaces.IfMacros.push_back("MYIF"); 22667 Spaces.SpacesInConditionalStatement = true; 22668 verifyFormat("for ( int i = 0; i; i++ )\n continue;", Spaces); 22669 verifyFormat("if ( !a )\n return;", Spaces); 22670 verifyFormat("if ( a )\n return;", Spaces); 22671 verifyFormat("if constexpr ( a )\n return;", Spaces); 22672 verifyFormat("MYIF ( a )\n return;", Spaces); 22673 verifyFormat("MYIF ( a )\n return;\nelse MYIF ( b )\n return;", Spaces); 22674 verifyFormat("MYIF ( a )\n return;\nelse\n return;", Spaces); 22675 verifyFormat("switch ( a )\ncase 1:\n return;", Spaces); 22676 verifyFormat("while ( a )\n return;", Spaces); 22677 verifyFormat("while ( (a && b) )\n return;", Spaces); 22678 verifyFormat("do {\n} while ( 1 != 0 );", Spaces); 22679 verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces); 22680 // Check that space on the left of "::" is inserted as expected at beginning 22681 // of condition. 22682 verifyFormat("while ( ::func() )\n return;", Spaces); 22683 22684 // Check impact of ControlStatementsExceptControlMacros is honored. 22685 Spaces.SpaceBeforeParens = 22686 FormatStyle::SBPO_ControlStatementsExceptControlMacros; 22687 verifyFormat("MYIF( a )\n return;", Spaces); 22688 verifyFormat("MYIF( a )\n return;\nelse MYIF( b )\n return;", Spaces); 22689 verifyFormat("MYIF( a )\n return;\nelse\n return;", Spaces); 22690 } 22691 22692 TEST_F(FormatTest, AlternativeOperators) { 22693 // Test case for ensuring alternate operators are not 22694 // combined with their right most neighbour. 22695 verifyFormat("int a and b;"); 22696 verifyFormat("int a and_eq b;"); 22697 verifyFormat("int a bitand b;"); 22698 verifyFormat("int a bitor b;"); 22699 verifyFormat("int a compl b;"); 22700 verifyFormat("int a not b;"); 22701 verifyFormat("int a not_eq b;"); 22702 verifyFormat("int a or b;"); 22703 verifyFormat("int a xor b;"); 22704 verifyFormat("int a xor_eq b;"); 22705 verifyFormat("return this not_eq bitand other;"); 22706 verifyFormat("bool operator not_eq(const X bitand other)"); 22707 22708 verifyFormat("int a and 5;"); 22709 verifyFormat("int a and_eq 5;"); 22710 verifyFormat("int a bitand 5;"); 22711 verifyFormat("int a bitor 5;"); 22712 verifyFormat("int a compl 5;"); 22713 verifyFormat("int a not 5;"); 22714 verifyFormat("int a not_eq 5;"); 22715 verifyFormat("int a or 5;"); 22716 verifyFormat("int a xor 5;"); 22717 verifyFormat("int a xor_eq 5;"); 22718 22719 verifyFormat("int a compl(5);"); 22720 verifyFormat("int a not(5);"); 22721 22722 /* FIXME handle alternate tokens 22723 * https://en.cppreference.com/w/cpp/language/operator_alternative 22724 // alternative tokens 22725 verifyFormat("compl foo();"); // ~foo(); 22726 verifyFormat("foo() <%%>;"); // foo(); 22727 verifyFormat("void foo() <%%>;"); // void foo(){} 22728 verifyFormat("int a <:1:>;"); // int a[1];[ 22729 verifyFormat("%:define ABC abc"); // #define ABC abc 22730 verifyFormat("%:%:"); // ## 22731 */ 22732 } 22733 22734 TEST_F(FormatTest, STLWhileNotDefineChed) { 22735 verifyFormat("#if defined(while)\n" 22736 "#define while EMIT WARNING C4005\n" 22737 "#endif // while"); 22738 } 22739 22740 TEST_F(FormatTest, OperatorSpacing) { 22741 FormatStyle Style = getLLVMStyle(); 22742 Style.PointerAlignment = FormatStyle::PAS_Right; 22743 verifyFormat("Foo::operator*();", Style); 22744 verifyFormat("Foo::operator void *();", Style); 22745 verifyFormat("Foo::operator void **();", Style); 22746 verifyFormat("Foo::operator void *&();", Style); 22747 verifyFormat("Foo::operator void *&&();", Style); 22748 verifyFormat("Foo::operator void const *();", Style); 22749 verifyFormat("Foo::operator void const **();", Style); 22750 verifyFormat("Foo::operator void const *&();", Style); 22751 verifyFormat("Foo::operator void const *&&();", Style); 22752 verifyFormat("Foo::operator()(void *);", Style); 22753 verifyFormat("Foo::operator*(void *);", Style); 22754 verifyFormat("Foo::operator*();", Style); 22755 verifyFormat("Foo::operator**();", Style); 22756 verifyFormat("Foo::operator&();", Style); 22757 verifyFormat("Foo::operator<int> *();", Style); 22758 verifyFormat("Foo::operator<Foo> *();", Style); 22759 verifyFormat("Foo::operator<int> **();", Style); 22760 verifyFormat("Foo::operator<Foo> **();", Style); 22761 verifyFormat("Foo::operator<int> &();", Style); 22762 verifyFormat("Foo::operator<Foo> &();", Style); 22763 verifyFormat("Foo::operator<int> &&();", Style); 22764 verifyFormat("Foo::operator<Foo> &&();", Style); 22765 verifyFormat("Foo::operator<int> *&();", Style); 22766 verifyFormat("Foo::operator<Foo> *&();", Style); 22767 verifyFormat("Foo::operator<int> *&&();", Style); 22768 verifyFormat("Foo::operator<Foo> *&&();", Style); 22769 verifyFormat("operator*(int (*)(), class Foo);", Style); 22770 22771 verifyFormat("Foo::operator&();", Style); 22772 verifyFormat("Foo::operator void &();", Style); 22773 verifyFormat("Foo::operator void const &();", Style); 22774 verifyFormat("Foo::operator()(void &);", Style); 22775 verifyFormat("Foo::operator&(void &);", Style); 22776 verifyFormat("Foo::operator&();", Style); 22777 verifyFormat("operator&(int (&)(), class Foo);", Style); 22778 verifyFormat("operator&&(int (&)(), class Foo);", Style); 22779 22780 verifyFormat("Foo::operator&&();", Style); 22781 verifyFormat("Foo::operator**();", Style); 22782 verifyFormat("Foo::operator void &&();", Style); 22783 verifyFormat("Foo::operator void const &&();", Style); 22784 verifyFormat("Foo::operator()(void &&);", Style); 22785 verifyFormat("Foo::operator&&(void &&);", Style); 22786 verifyFormat("Foo::operator&&();", Style); 22787 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 22788 verifyFormat("operator const nsTArrayRight<E> &()", Style); 22789 verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()", 22790 Style); 22791 verifyFormat("operator void **()", Style); 22792 verifyFormat("operator const FooRight<Object> &()", Style); 22793 verifyFormat("operator const FooRight<Object> *()", Style); 22794 verifyFormat("operator const FooRight<Object> **()", Style); 22795 verifyFormat("operator const FooRight<Object> *&()", Style); 22796 verifyFormat("operator const FooRight<Object> *&&()", Style); 22797 22798 Style.PointerAlignment = FormatStyle::PAS_Left; 22799 verifyFormat("Foo::operator*();", Style); 22800 verifyFormat("Foo::operator**();", Style); 22801 verifyFormat("Foo::operator void*();", Style); 22802 verifyFormat("Foo::operator void**();", Style); 22803 verifyFormat("Foo::operator void*&();", Style); 22804 verifyFormat("Foo::operator void*&&();", Style); 22805 verifyFormat("Foo::operator void const*();", Style); 22806 verifyFormat("Foo::operator void const**();", Style); 22807 verifyFormat("Foo::operator void const*&();", Style); 22808 verifyFormat("Foo::operator void const*&&();", Style); 22809 verifyFormat("Foo::operator/*comment*/ void*();", Style); 22810 verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style); 22811 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style); 22812 verifyFormat("Foo::operator()(void*);", Style); 22813 verifyFormat("Foo::operator*(void*);", Style); 22814 verifyFormat("Foo::operator*();", Style); 22815 verifyFormat("Foo::operator<int>*();", Style); 22816 verifyFormat("Foo::operator<Foo>*();", Style); 22817 verifyFormat("Foo::operator<int>**();", Style); 22818 verifyFormat("Foo::operator<Foo>**();", Style); 22819 verifyFormat("Foo::operator<Foo>*&();", Style); 22820 verifyFormat("Foo::operator<int>&();", Style); 22821 verifyFormat("Foo::operator<Foo>&();", Style); 22822 verifyFormat("Foo::operator<int>&&();", Style); 22823 verifyFormat("Foo::operator<Foo>&&();", Style); 22824 verifyFormat("Foo::operator<int>*&();", Style); 22825 verifyFormat("Foo::operator<Foo>*&();", Style); 22826 verifyFormat("operator*(int (*)(), class Foo);", Style); 22827 22828 verifyFormat("Foo::operator&();", Style); 22829 verifyFormat("Foo::operator void&();", Style); 22830 verifyFormat("Foo::operator void const&();", Style); 22831 verifyFormat("Foo::operator/*comment*/ void&();", Style); 22832 verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style); 22833 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style); 22834 verifyFormat("Foo::operator()(void&);", Style); 22835 verifyFormat("Foo::operator&(void&);", Style); 22836 verifyFormat("Foo::operator&();", Style); 22837 verifyFormat("operator&(int (&)(), class Foo);", Style); 22838 verifyFormat("operator&(int (&&)(), class Foo);", Style); 22839 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 22840 22841 verifyFormat("Foo::operator&&();", Style); 22842 verifyFormat("Foo::operator void&&();", Style); 22843 verifyFormat("Foo::operator void const&&();", Style); 22844 verifyFormat("Foo::operator/*comment*/ void&&();", Style); 22845 verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style); 22846 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style); 22847 verifyFormat("Foo::operator()(void&&);", Style); 22848 verifyFormat("Foo::operator&&(void&&);", Style); 22849 verifyFormat("Foo::operator&&();", Style); 22850 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 22851 verifyFormat("operator const nsTArrayLeft<E>&()", Style); 22852 verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()", 22853 Style); 22854 verifyFormat("operator void**()", Style); 22855 verifyFormat("operator const FooLeft<Object>&()", Style); 22856 verifyFormat("operator const FooLeft<Object>*()", Style); 22857 verifyFormat("operator const FooLeft<Object>**()", Style); 22858 verifyFormat("operator const FooLeft<Object>*&()", Style); 22859 verifyFormat("operator const FooLeft<Object>*&&()", Style); 22860 22861 // PR45107 22862 verifyFormat("operator Vector<String>&();", Style); 22863 verifyFormat("operator const Vector<String>&();", Style); 22864 verifyFormat("operator foo::Bar*();", Style); 22865 verifyFormat("operator const Foo<X>::Bar<Y>*();", Style); 22866 verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();", 22867 Style); 22868 22869 Style.PointerAlignment = FormatStyle::PAS_Middle; 22870 verifyFormat("Foo::operator*();", Style); 22871 verifyFormat("Foo::operator void *();", Style); 22872 verifyFormat("Foo::operator()(void *);", Style); 22873 verifyFormat("Foo::operator*(void *);", Style); 22874 verifyFormat("Foo::operator*();", Style); 22875 verifyFormat("operator*(int (*)(), class Foo);", Style); 22876 22877 verifyFormat("Foo::operator&();", Style); 22878 verifyFormat("Foo::operator void &();", Style); 22879 verifyFormat("Foo::operator void const &();", Style); 22880 verifyFormat("Foo::operator()(void &);", Style); 22881 verifyFormat("Foo::operator&(void &);", Style); 22882 verifyFormat("Foo::operator&();", Style); 22883 verifyFormat("operator&(int (&)(), class Foo);", Style); 22884 22885 verifyFormat("Foo::operator&&();", Style); 22886 verifyFormat("Foo::operator void &&();", Style); 22887 verifyFormat("Foo::operator void const &&();", Style); 22888 verifyFormat("Foo::operator()(void &&);", Style); 22889 verifyFormat("Foo::operator&&(void &&);", Style); 22890 verifyFormat("Foo::operator&&();", Style); 22891 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 22892 } 22893 22894 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) { 22895 FormatStyle Style = getLLVMStyle(); 22896 // PR46157 22897 verifyFormat("foo(operator+, -42);", Style); 22898 verifyFormat("foo(operator++, -42);", Style); 22899 verifyFormat("foo(operator--, -42);", Style); 22900 verifyFormat("foo(-42, operator--);", Style); 22901 verifyFormat("foo(-42, operator, );", Style); 22902 verifyFormat("foo(operator, , -42);", Style); 22903 } 22904 22905 TEST_F(FormatTest, WhitespaceSensitiveMacros) { 22906 FormatStyle Style = getLLVMStyle(); 22907 Style.WhitespaceSensitiveMacros.push_back("FOO"); 22908 22909 // Don't use the helpers here, since 'mess up' will change the whitespace 22910 // and these are all whitespace sensitive by definition 22911 EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);", 22912 format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style)); 22913 EXPECT_EQ( 22914 "FOO(String-ized&Messy+But\\(: :Still)=Intentional);", 22915 format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style)); 22916 EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);", 22917 format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style)); 22918 EXPECT_EQ("FOO(String-ized&Messy+But,: :\n" 22919 " Still=Intentional);", 22920 format("FOO(String-ized&Messy+But,: :\n" 22921 " Still=Intentional);", 22922 Style)); 22923 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 22924 EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n" 22925 " Still=Intentional);", 22926 format("FOO(String-ized=&Messy+But,: :\n" 22927 " Still=Intentional);", 22928 Style)); 22929 22930 Style.ColumnLimit = 21; 22931 EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);", 22932 format("FOO(String-ized&Messy+But: :Still=Intentional);", Style)); 22933 } 22934 22935 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) { 22936 // These tests are not in NamespaceFixer because that doesn't 22937 // test its interaction with line wrapping 22938 FormatStyle Style = getLLVMStyleWithColumns(80); 22939 verifyFormat("namespace {\n" 22940 "int i;\n" 22941 "int j;\n" 22942 "} // namespace", 22943 Style); 22944 22945 verifyFormat("namespace AAA {\n" 22946 "int i;\n" 22947 "int j;\n" 22948 "} // namespace AAA", 22949 Style); 22950 22951 EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n" 22952 "int i;\n" 22953 "int j;\n" 22954 "} // namespace Averyveryveryverylongnamespace", 22955 format("namespace Averyveryveryverylongnamespace {\n" 22956 "int i;\n" 22957 "int j;\n" 22958 "}", 22959 Style)); 22960 22961 EXPECT_EQ( 22962 "namespace " 22963 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n" 22964 " went::mad::now {\n" 22965 "int i;\n" 22966 "int j;\n" 22967 "} // namespace\n" 22968 " // " 22969 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::" 22970 "went::mad::now", 22971 format("namespace " 22972 "would::it::save::you::a::lot::of::time::if_::i::" 22973 "just::gave::up::and_::went::mad::now {\n" 22974 "int i;\n" 22975 "int j;\n" 22976 "}", 22977 Style)); 22978 22979 // This used to duplicate the comment again and again on subsequent runs 22980 EXPECT_EQ( 22981 "namespace " 22982 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n" 22983 " went::mad::now {\n" 22984 "int i;\n" 22985 "int j;\n" 22986 "} // namespace\n" 22987 " // " 22988 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::" 22989 "went::mad::now", 22990 format("namespace " 22991 "would::it::save::you::a::lot::of::time::if_::i::" 22992 "just::gave::up::and_::went::mad::now {\n" 22993 "int i;\n" 22994 "int j;\n" 22995 "} // namespace\n" 22996 " // " 22997 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::" 22998 "and_::went::mad::now", 22999 Style)); 23000 } 23001 23002 TEST_F(FormatTest, LikelyUnlikely) { 23003 FormatStyle Style = getLLVMStyle(); 23004 23005 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23006 " return 29;\n" 23007 "}", 23008 Style); 23009 23010 verifyFormat("if (argc > 5) [[likely]] {\n" 23011 " return 29;\n" 23012 "}", 23013 Style); 23014 23015 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23016 " return 29;\n" 23017 "} else [[likely]] {\n" 23018 " return 42;\n" 23019 "}\n", 23020 Style); 23021 23022 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23023 " return 29;\n" 23024 "} else if (argc > 10) [[likely]] {\n" 23025 " return 99;\n" 23026 "} else {\n" 23027 " return 42;\n" 23028 "}\n", 23029 Style); 23030 23031 verifyFormat("if (argc > 5) [[gnu::unused]] {\n" 23032 " return 29;\n" 23033 "}", 23034 Style); 23035 23036 verifyFormat("if (argc > 5) [[unlikely]]\n" 23037 " return 29;\n", 23038 Style); 23039 verifyFormat("if (argc > 5) [[likely]]\n" 23040 " return 29;\n", 23041 Style); 23042 23043 Style.AttributeMacros.push_back("UNLIKELY"); 23044 Style.AttributeMacros.push_back("LIKELY"); 23045 verifyFormat("if (argc > 5) UNLIKELY\n" 23046 " return 29;\n", 23047 Style); 23048 23049 verifyFormat("if (argc > 5) UNLIKELY {\n" 23050 " return 29;\n" 23051 "}", 23052 Style); 23053 verifyFormat("if (argc > 5) UNLIKELY {\n" 23054 " return 29;\n" 23055 "} else [[likely]] {\n" 23056 " return 42;\n" 23057 "}\n", 23058 Style); 23059 verifyFormat("if (argc > 5) UNLIKELY {\n" 23060 " return 29;\n" 23061 "} else LIKELY {\n" 23062 " return 42;\n" 23063 "}\n", 23064 Style); 23065 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23066 " return 29;\n" 23067 "} else LIKELY {\n" 23068 " return 42;\n" 23069 "}\n", 23070 Style); 23071 } 23072 23073 TEST_F(FormatTest, PenaltyIndentedWhitespace) { 23074 verifyFormat("Constructor()\n" 23075 " : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 23076 " aaaa(aaaaaaaaaaaaaaaaaa, " 23077 "aaaaaaaaaaaaaaaaaat))"); 23078 verifyFormat("Constructor()\n" 23079 " : aaaaaaaaaaaaa(aaaaaa), " 23080 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)"); 23081 23082 FormatStyle StyleWithWhitespacePenalty = getLLVMStyle(); 23083 StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5; 23084 verifyFormat("Constructor()\n" 23085 " : aaaaaa(aaaaaa),\n" 23086 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 23087 " aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))", 23088 StyleWithWhitespacePenalty); 23089 verifyFormat("Constructor()\n" 23090 " : aaaaaaaaaaaaa(aaaaaa), " 23091 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)", 23092 StyleWithWhitespacePenalty); 23093 } 23094 23095 TEST_F(FormatTest, LLVMDefaultStyle) { 23096 FormatStyle Style = getLLVMStyle(); 23097 verifyFormat("extern \"C\" {\n" 23098 "int foo();\n" 23099 "}", 23100 Style); 23101 } 23102 TEST_F(FormatTest, GNUDefaultStyle) { 23103 FormatStyle Style = getGNUStyle(); 23104 verifyFormat("extern \"C\"\n" 23105 "{\n" 23106 " int foo ();\n" 23107 "}", 23108 Style); 23109 } 23110 TEST_F(FormatTest, MozillaDefaultStyle) { 23111 FormatStyle Style = getMozillaStyle(); 23112 verifyFormat("extern \"C\"\n" 23113 "{\n" 23114 " int foo();\n" 23115 "}", 23116 Style); 23117 } 23118 TEST_F(FormatTest, GoogleDefaultStyle) { 23119 FormatStyle Style = getGoogleStyle(); 23120 verifyFormat("extern \"C\" {\n" 23121 "int foo();\n" 23122 "}", 23123 Style); 23124 } 23125 TEST_F(FormatTest, ChromiumDefaultStyle) { 23126 FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp); 23127 verifyFormat("extern \"C\" {\n" 23128 "int foo();\n" 23129 "}", 23130 Style); 23131 } 23132 TEST_F(FormatTest, MicrosoftDefaultStyle) { 23133 FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp); 23134 verifyFormat("extern \"C\"\n" 23135 "{\n" 23136 " int foo();\n" 23137 "}", 23138 Style); 23139 } 23140 TEST_F(FormatTest, WebKitDefaultStyle) { 23141 FormatStyle Style = getWebKitStyle(); 23142 verifyFormat("extern \"C\" {\n" 23143 "int foo();\n" 23144 "}", 23145 Style); 23146 } 23147 23148 TEST_F(FormatTest, ConceptsAndRequires) { 23149 FormatStyle Style = getLLVMStyle(); 23150 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 23151 23152 verifyFormat("template <typename T>\n" 23153 "concept Hashable = requires(T a) {\n" 23154 " { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;\n" 23155 "};", 23156 Style); 23157 verifyFormat("template <typename T>\n" 23158 "concept EqualityComparable = requires(T a, T b) {\n" 23159 " { a == b } -> bool;\n" 23160 "};", 23161 Style); 23162 verifyFormat("template <typename T>\n" 23163 "concept EqualityComparable = requires(T a, T b) {\n" 23164 " { a == b } -> bool;\n" 23165 " { a != b } -> bool;\n" 23166 "};", 23167 Style); 23168 verifyFormat("template <typename T>\n" 23169 "concept EqualityComparable = requires(T a, T b) {\n" 23170 " { a == b } -> bool;\n" 23171 " { a != b } -> bool;\n" 23172 "};", 23173 Style); 23174 23175 verifyFormat("template <typename It>\n" 23176 "requires Iterator<It>\n" 23177 "void sort(It begin, It end) {\n" 23178 " //....\n" 23179 "}", 23180 Style); 23181 23182 verifyFormat("template <typename T>\n" 23183 "concept Large = sizeof(T) > 10;", 23184 Style); 23185 23186 verifyFormat("template <typename T, typename U>\n" 23187 "concept FooableWith = requires(T t, U u) {\n" 23188 " typename T::foo_type;\n" 23189 " { t.foo(u) } -> typename T::foo_type;\n" 23190 " t++;\n" 23191 "};\n" 23192 "void doFoo(FooableWith<int> auto t) {\n" 23193 " t.foo(3);\n" 23194 "}", 23195 Style); 23196 verifyFormat("template <typename T>\n" 23197 "concept Context = sizeof(T) == 1;", 23198 Style); 23199 verifyFormat("template <typename T>\n" 23200 "concept Context = is_specialization_of_v<context, T>;", 23201 Style); 23202 verifyFormat("template <typename T>\n" 23203 "concept Node = std::is_object_v<T>;", 23204 Style); 23205 verifyFormat("template <typename T>\n" 23206 "concept Tree = true;", 23207 Style); 23208 23209 verifyFormat("template <typename T> int g(T i) requires Concept1<I> {\n" 23210 " //...\n" 23211 "}", 23212 Style); 23213 23214 verifyFormat( 23215 "template <typename T> int g(T i) requires Concept1<I> && Concept2<I> {\n" 23216 " //...\n" 23217 "}", 23218 Style); 23219 23220 verifyFormat( 23221 "template <typename T> int g(T i) requires Concept1<I> || Concept2<I> {\n" 23222 " //...\n" 23223 "}", 23224 Style); 23225 23226 verifyFormat("template <typename T>\n" 23227 "veryveryvery_long_return_type g(T i) requires Concept1<I> || " 23228 "Concept2<I> {\n" 23229 " //...\n" 23230 "}", 23231 Style); 23232 23233 verifyFormat("template <typename T>\n" 23234 "veryveryvery_long_return_type g(T i) requires Concept1<I> && " 23235 "Concept2<I> {\n" 23236 " //...\n" 23237 "}", 23238 Style); 23239 23240 verifyFormat( 23241 "template <typename T>\n" 23242 "veryveryvery_long_return_type g(T i) requires Concept1 && Concept2 {\n" 23243 " //...\n" 23244 "}", 23245 Style); 23246 23247 verifyFormat( 23248 "template <typename T>\n" 23249 "veryveryvery_long_return_type g(T i) requires Concept1 || Concept2 {\n" 23250 " //...\n" 23251 "}", 23252 Style); 23253 23254 verifyFormat("template <typename It>\n" 23255 "requires Foo<It>() && Bar<It> {\n" 23256 " //....\n" 23257 "}", 23258 Style); 23259 23260 verifyFormat("template <typename It>\n" 23261 "requires Foo<Bar<It>>() && Bar<Foo<It, It>> {\n" 23262 " //....\n" 23263 "}", 23264 Style); 23265 23266 verifyFormat("template <typename It>\n" 23267 "requires Foo<Bar<It, It>>() && Bar<Foo<It, It>> {\n" 23268 " //....\n" 23269 "}", 23270 Style); 23271 23272 verifyFormat( 23273 "template <typename It>\n" 23274 "requires Foo<Bar<It>, Baz<It>>() && Bar<Foo<It>, Baz<It, It>> {\n" 23275 " //....\n" 23276 "}", 23277 Style); 23278 23279 Style.IndentRequires = true; 23280 verifyFormat("template <typename It>\n" 23281 " requires Iterator<It>\n" 23282 "void sort(It begin, It end) {\n" 23283 " //....\n" 23284 "}", 23285 Style); 23286 verifyFormat("template <std::size index_>\n" 23287 " requires(index_ < sizeof...(Children_))\n" 23288 "Tree auto &child() {\n" 23289 " // ...\n" 23290 "}", 23291 Style); 23292 23293 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 23294 verifyFormat("template <typename T>\n" 23295 "concept Hashable = requires (T a) {\n" 23296 " { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;\n" 23297 "};", 23298 Style); 23299 23300 verifyFormat("template <class T = void>\n" 23301 " requires EqualityComparable<T> || Same<T, void>\n" 23302 "struct equal_to;", 23303 Style); 23304 23305 verifyFormat("template <class T>\n" 23306 " requires requires {\n" 23307 " T{};\n" 23308 " T (int);\n" 23309 " }\n", 23310 Style); 23311 23312 Style.ColumnLimit = 78; 23313 verifyFormat("template <typename T>\n" 23314 "concept Context = Traits<typename T::traits_type> and\n" 23315 " Interface<typename T::interface_type> and\n" 23316 " Request<typename T::request_type> and\n" 23317 " Response<typename T::response_type> and\n" 23318 " ContextExtension<typename T::extension_type> and\n" 23319 " ::std::is_copy_constructable<T> and " 23320 "::std::is_move_constructable<T> and\n" 23321 " requires (T c) {\n" 23322 " { c.response; } -> Response;\n" 23323 "} and requires (T c) {\n" 23324 " { c.request; } -> Request;\n" 23325 "}\n", 23326 Style); 23327 23328 verifyFormat("template <typename T>\n" 23329 "concept Context = Traits<typename T::traits_type> or\n" 23330 " Interface<typename T::interface_type> or\n" 23331 " Request<typename T::request_type> or\n" 23332 " Response<typename T::response_type> or\n" 23333 " ContextExtension<typename T::extension_type> or\n" 23334 " ::std::is_copy_constructable<T> or " 23335 "::std::is_move_constructable<T> or\n" 23336 " requires (T c) {\n" 23337 " { c.response; } -> Response;\n" 23338 "} or requires (T c) {\n" 23339 " { c.request; } -> Request;\n" 23340 "}\n", 23341 Style); 23342 23343 verifyFormat("template <typename T>\n" 23344 "concept Context = Traits<typename T::traits_type> &&\n" 23345 " Interface<typename T::interface_type> &&\n" 23346 " Request<typename T::request_type> &&\n" 23347 " Response<typename T::response_type> &&\n" 23348 " ContextExtension<typename T::extension_type> &&\n" 23349 " ::std::is_copy_constructable<T> && " 23350 "::std::is_move_constructable<T> &&\n" 23351 " requires (T c) {\n" 23352 " { c.response; } -> Response;\n" 23353 "} && requires (T c) {\n" 23354 " { c.request; } -> Request;\n" 23355 "}\n", 23356 Style); 23357 23358 verifyFormat("template <typename T>\nconcept someConcept = Constraint1<T> && " 23359 "Constraint2<T>;"); 23360 23361 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 23362 Style.BraceWrapping.AfterFunction = true; 23363 Style.BraceWrapping.AfterClass = true; 23364 Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 23365 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 23366 verifyFormat("void Foo () requires (std::copyable<T>)\n" 23367 "{\n" 23368 " return\n" 23369 "}\n", 23370 Style); 23371 23372 verifyFormat("void Foo () requires std::copyable<T>\n" 23373 "{\n" 23374 " return\n" 23375 "}\n", 23376 Style); 23377 23378 verifyFormat("template <std::semiregular F, std::semiregular... Args>\n" 23379 " requires (std::invocable<F, std::invoke_result_t<Args>...>)\n" 23380 "struct constant;", 23381 Style); 23382 23383 verifyFormat("template <std::semiregular F, std::semiregular... Args>\n" 23384 " requires std::invocable<F, std::invoke_result_t<Args>...>\n" 23385 "struct constant;", 23386 Style); 23387 23388 verifyFormat("template <class T>\n" 23389 "class plane_with_very_very_very_long_name\n" 23390 "{\n" 23391 " constexpr plane_with_very_very_very_long_name () requires " 23392 "std::copyable<T>\n" 23393 " : plane_with_very_very_very_long_name (1)\n" 23394 " {\n" 23395 " }\n" 23396 "}\n", 23397 Style); 23398 23399 verifyFormat("template <class T>\n" 23400 "class plane_with_long_name\n" 23401 "{\n" 23402 " constexpr plane_with_long_name () requires std::copyable<T>\n" 23403 " : plane_with_long_name (1)\n" 23404 " {\n" 23405 " }\n" 23406 "}\n", 23407 Style); 23408 23409 Style.BreakBeforeConceptDeclarations = false; 23410 verifyFormat("template <typename T> concept Tree = true;", Style); 23411 23412 Style.IndentRequires = false; 23413 verifyFormat("template <std::semiregular F, std::semiregular... Args>\n" 23414 "requires (std::invocable<F, std::invoke_result_t<Args>...>) " 23415 "struct constant;", 23416 Style); 23417 } 23418 23419 TEST_F(FormatTest, StatementAttributeLikeMacros) { 23420 FormatStyle Style = getLLVMStyle(); 23421 StringRef Source = "void Foo::slot() {\n" 23422 " unsigned char MyChar = 'x';\n" 23423 " emit signal(MyChar);\n" 23424 " Q_EMIT signal(MyChar);\n" 23425 "}"; 23426 23427 EXPECT_EQ(Source, format(Source, Style)); 23428 23429 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 23430 EXPECT_EQ("void Foo::slot() {\n" 23431 " unsigned char MyChar = 'x';\n" 23432 " emit signal(MyChar);\n" 23433 " Q_EMIT signal(MyChar);\n" 23434 "}", 23435 format(Source, Style)); 23436 23437 Style.StatementAttributeLikeMacros.push_back("emit"); 23438 EXPECT_EQ(Source, format(Source, Style)); 23439 23440 Style.StatementAttributeLikeMacros = {}; 23441 EXPECT_EQ("void Foo::slot() {\n" 23442 " unsigned char MyChar = 'x';\n" 23443 " emit signal(MyChar);\n" 23444 " Q_EMIT signal(MyChar);\n" 23445 "}", 23446 format(Source, Style)); 23447 } 23448 23449 TEST_F(FormatTest, IndentAccessModifiers) { 23450 FormatStyle Style = getLLVMStyle(); 23451 Style.IndentAccessModifiers = true; 23452 // Members are *two* levels below the record; 23453 // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation. 23454 verifyFormat("class C {\n" 23455 " int i;\n" 23456 "};\n", 23457 Style); 23458 verifyFormat("union C {\n" 23459 " int i;\n" 23460 " unsigned u;\n" 23461 "};\n", 23462 Style); 23463 // Access modifiers should be indented one level below the record. 23464 verifyFormat("class C {\n" 23465 " public:\n" 23466 " int i;\n" 23467 "};\n", 23468 Style); 23469 verifyFormat("struct S {\n" 23470 " private:\n" 23471 " class C {\n" 23472 " int j;\n" 23473 "\n" 23474 " public:\n" 23475 " C();\n" 23476 " };\n" 23477 "\n" 23478 " public:\n" 23479 " int i;\n" 23480 "};\n", 23481 Style); 23482 // Enumerations are not records and should be unaffected. 23483 Style.AllowShortEnumsOnASingleLine = false; 23484 verifyFormat("enum class E {\n" 23485 " A,\n" 23486 " B\n" 23487 "};\n", 23488 Style); 23489 // Test with a different indentation width; 23490 // also proves that the result is Style.AccessModifierOffset agnostic. 23491 Style.IndentWidth = 3; 23492 verifyFormat("class C {\n" 23493 " public:\n" 23494 " int i;\n" 23495 "};\n", 23496 Style); 23497 } 23498 23499 TEST_F(FormatTest, LimitlessStringsAndComments) { 23500 auto Style = getLLVMStyleWithColumns(0); 23501 constexpr StringRef Code = 23502 "/**\n" 23503 " * This is a multiline comment with quite some long lines, at least for " 23504 "the LLVM Style.\n" 23505 " * We will redo this with strings and line comments. Just to check if " 23506 "everything is working.\n" 23507 " */\n" 23508 "bool foo() {\n" 23509 " /* Single line multi line comment. */\n" 23510 " const std::string String = \"This is a multiline string with quite " 23511 "some long lines, at least for the LLVM Style.\"\n" 23512 " \"We already did it with multi line " 23513 "comments, and we will do it with line comments. Just to check if " 23514 "everything is working.\";\n" 23515 " // This is a line comment (block) with quite some long lines, at " 23516 "least for the LLVM Style.\n" 23517 " // We already did this with multi line comments and strings. Just to " 23518 "check if everything is working.\n" 23519 " const std::string SmallString = \"Hello World\";\n" 23520 " // Small line comment\n" 23521 " return String.size() > SmallString.size();\n" 23522 "}"; 23523 EXPECT_EQ(Code, format(Code, Style)); 23524 } 23525 23526 TEST_F(FormatTest, FormatDecayCopy) { 23527 // error cases from unit tests 23528 verifyFormat("foo(auto())"); 23529 verifyFormat("foo(auto{})"); 23530 verifyFormat("foo(auto({}))"); 23531 verifyFormat("foo(auto{{}})"); 23532 23533 verifyFormat("foo(auto(1))"); 23534 verifyFormat("foo(auto{1})"); 23535 verifyFormat("foo(new auto(1))"); 23536 verifyFormat("foo(new auto{1})"); 23537 verifyFormat("decltype(auto(1)) x;"); 23538 verifyFormat("decltype(auto{1}) x;"); 23539 verifyFormat("auto(x);"); 23540 verifyFormat("auto{x};"); 23541 verifyFormat("new auto{x};"); 23542 verifyFormat("auto{x} = y;"); 23543 verifyFormat("auto(x) = y;"); // actually a declaration, but this is clearly 23544 // the user's own fault 23545 verifyFormat("integral auto(x) = y;"); // actually a declaration, but this is 23546 // clearly the user's own fault 23547 verifyFormat("auto(*p)() = f;"); // actually a declaration; TODO FIXME 23548 } 23549 23550 TEST_F(FormatTest, Cpp20ModulesSupport) { 23551 FormatStyle Style = getLLVMStyle(); 23552 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 23553 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 23554 23555 verifyFormat("export import foo;", Style); 23556 verifyFormat("export import foo:bar;", Style); 23557 verifyFormat("export import foo.bar;", Style); 23558 verifyFormat("export import foo.bar:baz;", Style); 23559 verifyFormat("export import :bar;", Style); 23560 verifyFormat("export module foo:bar;", Style); 23561 verifyFormat("export module foo;", Style); 23562 verifyFormat("export module foo.bar;", Style); 23563 verifyFormat("export module foo.bar:baz;", Style); 23564 verifyFormat("export import <string_view>;", Style); 23565 23566 verifyFormat("export type_name var;", Style); 23567 verifyFormat("template <class T> export using A = B<T>;", Style); 23568 verifyFormat("export using A = B;", Style); 23569 verifyFormat("export int func() {\n" 23570 " foo();\n" 23571 "}", 23572 Style); 23573 verifyFormat("export struct {\n" 23574 " int foo;\n" 23575 "};", 23576 Style); 23577 verifyFormat("export {\n" 23578 " int foo;\n" 23579 "};", 23580 Style); 23581 verifyFormat("export export char const *hello() { return \"hello\"; }"); 23582 23583 verifyFormat("import bar;", Style); 23584 verifyFormat("import foo.bar;", Style); 23585 verifyFormat("import foo:bar;", Style); 23586 verifyFormat("import :bar;", Style); 23587 verifyFormat("import <ctime>;", Style); 23588 verifyFormat("import \"header\";", Style); 23589 23590 verifyFormat("module foo;", Style); 23591 verifyFormat("module foo:bar;", Style); 23592 verifyFormat("module foo.bar;", Style); 23593 verifyFormat("module;", Style); 23594 23595 verifyFormat("export namespace hi {\n" 23596 "const char *sayhi();\n" 23597 "}", 23598 Style); 23599 23600 verifyFormat("module :private;", Style); 23601 verifyFormat("import <foo/bar.h>;", Style); 23602 verifyFormat("import foo...bar;", Style); 23603 verifyFormat("import ..........;", Style); 23604 verifyFormat("module foo:private;", Style); 23605 verifyFormat("import a", Style); 23606 verifyFormat("module a", Style); 23607 verifyFormat("export import a", Style); 23608 verifyFormat("export module a", Style); 23609 23610 verifyFormat("import", Style); 23611 verifyFormat("module", Style); 23612 verifyFormat("export", Style); 23613 } 23614 23615 TEST_F(FormatTest, CoroutineForCoawait) { 23616 FormatStyle Style = getLLVMStyle(); 23617 verifyFormat("for co_await (auto x : range())\n ;"); 23618 verifyFormat("for (auto i : arr) {\n" 23619 "}", 23620 Style); 23621 verifyFormat("for co_await (auto i : arr) {\n" 23622 "}", 23623 Style); 23624 verifyFormat("for co_await (auto i : foo(T{})) {\n" 23625 "}", 23626 Style); 23627 } 23628 23629 TEST_F(FormatTest, CoroutineCoAwait) { 23630 verifyFormat("int x = co_await foo();"); 23631 verifyFormat("int x = (co_await foo());"); 23632 verifyFormat("co_await (42);"); 23633 verifyFormat("void operator co_await(int);"); 23634 verifyFormat("void operator co_await(a);"); 23635 verifyFormat("co_await a;"); 23636 verifyFormat("co_await missing_await_resume{};"); 23637 verifyFormat("co_await a; // comment"); 23638 verifyFormat("void test0() { co_await a; }"); 23639 verifyFormat("co_await co_await co_await foo();"); 23640 verifyFormat("co_await foo().bar();"); 23641 verifyFormat("co_await [this]() -> Task { co_return x; }"); 23642 verifyFormat("co_await [this](int a, int b) -> Task { co_return co_await " 23643 "foo(); }(x, y);"); 23644 23645 FormatStyle Style = getLLVMStyleWithColumns(40); 23646 verifyFormat("co_await [this](int a, int b) -> Task {\n" 23647 " co_return co_await foo();\n" 23648 "}(x, y);", 23649 Style); 23650 verifyFormat("co_await;"); 23651 } 23652 23653 TEST_F(FormatTest, CoroutineCoYield) { 23654 verifyFormat("int x = co_yield foo();"); 23655 verifyFormat("int x = (co_yield foo());"); 23656 verifyFormat("co_yield (42);"); 23657 verifyFormat("co_yield {42};"); 23658 verifyFormat("co_yield 42;"); 23659 verifyFormat("co_yield n++;"); 23660 verifyFormat("co_yield ++n;"); 23661 verifyFormat("co_yield;"); 23662 } 23663 23664 TEST_F(FormatTest, CoroutineCoReturn) { 23665 verifyFormat("co_return (42);"); 23666 verifyFormat("co_return;"); 23667 verifyFormat("co_return {};"); 23668 verifyFormat("co_return x;"); 23669 verifyFormat("co_return co_await foo();"); 23670 verifyFormat("co_return co_yield foo();"); 23671 } 23672 23673 TEST_F(FormatTest, EmptyShortBlock) { 23674 auto Style = getLLVMStyle(); 23675 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 23676 23677 verifyFormat("try {\n" 23678 " doA();\n" 23679 "} catch (Exception &e) {\n" 23680 " e.printStackTrace();\n" 23681 "}\n", 23682 Style); 23683 23684 verifyFormat("try {\n" 23685 " doA();\n" 23686 "} catch (Exception &e) {}\n", 23687 Style); 23688 } 23689 23690 TEST_F(FormatTest, ShortTemplatedArgumentLists) { 23691 auto Style = getLLVMStyle(); 23692 23693 verifyFormat("template <> struct S : Template<int (*)[]> {};\n", Style); 23694 verifyFormat("template <> struct S : Template<int (*)[10]> {};\n", Style); 23695 verifyFormat("struct Y : X<[] { return 0; }> {};", Style); 23696 verifyFormat("struct Y<[] { return 0; }> {};", Style); 23697 23698 verifyFormat("struct Z : X<decltype([] { return 0; }){}> {};", Style); 23699 verifyFormat("template <int N> struct Foo<char[N]> {};", Style); 23700 } 23701 23702 TEST_F(FormatTest, RemoveBraces) { 23703 FormatStyle Style = getLLVMStyle(); 23704 Style.RemoveBracesLLVM = true; 23705 23706 // The following eight test cases are fully-braced versions of the examples at 23707 // "llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single- 23708 // statement-bodies-of-if-else-loop-statements". 23709 23710 // 1. Omit the braces, since the body is simple and clearly associated with 23711 // the if. 23712 verifyFormat("if (isa<FunctionDecl>(D))\n" 23713 " handleFunctionDecl(D);\n" 23714 "else if (isa<VarDecl>(D))\n" 23715 " handleVarDecl(D);", 23716 "if (isa<FunctionDecl>(D)) {\n" 23717 " handleFunctionDecl(D);\n" 23718 "} else if (isa<VarDecl>(D)) {\n" 23719 " handleVarDecl(D);\n" 23720 "}", 23721 Style); 23722 23723 // 2. Here we document the condition itself and not the body. 23724 verifyFormat("if (isa<VarDecl>(D)) {\n" 23725 " // It is necessary that we explain the situation with this\n" 23726 " // surprisingly long comment, so it would be unclear\n" 23727 " // without the braces whether the following statement is in\n" 23728 " // the scope of the `if`.\n" 23729 " // Because the condition is documented, we can't really\n" 23730 " // hoist this comment that applies to the body above the\n" 23731 " // if.\n" 23732 " handleOtherDecl(D);\n" 23733 "}", 23734 Style); 23735 23736 // 3. Use braces on the outer `if` to avoid a potential dangling else 23737 // situation. 23738 verifyFormat("if (isa<VarDecl>(D)) {\n" 23739 " for (auto *A : D.attrs())\n" 23740 " if (shouldProcessAttr(A))\n" 23741 " handleAttr(A);\n" 23742 "}", 23743 "if (isa<VarDecl>(D)) {\n" 23744 " for (auto *A : D.attrs()) {\n" 23745 " if (shouldProcessAttr(A)) {\n" 23746 " handleAttr(A);\n" 23747 " }\n" 23748 " }\n" 23749 "}", 23750 Style); 23751 23752 // 4. Use braces for the `if` block to keep it uniform with the else block. 23753 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 23754 " handleFunctionDecl(D);\n" 23755 "} else {\n" 23756 " // In this else case, it is necessary that we explain the\n" 23757 " // situation with this surprisingly long comment, so it\n" 23758 " // would be unclear without the braces whether the\n" 23759 " // following statement is in the scope of the `if`.\n" 23760 " handleOtherDecl(D);\n" 23761 "}", 23762 Style); 23763 23764 // 5. This should also omit braces. The `for` loop contains only a single 23765 // statement, so it shouldn't have braces. The `if` also only contains a 23766 // single simple statement (the for loop), so it also should omit braces. 23767 verifyFormat("if (isa<FunctionDecl>(D))\n" 23768 " for (auto *A : D.attrs())\n" 23769 " handleAttr(A);", 23770 "if (isa<FunctionDecl>(D)) {\n" 23771 " for (auto *A : D.attrs()) {\n" 23772 " handleAttr(A);\n" 23773 " }\n" 23774 "}", 23775 Style); 23776 23777 // 6. Use braces for the outer `if` since the nested `for` is braced. 23778 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 23779 " for (auto *A : D.attrs()) {\n" 23780 " // In this for loop body, it is necessary that we explain\n" 23781 " // the situation with this surprisingly long comment,\n" 23782 " // forcing braces on the `for` block.\n" 23783 " handleAttr(A);\n" 23784 " }\n" 23785 "}", 23786 Style); 23787 23788 // 7. Use braces on the outer block because there are more than two levels of 23789 // nesting. 23790 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 23791 " for (auto *A : D.attrs())\n" 23792 " for (ssize_t i : llvm::seq<ssize_t>(count))\n" 23793 " handleAttrOnDecl(D, A, i);\n" 23794 "}", 23795 "if (isa<FunctionDecl>(D)) {\n" 23796 " for (auto *A : D.attrs()) {\n" 23797 " for (ssize_t i : llvm::seq<ssize_t>(count)) {\n" 23798 " handleAttrOnDecl(D, A, i);\n" 23799 " }\n" 23800 " }\n" 23801 "}", 23802 Style); 23803 23804 // 8. Use braces on the outer block because of a nested `if`, otherwise the 23805 // compiler would warn: `add explicit braces to avoid dangling else` 23806 verifyFormat("if (auto *D = dyn_cast<FunctionDecl>(D)) {\n" 23807 " if (shouldProcess(D))\n" 23808 " handleVarDecl(D);\n" 23809 " else\n" 23810 " markAsIgnored(D);\n" 23811 "}", 23812 "if (auto *D = dyn_cast<FunctionDecl>(D)) {\n" 23813 " if (shouldProcess(D)) {\n" 23814 " handleVarDecl(D);\n" 23815 " } else {\n" 23816 " markAsIgnored(D);\n" 23817 " }\n" 23818 "}", 23819 Style); 23820 23821 verifyFormat("if (a)\n" 23822 " b; // comment\n" 23823 "else if (c)\n" 23824 " d; /* comment */\n" 23825 "else\n" 23826 " e;", 23827 "if (a) {\n" 23828 " b; // comment\n" 23829 "} else if (c) {\n" 23830 " d; /* comment */\n" 23831 "} else {\n" 23832 " e;\n" 23833 "}", 23834 Style); 23835 23836 verifyFormat("if (a) {\n" 23837 " b;\n" 23838 " c;\n" 23839 "} else if (d) {\n" 23840 " e;\n" 23841 "}", 23842 Style); 23843 23844 verifyFormat("if (a) {\n" 23845 "#undef NDEBUG\n" 23846 " b;\n" 23847 "} else {\n" 23848 " c;\n" 23849 "}", 23850 Style); 23851 23852 verifyFormat("if (a) {\n" 23853 " // comment\n" 23854 "} else if (b) {\n" 23855 " c;\n" 23856 "}", 23857 Style); 23858 23859 verifyFormat("if (a) {\n" 23860 " b;\n" 23861 "} else {\n" 23862 " { c; }\n" 23863 "}", 23864 Style); 23865 23866 verifyFormat("if (a) {\n" 23867 " if (b) // comment\n" 23868 " c;\n" 23869 "} else if (d) {\n" 23870 " e;\n" 23871 "}", 23872 "if (a) {\n" 23873 " if (b) { // comment\n" 23874 " c;\n" 23875 " }\n" 23876 "} else if (d) {\n" 23877 " e;\n" 23878 "}", 23879 Style); 23880 23881 verifyFormat("if (a) {\n" 23882 " if (b) {\n" 23883 " c;\n" 23884 " // comment\n" 23885 " } else if (d) {\n" 23886 " e;\n" 23887 " }\n" 23888 "}", 23889 Style); 23890 23891 verifyFormat("if (a) {\n" 23892 " if (b)\n" 23893 " c;\n" 23894 "}", 23895 "if (a) {\n" 23896 " if (b) {\n" 23897 " c;\n" 23898 " }\n" 23899 "}", 23900 Style); 23901 23902 verifyFormat("if (a)\n" 23903 " if (b)\n" 23904 " c;\n" 23905 " else\n" 23906 " d;\n" 23907 "else\n" 23908 " e;", 23909 "if (a) {\n" 23910 " if (b) {\n" 23911 " c;\n" 23912 " } else {\n" 23913 " d;\n" 23914 " }\n" 23915 "} else {\n" 23916 " e;\n" 23917 "}", 23918 Style); 23919 23920 verifyFormat("if (a) {\n" 23921 " // comment\n" 23922 " if (b)\n" 23923 " c;\n" 23924 " else if (d)\n" 23925 " e;\n" 23926 "} else {\n" 23927 " g;\n" 23928 "}", 23929 "if (a) {\n" 23930 " // comment\n" 23931 " if (b) {\n" 23932 " c;\n" 23933 " } else if (d) {\n" 23934 " e;\n" 23935 " }\n" 23936 "} else {\n" 23937 " g;\n" 23938 "}", 23939 Style); 23940 23941 verifyFormat("if (a)\n" 23942 " b;\n" 23943 "else if (c)\n" 23944 " d;\n" 23945 "else\n" 23946 " e;", 23947 "if (a) {\n" 23948 " b;\n" 23949 "} else {\n" 23950 " if (c) {\n" 23951 " d;\n" 23952 " } else {\n" 23953 " e;\n" 23954 " }\n" 23955 "}", 23956 Style); 23957 23958 verifyFormat("if (a) {\n" 23959 " if (b)\n" 23960 " c;\n" 23961 " else if (d)\n" 23962 " e;\n" 23963 "} else {\n" 23964 " g;\n" 23965 "}", 23966 "if (a) {\n" 23967 " if (b)\n" 23968 " c;\n" 23969 " else {\n" 23970 " if (d)\n" 23971 " e;\n" 23972 " }\n" 23973 "} else {\n" 23974 " g;\n" 23975 "}", 23976 Style); 23977 23978 verifyFormat("if (a)\n" 23979 " b;\n" 23980 "else if (c)\n" 23981 " while (d)\n" 23982 " e;\n" 23983 "// comment", 23984 "if (a)\n" 23985 "{\n" 23986 " b;\n" 23987 "} else if (c) {\n" 23988 " while (d) {\n" 23989 " e;\n" 23990 " }\n" 23991 "}\n" 23992 "// comment", 23993 Style); 23994 23995 verifyFormat("if (a) {\n" 23996 " b;\n" 23997 "} else if (c) {\n" 23998 " d;\n" 23999 "} else {\n" 24000 " e;\n" 24001 " g;\n" 24002 "}", 24003 Style); 24004 24005 verifyFormat("if (a) {\n" 24006 " b;\n" 24007 "} else if (c) {\n" 24008 " d;\n" 24009 "} else {\n" 24010 " e;\n" 24011 "} // comment", 24012 Style); 24013 24014 verifyFormat("int abs = [](int i) {\n" 24015 " if (i >= 0)\n" 24016 " return i;\n" 24017 " return -i;\n" 24018 "};", 24019 "int abs = [](int i) {\n" 24020 " if (i >= 0) {\n" 24021 " return i;\n" 24022 " }\n" 24023 " return -i;\n" 24024 "};", 24025 Style); 24026 24027 // FIXME: See https://github.com/llvm/llvm-project/issues/53543. 24028 #if 0 24029 Style.ColumnLimit = 65; 24030 24031 verifyFormat("if (condition) {\n" 24032 " ff(Indices,\n" 24033 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 24034 "} else {\n" 24035 " ff(Indices,\n" 24036 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 24037 "}", 24038 Style); 24039 24040 Style.ColumnLimit = 20; 24041 24042 verifyFormat("if (a) {\n" 24043 " b = c + // 1 -\n" 24044 " d;\n" 24045 "}", 24046 Style); 24047 24048 verifyFormat("if (a) {\n" 24049 " b = c >= 0 ? d\n" 24050 " : e;\n" 24051 "}", 24052 "if (a) {\n" 24053 " b = c >= 0 ? d : e;\n" 24054 "}", 24055 Style); 24056 #endif 24057 24058 Style.ColumnLimit = 20; 24059 24060 verifyFormat("if (a)\n" 24061 " b = c > 0 ? d : e;", 24062 "if (a) {\n" 24063 " b = c > 0 ? d : e;\n" 24064 "}", 24065 Style); 24066 24067 Style.ColumnLimit = 0; 24068 24069 verifyFormat("if (a)\n" 24070 " b234567890223456789032345678904234567890 = " 24071 "c234567890223456789032345678904234567890;", 24072 "if (a) {\n" 24073 " b234567890223456789032345678904234567890 = " 24074 "c234567890223456789032345678904234567890;\n" 24075 "}", 24076 Style); 24077 } 24078 24079 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndent) { 24080 auto Style = getLLVMStyle(); 24081 24082 StringRef Short = "functionCall(paramA, paramB, paramC);\n" 24083 "void functionDecl(int a, int b, int c);"; 24084 24085 StringRef Medium = "functionCall(paramA, paramB, paramC, paramD, paramE, " 24086 "paramF, paramG, paramH, paramI);\n" 24087 "void functionDecl(int argumentA, int argumentB, int " 24088 "argumentC, int argumentD, int argumentE);"; 24089 24090 verifyFormat(Short, Style); 24091 24092 StringRef NoBreak = "functionCall(paramA, paramB, paramC, paramD, paramE, " 24093 "paramF, paramG, paramH,\n" 24094 " paramI);\n" 24095 "void functionDecl(int argumentA, int argumentB, int " 24096 "argumentC, int argumentD,\n" 24097 " int argumentE);"; 24098 24099 verifyFormat(NoBreak, Medium, Style); 24100 verifyFormat(NoBreak, 24101 "functionCall(\n" 24102 " paramA,\n" 24103 " paramB,\n" 24104 " paramC,\n" 24105 " paramD,\n" 24106 " paramE,\n" 24107 " paramF,\n" 24108 " paramG,\n" 24109 " paramH,\n" 24110 " paramI\n" 24111 ");\n" 24112 "void functionDecl(\n" 24113 " int argumentA,\n" 24114 " int argumentB,\n" 24115 " int argumentC,\n" 24116 " int argumentD,\n" 24117 " int argumentE\n" 24118 ");", 24119 Style); 24120 24121 verifyFormat("outerFunctionCall(nestedFunctionCall(argument1),\n" 24122 " nestedLongFunctionCall(argument1, " 24123 "argument2, argument3,\n" 24124 " argument4, " 24125 "argument5));", 24126 Style); 24127 24128 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 24129 24130 verifyFormat(Short, Style); 24131 verifyFormat( 24132 "functionCall(\n" 24133 " paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, " 24134 "paramI\n" 24135 ");\n" 24136 "void functionDecl(\n" 24137 " int argumentA, int argumentB, int argumentC, int argumentD, int " 24138 "argumentE\n" 24139 ");", 24140 Medium, Style); 24141 24142 Style.AllowAllArgumentsOnNextLine = false; 24143 Style.AllowAllParametersOfDeclarationOnNextLine = false; 24144 24145 verifyFormat(Short, Style); 24146 verifyFormat( 24147 "functionCall(\n" 24148 " paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, " 24149 "paramI\n" 24150 ");\n" 24151 "void functionDecl(\n" 24152 " int argumentA, int argumentB, int argumentC, int argumentD, int " 24153 "argumentE\n" 24154 ");", 24155 Medium, Style); 24156 24157 Style.BinPackArguments = false; 24158 Style.BinPackParameters = false; 24159 24160 verifyFormat(Short, Style); 24161 24162 verifyFormat("functionCall(\n" 24163 " paramA,\n" 24164 " paramB,\n" 24165 " paramC,\n" 24166 " paramD,\n" 24167 " paramE,\n" 24168 " paramF,\n" 24169 " paramG,\n" 24170 " paramH,\n" 24171 " paramI\n" 24172 ");\n" 24173 "void functionDecl(\n" 24174 " int argumentA,\n" 24175 " int argumentB,\n" 24176 " int argumentC,\n" 24177 " int argumentD,\n" 24178 " int argumentE\n" 24179 ");", 24180 Medium, Style); 24181 24182 verifyFormat("outerFunctionCall(\n" 24183 " nestedFunctionCall(argument1),\n" 24184 " nestedLongFunctionCall(\n" 24185 " argument1,\n" 24186 " argument2,\n" 24187 " argument3,\n" 24188 " argument4,\n" 24189 " argument5\n" 24190 " )\n" 24191 ");", 24192 Style); 24193 24194 verifyFormat("int a = (int)b;", Style); 24195 verifyFormat("int a = (int)b;", 24196 "int a = (\n" 24197 " int\n" 24198 ") b;", 24199 Style); 24200 24201 verifyFormat("return (true);", Style); 24202 verifyFormat("return (true);", 24203 "return (\n" 24204 " true\n" 24205 ");", 24206 Style); 24207 24208 verifyFormat("void foo();", Style); 24209 verifyFormat("void foo();", 24210 "void foo(\n" 24211 ");", 24212 Style); 24213 24214 verifyFormat("void foo() {}", Style); 24215 verifyFormat("void foo() {}", 24216 "void foo(\n" 24217 ") {\n" 24218 "}", 24219 Style); 24220 24221 verifyFormat("auto string = std::string();", Style); 24222 verifyFormat("auto string = std::string();", 24223 "auto string = std::string(\n" 24224 ");", 24225 Style); 24226 24227 verifyFormat("void (*functionPointer)() = nullptr;", Style); 24228 verifyFormat("void (*functionPointer)() = nullptr;", 24229 "void (\n" 24230 " *functionPointer\n" 24231 ")\n" 24232 "(\n" 24233 ") = nullptr;", 24234 Style); 24235 } 24236 24237 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentIfStatement) { 24238 auto Style = getLLVMStyle(); 24239 24240 verifyFormat("if (foo()) {\n" 24241 " return;\n" 24242 "}", 24243 Style); 24244 24245 verifyFormat("if (quitelongarg !=\n" 24246 " (alsolongarg - 1)) { // ABC is a very longgggggggggggg " 24247 "comment\n" 24248 " return;\n" 24249 "}", 24250 Style); 24251 24252 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 24253 24254 verifyFormat("if (foo()) {\n" 24255 " return;\n" 24256 "}", 24257 Style); 24258 24259 verifyFormat("if (quitelongarg !=\n" 24260 " (alsolongarg - 1)) { // ABC is a very longgggggggggggg " 24261 "comment\n" 24262 " return;\n" 24263 "}", 24264 Style); 24265 } 24266 24267 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentForStatement) { 24268 auto Style = getLLVMStyle(); 24269 24270 verifyFormat("for (int i = 0; i < 5; ++i) {\n" 24271 " doSomething();\n" 24272 "}", 24273 Style); 24274 24275 verifyFormat("for (int myReallyLongCountVariable = 0; " 24276 "myReallyLongCountVariable < count;\n" 24277 " myReallyLongCountVariable++) {\n" 24278 " doSomething();\n" 24279 "}", 24280 Style); 24281 24282 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 24283 24284 verifyFormat("for (int i = 0; i < 5; ++i) {\n" 24285 " doSomething();\n" 24286 "}", 24287 Style); 24288 24289 verifyFormat("for (int myReallyLongCountVariable = 0; " 24290 "myReallyLongCountVariable < count;\n" 24291 " myReallyLongCountVariable++) {\n" 24292 " doSomething();\n" 24293 "}", 24294 Style); 24295 } 24296 24297 TEST_F(FormatTest, UnderstandsDigraphs) { 24298 verifyFormat("int arr<:5:> = {};"); 24299 verifyFormat("int arr[5] = <%%>;"); 24300 verifyFormat("int arr<:::qualified_variable:> = {};"); 24301 verifyFormat("int arr[::qualified_variable] = <%%>;"); 24302 verifyFormat("%:include <header>"); 24303 verifyFormat("%:define A x##y"); 24304 verifyFormat("#define A x%:%:y"); 24305 } 24306 24307 } // namespace 24308 } // namespace format 24309 } // namespace clang 24310