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 EXPECT_EQ(AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine, false); 1524 EXPECT_EQ(AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine, 1525 FormatStyle::SIS_Never); 1526 EXPECT_EQ(AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine, false); 1527 EXPECT_EQ(AllowSimpleBracedStatements.BraceWrapping.AfterFunction, false); 1528 verifyFormat("for (;;) {\n" 1529 " f();\n" 1530 "}"); 1531 verifyFormat("/*comment*/ for (;;) {\n" 1532 " f();\n" 1533 "}"); 1534 verifyFormat("BOOST_FOREACH (int v, vec) {\n" 1535 " f();\n" 1536 "}"); 1537 verifyFormat("/*comment*/ BOOST_FOREACH (int v, vec) {\n" 1538 " f();\n" 1539 "}"); 1540 verifyFormat("while (true) {\n" 1541 " f();\n" 1542 "}"); 1543 verifyFormat("/*comment*/ while (true) {\n" 1544 " f();\n" 1545 "}"); 1546 verifyFormat("if (true) {\n" 1547 " f();\n" 1548 "}"); 1549 verifyFormat("/*comment*/ if (true) {\n" 1550 " f();\n" 1551 "}"); 1552 1553 AllowSimpleBracedStatements.IfMacros.push_back("MYIF"); 1554 // Where line-lengths matter, a 2-letter synonym that maintains line length. 1555 // Not IF to avoid any confusion that IF is somehow special. 1556 AllowSimpleBracedStatements.IfMacros.push_back("FI"); 1557 AllowSimpleBracedStatements.ColumnLimit = 40; 1558 AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine = 1559 FormatStyle::SBS_Always; 1560 1561 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1562 FormatStyle::SIS_WithoutElse; 1563 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true; 1564 1565 AllowSimpleBracedStatements.BreakBeforeBraces = FormatStyle::BS_Custom; 1566 AllowSimpleBracedStatements.BraceWrapping.AfterFunction = true; 1567 AllowSimpleBracedStatements.BraceWrapping.SplitEmptyRecord = false; 1568 1569 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1570 verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements); 1571 verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1572 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1573 verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements); 1574 verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1575 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1576 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1577 verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements); 1578 verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements); 1579 verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1580 verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements); 1581 verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements); 1582 verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1583 verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements); 1584 verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements); 1585 verifyFormat("if (true) { fffffffffffffffffffffff(); }", 1586 AllowSimpleBracedStatements); 1587 verifyFormat("if (true) {\n" 1588 " ffffffffffffffffffffffff();\n" 1589 "}", 1590 AllowSimpleBracedStatements); 1591 verifyFormat("if (true) {\n" 1592 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1593 "}", 1594 AllowSimpleBracedStatements); 1595 verifyFormat("if (true) { //\n" 1596 " f();\n" 1597 "}", 1598 AllowSimpleBracedStatements); 1599 verifyFormat("if (true) {\n" 1600 " f();\n" 1601 " f();\n" 1602 "}", 1603 AllowSimpleBracedStatements); 1604 verifyFormat("if (true) {\n" 1605 " f();\n" 1606 "} else {\n" 1607 " f();\n" 1608 "}", 1609 AllowSimpleBracedStatements); 1610 verifyFormat("FI (true) { fffffffffffffffffffffff(); }", 1611 AllowSimpleBracedStatements); 1612 verifyFormat("MYIF (true) {\n" 1613 " ffffffffffffffffffffffff();\n" 1614 "}", 1615 AllowSimpleBracedStatements); 1616 verifyFormat("MYIF (true) {\n" 1617 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1618 "}", 1619 AllowSimpleBracedStatements); 1620 verifyFormat("MYIF (true) { //\n" 1621 " f();\n" 1622 "}", 1623 AllowSimpleBracedStatements); 1624 verifyFormat("MYIF (true) {\n" 1625 " f();\n" 1626 " f();\n" 1627 "}", 1628 AllowSimpleBracedStatements); 1629 verifyFormat("MYIF (true) {\n" 1630 " f();\n" 1631 "} else {\n" 1632 " f();\n" 1633 "}", 1634 AllowSimpleBracedStatements); 1635 1636 verifyFormat("struct A2 {\n" 1637 " int X;\n" 1638 "};", 1639 AllowSimpleBracedStatements); 1640 verifyFormat("typedef struct A2 {\n" 1641 " int X;\n" 1642 "} A2_t;", 1643 AllowSimpleBracedStatements); 1644 verifyFormat("template <int> struct A2 {\n" 1645 " struct B {};\n" 1646 "};", 1647 AllowSimpleBracedStatements); 1648 1649 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1650 FormatStyle::SIS_Never; 1651 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1652 verifyFormat("if (true) {\n" 1653 " f();\n" 1654 "}", 1655 AllowSimpleBracedStatements); 1656 verifyFormat("if (true) {\n" 1657 " f();\n" 1658 "} else {\n" 1659 " f();\n" 1660 "}", 1661 AllowSimpleBracedStatements); 1662 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1663 verifyFormat("MYIF (true) {\n" 1664 " f();\n" 1665 "}", 1666 AllowSimpleBracedStatements); 1667 verifyFormat("MYIF (true) {\n" 1668 " f();\n" 1669 "} else {\n" 1670 " f();\n" 1671 "}", 1672 AllowSimpleBracedStatements); 1673 1674 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false; 1675 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1676 verifyFormat("while (true) {\n" 1677 " f();\n" 1678 "}", 1679 AllowSimpleBracedStatements); 1680 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1681 verifyFormat("for (;;) {\n" 1682 " f();\n" 1683 "}", 1684 AllowSimpleBracedStatements); 1685 verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements); 1686 verifyFormat("BOOST_FOREACH (int v, vec) {\n" 1687 " f();\n" 1688 "}", 1689 AllowSimpleBracedStatements); 1690 1691 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1692 FormatStyle::SIS_WithoutElse; 1693 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true; 1694 AllowSimpleBracedStatements.BraceWrapping.AfterControlStatement = 1695 FormatStyle::BWACS_Always; 1696 1697 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1698 verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements); 1699 verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1700 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1701 verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements); 1702 verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1703 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1704 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1705 verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements); 1706 verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements); 1707 verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1708 verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements); 1709 verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements); 1710 verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1711 verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements); 1712 verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements); 1713 verifyFormat("if (true) { fffffffffffffffffffffff(); }", 1714 AllowSimpleBracedStatements); 1715 verifyFormat("if (true)\n" 1716 "{\n" 1717 " ffffffffffffffffffffffff();\n" 1718 "}", 1719 AllowSimpleBracedStatements); 1720 verifyFormat("if (true)\n" 1721 "{\n" 1722 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1723 "}", 1724 AllowSimpleBracedStatements); 1725 verifyFormat("if (true)\n" 1726 "{ //\n" 1727 " f();\n" 1728 "}", 1729 AllowSimpleBracedStatements); 1730 verifyFormat("if (true)\n" 1731 "{\n" 1732 " f();\n" 1733 " f();\n" 1734 "}", 1735 AllowSimpleBracedStatements); 1736 verifyFormat("if (true)\n" 1737 "{\n" 1738 " f();\n" 1739 "} else\n" 1740 "{\n" 1741 " f();\n" 1742 "}", 1743 AllowSimpleBracedStatements); 1744 verifyFormat("FI (true) { fffffffffffffffffffffff(); }", 1745 AllowSimpleBracedStatements); 1746 verifyFormat("MYIF (true)\n" 1747 "{\n" 1748 " ffffffffffffffffffffffff();\n" 1749 "}", 1750 AllowSimpleBracedStatements); 1751 verifyFormat("MYIF (true)\n" 1752 "{\n" 1753 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1754 "}", 1755 AllowSimpleBracedStatements); 1756 verifyFormat("MYIF (true)\n" 1757 "{ //\n" 1758 " f();\n" 1759 "}", 1760 AllowSimpleBracedStatements); 1761 verifyFormat("MYIF (true)\n" 1762 "{\n" 1763 " f();\n" 1764 " f();\n" 1765 "}", 1766 AllowSimpleBracedStatements); 1767 verifyFormat("MYIF (true)\n" 1768 "{\n" 1769 " f();\n" 1770 "} else\n" 1771 "{\n" 1772 " f();\n" 1773 "}", 1774 AllowSimpleBracedStatements); 1775 1776 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1777 FormatStyle::SIS_Never; 1778 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1779 verifyFormat("if (true)\n" 1780 "{\n" 1781 " f();\n" 1782 "}", 1783 AllowSimpleBracedStatements); 1784 verifyFormat("if (true)\n" 1785 "{\n" 1786 " f();\n" 1787 "} else\n" 1788 "{\n" 1789 " f();\n" 1790 "}", 1791 AllowSimpleBracedStatements); 1792 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1793 verifyFormat("MYIF (true)\n" 1794 "{\n" 1795 " f();\n" 1796 "}", 1797 AllowSimpleBracedStatements); 1798 verifyFormat("MYIF (true)\n" 1799 "{\n" 1800 " f();\n" 1801 "} else\n" 1802 "{\n" 1803 " f();\n" 1804 "}", 1805 AllowSimpleBracedStatements); 1806 1807 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false; 1808 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1809 verifyFormat("while (true)\n" 1810 "{\n" 1811 " f();\n" 1812 "}", 1813 AllowSimpleBracedStatements); 1814 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1815 verifyFormat("for (;;)\n" 1816 "{\n" 1817 " f();\n" 1818 "}", 1819 AllowSimpleBracedStatements); 1820 verifyFormat("BOOST_FOREACH (int v, vec) {}", AllowSimpleBracedStatements); 1821 verifyFormat("BOOST_FOREACH (int v, vec)\n" 1822 "{\n" 1823 " f();\n" 1824 "}", 1825 AllowSimpleBracedStatements); 1826 } 1827 1828 TEST_F(FormatTest, UnderstandsMacros) { 1829 verifyFormat("#define A (parentheses)"); 1830 verifyFormat("/* comment */ #define A (parentheses)"); 1831 verifyFormat("/* comment */ /* another comment */ #define A (parentheses)"); 1832 // Even the partial code should never be merged. 1833 EXPECT_EQ("/* comment */ #define A (parentheses)\n" 1834 "#", 1835 format("/* comment */ #define A (parentheses)\n" 1836 "#")); 1837 verifyFormat("/* comment */ #define A (parentheses)\n" 1838 "#\n"); 1839 verifyFormat("/* comment */ #define A (parentheses)\n" 1840 "#define B (parentheses)"); 1841 verifyFormat("#define true ((int)1)"); 1842 verifyFormat("#define and(x)"); 1843 verifyFormat("#define if(x) x"); 1844 verifyFormat("#define return(x) (x)"); 1845 verifyFormat("#define while(x) for (; x;)"); 1846 verifyFormat("#define xor(x) (^(x))"); 1847 verifyFormat("#define __except(x)"); 1848 verifyFormat("#define __try(x)"); 1849 1850 FormatStyle Style = getLLVMStyle(); 1851 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 1852 Style.BraceWrapping.AfterFunction = true; 1853 // Test that a macro definition never gets merged with the following 1854 // definition. 1855 // FIXME: The AAA macro definition probably should not be split into 3 lines. 1856 verifyFormat("#define AAA " 1857 " \\\n" 1858 " N " 1859 " \\\n" 1860 " {\n" 1861 "#define BBB }\n", 1862 Style); 1863 // verifyFormat("#define AAA N { //\n", Style); 1864 } 1865 1866 TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) { 1867 FormatStyle Style = getLLVMStyleWithColumns(60); 1868 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 1869 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse; 1870 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 1871 EXPECT_EQ("#define A \\\n" 1872 " if (HANDLEwernufrnuLwrmviferuvnierv) \\\n" 1873 " { \\\n" 1874 " RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n" 1875 " }\n" 1876 "X;", 1877 format("#define A \\\n" 1878 " if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n" 1879 " RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n" 1880 " }\n" 1881 "X;", 1882 Style)); 1883 } 1884 1885 TEST_F(FormatTest, ParseIfElse) { 1886 verifyFormat("if (true)\n" 1887 " if (true)\n" 1888 " if (true)\n" 1889 " f();\n" 1890 " else\n" 1891 " g();\n" 1892 " else\n" 1893 " h();\n" 1894 "else\n" 1895 " i();"); 1896 verifyFormat("if (true)\n" 1897 " if (true)\n" 1898 " if (true) {\n" 1899 " if (true)\n" 1900 " f();\n" 1901 " } else {\n" 1902 " g();\n" 1903 " }\n" 1904 " else\n" 1905 " h();\n" 1906 "else {\n" 1907 " i();\n" 1908 "}"); 1909 verifyFormat("if (true)\n" 1910 " if constexpr (true)\n" 1911 " if (true) {\n" 1912 " if constexpr (true)\n" 1913 " f();\n" 1914 " } else {\n" 1915 " g();\n" 1916 " }\n" 1917 " else\n" 1918 " h();\n" 1919 "else {\n" 1920 " i();\n" 1921 "}"); 1922 verifyFormat("if (true)\n" 1923 " if CONSTEXPR (true)\n" 1924 " if (true) {\n" 1925 " if CONSTEXPR (true)\n" 1926 " f();\n" 1927 " } else {\n" 1928 " g();\n" 1929 " }\n" 1930 " else\n" 1931 " h();\n" 1932 "else {\n" 1933 " i();\n" 1934 "}"); 1935 verifyFormat("void f() {\n" 1936 " if (a) {\n" 1937 " } else {\n" 1938 " }\n" 1939 "}"); 1940 } 1941 1942 TEST_F(FormatTest, ElseIf) { 1943 verifyFormat("if (a) {\n} else if (b) {\n}"); 1944 verifyFormat("if (a)\n" 1945 " f();\n" 1946 "else if (b)\n" 1947 " g();\n" 1948 "else\n" 1949 " h();"); 1950 verifyFormat("if (a)\n" 1951 " f();\n" 1952 "else // comment\n" 1953 " if (b) {\n" 1954 " g();\n" 1955 " h();\n" 1956 " }"); 1957 verifyFormat("if constexpr (a)\n" 1958 " f();\n" 1959 "else if constexpr (b)\n" 1960 " g();\n" 1961 "else\n" 1962 " h();"); 1963 verifyFormat("if CONSTEXPR (a)\n" 1964 " f();\n" 1965 "else if CONSTEXPR (b)\n" 1966 " g();\n" 1967 "else\n" 1968 " h();"); 1969 verifyFormat("if (a) {\n" 1970 " f();\n" 1971 "}\n" 1972 "// or else ..\n" 1973 "else {\n" 1974 " g()\n" 1975 "}"); 1976 1977 verifyFormat("if (a) {\n" 1978 "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 1979 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 1980 "}"); 1981 verifyFormat("if (a) {\n" 1982 "} else if constexpr (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 1983 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 1984 "}"); 1985 verifyFormat("if (a) {\n" 1986 "} else if CONSTEXPR (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 1987 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 1988 "}"); 1989 verifyFormat("if (a) {\n" 1990 "} else if (\n" 1991 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 1992 "}", 1993 getLLVMStyleWithColumns(62)); 1994 verifyFormat("if (a) {\n" 1995 "} else if constexpr (\n" 1996 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 1997 "}", 1998 getLLVMStyleWithColumns(62)); 1999 verifyFormat("if (a) {\n" 2000 "} else if CONSTEXPR (\n" 2001 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 2002 "}", 2003 getLLVMStyleWithColumns(62)); 2004 } 2005 2006 TEST_F(FormatTest, SeparatePointerReferenceAlignment) { 2007 FormatStyle Style = getLLVMStyle(); 2008 EXPECT_EQ(Style.PointerAlignment, FormatStyle::PAS_Right); 2009 EXPECT_EQ(Style.ReferenceAlignment, FormatStyle::RAS_Pointer); 2010 verifyFormat("int *f1(int *a, int &b, int &&c);", Style); 2011 verifyFormat("int &f2(int &&c, int *a, int &b);", Style); 2012 verifyFormat("int &&f3(int &b, int &&c, int *a);", Style); 2013 verifyFormat("int *f1(int &a) const &;", Style); 2014 verifyFormat("int *f1(int &a) const & = 0;", Style); 2015 verifyFormat("int *a = f1();", Style); 2016 verifyFormat("int &b = f2();", Style); 2017 verifyFormat("int &&c = f3();", Style); 2018 verifyFormat("for (auto a = 0, b = 0; const auto &c : {1, 2, 3})", Style); 2019 verifyFormat("for (auto a = 0, b = 0; const int &c : {1, 2, 3})", Style); 2020 verifyFormat("for (auto a = 0, b = 0; const Foo &c : {1, 2, 3})", Style); 2021 verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style); 2022 verifyFormat("for (int a = 0, b = 0; const auto &c : {1, 2, 3})", Style); 2023 verifyFormat("for (int a = 0, b = 0; const int &c : {1, 2, 3})", Style); 2024 verifyFormat("for (int a = 0, b = 0; const Foo &c : {1, 2, 3})", Style); 2025 verifyFormat("for (int a = 0, b++; const auto &c : {1, 2, 3})", Style); 2026 verifyFormat("for (int a = 0, b++; const int &c : {1, 2, 3})", Style); 2027 verifyFormat("for (int a = 0, b++; const Foo &c : {1, 2, 3})", Style); 2028 verifyFormat("for (auto x = 0; auto &c : {1, 2, 3})", Style); 2029 verifyFormat("for (auto x = 0; int &c : {1, 2, 3})", Style); 2030 verifyFormat("for (int x = 0; auto &c : {1, 2, 3})", Style); 2031 verifyFormat("for (int x = 0; int &c : {1, 2, 3})", Style); 2032 verifyFormat("for (f(); auto &c : {1, 2, 3})", Style); 2033 verifyFormat("for (f(); int &c : {1, 2, 3})", Style); 2034 verifyFormat( 2035 "function<int(int &)> res1 = [](int &a) { return 0000000000000; },\n" 2036 " res2 = [](int &a) { return 0000000000000; };", 2037 Style); 2038 2039 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 2040 verifyFormat("Const unsigned int *c;\n" 2041 "const unsigned int *d;\n" 2042 "Const unsigned int &e;\n" 2043 "const unsigned int &f;\n" 2044 "const unsigned &&g;\n" 2045 "Const unsigned h;", 2046 Style); 2047 2048 Style.PointerAlignment = FormatStyle::PAS_Left; 2049 Style.ReferenceAlignment = FormatStyle::RAS_Pointer; 2050 verifyFormat("int* f1(int* a, int& b, int&& c);", Style); 2051 verifyFormat("int& f2(int&& c, int* a, int& b);", Style); 2052 verifyFormat("int&& f3(int& b, int&& c, int* a);", Style); 2053 verifyFormat("int* f1(int& a) const& = 0;", Style); 2054 verifyFormat("int* a = f1();", Style); 2055 verifyFormat("int& b = f2();", Style); 2056 verifyFormat("int&& c = f3();", Style); 2057 verifyFormat("for (auto a = 0, b = 0; const auto& c : {1, 2, 3})", Style); 2058 verifyFormat("for (auto a = 0, b = 0; const int& c : {1, 2, 3})", Style); 2059 verifyFormat("for (auto a = 0, b = 0; const Foo& c : {1, 2, 3})", 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 auto& c : {1, 2, 3})", Style); 2062 verifyFormat("for (int a = 0, b = 0; const int& c : {1, 2, 3})", Style); 2063 verifyFormat("for (int a = 0, b = 0; const Foo& c : {1, 2, 3})", Style); 2064 verifyFormat("for (int a = 0, b = 0; const Foo* c : {1, 2, 3})", Style); 2065 verifyFormat("for (int a = 0, b++; const auto& c : {1, 2, 3})", Style); 2066 verifyFormat("for (int a = 0, b++; const int& c : {1, 2, 3})", Style); 2067 verifyFormat("for (int a = 0, b++; const Foo& c : {1, 2, 3})", Style); 2068 verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style); 2069 verifyFormat("for (auto x = 0; auto& c : {1, 2, 3})", Style); 2070 verifyFormat("for (auto x = 0; int& c : {1, 2, 3})", Style); 2071 verifyFormat("for (int x = 0; auto& c : {1, 2, 3})", Style); 2072 verifyFormat("for (int x = 0; int& c : {1, 2, 3})", Style); 2073 verifyFormat("for (f(); auto& c : {1, 2, 3})", Style); 2074 verifyFormat("for (f(); int& c : {1, 2, 3})", Style); 2075 verifyFormat( 2076 "function<int(int&)> res1 = [](int& a) { return 0000000000000; },\n" 2077 " res2 = [](int& a) { return 0000000000000; };", 2078 Style); 2079 2080 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 2081 verifyFormat("Const unsigned int* c;\n" 2082 "const unsigned int* d;\n" 2083 "Const unsigned int& e;\n" 2084 "const unsigned int& f;\n" 2085 "const unsigned&& g;\n" 2086 "Const unsigned h;", 2087 Style); 2088 2089 Style.PointerAlignment = FormatStyle::PAS_Right; 2090 Style.ReferenceAlignment = FormatStyle::RAS_Left; 2091 verifyFormat("int *f1(int *a, int& b, int&& c);", Style); 2092 verifyFormat("int& f2(int&& c, int *a, int& b);", Style); 2093 verifyFormat("int&& f3(int& b, int&& c, int *a);", Style); 2094 verifyFormat("int *a = f1();", Style); 2095 verifyFormat("int& b = f2();", Style); 2096 verifyFormat("int&& c = f3();", Style); 2097 verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style); 2098 verifyFormat("for (int a = 0, b = 0; const Foo *c : {1, 2, 3})", Style); 2099 verifyFormat("for (int a = 0, b++; const Foo *c : {1, 2, 3})", Style); 2100 2101 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 2102 verifyFormat("Const unsigned int *c;\n" 2103 "const unsigned int *d;\n" 2104 "Const unsigned int& e;\n" 2105 "const unsigned int& f;\n" 2106 "const unsigned g;\n" 2107 "Const unsigned h;", 2108 Style); 2109 2110 Style.PointerAlignment = FormatStyle::PAS_Left; 2111 Style.ReferenceAlignment = FormatStyle::RAS_Middle; 2112 verifyFormat("int* f1(int* a, int & b, int && c);", Style); 2113 verifyFormat("int & f2(int && c, int* a, int & b);", Style); 2114 verifyFormat("int && f3(int & b, int && c, int* a);", Style); 2115 verifyFormat("int* a = f1();", Style); 2116 verifyFormat("int & b = f2();", Style); 2117 verifyFormat("int && c = f3();", Style); 2118 verifyFormat("for (auto a = 0, b = 0; const auto & c : {1, 2, 3})", Style); 2119 verifyFormat("for (auto a = 0, b = 0; const int & c : {1, 2, 3})", Style); 2120 verifyFormat("for (auto a = 0, b = 0; const Foo & c : {1, 2, 3})", Style); 2121 verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style); 2122 verifyFormat("for (int a = 0, b++; const auto & c : {1, 2, 3})", Style); 2123 verifyFormat("for (int a = 0, b++; const int & c : {1, 2, 3})", Style); 2124 verifyFormat("for (int a = 0, b++; const Foo & c : {1, 2, 3})", Style); 2125 verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style); 2126 verifyFormat("for (auto x = 0; auto & c : {1, 2, 3})", Style); 2127 verifyFormat("for (auto x = 0; int & c : {1, 2, 3})", Style); 2128 verifyFormat("for (int x = 0; auto & c : {1, 2, 3})", Style); 2129 verifyFormat("for (int x = 0; int & c : {1, 2, 3})", Style); 2130 verifyFormat("for (f(); auto & c : {1, 2, 3})", Style); 2131 verifyFormat("for (f(); int & c : {1, 2, 3})", Style); 2132 verifyFormat( 2133 "function<int(int &)> res1 = [](int & a) { return 0000000000000; },\n" 2134 " res2 = [](int & a) { return 0000000000000; };", 2135 Style); 2136 2137 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 2138 verifyFormat("Const unsigned int* c;\n" 2139 "const unsigned int* d;\n" 2140 "Const unsigned int & e;\n" 2141 "const unsigned int & f;\n" 2142 "const unsigned && g;\n" 2143 "Const unsigned h;", 2144 Style); 2145 2146 Style.PointerAlignment = FormatStyle::PAS_Middle; 2147 Style.ReferenceAlignment = FormatStyle::RAS_Right; 2148 verifyFormat("int * f1(int * a, int &b, int &&c);", Style); 2149 verifyFormat("int &f2(int &&c, int * a, int &b);", Style); 2150 verifyFormat("int &&f3(int &b, int &&c, int * a);", Style); 2151 verifyFormat("int * a = f1();", Style); 2152 verifyFormat("int &b = f2();", Style); 2153 verifyFormat("int &&c = f3();", Style); 2154 verifyFormat("for (auto a = 0, b = 0; const Foo * c : {1, 2, 3})", Style); 2155 verifyFormat("for (int a = 0, b = 0; const Foo * c : {1, 2, 3})", Style); 2156 verifyFormat("for (int a = 0, b++; const Foo * c : {1, 2, 3})", Style); 2157 2158 // FIXME: we don't handle this yet, so output may be arbitrary until it's 2159 // specifically handled 2160 // verifyFormat("int Add2(BTree * &Root, char * szToAdd)", Style); 2161 } 2162 2163 TEST_F(FormatTest, FormatsForLoop) { 2164 verifyFormat( 2165 "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n" 2166 " ++VeryVeryLongLoopVariable)\n" 2167 " ;"); 2168 verifyFormat("for (;;)\n" 2169 " f();"); 2170 verifyFormat("for (;;) {\n}"); 2171 verifyFormat("for (;;) {\n" 2172 " f();\n" 2173 "}"); 2174 verifyFormat("for (int i = 0; (i < 10); ++i) {\n}"); 2175 2176 verifyFormat( 2177 "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n" 2178 " E = UnwrappedLines.end();\n" 2179 " I != E; ++I) {\n}"); 2180 2181 verifyFormat( 2182 "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n" 2183 " ++IIIII) {\n}"); 2184 verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n" 2185 " aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n" 2186 " aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}"); 2187 verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n" 2188 " I = FD->getDeclsInPrototypeScope().begin(),\n" 2189 " E = FD->getDeclsInPrototypeScope().end();\n" 2190 " I != E; ++I) {\n}"); 2191 verifyFormat("for (SmallVectorImpl<TemplateIdAnnotationn *>::iterator\n" 2192 " I = Container.begin(),\n" 2193 " E = Container.end();\n" 2194 " I != E; ++I) {\n}", 2195 getLLVMStyleWithColumns(76)); 2196 2197 verifyFormat( 2198 "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n" 2199 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n" 2200 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2201 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 2202 " ++aaaaaaaaaaa) {\n}"); 2203 verifyFormat("for (int i = 0; i < aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 2204 " bbbbbbbbbbbbbbbbbbbb < ccccccccccccccc;\n" 2205 " ++i) {\n}"); 2206 verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n" 2207 " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n" 2208 "}"); 2209 verifyFormat("for (some_namespace::SomeIterator iter( // force break\n" 2210 " aaaaaaaaaa);\n" 2211 " iter; ++iter) {\n" 2212 "}"); 2213 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2214 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 2215 " aaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbbbbbbb;\n" 2216 " ++aaaaaaaaaaaaaaaaaaaaaaaaaaa) {"); 2217 2218 // These should not be formatted as Objective-C for-in loops. 2219 verifyFormat("for (Foo *x = 0; x != in; x++) {\n}"); 2220 verifyFormat("Foo *x;\nfor (x = 0; x != in; x++) {\n}"); 2221 verifyFormat("Foo *x;\nfor (x in y) {\n}"); 2222 verifyFormat( 2223 "for (const Foo<Bar> &baz = in.value(); !baz.at_end(); ++baz) {\n}"); 2224 2225 FormatStyle NoBinPacking = getLLVMStyle(); 2226 NoBinPacking.BinPackParameters = false; 2227 verifyFormat("for (int aaaaaaaaaaa = 1;\n" 2228 " aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n" 2229 " aaaaaaaaaaaaaaaa,\n" 2230 " aaaaaaaaaaaaaaaa,\n" 2231 " aaaaaaaaaaaaaaaa);\n" 2232 " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n" 2233 "}", 2234 NoBinPacking); 2235 verifyFormat( 2236 "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n" 2237 " E = UnwrappedLines.end();\n" 2238 " I != E;\n" 2239 " ++I) {\n}", 2240 NoBinPacking); 2241 2242 FormatStyle AlignLeft = getLLVMStyle(); 2243 AlignLeft.PointerAlignment = FormatStyle::PAS_Left; 2244 verifyFormat("for (A* a = start; a < end; ++a, ++value) {\n}", AlignLeft); 2245 } 2246 2247 TEST_F(FormatTest, RangeBasedForLoops) { 2248 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 2249 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 2250 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n" 2251 " aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}"); 2252 verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n" 2253 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 2254 verifyFormat("for (aaaaaaaaa aaaaaaaaaaaaaaaaaaaaa :\n" 2255 " aaaaaaaaaaaa.aaaaaaaaaaaa().aaaaaaaaa().a()) {\n}"); 2256 } 2257 2258 TEST_F(FormatTest, ForEachLoops) { 2259 FormatStyle Style = getLLVMStyle(); 2260 EXPECT_EQ(Style.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 2261 EXPECT_EQ(Style.AllowShortLoopsOnASingleLine, false); 2262 verifyFormat("void f() {\n" 2263 " for (;;) {\n" 2264 " }\n" 2265 " foreach (Item *item, itemlist) {\n" 2266 " }\n" 2267 " Q_FOREACH (Item *item, itemlist) {\n" 2268 " }\n" 2269 " BOOST_FOREACH (Item *item, itemlist) {\n" 2270 " }\n" 2271 " UNKNOWN_FOREACH(Item * item, itemlist) {}\n" 2272 "}", 2273 Style); 2274 verifyFormat("void f() {\n" 2275 " for (;;)\n" 2276 " int j = 1;\n" 2277 " Q_FOREACH (int v, vec)\n" 2278 " v *= 2;\n" 2279 " for (;;) {\n" 2280 " int j = 1;\n" 2281 " }\n" 2282 " Q_FOREACH (int v, vec) {\n" 2283 " v *= 2;\n" 2284 " }\n" 2285 "}", 2286 Style); 2287 2288 FormatStyle ShortBlocks = getLLVMStyle(); 2289 ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 2290 EXPECT_EQ(ShortBlocks.AllowShortLoopsOnASingleLine, false); 2291 verifyFormat("void f() {\n" 2292 " for (;;)\n" 2293 " int j = 1;\n" 2294 " Q_FOREACH (int &v, vec)\n" 2295 " v *= 2;\n" 2296 " for (;;) {\n" 2297 " int j = 1;\n" 2298 " }\n" 2299 " Q_FOREACH (int &v, vec) {\n" 2300 " int j = 1;\n" 2301 " }\n" 2302 "}", 2303 ShortBlocks); 2304 2305 FormatStyle ShortLoops = getLLVMStyle(); 2306 ShortLoops.AllowShortLoopsOnASingleLine = true; 2307 EXPECT_EQ(ShortLoops.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 2308 verifyFormat("void f() {\n" 2309 " for (;;) int j = 1;\n" 2310 " Q_FOREACH (int &v, vec) int j = 1;\n" 2311 " for (;;) {\n" 2312 " int j = 1;\n" 2313 " }\n" 2314 " Q_FOREACH (int &v, vec) {\n" 2315 " int j = 1;\n" 2316 " }\n" 2317 "}", 2318 ShortLoops); 2319 2320 FormatStyle ShortBlocksAndLoops = getLLVMStyle(); 2321 ShortBlocksAndLoops.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 2322 ShortBlocksAndLoops.AllowShortLoopsOnASingleLine = true; 2323 verifyFormat("void f() {\n" 2324 " for (;;) int j = 1;\n" 2325 " Q_FOREACH (int &v, vec) int j = 1;\n" 2326 " for (;;) { int j = 1; }\n" 2327 " Q_FOREACH (int &v, vec) { int j = 1; }\n" 2328 "}", 2329 ShortBlocksAndLoops); 2330 2331 Style.SpaceBeforeParens = 2332 FormatStyle::SBPO_ControlStatementsExceptControlMacros; 2333 verifyFormat("void f() {\n" 2334 " for (;;) {\n" 2335 " }\n" 2336 " foreach(Item *item, itemlist) {\n" 2337 " }\n" 2338 " Q_FOREACH(Item *item, itemlist) {\n" 2339 " }\n" 2340 " BOOST_FOREACH(Item *item, itemlist) {\n" 2341 " }\n" 2342 " UNKNOWN_FOREACH(Item * item, itemlist) {}\n" 2343 "}", 2344 Style); 2345 2346 // As function-like macros. 2347 verifyFormat("#define foreach(x, y)\n" 2348 "#define Q_FOREACH(x, y)\n" 2349 "#define BOOST_FOREACH(x, y)\n" 2350 "#define UNKNOWN_FOREACH(x, y)\n"); 2351 2352 // Not as function-like macros. 2353 verifyFormat("#define foreach (x, y)\n" 2354 "#define Q_FOREACH (x, y)\n" 2355 "#define BOOST_FOREACH (x, y)\n" 2356 "#define UNKNOWN_FOREACH (x, y)\n"); 2357 2358 // handle microsoft non standard extension 2359 verifyFormat("for each (char c in x->MyStringProperty)"); 2360 } 2361 2362 TEST_F(FormatTest, FormatsWhileLoop) { 2363 verifyFormat("while (true) {\n}"); 2364 verifyFormat("while (true)\n" 2365 " f();"); 2366 verifyFormat("while () {\n}"); 2367 verifyFormat("while () {\n" 2368 " f();\n" 2369 "}"); 2370 } 2371 2372 TEST_F(FormatTest, FormatsDoWhile) { 2373 verifyFormat("do {\n" 2374 " do_something();\n" 2375 "} while (something());"); 2376 verifyFormat("do\n" 2377 " do_something();\n" 2378 "while (something());"); 2379 } 2380 2381 TEST_F(FormatTest, FormatsSwitchStatement) { 2382 verifyFormat("switch (x) {\n" 2383 "case 1:\n" 2384 " f();\n" 2385 " break;\n" 2386 "case kFoo:\n" 2387 "case ns::kBar:\n" 2388 "case kBaz:\n" 2389 " break;\n" 2390 "default:\n" 2391 " g();\n" 2392 " break;\n" 2393 "}"); 2394 verifyFormat("switch (x) {\n" 2395 "case 1: {\n" 2396 " f();\n" 2397 " break;\n" 2398 "}\n" 2399 "case 2: {\n" 2400 " break;\n" 2401 "}\n" 2402 "}"); 2403 verifyFormat("switch (x) {\n" 2404 "case 1: {\n" 2405 " f();\n" 2406 " {\n" 2407 " g();\n" 2408 " h();\n" 2409 " }\n" 2410 " break;\n" 2411 "}\n" 2412 "}"); 2413 verifyFormat("switch (x) {\n" 2414 "case 1: {\n" 2415 " f();\n" 2416 " if (foo) {\n" 2417 " g();\n" 2418 " h();\n" 2419 " }\n" 2420 " break;\n" 2421 "}\n" 2422 "}"); 2423 verifyFormat("switch (x) {\n" 2424 "case 1: {\n" 2425 " f();\n" 2426 " g();\n" 2427 "} break;\n" 2428 "}"); 2429 verifyFormat("switch (test)\n" 2430 " ;"); 2431 verifyFormat("switch (x) {\n" 2432 "default: {\n" 2433 " // Do nothing.\n" 2434 "}\n" 2435 "}"); 2436 verifyFormat("switch (x) {\n" 2437 "// comment\n" 2438 "// if 1, do f()\n" 2439 "case 1:\n" 2440 " f();\n" 2441 "}"); 2442 verifyFormat("switch (x) {\n" 2443 "case 1:\n" 2444 " // Do amazing stuff\n" 2445 " {\n" 2446 " f();\n" 2447 " g();\n" 2448 " }\n" 2449 " break;\n" 2450 "}"); 2451 verifyFormat("#define A \\\n" 2452 " switch (x) { \\\n" 2453 " case a: \\\n" 2454 " foo = b; \\\n" 2455 " }", 2456 getLLVMStyleWithColumns(20)); 2457 verifyFormat("#define OPERATION_CASE(name) \\\n" 2458 " case OP_name: \\\n" 2459 " return operations::Operation##name\n", 2460 getLLVMStyleWithColumns(40)); 2461 verifyFormat("switch (x) {\n" 2462 "case 1:;\n" 2463 "default:;\n" 2464 " int i;\n" 2465 "}"); 2466 2467 verifyGoogleFormat("switch (x) {\n" 2468 " case 1:\n" 2469 " f();\n" 2470 " break;\n" 2471 " case kFoo:\n" 2472 " case ns::kBar:\n" 2473 " case kBaz:\n" 2474 " break;\n" 2475 " default:\n" 2476 " g();\n" 2477 " break;\n" 2478 "}"); 2479 verifyGoogleFormat("switch (x) {\n" 2480 " case 1: {\n" 2481 " f();\n" 2482 " break;\n" 2483 " }\n" 2484 "}"); 2485 verifyGoogleFormat("switch (test)\n" 2486 " ;"); 2487 2488 verifyGoogleFormat("#define OPERATION_CASE(name) \\\n" 2489 " case OP_name: \\\n" 2490 " return operations::Operation##name\n"); 2491 verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n" 2492 " // Get the correction operation class.\n" 2493 " switch (OpCode) {\n" 2494 " CASE(Add);\n" 2495 " CASE(Subtract);\n" 2496 " default:\n" 2497 " return operations::Unknown;\n" 2498 " }\n" 2499 "#undef OPERATION_CASE\n" 2500 "}"); 2501 verifyFormat("DEBUG({\n" 2502 " switch (x) {\n" 2503 " case A:\n" 2504 " f();\n" 2505 " break;\n" 2506 " // fallthrough\n" 2507 " case B:\n" 2508 " g();\n" 2509 " break;\n" 2510 " }\n" 2511 "});"); 2512 EXPECT_EQ("DEBUG({\n" 2513 " switch (x) {\n" 2514 " case A:\n" 2515 " f();\n" 2516 " break;\n" 2517 " // On B:\n" 2518 " case B:\n" 2519 " g();\n" 2520 " break;\n" 2521 " }\n" 2522 "});", 2523 format("DEBUG({\n" 2524 " switch (x) {\n" 2525 " case A:\n" 2526 " f();\n" 2527 " break;\n" 2528 " // On B:\n" 2529 " case B:\n" 2530 " g();\n" 2531 " break;\n" 2532 " }\n" 2533 "});", 2534 getLLVMStyle())); 2535 EXPECT_EQ("switch (n) {\n" 2536 "case 0: {\n" 2537 " return false;\n" 2538 "}\n" 2539 "default: {\n" 2540 " return true;\n" 2541 "}\n" 2542 "}", 2543 format("switch (n)\n" 2544 "{\n" 2545 "case 0: {\n" 2546 " return false;\n" 2547 "}\n" 2548 "default: {\n" 2549 " return true;\n" 2550 "}\n" 2551 "}", 2552 getLLVMStyle())); 2553 verifyFormat("switch (a) {\n" 2554 "case (b):\n" 2555 " return;\n" 2556 "}"); 2557 2558 verifyFormat("switch (a) {\n" 2559 "case some_namespace::\n" 2560 " some_constant:\n" 2561 " return;\n" 2562 "}", 2563 getLLVMStyleWithColumns(34)); 2564 2565 FormatStyle Style = getLLVMStyle(); 2566 Style.IndentCaseLabels = true; 2567 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 2568 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2569 Style.BraceWrapping.AfterCaseLabel = true; 2570 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 2571 EXPECT_EQ("switch (n)\n" 2572 "{\n" 2573 " case 0:\n" 2574 " {\n" 2575 " return false;\n" 2576 " }\n" 2577 " default:\n" 2578 " {\n" 2579 " return true;\n" 2580 " }\n" 2581 "}", 2582 format("switch (n) {\n" 2583 " case 0: {\n" 2584 " return false;\n" 2585 " }\n" 2586 " default: {\n" 2587 " return true;\n" 2588 " }\n" 2589 "}", 2590 Style)); 2591 Style.BraceWrapping.AfterCaseLabel = false; 2592 EXPECT_EQ("switch (n)\n" 2593 "{\n" 2594 " case 0: {\n" 2595 " return false;\n" 2596 " }\n" 2597 " default: {\n" 2598 " return true;\n" 2599 " }\n" 2600 "}", 2601 format("switch (n) {\n" 2602 " case 0:\n" 2603 " {\n" 2604 " return false;\n" 2605 " }\n" 2606 " default:\n" 2607 " {\n" 2608 " return true;\n" 2609 " }\n" 2610 "}", 2611 Style)); 2612 Style.IndentCaseLabels = false; 2613 Style.IndentCaseBlocks = true; 2614 EXPECT_EQ("switch (n)\n" 2615 "{\n" 2616 "case 0:\n" 2617 " {\n" 2618 " return false;\n" 2619 " }\n" 2620 "case 1:\n" 2621 " break;\n" 2622 "default:\n" 2623 " {\n" 2624 " return true;\n" 2625 " }\n" 2626 "}", 2627 format("switch (n) {\n" 2628 "case 0: {\n" 2629 " return false;\n" 2630 "}\n" 2631 "case 1:\n" 2632 " break;\n" 2633 "default: {\n" 2634 " return true;\n" 2635 "}\n" 2636 "}", 2637 Style)); 2638 Style.IndentCaseLabels = true; 2639 Style.IndentCaseBlocks = true; 2640 EXPECT_EQ("switch (n)\n" 2641 "{\n" 2642 " case 0:\n" 2643 " {\n" 2644 " return false;\n" 2645 " }\n" 2646 " case 1:\n" 2647 " break;\n" 2648 " default:\n" 2649 " {\n" 2650 " return true;\n" 2651 " }\n" 2652 "}", 2653 format("switch (n) {\n" 2654 "case 0: {\n" 2655 " return false;\n" 2656 "}\n" 2657 "case 1:\n" 2658 " break;\n" 2659 "default: {\n" 2660 " return true;\n" 2661 "}\n" 2662 "}", 2663 Style)); 2664 } 2665 2666 TEST_F(FormatTest, CaseRanges) { 2667 verifyFormat("switch (x) {\n" 2668 "case 'A' ... 'Z':\n" 2669 "case 1 ... 5:\n" 2670 "case a ... b:\n" 2671 " break;\n" 2672 "}"); 2673 } 2674 2675 TEST_F(FormatTest, ShortEnums) { 2676 FormatStyle Style = getLLVMStyle(); 2677 Style.AllowShortEnumsOnASingleLine = true; 2678 verifyFormat("enum { A, B, C } ShortEnum1, ShortEnum2;", Style); 2679 verifyFormat("typedef enum { A, B, C } ShortEnum1, ShortEnum2;", Style); 2680 Style.AllowShortEnumsOnASingleLine = false; 2681 verifyFormat("enum {\n" 2682 " A,\n" 2683 " B,\n" 2684 " C\n" 2685 "} ShortEnum1, ShortEnum2;", 2686 Style); 2687 verifyFormat("typedef enum {\n" 2688 " A,\n" 2689 " B,\n" 2690 " C\n" 2691 "} ShortEnum1, ShortEnum2;", 2692 Style); 2693 verifyFormat("enum {\n" 2694 " A,\n" 2695 "} ShortEnum1, ShortEnum2;", 2696 Style); 2697 verifyFormat("typedef enum {\n" 2698 " A,\n" 2699 "} ShortEnum1, ShortEnum2;", 2700 Style); 2701 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2702 Style.BraceWrapping.AfterEnum = true; 2703 verifyFormat("enum\n" 2704 "{\n" 2705 " A,\n" 2706 " B,\n" 2707 " C\n" 2708 "} ShortEnum1, ShortEnum2;", 2709 Style); 2710 verifyFormat("typedef enum\n" 2711 "{\n" 2712 " A,\n" 2713 " B,\n" 2714 " C\n" 2715 "} ShortEnum1, ShortEnum2;", 2716 Style); 2717 } 2718 2719 TEST_F(FormatTest, ShortCaseLabels) { 2720 FormatStyle Style = getLLVMStyle(); 2721 Style.AllowShortCaseLabelsOnASingleLine = true; 2722 verifyFormat("switch (a) {\n" 2723 "case 1: x = 1; break;\n" 2724 "case 2: return;\n" 2725 "case 3:\n" 2726 "case 4:\n" 2727 "case 5: return;\n" 2728 "case 6: // comment\n" 2729 " return;\n" 2730 "case 7:\n" 2731 " // comment\n" 2732 " return;\n" 2733 "case 8:\n" 2734 " x = 8; // comment\n" 2735 " break;\n" 2736 "default: y = 1; break;\n" 2737 "}", 2738 Style); 2739 verifyFormat("switch (a) {\n" 2740 "case 0: return; // comment\n" 2741 "case 1: break; // comment\n" 2742 "case 2: return;\n" 2743 "// comment\n" 2744 "case 3: return;\n" 2745 "// comment 1\n" 2746 "// comment 2\n" 2747 "// comment 3\n" 2748 "case 4: break; /* comment */\n" 2749 "case 5:\n" 2750 " // comment\n" 2751 " break;\n" 2752 "case 6: /* comment */ x = 1; break;\n" 2753 "case 7: x = /* comment */ 1; break;\n" 2754 "case 8:\n" 2755 " x = 1; /* comment */\n" 2756 " break;\n" 2757 "case 9:\n" 2758 " break; // comment line 1\n" 2759 " // comment line 2\n" 2760 "}", 2761 Style); 2762 EXPECT_EQ("switch (a) {\n" 2763 "case 1:\n" 2764 " x = 8;\n" 2765 " // fall through\n" 2766 "case 2: x = 8;\n" 2767 "// comment\n" 2768 "case 3:\n" 2769 " return; /* comment line 1\n" 2770 " * comment line 2 */\n" 2771 "case 4: i = 8;\n" 2772 "// something else\n" 2773 "#if FOO\n" 2774 "case 5: break;\n" 2775 "#endif\n" 2776 "}", 2777 format("switch (a) {\n" 2778 "case 1: x = 8;\n" 2779 " // fall through\n" 2780 "case 2:\n" 2781 " x = 8;\n" 2782 "// comment\n" 2783 "case 3:\n" 2784 " return; /* comment line 1\n" 2785 " * comment line 2 */\n" 2786 "case 4:\n" 2787 " i = 8;\n" 2788 "// something else\n" 2789 "#if FOO\n" 2790 "case 5: break;\n" 2791 "#endif\n" 2792 "}", 2793 Style)); 2794 EXPECT_EQ("switch (a) {\n" 2795 "case 0:\n" 2796 " return; // long long long long long long long long long long " 2797 "long long comment\n" 2798 " // line\n" 2799 "}", 2800 format("switch (a) {\n" 2801 "case 0: return; // long long long long long long long long " 2802 "long long long long comment line\n" 2803 "}", 2804 Style)); 2805 EXPECT_EQ("switch (a) {\n" 2806 "case 0:\n" 2807 " return; /* long long long long long long long long long long " 2808 "long long comment\n" 2809 " line */\n" 2810 "}", 2811 format("switch (a) {\n" 2812 "case 0: return; /* long long long long long long long long " 2813 "long long long long comment line */\n" 2814 "}", 2815 Style)); 2816 verifyFormat("switch (a) {\n" 2817 "#if FOO\n" 2818 "case 0: return 0;\n" 2819 "#endif\n" 2820 "}", 2821 Style); 2822 verifyFormat("switch (a) {\n" 2823 "case 1: {\n" 2824 "}\n" 2825 "case 2: {\n" 2826 " return;\n" 2827 "}\n" 2828 "case 3: {\n" 2829 " x = 1;\n" 2830 " return;\n" 2831 "}\n" 2832 "case 4:\n" 2833 " if (x)\n" 2834 " return;\n" 2835 "}", 2836 Style); 2837 Style.ColumnLimit = 21; 2838 verifyFormat("switch (a) {\n" 2839 "case 1: x = 1; break;\n" 2840 "case 2: return;\n" 2841 "case 3:\n" 2842 "case 4:\n" 2843 "case 5: return;\n" 2844 "default:\n" 2845 " y = 1;\n" 2846 " break;\n" 2847 "}", 2848 Style); 2849 Style.ColumnLimit = 80; 2850 Style.AllowShortCaseLabelsOnASingleLine = false; 2851 Style.IndentCaseLabels = true; 2852 EXPECT_EQ("switch (n) {\n" 2853 " default /*comments*/:\n" 2854 " return true;\n" 2855 " case 0:\n" 2856 " return false;\n" 2857 "}", 2858 format("switch (n) {\n" 2859 "default/*comments*/:\n" 2860 " return true;\n" 2861 "case 0:\n" 2862 " return false;\n" 2863 "}", 2864 Style)); 2865 Style.AllowShortCaseLabelsOnASingleLine = true; 2866 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2867 Style.BraceWrapping.AfterCaseLabel = true; 2868 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 2869 EXPECT_EQ("switch (n)\n" 2870 "{\n" 2871 " case 0:\n" 2872 " {\n" 2873 " return false;\n" 2874 " }\n" 2875 " default:\n" 2876 " {\n" 2877 " return true;\n" 2878 " }\n" 2879 "}", 2880 format("switch (n) {\n" 2881 " case 0: {\n" 2882 " return false;\n" 2883 " }\n" 2884 " default:\n" 2885 " {\n" 2886 " return true;\n" 2887 " }\n" 2888 "}", 2889 Style)); 2890 } 2891 2892 TEST_F(FormatTest, FormatsLabels) { 2893 verifyFormat("void f() {\n" 2894 " some_code();\n" 2895 "test_label:\n" 2896 " some_other_code();\n" 2897 " {\n" 2898 " some_more_code();\n" 2899 " another_label:\n" 2900 " some_more_code();\n" 2901 " }\n" 2902 "}"); 2903 verifyFormat("{\n" 2904 " some_code();\n" 2905 "test_label:\n" 2906 " some_other_code();\n" 2907 "}"); 2908 verifyFormat("{\n" 2909 " some_code();\n" 2910 "test_label:;\n" 2911 " int i = 0;\n" 2912 "}"); 2913 FormatStyle Style = getLLVMStyle(); 2914 Style.IndentGotoLabels = false; 2915 verifyFormat("void f() {\n" 2916 " some_code();\n" 2917 "test_label:\n" 2918 " some_other_code();\n" 2919 " {\n" 2920 " some_more_code();\n" 2921 "another_label:\n" 2922 " some_more_code();\n" 2923 " }\n" 2924 "}", 2925 Style); 2926 verifyFormat("{\n" 2927 " some_code();\n" 2928 "test_label:\n" 2929 " some_other_code();\n" 2930 "}", 2931 Style); 2932 verifyFormat("{\n" 2933 " some_code();\n" 2934 "test_label:;\n" 2935 " int i = 0;\n" 2936 "}"); 2937 } 2938 2939 TEST_F(FormatTest, MultiLineControlStatements) { 2940 FormatStyle Style = getLLVMStyleWithColumns(20); 2941 Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom; 2942 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine; 2943 // Short lines should keep opening brace on same line. 2944 EXPECT_EQ("if (foo) {\n" 2945 " bar();\n" 2946 "}", 2947 format("if(foo){bar();}", Style)); 2948 EXPECT_EQ("if (foo) {\n" 2949 " bar();\n" 2950 "} else {\n" 2951 " baz();\n" 2952 "}", 2953 format("if(foo){bar();}else{baz();}", Style)); 2954 EXPECT_EQ("if (foo && bar) {\n" 2955 " baz();\n" 2956 "}", 2957 format("if(foo&&bar){baz();}", Style)); 2958 EXPECT_EQ("if (foo) {\n" 2959 " bar();\n" 2960 "} else if (baz) {\n" 2961 " quux();\n" 2962 "}", 2963 format("if(foo){bar();}else if(baz){quux();}", Style)); 2964 EXPECT_EQ( 2965 "if (foo) {\n" 2966 " bar();\n" 2967 "} else if (baz) {\n" 2968 " quux();\n" 2969 "} else {\n" 2970 " foobar();\n" 2971 "}", 2972 format("if(foo){bar();}else if(baz){quux();}else{foobar();}", Style)); 2973 EXPECT_EQ("for (;;) {\n" 2974 " foo();\n" 2975 "}", 2976 format("for(;;){foo();}")); 2977 EXPECT_EQ("while (1) {\n" 2978 " foo();\n" 2979 "}", 2980 format("while(1){foo();}", Style)); 2981 EXPECT_EQ("switch (foo) {\n" 2982 "case bar:\n" 2983 " return;\n" 2984 "}", 2985 format("switch(foo){case bar:return;}", Style)); 2986 EXPECT_EQ("try {\n" 2987 " foo();\n" 2988 "} catch (...) {\n" 2989 " bar();\n" 2990 "}", 2991 format("try{foo();}catch(...){bar();}", Style)); 2992 EXPECT_EQ("do {\n" 2993 " foo();\n" 2994 "} while (bar &&\n" 2995 " baz);", 2996 format("do{foo();}while(bar&&baz);", Style)); 2997 // Long lines should put opening brace on new line. 2998 EXPECT_EQ("if (foo && bar &&\n" 2999 " baz)\n" 3000 "{\n" 3001 " quux();\n" 3002 "}", 3003 format("if(foo&&bar&&baz){quux();}", Style)); 3004 EXPECT_EQ("if (foo && bar &&\n" 3005 " baz)\n" 3006 "{\n" 3007 " quux();\n" 3008 "}", 3009 format("if (foo && bar &&\n" 3010 " baz) {\n" 3011 " quux();\n" 3012 "}", 3013 Style)); 3014 EXPECT_EQ("if (foo) {\n" 3015 " bar();\n" 3016 "} else if (baz ||\n" 3017 " quux)\n" 3018 "{\n" 3019 " foobar();\n" 3020 "}", 3021 format("if(foo){bar();}else if(baz||quux){foobar();}", Style)); 3022 EXPECT_EQ( 3023 "if (foo) {\n" 3024 " bar();\n" 3025 "} else if (baz ||\n" 3026 " quux)\n" 3027 "{\n" 3028 " foobar();\n" 3029 "} else {\n" 3030 " barbaz();\n" 3031 "}", 3032 format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}", 3033 Style)); 3034 EXPECT_EQ("for (int i = 0;\n" 3035 " i < 10; ++i)\n" 3036 "{\n" 3037 " foo();\n" 3038 "}", 3039 format("for(int i=0;i<10;++i){foo();}", Style)); 3040 EXPECT_EQ("foreach (int i,\n" 3041 " list)\n" 3042 "{\n" 3043 " foo();\n" 3044 "}", 3045 format("foreach(int i, list){foo();}", Style)); 3046 Style.ColumnLimit = 3047 40; // to concentrate at brace wrapping, not line wrap due to column limit 3048 EXPECT_EQ("foreach (int i, list) {\n" 3049 " foo();\n" 3050 "}", 3051 format("foreach(int i, list){foo();}", Style)); 3052 Style.ColumnLimit = 3053 20; // to concentrate at brace wrapping, not line wrap due to column limit 3054 EXPECT_EQ("while (foo || bar ||\n" 3055 " baz)\n" 3056 "{\n" 3057 " quux();\n" 3058 "}", 3059 format("while(foo||bar||baz){quux();}", Style)); 3060 EXPECT_EQ("switch (\n" 3061 " foo = barbaz)\n" 3062 "{\n" 3063 "case quux:\n" 3064 " return;\n" 3065 "}", 3066 format("switch(foo=barbaz){case quux:return;}", Style)); 3067 EXPECT_EQ("try {\n" 3068 " foo();\n" 3069 "} catch (\n" 3070 " Exception &bar)\n" 3071 "{\n" 3072 " baz();\n" 3073 "}", 3074 format("try{foo();}catch(Exception&bar){baz();}", Style)); 3075 Style.ColumnLimit = 3076 40; // to concentrate at brace wrapping, not line wrap due to column limit 3077 EXPECT_EQ("try {\n" 3078 " foo();\n" 3079 "} catch (Exception &bar) {\n" 3080 " baz();\n" 3081 "}", 3082 format("try{foo();}catch(Exception&bar){baz();}", Style)); 3083 Style.ColumnLimit = 3084 20; // to concentrate at brace wrapping, not line wrap due to column limit 3085 3086 Style.BraceWrapping.BeforeElse = true; 3087 EXPECT_EQ( 3088 "if (foo) {\n" 3089 " bar();\n" 3090 "}\n" 3091 "else if (baz ||\n" 3092 " quux)\n" 3093 "{\n" 3094 " foobar();\n" 3095 "}\n" 3096 "else {\n" 3097 " barbaz();\n" 3098 "}", 3099 format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}", 3100 Style)); 3101 3102 Style.BraceWrapping.BeforeCatch = true; 3103 EXPECT_EQ("try {\n" 3104 " foo();\n" 3105 "}\n" 3106 "catch (...) {\n" 3107 " baz();\n" 3108 "}", 3109 format("try{foo();}catch(...){baz();}", Style)); 3110 3111 Style.BraceWrapping.AfterFunction = true; 3112 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine; 3113 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 3114 Style.ColumnLimit = 80; 3115 verifyFormat("void shortfunction() { bar(); }", Style); 3116 3117 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 3118 verifyFormat("void shortfunction()\n" 3119 "{\n" 3120 " bar();\n" 3121 "}", 3122 Style); 3123 } 3124 3125 TEST_F(FormatTest, BeforeWhile) { 3126 FormatStyle Style = getLLVMStyle(); 3127 Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom; 3128 3129 verifyFormat("do {\n" 3130 " foo();\n" 3131 "} while (1);", 3132 Style); 3133 Style.BraceWrapping.BeforeWhile = true; 3134 verifyFormat("do {\n" 3135 " foo();\n" 3136 "}\n" 3137 "while (1);", 3138 Style); 3139 } 3140 3141 //===----------------------------------------------------------------------===// 3142 // Tests for classes, namespaces, etc. 3143 //===----------------------------------------------------------------------===// 3144 3145 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) { 3146 verifyFormat("class A {};"); 3147 } 3148 3149 TEST_F(FormatTest, UnderstandsAccessSpecifiers) { 3150 verifyFormat("class A {\n" 3151 "public:\n" 3152 "public: // comment\n" 3153 "protected:\n" 3154 "private:\n" 3155 " void f() {}\n" 3156 "};"); 3157 verifyFormat("export class A {\n" 3158 "public:\n" 3159 "public: // comment\n" 3160 "protected:\n" 3161 "private:\n" 3162 " void f() {}\n" 3163 "};"); 3164 verifyGoogleFormat("class A {\n" 3165 " public:\n" 3166 " protected:\n" 3167 " private:\n" 3168 " void f() {}\n" 3169 "};"); 3170 verifyGoogleFormat("export class A {\n" 3171 " public:\n" 3172 " protected:\n" 3173 " private:\n" 3174 " void f() {}\n" 3175 "};"); 3176 verifyFormat("class A {\n" 3177 "public slots:\n" 3178 " void f1() {}\n" 3179 "public Q_SLOTS:\n" 3180 " void f2() {}\n" 3181 "protected slots:\n" 3182 " void f3() {}\n" 3183 "protected Q_SLOTS:\n" 3184 " void f4() {}\n" 3185 "private slots:\n" 3186 " void f5() {}\n" 3187 "private Q_SLOTS:\n" 3188 " void f6() {}\n" 3189 "signals:\n" 3190 " void g1();\n" 3191 "Q_SIGNALS:\n" 3192 " void g2();\n" 3193 "};"); 3194 3195 // Don't interpret 'signals' the wrong way. 3196 verifyFormat("signals.set();"); 3197 verifyFormat("for (Signals signals : f()) {\n}"); 3198 verifyFormat("{\n" 3199 " signals.set(); // This needs indentation.\n" 3200 "}"); 3201 verifyFormat("void f() {\n" 3202 "label:\n" 3203 " signals.baz();\n" 3204 "}"); 3205 verifyFormat("private[1];"); 3206 verifyFormat("testArray[public] = 1;"); 3207 verifyFormat("public();"); 3208 verifyFormat("myFunc(public);"); 3209 verifyFormat("std::vector<int> testVec = {private};"); 3210 verifyFormat("private.p = 1;"); 3211 verifyFormat("void function(private...){};"); 3212 verifyFormat("if (private && public)\n"); 3213 verifyFormat("private &= true;"); 3214 verifyFormat("int x = private * public;"); 3215 verifyFormat("public *= private;"); 3216 verifyFormat("int x = public + private;"); 3217 verifyFormat("private++;"); 3218 verifyFormat("++private;"); 3219 verifyFormat("public += private;"); 3220 verifyFormat("public = public - private;"); 3221 verifyFormat("public->foo();"); 3222 verifyFormat("private--;"); 3223 verifyFormat("--private;"); 3224 verifyFormat("public -= 1;"); 3225 verifyFormat("if (!private && !public)\n"); 3226 verifyFormat("public != private;"); 3227 verifyFormat("int x = public / private;"); 3228 verifyFormat("public /= 2;"); 3229 verifyFormat("public = public % 2;"); 3230 verifyFormat("public %= 2;"); 3231 verifyFormat("if (public < private)\n"); 3232 verifyFormat("public << private;"); 3233 verifyFormat("public <<= private;"); 3234 verifyFormat("if (public > private)\n"); 3235 verifyFormat("public >> private;"); 3236 verifyFormat("public >>= private;"); 3237 verifyFormat("public ^ private;"); 3238 verifyFormat("public ^= private;"); 3239 verifyFormat("public | private;"); 3240 verifyFormat("public |= private;"); 3241 verifyFormat("auto x = private ? 1 : 2;"); 3242 verifyFormat("if (public == private)\n"); 3243 verifyFormat("void foo(public, private)"); 3244 verifyFormat("public::foo();"); 3245 } 3246 3247 TEST_F(FormatTest, SeparatesLogicalBlocks) { 3248 EXPECT_EQ("class A {\n" 3249 "public:\n" 3250 " void f();\n" 3251 "\n" 3252 "private:\n" 3253 " void g() {}\n" 3254 " // test\n" 3255 "protected:\n" 3256 " int h;\n" 3257 "};", 3258 format("class A {\n" 3259 "public:\n" 3260 "void f();\n" 3261 "private:\n" 3262 "void g() {}\n" 3263 "// test\n" 3264 "protected:\n" 3265 "int h;\n" 3266 "};")); 3267 EXPECT_EQ("class A {\n" 3268 "protected:\n" 3269 "public:\n" 3270 " void f();\n" 3271 "};", 3272 format("class A {\n" 3273 "protected:\n" 3274 "\n" 3275 "public:\n" 3276 "\n" 3277 " void f();\n" 3278 "};")); 3279 3280 // Even ensure proper spacing inside macros. 3281 EXPECT_EQ("#define B \\\n" 3282 " class A { \\\n" 3283 " protected: \\\n" 3284 " public: \\\n" 3285 " void f(); \\\n" 3286 " };", 3287 format("#define B \\\n" 3288 " class A { \\\n" 3289 " protected: \\\n" 3290 " \\\n" 3291 " public: \\\n" 3292 " \\\n" 3293 " void f(); \\\n" 3294 " };", 3295 getGoogleStyle())); 3296 // But don't remove empty lines after macros ending in access specifiers. 3297 EXPECT_EQ("#define A private:\n" 3298 "\n" 3299 "int i;", 3300 format("#define A private:\n" 3301 "\n" 3302 "int i;")); 3303 } 3304 3305 TEST_F(FormatTest, FormatsClasses) { 3306 verifyFormat("class A : public B {};"); 3307 verifyFormat("class A : public ::B {};"); 3308 3309 verifyFormat( 3310 "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3311 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};"); 3312 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n" 3313 " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3314 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};"); 3315 verifyFormat( 3316 "class A : public B, public C, public D, public E, public F {};"); 3317 verifyFormat("class AAAAAAAAAAAA : public B,\n" 3318 " public C,\n" 3319 " public D,\n" 3320 " public E,\n" 3321 " public F,\n" 3322 " public G {};"); 3323 3324 verifyFormat("class\n" 3325 " ReallyReallyLongClassName {\n" 3326 " int i;\n" 3327 "};", 3328 getLLVMStyleWithColumns(32)); 3329 verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n" 3330 " aaaaaaaaaaaaaaaa> {};"); 3331 verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n" 3332 " : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n" 3333 " aaaaaaaaaaaaaaaaaaaaaa> {};"); 3334 verifyFormat("template <class R, class C>\n" 3335 "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n" 3336 " : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};"); 3337 verifyFormat("class ::A::B {};"); 3338 } 3339 3340 TEST_F(FormatTest, BreakInheritanceStyle) { 3341 FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle(); 3342 StyleWithInheritanceBreakBeforeComma.BreakInheritanceList = 3343 FormatStyle::BILS_BeforeComma; 3344 verifyFormat("class MyClass : public X {};", 3345 StyleWithInheritanceBreakBeforeComma); 3346 verifyFormat("class MyClass\n" 3347 " : public X\n" 3348 " , public Y {};", 3349 StyleWithInheritanceBreakBeforeComma); 3350 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n" 3351 " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n" 3352 " , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};", 3353 StyleWithInheritanceBreakBeforeComma); 3354 verifyFormat("struct aaaaaaaaaaaaa\n" 3355 " : public aaaaaaaaaaaaaaaaaaa< // break\n" 3356 " aaaaaaaaaaaaaaaa> {};", 3357 StyleWithInheritanceBreakBeforeComma); 3358 3359 FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle(); 3360 StyleWithInheritanceBreakAfterColon.BreakInheritanceList = 3361 FormatStyle::BILS_AfterColon; 3362 verifyFormat("class MyClass : public X {};", 3363 StyleWithInheritanceBreakAfterColon); 3364 verifyFormat("class MyClass : public X, public Y {};", 3365 StyleWithInheritanceBreakAfterColon); 3366 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n" 3367 " public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3368 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};", 3369 StyleWithInheritanceBreakAfterColon); 3370 verifyFormat("struct aaaaaaaaaaaaa :\n" 3371 " public aaaaaaaaaaaaaaaaaaa< // break\n" 3372 " aaaaaaaaaaaaaaaa> {};", 3373 StyleWithInheritanceBreakAfterColon); 3374 3375 FormatStyle StyleWithInheritanceBreakAfterComma = getLLVMStyle(); 3376 StyleWithInheritanceBreakAfterComma.BreakInheritanceList = 3377 FormatStyle::BILS_AfterComma; 3378 verifyFormat("class MyClass : public X {};", 3379 StyleWithInheritanceBreakAfterComma); 3380 verifyFormat("class MyClass : public X,\n" 3381 " public Y {};", 3382 StyleWithInheritanceBreakAfterComma); 3383 verifyFormat( 3384 "class AAAAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3385 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC " 3386 "{};", 3387 StyleWithInheritanceBreakAfterComma); 3388 verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n" 3389 " aaaaaaaaaaaaaaaa> {};", 3390 StyleWithInheritanceBreakAfterComma); 3391 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n" 3392 " : public OnceBreak,\n" 3393 " public AlwaysBreak,\n" 3394 " EvenBasesFitInOneLine {};", 3395 StyleWithInheritanceBreakAfterComma); 3396 } 3397 3398 TEST_F(FormatTest, FormatsVariableDeclarationsAfterStructOrClass) { 3399 verifyFormat("class A {\n} a, b;"); 3400 verifyFormat("struct A {\n} a, b;"); 3401 verifyFormat("union A {\n} a;"); 3402 } 3403 3404 TEST_F(FormatTest, FormatsEnum) { 3405 verifyFormat("enum {\n" 3406 " Zero,\n" 3407 " One = 1,\n" 3408 " Two = One + 1,\n" 3409 " Three = (One + Two),\n" 3410 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3411 " Five = (One, Two, Three, Four, 5)\n" 3412 "};"); 3413 verifyGoogleFormat("enum {\n" 3414 " Zero,\n" 3415 " One = 1,\n" 3416 " Two = One + 1,\n" 3417 " Three = (One + Two),\n" 3418 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3419 " Five = (One, Two, Three, Four, 5)\n" 3420 "};"); 3421 verifyFormat("enum Enum {};"); 3422 verifyFormat("enum {};"); 3423 verifyFormat("enum X E {} d;"); 3424 verifyFormat("enum __attribute__((...)) E {} d;"); 3425 verifyFormat("enum __declspec__((...)) E {} d;"); 3426 verifyFormat("enum {\n" 3427 " Bar = Foo<int, int>::value\n" 3428 "};", 3429 getLLVMStyleWithColumns(30)); 3430 3431 verifyFormat("enum ShortEnum { A, B, C };"); 3432 verifyGoogleFormat("enum ShortEnum { A, B, C };"); 3433 3434 EXPECT_EQ("enum KeepEmptyLines {\n" 3435 " ONE,\n" 3436 "\n" 3437 " TWO,\n" 3438 "\n" 3439 " THREE\n" 3440 "}", 3441 format("enum KeepEmptyLines {\n" 3442 " ONE,\n" 3443 "\n" 3444 " TWO,\n" 3445 "\n" 3446 "\n" 3447 " THREE\n" 3448 "}")); 3449 verifyFormat("enum E { // comment\n" 3450 " ONE,\n" 3451 " TWO\n" 3452 "};\n" 3453 "int i;"); 3454 3455 FormatStyle EightIndent = getLLVMStyle(); 3456 EightIndent.IndentWidth = 8; 3457 verifyFormat("enum {\n" 3458 " VOID,\n" 3459 " CHAR,\n" 3460 " SHORT,\n" 3461 " INT,\n" 3462 " LONG,\n" 3463 " SIGNED,\n" 3464 " UNSIGNED,\n" 3465 " BOOL,\n" 3466 " FLOAT,\n" 3467 " DOUBLE,\n" 3468 " COMPLEX\n" 3469 "};", 3470 EightIndent); 3471 3472 // Not enums. 3473 verifyFormat("enum X f() {\n" 3474 " a();\n" 3475 " return 42;\n" 3476 "}"); 3477 verifyFormat("enum X Type::f() {\n" 3478 " a();\n" 3479 " return 42;\n" 3480 "}"); 3481 verifyFormat("enum ::X f() {\n" 3482 " a();\n" 3483 " return 42;\n" 3484 "}"); 3485 verifyFormat("enum ns::X f() {\n" 3486 " a();\n" 3487 " return 42;\n" 3488 "}"); 3489 } 3490 3491 TEST_F(FormatTest, FormatsEnumsWithErrors) { 3492 verifyFormat("enum Type {\n" 3493 " One = 0; // These semicolons should be commas.\n" 3494 " Two = 1;\n" 3495 "};"); 3496 verifyFormat("namespace n {\n" 3497 "enum Type {\n" 3498 " One,\n" 3499 " Two, // missing };\n" 3500 " int i;\n" 3501 "}\n" 3502 "void g() {}"); 3503 } 3504 3505 TEST_F(FormatTest, FormatsEnumStruct) { 3506 verifyFormat("enum struct {\n" 3507 " Zero,\n" 3508 " One = 1,\n" 3509 " Two = One + 1,\n" 3510 " Three = (One + Two),\n" 3511 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3512 " Five = (One, Two, Three, Four, 5)\n" 3513 "};"); 3514 verifyFormat("enum struct Enum {};"); 3515 verifyFormat("enum struct {};"); 3516 verifyFormat("enum struct X E {} d;"); 3517 verifyFormat("enum struct __attribute__((...)) E {} d;"); 3518 verifyFormat("enum struct __declspec__((...)) E {} d;"); 3519 verifyFormat("enum struct X f() {\n a();\n return 42;\n}"); 3520 } 3521 3522 TEST_F(FormatTest, FormatsEnumClass) { 3523 verifyFormat("enum class {\n" 3524 " Zero,\n" 3525 " One = 1,\n" 3526 " Two = One + 1,\n" 3527 " Three = (One + Two),\n" 3528 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3529 " Five = (One, Two, Three, Four, 5)\n" 3530 "};"); 3531 verifyFormat("enum class Enum {};"); 3532 verifyFormat("enum class {};"); 3533 verifyFormat("enum class X E {} d;"); 3534 verifyFormat("enum class __attribute__((...)) E {} d;"); 3535 verifyFormat("enum class __declspec__((...)) E {} d;"); 3536 verifyFormat("enum class X f() {\n a();\n return 42;\n}"); 3537 } 3538 3539 TEST_F(FormatTest, FormatsEnumTypes) { 3540 verifyFormat("enum X : int {\n" 3541 " A, // Force multiple lines.\n" 3542 " B\n" 3543 "};"); 3544 verifyFormat("enum X : int { A, B };"); 3545 verifyFormat("enum X : std::uint32_t { A, B };"); 3546 } 3547 3548 TEST_F(FormatTest, FormatsTypedefEnum) { 3549 FormatStyle Style = getLLVMStyleWithColumns(40); 3550 verifyFormat("typedef enum {} EmptyEnum;"); 3551 verifyFormat("typedef enum { A, B, C } ShortEnum;"); 3552 verifyFormat("typedef enum {\n" 3553 " ZERO = 0,\n" 3554 " ONE = 1,\n" 3555 " TWO = 2,\n" 3556 " THREE = 3\n" 3557 "} LongEnum;", 3558 Style); 3559 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 3560 Style.BraceWrapping.AfterEnum = true; 3561 verifyFormat("typedef enum {} EmptyEnum;"); 3562 verifyFormat("typedef enum { A, B, C } ShortEnum;"); 3563 verifyFormat("typedef enum\n" 3564 "{\n" 3565 " ZERO = 0,\n" 3566 " ONE = 1,\n" 3567 " TWO = 2,\n" 3568 " THREE = 3\n" 3569 "} LongEnum;", 3570 Style); 3571 } 3572 3573 TEST_F(FormatTest, FormatsNSEnums) { 3574 verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }"); 3575 verifyGoogleFormat( 3576 "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }"); 3577 verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n" 3578 " // Information about someDecentlyLongValue.\n" 3579 " someDecentlyLongValue,\n" 3580 " // Information about anotherDecentlyLongValue.\n" 3581 " anotherDecentlyLongValue,\n" 3582 " // Information about aThirdDecentlyLongValue.\n" 3583 " aThirdDecentlyLongValue\n" 3584 "};"); 3585 verifyGoogleFormat("typedef NS_CLOSED_ENUM(NSInteger, MyType) {\n" 3586 " // Information about someDecentlyLongValue.\n" 3587 " someDecentlyLongValue,\n" 3588 " // Information about anotherDecentlyLongValue.\n" 3589 " anotherDecentlyLongValue,\n" 3590 " // Information about aThirdDecentlyLongValue.\n" 3591 " aThirdDecentlyLongValue\n" 3592 "};"); 3593 verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n" 3594 " a = 1,\n" 3595 " b = 2,\n" 3596 " c = 3,\n" 3597 "};"); 3598 verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n" 3599 " a = 1,\n" 3600 " b = 2,\n" 3601 " c = 3,\n" 3602 "};"); 3603 verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n" 3604 " a = 1,\n" 3605 " b = 2,\n" 3606 " c = 3,\n" 3607 "};"); 3608 verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n" 3609 " a = 1,\n" 3610 " b = 2,\n" 3611 " c = 3,\n" 3612 "};"); 3613 } 3614 3615 TEST_F(FormatTest, FormatsBitfields) { 3616 verifyFormat("struct Bitfields {\n" 3617 " unsigned sClass : 8;\n" 3618 " unsigned ValueKind : 2;\n" 3619 "};"); 3620 verifyFormat("struct A {\n" 3621 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n" 3622 " bbbbbbbbbbbbbbbbbbbbbbbbb;\n" 3623 "};"); 3624 verifyFormat("struct MyStruct {\n" 3625 " uchar data;\n" 3626 " uchar : 8;\n" 3627 " uchar : 8;\n" 3628 " uchar other;\n" 3629 "};"); 3630 FormatStyle Style = getLLVMStyle(); 3631 Style.BitFieldColonSpacing = FormatStyle::BFCS_None; 3632 verifyFormat("struct Bitfields {\n" 3633 " unsigned sClass:8;\n" 3634 " unsigned ValueKind:2;\n" 3635 " uchar other;\n" 3636 "};", 3637 Style); 3638 verifyFormat("struct A {\n" 3639 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:1,\n" 3640 " bbbbbbbbbbbbbbbbbbbbbbbbb:2;\n" 3641 "};", 3642 Style); 3643 Style.BitFieldColonSpacing = FormatStyle::BFCS_Before; 3644 verifyFormat("struct Bitfields {\n" 3645 " unsigned sClass :8;\n" 3646 " unsigned ValueKind :2;\n" 3647 " uchar other;\n" 3648 "};", 3649 Style); 3650 Style.BitFieldColonSpacing = FormatStyle::BFCS_After; 3651 verifyFormat("struct Bitfields {\n" 3652 " unsigned sClass: 8;\n" 3653 " unsigned ValueKind: 2;\n" 3654 " uchar other;\n" 3655 "};", 3656 Style); 3657 } 3658 3659 TEST_F(FormatTest, FormatsNamespaces) { 3660 FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle(); 3661 LLVMWithNoNamespaceFix.FixNamespaceComments = false; 3662 3663 verifyFormat("namespace some_namespace {\n" 3664 "class A {};\n" 3665 "void f() { f(); }\n" 3666 "}", 3667 LLVMWithNoNamespaceFix); 3668 verifyFormat("namespace N::inline D {\n" 3669 "class A {};\n" 3670 "void f() { f(); }\n" 3671 "}", 3672 LLVMWithNoNamespaceFix); 3673 verifyFormat("namespace N::inline D::E {\n" 3674 "class A {};\n" 3675 "void f() { f(); }\n" 3676 "}", 3677 LLVMWithNoNamespaceFix); 3678 verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n" 3679 "class A {};\n" 3680 "void f() { f(); }\n" 3681 "}", 3682 LLVMWithNoNamespaceFix); 3683 verifyFormat("/* something */ namespace some_namespace {\n" 3684 "class A {};\n" 3685 "void f() { f(); }\n" 3686 "}", 3687 LLVMWithNoNamespaceFix); 3688 verifyFormat("namespace {\n" 3689 "class A {};\n" 3690 "void f() { f(); }\n" 3691 "}", 3692 LLVMWithNoNamespaceFix); 3693 verifyFormat("/* something */ namespace {\n" 3694 "class A {};\n" 3695 "void f() { f(); }\n" 3696 "}", 3697 LLVMWithNoNamespaceFix); 3698 verifyFormat("inline namespace X {\n" 3699 "class A {};\n" 3700 "void f() { f(); }\n" 3701 "}", 3702 LLVMWithNoNamespaceFix); 3703 verifyFormat("/* something */ inline namespace X {\n" 3704 "class A {};\n" 3705 "void f() { f(); }\n" 3706 "}", 3707 LLVMWithNoNamespaceFix); 3708 verifyFormat("export namespace X {\n" 3709 "class A {};\n" 3710 "void f() { f(); }\n" 3711 "}", 3712 LLVMWithNoNamespaceFix); 3713 verifyFormat("using namespace some_namespace;\n" 3714 "class A {};\n" 3715 "void f() { f(); }", 3716 LLVMWithNoNamespaceFix); 3717 3718 // This code is more common than we thought; if we 3719 // layout this correctly the semicolon will go into 3720 // its own line, which is undesirable. 3721 verifyFormat("namespace {};", LLVMWithNoNamespaceFix); 3722 verifyFormat("namespace {\n" 3723 "class A {};\n" 3724 "};", 3725 LLVMWithNoNamespaceFix); 3726 3727 verifyFormat("namespace {\n" 3728 "int SomeVariable = 0; // comment\n" 3729 "} // namespace", 3730 LLVMWithNoNamespaceFix); 3731 EXPECT_EQ("#ifndef HEADER_GUARD\n" 3732 "#define HEADER_GUARD\n" 3733 "namespace my_namespace {\n" 3734 "int i;\n" 3735 "} // my_namespace\n" 3736 "#endif // HEADER_GUARD", 3737 format("#ifndef HEADER_GUARD\n" 3738 " #define HEADER_GUARD\n" 3739 " namespace my_namespace {\n" 3740 "int i;\n" 3741 "} // my_namespace\n" 3742 "#endif // HEADER_GUARD", 3743 LLVMWithNoNamespaceFix)); 3744 3745 EXPECT_EQ("namespace A::B {\n" 3746 "class C {};\n" 3747 "}", 3748 format("namespace A::B {\n" 3749 "class C {};\n" 3750 "}", 3751 LLVMWithNoNamespaceFix)); 3752 3753 FormatStyle Style = getLLVMStyle(); 3754 Style.NamespaceIndentation = FormatStyle::NI_All; 3755 EXPECT_EQ("namespace out {\n" 3756 " int i;\n" 3757 " namespace in {\n" 3758 " int i;\n" 3759 " } // namespace in\n" 3760 "} // namespace out", 3761 format("namespace out {\n" 3762 "int i;\n" 3763 "namespace in {\n" 3764 "int i;\n" 3765 "} // namespace in\n" 3766 "} // namespace out", 3767 Style)); 3768 3769 FormatStyle ShortInlineFunctions = getLLVMStyle(); 3770 ShortInlineFunctions.NamespaceIndentation = FormatStyle::NI_All; 3771 ShortInlineFunctions.AllowShortFunctionsOnASingleLine = 3772 FormatStyle::SFS_Inline; 3773 verifyFormat("namespace {\n" 3774 " void f() {\n" 3775 " return;\n" 3776 " }\n" 3777 "} // namespace\n", 3778 ShortInlineFunctions); 3779 verifyFormat("namespace {\n" 3780 " int some_int;\n" 3781 " void f() {\n" 3782 " return;\n" 3783 " }\n" 3784 "} // namespace\n", 3785 ShortInlineFunctions); 3786 verifyFormat("namespace interface {\n" 3787 " void f() {\n" 3788 " return;\n" 3789 " }\n" 3790 "} // namespace interface\n", 3791 ShortInlineFunctions); 3792 verifyFormat("namespace {\n" 3793 " class X {\n" 3794 " void f() { return; }\n" 3795 " };\n" 3796 "} // namespace\n", 3797 ShortInlineFunctions); 3798 verifyFormat("namespace {\n" 3799 " struct X {\n" 3800 " void f() { return; }\n" 3801 " };\n" 3802 "} // namespace\n", 3803 ShortInlineFunctions); 3804 verifyFormat("namespace {\n" 3805 " union X {\n" 3806 " void f() { return; }\n" 3807 " };\n" 3808 "} // namespace\n", 3809 ShortInlineFunctions); 3810 verifyFormat("extern \"C\" {\n" 3811 "void f() {\n" 3812 " return;\n" 3813 "}\n" 3814 "} // namespace\n", 3815 ShortInlineFunctions); 3816 verifyFormat("namespace {\n" 3817 " class X {\n" 3818 " void f() { return; }\n" 3819 " } x;\n" 3820 "} // namespace\n", 3821 ShortInlineFunctions); 3822 verifyFormat("namespace {\n" 3823 " [[nodiscard]] class X {\n" 3824 " void f() { return; }\n" 3825 " };\n" 3826 "} // namespace\n", 3827 ShortInlineFunctions); 3828 verifyFormat("namespace {\n" 3829 " static class X {\n" 3830 " void f() { return; }\n" 3831 " } x;\n" 3832 "} // namespace\n", 3833 ShortInlineFunctions); 3834 verifyFormat("namespace {\n" 3835 " constexpr class X {\n" 3836 " void f() { return; }\n" 3837 " } x;\n" 3838 "} // namespace\n", 3839 ShortInlineFunctions); 3840 3841 ShortInlineFunctions.IndentExternBlock = FormatStyle::IEBS_Indent; 3842 verifyFormat("extern \"C\" {\n" 3843 " void f() {\n" 3844 " return;\n" 3845 " }\n" 3846 "} // namespace\n", 3847 ShortInlineFunctions); 3848 3849 Style.NamespaceIndentation = FormatStyle::NI_Inner; 3850 EXPECT_EQ("namespace out {\n" 3851 "int i;\n" 3852 "namespace in {\n" 3853 " int i;\n" 3854 "} // namespace in\n" 3855 "} // namespace out", 3856 format("namespace out {\n" 3857 "int i;\n" 3858 "namespace in {\n" 3859 "int i;\n" 3860 "} // namespace in\n" 3861 "} // namespace out", 3862 Style)); 3863 3864 Style.NamespaceIndentation = FormatStyle::NI_None; 3865 verifyFormat("template <class T>\n" 3866 "concept a_concept = X<>;\n" 3867 "namespace B {\n" 3868 "struct b_struct {};\n" 3869 "} // namespace B\n", 3870 Style); 3871 verifyFormat("template <int I>\n" 3872 "constexpr void foo()\n" 3873 " requires(I == 42)\n" 3874 "{}\n" 3875 "namespace ns {\n" 3876 "void foo() {}\n" 3877 "} // namespace ns\n", 3878 Style); 3879 } 3880 3881 TEST_F(FormatTest, NamespaceMacros) { 3882 FormatStyle Style = getLLVMStyle(); 3883 Style.NamespaceMacros.push_back("TESTSUITE"); 3884 3885 verifyFormat("TESTSUITE(A) {\n" 3886 "int foo();\n" 3887 "} // TESTSUITE(A)", 3888 Style); 3889 3890 verifyFormat("TESTSUITE(A, B) {\n" 3891 "int foo();\n" 3892 "} // TESTSUITE(A)", 3893 Style); 3894 3895 // Properly indent according to NamespaceIndentation style 3896 Style.NamespaceIndentation = FormatStyle::NI_All; 3897 verifyFormat("TESTSUITE(A) {\n" 3898 " int foo();\n" 3899 "} // TESTSUITE(A)", 3900 Style); 3901 verifyFormat("TESTSUITE(A) {\n" 3902 " namespace B {\n" 3903 " int foo();\n" 3904 " } // namespace B\n" 3905 "} // TESTSUITE(A)", 3906 Style); 3907 verifyFormat("namespace A {\n" 3908 " TESTSUITE(B) {\n" 3909 " int foo();\n" 3910 " } // TESTSUITE(B)\n" 3911 "} // namespace A", 3912 Style); 3913 3914 Style.NamespaceIndentation = FormatStyle::NI_Inner; 3915 verifyFormat("TESTSUITE(A) {\n" 3916 "TESTSUITE(B) {\n" 3917 " int foo();\n" 3918 "} // TESTSUITE(B)\n" 3919 "} // TESTSUITE(A)", 3920 Style); 3921 verifyFormat("TESTSUITE(A) {\n" 3922 "namespace B {\n" 3923 " int foo();\n" 3924 "} // namespace B\n" 3925 "} // TESTSUITE(A)", 3926 Style); 3927 verifyFormat("namespace A {\n" 3928 "TESTSUITE(B) {\n" 3929 " int foo();\n" 3930 "} // TESTSUITE(B)\n" 3931 "} // namespace A", 3932 Style); 3933 3934 // Properly merge namespace-macros blocks in CompactNamespaces mode 3935 Style.NamespaceIndentation = FormatStyle::NI_None; 3936 Style.CompactNamespaces = true; 3937 verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n" 3938 "}} // TESTSUITE(A::B)", 3939 Style); 3940 3941 EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n" 3942 "}} // TESTSUITE(out::in)", 3943 format("TESTSUITE(out) {\n" 3944 "TESTSUITE(in) {\n" 3945 "} // TESTSUITE(in)\n" 3946 "} // TESTSUITE(out)", 3947 Style)); 3948 3949 EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n" 3950 "}} // TESTSUITE(out::in)", 3951 format("TESTSUITE(out) {\n" 3952 "TESTSUITE(in) {\n" 3953 "} // TESTSUITE(in)\n" 3954 "} // TESTSUITE(out)", 3955 Style)); 3956 3957 // Do not merge different namespaces/macros 3958 EXPECT_EQ("namespace out {\n" 3959 "TESTSUITE(in) {\n" 3960 "} // TESTSUITE(in)\n" 3961 "} // namespace out", 3962 format("namespace out {\n" 3963 "TESTSUITE(in) {\n" 3964 "} // TESTSUITE(in)\n" 3965 "} // namespace out", 3966 Style)); 3967 EXPECT_EQ("TESTSUITE(out) {\n" 3968 "namespace in {\n" 3969 "} // namespace in\n" 3970 "} // TESTSUITE(out)", 3971 format("TESTSUITE(out) {\n" 3972 "namespace in {\n" 3973 "} // namespace in\n" 3974 "} // TESTSUITE(out)", 3975 Style)); 3976 Style.NamespaceMacros.push_back("FOOBAR"); 3977 EXPECT_EQ("TESTSUITE(out) {\n" 3978 "FOOBAR(in) {\n" 3979 "} // FOOBAR(in)\n" 3980 "} // TESTSUITE(out)", 3981 format("TESTSUITE(out) {\n" 3982 "FOOBAR(in) {\n" 3983 "} // FOOBAR(in)\n" 3984 "} // TESTSUITE(out)", 3985 Style)); 3986 } 3987 3988 TEST_F(FormatTest, FormatsCompactNamespaces) { 3989 FormatStyle Style = getLLVMStyle(); 3990 Style.CompactNamespaces = true; 3991 Style.NamespaceMacros.push_back("TESTSUITE"); 3992 3993 verifyFormat("namespace A { namespace B {\n" 3994 "}} // namespace A::B", 3995 Style); 3996 3997 EXPECT_EQ("namespace out { namespace in {\n" 3998 "}} // namespace out::in", 3999 format("namespace out {\n" 4000 "namespace in {\n" 4001 "} // namespace in\n" 4002 "} // namespace out", 4003 Style)); 4004 4005 // Only namespaces which have both consecutive opening and end get compacted 4006 EXPECT_EQ("namespace out {\n" 4007 "namespace in1 {\n" 4008 "} // namespace in1\n" 4009 "namespace in2 {\n" 4010 "} // namespace in2\n" 4011 "} // namespace out", 4012 format("namespace out {\n" 4013 "namespace in1 {\n" 4014 "} // namespace in1\n" 4015 "namespace in2 {\n" 4016 "} // namespace in2\n" 4017 "} // namespace out", 4018 Style)); 4019 4020 EXPECT_EQ("namespace out {\n" 4021 "int i;\n" 4022 "namespace in {\n" 4023 "int j;\n" 4024 "} // namespace in\n" 4025 "int k;\n" 4026 "} // namespace out", 4027 format("namespace out { int i;\n" 4028 "namespace in { int j; } // namespace in\n" 4029 "int k; } // namespace out", 4030 Style)); 4031 4032 EXPECT_EQ("namespace A { namespace B { namespace C {\n" 4033 "}}} // namespace A::B::C\n", 4034 format("namespace A { namespace B {\n" 4035 "namespace C {\n" 4036 "}} // namespace B::C\n" 4037 "} // namespace A\n", 4038 Style)); 4039 4040 Style.ColumnLimit = 40; 4041 EXPECT_EQ("namespace aaaaaaaaaa {\n" 4042 "namespace bbbbbbbbbb {\n" 4043 "}} // namespace aaaaaaaaaa::bbbbbbbbbb", 4044 format("namespace aaaaaaaaaa {\n" 4045 "namespace bbbbbbbbbb {\n" 4046 "} // namespace bbbbbbbbbb\n" 4047 "} // namespace aaaaaaaaaa", 4048 Style)); 4049 4050 EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n" 4051 "namespace cccccc {\n" 4052 "}}} // namespace aaaaaa::bbbbbb::cccccc", 4053 format("namespace aaaaaa {\n" 4054 "namespace bbbbbb {\n" 4055 "namespace cccccc {\n" 4056 "} // namespace cccccc\n" 4057 "} // namespace bbbbbb\n" 4058 "} // namespace aaaaaa", 4059 Style)); 4060 Style.ColumnLimit = 80; 4061 4062 // Extra semicolon after 'inner' closing brace prevents merging 4063 EXPECT_EQ("namespace out { namespace in {\n" 4064 "}; } // namespace out::in", 4065 format("namespace out {\n" 4066 "namespace in {\n" 4067 "}; // namespace in\n" 4068 "} // namespace out", 4069 Style)); 4070 4071 // Extra semicolon after 'outer' closing brace is conserved 4072 EXPECT_EQ("namespace out { namespace in {\n" 4073 "}}; // namespace out::in", 4074 format("namespace out {\n" 4075 "namespace in {\n" 4076 "} // namespace in\n" 4077 "}; // namespace out", 4078 Style)); 4079 4080 Style.NamespaceIndentation = FormatStyle::NI_All; 4081 EXPECT_EQ("namespace out { namespace in {\n" 4082 " int i;\n" 4083 "}} // namespace out::in", 4084 format("namespace out {\n" 4085 "namespace in {\n" 4086 "int i;\n" 4087 "} // namespace in\n" 4088 "} // namespace out", 4089 Style)); 4090 EXPECT_EQ("namespace out { namespace mid {\n" 4091 " namespace in {\n" 4092 " int j;\n" 4093 " } // namespace in\n" 4094 " int k;\n" 4095 "}} // namespace out::mid", 4096 format("namespace out { namespace mid {\n" 4097 "namespace in { int j; } // namespace in\n" 4098 "int k; }} // namespace out::mid", 4099 Style)); 4100 4101 Style.NamespaceIndentation = FormatStyle::NI_Inner; 4102 EXPECT_EQ("namespace out { namespace in {\n" 4103 " int i;\n" 4104 "}} // namespace out::in", 4105 format("namespace out {\n" 4106 "namespace in {\n" 4107 "int i;\n" 4108 "} // namespace in\n" 4109 "} // namespace out", 4110 Style)); 4111 EXPECT_EQ("namespace out { namespace mid { namespace in {\n" 4112 " int i;\n" 4113 "}}} // namespace out::mid::in", 4114 format("namespace out {\n" 4115 "namespace mid {\n" 4116 "namespace in {\n" 4117 "int i;\n" 4118 "} // namespace in\n" 4119 "} // namespace mid\n" 4120 "} // namespace out", 4121 Style)); 4122 4123 Style.CompactNamespaces = true; 4124 Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 4125 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4126 Style.BraceWrapping.BeforeLambdaBody = true; 4127 verifyFormat("namespace out { namespace in {\n" 4128 "}} // namespace out::in", 4129 Style); 4130 EXPECT_EQ("namespace out { namespace in {\n" 4131 "}} // namespace out::in", 4132 format("namespace out {\n" 4133 "namespace in {\n" 4134 "} // namespace in\n" 4135 "} // namespace out", 4136 Style)); 4137 } 4138 4139 TEST_F(FormatTest, FormatsExternC) { 4140 verifyFormat("extern \"C\" {\nint a;"); 4141 verifyFormat("extern \"C\" {}"); 4142 verifyFormat("extern \"C\" {\n" 4143 "int foo();\n" 4144 "}"); 4145 verifyFormat("extern \"C\" int foo() {}"); 4146 verifyFormat("extern \"C\" int foo();"); 4147 verifyFormat("extern \"C\" int foo() {\n" 4148 " int i = 42;\n" 4149 " return i;\n" 4150 "}"); 4151 4152 FormatStyle Style = getLLVMStyle(); 4153 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4154 Style.BraceWrapping.AfterFunction = true; 4155 verifyFormat("extern \"C\" int foo() {}", Style); 4156 verifyFormat("extern \"C\" int foo();", Style); 4157 verifyFormat("extern \"C\" int foo()\n" 4158 "{\n" 4159 " int i = 42;\n" 4160 " return i;\n" 4161 "}", 4162 Style); 4163 4164 Style.BraceWrapping.AfterExternBlock = true; 4165 Style.BraceWrapping.SplitEmptyRecord = false; 4166 verifyFormat("extern \"C\"\n" 4167 "{}", 4168 Style); 4169 verifyFormat("extern \"C\"\n" 4170 "{\n" 4171 " int foo();\n" 4172 "}", 4173 Style); 4174 } 4175 4176 TEST_F(FormatTest, IndentExternBlockStyle) { 4177 FormatStyle Style = getLLVMStyle(); 4178 Style.IndentWidth = 2; 4179 4180 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4181 verifyFormat("extern \"C\" { /*9*/\n" 4182 "}", 4183 Style); 4184 verifyFormat("extern \"C\" {\n" 4185 " int foo10();\n" 4186 "}", 4187 Style); 4188 4189 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 4190 verifyFormat("extern \"C\" { /*11*/\n" 4191 "}", 4192 Style); 4193 verifyFormat("extern \"C\" {\n" 4194 "int foo12();\n" 4195 "}", 4196 Style); 4197 4198 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4199 Style.BraceWrapping.AfterExternBlock = true; 4200 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4201 verifyFormat("extern \"C\"\n" 4202 "{ /*13*/\n" 4203 "}", 4204 Style); 4205 verifyFormat("extern \"C\"\n{\n" 4206 " int foo14();\n" 4207 "}", 4208 Style); 4209 4210 Style.BraceWrapping.AfterExternBlock = false; 4211 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 4212 verifyFormat("extern \"C\" { /*15*/\n" 4213 "}", 4214 Style); 4215 verifyFormat("extern \"C\" {\n" 4216 "int foo16();\n" 4217 "}", 4218 Style); 4219 4220 Style.BraceWrapping.AfterExternBlock = true; 4221 verifyFormat("extern \"C\"\n" 4222 "{ /*13*/\n" 4223 "}", 4224 Style); 4225 verifyFormat("extern \"C\"\n" 4226 "{\n" 4227 "int foo14();\n" 4228 "}", 4229 Style); 4230 4231 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4232 verifyFormat("extern \"C\"\n" 4233 "{ /*13*/\n" 4234 "}", 4235 Style); 4236 verifyFormat("extern \"C\"\n" 4237 "{\n" 4238 " int foo14();\n" 4239 "}", 4240 Style); 4241 } 4242 4243 TEST_F(FormatTest, FormatsInlineASM) { 4244 verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));"); 4245 verifyFormat("asm(\"nop\" ::: \"memory\");"); 4246 verifyFormat( 4247 "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n" 4248 " \"cpuid\\n\\t\"\n" 4249 " \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n" 4250 " : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n" 4251 " : \"a\"(value));"); 4252 EXPECT_EQ( 4253 "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n" 4254 " __asm {\n" 4255 " mov edx,[that] // vtable in edx\n" 4256 " mov eax,methodIndex\n" 4257 " call [edx][eax*4] // stdcall\n" 4258 " }\n" 4259 "}", 4260 format("void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n" 4261 " __asm {\n" 4262 " mov edx,[that] // vtable in edx\n" 4263 " mov eax,methodIndex\n" 4264 " call [edx][eax*4] // stdcall\n" 4265 " }\n" 4266 "}")); 4267 EXPECT_EQ("_asm {\n" 4268 " xor eax, eax;\n" 4269 " cpuid;\n" 4270 "}", 4271 format("_asm {\n" 4272 " xor eax, eax;\n" 4273 " cpuid;\n" 4274 "}")); 4275 verifyFormat("void function() {\n" 4276 " // comment\n" 4277 " asm(\"\");\n" 4278 "}"); 4279 EXPECT_EQ("__asm {\n" 4280 "}\n" 4281 "int i;", 4282 format("__asm {\n" 4283 "}\n" 4284 "int i;")); 4285 } 4286 4287 TEST_F(FormatTest, FormatTryCatch) { 4288 verifyFormat("try {\n" 4289 " throw a * b;\n" 4290 "} catch (int a) {\n" 4291 " // Do nothing.\n" 4292 "} catch (...) {\n" 4293 " exit(42);\n" 4294 "}"); 4295 4296 // Function-level try statements. 4297 verifyFormat("int f() try { return 4; } catch (...) {\n" 4298 " return 5;\n" 4299 "}"); 4300 verifyFormat("class A {\n" 4301 " int a;\n" 4302 " A() try : a(0) {\n" 4303 " } catch (...) {\n" 4304 " throw;\n" 4305 " }\n" 4306 "};\n"); 4307 verifyFormat("class A {\n" 4308 " int a;\n" 4309 " A() try : a(0), b{1} {\n" 4310 " } catch (...) {\n" 4311 " throw;\n" 4312 " }\n" 4313 "};\n"); 4314 verifyFormat("class A {\n" 4315 " int a;\n" 4316 " A() try : a(0), b{1}, c{2} {\n" 4317 " } catch (...) {\n" 4318 " throw;\n" 4319 " }\n" 4320 "};\n"); 4321 verifyFormat("class A {\n" 4322 " int a;\n" 4323 " A() try : a(0), b{1}, c{2} {\n" 4324 " { // New scope.\n" 4325 " }\n" 4326 " } catch (...) {\n" 4327 " throw;\n" 4328 " }\n" 4329 "};\n"); 4330 4331 // Incomplete try-catch blocks. 4332 verifyIncompleteFormat("try {} catch ("); 4333 } 4334 4335 TEST_F(FormatTest, FormatTryAsAVariable) { 4336 verifyFormat("int try;"); 4337 verifyFormat("int try, size;"); 4338 verifyFormat("try = foo();"); 4339 verifyFormat("if (try < size) {\n return true;\n}"); 4340 4341 verifyFormat("int catch;"); 4342 verifyFormat("int catch, size;"); 4343 verifyFormat("catch = foo();"); 4344 verifyFormat("if (catch < size) {\n return true;\n}"); 4345 4346 FormatStyle Style = getLLVMStyle(); 4347 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4348 Style.BraceWrapping.AfterFunction = true; 4349 Style.BraceWrapping.BeforeCatch = true; 4350 verifyFormat("try {\n" 4351 " int bar = 1;\n" 4352 "}\n" 4353 "catch (...) {\n" 4354 " int bar = 1;\n" 4355 "}", 4356 Style); 4357 verifyFormat("#if NO_EX\n" 4358 "try\n" 4359 "#endif\n" 4360 "{\n" 4361 "}\n" 4362 "#if NO_EX\n" 4363 "catch (...) {\n" 4364 "}", 4365 Style); 4366 verifyFormat("try /* abc */ {\n" 4367 " int bar = 1;\n" 4368 "}\n" 4369 "catch (...) {\n" 4370 " int bar = 1;\n" 4371 "}", 4372 Style); 4373 verifyFormat("try\n" 4374 "// abc\n" 4375 "{\n" 4376 " int bar = 1;\n" 4377 "}\n" 4378 "catch (...) {\n" 4379 " int bar = 1;\n" 4380 "}", 4381 Style); 4382 } 4383 4384 TEST_F(FormatTest, FormatSEHTryCatch) { 4385 verifyFormat("__try {\n" 4386 " int a = b * c;\n" 4387 "} __except (EXCEPTION_EXECUTE_HANDLER) {\n" 4388 " // Do nothing.\n" 4389 "}"); 4390 4391 verifyFormat("__try {\n" 4392 " int a = b * c;\n" 4393 "} __finally {\n" 4394 " // Do nothing.\n" 4395 "}"); 4396 4397 verifyFormat("DEBUG({\n" 4398 " __try {\n" 4399 " } __finally {\n" 4400 " }\n" 4401 "});\n"); 4402 } 4403 4404 TEST_F(FormatTest, IncompleteTryCatchBlocks) { 4405 verifyFormat("try {\n" 4406 " f();\n" 4407 "} catch {\n" 4408 " g();\n" 4409 "}"); 4410 verifyFormat("try {\n" 4411 " f();\n" 4412 "} catch (A a) MACRO(x) {\n" 4413 " g();\n" 4414 "} catch (B b) MACRO(x) {\n" 4415 " g();\n" 4416 "}"); 4417 } 4418 4419 TEST_F(FormatTest, FormatTryCatchBraceStyles) { 4420 FormatStyle Style = getLLVMStyle(); 4421 for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla, 4422 FormatStyle::BS_WebKit}) { 4423 Style.BreakBeforeBraces = BraceStyle; 4424 verifyFormat("try {\n" 4425 " // something\n" 4426 "} catch (...) {\n" 4427 " // something\n" 4428 "}", 4429 Style); 4430 } 4431 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 4432 verifyFormat("try {\n" 4433 " // something\n" 4434 "}\n" 4435 "catch (...) {\n" 4436 " // something\n" 4437 "}", 4438 Style); 4439 verifyFormat("__try {\n" 4440 " // something\n" 4441 "}\n" 4442 "__finally {\n" 4443 " // something\n" 4444 "}", 4445 Style); 4446 verifyFormat("@try {\n" 4447 " // something\n" 4448 "}\n" 4449 "@finally {\n" 4450 " // something\n" 4451 "}", 4452 Style); 4453 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 4454 verifyFormat("try\n" 4455 "{\n" 4456 " // something\n" 4457 "}\n" 4458 "catch (...)\n" 4459 "{\n" 4460 " // something\n" 4461 "}", 4462 Style); 4463 Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 4464 verifyFormat("try\n" 4465 " {\n" 4466 " // something white\n" 4467 " }\n" 4468 "catch (...)\n" 4469 " {\n" 4470 " // something white\n" 4471 " }", 4472 Style); 4473 Style.BreakBeforeBraces = FormatStyle::BS_GNU; 4474 verifyFormat("try\n" 4475 " {\n" 4476 " // something\n" 4477 " }\n" 4478 "catch (...)\n" 4479 " {\n" 4480 " // something\n" 4481 " }", 4482 Style); 4483 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4484 Style.BraceWrapping.BeforeCatch = true; 4485 verifyFormat("try {\n" 4486 " // something\n" 4487 "}\n" 4488 "catch (...) {\n" 4489 " // something\n" 4490 "}", 4491 Style); 4492 } 4493 4494 TEST_F(FormatTest, StaticInitializers) { 4495 verifyFormat("static SomeClass SC = {1, 'a'};"); 4496 4497 verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n" 4498 " 100000000, " 4499 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};"); 4500 4501 // Here, everything other than the "}" would fit on a line. 4502 verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n" 4503 " 10000000000000000000000000};"); 4504 EXPECT_EQ("S s = {a,\n" 4505 "\n" 4506 " b};", 4507 format("S s = {\n" 4508 " a,\n" 4509 "\n" 4510 " b\n" 4511 "};")); 4512 4513 // FIXME: This would fit into the column limit if we'd fit "{ {" on the first 4514 // line. However, the formatting looks a bit off and this probably doesn't 4515 // happen often in practice. 4516 verifyFormat("static int Variable[1] = {\n" 4517 " {1000000000000000000000000000000000000}};", 4518 getLLVMStyleWithColumns(40)); 4519 } 4520 4521 TEST_F(FormatTest, DesignatedInitializers) { 4522 verifyFormat("const struct A a = {.a = 1, .b = 2};"); 4523 verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n" 4524 " .bbbbbbbbbb = 2,\n" 4525 " .cccccccccc = 3,\n" 4526 " .dddddddddd = 4,\n" 4527 " .eeeeeeeeee = 5};"); 4528 verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n" 4529 " .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n" 4530 " .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n" 4531 " .ccccccccccccccccccccccccccc = 3,\n" 4532 " .ddddddddddddddddddddddddddd = 4,\n" 4533 " .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};"); 4534 4535 verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};"); 4536 4537 verifyFormat("const struct A a = {[0] = 1, [1] = 2};"); 4538 verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n" 4539 " [2] = bbbbbbbbbb,\n" 4540 " [3] = cccccccccc,\n" 4541 " [4] = dddddddddd,\n" 4542 " [5] = eeeeeeeeee};"); 4543 verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n" 4544 " [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 4545 " [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 4546 " [3] = cccccccccccccccccccccccccccccccccccccc,\n" 4547 " [4] = dddddddddddddddddddddddddddddddddddddd,\n" 4548 " [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};"); 4549 } 4550 4551 TEST_F(FormatTest, NestedStaticInitializers) { 4552 verifyFormat("static A x = {{{}}};\n"); 4553 verifyFormat("static A x = {{{init1, init2, init3, init4},\n" 4554 " {init1, init2, init3, init4}}};", 4555 getLLVMStyleWithColumns(50)); 4556 4557 verifyFormat("somes Status::global_reps[3] = {\n" 4558 " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n" 4559 " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n" 4560 " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};", 4561 getLLVMStyleWithColumns(60)); 4562 verifyGoogleFormat("SomeType Status::global_reps[3] = {\n" 4563 " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n" 4564 " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n" 4565 " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};"); 4566 verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n" 4567 " {rect.fRight - rect.fLeft, rect.fBottom - " 4568 "rect.fTop}};"); 4569 4570 verifyFormat( 4571 "SomeArrayOfSomeType a = {\n" 4572 " {{1, 2, 3},\n" 4573 " {1, 2, 3},\n" 4574 " {111111111111111111111111111111, 222222222222222222222222222222,\n" 4575 " 333333333333333333333333333333},\n" 4576 " {1, 2, 3},\n" 4577 " {1, 2, 3}}};"); 4578 verifyFormat( 4579 "SomeArrayOfSomeType a = {\n" 4580 " {{1, 2, 3}},\n" 4581 " {{1, 2, 3}},\n" 4582 " {{111111111111111111111111111111, 222222222222222222222222222222,\n" 4583 " 333333333333333333333333333333}},\n" 4584 " {{1, 2, 3}},\n" 4585 " {{1, 2, 3}}};"); 4586 4587 verifyFormat("struct {\n" 4588 " unsigned bit;\n" 4589 " const char *const name;\n" 4590 "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n" 4591 " {kOsWin, \"Windows\"},\n" 4592 " {kOsLinux, \"Linux\"},\n" 4593 " {kOsCrOS, \"Chrome OS\"}};"); 4594 verifyFormat("struct {\n" 4595 " unsigned bit;\n" 4596 " const char *const name;\n" 4597 "} kBitsToOs[] = {\n" 4598 " {kOsMac, \"Mac\"},\n" 4599 " {kOsWin, \"Windows\"},\n" 4600 " {kOsLinux, \"Linux\"},\n" 4601 " {kOsCrOS, \"Chrome OS\"},\n" 4602 "};"); 4603 } 4604 4605 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) { 4606 verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro(" 4607 " \\\n" 4608 " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)"); 4609 } 4610 4611 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) { 4612 verifyFormat("virtual void write(ELFWriter *writerrr,\n" 4613 " OwningPtr<FileOutputBuffer> &buffer) = 0;"); 4614 4615 // Do break defaulted and deleted functions. 4616 verifyFormat("virtual void ~Deeeeeeeestructor() =\n" 4617 " default;", 4618 getLLVMStyleWithColumns(40)); 4619 verifyFormat("virtual void ~Deeeeeeeestructor() =\n" 4620 " delete;", 4621 getLLVMStyleWithColumns(40)); 4622 } 4623 4624 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) { 4625 verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3", 4626 getLLVMStyleWithColumns(40)); 4627 verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"", 4628 getLLVMStyleWithColumns(40)); 4629 EXPECT_EQ("#define Q \\\n" 4630 " \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\" \\\n" 4631 " \"aaaaaaaa.cpp\"", 4632 format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"", 4633 getLLVMStyleWithColumns(40))); 4634 } 4635 4636 TEST_F(FormatTest, UnderstandsLinePPDirective) { 4637 EXPECT_EQ("# 123 \"A string literal\"", 4638 format(" # 123 \"A string literal\"")); 4639 } 4640 4641 TEST_F(FormatTest, LayoutUnknownPPDirective) { 4642 EXPECT_EQ("#;", format("#;")); 4643 verifyFormat("#\n;\n;\n;"); 4644 } 4645 4646 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) { 4647 EXPECT_EQ("#line 42 \"test\"\n", 4648 format("# \\\n line \\\n 42 \\\n \"test\"\n")); 4649 EXPECT_EQ("#define A B\n", format("# \\\n define \\\n A \\\n B\n", 4650 getLLVMStyleWithColumns(12))); 4651 } 4652 4653 TEST_F(FormatTest, EndOfFileEndsPPDirective) { 4654 EXPECT_EQ("#line 42 \"test\"", 4655 format("# \\\n line \\\n 42 \\\n \"test\"")); 4656 EXPECT_EQ("#define A B", format("# \\\n define \\\n A \\\n B")); 4657 } 4658 4659 TEST_F(FormatTest, DoesntRemoveUnknownTokens) { 4660 verifyFormat("#define A \\x20"); 4661 verifyFormat("#define A \\ x20"); 4662 EXPECT_EQ("#define A \\ x20", format("#define A \\ x20")); 4663 verifyFormat("#define A ''"); 4664 verifyFormat("#define A ''qqq"); 4665 verifyFormat("#define A `qqq"); 4666 verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");"); 4667 EXPECT_EQ("const char *c = STRINGIFY(\n" 4668 "\\na : b);", 4669 format("const char * c = STRINGIFY(\n" 4670 "\\na : b);")); 4671 4672 verifyFormat("a\r\\"); 4673 verifyFormat("a\v\\"); 4674 verifyFormat("a\f\\"); 4675 } 4676 4677 TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) { 4678 FormatStyle style = getChromiumStyle(FormatStyle::LK_Cpp); 4679 style.IndentWidth = 4; 4680 style.PPIndentWidth = 1; 4681 4682 style.IndentPPDirectives = FormatStyle::PPDIS_None; 4683 verifyFormat("#ifdef __linux__\n" 4684 "void foo() {\n" 4685 " int x = 0;\n" 4686 "}\n" 4687 "#define FOO\n" 4688 "#endif\n" 4689 "void bar() {\n" 4690 " int y = 0;\n" 4691 "}\n", 4692 style); 4693 4694 style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash; 4695 verifyFormat("#ifdef __linux__\n" 4696 "void foo() {\n" 4697 " int x = 0;\n" 4698 "}\n" 4699 "# define FOO foo\n" 4700 "#endif\n" 4701 "void bar() {\n" 4702 " int y = 0;\n" 4703 "}\n", 4704 style); 4705 4706 style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash; 4707 verifyFormat("#ifdef __linux__\n" 4708 "void foo() {\n" 4709 " int x = 0;\n" 4710 "}\n" 4711 " #define FOO foo\n" 4712 "#endif\n" 4713 "void bar() {\n" 4714 " int y = 0;\n" 4715 "}\n", 4716 style); 4717 } 4718 4719 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) { 4720 verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13)); 4721 verifyFormat("#define A( \\\n BB)", getLLVMStyleWithColumns(12)); 4722 verifyFormat("#define A( \\\n A, B)", getLLVMStyleWithColumns(12)); 4723 // FIXME: We never break before the macro name. 4724 verifyFormat("#define AA( \\\n B)", getLLVMStyleWithColumns(12)); 4725 4726 verifyFormat("#define A A\n#define A A"); 4727 verifyFormat("#define A(X) A\n#define A A"); 4728 4729 verifyFormat("#define Something Other", getLLVMStyleWithColumns(23)); 4730 verifyFormat("#define Something \\\n Other", getLLVMStyleWithColumns(22)); 4731 } 4732 4733 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) { 4734 EXPECT_EQ("// somecomment\n" 4735 "#include \"a.h\"\n" 4736 "#define A( \\\n" 4737 " A, B)\n" 4738 "#include \"b.h\"\n" 4739 "// somecomment\n", 4740 format(" // somecomment\n" 4741 " #include \"a.h\"\n" 4742 "#define A(A,\\\n" 4743 " B)\n" 4744 " #include \"b.h\"\n" 4745 " // somecomment\n", 4746 getLLVMStyleWithColumns(13))); 4747 } 4748 4749 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); } 4750 4751 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) { 4752 EXPECT_EQ("#define A \\\n" 4753 " c; \\\n" 4754 " e;\n" 4755 "f;", 4756 format("#define A c; e;\n" 4757 "f;", 4758 getLLVMStyleWithColumns(14))); 4759 } 4760 4761 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); } 4762 4763 TEST_F(FormatTest, MacroDefinitionInsideStatement) { 4764 EXPECT_EQ("int x,\n" 4765 "#define A\n" 4766 " y;", 4767 format("int x,\n#define A\ny;")); 4768 } 4769 4770 TEST_F(FormatTest, HashInMacroDefinition) { 4771 EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle())); 4772 EXPECT_EQ("#define A(c) u#c", format("#define A(c) u#c", getLLVMStyle())); 4773 EXPECT_EQ("#define A(c) U#c", format("#define A(c) U#c", getLLVMStyle())); 4774 EXPECT_EQ("#define A(c) u8#c", format("#define A(c) u8#c", getLLVMStyle())); 4775 EXPECT_EQ("#define A(c) LR#c", format("#define A(c) LR#c", getLLVMStyle())); 4776 EXPECT_EQ("#define A(c) uR#c", format("#define A(c) uR#c", getLLVMStyle())); 4777 EXPECT_EQ("#define A(c) UR#c", format("#define A(c) UR#c", getLLVMStyle())); 4778 EXPECT_EQ("#define A(c) u8R#c", format("#define A(c) u8R#c", getLLVMStyle())); 4779 verifyFormat("#define A \\\n b #c;", getLLVMStyleWithColumns(11)); 4780 verifyFormat("#define A \\\n" 4781 " { \\\n" 4782 " f(#c); \\\n" 4783 " }", 4784 getLLVMStyleWithColumns(11)); 4785 4786 verifyFormat("#define A(X) \\\n" 4787 " void function##X()", 4788 getLLVMStyleWithColumns(22)); 4789 4790 verifyFormat("#define A(a, b, c) \\\n" 4791 " void a##b##c()", 4792 getLLVMStyleWithColumns(22)); 4793 4794 verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22)); 4795 } 4796 4797 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) { 4798 EXPECT_EQ("#define A (x)", format("#define A (x)")); 4799 EXPECT_EQ("#define A(x)", format("#define A(x)")); 4800 4801 FormatStyle Style = getLLVMStyle(); 4802 Style.SpaceBeforeParens = FormatStyle::SBPO_Never; 4803 verifyFormat("#define true ((foo)1)", Style); 4804 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 4805 verifyFormat("#define false((foo)0)", Style); 4806 } 4807 4808 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) { 4809 EXPECT_EQ("#define A b;", format("#define A \\\n" 4810 " \\\n" 4811 " b;", 4812 getLLVMStyleWithColumns(25))); 4813 EXPECT_EQ("#define A \\\n" 4814 " \\\n" 4815 " a; \\\n" 4816 " b;", 4817 format("#define A \\\n" 4818 " \\\n" 4819 " a; \\\n" 4820 " b;", 4821 getLLVMStyleWithColumns(11))); 4822 EXPECT_EQ("#define A \\\n" 4823 " a; \\\n" 4824 " \\\n" 4825 " b;", 4826 format("#define A \\\n" 4827 " a; \\\n" 4828 " \\\n" 4829 " b;", 4830 getLLVMStyleWithColumns(11))); 4831 } 4832 4833 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) { 4834 verifyIncompleteFormat("#define A :"); 4835 verifyFormat("#define SOMECASES \\\n" 4836 " case 1: \\\n" 4837 " case 2\n", 4838 getLLVMStyleWithColumns(20)); 4839 verifyFormat("#define MACRO(a) \\\n" 4840 " if (a) \\\n" 4841 " f(); \\\n" 4842 " else \\\n" 4843 " g()", 4844 getLLVMStyleWithColumns(18)); 4845 verifyFormat("#define A template <typename T>"); 4846 verifyIncompleteFormat("#define STR(x) #x\n" 4847 "f(STR(this_is_a_string_literal{));"); 4848 verifyFormat("#pragma omp threadprivate( \\\n" 4849 " y)), // expected-warning", 4850 getLLVMStyleWithColumns(28)); 4851 verifyFormat("#d, = };"); 4852 verifyFormat("#if \"a"); 4853 verifyIncompleteFormat("({\n" 4854 "#define b \\\n" 4855 " } \\\n" 4856 " a\n" 4857 "a", 4858 getLLVMStyleWithColumns(15)); 4859 verifyFormat("#define A \\\n" 4860 " { \\\n" 4861 " {\n" 4862 "#define B \\\n" 4863 " } \\\n" 4864 " }", 4865 getLLVMStyleWithColumns(15)); 4866 verifyNoCrash("#if a\na(\n#else\n#endif\n{a"); 4867 verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}"); 4868 verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};"); 4869 verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() { \n)}"); 4870 } 4871 4872 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) { 4873 verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline. 4874 EXPECT_EQ("class A : public QObject {\n" 4875 " Q_OBJECT\n" 4876 "\n" 4877 " A() {}\n" 4878 "};", 4879 format("class A : public QObject {\n" 4880 " Q_OBJECT\n" 4881 "\n" 4882 " A() {\n}\n" 4883 "} ;")); 4884 EXPECT_EQ("MACRO\n" 4885 "/*static*/ int i;", 4886 format("MACRO\n" 4887 " /*static*/ int i;")); 4888 EXPECT_EQ("SOME_MACRO\n" 4889 "namespace {\n" 4890 "void f();\n" 4891 "} // namespace", 4892 format("SOME_MACRO\n" 4893 " namespace {\n" 4894 "void f( );\n" 4895 "} // namespace")); 4896 // Only if the identifier contains at least 5 characters. 4897 EXPECT_EQ("HTTP f();", format("HTTP\nf();")); 4898 EXPECT_EQ("MACRO\nf();", format("MACRO\nf();")); 4899 // Only if everything is upper case. 4900 EXPECT_EQ("class A : public QObject {\n" 4901 " Q_Object A() {}\n" 4902 "};", 4903 format("class A : public QObject {\n" 4904 " Q_Object\n" 4905 " A() {\n}\n" 4906 "} ;")); 4907 4908 // Only if the next line can actually start an unwrapped line. 4909 EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;", 4910 format("SOME_WEIRD_LOG_MACRO\n" 4911 "<< SomeThing;")); 4912 4913 verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), " 4914 "(n, buffers))\n", 4915 getChromiumStyle(FormatStyle::LK_Cpp)); 4916 4917 // See PR41483 4918 EXPECT_EQ("/**/ FOO(a)\n" 4919 "FOO(b)", 4920 format("/**/ FOO(a)\n" 4921 "FOO(b)")); 4922 } 4923 4924 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) { 4925 EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n" 4926 "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n" 4927 "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n" 4928 "class X {};\n" 4929 "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n" 4930 "int *createScopDetectionPass() { return 0; }", 4931 format(" INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n" 4932 " INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n" 4933 " INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n" 4934 " class X {};\n" 4935 " INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n" 4936 " int *createScopDetectionPass() { return 0; }")); 4937 // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as 4938 // braces, so that inner block is indented one level more. 4939 EXPECT_EQ("int q() {\n" 4940 " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n" 4941 " IPC_MESSAGE_HANDLER(xxx, qqq)\n" 4942 " IPC_END_MESSAGE_MAP()\n" 4943 "}", 4944 format("int q() {\n" 4945 " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n" 4946 " IPC_MESSAGE_HANDLER(xxx, qqq)\n" 4947 " IPC_END_MESSAGE_MAP()\n" 4948 "}")); 4949 4950 // Same inside macros. 4951 EXPECT_EQ("#define LIST(L) \\\n" 4952 " L(A) \\\n" 4953 " L(B) \\\n" 4954 " L(C)", 4955 format("#define LIST(L) \\\n" 4956 " L(A) \\\n" 4957 " L(B) \\\n" 4958 " L(C)", 4959 getGoogleStyle())); 4960 4961 // These must not be recognized as macros. 4962 EXPECT_EQ("int q() {\n" 4963 " f(x);\n" 4964 " f(x) {}\n" 4965 " f(x)->g();\n" 4966 " f(x)->*g();\n" 4967 " f(x).g();\n" 4968 " f(x) = x;\n" 4969 " f(x) += x;\n" 4970 " f(x) -= x;\n" 4971 " f(x) *= x;\n" 4972 " f(x) /= x;\n" 4973 " f(x) %= x;\n" 4974 " f(x) &= x;\n" 4975 " f(x) |= x;\n" 4976 " f(x) ^= x;\n" 4977 " f(x) >>= x;\n" 4978 " f(x) <<= x;\n" 4979 " f(x)[y].z();\n" 4980 " LOG(INFO) << x;\n" 4981 " ifstream(x) >> x;\n" 4982 "}\n", 4983 format("int q() {\n" 4984 " f(x)\n;\n" 4985 " f(x)\n {}\n" 4986 " f(x)\n->g();\n" 4987 " f(x)\n->*g();\n" 4988 " f(x)\n.g();\n" 4989 " f(x)\n = x;\n" 4990 " f(x)\n += x;\n" 4991 " f(x)\n -= x;\n" 4992 " f(x)\n *= x;\n" 4993 " f(x)\n /= x;\n" 4994 " f(x)\n %= x;\n" 4995 " f(x)\n &= x;\n" 4996 " f(x)\n |= x;\n" 4997 " f(x)\n ^= x;\n" 4998 " f(x)\n >>= x;\n" 4999 " f(x)\n <<= x;\n" 5000 " f(x)\n[y].z();\n" 5001 " LOG(INFO)\n << x;\n" 5002 " ifstream(x)\n >> x;\n" 5003 "}\n")); 5004 EXPECT_EQ("int q() {\n" 5005 " F(x)\n" 5006 " if (1) {\n" 5007 " }\n" 5008 " F(x)\n" 5009 " while (1) {\n" 5010 " }\n" 5011 " F(x)\n" 5012 " G(x);\n" 5013 " F(x)\n" 5014 " try {\n" 5015 " Q();\n" 5016 " } catch (...) {\n" 5017 " }\n" 5018 "}\n", 5019 format("int q() {\n" 5020 "F(x)\n" 5021 "if (1) {}\n" 5022 "F(x)\n" 5023 "while (1) {}\n" 5024 "F(x)\n" 5025 "G(x);\n" 5026 "F(x)\n" 5027 "try { Q(); } catch (...) {}\n" 5028 "}\n")); 5029 EXPECT_EQ("class A {\n" 5030 " A() : t(0) {}\n" 5031 " A(int i) noexcept() : {}\n" 5032 " A(X x)\n" // FIXME: function-level try blocks are broken. 5033 " try : t(0) {\n" 5034 " } catch (...) {\n" 5035 " }\n" 5036 "};", 5037 format("class A {\n" 5038 " A()\n : t(0) {}\n" 5039 " A(int i)\n noexcept() : {}\n" 5040 " A(X x)\n" 5041 " try : t(0) {} catch (...) {}\n" 5042 "};")); 5043 FormatStyle Style = getLLVMStyle(); 5044 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 5045 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 5046 Style.BraceWrapping.AfterFunction = true; 5047 EXPECT_EQ("void f()\n" 5048 "try\n" 5049 "{\n" 5050 "}", 5051 format("void f() try {\n" 5052 "}", 5053 Style)); 5054 EXPECT_EQ("class SomeClass {\n" 5055 "public:\n" 5056 " SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5057 "};", 5058 format("class SomeClass {\n" 5059 "public:\n" 5060 " SomeClass()\n" 5061 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5062 "};")); 5063 EXPECT_EQ("class SomeClass {\n" 5064 "public:\n" 5065 " SomeClass()\n" 5066 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5067 "};", 5068 format("class SomeClass {\n" 5069 "public:\n" 5070 " SomeClass()\n" 5071 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5072 "};", 5073 getLLVMStyleWithColumns(40))); 5074 5075 verifyFormat("MACRO(>)"); 5076 5077 // Some macros contain an implicit semicolon. 5078 Style = getLLVMStyle(); 5079 Style.StatementMacros.push_back("FOO"); 5080 verifyFormat("FOO(a) int b = 0;"); 5081 verifyFormat("FOO(a)\n" 5082 "int b = 0;", 5083 Style); 5084 verifyFormat("FOO(a);\n" 5085 "int b = 0;", 5086 Style); 5087 verifyFormat("FOO(argc, argv, \"4.0.2\")\n" 5088 "int b = 0;", 5089 Style); 5090 verifyFormat("FOO()\n" 5091 "int b = 0;", 5092 Style); 5093 verifyFormat("FOO\n" 5094 "int b = 0;", 5095 Style); 5096 verifyFormat("void f() {\n" 5097 " FOO(a)\n" 5098 " return a;\n" 5099 "}", 5100 Style); 5101 verifyFormat("FOO(a)\n" 5102 "FOO(b)", 5103 Style); 5104 verifyFormat("int a = 0;\n" 5105 "FOO(b)\n" 5106 "int c = 0;", 5107 Style); 5108 verifyFormat("int a = 0;\n" 5109 "int x = FOO(a)\n" 5110 "int b = 0;", 5111 Style); 5112 verifyFormat("void foo(int a) { FOO(a) }\n" 5113 "uint32_t bar() {}", 5114 Style); 5115 } 5116 5117 TEST_F(FormatTest, FormatsMacrosWithZeroColumnWidth) { 5118 FormatStyle ZeroColumn = getLLVMStyleWithColumns(0); 5119 5120 verifyFormat("#define A LOOOOOOOOOOOOOOOOOOONG() LOOOOOOOOOOOOOOOOOOONG()", 5121 ZeroColumn); 5122 } 5123 5124 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) { 5125 verifyFormat("#define A \\\n" 5126 " f({ \\\n" 5127 " g(); \\\n" 5128 " });", 5129 getLLVMStyleWithColumns(11)); 5130 } 5131 5132 TEST_F(FormatTest, IndentPreprocessorDirectives) { 5133 FormatStyle Style = getLLVMStyleWithColumns(40); 5134 Style.IndentPPDirectives = FormatStyle::PPDIS_None; 5135 verifyFormat("#ifdef _WIN32\n" 5136 "#define A 0\n" 5137 "#ifdef VAR2\n" 5138 "#define B 1\n" 5139 "#include <someheader.h>\n" 5140 "#define MACRO \\\n" 5141 " some_very_long_func_aaaaaaaaaa();\n" 5142 "#endif\n" 5143 "#else\n" 5144 "#define A 1\n" 5145 "#endif", 5146 Style); 5147 Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash; 5148 verifyFormat("#ifdef _WIN32\n" 5149 "# define A 0\n" 5150 "# ifdef VAR2\n" 5151 "# define B 1\n" 5152 "# include <someheader.h>\n" 5153 "# define MACRO \\\n" 5154 " some_very_long_func_aaaaaaaaaa();\n" 5155 "# endif\n" 5156 "#else\n" 5157 "# define A 1\n" 5158 "#endif", 5159 Style); 5160 verifyFormat("#if A\n" 5161 "# define MACRO \\\n" 5162 " void a(int x) { \\\n" 5163 " b(); \\\n" 5164 " c(); \\\n" 5165 " d(); \\\n" 5166 " e(); \\\n" 5167 " f(); \\\n" 5168 " }\n" 5169 "#endif", 5170 Style); 5171 // Comments before include guard. 5172 verifyFormat("// file comment\n" 5173 "// file comment\n" 5174 "#ifndef HEADER_H\n" 5175 "#define HEADER_H\n" 5176 "code();\n" 5177 "#endif", 5178 Style); 5179 // Test with include guards. 5180 verifyFormat("#ifndef HEADER_H\n" 5181 "#define HEADER_H\n" 5182 "code();\n" 5183 "#endif", 5184 Style); 5185 // Include guards must have a #define with the same variable immediately 5186 // after #ifndef. 5187 verifyFormat("#ifndef NOT_GUARD\n" 5188 "# define FOO\n" 5189 "code();\n" 5190 "#endif", 5191 Style); 5192 5193 // Include guards must cover the entire file. 5194 verifyFormat("code();\n" 5195 "code();\n" 5196 "#ifndef NOT_GUARD\n" 5197 "# define NOT_GUARD\n" 5198 "code();\n" 5199 "#endif", 5200 Style); 5201 verifyFormat("#ifndef NOT_GUARD\n" 5202 "# define NOT_GUARD\n" 5203 "code();\n" 5204 "#endif\n" 5205 "code();", 5206 Style); 5207 // Test with trailing blank lines. 5208 verifyFormat("#ifndef HEADER_H\n" 5209 "#define HEADER_H\n" 5210 "code();\n" 5211 "#endif\n", 5212 Style); 5213 // Include guards don't have #else. 5214 verifyFormat("#ifndef NOT_GUARD\n" 5215 "# define NOT_GUARD\n" 5216 "code();\n" 5217 "#else\n" 5218 "#endif", 5219 Style); 5220 verifyFormat("#ifndef NOT_GUARD\n" 5221 "# define NOT_GUARD\n" 5222 "code();\n" 5223 "#elif FOO\n" 5224 "#endif", 5225 Style); 5226 // Non-identifier #define after potential include guard. 5227 verifyFormat("#ifndef FOO\n" 5228 "# define 1\n" 5229 "#endif\n", 5230 Style); 5231 // #if closes past last non-preprocessor line. 5232 verifyFormat("#ifndef FOO\n" 5233 "#define FOO\n" 5234 "#if 1\n" 5235 "int i;\n" 5236 "# define A 0\n" 5237 "#endif\n" 5238 "#endif\n", 5239 Style); 5240 // Don't crash if there is an #elif directive without a condition. 5241 verifyFormat("#if 1\n" 5242 "int x;\n" 5243 "#elif\n" 5244 "int y;\n" 5245 "#else\n" 5246 "int z;\n" 5247 "#endif", 5248 Style); 5249 // FIXME: This doesn't handle the case where there's code between the 5250 // #ifndef and #define but all other conditions hold. This is because when 5251 // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the 5252 // previous code line yet, so we can't detect it. 5253 EXPECT_EQ("#ifndef NOT_GUARD\n" 5254 "code();\n" 5255 "#define NOT_GUARD\n" 5256 "code();\n" 5257 "#endif", 5258 format("#ifndef NOT_GUARD\n" 5259 "code();\n" 5260 "# define NOT_GUARD\n" 5261 "code();\n" 5262 "#endif", 5263 Style)); 5264 // FIXME: This doesn't handle cases where legitimate preprocessor lines may 5265 // be outside an include guard. Examples are #pragma once and 5266 // #pragma GCC diagnostic, or anything else that does not change the meaning 5267 // of the file if it's included multiple times. 5268 EXPECT_EQ("#ifdef WIN32\n" 5269 "# pragma once\n" 5270 "#endif\n" 5271 "#ifndef HEADER_H\n" 5272 "# define HEADER_H\n" 5273 "code();\n" 5274 "#endif", 5275 format("#ifdef WIN32\n" 5276 "# pragma once\n" 5277 "#endif\n" 5278 "#ifndef HEADER_H\n" 5279 "#define HEADER_H\n" 5280 "code();\n" 5281 "#endif", 5282 Style)); 5283 // FIXME: This does not detect when there is a single non-preprocessor line 5284 // in front of an include-guard-like structure where other conditions hold 5285 // because ScopedLineState hides the line. 5286 EXPECT_EQ("code();\n" 5287 "#ifndef HEADER_H\n" 5288 "#define HEADER_H\n" 5289 "code();\n" 5290 "#endif", 5291 format("code();\n" 5292 "#ifndef HEADER_H\n" 5293 "# define HEADER_H\n" 5294 "code();\n" 5295 "#endif", 5296 Style)); 5297 // Keep comments aligned with #, otherwise indent comments normally. These 5298 // tests cannot use verifyFormat because messUp manipulates leading 5299 // whitespace. 5300 { 5301 const char *Expected = "" 5302 "void f() {\n" 5303 "#if 1\n" 5304 "// Preprocessor aligned.\n" 5305 "# define A 0\n" 5306 " // Code. Separated by blank line.\n" 5307 "\n" 5308 "# define B 0\n" 5309 " // Code. Not aligned with #\n" 5310 "# define C 0\n" 5311 "#endif"; 5312 const char *ToFormat = "" 5313 "void f() {\n" 5314 "#if 1\n" 5315 "// Preprocessor aligned.\n" 5316 "# define A 0\n" 5317 "// Code. Separated by blank line.\n" 5318 "\n" 5319 "# define B 0\n" 5320 " // Code. Not aligned with #\n" 5321 "# define C 0\n" 5322 "#endif"; 5323 EXPECT_EQ(Expected, format(ToFormat, Style)); 5324 EXPECT_EQ(Expected, format(Expected, Style)); 5325 } 5326 // Keep block quotes aligned. 5327 { 5328 const char *Expected = "" 5329 "void f() {\n" 5330 "#if 1\n" 5331 "/* Preprocessor aligned. */\n" 5332 "# define A 0\n" 5333 " /* Code. Separated by blank line. */\n" 5334 "\n" 5335 "# define B 0\n" 5336 " /* Code. Not aligned with # */\n" 5337 "# define C 0\n" 5338 "#endif"; 5339 const char *ToFormat = "" 5340 "void f() {\n" 5341 "#if 1\n" 5342 "/* Preprocessor aligned. */\n" 5343 "# define A 0\n" 5344 "/* Code. Separated by blank line. */\n" 5345 "\n" 5346 "# define B 0\n" 5347 " /* Code. Not aligned with # */\n" 5348 "# define C 0\n" 5349 "#endif"; 5350 EXPECT_EQ(Expected, format(ToFormat, Style)); 5351 EXPECT_EQ(Expected, format(Expected, Style)); 5352 } 5353 // Keep comments aligned with un-indented directives. 5354 { 5355 const char *Expected = "" 5356 "void f() {\n" 5357 "// Preprocessor aligned.\n" 5358 "#define A 0\n" 5359 " // Code. Separated by blank line.\n" 5360 "\n" 5361 "#define B 0\n" 5362 " // Code. Not aligned with #\n" 5363 "#define C 0\n"; 5364 const char *ToFormat = "" 5365 "void f() {\n" 5366 "// Preprocessor aligned.\n" 5367 "#define A 0\n" 5368 "// Code. Separated by blank line.\n" 5369 "\n" 5370 "#define B 0\n" 5371 " // Code. Not aligned with #\n" 5372 "#define C 0\n"; 5373 EXPECT_EQ(Expected, format(ToFormat, Style)); 5374 EXPECT_EQ(Expected, format(Expected, Style)); 5375 } 5376 // Test AfterHash with tabs. 5377 { 5378 FormatStyle Tabbed = Style; 5379 Tabbed.UseTab = FormatStyle::UT_Always; 5380 Tabbed.IndentWidth = 8; 5381 Tabbed.TabWidth = 8; 5382 verifyFormat("#ifdef _WIN32\n" 5383 "#\tdefine A 0\n" 5384 "#\tifdef VAR2\n" 5385 "#\t\tdefine B 1\n" 5386 "#\t\tinclude <someheader.h>\n" 5387 "#\t\tdefine MACRO \\\n" 5388 "\t\t\tsome_very_long_func_aaaaaaaaaa();\n" 5389 "#\tendif\n" 5390 "#else\n" 5391 "#\tdefine A 1\n" 5392 "#endif", 5393 Tabbed); 5394 } 5395 5396 // Regression test: Multiline-macro inside include guards. 5397 verifyFormat("#ifndef HEADER_H\n" 5398 "#define HEADER_H\n" 5399 "#define A() \\\n" 5400 " int i; \\\n" 5401 " int j;\n" 5402 "#endif // HEADER_H", 5403 getLLVMStyleWithColumns(20)); 5404 5405 Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash; 5406 // Basic before hash indent tests 5407 verifyFormat("#ifdef _WIN32\n" 5408 " #define A 0\n" 5409 " #ifdef VAR2\n" 5410 " #define B 1\n" 5411 " #include <someheader.h>\n" 5412 " #define MACRO \\\n" 5413 " some_very_long_func_aaaaaaaaaa();\n" 5414 " #endif\n" 5415 "#else\n" 5416 " #define A 1\n" 5417 "#endif", 5418 Style); 5419 verifyFormat("#if A\n" 5420 " #define MACRO \\\n" 5421 " void a(int x) { \\\n" 5422 " b(); \\\n" 5423 " c(); \\\n" 5424 " d(); \\\n" 5425 " e(); \\\n" 5426 " f(); \\\n" 5427 " }\n" 5428 "#endif", 5429 Style); 5430 // Keep comments aligned with indented directives. These 5431 // tests cannot use verifyFormat because messUp manipulates leading 5432 // whitespace. 5433 { 5434 const char *Expected = "void f() {\n" 5435 "// Aligned to preprocessor.\n" 5436 "#if 1\n" 5437 " // Aligned to code.\n" 5438 " int a;\n" 5439 " #if 1\n" 5440 " // Aligned to preprocessor.\n" 5441 " #define A 0\n" 5442 " // Aligned to code.\n" 5443 " int b;\n" 5444 " #endif\n" 5445 "#endif\n" 5446 "}"; 5447 const char *ToFormat = "void f() {\n" 5448 "// Aligned to preprocessor.\n" 5449 "#if 1\n" 5450 "// Aligned to code.\n" 5451 "int a;\n" 5452 "#if 1\n" 5453 "// Aligned to preprocessor.\n" 5454 "#define A 0\n" 5455 "// Aligned to code.\n" 5456 "int b;\n" 5457 "#endif\n" 5458 "#endif\n" 5459 "}"; 5460 EXPECT_EQ(Expected, format(ToFormat, Style)); 5461 EXPECT_EQ(Expected, format(Expected, Style)); 5462 } 5463 { 5464 const char *Expected = "void f() {\n" 5465 "/* Aligned to preprocessor. */\n" 5466 "#if 1\n" 5467 " /* Aligned to code. */\n" 5468 " int a;\n" 5469 " #if 1\n" 5470 " /* Aligned to preprocessor. */\n" 5471 " #define A 0\n" 5472 " /* Aligned to code. */\n" 5473 " int b;\n" 5474 " #endif\n" 5475 "#endif\n" 5476 "}"; 5477 const char *ToFormat = "void f() {\n" 5478 "/* Aligned to preprocessor. */\n" 5479 "#if 1\n" 5480 "/* Aligned to code. */\n" 5481 "int a;\n" 5482 "#if 1\n" 5483 "/* Aligned to preprocessor. */\n" 5484 "#define A 0\n" 5485 "/* Aligned to code. */\n" 5486 "int b;\n" 5487 "#endif\n" 5488 "#endif\n" 5489 "}"; 5490 EXPECT_EQ(Expected, format(ToFormat, Style)); 5491 EXPECT_EQ(Expected, format(Expected, Style)); 5492 } 5493 5494 // Test single comment before preprocessor 5495 verifyFormat("// Comment\n" 5496 "\n" 5497 "#if 1\n" 5498 "#endif", 5499 Style); 5500 } 5501 5502 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) { 5503 verifyFormat("{\n { a #c; }\n}"); 5504 } 5505 5506 TEST_F(FormatTest, FormatUnbalancedStructuralElements) { 5507 EXPECT_EQ("#define A \\\n { \\\n {\nint i;", 5508 format("#define A { {\nint i;", getLLVMStyleWithColumns(11))); 5509 EXPECT_EQ("#define A \\\n } \\\n }\nint i;", 5510 format("#define A } }\nint i;", getLLVMStyleWithColumns(11))); 5511 } 5512 5513 TEST_F(FormatTest, EscapedNewlines) { 5514 FormatStyle Narrow = getLLVMStyleWithColumns(11); 5515 EXPECT_EQ("#define A \\\n int i; \\\n int j;", 5516 format("#define A \\\nint i;\\\n int j;", Narrow)); 5517 EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;")); 5518 EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();")); 5519 EXPECT_EQ("/* \\ \\ \\\n */", format("\\\n/* \\ \\ \\\n */")); 5520 EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>")); 5521 5522 FormatStyle AlignLeft = getLLVMStyle(); 5523 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left; 5524 EXPECT_EQ("#define MACRO(x) \\\n" 5525 "private: \\\n" 5526 " int x(int a);\n", 5527 format("#define MACRO(x) \\\n" 5528 "private: \\\n" 5529 " int x(int a);\n", 5530 AlignLeft)); 5531 5532 // CRLF line endings 5533 EXPECT_EQ("#define A \\\r\n int i; \\\r\n int j;", 5534 format("#define A \\\r\nint i;\\\r\n int j;", Narrow)); 5535 EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;")); 5536 EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();")); 5537 EXPECT_EQ("/* \\ \\ \\\r\n */", format("\\\r\n/* \\ \\ \\\r\n */")); 5538 EXPECT_EQ("<a\r\n\\\\\r\n>", format("<a\r\n\\\\\r\n>")); 5539 EXPECT_EQ("#define MACRO(x) \\\r\n" 5540 "private: \\\r\n" 5541 " int x(int a);\r\n", 5542 format("#define MACRO(x) \\\r\n" 5543 "private: \\\r\n" 5544 " int x(int a);\r\n", 5545 AlignLeft)); 5546 5547 FormatStyle DontAlign = getLLVMStyle(); 5548 DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 5549 DontAlign.MaxEmptyLinesToKeep = 3; 5550 // FIXME: can't use verifyFormat here because the newline before 5551 // "public:" is not inserted the first time it's reformatted 5552 EXPECT_EQ("#define A \\\n" 5553 " class Foo { \\\n" 5554 " void bar(); \\\n" 5555 "\\\n" 5556 "\\\n" 5557 "\\\n" 5558 " public: \\\n" 5559 " void baz(); \\\n" 5560 " };", 5561 format("#define A \\\n" 5562 " class Foo { \\\n" 5563 " void bar(); \\\n" 5564 "\\\n" 5565 "\\\n" 5566 "\\\n" 5567 " public: \\\n" 5568 " void baz(); \\\n" 5569 " };", 5570 DontAlign)); 5571 } 5572 5573 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) { 5574 verifyFormat("#define A \\\n" 5575 " int v( \\\n" 5576 " a); \\\n" 5577 " int i;", 5578 getLLVMStyleWithColumns(11)); 5579 } 5580 5581 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) { 5582 EXPECT_EQ( 5583 "#define ALooooooooooooooooooooooooooooooooooooooongMacro(" 5584 " \\\n" 5585 " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n" 5586 "\n" 5587 "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n" 5588 " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n", 5589 format(" #define ALooooooooooooooooooooooooooooooooooooooongMacro(" 5590 "\\\n" 5591 "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n" 5592 " \n" 5593 " AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n" 5594 " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n")); 5595 } 5596 5597 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) { 5598 EXPECT_EQ("int\n" 5599 "#define A\n" 5600 " a;", 5601 format("int\n#define A\na;")); 5602 verifyFormat("functionCallTo(\n" 5603 " someOtherFunction(\n" 5604 " withSomeParameters, whichInSequence,\n" 5605 " areLongerThanALine(andAnotherCall,\n" 5606 "#define A B\n" 5607 " withMoreParamters,\n" 5608 " whichStronglyInfluenceTheLayout),\n" 5609 " andMoreParameters),\n" 5610 " trailing);", 5611 getLLVMStyleWithColumns(69)); 5612 verifyFormat("Foo::Foo()\n" 5613 "#ifdef BAR\n" 5614 " : baz(0)\n" 5615 "#endif\n" 5616 "{\n" 5617 "}"); 5618 verifyFormat("void f() {\n" 5619 " if (true)\n" 5620 "#ifdef A\n" 5621 " f(42);\n" 5622 " x();\n" 5623 "#else\n" 5624 " g();\n" 5625 " x();\n" 5626 "#endif\n" 5627 "}"); 5628 verifyFormat("void f(param1, param2,\n" 5629 " param3,\n" 5630 "#ifdef A\n" 5631 " param4(param5,\n" 5632 "#ifdef A1\n" 5633 " param6,\n" 5634 "#ifdef A2\n" 5635 " param7),\n" 5636 "#else\n" 5637 " param8),\n" 5638 " param9,\n" 5639 "#endif\n" 5640 " param10,\n" 5641 "#endif\n" 5642 " param11)\n" 5643 "#else\n" 5644 " param12)\n" 5645 "#endif\n" 5646 "{\n" 5647 " x();\n" 5648 "}", 5649 getLLVMStyleWithColumns(28)); 5650 verifyFormat("#if 1\n" 5651 "int i;"); 5652 verifyFormat("#if 1\n" 5653 "#endif\n" 5654 "#if 1\n" 5655 "#else\n" 5656 "#endif\n"); 5657 verifyFormat("DEBUG({\n" 5658 " return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5659 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n" 5660 "});\n" 5661 "#if a\n" 5662 "#else\n" 5663 "#endif"); 5664 5665 verifyIncompleteFormat("void f(\n" 5666 "#if A\n" 5667 ");\n" 5668 "#else\n" 5669 "#endif"); 5670 } 5671 5672 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) { 5673 verifyFormat("#endif\n" 5674 "#if B"); 5675 } 5676 5677 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) { 5678 FormatStyle SingleLine = getLLVMStyle(); 5679 SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse; 5680 verifyFormat("#if 0\n" 5681 "#elif 1\n" 5682 "#endif\n" 5683 "void foo() {\n" 5684 " if (test) foo2();\n" 5685 "}", 5686 SingleLine); 5687 } 5688 5689 TEST_F(FormatTest, LayoutBlockInsideParens) { 5690 verifyFormat("functionCall({ int i; });"); 5691 verifyFormat("functionCall({\n" 5692 " int i;\n" 5693 " int j;\n" 5694 "});"); 5695 verifyFormat("functionCall(\n" 5696 " {\n" 5697 " int i;\n" 5698 " int j;\n" 5699 " },\n" 5700 " aaaa, bbbb, cccc);"); 5701 verifyFormat("functionA(functionB({\n" 5702 " int i;\n" 5703 " int j;\n" 5704 " }),\n" 5705 " aaaa, bbbb, cccc);"); 5706 verifyFormat("functionCall(\n" 5707 " {\n" 5708 " int i;\n" 5709 " int j;\n" 5710 " },\n" 5711 " aaaa, bbbb, // comment\n" 5712 " cccc);"); 5713 verifyFormat("functionA(functionB({\n" 5714 " int i;\n" 5715 " int j;\n" 5716 " }),\n" 5717 " aaaa, bbbb, // comment\n" 5718 " cccc);"); 5719 verifyFormat("functionCall(aaaa, bbbb, { int i; });"); 5720 verifyFormat("functionCall(aaaa, bbbb, {\n" 5721 " int i;\n" 5722 " int j;\n" 5723 "});"); 5724 verifyFormat( 5725 "Aaa(\n" // FIXME: There shouldn't be a linebreak here. 5726 " {\n" 5727 " int i; // break\n" 5728 " },\n" 5729 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 5730 " ccccccccccccccccc));"); 5731 verifyFormat("DEBUG({\n" 5732 " if (a)\n" 5733 " f();\n" 5734 "});"); 5735 } 5736 5737 TEST_F(FormatTest, LayoutBlockInsideStatement) { 5738 EXPECT_EQ("SOME_MACRO { int i; }\n" 5739 "int i;", 5740 format(" SOME_MACRO {int i;} int i;")); 5741 } 5742 5743 TEST_F(FormatTest, LayoutNestedBlocks) { 5744 verifyFormat("void AddOsStrings(unsigned bitmask) {\n" 5745 " struct s {\n" 5746 " int i;\n" 5747 " };\n" 5748 " s kBitsToOs[] = {{10}};\n" 5749 " for (int i = 0; i < 10; ++i)\n" 5750 " return;\n" 5751 "}"); 5752 verifyFormat("call(parameter, {\n" 5753 " something();\n" 5754 " // Comment using all columns.\n" 5755 " somethingelse();\n" 5756 "});", 5757 getLLVMStyleWithColumns(40)); 5758 verifyFormat("DEBUG( //\n" 5759 " { f(); }, a);"); 5760 verifyFormat("DEBUG( //\n" 5761 " {\n" 5762 " f(); //\n" 5763 " },\n" 5764 " a);"); 5765 5766 EXPECT_EQ("call(parameter, {\n" 5767 " something();\n" 5768 " // Comment too\n" 5769 " // looooooooooong.\n" 5770 " somethingElse();\n" 5771 "});", 5772 format("call(parameter, {\n" 5773 " something();\n" 5774 " // Comment too looooooooooong.\n" 5775 " somethingElse();\n" 5776 "});", 5777 getLLVMStyleWithColumns(29))); 5778 EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int i; });")); 5779 EXPECT_EQ("DEBUG({ // comment\n" 5780 " int i;\n" 5781 "});", 5782 format("DEBUG({ // comment\n" 5783 "int i;\n" 5784 "});")); 5785 EXPECT_EQ("DEBUG({\n" 5786 " int i;\n" 5787 "\n" 5788 " // comment\n" 5789 " int j;\n" 5790 "});", 5791 format("DEBUG({\n" 5792 " int i;\n" 5793 "\n" 5794 " // comment\n" 5795 " int j;\n" 5796 "});")); 5797 5798 verifyFormat("DEBUG({\n" 5799 " if (a)\n" 5800 " return;\n" 5801 "});"); 5802 verifyGoogleFormat("DEBUG({\n" 5803 " if (a) return;\n" 5804 "});"); 5805 FormatStyle Style = getGoogleStyle(); 5806 Style.ColumnLimit = 45; 5807 verifyFormat("Debug(\n" 5808 " aaaaa,\n" 5809 " {\n" 5810 " if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n" 5811 " },\n" 5812 " a);", 5813 Style); 5814 5815 verifyFormat("SomeFunction({MACRO({ return output; }), b});"); 5816 5817 verifyNoCrash("^{v^{a}}"); 5818 } 5819 5820 TEST_F(FormatTest, FormatNestedBlocksInMacros) { 5821 EXPECT_EQ("#define MACRO() \\\n" 5822 " Debug(aaa, /* force line break */ \\\n" 5823 " { \\\n" 5824 " int i; \\\n" 5825 " int j; \\\n" 5826 " })", 5827 format("#define MACRO() Debug(aaa, /* force line break */ \\\n" 5828 " { int i; int j; })", 5829 getGoogleStyle())); 5830 5831 EXPECT_EQ("#define A \\\n" 5832 " [] { \\\n" 5833 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 5834 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n" 5835 " }", 5836 format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 5837 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }", 5838 getGoogleStyle())); 5839 } 5840 5841 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) { 5842 EXPECT_EQ("{}", format("{}")); 5843 verifyFormat("enum E {};"); 5844 verifyFormat("enum E {}"); 5845 FormatStyle Style = getLLVMStyle(); 5846 Style.SpaceInEmptyBlock = true; 5847 EXPECT_EQ("void f() { }", format("void f() {}", Style)); 5848 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 5849 EXPECT_EQ("while (true) { }", format("while (true) {}", Style)); 5850 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 5851 Style.BraceWrapping.BeforeElse = false; 5852 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 5853 verifyFormat("if (a)\n" 5854 "{\n" 5855 "} else if (b)\n" 5856 "{\n" 5857 "} else\n" 5858 "{ }", 5859 Style); 5860 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never; 5861 verifyFormat("if (a) {\n" 5862 "} else if (b) {\n" 5863 "} else {\n" 5864 "}", 5865 Style); 5866 Style.BraceWrapping.BeforeElse = true; 5867 verifyFormat("if (a) { }\n" 5868 "else if (b) { }\n" 5869 "else { }", 5870 Style); 5871 } 5872 5873 TEST_F(FormatTest, FormatBeginBlockEndMacros) { 5874 FormatStyle Style = getLLVMStyle(); 5875 Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$"; 5876 Style.MacroBlockEnd = "^[A-Z_]+_END$"; 5877 verifyFormat("FOO_BEGIN\n" 5878 " FOO_ENTRY\n" 5879 "FOO_END", 5880 Style); 5881 verifyFormat("FOO_BEGIN\n" 5882 " NESTED_FOO_BEGIN\n" 5883 " NESTED_FOO_ENTRY\n" 5884 " NESTED_FOO_END\n" 5885 "FOO_END", 5886 Style); 5887 verifyFormat("FOO_BEGIN(Foo, Bar)\n" 5888 " int x;\n" 5889 " x = 1;\n" 5890 "FOO_END(Baz)", 5891 Style); 5892 } 5893 5894 //===----------------------------------------------------------------------===// 5895 // Line break tests. 5896 //===----------------------------------------------------------------------===// 5897 5898 TEST_F(FormatTest, PreventConfusingIndents) { 5899 verifyFormat( 5900 "void f() {\n" 5901 " SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n" 5902 " parameter, parameter, parameter)),\n" 5903 " SecondLongCall(parameter));\n" 5904 "}"); 5905 verifyFormat( 5906 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5907 " aaaaaaaaaaaaaaaaaaaaaaaa(\n" 5908 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 5909 " aaaaaaaaaaaaaaaaaaaaaaaa);"); 5910 verifyFormat( 5911 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5912 " [aaaaaaaaaaaaaaaaaaaaaaaa\n" 5913 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n" 5914 " [aaaaaaaaaaaaaaaaaaaaaaaa]];"); 5915 verifyFormat( 5916 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 5917 " aaaaaaaaaaaaaaaaaaaaaaaa<\n" 5918 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n" 5919 " aaaaaaaaaaaaaaaaaaaaaaaa>;"); 5920 verifyFormat("int a = bbbb && ccc &&\n" 5921 " fffff(\n" 5922 "#define A Just forcing a new line\n" 5923 " ddd);"); 5924 } 5925 5926 TEST_F(FormatTest, LineBreakingInBinaryExpressions) { 5927 verifyFormat( 5928 "bool aaaaaaa =\n" 5929 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n" 5930 " bbbbbbbb();"); 5931 verifyFormat( 5932 "bool aaaaaaa =\n" 5933 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n" 5934 " bbbbbbbb();"); 5935 5936 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n" 5937 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n" 5938 " ccccccccc == ddddddddddd;"); 5939 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n" 5940 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n" 5941 " ccccccccc == ddddddddddd;"); 5942 verifyFormat( 5943 "bool aaaaaaaaaaaaaaaaaaaaa =\n" 5944 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n" 5945 " ccccccccc == ddddddddddd;"); 5946 5947 verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n" 5948 " aaaaaa) &&\n" 5949 " bbbbbb && cccccc;"); 5950 verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n" 5951 " aaaaaa) >>\n" 5952 " bbbbbb;"); 5953 verifyFormat("aa = Whitespaces.addUntouchableComment(\n" 5954 " SourceMgr.getSpellingColumnNumber(\n" 5955 " TheLine.Last->FormatTok.Tok.getLocation()) -\n" 5956 " 1);"); 5957 5958 verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 5959 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n" 5960 " cccccc) {\n}"); 5961 verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 5962 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n" 5963 " cccccc) {\n}"); 5964 verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 5965 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n" 5966 " cccccc) {\n}"); 5967 verifyFormat("b = a &&\n" 5968 " // Comment\n" 5969 " b.c && d;"); 5970 5971 // If the LHS of a comparison is not a binary expression itself, the 5972 // additional linebreak confuses many people. 5973 verifyFormat( 5974 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5975 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n" 5976 "}"); 5977 verifyFormat( 5978 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5979 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 5980 "}"); 5981 verifyFormat( 5982 "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n" 5983 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 5984 "}"); 5985 verifyFormat( 5986 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5987 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n" 5988 "}"); 5989 // Even explicit parentheses stress the precedence enough to make the 5990 // additional break unnecessary. 5991 verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5992 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 5993 "}"); 5994 // This cases is borderline, but with the indentation it is still readable. 5995 verifyFormat( 5996 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5997 " aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5998 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 5999 "}", 6000 getLLVMStyleWithColumns(75)); 6001 6002 // If the LHS is a binary expression, we should still use the additional break 6003 // as otherwise the formatting hides the operator precedence. 6004 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6005 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6006 " 5) {\n" 6007 "}"); 6008 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6009 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n" 6010 " 5) {\n" 6011 "}"); 6012 6013 FormatStyle OnePerLine = getLLVMStyle(); 6014 OnePerLine.BinPackParameters = false; 6015 verifyFormat( 6016 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6017 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6018 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}", 6019 OnePerLine); 6020 6021 verifyFormat("int i = someFunction(aaaaaaa, 0)\n" 6022 " .aaa(aaaaaaaaaaaaa) *\n" 6023 " aaaaaaa +\n" 6024 " aaaaaaa;", 6025 getLLVMStyleWithColumns(40)); 6026 } 6027 6028 TEST_F(FormatTest, ExpressionIndentation) { 6029 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6030 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6031 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6032 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6033 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n" 6034 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n" 6035 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6036 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n" 6037 " ccccccccccccccccccccccccccccccccccccccccc;"); 6038 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6039 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6040 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6041 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 6042 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6043 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6044 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6045 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 6046 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6047 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6048 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6049 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 6050 verifyFormat("if () {\n" 6051 "} else if (aaaaa && bbbbb > // break\n" 6052 " ccccc) {\n" 6053 "}"); 6054 verifyFormat("if () {\n" 6055 "} else if constexpr (aaaaa && bbbbb > // break\n" 6056 " ccccc) {\n" 6057 "}"); 6058 verifyFormat("if () {\n" 6059 "} else if CONSTEXPR (aaaaa && bbbbb > // break\n" 6060 " ccccc) {\n" 6061 "}"); 6062 verifyFormat("if () {\n" 6063 "} else if (aaaaa &&\n" 6064 " bbbbb > // break\n" 6065 " ccccc &&\n" 6066 " ddddd) {\n" 6067 "}"); 6068 6069 // Presence of a trailing comment used to change indentation of b. 6070 verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n" 6071 " b;\n" 6072 "return aaaaaaaaaaaaaaaaaaa +\n" 6073 " b; //", 6074 getLLVMStyleWithColumns(30)); 6075 } 6076 6077 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) { 6078 // Not sure what the best system is here. Like this, the LHS can be found 6079 // immediately above an operator (everything with the same or a higher 6080 // indent). The RHS is aligned right of the operator and so compasses 6081 // everything until something with the same indent as the operator is found. 6082 // FIXME: Is this a good system? 6083 FormatStyle Style = getLLVMStyle(); 6084 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 6085 verifyFormat( 6086 "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6087 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6088 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6089 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6090 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6091 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6092 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6093 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6094 " > ccccccccccccccccccccccccccccccccccccccccc;", 6095 Style); 6096 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6097 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6098 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6099 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6100 Style); 6101 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6102 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6103 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6104 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6105 Style); 6106 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6107 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6108 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6109 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6110 Style); 6111 verifyFormat("if () {\n" 6112 "} else if (aaaaa\n" 6113 " && bbbbb // break\n" 6114 " > ccccc) {\n" 6115 "}", 6116 Style); 6117 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6118 " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6119 Style); 6120 verifyFormat("return (a)\n" 6121 " // comment\n" 6122 " + b;", 6123 Style); 6124 verifyFormat( 6125 "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6126 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6127 " + cc;", 6128 Style); 6129 6130 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6131 " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 6132 Style); 6133 6134 // Forced by comments. 6135 verifyFormat( 6136 "unsigned ContentSize =\n" 6137 " sizeof(int16_t) // DWARF ARange version number\n" 6138 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6139 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6140 " + sizeof(int8_t); // Segment Size (in bytes)"); 6141 6142 verifyFormat("return boost::fusion::at_c<0>(iiii).second\n" 6143 " == boost::fusion::at_c<1>(iiii).second;", 6144 Style); 6145 6146 Style.ColumnLimit = 60; 6147 verifyFormat("zzzzzzzzzz\n" 6148 " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6149 " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);", 6150 Style); 6151 6152 Style.ColumnLimit = 80; 6153 Style.IndentWidth = 4; 6154 Style.TabWidth = 4; 6155 Style.UseTab = FormatStyle::UT_Always; 6156 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6157 Style.AlignOperands = FormatStyle::OAS_DontAlign; 6158 EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n" 6159 "\t&& (someOtherLongishConditionPart1\n" 6160 "\t\t|| someOtherEvenLongerNestedConditionPart2);", 6161 format("return someVeryVeryLongConditionThatBarelyFitsOnALine && " 6162 "(someOtherLongishConditionPart1 || " 6163 "someOtherEvenLongerNestedConditionPart2);", 6164 Style)); 6165 } 6166 6167 TEST_F(FormatTest, ExpressionIndentationStrictAlign) { 6168 FormatStyle Style = getLLVMStyle(); 6169 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 6170 Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator; 6171 6172 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6173 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6174 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6175 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6176 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6177 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6178 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6179 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6180 " > ccccccccccccccccccccccccccccccccccccccccc;", 6181 Style); 6182 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6183 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6184 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6185 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6186 Style); 6187 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6188 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6189 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6190 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6191 Style); 6192 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6193 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6194 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6195 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6196 Style); 6197 verifyFormat("if () {\n" 6198 "} else if (aaaaa\n" 6199 " && bbbbb // break\n" 6200 " > ccccc) {\n" 6201 "}", 6202 Style); 6203 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6204 " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6205 Style); 6206 verifyFormat("return (a)\n" 6207 " // comment\n" 6208 " + b;", 6209 Style); 6210 verifyFormat( 6211 "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6212 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6213 " + cc;", 6214 Style); 6215 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 6216 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 6217 " : 3333333333333333;", 6218 Style); 6219 verifyFormat( 6220 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 6221 " : ccccccccccccccc ? dddddddddddddddddd\n" 6222 " : eeeeeeeeeeeeeeeeee)\n" 6223 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 6224 " : 3333333333333333;", 6225 Style); 6226 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6227 " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 6228 Style); 6229 6230 verifyFormat("return boost::fusion::at_c<0>(iiii).second\n" 6231 " == boost::fusion::at_c<1>(iiii).second;", 6232 Style); 6233 6234 Style.ColumnLimit = 60; 6235 verifyFormat("zzzzzzzzzzzzz\n" 6236 " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6237 " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);", 6238 Style); 6239 6240 // Forced by comments. 6241 Style.ColumnLimit = 80; 6242 verifyFormat( 6243 "unsigned ContentSize\n" 6244 " = sizeof(int16_t) // DWARF ARange version number\n" 6245 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6246 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6247 " + sizeof(int8_t); // Segment Size (in bytes)", 6248 Style); 6249 6250 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6251 verifyFormat( 6252 "unsigned ContentSize =\n" 6253 " sizeof(int16_t) // DWARF ARange version number\n" 6254 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6255 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6256 " + sizeof(int8_t); // Segment Size (in bytes)", 6257 Style); 6258 6259 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 6260 verifyFormat( 6261 "unsigned ContentSize =\n" 6262 " sizeof(int16_t) // DWARF ARange version number\n" 6263 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6264 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6265 " + sizeof(int8_t); // Segment Size (in bytes)", 6266 Style); 6267 } 6268 6269 TEST_F(FormatTest, EnforcedOperatorWraps) { 6270 // Here we'd like to wrap after the || operators, but a comment is forcing an 6271 // earlier wrap. 6272 verifyFormat("bool x = aaaaa //\n" 6273 " || bbbbb\n" 6274 " //\n" 6275 " || cccc;"); 6276 } 6277 6278 TEST_F(FormatTest, NoOperandAlignment) { 6279 FormatStyle Style = getLLVMStyle(); 6280 Style.AlignOperands = FormatStyle::OAS_DontAlign; 6281 verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n" 6282 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6283 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 6284 Style); 6285 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6286 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6287 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6288 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6289 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6290 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6291 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6292 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6293 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6294 " > ccccccccccccccccccccccccccccccccccccccccc;", 6295 Style); 6296 6297 verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6298 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6299 " + cc;", 6300 Style); 6301 verifyFormat("int a = aa\n" 6302 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6303 " * cccccccccccccccccccccccccccccccccccc;\n", 6304 Style); 6305 6306 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6307 verifyFormat("return (a > b\n" 6308 " // comment1\n" 6309 " // comment2\n" 6310 " || c);", 6311 Style); 6312 } 6313 6314 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) { 6315 FormatStyle Style = getLLVMStyle(); 6316 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6317 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 6318 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6319 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6320 Style); 6321 } 6322 6323 TEST_F(FormatTest, AllowBinPackingInsideArguments) { 6324 FormatStyle Style = getLLVMStyleWithColumns(40); 6325 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6326 Style.BinPackArguments = false; 6327 verifyFormat("void test() {\n" 6328 " someFunction(\n" 6329 " this + argument + is + quite\n" 6330 " + long + so + it + gets + wrapped\n" 6331 " + but + remains + bin - packed);\n" 6332 "}", 6333 Style); 6334 verifyFormat("void test() {\n" 6335 " someFunction(arg1,\n" 6336 " this + argument + is\n" 6337 " + quite + long + so\n" 6338 " + it + gets + wrapped\n" 6339 " + but + remains + bin\n" 6340 " - packed,\n" 6341 " arg3);\n" 6342 "}", 6343 Style); 6344 verifyFormat("void test() {\n" 6345 " someFunction(\n" 6346 " arg1,\n" 6347 " this + argument + has\n" 6348 " + anotherFunc(nested,\n" 6349 " calls + whose\n" 6350 " + arguments\n" 6351 " + are + also\n" 6352 " + wrapped,\n" 6353 " in + addition)\n" 6354 " + to + being + bin - packed,\n" 6355 " arg3);\n" 6356 "}", 6357 Style); 6358 6359 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 6360 verifyFormat("void test() {\n" 6361 " someFunction(\n" 6362 " arg1,\n" 6363 " this + argument + has +\n" 6364 " anotherFunc(nested,\n" 6365 " calls + whose +\n" 6366 " arguments +\n" 6367 " are + also +\n" 6368 " wrapped,\n" 6369 " in + addition) +\n" 6370 " to + being + bin - packed,\n" 6371 " arg3);\n" 6372 "}", 6373 Style); 6374 } 6375 6376 TEST_F(FormatTest, ConstructorInitializers) { 6377 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}"); 6378 verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}", 6379 getLLVMStyleWithColumns(45)); 6380 verifyFormat("Constructor()\n" 6381 " : Inttializer(FitsOnTheLine) {}", 6382 getLLVMStyleWithColumns(44)); 6383 verifyFormat("Constructor()\n" 6384 " : Inttializer(FitsOnTheLine) {}", 6385 getLLVMStyleWithColumns(43)); 6386 6387 verifyFormat("template <typename T>\n" 6388 "Constructor() : Initializer(FitsOnTheLine) {}", 6389 getLLVMStyleWithColumns(45)); 6390 6391 verifyFormat( 6392 "SomeClass::Constructor()\n" 6393 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}"); 6394 6395 verifyFormat( 6396 "SomeClass::Constructor()\n" 6397 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6398 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}"); 6399 verifyFormat( 6400 "SomeClass::Constructor()\n" 6401 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6402 " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}"); 6403 verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6404 " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 6405 " : aaaaaaaaaa(aaaaaa) {}"); 6406 6407 verifyFormat("Constructor()\n" 6408 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6409 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6410 " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6411 " aaaaaaaaaaaaaaaaaaaaaaa() {}"); 6412 6413 verifyFormat("Constructor()\n" 6414 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6415 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 6416 6417 verifyFormat("Constructor(int Parameter = 0)\n" 6418 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n" 6419 " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}"); 6420 verifyFormat("Constructor()\n" 6421 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n" 6422 "}", 6423 getLLVMStyleWithColumns(60)); 6424 verifyFormat("Constructor()\n" 6425 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6426 " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}"); 6427 6428 // Here a line could be saved by splitting the second initializer onto two 6429 // lines, but that is not desirable. 6430 verifyFormat("Constructor()\n" 6431 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n" 6432 " aaaaaaaaaaa(aaaaaaaaaaa),\n" 6433 " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 6434 6435 FormatStyle OnePerLine = getLLVMStyle(); 6436 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_Never; 6437 verifyFormat("MyClass::MyClass()\n" 6438 " : a(a),\n" 6439 " b(b),\n" 6440 " c(c) {}", 6441 OnePerLine); 6442 verifyFormat("MyClass::MyClass()\n" 6443 " : a(a), // comment\n" 6444 " b(b),\n" 6445 " c(c) {}", 6446 OnePerLine); 6447 verifyFormat("MyClass::MyClass(int a)\n" 6448 " : b(a), // comment\n" 6449 " c(a + 1) { // lined up\n" 6450 "}", 6451 OnePerLine); 6452 verifyFormat("Constructor()\n" 6453 " : a(b, b, b) {}", 6454 OnePerLine); 6455 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6456 OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false; 6457 verifyFormat("SomeClass::Constructor()\n" 6458 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6459 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6460 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6461 OnePerLine); 6462 verifyFormat("SomeClass::Constructor()\n" 6463 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n" 6464 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6465 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6466 OnePerLine); 6467 verifyFormat("MyClass::MyClass(int var)\n" 6468 " : some_var_(var), // 4 space indent\n" 6469 " some_other_var_(var + 1) { // lined up\n" 6470 "}", 6471 OnePerLine); 6472 verifyFormat("Constructor()\n" 6473 " : aaaaa(aaaaaa),\n" 6474 " aaaaa(aaaaaa),\n" 6475 " aaaaa(aaaaaa),\n" 6476 " aaaaa(aaaaaa),\n" 6477 " aaaaa(aaaaaa) {}", 6478 OnePerLine); 6479 verifyFormat("Constructor()\n" 6480 " : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n" 6481 " aaaaaaaaaaaaaaaaaaaaaa) {}", 6482 OnePerLine); 6483 OnePerLine.BinPackParameters = false; 6484 verifyFormat( 6485 "Constructor()\n" 6486 " : aaaaaaaaaaaaaaaaaaaaaaaa(\n" 6487 " aaaaaaaaaaa().aaa(),\n" 6488 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6489 OnePerLine); 6490 OnePerLine.ColumnLimit = 60; 6491 verifyFormat("Constructor()\n" 6492 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6493 " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}", 6494 OnePerLine); 6495 6496 EXPECT_EQ("Constructor()\n" 6497 " : // Comment forcing unwanted break.\n" 6498 " aaaa(aaaa) {}", 6499 format("Constructor() :\n" 6500 " // Comment forcing unwanted break.\n" 6501 " aaaa(aaaa) {}")); 6502 } 6503 6504 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) { 6505 FormatStyle Style = getLLVMStyleWithColumns(60); 6506 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6507 Style.BinPackParameters = false; 6508 6509 for (int i = 0; i < 4; ++i) { 6510 // Test all combinations of parameters that should not have an effect. 6511 Style.AllowAllParametersOfDeclarationOnNextLine = i & 1; 6512 Style.AllowAllArgumentsOnNextLine = i & 2; 6513 6514 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6515 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6516 verifyFormat("Constructor()\n" 6517 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6518 Style); 6519 verifyFormat("Constructor() : a(a), b(b) {}", Style); 6520 6521 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6522 verifyFormat("Constructor()\n" 6523 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6524 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6525 Style); 6526 verifyFormat("Constructor() : a(a), b(b) {}", Style); 6527 6528 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 6529 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6530 verifyFormat("Constructor()\n" 6531 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6532 Style); 6533 6534 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6535 verifyFormat("Constructor()\n" 6536 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6537 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6538 Style); 6539 6540 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6541 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6542 verifyFormat("Constructor() :\n" 6543 " aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6544 Style); 6545 6546 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6547 verifyFormat("Constructor() :\n" 6548 " aaaaaaaaaaaaaaaaaa(a),\n" 6549 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6550 Style); 6551 } 6552 6553 // Test interactions between AllowAllParametersOfDeclarationOnNextLine and 6554 // AllowAllConstructorInitializersOnNextLine in all 6555 // BreakConstructorInitializers modes 6556 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6557 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6558 verifyFormat("SomeClassWithALongName::Constructor(\n" 6559 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n" 6560 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6561 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6562 Style); 6563 6564 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6565 verifyFormat("SomeClassWithALongName::Constructor(\n" 6566 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6567 " int bbbbbbbbbbbbb,\n" 6568 " int cccccccccccccccc)\n" 6569 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6570 Style); 6571 6572 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6573 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6574 verifyFormat("SomeClassWithALongName::Constructor(\n" 6575 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6576 " int bbbbbbbbbbbbb)\n" 6577 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6578 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6579 Style); 6580 6581 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 6582 6583 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6584 verifyFormat("SomeClassWithALongName::Constructor(\n" 6585 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n" 6586 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6587 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6588 Style); 6589 6590 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6591 verifyFormat("SomeClassWithALongName::Constructor(\n" 6592 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6593 " int bbbbbbbbbbbbb,\n" 6594 " int cccccccccccccccc)\n" 6595 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6596 Style); 6597 6598 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6599 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6600 verifyFormat("SomeClassWithALongName::Constructor(\n" 6601 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6602 " int bbbbbbbbbbbbb)\n" 6603 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6604 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6605 Style); 6606 6607 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6608 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6609 verifyFormat("SomeClassWithALongName::Constructor(\n" 6610 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n" 6611 " aaaaaaaaaaaaaaaaaaaa(a),\n" 6612 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6613 Style); 6614 6615 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6616 verifyFormat("SomeClassWithALongName::Constructor(\n" 6617 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6618 " int bbbbbbbbbbbbb,\n" 6619 " int cccccccccccccccc) :\n" 6620 " aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6621 Style); 6622 6623 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6624 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6625 verifyFormat("SomeClassWithALongName::Constructor(\n" 6626 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6627 " int bbbbbbbbbbbbb) :\n" 6628 " aaaaaaaaaaaaaaaaaaaa(a),\n" 6629 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6630 Style); 6631 } 6632 6633 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) { 6634 FormatStyle Style = getLLVMStyleWithColumns(60); 6635 Style.BinPackArguments = false; 6636 for (int i = 0; i < 4; ++i) { 6637 // Test all combinations of parameters that should not have an effect. 6638 Style.AllowAllParametersOfDeclarationOnNextLine = i & 1; 6639 Style.PackConstructorInitializers = 6640 i & 2 ? FormatStyle::PCIS_BinPack : FormatStyle::PCIS_Never; 6641 6642 Style.AllowAllArgumentsOnNextLine = true; 6643 verifyFormat("void foo() {\n" 6644 " FunctionCallWithReallyLongName(\n" 6645 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n" 6646 "}", 6647 Style); 6648 Style.AllowAllArgumentsOnNextLine = false; 6649 verifyFormat("void foo() {\n" 6650 " FunctionCallWithReallyLongName(\n" 6651 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6652 " bbbbbbbbbbbb);\n" 6653 "}", 6654 Style); 6655 6656 Style.AllowAllArgumentsOnNextLine = true; 6657 verifyFormat("void foo() {\n" 6658 " auto VariableWithReallyLongName = {\n" 6659 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n" 6660 "}", 6661 Style); 6662 Style.AllowAllArgumentsOnNextLine = false; 6663 verifyFormat("void foo() {\n" 6664 " auto VariableWithReallyLongName = {\n" 6665 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6666 " bbbbbbbbbbbb};\n" 6667 "}", 6668 Style); 6669 } 6670 6671 // This parameter should not affect declarations. 6672 Style.BinPackParameters = false; 6673 Style.AllowAllArgumentsOnNextLine = false; 6674 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6675 verifyFormat("void FunctionCallWithReallyLongName(\n" 6676 " int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);", 6677 Style); 6678 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6679 verifyFormat("void FunctionCallWithReallyLongName(\n" 6680 " int aaaaaaaaaaaaaaaaaaaaaaa,\n" 6681 " int bbbbbbbbbbbb);", 6682 Style); 6683 } 6684 6685 TEST_F(FormatTest, AllowAllArgumentsOnNextLineDontAlign) { 6686 // Check that AllowAllArgumentsOnNextLine is respected for both BAS_DontAlign 6687 // and BAS_Align. 6688 FormatStyle Style = getLLVMStyleWithColumns(35); 6689 StringRef Input = "functionCall(paramA, paramB, paramC);\n" 6690 "void functionDecl(int A, int B, int C);"; 6691 Style.AllowAllArgumentsOnNextLine = false; 6692 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6693 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6694 " paramC);\n" 6695 "void functionDecl(int A, int B,\n" 6696 " int C);"), 6697 format(Input, Style)); 6698 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 6699 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6700 " paramC);\n" 6701 "void functionDecl(int A, int B,\n" 6702 " int C);"), 6703 format(Input, Style)); 6704 // However, BAS_AlwaysBreak should take precedence over 6705 // AllowAllArgumentsOnNextLine. 6706 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 6707 EXPECT_EQ(StringRef("functionCall(\n" 6708 " paramA, paramB, paramC);\n" 6709 "void functionDecl(\n" 6710 " int A, int B, int C);"), 6711 format(Input, Style)); 6712 6713 // When AllowAllArgumentsOnNextLine is set, we prefer breaking before the 6714 // first argument. 6715 Style.AllowAllArgumentsOnNextLine = true; 6716 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 6717 EXPECT_EQ(StringRef("functionCall(\n" 6718 " paramA, paramB, paramC);\n" 6719 "void functionDecl(\n" 6720 " int A, int B, int C);"), 6721 format(Input, Style)); 6722 // It wouldn't fit on one line with aligned parameters so this setting 6723 // doesn't change anything for BAS_Align. 6724 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 6725 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6726 " paramC);\n" 6727 "void functionDecl(int A, int B,\n" 6728 " int C);"), 6729 format(Input, Style)); 6730 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6731 EXPECT_EQ(StringRef("functionCall(\n" 6732 " paramA, paramB, paramC);\n" 6733 "void functionDecl(\n" 6734 " int A, int B, int C);"), 6735 format(Input, Style)); 6736 } 6737 6738 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) { 6739 FormatStyle Style = getLLVMStyle(); 6740 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6741 6742 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}"); 6743 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}", 6744 getStyleWithColumns(Style, 45)); 6745 verifyFormat("Constructor() :\n" 6746 " Initializer(FitsOnTheLine) {}", 6747 getStyleWithColumns(Style, 44)); 6748 verifyFormat("Constructor() :\n" 6749 " Initializer(FitsOnTheLine) {}", 6750 getStyleWithColumns(Style, 43)); 6751 6752 verifyFormat("template <typename T>\n" 6753 "Constructor() : Initializer(FitsOnTheLine) {}", 6754 getStyleWithColumns(Style, 50)); 6755 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6756 verifyFormat( 6757 "SomeClass::Constructor() :\n" 6758 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 6759 Style); 6760 6761 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 6762 verifyFormat( 6763 "SomeClass::Constructor() :\n" 6764 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 6765 Style); 6766 6767 verifyFormat( 6768 "SomeClass::Constructor() :\n" 6769 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6770 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6771 Style); 6772 verifyFormat( 6773 "SomeClass::Constructor() :\n" 6774 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6775 " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 6776 Style); 6777 verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6778 " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 6779 " aaaaaaaaaa(aaaaaa) {}", 6780 Style); 6781 6782 verifyFormat("Constructor() :\n" 6783 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6784 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6785 " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6786 " aaaaaaaaaaaaaaaaaaaaaaa() {}", 6787 Style); 6788 6789 verifyFormat("Constructor() :\n" 6790 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6791 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6792 Style); 6793 6794 verifyFormat("Constructor(int Parameter = 0) :\n" 6795 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n" 6796 " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}", 6797 Style); 6798 verifyFormat("Constructor() :\n" 6799 " aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n" 6800 "}", 6801 getStyleWithColumns(Style, 60)); 6802 verifyFormat("Constructor() :\n" 6803 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6804 " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}", 6805 Style); 6806 6807 // Here a line could be saved by splitting the second initializer onto two 6808 // lines, but that is not desirable. 6809 verifyFormat("Constructor() :\n" 6810 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n" 6811 " aaaaaaaaaaa(aaaaaaaaaaa),\n" 6812 " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6813 Style); 6814 6815 FormatStyle OnePerLine = Style; 6816 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6817 verifyFormat("SomeClass::Constructor() :\n" 6818 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6819 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6820 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6821 OnePerLine); 6822 verifyFormat("SomeClass::Constructor() :\n" 6823 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n" 6824 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6825 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6826 OnePerLine); 6827 verifyFormat("MyClass::MyClass(int var) :\n" 6828 " some_var_(var), // 4 space indent\n" 6829 " some_other_var_(var + 1) { // lined up\n" 6830 "}", 6831 OnePerLine); 6832 verifyFormat("Constructor() :\n" 6833 " aaaaa(aaaaaa),\n" 6834 " aaaaa(aaaaaa),\n" 6835 " aaaaa(aaaaaa),\n" 6836 " aaaaa(aaaaaa),\n" 6837 " aaaaa(aaaaaa) {}", 6838 OnePerLine); 6839 verifyFormat("Constructor() :\n" 6840 " aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n" 6841 " aaaaaaaaaaaaaaaaaaaaaa) {}", 6842 OnePerLine); 6843 OnePerLine.BinPackParameters = false; 6844 verifyFormat("Constructor() :\n" 6845 " aaaaaaaaaaaaaaaaaaaaaaaa(\n" 6846 " aaaaaaaaaaa().aaa(),\n" 6847 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6848 OnePerLine); 6849 OnePerLine.ColumnLimit = 60; 6850 verifyFormat("Constructor() :\n" 6851 " aaaaaaaaaaaaaaaaaaaa(a),\n" 6852 " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}", 6853 OnePerLine); 6854 6855 EXPECT_EQ("Constructor() :\n" 6856 " // Comment forcing unwanted break.\n" 6857 " aaaa(aaaa) {}", 6858 format("Constructor() :\n" 6859 " // Comment forcing unwanted break.\n" 6860 " aaaa(aaaa) {}", 6861 Style)); 6862 6863 Style.ColumnLimit = 0; 6864 verifyFormat("SomeClass::Constructor() :\n" 6865 " a(a) {}", 6866 Style); 6867 verifyFormat("SomeClass::Constructor() noexcept :\n" 6868 " a(a) {}", 6869 Style); 6870 verifyFormat("SomeClass::Constructor() :\n" 6871 " a(a), b(b), c(c) {}", 6872 Style); 6873 verifyFormat("SomeClass::Constructor() :\n" 6874 " a(a) {\n" 6875 " foo();\n" 6876 " bar();\n" 6877 "}", 6878 Style); 6879 6880 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 6881 verifyFormat("SomeClass::Constructor() :\n" 6882 " a(a), b(b), c(c) {\n" 6883 "}", 6884 Style); 6885 verifyFormat("SomeClass::Constructor() :\n" 6886 " a(a) {\n" 6887 "}", 6888 Style); 6889 6890 Style.ColumnLimit = 80; 6891 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 6892 Style.ConstructorInitializerIndentWidth = 2; 6893 verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style); 6894 verifyFormat("SomeClass::Constructor() :\n" 6895 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6896 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}", 6897 Style); 6898 6899 // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as 6900 // well 6901 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 6902 verifyFormat( 6903 "class SomeClass\n" 6904 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6905 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 6906 Style); 6907 Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma; 6908 verifyFormat( 6909 "class SomeClass\n" 6910 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6911 " , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 6912 Style); 6913 Style.BreakInheritanceList = FormatStyle::BILS_AfterColon; 6914 verifyFormat( 6915 "class SomeClass :\n" 6916 " public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6917 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 6918 Style); 6919 Style.BreakInheritanceList = FormatStyle::BILS_AfterComma; 6920 verifyFormat( 6921 "class SomeClass\n" 6922 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6923 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 6924 Style); 6925 } 6926 6927 #ifndef EXPENSIVE_CHECKS 6928 // Expensive checks enables libstdc++ checking which includes validating the 6929 // state of ranges used in std::priority_queue - this blows out the 6930 // runtime/scalability of the function and makes this test unacceptably slow. 6931 TEST_F(FormatTest, MemoizationTests) { 6932 // This breaks if the memoization lookup does not take \c Indent and 6933 // \c LastSpace into account. 6934 verifyFormat( 6935 "extern CFRunLoopTimerRef\n" 6936 "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n" 6937 " CFTimeInterval interval, CFOptionFlags flags,\n" 6938 " CFIndex order, CFRunLoopTimerCallBack callout,\n" 6939 " CFRunLoopTimerContext *context) {}"); 6940 6941 // Deep nesting somewhat works around our memoization. 6942 verifyFormat( 6943 "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 6944 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 6945 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 6946 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 6947 " aaaaa())))))))))))))))))))))))))))))))))))))));", 6948 getLLVMStyleWithColumns(65)); 6949 verifyFormat( 6950 "aaaaa(\n" 6951 " aaaaa,\n" 6952 " aaaaa(\n" 6953 " aaaaa,\n" 6954 " aaaaa(\n" 6955 " aaaaa,\n" 6956 " aaaaa(\n" 6957 " aaaaa,\n" 6958 " aaaaa(\n" 6959 " aaaaa,\n" 6960 " aaaaa(\n" 6961 " aaaaa,\n" 6962 " aaaaa(\n" 6963 " aaaaa,\n" 6964 " aaaaa(\n" 6965 " aaaaa,\n" 6966 " aaaaa(\n" 6967 " aaaaa,\n" 6968 " aaaaa(\n" 6969 " aaaaa,\n" 6970 " aaaaa(\n" 6971 " aaaaa,\n" 6972 " aaaaa(\n" 6973 " aaaaa,\n" 6974 " aaaaa))))))))))));", 6975 getLLVMStyleWithColumns(65)); 6976 verifyFormat( 6977 "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" 6978 " a),\n" 6979 " a),\n" 6980 " a),\n" 6981 " a),\n" 6982 " a),\n" 6983 " a),\n" 6984 " a),\n" 6985 " a),\n" 6986 " a),\n" 6987 " a),\n" 6988 " a),\n" 6989 " a),\n" 6990 " a),\n" 6991 " a),\n" 6992 " a),\n" 6993 " a),\n" 6994 " a)", 6995 getLLVMStyleWithColumns(65)); 6996 6997 // This test takes VERY long when memoization is broken. 6998 FormatStyle OnePerLine = getLLVMStyle(); 6999 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 7000 OnePerLine.BinPackParameters = false; 7001 std::string input = "Constructor()\n" 7002 " : aaaa(a,\n"; 7003 for (unsigned i = 0, e = 80; i != e; ++i) { 7004 input += " a,\n"; 7005 } 7006 input += " a) {}"; 7007 verifyFormat(input, OnePerLine); 7008 } 7009 #endif 7010 7011 TEST_F(FormatTest, BreaksAsHighAsPossible) { 7012 verifyFormat( 7013 "void f() {\n" 7014 " if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n" 7015 " (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n" 7016 " f();\n" 7017 "}"); 7018 verifyFormat("if (Intervals[i].getRange().getFirst() <\n" 7019 " Intervals[i - 1].getRange().getLast()) {\n}"); 7020 } 7021 7022 TEST_F(FormatTest, BreaksFunctionDeclarations) { 7023 // Principially, we break function declarations in a certain order: 7024 // 1) break amongst arguments. 7025 verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n" 7026 " Cccccccccccccc cccccccccccccc);"); 7027 verifyFormat("template <class TemplateIt>\n" 7028 "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n" 7029 " TemplateIt *stop) {}"); 7030 7031 // 2) break after return type. 7032 verifyFormat( 7033 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7034 "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);", 7035 getGoogleStyle()); 7036 7037 // 3) break after (. 7038 verifyFormat( 7039 "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n" 7040 " Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);", 7041 getGoogleStyle()); 7042 7043 // 4) break before after nested name specifiers. 7044 verifyFormat( 7045 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7046 "SomeClasssssssssssssssssssssssssssssssssssssss::\n" 7047 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);", 7048 getGoogleStyle()); 7049 7050 // However, there are exceptions, if a sufficient amount of lines can be 7051 // saved. 7052 // FIXME: The precise cut-offs wrt. the number of saved lines might need some 7053 // more adjusting. 7054 verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n" 7055 " Cccccccccccccc cccccccccc,\n" 7056 " Cccccccccccccc cccccccccc,\n" 7057 " Cccccccccccccc cccccccccc,\n" 7058 " Cccccccccccccc cccccccccc);"); 7059 verifyFormat( 7060 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7061 "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7062 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7063 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);", 7064 getGoogleStyle()); 7065 verifyFormat( 7066 "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n" 7067 " Cccccccccccccc cccccccccc,\n" 7068 " Cccccccccccccc cccccccccc,\n" 7069 " Cccccccccccccc cccccccccc,\n" 7070 " Cccccccccccccc cccccccccc,\n" 7071 " Cccccccccccccc cccccccccc,\n" 7072 " Cccccccccccccc cccccccccc);"); 7073 verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7074 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7075 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7076 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7077 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);"); 7078 7079 // Break after multi-line parameters. 7080 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7081 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7082 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7083 " bbbb bbbb);"); 7084 verifyFormat("void SomeLoooooooooooongFunction(\n" 7085 " std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n" 7086 " aaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7087 " int bbbbbbbbbbbbb);"); 7088 7089 // Treat overloaded operators like other functions. 7090 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 7091 "operator>(const SomeLoooooooooooooooooooooooooogType &other);"); 7092 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 7093 "operator>>(const SomeLooooooooooooooooooooooooogType &other);"); 7094 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 7095 "operator<<(const SomeLooooooooooooooooooooooooogType &other);"); 7096 verifyGoogleFormat( 7097 "SomeLoooooooooooooooooooooooooooooogType operator>>(\n" 7098 " const SomeLooooooooogType &a, const SomeLooooooooogType &b);"); 7099 verifyGoogleFormat( 7100 "SomeLoooooooooooooooooooooooooooooogType operator<<(\n" 7101 " const SomeLooooooooogType &a, const SomeLooooooooogType &b);"); 7102 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7103 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);"); 7104 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n" 7105 "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);"); 7106 verifyGoogleFormat( 7107 "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n" 7108 "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7109 " bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}"); 7110 verifyGoogleFormat("template <typename T>\n" 7111 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7112 "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n" 7113 " aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);"); 7114 7115 FormatStyle Style = getLLVMStyle(); 7116 Style.PointerAlignment = FormatStyle::PAS_Left; 7117 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7118 " aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}", 7119 Style); 7120 verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n" 7121 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7122 Style); 7123 } 7124 7125 TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) { 7126 // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516: 7127 // Prefer keeping `::` followed by `operator` together. 7128 EXPECT_EQ("const aaaa::bbbbbbb &\n" 7129 "ccccccccc::operator++() {\n" 7130 " stuff();\n" 7131 "}", 7132 format("const aaaa::bbbbbbb\n" 7133 "&ccccccccc::operator++() { stuff(); }", 7134 getLLVMStyleWithColumns(40))); 7135 } 7136 7137 TEST_F(FormatTest, TrailingReturnType) { 7138 verifyFormat("auto foo() -> int;\n"); 7139 // correct trailing return type spacing 7140 verifyFormat("auto operator->() -> int;\n"); 7141 verifyFormat("auto operator++(int) -> int;\n"); 7142 7143 verifyFormat("struct S {\n" 7144 " auto bar() const -> int;\n" 7145 "};"); 7146 verifyFormat("template <size_t Order, typename T>\n" 7147 "auto load_img(const std::string &filename)\n" 7148 " -> alias::tensor<Order, T, mem::tag::cpu> {}"); 7149 verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n" 7150 " -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}"); 7151 verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}"); 7152 verifyFormat("template <typename T>\n" 7153 "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n" 7154 " -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());"); 7155 7156 // Not trailing return types. 7157 verifyFormat("void f() { auto a = b->c(); }"); 7158 verifyFormat("auto a = p->foo();"); 7159 verifyFormat("int a = p->foo();"); 7160 verifyFormat("auto lmbd = [] NOEXCEPT -> int { return 0; };"); 7161 } 7162 7163 TEST_F(FormatTest, DeductionGuides) { 7164 verifyFormat("template <class T> A(const T &, const T &) -> A<T &>;"); 7165 verifyFormat("template <class T> explicit A(T &, T &&) -> A<T>;"); 7166 verifyFormat("template <class... Ts> S(Ts...) -> S<Ts...>;"); 7167 verifyFormat( 7168 "template <class... T>\n" 7169 "array(T &&...t) -> array<std::common_type_t<T...>, sizeof...(T)>;"); 7170 verifyFormat("template <class T> A() -> A<decltype(p->foo<3>())>;"); 7171 verifyFormat("template <class T> A() -> A<decltype(foo<traits<1>>)>;"); 7172 verifyFormat("template <class T> A() -> A<sizeof(p->foo<1>)>;"); 7173 verifyFormat("template <class T> A() -> A<(3 < 2)>;"); 7174 verifyFormat("template <class T> A() -> A<((3) < (2))>;"); 7175 verifyFormat("template <class T> x() -> x<1>;"); 7176 verifyFormat("template <class T> explicit x(T &) -> x<1>;"); 7177 7178 // Ensure not deduction guides. 7179 verifyFormat("c()->f<int>();"); 7180 verifyFormat("x()->foo<1>;"); 7181 verifyFormat("x = p->foo<3>();"); 7182 verifyFormat("x()->x<1>();"); 7183 verifyFormat("x()->x<1>;"); 7184 } 7185 7186 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) { 7187 // Avoid breaking before trailing 'const' or other trailing annotations, if 7188 // they are not function-like. 7189 FormatStyle Style = getGoogleStyleWithColumns(47); 7190 verifyFormat("void someLongFunction(\n" 7191 " int someLoooooooooooooongParameter) const {\n}", 7192 getLLVMStyleWithColumns(47)); 7193 verifyFormat("LoooooongReturnType\n" 7194 "someLoooooooongFunction() const {}", 7195 getLLVMStyleWithColumns(47)); 7196 verifyFormat("LoooooongReturnType someLoooooooongFunction()\n" 7197 " const {}", 7198 Style); 7199 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7200 " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;"); 7201 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7202 " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;"); 7203 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7204 " aaaaa aaaaaaaaaaaaaaaaaaaa) override final;"); 7205 verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n" 7206 " aaaaaaaaaaa aaaaa) const override;"); 7207 verifyGoogleFormat( 7208 "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7209 " const override;"); 7210 7211 // Even if the first parameter has to be wrapped. 7212 verifyFormat("void someLongFunction(\n" 7213 " int someLongParameter) const {}", 7214 getLLVMStyleWithColumns(46)); 7215 verifyFormat("void someLongFunction(\n" 7216 " int someLongParameter) const {}", 7217 Style); 7218 verifyFormat("void someLongFunction(\n" 7219 " int someLongParameter) override {}", 7220 Style); 7221 verifyFormat("void someLongFunction(\n" 7222 " int someLongParameter) OVERRIDE {}", 7223 Style); 7224 verifyFormat("void someLongFunction(\n" 7225 " int someLongParameter) final {}", 7226 Style); 7227 verifyFormat("void someLongFunction(\n" 7228 " int someLongParameter) FINAL {}", 7229 Style); 7230 verifyFormat("void someLongFunction(\n" 7231 " int parameter) const override {}", 7232 Style); 7233 7234 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 7235 verifyFormat("void someLongFunction(\n" 7236 " int someLongParameter) const\n" 7237 "{\n" 7238 "}", 7239 Style); 7240 7241 Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 7242 verifyFormat("void someLongFunction(\n" 7243 " int someLongParameter) const\n" 7244 " {\n" 7245 " }", 7246 Style); 7247 7248 // Unless these are unknown annotations. 7249 verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n" 7250 " aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7251 " LONG_AND_UGLY_ANNOTATION;"); 7252 7253 // Breaking before function-like trailing annotations is fine to keep them 7254 // close to their arguments. 7255 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7256 " LOCKS_EXCLUDED(aaaaaaaaaaaaa);"); 7257 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n" 7258 " LOCKS_EXCLUDED(aaaaaaaaaaaaa);"); 7259 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n" 7260 " LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}"); 7261 verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n" 7262 " AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);"); 7263 verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});"); 7264 7265 verifyFormat( 7266 "void aaaaaaaaaaaaaaaaaa()\n" 7267 " __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n" 7268 " aaaaaaaaaaaaaaaaaaaaaaaaa));"); 7269 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7270 " __attribute__((unused));"); 7271 verifyGoogleFormat( 7272 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7273 " GUARDED_BY(aaaaaaaaaaaa);"); 7274 verifyGoogleFormat( 7275 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7276 " GUARDED_BY(aaaaaaaaaaaa);"); 7277 verifyGoogleFormat( 7278 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n" 7279 " aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7280 verifyGoogleFormat( 7281 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n" 7282 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7283 } 7284 7285 TEST_F(FormatTest, FunctionAnnotations) { 7286 verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7287 "int OldFunction(const string ¶meter) {}"); 7288 verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7289 "string OldFunction(const string ¶meter) {}"); 7290 verifyFormat("template <typename T>\n" 7291 "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7292 "string OldFunction(const string ¶meter) {}"); 7293 7294 // Not function annotations. 7295 verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7296 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"); 7297 verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n" 7298 " ThisIsATestWithAReallyReallyReallyReallyLongName) {}"); 7299 verifyFormat("MACRO(abc).function() // wrap\n" 7300 " << abc;"); 7301 verifyFormat("MACRO(abc)->function() // wrap\n" 7302 " << abc;"); 7303 verifyFormat("MACRO(abc)::function() // wrap\n" 7304 " << abc;"); 7305 } 7306 7307 TEST_F(FormatTest, BreaksDesireably) { 7308 verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n" 7309 " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n" 7310 " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}"); 7311 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7312 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 7313 "}"); 7314 7315 verifyFormat( 7316 "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7317 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 7318 7319 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7320 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7321 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7322 7323 verifyFormat( 7324 "aaaaaaaa(aaaaaaaaaaaaa,\n" 7325 " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7326 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n" 7327 " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7328 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));"); 7329 7330 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 7331 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7332 7333 verifyFormat( 7334 "void f() {\n" 7335 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n" 7336 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 7337 "}"); 7338 verifyFormat( 7339 "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7340 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7341 verifyFormat( 7342 "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7343 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7344 verifyFormat( 7345 "aaaaaa(aaa,\n" 7346 " new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7347 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7348 " aaaa);"); 7349 verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7350 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7351 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7352 7353 // Indent consistently independent of call expression and unary operator. 7354 verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7355 " dddddddddddddddddddddddddddddd));"); 7356 verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7357 " dddddddddddddddddddddddddddddd));"); 7358 verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n" 7359 " dddddddddddddddddddddddddddddd));"); 7360 7361 // This test case breaks on an incorrect memoization, i.e. an optimization not 7362 // taking into account the StopAt value. 7363 verifyFormat( 7364 "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7365 " aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7366 " aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7367 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7368 7369 verifyFormat("{\n {\n {\n" 7370 " Annotation.SpaceRequiredBefore =\n" 7371 " Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n" 7372 " Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n" 7373 " }\n }\n}"); 7374 7375 // Break on an outer level if there was a break on an inner level. 7376 EXPECT_EQ("f(g(h(a, // comment\n" 7377 " b, c),\n" 7378 " d, e),\n" 7379 " x, y);", 7380 format("f(g(h(a, // comment\n" 7381 " b, c), d, e), x, y);")); 7382 7383 // Prefer breaking similar line breaks. 7384 verifyFormat( 7385 "const int kTrackingOptions = NSTrackingMouseMoved |\n" 7386 " NSTrackingMouseEnteredAndExited |\n" 7387 " NSTrackingActiveAlways;"); 7388 } 7389 7390 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) { 7391 FormatStyle NoBinPacking = getGoogleStyle(); 7392 NoBinPacking.BinPackParameters = false; 7393 NoBinPacking.BinPackArguments = true; 7394 verifyFormat("void f() {\n" 7395 " f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n" 7396 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 7397 "}", 7398 NoBinPacking); 7399 verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n" 7400 " int aaaaaaaaaaaaaaaaaaaa,\n" 7401 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7402 NoBinPacking); 7403 7404 NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false; 7405 verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7406 " vector<int> bbbbbbbbbbbbbbb);", 7407 NoBinPacking); 7408 // FIXME: This behavior difference is probably not wanted. However, currently 7409 // we cannot distinguish BreakBeforeParameter being set because of the wrapped 7410 // template arguments from BreakBeforeParameter being set because of the 7411 // one-per-line formatting. 7412 verifyFormat( 7413 "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n" 7414 " aaaaaaaaaa> aaaaaaaaaa);", 7415 NoBinPacking); 7416 verifyFormat( 7417 "void fffffffffff(\n" 7418 " aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n" 7419 " aaaaaaaaaa);"); 7420 } 7421 7422 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) { 7423 FormatStyle NoBinPacking = getGoogleStyle(); 7424 NoBinPacking.BinPackParameters = false; 7425 NoBinPacking.BinPackArguments = false; 7426 verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n" 7427 " aaaaaaaaaaaaaaaaaaaa,\n" 7428 " aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);", 7429 NoBinPacking); 7430 verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n" 7431 " aaaaaaaaaaaaa,\n" 7432 " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));", 7433 NoBinPacking); 7434 verifyFormat( 7435 "aaaaaaaa(aaaaaaaaaaaaa,\n" 7436 " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7437 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n" 7438 " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7439 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));", 7440 NoBinPacking); 7441 verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n" 7442 " .aaaaaaaaaaaaaaaaaa();", 7443 NoBinPacking); 7444 verifyFormat("void f() {\n" 7445 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7446 " aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n" 7447 "}", 7448 NoBinPacking); 7449 7450 verifyFormat( 7451 "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7452 " aaaaaaaaaaaa,\n" 7453 " aaaaaaaaaaaa);", 7454 NoBinPacking); 7455 verifyFormat( 7456 "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n" 7457 " ddddddddddddddddddddddddddddd),\n" 7458 " test);", 7459 NoBinPacking); 7460 7461 verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n" 7462 " aaaaaaaaaaaaaaaaaaaaaaa,\n" 7463 " aaaaaaaaaaaaaaaaaaaaaaa>\n" 7464 " aaaaaaaaaaaaaaaaaa;", 7465 NoBinPacking); 7466 verifyFormat("a(\"a\"\n" 7467 " \"a\",\n" 7468 " a);"); 7469 7470 NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false; 7471 verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n" 7472 " aaaaaaaaa,\n" 7473 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7474 NoBinPacking); 7475 verifyFormat( 7476 "void f() {\n" 7477 " aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n" 7478 " .aaaaaaa();\n" 7479 "}", 7480 NoBinPacking); 7481 verifyFormat( 7482 "template <class SomeType, class SomeOtherType>\n" 7483 "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}", 7484 NoBinPacking); 7485 } 7486 7487 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) { 7488 FormatStyle Style = getLLVMStyleWithColumns(15); 7489 Style.ExperimentalAutoDetectBinPacking = true; 7490 EXPECT_EQ("aaa(aaaa,\n" 7491 " aaaa,\n" 7492 " aaaa);\n" 7493 "aaa(aaaa,\n" 7494 " aaaa,\n" 7495 " aaaa);", 7496 format("aaa(aaaa,\n" // one-per-line 7497 " aaaa,\n" 7498 " aaaa );\n" 7499 "aaa(aaaa, aaaa, aaaa);", // inconclusive 7500 Style)); 7501 EXPECT_EQ("aaa(aaaa, aaaa,\n" 7502 " aaaa);\n" 7503 "aaa(aaaa, aaaa,\n" 7504 " aaaa);", 7505 format("aaa(aaaa, aaaa,\n" // bin-packed 7506 " aaaa );\n" 7507 "aaa(aaaa, aaaa, aaaa);", // inconclusive 7508 Style)); 7509 } 7510 7511 TEST_F(FormatTest, FormatsBuilderPattern) { 7512 verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n" 7513 " .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n" 7514 " .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n" 7515 " .StartsWith(\".init\", ORDER_INIT)\n" 7516 " .StartsWith(\".fini\", ORDER_FINI)\n" 7517 " .StartsWith(\".hash\", ORDER_HASH)\n" 7518 " .Default(ORDER_TEXT);\n"); 7519 7520 verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n" 7521 " aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();"); 7522 verifyFormat("aaaaaaa->aaaaaaa\n" 7523 " ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7524 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7525 " ->aaaaaaaa(aaaaaaaaaaaaaaa);"); 7526 verifyFormat( 7527 "aaaaaaa->aaaaaaa\n" 7528 " ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7529 " ->aaaaaaaa(aaaaaaaaaaaaaaa);"); 7530 verifyFormat( 7531 "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n" 7532 " aaaaaaaaaaaaaa);"); 7533 verifyFormat( 7534 "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n" 7535 " aaaaaa->aaaaaaaaaaaa()\n" 7536 " ->aaaaaaaaaaaaaaaa(\n" 7537 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7538 " ->aaaaaaaaaaaaaaaaa();"); 7539 verifyGoogleFormat( 7540 "void f() {\n" 7541 " someo->Add((new util::filetools::Handler(dir))\n" 7542 " ->OnEvent1(NewPermanentCallback(\n" 7543 " this, &HandlerHolderClass::EventHandlerCBA))\n" 7544 " ->OnEvent2(NewPermanentCallback(\n" 7545 " this, &HandlerHolderClass::EventHandlerCBB))\n" 7546 " ->OnEvent3(NewPermanentCallback(\n" 7547 " this, &HandlerHolderClass::EventHandlerCBC))\n" 7548 " ->OnEvent5(NewPermanentCallback(\n" 7549 " this, &HandlerHolderClass::EventHandlerCBD))\n" 7550 " ->OnEvent6(NewPermanentCallback(\n" 7551 " this, &HandlerHolderClass::EventHandlerCBE)));\n" 7552 "}"); 7553 7554 verifyFormat( 7555 "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();"); 7556 verifyFormat("aaaaaaaaaaaaaaa()\n" 7557 " .aaaaaaaaaaaaaaa()\n" 7558 " .aaaaaaaaaaaaaaa()\n" 7559 " .aaaaaaaaaaaaaaa()\n" 7560 " .aaaaaaaaaaaaaaa();"); 7561 verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7562 " .aaaaaaaaaaaaaaa()\n" 7563 " .aaaaaaaaaaaaaaa()\n" 7564 " .aaaaaaaaaaaaaaa();"); 7565 verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7566 " .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7567 " .aaaaaaaaaaaaaaa();"); 7568 verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n" 7569 " ->aaaaaaaaaaaaaae(0)\n" 7570 " ->aaaaaaaaaaaaaaa();"); 7571 7572 // Don't linewrap after very short segments. 7573 verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7574 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7575 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7576 verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7577 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7578 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7579 verifyFormat("aaa()\n" 7580 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7581 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7582 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7583 7584 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n" 7585 " .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7586 " .has<bbbbbbbbbbbbbbbbbbbbb>();"); 7587 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n" 7588 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 7589 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();"); 7590 7591 // Prefer not to break after empty parentheses. 7592 verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n" 7593 " First->LastNewlineOffset);"); 7594 7595 // Prefer not to create "hanging" indents. 7596 verifyFormat( 7597 "return !soooooooooooooome_map\n" 7598 " .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7599 " .second;"); 7600 verifyFormat( 7601 "return aaaaaaaaaaaaaaaa\n" 7602 " .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n" 7603 " .aaaa(aaaaaaaaaaaaaa);"); 7604 // No hanging indent here. 7605 verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n" 7606 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7607 verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n" 7608 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7609 verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n" 7610 " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7611 getLLVMStyleWithColumns(60)); 7612 verifyFormat("aaaaaaaaaaaaaaaaaa\n" 7613 " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n" 7614 " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7615 getLLVMStyleWithColumns(59)); 7616 verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7617 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7618 " .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7619 7620 // Dont break if only closing statements before member call 7621 verifyFormat("test() {\n" 7622 " ([]() -> {\n" 7623 " int b = 32;\n" 7624 " return 3;\n" 7625 " }).foo();\n" 7626 "}"); 7627 verifyFormat("test() {\n" 7628 " (\n" 7629 " []() -> {\n" 7630 " int b = 32;\n" 7631 " return 3;\n" 7632 " },\n" 7633 " foo, bar)\n" 7634 " .foo();\n" 7635 "}"); 7636 verifyFormat("test() {\n" 7637 " ([]() -> {\n" 7638 " int b = 32;\n" 7639 " return 3;\n" 7640 " })\n" 7641 " .foo()\n" 7642 " .bar();\n" 7643 "}"); 7644 verifyFormat("test() {\n" 7645 " ([]() -> {\n" 7646 " int b = 32;\n" 7647 " return 3;\n" 7648 " })\n" 7649 " .foo(\"aaaaaaaaaaaaaaaaa\"\n" 7650 " \"bbbb\");\n" 7651 "}", 7652 getLLVMStyleWithColumns(30)); 7653 } 7654 7655 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) { 7656 verifyFormat( 7657 "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 7658 " bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}"); 7659 verifyFormat( 7660 "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n" 7661 " bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}"); 7662 7663 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" 7664 " ccccccccccccccccccccccccc) {\n}"); 7665 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n" 7666 " ccccccccccccccccccccccccc) {\n}"); 7667 7668 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" 7669 " ccccccccccccccccccccccccc) {\n}"); 7670 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n" 7671 " ccccccccccccccccccccccccc) {\n}"); 7672 7673 verifyFormat( 7674 "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n" 7675 " ccccccccccccccccccccccccc) {\n}"); 7676 verifyFormat( 7677 "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n" 7678 " ccccccccccccccccccccccccc) {\n}"); 7679 7680 verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n" 7681 " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n" 7682 " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n" 7683 " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;"); 7684 verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n" 7685 " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n" 7686 " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n" 7687 " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;"); 7688 7689 verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n" 7690 " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n" 7691 " aaaaaaaaaaaaaaa != aa) {\n}"); 7692 verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n" 7693 " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n" 7694 " aaaaaaaaaaaaaaa != aa) {\n}"); 7695 } 7696 7697 TEST_F(FormatTest, BreaksAfterAssignments) { 7698 verifyFormat( 7699 "unsigned Cost =\n" 7700 " TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n" 7701 " SI->getPointerAddressSpaceee());\n"); 7702 verifyFormat( 7703 "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n" 7704 " Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());"); 7705 7706 verifyFormat( 7707 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n" 7708 " aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);"); 7709 verifyFormat("unsigned OriginalStartColumn =\n" 7710 " SourceMgr.getSpellingColumnNumber(\n" 7711 " Current.FormatTok.getStartOfNonWhitespace()) -\n" 7712 " 1;"); 7713 } 7714 7715 TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) { 7716 FormatStyle Style = getLLVMStyle(); 7717 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 7718 " bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;", 7719 Style); 7720 7721 Style.PenaltyBreakAssignment = 20; 7722 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n" 7723 " cccccccccccccccccccccccccc;", 7724 Style); 7725 } 7726 7727 TEST_F(FormatTest, AlignsAfterAssignments) { 7728 verifyFormat( 7729 "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7730 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7731 verifyFormat( 7732 "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7733 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7734 verifyFormat( 7735 "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7736 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7737 verifyFormat( 7738 "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7739 " aaaaaaaaaaaaaaaaaaaaaaaaa);"); 7740 verifyFormat( 7741 "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n" 7742 " aaaaaaaaaaaaaaaaaaaaaaaa +\n" 7743 " aaaaaaaaaaaaaaaaaaaaaaaa;"); 7744 } 7745 7746 TEST_F(FormatTest, AlignsAfterReturn) { 7747 verifyFormat( 7748 "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7749 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7750 verifyFormat( 7751 "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7752 " aaaaaaaaaaaaaaaaaaaaaaaaa);"); 7753 verifyFormat( 7754 "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n" 7755 " aaaaaaaaaaaaaaaaaaaaaa();"); 7756 verifyFormat( 7757 "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n" 7758 " aaaaaaaaaaaaaaaaaaaaaa());"); 7759 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7760 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7761 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7762 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n" 7763 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7764 verifyFormat("return\n" 7765 " // true if code is one of a or b.\n" 7766 " code == a || code == b;"); 7767 } 7768 7769 TEST_F(FormatTest, AlignsAfterOpenBracket) { 7770 verifyFormat( 7771 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n" 7772 " aaaaaaaaa aaaaaaa) {}"); 7773 verifyFormat( 7774 "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n" 7775 " aaaaaaaaaaa aaaaaaaaa);"); 7776 verifyFormat( 7777 "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n" 7778 " aaaaaaaaaaaaaaaaaaaaa));"); 7779 FormatStyle Style = getLLVMStyle(); 7780 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 7781 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7782 " aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}", 7783 Style); 7784 verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n" 7785 " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);", 7786 Style); 7787 verifyFormat("SomeLongVariableName->someFunction(\n" 7788 " foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));", 7789 Style); 7790 verifyFormat( 7791 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n" 7792 " aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7793 Style); 7794 verifyFormat( 7795 "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n" 7796 " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7797 Style); 7798 verifyFormat( 7799 "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n" 7800 " aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));", 7801 Style); 7802 7803 verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n" 7804 " ccccccc(aaaaaaaaaaaaaaaaa, //\n" 7805 " b));", 7806 Style); 7807 7808 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 7809 Style.BinPackArguments = false; 7810 Style.BinPackParameters = false; 7811 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7812 " aaaaaaaaaaa aaaaaaaa,\n" 7813 " aaaaaaaaa aaaaaaa,\n" 7814 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7815 Style); 7816 verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n" 7817 " aaaaaaaaaaa aaaaaaaaa,\n" 7818 " aaaaaaaaaaa aaaaaaaaa,\n" 7819 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7820 Style); 7821 verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n" 7822 " aaaaaaaaaaaaaaa,\n" 7823 " aaaaaaaaaaaaaaaaaaaaa,\n" 7824 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));", 7825 Style); 7826 verifyFormat( 7827 "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n" 7828 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));", 7829 Style); 7830 verifyFormat( 7831 "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n" 7832 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));", 7833 Style); 7834 verifyFormat( 7835 "aaaaaaaaaaaaaaaaaaaaaaaa(\n" 7836 " aaaaaaaaaaaaaaaaaaaaa(\n" 7837 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n" 7838 " aaaaaaaaaaaaaaaa);", 7839 Style); 7840 verifyFormat( 7841 "aaaaaaaaaaaaaaaaaaaaaaaa(\n" 7842 " aaaaaaaaaaaaaaaaaaaaa(\n" 7843 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n" 7844 " aaaaaaaaaaaaaaaa);", 7845 Style); 7846 } 7847 7848 TEST_F(FormatTest, ParenthesesAndOperandAlignment) { 7849 FormatStyle Style = getLLVMStyleWithColumns(40); 7850 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 7851 " bbbbbbbbbbbbbbbbbbbbbb);", 7852 Style); 7853 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 7854 Style.AlignOperands = FormatStyle::OAS_DontAlign; 7855 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 7856 " bbbbbbbbbbbbbbbbbbbbbb);", 7857 Style); 7858 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 7859 Style.AlignOperands = FormatStyle::OAS_Align; 7860 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 7861 " bbbbbbbbbbbbbbbbbbbbbb);", 7862 Style); 7863 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 7864 Style.AlignOperands = FormatStyle::OAS_DontAlign; 7865 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 7866 " bbbbbbbbbbbbbbbbbbbbbb);", 7867 Style); 7868 } 7869 7870 TEST_F(FormatTest, BreaksConditionalExpressions) { 7871 verifyFormat( 7872 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7873 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7874 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7875 verifyFormat( 7876 "aaaa(aaaaaaaaaa, aaaaaaaa,\n" 7877 " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7878 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7879 verifyFormat( 7880 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7881 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7882 verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n" 7883 " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7884 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7885 verifyFormat( 7886 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n" 7887 " : aaaaaaaaaaaaa);"); 7888 verifyFormat( 7889 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7890 " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7891 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7892 " aaaaaaaaaaaaa);"); 7893 verifyFormat( 7894 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7895 " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7896 " aaaaaaaaaaaaa);"); 7897 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7898 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7899 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7900 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7901 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7902 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7903 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7904 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7905 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7906 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7907 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7908 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7909 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7910 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7911 " ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7912 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7913 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7914 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7915 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7916 " : aaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7917 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n" 7918 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7919 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7920 " : aaaaaaaaaaaaaaaa;"); 7921 verifyFormat( 7922 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7923 " ? aaaaaaaaaaaaaaa\n" 7924 " : aaaaaaaaaaaaaaa;"); 7925 verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n" 7926 " aaaaaaaaa\n" 7927 " ? b\n" 7928 " : c);"); 7929 verifyFormat("return aaaa == bbbb\n" 7930 " // comment\n" 7931 " ? aaaa\n" 7932 " : bbbb;"); 7933 verifyFormat("unsigned Indent =\n" 7934 " format(TheLine.First,\n" 7935 " IndentForLevel[TheLine.Level] >= 0\n" 7936 " ? IndentForLevel[TheLine.Level]\n" 7937 " : TheLine * 2,\n" 7938 " TheLine.InPPDirective, PreviousEndOfLineColumn);", 7939 getLLVMStyleWithColumns(60)); 7940 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n" 7941 " ? aaaaaaaaaaaaaaa\n" 7942 " : bbbbbbbbbbbbbbb //\n" 7943 " ? ccccccccccccccc\n" 7944 " : ddddddddddddddd;"); 7945 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n" 7946 " ? aaaaaaaaaaaaaaa\n" 7947 " : (bbbbbbbbbbbbbbb //\n" 7948 " ? ccccccccccccccc\n" 7949 " : ddddddddddddddd);"); 7950 verifyFormat( 7951 "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7952 " ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7953 " aaaaaaaaaaaaaaaaaaaaa +\n" 7954 " aaaaaaaaaaaaaaaaaaaaa\n" 7955 " : aaaaaaaaaa;"); 7956 verifyFormat( 7957 "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7958 " : aaaaaaaaaaaaaaaaaaaaaa\n" 7959 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7960 7961 FormatStyle NoBinPacking = getLLVMStyle(); 7962 NoBinPacking.BinPackArguments = false; 7963 verifyFormat( 7964 "void f() {\n" 7965 " g(aaa,\n" 7966 " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n" 7967 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7968 " ? aaaaaaaaaaaaaaa\n" 7969 " : aaaaaaaaaaaaaaa);\n" 7970 "}", 7971 NoBinPacking); 7972 verifyFormat( 7973 "void f() {\n" 7974 " g(aaa,\n" 7975 " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n" 7976 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7977 " ?: aaaaaaaaaaaaaaa);\n" 7978 "}", 7979 NoBinPacking); 7980 7981 verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n" 7982 " // comment.\n" 7983 " ccccccccccccccccccccccccccccccccccccccc\n" 7984 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7985 " : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);"); 7986 7987 // Assignments in conditional expressions. Apparently not uncommon :-(. 7988 verifyFormat("return a != b\n" 7989 " // comment\n" 7990 " ? a = b\n" 7991 " : a = b;"); 7992 verifyFormat("return a != b\n" 7993 " // comment\n" 7994 " ? a = a != b\n" 7995 " // comment\n" 7996 " ? a = b\n" 7997 " : a\n" 7998 " : a;\n"); 7999 verifyFormat("return a != b\n" 8000 " // comment\n" 8001 " ? a\n" 8002 " : a = a != b\n" 8003 " // comment\n" 8004 " ? a = b\n" 8005 " : a;"); 8006 8007 // Chained conditionals 8008 FormatStyle Style = getLLVMStyleWithColumns(70); 8009 Style.AlignOperands = FormatStyle::OAS_Align; 8010 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8011 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8012 " : 3333333333333333;", 8013 Style); 8014 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8015 " : bbbbbbbbbb ? 2222222222222222\n" 8016 " : 3333333333333333;", 8017 Style); 8018 verifyFormat("return aaaaaaaaaa ? 1111111111111111\n" 8019 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 8020 " : 3333333333333333;", 8021 Style); 8022 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8023 " : bbbbbbbbbbbbbb ? 222222\n" 8024 " : 333333;", 8025 Style); 8026 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8027 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8028 " : cccccccccccccc ? 3333333333333333\n" 8029 " : 4444444444444444;", 8030 Style); 8031 verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc)\n" 8032 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8033 " : 3333333333333333;", 8034 Style); 8035 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8036 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8037 " : (aaa ? bbb : ccc);", 8038 Style); 8039 verifyFormat( 8040 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8041 " : cccccccccccccccccc)\n" 8042 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8043 " : 3333333333333333;", 8044 Style); 8045 verifyFormat( 8046 "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8047 " : cccccccccccccccccc)\n" 8048 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8049 " : 3333333333333333;", 8050 Style); 8051 verifyFormat( 8052 "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8053 " : dddddddddddddddddd)\n" 8054 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8055 " : 3333333333333333;", 8056 Style); 8057 verifyFormat( 8058 "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8059 " : dddddddddddddddddd)\n" 8060 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8061 " : 3333333333333333;", 8062 Style); 8063 verifyFormat( 8064 "return aaaaaaaaa ? 1111111111111111\n" 8065 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8066 " : a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8067 " : dddddddddddddddddd)\n", 8068 Style); 8069 verifyFormat( 8070 "return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8071 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8072 " : (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8073 " : cccccccccccccccccc);", 8074 Style); 8075 verifyFormat( 8076 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8077 " : ccccccccccccccc ? dddddddddddddddddd\n" 8078 " : eeeeeeeeeeeeeeeeee)\n" 8079 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8080 " : 3333333333333333;", 8081 Style); 8082 verifyFormat( 8083 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8084 " : ccccccccccccccc ? dddddddddddddddddd\n" 8085 " : eeeeeeeeeeeeeeeeee)\n" 8086 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8087 " : 3333333333333333;", 8088 Style); 8089 verifyFormat( 8090 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8091 " : cccccccccccc ? dddddddddddddddddd\n" 8092 " : eeeeeeeeeeeeeeeeee)\n" 8093 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8094 " : 3333333333333333;", 8095 Style); 8096 verifyFormat( 8097 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8098 " : cccccccccccccccccc\n" 8099 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8100 " : 3333333333333333;", 8101 Style); 8102 verifyFormat( 8103 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8104 " : cccccccccccccccc ? dddddddddddddddddd\n" 8105 " : eeeeeeeeeeeeeeeeee\n" 8106 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8107 " : 3333333333333333;", 8108 Style); 8109 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa\n" 8110 " ? (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8111 " : cccccccccccccccccc ? dddddddddddddddddd\n" 8112 " : eeeeeeeeeeeeeeeeee)\n" 8113 " : bbbbbbbbbbbbbbbbbbb ? 2222222222222222\n" 8114 " : 3333333333333333;", 8115 Style); 8116 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaa\n" 8117 " ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8118 " : cccccccccccccccc ? dddddddddddddddddd\n" 8119 " : eeeeeeeeeeeeeeeeee\n" 8120 " : bbbbbbbbbbbbbbbbbbbbbbb ? 2222222222222222\n" 8121 " : 3333333333333333;", 8122 Style); 8123 8124 Style.AlignOperands = FormatStyle::OAS_DontAlign; 8125 Style.BreakBeforeTernaryOperators = false; 8126 // FIXME: Aligning the question marks is weird given DontAlign. 8127 // Consider disabling this alignment in this case. Also check whether this 8128 // will render the adjustment from https://reviews.llvm.org/D82199 8129 // unnecessary. 8130 verifyFormat("int x = aaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa :\n" 8131 " bbbb ? cccccccccccccccccc :\n" 8132 " ddddd;\n", 8133 Style); 8134 8135 EXPECT_EQ( 8136 "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n" 8137 " /*\n" 8138 " */\n" 8139 " function() {\n" 8140 " try {\n" 8141 " return JJJJJJJJJJJJJJ(\n" 8142 " pppppppppppppppppppppppppppppppppppppppppppppppppp);\n" 8143 " }\n" 8144 " } :\n" 8145 " function() {};", 8146 format( 8147 "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n" 8148 " /*\n" 8149 " */\n" 8150 " function() {\n" 8151 " try {\n" 8152 " return JJJJJJJJJJJJJJ(\n" 8153 " pppppppppppppppppppppppppppppppppppppppppppppppppp);\n" 8154 " }\n" 8155 " } :\n" 8156 " function() {};", 8157 getGoogleStyle(FormatStyle::LK_JavaScript))); 8158 } 8159 8160 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) { 8161 FormatStyle Style = getLLVMStyleWithColumns(70); 8162 Style.BreakBeforeTernaryOperators = false; 8163 verifyFormat( 8164 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8165 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8166 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8167 Style); 8168 verifyFormat( 8169 "aaaa(aaaaaaaaaa, aaaaaaaa,\n" 8170 " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8171 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8172 Style); 8173 verifyFormat( 8174 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8175 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8176 Style); 8177 verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n" 8178 " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8179 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8180 Style); 8181 verifyFormat( 8182 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n" 8183 " aaaaaaaaaaaaa);", 8184 Style); 8185 verifyFormat( 8186 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8187 " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8188 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8189 " aaaaaaaaaaaaa);", 8190 Style); 8191 verifyFormat( 8192 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8193 " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8194 " aaaaaaaaaaaaa);", 8195 Style); 8196 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8197 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8198 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 8199 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8200 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8201 Style); 8202 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8203 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8204 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8205 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 8206 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8207 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8208 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8209 Style); 8210 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8211 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n" 8212 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8213 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8214 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8215 Style); 8216 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8217 " aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8218 " aaaaaaaaaaaaaaaaaaaaaaaaaaa;", 8219 Style); 8220 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n" 8221 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8222 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8223 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 8224 Style); 8225 verifyFormat( 8226 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8227 " aaaaaaaaaaaaaaa :\n" 8228 " aaaaaaaaaaaaaaa;", 8229 Style); 8230 verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n" 8231 " aaaaaaaaa ?\n" 8232 " b :\n" 8233 " c);", 8234 Style); 8235 verifyFormat("unsigned Indent =\n" 8236 " format(TheLine.First,\n" 8237 " IndentForLevel[TheLine.Level] >= 0 ?\n" 8238 " IndentForLevel[TheLine.Level] :\n" 8239 " TheLine * 2,\n" 8240 " TheLine.InPPDirective, PreviousEndOfLineColumn);", 8241 Style); 8242 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n" 8243 " aaaaaaaaaaaaaaa :\n" 8244 " bbbbbbbbbbbbbbb ? //\n" 8245 " ccccccccccccccc :\n" 8246 " ddddddddddddddd;", 8247 Style); 8248 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n" 8249 " aaaaaaaaaaaaaaa :\n" 8250 " (bbbbbbbbbbbbbbb ? //\n" 8251 " ccccccccccccccc :\n" 8252 " ddddddddddddddd);", 8253 Style); 8254 verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8255 " /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n" 8256 " ccccccccccccccccccccccccccc;", 8257 Style); 8258 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8259 " aaaaa :\n" 8260 " bbbbbbbbbbbbbbb + cccccccccccccccc;", 8261 Style); 8262 8263 // Chained conditionals 8264 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8265 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8266 " 3333333333333333;", 8267 Style); 8268 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8269 " bbbbbbbbbb ? 2222222222222222 :\n" 8270 " 3333333333333333;", 8271 Style); 8272 verifyFormat("return aaaaaaaaaa ? 1111111111111111 :\n" 8273 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8274 " 3333333333333333;", 8275 Style); 8276 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8277 " bbbbbbbbbbbbbbbb ? 222222 :\n" 8278 " 333333;", 8279 Style); 8280 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8281 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8282 " cccccccccccccccc ? 3333333333333333 :\n" 8283 " 4444444444444444;", 8284 Style); 8285 verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc) :\n" 8286 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8287 " 3333333333333333;", 8288 Style); 8289 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8290 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8291 " (aaa ? bbb : ccc);", 8292 Style); 8293 verifyFormat( 8294 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8295 " cccccccccccccccccc) :\n" 8296 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8297 " 3333333333333333;", 8298 Style); 8299 verifyFormat( 8300 "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8301 " cccccccccccccccccc) :\n" 8302 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8303 " 3333333333333333;", 8304 Style); 8305 verifyFormat( 8306 "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8307 " dddddddddddddddddd) :\n" 8308 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8309 " 3333333333333333;", 8310 Style); 8311 verifyFormat( 8312 "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8313 " dddddddddddddddddd) :\n" 8314 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8315 " 3333333333333333;", 8316 Style); 8317 verifyFormat( 8318 "return aaaaaaaaa ? 1111111111111111 :\n" 8319 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8320 " a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8321 " dddddddddddddddddd)\n", 8322 Style); 8323 verifyFormat( 8324 "return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8325 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8326 " (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8327 " cccccccccccccccccc);", 8328 Style); 8329 verifyFormat( 8330 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8331 " ccccccccccccccccc ? dddddddddddddddddd :\n" 8332 " eeeeeeeeeeeeeeeeee) :\n" 8333 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8334 " 3333333333333333;", 8335 Style); 8336 verifyFormat( 8337 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8338 " ccccccccccccc ? dddddddddddddddddd :\n" 8339 " eeeeeeeeeeeeeeeeee) :\n" 8340 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8341 " 3333333333333333;", 8342 Style); 8343 verifyFormat( 8344 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8345 " ccccccccccccccccc ? dddddddddddddddddd :\n" 8346 " eeeeeeeeeeeeeeeeee) :\n" 8347 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8348 " 3333333333333333;", 8349 Style); 8350 verifyFormat( 8351 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8352 " cccccccccccccccccc :\n" 8353 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8354 " 3333333333333333;", 8355 Style); 8356 verifyFormat( 8357 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8358 " cccccccccccccccccc ? dddddddddddddddddd :\n" 8359 " eeeeeeeeeeeeeeeeee :\n" 8360 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8361 " 3333333333333333;", 8362 Style); 8363 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n" 8364 " (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8365 " cccccccccccccccccc ? dddddddddddddddddd :\n" 8366 " eeeeeeeeeeeeeeeeee) :\n" 8367 " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8368 " 3333333333333333;", 8369 Style); 8370 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n" 8371 " aaaaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8372 " cccccccccccccccccccc ? dddddddddddddddddd :\n" 8373 " eeeeeeeeeeeeeeeeee :\n" 8374 " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8375 " 3333333333333333;", 8376 Style); 8377 } 8378 8379 TEST_F(FormatTest, DeclarationsOfMultipleVariables) { 8380 verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n" 8381 " aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();"); 8382 verifyFormat("bool a = true, b = false;"); 8383 8384 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n" 8385 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n" 8386 " bbbbbbbbbbbbbbbbbbbbbbbbb =\n" 8387 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);"); 8388 verifyFormat( 8389 "bool aaaaaaaaaaaaaaaaaaaaa =\n" 8390 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n" 8391 " d = e && f;"); 8392 verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n" 8393 " c = cccccccccccccccccccc, d = dddddddddddddddddddd;"); 8394 verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n" 8395 " *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;"); 8396 verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n" 8397 " ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;"); 8398 8399 FormatStyle Style = getGoogleStyle(); 8400 Style.PointerAlignment = FormatStyle::PAS_Left; 8401 Style.DerivePointerAlignment = false; 8402 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8403 " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n" 8404 " *b = bbbbbbbbbbbbbbbbbbb;", 8405 Style); 8406 verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n" 8407 " *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;", 8408 Style); 8409 verifyFormat("vector<int*> a, b;", Style); 8410 verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style); 8411 verifyFormat("/*comment*/ for (int *p, *q; p != q; p = p->next) {\n}", Style); 8412 verifyFormat("if (int *p, *q; p != q) {\n p = p->next;\n}", Style); 8413 verifyFormat("/*comment*/ if (int *p, *q; p != q) {\n p = p->next;\n}", 8414 Style); 8415 verifyFormat("switch (int *p, *q; p != q) {\n default:\n break;\n}", 8416 Style); 8417 verifyFormat( 8418 "/*comment*/ switch (int *p, *q; p != q) {\n default:\n break;\n}", 8419 Style); 8420 8421 verifyFormat("if ([](int* p, int* q) {}()) {\n}", Style); 8422 verifyFormat("for ([](int* p, int* q) {}();;) {\n}", Style); 8423 verifyFormat("for (; [](int* p, int* q) {}();) {\n}", Style); 8424 verifyFormat("for (;; [](int* p, int* q) {}()) {\n}", Style); 8425 verifyFormat("switch ([](int* p, int* q) {}()) {\n default:\n break;\n}", 8426 Style); 8427 } 8428 8429 TEST_F(FormatTest, ConditionalExpressionsInBrackets) { 8430 verifyFormat("arr[foo ? bar : baz];"); 8431 verifyFormat("f()[foo ? bar : baz];"); 8432 verifyFormat("(a + b)[foo ? bar : baz];"); 8433 verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];"); 8434 } 8435 8436 TEST_F(FormatTest, AlignsStringLiterals) { 8437 verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n" 8438 " \"short literal\");"); 8439 verifyFormat( 8440 "looooooooooooooooooooooooongFunction(\n" 8441 " \"short literal\"\n" 8442 " \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");"); 8443 verifyFormat("someFunction(\"Always break between multi-line\"\n" 8444 " \" string literals\",\n" 8445 " and, other, parameters);"); 8446 EXPECT_EQ("fun + \"1243\" /* comment */\n" 8447 " \"5678\";", 8448 format("fun + \"1243\" /* comment */\n" 8449 " \"5678\";", 8450 getLLVMStyleWithColumns(28))); 8451 EXPECT_EQ( 8452 "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 8453 " \"aaaaaaaaaaaaaaaaaaaaa\"\n" 8454 " \"aaaaaaaaaaaaaaaa\";", 8455 format("aaaaaa =" 8456 "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa " 8457 "aaaaaaaaaaaaaaaaaaaaa\" " 8458 "\"aaaaaaaaaaaaaaaa\";")); 8459 verifyFormat("a = a + \"a\"\n" 8460 " \"a\"\n" 8461 " \"a\";"); 8462 verifyFormat("f(\"a\", \"b\"\n" 8463 " \"c\");"); 8464 8465 verifyFormat( 8466 "#define LL_FORMAT \"ll\"\n" 8467 "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n" 8468 " \"d, ddddddddd: %\" LL_FORMAT \"d\");"); 8469 8470 verifyFormat("#define A(X) \\\n" 8471 " \"aaaaa\" #X \"bbbbbb\" \\\n" 8472 " \"ccccc\"", 8473 getLLVMStyleWithColumns(23)); 8474 verifyFormat("#define A \"def\"\n" 8475 "f(\"abc\" A \"ghi\"\n" 8476 " \"jkl\");"); 8477 8478 verifyFormat("f(L\"a\"\n" 8479 " L\"b\");"); 8480 verifyFormat("#define A(X) \\\n" 8481 " L\"aaaaa\" #X L\"bbbbbb\" \\\n" 8482 " L\"ccccc\"", 8483 getLLVMStyleWithColumns(25)); 8484 8485 verifyFormat("f(@\"a\"\n" 8486 " @\"b\");"); 8487 verifyFormat("NSString s = @\"a\"\n" 8488 " @\"b\"\n" 8489 " @\"c\";"); 8490 verifyFormat("NSString s = @\"a\"\n" 8491 " \"b\"\n" 8492 " \"c\";"); 8493 } 8494 8495 TEST_F(FormatTest, ReturnTypeBreakingStyle) { 8496 FormatStyle Style = getLLVMStyle(); 8497 // No declarations or definitions should be moved to own line. 8498 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None; 8499 verifyFormat("class A {\n" 8500 " int f() { return 1; }\n" 8501 " int g();\n" 8502 "};\n" 8503 "int f() { return 1; }\n" 8504 "int g();\n", 8505 Style); 8506 8507 // All declarations and definitions should have the return type moved to its 8508 // own line. 8509 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 8510 Style.TypenameMacros = {"LIST"}; 8511 verifyFormat("SomeType\n" 8512 "funcdecl(LIST(uint64_t));", 8513 Style); 8514 verifyFormat("class E {\n" 8515 " int\n" 8516 " f() {\n" 8517 " return 1;\n" 8518 " }\n" 8519 " int\n" 8520 " g();\n" 8521 "};\n" 8522 "int\n" 8523 "f() {\n" 8524 " return 1;\n" 8525 "}\n" 8526 "int\n" 8527 "g();\n", 8528 Style); 8529 8530 // Top-level definitions, and no kinds of declarations should have the 8531 // return type moved to its own line. 8532 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions; 8533 verifyFormat("class B {\n" 8534 " int f() { return 1; }\n" 8535 " int g();\n" 8536 "};\n" 8537 "int\n" 8538 "f() {\n" 8539 " return 1;\n" 8540 "}\n" 8541 "int g();\n", 8542 Style); 8543 8544 // Top-level definitions and declarations should have the return type moved 8545 // to its own line. 8546 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel; 8547 verifyFormat("class C {\n" 8548 " int f() { return 1; }\n" 8549 " int g();\n" 8550 "};\n" 8551 "int\n" 8552 "f() {\n" 8553 " return 1;\n" 8554 "}\n" 8555 "int\n" 8556 "g();\n", 8557 Style); 8558 8559 // All definitions should have the return type moved to its own line, but no 8560 // kinds of declarations. 8561 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions; 8562 verifyFormat("class D {\n" 8563 " int\n" 8564 " f() {\n" 8565 " return 1;\n" 8566 " }\n" 8567 " int g();\n" 8568 "};\n" 8569 "int\n" 8570 "f() {\n" 8571 " return 1;\n" 8572 "}\n" 8573 "int g();\n", 8574 Style); 8575 verifyFormat("const char *\n" 8576 "f(void) {\n" // Break here. 8577 " return \"\";\n" 8578 "}\n" 8579 "const char *bar(void);\n", // No break here. 8580 Style); 8581 verifyFormat("template <class T>\n" 8582 "T *\n" 8583 "f(T &c) {\n" // Break here. 8584 " return NULL;\n" 8585 "}\n" 8586 "template <class T> T *f(T &c);\n", // No break here. 8587 Style); 8588 verifyFormat("class C {\n" 8589 " int\n" 8590 " operator+() {\n" 8591 " return 1;\n" 8592 " }\n" 8593 " int\n" 8594 " operator()() {\n" 8595 " return 1;\n" 8596 " }\n" 8597 "};\n", 8598 Style); 8599 verifyFormat("void\n" 8600 "A::operator()() {}\n" 8601 "void\n" 8602 "A::operator>>() {}\n" 8603 "void\n" 8604 "A::operator+() {}\n" 8605 "void\n" 8606 "A::operator*() {}\n" 8607 "void\n" 8608 "A::operator->() {}\n" 8609 "void\n" 8610 "A::operator void *() {}\n" 8611 "void\n" 8612 "A::operator void &() {}\n" 8613 "void\n" 8614 "A::operator void &&() {}\n" 8615 "void\n" 8616 "A::operator char *() {}\n" 8617 "void\n" 8618 "A::operator[]() {}\n" 8619 "void\n" 8620 "A::operator!() {}\n" 8621 "void\n" 8622 "A::operator**() {}\n" 8623 "void\n" 8624 "A::operator<Foo> *() {}\n" 8625 "void\n" 8626 "A::operator<Foo> **() {}\n" 8627 "void\n" 8628 "A::operator<Foo> &() {}\n" 8629 "void\n" 8630 "A::operator void **() {}\n", 8631 Style); 8632 verifyFormat("constexpr auto\n" 8633 "operator()() const -> reference {}\n" 8634 "constexpr auto\n" 8635 "operator>>() const -> reference {}\n" 8636 "constexpr auto\n" 8637 "operator+() const -> reference {}\n" 8638 "constexpr auto\n" 8639 "operator*() const -> reference {}\n" 8640 "constexpr auto\n" 8641 "operator->() const -> reference {}\n" 8642 "constexpr auto\n" 8643 "operator++() const -> reference {}\n" 8644 "constexpr auto\n" 8645 "operator void *() const -> reference {}\n" 8646 "constexpr auto\n" 8647 "operator void **() const -> reference {}\n" 8648 "constexpr auto\n" 8649 "operator void *() const -> reference {}\n" 8650 "constexpr auto\n" 8651 "operator void &() const -> reference {}\n" 8652 "constexpr auto\n" 8653 "operator void &&() const -> reference {}\n" 8654 "constexpr auto\n" 8655 "operator char *() const -> reference {}\n" 8656 "constexpr auto\n" 8657 "operator!() const -> reference {}\n" 8658 "constexpr auto\n" 8659 "operator[]() const -> reference {}\n", 8660 Style); 8661 verifyFormat("void *operator new(std::size_t s);", // No break here. 8662 Style); 8663 verifyFormat("void *\n" 8664 "operator new(std::size_t s) {}", 8665 Style); 8666 verifyFormat("void *\n" 8667 "operator delete[](void *ptr) {}", 8668 Style); 8669 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 8670 verifyFormat("const char *\n" 8671 "f(void)\n" // Break here. 8672 "{\n" 8673 " return \"\";\n" 8674 "}\n" 8675 "const char *bar(void);\n", // No break here. 8676 Style); 8677 verifyFormat("template <class T>\n" 8678 "T *\n" // Problem here: no line break 8679 "f(T &c)\n" // Break here. 8680 "{\n" 8681 " return NULL;\n" 8682 "}\n" 8683 "template <class T> T *f(T &c);\n", // No break here. 8684 Style); 8685 verifyFormat("int\n" 8686 "foo(A<bool> a)\n" 8687 "{\n" 8688 " return a;\n" 8689 "}\n", 8690 Style); 8691 verifyFormat("int\n" 8692 "foo(A<8> a)\n" 8693 "{\n" 8694 " return a;\n" 8695 "}\n", 8696 Style); 8697 verifyFormat("int\n" 8698 "foo(A<B<bool>, 8> a)\n" 8699 "{\n" 8700 " return a;\n" 8701 "}\n", 8702 Style); 8703 verifyFormat("int\n" 8704 "foo(A<B<8>, bool> a)\n" 8705 "{\n" 8706 " return a;\n" 8707 "}\n", 8708 Style); 8709 verifyFormat("int\n" 8710 "foo(A<B<bool>, bool> a)\n" 8711 "{\n" 8712 " return a;\n" 8713 "}\n", 8714 Style); 8715 verifyFormat("int\n" 8716 "foo(A<B<8>, 8> a)\n" 8717 "{\n" 8718 " return a;\n" 8719 "}\n", 8720 Style); 8721 8722 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 8723 Style.BraceWrapping.AfterFunction = true; 8724 verifyFormat("int f(i);\n" // No break here. 8725 "int\n" // Break here. 8726 "f(i)\n" 8727 "{\n" 8728 " return i + 1;\n" 8729 "}\n" 8730 "int\n" // Break here. 8731 "f(i)\n" 8732 "{\n" 8733 " return i + 1;\n" 8734 "};", 8735 Style); 8736 verifyFormat("int f(a, b, c);\n" // No break here. 8737 "int\n" // Break here. 8738 "f(a, b, c)\n" // Break here. 8739 "short a, b;\n" 8740 "float c;\n" 8741 "{\n" 8742 " return a + b < c;\n" 8743 "}\n" 8744 "int\n" // Break here. 8745 "f(a, b, c)\n" // Break here. 8746 "short a, b;\n" 8747 "float c;\n" 8748 "{\n" 8749 " return a + b < c;\n" 8750 "};", 8751 Style); 8752 verifyFormat("byte *\n" // Break here. 8753 "f(a)\n" // Break here. 8754 "byte a[];\n" 8755 "{\n" 8756 " return a;\n" 8757 "}", 8758 Style); 8759 verifyFormat("bool f(int a, int) override;\n" 8760 "Bar g(int a, Bar) final;\n" 8761 "Bar h(a, Bar) final;", 8762 Style); 8763 verifyFormat("int\n" 8764 "f(a)", 8765 Style); 8766 verifyFormat("bool\n" 8767 "f(size_t = 0, bool b = false)\n" 8768 "{\n" 8769 " return !b;\n" 8770 "}", 8771 Style); 8772 8773 // The return breaking style doesn't affect: 8774 // * function and object definitions with attribute-like macros 8775 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 8776 " ABSL_GUARDED_BY(mutex) = {};", 8777 getGoogleStyleWithColumns(40)); 8778 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 8779 " ABSL_GUARDED_BY(mutex); // comment", 8780 getGoogleStyleWithColumns(40)); 8781 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 8782 " ABSL_GUARDED_BY(mutex1)\n" 8783 " ABSL_GUARDED_BY(mutex2);", 8784 getGoogleStyleWithColumns(40)); 8785 verifyFormat("Tttttt f(int a, int b)\n" 8786 " ABSL_GUARDED_BY(mutex1)\n" 8787 " ABSL_GUARDED_BY(mutex2);", 8788 getGoogleStyleWithColumns(40)); 8789 // * typedefs 8790 verifyFormat("typedef ATTR(X) char x;", getGoogleStyle()); 8791 8792 Style = getGNUStyle(); 8793 8794 // Test for comments at the end of function declarations. 8795 verifyFormat("void\n" 8796 "foo (int a, /*abc*/ int b) // def\n" 8797 "{\n" 8798 "}\n", 8799 Style); 8800 8801 verifyFormat("void\n" 8802 "foo (int a, /* abc */ int b) /* def */\n" 8803 "{\n" 8804 "}\n", 8805 Style); 8806 8807 // Definitions that should not break after return type 8808 verifyFormat("void foo (int a, int b); // def\n", Style); 8809 verifyFormat("void foo (int a, int b); /* def */\n", Style); 8810 verifyFormat("void foo (int a, int b);\n", Style); 8811 } 8812 8813 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) { 8814 FormatStyle NoBreak = getLLVMStyle(); 8815 NoBreak.AlwaysBreakBeforeMultilineStrings = false; 8816 FormatStyle Break = getLLVMStyle(); 8817 Break.AlwaysBreakBeforeMultilineStrings = true; 8818 verifyFormat("aaaa = \"bbbb\"\n" 8819 " \"cccc\";", 8820 NoBreak); 8821 verifyFormat("aaaa =\n" 8822 " \"bbbb\"\n" 8823 " \"cccc\";", 8824 Break); 8825 verifyFormat("aaaa(\"bbbb\"\n" 8826 " \"cccc\");", 8827 NoBreak); 8828 verifyFormat("aaaa(\n" 8829 " \"bbbb\"\n" 8830 " \"cccc\");", 8831 Break); 8832 verifyFormat("aaaa(qqq, \"bbbb\"\n" 8833 " \"cccc\");", 8834 NoBreak); 8835 verifyFormat("aaaa(qqq,\n" 8836 " \"bbbb\"\n" 8837 " \"cccc\");", 8838 Break); 8839 verifyFormat("aaaa(qqq,\n" 8840 " L\"bbbb\"\n" 8841 " L\"cccc\");", 8842 Break); 8843 verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n" 8844 " \"bbbb\"));", 8845 Break); 8846 verifyFormat("string s = someFunction(\n" 8847 " \"abc\"\n" 8848 " \"abc\");", 8849 Break); 8850 8851 // As we break before unary operators, breaking right after them is bad. 8852 verifyFormat("string foo = abc ? \"x\"\n" 8853 " \"blah blah blah blah blah blah\"\n" 8854 " : \"y\";", 8855 Break); 8856 8857 // Don't break if there is no column gain. 8858 verifyFormat("f(\"aaaa\"\n" 8859 " \"bbbb\");", 8860 Break); 8861 8862 // Treat literals with escaped newlines like multi-line string literals. 8863 EXPECT_EQ("x = \"a\\\n" 8864 "b\\\n" 8865 "c\";", 8866 format("x = \"a\\\n" 8867 "b\\\n" 8868 "c\";", 8869 NoBreak)); 8870 EXPECT_EQ("xxxx =\n" 8871 " \"a\\\n" 8872 "b\\\n" 8873 "c\";", 8874 format("xxxx = \"a\\\n" 8875 "b\\\n" 8876 "c\";", 8877 Break)); 8878 8879 EXPECT_EQ("NSString *const kString =\n" 8880 " @\"aaaa\"\n" 8881 " @\"bbbb\";", 8882 format("NSString *const kString = @\"aaaa\"\n" 8883 "@\"bbbb\";", 8884 Break)); 8885 8886 Break.ColumnLimit = 0; 8887 verifyFormat("const char *hello = \"hello llvm\";", Break); 8888 } 8889 8890 TEST_F(FormatTest, AlignsPipes) { 8891 verifyFormat( 8892 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8893 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8894 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8895 verifyFormat( 8896 "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n" 8897 " << aaaaaaaaaaaaaaaaaaaa;"); 8898 verifyFormat( 8899 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8900 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8901 verifyFormat( 8902 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 8903 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8904 verifyFormat( 8905 "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n" 8906 " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n" 8907 " << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";"); 8908 verifyFormat( 8909 "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8910 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8911 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8912 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8913 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8914 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8915 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 8916 verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n" 8917 " << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);"); 8918 verifyFormat( 8919 "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8920 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8921 verifyFormat( 8922 "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n" 8923 " aaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8924 8925 verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n" 8926 " << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();"); 8927 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8928 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8929 " aaaaaaaaaaaaaaaaaaaaa)\n" 8930 " << aaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8931 verifyFormat("LOG_IF(aaa == //\n" 8932 " bbb)\n" 8933 " << a << b;"); 8934 8935 // But sometimes, breaking before the first "<<" is desirable. 8936 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 8937 " << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);"); 8938 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n" 8939 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8940 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8941 verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n" 8942 " << BEF << IsTemplate << Description << E->getType();"); 8943 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 8944 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8945 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8946 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 8947 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8948 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8949 " << aaa;"); 8950 8951 verifyFormat( 8952 "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8953 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 8954 8955 // Incomplete string literal. 8956 EXPECT_EQ("llvm::errs() << \"\n" 8957 " << a;", 8958 format("llvm::errs() << \"\n<<a;")); 8959 8960 verifyFormat("void f() {\n" 8961 " CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n" 8962 " << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n" 8963 "}"); 8964 8965 // Handle 'endl'. 8966 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n" 8967 " << bbbbbbbbbbbbbbbbbbbbbb << endl;"); 8968 verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;"); 8969 8970 // Handle '\n'. 8971 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n" 8972 " << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";"); 8973 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n" 8974 " << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';"); 8975 verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n" 8976 " << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";"); 8977 verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";"); 8978 } 8979 8980 TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) { 8981 verifyFormat("return out << \"somepacket = {\\n\"\n" 8982 " << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n" 8983 " << \" bbbb = \" << pkt.bbbb << \"\\n\"\n" 8984 " << \" cccccc = \" << pkt.cccccc << \"\\n\"\n" 8985 " << \" ddd = [\" << pkt.ddd << \"]\\n\"\n" 8986 " << \"}\";"); 8987 8988 verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n" 8989 " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n" 8990 " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;"); 8991 verifyFormat( 8992 "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n" 8993 " << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n" 8994 " << \"ccccccccccccccccc = \" << ccccccccccccccccc\n" 8995 " << \"ddddddddddddddddd = \" << ddddddddddddddddd\n" 8996 " << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;"); 8997 verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n" 8998 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 8999 verifyFormat( 9000 "void f() {\n" 9001 " llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n" 9002 " << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 9003 "}"); 9004 9005 // Breaking before the first "<<" is generally not desirable. 9006 verifyFormat( 9007 "llvm::errs()\n" 9008 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9009 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9010 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9011 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 9012 getLLVMStyleWithColumns(70)); 9013 verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n" 9014 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9015 " << \"aaaaaaaaaaaaaaaaaaa: \"\n" 9016 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9017 " << \"aaaaaaaaaaaaaaaaaaa: \"\n" 9018 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 9019 getLLVMStyleWithColumns(70)); 9020 9021 verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n" 9022 " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n" 9023 " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;"); 9024 verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n" 9025 " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n" 9026 " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);"); 9027 verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n" 9028 " (aaaa + aaaa);", 9029 getLLVMStyleWithColumns(40)); 9030 verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n" 9031 " (aaaaaaa + aaaaa));", 9032 getLLVMStyleWithColumns(40)); 9033 verifyFormat( 9034 "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n" 9035 " SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n" 9036 " bbbbbbbbbbbbbbbbbbbbbbb);"); 9037 } 9038 9039 TEST_F(FormatTest, UnderstandsEquals) { 9040 verifyFormat( 9041 "aaaaaaaaaaaaaaaaa =\n" 9042 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9043 verifyFormat( 9044 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9045 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 9046 verifyFormat( 9047 "if (a) {\n" 9048 " f();\n" 9049 "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9050 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 9051 "}"); 9052 9053 verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9054 " 100000000 + 10000000) {\n}"); 9055 } 9056 9057 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) { 9058 verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n" 9059 " .looooooooooooooooooooooooooooooooooooooongFunction();"); 9060 9061 verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n" 9062 " ->looooooooooooooooooooooooooooooooooooooongFunction();"); 9063 9064 verifyFormat( 9065 "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n" 9066 " Parameter2);"); 9067 9068 verifyFormat( 9069 "ShortObject->shortFunction(\n" 9070 " LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n" 9071 " LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);"); 9072 9073 verifyFormat("loooooooooooooongFunction(\n" 9074 " LoooooooooooooongObject->looooooooooooooooongFunction());"); 9075 9076 verifyFormat( 9077 "function(LoooooooooooooooooooooooooooooooooooongObject\n" 9078 " ->loooooooooooooooooooooooooooooooooooooooongFunction());"); 9079 9080 verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n" 9081 " .WillRepeatedly(Return(SomeValue));"); 9082 verifyFormat("void f() {\n" 9083 " EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n" 9084 " .Times(2)\n" 9085 " .WillRepeatedly(Return(SomeValue));\n" 9086 "}"); 9087 verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n" 9088 " ccccccccccccccccccccccc);"); 9089 verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9090 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9091 " .aaaaa(aaaaa),\n" 9092 " aaaaaaaaaaaaaaaaaaaaa);"); 9093 verifyFormat("void f() {\n" 9094 " aaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9095 " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n" 9096 "}"); 9097 verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9098 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9099 " .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9100 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9101 " aaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 9102 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9103 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9104 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9105 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n" 9106 "}"); 9107 9108 // Here, it is not necessary to wrap at "." or "->". 9109 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n" 9110 " aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 9111 verifyFormat( 9112 "aaaaaaaaaaa->aaaaaaaaa(\n" 9113 " aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9114 " aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n"); 9115 9116 verifyFormat( 9117 "aaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9118 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());"); 9119 verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n" 9120 " aaaaaaaaa()->aaaaaa()->aaaaa());"); 9121 verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n" 9122 " aaaaaaaaa()->aaaaaa()->aaaaa());"); 9123 9124 verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9125 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9126 " .a();"); 9127 9128 FormatStyle NoBinPacking = getLLVMStyle(); 9129 NoBinPacking.BinPackParameters = false; 9130 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n" 9131 " .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n" 9132 " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n" 9133 " aaaaaaaaaaaaaaaaaaa,\n" 9134 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 9135 NoBinPacking); 9136 9137 // If there is a subsequent call, change to hanging indentation. 9138 verifyFormat( 9139 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9140 " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n" 9141 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9142 verifyFormat( 9143 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9144 " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));"); 9145 verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9146 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9147 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9148 verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9149 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9150 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());"); 9151 } 9152 9153 TEST_F(FormatTest, WrapsTemplateDeclarations) { 9154 verifyFormat("template <typename T>\n" 9155 "virtual void loooooooooooongFunction(int Param1, int Param2);"); 9156 verifyFormat("template <typename T>\n" 9157 "// T should be one of {A, B}.\n" 9158 "virtual void loooooooooooongFunction(int Param1, int Param2);"); 9159 verifyFormat( 9160 "template <typename T>\n" 9161 "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;"); 9162 verifyFormat("template <typename T>\n" 9163 "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n" 9164 " int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);"); 9165 verifyFormat( 9166 "template <typename T>\n" 9167 "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n" 9168 " int Paaaaaaaaaaaaaaaaaaaaram2);"); 9169 verifyFormat( 9170 "template <typename T>\n" 9171 "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n" 9172 " aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n" 9173 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9174 verifyFormat("template <typename T>\n" 9175 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9176 " int aaaaaaaaaaaaaaaaaaaaaa);"); 9177 verifyFormat( 9178 "template <typename T1, typename T2 = char, typename T3 = char,\n" 9179 " typename T4 = char>\n" 9180 "void f();"); 9181 verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n" 9182 " template <typename> class cccccccccccccccccccccc,\n" 9183 " typename ddddddddddddd>\n" 9184 "class C {};"); 9185 verifyFormat( 9186 "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n" 9187 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9188 9189 verifyFormat("void f() {\n" 9190 " a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n" 9191 " a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n" 9192 "}"); 9193 9194 verifyFormat("template <typename T> class C {};"); 9195 verifyFormat("template <typename T> void f();"); 9196 verifyFormat("template <typename T> void f() {}"); 9197 verifyFormat( 9198 "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n" 9199 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9200 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n" 9201 " new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n" 9202 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9203 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n" 9204 " bbbbbbbbbbbbbbbbbbbbbbbb);", 9205 getLLVMStyleWithColumns(72)); 9206 EXPECT_EQ("static_cast<A< //\n" 9207 " B> *>(\n" 9208 "\n" 9209 ");", 9210 format("static_cast<A<//\n" 9211 " B>*>(\n" 9212 "\n" 9213 " );")); 9214 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9215 " const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);"); 9216 9217 FormatStyle AlwaysBreak = getLLVMStyle(); 9218 AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 9219 verifyFormat("template <typename T>\nclass C {};", AlwaysBreak); 9220 verifyFormat("template <typename T>\nvoid f();", AlwaysBreak); 9221 verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak); 9222 verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9223 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n" 9224 " ccccccccccccccccccccccccccccccccccccccccccccccc);"); 9225 verifyFormat("template <template <typename> class Fooooooo,\n" 9226 " template <typename> class Baaaaaaar>\n" 9227 "struct C {};", 9228 AlwaysBreak); 9229 verifyFormat("template <typename T> // T can be A, B or C.\n" 9230 "struct C {};", 9231 AlwaysBreak); 9232 verifyFormat("template <enum E> class A {\n" 9233 "public:\n" 9234 " E *f();\n" 9235 "};"); 9236 9237 FormatStyle NeverBreak = getLLVMStyle(); 9238 NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No; 9239 verifyFormat("template <typename T> class C {};", NeverBreak); 9240 verifyFormat("template <typename T> void f();", NeverBreak); 9241 verifyFormat("template <typename T> void f() {}", NeverBreak); 9242 verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa " 9243 "bbbbbbbbbbbbbbbbbbbb) {}", 9244 NeverBreak); 9245 verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9246 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n" 9247 " ccccccccccccccccccccccccccccccccccccccccccccccc);", 9248 NeverBreak); 9249 verifyFormat("template <template <typename> class Fooooooo,\n" 9250 " template <typename> class Baaaaaaar>\n" 9251 "struct C {};", 9252 NeverBreak); 9253 verifyFormat("template <typename T> // T can be A, B or C.\n" 9254 "struct C {};", 9255 NeverBreak); 9256 verifyFormat("template <enum E> class A {\n" 9257 "public:\n" 9258 " E *f();\n" 9259 "};", 9260 NeverBreak); 9261 NeverBreak.PenaltyBreakTemplateDeclaration = 100; 9262 verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa " 9263 "bbbbbbbbbbbbbbbbbbbb) {}", 9264 NeverBreak); 9265 } 9266 9267 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) { 9268 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp); 9269 Style.ColumnLimit = 60; 9270 EXPECT_EQ("// Baseline - no comments.\n" 9271 "template <\n" 9272 " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n" 9273 "void f() {}", 9274 format("// Baseline - no comments.\n" 9275 "template <\n" 9276 " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n" 9277 "void f() {}", 9278 Style)); 9279 9280 EXPECT_EQ("template <\n" 9281 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9282 "void f() {}", 9283 format("template <\n" 9284 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9285 "void f() {}", 9286 Style)); 9287 9288 EXPECT_EQ( 9289 "template <\n" 9290 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n" 9291 "void f() {}", 9292 format("template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n" 9293 "void f() {}", 9294 Style)); 9295 9296 EXPECT_EQ( 9297 "template <\n" 9298 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9299 " // multiline\n" 9300 "void f() {}", 9301 format("template <\n" 9302 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9303 " // multiline\n" 9304 "void f() {}", 9305 Style)); 9306 9307 EXPECT_EQ( 9308 "template <typename aaaaaaaaaa<\n" 9309 " bbbbbbbbbbbb>::value> // trailing loooong\n" 9310 "void f() {}", 9311 format( 9312 "template <\n" 9313 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n" 9314 "void f() {}", 9315 Style)); 9316 } 9317 9318 TEST_F(FormatTest, WrapsTemplateParameters) { 9319 FormatStyle Style = getLLVMStyle(); 9320 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 9321 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 9322 verifyFormat( 9323 "template <typename... a> struct q {};\n" 9324 "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n" 9325 " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n" 9326 " y;", 9327 Style); 9328 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 9329 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 9330 verifyFormat( 9331 "template <typename... a> struct r {};\n" 9332 "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n" 9333 " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n" 9334 " y;", 9335 Style); 9336 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 9337 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 9338 verifyFormat("template <typename... a> struct s {};\n" 9339 "extern s<\n" 9340 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9341 "aaaaaaaaaaaaaaaaaaaaaa,\n" 9342 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9343 "aaaaaaaaaaaaaaaaaaaaaa>\n" 9344 " y;", 9345 Style); 9346 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 9347 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 9348 verifyFormat("template <typename... a> struct t {};\n" 9349 "extern t<\n" 9350 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9351 "aaaaaaaaaaaaaaaaaaaaaa,\n" 9352 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9353 "aaaaaaaaaaaaaaaaaaaaaa>\n" 9354 " y;", 9355 Style); 9356 } 9357 9358 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) { 9359 verifyFormat( 9360 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9361 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9362 verifyFormat( 9363 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9364 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9365 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());"); 9366 9367 // FIXME: Should we have the extra indent after the second break? 9368 verifyFormat( 9369 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9370 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9371 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9372 9373 verifyFormat( 9374 "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n" 9375 " cccccccccccccccccccccccccccccccccccccccccccccc());"); 9376 9377 // Breaking at nested name specifiers is generally not desirable. 9378 verifyFormat( 9379 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9380 " aaaaaaaaaaaaaaaaaaaaaaa);"); 9381 9382 verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n" 9383 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9384 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9385 " aaaaaaaaaaaaaaaaaaaaa);", 9386 getLLVMStyleWithColumns(74)); 9387 9388 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9389 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9390 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9391 } 9392 9393 TEST_F(FormatTest, UnderstandsTemplateParameters) { 9394 verifyFormat("A<int> a;"); 9395 verifyFormat("A<A<A<int>>> a;"); 9396 verifyFormat("A<A<A<int, 2>, 3>, 4> a;"); 9397 verifyFormat("bool x = a < 1 || 2 > a;"); 9398 verifyFormat("bool x = 5 < f<int>();"); 9399 verifyFormat("bool x = f<int>() > 5;"); 9400 verifyFormat("bool x = 5 < a<int>::x;"); 9401 verifyFormat("bool x = a < 4 ? a > 2 : false;"); 9402 verifyFormat("bool x = f() ? a < 2 : a > 2;"); 9403 9404 verifyGoogleFormat("A<A<int>> a;"); 9405 verifyGoogleFormat("A<A<A<int>>> a;"); 9406 verifyGoogleFormat("A<A<A<A<int>>>> a;"); 9407 verifyGoogleFormat("A<A<int> > a;"); 9408 verifyGoogleFormat("A<A<A<int> > > a;"); 9409 verifyGoogleFormat("A<A<A<A<int> > > > a;"); 9410 verifyGoogleFormat("A<::A<int>> a;"); 9411 verifyGoogleFormat("A<::A> a;"); 9412 verifyGoogleFormat("A< ::A> a;"); 9413 verifyGoogleFormat("A< ::A<int> > a;"); 9414 EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle())); 9415 EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle())); 9416 EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle())); 9417 EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle())); 9418 EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };", 9419 format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle())); 9420 9421 verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp)); 9422 9423 // template closer followed by a token that starts with > or = 9424 verifyFormat("bool b = a<1> > 1;"); 9425 verifyFormat("bool b = a<1> >= 1;"); 9426 verifyFormat("int i = a<1> >> 1;"); 9427 FormatStyle Style = getLLVMStyle(); 9428 Style.SpaceBeforeAssignmentOperators = false; 9429 verifyFormat("bool b= a<1> == 1;", Style); 9430 verifyFormat("a<int> = 1;", Style); 9431 verifyFormat("a<int> >>= 1;", Style); 9432 9433 verifyFormat("test < a | b >> c;"); 9434 verifyFormat("test<test<a | b>> c;"); 9435 verifyFormat("test >> a >> b;"); 9436 verifyFormat("test << a >> b;"); 9437 9438 verifyFormat("f<int>();"); 9439 verifyFormat("template <typename T> void f() {}"); 9440 verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;"); 9441 verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : " 9442 "sizeof(char)>::type>;"); 9443 verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};"); 9444 verifyFormat("f(a.operator()<A>());"); 9445 verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9446 " .template operator()<A>());", 9447 getLLVMStyleWithColumns(35)); 9448 9449 // Not template parameters. 9450 verifyFormat("return a < b && c > d;"); 9451 verifyFormat("void f() {\n" 9452 " while (a < b && c > d) {\n" 9453 " }\n" 9454 "}"); 9455 verifyFormat("template <typename... Types>\n" 9456 "typename enable_if<0 < sizeof...(Types)>::type Foo() {}"); 9457 9458 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9459 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);", 9460 getLLVMStyleWithColumns(60)); 9461 verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");"); 9462 verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}"); 9463 verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <"); 9464 verifyFormat("some_templated_type<decltype([](int i) { return i; })>"); 9465 } 9466 9467 TEST_F(FormatTest, UnderstandsShiftOperators) { 9468 verifyFormat("if (i < x >> 1)"); 9469 verifyFormat("while (i < x >> 1)"); 9470 verifyFormat("for (unsigned i = 0; i < i; ++i, v = v >> 1)"); 9471 verifyFormat("for (unsigned i = 0; i < x >> 1; ++i, v = v >> 1)"); 9472 verifyFormat( 9473 "for (std::vector<int>::iterator i = 0; i < x >> 1; ++i, v = v >> 1)"); 9474 verifyFormat("Foo.call<Bar<Function>>()"); 9475 verifyFormat("if (Foo.call<Bar<Function>>() == 0)"); 9476 verifyFormat("for (std::vector<std::pair<int>>::iterator i = 0; i < x >> 1; " 9477 "++i, v = v >> 1)"); 9478 verifyFormat("if (w<u<v<x>>, 1>::t)"); 9479 } 9480 9481 TEST_F(FormatTest, BitshiftOperatorWidth) { 9482 EXPECT_EQ("int a = 1 << 2; /* foo\n" 9483 " bar */", 9484 format("int a=1<<2; /* foo\n" 9485 " bar */")); 9486 9487 EXPECT_EQ("int b = 256 >> 1; /* foo\n" 9488 " bar */", 9489 format("int b =256>>1 ; /* foo\n" 9490 " bar */")); 9491 } 9492 9493 TEST_F(FormatTest, UnderstandsBinaryOperators) { 9494 verifyFormat("COMPARE(a, ==, b);"); 9495 verifyFormat("auto s = sizeof...(Ts) - 1;"); 9496 } 9497 9498 TEST_F(FormatTest, UnderstandsPointersToMembers) { 9499 verifyFormat("int A::*x;"); 9500 verifyFormat("int (S::*func)(void *);"); 9501 verifyFormat("void f() { int (S::*func)(void *); }"); 9502 verifyFormat("typedef bool *(Class::*Member)() const;"); 9503 verifyFormat("void f() {\n" 9504 " (a->*f)();\n" 9505 " a->*x;\n" 9506 " (a.*f)();\n" 9507 " ((*a).*f)();\n" 9508 " a.*x;\n" 9509 "}"); 9510 verifyFormat("void f() {\n" 9511 " (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n" 9512 " aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n" 9513 "}"); 9514 verifyFormat( 9515 "(aaaaaaaaaa->*bbbbbbb)(\n" 9516 " aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 9517 FormatStyle Style = getLLVMStyle(); 9518 Style.PointerAlignment = FormatStyle::PAS_Left; 9519 verifyFormat("typedef bool* (Class::*Member)() const;", Style); 9520 } 9521 9522 TEST_F(FormatTest, UnderstandsUnaryOperators) { 9523 verifyFormat("int a = -2;"); 9524 verifyFormat("f(-1, -2, -3);"); 9525 verifyFormat("a[-1] = 5;"); 9526 verifyFormat("int a = 5 + -2;"); 9527 verifyFormat("if (i == -1) {\n}"); 9528 verifyFormat("if (i != -1) {\n}"); 9529 verifyFormat("if (i > -1) {\n}"); 9530 verifyFormat("if (i < -1) {\n}"); 9531 verifyFormat("++(a->f());"); 9532 verifyFormat("--(a->f());"); 9533 verifyFormat("(a->f())++;"); 9534 verifyFormat("a[42]++;"); 9535 verifyFormat("if (!(a->f())) {\n}"); 9536 verifyFormat("if (!+i) {\n}"); 9537 verifyFormat("~&a;"); 9538 9539 verifyFormat("a-- > b;"); 9540 verifyFormat("b ? -a : c;"); 9541 verifyFormat("n * sizeof char16;"); 9542 verifyFormat("n * alignof char16;", getGoogleStyle()); 9543 verifyFormat("sizeof(char);"); 9544 verifyFormat("alignof(char);", getGoogleStyle()); 9545 9546 verifyFormat("return -1;"); 9547 verifyFormat("throw -1;"); 9548 verifyFormat("switch (a) {\n" 9549 "case -1:\n" 9550 " break;\n" 9551 "}"); 9552 verifyFormat("#define X -1"); 9553 verifyFormat("#define X -kConstant"); 9554 9555 verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};"); 9556 verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};"); 9557 9558 verifyFormat("int a = /* confusing comment */ -1;"); 9559 // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case. 9560 verifyFormat("int a = i /* confusing comment */++;"); 9561 9562 verifyFormat("co_yield -1;"); 9563 verifyFormat("co_return -1;"); 9564 9565 // Check that * is not treated as a binary operator when we set 9566 // PointerAlignment as PAS_Left after a keyword and not a declaration. 9567 FormatStyle PASLeftStyle = getLLVMStyle(); 9568 PASLeftStyle.PointerAlignment = FormatStyle::PAS_Left; 9569 verifyFormat("co_return *a;", PASLeftStyle); 9570 verifyFormat("co_await *a;", PASLeftStyle); 9571 verifyFormat("co_yield *a", PASLeftStyle); 9572 verifyFormat("return *a;", PASLeftStyle); 9573 } 9574 9575 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) { 9576 verifyFormat("if (!aaaaaaaaaa( // break\n" 9577 " aaaaa)) {\n" 9578 "}"); 9579 verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n" 9580 " aaaaa));"); 9581 verifyFormat("*aaa = aaaaaaa( // break\n" 9582 " bbbbbb);"); 9583 } 9584 9585 TEST_F(FormatTest, UnderstandsOverloadedOperators) { 9586 verifyFormat("bool operator<();"); 9587 verifyFormat("bool operator>();"); 9588 verifyFormat("bool operator=();"); 9589 verifyFormat("bool operator==();"); 9590 verifyFormat("bool operator!=();"); 9591 verifyFormat("int operator+();"); 9592 verifyFormat("int operator++();"); 9593 verifyFormat("int operator++(int) volatile noexcept;"); 9594 verifyFormat("bool operator,();"); 9595 verifyFormat("bool operator();"); 9596 verifyFormat("bool operator()();"); 9597 verifyFormat("bool operator[]();"); 9598 verifyFormat("operator bool();"); 9599 verifyFormat("operator int();"); 9600 verifyFormat("operator void *();"); 9601 verifyFormat("operator SomeType<int>();"); 9602 verifyFormat("operator SomeType<int, int>();"); 9603 verifyFormat("operator SomeType<SomeType<int>>();"); 9604 verifyFormat("operator< <>();"); 9605 verifyFormat("operator<< <>();"); 9606 verifyFormat("< <>"); 9607 9608 verifyFormat("void *operator new(std::size_t size);"); 9609 verifyFormat("void *operator new[](std::size_t size);"); 9610 verifyFormat("void operator delete(void *ptr);"); 9611 verifyFormat("void operator delete[](void *ptr);"); 9612 verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n" 9613 "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);"); 9614 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n" 9615 " aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;"); 9616 9617 verifyFormat( 9618 "ostream &operator<<(ostream &OutputStream,\n" 9619 " SomeReallyLongType WithSomeReallyLongValue);"); 9620 verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n" 9621 " const aaaaaaaaaaaaaaaaaaaaa &right) {\n" 9622 " return left.group < right.group;\n" 9623 "}"); 9624 verifyFormat("SomeType &operator=(const SomeType &S);"); 9625 verifyFormat("f.template operator()<int>();"); 9626 9627 verifyGoogleFormat("operator void*();"); 9628 verifyGoogleFormat("operator SomeType<SomeType<int>>();"); 9629 verifyGoogleFormat("operator ::A();"); 9630 9631 verifyFormat("using A::operator+;"); 9632 verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n" 9633 "int i;"); 9634 9635 // Calling an operator as a member function. 9636 verifyFormat("void f() { a.operator*(); }"); 9637 verifyFormat("void f() { a.operator*(b & b); }"); 9638 verifyFormat("void f() { a->operator&(a * b); }"); 9639 verifyFormat("void f() { NS::a.operator+(*b * *b); }"); 9640 // TODO: Calling an operator as a non-member function is hard to distinguish. 9641 // https://llvm.org/PR50629 9642 // verifyFormat("void f() { operator*(a & a); }"); 9643 // verifyFormat("void f() { operator&(a, b * b); }"); 9644 9645 verifyFormat("::operator delete(foo);"); 9646 verifyFormat("::operator new(n * sizeof(foo));"); 9647 verifyFormat("foo() { ::operator delete(foo); }"); 9648 verifyFormat("foo() { ::operator new(n * sizeof(foo)); }"); 9649 } 9650 9651 TEST_F(FormatTest, UnderstandsFunctionRefQualification) { 9652 verifyFormat("void A::b() && {}"); 9653 verifyFormat("void A::b() &&noexcept {}"); 9654 verifyFormat("Deleted &operator=(const Deleted &) & = default;"); 9655 verifyFormat("Deleted &operator=(const Deleted &) && = delete;"); 9656 verifyFormat("Deleted &operator=(const Deleted &) &noexcept = default;"); 9657 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;"); 9658 verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;"); 9659 verifyFormat("Deleted &operator=(const Deleted &) &;"); 9660 verifyFormat("Deleted &operator=(const Deleted &) &&;"); 9661 verifyFormat("SomeType MemberFunction(const Deleted &) &;"); 9662 verifyFormat("SomeType MemberFunction(const Deleted &) &&;"); 9663 verifyFormat("SomeType MemberFunction(const Deleted &) && {}"); 9664 verifyFormat("SomeType MemberFunction(const Deleted &) && final {}"); 9665 verifyFormat("SomeType MemberFunction(const Deleted &) && override {}"); 9666 verifyFormat("SomeType MemberFunction(const Deleted &) &&noexcept {}"); 9667 verifyFormat("void Fn(T const &) const &;"); 9668 verifyFormat("void Fn(T const volatile &&) const volatile &&;"); 9669 verifyFormat("void Fn(T const volatile &&) const volatile &&noexcept;"); 9670 verifyFormat("template <typename T>\n" 9671 "void F(T) && = delete;", 9672 getGoogleStyle()); 9673 9674 FormatStyle AlignLeft = getLLVMStyle(); 9675 AlignLeft.PointerAlignment = FormatStyle::PAS_Left; 9676 verifyFormat("void A::b() && {}", AlignLeft); 9677 verifyFormat("void A::b() && noexcept {}", AlignLeft); 9678 verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft); 9679 verifyFormat("Deleted& operator=(const Deleted&) & noexcept = default;", 9680 AlignLeft); 9681 verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;", 9682 AlignLeft); 9683 verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft); 9684 verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft); 9685 verifyFormat("auto Function(T t) & -> void {}", AlignLeft); 9686 verifyFormat("auto Function(T... t) & -> void {}", AlignLeft); 9687 verifyFormat("auto Function(T) & -> void {}", AlignLeft); 9688 verifyFormat("auto Function(T) & -> void;", AlignLeft); 9689 verifyFormat("void Fn(T const&) const&;", AlignLeft); 9690 verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft); 9691 verifyFormat("void Fn(T const volatile&&) const volatile&& noexcept;", 9692 AlignLeft); 9693 9694 FormatStyle AlignMiddle = getLLVMStyle(); 9695 AlignMiddle.PointerAlignment = FormatStyle::PAS_Middle; 9696 verifyFormat("void A::b() && {}", AlignMiddle); 9697 verifyFormat("void A::b() && noexcept {}", AlignMiddle); 9698 verifyFormat("Deleted & operator=(const Deleted &) & = default;", 9699 AlignMiddle); 9700 verifyFormat("Deleted & operator=(const Deleted &) & noexcept = default;", 9701 AlignMiddle); 9702 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", 9703 AlignMiddle); 9704 verifyFormat("Deleted & operator=(const Deleted &) &;", AlignMiddle); 9705 verifyFormat("SomeType MemberFunction(const Deleted &) &;", AlignMiddle); 9706 verifyFormat("auto Function(T t) & -> void {}", AlignMiddle); 9707 verifyFormat("auto Function(T... t) & -> void {}", AlignMiddle); 9708 verifyFormat("auto Function(T) & -> void {}", AlignMiddle); 9709 verifyFormat("auto Function(T) & -> void;", AlignMiddle); 9710 verifyFormat("void Fn(T const &) const &;", AlignMiddle); 9711 verifyFormat("void Fn(T const volatile &&) const volatile &&;", AlignMiddle); 9712 verifyFormat("void Fn(T const volatile &&) const volatile && noexcept;", 9713 AlignMiddle); 9714 9715 FormatStyle Spaces = getLLVMStyle(); 9716 Spaces.SpacesInCStyleCastParentheses = true; 9717 verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces); 9718 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces); 9719 verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces); 9720 verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces); 9721 9722 Spaces.SpacesInCStyleCastParentheses = false; 9723 Spaces.SpacesInParentheses = true; 9724 verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces); 9725 verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;", 9726 Spaces); 9727 verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces); 9728 verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces); 9729 9730 FormatStyle BreakTemplate = getLLVMStyle(); 9731 BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 9732 9733 verifyFormat("struct f {\n" 9734 " template <class T>\n" 9735 " int &foo(const std::string &str) &noexcept {}\n" 9736 "};", 9737 BreakTemplate); 9738 9739 verifyFormat("struct f {\n" 9740 " template <class T>\n" 9741 " int &foo(const std::string &str) &&noexcept {}\n" 9742 "};", 9743 BreakTemplate); 9744 9745 verifyFormat("struct f {\n" 9746 " template <class T>\n" 9747 " int &foo(const std::string &str) const &noexcept {}\n" 9748 "};", 9749 BreakTemplate); 9750 9751 verifyFormat("struct f {\n" 9752 " template <class T>\n" 9753 " int &foo(const std::string &str) const &noexcept {}\n" 9754 "};", 9755 BreakTemplate); 9756 9757 verifyFormat("struct f {\n" 9758 " template <class T>\n" 9759 " auto foo(const std::string &str) &&noexcept -> int & {}\n" 9760 "};", 9761 BreakTemplate); 9762 9763 FormatStyle AlignLeftBreakTemplate = getLLVMStyle(); 9764 AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations = 9765 FormatStyle::BTDS_Yes; 9766 AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left; 9767 9768 verifyFormat("struct f {\n" 9769 " template <class T>\n" 9770 " int& foo(const std::string& str) & noexcept {}\n" 9771 "};", 9772 AlignLeftBreakTemplate); 9773 9774 verifyFormat("struct f {\n" 9775 " template <class T>\n" 9776 " int& foo(const std::string& str) && noexcept {}\n" 9777 "};", 9778 AlignLeftBreakTemplate); 9779 9780 verifyFormat("struct f {\n" 9781 " template <class T>\n" 9782 " int& foo(const std::string& str) const& noexcept {}\n" 9783 "};", 9784 AlignLeftBreakTemplate); 9785 9786 verifyFormat("struct f {\n" 9787 " template <class T>\n" 9788 " int& foo(const std::string& str) const&& noexcept {}\n" 9789 "};", 9790 AlignLeftBreakTemplate); 9791 9792 verifyFormat("struct f {\n" 9793 " template <class T>\n" 9794 " auto foo(const std::string& str) && noexcept -> int& {}\n" 9795 "};", 9796 AlignLeftBreakTemplate); 9797 9798 // The `&` in `Type&` should not be confused with a trailing `&` of 9799 // DEPRECATED(reason) member function. 9800 verifyFormat("struct f {\n" 9801 " template <class T>\n" 9802 " DEPRECATED(reason)\n" 9803 " Type &foo(arguments) {}\n" 9804 "};", 9805 BreakTemplate); 9806 9807 verifyFormat("struct f {\n" 9808 " template <class T>\n" 9809 " DEPRECATED(reason)\n" 9810 " Type& foo(arguments) {}\n" 9811 "};", 9812 AlignLeftBreakTemplate); 9813 9814 verifyFormat("void (*foopt)(int) = &func;"); 9815 9816 FormatStyle DerivePointerAlignment = getLLVMStyle(); 9817 DerivePointerAlignment.DerivePointerAlignment = true; 9818 // There's always a space between the function and its trailing qualifiers. 9819 // This isn't evidence for PAS_Right (or for PAS_Left). 9820 std::string Prefix = "void a() &;\n" 9821 "void b() &;\n"; 9822 verifyFormat(Prefix + "int* x;", DerivePointerAlignment); 9823 verifyFormat(Prefix + "int *x;", DerivePointerAlignment); 9824 // Same if the function is an overloaded operator, and with &&. 9825 Prefix = "void operator()() &&;\n" 9826 "void operator()() &&;\n"; 9827 verifyFormat(Prefix + "int* x;", DerivePointerAlignment); 9828 verifyFormat(Prefix + "int *x;", DerivePointerAlignment); 9829 // However a space between cv-qualifiers and ref-qualifiers *is* evidence. 9830 Prefix = "void a() const &;\n" 9831 "void b() const &;\n"; 9832 EXPECT_EQ(Prefix + "int *x;", 9833 format(Prefix + "int* x;", DerivePointerAlignment)); 9834 } 9835 9836 TEST_F(FormatTest, UnderstandsNewAndDelete) { 9837 verifyFormat("void f() {\n" 9838 " A *a = new A;\n" 9839 " A *a = new (placement) A;\n" 9840 " delete a;\n" 9841 " delete (A *)a;\n" 9842 "}"); 9843 verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n" 9844 " typename aaaaaaaaaaaaaaaaaaaaaaaa();"); 9845 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9846 " new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n" 9847 " typename aaaaaaaaaaaaaaaaaaaaaaaa();"); 9848 verifyFormat("delete[] h->p;"); 9849 verifyFormat("delete[] (void *)p;"); 9850 9851 verifyFormat("void operator delete(void *foo) ATTRIB;"); 9852 verifyFormat("void operator new(void *foo) ATTRIB;"); 9853 verifyFormat("void operator delete[](void *foo) ATTRIB;"); 9854 verifyFormat("void operator delete(void *ptr) noexcept;"); 9855 } 9856 9857 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) { 9858 verifyFormat("int *f(int *a) {}"); 9859 verifyFormat("int main(int argc, char **argv) {}"); 9860 verifyFormat("Test::Test(int b) : a(b * b) {}"); 9861 verifyIndependentOfContext("f(a, *a);"); 9862 verifyFormat("void g() { f(*a); }"); 9863 verifyIndependentOfContext("int a = b * 10;"); 9864 verifyIndependentOfContext("int a = 10 * b;"); 9865 verifyIndependentOfContext("int a = b * c;"); 9866 verifyIndependentOfContext("int a += b * c;"); 9867 verifyIndependentOfContext("int a -= b * c;"); 9868 verifyIndependentOfContext("int a *= b * c;"); 9869 verifyIndependentOfContext("int a /= b * c;"); 9870 verifyIndependentOfContext("int a = *b;"); 9871 verifyIndependentOfContext("int a = *b * c;"); 9872 verifyIndependentOfContext("int a = b * *c;"); 9873 verifyIndependentOfContext("int a = b * (10);"); 9874 verifyIndependentOfContext("S << b * (10);"); 9875 verifyIndependentOfContext("return 10 * b;"); 9876 verifyIndependentOfContext("return *b * *c;"); 9877 verifyIndependentOfContext("return a & ~b;"); 9878 verifyIndependentOfContext("f(b ? *c : *d);"); 9879 verifyIndependentOfContext("int a = b ? *c : *d;"); 9880 verifyIndependentOfContext("*b = a;"); 9881 verifyIndependentOfContext("a * ~b;"); 9882 verifyIndependentOfContext("a * !b;"); 9883 verifyIndependentOfContext("a * +b;"); 9884 verifyIndependentOfContext("a * -b;"); 9885 verifyIndependentOfContext("a * ++b;"); 9886 verifyIndependentOfContext("a * --b;"); 9887 verifyIndependentOfContext("a[4] * b;"); 9888 verifyIndependentOfContext("a[a * a] = 1;"); 9889 verifyIndependentOfContext("f() * b;"); 9890 verifyIndependentOfContext("a * [self dostuff];"); 9891 verifyIndependentOfContext("int x = a * (a + b);"); 9892 verifyIndependentOfContext("(a *)(a + b);"); 9893 verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;"); 9894 verifyIndependentOfContext("int *pa = (int *)&a;"); 9895 verifyIndependentOfContext("return sizeof(int **);"); 9896 verifyIndependentOfContext("return sizeof(int ******);"); 9897 verifyIndependentOfContext("return (int **&)a;"); 9898 verifyIndependentOfContext("f((*PointerToArray)[10]);"); 9899 verifyFormat("void f(Type (*parameter)[10]) {}"); 9900 verifyFormat("void f(Type (¶meter)[10]) {}"); 9901 verifyGoogleFormat("return sizeof(int**);"); 9902 verifyIndependentOfContext("Type **A = static_cast<Type **>(P);"); 9903 verifyGoogleFormat("Type** A = static_cast<Type**>(P);"); 9904 verifyFormat("auto a = [](int **&, int ***) {};"); 9905 verifyFormat("auto PointerBinding = [](const char *S) {};"); 9906 verifyFormat("typedef typeof(int(int, int)) *MyFunc;"); 9907 verifyFormat("[](const decltype(*a) &value) {}"); 9908 verifyFormat("[](const typeof(*a) &value) {}"); 9909 verifyFormat("[](const _Atomic(a *) &value) {}"); 9910 verifyFormat("[](const __underlying_type(a) &value) {}"); 9911 verifyFormat("decltype(a * b) F();"); 9912 verifyFormat("typeof(a * b) F();"); 9913 verifyFormat("#define MACRO() [](A *a) { return 1; }"); 9914 verifyFormat("Constructor() : member([](A *a, B *b) {}) {}"); 9915 verifyIndependentOfContext("typedef void (*f)(int *a);"); 9916 verifyIndependentOfContext("int i{a * b};"); 9917 verifyIndependentOfContext("aaa && aaa->f();"); 9918 verifyIndependentOfContext("int x = ~*p;"); 9919 verifyFormat("Constructor() : a(a), area(width * height) {}"); 9920 verifyFormat("Constructor() : a(a), area(a, width * height) {}"); 9921 verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}"); 9922 verifyFormat("void f() { f(a, c * d); }"); 9923 verifyFormat("void f() { f(new a(), c * d); }"); 9924 verifyFormat("void f(const MyOverride &override);"); 9925 verifyFormat("void f(const MyFinal &final);"); 9926 verifyIndependentOfContext("bool a = f() && override.f();"); 9927 verifyIndependentOfContext("bool a = f() && final.f();"); 9928 9929 verifyIndependentOfContext("InvalidRegions[*R] = 0;"); 9930 9931 verifyIndependentOfContext("A<int *> a;"); 9932 verifyIndependentOfContext("A<int **> a;"); 9933 verifyIndependentOfContext("A<int *, int *> a;"); 9934 verifyIndependentOfContext("A<int *[]> a;"); 9935 verifyIndependentOfContext( 9936 "const char *const p = reinterpret_cast<const char *const>(q);"); 9937 verifyIndependentOfContext("A<int **, int **> a;"); 9938 verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);"); 9939 verifyFormat("for (char **a = b; *a; ++a) {\n}"); 9940 verifyFormat("for (; a && b;) {\n}"); 9941 verifyFormat("bool foo = true && [] { return false; }();"); 9942 9943 verifyFormat( 9944 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9945 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9946 9947 verifyGoogleFormat("int const* a = &b;"); 9948 verifyGoogleFormat("**outparam = 1;"); 9949 verifyGoogleFormat("*outparam = a * b;"); 9950 verifyGoogleFormat("int main(int argc, char** argv) {}"); 9951 verifyGoogleFormat("A<int*> a;"); 9952 verifyGoogleFormat("A<int**> a;"); 9953 verifyGoogleFormat("A<int*, int*> a;"); 9954 verifyGoogleFormat("A<int**, int**> a;"); 9955 verifyGoogleFormat("f(b ? *c : *d);"); 9956 verifyGoogleFormat("int a = b ? *c : *d;"); 9957 verifyGoogleFormat("Type* t = **x;"); 9958 verifyGoogleFormat("Type* t = *++*x;"); 9959 verifyGoogleFormat("*++*x;"); 9960 verifyGoogleFormat("Type* t = const_cast<T*>(&*x);"); 9961 verifyGoogleFormat("Type* t = x++ * y;"); 9962 verifyGoogleFormat( 9963 "const char* const p = reinterpret_cast<const char* const>(q);"); 9964 verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);"); 9965 verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);"); 9966 verifyGoogleFormat("template <typename T>\n" 9967 "void f(int i = 0, SomeType** temps = NULL);"); 9968 9969 FormatStyle Left = getLLVMStyle(); 9970 Left.PointerAlignment = FormatStyle::PAS_Left; 9971 verifyFormat("x = *a(x) = *a(y);", Left); 9972 verifyFormat("for (;; *a = b) {\n}", Left); 9973 verifyFormat("return *this += 1;", Left); 9974 verifyFormat("throw *x;", Left); 9975 verifyFormat("delete *x;", Left); 9976 verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left); 9977 verifyFormat("[](const decltype(*a)* ptr) {}", Left); 9978 verifyFormat("[](const typeof(*a)* ptr) {}", Left); 9979 verifyFormat("[](const _Atomic(a*)* ptr) {}", Left); 9980 verifyFormat("[](const __underlying_type(a)* ptr) {}", Left); 9981 verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left); 9982 verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left); 9983 verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left); 9984 verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left); 9985 9986 verifyIndependentOfContext("a = *(x + y);"); 9987 verifyIndependentOfContext("a = &(x + y);"); 9988 verifyIndependentOfContext("*(x + y).call();"); 9989 verifyIndependentOfContext("&(x + y)->call();"); 9990 verifyFormat("void f() { &(*I).first; }"); 9991 9992 verifyIndependentOfContext("f(b * /* confusing comment */ ++c);"); 9993 verifyFormat("f(* /* confusing comment */ foo);"); 9994 verifyFormat("void (* /*deleter*/)(const Slice &key, void *value)"); 9995 verifyFormat("void foo(int * // this is the first paramters\n" 9996 " ,\n" 9997 " int second);"); 9998 verifyFormat("double term = a * // first\n" 9999 " b;"); 10000 verifyFormat( 10001 "int *MyValues = {\n" 10002 " *A, // Operator detection might be confused by the '{'\n" 10003 " *BB // Operator detection might be confused by previous comment\n" 10004 "};"); 10005 10006 verifyIndependentOfContext("if (int *a = &b)"); 10007 verifyIndependentOfContext("if (int &a = *b)"); 10008 verifyIndependentOfContext("if (a & b[i])"); 10009 verifyIndependentOfContext("if constexpr (a & b[i])"); 10010 verifyIndependentOfContext("if CONSTEXPR (a & b[i])"); 10011 verifyIndependentOfContext("if (a * (b * c))"); 10012 verifyIndependentOfContext("if constexpr (a * (b * c))"); 10013 verifyIndependentOfContext("if CONSTEXPR (a * (b * c))"); 10014 verifyIndependentOfContext("if (a::b::c::d & b[i])"); 10015 verifyIndependentOfContext("if (*b[i])"); 10016 verifyIndependentOfContext("if (int *a = (&b))"); 10017 verifyIndependentOfContext("while (int *a = &b)"); 10018 verifyIndependentOfContext("while (a * (b * c))"); 10019 verifyIndependentOfContext("size = sizeof *a;"); 10020 verifyIndependentOfContext("if (a && (b = c))"); 10021 verifyFormat("void f() {\n" 10022 " for (const int &v : Values) {\n" 10023 " }\n" 10024 "}"); 10025 verifyFormat("for (int i = a * a; i < 10; ++i) {\n}"); 10026 verifyFormat("for (int i = 0; i < a * a; ++i) {\n}"); 10027 verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}"); 10028 10029 verifyFormat("#define A (!a * b)"); 10030 verifyFormat("#define MACRO \\\n" 10031 " int *i = a * b; \\\n" 10032 " void f(a *b);", 10033 getLLVMStyleWithColumns(19)); 10034 10035 verifyIndependentOfContext("A = new SomeType *[Length];"); 10036 verifyIndependentOfContext("A = new SomeType *[Length]();"); 10037 verifyIndependentOfContext("T **t = new T *;"); 10038 verifyIndependentOfContext("T **t = new T *();"); 10039 verifyGoogleFormat("A = new SomeType*[Length]();"); 10040 verifyGoogleFormat("A = new SomeType*[Length];"); 10041 verifyGoogleFormat("T** t = new T*;"); 10042 verifyGoogleFormat("T** t = new T*();"); 10043 10044 verifyFormat("STATIC_ASSERT((a & b) == 0);"); 10045 verifyFormat("STATIC_ASSERT(0 == (a & b));"); 10046 verifyFormat("template <bool a, bool b> " 10047 "typename t::if<x && y>::type f() {}"); 10048 verifyFormat("template <int *y> f() {}"); 10049 verifyFormat("vector<int *> v;"); 10050 verifyFormat("vector<int *const> v;"); 10051 verifyFormat("vector<int *const **const *> v;"); 10052 verifyFormat("vector<int *volatile> v;"); 10053 verifyFormat("vector<a *_Nonnull> v;"); 10054 verifyFormat("vector<a *_Nullable> v;"); 10055 verifyFormat("vector<a *_Null_unspecified> v;"); 10056 verifyFormat("vector<a *__ptr32> v;"); 10057 verifyFormat("vector<a *__ptr64> v;"); 10058 verifyFormat("vector<a *__capability> v;"); 10059 FormatStyle TypeMacros = getLLVMStyle(); 10060 TypeMacros.TypenameMacros = {"LIST"}; 10061 verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros); 10062 verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros); 10063 verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros); 10064 verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros); 10065 verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication 10066 10067 FormatStyle CustomQualifier = getLLVMStyle(); 10068 // Add identifiers that should not be parsed as a qualifier by default. 10069 CustomQualifier.AttributeMacros.push_back("__my_qualifier"); 10070 CustomQualifier.AttributeMacros.push_back("_My_qualifier"); 10071 CustomQualifier.AttributeMacros.push_back("my_other_qualifier"); 10072 verifyFormat("vector<a * __my_qualifier> parse_as_multiply;"); 10073 verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier); 10074 verifyFormat("vector<a * _My_qualifier> parse_as_multiply;"); 10075 verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier); 10076 verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;"); 10077 verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier); 10078 verifyFormat("vector<a * _NotAQualifier> v;"); 10079 verifyFormat("vector<a * __not_a_qualifier> v;"); 10080 verifyFormat("vector<a * b> v;"); 10081 verifyFormat("foo<b && false>();"); 10082 verifyFormat("foo<b & 1>();"); 10083 verifyFormat("decltype(*::std::declval<const T &>()) void F();"); 10084 verifyFormat("typeof(*::std::declval<const T &>()) void F();"); 10085 verifyFormat("_Atomic(*::std::declval<const T &>()) void F();"); 10086 verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();"); 10087 verifyFormat( 10088 "template <class T, class = typename std::enable_if<\n" 10089 " std::is_integral<T>::value &&\n" 10090 " (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n" 10091 "void F();", 10092 getLLVMStyleWithColumns(70)); 10093 verifyFormat("template <class T,\n" 10094 " class = typename std::enable_if<\n" 10095 " std::is_integral<T>::value &&\n" 10096 " (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n" 10097 " class U>\n" 10098 "void F();", 10099 getLLVMStyleWithColumns(70)); 10100 verifyFormat( 10101 "template <class T,\n" 10102 " class = typename ::std::enable_if<\n" 10103 " ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n" 10104 "void F();", 10105 getGoogleStyleWithColumns(68)); 10106 10107 verifyIndependentOfContext("MACRO(int *i);"); 10108 verifyIndependentOfContext("MACRO(auto *a);"); 10109 verifyIndependentOfContext("MACRO(const A *a);"); 10110 verifyIndependentOfContext("MACRO(_Atomic(A) *a);"); 10111 verifyIndependentOfContext("MACRO(decltype(A) *a);"); 10112 verifyIndependentOfContext("MACRO(typeof(A) *a);"); 10113 verifyIndependentOfContext("MACRO(__underlying_type(A) *a);"); 10114 verifyIndependentOfContext("MACRO(A *const a);"); 10115 verifyIndependentOfContext("MACRO(A *restrict a);"); 10116 verifyIndependentOfContext("MACRO(A *__restrict__ a);"); 10117 verifyIndependentOfContext("MACRO(A *__restrict a);"); 10118 verifyIndependentOfContext("MACRO(A *volatile a);"); 10119 verifyIndependentOfContext("MACRO(A *__volatile a);"); 10120 verifyIndependentOfContext("MACRO(A *__volatile__ a);"); 10121 verifyIndependentOfContext("MACRO(A *_Nonnull a);"); 10122 verifyIndependentOfContext("MACRO(A *_Nullable a);"); 10123 verifyIndependentOfContext("MACRO(A *_Null_unspecified a);"); 10124 verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);"); 10125 verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);"); 10126 verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);"); 10127 verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);"); 10128 verifyIndependentOfContext("MACRO(A *__ptr32 a);"); 10129 verifyIndependentOfContext("MACRO(A *__ptr64 a);"); 10130 verifyIndependentOfContext("MACRO(A *__capability);"); 10131 verifyIndependentOfContext("MACRO(A &__capability);"); 10132 verifyFormat("MACRO(A *__my_qualifier);"); // type declaration 10133 verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication 10134 // If we add __my_qualifier to AttributeMacros it should always be parsed as 10135 // a type declaration: 10136 verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier); 10137 verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier); 10138 // Also check that TypenameMacros prevents parsing it as multiplication: 10139 verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication 10140 verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type 10141 10142 verifyIndependentOfContext("MACRO('0' <= c && c <= '9');"); 10143 verifyFormat("void f() { f(float{1}, a * a); }"); 10144 verifyFormat("void f() { f(float(1), a * a); }"); 10145 10146 verifyFormat("f((void (*)(int))g);"); 10147 verifyFormat("f((void (&)(int))g);"); 10148 verifyFormat("f((void (^)(int))g);"); 10149 10150 // FIXME: Is there a way to make this work? 10151 // verifyIndependentOfContext("MACRO(A *a);"); 10152 verifyFormat("MACRO(A &B);"); 10153 verifyFormat("MACRO(A *B);"); 10154 verifyFormat("void f() { MACRO(A * B); }"); 10155 verifyFormat("void f() { MACRO(A & B); }"); 10156 10157 // This lambda was mis-formatted after D88956 (treating it as a binop): 10158 verifyFormat("auto x = [](const decltype(x) &ptr) {};"); 10159 verifyFormat("auto x = [](const decltype(x) *ptr) {};"); 10160 verifyFormat("#define lambda [](const decltype(x) &ptr) {}"); 10161 verifyFormat("#define lambda [](const decltype(x) *ptr) {}"); 10162 10163 verifyFormat("DatumHandle const *operator->() const { return input_; }"); 10164 verifyFormat("return options != nullptr && operator==(*options);"); 10165 10166 EXPECT_EQ("#define OP(x) \\\n" 10167 " ostream &operator<<(ostream &s, const A &a) { \\\n" 10168 " return s << a.DebugString(); \\\n" 10169 " }", 10170 format("#define OP(x) \\\n" 10171 " ostream &operator<<(ostream &s, const A &a) { \\\n" 10172 " return s << a.DebugString(); \\\n" 10173 " }", 10174 getLLVMStyleWithColumns(50))); 10175 10176 // FIXME: We cannot handle this case yet; we might be able to figure out that 10177 // foo<x> d > v; doesn't make sense. 10178 verifyFormat("foo<a<b && c> d> v;"); 10179 10180 FormatStyle PointerMiddle = getLLVMStyle(); 10181 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle; 10182 verifyFormat("delete *x;", PointerMiddle); 10183 verifyFormat("int * x;", PointerMiddle); 10184 verifyFormat("int *[] x;", PointerMiddle); 10185 verifyFormat("template <int * y> f() {}", PointerMiddle); 10186 verifyFormat("int * f(int * a) {}", PointerMiddle); 10187 verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle); 10188 verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle); 10189 verifyFormat("A<int *> a;", PointerMiddle); 10190 verifyFormat("A<int **> a;", PointerMiddle); 10191 verifyFormat("A<int *, int *> a;", PointerMiddle); 10192 verifyFormat("A<int *[]> a;", PointerMiddle); 10193 verifyFormat("A = new SomeType *[Length]();", PointerMiddle); 10194 verifyFormat("A = new SomeType *[Length];", PointerMiddle); 10195 verifyFormat("T ** t = new T *;", PointerMiddle); 10196 10197 // Member function reference qualifiers aren't binary operators. 10198 verifyFormat("string // break\n" 10199 "operator()() & {}"); 10200 verifyFormat("string // break\n" 10201 "operator()() && {}"); 10202 verifyGoogleFormat("template <typename T>\n" 10203 "auto x() & -> int {}"); 10204 10205 // Should be binary operators when used as an argument expression (overloaded 10206 // operator invoked as a member function). 10207 verifyFormat("void f() { a.operator()(a * a); }"); 10208 verifyFormat("void f() { a->operator()(a & a); }"); 10209 verifyFormat("void f() { a.operator()(*a & *a); }"); 10210 verifyFormat("void f() { a->operator()(*a * *a); }"); 10211 10212 verifyFormat("int operator()(T (&&)[N]) { return 1; }"); 10213 verifyFormat("int operator()(T (&)[N]) { return 0; }"); 10214 } 10215 10216 TEST_F(FormatTest, UnderstandsAttributes) { 10217 verifyFormat("SomeType s __attribute__((unused)) (InitValue);"); 10218 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n" 10219 "aaaaaaaaaaaaaaaaaaaaaaa(int i);"); 10220 verifyFormat("__attribute__((nodebug)) ::qualified_type f();"); 10221 FormatStyle AfterType = getLLVMStyle(); 10222 AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 10223 verifyFormat("__attribute__((nodebug)) void\n" 10224 "foo() {}\n", 10225 AfterType); 10226 verifyFormat("__unused void\n" 10227 "foo() {}", 10228 AfterType); 10229 10230 FormatStyle CustomAttrs = getLLVMStyle(); 10231 CustomAttrs.AttributeMacros.push_back("__unused"); 10232 CustomAttrs.AttributeMacros.push_back("__attr1"); 10233 CustomAttrs.AttributeMacros.push_back("__attr2"); 10234 CustomAttrs.AttributeMacros.push_back("no_underscore_attr"); 10235 verifyFormat("vector<SomeType *__attribute((foo))> v;"); 10236 verifyFormat("vector<SomeType *__attribute__((foo))> v;"); 10237 verifyFormat("vector<SomeType * __not_attribute__((foo))> v;"); 10238 // Check that it is parsed as a multiplication without AttributeMacros and 10239 // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros. 10240 verifyFormat("vector<SomeType * __attr1> v;"); 10241 verifyFormat("vector<SomeType __attr1 *> v;"); 10242 verifyFormat("vector<SomeType __attr1 *const> v;"); 10243 verifyFormat("vector<SomeType __attr1 * __attr2> v;"); 10244 verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs); 10245 verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs); 10246 verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs); 10247 verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs); 10248 verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs); 10249 verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs); 10250 verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs); 10251 10252 // Check that these are not parsed as function declarations: 10253 CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 10254 CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman; 10255 verifyFormat("SomeType s(InitValue);", CustomAttrs); 10256 verifyFormat("SomeType s{InitValue};", CustomAttrs); 10257 verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs); 10258 verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs); 10259 verifyFormat("SomeType s __unused(InitValue);", CustomAttrs); 10260 verifyFormat("SomeType s __unused{InitValue};", CustomAttrs); 10261 verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs); 10262 verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs); 10263 } 10264 10265 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) { 10266 // Check that qualifiers on pointers don't break parsing of casts. 10267 verifyFormat("x = (foo *const)*v;"); 10268 verifyFormat("x = (foo *volatile)*v;"); 10269 verifyFormat("x = (foo *restrict)*v;"); 10270 verifyFormat("x = (foo *__attribute__((foo)))*v;"); 10271 verifyFormat("x = (foo *_Nonnull)*v;"); 10272 verifyFormat("x = (foo *_Nullable)*v;"); 10273 verifyFormat("x = (foo *_Null_unspecified)*v;"); 10274 verifyFormat("x = (foo *_Nonnull)*v;"); 10275 verifyFormat("x = (foo *[[clang::attr]])*v;"); 10276 verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;"); 10277 verifyFormat("x = (foo *__ptr32)*v;"); 10278 verifyFormat("x = (foo *__ptr64)*v;"); 10279 verifyFormat("x = (foo *__capability)*v;"); 10280 10281 // Check that we handle multiple trailing qualifiers and skip them all to 10282 // determine that the expression is a cast to a pointer type. 10283 FormatStyle LongPointerRight = getLLVMStyleWithColumns(999); 10284 FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999); 10285 LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left; 10286 StringRef AllQualifiers = 10287 "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified " 10288 "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability"; 10289 verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight); 10290 verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft); 10291 10292 // Also check that address-of is not parsed as a binary bitwise-and: 10293 verifyFormat("x = (foo *const)&v;"); 10294 verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight); 10295 verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft); 10296 10297 // Check custom qualifiers: 10298 FormatStyle CustomQualifier = getLLVMStyleWithColumns(999); 10299 CustomQualifier.AttributeMacros.push_back("__my_qualifier"); 10300 verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier. 10301 verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier); 10302 verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(), 10303 CustomQualifier); 10304 verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(), 10305 CustomQualifier); 10306 10307 // Check that unknown identifiers result in binary operator parsing: 10308 verifyFormat("x = (foo * __unknown_qualifier) * v;"); 10309 verifyFormat("x = (foo * __unknown_qualifier) & v;"); 10310 } 10311 10312 TEST_F(FormatTest, UnderstandsSquareAttributes) { 10313 verifyFormat("SomeType s [[unused]] (InitValue);"); 10314 verifyFormat("SomeType s [[gnu::unused]] (InitValue);"); 10315 verifyFormat("SomeType s [[using gnu: unused]] (InitValue);"); 10316 verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}"); 10317 verifyFormat("void f() [[deprecated(\"so sorry\")]];"); 10318 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10319 " [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);"); 10320 verifyFormat("[[nodiscard]] bool f() { return false; }"); 10321 verifyFormat("class [[nodiscard]] f {\npublic:\n f() {}\n}"); 10322 verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n f() {}\n}"); 10323 verifyFormat("class [[gnu::unused]] f {\npublic:\n f() {}\n}"); 10324 verifyFormat("[[nodiscard]] ::qualified_type f();"); 10325 10326 // Make sure we do not mistake attributes for array subscripts. 10327 verifyFormat("int a() {}\n" 10328 "[[unused]] int b() {}\n"); 10329 verifyFormat("NSArray *arr;\n" 10330 "arr[[Foo() bar]];"); 10331 10332 // On the other hand, we still need to correctly find array subscripts. 10333 verifyFormat("int a = std::vector<int>{1, 2, 3}[0];"); 10334 10335 // Make sure that we do not mistake Objective-C method inside array literals 10336 // as attributes, even if those method names are also keywords. 10337 verifyFormat("@[ [foo bar] ];"); 10338 verifyFormat("@[ [NSArray class] ];"); 10339 verifyFormat("@[ [foo enum] ];"); 10340 10341 verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }"); 10342 10343 // Make sure we do not parse attributes as lambda introducers. 10344 FormatStyle MultiLineFunctions = getLLVMStyle(); 10345 MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 10346 verifyFormat("[[unused]] int b() {\n" 10347 " return 42;\n" 10348 "}\n", 10349 MultiLineFunctions); 10350 } 10351 10352 TEST_F(FormatTest, AttributeClass) { 10353 FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp); 10354 verifyFormat("class S {\n" 10355 " S(S&&) = default;\n" 10356 "};", 10357 Style); 10358 verifyFormat("class [[nodiscard]] S {\n" 10359 " S(S&&) = default;\n" 10360 "};", 10361 Style); 10362 verifyFormat("class __attribute((maybeunused)) S {\n" 10363 " S(S&&) = default;\n" 10364 "};", 10365 Style); 10366 verifyFormat("struct S {\n" 10367 " S(S&&) = default;\n" 10368 "};", 10369 Style); 10370 verifyFormat("struct [[nodiscard]] S {\n" 10371 " S(S&&) = default;\n" 10372 "};", 10373 Style); 10374 } 10375 10376 TEST_F(FormatTest, AttributesAfterMacro) { 10377 FormatStyle Style = getLLVMStyle(); 10378 verifyFormat("MACRO;\n" 10379 "__attribute__((maybe_unused)) int foo() {\n" 10380 " //...\n" 10381 "}"); 10382 10383 verifyFormat("MACRO;\n" 10384 "[[nodiscard]] int foo() {\n" 10385 " //...\n" 10386 "}"); 10387 10388 EXPECT_EQ("MACRO\n\n" 10389 "__attribute__((maybe_unused)) int foo() {\n" 10390 " //...\n" 10391 "}", 10392 format("MACRO\n\n" 10393 "__attribute__((maybe_unused)) int foo() {\n" 10394 " //...\n" 10395 "}")); 10396 10397 EXPECT_EQ("MACRO\n\n" 10398 "[[nodiscard]] int foo() {\n" 10399 " //...\n" 10400 "}", 10401 format("MACRO\n\n" 10402 "[[nodiscard]] int foo() {\n" 10403 " //...\n" 10404 "}")); 10405 } 10406 10407 TEST_F(FormatTest, AttributePenaltyBreaking) { 10408 FormatStyle Style = getLLVMStyle(); 10409 verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n" 10410 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}", 10411 Style); 10412 verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n" 10413 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}", 10414 Style); 10415 verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const " 10416 "shared_ptr<ALongTypeName> &C d) {\n}", 10417 Style); 10418 } 10419 10420 TEST_F(FormatTest, UnderstandsEllipsis) { 10421 FormatStyle Style = getLLVMStyle(); 10422 verifyFormat("int printf(const char *fmt, ...);"); 10423 verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }"); 10424 verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}"); 10425 10426 verifyFormat("template <int *...PP> a;", Style); 10427 10428 Style.PointerAlignment = FormatStyle::PAS_Left; 10429 verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style); 10430 10431 verifyFormat("template <int*... PP> a;", Style); 10432 10433 Style.PointerAlignment = FormatStyle::PAS_Middle; 10434 verifyFormat("template <int *... PP> a;", Style); 10435 } 10436 10437 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) { 10438 EXPECT_EQ("int *a;\n" 10439 "int *a;\n" 10440 "int *a;", 10441 format("int *a;\n" 10442 "int* a;\n" 10443 "int *a;", 10444 getGoogleStyle())); 10445 EXPECT_EQ("int* a;\n" 10446 "int* a;\n" 10447 "int* a;", 10448 format("int* a;\n" 10449 "int* a;\n" 10450 "int *a;", 10451 getGoogleStyle())); 10452 EXPECT_EQ("int *a;\n" 10453 "int *a;\n" 10454 "int *a;", 10455 format("int *a;\n" 10456 "int * a;\n" 10457 "int * a;", 10458 getGoogleStyle())); 10459 EXPECT_EQ("auto x = [] {\n" 10460 " int *a;\n" 10461 " int *a;\n" 10462 " int *a;\n" 10463 "};", 10464 format("auto x=[]{int *a;\n" 10465 "int * a;\n" 10466 "int * a;};", 10467 getGoogleStyle())); 10468 } 10469 10470 TEST_F(FormatTest, UnderstandsRvalueReferences) { 10471 verifyFormat("int f(int &&a) {}"); 10472 verifyFormat("int f(int a, char &&b) {}"); 10473 verifyFormat("void f() { int &&a = b; }"); 10474 verifyGoogleFormat("int f(int a, char&& b) {}"); 10475 verifyGoogleFormat("void f() { int&& a = b; }"); 10476 10477 verifyIndependentOfContext("A<int &&> a;"); 10478 verifyIndependentOfContext("A<int &&, int &&> a;"); 10479 verifyGoogleFormat("A<int&&> a;"); 10480 verifyGoogleFormat("A<int&&, int&&> a;"); 10481 10482 // Not rvalue references: 10483 verifyFormat("template <bool B, bool C> class A {\n" 10484 " static_assert(B && C, \"Something is wrong\");\n" 10485 "};"); 10486 verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))"); 10487 verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))"); 10488 verifyFormat("#define A(a, b) (a && b)"); 10489 } 10490 10491 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) { 10492 verifyFormat("void f() {\n" 10493 " x[aaaaaaaaa -\n" 10494 " b] = 23;\n" 10495 "}", 10496 getLLVMStyleWithColumns(15)); 10497 } 10498 10499 TEST_F(FormatTest, FormatsCasts) { 10500 verifyFormat("Type *A = static_cast<Type *>(P);"); 10501 verifyFormat("Type *A = (Type *)P;"); 10502 verifyFormat("Type *A = (vector<Type *, int *>)P;"); 10503 verifyFormat("int a = (int)(2.0f);"); 10504 verifyFormat("int a = (int)2.0f;"); 10505 verifyFormat("x[(int32)y];"); 10506 verifyFormat("x = (int32)y;"); 10507 verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)"); 10508 verifyFormat("int a = (int)*b;"); 10509 verifyFormat("int a = (int)2.0f;"); 10510 verifyFormat("int a = (int)~0;"); 10511 verifyFormat("int a = (int)++a;"); 10512 verifyFormat("int a = (int)sizeof(int);"); 10513 verifyFormat("int a = (int)+2;"); 10514 verifyFormat("my_int a = (my_int)2.0f;"); 10515 verifyFormat("my_int a = (my_int)sizeof(int);"); 10516 verifyFormat("return (my_int)aaa;"); 10517 verifyFormat("#define x ((int)-1)"); 10518 verifyFormat("#define LENGTH(x, y) (x) - (y) + 1"); 10519 verifyFormat("#define p(q) ((int *)&q)"); 10520 verifyFormat("fn(a)(b) + 1;"); 10521 10522 verifyFormat("void f() { my_int a = (my_int)*b; }"); 10523 verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }"); 10524 verifyFormat("my_int a = (my_int)~0;"); 10525 verifyFormat("my_int a = (my_int)++a;"); 10526 verifyFormat("my_int a = (my_int)-2;"); 10527 verifyFormat("my_int a = (my_int)1;"); 10528 verifyFormat("my_int a = (my_int *)1;"); 10529 verifyFormat("my_int a = (const my_int)-1;"); 10530 verifyFormat("my_int a = (const my_int *)-1;"); 10531 verifyFormat("my_int a = (my_int)(my_int)-1;"); 10532 verifyFormat("my_int a = (ns::my_int)-2;"); 10533 verifyFormat("case (my_int)ONE:"); 10534 verifyFormat("auto x = (X)this;"); 10535 // Casts in Obj-C style calls used to not be recognized as such. 10536 verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle()); 10537 10538 // FIXME: single value wrapped with paren will be treated as cast. 10539 verifyFormat("void f(int i = (kValue)*kMask) {}"); 10540 10541 verifyFormat("{ (void)F; }"); 10542 10543 // Don't break after a cast's 10544 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 10545 " (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n" 10546 " bbbbbbbbbbbbbbbbbbbbbb);"); 10547 10548 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(x)"); 10549 verifyFormat("#define CONF_BOOL(x) (bool *)(x)"); 10550 verifyFormat("#define CONF_BOOL(x) (bool)(x)"); 10551 verifyFormat("bool *y = (bool *)(void *)(x);"); 10552 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)(x)"); 10553 verifyFormat("bool *y = (bool *)(void *)(int)(x);"); 10554 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)foo(x)"); 10555 verifyFormat("bool *y = (bool *)(void *)(int)foo(x);"); 10556 10557 // These are not casts. 10558 verifyFormat("void f(int *) {}"); 10559 verifyFormat("f(foo)->b;"); 10560 verifyFormat("f(foo).b;"); 10561 verifyFormat("f(foo)(b);"); 10562 verifyFormat("f(foo)[b];"); 10563 verifyFormat("[](foo) { return 4; }(bar);"); 10564 verifyFormat("(*funptr)(foo)[4];"); 10565 verifyFormat("funptrs[4](foo)[4];"); 10566 verifyFormat("void f(int *);"); 10567 verifyFormat("void f(int *) = 0;"); 10568 verifyFormat("void f(SmallVector<int>) {}"); 10569 verifyFormat("void f(SmallVector<int>);"); 10570 verifyFormat("void f(SmallVector<int>) = 0;"); 10571 verifyFormat("void f(int i = (kA * kB) & kMask) {}"); 10572 verifyFormat("int a = sizeof(int) * b;"); 10573 verifyFormat("int a = alignof(int) * b;", getGoogleStyle()); 10574 verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;"); 10575 verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");"); 10576 verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;"); 10577 10578 // These are not casts, but at some point were confused with casts. 10579 verifyFormat("virtual void foo(int *) override;"); 10580 verifyFormat("virtual void foo(char &) const;"); 10581 verifyFormat("virtual void foo(int *a, char *) const;"); 10582 verifyFormat("int a = sizeof(int *) + b;"); 10583 verifyFormat("int a = alignof(int *) + b;", getGoogleStyle()); 10584 verifyFormat("bool b = f(g<int>) && c;"); 10585 verifyFormat("typedef void (*f)(int i) func;"); 10586 verifyFormat("void operator++(int) noexcept;"); 10587 verifyFormat("void operator++(int &) noexcept;"); 10588 verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t " 10589 "&) noexcept;"); 10590 verifyFormat( 10591 "void operator delete(std::size_t, const std::nothrow_t &) noexcept;"); 10592 verifyFormat("void operator delete(const std::nothrow_t &) noexcept;"); 10593 verifyFormat("void operator delete(std::nothrow_t &) noexcept;"); 10594 verifyFormat("void operator delete(nothrow_t &) noexcept;"); 10595 verifyFormat("void operator delete(foo &) noexcept;"); 10596 verifyFormat("void operator delete(foo) noexcept;"); 10597 verifyFormat("void operator delete(int) noexcept;"); 10598 verifyFormat("void operator delete(int &) noexcept;"); 10599 verifyFormat("void operator delete(int &) volatile noexcept;"); 10600 verifyFormat("void operator delete(int &) const"); 10601 verifyFormat("void operator delete(int &) = default"); 10602 verifyFormat("void operator delete(int &) = delete"); 10603 verifyFormat("void operator delete(int &) [[noreturn]]"); 10604 verifyFormat("void operator delete(int &) throw();"); 10605 verifyFormat("void operator delete(int &) throw(int);"); 10606 verifyFormat("auto operator delete(int &) -> int;"); 10607 verifyFormat("auto operator delete(int &) override"); 10608 verifyFormat("auto operator delete(int &) final"); 10609 10610 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n" 10611 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 10612 // FIXME: The indentation here is not ideal. 10613 verifyFormat( 10614 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10615 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n" 10616 " [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];"); 10617 } 10618 10619 TEST_F(FormatTest, FormatsFunctionTypes) { 10620 verifyFormat("A<bool()> a;"); 10621 verifyFormat("A<SomeType()> a;"); 10622 verifyFormat("A<void (*)(int, std::string)> a;"); 10623 verifyFormat("A<void *(int)>;"); 10624 verifyFormat("void *(*a)(int *, SomeType *);"); 10625 verifyFormat("int (*func)(void *);"); 10626 verifyFormat("void f() { int (*func)(void *); }"); 10627 verifyFormat("template <class CallbackClass>\n" 10628 "using MyCallback = void (CallbackClass::*)(SomeObject *Data);"); 10629 10630 verifyGoogleFormat("A<void*(int*, SomeType*)>;"); 10631 verifyGoogleFormat("void* (*a)(int);"); 10632 verifyGoogleFormat( 10633 "template <class CallbackClass>\n" 10634 "using MyCallback = void (CallbackClass::*)(SomeObject* Data);"); 10635 10636 // Other constructs can look somewhat like function types: 10637 verifyFormat("A<sizeof(*x)> a;"); 10638 verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)"); 10639 verifyFormat("some_var = function(*some_pointer_var)[0];"); 10640 verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }"); 10641 verifyFormat("int x = f(&h)();"); 10642 verifyFormat("returnsFunction(¶m1, ¶m2)(param);"); 10643 verifyFormat("std::function<\n" 10644 " LooooooooooongTemplatedType<\n" 10645 " SomeType>*(\n" 10646 " LooooooooooooooooongType type)>\n" 10647 " function;", 10648 getGoogleStyleWithColumns(40)); 10649 } 10650 10651 TEST_F(FormatTest, FormatsPointersToArrayTypes) { 10652 verifyFormat("A (*foo_)[6];"); 10653 verifyFormat("vector<int> (*foo_)[6];"); 10654 } 10655 10656 TEST_F(FormatTest, BreaksLongVariableDeclarations) { 10657 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10658 " LoooooooooooooooooooooooooooooooooooooooongVariable;"); 10659 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n" 10660 " LoooooooooooooooooooooooooooooooooooooooongVariable;"); 10661 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10662 " *LoooooooooooooooooooooooooooooooooooooooongVariable;"); 10663 10664 // Different ways of ()-initializiation. 10665 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10666 " LoooooooooooooooooooooooooooooooooooooooongVariable(1);"); 10667 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10668 " LoooooooooooooooooooooooooooooooooooooooongVariable(a);"); 10669 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10670 " LoooooooooooooooooooooooooooooooooooooooongVariable({});"); 10671 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10672 " LoooooooooooooooooooooooooooooooooooooongVariable([A a]);"); 10673 10674 // Lambdas should not confuse the variable declaration heuristic. 10675 verifyFormat("LooooooooooooooooongType\n" 10676 " variable(nullptr, [](A *a) {});", 10677 getLLVMStyleWithColumns(40)); 10678 } 10679 10680 TEST_F(FormatTest, BreaksLongDeclarations) { 10681 verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n" 10682 " AnotherNameForTheLongType;"); 10683 verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n" 10684 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 10685 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10686 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();"); 10687 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n" 10688 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();"); 10689 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10690 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10691 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n" 10692 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10693 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n" 10694 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10695 verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n" 10696 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10697 verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n" 10698 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10699 verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n" 10700 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10701 verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n" 10702 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10703 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10704 "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);"); 10705 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10706 "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}"); 10707 FormatStyle Indented = getLLVMStyle(); 10708 Indented.IndentWrappedFunctionNames = true; 10709 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10710 " LoooooooooooooooooooooooooooooooongFunctionDeclaration();", 10711 Indented); 10712 verifyFormat( 10713 "LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10714 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 10715 Indented); 10716 verifyFormat( 10717 "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n" 10718 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 10719 Indented); 10720 verifyFormat( 10721 "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n" 10722 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 10723 Indented); 10724 10725 // FIXME: Without the comment, this breaks after "(". 10726 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType // break\n" 10727 " (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();", 10728 getGoogleStyle()); 10729 10730 verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n" 10731 " int LoooooooooooooooooooongParam2) {}"); 10732 verifyFormat( 10733 "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n" 10734 " SourceLocation L, IdentifierIn *II,\n" 10735 " Type *T) {}"); 10736 verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n" 10737 "ReallyReaaallyLongFunctionName(\n" 10738 " const std::string &SomeParameter,\n" 10739 " const SomeType<string, SomeOtherTemplateParameter>\n" 10740 " &ReallyReallyLongParameterName,\n" 10741 " const SomeType<string, SomeOtherTemplateParameter>\n" 10742 " &AnotherLongParameterName) {}"); 10743 verifyFormat("template <typename A>\n" 10744 "SomeLoooooooooooooooooooooongType<\n" 10745 " typename some_namespace::SomeOtherType<A>::Type>\n" 10746 "Function() {}"); 10747 10748 verifyGoogleFormat( 10749 "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n" 10750 " aaaaaaaaaaaaaaaaaaaaaaa;"); 10751 verifyGoogleFormat( 10752 "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n" 10753 " SourceLocation L) {}"); 10754 verifyGoogleFormat( 10755 "some_namespace::LongReturnType\n" 10756 "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n" 10757 " int first_long_parameter, int second_parameter) {}"); 10758 10759 verifyGoogleFormat("template <typename T>\n" 10760 "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n" 10761 "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}"); 10762 verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 10763 " int aaaaaaaaaaaaaaaaaaaaaaa);"); 10764 10765 verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n" 10766 " const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10767 " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 10768 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 10769 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n" 10770 " aaaaaaaaaaaaaaaaaaaaaaaa);"); 10771 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 10772 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 10773 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n" 10774 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 10775 10776 verifyFormat("template <typename T> // Templates on own line.\n" 10777 "static int // Some comment.\n" 10778 "MyFunction(int a);", 10779 getLLVMStyle()); 10780 } 10781 10782 TEST_F(FormatTest, FormatsAccessModifiers) { 10783 FormatStyle Style = getLLVMStyle(); 10784 EXPECT_EQ(Style.EmptyLineBeforeAccessModifier, 10785 FormatStyle::ELBAMS_LogicalBlock); 10786 verifyFormat("struct foo {\n" 10787 "private:\n" 10788 " void f() {}\n" 10789 "\n" 10790 "private:\n" 10791 " int i;\n" 10792 "\n" 10793 "protected:\n" 10794 " int j;\n" 10795 "};\n", 10796 Style); 10797 verifyFormat("struct foo {\n" 10798 "private:\n" 10799 " void f() {}\n" 10800 "\n" 10801 "private:\n" 10802 " int i;\n" 10803 "\n" 10804 "protected:\n" 10805 " int j;\n" 10806 "};\n", 10807 "struct foo {\n" 10808 "private:\n" 10809 " void f() {}\n" 10810 "private:\n" 10811 " int i;\n" 10812 "protected:\n" 10813 " int j;\n" 10814 "};\n", 10815 Style); 10816 verifyFormat("struct foo { /* comment */\n" 10817 "private:\n" 10818 " int i;\n" 10819 " // comment\n" 10820 "private:\n" 10821 " int j;\n" 10822 "};\n", 10823 Style); 10824 verifyFormat("struct foo {\n" 10825 "#ifdef FOO\n" 10826 "#endif\n" 10827 "private:\n" 10828 " int i;\n" 10829 "#ifdef FOO\n" 10830 "private:\n" 10831 "#endif\n" 10832 " int j;\n" 10833 "};\n", 10834 Style); 10835 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 10836 verifyFormat("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 {\n" 10846 "private:\n" 10847 " void f() {}\n" 10848 "private:\n" 10849 " int i;\n" 10850 "protected:\n" 10851 " int j;\n" 10852 "};\n", 10853 "struct foo {\n" 10854 "\n" 10855 "private:\n" 10856 " void f() {}\n" 10857 "\n" 10858 "private:\n" 10859 " int i;\n" 10860 "\n" 10861 "protected:\n" 10862 " int j;\n" 10863 "};\n", 10864 Style); 10865 verifyFormat("struct foo { /* comment */\n" 10866 "private:\n" 10867 " int i;\n" 10868 " // comment\n" 10869 "private:\n" 10870 " int j;\n" 10871 "};\n", 10872 "struct foo { /* comment */\n" 10873 "\n" 10874 "private:\n" 10875 " int i;\n" 10876 " // comment\n" 10877 "\n" 10878 "private:\n" 10879 " int j;\n" 10880 "};\n", 10881 Style); 10882 verifyFormat("struct foo {\n" 10883 "#ifdef FOO\n" 10884 "#endif\n" 10885 "private:\n" 10886 " int i;\n" 10887 "#ifdef FOO\n" 10888 "private:\n" 10889 "#endif\n" 10890 " int j;\n" 10891 "};\n", 10892 "struct foo {\n" 10893 "#ifdef FOO\n" 10894 "#endif\n" 10895 "\n" 10896 "private:\n" 10897 " int i;\n" 10898 "#ifdef FOO\n" 10899 "\n" 10900 "private:\n" 10901 "#endif\n" 10902 " int j;\n" 10903 "};\n", 10904 Style); 10905 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 10906 verifyFormat("struct foo {\n" 10907 "private:\n" 10908 " void f() {}\n" 10909 "\n" 10910 "private:\n" 10911 " int i;\n" 10912 "\n" 10913 "protected:\n" 10914 " int j;\n" 10915 "};\n", 10916 Style); 10917 verifyFormat("struct foo {\n" 10918 "private:\n" 10919 " void f() {}\n" 10920 "\n" 10921 "private:\n" 10922 " int i;\n" 10923 "\n" 10924 "protected:\n" 10925 " int j;\n" 10926 "};\n", 10927 "struct foo {\n" 10928 "private:\n" 10929 " void f() {}\n" 10930 "private:\n" 10931 " int i;\n" 10932 "protected:\n" 10933 " int j;\n" 10934 "};\n", 10935 Style); 10936 verifyFormat("struct foo { /* comment */\n" 10937 "private:\n" 10938 " int i;\n" 10939 " // comment\n" 10940 "\n" 10941 "private:\n" 10942 " int j;\n" 10943 "};\n", 10944 "struct foo { /* comment */\n" 10945 "private:\n" 10946 " int i;\n" 10947 " // comment\n" 10948 "\n" 10949 "private:\n" 10950 " int j;\n" 10951 "};\n", 10952 Style); 10953 verifyFormat("struct foo {\n" 10954 "#ifdef FOO\n" 10955 "#endif\n" 10956 "\n" 10957 "private:\n" 10958 " int i;\n" 10959 "#ifdef FOO\n" 10960 "\n" 10961 "private:\n" 10962 "#endif\n" 10963 " int j;\n" 10964 "};\n", 10965 "struct foo {\n" 10966 "#ifdef FOO\n" 10967 "#endif\n" 10968 "private:\n" 10969 " int i;\n" 10970 "#ifdef FOO\n" 10971 "private:\n" 10972 "#endif\n" 10973 " int j;\n" 10974 "};\n", 10975 Style); 10976 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 10977 EXPECT_EQ("struct foo {\n" 10978 "\n" 10979 "private:\n" 10980 " void f() {}\n" 10981 "\n" 10982 "private:\n" 10983 " int i;\n" 10984 "\n" 10985 "protected:\n" 10986 " int j;\n" 10987 "};\n", 10988 format("struct foo {\n" 10989 "\n" 10990 "private:\n" 10991 " void f() {}\n" 10992 "\n" 10993 "private:\n" 10994 " int i;\n" 10995 "\n" 10996 "protected:\n" 10997 " int j;\n" 10998 "};\n", 10999 Style)); 11000 verifyFormat("struct foo {\n" 11001 "private:\n" 11002 " void f() {}\n" 11003 "private:\n" 11004 " int i;\n" 11005 "protected:\n" 11006 " int j;\n" 11007 "};\n", 11008 Style); 11009 EXPECT_EQ("struct foo { /* comment */\n" 11010 "\n" 11011 "private:\n" 11012 " int i;\n" 11013 " // comment\n" 11014 "\n" 11015 "private:\n" 11016 " int j;\n" 11017 "};\n", 11018 format("struct foo { /* comment */\n" 11019 "\n" 11020 "private:\n" 11021 " int i;\n" 11022 " // comment\n" 11023 "\n" 11024 "private:\n" 11025 " int j;\n" 11026 "};\n", 11027 Style)); 11028 verifyFormat("struct foo { /* comment */\n" 11029 "private:\n" 11030 " int i;\n" 11031 " // comment\n" 11032 "private:\n" 11033 " int j;\n" 11034 "};\n", 11035 Style); 11036 EXPECT_EQ("struct foo {\n" 11037 "#ifdef FOO\n" 11038 "#endif\n" 11039 "\n" 11040 "private:\n" 11041 " int i;\n" 11042 "#ifdef FOO\n" 11043 "\n" 11044 "private:\n" 11045 "#endif\n" 11046 " int j;\n" 11047 "};\n", 11048 format("struct foo {\n" 11049 "#ifdef FOO\n" 11050 "#endif\n" 11051 "\n" 11052 "private:\n" 11053 " int i;\n" 11054 "#ifdef FOO\n" 11055 "\n" 11056 "private:\n" 11057 "#endif\n" 11058 " int j;\n" 11059 "};\n", 11060 Style)); 11061 verifyFormat("struct foo {\n" 11062 "#ifdef FOO\n" 11063 "#endif\n" 11064 "private:\n" 11065 " int i;\n" 11066 "#ifdef FOO\n" 11067 "private:\n" 11068 "#endif\n" 11069 " int j;\n" 11070 "};\n", 11071 Style); 11072 11073 FormatStyle NoEmptyLines = getLLVMStyle(); 11074 NoEmptyLines.MaxEmptyLinesToKeep = 0; 11075 verifyFormat("struct foo {\n" 11076 "private:\n" 11077 " void f() {}\n" 11078 "\n" 11079 "private:\n" 11080 " int i;\n" 11081 "\n" 11082 "public:\n" 11083 "protected:\n" 11084 " int j;\n" 11085 "};\n", 11086 NoEmptyLines); 11087 11088 NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11089 verifyFormat("struct foo {\n" 11090 "private:\n" 11091 " void f() {}\n" 11092 "private:\n" 11093 " int i;\n" 11094 "public:\n" 11095 "protected:\n" 11096 " int j;\n" 11097 "};\n", 11098 NoEmptyLines); 11099 11100 NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11101 verifyFormat("struct foo {\n" 11102 "private:\n" 11103 " void f() {}\n" 11104 "\n" 11105 "private:\n" 11106 " int i;\n" 11107 "\n" 11108 "public:\n" 11109 "\n" 11110 "protected:\n" 11111 " int j;\n" 11112 "};\n", 11113 NoEmptyLines); 11114 } 11115 11116 TEST_F(FormatTest, FormatsAfterAccessModifiers) { 11117 11118 FormatStyle Style = getLLVMStyle(); 11119 EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never); 11120 verifyFormat("struct foo {\n" 11121 "private:\n" 11122 " void f() {}\n" 11123 "\n" 11124 "private:\n" 11125 " int i;\n" 11126 "\n" 11127 "protected:\n" 11128 " int j;\n" 11129 "};\n", 11130 Style); 11131 11132 // Check if lines are removed. 11133 verifyFormat("struct foo {\n" 11134 "private:\n" 11135 " void f() {}\n" 11136 "\n" 11137 "private:\n" 11138 " int i;\n" 11139 "\n" 11140 "protected:\n" 11141 " int j;\n" 11142 "};\n", 11143 "struct foo {\n" 11144 "private:\n" 11145 "\n" 11146 " void f() {}\n" 11147 "\n" 11148 "private:\n" 11149 "\n" 11150 " int i;\n" 11151 "\n" 11152 "protected:\n" 11153 "\n" 11154 " int j;\n" 11155 "};\n", 11156 Style); 11157 11158 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11159 verifyFormat("struct foo {\n" 11160 "private:\n" 11161 "\n" 11162 " void f() {}\n" 11163 "\n" 11164 "private:\n" 11165 "\n" 11166 " int i;\n" 11167 "\n" 11168 "protected:\n" 11169 "\n" 11170 " int j;\n" 11171 "};\n", 11172 Style); 11173 11174 // Check if lines are added. 11175 verifyFormat("struct foo {\n" 11176 "private:\n" 11177 "\n" 11178 " void f() {}\n" 11179 "\n" 11180 "private:\n" 11181 "\n" 11182 " int i;\n" 11183 "\n" 11184 "protected:\n" 11185 "\n" 11186 " int j;\n" 11187 "};\n", 11188 "struct foo {\n" 11189 "private:\n" 11190 " void f() {}\n" 11191 "\n" 11192 "private:\n" 11193 " int i;\n" 11194 "\n" 11195 "protected:\n" 11196 " int j;\n" 11197 "};\n", 11198 Style); 11199 11200 // Leave tests rely on the code layout, test::messUp can not be used. 11201 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11202 Style.MaxEmptyLinesToKeep = 0u; 11203 verifyFormat("struct foo {\n" 11204 "private:\n" 11205 " void f() {}\n" 11206 "\n" 11207 "private:\n" 11208 " int i;\n" 11209 "\n" 11210 "protected:\n" 11211 " int j;\n" 11212 "};\n", 11213 Style); 11214 11215 // Check if MaxEmptyLinesToKeep is respected. 11216 EXPECT_EQ("struct foo {\n" 11217 "private:\n" 11218 " void f() {}\n" 11219 "\n" 11220 "private:\n" 11221 " int i;\n" 11222 "\n" 11223 "protected:\n" 11224 " int j;\n" 11225 "};\n", 11226 format("struct foo {\n" 11227 "private:\n" 11228 "\n\n\n" 11229 " void f() {}\n" 11230 "\n" 11231 "private:\n" 11232 "\n\n\n" 11233 " int i;\n" 11234 "\n" 11235 "protected:\n" 11236 "\n\n\n" 11237 " int j;\n" 11238 "};\n", 11239 Style)); 11240 11241 Style.MaxEmptyLinesToKeep = 1u; 11242 EXPECT_EQ("struct foo {\n" 11243 "private:\n" 11244 "\n" 11245 " void f() {}\n" 11246 "\n" 11247 "private:\n" 11248 "\n" 11249 " int i;\n" 11250 "\n" 11251 "protected:\n" 11252 "\n" 11253 " int j;\n" 11254 "};\n", 11255 format("struct foo {\n" 11256 "private:\n" 11257 "\n" 11258 " void f() {}\n" 11259 "\n" 11260 "private:\n" 11261 "\n" 11262 " int i;\n" 11263 "\n" 11264 "protected:\n" 11265 "\n" 11266 " int j;\n" 11267 "};\n", 11268 Style)); 11269 // Check if no lines are kept. 11270 EXPECT_EQ("struct foo {\n" 11271 "private:\n" 11272 " void f() {}\n" 11273 "\n" 11274 "private:\n" 11275 " int i;\n" 11276 "\n" 11277 "protected:\n" 11278 " int j;\n" 11279 "};\n", 11280 format("struct foo {\n" 11281 "private:\n" 11282 " void f() {}\n" 11283 "\n" 11284 "private:\n" 11285 " int i;\n" 11286 "\n" 11287 "protected:\n" 11288 " int j;\n" 11289 "};\n", 11290 Style)); 11291 // Check if MaxEmptyLinesToKeep is respected. 11292 EXPECT_EQ("struct foo {\n" 11293 "private:\n" 11294 "\n" 11295 " void f() {}\n" 11296 "\n" 11297 "private:\n" 11298 "\n" 11299 " int i;\n" 11300 "\n" 11301 "protected:\n" 11302 "\n" 11303 " int j;\n" 11304 "};\n", 11305 format("struct foo {\n" 11306 "private:\n" 11307 "\n\n\n" 11308 " void f() {}\n" 11309 "\n" 11310 "private:\n" 11311 "\n\n\n" 11312 " int i;\n" 11313 "\n" 11314 "protected:\n" 11315 "\n\n\n" 11316 " int j;\n" 11317 "};\n", 11318 Style)); 11319 11320 Style.MaxEmptyLinesToKeep = 10u; 11321 EXPECT_EQ("struct foo {\n" 11322 "private:\n" 11323 "\n\n\n" 11324 " void f() {}\n" 11325 "\n" 11326 "private:\n" 11327 "\n\n\n" 11328 " int i;\n" 11329 "\n" 11330 "protected:\n" 11331 "\n\n\n" 11332 " int j;\n" 11333 "};\n", 11334 format("struct foo {\n" 11335 "private:\n" 11336 "\n\n\n" 11337 " void f() {}\n" 11338 "\n" 11339 "private:\n" 11340 "\n\n\n" 11341 " int i;\n" 11342 "\n" 11343 "protected:\n" 11344 "\n\n\n" 11345 " int j;\n" 11346 "};\n", 11347 Style)); 11348 11349 // Test with comments. 11350 Style = getLLVMStyle(); 11351 verifyFormat("struct foo {\n" 11352 "private:\n" 11353 " // comment\n" 11354 " void f() {}\n" 11355 "\n" 11356 "private: /* comment */\n" 11357 " int i;\n" 11358 "};\n", 11359 Style); 11360 verifyFormat("struct foo {\n" 11361 "private:\n" 11362 " // comment\n" 11363 " void f() {}\n" 11364 "\n" 11365 "private: /* comment */\n" 11366 " int i;\n" 11367 "};\n", 11368 "struct foo {\n" 11369 "private:\n" 11370 "\n" 11371 " // comment\n" 11372 " void f() {}\n" 11373 "\n" 11374 "private: /* comment */\n" 11375 "\n" 11376 " int i;\n" 11377 "};\n", 11378 Style); 11379 11380 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11381 verifyFormat("struct foo {\n" 11382 "private:\n" 11383 "\n" 11384 " // comment\n" 11385 " void f() {}\n" 11386 "\n" 11387 "private: /* comment */\n" 11388 "\n" 11389 " int i;\n" 11390 "};\n", 11391 "struct foo {\n" 11392 "private:\n" 11393 " // comment\n" 11394 " void f() {}\n" 11395 "\n" 11396 "private: /* comment */\n" 11397 " int i;\n" 11398 "};\n", 11399 Style); 11400 verifyFormat("struct foo {\n" 11401 "private:\n" 11402 "\n" 11403 " // comment\n" 11404 " void f() {}\n" 11405 "\n" 11406 "private: /* comment */\n" 11407 "\n" 11408 " int i;\n" 11409 "};\n", 11410 Style); 11411 11412 // Test with preprocessor defines. 11413 Style = getLLVMStyle(); 11414 verifyFormat("struct foo {\n" 11415 "private:\n" 11416 "#ifdef FOO\n" 11417 "#endif\n" 11418 " void f() {}\n" 11419 "};\n", 11420 Style); 11421 verifyFormat("struct foo {\n" 11422 "private:\n" 11423 "#ifdef FOO\n" 11424 "#endif\n" 11425 " void f() {}\n" 11426 "};\n", 11427 "struct foo {\n" 11428 "private:\n" 11429 "\n" 11430 "#ifdef FOO\n" 11431 "#endif\n" 11432 " void f() {}\n" 11433 "};\n", 11434 Style); 11435 11436 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11437 verifyFormat("struct foo {\n" 11438 "private:\n" 11439 "\n" 11440 "#ifdef FOO\n" 11441 "#endif\n" 11442 " void f() {}\n" 11443 "};\n", 11444 "struct foo {\n" 11445 "private:\n" 11446 "#ifdef FOO\n" 11447 "#endif\n" 11448 " void f() {}\n" 11449 "};\n", 11450 Style); 11451 verifyFormat("struct foo {\n" 11452 "private:\n" 11453 "\n" 11454 "#ifdef FOO\n" 11455 "#endif\n" 11456 " void f() {}\n" 11457 "};\n", 11458 Style); 11459 } 11460 11461 TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) { 11462 // Combined tests of EmptyLineAfterAccessModifier and 11463 // EmptyLineBeforeAccessModifier. 11464 FormatStyle Style = getLLVMStyle(); 11465 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11466 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11467 verifyFormat("struct foo {\n" 11468 "private:\n" 11469 "\n" 11470 "protected:\n" 11471 "};\n", 11472 Style); 11473 11474 Style.MaxEmptyLinesToKeep = 10u; 11475 // Both remove all new lines. 11476 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11477 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11478 verifyFormat("struct foo {\n" 11479 "private:\n" 11480 "protected:\n" 11481 "};\n", 11482 "struct foo {\n" 11483 "private:\n" 11484 "\n\n\n" 11485 "protected:\n" 11486 "};\n", 11487 Style); 11488 11489 // Leave tests rely on the code layout, test::messUp can not be used. 11490 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11491 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11492 Style.MaxEmptyLinesToKeep = 10u; 11493 EXPECT_EQ("struct foo {\n" 11494 "private:\n" 11495 "\n\n\n" 11496 "protected:\n" 11497 "};\n", 11498 format("struct foo {\n" 11499 "private:\n" 11500 "\n\n\n" 11501 "protected:\n" 11502 "};\n", 11503 Style)); 11504 Style.MaxEmptyLinesToKeep = 3u; 11505 EXPECT_EQ("struct foo {\n" 11506 "private:\n" 11507 "\n\n\n" 11508 "protected:\n" 11509 "};\n", 11510 format("struct foo {\n" 11511 "private:\n" 11512 "\n\n\n" 11513 "protected:\n" 11514 "};\n", 11515 Style)); 11516 Style.MaxEmptyLinesToKeep = 1u; 11517 EXPECT_EQ("struct foo {\n" 11518 "private:\n" 11519 "\n\n\n" 11520 "protected:\n" 11521 "};\n", 11522 format("struct foo {\n" 11523 "private:\n" 11524 "\n\n\n" 11525 "protected:\n" 11526 "};\n", 11527 Style)); // Based on new lines in original document and not 11528 // on the setting. 11529 11530 Style.MaxEmptyLinesToKeep = 10u; 11531 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11532 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11533 // Newlines are kept if they are greater than zero, 11534 // test::messUp removes all new lines which changes the logic 11535 EXPECT_EQ("struct foo {\n" 11536 "private:\n" 11537 "\n\n\n" 11538 "protected:\n" 11539 "};\n", 11540 format("struct foo {\n" 11541 "private:\n" 11542 "\n\n\n" 11543 "protected:\n" 11544 "};\n", 11545 Style)); 11546 11547 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11548 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11549 // test::messUp removes all new lines which changes the logic 11550 EXPECT_EQ("struct foo {\n" 11551 "private:\n" 11552 "\n\n\n" 11553 "protected:\n" 11554 "};\n", 11555 format("struct foo {\n" 11556 "private:\n" 11557 "\n\n\n" 11558 "protected:\n" 11559 "};\n", 11560 Style)); 11561 11562 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11563 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11564 EXPECT_EQ("struct foo {\n" 11565 "private:\n" 11566 "\n\n\n" 11567 "protected:\n" 11568 "};\n", 11569 format("struct foo {\n" 11570 "private:\n" 11571 "\n\n\n" 11572 "protected:\n" 11573 "};\n", 11574 Style)); // test::messUp removes all new lines which changes 11575 // the logic. 11576 11577 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11578 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11579 verifyFormat("struct foo {\n" 11580 "private:\n" 11581 "protected:\n" 11582 "};\n", 11583 "struct foo {\n" 11584 "private:\n" 11585 "\n\n\n" 11586 "protected:\n" 11587 "};\n", 11588 Style); 11589 11590 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11591 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11592 EXPECT_EQ("struct foo {\n" 11593 "private:\n" 11594 "\n\n\n" 11595 "protected:\n" 11596 "};\n", 11597 format("struct foo {\n" 11598 "private:\n" 11599 "\n\n\n" 11600 "protected:\n" 11601 "};\n", 11602 Style)); // test::messUp removes all new lines which changes 11603 // the logic. 11604 11605 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11606 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11607 verifyFormat("struct foo {\n" 11608 "private:\n" 11609 "protected:\n" 11610 "};\n", 11611 "struct foo {\n" 11612 "private:\n" 11613 "\n\n\n" 11614 "protected:\n" 11615 "};\n", 11616 Style); 11617 11618 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11619 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11620 verifyFormat("struct foo {\n" 11621 "private:\n" 11622 "protected:\n" 11623 "};\n", 11624 "struct foo {\n" 11625 "private:\n" 11626 "\n\n\n" 11627 "protected:\n" 11628 "};\n", 11629 Style); 11630 11631 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11632 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11633 verifyFormat("struct foo {\n" 11634 "private:\n" 11635 "protected:\n" 11636 "};\n", 11637 "struct foo {\n" 11638 "private:\n" 11639 "\n\n\n" 11640 "protected:\n" 11641 "};\n", 11642 Style); 11643 11644 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11645 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11646 verifyFormat("struct foo {\n" 11647 "private:\n" 11648 "protected:\n" 11649 "};\n", 11650 "struct foo {\n" 11651 "private:\n" 11652 "\n\n\n" 11653 "protected:\n" 11654 "};\n", 11655 Style); 11656 } 11657 11658 TEST_F(FormatTest, FormatsArrays) { 11659 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n" 11660 " [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;"); 11661 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n" 11662 " [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;"); 11663 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n" 11664 " aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}"); 11665 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11666 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;"); 11667 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11668 " [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;"); 11669 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11670 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n" 11671 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;"); 11672 verifyFormat( 11673 "llvm::outs() << \"aaaaaaaaaaaa: \"\n" 11674 " << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n" 11675 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];"); 11676 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n" 11677 " .aaaaaaaaaaaaaaaaaaaaaa();"); 11678 11679 verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n" 11680 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];"); 11681 verifyFormat( 11682 "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n" 11683 " .aaaaaaa[0]\n" 11684 " .aaaaaaaaaaaaaaaaaaaaaa();"); 11685 verifyFormat("a[::b::c];"); 11686 11687 verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10)); 11688 11689 FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0); 11690 verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit); 11691 } 11692 11693 TEST_F(FormatTest, LineStartsWithSpecialCharacter) { 11694 verifyFormat("(a)->b();"); 11695 verifyFormat("--a;"); 11696 } 11697 11698 TEST_F(FormatTest, HandlesIncludeDirectives) { 11699 verifyFormat("#include <string>\n" 11700 "#include <a/b/c.h>\n" 11701 "#include \"a/b/string\"\n" 11702 "#include \"string.h\"\n" 11703 "#include \"string.h\"\n" 11704 "#include <a-a>\n" 11705 "#include < path with space >\n" 11706 "#include_next <test.h>" 11707 "#include \"abc.h\" // this is included for ABC\n" 11708 "#include \"some long include\" // with a comment\n" 11709 "#include \"some very long include path\"\n" 11710 "#include <some/very/long/include/path>\n", 11711 getLLVMStyleWithColumns(35)); 11712 EXPECT_EQ("#include \"a.h\"", format("#include \"a.h\"")); 11713 EXPECT_EQ("#include <a>", format("#include<a>")); 11714 11715 verifyFormat("#import <string>"); 11716 verifyFormat("#import <a/b/c.h>"); 11717 verifyFormat("#import \"a/b/string\""); 11718 verifyFormat("#import \"string.h\""); 11719 verifyFormat("#import \"string.h\""); 11720 verifyFormat("#if __has_include(<strstream>)\n" 11721 "#include <strstream>\n" 11722 "#endif"); 11723 11724 verifyFormat("#define MY_IMPORT <a/b>"); 11725 11726 verifyFormat("#if __has_include(<a/b>)"); 11727 verifyFormat("#if __has_include_next(<a/b>)"); 11728 verifyFormat("#define F __has_include(<a/b>)"); 11729 verifyFormat("#define F __has_include_next(<a/b>)"); 11730 11731 // Protocol buffer definition or missing "#". 11732 verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";", 11733 getLLVMStyleWithColumns(30)); 11734 11735 FormatStyle Style = getLLVMStyle(); 11736 Style.AlwaysBreakBeforeMultilineStrings = true; 11737 Style.ColumnLimit = 0; 11738 verifyFormat("#import \"abc.h\"", Style); 11739 11740 // But 'import' might also be a regular C++ namespace. 11741 verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 11742 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 11743 } 11744 11745 //===----------------------------------------------------------------------===// 11746 // Error recovery tests. 11747 //===----------------------------------------------------------------------===// 11748 11749 TEST_F(FormatTest, IncompleteParameterLists) { 11750 FormatStyle NoBinPacking = getLLVMStyle(); 11751 NoBinPacking.BinPackParameters = false; 11752 verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n" 11753 " double *min_x,\n" 11754 " double *max_x,\n" 11755 " double *min_y,\n" 11756 " double *max_y,\n" 11757 " double *min_z,\n" 11758 " double *max_z, ) {}", 11759 NoBinPacking); 11760 } 11761 11762 TEST_F(FormatTest, IncorrectCodeTrailingStuff) { 11763 verifyFormat("void f() { return; }\n42"); 11764 verifyFormat("void f() {\n" 11765 " if (0)\n" 11766 " return;\n" 11767 "}\n" 11768 "42"); 11769 verifyFormat("void f() { return }\n42"); 11770 verifyFormat("void f() {\n" 11771 " if (0)\n" 11772 " return\n" 11773 "}\n" 11774 "42"); 11775 } 11776 11777 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) { 11778 EXPECT_EQ("void f() { return }", format("void f ( ) { return }")); 11779 EXPECT_EQ("void f() {\n" 11780 " if (a)\n" 11781 " return\n" 11782 "}", 11783 format("void f ( ) { if ( a ) return }")); 11784 EXPECT_EQ("namespace N {\n" 11785 "void f()\n" 11786 "}", 11787 format("namespace N { void f() }")); 11788 EXPECT_EQ("namespace N {\n" 11789 "void f() {}\n" 11790 "void g()\n" 11791 "} // namespace N", 11792 format("namespace N { void f( ) { } void g( ) }")); 11793 } 11794 11795 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) { 11796 verifyFormat("int aaaaaaaa =\n" 11797 " // Overlylongcomment\n" 11798 " b;", 11799 getLLVMStyleWithColumns(20)); 11800 verifyFormat("function(\n" 11801 " ShortArgument,\n" 11802 " LoooooooooooongArgument);\n", 11803 getLLVMStyleWithColumns(20)); 11804 } 11805 11806 TEST_F(FormatTest, IncorrectAccessSpecifier) { 11807 verifyFormat("public:"); 11808 verifyFormat("class A {\n" 11809 "public\n" 11810 " void f() {}\n" 11811 "};"); 11812 verifyFormat("public\n" 11813 "int qwerty;"); 11814 verifyFormat("public\n" 11815 "B {}"); 11816 verifyFormat("public\n" 11817 "{}"); 11818 verifyFormat("public\n" 11819 "B { int x; }"); 11820 } 11821 11822 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) { 11823 verifyFormat("{"); 11824 verifyFormat("#})"); 11825 verifyNoCrash("(/**/[:!] ?[)."); 11826 } 11827 11828 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) { 11829 // Found by oss-fuzz: 11830 // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212 11831 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp); 11832 Style.ColumnLimit = 60; 11833 verifyNoCrash( 11834 "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20" 11835 "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20" 11836 "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a", 11837 Style); 11838 } 11839 11840 TEST_F(FormatTest, IncorrectCodeDoNoWhile) { 11841 verifyFormat("do {\n}"); 11842 verifyFormat("do {\n}\n" 11843 "f();"); 11844 verifyFormat("do {\n}\n" 11845 "wheeee(fun);"); 11846 verifyFormat("do {\n" 11847 " f();\n" 11848 "}"); 11849 } 11850 11851 TEST_F(FormatTest, IncorrectCodeMissingParens) { 11852 verifyFormat("if {\n foo;\n foo();\n}"); 11853 verifyFormat("switch {\n foo;\n foo();\n}"); 11854 verifyIncompleteFormat("for {\n foo;\n foo();\n}"); 11855 verifyFormat("while {\n foo;\n foo();\n}"); 11856 verifyFormat("do {\n foo;\n foo();\n} while;"); 11857 } 11858 11859 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) { 11860 verifyIncompleteFormat("namespace {\n" 11861 "class Foo { Foo (\n" 11862 "};\n" 11863 "} // namespace"); 11864 } 11865 11866 TEST_F(FormatTest, IncorrectCodeErrorDetection) { 11867 EXPECT_EQ("{\n {}\n", format("{\n{\n}\n")); 11868 EXPECT_EQ("{\n {}\n", format("{\n {\n}\n")); 11869 EXPECT_EQ("{\n {}\n", format("{\n {\n }\n")); 11870 EXPECT_EQ("{\n {}\n}\n}\n", format("{\n {\n }\n }\n}\n")); 11871 11872 EXPECT_EQ("{\n" 11873 " {\n" 11874 " breakme(\n" 11875 " qwe);\n" 11876 " }\n", 11877 format("{\n" 11878 " {\n" 11879 " breakme(qwe);\n" 11880 "}\n", 11881 getLLVMStyleWithColumns(10))); 11882 } 11883 11884 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) { 11885 verifyFormat("int x = {\n" 11886 " avariable,\n" 11887 " b(alongervariable)};", 11888 getLLVMStyleWithColumns(25)); 11889 } 11890 11891 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) { 11892 verifyFormat("return (a)(b){1, 2, 3};"); 11893 } 11894 11895 TEST_F(FormatTest, LayoutCxx11BraceInitializers) { 11896 verifyFormat("vector<int> x{1, 2, 3, 4};"); 11897 verifyFormat("vector<int> x{\n" 11898 " 1,\n" 11899 " 2,\n" 11900 " 3,\n" 11901 " 4,\n" 11902 "};"); 11903 verifyFormat("vector<T> x{{}, {}, {}, {}};"); 11904 verifyFormat("f({1, 2});"); 11905 verifyFormat("auto v = Foo{-1};"); 11906 verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});"); 11907 verifyFormat("Class::Class : member{1, 2, 3} {}"); 11908 verifyFormat("new vector<int>{1, 2, 3};"); 11909 verifyFormat("new int[3]{1, 2, 3};"); 11910 verifyFormat("new int{1};"); 11911 verifyFormat("return {arg1, arg2};"); 11912 verifyFormat("return {arg1, SomeType{parameter}};"); 11913 verifyFormat("int count = set<int>{f(), g(), h()}.size();"); 11914 verifyFormat("new T{arg1, arg2};"); 11915 verifyFormat("f(MyMap[{composite, key}]);"); 11916 verifyFormat("class Class {\n" 11917 " T member = {arg1, arg2};\n" 11918 "};"); 11919 verifyFormat("vector<int> foo = {::SomeGlobalFunction()};"); 11920 verifyFormat("const struct A a = {.a = 1, .b = 2};"); 11921 verifyFormat("const struct A a = {[0] = 1, [1] = 2};"); 11922 verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");"); 11923 verifyFormat("int a = std::is_integral<int>{} + 0;"); 11924 11925 verifyFormat("int foo(int i) { return fo1{}(i); }"); 11926 verifyFormat("int foo(int i) { return fo1{}(i); }"); 11927 verifyFormat("auto i = decltype(x){};"); 11928 verifyFormat("auto i = typeof(x){};"); 11929 verifyFormat("auto i = _Atomic(x){};"); 11930 verifyFormat("std::vector<int> v = {1, 0 /* comment */};"); 11931 verifyFormat("Node n{1, Node{1000}, //\n" 11932 " 2};"); 11933 verifyFormat("Aaaa aaaaaaa{\n" 11934 " {\n" 11935 " aaaa,\n" 11936 " },\n" 11937 "};"); 11938 verifyFormat("class C : public D {\n" 11939 " SomeClass SC{2};\n" 11940 "};"); 11941 verifyFormat("class C : public A {\n" 11942 " class D : public B {\n" 11943 " void f() { int i{2}; }\n" 11944 " };\n" 11945 "};"); 11946 verifyFormat("#define A {a, a},"); 11947 // Don't confuse braced list initializers with compound statements. 11948 verifyFormat( 11949 "class A {\n" 11950 " A() : a{} {}\n" 11951 " A(int b) : b(b) {}\n" 11952 " A(int a, int b) : a(a), bs{{bs...}} { f(); }\n" 11953 " int a, b;\n" 11954 " explicit Expr(const Scalar<Result> &x) : u{Constant<Result>{x}} {}\n" 11955 " explicit Expr(Scalar<Result> &&x) : u{Constant<Result>{std::move(x)}} " 11956 "{}\n" 11957 "};"); 11958 11959 // Avoid breaking between equal sign and opening brace 11960 FormatStyle AvoidBreakingFirstArgument = getLLVMStyle(); 11961 AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200; 11962 verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n" 11963 " {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n" 11964 " {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n" 11965 " {\"ccccccccccccccccccccc\", 2}};", 11966 AvoidBreakingFirstArgument); 11967 11968 // Binpacking only if there is no trailing comma 11969 verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n" 11970 " cccccccccc, dddddddddd};", 11971 getLLVMStyleWithColumns(50)); 11972 verifyFormat("const Aaaaaa aaaaa = {\n" 11973 " aaaaaaaaaaa,\n" 11974 " bbbbbbbbbbb,\n" 11975 " ccccccccccc,\n" 11976 " ddddddddddd,\n" 11977 "};", 11978 getLLVMStyleWithColumns(50)); 11979 11980 // Cases where distinguising braced lists and blocks is hard. 11981 verifyFormat("vector<int> v{12} GUARDED_BY(mutex);"); 11982 verifyFormat("void f() {\n" 11983 " return; // comment\n" 11984 "}\n" 11985 "SomeType t;"); 11986 verifyFormat("void f() {\n" 11987 " if (a) {\n" 11988 " f();\n" 11989 " }\n" 11990 "}\n" 11991 "SomeType t;"); 11992 11993 // In combination with BinPackArguments = false. 11994 FormatStyle NoBinPacking = getLLVMStyle(); 11995 NoBinPacking.BinPackArguments = false; 11996 verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n" 11997 " bbbbb,\n" 11998 " ccccc,\n" 11999 " ddddd,\n" 12000 " eeeee,\n" 12001 " ffffff,\n" 12002 " ggggg,\n" 12003 " hhhhhh,\n" 12004 " iiiiii,\n" 12005 " jjjjjj,\n" 12006 " kkkkkk};", 12007 NoBinPacking); 12008 verifyFormat("const Aaaaaa aaaaa = {\n" 12009 " aaaaa,\n" 12010 " bbbbb,\n" 12011 " ccccc,\n" 12012 " ddddd,\n" 12013 " eeeee,\n" 12014 " ffffff,\n" 12015 " ggggg,\n" 12016 " hhhhhh,\n" 12017 " iiiiii,\n" 12018 " jjjjjj,\n" 12019 " kkkkkk,\n" 12020 "};", 12021 NoBinPacking); 12022 verifyFormat( 12023 "const Aaaaaa aaaaa = {\n" 12024 " aaaaa, bbbbb, ccccc, ddddd, eeeee, ffffff, ggggg, hhhhhh,\n" 12025 " iiiiii, jjjjjj, kkkkkk, aaaaa, bbbbb, ccccc, ddddd, eeeee,\n" 12026 " ffffff, ggggg, hhhhhh, iiiiii, jjjjjj, kkkkkk,\n" 12027 "};", 12028 NoBinPacking); 12029 12030 NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 12031 EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n" 12032 " CDDDP83848_BMCR_REGISTER,\n" 12033 " CDDDP83848_BMSR_REGISTER,\n" 12034 " CDDDP83848_RBR_REGISTER};", 12035 format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n" 12036 " CDDDP83848_BMSR_REGISTER,\n" 12037 " CDDDP83848_RBR_REGISTER};", 12038 NoBinPacking)); 12039 12040 // FIXME: The alignment of these trailing comments might be bad. Then again, 12041 // this might be utterly useless in real code. 12042 verifyFormat("Constructor::Constructor()\n" 12043 " : some_value{ //\n" 12044 " aaaaaaa, //\n" 12045 " bbbbbbb} {}"); 12046 12047 // In braced lists, the first comment is always assumed to belong to the 12048 // first element. Thus, it can be moved to the next or previous line as 12049 // appropriate. 12050 EXPECT_EQ("function({// First element:\n" 12051 " 1,\n" 12052 " // Second element:\n" 12053 " 2});", 12054 format("function({\n" 12055 " // First element:\n" 12056 " 1,\n" 12057 " // Second element:\n" 12058 " 2});")); 12059 EXPECT_EQ("std::vector<int> MyNumbers{\n" 12060 " // First element:\n" 12061 " 1,\n" 12062 " // Second element:\n" 12063 " 2};", 12064 format("std::vector<int> MyNumbers{// First element:\n" 12065 " 1,\n" 12066 " // Second element:\n" 12067 " 2};", 12068 getLLVMStyleWithColumns(30))); 12069 // A trailing comma should still lead to an enforced line break and no 12070 // binpacking. 12071 EXPECT_EQ("vector<int> SomeVector = {\n" 12072 " // aaa\n" 12073 " 1,\n" 12074 " 2,\n" 12075 "};", 12076 format("vector<int> SomeVector = { // aaa\n" 12077 " 1, 2, };")); 12078 12079 // C++11 brace initializer list l-braces should not be treated any differently 12080 // when breaking before lambda bodies is enabled 12081 FormatStyle BreakBeforeLambdaBody = getLLVMStyle(); 12082 BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 12083 BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 12084 BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true; 12085 verifyFormat( 12086 "std::runtime_error{\n" 12087 " \"Long string which will force a break onto the next line...\"};", 12088 BreakBeforeLambdaBody); 12089 12090 FormatStyle ExtraSpaces = getLLVMStyle(); 12091 ExtraSpaces.Cpp11BracedListStyle = false; 12092 ExtraSpaces.ColumnLimit = 75; 12093 verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces); 12094 verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces); 12095 verifyFormat("f({ 1, 2 });", ExtraSpaces); 12096 verifyFormat("auto v = Foo{ 1 };", ExtraSpaces); 12097 verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces); 12098 verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces); 12099 verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces); 12100 verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces); 12101 verifyFormat("return { arg1, arg2 };", ExtraSpaces); 12102 verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces); 12103 verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces); 12104 verifyFormat("new T{ arg1, arg2 };", ExtraSpaces); 12105 verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces); 12106 verifyFormat("class Class {\n" 12107 " T member = { arg1, arg2 };\n" 12108 "};", 12109 ExtraSpaces); 12110 verifyFormat( 12111 "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12112 " aaaaaaaaaaaaaaaaaaaa, aaaaa }\n" 12113 " : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 12114 " bbbbbbbbbbbbbbbbbbbb, bbbbb };", 12115 ExtraSpaces); 12116 verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces); 12117 verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });", 12118 ExtraSpaces); 12119 verifyFormat( 12120 "someFunction(OtherParam,\n" 12121 " BracedList{ // comment 1 (Forcing interesting break)\n" 12122 " param1, param2,\n" 12123 " // comment 2\n" 12124 " param3, param4 });", 12125 ExtraSpaces); 12126 verifyFormat( 12127 "std::this_thread::sleep_for(\n" 12128 " std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);", 12129 ExtraSpaces); 12130 verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n" 12131 " aaaaaaa,\n" 12132 " aaaaaaaaaa,\n" 12133 " aaaaa,\n" 12134 " aaaaaaaaaaaaaaa,\n" 12135 " aaa,\n" 12136 " aaaaaaaaaa,\n" 12137 " a,\n" 12138 " aaaaaaaaaaaaaaaaaaaaa,\n" 12139 " aaaaaaaaaaaa,\n" 12140 " aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n" 12141 " aaaaaaa,\n" 12142 " a};"); 12143 verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces); 12144 verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces); 12145 verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces); 12146 12147 // Avoid breaking between initializer/equal sign and opening brace 12148 ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200; 12149 verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n" 12150 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n" 12151 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n" 12152 " { \"ccccccccccccccccccccc\", 2 }\n" 12153 "};", 12154 ExtraSpaces); 12155 verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n" 12156 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n" 12157 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n" 12158 " { \"ccccccccccccccccccccc\", 2 }\n" 12159 "};", 12160 ExtraSpaces); 12161 12162 FormatStyle SpaceBeforeBrace = getLLVMStyle(); 12163 SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true; 12164 verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace); 12165 verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace); 12166 12167 FormatStyle SpaceBetweenBraces = getLLVMStyle(); 12168 SpaceBetweenBraces.SpacesInAngles = FormatStyle::SIAS_Always; 12169 SpaceBetweenBraces.SpacesInParentheses = true; 12170 SpaceBetweenBraces.SpacesInSquareBrackets = true; 12171 verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces); 12172 verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces); 12173 verifyFormat("vector< int > x{ // comment 1\n" 12174 " 1, 2, 3, 4 };", 12175 SpaceBetweenBraces); 12176 SpaceBetweenBraces.ColumnLimit = 20; 12177 EXPECT_EQ("vector< int > x{\n" 12178 " 1, 2, 3, 4 };", 12179 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces)); 12180 SpaceBetweenBraces.ColumnLimit = 24; 12181 EXPECT_EQ("vector< int > x{ 1, 2,\n" 12182 " 3, 4 };", 12183 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces)); 12184 EXPECT_EQ("vector< int > x{\n" 12185 " 1,\n" 12186 " 2,\n" 12187 " 3,\n" 12188 " 4,\n" 12189 "};", 12190 format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces)); 12191 verifyFormat("vector< int > x{};", SpaceBetweenBraces); 12192 SpaceBetweenBraces.SpaceInEmptyParentheses = true; 12193 verifyFormat("vector< int > x{ };", SpaceBetweenBraces); 12194 } 12195 12196 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) { 12197 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12198 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12199 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12200 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12201 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12202 " 1, 22, 333, 4444, 55555, 666666, 7777777};"); 12203 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n" 12204 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12205 " 1, 22, 333, 4444, 55555, //\n" 12206 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12207 " 1, 22, 333, 4444, 55555, 666666, 7777777};"); 12208 verifyFormat( 12209 "vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12210 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12211 " 1, 22, 333, 4444, 55555, 666666, // comment\n" 12212 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12213 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12214 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12215 " 7777777};"); 12216 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12217 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12218 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12219 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12220 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12221 " // Separating comment.\n" 12222 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12223 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12224 " // Leading comment\n" 12225 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12226 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12227 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12228 " 1, 1, 1, 1};", 12229 getLLVMStyleWithColumns(39)); 12230 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12231 " 1, 1, 1, 1};", 12232 getLLVMStyleWithColumns(38)); 12233 verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n" 12234 " 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};", 12235 getLLVMStyleWithColumns(43)); 12236 verifyFormat( 12237 "static unsigned SomeValues[10][3] = {\n" 12238 " {1, 4, 0}, {4, 9, 0}, {4, 5, 9}, {8, 5, 4}, {1, 8, 4},\n" 12239 " {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};"); 12240 verifyFormat("static auto fields = new vector<string>{\n" 12241 " \"aaaaaaaaaaaaa\",\n" 12242 " \"aaaaaaaaaaaaa\",\n" 12243 " \"aaaaaaaaaaaa\",\n" 12244 " \"aaaaaaaaaaaaaa\",\n" 12245 " \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n" 12246 " \"aaaaaaaaaaaa\",\n" 12247 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n" 12248 "};"); 12249 verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};"); 12250 verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n" 12251 " 2, bbbbbbbbbbbbbbbbbbbbbb,\n" 12252 " 3, cccccccccccccccccccccc};", 12253 getLLVMStyleWithColumns(60)); 12254 12255 // Trailing commas. 12256 verifyFormat("vector<int> x = {\n" 12257 " 1, 1, 1, 1, 1, 1, 1, 1,\n" 12258 "};", 12259 getLLVMStyleWithColumns(39)); 12260 verifyFormat("vector<int> x = {\n" 12261 " 1, 1, 1, 1, 1, 1, 1, 1, //\n" 12262 "};", 12263 getLLVMStyleWithColumns(39)); 12264 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12265 " 1, 1, 1, 1,\n" 12266 " /**/ /**/};", 12267 getLLVMStyleWithColumns(39)); 12268 12269 // Trailing comment in the first line. 12270 verifyFormat("vector<int> iiiiiiiiiiiiiii = { //\n" 12271 " 1111111111, 2222222222, 33333333333, 4444444444, //\n" 12272 " 111111111, 222222222, 3333333333, 444444444, //\n" 12273 " 11111111, 22222222, 333333333, 44444444};"); 12274 // Trailing comment in the last line. 12275 verifyFormat("int aaaaa[] = {\n" 12276 " 1, 2, 3, // comment\n" 12277 " 4, 5, 6 // comment\n" 12278 "};"); 12279 12280 // With nested lists, we should either format one item per line or all nested 12281 // lists one on line. 12282 // FIXME: For some nested lists, we can do better. 12283 verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n" 12284 " {aaaaaaaaaaaaaaaaaaa},\n" 12285 " {aaaaaaaaaaaaaaaaaaaaa},\n" 12286 " {aaaaaaaaaaaaaaaaa}};", 12287 getLLVMStyleWithColumns(60)); 12288 verifyFormat( 12289 "SomeStruct my_struct_array = {\n" 12290 " {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n" 12291 " aaaaaaaaaaaaa, aaaaaaa, aaa},\n" 12292 " {aaa, aaa},\n" 12293 " {aaa, aaa},\n" 12294 " {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n" 12295 " {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n" 12296 " aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};"); 12297 12298 // No column layout should be used here. 12299 verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n" 12300 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};"); 12301 12302 verifyNoCrash("a<,"); 12303 12304 // No braced initializer here. 12305 verifyFormat("void f() {\n" 12306 " struct Dummy {};\n" 12307 " f(v);\n" 12308 "}"); 12309 12310 // Long lists should be formatted in columns even if they are nested. 12311 verifyFormat( 12312 "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12313 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12314 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12315 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12316 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12317 " 1, 22, 333, 4444, 55555, 666666, 7777777});"); 12318 12319 // Allow "single-column" layout even if that violates the column limit. There 12320 // isn't going to be a better way. 12321 verifyFormat("std::vector<int> a = {\n" 12322 " aaaaaaaa,\n" 12323 " aaaaaaaa,\n" 12324 " aaaaaaaa,\n" 12325 " aaaaaaaa,\n" 12326 " aaaaaaaaaa,\n" 12327 " aaaaaaaa,\n" 12328 " aaaaaaaaaaaaaaaaaaaaaaaaaaa};", 12329 getLLVMStyleWithColumns(30)); 12330 verifyFormat("vector<int> aaaa = {\n" 12331 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12332 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12333 " aaaaaa.aaaaaaa,\n" 12334 " aaaaaa.aaaaaaa,\n" 12335 " aaaaaa.aaaaaaa,\n" 12336 " aaaaaa.aaaaaaa,\n" 12337 "};"); 12338 12339 // Don't create hanging lists. 12340 verifyFormat("someFunction(Param, {List1, List2,\n" 12341 " List3});", 12342 getLLVMStyleWithColumns(35)); 12343 verifyFormat("someFunction(Param, Param,\n" 12344 " {List1, List2,\n" 12345 " List3});", 12346 getLLVMStyleWithColumns(35)); 12347 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n" 12348 " aaaaaaaaaaaaaaaaaaaaaaa);"); 12349 } 12350 12351 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) { 12352 FormatStyle DoNotMerge = getLLVMStyle(); 12353 DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12354 12355 verifyFormat("void f() { return 42; }"); 12356 verifyFormat("void f() {\n" 12357 " return 42;\n" 12358 "}", 12359 DoNotMerge); 12360 verifyFormat("void f() {\n" 12361 " // Comment\n" 12362 "}"); 12363 verifyFormat("{\n" 12364 "#error {\n" 12365 " int a;\n" 12366 "}"); 12367 verifyFormat("{\n" 12368 " int a;\n" 12369 "#error {\n" 12370 "}"); 12371 verifyFormat("void f() {} // comment"); 12372 verifyFormat("void f() { int a; } // comment"); 12373 verifyFormat("void f() {\n" 12374 "} // comment", 12375 DoNotMerge); 12376 verifyFormat("void f() {\n" 12377 " int a;\n" 12378 "} // comment", 12379 DoNotMerge); 12380 verifyFormat("void f() {\n" 12381 "} // comment", 12382 getLLVMStyleWithColumns(15)); 12383 12384 verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23)); 12385 verifyFormat("void f() {\n return 42;\n}", getLLVMStyleWithColumns(22)); 12386 12387 verifyFormat("void f() {}", getLLVMStyleWithColumns(11)); 12388 verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10)); 12389 verifyFormat("class C {\n" 12390 " C()\n" 12391 " : iiiiiiii(nullptr),\n" 12392 " kkkkkkk(nullptr),\n" 12393 " mmmmmmm(nullptr),\n" 12394 " nnnnnnn(nullptr) {}\n" 12395 "};", 12396 getGoogleStyle()); 12397 12398 FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0); 12399 EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit)); 12400 EXPECT_EQ("class C {\n" 12401 " A() : b(0) {}\n" 12402 "};", 12403 format("class C{A():b(0){}};", NoColumnLimit)); 12404 EXPECT_EQ("A()\n" 12405 " : b(0) {\n" 12406 "}", 12407 format("A()\n:b(0)\n{\n}", NoColumnLimit)); 12408 12409 FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit; 12410 DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine = 12411 FormatStyle::SFS_None; 12412 EXPECT_EQ("A()\n" 12413 " : b(0) {\n" 12414 "}", 12415 format("A():b(0){}", DoNotMergeNoColumnLimit)); 12416 EXPECT_EQ("A()\n" 12417 " : b(0) {\n" 12418 "}", 12419 format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit)); 12420 12421 verifyFormat("#define A \\\n" 12422 " void f() { \\\n" 12423 " int i; \\\n" 12424 " }", 12425 getLLVMStyleWithColumns(20)); 12426 verifyFormat("#define A \\\n" 12427 " void f() { int i; }", 12428 getLLVMStyleWithColumns(21)); 12429 verifyFormat("#define A \\\n" 12430 " void f() { \\\n" 12431 " int i; \\\n" 12432 " } \\\n" 12433 " int j;", 12434 getLLVMStyleWithColumns(22)); 12435 verifyFormat("#define A \\\n" 12436 " void f() { int i; } \\\n" 12437 " int j;", 12438 getLLVMStyleWithColumns(23)); 12439 } 12440 12441 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) { 12442 FormatStyle MergeEmptyOnly = getLLVMStyle(); 12443 MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 12444 verifyFormat("class C {\n" 12445 " int f() {}\n" 12446 "};", 12447 MergeEmptyOnly); 12448 verifyFormat("class C {\n" 12449 " int f() {\n" 12450 " return 42;\n" 12451 " }\n" 12452 "};", 12453 MergeEmptyOnly); 12454 verifyFormat("int f() {}", MergeEmptyOnly); 12455 verifyFormat("int f() {\n" 12456 " return 42;\n" 12457 "}", 12458 MergeEmptyOnly); 12459 12460 // Also verify behavior when BraceWrapping.AfterFunction = true 12461 MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12462 MergeEmptyOnly.BraceWrapping.AfterFunction = true; 12463 verifyFormat("int f() {}", MergeEmptyOnly); 12464 verifyFormat("class C {\n" 12465 " int f() {}\n" 12466 "};", 12467 MergeEmptyOnly); 12468 } 12469 12470 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) { 12471 FormatStyle MergeInlineOnly = getLLVMStyle(); 12472 MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 12473 verifyFormat("class C {\n" 12474 " int f() { return 42; }\n" 12475 "};", 12476 MergeInlineOnly); 12477 verifyFormat("int f() {\n" 12478 " return 42;\n" 12479 "}", 12480 MergeInlineOnly); 12481 12482 // SFS_Inline implies SFS_Empty 12483 verifyFormat("class C {\n" 12484 " int f() {}\n" 12485 "};", 12486 MergeInlineOnly); 12487 verifyFormat("int f() {}", MergeInlineOnly); 12488 12489 // Also verify behavior when BraceWrapping.AfterFunction = true 12490 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12491 MergeInlineOnly.BraceWrapping.AfterFunction = true; 12492 verifyFormat("class C {\n" 12493 " int f() { return 42; }\n" 12494 "};", 12495 MergeInlineOnly); 12496 verifyFormat("int f()\n" 12497 "{\n" 12498 " return 42;\n" 12499 "}", 12500 MergeInlineOnly); 12501 12502 // SFS_Inline implies SFS_Empty 12503 verifyFormat("int f() {}", MergeInlineOnly); 12504 verifyFormat("class C {\n" 12505 " int f() {}\n" 12506 "};", 12507 MergeInlineOnly); 12508 12509 MergeInlineOnly.BraceWrapping.AfterClass = true; 12510 MergeInlineOnly.BraceWrapping.AfterStruct = true; 12511 verifyFormat("class C\n" 12512 "{\n" 12513 " int f() { return 42; }\n" 12514 "};", 12515 MergeInlineOnly); 12516 verifyFormat("struct C\n" 12517 "{\n" 12518 " int f() { return 42; }\n" 12519 "};", 12520 MergeInlineOnly); 12521 verifyFormat("int f()\n" 12522 "{\n" 12523 " return 42;\n" 12524 "}", 12525 MergeInlineOnly); 12526 verifyFormat("int f() {}", MergeInlineOnly); 12527 verifyFormat("class C\n" 12528 "{\n" 12529 " int f() { return 42; }\n" 12530 "};", 12531 MergeInlineOnly); 12532 verifyFormat("struct C\n" 12533 "{\n" 12534 " int f() { return 42; }\n" 12535 "};", 12536 MergeInlineOnly); 12537 verifyFormat("struct C\n" 12538 "// comment\n" 12539 "/* comment */\n" 12540 "// comment\n" 12541 "{\n" 12542 " int f() { return 42; }\n" 12543 "};", 12544 MergeInlineOnly); 12545 verifyFormat("/* comment */ struct C\n" 12546 "{\n" 12547 " int f() { return 42; }\n" 12548 "};", 12549 MergeInlineOnly); 12550 } 12551 12552 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) { 12553 FormatStyle MergeInlineOnly = getLLVMStyle(); 12554 MergeInlineOnly.AllowShortFunctionsOnASingleLine = 12555 FormatStyle::SFS_InlineOnly; 12556 verifyFormat("class C {\n" 12557 " int f() { return 42; }\n" 12558 "};", 12559 MergeInlineOnly); 12560 verifyFormat("int f() {\n" 12561 " return 42;\n" 12562 "}", 12563 MergeInlineOnly); 12564 12565 // SFS_InlineOnly does not imply SFS_Empty 12566 verifyFormat("class C {\n" 12567 " int f() {}\n" 12568 "};", 12569 MergeInlineOnly); 12570 verifyFormat("int f() {\n" 12571 "}", 12572 MergeInlineOnly); 12573 12574 // Also verify behavior when BraceWrapping.AfterFunction = true 12575 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12576 MergeInlineOnly.BraceWrapping.AfterFunction = true; 12577 verifyFormat("class C {\n" 12578 " int f() { return 42; }\n" 12579 "};", 12580 MergeInlineOnly); 12581 verifyFormat("int f()\n" 12582 "{\n" 12583 " return 42;\n" 12584 "}", 12585 MergeInlineOnly); 12586 12587 // SFS_InlineOnly does not imply SFS_Empty 12588 verifyFormat("int f()\n" 12589 "{\n" 12590 "}", 12591 MergeInlineOnly); 12592 verifyFormat("class C {\n" 12593 " int f() {}\n" 12594 "};", 12595 MergeInlineOnly); 12596 } 12597 12598 TEST_F(FormatTest, SplitEmptyFunction) { 12599 FormatStyle Style = getLLVMStyleWithColumns(40); 12600 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12601 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12602 Style.BraceWrapping.AfterFunction = true; 12603 Style.BraceWrapping.SplitEmptyFunction = false; 12604 12605 verifyFormat("int f()\n" 12606 "{}", 12607 Style); 12608 verifyFormat("int f()\n" 12609 "{\n" 12610 " return 42;\n" 12611 "}", 12612 Style); 12613 verifyFormat("int f()\n" 12614 "{\n" 12615 " // some comment\n" 12616 "}", 12617 Style); 12618 12619 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 12620 verifyFormat("int f() {}", Style); 12621 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12622 "{}", 12623 Style); 12624 verifyFormat("int f()\n" 12625 "{\n" 12626 " return 0;\n" 12627 "}", 12628 Style); 12629 12630 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 12631 verifyFormat("class Foo {\n" 12632 " int f() {}\n" 12633 "};\n", 12634 Style); 12635 verifyFormat("class Foo {\n" 12636 " int f() { return 0; }\n" 12637 "};\n", 12638 Style); 12639 verifyFormat("class Foo {\n" 12640 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12641 " {}\n" 12642 "};\n", 12643 Style); 12644 verifyFormat("class Foo {\n" 12645 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12646 " {\n" 12647 " return 0;\n" 12648 " }\n" 12649 "};\n", 12650 Style); 12651 12652 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 12653 verifyFormat("int f() {}", Style); 12654 verifyFormat("int f() { return 0; }", Style); 12655 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12656 "{}", 12657 Style); 12658 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12659 "{\n" 12660 " return 0;\n" 12661 "}", 12662 Style); 12663 } 12664 12665 TEST_F(FormatTest, SplitEmptyFunctionButNotRecord) { 12666 FormatStyle Style = getLLVMStyleWithColumns(40); 12667 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12668 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12669 Style.BraceWrapping.AfterFunction = true; 12670 Style.BraceWrapping.SplitEmptyFunction = true; 12671 Style.BraceWrapping.SplitEmptyRecord = false; 12672 12673 verifyFormat("class C {};", Style); 12674 verifyFormat("struct C {};", Style); 12675 verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12676 " int bbbbbbbbbbbbbbbbbbbbbbbb)\n" 12677 "{\n" 12678 "}", 12679 Style); 12680 verifyFormat("class C {\n" 12681 " C()\n" 12682 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa(),\n" 12683 " bbbbbbbbbbbbbbbbbbb()\n" 12684 " {\n" 12685 " }\n" 12686 " void\n" 12687 " m(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12688 " int bbbbbbbbbbbbbbbbbbbbbbbb)\n" 12689 " {\n" 12690 " }\n" 12691 "};", 12692 Style); 12693 } 12694 12695 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) { 12696 FormatStyle Style = getLLVMStyle(); 12697 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 12698 verifyFormat("#ifdef A\n" 12699 "int f() {}\n" 12700 "#else\n" 12701 "int g() {}\n" 12702 "#endif", 12703 Style); 12704 } 12705 12706 TEST_F(FormatTest, SplitEmptyClass) { 12707 FormatStyle Style = getLLVMStyle(); 12708 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12709 Style.BraceWrapping.AfterClass = true; 12710 Style.BraceWrapping.SplitEmptyRecord = false; 12711 12712 verifyFormat("class Foo\n" 12713 "{};", 12714 Style); 12715 verifyFormat("/* something */ class Foo\n" 12716 "{};", 12717 Style); 12718 verifyFormat("template <typename X> class Foo\n" 12719 "{};", 12720 Style); 12721 verifyFormat("class Foo\n" 12722 "{\n" 12723 " Foo();\n" 12724 "};", 12725 Style); 12726 verifyFormat("typedef class Foo\n" 12727 "{\n" 12728 "} Foo_t;", 12729 Style); 12730 12731 Style.BraceWrapping.SplitEmptyRecord = true; 12732 Style.BraceWrapping.AfterStruct = true; 12733 verifyFormat("class rep\n" 12734 "{\n" 12735 "};", 12736 Style); 12737 verifyFormat("struct rep\n" 12738 "{\n" 12739 "};", 12740 Style); 12741 verifyFormat("template <typename T> class rep\n" 12742 "{\n" 12743 "};", 12744 Style); 12745 verifyFormat("template <typename T> struct rep\n" 12746 "{\n" 12747 "};", 12748 Style); 12749 verifyFormat("class rep\n" 12750 "{\n" 12751 " int x;\n" 12752 "};", 12753 Style); 12754 verifyFormat("struct rep\n" 12755 "{\n" 12756 " int x;\n" 12757 "};", 12758 Style); 12759 verifyFormat("template <typename T> class rep\n" 12760 "{\n" 12761 " int x;\n" 12762 "};", 12763 Style); 12764 verifyFormat("template <typename T> struct rep\n" 12765 "{\n" 12766 " int x;\n" 12767 "};", 12768 Style); 12769 verifyFormat("template <typename T> class rep // Foo\n" 12770 "{\n" 12771 " int x;\n" 12772 "};", 12773 Style); 12774 verifyFormat("template <typename T> struct rep // Bar\n" 12775 "{\n" 12776 " int x;\n" 12777 "};", 12778 Style); 12779 12780 verifyFormat("template <typename T> class rep<T>\n" 12781 "{\n" 12782 " int x;\n" 12783 "};", 12784 Style); 12785 12786 verifyFormat("template <typename T> class rep<std::complex<T>>\n" 12787 "{\n" 12788 " int x;\n" 12789 "};", 12790 Style); 12791 verifyFormat("template <typename T> class rep<std::complex<T>>\n" 12792 "{\n" 12793 "};", 12794 Style); 12795 12796 verifyFormat("#include \"stdint.h\"\n" 12797 "namespace rep {}", 12798 Style); 12799 verifyFormat("#include <stdint.h>\n" 12800 "namespace rep {}", 12801 Style); 12802 verifyFormat("#include <stdint.h>\n" 12803 "namespace rep {}", 12804 "#include <stdint.h>\n" 12805 "namespace rep {\n" 12806 "\n" 12807 "\n" 12808 "}", 12809 Style); 12810 } 12811 12812 TEST_F(FormatTest, SplitEmptyStruct) { 12813 FormatStyle Style = getLLVMStyle(); 12814 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12815 Style.BraceWrapping.AfterStruct = true; 12816 Style.BraceWrapping.SplitEmptyRecord = false; 12817 12818 verifyFormat("struct Foo\n" 12819 "{};", 12820 Style); 12821 verifyFormat("/* something */ struct Foo\n" 12822 "{};", 12823 Style); 12824 verifyFormat("template <typename X> struct Foo\n" 12825 "{};", 12826 Style); 12827 verifyFormat("struct Foo\n" 12828 "{\n" 12829 " Foo();\n" 12830 "};", 12831 Style); 12832 verifyFormat("typedef struct Foo\n" 12833 "{\n" 12834 "} Foo_t;", 12835 Style); 12836 // typedef struct Bar {} Bar_t; 12837 } 12838 12839 TEST_F(FormatTest, SplitEmptyUnion) { 12840 FormatStyle Style = getLLVMStyle(); 12841 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12842 Style.BraceWrapping.AfterUnion = true; 12843 Style.BraceWrapping.SplitEmptyRecord = false; 12844 12845 verifyFormat("union Foo\n" 12846 "{};", 12847 Style); 12848 verifyFormat("/* something */ union Foo\n" 12849 "{};", 12850 Style); 12851 verifyFormat("union Foo\n" 12852 "{\n" 12853 " A,\n" 12854 "};", 12855 Style); 12856 verifyFormat("typedef union Foo\n" 12857 "{\n" 12858 "} Foo_t;", 12859 Style); 12860 } 12861 12862 TEST_F(FormatTest, SplitEmptyNamespace) { 12863 FormatStyle Style = getLLVMStyle(); 12864 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12865 Style.BraceWrapping.AfterNamespace = true; 12866 Style.BraceWrapping.SplitEmptyNamespace = false; 12867 12868 verifyFormat("namespace Foo\n" 12869 "{};", 12870 Style); 12871 verifyFormat("/* something */ namespace Foo\n" 12872 "{};", 12873 Style); 12874 verifyFormat("inline namespace Foo\n" 12875 "{};", 12876 Style); 12877 verifyFormat("/* something */ inline namespace Foo\n" 12878 "{};", 12879 Style); 12880 verifyFormat("export namespace Foo\n" 12881 "{};", 12882 Style); 12883 verifyFormat("namespace Foo\n" 12884 "{\n" 12885 "void Bar();\n" 12886 "};", 12887 Style); 12888 } 12889 12890 TEST_F(FormatTest, NeverMergeShortRecords) { 12891 FormatStyle Style = getLLVMStyle(); 12892 12893 verifyFormat("class Foo {\n" 12894 " Foo();\n" 12895 "};", 12896 Style); 12897 verifyFormat("typedef class Foo {\n" 12898 " Foo();\n" 12899 "} Foo_t;", 12900 Style); 12901 verifyFormat("struct Foo {\n" 12902 " Foo();\n" 12903 "};", 12904 Style); 12905 verifyFormat("typedef struct Foo {\n" 12906 " Foo();\n" 12907 "} Foo_t;", 12908 Style); 12909 verifyFormat("union Foo {\n" 12910 " A,\n" 12911 "};", 12912 Style); 12913 verifyFormat("typedef union Foo {\n" 12914 " A,\n" 12915 "} Foo_t;", 12916 Style); 12917 verifyFormat("namespace Foo {\n" 12918 "void Bar();\n" 12919 "};", 12920 Style); 12921 12922 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12923 Style.BraceWrapping.AfterClass = true; 12924 Style.BraceWrapping.AfterStruct = true; 12925 Style.BraceWrapping.AfterUnion = true; 12926 Style.BraceWrapping.AfterNamespace = true; 12927 verifyFormat("class Foo\n" 12928 "{\n" 12929 " Foo();\n" 12930 "};", 12931 Style); 12932 verifyFormat("typedef class Foo\n" 12933 "{\n" 12934 " Foo();\n" 12935 "} Foo_t;", 12936 Style); 12937 verifyFormat("struct Foo\n" 12938 "{\n" 12939 " Foo();\n" 12940 "};", 12941 Style); 12942 verifyFormat("typedef struct Foo\n" 12943 "{\n" 12944 " Foo();\n" 12945 "} Foo_t;", 12946 Style); 12947 verifyFormat("union Foo\n" 12948 "{\n" 12949 " A,\n" 12950 "};", 12951 Style); 12952 verifyFormat("typedef union Foo\n" 12953 "{\n" 12954 " A,\n" 12955 "} Foo_t;", 12956 Style); 12957 verifyFormat("namespace Foo\n" 12958 "{\n" 12959 "void Bar();\n" 12960 "};", 12961 Style); 12962 } 12963 12964 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) { 12965 // Elaborate type variable declarations. 12966 verifyFormat("struct foo a = {bar};\nint n;"); 12967 verifyFormat("class foo a = {bar};\nint n;"); 12968 verifyFormat("union foo a = {bar};\nint n;"); 12969 12970 // Elaborate types inside function definitions. 12971 verifyFormat("struct foo f() {}\nint n;"); 12972 verifyFormat("class foo f() {}\nint n;"); 12973 verifyFormat("union foo f() {}\nint n;"); 12974 12975 // Templates. 12976 verifyFormat("template <class X> void f() {}\nint n;"); 12977 verifyFormat("template <struct X> void f() {}\nint n;"); 12978 verifyFormat("template <union X> void f() {}\nint n;"); 12979 12980 // Actual definitions... 12981 verifyFormat("struct {\n} n;"); 12982 verifyFormat( 12983 "template <template <class T, class Y>, class Z> class X {\n} n;"); 12984 verifyFormat("union Z {\n int n;\n} x;"); 12985 verifyFormat("class MACRO Z {\n} n;"); 12986 verifyFormat("class MACRO(X) Z {\n} n;"); 12987 verifyFormat("class __attribute__(X) Z {\n} n;"); 12988 verifyFormat("class __declspec(X) Z {\n} n;"); 12989 verifyFormat("class A##B##C {\n} n;"); 12990 verifyFormat("class alignas(16) Z {\n} n;"); 12991 verifyFormat("class MACRO(X) alignas(16) Z {\n} n;"); 12992 verifyFormat("class MACROA MACRO(X) Z {\n} n;"); 12993 12994 // Redefinition from nested context: 12995 verifyFormat("class A::B::C {\n} n;"); 12996 12997 // Template definitions. 12998 verifyFormat( 12999 "template <typename F>\n" 13000 "Matcher(const Matcher<F> &Other,\n" 13001 " typename enable_if_c<is_base_of<F, T>::value &&\n" 13002 " !is_same<F, T>::value>::type * = 0)\n" 13003 " : Implementation(new ImplicitCastMatcher<F>(Other)) {}"); 13004 13005 // FIXME: This is still incorrectly handled at the formatter side. 13006 verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};"); 13007 verifyFormat("int i = SomeFunction(a<b, a> b);"); 13008 13009 // FIXME: 13010 // This now gets parsed incorrectly as class definition. 13011 // verifyFormat("class A<int> f() {\n}\nint n;"); 13012 13013 // Elaborate types where incorrectly parsing the structural element would 13014 // break the indent. 13015 verifyFormat("if (true)\n" 13016 " class X x;\n" 13017 "else\n" 13018 " f();\n"); 13019 13020 // This is simply incomplete. Formatting is not important, but must not crash. 13021 verifyFormat("class A:"); 13022 } 13023 13024 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) { 13025 EXPECT_EQ("#error Leave all white!!!!! space* alone!\n", 13026 format("#error Leave all white!!!!! space* alone!\n")); 13027 EXPECT_EQ( 13028 "#warning Leave all white!!!!! space* alone!\n", 13029 format("#warning Leave all white!!!!! space* alone!\n")); 13030 EXPECT_EQ("#error 1", format(" # error 1")); 13031 EXPECT_EQ("#warning 1", format(" # warning 1")); 13032 } 13033 13034 TEST_F(FormatTest, FormatHashIfExpressions) { 13035 verifyFormat("#if AAAA && BBBB"); 13036 verifyFormat("#if (AAAA && BBBB)"); 13037 verifyFormat("#elif (AAAA && BBBB)"); 13038 // FIXME: Come up with a better indentation for #elif. 13039 verifyFormat( 13040 "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) && \\\n" 13041 " defined(BBBBBBBB)\n" 13042 "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) && \\\n" 13043 " defined(BBBBBBBB)\n" 13044 "#endif", 13045 getLLVMStyleWithColumns(65)); 13046 } 13047 13048 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) { 13049 FormatStyle AllowsMergedIf = getGoogleStyle(); 13050 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 13051 FormatStyle::SIS_WithoutElse; 13052 verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf); 13053 verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf); 13054 verifyFormat("if (true)\n#error E\n return 42;", AllowsMergedIf); 13055 EXPECT_EQ("if (true) return 42;", 13056 format("if (true)\nreturn 42;", AllowsMergedIf)); 13057 FormatStyle ShortMergedIf = AllowsMergedIf; 13058 ShortMergedIf.ColumnLimit = 25; 13059 verifyFormat("#define A \\\n" 13060 " if (true) return 42;", 13061 ShortMergedIf); 13062 verifyFormat("#define A \\\n" 13063 " f(); \\\n" 13064 " if (true)\n" 13065 "#define B", 13066 ShortMergedIf); 13067 verifyFormat("#define A \\\n" 13068 " f(); \\\n" 13069 " if (true)\n" 13070 "g();", 13071 ShortMergedIf); 13072 verifyFormat("{\n" 13073 "#ifdef A\n" 13074 " // Comment\n" 13075 " if (true) continue;\n" 13076 "#endif\n" 13077 " // Comment\n" 13078 " if (true) continue;\n" 13079 "}", 13080 ShortMergedIf); 13081 ShortMergedIf.ColumnLimit = 33; 13082 verifyFormat("#define A \\\n" 13083 " if constexpr (true) return 42;", 13084 ShortMergedIf); 13085 verifyFormat("#define A \\\n" 13086 " if CONSTEXPR (true) return 42;", 13087 ShortMergedIf); 13088 ShortMergedIf.ColumnLimit = 29; 13089 verifyFormat("#define A \\\n" 13090 " if (aaaaaaaaaa) return 1; \\\n" 13091 " return 2;", 13092 ShortMergedIf); 13093 ShortMergedIf.ColumnLimit = 28; 13094 verifyFormat("#define A \\\n" 13095 " if (aaaaaaaaaa) \\\n" 13096 " return 1; \\\n" 13097 " return 2;", 13098 ShortMergedIf); 13099 verifyFormat("#define A \\\n" 13100 " if constexpr (aaaaaaa) \\\n" 13101 " return 1; \\\n" 13102 " return 2;", 13103 ShortMergedIf); 13104 verifyFormat("#define A \\\n" 13105 " if CONSTEXPR (aaaaaaa) \\\n" 13106 " return 1; \\\n" 13107 " return 2;", 13108 ShortMergedIf); 13109 } 13110 13111 TEST_F(FormatTest, FormatStarDependingOnContext) { 13112 verifyFormat("void f(int *a);"); 13113 verifyFormat("void f() { f(fint * b); }"); 13114 verifyFormat("class A {\n void f(int *a);\n};"); 13115 verifyFormat("class A {\n int *a;\n};"); 13116 verifyFormat("namespace a {\n" 13117 "namespace b {\n" 13118 "class A {\n" 13119 " void f() {}\n" 13120 " int *a;\n" 13121 "};\n" 13122 "} // namespace b\n" 13123 "} // namespace a"); 13124 } 13125 13126 TEST_F(FormatTest, SpecialTokensAtEndOfLine) { 13127 verifyFormat("while"); 13128 verifyFormat("operator"); 13129 } 13130 13131 TEST_F(FormatTest, SkipsDeeplyNestedLines) { 13132 // This code would be painfully slow to format if we didn't skip it. 13133 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 13134 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13135 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13136 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13137 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13138 "A(1, 1)\n" 13139 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x 13140 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13141 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13142 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13143 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13144 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13145 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13146 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13147 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13148 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n"); 13149 // Deeply nested part is untouched, rest is formatted. 13150 EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n", 13151 format(std::string("int i;\n") + Code + "int j;\n", 13152 getLLVMStyle(), SC_ExpectIncomplete)); 13153 } 13154 13155 //===----------------------------------------------------------------------===// 13156 // Objective-C tests. 13157 //===----------------------------------------------------------------------===// 13158 13159 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) { 13160 verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;"); 13161 EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;", 13162 format("-(NSUInteger)indexOfObject:(id)anObject;")); 13163 EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;")); 13164 EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;")); 13165 EXPECT_EQ("- (NSInteger)Method3:(id)anObject;", 13166 format("-(NSInteger)Method3:(id)anObject;")); 13167 EXPECT_EQ("- (NSInteger)Method4:(id)anObject;", 13168 format("-(NSInteger)Method4:(id)anObject;")); 13169 EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;", 13170 format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;")); 13171 EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;", 13172 format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;")); 13173 EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject " 13174 "forAllCells:(BOOL)flag;", 13175 format("- (void)sendAction:(SEL)aSelector to:(id)anObject " 13176 "forAllCells:(BOOL)flag;")); 13177 13178 // Very long objectiveC method declaration. 13179 verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n" 13180 " (SoooooooooooooooooooooomeType *)bbbbbbbbbb;"); 13181 verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n" 13182 " inRange:(NSRange)range\n" 13183 " outRange:(NSRange)out_range\n" 13184 " outRange1:(NSRange)out_range1\n" 13185 " outRange2:(NSRange)out_range2\n" 13186 " outRange3:(NSRange)out_range3\n" 13187 " outRange4:(NSRange)out_range4\n" 13188 " outRange5:(NSRange)out_range5\n" 13189 " outRange6:(NSRange)out_range6\n" 13190 " outRange7:(NSRange)out_range7\n" 13191 " outRange8:(NSRange)out_range8\n" 13192 " outRange9:(NSRange)out_range9;"); 13193 13194 // When the function name has to be wrapped. 13195 FormatStyle Style = getLLVMStyle(); 13196 // ObjC ignores IndentWrappedFunctionNames when wrapping methods 13197 // and always indents instead. 13198 Style.IndentWrappedFunctionNames = false; 13199 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n" 13200 " veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n" 13201 " anotherName:(NSString)bbbbbbbbbbbbbb {\n" 13202 "}", 13203 Style); 13204 Style.IndentWrappedFunctionNames = true; 13205 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n" 13206 " veryLooooooooooongName:(NSString)cccccccccccccc\n" 13207 " anotherName:(NSString)dddddddddddddd {\n" 13208 "}", 13209 Style); 13210 13211 verifyFormat("- (int)sum:(vector<int>)numbers;"); 13212 verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;"); 13213 // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC 13214 // protocol lists (but not for template classes): 13215 // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;"); 13216 13217 verifyFormat("- (int (*)())foo:(int (*)())f;"); 13218 verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;"); 13219 13220 // If there's no return type (very rare in practice!), LLVM and Google style 13221 // agree. 13222 verifyFormat("- foo;"); 13223 verifyFormat("- foo:(int)f;"); 13224 verifyGoogleFormat("- foo:(int)foo;"); 13225 } 13226 13227 TEST_F(FormatTest, BreaksStringLiterals) { 13228 EXPECT_EQ("\"some text \"\n" 13229 "\"other\";", 13230 format("\"some text other\";", getLLVMStyleWithColumns(12))); 13231 EXPECT_EQ("\"some text \"\n" 13232 "\"other\";", 13233 format("\\\n\"some text other\";", getLLVMStyleWithColumns(12))); 13234 EXPECT_EQ( 13235 "#define A \\\n" 13236 " \"some \" \\\n" 13237 " \"text \" \\\n" 13238 " \"other\";", 13239 format("#define A \"some text other\";", getLLVMStyleWithColumns(12))); 13240 EXPECT_EQ( 13241 "#define A \\\n" 13242 " \"so \" \\\n" 13243 " \"text \" \\\n" 13244 " \"other\";", 13245 format("#define A \"so text other\";", getLLVMStyleWithColumns(12))); 13246 13247 EXPECT_EQ("\"some text\"", 13248 format("\"some text\"", getLLVMStyleWithColumns(1))); 13249 EXPECT_EQ("\"some text\"", 13250 format("\"some text\"", getLLVMStyleWithColumns(11))); 13251 EXPECT_EQ("\"some \"\n" 13252 "\"text\"", 13253 format("\"some text\"", getLLVMStyleWithColumns(10))); 13254 EXPECT_EQ("\"some \"\n" 13255 "\"text\"", 13256 format("\"some text\"", getLLVMStyleWithColumns(7))); 13257 EXPECT_EQ("\"some\"\n" 13258 "\" tex\"\n" 13259 "\"t\"", 13260 format("\"some text\"", getLLVMStyleWithColumns(6))); 13261 EXPECT_EQ("\"some\"\n" 13262 "\" tex\"\n" 13263 "\" and\"", 13264 format("\"some tex and\"", getLLVMStyleWithColumns(6))); 13265 EXPECT_EQ("\"some\"\n" 13266 "\"/tex\"\n" 13267 "\"/and\"", 13268 format("\"some/tex/and\"", getLLVMStyleWithColumns(6))); 13269 13270 EXPECT_EQ("variable =\n" 13271 " \"long string \"\n" 13272 " \"literal\";", 13273 format("variable = \"long string literal\";", 13274 getLLVMStyleWithColumns(20))); 13275 13276 EXPECT_EQ("variable = f(\n" 13277 " \"long string \"\n" 13278 " \"literal\",\n" 13279 " short,\n" 13280 " loooooooooooooooooooong);", 13281 format("variable = f(\"long string literal\", short, " 13282 "loooooooooooooooooooong);", 13283 getLLVMStyleWithColumns(20))); 13284 13285 EXPECT_EQ( 13286 "f(g(\"long string \"\n" 13287 " \"literal\"),\n" 13288 " b);", 13289 format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20))); 13290 EXPECT_EQ("f(g(\"long string \"\n" 13291 " \"literal\",\n" 13292 " a),\n" 13293 " b);", 13294 format("f(g(\"long string literal\", a), b);", 13295 getLLVMStyleWithColumns(20))); 13296 EXPECT_EQ( 13297 "f(\"one two\".split(\n" 13298 " variable));", 13299 format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20))); 13300 EXPECT_EQ("f(\"one two three four five six \"\n" 13301 " \"seven\".split(\n" 13302 " really_looooong_variable));", 13303 format("f(\"one two three four five six seven\"." 13304 "split(really_looooong_variable));", 13305 getLLVMStyleWithColumns(33))); 13306 13307 EXPECT_EQ("f(\"some \"\n" 13308 " \"text\",\n" 13309 " other);", 13310 format("f(\"some text\", other);", getLLVMStyleWithColumns(10))); 13311 13312 // Only break as a last resort. 13313 verifyFormat( 13314 "aaaaaaaaaaaaaaaaaaaa(\n" 13315 " aaaaaaaaaaaaaaaaaaaa,\n" 13316 " aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));"); 13317 13318 EXPECT_EQ("\"splitmea\"\n" 13319 "\"trandomp\"\n" 13320 "\"oint\"", 13321 format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10))); 13322 13323 EXPECT_EQ("\"split/\"\n" 13324 "\"pathat/\"\n" 13325 "\"slashes\"", 13326 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10))); 13327 13328 EXPECT_EQ("\"split/\"\n" 13329 "\"pathat/\"\n" 13330 "\"slashes\"", 13331 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10))); 13332 EXPECT_EQ("\"split at \"\n" 13333 "\"spaces/at/\"\n" 13334 "\"slashes.at.any$\"\n" 13335 "\"non-alphanumeric%\"\n" 13336 "\"1111111111characte\"\n" 13337 "\"rs\"", 13338 format("\"split at " 13339 "spaces/at/" 13340 "slashes.at." 13341 "any$non-" 13342 "alphanumeric%" 13343 "1111111111characte" 13344 "rs\"", 13345 getLLVMStyleWithColumns(20))); 13346 13347 // Verify that splitting the strings understands 13348 // Style::AlwaysBreakBeforeMultilineStrings. 13349 EXPECT_EQ("aaaaaaaaaaaa(\n" 13350 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n" 13351 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");", 13352 format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa " 13353 "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa " 13354 "aaaaaaaaaaaaaaaaaaaaaa\");", 13355 getGoogleStyle())); 13356 EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13357 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";", 13358 format("return \"aaaaaaaaaaaaaaaaaaaaaa " 13359 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa " 13360 "aaaaaaaaaaaaaaaaaaaaaa\";", 13361 getGoogleStyle())); 13362 EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13363 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";", 13364 format("llvm::outs() << " 13365 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa" 13366 "aaaaaaaaaaaaaaaaaaa\";")); 13367 EXPECT_EQ("ffff(\n" 13368 " {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13369 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});", 13370 format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa " 13371 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});", 13372 getGoogleStyle())); 13373 13374 FormatStyle Style = getLLVMStyleWithColumns(12); 13375 Style.BreakStringLiterals = false; 13376 EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style)); 13377 13378 FormatStyle AlignLeft = getLLVMStyleWithColumns(12); 13379 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left; 13380 EXPECT_EQ("#define A \\\n" 13381 " \"some \" \\\n" 13382 " \"text \" \\\n" 13383 " \"other\";", 13384 format("#define A \"some text other\";", AlignLeft)); 13385 } 13386 13387 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) { 13388 EXPECT_EQ("C a = \"some more \"\n" 13389 " \"text\";", 13390 format("C a = \"some more text\";", getLLVMStyleWithColumns(18))); 13391 } 13392 13393 TEST_F(FormatTest, FullyRemoveEmptyLines) { 13394 FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80); 13395 NoEmptyLines.MaxEmptyLinesToKeep = 0; 13396 EXPECT_EQ("int i = a(b());", 13397 format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines)); 13398 } 13399 13400 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) { 13401 EXPECT_EQ( 13402 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 13403 "(\n" 13404 " \"x\t\");", 13405 format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 13406 "aaaaaaa(" 13407 "\"x\t\");")); 13408 } 13409 13410 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) { 13411 EXPECT_EQ( 13412 "u8\"utf8 string \"\n" 13413 "u8\"literal\";", 13414 format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16))); 13415 EXPECT_EQ( 13416 "u\"utf16 string \"\n" 13417 "u\"literal\";", 13418 format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16))); 13419 EXPECT_EQ( 13420 "U\"utf32 string \"\n" 13421 "U\"literal\";", 13422 format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16))); 13423 EXPECT_EQ("L\"wide string \"\n" 13424 "L\"literal\";", 13425 format("L\"wide string literal\";", getGoogleStyleWithColumns(16))); 13426 EXPECT_EQ("@\"NSString \"\n" 13427 "@\"literal\";", 13428 format("@\"NSString literal\";", getGoogleStyleWithColumns(19))); 13429 verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26)); 13430 13431 // This input makes clang-format try to split the incomplete unicode escape 13432 // sequence, which used to lead to a crasher. 13433 verifyNoCrash( 13434 "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 13435 getLLVMStyleWithColumns(60)); 13436 } 13437 13438 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) { 13439 FormatStyle Style = getGoogleStyleWithColumns(15); 13440 EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style)); 13441 EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style)); 13442 EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style)); 13443 EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style)); 13444 EXPECT_EQ("u8R\"x(raw literal)x\";", 13445 format("u8R\"x(raw literal)x\";", Style)); 13446 } 13447 13448 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) { 13449 FormatStyle Style = getLLVMStyleWithColumns(20); 13450 EXPECT_EQ( 13451 "_T(\"aaaaaaaaaaaaaa\")\n" 13452 "_T(\"aaaaaaaaaaaaaa\")\n" 13453 "_T(\"aaaaaaaaaaaa\")", 13454 format(" _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style)); 13455 EXPECT_EQ("f(x,\n" 13456 " _T(\"aaaaaaaaaaaa\")\n" 13457 " _T(\"aaa\"),\n" 13458 " z);", 13459 format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style)); 13460 13461 // FIXME: Handle embedded spaces in one iteration. 13462 // EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n" 13463 // "_T(\"aaaaaaaaaaaaa\")\n" 13464 // "_T(\"aaaaaaaaaaaaa\")\n" 13465 // "_T(\"a\")", 13466 // format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", 13467 // getLLVMStyleWithColumns(20))); 13468 EXPECT_EQ( 13469 "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", 13470 format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style)); 13471 EXPECT_EQ("f(\n" 13472 "#if !TEST\n" 13473 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n" 13474 "#endif\n" 13475 ");", 13476 format("f(\n" 13477 "#if !TEST\n" 13478 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n" 13479 "#endif\n" 13480 ");")); 13481 EXPECT_EQ("f(\n" 13482 "\n" 13483 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));", 13484 format("f(\n" 13485 "\n" 13486 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));")); 13487 // Regression test for accessing tokens past the end of a vector in the 13488 // TokenLexer. 13489 verifyNoCrash(R"(_T( 13490 " 13491 ) 13492 )"); 13493 } 13494 13495 TEST_F(FormatTest, BreaksStringLiteralOperands) { 13496 // In a function call with two operands, the second can be broken with no line 13497 // break before it. 13498 EXPECT_EQ( 13499 "func(a, \"long long \"\n" 13500 " \"long long\");", 13501 format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24))); 13502 // In a function call with three operands, the second must be broken with a 13503 // line break before it. 13504 EXPECT_EQ("func(a,\n" 13505 " \"long long long \"\n" 13506 " \"long\",\n" 13507 " c);", 13508 format("func(a, \"long long long long\", c);", 13509 getLLVMStyleWithColumns(24))); 13510 // In a function call with three operands, the third must be broken with a 13511 // line break before it. 13512 EXPECT_EQ("func(a, b,\n" 13513 " \"long long long \"\n" 13514 " \"long\");", 13515 format("func(a, b, \"long long long long\");", 13516 getLLVMStyleWithColumns(24))); 13517 // In a function call with three operands, both the second and the third must 13518 // be broken with a line break before them. 13519 EXPECT_EQ("func(a,\n" 13520 " \"long long long \"\n" 13521 " \"long\",\n" 13522 " \"long long long \"\n" 13523 " \"long\");", 13524 format("func(a, \"long long long long\", \"long long long long\");", 13525 getLLVMStyleWithColumns(24))); 13526 // In a chain of << with two operands, the second can be broken with no line 13527 // break before it. 13528 EXPECT_EQ("a << \"line line \"\n" 13529 " \"line\";", 13530 format("a << \"line line line\";", getLLVMStyleWithColumns(20))); 13531 // In a chain of << with three operands, the second can be broken with no line 13532 // break before it. 13533 EXPECT_EQ( 13534 "abcde << \"line \"\n" 13535 " \"line line\"\n" 13536 " << c;", 13537 format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20))); 13538 // In a chain of << with three operands, the third must be broken with a line 13539 // break before it. 13540 EXPECT_EQ( 13541 "a << b\n" 13542 " << \"line line \"\n" 13543 " \"line\";", 13544 format("a << b << \"line line line\";", getLLVMStyleWithColumns(20))); 13545 // In a chain of << with three operands, the second can be broken with no line 13546 // break before it and the third must be broken with a line break before it. 13547 EXPECT_EQ("abcd << \"line line \"\n" 13548 " \"line\"\n" 13549 " << \"line line \"\n" 13550 " \"line\";", 13551 format("abcd << \"line line line\" << \"line line line\";", 13552 getLLVMStyleWithColumns(20))); 13553 // In a chain of binary operators with two operands, the second can be broken 13554 // with no line break before it. 13555 EXPECT_EQ( 13556 "abcd + \"line line \"\n" 13557 " \"line line\";", 13558 format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20))); 13559 // In a chain of binary operators with three operands, the second must be 13560 // broken with a line break before it. 13561 EXPECT_EQ("abcd +\n" 13562 " \"line line \"\n" 13563 " \"line line\" +\n" 13564 " e;", 13565 format("abcd + \"line line line line\" + e;", 13566 getLLVMStyleWithColumns(20))); 13567 // In a function call with two operands, with AlignAfterOpenBracket enabled, 13568 // the first must be broken with a line break before it. 13569 FormatStyle Style = getLLVMStyleWithColumns(25); 13570 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 13571 EXPECT_EQ("someFunction(\n" 13572 " \"long long long \"\n" 13573 " \"long\",\n" 13574 " a);", 13575 format("someFunction(\"long long long long\", a);", Style)); 13576 } 13577 13578 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) { 13579 EXPECT_EQ( 13580 "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13581 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13582 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";", 13583 format("aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13584 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13585 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";")); 13586 } 13587 13588 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) { 13589 EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);", 13590 format("f(g(R\"x(raw literal)x\", a), b);", getGoogleStyle())); 13591 EXPECT_EQ("fffffffffff(g(R\"x(\n" 13592 "multiline raw string literal xxxxxxxxxxxxxx\n" 13593 ")x\",\n" 13594 " a),\n" 13595 " b);", 13596 format("fffffffffff(g(R\"x(\n" 13597 "multiline raw string literal xxxxxxxxxxxxxx\n" 13598 ")x\", a), b);", 13599 getGoogleStyleWithColumns(20))); 13600 EXPECT_EQ("fffffffffff(\n" 13601 " g(R\"x(qqq\n" 13602 "multiline raw string literal xxxxxxxxxxxxxx\n" 13603 ")x\",\n" 13604 " a),\n" 13605 " b);", 13606 format("fffffffffff(g(R\"x(qqq\n" 13607 "multiline raw string literal xxxxxxxxxxxxxx\n" 13608 ")x\", a), b);", 13609 getGoogleStyleWithColumns(20))); 13610 13611 EXPECT_EQ("fffffffffff(R\"x(\n" 13612 "multiline raw string literal xxxxxxxxxxxxxx\n" 13613 ")x\");", 13614 format("fffffffffff(R\"x(\n" 13615 "multiline raw string literal xxxxxxxxxxxxxx\n" 13616 ")x\");", 13617 getGoogleStyleWithColumns(20))); 13618 EXPECT_EQ("fffffffffff(R\"x(\n" 13619 "multiline raw string literal xxxxxxxxxxxxxx\n" 13620 ")x\" + bbbbbb);", 13621 format("fffffffffff(R\"x(\n" 13622 "multiline raw string literal xxxxxxxxxxxxxx\n" 13623 ")x\" + bbbbbb);", 13624 getGoogleStyleWithColumns(20))); 13625 EXPECT_EQ("fffffffffff(\n" 13626 " R\"x(\n" 13627 "multiline raw string literal xxxxxxxxxxxxxx\n" 13628 ")x\" +\n" 13629 " bbbbbb);", 13630 format("fffffffffff(\n" 13631 " R\"x(\n" 13632 "multiline raw string literal xxxxxxxxxxxxxx\n" 13633 ")x\" + bbbbbb);", 13634 getGoogleStyleWithColumns(20))); 13635 EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);", 13636 format("fffffffffff(\n" 13637 " R\"(single line raw string)\" + bbbbbb);")); 13638 } 13639 13640 TEST_F(FormatTest, SkipsUnknownStringLiterals) { 13641 verifyFormat("string a = \"unterminated;"); 13642 EXPECT_EQ("function(\"unterminated,\n" 13643 " OtherParameter);", 13644 format("function( \"unterminated,\n" 13645 " OtherParameter);")); 13646 } 13647 13648 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) { 13649 FormatStyle Style = getLLVMStyle(); 13650 Style.Standard = FormatStyle::LS_Cpp03; 13651 EXPECT_EQ("#define x(_a) printf(\"foo\" _a);", 13652 format("#define x(_a) printf(\"foo\"_a);", Style)); 13653 } 13654 13655 TEST_F(FormatTest, CppLexVersion) { 13656 FormatStyle Style = getLLVMStyle(); 13657 // Formatting of x * y differs if x is a type. 13658 verifyFormat("void foo() { MACRO(a * b); }", Style); 13659 verifyFormat("void foo() { MACRO(int *b); }", Style); 13660 13661 // LLVM style uses latest lexer. 13662 verifyFormat("void foo() { MACRO(char8_t *b); }", Style); 13663 Style.Standard = FormatStyle::LS_Cpp17; 13664 // But in c++17, char8_t isn't a keyword. 13665 verifyFormat("void foo() { MACRO(char8_t * b); }", Style); 13666 } 13667 13668 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); } 13669 13670 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) { 13671 EXPECT_EQ("someFunction(\"aaabbbcccd\"\n" 13672 " \"ddeeefff\");", 13673 format("someFunction(\"aaabbbcccdddeeefff\");", 13674 getLLVMStyleWithColumns(25))); 13675 EXPECT_EQ("someFunction1234567890(\n" 13676 " \"aaabbbcccdddeeefff\");", 13677 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 13678 getLLVMStyleWithColumns(26))); 13679 EXPECT_EQ("someFunction1234567890(\n" 13680 " \"aaabbbcccdddeeeff\"\n" 13681 " \"f\");", 13682 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 13683 getLLVMStyleWithColumns(25))); 13684 EXPECT_EQ("someFunction1234567890(\n" 13685 " \"aaabbbcccdddeeeff\"\n" 13686 " \"f\");", 13687 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 13688 getLLVMStyleWithColumns(24))); 13689 EXPECT_EQ("someFunction(\n" 13690 " \"aaabbbcc ddde \"\n" 13691 " \"efff\");", 13692 format("someFunction(\"aaabbbcc ddde efff\");", 13693 getLLVMStyleWithColumns(25))); 13694 EXPECT_EQ("someFunction(\"aaabbbccc \"\n" 13695 " \"ddeeefff\");", 13696 format("someFunction(\"aaabbbccc ddeeefff\");", 13697 getLLVMStyleWithColumns(25))); 13698 EXPECT_EQ("someFunction1234567890(\n" 13699 " \"aaabb \"\n" 13700 " \"cccdddeeefff\");", 13701 format("someFunction1234567890(\"aaabb cccdddeeefff\");", 13702 getLLVMStyleWithColumns(25))); 13703 EXPECT_EQ("#define A \\\n" 13704 " string s = \\\n" 13705 " \"123456789\" \\\n" 13706 " \"0\"; \\\n" 13707 " int i;", 13708 format("#define A string s = \"1234567890\"; int i;", 13709 getLLVMStyleWithColumns(20))); 13710 EXPECT_EQ("someFunction(\n" 13711 " \"aaabbbcc \"\n" 13712 " \"dddeeefff\");", 13713 format("someFunction(\"aaabbbcc dddeeefff\");", 13714 getLLVMStyleWithColumns(25))); 13715 } 13716 13717 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) { 13718 EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3))); 13719 EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2))); 13720 EXPECT_EQ("\"test\"\n" 13721 "\"\\n\"", 13722 format("\"test\\n\"", getLLVMStyleWithColumns(7))); 13723 EXPECT_EQ("\"tes\\\\\"\n" 13724 "\"n\"", 13725 format("\"tes\\\\n\"", getLLVMStyleWithColumns(7))); 13726 EXPECT_EQ("\"\\\\\\\\\"\n" 13727 "\"\\n\"", 13728 format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7))); 13729 EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7))); 13730 EXPECT_EQ("\"\\uff01\"\n" 13731 "\"test\"", 13732 format("\"\\uff01test\"", getLLVMStyleWithColumns(8))); 13733 EXPECT_EQ("\"\\Uff01ff02\"", 13734 format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11))); 13735 EXPECT_EQ("\"\\x000000000001\"\n" 13736 "\"next\"", 13737 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16))); 13738 EXPECT_EQ("\"\\x000000000001next\"", 13739 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15))); 13740 EXPECT_EQ("\"\\x000000000001\"", 13741 format("\"\\x000000000001\"", getLLVMStyleWithColumns(7))); 13742 EXPECT_EQ("\"test\"\n" 13743 "\"\\000000\"\n" 13744 "\"000001\"", 13745 format("\"test\\000000000001\"", getLLVMStyleWithColumns(9))); 13746 EXPECT_EQ("\"test\\000\"\n" 13747 "\"00000000\"\n" 13748 "\"1\"", 13749 format("\"test\\000000000001\"", getLLVMStyleWithColumns(10))); 13750 } 13751 13752 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) { 13753 verifyFormat("void f() {\n" 13754 " return g() {}\n" 13755 " void h() {}"); 13756 verifyFormat("int a[] = {void forgot_closing_brace(){f();\n" 13757 "g();\n" 13758 "}"); 13759 } 13760 13761 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) { 13762 verifyFormat( 13763 "void f() { return C{param1, param2}.SomeCall(param1, param2); }"); 13764 } 13765 13766 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) { 13767 verifyFormat("class X {\n" 13768 " void f() {\n" 13769 " }\n" 13770 "};", 13771 getLLVMStyleWithColumns(12)); 13772 } 13773 13774 TEST_F(FormatTest, ConfigurableIndentWidth) { 13775 FormatStyle EightIndent = getLLVMStyleWithColumns(18); 13776 EightIndent.IndentWidth = 8; 13777 EightIndent.ContinuationIndentWidth = 8; 13778 verifyFormat("void f() {\n" 13779 " someFunction();\n" 13780 " if (true) {\n" 13781 " f();\n" 13782 " }\n" 13783 "}", 13784 EightIndent); 13785 verifyFormat("class X {\n" 13786 " void f() {\n" 13787 " }\n" 13788 "};", 13789 EightIndent); 13790 verifyFormat("int x[] = {\n" 13791 " call(),\n" 13792 " call()};", 13793 EightIndent); 13794 } 13795 13796 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) { 13797 verifyFormat("double\n" 13798 "f();", 13799 getLLVMStyleWithColumns(8)); 13800 } 13801 13802 TEST_F(FormatTest, ConfigurableUseOfTab) { 13803 FormatStyle Tab = getLLVMStyleWithColumns(42); 13804 Tab.IndentWidth = 8; 13805 Tab.UseTab = FormatStyle::UT_Always; 13806 Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left; 13807 13808 EXPECT_EQ("if (aaaaaaaa && // q\n" 13809 " bb)\t\t// w\n" 13810 "\t;", 13811 format("if (aaaaaaaa &&// q\n" 13812 "bb)// w\n" 13813 ";", 13814 Tab)); 13815 EXPECT_EQ("if (aaa && bbb) // w\n" 13816 "\t;", 13817 format("if(aaa&&bbb)// w\n" 13818 ";", 13819 Tab)); 13820 13821 verifyFormat("class X {\n" 13822 "\tvoid f() {\n" 13823 "\t\tsomeFunction(parameter1,\n" 13824 "\t\t\t parameter2);\n" 13825 "\t}\n" 13826 "};", 13827 Tab); 13828 verifyFormat("#define A \\\n" 13829 "\tvoid f() { \\\n" 13830 "\t\tsomeFunction( \\\n" 13831 "\t\t parameter1, \\\n" 13832 "\t\t parameter2); \\\n" 13833 "\t}", 13834 Tab); 13835 verifyFormat("int a;\t // x\n" 13836 "int bbbbbbbb; // x\n", 13837 Tab); 13838 13839 Tab.TabWidth = 4; 13840 Tab.IndentWidth = 8; 13841 verifyFormat("class TabWidth4Indent8 {\n" 13842 "\t\tvoid f() {\n" 13843 "\t\t\t\tsomeFunction(parameter1,\n" 13844 "\t\t\t\t\t\t\t parameter2);\n" 13845 "\t\t}\n" 13846 "};", 13847 Tab); 13848 13849 Tab.TabWidth = 4; 13850 Tab.IndentWidth = 4; 13851 verifyFormat("class TabWidth4Indent4 {\n" 13852 "\tvoid f() {\n" 13853 "\t\tsomeFunction(parameter1,\n" 13854 "\t\t\t\t\t parameter2);\n" 13855 "\t}\n" 13856 "};", 13857 Tab); 13858 13859 Tab.TabWidth = 8; 13860 Tab.IndentWidth = 4; 13861 verifyFormat("class TabWidth8Indent4 {\n" 13862 " void f() {\n" 13863 "\tsomeFunction(parameter1,\n" 13864 "\t\t parameter2);\n" 13865 " }\n" 13866 "};", 13867 Tab); 13868 13869 Tab.TabWidth = 8; 13870 Tab.IndentWidth = 8; 13871 EXPECT_EQ("/*\n" 13872 "\t a\t\tcomment\n" 13873 "\t in multiple lines\n" 13874 " */", 13875 format(" /*\t \t \n" 13876 " \t \t a\t\tcomment\t \t\n" 13877 " \t \t in multiple lines\t\n" 13878 " \t */", 13879 Tab)); 13880 13881 Tab.UseTab = FormatStyle::UT_ForIndentation; 13882 verifyFormat("{\n" 13883 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13884 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13885 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13886 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13887 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13888 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13889 "};", 13890 Tab); 13891 verifyFormat("enum AA {\n" 13892 "\ta1, // Force multiple lines\n" 13893 "\ta2,\n" 13894 "\ta3\n" 13895 "};", 13896 Tab); 13897 EXPECT_EQ("if (aaaaaaaa && // q\n" 13898 " bb) // w\n" 13899 "\t;", 13900 format("if (aaaaaaaa &&// q\n" 13901 "bb)// w\n" 13902 ";", 13903 Tab)); 13904 verifyFormat("class X {\n" 13905 "\tvoid f() {\n" 13906 "\t\tsomeFunction(parameter1,\n" 13907 "\t\t parameter2);\n" 13908 "\t}\n" 13909 "};", 13910 Tab); 13911 verifyFormat("{\n" 13912 "\tQ(\n" 13913 "\t {\n" 13914 "\t\t int a;\n" 13915 "\t\t someFunction(aaaaaaaa,\n" 13916 "\t\t bbbbbbb);\n" 13917 "\t },\n" 13918 "\t p);\n" 13919 "}", 13920 Tab); 13921 EXPECT_EQ("{\n" 13922 "\t/* aaaa\n" 13923 "\t bbbb */\n" 13924 "}", 13925 format("{\n" 13926 "/* aaaa\n" 13927 " bbbb */\n" 13928 "}", 13929 Tab)); 13930 EXPECT_EQ("{\n" 13931 "\t/*\n" 13932 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 13933 "\t bbbbbbbbbbbbb\n" 13934 "\t*/\n" 13935 "}", 13936 format("{\n" 13937 "/*\n" 13938 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 13939 "*/\n" 13940 "}", 13941 Tab)); 13942 EXPECT_EQ("{\n" 13943 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 13944 "\t// bbbbbbbbbbbbb\n" 13945 "}", 13946 format("{\n" 13947 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 13948 "}", 13949 Tab)); 13950 EXPECT_EQ("{\n" 13951 "\t/*\n" 13952 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 13953 "\t bbbbbbbbbbbbb\n" 13954 "\t*/\n" 13955 "}", 13956 format("{\n" 13957 "\t/*\n" 13958 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 13959 "\t*/\n" 13960 "}", 13961 Tab)); 13962 EXPECT_EQ("{\n" 13963 "\t/*\n" 13964 "\n" 13965 "\t*/\n" 13966 "}", 13967 format("{\n" 13968 "\t/*\n" 13969 "\n" 13970 "\t*/\n" 13971 "}", 13972 Tab)); 13973 EXPECT_EQ("{\n" 13974 "\t/*\n" 13975 " asdf\n" 13976 "\t*/\n" 13977 "}", 13978 format("{\n" 13979 "\t/*\n" 13980 " asdf\n" 13981 "\t*/\n" 13982 "}", 13983 Tab)); 13984 13985 verifyFormat("void f() {\n" 13986 "\treturn true ? aaaaaaaaaaaaaaaaaa\n" 13987 "\t : bbbbbbbbbbbbbbbbbb\n" 13988 "}", 13989 Tab); 13990 FormatStyle TabNoBreak = Tab; 13991 TabNoBreak.BreakBeforeTernaryOperators = false; 13992 verifyFormat("void f() {\n" 13993 "\treturn true ? aaaaaaaaaaaaaaaaaa :\n" 13994 "\t bbbbbbbbbbbbbbbbbb\n" 13995 "}", 13996 TabNoBreak); 13997 verifyFormat("void f() {\n" 13998 "\treturn true ?\n" 13999 "\t aaaaaaaaaaaaaaaaaaaa :\n" 14000 "\t bbbbbbbbbbbbbbbbbbbb\n" 14001 "}", 14002 TabNoBreak); 14003 14004 Tab.UseTab = FormatStyle::UT_Never; 14005 EXPECT_EQ("/*\n" 14006 " a\t\tcomment\n" 14007 " in multiple lines\n" 14008 " */", 14009 format(" /*\t \t \n" 14010 " \t \t a\t\tcomment\t \t\n" 14011 " \t \t in multiple lines\t\n" 14012 " \t */", 14013 Tab)); 14014 EXPECT_EQ("/* some\n" 14015 " comment */", 14016 format(" \t \t /* some\n" 14017 " \t \t comment */", 14018 Tab)); 14019 EXPECT_EQ("int a; /* some\n" 14020 " comment */", 14021 format(" \t \t int a; /* some\n" 14022 " \t \t comment */", 14023 Tab)); 14024 14025 EXPECT_EQ("int a; /* some\n" 14026 "comment */", 14027 format(" \t \t int\ta; /* some\n" 14028 " \t \t comment */", 14029 Tab)); 14030 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14031 " comment */", 14032 format(" \t \t f(\"\t\t\"); /* some\n" 14033 " \t \t comment */", 14034 Tab)); 14035 EXPECT_EQ("{\n" 14036 " /*\n" 14037 " * Comment\n" 14038 " */\n" 14039 " int i;\n" 14040 "}", 14041 format("{\n" 14042 "\t/*\n" 14043 "\t * Comment\n" 14044 "\t */\n" 14045 "\t int i;\n" 14046 "}", 14047 Tab)); 14048 14049 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation; 14050 Tab.TabWidth = 8; 14051 Tab.IndentWidth = 8; 14052 EXPECT_EQ("if (aaaaaaaa && // q\n" 14053 " bb) // w\n" 14054 "\t;", 14055 format("if (aaaaaaaa &&// q\n" 14056 "bb)// w\n" 14057 ";", 14058 Tab)); 14059 EXPECT_EQ("if (aaa && bbb) // w\n" 14060 "\t;", 14061 format("if(aaa&&bbb)// w\n" 14062 ";", 14063 Tab)); 14064 verifyFormat("class X {\n" 14065 "\tvoid f() {\n" 14066 "\t\tsomeFunction(parameter1,\n" 14067 "\t\t\t parameter2);\n" 14068 "\t}\n" 14069 "};", 14070 Tab); 14071 verifyFormat("#define A \\\n" 14072 "\tvoid f() { \\\n" 14073 "\t\tsomeFunction( \\\n" 14074 "\t\t parameter1, \\\n" 14075 "\t\t parameter2); \\\n" 14076 "\t}", 14077 Tab); 14078 Tab.TabWidth = 4; 14079 Tab.IndentWidth = 8; 14080 verifyFormat("class TabWidth4Indent8 {\n" 14081 "\t\tvoid f() {\n" 14082 "\t\t\t\tsomeFunction(parameter1,\n" 14083 "\t\t\t\t\t\t\t parameter2);\n" 14084 "\t\t}\n" 14085 "};", 14086 Tab); 14087 Tab.TabWidth = 4; 14088 Tab.IndentWidth = 4; 14089 verifyFormat("class TabWidth4Indent4 {\n" 14090 "\tvoid f() {\n" 14091 "\t\tsomeFunction(parameter1,\n" 14092 "\t\t\t\t\t parameter2);\n" 14093 "\t}\n" 14094 "};", 14095 Tab); 14096 Tab.TabWidth = 8; 14097 Tab.IndentWidth = 4; 14098 verifyFormat("class TabWidth8Indent4 {\n" 14099 " void f() {\n" 14100 "\tsomeFunction(parameter1,\n" 14101 "\t\t parameter2);\n" 14102 " }\n" 14103 "};", 14104 Tab); 14105 Tab.TabWidth = 8; 14106 Tab.IndentWidth = 8; 14107 EXPECT_EQ("/*\n" 14108 "\t a\t\tcomment\n" 14109 "\t in multiple lines\n" 14110 " */", 14111 format(" /*\t \t \n" 14112 " \t \t a\t\tcomment\t \t\n" 14113 " \t \t in multiple lines\t\n" 14114 " \t */", 14115 Tab)); 14116 verifyFormat("{\n" 14117 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14118 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14119 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14120 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14121 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14122 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14123 "};", 14124 Tab); 14125 verifyFormat("enum AA {\n" 14126 "\ta1, // Force multiple lines\n" 14127 "\ta2,\n" 14128 "\ta3\n" 14129 "};", 14130 Tab); 14131 EXPECT_EQ("if (aaaaaaaa && // q\n" 14132 " bb) // w\n" 14133 "\t;", 14134 format("if (aaaaaaaa &&// q\n" 14135 "bb)// w\n" 14136 ";", 14137 Tab)); 14138 verifyFormat("class X {\n" 14139 "\tvoid f() {\n" 14140 "\t\tsomeFunction(parameter1,\n" 14141 "\t\t\t parameter2);\n" 14142 "\t}\n" 14143 "};", 14144 Tab); 14145 verifyFormat("{\n" 14146 "\tQ(\n" 14147 "\t {\n" 14148 "\t\t int a;\n" 14149 "\t\t someFunction(aaaaaaaa,\n" 14150 "\t\t\t\t bbbbbbb);\n" 14151 "\t },\n" 14152 "\t p);\n" 14153 "}", 14154 Tab); 14155 EXPECT_EQ("{\n" 14156 "\t/* aaaa\n" 14157 "\t bbbb */\n" 14158 "}", 14159 format("{\n" 14160 "/* aaaa\n" 14161 " bbbb */\n" 14162 "}", 14163 Tab)); 14164 EXPECT_EQ("{\n" 14165 "\t/*\n" 14166 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14167 "\t bbbbbbbbbbbbb\n" 14168 "\t*/\n" 14169 "}", 14170 format("{\n" 14171 "/*\n" 14172 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14173 "*/\n" 14174 "}", 14175 Tab)); 14176 EXPECT_EQ("{\n" 14177 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14178 "\t// bbbbbbbbbbbbb\n" 14179 "}", 14180 format("{\n" 14181 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14182 "}", 14183 Tab)); 14184 EXPECT_EQ("{\n" 14185 "\t/*\n" 14186 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14187 "\t bbbbbbbbbbbbb\n" 14188 "\t*/\n" 14189 "}", 14190 format("{\n" 14191 "\t/*\n" 14192 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14193 "\t*/\n" 14194 "}", 14195 Tab)); 14196 EXPECT_EQ("{\n" 14197 "\t/*\n" 14198 "\n" 14199 "\t*/\n" 14200 "}", 14201 format("{\n" 14202 "\t/*\n" 14203 "\n" 14204 "\t*/\n" 14205 "}", 14206 Tab)); 14207 EXPECT_EQ("{\n" 14208 "\t/*\n" 14209 " asdf\n" 14210 "\t*/\n" 14211 "}", 14212 format("{\n" 14213 "\t/*\n" 14214 " asdf\n" 14215 "\t*/\n" 14216 "}", 14217 Tab)); 14218 EXPECT_EQ("/* some\n" 14219 " comment */", 14220 format(" \t \t /* some\n" 14221 " \t \t comment */", 14222 Tab)); 14223 EXPECT_EQ("int a; /* some\n" 14224 " comment */", 14225 format(" \t \t int a; /* some\n" 14226 " \t \t comment */", 14227 Tab)); 14228 EXPECT_EQ("int a; /* some\n" 14229 "comment */", 14230 format(" \t \t int\ta; /* some\n" 14231 " \t \t comment */", 14232 Tab)); 14233 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14234 " comment */", 14235 format(" \t \t f(\"\t\t\"); /* some\n" 14236 " \t \t comment */", 14237 Tab)); 14238 EXPECT_EQ("{\n" 14239 "\t/*\n" 14240 "\t * Comment\n" 14241 "\t */\n" 14242 "\tint i;\n" 14243 "}", 14244 format("{\n" 14245 "\t/*\n" 14246 "\t * Comment\n" 14247 "\t */\n" 14248 "\t int i;\n" 14249 "}", 14250 Tab)); 14251 Tab.TabWidth = 2; 14252 Tab.IndentWidth = 2; 14253 EXPECT_EQ("{\n" 14254 "\t/* aaaa\n" 14255 "\t\t bbbb */\n" 14256 "}", 14257 format("{\n" 14258 "/* aaaa\n" 14259 "\t bbbb */\n" 14260 "}", 14261 Tab)); 14262 EXPECT_EQ("{\n" 14263 "\t/*\n" 14264 "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14265 "\t\tbbbbbbbbbbbbb\n" 14266 "\t*/\n" 14267 "}", 14268 format("{\n" 14269 "/*\n" 14270 "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14271 "*/\n" 14272 "}", 14273 Tab)); 14274 Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 14275 Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 14276 Tab.TabWidth = 4; 14277 Tab.IndentWidth = 4; 14278 verifyFormat("class Assign {\n" 14279 "\tvoid f() {\n" 14280 "\t\tint x = 123;\n" 14281 "\t\tint random = 4;\n" 14282 "\t\tstd::string alphabet =\n" 14283 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n" 14284 "\t}\n" 14285 "};", 14286 Tab); 14287 14288 Tab.UseTab = FormatStyle::UT_AlignWithSpaces; 14289 Tab.TabWidth = 8; 14290 Tab.IndentWidth = 8; 14291 EXPECT_EQ("if (aaaaaaaa && // q\n" 14292 " bb) // w\n" 14293 "\t;", 14294 format("if (aaaaaaaa &&// q\n" 14295 "bb)// w\n" 14296 ";", 14297 Tab)); 14298 EXPECT_EQ("if (aaa && bbb) // w\n" 14299 "\t;", 14300 format("if(aaa&&bbb)// w\n" 14301 ";", 14302 Tab)); 14303 verifyFormat("class X {\n" 14304 "\tvoid f() {\n" 14305 "\t\tsomeFunction(parameter1,\n" 14306 "\t\t parameter2);\n" 14307 "\t}\n" 14308 "};", 14309 Tab); 14310 verifyFormat("#define A \\\n" 14311 "\tvoid f() { \\\n" 14312 "\t\tsomeFunction( \\\n" 14313 "\t\t parameter1, \\\n" 14314 "\t\t parameter2); \\\n" 14315 "\t}", 14316 Tab); 14317 Tab.TabWidth = 4; 14318 Tab.IndentWidth = 8; 14319 verifyFormat("class TabWidth4Indent8 {\n" 14320 "\t\tvoid f() {\n" 14321 "\t\t\t\tsomeFunction(parameter1,\n" 14322 "\t\t\t\t parameter2);\n" 14323 "\t\t}\n" 14324 "};", 14325 Tab); 14326 Tab.TabWidth = 4; 14327 Tab.IndentWidth = 4; 14328 verifyFormat("class TabWidth4Indent4 {\n" 14329 "\tvoid f() {\n" 14330 "\t\tsomeFunction(parameter1,\n" 14331 "\t\t parameter2);\n" 14332 "\t}\n" 14333 "};", 14334 Tab); 14335 Tab.TabWidth = 8; 14336 Tab.IndentWidth = 4; 14337 verifyFormat("class TabWidth8Indent4 {\n" 14338 " void f() {\n" 14339 "\tsomeFunction(parameter1,\n" 14340 "\t parameter2);\n" 14341 " }\n" 14342 "};", 14343 Tab); 14344 Tab.TabWidth = 8; 14345 Tab.IndentWidth = 8; 14346 EXPECT_EQ("/*\n" 14347 " a\t\tcomment\n" 14348 " in multiple lines\n" 14349 " */", 14350 format(" /*\t \t \n" 14351 " \t \t a\t\tcomment\t \t\n" 14352 " \t \t in multiple lines\t\n" 14353 " \t */", 14354 Tab)); 14355 verifyFormat("{\n" 14356 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14357 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14358 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14359 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14360 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14361 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14362 "};", 14363 Tab); 14364 verifyFormat("enum AA {\n" 14365 "\ta1, // Force multiple lines\n" 14366 "\ta2,\n" 14367 "\ta3\n" 14368 "};", 14369 Tab); 14370 EXPECT_EQ("if (aaaaaaaa && // q\n" 14371 " bb) // w\n" 14372 "\t;", 14373 format("if (aaaaaaaa &&// q\n" 14374 "bb)// w\n" 14375 ";", 14376 Tab)); 14377 verifyFormat("class X {\n" 14378 "\tvoid f() {\n" 14379 "\t\tsomeFunction(parameter1,\n" 14380 "\t\t parameter2);\n" 14381 "\t}\n" 14382 "};", 14383 Tab); 14384 verifyFormat("{\n" 14385 "\tQ(\n" 14386 "\t {\n" 14387 "\t\t int a;\n" 14388 "\t\t someFunction(aaaaaaaa,\n" 14389 "\t\t bbbbbbb);\n" 14390 "\t },\n" 14391 "\t p);\n" 14392 "}", 14393 Tab); 14394 EXPECT_EQ("{\n" 14395 "\t/* aaaa\n" 14396 "\t bbbb */\n" 14397 "}", 14398 format("{\n" 14399 "/* aaaa\n" 14400 " bbbb */\n" 14401 "}", 14402 Tab)); 14403 EXPECT_EQ("{\n" 14404 "\t/*\n" 14405 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14406 "\t bbbbbbbbbbbbb\n" 14407 "\t*/\n" 14408 "}", 14409 format("{\n" 14410 "/*\n" 14411 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14412 "*/\n" 14413 "}", 14414 Tab)); 14415 EXPECT_EQ("{\n" 14416 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14417 "\t// bbbbbbbbbbbbb\n" 14418 "}", 14419 format("{\n" 14420 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14421 "}", 14422 Tab)); 14423 EXPECT_EQ("{\n" 14424 "\t/*\n" 14425 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14426 "\t bbbbbbbbbbbbb\n" 14427 "\t*/\n" 14428 "}", 14429 format("{\n" 14430 "\t/*\n" 14431 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14432 "\t*/\n" 14433 "}", 14434 Tab)); 14435 EXPECT_EQ("{\n" 14436 "\t/*\n" 14437 "\n" 14438 "\t*/\n" 14439 "}", 14440 format("{\n" 14441 "\t/*\n" 14442 "\n" 14443 "\t*/\n" 14444 "}", 14445 Tab)); 14446 EXPECT_EQ("{\n" 14447 "\t/*\n" 14448 " asdf\n" 14449 "\t*/\n" 14450 "}", 14451 format("{\n" 14452 "\t/*\n" 14453 " asdf\n" 14454 "\t*/\n" 14455 "}", 14456 Tab)); 14457 EXPECT_EQ("/* some\n" 14458 " comment */", 14459 format(" \t \t /* some\n" 14460 " \t \t comment */", 14461 Tab)); 14462 EXPECT_EQ("int a; /* some\n" 14463 " comment */", 14464 format(" \t \t int a; /* some\n" 14465 " \t \t comment */", 14466 Tab)); 14467 EXPECT_EQ("int a; /* some\n" 14468 "comment */", 14469 format(" \t \t int\ta; /* some\n" 14470 " \t \t comment */", 14471 Tab)); 14472 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14473 " comment */", 14474 format(" \t \t f(\"\t\t\"); /* some\n" 14475 " \t \t comment */", 14476 Tab)); 14477 EXPECT_EQ("{\n" 14478 "\t/*\n" 14479 "\t * Comment\n" 14480 "\t */\n" 14481 "\tint i;\n" 14482 "}", 14483 format("{\n" 14484 "\t/*\n" 14485 "\t * Comment\n" 14486 "\t */\n" 14487 "\t int i;\n" 14488 "}", 14489 Tab)); 14490 Tab.TabWidth = 2; 14491 Tab.IndentWidth = 2; 14492 EXPECT_EQ("{\n" 14493 "\t/* aaaa\n" 14494 "\t bbbb */\n" 14495 "}", 14496 format("{\n" 14497 "/* aaaa\n" 14498 " bbbb */\n" 14499 "}", 14500 Tab)); 14501 EXPECT_EQ("{\n" 14502 "\t/*\n" 14503 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14504 "\t bbbbbbbbbbbbb\n" 14505 "\t*/\n" 14506 "}", 14507 format("{\n" 14508 "/*\n" 14509 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14510 "*/\n" 14511 "}", 14512 Tab)); 14513 Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 14514 Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 14515 Tab.TabWidth = 4; 14516 Tab.IndentWidth = 4; 14517 verifyFormat("class Assign {\n" 14518 "\tvoid f() {\n" 14519 "\t\tint x = 123;\n" 14520 "\t\tint random = 4;\n" 14521 "\t\tstd::string alphabet =\n" 14522 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n" 14523 "\t}\n" 14524 "};", 14525 Tab); 14526 Tab.AlignOperands = FormatStyle::OAS_Align; 14527 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n" 14528 " cccccccccccccccccccc;", 14529 Tab); 14530 // no alignment 14531 verifyFormat("int aaaaaaaaaa =\n" 14532 "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 14533 Tab); 14534 verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n" 14535 " : bbbbbbbbbbbbbb ? 222222222222222\n" 14536 " : 333333333333333;", 14537 Tab); 14538 Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 14539 Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator; 14540 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n" 14541 " + cccccccccccccccccccc;", 14542 Tab); 14543 } 14544 14545 TEST_F(FormatTest, ZeroTabWidth) { 14546 FormatStyle Tab = getLLVMStyleWithColumns(42); 14547 Tab.IndentWidth = 8; 14548 Tab.UseTab = FormatStyle::UT_Never; 14549 Tab.TabWidth = 0; 14550 EXPECT_EQ("void a(){\n" 14551 " // line starts with '\t'\n" 14552 "};", 14553 format("void a(){\n" 14554 "\t// line starts with '\t'\n" 14555 "};", 14556 Tab)); 14557 14558 EXPECT_EQ("void a(){\n" 14559 " // line starts with '\t'\n" 14560 "};", 14561 format("void a(){\n" 14562 "\t\t// line starts with '\t'\n" 14563 "};", 14564 Tab)); 14565 14566 Tab.UseTab = FormatStyle::UT_ForIndentation; 14567 EXPECT_EQ("void a(){\n" 14568 " // line starts with '\t'\n" 14569 "};", 14570 format("void a(){\n" 14571 "\t// line starts with '\t'\n" 14572 "};", 14573 Tab)); 14574 14575 EXPECT_EQ("void a(){\n" 14576 " // line starts with '\t'\n" 14577 "};", 14578 format("void a(){\n" 14579 "\t\t// line starts with '\t'\n" 14580 "};", 14581 Tab)); 14582 14583 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation; 14584 EXPECT_EQ("void a(){\n" 14585 " // line starts with '\t'\n" 14586 "};", 14587 format("void a(){\n" 14588 "\t// line starts with '\t'\n" 14589 "};", 14590 Tab)); 14591 14592 EXPECT_EQ("void a(){\n" 14593 " // line starts with '\t'\n" 14594 "};", 14595 format("void a(){\n" 14596 "\t\t// line starts with '\t'\n" 14597 "};", 14598 Tab)); 14599 14600 Tab.UseTab = FormatStyle::UT_AlignWithSpaces; 14601 EXPECT_EQ("void a(){\n" 14602 " // line starts with '\t'\n" 14603 "};", 14604 format("void a(){\n" 14605 "\t// line starts with '\t'\n" 14606 "};", 14607 Tab)); 14608 14609 EXPECT_EQ("void a(){\n" 14610 " // line starts with '\t'\n" 14611 "};", 14612 format("void a(){\n" 14613 "\t\t// line starts with '\t'\n" 14614 "};", 14615 Tab)); 14616 14617 Tab.UseTab = FormatStyle::UT_Always; 14618 EXPECT_EQ("void a(){\n" 14619 "// line starts with '\t'\n" 14620 "};", 14621 format("void a(){\n" 14622 "\t// line starts with '\t'\n" 14623 "};", 14624 Tab)); 14625 14626 EXPECT_EQ("void a(){\n" 14627 "// line starts with '\t'\n" 14628 "};", 14629 format("void a(){\n" 14630 "\t\t// line starts with '\t'\n" 14631 "};", 14632 Tab)); 14633 } 14634 14635 TEST_F(FormatTest, CalculatesOriginalColumn) { 14636 EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14637 "q\"; /* some\n" 14638 " comment */", 14639 format(" \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14640 "q\"; /* some\n" 14641 " comment */", 14642 getLLVMStyle())); 14643 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n" 14644 "/* some\n" 14645 " comment */", 14646 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n" 14647 " /* some\n" 14648 " comment */", 14649 getLLVMStyle())); 14650 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14651 "qqq\n" 14652 "/* some\n" 14653 " comment */", 14654 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14655 "qqq\n" 14656 " /* some\n" 14657 " comment */", 14658 getLLVMStyle())); 14659 EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14660 "wwww; /* some\n" 14661 " comment */", 14662 format(" inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14663 "wwww; /* some\n" 14664 " comment */", 14665 getLLVMStyle())); 14666 } 14667 14668 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) { 14669 FormatStyle NoSpace = getLLVMStyle(); 14670 NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never; 14671 14672 verifyFormat("while(true)\n" 14673 " continue;", 14674 NoSpace); 14675 verifyFormat("for(;;)\n" 14676 " continue;", 14677 NoSpace); 14678 verifyFormat("if(true)\n" 14679 " f();\n" 14680 "else if(true)\n" 14681 " f();", 14682 NoSpace); 14683 verifyFormat("do {\n" 14684 " do_something();\n" 14685 "} while(something());", 14686 NoSpace); 14687 verifyFormat("switch(x) {\n" 14688 "default:\n" 14689 " break;\n" 14690 "}", 14691 NoSpace); 14692 verifyFormat("auto i = std::make_unique<int>(5);", NoSpace); 14693 verifyFormat("size_t x = sizeof(x);", NoSpace); 14694 verifyFormat("auto f(int x) -> decltype(x);", NoSpace); 14695 verifyFormat("auto f(int x) -> typeof(x);", NoSpace); 14696 verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace); 14697 verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace); 14698 verifyFormat("int f(T x) noexcept(x.create());", NoSpace); 14699 verifyFormat("alignas(128) char a[128];", NoSpace); 14700 verifyFormat("size_t x = alignof(MyType);", NoSpace); 14701 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace); 14702 verifyFormat("int f() throw(Deprecated);", NoSpace); 14703 verifyFormat("typedef void (*cb)(int);", NoSpace); 14704 verifyFormat("T A::operator()();", NoSpace); 14705 verifyFormat("X A::operator++(T);", NoSpace); 14706 verifyFormat("auto lambda = []() { return 0; };", NoSpace); 14707 14708 FormatStyle Space = getLLVMStyle(); 14709 Space.SpaceBeforeParens = FormatStyle::SBPO_Always; 14710 14711 verifyFormat("int f ();", Space); 14712 verifyFormat("void f (int a, T b) {\n" 14713 " while (true)\n" 14714 " continue;\n" 14715 "}", 14716 Space); 14717 verifyFormat("if (true)\n" 14718 " f ();\n" 14719 "else if (true)\n" 14720 " f ();", 14721 Space); 14722 verifyFormat("do {\n" 14723 " do_something ();\n" 14724 "} while (something ());", 14725 Space); 14726 verifyFormat("switch (x) {\n" 14727 "default:\n" 14728 " break;\n" 14729 "}", 14730 Space); 14731 verifyFormat("A::A () : a (1) {}", Space); 14732 verifyFormat("void f () __attribute__ ((asdf));", Space); 14733 verifyFormat("*(&a + 1);\n" 14734 "&((&a)[1]);\n" 14735 "a[(b + c) * d];\n" 14736 "(((a + 1) * 2) + 3) * 4;", 14737 Space); 14738 verifyFormat("#define A(x) x", Space); 14739 verifyFormat("#define A (x) x", Space); 14740 verifyFormat("#if defined(x)\n" 14741 "#endif", 14742 Space); 14743 verifyFormat("auto i = std::make_unique<int> (5);", Space); 14744 verifyFormat("size_t x = sizeof (x);", Space); 14745 verifyFormat("auto f (int x) -> decltype (x);", Space); 14746 verifyFormat("auto f (int x) -> typeof (x);", Space); 14747 verifyFormat("auto f (int x) -> _Atomic (x);", Space); 14748 verifyFormat("auto f (int x) -> __underlying_type (x);", Space); 14749 verifyFormat("int f (T x) noexcept (x.create ());", Space); 14750 verifyFormat("alignas (128) char a[128];", Space); 14751 verifyFormat("size_t x = alignof (MyType);", Space); 14752 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space); 14753 verifyFormat("int f () throw (Deprecated);", Space); 14754 verifyFormat("typedef void (*cb) (int);", Space); 14755 // FIXME these tests regressed behaviour. 14756 // verifyFormat("T A::operator() ();", Space); 14757 // verifyFormat("X A::operator++ (T);", Space); 14758 verifyFormat("auto lambda = [] () { return 0; };", Space); 14759 verifyFormat("int x = int (y);", Space); 14760 14761 FormatStyle SomeSpace = getLLVMStyle(); 14762 SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses; 14763 14764 verifyFormat("[]() -> float {}", SomeSpace); 14765 verifyFormat("[] (auto foo) {}", SomeSpace); 14766 verifyFormat("[foo]() -> int {}", SomeSpace); 14767 verifyFormat("int f();", SomeSpace); 14768 verifyFormat("void f (int a, T b) {\n" 14769 " while (true)\n" 14770 " continue;\n" 14771 "}", 14772 SomeSpace); 14773 verifyFormat("if (true)\n" 14774 " f();\n" 14775 "else if (true)\n" 14776 " f();", 14777 SomeSpace); 14778 verifyFormat("do {\n" 14779 " do_something();\n" 14780 "} while (something());", 14781 SomeSpace); 14782 verifyFormat("switch (x) {\n" 14783 "default:\n" 14784 " break;\n" 14785 "}", 14786 SomeSpace); 14787 verifyFormat("A::A() : a (1) {}", SomeSpace); 14788 verifyFormat("void f() __attribute__ ((asdf));", SomeSpace); 14789 verifyFormat("*(&a + 1);\n" 14790 "&((&a)[1]);\n" 14791 "a[(b + c) * d];\n" 14792 "(((a + 1) * 2) + 3) * 4;", 14793 SomeSpace); 14794 verifyFormat("#define A(x) x", SomeSpace); 14795 verifyFormat("#define A (x) x", SomeSpace); 14796 verifyFormat("#if defined(x)\n" 14797 "#endif", 14798 SomeSpace); 14799 verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace); 14800 verifyFormat("size_t x = sizeof (x);", SomeSpace); 14801 verifyFormat("auto f (int x) -> decltype (x);", SomeSpace); 14802 verifyFormat("auto f (int x) -> typeof (x);", SomeSpace); 14803 verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace); 14804 verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace); 14805 verifyFormat("int f (T x) noexcept (x.create());", SomeSpace); 14806 verifyFormat("alignas (128) char a[128];", SomeSpace); 14807 verifyFormat("size_t x = alignof (MyType);", SomeSpace); 14808 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", 14809 SomeSpace); 14810 verifyFormat("int f() throw (Deprecated);", SomeSpace); 14811 verifyFormat("typedef void (*cb) (int);", SomeSpace); 14812 verifyFormat("T A::operator()();", SomeSpace); 14813 // FIXME these tests regressed behaviour. 14814 // verifyFormat("X A::operator++ (T);", SomeSpace); 14815 verifyFormat("int x = int (y);", SomeSpace); 14816 verifyFormat("auto lambda = []() { return 0; };", SomeSpace); 14817 14818 FormatStyle SpaceControlStatements = getLLVMStyle(); 14819 SpaceControlStatements.SpaceBeforeParens = FormatStyle::SBPO_Custom; 14820 SpaceControlStatements.SpaceBeforeParensOptions.AfterControlStatements = true; 14821 14822 verifyFormat("while (true)\n" 14823 " continue;", 14824 SpaceControlStatements); 14825 verifyFormat("if (true)\n" 14826 " f();\n" 14827 "else if (true)\n" 14828 " f();", 14829 SpaceControlStatements); 14830 verifyFormat("for (;;) {\n" 14831 " do_something();\n" 14832 "}", 14833 SpaceControlStatements); 14834 verifyFormat("do {\n" 14835 " do_something();\n" 14836 "} while (something());", 14837 SpaceControlStatements); 14838 verifyFormat("switch (x) {\n" 14839 "default:\n" 14840 " break;\n" 14841 "}", 14842 SpaceControlStatements); 14843 14844 FormatStyle SpaceFuncDecl = getLLVMStyle(); 14845 SpaceFuncDecl.SpaceBeforeParens = FormatStyle::SBPO_Custom; 14846 SpaceFuncDecl.SpaceBeforeParensOptions.AfterFunctionDeclarationName = true; 14847 14848 verifyFormat("int f ();", SpaceFuncDecl); 14849 verifyFormat("void f(int a, T b) {}", SpaceFuncDecl); 14850 verifyFormat("A::A() : a(1) {}", SpaceFuncDecl); 14851 verifyFormat("void f () __attribute__((asdf));", SpaceFuncDecl); 14852 verifyFormat("#define A(x) x", SpaceFuncDecl); 14853 verifyFormat("#define A (x) x", SpaceFuncDecl); 14854 verifyFormat("#if defined(x)\n" 14855 "#endif", 14856 SpaceFuncDecl); 14857 verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDecl); 14858 verifyFormat("size_t x = sizeof(x);", SpaceFuncDecl); 14859 verifyFormat("auto f (int x) -> decltype(x);", SpaceFuncDecl); 14860 verifyFormat("auto f (int x) -> typeof(x);", SpaceFuncDecl); 14861 verifyFormat("auto f (int x) -> _Atomic(x);", SpaceFuncDecl); 14862 verifyFormat("auto f (int x) -> __underlying_type(x);", SpaceFuncDecl); 14863 verifyFormat("int f (T x) noexcept(x.create());", SpaceFuncDecl); 14864 verifyFormat("alignas(128) char a[128];", SpaceFuncDecl); 14865 verifyFormat("size_t x = alignof(MyType);", SpaceFuncDecl); 14866 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", 14867 SpaceFuncDecl); 14868 verifyFormat("int f () throw(Deprecated);", SpaceFuncDecl); 14869 verifyFormat("typedef void (*cb)(int);", SpaceFuncDecl); 14870 // FIXME these tests regressed behaviour. 14871 // verifyFormat("T A::operator() ();", SpaceFuncDecl); 14872 // verifyFormat("X A::operator++ (T);", SpaceFuncDecl); 14873 verifyFormat("T A::operator()() {}", SpaceFuncDecl); 14874 verifyFormat("auto lambda = []() { return 0; };", SpaceFuncDecl); 14875 verifyFormat("int x = int(y);", SpaceFuncDecl); 14876 verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}", 14877 SpaceFuncDecl); 14878 14879 FormatStyle SpaceFuncDef = getLLVMStyle(); 14880 SpaceFuncDef.SpaceBeforeParens = FormatStyle::SBPO_Custom; 14881 SpaceFuncDef.SpaceBeforeParensOptions.AfterFunctionDefinitionName = true; 14882 14883 verifyFormat("int f();", SpaceFuncDef); 14884 verifyFormat("void f (int a, T b) {}", SpaceFuncDef); 14885 verifyFormat("A::A() : a(1) {}", SpaceFuncDef); 14886 verifyFormat("void f() __attribute__((asdf));", SpaceFuncDef); 14887 verifyFormat("#define A(x) x", SpaceFuncDef); 14888 verifyFormat("#define A (x) x", SpaceFuncDef); 14889 verifyFormat("#if defined(x)\n" 14890 "#endif", 14891 SpaceFuncDef); 14892 verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDef); 14893 verifyFormat("size_t x = sizeof(x);", SpaceFuncDef); 14894 verifyFormat("auto f(int x) -> decltype(x);", SpaceFuncDef); 14895 verifyFormat("auto f(int x) -> typeof(x);", SpaceFuncDef); 14896 verifyFormat("auto f(int x) -> _Atomic(x);", SpaceFuncDef); 14897 verifyFormat("auto f(int x) -> __underlying_type(x);", SpaceFuncDef); 14898 verifyFormat("int f(T x) noexcept(x.create());", SpaceFuncDef); 14899 verifyFormat("alignas(128) char a[128];", SpaceFuncDef); 14900 verifyFormat("size_t x = alignof(MyType);", SpaceFuncDef); 14901 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", 14902 SpaceFuncDef); 14903 verifyFormat("int f() throw(Deprecated);", SpaceFuncDef); 14904 verifyFormat("typedef void (*cb)(int);", SpaceFuncDef); 14905 verifyFormat("T A::operator()();", SpaceFuncDef); 14906 verifyFormat("X A::operator++(T);", SpaceFuncDef); 14907 // verifyFormat("T A::operator() () {}", SpaceFuncDef); 14908 verifyFormat("auto lambda = [] () { return 0; };", SpaceFuncDef); 14909 verifyFormat("int x = int(y);", SpaceFuncDef); 14910 verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}", 14911 SpaceFuncDef); 14912 14913 FormatStyle SpaceIfMacros = getLLVMStyle(); 14914 SpaceIfMacros.IfMacros.clear(); 14915 SpaceIfMacros.IfMacros.push_back("MYIF"); 14916 SpaceIfMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom; 14917 SpaceIfMacros.SpaceBeforeParensOptions.AfterIfMacros = true; 14918 verifyFormat("MYIF (a)\n return;", SpaceIfMacros); 14919 verifyFormat("MYIF (a)\n return;\nelse MYIF (b)\n return;", SpaceIfMacros); 14920 verifyFormat("MYIF (a)\n return;\nelse\n return;", SpaceIfMacros); 14921 14922 FormatStyle SpaceForeachMacros = getLLVMStyle(); 14923 EXPECT_EQ(SpaceForeachMacros.AllowShortBlocksOnASingleLine, 14924 FormatStyle::SBS_Never); 14925 EXPECT_EQ(SpaceForeachMacros.AllowShortLoopsOnASingleLine, false); 14926 SpaceForeachMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom; 14927 SpaceForeachMacros.SpaceBeforeParensOptions.AfterForeachMacros = true; 14928 verifyFormat("for (;;) {\n" 14929 "}", 14930 SpaceForeachMacros); 14931 verifyFormat("foreach (Item *item, itemlist) {\n" 14932 "}", 14933 SpaceForeachMacros); 14934 verifyFormat("Q_FOREACH (Item *item, itemlist) {\n" 14935 "}", 14936 SpaceForeachMacros); 14937 verifyFormat("BOOST_FOREACH (Item *item, itemlist) {\n" 14938 "}", 14939 SpaceForeachMacros); 14940 verifyFormat("UNKNOWN_FOREACH(Item *item, itemlist) {}", SpaceForeachMacros); 14941 14942 FormatStyle SomeSpace2 = getLLVMStyle(); 14943 SomeSpace2.SpaceBeforeParens = FormatStyle::SBPO_Custom; 14944 SomeSpace2.SpaceBeforeParensOptions.BeforeNonEmptyParentheses = true; 14945 verifyFormat("[]() -> float {}", SomeSpace2); 14946 verifyFormat("[] (auto foo) {}", SomeSpace2); 14947 verifyFormat("[foo]() -> int {}", SomeSpace2); 14948 verifyFormat("int f();", SomeSpace2); 14949 verifyFormat("void f (int a, T b) {\n" 14950 " while (true)\n" 14951 " continue;\n" 14952 "}", 14953 SomeSpace2); 14954 verifyFormat("if (true)\n" 14955 " f();\n" 14956 "else if (true)\n" 14957 " f();", 14958 SomeSpace2); 14959 verifyFormat("do {\n" 14960 " do_something();\n" 14961 "} while (something());", 14962 SomeSpace2); 14963 verifyFormat("switch (x) {\n" 14964 "default:\n" 14965 " break;\n" 14966 "}", 14967 SomeSpace2); 14968 verifyFormat("A::A() : a (1) {}", SomeSpace2); 14969 verifyFormat("void f() __attribute__ ((asdf));", SomeSpace2); 14970 verifyFormat("*(&a + 1);\n" 14971 "&((&a)[1]);\n" 14972 "a[(b + c) * d];\n" 14973 "(((a + 1) * 2) + 3) * 4;", 14974 SomeSpace2); 14975 verifyFormat("#define A(x) x", SomeSpace2); 14976 verifyFormat("#define A (x) x", SomeSpace2); 14977 verifyFormat("#if defined(x)\n" 14978 "#endif", 14979 SomeSpace2); 14980 verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace2); 14981 verifyFormat("size_t x = sizeof (x);", SomeSpace2); 14982 verifyFormat("auto f (int x) -> decltype (x);", SomeSpace2); 14983 verifyFormat("auto f (int x) -> typeof (x);", SomeSpace2); 14984 verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace2); 14985 verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace2); 14986 verifyFormat("int f (T x) noexcept (x.create());", SomeSpace2); 14987 verifyFormat("alignas (128) char a[128];", SomeSpace2); 14988 verifyFormat("size_t x = alignof (MyType);", SomeSpace2); 14989 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", 14990 SomeSpace2); 14991 verifyFormat("int f() throw (Deprecated);", SomeSpace2); 14992 verifyFormat("typedef void (*cb) (int);", SomeSpace2); 14993 verifyFormat("T A::operator()();", SomeSpace2); 14994 // verifyFormat("X A::operator++ (T);", SomeSpace2); 14995 verifyFormat("int x = int (y);", SomeSpace2); 14996 verifyFormat("auto lambda = []() { return 0; };", SomeSpace2); 14997 14998 FormatStyle SpaceAfterOverloadedOperator = getLLVMStyle(); 14999 SpaceAfterOverloadedOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15000 SpaceAfterOverloadedOperator.SpaceBeforeParensOptions 15001 .AfterOverloadedOperator = true; 15002 15003 verifyFormat("auto operator++ () -> int;", SpaceAfterOverloadedOperator); 15004 verifyFormat("X A::operator++ ();", SpaceAfterOverloadedOperator); 15005 verifyFormat("some_object.operator++ ();", SpaceAfterOverloadedOperator); 15006 verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator); 15007 15008 SpaceAfterOverloadedOperator.SpaceBeforeParensOptions 15009 .AfterOverloadedOperator = false; 15010 15011 verifyFormat("auto operator++() -> int;", SpaceAfterOverloadedOperator); 15012 verifyFormat("X A::operator++();", SpaceAfterOverloadedOperator); 15013 verifyFormat("some_object.operator++();", SpaceAfterOverloadedOperator); 15014 verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator); 15015 15016 auto SpaceAfterRequires = getLLVMStyle(); 15017 SpaceAfterRequires.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15018 EXPECT_FALSE( 15019 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause); 15020 EXPECT_FALSE( 15021 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression); 15022 verifyFormat("void f(auto x)\n" 15023 " requires requires(int i) { x + i; }\n" 15024 "{}", 15025 SpaceAfterRequires); 15026 verifyFormat("void f(auto x)\n" 15027 " requires(requires(int i) { x + i; })\n" 15028 "{}", 15029 SpaceAfterRequires); 15030 verifyFormat("if (requires(int i) { x + i; })\n" 15031 " return;", 15032 SpaceAfterRequires); 15033 verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires); 15034 verifyFormat("template <typename T>\n" 15035 " requires(Foo<T>)\n" 15036 "class Bar;", 15037 SpaceAfterRequires); 15038 15039 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true; 15040 verifyFormat("void f(auto x)\n" 15041 " requires requires(int i) { x + i; }\n" 15042 "{}", 15043 SpaceAfterRequires); 15044 verifyFormat("void f(auto x)\n" 15045 " requires (requires(int i) { x + i; })\n" 15046 "{}", 15047 SpaceAfterRequires); 15048 verifyFormat("if (requires(int i) { x + i; })\n" 15049 " return;", 15050 SpaceAfterRequires); 15051 verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires); 15052 verifyFormat("template <typename T>\n" 15053 " requires (Foo<T>)\n" 15054 "class Bar;", 15055 SpaceAfterRequires); 15056 15057 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = false; 15058 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression = true; 15059 verifyFormat("void f(auto x)\n" 15060 " requires requires (int i) { x + i; }\n" 15061 "{}", 15062 SpaceAfterRequires); 15063 verifyFormat("void f(auto x)\n" 15064 " requires(requires (int i) { x + i; })\n" 15065 "{}", 15066 SpaceAfterRequires); 15067 verifyFormat("if (requires (int i) { x + i; })\n" 15068 " return;", 15069 SpaceAfterRequires); 15070 verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires); 15071 verifyFormat("template <typename T>\n" 15072 " requires(Foo<T>)\n" 15073 "class Bar;", 15074 SpaceAfterRequires); 15075 15076 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true; 15077 verifyFormat("void f(auto x)\n" 15078 " requires requires (int i) { x + i; }\n" 15079 "{}", 15080 SpaceAfterRequires); 15081 verifyFormat("void f(auto x)\n" 15082 " requires (requires (int i) { x + i; })\n" 15083 "{}", 15084 SpaceAfterRequires); 15085 verifyFormat("if (requires (int i) { x + i; })\n" 15086 " return;", 15087 SpaceAfterRequires); 15088 verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires); 15089 verifyFormat("template <typename T>\n" 15090 " requires (Foo<T>)\n" 15091 "class Bar;", 15092 SpaceAfterRequires); 15093 } 15094 15095 TEST_F(FormatTest, SpaceAfterLogicalNot) { 15096 FormatStyle Spaces = getLLVMStyle(); 15097 Spaces.SpaceAfterLogicalNot = true; 15098 15099 verifyFormat("bool x = ! y", Spaces); 15100 verifyFormat("if (! isFailure())", Spaces); 15101 verifyFormat("if (! (a && b))", Spaces); 15102 verifyFormat("\"Error!\"", Spaces); 15103 verifyFormat("! ! x", Spaces); 15104 } 15105 15106 TEST_F(FormatTest, ConfigurableSpacesInParentheses) { 15107 FormatStyle Spaces = getLLVMStyle(); 15108 15109 Spaces.SpacesInParentheses = true; 15110 verifyFormat("do_something( ::globalVar );", Spaces); 15111 verifyFormat("call( x, y, z );", Spaces); 15112 verifyFormat("call();", Spaces); 15113 verifyFormat("std::function<void( int, int )> callback;", Spaces); 15114 verifyFormat("void inFunction() { std::function<void( int, int )> fct; }", 15115 Spaces); 15116 verifyFormat("while ( (bool)1 )\n" 15117 " continue;", 15118 Spaces); 15119 verifyFormat("for ( ;; )\n" 15120 " continue;", 15121 Spaces); 15122 verifyFormat("if ( true )\n" 15123 " f();\n" 15124 "else if ( true )\n" 15125 " f();", 15126 Spaces); 15127 verifyFormat("do {\n" 15128 " do_something( (int)i );\n" 15129 "} while ( something() );", 15130 Spaces); 15131 verifyFormat("switch ( x ) {\n" 15132 "default:\n" 15133 " break;\n" 15134 "}", 15135 Spaces); 15136 15137 Spaces.SpacesInParentheses = false; 15138 Spaces.SpacesInCStyleCastParentheses = true; 15139 verifyFormat("Type *A = ( Type * )P;", Spaces); 15140 verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces); 15141 verifyFormat("x = ( int32 )y;", Spaces); 15142 verifyFormat("int a = ( int )(2.0f);", Spaces); 15143 verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces); 15144 verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces); 15145 verifyFormat("#define x (( int )-1)", Spaces); 15146 15147 // Run the first set of tests again with: 15148 Spaces.SpacesInParentheses = false; 15149 Spaces.SpaceInEmptyParentheses = true; 15150 Spaces.SpacesInCStyleCastParentheses = true; 15151 verifyFormat("call(x, y, z);", Spaces); 15152 verifyFormat("call( );", Spaces); 15153 verifyFormat("std::function<void(int, int)> callback;", Spaces); 15154 verifyFormat("while (( bool )1)\n" 15155 " continue;", 15156 Spaces); 15157 verifyFormat("for (;;)\n" 15158 " continue;", 15159 Spaces); 15160 verifyFormat("if (true)\n" 15161 " f( );\n" 15162 "else if (true)\n" 15163 " f( );", 15164 Spaces); 15165 verifyFormat("do {\n" 15166 " do_something(( int )i);\n" 15167 "} while (something( ));", 15168 Spaces); 15169 verifyFormat("switch (x) {\n" 15170 "default:\n" 15171 " break;\n" 15172 "}", 15173 Spaces); 15174 15175 // Run the first set of tests again with: 15176 Spaces.SpaceAfterCStyleCast = true; 15177 verifyFormat("call(x, y, z);", Spaces); 15178 verifyFormat("call( );", Spaces); 15179 verifyFormat("std::function<void(int, int)> callback;", Spaces); 15180 verifyFormat("while (( bool ) 1)\n" 15181 " continue;", 15182 Spaces); 15183 verifyFormat("for (;;)\n" 15184 " continue;", 15185 Spaces); 15186 verifyFormat("if (true)\n" 15187 " f( );\n" 15188 "else if (true)\n" 15189 " f( );", 15190 Spaces); 15191 verifyFormat("do {\n" 15192 " do_something(( int ) i);\n" 15193 "} while (something( ));", 15194 Spaces); 15195 verifyFormat("switch (x) {\n" 15196 "default:\n" 15197 " break;\n" 15198 "}", 15199 Spaces); 15200 verifyFormat("#define CONF_BOOL(x) ( bool * ) ( void * ) (x)", Spaces); 15201 verifyFormat("#define CONF_BOOL(x) ( bool * ) (x)", Spaces); 15202 verifyFormat("#define CONF_BOOL(x) ( bool ) (x)", Spaces); 15203 verifyFormat("bool *y = ( bool * ) ( void * ) (x);", Spaces); 15204 verifyFormat("bool *y = ( bool * ) (x);", Spaces); 15205 15206 // Run subset of tests again with: 15207 Spaces.SpacesInCStyleCastParentheses = false; 15208 Spaces.SpaceAfterCStyleCast = true; 15209 verifyFormat("while ((bool) 1)\n" 15210 " continue;", 15211 Spaces); 15212 verifyFormat("do {\n" 15213 " do_something((int) i);\n" 15214 "} while (something( ));", 15215 Spaces); 15216 15217 verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces); 15218 verifyFormat("size_t idx = (size_t) a;", Spaces); 15219 verifyFormat("size_t idx = (size_t) (a - 1);", Spaces); 15220 verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces); 15221 verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces); 15222 verifyFormat("size_t idx = (*foo)(a - 1);", Spaces); 15223 verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces); 15224 verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (x)", Spaces); 15225 verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (int) (x)", Spaces); 15226 verifyFormat("bool *y = (bool *) (void *) (x);", Spaces); 15227 verifyFormat("bool *y = (bool *) (void *) (int) (x);", Spaces); 15228 verifyFormat("bool *y = (bool *) (void *) (int) foo(x);", Spaces); 15229 Spaces.ColumnLimit = 80; 15230 Spaces.IndentWidth = 4; 15231 Spaces.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 15232 verifyFormat("void foo( ) {\n" 15233 " size_t foo = (*(function))(\n" 15234 " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, " 15235 "BarrrrrrrrrrrrLong,\n" 15236 " FoooooooooLooooong);\n" 15237 "}", 15238 Spaces); 15239 Spaces.SpaceAfterCStyleCast = false; 15240 verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces); 15241 verifyFormat("size_t idx = (size_t)a;", Spaces); 15242 verifyFormat("size_t idx = (size_t)(a - 1);", Spaces); 15243 verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces); 15244 verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces); 15245 verifyFormat("size_t idx = (*foo)(a - 1);", Spaces); 15246 verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces); 15247 15248 verifyFormat("void foo( ) {\n" 15249 " size_t foo = (*(function))(\n" 15250 " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, " 15251 "BarrrrrrrrrrrrLong,\n" 15252 " FoooooooooLooooong);\n" 15253 "}", 15254 Spaces); 15255 } 15256 15257 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) { 15258 verifyFormat("int a[5];"); 15259 verifyFormat("a[3] += 42;"); 15260 15261 FormatStyle Spaces = getLLVMStyle(); 15262 Spaces.SpacesInSquareBrackets = true; 15263 // Not lambdas. 15264 verifyFormat("int a[ 5 ];", Spaces); 15265 verifyFormat("a[ 3 ] += 42;", Spaces); 15266 verifyFormat("constexpr char hello[]{\"hello\"};", Spaces); 15267 verifyFormat("double &operator[](int i) { return 0; }\n" 15268 "int i;", 15269 Spaces); 15270 verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces); 15271 verifyFormat("int i = a[ a ][ a ]->f();", Spaces); 15272 verifyFormat("int i = (*b)[ a ]->f();", Spaces); 15273 // Lambdas. 15274 verifyFormat("int c = []() -> int { return 2; }();\n", Spaces); 15275 verifyFormat("return [ i, args... ] {};", Spaces); 15276 verifyFormat("int foo = [ &bar ]() {};", Spaces); 15277 verifyFormat("int foo = [ = ]() {};", Spaces); 15278 verifyFormat("int foo = [ & ]() {};", Spaces); 15279 verifyFormat("int foo = [ =, &bar ]() {};", Spaces); 15280 verifyFormat("int foo = [ &bar, = ]() {};", Spaces); 15281 } 15282 15283 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) { 15284 FormatStyle NoSpaceStyle = getLLVMStyle(); 15285 verifyFormat("int a[5];", NoSpaceStyle); 15286 verifyFormat("a[3] += 42;", NoSpaceStyle); 15287 15288 verifyFormat("int a[1];", NoSpaceStyle); 15289 verifyFormat("int 1 [a];", NoSpaceStyle); 15290 verifyFormat("int a[1][2];", NoSpaceStyle); 15291 verifyFormat("a[7] = 5;", NoSpaceStyle); 15292 verifyFormat("int a = (f())[23];", NoSpaceStyle); 15293 verifyFormat("f([] {})", NoSpaceStyle); 15294 15295 FormatStyle Space = getLLVMStyle(); 15296 Space.SpaceBeforeSquareBrackets = true; 15297 verifyFormat("int c = []() -> int { return 2; }();\n", Space); 15298 verifyFormat("return [i, args...] {};", Space); 15299 15300 verifyFormat("int a [5];", Space); 15301 verifyFormat("a [3] += 42;", Space); 15302 verifyFormat("constexpr char hello []{\"hello\"};", Space); 15303 verifyFormat("double &operator[](int i) { return 0; }\n" 15304 "int i;", 15305 Space); 15306 verifyFormat("std::unique_ptr<int []> foo() {}", Space); 15307 verifyFormat("int i = a [a][a]->f();", Space); 15308 verifyFormat("int i = (*b) [a]->f();", Space); 15309 15310 verifyFormat("int a [1];", Space); 15311 verifyFormat("int 1 [a];", Space); 15312 verifyFormat("int a [1][2];", Space); 15313 verifyFormat("a [7] = 5;", Space); 15314 verifyFormat("int a = (f()) [23];", Space); 15315 verifyFormat("f([] {})", Space); 15316 } 15317 15318 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) { 15319 verifyFormat("int a = 5;"); 15320 verifyFormat("a += 42;"); 15321 verifyFormat("a or_eq 8;"); 15322 15323 FormatStyle Spaces = getLLVMStyle(); 15324 Spaces.SpaceBeforeAssignmentOperators = false; 15325 verifyFormat("int a= 5;", Spaces); 15326 verifyFormat("a+= 42;", Spaces); 15327 verifyFormat("a or_eq 8;", Spaces); 15328 } 15329 15330 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) { 15331 verifyFormat("class Foo : public Bar {};"); 15332 verifyFormat("Foo::Foo() : foo(1) {}"); 15333 verifyFormat("for (auto a : b) {\n}"); 15334 verifyFormat("int x = a ? b : c;"); 15335 verifyFormat("{\n" 15336 "label0:\n" 15337 " int x = 0;\n" 15338 "}"); 15339 verifyFormat("switch (x) {\n" 15340 "case 1:\n" 15341 "default:\n" 15342 "}"); 15343 verifyFormat("switch (allBraces) {\n" 15344 "case 1: {\n" 15345 " break;\n" 15346 "}\n" 15347 "case 2: {\n" 15348 " [[fallthrough]];\n" 15349 "}\n" 15350 "default: {\n" 15351 " break;\n" 15352 "}\n" 15353 "}"); 15354 15355 FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30); 15356 CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false; 15357 verifyFormat("class Foo : public Bar {};", CtorInitializerStyle); 15358 verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle); 15359 verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle); 15360 verifyFormat("int x = a ? b : c;", CtorInitializerStyle); 15361 verifyFormat("{\n" 15362 "label1:\n" 15363 " int x = 0;\n" 15364 "}", 15365 CtorInitializerStyle); 15366 verifyFormat("switch (x) {\n" 15367 "case 1:\n" 15368 "default:\n" 15369 "}", 15370 CtorInitializerStyle); 15371 verifyFormat("switch (allBraces) {\n" 15372 "case 1: {\n" 15373 " break;\n" 15374 "}\n" 15375 "case 2: {\n" 15376 " [[fallthrough]];\n" 15377 "}\n" 15378 "default: {\n" 15379 " break;\n" 15380 "}\n" 15381 "}", 15382 CtorInitializerStyle); 15383 CtorInitializerStyle.BreakConstructorInitializers = 15384 FormatStyle::BCIS_AfterColon; 15385 verifyFormat("Fooooooooooo::Fooooooooooo():\n" 15386 " aaaaaaaaaaaaaaaa(1),\n" 15387 " bbbbbbbbbbbbbbbb(2) {}", 15388 CtorInitializerStyle); 15389 CtorInitializerStyle.BreakConstructorInitializers = 15390 FormatStyle::BCIS_BeforeComma; 15391 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15392 " : aaaaaaaaaaaaaaaa(1)\n" 15393 " , bbbbbbbbbbbbbbbb(2) {}", 15394 CtorInitializerStyle); 15395 CtorInitializerStyle.BreakConstructorInitializers = 15396 FormatStyle::BCIS_BeforeColon; 15397 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15398 " : aaaaaaaaaaaaaaaa(1),\n" 15399 " bbbbbbbbbbbbbbbb(2) {}", 15400 CtorInitializerStyle); 15401 CtorInitializerStyle.ConstructorInitializerIndentWidth = 0; 15402 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15403 ": aaaaaaaaaaaaaaaa(1),\n" 15404 " bbbbbbbbbbbbbbbb(2) {}", 15405 CtorInitializerStyle); 15406 15407 FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30); 15408 InheritanceStyle.SpaceBeforeInheritanceColon = false; 15409 verifyFormat("class Foo: public Bar {};", InheritanceStyle); 15410 verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle); 15411 verifyFormat("for (auto a : b) {\n}", InheritanceStyle); 15412 verifyFormat("int x = a ? b : c;", InheritanceStyle); 15413 verifyFormat("{\n" 15414 "label2:\n" 15415 " int x = 0;\n" 15416 "}", 15417 InheritanceStyle); 15418 verifyFormat("switch (x) {\n" 15419 "case 1:\n" 15420 "default:\n" 15421 "}", 15422 InheritanceStyle); 15423 verifyFormat("switch (allBraces) {\n" 15424 "case 1: {\n" 15425 " break;\n" 15426 "}\n" 15427 "case 2: {\n" 15428 " [[fallthrough]];\n" 15429 "}\n" 15430 "default: {\n" 15431 " break;\n" 15432 "}\n" 15433 "}", 15434 InheritanceStyle); 15435 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterComma; 15436 verifyFormat("class Foooooooooooooooooooooo\n" 15437 " : public aaaaaaaaaaaaaaaaaa,\n" 15438 " public bbbbbbbbbbbbbbbbbb {\n" 15439 "}", 15440 InheritanceStyle); 15441 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon; 15442 verifyFormat("class Foooooooooooooooooooooo:\n" 15443 " public aaaaaaaaaaaaaaaaaa,\n" 15444 " public bbbbbbbbbbbbbbbbbb {\n" 15445 "}", 15446 InheritanceStyle); 15447 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma; 15448 verifyFormat("class Foooooooooooooooooooooo\n" 15449 " : public aaaaaaaaaaaaaaaaaa\n" 15450 " , public bbbbbbbbbbbbbbbbbb {\n" 15451 "}", 15452 InheritanceStyle); 15453 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 15454 verifyFormat("class Foooooooooooooooooooooo\n" 15455 " : public aaaaaaaaaaaaaaaaaa,\n" 15456 " public bbbbbbbbbbbbbbbbbb {\n" 15457 "}", 15458 InheritanceStyle); 15459 InheritanceStyle.ConstructorInitializerIndentWidth = 0; 15460 verifyFormat("class Foooooooooooooooooooooo\n" 15461 ": public aaaaaaaaaaaaaaaaaa,\n" 15462 " public bbbbbbbbbbbbbbbbbb {}", 15463 InheritanceStyle); 15464 15465 FormatStyle ForLoopStyle = getLLVMStyle(); 15466 ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false; 15467 verifyFormat("class Foo : public Bar {};", ForLoopStyle); 15468 verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle); 15469 verifyFormat("for (auto a: b) {\n}", ForLoopStyle); 15470 verifyFormat("int x = a ? b : c;", ForLoopStyle); 15471 verifyFormat("{\n" 15472 "label2:\n" 15473 " int x = 0;\n" 15474 "}", 15475 ForLoopStyle); 15476 verifyFormat("switch (x) {\n" 15477 "case 1:\n" 15478 "default:\n" 15479 "}", 15480 ForLoopStyle); 15481 verifyFormat("switch (allBraces) {\n" 15482 "case 1: {\n" 15483 " break;\n" 15484 "}\n" 15485 "case 2: {\n" 15486 " [[fallthrough]];\n" 15487 "}\n" 15488 "default: {\n" 15489 " break;\n" 15490 "}\n" 15491 "}", 15492 ForLoopStyle); 15493 15494 FormatStyle CaseStyle = getLLVMStyle(); 15495 CaseStyle.SpaceBeforeCaseColon = true; 15496 verifyFormat("class Foo : public Bar {};", CaseStyle); 15497 verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle); 15498 verifyFormat("for (auto a : b) {\n}", CaseStyle); 15499 verifyFormat("int x = a ? b : c;", CaseStyle); 15500 verifyFormat("switch (x) {\n" 15501 "case 1 :\n" 15502 "default :\n" 15503 "}", 15504 CaseStyle); 15505 verifyFormat("switch (allBraces) {\n" 15506 "case 1 : {\n" 15507 " break;\n" 15508 "}\n" 15509 "case 2 : {\n" 15510 " [[fallthrough]];\n" 15511 "}\n" 15512 "default : {\n" 15513 " break;\n" 15514 "}\n" 15515 "}", 15516 CaseStyle); 15517 15518 FormatStyle NoSpaceStyle = getLLVMStyle(); 15519 EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false); 15520 NoSpaceStyle.SpaceBeforeCtorInitializerColon = false; 15521 NoSpaceStyle.SpaceBeforeInheritanceColon = false; 15522 NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false; 15523 verifyFormat("class Foo: public Bar {};", NoSpaceStyle); 15524 verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle); 15525 verifyFormat("for (auto a: b) {\n}", NoSpaceStyle); 15526 verifyFormat("int x = a ? b : c;", NoSpaceStyle); 15527 verifyFormat("{\n" 15528 "label3:\n" 15529 " int x = 0;\n" 15530 "}", 15531 NoSpaceStyle); 15532 verifyFormat("switch (x) {\n" 15533 "case 1:\n" 15534 "default:\n" 15535 "}", 15536 NoSpaceStyle); 15537 verifyFormat("switch (allBraces) {\n" 15538 "case 1: {\n" 15539 " break;\n" 15540 "}\n" 15541 "case 2: {\n" 15542 " [[fallthrough]];\n" 15543 "}\n" 15544 "default: {\n" 15545 " break;\n" 15546 "}\n" 15547 "}", 15548 NoSpaceStyle); 15549 15550 FormatStyle InvertedSpaceStyle = getLLVMStyle(); 15551 InvertedSpaceStyle.SpaceBeforeCaseColon = true; 15552 InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false; 15553 InvertedSpaceStyle.SpaceBeforeInheritanceColon = false; 15554 InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false; 15555 verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle); 15556 verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle); 15557 verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle); 15558 verifyFormat("int x = a ? b : c;", InvertedSpaceStyle); 15559 verifyFormat("{\n" 15560 "label3:\n" 15561 " int x = 0;\n" 15562 "}", 15563 InvertedSpaceStyle); 15564 verifyFormat("switch (x) {\n" 15565 "case 1 :\n" 15566 "case 2 : {\n" 15567 " break;\n" 15568 "}\n" 15569 "default :\n" 15570 " break;\n" 15571 "}", 15572 InvertedSpaceStyle); 15573 verifyFormat("switch (allBraces) {\n" 15574 "case 1 : {\n" 15575 " break;\n" 15576 "}\n" 15577 "case 2 : {\n" 15578 " [[fallthrough]];\n" 15579 "}\n" 15580 "default : {\n" 15581 " break;\n" 15582 "}\n" 15583 "}", 15584 InvertedSpaceStyle); 15585 } 15586 15587 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) { 15588 FormatStyle Style = getLLVMStyle(); 15589 15590 Style.PointerAlignment = FormatStyle::PAS_Left; 15591 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default; 15592 verifyFormat("void* const* x = NULL;", Style); 15593 15594 #define verifyQualifierSpaces(Code, Pointers, Qualifiers) \ 15595 do { \ 15596 Style.PointerAlignment = FormatStyle::Pointers; \ 15597 Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers; \ 15598 verifyFormat(Code, Style); \ 15599 } while (false) 15600 15601 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default); 15602 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default); 15603 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default); 15604 15605 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before); 15606 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before); 15607 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before); 15608 15609 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After); 15610 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After); 15611 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After); 15612 15613 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both); 15614 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both); 15615 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both); 15616 15617 verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default); 15618 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, 15619 SAPQ_Default); 15620 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15621 SAPQ_Default); 15622 15623 verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before); 15624 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, 15625 SAPQ_Before); 15626 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15627 SAPQ_Before); 15628 15629 verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After); 15630 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After); 15631 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15632 SAPQ_After); 15633 15634 verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both); 15635 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both); 15636 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both); 15637 15638 #undef verifyQualifierSpaces 15639 15640 FormatStyle Spaces = getLLVMStyle(); 15641 Spaces.AttributeMacros.push_back("qualified"); 15642 Spaces.PointerAlignment = FormatStyle::PAS_Right; 15643 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default; 15644 verifyFormat("SomeType *volatile *a = NULL;", Spaces); 15645 verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces); 15646 verifyFormat("std::vector<SomeType *const *> x;", Spaces); 15647 verifyFormat("std::vector<SomeType *qualified *> x;", Spaces); 15648 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15649 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before; 15650 verifyFormat("SomeType * volatile *a = NULL;", Spaces); 15651 verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces); 15652 verifyFormat("std::vector<SomeType * const *> x;", Spaces); 15653 verifyFormat("std::vector<SomeType * qualified *> x;", Spaces); 15654 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15655 15656 // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left. 15657 Spaces.PointerAlignment = FormatStyle::PAS_Left; 15658 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before; 15659 verifyFormat("SomeType* volatile* a = NULL;", Spaces); 15660 verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces); 15661 verifyFormat("std::vector<SomeType* const*> x;", Spaces); 15662 verifyFormat("std::vector<SomeType* qualified*> x;", Spaces); 15663 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15664 // However, setting it to SAPQ_After should add spaces after __attribute, etc. 15665 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After; 15666 verifyFormat("SomeType* volatile * a = NULL;", Spaces); 15667 verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces); 15668 verifyFormat("std::vector<SomeType* const *> x;", Spaces); 15669 verifyFormat("std::vector<SomeType* qualified *> x;", Spaces); 15670 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15671 15672 // PAS_Middle should not have any noticeable changes even for SAPQ_Both 15673 Spaces.PointerAlignment = FormatStyle::PAS_Middle; 15674 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After; 15675 verifyFormat("SomeType * volatile * a = NULL;", Spaces); 15676 verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces); 15677 verifyFormat("std::vector<SomeType * const *> x;", Spaces); 15678 verifyFormat("std::vector<SomeType * qualified *> x;", Spaces); 15679 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15680 } 15681 15682 TEST_F(FormatTest, AlignConsecutiveMacros) { 15683 FormatStyle Style = getLLVMStyle(); 15684 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 15685 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 15686 Style.AlignConsecutiveMacros = FormatStyle::ACS_None; 15687 15688 verifyFormat("#define a 3\n" 15689 "#define bbbb 4\n" 15690 "#define ccc (5)", 15691 Style); 15692 15693 verifyFormat("#define f(x) (x * x)\n" 15694 "#define fff(x, y, z) (x * y + z)\n" 15695 "#define ffff(x, y) (x - y)", 15696 Style); 15697 15698 verifyFormat("#define foo(x, y) (x + y)\n" 15699 "#define bar (5, 6)(2 + 2)", 15700 Style); 15701 15702 verifyFormat("#define a 3\n" 15703 "#define bbbb 4\n" 15704 "#define ccc (5)\n" 15705 "#define f(x) (x * x)\n" 15706 "#define fff(x, y, z) (x * y + z)\n" 15707 "#define ffff(x, y) (x - y)", 15708 Style); 15709 15710 Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 15711 verifyFormat("#define a 3\n" 15712 "#define bbbb 4\n" 15713 "#define ccc (5)", 15714 Style); 15715 15716 verifyFormat("#define f(x) (x * x)\n" 15717 "#define fff(x, y, z) (x * y + z)\n" 15718 "#define ffff(x, y) (x - y)", 15719 Style); 15720 15721 verifyFormat("#define foo(x, y) (x + y)\n" 15722 "#define bar (5, 6)(2 + 2)", 15723 Style); 15724 15725 verifyFormat("#define a 3\n" 15726 "#define bbbb 4\n" 15727 "#define ccc (5)\n" 15728 "#define f(x) (x * x)\n" 15729 "#define fff(x, y, z) (x * y + z)\n" 15730 "#define ffff(x, y) (x - y)", 15731 Style); 15732 15733 verifyFormat("#define a 5\n" 15734 "#define foo(x, y) (x + y)\n" 15735 "#define CCC (6)\n" 15736 "auto lambda = []() {\n" 15737 " auto ii = 0;\n" 15738 " float j = 0;\n" 15739 " return 0;\n" 15740 "};\n" 15741 "int i = 0;\n" 15742 "float i2 = 0;\n" 15743 "auto v = type{\n" 15744 " i = 1, //\n" 15745 " (i = 2), //\n" 15746 " i = 3 //\n" 15747 "};", 15748 Style); 15749 15750 Style.AlignConsecutiveMacros = FormatStyle::ACS_None; 15751 Style.ColumnLimit = 20; 15752 15753 verifyFormat("#define a \\\n" 15754 " \"aabbbbbbbbbbbb\"\n" 15755 "#define D \\\n" 15756 " \"aabbbbbbbbbbbb\" \\\n" 15757 " \"ccddeeeeeeeee\"\n" 15758 "#define B \\\n" 15759 " \"QQQQQQQQQQQQQ\" \\\n" 15760 " \"FFFFFFFFFFFFF\" \\\n" 15761 " \"LLLLLLLL\"\n", 15762 Style); 15763 15764 Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 15765 verifyFormat("#define a \\\n" 15766 " \"aabbbbbbbbbbbb\"\n" 15767 "#define D \\\n" 15768 " \"aabbbbbbbbbbbb\" \\\n" 15769 " \"ccddeeeeeeeee\"\n" 15770 "#define B \\\n" 15771 " \"QQQQQQQQQQQQQ\" \\\n" 15772 " \"FFFFFFFFFFFFF\" \\\n" 15773 " \"LLLLLLLL\"\n", 15774 Style); 15775 15776 // Test across comments 15777 Style.MaxEmptyLinesToKeep = 10; 15778 Style.ReflowComments = false; 15779 Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossComments; 15780 EXPECT_EQ("#define a 3\n" 15781 "// line comment\n" 15782 "#define bbbb 4\n" 15783 "#define ccc (5)", 15784 format("#define a 3\n" 15785 "// line comment\n" 15786 "#define bbbb 4\n" 15787 "#define ccc (5)", 15788 Style)); 15789 15790 EXPECT_EQ("#define a 3\n" 15791 "/* block comment */\n" 15792 "#define bbbb 4\n" 15793 "#define ccc (5)", 15794 format("#define a 3\n" 15795 "/* block comment */\n" 15796 "#define bbbb 4\n" 15797 "#define ccc (5)", 15798 Style)); 15799 15800 EXPECT_EQ("#define a 3\n" 15801 "/* multi-line *\n" 15802 " * block comment */\n" 15803 "#define bbbb 4\n" 15804 "#define ccc (5)", 15805 format("#define a 3\n" 15806 "/* multi-line *\n" 15807 " * block comment */\n" 15808 "#define bbbb 4\n" 15809 "#define ccc (5)", 15810 Style)); 15811 15812 EXPECT_EQ("#define a 3\n" 15813 "// multi-line line comment\n" 15814 "//\n" 15815 "#define bbbb 4\n" 15816 "#define ccc (5)", 15817 format("#define a 3\n" 15818 "// multi-line line comment\n" 15819 "//\n" 15820 "#define bbbb 4\n" 15821 "#define ccc (5)", 15822 Style)); 15823 15824 EXPECT_EQ("#define a 3\n" 15825 "// empty lines still break.\n" 15826 "\n" 15827 "#define bbbb 4\n" 15828 "#define ccc (5)", 15829 format("#define a 3\n" 15830 "// empty lines still break.\n" 15831 "\n" 15832 "#define bbbb 4\n" 15833 "#define ccc (5)", 15834 Style)); 15835 15836 // Test across empty lines 15837 Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLines; 15838 EXPECT_EQ("#define a 3\n" 15839 "\n" 15840 "#define bbbb 4\n" 15841 "#define ccc (5)", 15842 format("#define a 3\n" 15843 "\n" 15844 "#define bbbb 4\n" 15845 "#define ccc (5)", 15846 Style)); 15847 15848 EXPECT_EQ("#define a 3\n" 15849 "\n" 15850 "\n" 15851 "\n" 15852 "#define bbbb 4\n" 15853 "#define ccc (5)", 15854 format("#define a 3\n" 15855 "\n" 15856 "\n" 15857 "\n" 15858 "#define bbbb 4\n" 15859 "#define ccc (5)", 15860 Style)); 15861 15862 EXPECT_EQ("#define a 3\n" 15863 "// comments should break alignment\n" 15864 "//\n" 15865 "#define bbbb 4\n" 15866 "#define ccc (5)", 15867 format("#define a 3\n" 15868 "// comments should break alignment\n" 15869 "//\n" 15870 "#define bbbb 4\n" 15871 "#define ccc (5)", 15872 Style)); 15873 15874 // Test across empty lines and comments 15875 Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLinesAndComments; 15876 verifyFormat("#define a 3\n" 15877 "\n" 15878 "// line comment\n" 15879 "#define bbbb 4\n" 15880 "#define ccc (5)", 15881 Style); 15882 15883 EXPECT_EQ("#define a 3\n" 15884 "\n" 15885 "\n" 15886 "/* multi-line *\n" 15887 " * block comment */\n" 15888 "\n" 15889 "\n" 15890 "#define bbbb 4\n" 15891 "#define ccc (5)", 15892 format("#define a 3\n" 15893 "\n" 15894 "\n" 15895 "/* multi-line *\n" 15896 " * block comment */\n" 15897 "\n" 15898 "\n" 15899 "#define bbbb 4\n" 15900 "#define ccc (5)", 15901 Style)); 15902 15903 EXPECT_EQ("#define a 3\n" 15904 "\n" 15905 "\n" 15906 "/* multi-line *\n" 15907 " * block comment */\n" 15908 "\n" 15909 "\n" 15910 "#define bbbb 4\n" 15911 "#define ccc (5)", 15912 format("#define a 3\n" 15913 "\n" 15914 "\n" 15915 "/* multi-line *\n" 15916 " * block comment */\n" 15917 "\n" 15918 "\n" 15919 "#define bbbb 4\n" 15920 "#define ccc (5)", 15921 Style)); 15922 } 15923 15924 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) { 15925 FormatStyle Alignment = getLLVMStyle(); 15926 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 15927 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossEmptyLines; 15928 15929 Alignment.MaxEmptyLinesToKeep = 10; 15930 /* Test alignment across empty lines */ 15931 EXPECT_EQ("int a = 5;\n" 15932 "\n" 15933 "int oneTwoThree = 123;", 15934 format("int a = 5;\n" 15935 "\n" 15936 "int oneTwoThree= 123;", 15937 Alignment)); 15938 EXPECT_EQ("int a = 5;\n" 15939 "int one = 1;\n" 15940 "\n" 15941 "int oneTwoThree = 123;", 15942 format("int a = 5;\n" 15943 "int one = 1;\n" 15944 "\n" 15945 "int oneTwoThree = 123;", 15946 Alignment)); 15947 EXPECT_EQ("int a = 5;\n" 15948 "int one = 1;\n" 15949 "\n" 15950 "int oneTwoThree = 123;\n" 15951 "int oneTwo = 12;", 15952 format("int a = 5;\n" 15953 "int one = 1;\n" 15954 "\n" 15955 "int oneTwoThree = 123;\n" 15956 "int oneTwo = 12;", 15957 Alignment)); 15958 15959 /* Test across comments */ 15960 EXPECT_EQ("int a = 5;\n" 15961 "/* block comment */\n" 15962 "int oneTwoThree = 123;", 15963 format("int a = 5;\n" 15964 "/* block comment */\n" 15965 "int oneTwoThree=123;", 15966 Alignment)); 15967 15968 EXPECT_EQ("int a = 5;\n" 15969 "// line comment\n" 15970 "int oneTwoThree = 123;", 15971 format("int a = 5;\n" 15972 "// line comment\n" 15973 "int oneTwoThree=123;", 15974 Alignment)); 15975 15976 /* Test across comments and newlines */ 15977 EXPECT_EQ("int a = 5;\n" 15978 "\n" 15979 "/* block comment */\n" 15980 "int oneTwoThree = 123;", 15981 format("int a = 5;\n" 15982 "\n" 15983 "/* block comment */\n" 15984 "int oneTwoThree=123;", 15985 Alignment)); 15986 15987 EXPECT_EQ("int a = 5;\n" 15988 "\n" 15989 "// line comment\n" 15990 "int oneTwoThree = 123;", 15991 format("int a = 5;\n" 15992 "\n" 15993 "// line comment\n" 15994 "int oneTwoThree=123;", 15995 Alignment)); 15996 } 15997 15998 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) { 15999 FormatStyle Alignment = getLLVMStyle(); 16000 Alignment.AlignConsecutiveDeclarations = 16001 FormatStyle::ACS_AcrossEmptyLinesAndComments; 16002 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 16003 16004 Alignment.MaxEmptyLinesToKeep = 10; 16005 /* Test alignment across empty lines */ 16006 EXPECT_EQ("int a = 5;\n" 16007 "\n" 16008 "float const oneTwoThree = 123;", 16009 format("int a = 5;\n" 16010 "\n" 16011 "float const oneTwoThree = 123;", 16012 Alignment)); 16013 EXPECT_EQ("int a = 5;\n" 16014 "float const one = 1;\n" 16015 "\n" 16016 "int oneTwoThree = 123;", 16017 format("int a = 5;\n" 16018 "float const one = 1;\n" 16019 "\n" 16020 "int oneTwoThree = 123;", 16021 Alignment)); 16022 16023 /* Test across comments */ 16024 EXPECT_EQ("float const a = 5;\n" 16025 "/* block comment */\n" 16026 "int oneTwoThree = 123;", 16027 format("float const a = 5;\n" 16028 "/* block comment */\n" 16029 "int oneTwoThree=123;", 16030 Alignment)); 16031 16032 EXPECT_EQ("float const a = 5;\n" 16033 "// line comment\n" 16034 "int oneTwoThree = 123;", 16035 format("float const a = 5;\n" 16036 "// line comment\n" 16037 "int oneTwoThree=123;", 16038 Alignment)); 16039 16040 /* Test across comments and newlines */ 16041 EXPECT_EQ("float const a = 5;\n" 16042 "\n" 16043 "/* block comment */\n" 16044 "int oneTwoThree = 123;", 16045 format("float const a = 5;\n" 16046 "\n" 16047 "/* block comment */\n" 16048 "int oneTwoThree=123;", 16049 Alignment)); 16050 16051 EXPECT_EQ("float const a = 5;\n" 16052 "\n" 16053 "// line comment\n" 16054 "int oneTwoThree = 123;", 16055 format("float const a = 5;\n" 16056 "\n" 16057 "// line comment\n" 16058 "int oneTwoThree=123;", 16059 Alignment)); 16060 } 16061 16062 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) { 16063 FormatStyle Alignment = getLLVMStyle(); 16064 Alignment.AlignConsecutiveBitFields = 16065 FormatStyle::ACS_AcrossEmptyLinesAndComments; 16066 16067 Alignment.MaxEmptyLinesToKeep = 10; 16068 /* Test alignment across empty lines */ 16069 EXPECT_EQ("int a : 5;\n" 16070 "\n" 16071 "int longbitfield : 6;", 16072 format("int a : 5;\n" 16073 "\n" 16074 "int longbitfield : 6;", 16075 Alignment)); 16076 EXPECT_EQ("int a : 5;\n" 16077 "int one : 1;\n" 16078 "\n" 16079 "int longbitfield : 6;", 16080 format("int a : 5;\n" 16081 "int one : 1;\n" 16082 "\n" 16083 "int longbitfield : 6;", 16084 Alignment)); 16085 16086 /* Test across comments */ 16087 EXPECT_EQ("int a : 5;\n" 16088 "/* block comment */\n" 16089 "int longbitfield : 6;", 16090 format("int a : 5;\n" 16091 "/* block comment */\n" 16092 "int longbitfield : 6;", 16093 Alignment)); 16094 EXPECT_EQ("int a : 5;\n" 16095 "int one : 1;\n" 16096 "// line comment\n" 16097 "int longbitfield : 6;", 16098 format("int a : 5;\n" 16099 "int one : 1;\n" 16100 "// line comment\n" 16101 "int longbitfield : 6;", 16102 Alignment)); 16103 16104 /* Test across comments and newlines */ 16105 EXPECT_EQ("int a : 5;\n" 16106 "/* block comment */\n" 16107 "\n" 16108 "int longbitfield : 6;", 16109 format("int a : 5;\n" 16110 "/* block comment */\n" 16111 "\n" 16112 "int longbitfield : 6;", 16113 Alignment)); 16114 EXPECT_EQ("int a : 5;\n" 16115 "int one : 1;\n" 16116 "\n" 16117 "// line comment\n" 16118 "\n" 16119 "int longbitfield : 6;", 16120 format("int a : 5;\n" 16121 "int one : 1;\n" 16122 "\n" 16123 "// line comment \n" 16124 "\n" 16125 "int longbitfield : 6;", 16126 Alignment)); 16127 } 16128 16129 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) { 16130 FormatStyle Alignment = getLLVMStyle(); 16131 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 16132 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossComments; 16133 16134 Alignment.MaxEmptyLinesToKeep = 10; 16135 /* Test alignment across empty lines */ 16136 EXPECT_EQ("int a = 5;\n" 16137 "\n" 16138 "int oneTwoThree = 123;", 16139 format("int a = 5;\n" 16140 "\n" 16141 "int oneTwoThree= 123;", 16142 Alignment)); 16143 EXPECT_EQ("int a = 5;\n" 16144 "int one = 1;\n" 16145 "\n" 16146 "int oneTwoThree = 123;", 16147 format("int a = 5;\n" 16148 "int one = 1;\n" 16149 "\n" 16150 "int oneTwoThree = 123;", 16151 Alignment)); 16152 16153 /* Test across comments */ 16154 EXPECT_EQ("int a = 5;\n" 16155 "/* block comment */\n" 16156 "int oneTwoThree = 123;", 16157 format("int a = 5;\n" 16158 "/* block comment */\n" 16159 "int oneTwoThree=123;", 16160 Alignment)); 16161 16162 EXPECT_EQ("int a = 5;\n" 16163 "// line comment\n" 16164 "int oneTwoThree = 123;", 16165 format("int a = 5;\n" 16166 "// line comment\n" 16167 "int oneTwoThree=123;", 16168 Alignment)); 16169 16170 EXPECT_EQ("int a = 5;\n" 16171 "/*\n" 16172 " * multi-line block comment\n" 16173 " */\n" 16174 "int oneTwoThree = 123;", 16175 format("int a = 5;\n" 16176 "/*\n" 16177 " * multi-line block comment\n" 16178 " */\n" 16179 "int oneTwoThree=123;", 16180 Alignment)); 16181 16182 EXPECT_EQ("int a = 5;\n" 16183 "//\n" 16184 "// multi-line line comment\n" 16185 "//\n" 16186 "int oneTwoThree = 123;", 16187 format("int a = 5;\n" 16188 "//\n" 16189 "// multi-line line comment\n" 16190 "//\n" 16191 "int oneTwoThree=123;", 16192 Alignment)); 16193 16194 /* Test across comments and newlines */ 16195 EXPECT_EQ("int a = 5;\n" 16196 "\n" 16197 "/* block comment */\n" 16198 "int oneTwoThree = 123;", 16199 format("int a = 5;\n" 16200 "\n" 16201 "/* block comment */\n" 16202 "int oneTwoThree=123;", 16203 Alignment)); 16204 16205 EXPECT_EQ("int a = 5;\n" 16206 "\n" 16207 "// line comment\n" 16208 "int oneTwoThree = 123;", 16209 format("int a = 5;\n" 16210 "\n" 16211 "// line comment\n" 16212 "int oneTwoThree=123;", 16213 Alignment)); 16214 } 16215 16216 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) { 16217 FormatStyle Alignment = getLLVMStyle(); 16218 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 16219 Alignment.AlignConsecutiveAssignments = 16220 FormatStyle::ACS_AcrossEmptyLinesAndComments; 16221 verifyFormat("int a = 5;\n" 16222 "int oneTwoThree = 123;", 16223 Alignment); 16224 verifyFormat("int a = method();\n" 16225 "int oneTwoThree = 133;", 16226 Alignment); 16227 verifyFormat("a &= 5;\n" 16228 "bcd *= 5;\n" 16229 "ghtyf += 5;\n" 16230 "dvfvdb -= 5;\n" 16231 "a /= 5;\n" 16232 "vdsvsv %= 5;\n" 16233 "sfdbddfbdfbb ^= 5;\n" 16234 "dvsdsv |= 5;\n" 16235 "int dsvvdvsdvvv = 123;", 16236 Alignment); 16237 verifyFormat("int i = 1, j = 10;\n" 16238 "something = 2000;", 16239 Alignment); 16240 verifyFormat("something = 2000;\n" 16241 "int i = 1, j = 10;\n", 16242 Alignment); 16243 verifyFormat("something = 2000;\n" 16244 "another = 911;\n" 16245 "int i = 1, j = 10;\n" 16246 "oneMore = 1;\n" 16247 "i = 2;", 16248 Alignment); 16249 verifyFormat("int a = 5;\n" 16250 "int one = 1;\n" 16251 "method();\n" 16252 "int oneTwoThree = 123;\n" 16253 "int oneTwo = 12;", 16254 Alignment); 16255 verifyFormat("int oneTwoThree = 123;\n" 16256 "int oneTwo = 12;\n" 16257 "method();\n", 16258 Alignment); 16259 verifyFormat("int oneTwoThree = 123; // comment\n" 16260 "int oneTwo = 12; // comment", 16261 Alignment); 16262 16263 // Bug 25167 16264 /* Uncomment when fixed 16265 verifyFormat("#if A\n" 16266 "#else\n" 16267 "int aaaaaaaa = 12;\n" 16268 "#endif\n" 16269 "#if B\n" 16270 "#else\n" 16271 "int a = 12;\n" 16272 "#endif\n", 16273 Alignment); 16274 verifyFormat("enum foo {\n" 16275 "#if A\n" 16276 "#else\n" 16277 " aaaaaaaa = 12;\n" 16278 "#endif\n" 16279 "#if B\n" 16280 "#else\n" 16281 " a = 12;\n" 16282 "#endif\n" 16283 "};\n", 16284 Alignment); 16285 */ 16286 16287 Alignment.MaxEmptyLinesToKeep = 10; 16288 /* Test alignment across empty lines */ 16289 EXPECT_EQ("int a = 5;\n" 16290 "\n" 16291 "int oneTwoThree = 123;", 16292 format("int a = 5;\n" 16293 "\n" 16294 "int oneTwoThree= 123;", 16295 Alignment)); 16296 EXPECT_EQ("int a = 5;\n" 16297 "int one = 1;\n" 16298 "\n" 16299 "int oneTwoThree = 123;", 16300 format("int a = 5;\n" 16301 "int one = 1;\n" 16302 "\n" 16303 "int oneTwoThree = 123;", 16304 Alignment)); 16305 EXPECT_EQ("int a = 5;\n" 16306 "int one = 1;\n" 16307 "\n" 16308 "int oneTwoThree = 123;\n" 16309 "int oneTwo = 12;", 16310 format("int a = 5;\n" 16311 "int one = 1;\n" 16312 "\n" 16313 "int oneTwoThree = 123;\n" 16314 "int oneTwo = 12;", 16315 Alignment)); 16316 16317 /* Test across comments */ 16318 EXPECT_EQ("int a = 5;\n" 16319 "/* block comment */\n" 16320 "int oneTwoThree = 123;", 16321 format("int a = 5;\n" 16322 "/* block comment */\n" 16323 "int oneTwoThree=123;", 16324 Alignment)); 16325 16326 EXPECT_EQ("int a = 5;\n" 16327 "// line comment\n" 16328 "int oneTwoThree = 123;", 16329 format("int a = 5;\n" 16330 "// line comment\n" 16331 "int oneTwoThree=123;", 16332 Alignment)); 16333 16334 /* Test across comments and newlines */ 16335 EXPECT_EQ("int a = 5;\n" 16336 "\n" 16337 "/* block comment */\n" 16338 "int oneTwoThree = 123;", 16339 format("int a = 5;\n" 16340 "\n" 16341 "/* block comment */\n" 16342 "int oneTwoThree=123;", 16343 Alignment)); 16344 16345 EXPECT_EQ("int a = 5;\n" 16346 "\n" 16347 "// line comment\n" 16348 "int oneTwoThree = 123;", 16349 format("int a = 5;\n" 16350 "\n" 16351 "// line comment\n" 16352 "int oneTwoThree=123;", 16353 Alignment)); 16354 16355 EXPECT_EQ("int a = 5;\n" 16356 "//\n" 16357 "// multi-line line comment\n" 16358 "//\n" 16359 "int oneTwoThree = 123;", 16360 format("int a = 5;\n" 16361 "//\n" 16362 "// multi-line line comment\n" 16363 "//\n" 16364 "int oneTwoThree=123;", 16365 Alignment)); 16366 16367 EXPECT_EQ("int a = 5;\n" 16368 "/*\n" 16369 " * multi-line block comment\n" 16370 " */\n" 16371 "int oneTwoThree = 123;", 16372 format("int a = 5;\n" 16373 "/*\n" 16374 " * multi-line block comment\n" 16375 " */\n" 16376 "int oneTwoThree=123;", 16377 Alignment)); 16378 16379 EXPECT_EQ("int a = 5;\n" 16380 "\n" 16381 "/* block comment */\n" 16382 "\n" 16383 "\n" 16384 "\n" 16385 "int oneTwoThree = 123;", 16386 format("int a = 5;\n" 16387 "\n" 16388 "/* block comment */\n" 16389 "\n" 16390 "\n" 16391 "\n" 16392 "int oneTwoThree=123;", 16393 Alignment)); 16394 16395 EXPECT_EQ("int a = 5;\n" 16396 "\n" 16397 "// line comment\n" 16398 "\n" 16399 "\n" 16400 "\n" 16401 "int oneTwoThree = 123;", 16402 format("int a = 5;\n" 16403 "\n" 16404 "// line comment\n" 16405 "\n" 16406 "\n" 16407 "\n" 16408 "int oneTwoThree=123;", 16409 Alignment)); 16410 16411 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 16412 verifyFormat("#define A \\\n" 16413 " int aaaa = 12; \\\n" 16414 " int b = 23; \\\n" 16415 " int ccc = 234; \\\n" 16416 " int dddddddddd = 2345;", 16417 Alignment); 16418 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 16419 verifyFormat("#define A \\\n" 16420 " int aaaa = 12; \\\n" 16421 " int b = 23; \\\n" 16422 " int ccc = 234; \\\n" 16423 " int dddddddddd = 2345;", 16424 Alignment); 16425 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 16426 verifyFormat("#define A " 16427 " \\\n" 16428 " int aaaa = 12; " 16429 " \\\n" 16430 " int b = 23; " 16431 " \\\n" 16432 " int ccc = 234; " 16433 " \\\n" 16434 " int dddddddddd = 2345;", 16435 Alignment); 16436 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 16437 "k = 4, int l = 5,\n" 16438 " int m = 6) {\n" 16439 " int j = 10;\n" 16440 " otherThing = 1;\n" 16441 "}", 16442 Alignment); 16443 verifyFormat("void SomeFunction(int parameter = 0) {\n" 16444 " int i = 1;\n" 16445 " int j = 2;\n" 16446 " int big = 10000;\n" 16447 "}", 16448 Alignment); 16449 verifyFormat("class C {\n" 16450 "public:\n" 16451 " int i = 1;\n" 16452 " virtual void f() = 0;\n" 16453 "};", 16454 Alignment); 16455 verifyFormat("int i = 1;\n" 16456 "if (SomeType t = getSomething()) {\n" 16457 "}\n" 16458 "int j = 2;\n" 16459 "int big = 10000;", 16460 Alignment); 16461 verifyFormat("int j = 7;\n" 16462 "for (int k = 0; k < N; ++k) {\n" 16463 "}\n" 16464 "int j = 2;\n" 16465 "int big = 10000;\n" 16466 "}", 16467 Alignment); 16468 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 16469 verifyFormat("int i = 1;\n" 16470 "LooooooooooongType loooooooooooooooooooooongVariable\n" 16471 " = someLooooooooooooooooongFunction();\n" 16472 "int j = 2;", 16473 Alignment); 16474 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 16475 verifyFormat("int i = 1;\n" 16476 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 16477 " someLooooooooooooooooongFunction();\n" 16478 "int j = 2;", 16479 Alignment); 16480 16481 verifyFormat("auto lambda = []() {\n" 16482 " auto i = 0;\n" 16483 " return 0;\n" 16484 "};\n" 16485 "int i = 0;\n" 16486 "auto v = type{\n" 16487 " i = 1, //\n" 16488 " (i = 2), //\n" 16489 " i = 3 //\n" 16490 "};", 16491 Alignment); 16492 16493 verifyFormat( 16494 "int i = 1;\n" 16495 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 16496 " loooooooooooooooooooooongParameterB);\n" 16497 "int j = 2;", 16498 Alignment); 16499 16500 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n" 16501 " typename B = very_long_type_name_1,\n" 16502 " typename T_2 = very_long_type_name_2>\n" 16503 "auto foo() {}\n", 16504 Alignment); 16505 verifyFormat("int a, b = 1;\n" 16506 "int c = 2;\n" 16507 "int dd = 3;\n", 16508 Alignment); 16509 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 16510 "float b[1][] = {{3.f}};\n", 16511 Alignment); 16512 verifyFormat("for (int i = 0; i < 1; i++)\n" 16513 " int x = 1;\n", 16514 Alignment); 16515 verifyFormat("for (i = 0; i < 1; i++)\n" 16516 " x = 1;\n" 16517 "y = 1;\n", 16518 Alignment); 16519 16520 Alignment.ReflowComments = true; 16521 Alignment.ColumnLimit = 50; 16522 EXPECT_EQ("int x = 0;\n" 16523 "int yy = 1; /// specificlennospace\n" 16524 "int zzz = 2;\n", 16525 format("int x = 0;\n" 16526 "int yy = 1; ///specificlennospace\n" 16527 "int zzz = 2;\n", 16528 Alignment)); 16529 } 16530 16531 TEST_F(FormatTest, AlignConsecutiveAssignments) { 16532 FormatStyle Alignment = getLLVMStyle(); 16533 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 16534 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 16535 verifyFormat("int a = 5;\n" 16536 "int oneTwoThree = 123;", 16537 Alignment); 16538 verifyFormat("int a = 5;\n" 16539 "int oneTwoThree = 123;", 16540 Alignment); 16541 16542 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 16543 verifyFormat("int a = 5;\n" 16544 "int oneTwoThree = 123;", 16545 Alignment); 16546 verifyFormat("int a = method();\n" 16547 "int oneTwoThree = 133;", 16548 Alignment); 16549 verifyFormat("a &= 5;\n" 16550 "bcd *= 5;\n" 16551 "ghtyf += 5;\n" 16552 "dvfvdb -= 5;\n" 16553 "a /= 5;\n" 16554 "vdsvsv %= 5;\n" 16555 "sfdbddfbdfbb ^= 5;\n" 16556 "dvsdsv |= 5;\n" 16557 "int dsvvdvsdvvv = 123;", 16558 Alignment); 16559 verifyFormat("int i = 1, j = 10;\n" 16560 "something = 2000;", 16561 Alignment); 16562 verifyFormat("something = 2000;\n" 16563 "int i = 1, j = 10;\n", 16564 Alignment); 16565 verifyFormat("something = 2000;\n" 16566 "another = 911;\n" 16567 "int i = 1, j = 10;\n" 16568 "oneMore = 1;\n" 16569 "i = 2;", 16570 Alignment); 16571 verifyFormat("int a = 5;\n" 16572 "int one = 1;\n" 16573 "method();\n" 16574 "int oneTwoThree = 123;\n" 16575 "int oneTwo = 12;", 16576 Alignment); 16577 verifyFormat("int oneTwoThree = 123;\n" 16578 "int oneTwo = 12;\n" 16579 "method();\n", 16580 Alignment); 16581 verifyFormat("int oneTwoThree = 123; // comment\n" 16582 "int oneTwo = 12; // comment", 16583 Alignment); 16584 verifyFormat("int f() = default;\n" 16585 "int &operator() = default;\n" 16586 "int &operator=() {", 16587 Alignment); 16588 verifyFormat("int f() = delete;\n" 16589 "int &operator() = delete;\n" 16590 "int &operator=() {", 16591 Alignment); 16592 verifyFormat("int f() = default; // comment\n" 16593 "int &operator() = default; // comment\n" 16594 "int &operator=() {", 16595 Alignment); 16596 verifyFormat("int f() = default;\n" 16597 "int &operator() = default;\n" 16598 "int &operator==() {", 16599 Alignment); 16600 verifyFormat("int f() = default;\n" 16601 "int &operator() = default;\n" 16602 "int &operator<=() {", 16603 Alignment); 16604 verifyFormat("int f() = default;\n" 16605 "int &operator() = default;\n" 16606 "int &operator!=() {", 16607 Alignment); 16608 verifyFormat("int f() = default;\n" 16609 "int &operator() = default;\n" 16610 "int &operator=();", 16611 Alignment); 16612 verifyFormat("int f() = delete;\n" 16613 "int &operator() = delete;\n" 16614 "int &operator=();", 16615 Alignment); 16616 verifyFormat("/* long long padding */ int f() = default;\n" 16617 "int &operator() = default;\n" 16618 "int &operator/**/ =();", 16619 Alignment); 16620 // https://llvm.org/PR33697 16621 FormatStyle AlignmentWithPenalty = getLLVMStyle(); 16622 AlignmentWithPenalty.AlignConsecutiveAssignments = 16623 FormatStyle::ACS_Consecutive; 16624 AlignmentWithPenalty.PenaltyReturnTypeOnItsOwnLine = 5000; 16625 verifyFormat("class SSSSSSSSSSSSSSSSSSSSSSSSSSSS {\n" 16626 " void f() = delete;\n" 16627 " SSSSSSSSSSSSSSSSSSSSSSSSSSSS &operator=(\n" 16628 " const SSSSSSSSSSSSSSSSSSSSSSSSSSSS &other) = delete;\n" 16629 "};\n", 16630 AlignmentWithPenalty); 16631 16632 // Bug 25167 16633 /* Uncomment when fixed 16634 verifyFormat("#if A\n" 16635 "#else\n" 16636 "int aaaaaaaa = 12;\n" 16637 "#endif\n" 16638 "#if B\n" 16639 "#else\n" 16640 "int a = 12;\n" 16641 "#endif\n", 16642 Alignment); 16643 verifyFormat("enum foo {\n" 16644 "#if A\n" 16645 "#else\n" 16646 " aaaaaaaa = 12;\n" 16647 "#endif\n" 16648 "#if B\n" 16649 "#else\n" 16650 " a = 12;\n" 16651 "#endif\n" 16652 "};\n", 16653 Alignment); 16654 */ 16655 16656 EXPECT_EQ("int a = 5;\n" 16657 "\n" 16658 "int oneTwoThree = 123;", 16659 format("int a = 5;\n" 16660 "\n" 16661 "int oneTwoThree= 123;", 16662 Alignment)); 16663 EXPECT_EQ("int a = 5;\n" 16664 "int one = 1;\n" 16665 "\n" 16666 "int oneTwoThree = 123;", 16667 format("int a = 5;\n" 16668 "int one = 1;\n" 16669 "\n" 16670 "int oneTwoThree = 123;", 16671 Alignment)); 16672 EXPECT_EQ("int a = 5;\n" 16673 "int one = 1;\n" 16674 "\n" 16675 "int oneTwoThree = 123;\n" 16676 "int oneTwo = 12;", 16677 format("int a = 5;\n" 16678 "int one = 1;\n" 16679 "\n" 16680 "int oneTwoThree = 123;\n" 16681 "int oneTwo = 12;", 16682 Alignment)); 16683 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 16684 verifyFormat("#define A \\\n" 16685 " int aaaa = 12; \\\n" 16686 " int b = 23; \\\n" 16687 " int ccc = 234; \\\n" 16688 " int dddddddddd = 2345;", 16689 Alignment); 16690 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 16691 verifyFormat("#define A \\\n" 16692 " int aaaa = 12; \\\n" 16693 " int b = 23; \\\n" 16694 " int ccc = 234; \\\n" 16695 " int dddddddddd = 2345;", 16696 Alignment); 16697 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 16698 verifyFormat("#define A " 16699 " \\\n" 16700 " int aaaa = 12; " 16701 " \\\n" 16702 " int b = 23; " 16703 " \\\n" 16704 " int ccc = 234; " 16705 " \\\n" 16706 " int dddddddddd = 2345;", 16707 Alignment); 16708 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 16709 "k = 4, int l = 5,\n" 16710 " int m = 6) {\n" 16711 " int j = 10;\n" 16712 " otherThing = 1;\n" 16713 "}", 16714 Alignment); 16715 verifyFormat("void SomeFunction(int parameter = 0) {\n" 16716 " int i = 1;\n" 16717 " int j = 2;\n" 16718 " int big = 10000;\n" 16719 "}", 16720 Alignment); 16721 verifyFormat("class C {\n" 16722 "public:\n" 16723 " int i = 1;\n" 16724 " virtual void f() = 0;\n" 16725 "};", 16726 Alignment); 16727 verifyFormat("int i = 1;\n" 16728 "if (SomeType t = getSomething()) {\n" 16729 "}\n" 16730 "int j = 2;\n" 16731 "int big = 10000;", 16732 Alignment); 16733 verifyFormat("int j = 7;\n" 16734 "for (int k = 0; k < N; ++k) {\n" 16735 "}\n" 16736 "int j = 2;\n" 16737 "int big = 10000;\n" 16738 "}", 16739 Alignment); 16740 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 16741 verifyFormat("int i = 1;\n" 16742 "LooooooooooongType loooooooooooooooooooooongVariable\n" 16743 " = someLooooooooooooooooongFunction();\n" 16744 "int j = 2;", 16745 Alignment); 16746 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 16747 verifyFormat("int i = 1;\n" 16748 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 16749 " someLooooooooooooooooongFunction();\n" 16750 "int j = 2;", 16751 Alignment); 16752 16753 verifyFormat("auto lambda = []() {\n" 16754 " auto i = 0;\n" 16755 " return 0;\n" 16756 "};\n" 16757 "int i = 0;\n" 16758 "auto v = type{\n" 16759 " i = 1, //\n" 16760 " (i = 2), //\n" 16761 " i = 3 //\n" 16762 "};", 16763 Alignment); 16764 16765 verifyFormat( 16766 "int i = 1;\n" 16767 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 16768 " loooooooooooooooooooooongParameterB);\n" 16769 "int j = 2;", 16770 Alignment); 16771 16772 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n" 16773 " typename B = very_long_type_name_1,\n" 16774 " typename T_2 = very_long_type_name_2>\n" 16775 "auto foo() {}\n", 16776 Alignment); 16777 verifyFormat("int a, b = 1;\n" 16778 "int c = 2;\n" 16779 "int dd = 3;\n", 16780 Alignment); 16781 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 16782 "float b[1][] = {{3.f}};\n", 16783 Alignment); 16784 verifyFormat("for (int i = 0; i < 1; i++)\n" 16785 " int x = 1;\n", 16786 Alignment); 16787 verifyFormat("for (i = 0; i < 1; i++)\n" 16788 " x = 1;\n" 16789 "y = 1;\n", 16790 Alignment); 16791 16792 EXPECT_EQ(Alignment.ReflowComments, true); 16793 Alignment.ColumnLimit = 50; 16794 EXPECT_EQ("int x = 0;\n" 16795 "int yy = 1; /// specificlennospace\n" 16796 "int zzz = 2;\n", 16797 format("int x = 0;\n" 16798 "int yy = 1; ///specificlennospace\n" 16799 "int zzz = 2;\n", 16800 Alignment)); 16801 16802 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 16803 "auto b = [] {\n" 16804 " f();\n" 16805 " return;\n" 16806 "};", 16807 Alignment); 16808 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 16809 "auto b = g([] {\n" 16810 " f();\n" 16811 " return;\n" 16812 "});", 16813 Alignment); 16814 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 16815 "auto b = g(param, [] {\n" 16816 " f();\n" 16817 " return;\n" 16818 "});", 16819 Alignment); 16820 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 16821 "auto b = [] {\n" 16822 " if (condition) {\n" 16823 " return;\n" 16824 " }\n" 16825 "};", 16826 Alignment); 16827 16828 verifyFormat("auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 16829 " ccc ? aaaaa : bbbbb,\n" 16830 " dddddddddddddddddddddddddd);", 16831 Alignment); 16832 // FIXME: https://llvm.org/PR53497 16833 // verifyFormat("auto aaaaaaaaaaaa = f();\n" 16834 // "auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 16835 // " ccc ? aaaaa : bbbbb,\n" 16836 // " dddddddddddddddddddddddddd);", 16837 // Alignment); 16838 } 16839 16840 TEST_F(FormatTest, AlignConsecutiveBitFields) { 16841 FormatStyle Alignment = getLLVMStyle(); 16842 Alignment.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive; 16843 verifyFormat("int const a : 5;\n" 16844 "int oneTwoThree : 23;", 16845 Alignment); 16846 16847 // Initializers are allowed starting with c++2a 16848 verifyFormat("int const a : 5 = 1;\n" 16849 "int oneTwoThree : 23 = 0;", 16850 Alignment); 16851 16852 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 16853 verifyFormat("int const a : 5;\n" 16854 "int oneTwoThree : 23;", 16855 Alignment); 16856 16857 verifyFormat("int const a : 5; // comment\n" 16858 "int oneTwoThree : 23; // comment", 16859 Alignment); 16860 16861 verifyFormat("int const a : 5 = 1;\n" 16862 "int oneTwoThree : 23 = 0;", 16863 Alignment); 16864 16865 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 16866 verifyFormat("int const a : 5 = 1;\n" 16867 "int oneTwoThree : 23 = 0;", 16868 Alignment); 16869 verifyFormat("int const a : 5 = {1};\n" 16870 "int oneTwoThree : 23 = 0;", 16871 Alignment); 16872 16873 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None; 16874 verifyFormat("int const a :5;\n" 16875 "int oneTwoThree:23;", 16876 Alignment); 16877 16878 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before; 16879 verifyFormat("int const a :5;\n" 16880 "int oneTwoThree :23;", 16881 Alignment); 16882 16883 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After; 16884 verifyFormat("int const a : 5;\n" 16885 "int oneTwoThree: 23;", 16886 Alignment); 16887 16888 // Known limitations: ':' is only recognized as a bitfield colon when 16889 // followed by a number. 16890 /* 16891 verifyFormat("int oneTwoThree : SOME_CONSTANT;\n" 16892 "int a : 5;", 16893 Alignment); 16894 */ 16895 } 16896 16897 TEST_F(FormatTest, AlignConsecutiveDeclarations) { 16898 FormatStyle Alignment = getLLVMStyle(); 16899 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 16900 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_None; 16901 Alignment.PointerAlignment = FormatStyle::PAS_Right; 16902 verifyFormat("float const a = 5;\n" 16903 "int oneTwoThree = 123;", 16904 Alignment); 16905 verifyFormat("int a = 5;\n" 16906 "float const oneTwoThree = 123;", 16907 Alignment); 16908 16909 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 16910 verifyFormat("float const a = 5;\n" 16911 "int oneTwoThree = 123;", 16912 Alignment); 16913 verifyFormat("int a = method();\n" 16914 "float const oneTwoThree = 133;", 16915 Alignment); 16916 verifyFormat("int i = 1, j = 10;\n" 16917 "something = 2000;", 16918 Alignment); 16919 verifyFormat("something = 2000;\n" 16920 "int i = 1, j = 10;\n", 16921 Alignment); 16922 verifyFormat("float something = 2000;\n" 16923 "double another = 911;\n" 16924 "int i = 1, j = 10;\n" 16925 "const int *oneMore = 1;\n" 16926 "unsigned i = 2;", 16927 Alignment); 16928 verifyFormat("float a = 5;\n" 16929 "int one = 1;\n" 16930 "method();\n" 16931 "const double oneTwoThree = 123;\n" 16932 "const unsigned int oneTwo = 12;", 16933 Alignment); 16934 verifyFormat("int oneTwoThree{0}; // comment\n" 16935 "unsigned oneTwo; // comment", 16936 Alignment); 16937 verifyFormat("unsigned int *a;\n" 16938 "int *b;\n" 16939 "unsigned int Const *c;\n" 16940 "unsigned int const *d;\n" 16941 "unsigned int Const &e;\n" 16942 "unsigned int const &f;", 16943 Alignment); 16944 verifyFormat("Const unsigned int *c;\n" 16945 "const unsigned int *d;\n" 16946 "Const unsigned int &e;\n" 16947 "const unsigned int &f;\n" 16948 "const unsigned g;\n" 16949 "Const unsigned h;", 16950 Alignment); 16951 EXPECT_EQ("float const a = 5;\n" 16952 "\n" 16953 "int oneTwoThree = 123;", 16954 format("float const a = 5;\n" 16955 "\n" 16956 "int oneTwoThree= 123;", 16957 Alignment)); 16958 EXPECT_EQ("float a = 5;\n" 16959 "int one = 1;\n" 16960 "\n" 16961 "unsigned oneTwoThree = 123;", 16962 format("float a = 5;\n" 16963 "int one = 1;\n" 16964 "\n" 16965 "unsigned oneTwoThree = 123;", 16966 Alignment)); 16967 EXPECT_EQ("float a = 5;\n" 16968 "int one = 1;\n" 16969 "\n" 16970 "unsigned oneTwoThree = 123;\n" 16971 "int oneTwo = 12;", 16972 format("float a = 5;\n" 16973 "int one = 1;\n" 16974 "\n" 16975 "unsigned oneTwoThree = 123;\n" 16976 "int oneTwo = 12;", 16977 Alignment)); 16978 // Function prototype alignment 16979 verifyFormat("int a();\n" 16980 "double b();", 16981 Alignment); 16982 verifyFormat("int a(int x);\n" 16983 "double b();", 16984 Alignment); 16985 unsigned OldColumnLimit = Alignment.ColumnLimit; 16986 // We need to set ColumnLimit to zero, in order to stress nested alignments, 16987 // otherwise the function parameters will be re-flowed onto a single line. 16988 Alignment.ColumnLimit = 0; 16989 EXPECT_EQ("int a(int x,\n" 16990 " float y);\n" 16991 "double b(int x,\n" 16992 " double y);", 16993 format("int a(int x,\n" 16994 " float y);\n" 16995 "double b(int x,\n" 16996 " double y);", 16997 Alignment)); 16998 // This ensures that function parameters of function declarations are 16999 // correctly indented when their owning functions are indented. 17000 // The failure case here is for 'double y' to not be indented enough. 17001 EXPECT_EQ("double a(int x);\n" 17002 "int b(int y,\n" 17003 " double z);", 17004 format("double a(int x);\n" 17005 "int b(int y,\n" 17006 " double z);", 17007 Alignment)); 17008 // Set ColumnLimit low so that we induce wrapping immediately after 17009 // the function name and opening paren. 17010 Alignment.ColumnLimit = 13; 17011 verifyFormat("int function(\n" 17012 " int x,\n" 17013 " bool y);", 17014 Alignment); 17015 Alignment.ColumnLimit = OldColumnLimit; 17016 // Ensure function pointers don't screw up recursive alignment 17017 verifyFormat("int a(int x, void (*fp)(int y));\n" 17018 "double b();", 17019 Alignment); 17020 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17021 // Ensure recursive alignment is broken by function braces, so that the 17022 // "a = 1" does not align with subsequent assignments inside the function 17023 // body. 17024 verifyFormat("int func(int a = 1) {\n" 17025 " int b = 2;\n" 17026 " int cc = 3;\n" 17027 "}", 17028 Alignment); 17029 verifyFormat("float something = 2000;\n" 17030 "double another = 911;\n" 17031 "int i = 1, j = 10;\n" 17032 "const int *oneMore = 1;\n" 17033 "unsigned i = 2;", 17034 Alignment); 17035 verifyFormat("int oneTwoThree = {0}; // comment\n" 17036 "unsigned oneTwo = 0; // comment", 17037 Alignment); 17038 // Make sure that scope is correctly tracked, in the absence of braces 17039 verifyFormat("for (int i = 0; i < n; i++)\n" 17040 " j = i;\n" 17041 "double x = 1;\n", 17042 Alignment); 17043 verifyFormat("if (int i = 0)\n" 17044 " j = i;\n" 17045 "double x = 1;\n", 17046 Alignment); 17047 // Ensure operator[] and operator() are comprehended 17048 verifyFormat("struct test {\n" 17049 " long long int foo();\n" 17050 " int operator[](int a);\n" 17051 " double bar();\n" 17052 "};\n", 17053 Alignment); 17054 verifyFormat("struct test {\n" 17055 " long long int foo();\n" 17056 " int operator()(int a);\n" 17057 " double bar();\n" 17058 "};\n", 17059 Alignment); 17060 // http://llvm.org/PR52914 17061 verifyFormat("char *a[] = {\"a\", // comment\n" 17062 " \"bb\"};\n" 17063 "int bbbbbbb = 0;", 17064 Alignment); 17065 17066 // PAS_Right 17067 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17068 " int const i = 1;\n" 17069 " int *j = 2;\n" 17070 " int big = 10000;\n" 17071 "\n" 17072 " unsigned oneTwoThree = 123;\n" 17073 " int oneTwo = 12;\n" 17074 " method();\n" 17075 " float k = 2;\n" 17076 " int ll = 10000;\n" 17077 "}", 17078 format("void SomeFunction(int parameter= 0) {\n" 17079 " int const i= 1;\n" 17080 " int *j=2;\n" 17081 " int big = 10000;\n" 17082 "\n" 17083 "unsigned oneTwoThree =123;\n" 17084 "int oneTwo = 12;\n" 17085 " method();\n" 17086 "float k= 2;\n" 17087 "int ll=10000;\n" 17088 "}", 17089 Alignment)); 17090 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17091 " int const i = 1;\n" 17092 " int **j = 2, ***k;\n" 17093 " int &k = i;\n" 17094 " int &&l = i + j;\n" 17095 " int big = 10000;\n" 17096 "\n" 17097 " unsigned oneTwoThree = 123;\n" 17098 " int oneTwo = 12;\n" 17099 " method();\n" 17100 " float k = 2;\n" 17101 " int ll = 10000;\n" 17102 "}", 17103 format("void SomeFunction(int parameter= 0) {\n" 17104 " int const i= 1;\n" 17105 " int **j=2,***k;\n" 17106 "int &k=i;\n" 17107 "int &&l=i+j;\n" 17108 " int big = 10000;\n" 17109 "\n" 17110 "unsigned oneTwoThree =123;\n" 17111 "int oneTwo = 12;\n" 17112 " method();\n" 17113 "float k= 2;\n" 17114 "int ll=10000;\n" 17115 "}", 17116 Alignment)); 17117 // variables are aligned at their name, pointers are at the right most 17118 // position 17119 verifyFormat("int *a;\n" 17120 "int **b;\n" 17121 "int ***c;\n" 17122 "int foobar;\n", 17123 Alignment); 17124 17125 // PAS_Left 17126 FormatStyle AlignmentLeft = Alignment; 17127 AlignmentLeft.PointerAlignment = FormatStyle::PAS_Left; 17128 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17129 " int const i = 1;\n" 17130 " int* j = 2;\n" 17131 " int big = 10000;\n" 17132 "\n" 17133 " unsigned oneTwoThree = 123;\n" 17134 " int oneTwo = 12;\n" 17135 " method();\n" 17136 " float k = 2;\n" 17137 " int ll = 10000;\n" 17138 "}", 17139 format("void SomeFunction(int parameter= 0) {\n" 17140 " int const i= 1;\n" 17141 " int *j=2;\n" 17142 " int big = 10000;\n" 17143 "\n" 17144 "unsigned oneTwoThree =123;\n" 17145 "int oneTwo = 12;\n" 17146 " method();\n" 17147 "float k= 2;\n" 17148 "int ll=10000;\n" 17149 "}", 17150 AlignmentLeft)); 17151 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17152 " int const i = 1;\n" 17153 " int** j = 2;\n" 17154 " int& k = i;\n" 17155 " int&& l = i + j;\n" 17156 " int big = 10000;\n" 17157 "\n" 17158 " unsigned oneTwoThree = 123;\n" 17159 " int oneTwo = 12;\n" 17160 " method();\n" 17161 " float k = 2;\n" 17162 " int ll = 10000;\n" 17163 "}", 17164 format("void SomeFunction(int parameter= 0) {\n" 17165 " int const i= 1;\n" 17166 " int **j=2;\n" 17167 "int &k=i;\n" 17168 "int &&l=i+j;\n" 17169 " int big = 10000;\n" 17170 "\n" 17171 "unsigned oneTwoThree =123;\n" 17172 "int oneTwo = 12;\n" 17173 " method();\n" 17174 "float k= 2;\n" 17175 "int ll=10000;\n" 17176 "}", 17177 AlignmentLeft)); 17178 // variables are aligned at their name, pointers are at the left most position 17179 verifyFormat("int* a;\n" 17180 "int** b;\n" 17181 "int*** c;\n" 17182 "int foobar;\n", 17183 AlignmentLeft); 17184 17185 // PAS_Middle 17186 FormatStyle AlignmentMiddle = Alignment; 17187 AlignmentMiddle.PointerAlignment = FormatStyle::PAS_Middle; 17188 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17189 " int const i = 1;\n" 17190 " int * j = 2;\n" 17191 " int big = 10000;\n" 17192 "\n" 17193 " unsigned oneTwoThree = 123;\n" 17194 " int oneTwo = 12;\n" 17195 " method();\n" 17196 " float k = 2;\n" 17197 " int ll = 10000;\n" 17198 "}", 17199 format("void SomeFunction(int parameter= 0) {\n" 17200 " int const i= 1;\n" 17201 " int *j=2;\n" 17202 " int big = 10000;\n" 17203 "\n" 17204 "unsigned oneTwoThree =123;\n" 17205 "int oneTwo = 12;\n" 17206 " method();\n" 17207 "float k= 2;\n" 17208 "int ll=10000;\n" 17209 "}", 17210 AlignmentMiddle)); 17211 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17212 " int const i = 1;\n" 17213 " int ** j = 2, ***k;\n" 17214 " int & k = i;\n" 17215 " int && l = i + j;\n" 17216 " int big = 10000;\n" 17217 "\n" 17218 " unsigned oneTwoThree = 123;\n" 17219 " int oneTwo = 12;\n" 17220 " method();\n" 17221 " float k = 2;\n" 17222 " int ll = 10000;\n" 17223 "}", 17224 format("void SomeFunction(int parameter= 0) {\n" 17225 " int const i= 1;\n" 17226 " int **j=2,***k;\n" 17227 "int &k=i;\n" 17228 "int &&l=i+j;\n" 17229 " int big = 10000;\n" 17230 "\n" 17231 "unsigned oneTwoThree =123;\n" 17232 "int oneTwo = 12;\n" 17233 " method();\n" 17234 "float k= 2;\n" 17235 "int ll=10000;\n" 17236 "}", 17237 AlignmentMiddle)); 17238 // variables are aligned at their name, pointers are in the middle 17239 verifyFormat("int * a;\n" 17240 "int * b;\n" 17241 "int *** c;\n" 17242 "int foobar;\n", 17243 AlignmentMiddle); 17244 17245 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 17246 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 17247 verifyFormat("#define A \\\n" 17248 " int aaaa = 12; \\\n" 17249 " float b = 23; \\\n" 17250 " const int ccc = 234; \\\n" 17251 " unsigned dddddddddd = 2345;", 17252 Alignment); 17253 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 17254 verifyFormat("#define A \\\n" 17255 " int aaaa = 12; \\\n" 17256 " float b = 23; \\\n" 17257 " const int ccc = 234; \\\n" 17258 " unsigned dddddddddd = 2345;", 17259 Alignment); 17260 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 17261 Alignment.ColumnLimit = 30; 17262 verifyFormat("#define A \\\n" 17263 " int aaaa = 12; \\\n" 17264 " float b = 23; \\\n" 17265 " const int ccc = 234; \\\n" 17266 " int dddddddddd = 2345;", 17267 Alignment); 17268 Alignment.ColumnLimit = 80; 17269 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 17270 "k = 4, int l = 5,\n" 17271 " int m = 6) {\n" 17272 " const int j = 10;\n" 17273 " otherThing = 1;\n" 17274 "}", 17275 Alignment); 17276 verifyFormat("void SomeFunction(int parameter = 0) {\n" 17277 " int const i = 1;\n" 17278 " int *j = 2;\n" 17279 " int big = 10000;\n" 17280 "}", 17281 Alignment); 17282 verifyFormat("class C {\n" 17283 "public:\n" 17284 " int i = 1;\n" 17285 " virtual void f() = 0;\n" 17286 "};", 17287 Alignment); 17288 verifyFormat("float i = 1;\n" 17289 "if (SomeType t = getSomething()) {\n" 17290 "}\n" 17291 "const unsigned j = 2;\n" 17292 "int big = 10000;", 17293 Alignment); 17294 verifyFormat("float j = 7;\n" 17295 "for (int k = 0; k < N; ++k) {\n" 17296 "}\n" 17297 "unsigned j = 2;\n" 17298 "int big = 10000;\n" 17299 "}", 17300 Alignment); 17301 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 17302 verifyFormat("float i = 1;\n" 17303 "LooooooooooongType loooooooooooooooooooooongVariable\n" 17304 " = someLooooooooooooooooongFunction();\n" 17305 "int j = 2;", 17306 Alignment); 17307 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 17308 verifyFormat("int i = 1;\n" 17309 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 17310 " someLooooooooooooooooongFunction();\n" 17311 "int j = 2;", 17312 Alignment); 17313 17314 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17315 verifyFormat("auto lambda = []() {\n" 17316 " auto ii = 0;\n" 17317 " float j = 0;\n" 17318 " return 0;\n" 17319 "};\n" 17320 "int i = 0;\n" 17321 "float i2 = 0;\n" 17322 "auto v = type{\n" 17323 " i = 1, //\n" 17324 " (i = 2), //\n" 17325 " i = 3 //\n" 17326 "};", 17327 Alignment); 17328 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 17329 17330 verifyFormat( 17331 "int i = 1;\n" 17332 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 17333 " loooooooooooooooooooooongParameterB);\n" 17334 "int j = 2;", 17335 Alignment); 17336 17337 // Test interactions with ColumnLimit and AlignConsecutiveAssignments: 17338 // We expect declarations and assignments to align, as long as it doesn't 17339 // exceed the column limit, starting a new alignment sequence whenever it 17340 // happens. 17341 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17342 Alignment.ColumnLimit = 30; 17343 verifyFormat("float ii = 1;\n" 17344 "unsigned j = 2;\n" 17345 "int someVerylongVariable = 1;\n" 17346 "AnotherLongType ll = 123456;\n" 17347 "VeryVeryLongType k = 2;\n" 17348 "int myvar = 1;", 17349 Alignment); 17350 Alignment.ColumnLimit = 80; 17351 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 17352 17353 verifyFormat( 17354 "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n" 17355 " typename LongType, typename B>\n" 17356 "auto foo() {}\n", 17357 Alignment); 17358 verifyFormat("float a, b = 1;\n" 17359 "int c = 2;\n" 17360 "int dd = 3;\n", 17361 Alignment); 17362 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17363 "float b[1][] = {{3.f}};\n", 17364 Alignment); 17365 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17366 verifyFormat("float a, b = 1;\n" 17367 "int c = 2;\n" 17368 "int dd = 3;\n", 17369 Alignment); 17370 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17371 "float b[1][] = {{3.f}};\n", 17372 Alignment); 17373 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 17374 17375 Alignment.ColumnLimit = 30; 17376 Alignment.BinPackParameters = false; 17377 verifyFormat("void foo(float a,\n" 17378 " float b,\n" 17379 " int c,\n" 17380 " uint32_t *d) {\n" 17381 " int *e = 0;\n" 17382 " float f = 0;\n" 17383 " double g = 0;\n" 17384 "}\n" 17385 "void bar(ino_t a,\n" 17386 " int b,\n" 17387 " uint32_t *c,\n" 17388 " bool d) {}\n", 17389 Alignment); 17390 Alignment.BinPackParameters = true; 17391 Alignment.ColumnLimit = 80; 17392 17393 // Bug 33507 17394 Alignment.PointerAlignment = FormatStyle::PAS_Middle; 17395 verifyFormat( 17396 "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n" 17397 " static const Version verVs2017;\n" 17398 " return true;\n" 17399 "});\n", 17400 Alignment); 17401 Alignment.PointerAlignment = FormatStyle::PAS_Right; 17402 17403 // See llvm.org/PR35641 17404 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17405 verifyFormat("int func() { //\n" 17406 " int b;\n" 17407 " unsigned c;\n" 17408 "}", 17409 Alignment); 17410 17411 // See PR37175 17412 FormatStyle Style = getMozillaStyle(); 17413 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17414 EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n" 17415 "foo(int a);", 17416 format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style)); 17417 17418 Alignment.PointerAlignment = FormatStyle::PAS_Left; 17419 verifyFormat("unsigned int* a;\n" 17420 "int* b;\n" 17421 "unsigned int Const* c;\n" 17422 "unsigned int const* d;\n" 17423 "unsigned int Const& e;\n" 17424 "unsigned int const& f;", 17425 Alignment); 17426 verifyFormat("Const unsigned int* c;\n" 17427 "const unsigned int* d;\n" 17428 "Const unsigned int& e;\n" 17429 "const unsigned int& f;\n" 17430 "const unsigned g;\n" 17431 "Const unsigned h;", 17432 Alignment); 17433 17434 Alignment.PointerAlignment = FormatStyle::PAS_Middle; 17435 verifyFormat("unsigned int * a;\n" 17436 "int * b;\n" 17437 "unsigned int Const * c;\n" 17438 "unsigned int const * d;\n" 17439 "unsigned int Const & e;\n" 17440 "unsigned int const & f;", 17441 Alignment); 17442 verifyFormat("Const unsigned int * c;\n" 17443 "const unsigned int * d;\n" 17444 "Const unsigned int & e;\n" 17445 "const unsigned int & f;\n" 17446 "const unsigned g;\n" 17447 "Const unsigned h;", 17448 Alignment); 17449 17450 // See PR46529 17451 FormatStyle BracedAlign = getLLVMStyle(); 17452 BracedAlign.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17453 verifyFormat("const auto result{[]() {\n" 17454 " const auto something = 1;\n" 17455 " return 2;\n" 17456 "}};", 17457 BracedAlign); 17458 verifyFormat("int foo{[]() {\n" 17459 " int bar{0};\n" 17460 " return 0;\n" 17461 "}()};", 17462 BracedAlign); 17463 BracedAlign.Cpp11BracedListStyle = false; 17464 verifyFormat("const auto result{ []() {\n" 17465 " const auto something = 1;\n" 17466 " return 2;\n" 17467 "} };", 17468 BracedAlign); 17469 verifyFormat("int foo{ []() {\n" 17470 " int bar{ 0 };\n" 17471 " return 0;\n" 17472 "}() };", 17473 BracedAlign); 17474 } 17475 17476 TEST_F(FormatTest, AlignWithLineBreaks) { 17477 auto Style = getLLVMStyleWithColumns(120); 17478 17479 EXPECT_EQ(Style.AlignConsecutiveAssignments, FormatStyle::ACS_None); 17480 EXPECT_EQ(Style.AlignConsecutiveDeclarations, FormatStyle::ACS_None); 17481 verifyFormat("void foo() {\n" 17482 " int myVar = 5;\n" 17483 " double x = 3.14;\n" 17484 " auto str = \"Hello \"\n" 17485 " \"World\";\n" 17486 " auto s = \"Hello \"\n" 17487 " \"Again\";\n" 17488 "}", 17489 Style); 17490 17491 // clang-format off 17492 verifyFormat("void foo() {\n" 17493 " const int capacityBefore = Entries.capacity();\n" 17494 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17495 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17496 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17497 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17498 "}", 17499 Style); 17500 // clang-format on 17501 17502 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17503 verifyFormat("void foo() {\n" 17504 " int myVar = 5;\n" 17505 " double x = 3.14;\n" 17506 " auto str = \"Hello \"\n" 17507 " \"World\";\n" 17508 " auto s = \"Hello \"\n" 17509 " \"Again\";\n" 17510 "}", 17511 Style); 17512 17513 // clang-format off 17514 verifyFormat("void foo() {\n" 17515 " const int capacityBefore = Entries.capacity();\n" 17516 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17517 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17518 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17519 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17520 "}", 17521 Style); 17522 // clang-format on 17523 17524 Style.AlignConsecutiveAssignments = FormatStyle::ACS_None; 17525 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17526 verifyFormat("void foo() {\n" 17527 " int myVar = 5;\n" 17528 " double x = 3.14;\n" 17529 " auto str = \"Hello \"\n" 17530 " \"World\";\n" 17531 " auto s = \"Hello \"\n" 17532 " \"Again\";\n" 17533 "}", 17534 Style); 17535 17536 // clang-format off 17537 verifyFormat("void foo() {\n" 17538 " const int capacityBefore = Entries.capacity();\n" 17539 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17540 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17541 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17542 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17543 "}", 17544 Style); 17545 // clang-format on 17546 17547 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17548 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17549 17550 verifyFormat("void foo() {\n" 17551 " int myVar = 5;\n" 17552 " double x = 3.14;\n" 17553 " auto str = \"Hello \"\n" 17554 " \"World\";\n" 17555 " auto s = \"Hello \"\n" 17556 " \"Again\";\n" 17557 "}", 17558 Style); 17559 17560 // clang-format off 17561 verifyFormat("void foo() {\n" 17562 " const int capacityBefore = Entries.capacity();\n" 17563 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17564 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17565 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17566 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17567 "}", 17568 Style); 17569 // clang-format on 17570 17571 Style = getLLVMStyleWithColumns(120); 17572 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17573 Style.ContinuationIndentWidth = 4; 17574 Style.IndentWidth = 4; 17575 17576 // clang-format off 17577 verifyFormat("void SomeFunc() {\n" 17578 " newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 17579 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17580 " newWatcher.maxAge = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 17581 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17582 " newWatcher.max = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 17583 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17584 "}", 17585 Style); 17586 // clang-format on 17587 17588 Style.BinPackArguments = false; 17589 17590 // clang-format off 17591 verifyFormat("void SomeFunc() {\n" 17592 " newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(\n" 17593 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17594 " newWatcher.maxAge = ToLegacyTimestamp(GetMaxAge(\n" 17595 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17596 " newWatcher.max = ToLegacyTimestamp(GetMaxAge(\n" 17597 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17598 "}", 17599 Style); 17600 // clang-format on 17601 } 17602 17603 TEST_F(FormatTest, AlignWithInitializerPeriods) { 17604 auto Style = getLLVMStyleWithColumns(60); 17605 17606 verifyFormat("void foo1(void) {\n" 17607 " BYTE p[1] = 1;\n" 17608 " A B = {.one_foooooooooooooooo = 2,\n" 17609 " .two_fooooooooooooo = 3,\n" 17610 " .three_fooooooooooooo = 4};\n" 17611 " BYTE payload = 2;\n" 17612 "}", 17613 Style); 17614 17615 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17616 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_None; 17617 verifyFormat("void foo2(void) {\n" 17618 " BYTE p[1] = 1;\n" 17619 " A B = {.one_foooooooooooooooo = 2,\n" 17620 " .two_fooooooooooooo = 3,\n" 17621 " .three_fooooooooooooo = 4};\n" 17622 " BYTE payload = 2;\n" 17623 "}", 17624 Style); 17625 17626 Style.AlignConsecutiveAssignments = FormatStyle::ACS_None; 17627 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17628 verifyFormat("void foo3(void) {\n" 17629 " BYTE p[1] = 1;\n" 17630 " A B = {.one_foooooooooooooooo = 2,\n" 17631 " .two_fooooooooooooo = 3,\n" 17632 " .three_fooooooooooooo = 4};\n" 17633 " BYTE payload = 2;\n" 17634 "}", 17635 Style); 17636 17637 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17638 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17639 verifyFormat("void foo4(void) {\n" 17640 " BYTE p[1] = 1;\n" 17641 " A B = {.one_foooooooooooooooo = 2,\n" 17642 " .two_fooooooooooooo = 3,\n" 17643 " .three_fooooooooooooo = 4};\n" 17644 " BYTE payload = 2;\n" 17645 "}", 17646 Style); 17647 } 17648 17649 TEST_F(FormatTest, LinuxBraceBreaking) { 17650 FormatStyle LinuxBraceStyle = getLLVMStyle(); 17651 LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux; 17652 verifyFormat("namespace a\n" 17653 "{\n" 17654 "class A\n" 17655 "{\n" 17656 " void f()\n" 17657 " {\n" 17658 " if (true) {\n" 17659 " a();\n" 17660 " b();\n" 17661 " } else {\n" 17662 " a();\n" 17663 " }\n" 17664 " }\n" 17665 " void g() { return; }\n" 17666 "};\n" 17667 "struct B {\n" 17668 " int x;\n" 17669 "};\n" 17670 "} // namespace a\n", 17671 LinuxBraceStyle); 17672 verifyFormat("enum X {\n" 17673 " Y = 0,\n" 17674 "}\n", 17675 LinuxBraceStyle); 17676 verifyFormat("struct S {\n" 17677 " int Type;\n" 17678 " union {\n" 17679 " int x;\n" 17680 " double y;\n" 17681 " } Value;\n" 17682 " class C\n" 17683 " {\n" 17684 " MyFavoriteType Value;\n" 17685 " } Class;\n" 17686 "}\n", 17687 LinuxBraceStyle); 17688 } 17689 17690 TEST_F(FormatTest, MozillaBraceBreaking) { 17691 FormatStyle MozillaBraceStyle = getLLVMStyle(); 17692 MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla; 17693 MozillaBraceStyle.FixNamespaceComments = false; 17694 verifyFormat("namespace a {\n" 17695 "class A\n" 17696 "{\n" 17697 " void f()\n" 17698 " {\n" 17699 " if (true) {\n" 17700 " a();\n" 17701 " b();\n" 17702 " }\n" 17703 " }\n" 17704 " void g() { return; }\n" 17705 "};\n" 17706 "enum E\n" 17707 "{\n" 17708 " A,\n" 17709 " // foo\n" 17710 " B,\n" 17711 " C\n" 17712 "};\n" 17713 "struct B\n" 17714 "{\n" 17715 " int x;\n" 17716 "};\n" 17717 "}\n", 17718 MozillaBraceStyle); 17719 verifyFormat("struct S\n" 17720 "{\n" 17721 " int Type;\n" 17722 " union\n" 17723 " {\n" 17724 " int x;\n" 17725 " double y;\n" 17726 " } Value;\n" 17727 " class C\n" 17728 " {\n" 17729 " MyFavoriteType Value;\n" 17730 " } Class;\n" 17731 "}\n", 17732 MozillaBraceStyle); 17733 } 17734 17735 TEST_F(FormatTest, StroustrupBraceBreaking) { 17736 FormatStyle StroustrupBraceStyle = getLLVMStyle(); 17737 StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 17738 verifyFormat("namespace a {\n" 17739 "class A {\n" 17740 " void f()\n" 17741 " {\n" 17742 " if (true) {\n" 17743 " a();\n" 17744 " b();\n" 17745 " }\n" 17746 " }\n" 17747 " void g() { return; }\n" 17748 "};\n" 17749 "struct B {\n" 17750 " int x;\n" 17751 "};\n" 17752 "} // namespace a\n", 17753 StroustrupBraceStyle); 17754 17755 verifyFormat("void foo()\n" 17756 "{\n" 17757 " if (a) {\n" 17758 " a();\n" 17759 " }\n" 17760 " else {\n" 17761 " b();\n" 17762 " }\n" 17763 "}\n", 17764 StroustrupBraceStyle); 17765 17766 verifyFormat("#ifdef _DEBUG\n" 17767 "int foo(int i = 0)\n" 17768 "#else\n" 17769 "int foo(int i = 5)\n" 17770 "#endif\n" 17771 "{\n" 17772 " return i;\n" 17773 "}", 17774 StroustrupBraceStyle); 17775 17776 verifyFormat("void foo() {}\n" 17777 "void bar()\n" 17778 "#ifdef _DEBUG\n" 17779 "{\n" 17780 " foo();\n" 17781 "}\n" 17782 "#else\n" 17783 "{\n" 17784 "}\n" 17785 "#endif", 17786 StroustrupBraceStyle); 17787 17788 verifyFormat("void foobar() { int i = 5; }\n" 17789 "#ifdef _DEBUG\n" 17790 "void bar() {}\n" 17791 "#else\n" 17792 "void bar() { foobar(); }\n" 17793 "#endif", 17794 StroustrupBraceStyle); 17795 } 17796 17797 TEST_F(FormatTest, AllmanBraceBreaking) { 17798 FormatStyle AllmanBraceStyle = getLLVMStyle(); 17799 AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman; 17800 17801 EXPECT_EQ("namespace a\n" 17802 "{\n" 17803 "void f();\n" 17804 "void g();\n" 17805 "} // namespace a\n", 17806 format("namespace a\n" 17807 "{\n" 17808 "void f();\n" 17809 "void g();\n" 17810 "}\n", 17811 AllmanBraceStyle)); 17812 17813 verifyFormat("namespace a\n" 17814 "{\n" 17815 "class A\n" 17816 "{\n" 17817 " void f()\n" 17818 " {\n" 17819 " if (true)\n" 17820 " {\n" 17821 " a();\n" 17822 " b();\n" 17823 " }\n" 17824 " }\n" 17825 " void g() { return; }\n" 17826 "};\n" 17827 "struct B\n" 17828 "{\n" 17829 " int x;\n" 17830 "};\n" 17831 "union C\n" 17832 "{\n" 17833 "};\n" 17834 "} // namespace a", 17835 AllmanBraceStyle); 17836 17837 verifyFormat("void f()\n" 17838 "{\n" 17839 " if (true)\n" 17840 " {\n" 17841 " a();\n" 17842 " }\n" 17843 " else if (false)\n" 17844 " {\n" 17845 " b();\n" 17846 " }\n" 17847 " else\n" 17848 " {\n" 17849 " c();\n" 17850 " }\n" 17851 "}\n", 17852 AllmanBraceStyle); 17853 17854 verifyFormat("void f()\n" 17855 "{\n" 17856 " for (int i = 0; i < 10; ++i)\n" 17857 " {\n" 17858 " a();\n" 17859 " }\n" 17860 " while (false)\n" 17861 " {\n" 17862 " b();\n" 17863 " }\n" 17864 " do\n" 17865 " {\n" 17866 " c();\n" 17867 " } while (false)\n" 17868 "}\n", 17869 AllmanBraceStyle); 17870 17871 verifyFormat("void f(int a)\n" 17872 "{\n" 17873 " switch (a)\n" 17874 " {\n" 17875 " case 0:\n" 17876 " break;\n" 17877 " case 1:\n" 17878 " {\n" 17879 " break;\n" 17880 " }\n" 17881 " case 2:\n" 17882 " {\n" 17883 " }\n" 17884 " break;\n" 17885 " default:\n" 17886 " break;\n" 17887 " }\n" 17888 "}\n", 17889 AllmanBraceStyle); 17890 17891 verifyFormat("enum X\n" 17892 "{\n" 17893 " Y = 0,\n" 17894 "}\n", 17895 AllmanBraceStyle); 17896 verifyFormat("enum X\n" 17897 "{\n" 17898 " Y = 0\n" 17899 "}\n", 17900 AllmanBraceStyle); 17901 17902 verifyFormat("@interface BSApplicationController ()\n" 17903 "{\n" 17904 "@private\n" 17905 " id _extraIvar;\n" 17906 "}\n" 17907 "@end\n", 17908 AllmanBraceStyle); 17909 17910 verifyFormat("#ifdef _DEBUG\n" 17911 "int foo(int i = 0)\n" 17912 "#else\n" 17913 "int foo(int i = 5)\n" 17914 "#endif\n" 17915 "{\n" 17916 " return i;\n" 17917 "}", 17918 AllmanBraceStyle); 17919 17920 verifyFormat("void foo() {}\n" 17921 "void bar()\n" 17922 "#ifdef _DEBUG\n" 17923 "{\n" 17924 " foo();\n" 17925 "}\n" 17926 "#else\n" 17927 "{\n" 17928 "}\n" 17929 "#endif", 17930 AllmanBraceStyle); 17931 17932 verifyFormat("void foobar() { int i = 5; }\n" 17933 "#ifdef _DEBUG\n" 17934 "void bar() {}\n" 17935 "#else\n" 17936 "void bar() { foobar(); }\n" 17937 "#endif", 17938 AllmanBraceStyle); 17939 17940 EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine, 17941 FormatStyle::SLS_All); 17942 17943 verifyFormat("[](int i) { return i + 2; };\n" 17944 "[](int i, int j)\n" 17945 "{\n" 17946 " auto x = i + j;\n" 17947 " auto y = i * j;\n" 17948 " return x ^ y;\n" 17949 "};\n" 17950 "void foo()\n" 17951 "{\n" 17952 " auto shortLambda = [](int i) { return i + 2; };\n" 17953 " auto longLambda = [](int i, int j)\n" 17954 " {\n" 17955 " auto x = i + j;\n" 17956 " auto y = i * j;\n" 17957 " return x ^ y;\n" 17958 " };\n" 17959 "}", 17960 AllmanBraceStyle); 17961 17962 AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 17963 17964 verifyFormat("[](int i)\n" 17965 "{\n" 17966 " return i + 2;\n" 17967 "};\n" 17968 "[](int i, int j)\n" 17969 "{\n" 17970 " auto x = i + j;\n" 17971 " auto y = i * j;\n" 17972 " return x ^ y;\n" 17973 "};\n" 17974 "void foo()\n" 17975 "{\n" 17976 " auto shortLambda = [](int i)\n" 17977 " {\n" 17978 " return i + 2;\n" 17979 " };\n" 17980 " auto longLambda = [](int i, int j)\n" 17981 " {\n" 17982 " auto x = i + j;\n" 17983 " auto y = i * j;\n" 17984 " return x ^ y;\n" 17985 " };\n" 17986 "}", 17987 AllmanBraceStyle); 17988 17989 // Reset 17990 AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All; 17991 17992 // This shouldn't affect ObjC blocks.. 17993 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n" 17994 " // ...\n" 17995 " int i;\n" 17996 "}];", 17997 AllmanBraceStyle); 17998 verifyFormat("void (^block)(void) = ^{\n" 17999 " // ...\n" 18000 " int i;\n" 18001 "};", 18002 AllmanBraceStyle); 18003 // .. or dict literals. 18004 verifyFormat("void f()\n" 18005 "{\n" 18006 " // ...\n" 18007 " [object someMethod:@{@\"a\" : @\"b\"}];\n" 18008 "}", 18009 AllmanBraceStyle); 18010 verifyFormat("void f()\n" 18011 "{\n" 18012 " // ...\n" 18013 " [object someMethod:@{a : @\"b\"}];\n" 18014 "}", 18015 AllmanBraceStyle); 18016 verifyFormat("int f()\n" 18017 "{ // comment\n" 18018 " return 42;\n" 18019 "}", 18020 AllmanBraceStyle); 18021 18022 AllmanBraceStyle.ColumnLimit = 19; 18023 verifyFormat("void f() { int i; }", AllmanBraceStyle); 18024 AllmanBraceStyle.ColumnLimit = 18; 18025 verifyFormat("void f()\n" 18026 "{\n" 18027 " int i;\n" 18028 "}", 18029 AllmanBraceStyle); 18030 AllmanBraceStyle.ColumnLimit = 80; 18031 18032 FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle; 18033 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = 18034 FormatStyle::SIS_WithoutElse; 18035 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true; 18036 verifyFormat("void f(bool b)\n" 18037 "{\n" 18038 " if (b)\n" 18039 " {\n" 18040 " return;\n" 18041 " }\n" 18042 "}\n", 18043 BreakBeforeBraceShortIfs); 18044 verifyFormat("void f(bool b)\n" 18045 "{\n" 18046 " if constexpr (b)\n" 18047 " {\n" 18048 " return;\n" 18049 " }\n" 18050 "}\n", 18051 BreakBeforeBraceShortIfs); 18052 verifyFormat("void f(bool b)\n" 18053 "{\n" 18054 " if CONSTEXPR (b)\n" 18055 " {\n" 18056 " return;\n" 18057 " }\n" 18058 "}\n", 18059 BreakBeforeBraceShortIfs); 18060 verifyFormat("void f(bool b)\n" 18061 "{\n" 18062 " if (b) return;\n" 18063 "}\n", 18064 BreakBeforeBraceShortIfs); 18065 verifyFormat("void f(bool b)\n" 18066 "{\n" 18067 " if constexpr (b) return;\n" 18068 "}\n", 18069 BreakBeforeBraceShortIfs); 18070 verifyFormat("void f(bool b)\n" 18071 "{\n" 18072 " if CONSTEXPR (b) return;\n" 18073 "}\n", 18074 BreakBeforeBraceShortIfs); 18075 verifyFormat("void f(bool b)\n" 18076 "{\n" 18077 " while (b)\n" 18078 " {\n" 18079 " return;\n" 18080 " }\n" 18081 "}\n", 18082 BreakBeforeBraceShortIfs); 18083 } 18084 18085 TEST_F(FormatTest, WhitesmithsBraceBreaking) { 18086 FormatStyle WhitesmithsBraceStyle = getLLVMStyleWithColumns(0); 18087 WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 18088 18089 // Make a few changes to the style for testing purposes 18090 WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine = 18091 FormatStyle::SFS_Empty; 18092 WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 18093 18094 // FIXME: this test case can't decide whether there should be a blank line 18095 // after the ~D() line or not. It adds one if one doesn't exist in the test 18096 // and it removes the line if one exists. 18097 /* 18098 verifyFormat("class A;\n" 18099 "namespace B\n" 18100 " {\n" 18101 "class C;\n" 18102 "// Comment\n" 18103 "class D\n" 18104 " {\n" 18105 "public:\n" 18106 " D();\n" 18107 " ~D() {}\n" 18108 "private:\n" 18109 " enum E\n" 18110 " {\n" 18111 " F\n" 18112 " }\n" 18113 " };\n" 18114 " } // namespace B\n", 18115 WhitesmithsBraceStyle); 18116 */ 18117 18118 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None; 18119 verifyFormat("namespace a\n" 18120 " {\n" 18121 "class A\n" 18122 " {\n" 18123 " void f()\n" 18124 " {\n" 18125 " if (true)\n" 18126 " {\n" 18127 " a();\n" 18128 " b();\n" 18129 " }\n" 18130 " }\n" 18131 " void g()\n" 18132 " {\n" 18133 " return;\n" 18134 " }\n" 18135 " };\n" 18136 "struct B\n" 18137 " {\n" 18138 " int x;\n" 18139 " };\n" 18140 " } // namespace a", 18141 WhitesmithsBraceStyle); 18142 18143 verifyFormat("namespace a\n" 18144 " {\n" 18145 "namespace b\n" 18146 " {\n" 18147 "class A\n" 18148 " {\n" 18149 " void f()\n" 18150 " {\n" 18151 " if (true)\n" 18152 " {\n" 18153 " a();\n" 18154 " b();\n" 18155 " }\n" 18156 " }\n" 18157 " void g()\n" 18158 " {\n" 18159 " return;\n" 18160 " }\n" 18161 " };\n" 18162 "struct B\n" 18163 " {\n" 18164 " int x;\n" 18165 " };\n" 18166 " } // namespace b\n" 18167 " } // namespace a", 18168 WhitesmithsBraceStyle); 18169 18170 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner; 18171 verifyFormat("namespace a\n" 18172 " {\n" 18173 "namespace b\n" 18174 " {\n" 18175 " class A\n" 18176 " {\n" 18177 " void f()\n" 18178 " {\n" 18179 " if (true)\n" 18180 " {\n" 18181 " a();\n" 18182 " b();\n" 18183 " }\n" 18184 " }\n" 18185 " void g()\n" 18186 " {\n" 18187 " return;\n" 18188 " }\n" 18189 " };\n" 18190 " struct B\n" 18191 " {\n" 18192 " int x;\n" 18193 " };\n" 18194 " } // namespace b\n" 18195 " } // namespace a", 18196 WhitesmithsBraceStyle); 18197 18198 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All; 18199 verifyFormat("namespace a\n" 18200 " {\n" 18201 " namespace b\n" 18202 " {\n" 18203 " class A\n" 18204 " {\n" 18205 " void f()\n" 18206 " {\n" 18207 " if (true)\n" 18208 " {\n" 18209 " a();\n" 18210 " b();\n" 18211 " }\n" 18212 " }\n" 18213 " void g()\n" 18214 " {\n" 18215 " return;\n" 18216 " }\n" 18217 " };\n" 18218 " struct B\n" 18219 " {\n" 18220 " int x;\n" 18221 " };\n" 18222 " } // namespace b\n" 18223 " } // namespace a", 18224 WhitesmithsBraceStyle); 18225 18226 verifyFormat("void f()\n" 18227 " {\n" 18228 " if (true)\n" 18229 " {\n" 18230 " a();\n" 18231 " }\n" 18232 " else if (false)\n" 18233 " {\n" 18234 " b();\n" 18235 " }\n" 18236 " else\n" 18237 " {\n" 18238 " c();\n" 18239 " }\n" 18240 " }\n", 18241 WhitesmithsBraceStyle); 18242 18243 verifyFormat("void f()\n" 18244 " {\n" 18245 " for (int i = 0; i < 10; ++i)\n" 18246 " {\n" 18247 " a();\n" 18248 " }\n" 18249 " while (false)\n" 18250 " {\n" 18251 " b();\n" 18252 " }\n" 18253 " do\n" 18254 " {\n" 18255 " c();\n" 18256 " } while (false)\n" 18257 " }\n", 18258 WhitesmithsBraceStyle); 18259 18260 WhitesmithsBraceStyle.IndentCaseLabels = true; 18261 verifyFormat("void switchTest1(int a)\n" 18262 " {\n" 18263 " switch (a)\n" 18264 " {\n" 18265 " case 2:\n" 18266 " {\n" 18267 " }\n" 18268 " break;\n" 18269 " }\n" 18270 " }\n", 18271 WhitesmithsBraceStyle); 18272 18273 verifyFormat("void switchTest2(int a)\n" 18274 " {\n" 18275 " switch (a)\n" 18276 " {\n" 18277 " case 0:\n" 18278 " break;\n" 18279 " case 1:\n" 18280 " {\n" 18281 " break;\n" 18282 " }\n" 18283 " case 2:\n" 18284 " {\n" 18285 " }\n" 18286 " break;\n" 18287 " default:\n" 18288 " break;\n" 18289 " }\n" 18290 " }\n", 18291 WhitesmithsBraceStyle); 18292 18293 verifyFormat("void switchTest3(int a)\n" 18294 " {\n" 18295 " switch (a)\n" 18296 " {\n" 18297 " case 0:\n" 18298 " {\n" 18299 " foo(x);\n" 18300 " }\n" 18301 " break;\n" 18302 " default:\n" 18303 " {\n" 18304 " foo(1);\n" 18305 " }\n" 18306 " break;\n" 18307 " }\n" 18308 " }\n", 18309 WhitesmithsBraceStyle); 18310 18311 WhitesmithsBraceStyle.IndentCaseLabels = false; 18312 18313 verifyFormat("void switchTest4(int a)\n" 18314 " {\n" 18315 " switch (a)\n" 18316 " {\n" 18317 " case 2:\n" 18318 " {\n" 18319 " }\n" 18320 " break;\n" 18321 " }\n" 18322 " }\n", 18323 WhitesmithsBraceStyle); 18324 18325 verifyFormat("void switchTest5(int a)\n" 18326 " {\n" 18327 " switch (a)\n" 18328 " {\n" 18329 " case 0:\n" 18330 " break;\n" 18331 " case 1:\n" 18332 " {\n" 18333 " foo();\n" 18334 " break;\n" 18335 " }\n" 18336 " case 2:\n" 18337 " {\n" 18338 " }\n" 18339 " break;\n" 18340 " default:\n" 18341 " break;\n" 18342 " }\n" 18343 " }\n", 18344 WhitesmithsBraceStyle); 18345 18346 verifyFormat("void switchTest6(int a)\n" 18347 " {\n" 18348 " switch (a)\n" 18349 " {\n" 18350 " case 0:\n" 18351 " {\n" 18352 " foo(x);\n" 18353 " }\n" 18354 " break;\n" 18355 " default:\n" 18356 " {\n" 18357 " foo(1);\n" 18358 " }\n" 18359 " break;\n" 18360 " }\n" 18361 " }\n", 18362 WhitesmithsBraceStyle); 18363 18364 verifyFormat("enum X\n" 18365 " {\n" 18366 " Y = 0, // testing\n" 18367 " }\n", 18368 WhitesmithsBraceStyle); 18369 18370 verifyFormat("enum X\n" 18371 " {\n" 18372 " Y = 0\n" 18373 " }\n", 18374 WhitesmithsBraceStyle); 18375 verifyFormat("enum X\n" 18376 " {\n" 18377 " Y = 0,\n" 18378 " Z = 1\n" 18379 " };\n", 18380 WhitesmithsBraceStyle); 18381 18382 verifyFormat("@interface BSApplicationController ()\n" 18383 " {\n" 18384 "@private\n" 18385 " id _extraIvar;\n" 18386 " }\n" 18387 "@end\n", 18388 WhitesmithsBraceStyle); 18389 18390 verifyFormat("#ifdef _DEBUG\n" 18391 "int foo(int i = 0)\n" 18392 "#else\n" 18393 "int foo(int i = 5)\n" 18394 "#endif\n" 18395 " {\n" 18396 " return i;\n" 18397 " }", 18398 WhitesmithsBraceStyle); 18399 18400 verifyFormat("void foo() {}\n" 18401 "void bar()\n" 18402 "#ifdef _DEBUG\n" 18403 " {\n" 18404 " foo();\n" 18405 " }\n" 18406 "#else\n" 18407 " {\n" 18408 " }\n" 18409 "#endif", 18410 WhitesmithsBraceStyle); 18411 18412 verifyFormat("void foobar()\n" 18413 " {\n" 18414 " int i = 5;\n" 18415 " }\n" 18416 "#ifdef _DEBUG\n" 18417 "void bar()\n" 18418 " {\n" 18419 " }\n" 18420 "#else\n" 18421 "void bar()\n" 18422 " {\n" 18423 " foobar();\n" 18424 " }\n" 18425 "#endif", 18426 WhitesmithsBraceStyle); 18427 18428 // This shouldn't affect ObjC blocks.. 18429 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n" 18430 " // ...\n" 18431 " int i;\n" 18432 "}];", 18433 WhitesmithsBraceStyle); 18434 verifyFormat("void (^block)(void) = ^{\n" 18435 " // ...\n" 18436 " int i;\n" 18437 "};", 18438 WhitesmithsBraceStyle); 18439 // .. or dict literals. 18440 verifyFormat("void f()\n" 18441 " {\n" 18442 " [object someMethod:@{@\"a\" : @\"b\"}];\n" 18443 " }", 18444 WhitesmithsBraceStyle); 18445 18446 verifyFormat("int f()\n" 18447 " { // comment\n" 18448 " return 42;\n" 18449 " }", 18450 WhitesmithsBraceStyle); 18451 18452 FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle; 18453 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = 18454 FormatStyle::SIS_OnlyFirstIf; 18455 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true; 18456 verifyFormat("void f(bool b)\n" 18457 " {\n" 18458 " if (b)\n" 18459 " {\n" 18460 " return;\n" 18461 " }\n" 18462 " }\n", 18463 BreakBeforeBraceShortIfs); 18464 verifyFormat("void f(bool b)\n" 18465 " {\n" 18466 " if (b) return;\n" 18467 " }\n", 18468 BreakBeforeBraceShortIfs); 18469 verifyFormat("void f(bool b)\n" 18470 " {\n" 18471 " while (b)\n" 18472 " {\n" 18473 " return;\n" 18474 " }\n" 18475 " }\n", 18476 BreakBeforeBraceShortIfs); 18477 } 18478 18479 TEST_F(FormatTest, GNUBraceBreaking) { 18480 FormatStyle GNUBraceStyle = getLLVMStyle(); 18481 GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU; 18482 verifyFormat("namespace a\n" 18483 "{\n" 18484 "class A\n" 18485 "{\n" 18486 " void f()\n" 18487 " {\n" 18488 " int a;\n" 18489 " {\n" 18490 " int b;\n" 18491 " }\n" 18492 " if (true)\n" 18493 " {\n" 18494 " a();\n" 18495 " b();\n" 18496 " }\n" 18497 " }\n" 18498 " void g() { return; }\n" 18499 "}\n" 18500 "} // namespace a", 18501 GNUBraceStyle); 18502 18503 verifyFormat("void f()\n" 18504 "{\n" 18505 " if (true)\n" 18506 " {\n" 18507 " a();\n" 18508 " }\n" 18509 " else if (false)\n" 18510 " {\n" 18511 " b();\n" 18512 " }\n" 18513 " else\n" 18514 " {\n" 18515 " c();\n" 18516 " }\n" 18517 "}\n", 18518 GNUBraceStyle); 18519 18520 verifyFormat("void f()\n" 18521 "{\n" 18522 " for (int i = 0; i < 10; ++i)\n" 18523 " {\n" 18524 " a();\n" 18525 " }\n" 18526 " while (false)\n" 18527 " {\n" 18528 " b();\n" 18529 " }\n" 18530 " do\n" 18531 " {\n" 18532 " c();\n" 18533 " }\n" 18534 " while (false);\n" 18535 "}\n", 18536 GNUBraceStyle); 18537 18538 verifyFormat("void f(int a)\n" 18539 "{\n" 18540 " switch (a)\n" 18541 " {\n" 18542 " case 0:\n" 18543 " break;\n" 18544 " case 1:\n" 18545 " {\n" 18546 " break;\n" 18547 " }\n" 18548 " case 2:\n" 18549 " {\n" 18550 " }\n" 18551 " break;\n" 18552 " default:\n" 18553 " break;\n" 18554 " }\n" 18555 "}\n", 18556 GNUBraceStyle); 18557 18558 verifyFormat("enum X\n" 18559 "{\n" 18560 " Y = 0,\n" 18561 "}\n", 18562 GNUBraceStyle); 18563 18564 verifyFormat("@interface BSApplicationController ()\n" 18565 "{\n" 18566 "@private\n" 18567 " id _extraIvar;\n" 18568 "}\n" 18569 "@end\n", 18570 GNUBraceStyle); 18571 18572 verifyFormat("#ifdef _DEBUG\n" 18573 "int foo(int i = 0)\n" 18574 "#else\n" 18575 "int foo(int i = 5)\n" 18576 "#endif\n" 18577 "{\n" 18578 " return i;\n" 18579 "}", 18580 GNUBraceStyle); 18581 18582 verifyFormat("void foo() {}\n" 18583 "void bar()\n" 18584 "#ifdef _DEBUG\n" 18585 "{\n" 18586 " foo();\n" 18587 "}\n" 18588 "#else\n" 18589 "{\n" 18590 "}\n" 18591 "#endif", 18592 GNUBraceStyle); 18593 18594 verifyFormat("void foobar() { int i = 5; }\n" 18595 "#ifdef _DEBUG\n" 18596 "void bar() {}\n" 18597 "#else\n" 18598 "void bar() { foobar(); }\n" 18599 "#endif", 18600 GNUBraceStyle); 18601 } 18602 18603 TEST_F(FormatTest, WebKitBraceBreaking) { 18604 FormatStyle WebKitBraceStyle = getLLVMStyle(); 18605 WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit; 18606 WebKitBraceStyle.FixNamespaceComments = false; 18607 verifyFormat("namespace a {\n" 18608 "class A {\n" 18609 " void f()\n" 18610 " {\n" 18611 " if (true) {\n" 18612 " a();\n" 18613 " b();\n" 18614 " }\n" 18615 " }\n" 18616 " void g() { return; }\n" 18617 "};\n" 18618 "enum E {\n" 18619 " A,\n" 18620 " // foo\n" 18621 " B,\n" 18622 " C\n" 18623 "};\n" 18624 "struct B {\n" 18625 " int x;\n" 18626 "};\n" 18627 "}\n", 18628 WebKitBraceStyle); 18629 verifyFormat("struct S {\n" 18630 " int Type;\n" 18631 " union {\n" 18632 " int x;\n" 18633 " double y;\n" 18634 " } Value;\n" 18635 " class C {\n" 18636 " MyFavoriteType Value;\n" 18637 " } Class;\n" 18638 "};\n", 18639 WebKitBraceStyle); 18640 } 18641 18642 TEST_F(FormatTest, CatchExceptionReferenceBinding) { 18643 verifyFormat("void f() {\n" 18644 " try {\n" 18645 " } catch (const Exception &e) {\n" 18646 " }\n" 18647 "}\n", 18648 getLLVMStyle()); 18649 } 18650 18651 TEST_F(FormatTest, CatchAlignArrayOfStructuresRightAlignment) { 18652 auto Style = getLLVMStyle(); 18653 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 18654 Style.AlignConsecutiveAssignments = 18655 FormatStyle::AlignConsecutiveStyle::ACS_Consecutive; 18656 Style.AlignConsecutiveDeclarations = 18657 FormatStyle::AlignConsecutiveStyle::ACS_Consecutive; 18658 verifyFormat("struct test demo[] = {\n" 18659 " {56, 23, \"hello\"},\n" 18660 " {-1, 93463, \"world\"},\n" 18661 " { 7, 5, \"!!\"}\n" 18662 "};\n", 18663 Style); 18664 18665 verifyFormat("struct test demo[] = {\n" 18666 " {56, 23, \"hello\"}, // first line\n" 18667 " {-1, 93463, \"world\"}, // second line\n" 18668 " { 7, 5, \"!!\"} // third line\n" 18669 "};\n", 18670 Style); 18671 18672 verifyFormat("struct test demo[4] = {\n" 18673 " { 56, 23, 21, \"oh\"}, // first line\n" 18674 " { -1, 93463, 22, \"my\"}, // second line\n" 18675 " { 7, 5, 1, \"goodness\"} // third line\n" 18676 " {234, 5, 1, \"gracious\"} // fourth line\n" 18677 "};\n", 18678 Style); 18679 18680 verifyFormat("struct test demo[3] = {\n" 18681 " {56, 23, \"hello\"},\n" 18682 " {-1, 93463, \"world\"},\n" 18683 " { 7, 5, \"!!\"}\n" 18684 "};\n", 18685 Style); 18686 18687 verifyFormat("struct test demo[3] = {\n" 18688 " {int{56}, 23, \"hello\"},\n" 18689 " {int{-1}, 93463, \"world\"},\n" 18690 " { int{7}, 5, \"!!\"}\n" 18691 "};\n", 18692 Style); 18693 18694 verifyFormat("struct test demo[] = {\n" 18695 " {56, 23, \"hello\"},\n" 18696 " {-1, 93463, \"world\"},\n" 18697 " { 7, 5, \"!!\"},\n" 18698 "};\n", 18699 Style); 18700 18701 verifyFormat("test demo[] = {\n" 18702 " {56, 23, \"hello\"},\n" 18703 " {-1, 93463, \"world\"},\n" 18704 " { 7, 5, \"!!\"},\n" 18705 "};\n", 18706 Style); 18707 18708 verifyFormat("demo = std::array<struct test, 3>{\n" 18709 " test{56, 23, \"hello\"},\n" 18710 " test{-1, 93463, \"world\"},\n" 18711 " test{ 7, 5, \"!!\"},\n" 18712 "};\n", 18713 Style); 18714 18715 verifyFormat("test demo[] = {\n" 18716 " {56, 23, \"hello\"},\n" 18717 "#if X\n" 18718 " {-1, 93463, \"world\"},\n" 18719 "#endif\n" 18720 " { 7, 5, \"!!\"}\n" 18721 "};\n", 18722 Style); 18723 18724 verifyFormat( 18725 "test demo[] = {\n" 18726 " { 7, 23,\n" 18727 " \"hello world i am a very long line that really, in any\"\n" 18728 " \"just world, ought to be split over multiple lines\"},\n" 18729 " {-1, 93463, \"world\"},\n" 18730 " {56, 5, \"!!\"}\n" 18731 "};\n", 18732 Style); 18733 18734 verifyFormat("return GradForUnaryCwise(g, {\n" 18735 " {{\"sign\"}, \"Sign\", " 18736 " {\"x\", \"dy\"}},\n" 18737 " { {\"dx\"}, \"Mul\", {\"dy\"" 18738 ", \"sign\"}},\n" 18739 "});\n", 18740 Style); 18741 18742 Style.ColumnLimit = 0; 18743 EXPECT_EQ( 18744 "test demo[] = {\n" 18745 " {56, 23, \"hello world i am a very long line that really, " 18746 "in any just world, ought to be split over multiple lines\"},\n" 18747 " {-1, 93463, " 18748 " \"world\"},\n" 18749 " { 7, 5, " 18750 " \"!!\"},\n" 18751 "};", 18752 format("test demo[] = {{56, 23, \"hello world i am a very long line " 18753 "that really, in any just world, ought to be split over multiple " 18754 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 18755 Style)); 18756 18757 Style.ColumnLimit = 80; 18758 verifyFormat("test demo[] = {\n" 18759 " {56, 23, /* a comment */ \"hello\"},\n" 18760 " {-1, 93463, \"world\"},\n" 18761 " { 7, 5, \"!!\"}\n" 18762 "};\n", 18763 Style); 18764 18765 verifyFormat("test demo[] = {\n" 18766 " {56, 23, \"hello\"},\n" 18767 " {-1, 93463, \"world\" /* comment here */},\n" 18768 " { 7, 5, \"!!\"}\n" 18769 "};\n", 18770 Style); 18771 18772 verifyFormat("test demo[] = {\n" 18773 " {56, /* a comment */ 23, \"hello\"},\n" 18774 " {-1, 93463, \"world\"},\n" 18775 " { 7, 5, \"!!\"}\n" 18776 "};\n", 18777 Style); 18778 18779 Style.ColumnLimit = 20; 18780 EXPECT_EQ( 18781 "demo = std::array<\n" 18782 " struct test, 3>{\n" 18783 " test{\n" 18784 " 56, 23,\n" 18785 " \"hello \"\n" 18786 " \"world i \"\n" 18787 " \"am a very \"\n" 18788 " \"long line \"\n" 18789 " \"that \"\n" 18790 " \"really, \"\n" 18791 " \"in any \"\n" 18792 " \"just \"\n" 18793 " \"world, \"\n" 18794 " \"ought to \"\n" 18795 " \"be split \"\n" 18796 " \"over \"\n" 18797 " \"multiple \"\n" 18798 " \"lines\"},\n" 18799 " test{-1, 93463,\n" 18800 " \"world\"},\n" 18801 " test{ 7, 5,\n" 18802 " \"!!\" },\n" 18803 "};", 18804 format("demo = std::array<struct test, 3>{test{56, 23, \"hello world " 18805 "i am a very long line that really, in any just world, ought " 18806 "to be split over multiple lines\"},test{-1, 93463, \"world\"}," 18807 "test{7, 5, \"!!\"},};", 18808 Style)); 18809 // This caused a core dump by enabling Alignment in the LLVMStyle globally 18810 Style = getLLVMStyleWithColumns(50); 18811 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 18812 verifyFormat("static A x = {\n" 18813 " {{init1, init2, init3, init4},\n" 18814 " {init1, init2, init3, init4}}\n" 18815 "};", 18816 Style); 18817 Style.ColumnLimit = 100; 18818 EXPECT_EQ( 18819 "test demo[] = {\n" 18820 " {56, 23,\n" 18821 " \"hello world i am a very long line that really, in any just world" 18822 ", ought to be split over \"\n" 18823 " \"multiple lines\" },\n" 18824 " {-1, 93463, \"world\"},\n" 18825 " { 7, 5, \"!!\"},\n" 18826 "};", 18827 format("test demo[] = {{56, 23, \"hello world i am a very long line " 18828 "that really, in any just world, ought to be split over multiple " 18829 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 18830 Style)); 18831 18832 Style = getLLVMStyleWithColumns(50); 18833 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 18834 Style.AlignConsecutiveAssignments = 18835 FormatStyle::AlignConsecutiveStyle::ACS_Consecutive; 18836 Style.AlignConsecutiveDeclarations = 18837 FormatStyle::AlignConsecutiveStyle::ACS_Consecutive; 18838 verifyFormat("struct test demo[] = {\n" 18839 " {56, 23, \"hello\"},\n" 18840 " {-1, 93463, \"world\"},\n" 18841 " { 7, 5, \"!!\"}\n" 18842 "};\n" 18843 "static A x = {\n" 18844 " {{init1, init2, init3, init4},\n" 18845 " {init1, init2, init3, init4}}\n" 18846 "};", 18847 Style); 18848 Style.ColumnLimit = 100; 18849 Style.AlignConsecutiveAssignments = 18850 FormatStyle::AlignConsecutiveStyle::ACS_AcrossComments; 18851 Style.AlignConsecutiveDeclarations = 18852 FormatStyle::AlignConsecutiveStyle::ACS_AcrossComments; 18853 verifyFormat("struct test demo[] = {\n" 18854 " {56, 23, \"hello\"},\n" 18855 " {-1, 93463, \"world\"},\n" 18856 " { 7, 5, \"!!\"}\n" 18857 "};\n" 18858 "struct test demo[4] = {\n" 18859 " { 56, 23, 21, \"oh\"}, // first line\n" 18860 " { -1, 93463, 22, \"my\"}, // second line\n" 18861 " { 7, 5, 1, \"goodness\"} // third line\n" 18862 " {234, 5, 1, \"gracious\"} // fourth line\n" 18863 "};\n", 18864 Style); 18865 EXPECT_EQ( 18866 "test demo[] = {\n" 18867 " {56,\n" 18868 " \"hello world i am a very long line that really, in any just world" 18869 ", ought to be split over \"\n" 18870 " \"multiple lines\", 23},\n" 18871 " {-1, \"world\", 93463},\n" 18872 " { 7, \"!!\", 5},\n" 18873 "};", 18874 format("test demo[] = {{56, \"hello world i am a very long line " 18875 "that really, in any just world, ought to be split over multiple " 18876 "lines\", 23},{-1, \"world\", 93463},{7, \"!!\", 5},};", 18877 Style)); 18878 } 18879 18880 TEST_F(FormatTest, CatchAlignArrayOfStructuresLeftAlignment) { 18881 auto Style = getLLVMStyle(); 18882 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 18883 /* FIXME: This case gets misformatted. 18884 verifyFormat("auto foo = Items{\n" 18885 " Section{0, bar(), },\n" 18886 " Section{1, boo() }\n" 18887 "};\n", 18888 Style); 18889 */ 18890 verifyFormat("auto foo = Items{\n" 18891 " Section{\n" 18892 " 0, bar(),\n" 18893 " }\n" 18894 "};\n", 18895 Style); 18896 verifyFormat("struct test demo[] = {\n" 18897 " {56, 23, \"hello\"},\n" 18898 " {-1, 93463, \"world\"},\n" 18899 " {7, 5, \"!!\" }\n" 18900 "};\n", 18901 Style); 18902 verifyFormat("struct test demo[] = {\n" 18903 " {56, 23, \"hello\"}, // first line\n" 18904 " {-1, 93463, \"world\"}, // second line\n" 18905 " {7, 5, \"!!\" } // third line\n" 18906 "};\n", 18907 Style); 18908 verifyFormat("struct test demo[4] = {\n" 18909 " {56, 23, 21, \"oh\" }, // first line\n" 18910 " {-1, 93463, 22, \"my\" }, // second line\n" 18911 " {7, 5, 1, \"goodness\"} // third line\n" 18912 " {234, 5, 1, \"gracious\"} // fourth line\n" 18913 "};\n", 18914 Style); 18915 verifyFormat("struct test demo[3] = {\n" 18916 " {56, 23, \"hello\"},\n" 18917 " {-1, 93463, \"world\"},\n" 18918 " {7, 5, \"!!\" }\n" 18919 "};\n", 18920 Style); 18921 18922 verifyFormat("struct test demo[3] = {\n" 18923 " {int{56}, 23, \"hello\"},\n" 18924 " {int{-1}, 93463, \"world\"},\n" 18925 " {int{7}, 5, \"!!\" }\n" 18926 "};\n", 18927 Style); 18928 verifyFormat("struct test demo[] = {\n" 18929 " {56, 23, \"hello\"},\n" 18930 " {-1, 93463, \"world\"},\n" 18931 " {7, 5, \"!!\" },\n" 18932 "};\n", 18933 Style); 18934 verifyFormat("test demo[] = {\n" 18935 " {56, 23, \"hello\"},\n" 18936 " {-1, 93463, \"world\"},\n" 18937 " {7, 5, \"!!\" },\n" 18938 "};\n", 18939 Style); 18940 verifyFormat("demo = std::array<struct test, 3>{\n" 18941 " test{56, 23, \"hello\"},\n" 18942 " test{-1, 93463, \"world\"},\n" 18943 " test{7, 5, \"!!\" },\n" 18944 "};\n", 18945 Style); 18946 verifyFormat("test demo[] = {\n" 18947 " {56, 23, \"hello\"},\n" 18948 "#if X\n" 18949 " {-1, 93463, \"world\"},\n" 18950 "#endif\n" 18951 " {7, 5, \"!!\" }\n" 18952 "};\n", 18953 Style); 18954 verifyFormat( 18955 "test demo[] = {\n" 18956 " {7, 23,\n" 18957 " \"hello world i am a very long line that really, in any\"\n" 18958 " \"just world, ought to be split over multiple lines\"},\n" 18959 " {-1, 93463, \"world\" },\n" 18960 " {56, 5, \"!!\" }\n" 18961 "};\n", 18962 Style); 18963 18964 verifyFormat("return GradForUnaryCwise(g, {\n" 18965 " {{\"sign\"}, \"Sign\", {\"x\", " 18966 "\"dy\"} },\n" 18967 " {{\"dx\"}, \"Mul\", " 18968 "{\"dy\", \"sign\"}},\n" 18969 "});\n", 18970 Style); 18971 18972 Style.ColumnLimit = 0; 18973 EXPECT_EQ( 18974 "test demo[] = {\n" 18975 " {56, 23, \"hello world i am a very long line that really, in any " 18976 "just world, ought to be split over multiple lines\"},\n" 18977 " {-1, 93463, \"world\" " 18978 " },\n" 18979 " {7, 5, \"!!\" " 18980 " },\n" 18981 "};", 18982 format("test demo[] = {{56, 23, \"hello world i am a very long line " 18983 "that really, in any just world, ought to be split over multiple " 18984 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 18985 Style)); 18986 18987 Style.ColumnLimit = 80; 18988 verifyFormat("test demo[] = {\n" 18989 " {56, 23, /* a comment */ \"hello\"},\n" 18990 " {-1, 93463, \"world\" },\n" 18991 " {7, 5, \"!!\" }\n" 18992 "};\n", 18993 Style); 18994 18995 verifyFormat("test demo[] = {\n" 18996 " {56, 23, \"hello\" },\n" 18997 " {-1, 93463, \"world\" /* comment here */},\n" 18998 " {7, 5, \"!!\" }\n" 18999 "};\n", 19000 Style); 19001 19002 verifyFormat("test demo[] = {\n" 19003 " {56, /* a comment */ 23, \"hello\"},\n" 19004 " {-1, 93463, \"world\"},\n" 19005 " {7, 5, \"!!\" }\n" 19006 "};\n", 19007 Style); 19008 19009 Style.ColumnLimit = 20; 19010 EXPECT_EQ( 19011 "demo = std::array<\n" 19012 " struct test, 3>{\n" 19013 " test{\n" 19014 " 56, 23,\n" 19015 " \"hello \"\n" 19016 " \"world i \"\n" 19017 " \"am a very \"\n" 19018 " \"long line \"\n" 19019 " \"that \"\n" 19020 " \"really, \"\n" 19021 " \"in any \"\n" 19022 " \"just \"\n" 19023 " \"world, \"\n" 19024 " \"ought to \"\n" 19025 " \"be split \"\n" 19026 " \"over \"\n" 19027 " \"multiple \"\n" 19028 " \"lines\"},\n" 19029 " test{-1, 93463,\n" 19030 " \"world\"},\n" 19031 " test{7, 5,\n" 19032 " \"!!\" },\n" 19033 "};", 19034 format("demo = std::array<struct test, 3>{test{56, 23, \"hello world " 19035 "i am a very long line that really, in any just world, ought " 19036 "to be split over multiple lines\"},test{-1, 93463, \"world\"}," 19037 "test{7, 5, \"!!\"},};", 19038 Style)); 19039 19040 // This caused a core dump by enabling Alignment in the LLVMStyle globally 19041 Style = getLLVMStyleWithColumns(50); 19042 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 19043 verifyFormat("static A x = {\n" 19044 " {{init1, init2, init3, init4},\n" 19045 " {init1, init2, init3, init4}}\n" 19046 "};", 19047 Style); 19048 Style.ColumnLimit = 100; 19049 EXPECT_EQ( 19050 "test demo[] = {\n" 19051 " {56, 23,\n" 19052 " \"hello world i am a very long line that really, in any just world" 19053 ", ought to be split over \"\n" 19054 " \"multiple lines\" },\n" 19055 " {-1, 93463, \"world\"},\n" 19056 " {7, 5, \"!!\" },\n" 19057 "};", 19058 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19059 "that really, in any just world, ought to be split over multiple " 19060 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19061 Style)); 19062 } 19063 19064 TEST_F(FormatTest, UnderstandsPragmas) { 19065 verifyFormat("#pragma omp reduction(| : var)"); 19066 verifyFormat("#pragma omp reduction(+ : var)"); 19067 19068 EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string " 19069 "(including parentheses).", 19070 format("#pragma mark Any non-hyphenated or hyphenated string " 19071 "(including parentheses).")); 19072 } 19073 19074 TEST_F(FormatTest, UnderstandPragmaOption) { 19075 verifyFormat("#pragma option -C -A"); 19076 19077 EXPECT_EQ("#pragma option -C -A", format("#pragma option -C -A")); 19078 } 19079 19080 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) { 19081 FormatStyle Style = getLLVMStyleWithColumns(20); 19082 19083 // See PR41213 19084 EXPECT_EQ("/*\n" 19085 " *\t9012345\n" 19086 " * /8901\n" 19087 " */", 19088 format("/*\n" 19089 " *\t9012345 /8901\n" 19090 " */", 19091 Style)); 19092 EXPECT_EQ("/*\n" 19093 " *345678\n" 19094 " *\t/8901\n" 19095 " */", 19096 format("/*\n" 19097 " *345678\t/8901\n" 19098 " */", 19099 Style)); 19100 19101 verifyFormat("int a; // the\n" 19102 " // comment", 19103 Style); 19104 EXPECT_EQ("int a; /* first line\n" 19105 " * second\n" 19106 " * line third\n" 19107 " * line\n" 19108 " */", 19109 format("int a; /* first line\n" 19110 " * second\n" 19111 " * line third\n" 19112 " * line\n" 19113 " */", 19114 Style)); 19115 EXPECT_EQ("int a; // first line\n" 19116 " // second\n" 19117 " // line third\n" 19118 " // line", 19119 format("int a; // first line\n" 19120 " // second line\n" 19121 " // third line", 19122 Style)); 19123 19124 Style.PenaltyExcessCharacter = 90; 19125 verifyFormat("int a; // the comment", Style); 19126 EXPECT_EQ("int a; // the comment\n" 19127 " // aaa", 19128 format("int a; // the comment aaa", Style)); 19129 EXPECT_EQ("int a; /* first line\n" 19130 " * second line\n" 19131 " * third line\n" 19132 " */", 19133 format("int a; /* first line\n" 19134 " * second line\n" 19135 " * third line\n" 19136 " */", 19137 Style)); 19138 EXPECT_EQ("int a; // first line\n" 19139 " // second line\n" 19140 " // third line", 19141 format("int a; // first line\n" 19142 " // second line\n" 19143 " // third line", 19144 Style)); 19145 // FIXME: Investigate why this is not getting the same layout as the test 19146 // above. 19147 EXPECT_EQ("int a; /* first line\n" 19148 " * second line\n" 19149 " * third line\n" 19150 " */", 19151 format("int a; /* first line second line third line" 19152 "\n*/", 19153 Style)); 19154 19155 EXPECT_EQ("// foo bar baz bazfoo\n" 19156 "// foo bar foo bar\n", 19157 format("// foo bar baz bazfoo\n" 19158 "// foo bar foo bar\n", 19159 Style)); 19160 EXPECT_EQ("// foo bar baz bazfoo\n" 19161 "// foo bar foo bar\n", 19162 format("// foo bar baz bazfoo\n" 19163 "// foo bar foo bar\n", 19164 Style)); 19165 19166 // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the 19167 // next one. 19168 EXPECT_EQ("// foo bar baz bazfoo\n" 19169 "// bar foo bar\n", 19170 format("// foo bar baz bazfoo bar\n" 19171 "// foo bar\n", 19172 Style)); 19173 19174 EXPECT_EQ("// foo bar baz bazfoo\n" 19175 "// foo bar baz bazfoo\n" 19176 "// bar foo bar\n", 19177 format("// foo bar baz bazfoo\n" 19178 "// foo bar baz bazfoo bar\n" 19179 "// foo bar\n", 19180 Style)); 19181 19182 EXPECT_EQ("// foo bar baz bazfoo\n" 19183 "// foo bar baz bazfoo\n" 19184 "// bar foo bar\n", 19185 format("// foo bar baz bazfoo\n" 19186 "// foo bar baz bazfoo bar\n" 19187 "// foo bar\n", 19188 Style)); 19189 19190 // Make sure we do not keep protruding characters if strict mode reflow is 19191 // cheaper than keeping protruding characters. 19192 Style.ColumnLimit = 21; 19193 EXPECT_EQ( 19194 "// foo foo foo foo\n" 19195 "// foo foo foo foo\n" 19196 "// foo foo foo foo\n", 19197 format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style)); 19198 19199 EXPECT_EQ("int a = /* long block\n" 19200 " comment */\n" 19201 " 42;", 19202 format("int a = /* long block comment */ 42;", Style)); 19203 } 19204 19205 TEST_F(FormatTest, BreakPenaltyAfterLParen) { 19206 FormatStyle Style = getLLVMStyle(); 19207 Style.ColumnLimit = 8; 19208 Style.PenaltyExcessCharacter = 15; 19209 verifyFormat("int foo(\n" 19210 " int aaaaaaaaaaaaaaaaaaaaaaaa);", 19211 Style); 19212 Style.PenaltyBreakOpenParenthesis = 200; 19213 EXPECT_EQ("int foo(int aaaaaaaaaaaaaaaaaaaaaaaa);", 19214 format("int foo(\n" 19215 " int aaaaaaaaaaaaaaaaaaaaaaaa);", 19216 Style)); 19217 } 19218 19219 TEST_F(FormatTest, BreakPenaltyAfterCastLParen) { 19220 FormatStyle Style = getLLVMStyle(); 19221 Style.ColumnLimit = 5; 19222 Style.PenaltyExcessCharacter = 150; 19223 verifyFormat("foo((\n" 19224 " int)aaaaaaaaaaaaaaaaaaaaaaaa);", 19225 19226 Style); 19227 Style.PenaltyBreakOpenParenthesis = 100000; 19228 EXPECT_EQ("foo((int)\n" 19229 " aaaaaaaaaaaaaaaaaaaaaaaa);", 19230 format("foo((\n" 19231 "int)aaaaaaaaaaaaaaaaaaaaaaaa);", 19232 Style)); 19233 } 19234 19235 TEST_F(FormatTest, BreakPenaltyAfterForLoopLParen) { 19236 FormatStyle Style = getLLVMStyle(); 19237 Style.ColumnLimit = 4; 19238 Style.PenaltyExcessCharacter = 100; 19239 verifyFormat("for (\n" 19240 " int iiiiiiiiiiiiiiiii =\n" 19241 " 0;\n" 19242 " iiiiiiiiiiiiiiiii <\n" 19243 " 2;\n" 19244 " iiiiiiiiiiiiiiiii++) {\n" 19245 "}", 19246 19247 Style); 19248 Style.PenaltyBreakOpenParenthesis = 1250; 19249 EXPECT_EQ("for (int iiiiiiiiiiiiiiiii =\n" 19250 " 0;\n" 19251 " iiiiiiiiiiiiiiiii <\n" 19252 " 2;\n" 19253 " iiiiiiiiiiiiiiiii++) {\n" 19254 "}", 19255 format("for (\n" 19256 " int iiiiiiiiiiiiiiiii =\n" 19257 " 0;\n" 19258 " iiiiiiiiiiiiiiiii <\n" 19259 " 2;\n" 19260 " iiiiiiiiiiiiiiiii++) {\n" 19261 "}", 19262 Style)); 19263 } 19264 19265 #define EXPECT_ALL_STYLES_EQUAL(Styles) \ 19266 for (size_t i = 1; i < Styles.size(); ++i) \ 19267 EXPECT_EQ(Styles[0], Styles[i]) \ 19268 << "Style #" << i << " of " << Styles.size() << " differs from Style #0" 19269 19270 TEST_F(FormatTest, GetsPredefinedStyleByName) { 19271 SmallVector<FormatStyle, 3> Styles; 19272 Styles.resize(3); 19273 19274 Styles[0] = getLLVMStyle(); 19275 EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1])); 19276 EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2])); 19277 EXPECT_ALL_STYLES_EQUAL(Styles); 19278 19279 Styles[0] = getGoogleStyle(); 19280 EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1])); 19281 EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2])); 19282 EXPECT_ALL_STYLES_EQUAL(Styles); 19283 19284 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript); 19285 EXPECT_TRUE( 19286 getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1])); 19287 EXPECT_TRUE( 19288 getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2])); 19289 EXPECT_ALL_STYLES_EQUAL(Styles); 19290 19291 Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp); 19292 EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1])); 19293 EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2])); 19294 EXPECT_ALL_STYLES_EQUAL(Styles); 19295 19296 Styles[0] = getMozillaStyle(); 19297 EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1])); 19298 EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2])); 19299 EXPECT_ALL_STYLES_EQUAL(Styles); 19300 19301 Styles[0] = getWebKitStyle(); 19302 EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1])); 19303 EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2])); 19304 EXPECT_ALL_STYLES_EQUAL(Styles); 19305 19306 Styles[0] = getGNUStyle(); 19307 EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1])); 19308 EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2])); 19309 EXPECT_ALL_STYLES_EQUAL(Styles); 19310 19311 EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0])); 19312 } 19313 19314 TEST_F(FormatTest, GetsCorrectBasedOnStyle) { 19315 SmallVector<FormatStyle, 8> Styles; 19316 Styles.resize(2); 19317 19318 Styles[0] = getGoogleStyle(); 19319 Styles[1] = getLLVMStyle(); 19320 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value()); 19321 EXPECT_ALL_STYLES_EQUAL(Styles); 19322 19323 Styles.resize(5); 19324 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript); 19325 Styles[1] = getLLVMStyle(); 19326 Styles[1].Language = FormatStyle::LK_JavaScript; 19327 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value()); 19328 19329 Styles[2] = getLLVMStyle(); 19330 Styles[2].Language = FormatStyle::LK_JavaScript; 19331 EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n" 19332 "BasedOnStyle: Google", 19333 &Styles[2]) 19334 .value()); 19335 19336 Styles[3] = getLLVMStyle(); 19337 Styles[3].Language = FormatStyle::LK_JavaScript; 19338 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n" 19339 "Language: JavaScript", 19340 &Styles[3]) 19341 .value()); 19342 19343 Styles[4] = getLLVMStyle(); 19344 Styles[4].Language = FormatStyle::LK_JavaScript; 19345 EXPECT_EQ(0, parseConfiguration("---\n" 19346 "BasedOnStyle: LLVM\n" 19347 "IndentWidth: 123\n" 19348 "---\n" 19349 "BasedOnStyle: Google\n" 19350 "Language: JavaScript", 19351 &Styles[4]) 19352 .value()); 19353 EXPECT_ALL_STYLES_EQUAL(Styles); 19354 } 19355 19356 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME) \ 19357 Style.FIELD = false; \ 19358 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value()); \ 19359 EXPECT_TRUE(Style.FIELD); \ 19360 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value()); \ 19361 EXPECT_FALSE(Style.FIELD); 19362 19363 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD) 19364 19365 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME) \ 19366 Style.STRUCT.FIELD = false; \ 19367 EXPECT_EQ(0, \ 19368 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": true", &Style) \ 19369 .value()); \ 19370 EXPECT_TRUE(Style.STRUCT.FIELD); \ 19371 EXPECT_EQ(0, \ 19372 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": false", &Style) \ 19373 .value()); \ 19374 EXPECT_FALSE(Style.STRUCT.FIELD); 19375 19376 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD) \ 19377 CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD) 19378 19379 #define CHECK_PARSE(TEXT, FIELD, VALUE) \ 19380 EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!"; \ 19381 EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value()); \ 19382 EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!" 19383 19384 TEST_F(FormatTest, ParsesConfigurationBools) { 19385 FormatStyle Style = {}; 19386 Style.Language = FormatStyle::LK_Cpp; 19387 CHECK_PARSE_BOOL(AlignTrailingComments); 19388 CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine); 19389 CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine); 19390 CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine); 19391 CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine); 19392 CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine); 19393 CHECK_PARSE_BOOL(BinPackArguments); 19394 CHECK_PARSE_BOOL(BinPackParameters); 19395 CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations); 19396 CHECK_PARSE_BOOL(BreakBeforeTernaryOperators); 19397 CHECK_PARSE_BOOL(BreakStringLiterals); 19398 CHECK_PARSE_BOOL(CompactNamespaces); 19399 CHECK_PARSE_BOOL(DeriveLineEnding); 19400 CHECK_PARSE_BOOL(DerivePointerAlignment); 19401 CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding"); 19402 CHECK_PARSE_BOOL(DisableFormat); 19403 CHECK_PARSE_BOOL(IndentAccessModifiers); 19404 CHECK_PARSE_BOOL(IndentCaseLabels); 19405 CHECK_PARSE_BOOL(IndentCaseBlocks); 19406 CHECK_PARSE_BOOL(IndentGotoLabels); 19407 CHECK_PARSE_BOOL_FIELD(IndentRequiresClause, "IndentRequires"); 19408 CHECK_PARSE_BOOL(IndentRequiresClause); 19409 CHECK_PARSE_BOOL(IndentWrappedFunctionNames); 19410 CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks); 19411 CHECK_PARSE_BOOL(ObjCSpaceAfterProperty); 19412 CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList); 19413 CHECK_PARSE_BOOL(Cpp11BracedListStyle); 19414 CHECK_PARSE_BOOL(ReflowComments); 19415 CHECK_PARSE_BOOL(RemoveBracesLLVM); 19416 CHECK_PARSE_BOOL(SortUsingDeclarations); 19417 CHECK_PARSE_BOOL(SpacesInParentheses); 19418 CHECK_PARSE_BOOL(SpacesInSquareBrackets); 19419 CHECK_PARSE_BOOL(SpacesInConditionalStatement); 19420 CHECK_PARSE_BOOL(SpaceInEmptyBlock); 19421 CHECK_PARSE_BOOL(SpaceInEmptyParentheses); 19422 CHECK_PARSE_BOOL(SpacesInContainerLiterals); 19423 CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses); 19424 CHECK_PARSE_BOOL(SpaceAfterCStyleCast); 19425 CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword); 19426 CHECK_PARSE_BOOL(SpaceAfterLogicalNot); 19427 CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators); 19428 CHECK_PARSE_BOOL(SpaceBeforeCaseColon); 19429 CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList); 19430 CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon); 19431 CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon); 19432 CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon); 19433 CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets); 19434 CHECK_PARSE_BOOL(UseCRLF); 19435 19436 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel); 19437 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass); 19438 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum); 19439 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction); 19440 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace); 19441 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration); 19442 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct); 19443 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion); 19444 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock); 19445 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch); 19446 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse); 19447 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody); 19448 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile); 19449 CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces); 19450 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction); 19451 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord); 19452 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace); 19453 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterControlStatements); 19454 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterForeachMacros); 19455 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, 19456 AfterFunctionDeclarationName); 19457 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, 19458 AfterFunctionDefinitionName); 19459 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterIfMacros); 19460 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterOverloadedOperator); 19461 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, BeforeNonEmptyParentheses); 19462 } 19463 19464 #undef CHECK_PARSE_BOOL 19465 19466 TEST_F(FormatTest, ParsesConfiguration) { 19467 FormatStyle Style = {}; 19468 Style.Language = FormatStyle::LK_Cpp; 19469 CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234); 19470 CHECK_PARSE("ConstructorInitializerIndentWidth: 1234", 19471 ConstructorInitializerIndentWidth, 1234u); 19472 CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u); 19473 CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u); 19474 CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u); 19475 CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u); 19476 CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234", 19477 PenaltyBreakBeforeFirstCallParameter, 1234u); 19478 CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234", 19479 PenaltyBreakTemplateDeclaration, 1234u); 19480 CHECK_PARSE("PenaltyBreakOpenParenthesis: 1234", PenaltyBreakOpenParenthesis, 19481 1234u); 19482 CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u); 19483 CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234", 19484 PenaltyReturnTypeOnItsOwnLine, 1234u); 19485 CHECK_PARSE("SpacesBeforeTrailingComments: 1234", 19486 SpacesBeforeTrailingComments, 1234u); 19487 CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u); 19488 CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u); 19489 CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$"); 19490 19491 Style.QualifierAlignment = FormatStyle::QAS_Right; 19492 CHECK_PARSE("QualifierAlignment: Leave", QualifierAlignment, 19493 FormatStyle::QAS_Leave); 19494 CHECK_PARSE("QualifierAlignment: Right", QualifierAlignment, 19495 FormatStyle::QAS_Right); 19496 CHECK_PARSE("QualifierAlignment: Left", QualifierAlignment, 19497 FormatStyle::QAS_Left); 19498 CHECK_PARSE("QualifierAlignment: Custom", QualifierAlignment, 19499 FormatStyle::QAS_Custom); 19500 19501 Style.QualifierOrder.clear(); 19502 CHECK_PARSE("QualifierOrder: [ const, volatile, type ]", QualifierOrder, 19503 std::vector<std::string>({"const", "volatile", "type"})); 19504 Style.QualifierOrder.clear(); 19505 CHECK_PARSE("QualifierOrder: [const, type]", QualifierOrder, 19506 std::vector<std::string>({"const", "type"})); 19507 Style.QualifierOrder.clear(); 19508 CHECK_PARSE("QualifierOrder: [volatile, type]", QualifierOrder, 19509 std::vector<std::string>({"volatile", "type"})); 19510 19511 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 19512 CHECK_PARSE("AlignConsecutiveAssignments: None", AlignConsecutiveAssignments, 19513 FormatStyle::ACS_None); 19514 CHECK_PARSE("AlignConsecutiveAssignments: Consecutive", 19515 AlignConsecutiveAssignments, FormatStyle::ACS_Consecutive); 19516 CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLines", 19517 AlignConsecutiveAssignments, FormatStyle::ACS_AcrossEmptyLines); 19518 CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLinesAndComments", 19519 AlignConsecutiveAssignments, 19520 FormatStyle::ACS_AcrossEmptyLinesAndComments); 19521 // For backwards compability, false / true should still parse 19522 CHECK_PARSE("AlignConsecutiveAssignments: false", AlignConsecutiveAssignments, 19523 FormatStyle::ACS_None); 19524 CHECK_PARSE("AlignConsecutiveAssignments: true", AlignConsecutiveAssignments, 19525 FormatStyle::ACS_Consecutive); 19526 19527 Style.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive; 19528 CHECK_PARSE("AlignConsecutiveBitFields: None", AlignConsecutiveBitFields, 19529 FormatStyle::ACS_None); 19530 CHECK_PARSE("AlignConsecutiveBitFields: Consecutive", 19531 AlignConsecutiveBitFields, FormatStyle::ACS_Consecutive); 19532 CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLines", 19533 AlignConsecutiveBitFields, FormatStyle::ACS_AcrossEmptyLines); 19534 CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLinesAndComments", 19535 AlignConsecutiveBitFields, 19536 FormatStyle::ACS_AcrossEmptyLinesAndComments); 19537 // For backwards compability, false / true should still parse 19538 CHECK_PARSE("AlignConsecutiveBitFields: false", AlignConsecutiveBitFields, 19539 FormatStyle::ACS_None); 19540 CHECK_PARSE("AlignConsecutiveBitFields: true", AlignConsecutiveBitFields, 19541 FormatStyle::ACS_Consecutive); 19542 19543 Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 19544 CHECK_PARSE("AlignConsecutiveMacros: None", AlignConsecutiveMacros, 19545 FormatStyle::ACS_None); 19546 CHECK_PARSE("AlignConsecutiveMacros: Consecutive", AlignConsecutiveMacros, 19547 FormatStyle::ACS_Consecutive); 19548 CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLines", 19549 AlignConsecutiveMacros, FormatStyle::ACS_AcrossEmptyLines); 19550 CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLinesAndComments", 19551 AlignConsecutiveMacros, 19552 FormatStyle::ACS_AcrossEmptyLinesAndComments); 19553 // For backwards compability, false / true should still parse 19554 CHECK_PARSE("AlignConsecutiveMacros: false", AlignConsecutiveMacros, 19555 FormatStyle::ACS_None); 19556 CHECK_PARSE("AlignConsecutiveMacros: true", AlignConsecutiveMacros, 19557 FormatStyle::ACS_Consecutive); 19558 19559 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 19560 CHECK_PARSE("AlignConsecutiveDeclarations: None", 19561 AlignConsecutiveDeclarations, FormatStyle::ACS_None); 19562 CHECK_PARSE("AlignConsecutiveDeclarations: Consecutive", 19563 AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive); 19564 CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLines", 19565 AlignConsecutiveDeclarations, FormatStyle::ACS_AcrossEmptyLines); 19566 CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLinesAndComments", 19567 AlignConsecutiveDeclarations, 19568 FormatStyle::ACS_AcrossEmptyLinesAndComments); 19569 // For backwards compability, false / true should still parse 19570 CHECK_PARSE("AlignConsecutiveDeclarations: false", 19571 AlignConsecutiveDeclarations, FormatStyle::ACS_None); 19572 CHECK_PARSE("AlignConsecutiveDeclarations: true", 19573 AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive); 19574 19575 Style.PointerAlignment = FormatStyle::PAS_Middle; 19576 CHECK_PARSE("PointerAlignment: Left", PointerAlignment, 19577 FormatStyle::PAS_Left); 19578 CHECK_PARSE("PointerAlignment: Right", PointerAlignment, 19579 FormatStyle::PAS_Right); 19580 CHECK_PARSE("PointerAlignment: Middle", PointerAlignment, 19581 FormatStyle::PAS_Middle); 19582 Style.ReferenceAlignment = FormatStyle::RAS_Middle; 19583 CHECK_PARSE("ReferenceAlignment: Pointer", ReferenceAlignment, 19584 FormatStyle::RAS_Pointer); 19585 CHECK_PARSE("ReferenceAlignment: Left", ReferenceAlignment, 19586 FormatStyle::RAS_Left); 19587 CHECK_PARSE("ReferenceAlignment: Right", ReferenceAlignment, 19588 FormatStyle::RAS_Right); 19589 CHECK_PARSE("ReferenceAlignment: Middle", ReferenceAlignment, 19590 FormatStyle::RAS_Middle); 19591 // For backward compatibility: 19592 CHECK_PARSE("PointerBindsToType: Left", PointerAlignment, 19593 FormatStyle::PAS_Left); 19594 CHECK_PARSE("PointerBindsToType: Right", PointerAlignment, 19595 FormatStyle::PAS_Right); 19596 CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment, 19597 FormatStyle::PAS_Middle); 19598 19599 Style.Standard = FormatStyle::LS_Auto; 19600 CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03); 19601 CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11); 19602 CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14); 19603 CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17); 19604 CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20); 19605 CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto); 19606 CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest); 19607 // Legacy aliases: 19608 CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03); 19609 CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest); 19610 CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03); 19611 CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11); 19612 19613 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 19614 CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment", 19615 BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment); 19616 CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators, 19617 FormatStyle::BOS_None); 19618 CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators, 19619 FormatStyle::BOS_All); 19620 // For backward compatibility: 19621 CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators, 19622 FormatStyle::BOS_None); 19623 CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators, 19624 FormatStyle::BOS_All); 19625 19626 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 19627 CHECK_PARSE("BreakConstructorInitializers: BeforeComma", 19628 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma); 19629 CHECK_PARSE("BreakConstructorInitializers: AfterColon", 19630 BreakConstructorInitializers, FormatStyle::BCIS_AfterColon); 19631 CHECK_PARSE("BreakConstructorInitializers: BeforeColon", 19632 BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon); 19633 // For backward compatibility: 19634 CHECK_PARSE("BreakConstructorInitializersBeforeComma: true", 19635 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma); 19636 19637 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 19638 CHECK_PARSE("BreakInheritanceList: AfterComma", BreakInheritanceList, 19639 FormatStyle::BILS_AfterComma); 19640 CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList, 19641 FormatStyle::BILS_BeforeComma); 19642 CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList, 19643 FormatStyle::BILS_AfterColon); 19644 CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList, 19645 FormatStyle::BILS_BeforeColon); 19646 // For backward compatibility: 19647 CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList, 19648 FormatStyle::BILS_BeforeComma); 19649 19650 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 19651 CHECK_PARSE("PackConstructorInitializers: Never", PackConstructorInitializers, 19652 FormatStyle::PCIS_Never); 19653 CHECK_PARSE("PackConstructorInitializers: BinPack", 19654 PackConstructorInitializers, FormatStyle::PCIS_BinPack); 19655 CHECK_PARSE("PackConstructorInitializers: CurrentLine", 19656 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 19657 CHECK_PARSE("PackConstructorInitializers: NextLine", 19658 PackConstructorInitializers, FormatStyle::PCIS_NextLine); 19659 // For backward compatibility: 19660 CHECK_PARSE("BasedOnStyle: Google\n" 19661 "ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 19662 "AllowAllConstructorInitializersOnNextLine: false", 19663 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 19664 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 19665 CHECK_PARSE("BasedOnStyle: Google\n" 19666 "ConstructorInitializerAllOnOneLineOrOnePerLine: false", 19667 PackConstructorInitializers, FormatStyle::PCIS_BinPack); 19668 CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 19669 "AllowAllConstructorInitializersOnNextLine: true", 19670 PackConstructorInitializers, FormatStyle::PCIS_NextLine); 19671 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 19672 CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 19673 "AllowAllConstructorInitializersOnNextLine: false", 19674 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 19675 19676 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 19677 CHECK_PARSE("EmptyLineBeforeAccessModifier: Never", 19678 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never); 19679 CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave", 19680 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave); 19681 CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock", 19682 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock); 19683 CHECK_PARSE("EmptyLineBeforeAccessModifier: Always", 19684 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always); 19685 19686 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 19687 CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket, 19688 FormatStyle::BAS_Align); 19689 CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket, 19690 FormatStyle::BAS_DontAlign); 19691 CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket, 19692 FormatStyle::BAS_AlwaysBreak); 19693 CHECK_PARSE("AlignAfterOpenBracket: BlockIndent", AlignAfterOpenBracket, 19694 FormatStyle::BAS_BlockIndent); 19695 // For backward compatibility: 19696 CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket, 19697 FormatStyle::BAS_DontAlign); 19698 CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket, 19699 FormatStyle::BAS_Align); 19700 19701 Style.AlignEscapedNewlines = FormatStyle::ENAS_Left; 19702 CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines, 19703 FormatStyle::ENAS_DontAlign); 19704 CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines, 19705 FormatStyle::ENAS_Left); 19706 CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines, 19707 FormatStyle::ENAS_Right); 19708 // For backward compatibility: 19709 CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines, 19710 FormatStyle::ENAS_Left); 19711 CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines, 19712 FormatStyle::ENAS_Right); 19713 19714 Style.AlignOperands = FormatStyle::OAS_Align; 19715 CHECK_PARSE("AlignOperands: DontAlign", AlignOperands, 19716 FormatStyle::OAS_DontAlign); 19717 CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align); 19718 CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands, 19719 FormatStyle::OAS_AlignAfterOperator); 19720 // For backward compatibility: 19721 CHECK_PARSE("AlignOperands: false", AlignOperands, 19722 FormatStyle::OAS_DontAlign); 19723 CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align); 19724 19725 Style.UseTab = FormatStyle::UT_ForIndentation; 19726 CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never); 19727 CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation); 19728 CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always); 19729 CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab, 19730 FormatStyle::UT_ForContinuationAndIndentation); 19731 CHECK_PARSE("UseTab: AlignWithSpaces", UseTab, 19732 FormatStyle::UT_AlignWithSpaces); 19733 // For backward compatibility: 19734 CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never); 19735 CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always); 19736 19737 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 19738 CHECK_PARSE("AllowShortBlocksOnASingleLine: Never", 19739 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 19740 CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty", 19741 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty); 19742 CHECK_PARSE("AllowShortBlocksOnASingleLine: Always", 19743 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always); 19744 // For backward compatibility: 19745 CHECK_PARSE("AllowShortBlocksOnASingleLine: false", 19746 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 19747 CHECK_PARSE("AllowShortBlocksOnASingleLine: true", 19748 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always); 19749 19750 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 19751 CHECK_PARSE("AllowShortFunctionsOnASingleLine: None", 19752 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None); 19753 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline", 19754 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline); 19755 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty", 19756 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty); 19757 CHECK_PARSE("AllowShortFunctionsOnASingleLine: All", 19758 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All); 19759 // For backward compatibility: 19760 CHECK_PARSE("AllowShortFunctionsOnASingleLine: false", 19761 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None); 19762 CHECK_PARSE("AllowShortFunctionsOnASingleLine: true", 19763 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All); 19764 19765 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both; 19766 CHECK_PARSE("SpaceAroundPointerQualifiers: Default", 19767 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default); 19768 CHECK_PARSE("SpaceAroundPointerQualifiers: Before", 19769 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before); 19770 CHECK_PARSE("SpaceAroundPointerQualifiers: After", 19771 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After); 19772 CHECK_PARSE("SpaceAroundPointerQualifiers: Both", 19773 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both); 19774 19775 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 19776 CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens, 19777 FormatStyle::SBPO_Never); 19778 CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens, 19779 FormatStyle::SBPO_Always); 19780 CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens, 19781 FormatStyle::SBPO_ControlStatements); 19782 CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptControlMacros", 19783 SpaceBeforeParens, 19784 FormatStyle::SBPO_ControlStatementsExceptControlMacros); 19785 CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens, 19786 FormatStyle::SBPO_NonEmptyParentheses); 19787 CHECK_PARSE("SpaceBeforeParens: Custom", SpaceBeforeParens, 19788 FormatStyle::SBPO_Custom); 19789 // For backward compatibility: 19790 CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens, 19791 FormatStyle::SBPO_Never); 19792 CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens, 19793 FormatStyle::SBPO_ControlStatements); 19794 CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptForEachMacros", 19795 SpaceBeforeParens, 19796 FormatStyle::SBPO_ControlStatementsExceptControlMacros); 19797 19798 Style.ColumnLimit = 123; 19799 FormatStyle BaseStyle = getLLVMStyle(); 19800 CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit); 19801 CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u); 19802 19803 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 19804 CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces, 19805 FormatStyle::BS_Attach); 19806 CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces, 19807 FormatStyle::BS_Linux); 19808 CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces, 19809 FormatStyle::BS_Mozilla); 19810 CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces, 19811 FormatStyle::BS_Stroustrup); 19812 CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces, 19813 FormatStyle::BS_Allman); 19814 CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces, 19815 FormatStyle::BS_Whitesmiths); 19816 CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU); 19817 CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces, 19818 FormatStyle::BS_WebKit); 19819 CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces, 19820 FormatStyle::BS_Custom); 19821 19822 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never; 19823 CHECK_PARSE("BraceWrapping:\n" 19824 " AfterControlStatement: MultiLine", 19825 BraceWrapping.AfterControlStatement, 19826 FormatStyle::BWACS_MultiLine); 19827 CHECK_PARSE("BraceWrapping:\n" 19828 " AfterControlStatement: Always", 19829 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always); 19830 CHECK_PARSE("BraceWrapping:\n" 19831 " AfterControlStatement: Never", 19832 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never); 19833 // For backward compatibility: 19834 CHECK_PARSE("BraceWrapping:\n" 19835 " AfterControlStatement: true", 19836 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always); 19837 CHECK_PARSE("BraceWrapping:\n" 19838 " AfterControlStatement: false", 19839 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never); 19840 19841 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 19842 CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType, 19843 FormatStyle::RTBS_None); 19844 CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType, 19845 FormatStyle::RTBS_All); 19846 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel", 19847 AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel); 19848 CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions", 19849 AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions); 19850 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions", 19851 AlwaysBreakAfterReturnType, 19852 FormatStyle::RTBS_TopLevelDefinitions); 19853 19854 Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 19855 CHECK_PARSE("AlwaysBreakTemplateDeclarations: No", 19856 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No); 19857 CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine", 19858 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine); 19859 CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes", 19860 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes); 19861 CHECK_PARSE("AlwaysBreakTemplateDeclarations: false", 19862 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine); 19863 CHECK_PARSE("AlwaysBreakTemplateDeclarations: true", 19864 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes); 19865 19866 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All; 19867 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None", 19868 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None); 19869 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All", 19870 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All); 19871 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel", 19872 AlwaysBreakAfterDefinitionReturnType, 19873 FormatStyle::DRTBS_TopLevel); 19874 19875 Style.NamespaceIndentation = FormatStyle::NI_All; 19876 CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation, 19877 FormatStyle::NI_None); 19878 CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation, 19879 FormatStyle::NI_Inner); 19880 CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation, 19881 FormatStyle::NI_All); 19882 19883 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_OnlyFirstIf; 19884 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never", 19885 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never); 19886 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse", 19887 AllowShortIfStatementsOnASingleLine, 19888 FormatStyle::SIS_WithoutElse); 19889 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: OnlyFirstIf", 19890 AllowShortIfStatementsOnASingleLine, 19891 FormatStyle::SIS_OnlyFirstIf); 19892 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: AllIfsAndElse", 19893 AllowShortIfStatementsOnASingleLine, 19894 FormatStyle::SIS_AllIfsAndElse); 19895 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always", 19896 AllowShortIfStatementsOnASingleLine, 19897 FormatStyle::SIS_OnlyFirstIf); 19898 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false", 19899 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never); 19900 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true", 19901 AllowShortIfStatementsOnASingleLine, 19902 FormatStyle::SIS_WithoutElse); 19903 19904 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 19905 CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock, 19906 FormatStyle::IEBS_AfterExternBlock); 19907 CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock, 19908 FormatStyle::IEBS_Indent); 19909 CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock, 19910 FormatStyle::IEBS_NoIndent); 19911 CHECK_PARSE("IndentExternBlock: true", IndentExternBlock, 19912 FormatStyle::IEBS_Indent); 19913 CHECK_PARSE("IndentExternBlock: false", IndentExternBlock, 19914 FormatStyle::IEBS_NoIndent); 19915 19916 Style.BitFieldColonSpacing = FormatStyle::BFCS_None; 19917 CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing, 19918 FormatStyle::BFCS_Both); 19919 CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing, 19920 FormatStyle::BFCS_None); 19921 CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing, 19922 FormatStyle::BFCS_Before); 19923 CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing, 19924 FormatStyle::BFCS_After); 19925 19926 Style.SortJavaStaticImport = FormatStyle::SJSIO_Before; 19927 CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport, 19928 FormatStyle::SJSIO_After); 19929 CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport, 19930 FormatStyle::SJSIO_Before); 19931 19932 // FIXME: This is required because parsing a configuration simply overwrites 19933 // the first N elements of the list instead of resetting it. 19934 Style.ForEachMacros.clear(); 19935 std::vector<std::string> BoostForeach; 19936 BoostForeach.push_back("BOOST_FOREACH"); 19937 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach); 19938 std::vector<std::string> BoostAndQForeach; 19939 BoostAndQForeach.push_back("BOOST_FOREACH"); 19940 BoostAndQForeach.push_back("Q_FOREACH"); 19941 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros, 19942 BoostAndQForeach); 19943 19944 Style.IfMacros.clear(); 19945 std::vector<std::string> CustomIfs; 19946 CustomIfs.push_back("MYIF"); 19947 CHECK_PARSE("IfMacros: [MYIF]", IfMacros, CustomIfs); 19948 19949 Style.AttributeMacros.clear(); 19950 CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros, 19951 std::vector<std::string>{"__capability"}); 19952 CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros, 19953 std::vector<std::string>({"attr1", "attr2"})); 19954 19955 Style.StatementAttributeLikeMacros.clear(); 19956 CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]", 19957 StatementAttributeLikeMacros, 19958 std::vector<std::string>({"emit", "Q_EMIT"})); 19959 19960 Style.StatementMacros.clear(); 19961 CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros, 19962 std::vector<std::string>{"QUNUSED"}); 19963 CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros, 19964 std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"})); 19965 19966 Style.NamespaceMacros.clear(); 19967 CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros, 19968 std::vector<std::string>{"TESTSUITE"}); 19969 CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros, 19970 std::vector<std::string>({"TESTSUITE", "SUITE"})); 19971 19972 Style.WhitespaceSensitiveMacros.clear(); 19973 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]", 19974 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"}); 19975 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]", 19976 WhitespaceSensitiveMacros, 19977 std::vector<std::string>({"STRINGIZE", "ASSERT"})); 19978 Style.WhitespaceSensitiveMacros.clear(); 19979 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']", 19980 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"}); 19981 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']", 19982 WhitespaceSensitiveMacros, 19983 std::vector<std::string>({"STRINGIZE", "ASSERT"})); 19984 19985 Style.IncludeStyle.IncludeCategories.clear(); 19986 std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = { 19987 {"abc/.*", 2, 0, false}, {".*", 1, 0, true}}; 19988 CHECK_PARSE("IncludeCategories:\n" 19989 " - Regex: abc/.*\n" 19990 " Priority: 2\n" 19991 " - Regex: .*\n" 19992 " Priority: 1\n" 19993 " CaseSensitive: true\n", 19994 IncludeStyle.IncludeCategories, ExpectedCategories); 19995 CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex, 19996 "abc$"); 19997 CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'", 19998 IncludeStyle.IncludeIsMainSourceRegex, "abc$"); 19999 20000 Style.SortIncludes = FormatStyle::SI_Never; 20001 CHECK_PARSE("SortIncludes: true", SortIncludes, 20002 FormatStyle::SI_CaseSensitive); 20003 CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never); 20004 CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes, 20005 FormatStyle::SI_CaseInsensitive); 20006 CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes, 20007 FormatStyle::SI_CaseSensitive); 20008 CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never); 20009 20010 Style.RawStringFormats.clear(); 20011 std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = { 20012 { 20013 FormatStyle::LK_TextProto, 20014 {"pb", "proto"}, 20015 {"PARSE_TEXT_PROTO"}, 20016 /*CanonicalDelimiter=*/"", 20017 "llvm", 20018 }, 20019 { 20020 FormatStyle::LK_Cpp, 20021 {"cc", "cpp"}, 20022 {"C_CODEBLOCK", "CPPEVAL"}, 20023 /*CanonicalDelimiter=*/"cc", 20024 /*BasedOnStyle=*/"", 20025 }, 20026 }; 20027 20028 CHECK_PARSE("RawStringFormats:\n" 20029 " - Language: TextProto\n" 20030 " Delimiters:\n" 20031 " - 'pb'\n" 20032 " - 'proto'\n" 20033 " EnclosingFunctions:\n" 20034 " - 'PARSE_TEXT_PROTO'\n" 20035 " BasedOnStyle: llvm\n" 20036 " - Language: Cpp\n" 20037 " Delimiters:\n" 20038 " - 'cc'\n" 20039 " - 'cpp'\n" 20040 " EnclosingFunctions:\n" 20041 " - 'C_CODEBLOCK'\n" 20042 " - 'CPPEVAL'\n" 20043 " CanonicalDelimiter: 'cc'", 20044 RawStringFormats, ExpectedRawStringFormats); 20045 20046 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20047 " Minimum: 0\n" 20048 " Maximum: 0", 20049 SpacesInLineCommentPrefix.Minimum, 0u); 20050 EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u); 20051 Style.SpacesInLineCommentPrefix.Minimum = 1; 20052 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20053 " Minimum: 2", 20054 SpacesInLineCommentPrefix.Minimum, 0u); 20055 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20056 " Maximum: -1", 20057 SpacesInLineCommentPrefix.Maximum, -1u); 20058 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20059 " Minimum: 2", 20060 SpacesInLineCommentPrefix.Minimum, 2u); 20061 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20062 " Maximum: 1", 20063 SpacesInLineCommentPrefix.Maximum, 1u); 20064 EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u); 20065 20066 Style.SpacesInAngles = FormatStyle::SIAS_Always; 20067 CHECK_PARSE("SpacesInAngles: Never", SpacesInAngles, FormatStyle::SIAS_Never); 20068 CHECK_PARSE("SpacesInAngles: Always", SpacesInAngles, 20069 FormatStyle::SIAS_Always); 20070 CHECK_PARSE("SpacesInAngles: Leave", SpacesInAngles, FormatStyle::SIAS_Leave); 20071 // For backward compatibility: 20072 CHECK_PARSE("SpacesInAngles: false", SpacesInAngles, FormatStyle::SIAS_Never); 20073 CHECK_PARSE("SpacesInAngles: true", SpacesInAngles, FormatStyle::SIAS_Always); 20074 20075 CHECK_PARSE("RequiresClausePosition: WithPreceding", RequiresClausePosition, 20076 FormatStyle::RCPS_WithPreceding); 20077 CHECK_PARSE("RequiresClausePosition: WithFollowing", RequiresClausePosition, 20078 FormatStyle::RCPS_WithFollowing); 20079 CHECK_PARSE("RequiresClausePosition: SingleLine", RequiresClausePosition, 20080 FormatStyle::RCPS_SingleLine); 20081 CHECK_PARSE("RequiresClausePosition: OwnLine", RequiresClausePosition, 20082 FormatStyle::RCPS_OwnLine); 20083 20084 CHECK_PARSE("BreakBeforeConceptDeclarations: Never", 20085 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Never); 20086 CHECK_PARSE("BreakBeforeConceptDeclarations: Always", 20087 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always); 20088 CHECK_PARSE("BreakBeforeConceptDeclarations: Allowed", 20089 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed); 20090 // For backward compatibility: 20091 CHECK_PARSE("BreakBeforeConceptDeclarations: true", 20092 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always); 20093 CHECK_PARSE("BreakBeforeConceptDeclarations: false", 20094 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed); 20095 } 20096 20097 TEST_F(FormatTest, ParsesConfigurationWithLanguages) { 20098 FormatStyle Style = {}; 20099 Style.Language = FormatStyle::LK_Cpp; 20100 CHECK_PARSE("Language: Cpp\n" 20101 "IndentWidth: 12", 20102 IndentWidth, 12u); 20103 EXPECT_EQ(parseConfiguration("Language: JavaScript\n" 20104 "IndentWidth: 34", 20105 &Style), 20106 ParseError::Unsuitable); 20107 FormatStyle BinPackedTCS = {}; 20108 BinPackedTCS.Language = FormatStyle::LK_JavaScript; 20109 EXPECT_EQ(parseConfiguration("BinPackArguments: true\n" 20110 "InsertTrailingCommas: Wrapped", 20111 &BinPackedTCS), 20112 ParseError::BinPackTrailingCommaConflict); 20113 EXPECT_EQ(12u, Style.IndentWidth); 20114 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u); 20115 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language); 20116 20117 Style.Language = FormatStyle::LK_JavaScript; 20118 CHECK_PARSE("Language: JavaScript\n" 20119 "IndentWidth: 12", 20120 IndentWidth, 12u); 20121 CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u); 20122 EXPECT_EQ(parseConfiguration("Language: Cpp\n" 20123 "IndentWidth: 34", 20124 &Style), 20125 ParseError::Unsuitable); 20126 EXPECT_EQ(23u, Style.IndentWidth); 20127 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u); 20128 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language); 20129 20130 CHECK_PARSE("BasedOnStyle: LLVM\n" 20131 "IndentWidth: 67", 20132 IndentWidth, 67u); 20133 20134 CHECK_PARSE("---\n" 20135 "Language: JavaScript\n" 20136 "IndentWidth: 12\n" 20137 "---\n" 20138 "Language: Cpp\n" 20139 "IndentWidth: 34\n" 20140 "...\n", 20141 IndentWidth, 12u); 20142 20143 Style.Language = FormatStyle::LK_Cpp; 20144 CHECK_PARSE("---\n" 20145 "Language: JavaScript\n" 20146 "IndentWidth: 12\n" 20147 "---\n" 20148 "Language: Cpp\n" 20149 "IndentWidth: 34\n" 20150 "...\n", 20151 IndentWidth, 34u); 20152 CHECK_PARSE("---\n" 20153 "IndentWidth: 78\n" 20154 "---\n" 20155 "Language: JavaScript\n" 20156 "IndentWidth: 56\n" 20157 "...\n", 20158 IndentWidth, 78u); 20159 20160 Style.ColumnLimit = 123; 20161 Style.IndentWidth = 234; 20162 Style.BreakBeforeBraces = FormatStyle::BS_Linux; 20163 Style.TabWidth = 345; 20164 EXPECT_FALSE(parseConfiguration("---\n" 20165 "IndentWidth: 456\n" 20166 "BreakBeforeBraces: Allman\n" 20167 "---\n" 20168 "Language: JavaScript\n" 20169 "IndentWidth: 111\n" 20170 "TabWidth: 111\n" 20171 "---\n" 20172 "Language: Cpp\n" 20173 "BreakBeforeBraces: Stroustrup\n" 20174 "TabWidth: 789\n" 20175 "...\n", 20176 &Style)); 20177 EXPECT_EQ(123u, Style.ColumnLimit); 20178 EXPECT_EQ(456u, Style.IndentWidth); 20179 EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces); 20180 EXPECT_EQ(789u, Style.TabWidth); 20181 20182 EXPECT_EQ(parseConfiguration("---\n" 20183 "Language: JavaScript\n" 20184 "IndentWidth: 56\n" 20185 "---\n" 20186 "IndentWidth: 78\n" 20187 "...\n", 20188 &Style), 20189 ParseError::Error); 20190 EXPECT_EQ(parseConfiguration("---\n" 20191 "Language: JavaScript\n" 20192 "IndentWidth: 56\n" 20193 "---\n" 20194 "Language: JavaScript\n" 20195 "IndentWidth: 78\n" 20196 "...\n", 20197 &Style), 20198 ParseError::Error); 20199 20200 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language); 20201 } 20202 20203 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) { 20204 FormatStyle Style = {}; 20205 Style.Language = FormatStyle::LK_JavaScript; 20206 Style.BreakBeforeTernaryOperators = true; 20207 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value()); 20208 EXPECT_FALSE(Style.BreakBeforeTernaryOperators); 20209 20210 Style.BreakBeforeTernaryOperators = true; 20211 EXPECT_EQ(0, parseConfiguration("---\n" 20212 "BasedOnStyle: Google\n" 20213 "---\n" 20214 "Language: JavaScript\n" 20215 "IndentWidth: 76\n" 20216 "...\n", 20217 &Style) 20218 .value()); 20219 EXPECT_FALSE(Style.BreakBeforeTernaryOperators); 20220 EXPECT_EQ(76u, Style.IndentWidth); 20221 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language); 20222 } 20223 20224 TEST_F(FormatTest, ConfigurationRoundTripTest) { 20225 FormatStyle Style = getLLVMStyle(); 20226 std::string YAML = configurationAsText(Style); 20227 FormatStyle ParsedStyle = {}; 20228 ParsedStyle.Language = FormatStyle::LK_Cpp; 20229 EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value()); 20230 EXPECT_EQ(Style, ParsedStyle); 20231 } 20232 20233 TEST_F(FormatTest, WorksFor8bitEncodings) { 20234 EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n" 20235 "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n" 20236 "\"\xe7\xe8\xec\xed\xfe\xfe \"\n" 20237 "\"\xef\xee\xf0\xf3...\"", 20238 format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 " 20239 "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe " 20240 "\xef\xee\xf0\xf3...\"", 20241 getLLVMStyleWithColumns(12))); 20242 } 20243 20244 TEST_F(FormatTest, HandlesUTF8BOM) { 20245 EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf")); 20246 EXPECT_EQ("\xef\xbb\xbf#include <iostream>", 20247 format("\xef\xbb\xbf#include <iostream>")); 20248 EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>", 20249 format("\xef\xbb\xbf\n#include <iostream>")); 20250 } 20251 20252 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers. 20253 #if !defined(_MSC_VER) 20254 20255 TEST_F(FormatTest, CountsUTF8CharactersProperly) { 20256 verifyFormat("\"Однажды в студёную зимнюю пору...\"", 20257 getLLVMStyleWithColumns(35)); 20258 verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"", 20259 getLLVMStyleWithColumns(31)); 20260 verifyFormat("// Однажды в студёную зимнюю пору...", 20261 getLLVMStyleWithColumns(36)); 20262 verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32)); 20263 verifyFormat("/* Однажды в студёную зимнюю пору... */", 20264 getLLVMStyleWithColumns(39)); 20265 verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */", 20266 getLLVMStyleWithColumns(35)); 20267 } 20268 20269 TEST_F(FormatTest, SplitsUTF8Strings) { 20270 // Non-printable characters' width is currently considered to be the length in 20271 // bytes in UTF8. The characters can be displayed in very different manner 20272 // (zero-width, single width with a substitution glyph, expanded to their code 20273 // (e.g. "<8d>"), so there's no single correct way to handle them. 20274 EXPECT_EQ("\"aaaaÄ\"\n" 20275 "\"\xc2\x8d\";", 20276 format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10))); 20277 EXPECT_EQ("\"aaaaaaaÄ\"\n" 20278 "\"\xc2\x8d\";", 20279 format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10))); 20280 EXPECT_EQ("\"Однажды, в \"\n" 20281 "\"студёную \"\n" 20282 "\"зимнюю \"\n" 20283 "\"пору,\"", 20284 format("\"Однажды, в студёную зимнюю пору,\"", 20285 getLLVMStyleWithColumns(13))); 20286 EXPECT_EQ( 20287 "\"一 二 三 \"\n" 20288 "\"四 五六 \"\n" 20289 "\"七 八 九 \"\n" 20290 "\"十\"", 20291 format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11))); 20292 EXPECT_EQ("\"一\t\"\n" 20293 "\"二 \t\"\n" 20294 "\"三 四 \"\n" 20295 "\"五\t\"\n" 20296 "\"六 \t\"\n" 20297 "\"七 \"\n" 20298 "\"八九十\tqq\"", 20299 format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"", 20300 getLLVMStyleWithColumns(11))); 20301 20302 // UTF8 character in an escape sequence. 20303 EXPECT_EQ("\"aaaaaa\"\n" 20304 "\"\\\xC2\x8D\"", 20305 format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10))); 20306 } 20307 20308 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) { 20309 EXPECT_EQ("const char *sssss =\n" 20310 " \"一二三四五六七八\\\n" 20311 " 九 十\";", 20312 format("const char *sssss = \"一二三四五六七八\\\n" 20313 " 九 十\";", 20314 getLLVMStyleWithColumns(30))); 20315 } 20316 20317 TEST_F(FormatTest, SplitsUTF8LineComments) { 20318 EXPECT_EQ("// aaaaÄ\xc2\x8d", 20319 format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10))); 20320 EXPECT_EQ("// Я из лесу\n" 20321 "// вышел; был\n" 20322 "// сильный\n" 20323 "// мороз.", 20324 format("// Я из лесу вышел; был сильный мороз.", 20325 getLLVMStyleWithColumns(13))); 20326 EXPECT_EQ("// 一二三\n" 20327 "// 四五六七\n" 20328 "// 八 九\n" 20329 "// 十", 20330 format("// 一二三 四五六七 八 九 十", getLLVMStyleWithColumns(9))); 20331 } 20332 20333 TEST_F(FormatTest, SplitsUTF8BlockComments) { 20334 EXPECT_EQ("/* Гляжу,\n" 20335 " * поднимается\n" 20336 " * медленно в\n" 20337 " * гору\n" 20338 " * Лошадка,\n" 20339 " * везущая\n" 20340 " * хворосту\n" 20341 " * воз. */", 20342 format("/* Гляжу, поднимается медленно в гору\n" 20343 " * Лошадка, везущая хворосту воз. */", 20344 getLLVMStyleWithColumns(13))); 20345 EXPECT_EQ( 20346 "/* 一二三\n" 20347 " * 四五六七\n" 20348 " * 八 九\n" 20349 " * 十 */", 20350 format("/* 一二三 四五六七 八 九 十 */", getLLVMStyleWithColumns(9))); 20351 EXPECT_EQ("/* \n" 20352 " * \n" 20353 " * - */", 20354 format("/* - */", getLLVMStyleWithColumns(12))); 20355 } 20356 20357 #endif // _MSC_VER 20358 20359 TEST_F(FormatTest, ConstructorInitializerIndentWidth) { 20360 FormatStyle Style = getLLVMStyle(); 20361 20362 Style.ConstructorInitializerIndentWidth = 4; 20363 verifyFormat( 20364 "SomeClass::Constructor()\n" 20365 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20366 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20367 Style); 20368 20369 Style.ConstructorInitializerIndentWidth = 2; 20370 verifyFormat( 20371 "SomeClass::Constructor()\n" 20372 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20373 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20374 Style); 20375 20376 Style.ConstructorInitializerIndentWidth = 0; 20377 verifyFormat( 20378 "SomeClass::Constructor()\n" 20379 ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20380 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20381 Style); 20382 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 20383 verifyFormat( 20384 "SomeLongTemplateVariableName<\n" 20385 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>", 20386 Style); 20387 verifyFormat("bool smaller = 1 < " 20388 "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 20389 " " 20390 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 20391 Style); 20392 20393 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 20394 verifyFormat("SomeClass::Constructor() :\n" 20395 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n" 20396 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}", 20397 Style); 20398 } 20399 20400 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) { 20401 FormatStyle Style = getLLVMStyle(); 20402 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 20403 Style.ConstructorInitializerIndentWidth = 4; 20404 verifyFormat("SomeClass::Constructor()\n" 20405 " : a(a)\n" 20406 " , b(b)\n" 20407 " , c(c) {}", 20408 Style); 20409 verifyFormat("SomeClass::Constructor()\n" 20410 " : a(a) {}", 20411 Style); 20412 20413 Style.ColumnLimit = 0; 20414 verifyFormat("SomeClass::Constructor()\n" 20415 " : a(a) {}", 20416 Style); 20417 verifyFormat("SomeClass::Constructor() noexcept\n" 20418 " : a(a) {}", 20419 Style); 20420 verifyFormat("SomeClass::Constructor()\n" 20421 " : a(a)\n" 20422 " , b(b)\n" 20423 " , c(c) {}", 20424 Style); 20425 verifyFormat("SomeClass::Constructor()\n" 20426 " : a(a) {\n" 20427 " foo();\n" 20428 " bar();\n" 20429 "}", 20430 Style); 20431 20432 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 20433 verifyFormat("SomeClass::Constructor()\n" 20434 " : a(a)\n" 20435 " , b(b)\n" 20436 " , c(c) {\n}", 20437 Style); 20438 verifyFormat("SomeClass::Constructor()\n" 20439 " : a(a) {\n}", 20440 Style); 20441 20442 Style.ColumnLimit = 80; 20443 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 20444 Style.ConstructorInitializerIndentWidth = 2; 20445 verifyFormat("SomeClass::Constructor()\n" 20446 " : a(a)\n" 20447 " , b(b)\n" 20448 " , c(c) {}", 20449 Style); 20450 20451 Style.ConstructorInitializerIndentWidth = 0; 20452 verifyFormat("SomeClass::Constructor()\n" 20453 ": a(a)\n" 20454 ", b(b)\n" 20455 ", c(c) {}", 20456 Style); 20457 20458 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 20459 Style.ConstructorInitializerIndentWidth = 4; 20460 verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style); 20461 verifyFormat( 20462 "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n", 20463 Style); 20464 verifyFormat( 20465 "SomeClass::Constructor()\n" 20466 " : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}", 20467 Style); 20468 Style.ConstructorInitializerIndentWidth = 4; 20469 Style.ColumnLimit = 60; 20470 verifyFormat("SomeClass::Constructor()\n" 20471 " : aaaaaaaa(aaaaaaaa)\n" 20472 " , aaaaaaaa(aaaaaaaa)\n" 20473 " , aaaaaaaa(aaaaaaaa) {}", 20474 Style); 20475 } 20476 20477 TEST_F(FormatTest, ConstructorInitializersWithPreprocessorDirective) { 20478 FormatStyle Style = getLLVMStyle(); 20479 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 20480 Style.ConstructorInitializerIndentWidth = 4; 20481 verifyFormat("SomeClass::Constructor()\n" 20482 " : a{a}\n" 20483 " , b{b} {}", 20484 Style); 20485 verifyFormat("SomeClass::Constructor()\n" 20486 " : a{a}\n" 20487 "#if CONDITION\n" 20488 " , b{b}\n" 20489 "#endif\n" 20490 "{\n}", 20491 Style); 20492 Style.ConstructorInitializerIndentWidth = 2; 20493 verifyFormat("SomeClass::Constructor()\n" 20494 "#if CONDITION\n" 20495 " : a{a}\n" 20496 "#endif\n" 20497 " , b{b}\n" 20498 " , c{c} {\n}", 20499 Style); 20500 Style.ConstructorInitializerIndentWidth = 0; 20501 verifyFormat("SomeClass::Constructor()\n" 20502 ": a{a}\n" 20503 "#ifdef CONDITION\n" 20504 ", b{b}\n" 20505 "#else\n" 20506 ", c{c}\n" 20507 "#endif\n" 20508 ", d{d} {\n}", 20509 Style); 20510 Style.ConstructorInitializerIndentWidth = 4; 20511 verifyFormat("SomeClass::Constructor()\n" 20512 " : a{a}\n" 20513 "#if WINDOWS\n" 20514 "#if DEBUG\n" 20515 " , b{0}\n" 20516 "#else\n" 20517 " , b{1}\n" 20518 "#endif\n" 20519 "#else\n" 20520 "#if DEBUG\n" 20521 " , b{2}\n" 20522 "#else\n" 20523 " , b{3}\n" 20524 "#endif\n" 20525 "#endif\n" 20526 "{\n}", 20527 Style); 20528 verifyFormat("SomeClass::Constructor()\n" 20529 " : a{a}\n" 20530 "#if WINDOWS\n" 20531 " , b{0}\n" 20532 "#if DEBUG\n" 20533 " , c{0}\n" 20534 "#else\n" 20535 " , c{1}\n" 20536 "#endif\n" 20537 "#else\n" 20538 "#if DEBUG\n" 20539 " , c{2}\n" 20540 "#else\n" 20541 " , c{3}\n" 20542 "#endif\n" 20543 " , b{1}\n" 20544 "#endif\n" 20545 "{\n}", 20546 Style); 20547 } 20548 20549 TEST_F(FormatTest, Destructors) { 20550 verifyFormat("void F(int &i) { i.~int(); }"); 20551 verifyFormat("void F(int &i) { i->~int(); }"); 20552 } 20553 20554 TEST_F(FormatTest, FormatsWithWebKitStyle) { 20555 FormatStyle Style = getWebKitStyle(); 20556 20557 // Don't indent in outer namespaces. 20558 verifyFormat("namespace outer {\n" 20559 "int i;\n" 20560 "namespace inner {\n" 20561 " int i;\n" 20562 "} // namespace inner\n" 20563 "} // namespace outer\n" 20564 "namespace other_outer {\n" 20565 "int i;\n" 20566 "}", 20567 Style); 20568 20569 // Don't indent case labels. 20570 verifyFormat("switch (variable) {\n" 20571 "case 1:\n" 20572 "case 2:\n" 20573 " doSomething();\n" 20574 " break;\n" 20575 "default:\n" 20576 " ++variable;\n" 20577 "}", 20578 Style); 20579 20580 // Wrap before binary operators. 20581 EXPECT_EQ("void f()\n" 20582 "{\n" 20583 " if (aaaaaaaaaaaaaaaa\n" 20584 " && bbbbbbbbbbbbbbbbbbbbbbbb\n" 20585 " && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n" 20586 " return;\n" 20587 "}", 20588 format("void f() {\n" 20589 "if (aaaaaaaaaaaaaaaa\n" 20590 "&& bbbbbbbbbbbbbbbbbbbbbbbb\n" 20591 "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n" 20592 "return;\n" 20593 "}", 20594 Style)); 20595 20596 // Allow functions on a single line. 20597 verifyFormat("void f() { return; }", Style); 20598 20599 // Allow empty blocks on a single line and insert a space in empty blocks. 20600 EXPECT_EQ("void f() { }", format("void f() {}", Style)); 20601 EXPECT_EQ("while (true) { }", format("while (true) {}", Style)); 20602 // However, don't merge non-empty short loops. 20603 EXPECT_EQ("while (true) {\n" 20604 " continue;\n" 20605 "}", 20606 format("while (true) { continue; }", Style)); 20607 20608 // Constructor initializers are formatted one per line with the "," on the 20609 // new line. 20610 verifyFormat("Constructor()\n" 20611 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 20612 " , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n" 20613 " aaaaaaaaaaaaaa)\n" 20614 " , aaaaaaaaaaaaaaaaaaaaaaa()\n" 20615 "{\n" 20616 "}", 20617 Style); 20618 verifyFormat("SomeClass::Constructor()\n" 20619 " : a(a)\n" 20620 "{\n" 20621 "}", 20622 Style); 20623 EXPECT_EQ("SomeClass::Constructor()\n" 20624 " : a(a)\n" 20625 "{\n" 20626 "}", 20627 format("SomeClass::Constructor():a(a){}", Style)); 20628 verifyFormat("SomeClass::Constructor()\n" 20629 " : a(a)\n" 20630 " , b(b)\n" 20631 " , c(c)\n" 20632 "{\n" 20633 "}", 20634 Style); 20635 verifyFormat("SomeClass::Constructor()\n" 20636 " : a(a)\n" 20637 "{\n" 20638 " foo();\n" 20639 " bar();\n" 20640 "}", 20641 Style); 20642 20643 // Access specifiers should be aligned left. 20644 verifyFormat("class C {\n" 20645 "public:\n" 20646 " int i;\n" 20647 "};", 20648 Style); 20649 20650 // Do not align comments. 20651 verifyFormat("int a; // Do not\n" 20652 "double b; // align comments.", 20653 Style); 20654 20655 // Do not align operands. 20656 EXPECT_EQ("ASSERT(aaaa\n" 20657 " || bbbb);", 20658 format("ASSERT ( aaaa\n||bbbb);", Style)); 20659 20660 // Accept input's line breaks. 20661 EXPECT_EQ("if (aaaaaaaaaaaaaaa\n" 20662 " || bbbbbbbbbbbbbbb) {\n" 20663 " i++;\n" 20664 "}", 20665 format("if (aaaaaaaaaaaaaaa\n" 20666 "|| bbbbbbbbbbbbbbb) { i++; }", 20667 Style)); 20668 EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n" 20669 " i++;\n" 20670 "}", 20671 format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style)); 20672 20673 // Don't automatically break all macro definitions (llvm.org/PR17842). 20674 verifyFormat("#define aNumber 10", Style); 20675 // However, generally keep the line breaks that the user authored. 20676 EXPECT_EQ("#define aNumber \\\n" 20677 " 10", 20678 format("#define aNumber \\\n" 20679 " 10", 20680 Style)); 20681 20682 // Keep empty and one-element array literals on a single line. 20683 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n" 20684 " copyItems:YES];", 20685 format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n" 20686 "copyItems:YES];", 20687 Style)); 20688 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n" 20689 " copyItems:YES];", 20690 format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n" 20691 " copyItems:YES];", 20692 Style)); 20693 // FIXME: This does not seem right, there should be more indentation before 20694 // the array literal's entries. Nested blocks have the same problem. 20695 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n" 20696 " @\"a\",\n" 20697 " @\"a\"\n" 20698 "]\n" 20699 " copyItems:YES];", 20700 format("NSArray* a = [[NSArray alloc] initWithArray:@[\n" 20701 " @\"a\",\n" 20702 " @\"a\"\n" 20703 " ]\n" 20704 " copyItems:YES];", 20705 Style)); 20706 EXPECT_EQ( 20707 "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n" 20708 " copyItems:YES];", 20709 format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n" 20710 " copyItems:YES];", 20711 Style)); 20712 20713 verifyFormat("[self.a b:c c:d];", Style); 20714 EXPECT_EQ("[self.a b:c\n" 20715 " c:d];", 20716 format("[self.a b:c\n" 20717 "c:d];", 20718 Style)); 20719 } 20720 20721 TEST_F(FormatTest, FormatsLambdas) { 20722 verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n"); 20723 verifyFormat( 20724 "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n"); 20725 verifyFormat("int c = [&] { [=] { return b++; }(); }();\n"); 20726 verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n"); 20727 verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n"); 20728 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n"); 20729 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n"); 20730 verifyFormat("auto c = [a = [b = 42] {}] {};\n"); 20731 verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n"); 20732 verifyFormat("int x = f(*+[] {});"); 20733 verifyFormat("void f() {\n" 20734 " other(x.begin(), x.end(), [&](int, int) { return 1; });\n" 20735 "}\n"); 20736 verifyFormat("void f() {\n" 20737 " other(x.begin(), //\n" 20738 " x.end(), //\n" 20739 " [&](int, int) { return 1; });\n" 20740 "}\n"); 20741 verifyFormat("void f() {\n" 20742 " other.other.other.other.other(\n" 20743 " x.begin(), x.end(),\n" 20744 " [something, rather](int, int, int, int, int, int, int) { " 20745 "return 1; });\n" 20746 "}\n"); 20747 verifyFormat( 20748 "void f() {\n" 20749 " other.other.other.other.other(\n" 20750 " x.begin(), x.end(),\n" 20751 " [something, rather](int, int, int, int, int, int, int) {\n" 20752 " //\n" 20753 " });\n" 20754 "}\n"); 20755 verifyFormat("SomeFunction([]() { // A cool function...\n" 20756 " return 43;\n" 20757 "});"); 20758 EXPECT_EQ("SomeFunction([]() {\n" 20759 "#define A a\n" 20760 " return 43;\n" 20761 "});", 20762 format("SomeFunction([](){\n" 20763 "#define A a\n" 20764 "return 43;\n" 20765 "});")); 20766 verifyFormat("void f() {\n" 20767 " SomeFunction([](decltype(x), A *a) {});\n" 20768 " SomeFunction([](typeof(x), A *a) {});\n" 20769 " SomeFunction([](_Atomic(x), A *a) {});\n" 20770 " SomeFunction([](__underlying_type(x), A *a) {});\n" 20771 "}"); 20772 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 20773 " [](const aaaaaaaaaa &a) { return a; });"); 20774 verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n" 20775 " SomeOtherFunctioooooooooooooooooooooooooon();\n" 20776 "});"); 20777 verifyFormat("Constructor()\n" 20778 " : Field([] { // comment\n" 20779 " int i;\n" 20780 " }) {}"); 20781 verifyFormat("auto my_lambda = [](const string &some_parameter) {\n" 20782 " return some_parameter.size();\n" 20783 "};"); 20784 verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n" 20785 " [](const string &s) { return s; };"); 20786 verifyFormat("int i = aaaaaa ? 1 //\n" 20787 " : [] {\n" 20788 " return 2; //\n" 20789 " }();"); 20790 verifyFormat("llvm::errs() << \"number of twos is \"\n" 20791 " << std::count_if(v.begin(), v.end(), [](int x) {\n" 20792 " return x == 2; // force break\n" 20793 " });"); 20794 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 20795 " [=](int iiiiiiiiiiii) {\n" 20796 " return aaaaaaaaaaaaaaaaaaaaaaa !=\n" 20797 " aaaaaaaaaaaaaaaaaaaaaaa;\n" 20798 " });", 20799 getLLVMStyleWithColumns(60)); 20800 20801 verifyFormat("SomeFunction({[&] {\n" 20802 " // comment\n" 20803 " },\n" 20804 " [&] {\n" 20805 " // comment\n" 20806 " }});"); 20807 verifyFormat("SomeFunction({[&] {\n" 20808 " // comment\n" 20809 "}});"); 20810 verifyFormat( 20811 "virtual aaaaaaaaaaaaaaaa(\n" 20812 " std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n" 20813 " aaaaa aaaaaaaaa);"); 20814 20815 // Lambdas with return types. 20816 verifyFormat("int c = []() -> int { return 2; }();\n"); 20817 verifyFormat("int c = []() -> int * { return 2; }();\n"); 20818 verifyFormat("int c = []() -> vector<int> { return {2}; }();\n"); 20819 verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());"); 20820 verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};"); 20821 verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};"); 20822 verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};"); 20823 verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};"); 20824 verifyFormat("[a, a]() -> a<1> {};"); 20825 verifyFormat("[]() -> foo<5 + 2> { return {}; };"); 20826 verifyFormat("[]() -> foo<5 - 2> { return {}; };"); 20827 verifyFormat("[]() -> foo<5 / 2> { return {}; };"); 20828 verifyFormat("[]() -> foo<5 * 2> { return {}; };"); 20829 verifyFormat("[]() -> foo<5 % 2> { return {}; };"); 20830 verifyFormat("[]() -> foo<5 << 2> { return {}; };"); 20831 verifyFormat("[]() -> foo<!5> { return {}; };"); 20832 verifyFormat("[]() -> foo<~5> { return {}; };"); 20833 verifyFormat("[]() -> foo<5 | 2> { return {}; };"); 20834 verifyFormat("[]() -> foo<5 || 2> { return {}; };"); 20835 verifyFormat("[]() -> foo<5 & 2> { return {}; };"); 20836 verifyFormat("[]() -> foo<5 && 2> { return {}; };"); 20837 verifyFormat("[]() -> foo<5 == 2> { return {}; };"); 20838 verifyFormat("[]() -> foo<5 != 2> { return {}; };"); 20839 verifyFormat("[]() -> foo<5 >= 2> { return {}; };"); 20840 verifyFormat("[]() -> foo<5 <= 2> { return {}; };"); 20841 verifyFormat("[]() -> foo<5 < 2> { return {}; };"); 20842 verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };"); 20843 verifyFormat("namespace bar {\n" 20844 "// broken:\n" 20845 "auto foo{[]() -> foo<5 + 2> { return {}; }};\n" 20846 "} // namespace bar"); 20847 verifyFormat("namespace bar {\n" 20848 "// broken:\n" 20849 "auto foo{[]() -> foo<5 - 2> { return {}; }};\n" 20850 "} // namespace bar"); 20851 verifyFormat("namespace bar {\n" 20852 "// broken:\n" 20853 "auto foo{[]() -> foo<5 / 2> { return {}; }};\n" 20854 "} // namespace bar"); 20855 verifyFormat("namespace bar {\n" 20856 "// broken:\n" 20857 "auto foo{[]() -> foo<5 * 2> { return {}; }};\n" 20858 "} // namespace bar"); 20859 verifyFormat("namespace bar {\n" 20860 "// broken:\n" 20861 "auto foo{[]() -> foo<5 % 2> { return {}; }};\n" 20862 "} // namespace bar"); 20863 verifyFormat("namespace bar {\n" 20864 "// broken:\n" 20865 "auto foo{[]() -> foo<5 << 2> { return {}; }};\n" 20866 "} // namespace bar"); 20867 verifyFormat("namespace bar {\n" 20868 "// broken:\n" 20869 "auto foo{[]() -> foo<!5> { return {}; }};\n" 20870 "} // namespace bar"); 20871 verifyFormat("namespace bar {\n" 20872 "// broken:\n" 20873 "auto foo{[]() -> foo<~5> { return {}; }};\n" 20874 "} // namespace bar"); 20875 verifyFormat("namespace bar {\n" 20876 "// broken:\n" 20877 "auto foo{[]() -> foo<5 | 2> { return {}; }};\n" 20878 "} // namespace bar"); 20879 verifyFormat("namespace bar {\n" 20880 "// broken:\n" 20881 "auto foo{[]() -> foo<5 || 2> { return {}; }};\n" 20882 "} // namespace bar"); 20883 verifyFormat("namespace bar {\n" 20884 "// broken:\n" 20885 "auto foo{[]() -> foo<5 & 2> { return {}; }};\n" 20886 "} // namespace bar"); 20887 verifyFormat("namespace bar {\n" 20888 "// broken:\n" 20889 "auto foo{[]() -> foo<5 && 2> { return {}; }};\n" 20890 "} // namespace bar"); 20891 verifyFormat("namespace bar {\n" 20892 "// broken:\n" 20893 "auto foo{[]() -> foo<5 == 2> { return {}; }};\n" 20894 "} // namespace bar"); 20895 verifyFormat("namespace bar {\n" 20896 "// broken:\n" 20897 "auto foo{[]() -> foo<5 != 2> { return {}; }};\n" 20898 "} // namespace bar"); 20899 verifyFormat("namespace bar {\n" 20900 "// broken:\n" 20901 "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n" 20902 "} // namespace bar"); 20903 verifyFormat("namespace bar {\n" 20904 "// broken:\n" 20905 "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n" 20906 "} // namespace bar"); 20907 verifyFormat("namespace bar {\n" 20908 "// broken:\n" 20909 "auto foo{[]() -> foo<5 < 2> { return {}; }};\n" 20910 "} // namespace bar"); 20911 verifyFormat("namespace bar {\n" 20912 "// broken:\n" 20913 "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n" 20914 "} // namespace bar"); 20915 verifyFormat("[]() -> a<1> {};"); 20916 verifyFormat("[]() -> a<1> { ; };"); 20917 verifyFormat("[]() -> a<1> { ; }();"); 20918 verifyFormat("[a, a]() -> a<true> {};"); 20919 verifyFormat("[]() -> a<true> {};"); 20920 verifyFormat("[]() -> a<true> { ; };"); 20921 verifyFormat("[]() -> a<true> { ; }();"); 20922 verifyFormat("[a, a]() -> a<false> {};"); 20923 verifyFormat("[]() -> a<false> {};"); 20924 verifyFormat("[]() -> a<false> { ; };"); 20925 verifyFormat("[]() -> a<false> { ; }();"); 20926 verifyFormat("auto foo{[]() -> foo<false> { ; }};"); 20927 verifyFormat("namespace bar {\n" 20928 "auto foo{[]() -> foo<false> { ; }};\n" 20929 "} // namespace bar"); 20930 verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n" 20931 " int j) -> int {\n" 20932 " return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n" 20933 "};"); 20934 verifyFormat( 20935 "aaaaaaaaaaaaaaaaaaaaaa(\n" 20936 " [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n" 20937 " return aaaaaaaaaaaaaaaaa;\n" 20938 " });", 20939 getLLVMStyleWithColumns(70)); 20940 verifyFormat("[]() //\n" 20941 " -> int {\n" 20942 " return 1; //\n" 20943 "};"); 20944 verifyFormat("[]() -> Void<T...> {};"); 20945 verifyFormat("[a, b]() -> Tuple<T...> { return {}; };"); 20946 verifyFormat("SomeFunction({[]() -> int[] { return {}; }});"); 20947 verifyFormat("SomeFunction({[]() -> int *[] { return {}; }});"); 20948 verifyFormat("SomeFunction({[]() -> int (*)[] { return {}; }});"); 20949 verifyFormat("SomeFunction({[]() -> ns::type<int (*)[]> { return {}; }});"); 20950 verifyFormat("return int{[x = x]() { return x; }()};"); 20951 20952 // Lambdas with explicit template argument lists. 20953 verifyFormat( 20954 "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n"); 20955 verifyFormat("auto L = []<class T>(T) {\n" 20956 " {\n" 20957 " f();\n" 20958 " g();\n" 20959 " }\n" 20960 "};\n"); 20961 verifyFormat("auto L = []<class... T>(T...) {\n" 20962 " {\n" 20963 " f();\n" 20964 " g();\n" 20965 " }\n" 20966 "};\n"); 20967 verifyFormat("auto L = []<typename... T>(T...) {\n" 20968 " {\n" 20969 " f();\n" 20970 " g();\n" 20971 " }\n" 20972 "};\n"); 20973 verifyFormat("auto L = []<template <typename...> class T>(T...) {\n" 20974 " {\n" 20975 " f();\n" 20976 " g();\n" 20977 " }\n" 20978 "};\n"); 20979 verifyFormat("auto L = []</*comment*/ class... T>(T...) {\n" 20980 " {\n" 20981 " f();\n" 20982 " g();\n" 20983 " }\n" 20984 "};\n"); 20985 20986 // Multiple lambdas in the same parentheses change indentation rules. These 20987 // lambdas are forced to start on new lines. 20988 verifyFormat("SomeFunction(\n" 20989 " []() {\n" 20990 " //\n" 20991 " },\n" 20992 " []() {\n" 20993 " //\n" 20994 " });"); 20995 20996 // A lambda passed as arg0 is always pushed to the next line. 20997 verifyFormat("SomeFunction(\n" 20998 " [this] {\n" 20999 " //\n" 21000 " },\n" 21001 " 1);\n"); 21002 21003 // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like 21004 // the arg0 case above. 21005 auto Style = getGoogleStyle(); 21006 Style.BinPackArguments = false; 21007 verifyFormat("SomeFunction(\n" 21008 " a,\n" 21009 " [this] {\n" 21010 " //\n" 21011 " },\n" 21012 " b);\n", 21013 Style); 21014 verifyFormat("SomeFunction(\n" 21015 " a,\n" 21016 " [this] {\n" 21017 " //\n" 21018 " },\n" 21019 " b);\n"); 21020 21021 // A lambda with a very long line forces arg0 to be pushed out irrespective of 21022 // the BinPackArguments value (as long as the code is wide enough). 21023 verifyFormat( 21024 "something->SomeFunction(\n" 21025 " a,\n" 21026 " [this] {\n" 21027 " " 21028 "D0000000000000000000000000000000000000000000000000000000000001();\n" 21029 " },\n" 21030 " b);\n"); 21031 21032 // A multi-line lambda is pulled up as long as the introducer fits on the 21033 // previous line and there are no further args. 21034 verifyFormat("function(1, [this, that] {\n" 21035 " //\n" 21036 "});\n"); 21037 verifyFormat("function([this, that] {\n" 21038 " //\n" 21039 "});\n"); 21040 // FIXME: this format is not ideal and we should consider forcing the first 21041 // arg onto its own line. 21042 verifyFormat("function(a, b, c, //\n" 21043 " d, [this, that] {\n" 21044 " //\n" 21045 " });\n"); 21046 21047 // Multiple lambdas are treated correctly even when there is a short arg0. 21048 verifyFormat("SomeFunction(\n" 21049 " 1,\n" 21050 " [this] {\n" 21051 " //\n" 21052 " },\n" 21053 " [this] {\n" 21054 " //\n" 21055 " },\n" 21056 " 1);\n"); 21057 21058 // More complex introducers. 21059 verifyFormat("return [i, args...] {};"); 21060 21061 // Not lambdas. 21062 verifyFormat("constexpr char hello[]{\"hello\"};"); 21063 verifyFormat("double &operator[](int i) { return 0; }\n" 21064 "int i;"); 21065 verifyFormat("std::unique_ptr<int[]> foo() {}"); 21066 verifyFormat("int i = a[a][a]->f();"); 21067 verifyFormat("int i = (*b)[a]->f();"); 21068 21069 // Other corner cases. 21070 verifyFormat("void f() {\n" 21071 " bar([]() {} // Did not respect SpacesBeforeTrailingComments\n" 21072 " );\n" 21073 "}"); 21074 21075 // Lambdas created through weird macros. 21076 verifyFormat("void f() {\n" 21077 " MACRO((const AA &a) { return 1; });\n" 21078 " MACRO((AA &a) { return 1; });\n" 21079 "}"); 21080 21081 verifyFormat("if (blah_blah(whatever, whatever, [] {\n" 21082 " doo_dah();\n" 21083 " doo_dah();\n" 21084 " })) {\n" 21085 "}"); 21086 verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n" 21087 " doo_dah();\n" 21088 " doo_dah();\n" 21089 " })) {\n" 21090 "}"); 21091 verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n" 21092 " doo_dah();\n" 21093 " doo_dah();\n" 21094 " })) {\n" 21095 "}"); 21096 verifyFormat("auto lambda = []() {\n" 21097 " int a = 2\n" 21098 "#if A\n" 21099 " + 2\n" 21100 "#endif\n" 21101 " ;\n" 21102 "};"); 21103 21104 // Lambdas with complex multiline introducers. 21105 verifyFormat( 21106 "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 21107 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n" 21108 " -> ::std::unordered_set<\n" 21109 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n" 21110 " //\n" 21111 " });"); 21112 21113 FormatStyle DoNotMerge = getLLVMStyle(); 21114 DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 21115 verifyFormat("auto c = []() {\n" 21116 " return b;\n" 21117 "};", 21118 "auto c = []() { return b; };", DoNotMerge); 21119 verifyFormat("auto c = []() {\n" 21120 "};", 21121 " auto c = []() {};", DoNotMerge); 21122 21123 FormatStyle MergeEmptyOnly = getLLVMStyle(); 21124 MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty; 21125 verifyFormat("auto c = []() {\n" 21126 " return b;\n" 21127 "};", 21128 "auto c = []() {\n" 21129 " return b;\n" 21130 " };", 21131 MergeEmptyOnly); 21132 verifyFormat("auto c = []() {};", 21133 "auto c = []() {\n" 21134 "};", 21135 MergeEmptyOnly); 21136 21137 FormatStyle MergeInline = getLLVMStyle(); 21138 MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline; 21139 verifyFormat("auto c = []() {\n" 21140 " return b;\n" 21141 "};", 21142 "auto c = []() { return b; };", MergeInline); 21143 verifyFormat("function([]() { return b; })", "function([]() { return b; })", 21144 MergeInline); 21145 verifyFormat("function([]() { return b; }, a)", 21146 "function([]() { return b; }, a)", MergeInline); 21147 verifyFormat("function(a, []() { return b; })", 21148 "function(a, []() { return b; })", MergeInline); 21149 21150 // Check option "BraceWrapping.BeforeLambdaBody" and different state of 21151 // AllowShortLambdasOnASingleLine 21152 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle(); 21153 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 21154 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 21155 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21156 FormatStyle::ShortLambdaStyle::SLS_None; 21157 verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n" 21158 " []()\n" 21159 " {\n" 21160 " return 17;\n" 21161 " });", 21162 LLVMWithBeforeLambdaBody); 21163 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n" 21164 " []()\n" 21165 " {\n" 21166 " });", 21167 LLVMWithBeforeLambdaBody); 21168 verifyFormat("auto fct_SLS_None = []()\n" 21169 "{\n" 21170 " return 17;\n" 21171 "};", 21172 LLVMWithBeforeLambdaBody); 21173 verifyFormat("TwoNestedLambdas_SLS_None(\n" 21174 " []()\n" 21175 " {\n" 21176 " return Call(\n" 21177 " []()\n" 21178 " {\n" 21179 " return 17;\n" 21180 " });\n" 21181 " });", 21182 LLVMWithBeforeLambdaBody); 21183 verifyFormat("void Fct() {\n" 21184 " return {[]()\n" 21185 " {\n" 21186 " return 17;\n" 21187 " }};\n" 21188 "}", 21189 LLVMWithBeforeLambdaBody); 21190 21191 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21192 FormatStyle::ShortLambdaStyle::SLS_Empty; 21193 verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n" 21194 " []()\n" 21195 " {\n" 21196 " return 17;\n" 21197 " });", 21198 LLVMWithBeforeLambdaBody); 21199 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});", 21200 LLVMWithBeforeLambdaBody); 21201 verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL" 21202 "ongFunctionName_SLS_Empty(\n" 21203 " []() {});", 21204 LLVMWithBeforeLambdaBody); 21205 verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n" 21206 " []()\n" 21207 " {\n" 21208 " return 17;\n" 21209 " });", 21210 LLVMWithBeforeLambdaBody); 21211 verifyFormat("auto fct_SLS_Empty = []()\n" 21212 "{\n" 21213 " return 17;\n" 21214 "};", 21215 LLVMWithBeforeLambdaBody); 21216 verifyFormat("TwoNestedLambdas_SLS_Empty(\n" 21217 " []()\n" 21218 " {\n" 21219 " return Call([]() {});\n" 21220 " });", 21221 LLVMWithBeforeLambdaBody); 21222 verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n" 21223 " []()\n" 21224 " {\n" 21225 " return Call([]() {});\n" 21226 " });", 21227 LLVMWithBeforeLambdaBody); 21228 verifyFormat( 21229 "FctWithLongLineInLambda_SLS_Empty(\n" 21230 " []()\n" 21231 " {\n" 21232 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21233 " AndShouldNotBeConsiderAsInline,\n" 21234 " LambdaBodyMustBeBreak);\n" 21235 " });", 21236 LLVMWithBeforeLambdaBody); 21237 21238 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21239 FormatStyle::ShortLambdaStyle::SLS_Inline; 21240 verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });", 21241 LLVMWithBeforeLambdaBody); 21242 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});", 21243 LLVMWithBeforeLambdaBody); 21244 verifyFormat("auto fct_SLS_Inline = []()\n" 21245 "{\n" 21246 " return 17;\n" 21247 "};", 21248 LLVMWithBeforeLambdaBody); 21249 verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return " 21250 "17; }); });", 21251 LLVMWithBeforeLambdaBody); 21252 verifyFormat( 21253 "FctWithLongLineInLambda_SLS_Inline(\n" 21254 " []()\n" 21255 " {\n" 21256 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21257 " AndShouldNotBeConsiderAsInline,\n" 21258 " LambdaBodyMustBeBreak);\n" 21259 " });", 21260 LLVMWithBeforeLambdaBody); 21261 verifyFormat("FctWithMultipleParams_SLS_Inline(" 21262 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n" 21263 " []() { return 17; });", 21264 LLVMWithBeforeLambdaBody); 21265 verifyFormat( 21266 "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });", 21267 LLVMWithBeforeLambdaBody); 21268 21269 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21270 FormatStyle::ShortLambdaStyle::SLS_All; 21271 verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });", 21272 LLVMWithBeforeLambdaBody); 21273 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});", 21274 LLVMWithBeforeLambdaBody); 21275 verifyFormat("auto fct_SLS_All = []() { return 17; };", 21276 LLVMWithBeforeLambdaBody); 21277 verifyFormat("FctWithOneParam_SLS_All(\n" 21278 " []()\n" 21279 " {\n" 21280 " // A cool function...\n" 21281 " return 43;\n" 21282 " });", 21283 LLVMWithBeforeLambdaBody); 21284 verifyFormat("FctWithMultipleParams_SLS_All(" 21285 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n" 21286 " []() { return 17; });", 21287 LLVMWithBeforeLambdaBody); 21288 verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });", 21289 LLVMWithBeforeLambdaBody); 21290 verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });", 21291 LLVMWithBeforeLambdaBody); 21292 verifyFormat( 21293 "FctWithLongLineInLambda_SLS_All(\n" 21294 " []()\n" 21295 " {\n" 21296 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21297 " AndShouldNotBeConsiderAsInline,\n" 21298 " LambdaBodyMustBeBreak);\n" 21299 " });", 21300 LLVMWithBeforeLambdaBody); 21301 verifyFormat( 21302 "auto fct_SLS_All = []()\n" 21303 "{\n" 21304 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21305 " AndShouldNotBeConsiderAsInline,\n" 21306 " LambdaBodyMustBeBreak);\n" 21307 "};", 21308 LLVMWithBeforeLambdaBody); 21309 LLVMWithBeforeLambdaBody.BinPackParameters = false; 21310 verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);", 21311 LLVMWithBeforeLambdaBody); 21312 verifyFormat( 21313 "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n" 21314 " FirstParam,\n" 21315 " SecondParam,\n" 21316 " ThirdParam,\n" 21317 " FourthParam);", 21318 LLVMWithBeforeLambdaBody); 21319 verifyFormat("FctWithLongLineInLambda_SLS_All(\n" 21320 " []() { return " 21321 "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n" 21322 " FirstParam,\n" 21323 " SecondParam,\n" 21324 " ThirdParam,\n" 21325 " FourthParam);", 21326 LLVMWithBeforeLambdaBody); 21327 verifyFormat( 21328 "FctWithLongLineInLambda_SLS_All(FirstParam,\n" 21329 " SecondParam,\n" 21330 " ThirdParam,\n" 21331 " FourthParam,\n" 21332 " []() { return SomeValueNotSoLong; });", 21333 LLVMWithBeforeLambdaBody); 21334 verifyFormat("FctWithLongLineInLambda_SLS_All(\n" 21335 " []()\n" 21336 " {\n" 21337 " return " 21338 "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB" 21339 "eConsiderAsInline;\n" 21340 " });", 21341 LLVMWithBeforeLambdaBody); 21342 verifyFormat( 21343 "FctWithLongLineInLambda_SLS_All(\n" 21344 " []()\n" 21345 " {\n" 21346 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21347 " AndShouldNotBeConsiderAsInline,\n" 21348 " LambdaBodyMustBeBreak);\n" 21349 " });", 21350 LLVMWithBeforeLambdaBody); 21351 verifyFormat("FctWithTwoParams_SLS_All(\n" 21352 " []()\n" 21353 " {\n" 21354 " // A cool function...\n" 21355 " return 43;\n" 21356 " },\n" 21357 " 87);", 21358 LLVMWithBeforeLambdaBody); 21359 verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);", 21360 LLVMWithBeforeLambdaBody); 21361 verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });", 21362 LLVMWithBeforeLambdaBody); 21363 verifyFormat( 21364 "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });", 21365 LLVMWithBeforeLambdaBody); 21366 verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; " 21367 "}); }, x);", 21368 LLVMWithBeforeLambdaBody); 21369 verifyFormat("TwoNestedLambdas_SLS_All(\n" 21370 " []()\n" 21371 " {\n" 21372 " // A cool function...\n" 21373 " return Call([]() { return 17; });\n" 21374 " });", 21375 LLVMWithBeforeLambdaBody); 21376 verifyFormat("TwoNestedLambdas_SLS_All(\n" 21377 " []()\n" 21378 " {\n" 21379 " return Call(\n" 21380 " []()\n" 21381 " {\n" 21382 " // A cool function...\n" 21383 " return 17;\n" 21384 " });\n" 21385 " });", 21386 LLVMWithBeforeLambdaBody); 21387 21388 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21389 FormatStyle::ShortLambdaStyle::SLS_None; 21390 21391 verifyFormat("auto select = [this]() -> const Library::Object *\n" 21392 "{\n" 21393 " return MyAssignment::SelectFromList(this);\n" 21394 "};\n", 21395 LLVMWithBeforeLambdaBody); 21396 21397 verifyFormat("auto select = [this]() -> const Library::Object &\n" 21398 "{\n" 21399 " return MyAssignment::SelectFromList(this);\n" 21400 "};\n", 21401 LLVMWithBeforeLambdaBody); 21402 21403 verifyFormat("auto select = [this]() -> std::unique_ptr<Object>\n" 21404 "{\n" 21405 " return MyAssignment::SelectFromList(this);\n" 21406 "};\n", 21407 LLVMWithBeforeLambdaBody); 21408 21409 verifyFormat("namespace test {\n" 21410 "class Test {\n" 21411 "public:\n" 21412 " Test() = default;\n" 21413 "};\n" 21414 "} // namespace test", 21415 LLVMWithBeforeLambdaBody); 21416 21417 // Lambdas with different indentation styles. 21418 Style = getLLVMStyleWithColumns(100); 21419 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 21420 " return promise.then(\n" 21421 " [this, &someVariable, someObject = " 21422 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21423 " return someObject.startAsyncAction().then(\n" 21424 " [this, &someVariable](AsyncActionResult result) " 21425 "mutable { result.processMore(); });\n" 21426 " });\n" 21427 "}\n", 21428 format("SomeResult doSomething(SomeObject promise) {\n" 21429 " return promise.then([this, &someVariable, someObject = " 21430 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21431 " return someObject.startAsyncAction().then([this, " 21432 "&someVariable](AsyncActionResult result) mutable {\n" 21433 " result.processMore();\n" 21434 " });\n" 21435 " });\n" 21436 "}\n", 21437 Style)); 21438 Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope; 21439 verifyFormat("test() {\n" 21440 " ([]() -> {\n" 21441 " int b = 32;\n" 21442 " return 3;\n" 21443 " }).foo();\n" 21444 "}", 21445 Style); 21446 verifyFormat("test() {\n" 21447 " []() -> {\n" 21448 " int b = 32;\n" 21449 " return 3;\n" 21450 " }\n" 21451 "}", 21452 Style); 21453 verifyFormat("std::sort(v.begin(), v.end(),\n" 21454 " [](const auto &someLongArgumentName, const auto " 21455 "&someOtherLongArgumentName) {\n" 21456 " return someLongArgumentName.someMemberVariable < " 21457 "someOtherLongArgumentName.someMemberVariable;\n" 21458 "});", 21459 Style); 21460 verifyFormat("test() {\n" 21461 " (\n" 21462 " []() -> {\n" 21463 " int b = 32;\n" 21464 " return 3;\n" 21465 " },\n" 21466 " foo, bar)\n" 21467 " .foo();\n" 21468 "}", 21469 Style); 21470 verifyFormat("test() {\n" 21471 " ([]() -> {\n" 21472 " int b = 32;\n" 21473 " return 3;\n" 21474 " })\n" 21475 " .foo()\n" 21476 " .bar();\n" 21477 "}", 21478 Style); 21479 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 21480 " return promise.then(\n" 21481 " [this, &someVariable, someObject = " 21482 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21483 " return someObject.startAsyncAction().then(\n" 21484 " [this, &someVariable](AsyncActionResult result) mutable { " 21485 "result.processMore(); });\n" 21486 " });\n" 21487 "}\n", 21488 format("SomeResult doSomething(SomeObject promise) {\n" 21489 " return promise.then([this, &someVariable, someObject = " 21490 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21491 " return someObject.startAsyncAction().then([this, " 21492 "&someVariable](AsyncActionResult result) mutable {\n" 21493 " result.processMore();\n" 21494 " });\n" 21495 " });\n" 21496 "}\n", 21497 Style)); 21498 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 21499 " return promise.then([this, &someVariable] {\n" 21500 " return someObject.startAsyncAction().then(\n" 21501 " [this, &someVariable](AsyncActionResult result) mutable { " 21502 "result.processMore(); });\n" 21503 " });\n" 21504 "}\n", 21505 format("SomeResult doSomething(SomeObject promise) {\n" 21506 " return promise.then([this, &someVariable] {\n" 21507 " return someObject.startAsyncAction().then([this, " 21508 "&someVariable](AsyncActionResult result) mutable {\n" 21509 " result.processMore();\n" 21510 " });\n" 21511 " });\n" 21512 "}\n", 21513 Style)); 21514 Style = getGoogleStyle(); 21515 Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope; 21516 EXPECT_EQ("#define A \\\n" 21517 " [] { \\\n" 21518 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 21519 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n" 21520 " }", 21521 format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 21522 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }", 21523 Style)); 21524 // TODO: The current formatting has a minor issue that's not worth fixing 21525 // right now whereby the closing brace is indented relative to the signature 21526 // instead of being aligned. This only happens with macros. 21527 } 21528 21529 TEST_F(FormatTest, LambdaWithLineComments) { 21530 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle(); 21531 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 21532 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 21533 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21534 FormatStyle::ShortLambdaStyle::SLS_All; 21535 21536 verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody); 21537 verifyFormat("auto k = []() // comment\n" 21538 "{ return; }", 21539 LLVMWithBeforeLambdaBody); 21540 verifyFormat("auto k = []() /* comment */ { return; }", 21541 LLVMWithBeforeLambdaBody); 21542 verifyFormat("auto k = []() /* comment */ /* comment */ { return; }", 21543 LLVMWithBeforeLambdaBody); 21544 verifyFormat("auto k = []() // X\n" 21545 "{ return; }", 21546 LLVMWithBeforeLambdaBody); 21547 verifyFormat( 21548 "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" 21549 "{ return; }", 21550 LLVMWithBeforeLambdaBody); 21551 } 21552 21553 TEST_F(FormatTest, EmptyLinesInLambdas) { 21554 verifyFormat("auto lambda = []() {\n" 21555 " x(); //\n" 21556 "};", 21557 "auto lambda = []() {\n" 21558 "\n" 21559 " x(); //\n" 21560 "\n" 21561 "};"); 21562 } 21563 21564 TEST_F(FormatTest, FormatsBlocks) { 21565 FormatStyle ShortBlocks = getLLVMStyle(); 21566 ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 21567 verifyFormat("int (^Block)(int, int);", ShortBlocks); 21568 verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks); 21569 verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks); 21570 verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks); 21571 verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks); 21572 verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks); 21573 21574 verifyFormat("foo(^{ bar(); });", ShortBlocks); 21575 verifyFormat("foo(a, ^{ bar(); });", ShortBlocks); 21576 verifyFormat("{ void (^block)(Object *x); }", ShortBlocks); 21577 21578 verifyFormat("[operation setCompletionBlock:^{\n" 21579 " [self onOperationDone];\n" 21580 "}];"); 21581 verifyFormat("int i = {[operation setCompletionBlock:^{\n" 21582 " [self onOperationDone];\n" 21583 "}]};"); 21584 verifyFormat("[operation setCompletionBlock:^(int *i) {\n" 21585 " f();\n" 21586 "}];"); 21587 verifyFormat("int a = [operation block:^int(int *i) {\n" 21588 " return 1;\n" 21589 "}];"); 21590 verifyFormat("[myObject doSomethingWith:arg1\n" 21591 " aaa:^int(int *a) {\n" 21592 " return 1;\n" 21593 " }\n" 21594 " bbb:f(a * bbbbbbbb)];"); 21595 21596 verifyFormat("[operation setCompletionBlock:^{\n" 21597 " [self.delegate newDataAvailable];\n" 21598 "}];", 21599 getLLVMStyleWithColumns(60)); 21600 verifyFormat("dispatch_async(_fileIOQueue, ^{\n" 21601 " NSString *path = [self sessionFilePath];\n" 21602 " if (path) {\n" 21603 " // ...\n" 21604 " }\n" 21605 "});"); 21606 verifyFormat("[[SessionService sharedService]\n" 21607 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 21608 " if (window) {\n" 21609 " [self windowDidLoad:window];\n" 21610 " } else {\n" 21611 " [self errorLoadingWindow];\n" 21612 " }\n" 21613 " }];"); 21614 verifyFormat("void (^largeBlock)(void) = ^{\n" 21615 " // ...\n" 21616 "};\n", 21617 getLLVMStyleWithColumns(40)); 21618 verifyFormat("[[SessionService sharedService]\n" 21619 " loadWindowWithCompletionBlock: //\n" 21620 " ^(SessionWindow *window) {\n" 21621 " if (window) {\n" 21622 " [self windowDidLoad:window];\n" 21623 " } else {\n" 21624 " [self errorLoadingWindow];\n" 21625 " }\n" 21626 " }];", 21627 getLLVMStyleWithColumns(60)); 21628 verifyFormat("[myObject doSomethingWith:arg1\n" 21629 " firstBlock:^(Foo *a) {\n" 21630 " // ...\n" 21631 " int i;\n" 21632 " }\n" 21633 " secondBlock:^(Bar *b) {\n" 21634 " // ...\n" 21635 " int i;\n" 21636 " }\n" 21637 " thirdBlock:^Foo(Bar *b) {\n" 21638 " // ...\n" 21639 " int i;\n" 21640 " }];"); 21641 verifyFormat("[myObject doSomethingWith:arg1\n" 21642 " firstBlock:-1\n" 21643 " secondBlock:^(Bar *b) {\n" 21644 " // ...\n" 21645 " int i;\n" 21646 " }];"); 21647 21648 verifyFormat("f(^{\n" 21649 " @autoreleasepool {\n" 21650 " if (a) {\n" 21651 " g();\n" 21652 " }\n" 21653 " }\n" 21654 "});"); 21655 verifyFormat("Block b = ^int *(A *a, B *b) {}"); 21656 verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n" 21657 "};"); 21658 21659 FormatStyle FourIndent = getLLVMStyle(); 21660 FourIndent.ObjCBlockIndentWidth = 4; 21661 verifyFormat("[operation setCompletionBlock:^{\n" 21662 " [self onOperationDone];\n" 21663 "}];", 21664 FourIndent); 21665 } 21666 21667 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) { 21668 FormatStyle ZeroColumn = getLLVMStyleWithColumns(0); 21669 21670 verifyFormat("[[SessionService sharedService] " 21671 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 21672 " if (window) {\n" 21673 " [self windowDidLoad:window];\n" 21674 " } else {\n" 21675 " [self errorLoadingWindow];\n" 21676 " }\n" 21677 "}];", 21678 ZeroColumn); 21679 EXPECT_EQ("[[SessionService sharedService]\n" 21680 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 21681 " if (window) {\n" 21682 " [self windowDidLoad:window];\n" 21683 " } else {\n" 21684 " [self errorLoadingWindow];\n" 21685 " }\n" 21686 " }];", 21687 format("[[SessionService sharedService]\n" 21688 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 21689 " if (window) {\n" 21690 " [self windowDidLoad:window];\n" 21691 " } else {\n" 21692 " [self errorLoadingWindow];\n" 21693 " }\n" 21694 "}];", 21695 ZeroColumn)); 21696 verifyFormat("[myObject doSomethingWith:arg1\n" 21697 " firstBlock:^(Foo *a) {\n" 21698 " // ...\n" 21699 " int i;\n" 21700 " }\n" 21701 " secondBlock:^(Bar *b) {\n" 21702 " // ...\n" 21703 " int i;\n" 21704 " }\n" 21705 " thirdBlock:^Foo(Bar *b) {\n" 21706 " // ...\n" 21707 " int i;\n" 21708 " }];", 21709 ZeroColumn); 21710 verifyFormat("f(^{\n" 21711 " @autoreleasepool {\n" 21712 " if (a) {\n" 21713 " g();\n" 21714 " }\n" 21715 " }\n" 21716 "});", 21717 ZeroColumn); 21718 verifyFormat("void (^largeBlock)(void) = ^{\n" 21719 " // ...\n" 21720 "};", 21721 ZeroColumn); 21722 21723 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 21724 EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };", 21725 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn)); 21726 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 21727 EXPECT_EQ("void (^largeBlock)(void) = ^{\n" 21728 " int i;\n" 21729 "};", 21730 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn)); 21731 } 21732 21733 TEST_F(FormatTest, SupportsCRLF) { 21734 EXPECT_EQ("int a;\r\n" 21735 "int b;\r\n" 21736 "int c;\r\n", 21737 format("int a;\r\n" 21738 " int b;\r\n" 21739 " int c;\r\n", 21740 getLLVMStyle())); 21741 EXPECT_EQ("int a;\r\n" 21742 "int b;\r\n" 21743 "int c;\r\n", 21744 format("int a;\r\n" 21745 " int b;\n" 21746 " int c;\r\n", 21747 getLLVMStyle())); 21748 EXPECT_EQ("int a;\n" 21749 "int b;\n" 21750 "int c;\n", 21751 format("int a;\r\n" 21752 " int b;\n" 21753 " int c;\n", 21754 getLLVMStyle())); 21755 EXPECT_EQ("\"aaaaaaa \"\r\n" 21756 "\"bbbbbbb\";\r\n", 21757 format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10))); 21758 EXPECT_EQ("#define A \\\r\n" 21759 " b; \\\r\n" 21760 " c; \\\r\n" 21761 " d;\r\n", 21762 format("#define A \\\r\n" 21763 " b; \\\r\n" 21764 " c; d; \r\n", 21765 getGoogleStyle())); 21766 21767 EXPECT_EQ("/*\r\n" 21768 "multi line block comments\r\n" 21769 "should not introduce\r\n" 21770 "an extra carriage return\r\n" 21771 "*/\r\n", 21772 format("/*\r\n" 21773 "multi line block comments\r\n" 21774 "should not introduce\r\n" 21775 "an extra carriage return\r\n" 21776 "*/\r\n")); 21777 EXPECT_EQ("/*\r\n" 21778 "\r\n" 21779 "*/", 21780 format("/*\r\n" 21781 " \r\r\r\n" 21782 "*/")); 21783 21784 FormatStyle style = getLLVMStyle(); 21785 21786 style.DeriveLineEnding = true; 21787 style.UseCRLF = false; 21788 EXPECT_EQ("union FooBarBazQux {\n" 21789 " int foo;\n" 21790 " int bar;\n" 21791 " int baz;\n" 21792 "};", 21793 format("union FooBarBazQux {\r\n" 21794 " int foo;\n" 21795 " int bar;\r\n" 21796 " int baz;\n" 21797 "};", 21798 style)); 21799 style.UseCRLF = true; 21800 EXPECT_EQ("union FooBarBazQux {\r\n" 21801 " int foo;\r\n" 21802 " int bar;\r\n" 21803 " int baz;\r\n" 21804 "};", 21805 format("union FooBarBazQux {\r\n" 21806 " int foo;\n" 21807 " int bar;\r\n" 21808 " int baz;\n" 21809 "};", 21810 style)); 21811 21812 style.DeriveLineEnding = false; 21813 style.UseCRLF = false; 21814 EXPECT_EQ("union FooBarBazQux {\n" 21815 " int foo;\n" 21816 " int bar;\n" 21817 " int baz;\n" 21818 " int qux;\n" 21819 "};", 21820 format("union FooBarBazQux {\r\n" 21821 " int foo;\n" 21822 " int bar;\r\n" 21823 " int baz;\n" 21824 " int qux;\r\n" 21825 "};", 21826 style)); 21827 style.UseCRLF = true; 21828 EXPECT_EQ("union FooBarBazQux {\r\n" 21829 " int foo;\r\n" 21830 " int bar;\r\n" 21831 " int baz;\r\n" 21832 " int qux;\r\n" 21833 "};", 21834 format("union FooBarBazQux {\r\n" 21835 " int foo;\n" 21836 " int bar;\r\n" 21837 " int baz;\n" 21838 " int qux;\n" 21839 "};", 21840 style)); 21841 21842 style.DeriveLineEnding = true; 21843 style.UseCRLF = false; 21844 EXPECT_EQ("union FooBarBazQux {\r\n" 21845 " int foo;\r\n" 21846 " int bar;\r\n" 21847 " int baz;\r\n" 21848 " int qux;\r\n" 21849 "};", 21850 format("union FooBarBazQux {\r\n" 21851 " int foo;\n" 21852 " int bar;\r\n" 21853 " int baz;\n" 21854 " int qux;\r\n" 21855 "};", 21856 style)); 21857 style.UseCRLF = true; 21858 EXPECT_EQ("union FooBarBazQux {\n" 21859 " int foo;\n" 21860 " int bar;\n" 21861 " int baz;\n" 21862 " int qux;\n" 21863 "};", 21864 format("union FooBarBazQux {\r\n" 21865 " int foo;\n" 21866 " int bar;\r\n" 21867 " int baz;\n" 21868 " int qux;\n" 21869 "};", 21870 style)); 21871 } 21872 21873 TEST_F(FormatTest, MunchSemicolonAfterBlocks) { 21874 verifyFormat("MY_CLASS(C) {\n" 21875 " int i;\n" 21876 " int j;\n" 21877 "};"); 21878 } 21879 21880 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) { 21881 FormatStyle TwoIndent = getLLVMStyleWithColumns(15); 21882 TwoIndent.ContinuationIndentWidth = 2; 21883 21884 EXPECT_EQ("int i =\n" 21885 " longFunction(\n" 21886 " arg);", 21887 format("int i = longFunction(arg);", TwoIndent)); 21888 21889 FormatStyle SixIndent = getLLVMStyleWithColumns(20); 21890 SixIndent.ContinuationIndentWidth = 6; 21891 21892 EXPECT_EQ("int i =\n" 21893 " longFunction(\n" 21894 " arg);", 21895 format("int i = longFunction(arg);", SixIndent)); 21896 } 21897 21898 TEST_F(FormatTest, WrappedClosingParenthesisIndent) { 21899 FormatStyle Style = getLLVMStyle(); 21900 verifyFormat("int Foo::getter(\n" 21901 " //\n" 21902 ") const {\n" 21903 " return foo;\n" 21904 "}", 21905 Style); 21906 verifyFormat("void Foo::setter(\n" 21907 " //\n" 21908 ") {\n" 21909 " foo = 1;\n" 21910 "}", 21911 Style); 21912 } 21913 21914 TEST_F(FormatTest, SpacesInAngles) { 21915 FormatStyle Spaces = getLLVMStyle(); 21916 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 21917 21918 verifyFormat("vector< ::std::string > x1;", Spaces); 21919 verifyFormat("Foo< int, Bar > x2;", Spaces); 21920 verifyFormat("Foo< ::int, ::Bar > x3;", Spaces); 21921 21922 verifyFormat("static_cast< int >(arg);", Spaces); 21923 verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces); 21924 verifyFormat("f< int, float >();", Spaces); 21925 verifyFormat("template <> g() {}", Spaces); 21926 verifyFormat("template < std::vector< int > > f() {}", Spaces); 21927 verifyFormat("std::function< void(int, int) > fct;", Spaces); 21928 verifyFormat("void inFunction() { std::function< void(int, int) > fct; }", 21929 Spaces); 21930 21931 Spaces.Standard = FormatStyle::LS_Cpp03; 21932 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 21933 verifyFormat("A< A< int > >();", Spaces); 21934 21935 Spaces.SpacesInAngles = FormatStyle::SIAS_Never; 21936 verifyFormat("A<A<int> >();", Spaces); 21937 21938 Spaces.SpacesInAngles = FormatStyle::SIAS_Leave; 21939 verifyFormat("vector< ::std::string> x4;", "vector<::std::string> x4;", 21940 Spaces); 21941 verifyFormat("vector< ::std::string > x4;", "vector<::std::string > x4;", 21942 Spaces); 21943 21944 verifyFormat("A<A<int> >();", Spaces); 21945 verifyFormat("A<A<int> >();", "A<A<int>>();", Spaces); 21946 verifyFormat("A< A< int > >();", Spaces); 21947 21948 Spaces.Standard = FormatStyle::LS_Cpp11; 21949 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 21950 verifyFormat("A< A< int > >();", Spaces); 21951 21952 Spaces.SpacesInAngles = FormatStyle::SIAS_Never; 21953 verifyFormat("vector<::std::string> x4;", Spaces); 21954 verifyFormat("vector<int> x5;", Spaces); 21955 verifyFormat("Foo<int, Bar> x6;", Spaces); 21956 verifyFormat("Foo<::int, ::Bar> x7;", Spaces); 21957 21958 verifyFormat("A<A<int>>();", Spaces); 21959 21960 Spaces.SpacesInAngles = FormatStyle::SIAS_Leave; 21961 verifyFormat("vector<::std::string> x4;", Spaces); 21962 verifyFormat("vector< ::std::string > x4;", Spaces); 21963 verifyFormat("vector<int> x5;", Spaces); 21964 verifyFormat("vector< int > x5;", Spaces); 21965 verifyFormat("Foo<int, Bar> x6;", Spaces); 21966 verifyFormat("Foo< int, Bar > x6;", Spaces); 21967 verifyFormat("Foo<::int, ::Bar> x7;", Spaces); 21968 verifyFormat("Foo< ::int, ::Bar > x7;", Spaces); 21969 21970 verifyFormat("A<A<int>>();", Spaces); 21971 verifyFormat("A< A< int > >();", Spaces); 21972 verifyFormat("A<A<int > >();", Spaces); 21973 verifyFormat("A< A< int>>();", Spaces); 21974 21975 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 21976 verifyFormat("// clang-format off\n" 21977 "foo<<<1, 1>>>();\n" 21978 "// clang-format on\n", 21979 Spaces); 21980 verifyFormat("// clang-format off\n" 21981 "foo< < <1, 1> > >();\n" 21982 "// clang-format on\n", 21983 Spaces); 21984 } 21985 21986 TEST_F(FormatTest, SpaceAfterTemplateKeyword) { 21987 FormatStyle Style = getLLVMStyle(); 21988 Style.SpaceAfterTemplateKeyword = false; 21989 verifyFormat("template<int> void foo();", Style); 21990 } 21991 21992 TEST_F(FormatTest, TripleAngleBrackets) { 21993 verifyFormat("f<<<1, 1>>>();"); 21994 verifyFormat("f<<<1, 1, 1, s>>>();"); 21995 verifyFormat("f<<<a, b, c, d>>>();"); 21996 EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();")); 21997 verifyFormat("f<param><<<1, 1>>>();"); 21998 verifyFormat("f<1><<<1, 1>>>();"); 21999 EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();")); 22000 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 22001 "aaaaaaaaaaa<<<\n 1, 1>>>();"); 22002 verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n" 22003 " <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();"); 22004 } 22005 22006 TEST_F(FormatTest, MergeLessLessAtEnd) { 22007 verifyFormat("<<"); 22008 EXPECT_EQ("< < <", format("\\\n<<<")); 22009 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 22010 "aaallvm::outs() <<"); 22011 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 22012 "aaaallvm::outs()\n <<"); 22013 } 22014 22015 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) { 22016 std::string code = "#if A\n" 22017 "#if B\n" 22018 "a.\n" 22019 "#endif\n" 22020 " a = 1;\n" 22021 "#else\n" 22022 "#endif\n" 22023 "#if C\n" 22024 "#else\n" 22025 "#endif\n"; 22026 EXPECT_EQ(code, format(code)); 22027 } 22028 22029 TEST_F(FormatTest, HandleConflictMarkers) { 22030 // Git/SVN conflict markers. 22031 EXPECT_EQ("int a;\n" 22032 "void f() {\n" 22033 " callme(some(parameter1,\n" 22034 "<<<<<<< text by the vcs\n" 22035 " parameter2),\n" 22036 "||||||| text by the vcs\n" 22037 " parameter2),\n" 22038 " parameter3,\n" 22039 "======= text by the vcs\n" 22040 " parameter2, parameter3),\n" 22041 ">>>>>>> text by the vcs\n" 22042 " otherparameter);\n", 22043 format("int a;\n" 22044 "void f() {\n" 22045 " callme(some(parameter1,\n" 22046 "<<<<<<< text by the vcs\n" 22047 " parameter2),\n" 22048 "||||||| text by the vcs\n" 22049 " parameter2),\n" 22050 " parameter3,\n" 22051 "======= text by the vcs\n" 22052 " parameter2,\n" 22053 " parameter3),\n" 22054 ">>>>>>> text by the vcs\n" 22055 " otherparameter);\n")); 22056 22057 // Perforce markers. 22058 EXPECT_EQ("void f() {\n" 22059 " function(\n" 22060 ">>>> text by the vcs\n" 22061 " parameter,\n" 22062 "==== text by the vcs\n" 22063 " parameter,\n" 22064 "==== text by the vcs\n" 22065 " parameter,\n" 22066 "<<<< text by the vcs\n" 22067 " parameter);\n", 22068 format("void f() {\n" 22069 " function(\n" 22070 ">>>> text by the vcs\n" 22071 " parameter,\n" 22072 "==== text by the vcs\n" 22073 " parameter,\n" 22074 "==== text by the vcs\n" 22075 " parameter,\n" 22076 "<<<< text by the vcs\n" 22077 " parameter);\n")); 22078 22079 EXPECT_EQ("<<<<<<<\n" 22080 "|||||||\n" 22081 "=======\n" 22082 ">>>>>>>", 22083 format("<<<<<<<\n" 22084 "|||||||\n" 22085 "=======\n" 22086 ">>>>>>>")); 22087 22088 EXPECT_EQ("<<<<<<<\n" 22089 "|||||||\n" 22090 "int i;\n" 22091 "=======\n" 22092 ">>>>>>>", 22093 format("<<<<<<<\n" 22094 "|||||||\n" 22095 "int i;\n" 22096 "=======\n" 22097 ">>>>>>>")); 22098 22099 // FIXME: Handle parsing of macros around conflict markers correctly: 22100 EXPECT_EQ("#define Macro \\\n" 22101 "<<<<<<<\n" 22102 "Something \\\n" 22103 "|||||||\n" 22104 "Else \\\n" 22105 "=======\n" 22106 "Other \\\n" 22107 ">>>>>>>\n" 22108 " End int i;\n", 22109 format("#define Macro \\\n" 22110 "<<<<<<<\n" 22111 " Something \\\n" 22112 "|||||||\n" 22113 " Else \\\n" 22114 "=======\n" 22115 " Other \\\n" 22116 ">>>>>>>\n" 22117 " End\n" 22118 "int i;\n")); 22119 22120 verifyFormat(R"(==== 22121 #ifdef A 22122 a 22123 #else 22124 b 22125 #endif 22126 )"); 22127 } 22128 22129 TEST_F(FormatTest, DisableRegions) { 22130 EXPECT_EQ("int i;\n" 22131 "// clang-format off\n" 22132 " int j;\n" 22133 "// clang-format on\n" 22134 "int k;", 22135 format(" int i;\n" 22136 " // clang-format off\n" 22137 " int j;\n" 22138 " // clang-format on\n" 22139 " int k;")); 22140 EXPECT_EQ("int i;\n" 22141 "/* clang-format off */\n" 22142 " int j;\n" 22143 "/* clang-format on */\n" 22144 "int k;", 22145 format(" int i;\n" 22146 " /* clang-format off */\n" 22147 " int j;\n" 22148 " /* clang-format on */\n" 22149 " int k;")); 22150 22151 // Don't reflow comments within disabled regions. 22152 EXPECT_EQ("// clang-format off\n" 22153 "// long long long long long long line\n" 22154 "/* clang-format on */\n" 22155 "/* long long long\n" 22156 " * long long long\n" 22157 " * line */\n" 22158 "int i;\n" 22159 "/* clang-format off */\n" 22160 "/* long long long long long long line */\n", 22161 format("// clang-format off\n" 22162 "// long long long long long long line\n" 22163 "/* clang-format on */\n" 22164 "/* long long long long long long line */\n" 22165 "int i;\n" 22166 "/* clang-format off */\n" 22167 "/* long long long long long long line */\n", 22168 getLLVMStyleWithColumns(20))); 22169 } 22170 22171 TEST_F(FormatTest, DoNotCrashOnInvalidInput) { 22172 format("? ) ="); 22173 verifyNoCrash("#define a\\\n /**/}"); 22174 } 22175 22176 TEST_F(FormatTest, FormatsTableGenCode) { 22177 FormatStyle Style = getLLVMStyle(); 22178 Style.Language = FormatStyle::LK_TableGen; 22179 verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style); 22180 } 22181 22182 TEST_F(FormatTest, ArrayOfTemplates) { 22183 EXPECT_EQ("auto a = new unique_ptr<int>[10];", 22184 format("auto a = new unique_ptr<int > [ 10];")); 22185 22186 FormatStyle Spaces = getLLVMStyle(); 22187 Spaces.SpacesInSquareBrackets = true; 22188 EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];", 22189 format("auto a = new unique_ptr<int > [10];", Spaces)); 22190 } 22191 22192 TEST_F(FormatTest, ArrayAsTemplateType) { 22193 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;", 22194 format("auto a = unique_ptr < Foo < Bar>[ 10]> ;")); 22195 22196 FormatStyle Spaces = getLLVMStyle(); 22197 Spaces.SpacesInSquareBrackets = true; 22198 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;", 22199 format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces)); 22200 } 22201 22202 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); } 22203 22204 TEST(FormatStyle, GetStyleWithEmptyFileName) { 22205 llvm::vfs::InMemoryFileSystem FS; 22206 auto Style1 = getStyle("file", "", "Google", "", &FS); 22207 ASSERT_TRUE((bool)Style1); 22208 ASSERT_EQ(*Style1, getGoogleStyle()); 22209 } 22210 22211 TEST(FormatStyle, GetStyleOfFile) { 22212 llvm::vfs::InMemoryFileSystem FS; 22213 // Test 1: format file in the same directory. 22214 ASSERT_TRUE( 22215 FS.addFile("/a/.clang-format", 0, 22216 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM"))); 22217 ASSERT_TRUE( 22218 FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22219 auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS); 22220 ASSERT_TRUE((bool)Style1); 22221 ASSERT_EQ(*Style1, getLLVMStyle()); 22222 22223 // Test 2.1: fallback to default. 22224 ASSERT_TRUE( 22225 FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22226 auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS); 22227 ASSERT_TRUE((bool)Style2); 22228 ASSERT_EQ(*Style2, getMozillaStyle()); 22229 22230 // Test 2.2: no format on 'none' fallback style. 22231 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS); 22232 ASSERT_TRUE((bool)Style2); 22233 ASSERT_EQ(*Style2, getNoStyle()); 22234 22235 // Test 2.3: format if config is found with no based style while fallback is 22236 // 'none'. 22237 ASSERT_TRUE(FS.addFile("/b/.clang-format", 0, 22238 llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2"))); 22239 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS); 22240 ASSERT_TRUE((bool)Style2); 22241 ASSERT_EQ(*Style2, getLLVMStyle()); 22242 22243 // Test 2.4: format if yaml with no based style, while fallback is 'none'. 22244 Style2 = getStyle("{}", "a.h", "none", "", &FS); 22245 ASSERT_TRUE((bool)Style2); 22246 ASSERT_EQ(*Style2, getLLVMStyle()); 22247 22248 // Test 3: format file in parent directory. 22249 ASSERT_TRUE( 22250 FS.addFile("/c/.clang-format", 0, 22251 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 22252 ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0, 22253 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22254 auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS); 22255 ASSERT_TRUE((bool)Style3); 22256 ASSERT_EQ(*Style3, getGoogleStyle()); 22257 22258 // Test 4: error on invalid fallback style 22259 auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS); 22260 ASSERT_FALSE((bool)Style4); 22261 llvm::consumeError(Style4.takeError()); 22262 22263 // Test 5: error on invalid yaml on command line 22264 auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS); 22265 ASSERT_FALSE((bool)Style5); 22266 llvm::consumeError(Style5.takeError()); 22267 22268 // Test 6: error on invalid style 22269 auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS); 22270 ASSERT_FALSE((bool)Style6); 22271 llvm::consumeError(Style6.takeError()); 22272 22273 // Test 7: found config file, error on parsing it 22274 ASSERT_TRUE( 22275 FS.addFile("/d/.clang-format", 0, 22276 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n" 22277 "InvalidKey: InvalidValue"))); 22278 ASSERT_TRUE( 22279 FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22280 auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS); 22281 ASSERT_FALSE((bool)Style7a); 22282 llvm::consumeError(Style7a.takeError()); 22283 22284 auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true); 22285 ASSERT_TRUE((bool)Style7b); 22286 22287 // Test 8: inferred per-language defaults apply. 22288 auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS); 22289 ASSERT_TRUE((bool)StyleTd); 22290 ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen)); 22291 22292 // Test 9.1.1: overwriting a file style, when no parent file exists with no 22293 // fallback style. 22294 ASSERT_TRUE(FS.addFile( 22295 "/e/sub/.clang-format", 0, 22296 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n" 22297 "ColumnLimit: 20"))); 22298 ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0, 22299 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22300 auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS); 22301 ASSERT_TRUE(static_cast<bool>(Style9)); 22302 ASSERT_EQ(*Style9, [] { 22303 auto Style = getNoStyle(); 22304 Style.ColumnLimit = 20; 22305 return Style; 22306 }()); 22307 22308 // Test 9.1.2: propagate more than one level with no parent file. 22309 ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0, 22310 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22311 ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0, 22312 llvm::MemoryBuffer::getMemBuffer( 22313 "BasedOnStyle: InheritParentConfig\n" 22314 "WhitespaceSensitiveMacros: ['FOO', 'BAR']"))); 22315 std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"}; 22316 22317 ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros); 22318 Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS); 22319 ASSERT_TRUE(static_cast<bool>(Style9)); 22320 ASSERT_EQ(*Style9, [&NonDefaultWhiteSpaceMacros] { 22321 auto Style = getNoStyle(); 22322 Style.ColumnLimit = 20; 22323 Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros; 22324 return Style; 22325 }()); 22326 22327 // Test 9.2: with LLVM fallback style 22328 Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS); 22329 ASSERT_TRUE(static_cast<bool>(Style9)); 22330 ASSERT_EQ(*Style9, [] { 22331 auto Style = getLLVMStyle(); 22332 Style.ColumnLimit = 20; 22333 return Style; 22334 }()); 22335 22336 // Test 9.3: with a parent file 22337 ASSERT_TRUE( 22338 FS.addFile("/e/.clang-format", 0, 22339 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n" 22340 "UseTab: Always"))); 22341 Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS); 22342 ASSERT_TRUE(static_cast<bool>(Style9)); 22343 ASSERT_EQ(*Style9, [] { 22344 auto Style = getGoogleStyle(); 22345 Style.ColumnLimit = 20; 22346 Style.UseTab = FormatStyle::UT_Always; 22347 return Style; 22348 }()); 22349 22350 // Test 9.4: propagate more than one level with a parent file. 22351 const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] { 22352 auto Style = getGoogleStyle(); 22353 Style.ColumnLimit = 20; 22354 Style.UseTab = FormatStyle::UT_Always; 22355 Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros; 22356 return Style; 22357 }(); 22358 22359 ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros); 22360 Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS); 22361 ASSERT_TRUE(static_cast<bool>(Style9)); 22362 ASSERT_EQ(*Style9, SubSubStyle); 22363 22364 // Test 9.5: use InheritParentConfig as style name 22365 Style9 = 22366 getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS); 22367 ASSERT_TRUE(static_cast<bool>(Style9)); 22368 ASSERT_EQ(*Style9, SubSubStyle); 22369 22370 // Test 9.6: use command line style with inheritance 22371 Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp", 22372 "none", "", &FS); 22373 ASSERT_TRUE(static_cast<bool>(Style9)); 22374 ASSERT_EQ(*Style9, SubSubStyle); 22375 22376 // Test 9.7: use command line style with inheritance and own config 22377 Style9 = getStyle("{BasedOnStyle: InheritParentConfig, " 22378 "WhitespaceSensitiveMacros: ['FOO', 'BAR']}", 22379 "/e/sub/code.cpp", "none", "", &FS); 22380 ASSERT_TRUE(static_cast<bool>(Style9)); 22381 ASSERT_EQ(*Style9, SubSubStyle); 22382 22383 // Test 9.8: use inheritance from a file without BasedOnStyle 22384 ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0, 22385 llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123"))); 22386 ASSERT_TRUE( 22387 FS.addFile("/e/withoutbase/sub/.clang-format", 0, 22388 llvm::MemoryBuffer::getMemBuffer( 22389 "BasedOnStyle: InheritParentConfig\nIndentWidth: 7"))); 22390 // Make sure we do not use the fallback style 22391 Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS); 22392 ASSERT_TRUE(static_cast<bool>(Style9)); 22393 ASSERT_EQ(*Style9, [] { 22394 auto Style = getLLVMStyle(); 22395 Style.ColumnLimit = 123; 22396 return Style; 22397 }()); 22398 22399 Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS); 22400 ASSERT_TRUE(static_cast<bool>(Style9)); 22401 ASSERT_EQ(*Style9, [] { 22402 auto Style = getLLVMStyle(); 22403 Style.ColumnLimit = 123; 22404 Style.IndentWidth = 7; 22405 return Style; 22406 }()); 22407 22408 // Test 9.9: use inheritance from a specific config file. 22409 Style9 = getStyle("file:/e/sub/sub/.clang-format", "/e/sub/sub/code.cpp", 22410 "none", "", &FS); 22411 ASSERT_TRUE(static_cast<bool>(Style9)); 22412 ASSERT_EQ(*Style9, SubSubStyle); 22413 } 22414 22415 TEST(FormatStyle, GetStyleOfSpecificFile) { 22416 llvm::vfs::InMemoryFileSystem FS; 22417 // Specify absolute path to a format file in a parent directory. 22418 ASSERT_TRUE( 22419 FS.addFile("/e/.clang-format", 0, 22420 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM"))); 22421 ASSERT_TRUE( 22422 FS.addFile("/e/explicit.clang-format", 0, 22423 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 22424 ASSERT_TRUE(FS.addFile("/e/sub/sub/sub/test.cpp", 0, 22425 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22426 auto Style = getStyle("file:/e/explicit.clang-format", 22427 "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS); 22428 ASSERT_TRUE(static_cast<bool>(Style)); 22429 ASSERT_EQ(*Style, getGoogleStyle()); 22430 22431 // Specify relative path to a format file. 22432 ASSERT_TRUE( 22433 FS.addFile("../../e/explicit.clang-format", 0, 22434 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 22435 Style = getStyle("file:../../e/explicit.clang-format", 22436 "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS); 22437 ASSERT_TRUE(static_cast<bool>(Style)); 22438 ASSERT_EQ(*Style, getGoogleStyle()); 22439 22440 // Specify path to a format file that does not exist. 22441 Style = getStyle("file:/e/missing.clang-format", "/e/sub/sub/sub/test.cpp", 22442 "LLVM", "", &FS); 22443 ASSERT_FALSE(static_cast<bool>(Style)); 22444 llvm::consumeError(Style.takeError()); 22445 22446 // Specify path to a file on the filesystem. 22447 SmallString<128> FormatFilePath; 22448 std::error_code ECF = llvm::sys::fs::createTemporaryFile( 22449 "FormatFileTest", "tpl", FormatFilePath); 22450 EXPECT_FALSE((bool)ECF); 22451 llvm::raw_fd_ostream FormatFileTest(FormatFilePath, ECF); 22452 EXPECT_FALSE((bool)ECF); 22453 FormatFileTest << "BasedOnStyle: Google\n"; 22454 FormatFileTest.close(); 22455 22456 SmallString<128> TestFilePath; 22457 std::error_code ECT = 22458 llvm::sys::fs::createTemporaryFile("CodeFileTest", "cc", TestFilePath); 22459 EXPECT_FALSE((bool)ECT); 22460 llvm::raw_fd_ostream CodeFileTest(TestFilePath, ECT); 22461 CodeFileTest << "int i;\n"; 22462 CodeFileTest.close(); 22463 22464 std::string format_file_arg = std::string("file:") + FormatFilePath.c_str(); 22465 Style = getStyle(format_file_arg, TestFilePath, "LLVM", "", nullptr); 22466 22467 llvm::sys::fs::remove(FormatFilePath.c_str()); 22468 llvm::sys::fs::remove(TestFilePath.c_str()); 22469 ASSERT_TRUE(static_cast<bool>(Style)); 22470 ASSERT_EQ(*Style, getGoogleStyle()); 22471 } 22472 22473 TEST_F(ReplacementTest, FormatCodeAfterReplacements) { 22474 // Column limit is 20. 22475 std::string Code = "Type *a =\n" 22476 " new Type();\n" 22477 "g(iiiii, 0, jjjjj,\n" 22478 " 0, kkkkk, 0, mm);\n" 22479 "int bad = format ;"; 22480 std::string Expected = "auto a = new Type();\n" 22481 "g(iiiii, nullptr,\n" 22482 " jjjjj, nullptr,\n" 22483 " kkkkk, nullptr,\n" 22484 " mm);\n" 22485 "int bad = format ;"; 22486 FileID ID = Context.createInMemoryFile("format.cpp", Code); 22487 tooling::Replacements Replaces = toReplacements( 22488 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6, 22489 "auto "), 22490 tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1, 22491 "nullptr"), 22492 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1, 22493 "nullptr"), 22494 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1, 22495 "nullptr")}); 22496 22497 FormatStyle Style = getLLVMStyle(); 22498 Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility. 22499 auto FormattedReplaces = formatReplacements(Code, Replaces, Style); 22500 EXPECT_TRUE(static_cast<bool>(FormattedReplaces)) 22501 << llvm::toString(FormattedReplaces.takeError()) << "\n"; 22502 auto Result = applyAllReplacements(Code, *FormattedReplaces); 22503 EXPECT_TRUE(static_cast<bool>(Result)); 22504 EXPECT_EQ(Expected, *Result); 22505 } 22506 22507 TEST_F(ReplacementTest, SortIncludesAfterReplacement) { 22508 std::string Code = "#include \"a.h\"\n" 22509 "#include \"c.h\"\n" 22510 "\n" 22511 "int main() {\n" 22512 " return 0;\n" 22513 "}"; 22514 std::string Expected = "#include \"a.h\"\n" 22515 "#include \"b.h\"\n" 22516 "#include \"c.h\"\n" 22517 "\n" 22518 "int main() {\n" 22519 " return 0;\n" 22520 "}"; 22521 FileID ID = Context.createInMemoryFile("fix.cpp", Code); 22522 tooling::Replacements Replaces = toReplacements( 22523 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0, 22524 "#include \"b.h\"\n")}); 22525 22526 FormatStyle Style = getLLVMStyle(); 22527 Style.SortIncludes = FormatStyle::SI_CaseSensitive; 22528 auto FormattedReplaces = formatReplacements(Code, Replaces, Style); 22529 EXPECT_TRUE(static_cast<bool>(FormattedReplaces)) 22530 << llvm::toString(FormattedReplaces.takeError()) << "\n"; 22531 auto Result = applyAllReplacements(Code, *FormattedReplaces); 22532 EXPECT_TRUE(static_cast<bool>(Result)); 22533 EXPECT_EQ(Expected, *Result); 22534 } 22535 22536 TEST_F(FormatTest, FormatSortsUsingDeclarations) { 22537 EXPECT_EQ("using std::cin;\n" 22538 "using std::cout;", 22539 format("using std::cout;\n" 22540 "using std::cin;", 22541 getGoogleStyle())); 22542 } 22543 22544 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) { 22545 FormatStyle Style = getLLVMStyle(); 22546 Style.Standard = FormatStyle::LS_Cpp03; 22547 // cpp03 recognize this string as identifier u8 and literal character 'a' 22548 EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style)); 22549 } 22550 22551 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) { 22552 // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers 22553 // all modes, including C++11, C++14 and C++17 22554 EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';")); 22555 } 22556 22557 TEST_F(FormatTest, DoNotFormatLikelyXml) { 22558 EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle())); 22559 EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle())); 22560 } 22561 22562 TEST_F(FormatTest, StructuredBindings) { 22563 // Structured bindings is a C++17 feature. 22564 // all modes, including C++11, C++14 and C++17 22565 verifyFormat("auto [a, b] = f();"); 22566 EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();")); 22567 EXPECT_EQ("const auto [a, b] = f();", format("const auto[a, b] = f();")); 22568 EXPECT_EQ("auto const [a, b] = f();", format("auto const[a, b] = f();")); 22569 EXPECT_EQ("auto const volatile [a, b] = f();", 22570 format("auto const volatile[a, b] = f();")); 22571 EXPECT_EQ("auto [a, b, c] = f();", format("auto [ a , b,c ] = f();")); 22572 EXPECT_EQ("auto &[a, b, c] = f();", 22573 format("auto &[ a , b,c ] = f();")); 22574 EXPECT_EQ("auto &&[a, b, c] = f();", 22575 format("auto &&[ a , b,c ] = f();")); 22576 EXPECT_EQ("auto const &[a, b] = f();", format("auto const&[a, b] = f();")); 22577 EXPECT_EQ("auto const volatile &&[a, b] = f();", 22578 format("auto const volatile &&[a, b] = f();")); 22579 EXPECT_EQ("auto const &&[a, b] = f();", 22580 format("auto const && [a, b] = f();")); 22581 EXPECT_EQ("const auto &[a, b] = f();", 22582 format("const auto & [a, b] = f();")); 22583 EXPECT_EQ("const auto volatile &&[a, b] = f();", 22584 format("const auto volatile &&[a, b] = f();")); 22585 EXPECT_EQ("volatile const auto &&[a, b] = f();", 22586 format("volatile const auto &&[a, b] = f();")); 22587 EXPECT_EQ("const auto &&[a, b] = f();", 22588 format("const auto && [a, b] = f();")); 22589 22590 // Make sure we don't mistake structured bindings for lambdas. 22591 FormatStyle PointerMiddle = getLLVMStyle(); 22592 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle; 22593 verifyFormat("auto [a1, b]{A * i};", getGoogleStyle()); 22594 verifyFormat("auto [a2, b]{A * i};", getLLVMStyle()); 22595 verifyFormat("auto [a3, b]{A * i};", PointerMiddle); 22596 verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle()); 22597 verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle()); 22598 verifyFormat("auto const [a3, b]{A * i};", PointerMiddle); 22599 verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle()); 22600 verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle()); 22601 verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle); 22602 verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle()); 22603 verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle()); 22604 verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle); 22605 22606 EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}", 22607 format("for (const auto && [a, b] : some_range) {\n}")); 22608 EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}", 22609 format("for (const auto & [a, b] : some_range) {\n}")); 22610 EXPECT_EQ("for (const auto [a, b] : some_range) {\n}", 22611 format("for (const auto[a, b] : some_range) {\n}")); 22612 EXPECT_EQ("auto [x, y](expr);", format("auto[x,y] (expr);")); 22613 EXPECT_EQ("auto &[x, y](expr);", format("auto & [x,y] (expr);")); 22614 EXPECT_EQ("auto &&[x, y](expr);", format("auto && [x,y] (expr);")); 22615 EXPECT_EQ("auto const &[x, y](expr);", 22616 format("auto const & [x,y] (expr);")); 22617 EXPECT_EQ("auto const &&[x, y](expr);", 22618 format("auto const && [x,y] (expr);")); 22619 EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y] {expr};")); 22620 EXPECT_EQ("auto const &[x, y]{expr};", 22621 format("auto const & [x,y] {expr};")); 22622 EXPECT_EQ("auto const &&[x, y]{expr};", 22623 format("auto const && [x,y] {expr};")); 22624 22625 FormatStyle Spaces = getLLVMStyle(); 22626 Spaces.SpacesInSquareBrackets = true; 22627 verifyFormat("auto [ a, b ] = f();", Spaces); 22628 verifyFormat("auto &&[ a, b ] = f();", Spaces); 22629 verifyFormat("auto &[ a, b ] = f();", Spaces); 22630 verifyFormat("auto const &&[ a, b ] = f();", Spaces); 22631 verifyFormat("auto const &[ a, b ] = f();", Spaces); 22632 } 22633 22634 TEST_F(FormatTest, FileAndCode) { 22635 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", "")); 22636 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", "")); 22637 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", "")); 22638 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "")); 22639 EXPECT_EQ(FormatStyle::LK_ObjC, 22640 guessLanguage("foo.h", "@interface Foo\n@end\n")); 22641 EXPECT_EQ( 22642 FormatStyle::LK_ObjC, 22643 guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }")); 22644 EXPECT_EQ(FormatStyle::LK_ObjC, 22645 guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))")); 22646 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;")); 22647 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", "")); 22648 EXPECT_EQ(FormatStyle::LK_ObjC, 22649 guessLanguage("foo", "@interface Foo\n@end\n")); 22650 EXPECT_EQ(FormatStyle::LK_ObjC, 22651 guessLanguage("foo.h", "int DoStuff(CGRect rect);\n")); 22652 EXPECT_EQ( 22653 FormatStyle::LK_ObjC, 22654 guessLanguage("foo.h", 22655 "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n")); 22656 EXPECT_EQ( 22657 FormatStyle::LK_Cpp, 22658 guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;")); 22659 } 22660 22661 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) { 22662 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];")); 22663 EXPECT_EQ(FormatStyle::LK_ObjC, 22664 guessLanguage("foo.h", "array[[calculator getIndex]];")); 22665 EXPECT_EQ(FormatStyle::LK_Cpp, 22666 guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];")); 22667 EXPECT_EQ( 22668 FormatStyle::LK_Cpp, 22669 guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];")); 22670 EXPECT_EQ(FormatStyle::LK_ObjC, 22671 guessLanguage("foo.h", "[[noreturn foo] bar];")); 22672 EXPECT_EQ(FormatStyle::LK_Cpp, 22673 guessLanguage("foo.h", "[[clang::fallthrough]];")); 22674 EXPECT_EQ(FormatStyle::LK_ObjC, 22675 guessLanguage("foo.h", "[[clang:fallthrough] foo];")); 22676 EXPECT_EQ(FormatStyle::LK_Cpp, 22677 guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];")); 22678 EXPECT_EQ(FormatStyle::LK_Cpp, 22679 guessLanguage("foo.h", "[[using clang: fallthrough]];")); 22680 EXPECT_EQ(FormatStyle::LK_ObjC, 22681 guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];")); 22682 EXPECT_EQ(FormatStyle::LK_Cpp, 22683 guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];")); 22684 EXPECT_EQ( 22685 FormatStyle::LK_Cpp, 22686 guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)")); 22687 EXPECT_EQ( 22688 FormatStyle::LK_Cpp, 22689 guessLanguage("foo.h", 22690 "[[clang::callable_when(\"unconsumed\", \"unknown\")]]")); 22691 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]")); 22692 } 22693 22694 TEST_F(FormatTest, GuessLanguageWithCaret) { 22695 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);")); 22696 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);")); 22697 EXPECT_EQ(FormatStyle::LK_ObjC, 22698 guessLanguage("foo.h", "int(^)(char, float);")); 22699 EXPECT_EQ(FormatStyle::LK_ObjC, 22700 guessLanguage("foo.h", "int(^foo)(char, float);")); 22701 EXPECT_EQ(FormatStyle::LK_ObjC, 22702 guessLanguage("foo.h", "int(^foo[10])(char, float);")); 22703 EXPECT_EQ(FormatStyle::LK_ObjC, 22704 guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);")); 22705 EXPECT_EQ( 22706 FormatStyle::LK_ObjC, 22707 guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);")); 22708 } 22709 22710 TEST_F(FormatTest, GuessLanguageWithPragmas) { 22711 EXPECT_EQ(FormatStyle::LK_Cpp, 22712 guessLanguage("foo.h", "__pragma(warning(disable:))")); 22713 EXPECT_EQ(FormatStyle::LK_Cpp, 22714 guessLanguage("foo.h", "#pragma(warning(disable:))")); 22715 EXPECT_EQ(FormatStyle::LK_Cpp, 22716 guessLanguage("foo.h", "_Pragma(warning(disable:))")); 22717 } 22718 22719 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) { 22720 // ASM symbolic names are identifiers that must be surrounded by [] without 22721 // space in between: 22722 // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands 22723 22724 // Example from https://bugs.llvm.org/show_bug.cgi?id=45108. 22725 verifyFormat(R"(// 22726 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result)); 22727 )"); 22728 22729 // A list of several ASM symbolic names. 22730 verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)"); 22731 22732 // ASM symbolic names in inline ASM with inputs and outputs. 22733 verifyFormat(R"(// 22734 asm("cmoveq %1, %2, %[result]" 22735 : [result] "=r"(result) 22736 : "r"(test), "r"(new), "[result]"(old)); 22737 )"); 22738 22739 // ASM symbolic names in inline ASM with no outputs. 22740 verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)"); 22741 } 22742 22743 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) { 22744 EXPECT_EQ(FormatStyle::LK_Cpp, 22745 guessLanguage("foo.h", "void f() {\n" 22746 " asm (\"mov %[e], %[d]\"\n" 22747 " : [d] \"=rm\" (d)\n" 22748 " [e] \"rm\" (*e));\n" 22749 "}")); 22750 EXPECT_EQ(FormatStyle::LK_Cpp, 22751 guessLanguage("foo.h", "void f() {\n" 22752 " _asm (\"mov %[e], %[d]\"\n" 22753 " : [d] \"=rm\" (d)\n" 22754 " [e] \"rm\" (*e));\n" 22755 "}")); 22756 EXPECT_EQ(FormatStyle::LK_Cpp, 22757 guessLanguage("foo.h", "void f() {\n" 22758 " __asm (\"mov %[e], %[d]\"\n" 22759 " : [d] \"=rm\" (d)\n" 22760 " [e] \"rm\" (*e));\n" 22761 "}")); 22762 EXPECT_EQ(FormatStyle::LK_Cpp, 22763 guessLanguage("foo.h", "void f() {\n" 22764 " __asm__ (\"mov %[e], %[d]\"\n" 22765 " : [d] \"=rm\" (d)\n" 22766 " [e] \"rm\" (*e));\n" 22767 "}")); 22768 EXPECT_EQ(FormatStyle::LK_Cpp, 22769 guessLanguage("foo.h", "void f() {\n" 22770 " asm (\"mov %[e], %[d]\"\n" 22771 " : [d] \"=rm\" (d),\n" 22772 " [e] \"rm\" (*e));\n" 22773 "}")); 22774 EXPECT_EQ(FormatStyle::LK_Cpp, 22775 guessLanguage("foo.h", "void f() {\n" 22776 " asm volatile (\"mov %[e], %[d]\"\n" 22777 " : [d] \"=rm\" (d)\n" 22778 " [e] \"rm\" (*e));\n" 22779 "}")); 22780 } 22781 22782 TEST_F(FormatTest, GuessLanguageWithChildLines) { 22783 EXPECT_EQ(FormatStyle::LK_Cpp, 22784 guessLanguage("foo.h", "#define FOO ({ std::string s; })")); 22785 EXPECT_EQ(FormatStyle::LK_ObjC, 22786 guessLanguage("foo.h", "#define FOO ({ NSString *s; })")); 22787 EXPECT_EQ( 22788 FormatStyle::LK_Cpp, 22789 guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })")); 22790 EXPECT_EQ( 22791 FormatStyle::LK_ObjC, 22792 guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })")); 22793 } 22794 22795 TEST_F(FormatTest, TypenameMacros) { 22796 std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"}; 22797 22798 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353 22799 FormatStyle Google = getGoogleStyleWithColumns(0); 22800 Google.TypenameMacros = TypenameMacros; 22801 verifyFormat("struct foo {\n" 22802 " int bar;\n" 22803 " TAILQ_ENTRY(a) bleh;\n" 22804 "};", 22805 Google); 22806 22807 FormatStyle Macros = getLLVMStyle(); 22808 Macros.TypenameMacros = TypenameMacros; 22809 22810 verifyFormat("STACK_OF(int) a;", Macros); 22811 verifyFormat("STACK_OF(int) *a;", Macros); 22812 verifyFormat("STACK_OF(int const *) *a;", Macros); 22813 verifyFormat("STACK_OF(int *const) *a;", Macros); 22814 verifyFormat("STACK_OF(int, string) a;", Macros); 22815 verifyFormat("STACK_OF(LIST(int)) a;", Macros); 22816 verifyFormat("STACK_OF(LIST(int)) a, b;", Macros); 22817 verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros); 22818 verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros); 22819 verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros); 22820 verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros); 22821 22822 Macros.PointerAlignment = FormatStyle::PAS_Left; 22823 verifyFormat("STACK_OF(int)* a;", Macros); 22824 verifyFormat("STACK_OF(int*)* a;", Macros); 22825 verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros); 22826 verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros); 22827 verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros); 22828 } 22829 22830 TEST_F(FormatTest, AtomicQualifier) { 22831 // Check that we treate _Atomic as a type and not a function call 22832 FormatStyle Google = getGoogleStyleWithColumns(0); 22833 verifyFormat("struct foo {\n" 22834 " int a1;\n" 22835 " _Atomic(a) a2;\n" 22836 " _Atomic(_Atomic(int) *const) a3;\n" 22837 "};", 22838 Google); 22839 verifyFormat("_Atomic(uint64_t) a;"); 22840 verifyFormat("_Atomic(uint64_t) *a;"); 22841 verifyFormat("_Atomic(uint64_t const *) *a;"); 22842 verifyFormat("_Atomic(uint64_t *const) *a;"); 22843 verifyFormat("_Atomic(const uint64_t *) *a;"); 22844 verifyFormat("_Atomic(uint64_t) a;"); 22845 verifyFormat("_Atomic(_Atomic(uint64_t)) a;"); 22846 verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;"); 22847 verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}"); 22848 verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);"); 22849 22850 verifyFormat("_Atomic(uint64_t) *s(InitValue);"); 22851 verifyFormat("_Atomic(uint64_t) *s{InitValue};"); 22852 FormatStyle Style = getLLVMStyle(); 22853 Style.PointerAlignment = FormatStyle::PAS_Left; 22854 verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style); 22855 verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style); 22856 verifyFormat("_Atomic(int)* a;", Style); 22857 verifyFormat("_Atomic(int*)* a;", Style); 22858 verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style); 22859 22860 Style.SpacesInCStyleCastParentheses = true; 22861 Style.SpacesInParentheses = false; 22862 verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style); 22863 Style.SpacesInCStyleCastParentheses = false; 22864 Style.SpacesInParentheses = true; 22865 verifyFormat("x = (_Atomic( uint64_t ))*a;", Style); 22866 verifyFormat("x = (_Atomic( uint64_t ))&a;", Style); 22867 } 22868 22869 TEST_F(FormatTest, AmbersandInLamda) { 22870 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899 22871 FormatStyle AlignStyle = getLLVMStyle(); 22872 AlignStyle.PointerAlignment = FormatStyle::PAS_Left; 22873 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle); 22874 AlignStyle.PointerAlignment = FormatStyle::PAS_Right; 22875 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle); 22876 } 22877 22878 TEST_F(FormatTest, SpacesInConditionalStatement) { 22879 FormatStyle Spaces = getLLVMStyle(); 22880 Spaces.IfMacros.clear(); 22881 Spaces.IfMacros.push_back("MYIF"); 22882 Spaces.SpacesInConditionalStatement = true; 22883 verifyFormat("for ( int i = 0; i; i++ )\n continue;", Spaces); 22884 verifyFormat("if ( !a )\n return;", Spaces); 22885 verifyFormat("if ( a )\n return;", Spaces); 22886 verifyFormat("if constexpr ( a )\n return;", Spaces); 22887 verifyFormat("MYIF ( a )\n return;", Spaces); 22888 verifyFormat("MYIF ( a )\n return;\nelse MYIF ( b )\n return;", Spaces); 22889 verifyFormat("MYIF ( a )\n return;\nelse\n return;", Spaces); 22890 verifyFormat("switch ( a )\ncase 1:\n return;", Spaces); 22891 verifyFormat("while ( a )\n return;", Spaces); 22892 verifyFormat("while ( (a && b) )\n return;", Spaces); 22893 verifyFormat("do {\n} while ( 1 != 0 );", Spaces); 22894 verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces); 22895 // Check that space on the left of "::" is inserted as expected at beginning 22896 // of condition. 22897 verifyFormat("while ( ::func() )\n return;", Spaces); 22898 22899 // Check impact of ControlStatementsExceptControlMacros is honored. 22900 Spaces.SpaceBeforeParens = 22901 FormatStyle::SBPO_ControlStatementsExceptControlMacros; 22902 verifyFormat("MYIF( a )\n return;", Spaces); 22903 verifyFormat("MYIF( a )\n return;\nelse MYIF( b )\n return;", Spaces); 22904 verifyFormat("MYIF( a )\n return;\nelse\n return;", Spaces); 22905 } 22906 22907 TEST_F(FormatTest, AlternativeOperators) { 22908 // Test case for ensuring alternate operators are not 22909 // combined with their right most neighbour. 22910 verifyFormat("int a and b;"); 22911 verifyFormat("int a and_eq b;"); 22912 verifyFormat("int a bitand b;"); 22913 verifyFormat("int a bitor b;"); 22914 verifyFormat("int a compl b;"); 22915 verifyFormat("int a not b;"); 22916 verifyFormat("int a not_eq b;"); 22917 verifyFormat("int a or b;"); 22918 verifyFormat("int a xor b;"); 22919 verifyFormat("int a xor_eq b;"); 22920 verifyFormat("return this not_eq bitand other;"); 22921 verifyFormat("bool operator not_eq(const X bitand other)"); 22922 22923 verifyFormat("int a and 5;"); 22924 verifyFormat("int a and_eq 5;"); 22925 verifyFormat("int a bitand 5;"); 22926 verifyFormat("int a bitor 5;"); 22927 verifyFormat("int a compl 5;"); 22928 verifyFormat("int a not 5;"); 22929 verifyFormat("int a not_eq 5;"); 22930 verifyFormat("int a or 5;"); 22931 verifyFormat("int a xor 5;"); 22932 verifyFormat("int a xor_eq 5;"); 22933 22934 verifyFormat("int a compl(5);"); 22935 verifyFormat("int a not(5);"); 22936 22937 /* FIXME handle alternate tokens 22938 * https://en.cppreference.com/w/cpp/language/operator_alternative 22939 // alternative tokens 22940 verifyFormat("compl foo();"); // ~foo(); 22941 verifyFormat("foo() <%%>;"); // foo(); 22942 verifyFormat("void foo() <%%>;"); // void foo(){} 22943 verifyFormat("int a <:1:>;"); // int a[1];[ 22944 verifyFormat("%:define ABC abc"); // #define ABC abc 22945 verifyFormat("%:%:"); // ## 22946 */ 22947 } 22948 22949 TEST_F(FormatTest, STLWhileNotDefineChed) { 22950 verifyFormat("#if defined(while)\n" 22951 "#define while EMIT WARNING C4005\n" 22952 "#endif // while"); 22953 } 22954 22955 TEST_F(FormatTest, OperatorSpacing) { 22956 FormatStyle Style = getLLVMStyle(); 22957 Style.PointerAlignment = FormatStyle::PAS_Right; 22958 verifyFormat("Foo::operator*();", Style); 22959 verifyFormat("Foo::operator void *();", Style); 22960 verifyFormat("Foo::operator void **();", Style); 22961 verifyFormat("Foo::operator void *&();", Style); 22962 verifyFormat("Foo::operator void *&&();", Style); 22963 verifyFormat("Foo::operator void const *();", Style); 22964 verifyFormat("Foo::operator void const **();", Style); 22965 verifyFormat("Foo::operator void const *&();", Style); 22966 verifyFormat("Foo::operator void const *&&();", Style); 22967 verifyFormat("Foo::operator()(void *);", Style); 22968 verifyFormat("Foo::operator*(void *);", Style); 22969 verifyFormat("Foo::operator*();", Style); 22970 verifyFormat("Foo::operator**();", Style); 22971 verifyFormat("Foo::operator&();", Style); 22972 verifyFormat("Foo::operator<int> *();", Style); 22973 verifyFormat("Foo::operator<Foo> *();", Style); 22974 verifyFormat("Foo::operator<int> **();", Style); 22975 verifyFormat("Foo::operator<Foo> **();", Style); 22976 verifyFormat("Foo::operator<int> &();", Style); 22977 verifyFormat("Foo::operator<Foo> &();", Style); 22978 verifyFormat("Foo::operator<int> &&();", Style); 22979 verifyFormat("Foo::operator<Foo> &&();", Style); 22980 verifyFormat("Foo::operator<int> *&();", Style); 22981 verifyFormat("Foo::operator<Foo> *&();", Style); 22982 verifyFormat("Foo::operator<int> *&&();", Style); 22983 verifyFormat("Foo::operator<Foo> *&&();", Style); 22984 verifyFormat("operator*(int (*)(), class Foo);", Style); 22985 22986 verifyFormat("Foo::operator&();", Style); 22987 verifyFormat("Foo::operator void &();", Style); 22988 verifyFormat("Foo::operator void const &();", Style); 22989 verifyFormat("Foo::operator()(void &);", Style); 22990 verifyFormat("Foo::operator&(void &);", Style); 22991 verifyFormat("Foo::operator&();", Style); 22992 verifyFormat("operator&(int (&)(), class Foo);", Style); 22993 verifyFormat("operator&&(int (&)(), class Foo);", Style); 22994 22995 verifyFormat("Foo::operator&&();", Style); 22996 verifyFormat("Foo::operator**();", Style); 22997 verifyFormat("Foo::operator void &&();", Style); 22998 verifyFormat("Foo::operator void const &&();", Style); 22999 verifyFormat("Foo::operator()(void &&);", Style); 23000 verifyFormat("Foo::operator&&(void &&);", Style); 23001 verifyFormat("Foo::operator&&();", Style); 23002 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23003 verifyFormat("operator const nsTArrayRight<E> &()", Style); 23004 verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()", 23005 Style); 23006 verifyFormat("operator void **()", Style); 23007 verifyFormat("operator const FooRight<Object> &()", Style); 23008 verifyFormat("operator const FooRight<Object> *()", Style); 23009 verifyFormat("operator const FooRight<Object> **()", Style); 23010 verifyFormat("operator const FooRight<Object> *&()", Style); 23011 verifyFormat("operator const FooRight<Object> *&&()", Style); 23012 23013 Style.PointerAlignment = FormatStyle::PAS_Left; 23014 verifyFormat("Foo::operator*();", Style); 23015 verifyFormat("Foo::operator**();", Style); 23016 verifyFormat("Foo::operator void*();", Style); 23017 verifyFormat("Foo::operator void**();", Style); 23018 verifyFormat("Foo::operator void*&();", Style); 23019 verifyFormat("Foo::operator void*&&();", Style); 23020 verifyFormat("Foo::operator void const*();", Style); 23021 verifyFormat("Foo::operator void const**();", Style); 23022 verifyFormat("Foo::operator void const*&();", Style); 23023 verifyFormat("Foo::operator void const*&&();", Style); 23024 verifyFormat("Foo::operator/*comment*/ void*();", Style); 23025 verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style); 23026 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style); 23027 verifyFormat("Foo::operator()(void*);", Style); 23028 verifyFormat("Foo::operator*(void*);", Style); 23029 verifyFormat("Foo::operator*();", Style); 23030 verifyFormat("Foo::operator<int>*();", Style); 23031 verifyFormat("Foo::operator<Foo>*();", Style); 23032 verifyFormat("Foo::operator<int>**();", Style); 23033 verifyFormat("Foo::operator<Foo>**();", Style); 23034 verifyFormat("Foo::operator<Foo>*&();", Style); 23035 verifyFormat("Foo::operator<int>&();", Style); 23036 verifyFormat("Foo::operator<Foo>&();", Style); 23037 verifyFormat("Foo::operator<int>&&();", Style); 23038 verifyFormat("Foo::operator<Foo>&&();", Style); 23039 verifyFormat("Foo::operator<int>*&();", Style); 23040 verifyFormat("Foo::operator<Foo>*&();", Style); 23041 verifyFormat("operator*(int (*)(), class Foo);", Style); 23042 23043 verifyFormat("Foo::operator&();", Style); 23044 verifyFormat("Foo::operator void&();", Style); 23045 verifyFormat("Foo::operator void const&();", Style); 23046 verifyFormat("Foo::operator/*comment*/ void&();", Style); 23047 verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style); 23048 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style); 23049 verifyFormat("Foo::operator()(void&);", Style); 23050 verifyFormat("Foo::operator&(void&);", Style); 23051 verifyFormat("Foo::operator&();", Style); 23052 verifyFormat("operator&(int (&)(), class Foo);", Style); 23053 verifyFormat("operator&(int (&&)(), class Foo);", Style); 23054 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23055 23056 verifyFormat("Foo::operator&&();", Style); 23057 verifyFormat("Foo::operator void&&();", Style); 23058 verifyFormat("Foo::operator void const&&();", Style); 23059 verifyFormat("Foo::operator/*comment*/ void&&();", Style); 23060 verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style); 23061 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style); 23062 verifyFormat("Foo::operator()(void&&);", Style); 23063 verifyFormat("Foo::operator&&(void&&);", Style); 23064 verifyFormat("Foo::operator&&();", Style); 23065 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23066 verifyFormat("operator const nsTArrayLeft<E>&()", Style); 23067 verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()", 23068 Style); 23069 verifyFormat("operator void**()", Style); 23070 verifyFormat("operator const FooLeft<Object>&()", Style); 23071 verifyFormat("operator const FooLeft<Object>*()", Style); 23072 verifyFormat("operator const FooLeft<Object>**()", Style); 23073 verifyFormat("operator const FooLeft<Object>*&()", Style); 23074 verifyFormat("operator const FooLeft<Object>*&&()", Style); 23075 23076 // PR45107 23077 verifyFormat("operator Vector<String>&();", Style); 23078 verifyFormat("operator const Vector<String>&();", Style); 23079 verifyFormat("operator foo::Bar*();", Style); 23080 verifyFormat("operator const Foo<X>::Bar<Y>*();", Style); 23081 verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();", 23082 Style); 23083 23084 Style.PointerAlignment = FormatStyle::PAS_Middle; 23085 verifyFormat("Foo::operator*();", Style); 23086 verifyFormat("Foo::operator void *();", Style); 23087 verifyFormat("Foo::operator()(void *);", Style); 23088 verifyFormat("Foo::operator*(void *);", Style); 23089 verifyFormat("Foo::operator*();", Style); 23090 verifyFormat("operator*(int (*)(), class Foo);", Style); 23091 23092 verifyFormat("Foo::operator&();", Style); 23093 verifyFormat("Foo::operator void &();", Style); 23094 verifyFormat("Foo::operator void const &();", Style); 23095 verifyFormat("Foo::operator()(void &);", Style); 23096 verifyFormat("Foo::operator&(void &);", Style); 23097 verifyFormat("Foo::operator&();", Style); 23098 verifyFormat("operator&(int (&)(), class Foo);", Style); 23099 23100 verifyFormat("Foo::operator&&();", Style); 23101 verifyFormat("Foo::operator void &&();", Style); 23102 verifyFormat("Foo::operator void const &&();", Style); 23103 verifyFormat("Foo::operator()(void &&);", Style); 23104 verifyFormat("Foo::operator&&(void &&);", Style); 23105 verifyFormat("Foo::operator&&();", Style); 23106 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23107 } 23108 23109 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) { 23110 FormatStyle Style = getLLVMStyle(); 23111 // PR46157 23112 verifyFormat("foo(operator+, -42);", Style); 23113 verifyFormat("foo(operator++, -42);", Style); 23114 verifyFormat("foo(operator--, -42);", Style); 23115 verifyFormat("foo(-42, operator--);", Style); 23116 verifyFormat("foo(-42, operator, );", Style); 23117 verifyFormat("foo(operator, , -42);", Style); 23118 } 23119 23120 TEST_F(FormatTest, WhitespaceSensitiveMacros) { 23121 FormatStyle Style = getLLVMStyle(); 23122 Style.WhitespaceSensitiveMacros.push_back("FOO"); 23123 23124 // Don't use the helpers here, since 'mess up' will change the whitespace 23125 // and these are all whitespace sensitive by definition 23126 EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);", 23127 format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style)); 23128 EXPECT_EQ( 23129 "FOO(String-ized&Messy+But\\(: :Still)=Intentional);", 23130 format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style)); 23131 EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);", 23132 format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style)); 23133 EXPECT_EQ("FOO(String-ized&Messy+But,: :\n" 23134 " Still=Intentional);", 23135 format("FOO(String-ized&Messy+But,: :\n" 23136 " Still=Intentional);", 23137 Style)); 23138 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 23139 EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n" 23140 " Still=Intentional);", 23141 format("FOO(String-ized=&Messy+But,: :\n" 23142 " Still=Intentional);", 23143 Style)); 23144 23145 Style.ColumnLimit = 21; 23146 EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);", 23147 format("FOO(String-ized&Messy+But: :Still=Intentional);", Style)); 23148 } 23149 23150 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) { 23151 // These tests are not in NamespaceFixer because that doesn't 23152 // test its interaction with line wrapping 23153 FormatStyle Style = getLLVMStyleWithColumns(80); 23154 verifyFormat("namespace {\n" 23155 "int i;\n" 23156 "int j;\n" 23157 "} // namespace", 23158 Style); 23159 23160 verifyFormat("namespace AAA {\n" 23161 "int i;\n" 23162 "int j;\n" 23163 "} // namespace AAA", 23164 Style); 23165 23166 EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n" 23167 "int i;\n" 23168 "int j;\n" 23169 "} // namespace Averyveryveryverylongnamespace", 23170 format("namespace Averyveryveryverylongnamespace {\n" 23171 "int i;\n" 23172 "int j;\n" 23173 "}", 23174 Style)); 23175 23176 EXPECT_EQ( 23177 "namespace " 23178 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n" 23179 " went::mad::now {\n" 23180 "int i;\n" 23181 "int j;\n" 23182 "} // namespace\n" 23183 " // " 23184 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::" 23185 "went::mad::now", 23186 format("namespace " 23187 "would::it::save::you::a::lot::of::time::if_::i::" 23188 "just::gave::up::and_::went::mad::now {\n" 23189 "int i;\n" 23190 "int j;\n" 23191 "}", 23192 Style)); 23193 23194 // This used to duplicate the comment again and again on subsequent runs 23195 EXPECT_EQ( 23196 "namespace " 23197 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n" 23198 " went::mad::now {\n" 23199 "int i;\n" 23200 "int j;\n" 23201 "} // namespace\n" 23202 " // " 23203 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::" 23204 "went::mad::now", 23205 format("namespace " 23206 "would::it::save::you::a::lot::of::time::if_::i::" 23207 "just::gave::up::and_::went::mad::now {\n" 23208 "int i;\n" 23209 "int j;\n" 23210 "} // namespace\n" 23211 " // " 23212 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::" 23213 "and_::went::mad::now", 23214 Style)); 23215 } 23216 23217 TEST_F(FormatTest, LikelyUnlikely) { 23218 FormatStyle Style = getLLVMStyle(); 23219 23220 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23221 " return 29;\n" 23222 "}", 23223 Style); 23224 23225 verifyFormat("if (argc > 5) [[likely]] {\n" 23226 " return 29;\n" 23227 "}", 23228 Style); 23229 23230 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23231 " return 29;\n" 23232 "} else [[likely]] {\n" 23233 " return 42;\n" 23234 "}\n", 23235 Style); 23236 23237 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23238 " return 29;\n" 23239 "} else if (argc > 10) [[likely]] {\n" 23240 " return 99;\n" 23241 "} else {\n" 23242 " return 42;\n" 23243 "}\n", 23244 Style); 23245 23246 verifyFormat("if (argc > 5) [[gnu::unused]] {\n" 23247 " return 29;\n" 23248 "}", 23249 Style); 23250 23251 verifyFormat("if (argc > 5) [[unlikely]]\n" 23252 " return 29;\n", 23253 Style); 23254 verifyFormat("if (argc > 5) [[likely]]\n" 23255 " return 29;\n", 23256 Style); 23257 23258 Style.AttributeMacros.push_back("UNLIKELY"); 23259 Style.AttributeMacros.push_back("LIKELY"); 23260 verifyFormat("if (argc > 5) UNLIKELY\n" 23261 " return 29;\n", 23262 Style); 23263 23264 verifyFormat("if (argc > 5) UNLIKELY {\n" 23265 " return 29;\n" 23266 "}", 23267 Style); 23268 verifyFormat("if (argc > 5) UNLIKELY {\n" 23269 " return 29;\n" 23270 "} else [[likely]] {\n" 23271 " return 42;\n" 23272 "}\n", 23273 Style); 23274 verifyFormat("if (argc > 5) UNLIKELY {\n" 23275 " return 29;\n" 23276 "} else LIKELY {\n" 23277 " return 42;\n" 23278 "}\n", 23279 Style); 23280 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23281 " return 29;\n" 23282 "} else LIKELY {\n" 23283 " return 42;\n" 23284 "}\n", 23285 Style); 23286 } 23287 23288 TEST_F(FormatTest, PenaltyIndentedWhitespace) { 23289 verifyFormat("Constructor()\n" 23290 " : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 23291 " aaaa(aaaaaaaaaaaaaaaaaa, " 23292 "aaaaaaaaaaaaaaaaaat))"); 23293 verifyFormat("Constructor()\n" 23294 " : aaaaaaaaaaaaa(aaaaaa), " 23295 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)"); 23296 23297 FormatStyle StyleWithWhitespacePenalty = getLLVMStyle(); 23298 StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5; 23299 verifyFormat("Constructor()\n" 23300 " : aaaaaa(aaaaaa),\n" 23301 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 23302 " aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))", 23303 StyleWithWhitespacePenalty); 23304 verifyFormat("Constructor()\n" 23305 " : aaaaaaaaaaaaa(aaaaaa), " 23306 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)", 23307 StyleWithWhitespacePenalty); 23308 } 23309 23310 TEST_F(FormatTest, LLVMDefaultStyle) { 23311 FormatStyle Style = getLLVMStyle(); 23312 verifyFormat("extern \"C\" {\n" 23313 "int foo();\n" 23314 "}", 23315 Style); 23316 } 23317 TEST_F(FormatTest, GNUDefaultStyle) { 23318 FormatStyle Style = getGNUStyle(); 23319 verifyFormat("extern \"C\"\n" 23320 "{\n" 23321 " int foo ();\n" 23322 "}", 23323 Style); 23324 } 23325 TEST_F(FormatTest, MozillaDefaultStyle) { 23326 FormatStyle Style = getMozillaStyle(); 23327 verifyFormat("extern \"C\"\n" 23328 "{\n" 23329 " int foo();\n" 23330 "}", 23331 Style); 23332 } 23333 TEST_F(FormatTest, GoogleDefaultStyle) { 23334 FormatStyle Style = getGoogleStyle(); 23335 verifyFormat("extern \"C\" {\n" 23336 "int foo();\n" 23337 "}", 23338 Style); 23339 } 23340 TEST_F(FormatTest, ChromiumDefaultStyle) { 23341 FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp); 23342 verifyFormat("extern \"C\" {\n" 23343 "int foo();\n" 23344 "}", 23345 Style); 23346 } 23347 TEST_F(FormatTest, MicrosoftDefaultStyle) { 23348 FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp); 23349 verifyFormat("extern \"C\"\n" 23350 "{\n" 23351 " int foo();\n" 23352 "}", 23353 Style); 23354 } 23355 TEST_F(FormatTest, WebKitDefaultStyle) { 23356 FormatStyle Style = getWebKitStyle(); 23357 verifyFormat("extern \"C\" {\n" 23358 "int foo();\n" 23359 "}", 23360 Style); 23361 } 23362 23363 TEST_F(FormatTest, Concepts) { 23364 EXPECT_EQ(getLLVMStyle().BreakBeforeConceptDeclarations, 23365 FormatStyle::BBCDS_Always); 23366 verifyFormat("template <typename T>\n" 23367 "concept True = true;"); 23368 23369 verifyFormat("template <typename T>\n" 23370 "concept C = ((false || foo()) && C2<T>) ||\n" 23371 " (std::trait<T>::value && Baz) || sizeof(T) >= 6;", 23372 getLLVMStyleWithColumns(60)); 23373 23374 verifyFormat("template <typename T>\n" 23375 "concept DelayedCheck = true && requires(T t) { t.bar(); } && " 23376 "sizeof(T) <= 8;"); 23377 23378 verifyFormat("template <typename T>\n" 23379 "concept DelayedCheck = true && requires(T t) {\n" 23380 " t.bar();\n" 23381 " t.baz();\n" 23382 " } && sizeof(T) <= 8;"); 23383 23384 verifyFormat("template <typename T>\n" 23385 "concept DelayedCheck = true && requires(T t) { // Comment\n" 23386 " t.bar();\n" 23387 " t.baz();\n" 23388 " } && sizeof(T) <= 8;"); 23389 23390 verifyFormat("template <typename T>\n" 23391 "concept DelayedCheck = false || requires(T t) { t.bar(); } && " 23392 "sizeof(T) <= 8;"); 23393 23394 verifyFormat("template <typename T>\n" 23395 "concept DelayedCheck = !!false || requires(T t) { t.bar(); } " 23396 "&& sizeof(T) <= 8;"); 23397 23398 verifyFormat( 23399 "template <typename T>\n" 23400 "concept DelayedCheck = static_cast<bool>(0) ||\n" 23401 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 23402 23403 verifyFormat("template <typename T>\n" 23404 "concept DelayedCheck = bool(0) || requires(T t) { t.bar(); } " 23405 "&& sizeof(T) <= 8;"); 23406 23407 verifyFormat( 23408 "template <typename T>\n" 23409 "concept DelayedCheck = (bool)(0) ||\n" 23410 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 23411 23412 verifyFormat("template <typename T>\n" 23413 "concept DelayedCheck = (bool)0 || requires(T t) { t.bar(); } " 23414 "&& sizeof(T) <= 8;"); 23415 23416 verifyFormat("template <typename T>\n" 23417 "concept Size = sizeof(T) >= 5 && requires(T t) { t.bar(); } && " 23418 "sizeof(T) <= 8;"); 23419 23420 verifyFormat("template <typename T>\n" 23421 "concept Size = 2 < 5 && 2 <= 5 && 8 >= 5 && 8 > 5 &&\n" 23422 " requires(T t) {\n" 23423 " t.bar();\n" 23424 " t.baz();\n" 23425 " } && sizeof(T) <= 8 && !(4 < 3);", 23426 getLLVMStyleWithColumns(60)); 23427 23428 verifyFormat("template <typename T>\n" 23429 "concept TrueOrNot = IsAlwaysTrue || IsNeverTrue;"); 23430 23431 verifyFormat("template <typename T>\n" 23432 "concept C = foo();"); 23433 23434 verifyFormat("template <typename T>\n" 23435 "concept C = foo(T());"); 23436 23437 verifyFormat("template <typename T>\n" 23438 "concept C = foo(T{});"); 23439 23440 verifyFormat("template <typename T>\n" 23441 "concept Size = V<sizeof(T)>::Value > 5;"); 23442 23443 verifyFormat("template <typename T>\n" 23444 "concept True = S<T>::Value;"); 23445 23446 verifyFormat( 23447 "template <typename T>\n" 23448 "concept C = []() { return true; }() && requires(T t) { t.bar(); } &&\n" 23449 " sizeof(T) <= 8;"); 23450 23451 // FIXME: This is misformatted because the fake l paren starts at bool, not at 23452 // the lambda l square. 23453 verifyFormat("template <typename T>\n" 23454 "concept C = [] -> bool { return true; }() && requires(T t) { " 23455 "t.bar(); } &&\n" 23456 " sizeof(T) <= 8;"); 23457 23458 verifyFormat( 23459 "template <typename T>\n" 23460 "concept C = decltype([]() { return std::true_type{}; }())::value &&\n" 23461 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 23462 23463 verifyFormat("template <typename T>\n" 23464 "concept C = decltype([]() { return std::true_type{}; " 23465 "}())::value && requires(T t) { t.bar(); } && sizeof(T) <= 8;", 23466 getLLVMStyleWithColumns(120)); 23467 23468 verifyFormat("template <typename T>\n" 23469 "concept C = decltype([]() -> std::true_type { return {}; " 23470 "}())::value &&\n" 23471 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 23472 23473 verifyFormat("template <typename T>\n" 23474 "concept C = true;\n" 23475 "Foo Bar;"); 23476 23477 verifyFormat("template <typename T>\n" 23478 "concept Hashable = requires(T a) {\n" 23479 " { std::hash<T>{}(a) } -> " 23480 "std::convertible_to<std::size_t>;\n" 23481 " };"); 23482 23483 verifyFormat( 23484 "template <typename T>\n" 23485 "concept EqualityComparable = requires(T a, T b) {\n" 23486 " { a == b } -> std::same_as<bool>;\n" 23487 " };"); 23488 23489 verifyFormat( 23490 "template <typename T>\n" 23491 "concept EqualityComparable = requires(T a, T b) {\n" 23492 " { a == b } -> std::same_as<bool>;\n" 23493 " { a != b } -> std::same_as<bool>;\n" 23494 " };"); 23495 23496 verifyFormat("template <typename T>\n" 23497 "concept WeakEqualityComparable = requires(T a, T b) {\n" 23498 " { a == b };\n" 23499 " { a != b };\n" 23500 " };"); 23501 23502 verifyFormat("template <typename T>\n" 23503 "concept HasSizeT = requires { typename T::size_t; };"); 23504 23505 verifyFormat("template <typename T>\n" 23506 "concept Semiregular =\n" 23507 " DefaultConstructible<T> && CopyConstructible<T> && " 23508 "CopyAssignable<T> &&\n" 23509 " requires(T a, std::size_t n) {\n" 23510 " requires Same<T *, decltype(&a)>;\n" 23511 " { a.~T() } noexcept;\n" 23512 " requires Same<T *, decltype(new T)>;\n" 23513 " requires Same<T *, decltype(new T[n])>;\n" 23514 " { delete new T; };\n" 23515 " { delete new T[n]; };\n" 23516 " };"); 23517 23518 verifyFormat("template <typename T>\n" 23519 "concept Semiregular =\n" 23520 " requires(T a, std::size_t n) {\n" 23521 " requires Same<T *, decltype(&a)>;\n" 23522 " { a.~T() } noexcept;\n" 23523 " requires Same<T *, decltype(new T)>;\n" 23524 " requires Same<T *, decltype(new T[n])>;\n" 23525 " { delete new T; };\n" 23526 " { delete new T[n]; };\n" 23527 " { new T } -> std::same_as<T *>;\n" 23528 " } && DefaultConstructible<T> && CopyConstructible<T> && " 23529 "CopyAssignable<T>;"); 23530 23531 verifyFormat( 23532 "template <typename T>\n" 23533 "concept Semiregular =\n" 23534 " DefaultConstructible<T> && requires(T a, std::size_t n) {\n" 23535 " requires Same<T *, decltype(&a)>;\n" 23536 " { a.~T() } noexcept;\n" 23537 " requires Same<T *, decltype(new T)>;\n" 23538 " requires Same<T *, decltype(new " 23539 "T[n])>;\n" 23540 " { delete new T; };\n" 23541 " { delete new T[n]; };\n" 23542 " } && CopyConstructible<T> && " 23543 "CopyAssignable<T>;"); 23544 23545 verifyFormat("template <typename T>\n" 23546 "concept Two = requires(T t) {\n" 23547 " { t.foo() } -> std::same_as<Bar>;\n" 23548 " } && requires(T &&t) {\n" 23549 " { t.foo() } -> std::same_as<Bar &&>;\n" 23550 " };"); 23551 23552 verifyFormat( 23553 "template <typename T>\n" 23554 "concept C = requires(T x) {\n" 23555 " { *x } -> std::convertible_to<typename T::inner>;\n" 23556 " { x + 1 } noexcept -> std::same_as<int>;\n" 23557 " { x * 1 } -> std::convertible_to<T>;\n" 23558 " };"); 23559 23560 verifyFormat( 23561 "template <typename T, typename U = T>\n" 23562 "concept Swappable = requires(T &&t, U &&u) {\n" 23563 " swap(std::forward<T>(t), std::forward<U>(u));\n" 23564 " swap(std::forward<U>(u), std::forward<T>(t));\n" 23565 " };"); 23566 23567 verifyFormat("template <typename T, typename U>\n" 23568 "concept Common = requires(T &&t, U &&u) {\n" 23569 " typename CommonType<T, U>;\n" 23570 " { CommonType<T, U>(std::forward<T>(t)) };\n" 23571 " };"); 23572 23573 verifyFormat("template <typename T, typename U>\n" 23574 "concept Common = requires(T &&t, U &&u) {\n" 23575 " typename CommonType<T, U>;\n" 23576 " { CommonType<T, U>{std::forward<T>(t)} };\n" 23577 " };"); 23578 23579 verifyFormat( 23580 "template <typename T>\n" 23581 "concept C = requires(T t) {\n" 23582 " requires Bar<T> && Foo<T>;\n" 23583 " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n" 23584 " };"); 23585 23586 verifyFormat("template <typename T>\n" 23587 "concept HasFoo = requires(T t) {\n" 23588 " { t.foo() };\n" 23589 " t.foo();\n" 23590 " };\n" 23591 "template <typename T>\n" 23592 "concept HasBar = requires(T t) {\n" 23593 " { t.bar() };\n" 23594 " t.bar();\n" 23595 " };"); 23596 23597 verifyFormat("template <typename T>\n" 23598 "concept Large = sizeof(T) > 10;"); 23599 23600 verifyFormat("template <typename T, typename U>\n" 23601 "concept FooableWith = requires(T t, U u) {\n" 23602 " typename T::foo_type;\n" 23603 " { t.foo(u) } -> typename T::foo_type;\n" 23604 " t++;\n" 23605 " };\n" 23606 "void doFoo(FooableWith<int> auto t) { t.foo(3); }"); 23607 23608 verifyFormat("template <typename T>\n" 23609 "concept Context = is_specialization_of_v<context, T>;"); 23610 23611 verifyFormat("template <typename T>\n" 23612 "concept Node = std::is_object_v<T>;"); 23613 23614 auto Style = getLLVMStyle(); 23615 Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Allowed; 23616 23617 verifyFormat( 23618 "template <typename T>\n" 23619 "concept C = requires(T t) {\n" 23620 " requires Bar<T> && Foo<T>;\n" 23621 " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n" 23622 " };", 23623 Style); 23624 23625 verifyFormat("template <typename T>\n" 23626 "concept HasFoo = requires(T t) {\n" 23627 " { t.foo() };\n" 23628 " t.foo();\n" 23629 " };\n" 23630 "template <typename T>\n" 23631 "concept HasBar = requires(T t) {\n" 23632 " { t.bar() };\n" 23633 " t.bar();\n" 23634 " };", 23635 Style); 23636 23637 verifyFormat("template <typename T> concept True = true;", Style); 23638 23639 verifyFormat("template <typename T>\n" 23640 "concept C = decltype([]() -> std::true_type { return {}; " 23641 "}())::value &&\n" 23642 " requires(T t) { t.bar(); } && sizeof(T) <= 8;", 23643 Style); 23644 23645 verifyFormat("template <typename T>\n" 23646 "concept Semiregular =\n" 23647 " DefaultConstructible<T> && CopyConstructible<T> && " 23648 "CopyAssignable<T> &&\n" 23649 " requires(T a, std::size_t n) {\n" 23650 " requires Same<T *, decltype(&a)>;\n" 23651 " { a.~T() } noexcept;\n" 23652 " requires Same<T *, decltype(new T)>;\n" 23653 " requires Same<T *, decltype(new T[n])>;\n" 23654 " { delete new T; };\n" 23655 " { delete new T[n]; };\n" 23656 " };", 23657 Style); 23658 23659 Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Never; 23660 23661 verifyFormat("template <typename T> concept C =\n" 23662 " requires(T t) {\n" 23663 " requires Bar<T> && Foo<T>;\n" 23664 " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n" 23665 " };", 23666 Style); 23667 23668 verifyFormat("template <typename T> concept HasFoo = requires(T t) {\n" 23669 " { t.foo() };\n" 23670 " t.foo();\n" 23671 " };\n" 23672 "template <typename T> concept HasBar = requires(T t) {\n" 23673 " { t.bar() };\n" 23674 " t.bar();\n" 23675 " };", 23676 Style); 23677 23678 verifyFormat("template <typename T> concept True = true;", Style); 23679 23680 verifyFormat( 23681 "template <typename T> concept C = decltype([]() -> std::true_type {\n" 23682 " return {};\n" 23683 " }())::value\n" 23684 " && requires(T t) { t.bar(); } &&\n" 23685 " sizeof(T) <= 8;", 23686 Style); 23687 23688 verifyFormat("template <typename T> concept Semiregular =\n" 23689 " DefaultConstructible<T> && CopyConstructible<T> && " 23690 "CopyAssignable<T> &&\n" 23691 " requires(T a, std::size_t n) {\n" 23692 " requires Same<T *, decltype(&a)>;\n" 23693 " { a.~T() } noexcept;\n" 23694 " requires Same<T *, decltype(new T)>;\n" 23695 " requires Same<T *, decltype(new T[n])>;\n" 23696 " { delete new T; };\n" 23697 " { delete new T[n]; };\n" 23698 " };", 23699 Style); 23700 23701 // The following tests are invalid C++, we just want to make sure we don't 23702 // assert. 23703 verifyFormat("template <typename T>\n" 23704 "concept C = requires C2<T>;"); 23705 23706 verifyFormat("template <typename T>\n" 23707 "concept C = 5 + 4;"); 23708 23709 verifyFormat("template <typename T>\n" 23710 "concept C =\n" 23711 "class X;"); 23712 23713 verifyFormat("template <typename T>\n" 23714 "concept C = [] && true;"); 23715 23716 verifyFormat("template <typename T>\n" 23717 "concept C = [] && requires(T t) { typename T::size_type; };"); 23718 } 23719 23720 TEST_F(FormatTest, RequiresClauses) { 23721 auto Style = getLLVMStyle(); 23722 EXPECT_EQ(Style.RequiresClausePosition, FormatStyle::RCPS_OwnLine); 23723 EXPECT_EQ(Style.IndentRequiresClause, true); 23724 23725 verifyFormat("template <typename T>\n" 23726 " requires(Foo<T> && std::trait<T>)\n" 23727 "struct Bar;", 23728 Style); 23729 23730 verifyFormat("template <typename T>\n" 23731 " requires(Foo<T> && std::trait<T>)\n" 23732 "class Bar {\n" 23733 "public:\n" 23734 " Bar(T t);\n" 23735 " bool baz();\n" 23736 "};", 23737 Style); 23738 23739 verifyFormat( 23740 "template <typename T>\n" 23741 " requires requires(T &&t) {\n" 23742 " typename T::I;\n" 23743 " requires(F<typename T::I> && std::trait<typename T::I>);\n" 23744 " }\n" 23745 "Bar(T) -> Bar<typename T::I>;", 23746 Style); 23747 23748 verifyFormat("template <typename T>\n" 23749 " requires(Foo<T> && std::trait<T>)\n" 23750 "constexpr T MyGlobal;", 23751 Style); 23752 23753 verifyFormat("template <typename T>\n" 23754 " requires Foo<T> && requires(T t) {\n" 23755 " { t.baz() } -> std::same_as<bool>;\n" 23756 " requires std::same_as<T::Factor, int>;\n" 23757 " }\n" 23758 "inline int bar(T t) {\n" 23759 " return t.baz() ? T::Factor : 5;\n" 23760 "}", 23761 Style); 23762 23763 verifyFormat("template <typename T>\n" 23764 "inline int bar(T t)\n" 23765 " requires Foo<T> && requires(T t) {\n" 23766 " { t.baz() } -> std::same_as<bool>;\n" 23767 " requires std::same_as<T::Factor, int>;\n" 23768 " }\n" 23769 "{\n" 23770 " return t.baz() ? T::Factor : 5;\n" 23771 "}", 23772 Style); 23773 23774 verifyFormat("template <typename T>\n" 23775 " requires F<T>\n" 23776 "int bar(T t) {\n" 23777 " return 5;\n" 23778 "}", 23779 Style); 23780 23781 verifyFormat("template <typename T>\n" 23782 "int bar(T t)\n" 23783 " requires F<T>\n" 23784 "{\n" 23785 " return 5;\n" 23786 "}", 23787 Style); 23788 23789 Style.IndentRequiresClause = false; 23790 verifyFormat("template <typename T>\n" 23791 "requires F<T>\n" 23792 "int bar(T t) {\n" 23793 " return 5;\n" 23794 "}", 23795 Style); 23796 23797 verifyFormat("template <typename T>\n" 23798 "int bar(T t)\n" 23799 "requires F<T>\n" 23800 "{\n" 23801 " return 5;\n" 23802 "}", 23803 Style); 23804 23805 Style.RequiresClausePosition = FormatStyle::RCPS_SingleLine; 23806 verifyFormat("template <typename T> requires Foo<T> struct Bar {};\n" 23807 "template <typename T> requires Foo<T> void bar() {}\n" 23808 "template <typename T> void bar() requires Foo<T> {}\n" 23809 "template <typename T> requires Foo<T> Bar(T) -> Bar<T>;", 23810 Style); 23811 23812 auto ColumnStyle = Style; 23813 ColumnStyle.ColumnLimit = 40; 23814 verifyFormat("template <typename AAAAAAA>\n" 23815 "requires Foo<T> struct Bar {};\n" 23816 "template <typename AAAAAAA>\n" 23817 "requires Foo<T> void bar() {}\n" 23818 "template <typename AAAAAAA>\n" 23819 "void bar() requires Foo<T> {}\n" 23820 "template <typename AAAAAAA>\n" 23821 "requires Foo<T> Baz(T) -> Baz<T>;", 23822 ColumnStyle); 23823 23824 verifyFormat("template <typename T>\n" 23825 "requires Foo<AAAAAAA> struct Bar {};\n" 23826 "template <typename T>\n" 23827 "requires Foo<AAAAAAA> void bar() {}\n" 23828 "template <typename T>\n" 23829 "void bar() requires Foo<AAAAAAA> {}\n" 23830 "template <typename T>\n" 23831 "requires Foo<AAAAAAA> Bar(T) -> Bar<T>;", 23832 ColumnStyle); 23833 23834 verifyFormat("template <typename AAAAAAA>\n" 23835 "requires Foo<AAAAAAAAAAAAAAAA>\n" 23836 "struct Bar {};\n" 23837 "template <typename AAAAAAA>\n" 23838 "requires Foo<AAAAAAAAAAAAAAAA>\n" 23839 "void bar() {}\n" 23840 "template <typename AAAAAAA>\n" 23841 "void bar()\n" 23842 " requires Foo<AAAAAAAAAAAAAAAA> {}\n" 23843 "template <typename AAAAAAA>\n" 23844 "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n" 23845 "template <typename AAAAAAA>\n" 23846 "requires Foo<AAAAAAAAAAAAAAAA>\n" 23847 "Bar(T) -> Bar<T>;", 23848 ColumnStyle); 23849 23850 Style.RequiresClausePosition = FormatStyle::RCPS_WithFollowing; 23851 ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithFollowing; 23852 23853 verifyFormat("template <typename T>\n" 23854 "requires Foo<T> struct Bar {};\n" 23855 "template <typename T>\n" 23856 "requires Foo<T> void bar() {}\n" 23857 "template <typename T>\n" 23858 "void bar()\n" 23859 "requires Foo<T> {}\n" 23860 "template <typename T>\n" 23861 "requires Foo<T> Bar(T) -> Bar<T>;", 23862 Style); 23863 23864 verifyFormat("template <typename AAAAAAA>\n" 23865 "requires Foo<AAAAAAAAAAAAAAAA>\n" 23866 "struct Bar {};\n" 23867 "template <typename AAAAAAA>\n" 23868 "requires Foo<AAAAAAAAAAAAAAAA>\n" 23869 "void bar() {}\n" 23870 "template <typename AAAAAAA>\n" 23871 "void bar()\n" 23872 "requires Foo<AAAAAAAAAAAAAAAA> {}\n" 23873 "template <typename AAAAAAA>\n" 23874 "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n" 23875 "template <typename AAAAAAA>\n" 23876 "requires Foo<AAAAAAAAAAAAAAAA>\n" 23877 "Bar(T) -> Bar<T>;", 23878 ColumnStyle); 23879 23880 Style.IndentRequiresClause = true; 23881 ColumnStyle.IndentRequiresClause = true; 23882 23883 verifyFormat("template <typename T>\n" 23884 " requires Foo<T> struct Bar {};\n" 23885 "template <typename T>\n" 23886 " requires Foo<T> void bar() {}\n" 23887 "template <typename T>\n" 23888 "void bar()\n" 23889 " requires Foo<T> {}\n" 23890 "template <typename T>\n" 23891 " requires Foo<T> Bar(T) -> Bar<T>;", 23892 Style); 23893 23894 verifyFormat("template <typename AAAAAAA>\n" 23895 " requires Foo<AAAAAAAAAAAAAAAA>\n" 23896 "struct Bar {};\n" 23897 "template <typename AAAAAAA>\n" 23898 " requires Foo<AAAAAAAAAAAAAAAA>\n" 23899 "void bar() {}\n" 23900 "template <typename AAAAAAA>\n" 23901 "void bar()\n" 23902 " requires Foo<AAAAAAAAAAAAAAAA> {}\n" 23903 "template <typename AAAAAAA>\n" 23904 " requires Foo<AAAAAA> Bar(T) -> Bar<T>;\n" 23905 "template <typename AAAAAAA>\n" 23906 " requires Foo<AAAAAAAAAAAAAAAA>\n" 23907 "Bar(T) -> Bar<T>;", 23908 ColumnStyle); 23909 23910 Style.RequiresClausePosition = FormatStyle::RCPS_WithPreceding; 23911 ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithPreceding; 23912 23913 verifyFormat("template <typename T> requires Foo<T>\n" 23914 "struct Bar {};\n" 23915 "template <typename T> requires Foo<T>\n" 23916 "void bar() {}\n" 23917 "template <typename T>\n" 23918 "void bar() requires Foo<T>\n" 23919 "{}\n" 23920 "template <typename T> requires Foo<T>\n" 23921 "Bar(T) -> Bar<T>;", 23922 Style); 23923 23924 verifyFormat("template <typename AAAAAAA>\n" 23925 "requires Foo<AAAAAAAAAAAAAAAA>\n" 23926 "struct Bar {};\n" 23927 "template <typename AAAAAAA>\n" 23928 "requires Foo<AAAAAAAAAAAAAAAA>\n" 23929 "void bar() {}\n" 23930 "template <typename AAAAAAA>\n" 23931 "void bar()\n" 23932 " requires Foo<AAAAAAAAAAAAAAAA>\n" 23933 "{}\n" 23934 "template <typename AAAAAAA>\n" 23935 "requires Foo<AAAAAAAA>\n" 23936 "Bar(T) -> Bar<T>;\n" 23937 "template <typename AAAAAAA>\n" 23938 "requires Foo<AAAAAAAAAAAAAAAA>\n" 23939 "Bar(T) -> Bar<T>;", 23940 ColumnStyle); 23941 } 23942 23943 TEST_F(FormatTest, StatementAttributeLikeMacros) { 23944 FormatStyle Style = getLLVMStyle(); 23945 StringRef Source = "void Foo::slot() {\n" 23946 " unsigned char MyChar = 'x';\n" 23947 " emit signal(MyChar);\n" 23948 " Q_EMIT signal(MyChar);\n" 23949 "}"; 23950 23951 EXPECT_EQ(Source, format(Source, Style)); 23952 23953 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 23954 EXPECT_EQ("void Foo::slot() {\n" 23955 " unsigned char MyChar = 'x';\n" 23956 " emit signal(MyChar);\n" 23957 " Q_EMIT signal(MyChar);\n" 23958 "}", 23959 format(Source, Style)); 23960 23961 Style.StatementAttributeLikeMacros.push_back("emit"); 23962 EXPECT_EQ(Source, format(Source, Style)); 23963 23964 Style.StatementAttributeLikeMacros = {}; 23965 EXPECT_EQ("void Foo::slot() {\n" 23966 " unsigned char MyChar = 'x';\n" 23967 " emit signal(MyChar);\n" 23968 " Q_EMIT signal(MyChar);\n" 23969 "}", 23970 format(Source, Style)); 23971 } 23972 23973 TEST_F(FormatTest, IndentAccessModifiers) { 23974 FormatStyle Style = getLLVMStyle(); 23975 Style.IndentAccessModifiers = true; 23976 // Members are *two* levels below the record; 23977 // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation. 23978 verifyFormat("class C {\n" 23979 " int i;\n" 23980 "};\n", 23981 Style); 23982 verifyFormat("union C {\n" 23983 " int i;\n" 23984 " unsigned u;\n" 23985 "};\n", 23986 Style); 23987 // Access modifiers should be indented one level below the record. 23988 verifyFormat("class C {\n" 23989 " public:\n" 23990 " int i;\n" 23991 "};\n", 23992 Style); 23993 verifyFormat("struct S {\n" 23994 " private:\n" 23995 " class C {\n" 23996 " int j;\n" 23997 "\n" 23998 " public:\n" 23999 " C();\n" 24000 " };\n" 24001 "\n" 24002 " public:\n" 24003 " int i;\n" 24004 "};\n", 24005 Style); 24006 // Enumerations are not records and should be unaffected. 24007 Style.AllowShortEnumsOnASingleLine = false; 24008 verifyFormat("enum class E {\n" 24009 " A,\n" 24010 " B\n" 24011 "};\n", 24012 Style); 24013 // Test with a different indentation width; 24014 // also proves that the result is Style.AccessModifierOffset agnostic. 24015 Style.IndentWidth = 3; 24016 verifyFormat("class C {\n" 24017 " public:\n" 24018 " int i;\n" 24019 "};\n", 24020 Style); 24021 } 24022 24023 TEST_F(FormatTest, LimitlessStringsAndComments) { 24024 auto Style = getLLVMStyleWithColumns(0); 24025 constexpr StringRef Code = 24026 "/**\n" 24027 " * This is a multiline comment with quite some long lines, at least for " 24028 "the LLVM Style.\n" 24029 " * We will redo this with strings and line comments. Just to check if " 24030 "everything is working.\n" 24031 " */\n" 24032 "bool foo() {\n" 24033 " /* Single line multi line comment. */\n" 24034 " const std::string String = \"This is a multiline string with quite " 24035 "some long lines, at least for the LLVM Style.\"\n" 24036 " \"We already did it with multi line " 24037 "comments, and we will do it with line comments. Just to check if " 24038 "everything is working.\";\n" 24039 " // This is a line comment (block) with quite some long lines, at " 24040 "least for the LLVM Style.\n" 24041 " // We already did this with multi line comments and strings. Just to " 24042 "check if everything is working.\n" 24043 " const std::string SmallString = \"Hello World\";\n" 24044 " // Small line comment\n" 24045 " return String.size() > SmallString.size();\n" 24046 "}"; 24047 EXPECT_EQ(Code, format(Code, Style)); 24048 } 24049 24050 TEST_F(FormatTest, FormatDecayCopy) { 24051 // error cases from unit tests 24052 verifyFormat("foo(auto())"); 24053 verifyFormat("foo(auto{})"); 24054 verifyFormat("foo(auto({}))"); 24055 verifyFormat("foo(auto{{}})"); 24056 24057 verifyFormat("foo(auto(1))"); 24058 verifyFormat("foo(auto{1})"); 24059 verifyFormat("foo(new auto(1))"); 24060 verifyFormat("foo(new auto{1})"); 24061 verifyFormat("decltype(auto(1)) x;"); 24062 verifyFormat("decltype(auto{1}) x;"); 24063 verifyFormat("auto(x);"); 24064 verifyFormat("auto{x};"); 24065 verifyFormat("new auto{x};"); 24066 verifyFormat("auto{x} = y;"); 24067 verifyFormat("auto(x) = y;"); // actually a declaration, but this is clearly 24068 // the user's own fault 24069 verifyFormat("integral auto(x) = y;"); // actually a declaration, but this is 24070 // clearly the user's own fault 24071 verifyFormat("auto(*p)() = f;"); // actually a declaration; TODO FIXME 24072 } 24073 24074 TEST_F(FormatTest, Cpp20ModulesSupport) { 24075 FormatStyle Style = getLLVMStyle(); 24076 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 24077 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 24078 24079 verifyFormat("export import foo;", Style); 24080 verifyFormat("export import foo:bar;", Style); 24081 verifyFormat("export import foo.bar;", Style); 24082 verifyFormat("export import foo.bar:baz;", Style); 24083 verifyFormat("export import :bar;", Style); 24084 verifyFormat("export module foo:bar;", Style); 24085 verifyFormat("export module foo;", Style); 24086 verifyFormat("export module foo.bar;", Style); 24087 verifyFormat("export module foo.bar:baz;", Style); 24088 verifyFormat("export import <string_view>;", Style); 24089 24090 verifyFormat("export type_name var;", Style); 24091 verifyFormat("template <class T> export using A = B<T>;", Style); 24092 verifyFormat("export using A = B;", Style); 24093 verifyFormat("export int func() {\n" 24094 " foo();\n" 24095 "}", 24096 Style); 24097 verifyFormat("export struct {\n" 24098 " int foo;\n" 24099 "};", 24100 Style); 24101 verifyFormat("export {\n" 24102 " int foo;\n" 24103 "};", 24104 Style); 24105 verifyFormat("export export char const *hello() { return \"hello\"; }"); 24106 24107 verifyFormat("import bar;", Style); 24108 verifyFormat("import foo.bar;", Style); 24109 verifyFormat("import foo:bar;", Style); 24110 verifyFormat("import :bar;", Style); 24111 verifyFormat("import <ctime>;", Style); 24112 verifyFormat("import \"header\";", Style); 24113 24114 verifyFormat("module foo;", Style); 24115 verifyFormat("module foo:bar;", Style); 24116 verifyFormat("module foo.bar;", Style); 24117 verifyFormat("module;", Style); 24118 24119 verifyFormat("export namespace hi {\n" 24120 "const char *sayhi();\n" 24121 "}", 24122 Style); 24123 24124 verifyFormat("module :private;", Style); 24125 verifyFormat("import <foo/bar.h>;", Style); 24126 verifyFormat("import foo...bar;", Style); 24127 verifyFormat("import ..........;", Style); 24128 verifyFormat("module foo:private;", Style); 24129 verifyFormat("import a", Style); 24130 verifyFormat("module a", Style); 24131 verifyFormat("export import a", Style); 24132 verifyFormat("export module a", Style); 24133 24134 verifyFormat("import", Style); 24135 verifyFormat("module", Style); 24136 verifyFormat("export", Style); 24137 } 24138 24139 TEST_F(FormatTest, CoroutineForCoawait) { 24140 FormatStyle Style = getLLVMStyle(); 24141 verifyFormat("for co_await (auto x : range())\n ;"); 24142 verifyFormat("for (auto i : arr) {\n" 24143 "}", 24144 Style); 24145 verifyFormat("for co_await (auto i : arr) {\n" 24146 "}", 24147 Style); 24148 verifyFormat("for co_await (auto i : foo(T{})) {\n" 24149 "}", 24150 Style); 24151 } 24152 24153 TEST_F(FormatTest, CoroutineCoAwait) { 24154 verifyFormat("int x = co_await foo();"); 24155 verifyFormat("int x = (co_await foo());"); 24156 verifyFormat("co_await (42);"); 24157 verifyFormat("void operator co_await(int);"); 24158 verifyFormat("void operator co_await(a);"); 24159 verifyFormat("co_await a;"); 24160 verifyFormat("co_await missing_await_resume{};"); 24161 verifyFormat("co_await a; // comment"); 24162 verifyFormat("void test0() { co_await a; }"); 24163 verifyFormat("co_await co_await co_await foo();"); 24164 verifyFormat("co_await foo().bar();"); 24165 verifyFormat("co_await [this]() -> Task { co_return x; }"); 24166 verifyFormat("co_await [this](int a, int b) -> Task { co_return co_await " 24167 "foo(); }(x, y);"); 24168 24169 FormatStyle Style = getLLVMStyleWithColumns(40); 24170 verifyFormat("co_await [this](int a, int b) -> Task {\n" 24171 " co_return co_await foo();\n" 24172 "}(x, y);", 24173 Style); 24174 verifyFormat("co_await;"); 24175 } 24176 24177 TEST_F(FormatTest, CoroutineCoYield) { 24178 verifyFormat("int x = co_yield foo();"); 24179 verifyFormat("int x = (co_yield foo());"); 24180 verifyFormat("co_yield (42);"); 24181 verifyFormat("co_yield {42};"); 24182 verifyFormat("co_yield 42;"); 24183 verifyFormat("co_yield n++;"); 24184 verifyFormat("co_yield ++n;"); 24185 verifyFormat("co_yield;"); 24186 } 24187 24188 TEST_F(FormatTest, CoroutineCoReturn) { 24189 verifyFormat("co_return (42);"); 24190 verifyFormat("co_return;"); 24191 verifyFormat("co_return {};"); 24192 verifyFormat("co_return x;"); 24193 verifyFormat("co_return co_await foo();"); 24194 verifyFormat("co_return co_yield foo();"); 24195 } 24196 24197 TEST_F(FormatTest, EmptyShortBlock) { 24198 auto Style = getLLVMStyle(); 24199 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 24200 24201 verifyFormat("try {\n" 24202 " doA();\n" 24203 "} catch (Exception &e) {\n" 24204 " e.printStackTrace();\n" 24205 "}\n", 24206 Style); 24207 24208 verifyFormat("try {\n" 24209 " doA();\n" 24210 "} catch (Exception &e) {}\n", 24211 Style); 24212 } 24213 24214 TEST_F(FormatTest, ShortTemplatedArgumentLists) { 24215 auto Style = getLLVMStyle(); 24216 24217 verifyFormat("template <> struct S : Template<int (*)[]> {};\n", Style); 24218 verifyFormat("template <> struct S : Template<int (*)[10]> {};\n", Style); 24219 verifyFormat("struct Y : X<[] { return 0; }> {};", Style); 24220 verifyFormat("struct Y<[] { return 0; }> {};", Style); 24221 24222 verifyFormat("struct Z : X<decltype([] { return 0; }){}> {};", Style); 24223 verifyFormat("template <int N> struct Foo<char[N]> {};", Style); 24224 } 24225 24226 TEST_F(FormatTest, RemoveBraces) { 24227 FormatStyle Style = getLLVMStyle(); 24228 Style.RemoveBracesLLVM = true; 24229 24230 // The following eight test cases are fully-braced versions of the examples at 24231 // "llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single- 24232 // statement-bodies-of-if-else-loop-statements". 24233 24234 // 1. Omit the braces, since the body is simple and clearly associated with 24235 // the if. 24236 verifyFormat("if (isa<FunctionDecl>(D))\n" 24237 " handleFunctionDecl(D);\n" 24238 "else if (isa<VarDecl>(D))\n" 24239 " handleVarDecl(D);", 24240 "if (isa<FunctionDecl>(D)) {\n" 24241 " handleFunctionDecl(D);\n" 24242 "} else if (isa<VarDecl>(D)) {\n" 24243 " handleVarDecl(D);\n" 24244 "}", 24245 Style); 24246 24247 // 2. Here we document the condition itself and not the body. 24248 verifyFormat("if (isa<VarDecl>(D)) {\n" 24249 " // It is necessary that we explain the situation with this\n" 24250 " // surprisingly long comment, so it would be unclear\n" 24251 " // without the braces whether the following statement is in\n" 24252 " // the scope of the `if`.\n" 24253 " // Because the condition is documented, we can't really\n" 24254 " // hoist this comment that applies to the body above the\n" 24255 " // if.\n" 24256 " handleOtherDecl(D);\n" 24257 "}", 24258 Style); 24259 24260 // 3. Use braces on the outer `if` to avoid a potential dangling else 24261 // situation. 24262 verifyFormat("if (isa<VarDecl>(D)) {\n" 24263 " for (auto *A : D.attrs())\n" 24264 " if (shouldProcessAttr(A))\n" 24265 " handleAttr(A);\n" 24266 "}", 24267 "if (isa<VarDecl>(D)) {\n" 24268 " for (auto *A : D.attrs()) {\n" 24269 " if (shouldProcessAttr(A)) {\n" 24270 " handleAttr(A);\n" 24271 " }\n" 24272 " }\n" 24273 "}", 24274 Style); 24275 24276 // 4. Use braces for the `if` block to keep it uniform with the else block. 24277 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 24278 " handleFunctionDecl(D);\n" 24279 "} else {\n" 24280 " // In this else case, it is necessary that we explain the\n" 24281 " // situation with this surprisingly long comment, so it\n" 24282 " // would be unclear without the braces whether the\n" 24283 " // following statement is in the scope of the `if`.\n" 24284 " handleOtherDecl(D);\n" 24285 "}", 24286 Style); 24287 24288 // 5. This should also omit braces. The `for` loop contains only a single 24289 // statement, so it shouldn't have braces. The `if` also only contains a 24290 // single simple statement (the for loop), so it also should omit braces. 24291 verifyFormat("if (isa<FunctionDecl>(D))\n" 24292 " for (auto *A : D.attrs())\n" 24293 " handleAttr(A);", 24294 "if (isa<FunctionDecl>(D)) {\n" 24295 " for (auto *A : D.attrs()) {\n" 24296 " handleAttr(A);\n" 24297 " }\n" 24298 "}", 24299 Style); 24300 24301 // 6. Use braces for the outer `if` since the nested `for` is braced. 24302 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 24303 " for (auto *A : D.attrs()) {\n" 24304 " // In this for loop body, it is necessary that we explain\n" 24305 " // the situation with this surprisingly long comment,\n" 24306 " // forcing braces on the `for` block.\n" 24307 " handleAttr(A);\n" 24308 " }\n" 24309 "}", 24310 Style); 24311 24312 // 7. Use braces on the outer block because there are more than two levels of 24313 // nesting. 24314 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 24315 " for (auto *A : D.attrs())\n" 24316 " for (ssize_t i : llvm::seq<ssize_t>(count))\n" 24317 " handleAttrOnDecl(D, A, i);\n" 24318 "}", 24319 "if (isa<FunctionDecl>(D)) {\n" 24320 " for (auto *A : D.attrs()) {\n" 24321 " for (ssize_t i : llvm::seq<ssize_t>(count)) {\n" 24322 " handleAttrOnDecl(D, A, i);\n" 24323 " }\n" 24324 " }\n" 24325 "}", 24326 Style); 24327 24328 // 8. Use braces on the outer block because of a nested `if`, otherwise the 24329 // compiler would warn: `add explicit braces to avoid dangling else` 24330 verifyFormat("if (auto *D = dyn_cast<FunctionDecl>(D)) {\n" 24331 " if (shouldProcess(D))\n" 24332 " handleVarDecl(D);\n" 24333 " else\n" 24334 " markAsIgnored(D);\n" 24335 "}", 24336 "if (auto *D = dyn_cast<FunctionDecl>(D)) {\n" 24337 " if (shouldProcess(D)) {\n" 24338 " handleVarDecl(D);\n" 24339 " } else {\n" 24340 " markAsIgnored(D);\n" 24341 " }\n" 24342 "}", 24343 Style); 24344 24345 verifyFormat("if (a)\n" 24346 " b; // comment\n" 24347 "else if (c)\n" 24348 " d; /* comment */\n" 24349 "else\n" 24350 " e;", 24351 "if (a) {\n" 24352 " b; // comment\n" 24353 "} else if (c) {\n" 24354 " d; /* comment */\n" 24355 "} else {\n" 24356 " e;\n" 24357 "}", 24358 Style); 24359 24360 verifyFormat("if (a) {\n" 24361 " b;\n" 24362 " c;\n" 24363 "} else if (d) {\n" 24364 " e;\n" 24365 "}", 24366 Style); 24367 24368 verifyFormat("if (a) {\n" 24369 "#undef NDEBUG\n" 24370 " b;\n" 24371 "} else {\n" 24372 " c;\n" 24373 "}", 24374 Style); 24375 24376 verifyFormat("if (a) {\n" 24377 " // comment\n" 24378 "} else if (b) {\n" 24379 " c;\n" 24380 "}", 24381 Style); 24382 24383 verifyFormat("if (a) {\n" 24384 " b;\n" 24385 "} else {\n" 24386 " { c; }\n" 24387 "}", 24388 Style); 24389 24390 verifyFormat("if (a) {\n" 24391 " if (b) // comment\n" 24392 " c;\n" 24393 "} else if (d) {\n" 24394 " e;\n" 24395 "}", 24396 "if (a) {\n" 24397 " if (b) { // comment\n" 24398 " c;\n" 24399 " }\n" 24400 "} else if (d) {\n" 24401 " e;\n" 24402 "}", 24403 Style); 24404 24405 verifyFormat("if (a) {\n" 24406 " if (b) {\n" 24407 " c;\n" 24408 " // comment\n" 24409 " } else if (d) {\n" 24410 " e;\n" 24411 " }\n" 24412 "}", 24413 Style); 24414 24415 verifyFormat("if (a) {\n" 24416 " if (b)\n" 24417 " c;\n" 24418 "}", 24419 "if (a) {\n" 24420 " if (b) {\n" 24421 " c;\n" 24422 " }\n" 24423 "}", 24424 Style); 24425 24426 verifyFormat("if (a)\n" 24427 " if (b)\n" 24428 " c;\n" 24429 " else\n" 24430 " d;\n" 24431 "else\n" 24432 " e;", 24433 "if (a) {\n" 24434 " if (b) {\n" 24435 " c;\n" 24436 " } else {\n" 24437 " d;\n" 24438 " }\n" 24439 "} else {\n" 24440 " e;\n" 24441 "}", 24442 Style); 24443 24444 verifyFormat("if (a) {\n" 24445 " // comment\n" 24446 " if (b)\n" 24447 " c;\n" 24448 " else if (d)\n" 24449 " e;\n" 24450 "} else {\n" 24451 " g;\n" 24452 "}", 24453 "if (a) {\n" 24454 " // comment\n" 24455 " if (b) {\n" 24456 " c;\n" 24457 " } else if (d) {\n" 24458 " e;\n" 24459 " }\n" 24460 "} else {\n" 24461 " g;\n" 24462 "}", 24463 Style); 24464 24465 verifyFormat("if (a)\n" 24466 " b;\n" 24467 "else if (c)\n" 24468 " d;\n" 24469 "else\n" 24470 " e;", 24471 "if (a) {\n" 24472 " b;\n" 24473 "} else {\n" 24474 " if (c) {\n" 24475 " d;\n" 24476 " } else {\n" 24477 " e;\n" 24478 " }\n" 24479 "}", 24480 Style); 24481 24482 verifyFormat("if (a) {\n" 24483 " if (b)\n" 24484 " c;\n" 24485 " else if (d)\n" 24486 " e;\n" 24487 "} else {\n" 24488 " g;\n" 24489 "}", 24490 "if (a) {\n" 24491 " if (b)\n" 24492 " c;\n" 24493 " else {\n" 24494 " if (d)\n" 24495 " e;\n" 24496 " }\n" 24497 "} else {\n" 24498 " g;\n" 24499 "}", 24500 Style); 24501 24502 verifyFormat("if (a)\n" 24503 " b;\n" 24504 "else if (c)\n" 24505 " while (d)\n" 24506 " e;\n" 24507 "// comment", 24508 "if (a)\n" 24509 "{\n" 24510 " b;\n" 24511 "} else if (c) {\n" 24512 " while (d) {\n" 24513 " e;\n" 24514 " }\n" 24515 "}\n" 24516 "// comment", 24517 Style); 24518 24519 verifyFormat("if (a) {\n" 24520 " b;\n" 24521 "} else if (c) {\n" 24522 " d;\n" 24523 "} else {\n" 24524 " e;\n" 24525 " g;\n" 24526 "}", 24527 Style); 24528 24529 verifyFormat("if (a) {\n" 24530 " b;\n" 24531 "} else if (c) {\n" 24532 " d;\n" 24533 "} else {\n" 24534 " e;\n" 24535 "} // comment", 24536 Style); 24537 24538 verifyFormat("int abs = [](int i) {\n" 24539 " if (i >= 0)\n" 24540 " return i;\n" 24541 " return -i;\n" 24542 "};", 24543 "int abs = [](int i) {\n" 24544 " if (i >= 0) {\n" 24545 " return i;\n" 24546 " }\n" 24547 " return -i;\n" 24548 "};", 24549 Style); 24550 24551 // FIXME: See https://github.com/llvm/llvm-project/issues/53543. 24552 #if 0 24553 Style.ColumnLimit = 65; 24554 24555 verifyFormat("if (condition) {\n" 24556 " ff(Indices,\n" 24557 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 24558 "} else {\n" 24559 " ff(Indices,\n" 24560 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 24561 "}", 24562 Style); 24563 24564 Style.ColumnLimit = 20; 24565 24566 verifyFormat("if (a) {\n" 24567 " b = c + // 1 -\n" 24568 " d;\n" 24569 "}", 24570 Style); 24571 24572 verifyFormat("if (a) {\n" 24573 " b = c >= 0 ? d\n" 24574 " : e;\n" 24575 "}", 24576 "if (a) {\n" 24577 " b = c >= 0 ? d : e;\n" 24578 "}", 24579 Style); 24580 #endif 24581 24582 Style.ColumnLimit = 20; 24583 24584 verifyFormat("if (a)\n" 24585 " b = c > 0 ? d : e;", 24586 "if (a) {\n" 24587 " b = c > 0 ? d : e;\n" 24588 "}", 24589 Style); 24590 24591 Style.ColumnLimit = 0; 24592 24593 verifyFormat("if (a)\n" 24594 " b234567890223456789032345678904234567890 = " 24595 "c234567890223456789032345678904234567890;", 24596 "if (a) {\n" 24597 " b234567890223456789032345678904234567890 = " 24598 "c234567890223456789032345678904234567890;\n" 24599 "}", 24600 Style); 24601 } 24602 24603 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndent) { 24604 auto Style = getLLVMStyle(); 24605 24606 StringRef Short = "functionCall(paramA, paramB, paramC);\n" 24607 "void functionDecl(int a, int b, int c);"; 24608 24609 StringRef Medium = "functionCall(paramA, paramB, paramC, paramD, paramE, " 24610 "paramF, paramG, paramH, paramI);\n" 24611 "void functionDecl(int argumentA, int argumentB, int " 24612 "argumentC, int argumentD, int argumentE);"; 24613 24614 verifyFormat(Short, Style); 24615 24616 StringRef NoBreak = "functionCall(paramA, paramB, paramC, paramD, paramE, " 24617 "paramF, paramG, paramH,\n" 24618 " paramI);\n" 24619 "void functionDecl(int argumentA, int argumentB, int " 24620 "argumentC, int argumentD,\n" 24621 " int argumentE);"; 24622 24623 verifyFormat(NoBreak, Medium, Style); 24624 verifyFormat(NoBreak, 24625 "functionCall(\n" 24626 " paramA,\n" 24627 " paramB,\n" 24628 " paramC,\n" 24629 " paramD,\n" 24630 " paramE,\n" 24631 " paramF,\n" 24632 " paramG,\n" 24633 " paramH,\n" 24634 " paramI\n" 24635 ");\n" 24636 "void functionDecl(\n" 24637 " int argumentA,\n" 24638 " int argumentB,\n" 24639 " int argumentC,\n" 24640 " int argumentD,\n" 24641 " int argumentE\n" 24642 ");", 24643 Style); 24644 24645 verifyFormat("outerFunctionCall(nestedFunctionCall(argument1),\n" 24646 " nestedLongFunctionCall(argument1, " 24647 "argument2, argument3,\n" 24648 " argument4, " 24649 "argument5));", 24650 Style); 24651 24652 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 24653 24654 verifyFormat(Short, Style); 24655 verifyFormat( 24656 "functionCall(\n" 24657 " paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, " 24658 "paramI\n" 24659 ");\n" 24660 "void functionDecl(\n" 24661 " int argumentA, int argumentB, int argumentC, int argumentD, int " 24662 "argumentE\n" 24663 ");", 24664 Medium, Style); 24665 24666 Style.AllowAllArgumentsOnNextLine = false; 24667 Style.AllowAllParametersOfDeclarationOnNextLine = false; 24668 24669 verifyFormat(Short, Style); 24670 verifyFormat( 24671 "functionCall(\n" 24672 " paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, " 24673 "paramI\n" 24674 ");\n" 24675 "void functionDecl(\n" 24676 " int argumentA, int argumentB, int argumentC, int argumentD, int " 24677 "argumentE\n" 24678 ");", 24679 Medium, Style); 24680 24681 Style.BinPackArguments = false; 24682 Style.BinPackParameters = false; 24683 24684 verifyFormat(Short, Style); 24685 24686 verifyFormat("functionCall(\n" 24687 " paramA,\n" 24688 " paramB,\n" 24689 " paramC,\n" 24690 " paramD,\n" 24691 " paramE,\n" 24692 " paramF,\n" 24693 " paramG,\n" 24694 " paramH,\n" 24695 " paramI\n" 24696 ");\n" 24697 "void functionDecl(\n" 24698 " int argumentA,\n" 24699 " int argumentB,\n" 24700 " int argumentC,\n" 24701 " int argumentD,\n" 24702 " int argumentE\n" 24703 ");", 24704 Medium, Style); 24705 24706 verifyFormat("outerFunctionCall(\n" 24707 " nestedFunctionCall(argument1),\n" 24708 " nestedLongFunctionCall(\n" 24709 " argument1,\n" 24710 " argument2,\n" 24711 " argument3,\n" 24712 " argument4,\n" 24713 " argument5\n" 24714 " )\n" 24715 ");", 24716 Style); 24717 24718 verifyFormat("int a = (int)b;", Style); 24719 verifyFormat("int a = (int)b;", 24720 "int a = (\n" 24721 " int\n" 24722 ") b;", 24723 Style); 24724 24725 verifyFormat("return (true);", Style); 24726 verifyFormat("return (true);", 24727 "return (\n" 24728 " true\n" 24729 ");", 24730 Style); 24731 24732 verifyFormat("void foo();", Style); 24733 verifyFormat("void foo();", 24734 "void foo(\n" 24735 ");", 24736 Style); 24737 24738 verifyFormat("void foo() {}", Style); 24739 verifyFormat("void foo() {}", 24740 "void foo(\n" 24741 ") {\n" 24742 "}", 24743 Style); 24744 24745 verifyFormat("auto string = std::string();", Style); 24746 verifyFormat("auto string = std::string();", 24747 "auto string = std::string(\n" 24748 ");", 24749 Style); 24750 24751 verifyFormat("void (*functionPointer)() = nullptr;", Style); 24752 verifyFormat("void (*functionPointer)() = nullptr;", 24753 "void (\n" 24754 " *functionPointer\n" 24755 ")\n" 24756 "(\n" 24757 ") = nullptr;", 24758 Style); 24759 } 24760 24761 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentIfStatement) { 24762 auto Style = getLLVMStyle(); 24763 24764 verifyFormat("if (foo()) {\n" 24765 " return;\n" 24766 "}", 24767 Style); 24768 24769 verifyFormat("if (quitelongarg !=\n" 24770 " (alsolongarg - 1)) { // ABC is a very longgggggggggggg " 24771 "comment\n" 24772 " return;\n" 24773 "}", 24774 Style); 24775 24776 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 24777 24778 verifyFormat("if (foo()) {\n" 24779 " return;\n" 24780 "}", 24781 Style); 24782 24783 verifyFormat("if (quitelongarg !=\n" 24784 " (alsolongarg - 1)) { // ABC is a very longgggggggggggg " 24785 "comment\n" 24786 " return;\n" 24787 "}", 24788 Style); 24789 } 24790 24791 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentForStatement) { 24792 auto Style = getLLVMStyle(); 24793 24794 verifyFormat("for (int i = 0; i < 5; ++i) {\n" 24795 " doSomething();\n" 24796 "}", 24797 Style); 24798 24799 verifyFormat("for (int myReallyLongCountVariable = 0; " 24800 "myReallyLongCountVariable < count;\n" 24801 " myReallyLongCountVariable++) {\n" 24802 " doSomething();\n" 24803 "}", 24804 Style); 24805 24806 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 24807 24808 verifyFormat("for (int i = 0; i < 5; ++i) {\n" 24809 " doSomething();\n" 24810 "}", 24811 Style); 24812 24813 verifyFormat("for (int myReallyLongCountVariable = 0; " 24814 "myReallyLongCountVariable < count;\n" 24815 " myReallyLongCountVariable++) {\n" 24816 " doSomething();\n" 24817 "}", 24818 Style); 24819 } 24820 24821 TEST_F(FormatTest, UnderstandsDigraphs) { 24822 verifyFormat("int arr<:5:> = {};"); 24823 verifyFormat("int arr[5] = <%%>;"); 24824 verifyFormat("int arr<:::qualified_variable:> = {};"); 24825 verifyFormat("int arr[::qualified_variable] = <%%>;"); 24826 verifyFormat("%:include <header>"); 24827 verifyFormat("%:define A x##y"); 24828 verifyFormat("#define A x%:%:y"); 24829 } 24830 24831 } // namespace 24832 } // namespace format 24833 } // namespace clang 24834