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 verifyFormat("MACRO(return)"); 1866 verifyFormat("MACRO(co_await)"); 1867 verifyFormat("MACRO(co_return)"); 1868 verifyFormat("MACRO(co_yield)"); 1869 verifyFormat("MACRO(return, something)"); 1870 verifyFormat("MACRO(co_return, something)"); 1871 verifyFormat("MACRO(something##something)"); 1872 verifyFormat("MACRO(return##something)"); 1873 verifyFormat("MACRO(co_return##something)"); 1874 } 1875 1876 TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) { 1877 FormatStyle Style = getLLVMStyleWithColumns(60); 1878 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 1879 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse; 1880 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 1881 EXPECT_EQ("#define A \\\n" 1882 " if (HANDLEwernufrnuLwrmviferuvnierv) \\\n" 1883 " { \\\n" 1884 " RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n" 1885 " }\n" 1886 "X;", 1887 format("#define A \\\n" 1888 " if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n" 1889 " RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n" 1890 " }\n" 1891 "X;", 1892 Style)); 1893 } 1894 1895 TEST_F(FormatTest, ParseIfElse) { 1896 verifyFormat("if (true)\n" 1897 " if (true)\n" 1898 " if (true)\n" 1899 " f();\n" 1900 " else\n" 1901 " g();\n" 1902 " else\n" 1903 " h();\n" 1904 "else\n" 1905 " i();"); 1906 verifyFormat("if (true)\n" 1907 " if (true)\n" 1908 " if (true) {\n" 1909 " if (true)\n" 1910 " f();\n" 1911 " } else {\n" 1912 " g();\n" 1913 " }\n" 1914 " else\n" 1915 " h();\n" 1916 "else {\n" 1917 " i();\n" 1918 "}"); 1919 verifyFormat("if (true)\n" 1920 " if constexpr (true)\n" 1921 " if (true) {\n" 1922 " if constexpr (true)\n" 1923 " f();\n" 1924 " } else {\n" 1925 " g();\n" 1926 " }\n" 1927 " else\n" 1928 " h();\n" 1929 "else {\n" 1930 " i();\n" 1931 "}"); 1932 verifyFormat("if (true)\n" 1933 " if CONSTEXPR (true)\n" 1934 " if (true) {\n" 1935 " if CONSTEXPR (true)\n" 1936 " f();\n" 1937 " } else {\n" 1938 " g();\n" 1939 " }\n" 1940 " else\n" 1941 " h();\n" 1942 "else {\n" 1943 " i();\n" 1944 "}"); 1945 verifyFormat("void f() {\n" 1946 " if (a) {\n" 1947 " } else {\n" 1948 " }\n" 1949 "}"); 1950 } 1951 1952 TEST_F(FormatTest, ElseIf) { 1953 verifyFormat("if (a) {\n} else if (b) {\n}"); 1954 verifyFormat("if (a)\n" 1955 " f();\n" 1956 "else if (b)\n" 1957 " g();\n" 1958 "else\n" 1959 " h();"); 1960 verifyFormat("if (a)\n" 1961 " f();\n" 1962 "else // comment\n" 1963 " if (b) {\n" 1964 " g();\n" 1965 " h();\n" 1966 " }"); 1967 verifyFormat("if constexpr (a)\n" 1968 " f();\n" 1969 "else if constexpr (b)\n" 1970 " g();\n" 1971 "else\n" 1972 " h();"); 1973 verifyFormat("if CONSTEXPR (a)\n" 1974 " f();\n" 1975 "else if CONSTEXPR (b)\n" 1976 " g();\n" 1977 "else\n" 1978 " h();"); 1979 verifyFormat("if (a) {\n" 1980 " f();\n" 1981 "}\n" 1982 "// or else ..\n" 1983 "else {\n" 1984 " g()\n" 1985 "}"); 1986 1987 verifyFormat("if (a) {\n" 1988 "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 1989 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 1990 "}"); 1991 verifyFormat("if (a) {\n" 1992 "} else if constexpr (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 1993 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 1994 "}"); 1995 verifyFormat("if (a) {\n" 1996 "} else if CONSTEXPR (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 1997 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 1998 "}"); 1999 verifyFormat("if (a) {\n" 2000 "} else if (\n" 2001 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 2002 "}", 2003 getLLVMStyleWithColumns(62)); 2004 verifyFormat("if (a) {\n" 2005 "} else if constexpr (\n" 2006 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 2007 "}", 2008 getLLVMStyleWithColumns(62)); 2009 verifyFormat("if (a) {\n" 2010 "} else if CONSTEXPR (\n" 2011 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 2012 "}", 2013 getLLVMStyleWithColumns(62)); 2014 } 2015 2016 TEST_F(FormatTest, SeparatePointerReferenceAlignment) { 2017 FormatStyle Style = getLLVMStyle(); 2018 EXPECT_EQ(Style.PointerAlignment, FormatStyle::PAS_Right); 2019 EXPECT_EQ(Style.ReferenceAlignment, FormatStyle::RAS_Pointer); 2020 verifyFormat("int *f1(int *a, int &b, int &&c);", Style); 2021 verifyFormat("int &f2(int &&c, int *a, int &b);", Style); 2022 verifyFormat("int &&f3(int &b, int &&c, int *a);", Style); 2023 verifyFormat("int *f1(int &a) const &;", Style); 2024 verifyFormat("int *f1(int &a) const & = 0;", Style); 2025 verifyFormat("int *a = f1();", Style); 2026 verifyFormat("int &b = f2();", Style); 2027 verifyFormat("int &&c = f3();", Style); 2028 verifyFormat("for (auto a = 0, b = 0; const auto &c : {1, 2, 3})", Style); 2029 verifyFormat("for (auto a = 0, b = 0; const int &c : {1, 2, 3})", Style); 2030 verifyFormat("for (auto a = 0, b = 0; const Foo &c : {1, 2, 3})", Style); 2031 verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style); 2032 verifyFormat("for (int a = 0, b = 0; const auto &c : {1, 2, 3})", Style); 2033 verifyFormat("for (int a = 0, b = 0; const int &c : {1, 2, 3})", Style); 2034 verifyFormat("for (int a = 0, b = 0; const Foo &c : {1, 2, 3})", Style); 2035 verifyFormat("for (int a = 0, b++; const auto &c : {1, 2, 3})", Style); 2036 verifyFormat("for (int a = 0, b++; const int &c : {1, 2, 3})", Style); 2037 verifyFormat("for (int a = 0, b++; const Foo &c : {1, 2, 3})", Style); 2038 verifyFormat("for (auto x = 0; auto &c : {1, 2, 3})", Style); 2039 verifyFormat("for (auto x = 0; int &c : {1, 2, 3})", Style); 2040 verifyFormat("for (int x = 0; auto &c : {1, 2, 3})", Style); 2041 verifyFormat("for (int x = 0; int &c : {1, 2, 3})", Style); 2042 verifyFormat("for (f(); auto &c : {1, 2, 3})", Style); 2043 verifyFormat("for (f(); int &c : {1, 2, 3})", Style); 2044 verifyFormat( 2045 "function<int(int &)> res1 = [](int &a) { return 0000000000000; },\n" 2046 " res2 = [](int &a) { return 0000000000000; };", 2047 Style); 2048 2049 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 2050 verifyFormat("Const unsigned int *c;\n" 2051 "const unsigned int *d;\n" 2052 "Const unsigned int &e;\n" 2053 "const unsigned int &f;\n" 2054 "const unsigned &&g;\n" 2055 "Const unsigned h;", 2056 Style); 2057 2058 Style.PointerAlignment = FormatStyle::PAS_Left; 2059 Style.ReferenceAlignment = FormatStyle::RAS_Pointer; 2060 verifyFormat("int* f1(int* a, int& b, int&& c);", Style); 2061 verifyFormat("int& f2(int&& c, int* a, int& b);", Style); 2062 verifyFormat("int&& f3(int& b, int&& c, int* a);", Style); 2063 verifyFormat("int* f1(int& a) const& = 0;", Style); 2064 verifyFormat("int* a = f1();", Style); 2065 verifyFormat("int& b = f2();", Style); 2066 verifyFormat("int&& c = f3();", Style); 2067 verifyFormat("for (auto a = 0, b = 0; const auto& c : {1, 2, 3})", Style); 2068 verifyFormat("for (auto a = 0, b = 0; const int& c : {1, 2, 3})", Style); 2069 verifyFormat("for (auto a = 0, b = 0; const Foo& c : {1, 2, 3})", Style); 2070 verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style); 2071 verifyFormat("for (int a = 0, b = 0; const auto& c : {1, 2, 3})", Style); 2072 verifyFormat("for (int a = 0, b = 0; const int& c : {1, 2, 3})", Style); 2073 verifyFormat("for (int a = 0, b = 0; const Foo& c : {1, 2, 3})", Style); 2074 verifyFormat("for (int a = 0, b = 0; const Foo* c : {1, 2, 3})", Style); 2075 verifyFormat("for (int a = 0, b++; const auto& c : {1, 2, 3})", Style); 2076 verifyFormat("for (int a = 0, b++; const int& c : {1, 2, 3})", Style); 2077 verifyFormat("for (int a = 0, b++; const Foo& c : {1, 2, 3})", Style); 2078 verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style); 2079 verifyFormat("for (auto x = 0; auto& c : {1, 2, 3})", Style); 2080 verifyFormat("for (auto x = 0; int& c : {1, 2, 3})", Style); 2081 verifyFormat("for (int x = 0; auto& c : {1, 2, 3})", Style); 2082 verifyFormat("for (int x = 0; int& c : {1, 2, 3})", Style); 2083 verifyFormat("for (f(); auto& c : {1, 2, 3})", Style); 2084 verifyFormat("for (f(); int& c : {1, 2, 3})", Style); 2085 verifyFormat( 2086 "function<int(int&)> res1 = [](int& a) { return 0000000000000; },\n" 2087 " res2 = [](int& a) { return 0000000000000; };", 2088 Style); 2089 2090 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 2091 verifyFormat("Const unsigned int* c;\n" 2092 "const unsigned int* d;\n" 2093 "Const unsigned int& e;\n" 2094 "const unsigned int& f;\n" 2095 "const unsigned&& g;\n" 2096 "Const unsigned h;", 2097 Style); 2098 2099 Style.PointerAlignment = FormatStyle::PAS_Right; 2100 Style.ReferenceAlignment = FormatStyle::RAS_Left; 2101 verifyFormat("int *f1(int *a, int& b, int&& c);", Style); 2102 verifyFormat("int& f2(int&& c, int *a, int& b);", Style); 2103 verifyFormat("int&& f3(int& b, int&& c, int *a);", Style); 2104 verifyFormat("int *a = f1();", Style); 2105 verifyFormat("int& b = f2();", Style); 2106 verifyFormat("int&& c = f3();", Style); 2107 verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style); 2108 verifyFormat("for (int a = 0, b = 0; const Foo *c : {1, 2, 3})", Style); 2109 verifyFormat("for (int a = 0, b++; const Foo *c : {1, 2, 3})", Style); 2110 2111 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 2112 verifyFormat("Const unsigned int *c;\n" 2113 "const unsigned int *d;\n" 2114 "Const unsigned int& e;\n" 2115 "const unsigned int& f;\n" 2116 "const unsigned g;\n" 2117 "Const unsigned h;", 2118 Style); 2119 2120 Style.PointerAlignment = FormatStyle::PAS_Left; 2121 Style.ReferenceAlignment = FormatStyle::RAS_Middle; 2122 verifyFormat("int* f1(int* a, int & b, int && c);", Style); 2123 verifyFormat("int & f2(int && c, int* a, int & b);", Style); 2124 verifyFormat("int && f3(int & b, int && c, int* a);", Style); 2125 verifyFormat("int* a = f1();", Style); 2126 verifyFormat("int & b = f2();", Style); 2127 verifyFormat("int && c = f3();", Style); 2128 verifyFormat("for (auto a = 0, b = 0; const auto & c : {1, 2, 3})", Style); 2129 verifyFormat("for (auto a = 0, b = 0; const int & c : {1, 2, 3})", Style); 2130 verifyFormat("for (auto a = 0, b = 0; const Foo & c : {1, 2, 3})", Style); 2131 verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style); 2132 verifyFormat("for (int a = 0, b++; const auto & c : {1, 2, 3})", Style); 2133 verifyFormat("for (int a = 0, b++; const int & c : {1, 2, 3})", Style); 2134 verifyFormat("for (int a = 0, b++; const Foo & c : {1, 2, 3})", Style); 2135 verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style); 2136 verifyFormat("for (auto x = 0; auto & c : {1, 2, 3})", Style); 2137 verifyFormat("for (auto x = 0; int & c : {1, 2, 3})", Style); 2138 verifyFormat("for (int x = 0; auto & c : {1, 2, 3})", Style); 2139 verifyFormat("for (int x = 0; int & c : {1, 2, 3})", Style); 2140 verifyFormat("for (f(); auto & c : {1, 2, 3})", Style); 2141 verifyFormat("for (f(); int & c : {1, 2, 3})", Style); 2142 verifyFormat( 2143 "function<int(int &)> res1 = [](int & a) { return 0000000000000; },\n" 2144 " res2 = [](int & a) { return 0000000000000; };", 2145 Style); 2146 2147 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 2148 verifyFormat("Const unsigned int* c;\n" 2149 "const unsigned int* d;\n" 2150 "Const unsigned int & e;\n" 2151 "const unsigned int & f;\n" 2152 "const unsigned && g;\n" 2153 "Const unsigned h;", 2154 Style); 2155 2156 Style.PointerAlignment = FormatStyle::PAS_Middle; 2157 Style.ReferenceAlignment = FormatStyle::RAS_Right; 2158 verifyFormat("int * f1(int * a, int &b, int &&c);", Style); 2159 verifyFormat("int &f2(int &&c, int * a, int &b);", Style); 2160 verifyFormat("int &&f3(int &b, int &&c, int * a);", Style); 2161 verifyFormat("int * a = f1();", Style); 2162 verifyFormat("int &b = f2();", Style); 2163 verifyFormat("int &&c = f3();", Style); 2164 verifyFormat("for (auto a = 0, b = 0; const Foo * c : {1, 2, 3})", Style); 2165 verifyFormat("for (int a = 0, b = 0; const Foo * c : {1, 2, 3})", Style); 2166 verifyFormat("for (int a = 0, b++; const Foo * c : {1, 2, 3})", Style); 2167 2168 // FIXME: we don't handle this yet, so output may be arbitrary until it's 2169 // specifically handled 2170 // verifyFormat("int Add2(BTree * &Root, char * szToAdd)", Style); 2171 } 2172 2173 TEST_F(FormatTest, FormatsForLoop) { 2174 verifyFormat( 2175 "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n" 2176 " ++VeryVeryLongLoopVariable)\n" 2177 " ;"); 2178 verifyFormat("for (;;)\n" 2179 " f();"); 2180 verifyFormat("for (;;) {\n}"); 2181 verifyFormat("for (;;) {\n" 2182 " f();\n" 2183 "}"); 2184 verifyFormat("for (int i = 0; (i < 10); ++i) {\n}"); 2185 2186 verifyFormat( 2187 "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n" 2188 " E = UnwrappedLines.end();\n" 2189 " I != E; ++I) {\n}"); 2190 2191 verifyFormat( 2192 "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n" 2193 " ++IIIII) {\n}"); 2194 verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n" 2195 " aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n" 2196 " aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}"); 2197 verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n" 2198 " I = FD->getDeclsInPrototypeScope().begin(),\n" 2199 " E = FD->getDeclsInPrototypeScope().end();\n" 2200 " I != E; ++I) {\n}"); 2201 verifyFormat("for (SmallVectorImpl<TemplateIdAnnotationn *>::iterator\n" 2202 " I = Container.begin(),\n" 2203 " E = Container.end();\n" 2204 " I != E; ++I) {\n}", 2205 getLLVMStyleWithColumns(76)); 2206 2207 verifyFormat( 2208 "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n" 2209 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n" 2210 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2211 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 2212 " ++aaaaaaaaaaa) {\n}"); 2213 verifyFormat("for (int i = 0; i < aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 2214 " bbbbbbbbbbbbbbbbbbbb < ccccccccccccccc;\n" 2215 " ++i) {\n}"); 2216 verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n" 2217 " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n" 2218 "}"); 2219 verifyFormat("for (some_namespace::SomeIterator iter( // force break\n" 2220 " aaaaaaaaaa);\n" 2221 " iter; ++iter) {\n" 2222 "}"); 2223 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2224 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 2225 " aaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbbbbbbb;\n" 2226 " ++aaaaaaaaaaaaaaaaaaaaaaaaaaa) {"); 2227 2228 // These should not be formatted as Objective-C for-in loops. 2229 verifyFormat("for (Foo *x = 0; x != in; x++) {\n}"); 2230 verifyFormat("Foo *x;\nfor (x = 0; x != in; x++) {\n}"); 2231 verifyFormat("Foo *x;\nfor (x in y) {\n}"); 2232 verifyFormat( 2233 "for (const Foo<Bar> &baz = in.value(); !baz.at_end(); ++baz) {\n}"); 2234 2235 FormatStyle NoBinPacking = getLLVMStyle(); 2236 NoBinPacking.BinPackParameters = false; 2237 verifyFormat("for (int aaaaaaaaaaa = 1;\n" 2238 " aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n" 2239 " aaaaaaaaaaaaaaaa,\n" 2240 " aaaaaaaaaaaaaaaa,\n" 2241 " aaaaaaaaaaaaaaaa);\n" 2242 " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n" 2243 "}", 2244 NoBinPacking); 2245 verifyFormat( 2246 "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n" 2247 " E = UnwrappedLines.end();\n" 2248 " I != E;\n" 2249 " ++I) {\n}", 2250 NoBinPacking); 2251 2252 FormatStyle AlignLeft = getLLVMStyle(); 2253 AlignLeft.PointerAlignment = FormatStyle::PAS_Left; 2254 verifyFormat("for (A* a = start; a < end; ++a, ++value) {\n}", AlignLeft); 2255 } 2256 2257 TEST_F(FormatTest, RangeBasedForLoops) { 2258 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 2259 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 2260 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n" 2261 " aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}"); 2262 verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n" 2263 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 2264 verifyFormat("for (aaaaaaaaa aaaaaaaaaaaaaaaaaaaaa :\n" 2265 " aaaaaaaaaaaa.aaaaaaaaaaaa().aaaaaaaaa().a()) {\n}"); 2266 } 2267 2268 TEST_F(FormatTest, ForEachLoops) { 2269 FormatStyle Style = getLLVMStyle(); 2270 EXPECT_EQ(Style.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 2271 EXPECT_EQ(Style.AllowShortLoopsOnASingleLine, false); 2272 verifyFormat("void f() {\n" 2273 " for (;;) {\n" 2274 " }\n" 2275 " foreach (Item *item, itemlist) {\n" 2276 " }\n" 2277 " Q_FOREACH (Item *item, itemlist) {\n" 2278 " }\n" 2279 " BOOST_FOREACH (Item *item, itemlist) {\n" 2280 " }\n" 2281 " UNKNOWN_FOREACH(Item * item, itemlist) {}\n" 2282 "}", 2283 Style); 2284 verifyFormat("void f() {\n" 2285 " for (;;)\n" 2286 " int j = 1;\n" 2287 " Q_FOREACH (int v, vec)\n" 2288 " v *= 2;\n" 2289 " for (;;) {\n" 2290 " int j = 1;\n" 2291 " }\n" 2292 " Q_FOREACH (int v, vec) {\n" 2293 " v *= 2;\n" 2294 " }\n" 2295 "}", 2296 Style); 2297 2298 FormatStyle ShortBlocks = getLLVMStyle(); 2299 ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 2300 EXPECT_EQ(ShortBlocks.AllowShortLoopsOnASingleLine, false); 2301 verifyFormat("void f() {\n" 2302 " for (;;)\n" 2303 " int j = 1;\n" 2304 " Q_FOREACH (int &v, vec)\n" 2305 " v *= 2;\n" 2306 " for (;;) {\n" 2307 " int j = 1;\n" 2308 " }\n" 2309 " Q_FOREACH (int &v, vec) {\n" 2310 " int j = 1;\n" 2311 " }\n" 2312 "}", 2313 ShortBlocks); 2314 2315 FormatStyle ShortLoops = getLLVMStyle(); 2316 ShortLoops.AllowShortLoopsOnASingleLine = true; 2317 EXPECT_EQ(ShortLoops.AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 2318 verifyFormat("void f() {\n" 2319 " for (;;) int j = 1;\n" 2320 " Q_FOREACH (int &v, vec) int j = 1;\n" 2321 " for (;;) {\n" 2322 " int j = 1;\n" 2323 " }\n" 2324 " Q_FOREACH (int &v, vec) {\n" 2325 " int j = 1;\n" 2326 " }\n" 2327 "}", 2328 ShortLoops); 2329 2330 FormatStyle ShortBlocksAndLoops = getLLVMStyle(); 2331 ShortBlocksAndLoops.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 2332 ShortBlocksAndLoops.AllowShortLoopsOnASingleLine = true; 2333 verifyFormat("void f() {\n" 2334 " for (;;) int j = 1;\n" 2335 " Q_FOREACH (int &v, vec) int j = 1;\n" 2336 " for (;;) { int j = 1; }\n" 2337 " Q_FOREACH (int &v, vec) { int j = 1; }\n" 2338 "}", 2339 ShortBlocksAndLoops); 2340 2341 Style.SpaceBeforeParens = 2342 FormatStyle::SBPO_ControlStatementsExceptControlMacros; 2343 verifyFormat("void f() {\n" 2344 " for (;;) {\n" 2345 " }\n" 2346 " foreach(Item *item, itemlist) {\n" 2347 " }\n" 2348 " Q_FOREACH(Item *item, itemlist) {\n" 2349 " }\n" 2350 " BOOST_FOREACH(Item *item, itemlist) {\n" 2351 " }\n" 2352 " UNKNOWN_FOREACH(Item * item, itemlist) {}\n" 2353 "}", 2354 Style); 2355 2356 // As function-like macros. 2357 verifyFormat("#define foreach(x, y)\n" 2358 "#define Q_FOREACH(x, y)\n" 2359 "#define BOOST_FOREACH(x, y)\n" 2360 "#define UNKNOWN_FOREACH(x, y)\n"); 2361 2362 // Not as function-like macros. 2363 verifyFormat("#define foreach (x, y)\n" 2364 "#define Q_FOREACH (x, y)\n" 2365 "#define BOOST_FOREACH (x, y)\n" 2366 "#define UNKNOWN_FOREACH (x, y)\n"); 2367 2368 // handle microsoft non standard extension 2369 verifyFormat("for each (char c in x->MyStringProperty)"); 2370 } 2371 2372 TEST_F(FormatTest, FormatsWhileLoop) { 2373 verifyFormat("while (true) {\n}"); 2374 verifyFormat("while (true)\n" 2375 " f();"); 2376 verifyFormat("while () {\n}"); 2377 verifyFormat("while () {\n" 2378 " f();\n" 2379 "}"); 2380 } 2381 2382 TEST_F(FormatTest, FormatsDoWhile) { 2383 verifyFormat("do {\n" 2384 " do_something();\n" 2385 "} while (something());"); 2386 verifyFormat("do\n" 2387 " do_something();\n" 2388 "while (something());"); 2389 } 2390 2391 TEST_F(FormatTest, FormatsSwitchStatement) { 2392 verifyFormat("switch (x) {\n" 2393 "case 1:\n" 2394 " f();\n" 2395 " break;\n" 2396 "case kFoo:\n" 2397 "case ns::kBar:\n" 2398 "case kBaz:\n" 2399 " break;\n" 2400 "default:\n" 2401 " g();\n" 2402 " break;\n" 2403 "}"); 2404 verifyFormat("switch (x) {\n" 2405 "case 1: {\n" 2406 " f();\n" 2407 " break;\n" 2408 "}\n" 2409 "case 2: {\n" 2410 " break;\n" 2411 "}\n" 2412 "}"); 2413 verifyFormat("switch (x) {\n" 2414 "case 1: {\n" 2415 " f();\n" 2416 " {\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 " if (foo) {\n" 2427 " g();\n" 2428 " h();\n" 2429 " }\n" 2430 " break;\n" 2431 "}\n" 2432 "}"); 2433 verifyFormat("switch (x) {\n" 2434 "case 1: {\n" 2435 " f();\n" 2436 " g();\n" 2437 "} break;\n" 2438 "}"); 2439 verifyFormat("switch (test)\n" 2440 " ;"); 2441 verifyFormat("switch (x) {\n" 2442 "default: {\n" 2443 " // Do nothing.\n" 2444 "}\n" 2445 "}"); 2446 verifyFormat("switch (x) {\n" 2447 "// comment\n" 2448 "// if 1, do f()\n" 2449 "case 1:\n" 2450 " f();\n" 2451 "}"); 2452 verifyFormat("switch (x) {\n" 2453 "case 1:\n" 2454 " // Do amazing stuff\n" 2455 " {\n" 2456 " f();\n" 2457 " g();\n" 2458 " }\n" 2459 " break;\n" 2460 "}"); 2461 verifyFormat("#define A \\\n" 2462 " switch (x) { \\\n" 2463 " case a: \\\n" 2464 " foo = b; \\\n" 2465 " }", 2466 getLLVMStyleWithColumns(20)); 2467 verifyFormat("#define OPERATION_CASE(name) \\\n" 2468 " case OP_name: \\\n" 2469 " return operations::Operation##name\n", 2470 getLLVMStyleWithColumns(40)); 2471 verifyFormat("switch (x) {\n" 2472 "case 1:;\n" 2473 "default:;\n" 2474 " int i;\n" 2475 "}"); 2476 2477 verifyGoogleFormat("switch (x) {\n" 2478 " case 1:\n" 2479 " f();\n" 2480 " break;\n" 2481 " case kFoo:\n" 2482 " case ns::kBar:\n" 2483 " case kBaz:\n" 2484 " break;\n" 2485 " default:\n" 2486 " g();\n" 2487 " break;\n" 2488 "}"); 2489 verifyGoogleFormat("switch (x) {\n" 2490 " case 1: {\n" 2491 " f();\n" 2492 " break;\n" 2493 " }\n" 2494 "}"); 2495 verifyGoogleFormat("switch (test)\n" 2496 " ;"); 2497 2498 verifyGoogleFormat("#define OPERATION_CASE(name) \\\n" 2499 " case OP_name: \\\n" 2500 " return operations::Operation##name\n"); 2501 verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n" 2502 " // Get the correction operation class.\n" 2503 " switch (OpCode) {\n" 2504 " CASE(Add);\n" 2505 " CASE(Subtract);\n" 2506 " default:\n" 2507 " return operations::Unknown;\n" 2508 " }\n" 2509 "#undef OPERATION_CASE\n" 2510 "}"); 2511 verifyFormat("DEBUG({\n" 2512 " switch (x) {\n" 2513 " case A:\n" 2514 " f();\n" 2515 " break;\n" 2516 " // fallthrough\n" 2517 " case B:\n" 2518 " g();\n" 2519 " break;\n" 2520 " }\n" 2521 "});"); 2522 EXPECT_EQ("DEBUG({\n" 2523 " switch (x) {\n" 2524 " case A:\n" 2525 " f();\n" 2526 " break;\n" 2527 " // On B:\n" 2528 " case B:\n" 2529 " g();\n" 2530 " break;\n" 2531 " }\n" 2532 "});", 2533 format("DEBUG({\n" 2534 " switch (x) {\n" 2535 " case A:\n" 2536 " f();\n" 2537 " break;\n" 2538 " // On B:\n" 2539 " case B:\n" 2540 " g();\n" 2541 " break;\n" 2542 " }\n" 2543 "});", 2544 getLLVMStyle())); 2545 EXPECT_EQ("switch (n) {\n" 2546 "case 0: {\n" 2547 " return false;\n" 2548 "}\n" 2549 "default: {\n" 2550 " return true;\n" 2551 "}\n" 2552 "}", 2553 format("switch (n)\n" 2554 "{\n" 2555 "case 0: {\n" 2556 " return false;\n" 2557 "}\n" 2558 "default: {\n" 2559 " return true;\n" 2560 "}\n" 2561 "}", 2562 getLLVMStyle())); 2563 verifyFormat("switch (a) {\n" 2564 "case (b):\n" 2565 " return;\n" 2566 "}"); 2567 2568 verifyFormat("switch (a) {\n" 2569 "case some_namespace::\n" 2570 " some_constant:\n" 2571 " return;\n" 2572 "}", 2573 getLLVMStyleWithColumns(34)); 2574 2575 FormatStyle Style = getLLVMStyle(); 2576 Style.IndentCaseLabels = true; 2577 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 2578 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2579 Style.BraceWrapping.AfterCaseLabel = true; 2580 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 2581 EXPECT_EQ("switch (n)\n" 2582 "{\n" 2583 " case 0:\n" 2584 " {\n" 2585 " return false;\n" 2586 " }\n" 2587 " default:\n" 2588 " {\n" 2589 " return true;\n" 2590 " }\n" 2591 "}", 2592 format("switch (n) {\n" 2593 " case 0: {\n" 2594 " return false;\n" 2595 " }\n" 2596 " default: {\n" 2597 " return true;\n" 2598 " }\n" 2599 "}", 2600 Style)); 2601 Style.BraceWrapping.AfterCaseLabel = false; 2602 EXPECT_EQ("switch (n)\n" 2603 "{\n" 2604 " case 0: {\n" 2605 " return false;\n" 2606 " }\n" 2607 " default: {\n" 2608 " return true;\n" 2609 " }\n" 2610 "}", 2611 format("switch (n) {\n" 2612 " case 0:\n" 2613 " {\n" 2614 " return false;\n" 2615 " }\n" 2616 " default:\n" 2617 " {\n" 2618 " return true;\n" 2619 " }\n" 2620 "}", 2621 Style)); 2622 Style.IndentCaseLabels = false; 2623 Style.IndentCaseBlocks = true; 2624 EXPECT_EQ("switch (n)\n" 2625 "{\n" 2626 "case 0:\n" 2627 " {\n" 2628 " return false;\n" 2629 " }\n" 2630 "case 1:\n" 2631 " break;\n" 2632 "default:\n" 2633 " {\n" 2634 " return true;\n" 2635 " }\n" 2636 "}", 2637 format("switch (n) {\n" 2638 "case 0: {\n" 2639 " return false;\n" 2640 "}\n" 2641 "case 1:\n" 2642 " break;\n" 2643 "default: {\n" 2644 " return true;\n" 2645 "}\n" 2646 "}", 2647 Style)); 2648 Style.IndentCaseLabels = true; 2649 Style.IndentCaseBlocks = true; 2650 EXPECT_EQ("switch (n)\n" 2651 "{\n" 2652 " case 0:\n" 2653 " {\n" 2654 " return false;\n" 2655 " }\n" 2656 " case 1:\n" 2657 " break;\n" 2658 " default:\n" 2659 " {\n" 2660 " return true;\n" 2661 " }\n" 2662 "}", 2663 format("switch (n) {\n" 2664 "case 0: {\n" 2665 " return false;\n" 2666 "}\n" 2667 "case 1:\n" 2668 " break;\n" 2669 "default: {\n" 2670 " return true;\n" 2671 "}\n" 2672 "}", 2673 Style)); 2674 } 2675 2676 TEST_F(FormatTest, CaseRanges) { 2677 verifyFormat("switch (x) {\n" 2678 "case 'A' ... 'Z':\n" 2679 "case 1 ... 5:\n" 2680 "case a ... b:\n" 2681 " break;\n" 2682 "}"); 2683 } 2684 2685 TEST_F(FormatTest, ShortEnums) { 2686 FormatStyle Style = getLLVMStyle(); 2687 Style.AllowShortEnumsOnASingleLine = true; 2688 verifyFormat("enum { A, B, C } ShortEnum1, ShortEnum2;", Style); 2689 verifyFormat("typedef enum { A, B, C } ShortEnum1, ShortEnum2;", Style); 2690 Style.AllowShortEnumsOnASingleLine = false; 2691 verifyFormat("enum {\n" 2692 " A,\n" 2693 " B,\n" 2694 " C\n" 2695 "} ShortEnum1, ShortEnum2;", 2696 Style); 2697 verifyFormat("typedef enum {\n" 2698 " A,\n" 2699 " B,\n" 2700 " C\n" 2701 "} ShortEnum1, ShortEnum2;", 2702 Style); 2703 verifyFormat("enum {\n" 2704 " A,\n" 2705 "} ShortEnum1, ShortEnum2;", 2706 Style); 2707 verifyFormat("typedef enum {\n" 2708 " A,\n" 2709 "} ShortEnum1, ShortEnum2;", 2710 Style); 2711 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2712 Style.BraceWrapping.AfterEnum = true; 2713 verifyFormat("enum\n" 2714 "{\n" 2715 " A,\n" 2716 " B,\n" 2717 " C\n" 2718 "} ShortEnum1, ShortEnum2;", 2719 Style); 2720 verifyFormat("typedef enum\n" 2721 "{\n" 2722 " A,\n" 2723 " B,\n" 2724 " C\n" 2725 "} ShortEnum1, ShortEnum2;", 2726 Style); 2727 } 2728 2729 TEST_F(FormatTest, ShortCaseLabels) { 2730 FormatStyle Style = getLLVMStyle(); 2731 Style.AllowShortCaseLabelsOnASingleLine = true; 2732 verifyFormat("switch (a) {\n" 2733 "case 1: x = 1; break;\n" 2734 "case 2: return;\n" 2735 "case 3:\n" 2736 "case 4:\n" 2737 "case 5: return;\n" 2738 "case 6: // comment\n" 2739 " return;\n" 2740 "case 7:\n" 2741 " // comment\n" 2742 " return;\n" 2743 "case 8:\n" 2744 " x = 8; // comment\n" 2745 " break;\n" 2746 "default: y = 1; break;\n" 2747 "}", 2748 Style); 2749 verifyFormat("switch (a) {\n" 2750 "case 0: return; // comment\n" 2751 "case 1: break; // comment\n" 2752 "case 2: return;\n" 2753 "// comment\n" 2754 "case 3: return;\n" 2755 "// comment 1\n" 2756 "// comment 2\n" 2757 "// comment 3\n" 2758 "case 4: break; /* comment */\n" 2759 "case 5:\n" 2760 " // comment\n" 2761 " break;\n" 2762 "case 6: /* comment */ x = 1; break;\n" 2763 "case 7: x = /* comment */ 1; break;\n" 2764 "case 8:\n" 2765 " x = 1; /* comment */\n" 2766 " break;\n" 2767 "case 9:\n" 2768 " break; // comment line 1\n" 2769 " // comment line 2\n" 2770 "}", 2771 Style); 2772 EXPECT_EQ("switch (a) {\n" 2773 "case 1:\n" 2774 " x = 8;\n" 2775 " // fall through\n" 2776 "case 2: x = 8;\n" 2777 "// comment\n" 2778 "case 3:\n" 2779 " return; /* comment line 1\n" 2780 " * comment line 2 */\n" 2781 "case 4: i = 8;\n" 2782 "// something else\n" 2783 "#if FOO\n" 2784 "case 5: break;\n" 2785 "#endif\n" 2786 "}", 2787 format("switch (a) {\n" 2788 "case 1: x = 8;\n" 2789 " // fall through\n" 2790 "case 2:\n" 2791 " x = 8;\n" 2792 "// comment\n" 2793 "case 3:\n" 2794 " return; /* comment line 1\n" 2795 " * comment line 2 */\n" 2796 "case 4:\n" 2797 " i = 8;\n" 2798 "// something else\n" 2799 "#if FOO\n" 2800 "case 5: break;\n" 2801 "#endif\n" 2802 "}", 2803 Style)); 2804 EXPECT_EQ("switch (a) {\n" 2805 "case 0:\n" 2806 " return; // long long long long long long long long long long " 2807 "long long comment\n" 2808 " // line\n" 2809 "}", 2810 format("switch (a) {\n" 2811 "case 0: return; // long long long long long long long long " 2812 "long long long long comment line\n" 2813 "}", 2814 Style)); 2815 EXPECT_EQ("switch (a) {\n" 2816 "case 0:\n" 2817 " return; /* long long long long long long long long long long " 2818 "long long comment\n" 2819 " line */\n" 2820 "}", 2821 format("switch (a) {\n" 2822 "case 0: return; /* long long long long long long long long " 2823 "long long long long comment line */\n" 2824 "}", 2825 Style)); 2826 verifyFormat("switch (a) {\n" 2827 "#if FOO\n" 2828 "case 0: return 0;\n" 2829 "#endif\n" 2830 "}", 2831 Style); 2832 verifyFormat("switch (a) {\n" 2833 "case 1: {\n" 2834 "}\n" 2835 "case 2: {\n" 2836 " return;\n" 2837 "}\n" 2838 "case 3: {\n" 2839 " x = 1;\n" 2840 " return;\n" 2841 "}\n" 2842 "case 4:\n" 2843 " if (x)\n" 2844 " return;\n" 2845 "}", 2846 Style); 2847 Style.ColumnLimit = 21; 2848 verifyFormat("switch (a) {\n" 2849 "case 1: x = 1; break;\n" 2850 "case 2: return;\n" 2851 "case 3:\n" 2852 "case 4:\n" 2853 "case 5: return;\n" 2854 "default:\n" 2855 " y = 1;\n" 2856 " break;\n" 2857 "}", 2858 Style); 2859 Style.ColumnLimit = 80; 2860 Style.AllowShortCaseLabelsOnASingleLine = false; 2861 Style.IndentCaseLabels = true; 2862 EXPECT_EQ("switch (n) {\n" 2863 " default /*comments*/:\n" 2864 " return true;\n" 2865 " case 0:\n" 2866 " return false;\n" 2867 "}", 2868 format("switch (n) {\n" 2869 "default/*comments*/:\n" 2870 " return true;\n" 2871 "case 0:\n" 2872 " return false;\n" 2873 "}", 2874 Style)); 2875 Style.AllowShortCaseLabelsOnASingleLine = true; 2876 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2877 Style.BraceWrapping.AfterCaseLabel = true; 2878 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 2879 EXPECT_EQ("switch (n)\n" 2880 "{\n" 2881 " case 0:\n" 2882 " {\n" 2883 " return false;\n" 2884 " }\n" 2885 " default:\n" 2886 " {\n" 2887 " return true;\n" 2888 " }\n" 2889 "}", 2890 format("switch (n) {\n" 2891 " case 0: {\n" 2892 " return false;\n" 2893 " }\n" 2894 " default:\n" 2895 " {\n" 2896 " return true;\n" 2897 " }\n" 2898 "}", 2899 Style)); 2900 } 2901 2902 TEST_F(FormatTest, FormatsLabels) { 2903 verifyFormat("void f() {\n" 2904 " some_code();\n" 2905 "test_label:\n" 2906 " some_other_code();\n" 2907 " {\n" 2908 " some_more_code();\n" 2909 " another_label:\n" 2910 " some_more_code();\n" 2911 " }\n" 2912 "}"); 2913 verifyFormat("{\n" 2914 " some_code();\n" 2915 "test_label:\n" 2916 " some_other_code();\n" 2917 "}"); 2918 verifyFormat("{\n" 2919 " some_code();\n" 2920 "test_label:;\n" 2921 " int i = 0;\n" 2922 "}"); 2923 FormatStyle Style = getLLVMStyle(); 2924 Style.IndentGotoLabels = false; 2925 verifyFormat("void f() {\n" 2926 " some_code();\n" 2927 "test_label:\n" 2928 " some_other_code();\n" 2929 " {\n" 2930 " some_more_code();\n" 2931 "another_label:\n" 2932 " some_more_code();\n" 2933 " }\n" 2934 "}", 2935 Style); 2936 verifyFormat("{\n" 2937 " some_code();\n" 2938 "test_label:\n" 2939 " some_other_code();\n" 2940 "}", 2941 Style); 2942 verifyFormat("{\n" 2943 " some_code();\n" 2944 "test_label:;\n" 2945 " int i = 0;\n" 2946 "}"); 2947 } 2948 2949 TEST_F(FormatTest, MultiLineControlStatements) { 2950 FormatStyle Style = getLLVMStyleWithColumns(20); 2951 Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom; 2952 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine; 2953 // Short lines should keep opening brace on same line. 2954 EXPECT_EQ("if (foo) {\n" 2955 " bar();\n" 2956 "}", 2957 format("if(foo){bar();}", Style)); 2958 EXPECT_EQ("if (foo) {\n" 2959 " bar();\n" 2960 "} else {\n" 2961 " baz();\n" 2962 "}", 2963 format("if(foo){bar();}else{baz();}", Style)); 2964 EXPECT_EQ("if (foo && bar) {\n" 2965 " baz();\n" 2966 "}", 2967 format("if(foo&&bar){baz();}", Style)); 2968 EXPECT_EQ("if (foo) {\n" 2969 " bar();\n" 2970 "} else if (baz) {\n" 2971 " quux();\n" 2972 "}", 2973 format("if(foo){bar();}else if(baz){quux();}", Style)); 2974 EXPECT_EQ( 2975 "if (foo) {\n" 2976 " bar();\n" 2977 "} else if (baz) {\n" 2978 " quux();\n" 2979 "} else {\n" 2980 " foobar();\n" 2981 "}", 2982 format("if(foo){bar();}else if(baz){quux();}else{foobar();}", Style)); 2983 EXPECT_EQ("for (;;) {\n" 2984 " foo();\n" 2985 "}", 2986 format("for(;;){foo();}")); 2987 EXPECT_EQ("while (1) {\n" 2988 " foo();\n" 2989 "}", 2990 format("while(1){foo();}", Style)); 2991 EXPECT_EQ("switch (foo) {\n" 2992 "case bar:\n" 2993 " return;\n" 2994 "}", 2995 format("switch(foo){case bar:return;}", Style)); 2996 EXPECT_EQ("try {\n" 2997 " foo();\n" 2998 "} catch (...) {\n" 2999 " bar();\n" 3000 "}", 3001 format("try{foo();}catch(...){bar();}", Style)); 3002 EXPECT_EQ("do {\n" 3003 " foo();\n" 3004 "} while (bar &&\n" 3005 " baz);", 3006 format("do{foo();}while(bar&&baz);", Style)); 3007 // Long lines should put opening brace on new line. 3008 EXPECT_EQ("if (foo && bar &&\n" 3009 " baz)\n" 3010 "{\n" 3011 " quux();\n" 3012 "}", 3013 format("if(foo&&bar&&baz){quux();}", Style)); 3014 EXPECT_EQ("if (foo && bar &&\n" 3015 " baz)\n" 3016 "{\n" 3017 " quux();\n" 3018 "}", 3019 format("if (foo && bar &&\n" 3020 " baz) {\n" 3021 " quux();\n" 3022 "}", 3023 Style)); 3024 EXPECT_EQ("if (foo) {\n" 3025 " bar();\n" 3026 "} else if (baz ||\n" 3027 " quux)\n" 3028 "{\n" 3029 " foobar();\n" 3030 "}", 3031 format("if(foo){bar();}else if(baz||quux){foobar();}", Style)); 3032 EXPECT_EQ( 3033 "if (foo) {\n" 3034 " bar();\n" 3035 "} else if (baz ||\n" 3036 " quux)\n" 3037 "{\n" 3038 " foobar();\n" 3039 "} else {\n" 3040 " barbaz();\n" 3041 "}", 3042 format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}", 3043 Style)); 3044 EXPECT_EQ("for (int i = 0;\n" 3045 " i < 10; ++i)\n" 3046 "{\n" 3047 " foo();\n" 3048 "}", 3049 format("for(int i=0;i<10;++i){foo();}", Style)); 3050 EXPECT_EQ("foreach (int i,\n" 3051 " list)\n" 3052 "{\n" 3053 " foo();\n" 3054 "}", 3055 format("foreach(int i, list){foo();}", Style)); 3056 Style.ColumnLimit = 3057 40; // to concentrate at brace wrapping, not line wrap due to column limit 3058 EXPECT_EQ("foreach (int i, list) {\n" 3059 " foo();\n" 3060 "}", 3061 format("foreach(int i, list){foo();}", Style)); 3062 Style.ColumnLimit = 3063 20; // to concentrate at brace wrapping, not line wrap due to column limit 3064 EXPECT_EQ("while (foo || bar ||\n" 3065 " baz)\n" 3066 "{\n" 3067 " quux();\n" 3068 "}", 3069 format("while(foo||bar||baz){quux();}", Style)); 3070 EXPECT_EQ("switch (\n" 3071 " foo = barbaz)\n" 3072 "{\n" 3073 "case quux:\n" 3074 " return;\n" 3075 "}", 3076 format("switch(foo=barbaz){case quux:return;}", Style)); 3077 EXPECT_EQ("try {\n" 3078 " foo();\n" 3079 "} catch (\n" 3080 " Exception &bar)\n" 3081 "{\n" 3082 " baz();\n" 3083 "}", 3084 format("try{foo();}catch(Exception&bar){baz();}", Style)); 3085 Style.ColumnLimit = 3086 40; // to concentrate at brace wrapping, not line wrap due to column limit 3087 EXPECT_EQ("try {\n" 3088 " foo();\n" 3089 "} catch (Exception &bar) {\n" 3090 " baz();\n" 3091 "}", 3092 format("try{foo();}catch(Exception&bar){baz();}", Style)); 3093 Style.ColumnLimit = 3094 20; // to concentrate at brace wrapping, not line wrap due to column limit 3095 3096 Style.BraceWrapping.BeforeElse = true; 3097 EXPECT_EQ( 3098 "if (foo) {\n" 3099 " bar();\n" 3100 "}\n" 3101 "else if (baz ||\n" 3102 " quux)\n" 3103 "{\n" 3104 " foobar();\n" 3105 "}\n" 3106 "else {\n" 3107 " barbaz();\n" 3108 "}", 3109 format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}", 3110 Style)); 3111 3112 Style.BraceWrapping.BeforeCatch = true; 3113 EXPECT_EQ("try {\n" 3114 " foo();\n" 3115 "}\n" 3116 "catch (...) {\n" 3117 " baz();\n" 3118 "}", 3119 format("try{foo();}catch(...){baz();}", Style)); 3120 3121 Style.BraceWrapping.AfterFunction = true; 3122 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine; 3123 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 3124 Style.ColumnLimit = 80; 3125 verifyFormat("void shortfunction() { bar(); }", Style); 3126 3127 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 3128 verifyFormat("void shortfunction()\n" 3129 "{\n" 3130 " bar();\n" 3131 "}", 3132 Style); 3133 } 3134 3135 TEST_F(FormatTest, BeforeWhile) { 3136 FormatStyle Style = getLLVMStyle(); 3137 Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom; 3138 3139 verifyFormat("do {\n" 3140 " foo();\n" 3141 "} while (1);", 3142 Style); 3143 Style.BraceWrapping.BeforeWhile = true; 3144 verifyFormat("do {\n" 3145 " foo();\n" 3146 "}\n" 3147 "while (1);", 3148 Style); 3149 } 3150 3151 //===----------------------------------------------------------------------===// 3152 // Tests for classes, namespaces, etc. 3153 //===----------------------------------------------------------------------===// 3154 3155 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) { 3156 verifyFormat("class A {};"); 3157 } 3158 3159 TEST_F(FormatTest, UnderstandsAccessSpecifiers) { 3160 verifyFormat("class A {\n" 3161 "public:\n" 3162 "public: // comment\n" 3163 "protected:\n" 3164 "private:\n" 3165 " void f() {}\n" 3166 "};"); 3167 verifyFormat("export class A {\n" 3168 "public:\n" 3169 "public: // comment\n" 3170 "protected:\n" 3171 "private:\n" 3172 " void f() {}\n" 3173 "};"); 3174 verifyGoogleFormat("class A {\n" 3175 " public:\n" 3176 " protected:\n" 3177 " private:\n" 3178 " void f() {}\n" 3179 "};"); 3180 verifyGoogleFormat("export class A {\n" 3181 " public:\n" 3182 " protected:\n" 3183 " private:\n" 3184 " void f() {}\n" 3185 "};"); 3186 verifyFormat("class A {\n" 3187 "public slots:\n" 3188 " void f1() {}\n" 3189 "public Q_SLOTS:\n" 3190 " void f2() {}\n" 3191 "protected slots:\n" 3192 " void f3() {}\n" 3193 "protected Q_SLOTS:\n" 3194 " void f4() {}\n" 3195 "private slots:\n" 3196 " void f5() {}\n" 3197 "private Q_SLOTS:\n" 3198 " void f6() {}\n" 3199 "signals:\n" 3200 " void g1();\n" 3201 "Q_SIGNALS:\n" 3202 " void g2();\n" 3203 "};"); 3204 3205 // Don't interpret 'signals' the wrong way. 3206 verifyFormat("signals.set();"); 3207 verifyFormat("for (Signals signals : f()) {\n}"); 3208 verifyFormat("{\n" 3209 " signals.set(); // This needs indentation.\n" 3210 "}"); 3211 verifyFormat("void f() {\n" 3212 "label:\n" 3213 " signals.baz();\n" 3214 "}"); 3215 verifyFormat("private[1];"); 3216 verifyFormat("testArray[public] = 1;"); 3217 verifyFormat("public();"); 3218 verifyFormat("myFunc(public);"); 3219 verifyFormat("std::vector<int> testVec = {private};"); 3220 verifyFormat("private.p = 1;"); 3221 verifyFormat("void function(private...){};"); 3222 verifyFormat("if (private && public)\n"); 3223 verifyFormat("private &= true;"); 3224 verifyFormat("int x = private * public;"); 3225 verifyFormat("public *= private;"); 3226 verifyFormat("int x = public + private;"); 3227 verifyFormat("private++;"); 3228 verifyFormat("++private;"); 3229 verifyFormat("public += private;"); 3230 verifyFormat("public = public - private;"); 3231 verifyFormat("public->foo();"); 3232 verifyFormat("private--;"); 3233 verifyFormat("--private;"); 3234 verifyFormat("public -= 1;"); 3235 verifyFormat("if (!private && !public)\n"); 3236 verifyFormat("public != private;"); 3237 verifyFormat("int x = public / private;"); 3238 verifyFormat("public /= 2;"); 3239 verifyFormat("public = public % 2;"); 3240 verifyFormat("public %= 2;"); 3241 verifyFormat("if (public < private)\n"); 3242 verifyFormat("public << private;"); 3243 verifyFormat("public <<= private;"); 3244 verifyFormat("if (public > private)\n"); 3245 verifyFormat("public >> private;"); 3246 verifyFormat("public >>= private;"); 3247 verifyFormat("public ^ private;"); 3248 verifyFormat("public ^= private;"); 3249 verifyFormat("public | private;"); 3250 verifyFormat("public |= private;"); 3251 verifyFormat("auto x = private ? 1 : 2;"); 3252 verifyFormat("if (public == private)\n"); 3253 verifyFormat("void foo(public, private)"); 3254 verifyFormat("public::foo();"); 3255 } 3256 3257 TEST_F(FormatTest, SeparatesLogicalBlocks) { 3258 EXPECT_EQ("class A {\n" 3259 "public:\n" 3260 " void f();\n" 3261 "\n" 3262 "private:\n" 3263 " void g() {}\n" 3264 " // test\n" 3265 "protected:\n" 3266 " int h;\n" 3267 "};", 3268 format("class A {\n" 3269 "public:\n" 3270 "void f();\n" 3271 "private:\n" 3272 "void g() {}\n" 3273 "// test\n" 3274 "protected:\n" 3275 "int h;\n" 3276 "};")); 3277 EXPECT_EQ("class A {\n" 3278 "protected:\n" 3279 "public:\n" 3280 " void f();\n" 3281 "};", 3282 format("class A {\n" 3283 "protected:\n" 3284 "\n" 3285 "public:\n" 3286 "\n" 3287 " void f();\n" 3288 "};")); 3289 3290 // Even ensure proper spacing inside macros. 3291 EXPECT_EQ("#define B \\\n" 3292 " class A { \\\n" 3293 " protected: \\\n" 3294 " public: \\\n" 3295 " void f(); \\\n" 3296 " };", 3297 format("#define B \\\n" 3298 " class A { \\\n" 3299 " protected: \\\n" 3300 " \\\n" 3301 " public: \\\n" 3302 " \\\n" 3303 " void f(); \\\n" 3304 " };", 3305 getGoogleStyle())); 3306 // But don't remove empty lines after macros ending in access specifiers. 3307 EXPECT_EQ("#define A private:\n" 3308 "\n" 3309 "int i;", 3310 format("#define A private:\n" 3311 "\n" 3312 "int i;")); 3313 } 3314 3315 TEST_F(FormatTest, FormatsClasses) { 3316 verifyFormat("class A : public B {};"); 3317 verifyFormat("class A : public ::B {};"); 3318 3319 verifyFormat( 3320 "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3321 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};"); 3322 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n" 3323 " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3324 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};"); 3325 verifyFormat( 3326 "class A : public B, public C, public D, public E, public F {};"); 3327 verifyFormat("class AAAAAAAAAAAA : public B,\n" 3328 " public C,\n" 3329 " public D,\n" 3330 " public E,\n" 3331 " public F,\n" 3332 " public G {};"); 3333 3334 verifyFormat("class\n" 3335 " ReallyReallyLongClassName {\n" 3336 " int i;\n" 3337 "};", 3338 getLLVMStyleWithColumns(32)); 3339 verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n" 3340 " aaaaaaaaaaaaaaaa> {};"); 3341 verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n" 3342 " : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n" 3343 " aaaaaaaaaaaaaaaaaaaaaa> {};"); 3344 verifyFormat("template <class R, class C>\n" 3345 "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n" 3346 " : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};"); 3347 verifyFormat("class ::A::B {};"); 3348 } 3349 3350 TEST_F(FormatTest, BreakInheritanceStyle) { 3351 FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle(); 3352 StyleWithInheritanceBreakBeforeComma.BreakInheritanceList = 3353 FormatStyle::BILS_BeforeComma; 3354 verifyFormat("class MyClass : public X {};", 3355 StyleWithInheritanceBreakBeforeComma); 3356 verifyFormat("class MyClass\n" 3357 " : public X\n" 3358 " , public Y {};", 3359 StyleWithInheritanceBreakBeforeComma); 3360 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n" 3361 " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n" 3362 " , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};", 3363 StyleWithInheritanceBreakBeforeComma); 3364 verifyFormat("struct aaaaaaaaaaaaa\n" 3365 " : public aaaaaaaaaaaaaaaaaaa< // break\n" 3366 " aaaaaaaaaaaaaaaa> {};", 3367 StyleWithInheritanceBreakBeforeComma); 3368 3369 FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle(); 3370 StyleWithInheritanceBreakAfterColon.BreakInheritanceList = 3371 FormatStyle::BILS_AfterColon; 3372 verifyFormat("class MyClass : public X {};", 3373 StyleWithInheritanceBreakAfterColon); 3374 verifyFormat("class MyClass : public X, public Y {};", 3375 StyleWithInheritanceBreakAfterColon); 3376 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n" 3377 " public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3378 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};", 3379 StyleWithInheritanceBreakAfterColon); 3380 verifyFormat("struct aaaaaaaaaaaaa :\n" 3381 " public aaaaaaaaaaaaaaaaaaa< // break\n" 3382 " aaaaaaaaaaaaaaaa> {};", 3383 StyleWithInheritanceBreakAfterColon); 3384 3385 FormatStyle StyleWithInheritanceBreakAfterComma = getLLVMStyle(); 3386 StyleWithInheritanceBreakAfterComma.BreakInheritanceList = 3387 FormatStyle::BILS_AfterComma; 3388 verifyFormat("class MyClass : public X {};", 3389 StyleWithInheritanceBreakAfterComma); 3390 verifyFormat("class MyClass : public X,\n" 3391 " public Y {};", 3392 StyleWithInheritanceBreakAfterComma); 3393 verifyFormat( 3394 "class AAAAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3395 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC " 3396 "{};", 3397 StyleWithInheritanceBreakAfterComma); 3398 verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n" 3399 " aaaaaaaaaaaaaaaa> {};", 3400 StyleWithInheritanceBreakAfterComma); 3401 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n" 3402 " : public OnceBreak,\n" 3403 " public AlwaysBreak,\n" 3404 " EvenBasesFitInOneLine {};", 3405 StyleWithInheritanceBreakAfterComma); 3406 } 3407 3408 TEST_F(FormatTest, FormatsVariableDeclarationsAfterRecord) { 3409 verifyFormat("class A {\n} a, b;"); 3410 verifyFormat("struct A {\n} a, b;"); 3411 verifyFormat("union A {\n} a, b;"); 3412 3413 verifyFormat("constexpr class A {\n} a, b;"); 3414 verifyFormat("constexpr struct A {\n} a, b;"); 3415 verifyFormat("constexpr union A {\n} a, b;"); 3416 3417 verifyFormat("namespace {\nclass A {\n} a, b;\n} // namespace"); 3418 verifyFormat("namespace {\nstruct A {\n} a, b;\n} // namespace"); 3419 verifyFormat("namespace {\nunion A {\n} a, b;\n} // namespace"); 3420 3421 verifyFormat("namespace {\nconstexpr class A {\n} a, b;\n} // namespace"); 3422 verifyFormat("namespace {\nconstexpr struct A {\n} a, b;\n} // namespace"); 3423 verifyFormat("namespace {\nconstexpr union A {\n} a, b;\n} // namespace"); 3424 3425 verifyFormat("namespace ns {\n" 3426 "class {\n" 3427 "} a, b;\n" 3428 "} // namespace ns"); 3429 verifyFormat("namespace ns {\n" 3430 "const class {\n" 3431 "} a, b;\n" 3432 "} // namespace ns"); 3433 verifyFormat("namespace ns {\n" 3434 "constexpr class C {\n" 3435 "} a, b;\n" 3436 "} // namespace ns"); 3437 verifyFormat("namespace ns {\n" 3438 "class { /* comment */\n" 3439 "} a, b;\n" 3440 "} // namespace ns"); 3441 verifyFormat("namespace ns {\n" 3442 "const class { /* comment */\n" 3443 "} a, b;\n" 3444 "} // namespace ns"); 3445 } 3446 3447 TEST_F(FormatTest, FormatsEnum) { 3448 verifyFormat("enum {\n" 3449 " Zero,\n" 3450 " One = 1,\n" 3451 " Two = One + 1,\n" 3452 " Three = (One + Two),\n" 3453 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3454 " Five = (One, Two, Three, Four, 5)\n" 3455 "};"); 3456 verifyGoogleFormat("enum {\n" 3457 " Zero,\n" 3458 " One = 1,\n" 3459 " Two = One + 1,\n" 3460 " Three = (One + Two),\n" 3461 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3462 " Five = (One, Two, Three, Four, 5)\n" 3463 "};"); 3464 verifyFormat("enum Enum {};"); 3465 verifyFormat("enum {};"); 3466 verifyFormat("enum X E {} d;"); 3467 verifyFormat("enum __attribute__((...)) E {} d;"); 3468 verifyFormat("enum __declspec__((...)) E {} d;"); 3469 verifyFormat("enum {\n" 3470 " Bar = Foo<int, int>::value\n" 3471 "};", 3472 getLLVMStyleWithColumns(30)); 3473 3474 verifyFormat("enum ShortEnum { A, B, C };"); 3475 verifyGoogleFormat("enum ShortEnum { A, B, C };"); 3476 3477 EXPECT_EQ("enum KeepEmptyLines {\n" 3478 " ONE,\n" 3479 "\n" 3480 " TWO,\n" 3481 "\n" 3482 " THREE\n" 3483 "}", 3484 format("enum KeepEmptyLines {\n" 3485 " ONE,\n" 3486 "\n" 3487 " TWO,\n" 3488 "\n" 3489 "\n" 3490 " THREE\n" 3491 "}")); 3492 verifyFormat("enum E { // comment\n" 3493 " ONE,\n" 3494 " TWO\n" 3495 "};\n" 3496 "int i;"); 3497 3498 FormatStyle EightIndent = getLLVMStyle(); 3499 EightIndent.IndentWidth = 8; 3500 verifyFormat("enum {\n" 3501 " VOID,\n" 3502 " CHAR,\n" 3503 " SHORT,\n" 3504 " INT,\n" 3505 " LONG,\n" 3506 " SIGNED,\n" 3507 " UNSIGNED,\n" 3508 " BOOL,\n" 3509 " FLOAT,\n" 3510 " DOUBLE,\n" 3511 " COMPLEX\n" 3512 "};", 3513 EightIndent); 3514 3515 // Not enums. 3516 verifyFormat("enum X f() {\n" 3517 " a();\n" 3518 " return 42;\n" 3519 "}"); 3520 verifyFormat("enum X Type::f() {\n" 3521 " a();\n" 3522 " return 42;\n" 3523 "}"); 3524 verifyFormat("enum ::X f() {\n" 3525 " a();\n" 3526 " return 42;\n" 3527 "}"); 3528 verifyFormat("enum ns::X f() {\n" 3529 " a();\n" 3530 " return 42;\n" 3531 "}"); 3532 } 3533 3534 TEST_F(FormatTest, FormatsEnumsWithErrors) { 3535 verifyFormat("enum Type {\n" 3536 " One = 0; // These semicolons should be commas.\n" 3537 " Two = 1;\n" 3538 "};"); 3539 verifyFormat("namespace n {\n" 3540 "enum Type {\n" 3541 " One,\n" 3542 " Two, // missing };\n" 3543 " int i;\n" 3544 "}\n" 3545 "void g() {}"); 3546 } 3547 3548 TEST_F(FormatTest, FormatsEnumStruct) { 3549 verifyFormat("enum struct {\n" 3550 " Zero,\n" 3551 " One = 1,\n" 3552 " Two = One + 1,\n" 3553 " Three = (One + Two),\n" 3554 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3555 " Five = (One, Two, Three, Four, 5)\n" 3556 "};"); 3557 verifyFormat("enum struct Enum {};"); 3558 verifyFormat("enum struct {};"); 3559 verifyFormat("enum struct X E {} d;"); 3560 verifyFormat("enum struct __attribute__((...)) E {} d;"); 3561 verifyFormat("enum struct __declspec__((...)) E {} d;"); 3562 verifyFormat("enum struct X f() {\n a();\n return 42;\n}"); 3563 } 3564 3565 TEST_F(FormatTest, FormatsEnumClass) { 3566 verifyFormat("enum class {\n" 3567 " Zero,\n" 3568 " One = 1,\n" 3569 " Two = One + 1,\n" 3570 " Three = (One + Two),\n" 3571 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3572 " Five = (One, Two, Three, Four, 5)\n" 3573 "};"); 3574 verifyFormat("enum class Enum {};"); 3575 verifyFormat("enum class {};"); 3576 verifyFormat("enum class X E {} d;"); 3577 verifyFormat("enum class __attribute__((...)) E {} d;"); 3578 verifyFormat("enum class __declspec__((...)) E {} d;"); 3579 verifyFormat("enum class X f() {\n a();\n return 42;\n}"); 3580 } 3581 3582 TEST_F(FormatTest, FormatsEnumTypes) { 3583 verifyFormat("enum X : int {\n" 3584 " A, // Force multiple lines.\n" 3585 " B\n" 3586 "};"); 3587 verifyFormat("enum X : int { A, B };"); 3588 verifyFormat("enum X : std::uint32_t { A, B };"); 3589 } 3590 3591 TEST_F(FormatTest, FormatsTypedefEnum) { 3592 FormatStyle Style = getLLVMStyleWithColumns(40); 3593 verifyFormat("typedef enum {} EmptyEnum;"); 3594 verifyFormat("typedef enum { A, B, C } ShortEnum;"); 3595 verifyFormat("typedef enum {\n" 3596 " ZERO = 0,\n" 3597 " ONE = 1,\n" 3598 " TWO = 2,\n" 3599 " THREE = 3\n" 3600 "} LongEnum;", 3601 Style); 3602 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 3603 Style.BraceWrapping.AfterEnum = true; 3604 verifyFormat("typedef enum {} EmptyEnum;"); 3605 verifyFormat("typedef enum { A, B, C } ShortEnum;"); 3606 verifyFormat("typedef enum\n" 3607 "{\n" 3608 " ZERO = 0,\n" 3609 " ONE = 1,\n" 3610 " TWO = 2,\n" 3611 " THREE = 3\n" 3612 "} LongEnum;", 3613 Style); 3614 } 3615 3616 TEST_F(FormatTest, FormatsNSEnums) { 3617 verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }"); 3618 verifyGoogleFormat( 3619 "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }"); 3620 verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n" 3621 " // Information about someDecentlyLongValue.\n" 3622 " someDecentlyLongValue,\n" 3623 " // Information about anotherDecentlyLongValue.\n" 3624 " anotherDecentlyLongValue,\n" 3625 " // Information about aThirdDecentlyLongValue.\n" 3626 " aThirdDecentlyLongValue\n" 3627 "};"); 3628 verifyGoogleFormat("typedef NS_CLOSED_ENUM(NSInteger, MyType) {\n" 3629 " // Information about someDecentlyLongValue.\n" 3630 " someDecentlyLongValue,\n" 3631 " // Information about anotherDecentlyLongValue.\n" 3632 " anotherDecentlyLongValue,\n" 3633 " // Information about aThirdDecentlyLongValue.\n" 3634 " aThirdDecentlyLongValue\n" 3635 "};"); 3636 verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n" 3637 " a = 1,\n" 3638 " b = 2,\n" 3639 " c = 3,\n" 3640 "};"); 3641 verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n" 3642 " a = 1,\n" 3643 " b = 2,\n" 3644 " c = 3,\n" 3645 "};"); 3646 verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n" 3647 " a = 1,\n" 3648 " b = 2,\n" 3649 " c = 3,\n" 3650 "};"); 3651 verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n" 3652 " a = 1,\n" 3653 " b = 2,\n" 3654 " c = 3,\n" 3655 "};"); 3656 } 3657 3658 TEST_F(FormatTest, FormatsBitfields) { 3659 verifyFormat("struct Bitfields {\n" 3660 " unsigned sClass : 8;\n" 3661 " unsigned ValueKind : 2;\n" 3662 "};"); 3663 verifyFormat("struct A {\n" 3664 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n" 3665 " bbbbbbbbbbbbbbbbbbbbbbbbb;\n" 3666 "};"); 3667 verifyFormat("struct MyStruct {\n" 3668 " uchar data;\n" 3669 " uchar : 8;\n" 3670 " uchar : 8;\n" 3671 " uchar other;\n" 3672 "};"); 3673 FormatStyle Style = getLLVMStyle(); 3674 Style.BitFieldColonSpacing = FormatStyle::BFCS_None; 3675 verifyFormat("struct Bitfields {\n" 3676 " unsigned sClass:8;\n" 3677 " unsigned ValueKind:2;\n" 3678 " uchar other;\n" 3679 "};", 3680 Style); 3681 verifyFormat("struct A {\n" 3682 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:1,\n" 3683 " bbbbbbbbbbbbbbbbbbbbbbbbb:2;\n" 3684 "};", 3685 Style); 3686 Style.BitFieldColonSpacing = FormatStyle::BFCS_Before; 3687 verifyFormat("struct Bitfields {\n" 3688 " unsigned sClass :8;\n" 3689 " unsigned ValueKind :2;\n" 3690 " uchar other;\n" 3691 "};", 3692 Style); 3693 Style.BitFieldColonSpacing = FormatStyle::BFCS_After; 3694 verifyFormat("struct Bitfields {\n" 3695 " unsigned sClass: 8;\n" 3696 " unsigned ValueKind: 2;\n" 3697 " uchar other;\n" 3698 "};", 3699 Style); 3700 } 3701 3702 TEST_F(FormatTest, FormatsNamespaces) { 3703 FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle(); 3704 LLVMWithNoNamespaceFix.FixNamespaceComments = false; 3705 3706 verifyFormat("namespace some_namespace {\n" 3707 "class A {};\n" 3708 "void f() { f(); }\n" 3709 "}", 3710 LLVMWithNoNamespaceFix); 3711 verifyFormat("namespace N::inline D {\n" 3712 "class A {};\n" 3713 "void f() { f(); }\n" 3714 "}", 3715 LLVMWithNoNamespaceFix); 3716 verifyFormat("namespace N::inline D::E {\n" 3717 "class A {};\n" 3718 "void f() { f(); }\n" 3719 "}", 3720 LLVMWithNoNamespaceFix); 3721 verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n" 3722 "class A {};\n" 3723 "void f() { f(); }\n" 3724 "}", 3725 LLVMWithNoNamespaceFix); 3726 verifyFormat("/* something */ namespace some_namespace {\n" 3727 "class A {};\n" 3728 "void f() { f(); }\n" 3729 "}", 3730 LLVMWithNoNamespaceFix); 3731 verifyFormat("namespace {\n" 3732 "class A {};\n" 3733 "void f() { f(); }\n" 3734 "}", 3735 LLVMWithNoNamespaceFix); 3736 verifyFormat("/* something */ namespace {\n" 3737 "class A {};\n" 3738 "void f() { f(); }\n" 3739 "}", 3740 LLVMWithNoNamespaceFix); 3741 verifyFormat("inline namespace X {\n" 3742 "class A {};\n" 3743 "void f() { f(); }\n" 3744 "}", 3745 LLVMWithNoNamespaceFix); 3746 verifyFormat("/* something */ inline namespace X {\n" 3747 "class A {};\n" 3748 "void f() { f(); }\n" 3749 "}", 3750 LLVMWithNoNamespaceFix); 3751 verifyFormat("export namespace X {\n" 3752 "class A {};\n" 3753 "void f() { f(); }\n" 3754 "}", 3755 LLVMWithNoNamespaceFix); 3756 verifyFormat("using namespace some_namespace;\n" 3757 "class A {};\n" 3758 "void f() { f(); }", 3759 LLVMWithNoNamespaceFix); 3760 3761 // This code is more common than we thought; if we 3762 // layout this correctly the semicolon will go into 3763 // its own line, which is undesirable. 3764 verifyFormat("namespace {};", LLVMWithNoNamespaceFix); 3765 verifyFormat("namespace {\n" 3766 "class A {};\n" 3767 "};", 3768 LLVMWithNoNamespaceFix); 3769 3770 verifyFormat("namespace {\n" 3771 "int SomeVariable = 0; // comment\n" 3772 "} // namespace", 3773 LLVMWithNoNamespaceFix); 3774 EXPECT_EQ("#ifndef HEADER_GUARD\n" 3775 "#define HEADER_GUARD\n" 3776 "namespace my_namespace {\n" 3777 "int i;\n" 3778 "} // my_namespace\n" 3779 "#endif // HEADER_GUARD", 3780 format("#ifndef HEADER_GUARD\n" 3781 " #define HEADER_GUARD\n" 3782 " namespace my_namespace {\n" 3783 "int i;\n" 3784 "} // my_namespace\n" 3785 "#endif // HEADER_GUARD", 3786 LLVMWithNoNamespaceFix)); 3787 3788 EXPECT_EQ("namespace A::B {\n" 3789 "class C {};\n" 3790 "}", 3791 format("namespace A::B {\n" 3792 "class C {};\n" 3793 "}", 3794 LLVMWithNoNamespaceFix)); 3795 3796 FormatStyle Style = getLLVMStyle(); 3797 Style.NamespaceIndentation = FormatStyle::NI_All; 3798 EXPECT_EQ("namespace out {\n" 3799 " int i;\n" 3800 " namespace in {\n" 3801 " int i;\n" 3802 " } // namespace in\n" 3803 "} // namespace out", 3804 format("namespace out {\n" 3805 "int i;\n" 3806 "namespace in {\n" 3807 "int i;\n" 3808 "} // namespace in\n" 3809 "} // namespace out", 3810 Style)); 3811 3812 FormatStyle ShortInlineFunctions = getLLVMStyle(); 3813 ShortInlineFunctions.NamespaceIndentation = FormatStyle::NI_All; 3814 ShortInlineFunctions.AllowShortFunctionsOnASingleLine = 3815 FormatStyle::SFS_Inline; 3816 verifyFormat("namespace {\n" 3817 " void f() {\n" 3818 " return;\n" 3819 " }\n" 3820 "} // namespace\n", 3821 ShortInlineFunctions); 3822 verifyFormat("namespace { /* comment */\n" 3823 " void f() {\n" 3824 " return;\n" 3825 " }\n" 3826 "} // namespace\n", 3827 ShortInlineFunctions); 3828 verifyFormat("namespace { // comment\n" 3829 " void f() {\n" 3830 " return;\n" 3831 " }\n" 3832 "} // namespace\n", 3833 ShortInlineFunctions); 3834 verifyFormat("namespace {\n" 3835 " int some_int;\n" 3836 " void f() {\n" 3837 " return;\n" 3838 " }\n" 3839 "} // namespace\n", 3840 ShortInlineFunctions); 3841 verifyFormat("namespace interface {\n" 3842 " void f() {\n" 3843 " return;\n" 3844 " }\n" 3845 "} // namespace interface\n", 3846 ShortInlineFunctions); 3847 verifyFormat("namespace {\n" 3848 " class X {\n" 3849 " void f() { return; }\n" 3850 " };\n" 3851 "} // namespace\n", 3852 ShortInlineFunctions); 3853 verifyFormat("namespace {\n" 3854 " class X { /* comment */\n" 3855 " void f() { return; }\n" 3856 " };\n" 3857 "} // namespace\n", 3858 ShortInlineFunctions); 3859 verifyFormat("namespace {\n" 3860 " class X { // comment\n" 3861 " void f() { return; }\n" 3862 " };\n" 3863 "} // namespace\n", 3864 ShortInlineFunctions); 3865 verifyFormat("namespace {\n" 3866 " struct X {\n" 3867 " void f() { return; }\n" 3868 " };\n" 3869 "} // namespace\n", 3870 ShortInlineFunctions); 3871 verifyFormat("namespace {\n" 3872 " union X {\n" 3873 " void f() { return; }\n" 3874 " };\n" 3875 "} // namespace\n", 3876 ShortInlineFunctions); 3877 verifyFormat("extern \"C\" {\n" 3878 "void f() {\n" 3879 " return;\n" 3880 "}\n" 3881 "} // namespace\n", 3882 ShortInlineFunctions); 3883 verifyFormat("namespace {\n" 3884 " class X {\n" 3885 " void f() { return; }\n" 3886 " } x;\n" 3887 "} // namespace\n", 3888 ShortInlineFunctions); 3889 verifyFormat("namespace {\n" 3890 " [[nodiscard]] class X {\n" 3891 " void f() { return; }\n" 3892 " };\n" 3893 "} // namespace\n", 3894 ShortInlineFunctions); 3895 verifyFormat("namespace {\n" 3896 " static class X {\n" 3897 " void f() { return; }\n" 3898 " } x;\n" 3899 "} // namespace\n", 3900 ShortInlineFunctions); 3901 verifyFormat("namespace {\n" 3902 " constexpr class X {\n" 3903 " void f() { return; }\n" 3904 " } x;\n" 3905 "} // namespace\n", 3906 ShortInlineFunctions); 3907 3908 ShortInlineFunctions.IndentExternBlock = FormatStyle::IEBS_Indent; 3909 verifyFormat("extern \"C\" {\n" 3910 " void f() {\n" 3911 " return;\n" 3912 " }\n" 3913 "} // namespace\n", 3914 ShortInlineFunctions); 3915 3916 Style.NamespaceIndentation = FormatStyle::NI_Inner; 3917 EXPECT_EQ("namespace out {\n" 3918 "int i;\n" 3919 "namespace in {\n" 3920 " int i;\n" 3921 "} // namespace in\n" 3922 "} // namespace out", 3923 format("namespace out {\n" 3924 "int i;\n" 3925 "namespace in {\n" 3926 "int i;\n" 3927 "} // namespace in\n" 3928 "} // namespace out", 3929 Style)); 3930 3931 Style.NamespaceIndentation = FormatStyle::NI_None; 3932 verifyFormat("template <class T>\n" 3933 "concept a_concept = X<>;\n" 3934 "namespace B {\n" 3935 "struct b_struct {};\n" 3936 "} // namespace B\n", 3937 Style); 3938 verifyFormat("template <int I>\n" 3939 "constexpr void foo()\n" 3940 " requires(I == 42)\n" 3941 "{}\n" 3942 "namespace ns {\n" 3943 "void foo() {}\n" 3944 "} // namespace ns\n", 3945 Style); 3946 } 3947 3948 TEST_F(FormatTest, NamespaceMacros) { 3949 FormatStyle Style = getLLVMStyle(); 3950 Style.NamespaceMacros.push_back("TESTSUITE"); 3951 3952 verifyFormat("TESTSUITE(A) {\n" 3953 "int foo();\n" 3954 "} // TESTSUITE(A)", 3955 Style); 3956 3957 verifyFormat("TESTSUITE(A, B) {\n" 3958 "int foo();\n" 3959 "} // TESTSUITE(A)", 3960 Style); 3961 3962 // Properly indent according to NamespaceIndentation style 3963 Style.NamespaceIndentation = FormatStyle::NI_All; 3964 verifyFormat("TESTSUITE(A) {\n" 3965 " int foo();\n" 3966 "} // TESTSUITE(A)", 3967 Style); 3968 verifyFormat("TESTSUITE(A) {\n" 3969 " namespace B {\n" 3970 " int foo();\n" 3971 " } // namespace B\n" 3972 "} // TESTSUITE(A)", 3973 Style); 3974 verifyFormat("namespace A {\n" 3975 " TESTSUITE(B) {\n" 3976 " int foo();\n" 3977 " } // TESTSUITE(B)\n" 3978 "} // namespace A", 3979 Style); 3980 3981 Style.NamespaceIndentation = FormatStyle::NI_Inner; 3982 verifyFormat("TESTSUITE(A) {\n" 3983 "TESTSUITE(B) {\n" 3984 " int foo();\n" 3985 "} // TESTSUITE(B)\n" 3986 "} // TESTSUITE(A)", 3987 Style); 3988 verifyFormat("TESTSUITE(A) {\n" 3989 "namespace B {\n" 3990 " int foo();\n" 3991 "} // namespace B\n" 3992 "} // TESTSUITE(A)", 3993 Style); 3994 verifyFormat("namespace A {\n" 3995 "TESTSUITE(B) {\n" 3996 " int foo();\n" 3997 "} // TESTSUITE(B)\n" 3998 "} // namespace A", 3999 Style); 4000 4001 // Properly merge namespace-macros blocks in CompactNamespaces mode 4002 Style.NamespaceIndentation = FormatStyle::NI_None; 4003 Style.CompactNamespaces = true; 4004 verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n" 4005 "}} // TESTSUITE(A::B)", 4006 Style); 4007 4008 EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n" 4009 "}} // TESTSUITE(out::in)", 4010 format("TESTSUITE(out) {\n" 4011 "TESTSUITE(in) {\n" 4012 "} // TESTSUITE(in)\n" 4013 "} // TESTSUITE(out)", 4014 Style)); 4015 4016 EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n" 4017 "}} // TESTSUITE(out::in)", 4018 format("TESTSUITE(out) {\n" 4019 "TESTSUITE(in) {\n" 4020 "} // TESTSUITE(in)\n" 4021 "} // TESTSUITE(out)", 4022 Style)); 4023 4024 // Do not merge different namespaces/macros 4025 EXPECT_EQ("namespace out {\n" 4026 "TESTSUITE(in) {\n" 4027 "} // TESTSUITE(in)\n" 4028 "} // namespace out", 4029 format("namespace out {\n" 4030 "TESTSUITE(in) {\n" 4031 "} // TESTSUITE(in)\n" 4032 "} // namespace out", 4033 Style)); 4034 EXPECT_EQ("TESTSUITE(out) {\n" 4035 "namespace in {\n" 4036 "} // namespace in\n" 4037 "} // TESTSUITE(out)", 4038 format("TESTSUITE(out) {\n" 4039 "namespace in {\n" 4040 "} // namespace in\n" 4041 "} // TESTSUITE(out)", 4042 Style)); 4043 Style.NamespaceMacros.push_back("FOOBAR"); 4044 EXPECT_EQ("TESTSUITE(out) {\n" 4045 "FOOBAR(in) {\n" 4046 "} // FOOBAR(in)\n" 4047 "} // TESTSUITE(out)", 4048 format("TESTSUITE(out) {\n" 4049 "FOOBAR(in) {\n" 4050 "} // FOOBAR(in)\n" 4051 "} // TESTSUITE(out)", 4052 Style)); 4053 } 4054 4055 TEST_F(FormatTest, FormatsCompactNamespaces) { 4056 FormatStyle Style = getLLVMStyle(); 4057 Style.CompactNamespaces = true; 4058 Style.NamespaceMacros.push_back("TESTSUITE"); 4059 4060 verifyFormat("namespace A { namespace B {\n" 4061 "}} // namespace A::B", 4062 Style); 4063 4064 EXPECT_EQ("namespace out { namespace in {\n" 4065 "}} // namespace out::in", 4066 format("namespace out {\n" 4067 "namespace in {\n" 4068 "} // namespace in\n" 4069 "} // namespace out", 4070 Style)); 4071 4072 // Only namespaces which have both consecutive opening and end get compacted 4073 EXPECT_EQ("namespace out {\n" 4074 "namespace in1 {\n" 4075 "} // namespace in1\n" 4076 "namespace in2 {\n" 4077 "} // namespace in2\n" 4078 "} // namespace out", 4079 format("namespace out {\n" 4080 "namespace in1 {\n" 4081 "} // namespace in1\n" 4082 "namespace in2 {\n" 4083 "} // namespace in2\n" 4084 "} // namespace out", 4085 Style)); 4086 4087 EXPECT_EQ("namespace out {\n" 4088 "int i;\n" 4089 "namespace in {\n" 4090 "int j;\n" 4091 "} // namespace in\n" 4092 "int k;\n" 4093 "} // namespace out", 4094 format("namespace out { int i;\n" 4095 "namespace in { int j; } // namespace in\n" 4096 "int k; } // namespace out", 4097 Style)); 4098 4099 EXPECT_EQ("namespace A { namespace B { namespace C {\n" 4100 "}}} // namespace A::B::C\n", 4101 format("namespace A { namespace B {\n" 4102 "namespace C {\n" 4103 "}} // namespace B::C\n" 4104 "} // namespace A\n", 4105 Style)); 4106 4107 Style.ColumnLimit = 40; 4108 EXPECT_EQ("namespace aaaaaaaaaa {\n" 4109 "namespace bbbbbbbbbb {\n" 4110 "}} // namespace aaaaaaaaaa::bbbbbbbbbb", 4111 format("namespace aaaaaaaaaa {\n" 4112 "namespace bbbbbbbbbb {\n" 4113 "} // namespace bbbbbbbbbb\n" 4114 "} // namespace aaaaaaaaaa", 4115 Style)); 4116 4117 EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n" 4118 "namespace cccccc {\n" 4119 "}}} // namespace aaaaaa::bbbbbb::cccccc", 4120 format("namespace aaaaaa {\n" 4121 "namespace bbbbbb {\n" 4122 "namespace cccccc {\n" 4123 "} // namespace cccccc\n" 4124 "} // namespace bbbbbb\n" 4125 "} // namespace aaaaaa", 4126 Style)); 4127 Style.ColumnLimit = 80; 4128 4129 // Extra semicolon after 'inner' closing brace prevents merging 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 // Extra semicolon after 'outer' closing brace is conserved 4139 EXPECT_EQ("namespace out { namespace in {\n" 4140 "}}; // namespace out::in", 4141 format("namespace out {\n" 4142 "namespace in {\n" 4143 "} // namespace in\n" 4144 "}; // namespace out", 4145 Style)); 4146 4147 Style.NamespaceIndentation = FormatStyle::NI_All; 4148 EXPECT_EQ("namespace out { namespace in {\n" 4149 " int i;\n" 4150 "}} // namespace out::in", 4151 format("namespace out {\n" 4152 "namespace in {\n" 4153 "int i;\n" 4154 "} // namespace in\n" 4155 "} // namespace out", 4156 Style)); 4157 EXPECT_EQ("namespace out { namespace mid {\n" 4158 " namespace in {\n" 4159 " int j;\n" 4160 " } // namespace in\n" 4161 " int k;\n" 4162 "}} // namespace out::mid", 4163 format("namespace out { namespace mid {\n" 4164 "namespace in { int j; } // namespace in\n" 4165 "int k; }} // namespace out::mid", 4166 Style)); 4167 4168 Style.NamespaceIndentation = FormatStyle::NI_Inner; 4169 EXPECT_EQ("namespace out { namespace in {\n" 4170 " int i;\n" 4171 "}} // namespace out::in", 4172 format("namespace out {\n" 4173 "namespace in {\n" 4174 "int i;\n" 4175 "} // namespace in\n" 4176 "} // namespace out", 4177 Style)); 4178 EXPECT_EQ("namespace out { namespace mid { namespace in {\n" 4179 " int i;\n" 4180 "}}} // namespace out::mid::in", 4181 format("namespace out {\n" 4182 "namespace mid {\n" 4183 "namespace in {\n" 4184 "int i;\n" 4185 "} // namespace in\n" 4186 "} // namespace mid\n" 4187 "} // namespace out", 4188 Style)); 4189 4190 Style.CompactNamespaces = true; 4191 Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 4192 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4193 Style.BraceWrapping.BeforeLambdaBody = true; 4194 verifyFormat("namespace out { namespace in {\n" 4195 "}} // namespace out::in", 4196 Style); 4197 EXPECT_EQ("namespace out { namespace in {\n" 4198 "}} // namespace out::in", 4199 format("namespace out {\n" 4200 "namespace in {\n" 4201 "} // namespace in\n" 4202 "} // namespace out", 4203 Style)); 4204 } 4205 4206 TEST_F(FormatTest, FormatsExternC) { 4207 verifyFormat("extern \"C\" {\nint a;"); 4208 verifyFormat("extern \"C\" {}"); 4209 verifyFormat("extern \"C\" {\n" 4210 "int foo();\n" 4211 "}"); 4212 verifyFormat("extern \"C\" int foo() {}"); 4213 verifyFormat("extern \"C\" int foo();"); 4214 verifyFormat("extern \"C\" int foo() {\n" 4215 " int i = 42;\n" 4216 " return i;\n" 4217 "}"); 4218 4219 FormatStyle Style = getLLVMStyle(); 4220 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4221 Style.BraceWrapping.AfterFunction = true; 4222 verifyFormat("extern \"C\" int foo() {}", Style); 4223 verifyFormat("extern \"C\" int foo();", Style); 4224 verifyFormat("extern \"C\" int foo()\n" 4225 "{\n" 4226 " int i = 42;\n" 4227 " return i;\n" 4228 "}", 4229 Style); 4230 4231 Style.BraceWrapping.AfterExternBlock = true; 4232 Style.BraceWrapping.SplitEmptyRecord = false; 4233 verifyFormat("extern \"C\"\n" 4234 "{}", 4235 Style); 4236 verifyFormat("extern \"C\"\n" 4237 "{\n" 4238 " int foo();\n" 4239 "}", 4240 Style); 4241 } 4242 4243 TEST_F(FormatTest, IndentExternBlockStyle) { 4244 FormatStyle Style = getLLVMStyle(); 4245 Style.IndentWidth = 2; 4246 4247 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4248 verifyFormat("extern \"C\" { /*9*/\n" 4249 "}", 4250 Style); 4251 verifyFormat("extern \"C\" {\n" 4252 " int foo10();\n" 4253 "}", 4254 Style); 4255 4256 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 4257 verifyFormat("extern \"C\" { /*11*/\n" 4258 "}", 4259 Style); 4260 verifyFormat("extern \"C\" {\n" 4261 "int foo12();\n" 4262 "}", 4263 Style); 4264 4265 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4266 Style.BraceWrapping.AfterExternBlock = true; 4267 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4268 verifyFormat("extern \"C\"\n" 4269 "{ /*13*/\n" 4270 "}", 4271 Style); 4272 verifyFormat("extern \"C\"\n{\n" 4273 " int foo14();\n" 4274 "}", 4275 Style); 4276 4277 Style.BraceWrapping.AfterExternBlock = false; 4278 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 4279 verifyFormat("extern \"C\" { /*15*/\n" 4280 "}", 4281 Style); 4282 verifyFormat("extern \"C\" {\n" 4283 "int foo16();\n" 4284 "}", 4285 Style); 4286 4287 Style.BraceWrapping.AfterExternBlock = true; 4288 verifyFormat("extern \"C\"\n" 4289 "{ /*13*/\n" 4290 "}", 4291 Style); 4292 verifyFormat("extern \"C\"\n" 4293 "{\n" 4294 "int foo14();\n" 4295 "}", 4296 Style); 4297 4298 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 4299 verifyFormat("extern \"C\"\n" 4300 "{ /*13*/\n" 4301 "}", 4302 Style); 4303 verifyFormat("extern \"C\"\n" 4304 "{\n" 4305 " int foo14();\n" 4306 "}", 4307 Style); 4308 } 4309 4310 TEST_F(FormatTest, FormatsInlineASM) { 4311 verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));"); 4312 verifyFormat("asm(\"nop\" ::: \"memory\");"); 4313 verifyFormat( 4314 "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n" 4315 " \"cpuid\\n\\t\"\n" 4316 " \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n" 4317 " : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n" 4318 " : \"a\"(value));"); 4319 EXPECT_EQ( 4320 "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n" 4321 " __asm {\n" 4322 " mov edx,[that] // vtable in edx\n" 4323 " mov eax,methodIndex\n" 4324 " call [edx][eax*4] // stdcall\n" 4325 " }\n" 4326 "}", 4327 format("void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n" 4328 " __asm {\n" 4329 " mov edx,[that] // vtable in edx\n" 4330 " mov eax,methodIndex\n" 4331 " call [edx][eax*4] // stdcall\n" 4332 " }\n" 4333 "}")); 4334 EXPECT_EQ("_asm {\n" 4335 " xor eax, eax;\n" 4336 " cpuid;\n" 4337 "}", 4338 format("_asm {\n" 4339 " xor eax, eax;\n" 4340 " cpuid;\n" 4341 "}")); 4342 verifyFormat("void function() {\n" 4343 " // comment\n" 4344 " asm(\"\");\n" 4345 "}"); 4346 EXPECT_EQ("__asm {\n" 4347 "}\n" 4348 "int i;", 4349 format("__asm {\n" 4350 "}\n" 4351 "int i;")); 4352 } 4353 4354 TEST_F(FormatTest, FormatTryCatch) { 4355 verifyFormat("try {\n" 4356 " throw a * b;\n" 4357 "} catch (int a) {\n" 4358 " // Do nothing.\n" 4359 "} catch (...) {\n" 4360 " exit(42);\n" 4361 "}"); 4362 4363 // Function-level try statements. 4364 verifyFormat("int f() try { return 4; } catch (...) {\n" 4365 " return 5;\n" 4366 "}"); 4367 verifyFormat("class A {\n" 4368 " int a;\n" 4369 " A() try : a(0) {\n" 4370 " } catch (...) {\n" 4371 " throw;\n" 4372 " }\n" 4373 "};\n"); 4374 verifyFormat("class A {\n" 4375 " int a;\n" 4376 " A() try : a(0), b{1} {\n" 4377 " } catch (...) {\n" 4378 " throw;\n" 4379 " }\n" 4380 "};\n"); 4381 verifyFormat("class A {\n" 4382 " int a;\n" 4383 " A() try : a(0), b{1}, c{2} {\n" 4384 " } catch (...) {\n" 4385 " throw;\n" 4386 " }\n" 4387 "};\n"); 4388 verifyFormat("class A {\n" 4389 " int a;\n" 4390 " A() try : a(0), b{1}, c{2} {\n" 4391 " { // New scope.\n" 4392 " }\n" 4393 " } catch (...) {\n" 4394 " throw;\n" 4395 " }\n" 4396 "};\n"); 4397 4398 // Incomplete try-catch blocks. 4399 verifyIncompleteFormat("try {} catch ("); 4400 } 4401 4402 TEST_F(FormatTest, FormatTryAsAVariable) { 4403 verifyFormat("int try;"); 4404 verifyFormat("int try, size;"); 4405 verifyFormat("try = foo();"); 4406 verifyFormat("if (try < size) {\n return true;\n}"); 4407 4408 verifyFormat("int catch;"); 4409 verifyFormat("int catch, size;"); 4410 verifyFormat("catch = foo();"); 4411 verifyFormat("if (catch < size) {\n return true;\n}"); 4412 4413 FormatStyle Style = getLLVMStyle(); 4414 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4415 Style.BraceWrapping.AfterFunction = true; 4416 Style.BraceWrapping.BeforeCatch = true; 4417 verifyFormat("try {\n" 4418 " int bar = 1;\n" 4419 "}\n" 4420 "catch (...) {\n" 4421 " int bar = 1;\n" 4422 "}", 4423 Style); 4424 verifyFormat("#if NO_EX\n" 4425 "try\n" 4426 "#endif\n" 4427 "{\n" 4428 "}\n" 4429 "#if NO_EX\n" 4430 "catch (...) {\n" 4431 "}", 4432 Style); 4433 verifyFormat("try /* abc */ {\n" 4434 " int bar = 1;\n" 4435 "}\n" 4436 "catch (...) {\n" 4437 " int bar = 1;\n" 4438 "}", 4439 Style); 4440 verifyFormat("try\n" 4441 "// abc\n" 4442 "{\n" 4443 " int bar = 1;\n" 4444 "}\n" 4445 "catch (...) {\n" 4446 " int bar = 1;\n" 4447 "}", 4448 Style); 4449 } 4450 4451 TEST_F(FormatTest, FormatSEHTryCatch) { 4452 verifyFormat("__try {\n" 4453 " int a = b * c;\n" 4454 "} __except (EXCEPTION_EXECUTE_HANDLER) {\n" 4455 " // Do nothing.\n" 4456 "}"); 4457 4458 verifyFormat("__try {\n" 4459 " int a = b * c;\n" 4460 "} __finally {\n" 4461 " // Do nothing.\n" 4462 "}"); 4463 4464 verifyFormat("DEBUG({\n" 4465 " __try {\n" 4466 " } __finally {\n" 4467 " }\n" 4468 "});\n"); 4469 } 4470 4471 TEST_F(FormatTest, IncompleteTryCatchBlocks) { 4472 verifyFormat("try {\n" 4473 " f();\n" 4474 "} catch {\n" 4475 " g();\n" 4476 "}"); 4477 verifyFormat("try {\n" 4478 " f();\n" 4479 "} catch (A a) MACRO(x) {\n" 4480 " g();\n" 4481 "} catch (B b) MACRO(x) {\n" 4482 " g();\n" 4483 "}"); 4484 } 4485 4486 TEST_F(FormatTest, FormatTryCatchBraceStyles) { 4487 FormatStyle Style = getLLVMStyle(); 4488 for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla, 4489 FormatStyle::BS_WebKit}) { 4490 Style.BreakBeforeBraces = BraceStyle; 4491 verifyFormat("try {\n" 4492 " // something\n" 4493 "} catch (...) {\n" 4494 " // something\n" 4495 "}", 4496 Style); 4497 } 4498 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 4499 verifyFormat("try {\n" 4500 " // something\n" 4501 "}\n" 4502 "catch (...) {\n" 4503 " // something\n" 4504 "}", 4505 Style); 4506 verifyFormat("__try {\n" 4507 " // something\n" 4508 "}\n" 4509 "__finally {\n" 4510 " // something\n" 4511 "}", 4512 Style); 4513 verifyFormat("@try {\n" 4514 " // something\n" 4515 "}\n" 4516 "@finally {\n" 4517 " // something\n" 4518 "}", 4519 Style); 4520 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 4521 verifyFormat("try\n" 4522 "{\n" 4523 " // something\n" 4524 "}\n" 4525 "catch (...)\n" 4526 "{\n" 4527 " // something\n" 4528 "}", 4529 Style); 4530 Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 4531 verifyFormat("try\n" 4532 " {\n" 4533 " // something white\n" 4534 " }\n" 4535 "catch (...)\n" 4536 " {\n" 4537 " // something white\n" 4538 " }", 4539 Style); 4540 Style.BreakBeforeBraces = FormatStyle::BS_GNU; 4541 verifyFormat("try\n" 4542 " {\n" 4543 " // something\n" 4544 " }\n" 4545 "catch (...)\n" 4546 " {\n" 4547 " // something\n" 4548 " }", 4549 Style); 4550 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4551 Style.BraceWrapping.BeforeCatch = true; 4552 verifyFormat("try {\n" 4553 " // something\n" 4554 "}\n" 4555 "catch (...) {\n" 4556 " // something\n" 4557 "}", 4558 Style); 4559 } 4560 4561 TEST_F(FormatTest, StaticInitializers) { 4562 verifyFormat("static SomeClass SC = {1, 'a'};"); 4563 4564 verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n" 4565 " 100000000, " 4566 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};"); 4567 4568 // Here, everything other than the "}" would fit on a line. 4569 verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n" 4570 " 10000000000000000000000000};"); 4571 EXPECT_EQ("S s = {a,\n" 4572 "\n" 4573 " b};", 4574 format("S s = {\n" 4575 " a,\n" 4576 "\n" 4577 " b\n" 4578 "};")); 4579 4580 // FIXME: This would fit into the column limit if we'd fit "{ {" on the first 4581 // line. However, the formatting looks a bit off and this probably doesn't 4582 // happen often in practice. 4583 verifyFormat("static int Variable[1] = {\n" 4584 " {1000000000000000000000000000000000000}};", 4585 getLLVMStyleWithColumns(40)); 4586 } 4587 4588 TEST_F(FormatTest, DesignatedInitializers) { 4589 verifyFormat("const struct A a = {.a = 1, .b = 2};"); 4590 verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n" 4591 " .bbbbbbbbbb = 2,\n" 4592 " .cccccccccc = 3,\n" 4593 " .dddddddddd = 4,\n" 4594 " .eeeeeeeeee = 5};"); 4595 verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n" 4596 " .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n" 4597 " .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n" 4598 " .ccccccccccccccccccccccccccc = 3,\n" 4599 " .ddddddddddddddddddddddddddd = 4,\n" 4600 " .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};"); 4601 4602 verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};"); 4603 4604 verifyFormat("const struct A a = {[0] = 1, [1] = 2};"); 4605 verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n" 4606 " [2] = bbbbbbbbbb,\n" 4607 " [3] = cccccccccc,\n" 4608 " [4] = dddddddddd,\n" 4609 " [5] = eeeeeeeeee};"); 4610 verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n" 4611 " [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 4612 " [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 4613 " [3] = cccccccccccccccccccccccccccccccccccccc,\n" 4614 " [4] = dddddddddddddddddddddddddddddddddddddd,\n" 4615 " [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};"); 4616 } 4617 4618 TEST_F(FormatTest, NestedStaticInitializers) { 4619 verifyFormat("static A x = {{{}}};\n"); 4620 verifyFormat("static A x = {{{init1, init2, init3, init4},\n" 4621 " {init1, init2, init3, init4}}};", 4622 getLLVMStyleWithColumns(50)); 4623 4624 verifyFormat("somes Status::global_reps[3] = {\n" 4625 " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n" 4626 " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n" 4627 " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};", 4628 getLLVMStyleWithColumns(60)); 4629 verifyGoogleFormat("SomeType Status::global_reps[3] = {\n" 4630 " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n" 4631 " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n" 4632 " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};"); 4633 verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n" 4634 " {rect.fRight - rect.fLeft, rect.fBottom - " 4635 "rect.fTop}};"); 4636 4637 verifyFormat( 4638 "SomeArrayOfSomeType a = {\n" 4639 " {{1, 2, 3},\n" 4640 " {1, 2, 3},\n" 4641 " {111111111111111111111111111111, 222222222222222222222222222222,\n" 4642 " 333333333333333333333333333333},\n" 4643 " {1, 2, 3},\n" 4644 " {1, 2, 3}}};"); 4645 verifyFormat( 4646 "SomeArrayOfSomeType a = {\n" 4647 " {{1, 2, 3}},\n" 4648 " {{1, 2, 3}},\n" 4649 " {{111111111111111111111111111111, 222222222222222222222222222222,\n" 4650 " 333333333333333333333333333333}},\n" 4651 " {{1, 2, 3}},\n" 4652 " {{1, 2, 3}}};"); 4653 4654 verifyFormat("struct {\n" 4655 " unsigned bit;\n" 4656 " const char *const name;\n" 4657 "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n" 4658 " {kOsWin, \"Windows\"},\n" 4659 " {kOsLinux, \"Linux\"},\n" 4660 " {kOsCrOS, \"Chrome OS\"}};"); 4661 verifyFormat("struct {\n" 4662 " unsigned bit;\n" 4663 " const char *const name;\n" 4664 "} kBitsToOs[] = {\n" 4665 " {kOsMac, \"Mac\"},\n" 4666 " {kOsWin, \"Windows\"},\n" 4667 " {kOsLinux, \"Linux\"},\n" 4668 " {kOsCrOS, \"Chrome OS\"},\n" 4669 "};"); 4670 } 4671 4672 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) { 4673 verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro(" 4674 " \\\n" 4675 " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)"); 4676 } 4677 4678 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) { 4679 verifyFormat("virtual void write(ELFWriter *writerrr,\n" 4680 " OwningPtr<FileOutputBuffer> &buffer) = 0;"); 4681 4682 // Do break defaulted and deleted functions. 4683 verifyFormat("virtual void ~Deeeeeeeestructor() =\n" 4684 " default;", 4685 getLLVMStyleWithColumns(40)); 4686 verifyFormat("virtual void ~Deeeeeeeestructor() =\n" 4687 " delete;", 4688 getLLVMStyleWithColumns(40)); 4689 } 4690 4691 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) { 4692 verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3", 4693 getLLVMStyleWithColumns(40)); 4694 verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"", 4695 getLLVMStyleWithColumns(40)); 4696 EXPECT_EQ("#define Q \\\n" 4697 " \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\" \\\n" 4698 " \"aaaaaaaa.cpp\"", 4699 format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"", 4700 getLLVMStyleWithColumns(40))); 4701 } 4702 4703 TEST_F(FormatTest, UnderstandsLinePPDirective) { 4704 EXPECT_EQ("# 123 \"A string literal\"", 4705 format(" # 123 \"A string literal\"")); 4706 } 4707 4708 TEST_F(FormatTest, LayoutUnknownPPDirective) { 4709 EXPECT_EQ("#;", format("#;")); 4710 verifyFormat("#\n;\n;\n;"); 4711 } 4712 4713 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) { 4714 EXPECT_EQ("#line 42 \"test\"\n", 4715 format("# \\\n line \\\n 42 \\\n \"test\"\n")); 4716 EXPECT_EQ("#define A B\n", format("# \\\n define \\\n A \\\n B\n", 4717 getLLVMStyleWithColumns(12))); 4718 } 4719 4720 TEST_F(FormatTest, EndOfFileEndsPPDirective) { 4721 EXPECT_EQ("#line 42 \"test\"", 4722 format("# \\\n line \\\n 42 \\\n \"test\"")); 4723 EXPECT_EQ("#define A B", format("# \\\n define \\\n A \\\n B")); 4724 } 4725 4726 TEST_F(FormatTest, DoesntRemoveUnknownTokens) { 4727 verifyFormat("#define A \\x20"); 4728 verifyFormat("#define A \\ x20"); 4729 EXPECT_EQ("#define A \\ x20", format("#define A \\ x20")); 4730 verifyFormat("#define A ''"); 4731 verifyFormat("#define A ''qqq"); 4732 verifyFormat("#define A `qqq"); 4733 verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");"); 4734 EXPECT_EQ("const char *c = STRINGIFY(\n" 4735 "\\na : b);", 4736 format("const char * c = STRINGIFY(\n" 4737 "\\na : b);")); 4738 4739 verifyFormat("a\r\\"); 4740 verifyFormat("a\v\\"); 4741 verifyFormat("a\f\\"); 4742 } 4743 4744 TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) { 4745 FormatStyle style = getChromiumStyle(FormatStyle::LK_Cpp); 4746 style.IndentWidth = 4; 4747 style.PPIndentWidth = 1; 4748 4749 style.IndentPPDirectives = FormatStyle::PPDIS_None; 4750 verifyFormat("#ifdef __linux__\n" 4751 "void foo() {\n" 4752 " int x = 0;\n" 4753 "}\n" 4754 "#define FOO\n" 4755 "#endif\n" 4756 "void bar() {\n" 4757 " int y = 0;\n" 4758 "}\n", 4759 style); 4760 4761 style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash; 4762 verifyFormat("#ifdef __linux__\n" 4763 "void foo() {\n" 4764 " int x = 0;\n" 4765 "}\n" 4766 "# define FOO foo\n" 4767 "#endif\n" 4768 "void bar() {\n" 4769 " int y = 0;\n" 4770 "}\n", 4771 style); 4772 4773 style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash; 4774 verifyFormat("#ifdef __linux__\n" 4775 "void foo() {\n" 4776 " int x = 0;\n" 4777 "}\n" 4778 " #define FOO foo\n" 4779 "#endif\n" 4780 "void bar() {\n" 4781 " int y = 0;\n" 4782 "}\n", 4783 style); 4784 } 4785 4786 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) { 4787 verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13)); 4788 verifyFormat("#define A( \\\n BB)", getLLVMStyleWithColumns(12)); 4789 verifyFormat("#define A( \\\n A, B)", getLLVMStyleWithColumns(12)); 4790 // FIXME: We never break before the macro name. 4791 verifyFormat("#define AA( \\\n B)", getLLVMStyleWithColumns(12)); 4792 4793 verifyFormat("#define A A\n#define A A"); 4794 verifyFormat("#define A(X) A\n#define A A"); 4795 4796 verifyFormat("#define Something Other", getLLVMStyleWithColumns(23)); 4797 verifyFormat("#define Something \\\n Other", getLLVMStyleWithColumns(22)); 4798 } 4799 4800 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) { 4801 EXPECT_EQ("// somecomment\n" 4802 "#include \"a.h\"\n" 4803 "#define A( \\\n" 4804 " A, B)\n" 4805 "#include \"b.h\"\n" 4806 "// somecomment\n", 4807 format(" // somecomment\n" 4808 " #include \"a.h\"\n" 4809 "#define A(A,\\\n" 4810 " B)\n" 4811 " #include \"b.h\"\n" 4812 " // somecomment\n", 4813 getLLVMStyleWithColumns(13))); 4814 } 4815 4816 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); } 4817 4818 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) { 4819 EXPECT_EQ("#define A \\\n" 4820 " c; \\\n" 4821 " e;\n" 4822 "f;", 4823 format("#define A c; e;\n" 4824 "f;", 4825 getLLVMStyleWithColumns(14))); 4826 } 4827 4828 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); } 4829 4830 TEST_F(FormatTest, MacroDefinitionInsideStatement) { 4831 EXPECT_EQ("int x,\n" 4832 "#define A\n" 4833 " y;", 4834 format("int x,\n#define A\ny;")); 4835 } 4836 4837 TEST_F(FormatTest, HashInMacroDefinition) { 4838 EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle())); 4839 EXPECT_EQ("#define A(c) u#c", format("#define A(c) u#c", getLLVMStyle())); 4840 EXPECT_EQ("#define A(c) U#c", format("#define A(c) U#c", getLLVMStyle())); 4841 EXPECT_EQ("#define A(c) u8#c", format("#define A(c) u8#c", getLLVMStyle())); 4842 EXPECT_EQ("#define A(c) LR#c", format("#define A(c) LR#c", getLLVMStyle())); 4843 EXPECT_EQ("#define A(c) uR#c", format("#define A(c) uR#c", getLLVMStyle())); 4844 EXPECT_EQ("#define A(c) UR#c", format("#define A(c) UR#c", getLLVMStyle())); 4845 EXPECT_EQ("#define A(c) u8R#c", format("#define A(c) u8R#c", getLLVMStyle())); 4846 verifyFormat("#define A \\\n b #c;", getLLVMStyleWithColumns(11)); 4847 verifyFormat("#define A \\\n" 4848 " { \\\n" 4849 " f(#c); \\\n" 4850 " }", 4851 getLLVMStyleWithColumns(11)); 4852 4853 verifyFormat("#define A(X) \\\n" 4854 " void function##X()", 4855 getLLVMStyleWithColumns(22)); 4856 4857 verifyFormat("#define A(a, b, c) \\\n" 4858 " void a##b##c()", 4859 getLLVMStyleWithColumns(22)); 4860 4861 verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22)); 4862 } 4863 4864 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) { 4865 EXPECT_EQ("#define A (x)", format("#define A (x)")); 4866 EXPECT_EQ("#define A(x)", format("#define A(x)")); 4867 4868 FormatStyle Style = getLLVMStyle(); 4869 Style.SpaceBeforeParens = FormatStyle::SBPO_Never; 4870 verifyFormat("#define true ((foo)1)", Style); 4871 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 4872 verifyFormat("#define false((foo)0)", Style); 4873 } 4874 4875 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) { 4876 EXPECT_EQ("#define A b;", format("#define A \\\n" 4877 " \\\n" 4878 " b;", 4879 getLLVMStyleWithColumns(25))); 4880 EXPECT_EQ("#define A \\\n" 4881 " \\\n" 4882 " a; \\\n" 4883 " b;", 4884 format("#define A \\\n" 4885 " \\\n" 4886 " a; \\\n" 4887 " b;", 4888 getLLVMStyleWithColumns(11))); 4889 EXPECT_EQ("#define A \\\n" 4890 " a; \\\n" 4891 " \\\n" 4892 " b;", 4893 format("#define A \\\n" 4894 " a; \\\n" 4895 " \\\n" 4896 " b;", 4897 getLLVMStyleWithColumns(11))); 4898 } 4899 4900 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) { 4901 verifyIncompleteFormat("#define A :"); 4902 verifyFormat("#define SOMECASES \\\n" 4903 " case 1: \\\n" 4904 " case 2\n", 4905 getLLVMStyleWithColumns(20)); 4906 verifyFormat("#define MACRO(a) \\\n" 4907 " if (a) \\\n" 4908 " f(); \\\n" 4909 " else \\\n" 4910 " g()", 4911 getLLVMStyleWithColumns(18)); 4912 verifyFormat("#define A template <typename T>"); 4913 verifyIncompleteFormat("#define STR(x) #x\n" 4914 "f(STR(this_is_a_string_literal{));"); 4915 verifyFormat("#pragma omp threadprivate( \\\n" 4916 " y)), // expected-warning", 4917 getLLVMStyleWithColumns(28)); 4918 verifyFormat("#d, = };"); 4919 verifyFormat("#if \"a"); 4920 verifyIncompleteFormat("({\n" 4921 "#define b \\\n" 4922 " } \\\n" 4923 " a\n" 4924 "a", 4925 getLLVMStyleWithColumns(15)); 4926 verifyFormat("#define A \\\n" 4927 " { \\\n" 4928 " {\n" 4929 "#define B \\\n" 4930 " } \\\n" 4931 " }", 4932 getLLVMStyleWithColumns(15)); 4933 verifyNoCrash("#if a\na(\n#else\n#endif\n{a"); 4934 verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}"); 4935 verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};"); 4936 verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() { \n)}"); 4937 } 4938 4939 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) { 4940 verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline. 4941 EXPECT_EQ("class A : public QObject {\n" 4942 " Q_OBJECT\n" 4943 "\n" 4944 " A() {}\n" 4945 "};", 4946 format("class A : public QObject {\n" 4947 " Q_OBJECT\n" 4948 "\n" 4949 " A() {\n}\n" 4950 "} ;")); 4951 EXPECT_EQ("MACRO\n" 4952 "/*static*/ int i;", 4953 format("MACRO\n" 4954 " /*static*/ int i;")); 4955 EXPECT_EQ("SOME_MACRO\n" 4956 "namespace {\n" 4957 "void f();\n" 4958 "} // namespace", 4959 format("SOME_MACRO\n" 4960 " namespace {\n" 4961 "void f( );\n" 4962 "} // namespace")); 4963 // Only if the identifier contains at least 5 characters. 4964 EXPECT_EQ("HTTP f();", format("HTTP\nf();")); 4965 EXPECT_EQ("MACRO\nf();", format("MACRO\nf();")); 4966 // Only if everything is upper case. 4967 EXPECT_EQ("class A : public QObject {\n" 4968 " Q_Object A() {}\n" 4969 "};", 4970 format("class A : public QObject {\n" 4971 " Q_Object\n" 4972 " A() {\n}\n" 4973 "} ;")); 4974 4975 // Only if the next line can actually start an unwrapped line. 4976 EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;", 4977 format("SOME_WEIRD_LOG_MACRO\n" 4978 "<< SomeThing;")); 4979 4980 verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), " 4981 "(n, buffers))\n", 4982 getChromiumStyle(FormatStyle::LK_Cpp)); 4983 4984 // See PR41483 4985 EXPECT_EQ("/**/ FOO(a)\n" 4986 "FOO(b)", 4987 format("/**/ FOO(a)\n" 4988 "FOO(b)")); 4989 } 4990 4991 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) { 4992 EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n" 4993 "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n" 4994 "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n" 4995 "class X {};\n" 4996 "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n" 4997 "int *createScopDetectionPass() { return 0; }", 4998 format(" INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n" 4999 " INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n" 5000 " INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n" 5001 " class X {};\n" 5002 " INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n" 5003 " int *createScopDetectionPass() { return 0; }")); 5004 // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as 5005 // braces, so that inner block is indented one level more. 5006 EXPECT_EQ("int q() {\n" 5007 " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n" 5008 " IPC_MESSAGE_HANDLER(xxx, qqq)\n" 5009 " IPC_END_MESSAGE_MAP()\n" 5010 "}", 5011 format("int q() {\n" 5012 " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n" 5013 " IPC_MESSAGE_HANDLER(xxx, qqq)\n" 5014 " IPC_END_MESSAGE_MAP()\n" 5015 "}")); 5016 5017 // Same inside macros. 5018 EXPECT_EQ("#define LIST(L) \\\n" 5019 " L(A) \\\n" 5020 " L(B) \\\n" 5021 " L(C)", 5022 format("#define LIST(L) \\\n" 5023 " L(A) \\\n" 5024 " L(B) \\\n" 5025 " L(C)", 5026 getGoogleStyle())); 5027 5028 // These must not be recognized as macros. 5029 EXPECT_EQ("int q() {\n" 5030 " f(x);\n" 5031 " f(x) {}\n" 5032 " f(x)->g();\n" 5033 " f(x)->*g();\n" 5034 " f(x).g();\n" 5035 " f(x) = x;\n" 5036 " f(x) += x;\n" 5037 " f(x) -= x;\n" 5038 " f(x) *= x;\n" 5039 " f(x) /= x;\n" 5040 " f(x) %= x;\n" 5041 " f(x) &= x;\n" 5042 " f(x) |= x;\n" 5043 " f(x) ^= x;\n" 5044 " f(x) >>= x;\n" 5045 " f(x) <<= x;\n" 5046 " f(x)[y].z();\n" 5047 " LOG(INFO) << x;\n" 5048 " ifstream(x) >> x;\n" 5049 "}\n", 5050 format("int q() {\n" 5051 " f(x)\n;\n" 5052 " f(x)\n {}\n" 5053 " f(x)\n->g();\n" 5054 " f(x)\n->*g();\n" 5055 " f(x)\n.g();\n" 5056 " f(x)\n = x;\n" 5057 " f(x)\n += x;\n" 5058 " f(x)\n -= x;\n" 5059 " f(x)\n *= x;\n" 5060 " f(x)\n /= x;\n" 5061 " f(x)\n %= x;\n" 5062 " f(x)\n &= x;\n" 5063 " f(x)\n |= x;\n" 5064 " f(x)\n ^= x;\n" 5065 " f(x)\n >>= x;\n" 5066 " f(x)\n <<= x;\n" 5067 " f(x)\n[y].z();\n" 5068 " LOG(INFO)\n << x;\n" 5069 " ifstream(x)\n >> x;\n" 5070 "}\n")); 5071 EXPECT_EQ("int q() {\n" 5072 " F(x)\n" 5073 " if (1) {\n" 5074 " }\n" 5075 " F(x)\n" 5076 " while (1) {\n" 5077 " }\n" 5078 " F(x)\n" 5079 " G(x);\n" 5080 " F(x)\n" 5081 " try {\n" 5082 " Q();\n" 5083 " } catch (...) {\n" 5084 " }\n" 5085 "}\n", 5086 format("int q() {\n" 5087 "F(x)\n" 5088 "if (1) {}\n" 5089 "F(x)\n" 5090 "while (1) {}\n" 5091 "F(x)\n" 5092 "G(x);\n" 5093 "F(x)\n" 5094 "try { Q(); } catch (...) {}\n" 5095 "}\n")); 5096 EXPECT_EQ("class A {\n" 5097 " A() : t(0) {}\n" 5098 " A(int i) noexcept() : {}\n" 5099 " A(X x)\n" // FIXME: function-level try blocks are broken. 5100 " try : t(0) {\n" 5101 " } catch (...) {\n" 5102 " }\n" 5103 "};", 5104 format("class A {\n" 5105 " A()\n : t(0) {}\n" 5106 " A(int i)\n noexcept() : {}\n" 5107 " A(X x)\n" 5108 " try : t(0) {} catch (...) {}\n" 5109 "};")); 5110 FormatStyle Style = getLLVMStyle(); 5111 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 5112 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 5113 Style.BraceWrapping.AfterFunction = true; 5114 EXPECT_EQ("void f()\n" 5115 "try\n" 5116 "{\n" 5117 "}", 5118 format("void f() try {\n" 5119 "}", 5120 Style)); 5121 EXPECT_EQ("class SomeClass {\n" 5122 "public:\n" 5123 " SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5124 "};", 5125 format("class SomeClass {\n" 5126 "public:\n" 5127 " SomeClass()\n" 5128 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5129 "};")); 5130 EXPECT_EQ("class SomeClass {\n" 5131 "public:\n" 5132 " SomeClass()\n" 5133 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5134 "};", 5135 format("class SomeClass {\n" 5136 "public:\n" 5137 " SomeClass()\n" 5138 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 5139 "};", 5140 getLLVMStyleWithColumns(40))); 5141 5142 verifyFormat("MACRO(>)"); 5143 5144 // Some macros contain an implicit semicolon. 5145 Style = getLLVMStyle(); 5146 Style.StatementMacros.push_back("FOO"); 5147 verifyFormat("FOO(a) int b = 0;"); 5148 verifyFormat("FOO(a)\n" 5149 "int b = 0;", 5150 Style); 5151 verifyFormat("FOO(a);\n" 5152 "int b = 0;", 5153 Style); 5154 verifyFormat("FOO(argc, argv, \"4.0.2\")\n" 5155 "int b = 0;", 5156 Style); 5157 verifyFormat("FOO()\n" 5158 "int b = 0;", 5159 Style); 5160 verifyFormat("FOO\n" 5161 "int b = 0;", 5162 Style); 5163 verifyFormat("void f() {\n" 5164 " FOO(a)\n" 5165 " return a;\n" 5166 "}", 5167 Style); 5168 verifyFormat("FOO(a)\n" 5169 "FOO(b)", 5170 Style); 5171 verifyFormat("int a = 0;\n" 5172 "FOO(b)\n" 5173 "int c = 0;", 5174 Style); 5175 verifyFormat("int a = 0;\n" 5176 "int x = FOO(a)\n" 5177 "int b = 0;", 5178 Style); 5179 verifyFormat("void foo(int a) { FOO(a) }\n" 5180 "uint32_t bar() {}", 5181 Style); 5182 } 5183 5184 TEST_F(FormatTest, FormatsMacrosWithZeroColumnWidth) { 5185 FormatStyle ZeroColumn = getLLVMStyleWithColumns(0); 5186 5187 verifyFormat("#define A LOOOOOOOOOOOOOOOOOOONG() LOOOOOOOOOOOOOOOOOOONG()", 5188 ZeroColumn); 5189 } 5190 5191 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) { 5192 verifyFormat("#define A \\\n" 5193 " f({ \\\n" 5194 " g(); \\\n" 5195 " });", 5196 getLLVMStyleWithColumns(11)); 5197 } 5198 5199 TEST_F(FormatTest, IndentPreprocessorDirectives) { 5200 FormatStyle Style = getLLVMStyleWithColumns(40); 5201 Style.IndentPPDirectives = FormatStyle::PPDIS_None; 5202 verifyFormat("#ifdef _WIN32\n" 5203 "#define A 0\n" 5204 "#ifdef VAR2\n" 5205 "#define B 1\n" 5206 "#include <someheader.h>\n" 5207 "#define MACRO \\\n" 5208 " some_very_long_func_aaaaaaaaaa();\n" 5209 "#endif\n" 5210 "#else\n" 5211 "#define A 1\n" 5212 "#endif", 5213 Style); 5214 Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash; 5215 verifyFormat("#ifdef _WIN32\n" 5216 "# define A 0\n" 5217 "# ifdef VAR2\n" 5218 "# define B 1\n" 5219 "# include <someheader.h>\n" 5220 "# define MACRO \\\n" 5221 " some_very_long_func_aaaaaaaaaa();\n" 5222 "# endif\n" 5223 "#else\n" 5224 "# define A 1\n" 5225 "#endif", 5226 Style); 5227 verifyFormat("#if A\n" 5228 "# define MACRO \\\n" 5229 " void a(int x) { \\\n" 5230 " b(); \\\n" 5231 " c(); \\\n" 5232 " d(); \\\n" 5233 " e(); \\\n" 5234 " f(); \\\n" 5235 " }\n" 5236 "#endif", 5237 Style); 5238 // Comments before include guard. 5239 verifyFormat("// file comment\n" 5240 "// file comment\n" 5241 "#ifndef HEADER_H\n" 5242 "#define HEADER_H\n" 5243 "code();\n" 5244 "#endif", 5245 Style); 5246 // Test with include guards. 5247 verifyFormat("#ifndef HEADER_H\n" 5248 "#define HEADER_H\n" 5249 "code();\n" 5250 "#endif", 5251 Style); 5252 // Include guards must have a #define with the same variable immediately 5253 // after #ifndef. 5254 verifyFormat("#ifndef NOT_GUARD\n" 5255 "# define FOO\n" 5256 "code();\n" 5257 "#endif", 5258 Style); 5259 5260 // Include guards must cover the entire file. 5261 verifyFormat("code();\n" 5262 "code();\n" 5263 "#ifndef NOT_GUARD\n" 5264 "# define NOT_GUARD\n" 5265 "code();\n" 5266 "#endif", 5267 Style); 5268 verifyFormat("#ifndef NOT_GUARD\n" 5269 "# define NOT_GUARD\n" 5270 "code();\n" 5271 "#endif\n" 5272 "code();", 5273 Style); 5274 // Test with trailing blank lines. 5275 verifyFormat("#ifndef HEADER_H\n" 5276 "#define HEADER_H\n" 5277 "code();\n" 5278 "#endif\n", 5279 Style); 5280 // Include guards don't have #else. 5281 verifyFormat("#ifndef NOT_GUARD\n" 5282 "# define NOT_GUARD\n" 5283 "code();\n" 5284 "#else\n" 5285 "#endif", 5286 Style); 5287 verifyFormat("#ifndef NOT_GUARD\n" 5288 "# define NOT_GUARD\n" 5289 "code();\n" 5290 "#elif FOO\n" 5291 "#endif", 5292 Style); 5293 // Non-identifier #define after potential include guard. 5294 verifyFormat("#ifndef FOO\n" 5295 "# define 1\n" 5296 "#endif\n", 5297 Style); 5298 // #if closes past last non-preprocessor line. 5299 verifyFormat("#ifndef FOO\n" 5300 "#define FOO\n" 5301 "#if 1\n" 5302 "int i;\n" 5303 "# define A 0\n" 5304 "#endif\n" 5305 "#endif\n", 5306 Style); 5307 // Don't crash if there is an #elif directive without a condition. 5308 verifyFormat("#if 1\n" 5309 "int x;\n" 5310 "#elif\n" 5311 "int y;\n" 5312 "#else\n" 5313 "int z;\n" 5314 "#endif", 5315 Style); 5316 // FIXME: This doesn't handle the case where there's code between the 5317 // #ifndef and #define but all other conditions hold. This is because when 5318 // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the 5319 // previous code line yet, so we can't detect it. 5320 EXPECT_EQ("#ifndef NOT_GUARD\n" 5321 "code();\n" 5322 "#define NOT_GUARD\n" 5323 "code();\n" 5324 "#endif", 5325 format("#ifndef NOT_GUARD\n" 5326 "code();\n" 5327 "# define NOT_GUARD\n" 5328 "code();\n" 5329 "#endif", 5330 Style)); 5331 // FIXME: This doesn't handle cases where legitimate preprocessor lines may 5332 // be outside an include guard. Examples are #pragma once and 5333 // #pragma GCC diagnostic, or anything else that does not change the meaning 5334 // of the file if it's included multiple times. 5335 EXPECT_EQ("#ifdef WIN32\n" 5336 "# pragma once\n" 5337 "#endif\n" 5338 "#ifndef HEADER_H\n" 5339 "# define HEADER_H\n" 5340 "code();\n" 5341 "#endif", 5342 format("#ifdef WIN32\n" 5343 "# pragma once\n" 5344 "#endif\n" 5345 "#ifndef HEADER_H\n" 5346 "#define HEADER_H\n" 5347 "code();\n" 5348 "#endif", 5349 Style)); 5350 // FIXME: This does not detect when there is a single non-preprocessor line 5351 // in front of an include-guard-like structure where other conditions hold 5352 // because ScopedLineState hides the line. 5353 EXPECT_EQ("code();\n" 5354 "#ifndef HEADER_H\n" 5355 "#define HEADER_H\n" 5356 "code();\n" 5357 "#endif", 5358 format("code();\n" 5359 "#ifndef HEADER_H\n" 5360 "# define HEADER_H\n" 5361 "code();\n" 5362 "#endif", 5363 Style)); 5364 // Keep comments aligned with #, otherwise indent comments normally. These 5365 // tests cannot use verifyFormat because messUp manipulates leading 5366 // whitespace. 5367 { 5368 const char *Expected = "" 5369 "void f() {\n" 5370 "#if 1\n" 5371 "// Preprocessor aligned.\n" 5372 "# define A 0\n" 5373 " // Code. Separated by blank line.\n" 5374 "\n" 5375 "# define B 0\n" 5376 " // Code. Not aligned with #\n" 5377 "# define C 0\n" 5378 "#endif"; 5379 const char *ToFormat = "" 5380 "void f() {\n" 5381 "#if 1\n" 5382 "// Preprocessor aligned.\n" 5383 "# define A 0\n" 5384 "// Code. Separated by blank line.\n" 5385 "\n" 5386 "# define B 0\n" 5387 " // Code. Not aligned with #\n" 5388 "# define C 0\n" 5389 "#endif"; 5390 EXPECT_EQ(Expected, format(ToFormat, Style)); 5391 EXPECT_EQ(Expected, format(Expected, Style)); 5392 } 5393 // Keep block quotes aligned. 5394 { 5395 const char *Expected = "" 5396 "void f() {\n" 5397 "#if 1\n" 5398 "/* Preprocessor aligned. */\n" 5399 "# define A 0\n" 5400 " /* Code. Separated by blank line. */\n" 5401 "\n" 5402 "# define B 0\n" 5403 " /* Code. Not aligned with # */\n" 5404 "# define C 0\n" 5405 "#endif"; 5406 const char *ToFormat = "" 5407 "void f() {\n" 5408 "#if 1\n" 5409 "/* Preprocessor aligned. */\n" 5410 "# define A 0\n" 5411 "/* Code. Separated by blank line. */\n" 5412 "\n" 5413 "# define B 0\n" 5414 " /* Code. Not aligned with # */\n" 5415 "# define C 0\n" 5416 "#endif"; 5417 EXPECT_EQ(Expected, format(ToFormat, Style)); 5418 EXPECT_EQ(Expected, format(Expected, Style)); 5419 } 5420 // Keep comments aligned with un-indented directives. 5421 { 5422 const char *Expected = "" 5423 "void f() {\n" 5424 "// Preprocessor aligned.\n" 5425 "#define A 0\n" 5426 " // Code. Separated by blank line.\n" 5427 "\n" 5428 "#define B 0\n" 5429 " // Code. Not aligned with #\n" 5430 "#define C 0\n"; 5431 const char *ToFormat = "" 5432 "void f() {\n" 5433 "// Preprocessor aligned.\n" 5434 "#define A 0\n" 5435 "// Code. Separated by blank line.\n" 5436 "\n" 5437 "#define B 0\n" 5438 " // Code. Not aligned with #\n" 5439 "#define C 0\n"; 5440 EXPECT_EQ(Expected, format(ToFormat, Style)); 5441 EXPECT_EQ(Expected, format(Expected, Style)); 5442 } 5443 // Test AfterHash with tabs. 5444 { 5445 FormatStyle Tabbed = Style; 5446 Tabbed.UseTab = FormatStyle::UT_Always; 5447 Tabbed.IndentWidth = 8; 5448 Tabbed.TabWidth = 8; 5449 verifyFormat("#ifdef _WIN32\n" 5450 "#\tdefine A 0\n" 5451 "#\tifdef VAR2\n" 5452 "#\t\tdefine B 1\n" 5453 "#\t\tinclude <someheader.h>\n" 5454 "#\t\tdefine MACRO \\\n" 5455 "\t\t\tsome_very_long_func_aaaaaaaaaa();\n" 5456 "#\tendif\n" 5457 "#else\n" 5458 "#\tdefine A 1\n" 5459 "#endif", 5460 Tabbed); 5461 } 5462 5463 // Regression test: Multiline-macro inside include guards. 5464 verifyFormat("#ifndef HEADER_H\n" 5465 "#define HEADER_H\n" 5466 "#define A() \\\n" 5467 " int i; \\\n" 5468 " int j;\n" 5469 "#endif // HEADER_H", 5470 getLLVMStyleWithColumns(20)); 5471 5472 Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash; 5473 // Basic before hash indent tests 5474 verifyFormat("#ifdef _WIN32\n" 5475 " #define A 0\n" 5476 " #ifdef VAR2\n" 5477 " #define B 1\n" 5478 " #include <someheader.h>\n" 5479 " #define MACRO \\\n" 5480 " some_very_long_func_aaaaaaaaaa();\n" 5481 " #endif\n" 5482 "#else\n" 5483 " #define A 1\n" 5484 "#endif", 5485 Style); 5486 verifyFormat("#if A\n" 5487 " #define MACRO \\\n" 5488 " void a(int x) { \\\n" 5489 " b(); \\\n" 5490 " c(); \\\n" 5491 " d(); \\\n" 5492 " e(); \\\n" 5493 " f(); \\\n" 5494 " }\n" 5495 "#endif", 5496 Style); 5497 // Keep comments aligned with indented directives. These 5498 // tests cannot use verifyFormat because messUp manipulates leading 5499 // whitespace. 5500 { 5501 const char *Expected = "void f() {\n" 5502 "// Aligned to preprocessor.\n" 5503 "#if 1\n" 5504 " // Aligned to code.\n" 5505 " int a;\n" 5506 " #if 1\n" 5507 " // Aligned to preprocessor.\n" 5508 " #define A 0\n" 5509 " // Aligned to code.\n" 5510 " int b;\n" 5511 " #endif\n" 5512 "#endif\n" 5513 "}"; 5514 const char *ToFormat = "void f() {\n" 5515 "// Aligned to preprocessor.\n" 5516 "#if 1\n" 5517 "// Aligned to code.\n" 5518 "int a;\n" 5519 "#if 1\n" 5520 "// Aligned to preprocessor.\n" 5521 "#define A 0\n" 5522 "// Aligned to code.\n" 5523 "int b;\n" 5524 "#endif\n" 5525 "#endif\n" 5526 "}"; 5527 EXPECT_EQ(Expected, format(ToFormat, Style)); 5528 EXPECT_EQ(Expected, format(Expected, Style)); 5529 } 5530 { 5531 const char *Expected = "void f() {\n" 5532 "/* Aligned to preprocessor. */\n" 5533 "#if 1\n" 5534 " /* Aligned to code. */\n" 5535 " int a;\n" 5536 " #if 1\n" 5537 " /* Aligned to preprocessor. */\n" 5538 " #define A 0\n" 5539 " /* Aligned to code. */\n" 5540 " int b;\n" 5541 " #endif\n" 5542 "#endif\n" 5543 "}"; 5544 const char *ToFormat = "void f() {\n" 5545 "/* Aligned to preprocessor. */\n" 5546 "#if 1\n" 5547 "/* Aligned to code. */\n" 5548 "int a;\n" 5549 "#if 1\n" 5550 "/* Aligned to preprocessor. */\n" 5551 "#define A 0\n" 5552 "/* Aligned to code. */\n" 5553 "int b;\n" 5554 "#endif\n" 5555 "#endif\n" 5556 "}"; 5557 EXPECT_EQ(Expected, format(ToFormat, Style)); 5558 EXPECT_EQ(Expected, format(Expected, Style)); 5559 } 5560 5561 // Test single comment before preprocessor 5562 verifyFormat("// Comment\n" 5563 "\n" 5564 "#if 1\n" 5565 "#endif", 5566 Style); 5567 } 5568 5569 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) { 5570 verifyFormat("{\n { a #c; }\n}"); 5571 } 5572 5573 TEST_F(FormatTest, FormatUnbalancedStructuralElements) { 5574 EXPECT_EQ("#define A \\\n { \\\n {\nint i;", 5575 format("#define A { {\nint i;", getLLVMStyleWithColumns(11))); 5576 EXPECT_EQ("#define A \\\n } \\\n }\nint i;", 5577 format("#define A } }\nint i;", getLLVMStyleWithColumns(11))); 5578 } 5579 5580 TEST_F(FormatTest, EscapedNewlines) { 5581 FormatStyle Narrow = getLLVMStyleWithColumns(11); 5582 EXPECT_EQ("#define A \\\n int i; \\\n int j;", 5583 format("#define A \\\nint i;\\\n int j;", Narrow)); 5584 EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;")); 5585 EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();")); 5586 EXPECT_EQ("/* \\ \\ \\\n */", format("\\\n/* \\ \\ \\\n */")); 5587 EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>")); 5588 5589 FormatStyle AlignLeft = getLLVMStyle(); 5590 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left; 5591 EXPECT_EQ("#define MACRO(x) \\\n" 5592 "private: \\\n" 5593 " int x(int a);\n", 5594 format("#define MACRO(x) \\\n" 5595 "private: \\\n" 5596 " int x(int a);\n", 5597 AlignLeft)); 5598 5599 // CRLF line endings 5600 EXPECT_EQ("#define A \\\r\n int i; \\\r\n int j;", 5601 format("#define A \\\r\nint i;\\\r\n int j;", Narrow)); 5602 EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;")); 5603 EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();")); 5604 EXPECT_EQ("/* \\ \\ \\\r\n */", format("\\\r\n/* \\ \\ \\\r\n */")); 5605 EXPECT_EQ("<a\r\n\\\\\r\n>", format("<a\r\n\\\\\r\n>")); 5606 EXPECT_EQ("#define MACRO(x) \\\r\n" 5607 "private: \\\r\n" 5608 " int x(int a);\r\n", 5609 format("#define MACRO(x) \\\r\n" 5610 "private: \\\r\n" 5611 " int x(int a);\r\n", 5612 AlignLeft)); 5613 5614 FormatStyle DontAlign = getLLVMStyle(); 5615 DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 5616 DontAlign.MaxEmptyLinesToKeep = 3; 5617 // FIXME: can't use verifyFormat here because the newline before 5618 // "public:" is not inserted the first time it's reformatted 5619 EXPECT_EQ("#define A \\\n" 5620 " class Foo { \\\n" 5621 " void bar(); \\\n" 5622 "\\\n" 5623 "\\\n" 5624 "\\\n" 5625 " public: \\\n" 5626 " void baz(); \\\n" 5627 " };", 5628 format("#define A \\\n" 5629 " class Foo { \\\n" 5630 " void bar(); \\\n" 5631 "\\\n" 5632 "\\\n" 5633 "\\\n" 5634 " public: \\\n" 5635 " void baz(); \\\n" 5636 " };", 5637 DontAlign)); 5638 } 5639 5640 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) { 5641 verifyFormat("#define A \\\n" 5642 " int v( \\\n" 5643 " a); \\\n" 5644 " int i;", 5645 getLLVMStyleWithColumns(11)); 5646 } 5647 5648 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) { 5649 EXPECT_EQ( 5650 "#define ALooooooooooooooooooooooooooooooooooooooongMacro(" 5651 " \\\n" 5652 " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n" 5653 "\n" 5654 "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n" 5655 " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n", 5656 format(" #define ALooooooooooooooooooooooooooooooooooooooongMacro(" 5657 "\\\n" 5658 "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n" 5659 " \n" 5660 " AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n" 5661 " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n")); 5662 } 5663 5664 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) { 5665 EXPECT_EQ("int\n" 5666 "#define A\n" 5667 " a;", 5668 format("int\n#define A\na;")); 5669 verifyFormat("functionCallTo(\n" 5670 " someOtherFunction(\n" 5671 " withSomeParameters, whichInSequence,\n" 5672 " areLongerThanALine(andAnotherCall,\n" 5673 "#define A B\n" 5674 " withMoreParamters,\n" 5675 " whichStronglyInfluenceTheLayout),\n" 5676 " andMoreParameters),\n" 5677 " trailing);", 5678 getLLVMStyleWithColumns(69)); 5679 verifyFormat("Foo::Foo()\n" 5680 "#ifdef BAR\n" 5681 " : baz(0)\n" 5682 "#endif\n" 5683 "{\n" 5684 "}"); 5685 verifyFormat("void f() {\n" 5686 " if (true)\n" 5687 "#ifdef A\n" 5688 " f(42);\n" 5689 " x();\n" 5690 "#else\n" 5691 " g();\n" 5692 " x();\n" 5693 "#endif\n" 5694 "}"); 5695 verifyFormat("void f(param1, param2,\n" 5696 " param3,\n" 5697 "#ifdef A\n" 5698 " param4(param5,\n" 5699 "#ifdef A1\n" 5700 " param6,\n" 5701 "#ifdef A2\n" 5702 " param7),\n" 5703 "#else\n" 5704 " param8),\n" 5705 " param9,\n" 5706 "#endif\n" 5707 " param10,\n" 5708 "#endif\n" 5709 " param11)\n" 5710 "#else\n" 5711 " param12)\n" 5712 "#endif\n" 5713 "{\n" 5714 " x();\n" 5715 "}", 5716 getLLVMStyleWithColumns(28)); 5717 verifyFormat("#if 1\n" 5718 "int i;"); 5719 verifyFormat("#if 1\n" 5720 "#endif\n" 5721 "#if 1\n" 5722 "#else\n" 5723 "#endif\n"); 5724 verifyFormat("DEBUG({\n" 5725 " return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5726 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n" 5727 "});\n" 5728 "#if a\n" 5729 "#else\n" 5730 "#endif"); 5731 5732 verifyIncompleteFormat("void f(\n" 5733 "#if A\n" 5734 ");\n" 5735 "#else\n" 5736 "#endif"); 5737 } 5738 5739 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) { 5740 verifyFormat("#endif\n" 5741 "#if B"); 5742 } 5743 5744 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) { 5745 FormatStyle SingleLine = getLLVMStyle(); 5746 SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse; 5747 verifyFormat("#if 0\n" 5748 "#elif 1\n" 5749 "#endif\n" 5750 "void foo() {\n" 5751 " if (test) foo2();\n" 5752 "}", 5753 SingleLine); 5754 } 5755 5756 TEST_F(FormatTest, LayoutBlockInsideParens) { 5757 verifyFormat("functionCall({ int i; });"); 5758 verifyFormat("functionCall({\n" 5759 " int i;\n" 5760 " int j;\n" 5761 "});"); 5762 verifyFormat("functionCall(\n" 5763 " {\n" 5764 " int i;\n" 5765 " int j;\n" 5766 " },\n" 5767 " aaaa, bbbb, cccc);"); 5768 verifyFormat("functionA(functionB({\n" 5769 " int i;\n" 5770 " int j;\n" 5771 " }),\n" 5772 " aaaa, bbbb, cccc);"); 5773 verifyFormat("functionCall(\n" 5774 " {\n" 5775 " int i;\n" 5776 " int j;\n" 5777 " },\n" 5778 " aaaa, bbbb, // comment\n" 5779 " cccc);"); 5780 verifyFormat("functionA(functionB({\n" 5781 " int i;\n" 5782 " int j;\n" 5783 " }),\n" 5784 " aaaa, bbbb, // comment\n" 5785 " cccc);"); 5786 verifyFormat("functionCall(aaaa, bbbb, { int i; });"); 5787 verifyFormat("functionCall(aaaa, bbbb, {\n" 5788 " int i;\n" 5789 " int j;\n" 5790 "});"); 5791 verifyFormat( 5792 "Aaa(\n" // FIXME: There shouldn't be a linebreak here. 5793 " {\n" 5794 " int i; // break\n" 5795 " },\n" 5796 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 5797 " ccccccccccccccccc));"); 5798 verifyFormat("DEBUG({\n" 5799 " if (a)\n" 5800 " f();\n" 5801 "});"); 5802 } 5803 5804 TEST_F(FormatTest, LayoutBlockInsideStatement) { 5805 EXPECT_EQ("SOME_MACRO { int i; }\n" 5806 "int i;", 5807 format(" SOME_MACRO {int i;} int i;")); 5808 } 5809 5810 TEST_F(FormatTest, LayoutNestedBlocks) { 5811 verifyFormat("void AddOsStrings(unsigned bitmask) {\n" 5812 " struct s {\n" 5813 " int i;\n" 5814 " };\n" 5815 " s kBitsToOs[] = {{10}};\n" 5816 " for (int i = 0; i < 10; ++i)\n" 5817 " return;\n" 5818 "}"); 5819 verifyFormat("call(parameter, {\n" 5820 " something();\n" 5821 " // Comment using all columns.\n" 5822 " somethingelse();\n" 5823 "});", 5824 getLLVMStyleWithColumns(40)); 5825 verifyFormat("DEBUG( //\n" 5826 " { f(); }, a);"); 5827 verifyFormat("DEBUG( //\n" 5828 " {\n" 5829 " f(); //\n" 5830 " },\n" 5831 " a);"); 5832 5833 EXPECT_EQ("call(parameter, {\n" 5834 " something();\n" 5835 " // Comment too\n" 5836 " // looooooooooong.\n" 5837 " somethingElse();\n" 5838 "});", 5839 format("call(parameter, {\n" 5840 " something();\n" 5841 " // Comment too looooooooooong.\n" 5842 " somethingElse();\n" 5843 "});", 5844 getLLVMStyleWithColumns(29))); 5845 EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int i; });")); 5846 EXPECT_EQ("DEBUG({ // comment\n" 5847 " int i;\n" 5848 "});", 5849 format("DEBUG({ // comment\n" 5850 "int i;\n" 5851 "});")); 5852 EXPECT_EQ("DEBUG({\n" 5853 " int i;\n" 5854 "\n" 5855 " // comment\n" 5856 " int j;\n" 5857 "});", 5858 format("DEBUG({\n" 5859 " int i;\n" 5860 "\n" 5861 " // comment\n" 5862 " int j;\n" 5863 "});")); 5864 5865 verifyFormat("DEBUG({\n" 5866 " if (a)\n" 5867 " return;\n" 5868 "});"); 5869 verifyGoogleFormat("DEBUG({\n" 5870 " if (a) return;\n" 5871 "});"); 5872 FormatStyle Style = getGoogleStyle(); 5873 Style.ColumnLimit = 45; 5874 verifyFormat("Debug(\n" 5875 " aaaaa,\n" 5876 " {\n" 5877 " if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n" 5878 " },\n" 5879 " a);", 5880 Style); 5881 5882 verifyFormat("SomeFunction({MACRO({ return output; }), b});"); 5883 5884 verifyNoCrash("^{v^{a}}"); 5885 } 5886 5887 TEST_F(FormatTest, FormatNestedBlocksInMacros) { 5888 EXPECT_EQ("#define MACRO() \\\n" 5889 " Debug(aaa, /* force line break */ \\\n" 5890 " { \\\n" 5891 " int i; \\\n" 5892 " int j; \\\n" 5893 " })", 5894 format("#define MACRO() Debug(aaa, /* force line break */ \\\n" 5895 " { int i; int j; })", 5896 getGoogleStyle())); 5897 5898 EXPECT_EQ("#define A \\\n" 5899 " [] { \\\n" 5900 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 5901 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n" 5902 " }", 5903 format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 5904 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }", 5905 getGoogleStyle())); 5906 } 5907 5908 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) { 5909 EXPECT_EQ("{}", format("{}")); 5910 verifyFormat("enum E {};"); 5911 verifyFormat("enum E {}"); 5912 FormatStyle Style = getLLVMStyle(); 5913 Style.SpaceInEmptyBlock = true; 5914 EXPECT_EQ("void f() { }", format("void f() {}", Style)); 5915 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 5916 EXPECT_EQ("while (true) { }", format("while (true) {}", Style)); 5917 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 5918 Style.BraceWrapping.BeforeElse = false; 5919 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 5920 verifyFormat("if (a)\n" 5921 "{\n" 5922 "} else if (b)\n" 5923 "{\n" 5924 "} else\n" 5925 "{ }", 5926 Style); 5927 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never; 5928 verifyFormat("if (a) {\n" 5929 "} else if (b) {\n" 5930 "} else {\n" 5931 "}", 5932 Style); 5933 Style.BraceWrapping.BeforeElse = true; 5934 verifyFormat("if (a) { }\n" 5935 "else if (b) { }\n" 5936 "else { }", 5937 Style); 5938 } 5939 5940 TEST_F(FormatTest, FormatBeginBlockEndMacros) { 5941 FormatStyle Style = getLLVMStyle(); 5942 Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$"; 5943 Style.MacroBlockEnd = "^[A-Z_]+_END$"; 5944 verifyFormat("FOO_BEGIN\n" 5945 " FOO_ENTRY\n" 5946 "FOO_END", 5947 Style); 5948 verifyFormat("FOO_BEGIN\n" 5949 " NESTED_FOO_BEGIN\n" 5950 " NESTED_FOO_ENTRY\n" 5951 " NESTED_FOO_END\n" 5952 "FOO_END", 5953 Style); 5954 verifyFormat("FOO_BEGIN(Foo, Bar)\n" 5955 " int x;\n" 5956 " x = 1;\n" 5957 "FOO_END(Baz)", 5958 Style); 5959 } 5960 5961 //===----------------------------------------------------------------------===// 5962 // Line break tests. 5963 //===----------------------------------------------------------------------===// 5964 5965 TEST_F(FormatTest, PreventConfusingIndents) { 5966 verifyFormat( 5967 "void f() {\n" 5968 " SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n" 5969 " parameter, parameter, parameter)),\n" 5970 " SecondLongCall(parameter));\n" 5971 "}"); 5972 verifyFormat( 5973 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5974 " aaaaaaaaaaaaaaaaaaaaaaaa(\n" 5975 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 5976 " aaaaaaaaaaaaaaaaaaaaaaaa);"); 5977 verifyFormat( 5978 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5979 " [aaaaaaaaaaaaaaaaaaaaaaaa\n" 5980 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n" 5981 " [aaaaaaaaaaaaaaaaaaaaaaaa]];"); 5982 verifyFormat( 5983 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 5984 " aaaaaaaaaaaaaaaaaaaaaaaa<\n" 5985 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n" 5986 " aaaaaaaaaaaaaaaaaaaaaaaa>;"); 5987 verifyFormat("int a = bbbb && ccc &&\n" 5988 " fffff(\n" 5989 "#define A Just forcing a new line\n" 5990 " ddd);"); 5991 } 5992 5993 TEST_F(FormatTest, LineBreakingInBinaryExpressions) { 5994 verifyFormat( 5995 "bool aaaaaaa =\n" 5996 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n" 5997 " bbbbbbbb();"); 5998 verifyFormat( 5999 "bool aaaaaaa =\n" 6000 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n" 6001 " bbbbbbbb();"); 6002 6003 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n" 6004 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n" 6005 " ccccccccc == ddddddddddd;"); 6006 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n" 6007 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n" 6008 " ccccccccc == ddddddddddd;"); 6009 verifyFormat( 6010 "bool aaaaaaaaaaaaaaaaaaaaa =\n" 6011 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n" 6012 " ccccccccc == ddddddddddd;"); 6013 6014 verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n" 6015 " aaaaaa) &&\n" 6016 " bbbbbb && cccccc;"); 6017 verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n" 6018 " aaaaaa) >>\n" 6019 " bbbbbb;"); 6020 verifyFormat("aa = Whitespaces.addUntouchableComment(\n" 6021 " SourceMgr.getSpellingColumnNumber(\n" 6022 " TheLine.Last->FormatTok.Tok.getLocation()) -\n" 6023 " 1);"); 6024 6025 verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6026 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n" 6027 " cccccc) {\n}"); 6028 verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6029 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n" 6030 " cccccc) {\n}"); 6031 verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6032 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n" 6033 " cccccc) {\n}"); 6034 verifyFormat("b = a &&\n" 6035 " // Comment\n" 6036 " b.c && d;"); 6037 6038 // If the LHS of a comparison is not a binary expression itself, the 6039 // additional linebreak confuses many people. 6040 verifyFormat( 6041 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6042 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n" 6043 "}"); 6044 verifyFormat( 6045 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6046 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 6047 "}"); 6048 verifyFormat( 6049 "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n" 6050 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 6051 "}"); 6052 verifyFormat( 6053 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6054 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n" 6055 "}"); 6056 // Even explicit parentheses stress the precedence enough to make the 6057 // additional break unnecessary. 6058 verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6059 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 6060 "}"); 6061 // This cases is borderline, but with the indentation it is still readable. 6062 verifyFormat( 6063 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6064 " aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6065 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 6066 "}", 6067 getLLVMStyleWithColumns(75)); 6068 6069 // If the LHS is a binary expression, we should still use the additional break 6070 // as otherwise the formatting hides the operator precedence. 6071 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6072 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6073 " 5) {\n" 6074 "}"); 6075 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6076 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n" 6077 " 5) {\n" 6078 "}"); 6079 6080 FormatStyle OnePerLine = getLLVMStyle(); 6081 OnePerLine.BinPackParameters = false; 6082 verifyFormat( 6083 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6084 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 6085 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}", 6086 OnePerLine); 6087 6088 verifyFormat("int i = someFunction(aaaaaaa, 0)\n" 6089 " .aaa(aaaaaaaaaaaaa) *\n" 6090 " aaaaaaa +\n" 6091 " aaaaaaa;", 6092 getLLVMStyleWithColumns(40)); 6093 } 6094 6095 TEST_F(FormatTest, ExpressionIndentation) { 6096 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6097 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6098 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6099 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6100 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n" 6101 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n" 6102 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6103 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n" 6104 " ccccccccccccccccccccccccccccccccccccccccc;"); 6105 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6106 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6107 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6108 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 6109 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6110 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6111 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6112 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 6113 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 6114 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 6115 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6116 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 6117 verifyFormat("if () {\n" 6118 "} else if (aaaaa && bbbbb > // break\n" 6119 " ccccc) {\n" 6120 "}"); 6121 verifyFormat("if () {\n" 6122 "} else if constexpr (aaaaa && bbbbb > // break\n" 6123 " ccccc) {\n" 6124 "}"); 6125 verifyFormat("if () {\n" 6126 "} else if CONSTEXPR (aaaaa && bbbbb > // break\n" 6127 " ccccc) {\n" 6128 "}"); 6129 verifyFormat("if () {\n" 6130 "} else if (aaaaa &&\n" 6131 " bbbbb > // break\n" 6132 " ccccc &&\n" 6133 " ddddd) {\n" 6134 "}"); 6135 6136 // Presence of a trailing comment used to change indentation of b. 6137 verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n" 6138 " b;\n" 6139 "return aaaaaaaaaaaaaaaaaaa +\n" 6140 " b; //", 6141 getLLVMStyleWithColumns(30)); 6142 } 6143 6144 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) { 6145 // Not sure what the best system is here. Like this, the LHS can be found 6146 // immediately above an operator (everything with the same or a higher 6147 // indent). The RHS is aligned right of the operator and so compasses 6148 // everything until something with the same indent as the operator is found. 6149 // FIXME: Is this a good system? 6150 FormatStyle Style = getLLVMStyle(); 6151 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 6152 verifyFormat( 6153 "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6154 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6155 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6156 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6157 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6158 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6159 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6160 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6161 " > ccccccccccccccccccccccccccccccccccccccccc;", 6162 Style); 6163 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6164 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6165 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6166 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6167 Style); 6168 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6169 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6170 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6171 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6172 Style); 6173 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6174 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6175 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6176 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6177 Style); 6178 verifyFormat("if () {\n" 6179 "} else if (aaaaa\n" 6180 " && bbbbb // break\n" 6181 " > ccccc) {\n" 6182 "}", 6183 Style); 6184 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6185 " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6186 Style); 6187 verifyFormat("return (a)\n" 6188 " // comment\n" 6189 " + b;", 6190 Style); 6191 verifyFormat( 6192 "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6193 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6194 " + cc;", 6195 Style); 6196 6197 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6198 " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 6199 Style); 6200 6201 // Forced by comments. 6202 verifyFormat( 6203 "unsigned ContentSize =\n" 6204 " sizeof(int16_t) // DWARF ARange version number\n" 6205 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6206 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6207 " + sizeof(int8_t); // Segment Size (in bytes)"); 6208 6209 verifyFormat("return boost::fusion::at_c<0>(iiii).second\n" 6210 " == boost::fusion::at_c<1>(iiii).second;", 6211 Style); 6212 6213 Style.ColumnLimit = 60; 6214 verifyFormat("zzzzzzzzzz\n" 6215 " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6216 " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);", 6217 Style); 6218 6219 Style.ColumnLimit = 80; 6220 Style.IndentWidth = 4; 6221 Style.TabWidth = 4; 6222 Style.UseTab = FormatStyle::UT_Always; 6223 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6224 Style.AlignOperands = FormatStyle::OAS_DontAlign; 6225 EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n" 6226 "\t&& (someOtherLongishConditionPart1\n" 6227 "\t\t|| someOtherEvenLongerNestedConditionPart2);", 6228 format("return someVeryVeryLongConditionThatBarelyFitsOnALine && " 6229 "(someOtherLongishConditionPart1 || " 6230 "someOtherEvenLongerNestedConditionPart2);", 6231 Style)); 6232 } 6233 6234 TEST_F(FormatTest, ExpressionIndentationStrictAlign) { 6235 FormatStyle Style = getLLVMStyle(); 6236 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 6237 Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator; 6238 6239 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6240 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6241 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6242 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6243 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6244 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6245 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6246 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6247 " > ccccccccccccccccccccccccccccccccccccccccc;", 6248 Style); 6249 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6250 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6251 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6252 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6253 Style); 6254 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6255 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6256 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6257 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6258 Style); 6259 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6260 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6261 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6262 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 6263 Style); 6264 verifyFormat("if () {\n" 6265 "} else if (aaaaa\n" 6266 " && bbbbb // break\n" 6267 " > ccccc) {\n" 6268 "}", 6269 Style); 6270 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6271 " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6272 Style); 6273 verifyFormat("return (a)\n" 6274 " // comment\n" 6275 " + b;", 6276 Style); 6277 verifyFormat( 6278 "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6279 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6280 " + cc;", 6281 Style); 6282 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 6283 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 6284 " : 3333333333333333;", 6285 Style); 6286 verifyFormat( 6287 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 6288 " : ccccccccccccccc ? dddddddddddddddddd\n" 6289 " : eeeeeeeeeeeeeeeeee)\n" 6290 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 6291 " : 3333333333333333;", 6292 Style); 6293 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6294 " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 6295 Style); 6296 6297 verifyFormat("return boost::fusion::at_c<0>(iiii).second\n" 6298 " == boost::fusion::at_c<1>(iiii).second;", 6299 Style); 6300 6301 Style.ColumnLimit = 60; 6302 verifyFormat("zzzzzzzzzzzzz\n" 6303 " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6304 " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);", 6305 Style); 6306 6307 // Forced by comments. 6308 Style.ColumnLimit = 80; 6309 verifyFormat( 6310 "unsigned ContentSize\n" 6311 " = sizeof(int16_t) // DWARF ARange version number\n" 6312 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6313 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6314 " + sizeof(int8_t); // Segment Size (in bytes)", 6315 Style); 6316 6317 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6318 verifyFormat( 6319 "unsigned ContentSize =\n" 6320 " sizeof(int16_t) // DWARF ARange version number\n" 6321 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6322 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6323 " + sizeof(int8_t); // Segment Size (in bytes)", 6324 Style); 6325 6326 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 6327 verifyFormat( 6328 "unsigned ContentSize =\n" 6329 " sizeof(int16_t) // DWARF ARange version number\n" 6330 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 6331 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 6332 " + sizeof(int8_t); // Segment Size (in bytes)", 6333 Style); 6334 } 6335 6336 TEST_F(FormatTest, EnforcedOperatorWraps) { 6337 // Here we'd like to wrap after the || operators, but a comment is forcing an 6338 // earlier wrap. 6339 verifyFormat("bool x = aaaaa //\n" 6340 " || bbbbb\n" 6341 " //\n" 6342 " || cccc;"); 6343 } 6344 6345 TEST_F(FormatTest, NoOperandAlignment) { 6346 FormatStyle Style = getLLVMStyle(); 6347 Style.AlignOperands = FormatStyle::OAS_DontAlign; 6348 verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n" 6349 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 6350 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 6351 Style); 6352 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6353 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6354 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6355 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6356 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6357 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6358 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6359 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6360 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6361 " > ccccccccccccccccccccccccccccccccccccccccc;", 6362 Style); 6363 6364 verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6365 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6366 " + cc;", 6367 Style); 6368 verifyFormat("int a = aa\n" 6369 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 6370 " * cccccccccccccccccccccccccccccccccccc;\n", 6371 Style); 6372 6373 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6374 verifyFormat("return (a > b\n" 6375 " // comment1\n" 6376 " // comment2\n" 6377 " || c);", 6378 Style); 6379 } 6380 6381 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) { 6382 FormatStyle Style = getLLVMStyle(); 6383 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6384 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 6385 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6386 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 6387 Style); 6388 } 6389 6390 TEST_F(FormatTest, AllowBinPackingInsideArguments) { 6391 FormatStyle Style = getLLVMStyleWithColumns(40); 6392 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6393 Style.BinPackArguments = false; 6394 verifyFormat("void test() {\n" 6395 " someFunction(\n" 6396 " this + argument + is + quite\n" 6397 " + long + so + it + gets + wrapped\n" 6398 " + but + remains + bin - packed);\n" 6399 "}", 6400 Style); 6401 verifyFormat("void test() {\n" 6402 " someFunction(arg1,\n" 6403 " this + argument + is\n" 6404 " + quite + long + so\n" 6405 " + it + gets + wrapped\n" 6406 " + but + remains + bin\n" 6407 " - packed,\n" 6408 " arg3);\n" 6409 "}", 6410 Style); 6411 verifyFormat("void test() {\n" 6412 " someFunction(\n" 6413 " arg1,\n" 6414 " this + argument + has\n" 6415 " + anotherFunc(nested,\n" 6416 " calls + whose\n" 6417 " + arguments\n" 6418 " + are + also\n" 6419 " + wrapped,\n" 6420 " in + addition)\n" 6421 " + to + being + bin - packed,\n" 6422 " arg3);\n" 6423 "}", 6424 Style); 6425 6426 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 6427 verifyFormat("void test() {\n" 6428 " someFunction(\n" 6429 " arg1,\n" 6430 " this + argument + has +\n" 6431 " anotherFunc(nested,\n" 6432 " calls + whose +\n" 6433 " arguments +\n" 6434 " are + also +\n" 6435 " wrapped,\n" 6436 " in + addition) +\n" 6437 " to + being + bin - packed,\n" 6438 " arg3);\n" 6439 "}", 6440 Style); 6441 } 6442 6443 TEST_F(FormatTest, BreakBinaryOperatorsInPresenceOfTemplates) { 6444 auto Style = getLLVMStyleWithColumns(45); 6445 EXPECT_EQ(Style.BreakBeforeBinaryOperators, FormatStyle::BOS_None); 6446 verifyFormat("bool b =\n" 6447 " is_default_constructible_v<hash<T>> and\n" 6448 " is_copy_constructible_v<hash<T>> and\n" 6449 " is_move_constructible_v<hash<T>> and\n" 6450 " is_copy_assignable_v<hash<T>> and\n" 6451 " is_move_assignable_v<hash<T>> and\n" 6452 " is_destructible_v<hash<T>> and\n" 6453 " is_swappable_v<hash<T>> and\n" 6454 " is_callable_v<hash<T>(T)>;", 6455 Style); 6456 6457 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 6458 verifyFormat("bool b = is_default_constructible_v<hash<T>>\n" 6459 " and is_copy_constructible_v<hash<T>>\n" 6460 " and is_move_constructible_v<hash<T>>\n" 6461 " and is_copy_assignable_v<hash<T>>\n" 6462 " and is_move_assignable_v<hash<T>>\n" 6463 " and is_destructible_v<hash<T>>\n" 6464 " and is_swappable_v<hash<T>>\n" 6465 " and is_callable_v<hash<T>(T)>;", 6466 Style); 6467 6468 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 6469 verifyFormat("bool b = is_default_constructible_v<hash<T>>\n" 6470 " and is_copy_constructible_v<hash<T>>\n" 6471 " and is_move_constructible_v<hash<T>>\n" 6472 " and is_copy_assignable_v<hash<T>>\n" 6473 " and is_move_assignable_v<hash<T>>\n" 6474 " and is_destructible_v<hash<T>>\n" 6475 " and is_swappable_v<hash<T>>\n" 6476 " and is_callable_v<hash<T>(T)>;", 6477 Style); 6478 } 6479 6480 TEST_F(FormatTest, ConstructorInitializers) { 6481 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}"); 6482 verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}", 6483 getLLVMStyleWithColumns(45)); 6484 verifyFormat("Constructor()\n" 6485 " : Inttializer(FitsOnTheLine) {}", 6486 getLLVMStyleWithColumns(44)); 6487 verifyFormat("Constructor()\n" 6488 " : Inttializer(FitsOnTheLine) {}", 6489 getLLVMStyleWithColumns(43)); 6490 6491 verifyFormat("template <typename T>\n" 6492 "Constructor() : Initializer(FitsOnTheLine) {}", 6493 getLLVMStyleWithColumns(45)); 6494 6495 verifyFormat( 6496 "SomeClass::Constructor()\n" 6497 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}"); 6498 6499 verifyFormat( 6500 "SomeClass::Constructor()\n" 6501 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6502 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}"); 6503 verifyFormat( 6504 "SomeClass::Constructor()\n" 6505 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6506 " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}"); 6507 verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6508 " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 6509 " : aaaaaaaaaa(aaaaaa) {}"); 6510 6511 verifyFormat("Constructor()\n" 6512 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6513 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6514 " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6515 " aaaaaaaaaaaaaaaaaaaaaaa() {}"); 6516 6517 verifyFormat("Constructor()\n" 6518 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6519 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 6520 6521 verifyFormat("Constructor(int Parameter = 0)\n" 6522 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n" 6523 " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}"); 6524 verifyFormat("Constructor()\n" 6525 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n" 6526 "}", 6527 getLLVMStyleWithColumns(60)); 6528 verifyFormat("Constructor()\n" 6529 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6530 " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}"); 6531 6532 // Here a line could be saved by splitting the second initializer onto two 6533 // lines, but that is not desirable. 6534 verifyFormat("Constructor()\n" 6535 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n" 6536 " aaaaaaaaaaa(aaaaaaaaaaa),\n" 6537 " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 6538 6539 FormatStyle OnePerLine = getLLVMStyle(); 6540 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_Never; 6541 verifyFormat("MyClass::MyClass()\n" 6542 " : a(a),\n" 6543 " b(b),\n" 6544 " c(c) {}", 6545 OnePerLine); 6546 verifyFormat("MyClass::MyClass()\n" 6547 " : a(a), // comment\n" 6548 " b(b),\n" 6549 " c(c) {}", 6550 OnePerLine); 6551 verifyFormat("MyClass::MyClass(int a)\n" 6552 " : b(a), // comment\n" 6553 " c(a + 1) { // lined up\n" 6554 "}", 6555 OnePerLine); 6556 verifyFormat("Constructor()\n" 6557 " : a(b, b, b) {}", 6558 OnePerLine); 6559 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6560 OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false; 6561 verifyFormat("SomeClass::Constructor()\n" 6562 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6563 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6564 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6565 OnePerLine); 6566 verifyFormat("SomeClass::Constructor()\n" 6567 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n" 6568 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6569 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6570 OnePerLine); 6571 verifyFormat("MyClass::MyClass(int var)\n" 6572 " : some_var_(var), // 4 space indent\n" 6573 " some_other_var_(var + 1) { // lined up\n" 6574 "}", 6575 OnePerLine); 6576 verifyFormat("Constructor()\n" 6577 " : aaaaa(aaaaaa),\n" 6578 " aaaaa(aaaaaa),\n" 6579 " aaaaa(aaaaaa),\n" 6580 " aaaaa(aaaaaa),\n" 6581 " aaaaa(aaaaaa) {}", 6582 OnePerLine); 6583 verifyFormat("Constructor()\n" 6584 " : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n" 6585 " aaaaaaaaaaaaaaaaaaaaaa) {}", 6586 OnePerLine); 6587 OnePerLine.BinPackParameters = false; 6588 verifyFormat( 6589 "Constructor()\n" 6590 " : aaaaaaaaaaaaaaaaaaaaaaaa(\n" 6591 " aaaaaaaaaaa().aaa(),\n" 6592 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6593 OnePerLine); 6594 OnePerLine.ColumnLimit = 60; 6595 verifyFormat("Constructor()\n" 6596 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6597 " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}", 6598 OnePerLine); 6599 6600 EXPECT_EQ("Constructor()\n" 6601 " : // Comment forcing unwanted break.\n" 6602 " aaaa(aaaa) {}", 6603 format("Constructor() :\n" 6604 " // Comment forcing unwanted break.\n" 6605 " aaaa(aaaa) {}")); 6606 } 6607 6608 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) { 6609 FormatStyle Style = getLLVMStyleWithColumns(60); 6610 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6611 Style.BinPackParameters = false; 6612 6613 for (int i = 0; i < 4; ++i) { 6614 // Test all combinations of parameters that should not have an effect. 6615 Style.AllowAllParametersOfDeclarationOnNextLine = i & 1; 6616 Style.AllowAllArgumentsOnNextLine = i & 2; 6617 6618 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6619 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6620 verifyFormat("Constructor()\n" 6621 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6622 Style); 6623 verifyFormat("Constructor() : a(a), b(b) {}", Style); 6624 6625 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6626 verifyFormat("Constructor()\n" 6627 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6628 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6629 Style); 6630 verifyFormat("Constructor() : a(a), b(b) {}", Style); 6631 6632 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 6633 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6634 verifyFormat("Constructor()\n" 6635 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6636 Style); 6637 6638 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6639 verifyFormat("Constructor()\n" 6640 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6641 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6642 Style); 6643 6644 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6645 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6646 verifyFormat("Constructor() :\n" 6647 " aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6648 Style); 6649 6650 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6651 verifyFormat("Constructor() :\n" 6652 " aaaaaaaaaaaaaaaaaa(a),\n" 6653 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6654 Style); 6655 } 6656 6657 // Test interactions between AllowAllParametersOfDeclarationOnNextLine and 6658 // AllowAllConstructorInitializersOnNextLine in all 6659 // BreakConstructorInitializers modes 6660 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6661 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6662 verifyFormat("SomeClassWithALongName::Constructor(\n" 6663 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n" 6664 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6665 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6666 Style); 6667 6668 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6669 verifyFormat("SomeClassWithALongName::Constructor(\n" 6670 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6671 " int bbbbbbbbbbbbb,\n" 6672 " int cccccccccccccccc)\n" 6673 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6674 Style); 6675 6676 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6677 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6678 verifyFormat("SomeClassWithALongName::Constructor(\n" 6679 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6680 " int bbbbbbbbbbbbb)\n" 6681 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6682 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6683 Style); 6684 6685 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 6686 6687 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6688 verifyFormat("SomeClassWithALongName::Constructor(\n" 6689 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n" 6690 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6691 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6692 Style); 6693 6694 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6695 verifyFormat("SomeClassWithALongName::Constructor(\n" 6696 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6697 " int bbbbbbbbbbbbb,\n" 6698 " int cccccccccccccccc)\n" 6699 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6700 Style); 6701 6702 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6703 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6704 verifyFormat("SomeClassWithALongName::Constructor(\n" 6705 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6706 " int bbbbbbbbbbbbb)\n" 6707 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6708 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6709 Style); 6710 6711 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6712 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6713 verifyFormat("SomeClassWithALongName::Constructor(\n" 6714 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n" 6715 " aaaaaaaaaaaaaaaaaaaa(a),\n" 6716 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6717 Style); 6718 6719 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6720 verifyFormat("SomeClassWithALongName::Constructor(\n" 6721 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6722 " int bbbbbbbbbbbbb,\n" 6723 " int cccccccccccccccc) :\n" 6724 " aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6725 Style); 6726 6727 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6728 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6729 verifyFormat("SomeClassWithALongName::Constructor(\n" 6730 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6731 " int bbbbbbbbbbbbb) :\n" 6732 " aaaaaaaaaaaaaaaaaaaa(a),\n" 6733 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6734 Style); 6735 } 6736 6737 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) { 6738 FormatStyle Style = getLLVMStyleWithColumns(60); 6739 Style.BinPackArguments = false; 6740 for (int i = 0; i < 4; ++i) { 6741 // Test all combinations of parameters that should not have an effect. 6742 Style.AllowAllParametersOfDeclarationOnNextLine = i & 1; 6743 Style.PackConstructorInitializers = 6744 i & 2 ? FormatStyle::PCIS_BinPack : FormatStyle::PCIS_Never; 6745 6746 Style.AllowAllArgumentsOnNextLine = true; 6747 verifyFormat("void foo() {\n" 6748 " FunctionCallWithReallyLongName(\n" 6749 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n" 6750 "}", 6751 Style); 6752 Style.AllowAllArgumentsOnNextLine = false; 6753 verifyFormat("void foo() {\n" 6754 " FunctionCallWithReallyLongName(\n" 6755 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6756 " bbbbbbbbbbbb);\n" 6757 "}", 6758 Style); 6759 6760 Style.AllowAllArgumentsOnNextLine = true; 6761 verifyFormat("void foo() {\n" 6762 " auto VariableWithReallyLongName = {\n" 6763 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n" 6764 "}", 6765 Style); 6766 Style.AllowAllArgumentsOnNextLine = false; 6767 verifyFormat("void foo() {\n" 6768 " auto VariableWithReallyLongName = {\n" 6769 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6770 " bbbbbbbbbbbb};\n" 6771 "}", 6772 Style); 6773 } 6774 6775 // This parameter should not affect declarations. 6776 Style.BinPackParameters = false; 6777 Style.AllowAllArgumentsOnNextLine = false; 6778 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6779 verifyFormat("void FunctionCallWithReallyLongName(\n" 6780 " int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);", 6781 Style); 6782 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6783 verifyFormat("void FunctionCallWithReallyLongName(\n" 6784 " int aaaaaaaaaaaaaaaaaaaaaaa,\n" 6785 " int bbbbbbbbbbbb);", 6786 Style); 6787 } 6788 6789 TEST_F(FormatTest, AllowAllArgumentsOnNextLineDontAlign) { 6790 // Check that AllowAllArgumentsOnNextLine is respected for both BAS_DontAlign 6791 // and BAS_Align. 6792 FormatStyle Style = getLLVMStyleWithColumns(35); 6793 StringRef Input = "functionCall(paramA, paramB, paramC);\n" 6794 "void functionDecl(int A, int B, int C);"; 6795 Style.AllowAllArgumentsOnNextLine = false; 6796 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6797 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6798 " paramC);\n" 6799 "void functionDecl(int A, int B,\n" 6800 " int C);"), 6801 format(Input, Style)); 6802 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 6803 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6804 " paramC);\n" 6805 "void functionDecl(int A, int B,\n" 6806 " int C);"), 6807 format(Input, Style)); 6808 // However, BAS_AlwaysBreak should take precedence over 6809 // AllowAllArgumentsOnNextLine. 6810 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 6811 EXPECT_EQ(StringRef("functionCall(\n" 6812 " paramA, paramB, paramC);\n" 6813 "void functionDecl(\n" 6814 " int A, int B, int C);"), 6815 format(Input, Style)); 6816 6817 // When AllowAllArgumentsOnNextLine is set, we prefer breaking before the 6818 // first argument. 6819 Style.AllowAllArgumentsOnNextLine = true; 6820 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 6821 EXPECT_EQ(StringRef("functionCall(\n" 6822 " paramA, paramB, paramC);\n" 6823 "void functionDecl(\n" 6824 " int A, int B, int C);"), 6825 format(Input, Style)); 6826 // It wouldn't fit on one line with aligned parameters so this setting 6827 // doesn't change anything for BAS_Align. 6828 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 6829 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6830 " paramC);\n" 6831 "void functionDecl(int A, int B,\n" 6832 " int C);"), 6833 format(Input, Style)); 6834 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6835 EXPECT_EQ(StringRef("functionCall(\n" 6836 " paramA, paramB, paramC);\n" 6837 "void functionDecl(\n" 6838 " int A, int B, int C);"), 6839 format(Input, Style)); 6840 } 6841 6842 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) { 6843 FormatStyle Style = getLLVMStyle(); 6844 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6845 6846 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}"); 6847 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}", 6848 getStyleWithColumns(Style, 45)); 6849 verifyFormat("Constructor() :\n" 6850 " Initializer(FitsOnTheLine) {}", 6851 getStyleWithColumns(Style, 44)); 6852 verifyFormat("Constructor() :\n" 6853 " Initializer(FitsOnTheLine) {}", 6854 getStyleWithColumns(Style, 43)); 6855 6856 verifyFormat("template <typename T>\n" 6857 "Constructor() : Initializer(FitsOnTheLine) {}", 6858 getStyleWithColumns(Style, 50)); 6859 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6860 verifyFormat( 6861 "SomeClass::Constructor() :\n" 6862 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 6863 Style); 6864 6865 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 6866 verifyFormat( 6867 "SomeClass::Constructor() :\n" 6868 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 6869 Style); 6870 6871 verifyFormat( 6872 "SomeClass::Constructor() :\n" 6873 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6874 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6875 Style); 6876 verifyFormat( 6877 "SomeClass::Constructor() :\n" 6878 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6879 " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 6880 Style); 6881 verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6882 " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 6883 " aaaaaaaaaa(aaaaaa) {}", 6884 Style); 6885 6886 verifyFormat("Constructor() :\n" 6887 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6888 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6889 " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6890 " aaaaaaaaaaaaaaaaaaaaaaa() {}", 6891 Style); 6892 6893 verifyFormat("Constructor() :\n" 6894 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6895 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6896 Style); 6897 6898 verifyFormat("Constructor(int Parameter = 0) :\n" 6899 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n" 6900 " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}", 6901 Style); 6902 verifyFormat("Constructor() :\n" 6903 " aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n" 6904 "}", 6905 getStyleWithColumns(Style, 60)); 6906 verifyFormat("Constructor() :\n" 6907 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6908 " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}", 6909 Style); 6910 6911 // Here a line could be saved by splitting the second initializer onto two 6912 // lines, but that is not desirable. 6913 verifyFormat("Constructor() :\n" 6914 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n" 6915 " aaaaaaaaaaa(aaaaaaaaaaa),\n" 6916 " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6917 Style); 6918 6919 FormatStyle OnePerLine = Style; 6920 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6921 verifyFormat("SomeClass::Constructor() :\n" 6922 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6923 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6924 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6925 OnePerLine); 6926 verifyFormat("SomeClass::Constructor() :\n" 6927 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n" 6928 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6929 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6930 OnePerLine); 6931 verifyFormat("MyClass::MyClass(int var) :\n" 6932 " some_var_(var), // 4 space indent\n" 6933 " some_other_var_(var + 1) { // lined up\n" 6934 "}", 6935 OnePerLine); 6936 verifyFormat("Constructor() :\n" 6937 " aaaaa(aaaaaa),\n" 6938 " aaaaa(aaaaaa),\n" 6939 " aaaaa(aaaaaa),\n" 6940 " aaaaa(aaaaaa),\n" 6941 " aaaaa(aaaaaa) {}", 6942 OnePerLine); 6943 verifyFormat("Constructor() :\n" 6944 " aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n" 6945 " aaaaaaaaaaaaaaaaaaaaaa) {}", 6946 OnePerLine); 6947 OnePerLine.BinPackParameters = false; 6948 verifyFormat("Constructor() :\n" 6949 " aaaaaaaaaaaaaaaaaaaaaaaa(\n" 6950 " aaaaaaaaaaa().aaa(),\n" 6951 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6952 OnePerLine); 6953 OnePerLine.ColumnLimit = 60; 6954 verifyFormat("Constructor() :\n" 6955 " aaaaaaaaaaaaaaaaaaaa(a),\n" 6956 " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}", 6957 OnePerLine); 6958 6959 EXPECT_EQ("Constructor() :\n" 6960 " // Comment forcing unwanted break.\n" 6961 " aaaa(aaaa) {}", 6962 format("Constructor() :\n" 6963 " // Comment forcing unwanted break.\n" 6964 " aaaa(aaaa) {}", 6965 Style)); 6966 6967 Style.ColumnLimit = 0; 6968 verifyFormat("SomeClass::Constructor() :\n" 6969 " a(a) {}", 6970 Style); 6971 verifyFormat("SomeClass::Constructor() noexcept :\n" 6972 " a(a) {}", 6973 Style); 6974 verifyFormat("SomeClass::Constructor() :\n" 6975 " a(a), b(b), c(c) {}", 6976 Style); 6977 verifyFormat("SomeClass::Constructor() :\n" 6978 " a(a) {\n" 6979 " foo();\n" 6980 " bar();\n" 6981 "}", 6982 Style); 6983 6984 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 6985 verifyFormat("SomeClass::Constructor() :\n" 6986 " a(a), b(b), c(c) {\n" 6987 "}", 6988 Style); 6989 verifyFormat("SomeClass::Constructor() :\n" 6990 " a(a) {\n" 6991 "}", 6992 Style); 6993 6994 Style.ColumnLimit = 80; 6995 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 6996 Style.ConstructorInitializerIndentWidth = 2; 6997 verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style); 6998 verifyFormat("SomeClass::Constructor() :\n" 6999 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7000 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}", 7001 Style); 7002 7003 // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as 7004 // well 7005 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 7006 verifyFormat( 7007 "class SomeClass\n" 7008 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7009 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7010 Style); 7011 Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma; 7012 verifyFormat( 7013 "class SomeClass\n" 7014 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7015 " , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7016 Style); 7017 Style.BreakInheritanceList = FormatStyle::BILS_AfterColon; 7018 verifyFormat( 7019 "class SomeClass :\n" 7020 " public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7021 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7022 Style); 7023 Style.BreakInheritanceList = FormatStyle::BILS_AfterComma; 7024 verifyFormat( 7025 "class SomeClass\n" 7026 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7027 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 7028 Style); 7029 } 7030 7031 #ifndef EXPENSIVE_CHECKS 7032 // Expensive checks enables libstdc++ checking which includes validating the 7033 // state of ranges used in std::priority_queue - this blows out the 7034 // runtime/scalability of the function and makes this test unacceptably slow. 7035 TEST_F(FormatTest, MemoizationTests) { 7036 // This breaks if the memoization lookup does not take \c Indent and 7037 // \c LastSpace into account. 7038 verifyFormat( 7039 "extern CFRunLoopTimerRef\n" 7040 "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n" 7041 " CFTimeInterval interval, CFOptionFlags flags,\n" 7042 " CFIndex order, CFRunLoopTimerCallBack callout,\n" 7043 " CFRunLoopTimerContext *context) {}"); 7044 7045 // Deep nesting somewhat works around our memoization. 7046 verifyFormat( 7047 "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7048 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7049 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7050 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 7051 " aaaaa())))))))))))))))))))))))))))))))))))))));", 7052 getLLVMStyleWithColumns(65)); 7053 verifyFormat( 7054 "aaaaa(\n" 7055 " aaaaa,\n" 7056 " aaaaa(\n" 7057 " aaaaa,\n" 7058 " aaaaa(\n" 7059 " aaaaa,\n" 7060 " aaaaa(\n" 7061 " aaaaa,\n" 7062 " aaaaa(\n" 7063 " aaaaa,\n" 7064 " aaaaa(\n" 7065 " aaaaa,\n" 7066 " aaaaa(\n" 7067 " aaaaa,\n" 7068 " aaaaa(\n" 7069 " aaaaa,\n" 7070 " aaaaa(\n" 7071 " aaaaa,\n" 7072 " aaaaa(\n" 7073 " aaaaa,\n" 7074 " aaaaa(\n" 7075 " aaaaa,\n" 7076 " aaaaa(\n" 7077 " aaaaa,\n" 7078 " aaaaa))))))))))));", 7079 getLLVMStyleWithColumns(65)); 7080 verifyFormat( 7081 "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" 7082 " a),\n" 7083 " a),\n" 7084 " a),\n" 7085 " a),\n" 7086 " a),\n" 7087 " a),\n" 7088 " a),\n" 7089 " a),\n" 7090 " a),\n" 7091 " a),\n" 7092 " a),\n" 7093 " a),\n" 7094 " a),\n" 7095 " a),\n" 7096 " a),\n" 7097 " a),\n" 7098 " a)", 7099 getLLVMStyleWithColumns(65)); 7100 7101 // This test takes VERY long when memoization is broken. 7102 FormatStyle OnePerLine = getLLVMStyle(); 7103 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 7104 OnePerLine.BinPackParameters = false; 7105 std::string input = "Constructor()\n" 7106 " : aaaa(a,\n"; 7107 for (unsigned i = 0, e = 80; i != e; ++i) { 7108 input += " a,\n"; 7109 } 7110 input += " a) {}"; 7111 verifyFormat(input, OnePerLine); 7112 } 7113 #endif 7114 7115 TEST_F(FormatTest, BreaksAsHighAsPossible) { 7116 verifyFormat( 7117 "void f() {\n" 7118 " if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n" 7119 " (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n" 7120 " f();\n" 7121 "}"); 7122 verifyFormat("if (Intervals[i].getRange().getFirst() <\n" 7123 " Intervals[i - 1].getRange().getLast()) {\n}"); 7124 } 7125 7126 TEST_F(FormatTest, BreaksFunctionDeclarations) { 7127 // Principially, we break function declarations in a certain order: 7128 // 1) break amongst arguments. 7129 verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n" 7130 " Cccccccccccccc cccccccccccccc);"); 7131 verifyFormat("template <class TemplateIt>\n" 7132 "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n" 7133 " TemplateIt *stop) {}"); 7134 7135 // 2) break after return type. 7136 verifyFormat( 7137 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7138 "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);", 7139 getGoogleStyle()); 7140 7141 // 3) break after (. 7142 verifyFormat( 7143 "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n" 7144 " Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);", 7145 getGoogleStyle()); 7146 7147 // 4) break before after nested name specifiers. 7148 verifyFormat( 7149 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7150 "SomeClasssssssssssssssssssssssssssssssssssssss::\n" 7151 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);", 7152 getGoogleStyle()); 7153 7154 // However, there are exceptions, if a sufficient amount of lines can be 7155 // saved. 7156 // FIXME: The precise cut-offs wrt. the number of saved lines might need some 7157 // more adjusting. 7158 verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n" 7159 " Cccccccccccccc cccccccccc,\n" 7160 " Cccccccccccccc cccccccccc,\n" 7161 " Cccccccccccccc cccccccccc,\n" 7162 " Cccccccccccccc cccccccccc);"); 7163 verifyFormat( 7164 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7165 "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7166 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7167 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);", 7168 getGoogleStyle()); 7169 verifyFormat( 7170 "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n" 7171 " Cccccccccccccc cccccccccc,\n" 7172 " Cccccccccccccc cccccccccc,\n" 7173 " Cccccccccccccc cccccccccc,\n" 7174 " Cccccccccccccc cccccccccc,\n" 7175 " Cccccccccccccc cccccccccc,\n" 7176 " Cccccccccccccc cccccccccc);"); 7177 verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7178 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7179 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7180 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 7181 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);"); 7182 7183 // Break after multi-line parameters. 7184 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7185 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7186 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7187 " bbbb bbbb);"); 7188 verifyFormat("void SomeLoooooooooooongFunction(\n" 7189 " std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n" 7190 " aaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7191 " int bbbbbbbbbbbbb);"); 7192 7193 // Treat overloaded operators like other functions. 7194 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 7195 "operator>(const SomeLoooooooooooooooooooooooooogType &other);"); 7196 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 7197 "operator>>(const SomeLooooooooooooooooooooooooogType &other);"); 7198 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 7199 "operator<<(const SomeLooooooooooooooooooooooooogType &other);"); 7200 verifyGoogleFormat( 7201 "SomeLoooooooooooooooooooooooooooooogType operator>>(\n" 7202 " const SomeLooooooooogType &a, const SomeLooooooooogType &b);"); 7203 verifyGoogleFormat( 7204 "SomeLoooooooooooooooooooooooooooooogType operator<<(\n" 7205 " const SomeLooooooooogType &a, const SomeLooooooooogType &b);"); 7206 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7207 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);"); 7208 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n" 7209 "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);"); 7210 verifyGoogleFormat( 7211 "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n" 7212 "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7213 " bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}"); 7214 verifyGoogleFormat("template <typename T>\n" 7215 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7216 "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n" 7217 " aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);"); 7218 7219 FormatStyle Style = getLLVMStyle(); 7220 Style.PointerAlignment = FormatStyle::PAS_Left; 7221 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7222 " aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}", 7223 Style); 7224 verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n" 7225 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7226 Style); 7227 } 7228 7229 TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) { 7230 // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516: 7231 // Prefer keeping `::` followed by `operator` together. 7232 EXPECT_EQ("const aaaa::bbbbbbb &\n" 7233 "ccccccccc::operator++() {\n" 7234 " stuff();\n" 7235 "}", 7236 format("const aaaa::bbbbbbb\n" 7237 "&ccccccccc::operator++() { stuff(); }", 7238 getLLVMStyleWithColumns(40))); 7239 } 7240 7241 TEST_F(FormatTest, TrailingReturnType) { 7242 verifyFormat("auto foo() -> int;\n"); 7243 // correct trailing return type spacing 7244 verifyFormat("auto operator->() -> int;\n"); 7245 verifyFormat("auto operator++(int) -> int;\n"); 7246 7247 verifyFormat("struct S {\n" 7248 " auto bar() const -> int;\n" 7249 "};"); 7250 verifyFormat("template <size_t Order, typename T>\n" 7251 "auto load_img(const std::string &filename)\n" 7252 " -> alias::tensor<Order, T, mem::tag::cpu> {}"); 7253 verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n" 7254 " -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}"); 7255 verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}"); 7256 verifyFormat("template <typename T>\n" 7257 "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n" 7258 " -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());"); 7259 7260 // Not trailing return types. 7261 verifyFormat("void f() { auto a = b->c(); }"); 7262 verifyFormat("auto a = p->foo();"); 7263 verifyFormat("int a = p->foo();"); 7264 verifyFormat("auto lmbd = [] NOEXCEPT -> int { return 0; };"); 7265 } 7266 7267 TEST_F(FormatTest, DeductionGuides) { 7268 verifyFormat("template <class T> A(const T &, const T &) -> A<T &>;"); 7269 verifyFormat("template <class T> explicit A(T &, T &&) -> A<T>;"); 7270 verifyFormat("template <class... Ts> S(Ts...) -> S<Ts...>;"); 7271 verifyFormat( 7272 "template <class... T>\n" 7273 "array(T &&...t) -> array<std::common_type_t<T...>, sizeof...(T)>;"); 7274 verifyFormat("template <class T> A() -> A<decltype(p->foo<3>())>;"); 7275 verifyFormat("template <class T> A() -> A<decltype(foo<traits<1>>)>;"); 7276 verifyFormat("template <class T> A() -> A<sizeof(p->foo<1>)>;"); 7277 verifyFormat("template <class T> A() -> A<(3 < 2)>;"); 7278 verifyFormat("template <class T> A() -> A<((3) < (2))>;"); 7279 verifyFormat("template <class T> x() -> x<1>;"); 7280 verifyFormat("template <class T> explicit x(T &) -> x<1>;"); 7281 7282 // Ensure not deduction guides. 7283 verifyFormat("c()->f<int>();"); 7284 verifyFormat("x()->foo<1>;"); 7285 verifyFormat("x = p->foo<3>();"); 7286 verifyFormat("x()->x<1>();"); 7287 verifyFormat("x()->x<1>;"); 7288 } 7289 7290 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) { 7291 // Avoid breaking before trailing 'const' or other trailing annotations, if 7292 // they are not function-like. 7293 FormatStyle Style = getGoogleStyleWithColumns(47); 7294 verifyFormat("void someLongFunction(\n" 7295 " int someLoooooooooooooongParameter) const {\n}", 7296 getLLVMStyleWithColumns(47)); 7297 verifyFormat("LoooooongReturnType\n" 7298 "someLoooooooongFunction() const {}", 7299 getLLVMStyleWithColumns(47)); 7300 verifyFormat("LoooooongReturnType someLoooooooongFunction()\n" 7301 " const {}", 7302 Style); 7303 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7304 " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;"); 7305 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7306 " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;"); 7307 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 7308 " aaaaa aaaaaaaaaaaaaaaaaaaa) override final;"); 7309 verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n" 7310 " aaaaaaaaaaa aaaaa) const override;"); 7311 verifyGoogleFormat( 7312 "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7313 " const override;"); 7314 7315 // Even if the first parameter has to be wrapped. 7316 verifyFormat("void someLongFunction(\n" 7317 " int someLongParameter) const {}", 7318 getLLVMStyleWithColumns(46)); 7319 verifyFormat("void someLongFunction(\n" 7320 " int someLongParameter) const {}", 7321 Style); 7322 verifyFormat("void someLongFunction(\n" 7323 " int someLongParameter) override {}", 7324 Style); 7325 verifyFormat("void someLongFunction(\n" 7326 " int someLongParameter) OVERRIDE {}", 7327 Style); 7328 verifyFormat("void someLongFunction(\n" 7329 " int someLongParameter) final {}", 7330 Style); 7331 verifyFormat("void someLongFunction(\n" 7332 " int someLongParameter) FINAL {}", 7333 Style); 7334 verifyFormat("void someLongFunction(\n" 7335 " int parameter) const override {}", 7336 Style); 7337 7338 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 7339 verifyFormat("void someLongFunction(\n" 7340 " int someLongParameter) const\n" 7341 "{\n" 7342 "}", 7343 Style); 7344 7345 Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 7346 verifyFormat("void someLongFunction(\n" 7347 " int someLongParameter) const\n" 7348 " {\n" 7349 " }", 7350 Style); 7351 7352 // Unless these are unknown annotations. 7353 verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n" 7354 " aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7355 " LONG_AND_UGLY_ANNOTATION;"); 7356 7357 // Breaking before function-like trailing annotations is fine to keep them 7358 // close to their arguments. 7359 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7360 " LOCKS_EXCLUDED(aaaaaaaaaaaaa);"); 7361 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n" 7362 " LOCKS_EXCLUDED(aaaaaaaaaaaaa);"); 7363 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n" 7364 " LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}"); 7365 verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n" 7366 " AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);"); 7367 verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});"); 7368 7369 verifyFormat( 7370 "void aaaaaaaaaaaaaaaaaa()\n" 7371 " __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n" 7372 " aaaaaaaaaaaaaaaaaaaaaaaaa));"); 7373 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7374 " __attribute__((unused));"); 7375 verifyGoogleFormat( 7376 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7377 " GUARDED_BY(aaaaaaaaaaaa);"); 7378 verifyGoogleFormat( 7379 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7380 " GUARDED_BY(aaaaaaaaaaaa);"); 7381 verifyGoogleFormat( 7382 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n" 7383 " aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7384 verifyGoogleFormat( 7385 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n" 7386 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7387 } 7388 7389 TEST_F(FormatTest, FunctionAnnotations) { 7390 verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7391 "int OldFunction(const string ¶meter) {}"); 7392 verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7393 "string OldFunction(const string ¶meter) {}"); 7394 verifyFormat("template <typename T>\n" 7395 "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 7396 "string OldFunction(const string ¶meter) {}"); 7397 7398 // Not function annotations. 7399 verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7400 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"); 7401 verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n" 7402 " ThisIsATestWithAReallyReallyReallyReallyLongName) {}"); 7403 verifyFormat("MACRO(abc).function() // wrap\n" 7404 " << abc;"); 7405 verifyFormat("MACRO(abc)->function() // wrap\n" 7406 " << abc;"); 7407 verifyFormat("MACRO(abc)::function() // wrap\n" 7408 " << abc;"); 7409 } 7410 7411 TEST_F(FormatTest, BreaksDesireably) { 7412 verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n" 7413 " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n" 7414 " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}"); 7415 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7416 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 7417 "}"); 7418 7419 verifyFormat( 7420 "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7421 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 7422 7423 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7424 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7425 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7426 7427 verifyFormat( 7428 "aaaaaaaa(aaaaaaaaaaaaa,\n" 7429 " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7430 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n" 7431 " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7432 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));"); 7433 7434 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 7435 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7436 7437 verifyFormat( 7438 "void f() {\n" 7439 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n" 7440 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 7441 "}"); 7442 verifyFormat( 7443 "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7444 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7445 verifyFormat( 7446 "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7447 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7448 verifyFormat( 7449 "aaaaaa(aaa,\n" 7450 " new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7451 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7452 " aaaa);"); 7453 verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7454 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7455 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7456 7457 // Indent consistently independent of call expression and unary operator. 7458 verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7459 " dddddddddddddddddddddddddddddd));"); 7460 verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7461 " dddddddddddddddddddddddddddddd));"); 7462 verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n" 7463 " dddddddddddddddddddddddddddddd));"); 7464 7465 // This test case breaks on an incorrect memoization, i.e. an optimization not 7466 // taking into account the StopAt value. 7467 verifyFormat( 7468 "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7469 " aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7470 " aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7471 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7472 7473 verifyFormat("{\n {\n {\n" 7474 " Annotation.SpaceRequiredBefore =\n" 7475 " Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n" 7476 " Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n" 7477 " }\n }\n}"); 7478 7479 // Break on an outer level if there was a break on an inner level. 7480 EXPECT_EQ("f(g(h(a, // comment\n" 7481 " b, c),\n" 7482 " d, e),\n" 7483 " x, y);", 7484 format("f(g(h(a, // comment\n" 7485 " b, c), d, e), x, y);")); 7486 7487 // Prefer breaking similar line breaks. 7488 verifyFormat( 7489 "const int kTrackingOptions = NSTrackingMouseMoved |\n" 7490 " NSTrackingMouseEnteredAndExited |\n" 7491 " NSTrackingActiveAlways;"); 7492 } 7493 7494 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) { 7495 FormatStyle NoBinPacking = getGoogleStyle(); 7496 NoBinPacking.BinPackParameters = false; 7497 NoBinPacking.BinPackArguments = true; 7498 verifyFormat("void f() {\n" 7499 " f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n" 7500 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 7501 "}", 7502 NoBinPacking); 7503 verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n" 7504 " int aaaaaaaaaaaaaaaaaaaa,\n" 7505 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7506 NoBinPacking); 7507 7508 NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false; 7509 verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7510 " vector<int> bbbbbbbbbbbbbbb);", 7511 NoBinPacking); 7512 // FIXME: This behavior difference is probably not wanted. However, currently 7513 // we cannot distinguish BreakBeforeParameter being set because of the wrapped 7514 // template arguments from BreakBeforeParameter being set because of the 7515 // one-per-line formatting. 7516 verifyFormat( 7517 "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n" 7518 " aaaaaaaaaa> aaaaaaaaaa);", 7519 NoBinPacking); 7520 verifyFormat( 7521 "void fffffffffff(\n" 7522 " aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n" 7523 " aaaaaaaaaa);"); 7524 } 7525 7526 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) { 7527 FormatStyle NoBinPacking = getGoogleStyle(); 7528 NoBinPacking.BinPackParameters = false; 7529 NoBinPacking.BinPackArguments = false; 7530 verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n" 7531 " aaaaaaaaaaaaaaaaaaaa,\n" 7532 " aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);", 7533 NoBinPacking); 7534 verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n" 7535 " aaaaaaaaaaaaa,\n" 7536 " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));", 7537 NoBinPacking); 7538 verifyFormat( 7539 "aaaaaaaa(aaaaaaaaaaaaa,\n" 7540 " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7541 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n" 7542 " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7543 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));", 7544 NoBinPacking); 7545 verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n" 7546 " .aaaaaaaaaaaaaaaaaa();", 7547 NoBinPacking); 7548 verifyFormat("void f() {\n" 7549 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7550 " aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n" 7551 "}", 7552 NoBinPacking); 7553 7554 verifyFormat( 7555 "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7556 " aaaaaaaaaaaa,\n" 7557 " aaaaaaaaaaaa);", 7558 NoBinPacking); 7559 verifyFormat( 7560 "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n" 7561 " ddddddddddddddddddddddddddddd),\n" 7562 " test);", 7563 NoBinPacking); 7564 7565 verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n" 7566 " aaaaaaaaaaaaaaaaaaaaaaa,\n" 7567 " aaaaaaaaaaaaaaaaaaaaaaa>\n" 7568 " aaaaaaaaaaaaaaaaaa;", 7569 NoBinPacking); 7570 verifyFormat("a(\"a\"\n" 7571 " \"a\",\n" 7572 " a);"); 7573 7574 NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false; 7575 verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n" 7576 " aaaaaaaaa,\n" 7577 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7578 NoBinPacking); 7579 verifyFormat( 7580 "void f() {\n" 7581 " aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n" 7582 " .aaaaaaa();\n" 7583 "}", 7584 NoBinPacking); 7585 verifyFormat( 7586 "template <class SomeType, class SomeOtherType>\n" 7587 "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}", 7588 NoBinPacking); 7589 } 7590 7591 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) { 7592 FormatStyle Style = getLLVMStyleWithColumns(15); 7593 Style.ExperimentalAutoDetectBinPacking = true; 7594 EXPECT_EQ("aaa(aaaa,\n" 7595 " aaaa,\n" 7596 " aaaa);\n" 7597 "aaa(aaaa,\n" 7598 " aaaa,\n" 7599 " aaaa);", 7600 format("aaa(aaaa,\n" // one-per-line 7601 " aaaa,\n" 7602 " aaaa );\n" 7603 "aaa(aaaa, aaaa, aaaa);", // inconclusive 7604 Style)); 7605 EXPECT_EQ("aaa(aaaa, aaaa,\n" 7606 " aaaa);\n" 7607 "aaa(aaaa, aaaa,\n" 7608 " aaaa);", 7609 format("aaa(aaaa, aaaa,\n" // bin-packed 7610 " aaaa );\n" 7611 "aaa(aaaa, aaaa, aaaa);", // inconclusive 7612 Style)); 7613 } 7614 7615 TEST_F(FormatTest, FormatsBuilderPattern) { 7616 verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n" 7617 " .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n" 7618 " .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n" 7619 " .StartsWith(\".init\", ORDER_INIT)\n" 7620 " .StartsWith(\".fini\", ORDER_FINI)\n" 7621 " .StartsWith(\".hash\", ORDER_HASH)\n" 7622 " .Default(ORDER_TEXT);\n"); 7623 7624 verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n" 7625 " aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();"); 7626 verifyFormat("aaaaaaa->aaaaaaa\n" 7627 " ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7628 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7629 " ->aaaaaaaa(aaaaaaaaaaaaaaa);"); 7630 verifyFormat( 7631 "aaaaaaa->aaaaaaa\n" 7632 " ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7633 " ->aaaaaaaa(aaaaaaaaaaaaaaa);"); 7634 verifyFormat( 7635 "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n" 7636 " aaaaaaaaaaaaaa);"); 7637 verifyFormat( 7638 "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n" 7639 " aaaaaa->aaaaaaaaaaaa()\n" 7640 " ->aaaaaaaaaaaaaaaa(\n" 7641 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7642 " ->aaaaaaaaaaaaaaaaa();"); 7643 verifyGoogleFormat( 7644 "void f() {\n" 7645 " someo->Add((new util::filetools::Handler(dir))\n" 7646 " ->OnEvent1(NewPermanentCallback(\n" 7647 " this, &HandlerHolderClass::EventHandlerCBA))\n" 7648 " ->OnEvent2(NewPermanentCallback(\n" 7649 " this, &HandlerHolderClass::EventHandlerCBB))\n" 7650 " ->OnEvent3(NewPermanentCallback(\n" 7651 " this, &HandlerHolderClass::EventHandlerCBC))\n" 7652 " ->OnEvent5(NewPermanentCallback(\n" 7653 " this, &HandlerHolderClass::EventHandlerCBD))\n" 7654 " ->OnEvent6(NewPermanentCallback(\n" 7655 " this, &HandlerHolderClass::EventHandlerCBE)));\n" 7656 "}"); 7657 7658 verifyFormat( 7659 "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();"); 7660 verifyFormat("aaaaaaaaaaaaaaa()\n" 7661 " .aaaaaaaaaaaaaaa()\n" 7662 " .aaaaaaaaaaaaaaa()\n" 7663 " .aaaaaaaaaaaaaaa()\n" 7664 " .aaaaaaaaaaaaaaa();"); 7665 verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7666 " .aaaaaaaaaaaaaaa()\n" 7667 " .aaaaaaaaaaaaaaa()\n" 7668 " .aaaaaaaaaaaaaaa();"); 7669 verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7670 " .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7671 " .aaaaaaaaaaaaaaa();"); 7672 verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n" 7673 " ->aaaaaaaaaaaaaae(0)\n" 7674 " ->aaaaaaaaaaaaaaa();"); 7675 7676 // Don't linewrap after very short segments. 7677 verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7678 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7679 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7680 verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7681 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7682 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7683 verifyFormat("aaa()\n" 7684 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7685 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7686 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7687 7688 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n" 7689 " .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7690 " .has<bbbbbbbbbbbbbbbbbbbbb>();"); 7691 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n" 7692 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 7693 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();"); 7694 7695 // Prefer not to break after empty parentheses. 7696 verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n" 7697 " First->LastNewlineOffset);"); 7698 7699 // Prefer not to create "hanging" indents. 7700 verifyFormat( 7701 "return !soooooooooooooome_map\n" 7702 " .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7703 " .second;"); 7704 verifyFormat( 7705 "return aaaaaaaaaaaaaaaa\n" 7706 " .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n" 7707 " .aaaa(aaaaaaaaaaaaaa);"); 7708 // No hanging indent here. 7709 verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n" 7710 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7711 verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n" 7712 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7713 verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n" 7714 " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7715 getLLVMStyleWithColumns(60)); 7716 verifyFormat("aaaaaaaaaaaaaaaaaa\n" 7717 " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n" 7718 " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7719 getLLVMStyleWithColumns(59)); 7720 verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7721 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7722 " .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7723 7724 // Dont break if only closing statements before member call 7725 verifyFormat("test() {\n" 7726 " ([]() -> {\n" 7727 " int b = 32;\n" 7728 " return 3;\n" 7729 " }).foo();\n" 7730 "}"); 7731 verifyFormat("test() {\n" 7732 " (\n" 7733 " []() -> {\n" 7734 " int b = 32;\n" 7735 " return 3;\n" 7736 " },\n" 7737 " foo, bar)\n" 7738 " .foo();\n" 7739 "}"); 7740 verifyFormat("test() {\n" 7741 " ([]() -> {\n" 7742 " int b = 32;\n" 7743 " return 3;\n" 7744 " })\n" 7745 " .foo()\n" 7746 " .bar();\n" 7747 "}"); 7748 verifyFormat("test() {\n" 7749 " ([]() -> {\n" 7750 " int b = 32;\n" 7751 " return 3;\n" 7752 " })\n" 7753 " .foo(\"aaaaaaaaaaaaaaaaa\"\n" 7754 " \"bbbb\");\n" 7755 "}", 7756 getLLVMStyleWithColumns(30)); 7757 } 7758 7759 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) { 7760 verifyFormat( 7761 "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 7762 " bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}"); 7763 verifyFormat( 7764 "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n" 7765 " bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}"); 7766 7767 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" 7768 " ccccccccccccccccccccccccc) {\n}"); 7769 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n" 7770 " ccccccccccccccccccccccccc) {\n}"); 7771 7772 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" 7773 " ccccccccccccccccccccccccc) {\n}"); 7774 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n" 7775 " ccccccccccccccccccccccccc) {\n}"); 7776 7777 verifyFormat( 7778 "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n" 7779 " ccccccccccccccccccccccccc) {\n}"); 7780 verifyFormat( 7781 "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n" 7782 " ccccccccccccccccccccccccc) {\n}"); 7783 7784 verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n" 7785 " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n" 7786 " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n" 7787 " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;"); 7788 verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n" 7789 " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n" 7790 " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n" 7791 " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;"); 7792 7793 verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n" 7794 " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n" 7795 " aaaaaaaaaaaaaaa != aa) {\n}"); 7796 verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n" 7797 " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n" 7798 " aaaaaaaaaaaaaaa != aa) {\n}"); 7799 } 7800 7801 TEST_F(FormatTest, BreaksAfterAssignments) { 7802 verifyFormat( 7803 "unsigned Cost =\n" 7804 " TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n" 7805 " SI->getPointerAddressSpaceee());\n"); 7806 verifyFormat( 7807 "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n" 7808 " Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());"); 7809 7810 verifyFormat( 7811 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n" 7812 " aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);"); 7813 verifyFormat("unsigned OriginalStartColumn =\n" 7814 " SourceMgr.getSpellingColumnNumber(\n" 7815 " Current.FormatTok.getStartOfNonWhitespace()) -\n" 7816 " 1;"); 7817 } 7818 7819 TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) { 7820 FormatStyle Style = getLLVMStyle(); 7821 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 7822 " bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;", 7823 Style); 7824 7825 Style.PenaltyBreakAssignment = 20; 7826 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n" 7827 " cccccccccccccccccccccccccc;", 7828 Style); 7829 } 7830 7831 TEST_F(FormatTest, AlignsAfterAssignments) { 7832 verifyFormat( 7833 "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7834 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7835 verifyFormat( 7836 "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7837 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7838 verifyFormat( 7839 "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7840 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7841 verifyFormat( 7842 "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7843 " aaaaaaaaaaaaaaaaaaaaaaaaa);"); 7844 verifyFormat( 7845 "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n" 7846 " aaaaaaaaaaaaaaaaaaaaaaaa +\n" 7847 " aaaaaaaaaaaaaaaaaaaaaaaa;"); 7848 } 7849 7850 TEST_F(FormatTest, AlignsAfterReturn) { 7851 verifyFormat( 7852 "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7853 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7854 verifyFormat( 7855 "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7856 " aaaaaaaaaaaaaaaaaaaaaaaaa);"); 7857 verifyFormat( 7858 "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n" 7859 " aaaaaaaaaaaaaaaaaaaaaa();"); 7860 verifyFormat( 7861 "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n" 7862 " aaaaaaaaaaaaaaaaaaaaaa());"); 7863 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7864 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7865 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7866 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n" 7867 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7868 verifyFormat("return\n" 7869 " // true if code is one of a or b.\n" 7870 " code == a || code == b;"); 7871 } 7872 7873 TEST_F(FormatTest, AlignsAfterOpenBracket) { 7874 verifyFormat( 7875 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n" 7876 " aaaaaaaaa aaaaaaa) {}"); 7877 verifyFormat( 7878 "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n" 7879 " aaaaaaaaaaa aaaaaaaaa);"); 7880 verifyFormat( 7881 "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n" 7882 " aaaaaaaaaaaaaaaaaaaaa));"); 7883 FormatStyle Style = getLLVMStyle(); 7884 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 7885 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7886 " aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}", 7887 Style); 7888 verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n" 7889 " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);", 7890 Style); 7891 verifyFormat("SomeLongVariableName->someFunction(\n" 7892 " foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));", 7893 Style); 7894 verifyFormat( 7895 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n" 7896 " aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7897 Style); 7898 verifyFormat( 7899 "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n" 7900 " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7901 Style); 7902 verifyFormat( 7903 "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n" 7904 " aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));", 7905 Style); 7906 7907 verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n" 7908 " ccccccc(aaaaaaaaaaaaaaaaa, //\n" 7909 " b));", 7910 Style); 7911 7912 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 7913 Style.BinPackArguments = false; 7914 Style.BinPackParameters = false; 7915 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7916 " aaaaaaaaaaa aaaaaaaa,\n" 7917 " aaaaaaaaa aaaaaaa,\n" 7918 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7919 Style); 7920 verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n" 7921 " aaaaaaaaaaa aaaaaaaaa,\n" 7922 " aaaaaaaaaaa aaaaaaaaa,\n" 7923 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7924 Style); 7925 verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n" 7926 " aaaaaaaaaaaaaaa,\n" 7927 " aaaaaaaaaaaaaaaaaaaaa,\n" 7928 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));", 7929 Style); 7930 verifyFormat( 7931 "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n" 7932 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));", 7933 Style); 7934 verifyFormat( 7935 "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n" 7936 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));", 7937 Style); 7938 verifyFormat( 7939 "aaaaaaaaaaaaaaaaaaaaaaaa(\n" 7940 " aaaaaaaaaaaaaaaaaaaaa(\n" 7941 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n" 7942 " aaaaaaaaaaaaaaaa);", 7943 Style); 7944 verifyFormat( 7945 "aaaaaaaaaaaaaaaaaaaaaaaa(\n" 7946 " aaaaaaaaaaaaaaaaaaaaa(\n" 7947 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n" 7948 " aaaaaaaaaaaaaaaa);", 7949 Style); 7950 } 7951 7952 TEST_F(FormatTest, ParenthesesAndOperandAlignment) { 7953 FormatStyle Style = getLLVMStyleWithColumns(40); 7954 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 7955 " bbbbbbbbbbbbbbbbbbbbbb);", 7956 Style); 7957 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 7958 Style.AlignOperands = FormatStyle::OAS_DontAlign; 7959 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 7960 " bbbbbbbbbbbbbbbbbbbbbb);", 7961 Style); 7962 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 7963 Style.AlignOperands = FormatStyle::OAS_Align; 7964 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 7965 " bbbbbbbbbbbbbbbbbbbbbb);", 7966 Style); 7967 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 7968 Style.AlignOperands = FormatStyle::OAS_DontAlign; 7969 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 7970 " bbbbbbbbbbbbbbbbbbbbbb);", 7971 Style); 7972 } 7973 7974 TEST_F(FormatTest, BreaksConditionalExpressions) { 7975 verifyFormat( 7976 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7977 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7978 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7979 verifyFormat( 7980 "aaaa(aaaaaaaaaa, aaaaaaaa,\n" 7981 " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7982 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7983 verifyFormat( 7984 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7985 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7986 verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n" 7987 " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7988 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7989 verifyFormat( 7990 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n" 7991 " : aaaaaaaaaaaaa);"); 7992 verifyFormat( 7993 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7994 " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7995 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7996 " aaaaaaaaaaaaa);"); 7997 verifyFormat( 7998 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7999 " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8000 " aaaaaaaaaaaaa);"); 8001 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8002 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8003 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8004 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8005 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8006 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8007 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8008 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8009 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8010 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8011 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8012 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8013 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8014 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8015 " ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8016 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8017 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8018 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8019 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8020 " : aaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8021 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n" 8022 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8023 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8024 " : aaaaaaaaaaaaaaaa;"); 8025 verifyFormat( 8026 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8027 " ? aaaaaaaaaaaaaaa\n" 8028 " : aaaaaaaaaaaaaaa;"); 8029 verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n" 8030 " aaaaaaaaa\n" 8031 " ? b\n" 8032 " : c);"); 8033 verifyFormat("return aaaa == bbbb\n" 8034 " // comment\n" 8035 " ? aaaa\n" 8036 " : bbbb;"); 8037 verifyFormat("unsigned Indent =\n" 8038 " format(TheLine.First,\n" 8039 " IndentForLevel[TheLine.Level] >= 0\n" 8040 " ? IndentForLevel[TheLine.Level]\n" 8041 " : TheLine * 2,\n" 8042 " TheLine.InPPDirective, PreviousEndOfLineColumn);", 8043 getLLVMStyleWithColumns(60)); 8044 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n" 8045 " ? aaaaaaaaaaaaaaa\n" 8046 " : bbbbbbbbbbbbbbb //\n" 8047 " ? ccccccccccccccc\n" 8048 " : ddddddddddddddd;"); 8049 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n" 8050 " ? aaaaaaaaaaaaaaa\n" 8051 " : (bbbbbbbbbbbbbbb //\n" 8052 " ? ccccccccccccccc\n" 8053 " : ddddddddddddddd);"); 8054 verifyFormat( 8055 "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8056 " ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 8057 " aaaaaaaaaaaaaaaaaaaaa +\n" 8058 " aaaaaaaaaaaaaaaaaaaaa\n" 8059 " : aaaaaaaaaa;"); 8060 verifyFormat( 8061 "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8062 " : aaaaaaaaaaaaaaaaaaaaaa\n" 8063 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8064 8065 FormatStyle NoBinPacking = getLLVMStyle(); 8066 NoBinPacking.BinPackArguments = false; 8067 verifyFormat( 8068 "void f() {\n" 8069 " g(aaa,\n" 8070 " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n" 8071 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8072 " ? aaaaaaaaaaaaaaa\n" 8073 " : aaaaaaaaaaaaaaa);\n" 8074 "}", 8075 NoBinPacking); 8076 verifyFormat( 8077 "void f() {\n" 8078 " g(aaa,\n" 8079 " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n" 8080 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8081 " ?: aaaaaaaaaaaaaaa);\n" 8082 "}", 8083 NoBinPacking); 8084 8085 verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n" 8086 " // comment.\n" 8087 " ccccccccccccccccccccccccccccccccccccccc\n" 8088 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8089 " : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);"); 8090 8091 // Assignments in conditional expressions. Apparently not uncommon :-(. 8092 verifyFormat("return a != b\n" 8093 " // comment\n" 8094 " ? a = b\n" 8095 " : a = b;"); 8096 verifyFormat("return a != b\n" 8097 " // comment\n" 8098 " ? a = a != b\n" 8099 " // comment\n" 8100 " ? a = b\n" 8101 " : a\n" 8102 " : a;\n"); 8103 verifyFormat("return a != b\n" 8104 " // comment\n" 8105 " ? a\n" 8106 " : a = a != b\n" 8107 " // comment\n" 8108 " ? a = b\n" 8109 " : a;"); 8110 8111 // Chained conditionals 8112 FormatStyle Style = getLLVMStyleWithColumns(70); 8113 Style.AlignOperands = FormatStyle::OAS_Align; 8114 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8115 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8116 " : 3333333333333333;", 8117 Style); 8118 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8119 " : bbbbbbbbbb ? 2222222222222222\n" 8120 " : 3333333333333333;", 8121 Style); 8122 verifyFormat("return aaaaaaaaaa ? 1111111111111111\n" 8123 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 8124 " : 3333333333333333;", 8125 Style); 8126 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8127 " : bbbbbbbbbbbbbb ? 222222\n" 8128 " : 333333;", 8129 Style); 8130 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8131 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8132 " : cccccccccccccc ? 3333333333333333\n" 8133 " : 4444444444444444;", 8134 Style); 8135 verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc)\n" 8136 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8137 " : 3333333333333333;", 8138 Style); 8139 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8140 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8141 " : (aaa ? bbb : ccc);", 8142 Style); 8143 verifyFormat( 8144 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8145 " : cccccccccccccccccc)\n" 8146 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8147 " : 3333333333333333;", 8148 Style); 8149 verifyFormat( 8150 "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8151 " : cccccccccccccccccc)\n" 8152 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8153 " : 3333333333333333;", 8154 Style); 8155 verifyFormat( 8156 "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8157 " : dddddddddddddddddd)\n" 8158 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8159 " : 3333333333333333;", 8160 Style); 8161 verifyFormat( 8162 "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8163 " : dddddddddddddddddd)\n" 8164 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8165 " : 3333333333333333;", 8166 Style); 8167 verifyFormat( 8168 "return aaaaaaaaa ? 1111111111111111\n" 8169 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8170 " : a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8171 " : dddddddddddddddddd)\n", 8172 Style); 8173 verifyFormat( 8174 "return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 8175 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8176 " : (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8177 " : cccccccccccccccccc);", 8178 Style); 8179 verifyFormat( 8180 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8181 " : ccccccccccccccc ? dddddddddddddddddd\n" 8182 " : eeeeeeeeeeeeeeeeee)\n" 8183 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8184 " : 3333333333333333;", 8185 Style); 8186 verifyFormat( 8187 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8188 " : ccccccccccccccc ? dddddddddddddddddd\n" 8189 " : eeeeeeeeeeeeeeeeee)\n" 8190 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8191 " : 3333333333333333;", 8192 Style); 8193 verifyFormat( 8194 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8195 " : cccccccccccc ? dddddddddddddddddd\n" 8196 " : eeeeeeeeeeeeeeeeee)\n" 8197 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8198 " : 3333333333333333;", 8199 Style); 8200 verifyFormat( 8201 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8202 " : cccccccccccccccccc\n" 8203 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8204 " : 3333333333333333;", 8205 Style); 8206 verifyFormat( 8207 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8208 " : cccccccccccccccc ? dddddddddddddddddd\n" 8209 " : eeeeeeeeeeeeeeeeee\n" 8210 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 8211 " : 3333333333333333;", 8212 Style); 8213 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa\n" 8214 " ? (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8215 " : cccccccccccccccccc ? dddddddddddddddddd\n" 8216 " : eeeeeeeeeeeeeeeeee)\n" 8217 " : bbbbbbbbbbbbbbbbbbb ? 2222222222222222\n" 8218 " : 3333333333333333;", 8219 Style); 8220 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaa\n" 8221 " ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 8222 " : cccccccccccccccc ? dddddddddddddddddd\n" 8223 " : eeeeeeeeeeeeeeeeee\n" 8224 " : bbbbbbbbbbbbbbbbbbbbbbb ? 2222222222222222\n" 8225 " : 3333333333333333;", 8226 Style); 8227 8228 Style.AlignOperands = FormatStyle::OAS_DontAlign; 8229 Style.BreakBeforeTernaryOperators = false; 8230 // FIXME: Aligning the question marks is weird given DontAlign. 8231 // Consider disabling this alignment in this case. Also check whether this 8232 // will render the adjustment from https://reviews.llvm.org/D82199 8233 // unnecessary. 8234 verifyFormat("int x = aaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa :\n" 8235 " bbbb ? cccccccccccccccccc :\n" 8236 " ddddd;\n", 8237 Style); 8238 8239 EXPECT_EQ( 8240 "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n" 8241 " /*\n" 8242 " */\n" 8243 " function() {\n" 8244 " try {\n" 8245 " return JJJJJJJJJJJJJJ(\n" 8246 " pppppppppppppppppppppppppppppppppppppppppppppppppp);\n" 8247 " }\n" 8248 " } :\n" 8249 " function() {};", 8250 format( 8251 "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n" 8252 " /*\n" 8253 " */\n" 8254 " function() {\n" 8255 " try {\n" 8256 " return JJJJJJJJJJJJJJ(\n" 8257 " pppppppppppppppppppppppppppppppppppppppppppppppppp);\n" 8258 " }\n" 8259 " } :\n" 8260 " function() {};", 8261 getGoogleStyle(FormatStyle::LK_JavaScript))); 8262 } 8263 8264 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) { 8265 FormatStyle Style = getLLVMStyleWithColumns(70); 8266 Style.BreakBeforeTernaryOperators = false; 8267 verifyFormat( 8268 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8269 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8270 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8271 Style); 8272 verifyFormat( 8273 "aaaa(aaaaaaaaaa, aaaaaaaa,\n" 8274 " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8275 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8276 Style); 8277 verifyFormat( 8278 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8279 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8280 Style); 8281 verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n" 8282 " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8283 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8284 Style); 8285 verifyFormat( 8286 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n" 8287 " aaaaaaaaaaaaa);", 8288 Style); 8289 verifyFormat( 8290 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8291 " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8292 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8293 " aaaaaaaaaaaaa);", 8294 Style); 8295 verifyFormat( 8296 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8297 " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8298 " aaaaaaaaaaaaa);", 8299 Style); 8300 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8301 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8302 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 8303 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8304 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8305 Style); 8306 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8307 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8308 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8309 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 8310 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8311 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8312 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8313 Style); 8314 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8315 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n" 8316 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8317 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 8318 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8319 Style); 8320 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8321 " aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8322 " aaaaaaaaaaaaaaaaaaaaaaaaaaa;", 8323 Style); 8324 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n" 8325 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8326 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 8327 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 8328 Style); 8329 verifyFormat( 8330 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8331 " aaaaaaaaaaaaaaa :\n" 8332 " aaaaaaaaaaaaaaa;", 8333 Style); 8334 verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n" 8335 " aaaaaaaaa ?\n" 8336 " b :\n" 8337 " c);", 8338 Style); 8339 verifyFormat("unsigned Indent =\n" 8340 " format(TheLine.First,\n" 8341 " IndentForLevel[TheLine.Level] >= 0 ?\n" 8342 " IndentForLevel[TheLine.Level] :\n" 8343 " TheLine * 2,\n" 8344 " TheLine.InPPDirective, PreviousEndOfLineColumn);", 8345 Style); 8346 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n" 8347 " aaaaaaaaaaaaaaa :\n" 8348 " bbbbbbbbbbbbbbb ? //\n" 8349 " ccccccccccccccc :\n" 8350 " ddddddddddddddd;", 8351 Style); 8352 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n" 8353 " aaaaaaaaaaaaaaa :\n" 8354 " (bbbbbbbbbbbbbbb ? //\n" 8355 " ccccccccccccccc :\n" 8356 " ddddddddddddddd);", 8357 Style); 8358 verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8359 " /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n" 8360 " ccccccccccccccccccccccccccc;", 8361 Style); 8362 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 8363 " aaaaa :\n" 8364 " bbbbbbbbbbbbbbb + cccccccccccccccc;", 8365 Style); 8366 8367 // Chained conditionals 8368 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8369 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8370 " 3333333333333333;", 8371 Style); 8372 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8373 " bbbbbbbbbb ? 2222222222222222 :\n" 8374 " 3333333333333333;", 8375 Style); 8376 verifyFormat("return aaaaaaaaaa ? 1111111111111111 :\n" 8377 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8378 " 3333333333333333;", 8379 Style); 8380 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8381 " bbbbbbbbbbbbbbbb ? 222222 :\n" 8382 " 333333;", 8383 Style); 8384 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8385 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8386 " cccccccccccccccc ? 3333333333333333 :\n" 8387 " 4444444444444444;", 8388 Style); 8389 verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc) :\n" 8390 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8391 " 3333333333333333;", 8392 Style); 8393 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8394 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8395 " (aaa ? bbb : ccc);", 8396 Style); 8397 verifyFormat( 8398 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8399 " cccccccccccccccccc) :\n" 8400 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8401 " 3333333333333333;", 8402 Style); 8403 verifyFormat( 8404 "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8405 " cccccccccccccccccc) :\n" 8406 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8407 " 3333333333333333;", 8408 Style); 8409 verifyFormat( 8410 "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8411 " dddddddddddddddddd) :\n" 8412 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8413 " 3333333333333333;", 8414 Style); 8415 verifyFormat( 8416 "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8417 " dddddddddddddddddd) :\n" 8418 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8419 " 3333333333333333;", 8420 Style); 8421 verifyFormat( 8422 "return aaaaaaaaa ? 1111111111111111 :\n" 8423 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8424 " a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8425 " dddddddddddddddddd)\n", 8426 Style); 8427 verifyFormat( 8428 "return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 8429 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8430 " (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8431 " cccccccccccccccccc);", 8432 Style); 8433 verifyFormat( 8434 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8435 " ccccccccccccccccc ? dddddddddddddddddd :\n" 8436 " eeeeeeeeeeeeeeeeee) :\n" 8437 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8438 " 3333333333333333;", 8439 Style); 8440 verifyFormat( 8441 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8442 " ccccccccccccc ? dddddddddddddddddd :\n" 8443 " eeeeeeeeeeeeeeeeee) :\n" 8444 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8445 " 3333333333333333;", 8446 Style); 8447 verifyFormat( 8448 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8449 " ccccccccccccccccc ? dddddddddddddddddd :\n" 8450 " eeeeeeeeeeeeeeeeee) :\n" 8451 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8452 " 3333333333333333;", 8453 Style); 8454 verifyFormat( 8455 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8456 " cccccccccccccccccc :\n" 8457 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8458 " 3333333333333333;", 8459 Style); 8460 verifyFormat( 8461 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8462 " cccccccccccccccccc ? dddddddddddddddddd :\n" 8463 " eeeeeeeeeeeeeeeeee :\n" 8464 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8465 " 3333333333333333;", 8466 Style); 8467 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n" 8468 " (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8469 " cccccccccccccccccc ? dddddddddddddddddd :\n" 8470 " eeeeeeeeeeeeeeeeee) :\n" 8471 " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8472 " 3333333333333333;", 8473 Style); 8474 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n" 8475 " aaaaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8476 " cccccccccccccccccccc ? dddddddddddddddddd :\n" 8477 " eeeeeeeeeeeeeeeeee :\n" 8478 " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8479 " 3333333333333333;", 8480 Style); 8481 } 8482 8483 TEST_F(FormatTest, DeclarationsOfMultipleVariables) { 8484 verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n" 8485 " aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();"); 8486 verifyFormat("bool a = true, b = false;"); 8487 8488 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n" 8489 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n" 8490 " bbbbbbbbbbbbbbbbbbbbbbbbb =\n" 8491 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);"); 8492 verifyFormat( 8493 "bool aaaaaaaaaaaaaaaaaaaaa =\n" 8494 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n" 8495 " d = e && f;"); 8496 verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n" 8497 " c = cccccccccccccccccccc, d = dddddddddddddddddddd;"); 8498 verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n" 8499 " *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;"); 8500 verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n" 8501 " ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;"); 8502 8503 FormatStyle Style = getGoogleStyle(); 8504 Style.PointerAlignment = FormatStyle::PAS_Left; 8505 Style.DerivePointerAlignment = false; 8506 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8507 " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n" 8508 " *b = bbbbbbbbbbbbbbbbbbb;", 8509 Style); 8510 verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n" 8511 " *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;", 8512 Style); 8513 verifyFormat("vector<int*> a, b;", Style); 8514 verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style); 8515 verifyFormat("/*comment*/ for (int *p, *q; p != q; p = p->next) {\n}", Style); 8516 verifyFormat("if (int *p, *q; p != q) {\n p = p->next;\n}", Style); 8517 verifyFormat("/*comment*/ if (int *p, *q; p != q) {\n p = p->next;\n}", 8518 Style); 8519 verifyFormat("switch (int *p, *q; p != q) {\n default:\n break;\n}", 8520 Style); 8521 verifyFormat( 8522 "/*comment*/ switch (int *p, *q; p != q) {\n default:\n break;\n}", 8523 Style); 8524 8525 verifyFormat("if ([](int* p, int* q) {}()) {\n}", Style); 8526 verifyFormat("for ([](int* p, int* q) {}();;) {\n}", Style); 8527 verifyFormat("for (; [](int* p, int* q) {}();) {\n}", Style); 8528 verifyFormat("for (;; [](int* p, int* q) {}()) {\n}", Style); 8529 verifyFormat("switch ([](int* p, int* q) {}()) {\n default:\n break;\n}", 8530 Style); 8531 } 8532 8533 TEST_F(FormatTest, ConditionalExpressionsInBrackets) { 8534 verifyFormat("arr[foo ? bar : baz];"); 8535 verifyFormat("f()[foo ? bar : baz];"); 8536 verifyFormat("(a + b)[foo ? bar : baz];"); 8537 verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];"); 8538 } 8539 8540 TEST_F(FormatTest, AlignsStringLiterals) { 8541 verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n" 8542 " \"short literal\");"); 8543 verifyFormat( 8544 "looooooooooooooooooooooooongFunction(\n" 8545 " \"short literal\"\n" 8546 " \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");"); 8547 verifyFormat("someFunction(\"Always break between multi-line\"\n" 8548 " \" string literals\",\n" 8549 " and, other, parameters);"); 8550 EXPECT_EQ("fun + \"1243\" /* comment */\n" 8551 " \"5678\";", 8552 format("fun + \"1243\" /* comment */\n" 8553 " \"5678\";", 8554 getLLVMStyleWithColumns(28))); 8555 EXPECT_EQ( 8556 "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 8557 " \"aaaaaaaaaaaaaaaaaaaaa\"\n" 8558 " \"aaaaaaaaaaaaaaaa\";", 8559 format("aaaaaa =" 8560 "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa " 8561 "aaaaaaaaaaaaaaaaaaaaa\" " 8562 "\"aaaaaaaaaaaaaaaa\";")); 8563 verifyFormat("a = a + \"a\"\n" 8564 " \"a\"\n" 8565 " \"a\";"); 8566 verifyFormat("f(\"a\", \"b\"\n" 8567 " \"c\");"); 8568 8569 verifyFormat( 8570 "#define LL_FORMAT \"ll\"\n" 8571 "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n" 8572 " \"d, ddddddddd: %\" LL_FORMAT \"d\");"); 8573 8574 verifyFormat("#define A(X) \\\n" 8575 " \"aaaaa\" #X \"bbbbbb\" \\\n" 8576 " \"ccccc\"", 8577 getLLVMStyleWithColumns(23)); 8578 verifyFormat("#define A \"def\"\n" 8579 "f(\"abc\" A \"ghi\"\n" 8580 " \"jkl\");"); 8581 8582 verifyFormat("f(L\"a\"\n" 8583 " L\"b\");"); 8584 verifyFormat("#define A(X) \\\n" 8585 " L\"aaaaa\" #X L\"bbbbbb\" \\\n" 8586 " L\"ccccc\"", 8587 getLLVMStyleWithColumns(25)); 8588 8589 verifyFormat("f(@\"a\"\n" 8590 " @\"b\");"); 8591 verifyFormat("NSString s = @\"a\"\n" 8592 " @\"b\"\n" 8593 " @\"c\";"); 8594 verifyFormat("NSString s = @\"a\"\n" 8595 " \"b\"\n" 8596 " \"c\";"); 8597 } 8598 8599 TEST_F(FormatTest, ReturnTypeBreakingStyle) { 8600 FormatStyle Style = getLLVMStyle(); 8601 // No declarations or definitions should be moved to own line. 8602 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None; 8603 verifyFormat("class A {\n" 8604 " int f() { return 1; }\n" 8605 " int g();\n" 8606 "};\n" 8607 "int f() { return 1; }\n" 8608 "int g();\n", 8609 Style); 8610 8611 // All declarations and definitions should have the return type moved to its 8612 // own line. 8613 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 8614 Style.TypenameMacros = {"LIST"}; 8615 verifyFormat("SomeType\n" 8616 "funcdecl(LIST(uint64_t));", 8617 Style); 8618 verifyFormat("class E {\n" 8619 " int\n" 8620 " f() {\n" 8621 " return 1;\n" 8622 " }\n" 8623 " int\n" 8624 " g();\n" 8625 "};\n" 8626 "int\n" 8627 "f() {\n" 8628 " return 1;\n" 8629 "}\n" 8630 "int\n" 8631 "g();\n", 8632 Style); 8633 8634 // Top-level definitions, and no kinds of declarations should have the 8635 // return type moved to its own line. 8636 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions; 8637 verifyFormat("class B {\n" 8638 " int f() { return 1; }\n" 8639 " int g();\n" 8640 "};\n" 8641 "int\n" 8642 "f() {\n" 8643 " return 1;\n" 8644 "}\n" 8645 "int g();\n", 8646 Style); 8647 8648 // Top-level definitions and declarations should have the return type moved 8649 // to its own line. 8650 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel; 8651 verifyFormat("class C {\n" 8652 " int f() { return 1; }\n" 8653 " int g();\n" 8654 "};\n" 8655 "int\n" 8656 "f() {\n" 8657 " return 1;\n" 8658 "}\n" 8659 "int\n" 8660 "g();\n", 8661 Style); 8662 8663 // All definitions should have the return type moved to its own line, but no 8664 // kinds of declarations. 8665 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions; 8666 verifyFormat("class D {\n" 8667 " int\n" 8668 " f() {\n" 8669 " return 1;\n" 8670 " }\n" 8671 " int g();\n" 8672 "};\n" 8673 "int\n" 8674 "f() {\n" 8675 " return 1;\n" 8676 "}\n" 8677 "int g();\n", 8678 Style); 8679 verifyFormat("const char *\n" 8680 "f(void) {\n" // Break here. 8681 " return \"\";\n" 8682 "}\n" 8683 "const char *bar(void);\n", // No break here. 8684 Style); 8685 verifyFormat("template <class T>\n" 8686 "T *\n" 8687 "f(T &c) {\n" // Break here. 8688 " return NULL;\n" 8689 "}\n" 8690 "template <class T> T *f(T &c);\n", // No break here. 8691 Style); 8692 verifyFormat("class C {\n" 8693 " int\n" 8694 " operator+() {\n" 8695 " return 1;\n" 8696 " }\n" 8697 " int\n" 8698 " operator()() {\n" 8699 " return 1;\n" 8700 " }\n" 8701 "};\n", 8702 Style); 8703 verifyFormat("void\n" 8704 "A::operator()() {}\n" 8705 "void\n" 8706 "A::operator>>() {}\n" 8707 "void\n" 8708 "A::operator+() {}\n" 8709 "void\n" 8710 "A::operator*() {}\n" 8711 "void\n" 8712 "A::operator->() {}\n" 8713 "void\n" 8714 "A::operator void *() {}\n" 8715 "void\n" 8716 "A::operator void &() {}\n" 8717 "void\n" 8718 "A::operator void &&() {}\n" 8719 "void\n" 8720 "A::operator char *() {}\n" 8721 "void\n" 8722 "A::operator[]() {}\n" 8723 "void\n" 8724 "A::operator!() {}\n" 8725 "void\n" 8726 "A::operator**() {}\n" 8727 "void\n" 8728 "A::operator<Foo> *() {}\n" 8729 "void\n" 8730 "A::operator<Foo> **() {}\n" 8731 "void\n" 8732 "A::operator<Foo> &() {}\n" 8733 "void\n" 8734 "A::operator void **() {}\n", 8735 Style); 8736 verifyFormat("constexpr auto\n" 8737 "operator()() const -> reference {}\n" 8738 "constexpr auto\n" 8739 "operator>>() const -> reference {}\n" 8740 "constexpr auto\n" 8741 "operator+() const -> reference {}\n" 8742 "constexpr auto\n" 8743 "operator*() const -> reference {}\n" 8744 "constexpr auto\n" 8745 "operator->() const -> reference {}\n" 8746 "constexpr auto\n" 8747 "operator++() const -> reference {}\n" 8748 "constexpr auto\n" 8749 "operator void *() const -> reference {}\n" 8750 "constexpr auto\n" 8751 "operator void **() const -> reference {}\n" 8752 "constexpr auto\n" 8753 "operator void *() const -> reference {}\n" 8754 "constexpr auto\n" 8755 "operator void &() const -> reference {}\n" 8756 "constexpr auto\n" 8757 "operator void &&() const -> reference {}\n" 8758 "constexpr auto\n" 8759 "operator char *() const -> reference {}\n" 8760 "constexpr auto\n" 8761 "operator!() const -> reference {}\n" 8762 "constexpr auto\n" 8763 "operator[]() const -> reference {}\n", 8764 Style); 8765 verifyFormat("void *operator new(std::size_t s);", // No break here. 8766 Style); 8767 verifyFormat("void *\n" 8768 "operator new(std::size_t s) {}", 8769 Style); 8770 verifyFormat("void *\n" 8771 "operator delete[](void *ptr) {}", 8772 Style); 8773 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 8774 verifyFormat("const char *\n" 8775 "f(void)\n" // Break here. 8776 "{\n" 8777 " return \"\";\n" 8778 "}\n" 8779 "const char *bar(void);\n", // No break here. 8780 Style); 8781 verifyFormat("template <class T>\n" 8782 "T *\n" // Problem here: no line break 8783 "f(T &c)\n" // Break here. 8784 "{\n" 8785 " return NULL;\n" 8786 "}\n" 8787 "template <class T> T *f(T &c);\n", // No break here. 8788 Style); 8789 verifyFormat("int\n" 8790 "foo(A<bool> a)\n" 8791 "{\n" 8792 " return a;\n" 8793 "}\n", 8794 Style); 8795 verifyFormat("int\n" 8796 "foo(A<8> a)\n" 8797 "{\n" 8798 " return a;\n" 8799 "}\n", 8800 Style); 8801 verifyFormat("int\n" 8802 "foo(A<B<bool>, 8> a)\n" 8803 "{\n" 8804 " return a;\n" 8805 "}\n", 8806 Style); 8807 verifyFormat("int\n" 8808 "foo(A<B<8>, bool> a)\n" 8809 "{\n" 8810 " return a;\n" 8811 "}\n", 8812 Style); 8813 verifyFormat("int\n" 8814 "foo(A<B<bool>, bool> a)\n" 8815 "{\n" 8816 " return a;\n" 8817 "}\n", 8818 Style); 8819 verifyFormat("int\n" 8820 "foo(A<B<8>, 8> a)\n" 8821 "{\n" 8822 " return a;\n" 8823 "}\n", 8824 Style); 8825 8826 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 8827 Style.BraceWrapping.AfterFunction = true; 8828 verifyFormat("int f(i);\n" // No break here. 8829 "int\n" // Break here. 8830 "f(i)\n" 8831 "{\n" 8832 " return i + 1;\n" 8833 "}\n" 8834 "int\n" // Break here. 8835 "f(i)\n" 8836 "{\n" 8837 " return i + 1;\n" 8838 "};", 8839 Style); 8840 verifyFormat("int f(a, b, c);\n" // No break here. 8841 "int\n" // Break here. 8842 "f(a, b, c)\n" // Break here. 8843 "short a, b;\n" 8844 "float c;\n" 8845 "{\n" 8846 " return a + b < c;\n" 8847 "}\n" 8848 "int\n" // Break here. 8849 "f(a, b, c)\n" // Break here. 8850 "short a, b;\n" 8851 "float c;\n" 8852 "{\n" 8853 " return a + b < c;\n" 8854 "};", 8855 Style); 8856 verifyFormat("byte *\n" // Break here. 8857 "f(a)\n" // Break here. 8858 "byte a[];\n" 8859 "{\n" 8860 " return a;\n" 8861 "}", 8862 Style); 8863 verifyFormat("bool f(int a, int) override;\n" 8864 "Bar g(int a, Bar) final;\n" 8865 "Bar h(a, Bar) final;", 8866 Style); 8867 verifyFormat("int\n" 8868 "f(a)", 8869 Style); 8870 verifyFormat("bool\n" 8871 "f(size_t = 0, bool b = false)\n" 8872 "{\n" 8873 " return !b;\n" 8874 "}", 8875 Style); 8876 8877 // The return breaking style doesn't affect: 8878 // * function and object definitions with attribute-like macros 8879 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 8880 " ABSL_GUARDED_BY(mutex) = {};", 8881 getGoogleStyleWithColumns(40)); 8882 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 8883 " ABSL_GUARDED_BY(mutex); // comment", 8884 getGoogleStyleWithColumns(40)); 8885 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 8886 " ABSL_GUARDED_BY(mutex1)\n" 8887 " ABSL_GUARDED_BY(mutex2);", 8888 getGoogleStyleWithColumns(40)); 8889 verifyFormat("Tttttt f(int a, int b)\n" 8890 " ABSL_GUARDED_BY(mutex1)\n" 8891 " ABSL_GUARDED_BY(mutex2);", 8892 getGoogleStyleWithColumns(40)); 8893 // * typedefs 8894 verifyFormat("typedef ATTR(X) char x;", getGoogleStyle()); 8895 8896 Style = getGNUStyle(); 8897 8898 // Test for comments at the end of function declarations. 8899 verifyFormat("void\n" 8900 "foo (int a, /*abc*/ int b) // def\n" 8901 "{\n" 8902 "}\n", 8903 Style); 8904 8905 verifyFormat("void\n" 8906 "foo (int a, /* abc */ int b) /* def */\n" 8907 "{\n" 8908 "}\n", 8909 Style); 8910 8911 // Definitions that should not break after return type 8912 verifyFormat("void foo (int a, int b); // def\n", Style); 8913 verifyFormat("void foo (int a, int b); /* def */\n", Style); 8914 verifyFormat("void foo (int a, int b);\n", Style); 8915 } 8916 8917 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) { 8918 FormatStyle NoBreak = getLLVMStyle(); 8919 NoBreak.AlwaysBreakBeforeMultilineStrings = false; 8920 FormatStyle Break = getLLVMStyle(); 8921 Break.AlwaysBreakBeforeMultilineStrings = true; 8922 verifyFormat("aaaa = \"bbbb\"\n" 8923 " \"cccc\";", 8924 NoBreak); 8925 verifyFormat("aaaa =\n" 8926 " \"bbbb\"\n" 8927 " \"cccc\";", 8928 Break); 8929 verifyFormat("aaaa(\"bbbb\"\n" 8930 " \"cccc\");", 8931 NoBreak); 8932 verifyFormat("aaaa(\n" 8933 " \"bbbb\"\n" 8934 " \"cccc\");", 8935 Break); 8936 verifyFormat("aaaa(qqq, \"bbbb\"\n" 8937 " \"cccc\");", 8938 NoBreak); 8939 verifyFormat("aaaa(qqq,\n" 8940 " \"bbbb\"\n" 8941 " \"cccc\");", 8942 Break); 8943 verifyFormat("aaaa(qqq,\n" 8944 " L\"bbbb\"\n" 8945 " L\"cccc\");", 8946 Break); 8947 verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n" 8948 " \"bbbb\"));", 8949 Break); 8950 verifyFormat("string s = someFunction(\n" 8951 " \"abc\"\n" 8952 " \"abc\");", 8953 Break); 8954 8955 // As we break before unary operators, breaking right after them is bad. 8956 verifyFormat("string foo = abc ? \"x\"\n" 8957 " \"blah blah blah blah blah blah\"\n" 8958 " : \"y\";", 8959 Break); 8960 8961 // Don't break if there is no column gain. 8962 verifyFormat("f(\"aaaa\"\n" 8963 " \"bbbb\");", 8964 Break); 8965 8966 // Treat literals with escaped newlines like multi-line string literals. 8967 EXPECT_EQ("x = \"a\\\n" 8968 "b\\\n" 8969 "c\";", 8970 format("x = \"a\\\n" 8971 "b\\\n" 8972 "c\";", 8973 NoBreak)); 8974 EXPECT_EQ("xxxx =\n" 8975 " \"a\\\n" 8976 "b\\\n" 8977 "c\";", 8978 format("xxxx = \"a\\\n" 8979 "b\\\n" 8980 "c\";", 8981 Break)); 8982 8983 EXPECT_EQ("NSString *const kString =\n" 8984 " @\"aaaa\"\n" 8985 " @\"bbbb\";", 8986 format("NSString *const kString = @\"aaaa\"\n" 8987 "@\"bbbb\";", 8988 Break)); 8989 8990 Break.ColumnLimit = 0; 8991 verifyFormat("const char *hello = \"hello llvm\";", Break); 8992 } 8993 8994 TEST_F(FormatTest, AlignsPipes) { 8995 verifyFormat( 8996 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8997 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8998 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8999 verifyFormat( 9000 "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n" 9001 " << aaaaaaaaaaaaaaaaaaaa;"); 9002 verifyFormat( 9003 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9004 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9005 verifyFormat( 9006 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 9007 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9008 verifyFormat( 9009 "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n" 9010 " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n" 9011 " << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";"); 9012 verifyFormat( 9013 "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9014 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9015 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9016 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9017 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9018 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9019 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 9020 verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n" 9021 " << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);"); 9022 verifyFormat( 9023 "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9024 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9025 verifyFormat( 9026 "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n" 9027 " aaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9028 9029 verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n" 9030 " << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();"); 9031 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9032 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9033 " aaaaaaaaaaaaaaaaaaaaa)\n" 9034 " << aaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9035 verifyFormat("LOG_IF(aaa == //\n" 9036 " bbb)\n" 9037 " << a << b;"); 9038 9039 // But sometimes, breaking before the first "<<" is desirable. 9040 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 9041 " << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);"); 9042 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n" 9043 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9044 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9045 verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n" 9046 " << BEF << IsTemplate << Description << E->getType();"); 9047 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 9048 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9049 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9050 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 9051 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9052 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9053 " << aaa;"); 9054 9055 verifyFormat( 9056 "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9057 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9058 9059 // Incomplete string literal. 9060 EXPECT_EQ("llvm::errs() << \"\n" 9061 " << a;", 9062 format("llvm::errs() << \"\n<<a;")); 9063 9064 verifyFormat("void f() {\n" 9065 " CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n" 9066 " << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n" 9067 "}"); 9068 9069 // Handle 'endl'. 9070 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n" 9071 " << bbbbbbbbbbbbbbbbbbbbbb << endl;"); 9072 verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;"); 9073 9074 // Handle '\n'. 9075 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n" 9076 " << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";"); 9077 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n" 9078 " << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';"); 9079 verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n" 9080 " << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";"); 9081 verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";"); 9082 } 9083 9084 TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) { 9085 verifyFormat("return out << \"somepacket = {\\n\"\n" 9086 " << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n" 9087 " << \" bbbb = \" << pkt.bbbb << \"\\n\"\n" 9088 " << \" cccccc = \" << pkt.cccccc << \"\\n\"\n" 9089 " << \" ddd = [\" << pkt.ddd << \"]\\n\"\n" 9090 " << \"}\";"); 9091 9092 verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n" 9093 " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n" 9094 " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;"); 9095 verifyFormat( 9096 "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n" 9097 " << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n" 9098 " << \"ccccccccccccccccc = \" << ccccccccccccccccc\n" 9099 " << \"ddddddddddddddddd = \" << ddddddddddddddddd\n" 9100 " << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;"); 9101 verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n" 9102 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 9103 verifyFormat( 9104 "void f() {\n" 9105 " llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n" 9106 " << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 9107 "}"); 9108 9109 // Breaking before the first "<<" is generally not desirable. 9110 verifyFormat( 9111 "llvm::errs()\n" 9112 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9113 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9114 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9115 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 9116 getLLVMStyleWithColumns(70)); 9117 verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n" 9118 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9119 " << \"aaaaaaaaaaaaaaaaaaa: \"\n" 9120 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9121 " << \"aaaaaaaaaaaaaaaaaaa: \"\n" 9122 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 9123 getLLVMStyleWithColumns(70)); 9124 9125 verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n" 9126 " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n" 9127 " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;"); 9128 verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n" 9129 " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n" 9130 " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);"); 9131 verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n" 9132 " (aaaa + aaaa);", 9133 getLLVMStyleWithColumns(40)); 9134 verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n" 9135 " (aaaaaaa + aaaaa));", 9136 getLLVMStyleWithColumns(40)); 9137 verifyFormat( 9138 "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n" 9139 " SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n" 9140 " bbbbbbbbbbbbbbbbbbbbbbb);"); 9141 } 9142 9143 TEST_F(FormatTest, UnderstandsEquals) { 9144 verifyFormat( 9145 "aaaaaaaaaaaaaaaaa =\n" 9146 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 9147 verifyFormat( 9148 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9149 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 9150 verifyFormat( 9151 "if (a) {\n" 9152 " f();\n" 9153 "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9154 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 9155 "}"); 9156 9157 verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9158 " 100000000 + 10000000) {\n}"); 9159 } 9160 9161 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) { 9162 verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n" 9163 " .looooooooooooooooooooooooooooooooooooooongFunction();"); 9164 9165 verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n" 9166 " ->looooooooooooooooooooooooooooooooooooooongFunction();"); 9167 9168 verifyFormat( 9169 "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n" 9170 " Parameter2);"); 9171 9172 verifyFormat( 9173 "ShortObject->shortFunction(\n" 9174 " LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n" 9175 " LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);"); 9176 9177 verifyFormat("loooooooooooooongFunction(\n" 9178 " LoooooooooooooongObject->looooooooooooooooongFunction());"); 9179 9180 verifyFormat( 9181 "function(LoooooooooooooooooooooooooooooooooooongObject\n" 9182 " ->loooooooooooooooooooooooooooooooooooooooongFunction());"); 9183 9184 verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n" 9185 " .WillRepeatedly(Return(SomeValue));"); 9186 verifyFormat("void f() {\n" 9187 " EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n" 9188 " .Times(2)\n" 9189 " .WillRepeatedly(Return(SomeValue));\n" 9190 "}"); 9191 verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n" 9192 " ccccccccccccccccccccccc);"); 9193 verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9194 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9195 " .aaaaa(aaaaa),\n" 9196 " aaaaaaaaaaaaaaaaaaaaa);"); 9197 verifyFormat("void f() {\n" 9198 " aaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9199 " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n" 9200 "}"); 9201 verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9202 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9203 " .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9204 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9205 " aaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 9206 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9207 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9208 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9209 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n" 9210 "}"); 9211 9212 // Here, it is not necessary to wrap at "." or "->". 9213 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n" 9214 " aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 9215 verifyFormat( 9216 "aaaaaaaaaaa->aaaaaaaaa(\n" 9217 " aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9218 " aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n"); 9219 9220 verifyFormat( 9221 "aaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9222 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());"); 9223 verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n" 9224 " aaaaaaaaa()->aaaaaa()->aaaaa());"); 9225 verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n" 9226 " aaaaaaaaa()->aaaaaa()->aaaaa());"); 9227 9228 verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9229 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9230 " .a();"); 9231 9232 FormatStyle NoBinPacking = getLLVMStyle(); 9233 NoBinPacking.BinPackParameters = false; 9234 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n" 9235 " .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n" 9236 " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n" 9237 " aaaaaaaaaaaaaaaaaaa,\n" 9238 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 9239 NoBinPacking); 9240 9241 // If there is a subsequent call, change to hanging indentation. 9242 verifyFormat( 9243 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9244 " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n" 9245 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9246 verifyFormat( 9247 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9248 " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));"); 9249 verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9250 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9251 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9252 verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9253 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 9254 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());"); 9255 } 9256 9257 TEST_F(FormatTest, WrapsTemplateDeclarations) { 9258 verifyFormat("template <typename T>\n" 9259 "virtual void loooooooooooongFunction(int Param1, int Param2);"); 9260 verifyFormat("template <typename T>\n" 9261 "// T should be one of {A, B}.\n" 9262 "virtual void loooooooooooongFunction(int Param1, int Param2);"); 9263 verifyFormat( 9264 "template <typename T>\n" 9265 "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;"); 9266 verifyFormat("template <typename T>\n" 9267 "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n" 9268 " int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);"); 9269 verifyFormat( 9270 "template <typename T>\n" 9271 "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n" 9272 " int Paaaaaaaaaaaaaaaaaaaaram2);"); 9273 verifyFormat( 9274 "template <typename T>\n" 9275 "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n" 9276 " aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n" 9277 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9278 verifyFormat("template <typename T>\n" 9279 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9280 " int aaaaaaaaaaaaaaaaaaaaaa);"); 9281 verifyFormat( 9282 "template <typename T1, typename T2 = char, typename T3 = char,\n" 9283 " typename T4 = char>\n" 9284 "void f();"); 9285 verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n" 9286 " template <typename> class cccccccccccccccccccccc,\n" 9287 " typename ddddddddddddd>\n" 9288 "class C {};"); 9289 verifyFormat( 9290 "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n" 9291 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9292 9293 verifyFormat("void f() {\n" 9294 " a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n" 9295 " a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n" 9296 "}"); 9297 9298 verifyFormat("template <typename T> class C {};"); 9299 verifyFormat("template <typename T> void f();"); 9300 verifyFormat("template <typename T> void f() {}"); 9301 verifyFormat( 9302 "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n" 9303 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9304 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n" 9305 " new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n" 9306 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9307 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n" 9308 " bbbbbbbbbbbbbbbbbbbbbbbb);", 9309 getLLVMStyleWithColumns(72)); 9310 EXPECT_EQ("static_cast<A< //\n" 9311 " B> *>(\n" 9312 "\n" 9313 ");", 9314 format("static_cast<A<//\n" 9315 " B>*>(\n" 9316 "\n" 9317 " );")); 9318 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9319 " const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);"); 9320 9321 FormatStyle AlwaysBreak = getLLVMStyle(); 9322 AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 9323 verifyFormat("template <typename T>\nclass C {};", AlwaysBreak); 9324 verifyFormat("template <typename T>\nvoid f();", AlwaysBreak); 9325 verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak); 9326 verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9327 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n" 9328 " ccccccccccccccccccccccccccccccccccccccccccccccc);"); 9329 verifyFormat("template <template <typename> class Fooooooo,\n" 9330 " template <typename> class Baaaaaaar>\n" 9331 "struct C {};", 9332 AlwaysBreak); 9333 verifyFormat("template <typename T> // T can be A, B or C.\n" 9334 "struct C {};", 9335 AlwaysBreak); 9336 verifyFormat("template <enum E> class A {\n" 9337 "public:\n" 9338 " E *f();\n" 9339 "};"); 9340 9341 FormatStyle NeverBreak = getLLVMStyle(); 9342 NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No; 9343 verifyFormat("template <typename T> class C {};", NeverBreak); 9344 verifyFormat("template <typename T> void f();", NeverBreak); 9345 verifyFormat("template <typename T> void f() {}", NeverBreak); 9346 verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa " 9347 "bbbbbbbbbbbbbbbbbbbb) {}", 9348 NeverBreak); 9349 verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9350 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n" 9351 " ccccccccccccccccccccccccccccccccccccccccccccccc);", 9352 NeverBreak); 9353 verifyFormat("template <template <typename> class Fooooooo,\n" 9354 " template <typename> class Baaaaaaar>\n" 9355 "struct C {};", 9356 NeverBreak); 9357 verifyFormat("template <typename T> // T can be A, B or C.\n" 9358 "struct C {};", 9359 NeverBreak); 9360 verifyFormat("template <enum E> class A {\n" 9361 "public:\n" 9362 " E *f();\n" 9363 "};", 9364 NeverBreak); 9365 NeverBreak.PenaltyBreakTemplateDeclaration = 100; 9366 verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa " 9367 "bbbbbbbbbbbbbbbbbbbb) {}", 9368 NeverBreak); 9369 } 9370 9371 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) { 9372 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp); 9373 Style.ColumnLimit = 60; 9374 EXPECT_EQ("// Baseline - no comments.\n" 9375 "template <\n" 9376 " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n" 9377 "void f() {}", 9378 format("// Baseline - no comments.\n" 9379 "template <\n" 9380 " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n" 9381 "void f() {}", 9382 Style)); 9383 9384 EXPECT_EQ("template <\n" 9385 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9386 "void f() {}", 9387 format("template <\n" 9388 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9389 "void f() {}", 9390 Style)); 9391 9392 EXPECT_EQ( 9393 "template <\n" 9394 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n" 9395 "void f() {}", 9396 format("template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n" 9397 "void f() {}", 9398 Style)); 9399 9400 EXPECT_EQ( 9401 "template <\n" 9402 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9403 " // multiline\n" 9404 "void f() {}", 9405 format("template <\n" 9406 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 9407 " // multiline\n" 9408 "void f() {}", 9409 Style)); 9410 9411 EXPECT_EQ( 9412 "template <typename aaaaaaaaaa<\n" 9413 " bbbbbbbbbbbb>::value> // trailing loooong\n" 9414 "void f() {}", 9415 format( 9416 "template <\n" 9417 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n" 9418 "void f() {}", 9419 Style)); 9420 } 9421 9422 TEST_F(FormatTest, WrapsTemplateParameters) { 9423 FormatStyle Style = getLLVMStyle(); 9424 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 9425 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 9426 verifyFormat( 9427 "template <typename... a> struct q {};\n" 9428 "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n" 9429 " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n" 9430 " y;", 9431 Style); 9432 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 9433 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 9434 verifyFormat( 9435 "template <typename... a> struct r {};\n" 9436 "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n" 9437 " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n" 9438 " y;", 9439 Style); 9440 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 9441 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 9442 verifyFormat("template <typename... a> struct s {};\n" 9443 "extern s<\n" 9444 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9445 "aaaaaaaaaaaaaaaaaaaaaa,\n" 9446 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9447 "aaaaaaaaaaaaaaaaaaaaaa>\n" 9448 " y;", 9449 Style); 9450 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 9451 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 9452 verifyFormat("template <typename... a> struct t {};\n" 9453 "extern t<\n" 9454 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9455 "aaaaaaaaaaaaaaaaaaaaaa,\n" 9456 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9457 "aaaaaaaaaaaaaaaaaaaaaa>\n" 9458 " y;", 9459 Style); 9460 } 9461 9462 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) { 9463 verifyFormat( 9464 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9465 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9466 verifyFormat( 9467 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9468 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9469 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());"); 9470 9471 // FIXME: Should we have the extra indent after the second break? 9472 verifyFormat( 9473 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9474 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9475 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9476 9477 verifyFormat( 9478 "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n" 9479 " cccccccccccccccccccccccccccccccccccccccccccccc());"); 9480 9481 // Breaking at nested name specifiers is generally not desirable. 9482 verifyFormat( 9483 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9484 " aaaaaaaaaaaaaaaaaaaaaaa);"); 9485 9486 verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n" 9487 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9488 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9489 " aaaaaaaaaaaaaaaaaaaaa);", 9490 getLLVMStyleWithColumns(74)); 9491 9492 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9493 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9494 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9495 } 9496 9497 TEST_F(FormatTest, UnderstandsTemplateParameters) { 9498 verifyFormat("A<int> a;"); 9499 verifyFormat("A<A<A<int>>> a;"); 9500 verifyFormat("A<A<A<int, 2>, 3>, 4> a;"); 9501 verifyFormat("bool x = a < 1 || 2 > a;"); 9502 verifyFormat("bool x = 5 < f<int>();"); 9503 verifyFormat("bool x = f<int>() > 5;"); 9504 verifyFormat("bool x = 5 < a<int>::x;"); 9505 verifyFormat("bool x = a < 4 ? a > 2 : false;"); 9506 verifyFormat("bool x = f() ? a < 2 : a > 2;"); 9507 9508 verifyGoogleFormat("A<A<int>> a;"); 9509 verifyGoogleFormat("A<A<A<int>>> a;"); 9510 verifyGoogleFormat("A<A<A<A<int>>>> a;"); 9511 verifyGoogleFormat("A<A<int> > a;"); 9512 verifyGoogleFormat("A<A<A<int> > > a;"); 9513 verifyGoogleFormat("A<A<A<A<int> > > > a;"); 9514 verifyGoogleFormat("A<::A<int>> a;"); 9515 verifyGoogleFormat("A<::A> a;"); 9516 verifyGoogleFormat("A< ::A> a;"); 9517 verifyGoogleFormat("A< ::A<int> > a;"); 9518 EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle())); 9519 EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle())); 9520 EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle())); 9521 EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle())); 9522 EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };", 9523 format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle())); 9524 9525 verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp)); 9526 9527 // template closer followed by a token that starts with > or = 9528 verifyFormat("bool b = a<1> > 1;"); 9529 verifyFormat("bool b = a<1> >= 1;"); 9530 verifyFormat("int i = a<1> >> 1;"); 9531 FormatStyle Style = getLLVMStyle(); 9532 Style.SpaceBeforeAssignmentOperators = false; 9533 verifyFormat("bool b= a<1> == 1;", Style); 9534 verifyFormat("a<int> = 1;", Style); 9535 verifyFormat("a<int> >>= 1;", Style); 9536 9537 verifyFormat("test < a | b >> c;"); 9538 verifyFormat("test<test<a | b>> c;"); 9539 verifyFormat("test >> a >> b;"); 9540 verifyFormat("test << a >> b;"); 9541 9542 verifyFormat("f<int>();"); 9543 verifyFormat("template <typename T> void f() {}"); 9544 verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;"); 9545 verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : " 9546 "sizeof(char)>::type>;"); 9547 verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};"); 9548 verifyFormat("f(a.operator()<A>());"); 9549 verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9550 " .template operator()<A>());", 9551 getLLVMStyleWithColumns(35)); 9552 verifyFormat("bool_constant<a && noexcept(f())>"); 9553 verifyFormat("bool_constant<a || noexcept(f())>"); 9554 9555 // Not template parameters. 9556 verifyFormat("return a < b && c > d;"); 9557 verifyFormat("void f() {\n" 9558 " while (a < b && c > d) {\n" 9559 " }\n" 9560 "}"); 9561 verifyFormat("template <typename... Types>\n" 9562 "typename enable_if<0 < sizeof...(Types)>::type Foo() {}"); 9563 9564 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9565 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);", 9566 getLLVMStyleWithColumns(60)); 9567 verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");"); 9568 verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}"); 9569 verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <"); 9570 verifyFormat("some_templated_type<decltype([](int i) { return i; })>"); 9571 } 9572 9573 TEST_F(FormatTest, UnderstandsShiftOperators) { 9574 verifyFormat("if (i < x >> 1)"); 9575 verifyFormat("while (i < x >> 1)"); 9576 verifyFormat("for (unsigned i = 0; i < i; ++i, v = v >> 1)"); 9577 verifyFormat("for (unsigned i = 0; i < x >> 1; ++i, v = v >> 1)"); 9578 verifyFormat( 9579 "for (std::vector<int>::iterator i = 0; i < x >> 1; ++i, v = v >> 1)"); 9580 verifyFormat("Foo.call<Bar<Function>>()"); 9581 verifyFormat("if (Foo.call<Bar<Function>>() == 0)"); 9582 verifyFormat("for (std::vector<std::pair<int>>::iterator i = 0; i < x >> 1; " 9583 "++i, v = v >> 1)"); 9584 verifyFormat("if (w<u<v<x>>, 1>::t)"); 9585 } 9586 9587 TEST_F(FormatTest, BitshiftOperatorWidth) { 9588 EXPECT_EQ("int a = 1 << 2; /* foo\n" 9589 " bar */", 9590 format("int a=1<<2; /* foo\n" 9591 " bar */")); 9592 9593 EXPECT_EQ("int b = 256 >> 1; /* foo\n" 9594 " bar */", 9595 format("int b =256>>1 ; /* foo\n" 9596 " bar */")); 9597 } 9598 9599 TEST_F(FormatTest, UnderstandsBinaryOperators) { 9600 verifyFormat("COMPARE(a, ==, b);"); 9601 verifyFormat("auto s = sizeof...(Ts) - 1;"); 9602 } 9603 9604 TEST_F(FormatTest, UnderstandsPointersToMembers) { 9605 verifyFormat("int A::*x;"); 9606 verifyFormat("int (S::*func)(void *);"); 9607 verifyFormat("void f() { int (S::*func)(void *); }"); 9608 verifyFormat("typedef bool *(Class::*Member)() const;"); 9609 verifyFormat("void f() {\n" 9610 " (a->*f)();\n" 9611 " a->*x;\n" 9612 " (a.*f)();\n" 9613 " ((*a).*f)();\n" 9614 " a.*x;\n" 9615 "}"); 9616 verifyFormat("void f() {\n" 9617 " (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n" 9618 " aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n" 9619 "}"); 9620 verifyFormat( 9621 "(aaaaaaaaaa->*bbbbbbb)(\n" 9622 " aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 9623 FormatStyle Style = getLLVMStyle(); 9624 Style.PointerAlignment = FormatStyle::PAS_Left; 9625 verifyFormat("typedef bool* (Class::*Member)() const;", Style); 9626 } 9627 9628 TEST_F(FormatTest, UnderstandsUnaryOperators) { 9629 verifyFormat("int a = -2;"); 9630 verifyFormat("f(-1, -2, -3);"); 9631 verifyFormat("a[-1] = 5;"); 9632 verifyFormat("int a = 5 + -2;"); 9633 verifyFormat("if (i == -1) {\n}"); 9634 verifyFormat("if (i != -1) {\n}"); 9635 verifyFormat("if (i > -1) {\n}"); 9636 verifyFormat("if (i < -1) {\n}"); 9637 verifyFormat("++(a->f());"); 9638 verifyFormat("--(a->f());"); 9639 verifyFormat("(a->f())++;"); 9640 verifyFormat("a[42]++;"); 9641 verifyFormat("if (!(a->f())) {\n}"); 9642 verifyFormat("if (!+i) {\n}"); 9643 verifyFormat("~&a;"); 9644 9645 verifyFormat("a-- > b;"); 9646 verifyFormat("b ? -a : c;"); 9647 verifyFormat("n * sizeof char16;"); 9648 verifyFormat("n * alignof char16;", getGoogleStyle()); 9649 verifyFormat("sizeof(char);"); 9650 verifyFormat("alignof(char);", getGoogleStyle()); 9651 9652 verifyFormat("return -1;"); 9653 verifyFormat("throw -1;"); 9654 verifyFormat("switch (a) {\n" 9655 "case -1:\n" 9656 " break;\n" 9657 "}"); 9658 verifyFormat("#define X -1"); 9659 verifyFormat("#define X -kConstant"); 9660 9661 verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};"); 9662 verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};"); 9663 9664 verifyFormat("int a = /* confusing comment */ -1;"); 9665 // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case. 9666 verifyFormat("int a = i /* confusing comment */++;"); 9667 9668 verifyFormat("co_yield -1;"); 9669 verifyFormat("co_return -1;"); 9670 9671 // Check that * is not treated as a binary operator when we set 9672 // PointerAlignment as PAS_Left after a keyword and not a declaration. 9673 FormatStyle PASLeftStyle = getLLVMStyle(); 9674 PASLeftStyle.PointerAlignment = FormatStyle::PAS_Left; 9675 verifyFormat("co_return *a;", PASLeftStyle); 9676 verifyFormat("co_await *a;", PASLeftStyle); 9677 verifyFormat("co_yield *a", PASLeftStyle); 9678 verifyFormat("return *a;", PASLeftStyle); 9679 } 9680 9681 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) { 9682 verifyFormat("if (!aaaaaaaaaa( // break\n" 9683 " aaaaa)) {\n" 9684 "}"); 9685 verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n" 9686 " aaaaa));"); 9687 verifyFormat("*aaa = aaaaaaa( // break\n" 9688 " bbbbbb);"); 9689 } 9690 9691 TEST_F(FormatTest, UnderstandsOverloadedOperators) { 9692 verifyFormat("bool operator<();"); 9693 verifyFormat("bool operator>();"); 9694 verifyFormat("bool operator=();"); 9695 verifyFormat("bool operator==();"); 9696 verifyFormat("bool operator!=();"); 9697 verifyFormat("int operator+();"); 9698 verifyFormat("int operator++();"); 9699 verifyFormat("int operator++(int) volatile noexcept;"); 9700 verifyFormat("bool operator,();"); 9701 verifyFormat("bool operator();"); 9702 verifyFormat("bool operator()();"); 9703 verifyFormat("bool operator[]();"); 9704 verifyFormat("operator bool();"); 9705 verifyFormat("operator int();"); 9706 verifyFormat("operator void *();"); 9707 verifyFormat("operator SomeType<int>();"); 9708 verifyFormat("operator SomeType<int, int>();"); 9709 verifyFormat("operator SomeType<SomeType<int>>();"); 9710 verifyFormat("operator< <>();"); 9711 verifyFormat("operator<< <>();"); 9712 verifyFormat("< <>"); 9713 9714 verifyFormat("void *operator new(std::size_t size);"); 9715 verifyFormat("void *operator new[](std::size_t size);"); 9716 verifyFormat("void operator delete(void *ptr);"); 9717 verifyFormat("void operator delete[](void *ptr);"); 9718 verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n" 9719 "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);"); 9720 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n" 9721 " aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;"); 9722 9723 verifyFormat( 9724 "ostream &operator<<(ostream &OutputStream,\n" 9725 " SomeReallyLongType WithSomeReallyLongValue);"); 9726 verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n" 9727 " const aaaaaaaaaaaaaaaaaaaaa &right) {\n" 9728 " return left.group < right.group;\n" 9729 "}"); 9730 verifyFormat("SomeType &operator=(const SomeType &S);"); 9731 verifyFormat("f.template operator()<int>();"); 9732 9733 verifyGoogleFormat("operator void*();"); 9734 verifyGoogleFormat("operator SomeType<SomeType<int>>();"); 9735 verifyGoogleFormat("operator ::A();"); 9736 9737 verifyFormat("using A::operator+;"); 9738 verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n" 9739 "int i;"); 9740 9741 // Calling an operator as a member function. 9742 verifyFormat("void f() { a.operator*(); }"); 9743 verifyFormat("void f() { a.operator*(b & b); }"); 9744 verifyFormat("void f() { a->operator&(a * b); }"); 9745 verifyFormat("void f() { NS::a.operator+(*b * *b); }"); 9746 // TODO: Calling an operator as a non-member function is hard to distinguish. 9747 // https://llvm.org/PR50629 9748 // verifyFormat("void f() { operator*(a & a); }"); 9749 // verifyFormat("void f() { operator&(a, b * b); }"); 9750 9751 verifyFormat("::operator delete(foo);"); 9752 verifyFormat("::operator new(n * sizeof(foo));"); 9753 verifyFormat("foo() { ::operator delete(foo); }"); 9754 verifyFormat("foo() { ::operator new(n * sizeof(foo)); }"); 9755 } 9756 9757 TEST_F(FormatTest, UnderstandsFunctionRefQualification) { 9758 verifyFormat("void A::b() && {}"); 9759 verifyFormat("void A::b() &&noexcept {}"); 9760 verifyFormat("Deleted &operator=(const Deleted &) & = default;"); 9761 verifyFormat("Deleted &operator=(const Deleted &) && = delete;"); 9762 verifyFormat("Deleted &operator=(const Deleted &) &noexcept = default;"); 9763 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;"); 9764 verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;"); 9765 verifyFormat("Deleted &operator=(const Deleted &) &;"); 9766 verifyFormat("Deleted &operator=(const Deleted &) &&;"); 9767 verifyFormat("SomeType MemberFunction(const Deleted &) &;"); 9768 verifyFormat("SomeType MemberFunction(const Deleted &) &&;"); 9769 verifyFormat("SomeType MemberFunction(const Deleted &) && {}"); 9770 verifyFormat("SomeType MemberFunction(const Deleted &) && final {}"); 9771 verifyFormat("SomeType MemberFunction(const Deleted &) && override {}"); 9772 verifyFormat("SomeType MemberFunction(const Deleted &) &&noexcept {}"); 9773 verifyFormat("void Fn(T const &) const &;"); 9774 verifyFormat("void Fn(T const volatile &&) const volatile &&;"); 9775 verifyFormat("void Fn(T const volatile &&) const volatile &&noexcept;"); 9776 verifyFormat("template <typename T>\n" 9777 "void F(T) && = delete;", 9778 getGoogleStyle()); 9779 9780 FormatStyle AlignLeft = getLLVMStyle(); 9781 AlignLeft.PointerAlignment = FormatStyle::PAS_Left; 9782 verifyFormat("void A::b() && {}", AlignLeft); 9783 verifyFormat("void A::b() && noexcept {}", AlignLeft); 9784 verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft); 9785 verifyFormat("Deleted& operator=(const Deleted&) & noexcept = default;", 9786 AlignLeft); 9787 verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;", 9788 AlignLeft); 9789 verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft); 9790 verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft); 9791 verifyFormat("auto Function(T t) & -> void {}", AlignLeft); 9792 verifyFormat("auto Function(T... t) & -> void {}", AlignLeft); 9793 verifyFormat("auto Function(T) & -> void {}", AlignLeft); 9794 verifyFormat("auto Function(T) & -> void;", AlignLeft); 9795 verifyFormat("void Fn(T const&) const&;", AlignLeft); 9796 verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft); 9797 verifyFormat("void Fn(T const volatile&&) const volatile&& noexcept;", 9798 AlignLeft); 9799 9800 FormatStyle AlignMiddle = getLLVMStyle(); 9801 AlignMiddle.PointerAlignment = FormatStyle::PAS_Middle; 9802 verifyFormat("void A::b() && {}", AlignMiddle); 9803 verifyFormat("void A::b() && noexcept {}", AlignMiddle); 9804 verifyFormat("Deleted & operator=(const Deleted &) & = default;", 9805 AlignMiddle); 9806 verifyFormat("Deleted & operator=(const Deleted &) & noexcept = default;", 9807 AlignMiddle); 9808 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", 9809 AlignMiddle); 9810 verifyFormat("Deleted & operator=(const Deleted &) &;", AlignMiddle); 9811 verifyFormat("SomeType MemberFunction(const Deleted &) &;", AlignMiddle); 9812 verifyFormat("auto Function(T t) & -> void {}", AlignMiddle); 9813 verifyFormat("auto Function(T... t) & -> void {}", AlignMiddle); 9814 verifyFormat("auto Function(T) & -> void {}", AlignMiddle); 9815 verifyFormat("auto Function(T) & -> void;", AlignMiddle); 9816 verifyFormat("void Fn(T const &) const &;", AlignMiddle); 9817 verifyFormat("void Fn(T const volatile &&) const volatile &&;", AlignMiddle); 9818 verifyFormat("void Fn(T const volatile &&) const volatile && noexcept;", 9819 AlignMiddle); 9820 9821 FormatStyle Spaces = getLLVMStyle(); 9822 Spaces.SpacesInCStyleCastParentheses = true; 9823 verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces); 9824 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces); 9825 verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces); 9826 verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces); 9827 9828 Spaces.SpacesInCStyleCastParentheses = false; 9829 Spaces.SpacesInParentheses = true; 9830 verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces); 9831 verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;", 9832 Spaces); 9833 verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces); 9834 verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces); 9835 9836 FormatStyle BreakTemplate = getLLVMStyle(); 9837 BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 9838 9839 verifyFormat("struct f {\n" 9840 " template <class T>\n" 9841 " int &foo(const std::string &str) &noexcept {}\n" 9842 "};", 9843 BreakTemplate); 9844 9845 verifyFormat("struct f {\n" 9846 " template <class T>\n" 9847 " int &foo(const std::string &str) &&noexcept {}\n" 9848 "};", 9849 BreakTemplate); 9850 9851 verifyFormat("struct f {\n" 9852 " template <class T>\n" 9853 " int &foo(const std::string &str) const &noexcept {}\n" 9854 "};", 9855 BreakTemplate); 9856 9857 verifyFormat("struct f {\n" 9858 " template <class T>\n" 9859 " int &foo(const std::string &str) const &noexcept {}\n" 9860 "};", 9861 BreakTemplate); 9862 9863 verifyFormat("struct f {\n" 9864 " template <class T>\n" 9865 " auto foo(const std::string &str) &&noexcept -> int & {}\n" 9866 "};", 9867 BreakTemplate); 9868 9869 FormatStyle AlignLeftBreakTemplate = getLLVMStyle(); 9870 AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations = 9871 FormatStyle::BTDS_Yes; 9872 AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left; 9873 9874 verifyFormat("struct f {\n" 9875 " template <class T>\n" 9876 " int& foo(const std::string& str) & noexcept {}\n" 9877 "};", 9878 AlignLeftBreakTemplate); 9879 9880 verifyFormat("struct f {\n" 9881 " template <class T>\n" 9882 " int& foo(const std::string& str) && noexcept {}\n" 9883 "};", 9884 AlignLeftBreakTemplate); 9885 9886 verifyFormat("struct f {\n" 9887 " template <class T>\n" 9888 " int& foo(const std::string& str) const& noexcept {}\n" 9889 "};", 9890 AlignLeftBreakTemplate); 9891 9892 verifyFormat("struct f {\n" 9893 " template <class T>\n" 9894 " int& foo(const std::string& str) const&& noexcept {}\n" 9895 "};", 9896 AlignLeftBreakTemplate); 9897 9898 verifyFormat("struct f {\n" 9899 " template <class T>\n" 9900 " auto foo(const std::string& str) && noexcept -> int& {}\n" 9901 "};", 9902 AlignLeftBreakTemplate); 9903 9904 // The `&` in `Type&` should not be confused with a trailing `&` of 9905 // DEPRECATED(reason) member function. 9906 verifyFormat("struct f {\n" 9907 " template <class T>\n" 9908 " DEPRECATED(reason)\n" 9909 " Type &foo(arguments) {}\n" 9910 "};", 9911 BreakTemplate); 9912 9913 verifyFormat("struct f {\n" 9914 " template <class T>\n" 9915 " DEPRECATED(reason)\n" 9916 " Type& foo(arguments) {}\n" 9917 "};", 9918 AlignLeftBreakTemplate); 9919 9920 verifyFormat("void (*foopt)(int) = &func;"); 9921 9922 FormatStyle DerivePointerAlignment = getLLVMStyle(); 9923 DerivePointerAlignment.DerivePointerAlignment = true; 9924 // There's always a space between the function and its trailing qualifiers. 9925 // This isn't evidence for PAS_Right (or for PAS_Left). 9926 std::string Prefix = "void a() &;\n" 9927 "void b() &;\n"; 9928 verifyFormat(Prefix + "int* x;", DerivePointerAlignment); 9929 verifyFormat(Prefix + "int *x;", DerivePointerAlignment); 9930 // Same if the function is an overloaded operator, and with &&. 9931 Prefix = "void operator()() &&;\n" 9932 "void operator()() &&;\n"; 9933 verifyFormat(Prefix + "int* x;", DerivePointerAlignment); 9934 verifyFormat(Prefix + "int *x;", DerivePointerAlignment); 9935 // However a space between cv-qualifiers and ref-qualifiers *is* evidence. 9936 Prefix = "void a() const &;\n" 9937 "void b() const &;\n"; 9938 EXPECT_EQ(Prefix + "int *x;", 9939 format(Prefix + "int* x;", DerivePointerAlignment)); 9940 } 9941 9942 TEST_F(FormatTest, UnderstandsNewAndDelete) { 9943 verifyFormat("void f() {\n" 9944 " A *a = new A;\n" 9945 " A *a = new (placement) A;\n" 9946 " delete a;\n" 9947 " delete (A *)a;\n" 9948 "}"); 9949 verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n" 9950 " typename aaaaaaaaaaaaaaaaaaaaaaaa();"); 9951 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9952 " new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n" 9953 " typename aaaaaaaaaaaaaaaaaaaaaaaa();"); 9954 verifyFormat("delete[] h->p;"); 9955 verifyFormat("delete[] (void *)p;"); 9956 9957 verifyFormat("void operator delete(void *foo) ATTRIB;"); 9958 verifyFormat("void operator new(void *foo) ATTRIB;"); 9959 verifyFormat("void operator delete[](void *foo) ATTRIB;"); 9960 verifyFormat("void operator delete(void *ptr) noexcept;"); 9961 9962 EXPECT_EQ("void new(link p);\n" 9963 "void delete(link p);\n", 9964 format("void new (link p);\n" 9965 "void delete (link p);\n")); 9966 } 9967 9968 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) { 9969 verifyFormat("int *f(int *a) {}"); 9970 verifyFormat("int main(int argc, char **argv) {}"); 9971 verifyFormat("Test::Test(int b) : a(b * b) {}"); 9972 verifyIndependentOfContext("f(a, *a);"); 9973 verifyFormat("void g() { f(*a); }"); 9974 verifyIndependentOfContext("int a = b * 10;"); 9975 verifyIndependentOfContext("int a = 10 * b;"); 9976 verifyIndependentOfContext("int a = b * c;"); 9977 verifyIndependentOfContext("int a += b * c;"); 9978 verifyIndependentOfContext("int a -= b * c;"); 9979 verifyIndependentOfContext("int a *= b * c;"); 9980 verifyIndependentOfContext("int a /= b * c;"); 9981 verifyIndependentOfContext("int a = *b;"); 9982 verifyIndependentOfContext("int a = *b * c;"); 9983 verifyIndependentOfContext("int a = b * *c;"); 9984 verifyIndependentOfContext("int a = b * (10);"); 9985 verifyIndependentOfContext("S << b * (10);"); 9986 verifyIndependentOfContext("return 10 * b;"); 9987 verifyIndependentOfContext("return *b * *c;"); 9988 verifyIndependentOfContext("return a & ~b;"); 9989 verifyIndependentOfContext("f(b ? *c : *d);"); 9990 verifyIndependentOfContext("int a = b ? *c : *d;"); 9991 verifyIndependentOfContext("*b = a;"); 9992 verifyIndependentOfContext("a * ~b;"); 9993 verifyIndependentOfContext("a * !b;"); 9994 verifyIndependentOfContext("a * +b;"); 9995 verifyIndependentOfContext("a * -b;"); 9996 verifyIndependentOfContext("a * ++b;"); 9997 verifyIndependentOfContext("a * --b;"); 9998 verifyIndependentOfContext("a[4] * b;"); 9999 verifyIndependentOfContext("a[a * a] = 1;"); 10000 verifyIndependentOfContext("f() * b;"); 10001 verifyIndependentOfContext("a * [self dostuff];"); 10002 verifyIndependentOfContext("int x = a * (a + b);"); 10003 verifyIndependentOfContext("(a *)(a + b);"); 10004 verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;"); 10005 verifyIndependentOfContext("int *pa = (int *)&a;"); 10006 verifyIndependentOfContext("return sizeof(int **);"); 10007 verifyIndependentOfContext("return sizeof(int ******);"); 10008 verifyIndependentOfContext("return (int **&)a;"); 10009 verifyIndependentOfContext("f((*PointerToArray)[10]);"); 10010 verifyFormat("void f(Type (*parameter)[10]) {}"); 10011 verifyFormat("void f(Type (¶meter)[10]) {}"); 10012 verifyGoogleFormat("return sizeof(int**);"); 10013 verifyIndependentOfContext("Type **A = static_cast<Type **>(P);"); 10014 verifyGoogleFormat("Type** A = static_cast<Type**>(P);"); 10015 verifyFormat("auto a = [](int **&, int ***) {};"); 10016 verifyFormat("auto PointerBinding = [](const char *S) {};"); 10017 verifyFormat("typedef typeof(int(int, int)) *MyFunc;"); 10018 verifyFormat("[](const decltype(*a) &value) {}"); 10019 verifyFormat("[](const typeof(*a) &value) {}"); 10020 verifyFormat("[](const _Atomic(a *) &value) {}"); 10021 verifyFormat("[](const __underlying_type(a) &value) {}"); 10022 verifyFormat("decltype(a * b) F();"); 10023 verifyFormat("typeof(a * b) F();"); 10024 verifyFormat("#define MACRO() [](A *a) { return 1; }"); 10025 verifyFormat("Constructor() : member([](A *a, B *b) {}) {}"); 10026 verifyIndependentOfContext("typedef void (*f)(int *a);"); 10027 verifyIndependentOfContext("int i{a * b};"); 10028 verifyIndependentOfContext("aaa && aaa->f();"); 10029 verifyIndependentOfContext("int x = ~*p;"); 10030 verifyFormat("Constructor() : a(a), area(width * height) {}"); 10031 verifyFormat("Constructor() : a(a), area(a, width * height) {}"); 10032 verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}"); 10033 verifyFormat("void f() { f(a, c * d); }"); 10034 verifyFormat("void f() { f(new a(), c * d); }"); 10035 verifyFormat("void f(const MyOverride &override);"); 10036 verifyFormat("void f(const MyFinal &final);"); 10037 verifyIndependentOfContext("bool a = f() && override.f();"); 10038 verifyIndependentOfContext("bool a = f() && final.f();"); 10039 10040 verifyIndependentOfContext("InvalidRegions[*R] = 0;"); 10041 10042 verifyIndependentOfContext("A<int *> a;"); 10043 verifyIndependentOfContext("A<int **> a;"); 10044 verifyIndependentOfContext("A<int *, int *> a;"); 10045 verifyIndependentOfContext("A<int *[]> a;"); 10046 verifyIndependentOfContext( 10047 "const char *const p = reinterpret_cast<const char *const>(q);"); 10048 verifyIndependentOfContext("A<int **, int **> a;"); 10049 verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);"); 10050 verifyFormat("for (char **a = b; *a; ++a) {\n}"); 10051 verifyFormat("for (; a && b;) {\n}"); 10052 verifyFormat("bool foo = true && [] { return false; }();"); 10053 10054 verifyFormat( 10055 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 10056 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 10057 10058 verifyGoogleFormat("int const* a = &b;"); 10059 verifyGoogleFormat("**outparam = 1;"); 10060 verifyGoogleFormat("*outparam = a * b;"); 10061 verifyGoogleFormat("int main(int argc, char** argv) {}"); 10062 verifyGoogleFormat("A<int*> a;"); 10063 verifyGoogleFormat("A<int**> a;"); 10064 verifyGoogleFormat("A<int*, int*> a;"); 10065 verifyGoogleFormat("A<int**, int**> a;"); 10066 verifyGoogleFormat("f(b ? *c : *d);"); 10067 verifyGoogleFormat("int a = b ? *c : *d;"); 10068 verifyGoogleFormat("Type* t = **x;"); 10069 verifyGoogleFormat("Type* t = *++*x;"); 10070 verifyGoogleFormat("*++*x;"); 10071 verifyGoogleFormat("Type* t = const_cast<T*>(&*x);"); 10072 verifyGoogleFormat("Type* t = x++ * y;"); 10073 verifyGoogleFormat( 10074 "const char* const p = reinterpret_cast<const char* const>(q);"); 10075 verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);"); 10076 verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);"); 10077 verifyGoogleFormat("template <typename T>\n" 10078 "void f(int i = 0, SomeType** temps = NULL);"); 10079 10080 FormatStyle Left = getLLVMStyle(); 10081 Left.PointerAlignment = FormatStyle::PAS_Left; 10082 verifyFormat("x = *a(x) = *a(y);", Left); 10083 verifyFormat("for (;; *a = b) {\n}", Left); 10084 verifyFormat("return *this += 1;", Left); 10085 verifyFormat("throw *x;", Left); 10086 verifyFormat("delete *x;", Left); 10087 verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left); 10088 verifyFormat("[](const decltype(*a)* ptr) {}", Left); 10089 verifyFormat("[](const typeof(*a)* ptr) {}", Left); 10090 verifyFormat("[](const _Atomic(a*)* ptr) {}", Left); 10091 verifyFormat("[](const __underlying_type(a)* ptr) {}", Left); 10092 verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left); 10093 verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left); 10094 verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left); 10095 verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left); 10096 10097 verifyIndependentOfContext("a = *(x + y);"); 10098 verifyIndependentOfContext("a = &(x + y);"); 10099 verifyIndependentOfContext("*(x + y).call();"); 10100 verifyIndependentOfContext("&(x + y)->call();"); 10101 verifyFormat("void f() { &(*I).first; }"); 10102 10103 verifyIndependentOfContext("f(b * /* confusing comment */ ++c);"); 10104 verifyFormat("f(* /* confusing comment */ foo);"); 10105 verifyFormat("void (* /*deleter*/)(const Slice &key, void *value)"); 10106 verifyFormat("void foo(int * // this is the first paramters\n" 10107 " ,\n" 10108 " int second);"); 10109 verifyFormat("double term = a * // first\n" 10110 " b;"); 10111 verifyFormat( 10112 "int *MyValues = {\n" 10113 " *A, // Operator detection might be confused by the '{'\n" 10114 " *BB // Operator detection might be confused by previous comment\n" 10115 "};"); 10116 10117 verifyIndependentOfContext("if (int *a = &b)"); 10118 verifyIndependentOfContext("if (int &a = *b)"); 10119 verifyIndependentOfContext("if (a & b[i])"); 10120 verifyIndependentOfContext("if constexpr (a & b[i])"); 10121 verifyIndependentOfContext("if CONSTEXPR (a & b[i])"); 10122 verifyIndependentOfContext("if (a * (b * c))"); 10123 verifyIndependentOfContext("if constexpr (a * (b * c))"); 10124 verifyIndependentOfContext("if CONSTEXPR (a * (b * c))"); 10125 verifyIndependentOfContext("if (a::b::c::d & b[i])"); 10126 verifyIndependentOfContext("if (*b[i])"); 10127 verifyIndependentOfContext("if (int *a = (&b))"); 10128 verifyIndependentOfContext("while (int *a = &b)"); 10129 verifyIndependentOfContext("while (a * (b * c))"); 10130 verifyIndependentOfContext("size = sizeof *a;"); 10131 verifyIndependentOfContext("if (a && (b = c))"); 10132 verifyFormat("void f() {\n" 10133 " for (const int &v : Values) {\n" 10134 " }\n" 10135 "}"); 10136 verifyFormat("for (int i = a * a; i < 10; ++i) {\n}"); 10137 verifyFormat("for (int i = 0; i < a * a; ++i) {\n}"); 10138 verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}"); 10139 10140 verifyFormat("#define A (!a * b)"); 10141 verifyFormat("#define MACRO \\\n" 10142 " int *i = a * b; \\\n" 10143 " void f(a *b);", 10144 getLLVMStyleWithColumns(19)); 10145 10146 verifyIndependentOfContext("A = new SomeType *[Length];"); 10147 verifyIndependentOfContext("A = new SomeType *[Length]();"); 10148 verifyIndependentOfContext("T **t = new T *;"); 10149 verifyIndependentOfContext("T **t = new T *();"); 10150 verifyGoogleFormat("A = new SomeType*[Length]();"); 10151 verifyGoogleFormat("A = new SomeType*[Length];"); 10152 verifyGoogleFormat("T** t = new T*;"); 10153 verifyGoogleFormat("T** t = new T*();"); 10154 10155 verifyFormat("STATIC_ASSERT((a & b) == 0);"); 10156 verifyFormat("STATIC_ASSERT(0 == (a & b));"); 10157 verifyFormat("template <bool a, bool b> " 10158 "typename t::if<x && y>::type f() {}"); 10159 verifyFormat("template <int *y> f() {}"); 10160 verifyFormat("vector<int *> v;"); 10161 verifyFormat("vector<int *const> v;"); 10162 verifyFormat("vector<int *const **const *> v;"); 10163 verifyFormat("vector<int *volatile> v;"); 10164 verifyFormat("vector<a *_Nonnull> v;"); 10165 verifyFormat("vector<a *_Nullable> v;"); 10166 verifyFormat("vector<a *_Null_unspecified> v;"); 10167 verifyFormat("vector<a *__ptr32> v;"); 10168 verifyFormat("vector<a *__ptr64> v;"); 10169 verifyFormat("vector<a *__capability> v;"); 10170 FormatStyle TypeMacros = getLLVMStyle(); 10171 TypeMacros.TypenameMacros = {"LIST"}; 10172 verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros); 10173 verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros); 10174 verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros); 10175 verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros); 10176 verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication 10177 10178 FormatStyle CustomQualifier = getLLVMStyle(); 10179 // Add identifiers that should not be parsed as a qualifier by default. 10180 CustomQualifier.AttributeMacros.push_back("__my_qualifier"); 10181 CustomQualifier.AttributeMacros.push_back("_My_qualifier"); 10182 CustomQualifier.AttributeMacros.push_back("my_other_qualifier"); 10183 verifyFormat("vector<a * __my_qualifier> parse_as_multiply;"); 10184 verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier); 10185 verifyFormat("vector<a * _My_qualifier> parse_as_multiply;"); 10186 verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier); 10187 verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;"); 10188 verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier); 10189 verifyFormat("vector<a * _NotAQualifier> v;"); 10190 verifyFormat("vector<a * __not_a_qualifier> v;"); 10191 verifyFormat("vector<a * b> v;"); 10192 verifyFormat("foo<b && false>();"); 10193 verifyFormat("foo<b & 1>();"); 10194 verifyFormat("decltype(*::std::declval<const T &>()) void F();"); 10195 verifyFormat("typeof(*::std::declval<const T &>()) void F();"); 10196 verifyFormat("_Atomic(*::std::declval<const T &>()) void F();"); 10197 verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();"); 10198 verifyFormat( 10199 "template <class T, class = typename std::enable_if<\n" 10200 " std::is_integral<T>::value &&\n" 10201 " (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n" 10202 "void F();", 10203 getLLVMStyleWithColumns(70)); 10204 verifyFormat("template <class T,\n" 10205 " class = typename std::enable_if<\n" 10206 " std::is_integral<T>::value &&\n" 10207 " (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n" 10208 " class U>\n" 10209 "void F();", 10210 getLLVMStyleWithColumns(70)); 10211 verifyFormat( 10212 "template <class T,\n" 10213 " class = typename ::std::enable_if<\n" 10214 " ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n" 10215 "void F();", 10216 getGoogleStyleWithColumns(68)); 10217 10218 verifyIndependentOfContext("MACRO(int *i);"); 10219 verifyIndependentOfContext("MACRO(auto *a);"); 10220 verifyIndependentOfContext("MACRO(const A *a);"); 10221 verifyIndependentOfContext("MACRO(_Atomic(A) *a);"); 10222 verifyIndependentOfContext("MACRO(decltype(A) *a);"); 10223 verifyIndependentOfContext("MACRO(typeof(A) *a);"); 10224 verifyIndependentOfContext("MACRO(__underlying_type(A) *a);"); 10225 verifyIndependentOfContext("MACRO(A *const a);"); 10226 verifyIndependentOfContext("MACRO(A *restrict a);"); 10227 verifyIndependentOfContext("MACRO(A *__restrict__ a);"); 10228 verifyIndependentOfContext("MACRO(A *__restrict a);"); 10229 verifyIndependentOfContext("MACRO(A *volatile a);"); 10230 verifyIndependentOfContext("MACRO(A *__volatile a);"); 10231 verifyIndependentOfContext("MACRO(A *__volatile__ a);"); 10232 verifyIndependentOfContext("MACRO(A *_Nonnull a);"); 10233 verifyIndependentOfContext("MACRO(A *_Nullable a);"); 10234 verifyIndependentOfContext("MACRO(A *_Null_unspecified a);"); 10235 verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);"); 10236 verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);"); 10237 verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);"); 10238 verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);"); 10239 verifyIndependentOfContext("MACRO(A *__ptr32 a);"); 10240 verifyIndependentOfContext("MACRO(A *__ptr64 a);"); 10241 verifyIndependentOfContext("MACRO(A *__capability);"); 10242 verifyIndependentOfContext("MACRO(A &__capability);"); 10243 verifyFormat("MACRO(A *__my_qualifier);"); // type declaration 10244 verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication 10245 // If we add __my_qualifier to AttributeMacros it should always be parsed as 10246 // a type declaration: 10247 verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier); 10248 verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier); 10249 // Also check that TypenameMacros prevents parsing it as multiplication: 10250 verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication 10251 verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type 10252 10253 verifyIndependentOfContext("MACRO('0' <= c && c <= '9');"); 10254 verifyFormat("void f() { f(float{1}, a * a); }"); 10255 verifyFormat("void f() { f(float(1), a * a); }"); 10256 10257 verifyFormat("f((void (*)(int))g);"); 10258 verifyFormat("f((void (&)(int))g);"); 10259 verifyFormat("f((void (^)(int))g);"); 10260 10261 // FIXME: Is there a way to make this work? 10262 // verifyIndependentOfContext("MACRO(A *a);"); 10263 verifyFormat("MACRO(A &B);"); 10264 verifyFormat("MACRO(A *B);"); 10265 verifyFormat("void f() { MACRO(A * B); }"); 10266 verifyFormat("void f() { MACRO(A & B); }"); 10267 10268 // This lambda was mis-formatted after D88956 (treating it as a binop): 10269 verifyFormat("auto x = [](const decltype(x) &ptr) {};"); 10270 verifyFormat("auto x = [](const decltype(x) *ptr) {};"); 10271 verifyFormat("#define lambda [](const decltype(x) &ptr) {}"); 10272 verifyFormat("#define lambda [](const decltype(x) *ptr) {}"); 10273 10274 verifyFormat("DatumHandle const *operator->() const { return input_; }"); 10275 verifyFormat("return options != nullptr && operator==(*options);"); 10276 10277 EXPECT_EQ("#define OP(x) \\\n" 10278 " ostream &operator<<(ostream &s, const A &a) { \\\n" 10279 " return s << a.DebugString(); \\\n" 10280 " }", 10281 format("#define OP(x) \\\n" 10282 " ostream &operator<<(ostream &s, const A &a) { \\\n" 10283 " return s << a.DebugString(); \\\n" 10284 " }", 10285 getLLVMStyleWithColumns(50))); 10286 10287 // FIXME: We cannot handle this case yet; we might be able to figure out that 10288 // foo<x> d > v; doesn't make sense. 10289 verifyFormat("foo<a<b && c> d> v;"); 10290 10291 FormatStyle PointerMiddle = getLLVMStyle(); 10292 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle; 10293 verifyFormat("delete *x;", PointerMiddle); 10294 verifyFormat("int * x;", PointerMiddle); 10295 verifyFormat("int *[] x;", PointerMiddle); 10296 verifyFormat("template <int * y> f() {}", PointerMiddle); 10297 verifyFormat("int * f(int * a) {}", PointerMiddle); 10298 verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle); 10299 verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle); 10300 verifyFormat("A<int *> a;", PointerMiddle); 10301 verifyFormat("A<int **> a;", PointerMiddle); 10302 verifyFormat("A<int *, int *> a;", PointerMiddle); 10303 verifyFormat("A<int *[]> a;", PointerMiddle); 10304 verifyFormat("A = new SomeType *[Length]();", PointerMiddle); 10305 verifyFormat("A = new SomeType *[Length];", PointerMiddle); 10306 verifyFormat("T ** t = new T *;", PointerMiddle); 10307 10308 // Member function reference qualifiers aren't binary operators. 10309 verifyFormat("string // break\n" 10310 "operator()() & {}"); 10311 verifyFormat("string // break\n" 10312 "operator()() && {}"); 10313 verifyGoogleFormat("template <typename T>\n" 10314 "auto x() & -> int {}"); 10315 10316 // Should be binary operators when used as an argument expression (overloaded 10317 // operator invoked as a member function). 10318 verifyFormat("void f() { a.operator()(a * a); }"); 10319 verifyFormat("void f() { a->operator()(a & a); }"); 10320 verifyFormat("void f() { a.operator()(*a & *a); }"); 10321 verifyFormat("void f() { a->operator()(*a * *a); }"); 10322 10323 verifyFormat("int operator()(T (&&)[N]) { return 1; }"); 10324 verifyFormat("int operator()(T (&)[N]) { return 0; }"); 10325 } 10326 10327 TEST_F(FormatTest, UnderstandsAttributes) { 10328 verifyFormat("SomeType s __attribute__((unused)) (InitValue);"); 10329 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n" 10330 "aaaaaaaaaaaaaaaaaaaaaaa(int i);"); 10331 verifyFormat("__attribute__((nodebug)) ::qualified_type f();"); 10332 FormatStyle AfterType = getLLVMStyle(); 10333 AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 10334 verifyFormat("__attribute__((nodebug)) void\n" 10335 "foo() {}\n", 10336 AfterType); 10337 verifyFormat("__unused void\n" 10338 "foo() {}", 10339 AfterType); 10340 10341 FormatStyle CustomAttrs = getLLVMStyle(); 10342 CustomAttrs.AttributeMacros.push_back("__unused"); 10343 CustomAttrs.AttributeMacros.push_back("__attr1"); 10344 CustomAttrs.AttributeMacros.push_back("__attr2"); 10345 CustomAttrs.AttributeMacros.push_back("no_underscore_attr"); 10346 verifyFormat("vector<SomeType *__attribute((foo))> v;"); 10347 verifyFormat("vector<SomeType *__attribute__((foo))> v;"); 10348 verifyFormat("vector<SomeType * __not_attribute__((foo))> v;"); 10349 // Check that it is parsed as a multiplication without AttributeMacros and 10350 // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros. 10351 verifyFormat("vector<SomeType * __attr1> v;"); 10352 verifyFormat("vector<SomeType __attr1 *> v;"); 10353 verifyFormat("vector<SomeType __attr1 *const> v;"); 10354 verifyFormat("vector<SomeType __attr1 * __attr2> v;"); 10355 verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs); 10356 verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs); 10357 verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs); 10358 verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs); 10359 verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs); 10360 verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs); 10361 verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs); 10362 10363 // Check that these are not parsed as function declarations: 10364 CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 10365 CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman; 10366 verifyFormat("SomeType s(InitValue);", CustomAttrs); 10367 verifyFormat("SomeType s{InitValue};", CustomAttrs); 10368 verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs); 10369 verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs); 10370 verifyFormat("SomeType s __unused(InitValue);", CustomAttrs); 10371 verifyFormat("SomeType s __unused{InitValue};", CustomAttrs); 10372 verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs); 10373 verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs); 10374 } 10375 10376 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) { 10377 // Check that qualifiers on pointers don't break parsing of casts. 10378 verifyFormat("x = (foo *const)*v;"); 10379 verifyFormat("x = (foo *volatile)*v;"); 10380 verifyFormat("x = (foo *restrict)*v;"); 10381 verifyFormat("x = (foo *__attribute__((foo)))*v;"); 10382 verifyFormat("x = (foo *_Nonnull)*v;"); 10383 verifyFormat("x = (foo *_Nullable)*v;"); 10384 verifyFormat("x = (foo *_Null_unspecified)*v;"); 10385 verifyFormat("x = (foo *_Nonnull)*v;"); 10386 verifyFormat("x = (foo *[[clang::attr]])*v;"); 10387 verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;"); 10388 verifyFormat("x = (foo *__ptr32)*v;"); 10389 verifyFormat("x = (foo *__ptr64)*v;"); 10390 verifyFormat("x = (foo *__capability)*v;"); 10391 10392 // Check that we handle multiple trailing qualifiers and skip them all to 10393 // determine that the expression is a cast to a pointer type. 10394 FormatStyle LongPointerRight = getLLVMStyleWithColumns(999); 10395 FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999); 10396 LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left; 10397 StringRef AllQualifiers = 10398 "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified " 10399 "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability"; 10400 verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight); 10401 verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft); 10402 10403 // Also check that address-of is not parsed as a binary bitwise-and: 10404 verifyFormat("x = (foo *const)&v;"); 10405 verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight); 10406 verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft); 10407 10408 // Check custom qualifiers: 10409 FormatStyle CustomQualifier = getLLVMStyleWithColumns(999); 10410 CustomQualifier.AttributeMacros.push_back("__my_qualifier"); 10411 verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier. 10412 verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier); 10413 verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(), 10414 CustomQualifier); 10415 verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(), 10416 CustomQualifier); 10417 10418 // Check that unknown identifiers result in binary operator parsing: 10419 verifyFormat("x = (foo * __unknown_qualifier) * v;"); 10420 verifyFormat("x = (foo * __unknown_qualifier) & v;"); 10421 } 10422 10423 TEST_F(FormatTest, UnderstandsSquareAttributes) { 10424 verifyFormat("SomeType s [[unused]] (InitValue);"); 10425 verifyFormat("SomeType s [[gnu::unused]] (InitValue);"); 10426 verifyFormat("SomeType s [[using gnu: unused]] (InitValue);"); 10427 verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}"); 10428 verifyFormat("void f() [[deprecated(\"so sorry\")]];"); 10429 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10430 " [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);"); 10431 verifyFormat("[[nodiscard]] bool f() { return false; }"); 10432 verifyFormat("class [[nodiscard]] f {\npublic:\n f() {}\n}"); 10433 verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n f() {}\n}"); 10434 verifyFormat("class [[gnu::unused]] f {\npublic:\n f() {}\n}"); 10435 verifyFormat("[[nodiscard]] ::qualified_type f();"); 10436 10437 // Make sure we do not mistake attributes for array subscripts. 10438 verifyFormat("int a() {}\n" 10439 "[[unused]] int b() {}\n"); 10440 verifyFormat("NSArray *arr;\n" 10441 "arr[[Foo() bar]];"); 10442 10443 // On the other hand, we still need to correctly find array subscripts. 10444 verifyFormat("int a = std::vector<int>{1, 2, 3}[0];"); 10445 10446 // Make sure that we do not mistake Objective-C method inside array literals 10447 // as attributes, even if those method names are also keywords. 10448 verifyFormat("@[ [foo bar] ];"); 10449 verifyFormat("@[ [NSArray class] ];"); 10450 verifyFormat("@[ [foo enum] ];"); 10451 10452 verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }"); 10453 10454 // Make sure we do not parse attributes as lambda introducers. 10455 FormatStyle MultiLineFunctions = getLLVMStyle(); 10456 MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 10457 verifyFormat("[[unused]] int b() {\n" 10458 " return 42;\n" 10459 "}\n", 10460 MultiLineFunctions); 10461 } 10462 10463 TEST_F(FormatTest, AttributeClass) { 10464 FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp); 10465 verifyFormat("class S {\n" 10466 " S(S&&) = default;\n" 10467 "};", 10468 Style); 10469 verifyFormat("class [[nodiscard]] S {\n" 10470 " S(S&&) = default;\n" 10471 "};", 10472 Style); 10473 verifyFormat("class __attribute((maybeunused)) S {\n" 10474 " S(S&&) = default;\n" 10475 "};", 10476 Style); 10477 verifyFormat("struct S {\n" 10478 " S(S&&) = default;\n" 10479 "};", 10480 Style); 10481 verifyFormat("struct [[nodiscard]] S {\n" 10482 " S(S&&) = default;\n" 10483 "};", 10484 Style); 10485 } 10486 10487 TEST_F(FormatTest, AttributesAfterMacro) { 10488 FormatStyle Style = getLLVMStyle(); 10489 verifyFormat("MACRO;\n" 10490 "__attribute__((maybe_unused)) int foo() {\n" 10491 " //...\n" 10492 "}"); 10493 10494 verifyFormat("MACRO;\n" 10495 "[[nodiscard]] int foo() {\n" 10496 " //...\n" 10497 "}"); 10498 10499 EXPECT_EQ("MACRO\n\n" 10500 "__attribute__((maybe_unused)) int foo() {\n" 10501 " //...\n" 10502 "}", 10503 format("MACRO\n\n" 10504 "__attribute__((maybe_unused)) int foo() {\n" 10505 " //...\n" 10506 "}")); 10507 10508 EXPECT_EQ("MACRO\n\n" 10509 "[[nodiscard]] int foo() {\n" 10510 " //...\n" 10511 "}", 10512 format("MACRO\n\n" 10513 "[[nodiscard]] int foo() {\n" 10514 " //...\n" 10515 "}")); 10516 } 10517 10518 TEST_F(FormatTest, AttributePenaltyBreaking) { 10519 FormatStyle Style = getLLVMStyle(); 10520 verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n" 10521 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}", 10522 Style); 10523 verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n" 10524 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}", 10525 Style); 10526 verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const " 10527 "shared_ptr<ALongTypeName> &C d) {\n}", 10528 Style); 10529 } 10530 10531 TEST_F(FormatTest, UnderstandsEllipsis) { 10532 FormatStyle Style = getLLVMStyle(); 10533 verifyFormat("int printf(const char *fmt, ...);"); 10534 verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }"); 10535 verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}"); 10536 10537 verifyFormat("template <int *...PP> a;", Style); 10538 10539 Style.PointerAlignment = FormatStyle::PAS_Left; 10540 verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style); 10541 10542 verifyFormat("template <int*... PP> a;", Style); 10543 10544 Style.PointerAlignment = FormatStyle::PAS_Middle; 10545 verifyFormat("template <int *... PP> a;", Style); 10546 } 10547 10548 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) { 10549 EXPECT_EQ("int *a;\n" 10550 "int *a;\n" 10551 "int *a;", 10552 format("int *a;\n" 10553 "int* a;\n" 10554 "int *a;", 10555 getGoogleStyle())); 10556 EXPECT_EQ("int* a;\n" 10557 "int* a;\n" 10558 "int* a;", 10559 format("int* a;\n" 10560 "int* a;\n" 10561 "int *a;", 10562 getGoogleStyle())); 10563 EXPECT_EQ("int *a;\n" 10564 "int *a;\n" 10565 "int *a;", 10566 format("int *a;\n" 10567 "int * a;\n" 10568 "int * a;", 10569 getGoogleStyle())); 10570 EXPECT_EQ("auto x = [] {\n" 10571 " int *a;\n" 10572 " int *a;\n" 10573 " int *a;\n" 10574 "};", 10575 format("auto x=[]{int *a;\n" 10576 "int * a;\n" 10577 "int * a;};", 10578 getGoogleStyle())); 10579 } 10580 10581 TEST_F(FormatTest, UnderstandsRvalueReferences) { 10582 verifyFormat("int f(int &&a) {}"); 10583 verifyFormat("int f(int a, char &&b) {}"); 10584 verifyFormat("void f() { int &&a = b; }"); 10585 verifyGoogleFormat("int f(int a, char&& b) {}"); 10586 verifyGoogleFormat("void f() { int&& a = b; }"); 10587 10588 verifyIndependentOfContext("A<int &&> a;"); 10589 verifyIndependentOfContext("A<int &&, int &&> a;"); 10590 verifyGoogleFormat("A<int&&> a;"); 10591 verifyGoogleFormat("A<int&&, int&&> a;"); 10592 10593 // Not rvalue references: 10594 verifyFormat("template <bool B, bool C> class A {\n" 10595 " static_assert(B && C, \"Something is wrong\");\n" 10596 "};"); 10597 verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))"); 10598 verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))"); 10599 verifyFormat("#define A(a, b) (a && b)"); 10600 } 10601 10602 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) { 10603 verifyFormat("void f() {\n" 10604 " x[aaaaaaaaa -\n" 10605 " b] = 23;\n" 10606 "}", 10607 getLLVMStyleWithColumns(15)); 10608 } 10609 10610 TEST_F(FormatTest, FormatsCasts) { 10611 verifyFormat("Type *A = static_cast<Type *>(P);"); 10612 verifyFormat("static_cast<Type *>(P);"); 10613 verifyFormat("static_cast<Type &>(Fun)(Args);"); 10614 verifyFormat("static_cast<Type &>(*Fun)(Args);"); 10615 verifyFormat("if (static_cast<int>(A) + B >= 0)\n ;"); 10616 // Check that static_cast<...>(...) does not require the next token to be on 10617 // the same line. 10618 verifyFormat("some_loooong_output << something_something__ << " 10619 "static_cast<const void *>(R)\n" 10620 " << something;"); 10621 verifyFormat("a = static_cast<Type &>(*Fun)(Args);"); 10622 verifyFormat("const_cast<Type &>(*Fun)(Args);"); 10623 verifyFormat("dynamic_cast<Type &>(*Fun)(Args);"); 10624 verifyFormat("reinterpret_cast<Type &>(*Fun)(Args);"); 10625 verifyFormat("Type *A = (Type *)P;"); 10626 verifyFormat("Type *A = (vector<Type *, int *>)P;"); 10627 verifyFormat("int a = (int)(2.0f);"); 10628 verifyFormat("int a = (int)2.0f;"); 10629 verifyFormat("x[(int32)y];"); 10630 verifyFormat("x = (int32)y;"); 10631 verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)"); 10632 verifyFormat("int a = (int)*b;"); 10633 verifyFormat("int a = (int)2.0f;"); 10634 verifyFormat("int a = (int)~0;"); 10635 verifyFormat("int a = (int)++a;"); 10636 verifyFormat("int a = (int)sizeof(int);"); 10637 verifyFormat("int a = (int)+2;"); 10638 verifyFormat("my_int a = (my_int)2.0f;"); 10639 verifyFormat("my_int a = (my_int)sizeof(int);"); 10640 verifyFormat("return (my_int)aaa;"); 10641 verifyFormat("#define x ((int)-1)"); 10642 verifyFormat("#define LENGTH(x, y) (x) - (y) + 1"); 10643 verifyFormat("#define p(q) ((int *)&q)"); 10644 verifyFormat("fn(a)(b) + 1;"); 10645 10646 verifyFormat("void f() { my_int a = (my_int)*b; }"); 10647 verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }"); 10648 verifyFormat("my_int a = (my_int)~0;"); 10649 verifyFormat("my_int a = (my_int)++a;"); 10650 verifyFormat("my_int a = (my_int)-2;"); 10651 verifyFormat("my_int a = (my_int)1;"); 10652 verifyFormat("my_int a = (my_int *)1;"); 10653 verifyFormat("my_int a = (const my_int)-1;"); 10654 verifyFormat("my_int a = (const my_int *)-1;"); 10655 verifyFormat("my_int a = (my_int)(my_int)-1;"); 10656 verifyFormat("my_int a = (ns::my_int)-2;"); 10657 verifyFormat("case (my_int)ONE:"); 10658 verifyFormat("auto x = (X)this;"); 10659 // Casts in Obj-C style calls used to not be recognized as such. 10660 verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle()); 10661 10662 // FIXME: single value wrapped with paren will be treated as cast. 10663 verifyFormat("void f(int i = (kValue)*kMask) {}"); 10664 10665 verifyFormat("{ (void)F; }"); 10666 10667 // Don't break after a cast's 10668 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 10669 " (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n" 10670 " bbbbbbbbbbbbbbbbbbbbbb);"); 10671 10672 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(x)"); 10673 verifyFormat("#define CONF_BOOL(x) (bool *)(x)"); 10674 verifyFormat("#define CONF_BOOL(x) (bool)(x)"); 10675 verifyFormat("bool *y = (bool *)(void *)(x);"); 10676 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)(x)"); 10677 verifyFormat("bool *y = (bool *)(void *)(int)(x);"); 10678 verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)foo(x)"); 10679 verifyFormat("bool *y = (bool *)(void *)(int)foo(x);"); 10680 10681 // These are not casts. 10682 verifyFormat("void f(int *) {}"); 10683 verifyFormat("f(foo)->b;"); 10684 verifyFormat("f(foo).b;"); 10685 verifyFormat("f(foo)(b);"); 10686 verifyFormat("f(foo)[b];"); 10687 verifyFormat("[](foo) { return 4; }(bar);"); 10688 verifyFormat("(*funptr)(foo)[4];"); 10689 verifyFormat("funptrs[4](foo)[4];"); 10690 verifyFormat("void f(int *);"); 10691 verifyFormat("void f(int *) = 0;"); 10692 verifyFormat("void f(SmallVector<int>) {}"); 10693 verifyFormat("void f(SmallVector<int>);"); 10694 verifyFormat("void f(SmallVector<int>) = 0;"); 10695 verifyFormat("void f(int i = (kA * kB) & kMask) {}"); 10696 verifyFormat("int a = sizeof(int) * b;"); 10697 verifyFormat("int a = alignof(int) * b;", getGoogleStyle()); 10698 verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;"); 10699 verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");"); 10700 verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;"); 10701 10702 // These are not casts, but at some point were confused with casts. 10703 verifyFormat("virtual void foo(int *) override;"); 10704 verifyFormat("virtual void foo(char &) const;"); 10705 verifyFormat("virtual void foo(int *a, char *) const;"); 10706 verifyFormat("int a = sizeof(int *) + b;"); 10707 verifyFormat("int a = alignof(int *) + b;", getGoogleStyle()); 10708 verifyFormat("bool b = f(g<int>) && c;"); 10709 verifyFormat("typedef void (*f)(int i) func;"); 10710 verifyFormat("void operator++(int) noexcept;"); 10711 verifyFormat("void operator++(int &) noexcept;"); 10712 verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t " 10713 "&) noexcept;"); 10714 verifyFormat( 10715 "void operator delete(std::size_t, const std::nothrow_t &) noexcept;"); 10716 verifyFormat("void operator delete(const std::nothrow_t &) noexcept;"); 10717 verifyFormat("void operator delete(std::nothrow_t &) noexcept;"); 10718 verifyFormat("void operator delete(nothrow_t &) noexcept;"); 10719 verifyFormat("void operator delete(foo &) noexcept;"); 10720 verifyFormat("void operator delete(foo) noexcept;"); 10721 verifyFormat("void operator delete(int) noexcept;"); 10722 verifyFormat("void operator delete(int &) noexcept;"); 10723 verifyFormat("void operator delete(int &) volatile noexcept;"); 10724 verifyFormat("void operator delete(int &) const"); 10725 verifyFormat("void operator delete(int &) = default"); 10726 verifyFormat("void operator delete(int &) = delete"); 10727 verifyFormat("void operator delete(int &) [[noreturn]]"); 10728 verifyFormat("void operator delete(int &) throw();"); 10729 verifyFormat("void operator delete(int &) throw(int);"); 10730 verifyFormat("auto operator delete(int &) -> int;"); 10731 verifyFormat("auto operator delete(int &) override"); 10732 verifyFormat("auto operator delete(int &) final"); 10733 10734 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n" 10735 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 10736 // FIXME: The indentation here is not ideal. 10737 verifyFormat( 10738 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10739 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n" 10740 " [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];"); 10741 } 10742 10743 TEST_F(FormatTest, FormatsFunctionTypes) { 10744 verifyFormat("A<bool()> a;"); 10745 verifyFormat("A<SomeType()> a;"); 10746 verifyFormat("A<void (*)(int, std::string)> a;"); 10747 verifyFormat("A<void *(int)>;"); 10748 verifyFormat("void *(*a)(int *, SomeType *);"); 10749 verifyFormat("int (*func)(void *);"); 10750 verifyFormat("void f() { int (*func)(void *); }"); 10751 verifyFormat("template <class CallbackClass>\n" 10752 "using MyCallback = void (CallbackClass::*)(SomeObject *Data);"); 10753 10754 verifyGoogleFormat("A<void*(int*, SomeType*)>;"); 10755 verifyGoogleFormat("void* (*a)(int);"); 10756 verifyGoogleFormat( 10757 "template <class CallbackClass>\n" 10758 "using MyCallback = void (CallbackClass::*)(SomeObject* Data);"); 10759 10760 // Other constructs can look somewhat like function types: 10761 verifyFormat("A<sizeof(*x)> a;"); 10762 verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)"); 10763 verifyFormat("some_var = function(*some_pointer_var)[0];"); 10764 verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }"); 10765 verifyFormat("int x = f(&h)();"); 10766 verifyFormat("returnsFunction(¶m1, ¶m2)(param);"); 10767 verifyFormat("std::function<\n" 10768 " LooooooooooongTemplatedType<\n" 10769 " SomeType>*(\n" 10770 " LooooooooooooooooongType type)>\n" 10771 " function;", 10772 getGoogleStyleWithColumns(40)); 10773 } 10774 10775 TEST_F(FormatTest, FormatsPointersToArrayTypes) { 10776 verifyFormat("A (*foo_)[6];"); 10777 verifyFormat("vector<int> (*foo_)[6];"); 10778 } 10779 10780 TEST_F(FormatTest, BreaksLongVariableDeclarations) { 10781 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10782 " LoooooooooooooooooooooooooooooooooooooooongVariable;"); 10783 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n" 10784 " LoooooooooooooooooooooooooooooooooooooooongVariable;"); 10785 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10786 " *LoooooooooooooooooooooooooooooooooooooooongVariable;"); 10787 10788 // Different ways of ()-initializiation. 10789 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10790 " LoooooooooooooooooooooooooooooooooooooooongVariable(1);"); 10791 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10792 " LoooooooooooooooooooooooooooooooooooooooongVariable(a);"); 10793 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10794 " LoooooooooooooooooooooooooooooooooooooooongVariable({});"); 10795 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10796 " LoooooooooooooooooooooooooooooooooooooongVariable([A a]);"); 10797 10798 // Lambdas should not confuse the variable declaration heuristic. 10799 verifyFormat("LooooooooooooooooongType\n" 10800 " variable(nullptr, [](A *a) {});", 10801 getLLVMStyleWithColumns(40)); 10802 } 10803 10804 TEST_F(FormatTest, BreaksLongDeclarations) { 10805 verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n" 10806 " AnotherNameForTheLongType;"); 10807 verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n" 10808 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 10809 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10810 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();"); 10811 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n" 10812 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();"); 10813 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10814 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10815 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n" 10816 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10817 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n" 10818 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10819 verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n" 10820 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10821 verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n" 10822 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10823 verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n" 10824 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10825 verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n" 10826 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10827 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10828 "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);"); 10829 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10830 "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}"); 10831 FormatStyle Indented = getLLVMStyle(); 10832 Indented.IndentWrappedFunctionNames = true; 10833 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10834 " LoooooooooooooooooooooooooooooooongFunctionDeclaration();", 10835 Indented); 10836 verifyFormat( 10837 "LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10838 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 10839 Indented); 10840 verifyFormat( 10841 "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n" 10842 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 10843 Indented); 10844 verifyFormat( 10845 "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n" 10846 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 10847 Indented); 10848 10849 // FIXME: Without the comment, this breaks after "(". 10850 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType // break\n" 10851 " (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();", 10852 getGoogleStyle()); 10853 10854 verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n" 10855 " int LoooooooooooooooooooongParam2) {}"); 10856 verifyFormat( 10857 "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n" 10858 " SourceLocation L, IdentifierIn *II,\n" 10859 " Type *T) {}"); 10860 verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n" 10861 "ReallyReaaallyLongFunctionName(\n" 10862 " const std::string &SomeParameter,\n" 10863 " const SomeType<string, SomeOtherTemplateParameter>\n" 10864 " &ReallyReallyLongParameterName,\n" 10865 " const SomeType<string, SomeOtherTemplateParameter>\n" 10866 " &AnotherLongParameterName) {}"); 10867 verifyFormat("template <typename A>\n" 10868 "SomeLoooooooooooooooooooooongType<\n" 10869 " typename some_namespace::SomeOtherType<A>::Type>\n" 10870 "Function() {}"); 10871 10872 verifyGoogleFormat( 10873 "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n" 10874 " aaaaaaaaaaaaaaaaaaaaaaa;"); 10875 verifyGoogleFormat( 10876 "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n" 10877 " SourceLocation L) {}"); 10878 verifyGoogleFormat( 10879 "some_namespace::LongReturnType\n" 10880 "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n" 10881 " int first_long_parameter, int second_parameter) {}"); 10882 10883 verifyGoogleFormat("template <typename T>\n" 10884 "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n" 10885 "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}"); 10886 verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 10887 " int aaaaaaaaaaaaaaaaaaaaaaa);"); 10888 10889 verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n" 10890 " const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10891 " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 10892 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 10893 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n" 10894 " aaaaaaaaaaaaaaaaaaaaaaaa);"); 10895 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 10896 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 10897 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n" 10898 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 10899 10900 verifyFormat("template <typename T> // Templates on own line.\n" 10901 "static int // Some comment.\n" 10902 "MyFunction(int a);", 10903 getLLVMStyle()); 10904 } 10905 10906 TEST_F(FormatTest, FormatsAccessModifiers) { 10907 FormatStyle Style = getLLVMStyle(); 10908 EXPECT_EQ(Style.EmptyLineBeforeAccessModifier, 10909 FormatStyle::ELBAMS_LogicalBlock); 10910 verifyFormat("struct foo {\n" 10911 "private:\n" 10912 " void f() {}\n" 10913 "\n" 10914 "private:\n" 10915 " int i;\n" 10916 "\n" 10917 "protected:\n" 10918 " int j;\n" 10919 "};\n", 10920 Style); 10921 verifyFormat("struct foo {\n" 10922 "private:\n" 10923 " void f() {}\n" 10924 "\n" 10925 "private:\n" 10926 " int i;\n" 10927 "\n" 10928 "protected:\n" 10929 " int j;\n" 10930 "};\n", 10931 "struct foo {\n" 10932 "private:\n" 10933 " void f() {}\n" 10934 "private:\n" 10935 " int i;\n" 10936 "protected:\n" 10937 " int j;\n" 10938 "};\n", 10939 Style); 10940 verifyFormat("struct foo { /* comment */\n" 10941 "private:\n" 10942 " int i;\n" 10943 " // comment\n" 10944 "private:\n" 10945 " int j;\n" 10946 "};\n", 10947 Style); 10948 verifyFormat("struct foo {\n" 10949 "#ifdef FOO\n" 10950 "#endif\n" 10951 "private:\n" 10952 " int i;\n" 10953 "#ifdef FOO\n" 10954 "private:\n" 10955 "#endif\n" 10956 " int j;\n" 10957 "};\n", 10958 Style); 10959 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 10960 verifyFormat("struct foo {\n" 10961 "private:\n" 10962 " void f() {}\n" 10963 "private:\n" 10964 " int i;\n" 10965 "protected:\n" 10966 " int j;\n" 10967 "};\n", 10968 Style); 10969 verifyFormat("struct foo {\n" 10970 "private:\n" 10971 " void f() {}\n" 10972 "private:\n" 10973 " int i;\n" 10974 "protected:\n" 10975 " int j;\n" 10976 "};\n", 10977 "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 Style); 10989 verifyFormat("struct foo { /* comment */\n" 10990 "private:\n" 10991 " int i;\n" 10992 " // comment\n" 10993 "private:\n" 10994 " int j;\n" 10995 "};\n", 10996 "struct foo { /* comment */\n" 10997 "\n" 10998 "private:\n" 10999 " int i;\n" 11000 " // comment\n" 11001 "\n" 11002 "private:\n" 11003 " int j;\n" 11004 "};\n", 11005 Style); 11006 verifyFormat("struct foo {\n" 11007 "#ifdef FOO\n" 11008 "#endif\n" 11009 "private:\n" 11010 " int i;\n" 11011 "#ifdef FOO\n" 11012 "private:\n" 11013 "#endif\n" 11014 " int j;\n" 11015 "};\n", 11016 "struct foo {\n" 11017 "#ifdef FOO\n" 11018 "#endif\n" 11019 "\n" 11020 "private:\n" 11021 " int i;\n" 11022 "#ifdef FOO\n" 11023 "\n" 11024 "private:\n" 11025 "#endif\n" 11026 " int j;\n" 11027 "};\n", 11028 Style); 11029 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11030 verifyFormat("struct foo {\n" 11031 "private:\n" 11032 " void f() {}\n" 11033 "\n" 11034 "private:\n" 11035 " int i;\n" 11036 "\n" 11037 "protected:\n" 11038 " int j;\n" 11039 "};\n", 11040 Style); 11041 verifyFormat("struct foo {\n" 11042 "private:\n" 11043 " void f() {}\n" 11044 "\n" 11045 "private:\n" 11046 " int i;\n" 11047 "\n" 11048 "protected:\n" 11049 " int j;\n" 11050 "};\n", 11051 "struct foo {\n" 11052 "private:\n" 11053 " void f() {}\n" 11054 "private:\n" 11055 " int i;\n" 11056 "protected:\n" 11057 " int j;\n" 11058 "};\n", 11059 Style); 11060 verifyFormat("struct foo { /* comment */\n" 11061 "private:\n" 11062 " int i;\n" 11063 " // comment\n" 11064 "\n" 11065 "private:\n" 11066 " int j;\n" 11067 "};\n", 11068 "struct foo { /* comment */\n" 11069 "private:\n" 11070 " int i;\n" 11071 " // comment\n" 11072 "\n" 11073 "private:\n" 11074 " int j;\n" 11075 "};\n", 11076 Style); 11077 verifyFormat("struct foo {\n" 11078 "#ifdef FOO\n" 11079 "#endif\n" 11080 "\n" 11081 "private:\n" 11082 " int i;\n" 11083 "#ifdef FOO\n" 11084 "\n" 11085 "private:\n" 11086 "#endif\n" 11087 " int j;\n" 11088 "};\n", 11089 "struct foo {\n" 11090 "#ifdef FOO\n" 11091 "#endif\n" 11092 "private:\n" 11093 " int i;\n" 11094 "#ifdef FOO\n" 11095 "private:\n" 11096 "#endif\n" 11097 " int j;\n" 11098 "};\n", 11099 Style); 11100 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11101 EXPECT_EQ("struct foo {\n" 11102 "\n" 11103 "private:\n" 11104 " void f() {}\n" 11105 "\n" 11106 "private:\n" 11107 " int i;\n" 11108 "\n" 11109 "protected:\n" 11110 " int j;\n" 11111 "};\n", 11112 format("struct foo {\n" 11113 "\n" 11114 "private:\n" 11115 " void f() {}\n" 11116 "\n" 11117 "private:\n" 11118 " int i;\n" 11119 "\n" 11120 "protected:\n" 11121 " int j;\n" 11122 "};\n", 11123 Style)); 11124 verifyFormat("struct foo {\n" 11125 "private:\n" 11126 " void f() {}\n" 11127 "private:\n" 11128 " int i;\n" 11129 "protected:\n" 11130 " int j;\n" 11131 "};\n", 11132 Style); 11133 EXPECT_EQ("struct foo { /* comment */\n" 11134 "\n" 11135 "private:\n" 11136 " int i;\n" 11137 " // comment\n" 11138 "\n" 11139 "private:\n" 11140 " int j;\n" 11141 "};\n", 11142 format("struct foo { /* comment */\n" 11143 "\n" 11144 "private:\n" 11145 " int i;\n" 11146 " // comment\n" 11147 "\n" 11148 "private:\n" 11149 " int j;\n" 11150 "};\n", 11151 Style)); 11152 verifyFormat("struct foo { /* comment */\n" 11153 "private:\n" 11154 " int i;\n" 11155 " // comment\n" 11156 "private:\n" 11157 " int j;\n" 11158 "};\n", 11159 Style); 11160 EXPECT_EQ("struct foo {\n" 11161 "#ifdef FOO\n" 11162 "#endif\n" 11163 "\n" 11164 "private:\n" 11165 " int i;\n" 11166 "#ifdef FOO\n" 11167 "\n" 11168 "private:\n" 11169 "#endif\n" 11170 " int j;\n" 11171 "};\n", 11172 format("struct foo {\n" 11173 "#ifdef FOO\n" 11174 "#endif\n" 11175 "\n" 11176 "private:\n" 11177 " int i;\n" 11178 "#ifdef FOO\n" 11179 "\n" 11180 "private:\n" 11181 "#endif\n" 11182 " int j;\n" 11183 "};\n", 11184 Style)); 11185 verifyFormat("struct foo {\n" 11186 "#ifdef FOO\n" 11187 "#endif\n" 11188 "private:\n" 11189 " int i;\n" 11190 "#ifdef FOO\n" 11191 "private:\n" 11192 "#endif\n" 11193 " int j;\n" 11194 "};\n", 11195 Style); 11196 11197 FormatStyle NoEmptyLines = getLLVMStyle(); 11198 NoEmptyLines.MaxEmptyLinesToKeep = 0; 11199 verifyFormat("struct foo {\n" 11200 "private:\n" 11201 " void f() {}\n" 11202 "\n" 11203 "private:\n" 11204 " int i;\n" 11205 "\n" 11206 "public:\n" 11207 "protected:\n" 11208 " int j;\n" 11209 "};\n", 11210 NoEmptyLines); 11211 11212 NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11213 verifyFormat("struct foo {\n" 11214 "private:\n" 11215 " void f() {}\n" 11216 "private:\n" 11217 " int i;\n" 11218 "public:\n" 11219 "protected:\n" 11220 " int j;\n" 11221 "};\n", 11222 NoEmptyLines); 11223 11224 NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11225 verifyFormat("struct foo {\n" 11226 "private:\n" 11227 " void f() {}\n" 11228 "\n" 11229 "private:\n" 11230 " int i;\n" 11231 "\n" 11232 "public:\n" 11233 "\n" 11234 "protected:\n" 11235 " int j;\n" 11236 "};\n", 11237 NoEmptyLines); 11238 } 11239 11240 TEST_F(FormatTest, FormatsAfterAccessModifiers) { 11241 11242 FormatStyle Style = getLLVMStyle(); 11243 EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never); 11244 verifyFormat("struct foo {\n" 11245 "private:\n" 11246 " void f() {}\n" 11247 "\n" 11248 "private:\n" 11249 " int i;\n" 11250 "\n" 11251 "protected:\n" 11252 " int j;\n" 11253 "};\n", 11254 Style); 11255 11256 // Check if lines are removed. 11257 verifyFormat("struct foo {\n" 11258 "private:\n" 11259 " void f() {}\n" 11260 "\n" 11261 "private:\n" 11262 " int i;\n" 11263 "\n" 11264 "protected:\n" 11265 " int j;\n" 11266 "};\n", 11267 "struct foo {\n" 11268 "private:\n" 11269 "\n" 11270 " void f() {}\n" 11271 "\n" 11272 "private:\n" 11273 "\n" 11274 " int i;\n" 11275 "\n" 11276 "protected:\n" 11277 "\n" 11278 " int j;\n" 11279 "};\n", 11280 Style); 11281 11282 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11283 verifyFormat("struct foo {\n" 11284 "private:\n" 11285 "\n" 11286 " void f() {}\n" 11287 "\n" 11288 "private:\n" 11289 "\n" 11290 " int i;\n" 11291 "\n" 11292 "protected:\n" 11293 "\n" 11294 " int j;\n" 11295 "};\n", 11296 Style); 11297 11298 // Check if lines are added. 11299 verifyFormat("struct foo {\n" 11300 "private:\n" 11301 "\n" 11302 " void f() {}\n" 11303 "\n" 11304 "private:\n" 11305 "\n" 11306 " int i;\n" 11307 "\n" 11308 "protected:\n" 11309 "\n" 11310 " int j;\n" 11311 "};\n", 11312 "struct foo {\n" 11313 "private:\n" 11314 " void f() {}\n" 11315 "\n" 11316 "private:\n" 11317 " int i;\n" 11318 "\n" 11319 "protected:\n" 11320 " int j;\n" 11321 "};\n", 11322 Style); 11323 11324 // Leave tests rely on the code layout, test::messUp can not be used. 11325 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11326 Style.MaxEmptyLinesToKeep = 0u; 11327 verifyFormat("struct foo {\n" 11328 "private:\n" 11329 " void f() {}\n" 11330 "\n" 11331 "private:\n" 11332 " int i;\n" 11333 "\n" 11334 "protected:\n" 11335 " int j;\n" 11336 "};\n", 11337 Style); 11338 11339 // Check if MaxEmptyLinesToKeep is respected. 11340 EXPECT_EQ("struct foo {\n" 11341 "private:\n" 11342 " void f() {}\n" 11343 "\n" 11344 "private:\n" 11345 " int i;\n" 11346 "\n" 11347 "protected:\n" 11348 " int j;\n" 11349 "};\n", 11350 format("struct foo {\n" 11351 "private:\n" 11352 "\n\n\n" 11353 " void f() {}\n" 11354 "\n" 11355 "private:\n" 11356 "\n\n\n" 11357 " int i;\n" 11358 "\n" 11359 "protected:\n" 11360 "\n\n\n" 11361 " int j;\n" 11362 "};\n", 11363 Style)); 11364 11365 Style.MaxEmptyLinesToKeep = 1u; 11366 EXPECT_EQ("struct foo {\n" 11367 "private:\n" 11368 "\n" 11369 " void f() {}\n" 11370 "\n" 11371 "private:\n" 11372 "\n" 11373 " int i;\n" 11374 "\n" 11375 "protected:\n" 11376 "\n" 11377 " int j;\n" 11378 "};\n", 11379 format("struct foo {\n" 11380 "private:\n" 11381 "\n" 11382 " void f() {}\n" 11383 "\n" 11384 "private:\n" 11385 "\n" 11386 " int i;\n" 11387 "\n" 11388 "protected:\n" 11389 "\n" 11390 " int j;\n" 11391 "};\n", 11392 Style)); 11393 // Check if no lines are kept. 11394 EXPECT_EQ("struct foo {\n" 11395 "private:\n" 11396 " void f() {}\n" 11397 "\n" 11398 "private:\n" 11399 " int i;\n" 11400 "\n" 11401 "protected:\n" 11402 " int j;\n" 11403 "};\n", 11404 format("struct foo {\n" 11405 "private:\n" 11406 " void f() {}\n" 11407 "\n" 11408 "private:\n" 11409 " int i;\n" 11410 "\n" 11411 "protected:\n" 11412 " int j;\n" 11413 "};\n", 11414 Style)); 11415 // Check if MaxEmptyLinesToKeep is respected. 11416 EXPECT_EQ("struct foo {\n" 11417 "private:\n" 11418 "\n" 11419 " void f() {}\n" 11420 "\n" 11421 "private:\n" 11422 "\n" 11423 " int i;\n" 11424 "\n" 11425 "protected:\n" 11426 "\n" 11427 " int j;\n" 11428 "};\n", 11429 format("struct foo {\n" 11430 "private:\n" 11431 "\n\n\n" 11432 " void f() {}\n" 11433 "\n" 11434 "private:\n" 11435 "\n\n\n" 11436 " int i;\n" 11437 "\n" 11438 "protected:\n" 11439 "\n\n\n" 11440 " int j;\n" 11441 "};\n", 11442 Style)); 11443 11444 Style.MaxEmptyLinesToKeep = 10u; 11445 EXPECT_EQ("struct foo {\n" 11446 "private:\n" 11447 "\n\n\n" 11448 " void f() {}\n" 11449 "\n" 11450 "private:\n" 11451 "\n\n\n" 11452 " int i;\n" 11453 "\n" 11454 "protected:\n" 11455 "\n\n\n" 11456 " int j;\n" 11457 "};\n", 11458 format("struct foo {\n" 11459 "private:\n" 11460 "\n\n\n" 11461 " void f() {}\n" 11462 "\n" 11463 "private:\n" 11464 "\n\n\n" 11465 " int i;\n" 11466 "\n" 11467 "protected:\n" 11468 "\n\n\n" 11469 " int j;\n" 11470 "};\n", 11471 Style)); 11472 11473 // Test with comments. 11474 Style = getLLVMStyle(); 11475 verifyFormat("struct foo {\n" 11476 "private:\n" 11477 " // comment\n" 11478 " void f() {}\n" 11479 "\n" 11480 "private: /* comment */\n" 11481 " int i;\n" 11482 "};\n", 11483 Style); 11484 verifyFormat("struct foo {\n" 11485 "private:\n" 11486 " // comment\n" 11487 " void f() {}\n" 11488 "\n" 11489 "private: /* comment */\n" 11490 " int i;\n" 11491 "};\n", 11492 "struct foo {\n" 11493 "private:\n" 11494 "\n" 11495 " // comment\n" 11496 " void f() {}\n" 11497 "\n" 11498 "private: /* comment */\n" 11499 "\n" 11500 " int i;\n" 11501 "};\n", 11502 Style); 11503 11504 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11505 verifyFormat("struct foo {\n" 11506 "private:\n" 11507 "\n" 11508 " // comment\n" 11509 " void f() {}\n" 11510 "\n" 11511 "private: /* comment */\n" 11512 "\n" 11513 " int i;\n" 11514 "};\n", 11515 "struct foo {\n" 11516 "private:\n" 11517 " // comment\n" 11518 " void f() {}\n" 11519 "\n" 11520 "private: /* comment */\n" 11521 " int i;\n" 11522 "};\n", 11523 Style); 11524 verifyFormat("struct foo {\n" 11525 "private:\n" 11526 "\n" 11527 " // comment\n" 11528 " void f() {}\n" 11529 "\n" 11530 "private: /* comment */\n" 11531 "\n" 11532 " int i;\n" 11533 "};\n", 11534 Style); 11535 11536 // Test with preprocessor defines. 11537 Style = getLLVMStyle(); 11538 verifyFormat("struct foo {\n" 11539 "private:\n" 11540 "#ifdef FOO\n" 11541 "#endif\n" 11542 " void f() {}\n" 11543 "};\n", 11544 Style); 11545 verifyFormat("struct foo {\n" 11546 "private:\n" 11547 "#ifdef FOO\n" 11548 "#endif\n" 11549 " void f() {}\n" 11550 "};\n", 11551 "struct foo {\n" 11552 "private:\n" 11553 "\n" 11554 "#ifdef FOO\n" 11555 "#endif\n" 11556 " void f() {}\n" 11557 "};\n", 11558 Style); 11559 11560 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11561 verifyFormat("struct foo {\n" 11562 "private:\n" 11563 "\n" 11564 "#ifdef FOO\n" 11565 "#endif\n" 11566 " void f() {}\n" 11567 "};\n", 11568 "struct foo {\n" 11569 "private:\n" 11570 "#ifdef FOO\n" 11571 "#endif\n" 11572 " void f() {}\n" 11573 "};\n", 11574 Style); 11575 verifyFormat("struct foo {\n" 11576 "private:\n" 11577 "\n" 11578 "#ifdef FOO\n" 11579 "#endif\n" 11580 " void f() {}\n" 11581 "};\n", 11582 Style); 11583 } 11584 11585 TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) { 11586 // Combined tests of EmptyLineAfterAccessModifier and 11587 // EmptyLineBeforeAccessModifier. 11588 FormatStyle Style = getLLVMStyle(); 11589 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11590 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11591 verifyFormat("struct foo {\n" 11592 "private:\n" 11593 "\n" 11594 "protected:\n" 11595 "};\n", 11596 Style); 11597 11598 Style.MaxEmptyLinesToKeep = 10u; 11599 // Both remove all new lines. 11600 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11601 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11602 verifyFormat("struct foo {\n" 11603 "private:\n" 11604 "protected:\n" 11605 "};\n", 11606 "struct foo {\n" 11607 "private:\n" 11608 "\n\n\n" 11609 "protected:\n" 11610 "};\n", 11611 Style); 11612 11613 // Leave tests rely on the code layout, test::messUp can not be used. 11614 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11615 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11616 Style.MaxEmptyLinesToKeep = 10u; 11617 EXPECT_EQ("struct foo {\n" 11618 "private:\n" 11619 "\n\n\n" 11620 "protected:\n" 11621 "};\n", 11622 format("struct foo {\n" 11623 "private:\n" 11624 "\n\n\n" 11625 "protected:\n" 11626 "};\n", 11627 Style)); 11628 Style.MaxEmptyLinesToKeep = 3u; 11629 EXPECT_EQ("struct foo {\n" 11630 "private:\n" 11631 "\n\n\n" 11632 "protected:\n" 11633 "};\n", 11634 format("struct foo {\n" 11635 "private:\n" 11636 "\n\n\n" 11637 "protected:\n" 11638 "};\n", 11639 Style)); 11640 Style.MaxEmptyLinesToKeep = 1u; 11641 EXPECT_EQ("struct foo {\n" 11642 "private:\n" 11643 "\n\n\n" 11644 "protected:\n" 11645 "};\n", 11646 format("struct foo {\n" 11647 "private:\n" 11648 "\n\n\n" 11649 "protected:\n" 11650 "};\n", 11651 Style)); // Based on new lines in original document and not 11652 // on the setting. 11653 11654 Style.MaxEmptyLinesToKeep = 10u; 11655 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11656 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11657 // Newlines are kept if they are greater than zero, 11658 // test::messUp removes all new lines which changes the logic 11659 EXPECT_EQ("struct foo {\n" 11660 "private:\n" 11661 "\n\n\n" 11662 "protected:\n" 11663 "};\n", 11664 format("struct foo {\n" 11665 "private:\n" 11666 "\n\n\n" 11667 "protected:\n" 11668 "};\n", 11669 Style)); 11670 11671 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11672 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11673 // test::messUp removes all new lines which changes the logic 11674 EXPECT_EQ("struct foo {\n" 11675 "private:\n" 11676 "\n\n\n" 11677 "protected:\n" 11678 "};\n", 11679 format("struct foo {\n" 11680 "private:\n" 11681 "\n\n\n" 11682 "protected:\n" 11683 "};\n", 11684 Style)); 11685 11686 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11687 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11688 EXPECT_EQ("struct foo {\n" 11689 "private:\n" 11690 "\n\n\n" 11691 "protected:\n" 11692 "};\n", 11693 format("struct foo {\n" 11694 "private:\n" 11695 "\n\n\n" 11696 "protected:\n" 11697 "};\n", 11698 Style)); // test::messUp removes all new lines which changes 11699 // the logic. 11700 11701 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11702 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11703 verifyFormat("struct foo {\n" 11704 "private:\n" 11705 "protected:\n" 11706 "};\n", 11707 "struct foo {\n" 11708 "private:\n" 11709 "\n\n\n" 11710 "protected:\n" 11711 "};\n", 11712 Style); 11713 11714 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11715 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11716 EXPECT_EQ("struct foo {\n" 11717 "private:\n" 11718 "\n\n\n" 11719 "protected:\n" 11720 "};\n", 11721 format("struct foo {\n" 11722 "private:\n" 11723 "\n\n\n" 11724 "protected:\n" 11725 "};\n", 11726 Style)); // test::messUp removes all new lines which changes 11727 // the logic. 11728 11729 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11730 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11731 verifyFormat("struct foo {\n" 11732 "private:\n" 11733 "protected:\n" 11734 "};\n", 11735 "struct foo {\n" 11736 "private:\n" 11737 "\n\n\n" 11738 "protected:\n" 11739 "};\n", 11740 Style); 11741 11742 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11743 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11744 verifyFormat("struct foo {\n" 11745 "private:\n" 11746 "protected:\n" 11747 "};\n", 11748 "struct foo {\n" 11749 "private:\n" 11750 "\n\n\n" 11751 "protected:\n" 11752 "};\n", 11753 Style); 11754 11755 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11756 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11757 verifyFormat("struct foo {\n" 11758 "private:\n" 11759 "protected:\n" 11760 "};\n", 11761 "struct foo {\n" 11762 "private:\n" 11763 "\n\n\n" 11764 "protected:\n" 11765 "};\n", 11766 Style); 11767 11768 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11769 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11770 verifyFormat("struct foo {\n" 11771 "private:\n" 11772 "protected:\n" 11773 "};\n", 11774 "struct foo {\n" 11775 "private:\n" 11776 "\n\n\n" 11777 "protected:\n" 11778 "};\n", 11779 Style); 11780 } 11781 11782 TEST_F(FormatTest, FormatsArrays) { 11783 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n" 11784 " [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;"); 11785 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n" 11786 " [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;"); 11787 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n" 11788 " aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}"); 11789 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11790 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;"); 11791 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11792 " [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;"); 11793 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11794 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n" 11795 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;"); 11796 verifyFormat( 11797 "llvm::outs() << \"aaaaaaaaaaaa: \"\n" 11798 " << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n" 11799 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];"); 11800 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n" 11801 " .aaaaaaaaaaaaaaaaaaaaaa();"); 11802 11803 verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n" 11804 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];"); 11805 verifyFormat( 11806 "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n" 11807 " .aaaaaaa[0]\n" 11808 " .aaaaaaaaaaaaaaaaaaaaaa();"); 11809 verifyFormat("a[::b::c];"); 11810 11811 verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10)); 11812 11813 FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0); 11814 verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit); 11815 } 11816 11817 TEST_F(FormatTest, LineStartsWithSpecialCharacter) { 11818 verifyFormat("(a)->b();"); 11819 verifyFormat("--a;"); 11820 } 11821 11822 TEST_F(FormatTest, HandlesIncludeDirectives) { 11823 verifyFormat("#include <string>\n" 11824 "#include <a/b/c.h>\n" 11825 "#include \"a/b/string\"\n" 11826 "#include \"string.h\"\n" 11827 "#include \"string.h\"\n" 11828 "#include <a-a>\n" 11829 "#include < path with space >\n" 11830 "#include_next <test.h>" 11831 "#include \"abc.h\" // this is included for ABC\n" 11832 "#include \"some long include\" // with a comment\n" 11833 "#include \"some very long include path\"\n" 11834 "#include <some/very/long/include/path>\n", 11835 getLLVMStyleWithColumns(35)); 11836 EXPECT_EQ("#include \"a.h\"", format("#include \"a.h\"")); 11837 EXPECT_EQ("#include <a>", format("#include<a>")); 11838 11839 verifyFormat("#import <string>"); 11840 verifyFormat("#import <a/b/c.h>"); 11841 verifyFormat("#import \"a/b/string\""); 11842 verifyFormat("#import \"string.h\""); 11843 verifyFormat("#import \"string.h\""); 11844 verifyFormat("#if __has_include(<strstream>)\n" 11845 "#include <strstream>\n" 11846 "#endif"); 11847 11848 verifyFormat("#define MY_IMPORT <a/b>"); 11849 11850 verifyFormat("#if __has_include(<a/b>)"); 11851 verifyFormat("#if __has_include_next(<a/b>)"); 11852 verifyFormat("#define F __has_include(<a/b>)"); 11853 verifyFormat("#define F __has_include_next(<a/b>)"); 11854 11855 // Protocol buffer definition or missing "#". 11856 verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";", 11857 getLLVMStyleWithColumns(30)); 11858 11859 FormatStyle Style = getLLVMStyle(); 11860 Style.AlwaysBreakBeforeMultilineStrings = true; 11861 Style.ColumnLimit = 0; 11862 verifyFormat("#import \"abc.h\"", Style); 11863 11864 // But 'import' might also be a regular C++ namespace. 11865 verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 11866 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 11867 } 11868 11869 //===----------------------------------------------------------------------===// 11870 // Error recovery tests. 11871 //===----------------------------------------------------------------------===// 11872 11873 TEST_F(FormatTest, IncompleteParameterLists) { 11874 FormatStyle NoBinPacking = getLLVMStyle(); 11875 NoBinPacking.BinPackParameters = false; 11876 verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n" 11877 " double *min_x,\n" 11878 " double *max_x,\n" 11879 " double *min_y,\n" 11880 " double *max_y,\n" 11881 " double *min_z,\n" 11882 " double *max_z, ) {}", 11883 NoBinPacking); 11884 } 11885 11886 TEST_F(FormatTest, IncorrectCodeTrailingStuff) { 11887 verifyFormat("void f() { return; }\n42"); 11888 verifyFormat("void f() {\n" 11889 " if (0)\n" 11890 " return;\n" 11891 "}\n" 11892 "42"); 11893 verifyFormat("void f() { return }\n42"); 11894 verifyFormat("void f() {\n" 11895 " if (0)\n" 11896 " return\n" 11897 "}\n" 11898 "42"); 11899 } 11900 11901 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) { 11902 EXPECT_EQ("void f() { return }", format("void f ( ) { return }")); 11903 EXPECT_EQ("void f() {\n" 11904 " if (a)\n" 11905 " return\n" 11906 "}", 11907 format("void f ( ) { if ( a ) return }")); 11908 EXPECT_EQ("namespace N {\n" 11909 "void f()\n" 11910 "}", 11911 format("namespace N { void f() }")); 11912 EXPECT_EQ("namespace N {\n" 11913 "void f() {}\n" 11914 "void g()\n" 11915 "} // namespace N", 11916 format("namespace N { void f( ) { } void g( ) }")); 11917 } 11918 11919 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) { 11920 verifyFormat("int aaaaaaaa =\n" 11921 " // Overlylongcomment\n" 11922 " b;", 11923 getLLVMStyleWithColumns(20)); 11924 verifyFormat("function(\n" 11925 " ShortArgument,\n" 11926 " LoooooooooooongArgument);\n", 11927 getLLVMStyleWithColumns(20)); 11928 } 11929 11930 TEST_F(FormatTest, IncorrectAccessSpecifier) { 11931 verifyFormat("public:"); 11932 verifyFormat("class A {\n" 11933 "public\n" 11934 " void f() {}\n" 11935 "};"); 11936 verifyFormat("public\n" 11937 "int qwerty;"); 11938 verifyFormat("public\n" 11939 "B {}"); 11940 verifyFormat("public\n" 11941 "{}"); 11942 verifyFormat("public\n" 11943 "B { int x; }"); 11944 } 11945 11946 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) { 11947 verifyFormat("{"); 11948 verifyFormat("#})"); 11949 verifyNoCrash("(/**/[:!] ?[)."); 11950 } 11951 11952 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) { 11953 // Found by oss-fuzz: 11954 // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212 11955 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp); 11956 Style.ColumnLimit = 60; 11957 verifyNoCrash( 11958 "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20" 11959 "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20" 11960 "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a", 11961 Style); 11962 } 11963 11964 TEST_F(FormatTest, IncorrectCodeDoNoWhile) { 11965 verifyFormat("do {\n}"); 11966 verifyFormat("do {\n}\n" 11967 "f();"); 11968 verifyFormat("do {\n}\n" 11969 "wheeee(fun);"); 11970 verifyFormat("do {\n" 11971 " f();\n" 11972 "}"); 11973 } 11974 11975 TEST_F(FormatTest, IncorrectCodeMissingParens) { 11976 verifyFormat("if {\n foo;\n foo();\n}"); 11977 verifyFormat("switch {\n foo;\n foo();\n}"); 11978 verifyIncompleteFormat("for {\n foo;\n foo();\n}"); 11979 verifyFormat("while {\n foo;\n foo();\n}"); 11980 verifyFormat("do {\n foo;\n foo();\n} while;"); 11981 } 11982 11983 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) { 11984 verifyIncompleteFormat("namespace {\n" 11985 "class Foo { Foo (\n" 11986 "};\n" 11987 "} // namespace"); 11988 } 11989 11990 TEST_F(FormatTest, IncorrectCodeErrorDetection) { 11991 EXPECT_EQ("{\n {}\n", format("{\n{\n}\n")); 11992 EXPECT_EQ("{\n {}\n", format("{\n {\n}\n")); 11993 EXPECT_EQ("{\n {}\n", format("{\n {\n }\n")); 11994 EXPECT_EQ("{\n {}\n}\n}\n", format("{\n {\n }\n }\n}\n")); 11995 11996 EXPECT_EQ("{\n" 11997 " {\n" 11998 " breakme(\n" 11999 " qwe);\n" 12000 " }\n", 12001 format("{\n" 12002 " {\n" 12003 " breakme(qwe);\n" 12004 "}\n", 12005 getLLVMStyleWithColumns(10))); 12006 } 12007 12008 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) { 12009 verifyFormat("int x = {\n" 12010 " avariable,\n" 12011 " b(alongervariable)};", 12012 getLLVMStyleWithColumns(25)); 12013 } 12014 12015 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) { 12016 verifyFormat("return (a)(b){1, 2, 3};"); 12017 } 12018 12019 TEST_F(FormatTest, LayoutCxx11BraceInitializers) { 12020 verifyFormat("vector<int> x{1, 2, 3, 4};"); 12021 verifyFormat("vector<int> x{\n" 12022 " 1,\n" 12023 " 2,\n" 12024 " 3,\n" 12025 " 4,\n" 12026 "};"); 12027 verifyFormat("vector<T> x{{}, {}, {}, {}};"); 12028 verifyFormat("f({1, 2});"); 12029 verifyFormat("auto v = Foo{-1};"); 12030 verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});"); 12031 verifyFormat("Class::Class : member{1, 2, 3} {}"); 12032 verifyFormat("new vector<int>{1, 2, 3};"); 12033 verifyFormat("new int[3]{1, 2, 3};"); 12034 verifyFormat("new int{1};"); 12035 verifyFormat("return {arg1, arg2};"); 12036 verifyFormat("return {arg1, SomeType{parameter}};"); 12037 verifyFormat("int count = set<int>{f(), g(), h()}.size();"); 12038 verifyFormat("new T{arg1, arg2};"); 12039 verifyFormat("f(MyMap[{composite, key}]);"); 12040 verifyFormat("class Class {\n" 12041 " T member = {arg1, arg2};\n" 12042 "};"); 12043 verifyFormat("vector<int> foo = {::SomeGlobalFunction()};"); 12044 verifyFormat("const struct A a = {.a = 1, .b = 2};"); 12045 verifyFormat("const struct A a = {[0] = 1, [1] = 2};"); 12046 verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");"); 12047 verifyFormat("int a = std::is_integral<int>{} + 0;"); 12048 12049 verifyFormat("int foo(int i) { return fo1{}(i); }"); 12050 verifyFormat("int foo(int i) { return fo1{}(i); }"); 12051 verifyFormat("auto i = decltype(x){};"); 12052 verifyFormat("auto i = typeof(x){};"); 12053 verifyFormat("auto i = _Atomic(x){};"); 12054 verifyFormat("std::vector<int> v = {1, 0 /* comment */};"); 12055 verifyFormat("Node n{1, Node{1000}, //\n" 12056 " 2};"); 12057 verifyFormat("Aaaa aaaaaaa{\n" 12058 " {\n" 12059 " aaaa,\n" 12060 " },\n" 12061 "};"); 12062 verifyFormat("class C : public D {\n" 12063 " SomeClass SC{2};\n" 12064 "};"); 12065 verifyFormat("class C : public A {\n" 12066 " class D : public B {\n" 12067 " void f() { int i{2}; }\n" 12068 " };\n" 12069 "};"); 12070 verifyFormat("#define A {a, a},"); 12071 // Don't confuse braced list initializers with compound statements. 12072 verifyFormat( 12073 "class A {\n" 12074 " A() : a{} {}\n" 12075 " A(int b) : b(b) {}\n" 12076 " A(int a, int b) : a(a), bs{{bs...}} { f(); }\n" 12077 " int a, b;\n" 12078 " explicit Expr(const Scalar<Result> &x) : u{Constant<Result>{x}} {}\n" 12079 " explicit Expr(Scalar<Result> &&x) : u{Constant<Result>{std::move(x)}} " 12080 "{}\n" 12081 "};"); 12082 12083 // Avoid breaking between equal sign and opening brace 12084 FormatStyle AvoidBreakingFirstArgument = getLLVMStyle(); 12085 AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200; 12086 verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n" 12087 " {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n" 12088 " {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n" 12089 " {\"ccccccccccccccccccccc\", 2}};", 12090 AvoidBreakingFirstArgument); 12091 12092 // Binpacking only if there is no trailing comma 12093 verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n" 12094 " cccccccccc, dddddddddd};", 12095 getLLVMStyleWithColumns(50)); 12096 verifyFormat("const Aaaaaa aaaaa = {\n" 12097 " aaaaaaaaaaa,\n" 12098 " bbbbbbbbbbb,\n" 12099 " ccccccccccc,\n" 12100 " ddddddddddd,\n" 12101 "};", 12102 getLLVMStyleWithColumns(50)); 12103 12104 // Cases where distinguising braced lists and blocks is hard. 12105 verifyFormat("vector<int> v{12} GUARDED_BY(mutex);"); 12106 verifyFormat("void f() {\n" 12107 " return; // comment\n" 12108 "}\n" 12109 "SomeType t;"); 12110 verifyFormat("void f() {\n" 12111 " if (a) {\n" 12112 " f();\n" 12113 " }\n" 12114 "}\n" 12115 "SomeType t;"); 12116 12117 // In combination with BinPackArguments = false. 12118 FormatStyle NoBinPacking = getLLVMStyle(); 12119 NoBinPacking.BinPackArguments = false; 12120 verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n" 12121 " bbbbb,\n" 12122 " ccccc,\n" 12123 " ddddd,\n" 12124 " eeeee,\n" 12125 " ffffff,\n" 12126 " ggggg,\n" 12127 " hhhhhh,\n" 12128 " iiiiii,\n" 12129 " jjjjjj,\n" 12130 " kkkkkk};", 12131 NoBinPacking); 12132 verifyFormat("const Aaaaaa aaaaa = {\n" 12133 " aaaaa,\n" 12134 " bbbbb,\n" 12135 " ccccc,\n" 12136 " ddddd,\n" 12137 " eeeee,\n" 12138 " ffffff,\n" 12139 " ggggg,\n" 12140 " hhhhhh,\n" 12141 " iiiiii,\n" 12142 " jjjjjj,\n" 12143 " kkkkkk,\n" 12144 "};", 12145 NoBinPacking); 12146 verifyFormat( 12147 "const Aaaaaa aaaaa = {\n" 12148 " aaaaa, bbbbb, ccccc, ddddd, eeeee, ffffff, ggggg, hhhhhh,\n" 12149 " iiiiii, jjjjjj, kkkkkk, aaaaa, bbbbb, ccccc, ddddd, eeeee,\n" 12150 " ffffff, ggggg, hhhhhh, iiiiii, jjjjjj, kkkkkk,\n" 12151 "};", 12152 NoBinPacking); 12153 12154 NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 12155 EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n" 12156 " CDDDP83848_BMCR_REGISTER,\n" 12157 " CDDDP83848_BMSR_REGISTER,\n" 12158 " CDDDP83848_RBR_REGISTER};", 12159 format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n" 12160 " CDDDP83848_BMSR_REGISTER,\n" 12161 " CDDDP83848_RBR_REGISTER};", 12162 NoBinPacking)); 12163 12164 // FIXME: The alignment of these trailing comments might be bad. Then again, 12165 // this might be utterly useless in real code. 12166 verifyFormat("Constructor::Constructor()\n" 12167 " : some_value{ //\n" 12168 " aaaaaaa, //\n" 12169 " bbbbbbb} {}"); 12170 12171 // In braced lists, the first comment is always assumed to belong to the 12172 // first element. Thus, it can be moved to the next or previous line as 12173 // appropriate. 12174 EXPECT_EQ("function({// First element:\n" 12175 " 1,\n" 12176 " // Second element:\n" 12177 " 2});", 12178 format("function({\n" 12179 " // First element:\n" 12180 " 1,\n" 12181 " // Second element:\n" 12182 " 2});")); 12183 EXPECT_EQ("std::vector<int> MyNumbers{\n" 12184 " // First element:\n" 12185 " 1,\n" 12186 " // Second element:\n" 12187 " 2};", 12188 format("std::vector<int> MyNumbers{// First element:\n" 12189 " 1,\n" 12190 " // Second element:\n" 12191 " 2};", 12192 getLLVMStyleWithColumns(30))); 12193 // A trailing comma should still lead to an enforced line break and no 12194 // binpacking. 12195 EXPECT_EQ("vector<int> SomeVector = {\n" 12196 " // aaa\n" 12197 " 1,\n" 12198 " 2,\n" 12199 "};", 12200 format("vector<int> SomeVector = { // aaa\n" 12201 " 1, 2, };")); 12202 12203 // C++11 brace initializer list l-braces should not be treated any differently 12204 // when breaking before lambda bodies is enabled 12205 FormatStyle BreakBeforeLambdaBody = getLLVMStyle(); 12206 BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 12207 BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 12208 BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true; 12209 verifyFormat( 12210 "std::runtime_error{\n" 12211 " \"Long string which will force a break onto the next line...\"};", 12212 BreakBeforeLambdaBody); 12213 12214 FormatStyle ExtraSpaces = getLLVMStyle(); 12215 ExtraSpaces.Cpp11BracedListStyle = false; 12216 ExtraSpaces.ColumnLimit = 75; 12217 verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces); 12218 verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces); 12219 verifyFormat("f({ 1, 2 });", ExtraSpaces); 12220 verifyFormat("auto v = Foo{ 1 };", ExtraSpaces); 12221 verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces); 12222 verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces); 12223 verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces); 12224 verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces); 12225 verifyFormat("return { arg1, arg2 };", ExtraSpaces); 12226 verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces); 12227 verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces); 12228 verifyFormat("new T{ arg1, arg2 };", ExtraSpaces); 12229 verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces); 12230 verifyFormat("class Class {\n" 12231 " T member = { arg1, arg2 };\n" 12232 "};", 12233 ExtraSpaces); 12234 verifyFormat( 12235 "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12236 " aaaaaaaaaaaaaaaaaaaa, aaaaa }\n" 12237 " : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 12238 " bbbbbbbbbbbbbbbbbbbb, bbbbb };", 12239 ExtraSpaces); 12240 verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces); 12241 verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });", 12242 ExtraSpaces); 12243 verifyFormat( 12244 "someFunction(OtherParam,\n" 12245 " BracedList{ // comment 1 (Forcing interesting break)\n" 12246 " param1, param2,\n" 12247 " // comment 2\n" 12248 " param3, param4 });", 12249 ExtraSpaces); 12250 verifyFormat( 12251 "std::this_thread::sleep_for(\n" 12252 " std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);", 12253 ExtraSpaces); 12254 verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n" 12255 " aaaaaaa,\n" 12256 " aaaaaaaaaa,\n" 12257 " aaaaa,\n" 12258 " aaaaaaaaaaaaaaa,\n" 12259 " aaa,\n" 12260 " aaaaaaaaaa,\n" 12261 " a,\n" 12262 " aaaaaaaaaaaaaaaaaaaaa,\n" 12263 " aaaaaaaaaaaa,\n" 12264 " aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n" 12265 " aaaaaaa,\n" 12266 " a};"); 12267 verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces); 12268 verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces); 12269 verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces); 12270 12271 // Avoid breaking between initializer/equal sign and opening brace 12272 ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200; 12273 verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n" 12274 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n" 12275 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n" 12276 " { \"ccccccccccccccccccccc\", 2 }\n" 12277 "};", 12278 ExtraSpaces); 12279 verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n" 12280 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n" 12281 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n" 12282 " { \"ccccccccccccccccccccc\", 2 }\n" 12283 "};", 12284 ExtraSpaces); 12285 12286 FormatStyle SpaceBeforeBrace = getLLVMStyle(); 12287 SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true; 12288 verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace); 12289 verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace); 12290 12291 FormatStyle SpaceBetweenBraces = getLLVMStyle(); 12292 SpaceBetweenBraces.SpacesInAngles = FormatStyle::SIAS_Always; 12293 SpaceBetweenBraces.SpacesInParentheses = true; 12294 SpaceBetweenBraces.SpacesInSquareBrackets = true; 12295 verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces); 12296 verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces); 12297 verifyFormat("vector< int > x{ // comment 1\n" 12298 " 1, 2, 3, 4 };", 12299 SpaceBetweenBraces); 12300 SpaceBetweenBraces.ColumnLimit = 20; 12301 EXPECT_EQ("vector< int > x{\n" 12302 " 1, 2, 3, 4 };", 12303 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces)); 12304 SpaceBetweenBraces.ColumnLimit = 24; 12305 EXPECT_EQ("vector< int > x{ 1, 2,\n" 12306 " 3, 4 };", 12307 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces)); 12308 EXPECT_EQ("vector< int > x{\n" 12309 " 1,\n" 12310 " 2,\n" 12311 " 3,\n" 12312 " 4,\n" 12313 "};", 12314 format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces)); 12315 verifyFormat("vector< int > x{};", SpaceBetweenBraces); 12316 SpaceBetweenBraces.SpaceInEmptyParentheses = true; 12317 verifyFormat("vector< int > x{ };", SpaceBetweenBraces); 12318 } 12319 12320 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) { 12321 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12322 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12323 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12324 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12325 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12326 " 1, 22, 333, 4444, 55555, 666666, 7777777};"); 12327 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n" 12328 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12329 " 1, 22, 333, 4444, 55555, //\n" 12330 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12331 " 1, 22, 333, 4444, 55555, 666666, 7777777};"); 12332 verifyFormat( 12333 "vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12334 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12335 " 1, 22, 333, 4444, 55555, 666666, // comment\n" 12336 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12337 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12338 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 12339 " 7777777};"); 12340 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12341 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12342 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12343 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12344 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12345 " // Separating comment.\n" 12346 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12347 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 12348 " // Leading comment\n" 12349 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 12350 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 12351 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12352 " 1, 1, 1, 1};", 12353 getLLVMStyleWithColumns(39)); 12354 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12355 " 1, 1, 1, 1};", 12356 getLLVMStyleWithColumns(38)); 12357 verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n" 12358 " 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};", 12359 getLLVMStyleWithColumns(43)); 12360 verifyFormat( 12361 "static unsigned SomeValues[10][3] = {\n" 12362 " {1, 4, 0}, {4, 9, 0}, {4, 5, 9}, {8, 5, 4}, {1, 8, 4},\n" 12363 " {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};"); 12364 verifyFormat("static auto fields = new vector<string>{\n" 12365 " \"aaaaaaaaaaaaa\",\n" 12366 " \"aaaaaaaaaaaaa\",\n" 12367 " \"aaaaaaaaaaaa\",\n" 12368 " \"aaaaaaaaaaaaaa\",\n" 12369 " \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n" 12370 " \"aaaaaaaaaaaa\",\n" 12371 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n" 12372 "};"); 12373 verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};"); 12374 verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n" 12375 " 2, bbbbbbbbbbbbbbbbbbbbbb,\n" 12376 " 3, cccccccccccccccccccccc};", 12377 getLLVMStyleWithColumns(60)); 12378 12379 // Trailing commas. 12380 verifyFormat("vector<int> x = {\n" 12381 " 1, 1, 1, 1, 1, 1, 1, 1,\n" 12382 "};", 12383 getLLVMStyleWithColumns(39)); 12384 verifyFormat("vector<int> x = {\n" 12385 " 1, 1, 1, 1, 1, 1, 1, 1, //\n" 12386 "};", 12387 getLLVMStyleWithColumns(39)); 12388 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 12389 " 1, 1, 1, 1,\n" 12390 " /**/ /**/};", 12391 getLLVMStyleWithColumns(39)); 12392 12393 // Trailing comment in the first line. 12394 verifyFormat("vector<int> iiiiiiiiiiiiiii = { //\n" 12395 " 1111111111, 2222222222, 33333333333, 4444444444, //\n" 12396 " 111111111, 222222222, 3333333333, 444444444, //\n" 12397 " 11111111, 22222222, 333333333, 44444444};"); 12398 // Trailing comment in the last line. 12399 verifyFormat("int aaaaa[] = {\n" 12400 " 1, 2, 3, // comment\n" 12401 " 4, 5, 6 // comment\n" 12402 "};"); 12403 12404 // With nested lists, we should either format one item per line or all nested 12405 // lists one on line. 12406 // FIXME: For some nested lists, we can do better. 12407 verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n" 12408 " {aaaaaaaaaaaaaaaaaaa},\n" 12409 " {aaaaaaaaaaaaaaaaaaaaa},\n" 12410 " {aaaaaaaaaaaaaaaaa}};", 12411 getLLVMStyleWithColumns(60)); 12412 verifyFormat( 12413 "SomeStruct my_struct_array = {\n" 12414 " {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n" 12415 " aaaaaaaaaaaaa, aaaaaaa, aaa},\n" 12416 " {aaa, aaa},\n" 12417 " {aaa, aaa},\n" 12418 " {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n" 12419 " {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n" 12420 " aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};"); 12421 12422 // No column layout should be used here. 12423 verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n" 12424 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};"); 12425 12426 verifyNoCrash("a<,"); 12427 12428 // No braced initializer here. 12429 verifyFormat("void f() {\n" 12430 " struct Dummy {};\n" 12431 " f(v);\n" 12432 "}"); 12433 12434 // Long lists should be formatted in columns even if they are nested. 12435 verifyFormat( 12436 "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12437 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12438 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12439 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12440 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 12441 " 1, 22, 333, 4444, 55555, 666666, 7777777});"); 12442 12443 // Allow "single-column" layout even if that violates the column limit. There 12444 // isn't going to be a better way. 12445 verifyFormat("std::vector<int> a = {\n" 12446 " aaaaaaaa,\n" 12447 " aaaaaaaa,\n" 12448 " aaaaaaaa,\n" 12449 " aaaaaaaa,\n" 12450 " aaaaaaaaaa,\n" 12451 " aaaaaaaa,\n" 12452 " aaaaaaaaaaaaaaaaaaaaaaaaaaa};", 12453 getLLVMStyleWithColumns(30)); 12454 verifyFormat("vector<int> aaaa = {\n" 12455 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12456 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12457 " aaaaaa.aaaaaaa,\n" 12458 " aaaaaa.aaaaaaa,\n" 12459 " aaaaaa.aaaaaaa,\n" 12460 " aaaaaa.aaaaaaa,\n" 12461 "};"); 12462 12463 // Don't create hanging lists. 12464 verifyFormat("someFunction(Param, {List1, List2,\n" 12465 " List3});", 12466 getLLVMStyleWithColumns(35)); 12467 verifyFormat("someFunction(Param, Param,\n" 12468 " {List1, List2,\n" 12469 " List3});", 12470 getLLVMStyleWithColumns(35)); 12471 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n" 12472 " aaaaaaaaaaaaaaaaaaaaaaa);"); 12473 } 12474 12475 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) { 12476 FormatStyle DoNotMerge = getLLVMStyle(); 12477 DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12478 12479 verifyFormat("void f() { return 42; }"); 12480 verifyFormat("void f() {\n" 12481 " return 42;\n" 12482 "}", 12483 DoNotMerge); 12484 verifyFormat("void f() {\n" 12485 " // Comment\n" 12486 "}"); 12487 verifyFormat("{\n" 12488 "#error {\n" 12489 " int a;\n" 12490 "}"); 12491 verifyFormat("{\n" 12492 " int a;\n" 12493 "#error {\n" 12494 "}"); 12495 verifyFormat("void f() {} // comment"); 12496 verifyFormat("void f() { int a; } // comment"); 12497 verifyFormat("void f() {\n" 12498 "} // comment", 12499 DoNotMerge); 12500 verifyFormat("void f() {\n" 12501 " int a;\n" 12502 "} // comment", 12503 DoNotMerge); 12504 verifyFormat("void f() {\n" 12505 "} // comment", 12506 getLLVMStyleWithColumns(15)); 12507 12508 verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23)); 12509 verifyFormat("void f() {\n return 42;\n}", getLLVMStyleWithColumns(22)); 12510 12511 verifyFormat("void f() {}", getLLVMStyleWithColumns(11)); 12512 verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10)); 12513 verifyFormat("class C {\n" 12514 " C()\n" 12515 " : iiiiiiii(nullptr),\n" 12516 " kkkkkkk(nullptr),\n" 12517 " mmmmmmm(nullptr),\n" 12518 " nnnnnnn(nullptr) {}\n" 12519 "};", 12520 getGoogleStyle()); 12521 12522 FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0); 12523 EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit)); 12524 EXPECT_EQ("class C {\n" 12525 " A() : b(0) {}\n" 12526 "};", 12527 format("class C{A():b(0){}};", NoColumnLimit)); 12528 EXPECT_EQ("A()\n" 12529 " : b(0) {\n" 12530 "}", 12531 format("A()\n:b(0)\n{\n}", NoColumnLimit)); 12532 12533 FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit; 12534 DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine = 12535 FormatStyle::SFS_None; 12536 EXPECT_EQ("A()\n" 12537 " : b(0) {\n" 12538 "}", 12539 format("A():b(0){}", DoNotMergeNoColumnLimit)); 12540 EXPECT_EQ("A()\n" 12541 " : b(0) {\n" 12542 "}", 12543 format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit)); 12544 12545 verifyFormat("#define A \\\n" 12546 " void f() { \\\n" 12547 " int i; \\\n" 12548 " }", 12549 getLLVMStyleWithColumns(20)); 12550 verifyFormat("#define A \\\n" 12551 " void f() { int i; }", 12552 getLLVMStyleWithColumns(21)); 12553 verifyFormat("#define A \\\n" 12554 " void f() { \\\n" 12555 " int i; \\\n" 12556 " } \\\n" 12557 " int j;", 12558 getLLVMStyleWithColumns(22)); 12559 verifyFormat("#define A \\\n" 12560 " void f() { int i; } \\\n" 12561 " int j;", 12562 getLLVMStyleWithColumns(23)); 12563 } 12564 12565 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) { 12566 FormatStyle MergeEmptyOnly = getLLVMStyle(); 12567 MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 12568 verifyFormat("class C {\n" 12569 " int f() {}\n" 12570 "};", 12571 MergeEmptyOnly); 12572 verifyFormat("class C {\n" 12573 " int f() {\n" 12574 " return 42;\n" 12575 " }\n" 12576 "};", 12577 MergeEmptyOnly); 12578 verifyFormat("int f() {}", MergeEmptyOnly); 12579 verifyFormat("int f() {\n" 12580 " return 42;\n" 12581 "}", 12582 MergeEmptyOnly); 12583 12584 // Also verify behavior when BraceWrapping.AfterFunction = true 12585 MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12586 MergeEmptyOnly.BraceWrapping.AfterFunction = true; 12587 verifyFormat("int f() {}", MergeEmptyOnly); 12588 verifyFormat("class C {\n" 12589 " int f() {}\n" 12590 "};", 12591 MergeEmptyOnly); 12592 } 12593 12594 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) { 12595 FormatStyle MergeInlineOnly = getLLVMStyle(); 12596 MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 12597 verifyFormat("class C {\n" 12598 " int f() { return 42; }\n" 12599 "};", 12600 MergeInlineOnly); 12601 verifyFormat("int f() {\n" 12602 " return 42;\n" 12603 "}", 12604 MergeInlineOnly); 12605 12606 // SFS_Inline implies SFS_Empty 12607 verifyFormat("class C {\n" 12608 " int f() {}\n" 12609 "};", 12610 MergeInlineOnly); 12611 verifyFormat("int f() {}", MergeInlineOnly); 12612 12613 // Also verify behavior when BraceWrapping.AfterFunction = true 12614 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12615 MergeInlineOnly.BraceWrapping.AfterFunction = true; 12616 verifyFormat("class C {\n" 12617 " int f() { return 42; }\n" 12618 "};", 12619 MergeInlineOnly); 12620 verifyFormat("int f()\n" 12621 "{\n" 12622 " return 42;\n" 12623 "}", 12624 MergeInlineOnly); 12625 12626 // SFS_Inline implies SFS_Empty 12627 verifyFormat("int f() {}", MergeInlineOnly); 12628 verifyFormat("class C {\n" 12629 " int f() {}\n" 12630 "};", 12631 MergeInlineOnly); 12632 12633 MergeInlineOnly.BraceWrapping.AfterClass = true; 12634 MergeInlineOnly.BraceWrapping.AfterStruct = true; 12635 verifyFormat("class C\n" 12636 "{\n" 12637 " int f() { return 42; }\n" 12638 "};", 12639 MergeInlineOnly); 12640 verifyFormat("struct C\n" 12641 "{\n" 12642 " int f() { return 42; }\n" 12643 "};", 12644 MergeInlineOnly); 12645 verifyFormat("int f()\n" 12646 "{\n" 12647 " return 42;\n" 12648 "}", 12649 MergeInlineOnly); 12650 verifyFormat("int f() {}", MergeInlineOnly); 12651 verifyFormat("class C\n" 12652 "{\n" 12653 " int f() { return 42; }\n" 12654 "};", 12655 MergeInlineOnly); 12656 verifyFormat("struct C\n" 12657 "{\n" 12658 " int f() { return 42; }\n" 12659 "};", 12660 MergeInlineOnly); 12661 verifyFormat("struct C\n" 12662 "// comment\n" 12663 "/* comment */\n" 12664 "// comment\n" 12665 "{\n" 12666 " int f() { return 42; }\n" 12667 "};", 12668 MergeInlineOnly); 12669 verifyFormat("/* comment */ struct C\n" 12670 "{\n" 12671 " int f() { return 42; }\n" 12672 "};", 12673 MergeInlineOnly); 12674 } 12675 12676 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) { 12677 FormatStyle MergeInlineOnly = getLLVMStyle(); 12678 MergeInlineOnly.AllowShortFunctionsOnASingleLine = 12679 FormatStyle::SFS_InlineOnly; 12680 verifyFormat("class C {\n" 12681 " int f() { return 42; }\n" 12682 "};", 12683 MergeInlineOnly); 12684 verifyFormat("int f() {\n" 12685 " return 42;\n" 12686 "}", 12687 MergeInlineOnly); 12688 12689 // SFS_InlineOnly does not imply SFS_Empty 12690 verifyFormat("class C {\n" 12691 " int f() {}\n" 12692 "};", 12693 MergeInlineOnly); 12694 verifyFormat("int f() {\n" 12695 "}", 12696 MergeInlineOnly); 12697 12698 // Also verify behavior when BraceWrapping.AfterFunction = true 12699 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12700 MergeInlineOnly.BraceWrapping.AfterFunction = true; 12701 verifyFormat("class C {\n" 12702 " int f() { return 42; }\n" 12703 "};", 12704 MergeInlineOnly); 12705 verifyFormat("int f()\n" 12706 "{\n" 12707 " return 42;\n" 12708 "}", 12709 MergeInlineOnly); 12710 12711 // SFS_InlineOnly does not imply SFS_Empty 12712 verifyFormat("int f()\n" 12713 "{\n" 12714 "}", 12715 MergeInlineOnly); 12716 verifyFormat("class C {\n" 12717 " int f() {}\n" 12718 "};", 12719 MergeInlineOnly); 12720 } 12721 12722 TEST_F(FormatTest, SplitEmptyFunction) { 12723 FormatStyle Style = getLLVMStyleWithColumns(40); 12724 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12725 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12726 Style.BraceWrapping.AfterFunction = true; 12727 Style.BraceWrapping.SplitEmptyFunction = false; 12728 12729 verifyFormat("int f()\n" 12730 "{}", 12731 Style); 12732 verifyFormat("int f()\n" 12733 "{\n" 12734 " return 42;\n" 12735 "}", 12736 Style); 12737 verifyFormat("int f()\n" 12738 "{\n" 12739 " // some comment\n" 12740 "}", 12741 Style); 12742 12743 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 12744 verifyFormat("int f() {}", Style); 12745 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12746 "{}", 12747 Style); 12748 verifyFormat("int f()\n" 12749 "{\n" 12750 " return 0;\n" 12751 "}", 12752 Style); 12753 12754 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 12755 verifyFormat("class Foo {\n" 12756 " int f() {}\n" 12757 "};\n", 12758 Style); 12759 verifyFormat("class Foo {\n" 12760 " int f() { return 0; }\n" 12761 "};\n", 12762 Style); 12763 verifyFormat("class Foo {\n" 12764 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12765 " {}\n" 12766 "};\n", 12767 Style); 12768 verifyFormat("class Foo {\n" 12769 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12770 " {\n" 12771 " return 0;\n" 12772 " }\n" 12773 "};\n", 12774 Style); 12775 12776 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 12777 verifyFormat("int f() {}", Style); 12778 verifyFormat("int f() { return 0; }", Style); 12779 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12780 "{}", 12781 Style); 12782 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12783 "{\n" 12784 " return 0;\n" 12785 "}", 12786 Style); 12787 } 12788 12789 TEST_F(FormatTest, SplitEmptyFunctionButNotRecord) { 12790 FormatStyle Style = getLLVMStyleWithColumns(40); 12791 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12792 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12793 Style.BraceWrapping.AfterFunction = true; 12794 Style.BraceWrapping.SplitEmptyFunction = true; 12795 Style.BraceWrapping.SplitEmptyRecord = false; 12796 12797 verifyFormat("class C {};", Style); 12798 verifyFormat("struct C {};", Style); 12799 verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12800 " int bbbbbbbbbbbbbbbbbbbbbbbb)\n" 12801 "{\n" 12802 "}", 12803 Style); 12804 verifyFormat("class C {\n" 12805 " C()\n" 12806 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa(),\n" 12807 " bbbbbbbbbbbbbbbbbbb()\n" 12808 " {\n" 12809 " }\n" 12810 " void\n" 12811 " m(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12812 " int bbbbbbbbbbbbbbbbbbbbbbbb)\n" 12813 " {\n" 12814 " }\n" 12815 "};", 12816 Style); 12817 } 12818 12819 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) { 12820 FormatStyle Style = getLLVMStyle(); 12821 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 12822 verifyFormat("#ifdef A\n" 12823 "int f() {}\n" 12824 "#else\n" 12825 "int g() {}\n" 12826 "#endif", 12827 Style); 12828 } 12829 12830 TEST_F(FormatTest, SplitEmptyClass) { 12831 FormatStyle Style = getLLVMStyle(); 12832 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12833 Style.BraceWrapping.AfterClass = true; 12834 Style.BraceWrapping.SplitEmptyRecord = false; 12835 12836 verifyFormat("class Foo\n" 12837 "{};", 12838 Style); 12839 verifyFormat("/* something */ class Foo\n" 12840 "{};", 12841 Style); 12842 verifyFormat("template <typename X> class Foo\n" 12843 "{};", 12844 Style); 12845 verifyFormat("class Foo\n" 12846 "{\n" 12847 " Foo();\n" 12848 "};", 12849 Style); 12850 verifyFormat("typedef class Foo\n" 12851 "{\n" 12852 "} Foo_t;", 12853 Style); 12854 12855 Style.BraceWrapping.SplitEmptyRecord = true; 12856 Style.BraceWrapping.AfterStruct = true; 12857 verifyFormat("class rep\n" 12858 "{\n" 12859 "};", 12860 Style); 12861 verifyFormat("struct rep\n" 12862 "{\n" 12863 "};", 12864 Style); 12865 verifyFormat("template <typename T> class rep\n" 12866 "{\n" 12867 "};", 12868 Style); 12869 verifyFormat("template <typename T> struct rep\n" 12870 "{\n" 12871 "};", 12872 Style); 12873 verifyFormat("class rep\n" 12874 "{\n" 12875 " int x;\n" 12876 "};", 12877 Style); 12878 verifyFormat("struct rep\n" 12879 "{\n" 12880 " int x;\n" 12881 "};", 12882 Style); 12883 verifyFormat("template <typename T> class rep\n" 12884 "{\n" 12885 " int x;\n" 12886 "};", 12887 Style); 12888 verifyFormat("template <typename T> struct rep\n" 12889 "{\n" 12890 " int x;\n" 12891 "};", 12892 Style); 12893 verifyFormat("template <typename T> class rep // Foo\n" 12894 "{\n" 12895 " int x;\n" 12896 "};", 12897 Style); 12898 verifyFormat("template <typename T> struct rep // Bar\n" 12899 "{\n" 12900 " int x;\n" 12901 "};", 12902 Style); 12903 12904 verifyFormat("template <typename T> class rep<T>\n" 12905 "{\n" 12906 " int x;\n" 12907 "};", 12908 Style); 12909 12910 verifyFormat("template <typename T> class rep<std::complex<T>>\n" 12911 "{\n" 12912 " int x;\n" 12913 "};", 12914 Style); 12915 verifyFormat("template <typename T> class rep<std::complex<T>>\n" 12916 "{\n" 12917 "};", 12918 Style); 12919 12920 verifyFormat("#include \"stdint.h\"\n" 12921 "namespace rep {}", 12922 Style); 12923 verifyFormat("#include <stdint.h>\n" 12924 "namespace rep {}", 12925 Style); 12926 verifyFormat("#include <stdint.h>\n" 12927 "namespace rep {}", 12928 "#include <stdint.h>\n" 12929 "namespace rep {\n" 12930 "\n" 12931 "\n" 12932 "}", 12933 Style); 12934 } 12935 12936 TEST_F(FormatTest, SplitEmptyStruct) { 12937 FormatStyle Style = getLLVMStyle(); 12938 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12939 Style.BraceWrapping.AfterStruct = true; 12940 Style.BraceWrapping.SplitEmptyRecord = false; 12941 12942 verifyFormat("struct Foo\n" 12943 "{};", 12944 Style); 12945 verifyFormat("/* something */ struct Foo\n" 12946 "{};", 12947 Style); 12948 verifyFormat("template <typename X> struct Foo\n" 12949 "{};", 12950 Style); 12951 verifyFormat("struct Foo\n" 12952 "{\n" 12953 " Foo();\n" 12954 "};", 12955 Style); 12956 verifyFormat("typedef struct Foo\n" 12957 "{\n" 12958 "} Foo_t;", 12959 Style); 12960 // typedef struct Bar {} Bar_t; 12961 } 12962 12963 TEST_F(FormatTest, SplitEmptyUnion) { 12964 FormatStyle Style = getLLVMStyle(); 12965 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12966 Style.BraceWrapping.AfterUnion = true; 12967 Style.BraceWrapping.SplitEmptyRecord = false; 12968 12969 verifyFormat("union Foo\n" 12970 "{};", 12971 Style); 12972 verifyFormat("/* something */ union Foo\n" 12973 "{};", 12974 Style); 12975 verifyFormat("union Foo\n" 12976 "{\n" 12977 " A,\n" 12978 "};", 12979 Style); 12980 verifyFormat("typedef union Foo\n" 12981 "{\n" 12982 "} Foo_t;", 12983 Style); 12984 } 12985 12986 TEST_F(FormatTest, SplitEmptyNamespace) { 12987 FormatStyle Style = getLLVMStyle(); 12988 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12989 Style.BraceWrapping.AfterNamespace = true; 12990 Style.BraceWrapping.SplitEmptyNamespace = false; 12991 12992 verifyFormat("namespace Foo\n" 12993 "{};", 12994 Style); 12995 verifyFormat("/* something */ namespace Foo\n" 12996 "{};", 12997 Style); 12998 verifyFormat("inline namespace Foo\n" 12999 "{};", 13000 Style); 13001 verifyFormat("/* something */ inline namespace Foo\n" 13002 "{};", 13003 Style); 13004 verifyFormat("export namespace Foo\n" 13005 "{};", 13006 Style); 13007 verifyFormat("namespace Foo\n" 13008 "{\n" 13009 "void Bar();\n" 13010 "};", 13011 Style); 13012 } 13013 13014 TEST_F(FormatTest, NeverMergeShortRecords) { 13015 FormatStyle Style = getLLVMStyle(); 13016 13017 verifyFormat("class Foo {\n" 13018 " Foo();\n" 13019 "};", 13020 Style); 13021 verifyFormat("typedef class Foo {\n" 13022 " Foo();\n" 13023 "} Foo_t;", 13024 Style); 13025 verifyFormat("struct Foo {\n" 13026 " Foo();\n" 13027 "};", 13028 Style); 13029 verifyFormat("typedef struct Foo {\n" 13030 " Foo();\n" 13031 "} Foo_t;", 13032 Style); 13033 verifyFormat("union Foo {\n" 13034 " A,\n" 13035 "};", 13036 Style); 13037 verifyFormat("typedef union Foo {\n" 13038 " A,\n" 13039 "} Foo_t;", 13040 Style); 13041 verifyFormat("namespace Foo {\n" 13042 "void Bar();\n" 13043 "};", 13044 Style); 13045 13046 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 13047 Style.BraceWrapping.AfterClass = true; 13048 Style.BraceWrapping.AfterStruct = true; 13049 Style.BraceWrapping.AfterUnion = true; 13050 Style.BraceWrapping.AfterNamespace = true; 13051 verifyFormat("class Foo\n" 13052 "{\n" 13053 " Foo();\n" 13054 "};", 13055 Style); 13056 verifyFormat("typedef class Foo\n" 13057 "{\n" 13058 " Foo();\n" 13059 "} Foo_t;", 13060 Style); 13061 verifyFormat("struct Foo\n" 13062 "{\n" 13063 " Foo();\n" 13064 "};", 13065 Style); 13066 verifyFormat("typedef struct Foo\n" 13067 "{\n" 13068 " Foo();\n" 13069 "} Foo_t;", 13070 Style); 13071 verifyFormat("union Foo\n" 13072 "{\n" 13073 " A,\n" 13074 "};", 13075 Style); 13076 verifyFormat("typedef union Foo\n" 13077 "{\n" 13078 " A,\n" 13079 "} Foo_t;", 13080 Style); 13081 verifyFormat("namespace Foo\n" 13082 "{\n" 13083 "void Bar();\n" 13084 "};", 13085 Style); 13086 } 13087 13088 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) { 13089 // Elaborate type variable declarations. 13090 verifyFormat("struct foo a = {bar};\nint n;"); 13091 verifyFormat("class foo a = {bar};\nint n;"); 13092 verifyFormat("union foo a = {bar};\nint n;"); 13093 13094 // Elaborate types inside function definitions. 13095 verifyFormat("struct foo f() {}\nint n;"); 13096 verifyFormat("class foo f() {}\nint n;"); 13097 verifyFormat("union foo f() {}\nint n;"); 13098 13099 // Templates. 13100 verifyFormat("template <class X> void f() {}\nint n;"); 13101 verifyFormat("template <struct X> void f() {}\nint n;"); 13102 verifyFormat("template <union X> void f() {}\nint n;"); 13103 13104 // Actual definitions... 13105 verifyFormat("struct {\n} n;"); 13106 verifyFormat( 13107 "template <template <class T, class Y>, class Z> class X {\n} n;"); 13108 verifyFormat("union Z {\n int n;\n} x;"); 13109 verifyFormat("class MACRO Z {\n} n;"); 13110 verifyFormat("class MACRO(X) Z {\n} n;"); 13111 verifyFormat("class __attribute__(X) Z {\n} n;"); 13112 verifyFormat("class __declspec(X) Z {\n} n;"); 13113 verifyFormat("class A##B##C {\n} n;"); 13114 verifyFormat("class alignas(16) Z {\n} n;"); 13115 verifyFormat("class MACRO(X) alignas(16) Z {\n} n;"); 13116 verifyFormat("class MACROA MACRO(X) Z {\n} n;"); 13117 13118 // Redefinition from nested context: 13119 verifyFormat("class A::B::C {\n} n;"); 13120 13121 // Template definitions. 13122 verifyFormat( 13123 "template <typename F>\n" 13124 "Matcher(const Matcher<F> &Other,\n" 13125 " typename enable_if_c<is_base_of<F, T>::value &&\n" 13126 " !is_same<F, T>::value>::type * = 0)\n" 13127 " : Implementation(new ImplicitCastMatcher<F>(Other)) {}"); 13128 13129 // FIXME: This is still incorrectly handled at the formatter side. 13130 verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};"); 13131 verifyFormat("int i = SomeFunction(a<b, a> b);"); 13132 13133 // FIXME: 13134 // This now gets parsed incorrectly as class definition. 13135 // verifyFormat("class A<int> f() {\n}\nint n;"); 13136 13137 // Elaborate types where incorrectly parsing the structural element would 13138 // break the indent. 13139 verifyFormat("if (true)\n" 13140 " class X x;\n" 13141 "else\n" 13142 " f();\n"); 13143 13144 // This is simply incomplete. Formatting is not important, but must not crash. 13145 verifyFormat("class A:"); 13146 } 13147 13148 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) { 13149 EXPECT_EQ("#error Leave all white!!!!! space* alone!\n", 13150 format("#error Leave all white!!!!! space* alone!\n")); 13151 EXPECT_EQ( 13152 "#warning Leave all white!!!!! space* alone!\n", 13153 format("#warning Leave all white!!!!! space* alone!\n")); 13154 EXPECT_EQ("#error 1", format(" # error 1")); 13155 EXPECT_EQ("#warning 1", format(" # warning 1")); 13156 } 13157 13158 TEST_F(FormatTest, FormatHashIfExpressions) { 13159 verifyFormat("#if AAAA && BBBB"); 13160 verifyFormat("#if (AAAA && BBBB)"); 13161 verifyFormat("#elif (AAAA && BBBB)"); 13162 // FIXME: Come up with a better indentation for #elif. 13163 verifyFormat( 13164 "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) && \\\n" 13165 " defined(BBBBBBBB)\n" 13166 "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) && \\\n" 13167 " defined(BBBBBBBB)\n" 13168 "#endif", 13169 getLLVMStyleWithColumns(65)); 13170 } 13171 13172 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) { 13173 FormatStyle AllowsMergedIf = getGoogleStyle(); 13174 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 13175 FormatStyle::SIS_WithoutElse; 13176 verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf); 13177 verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf); 13178 verifyFormat("if (true)\n#error E\n return 42;", AllowsMergedIf); 13179 EXPECT_EQ("if (true) return 42;", 13180 format("if (true)\nreturn 42;", AllowsMergedIf)); 13181 FormatStyle ShortMergedIf = AllowsMergedIf; 13182 ShortMergedIf.ColumnLimit = 25; 13183 verifyFormat("#define A \\\n" 13184 " if (true) return 42;", 13185 ShortMergedIf); 13186 verifyFormat("#define A \\\n" 13187 " f(); \\\n" 13188 " if (true)\n" 13189 "#define B", 13190 ShortMergedIf); 13191 verifyFormat("#define A \\\n" 13192 " f(); \\\n" 13193 " if (true)\n" 13194 "g();", 13195 ShortMergedIf); 13196 verifyFormat("{\n" 13197 "#ifdef A\n" 13198 " // Comment\n" 13199 " if (true) continue;\n" 13200 "#endif\n" 13201 " // Comment\n" 13202 " if (true) continue;\n" 13203 "}", 13204 ShortMergedIf); 13205 ShortMergedIf.ColumnLimit = 33; 13206 verifyFormat("#define A \\\n" 13207 " if constexpr (true) return 42;", 13208 ShortMergedIf); 13209 verifyFormat("#define A \\\n" 13210 " if CONSTEXPR (true) return 42;", 13211 ShortMergedIf); 13212 ShortMergedIf.ColumnLimit = 29; 13213 verifyFormat("#define A \\\n" 13214 " if (aaaaaaaaaa) return 1; \\\n" 13215 " return 2;", 13216 ShortMergedIf); 13217 ShortMergedIf.ColumnLimit = 28; 13218 verifyFormat("#define A \\\n" 13219 " if (aaaaaaaaaa) \\\n" 13220 " return 1; \\\n" 13221 " return 2;", 13222 ShortMergedIf); 13223 verifyFormat("#define A \\\n" 13224 " if constexpr (aaaaaaa) \\\n" 13225 " return 1; \\\n" 13226 " return 2;", 13227 ShortMergedIf); 13228 verifyFormat("#define A \\\n" 13229 " if CONSTEXPR (aaaaaaa) \\\n" 13230 " return 1; \\\n" 13231 " return 2;", 13232 ShortMergedIf); 13233 } 13234 13235 TEST_F(FormatTest, FormatStarDependingOnContext) { 13236 verifyFormat("void f(int *a);"); 13237 verifyFormat("void f() { f(fint * b); }"); 13238 verifyFormat("class A {\n void f(int *a);\n};"); 13239 verifyFormat("class A {\n int *a;\n};"); 13240 verifyFormat("namespace a {\n" 13241 "namespace b {\n" 13242 "class A {\n" 13243 " void f() {}\n" 13244 " int *a;\n" 13245 "};\n" 13246 "} // namespace b\n" 13247 "} // namespace a"); 13248 } 13249 13250 TEST_F(FormatTest, SpecialTokensAtEndOfLine) { 13251 verifyFormat("while"); 13252 verifyFormat("operator"); 13253 } 13254 13255 TEST_F(FormatTest, SkipsDeeplyNestedLines) { 13256 // This code would be painfully slow to format if we didn't skip it. 13257 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 13258 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13259 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13260 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13261 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 13262 "A(1, 1)\n" 13263 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x 13264 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13265 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13266 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13267 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13268 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13269 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13270 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13271 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 13272 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n"); 13273 // Deeply nested part is untouched, rest is formatted. 13274 EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n", 13275 format(std::string("int i;\n") + Code + "int j;\n", 13276 getLLVMStyle(), SC_ExpectIncomplete)); 13277 } 13278 13279 //===----------------------------------------------------------------------===// 13280 // Objective-C tests. 13281 //===----------------------------------------------------------------------===// 13282 13283 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) { 13284 verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;"); 13285 EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;", 13286 format("-(NSUInteger)indexOfObject:(id)anObject;")); 13287 EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;")); 13288 EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;")); 13289 EXPECT_EQ("- (NSInteger)Method3:(id)anObject;", 13290 format("-(NSInteger)Method3:(id)anObject;")); 13291 EXPECT_EQ("- (NSInteger)Method4:(id)anObject;", 13292 format("-(NSInteger)Method4:(id)anObject;")); 13293 EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;", 13294 format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;")); 13295 EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;", 13296 format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;")); 13297 EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject " 13298 "forAllCells:(BOOL)flag;", 13299 format("- (void)sendAction:(SEL)aSelector to:(id)anObject " 13300 "forAllCells:(BOOL)flag;")); 13301 13302 // Very long objectiveC method declaration. 13303 verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n" 13304 " (SoooooooooooooooooooooomeType *)bbbbbbbbbb;"); 13305 verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n" 13306 " inRange:(NSRange)range\n" 13307 " outRange:(NSRange)out_range\n" 13308 " outRange1:(NSRange)out_range1\n" 13309 " outRange2:(NSRange)out_range2\n" 13310 " outRange3:(NSRange)out_range3\n" 13311 " outRange4:(NSRange)out_range4\n" 13312 " outRange5:(NSRange)out_range5\n" 13313 " outRange6:(NSRange)out_range6\n" 13314 " outRange7:(NSRange)out_range7\n" 13315 " outRange8:(NSRange)out_range8\n" 13316 " outRange9:(NSRange)out_range9;"); 13317 13318 // When the function name has to be wrapped. 13319 FormatStyle Style = getLLVMStyle(); 13320 // ObjC ignores IndentWrappedFunctionNames when wrapping methods 13321 // and always indents instead. 13322 Style.IndentWrappedFunctionNames = false; 13323 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n" 13324 " veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n" 13325 " anotherName:(NSString)bbbbbbbbbbbbbb {\n" 13326 "}", 13327 Style); 13328 Style.IndentWrappedFunctionNames = true; 13329 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n" 13330 " veryLooooooooooongName:(NSString)cccccccccccccc\n" 13331 " anotherName:(NSString)dddddddddddddd {\n" 13332 "}", 13333 Style); 13334 13335 verifyFormat("- (int)sum:(vector<int>)numbers;"); 13336 verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;"); 13337 // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC 13338 // protocol lists (but not for template classes): 13339 // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;"); 13340 13341 verifyFormat("- (int (*)())foo:(int (*)())f;"); 13342 verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;"); 13343 13344 // If there's no return type (very rare in practice!), LLVM and Google style 13345 // agree. 13346 verifyFormat("- foo;"); 13347 verifyFormat("- foo:(int)f;"); 13348 verifyGoogleFormat("- foo:(int)foo;"); 13349 } 13350 13351 TEST_F(FormatTest, BreaksStringLiterals) { 13352 EXPECT_EQ("\"some text \"\n" 13353 "\"other\";", 13354 format("\"some text other\";", getLLVMStyleWithColumns(12))); 13355 EXPECT_EQ("\"some text \"\n" 13356 "\"other\";", 13357 format("\\\n\"some text other\";", getLLVMStyleWithColumns(12))); 13358 EXPECT_EQ( 13359 "#define A \\\n" 13360 " \"some \" \\\n" 13361 " \"text \" \\\n" 13362 " \"other\";", 13363 format("#define A \"some text other\";", getLLVMStyleWithColumns(12))); 13364 EXPECT_EQ( 13365 "#define A \\\n" 13366 " \"so \" \\\n" 13367 " \"text \" \\\n" 13368 " \"other\";", 13369 format("#define A \"so text other\";", getLLVMStyleWithColumns(12))); 13370 13371 EXPECT_EQ("\"some text\"", 13372 format("\"some text\"", getLLVMStyleWithColumns(1))); 13373 EXPECT_EQ("\"some text\"", 13374 format("\"some text\"", getLLVMStyleWithColumns(11))); 13375 EXPECT_EQ("\"some \"\n" 13376 "\"text\"", 13377 format("\"some text\"", getLLVMStyleWithColumns(10))); 13378 EXPECT_EQ("\"some \"\n" 13379 "\"text\"", 13380 format("\"some text\"", getLLVMStyleWithColumns(7))); 13381 EXPECT_EQ("\"some\"\n" 13382 "\" tex\"\n" 13383 "\"t\"", 13384 format("\"some text\"", getLLVMStyleWithColumns(6))); 13385 EXPECT_EQ("\"some\"\n" 13386 "\" tex\"\n" 13387 "\" and\"", 13388 format("\"some tex and\"", getLLVMStyleWithColumns(6))); 13389 EXPECT_EQ("\"some\"\n" 13390 "\"/tex\"\n" 13391 "\"/and\"", 13392 format("\"some/tex/and\"", getLLVMStyleWithColumns(6))); 13393 13394 EXPECT_EQ("variable =\n" 13395 " \"long string \"\n" 13396 " \"literal\";", 13397 format("variable = \"long string literal\";", 13398 getLLVMStyleWithColumns(20))); 13399 13400 EXPECT_EQ("variable = f(\n" 13401 " \"long string \"\n" 13402 " \"literal\",\n" 13403 " short,\n" 13404 " loooooooooooooooooooong);", 13405 format("variable = f(\"long string literal\", short, " 13406 "loooooooooooooooooooong);", 13407 getLLVMStyleWithColumns(20))); 13408 13409 EXPECT_EQ( 13410 "f(g(\"long string \"\n" 13411 " \"literal\"),\n" 13412 " b);", 13413 format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20))); 13414 EXPECT_EQ("f(g(\"long string \"\n" 13415 " \"literal\",\n" 13416 " a),\n" 13417 " b);", 13418 format("f(g(\"long string literal\", a), b);", 13419 getLLVMStyleWithColumns(20))); 13420 EXPECT_EQ( 13421 "f(\"one two\".split(\n" 13422 " variable));", 13423 format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20))); 13424 EXPECT_EQ("f(\"one two three four five six \"\n" 13425 " \"seven\".split(\n" 13426 " really_looooong_variable));", 13427 format("f(\"one two three four five six seven\"." 13428 "split(really_looooong_variable));", 13429 getLLVMStyleWithColumns(33))); 13430 13431 EXPECT_EQ("f(\"some \"\n" 13432 " \"text\",\n" 13433 " other);", 13434 format("f(\"some text\", other);", getLLVMStyleWithColumns(10))); 13435 13436 // Only break as a last resort. 13437 verifyFormat( 13438 "aaaaaaaaaaaaaaaaaaaa(\n" 13439 " aaaaaaaaaaaaaaaaaaaa,\n" 13440 " aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));"); 13441 13442 EXPECT_EQ("\"splitmea\"\n" 13443 "\"trandomp\"\n" 13444 "\"oint\"", 13445 format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10))); 13446 13447 EXPECT_EQ("\"split/\"\n" 13448 "\"pathat/\"\n" 13449 "\"slashes\"", 13450 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10))); 13451 13452 EXPECT_EQ("\"split/\"\n" 13453 "\"pathat/\"\n" 13454 "\"slashes\"", 13455 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10))); 13456 EXPECT_EQ("\"split at \"\n" 13457 "\"spaces/at/\"\n" 13458 "\"slashes.at.any$\"\n" 13459 "\"non-alphanumeric%\"\n" 13460 "\"1111111111characte\"\n" 13461 "\"rs\"", 13462 format("\"split at " 13463 "spaces/at/" 13464 "slashes.at." 13465 "any$non-" 13466 "alphanumeric%" 13467 "1111111111characte" 13468 "rs\"", 13469 getLLVMStyleWithColumns(20))); 13470 13471 // Verify that splitting the strings understands 13472 // Style::AlwaysBreakBeforeMultilineStrings. 13473 EXPECT_EQ("aaaaaaaaaaaa(\n" 13474 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n" 13475 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");", 13476 format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa " 13477 "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa " 13478 "aaaaaaaaaaaaaaaaaaaaaa\");", 13479 getGoogleStyle())); 13480 EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13481 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";", 13482 format("return \"aaaaaaaaaaaaaaaaaaaaaa " 13483 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa " 13484 "aaaaaaaaaaaaaaaaaaaaaa\";", 13485 getGoogleStyle())); 13486 EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13487 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";", 13488 format("llvm::outs() << " 13489 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa" 13490 "aaaaaaaaaaaaaaaaaaa\";")); 13491 EXPECT_EQ("ffff(\n" 13492 " {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 13493 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});", 13494 format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa " 13495 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});", 13496 getGoogleStyle())); 13497 13498 FormatStyle Style = getLLVMStyleWithColumns(12); 13499 Style.BreakStringLiterals = false; 13500 EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style)); 13501 13502 FormatStyle AlignLeft = getLLVMStyleWithColumns(12); 13503 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left; 13504 EXPECT_EQ("#define A \\\n" 13505 " \"some \" \\\n" 13506 " \"text \" \\\n" 13507 " \"other\";", 13508 format("#define A \"some text other\";", AlignLeft)); 13509 } 13510 13511 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) { 13512 EXPECT_EQ("C a = \"some more \"\n" 13513 " \"text\";", 13514 format("C a = \"some more text\";", getLLVMStyleWithColumns(18))); 13515 } 13516 13517 TEST_F(FormatTest, FullyRemoveEmptyLines) { 13518 FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80); 13519 NoEmptyLines.MaxEmptyLinesToKeep = 0; 13520 EXPECT_EQ("int i = a(b());", 13521 format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines)); 13522 } 13523 13524 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) { 13525 EXPECT_EQ( 13526 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 13527 "(\n" 13528 " \"x\t\");", 13529 format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 13530 "aaaaaaa(" 13531 "\"x\t\");")); 13532 } 13533 13534 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) { 13535 EXPECT_EQ( 13536 "u8\"utf8 string \"\n" 13537 "u8\"literal\";", 13538 format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16))); 13539 EXPECT_EQ( 13540 "u\"utf16 string \"\n" 13541 "u\"literal\";", 13542 format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16))); 13543 EXPECT_EQ( 13544 "U\"utf32 string \"\n" 13545 "U\"literal\";", 13546 format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16))); 13547 EXPECT_EQ("L\"wide string \"\n" 13548 "L\"literal\";", 13549 format("L\"wide string literal\";", getGoogleStyleWithColumns(16))); 13550 EXPECT_EQ("@\"NSString \"\n" 13551 "@\"literal\";", 13552 format("@\"NSString literal\";", getGoogleStyleWithColumns(19))); 13553 verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26)); 13554 13555 // This input makes clang-format try to split the incomplete unicode escape 13556 // sequence, which used to lead to a crasher. 13557 verifyNoCrash( 13558 "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 13559 getLLVMStyleWithColumns(60)); 13560 } 13561 13562 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) { 13563 FormatStyle Style = getGoogleStyleWithColumns(15); 13564 EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style)); 13565 EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style)); 13566 EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style)); 13567 EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style)); 13568 EXPECT_EQ("u8R\"x(raw literal)x\";", 13569 format("u8R\"x(raw literal)x\";", Style)); 13570 } 13571 13572 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) { 13573 FormatStyle Style = getLLVMStyleWithColumns(20); 13574 EXPECT_EQ( 13575 "_T(\"aaaaaaaaaaaaaa\")\n" 13576 "_T(\"aaaaaaaaaaaaaa\")\n" 13577 "_T(\"aaaaaaaaaaaa\")", 13578 format(" _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style)); 13579 EXPECT_EQ("f(x,\n" 13580 " _T(\"aaaaaaaaaaaa\")\n" 13581 " _T(\"aaa\"),\n" 13582 " z);", 13583 format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style)); 13584 13585 // FIXME: Handle embedded spaces in one iteration. 13586 // EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n" 13587 // "_T(\"aaaaaaaaaaaaa\")\n" 13588 // "_T(\"aaaaaaaaaaaaa\")\n" 13589 // "_T(\"a\")", 13590 // format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", 13591 // getLLVMStyleWithColumns(20))); 13592 EXPECT_EQ( 13593 "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", 13594 format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style)); 13595 EXPECT_EQ("f(\n" 13596 "#if !TEST\n" 13597 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n" 13598 "#endif\n" 13599 ");", 13600 format("f(\n" 13601 "#if !TEST\n" 13602 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n" 13603 "#endif\n" 13604 ");")); 13605 EXPECT_EQ("f(\n" 13606 "\n" 13607 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));", 13608 format("f(\n" 13609 "\n" 13610 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));")); 13611 // Regression test for accessing tokens past the end of a vector in the 13612 // TokenLexer. 13613 verifyNoCrash(R"(_T( 13614 " 13615 ) 13616 )"); 13617 } 13618 13619 TEST_F(FormatTest, BreaksStringLiteralOperands) { 13620 // In a function call with two operands, the second can be broken with no line 13621 // break before it. 13622 EXPECT_EQ( 13623 "func(a, \"long long \"\n" 13624 " \"long long\");", 13625 format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24))); 13626 // In a function call with three operands, the second must be broken with a 13627 // line break before it. 13628 EXPECT_EQ("func(a,\n" 13629 " \"long long long \"\n" 13630 " \"long\",\n" 13631 " c);", 13632 format("func(a, \"long long long long\", c);", 13633 getLLVMStyleWithColumns(24))); 13634 // In a function call with three operands, the third must be broken with a 13635 // line break before it. 13636 EXPECT_EQ("func(a, b,\n" 13637 " \"long long long \"\n" 13638 " \"long\");", 13639 format("func(a, b, \"long long long long\");", 13640 getLLVMStyleWithColumns(24))); 13641 // In a function call with three operands, both the second and the third must 13642 // be broken with a line break before them. 13643 EXPECT_EQ("func(a,\n" 13644 " \"long long long \"\n" 13645 " \"long\",\n" 13646 " \"long long long \"\n" 13647 " \"long\");", 13648 format("func(a, \"long long long long\", \"long long long long\");", 13649 getLLVMStyleWithColumns(24))); 13650 // In a chain of << with two operands, the second can be broken with no line 13651 // break before it. 13652 EXPECT_EQ("a << \"line line \"\n" 13653 " \"line\";", 13654 format("a << \"line line line\";", getLLVMStyleWithColumns(20))); 13655 // In a chain of << with three operands, the second can be broken with no line 13656 // break before it. 13657 EXPECT_EQ( 13658 "abcde << \"line \"\n" 13659 " \"line line\"\n" 13660 " << c;", 13661 format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20))); 13662 // In a chain of << with three operands, the third must be broken with a line 13663 // break before it. 13664 EXPECT_EQ( 13665 "a << b\n" 13666 " << \"line line \"\n" 13667 " \"line\";", 13668 format("a << b << \"line line line\";", getLLVMStyleWithColumns(20))); 13669 // In a chain of << with three operands, the second can be broken with no line 13670 // break before it and the third must be broken with a line break before it. 13671 EXPECT_EQ("abcd << \"line line \"\n" 13672 " \"line\"\n" 13673 " << \"line line \"\n" 13674 " \"line\";", 13675 format("abcd << \"line line line\" << \"line line line\";", 13676 getLLVMStyleWithColumns(20))); 13677 // In a chain of binary operators with two operands, the second can be broken 13678 // with no line break before it. 13679 EXPECT_EQ( 13680 "abcd + \"line line \"\n" 13681 " \"line line\";", 13682 format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20))); 13683 // In a chain of binary operators with three operands, the second must be 13684 // broken with a line break before it. 13685 EXPECT_EQ("abcd +\n" 13686 " \"line line \"\n" 13687 " \"line line\" +\n" 13688 " e;", 13689 format("abcd + \"line line line line\" + e;", 13690 getLLVMStyleWithColumns(20))); 13691 // In a function call with two operands, with AlignAfterOpenBracket enabled, 13692 // the first must be broken with a line break before it. 13693 FormatStyle Style = getLLVMStyleWithColumns(25); 13694 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 13695 EXPECT_EQ("someFunction(\n" 13696 " \"long long long \"\n" 13697 " \"long\",\n" 13698 " a);", 13699 format("someFunction(\"long long long long\", a);", Style)); 13700 } 13701 13702 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) { 13703 EXPECT_EQ( 13704 "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13705 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13706 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";", 13707 format("aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13708 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13709 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";")); 13710 } 13711 13712 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) { 13713 EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);", 13714 format("f(g(R\"x(raw literal)x\", a), b);", getGoogleStyle())); 13715 EXPECT_EQ("fffffffffff(g(R\"x(\n" 13716 "multiline raw string literal xxxxxxxxxxxxxx\n" 13717 ")x\",\n" 13718 " a),\n" 13719 " b);", 13720 format("fffffffffff(g(R\"x(\n" 13721 "multiline raw string literal xxxxxxxxxxxxxx\n" 13722 ")x\", a), b);", 13723 getGoogleStyleWithColumns(20))); 13724 EXPECT_EQ("fffffffffff(\n" 13725 " g(R\"x(qqq\n" 13726 "multiline raw string literal xxxxxxxxxxxxxx\n" 13727 ")x\",\n" 13728 " a),\n" 13729 " b);", 13730 format("fffffffffff(g(R\"x(qqq\n" 13731 "multiline raw string literal xxxxxxxxxxxxxx\n" 13732 ")x\", a), b);", 13733 getGoogleStyleWithColumns(20))); 13734 13735 EXPECT_EQ("fffffffffff(R\"x(\n" 13736 "multiline raw string literal xxxxxxxxxxxxxx\n" 13737 ")x\");", 13738 format("fffffffffff(R\"x(\n" 13739 "multiline raw string literal xxxxxxxxxxxxxx\n" 13740 ")x\");", 13741 getGoogleStyleWithColumns(20))); 13742 EXPECT_EQ("fffffffffff(R\"x(\n" 13743 "multiline raw string literal xxxxxxxxxxxxxx\n" 13744 ")x\" + bbbbbb);", 13745 format("fffffffffff(R\"x(\n" 13746 "multiline raw string literal xxxxxxxxxxxxxx\n" 13747 ")x\" + bbbbbb);", 13748 getGoogleStyleWithColumns(20))); 13749 EXPECT_EQ("fffffffffff(\n" 13750 " R\"x(\n" 13751 "multiline raw string literal xxxxxxxxxxxxxx\n" 13752 ")x\" +\n" 13753 " bbbbbb);", 13754 format("fffffffffff(\n" 13755 " R\"x(\n" 13756 "multiline raw string literal xxxxxxxxxxxxxx\n" 13757 ")x\" + bbbbbb);", 13758 getGoogleStyleWithColumns(20))); 13759 EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);", 13760 format("fffffffffff(\n" 13761 " R\"(single line raw string)\" + bbbbbb);")); 13762 } 13763 13764 TEST_F(FormatTest, SkipsUnknownStringLiterals) { 13765 verifyFormat("string a = \"unterminated;"); 13766 EXPECT_EQ("function(\"unterminated,\n" 13767 " OtherParameter);", 13768 format("function( \"unterminated,\n" 13769 " OtherParameter);")); 13770 } 13771 13772 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) { 13773 FormatStyle Style = getLLVMStyle(); 13774 Style.Standard = FormatStyle::LS_Cpp03; 13775 EXPECT_EQ("#define x(_a) printf(\"foo\" _a);", 13776 format("#define x(_a) printf(\"foo\"_a);", Style)); 13777 } 13778 13779 TEST_F(FormatTest, CppLexVersion) { 13780 FormatStyle Style = getLLVMStyle(); 13781 // Formatting of x * y differs if x is a type. 13782 verifyFormat("void foo() { MACRO(a * b); }", Style); 13783 verifyFormat("void foo() { MACRO(int *b); }", Style); 13784 13785 // LLVM style uses latest lexer. 13786 verifyFormat("void foo() { MACRO(char8_t *b); }", Style); 13787 Style.Standard = FormatStyle::LS_Cpp17; 13788 // But in c++17, char8_t isn't a keyword. 13789 verifyFormat("void foo() { MACRO(char8_t * b); }", Style); 13790 } 13791 13792 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); } 13793 13794 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) { 13795 EXPECT_EQ("someFunction(\"aaabbbcccd\"\n" 13796 " \"ddeeefff\");", 13797 format("someFunction(\"aaabbbcccdddeeefff\");", 13798 getLLVMStyleWithColumns(25))); 13799 EXPECT_EQ("someFunction1234567890(\n" 13800 " \"aaabbbcccdddeeefff\");", 13801 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 13802 getLLVMStyleWithColumns(26))); 13803 EXPECT_EQ("someFunction1234567890(\n" 13804 " \"aaabbbcccdddeeeff\"\n" 13805 " \"f\");", 13806 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 13807 getLLVMStyleWithColumns(25))); 13808 EXPECT_EQ("someFunction1234567890(\n" 13809 " \"aaabbbcccdddeeeff\"\n" 13810 " \"f\");", 13811 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 13812 getLLVMStyleWithColumns(24))); 13813 EXPECT_EQ("someFunction(\n" 13814 " \"aaabbbcc ddde \"\n" 13815 " \"efff\");", 13816 format("someFunction(\"aaabbbcc ddde efff\");", 13817 getLLVMStyleWithColumns(25))); 13818 EXPECT_EQ("someFunction(\"aaabbbccc \"\n" 13819 " \"ddeeefff\");", 13820 format("someFunction(\"aaabbbccc ddeeefff\");", 13821 getLLVMStyleWithColumns(25))); 13822 EXPECT_EQ("someFunction1234567890(\n" 13823 " \"aaabb \"\n" 13824 " \"cccdddeeefff\");", 13825 format("someFunction1234567890(\"aaabb cccdddeeefff\");", 13826 getLLVMStyleWithColumns(25))); 13827 EXPECT_EQ("#define A \\\n" 13828 " string s = \\\n" 13829 " \"123456789\" \\\n" 13830 " \"0\"; \\\n" 13831 " int i;", 13832 format("#define A string s = \"1234567890\"; int i;", 13833 getLLVMStyleWithColumns(20))); 13834 EXPECT_EQ("someFunction(\n" 13835 " \"aaabbbcc \"\n" 13836 " \"dddeeefff\");", 13837 format("someFunction(\"aaabbbcc dddeeefff\");", 13838 getLLVMStyleWithColumns(25))); 13839 } 13840 13841 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) { 13842 EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3))); 13843 EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2))); 13844 EXPECT_EQ("\"test\"\n" 13845 "\"\\n\"", 13846 format("\"test\\n\"", getLLVMStyleWithColumns(7))); 13847 EXPECT_EQ("\"tes\\\\\"\n" 13848 "\"n\"", 13849 format("\"tes\\\\n\"", getLLVMStyleWithColumns(7))); 13850 EXPECT_EQ("\"\\\\\\\\\"\n" 13851 "\"\\n\"", 13852 format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7))); 13853 EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7))); 13854 EXPECT_EQ("\"\\uff01\"\n" 13855 "\"test\"", 13856 format("\"\\uff01test\"", getLLVMStyleWithColumns(8))); 13857 EXPECT_EQ("\"\\Uff01ff02\"", 13858 format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11))); 13859 EXPECT_EQ("\"\\x000000000001\"\n" 13860 "\"next\"", 13861 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16))); 13862 EXPECT_EQ("\"\\x000000000001next\"", 13863 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15))); 13864 EXPECT_EQ("\"\\x000000000001\"", 13865 format("\"\\x000000000001\"", getLLVMStyleWithColumns(7))); 13866 EXPECT_EQ("\"test\"\n" 13867 "\"\\000000\"\n" 13868 "\"000001\"", 13869 format("\"test\\000000000001\"", getLLVMStyleWithColumns(9))); 13870 EXPECT_EQ("\"test\\000\"\n" 13871 "\"00000000\"\n" 13872 "\"1\"", 13873 format("\"test\\000000000001\"", getLLVMStyleWithColumns(10))); 13874 } 13875 13876 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) { 13877 verifyFormat("void f() {\n" 13878 " return g() {}\n" 13879 " void h() {}"); 13880 verifyFormat("int a[] = {void forgot_closing_brace(){f();\n" 13881 "g();\n" 13882 "}"); 13883 } 13884 13885 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) { 13886 verifyFormat( 13887 "void f() { return C{param1, param2}.SomeCall(param1, param2); }"); 13888 } 13889 13890 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) { 13891 verifyFormat("class X {\n" 13892 " void f() {\n" 13893 " }\n" 13894 "};", 13895 getLLVMStyleWithColumns(12)); 13896 } 13897 13898 TEST_F(FormatTest, ConfigurableIndentWidth) { 13899 FormatStyle EightIndent = getLLVMStyleWithColumns(18); 13900 EightIndent.IndentWidth = 8; 13901 EightIndent.ContinuationIndentWidth = 8; 13902 verifyFormat("void f() {\n" 13903 " someFunction();\n" 13904 " if (true) {\n" 13905 " f();\n" 13906 " }\n" 13907 "}", 13908 EightIndent); 13909 verifyFormat("class X {\n" 13910 " void f() {\n" 13911 " }\n" 13912 "};", 13913 EightIndent); 13914 verifyFormat("int x[] = {\n" 13915 " call(),\n" 13916 " call()};", 13917 EightIndent); 13918 } 13919 13920 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) { 13921 verifyFormat("double\n" 13922 "f();", 13923 getLLVMStyleWithColumns(8)); 13924 } 13925 13926 TEST_F(FormatTest, ConfigurableUseOfTab) { 13927 FormatStyle Tab = getLLVMStyleWithColumns(42); 13928 Tab.IndentWidth = 8; 13929 Tab.UseTab = FormatStyle::UT_Always; 13930 Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left; 13931 13932 EXPECT_EQ("if (aaaaaaaa && // q\n" 13933 " bb)\t\t// w\n" 13934 "\t;", 13935 format("if (aaaaaaaa &&// q\n" 13936 "bb)// w\n" 13937 ";", 13938 Tab)); 13939 EXPECT_EQ("if (aaa && bbb) // w\n" 13940 "\t;", 13941 format("if(aaa&&bbb)// w\n" 13942 ";", 13943 Tab)); 13944 13945 verifyFormat("class X {\n" 13946 "\tvoid f() {\n" 13947 "\t\tsomeFunction(parameter1,\n" 13948 "\t\t\t parameter2);\n" 13949 "\t}\n" 13950 "};", 13951 Tab); 13952 verifyFormat("#define A \\\n" 13953 "\tvoid f() { \\\n" 13954 "\t\tsomeFunction( \\\n" 13955 "\t\t parameter1, \\\n" 13956 "\t\t parameter2); \\\n" 13957 "\t}", 13958 Tab); 13959 verifyFormat("int a;\t // x\n" 13960 "int bbbbbbbb; // x\n", 13961 Tab); 13962 13963 Tab.TabWidth = 4; 13964 Tab.IndentWidth = 8; 13965 verifyFormat("class TabWidth4Indent8 {\n" 13966 "\t\tvoid f() {\n" 13967 "\t\t\t\tsomeFunction(parameter1,\n" 13968 "\t\t\t\t\t\t\t parameter2);\n" 13969 "\t\t}\n" 13970 "};", 13971 Tab); 13972 13973 Tab.TabWidth = 4; 13974 Tab.IndentWidth = 4; 13975 verifyFormat("class TabWidth4Indent4 {\n" 13976 "\tvoid f() {\n" 13977 "\t\tsomeFunction(parameter1,\n" 13978 "\t\t\t\t\t parameter2);\n" 13979 "\t}\n" 13980 "};", 13981 Tab); 13982 13983 Tab.TabWidth = 8; 13984 Tab.IndentWidth = 4; 13985 verifyFormat("class TabWidth8Indent4 {\n" 13986 " void f() {\n" 13987 "\tsomeFunction(parameter1,\n" 13988 "\t\t parameter2);\n" 13989 " }\n" 13990 "};", 13991 Tab); 13992 13993 Tab.TabWidth = 8; 13994 Tab.IndentWidth = 8; 13995 EXPECT_EQ("/*\n" 13996 "\t a\t\tcomment\n" 13997 "\t in multiple lines\n" 13998 " */", 13999 format(" /*\t \t \n" 14000 " \t \t a\t\tcomment\t \t\n" 14001 " \t \t in multiple lines\t\n" 14002 " \t */", 14003 Tab)); 14004 14005 Tab.UseTab = FormatStyle::UT_ForIndentation; 14006 verifyFormat("{\n" 14007 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14008 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14009 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14010 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14011 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14012 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14013 "};", 14014 Tab); 14015 verifyFormat("enum AA {\n" 14016 "\ta1, // Force multiple lines\n" 14017 "\ta2,\n" 14018 "\ta3\n" 14019 "};", 14020 Tab); 14021 EXPECT_EQ("if (aaaaaaaa && // q\n" 14022 " bb) // w\n" 14023 "\t;", 14024 format("if (aaaaaaaa &&// q\n" 14025 "bb)// w\n" 14026 ";", 14027 Tab)); 14028 verifyFormat("class X {\n" 14029 "\tvoid f() {\n" 14030 "\t\tsomeFunction(parameter1,\n" 14031 "\t\t parameter2);\n" 14032 "\t}\n" 14033 "};", 14034 Tab); 14035 verifyFormat("{\n" 14036 "\tQ(\n" 14037 "\t {\n" 14038 "\t\t int a;\n" 14039 "\t\t someFunction(aaaaaaaa,\n" 14040 "\t\t bbbbbbb);\n" 14041 "\t },\n" 14042 "\t p);\n" 14043 "}", 14044 Tab); 14045 EXPECT_EQ("{\n" 14046 "\t/* aaaa\n" 14047 "\t bbbb */\n" 14048 "}", 14049 format("{\n" 14050 "/* aaaa\n" 14051 " bbbb */\n" 14052 "}", 14053 Tab)); 14054 EXPECT_EQ("{\n" 14055 "\t/*\n" 14056 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14057 "\t bbbbbbbbbbbbb\n" 14058 "\t*/\n" 14059 "}", 14060 format("{\n" 14061 "/*\n" 14062 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14063 "*/\n" 14064 "}", 14065 Tab)); 14066 EXPECT_EQ("{\n" 14067 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14068 "\t// bbbbbbbbbbbbb\n" 14069 "}", 14070 format("{\n" 14071 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14072 "}", 14073 Tab)); 14074 EXPECT_EQ("{\n" 14075 "\t/*\n" 14076 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14077 "\t bbbbbbbbbbbbb\n" 14078 "\t*/\n" 14079 "}", 14080 format("{\n" 14081 "\t/*\n" 14082 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14083 "\t*/\n" 14084 "}", 14085 Tab)); 14086 EXPECT_EQ("{\n" 14087 "\t/*\n" 14088 "\n" 14089 "\t*/\n" 14090 "}", 14091 format("{\n" 14092 "\t/*\n" 14093 "\n" 14094 "\t*/\n" 14095 "}", 14096 Tab)); 14097 EXPECT_EQ("{\n" 14098 "\t/*\n" 14099 " asdf\n" 14100 "\t*/\n" 14101 "}", 14102 format("{\n" 14103 "\t/*\n" 14104 " asdf\n" 14105 "\t*/\n" 14106 "}", 14107 Tab)); 14108 14109 verifyFormat("void f() {\n" 14110 "\treturn true ? aaaaaaaaaaaaaaaaaa\n" 14111 "\t : bbbbbbbbbbbbbbbbbb\n" 14112 "}", 14113 Tab); 14114 FormatStyle TabNoBreak = Tab; 14115 TabNoBreak.BreakBeforeTernaryOperators = false; 14116 verifyFormat("void f() {\n" 14117 "\treturn true ? aaaaaaaaaaaaaaaaaa :\n" 14118 "\t bbbbbbbbbbbbbbbbbb\n" 14119 "}", 14120 TabNoBreak); 14121 verifyFormat("void f() {\n" 14122 "\treturn true ?\n" 14123 "\t aaaaaaaaaaaaaaaaaaaa :\n" 14124 "\t bbbbbbbbbbbbbbbbbbbb\n" 14125 "}", 14126 TabNoBreak); 14127 14128 Tab.UseTab = FormatStyle::UT_Never; 14129 EXPECT_EQ("/*\n" 14130 " a\t\tcomment\n" 14131 " in multiple lines\n" 14132 " */", 14133 format(" /*\t \t \n" 14134 " \t \t a\t\tcomment\t \t\n" 14135 " \t \t in multiple lines\t\n" 14136 " \t */", 14137 Tab)); 14138 EXPECT_EQ("/* some\n" 14139 " comment */", 14140 format(" \t \t /* some\n" 14141 " \t \t comment */", 14142 Tab)); 14143 EXPECT_EQ("int a; /* some\n" 14144 " comment */", 14145 format(" \t \t int a; /* some\n" 14146 " \t \t comment */", 14147 Tab)); 14148 14149 EXPECT_EQ("int a; /* some\n" 14150 "comment */", 14151 format(" \t \t int\ta; /* some\n" 14152 " \t \t comment */", 14153 Tab)); 14154 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14155 " comment */", 14156 format(" \t \t f(\"\t\t\"); /* some\n" 14157 " \t \t comment */", 14158 Tab)); 14159 EXPECT_EQ("{\n" 14160 " /*\n" 14161 " * Comment\n" 14162 " */\n" 14163 " int i;\n" 14164 "}", 14165 format("{\n" 14166 "\t/*\n" 14167 "\t * Comment\n" 14168 "\t */\n" 14169 "\t int i;\n" 14170 "}", 14171 Tab)); 14172 14173 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation; 14174 Tab.TabWidth = 8; 14175 Tab.IndentWidth = 8; 14176 EXPECT_EQ("if (aaaaaaaa && // q\n" 14177 " bb) // w\n" 14178 "\t;", 14179 format("if (aaaaaaaa &&// q\n" 14180 "bb)// w\n" 14181 ";", 14182 Tab)); 14183 EXPECT_EQ("if (aaa && bbb) // w\n" 14184 "\t;", 14185 format("if(aaa&&bbb)// w\n" 14186 ";", 14187 Tab)); 14188 verifyFormat("class X {\n" 14189 "\tvoid f() {\n" 14190 "\t\tsomeFunction(parameter1,\n" 14191 "\t\t\t parameter2);\n" 14192 "\t}\n" 14193 "};", 14194 Tab); 14195 verifyFormat("#define A \\\n" 14196 "\tvoid f() { \\\n" 14197 "\t\tsomeFunction( \\\n" 14198 "\t\t parameter1, \\\n" 14199 "\t\t parameter2); \\\n" 14200 "\t}", 14201 Tab); 14202 Tab.TabWidth = 4; 14203 Tab.IndentWidth = 8; 14204 verifyFormat("class TabWidth4Indent8 {\n" 14205 "\t\tvoid f() {\n" 14206 "\t\t\t\tsomeFunction(parameter1,\n" 14207 "\t\t\t\t\t\t\t parameter2);\n" 14208 "\t\t}\n" 14209 "};", 14210 Tab); 14211 Tab.TabWidth = 4; 14212 Tab.IndentWidth = 4; 14213 verifyFormat("class TabWidth4Indent4 {\n" 14214 "\tvoid f() {\n" 14215 "\t\tsomeFunction(parameter1,\n" 14216 "\t\t\t\t\t parameter2);\n" 14217 "\t}\n" 14218 "};", 14219 Tab); 14220 Tab.TabWidth = 8; 14221 Tab.IndentWidth = 4; 14222 verifyFormat("class TabWidth8Indent4 {\n" 14223 " void f() {\n" 14224 "\tsomeFunction(parameter1,\n" 14225 "\t\t parameter2);\n" 14226 " }\n" 14227 "};", 14228 Tab); 14229 Tab.TabWidth = 8; 14230 Tab.IndentWidth = 8; 14231 EXPECT_EQ("/*\n" 14232 "\t a\t\tcomment\n" 14233 "\t in multiple lines\n" 14234 " */", 14235 format(" /*\t \t \n" 14236 " \t \t a\t\tcomment\t \t\n" 14237 " \t \t in multiple lines\t\n" 14238 " \t */", 14239 Tab)); 14240 verifyFormat("{\n" 14241 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14242 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14243 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14244 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14245 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14246 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14247 "};", 14248 Tab); 14249 verifyFormat("enum AA {\n" 14250 "\ta1, // Force multiple lines\n" 14251 "\ta2,\n" 14252 "\ta3\n" 14253 "};", 14254 Tab); 14255 EXPECT_EQ("if (aaaaaaaa && // q\n" 14256 " bb) // w\n" 14257 "\t;", 14258 format("if (aaaaaaaa &&// q\n" 14259 "bb)// w\n" 14260 ";", 14261 Tab)); 14262 verifyFormat("class X {\n" 14263 "\tvoid f() {\n" 14264 "\t\tsomeFunction(parameter1,\n" 14265 "\t\t\t parameter2);\n" 14266 "\t}\n" 14267 "};", 14268 Tab); 14269 verifyFormat("{\n" 14270 "\tQ(\n" 14271 "\t {\n" 14272 "\t\t int a;\n" 14273 "\t\t someFunction(aaaaaaaa,\n" 14274 "\t\t\t\t bbbbbbb);\n" 14275 "\t },\n" 14276 "\t p);\n" 14277 "}", 14278 Tab); 14279 EXPECT_EQ("{\n" 14280 "\t/* aaaa\n" 14281 "\t bbbb */\n" 14282 "}", 14283 format("{\n" 14284 "/* aaaa\n" 14285 " bbbb */\n" 14286 "}", 14287 Tab)); 14288 EXPECT_EQ("{\n" 14289 "\t/*\n" 14290 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14291 "\t bbbbbbbbbbbbb\n" 14292 "\t*/\n" 14293 "}", 14294 format("{\n" 14295 "/*\n" 14296 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14297 "*/\n" 14298 "}", 14299 Tab)); 14300 EXPECT_EQ("{\n" 14301 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14302 "\t// bbbbbbbbbbbbb\n" 14303 "}", 14304 format("{\n" 14305 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14306 "}", 14307 Tab)); 14308 EXPECT_EQ("{\n" 14309 "\t/*\n" 14310 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14311 "\t bbbbbbbbbbbbb\n" 14312 "\t*/\n" 14313 "}", 14314 format("{\n" 14315 "\t/*\n" 14316 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14317 "\t*/\n" 14318 "}", 14319 Tab)); 14320 EXPECT_EQ("{\n" 14321 "\t/*\n" 14322 "\n" 14323 "\t*/\n" 14324 "}", 14325 format("{\n" 14326 "\t/*\n" 14327 "\n" 14328 "\t*/\n" 14329 "}", 14330 Tab)); 14331 EXPECT_EQ("{\n" 14332 "\t/*\n" 14333 " asdf\n" 14334 "\t*/\n" 14335 "}", 14336 format("{\n" 14337 "\t/*\n" 14338 " asdf\n" 14339 "\t*/\n" 14340 "}", 14341 Tab)); 14342 EXPECT_EQ("/* some\n" 14343 " comment */", 14344 format(" \t \t /* some\n" 14345 " \t \t comment */", 14346 Tab)); 14347 EXPECT_EQ("int a; /* some\n" 14348 " comment */", 14349 format(" \t \t int a; /* some\n" 14350 " \t \t comment */", 14351 Tab)); 14352 EXPECT_EQ("int a; /* some\n" 14353 "comment */", 14354 format(" \t \t int\ta; /* some\n" 14355 " \t \t comment */", 14356 Tab)); 14357 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14358 " comment */", 14359 format(" \t \t f(\"\t\t\"); /* some\n" 14360 " \t \t comment */", 14361 Tab)); 14362 EXPECT_EQ("{\n" 14363 "\t/*\n" 14364 "\t * Comment\n" 14365 "\t */\n" 14366 "\tint i;\n" 14367 "}", 14368 format("{\n" 14369 "\t/*\n" 14370 "\t * Comment\n" 14371 "\t */\n" 14372 "\t int i;\n" 14373 "}", 14374 Tab)); 14375 Tab.TabWidth = 2; 14376 Tab.IndentWidth = 2; 14377 EXPECT_EQ("{\n" 14378 "\t/* aaaa\n" 14379 "\t\t bbbb */\n" 14380 "}", 14381 format("{\n" 14382 "/* aaaa\n" 14383 "\t bbbb */\n" 14384 "}", 14385 Tab)); 14386 EXPECT_EQ("{\n" 14387 "\t/*\n" 14388 "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14389 "\t\tbbbbbbbbbbbbb\n" 14390 "\t*/\n" 14391 "}", 14392 format("{\n" 14393 "/*\n" 14394 "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14395 "*/\n" 14396 "}", 14397 Tab)); 14398 Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 14399 Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 14400 Tab.TabWidth = 4; 14401 Tab.IndentWidth = 4; 14402 verifyFormat("class Assign {\n" 14403 "\tvoid f() {\n" 14404 "\t\tint x = 123;\n" 14405 "\t\tint random = 4;\n" 14406 "\t\tstd::string alphabet =\n" 14407 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n" 14408 "\t}\n" 14409 "};", 14410 Tab); 14411 14412 Tab.UseTab = FormatStyle::UT_AlignWithSpaces; 14413 Tab.TabWidth = 8; 14414 Tab.IndentWidth = 8; 14415 EXPECT_EQ("if (aaaaaaaa && // q\n" 14416 " bb) // w\n" 14417 "\t;", 14418 format("if (aaaaaaaa &&// q\n" 14419 "bb)// w\n" 14420 ";", 14421 Tab)); 14422 EXPECT_EQ("if (aaa && bbb) // w\n" 14423 "\t;", 14424 format("if(aaa&&bbb)// w\n" 14425 ";", 14426 Tab)); 14427 verifyFormat("class X {\n" 14428 "\tvoid f() {\n" 14429 "\t\tsomeFunction(parameter1,\n" 14430 "\t\t parameter2);\n" 14431 "\t}\n" 14432 "};", 14433 Tab); 14434 verifyFormat("#define A \\\n" 14435 "\tvoid f() { \\\n" 14436 "\t\tsomeFunction( \\\n" 14437 "\t\t parameter1, \\\n" 14438 "\t\t parameter2); \\\n" 14439 "\t}", 14440 Tab); 14441 Tab.TabWidth = 4; 14442 Tab.IndentWidth = 8; 14443 verifyFormat("class TabWidth4Indent8 {\n" 14444 "\t\tvoid f() {\n" 14445 "\t\t\t\tsomeFunction(parameter1,\n" 14446 "\t\t\t\t parameter2);\n" 14447 "\t\t}\n" 14448 "};", 14449 Tab); 14450 Tab.TabWidth = 4; 14451 Tab.IndentWidth = 4; 14452 verifyFormat("class TabWidth4Indent4 {\n" 14453 "\tvoid f() {\n" 14454 "\t\tsomeFunction(parameter1,\n" 14455 "\t\t parameter2);\n" 14456 "\t}\n" 14457 "};", 14458 Tab); 14459 Tab.TabWidth = 8; 14460 Tab.IndentWidth = 4; 14461 verifyFormat("class TabWidth8Indent4 {\n" 14462 " void f() {\n" 14463 "\tsomeFunction(parameter1,\n" 14464 "\t parameter2);\n" 14465 " }\n" 14466 "};", 14467 Tab); 14468 Tab.TabWidth = 8; 14469 Tab.IndentWidth = 8; 14470 EXPECT_EQ("/*\n" 14471 " a\t\tcomment\n" 14472 " in multiple lines\n" 14473 " */", 14474 format(" /*\t \t \n" 14475 " \t \t a\t\tcomment\t \t\n" 14476 " \t \t in multiple lines\t\n" 14477 " \t */", 14478 Tab)); 14479 verifyFormat("{\n" 14480 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14481 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14482 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14483 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14484 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14485 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 14486 "};", 14487 Tab); 14488 verifyFormat("enum AA {\n" 14489 "\ta1, // Force multiple lines\n" 14490 "\ta2,\n" 14491 "\ta3\n" 14492 "};", 14493 Tab); 14494 EXPECT_EQ("if (aaaaaaaa && // q\n" 14495 " bb) // w\n" 14496 "\t;", 14497 format("if (aaaaaaaa &&// q\n" 14498 "bb)// w\n" 14499 ";", 14500 Tab)); 14501 verifyFormat("class X {\n" 14502 "\tvoid f() {\n" 14503 "\t\tsomeFunction(parameter1,\n" 14504 "\t\t parameter2);\n" 14505 "\t}\n" 14506 "};", 14507 Tab); 14508 verifyFormat("{\n" 14509 "\tQ(\n" 14510 "\t {\n" 14511 "\t\t int a;\n" 14512 "\t\t someFunction(aaaaaaaa,\n" 14513 "\t\t bbbbbbb);\n" 14514 "\t },\n" 14515 "\t p);\n" 14516 "}", 14517 Tab); 14518 EXPECT_EQ("{\n" 14519 "\t/* aaaa\n" 14520 "\t bbbb */\n" 14521 "}", 14522 format("{\n" 14523 "/* aaaa\n" 14524 " bbbb */\n" 14525 "}", 14526 Tab)); 14527 EXPECT_EQ("{\n" 14528 "\t/*\n" 14529 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14530 "\t bbbbbbbbbbbbb\n" 14531 "\t*/\n" 14532 "}", 14533 format("{\n" 14534 "/*\n" 14535 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14536 "*/\n" 14537 "}", 14538 Tab)); 14539 EXPECT_EQ("{\n" 14540 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14541 "\t// bbbbbbbbbbbbb\n" 14542 "}", 14543 format("{\n" 14544 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14545 "}", 14546 Tab)); 14547 EXPECT_EQ("{\n" 14548 "\t/*\n" 14549 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14550 "\t bbbbbbbbbbbbb\n" 14551 "\t*/\n" 14552 "}", 14553 format("{\n" 14554 "\t/*\n" 14555 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14556 "\t*/\n" 14557 "}", 14558 Tab)); 14559 EXPECT_EQ("{\n" 14560 "\t/*\n" 14561 "\n" 14562 "\t*/\n" 14563 "}", 14564 format("{\n" 14565 "\t/*\n" 14566 "\n" 14567 "\t*/\n" 14568 "}", 14569 Tab)); 14570 EXPECT_EQ("{\n" 14571 "\t/*\n" 14572 " asdf\n" 14573 "\t*/\n" 14574 "}", 14575 format("{\n" 14576 "\t/*\n" 14577 " asdf\n" 14578 "\t*/\n" 14579 "}", 14580 Tab)); 14581 EXPECT_EQ("/* some\n" 14582 " comment */", 14583 format(" \t \t /* some\n" 14584 " \t \t comment */", 14585 Tab)); 14586 EXPECT_EQ("int a; /* some\n" 14587 " comment */", 14588 format(" \t \t int a; /* some\n" 14589 " \t \t comment */", 14590 Tab)); 14591 EXPECT_EQ("int a; /* some\n" 14592 "comment */", 14593 format(" \t \t int\ta; /* some\n" 14594 " \t \t comment */", 14595 Tab)); 14596 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14597 " comment */", 14598 format(" \t \t f(\"\t\t\"); /* some\n" 14599 " \t \t comment */", 14600 Tab)); 14601 EXPECT_EQ("{\n" 14602 "\t/*\n" 14603 "\t * Comment\n" 14604 "\t */\n" 14605 "\tint i;\n" 14606 "}", 14607 format("{\n" 14608 "\t/*\n" 14609 "\t * Comment\n" 14610 "\t */\n" 14611 "\t int i;\n" 14612 "}", 14613 Tab)); 14614 Tab.TabWidth = 2; 14615 Tab.IndentWidth = 2; 14616 EXPECT_EQ("{\n" 14617 "\t/* aaaa\n" 14618 "\t bbbb */\n" 14619 "}", 14620 format("{\n" 14621 "/* aaaa\n" 14622 " bbbb */\n" 14623 "}", 14624 Tab)); 14625 EXPECT_EQ("{\n" 14626 "\t/*\n" 14627 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14628 "\t bbbbbbbbbbbbb\n" 14629 "\t*/\n" 14630 "}", 14631 format("{\n" 14632 "/*\n" 14633 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14634 "*/\n" 14635 "}", 14636 Tab)); 14637 Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 14638 Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 14639 Tab.TabWidth = 4; 14640 Tab.IndentWidth = 4; 14641 verifyFormat("class Assign {\n" 14642 "\tvoid f() {\n" 14643 "\t\tint x = 123;\n" 14644 "\t\tint random = 4;\n" 14645 "\t\tstd::string alphabet =\n" 14646 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n" 14647 "\t}\n" 14648 "};", 14649 Tab); 14650 Tab.AlignOperands = FormatStyle::OAS_Align; 14651 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n" 14652 " cccccccccccccccccccc;", 14653 Tab); 14654 // no alignment 14655 verifyFormat("int aaaaaaaaaa =\n" 14656 "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 14657 Tab); 14658 verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n" 14659 " : bbbbbbbbbbbbbb ? 222222222222222\n" 14660 " : 333333333333333;", 14661 Tab); 14662 Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 14663 Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator; 14664 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n" 14665 " + cccccccccccccccccccc;", 14666 Tab); 14667 } 14668 14669 TEST_F(FormatTest, ZeroTabWidth) { 14670 FormatStyle Tab = getLLVMStyleWithColumns(42); 14671 Tab.IndentWidth = 8; 14672 Tab.UseTab = FormatStyle::UT_Never; 14673 Tab.TabWidth = 0; 14674 EXPECT_EQ("void a(){\n" 14675 " // line starts with '\t'\n" 14676 "};", 14677 format("void a(){\n" 14678 "\t// line starts with '\t'\n" 14679 "};", 14680 Tab)); 14681 14682 EXPECT_EQ("void a(){\n" 14683 " // line starts with '\t'\n" 14684 "};", 14685 format("void a(){\n" 14686 "\t\t// line starts with '\t'\n" 14687 "};", 14688 Tab)); 14689 14690 Tab.UseTab = FormatStyle::UT_ForIndentation; 14691 EXPECT_EQ("void a(){\n" 14692 " // line starts with '\t'\n" 14693 "};", 14694 format("void a(){\n" 14695 "\t// line starts with '\t'\n" 14696 "};", 14697 Tab)); 14698 14699 EXPECT_EQ("void a(){\n" 14700 " // line starts with '\t'\n" 14701 "};", 14702 format("void a(){\n" 14703 "\t\t// line starts with '\t'\n" 14704 "};", 14705 Tab)); 14706 14707 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation; 14708 EXPECT_EQ("void a(){\n" 14709 " // line starts with '\t'\n" 14710 "};", 14711 format("void a(){\n" 14712 "\t// line starts with '\t'\n" 14713 "};", 14714 Tab)); 14715 14716 EXPECT_EQ("void a(){\n" 14717 " // line starts with '\t'\n" 14718 "};", 14719 format("void a(){\n" 14720 "\t\t// line starts with '\t'\n" 14721 "};", 14722 Tab)); 14723 14724 Tab.UseTab = FormatStyle::UT_AlignWithSpaces; 14725 EXPECT_EQ("void a(){\n" 14726 " // line starts with '\t'\n" 14727 "};", 14728 format("void a(){\n" 14729 "\t// line starts with '\t'\n" 14730 "};", 14731 Tab)); 14732 14733 EXPECT_EQ("void a(){\n" 14734 " // line starts with '\t'\n" 14735 "};", 14736 format("void a(){\n" 14737 "\t\t// line starts with '\t'\n" 14738 "};", 14739 Tab)); 14740 14741 Tab.UseTab = FormatStyle::UT_Always; 14742 EXPECT_EQ("void a(){\n" 14743 "// line starts with '\t'\n" 14744 "};", 14745 format("void a(){\n" 14746 "\t// line starts with '\t'\n" 14747 "};", 14748 Tab)); 14749 14750 EXPECT_EQ("void a(){\n" 14751 "// line starts with '\t'\n" 14752 "};", 14753 format("void a(){\n" 14754 "\t\t// line starts with '\t'\n" 14755 "};", 14756 Tab)); 14757 } 14758 14759 TEST_F(FormatTest, CalculatesOriginalColumn) { 14760 EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14761 "q\"; /* some\n" 14762 " comment */", 14763 format(" \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14764 "q\"; /* some\n" 14765 " comment */", 14766 getLLVMStyle())); 14767 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n" 14768 "/* some\n" 14769 " comment */", 14770 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n" 14771 " /* some\n" 14772 " comment */", 14773 getLLVMStyle())); 14774 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14775 "qqq\n" 14776 "/* some\n" 14777 " comment */", 14778 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14779 "qqq\n" 14780 " /* some\n" 14781 " comment */", 14782 getLLVMStyle())); 14783 EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14784 "wwww; /* some\n" 14785 " comment */", 14786 format(" inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14787 "wwww; /* some\n" 14788 " comment */", 14789 getLLVMStyle())); 14790 } 14791 14792 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) { 14793 FormatStyle NoSpace = getLLVMStyle(); 14794 NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never; 14795 14796 verifyFormat("while(true)\n" 14797 " continue;", 14798 NoSpace); 14799 verifyFormat("for(;;)\n" 14800 " continue;", 14801 NoSpace); 14802 verifyFormat("if(true)\n" 14803 " f();\n" 14804 "else if(true)\n" 14805 " f();", 14806 NoSpace); 14807 verifyFormat("do {\n" 14808 " do_something();\n" 14809 "} while(something());", 14810 NoSpace); 14811 verifyFormat("switch(x) {\n" 14812 "default:\n" 14813 " break;\n" 14814 "}", 14815 NoSpace); 14816 verifyFormat("auto i = std::make_unique<int>(5);", NoSpace); 14817 verifyFormat("size_t x = sizeof(x);", NoSpace); 14818 verifyFormat("auto f(int x) -> decltype(x);", NoSpace); 14819 verifyFormat("auto f(int x) -> typeof(x);", NoSpace); 14820 verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace); 14821 verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace); 14822 verifyFormat("int f(T x) noexcept(x.create());", NoSpace); 14823 verifyFormat("alignas(128) char a[128];", NoSpace); 14824 verifyFormat("size_t x = alignof(MyType);", NoSpace); 14825 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace); 14826 verifyFormat("int f() throw(Deprecated);", NoSpace); 14827 verifyFormat("typedef void (*cb)(int);", NoSpace); 14828 verifyFormat("T A::operator()();", NoSpace); 14829 verifyFormat("X A::operator++(T);", NoSpace); 14830 verifyFormat("auto lambda = []() { return 0; };", NoSpace); 14831 14832 FormatStyle Space = getLLVMStyle(); 14833 Space.SpaceBeforeParens = FormatStyle::SBPO_Always; 14834 14835 verifyFormat("int f ();", Space); 14836 verifyFormat("void f (int a, T b) {\n" 14837 " while (true)\n" 14838 " continue;\n" 14839 "}", 14840 Space); 14841 verifyFormat("if (true)\n" 14842 " f ();\n" 14843 "else if (true)\n" 14844 " f ();", 14845 Space); 14846 verifyFormat("do {\n" 14847 " do_something ();\n" 14848 "} while (something ());", 14849 Space); 14850 verifyFormat("switch (x) {\n" 14851 "default:\n" 14852 " break;\n" 14853 "}", 14854 Space); 14855 verifyFormat("A::A () : a (1) {}", Space); 14856 verifyFormat("void f () __attribute__ ((asdf));", Space); 14857 verifyFormat("*(&a + 1);\n" 14858 "&((&a)[1]);\n" 14859 "a[(b + c) * d];\n" 14860 "(((a + 1) * 2) + 3) * 4;", 14861 Space); 14862 verifyFormat("#define A(x) x", Space); 14863 verifyFormat("#define A (x) x", Space); 14864 verifyFormat("#if defined(x)\n" 14865 "#endif", 14866 Space); 14867 verifyFormat("auto i = std::make_unique<int> (5);", Space); 14868 verifyFormat("size_t x = sizeof (x);", Space); 14869 verifyFormat("auto f (int x) -> decltype (x);", Space); 14870 verifyFormat("auto f (int x) -> typeof (x);", Space); 14871 verifyFormat("auto f (int x) -> _Atomic (x);", Space); 14872 verifyFormat("auto f (int x) -> __underlying_type (x);", Space); 14873 verifyFormat("int f (T x) noexcept (x.create ());", Space); 14874 verifyFormat("alignas (128) char a[128];", Space); 14875 verifyFormat("size_t x = alignof (MyType);", Space); 14876 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space); 14877 verifyFormat("int f () throw (Deprecated);", Space); 14878 verifyFormat("typedef void (*cb) (int);", Space); 14879 // FIXME these tests regressed behaviour. 14880 // verifyFormat("T A::operator() ();", Space); 14881 // verifyFormat("X A::operator++ (T);", Space); 14882 verifyFormat("auto lambda = [] () { return 0; };", Space); 14883 verifyFormat("int x = int (y);", Space); 14884 14885 FormatStyle SomeSpace = getLLVMStyle(); 14886 SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses; 14887 14888 verifyFormat("[]() -> float {}", SomeSpace); 14889 verifyFormat("[] (auto foo) {}", SomeSpace); 14890 verifyFormat("[foo]() -> int {}", SomeSpace); 14891 verifyFormat("int f();", SomeSpace); 14892 verifyFormat("void f (int a, T b) {\n" 14893 " while (true)\n" 14894 " continue;\n" 14895 "}", 14896 SomeSpace); 14897 verifyFormat("if (true)\n" 14898 " f();\n" 14899 "else if (true)\n" 14900 " f();", 14901 SomeSpace); 14902 verifyFormat("do {\n" 14903 " do_something();\n" 14904 "} while (something());", 14905 SomeSpace); 14906 verifyFormat("switch (x) {\n" 14907 "default:\n" 14908 " break;\n" 14909 "}", 14910 SomeSpace); 14911 verifyFormat("A::A() : a (1) {}", SomeSpace); 14912 verifyFormat("void f() __attribute__ ((asdf));", SomeSpace); 14913 verifyFormat("*(&a + 1);\n" 14914 "&((&a)[1]);\n" 14915 "a[(b + c) * d];\n" 14916 "(((a + 1) * 2) + 3) * 4;", 14917 SomeSpace); 14918 verifyFormat("#define A(x) x", SomeSpace); 14919 verifyFormat("#define A (x) x", SomeSpace); 14920 verifyFormat("#if defined(x)\n" 14921 "#endif", 14922 SomeSpace); 14923 verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace); 14924 verifyFormat("size_t x = sizeof (x);", SomeSpace); 14925 verifyFormat("auto f (int x) -> decltype (x);", SomeSpace); 14926 verifyFormat("auto f (int x) -> typeof (x);", SomeSpace); 14927 verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace); 14928 verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace); 14929 verifyFormat("int f (T x) noexcept (x.create());", SomeSpace); 14930 verifyFormat("alignas (128) char a[128];", SomeSpace); 14931 verifyFormat("size_t x = alignof (MyType);", SomeSpace); 14932 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", 14933 SomeSpace); 14934 verifyFormat("int f() throw (Deprecated);", SomeSpace); 14935 verifyFormat("typedef void (*cb) (int);", SomeSpace); 14936 verifyFormat("T A::operator()();", SomeSpace); 14937 // FIXME these tests regressed behaviour. 14938 // verifyFormat("X A::operator++ (T);", SomeSpace); 14939 verifyFormat("int x = int (y);", SomeSpace); 14940 verifyFormat("auto lambda = []() { return 0; };", SomeSpace); 14941 14942 FormatStyle SpaceControlStatements = getLLVMStyle(); 14943 SpaceControlStatements.SpaceBeforeParens = FormatStyle::SBPO_Custom; 14944 SpaceControlStatements.SpaceBeforeParensOptions.AfterControlStatements = true; 14945 14946 verifyFormat("while (true)\n" 14947 " continue;", 14948 SpaceControlStatements); 14949 verifyFormat("if (true)\n" 14950 " f();\n" 14951 "else if (true)\n" 14952 " f();", 14953 SpaceControlStatements); 14954 verifyFormat("for (;;) {\n" 14955 " do_something();\n" 14956 "}", 14957 SpaceControlStatements); 14958 verifyFormat("do {\n" 14959 " do_something();\n" 14960 "} while (something());", 14961 SpaceControlStatements); 14962 verifyFormat("switch (x) {\n" 14963 "default:\n" 14964 " break;\n" 14965 "}", 14966 SpaceControlStatements); 14967 14968 FormatStyle SpaceFuncDecl = getLLVMStyle(); 14969 SpaceFuncDecl.SpaceBeforeParens = FormatStyle::SBPO_Custom; 14970 SpaceFuncDecl.SpaceBeforeParensOptions.AfterFunctionDeclarationName = true; 14971 14972 verifyFormat("int f ();", SpaceFuncDecl); 14973 verifyFormat("void f(int a, T b) {}", SpaceFuncDecl); 14974 verifyFormat("A::A() : a(1) {}", SpaceFuncDecl); 14975 verifyFormat("void f () __attribute__((asdf));", SpaceFuncDecl); 14976 verifyFormat("#define A(x) x", SpaceFuncDecl); 14977 verifyFormat("#define A (x) x", SpaceFuncDecl); 14978 verifyFormat("#if defined(x)\n" 14979 "#endif", 14980 SpaceFuncDecl); 14981 verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDecl); 14982 verifyFormat("size_t x = sizeof(x);", SpaceFuncDecl); 14983 verifyFormat("auto f (int x) -> decltype(x);", SpaceFuncDecl); 14984 verifyFormat("auto f (int x) -> typeof(x);", SpaceFuncDecl); 14985 verifyFormat("auto f (int x) -> _Atomic(x);", SpaceFuncDecl); 14986 verifyFormat("auto f (int x) -> __underlying_type(x);", SpaceFuncDecl); 14987 verifyFormat("int f (T x) noexcept(x.create());", SpaceFuncDecl); 14988 verifyFormat("alignas(128) char a[128];", SpaceFuncDecl); 14989 verifyFormat("size_t x = alignof(MyType);", SpaceFuncDecl); 14990 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", 14991 SpaceFuncDecl); 14992 verifyFormat("int f () throw(Deprecated);", SpaceFuncDecl); 14993 verifyFormat("typedef void (*cb)(int);", SpaceFuncDecl); 14994 // FIXME these tests regressed behaviour. 14995 // verifyFormat("T A::operator() ();", SpaceFuncDecl); 14996 // verifyFormat("X A::operator++ (T);", SpaceFuncDecl); 14997 verifyFormat("T A::operator()() {}", SpaceFuncDecl); 14998 verifyFormat("auto lambda = []() { return 0; };", SpaceFuncDecl); 14999 verifyFormat("int x = int(y);", SpaceFuncDecl); 15000 verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}", 15001 SpaceFuncDecl); 15002 15003 FormatStyle SpaceFuncDef = getLLVMStyle(); 15004 SpaceFuncDef.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15005 SpaceFuncDef.SpaceBeforeParensOptions.AfterFunctionDefinitionName = true; 15006 15007 verifyFormat("int f();", SpaceFuncDef); 15008 verifyFormat("void f (int a, T b) {}", SpaceFuncDef); 15009 verifyFormat("A::A() : a(1) {}", SpaceFuncDef); 15010 verifyFormat("void f() __attribute__((asdf));", SpaceFuncDef); 15011 verifyFormat("#define A(x) x", SpaceFuncDef); 15012 verifyFormat("#define A (x) x", SpaceFuncDef); 15013 verifyFormat("#if defined(x)\n" 15014 "#endif", 15015 SpaceFuncDef); 15016 verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDef); 15017 verifyFormat("size_t x = sizeof(x);", SpaceFuncDef); 15018 verifyFormat("auto f(int x) -> decltype(x);", SpaceFuncDef); 15019 verifyFormat("auto f(int x) -> typeof(x);", SpaceFuncDef); 15020 verifyFormat("auto f(int x) -> _Atomic(x);", SpaceFuncDef); 15021 verifyFormat("auto f(int x) -> __underlying_type(x);", SpaceFuncDef); 15022 verifyFormat("int f(T x) noexcept(x.create());", SpaceFuncDef); 15023 verifyFormat("alignas(128) char a[128];", SpaceFuncDef); 15024 verifyFormat("size_t x = alignof(MyType);", SpaceFuncDef); 15025 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", 15026 SpaceFuncDef); 15027 verifyFormat("int f() throw(Deprecated);", SpaceFuncDef); 15028 verifyFormat("typedef void (*cb)(int);", SpaceFuncDef); 15029 verifyFormat("T A::operator()();", SpaceFuncDef); 15030 verifyFormat("X A::operator++(T);", SpaceFuncDef); 15031 // verifyFormat("T A::operator() () {}", SpaceFuncDef); 15032 verifyFormat("auto lambda = [] () { return 0; };", SpaceFuncDef); 15033 verifyFormat("int x = int(y);", SpaceFuncDef); 15034 verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}", 15035 SpaceFuncDef); 15036 15037 FormatStyle SpaceIfMacros = getLLVMStyle(); 15038 SpaceIfMacros.IfMacros.clear(); 15039 SpaceIfMacros.IfMacros.push_back("MYIF"); 15040 SpaceIfMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15041 SpaceIfMacros.SpaceBeforeParensOptions.AfterIfMacros = true; 15042 verifyFormat("MYIF (a)\n return;", SpaceIfMacros); 15043 verifyFormat("MYIF (a)\n return;\nelse MYIF (b)\n return;", SpaceIfMacros); 15044 verifyFormat("MYIF (a)\n return;\nelse\n return;", SpaceIfMacros); 15045 15046 FormatStyle SpaceForeachMacros = getLLVMStyle(); 15047 EXPECT_EQ(SpaceForeachMacros.AllowShortBlocksOnASingleLine, 15048 FormatStyle::SBS_Never); 15049 EXPECT_EQ(SpaceForeachMacros.AllowShortLoopsOnASingleLine, false); 15050 SpaceForeachMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15051 SpaceForeachMacros.SpaceBeforeParensOptions.AfterForeachMacros = true; 15052 verifyFormat("for (;;) {\n" 15053 "}", 15054 SpaceForeachMacros); 15055 verifyFormat("foreach (Item *item, itemlist) {\n" 15056 "}", 15057 SpaceForeachMacros); 15058 verifyFormat("Q_FOREACH (Item *item, itemlist) {\n" 15059 "}", 15060 SpaceForeachMacros); 15061 verifyFormat("BOOST_FOREACH (Item *item, itemlist) {\n" 15062 "}", 15063 SpaceForeachMacros); 15064 verifyFormat("UNKNOWN_FOREACH(Item *item, itemlist) {}", SpaceForeachMacros); 15065 15066 FormatStyle SomeSpace2 = getLLVMStyle(); 15067 SomeSpace2.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15068 SomeSpace2.SpaceBeforeParensOptions.BeforeNonEmptyParentheses = true; 15069 verifyFormat("[]() -> float {}", SomeSpace2); 15070 verifyFormat("[] (auto foo) {}", SomeSpace2); 15071 verifyFormat("[foo]() -> int {}", SomeSpace2); 15072 verifyFormat("int f();", SomeSpace2); 15073 verifyFormat("void f (int a, T b) {\n" 15074 " while (true)\n" 15075 " continue;\n" 15076 "}", 15077 SomeSpace2); 15078 verifyFormat("if (true)\n" 15079 " f();\n" 15080 "else if (true)\n" 15081 " f();", 15082 SomeSpace2); 15083 verifyFormat("do {\n" 15084 " do_something();\n" 15085 "} while (something());", 15086 SomeSpace2); 15087 verifyFormat("switch (x) {\n" 15088 "default:\n" 15089 " break;\n" 15090 "}", 15091 SomeSpace2); 15092 verifyFormat("A::A() : a (1) {}", SomeSpace2); 15093 verifyFormat("void f() __attribute__ ((asdf));", SomeSpace2); 15094 verifyFormat("*(&a + 1);\n" 15095 "&((&a)[1]);\n" 15096 "a[(b + c) * d];\n" 15097 "(((a + 1) * 2) + 3) * 4;", 15098 SomeSpace2); 15099 verifyFormat("#define A(x) x", SomeSpace2); 15100 verifyFormat("#define A (x) x", SomeSpace2); 15101 verifyFormat("#if defined(x)\n" 15102 "#endif", 15103 SomeSpace2); 15104 verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace2); 15105 verifyFormat("size_t x = sizeof (x);", SomeSpace2); 15106 verifyFormat("auto f (int x) -> decltype (x);", SomeSpace2); 15107 verifyFormat("auto f (int x) -> typeof (x);", SomeSpace2); 15108 verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace2); 15109 verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace2); 15110 verifyFormat("int f (T x) noexcept (x.create());", SomeSpace2); 15111 verifyFormat("alignas (128) char a[128];", SomeSpace2); 15112 verifyFormat("size_t x = alignof (MyType);", SomeSpace2); 15113 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", 15114 SomeSpace2); 15115 verifyFormat("int f() throw (Deprecated);", SomeSpace2); 15116 verifyFormat("typedef void (*cb) (int);", SomeSpace2); 15117 verifyFormat("T A::operator()();", SomeSpace2); 15118 // verifyFormat("X A::operator++ (T);", SomeSpace2); 15119 verifyFormat("int x = int (y);", SomeSpace2); 15120 verifyFormat("auto lambda = []() { return 0; };", SomeSpace2); 15121 15122 FormatStyle SpaceAfterOverloadedOperator = getLLVMStyle(); 15123 SpaceAfterOverloadedOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15124 SpaceAfterOverloadedOperator.SpaceBeforeParensOptions 15125 .AfterOverloadedOperator = true; 15126 15127 verifyFormat("auto operator++ () -> int;", SpaceAfterOverloadedOperator); 15128 verifyFormat("X A::operator++ ();", SpaceAfterOverloadedOperator); 15129 verifyFormat("some_object.operator++ ();", SpaceAfterOverloadedOperator); 15130 verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator); 15131 15132 SpaceAfterOverloadedOperator.SpaceBeforeParensOptions 15133 .AfterOverloadedOperator = false; 15134 15135 verifyFormat("auto operator++() -> int;", SpaceAfterOverloadedOperator); 15136 verifyFormat("X A::operator++();", SpaceAfterOverloadedOperator); 15137 verifyFormat("some_object.operator++();", SpaceAfterOverloadedOperator); 15138 verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator); 15139 15140 auto SpaceAfterRequires = getLLVMStyle(); 15141 SpaceAfterRequires.SpaceBeforeParens = FormatStyle::SBPO_Custom; 15142 EXPECT_FALSE( 15143 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause); 15144 EXPECT_FALSE( 15145 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression); 15146 verifyFormat("void f(auto x)\n" 15147 " requires requires(int i) { x + i; }\n" 15148 "{}", 15149 SpaceAfterRequires); 15150 verifyFormat("void f(auto x)\n" 15151 " requires(requires(int i) { x + i; })\n" 15152 "{}", 15153 SpaceAfterRequires); 15154 verifyFormat("if (requires(int i) { x + i; })\n" 15155 " return;", 15156 SpaceAfterRequires); 15157 verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires); 15158 verifyFormat("template <typename T>\n" 15159 " requires(Foo<T>)\n" 15160 "class Bar;", 15161 SpaceAfterRequires); 15162 15163 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true; 15164 verifyFormat("void f(auto x)\n" 15165 " requires requires(int i) { x + i; }\n" 15166 "{}", 15167 SpaceAfterRequires); 15168 verifyFormat("void f(auto x)\n" 15169 " requires (requires(int i) { x + i; })\n" 15170 "{}", 15171 SpaceAfterRequires); 15172 verifyFormat("if (requires(int i) { x + i; })\n" 15173 " return;", 15174 SpaceAfterRequires); 15175 verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires); 15176 verifyFormat("template <typename T>\n" 15177 " requires (Foo<T>)\n" 15178 "class Bar;", 15179 SpaceAfterRequires); 15180 15181 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = false; 15182 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression = true; 15183 verifyFormat("void f(auto x)\n" 15184 " requires requires (int i) { x + i; }\n" 15185 "{}", 15186 SpaceAfterRequires); 15187 verifyFormat("void f(auto x)\n" 15188 " requires(requires (int i) { x + i; })\n" 15189 "{}", 15190 SpaceAfterRequires); 15191 verifyFormat("if (requires (int i) { x + i; })\n" 15192 " return;", 15193 SpaceAfterRequires); 15194 verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires); 15195 verifyFormat("template <typename T>\n" 15196 " requires(Foo<T>)\n" 15197 "class Bar;", 15198 SpaceAfterRequires); 15199 15200 SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true; 15201 verifyFormat("void f(auto x)\n" 15202 " requires requires (int i) { x + i; }\n" 15203 "{}", 15204 SpaceAfterRequires); 15205 verifyFormat("void f(auto x)\n" 15206 " requires (requires (int i) { x + i; })\n" 15207 "{}", 15208 SpaceAfterRequires); 15209 verifyFormat("if (requires (int i) { x + i; })\n" 15210 " return;", 15211 SpaceAfterRequires); 15212 verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires); 15213 verifyFormat("template <typename T>\n" 15214 " requires (Foo<T>)\n" 15215 "class Bar;", 15216 SpaceAfterRequires); 15217 } 15218 15219 TEST_F(FormatTest, SpaceAfterLogicalNot) { 15220 FormatStyle Spaces = getLLVMStyle(); 15221 Spaces.SpaceAfterLogicalNot = true; 15222 15223 verifyFormat("bool x = ! y", Spaces); 15224 verifyFormat("if (! isFailure())", Spaces); 15225 verifyFormat("if (! (a && b))", Spaces); 15226 verifyFormat("\"Error!\"", Spaces); 15227 verifyFormat("! ! x", Spaces); 15228 } 15229 15230 TEST_F(FormatTest, ConfigurableSpacesInParentheses) { 15231 FormatStyle Spaces = getLLVMStyle(); 15232 15233 Spaces.SpacesInParentheses = true; 15234 verifyFormat("do_something( ::globalVar );", Spaces); 15235 verifyFormat("call( x, y, z );", Spaces); 15236 verifyFormat("call();", Spaces); 15237 verifyFormat("std::function<void( int, int )> callback;", Spaces); 15238 verifyFormat("void inFunction() { std::function<void( int, int )> fct; }", 15239 Spaces); 15240 verifyFormat("while ( (bool)1 )\n" 15241 " continue;", 15242 Spaces); 15243 verifyFormat("for ( ;; )\n" 15244 " continue;", 15245 Spaces); 15246 verifyFormat("if ( true )\n" 15247 " f();\n" 15248 "else if ( true )\n" 15249 " f();", 15250 Spaces); 15251 verifyFormat("do {\n" 15252 " do_something( (int)i );\n" 15253 "} while ( something() );", 15254 Spaces); 15255 verifyFormat("switch ( x ) {\n" 15256 "default:\n" 15257 " break;\n" 15258 "}", 15259 Spaces); 15260 15261 Spaces.SpacesInParentheses = false; 15262 Spaces.SpacesInCStyleCastParentheses = true; 15263 verifyFormat("Type *A = ( Type * )P;", Spaces); 15264 verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces); 15265 verifyFormat("x = ( int32 )y;", Spaces); 15266 verifyFormat("int a = ( int )(2.0f);", Spaces); 15267 verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces); 15268 verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces); 15269 verifyFormat("#define x (( int )-1)", Spaces); 15270 15271 // Run the first set of tests again with: 15272 Spaces.SpacesInParentheses = false; 15273 Spaces.SpaceInEmptyParentheses = true; 15274 Spaces.SpacesInCStyleCastParentheses = true; 15275 verifyFormat("call(x, y, z);", Spaces); 15276 verifyFormat("call( );", Spaces); 15277 verifyFormat("std::function<void(int, int)> callback;", Spaces); 15278 verifyFormat("while (( bool )1)\n" 15279 " continue;", 15280 Spaces); 15281 verifyFormat("for (;;)\n" 15282 " continue;", 15283 Spaces); 15284 verifyFormat("if (true)\n" 15285 " f( );\n" 15286 "else if (true)\n" 15287 " f( );", 15288 Spaces); 15289 verifyFormat("do {\n" 15290 " do_something(( int )i);\n" 15291 "} while (something( ));", 15292 Spaces); 15293 verifyFormat("switch (x) {\n" 15294 "default:\n" 15295 " break;\n" 15296 "}", 15297 Spaces); 15298 15299 // Run the first set of tests again with: 15300 Spaces.SpaceAfterCStyleCast = true; 15301 verifyFormat("call(x, y, z);", Spaces); 15302 verifyFormat("call( );", Spaces); 15303 verifyFormat("std::function<void(int, int)> callback;", Spaces); 15304 verifyFormat("while (( bool ) 1)\n" 15305 " continue;", 15306 Spaces); 15307 verifyFormat("for (;;)\n" 15308 " continue;", 15309 Spaces); 15310 verifyFormat("if (true)\n" 15311 " f( );\n" 15312 "else if (true)\n" 15313 " f( );", 15314 Spaces); 15315 verifyFormat("do {\n" 15316 " do_something(( int ) i);\n" 15317 "} while (something( ));", 15318 Spaces); 15319 verifyFormat("switch (x) {\n" 15320 "default:\n" 15321 " break;\n" 15322 "}", 15323 Spaces); 15324 verifyFormat("#define CONF_BOOL(x) ( bool * ) ( void * ) (x)", Spaces); 15325 verifyFormat("#define CONF_BOOL(x) ( bool * ) (x)", Spaces); 15326 verifyFormat("#define CONF_BOOL(x) ( bool ) (x)", Spaces); 15327 verifyFormat("bool *y = ( bool * ) ( void * ) (x);", Spaces); 15328 verifyFormat("bool *y = ( bool * ) (x);", Spaces); 15329 15330 // Run subset of tests again with: 15331 Spaces.SpacesInCStyleCastParentheses = false; 15332 Spaces.SpaceAfterCStyleCast = true; 15333 verifyFormat("while ((bool) 1)\n" 15334 " continue;", 15335 Spaces); 15336 verifyFormat("do {\n" 15337 " do_something((int) i);\n" 15338 "} while (something( ));", 15339 Spaces); 15340 15341 verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces); 15342 verifyFormat("size_t idx = (size_t) a;", Spaces); 15343 verifyFormat("size_t idx = (size_t) (a - 1);", Spaces); 15344 verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces); 15345 verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces); 15346 verifyFormat("size_t idx = (*foo)(a - 1);", Spaces); 15347 verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces); 15348 verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (x)", Spaces); 15349 verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (int) (x)", Spaces); 15350 verifyFormat("bool *y = (bool *) (void *) (x);", Spaces); 15351 verifyFormat("bool *y = (bool *) (void *) (int) (x);", Spaces); 15352 verifyFormat("bool *y = (bool *) (void *) (int) foo(x);", Spaces); 15353 Spaces.ColumnLimit = 80; 15354 Spaces.IndentWidth = 4; 15355 Spaces.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 15356 verifyFormat("void foo( ) {\n" 15357 " size_t foo = (*(function))(\n" 15358 " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, " 15359 "BarrrrrrrrrrrrLong,\n" 15360 " FoooooooooLooooong);\n" 15361 "}", 15362 Spaces); 15363 Spaces.SpaceAfterCStyleCast = false; 15364 verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces); 15365 verifyFormat("size_t idx = (size_t)a;", Spaces); 15366 verifyFormat("size_t idx = (size_t)(a - 1);", Spaces); 15367 verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces); 15368 verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces); 15369 verifyFormat("size_t idx = (*foo)(a - 1);", Spaces); 15370 verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces); 15371 15372 verifyFormat("void foo( ) {\n" 15373 " size_t foo = (*(function))(\n" 15374 " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, " 15375 "BarrrrrrrrrrrrLong,\n" 15376 " FoooooooooLooooong);\n" 15377 "}", 15378 Spaces); 15379 } 15380 15381 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) { 15382 verifyFormat("int a[5];"); 15383 verifyFormat("a[3] += 42;"); 15384 15385 FormatStyle Spaces = getLLVMStyle(); 15386 Spaces.SpacesInSquareBrackets = true; 15387 // Not lambdas. 15388 verifyFormat("int a[ 5 ];", Spaces); 15389 verifyFormat("a[ 3 ] += 42;", Spaces); 15390 verifyFormat("constexpr char hello[]{\"hello\"};", Spaces); 15391 verifyFormat("double &operator[](int i) { return 0; }\n" 15392 "int i;", 15393 Spaces); 15394 verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces); 15395 verifyFormat("int i = a[ a ][ a ]->f();", Spaces); 15396 verifyFormat("int i = (*b)[ a ]->f();", Spaces); 15397 // Lambdas. 15398 verifyFormat("int c = []() -> int { return 2; }();\n", Spaces); 15399 verifyFormat("return [ i, args... ] {};", Spaces); 15400 verifyFormat("int foo = [ &bar ]() {};", Spaces); 15401 verifyFormat("int foo = [ = ]() {};", Spaces); 15402 verifyFormat("int foo = [ & ]() {};", Spaces); 15403 verifyFormat("int foo = [ =, &bar ]() {};", Spaces); 15404 verifyFormat("int foo = [ &bar, = ]() {};", Spaces); 15405 } 15406 15407 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) { 15408 FormatStyle NoSpaceStyle = getLLVMStyle(); 15409 verifyFormat("int a[5];", NoSpaceStyle); 15410 verifyFormat("a[3] += 42;", NoSpaceStyle); 15411 15412 verifyFormat("int a[1];", NoSpaceStyle); 15413 verifyFormat("int 1 [a];", NoSpaceStyle); 15414 verifyFormat("int a[1][2];", NoSpaceStyle); 15415 verifyFormat("a[7] = 5;", NoSpaceStyle); 15416 verifyFormat("int a = (f())[23];", NoSpaceStyle); 15417 verifyFormat("f([] {})", NoSpaceStyle); 15418 15419 FormatStyle Space = getLLVMStyle(); 15420 Space.SpaceBeforeSquareBrackets = true; 15421 verifyFormat("int c = []() -> int { return 2; }();\n", Space); 15422 verifyFormat("return [i, args...] {};", Space); 15423 15424 verifyFormat("int a [5];", Space); 15425 verifyFormat("a [3] += 42;", Space); 15426 verifyFormat("constexpr char hello []{\"hello\"};", Space); 15427 verifyFormat("double &operator[](int i) { return 0; }\n" 15428 "int i;", 15429 Space); 15430 verifyFormat("std::unique_ptr<int []> foo() {}", Space); 15431 verifyFormat("int i = a [a][a]->f();", Space); 15432 verifyFormat("int i = (*b) [a]->f();", Space); 15433 15434 verifyFormat("int a [1];", Space); 15435 verifyFormat("int 1 [a];", Space); 15436 verifyFormat("int a [1][2];", Space); 15437 verifyFormat("a [7] = 5;", Space); 15438 verifyFormat("int a = (f()) [23];", Space); 15439 verifyFormat("f([] {})", Space); 15440 } 15441 15442 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) { 15443 verifyFormat("int a = 5;"); 15444 verifyFormat("a += 42;"); 15445 verifyFormat("a or_eq 8;"); 15446 15447 FormatStyle Spaces = getLLVMStyle(); 15448 Spaces.SpaceBeforeAssignmentOperators = false; 15449 verifyFormat("int a= 5;", Spaces); 15450 verifyFormat("a+= 42;", Spaces); 15451 verifyFormat("a or_eq 8;", Spaces); 15452 } 15453 15454 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) { 15455 verifyFormat("class Foo : public Bar {};"); 15456 verifyFormat("Foo::Foo() : foo(1) {}"); 15457 verifyFormat("for (auto a : b) {\n}"); 15458 verifyFormat("int x = a ? b : c;"); 15459 verifyFormat("{\n" 15460 "label0:\n" 15461 " int x = 0;\n" 15462 "}"); 15463 verifyFormat("switch (x) {\n" 15464 "case 1:\n" 15465 "default:\n" 15466 "}"); 15467 verifyFormat("switch (allBraces) {\n" 15468 "case 1: {\n" 15469 " break;\n" 15470 "}\n" 15471 "case 2: {\n" 15472 " [[fallthrough]];\n" 15473 "}\n" 15474 "default: {\n" 15475 " break;\n" 15476 "}\n" 15477 "}"); 15478 15479 FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30); 15480 CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false; 15481 verifyFormat("class Foo : public Bar {};", CtorInitializerStyle); 15482 verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle); 15483 verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle); 15484 verifyFormat("int x = a ? b : c;", CtorInitializerStyle); 15485 verifyFormat("{\n" 15486 "label1:\n" 15487 " int x = 0;\n" 15488 "}", 15489 CtorInitializerStyle); 15490 verifyFormat("switch (x) {\n" 15491 "case 1:\n" 15492 "default:\n" 15493 "}", 15494 CtorInitializerStyle); 15495 verifyFormat("switch (allBraces) {\n" 15496 "case 1: {\n" 15497 " break;\n" 15498 "}\n" 15499 "case 2: {\n" 15500 " [[fallthrough]];\n" 15501 "}\n" 15502 "default: {\n" 15503 " break;\n" 15504 "}\n" 15505 "}", 15506 CtorInitializerStyle); 15507 CtorInitializerStyle.BreakConstructorInitializers = 15508 FormatStyle::BCIS_AfterColon; 15509 verifyFormat("Fooooooooooo::Fooooooooooo():\n" 15510 " aaaaaaaaaaaaaaaa(1),\n" 15511 " bbbbbbbbbbbbbbbb(2) {}", 15512 CtorInitializerStyle); 15513 CtorInitializerStyle.BreakConstructorInitializers = 15514 FormatStyle::BCIS_BeforeComma; 15515 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15516 " : aaaaaaaaaaaaaaaa(1)\n" 15517 " , bbbbbbbbbbbbbbbb(2) {}", 15518 CtorInitializerStyle); 15519 CtorInitializerStyle.BreakConstructorInitializers = 15520 FormatStyle::BCIS_BeforeColon; 15521 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15522 " : aaaaaaaaaaaaaaaa(1),\n" 15523 " bbbbbbbbbbbbbbbb(2) {}", 15524 CtorInitializerStyle); 15525 CtorInitializerStyle.ConstructorInitializerIndentWidth = 0; 15526 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 15527 ": aaaaaaaaaaaaaaaa(1),\n" 15528 " bbbbbbbbbbbbbbbb(2) {}", 15529 CtorInitializerStyle); 15530 15531 FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30); 15532 InheritanceStyle.SpaceBeforeInheritanceColon = false; 15533 verifyFormat("class Foo: public Bar {};", InheritanceStyle); 15534 verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle); 15535 verifyFormat("for (auto a : b) {\n}", InheritanceStyle); 15536 verifyFormat("int x = a ? b : c;", InheritanceStyle); 15537 verifyFormat("{\n" 15538 "label2:\n" 15539 " int x = 0;\n" 15540 "}", 15541 InheritanceStyle); 15542 verifyFormat("switch (x) {\n" 15543 "case 1:\n" 15544 "default:\n" 15545 "}", 15546 InheritanceStyle); 15547 verifyFormat("switch (allBraces) {\n" 15548 "case 1: {\n" 15549 " break;\n" 15550 "}\n" 15551 "case 2: {\n" 15552 " [[fallthrough]];\n" 15553 "}\n" 15554 "default: {\n" 15555 " break;\n" 15556 "}\n" 15557 "}", 15558 InheritanceStyle); 15559 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterComma; 15560 verifyFormat("class Foooooooooooooooooooooo\n" 15561 " : public aaaaaaaaaaaaaaaaaa,\n" 15562 " public bbbbbbbbbbbbbbbbbb {\n" 15563 "}", 15564 InheritanceStyle); 15565 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon; 15566 verifyFormat("class Foooooooooooooooooooooo:\n" 15567 " public aaaaaaaaaaaaaaaaaa,\n" 15568 " public bbbbbbbbbbbbbbbbbb {\n" 15569 "}", 15570 InheritanceStyle); 15571 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma; 15572 verifyFormat("class Foooooooooooooooooooooo\n" 15573 " : public aaaaaaaaaaaaaaaaaa\n" 15574 " , public bbbbbbbbbbbbbbbbbb {\n" 15575 "}", 15576 InheritanceStyle); 15577 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 15578 verifyFormat("class Foooooooooooooooooooooo\n" 15579 " : public aaaaaaaaaaaaaaaaaa,\n" 15580 " public bbbbbbbbbbbbbbbbbb {\n" 15581 "}", 15582 InheritanceStyle); 15583 InheritanceStyle.ConstructorInitializerIndentWidth = 0; 15584 verifyFormat("class Foooooooooooooooooooooo\n" 15585 ": public aaaaaaaaaaaaaaaaaa,\n" 15586 " public bbbbbbbbbbbbbbbbbb {}", 15587 InheritanceStyle); 15588 15589 FormatStyle ForLoopStyle = getLLVMStyle(); 15590 ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false; 15591 verifyFormat("class Foo : public Bar {};", ForLoopStyle); 15592 verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle); 15593 verifyFormat("for (auto a: b) {\n}", ForLoopStyle); 15594 verifyFormat("int x = a ? b : c;", ForLoopStyle); 15595 verifyFormat("{\n" 15596 "label2:\n" 15597 " int x = 0;\n" 15598 "}", 15599 ForLoopStyle); 15600 verifyFormat("switch (x) {\n" 15601 "case 1:\n" 15602 "default:\n" 15603 "}", 15604 ForLoopStyle); 15605 verifyFormat("switch (allBraces) {\n" 15606 "case 1: {\n" 15607 " break;\n" 15608 "}\n" 15609 "case 2: {\n" 15610 " [[fallthrough]];\n" 15611 "}\n" 15612 "default: {\n" 15613 " break;\n" 15614 "}\n" 15615 "}", 15616 ForLoopStyle); 15617 15618 FormatStyle CaseStyle = getLLVMStyle(); 15619 CaseStyle.SpaceBeforeCaseColon = true; 15620 verifyFormat("class Foo : public Bar {};", CaseStyle); 15621 verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle); 15622 verifyFormat("for (auto a : b) {\n}", CaseStyle); 15623 verifyFormat("int x = a ? b : c;", CaseStyle); 15624 verifyFormat("switch (x) {\n" 15625 "case 1 :\n" 15626 "default :\n" 15627 "}", 15628 CaseStyle); 15629 verifyFormat("switch (allBraces) {\n" 15630 "case 1 : {\n" 15631 " break;\n" 15632 "}\n" 15633 "case 2 : {\n" 15634 " [[fallthrough]];\n" 15635 "}\n" 15636 "default : {\n" 15637 " break;\n" 15638 "}\n" 15639 "}", 15640 CaseStyle); 15641 15642 FormatStyle NoSpaceStyle = getLLVMStyle(); 15643 EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false); 15644 NoSpaceStyle.SpaceBeforeCtorInitializerColon = false; 15645 NoSpaceStyle.SpaceBeforeInheritanceColon = false; 15646 NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false; 15647 verifyFormat("class Foo: public Bar {};", NoSpaceStyle); 15648 verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle); 15649 verifyFormat("for (auto a: b) {\n}", NoSpaceStyle); 15650 verifyFormat("int x = a ? b : c;", NoSpaceStyle); 15651 verifyFormat("{\n" 15652 "label3:\n" 15653 " int x = 0;\n" 15654 "}", 15655 NoSpaceStyle); 15656 verifyFormat("switch (x) {\n" 15657 "case 1:\n" 15658 "default:\n" 15659 "}", 15660 NoSpaceStyle); 15661 verifyFormat("switch (allBraces) {\n" 15662 "case 1: {\n" 15663 " break;\n" 15664 "}\n" 15665 "case 2: {\n" 15666 " [[fallthrough]];\n" 15667 "}\n" 15668 "default: {\n" 15669 " break;\n" 15670 "}\n" 15671 "}", 15672 NoSpaceStyle); 15673 15674 FormatStyle InvertedSpaceStyle = getLLVMStyle(); 15675 InvertedSpaceStyle.SpaceBeforeCaseColon = true; 15676 InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false; 15677 InvertedSpaceStyle.SpaceBeforeInheritanceColon = false; 15678 InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false; 15679 verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle); 15680 verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle); 15681 verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle); 15682 verifyFormat("int x = a ? b : c;", InvertedSpaceStyle); 15683 verifyFormat("{\n" 15684 "label3:\n" 15685 " int x = 0;\n" 15686 "}", 15687 InvertedSpaceStyle); 15688 verifyFormat("switch (x) {\n" 15689 "case 1 :\n" 15690 "case 2 : {\n" 15691 " break;\n" 15692 "}\n" 15693 "default :\n" 15694 " break;\n" 15695 "}", 15696 InvertedSpaceStyle); 15697 verifyFormat("switch (allBraces) {\n" 15698 "case 1 : {\n" 15699 " break;\n" 15700 "}\n" 15701 "case 2 : {\n" 15702 " [[fallthrough]];\n" 15703 "}\n" 15704 "default : {\n" 15705 " break;\n" 15706 "}\n" 15707 "}", 15708 InvertedSpaceStyle); 15709 } 15710 15711 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) { 15712 FormatStyle Style = getLLVMStyle(); 15713 15714 Style.PointerAlignment = FormatStyle::PAS_Left; 15715 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default; 15716 verifyFormat("void* const* x = NULL;", Style); 15717 15718 #define verifyQualifierSpaces(Code, Pointers, Qualifiers) \ 15719 do { \ 15720 Style.PointerAlignment = FormatStyle::Pointers; \ 15721 Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers; \ 15722 verifyFormat(Code, Style); \ 15723 } while (false) 15724 15725 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default); 15726 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default); 15727 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default); 15728 15729 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before); 15730 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before); 15731 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before); 15732 15733 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After); 15734 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After); 15735 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After); 15736 15737 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both); 15738 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both); 15739 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both); 15740 15741 verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default); 15742 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, 15743 SAPQ_Default); 15744 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15745 SAPQ_Default); 15746 15747 verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before); 15748 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, 15749 SAPQ_Before); 15750 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15751 SAPQ_Before); 15752 15753 verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After); 15754 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After); 15755 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15756 SAPQ_After); 15757 15758 verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both); 15759 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both); 15760 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both); 15761 15762 #undef verifyQualifierSpaces 15763 15764 FormatStyle Spaces = getLLVMStyle(); 15765 Spaces.AttributeMacros.push_back("qualified"); 15766 Spaces.PointerAlignment = FormatStyle::PAS_Right; 15767 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default; 15768 verifyFormat("SomeType *volatile *a = NULL;", Spaces); 15769 verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces); 15770 verifyFormat("std::vector<SomeType *const *> x;", Spaces); 15771 verifyFormat("std::vector<SomeType *qualified *> x;", Spaces); 15772 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15773 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before; 15774 verifyFormat("SomeType * volatile *a = NULL;", Spaces); 15775 verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces); 15776 verifyFormat("std::vector<SomeType * const *> x;", Spaces); 15777 verifyFormat("std::vector<SomeType * qualified *> x;", Spaces); 15778 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15779 15780 // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left. 15781 Spaces.PointerAlignment = FormatStyle::PAS_Left; 15782 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before; 15783 verifyFormat("SomeType* volatile* a = NULL;", Spaces); 15784 verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces); 15785 verifyFormat("std::vector<SomeType* const*> x;", Spaces); 15786 verifyFormat("std::vector<SomeType* qualified*> x;", Spaces); 15787 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15788 // However, setting it to SAPQ_After should add spaces after __attribute, etc. 15789 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After; 15790 verifyFormat("SomeType* volatile * a = NULL;", Spaces); 15791 verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces); 15792 verifyFormat("std::vector<SomeType* const *> x;", Spaces); 15793 verifyFormat("std::vector<SomeType* qualified *> x;", Spaces); 15794 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15795 15796 // PAS_Middle should not have any noticeable changes even for SAPQ_Both 15797 Spaces.PointerAlignment = FormatStyle::PAS_Middle; 15798 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After; 15799 verifyFormat("SomeType * volatile * a = NULL;", Spaces); 15800 verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces); 15801 verifyFormat("std::vector<SomeType * const *> x;", Spaces); 15802 verifyFormat("std::vector<SomeType * qualified *> x;", Spaces); 15803 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15804 } 15805 15806 TEST_F(FormatTest, AlignConsecutiveMacros) { 15807 FormatStyle Style = getLLVMStyle(); 15808 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 15809 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 15810 Style.AlignConsecutiveMacros = FormatStyle::ACS_None; 15811 15812 verifyFormat("#define a 3\n" 15813 "#define bbbb 4\n" 15814 "#define ccc (5)", 15815 Style); 15816 15817 verifyFormat("#define f(x) (x * x)\n" 15818 "#define fff(x, y, z) (x * y + z)\n" 15819 "#define ffff(x, y) (x - y)", 15820 Style); 15821 15822 verifyFormat("#define foo(x, y) (x + y)\n" 15823 "#define bar (5, 6)(2 + 2)", 15824 Style); 15825 15826 verifyFormat("#define a 3\n" 15827 "#define bbbb 4\n" 15828 "#define ccc (5)\n" 15829 "#define f(x) (x * x)\n" 15830 "#define fff(x, y, z) (x * y + z)\n" 15831 "#define ffff(x, y) (x - y)", 15832 Style); 15833 15834 Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 15835 verifyFormat("#define a 3\n" 15836 "#define bbbb 4\n" 15837 "#define ccc (5)", 15838 Style); 15839 15840 verifyFormat("#define f(x) (x * x)\n" 15841 "#define fff(x, y, z) (x * y + z)\n" 15842 "#define ffff(x, y) (x - y)", 15843 Style); 15844 15845 verifyFormat("#define foo(x, y) (x + y)\n" 15846 "#define bar (5, 6)(2 + 2)", 15847 Style); 15848 15849 verifyFormat("#define a 3\n" 15850 "#define bbbb 4\n" 15851 "#define ccc (5)\n" 15852 "#define f(x) (x * x)\n" 15853 "#define fff(x, y, z) (x * y + z)\n" 15854 "#define ffff(x, y) (x - y)", 15855 Style); 15856 15857 verifyFormat("#define a 5\n" 15858 "#define foo(x, y) (x + y)\n" 15859 "#define CCC (6)\n" 15860 "auto lambda = []() {\n" 15861 " auto ii = 0;\n" 15862 " float j = 0;\n" 15863 " return 0;\n" 15864 "};\n" 15865 "int i = 0;\n" 15866 "float i2 = 0;\n" 15867 "auto v = type{\n" 15868 " i = 1, //\n" 15869 " (i = 2), //\n" 15870 " i = 3 //\n" 15871 "};", 15872 Style); 15873 15874 Style.AlignConsecutiveMacros = FormatStyle::ACS_None; 15875 Style.ColumnLimit = 20; 15876 15877 verifyFormat("#define a \\\n" 15878 " \"aabbbbbbbbbbbb\"\n" 15879 "#define D \\\n" 15880 " \"aabbbbbbbbbbbb\" \\\n" 15881 " \"ccddeeeeeeeee\"\n" 15882 "#define B \\\n" 15883 " \"QQQQQQQQQQQQQ\" \\\n" 15884 " \"FFFFFFFFFFFFF\" \\\n" 15885 " \"LLLLLLLL\"\n", 15886 Style); 15887 15888 Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 15889 verifyFormat("#define a \\\n" 15890 " \"aabbbbbbbbbbbb\"\n" 15891 "#define D \\\n" 15892 " \"aabbbbbbbbbbbb\" \\\n" 15893 " \"ccddeeeeeeeee\"\n" 15894 "#define B \\\n" 15895 " \"QQQQQQQQQQQQQ\" \\\n" 15896 " \"FFFFFFFFFFFFF\" \\\n" 15897 " \"LLLLLLLL\"\n", 15898 Style); 15899 15900 // Test across comments 15901 Style.MaxEmptyLinesToKeep = 10; 15902 Style.ReflowComments = false; 15903 Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossComments; 15904 EXPECT_EQ("#define a 3\n" 15905 "// line comment\n" 15906 "#define bbbb 4\n" 15907 "#define ccc (5)", 15908 format("#define a 3\n" 15909 "// line comment\n" 15910 "#define bbbb 4\n" 15911 "#define ccc (5)", 15912 Style)); 15913 15914 EXPECT_EQ("#define a 3\n" 15915 "/* block comment */\n" 15916 "#define bbbb 4\n" 15917 "#define ccc (5)", 15918 format("#define a 3\n" 15919 "/* block comment */\n" 15920 "#define bbbb 4\n" 15921 "#define ccc (5)", 15922 Style)); 15923 15924 EXPECT_EQ("#define a 3\n" 15925 "/* multi-line *\n" 15926 " * block comment */\n" 15927 "#define bbbb 4\n" 15928 "#define ccc (5)", 15929 format("#define a 3\n" 15930 "/* multi-line *\n" 15931 " * block comment */\n" 15932 "#define bbbb 4\n" 15933 "#define ccc (5)", 15934 Style)); 15935 15936 EXPECT_EQ("#define a 3\n" 15937 "// multi-line line comment\n" 15938 "//\n" 15939 "#define bbbb 4\n" 15940 "#define ccc (5)", 15941 format("#define a 3\n" 15942 "// multi-line line comment\n" 15943 "//\n" 15944 "#define bbbb 4\n" 15945 "#define ccc (5)", 15946 Style)); 15947 15948 EXPECT_EQ("#define a 3\n" 15949 "// empty lines still break.\n" 15950 "\n" 15951 "#define bbbb 4\n" 15952 "#define ccc (5)", 15953 format("#define a 3\n" 15954 "// empty lines still break.\n" 15955 "\n" 15956 "#define bbbb 4\n" 15957 "#define ccc (5)", 15958 Style)); 15959 15960 // Test across empty lines 15961 Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLines; 15962 EXPECT_EQ("#define a 3\n" 15963 "\n" 15964 "#define bbbb 4\n" 15965 "#define ccc (5)", 15966 format("#define a 3\n" 15967 "\n" 15968 "#define bbbb 4\n" 15969 "#define ccc (5)", 15970 Style)); 15971 15972 EXPECT_EQ("#define a 3\n" 15973 "\n" 15974 "\n" 15975 "\n" 15976 "#define bbbb 4\n" 15977 "#define ccc (5)", 15978 format("#define a 3\n" 15979 "\n" 15980 "\n" 15981 "\n" 15982 "#define bbbb 4\n" 15983 "#define ccc (5)", 15984 Style)); 15985 15986 EXPECT_EQ("#define a 3\n" 15987 "// comments should break alignment\n" 15988 "//\n" 15989 "#define bbbb 4\n" 15990 "#define ccc (5)", 15991 format("#define a 3\n" 15992 "// comments should break alignment\n" 15993 "//\n" 15994 "#define bbbb 4\n" 15995 "#define ccc (5)", 15996 Style)); 15997 15998 // Test across empty lines and comments 15999 Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLinesAndComments; 16000 verifyFormat("#define a 3\n" 16001 "\n" 16002 "// line comment\n" 16003 "#define bbbb 4\n" 16004 "#define ccc (5)", 16005 Style); 16006 16007 EXPECT_EQ("#define a 3\n" 16008 "\n" 16009 "\n" 16010 "/* multi-line *\n" 16011 " * block comment */\n" 16012 "\n" 16013 "\n" 16014 "#define bbbb 4\n" 16015 "#define ccc (5)", 16016 format("#define a 3\n" 16017 "\n" 16018 "\n" 16019 "/* multi-line *\n" 16020 " * block comment */\n" 16021 "\n" 16022 "\n" 16023 "#define bbbb 4\n" 16024 "#define ccc (5)", 16025 Style)); 16026 16027 EXPECT_EQ("#define a 3\n" 16028 "\n" 16029 "\n" 16030 "/* multi-line *\n" 16031 " * block comment */\n" 16032 "\n" 16033 "\n" 16034 "#define bbbb 4\n" 16035 "#define ccc (5)", 16036 format("#define a 3\n" 16037 "\n" 16038 "\n" 16039 "/* multi-line *\n" 16040 " * block comment */\n" 16041 "\n" 16042 "\n" 16043 "#define bbbb 4\n" 16044 "#define ccc (5)", 16045 Style)); 16046 } 16047 16048 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) { 16049 FormatStyle Alignment = getLLVMStyle(); 16050 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 16051 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossEmptyLines; 16052 16053 Alignment.MaxEmptyLinesToKeep = 10; 16054 /* Test alignment across empty lines */ 16055 EXPECT_EQ("int a = 5;\n" 16056 "\n" 16057 "int oneTwoThree = 123;", 16058 format("int a = 5;\n" 16059 "\n" 16060 "int oneTwoThree= 123;", 16061 Alignment)); 16062 EXPECT_EQ("int a = 5;\n" 16063 "int one = 1;\n" 16064 "\n" 16065 "int oneTwoThree = 123;", 16066 format("int a = 5;\n" 16067 "int one = 1;\n" 16068 "\n" 16069 "int oneTwoThree = 123;", 16070 Alignment)); 16071 EXPECT_EQ("int a = 5;\n" 16072 "int one = 1;\n" 16073 "\n" 16074 "int oneTwoThree = 123;\n" 16075 "int oneTwo = 12;", 16076 format("int a = 5;\n" 16077 "int one = 1;\n" 16078 "\n" 16079 "int oneTwoThree = 123;\n" 16080 "int oneTwo = 12;", 16081 Alignment)); 16082 16083 /* Test across comments */ 16084 EXPECT_EQ("int a = 5;\n" 16085 "/* block comment */\n" 16086 "int oneTwoThree = 123;", 16087 format("int a = 5;\n" 16088 "/* block comment */\n" 16089 "int oneTwoThree=123;", 16090 Alignment)); 16091 16092 EXPECT_EQ("int a = 5;\n" 16093 "// line comment\n" 16094 "int oneTwoThree = 123;", 16095 format("int a = 5;\n" 16096 "// line comment\n" 16097 "int oneTwoThree=123;", 16098 Alignment)); 16099 16100 /* Test across comments and newlines */ 16101 EXPECT_EQ("int a = 5;\n" 16102 "\n" 16103 "/* block comment */\n" 16104 "int oneTwoThree = 123;", 16105 format("int a = 5;\n" 16106 "\n" 16107 "/* block comment */\n" 16108 "int oneTwoThree=123;", 16109 Alignment)); 16110 16111 EXPECT_EQ("int a = 5;\n" 16112 "\n" 16113 "// line comment\n" 16114 "int oneTwoThree = 123;", 16115 format("int a = 5;\n" 16116 "\n" 16117 "// line comment\n" 16118 "int oneTwoThree=123;", 16119 Alignment)); 16120 } 16121 16122 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) { 16123 FormatStyle Alignment = getLLVMStyle(); 16124 Alignment.AlignConsecutiveDeclarations = 16125 FormatStyle::ACS_AcrossEmptyLinesAndComments; 16126 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 16127 16128 Alignment.MaxEmptyLinesToKeep = 10; 16129 /* Test alignment across empty lines */ 16130 EXPECT_EQ("int a = 5;\n" 16131 "\n" 16132 "float const oneTwoThree = 123;", 16133 format("int a = 5;\n" 16134 "\n" 16135 "float const oneTwoThree = 123;", 16136 Alignment)); 16137 EXPECT_EQ("int a = 5;\n" 16138 "float const one = 1;\n" 16139 "\n" 16140 "int oneTwoThree = 123;", 16141 format("int a = 5;\n" 16142 "float const one = 1;\n" 16143 "\n" 16144 "int oneTwoThree = 123;", 16145 Alignment)); 16146 16147 /* Test across comments */ 16148 EXPECT_EQ("float const a = 5;\n" 16149 "/* block comment */\n" 16150 "int oneTwoThree = 123;", 16151 format("float const a = 5;\n" 16152 "/* block comment */\n" 16153 "int oneTwoThree=123;", 16154 Alignment)); 16155 16156 EXPECT_EQ("float const a = 5;\n" 16157 "// line comment\n" 16158 "int oneTwoThree = 123;", 16159 format("float const a = 5;\n" 16160 "// line comment\n" 16161 "int oneTwoThree=123;", 16162 Alignment)); 16163 16164 /* Test across comments and newlines */ 16165 EXPECT_EQ("float const a = 5;\n" 16166 "\n" 16167 "/* block comment */\n" 16168 "int oneTwoThree = 123;", 16169 format("float const a = 5;\n" 16170 "\n" 16171 "/* block comment */\n" 16172 "int oneTwoThree=123;", 16173 Alignment)); 16174 16175 EXPECT_EQ("float const a = 5;\n" 16176 "\n" 16177 "// line comment\n" 16178 "int oneTwoThree = 123;", 16179 format("float const a = 5;\n" 16180 "\n" 16181 "// line comment\n" 16182 "int oneTwoThree=123;", 16183 Alignment)); 16184 } 16185 16186 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) { 16187 FormatStyle Alignment = getLLVMStyle(); 16188 Alignment.AlignConsecutiveBitFields = 16189 FormatStyle::ACS_AcrossEmptyLinesAndComments; 16190 16191 Alignment.MaxEmptyLinesToKeep = 10; 16192 /* Test alignment across empty lines */ 16193 EXPECT_EQ("int a : 5;\n" 16194 "\n" 16195 "int longbitfield : 6;", 16196 format("int a : 5;\n" 16197 "\n" 16198 "int longbitfield : 6;", 16199 Alignment)); 16200 EXPECT_EQ("int a : 5;\n" 16201 "int one : 1;\n" 16202 "\n" 16203 "int longbitfield : 6;", 16204 format("int a : 5;\n" 16205 "int one : 1;\n" 16206 "\n" 16207 "int longbitfield : 6;", 16208 Alignment)); 16209 16210 /* Test across comments */ 16211 EXPECT_EQ("int a : 5;\n" 16212 "/* block comment */\n" 16213 "int longbitfield : 6;", 16214 format("int a : 5;\n" 16215 "/* block comment */\n" 16216 "int longbitfield : 6;", 16217 Alignment)); 16218 EXPECT_EQ("int a : 5;\n" 16219 "int one : 1;\n" 16220 "// line comment\n" 16221 "int longbitfield : 6;", 16222 format("int a : 5;\n" 16223 "int one : 1;\n" 16224 "// line comment\n" 16225 "int longbitfield : 6;", 16226 Alignment)); 16227 16228 /* Test across comments and newlines */ 16229 EXPECT_EQ("int a : 5;\n" 16230 "/* block comment */\n" 16231 "\n" 16232 "int longbitfield : 6;", 16233 format("int a : 5;\n" 16234 "/* block comment */\n" 16235 "\n" 16236 "int longbitfield : 6;", 16237 Alignment)); 16238 EXPECT_EQ("int a : 5;\n" 16239 "int one : 1;\n" 16240 "\n" 16241 "// line comment\n" 16242 "\n" 16243 "int longbitfield : 6;", 16244 format("int a : 5;\n" 16245 "int one : 1;\n" 16246 "\n" 16247 "// line comment \n" 16248 "\n" 16249 "int longbitfield : 6;", 16250 Alignment)); 16251 } 16252 16253 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) { 16254 FormatStyle Alignment = getLLVMStyle(); 16255 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 16256 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossComments; 16257 16258 Alignment.MaxEmptyLinesToKeep = 10; 16259 /* Test alignment across empty lines */ 16260 EXPECT_EQ("int a = 5;\n" 16261 "\n" 16262 "int oneTwoThree = 123;", 16263 format("int a = 5;\n" 16264 "\n" 16265 "int oneTwoThree= 123;", 16266 Alignment)); 16267 EXPECT_EQ("int a = 5;\n" 16268 "int one = 1;\n" 16269 "\n" 16270 "int oneTwoThree = 123;", 16271 format("int a = 5;\n" 16272 "int one = 1;\n" 16273 "\n" 16274 "int oneTwoThree = 123;", 16275 Alignment)); 16276 16277 /* Test across comments */ 16278 EXPECT_EQ("int a = 5;\n" 16279 "/* block comment */\n" 16280 "int oneTwoThree = 123;", 16281 format("int a = 5;\n" 16282 "/* block comment */\n" 16283 "int oneTwoThree=123;", 16284 Alignment)); 16285 16286 EXPECT_EQ("int a = 5;\n" 16287 "// line comment\n" 16288 "int oneTwoThree = 123;", 16289 format("int a = 5;\n" 16290 "// line comment\n" 16291 "int oneTwoThree=123;", 16292 Alignment)); 16293 16294 EXPECT_EQ("int a = 5;\n" 16295 "/*\n" 16296 " * multi-line block comment\n" 16297 " */\n" 16298 "int oneTwoThree = 123;", 16299 format("int a = 5;\n" 16300 "/*\n" 16301 " * multi-line block comment\n" 16302 " */\n" 16303 "int oneTwoThree=123;", 16304 Alignment)); 16305 16306 EXPECT_EQ("int a = 5;\n" 16307 "//\n" 16308 "// multi-line line comment\n" 16309 "//\n" 16310 "int oneTwoThree = 123;", 16311 format("int a = 5;\n" 16312 "//\n" 16313 "// multi-line line comment\n" 16314 "//\n" 16315 "int oneTwoThree=123;", 16316 Alignment)); 16317 16318 /* Test across comments and newlines */ 16319 EXPECT_EQ("int a = 5;\n" 16320 "\n" 16321 "/* block comment */\n" 16322 "int oneTwoThree = 123;", 16323 format("int a = 5;\n" 16324 "\n" 16325 "/* block comment */\n" 16326 "int oneTwoThree=123;", 16327 Alignment)); 16328 16329 EXPECT_EQ("int a = 5;\n" 16330 "\n" 16331 "// line comment\n" 16332 "int oneTwoThree = 123;", 16333 format("int a = 5;\n" 16334 "\n" 16335 "// line comment\n" 16336 "int oneTwoThree=123;", 16337 Alignment)); 16338 } 16339 16340 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) { 16341 FormatStyle Alignment = getLLVMStyle(); 16342 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 16343 Alignment.AlignConsecutiveAssignments = 16344 FormatStyle::ACS_AcrossEmptyLinesAndComments; 16345 verifyFormat("int a = 5;\n" 16346 "int oneTwoThree = 123;", 16347 Alignment); 16348 verifyFormat("int a = method();\n" 16349 "int oneTwoThree = 133;", 16350 Alignment); 16351 verifyFormat("a &= 5;\n" 16352 "bcd *= 5;\n" 16353 "ghtyf += 5;\n" 16354 "dvfvdb -= 5;\n" 16355 "a /= 5;\n" 16356 "vdsvsv %= 5;\n" 16357 "sfdbddfbdfbb ^= 5;\n" 16358 "dvsdsv |= 5;\n" 16359 "int dsvvdvsdvvv = 123;", 16360 Alignment); 16361 verifyFormat("int i = 1, j = 10;\n" 16362 "something = 2000;", 16363 Alignment); 16364 verifyFormat("something = 2000;\n" 16365 "int i = 1, j = 10;\n", 16366 Alignment); 16367 verifyFormat("something = 2000;\n" 16368 "another = 911;\n" 16369 "int i = 1, j = 10;\n" 16370 "oneMore = 1;\n" 16371 "i = 2;", 16372 Alignment); 16373 verifyFormat("int a = 5;\n" 16374 "int one = 1;\n" 16375 "method();\n" 16376 "int oneTwoThree = 123;\n" 16377 "int oneTwo = 12;", 16378 Alignment); 16379 verifyFormat("int oneTwoThree = 123;\n" 16380 "int oneTwo = 12;\n" 16381 "method();\n", 16382 Alignment); 16383 verifyFormat("int oneTwoThree = 123; // comment\n" 16384 "int oneTwo = 12; // comment", 16385 Alignment); 16386 16387 // Bug 25167 16388 /* Uncomment when fixed 16389 verifyFormat("#if A\n" 16390 "#else\n" 16391 "int aaaaaaaa = 12;\n" 16392 "#endif\n" 16393 "#if B\n" 16394 "#else\n" 16395 "int a = 12;\n" 16396 "#endif\n", 16397 Alignment); 16398 verifyFormat("enum foo {\n" 16399 "#if A\n" 16400 "#else\n" 16401 " aaaaaaaa = 12;\n" 16402 "#endif\n" 16403 "#if B\n" 16404 "#else\n" 16405 " a = 12;\n" 16406 "#endif\n" 16407 "};\n", 16408 Alignment); 16409 */ 16410 16411 Alignment.MaxEmptyLinesToKeep = 10; 16412 /* Test alignment across empty lines */ 16413 EXPECT_EQ("int a = 5;\n" 16414 "\n" 16415 "int oneTwoThree = 123;", 16416 format("int a = 5;\n" 16417 "\n" 16418 "int oneTwoThree= 123;", 16419 Alignment)); 16420 EXPECT_EQ("int a = 5;\n" 16421 "int one = 1;\n" 16422 "\n" 16423 "int oneTwoThree = 123;", 16424 format("int a = 5;\n" 16425 "int one = 1;\n" 16426 "\n" 16427 "int oneTwoThree = 123;", 16428 Alignment)); 16429 EXPECT_EQ("int a = 5;\n" 16430 "int one = 1;\n" 16431 "\n" 16432 "int oneTwoThree = 123;\n" 16433 "int oneTwo = 12;", 16434 format("int a = 5;\n" 16435 "int one = 1;\n" 16436 "\n" 16437 "int oneTwoThree = 123;\n" 16438 "int oneTwo = 12;", 16439 Alignment)); 16440 16441 /* Test across comments */ 16442 EXPECT_EQ("int a = 5;\n" 16443 "/* block comment */\n" 16444 "int oneTwoThree = 123;", 16445 format("int a = 5;\n" 16446 "/* block comment */\n" 16447 "int oneTwoThree=123;", 16448 Alignment)); 16449 16450 EXPECT_EQ("int a = 5;\n" 16451 "// line comment\n" 16452 "int oneTwoThree = 123;", 16453 format("int a = 5;\n" 16454 "// line comment\n" 16455 "int oneTwoThree=123;", 16456 Alignment)); 16457 16458 /* Test across comments and newlines */ 16459 EXPECT_EQ("int a = 5;\n" 16460 "\n" 16461 "/* block comment */\n" 16462 "int oneTwoThree = 123;", 16463 format("int a = 5;\n" 16464 "\n" 16465 "/* block comment */\n" 16466 "int oneTwoThree=123;", 16467 Alignment)); 16468 16469 EXPECT_EQ("int a = 5;\n" 16470 "\n" 16471 "// line comment\n" 16472 "int oneTwoThree = 123;", 16473 format("int a = 5;\n" 16474 "\n" 16475 "// line comment\n" 16476 "int oneTwoThree=123;", 16477 Alignment)); 16478 16479 EXPECT_EQ("int a = 5;\n" 16480 "//\n" 16481 "// multi-line line comment\n" 16482 "//\n" 16483 "int oneTwoThree = 123;", 16484 format("int a = 5;\n" 16485 "//\n" 16486 "// multi-line line comment\n" 16487 "//\n" 16488 "int oneTwoThree=123;", 16489 Alignment)); 16490 16491 EXPECT_EQ("int a = 5;\n" 16492 "/*\n" 16493 " * multi-line block comment\n" 16494 " */\n" 16495 "int oneTwoThree = 123;", 16496 format("int a = 5;\n" 16497 "/*\n" 16498 " * multi-line block comment\n" 16499 " */\n" 16500 "int oneTwoThree=123;", 16501 Alignment)); 16502 16503 EXPECT_EQ("int a = 5;\n" 16504 "\n" 16505 "/* block comment */\n" 16506 "\n" 16507 "\n" 16508 "\n" 16509 "int oneTwoThree = 123;", 16510 format("int a = 5;\n" 16511 "\n" 16512 "/* block comment */\n" 16513 "\n" 16514 "\n" 16515 "\n" 16516 "int oneTwoThree=123;", 16517 Alignment)); 16518 16519 EXPECT_EQ("int a = 5;\n" 16520 "\n" 16521 "// line comment\n" 16522 "\n" 16523 "\n" 16524 "\n" 16525 "int oneTwoThree = 123;", 16526 format("int a = 5;\n" 16527 "\n" 16528 "// line comment\n" 16529 "\n" 16530 "\n" 16531 "\n" 16532 "int oneTwoThree=123;", 16533 Alignment)); 16534 16535 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 16536 verifyFormat("#define A \\\n" 16537 " int aaaa = 12; \\\n" 16538 " int b = 23; \\\n" 16539 " int ccc = 234; \\\n" 16540 " int dddddddddd = 2345;", 16541 Alignment); 16542 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 16543 verifyFormat("#define A \\\n" 16544 " int aaaa = 12; \\\n" 16545 " int b = 23; \\\n" 16546 " int ccc = 234; \\\n" 16547 " int dddddddddd = 2345;", 16548 Alignment); 16549 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 16550 verifyFormat("#define A " 16551 " \\\n" 16552 " int aaaa = 12; " 16553 " \\\n" 16554 " int b = 23; " 16555 " \\\n" 16556 " int ccc = 234; " 16557 " \\\n" 16558 " int dddddddddd = 2345;", 16559 Alignment); 16560 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 16561 "k = 4, int l = 5,\n" 16562 " int m = 6) {\n" 16563 " int j = 10;\n" 16564 " otherThing = 1;\n" 16565 "}", 16566 Alignment); 16567 verifyFormat("void SomeFunction(int parameter = 0) {\n" 16568 " int i = 1;\n" 16569 " int j = 2;\n" 16570 " int big = 10000;\n" 16571 "}", 16572 Alignment); 16573 verifyFormat("class C {\n" 16574 "public:\n" 16575 " int i = 1;\n" 16576 " virtual void f() = 0;\n" 16577 "};", 16578 Alignment); 16579 verifyFormat("int i = 1;\n" 16580 "if (SomeType t = getSomething()) {\n" 16581 "}\n" 16582 "int j = 2;\n" 16583 "int big = 10000;", 16584 Alignment); 16585 verifyFormat("int j = 7;\n" 16586 "for (int k = 0; k < N; ++k) {\n" 16587 "}\n" 16588 "int j = 2;\n" 16589 "int big = 10000;\n" 16590 "}", 16591 Alignment); 16592 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 16593 verifyFormat("int i = 1;\n" 16594 "LooooooooooongType loooooooooooooooooooooongVariable\n" 16595 " = someLooooooooooooooooongFunction();\n" 16596 "int j = 2;", 16597 Alignment); 16598 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 16599 verifyFormat("int i = 1;\n" 16600 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 16601 " someLooooooooooooooooongFunction();\n" 16602 "int j = 2;", 16603 Alignment); 16604 16605 verifyFormat("auto lambda = []() {\n" 16606 " auto i = 0;\n" 16607 " return 0;\n" 16608 "};\n" 16609 "int i = 0;\n" 16610 "auto v = type{\n" 16611 " i = 1, //\n" 16612 " (i = 2), //\n" 16613 " i = 3 //\n" 16614 "};", 16615 Alignment); 16616 16617 verifyFormat( 16618 "int i = 1;\n" 16619 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 16620 " loooooooooooooooooooooongParameterB);\n" 16621 "int j = 2;", 16622 Alignment); 16623 16624 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n" 16625 " typename B = very_long_type_name_1,\n" 16626 " typename T_2 = very_long_type_name_2>\n" 16627 "auto foo() {}\n", 16628 Alignment); 16629 verifyFormat("int a, b = 1;\n" 16630 "int c = 2;\n" 16631 "int dd = 3;\n", 16632 Alignment); 16633 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 16634 "float b[1][] = {{3.f}};\n", 16635 Alignment); 16636 verifyFormat("for (int i = 0; i < 1; i++)\n" 16637 " int x = 1;\n", 16638 Alignment); 16639 verifyFormat("for (i = 0; i < 1; i++)\n" 16640 " x = 1;\n" 16641 "y = 1;\n", 16642 Alignment); 16643 16644 Alignment.ReflowComments = true; 16645 Alignment.ColumnLimit = 50; 16646 EXPECT_EQ("int x = 0;\n" 16647 "int yy = 1; /// specificlennospace\n" 16648 "int zzz = 2;\n", 16649 format("int x = 0;\n" 16650 "int yy = 1; ///specificlennospace\n" 16651 "int zzz = 2;\n", 16652 Alignment)); 16653 } 16654 16655 TEST_F(FormatTest, AlignConsecutiveAssignments) { 16656 FormatStyle Alignment = getLLVMStyle(); 16657 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 16658 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 16659 verifyFormat("int a = 5;\n" 16660 "int oneTwoThree = 123;", 16661 Alignment); 16662 verifyFormat("int a = 5;\n" 16663 "int oneTwoThree = 123;", 16664 Alignment); 16665 16666 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 16667 verifyFormat("int a = 5;\n" 16668 "int oneTwoThree = 123;", 16669 Alignment); 16670 verifyFormat("int a = method();\n" 16671 "int oneTwoThree = 133;", 16672 Alignment); 16673 verifyFormat("a &= 5;\n" 16674 "bcd *= 5;\n" 16675 "ghtyf += 5;\n" 16676 "dvfvdb -= 5;\n" 16677 "a /= 5;\n" 16678 "vdsvsv %= 5;\n" 16679 "sfdbddfbdfbb ^= 5;\n" 16680 "dvsdsv |= 5;\n" 16681 "int dsvvdvsdvvv = 123;", 16682 Alignment); 16683 verifyFormat("int i = 1, j = 10;\n" 16684 "something = 2000;", 16685 Alignment); 16686 verifyFormat("something = 2000;\n" 16687 "int i = 1, j = 10;\n", 16688 Alignment); 16689 verifyFormat("something = 2000;\n" 16690 "another = 911;\n" 16691 "int i = 1, j = 10;\n" 16692 "oneMore = 1;\n" 16693 "i = 2;", 16694 Alignment); 16695 verifyFormat("int a = 5;\n" 16696 "int one = 1;\n" 16697 "method();\n" 16698 "int oneTwoThree = 123;\n" 16699 "int oneTwo = 12;", 16700 Alignment); 16701 verifyFormat("int oneTwoThree = 123;\n" 16702 "int oneTwo = 12;\n" 16703 "method();\n", 16704 Alignment); 16705 verifyFormat("int oneTwoThree = 123; // comment\n" 16706 "int oneTwo = 12; // comment", 16707 Alignment); 16708 verifyFormat("int f() = default;\n" 16709 "int &operator() = default;\n" 16710 "int &operator=() {", 16711 Alignment); 16712 verifyFormat("int f() = delete;\n" 16713 "int &operator() = delete;\n" 16714 "int &operator=() {", 16715 Alignment); 16716 verifyFormat("int f() = default; // comment\n" 16717 "int &operator() = default; // comment\n" 16718 "int &operator=() {", 16719 Alignment); 16720 verifyFormat("int f() = default;\n" 16721 "int &operator() = default;\n" 16722 "int &operator==() {", 16723 Alignment); 16724 verifyFormat("int f() = default;\n" 16725 "int &operator() = default;\n" 16726 "int &operator<=() {", 16727 Alignment); 16728 verifyFormat("int f() = default;\n" 16729 "int &operator() = default;\n" 16730 "int &operator!=() {", 16731 Alignment); 16732 verifyFormat("int f() = default;\n" 16733 "int &operator() = default;\n" 16734 "int &operator=();", 16735 Alignment); 16736 verifyFormat("int f() = delete;\n" 16737 "int &operator() = delete;\n" 16738 "int &operator=();", 16739 Alignment); 16740 verifyFormat("/* long long padding */ int f() = default;\n" 16741 "int &operator() = default;\n" 16742 "int &operator/**/ =();", 16743 Alignment); 16744 // https://llvm.org/PR33697 16745 FormatStyle AlignmentWithPenalty = getLLVMStyle(); 16746 AlignmentWithPenalty.AlignConsecutiveAssignments = 16747 FormatStyle::ACS_Consecutive; 16748 AlignmentWithPenalty.PenaltyReturnTypeOnItsOwnLine = 5000; 16749 verifyFormat("class SSSSSSSSSSSSSSSSSSSSSSSSSSSS {\n" 16750 " void f() = delete;\n" 16751 " SSSSSSSSSSSSSSSSSSSSSSSSSSSS &operator=(\n" 16752 " const SSSSSSSSSSSSSSSSSSSSSSSSSSSS &other) = delete;\n" 16753 "};\n", 16754 AlignmentWithPenalty); 16755 16756 // Bug 25167 16757 /* Uncomment when fixed 16758 verifyFormat("#if A\n" 16759 "#else\n" 16760 "int aaaaaaaa = 12;\n" 16761 "#endif\n" 16762 "#if B\n" 16763 "#else\n" 16764 "int a = 12;\n" 16765 "#endif\n", 16766 Alignment); 16767 verifyFormat("enum foo {\n" 16768 "#if A\n" 16769 "#else\n" 16770 " aaaaaaaa = 12;\n" 16771 "#endif\n" 16772 "#if B\n" 16773 "#else\n" 16774 " a = 12;\n" 16775 "#endif\n" 16776 "};\n", 16777 Alignment); 16778 */ 16779 16780 EXPECT_EQ("int a = 5;\n" 16781 "\n" 16782 "int oneTwoThree = 123;", 16783 format("int a = 5;\n" 16784 "\n" 16785 "int oneTwoThree= 123;", 16786 Alignment)); 16787 EXPECT_EQ("int a = 5;\n" 16788 "int one = 1;\n" 16789 "\n" 16790 "int oneTwoThree = 123;", 16791 format("int a = 5;\n" 16792 "int one = 1;\n" 16793 "\n" 16794 "int oneTwoThree = 123;", 16795 Alignment)); 16796 EXPECT_EQ("int a = 5;\n" 16797 "int one = 1;\n" 16798 "\n" 16799 "int oneTwoThree = 123;\n" 16800 "int oneTwo = 12;", 16801 format("int a = 5;\n" 16802 "int one = 1;\n" 16803 "\n" 16804 "int oneTwoThree = 123;\n" 16805 "int oneTwo = 12;", 16806 Alignment)); 16807 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 16808 verifyFormat("#define A \\\n" 16809 " int aaaa = 12; \\\n" 16810 " int b = 23; \\\n" 16811 " int ccc = 234; \\\n" 16812 " int dddddddddd = 2345;", 16813 Alignment); 16814 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 16815 verifyFormat("#define A \\\n" 16816 " int aaaa = 12; \\\n" 16817 " int b = 23; \\\n" 16818 " int ccc = 234; \\\n" 16819 " int dddddddddd = 2345;", 16820 Alignment); 16821 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 16822 verifyFormat("#define A " 16823 " \\\n" 16824 " int aaaa = 12; " 16825 " \\\n" 16826 " int b = 23; " 16827 " \\\n" 16828 " int ccc = 234; " 16829 " \\\n" 16830 " int dddddddddd = 2345;", 16831 Alignment); 16832 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 16833 "k = 4, int l = 5,\n" 16834 " int m = 6) {\n" 16835 " int j = 10;\n" 16836 " otherThing = 1;\n" 16837 "}", 16838 Alignment); 16839 verifyFormat("void SomeFunction(int parameter = 0) {\n" 16840 " int i = 1;\n" 16841 " int j = 2;\n" 16842 " int big = 10000;\n" 16843 "}", 16844 Alignment); 16845 verifyFormat("class C {\n" 16846 "public:\n" 16847 " int i = 1;\n" 16848 " virtual void f() = 0;\n" 16849 "};", 16850 Alignment); 16851 verifyFormat("int i = 1;\n" 16852 "if (SomeType t = getSomething()) {\n" 16853 "}\n" 16854 "int j = 2;\n" 16855 "int big = 10000;", 16856 Alignment); 16857 verifyFormat("int j = 7;\n" 16858 "for (int k = 0; k < N; ++k) {\n" 16859 "}\n" 16860 "int j = 2;\n" 16861 "int big = 10000;\n" 16862 "}", 16863 Alignment); 16864 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 16865 verifyFormat("int i = 1;\n" 16866 "LooooooooooongType loooooooooooooooooooooongVariable\n" 16867 " = someLooooooooooooooooongFunction();\n" 16868 "int j = 2;", 16869 Alignment); 16870 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 16871 verifyFormat("int i = 1;\n" 16872 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 16873 " someLooooooooooooooooongFunction();\n" 16874 "int j = 2;", 16875 Alignment); 16876 16877 verifyFormat("auto lambda = []() {\n" 16878 " auto i = 0;\n" 16879 " return 0;\n" 16880 "};\n" 16881 "int i = 0;\n" 16882 "auto v = type{\n" 16883 " i = 1, //\n" 16884 " (i = 2), //\n" 16885 " i = 3 //\n" 16886 "};", 16887 Alignment); 16888 16889 verifyFormat( 16890 "int i = 1;\n" 16891 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 16892 " loooooooooooooooooooooongParameterB);\n" 16893 "int j = 2;", 16894 Alignment); 16895 16896 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n" 16897 " typename B = very_long_type_name_1,\n" 16898 " typename T_2 = very_long_type_name_2>\n" 16899 "auto foo() {}\n", 16900 Alignment); 16901 verifyFormat("int a, b = 1;\n" 16902 "int c = 2;\n" 16903 "int dd = 3;\n", 16904 Alignment); 16905 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 16906 "float b[1][] = {{3.f}};\n", 16907 Alignment); 16908 verifyFormat("for (int i = 0; i < 1; i++)\n" 16909 " int x = 1;\n", 16910 Alignment); 16911 verifyFormat("for (i = 0; i < 1; i++)\n" 16912 " x = 1;\n" 16913 "y = 1;\n", 16914 Alignment); 16915 16916 EXPECT_EQ(Alignment.ReflowComments, true); 16917 Alignment.ColumnLimit = 50; 16918 EXPECT_EQ("int x = 0;\n" 16919 "int yy = 1; /// specificlennospace\n" 16920 "int zzz = 2;\n", 16921 format("int x = 0;\n" 16922 "int yy = 1; ///specificlennospace\n" 16923 "int zzz = 2;\n", 16924 Alignment)); 16925 16926 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 16927 "auto b = [] {\n" 16928 " f();\n" 16929 " return;\n" 16930 "};", 16931 Alignment); 16932 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 16933 "auto b = g([] {\n" 16934 " f();\n" 16935 " return;\n" 16936 "});", 16937 Alignment); 16938 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 16939 "auto b = g(param, [] {\n" 16940 " f();\n" 16941 " return;\n" 16942 "});", 16943 Alignment); 16944 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n" 16945 "auto b = [] {\n" 16946 " if (condition) {\n" 16947 " return;\n" 16948 " }\n" 16949 "};", 16950 Alignment); 16951 16952 verifyFormat("auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 16953 " ccc ? aaaaa : bbbbb,\n" 16954 " dddddddddddddddddddddddddd);", 16955 Alignment); 16956 // FIXME: https://llvm.org/PR53497 16957 // verifyFormat("auto aaaaaaaaaaaa = f();\n" 16958 // "auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 16959 // " ccc ? aaaaa : bbbbb,\n" 16960 // " dddddddddddddddddddddddddd);", 16961 // Alignment); 16962 } 16963 16964 TEST_F(FormatTest, AlignConsecutiveBitFields) { 16965 FormatStyle Alignment = getLLVMStyle(); 16966 Alignment.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive; 16967 verifyFormat("int const a : 5;\n" 16968 "int oneTwoThree : 23;", 16969 Alignment); 16970 16971 // Initializers are allowed starting with c++2a 16972 verifyFormat("int const a : 5 = 1;\n" 16973 "int oneTwoThree : 23 = 0;", 16974 Alignment); 16975 16976 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 16977 verifyFormat("int const a : 5;\n" 16978 "int oneTwoThree : 23;", 16979 Alignment); 16980 16981 verifyFormat("int const a : 5; // comment\n" 16982 "int oneTwoThree : 23; // comment", 16983 Alignment); 16984 16985 verifyFormat("int const a : 5 = 1;\n" 16986 "int oneTwoThree : 23 = 0;", 16987 Alignment); 16988 16989 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 16990 verifyFormat("int const a : 5 = 1;\n" 16991 "int oneTwoThree : 23 = 0;", 16992 Alignment); 16993 verifyFormat("int const a : 5 = {1};\n" 16994 "int oneTwoThree : 23 = 0;", 16995 Alignment); 16996 16997 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None; 16998 verifyFormat("int const a :5;\n" 16999 "int oneTwoThree:23;", 17000 Alignment); 17001 17002 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before; 17003 verifyFormat("int const a :5;\n" 17004 "int oneTwoThree :23;", 17005 Alignment); 17006 17007 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After; 17008 verifyFormat("int const a : 5;\n" 17009 "int oneTwoThree: 23;", 17010 Alignment); 17011 17012 // Known limitations: ':' is only recognized as a bitfield colon when 17013 // followed by a number. 17014 /* 17015 verifyFormat("int oneTwoThree : SOME_CONSTANT;\n" 17016 "int a : 5;", 17017 Alignment); 17018 */ 17019 } 17020 17021 TEST_F(FormatTest, AlignConsecutiveDeclarations) { 17022 FormatStyle Alignment = getLLVMStyle(); 17023 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 17024 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_None; 17025 Alignment.PointerAlignment = FormatStyle::PAS_Right; 17026 verifyFormat("float const a = 5;\n" 17027 "int oneTwoThree = 123;", 17028 Alignment); 17029 verifyFormat("int a = 5;\n" 17030 "float const oneTwoThree = 123;", 17031 Alignment); 17032 17033 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17034 verifyFormat("float const a = 5;\n" 17035 "int oneTwoThree = 123;", 17036 Alignment); 17037 verifyFormat("int a = method();\n" 17038 "float const oneTwoThree = 133;", 17039 Alignment); 17040 verifyFormat("int i = 1, j = 10;\n" 17041 "something = 2000;", 17042 Alignment); 17043 verifyFormat("something = 2000;\n" 17044 "int i = 1, j = 10;\n", 17045 Alignment); 17046 verifyFormat("float something = 2000;\n" 17047 "double another = 911;\n" 17048 "int i = 1, j = 10;\n" 17049 "const int *oneMore = 1;\n" 17050 "unsigned i = 2;", 17051 Alignment); 17052 verifyFormat("float a = 5;\n" 17053 "int one = 1;\n" 17054 "method();\n" 17055 "const double oneTwoThree = 123;\n" 17056 "const unsigned int oneTwo = 12;", 17057 Alignment); 17058 verifyFormat("int oneTwoThree{0}; // comment\n" 17059 "unsigned oneTwo; // comment", 17060 Alignment); 17061 verifyFormat("unsigned int *a;\n" 17062 "int *b;\n" 17063 "unsigned int Const *c;\n" 17064 "unsigned int const *d;\n" 17065 "unsigned int Const &e;\n" 17066 "unsigned int const &f;", 17067 Alignment); 17068 verifyFormat("Const unsigned int *c;\n" 17069 "const unsigned int *d;\n" 17070 "Const unsigned int &e;\n" 17071 "const unsigned int &f;\n" 17072 "const unsigned g;\n" 17073 "Const unsigned h;", 17074 Alignment); 17075 EXPECT_EQ("float const a = 5;\n" 17076 "\n" 17077 "int oneTwoThree = 123;", 17078 format("float const a = 5;\n" 17079 "\n" 17080 "int oneTwoThree= 123;", 17081 Alignment)); 17082 EXPECT_EQ("float a = 5;\n" 17083 "int one = 1;\n" 17084 "\n" 17085 "unsigned oneTwoThree = 123;", 17086 format("float a = 5;\n" 17087 "int one = 1;\n" 17088 "\n" 17089 "unsigned oneTwoThree = 123;", 17090 Alignment)); 17091 EXPECT_EQ("float a = 5;\n" 17092 "int one = 1;\n" 17093 "\n" 17094 "unsigned oneTwoThree = 123;\n" 17095 "int oneTwo = 12;", 17096 format("float a = 5;\n" 17097 "int one = 1;\n" 17098 "\n" 17099 "unsigned oneTwoThree = 123;\n" 17100 "int oneTwo = 12;", 17101 Alignment)); 17102 // Function prototype alignment 17103 verifyFormat("int a();\n" 17104 "double b();", 17105 Alignment); 17106 verifyFormat("int a(int x);\n" 17107 "double b();", 17108 Alignment); 17109 unsigned OldColumnLimit = Alignment.ColumnLimit; 17110 // We need to set ColumnLimit to zero, in order to stress nested alignments, 17111 // otherwise the function parameters will be re-flowed onto a single line. 17112 Alignment.ColumnLimit = 0; 17113 EXPECT_EQ("int a(int x,\n" 17114 " float y);\n" 17115 "double b(int x,\n" 17116 " double y);", 17117 format("int a(int x,\n" 17118 " float y);\n" 17119 "double b(int x,\n" 17120 " double y);", 17121 Alignment)); 17122 // This ensures that function parameters of function declarations are 17123 // correctly indented when their owning functions are indented. 17124 // The failure case here is for 'double y' to not be indented enough. 17125 EXPECT_EQ("double a(int x);\n" 17126 "int b(int y,\n" 17127 " double z);", 17128 format("double a(int x);\n" 17129 "int b(int y,\n" 17130 " double z);", 17131 Alignment)); 17132 // Set ColumnLimit low so that we induce wrapping immediately after 17133 // the function name and opening paren. 17134 Alignment.ColumnLimit = 13; 17135 verifyFormat("int function(\n" 17136 " int x,\n" 17137 " bool y);", 17138 Alignment); 17139 Alignment.ColumnLimit = OldColumnLimit; 17140 // Ensure function pointers don't screw up recursive alignment 17141 verifyFormat("int a(int x, void (*fp)(int y));\n" 17142 "double b();", 17143 Alignment); 17144 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17145 // Ensure recursive alignment is broken by function braces, so that the 17146 // "a = 1" does not align with subsequent assignments inside the function 17147 // body. 17148 verifyFormat("int func(int a = 1) {\n" 17149 " int b = 2;\n" 17150 " int cc = 3;\n" 17151 "}", 17152 Alignment); 17153 verifyFormat("float something = 2000;\n" 17154 "double another = 911;\n" 17155 "int i = 1, j = 10;\n" 17156 "const int *oneMore = 1;\n" 17157 "unsigned i = 2;", 17158 Alignment); 17159 verifyFormat("int oneTwoThree = {0}; // comment\n" 17160 "unsigned oneTwo = 0; // comment", 17161 Alignment); 17162 // Make sure that scope is correctly tracked, in the absence of braces 17163 verifyFormat("for (int i = 0; i < n; i++)\n" 17164 " j = i;\n" 17165 "double x = 1;\n", 17166 Alignment); 17167 verifyFormat("if (int i = 0)\n" 17168 " j = i;\n" 17169 "double x = 1;\n", 17170 Alignment); 17171 // Ensure operator[] and operator() are comprehended 17172 verifyFormat("struct test {\n" 17173 " long long int foo();\n" 17174 " int operator[](int a);\n" 17175 " double bar();\n" 17176 "};\n", 17177 Alignment); 17178 verifyFormat("struct test {\n" 17179 " long long int foo();\n" 17180 " int operator()(int a);\n" 17181 " double bar();\n" 17182 "};\n", 17183 Alignment); 17184 // http://llvm.org/PR52914 17185 verifyFormat("char *a[] = {\"a\", // comment\n" 17186 " \"bb\"};\n" 17187 "int bbbbbbb = 0;", 17188 Alignment); 17189 17190 // PAS_Right 17191 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17192 " int const i = 1;\n" 17193 " int *j = 2;\n" 17194 " int big = 10000;\n" 17195 "\n" 17196 " unsigned oneTwoThree = 123;\n" 17197 " int oneTwo = 12;\n" 17198 " method();\n" 17199 " float k = 2;\n" 17200 " int ll = 10000;\n" 17201 "}", 17202 format("void SomeFunction(int parameter= 0) {\n" 17203 " int const i= 1;\n" 17204 " int *j=2;\n" 17205 " int big = 10000;\n" 17206 "\n" 17207 "unsigned oneTwoThree =123;\n" 17208 "int oneTwo = 12;\n" 17209 " method();\n" 17210 "float k= 2;\n" 17211 "int ll=10000;\n" 17212 "}", 17213 Alignment)); 17214 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17215 " int const i = 1;\n" 17216 " int **j = 2, ***k;\n" 17217 " int &k = i;\n" 17218 " int &&l = i + j;\n" 17219 " int big = 10000;\n" 17220 "\n" 17221 " unsigned oneTwoThree = 123;\n" 17222 " int oneTwo = 12;\n" 17223 " method();\n" 17224 " float k = 2;\n" 17225 " int ll = 10000;\n" 17226 "}", 17227 format("void SomeFunction(int parameter= 0) {\n" 17228 " int const i= 1;\n" 17229 " int **j=2,***k;\n" 17230 "int &k=i;\n" 17231 "int &&l=i+j;\n" 17232 " int big = 10000;\n" 17233 "\n" 17234 "unsigned oneTwoThree =123;\n" 17235 "int oneTwo = 12;\n" 17236 " method();\n" 17237 "float k= 2;\n" 17238 "int ll=10000;\n" 17239 "}", 17240 Alignment)); 17241 // variables are aligned at their name, pointers are at the right most 17242 // position 17243 verifyFormat("int *a;\n" 17244 "int **b;\n" 17245 "int ***c;\n" 17246 "int foobar;\n", 17247 Alignment); 17248 17249 // PAS_Left 17250 FormatStyle AlignmentLeft = Alignment; 17251 AlignmentLeft.PointerAlignment = FormatStyle::PAS_Left; 17252 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17253 " int const i = 1;\n" 17254 " int* j = 2;\n" 17255 " int big = 10000;\n" 17256 "\n" 17257 " unsigned oneTwoThree = 123;\n" 17258 " int oneTwo = 12;\n" 17259 " method();\n" 17260 " float k = 2;\n" 17261 " int ll = 10000;\n" 17262 "}", 17263 format("void SomeFunction(int parameter= 0) {\n" 17264 " int const i= 1;\n" 17265 " int *j=2;\n" 17266 " int big = 10000;\n" 17267 "\n" 17268 "unsigned oneTwoThree =123;\n" 17269 "int oneTwo = 12;\n" 17270 " method();\n" 17271 "float k= 2;\n" 17272 "int ll=10000;\n" 17273 "}", 17274 AlignmentLeft)); 17275 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17276 " int const i = 1;\n" 17277 " int** j = 2;\n" 17278 " int& k = i;\n" 17279 " int&& l = i + j;\n" 17280 " int big = 10000;\n" 17281 "\n" 17282 " unsigned oneTwoThree = 123;\n" 17283 " int oneTwo = 12;\n" 17284 " method();\n" 17285 " float k = 2;\n" 17286 " int ll = 10000;\n" 17287 "}", 17288 format("void SomeFunction(int parameter= 0) {\n" 17289 " int const i= 1;\n" 17290 " int **j=2;\n" 17291 "int &k=i;\n" 17292 "int &&l=i+j;\n" 17293 " int big = 10000;\n" 17294 "\n" 17295 "unsigned oneTwoThree =123;\n" 17296 "int oneTwo = 12;\n" 17297 " method();\n" 17298 "float k= 2;\n" 17299 "int ll=10000;\n" 17300 "}", 17301 AlignmentLeft)); 17302 // variables are aligned at their name, pointers are at the left most position 17303 verifyFormat("int* a;\n" 17304 "int** b;\n" 17305 "int*** c;\n" 17306 "int foobar;\n", 17307 AlignmentLeft); 17308 17309 // PAS_Middle 17310 FormatStyle AlignmentMiddle = Alignment; 17311 AlignmentMiddle.PointerAlignment = FormatStyle::PAS_Middle; 17312 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17313 " int const i = 1;\n" 17314 " int * j = 2;\n" 17315 " int big = 10000;\n" 17316 "\n" 17317 " unsigned oneTwoThree = 123;\n" 17318 " int oneTwo = 12;\n" 17319 " method();\n" 17320 " float k = 2;\n" 17321 " int ll = 10000;\n" 17322 "}", 17323 format("void SomeFunction(int parameter= 0) {\n" 17324 " int const i= 1;\n" 17325 " int *j=2;\n" 17326 " int big = 10000;\n" 17327 "\n" 17328 "unsigned oneTwoThree =123;\n" 17329 "int oneTwo = 12;\n" 17330 " method();\n" 17331 "float k= 2;\n" 17332 "int ll=10000;\n" 17333 "}", 17334 AlignmentMiddle)); 17335 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 17336 " int const i = 1;\n" 17337 " int ** j = 2, ***k;\n" 17338 " int & k = i;\n" 17339 " int && l = i + j;\n" 17340 " int big = 10000;\n" 17341 "\n" 17342 " unsigned oneTwoThree = 123;\n" 17343 " int oneTwo = 12;\n" 17344 " method();\n" 17345 " float k = 2;\n" 17346 " int ll = 10000;\n" 17347 "}", 17348 format("void SomeFunction(int parameter= 0) {\n" 17349 " int const i= 1;\n" 17350 " int **j=2,***k;\n" 17351 "int &k=i;\n" 17352 "int &&l=i+j;\n" 17353 " int big = 10000;\n" 17354 "\n" 17355 "unsigned oneTwoThree =123;\n" 17356 "int oneTwo = 12;\n" 17357 " method();\n" 17358 "float k= 2;\n" 17359 "int ll=10000;\n" 17360 "}", 17361 AlignmentMiddle)); 17362 // variables are aligned at their name, pointers are in the middle 17363 verifyFormat("int * a;\n" 17364 "int * b;\n" 17365 "int *** c;\n" 17366 "int foobar;\n", 17367 AlignmentMiddle); 17368 17369 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 17370 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 17371 verifyFormat("#define A \\\n" 17372 " int aaaa = 12; \\\n" 17373 " float b = 23; \\\n" 17374 " const int ccc = 234; \\\n" 17375 " unsigned dddddddddd = 2345;", 17376 Alignment); 17377 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 17378 verifyFormat("#define A \\\n" 17379 " int aaaa = 12; \\\n" 17380 " float b = 23; \\\n" 17381 " const int ccc = 234; \\\n" 17382 " unsigned dddddddddd = 2345;", 17383 Alignment); 17384 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 17385 Alignment.ColumnLimit = 30; 17386 verifyFormat("#define A \\\n" 17387 " int aaaa = 12; \\\n" 17388 " float b = 23; \\\n" 17389 " const int ccc = 234; \\\n" 17390 " int dddddddddd = 2345;", 17391 Alignment); 17392 Alignment.ColumnLimit = 80; 17393 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 17394 "k = 4, int l = 5,\n" 17395 " int m = 6) {\n" 17396 " const int j = 10;\n" 17397 " otherThing = 1;\n" 17398 "}", 17399 Alignment); 17400 verifyFormat("void SomeFunction(int parameter = 0) {\n" 17401 " int const i = 1;\n" 17402 " int *j = 2;\n" 17403 " int big = 10000;\n" 17404 "}", 17405 Alignment); 17406 verifyFormat("class C {\n" 17407 "public:\n" 17408 " int i = 1;\n" 17409 " virtual void f() = 0;\n" 17410 "};", 17411 Alignment); 17412 verifyFormat("float i = 1;\n" 17413 "if (SomeType t = getSomething()) {\n" 17414 "}\n" 17415 "const unsigned j = 2;\n" 17416 "int big = 10000;", 17417 Alignment); 17418 verifyFormat("float j = 7;\n" 17419 "for (int k = 0; k < N; ++k) {\n" 17420 "}\n" 17421 "unsigned j = 2;\n" 17422 "int big = 10000;\n" 17423 "}", 17424 Alignment); 17425 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 17426 verifyFormat("float i = 1;\n" 17427 "LooooooooooongType loooooooooooooooooooooongVariable\n" 17428 " = someLooooooooooooooooongFunction();\n" 17429 "int j = 2;", 17430 Alignment); 17431 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 17432 verifyFormat("int i = 1;\n" 17433 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 17434 " someLooooooooooooooooongFunction();\n" 17435 "int j = 2;", 17436 Alignment); 17437 17438 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17439 verifyFormat("auto lambda = []() {\n" 17440 " auto ii = 0;\n" 17441 " float j = 0;\n" 17442 " return 0;\n" 17443 "};\n" 17444 "int i = 0;\n" 17445 "float i2 = 0;\n" 17446 "auto v = type{\n" 17447 " i = 1, //\n" 17448 " (i = 2), //\n" 17449 " i = 3 //\n" 17450 "};", 17451 Alignment); 17452 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 17453 17454 verifyFormat( 17455 "int i = 1;\n" 17456 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 17457 " loooooooooooooooooooooongParameterB);\n" 17458 "int j = 2;", 17459 Alignment); 17460 17461 // Test interactions with ColumnLimit and AlignConsecutiveAssignments: 17462 // We expect declarations and assignments to align, as long as it doesn't 17463 // exceed the column limit, starting a new alignment sequence whenever it 17464 // happens. 17465 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17466 Alignment.ColumnLimit = 30; 17467 verifyFormat("float ii = 1;\n" 17468 "unsigned j = 2;\n" 17469 "int someVerylongVariable = 1;\n" 17470 "AnotherLongType ll = 123456;\n" 17471 "VeryVeryLongType k = 2;\n" 17472 "int myvar = 1;", 17473 Alignment); 17474 Alignment.ColumnLimit = 80; 17475 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 17476 17477 verifyFormat( 17478 "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n" 17479 " typename LongType, typename B>\n" 17480 "auto foo() {}\n", 17481 Alignment); 17482 verifyFormat("float a, b = 1;\n" 17483 "int c = 2;\n" 17484 "int dd = 3;\n", 17485 Alignment); 17486 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17487 "float b[1][] = {{3.f}};\n", 17488 Alignment); 17489 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17490 verifyFormat("float a, b = 1;\n" 17491 "int c = 2;\n" 17492 "int dd = 3;\n", 17493 Alignment); 17494 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 17495 "float b[1][] = {{3.f}};\n", 17496 Alignment); 17497 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 17498 17499 Alignment.ColumnLimit = 30; 17500 Alignment.BinPackParameters = false; 17501 verifyFormat("void foo(float a,\n" 17502 " float b,\n" 17503 " int c,\n" 17504 " uint32_t *d) {\n" 17505 " int *e = 0;\n" 17506 " float f = 0;\n" 17507 " double g = 0;\n" 17508 "}\n" 17509 "void bar(ino_t a,\n" 17510 " int b,\n" 17511 " uint32_t *c,\n" 17512 " bool d) {}\n", 17513 Alignment); 17514 Alignment.BinPackParameters = true; 17515 Alignment.ColumnLimit = 80; 17516 17517 // Bug 33507 17518 Alignment.PointerAlignment = FormatStyle::PAS_Middle; 17519 verifyFormat( 17520 "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n" 17521 " static const Version verVs2017;\n" 17522 " return true;\n" 17523 "});\n", 17524 Alignment); 17525 Alignment.PointerAlignment = FormatStyle::PAS_Right; 17526 17527 // See llvm.org/PR35641 17528 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17529 verifyFormat("int func() { //\n" 17530 " int b;\n" 17531 " unsigned c;\n" 17532 "}", 17533 Alignment); 17534 17535 // See PR37175 17536 FormatStyle Style = getMozillaStyle(); 17537 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17538 EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n" 17539 "foo(int a);", 17540 format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style)); 17541 17542 Alignment.PointerAlignment = FormatStyle::PAS_Left; 17543 verifyFormat("unsigned int* a;\n" 17544 "int* b;\n" 17545 "unsigned int Const* c;\n" 17546 "unsigned int const* d;\n" 17547 "unsigned int Const& e;\n" 17548 "unsigned int const& f;", 17549 Alignment); 17550 verifyFormat("Const unsigned int* c;\n" 17551 "const unsigned int* d;\n" 17552 "Const unsigned int& e;\n" 17553 "const unsigned int& f;\n" 17554 "const unsigned g;\n" 17555 "Const unsigned h;", 17556 Alignment); 17557 17558 Alignment.PointerAlignment = FormatStyle::PAS_Middle; 17559 verifyFormat("unsigned int * a;\n" 17560 "int * b;\n" 17561 "unsigned int Const * c;\n" 17562 "unsigned int const * d;\n" 17563 "unsigned int Const & e;\n" 17564 "unsigned int const & f;", 17565 Alignment); 17566 verifyFormat("Const unsigned int * c;\n" 17567 "const unsigned int * d;\n" 17568 "Const unsigned int & e;\n" 17569 "const unsigned int & f;\n" 17570 "const unsigned g;\n" 17571 "Const unsigned h;", 17572 Alignment); 17573 17574 // See PR46529 17575 FormatStyle BracedAlign = getLLVMStyle(); 17576 BracedAlign.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17577 verifyFormat("const auto result{[]() {\n" 17578 " const auto something = 1;\n" 17579 " return 2;\n" 17580 "}};", 17581 BracedAlign); 17582 verifyFormat("int foo{[]() {\n" 17583 " int bar{0};\n" 17584 " return 0;\n" 17585 "}()};", 17586 BracedAlign); 17587 BracedAlign.Cpp11BracedListStyle = false; 17588 verifyFormat("const auto result{ []() {\n" 17589 " const auto something = 1;\n" 17590 " return 2;\n" 17591 "} };", 17592 BracedAlign); 17593 verifyFormat("int foo{ []() {\n" 17594 " int bar{ 0 };\n" 17595 " return 0;\n" 17596 "}() };", 17597 BracedAlign); 17598 } 17599 17600 TEST_F(FormatTest, AlignWithLineBreaks) { 17601 auto Style = getLLVMStyleWithColumns(120); 17602 17603 EXPECT_EQ(Style.AlignConsecutiveAssignments, FormatStyle::ACS_None); 17604 EXPECT_EQ(Style.AlignConsecutiveDeclarations, FormatStyle::ACS_None); 17605 verifyFormat("void foo() {\n" 17606 " int myVar = 5;\n" 17607 " double x = 3.14;\n" 17608 " auto str = \"Hello \"\n" 17609 " \"World\";\n" 17610 " auto s = \"Hello \"\n" 17611 " \"Again\";\n" 17612 "}", 17613 Style); 17614 17615 // clang-format off 17616 verifyFormat("void foo() {\n" 17617 " const int capacityBefore = Entries.capacity();\n" 17618 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17619 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17620 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17621 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17622 "}", 17623 Style); 17624 // clang-format on 17625 17626 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17627 verifyFormat("void foo() {\n" 17628 " int myVar = 5;\n" 17629 " double x = 3.14;\n" 17630 " auto str = \"Hello \"\n" 17631 " \"World\";\n" 17632 " auto s = \"Hello \"\n" 17633 " \"Again\";\n" 17634 "}", 17635 Style); 17636 17637 // clang-format off 17638 verifyFormat("void foo() {\n" 17639 " const int capacityBefore = Entries.capacity();\n" 17640 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17641 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17642 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17643 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17644 "}", 17645 Style); 17646 // clang-format on 17647 17648 Style.AlignConsecutiveAssignments = FormatStyle::ACS_None; 17649 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17650 verifyFormat("void foo() {\n" 17651 " int myVar = 5;\n" 17652 " double x = 3.14;\n" 17653 " auto str = \"Hello \"\n" 17654 " \"World\";\n" 17655 " auto s = \"Hello \"\n" 17656 " \"Again\";\n" 17657 "}", 17658 Style); 17659 17660 // clang-format off 17661 verifyFormat("void foo() {\n" 17662 " const int capacityBefore = Entries.capacity();\n" 17663 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17664 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17665 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17666 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17667 "}", 17668 Style); 17669 // clang-format on 17670 17671 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17672 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17673 17674 verifyFormat("void foo() {\n" 17675 " int myVar = 5;\n" 17676 " double x = 3.14;\n" 17677 " auto str = \"Hello \"\n" 17678 " \"World\";\n" 17679 " auto s = \"Hello \"\n" 17680 " \"Again\";\n" 17681 "}", 17682 Style); 17683 17684 // clang-format off 17685 verifyFormat("void foo() {\n" 17686 " const int capacityBefore = Entries.capacity();\n" 17687 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17688 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17689 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 17690 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 17691 "}", 17692 Style); 17693 // clang-format on 17694 17695 Style = getLLVMStyleWithColumns(120); 17696 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17697 Style.ContinuationIndentWidth = 4; 17698 Style.IndentWidth = 4; 17699 17700 // clang-format off 17701 verifyFormat("void SomeFunc() {\n" 17702 " newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 17703 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17704 " newWatcher.maxAge = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 17705 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17706 " newWatcher.max = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 17707 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17708 "}", 17709 Style); 17710 // clang-format on 17711 17712 Style.BinPackArguments = false; 17713 17714 // clang-format off 17715 verifyFormat("void SomeFunc() {\n" 17716 " newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(\n" 17717 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17718 " newWatcher.maxAge = ToLegacyTimestamp(GetMaxAge(\n" 17719 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17720 " newWatcher.max = ToLegacyTimestamp(GetMaxAge(\n" 17721 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 17722 "}", 17723 Style); 17724 // clang-format on 17725 } 17726 17727 TEST_F(FormatTest, AlignWithInitializerPeriods) { 17728 auto Style = getLLVMStyleWithColumns(60); 17729 17730 verifyFormat("void foo1(void) {\n" 17731 " BYTE p[1] = 1;\n" 17732 " A B = {.one_foooooooooooooooo = 2,\n" 17733 " .two_fooooooooooooo = 3,\n" 17734 " .three_fooooooooooooo = 4};\n" 17735 " BYTE payload = 2;\n" 17736 "}", 17737 Style); 17738 17739 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17740 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_None; 17741 verifyFormat("void foo2(void) {\n" 17742 " BYTE p[1] = 1;\n" 17743 " A B = {.one_foooooooooooooooo = 2,\n" 17744 " .two_fooooooooooooo = 3,\n" 17745 " .three_fooooooooooooo = 4};\n" 17746 " BYTE payload = 2;\n" 17747 "}", 17748 Style); 17749 17750 Style.AlignConsecutiveAssignments = FormatStyle::ACS_None; 17751 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17752 verifyFormat("void foo3(void) {\n" 17753 " BYTE p[1] = 1;\n" 17754 " A B = {.one_foooooooooooooooo = 2,\n" 17755 " .two_fooooooooooooo = 3,\n" 17756 " .three_fooooooooooooo = 4};\n" 17757 " BYTE payload = 2;\n" 17758 "}", 17759 Style); 17760 17761 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 17762 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 17763 verifyFormat("void foo4(void) {\n" 17764 " BYTE p[1] = 1;\n" 17765 " A B = {.one_foooooooooooooooo = 2,\n" 17766 " .two_fooooooooooooo = 3,\n" 17767 " .three_fooooooooooooo = 4};\n" 17768 " BYTE payload = 2;\n" 17769 "}", 17770 Style); 17771 } 17772 17773 TEST_F(FormatTest, LinuxBraceBreaking) { 17774 FormatStyle LinuxBraceStyle = getLLVMStyle(); 17775 LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux; 17776 verifyFormat("namespace a\n" 17777 "{\n" 17778 "class A\n" 17779 "{\n" 17780 " void f()\n" 17781 " {\n" 17782 " if (true) {\n" 17783 " a();\n" 17784 " b();\n" 17785 " } else {\n" 17786 " a();\n" 17787 " }\n" 17788 " }\n" 17789 " void g() { return; }\n" 17790 "};\n" 17791 "struct B {\n" 17792 " int x;\n" 17793 "};\n" 17794 "} // namespace a\n", 17795 LinuxBraceStyle); 17796 verifyFormat("enum X {\n" 17797 " Y = 0,\n" 17798 "}\n", 17799 LinuxBraceStyle); 17800 verifyFormat("struct S {\n" 17801 " int Type;\n" 17802 " union {\n" 17803 " int x;\n" 17804 " double y;\n" 17805 " } Value;\n" 17806 " class C\n" 17807 " {\n" 17808 " MyFavoriteType Value;\n" 17809 " } Class;\n" 17810 "}\n", 17811 LinuxBraceStyle); 17812 } 17813 17814 TEST_F(FormatTest, MozillaBraceBreaking) { 17815 FormatStyle MozillaBraceStyle = getLLVMStyle(); 17816 MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla; 17817 MozillaBraceStyle.FixNamespaceComments = false; 17818 verifyFormat("namespace a {\n" 17819 "class A\n" 17820 "{\n" 17821 " void f()\n" 17822 " {\n" 17823 " if (true) {\n" 17824 " a();\n" 17825 " b();\n" 17826 " }\n" 17827 " }\n" 17828 " void g() { return; }\n" 17829 "};\n" 17830 "enum E\n" 17831 "{\n" 17832 " A,\n" 17833 " // foo\n" 17834 " B,\n" 17835 " C\n" 17836 "};\n" 17837 "struct B\n" 17838 "{\n" 17839 " int x;\n" 17840 "};\n" 17841 "}\n", 17842 MozillaBraceStyle); 17843 verifyFormat("struct S\n" 17844 "{\n" 17845 " int Type;\n" 17846 " union\n" 17847 " {\n" 17848 " int x;\n" 17849 " double y;\n" 17850 " } Value;\n" 17851 " class C\n" 17852 " {\n" 17853 " MyFavoriteType Value;\n" 17854 " } Class;\n" 17855 "}\n", 17856 MozillaBraceStyle); 17857 } 17858 17859 TEST_F(FormatTest, StroustrupBraceBreaking) { 17860 FormatStyle StroustrupBraceStyle = getLLVMStyle(); 17861 StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 17862 verifyFormat("namespace a {\n" 17863 "class A {\n" 17864 " void f()\n" 17865 " {\n" 17866 " if (true) {\n" 17867 " a();\n" 17868 " b();\n" 17869 " }\n" 17870 " }\n" 17871 " void g() { return; }\n" 17872 "};\n" 17873 "struct B {\n" 17874 " int x;\n" 17875 "};\n" 17876 "} // namespace a\n", 17877 StroustrupBraceStyle); 17878 17879 verifyFormat("void foo()\n" 17880 "{\n" 17881 " if (a) {\n" 17882 " a();\n" 17883 " }\n" 17884 " else {\n" 17885 " b();\n" 17886 " }\n" 17887 "}\n", 17888 StroustrupBraceStyle); 17889 17890 verifyFormat("#ifdef _DEBUG\n" 17891 "int foo(int i = 0)\n" 17892 "#else\n" 17893 "int foo(int i = 5)\n" 17894 "#endif\n" 17895 "{\n" 17896 " return i;\n" 17897 "}", 17898 StroustrupBraceStyle); 17899 17900 verifyFormat("void foo() {}\n" 17901 "void bar()\n" 17902 "#ifdef _DEBUG\n" 17903 "{\n" 17904 " foo();\n" 17905 "}\n" 17906 "#else\n" 17907 "{\n" 17908 "}\n" 17909 "#endif", 17910 StroustrupBraceStyle); 17911 17912 verifyFormat("void foobar() { int i = 5; }\n" 17913 "#ifdef _DEBUG\n" 17914 "void bar() {}\n" 17915 "#else\n" 17916 "void bar() { foobar(); }\n" 17917 "#endif", 17918 StroustrupBraceStyle); 17919 } 17920 17921 TEST_F(FormatTest, AllmanBraceBreaking) { 17922 FormatStyle AllmanBraceStyle = getLLVMStyle(); 17923 AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman; 17924 17925 EXPECT_EQ("namespace a\n" 17926 "{\n" 17927 "void f();\n" 17928 "void g();\n" 17929 "} // namespace a\n", 17930 format("namespace a\n" 17931 "{\n" 17932 "void f();\n" 17933 "void g();\n" 17934 "}\n", 17935 AllmanBraceStyle)); 17936 17937 verifyFormat("namespace a\n" 17938 "{\n" 17939 "class A\n" 17940 "{\n" 17941 " void f()\n" 17942 " {\n" 17943 " if (true)\n" 17944 " {\n" 17945 " a();\n" 17946 " b();\n" 17947 " }\n" 17948 " }\n" 17949 " void g() { return; }\n" 17950 "};\n" 17951 "struct B\n" 17952 "{\n" 17953 " int x;\n" 17954 "};\n" 17955 "union C\n" 17956 "{\n" 17957 "};\n" 17958 "} // namespace a", 17959 AllmanBraceStyle); 17960 17961 verifyFormat("void f()\n" 17962 "{\n" 17963 " if (true)\n" 17964 " {\n" 17965 " a();\n" 17966 " }\n" 17967 " else if (false)\n" 17968 " {\n" 17969 " b();\n" 17970 " }\n" 17971 " else\n" 17972 " {\n" 17973 " c();\n" 17974 " }\n" 17975 "}\n", 17976 AllmanBraceStyle); 17977 17978 verifyFormat("void f()\n" 17979 "{\n" 17980 " for (int i = 0; i < 10; ++i)\n" 17981 " {\n" 17982 " a();\n" 17983 " }\n" 17984 " while (false)\n" 17985 " {\n" 17986 " b();\n" 17987 " }\n" 17988 " do\n" 17989 " {\n" 17990 " c();\n" 17991 " } while (false)\n" 17992 "}\n", 17993 AllmanBraceStyle); 17994 17995 verifyFormat("void f(int a)\n" 17996 "{\n" 17997 " switch (a)\n" 17998 " {\n" 17999 " case 0:\n" 18000 " break;\n" 18001 " case 1:\n" 18002 " {\n" 18003 " break;\n" 18004 " }\n" 18005 " case 2:\n" 18006 " {\n" 18007 " }\n" 18008 " break;\n" 18009 " default:\n" 18010 " break;\n" 18011 " }\n" 18012 "}\n", 18013 AllmanBraceStyle); 18014 18015 verifyFormat("enum X\n" 18016 "{\n" 18017 " Y = 0,\n" 18018 "}\n", 18019 AllmanBraceStyle); 18020 verifyFormat("enum X\n" 18021 "{\n" 18022 " Y = 0\n" 18023 "}\n", 18024 AllmanBraceStyle); 18025 18026 verifyFormat("@interface BSApplicationController ()\n" 18027 "{\n" 18028 "@private\n" 18029 " id _extraIvar;\n" 18030 "}\n" 18031 "@end\n", 18032 AllmanBraceStyle); 18033 18034 verifyFormat("#ifdef _DEBUG\n" 18035 "int foo(int i = 0)\n" 18036 "#else\n" 18037 "int foo(int i = 5)\n" 18038 "#endif\n" 18039 "{\n" 18040 " return i;\n" 18041 "}", 18042 AllmanBraceStyle); 18043 18044 verifyFormat("void foo() {}\n" 18045 "void bar()\n" 18046 "#ifdef _DEBUG\n" 18047 "{\n" 18048 " foo();\n" 18049 "}\n" 18050 "#else\n" 18051 "{\n" 18052 "}\n" 18053 "#endif", 18054 AllmanBraceStyle); 18055 18056 verifyFormat("void foobar() { int i = 5; }\n" 18057 "#ifdef _DEBUG\n" 18058 "void bar() {}\n" 18059 "#else\n" 18060 "void bar() { foobar(); }\n" 18061 "#endif", 18062 AllmanBraceStyle); 18063 18064 EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine, 18065 FormatStyle::SLS_All); 18066 18067 verifyFormat("[](int i) { return i + 2; };\n" 18068 "[](int i, int j)\n" 18069 "{\n" 18070 " auto x = i + j;\n" 18071 " auto y = i * j;\n" 18072 " return x ^ y;\n" 18073 "};\n" 18074 "void foo()\n" 18075 "{\n" 18076 " auto shortLambda = [](int i) { return i + 2; };\n" 18077 " auto longLambda = [](int i, int j)\n" 18078 " {\n" 18079 " auto x = i + j;\n" 18080 " auto y = i * j;\n" 18081 " return x ^ y;\n" 18082 " };\n" 18083 "}", 18084 AllmanBraceStyle); 18085 18086 AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 18087 18088 verifyFormat("[](int i)\n" 18089 "{\n" 18090 " return i + 2;\n" 18091 "};\n" 18092 "[](int i, int j)\n" 18093 "{\n" 18094 " auto x = i + j;\n" 18095 " auto y = i * j;\n" 18096 " return x ^ y;\n" 18097 "};\n" 18098 "void foo()\n" 18099 "{\n" 18100 " auto shortLambda = [](int i)\n" 18101 " {\n" 18102 " return i + 2;\n" 18103 " };\n" 18104 " auto longLambda = [](int i, int j)\n" 18105 " {\n" 18106 " auto x = i + j;\n" 18107 " auto y = i * j;\n" 18108 " return x ^ y;\n" 18109 " };\n" 18110 "}", 18111 AllmanBraceStyle); 18112 18113 // Reset 18114 AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All; 18115 18116 // This shouldn't affect ObjC blocks.. 18117 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n" 18118 " // ...\n" 18119 " int i;\n" 18120 "}];", 18121 AllmanBraceStyle); 18122 verifyFormat("void (^block)(void) = ^{\n" 18123 " // ...\n" 18124 " int i;\n" 18125 "};", 18126 AllmanBraceStyle); 18127 // .. or dict literals. 18128 verifyFormat("void f()\n" 18129 "{\n" 18130 " // ...\n" 18131 " [object someMethod:@{@\"a\" : @\"b\"}];\n" 18132 "}", 18133 AllmanBraceStyle); 18134 verifyFormat("void f()\n" 18135 "{\n" 18136 " // ...\n" 18137 " [object someMethod:@{a : @\"b\"}];\n" 18138 "}", 18139 AllmanBraceStyle); 18140 verifyFormat("int f()\n" 18141 "{ // comment\n" 18142 " return 42;\n" 18143 "}", 18144 AllmanBraceStyle); 18145 18146 AllmanBraceStyle.ColumnLimit = 19; 18147 verifyFormat("void f() { int i; }", AllmanBraceStyle); 18148 AllmanBraceStyle.ColumnLimit = 18; 18149 verifyFormat("void f()\n" 18150 "{\n" 18151 " int i;\n" 18152 "}", 18153 AllmanBraceStyle); 18154 AllmanBraceStyle.ColumnLimit = 80; 18155 18156 FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle; 18157 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = 18158 FormatStyle::SIS_WithoutElse; 18159 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true; 18160 verifyFormat("void f(bool b)\n" 18161 "{\n" 18162 " if (b)\n" 18163 " {\n" 18164 " return;\n" 18165 " }\n" 18166 "}\n", 18167 BreakBeforeBraceShortIfs); 18168 verifyFormat("void f(bool b)\n" 18169 "{\n" 18170 " if constexpr (b)\n" 18171 " {\n" 18172 " return;\n" 18173 " }\n" 18174 "}\n", 18175 BreakBeforeBraceShortIfs); 18176 verifyFormat("void f(bool b)\n" 18177 "{\n" 18178 " if CONSTEXPR (b)\n" 18179 " {\n" 18180 " return;\n" 18181 " }\n" 18182 "}\n", 18183 BreakBeforeBraceShortIfs); 18184 verifyFormat("void f(bool b)\n" 18185 "{\n" 18186 " if (b) return;\n" 18187 "}\n", 18188 BreakBeforeBraceShortIfs); 18189 verifyFormat("void f(bool b)\n" 18190 "{\n" 18191 " if constexpr (b) return;\n" 18192 "}\n", 18193 BreakBeforeBraceShortIfs); 18194 verifyFormat("void f(bool b)\n" 18195 "{\n" 18196 " if CONSTEXPR (b) return;\n" 18197 "}\n", 18198 BreakBeforeBraceShortIfs); 18199 verifyFormat("void f(bool b)\n" 18200 "{\n" 18201 " while (b)\n" 18202 " {\n" 18203 " return;\n" 18204 " }\n" 18205 "}\n", 18206 BreakBeforeBraceShortIfs); 18207 } 18208 18209 TEST_F(FormatTest, WhitesmithsBraceBreaking) { 18210 FormatStyle WhitesmithsBraceStyle = getLLVMStyleWithColumns(0); 18211 WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 18212 18213 // Make a few changes to the style for testing purposes 18214 WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine = 18215 FormatStyle::SFS_Empty; 18216 WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 18217 18218 // FIXME: this test case can't decide whether there should be a blank line 18219 // after the ~D() line or not. It adds one if one doesn't exist in the test 18220 // and it removes the line if one exists. 18221 /* 18222 verifyFormat("class A;\n" 18223 "namespace B\n" 18224 " {\n" 18225 "class C;\n" 18226 "// Comment\n" 18227 "class D\n" 18228 " {\n" 18229 "public:\n" 18230 " D();\n" 18231 " ~D() {}\n" 18232 "private:\n" 18233 " enum E\n" 18234 " {\n" 18235 " F\n" 18236 " }\n" 18237 " };\n" 18238 " } // namespace B\n", 18239 WhitesmithsBraceStyle); 18240 */ 18241 18242 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None; 18243 verifyFormat("namespace a\n" 18244 " {\n" 18245 "class A\n" 18246 " {\n" 18247 " void f()\n" 18248 " {\n" 18249 " if (true)\n" 18250 " {\n" 18251 " a();\n" 18252 " b();\n" 18253 " }\n" 18254 " }\n" 18255 " void g()\n" 18256 " {\n" 18257 " return;\n" 18258 " }\n" 18259 " };\n" 18260 "struct B\n" 18261 " {\n" 18262 " int x;\n" 18263 " };\n" 18264 " } // namespace a", 18265 WhitesmithsBraceStyle); 18266 18267 verifyFormat("namespace a\n" 18268 " {\n" 18269 "namespace b\n" 18270 " {\n" 18271 "class A\n" 18272 " {\n" 18273 " void f()\n" 18274 " {\n" 18275 " if (true)\n" 18276 " {\n" 18277 " a();\n" 18278 " b();\n" 18279 " }\n" 18280 " }\n" 18281 " void g()\n" 18282 " {\n" 18283 " return;\n" 18284 " }\n" 18285 " };\n" 18286 "struct B\n" 18287 " {\n" 18288 " int x;\n" 18289 " };\n" 18290 " } // namespace b\n" 18291 " } // namespace a", 18292 WhitesmithsBraceStyle); 18293 18294 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner; 18295 verifyFormat("namespace a\n" 18296 " {\n" 18297 "namespace b\n" 18298 " {\n" 18299 " class A\n" 18300 " {\n" 18301 " void f()\n" 18302 " {\n" 18303 " if (true)\n" 18304 " {\n" 18305 " a();\n" 18306 " b();\n" 18307 " }\n" 18308 " }\n" 18309 " void g()\n" 18310 " {\n" 18311 " return;\n" 18312 " }\n" 18313 " };\n" 18314 " struct B\n" 18315 " {\n" 18316 " int x;\n" 18317 " };\n" 18318 " } // namespace b\n" 18319 " } // namespace a", 18320 WhitesmithsBraceStyle); 18321 18322 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All; 18323 verifyFormat("namespace a\n" 18324 " {\n" 18325 " namespace b\n" 18326 " {\n" 18327 " class A\n" 18328 " {\n" 18329 " void f()\n" 18330 " {\n" 18331 " if (true)\n" 18332 " {\n" 18333 " a();\n" 18334 " b();\n" 18335 " }\n" 18336 " }\n" 18337 " void g()\n" 18338 " {\n" 18339 " return;\n" 18340 " }\n" 18341 " };\n" 18342 " struct B\n" 18343 " {\n" 18344 " int x;\n" 18345 " };\n" 18346 " } // namespace b\n" 18347 " } // namespace a", 18348 WhitesmithsBraceStyle); 18349 18350 verifyFormat("void f()\n" 18351 " {\n" 18352 " if (true)\n" 18353 " {\n" 18354 " a();\n" 18355 " }\n" 18356 " else if (false)\n" 18357 " {\n" 18358 " b();\n" 18359 " }\n" 18360 " else\n" 18361 " {\n" 18362 " c();\n" 18363 " }\n" 18364 " }\n", 18365 WhitesmithsBraceStyle); 18366 18367 verifyFormat("void f()\n" 18368 " {\n" 18369 " for (int i = 0; i < 10; ++i)\n" 18370 " {\n" 18371 " a();\n" 18372 " }\n" 18373 " while (false)\n" 18374 " {\n" 18375 " b();\n" 18376 " }\n" 18377 " do\n" 18378 " {\n" 18379 " c();\n" 18380 " } while (false)\n" 18381 " }\n", 18382 WhitesmithsBraceStyle); 18383 18384 WhitesmithsBraceStyle.IndentCaseLabels = true; 18385 verifyFormat("void switchTest1(int a)\n" 18386 " {\n" 18387 " switch (a)\n" 18388 " {\n" 18389 " case 2:\n" 18390 " {\n" 18391 " }\n" 18392 " break;\n" 18393 " }\n" 18394 " }\n", 18395 WhitesmithsBraceStyle); 18396 18397 verifyFormat("void switchTest2(int a)\n" 18398 " {\n" 18399 " switch (a)\n" 18400 " {\n" 18401 " case 0:\n" 18402 " break;\n" 18403 " case 1:\n" 18404 " {\n" 18405 " break;\n" 18406 " }\n" 18407 " case 2:\n" 18408 " {\n" 18409 " }\n" 18410 " break;\n" 18411 " default:\n" 18412 " break;\n" 18413 " }\n" 18414 " }\n", 18415 WhitesmithsBraceStyle); 18416 18417 verifyFormat("void switchTest3(int a)\n" 18418 " {\n" 18419 " switch (a)\n" 18420 " {\n" 18421 " case 0:\n" 18422 " {\n" 18423 " foo(x);\n" 18424 " }\n" 18425 " break;\n" 18426 " default:\n" 18427 " {\n" 18428 " foo(1);\n" 18429 " }\n" 18430 " break;\n" 18431 " }\n" 18432 " }\n", 18433 WhitesmithsBraceStyle); 18434 18435 WhitesmithsBraceStyle.IndentCaseLabels = false; 18436 18437 verifyFormat("void switchTest4(int a)\n" 18438 " {\n" 18439 " switch (a)\n" 18440 " {\n" 18441 " case 2:\n" 18442 " {\n" 18443 " }\n" 18444 " break;\n" 18445 " }\n" 18446 " }\n", 18447 WhitesmithsBraceStyle); 18448 18449 verifyFormat("void switchTest5(int a)\n" 18450 " {\n" 18451 " switch (a)\n" 18452 " {\n" 18453 " case 0:\n" 18454 " break;\n" 18455 " case 1:\n" 18456 " {\n" 18457 " foo();\n" 18458 " break;\n" 18459 " }\n" 18460 " case 2:\n" 18461 " {\n" 18462 " }\n" 18463 " break;\n" 18464 " default:\n" 18465 " break;\n" 18466 " }\n" 18467 " }\n", 18468 WhitesmithsBraceStyle); 18469 18470 verifyFormat("void switchTest6(int a)\n" 18471 " {\n" 18472 " switch (a)\n" 18473 " {\n" 18474 " case 0:\n" 18475 " {\n" 18476 " foo(x);\n" 18477 " }\n" 18478 " break;\n" 18479 " default:\n" 18480 " {\n" 18481 " foo(1);\n" 18482 " }\n" 18483 " break;\n" 18484 " }\n" 18485 " }\n", 18486 WhitesmithsBraceStyle); 18487 18488 verifyFormat("enum X\n" 18489 " {\n" 18490 " Y = 0, // testing\n" 18491 " }\n", 18492 WhitesmithsBraceStyle); 18493 18494 verifyFormat("enum X\n" 18495 " {\n" 18496 " Y = 0\n" 18497 " }\n", 18498 WhitesmithsBraceStyle); 18499 verifyFormat("enum X\n" 18500 " {\n" 18501 " Y = 0,\n" 18502 " Z = 1\n" 18503 " };\n", 18504 WhitesmithsBraceStyle); 18505 18506 verifyFormat("@interface BSApplicationController ()\n" 18507 " {\n" 18508 "@private\n" 18509 " id _extraIvar;\n" 18510 " }\n" 18511 "@end\n", 18512 WhitesmithsBraceStyle); 18513 18514 verifyFormat("#ifdef _DEBUG\n" 18515 "int foo(int i = 0)\n" 18516 "#else\n" 18517 "int foo(int i = 5)\n" 18518 "#endif\n" 18519 " {\n" 18520 " return i;\n" 18521 " }", 18522 WhitesmithsBraceStyle); 18523 18524 verifyFormat("void foo() {}\n" 18525 "void bar()\n" 18526 "#ifdef _DEBUG\n" 18527 " {\n" 18528 " foo();\n" 18529 " }\n" 18530 "#else\n" 18531 " {\n" 18532 " }\n" 18533 "#endif", 18534 WhitesmithsBraceStyle); 18535 18536 verifyFormat("void foobar()\n" 18537 " {\n" 18538 " int i = 5;\n" 18539 " }\n" 18540 "#ifdef _DEBUG\n" 18541 "void bar()\n" 18542 " {\n" 18543 " }\n" 18544 "#else\n" 18545 "void bar()\n" 18546 " {\n" 18547 " foobar();\n" 18548 " }\n" 18549 "#endif", 18550 WhitesmithsBraceStyle); 18551 18552 // This shouldn't affect ObjC blocks.. 18553 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n" 18554 " // ...\n" 18555 " int i;\n" 18556 "}];", 18557 WhitesmithsBraceStyle); 18558 verifyFormat("void (^block)(void) = ^{\n" 18559 " // ...\n" 18560 " int i;\n" 18561 "};", 18562 WhitesmithsBraceStyle); 18563 // .. or dict literals. 18564 verifyFormat("void f()\n" 18565 " {\n" 18566 " [object someMethod:@{@\"a\" : @\"b\"}];\n" 18567 " }", 18568 WhitesmithsBraceStyle); 18569 18570 verifyFormat("int f()\n" 18571 " { // comment\n" 18572 " return 42;\n" 18573 " }", 18574 WhitesmithsBraceStyle); 18575 18576 FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle; 18577 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = 18578 FormatStyle::SIS_OnlyFirstIf; 18579 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true; 18580 verifyFormat("void f(bool b)\n" 18581 " {\n" 18582 " if (b)\n" 18583 " {\n" 18584 " return;\n" 18585 " }\n" 18586 " }\n", 18587 BreakBeforeBraceShortIfs); 18588 verifyFormat("void f(bool b)\n" 18589 " {\n" 18590 " if (b) return;\n" 18591 " }\n", 18592 BreakBeforeBraceShortIfs); 18593 verifyFormat("void f(bool b)\n" 18594 " {\n" 18595 " while (b)\n" 18596 " {\n" 18597 " return;\n" 18598 " }\n" 18599 " }\n", 18600 BreakBeforeBraceShortIfs); 18601 } 18602 18603 TEST_F(FormatTest, GNUBraceBreaking) { 18604 FormatStyle GNUBraceStyle = getLLVMStyle(); 18605 GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU; 18606 verifyFormat("namespace a\n" 18607 "{\n" 18608 "class A\n" 18609 "{\n" 18610 " void f()\n" 18611 " {\n" 18612 " int a;\n" 18613 " {\n" 18614 " int b;\n" 18615 " }\n" 18616 " if (true)\n" 18617 " {\n" 18618 " a();\n" 18619 " b();\n" 18620 " }\n" 18621 " }\n" 18622 " void g() { return; }\n" 18623 "}\n" 18624 "} // namespace a", 18625 GNUBraceStyle); 18626 18627 verifyFormat("void f()\n" 18628 "{\n" 18629 " if (true)\n" 18630 " {\n" 18631 " a();\n" 18632 " }\n" 18633 " else if (false)\n" 18634 " {\n" 18635 " b();\n" 18636 " }\n" 18637 " else\n" 18638 " {\n" 18639 " c();\n" 18640 " }\n" 18641 "}\n", 18642 GNUBraceStyle); 18643 18644 verifyFormat("void f()\n" 18645 "{\n" 18646 " for (int i = 0; i < 10; ++i)\n" 18647 " {\n" 18648 " a();\n" 18649 " }\n" 18650 " while (false)\n" 18651 " {\n" 18652 " b();\n" 18653 " }\n" 18654 " do\n" 18655 " {\n" 18656 " c();\n" 18657 " }\n" 18658 " while (false);\n" 18659 "}\n", 18660 GNUBraceStyle); 18661 18662 verifyFormat("void f(int a)\n" 18663 "{\n" 18664 " switch (a)\n" 18665 " {\n" 18666 " case 0:\n" 18667 " break;\n" 18668 " case 1:\n" 18669 " {\n" 18670 " break;\n" 18671 " }\n" 18672 " case 2:\n" 18673 " {\n" 18674 " }\n" 18675 " break;\n" 18676 " default:\n" 18677 " break;\n" 18678 " }\n" 18679 "}\n", 18680 GNUBraceStyle); 18681 18682 verifyFormat("enum X\n" 18683 "{\n" 18684 " Y = 0,\n" 18685 "}\n", 18686 GNUBraceStyle); 18687 18688 verifyFormat("@interface BSApplicationController ()\n" 18689 "{\n" 18690 "@private\n" 18691 " id _extraIvar;\n" 18692 "}\n" 18693 "@end\n", 18694 GNUBraceStyle); 18695 18696 verifyFormat("#ifdef _DEBUG\n" 18697 "int foo(int i = 0)\n" 18698 "#else\n" 18699 "int foo(int i = 5)\n" 18700 "#endif\n" 18701 "{\n" 18702 " return i;\n" 18703 "}", 18704 GNUBraceStyle); 18705 18706 verifyFormat("void foo() {}\n" 18707 "void bar()\n" 18708 "#ifdef _DEBUG\n" 18709 "{\n" 18710 " foo();\n" 18711 "}\n" 18712 "#else\n" 18713 "{\n" 18714 "}\n" 18715 "#endif", 18716 GNUBraceStyle); 18717 18718 verifyFormat("void foobar() { int i = 5; }\n" 18719 "#ifdef _DEBUG\n" 18720 "void bar() {}\n" 18721 "#else\n" 18722 "void bar() { foobar(); }\n" 18723 "#endif", 18724 GNUBraceStyle); 18725 } 18726 18727 TEST_F(FormatTest, WebKitBraceBreaking) { 18728 FormatStyle WebKitBraceStyle = getLLVMStyle(); 18729 WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit; 18730 WebKitBraceStyle.FixNamespaceComments = false; 18731 verifyFormat("namespace a {\n" 18732 "class A {\n" 18733 " void f()\n" 18734 " {\n" 18735 " if (true) {\n" 18736 " a();\n" 18737 " b();\n" 18738 " }\n" 18739 " }\n" 18740 " void g() { return; }\n" 18741 "};\n" 18742 "enum E {\n" 18743 " A,\n" 18744 " // foo\n" 18745 " B,\n" 18746 " C\n" 18747 "};\n" 18748 "struct B {\n" 18749 " int x;\n" 18750 "};\n" 18751 "}\n", 18752 WebKitBraceStyle); 18753 verifyFormat("struct S {\n" 18754 " int Type;\n" 18755 " union {\n" 18756 " int x;\n" 18757 " double y;\n" 18758 " } Value;\n" 18759 " class C {\n" 18760 " MyFavoriteType Value;\n" 18761 " } Class;\n" 18762 "};\n", 18763 WebKitBraceStyle); 18764 } 18765 18766 TEST_F(FormatTest, CatchExceptionReferenceBinding) { 18767 verifyFormat("void f() {\n" 18768 " try {\n" 18769 " } catch (const Exception &e) {\n" 18770 " }\n" 18771 "}\n", 18772 getLLVMStyle()); 18773 } 18774 18775 TEST_F(FormatTest, CatchAlignArrayOfStructuresRightAlignment) { 18776 auto Style = getLLVMStyle(); 18777 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 18778 Style.AlignConsecutiveAssignments = 18779 FormatStyle::AlignConsecutiveStyle::ACS_Consecutive; 18780 Style.AlignConsecutiveDeclarations = 18781 FormatStyle::AlignConsecutiveStyle::ACS_Consecutive; 18782 verifyFormat("struct test demo[] = {\n" 18783 " {56, 23, \"hello\"},\n" 18784 " {-1, 93463, \"world\"},\n" 18785 " { 7, 5, \"!!\"}\n" 18786 "};\n", 18787 Style); 18788 18789 verifyFormat("struct test demo[] = {\n" 18790 " {56, 23, \"hello\"}, // first line\n" 18791 " {-1, 93463, \"world\"}, // second line\n" 18792 " { 7, 5, \"!!\"} // third line\n" 18793 "};\n", 18794 Style); 18795 18796 verifyFormat("struct test demo[4] = {\n" 18797 " { 56, 23, 21, \"oh\"}, // first line\n" 18798 " { -1, 93463, 22, \"my\"}, // second line\n" 18799 " { 7, 5, 1, \"goodness\"} // third line\n" 18800 " {234, 5, 1, \"gracious\"} // fourth line\n" 18801 "};\n", 18802 Style); 18803 18804 verifyFormat("struct test demo[3] = {\n" 18805 " {56, 23, \"hello\"},\n" 18806 " {-1, 93463, \"world\"},\n" 18807 " { 7, 5, \"!!\"}\n" 18808 "};\n", 18809 Style); 18810 18811 verifyFormat("struct test demo[3] = {\n" 18812 " {int{56}, 23, \"hello\"},\n" 18813 " {int{-1}, 93463, \"world\"},\n" 18814 " { int{7}, 5, \"!!\"}\n" 18815 "};\n", 18816 Style); 18817 18818 verifyFormat("struct test demo[] = {\n" 18819 " {56, 23, \"hello\"},\n" 18820 " {-1, 93463, \"world\"},\n" 18821 " { 7, 5, \"!!\"},\n" 18822 "};\n", 18823 Style); 18824 18825 verifyFormat("test demo[] = {\n" 18826 " {56, 23, \"hello\"},\n" 18827 " {-1, 93463, \"world\"},\n" 18828 " { 7, 5, \"!!\"},\n" 18829 "};\n", 18830 Style); 18831 18832 verifyFormat("demo = std::array<struct test, 3>{\n" 18833 " test{56, 23, \"hello\"},\n" 18834 " test{-1, 93463, \"world\"},\n" 18835 " test{ 7, 5, \"!!\"},\n" 18836 "};\n", 18837 Style); 18838 18839 verifyFormat("test demo[] = {\n" 18840 " {56, 23, \"hello\"},\n" 18841 "#if X\n" 18842 " {-1, 93463, \"world\"},\n" 18843 "#endif\n" 18844 " { 7, 5, \"!!\"}\n" 18845 "};\n", 18846 Style); 18847 18848 verifyFormat( 18849 "test demo[] = {\n" 18850 " { 7, 23,\n" 18851 " \"hello world i am a very long line that really, in any\"\n" 18852 " \"just world, ought to be split over multiple lines\"},\n" 18853 " {-1, 93463, \"world\"},\n" 18854 " {56, 5, \"!!\"}\n" 18855 "};\n", 18856 Style); 18857 18858 verifyFormat("return GradForUnaryCwise(g, {\n" 18859 " {{\"sign\"}, \"Sign\", " 18860 " {\"x\", \"dy\"}},\n" 18861 " { {\"dx\"}, \"Mul\", {\"dy\"" 18862 ", \"sign\"}},\n" 18863 "});\n", 18864 Style); 18865 18866 Style.ColumnLimit = 0; 18867 EXPECT_EQ( 18868 "test demo[] = {\n" 18869 " {56, 23, \"hello world i am a very long line that really, " 18870 "in any just world, ought to be split over multiple lines\"},\n" 18871 " {-1, 93463, " 18872 " \"world\"},\n" 18873 " { 7, 5, " 18874 " \"!!\"},\n" 18875 "};", 18876 format("test demo[] = {{56, 23, \"hello world i am a very long line " 18877 "that really, in any just world, ought to be split over multiple " 18878 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 18879 Style)); 18880 18881 Style.ColumnLimit = 80; 18882 verifyFormat("test demo[] = {\n" 18883 " {56, 23, /* a comment */ \"hello\"},\n" 18884 " {-1, 93463, \"world\"},\n" 18885 " { 7, 5, \"!!\"}\n" 18886 "};\n", 18887 Style); 18888 18889 verifyFormat("test demo[] = {\n" 18890 " {56, 23, \"hello\"},\n" 18891 " {-1, 93463, \"world\" /* comment here */},\n" 18892 " { 7, 5, \"!!\"}\n" 18893 "};\n", 18894 Style); 18895 18896 verifyFormat("test demo[] = {\n" 18897 " {56, /* a comment */ 23, \"hello\"},\n" 18898 " {-1, 93463, \"world\"},\n" 18899 " { 7, 5, \"!!\"}\n" 18900 "};\n", 18901 Style); 18902 18903 Style.ColumnLimit = 20; 18904 EXPECT_EQ( 18905 "demo = std::array<\n" 18906 " struct test, 3>{\n" 18907 " test{\n" 18908 " 56, 23,\n" 18909 " \"hello \"\n" 18910 " \"world i \"\n" 18911 " \"am a very \"\n" 18912 " \"long line \"\n" 18913 " \"that \"\n" 18914 " \"really, \"\n" 18915 " \"in any \"\n" 18916 " \"just \"\n" 18917 " \"world, \"\n" 18918 " \"ought to \"\n" 18919 " \"be split \"\n" 18920 " \"over \"\n" 18921 " \"multiple \"\n" 18922 " \"lines\"},\n" 18923 " test{-1, 93463,\n" 18924 " \"world\"},\n" 18925 " test{ 7, 5,\n" 18926 " \"!!\" },\n" 18927 "};", 18928 format("demo = std::array<struct test, 3>{test{56, 23, \"hello world " 18929 "i am a very long line that really, in any just world, ought " 18930 "to be split over multiple lines\"},test{-1, 93463, \"world\"}," 18931 "test{7, 5, \"!!\"},};", 18932 Style)); 18933 // This caused a core dump by enabling Alignment in the LLVMStyle globally 18934 Style = getLLVMStyleWithColumns(50); 18935 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 18936 verifyFormat("static A x = {\n" 18937 " {{init1, init2, init3, init4},\n" 18938 " {init1, init2, init3, init4}}\n" 18939 "};", 18940 Style); 18941 Style.ColumnLimit = 100; 18942 EXPECT_EQ( 18943 "test demo[] = {\n" 18944 " {56, 23,\n" 18945 " \"hello world i am a very long line that really, in any just world" 18946 ", ought to be split over \"\n" 18947 " \"multiple lines\" },\n" 18948 " {-1, 93463, \"world\"},\n" 18949 " { 7, 5, \"!!\"},\n" 18950 "};", 18951 format("test demo[] = {{56, 23, \"hello world i am a very long line " 18952 "that really, in any just world, ought to be split over multiple " 18953 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 18954 Style)); 18955 18956 Style = getLLVMStyleWithColumns(50); 18957 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 18958 Style.AlignConsecutiveAssignments = 18959 FormatStyle::AlignConsecutiveStyle::ACS_Consecutive; 18960 Style.AlignConsecutiveDeclarations = 18961 FormatStyle::AlignConsecutiveStyle::ACS_Consecutive; 18962 verifyFormat("struct test demo[] = {\n" 18963 " {56, 23, \"hello\"},\n" 18964 " {-1, 93463, \"world\"},\n" 18965 " { 7, 5, \"!!\"}\n" 18966 "};\n" 18967 "static A x = {\n" 18968 " {{init1, init2, init3, init4},\n" 18969 " {init1, init2, init3, init4}}\n" 18970 "};", 18971 Style); 18972 Style.ColumnLimit = 100; 18973 Style.AlignConsecutiveAssignments = 18974 FormatStyle::AlignConsecutiveStyle::ACS_AcrossComments; 18975 Style.AlignConsecutiveDeclarations = 18976 FormatStyle::AlignConsecutiveStyle::ACS_AcrossComments; 18977 verifyFormat("struct test demo[] = {\n" 18978 " {56, 23, \"hello\"},\n" 18979 " {-1, 93463, \"world\"},\n" 18980 " { 7, 5, \"!!\"}\n" 18981 "};\n" 18982 "struct test demo[4] = {\n" 18983 " { 56, 23, 21, \"oh\"}, // first line\n" 18984 " { -1, 93463, 22, \"my\"}, // second line\n" 18985 " { 7, 5, 1, \"goodness\"} // third line\n" 18986 " {234, 5, 1, \"gracious\"} // fourth line\n" 18987 "};\n", 18988 Style); 18989 EXPECT_EQ( 18990 "test demo[] = {\n" 18991 " {56,\n" 18992 " \"hello world i am a very long line that really, in any just world" 18993 ", ought to be split over \"\n" 18994 " \"multiple lines\", 23},\n" 18995 " {-1, \"world\", 93463},\n" 18996 " { 7, \"!!\", 5},\n" 18997 "};", 18998 format("test demo[] = {{56, \"hello world i am a very long line " 18999 "that really, in any just world, ought to be split over multiple " 19000 "lines\", 23},{-1, \"world\", 93463},{7, \"!!\", 5},};", 19001 Style)); 19002 } 19003 19004 TEST_F(FormatTest, CatchAlignArrayOfStructuresLeftAlignment) { 19005 auto Style = getLLVMStyle(); 19006 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 19007 /* FIXME: This case gets misformatted. 19008 verifyFormat("auto foo = Items{\n" 19009 " Section{0, bar(), },\n" 19010 " Section{1, boo() }\n" 19011 "};\n", 19012 Style); 19013 */ 19014 verifyFormat("auto foo = Items{\n" 19015 " Section{\n" 19016 " 0, bar(),\n" 19017 " }\n" 19018 "};\n", 19019 Style); 19020 verifyFormat("struct test demo[] = {\n" 19021 " {56, 23, \"hello\"},\n" 19022 " {-1, 93463, \"world\"},\n" 19023 " {7, 5, \"!!\" }\n" 19024 "};\n", 19025 Style); 19026 verifyFormat("struct test demo[] = {\n" 19027 " {56, 23, \"hello\"}, // first line\n" 19028 " {-1, 93463, \"world\"}, // second line\n" 19029 " {7, 5, \"!!\" } // third line\n" 19030 "};\n", 19031 Style); 19032 verifyFormat("struct test demo[4] = {\n" 19033 " {56, 23, 21, \"oh\" }, // first line\n" 19034 " {-1, 93463, 22, \"my\" }, // second line\n" 19035 " {7, 5, 1, \"goodness\"} // third line\n" 19036 " {234, 5, 1, \"gracious\"} // fourth line\n" 19037 "};\n", 19038 Style); 19039 verifyFormat("struct test demo[3] = {\n" 19040 " {56, 23, \"hello\"},\n" 19041 " {-1, 93463, \"world\"},\n" 19042 " {7, 5, \"!!\" }\n" 19043 "};\n", 19044 Style); 19045 19046 verifyFormat("struct test demo[3] = {\n" 19047 " {int{56}, 23, \"hello\"},\n" 19048 " {int{-1}, 93463, \"world\"},\n" 19049 " {int{7}, 5, \"!!\" }\n" 19050 "};\n", 19051 Style); 19052 verifyFormat("struct test demo[] = {\n" 19053 " {56, 23, \"hello\"},\n" 19054 " {-1, 93463, \"world\"},\n" 19055 " {7, 5, \"!!\" },\n" 19056 "};\n", 19057 Style); 19058 verifyFormat("test demo[] = {\n" 19059 " {56, 23, \"hello\"},\n" 19060 " {-1, 93463, \"world\"},\n" 19061 " {7, 5, \"!!\" },\n" 19062 "};\n", 19063 Style); 19064 verifyFormat("demo = std::array<struct test, 3>{\n" 19065 " test{56, 23, \"hello\"},\n" 19066 " test{-1, 93463, \"world\"},\n" 19067 " test{7, 5, \"!!\" },\n" 19068 "};\n", 19069 Style); 19070 verifyFormat("test demo[] = {\n" 19071 " {56, 23, \"hello\"},\n" 19072 "#if X\n" 19073 " {-1, 93463, \"world\"},\n" 19074 "#endif\n" 19075 " {7, 5, \"!!\" }\n" 19076 "};\n", 19077 Style); 19078 verifyFormat( 19079 "test demo[] = {\n" 19080 " {7, 23,\n" 19081 " \"hello world i am a very long line that really, in any\"\n" 19082 " \"just world, ought to be split over multiple lines\"},\n" 19083 " {-1, 93463, \"world\" },\n" 19084 " {56, 5, \"!!\" }\n" 19085 "};\n", 19086 Style); 19087 19088 verifyFormat("return GradForUnaryCwise(g, {\n" 19089 " {{\"sign\"}, \"Sign\", {\"x\", " 19090 "\"dy\"} },\n" 19091 " {{\"dx\"}, \"Mul\", " 19092 "{\"dy\", \"sign\"}},\n" 19093 "});\n", 19094 Style); 19095 19096 Style.ColumnLimit = 0; 19097 EXPECT_EQ( 19098 "test demo[] = {\n" 19099 " {56, 23, \"hello world i am a very long line that really, in any " 19100 "just world, ought to be split over multiple lines\"},\n" 19101 " {-1, 93463, \"world\" " 19102 " },\n" 19103 " {7, 5, \"!!\" " 19104 " },\n" 19105 "};", 19106 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19107 "that really, in any just world, ought to be split over multiple " 19108 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19109 Style)); 19110 19111 Style.ColumnLimit = 80; 19112 verifyFormat("test demo[] = {\n" 19113 " {56, 23, /* a comment */ \"hello\"},\n" 19114 " {-1, 93463, \"world\" },\n" 19115 " {7, 5, \"!!\" }\n" 19116 "};\n", 19117 Style); 19118 19119 verifyFormat("test demo[] = {\n" 19120 " {56, 23, \"hello\" },\n" 19121 " {-1, 93463, \"world\" /* comment here */},\n" 19122 " {7, 5, \"!!\" }\n" 19123 "};\n", 19124 Style); 19125 19126 verifyFormat("test demo[] = {\n" 19127 " {56, /* a comment */ 23, \"hello\"},\n" 19128 " {-1, 93463, \"world\"},\n" 19129 " {7, 5, \"!!\" }\n" 19130 "};\n", 19131 Style); 19132 19133 Style.ColumnLimit = 20; 19134 EXPECT_EQ( 19135 "demo = std::array<\n" 19136 " struct test, 3>{\n" 19137 " test{\n" 19138 " 56, 23,\n" 19139 " \"hello \"\n" 19140 " \"world i \"\n" 19141 " \"am a very \"\n" 19142 " \"long line \"\n" 19143 " \"that \"\n" 19144 " \"really, \"\n" 19145 " \"in any \"\n" 19146 " \"just \"\n" 19147 " \"world, \"\n" 19148 " \"ought to \"\n" 19149 " \"be split \"\n" 19150 " \"over \"\n" 19151 " \"multiple \"\n" 19152 " \"lines\"},\n" 19153 " test{-1, 93463,\n" 19154 " \"world\"},\n" 19155 " test{7, 5,\n" 19156 " \"!!\" },\n" 19157 "};", 19158 format("demo = std::array<struct test, 3>{test{56, 23, \"hello world " 19159 "i am a very long line that really, in any just world, ought " 19160 "to be split over multiple lines\"},test{-1, 93463, \"world\"}," 19161 "test{7, 5, \"!!\"},};", 19162 Style)); 19163 19164 // This caused a core dump by enabling Alignment in the LLVMStyle globally 19165 Style = getLLVMStyleWithColumns(50); 19166 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 19167 verifyFormat("static A x = {\n" 19168 " {{init1, init2, init3, init4},\n" 19169 " {init1, init2, init3, init4}}\n" 19170 "};", 19171 Style); 19172 Style.ColumnLimit = 100; 19173 EXPECT_EQ( 19174 "test demo[] = {\n" 19175 " {56, 23,\n" 19176 " \"hello world i am a very long line that really, in any just world" 19177 ", ought to be split over \"\n" 19178 " \"multiple lines\" },\n" 19179 " {-1, 93463, \"world\"},\n" 19180 " {7, 5, \"!!\" },\n" 19181 "};", 19182 format("test demo[] = {{56, 23, \"hello world i am a very long line " 19183 "that really, in any just world, ought to be split over multiple " 19184 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 19185 Style)); 19186 } 19187 19188 TEST_F(FormatTest, UnderstandsPragmas) { 19189 verifyFormat("#pragma omp reduction(| : var)"); 19190 verifyFormat("#pragma omp reduction(+ : var)"); 19191 19192 EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string " 19193 "(including parentheses).", 19194 format("#pragma mark Any non-hyphenated or hyphenated string " 19195 "(including parentheses).")); 19196 } 19197 19198 TEST_F(FormatTest, UnderstandPragmaOption) { 19199 verifyFormat("#pragma option -C -A"); 19200 19201 EXPECT_EQ("#pragma option -C -A", format("#pragma option -C -A")); 19202 } 19203 19204 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) { 19205 FormatStyle Style = getLLVMStyleWithColumns(20); 19206 19207 // See PR41213 19208 EXPECT_EQ("/*\n" 19209 " *\t9012345\n" 19210 " * /8901\n" 19211 " */", 19212 format("/*\n" 19213 " *\t9012345 /8901\n" 19214 " */", 19215 Style)); 19216 EXPECT_EQ("/*\n" 19217 " *345678\n" 19218 " *\t/8901\n" 19219 " */", 19220 format("/*\n" 19221 " *345678\t/8901\n" 19222 " */", 19223 Style)); 19224 19225 verifyFormat("int a; // the\n" 19226 " // comment", 19227 Style); 19228 EXPECT_EQ("int a; /* first line\n" 19229 " * second\n" 19230 " * line third\n" 19231 " * line\n" 19232 " */", 19233 format("int a; /* first line\n" 19234 " * second\n" 19235 " * line third\n" 19236 " * line\n" 19237 " */", 19238 Style)); 19239 EXPECT_EQ("int a; // first line\n" 19240 " // second\n" 19241 " // line third\n" 19242 " // line", 19243 format("int a; // first line\n" 19244 " // second line\n" 19245 " // third line", 19246 Style)); 19247 19248 Style.PenaltyExcessCharacter = 90; 19249 verifyFormat("int a; // the comment", Style); 19250 EXPECT_EQ("int a; // the comment\n" 19251 " // aaa", 19252 format("int a; // the comment aaa", Style)); 19253 EXPECT_EQ("int a; /* first line\n" 19254 " * second line\n" 19255 " * third line\n" 19256 " */", 19257 format("int a; /* first line\n" 19258 " * second line\n" 19259 " * third line\n" 19260 " */", 19261 Style)); 19262 EXPECT_EQ("int a; // first line\n" 19263 " // second line\n" 19264 " // third line", 19265 format("int a; // first line\n" 19266 " // second line\n" 19267 " // third line", 19268 Style)); 19269 // FIXME: Investigate why this is not getting the same layout as the test 19270 // above. 19271 EXPECT_EQ("int a; /* first line\n" 19272 " * second line\n" 19273 " * third line\n" 19274 " */", 19275 format("int a; /* first line second line third line" 19276 "\n*/", 19277 Style)); 19278 19279 EXPECT_EQ("// foo bar baz bazfoo\n" 19280 "// foo bar foo bar\n", 19281 format("// foo bar baz bazfoo\n" 19282 "// foo bar foo bar\n", 19283 Style)); 19284 EXPECT_EQ("// foo bar baz bazfoo\n" 19285 "// foo bar foo bar\n", 19286 format("// foo bar baz bazfoo\n" 19287 "// foo bar foo bar\n", 19288 Style)); 19289 19290 // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the 19291 // next one. 19292 EXPECT_EQ("// foo bar baz bazfoo\n" 19293 "// bar foo bar\n", 19294 format("// foo bar baz bazfoo bar\n" 19295 "// foo bar\n", 19296 Style)); 19297 19298 EXPECT_EQ("// foo bar baz bazfoo\n" 19299 "// foo bar baz bazfoo\n" 19300 "// bar foo bar\n", 19301 format("// foo bar baz bazfoo\n" 19302 "// foo bar baz bazfoo bar\n" 19303 "// foo bar\n", 19304 Style)); 19305 19306 EXPECT_EQ("// foo bar baz bazfoo\n" 19307 "// foo bar baz bazfoo\n" 19308 "// bar foo bar\n", 19309 format("// foo bar baz bazfoo\n" 19310 "// foo bar baz bazfoo bar\n" 19311 "// foo bar\n", 19312 Style)); 19313 19314 // Make sure we do not keep protruding characters if strict mode reflow is 19315 // cheaper than keeping protruding characters. 19316 Style.ColumnLimit = 21; 19317 EXPECT_EQ( 19318 "// foo foo foo foo\n" 19319 "// foo foo foo foo\n" 19320 "// foo foo foo foo\n", 19321 format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style)); 19322 19323 EXPECT_EQ("int a = /* long block\n" 19324 " comment */\n" 19325 " 42;", 19326 format("int a = /* long block comment */ 42;", Style)); 19327 } 19328 19329 TEST_F(FormatTest, BreakPenaltyAfterLParen) { 19330 FormatStyle Style = getLLVMStyle(); 19331 Style.ColumnLimit = 8; 19332 Style.PenaltyExcessCharacter = 15; 19333 verifyFormat("int foo(\n" 19334 " int aaaaaaaaaaaaaaaaaaaaaaaa);", 19335 Style); 19336 Style.PenaltyBreakOpenParenthesis = 200; 19337 EXPECT_EQ("int foo(int aaaaaaaaaaaaaaaaaaaaaaaa);", 19338 format("int foo(\n" 19339 " int aaaaaaaaaaaaaaaaaaaaaaaa);", 19340 Style)); 19341 } 19342 19343 TEST_F(FormatTest, BreakPenaltyAfterCastLParen) { 19344 FormatStyle Style = getLLVMStyle(); 19345 Style.ColumnLimit = 5; 19346 Style.PenaltyExcessCharacter = 150; 19347 verifyFormat("foo((\n" 19348 " int)aaaaaaaaaaaaaaaaaaaaaaaa);", 19349 19350 Style); 19351 Style.PenaltyBreakOpenParenthesis = 100000; 19352 EXPECT_EQ("foo((int)\n" 19353 " aaaaaaaaaaaaaaaaaaaaaaaa);", 19354 format("foo((\n" 19355 "int)aaaaaaaaaaaaaaaaaaaaaaaa);", 19356 Style)); 19357 } 19358 19359 TEST_F(FormatTest, BreakPenaltyAfterForLoopLParen) { 19360 FormatStyle Style = getLLVMStyle(); 19361 Style.ColumnLimit = 4; 19362 Style.PenaltyExcessCharacter = 100; 19363 verifyFormat("for (\n" 19364 " int iiiiiiiiiiiiiiiii =\n" 19365 " 0;\n" 19366 " iiiiiiiiiiiiiiiii <\n" 19367 " 2;\n" 19368 " iiiiiiiiiiiiiiiii++) {\n" 19369 "}", 19370 19371 Style); 19372 Style.PenaltyBreakOpenParenthesis = 1250; 19373 EXPECT_EQ("for (int iiiiiiiiiiiiiiiii =\n" 19374 " 0;\n" 19375 " iiiiiiiiiiiiiiiii <\n" 19376 " 2;\n" 19377 " iiiiiiiiiiiiiiiii++) {\n" 19378 "}", 19379 format("for (\n" 19380 " int iiiiiiiiiiiiiiiii =\n" 19381 " 0;\n" 19382 " iiiiiiiiiiiiiiiii <\n" 19383 " 2;\n" 19384 " iiiiiiiiiiiiiiiii++) {\n" 19385 "}", 19386 Style)); 19387 } 19388 19389 #define EXPECT_ALL_STYLES_EQUAL(Styles) \ 19390 for (size_t i = 1; i < Styles.size(); ++i) \ 19391 EXPECT_EQ(Styles[0], Styles[i]) \ 19392 << "Style #" << i << " of " << Styles.size() << " differs from Style #0" 19393 19394 TEST_F(FormatTest, GetsPredefinedStyleByName) { 19395 SmallVector<FormatStyle, 3> Styles; 19396 Styles.resize(3); 19397 19398 Styles[0] = getLLVMStyle(); 19399 EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1])); 19400 EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2])); 19401 EXPECT_ALL_STYLES_EQUAL(Styles); 19402 19403 Styles[0] = getGoogleStyle(); 19404 EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1])); 19405 EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2])); 19406 EXPECT_ALL_STYLES_EQUAL(Styles); 19407 19408 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript); 19409 EXPECT_TRUE( 19410 getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1])); 19411 EXPECT_TRUE( 19412 getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2])); 19413 EXPECT_ALL_STYLES_EQUAL(Styles); 19414 19415 Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp); 19416 EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1])); 19417 EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2])); 19418 EXPECT_ALL_STYLES_EQUAL(Styles); 19419 19420 Styles[0] = getMozillaStyle(); 19421 EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1])); 19422 EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2])); 19423 EXPECT_ALL_STYLES_EQUAL(Styles); 19424 19425 Styles[0] = getWebKitStyle(); 19426 EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1])); 19427 EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2])); 19428 EXPECT_ALL_STYLES_EQUAL(Styles); 19429 19430 Styles[0] = getGNUStyle(); 19431 EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1])); 19432 EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2])); 19433 EXPECT_ALL_STYLES_EQUAL(Styles); 19434 19435 EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0])); 19436 } 19437 19438 TEST_F(FormatTest, GetsCorrectBasedOnStyle) { 19439 SmallVector<FormatStyle, 8> Styles; 19440 Styles.resize(2); 19441 19442 Styles[0] = getGoogleStyle(); 19443 Styles[1] = getLLVMStyle(); 19444 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value()); 19445 EXPECT_ALL_STYLES_EQUAL(Styles); 19446 19447 Styles.resize(5); 19448 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript); 19449 Styles[1] = getLLVMStyle(); 19450 Styles[1].Language = FormatStyle::LK_JavaScript; 19451 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value()); 19452 19453 Styles[2] = getLLVMStyle(); 19454 Styles[2].Language = FormatStyle::LK_JavaScript; 19455 EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n" 19456 "BasedOnStyle: Google", 19457 &Styles[2]) 19458 .value()); 19459 19460 Styles[3] = getLLVMStyle(); 19461 Styles[3].Language = FormatStyle::LK_JavaScript; 19462 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n" 19463 "Language: JavaScript", 19464 &Styles[3]) 19465 .value()); 19466 19467 Styles[4] = getLLVMStyle(); 19468 Styles[4].Language = FormatStyle::LK_JavaScript; 19469 EXPECT_EQ(0, parseConfiguration("---\n" 19470 "BasedOnStyle: LLVM\n" 19471 "IndentWidth: 123\n" 19472 "---\n" 19473 "BasedOnStyle: Google\n" 19474 "Language: JavaScript", 19475 &Styles[4]) 19476 .value()); 19477 EXPECT_ALL_STYLES_EQUAL(Styles); 19478 } 19479 19480 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME) \ 19481 Style.FIELD = false; \ 19482 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value()); \ 19483 EXPECT_TRUE(Style.FIELD); \ 19484 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value()); \ 19485 EXPECT_FALSE(Style.FIELD); 19486 19487 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD) 19488 19489 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME) \ 19490 Style.STRUCT.FIELD = false; \ 19491 EXPECT_EQ(0, \ 19492 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": true", &Style) \ 19493 .value()); \ 19494 EXPECT_TRUE(Style.STRUCT.FIELD); \ 19495 EXPECT_EQ(0, \ 19496 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": false", &Style) \ 19497 .value()); \ 19498 EXPECT_FALSE(Style.STRUCT.FIELD); 19499 19500 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD) \ 19501 CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD) 19502 19503 #define CHECK_PARSE(TEXT, FIELD, VALUE) \ 19504 EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!"; \ 19505 EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value()); \ 19506 EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!" 19507 19508 TEST_F(FormatTest, ParsesConfigurationBools) { 19509 FormatStyle Style = {}; 19510 Style.Language = FormatStyle::LK_Cpp; 19511 CHECK_PARSE_BOOL(AlignTrailingComments); 19512 CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine); 19513 CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine); 19514 CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine); 19515 CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine); 19516 CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine); 19517 CHECK_PARSE_BOOL(BinPackArguments); 19518 CHECK_PARSE_BOOL(BinPackParameters); 19519 CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations); 19520 CHECK_PARSE_BOOL(BreakBeforeTernaryOperators); 19521 CHECK_PARSE_BOOL(BreakStringLiterals); 19522 CHECK_PARSE_BOOL(CompactNamespaces); 19523 CHECK_PARSE_BOOL(DeriveLineEnding); 19524 CHECK_PARSE_BOOL(DerivePointerAlignment); 19525 CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding"); 19526 CHECK_PARSE_BOOL(DisableFormat); 19527 CHECK_PARSE_BOOL(IndentAccessModifiers); 19528 CHECK_PARSE_BOOL(IndentCaseLabels); 19529 CHECK_PARSE_BOOL(IndentCaseBlocks); 19530 CHECK_PARSE_BOOL(IndentGotoLabels); 19531 CHECK_PARSE_BOOL_FIELD(IndentRequiresClause, "IndentRequires"); 19532 CHECK_PARSE_BOOL(IndentRequiresClause); 19533 CHECK_PARSE_BOOL(IndentWrappedFunctionNames); 19534 CHECK_PARSE_BOOL(InsertBraces); 19535 CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks); 19536 CHECK_PARSE_BOOL(ObjCSpaceAfterProperty); 19537 CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList); 19538 CHECK_PARSE_BOOL(Cpp11BracedListStyle); 19539 CHECK_PARSE_BOOL(ReflowComments); 19540 CHECK_PARSE_BOOL(RemoveBracesLLVM); 19541 CHECK_PARSE_BOOL(SortUsingDeclarations); 19542 CHECK_PARSE_BOOL(SpacesInParentheses); 19543 CHECK_PARSE_BOOL(SpacesInSquareBrackets); 19544 CHECK_PARSE_BOOL(SpacesInConditionalStatement); 19545 CHECK_PARSE_BOOL(SpaceInEmptyBlock); 19546 CHECK_PARSE_BOOL(SpaceInEmptyParentheses); 19547 CHECK_PARSE_BOOL(SpacesInContainerLiterals); 19548 CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses); 19549 CHECK_PARSE_BOOL(SpaceAfterCStyleCast); 19550 CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword); 19551 CHECK_PARSE_BOOL(SpaceAfterLogicalNot); 19552 CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators); 19553 CHECK_PARSE_BOOL(SpaceBeforeCaseColon); 19554 CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList); 19555 CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon); 19556 CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon); 19557 CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon); 19558 CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets); 19559 CHECK_PARSE_BOOL(UseCRLF); 19560 19561 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel); 19562 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass); 19563 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum); 19564 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction); 19565 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace); 19566 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration); 19567 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct); 19568 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion); 19569 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock); 19570 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch); 19571 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse); 19572 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody); 19573 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile); 19574 CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces); 19575 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction); 19576 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord); 19577 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace); 19578 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterControlStatements); 19579 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterForeachMacros); 19580 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, 19581 AfterFunctionDeclarationName); 19582 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, 19583 AfterFunctionDefinitionName); 19584 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterIfMacros); 19585 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterOverloadedOperator); 19586 CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, BeforeNonEmptyParentheses); 19587 } 19588 19589 #undef CHECK_PARSE_BOOL 19590 19591 TEST_F(FormatTest, ParsesConfiguration) { 19592 FormatStyle Style = {}; 19593 Style.Language = FormatStyle::LK_Cpp; 19594 CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234); 19595 CHECK_PARSE("ConstructorInitializerIndentWidth: 1234", 19596 ConstructorInitializerIndentWidth, 1234u); 19597 CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u); 19598 CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u); 19599 CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u); 19600 CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u); 19601 CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234", 19602 PenaltyBreakBeforeFirstCallParameter, 1234u); 19603 CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234", 19604 PenaltyBreakTemplateDeclaration, 1234u); 19605 CHECK_PARSE("PenaltyBreakOpenParenthesis: 1234", PenaltyBreakOpenParenthesis, 19606 1234u); 19607 CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u); 19608 CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234", 19609 PenaltyReturnTypeOnItsOwnLine, 1234u); 19610 CHECK_PARSE("SpacesBeforeTrailingComments: 1234", 19611 SpacesBeforeTrailingComments, 1234u); 19612 CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u); 19613 CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u); 19614 CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$"); 19615 19616 Style.QualifierAlignment = FormatStyle::QAS_Right; 19617 CHECK_PARSE("QualifierAlignment: Leave", QualifierAlignment, 19618 FormatStyle::QAS_Leave); 19619 CHECK_PARSE("QualifierAlignment: Right", QualifierAlignment, 19620 FormatStyle::QAS_Right); 19621 CHECK_PARSE("QualifierAlignment: Left", QualifierAlignment, 19622 FormatStyle::QAS_Left); 19623 CHECK_PARSE("QualifierAlignment: Custom", QualifierAlignment, 19624 FormatStyle::QAS_Custom); 19625 19626 Style.QualifierOrder.clear(); 19627 CHECK_PARSE("QualifierOrder: [ const, volatile, type ]", QualifierOrder, 19628 std::vector<std::string>({"const", "volatile", "type"})); 19629 Style.QualifierOrder.clear(); 19630 CHECK_PARSE("QualifierOrder: [const, type]", QualifierOrder, 19631 std::vector<std::string>({"const", "type"})); 19632 Style.QualifierOrder.clear(); 19633 CHECK_PARSE("QualifierOrder: [volatile, type]", QualifierOrder, 19634 std::vector<std::string>({"volatile", "type"})); 19635 19636 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 19637 CHECK_PARSE("AlignConsecutiveAssignments: None", AlignConsecutiveAssignments, 19638 FormatStyle::ACS_None); 19639 CHECK_PARSE("AlignConsecutiveAssignments: Consecutive", 19640 AlignConsecutiveAssignments, FormatStyle::ACS_Consecutive); 19641 CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLines", 19642 AlignConsecutiveAssignments, FormatStyle::ACS_AcrossEmptyLines); 19643 CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLinesAndComments", 19644 AlignConsecutiveAssignments, 19645 FormatStyle::ACS_AcrossEmptyLinesAndComments); 19646 // For backwards compability, false / true should still parse 19647 CHECK_PARSE("AlignConsecutiveAssignments: false", AlignConsecutiveAssignments, 19648 FormatStyle::ACS_None); 19649 CHECK_PARSE("AlignConsecutiveAssignments: true", AlignConsecutiveAssignments, 19650 FormatStyle::ACS_Consecutive); 19651 19652 Style.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive; 19653 CHECK_PARSE("AlignConsecutiveBitFields: None", AlignConsecutiveBitFields, 19654 FormatStyle::ACS_None); 19655 CHECK_PARSE("AlignConsecutiveBitFields: Consecutive", 19656 AlignConsecutiveBitFields, FormatStyle::ACS_Consecutive); 19657 CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLines", 19658 AlignConsecutiveBitFields, FormatStyle::ACS_AcrossEmptyLines); 19659 CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLinesAndComments", 19660 AlignConsecutiveBitFields, 19661 FormatStyle::ACS_AcrossEmptyLinesAndComments); 19662 // For backwards compability, false / true should still parse 19663 CHECK_PARSE("AlignConsecutiveBitFields: false", AlignConsecutiveBitFields, 19664 FormatStyle::ACS_None); 19665 CHECK_PARSE("AlignConsecutiveBitFields: true", AlignConsecutiveBitFields, 19666 FormatStyle::ACS_Consecutive); 19667 19668 Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 19669 CHECK_PARSE("AlignConsecutiveMacros: None", AlignConsecutiveMacros, 19670 FormatStyle::ACS_None); 19671 CHECK_PARSE("AlignConsecutiveMacros: Consecutive", AlignConsecutiveMacros, 19672 FormatStyle::ACS_Consecutive); 19673 CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLines", 19674 AlignConsecutiveMacros, FormatStyle::ACS_AcrossEmptyLines); 19675 CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLinesAndComments", 19676 AlignConsecutiveMacros, 19677 FormatStyle::ACS_AcrossEmptyLinesAndComments); 19678 // For backwards compability, false / true should still parse 19679 CHECK_PARSE("AlignConsecutiveMacros: false", AlignConsecutiveMacros, 19680 FormatStyle::ACS_None); 19681 CHECK_PARSE("AlignConsecutiveMacros: true", AlignConsecutiveMacros, 19682 FormatStyle::ACS_Consecutive); 19683 19684 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 19685 CHECK_PARSE("AlignConsecutiveDeclarations: None", 19686 AlignConsecutiveDeclarations, FormatStyle::ACS_None); 19687 CHECK_PARSE("AlignConsecutiveDeclarations: Consecutive", 19688 AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive); 19689 CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLines", 19690 AlignConsecutiveDeclarations, FormatStyle::ACS_AcrossEmptyLines); 19691 CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLinesAndComments", 19692 AlignConsecutiveDeclarations, 19693 FormatStyle::ACS_AcrossEmptyLinesAndComments); 19694 // For backwards compability, false / true should still parse 19695 CHECK_PARSE("AlignConsecutiveDeclarations: false", 19696 AlignConsecutiveDeclarations, FormatStyle::ACS_None); 19697 CHECK_PARSE("AlignConsecutiveDeclarations: true", 19698 AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive); 19699 19700 Style.PointerAlignment = FormatStyle::PAS_Middle; 19701 CHECK_PARSE("PointerAlignment: Left", PointerAlignment, 19702 FormatStyle::PAS_Left); 19703 CHECK_PARSE("PointerAlignment: Right", PointerAlignment, 19704 FormatStyle::PAS_Right); 19705 CHECK_PARSE("PointerAlignment: Middle", PointerAlignment, 19706 FormatStyle::PAS_Middle); 19707 Style.ReferenceAlignment = FormatStyle::RAS_Middle; 19708 CHECK_PARSE("ReferenceAlignment: Pointer", ReferenceAlignment, 19709 FormatStyle::RAS_Pointer); 19710 CHECK_PARSE("ReferenceAlignment: Left", ReferenceAlignment, 19711 FormatStyle::RAS_Left); 19712 CHECK_PARSE("ReferenceAlignment: Right", ReferenceAlignment, 19713 FormatStyle::RAS_Right); 19714 CHECK_PARSE("ReferenceAlignment: Middle", ReferenceAlignment, 19715 FormatStyle::RAS_Middle); 19716 // For backward compatibility: 19717 CHECK_PARSE("PointerBindsToType: Left", PointerAlignment, 19718 FormatStyle::PAS_Left); 19719 CHECK_PARSE("PointerBindsToType: Right", PointerAlignment, 19720 FormatStyle::PAS_Right); 19721 CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment, 19722 FormatStyle::PAS_Middle); 19723 19724 Style.Standard = FormatStyle::LS_Auto; 19725 CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03); 19726 CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11); 19727 CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14); 19728 CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17); 19729 CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20); 19730 CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto); 19731 CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest); 19732 // Legacy aliases: 19733 CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03); 19734 CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest); 19735 CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03); 19736 CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11); 19737 19738 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 19739 CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment", 19740 BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment); 19741 CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators, 19742 FormatStyle::BOS_None); 19743 CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators, 19744 FormatStyle::BOS_All); 19745 // For backward compatibility: 19746 CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators, 19747 FormatStyle::BOS_None); 19748 CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators, 19749 FormatStyle::BOS_All); 19750 19751 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 19752 CHECK_PARSE("BreakConstructorInitializers: BeforeComma", 19753 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma); 19754 CHECK_PARSE("BreakConstructorInitializers: AfterColon", 19755 BreakConstructorInitializers, FormatStyle::BCIS_AfterColon); 19756 CHECK_PARSE("BreakConstructorInitializers: BeforeColon", 19757 BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon); 19758 // For backward compatibility: 19759 CHECK_PARSE("BreakConstructorInitializersBeforeComma: true", 19760 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma); 19761 19762 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 19763 CHECK_PARSE("BreakInheritanceList: AfterComma", BreakInheritanceList, 19764 FormatStyle::BILS_AfterComma); 19765 CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList, 19766 FormatStyle::BILS_BeforeComma); 19767 CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList, 19768 FormatStyle::BILS_AfterColon); 19769 CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList, 19770 FormatStyle::BILS_BeforeColon); 19771 // For backward compatibility: 19772 CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList, 19773 FormatStyle::BILS_BeforeComma); 19774 19775 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 19776 CHECK_PARSE("PackConstructorInitializers: Never", PackConstructorInitializers, 19777 FormatStyle::PCIS_Never); 19778 CHECK_PARSE("PackConstructorInitializers: BinPack", 19779 PackConstructorInitializers, FormatStyle::PCIS_BinPack); 19780 CHECK_PARSE("PackConstructorInitializers: CurrentLine", 19781 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 19782 CHECK_PARSE("PackConstructorInitializers: NextLine", 19783 PackConstructorInitializers, FormatStyle::PCIS_NextLine); 19784 // For backward compatibility: 19785 CHECK_PARSE("BasedOnStyle: Google\n" 19786 "ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 19787 "AllowAllConstructorInitializersOnNextLine: false", 19788 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 19789 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 19790 CHECK_PARSE("BasedOnStyle: Google\n" 19791 "ConstructorInitializerAllOnOneLineOrOnePerLine: false", 19792 PackConstructorInitializers, FormatStyle::PCIS_BinPack); 19793 CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 19794 "AllowAllConstructorInitializersOnNextLine: true", 19795 PackConstructorInitializers, FormatStyle::PCIS_NextLine); 19796 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 19797 CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 19798 "AllowAllConstructorInitializersOnNextLine: false", 19799 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 19800 19801 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 19802 CHECK_PARSE("EmptyLineBeforeAccessModifier: Never", 19803 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never); 19804 CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave", 19805 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave); 19806 CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock", 19807 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock); 19808 CHECK_PARSE("EmptyLineBeforeAccessModifier: Always", 19809 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always); 19810 19811 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 19812 CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket, 19813 FormatStyle::BAS_Align); 19814 CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket, 19815 FormatStyle::BAS_DontAlign); 19816 CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket, 19817 FormatStyle::BAS_AlwaysBreak); 19818 CHECK_PARSE("AlignAfterOpenBracket: BlockIndent", AlignAfterOpenBracket, 19819 FormatStyle::BAS_BlockIndent); 19820 // For backward compatibility: 19821 CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket, 19822 FormatStyle::BAS_DontAlign); 19823 CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket, 19824 FormatStyle::BAS_Align); 19825 19826 Style.AlignEscapedNewlines = FormatStyle::ENAS_Left; 19827 CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines, 19828 FormatStyle::ENAS_DontAlign); 19829 CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines, 19830 FormatStyle::ENAS_Left); 19831 CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines, 19832 FormatStyle::ENAS_Right); 19833 // For backward compatibility: 19834 CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines, 19835 FormatStyle::ENAS_Left); 19836 CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines, 19837 FormatStyle::ENAS_Right); 19838 19839 Style.AlignOperands = FormatStyle::OAS_Align; 19840 CHECK_PARSE("AlignOperands: DontAlign", AlignOperands, 19841 FormatStyle::OAS_DontAlign); 19842 CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align); 19843 CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands, 19844 FormatStyle::OAS_AlignAfterOperator); 19845 // For backward compatibility: 19846 CHECK_PARSE("AlignOperands: false", AlignOperands, 19847 FormatStyle::OAS_DontAlign); 19848 CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align); 19849 19850 Style.UseTab = FormatStyle::UT_ForIndentation; 19851 CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never); 19852 CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation); 19853 CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always); 19854 CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab, 19855 FormatStyle::UT_ForContinuationAndIndentation); 19856 CHECK_PARSE("UseTab: AlignWithSpaces", UseTab, 19857 FormatStyle::UT_AlignWithSpaces); 19858 // For backward compatibility: 19859 CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never); 19860 CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always); 19861 19862 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 19863 CHECK_PARSE("AllowShortBlocksOnASingleLine: Never", 19864 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 19865 CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty", 19866 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty); 19867 CHECK_PARSE("AllowShortBlocksOnASingleLine: Always", 19868 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always); 19869 // For backward compatibility: 19870 CHECK_PARSE("AllowShortBlocksOnASingleLine: false", 19871 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 19872 CHECK_PARSE("AllowShortBlocksOnASingleLine: true", 19873 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always); 19874 19875 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 19876 CHECK_PARSE("AllowShortFunctionsOnASingleLine: None", 19877 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None); 19878 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline", 19879 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline); 19880 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty", 19881 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty); 19882 CHECK_PARSE("AllowShortFunctionsOnASingleLine: All", 19883 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All); 19884 // For backward compatibility: 19885 CHECK_PARSE("AllowShortFunctionsOnASingleLine: false", 19886 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None); 19887 CHECK_PARSE("AllowShortFunctionsOnASingleLine: true", 19888 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All); 19889 19890 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both; 19891 CHECK_PARSE("SpaceAroundPointerQualifiers: Default", 19892 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default); 19893 CHECK_PARSE("SpaceAroundPointerQualifiers: Before", 19894 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before); 19895 CHECK_PARSE("SpaceAroundPointerQualifiers: After", 19896 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After); 19897 CHECK_PARSE("SpaceAroundPointerQualifiers: Both", 19898 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both); 19899 19900 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 19901 CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens, 19902 FormatStyle::SBPO_Never); 19903 CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens, 19904 FormatStyle::SBPO_Always); 19905 CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens, 19906 FormatStyle::SBPO_ControlStatements); 19907 CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptControlMacros", 19908 SpaceBeforeParens, 19909 FormatStyle::SBPO_ControlStatementsExceptControlMacros); 19910 CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens, 19911 FormatStyle::SBPO_NonEmptyParentheses); 19912 CHECK_PARSE("SpaceBeforeParens: Custom", SpaceBeforeParens, 19913 FormatStyle::SBPO_Custom); 19914 // For backward compatibility: 19915 CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens, 19916 FormatStyle::SBPO_Never); 19917 CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens, 19918 FormatStyle::SBPO_ControlStatements); 19919 CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptForEachMacros", 19920 SpaceBeforeParens, 19921 FormatStyle::SBPO_ControlStatementsExceptControlMacros); 19922 19923 Style.ColumnLimit = 123; 19924 FormatStyle BaseStyle = getLLVMStyle(); 19925 CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit); 19926 CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u); 19927 19928 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 19929 CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces, 19930 FormatStyle::BS_Attach); 19931 CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces, 19932 FormatStyle::BS_Linux); 19933 CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces, 19934 FormatStyle::BS_Mozilla); 19935 CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces, 19936 FormatStyle::BS_Stroustrup); 19937 CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces, 19938 FormatStyle::BS_Allman); 19939 CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces, 19940 FormatStyle::BS_Whitesmiths); 19941 CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU); 19942 CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces, 19943 FormatStyle::BS_WebKit); 19944 CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces, 19945 FormatStyle::BS_Custom); 19946 19947 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never; 19948 CHECK_PARSE("BraceWrapping:\n" 19949 " AfterControlStatement: MultiLine", 19950 BraceWrapping.AfterControlStatement, 19951 FormatStyle::BWACS_MultiLine); 19952 CHECK_PARSE("BraceWrapping:\n" 19953 " AfterControlStatement: Always", 19954 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always); 19955 CHECK_PARSE("BraceWrapping:\n" 19956 " AfterControlStatement: Never", 19957 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never); 19958 // For backward compatibility: 19959 CHECK_PARSE("BraceWrapping:\n" 19960 " AfterControlStatement: true", 19961 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always); 19962 CHECK_PARSE("BraceWrapping:\n" 19963 " AfterControlStatement: false", 19964 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never); 19965 19966 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 19967 CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType, 19968 FormatStyle::RTBS_None); 19969 CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType, 19970 FormatStyle::RTBS_All); 19971 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel", 19972 AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel); 19973 CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions", 19974 AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions); 19975 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions", 19976 AlwaysBreakAfterReturnType, 19977 FormatStyle::RTBS_TopLevelDefinitions); 19978 19979 Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 19980 CHECK_PARSE("AlwaysBreakTemplateDeclarations: No", 19981 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No); 19982 CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine", 19983 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine); 19984 CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes", 19985 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes); 19986 CHECK_PARSE("AlwaysBreakTemplateDeclarations: false", 19987 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine); 19988 CHECK_PARSE("AlwaysBreakTemplateDeclarations: true", 19989 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes); 19990 19991 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All; 19992 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None", 19993 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None); 19994 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All", 19995 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All); 19996 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel", 19997 AlwaysBreakAfterDefinitionReturnType, 19998 FormatStyle::DRTBS_TopLevel); 19999 20000 Style.NamespaceIndentation = FormatStyle::NI_All; 20001 CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation, 20002 FormatStyle::NI_None); 20003 CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation, 20004 FormatStyle::NI_Inner); 20005 CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation, 20006 FormatStyle::NI_All); 20007 20008 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_OnlyFirstIf; 20009 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never", 20010 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never); 20011 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse", 20012 AllowShortIfStatementsOnASingleLine, 20013 FormatStyle::SIS_WithoutElse); 20014 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: OnlyFirstIf", 20015 AllowShortIfStatementsOnASingleLine, 20016 FormatStyle::SIS_OnlyFirstIf); 20017 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: AllIfsAndElse", 20018 AllowShortIfStatementsOnASingleLine, 20019 FormatStyle::SIS_AllIfsAndElse); 20020 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always", 20021 AllowShortIfStatementsOnASingleLine, 20022 FormatStyle::SIS_OnlyFirstIf); 20023 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false", 20024 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never); 20025 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true", 20026 AllowShortIfStatementsOnASingleLine, 20027 FormatStyle::SIS_WithoutElse); 20028 20029 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 20030 CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock, 20031 FormatStyle::IEBS_AfterExternBlock); 20032 CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock, 20033 FormatStyle::IEBS_Indent); 20034 CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock, 20035 FormatStyle::IEBS_NoIndent); 20036 CHECK_PARSE("IndentExternBlock: true", IndentExternBlock, 20037 FormatStyle::IEBS_Indent); 20038 CHECK_PARSE("IndentExternBlock: false", IndentExternBlock, 20039 FormatStyle::IEBS_NoIndent); 20040 20041 Style.BitFieldColonSpacing = FormatStyle::BFCS_None; 20042 CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing, 20043 FormatStyle::BFCS_Both); 20044 CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing, 20045 FormatStyle::BFCS_None); 20046 CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing, 20047 FormatStyle::BFCS_Before); 20048 CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing, 20049 FormatStyle::BFCS_After); 20050 20051 Style.SortJavaStaticImport = FormatStyle::SJSIO_Before; 20052 CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport, 20053 FormatStyle::SJSIO_After); 20054 CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport, 20055 FormatStyle::SJSIO_Before); 20056 20057 // FIXME: This is required because parsing a configuration simply overwrites 20058 // the first N elements of the list instead of resetting it. 20059 Style.ForEachMacros.clear(); 20060 std::vector<std::string> BoostForeach; 20061 BoostForeach.push_back("BOOST_FOREACH"); 20062 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach); 20063 std::vector<std::string> BoostAndQForeach; 20064 BoostAndQForeach.push_back("BOOST_FOREACH"); 20065 BoostAndQForeach.push_back("Q_FOREACH"); 20066 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros, 20067 BoostAndQForeach); 20068 20069 Style.IfMacros.clear(); 20070 std::vector<std::string> CustomIfs; 20071 CustomIfs.push_back("MYIF"); 20072 CHECK_PARSE("IfMacros: [MYIF]", IfMacros, CustomIfs); 20073 20074 Style.AttributeMacros.clear(); 20075 CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros, 20076 std::vector<std::string>{"__capability"}); 20077 CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros, 20078 std::vector<std::string>({"attr1", "attr2"})); 20079 20080 Style.StatementAttributeLikeMacros.clear(); 20081 CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]", 20082 StatementAttributeLikeMacros, 20083 std::vector<std::string>({"emit", "Q_EMIT"})); 20084 20085 Style.StatementMacros.clear(); 20086 CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros, 20087 std::vector<std::string>{"QUNUSED"}); 20088 CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros, 20089 std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"})); 20090 20091 Style.NamespaceMacros.clear(); 20092 CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros, 20093 std::vector<std::string>{"TESTSUITE"}); 20094 CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros, 20095 std::vector<std::string>({"TESTSUITE", "SUITE"})); 20096 20097 Style.WhitespaceSensitiveMacros.clear(); 20098 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]", 20099 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"}); 20100 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]", 20101 WhitespaceSensitiveMacros, 20102 std::vector<std::string>({"STRINGIZE", "ASSERT"})); 20103 Style.WhitespaceSensitiveMacros.clear(); 20104 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']", 20105 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"}); 20106 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']", 20107 WhitespaceSensitiveMacros, 20108 std::vector<std::string>({"STRINGIZE", "ASSERT"})); 20109 20110 Style.IncludeStyle.IncludeCategories.clear(); 20111 std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = { 20112 {"abc/.*", 2, 0, false}, {".*", 1, 0, true}}; 20113 CHECK_PARSE("IncludeCategories:\n" 20114 " - Regex: abc/.*\n" 20115 " Priority: 2\n" 20116 " - Regex: .*\n" 20117 " Priority: 1\n" 20118 " CaseSensitive: true\n", 20119 IncludeStyle.IncludeCategories, ExpectedCategories); 20120 CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex, 20121 "abc$"); 20122 CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'", 20123 IncludeStyle.IncludeIsMainSourceRegex, "abc$"); 20124 20125 Style.SortIncludes = FormatStyle::SI_Never; 20126 CHECK_PARSE("SortIncludes: true", SortIncludes, 20127 FormatStyle::SI_CaseSensitive); 20128 CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never); 20129 CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes, 20130 FormatStyle::SI_CaseInsensitive); 20131 CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes, 20132 FormatStyle::SI_CaseSensitive); 20133 CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never); 20134 20135 Style.RawStringFormats.clear(); 20136 std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = { 20137 { 20138 FormatStyle::LK_TextProto, 20139 {"pb", "proto"}, 20140 {"PARSE_TEXT_PROTO"}, 20141 /*CanonicalDelimiter=*/"", 20142 "llvm", 20143 }, 20144 { 20145 FormatStyle::LK_Cpp, 20146 {"cc", "cpp"}, 20147 {"C_CODEBLOCK", "CPPEVAL"}, 20148 /*CanonicalDelimiter=*/"cc", 20149 /*BasedOnStyle=*/"", 20150 }, 20151 }; 20152 20153 CHECK_PARSE("RawStringFormats:\n" 20154 " - Language: TextProto\n" 20155 " Delimiters:\n" 20156 " - 'pb'\n" 20157 " - 'proto'\n" 20158 " EnclosingFunctions:\n" 20159 " - 'PARSE_TEXT_PROTO'\n" 20160 " BasedOnStyle: llvm\n" 20161 " - Language: Cpp\n" 20162 " Delimiters:\n" 20163 " - 'cc'\n" 20164 " - 'cpp'\n" 20165 " EnclosingFunctions:\n" 20166 " - 'C_CODEBLOCK'\n" 20167 " - 'CPPEVAL'\n" 20168 " CanonicalDelimiter: 'cc'", 20169 RawStringFormats, ExpectedRawStringFormats); 20170 20171 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20172 " Minimum: 0\n" 20173 " Maximum: 0", 20174 SpacesInLineCommentPrefix.Minimum, 0u); 20175 EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u); 20176 Style.SpacesInLineCommentPrefix.Minimum = 1; 20177 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20178 " Minimum: 2", 20179 SpacesInLineCommentPrefix.Minimum, 0u); 20180 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20181 " Maximum: -1", 20182 SpacesInLineCommentPrefix.Maximum, -1u); 20183 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20184 " Minimum: 2", 20185 SpacesInLineCommentPrefix.Minimum, 2u); 20186 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 20187 " Maximum: 1", 20188 SpacesInLineCommentPrefix.Maximum, 1u); 20189 EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u); 20190 20191 Style.SpacesInAngles = FormatStyle::SIAS_Always; 20192 CHECK_PARSE("SpacesInAngles: Never", SpacesInAngles, FormatStyle::SIAS_Never); 20193 CHECK_PARSE("SpacesInAngles: Always", SpacesInAngles, 20194 FormatStyle::SIAS_Always); 20195 CHECK_PARSE("SpacesInAngles: Leave", SpacesInAngles, FormatStyle::SIAS_Leave); 20196 // For backward compatibility: 20197 CHECK_PARSE("SpacesInAngles: false", SpacesInAngles, FormatStyle::SIAS_Never); 20198 CHECK_PARSE("SpacesInAngles: true", SpacesInAngles, FormatStyle::SIAS_Always); 20199 20200 CHECK_PARSE("RequiresClausePosition: WithPreceding", RequiresClausePosition, 20201 FormatStyle::RCPS_WithPreceding); 20202 CHECK_PARSE("RequiresClausePosition: WithFollowing", RequiresClausePosition, 20203 FormatStyle::RCPS_WithFollowing); 20204 CHECK_PARSE("RequiresClausePosition: SingleLine", RequiresClausePosition, 20205 FormatStyle::RCPS_SingleLine); 20206 CHECK_PARSE("RequiresClausePosition: OwnLine", RequiresClausePosition, 20207 FormatStyle::RCPS_OwnLine); 20208 20209 CHECK_PARSE("BreakBeforeConceptDeclarations: Never", 20210 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Never); 20211 CHECK_PARSE("BreakBeforeConceptDeclarations: Always", 20212 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always); 20213 CHECK_PARSE("BreakBeforeConceptDeclarations: Allowed", 20214 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed); 20215 // For backward compatibility: 20216 CHECK_PARSE("BreakBeforeConceptDeclarations: true", 20217 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always); 20218 CHECK_PARSE("BreakBeforeConceptDeclarations: false", 20219 BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed); 20220 } 20221 20222 TEST_F(FormatTest, ParsesConfigurationWithLanguages) { 20223 FormatStyle Style = {}; 20224 Style.Language = FormatStyle::LK_Cpp; 20225 CHECK_PARSE("Language: Cpp\n" 20226 "IndentWidth: 12", 20227 IndentWidth, 12u); 20228 EXPECT_EQ(parseConfiguration("Language: JavaScript\n" 20229 "IndentWidth: 34", 20230 &Style), 20231 ParseError::Unsuitable); 20232 FormatStyle BinPackedTCS = {}; 20233 BinPackedTCS.Language = FormatStyle::LK_JavaScript; 20234 EXPECT_EQ(parseConfiguration("BinPackArguments: true\n" 20235 "InsertTrailingCommas: Wrapped", 20236 &BinPackedTCS), 20237 ParseError::BinPackTrailingCommaConflict); 20238 EXPECT_EQ(12u, Style.IndentWidth); 20239 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u); 20240 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language); 20241 20242 Style.Language = FormatStyle::LK_JavaScript; 20243 CHECK_PARSE("Language: JavaScript\n" 20244 "IndentWidth: 12", 20245 IndentWidth, 12u); 20246 CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u); 20247 EXPECT_EQ(parseConfiguration("Language: Cpp\n" 20248 "IndentWidth: 34", 20249 &Style), 20250 ParseError::Unsuitable); 20251 EXPECT_EQ(23u, Style.IndentWidth); 20252 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u); 20253 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language); 20254 20255 CHECK_PARSE("BasedOnStyle: LLVM\n" 20256 "IndentWidth: 67", 20257 IndentWidth, 67u); 20258 20259 CHECK_PARSE("---\n" 20260 "Language: JavaScript\n" 20261 "IndentWidth: 12\n" 20262 "---\n" 20263 "Language: Cpp\n" 20264 "IndentWidth: 34\n" 20265 "...\n", 20266 IndentWidth, 12u); 20267 20268 Style.Language = FormatStyle::LK_Cpp; 20269 CHECK_PARSE("---\n" 20270 "Language: JavaScript\n" 20271 "IndentWidth: 12\n" 20272 "---\n" 20273 "Language: Cpp\n" 20274 "IndentWidth: 34\n" 20275 "...\n", 20276 IndentWidth, 34u); 20277 CHECK_PARSE("---\n" 20278 "IndentWidth: 78\n" 20279 "---\n" 20280 "Language: JavaScript\n" 20281 "IndentWidth: 56\n" 20282 "...\n", 20283 IndentWidth, 78u); 20284 20285 Style.ColumnLimit = 123; 20286 Style.IndentWidth = 234; 20287 Style.BreakBeforeBraces = FormatStyle::BS_Linux; 20288 Style.TabWidth = 345; 20289 EXPECT_FALSE(parseConfiguration("---\n" 20290 "IndentWidth: 456\n" 20291 "BreakBeforeBraces: Allman\n" 20292 "---\n" 20293 "Language: JavaScript\n" 20294 "IndentWidth: 111\n" 20295 "TabWidth: 111\n" 20296 "---\n" 20297 "Language: Cpp\n" 20298 "BreakBeforeBraces: Stroustrup\n" 20299 "TabWidth: 789\n" 20300 "...\n", 20301 &Style)); 20302 EXPECT_EQ(123u, Style.ColumnLimit); 20303 EXPECT_EQ(456u, Style.IndentWidth); 20304 EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces); 20305 EXPECT_EQ(789u, Style.TabWidth); 20306 20307 EXPECT_EQ(parseConfiguration("---\n" 20308 "Language: JavaScript\n" 20309 "IndentWidth: 56\n" 20310 "---\n" 20311 "IndentWidth: 78\n" 20312 "...\n", 20313 &Style), 20314 ParseError::Error); 20315 EXPECT_EQ(parseConfiguration("---\n" 20316 "Language: JavaScript\n" 20317 "IndentWidth: 56\n" 20318 "---\n" 20319 "Language: JavaScript\n" 20320 "IndentWidth: 78\n" 20321 "...\n", 20322 &Style), 20323 ParseError::Error); 20324 20325 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language); 20326 } 20327 20328 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) { 20329 FormatStyle Style = {}; 20330 Style.Language = FormatStyle::LK_JavaScript; 20331 Style.BreakBeforeTernaryOperators = true; 20332 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value()); 20333 EXPECT_FALSE(Style.BreakBeforeTernaryOperators); 20334 20335 Style.BreakBeforeTernaryOperators = true; 20336 EXPECT_EQ(0, parseConfiguration("---\n" 20337 "BasedOnStyle: Google\n" 20338 "---\n" 20339 "Language: JavaScript\n" 20340 "IndentWidth: 76\n" 20341 "...\n", 20342 &Style) 20343 .value()); 20344 EXPECT_FALSE(Style.BreakBeforeTernaryOperators); 20345 EXPECT_EQ(76u, Style.IndentWidth); 20346 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language); 20347 } 20348 20349 TEST_F(FormatTest, ConfigurationRoundTripTest) { 20350 FormatStyle Style = getLLVMStyle(); 20351 std::string YAML = configurationAsText(Style); 20352 FormatStyle ParsedStyle = {}; 20353 ParsedStyle.Language = FormatStyle::LK_Cpp; 20354 EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value()); 20355 EXPECT_EQ(Style, ParsedStyle); 20356 } 20357 20358 TEST_F(FormatTest, WorksFor8bitEncodings) { 20359 EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n" 20360 "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n" 20361 "\"\xe7\xe8\xec\xed\xfe\xfe \"\n" 20362 "\"\xef\xee\xf0\xf3...\"", 20363 format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 " 20364 "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe " 20365 "\xef\xee\xf0\xf3...\"", 20366 getLLVMStyleWithColumns(12))); 20367 } 20368 20369 TEST_F(FormatTest, HandlesUTF8BOM) { 20370 EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf")); 20371 EXPECT_EQ("\xef\xbb\xbf#include <iostream>", 20372 format("\xef\xbb\xbf#include <iostream>")); 20373 EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>", 20374 format("\xef\xbb\xbf\n#include <iostream>")); 20375 } 20376 20377 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers. 20378 #if !defined(_MSC_VER) 20379 20380 TEST_F(FormatTest, CountsUTF8CharactersProperly) { 20381 verifyFormat("\"Однажды в студёную зимнюю пору...\"", 20382 getLLVMStyleWithColumns(35)); 20383 verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"", 20384 getLLVMStyleWithColumns(31)); 20385 verifyFormat("// Однажды в студёную зимнюю пору...", 20386 getLLVMStyleWithColumns(36)); 20387 verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32)); 20388 verifyFormat("/* Однажды в студёную зимнюю пору... */", 20389 getLLVMStyleWithColumns(39)); 20390 verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */", 20391 getLLVMStyleWithColumns(35)); 20392 } 20393 20394 TEST_F(FormatTest, SplitsUTF8Strings) { 20395 // Non-printable characters' width is currently considered to be the length in 20396 // bytes in UTF8. The characters can be displayed in very different manner 20397 // (zero-width, single width with a substitution glyph, expanded to their code 20398 // (e.g. "<8d>"), so there's no single correct way to handle them. 20399 EXPECT_EQ("\"aaaaÄ\"\n" 20400 "\"\xc2\x8d\";", 20401 format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10))); 20402 EXPECT_EQ("\"aaaaaaaÄ\"\n" 20403 "\"\xc2\x8d\";", 20404 format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10))); 20405 EXPECT_EQ("\"Однажды, в \"\n" 20406 "\"студёную \"\n" 20407 "\"зимнюю \"\n" 20408 "\"пору,\"", 20409 format("\"Однажды, в студёную зимнюю пору,\"", 20410 getLLVMStyleWithColumns(13))); 20411 EXPECT_EQ( 20412 "\"一 二 三 \"\n" 20413 "\"四 五六 \"\n" 20414 "\"七 八 九 \"\n" 20415 "\"十\"", 20416 format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11))); 20417 EXPECT_EQ("\"一\t\"\n" 20418 "\"二 \t\"\n" 20419 "\"三 四 \"\n" 20420 "\"五\t\"\n" 20421 "\"六 \t\"\n" 20422 "\"七 \"\n" 20423 "\"八九十\tqq\"", 20424 format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"", 20425 getLLVMStyleWithColumns(11))); 20426 20427 // UTF8 character in an escape sequence. 20428 EXPECT_EQ("\"aaaaaa\"\n" 20429 "\"\\\xC2\x8D\"", 20430 format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10))); 20431 } 20432 20433 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) { 20434 EXPECT_EQ("const char *sssss =\n" 20435 " \"一二三四五六七八\\\n" 20436 " 九 十\";", 20437 format("const char *sssss = \"一二三四五六七八\\\n" 20438 " 九 十\";", 20439 getLLVMStyleWithColumns(30))); 20440 } 20441 20442 TEST_F(FormatTest, SplitsUTF8LineComments) { 20443 EXPECT_EQ("// aaaaÄ\xc2\x8d", 20444 format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10))); 20445 EXPECT_EQ("// Я из лесу\n" 20446 "// вышел; был\n" 20447 "// сильный\n" 20448 "// мороз.", 20449 format("// Я из лесу вышел; был сильный мороз.", 20450 getLLVMStyleWithColumns(13))); 20451 EXPECT_EQ("// 一二三\n" 20452 "// 四五六七\n" 20453 "// 八 九\n" 20454 "// 十", 20455 format("// 一二三 四五六七 八 九 十", getLLVMStyleWithColumns(9))); 20456 } 20457 20458 TEST_F(FormatTest, SplitsUTF8BlockComments) { 20459 EXPECT_EQ("/* Гляжу,\n" 20460 " * поднимается\n" 20461 " * медленно в\n" 20462 " * гору\n" 20463 " * Лошадка,\n" 20464 " * везущая\n" 20465 " * хворосту\n" 20466 " * воз. */", 20467 format("/* Гляжу, поднимается медленно в гору\n" 20468 " * Лошадка, везущая хворосту воз. */", 20469 getLLVMStyleWithColumns(13))); 20470 EXPECT_EQ( 20471 "/* 一二三\n" 20472 " * 四五六七\n" 20473 " * 八 九\n" 20474 " * 十 */", 20475 format("/* 一二三 四五六七 八 九 十 */", getLLVMStyleWithColumns(9))); 20476 EXPECT_EQ("/* \n" 20477 " * \n" 20478 " * - */", 20479 format("/* - */", getLLVMStyleWithColumns(12))); 20480 } 20481 20482 #endif // _MSC_VER 20483 20484 TEST_F(FormatTest, ConstructorInitializerIndentWidth) { 20485 FormatStyle Style = getLLVMStyle(); 20486 20487 Style.ConstructorInitializerIndentWidth = 4; 20488 verifyFormat( 20489 "SomeClass::Constructor()\n" 20490 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20491 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20492 Style); 20493 20494 Style.ConstructorInitializerIndentWidth = 2; 20495 verifyFormat( 20496 "SomeClass::Constructor()\n" 20497 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20498 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20499 Style); 20500 20501 Style.ConstructorInitializerIndentWidth = 0; 20502 verifyFormat( 20503 "SomeClass::Constructor()\n" 20504 ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 20505 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 20506 Style); 20507 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 20508 verifyFormat( 20509 "SomeLongTemplateVariableName<\n" 20510 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>", 20511 Style); 20512 verifyFormat("bool smaller = 1 < " 20513 "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 20514 " " 20515 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 20516 Style); 20517 20518 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 20519 verifyFormat("SomeClass::Constructor() :\n" 20520 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n" 20521 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}", 20522 Style); 20523 } 20524 20525 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) { 20526 FormatStyle Style = getLLVMStyle(); 20527 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 20528 Style.ConstructorInitializerIndentWidth = 4; 20529 verifyFormat("SomeClass::Constructor()\n" 20530 " : a(a)\n" 20531 " , b(b)\n" 20532 " , c(c) {}", 20533 Style); 20534 verifyFormat("SomeClass::Constructor()\n" 20535 " : a(a) {}", 20536 Style); 20537 20538 Style.ColumnLimit = 0; 20539 verifyFormat("SomeClass::Constructor()\n" 20540 " : a(a) {}", 20541 Style); 20542 verifyFormat("SomeClass::Constructor() noexcept\n" 20543 " : a(a) {}", 20544 Style); 20545 verifyFormat("SomeClass::Constructor()\n" 20546 " : a(a)\n" 20547 " , b(b)\n" 20548 " , c(c) {}", 20549 Style); 20550 verifyFormat("SomeClass::Constructor()\n" 20551 " : a(a) {\n" 20552 " foo();\n" 20553 " bar();\n" 20554 "}", 20555 Style); 20556 20557 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 20558 verifyFormat("SomeClass::Constructor()\n" 20559 " : a(a)\n" 20560 " , b(b)\n" 20561 " , c(c) {\n}", 20562 Style); 20563 verifyFormat("SomeClass::Constructor()\n" 20564 " : a(a) {\n}", 20565 Style); 20566 20567 Style.ColumnLimit = 80; 20568 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 20569 Style.ConstructorInitializerIndentWidth = 2; 20570 verifyFormat("SomeClass::Constructor()\n" 20571 " : a(a)\n" 20572 " , b(b)\n" 20573 " , c(c) {}", 20574 Style); 20575 20576 Style.ConstructorInitializerIndentWidth = 0; 20577 verifyFormat("SomeClass::Constructor()\n" 20578 ": a(a)\n" 20579 ", b(b)\n" 20580 ", c(c) {}", 20581 Style); 20582 20583 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 20584 Style.ConstructorInitializerIndentWidth = 4; 20585 verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style); 20586 verifyFormat( 20587 "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n", 20588 Style); 20589 verifyFormat( 20590 "SomeClass::Constructor()\n" 20591 " : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}", 20592 Style); 20593 Style.ConstructorInitializerIndentWidth = 4; 20594 Style.ColumnLimit = 60; 20595 verifyFormat("SomeClass::Constructor()\n" 20596 " : aaaaaaaa(aaaaaaaa)\n" 20597 " , aaaaaaaa(aaaaaaaa)\n" 20598 " , aaaaaaaa(aaaaaaaa) {}", 20599 Style); 20600 } 20601 20602 TEST_F(FormatTest, ConstructorInitializersWithPreprocessorDirective) { 20603 FormatStyle Style = getLLVMStyle(); 20604 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 20605 Style.ConstructorInitializerIndentWidth = 4; 20606 verifyFormat("SomeClass::Constructor()\n" 20607 " : a{a}\n" 20608 " , b{b} {}", 20609 Style); 20610 verifyFormat("SomeClass::Constructor()\n" 20611 " : a{a}\n" 20612 "#if CONDITION\n" 20613 " , b{b}\n" 20614 "#endif\n" 20615 "{\n}", 20616 Style); 20617 Style.ConstructorInitializerIndentWidth = 2; 20618 verifyFormat("SomeClass::Constructor()\n" 20619 "#if CONDITION\n" 20620 " : a{a}\n" 20621 "#endif\n" 20622 " , b{b}\n" 20623 " , c{c} {\n}", 20624 Style); 20625 Style.ConstructorInitializerIndentWidth = 0; 20626 verifyFormat("SomeClass::Constructor()\n" 20627 ": a{a}\n" 20628 "#ifdef CONDITION\n" 20629 ", b{b}\n" 20630 "#else\n" 20631 ", c{c}\n" 20632 "#endif\n" 20633 ", d{d} {\n}", 20634 Style); 20635 Style.ConstructorInitializerIndentWidth = 4; 20636 verifyFormat("SomeClass::Constructor()\n" 20637 " : a{a}\n" 20638 "#if WINDOWS\n" 20639 "#if DEBUG\n" 20640 " , b{0}\n" 20641 "#else\n" 20642 " , b{1}\n" 20643 "#endif\n" 20644 "#else\n" 20645 "#if DEBUG\n" 20646 " , b{2}\n" 20647 "#else\n" 20648 " , b{3}\n" 20649 "#endif\n" 20650 "#endif\n" 20651 "{\n}", 20652 Style); 20653 verifyFormat("SomeClass::Constructor()\n" 20654 " : a{a}\n" 20655 "#if WINDOWS\n" 20656 " , b{0}\n" 20657 "#if DEBUG\n" 20658 " , c{0}\n" 20659 "#else\n" 20660 " , c{1}\n" 20661 "#endif\n" 20662 "#else\n" 20663 "#if DEBUG\n" 20664 " , c{2}\n" 20665 "#else\n" 20666 " , c{3}\n" 20667 "#endif\n" 20668 " , b{1}\n" 20669 "#endif\n" 20670 "{\n}", 20671 Style); 20672 } 20673 20674 TEST_F(FormatTest, Destructors) { 20675 verifyFormat("void F(int &i) { i.~int(); }"); 20676 verifyFormat("void F(int &i) { i->~int(); }"); 20677 } 20678 20679 TEST_F(FormatTest, FormatsWithWebKitStyle) { 20680 FormatStyle Style = getWebKitStyle(); 20681 20682 // Don't indent in outer namespaces. 20683 verifyFormat("namespace outer {\n" 20684 "int i;\n" 20685 "namespace inner {\n" 20686 " int i;\n" 20687 "} // namespace inner\n" 20688 "} // namespace outer\n" 20689 "namespace other_outer {\n" 20690 "int i;\n" 20691 "}", 20692 Style); 20693 20694 // Don't indent case labels. 20695 verifyFormat("switch (variable) {\n" 20696 "case 1:\n" 20697 "case 2:\n" 20698 " doSomething();\n" 20699 " break;\n" 20700 "default:\n" 20701 " ++variable;\n" 20702 "}", 20703 Style); 20704 20705 // Wrap before binary operators. 20706 EXPECT_EQ("void f()\n" 20707 "{\n" 20708 " if (aaaaaaaaaaaaaaaa\n" 20709 " && bbbbbbbbbbbbbbbbbbbbbbbb\n" 20710 " && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n" 20711 " return;\n" 20712 "}", 20713 format("void f() {\n" 20714 "if (aaaaaaaaaaaaaaaa\n" 20715 "&& bbbbbbbbbbbbbbbbbbbbbbbb\n" 20716 "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n" 20717 "return;\n" 20718 "}", 20719 Style)); 20720 20721 // Allow functions on a single line. 20722 verifyFormat("void f() { return; }", Style); 20723 20724 // Allow empty blocks on a single line and insert a space in empty blocks. 20725 EXPECT_EQ("void f() { }", format("void f() {}", Style)); 20726 EXPECT_EQ("while (true) { }", format("while (true) {}", Style)); 20727 // However, don't merge non-empty short loops. 20728 EXPECT_EQ("while (true) {\n" 20729 " continue;\n" 20730 "}", 20731 format("while (true) { continue; }", Style)); 20732 20733 // Constructor initializers are formatted one per line with the "," on the 20734 // new line. 20735 verifyFormat("Constructor()\n" 20736 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 20737 " , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n" 20738 " aaaaaaaaaaaaaa)\n" 20739 " , aaaaaaaaaaaaaaaaaaaaaaa()\n" 20740 "{\n" 20741 "}", 20742 Style); 20743 verifyFormat("SomeClass::Constructor()\n" 20744 " : a(a)\n" 20745 "{\n" 20746 "}", 20747 Style); 20748 EXPECT_EQ("SomeClass::Constructor()\n" 20749 " : a(a)\n" 20750 "{\n" 20751 "}", 20752 format("SomeClass::Constructor():a(a){}", Style)); 20753 verifyFormat("SomeClass::Constructor()\n" 20754 " : a(a)\n" 20755 " , b(b)\n" 20756 " , c(c)\n" 20757 "{\n" 20758 "}", 20759 Style); 20760 verifyFormat("SomeClass::Constructor()\n" 20761 " : a(a)\n" 20762 "{\n" 20763 " foo();\n" 20764 " bar();\n" 20765 "}", 20766 Style); 20767 20768 // Access specifiers should be aligned left. 20769 verifyFormat("class C {\n" 20770 "public:\n" 20771 " int i;\n" 20772 "};", 20773 Style); 20774 20775 // Do not align comments. 20776 verifyFormat("int a; // Do not\n" 20777 "double b; // align comments.", 20778 Style); 20779 20780 // Do not align operands. 20781 EXPECT_EQ("ASSERT(aaaa\n" 20782 " || bbbb);", 20783 format("ASSERT ( aaaa\n||bbbb);", Style)); 20784 20785 // Accept input's line breaks. 20786 EXPECT_EQ("if (aaaaaaaaaaaaaaa\n" 20787 " || bbbbbbbbbbbbbbb) {\n" 20788 " i++;\n" 20789 "}", 20790 format("if (aaaaaaaaaaaaaaa\n" 20791 "|| bbbbbbbbbbbbbbb) { i++; }", 20792 Style)); 20793 EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n" 20794 " i++;\n" 20795 "}", 20796 format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style)); 20797 20798 // Don't automatically break all macro definitions (llvm.org/PR17842). 20799 verifyFormat("#define aNumber 10", Style); 20800 // However, generally keep the line breaks that the user authored. 20801 EXPECT_EQ("#define aNumber \\\n" 20802 " 10", 20803 format("#define aNumber \\\n" 20804 " 10", 20805 Style)); 20806 20807 // Keep empty and one-element array literals on a single line. 20808 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n" 20809 " copyItems:YES];", 20810 format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n" 20811 "copyItems:YES];", 20812 Style)); 20813 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n" 20814 " copyItems:YES];", 20815 format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n" 20816 " copyItems:YES];", 20817 Style)); 20818 // FIXME: This does not seem right, there should be more indentation before 20819 // the array literal's entries. Nested blocks have the same problem. 20820 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n" 20821 " @\"a\",\n" 20822 " @\"a\"\n" 20823 "]\n" 20824 " copyItems:YES];", 20825 format("NSArray* a = [[NSArray alloc] initWithArray:@[\n" 20826 " @\"a\",\n" 20827 " @\"a\"\n" 20828 " ]\n" 20829 " copyItems:YES];", 20830 Style)); 20831 EXPECT_EQ( 20832 "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n" 20833 " copyItems:YES];", 20834 format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n" 20835 " copyItems:YES];", 20836 Style)); 20837 20838 verifyFormat("[self.a b:c c:d];", Style); 20839 EXPECT_EQ("[self.a b:c\n" 20840 " c:d];", 20841 format("[self.a b:c\n" 20842 "c:d];", 20843 Style)); 20844 } 20845 20846 TEST_F(FormatTest, FormatsLambdas) { 20847 verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n"); 20848 verifyFormat( 20849 "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n"); 20850 verifyFormat("int c = [&] { [=] { return b++; }(); }();\n"); 20851 verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n"); 20852 verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n"); 20853 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n"); 20854 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n"); 20855 verifyFormat("auto c = [a = [b = 42] {}] {};\n"); 20856 verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n"); 20857 verifyFormat("int x = f(*+[] {});"); 20858 verifyFormat("void f() {\n" 20859 " other(x.begin(), x.end(), [&](int, int) { return 1; });\n" 20860 "}\n"); 20861 verifyFormat("void f() {\n" 20862 " other(x.begin(), //\n" 20863 " x.end(), //\n" 20864 " [&](int, int) { return 1; });\n" 20865 "}\n"); 20866 verifyFormat("void f() {\n" 20867 " other.other.other.other.other(\n" 20868 " x.begin(), x.end(),\n" 20869 " [something, rather](int, int, int, int, int, int, int) { " 20870 "return 1; });\n" 20871 "}\n"); 20872 verifyFormat( 20873 "void f() {\n" 20874 " other.other.other.other.other(\n" 20875 " x.begin(), x.end(),\n" 20876 " [something, rather](int, int, int, int, int, int, int) {\n" 20877 " //\n" 20878 " });\n" 20879 "}\n"); 20880 verifyFormat("SomeFunction([]() { // A cool function...\n" 20881 " return 43;\n" 20882 "});"); 20883 EXPECT_EQ("SomeFunction([]() {\n" 20884 "#define A a\n" 20885 " return 43;\n" 20886 "});", 20887 format("SomeFunction([](){\n" 20888 "#define A a\n" 20889 "return 43;\n" 20890 "});")); 20891 verifyFormat("void f() {\n" 20892 " SomeFunction([](decltype(x), A *a) {});\n" 20893 " SomeFunction([](typeof(x), A *a) {});\n" 20894 " SomeFunction([](_Atomic(x), A *a) {});\n" 20895 " SomeFunction([](__underlying_type(x), A *a) {});\n" 20896 "}"); 20897 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 20898 " [](const aaaaaaaaaa &a) { return a; });"); 20899 verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n" 20900 " SomeOtherFunctioooooooooooooooooooooooooon();\n" 20901 "});"); 20902 verifyFormat("Constructor()\n" 20903 " : Field([] { // comment\n" 20904 " int i;\n" 20905 " }) {}"); 20906 verifyFormat("auto my_lambda = [](const string &some_parameter) {\n" 20907 " return some_parameter.size();\n" 20908 "};"); 20909 verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n" 20910 " [](const string &s) { return s; };"); 20911 verifyFormat("int i = aaaaaa ? 1 //\n" 20912 " : [] {\n" 20913 " return 2; //\n" 20914 " }();"); 20915 verifyFormat("llvm::errs() << \"number of twos is \"\n" 20916 " << std::count_if(v.begin(), v.end(), [](int x) {\n" 20917 " return x == 2; // force break\n" 20918 " });"); 20919 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 20920 " [=](int iiiiiiiiiiii) {\n" 20921 " return aaaaaaaaaaaaaaaaaaaaaaa !=\n" 20922 " aaaaaaaaaaaaaaaaaaaaaaa;\n" 20923 " });", 20924 getLLVMStyleWithColumns(60)); 20925 20926 verifyFormat("SomeFunction({[&] {\n" 20927 " // comment\n" 20928 " },\n" 20929 " [&] {\n" 20930 " // comment\n" 20931 " }});"); 20932 verifyFormat("SomeFunction({[&] {\n" 20933 " // comment\n" 20934 "}});"); 20935 verifyFormat( 20936 "virtual aaaaaaaaaaaaaaaa(\n" 20937 " std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n" 20938 " aaaaa aaaaaaaaa);"); 20939 20940 // Lambdas with return types. 20941 verifyFormat("int c = []() -> int { return 2; }();\n"); 20942 verifyFormat("int c = []() -> int * { return 2; }();\n"); 20943 verifyFormat("int c = []() -> vector<int> { return {2}; }();\n"); 20944 verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());"); 20945 verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};"); 20946 verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};"); 20947 verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};"); 20948 verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};"); 20949 verifyFormat("[a, a]() -> a<1> {};"); 20950 verifyFormat("[]() -> foo<5 + 2> { return {}; };"); 20951 verifyFormat("[]() -> foo<5 - 2> { return {}; };"); 20952 verifyFormat("[]() -> foo<5 / 2> { return {}; };"); 20953 verifyFormat("[]() -> foo<5 * 2> { return {}; };"); 20954 verifyFormat("[]() -> foo<5 % 2> { return {}; };"); 20955 verifyFormat("[]() -> foo<5 << 2> { return {}; };"); 20956 verifyFormat("[]() -> foo<!5> { return {}; };"); 20957 verifyFormat("[]() -> foo<~5> { return {}; };"); 20958 verifyFormat("[]() -> foo<5 | 2> { return {}; };"); 20959 verifyFormat("[]() -> foo<5 || 2> { return {}; };"); 20960 verifyFormat("[]() -> foo<5 & 2> { return {}; };"); 20961 verifyFormat("[]() -> foo<5 && 2> { return {}; };"); 20962 verifyFormat("[]() -> foo<5 == 2> { return {}; };"); 20963 verifyFormat("[]() -> foo<5 != 2> { return {}; };"); 20964 verifyFormat("[]() -> foo<5 >= 2> { return {}; };"); 20965 verifyFormat("[]() -> foo<5 <= 2> { return {}; };"); 20966 verifyFormat("[]() -> foo<5 < 2> { return {}; };"); 20967 verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };"); 20968 verifyFormat("namespace bar {\n" 20969 "// broken:\n" 20970 "auto foo{[]() -> foo<5 + 2> { return {}; }};\n" 20971 "} // namespace bar"); 20972 verifyFormat("namespace bar {\n" 20973 "// broken:\n" 20974 "auto foo{[]() -> foo<5 - 2> { return {}; }};\n" 20975 "} // namespace bar"); 20976 verifyFormat("namespace bar {\n" 20977 "// broken:\n" 20978 "auto foo{[]() -> foo<5 / 2> { return {}; }};\n" 20979 "} // namespace bar"); 20980 verifyFormat("namespace bar {\n" 20981 "// broken:\n" 20982 "auto foo{[]() -> foo<5 * 2> { return {}; }};\n" 20983 "} // namespace bar"); 20984 verifyFormat("namespace bar {\n" 20985 "// broken:\n" 20986 "auto foo{[]() -> foo<5 % 2> { return {}; }};\n" 20987 "} // namespace bar"); 20988 verifyFormat("namespace bar {\n" 20989 "// broken:\n" 20990 "auto foo{[]() -> foo<5 << 2> { return {}; }};\n" 20991 "} // namespace bar"); 20992 verifyFormat("namespace bar {\n" 20993 "// broken:\n" 20994 "auto foo{[]() -> foo<!5> { return {}; }};\n" 20995 "} // namespace bar"); 20996 verifyFormat("namespace bar {\n" 20997 "// broken:\n" 20998 "auto foo{[]() -> foo<~5> { return {}; }};\n" 20999 "} // namespace bar"); 21000 verifyFormat("namespace bar {\n" 21001 "// broken:\n" 21002 "auto foo{[]() -> foo<5 | 2> { return {}; }};\n" 21003 "} // namespace bar"); 21004 verifyFormat("namespace bar {\n" 21005 "// broken:\n" 21006 "auto foo{[]() -> foo<5 || 2> { return {}; }};\n" 21007 "} // namespace bar"); 21008 verifyFormat("namespace bar {\n" 21009 "// broken:\n" 21010 "auto foo{[]() -> foo<5 & 2> { return {}; }};\n" 21011 "} // namespace bar"); 21012 verifyFormat("namespace bar {\n" 21013 "// broken:\n" 21014 "auto foo{[]() -> foo<5 && 2> { return {}; }};\n" 21015 "} // namespace bar"); 21016 verifyFormat("namespace bar {\n" 21017 "// broken:\n" 21018 "auto foo{[]() -> foo<5 == 2> { return {}; }};\n" 21019 "} // namespace bar"); 21020 verifyFormat("namespace bar {\n" 21021 "// broken:\n" 21022 "auto foo{[]() -> foo<5 != 2> { return {}; }};\n" 21023 "} // namespace bar"); 21024 verifyFormat("namespace bar {\n" 21025 "// broken:\n" 21026 "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n" 21027 "} // namespace bar"); 21028 verifyFormat("namespace bar {\n" 21029 "// broken:\n" 21030 "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n" 21031 "} // namespace bar"); 21032 verifyFormat("namespace bar {\n" 21033 "// broken:\n" 21034 "auto foo{[]() -> foo<5 < 2> { return {}; }};\n" 21035 "} // namespace bar"); 21036 verifyFormat("namespace bar {\n" 21037 "// broken:\n" 21038 "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n" 21039 "} // namespace bar"); 21040 verifyFormat("[]() -> a<1> {};"); 21041 verifyFormat("[]() -> a<1> { ; };"); 21042 verifyFormat("[]() -> a<1> { ; }();"); 21043 verifyFormat("[a, a]() -> a<true> {};"); 21044 verifyFormat("[]() -> a<true> {};"); 21045 verifyFormat("[]() -> a<true> { ; };"); 21046 verifyFormat("[]() -> a<true> { ; }();"); 21047 verifyFormat("[a, a]() -> a<false> {};"); 21048 verifyFormat("[]() -> a<false> {};"); 21049 verifyFormat("[]() -> a<false> { ; };"); 21050 verifyFormat("[]() -> a<false> { ; }();"); 21051 verifyFormat("auto foo{[]() -> foo<false> { ; }};"); 21052 verifyFormat("namespace bar {\n" 21053 "auto foo{[]() -> foo<false> { ; }};\n" 21054 "} // namespace bar"); 21055 verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n" 21056 " int j) -> int {\n" 21057 " return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n" 21058 "};"); 21059 verifyFormat( 21060 "aaaaaaaaaaaaaaaaaaaaaa(\n" 21061 " [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n" 21062 " return aaaaaaaaaaaaaaaaa;\n" 21063 " });", 21064 getLLVMStyleWithColumns(70)); 21065 verifyFormat("[]() //\n" 21066 " -> int {\n" 21067 " return 1; //\n" 21068 "};"); 21069 verifyFormat("[]() -> Void<T...> {};"); 21070 verifyFormat("[a, b]() -> Tuple<T...> { return {}; };"); 21071 verifyFormat("SomeFunction({[]() -> int[] { return {}; }});"); 21072 verifyFormat("SomeFunction({[]() -> int *[] { return {}; }});"); 21073 verifyFormat("SomeFunction({[]() -> int (*)[] { return {}; }});"); 21074 verifyFormat("SomeFunction({[]() -> ns::type<int (*)[]> { return {}; }});"); 21075 verifyFormat("return int{[x = x]() { return x; }()};"); 21076 21077 // Lambdas with explicit template argument lists. 21078 verifyFormat( 21079 "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n"); 21080 verifyFormat("auto L = []<class T>(T) {\n" 21081 " {\n" 21082 " f();\n" 21083 " g();\n" 21084 " }\n" 21085 "};\n"); 21086 verifyFormat("auto L = []<class... T>(T...) {\n" 21087 " {\n" 21088 " f();\n" 21089 " g();\n" 21090 " }\n" 21091 "};\n"); 21092 verifyFormat("auto L = []<typename... T>(T...) {\n" 21093 " {\n" 21094 " f();\n" 21095 " g();\n" 21096 " }\n" 21097 "};\n"); 21098 verifyFormat("auto L = []<template <typename...> class T>(T...) {\n" 21099 " {\n" 21100 " f();\n" 21101 " g();\n" 21102 " }\n" 21103 "};\n"); 21104 verifyFormat("auto L = []</*comment*/ class... T>(T...) {\n" 21105 " {\n" 21106 " f();\n" 21107 " g();\n" 21108 " }\n" 21109 "};\n"); 21110 21111 // Multiple lambdas in the same parentheses change indentation rules. These 21112 // lambdas are forced to start on new lines. 21113 verifyFormat("SomeFunction(\n" 21114 " []() {\n" 21115 " //\n" 21116 " },\n" 21117 " []() {\n" 21118 " //\n" 21119 " });"); 21120 21121 // A lambda passed as arg0 is always pushed to the next line. 21122 verifyFormat("SomeFunction(\n" 21123 " [this] {\n" 21124 " //\n" 21125 " },\n" 21126 " 1);\n"); 21127 21128 // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like 21129 // the arg0 case above. 21130 auto Style = getGoogleStyle(); 21131 Style.BinPackArguments = false; 21132 verifyFormat("SomeFunction(\n" 21133 " a,\n" 21134 " [this] {\n" 21135 " //\n" 21136 " },\n" 21137 " b);\n", 21138 Style); 21139 verifyFormat("SomeFunction(\n" 21140 " a,\n" 21141 " [this] {\n" 21142 " //\n" 21143 " },\n" 21144 " b);\n"); 21145 21146 // A lambda with a very long line forces arg0 to be pushed out irrespective of 21147 // the BinPackArguments value (as long as the code is wide enough). 21148 verifyFormat( 21149 "something->SomeFunction(\n" 21150 " a,\n" 21151 " [this] {\n" 21152 " " 21153 "D0000000000000000000000000000000000000000000000000000000000001();\n" 21154 " },\n" 21155 " b);\n"); 21156 21157 // A multi-line lambda is pulled up as long as the introducer fits on the 21158 // previous line and there are no further args. 21159 verifyFormat("function(1, [this, that] {\n" 21160 " //\n" 21161 "});\n"); 21162 verifyFormat("function([this, that] {\n" 21163 " //\n" 21164 "});\n"); 21165 // FIXME: this format is not ideal and we should consider forcing the first 21166 // arg onto its own line. 21167 verifyFormat("function(a, b, c, //\n" 21168 " d, [this, that] {\n" 21169 " //\n" 21170 " });\n"); 21171 21172 // Multiple lambdas are treated correctly even when there is a short arg0. 21173 verifyFormat("SomeFunction(\n" 21174 " 1,\n" 21175 " [this] {\n" 21176 " //\n" 21177 " },\n" 21178 " [this] {\n" 21179 " //\n" 21180 " },\n" 21181 " 1);\n"); 21182 21183 // More complex introducers. 21184 verifyFormat("return [i, args...] {};"); 21185 21186 // Not lambdas. 21187 verifyFormat("constexpr char hello[]{\"hello\"};"); 21188 verifyFormat("double &operator[](int i) { return 0; }\n" 21189 "int i;"); 21190 verifyFormat("std::unique_ptr<int[]> foo() {}"); 21191 verifyFormat("int i = a[a][a]->f();"); 21192 verifyFormat("int i = (*b)[a]->f();"); 21193 21194 // Other corner cases. 21195 verifyFormat("void f() {\n" 21196 " bar([]() {} // Did not respect SpacesBeforeTrailingComments\n" 21197 " );\n" 21198 "}"); 21199 21200 // Lambdas created through weird macros. 21201 verifyFormat("void f() {\n" 21202 " MACRO((const AA &a) { return 1; });\n" 21203 " MACRO((AA &a) { return 1; });\n" 21204 "}"); 21205 21206 verifyFormat("if (blah_blah(whatever, whatever, [] {\n" 21207 " doo_dah();\n" 21208 " doo_dah();\n" 21209 " })) {\n" 21210 "}"); 21211 verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n" 21212 " doo_dah();\n" 21213 " doo_dah();\n" 21214 " })) {\n" 21215 "}"); 21216 verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n" 21217 " doo_dah();\n" 21218 " doo_dah();\n" 21219 " })) {\n" 21220 "}"); 21221 verifyFormat("auto lambda = []() {\n" 21222 " int a = 2\n" 21223 "#if A\n" 21224 " + 2\n" 21225 "#endif\n" 21226 " ;\n" 21227 "};"); 21228 21229 // Lambdas with complex multiline introducers. 21230 verifyFormat( 21231 "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 21232 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n" 21233 " -> ::std::unordered_set<\n" 21234 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n" 21235 " //\n" 21236 " });"); 21237 21238 FormatStyle DoNotMerge = getLLVMStyle(); 21239 DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 21240 verifyFormat("auto c = []() {\n" 21241 " return b;\n" 21242 "};", 21243 "auto c = []() { return b; };", DoNotMerge); 21244 verifyFormat("auto c = []() {\n" 21245 "};", 21246 " auto c = []() {};", DoNotMerge); 21247 21248 FormatStyle MergeEmptyOnly = getLLVMStyle(); 21249 MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty; 21250 verifyFormat("auto c = []() {\n" 21251 " return b;\n" 21252 "};", 21253 "auto c = []() {\n" 21254 " return b;\n" 21255 " };", 21256 MergeEmptyOnly); 21257 verifyFormat("auto c = []() {};", 21258 "auto c = []() {\n" 21259 "};", 21260 MergeEmptyOnly); 21261 21262 FormatStyle MergeInline = getLLVMStyle(); 21263 MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline; 21264 verifyFormat("auto c = []() {\n" 21265 " return b;\n" 21266 "};", 21267 "auto c = []() { return b; };", MergeInline); 21268 verifyFormat("function([]() { return b; })", "function([]() { return b; })", 21269 MergeInline); 21270 verifyFormat("function([]() { return b; }, a)", 21271 "function([]() { return b; }, a)", MergeInline); 21272 verifyFormat("function(a, []() { return b; })", 21273 "function(a, []() { return b; })", MergeInline); 21274 21275 // Check option "BraceWrapping.BeforeLambdaBody" and different state of 21276 // AllowShortLambdasOnASingleLine 21277 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle(); 21278 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 21279 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 21280 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21281 FormatStyle::ShortLambdaStyle::SLS_None; 21282 verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n" 21283 " []()\n" 21284 " {\n" 21285 " return 17;\n" 21286 " });", 21287 LLVMWithBeforeLambdaBody); 21288 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n" 21289 " []()\n" 21290 " {\n" 21291 " });", 21292 LLVMWithBeforeLambdaBody); 21293 verifyFormat("auto fct_SLS_None = []()\n" 21294 "{\n" 21295 " return 17;\n" 21296 "};", 21297 LLVMWithBeforeLambdaBody); 21298 verifyFormat("TwoNestedLambdas_SLS_None(\n" 21299 " []()\n" 21300 " {\n" 21301 " return Call(\n" 21302 " []()\n" 21303 " {\n" 21304 " return 17;\n" 21305 " });\n" 21306 " });", 21307 LLVMWithBeforeLambdaBody); 21308 verifyFormat("void Fct() {\n" 21309 " return {[]()\n" 21310 " {\n" 21311 " return 17;\n" 21312 " }};\n" 21313 "}", 21314 LLVMWithBeforeLambdaBody); 21315 21316 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21317 FormatStyle::ShortLambdaStyle::SLS_Empty; 21318 verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n" 21319 " []()\n" 21320 " {\n" 21321 " return 17;\n" 21322 " });", 21323 LLVMWithBeforeLambdaBody); 21324 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});", 21325 LLVMWithBeforeLambdaBody); 21326 verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL" 21327 "ongFunctionName_SLS_Empty(\n" 21328 " []() {});", 21329 LLVMWithBeforeLambdaBody); 21330 verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n" 21331 " []()\n" 21332 " {\n" 21333 " return 17;\n" 21334 " });", 21335 LLVMWithBeforeLambdaBody); 21336 verifyFormat("auto fct_SLS_Empty = []()\n" 21337 "{\n" 21338 " return 17;\n" 21339 "};", 21340 LLVMWithBeforeLambdaBody); 21341 verifyFormat("TwoNestedLambdas_SLS_Empty(\n" 21342 " []()\n" 21343 " {\n" 21344 " return Call([]() {});\n" 21345 " });", 21346 LLVMWithBeforeLambdaBody); 21347 verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n" 21348 " []()\n" 21349 " {\n" 21350 " return Call([]() {});\n" 21351 " });", 21352 LLVMWithBeforeLambdaBody); 21353 verifyFormat( 21354 "FctWithLongLineInLambda_SLS_Empty(\n" 21355 " []()\n" 21356 " {\n" 21357 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21358 " AndShouldNotBeConsiderAsInline,\n" 21359 " LambdaBodyMustBeBreak);\n" 21360 " });", 21361 LLVMWithBeforeLambdaBody); 21362 21363 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21364 FormatStyle::ShortLambdaStyle::SLS_Inline; 21365 verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });", 21366 LLVMWithBeforeLambdaBody); 21367 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});", 21368 LLVMWithBeforeLambdaBody); 21369 verifyFormat("auto fct_SLS_Inline = []()\n" 21370 "{\n" 21371 " return 17;\n" 21372 "};", 21373 LLVMWithBeforeLambdaBody); 21374 verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return " 21375 "17; }); });", 21376 LLVMWithBeforeLambdaBody); 21377 verifyFormat( 21378 "FctWithLongLineInLambda_SLS_Inline(\n" 21379 " []()\n" 21380 " {\n" 21381 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21382 " AndShouldNotBeConsiderAsInline,\n" 21383 " LambdaBodyMustBeBreak);\n" 21384 " });", 21385 LLVMWithBeforeLambdaBody); 21386 verifyFormat("FctWithMultipleParams_SLS_Inline(" 21387 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n" 21388 " []() { return 17; });", 21389 LLVMWithBeforeLambdaBody); 21390 verifyFormat( 21391 "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });", 21392 LLVMWithBeforeLambdaBody); 21393 21394 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21395 FormatStyle::ShortLambdaStyle::SLS_All; 21396 verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });", 21397 LLVMWithBeforeLambdaBody); 21398 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});", 21399 LLVMWithBeforeLambdaBody); 21400 verifyFormat("auto fct_SLS_All = []() { return 17; };", 21401 LLVMWithBeforeLambdaBody); 21402 verifyFormat("FctWithOneParam_SLS_All(\n" 21403 " []()\n" 21404 " {\n" 21405 " // A cool function...\n" 21406 " return 43;\n" 21407 " });", 21408 LLVMWithBeforeLambdaBody); 21409 verifyFormat("FctWithMultipleParams_SLS_All(" 21410 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n" 21411 " []() { return 17; });", 21412 LLVMWithBeforeLambdaBody); 21413 verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });", 21414 LLVMWithBeforeLambdaBody); 21415 verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });", 21416 LLVMWithBeforeLambdaBody); 21417 verifyFormat( 21418 "FctWithLongLineInLambda_SLS_All(\n" 21419 " []()\n" 21420 " {\n" 21421 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21422 " AndShouldNotBeConsiderAsInline,\n" 21423 " LambdaBodyMustBeBreak);\n" 21424 " });", 21425 LLVMWithBeforeLambdaBody); 21426 verifyFormat( 21427 "auto fct_SLS_All = []()\n" 21428 "{\n" 21429 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21430 " AndShouldNotBeConsiderAsInline,\n" 21431 " LambdaBodyMustBeBreak);\n" 21432 "};", 21433 LLVMWithBeforeLambdaBody); 21434 LLVMWithBeforeLambdaBody.BinPackParameters = false; 21435 verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);", 21436 LLVMWithBeforeLambdaBody); 21437 verifyFormat( 21438 "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n" 21439 " FirstParam,\n" 21440 " SecondParam,\n" 21441 " ThirdParam,\n" 21442 " FourthParam);", 21443 LLVMWithBeforeLambdaBody); 21444 verifyFormat("FctWithLongLineInLambda_SLS_All(\n" 21445 " []() { return " 21446 "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n" 21447 " FirstParam,\n" 21448 " SecondParam,\n" 21449 " ThirdParam,\n" 21450 " FourthParam);", 21451 LLVMWithBeforeLambdaBody); 21452 verifyFormat( 21453 "FctWithLongLineInLambda_SLS_All(FirstParam,\n" 21454 " SecondParam,\n" 21455 " ThirdParam,\n" 21456 " FourthParam,\n" 21457 " []() { return SomeValueNotSoLong; });", 21458 LLVMWithBeforeLambdaBody); 21459 verifyFormat("FctWithLongLineInLambda_SLS_All(\n" 21460 " []()\n" 21461 " {\n" 21462 " return " 21463 "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB" 21464 "eConsiderAsInline;\n" 21465 " });", 21466 LLVMWithBeforeLambdaBody); 21467 verifyFormat( 21468 "FctWithLongLineInLambda_SLS_All(\n" 21469 " []()\n" 21470 " {\n" 21471 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 21472 " AndShouldNotBeConsiderAsInline,\n" 21473 " LambdaBodyMustBeBreak);\n" 21474 " });", 21475 LLVMWithBeforeLambdaBody); 21476 verifyFormat("FctWithTwoParams_SLS_All(\n" 21477 " []()\n" 21478 " {\n" 21479 " // A cool function...\n" 21480 " return 43;\n" 21481 " },\n" 21482 " 87);", 21483 LLVMWithBeforeLambdaBody); 21484 verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);", 21485 LLVMWithBeforeLambdaBody); 21486 verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });", 21487 LLVMWithBeforeLambdaBody); 21488 verifyFormat( 21489 "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });", 21490 LLVMWithBeforeLambdaBody); 21491 verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; " 21492 "}); }, x);", 21493 LLVMWithBeforeLambdaBody); 21494 verifyFormat("TwoNestedLambdas_SLS_All(\n" 21495 " []()\n" 21496 " {\n" 21497 " // A cool function...\n" 21498 " return Call([]() { return 17; });\n" 21499 " });", 21500 LLVMWithBeforeLambdaBody); 21501 verifyFormat("TwoNestedLambdas_SLS_All(\n" 21502 " []()\n" 21503 " {\n" 21504 " return Call(\n" 21505 " []()\n" 21506 " {\n" 21507 " // A cool function...\n" 21508 " return 17;\n" 21509 " });\n" 21510 " });", 21511 LLVMWithBeforeLambdaBody); 21512 21513 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21514 FormatStyle::ShortLambdaStyle::SLS_None; 21515 21516 verifyFormat("auto select = [this]() -> const Library::Object *\n" 21517 "{\n" 21518 " return MyAssignment::SelectFromList(this);\n" 21519 "};\n", 21520 LLVMWithBeforeLambdaBody); 21521 21522 verifyFormat("auto select = [this]() -> const Library::Object &\n" 21523 "{\n" 21524 " return MyAssignment::SelectFromList(this);\n" 21525 "};\n", 21526 LLVMWithBeforeLambdaBody); 21527 21528 verifyFormat("auto select = [this]() -> std::unique_ptr<Object>\n" 21529 "{\n" 21530 " return MyAssignment::SelectFromList(this);\n" 21531 "};\n", 21532 LLVMWithBeforeLambdaBody); 21533 21534 verifyFormat("namespace test {\n" 21535 "class Test {\n" 21536 "public:\n" 21537 " Test() = default;\n" 21538 "};\n" 21539 "} // namespace test", 21540 LLVMWithBeforeLambdaBody); 21541 21542 // Lambdas with different indentation styles. 21543 Style = getLLVMStyleWithColumns(100); 21544 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 21545 " return promise.then(\n" 21546 " [this, &someVariable, someObject = " 21547 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21548 " return someObject.startAsyncAction().then(\n" 21549 " [this, &someVariable](AsyncActionResult result) " 21550 "mutable { result.processMore(); });\n" 21551 " });\n" 21552 "}\n", 21553 format("SomeResult doSomething(SomeObject promise) {\n" 21554 " return promise.then([this, &someVariable, someObject = " 21555 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21556 " return someObject.startAsyncAction().then([this, " 21557 "&someVariable](AsyncActionResult result) mutable {\n" 21558 " result.processMore();\n" 21559 " });\n" 21560 " });\n" 21561 "}\n", 21562 Style)); 21563 Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope; 21564 verifyFormat("test() {\n" 21565 " ([]() -> {\n" 21566 " int b = 32;\n" 21567 " return 3;\n" 21568 " }).foo();\n" 21569 "}", 21570 Style); 21571 verifyFormat("test() {\n" 21572 " []() -> {\n" 21573 " int b = 32;\n" 21574 " return 3;\n" 21575 " }\n" 21576 "}", 21577 Style); 21578 verifyFormat("std::sort(v.begin(), v.end(),\n" 21579 " [](const auto &someLongArgumentName, const auto " 21580 "&someOtherLongArgumentName) {\n" 21581 " return someLongArgumentName.someMemberVariable < " 21582 "someOtherLongArgumentName.someMemberVariable;\n" 21583 "});", 21584 Style); 21585 verifyFormat("test() {\n" 21586 " (\n" 21587 " []() -> {\n" 21588 " int b = 32;\n" 21589 " return 3;\n" 21590 " },\n" 21591 " foo, bar)\n" 21592 " .foo();\n" 21593 "}", 21594 Style); 21595 verifyFormat("test() {\n" 21596 " ([]() -> {\n" 21597 " int b = 32;\n" 21598 " return 3;\n" 21599 " })\n" 21600 " .foo()\n" 21601 " .bar();\n" 21602 "}", 21603 Style); 21604 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 21605 " return promise.then(\n" 21606 " [this, &someVariable, someObject = " 21607 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21608 " return someObject.startAsyncAction().then(\n" 21609 " [this, &someVariable](AsyncActionResult result) mutable { " 21610 "result.processMore(); });\n" 21611 " });\n" 21612 "}\n", 21613 format("SomeResult doSomething(SomeObject promise) {\n" 21614 " return promise.then([this, &someVariable, someObject = " 21615 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 21616 " return someObject.startAsyncAction().then([this, " 21617 "&someVariable](AsyncActionResult result) mutable {\n" 21618 " result.processMore();\n" 21619 " });\n" 21620 " });\n" 21621 "}\n", 21622 Style)); 21623 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 21624 " return promise.then([this, &someVariable] {\n" 21625 " return someObject.startAsyncAction().then(\n" 21626 " [this, &someVariable](AsyncActionResult result) mutable { " 21627 "result.processMore(); });\n" 21628 " });\n" 21629 "}\n", 21630 format("SomeResult doSomething(SomeObject promise) {\n" 21631 " return promise.then([this, &someVariable] {\n" 21632 " return someObject.startAsyncAction().then([this, " 21633 "&someVariable](AsyncActionResult result) mutable {\n" 21634 " result.processMore();\n" 21635 " });\n" 21636 " });\n" 21637 "}\n", 21638 Style)); 21639 Style = getGoogleStyle(); 21640 Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope; 21641 EXPECT_EQ("#define A \\\n" 21642 " [] { \\\n" 21643 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 21644 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n" 21645 " }", 21646 format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 21647 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }", 21648 Style)); 21649 // TODO: The current formatting has a minor issue that's not worth fixing 21650 // right now whereby the closing brace is indented relative to the signature 21651 // instead of being aligned. This only happens with macros. 21652 } 21653 21654 TEST_F(FormatTest, LambdaWithLineComments) { 21655 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle(); 21656 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 21657 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 21658 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 21659 FormatStyle::ShortLambdaStyle::SLS_All; 21660 21661 verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody); 21662 verifyFormat("auto k = []() // comment\n" 21663 "{ return; }", 21664 LLVMWithBeforeLambdaBody); 21665 verifyFormat("auto k = []() /* comment */ { return; }", 21666 LLVMWithBeforeLambdaBody); 21667 verifyFormat("auto k = []() /* comment */ /* comment */ { return; }", 21668 LLVMWithBeforeLambdaBody); 21669 verifyFormat("auto k = []() // X\n" 21670 "{ return; }", 21671 LLVMWithBeforeLambdaBody); 21672 verifyFormat( 21673 "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" 21674 "{ return; }", 21675 LLVMWithBeforeLambdaBody); 21676 } 21677 21678 TEST_F(FormatTest, EmptyLinesInLambdas) { 21679 verifyFormat("auto lambda = []() {\n" 21680 " x(); //\n" 21681 "};", 21682 "auto lambda = []() {\n" 21683 "\n" 21684 " x(); //\n" 21685 "\n" 21686 "};"); 21687 } 21688 21689 TEST_F(FormatTest, FormatsBlocks) { 21690 FormatStyle ShortBlocks = getLLVMStyle(); 21691 ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 21692 verifyFormat("int (^Block)(int, int);", ShortBlocks); 21693 verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks); 21694 verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks); 21695 verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks); 21696 verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks); 21697 verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks); 21698 21699 verifyFormat("foo(^{ bar(); });", ShortBlocks); 21700 verifyFormat("foo(a, ^{ bar(); });", ShortBlocks); 21701 verifyFormat("{ void (^block)(Object *x); }", ShortBlocks); 21702 21703 verifyFormat("[operation setCompletionBlock:^{\n" 21704 " [self onOperationDone];\n" 21705 "}];"); 21706 verifyFormat("int i = {[operation setCompletionBlock:^{\n" 21707 " [self onOperationDone];\n" 21708 "}]};"); 21709 verifyFormat("[operation setCompletionBlock:^(int *i) {\n" 21710 " f();\n" 21711 "}];"); 21712 verifyFormat("int a = [operation block:^int(int *i) {\n" 21713 " return 1;\n" 21714 "}];"); 21715 verifyFormat("[myObject doSomethingWith:arg1\n" 21716 " aaa:^int(int *a) {\n" 21717 " return 1;\n" 21718 " }\n" 21719 " bbb:f(a * bbbbbbbb)];"); 21720 21721 verifyFormat("[operation setCompletionBlock:^{\n" 21722 " [self.delegate newDataAvailable];\n" 21723 "}];", 21724 getLLVMStyleWithColumns(60)); 21725 verifyFormat("dispatch_async(_fileIOQueue, ^{\n" 21726 " NSString *path = [self sessionFilePath];\n" 21727 " if (path) {\n" 21728 " // ...\n" 21729 " }\n" 21730 "});"); 21731 verifyFormat("[[SessionService sharedService]\n" 21732 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 21733 " if (window) {\n" 21734 " [self windowDidLoad:window];\n" 21735 " } else {\n" 21736 " [self errorLoadingWindow];\n" 21737 " }\n" 21738 " }];"); 21739 verifyFormat("void (^largeBlock)(void) = ^{\n" 21740 " // ...\n" 21741 "};\n", 21742 getLLVMStyleWithColumns(40)); 21743 verifyFormat("[[SessionService sharedService]\n" 21744 " loadWindowWithCompletionBlock: //\n" 21745 " ^(SessionWindow *window) {\n" 21746 " if (window) {\n" 21747 " [self windowDidLoad:window];\n" 21748 " } else {\n" 21749 " [self errorLoadingWindow];\n" 21750 " }\n" 21751 " }];", 21752 getLLVMStyleWithColumns(60)); 21753 verifyFormat("[myObject doSomethingWith:arg1\n" 21754 " firstBlock:^(Foo *a) {\n" 21755 " // ...\n" 21756 " int i;\n" 21757 " }\n" 21758 " secondBlock:^(Bar *b) {\n" 21759 " // ...\n" 21760 " int i;\n" 21761 " }\n" 21762 " thirdBlock:^Foo(Bar *b) {\n" 21763 " // ...\n" 21764 " int i;\n" 21765 " }];"); 21766 verifyFormat("[myObject doSomethingWith:arg1\n" 21767 " firstBlock:-1\n" 21768 " secondBlock:^(Bar *b) {\n" 21769 " // ...\n" 21770 " int i;\n" 21771 " }];"); 21772 21773 verifyFormat("f(^{\n" 21774 " @autoreleasepool {\n" 21775 " if (a) {\n" 21776 " g();\n" 21777 " }\n" 21778 " }\n" 21779 "});"); 21780 verifyFormat("Block b = ^int *(A *a, B *b) {}"); 21781 verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n" 21782 "};"); 21783 21784 FormatStyle FourIndent = getLLVMStyle(); 21785 FourIndent.ObjCBlockIndentWidth = 4; 21786 verifyFormat("[operation setCompletionBlock:^{\n" 21787 " [self onOperationDone];\n" 21788 "}];", 21789 FourIndent); 21790 } 21791 21792 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) { 21793 FormatStyle ZeroColumn = getLLVMStyleWithColumns(0); 21794 21795 verifyFormat("[[SessionService sharedService] " 21796 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 21797 " if (window) {\n" 21798 " [self windowDidLoad:window];\n" 21799 " } else {\n" 21800 " [self errorLoadingWindow];\n" 21801 " }\n" 21802 "}];", 21803 ZeroColumn); 21804 EXPECT_EQ("[[SessionService sharedService]\n" 21805 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 21806 " if (window) {\n" 21807 " [self windowDidLoad:window];\n" 21808 " } else {\n" 21809 " [self errorLoadingWindow];\n" 21810 " }\n" 21811 " }];", 21812 format("[[SessionService sharedService]\n" 21813 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 21814 " if (window) {\n" 21815 " [self windowDidLoad:window];\n" 21816 " } else {\n" 21817 " [self errorLoadingWindow];\n" 21818 " }\n" 21819 "}];", 21820 ZeroColumn)); 21821 verifyFormat("[myObject doSomethingWith:arg1\n" 21822 " firstBlock:^(Foo *a) {\n" 21823 " // ...\n" 21824 " int i;\n" 21825 " }\n" 21826 " secondBlock:^(Bar *b) {\n" 21827 " // ...\n" 21828 " int i;\n" 21829 " }\n" 21830 " thirdBlock:^Foo(Bar *b) {\n" 21831 " // ...\n" 21832 " int i;\n" 21833 " }];", 21834 ZeroColumn); 21835 verifyFormat("f(^{\n" 21836 " @autoreleasepool {\n" 21837 " if (a) {\n" 21838 " g();\n" 21839 " }\n" 21840 " }\n" 21841 "});", 21842 ZeroColumn); 21843 verifyFormat("void (^largeBlock)(void) = ^{\n" 21844 " // ...\n" 21845 "};", 21846 ZeroColumn); 21847 21848 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 21849 EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };", 21850 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn)); 21851 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 21852 EXPECT_EQ("void (^largeBlock)(void) = ^{\n" 21853 " int i;\n" 21854 "};", 21855 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn)); 21856 } 21857 21858 TEST_F(FormatTest, SupportsCRLF) { 21859 EXPECT_EQ("int a;\r\n" 21860 "int b;\r\n" 21861 "int c;\r\n", 21862 format("int a;\r\n" 21863 " int b;\r\n" 21864 " int c;\r\n", 21865 getLLVMStyle())); 21866 EXPECT_EQ("int a;\r\n" 21867 "int b;\r\n" 21868 "int c;\r\n", 21869 format("int a;\r\n" 21870 " int b;\n" 21871 " int c;\r\n", 21872 getLLVMStyle())); 21873 EXPECT_EQ("int a;\n" 21874 "int b;\n" 21875 "int c;\n", 21876 format("int a;\r\n" 21877 " int b;\n" 21878 " int c;\n", 21879 getLLVMStyle())); 21880 EXPECT_EQ("\"aaaaaaa \"\r\n" 21881 "\"bbbbbbb\";\r\n", 21882 format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10))); 21883 EXPECT_EQ("#define A \\\r\n" 21884 " b; \\\r\n" 21885 " c; \\\r\n" 21886 " d;\r\n", 21887 format("#define A \\\r\n" 21888 " b; \\\r\n" 21889 " c; d; \r\n", 21890 getGoogleStyle())); 21891 21892 EXPECT_EQ("/*\r\n" 21893 "multi line block comments\r\n" 21894 "should not introduce\r\n" 21895 "an extra carriage return\r\n" 21896 "*/\r\n", 21897 format("/*\r\n" 21898 "multi line block comments\r\n" 21899 "should not introduce\r\n" 21900 "an extra carriage return\r\n" 21901 "*/\r\n")); 21902 EXPECT_EQ("/*\r\n" 21903 "\r\n" 21904 "*/", 21905 format("/*\r\n" 21906 " \r\r\r\n" 21907 "*/")); 21908 21909 FormatStyle style = getLLVMStyle(); 21910 21911 style.DeriveLineEnding = true; 21912 style.UseCRLF = false; 21913 EXPECT_EQ("union FooBarBazQux {\n" 21914 " int foo;\n" 21915 " int bar;\n" 21916 " int baz;\n" 21917 "};", 21918 format("union FooBarBazQux {\r\n" 21919 " int foo;\n" 21920 " int bar;\r\n" 21921 " int baz;\n" 21922 "};", 21923 style)); 21924 style.UseCRLF = true; 21925 EXPECT_EQ("union FooBarBazQux {\r\n" 21926 " int foo;\r\n" 21927 " int bar;\r\n" 21928 " int baz;\r\n" 21929 "};", 21930 format("union FooBarBazQux {\r\n" 21931 " int foo;\n" 21932 " int bar;\r\n" 21933 " int baz;\n" 21934 "};", 21935 style)); 21936 21937 style.DeriveLineEnding = false; 21938 style.UseCRLF = false; 21939 EXPECT_EQ("union FooBarBazQux {\n" 21940 " int foo;\n" 21941 " int bar;\n" 21942 " int baz;\n" 21943 " int qux;\n" 21944 "};", 21945 format("union FooBarBazQux {\r\n" 21946 " int foo;\n" 21947 " int bar;\r\n" 21948 " int baz;\n" 21949 " int qux;\r\n" 21950 "};", 21951 style)); 21952 style.UseCRLF = true; 21953 EXPECT_EQ("union FooBarBazQux {\r\n" 21954 " int foo;\r\n" 21955 " int bar;\r\n" 21956 " int baz;\r\n" 21957 " int qux;\r\n" 21958 "};", 21959 format("union FooBarBazQux {\r\n" 21960 " int foo;\n" 21961 " int bar;\r\n" 21962 " int baz;\n" 21963 " int qux;\n" 21964 "};", 21965 style)); 21966 21967 style.DeriveLineEnding = true; 21968 style.UseCRLF = false; 21969 EXPECT_EQ("union FooBarBazQux {\r\n" 21970 " int foo;\r\n" 21971 " int bar;\r\n" 21972 " int baz;\r\n" 21973 " int qux;\r\n" 21974 "};", 21975 format("union FooBarBazQux {\r\n" 21976 " int foo;\n" 21977 " int bar;\r\n" 21978 " int baz;\n" 21979 " int qux;\r\n" 21980 "};", 21981 style)); 21982 style.UseCRLF = true; 21983 EXPECT_EQ("union FooBarBazQux {\n" 21984 " int foo;\n" 21985 " int bar;\n" 21986 " int baz;\n" 21987 " int qux;\n" 21988 "};", 21989 format("union FooBarBazQux {\r\n" 21990 " int foo;\n" 21991 " int bar;\r\n" 21992 " int baz;\n" 21993 " int qux;\n" 21994 "};", 21995 style)); 21996 } 21997 21998 TEST_F(FormatTest, MunchSemicolonAfterBlocks) { 21999 verifyFormat("MY_CLASS(C) {\n" 22000 " int i;\n" 22001 " int j;\n" 22002 "};"); 22003 } 22004 22005 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) { 22006 FormatStyle TwoIndent = getLLVMStyleWithColumns(15); 22007 TwoIndent.ContinuationIndentWidth = 2; 22008 22009 EXPECT_EQ("int i =\n" 22010 " longFunction(\n" 22011 " arg);", 22012 format("int i = longFunction(arg);", TwoIndent)); 22013 22014 FormatStyle SixIndent = getLLVMStyleWithColumns(20); 22015 SixIndent.ContinuationIndentWidth = 6; 22016 22017 EXPECT_EQ("int i =\n" 22018 " longFunction(\n" 22019 " arg);", 22020 format("int i = longFunction(arg);", SixIndent)); 22021 } 22022 22023 TEST_F(FormatTest, WrappedClosingParenthesisIndent) { 22024 FormatStyle Style = getLLVMStyle(); 22025 verifyFormat("int Foo::getter(\n" 22026 " //\n" 22027 ") const {\n" 22028 " return foo;\n" 22029 "}", 22030 Style); 22031 verifyFormat("void Foo::setter(\n" 22032 " //\n" 22033 ") {\n" 22034 " foo = 1;\n" 22035 "}", 22036 Style); 22037 } 22038 22039 TEST_F(FormatTest, SpacesInAngles) { 22040 FormatStyle Spaces = getLLVMStyle(); 22041 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22042 22043 verifyFormat("vector< ::std::string > x1;", Spaces); 22044 verifyFormat("Foo< int, Bar > x2;", Spaces); 22045 verifyFormat("Foo< ::int, ::Bar > x3;", Spaces); 22046 22047 verifyFormat("static_cast< int >(arg);", Spaces); 22048 verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces); 22049 verifyFormat("f< int, float >();", Spaces); 22050 verifyFormat("template <> g() {}", Spaces); 22051 verifyFormat("template < std::vector< int > > f() {}", Spaces); 22052 verifyFormat("std::function< void(int, int) > fct;", Spaces); 22053 verifyFormat("void inFunction() { std::function< void(int, int) > fct; }", 22054 Spaces); 22055 22056 Spaces.Standard = FormatStyle::LS_Cpp03; 22057 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22058 verifyFormat("A< A< int > >();", Spaces); 22059 22060 Spaces.SpacesInAngles = FormatStyle::SIAS_Never; 22061 verifyFormat("A<A<int> >();", Spaces); 22062 22063 Spaces.SpacesInAngles = FormatStyle::SIAS_Leave; 22064 verifyFormat("vector< ::std::string> x4;", "vector<::std::string> x4;", 22065 Spaces); 22066 verifyFormat("vector< ::std::string > x4;", "vector<::std::string > x4;", 22067 Spaces); 22068 22069 verifyFormat("A<A<int> >();", Spaces); 22070 verifyFormat("A<A<int> >();", "A<A<int>>();", Spaces); 22071 verifyFormat("A< A< int > >();", Spaces); 22072 22073 Spaces.Standard = FormatStyle::LS_Cpp11; 22074 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22075 verifyFormat("A< A< int > >();", Spaces); 22076 22077 Spaces.SpacesInAngles = FormatStyle::SIAS_Never; 22078 verifyFormat("vector<::std::string> x4;", Spaces); 22079 verifyFormat("vector<int> x5;", Spaces); 22080 verifyFormat("Foo<int, Bar> x6;", Spaces); 22081 verifyFormat("Foo<::int, ::Bar> x7;", Spaces); 22082 22083 verifyFormat("A<A<int>>();", Spaces); 22084 22085 Spaces.SpacesInAngles = FormatStyle::SIAS_Leave; 22086 verifyFormat("vector<::std::string> x4;", Spaces); 22087 verifyFormat("vector< ::std::string > x4;", Spaces); 22088 verifyFormat("vector<int> x5;", Spaces); 22089 verifyFormat("vector< int > x5;", Spaces); 22090 verifyFormat("Foo<int, Bar> x6;", Spaces); 22091 verifyFormat("Foo< int, Bar > x6;", Spaces); 22092 verifyFormat("Foo<::int, ::Bar> x7;", Spaces); 22093 verifyFormat("Foo< ::int, ::Bar > x7;", Spaces); 22094 22095 verifyFormat("A<A<int>>();", Spaces); 22096 verifyFormat("A< A< int > >();", Spaces); 22097 verifyFormat("A<A<int > >();", Spaces); 22098 verifyFormat("A< A< int>>();", Spaces); 22099 22100 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 22101 verifyFormat("// clang-format off\n" 22102 "foo<<<1, 1>>>();\n" 22103 "// clang-format on\n", 22104 Spaces); 22105 verifyFormat("// clang-format off\n" 22106 "foo< < <1, 1> > >();\n" 22107 "// clang-format on\n", 22108 Spaces); 22109 } 22110 22111 TEST_F(FormatTest, SpaceAfterTemplateKeyword) { 22112 FormatStyle Style = getLLVMStyle(); 22113 Style.SpaceAfterTemplateKeyword = false; 22114 verifyFormat("template<int> void foo();", Style); 22115 } 22116 22117 TEST_F(FormatTest, TripleAngleBrackets) { 22118 verifyFormat("f<<<1, 1>>>();"); 22119 verifyFormat("f<<<1, 1, 1, s>>>();"); 22120 verifyFormat("f<<<a, b, c, d>>>();"); 22121 EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();")); 22122 verifyFormat("f<param><<<1, 1>>>();"); 22123 verifyFormat("f<1><<<1, 1>>>();"); 22124 EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();")); 22125 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 22126 "aaaaaaaaaaa<<<\n 1, 1>>>();"); 22127 verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n" 22128 " <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();"); 22129 } 22130 22131 TEST_F(FormatTest, MergeLessLessAtEnd) { 22132 verifyFormat("<<"); 22133 EXPECT_EQ("< < <", format("\\\n<<<")); 22134 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 22135 "aaallvm::outs() <<"); 22136 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 22137 "aaaallvm::outs()\n <<"); 22138 } 22139 22140 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) { 22141 std::string code = "#if A\n" 22142 "#if B\n" 22143 "a.\n" 22144 "#endif\n" 22145 " a = 1;\n" 22146 "#else\n" 22147 "#endif\n" 22148 "#if C\n" 22149 "#else\n" 22150 "#endif\n"; 22151 EXPECT_EQ(code, format(code)); 22152 } 22153 22154 TEST_F(FormatTest, HandleConflictMarkers) { 22155 // Git/SVN conflict markers. 22156 EXPECT_EQ("int a;\n" 22157 "void f() {\n" 22158 " callme(some(parameter1,\n" 22159 "<<<<<<< text by the vcs\n" 22160 " parameter2),\n" 22161 "||||||| text by the vcs\n" 22162 " parameter2),\n" 22163 " parameter3,\n" 22164 "======= text by the vcs\n" 22165 " parameter2, parameter3),\n" 22166 ">>>>>>> text by the vcs\n" 22167 " otherparameter);\n", 22168 format("int a;\n" 22169 "void f() {\n" 22170 " callme(some(parameter1,\n" 22171 "<<<<<<< text by the vcs\n" 22172 " parameter2),\n" 22173 "||||||| text by the vcs\n" 22174 " parameter2),\n" 22175 " parameter3,\n" 22176 "======= text by the vcs\n" 22177 " parameter2,\n" 22178 " parameter3),\n" 22179 ">>>>>>> text by the vcs\n" 22180 " otherparameter);\n")); 22181 22182 // Perforce markers. 22183 EXPECT_EQ("void f() {\n" 22184 " function(\n" 22185 ">>>> text by the vcs\n" 22186 " parameter,\n" 22187 "==== text by the vcs\n" 22188 " parameter,\n" 22189 "==== text by the vcs\n" 22190 " parameter,\n" 22191 "<<<< text by the vcs\n" 22192 " parameter);\n", 22193 format("void f() {\n" 22194 " function(\n" 22195 ">>>> text by the vcs\n" 22196 " parameter,\n" 22197 "==== text by the vcs\n" 22198 " parameter,\n" 22199 "==== text by the vcs\n" 22200 " parameter,\n" 22201 "<<<< text by the vcs\n" 22202 " parameter);\n")); 22203 22204 EXPECT_EQ("<<<<<<<\n" 22205 "|||||||\n" 22206 "=======\n" 22207 ">>>>>>>", 22208 format("<<<<<<<\n" 22209 "|||||||\n" 22210 "=======\n" 22211 ">>>>>>>")); 22212 22213 EXPECT_EQ("<<<<<<<\n" 22214 "|||||||\n" 22215 "int i;\n" 22216 "=======\n" 22217 ">>>>>>>", 22218 format("<<<<<<<\n" 22219 "|||||||\n" 22220 "int i;\n" 22221 "=======\n" 22222 ">>>>>>>")); 22223 22224 // FIXME: Handle parsing of macros around conflict markers correctly: 22225 EXPECT_EQ("#define Macro \\\n" 22226 "<<<<<<<\n" 22227 "Something \\\n" 22228 "|||||||\n" 22229 "Else \\\n" 22230 "=======\n" 22231 "Other \\\n" 22232 ">>>>>>>\n" 22233 " End int i;\n", 22234 format("#define Macro \\\n" 22235 "<<<<<<<\n" 22236 " Something \\\n" 22237 "|||||||\n" 22238 " Else \\\n" 22239 "=======\n" 22240 " Other \\\n" 22241 ">>>>>>>\n" 22242 " End\n" 22243 "int i;\n")); 22244 22245 verifyFormat(R"(==== 22246 #ifdef A 22247 a 22248 #else 22249 b 22250 #endif 22251 )"); 22252 } 22253 22254 TEST_F(FormatTest, DisableRegions) { 22255 EXPECT_EQ("int i;\n" 22256 "// clang-format off\n" 22257 " int j;\n" 22258 "// clang-format on\n" 22259 "int k;", 22260 format(" int i;\n" 22261 " // clang-format off\n" 22262 " int j;\n" 22263 " // clang-format on\n" 22264 " int k;")); 22265 EXPECT_EQ("int i;\n" 22266 "/* clang-format off */\n" 22267 " int j;\n" 22268 "/* clang-format on */\n" 22269 "int k;", 22270 format(" int i;\n" 22271 " /* clang-format off */\n" 22272 " int j;\n" 22273 " /* clang-format on */\n" 22274 " int k;")); 22275 22276 // Don't reflow comments within disabled regions. 22277 EXPECT_EQ("// clang-format off\n" 22278 "// long long long long long long line\n" 22279 "/* clang-format on */\n" 22280 "/* long long long\n" 22281 " * long long long\n" 22282 " * line */\n" 22283 "int i;\n" 22284 "/* clang-format off */\n" 22285 "/* long long long long long long line */\n", 22286 format("// clang-format off\n" 22287 "// long long long long long long line\n" 22288 "/* clang-format on */\n" 22289 "/* long long long long long long line */\n" 22290 "int i;\n" 22291 "/* clang-format off */\n" 22292 "/* long long long long long long line */\n", 22293 getLLVMStyleWithColumns(20))); 22294 } 22295 22296 TEST_F(FormatTest, DoNotCrashOnInvalidInput) { 22297 format("? ) ="); 22298 verifyNoCrash("#define a\\\n /**/}"); 22299 } 22300 22301 TEST_F(FormatTest, FormatsTableGenCode) { 22302 FormatStyle Style = getLLVMStyle(); 22303 Style.Language = FormatStyle::LK_TableGen; 22304 verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style); 22305 } 22306 22307 TEST_F(FormatTest, ArrayOfTemplates) { 22308 EXPECT_EQ("auto a = new unique_ptr<int>[10];", 22309 format("auto a = new unique_ptr<int > [ 10];")); 22310 22311 FormatStyle Spaces = getLLVMStyle(); 22312 Spaces.SpacesInSquareBrackets = true; 22313 EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];", 22314 format("auto a = new unique_ptr<int > [10];", Spaces)); 22315 } 22316 22317 TEST_F(FormatTest, ArrayAsTemplateType) { 22318 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;", 22319 format("auto a = unique_ptr < Foo < Bar>[ 10]> ;")); 22320 22321 FormatStyle Spaces = getLLVMStyle(); 22322 Spaces.SpacesInSquareBrackets = true; 22323 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;", 22324 format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces)); 22325 } 22326 22327 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); } 22328 22329 TEST(FormatStyle, GetStyleWithEmptyFileName) { 22330 llvm::vfs::InMemoryFileSystem FS; 22331 auto Style1 = getStyle("file", "", "Google", "", &FS); 22332 ASSERT_TRUE((bool)Style1); 22333 ASSERT_EQ(*Style1, getGoogleStyle()); 22334 } 22335 22336 TEST(FormatStyle, GetStyleOfFile) { 22337 llvm::vfs::InMemoryFileSystem FS; 22338 // Test 1: format file in the same directory. 22339 ASSERT_TRUE( 22340 FS.addFile("/a/.clang-format", 0, 22341 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM"))); 22342 ASSERT_TRUE( 22343 FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22344 auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS); 22345 ASSERT_TRUE((bool)Style1); 22346 ASSERT_EQ(*Style1, getLLVMStyle()); 22347 22348 // Test 2.1: fallback to default. 22349 ASSERT_TRUE( 22350 FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22351 auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS); 22352 ASSERT_TRUE((bool)Style2); 22353 ASSERT_EQ(*Style2, getMozillaStyle()); 22354 22355 // Test 2.2: no format on 'none' fallback style. 22356 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS); 22357 ASSERT_TRUE((bool)Style2); 22358 ASSERT_EQ(*Style2, getNoStyle()); 22359 22360 // Test 2.3: format if config is found with no based style while fallback is 22361 // 'none'. 22362 ASSERT_TRUE(FS.addFile("/b/.clang-format", 0, 22363 llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2"))); 22364 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS); 22365 ASSERT_TRUE((bool)Style2); 22366 ASSERT_EQ(*Style2, getLLVMStyle()); 22367 22368 // Test 2.4: format if yaml with no based style, while fallback is 'none'. 22369 Style2 = getStyle("{}", "a.h", "none", "", &FS); 22370 ASSERT_TRUE((bool)Style2); 22371 ASSERT_EQ(*Style2, getLLVMStyle()); 22372 22373 // Test 3: format file in parent directory. 22374 ASSERT_TRUE( 22375 FS.addFile("/c/.clang-format", 0, 22376 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 22377 ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0, 22378 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22379 auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS); 22380 ASSERT_TRUE((bool)Style3); 22381 ASSERT_EQ(*Style3, getGoogleStyle()); 22382 22383 // Test 4: error on invalid fallback style 22384 auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS); 22385 ASSERT_FALSE((bool)Style4); 22386 llvm::consumeError(Style4.takeError()); 22387 22388 // Test 5: error on invalid yaml on command line 22389 auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS); 22390 ASSERT_FALSE((bool)Style5); 22391 llvm::consumeError(Style5.takeError()); 22392 22393 // Test 6: error on invalid style 22394 auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS); 22395 ASSERT_FALSE((bool)Style6); 22396 llvm::consumeError(Style6.takeError()); 22397 22398 // Test 7: found config file, error on parsing it 22399 ASSERT_TRUE( 22400 FS.addFile("/d/.clang-format", 0, 22401 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n" 22402 "InvalidKey: InvalidValue"))); 22403 ASSERT_TRUE( 22404 FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 22405 auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS); 22406 ASSERT_FALSE((bool)Style7a); 22407 llvm::consumeError(Style7a.takeError()); 22408 22409 auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true); 22410 ASSERT_TRUE((bool)Style7b); 22411 22412 // Test 8: inferred per-language defaults apply. 22413 auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS); 22414 ASSERT_TRUE((bool)StyleTd); 22415 ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen)); 22416 22417 // Test 9.1.1: overwriting a file style, when no parent file exists with no 22418 // fallback style. 22419 ASSERT_TRUE(FS.addFile( 22420 "/e/sub/.clang-format", 0, 22421 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n" 22422 "ColumnLimit: 20"))); 22423 ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0, 22424 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22425 auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS); 22426 ASSERT_TRUE(static_cast<bool>(Style9)); 22427 ASSERT_EQ(*Style9, [] { 22428 auto Style = getNoStyle(); 22429 Style.ColumnLimit = 20; 22430 return Style; 22431 }()); 22432 22433 // Test 9.1.2: propagate more than one level with no parent file. 22434 ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0, 22435 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22436 ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0, 22437 llvm::MemoryBuffer::getMemBuffer( 22438 "BasedOnStyle: InheritParentConfig\n" 22439 "WhitespaceSensitiveMacros: ['FOO', 'BAR']"))); 22440 std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"}; 22441 22442 ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros); 22443 Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS); 22444 ASSERT_TRUE(static_cast<bool>(Style9)); 22445 ASSERT_EQ(*Style9, [&NonDefaultWhiteSpaceMacros] { 22446 auto Style = getNoStyle(); 22447 Style.ColumnLimit = 20; 22448 Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros; 22449 return Style; 22450 }()); 22451 22452 // Test 9.2: with LLVM fallback style 22453 Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS); 22454 ASSERT_TRUE(static_cast<bool>(Style9)); 22455 ASSERT_EQ(*Style9, [] { 22456 auto Style = getLLVMStyle(); 22457 Style.ColumnLimit = 20; 22458 return Style; 22459 }()); 22460 22461 // Test 9.3: with a parent file 22462 ASSERT_TRUE( 22463 FS.addFile("/e/.clang-format", 0, 22464 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n" 22465 "UseTab: Always"))); 22466 Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS); 22467 ASSERT_TRUE(static_cast<bool>(Style9)); 22468 ASSERT_EQ(*Style9, [] { 22469 auto Style = getGoogleStyle(); 22470 Style.ColumnLimit = 20; 22471 Style.UseTab = FormatStyle::UT_Always; 22472 return Style; 22473 }()); 22474 22475 // Test 9.4: propagate more than one level with a parent file. 22476 const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] { 22477 auto Style = getGoogleStyle(); 22478 Style.ColumnLimit = 20; 22479 Style.UseTab = FormatStyle::UT_Always; 22480 Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros; 22481 return Style; 22482 }(); 22483 22484 ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros); 22485 Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS); 22486 ASSERT_TRUE(static_cast<bool>(Style9)); 22487 ASSERT_EQ(*Style9, SubSubStyle); 22488 22489 // Test 9.5: use InheritParentConfig as style name 22490 Style9 = 22491 getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS); 22492 ASSERT_TRUE(static_cast<bool>(Style9)); 22493 ASSERT_EQ(*Style9, SubSubStyle); 22494 22495 // Test 9.6: use command line style with inheritance 22496 Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp", 22497 "none", "", &FS); 22498 ASSERT_TRUE(static_cast<bool>(Style9)); 22499 ASSERT_EQ(*Style9, SubSubStyle); 22500 22501 // Test 9.7: use command line style with inheritance and own config 22502 Style9 = getStyle("{BasedOnStyle: InheritParentConfig, " 22503 "WhitespaceSensitiveMacros: ['FOO', 'BAR']}", 22504 "/e/sub/code.cpp", "none", "", &FS); 22505 ASSERT_TRUE(static_cast<bool>(Style9)); 22506 ASSERT_EQ(*Style9, SubSubStyle); 22507 22508 // Test 9.8: use inheritance from a file without BasedOnStyle 22509 ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0, 22510 llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123"))); 22511 ASSERT_TRUE( 22512 FS.addFile("/e/withoutbase/sub/.clang-format", 0, 22513 llvm::MemoryBuffer::getMemBuffer( 22514 "BasedOnStyle: InheritParentConfig\nIndentWidth: 7"))); 22515 // Make sure we do not use the fallback style 22516 Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS); 22517 ASSERT_TRUE(static_cast<bool>(Style9)); 22518 ASSERT_EQ(*Style9, [] { 22519 auto Style = getLLVMStyle(); 22520 Style.ColumnLimit = 123; 22521 return Style; 22522 }()); 22523 22524 Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS); 22525 ASSERT_TRUE(static_cast<bool>(Style9)); 22526 ASSERT_EQ(*Style9, [] { 22527 auto Style = getLLVMStyle(); 22528 Style.ColumnLimit = 123; 22529 Style.IndentWidth = 7; 22530 return Style; 22531 }()); 22532 22533 // Test 9.9: use inheritance from a specific config file. 22534 Style9 = getStyle("file:/e/sub/sub/.clang-format", "/e/sub/sub/code.cpp", 22535 "none", "", &FS); 22536 ASSERT_TRUE(static_cast<bool>(Style9)); 22537 ASSERT_EQ(*Style9, SubSubStyle); 22538 } 22539 22540 TEST(FormatStyle, GetStyleOfSpecificFile) { 22541 llvm::vfs::InMemoryFileSystem FS; 22542 // Specify absolute path to a format file in a parent directory. 22543 ASSERT_TRUE( 22544 FS.addFile("/e/.clang-format", 0, 22545 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM"))); 22546 ASSERT_TRUE( 22547 FS.addFile("/e/explicit.clang-format", 0, 22548 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 22549 ASSERT_TRUE(FS.addFile("/e/sub/sub/sub/test.cpp", 0, 22550 llvm::MemoryBuffer::getMemBuffer("int i;"))); 22551 auto Style = getStyle("file:/e/explicit.clang-format", 22552 "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS); 22553 ASSERT_TRUE(static_cast<bool>(Style)); 22554 ASSERT_EQ(*Style, getGoogleStyle()); 22555 22556 // Specify relative path to a format file. 22557 ASSERT_TRUE( 22558 FS.addFile("../../e/explicit.clang-format", 0, 22559 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 22560 Style = getStyle("file:../../e/explicit.clang-format", 22561 "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS); 22562 ASSERT_TRUE(static_cast<bool>(Style)); 22563 ASSERT_EQ(*Style, getGoogleStyle()); 22564 22565 // Specify path to a format file that does not exist. 22566 Style = getStyle("file:/e/missing.clang-format", "/e/sub/sub/sub/test.cpp", 22567 "LLVM", "", &FS); 22568 ASSERT_FALSE(static_cast<bool>(Style)); 22569 llvm::consumeError(Style.takeError()); 22570 22571 // Specify path to a file on the filesystem. 22572 SmallString<128> FormatFilePath; 22573 std::error_code ECF = llvm::sys::fs::createTemporaryFile( 22574 "FormatFileTest", "tpl", FormatFilePath); 22575 EXPECT_FALSE((bool)ECF); 22576 llvm::raw_fd_ostream FormatFileTest(FormatFilePath, ECF); 22577 EXPECT_FALSE((bool)ECF); 22578 FormatFileTest << "BasedOnStyle: Google\n"; 22579 FormatFileTest.close(); 22580 22581 SmallString<128> TestFilePath; 22582 std::error_code ECT = 22583 llvm::sys::fs::createTemporaryFile("CodeFileTest", "cc", TestFilePath); 22584 EXPECT_FALSE((bool)ECT); 22585 llvm::raw_fd_ostream CodeFileTest(TestFilePath, ECT); 22586 CodeFileTest << "int i;\n"; 22587 CodeFileTest.close(); 22588 22589 std::string format_file_arg = std::string("file:") + FormatFilePath.c_str(); 22590 Style = getStyle(format_file_arg, TestFilePath, "LLVM", "", nullptr); 22591 22592 llvm::sys::fs::remove(FormatFilePath.c_str()); 22593 llvm::sys::fs::remove(TestFilePath.c_str()); 22594 ASSERT_TRUE(static_cast<bool>(Style)); 22595 ASSERT_EQ(*Style, getGoogleStyle()); 22596 } 22597 22598 TEST_F(ReplacementTest, FormatCodeAfterReplacements) { 22599 // Column limit is 20. 22600 std::string Code = "Type *a =\n" 22601 " new Type();\n" 22602 "g(iiiii, 0, jjjjj,\n" 22603 " 0, kkkkk, 0, mm);\n" 22604 "int bad = format ;"; 22605 std::string Expected = "auto a = new Type();\n" 22606 "g(iiiii, nullptr,\n" 22607 " jjjjj, nullptr,\n" 22608 " kkkkk, nullptr,\n" 22609 " mm);\n" 22610 "int bad = format ;"; 22611 FileID ID = Context.createInMemoryFile("format.cpp", Code); 22612 tooling::Replacements Replaces = toReplacements( 22613 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6, 22614 "auto "), 22615 tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1, 22616 "nullptr"), 22617 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1, 22618 "nullptr"), 22619 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1, 22620 "nullptr")}); 22621 22622 FormatStyle Style = getLLVMStyle(); 22623 Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility. 22624 auto FormattedReplaces = formatReplacements(Code, Replaces, Style); 22625 EXPECT_TRUE(static_cast<bool>(FormattedReplaces)) 22626 << llvm::toString(FormattedReplaces.takeError()) << "\n"; 22627 auto Result = applyAllReplacements(Code, *FormattedReplaces); 22628 EXPECT_TRUE(static_cast<bool>(Result)); 22629 EXPECT_EQ(Expected, *Result); 22630 } 22631 22632 TEST_F(ReplacementTest, SortIncludesAfterReplacement) { 22633 std::string Code = "#include \"a.h\"\n" 22634 "#include \"c.h\"\n" 22635 "\n" 22636 "int main() {\n" 22637 " return 0;\n" 22638 "}"; 22639 std::string Expected = "#include \"a.h\"\n" 22640 "#include \"b.h\"\n" 22641 "#include \"c.h\"\n" 22642 "\n" 22643 "int main() {\n" 22644 " return 0;\n" 22645 "}"; 22646 FileID ID = Context.createInMemoryFile("fix.cpp", Code); 22647 tooling::Replacements Replaces = toReplacements( 22648 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0, 22649 "#include \"b.h\"\n")}); 22650 22651 FormatStyle Style = getLLVMStyle(); 22652 Style.SortIncludes = FormatStyle::SI_CaseSensitive; 22653 auto FormattedReplaces = formatReplacements(Code, Replaces, Style); 22654 EXPECT_TRUE(static_cast<bool>(FormattedReplaces)) 22655 << llvm::toString(FormattedReplaces.takeError()) << "\n"; 22656 auto Result = applyAllReplacements(Code, *FormattedReplaces); 22657 EXPECT_TRUE(static_cast<bool>(Result)); 22658 EXPECT_EQ(Expected, *Result); 22659 } 22660 22661 TEST_F(FormatTest, FormatSortsUsingDeclarations) { 22662 EXPECT_EQ("using std::cin;\n" 22663 "using std::cout;", 22664 format("using std::cout;\n" 22665 "using std::cin;", 22666 getGoogleStyle())); 22667 } 22668 22669 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) { 22670 FormatStyle Style = getLLVMStyle(); 22671 Style.Standard = FormatStyle::LS_Cpp03; 22672 // cpp03 recognize this string as identifier u8 and literal character 'a' 22673 EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style)); 22674 } 22675 22676 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) { 22677 // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers 22678 // all modes, including C++11, C++14 and C++17 22679 EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';")); 22680 } 22681 22682 TEST_F(FormatTest, DoNotFormatLikelyXml) { 22683 EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle())); 22684 EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle())); 22685 } 22686 22687 TEST_F(FormatTest, StructuredBindings) { 22688 // Structured bindings is a C++17 feature. 22689 // all modes, including C++11, C++14 and C++17 22690 verifyFormat("auto [a, b] = f();"); 22691 EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();")); 22692 EXPECT_EQ("const auto [a, b] = f();", format("const auto[a, b] = f();")); 22693 EXPECT_EQ("auto const [a, b] = f();", format("auto const[a, b] = f();")); 22694 EXPECT_EQ("auto const volatile [a, b] = f();", 22695 format("auto const volatile[a, b] = f();")); 22696 EXPECT_EQ("auto [a, b, c] = f();", format("auto [ a , b,c ] = f();")); 22697 EXPECT_EQ("auto &[a, b, c] = f();", 22698 format("auto &[ a , b,c ] = f();")); 22699 EXPECT_EQ("auto &&[a, b, c] = f();", 22700 format("auto &&[ a , b,c ] = f();")); 22701 EXPECT_EQ("auto const &[a, b] = f();", format("auto const&[a, b] = f();")); 22702 EXPECT_EQ("auto const volatile &&[a, b] = f();", 22703 format("auto const volatile &&[a, b] = f();")); 22704 EXPECT_EQ("auto const &&[a, b] = f();", 22705 format("auto const && [a, b] = f();")); 22706 EXPECT_EQ("const auto &[a, b] = f();", 22707 format("const auto & [a, b] = f();")); 22708 EXPECT_EQ("const auto volatile &&[a, b] = f();", 22709 format("const auto volatile &&[a, b] = f();")); 22710 EXPECT_EQ("volatile const auto &&[a, b] = f();", 22711 format("volatile const auto &&[a, b] = f();")); 22712 EXPECT_EQ("const auto &&[a, b] = f();", 22713 format("const auto && [a, b] = f();")); 22714 22715 // Make sure we don't mistake structured bindings for lambdas. 22716 FormatStyle PointerMiddle = getLLVMStyle(); 22717 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle; 22718 verifyFormat("auto [a1, b]{A * i};", getGoogleStyle()); 22719 verifyFormat("auto [a2, b]{A * i};", getLLVMStyle()); 22720 verifyFormat("auto [a3, b]{A * i};", PointerMiddle); 22721 verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle()); 22722 verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle()); 22723 verifyFormat("auto const [a3, b]{A * i};", PointerMiddle); 22724 verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle()); 22725 verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle()); 22726 verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle); 22727 verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle()); 22728 verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle()); 22729 verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle); 22730 22731 EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}", 22732 format("for (const auto && [a, b] : some_range) {\n}")); 22733 EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}", 22734 format("for (const auto & [a, b] : some_range) {\n}")); 22735 EXPECT_EQ("for (const auto [a, b] : some_range) {\n}", 22736 format("for (const auto[a, b] : some_range) {\n}")); 22737 EXPECT_EQ("auto [x, y](expr);", format("auto[x,y] (expr);")); 22738 EXPECT_EQ("auto &[x, y](expr);", format("auto & [x,y] (expr);")); 22739 EXPECT_EQ("auto &&[x, y](expr);", format("auto && [x,y] (expr);")); 22740 EXPECT_EQ("auto const &[x, y](expr);", 22741 format("auto const & [x,y] (expr);")); 22742 EXPECT_EQ("auto const &&[x, y](expr);", 22743 format("auto const && [x,y] (expr);")); 22744 EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y] {expr};")); 22745 EXPECT_EQ("auto const &[x, y]{expr};", 22746 format("auto const & [x,y] {expr};")); 22747 EXPECT_EQ("auto const &&[x, y]{expr};", 22748 format("auto const && [x,y] {expr};")); 22749 22750 FormatStyle Spaces = getLLVMStyle(); 22751 Spaces.SpacesInSquareBrackets = true; 22752 verifyFormat("auto [ a, b ] = f();", Spaces); 22753 verifyFormat("auto &&[ a, b ] = f();", Spaces); 22754 verifyFormat("auto &[ a, b ] = f();", Spaces); 22755 verifyFormat("auto const &&[ a, b ] = f();", Spaces); 22756 verifyFormat("auto const &[ a, b ] = f();", Spaces); 22757 } 22758 22759 TEST_F(FormatTest, FileAndCode) { 22760 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", "")); 22761 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", "")); 22762 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", "")); 22763 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "")); 22764 EXPECT_EQ(FormatStyle::LK_ObjC, 22765 guessLanguage("foo.h", "@interface Foo\n@end\n")); 22766 EXPECT_EQ( 22767 FormatStyle::LK_ObjC, 22768 guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }")); 22769 EXPECT_EQ(FormatStyle::LK_ObjC, 22770 guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))")); 22771 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;")); 22772 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", "")); 22773 EXPECT_EQ(FormatStyle::LK_ObjC, 22774 guessLanguage("foo", "@interface Foo\n@end\n")); 22775 EXPECT_EQ(FormatStyle::LK_ObjC, 22776 guessLanguage("foo.h", "int DoStuff(CGRect rect);\n")); 22777 EXPECT_EQ( 22778 FormatStyle::LK_ObjC, 22779 guessLanguage("foo.h", 22780 "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n")); 22781 EXPECT_EQ( 22782 FormatStyle::LK_Cpp, 22783 guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;")); 22784 // Only one of the two preprocessor regions has ObjC-like code. 22785 EXPECT_EQ(FormatStyle::LK_ObjC, 22786 guessLanguage("foo.h", "#if A\n" 22787 "#define B() C\n" 22788 "#else\n" 22789 "#define B() [NSString a:@\"\"]\n" 22790 "#endif\n")); 22791 } 22792 22793 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) { 22794 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];")); 22795 EXPECT_EQ(FormatStyle::LK_ObjC, 22796 guessLanguage("foo.h", "array[[calculator getIndex]];")); 22797 EXPECT_EQ(FormatStyle::LK_Cpp, 22798 guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];")); 22799 EXPECT_EQ( 22800 FormatStyle::LK_Cpp, 22801 guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];")); 22802 EXPECT_EQ(FormatStyle::LK_ObjC, 22803 guessLanguage("foo.h", "[[noreturn foo] bar];")); 22804 EXPECT_EQ(FormatStyle::LK_Cpp, 22805 guessLanguage("foo.h", "[[clang::fallthrough]];")); 22806 EXPECT_EQ(FormatStyle::LK_ObjC, 22807 guessLanguage("foo.h", "[[clang:fallthrough] foo];")); 22808 EXPECT_EQ(FormatStyle::LK_Cpp, 22809 guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];")); 22810 EXPECT_EQ(FormatStyle::LK_Cpp, 22811 guessLanguage("foo.h", "[[using clang: fallthrough]];")); 22812 EXPECT_EQ(FormatStyle::LK_ObjC, 22813 guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];")); 22814 EXPECT_EQ(FormatStyle::LK_Cpp, 22815 guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];")); 22816 EXPECT_EQ( 22817 FormatStyle::LK_Cpp, 22818 guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)")); 22819 EXPECT_EQ( 22820 FormatStyle::LK_Cpp, 22821 guessLanguage("foo.h", 22822 "[[clang::callable_when(\"unconsumed\", \"unknown\")]]")); 22823 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]")); 22824 } 22825 22826 TEST_F(FormatTest, GuessLanguageWithCaret) { 22827 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);")); 22828 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);")); 22829 EXPECT_EQ(FormatStyle::LK_ObjC, 22830 guessLanguage("foo.h", "int(^)(char, float);")); 22831 EXPECT_EQ(FormatStyle::LK_ObjC, 22832 guessLanguage("foo.h", "int(^foo)(char, float);")); 22833 EXPECT_EQ(FormatStyle::LK_ObjC, 22834 guessLanguage("foo.h", "int(^foo[10])(char, float);")); 22835 EXPECT_EQ(FormatStyle::LK_ObjC, 22836 guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);")); 22837 EXPECT_EQ( 22838 FormatStyle::LK_ObjC, 22839 guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);")); 22840 } 22841 22842 TEST_F(FormatTest, GuessLanguageWithPragmas) { 22843 EXPECT_EQ(FormatStyle::LK_Cpp, 22844 guessLanguage("foo.h", "__pragma(warning(disable:))")); 22845 EXPECT_EQ(FormatStyle::LK_Cpp, 22846 guessLanguage("foo.h", "#pragma(warning(disable:))")); 22847 EXPECT_EQ(FormatStyle::LK_Cpp, 22848 guessLanguage("foo.h", "_Pragma(warning(disable:))")); 22849 } 22850 22851 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) { 22852 // ASM symbolic names are identifiers that must be surrounded by [] without 22853 // space in between: 22854 // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands 22855 22856 // Example from https://bugs.llvm.org/show_bug.cgi?id=45108. 22857 verifyFormat(R"(// 22858 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result)); 22859 )"); 22860 22861 // A list of several ASM symbolic names. 22862 verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)"); 22863 22864 // ASM symbolic names in inline ASM with inputs and outputs. 22865 verifyFormat(R"(// 22866 asm("cmoveq %1, %2, %[result]" 22867 : [result] "=r"(result) 22868 : "r"(test), "r"(new), "[result]"(old)); 22869 )"); 22870 22871 // ASM symbolic names in inline ASM with no outputs. 22872 verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)"); 22873 } 22874 22875 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) { 22876 EXPECT_EQ(FormatStyle::LK_Cpp, 22877 guessLanguage("foo.h", "void f() {\n" 22878 " asm (\"mov %[e], %[d]\"\n" 22879 " : [d] \"=rm\" (d)\n" 22880 " [e] \"rm\" (*e));\n" 22881 "}")); 22882 EXPECT_EQ(FormatStyle::LK_Cpp, 22883 guessLanguage("foo.h", "void f() {\n" 22884 " _asm (\"mov %[e], %[d]\"\n" 22885 " : [d] \"=rm\" (d)\n" 22886 " [e] \"rm\" (*e));\n" 22887 "}")); 22888 EXPECT_EQ(FormatStyle::LK_Cpp, 22889 guessLanguage("foo.h", "void f() {\n" 22890 " __asm (\"mov %[e], %[d]\"\n" 22891 " : [d] \"=rm\" (d)\n" 22892 " [e] \"rm\" (*e));\n" 22893 "}")); 22894 EXPECT_EQ(FormatStyle::LK_Cpp, 22895 guessLanguage("foo.h", "void f() {\n" 22896 " __asm__ (\"mov %[e], %[d]\"\n" 22897 " : [d] \"=rm\" (d)\n" 22898 " [e] \"rm\" (*e));\n" 22899 "}")); 22900 EXPECT_EQ(FormatStyle::LK_Cpp, 22901 guessLanguage("foo.h", "void f() {\n" 22902 " asm (\"mov %[e], %[d]\"\n" 22903 " : [d] \"=rm\" (d),\n" 22904 " [e] \"rm\" (*e));\n" 22905 "}")); 22906 EXPECT_EQ(FormatStyle::LK_Cpp, 22907 guessLanguage("foo.h", "void f() {\n" 22908 " asm volatile (\"mov %[e], %[d]\"\n" 22909 " : [d] \"=rm\" (d)\n" 22910 " [e] \"rm\" (*e));\n" 22911 "}")); 22912 } 22913 22914 TEST_F(FormatTest, GuessLanguageWithChildLines) { 22915 EXPECT_EQ(FormatStyle::LK_Cpp, 22916 guessLanguage("foo.h", "#define FOO ({ std::string s; })")); 22917 EXPECT_EQ(FormatStyle::LK_ObjC, 22918 guessLanguage("foo.h", "#define FOO ({ NSString *s; })")); 22919 EXPECT_EQ( 22920 FormatStyle::LK_Cpp, 22921 guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })")); 22922 EXPECT_EQ( 22923 FormatStyle::LK_ObjC, 22924 guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })")); 22925 } 22926 22927 TEST_F(FormatTest, TypenameMacros) { 22928 std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"}; 22929 22930 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353 22931 FormatStyle Google = getGoogleStyleWithColumns(0); 22932 Google.TypenameMacros = TypenameMacros; 22933 verifyFormat("struct foo {\n" 22934 " int bar;\n" 22935 " TAILQ_ENTRY(a) bleh;\n" 22936 "};", 22937 Google); 22938 22939 FormatStyle Macros = getLLVMStyle(); 22940 Macros.TypenameMacros = TypenameMacros; 22941 22942 verifyFormat("STACK_OF(int) a;", Macros); 22943 verifyFormat("STACK_OF(int) *a;", Macros); 22944 verifyFormat("STACK_OF(int const *) *a;", Macros); 22945 verifyFormat("STACK_OF(int *const) *a;", Macros); 22946 verifyFormat("STACK_OF(int, string) a;", Macros); 22947 verifyFormat("STACK_OF(LIST(int)) a;", Macros); 22948 verifyFormat("STACK_OF(LIST(int)) a, b;", Macros); 22949 verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros); 22950 verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros); 22951 verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros); 22952 verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros); 22953 22954 Macros.PointerAlignment = FormatStyle::PAS_Left; 22955 verifyFormat("STACK_OF(int)* a;", Macros); 22956 verifyFormat("STACK_OF(int*)* a;", Macros); 22957 verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros); 22958 verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros); 22959 verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros); 22960 } 22961 22962 TEST_F(FormatTest, AtomicQualifier) { 22963 // Check that we treate _Atomic as a type and not a function call 22964 FormatStyle Google = getGoogleStyleWithColumns(0); 22965 verifyFormat("struct foo {\n" 22966 " int a1;\n" 22967 " _Atomic(a) a2;\n" 22968 " _Atomic(_Atomic(int) *const) a3;\n" 22969 "};", 22970 Google); 22971 verifyFormat("_Atomic(uint64_t) a;"); 22972 verifyFormat("_Atomic(uint64_t) *a;"); 22973 verifyFormat("_Atomic(uint64_t const *) *a;"); 22974 verifyFormat("_Atomic(uint64_t *const) *a;"); 22975 verifyFormat("_Atomic(const uint64_t *) *a;"); 22976 verifyFormat("_Atomic(uint64_t) a;"); 22977 verifyFormat("_Atomic(_Atomic(uint64_t)) a;"); 22978 verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;"); 22979 verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}"); 22980 verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);"); 22981 22982 verifyFormat("_Atomic(uint64_t) *s(InitValue);"); 22983 verifyFormat("_Atomic(uint64_t) *s{InitValue};"); 22984 FormatStyle Style = getLLVMStyle(); 22985 Style.PointerAlignment = FormatStyle::PAS_Left; 22986 verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style); 22987 verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style); 22988 verifyFormat("_Atomic(int)* a;", Style); 22989 verifyFormat("_Atomic(int*)* a;", Style); 22990 verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style); 22991 22992 Style.SpacesInCStyleCastParentheses = true; 22993 Style.SpacesInParentheses = false; 22994 verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style); 22995 Style.SpacesInCStyleCastParentheses = false; 22996 Style.SpacesInParentheses = true; 22997 verifyFormat("x = (_Atomic( uint64_t ))*a;", Style); 22998 verifyFormat("x = (_Atomic( uint64_t ))&a;", Style); 22999 } 23000 23001 TEST_F(FormatTest, AmbersandInLamda) { 23002 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899 23003 FormatStyle AlignStyle = getLLVMStyle(); 23004 AlignStyle.PointerAlignment = FormatStyle::PAS_Left; 23005 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle); 23006 AlignStyle.PointerAlignment = FormatStyle::PAS_Right; 23007 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle); 23008 } 23009 23010 TEST_F(FormatTest, SpacesInConditionalStatement) { 23011 FormatStyle Spaces = getLLVMStyle(); 23012 Spaces.IfMacros.clear(); 23013 Spaces.IfMacros.push_back("MYIF"); 23014 Spaces.SpacesInConditionalStatement = true; 23015 verifyFormat("for ( int i = 0; i; i++ )\n continue;", Spaces); 23016 verifyFormat("if ( !a )\n return;", Spaces); 23017 verifyFormat("if ( a )\n return;", Spaces); 23018 verifyFormat("if constexpr ( a )\n return;", Spaces); 23019 verifyFormat("MYIF ( a )\n return;", Spaces); 23020 verifyFormat("MYIF ( a )\n return;\nelse MYIF ( b )\n return;", Spaces); 23021 verifyFormat("MYIF ( a )\n return;\nelse\n return;", Spaces); 23022 verifyFormat("switch ( a )\ncase 1:\n return;", Spaces); 23023 verifyFormat("while ( a )\n return;", Spaces); 23024 verifyFormat("while ( (a && b) )\n return;", Spaces); 23025 verifyFormat("do {\n} while ( 1 != 0 );", Spaces); 23026 verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces); 23027 // Check that space on the left of "::" is inserted as expected at beginning 23028 // of condition. 23029 verifyFormat("while ( ::func() )\n return;", Spaces); 23030 23031 // Check impact of ControlStatementsExceptControlMacros is honored. 23032 Spaces.SpaceBeforeParens = 23033 FormatStyle::SBPO_ControlStatementsExceptControlMacros; 23034 verifyFormat("MYIF( a )\n return;", Spaces); 23035 verifyFormat("MYIF( a )\n return;\nelse MYIF( b )\n return;", Spaces); 23036 verifyFormat("MYIF( a )\n return;\nelse\n return;", Spaces); 23037 } 23038 23039 TEST_F(FormatTest, AlternativeOperators) { 23040 // Test case for ensuring alternate operators are not 23041 // combined with their right most neighbour. 23042 verifyFormat("int a and b;"); 23043 verifyFormat("int a and_eq b;"); 23044 verifyFormat("int a bitand b;"); 23045 verifyFormat("int a bitor b;"); 23046 verifyFormat("int a compl b;"); 23047 verifyFormat("int a not b;"); 23048 verifyFormat("int a not_eq b;"); 23049 verifyFormat("int a or b;"); 23050 verifyFormat("int a xor b;"); 23051 verifyFormat("int a xor_eq b;"); 23052 verifyFormat("return this not_eq bitand other;"); 23053 verifyFormat("bool operator not_eq(const X bitand other)"); 23054 23055 verifyFormat("int a and 5;"); 23056 verifyFormat("int a and_eq 5;"); 23057 verifyFormat("int a bitand 5;"); 23058 verifyFormat("int a bitor 5;"); 23059 verifyFormat("int a compl 5;"); 23060 verifyFormat("int a not 5;"); 23061 verifyFormat("int a not_eq 5;"); 23062 verifyFormat("int a or 5;"); 23063 verifyFormat("int a xor 5;"); 23064 verifyFormat("int a xor_eq 5;"); 23065 23066 verifyFormat("int a compl(5);"); 23067 verifyFormat("int a not(5);"); 23068 23069 /* FIXME handle alternate tokens 23070 * https://en.cppreference.com/w/cpp/language/operator_alternative 23071 // alternative tokens 23072 verifyFormat("compl foo();"); // ~foo(); 23073 verifyFormat("foo() <%%>;"); // foo(); 23074 verifyFormat("void foo() <%%>;"); // void foo(){} 23075 verifyFormat("int a <:1:>;"); // int a[1];[ 23076 verifyFormat("%:define ABC abc"); // #define ABC abc 23077 verifyFormat("%:%:"); // ## 23078 */ 23079 } 23080 23081 TEST_F(FormatTest, STLWhileNotDefineChed) { 23082 verifyFormat("#if defined(while)\n" 23083 "#define while EMIT WARNING C4005\n" 23084 "#endif // while"); 23085 } 23086 23087 TEST_F(FormatTest, OperatorSpacing) { 23088 FormatStyle Style = getLLVMStyle(); 23089 Style.PointerAlignment = FormatStyle::PAS_Right; 23090 verifyFormat("Foo::operator*();", Style); 23091 verifyFormat("Foo::operator void *();", Style); 23092 verifyFormat("Foo::operator void **();", Style); 23093 verifyFormat("Foo::operator void *&();", Style); 23094 verifyFormat("Foo::operator void *&&();", Style); 23095 verifyFormat("Foo::operator void const *();", Style); 23096 verifyFormat("Foo::operator void const **();", Style); 23097 verifyFormat("Foo::operator void const *&();", Style); 23098 verifyFormat("Foo::operator void const *&&();", Style); 23099 verifyFormat("Foo::operator()(void *);", Style); 23100 verifyFormat("Foo::operator*(void *);", Style); 23101 verifyFormat("Foo::operator*();", Style); 23102 verifyFormat("Foo::operator**();", Style); 23103 verifyFormat("Foo::operator&();", Style); 23104 verifyFormat("Foo::operator<int> *();", Style); 23105 verifyFormat("Foo::operator<Foo> *();", Style); 23106 verifyFormat("Foo::operator<int> **();", Style); 23107 verifyFormat("Foo::operator<Foo> **();", Style); 23108 verifyFormat("Foo::operator<int> &();", Style); 23109 verifyFormat("Foo::operator<Foo> &();", Style); 23110 verifyFormat("Foo::operator<int> &&();", Style); 23111 verifyFormat("Foo::operator<Foo> &&();", Style); 23112 verifyFormat("Foo::operator<int> *&();", Style); 23113 verifyFormat("Foo::operator<Foo> *&();", Style); 23114 verifyFormat("Foo::operator<int> *&&();", Style); 23115 verifyFormat("Foo::operator<Foo> *&&();", Style); 23116 verifyFormat("operator*(int (*)(), class Foo);", Style); 23117 23118 verifyFormat("Foo::operator&();", Style); 23119 verifyFormat("Foo::operator void &();", Style); 23120 verifyFormat("Foo::operator void const &();", Style); 23121 verifyFormat("Foo::operator()(void &);", Style); 23122 verifyFormat("Foo::operator&(void &);", Style); 23123 verifyFormat("Foo::operator&();", Style); 23124 verifyFormat("operator&(int (&)(), class Foo);", Style); 23125 verifyFormat("operator&&(int (&)(), class Foo);", Style); 23126 23127 verifyFormat("Foo::operator&&();", Style); 23128 verifyFormat("Foo::operator**();", Style); 23129 verifyFormat("Foo::operator void &&();", Style); 23130 verifyFormat("Foo::operator void const &&();", Style); 23131 verifyFormat("Foo::operator()(void &&);", Style); 23132 verifyFormat("Foo::operator&&(void &&);", Style); 23133 verifyFormat("Foo::operator&&();", Style); 23134 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23135 verifyFormat("operator const nsTArrayRight<E> &()", Style); 23136 verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()", 23137 Style); 23138 verifyFormat("operator void **()", Style); 23139 verifyFormat("operator const FooRight<Object> &()", Style); 23140 verifyFormat("operator const FooRight<Object> *()", Style); 23141 verifyFormat("operator const FooRight<Object> **()", Style); 23142 verifyFormat("operator const FooRight<Object> *&()", Style); 23143 verifyFormat("operator const FooRight<Object> *&&()", Style); 23144 23145 Style.PointerAlignment = FormatStyle::PAS_Left; 23146 verifyFormat("Foo::operator*();", Style); 23147 verifyFormat("Foo::operator**();", Style); 23148 verifyFormat("Foo::operator void*();", Style); 23149 verifyFormat("Foo::operator void**();", Style); 23150 verifyFormat("Foo::operator void*&();", Style); 23151 verifyFormat("Foo::operator void*&&();", Style); 23152 verifyFormat("Foo::operator void const*();", Style); 23153 verifyFormat("Foo::operator void const**();", Style); 23154 verifyFormat("Foo::operator void const*&();", Style); 23155 verifyFormat("Foo::operator void const*&&();", Style); 23156 verifyFormat("Foo::operator/*comment*/ void*();", Style); 23157 verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style); 23158 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style); 23159 verifyFormat("Foo::operator()(void*);", Style); 23160 verifyFormat("Foo::operator*(void*);", Style); 23161 verifyFormat("Foo::operator*();", Style); 23162 verifyFormat("Foo::operator<int>*();", Style); 23163 verifyFormat("Foo::operator<Foo>*();", Style); 23164 verifyFormat("Foo::operator<int>**();", Style); 23165 verifyFormat("Foo::operator<Foo>**();", Style); 23166 verifyFormat("Foo::operator<Foo>*&();", Style); 23167 verifyFormat("Foo::operator<int>&();", Style); 23168 verifyFormat("Foo::operator<Foo>&();", Style); 23169 verifyFormat("Foo::operator<int>&&();", Style); 23170 verifyFormat("Foo::operator<Foo>&&();", Style); 23171 verifyFormat("Foo::operator<int>*&();", Style); 23172 verifyFormat("Foo::operator<Foo>*&();", Style); 23173 verifyFormat("operator*(int (*)(), class Foo);", Style); 23174 23175 verifyFormat("Foo::operator&();", Style); 23176 verifyFormat("Foo::operator void&();", Style); 23177 verifyFormat("Foo::operator void const&();", Style); 23178 verifyFormat("Foo::operator/*comment*/ void&();", Style); 23179 verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style); 23180 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style); 23181 verifyFormat("Foo::operator()(void&);", Style); 23182 verifyFormat("Foo::operator&(void&);", Style); 23183 verifyFormat("Foo::operator&();", Style); 23184 verifyFormat("operator&(int (&)(), class Foo);", Style); 23185 verifyFormat("operator&(int (&&)(), class Foo);", Style); 23186 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23187 23188 verifyFormat("Foo::operator&&();", Style); 23189 verifyFormat("Foo::operator void&&();", Style); 23190 verifyFormat("Foo::operator void const&&();", Style); 23191 verifyFormat("Foo::operator/*comment*/ void&&();", Style); 23192 verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style); 23193 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style); 23194 verifyFormat("Foo::operator()(void&&);", Style); 23195 verifyFormat("Foo::operator&&(void&&);", Style); 23196 verifyFormat("Foo::operator&&();", Style); 23197 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23198 verifyFormat("operator const nsTArrayLeft<E>&()", Style); 23199 verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()", 23200 Style); 23201 verifyFormat("operator void**()", Style); 23202 verifyFormat("operator const FooLeft<Object>&()", Style); 23203 verifyFormat("operator const FooLeft<Object>*()", Style); 23204 verifyFormat("operator const FooLeft<Object>**()", Style); 23205 verifyFormat("operator const FooLeft<Object>*&()", Style); 23206 verifyFormat("operator const FooLeft<Object>*&&()", Style); 23207 23208 // PR45107 23209 verifyFormat("operator Vector<String>&();", Style); 23210 verifyFormat("operator const Vector<String>&();", Style); 23211 verifyFormat("operator foo::Bar*();", Style); 23212 verifyFormat("operator const Foo<X>::Bar<Y>*();", Style); 23213 verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();", 23214 Style); 23215 23216 Style.PointerAlignment = FormatStyle::PAS_Middle; 23217 verifyFormat("Foo::operator*();", Style); 23218 verifyFormat("Foo::operator void *();", Style); 23219 verifyFormat("Foo::operator()(void *);", Style); 23220 verifyFormat("Foo::operator*(void *);", Style); 23221 verifyFormat("Foo::operator*();", Style); 23222 verifyFormat("operator*(int (*)(), class Foo);", Style); 23223 23224 verifyFormat("Foo::operator&();", Style); 23225 verifyFormat("Foo::operator void &();", Style); 23226 verifyFormat("Foo::operator void const &();", Style); 23227 verifyFormat("Foo::operator()(void &);", Style); 23228 verifyFormat("Foo::operator&(void &);", Style); 23229 verifyFormat("Foo::operator&();", Style); 23230 verifyFormat("operator&(int (&)(), class Foo);", Style); 23231 23232 verifyFormat("Foo::operator&&();", Style); 23233 verifyFormat("Foo::operator void &&();", Style); 23234 verifyFormat("Foo::operator void const &&();", Style); 23235 verifyFormat("Foo::operator()(void &&);", Style); 23236 verifyFormat("Foo::operator&&(void &&);", Style); 23237 verifyFormat("Foo::operator&&();", Style); 23238 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 23239 } 23240 23241 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) { 23242 FormatStyle Style = getLLVMStyle(); 23243 // PR46157 23244 verifyFormat("foo(operator+, -42);", Style); 23245 verifyFormat("foo(operator++, -42);", Style); 23246 verifyFormat("foo(operator--, -42);", Style); 23247 verifyFormat("foo(-42, operator--);", Style); 23248 verifyFormat("foo(-42, operator, );", Style); 23249 verifyFormat("foo(operator, , -42);", Style); 23250 } 23251 23252 TEST_F(FormatTest, WhitespaceSensitiveMacros) { 23253 FormatStyle Style = getLLVMStyle(); 23254 Style.WhitespaceSensitiveMacros.push_back("FOO"); 23255 23256 // Don't use the helpers here, since 'mess up' will change the whitespace 23257 // and these are all whitespace sensitive by definition 23258 EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);", 23259 format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style)); 23260 EXPECT_EQ( 23261 "FOO(String-ized&Messy+But\\(: :Still)=Intentional);", 23262 format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style)); 23263 EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);", 23264 format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style)); 23265 EXPECT_EQ("FOO(String-ized&Messy+But,: :\n" 23266 " Still=Intentional);", 23267 format("FOO(String-ized&Messy+But,: :\n" 23268 " Still=Intentional);", 23269 Style)); 23270 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 23271 EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n" 23272 " Still=Intentional);", 23273 format("FOO(String-ized=&Messy+But,: :\n" 23274 " Still=Intentional);", 23275 Style)); 23276 23277 Style.ColumnLimit = 21; 23278 EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);", 23279 format("FOO(String-ized&Messy+But: :Still=Intentional);", Style)); 23280 } 23281 23282 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) { 23283 // These tests are not in NamespaceFixer because that doesn't 23284 // test its interaction with line wrapping 23285 FormatStyle Style = getLLVMStyleWithColumns(80); 23286 verifyFormat("namespace {\n" 23287 "int i;\n" 23288 "int j;\n" 23289 "} // namespace", 23290 Style); 23291 23292 verifyFormat("namespace AAA {\n" 23293 "int i;\n" 23294 "int j;\n" 23295 "} // namespace AAA", 23296 Style); 23297 23298 EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n" 23299 "int i;\n" 23300 "int j;\n" 23301 "} // namespace Averyveryveryverylongnamespace", 23302 format("namespace Averyveryveryverylongnamespace {\n" 23303 "int i;\n" 23304 "int j;\n" 23305 "}", 23306 Style)); 23307 23308 EXPECT_EQ( 23309 "namespace " 23310 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n" 23311 " went::mad::now {\n" 23312 "int i;\n" 23313 "int j;\n" 23314 "} // namespace\n" 23315 " // " 23316 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::" 23317 "went::mad::now", 23318 format("namespace " 23319 "would::it::save::you::a::lot::of::time::if_::i::" 23320 "just::gave::up::and_::went::mad::now {\n" 23321 "int i;\n" 23322 "int j;\n" 23323 "}", 23324 Style)); 23325 23326 // This used to duplicate the comment again and again on subsequent runs 23327 EXPECT_EQ( 23328 "namespace " 23329 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n" 23330 " went::mad::now {\n" 23331 "int i;\n" 23332 "int j;\n" 23333 "} // namespace\n" 23334 " // " 23335 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::" 23336 "went::mad::now", 23337 format("namespace " 23338 "would::it::save::you::a::lot::of::time::if_::i::" 23339 "just::gave::up::and_::went::mad::now {\n" 23340 "int i;\n" 23341 "int j;\n" 23342 "} // namespace\n" 23343 " // " 23344 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::" 23345 "and_::went::mad::now", 23346 Style)); 23347 } 23348 23349 TEST_F(FormatTest, LikelyUnlikely) { 23350 FormatStyle Style = getLLVMStyle(); 23351 23352 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23353 " return 29;\n" 23354 "}", 23355 Style); 23356 23357 verifyFormat("if (argc > 5) [[likely]] {\n" 23358 " return 29;\n" 23359 "}", 23360 Style); 23361 23362 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23363 " return 29;\n" 23364 "} else [[likely]] {\n" 23365 " return 42;\n" 23366 "}\n", 23367 Style); 23368 23369 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23370 " return 29;\n" 23371 "} else if (argc > 10) [[likely]] {\n" 23372 " return 99;\n" 23373 "} else {\n" 23374 " return 42;\n" 23375 "}\n", 23376 Style); 23377 23378 verifyFormat("if (argc > 5) [[gnu::unused]] {\n" 23379 " return 29;\n" 23380 "}", 23381 Style); 23382 23383 verifyFormat("if (argc > 5) [[unlikely]]\n" 23384 " return 29;\n", 23385 Style); 23386 verifyFormat("if (argc > 5) [[likely]]\n" 23387 " return 29;\n", 23388 Style); 23389 23390 Style.AttributeMacros.push_back("UNLIKELY"); 23391 Style.AttributeMacros.push_back("LIKELY"); 23392 verifyFormat("if (argc > 5) UNLIKELY\n" 23393 " return 29;\n", 23394 Style); 23395 23396 verifyFormat("if (argc > 5) UNLIKELY {\n" 23397 " return 29;\n" 23398 "}", 23399 Style); 23400 verifyFormat("if (argc > 5) UNLIKELY {\n" 23401 " return 29;\n" 23402 "} else [[likely]] {\n" 23403 " return 42;\n" 23404 "}\n", 23405 Style); 23406 verifyFormat("if (argc > 5) UNLIKELY {\n" 23407 " return 29;\n" 23408 "} else LIKELY {\n" 23409 " return 42;\n" 23410 "}\n", 23411 Style); 23412 verifyFormat("if (argc > 5) [[unlikely]] {\n" 23413 " return 29;\n" 23414 "} else LIKELY {\n" 23415 " return 42;\n" 23416 "}\n", 23417 Style); 23418 } 23419 23420 TEST_F(FormatTest, PenaltyIndentedWhitespace) { 23421 verifyFormat("Constructor()\n" 23422 " : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 23423 " aaaa(aaaaaaaaaaaaaaaaaa, " 23424 "aaaaaaaaaaaaaaaaaat))"); 23425 verifyFormat("Constructor()\n" 23426 " : aaaaaaaaaaaaa(aaaaaa), " 23427 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)"); 23428 23429 FormatStyle StyleWithWhitespacePenalty = getLLVMStyle(); 23430 StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5; 23431 verifyFormat("Constructor()\n" 23432 " : aaaaaa(aaaaaa),\n" 23433 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 23434 " aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))", 23435 StyleWithWhitespacePenalty); 23436 verifyFormat("Constructor()\n" 23437 " : aaaaaaaaaaaaa(aaaaaa), " 23438 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)", 23439 StyleWithWhitespacePenalty); 23440 } 23441 23442 TEST_F(FormatTest, LLVMDefaultStyle) { 23443 FormatStyle Style = getLLVMStyle(); 23444 verifyFormat("extern \"C\" {\n" 23445 "int foo();\n" 23446 "}", 23447 Style); 23448 } 23449 TEST_F(FormatTest, GNUDefaultStyle) { 23450 FormatStyle Style = getGNUStyle(); 23451 verifyFormat("extern \"C\"\n" 23452 "{\n" 23453 " int foo ();\n" 23454 "}", 23455 Style); 23456 } 23457 TEST_F(FormatTest, MozillaDefaultStyle) { 23458 FormatStyle Style = getMozillaStyle(); 23459 verifyFormat("extern \"C\"\n" 23460 "{\n" 23461 " int foo();\n" 23462 "}", 23463 Style); 23464 } 23465 TEST_F(FormatTest, GoogleDefaultStyle) { 23466 FormatStyle Style = getGoogleStyle(); 23467 verifyFormat("extern \"C\" {\n" 23468 "int foo();\n" 23469 "}", 23470 Style); 23471 } 23472 TEST_F(FormatTest, ChromiumDefaultStyle) { 23473 FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp); 23474 verifyFormat("extern \"C\" {\n" 23475 "int foo();\n" 23476 "}", 23477 Style); 23478 } 23479 TEST_F(FormatTest, MicrosoftDefaultStyle) { 23480 FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp); 23481 verifyFormat("extern \"C\"\n" 23482 "{\n" 23483 " int foo();\n" 23484 "}", 23485 Style); 23486 } 23487 TEST_F(FormatTest, WebKitDefaultStyle) { 23488 FormatStyle Style = getWebKitStyle(); 23489 verifyFormat("extern \"C\" {\n" 23490 "int foo();\n" 23491 "}", 23492 Style); 23493 } 23494 23495 TEST_F(FormatTest, Concepts) { 23496 EXPECT_EQ(getLLVMStyle().BreakBeforeConceptDeclarations, 23497 FormatStyle::BBCDS_Always); 23498 verifyFormat("template <typename T>\n" 23499 "concept True = true;"); 23500 23501 verifyFormat("template <typename T>\n" 23502 "concept C = ((false || foo()) && C2<T>) ||\n" 23503 " (std::trait<T>::value && Baz) || sizeof(T) >= 6;", 23504 getLLVMStyleWithColumns(60)); 23505 23506 verifyFormat("template <typename T>\n" 23507 "concept DelayedCheck = true && requires(T t) { t.bar(); } && " 23508 "sizeof(T) <= 8;"); 23509 23510 verifyFormat("template <typename T>\n" 23511 "concept DelayedCheck = true && requires(T t) {\n" 23512 " t.bar();\n" 23513 " t.baz();\n" 23514 " } && sizeof(T) <= 8;"); 23515 23516 verifyFormat("template <typename T>\n" 23517 "concept DelayedCheck = true && requires(T t) { // Comment\n" 23518 " t.bar();\n" 23519 " t.baz();\n" 23520 " } && sizeof(T) <= 8;"); 23521 23522 verifyFormat("template <typename T>\n" 23523 "concept DelayedCheck = false || requires(T t) { t.bar(); } && " 23524 "sizeof(T) <= 8;"); 23525 23526 verifyFormat("template <typename T>\n" 23527 "concept DelayedCheck = !!false || requires(T t) { t.bar(); } " 23528 "&& sizeof(T) <= 8;"); 23529 23530 verifyFormat( 23531 "template <typename T>\n" 23532 "concept DelayedCheck = static_cast<bool>(0) ||\n" 23533 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 23534 23535 verifyFormat("template <typename T>\n" 23536 "concept DelayedCheck = bool(0) || requires(T t) { t.bar(); } " 23537 "&& sizeof(T) <= 8;"); 23538 23539 verifyFormat( 23540 "template <typename T>\n" 23541 "concept DelayedCheck = (bool)(0) ||\n" 23542 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 23543 23544 verifyFormat("template <typename T>\n" 23545 "concept DelayedCheck = (bool)0 || requires(T t) { t.bar(); } " 23546 "&& sizeof(T) <= 8;"); 23547 23548 verifyFormat("template <typename T>\n" 23549 "concept Size = sizeof(T) >= 5 && requires(T t) { t.bar(); } && " 23550 "sizeof(T) <= 8;"); 23551 23552 verifyFormat("template <typename T>\n" 23553 "concept Size = 2 < 5 && 2 <= 5 && 8 >= 5 && 8 > 5 &&\n" 23554 " requires(T t) {\n" 23555 " t.bar();\n" 23556 " t.baz();\n" 23557 " } && sizeof(T) <= 8 && !(4 < 3);", 23558 getLLVMStyleWithColumns(60)); 23559 23560 verifyFormat("template <typename T>\n" 23561 "concept TrueOrNot = IsAlwaysTrue || IsNeverTrue;"); 23562 23563 verifyFormat("template <typename T>\n" 23564 "concept C = foo();"); 23565 23566 verifyFormat("template <typename T>\n" 23567 "concept C = foo(T());"); 23568 23569 verifyFormat("template <typename T>\n" 23570 "concept C = foo(T{});"); 23571 23572 verifyFormat("template <typename T>\n" 23573 "concept Size = V<sizeof(T)>::Value > 5;"); 23574 23575 verifyFormat("template <typename T>\n" 23576 "concept True = S<T>::Value;"); 23577 23578 verifyFormat( 23579 "template <typename T>\n" 23580 "concept C = []() { return true; }() && requires(T t) { t.bar(); } &&\n" 23581 " sizeof(T) <= 8;"); 23582 23583 // FIXME: This is misformatted because the fake l paren starts at bool, not at 23584 // the lambda l square. 23585 verifyFormat("template <typename T>\n" 23586 "concept C = [] -> bool { return true; }() && requires(T t) { " 23587 "t.bar(); } &&\n" 23588 " sizeof(T) <= 8;"); 23589 23590 verifyFormat( 23591 "template <typename T>\n" 23592 "concept C = decltype([]() { return std::true_type{}; }())::value &&\n" 23593 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 23594 23595 verifyFormat("template <typename T>\n" 23596 "concept C = decltype([]() { return std::true_type{}; " 23597 "}())::value && requires(T t) { t.bar(); } && sizeof(T) <= 8;", 23598 getLLVMStyleWithColumns(120)); 23599 23600 verifyFormat("template <typename T>\n" 23601 "concept C = decltype([]() -> std::true_type { return {}; " 23602 "}())::value &&\n" 23603 " requires(T t) { t.bar(); } && sizeof(T) <= 8;"); 23604 23605 verifyFormat("template <typename T>\n" 23606 "concept C = true;\n" 23607 "Foo Bar;"); 23608 23609 verifyFormat("template <typename T>\n" 23610 "concept Hashable = requires(T a) {\n" 23611 " { std::hash<T>{}(a) } -> " 23612 "std::convertible_to<std::size_t>;\n" 23613 " };"); 23614 23615 verifyFormat( 23616 "template <typename T>\n" 23617 "concept EqualityComparable = requires(T a, T b) {\n" 23618 " { a == b } -> std::same_as<bool>;\n" 23619 " };"); 23620 23621 verifyFormat( 23622 "template <typename T>\n" 23623 "concept EqualityComparable = requires(T a, T b) {\n" 23624 " { a == b } -> std::same_as<bool>;\n" 23625 " { a != b } -> std::same_as<bool>;\n" 23626 " };"); 23627 23628 verifyFormat("template <typename T>\n" 23629 "concept WeakEqualityComparable = requires(T a, T b) {\n" 23630 " { a == b };\n" 23631 " { a != b };\n" 23632 " };"); 23633 23634 verifyFormat("template <typename T>\n" 23635 "concept HasSizeT = requires { typename T::size_t; };"); 23636 23637 verifyFormat("template <typename T>\n" 23638 "concept Semiregular =\n" 23639 " DefaultConstructible<T> && CopyConstructible<T> && " 23640 "CopyAssignable<T> &&\n" 23641 " requires(T a, std::size_t n) {\n" 23642 " requires Same<T *, decltype(&a)>;\n" 23643 " { a.~T() } noexcept;\n" 23644 " requires Same<T *, decltype(new T)>;\n" 23645 " requires Same<T *, decltype(new T[n])>;\n" 23646 " { delete new T; };\n" 23647 " { delete new T[n]; };\n" 23648 " };"); 23649 23650 verifyFormat("template <typename T>\n" 23651 "concept Semiregular =\n" 23652 " requires(T a, std::size_t n) {\n" 23653 " requires Same<T *, decltype(&a)>;\n" 23654 " { a.~T() } noexcept;\n" 23655 " requires Same<T *, decltype(new T)>;\n" 23656 " requires Same<T *, decltype(new T[n])>;\n" 23657 " { delete new T; };\n" 23658 " { delete new T[n]; };\n" 23659 " { new T } -> std::same_as<T *>;\n" 23660 " } && DefaultConstructible<T> && CopyConstructible<T> && " 23661 "CopyAssignable<T>;"); 23662 23663 verifyFormat( 23664 "template <typename T>\n" 23665 "concept Semiregular =\n" 23666 " DefaultConstructible<T> && requires(T a, std::size_t n) {\n" 23667 " requires Same<T *, decltype(&a)>;\n" 23668 " { a.~T() } noexcept;\n" 23669 " requires Same<T *, decltype(new T)>;\n" 23670 " requires Same<T *, decltype(new " 23671 "T[n])>;\n" 23672 " { delete new T; };\n" 23673 " { delete new T[n]; };\n" 23674 " } && CopyConstructible<T> && " 23675 "CopyAssignable<T>;"); 23676 23677 verifyFormat("template <typename T>\n" 23678 "concept Two = requires(T t) {\n" 23679 " { t.foo() } -> std::same_as<Bar>;\n" 23680 " } && requires(T &&t) {\n" 23681 " { t.foo() } -> std::same_as<Bar &&>;\n" 23682 " };"); 23683 23684 verifyFormat( 23685 "template <typename T>\n" 23686 "concept C = requires(T x) {\n" 23687 " { *x } -> std::convertible_to<typename T::inner>;\n" 23688 " { x + 1 } noexcept -> std::same_as<int>;\n" 23689 " { x * 1 } -> std::convertible_to<T>;\n" 23690 " };"); 23691 23692 verifyFormat( 23693 "template <typename T, typename U = T>\n" 23694 "concept Swappable = requires(T &&t, U &&u) {\n" 23695 " swap(std::forward<T>(t), std::forward<U>(u));\n" 23696 " swap(std::forward<U>(u), std::forward<T>(t));\n" 23697 " };"); 23698 23699 verifyFormat("template <typename T, typename U>\n" 23700 "concept Common = requires(T &&t, U &&u) {\n" 23701 " typename CommonType<T, U>;\n" 23702 " { CommonType<T, U>(std::forward<T>(t)) };\n" 23703 " };"); 23704 23705 verifyFormat("template <typename T, typename U>\n" 23706 "concept Common = requires(T &&t, U &&u) {\n" 23707 " typename CommonType<T, U>;\n" 23708 " { CommonType<T, U>{std::forward<T>(t)} };\n" 23709 " };"); 23710 23711 verifyFormat( 23712 "template <typename T>\n" 23713 "concept C = requires(T t) {\n" 23714 " requires Bar<T> && Foo<T>;\n" 23715 " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n" 23716 " };"); 23717 23718 verifyFormat("template <typename T>\n" 23719 "concept HasFoo = requires(T t) {\n" 23720 " { t.foo() };\n" 23721 " t.foo();\n" 23722 " };\n" 23723 "template <typename T>\n" 23724 "concept HasBar = requires(T t) {\n" 23725 " { t.bar() };\n" 23726 " t.bar();\n" 23727 " };"); 23728 23729 verifyFormat("template <typename T>\n" 23730 "concept Large = sizeof(T) > 10;"); 23731 23732 verifyFormat("template <typename T, typename U>\n" 23733 "concept FooableWith = requires(T t, U u) {\n" 23734 " typename T::foo_type;\n" 23735 " { t.foo(u) } -> typename T::foo_type;\n" 23736 " t++;\n" 23737 " };\n" 23738 "void doFoo(FooableWith<int> auto t) { t.foo(3); }"); 23739 23740 verifyFormat("template <typename T>\n" 23741 "concept Context = is_specialization_of_v<context, T>;"); 23742 23743 verifyFormat("template <typename T>\n" 23744 "concept Node = std::is_object_v<T>;"); 23745 23746 auto Style = getLLVMStyle(); 23747 Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Allowed; 23748 23749 verifyFormat( 23750 "template <typename T>\n" 23751 "concept C = requires(T t) {\n" 23752 " requires Bar<T> && Foo<T>;\n" 23753 " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n" 23754 " };", 23755 Style); 23756 23757 verifyFormat("template <typename T>\n" 23758 "concept HasFoo = requires(T t) {\n" 23759 " { t.foo() };\n" 23760 " t.foo();\n" 23761 " };\n" 23762 "template <typename T>\n" 23763 "concept HasBar = requires(T t) {\n" 23764 " { t.bar() };\n" 23765 " t.bar();\n" 23766 " };", 23767 Style); 23768 23769 verifyFormat("template <typename T> concept True = true;", Style); 23770 23771 verifyFormat("template <typename T>\n" 23772 "concept C = decltype([]() -> std::true_type { return {}; " 23773 "}())::value &&\n" 23774 " requires(T t) { t.bar(); } && sizeof(T) <= 8;", 23775 Style); 23776 23777 verifyFormat("template <typename T>\n" 23778 "concept Semiregular =\n" 23779 " DefaultConstructible<T> && CopyConstructible<T> && " 23780 "CopyAssignable<T> &&\n" 23781 " requires(T a, std::size_t n) {\n" 23782 " requires Same<T *, decltype(&a)>;\n" 23783 " { a.~T() } noexcept;\n" 23784 " requires Same<T *, decltype(new T)>;\n" 23785 " requires Same<T *, decltype(new T[n])>;\n" 23786 " { delete new T; };\n" 23787 " { delete new T[n]; };\n" 23788 " };", 23789 Style); 23790 23791 Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Never; 23792 23793 verifyFormat("template <typename T> concept C =\n" 23794 " requires(T t) {\n" 23795 " requires Bar<T> && Foo<T>;\n" 23796 " requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n" 23797 " };", 23798 Style); 23799 23800 verifyFormat("template <typename T> concept HasFoo = requires(T t) {\n" 23801 " { t.foo() };\n" 23802 " t.foo();\n" 23803 " };\n" 23804 "template <typename T> concept HasBar = requires(T t) {\n" 23805 " { t.bar() };\n" 23806 " t.bar();\n" 23807 " };", 23808 Style); 23809 23810 verifyFormat("template <typename T> concept True = true;", Style); 23811 23812 verifyFormat( 23813 "template <typename T> concept C = decltype([]() -> std::true_type {\n" 23814 " return {};\n" 23815 " }())::value\n" 23816 " && requires(T t) { t.bar(); } &&\n" 23817 " sizeof(T) <= 8;", 23818 Style); 23819 23820 verifyFormat("template <typename T> concept Semiregular =\n" 23821 " DefaultConstructible<T> && CopyConstructible<T> && " 23822 "CopyAssignable<T> &&\n" 23823 " requires(T a, std::size_t n) {\n" 23824 " requires Same<T *, decltype(&a)>;\n" 23825 " { a.~T() } noexcept;\n" 23826 " requires Same<T *, decltype(new T)>;\n" 23827 " requires Same<T *, decltype(new T[n])>;\n" 23828 " { delete new T; };\n" 23829 " { delete new T[n]; };\n" 23830 " };", 23831 Style); 23832 23833 // The following tests are invalid C++, we just want to make sure we don't 23834 // assert. 23835 verifyFormat("template <typename T>\n" 23836 "concept C = requires C2<T>;"); 23837 23838 verifyFormat("template <typename T>\n" 23839 "concept C = 5 + 4;"); 23840 23841 verifyFormat("template <typename T>\n" 23842 "concept C =\n" 23843 "class X;"); 23844 23845 verifyFormat("template <typename T>\n" 23846 "concept C = [] && true;"); 23847 23848 verifyFormat("template <typename T>\n" 23849 "concept C = [] && requires(T t) { typename T::size_type; };"); 23850 } 23851 23852 TEST_F(FormatTest, RequiresClausesPositions) { 23853 auto Style = getLLVMStyle(); 23854 EXPECT_EQ(Style.RequiresClausePosition, FormatStyle::RCPS_OwnLine); 23855 EXPECT_EQ(Style.IndentRequiresClause, true); 23856 23857 verifyFormat("template <typename T>\n" 23858 " requires(Foo<T> && std::trait<T>)\n" 23859 "struct Bar;", 23860 Style); 23861 23862 verifyFormat("template <typename T>\n" 23863 " requires(Foo<T> && std::trait<T>)\n" 23864 "class Bar {\n" 23865 "public:\n" 23866 " Bar(T t);\n" 23867 " bool baz();\n" 23868 "};", 23869 Style); 23870 23871 verifyFormat( 23872 "template <typename T>\n" 23873 " requires requires(T &&t) {\n" 23874 " typename T::I;\n" 23875 " requires(F<typename T::I> && std::trait<typename T::I>);\n" 23876 " }\n" 23877 "Bar(T) -> Bar<typename T::I>;", 23878 Style); 23879 23880 verifyFormat("template <typename T>\n" 23881 " requires(Foo<T> && std::trait<T>)\n" 23882 "constexpr T MyGlobal;", 23883 Style); 23884 23885 verifyFormat("template <typename T>\n" 23886 " requires Foo<T> && requires(T t) {\n" 23887 " { t.baz() } -> std::same_as<bool>;\n" 23888 " requires std::same_as<T::Factor, int>;\n" 23889 " }\n" 23890 "inline int bar(T t) {\n" 23891 " return t.baz() ? T::Factor : 5;\n" 23892 "}", 23893 Style); 23894 23895 verifyFormat("template <typename T>\n" 23896 "inline int bar(T t)\n" 23897 " requires Foo<T> && requires(T t) {\n" 23898 " { t.baz() } -> std::same_as<bool>;\n" 23899 " requires std::same_as<T::Factor, int>;\n" 23900 " }\n" 23901 "{\n" 23902 " return t.baz() ? T::Factor : 5;\n" 23903 "}", 23904 Style); 23905 23906 verifyFormat("template <typename T>\n" 23907 " requires F<T>\n" 23908 "int bar(T t) {\n" 23909 " return 5;\n" 23910 "}", 23911 Style); 23912 23913 verifyFormat("template <typename T>\n" 23914 "int bar(T t)\n" 23915 " requires F<T>\n" 23916 "{\n" 23917 " return 5;\n" 23918 "}", 23919 Style); 23920 23921 verifyFormat("template <typename T>\n" 23922 "int bar(T t)\n" 23923 " requires F<T>;", 23924 Style); 23925 23926 Style.IndentRequiresClause = false; 23927 verifyFormat("template <typename T>\n" 23928 "requires F<T>\n" 23929 "int bar(T t) {\n" 23930 " return 5;\n" 23931 "}", 23932 Style); 23933 23934 verifyFormat("template <typename T>\n" 23935 "int bar(T t)\n" 23936 "requires F<T>\n" 23937 "{\n" 23938 " return 5;\n" 23939 "}", 23940 Style); 23941 23942 Style.RequiresClausePosition = FormatStyle::RCPS_SingleLine; 23943 verifyFormat("template <typename T> requires Foo<T> struct Bar {};\n" 23944 "template <typename T> requires Foo<T> void bar() {}\n" 23945 "template <typename T> void bar() requires Foo<T> {}\n" 23946 "template <typename T> void bar() requires Foo<T>;\n" 23947 "template <typename T> requires Foo<T> Bar(T) -> Bar<T>;", 23948 Style); 23949 23950 auto ColumnStyle = Style; 23951 ColumnStyle.ColumnLimit = 40; 23952 verifyFormat("template <typename AAAAAAA>\n" 23953 "requires Foo<T> struct Bar {};\n" 23954 "template <typename AAAAAAA>\n" 23955 "requires Foo<T> void bar() {}\n" 23956 "template <typename AAAAAAA>\n" 23957 "void bar() requires Foo<T> {}\n" 23958 "template <typename AAAAAAA>\n" 23959 "requires Foo<T> Baz(T) -> Baz<T>;", 23960 ColumnStyle); 23961 23962 verifyFormat("template <typename T>\n" 23963 "requires Foo<AAAAAAA> struct Bar {};\n" 23964 "template <typename T>\n" 23965 "requires Foo<AAAAAAA> void bar() {}\n" 23966 "template <typename T>\n" 23967 "void bar() requires Foo<AAAAAAA> {}\n" 23968 "template <typename T>\n" 23969 "requires Foo<AAAAAAA> Bar(T) -> Bar<T>;", 23970 ColumnStyle); 23971 23972 verifyFormat("template <typename AAAAAAA>\n" 23973 "requires Foo<AAAAAAAAAAAAAAAA>\n" 23974 "struct Bar {};\n" 23975 "template <typename AAAAAAA>\n" 23976 "requires Foo<AAAAAAAAAAAAAAAA>\n" 23977 "void bar() {}\n" 23978 "template <typename AAAAAAA>\n" 23979 "void bar()\n" 23980 " requires Foo<AAAAAAAAAAAAAAAA> {}\n" 23981 "template <typename AAAAAAA>\n" 23982 "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n" 23983 "template <typename AAAAAAA>\n" 23984 "requires Foo<AAAAAAAAAAAAAAAA>\n" 23985 "Bar(T) -> Bar<T>;", 23986 ColumnStyle); 23987 23988 Style.RequiresClausePosition = FormatStyle::RCPS_WithFollowing; 23989 ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithFollowing; 23990 23991 verifyFormat("template <typename T>\n" 23992 "requires Foo<T> struct Bar {};\n" 23993 "template <typename T>\n" 23994 "requires Foo<T> void bar() {}\n" 23995 "template <typename T>\n" 23996 "void bar()\n" 23997 "requires Foo<T> {}\n" 23998 "template <typename T>\n" 23999 "void bar()\n" 24000 "requires Foo<T>;\n" 24001 "template <typename T>\n" 24002 "requires Foo<T> Bar(T) -> Bar<T>;", 24003 Style); 24004 24005 verifyFormat("template <typename AAAAAAA>\n" 24006 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24007 "struct Bar {};\n" 24008 "template <typename AAAAAAA>\n" 24009 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24010 "void bar() {}\n" 24011 "template <typename AAAAAAA>\n" 24012 "void bar()\n" 24013 "requires Foo<AAAAAAAAAAAAAAAA> {}\n" 24014 "template <typename AAAAAAA>\n" 24015 "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n" 24016 "template <typename AAAAAAA>\n" 24017 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24018 "Bar(T) -> Bar<T>;", 24019 ColumnStyle); 24020 24021 Style.IndentRequiresClause = true; 24022 ColumnStyle.IndentRequiresClause = true; 24023 24024 verifyFormat("template <typename T>\n" 24025 " requires Foo<T> struct Bar {};\n" 24026 "template <typename T>\n" 24027 " requires Foo<T> void bar() {}\n" 24028 "template <typename T>\n" 24029 "void bar()\n" 24030 " requires Foo<T> {}\n" 24031 "template <typename T>\n" 24032 " requires Foo<T> Bar(T) -> Bar<T>;", 24033 Style); 24034 24035 verifyFormat("template <typename AAAAAAA>\n" 24036 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24037 "struct Bar {};\n" 24038 "template <typename AAAAAAA>\n" 24039 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24040 "void bar() {}\n" 24041 "template <typename AAAAAAA>\n" 24042 "void bar()\n" 24043 " requires Foo<AAAAAAAAAAAAAAAA> {}\n" 24044 "template <typename AAAAAAA>\n" 24045 " requires Foo<AAAAAA> Bar(T) -> Bar<T>;\n" 24046 "template <typename AAAAAAA>\n" 24047 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24048 "Bar(T) -> Bar<T>;", 24049 ColumnStyle); 24050 24051 Style.RequiresClausePosition = FormatStyle::RCPS_WithPreceding; 24052 ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithPreceding; 24053 24054 verifyFormat("template <typename T> requires Foo<T>\n" 24055 "struct Bar {};\n" 24056 "template <typename T> requires Foo<T>\n" 24057 "void bar() {}\n" 24058 "template <typename T>\n" 24059 "void bar() requires Foo<T>\n" 24060 "{}\n" 24061 "template <typename T> void bar() requires Foo<T>;\n" 24062 "template <typename T> requires Foo<T>\n" 24063 "Bar(T) -> Bar<T>;", 24064 Style); 24065 24066 verifyFormat("template <typename AAAAAAA>\n" 24067 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24068 "struct Bar {};\n" 24069 "template <typename AAAAAAA>\n" 24070 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24071 "void bar() {}\n" 24072 "template <typename AAAAAAA>\n" 24073 "void bar()\n" 24074 " requires Foo<AAAAAAAAAAAAAAAA>\n" 24075 "{}\n" 24076 "template <typename AAAAAAA>\n" 24077 "requires Foo<AAAAAAAA>\n" 24078 "Bar(T) -> Bar<T>;\n" 24079 "template <typename AAAAAAA>\n" 24080 "requires Foo<AAAAAAAAAAAAAAAA>\n" 24081 "Bar(T) -> Bar<T>;", 24082 ColumnStyle); 24083 } 24084 24085 TEST_F(FormatTest, RequiresClauses) { 24086 verifyFormat("struct [[nodiscard]] zero_t {\n" 24087 " template <class T>\n" 24088 " requires requires { number_zero_v<T>; }\n" 24089 " [[nodiscard]] constexpr operator T() const {\n" 24090 " return number_zero_v<T>;\n" 24091 " }\n" 24092 "};"); 24093 24094 auto Style = getLLVMStyle(); 24095 24096 verifyFormat( 24097 "template <typename T>\n" 24098 " requires is_default_constructible_v<hash<T>> and\n" 24099 " is_copy_constructible_v<hash<T>> and\n" 24100 " is_move_constructible_v<hash<T>> and\n" 24101 " is_copy_assignable_v<hash<T>> and " 24102 "is_move_assignable_v<hash<T>> and\n" 24103 " is_destructible_v<hash<T>> and is_swappable_v<hash<T>> and\n" 24104 " is_callable_v<hash<T>(T)> and\n" 24105 " is_same_v<size_t, decltype(hash<T>(declval<T>()))> and\n" 24106 " is_same_v<size_t, decltype(hash<T>(declval<T &>()))> and\n" 24107 " is_same_v<size_t, decltype(hash<T>(declval<const T &>()))>\n" 24108 "struct S {};", 24109 Style); 24110 24111 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 24112 verifyFormat( 24113 "template <typename T>\n" 24114 " requires is_default_constructible_v<hash<T>>\n" 24115 " and is_copy_constructible_v<hash<T>>\n" 24116 " and is_move_constructible_v<hash<T>>\n" 24117 " and is_copy_assignable_v<hash<T>> and " 24118 "is_move_assignable_v<hash<T>>\n" 24119 " and is_destructible_v<hash<T>> and is_swappable_v<hash<T>>\n" 24120 " and is_callable_v<hash<T>(T)>\n" 24121 " and is_same_v<size_t, decltype(hash<T>(declval<T>()))>\n" 24122 " and is_same_v<size_t, decltype(hash<T>(declval<T &>()))>\n" 24123 " and is_same_v<size_t, decltype(hash<T>(declval<const T " 24124 "&>()))>\n" 24125 "struct S {};", 24126 Style); 24127 24128 // Not a clause, but we once hit an assert. 24129 verifyFormat("#if 0\n" 24130 "#else\n" 24131 "foo();\n" 24132 "#endif\n" 24133 "bar(requires);"); 24134 } 24135 24136 TEST_F(FormatTest, StatementAttributeLikeMacros) { 24137 FormatStyle Style = getLLVMStyle(); 24138 StringRef Source = "void Foo::slot() {\n" 24139 " unsigned char MyChar = 'x';\n" 24140 " emit signal(MyChar);\n" 24141 " Q_EMIT signal(MyChar);\n" 24142 "}"; 24143 24144 EXPECT_EQ(Source, format(Source, Style)); 24145 24146 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 24147 EXPECT_EQ("void Foo::slot() {\n" 24148 " unsigned char MyChar = 'x';\n" 24149 " emit signal(MyChar);\n" 24150 " Q_EMIT signal(MyChar);\n" 24151 "}", 24152 format(Source, Style)); 24153 24154 Style.StatementAttributeLikeMacros.push_back("emit"); 24155 EXPECT_EQ(Source, format(Source, Style)); 24156 24157 Style.StatementAttributeLikeMacros = {}; 24158 EXPECT_EQ("void Foo::slot() {\n" 24159 " unsigned char MyChar = 'x';\n" 24160 " emit signal(MyChar);\n" 24161 " Q_EMIT signal(MyChar);\n" 24162 "}", 24163 format(Source, Style)); 24164 } 24165 24166 TEST_F(FormatTest, IndentAccessModifiers) { 24167 FormatStyle Style = getLLVMStyle(); 24168 Style.IndentAccessModifiers = true; 24169 // Members are *two* levels below the record; 24170 // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation. 24171 verifyFormat("class C {\n" 24172 " int i;\n" 24173 "};\n", 24174 Style); 24175 verifyFormat("union C {\n" 24176 " int i;\n" 24177 " unsigned u;\n" 24178 "};\n", 24179 Style); 24180 // Access modifiers should be indented one level below the record. 24181 verifyFormat("class C {\n" 24182 " public:\n" 24183 " int i;\n" 24184 "};\n", 24185 Style); 24186 verifyFormat("struct S {\n" 24187 " private:\n" 24188 " class C {\n" 24189 " int j;\n" 24190 "\n" 24191 " public:\n" 24192 " C();\n" 24193 " };\n" 24194 "\n" 24195 " public:\n" 24196 " int i;\n" 24197 "};\n", 24198 Style); 24199 // Enumerations are not records and should be unaffected. 24200 Style.AllowShortEnumsOnASingleLine = false; 24201 verifyFormat("enum class E {\n" 24202 " A,\n" 24203 " B\n" 24204 "};\n", 24205 Style); 24206 // Test with a different indentation width; 24207 // also proves that the result is Style.AccessModifierOffset agnostic. 24208 Style.IndentWidth = 3; 24209 verifyFormat("class C {\n" 24210 " public:\n" 24211 " int i;\n" 24212 "};\n", 24213 Style); 24214 } 24215 24216 TEST_F(FormatTest, LimitlessStringsAndComments) { 24217 auto Style = getLLVMStyleWithColumns(0); 24218 constexpr StringRef Code = 24219 "/**\n" 24220 " * This is a multiline comment with quite some long lines, at least for " 24221 "the LLVM Style.\n" 24222 " * We will redo this with strings and line comments. Just to check if " 24223 "everything is working.\n" 24224 " */\n" 24225 "bool foo() {\n" 24226 " /* Single line multi line comment. */\n" 24227 " const std::string String = \"This is a multiline string with quite " 24228 "some long lines, at least for the LLVM Style.\"\n" 24229 " \"We already did it with multi line " 24230 "comments, and we will do it with line comments. Just to check if " 24231 "everything is working.\";\n" 24232 " // This is a line comment (block) with quite some long lines, at " 24233 "least for the LLVM Style.\n" 24234 " // We already did this with multi line comments and strings. Just to " 24235 "check if everything is working.\n" 24236 " const std::string SmallString = \"Hello World\";\n" 24237 " // Small line comment\n" 24238 " return String.size() > SmallString.size();\n" 24239 "}"; 24240 EXPECT_EQ(Code, format(Code, Style)); 24241 } 24242 24243 TEST_F(FormatTest, FormatDecayCopy) { 24244 // error cases from unit tests 24245 verifyFormat("foo(auto())"); 24246 verifyFormat("foo(auto{})"); 24247 verifyFormat("foo(auto({}))"); 24248 verifyFormat("foo(auto{{}})"); 24249 24250 verifyFormat("foo(auto(1))"); 24251 verifyFormat("foo(auto{1})"); 24252 verifyFormat("foo(new auto(1))"); 24253 verifyFormat("foo(new auto{1})"); 24254 verifyFormat("decltype(auto(1)) x;"); 24255 verifyFormat("decltype(auto{1}) x;"); 24256 verifyFormat("auto(x);"); 24257 verifyFormat("auto{x};"); 24258 verifyFormat("new auto{x};"); 24259 verifyFormat("auto{x} = y;"); 24260 verifyFormat("auto(x) = y;"); // actually a declaration, but this is clearly 24261 // the user's own fault 24262 verifyFormat("integral auto(x) = y;"); // actually a declaration, but this is 24263 // clearly the user's own fault 24264 verifyFormat("auto(*p)() = f;"); // actually a declaration; TODO FIXME 24265 } 24266 24267 TEST_F(FormatTest, Cpp20ModulesSupport) { 24268 FormatStyle Style = getLLVMStyle(); 24269 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 24270 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 24271 24272 verifyFormat("export import foo;", Style); 24273 verifyFormat("export import foo:bar;", Style); 24274 verifyFormat("export import foo.bar;", Style); 24275 verifyFormat("export import foo.bar:baz;", Style); 24276 verifyFormat("export import :bar;", Style); 24277 verifyFormat("export module foo:bar;", Style); 24278 verifyFormat("export module foo;", Style); 24279 verifyFormat("export module foo.bar;", Style); 24280 verifyFormat("export module foo.bar:baz;", Style); 24281 verifyFormat("export import <string_view>;", Style); 24282 24283 verifyFormat("export type_name var;", Style); 24284 verifyFormat("template <class T> export using A = B<T>;", Style); 24285 verifyFormat("export using A = B;", Style); 24286 verifyFormat("export int func() {\n" 24287 " foo();\n" 24288 "}", 24289 Style); 24290 verifyFormat("export struct {\n" 24291 " int foo;\n" 24292 "};", 24293 Style); 24294 verifyFormat("export {\n" 24295 " int foo;\n" 24296 "};", 24297 Style); 24298 verifyFormat("export export char const *hello() { return \"hello\"; }"); 24299 24300 verifyFormat("import bar;", Style); 24301 verifyFormat("import foo.bar;", Style); 24302 verifyFormat("import foo:bar;", Style); 24303 verifyFormat("import :bar;", Style); 24304 verifyFormat("import <ctime>;", Style); 24305 verifyFormat("import \"header\";", Style); 24306 24307 verifyFormat("module foo;", Style); 24308 verifyFormat("module foo:bar;", Style); 24309 verifyFormat("module foo.bar;", Style); 24310 verifyFormat("module;", Style); 24311 24312 verifyFormat("export namespace hi {\n" 24313 "const char *sayhi();\n" 24314 "}", 24315 Style); 24316 24317 verifyFormat("module :private;", Style); 24318 verifyFormat("import <foo/bar.h>;", Style); 24319 verifyFormat("import foo...bar;", Style); 24320 verifyFormat("import ..........;", Style); 24321 verifyFormat("module foo:private;", Style); 24322 verifyFormat("import a", Style); 24323 verifyFormat("module a", Style); 24324 verifyFormat("export import a", Style); 24325 verifyFormat("export module a", Style); 24326 24327 verifyFormat("import", Style); 24328 verifyFormat("module", Style); 24329 verifyFormat("export", Style); 24330 } 24331 24332 TEST_F(FormatTest, CoroutineForCoawait) { 24333 FormatStyle Style = getLLVMStyle(); 24334 verifyFormat("for co_await (auto x : range())\n ;"); 24335 verifyFormat("for (auto i : arr) {\n" 24336 "}", 24337 Style); 24338 verifyFormat("for co_await (auto i : arr) {\n" 24339 "}", 24340 Style); 24341 verifyFormat("for co_await (auto i : foo(T{})) {\n" 24342 "}", 24343 Style); 24344 } 24345 24346 TEST_F(FormatTest, CoroutineCoAwait) { 24347 verifyFormat("int x = co_await foo();"); 24348 verifyFormat("int x = (co_await foo());"); 24349 verifyFormat("co_await (42);"); 24350 verifyFormat("void operator co_await(int);"); 24351 verifyFormat("void operator co_await(a);"); 24352 verifyFormat("co_await a;"); 24353 verifyFormat("co_await missing_await_resume{};"); 24354 verifyFormat("co_await a; // comment"); 24355 verifyFormat("void test0() { co_await a; }"); 24356 verifyFormat("co_await co_await co_await foo();"); 24357 verifyFormat("co_await foo().bar();"); 24358 verifyFormat("co_await [this]() -> Task { co_return x; }"); 24359 verifyFormat("co_await [this](int a, int b) -> Task { co_return co_await " 24360 "foo(); }(x, y);"); 24361 24362 FormatStyle Style = getLLVMStyleWithColumns(40); 24363 verifyFormat("co_await [this](int a, int b) -> Task {\n" 24364 " co_return co_await foo();\n" 24365 "}(x, y);", 24366 Style); 24367 verifyFormat("co_await;"); 24368 } 24369 24370 TEST_F(FormatTest, CoroutineCoYield) { 24371 verifyFormat("int x = co_yield foo();"); 24372 verifyFormat("int x = (co_yield foo());"); 24373 verifyFormat("co_yield (42);"); 24374 verifyFormat("co_yield {42};"); 24375 verifyFormat("co_yield 42;"); 24376 verifyFormat("co_yield n++;"); 24377 verifyFormat("co_yield ++n;"); 24378 verifyFormat("co_yield;"); 24379 } 24380 24381 TEST_F(FormatTest, CoroutineCoReturn) { 24382 verifyFormat("co_return (42);"); 24383 verifyFormat("co_return;"); 24384 verifyFormat("co_return {};"); 24385 verifyFormat("co_return x;"); 24386 verifyFormat("co_return co_await foo();"); 24387 verifyFormat("co_return co_yield foo();"); 24388 } 24389 24390 TEST_F(FormatTest, EmptyShortBlock) { 24391 auto Style = getLLVMStyle(); 24392 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 24393 24394 verifyFormat("try {\n" 24395 " doA();\n" 24396 "} catch (Exception &e) {\n" 24397 " e.printStackTrace();\n" 24398 "}\n", 24399 Style); 24400 24401 verifyFormat("try {\n" 24402 " doA();\n" 24403 "} catch (Exception &e) {}\n", 24404 Style); 24405 } 24406 24407 TEST_F(FormatTest, ShortTemplatedArgumentLists) { 24408 auto Style = getLLVMStyle(); 24409 24410 verifyFormat("template <> struct S : Template<int (*)[]> {};\n", Style); 24411 verifyFormat("template <> struct S : Template<int (*)[10]> {};\n", Style); 24412 verifyFormat("struct Y : X<[] { return 0; }> {};", Style); 24413 verifyFormat("struct Y<[] { return 0; }> {};", Style); 24414 24415 verifyFormat("struct Z : X<decltype([] { return 0; }){}> {};", Style); 24416 verifyFormat("template <int N> struct Foo<char[N]> {};", Style); 24417 } 24418 24419 TEST_F(FormatTest, InsertBraces) { 24420 FormatStyle Style = getLLVMStyle(); 24421 Style.InsertBraces = true; 24422 24423 verifyFormat("// clang-format off\n" 24424 "// comment\n" 24425 "if (a) f();\n" 24426 "// clang-format on\n" 24427 "if (b) {\n" 24428 " g();\n" 24429 "}", 24430 "// clang-format off\n" 24431 "// comment\n" 24432 "if (a) f();\n" 24433 "// clang-format on\n" 24434 "if (b) g();", 24435 Style); 24436 24437 verifyFormat("if (a) {\n" 24438 " switch (b) {\n" 24439 " case 1:\n" 24440 " c = 0;\n" 24441 " break;\n" 24442 " default:\n" 24443 " c = 1;\n" 24444 " }\n" 24445 "}", 24446 "if (a)\n" 24447 " switch (b) {\n" 24448 " case 1:\n" 24449 " c = 0;\n" 24450 " break;\n" 24451 " default:\n" 24452 " c = 1;\n" 24453 " }", 24454 Style); 24455 24456 verifyFormat("for (auto node : nodes) {\n" 24457 " if (node) {\n" 24458 " break;\n" 24459 " }\n" 24460 "}", 24461 "for (auto node : nodes)\n" 24462 " if (node)\n" 24463 " break;", 24464 Style); 24465 24466 verifyFormat("for (auto node : nodes) {\n" 24467 " if (node)\n" 24468 "}", 24469 "for (auto node : nodes)\n" 24470 " if (node)", 24471 Style); 24472 24473 verifyFormat("do {\n" 24474 " --a;\n" 24475 "} while (a);", 24476 "do\n" 24477 " --a;\n" 24478 "while (a);", 24479 Style); 24480 24481 verifyFormat("if (i) {\n" 24482 " ++i;\n" 24483 "} else {\n" 24484 " --i;\n" 24485 "}", 24486 "if (i)\n" 24487 " ++i;\n" 24488 "else {\n" 24489 " --i;\n" 24490 "}", 24491 Style); 24492 24493 verifyFormat("void f() {\n" 24494 " while (j--) {\n" 24495 " while (i) {\n" 24496 " --i;\n" 24497 " }\n" 24498 " }\n" 24499 "}", 24500 "void f() {\n" 24501 " while (j--)\n" 24502 " while (i)\n" 24503 " --i;\n" 24504 "}", 24505 Style); 24506 24507 verifyFormat("f({\n" 24508 " if (a) {\n" 24509 " g();\n" 24510 " }\n" 24511 "});", 24512 "f({\n" 24513 " if (a)\n" 24514 " g();\n" 24515 "});", 24516 Style); 24517 24518 verifyFormat("if (a) {\n" 24519 " f();\n" 24520 "} else if (b) {\n" 24521 " g();\n" 24522 "} else {\n" 24523 " h();\n" 24524 "}", 24525 "if (a)\n" 24526 " f();\n" 24527 "else if (b)\n" 24528 " g();\n" 24529 "else\n" 24530 " h();", 24531 Style); 24532 24533 verifyFormat("if (a) {\n" 24534 " f();\n" 24535 "}\n" 24536 "// comment\n" 24537 "/* comment */", 24538 "if (a)\n" 24539 " f();\n" 24540 "// comment\n" 24541 "/* comment */", 24542 Style); 24543 24544 verifyFormat("if (a) {\n" 24545 " // foo\n" 24546 " // bar\n" 24547 " f();\n" 24548 "}", 24549 "if (a)\n" 24550 " // foo\n" 24551 " // bar\n" 24552 " f();", 24553 Style); 24554 24555 verifyFormat("if (a) { // comment\n" 24556 " // comment\n" 24557 " f();\n" 24558 "}", 24559 "if (a) // comment\n" 24560 " // comment\n" 24561 " f();", 24562 Style); 24563 24564 verifyFormat("if (a) {\n" 24565 " f(); // comment\n" 24566 "}", 24567 "if (a)\n" 24568 " f(); // comment", 24569 Style); 24570 24571 verifyFormat("if (a) {\n" 24572 " f();\n" 24573 "}\n" 24574 "#undef A\n" 24575 "#undef B", 24576 "if (a)\n" 24577 " f();\n" 24578 "#undef A\n" 24579 "#undef B", 24580 Style); 24581 24582 verifyFormat("if (a)\n" 24583 "#ifdef A\n" 24584 " f();\n" 24585 "#else\n" 24586 " g();\n" 24587 "#endif", 24588 Style); 24589 24590 verifyFormat("#if 0\n" 24591 "#elif 1\n" 24592 "#endif\n" 24593 "void f() {\n" 24594 " if (a) {\n" 24595 " g();\n" 24596 " }\n" 24597 "}", 24598 "#if 0\n" 24599 "#elif 1\n" 24600 "#endif\n" 24601 "void f() {\n" 24602 " if (a) g();\n" 24603 "}", 24604 Style); 24605 24606 Style.ColumnLimit = 15; 24607 24608 verifyFormat("#define A \\\n" 24609 " if (a) \\\n" 24610 " f();", 24611 Style); 24612 24613 verifyFormat("if (a + b >\n" 24614 " c) {\n" 24615 " f();\n" 24616 "}", 24617 "if (a + b > c)\n" 24618 " f();", 24619 Style); 24620 } 24621 24622 TEST_F(FormatTest, RemoveBraces) { 24623 FormatStyle Style = getLLVMStyle(); 24624 Style.RemoveBracesLLVM = true; 24625 24626 // The following eight test cases are fully-braced versions of the examples at 24627 // "llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single- 24628 // statement-bodies-of-if-else-loop-statements". 24629 24630 // 1. Omit the braces, since the body is simple and clearly associated with 24631 // the if. 24632 verifyFormat("if (isa<FunctionDecl>(D))\n" 24633 " handleFunctionDecl(D);\n" 24634 "else if (isa<VarDecl>(D))\n" 24635 " handleVarDecl(D);", 24636 "if (isa<FunctionDecl>(D)) {\n" 24637 " handleFunctionDecl(D);\n" 24638 "} else if (isa<VarDecl>(D)) {\n" 24639 " handleVarDecl(D);\n" 24640 "}", 24641 Style); 24642 24643 // 2. Here we document the condition itself and not the body. 24644 verifyFormat("if (isa<VarDecl>(D)) {\n" 24645 " // It is necessary that we explain the situation with this\n" 24646 " // surprisingly long comment, so it would be unclear\n" 24647 " // without the braces whether the following statement is in\n" 24648 " // the scope of the `if`.\n" 24649 " // Because the condition is documented, we can't really\n" 24650 " // hoist this comment that applies to the body above the\n" 24651 " // if.\n" 24652 " handleOtherDecl(D);\n" 24653 "}", 24654 Style); 24655 24656 // 3. Use braces on the outer `if` to avoid a potential dangling else 24657 // situation. 24658 verifyFormat("if (isa<VarDecl>(D)) {\n" 24659 " for (auto *A : D.attrs())\n" 24660 " if (shouldProcessAttr(A))\n" 24661 " handleAttr(A);\n" 24662 "}", 24663 "if (isa<VarDecl>(D)) {\n" 24664 " for (auto *A : D.attrs()) {\n" 24665 " if (shouldProcessAttr(A)) {\n" 24666 " handleAttr(A);\n" 24667 " }\n" 24668 " }\n" 24669 "}", 24670 Style); 24671 24672 // 4. Use braces for the `if` block to keep it uniform with the else block. 24673 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 24674 " handleFunctionDecl(D);\n" 24675 "} else {\n" 24676 " // In this else case, it is necessary that we explain the\n" 24677 " // situation with this surprisingly long comment, so it\n" 24678 " // would be unclear without the braces whether the\n" 24679 " // following statement is in the scope of the `if`.\n" 24680 " handleOtherDecl(D);\n" 24681 "}", 24682 Style); 24683 24684 // 5. This should also omit braces. The `for` loop contains only a single 24685 // statement, so it shouldn't have braces. The `if` also only contains a 24686 // single simple statement (the for loop), so it also should omit braces. 24687 verifyFormat("if (isa<FunctionDecl>(D))\n" 24688 " for (auto *A : D.attrs())\n" 24689 " handleAttr(A);", 24690 "if (isa<FunctionDecl>(D)) {\n" 24691 " for (auto *A : D.attrs()) {\n" 24692 " handleAttr(A);\n" 24693 " }\n" 24694 "}", 24695 Style); 24696 24697 // 6. Use braces for the outer `if` since the nested `for` is braced. 24698 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 24699 " for (auto *A : D.attrs()) {\n" 24700 " // In this for loop body, it is necessary that we explain\n" 24701 " // the situation with this surprisingly long comment,\n" 24702 " // forcing braces on the `for` block.\n" 24703 " handleAttr(A);\n" 24704 " }\n" 24705 "}", 24706 Style); 24707 24708 // 7. Use braces on the outer block because there are more than two levels of 24709 // nesting. 24710 verifyFormat("if (isa<FunctionDecl>(D)) {\n" 24711 " for (auto *A : D.attrs())\n" 24712 " for (ssize_t i : llvm::seq<ssize_t>(count))\n" 24713 " handleAttrOnDecl(D, A, i);\n" 24714 "}", 24715 "if (isa<FunctionDecl>(D)) {\n" 24716 " for (auto *A : D.attrs()) {\n" 24717 " for (ssize_t i : llvm::seq<ssize_t>(count)) {\n" 24718 " handleAttrOnDecl(D, A, i);\n" 24719 " }\n" 24720 " }\n" 24721 "}", 24722 Style); 24723 24724 // 8. Use braces on the outer block because of a nested `if`, otherwise the 24725 // compiler would warn: `add explicit braces to avoid dangling else` 24726 verifyFormat("if (auto *D = dyn_cast<FunctionDecl>(D)) {\n" 24727 " if (shouldProcess(D))\n" 24728 " handleVarDecl(D);\n" 24729 " else\n" 24730 " markAsIgnored(D);\n" 24731 "}", 24732 "if (auto *D = dyn_cast<FunctionDecl>(D)) {\n" 24733 " if (shouldProcess(D)) {\n" 24734 " handleVarDecl(D);\n" 24735 " } else {\n" 24736 " markAsIgnored(D);\n" 24737 " }\n" 24738 "}", 24739 Style); 24740 24741 verifyFormat("if (a)\n" 24742 " b; // comment\n" 24743 "else if (c)\n" 24744 " d; /* comment */\n" 24745 "else\n" 24746 " e;", 24747 "if (a) {\n" 24748 " b; // comment\n" 24749 "} else if (c) {\n" 24750 " d; /* comment */\n" 24751 "} else {\n" 24752 " e;\n" 24753 "}", 24754 Style); 24755 24756 verifyFormat("if (a) {\n" 24757 " b;\n" 24758 " c;\n" 24759 "} else if (d) {\n" 24760 " e;\n" 24761 "}", 24762 Style); 24763 24764 verifyFormat("if (a) {\n" 24765 "#undef NDEBUG\n" 24766 " b;\n" 24767 "} else {\n" 24768 " c;\n" 24769 "}", 24770 Style); 24771 24772 verifyFormat("if (a) {\n" 24773 " // comment\n" 24774 "} else if (b) {\n" 24775 " c;\n" 24776 "}", 24777 Style); 24778 24779 verifyFormat("if (a) {\n" 24780 " b;\n" 24781 "} else {\n" 24782 " { c; }\n" 24783 "}", 24784 Style); 24785 24786 verifyFormat("if (a) {\n" 24787 " if (b) // comment\n" 24788 " c;\n" 24789 "} else if (d) {\n" 24790 " e;\n" 24791 "}", 24792 "if (a) {\n" 24793 " if (b) { // comment\n" 24794 " c;\n" 24795 " }\n" 24796 "} else if (d) {\n" 24797 " e;\n" 24798 "}", 24799 Style); 24800 24801 verifyFormat("if (a) {\n" 24802 " if (b) {\n" 24803 " c;\n" 24804 " // comment\n" 24805 " } else if (d) {\n" 24806 " e;\n" 24807 " }\n" 24808 "}", 24809 Style); 24810 24811 verifyFormat("if (a) {\n" 24812 " if (b)\n" 24813 " c;\n" 24814 "}", 24815 "if (a) {\n" 24816 " if (b) {\n" 24817 " c;\n" 24818 " }\n" 24819 "}", 24820 Style); 24821 24822 verifyFormat("if (a)\n" 24823 " if (b)\n" 24824 " c;\n" 24825 " else\n" 24826 " d;\n" 24827 "else\n" 24828 " e;", 24829 "if (a) {\n" 24830 " if (b) {\n" 24831 " c;\n" 24832 " } else {\n" 24833 " d;\n" 24834 " }\n" 24835 "} else {\n" 24836 " e;\n" 24837 "}", 24838 Style); 24839 24840 verifyFormat("if (a) {\n" 24841 " // comment\n" 24842 " if (b)\n" 24843 " c;\n" 24844 " else if (d)\n" 24845 " e;\n" 24846 "} else {\n" 24847 " g;\n" 24848 "}", 24849 "if (a) {\n" 24850 " // comment\n" 24851 " if (b) {\n" 24852 " c;\n" 24853 " } else if (d) {\n" 24854 " e;\n" 24855 " }\n" 24856 "} else {\n" 24857 " g;\n" 24858 "}", 24859 Style); 24860 24861 verifyFormat("if (a)\n" 24862 " b;\n" 24863 "else if (c)\n" 24864 " d;\n" 24865 "else\n" 24866 " e;", 24867 "if (a) {\n" 24868 " b;\n" 24869 "} else {\n" 24870 " if (c) {\n" 24871 " d;\n" 24872 " } else {\n" 24873 " e;\n" 24874 " }\n" 24875 "}", 24876 Style); 24877 24878 verifyFormat("if (a) {\n" 24879 " if (b)\n" 24880 " c;\n" 24881 " else if (d)\n" 24882 " e;\n" 24883 "} else {\n" 24884 " g;\n" 24885 "}", 24886 "if (a) {\n" 24887 " if (b)\n" 24888 " c;\n" 24889 " else {\n" 24890 " if (d)\n" 24891 " e;\n" 24892 " }\n" 24893 "} else {\n" 24894 " g;\n" 24895 "}", 24896 Style); 24897 24898 verifyFormat("if (a)\n" 24899 " b;\n" 24900 "else if (c)\n" 24901 " while (d)\n" 24902 " e;\n" 24903 "// comment", 24904 "if (a)\n" 24905 "{\n" 24906 " b;\n" 24907 "} else if (c) {\n" 24908 " while (d) {\n" 24909 " e;\n" 24910 " }\n" 24911 "}\n" 24912 "// comment", 24913 Style); 24914 24915 verifyFormat("if (a) {\n" 24916 " b;\n" 24917 "} else if (c) {\n" 24918 " d;\n" 24919 "} else {\n" 24920 " e;\n" 24921 " g;\n" 24922 "}", 24923 Style); 24924 24925 verifyFormat("if (a) {\n" 24926 " b;\n" 24927 "} else if (c) {\n" 24928 " d;\n" 24929 "} else {\n" 24930 " e;\n" 24931 "} // comment", 24932 Style); 24933 24934 verifyFormat("int abs = [](int i) {\n" 24935 " if (i >= 0)\n" 24936 " return i;\n" 24937 " return -i;\n" 24938 "};", 24939 "int abs = [](int i) {\n" 24940 " if (i >= 0) {\n" 24941 " return i;\n" 24942 " }\n" 24943 " return -i;\n" 24944 "};", 24945 Style); 24946 24947 // FIXME: See https://github.com/llvm/llvm-project/issues/53543. 24948 #if 0 24949 Style.ColumnLimit = 65; 24950 24951 verifyFormat("if (condition) {\n" 24952 " ff(Indices,\n" 24953 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 24954 "} else {\n" 24955 " ff(Indices,\n" 24956 " [&](unsigned LHSI, unsigned RHSI) { return true; });\n" 24957 "}", 24958 Style); 24959 24960 Style.ColumnLimit = 20; 24961 24962 verifyFormat("if (a) {\n" 24963 " b = c + // 1 -\n" 24964 " d;\n" 24965 "}", 24966 Style); 24967 24968 verifyFormat("if (a) {\n" 24969 " b = c >= 0 ? d\n" 24970 " : e;\n" 24971 "}", 24972 "if (a) {\n" 24973 " b = c >= 0 ? d : e;\n" 24974 "}", 24975 Style); 24976 #endif 24977 24978 Style.ColumnLimit = 20; 24979 24980 verifyFormat("if (a)\n" 24981 " b = c > 0 ? d : e;", 24982 "if (a) {\n" 24983 " b = c > 0 ? d : e;\n" 24984 "}", 24985 Style); 24986 24987 Style.ColumnLimit = 0; 24988 24989 verifyFormat("if (a)\n" 24990 " b234567890223456789032345678904234567890 = " 24991 "c234567890223456789032345678904234567890;", 24992 "if (a) {\n" 24993 " b234567890223456789032345678904234567890 = " 24994 "c234567890223456789032345678904234567890;\n" 24995 "}", 24996 Style); 24997 } 24998 24999 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndent) { 25000 auto Style = getLLVMStyle(); 25001 25002 StringRef Short = "functionCall(paramA, paramB, paramC);\n" 25003 "void functionDecl(int a, int b, int c);"; 25004 25005 StringRef Medium = "functionCall(paramA, paramB, paramC, paramD, paramE, " 25006 "paramF, paramG, paramH, paramI);\n" 25007 "void functionDecl(int argumentA, int argumentB, int " 25008 "argumentC, int argumentD, int argumentE);"; 25009 25010 verifyFormat(Short, Style); 25011 25012 StringRef NoBreak = "functionCall(paramA, paramB, paramC, paramD, paramE, " 25013 "paramF, paramG, paramH,\n" 25014 " paramI);\n" 25015 "void functionDecl(int argumentA, int argumentB, int " 25016 "argumentC, int argumentD,\n" 25017 " int argumentE);"; 25018 25019 verifyFormat(NoBreak, Medium, Style); 25020 verifyFormat(NoBreak, 25021 "functionCall(\n" 25022 " paramA,\n" 25023 " paramB,\n" 25024 " paramC,\n" 25025 " paramD,\n" 25026 " paramE,\n" 25027 " paramF,\n" 25028 " paramG,\n" 25029 " paramH,\n" 25030 " paramI\n" 25031 ");\n" 25032 "void functionDecl(\n" 25033 " int argumentA,\n" 25034 " int argumentB,\n" 25035 " int argumentC,\n" 25036 " int argumentD,\n" 25037 " int argumentE\n" 25038 ");", 25039 Style); 25040 25041 verifyFormat("outerFunctionCall(nestedFunctionCall(argument1),\n" 25042 " nestedLongFunctionCall(argument1, " 25043 "argument2, argument3,\n" 25044 " argument4, " 25045 "argument5));", 25046 Style); 25047 25048 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 25049 25050 verifyFormat(Short, Style); 25051 verifyFormat( 25052 "functionCall(\n" 25053 " paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, " 25054 "paramI\n" 25055 ");\n" 25056 "void functionDecl(\n" 25057 " int argumentA, int argumentB, int argumentC, int argumentD, int " 25058 "argumentE\n" 25059 ");", 25060 Medium, Style); 25061 25062 Style.AllowAllArgumentsOnNextLine = false; 25063 Style.AllowAllParametersOfDeclarationOnNextLine = false; 25064 25065 verifyFormat(Short, Style); 25066 verifyFormat( 25067 "functionCall(\n" 25068 " paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, " 25069 "paramI\n" 25070 ");\n" 25071 "void functionDecl(\n" 25072 " int argumentA, int argumentB, int argumentC, int argumentD, int " 25073 "argumentE\n" 25074 ");", 25075 Medium, Style); 25076 25077 Style.BinPackArguments = false; 25078 Style.BinPackParameters = false; 25079 25080 verifyFormat(Short, Style); 25081 25082 verifyFormat("functionCall(\n" 25083 " paramA,\n" 25084 " paramB,\n" 25085 " paramC,\n" 25086 " paramD,\n" 25087 " paramE,\n" 25088 " paramF,\n" 25089 " paramG,\n" 25090 " paramH,\n" 25091 " paramI\n" 25092 ");\n" 25093 "void functionDecl(\n" 25094 " int argumentA,\n" 25095 " int argumentB,\n" 25096 " int argumentC,\n" 25097 " int argumentD,\n" 25098 " int argumentE\n" 25099 ");", 25100 Medium, Style); 25101 25102 verifyFormat("outerFunctionCall(\n" 25103 " nestedFunctionCall(argument1),\n" 25104 " nestedLongFunctionCall(\n" 25105 " argument1,\n" 25106 " argument2,\n" 25107 " argument3,\n" 25108 " argument4,\n" 25109 " argument5\n" 25110 " )\n" 25111 ");", 25112 Style); 25113 25114 verifyFormat("int a = (int)b;", Style); 25115 verifyFormat("int a = (int)b;", 25116 "int a = (\n" 25117 " int\n" 25118 ") b;", 25119 Style); 25120 25121 verifyFormat("return (true);", Style); 25122 verifyFormat("return (true);", 25123 "return (\n" 25124 " true\n" 25125 ");", 25126 Style); 25127 25128 verifyFormat("void foo();", Style); 25129 verifyFormat("void foo();", 25130 "void foo(\n" 25131 ");", 25132 Style); 25133 25134 verifyFormat("void foo() {}", Style); 25135 verifyFormat("void foo() {}", 25136 "void foo(\n" 25137 ") {\n" 25138 "}", 25139 Style); 25140 25141 verifyFormat("auto string = std::string();", Style); 25142 verifyFormat("auto string = std::string();", 25143 "auto string = std::string(\n" 25144 ");", 25145 Style); 25146 25147 verifyFormat("void (*functionPointer)() = nullptr;", Style); 25148 verifyFormat("void (*functionPointer)() = nullptr;", 25149 "void (\n" 25150 " *functionPointer\n" 25151 ")\n" 25152 "(\n" 25153 ") = nullptr;", 25154 Style); 25155 } 25156 25157 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentIfStatement) { 25158 auto Style = getLLVMStyle(); 25159 25160 verifyFormat("if (foo()) {\n" 25161 " return;\n" 25162 "}", 25163 Style); 25164 25165 verifyFormat("if (quitelongarg !=\n" 25166 " (alsolongarg - 1)) { // ABC is a very longgggggggggggg " 25167 "comment\n" 25168 " return;\n" 25169 "}", 25170 Style); 25171 25172 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 25173 25174 verifyFormat("if (foo()) {\n" 25175 " return;\n" 25176 "}", 25177 Style); 25178 25179 verifyFormat("if (quitelongarg !=\n" 25180 " (alsolongarg - 1)) { // ABC is a very longgggggggggggg " 25181 "comment\n" 25182 " return;\n" 25183 "}", 25184 Style); 25185 } 25186 25187 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentForStatement) { 25188 auto Style = getLLVMStyle(); 25189 25190 verifyFormat("for (int i = 0; i < 5; ++i) {\n" 25191 " doSomething();\n" 25192 "}", 25193 Style); 25194 25195 verifyFormat("for (int myReallyLongCountVariable = 0; " 25196 "myReallyLongCountVariable < count;\n" 25197 " myReallyLongCountVariable++) {\n" 25198 " doSomething();\n" 25199 "}", 25200 Style); 25201 25202 Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent; 25203 25204 verifyFormat("for (int i = 0; i < 5; ++i) {\n" 25205 " doSomething();\n" 25206 "}", 25207 Style); 25208 25209 verifyFormat("for (int myReallyLongCountVariable = 0; " 25210 "myReallyLongCountVariable < count;\n" 25211 " myReallyLongCountVariable++) {\n" 25212 " doSomething();\n" 25213 "}", 25214 Style); 25215 } 25216 25217 TEST_F(FormatTest, UnderstandsDigraphs) { 25218 verifyFormat("int arr<:5:> = {};"); 25219 verifyFormat("int arr[5] = <%%>;"); 25220 verifyFormat("int arr<:::qualified_variable:> = {};"); 25221 verifyFormat("int arr[::qualified_variable] = <%%>;"); 25222 verifyFormat("%:include <header>"); 25223 verifyFormat("%:define A x##y"); 25224 verifyFormat("#define A x%:%:y"); 25225 } 25226 25227 } // namespace 25228 } // namespace format 25229 } // namespace clang 25230