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("while (true)\n" 1468 " ;", 1469 AllowsMergedLoops); 1470 verifyFormat("for (;;)\n" 1471 " ;", 1472 AllowsMergedLoops); 1473 verifyFormat("for (;;)\n" 1474 " for (;;) continue;", 1475 AllowsMergedLoops); 1476 verifyFormat("for (;;) // Can't merge this\n" 1477 " continue;", 1478 AllowsMergedLoops); 1479 verifyFormat("for (;;) /* still don't merge */\n" 1480 " continue;", 1481 AllowsMergedLoops); 1482 verifyFormat("do a++;\n" 1483 "while (true);", 1484 AllowsMergedLoops); 1485 verifyFormat("do /* Don't merge */\n" 1486 " a++;\n" 1487 "while (true);", 1488 AllowsMergedLoops); 1489 verifyFormat("do // Don't merge\n" 1490 " a++;\n" 1491 "while (true);", 1492 AllowsMergedLoops); 1493 verifyFormat("do\n" 1494 " // Don't merge\n" 1495 " a++;\n" 1496 "while (true);", 1497 AllowsMergedLoops); 1498 // Without braces labels are interpreted differently. 1499 verifyFormat("{\n" 1500 " do\n" 1501 " label:\n" 1502 " a++;\n" 1503 " while (true);\n" 1504 "}", 1505 AllowsMergedLoops); 1506 } 1507 1508 TEST_F(FormatTest, FormatShortBracedStatements) { 1509 FormatStyle AllowSimpleBracedStatements = getLLVMStyle(); 1510 AllowSimpleBracedStatements.IfMacros.push_back("MYIF"); 1511 // Where line-lengths matter, a 2-letter synonym that maintains line length. 1512 // Not IF to avoid any confusion that IF is somehow special. 1513 AllowSimpleBracedStatements.IfMacros.push_back("FI"); 1514 AllowSimpleBracedStatements.ColumnLimit = 40; 1515 AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine = 1516 FormatStyle::SBS_Always; 1517 1518 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1519 FormatStyle::SIS_WithoutElse; 1520 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true; 1521 1522 AllowSimpleBracedStatements.BreakBeforeBraces = FormatStyle::BS_Custom; 1523 AllowSimpleBracedStatements.BraceWrapping.AfterFunction = true; 1524 AllowSimpleBracedStatements.BraceWrapping.SplitEmptyRecord = false; 1525 1526 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1527 verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements); 1528 verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1529 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1530 verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements); 1531 verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1532 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1533 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1534 verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements); 1535 verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements); 1536 verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1537 verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements); 1538 verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements); 1539 verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1540 verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements); 1541 verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements); 1542 verifyFormat("if (true) { fffffffffffffffffffffff(); }", 1543 AllowSimpleBracedStatements); 1544 verifyFormat("if (true) {\n" 1545 " ffffffffffffffffffffffff();\n" 1546 "}", 1547 AllowSimpleBracedStatements); 1548 verifyFormat("if (true) {\n" 1549 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1550 "}", 1551 AllowSimpleBracedStatements); 1552 verifyFormat("if (true) { //\n" 1553 " f();\n" 1554 "}", 1555 AllowSimpleBracedStatements); 1556 verifyFormat("if (true) {\n" 1557 " f();\n" 1558 " f();\n" 1559 "}", 1560 AllowSimpleBracedStatements); 1561 verifyFormat("if (true) {\n" 1562 " f();\n" 1563 "} else {\n" 1564 " f();\n" 1565 "}", 1566 AllowSimpleBracedStatements); 1567 verifyFormat("FI (true) { fffffffffffffffffffffff(); }", 1568 AllowSimpleBracedStatements); 1569 verifyFormat("MYIF (true) {\n" 1570 " ffffffffffffffffffffffff();\n" 1571 "}", 1572 AllowSimpleBracedStatements); 1573 verifyFormat("MYIF (true) {\n" 1574 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1575 "}", 1576 AllowSimpleBracedStatements); 1577 verifyFormat("MYIF (true) { //\n" 1578 " f();\n" 1579 "}", 1580 AllowSimpleBracedStatements); 1581 verifyFormat("MYIF (true) {\n" 1582 " f();\n" 1583 " f();\n" 1584 "}", 1585 AllowSimpleBracedStatements); 1586 verifyFormat("MYIF (true) {\n" 1587 " f();\n" 1588 "} else {\n" 1589 " f();\n" 1590 "}", 1591 AllowSimpleBracedStatements); 1592 1593 verifyFormat("struct A2 {\n" 1594 " int X;\n" 1595 "};", 1596 AllowSimpleBracedStatements); 1597 verifyFormat("typedef struct A2 {\n" 1598 " int X;\n" 1599 "} A2_t;", 1600 AllowSimpleBracedStatements); 1601 verifyFormat("template <int> struct A2 {\n" 1602 " struct B {};\n" 1603 "};", 1604 AllowSimpleBracedStatements); 1605 1606 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1607 FormatStyle::SIS_Never; 1608 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1609 verifyFormat("if (true) {\n" 1610 " f();\n" 1611 "}", 1612 AllowSimpleBracedStatements); 1613 verifyFormat("if (true) {\n" 1614 " f();\n" 1615 "} else {\n" 1616 " f();\n" 1617 "}", 1618 AllowSimpleBracedStatements); 1619 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1620 verifyFormat("MYIF (true) {\n" 1621 " f();\n" 1622 "}", 1623 AllowSimpleBracedStatements); 1624 verifyFormat("MYIF (true) {\n" 1625 " f();\n" 1626 "} else {\n" 1627 " f();\n" 1628 "}", 1629 AllowSimpleBracedStatements); 1630 1631 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false; 1632 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1633 verifyFormat("while (true) {\n" 1634 " f();\n" 1635 "}", 1636 AllowSimpleBracedStatements); 1637 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1638 verifyFormat("for (;;) {\n" 1639 " f();\n" 1640 "}", 1641 AllowSimpleBracedStatements); 1642 1643 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1644 FormatStyle::SIS_WithoutElse; 1645 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true; 1646 AllowSimpleBracedStatements.BraceWrapping.AfterControlStatement = 1647 FormatStyle::BWACS_Always; 1648 1649 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1650 verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements); 1651 verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1652 verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements); 1653 verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements); 1654 verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements); 1655 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1656 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1657 verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements); 1658 verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements); 1659 verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1660 verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements); 1661 verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements); 1662 verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); 1663 verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements); 1664 verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements); 1665 verifyFormat("if (true) { fffffffffffffffffffffff(); }", 1666 AllowSimpleBracedStatements); 1667 verifyFormat("if (true)\n" 1668 "{\n" 1669 " ffffffffffffffffffffffff();\n" 1670 "}", 1671 AllowSimpleBracedStatements); 1672 verifyFormat("if (true)\n" 1673 "{\n" 1674 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1675 "}", 1676 AllowSimpleBracedStatements); 1677 verifyFormat("if (true)\n" 1678 "{ //\n" 1679 " f();\n" 1680 "}", 1681 AllowSimpleBracedStatements); 1682 verifyFormat("if (true)\n" 1683 "{\n" 1684 " f();\n" 1685 " f();\n" 1686 "}", 1687 AllowSimpleBracedStatements); 1688 verifyFormat("if (true)\n" 1689 "{\n" 1690 " f();\n" 1691 "} else\n" 1692 "{\n" 1693 " f();\n" 1694 "}", 1695 AllowSimpleBracedStatements); 1696 verifyFormat("FI (true) { fffffffffffffffffffffff(); }", 1697 AllowSimpleBracedStatements); 1698 verifyFormat("MYIF (true)\n" 1699 "{\n" 1700 " ffffffffffffffffffffffff();\n" 1701 "}", 1702 AllowSimpleBracedStatements); 1703 verifyFormat("MYIF (true)\n" 1704 "{\n" 1705 " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" 1706 "}", 1707 AllowSimpleBracedStatements); 1708 verifyFormat("MYIF (true)\n" 1709 "{ //\n" 1710 " f();\n" 1711 "}", 1712 AllowSimpleBracedStatements); 1713 verifyFormat("MYIF (true)\n" 1714 "{\n" 1715 " f();\n" 1716 " f();\n" 1717 "}", 1718 AllowSimpleBracedStatements); 1719 verifyFormat("MYIF (true)\n" 1720 "{\n" 1721 " f();\n" 1722 "} else\n" 1723 "{\n" 1724 " f();\n" 1725 "}", 1726 AllowSimpleBracedStatements); 1727 1728 AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = 1729 FormatStyle::SIS_Never; 1730 verifyFormat("if (true) {}", AllowSimpleBracedStatements); 1731 verifyFormat("if (true)\n" 1732 "{\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("MYIF (true) {}", AllowSimpleBracedStatements); 1745 verifyFormat("MYIF (true)\n" 1746 "{\n" 1747 " f();\n" 1748 "}", 1749 AllowSimpleBracedStatements); 1750 verifyFormat("MYIF (true)\n" 1751 "{\n" 1752 " f();\n" 1753 "} else\n" 1754 "{\n" 1755 " f();\n" 1756 "}", 1757 AllowSimpleBracedStatements); 1758 1759 AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false; 1760 verifyFormat("while (true) {}", AllowSimpleBracedStatements); 1761 verifyFormat("while (true)\n" 1762 "{\n" 1763 " f();\n" 1764 "}", 1765 AllowSimpleBracedStatements); 1766 verifyFormat("for (;;) {}", AllowSimpleBracedStatements); 1767 verifyFormat("for (;;)\n" 1768 "{\n" 1769 " f();\n" 1770 "}", 1771 AllowSimpleBracedStatements); 1772 } 1773 1774 TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) { 1775 FormatStyle Style = getLLVMStyleWithColumns(60); 1776 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 1777 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse; 1778 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 1779 EXPECT_EQ("#define A \\\n" 1780 " if (HANDLEwernufrnuLwrmviferuvnierv) \\\n" 1781 " { \\\n" 1782 " RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n" 1783 " }\n" 1784 "X;", 1785 format("#define A \\\n" 1786 " if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n" 1787 " RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n" 1788 " }\n" 1789 "X;", 1790 Style)); 1791 } 1792 1793 TEST_F(FormatTest, ParseIfElse) { 1794 verifyFormat("if (true)\n" 1795 " if (true)\n" 1796 " if (true)\n" 1797 " f();\n" 1798 " else\n" 1799 " g();\n" 1800 " else\n" 1801 " h();\n" 1802 "else\n" 1803 " i();"); 1804 verifyFormat("if (true)\n" 1805 " if (true)\n" 1806 " if (true) {\n" 1807 " if (true)\n" 1808 " f();\n" 1809 " } else {\n" 1810 " g();\n" 1811 " }\n" 1812 " else\n" 1813 " h();\n" 1814 "else {\n" 1815 " i();\n" 1816 "}"); 1817 verifyFormat("if (true)\n" 1818 " if constexpr (true)\n" 1819 " if (true) {\n" 1820 " if constexpr (true)\n" 1821 " f();\n" 1822 " } else {\n" 1823 " g();\n" 1824 " }\n" 1825 " else\n" 1826 " h();\n" 1827 "else {\n" 1828 " i();\n" 1829 "}"); 1830 verifyFormat("if (true)\n" 1831 " if CONSTEXPR (true)\n" 1832 " if (true) {\n" 1833 " if CONSTEXPR (true)\n" 1834 " f();\n" 1835 " } else {\n" 1836 " g();\n" 1837 " }\n" 1838 " else\n" 1839 " h();\n" 1840 "else {\n" 1841 " i();\n" 1842 "}"); 1843 verifyFormat("void f() {\n" 1844 " if (a) {\n" 1845 " } else {\n" 1846 " }\n" 1847 "}"); 1848 } 1849 1850 TEST_F(FormatTest, ElseIf) { 1851 verifyFormat("if (a) {\n} else if (b) {\n}"); 1852 verifyFormat("if (a)\n" 1853 " f();\n" 1854 "else if (b)\n" 1855 " g();\n" 1856 "else\n" 1857 " h();"); 1858 verifyFormat("if (a)\n" 1859 " f();\n" 1860 "else // comment\n" 1861 " if (b) {\n" 1862 " g();\n" 1863 " h();\n" 1864 " }"); 1865 verifyFormat("if constexpr (a)\n" 1866 " f();\n" 1867 "else if constexpr (b)\n" 1868 " g();\n" 1869 "else\n" 1870 " h();"); 1871 verifyFormat("if CONSTEXPR (a)\n" 1872 " f();\n" 1873 "else if CONSTEXPR (b)\n" 1874 " g();\n" 1875 "else\n" 1876 " h();"); 1877 verifyFormat("if (a) {\n" 1878 " f();\n" 1879 "}\n" 1880 "// or else ..\n" 1881 "else {\n" 1882 " g()\n" 1883 "}"); 1884 1885 verifyFormat("if (a) {\n" 1886 "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 1887 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 1888 "}"); 1889 verifyFormat("if (a) {\n" 1890 "} else if constexpr (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 1891 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 1892 "}"); 1893 verifyFormat("if (a) {\n" 1894 "} else if CONSTEXPR (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 1895 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 1896 "}"); 1897 verifyFormat("if (a) {\n" 1898 "} else if (\n" 1899 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 1900 "}", 1901 getLLVMStyleWithColumns(62)); 1902 verifyFormat("if (a) {\n" 1903 "} else if constexpr (\n" 1904 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 1905 "}", 1906 getLLVMStyleWithColumns(62)); 1907 verifyFormat("if (a) {\n" 1908 "} else if CONSTEXPR (\n" 1909 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 1910 "}", 1911 getLLVMStyleWithColumns(62)); 1912 } 1913 1914 TEST_F(FormatTest, SeparatePointerReferenceAlignment) { 1915 FormatStyle Style = getLLVMStyle(); 1916 // Check first the default LLVM style 1917 // Style.PointerAlignment = FormatStyle::PAS_Right; 1918 // Style.ReferenceAlignment = FormatStyle::RAS_Pointer; 1919 verifyFormat("int *f1(int *a, int &b, int &&c);", Style); 1920 verifyFormat("int &f2(int &&c, int *a, int &b);", Style); 1921 verifyFormat("int &&f3(int &b, int &&c, int *a);", Style); 1922 verifyFormat("int *f1(int &a) const &;", Style); 1923 verifyFormat("int *f1(int &a) const & = 0;", Style); 1924 verifyFormat("int *a = f1();", Style); 1925 verifyFormat("int &b = f2();", Style); 1926 verifyFormat("int &&c = f3();", Style); 1927 verifyFormat("for (auto a = 0, b = 0; const auto &c : {1, 2, 3})", Style); 1928 verifyFormat("for (auto a = 0, b = 0; const int &c : {1, 2, 3})", Style); 1929 verifyFormat("for (auto a = 0, b = 0; const Foo &c : {1, 2, 3})", Style); 1930 verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style); 1931 verifyFormat("for (int a = 0, b = 0; const auto &c : {1, 2, 3})", Style); 1932 verifyFormat("for (int a = 0, b = 0; const int &c : {1, 2, 3})", Style); 1933 verifyFormat("for (int a = 0, b = 0; const Foo &c : {1, 2, 3})", Style); 1934 verifyFormat("for (int a = 0, b++; const auto &c : {1, 2, 3})", Style); 1935 verifyFormat("for (int a = 0, b++; const int &c : {1, 2, 3})", Style); 1936 verifyFormat("for (int a = 0, b++; const Foo &c : {1, 2, 3})", Style); 1937 verifyFormat("for (auto x = 0; auto &c : {1, 2, 3})", Style); 1938 verifyFormat("for (auto x = 0; int &c : {1, 2, 3})", Style); 1939 verifyFormat("for (int x = 0; auto &c : {1, 2, 3})", Style); 1940 verifyFormat("for (int x = 0; int &c : {1, 2, 3})", Style); 1941 verifyFormat("for (f(); auto &c : {1, 2, 3})", Style); 1942 verifyFormat("for (f(); int &c : {1, 2, 3})", Style); 1943 1944 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 1945 verifyFormat("Const unsigned int *c;\n" 1946 "const unsigned int *d;\n" 1947 "Const unsigned int &e;\n" 1948 "const unsigned int &f;\n" 1949 "const unsigned &&g;\n" 1950 "Const unsigned h;", 1951 Style); 1952 1953 Style.PointerAlignment = FormatStyle::PAS_Left; 1954 Style.ReferenceAlignment = FormatStyle::RAS_Pointer; 1955 verifyFormat("int* f1(int* a, int& b, int&& c);", Style); 1956 verifyFormat("int& f2(int&& c, int* a, int& b);", Style); 1957 verifyFormat("int&& f3(int& b, int&& c, int* a);", Style); 1958 verifyFormat("int* f1(int& a) const& = 0;", Style); 1959 verifyFormat("int* a = f1();", Style); 1960 verifyFormat("int& b = f2();", Style); 1961 verifyFormat("int&& c = f3();", Style); 1962 verifyFormat("for (auto a = 0, b = 0; const auto& c : {1, 2, 3})", Style); 1963 verifyFormat("for (auto a = 0, b = 0; const int& c : {1, 2, 3})", Style); 1964 verifyFormat("for (auto a = 0, b = 0; const Foo& c : {1, 2, 3})", Style); 1965 verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style); 1966 verifyFormat("for (int a = 0, b = 0; const auto& c : {1, 2, 3})", Style); 1967 verifyFormat("for (int a = 0, b = 0; const int& c : {1, 2, 3})", Style); 1968 verifyFormat("for (int a = 0, b = 0; const Foo& c : {1, 2, 3})", Style); 1969 verifyFormat("for (int a = 0, b = 0; const Foo* c : {1, 2, 3})", Style); 1970 verifyFormat("for (int a = 0, b++; const auto& c : {1, 2, 3})", Style); 1971 verifyFormat("for (int a = 0, b++; const int& c : {1, 2, 3})", Style); 1972 verifyFormat("for (int a = 0, b++; const Foo& c : {1, 2, 3})", Style); 1973 verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style); 1974 verifyFormat("for (auto x = 0; auto& c : {1, 2, 3})", Style); 1975 verifyFormat("for (auto x = 0; int& c : {1, 2, 3})", Style); 1976 verifyFormat("for (int x = 0; auto& c : {1, 2, 3})", Style); 1977 verifyFormat("for (int x = 0; int& c : {1, 2, 3})", Style); 1978 verifyFormat("for (f(); auto& c : {1, 2, 3})", Style); 1979 verifyFormat("for (f(); int& c : {1, 2, 3})", Style); 1980 1981 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 1982 verifyFormat("Const unsigned int* c;\n" 1983 "const unsigned int* d;\n" 1984 "Const unsigned int& e;\n" 1985 "const unsigned int& f;\n" 1986 "const unsigned&& g;\n" 1987 "Const unsigned h;", 1988 Style); 1989 1990 Style.PointerAlignment = FormatStyle::PAS_Right; 1991 Style.ReferenceAlignment = FormatStyle::RAS_Left; 1992 verifyFormat("int *f1(int *a, int& b, int&& c);", Style); 1993 verifyFormat("int& f2(int&& c, int *a, int& b);", Style); 1994 verifyFormat("int&& f3(int& b, int&& c, int *a);", Style); 1995 verifyFormat("int *a = f1();", Style); 1996 verifyFormat("int& b = f2();", Style); 1997 verifyFormat("int&& c = f3();", Style); 1998 verifyFormat("for (auto a = 0, b = 0; const Foo *c : {1, 2, 3})", Style); 1999 verifyFormat("for (int a = 0, b = 0; const Foo *c : {1, 2, 3})", Style); 2000 verifyFormat("for (int a = 0, b++; const Foo *c : {1, 2, 3})", Style); 2001 2002 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 2003 verifyFormat("Const unsigned int *c;\n" 2004 "const unsigned int *d;\n" 2005 "Const unsigned int& e;\n" 2006 "const unsigned int& f;\n" 2007 "const unsigned g;\n" 2008 "Const unsigned h;", 2009 Style); 2010 2011 Style.PointerAlignment = FormatStyle::PAS_Left; 2012 Style.ReferenceAlignment = FormatStyle::RAS_Middle; 2013 verifyFormat("int* f1(int* a, int & b, int && c);", Style); 2014 verifyFormat("int & f2(int && c, int* a, int & b);", Style); 2015 verifyFormat("int && f3(int & b, int && c, int* a);", Style); 2016 verifyFormat("int* a = f1();", Style); 2017 verifyFormat("int & b = f2();", Style); 2018 verifyFormat("int && c = f3();", Style); 2019 verifyFormat("for (auto a = 0, b = 0; const auto & c : {1, 2, 3})", Style); 2020 verifyFormat("for (auto a = 0, b = 0; const int & c : {1, 2, 3})", Style); 2021 verifyFormat("for (auto a = 0, b = 0; const Foo & c : {1, 2, 3})", Style); 2022 verifyFormat("for (auto a = 0, b = 0; const Foo* c : {1, 2, 3})", Style); 2023 verifyFormat("for (int a = 0, b++; const auto & c : {1, 2, 3})", Style); 2024 verifyFormat("for (int a = 0, b++; const int & c : {1, 2, 3})", Style); 2025 verifyFormat("for (int a = 0, b++; const Foo & c : {1, 2, 3})", Style); 2026 verifyFormat("for (int a = 0, b++; const Foo* c : {1, 2, 3})", Style); 2027 verifyFormat("for (auto x = 0; auto & c : {1, 2, 3})", Style); 2028 verifyFormat("for (auto x = 0; int & c : {1, 2, 3})", Style); 2029 verifyFormat("for (int x = 0; auto & c : {1, 2, 3})", Style); 2030 verifyFormat("for (int x = 0; int & c : {1, 2, 3})", Style); 2031 verifyFormat("for (f(); auto & c : {1, 2, 3})", Style); 2032 verifyFormat("for (f(); int & c : {1, 2, 3})", Style); 2033 2034 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 2035 verifyFormat("Const unsigned int* c;\n" 2036 "const unsigned int* d;\n" 2037 "Const unsigned int & e;\n" 2038 "const unsigned int & f;\n" 2039 "const unsigned && g;\n" 2040 "Const unsigned h;", 2041 Style); 2042 2043 Style.PointerAlignment = FormatStyle::PAS_Middle; 2044 Style.ReferenceAlignment = FormatStyle::RAS_Right; 2045 verifyFormat("int * f1(int * a, int &b, int &&c);", Style); 2046 verifyFormat("int &f2(int &&c, int * a, int &b);", Style); 2047 verifyFormat("int &&f3(int &b, int &&c, int * a);", Style); 2048 verifyFormat("int * a = f1();", Style); 2049 verifyFormat("int &b = f2();", Style); 2050 verifyFormat("int &&c = f3();", Style); 2051 verifyFormat("for (auto a = 0, b = 0; const Foo * c : {1, 2, 3})", Style); 2052 verifyFormat("for (int a = 0, b = 0; const Foo * c : {1, 2, 3})", Style); 2053 verifyFormat("for (int a = 0, b++; const Foo * c : {1, 2, 3})", Style); 2054 2055 // FIXME: we don't handle this yet, so output may be arbitrary until it's 2056 // specifically handled 2057 // verifyFormat("int Add2(BTree * &Root, char * szToAdd)", Style); 2058 } 2059 2060 TEST_F(FormatTest, FormatsForLoop) { 2061 verifyFormat( 2062 "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n" 2063 " ++VeryVeryLongLoopVariable)\n" 2064 " ;"); 2065 verifyFormat("for (;;)\n" 2066 " f();"); 2067 verifyFormat("for (;;) {\n}"); 2068 verifyFormat("for (;;) {\n" 2069 " f();\n" 2070 "}"); 2071 verifyFormat("for (int i = 0; (i < 10); ++i) {\n}"); 2072 2073 verifyFormat( 2074 "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n" 2075 " E = UnwrappedLines.end();\n" 2076 " I != E; ++I) {\n}"); 2077 2078 verifyFormat( 2079 "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n" 2080 " ++IIIII) {\n}"); 2081 verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n" 2082 " aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n" 2083 " aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}"); 2084 verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n" 2085 " I = FD->getDeclsInPrototypeScope().begin(),\n" 2086 " E = FD->getDeclsInPrototypeScope().end();\n" 2087 " I != E; ++I) {\n}"); 2088 verifyFormat("for (SmallVectorImpl<TemplateIdAnnotationn *>::iterator\n" 2089 " I = Container.begin(),\n" 2090 " E = Container.end();\n" 2091 " I != E; ++I) {\n}", 2092 getLLVMStyleWithColumns(76)); 2093 2094 verifyFormat( 2095 "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n" 2096 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n" 2097 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2098 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 2099 " ++aaaaaaaaaaa) {\n}"); 2100 verifyFormat("for (int i = 0; i < aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 2101 " bbbbbbbbbbbbbbbbbbbb < ccccccccccccccc;\n" 2102 " ++i) {\n}"); 2103 verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n" 2104 " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n" 2105 "}"); 2106 verifyFormat("for (some_namespace::SomeIterator iter( // force break\n" 2107 " aaaaaaaaaa);\n" 2108 " iter; ++iter) {\n" 2109 "}"); 2110 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 2111 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 2112 " aaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbbbbbbb;\n" 2113 " ++aaaaaaaaaaaaaaaaaaaaaaaaaaa) {"); 2114 2115 // These should not be formatted as Objective-C for-in loops. 2116 verifyFormat("for (Foo *x = 0; x != in; x++) {\n}"); 2117 verifyFormat("Foo *x;\nfor (x = 0; x != in; x++) {\n}"); 2118 verifyFormat("Foo *x;\nfor (x in y) {\n}"); 2119 verifyFormat( 2120 "for (const Foo<Bar> &baz = in.value(); !baz.at_end(); ++baz) {\n}"); 2121 2122 FormatStyle NoBinPacking = getLLVMStyle(); 2123 NoBinPacking.BinPackParameters = false; 2124 verifyFormat("for (int aaaaaaaaaaa = 1;\n" 2125 " aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n" 2126 " aaaaaaaaaaaaaaaa,\n" 2127 " aaaaaaaaaaaaaaaa,\n" 2128 " aaaaaaaaaaaaaaaa);\n" 2129 " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n" 2130 "}", 2131 NoBinPacking); 2132 verifyFormat( 2133 "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n" 2134 " E = UnwrappedLines.end();\n" 2135 " I != E;\n" 2136 " ++I) {\n}", 2137 NoBinPacking); 2138 2139 FormatStyle AlignLeft = getLLVMStyle(); 2140 AlignLeft.PointerAlignment = FormatStyle::PAS_Left; 2141 verifyFormat("for (A* a = start; a < end; ++a, ++value) {\n}", AlignLeft); 2142 } 2143 2144 TEST_F(FormatTest, RangeBasedForLoops) { 2145 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 2146 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 2147 verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n" 2148 " aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}"); 2149 verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n" 2150 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 2151 verifyFormat("for (aaaaaaaaa aaaaaaaaaaaaaaaaaaaaa :\n" 2152 " aaaaaaaaaaaa.aaaaaaaaaaaa().aaaaaaaaa().a()) {\n}"); 2153 } 2154 2155 TEST_F(FormatTest, ForEachLoops) { 2156 verifyFormat("void f() {\n" 2157 " foreach (Item *item, itemlist) {}\n" 2158 " Q_FOREACH (Item *item, itemlist) {}\n" 2159 " BOOST_FOREACH (Item *item, itemlist) {}\n" 2160 " UNKNOWN_FORACH(Item * item, itemlist) {}\n" 2161 "}"); 2162 2163 FormatStyle Style = getLLVMStyle(); 2164 Style.SpaceBeforeParens = 2165 FormatStyle::SBPO_ControlStatementsExceptControlMacros; 2166 verifyFormat("void f() {\n" 2167 " foreach(Item *item, itemlist) {}\n" 2168 " Q_FOREACH(Item *item, itemlist) {}\n" 2169 " BOOST_FOREACH(Item *item, itemlist) {}\n" 2170 " UNKNOWN_FORACH(Item * item, itemlist) {}\n" 2171 "}", 2172 Style); 2173 2174 // As function-like macros. 2175 verifyFormat("#define foreach(x, y)\n" 2176 "#define Q_FOREACH(x, y)\n" 2177 "#define BOOST_FOREACH(x, y)\n" 2178 "#define UNKNOWN_FOREACH(x, y)\n"); 2179 2180 // Not as function-like macros. 2181 verifyFormat("#define foreach (x, y)\n" 2182 "#define Q_FOREACH (x, y)\n" 2183 "#define BOOST_FOREACH (x, y)\n" 2184 "#define UNKNOWN_FOREACH (x, y)\n"); 2185 2186 // handle microsoft non standard extension 2187 verifyFormat("for each (char c in x->MyStringProperty)"); 2188 } 2189 2190 TEST_F(FormatTest, FormatsWhileLoop) { 2191 verifyFormat("while (true) {\n}"); 2192 verifyFormat("while (true)\n" 2193 " f();"); 2194 verifyFormat("while () {\n}"); 2195 verifyFormat("while () {\n" 2196 " f();\n" 2197 "}"); 2198 } 2199 2200 TEST_F(FormatTest, FormatsDoWhile) { 2201 verifyFormat("do {\n" 2202 " do_something();\n" 2203 "} while (something());"); 2204 verifyFormat("do\n" 2205 " do_something();\n" 2206 "while (something());"); 2207 } 2208 2209 TEST_F(FormatTest, FormatsSwitchStatement) { 2210 verifyFormat("switch (x) {\n" 2211 "case 1:\n" 2212 " f();\n" 2213 " break;\n" 2214 "case kFoo:\n" 2215 "case ns::kBar:\n" 2216 "case kBaz:\n" 2217 " break;\n" 2218 "default:\n" 2219 " g();\n" 2220 " break;\n" 2221 "}"); 2222 verifyFormat("switch (x) {\n" 2223 "case 1: {\n" 2224 " f();\n" 2225 " break;\n" 2226 "}\n" 2227 "case 2: {\n" 2228 " break;\n" 2229 "}\n" 2230 "}"); 2231 verifyFormat("switch (x) {\n" 2232 "case 1: {\n" 2233 " f();\n" 2234 " {\n" 2235 " g();\n" 2236 " h();\n" 2237 " }\n" 2238 " break;\n" 2239 "}\n" 2240 "}"); 2241 verifyFormat("switch (x) {\n" 2242 "case 1: {\n" 2243 " f();\n" 2244 " if (foo) {\n" 2245 " g();\n" 2246 " h();\n" 2247 " }\n" 2248 " break;\n" 2249 "}\n" 2250 "}"); 2251 verifyFormat("switch (x) {\n" 2252 "case 1: {\n" 2253 " f();\n" 2254 " g();\n" 2255 "} break;\n" 2256 "}"); 2257 verifyFormat("switch (test)\n" 2258 " ;"); 2259 verifyFormat("switch (x) {\n" 2260 "default: {\n" 2261 " // Do nothing.\n" 2262 "}\n" 2263 "}"); 2264 verifyFormat("switch (x) {\n" 2265 "// comment\n" 2266 "// if 1, do f()\n" 2267 "case 1:\n" 2268 " f();\n" 2269 "}"); 2270 verifyFormat("switch (x) {\n" 2271 "case 1:\n" 2272 " // Do amazing stuff\n" 2273 " {\n" 2274 " f();\n" 2275 " g();\n" 2276 " }\n" 2277 " break;\n" 2278 "}"); 2279 verifyFormat("#define A \\\n" 2280 " switch (x) { \\\n" 2281 " case a: \\\n" 2282 " foo = b; \\\n" 2283 " }", 2284 getLLVMStyleWithColumns(20)); 2285 verifyFormat("#define OPERATION_CASE(name) \\\n" 2286 " case OP_name: \\\n" 2287 " return operations::Operation##name\n", 2288 getLLVMStyleWithColumns(40)); 2289 verifyFormat("switch (x) {\n" 2290 "case 1:;\n" 2291 "default:;\n" 2292 " int i;\n" 2293 "}"); 2294 2295 verifyGoogleFormat("switch (x) {\n" 2296 " case 1:\n" 2297 " f();\n" 2298 " break;\n" 2299 " case kFoo:\n" 2300 " case ns::kBar:\n" 2301 " case kBaz:\n" 2302 " break;\n" 2303 " default:\n" 2304 " g();\n" 2305 " break;\n" 2306 "}"); 2307 verifyGoogleFormat("switch (x) {\n" 2308 " case 1: {\n" 2309 " f();\n" 2310 " break;\n" 2311 " }\n" 2312 "}"); 2313 verifyGoogleFormat("switch (test)\n" 2314 " ;"); 2315 2316 verifyGoogleFormat("#define OPERATION_CASE(name) \\\n" 2317 " case OP_name: \\\n" 2318 " return operations::Operation##name\n"); 2319 verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n" 2320 " // Get the correction operation class.\n" 2321 " switch (OpCode) {\n" 2322 " CASE(Add);\n" 2323 " CASE(Subtract);\n" 2324 " default:\n" 2325 " return operations::Unknown;\n" 2326 " }\n" 2327 "#undef OPERATION_CASE\n" 2328 "}"); 2329 verifyFormat("DEBUG({\n" 2330 " switch (x) {\n" 2331 " case A:\n" 2332 " f();\n" 2333 " break;\n" 2334 " // fallthrough\n" 2335 " case B:\n" 2336 " g();\n" 2337 " break;\n" 2338 " }\n" 2339 "});"); 2340 EXPECT_EQ("DEBUG({\n" 2341 " switch (x) {\n" 2342 " case A:\n" 2343 " f();\n" 2344 " break;\n" 2345 " // On B:\n" 2346 " case B:\n" 2347 " g();\n" 2348 " break;\n" 2349 " }\n" 2350 "});", 2351 format("DEBUG({\n" 2352 " switch (x) {\n" 2353 " case A:\n" 2354 " f();\n" 2355 " break;\n" 2356 " // On B:\n" 2357 " case B:\n" 2358 " g();\n" 2359 " break;\n" 2360 " }\n" 2361 "});", 2362 getLLVMStyle())); 2363 EXPECT_EQ("switch (n) {\n" 2364 "case 0: {\n" 2365 " return false;\n" 2366 "}\n" 2367 "default: {\n" 2368 " return true;\n" 2369 "}\n" 2370 "}", 2371 format("switch (n)\n" 2372 "{\n" 2373 "case 0: {\n" 2374 " return false;\n" 2375 "}\n" 2376 "default: {\n" 2377 " return true;\n" 2378 "}\n" 2379 "}", 2380 getLLVMStyle())); 2381 verifyFormat("switch (a) {\n" 2382 "case (b):\n" 2383 " return;\n" 2384 "}"); 2385 2386 verifyFormat("switch (a) {\n" 2387 "case some_namespace::\n" 2388 " some_constant:\n" 2389 " return;\n" 2390 "}", 2391 getLLVMStyleWithColumns(34)); 2392 2393 FormatStyle Style = getLLVMStyle(); 2394 Style.IndentCaseLabels = true; 2395 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 2396 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2397 Style.BraceWrapping.AfterCaseLabel = true; 2398 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 2399 EXPECT_EQ("switch (n)\n" 2400 "{\n" 2401 " case 0:\n" 2402 " {\n" 2403 " return false;\n" 2404 " }\n" 2405 " default:\n" 2406 " {\n" 2407 " return true;\n" 2408 " }\n" 2409 "}", 2410 format("switch (n) {\n" 2411 " case 0: {\n" 2412 " return false;\n" 2413 " }\n" 2414 " default: {\n" 2415 " return true;\n" 2416 " }\n" 2417 "}", 2418 Style)); 2419 Style.BraceWrapping.AfterCaseLabel = false; 2420 EXPECT_EQ("switch (n)\n" 2421 "{\n" 2422 " case 0: {\n" 2423 " return false;\n" 2424 " }\n" 2425 " default: {\n" 2426 " return true;\n" 2427 " }\n" 2428 "}", 2429 format("switch (n) {\n" 2430 " case 0:\n" 2431 " {\n" 2432 " return false;\n" 2433 " }\n" 2434 " default:\n" 2435 " {\n" 2436 " return true;\n" 2437 " }\n" 2438 "}", 2439 Style)); 2440 Style.IndentCaseLabels = false; 2441 Style.IndentCaseBlocks = true; 2442 EXPECT_EQ("switch (n)\n" 2443 "{\n" 2444 "case 0:\n" 2445 " {\n" 2446 " return false;\n" 2447 " }\n" 2448 "case 1:\n" 2449 " break;\n" 2450 "default:\n" 2451 " {\n" 2452 " return true;\n" 2453 " }\n" 2454 "}", 2455 format("switch (n) {\n" 2456 "case 0: {\n" 2457 " return false;\n" 2458 "}\n" 2459 "case 1:\n" 2460 " break;\n" 2461 "default: {\n" 2462 " return true;\n" 2463 "}\n" 2464 "}", 2465 Style)); 2466 Style.IndentCaseLabels = true; 2467 Style.IndentCaseBlocks = true; 2468 EXPECT_EQ("switch (n)\n" 2469 "{\n" 2470 " case 0:\n" 2471 " {\n" 2472 " return false;\n" 2473 " }\n" 2474 " case 1:\n" 2475 " break;\n" 2476 " default:\n" 2477 " {\n" 2478 " return true;\n" 2479 " }\n" 2480 "}", 2481 format("switch (n) {\n" 2482 "case 0: {\n" 2483 " return false;\n" 2484 "}\n" 2485 "case 1:\n" 2486 " break;\n" 2487 "default: {\n" 2488 " return true;\n" 2489 "}\n" 2490 "}", 2491 Style)); 2492 } 2493 2494 TEST_F(FormatTest, CaseRanges) { 2495 verifyFormat("switch (x) {\n" 2496 "case 'A' ... 'Z':\n" 2497 "case 1 ... 5:\n" 2498 "case a ... b:\n" 2499 " break;\n" 2500 "}"); 2501 } 2502 2503 TEST_F(FormatTest, ShortEnums) { 2504 FormatStyle Style = getLLVMStyle(); 2505 Style.AllowShortEnumsOnASingleLine = true; 2506 verifyFormat("enum { A, B, C } ShortEnum1, ShortEnum2;", Style); 2507 Style.AllowShortEnumsOnASingleLine = false; 2508 verifyFormat("enum {\n" 2509 " A,\n" 2510 " B,\n" 2511 " C\n" 2512 "} ShortEnum1, ShortEnum2;", 2513 Style); 2514 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2515 Style.BraceWrapping.AfterEnum = true; 2516 verifyFormat("enum\n" 2517 "{\n" 2518 " A,\n" 2519 " B,\n" 2520 " C\n" 2521 "} ShortEnum1, ShortEnum2;", 2522 Style); 2523 } 2524 2525 TEST_F(FormatTest, ShortCaseLabels) { 2526 FormatStyle Style = getLLVMStyle(); 2527 Style.AllowShortCaseLabelsOnASingleLine = true; 2528 verifyFormat("switch (a) {\n" 2529 "case 1: x = 1; break;\n" 2530 "case 2: return;\n" 2531 "case 3:\n" 2532 "case 4:\n" 2533 "case 5: return;\n" 2534 "case 6: // comment\n" 2535 " return;\n" 2536 "case 7:\n" 2537 " // comment\n" 2538 " return;\n" 2539 "case 8:\n" 2540 " x = 8; // comment\n" 2541 " break;\n" 2542 "default: y = 1; break;\n" 2543 "}", 2544 Style); 2545 verifyFormat("switch (a) {\n" 2546 "case 0: return; // comment\n" 2547 "case 1: break; // comment\n" 2548 "case 2: return;\n" 2549 "// comment\n" 2550 "case 3: return;\n" 2551 "// comment 1\n" 2552 "// comment 2\n" 2553 "// comment 3\n" 2554 "case 4: break; /* comment */\n" 2555 "case 5:\n" 2556 " // comment\n" 2557 " break;\n" 2558 "case 6: /* comment */ x = 1; break;\n" 2559 "case 7: x = /* comment */ 1; break;\n" 2560 "case 8:\n" 2561 " x = 1; /* comment */\n" 2562 " break;\n" 2563 "case 9:\n" 2564 " break; // comment line 1\n" 2565 " // comment line 2\n" 2566 "}", 2567 Style); 2568 EXPECT_EQ("switch (a) {\n" 2569 "case 1:\n" 2570 " x = 8;\n" 2571 " // fall through\n" 2572 "case 2: x = 8;\n" 2573 "// comment\n" 2574 "case 3:\n" 2575 " return; /* comment line 1\n" 2576 " * comment line 2 */\n" 2577 "case 4: i = 8;\n" 2578 "// something else\n" 2579 "#if FOO\n" 2580 "case 5: break;\n" 2581 "#endif\n" 2582 "}", 2583 format("switch (a) {\n" 2584 "case 1: x = 8;\n" 2585 " // fall through\n" 2586 "case 2:\n" 2587 " x = 8;\n" 2588 "// comment\n" 2589 "case 3:\n" 2590 " return; /* comment line 1\n" 2591 " * comment line 2 */\n" 2592 "case 4:\n" 2593 " i = 8;\n" 2594 "// something else\n" 2595 "#if FOO\n" 2596 "case 5: break;\n" 2597 "#endif\n" 2598 "}", 2599 Style)); 2600 EXPECT_EQ("switch (a) {\n" 2601 "case 0:\n" 2602 " return; // long long long long long long long long long long " 2603 "long long comment\n" 2604 " // line\n" 2605 "}", 2606 format("switch (a) {\n" 2607 "case 0: return; // long long long long long long long long " 2608 "long long long long comment line\n" 2609 "}", 2610 Style)); 2611 EXPECT_EQ("switch (a) {\n" 2612 "case 0:\n" 2613 " return; /* long long long long long long long long long long " 2614 "long long comment\n" 2615 " line */\n" 2616 "}", 2617 format("switch (a) {\n" 2618 "case 0: return; /* long long long long long long long long " 2619 "long long long long comment line */\n" 2620 "}", 2621 Style)); 2622 verifyFormat("switch (a) {\n" 2623 "#if FOO\n" 2624 "case 0: return 0;\n" 2625 "#endif\n" 2626 "}", 2627 Style); 2628 verifyFormat("switch (a) {\n" 2629 "case 1: {\n" 2630 "}\n" 2631 "case 2: {\n" 2632 " return;\n" 2633 "}\n" 2634 "case 3: {\n" 2635 " x = 1;\n" 2636 " return;\n" 2637 "}\n" 2638 "case 4:\n" 2639 " if (x)\n" 2640 " return;\n" 2641 "}", 2642 Style); 2643 Style.ColumnLimit = 21; 2644 verifyFormat("switch (a) {\n" 2645 "case 1: x = 1; break;\n" 2646 "case 2: return;\n" 2647 "case 3:\n" 2648 "case 4:\n" 2649 "case 5: return;\n" 2650 "default:\n" 2651 " y = 1;\n" 2652 " break;\n" 2653 "}", 2654 Style); 2655 Style.ColumnLimit = 80; 2656 Style.AllowShortCaseLabelsOnASingleLine = false; 2657 Style.IndentCaseLabels = true; 2658 EXPECT_EQ("switch (n) {\n" 2659 " default /*comments*/:\n" 2660 " return true;\n" 2661 " case 0:\n" 2662 " return false;\n" 2663 "}", 2664 format("switch (n) {\n" 2665 "default/*comments*/:\n" 2666 " return true;\n" 2667 "case 0:\n" 2668 " return false;\n" 2669 "}", 2670 Style)); 2671 Style.AllowShortCaseLabelsOnASingleLine = true; 2672 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 2673 Style.BraceWrapping.AfterCaseLabel = true; 2674 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 2675 EXPECT_EQ("switch (n)\n" 2676 "{\n" 2677 " case 0:\n" 2678 " {\n" 2679 " return false;\n" 2680 " }\n" 2681 " default:\n" 2682 " {\n" 2683 " return true;\n" 2684 " }\n" 2685 "}", 2686 format("switch (n) {\n" 2687 " case 0: {\n" 2688 " return false;\n" 2689 " }\n" 2690 " default:\n" 2691 " {\n" 2692 " return true;\n" 2693 " }\n" 2694 "}", 2695 Style)); 2696 } 2697 2698 TEST_F(FormatTest, FormatsLabels) { 2699 verifyFormat("void f() {\n" 2700 " some_code();\n" 2701 "test_label:\n" 2702 " some_other_code();\n" 2703 " {\n" 2704 " some_more_code();\n" 2705 " another_label:\n" 2706 " some_more_code();\n" 2707 " }\n" 2708 "}"); 2709 verifyFormat("{\n" 2710 " some_code();\n" 2711 "test_label:\n" 2712 " some_other_code();\n" 2713 "}"); 2714 verifyFormat("{\n" 2715 " some_code();\n" 2716 "test_label:;\n" 2717 " int i = 0;\n" 2718 "}"); 2719 FormatStyle Style = getLLVMStyle(); 2720 Style.IndentGotoLabels = false; 2721 verifyFormat("void f() {\n" 2722 " some_code();\n" 2723 "test_label:\n" 2724 " some_other_code();\n" 2725 " {\n" 2726 " some_more_code();\n" 2727 "another_label:\n" 2728 " some_more_code();\n" 2729 " }\n" 2730 "}", 2731 Style); 2732 verifyFormat("{\n" 2733 " some_code();\n" 2734 "test_label:\n" 2735 " some_other_code();\n" 2736 "}", 2737 Style); 2738 verifyFormat("{\n" 2739 " some_code();\n" 2740 "test_label:;\n" 2741 " int i = 0;\n" 2742 "}"); 2743 } 2744 2745 TEST_F(FormatTest, MultiLineControlStatements) { 2746 FormatStyle Style = getLLVMStyle(); 2747 Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom; 2748 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine; 2749 Style.ColumnLimit = 20; 2750 // Short lines should keep opening brace on same line. 2751 EXPECT_EQ("if (foo) {\n" 2752 " bar();\n" 2753 "}", 2754 format("if(foo){bar();}", Style)); 2755 EXPECT_EQ("if (foo) {\n" 2756 " bar();\n" 2757 "} else {\n" 2758 " baz();\n" 2759 "}", 2760 format("if(foo){bar();}else{baz();}", Style)); 2761 EXPECT_EQ("if (foo && bar) {\n" 2762 " baz();\n" 2763 "}", 2764 format("if(foo&&bar){baz();}", Style)); 2765 EXPECT_EQ("if (foo) {\n" 2766 " bar();\n" 2767 "} else if (baz) {\n" 2768 " quux();\n" 2769 "}", 2770 format("if(foo){bar();}else if(baz){quux();}", Style)); 2771 EXPECT_EQ( 2772 "if (foo) {\n" 2773 " bar();\n" 2774 "} else if (baz) {\n" 2775 " quux();\n" 2776 "} else {\n" 2777 " foobar();\n" 2778 "}", 2779 format("if(foo){bar();}else if(baz){quux();}else{foobar();}", Style)); 2780 EXPECT_EQ("for (;;) {\n" 2781 " foo();\n" 2782 "}", 2783 format("for(;;){foo();}")); 2784 EXPECT_EQ("while (1) {\n" 2785 " foo();\n" 2786 "}", 2787 format("while(1){foo();}", Style)); 2788 EXPECT_EQ("switch (foo) {\n" 2789 "case bar:\n" 2790 " return;\n" 2791 "}", 2792 format("switch(foo){case bar:return;}", Style)); 2793 EXPECT_EQ("try {\n" 2794 " foo();\n" 2795 "} catch (...) {\n" 2796 " bar();\n" 2797 "}", 2798 format("try{foo();}catch(...){bar();}", Style)); 2799 EXPECT_EQ("do {\n" 2800 " foo();\n" 2801 "} while (bar &&\n" 2802 " baz);", 2803 format("do{foo();}while(bar&&baz);", Style)); 2804 // Long lines should put opening brace on new line. 2805 EXPECT_EQ("if (foo && bar &&\n" 2806 " baz)\n" 2807 "{\n" 2808 " quux();\n" 2809 "}", 2810 format("if(foo&&bar&&baz){quux();}", Style)); 2811 EXPECT_EQ("if (foo && bar &&\n" 2812 " baz)\n" 2813 "{\n" 2814 " quux();\n" 2815 "}", 2816 format("if (foo && bar &&\n" 2817 " baz) {\n" 2818 " quux();\n" 2819 "}", 2820 Style)); 2821 EXPECT_EQ("if (foo) {\n" 2822 " bar();\n" 2823 "} else if (baz ||\n" 2824 " quux)\n" 2825 "{\n" 2826 " foobar();\n" 2827 "}", 2828 format("if(foo){bar();}else if(baz||quux){foobar();}", Style)); 2829 EXPECT_EQ( 2830 "if (foo) {\n" 2831 " bar();\n" 2832 "} else if (baz ||\n" 2833 " quux)\n" 2834 "{\n" 2835 " foobar();\n" 2836 "} else {\n" 2837 " barbaz();\n" 2838 "}", 2839 format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}", 2840 Style)); 2841 EXPECT_EQ("for (int i = 0;\n" 2842 " i < 10; ++i)\n" 2843 "{\n" 2844 " foo();\n" 2845 "}", 2846 format("for(int i=0;i<10;++i){foo();}", Style)); 2847 EXPECT_EQ("foreach (int i,\n" 2848 " list)\n" 2849 "{\n" 2850 " foo();\n" 2851 "}", 2852 format("foreach(int i, list){foo();}", Style)); 2853 Style.ColumnLimit = 2854 40; // to concentrate at brace wrapping, not line wrap due to column limit 2855 EXPECT_EQ("foreach (int i, list) {\n" 2856 " foo();\n" 2857 "}", 2858 format("foreach(int i, list){foo();}", Style)); 2859 Style.ColumnLimit = 2860 20; // to concentrate at brace wrapping, not line wrap due to column limit 2861 EXPECT_EQ("while (foo || bar ||\n" 2862 " baz)\n" 2863 "{\n" 2864 " quux();\n" 2865 "}", 2866 format("while(foo||bar||baz){quux();}", Style)); 2867 EXPECT_EQ("switch (\n" 2868 " foo = barbaz)\n" 2869 "{\n" 2870 "case quux:\n" 2871 " return;\n" 2872 "}", 2873 format("switch(foo=barbaz){case quux:return;}", Style)); 2874 EXPECT_EQ("try {\n" 2875 " foo();\n" 2876 "} catch (\n" 2877 " Exception &bar)\n" 2878 "{\n" 2879 " baz();\n" 2880 "}", 2881 format("try{foo();}catch(Exception&bar){baz();}", Style)); 2882 Style.ColumnLimit = 2883 40; // to concentrate at brace wrapping, not line wrap due to column limit 2884 EXPECT_EQ("try {\n" 2885 " foo();\n" 2886 "} catch (Exception &bar) {\n" 2887 " baz();\n" 2888 "}", 2889 format("try{foo();}catch(Exception&bar){baz();}", Style)); 2890 Style.ColumnLimit = 2891 20; // to concentrate at brace wrapping, not line wrap due to column limit 2892 2893 Style.BraceWrapping.BeforeElse = true; 2894 EXPECT_EQ( 2895 "if (foo) {\n" 2896 " bar();\n" 2897 "}\n" 2898 "else if (baz ||\n" 2899 " quux)\n" 2900 "{\n" 2901 " foobar();\n" 2902 "}\n" 2903 "else {\n" 2904 " barbaz();\n" 2905 "}", 2906 format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}", 2907 Style)); 2908 2909 Style.BraceWrapping.BeforeCatch = true; 2910 EXPECT_EQ("try {\n" 2911 " foo();\n" 2912 "}\n" 2913 "catch (...) {\n" 2914 " baz();\n" 2915 "}", 2916 format("try{foo();}catch(...){baz();}", Style)); 2917 2918 Style.BraceWrapping.AfterFunction = true; 2919 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine; 2920 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 2921 Style.ColumnLimit = 80; 2922 verifyFormat("void shortfunction() { bar(); }", Style); 2923 2924 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 2925 verifyFormat("void shortfunction()\n" 2926 "{\n" 2927 " bar();\n" 2928 "}", 2929 Style); 2930 } 2931 2932 TEST_F(FormatTest, BeforeWhile) { 2933 FormatStyle Style = getLLVMStyle(); 2934 Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom; 2935 2936 verifyFormat("do {\n" 2937 " foo();\n" 2938 "} while (1);", 2939 Style); 2940 Style.BraceWrapping.BeforeWhile = true; 2941 verifyFormat("do {\n" 2942 " foo();\n" 2943 "}\n" 2944 "while (1);", 2945 Style); 2946 } 2947 2948 //===----------------------------------------------------------------------===// 2949 // Tests for classes, namespaces, etc. 2950 //===----------------------------------------------------------------------===// 2951 2952 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) { 2953 verifyFormat("class A {};"); 2954 } 2955 2956 TEST_F(FormatTest, UnderstandsAccessSpecifiers) { 2957 verifyFormat("class A {\n" 2958 "public:\n" 2959 "public: // comment\n" 2960 "protected:\n" 2961 "private:\n" 2962 " void f() {}\n" 2963 "};"); 2964 verifyFormat("export class A {\n" 2965 "public:\n" 2966 "public: // comment\n" 2967 "protected:\n" 2968 "private:\n" 2969 " void f() {}\n" 2970 "};"); 2971 verifyGoogleFormat("class A {\n" 2972 " public:\n" 2973 " protected:\n" 2974 " private:\n" 2975 " void f() {}\n" 2976 "};"); 2977 verifyGoogleFormat("export class A {\n" 2978 " public:\n" 2979 " protected:\n" 2980 " private:\n" 2981 " void f() {}\n" 2982 "};"); 2983 verifyFormat("class A {\n" 2984 "public slots:\n" 2985 " void f1() {}\n" 2986 "public Q_SLOTS:\n" 2987 " void f2() {}\n" 2988 "protected slots:\n" 2989 " void f3() {}\n" 2990 "protected Q_SLOTS:\n" 2991 " void f4() {}\n" 2992 "private slots:\n" 2993 " void f5() {}\n" 2994 "private Q_SLOTS:\n" 2995 " void f6() {}\n" 2996 "signals:\n" 2997 " void g1();\n" 2998 "Q_SIGNALS:\n" 2999 " void g2();\n" 3000 "};"); 3001 3002 // Don't interpret 'signals' the wrong way. 3003 verifyFormat("signals.set();"); 3004 verifyFormat("for (Signals signals : f()) {\n}"); 3005 verifyFormat("{\n" 3006 " signals.set(); // This needs indentation.\n" 3007 "}"); 3008 verifyFormat("void f() {\n" 3009 "label:\n" 3010 " signals.baz();\n" 3011 "}"); 3012 } 3013 3014 TEST_F(FormatTest, SeparatesLogicalBlocks) { 3015 EXPECT_EQ("class A {\n" 3016 "public:\n" 3017 " void f();\n" 3018 "\n" 3019 "private:\n" 3020 " void g() {}\n" 3021 " // test\n" 3022 "protected:\n" 3023 " int h;\n" 3024 "};", 3025 format("class A {\n" 3026 "public:\n" 3027 "void f();\n" 3028 "private:\n" 3029 "void g() {}\n" 3030 "// test\n" 3031 "protected:\n" 3032 "int h;\n" 3033 "};")); 3034 EXPECT_EQ("class A {\n" 3035 "protected:\n" 3036 "public:\n" 3037 " void f();\n" 3038 "};", 3039 format("class A {\n" 3040 "protected:\n" 3041 "\n" 3042 "public:\n" 3043 "\n" 3044 " void f();\n" 3045 "};")); 3046 3047 // Even ensure proper spacing inside macros. 3048 EXPECT_EQ("#define B \\\n" 3049 " class A { \\\n" 3050 " protected: \\\n" 3051 " public: \\\n" 3052 " void f(); \\\n" 3053 " };", 3054 format("#define B \\\n" 3055 " class A { \\\n" 3056 " protected: \\\n" 3057 " \\\n" 3058 " public: \\\n" 3059 " \\\n" 3060 " void f(); \\\n" 3061 " };", 3062 getGoogleStyle())); 3063 // But don't remove empty lines after macros ending in access specifiers. 3064 EXPECT_EQ("#define A private:\n" 3065 "\n" 3066 "int i;", 3067 format("#define A private:\n" 3068 "\n" 3069 "int i;")); 3070 } 3071 3072 TEST_F(FormatTest, FormatsClasses) { 3073 verifyFormat("class A : public B {};"); 3074 verifyFormat("class A : public ::B {};"); 3075 3076 verifyFormat( 3077 "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3078 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};"); 3079 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n" 3080 " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3081 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};"); 3082 verifyFormat( 3083 "class A : public B, public C, public D, public E, public F {};"); 3084 verifyFormat("class AAAAAAAAAAAA : public B,\n" 3085 " public C,\n" 3086 " public D,\n" 3087 " public E,\n" 3088 " public F,\n" 3089 " public G {};"); 3090 3091 verifyFormat("class\n" 3092 " ReallyReallyLongClassName {\n" 3093 " int i;\n" 3094 "};", 3095 getLLVMStyleWithColumns(32)); 3096 verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n" 3097 " aaaaaaaaaaaaaaaa> {};"); 3098 verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n" 3099 " : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n" 3100 " aaaaaaaaaaaaaaaaaaaaaa> {};"); 3101 verifyFormat("template <class R, class C>\n" 3102 "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n" 3103 " : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};"); 3104 verifyFormat("class ::A::B {};"); 3105 } 3106 3107 TEST_F(FormatTest, BreakInheritanceStyle) { 3108 FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle(); 3109 StyleWithInheritanceBreakBeforeComma.BreakInheritanceList = 3110 FormatStyle::BILS_BeforeComma; 3111 verifyFormat("class MyClass : public X {};", 3112 StyleWithInheritanceBreakBeforeComma); 3113 verifyFormat("class MyClass\n" 3114 " : public X\n" 3115 " , public Y {};", 3116 StyleWithInheritanceBreakBeforeComma); 3117 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n" 3118 " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n" 3119 " , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};", 3120 StyleWithInheritanceBreakBeforeComma); 3121 verifyFormat("struct aaaaaaaaaaaaa\n" 3122 " : public aaaaaaaaaaaaaaaaaaa< // break\n" 3123 " aaaaaaaaaaaaaaaa> {};", 3124 StyleWithInheritanceBreakBeforeComma); 3125 3126 FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle(); 3127 StyleWithInheritanceBreakAfterColon.BreakInheritanceList = 3128 FormatStyle::BILS_AfterColon; 3129 verifyFormat("class MyClass : public X {};", 3130 StyleWithInheritanceBreakAfterColon); 3131 verifyFormat("class MyClass : public X, public Y {};", 3132 StyleWithInheritanceBreakAfterColon); 3133 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n" 3134 " public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3135 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};", 3136 StyleWithInheritanceBreakAfterColon); 3137 verifyFormat("struct aaaaaaaaaaaaa :\n" 3138 " public aaaaaaaaaaaaaaaaaaa< // break\n" 3139 " aaaaaaaaaaaaaaaa> {};", 3140 StyleWithInheritanceBreakAfterColon); 3141 3142 FormatStyle StyleWithInheritanceBreakAfterComma = getLLVMStyle(); 3143 StyleWithInheritanceBreakAfterComma.BreakInheritanceList = 3144 FormatStyle::BILS_AfterComma; 3145 verifyFormat("class MyClass : public X {};", 3146 StyleWithInheritanceBreakAfterComma); 3147 verifyFormat("class MyClass : public X,\n" 3148 " public Y {};", 3149 StyleWithInheritanceBreakAfterComma); 3150 verifyFormat( 3151 "class AAAAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" 3152 " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC " 3153 "{};", 3154 StyleWithInheritanceBreakAfterComma); 3155 verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n" 3156 " aaaaaaaaaaaaaaaa> {};", 3157 StyleWithInheritanceBreakAfterComma); 3158 verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n" 3159 " : public OnceBreak,\n" 3160 " public AlwaysBreak,\n" 3161 " EvenBasesFitInOneLine {};", 3162 StyleWithInheritanceBreakAfterComma); 3163 } 3164 3165 TEST_F(FormatTest, FormatsVariableDeclarationsAfterStructOrClass) { 3166 verifyFormat("class A {\n} a, b;"); 3167 verifyFormat("struct A {\n} a, b;"); 3168 verifyFormat("union A {\n} a;"); 3169 } 3170 3171 TEST_F(FormatTest, FormatsEnum) { 3172 verifyFormat("enum {\n" 3173 " Zero,\n" 3174 " One = 1,\n" 3175 " Two = One + 1,\n" 3176 " Three = (One + Two),\n" 3177 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3178 " Five = (One, Two, Three, Four, 5)\n" 3179 "};"); 3180 verifyGoogleFormat("enum {\n" 3181 " Zero,\n" 3182 " One = 1,\n" 3183 " Two = One + 1,\n" 3184 " Three = (One + Two),\n" 3185 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3186 " Five = (One, Two, Three, Four, 5)\n" 3187 "};"); 3188 verifyFormat("enum Enum {};"); 3189 verifyFormat("enum {};"); 3190 verifyFormat("enum X E {} d;"); 3191 verifyFormat("enum __attribute__((...)) E {} d;"); 3192 verifyFormat("enum __declspec__((...)) E {} d;"); 3193 verifyFormat("enum {\n" 3194 " Bar = Foo<int, int>::value\n" 3195 "};", 3196 getLLVMStyleWithColumns(30)); 3197 3198 verifyFormat("enum ShortEnum { A, B, C };"); 3199 verifyGoogleFormat("enum ShortEnum { A, B, C };"); 3200 3201 EXPECT_EQ("enum KeepEmptyLines {\n" 3202 " ONE,\n" 3203 "\n" 3204 " TWO,\n" 3205 "\n" 3206 " THREE\n" 3207 "}", 3208 format("enum KeepEmptyLines {\n" 3209 " ONE,\n" 3210 "\n" 3211 " TWO,\n" 3212 "\n" 3213 "\n" 3214 " THREE\n" 3215 "}")); 3216 verifyFormat("enum E { // comment\n" 3217 " ONE,\n" 3218 " TWO\n" 3219 "};\n" 3220 "int i;"); 3221 3222 FormatStyle EightIndent = getLLVMStyle(); 3223 EightIndent.IndentWidth = 8; 3224 verifyFormat("enum {\n" 3225 " VOID,\n" 3226 " CHAR,\n" 3227 " SHORT,\n" 3228 " INT,\n" 3229 " LONG,\n" 3230 " SIGNED,\n" 3231 " UNSIGNED,\n" 3232 " BOOL,\n" 3233 " FLOAT,\n" 3234 " DOUBLE,\n" 3235 " COMPLEX\n" 3236 "};", 3237 EightIndent); 3238 3239 // Not enums. 3240 verifyFormat("enum X f() {\n" 3241 " a();\n" 3242 " return 42;\n" 3243 "}"); 3244 verifyFormat("enum X Type::f() {\n" 3245 " a();\n" 3246 " return 42;\n" 3247 "}"); 3248 verifyFormat("enum ::X f() {\n" 3249 " a();\n" 3250 " return 42;\n" 3251 "}"); 3252 verifyFormat("enum ns::X f() {\n" 3253 " a();\n" 3254 " return 42;\n" 3255 "}"); 3256 } 3257 3258 TEST_F(FormatTest, FormatsEnumsWithErrors) { 3259 verifyFormat("enum Type {\n" 3260 " One = 0; // These semicolons should be commas.\n" 3261 " Two = 1;\n" 3262 "};"); 3263 verifyFormat("namespace n {\n" 3264 "enum Type {\n" 3265 " One,\n" 3266 " Two, // missing };\n" 3267 " int i;\n" 3268 "}\n" 3269 "void g() {}"); 3270 } 3271 3272 TEST_F(FormatTest, FormatsEnumStruct) { 3273 verifyFormat("enum struct {\n" 3274 " Zero,\n" 3275 " One = 1,\n" 3276 " Two = One + 1,\n" 3277 " Three = (One + Two),\n" 3278 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3279 " Five = (One, Two, Three, Four, 5)\n" 3280 "};"); 3281 verifyFormat("enum struct Enum {};"); 3282 verifyFormat("enum struct {};"); 3283 verifyFormat("enum struct X E {} d;"); 3284 verifyFormat("enum struct __attribute__((...)) E {} d;"); 3285 verifyFormat("enum struct __declspec__((...)) E {} d;"); 3286 verifyFormat("enum struct X f() {\n a();\n return 42;\n}"); 3287 } 3288 3289 TEST_F(FormatTest, FormatsEnumClass) { 3290 verifyFormat("enum class {\n" 3291 " Zero,\n" 3292 " One = 1,\n" 3293 " Two = One + 1,\n" 3294 " Three = (One + Two),\n" 3295 " Four = (Zero && (One ^ Two)) | (One << Two),\n" 3296 " Five = (One, Two, Three, Four, 5)\n" 3297 "};"); 3298 verifyFormat("enum class Enum {};"); 3299 verifyFormat("enum class {};"); 3300 verifyFormat("enum class X E {} d;"); 3301 verifyFormat("enum class __attribute__((...)) E {} d;"); 3302 verifyFormat("enum class __declspec__((...)) E {} d;"); 3303 verifyFormat("enum class X f() {\n a();\n return 42;\n}"); 3304 } 3305 3306 TEST_F(FormatTest, FormatsEnumTypes) { 3307 verifyFormat("enum X : int {\n" 3308 " A, // Force multiple lines.\n" 3309 " B\n" 3310 "};"); 3311 verifyFormat("enum X : int { A, B };"); 3312 verifyFormat("enum X : std::uint32_t { A, B };"); 3313 } 3314 3315 TEST_F(FormatTest, FormatsTypedefEnum) { 3316 FormatStyle Style = getLLVMStyle(); 3317 Style.ColumnLimit = 40; 3318 verifyFormat("typedef enum {} EmptyEnum;"); 3319 verifyFormat("typedef enum { A, B, C } ShortEnum;"); 3320 verifyFormat("typedef enum {\n" 3321 " ZERO = 0,\n" 3322 " ONE = 1,\n" 3323 " TWO = 2,\n" 3324 " THREE = 3\n" 3325 "} LongEnum;", 3326 Style); 3327 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 3328 Style.BraceWrapping.AfterEnum = true; 3329 verifyFormat("typedef enum {} EmptyEnum;"); 3330 verifyFormat("typedef enum { A, B, C } ShortEnum;"); 3331 verifyFormat("typedef enum\n" 3332 "{\n" 3333 " ZERO = 0,\n" 3334 " ONE = 1,\n" 3335 " TWO = 2,\n" 3336 " THREE = 3\n" 3337 "} LongEnum;", 3338 Style); 3339 } 3340 3341 TEST_F(FormatTest, FormatsNSEnums) { 3342 verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }"); 3343 verifyGoogleFormat( 3344 "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }"); 3345 verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n" 3346 " // Information about someDecentlyLongValue.\n" 3347 " someDecentlyLongValue,\n" 3348 " // Information about anotherDecentlyLongValue.\n" 3349 " anotherDecentlyLongValue,\n" 3350 " // Information about aThirdDecentlyLongValue.\n" 3351 " aThirdDecentlyLongValue\n" 3352 "};"); 3353 verifyGoogleFormat("typedef NS_CLOSED_ENUM(NSInteger, MyType) {\n" 3354 " // Information about someDecentlyLongValue.\n" 3355 " someDecentlyLongValue,\n" 3356 " // Information about anotherDecentlyLongValue.\n" 3357 " anotherDecentlyLongValue,\n" 3358 " // Information about aThirdDecentlyLongValue.\n" 3359 " aThirdDecentlyLongValue\n" 3360 "};"); 3361 verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n" 3362 " a = 1,\n" 3363 " b = 2,\n" 3364 " c = 3,\n" 3365 "};"); 3366 verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n" 3367 " a = 1,\n" 3368 " b = 2,\n" 3369 " c = 3,\n" 3370 "};"); 3371 verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n" 3372 " a = 1,\n" 3373 " b = 2,\n" 3374 " c = 3,\n" 3375 "};"); 3376 verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n" 3377 " a = 1,\n" 3378 " b = 2,\n" 3379 " c = 3,\n" 3380 "};"); 3381 } 3382 3383 TEST_F(FormatTest, FormatsBitfields) { 3384 verifyFormat("struct Bitfields {\n" 3385 " unsigned sClass : 8;\n" 3386 " unsigned ValueKind : 2;\n" 3387 "};"); 3388 verifyFormat("struct A {\n" 3389 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n" 3390 " bbbbbbbbbbbbbbbbbbbbbbbbb;\n" 3391 "};"); 3392 verifyFormat("struct MyStruct {\n" 3393 " uchar data;\n" 3394 " uchar : 8;\n" 3395 " uchar : 8;\n" 3396 " uchar other;\n" 3397 "};"); 3398 FormatStyle Style = getLLVMStyle(); 3399 Style.BitFieldColonSpacing = FormatStyle::BFCS_None; 3400 verifyFormat("struct Bitfields {\n" 3401 " unsigned sClass:8;\n" 3402 " unsigned ValueKind:2;\n" 3403 " uchar other;\n" 3404 "};", 3405 Style); 3406 verifyFormat("struct A {\n" 3407 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:1,\n" 3408 " bbbbbbbbbbbbbbbbbbbbbbbbb:2;\n" 3409 "};", 3410 Style); 3411 Style.BitFieldColonSpacing = FormatStyle::BFCS_Before; 3412 verifyFormat("struct Bitfields {\n" 3413 " unsigned sClass :8;\n" 3414 " unsigned ValueKind :2;\n" 3415 " uchar other;\n" 3416 "};", 3417 Style); 3418 Style.BitFieldColonSpacing = FormatStyle::BFCS_After; 3419 verifyFormat("struct Bitfields {\n" 3420 " unsigned sClass: 8;\n" 3421 " unsigned ValueKind: 2;\n" 3422 " uchar other;\n" 3423 "};", 3424 Style); 3425 } 3426 3427 TEST_F(FormatTest, FormatsNamespaces) { 3428 FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle(); 3429 LLVMWithNoNamespaceFix.FixNamespaceComments = false; 3430 3431 verifyFormat("namespace some_namespace {\n" 3432 "class A {};\n" 3433 "void f() { f(); }\n" 3434 "}", 3435 LLVMWithNoNamespaceFix); 3436 verifyFormat("namespace N::inline D {\n" 3437 "class A {};\n" 3438 "void f() { f(); }\n" 3439 "}", 3440 LLVMWithNoNamespaceFix); 3441 verifyFormat("namespace N::inline D::E {\n" 3442 "class A {};\n" 3443 "void f() { f(); }\n" 3444 "}", 3445 LLVMWithNoNamespaceFix); 3446 verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n" 3447 "class A {};\n" 3448 "void f() { f(); }\n" 3449 "}", 3450 LLVMWithNoNamespaceFix); 3451 verifyFormat("/* something */ namespace some_namespace {\n" 3452 "class A {};\n" 3453 "void f() { f(); }\n" 3454 "}", 3455 LLVMWithNoNamespaceFix); 3456 verifyFormat("namespace {\n" 3457 "class A {};\n" 3458 "void f() { f(); }\n" 3459 "}", 3460 LLVMWithNoNamespaceFix); 3461 verifyFormat("/* something */ namespace {\n" 3462 "class A {};\n" 3463 "void f() { f(); }\n" 3464 "}", 3465 LLVMWithNoNamespaceFix); 3466 verifyFormat("inline namespace X {\n" 3467 "class A {};\n" 3468 "void f() { f(); }\n" 3469 "}", 3470 LLVMWithNoNamespaceFix); 3471 verifyFormat("/* something */ inline namespace X {\n" 3472 "class A {};\n" 3473 "void f() { f(); }\n" 3474 "}", 3475 LLVMWithNoNamespaceFix); 3476 verifyFormat("export namespace X {\n" 3477 "class A {};\n" 3478 "void f() { f(); }\n" 3479 "}", 3480 LLVMWithNoNamespaceFix); 3481 verifyFormat("using namespace some_namespace;\n" 3482 "class A {};\n" 3483 "void f() { f(); }", 3484 LLVMWithNoNamespaceFix); 3485 3486 // This code is more common than we thought; if we 3487 // layout this correctly the semicolon will go into 3488 // its own line, which is undesirable. 3489 verifyFormat("namespace {};", LLVMWithNoNamespaceFix); 3490 verifyFormat("namespace {\n" 3491 "class A {};\n" 3492 "};", 3493 LLVMWithNoNamespaceFix); 3494 3495 verifyFormat("namespace {\n" 3496 "int SomeVariable = 0; // comment\n" 3497 "} // namespace", 3498 LLVMWithNoNamespaceFix); 3499 EXPECT_EQ("#ifndef HEADER_GUARD\n" 3500 "#define HEADER_GUARD\n" 3501 "namespace my_namespace {\n" 3502 "int i;\n" 3503 "} // my_namespace\n" 3504 "#endif // HEADER_GUARD", 3505 format("#ifndef HEADER_GUARD\n" 3506 " #define HEADER_GUARD\n" 3507 " namespace my_namespace {\n" 3508 "int i;\n" 3509 "} // my_namespace\n" 3510 "#endif // HEADER_GUARD", 3511 LLVMWithNoNamespaceFix)); 3512 3513 EXPECT_EQ("namespace A::B {\n" 3514 "class C {};\n" 3515 "}", 3516 format("namespace A::B {\n" 3517 "class C {};\n" 3518 "}", 3519 LLVMWithNoNamespaceFix)); 3520 3521 FormatStyle Style = getLLVMStyle(); 3522 Style.NamespaceIndentation = FormatStyle::NI_All; 3523 EXPECT_EQ("namespace out {\n" 3524 " int i;\n" 3525 " namespace in {\n" 3526 " int i;\n" 3527 " } // namespace in\n" 3528 "} // namespace out", 3529 format("namespace out {\n" 3530 "int i;\n" 3531 "namespace in {\n" 3532 "int i;\n" 3533 "} // namespace in\n" 3534 "} // namespace out", 3535 Style)); 3536 3537 Style.NamespaceIndentation = FormatStyle::NI_Inner; 3538 EXPECT_EQ("namespace out {\n" 3539 "int i;\n" 3540 "namespace in {\n" 3541 " int i;\n" 3542 "} // namespace in\n" 3543 "} // namespace out", 3544 format("namespace out {\n" 3545 "int i;\n" 3546 "namespace in {\n" 3547 "int i;\n" 3548 "} // namespace in\n" 3549 "} // namespace out", 3550 Style)); 3551 3552 Style.NamespaceIndentation = FormatStyle::NI_None; 3553 verifyFormat("template <class T>\n" 3554 "concept a_concept = X<>;\n" 3555 "namespace B {\n" 3556 "struct b_struct {};\n" 3557 "} // namespace B\n", 3558 Style); 3559 verifyFormat("template <int I> constexpr void foo requires(I == 42) {}\n" 3560 "namespace ns {\n" 3561 "void foo() {}\n" 3562 "} // namespace ns\n", 3563 Style); 3564 } 3565 3566 TEST_F(FormatTest, NamespaceMacros) { 3567 FormatStyle Style = getLLVMStyle(); 3568 Style.NamespaceMacros.push_back("TESTSUITE"); 3569 3570 verifyFormat("TESTSUITE(A) {\n" 3571 "int foo();\n" 3572 "} // TESTSUITE(A)", 3573 Style); 3574 3575 verifyFormat("TESTSUITE(A, B) {\n" 3576 "int foo();\n" 3577 "} // TESTSUITE(A)", 3578 Style); 3579 3580 // Properly indent according to NamespaceIndentation style 3581 Style.NamespaceIndentation = FormatStyle::NI_All; 3582 verifyFormat("TESTSUITE(A) {\n" 3583 " int foo();\n" 3584 "} // TESTSUITE(A)", 3585 Style); 3586 verifyFormat("TESTSUITE(A) {\n" 3587 " namespace B {\n" 3588 " int foo();\n" 3589 " } // namespace B\n" 3590 "} // TESTSUITE(A)", 3591 Style); 3592 verifyFormat("namespace A {\n" 3593 " TESTSUITE(B) {\n" 3594 " int foo();\n" 3595 " } // TESTSUITE(B)\n" 3596 "} // namespace A", 3597 Style); 3598 3599 Style.NamespaceIndentation = FormatStyle::NI_Inner; 3600 verifyFormat("TESTSUITE(A) {\n" 3601 "TESTSUITE(B) {\n" 3602 " int foo();\n" 3603 "} // TESTSUITE(B)\n" 3604 "} // TESTSUITE(A)", 3605 Style); 3606 verifyFormat("TESTSUITE(A) {\n" 3607 "namespace B {\n" 3608 " int foo();\n" 3609 "} // namespace B\n" 3610 "} // TESTSUITE(A)", 3611 Style); 3612 verifyFormat("namespace A {\n" 3613 "TESTSUITE(B) {\n" 3614 " int foo();\n" 3615 "} // TESTSUITE(B)\n" 3616 "} // namespace A", 3617 Style); 3618 3619 // Properly merge namespace-macros blocks in CompactNamespaces mode 3620 Style.NamespaceIndentation = FormatStyle::NI_None; 3621 Style.CompactNamespaces = true; 3622 verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n" 3623 "}} // TESTSUITE(A::B)", 3624 Style); 3625 3626 EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n" 3627 "}} // TESTSUITE(out::in)", 3628 format("TESTSUITE(out) {\n" 3629 "TESTSUITE(in) {\n" 3630 "} // TESTSUITE(in)\n" 3631 "} // TESTSUITE(out)", 3632 Style)); 3633 3634 EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n" 3635 "}} // TESTSUITE(out::in)", 3636 format("TESTSUITE(out) {\n" 3637 "TESTSUITE(in) {\n" 3638 "} // TESTSUITE(in)\n" 3639 "} // TESTSUITE(out)", 3640 Style)); 3641 3642 // Do not merge different namespaces/macros 3643 EXPECT_EQ("namespace out {\n" 3644 "TESTSUITE(in) {\n" 3645 "} // TESTSUITE(in)\n" 3646 "} // namespace out", 3647 format("namespace out {\n" 3648 "TESTSUITE(in) {\n" 3649 "} // TESTSUITE(in)\n" 3650 "} // namespace out", 3651 Style)); 3652 EXPECT_EQ("TESTSUITE(out) {\n" 3653 "namespace in {\n" 3654 "} // namespace in\n" 3655 "} // TESTSUITE(out)", 3656 format("TESTSUITE(out) {\n" 3657 "namespace in {\n" 3658 "} // namespace in\n" 3659 "} // TESTSUITE(out)", 3660 Style)); 3661 Style.NamespaceMacros.push_back("FOOBAR"); 3662 EXPECT_EQ("TESTSUITE(out) {\n" 3663 "FOOBAR(in) {\n" 3664 "} // FOOBAR(in)\n" 3665 "} // TESTSUITE(out)", 3666 format("TESTSUITE(out) {\n" 3667 "FOOBAR(in) {\n" 3668 "} // FOOBAR(in)\n" 3669 "} // TESTSUITE(out)", 3670 Style)); 3671 } 3672 3673 TEST_F(FormatTest, FormatsCompactNamespaces) { 3674 FormatStyle Style = getLLVMStyle(); 3675 Style.CompactNamespaces = true; 3676 Style.NamespaceMacros.push_back("TESTSUITE"); 3677 3678 verifyFormat("namespace A { namespace B {\n" 3679 "}} // namespace A::B", 3680 Style); 3681 3682 EXPECT_EQ("namespace out { namespace in {\n" 3683 "}} // namespace out::in", 3684 format("namespace out {\n" 3685 "namespace in {\n" 3686 "} // namespace in\n" 3687 "} // namespace out", 3688 Style)); 3689 3690 // Only namespaces which have both consecutive opening and end get compacted 3691 EXPECT_EQ("namespace out {\n" 3692 "namespace in1 {\n" 3693 "} // namespace in1\n" 3694 "namespace in2 {\n" 3695 "} // namespace in2\n" 3696 "} // namespace out", 3697 format("namespace out {\n" 3698 "namespace in1 {\n" 3699 "} // namespace in1\n" 3700 "namespace in2 {\n" 3701 "} // namespace in2\n" 3702 "} // namespace out", 3703 Style)); 3704 3705 EXPECT_EQ("namespace out {\n" 3706 "int i;\n" 3707 "namespace in {\n" 3708 "int j;\n" 3709 "} // namespace in\n" 3710 "int k;\n" 3711 "} // namespace out", 3712 format("namespace out { int i;\n" 3713 "namespace in { int j; } // namespace in\n" 3714 "int k; } // namespace out", 3715 Style)); 3716 3717 EXPECT_EQ("namespace A { namespace B { namespace C {\n" 3718 "}}} // namespace A::B::C\n", 3719 format("namespace A { namespace B {\n" 3720 "namespace C {\n" 3721 "}} // namespace B::C\n" 3722 "} // namespace A\n", 3723 Style)); 3724 3725 Style.ColumnLimit = 40; 3726 EXPECT_EQ("namespace aaaaaaaaaa {\n" 3727 "namespace bbbbbbbbbb {\n" 3728 "}} // namespace aaaaaaaaaa::bbbbbbbbbb", 3729 format("namespace aaaaaaaaaa {\n" 3730 "namespace bbbbbbbbbb {\n" 3731 "} // namespace bbbbbbbbbb\n" 3732 "} // namespace aaaaaaaaaa", 3733 Style)); 3734 3735 EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n" 3736 "namespace cccccc {\n" 3737 "}}} // namespace aaaaaa::bbbbbb::cccccc", 3738 format("namespace aaaaaa {\n" 3739 "namespace bbbbbb {\n" 3740 "namespace cccccc {\n" 3741 "} // namespace cccccc\n" 3742 "} // namespace bbbbbb\n" 3743 "} // namespace aaaaaa", 3744 Style)); 3745 Style.ColumnLimit = 80; 3746 3747 // Extra semicolon after 'inner' closing brace prevents merging 3748 EXPECT_EQ("namespace out { namespace in {\n" 3749 "}; } // namespace out::in", 3750 format("namespace out {\n" 3751 "namespace in {\n" 3752 "}; // namespace in\n" 3753 "} // namespace out", 3754 Style)); 3755 3756 // Extra semicolon after 'outer' closing brace is conserved 3757 EXPECT_EQ("namespace out { namespace in {\n" 3758 "}}; // namespace out::in", 3759 format("namespace out {\n" 3760 "namespace in {\n" 3761 "} // namespace in\n" 3762 "}; // namespace out", 3763 Style)); 3764 3765 Style.NamespaceIndentation = FormatStyle::NI_All; 3766 EXPECT_EQ("namespace out { namespace in {\n" 3767 " int i;\n" 3768 "}} // namespace out::in", 3769 format("namespace out {\n" 3770 "namespace in {\n" 3771 "int i;\n" 3772 "} // namespace in\n" 3773 "} // namespace out", 3774 Style)); 3775 EXPECT_EQ("namespace out { namespace mid {\n" 3776 " namespace in {\n" 3777 " int j;\n" 3778 " } // namespace in\n" 3779 " int k;\n" 3780 "}} // namespace out::mid", 3781 format("namespace out { namespace mid {\n" 3782 "namespace in { int j; } // namespace in\n" 3783 "int k; }} // namespace out::mid", 3784 Style)); 3785 3786 Style.NamespaceIndentation = FormatStyle::NI_Inner; 3787 EXPECT_EQ("namespace out { namespace in {\n" 3788 " int i;\n" 3789 "}} // namespace out::in", 3790 format("namespace out {\n" 3791 "namespace in {\n" 3792 "int i;\n" 3793 "} // namespace in\n" 3794 "} // namespace out", 3795 Style)); 3796 EXPECT_EQ("namespace out { namespace mid { namespace in {\n" 3797 " int i;\n" 3798 "}}} // namespace out::mid::in", 3799 format("namespace out {\n" 3800 "namespace mid {\n" 3801 "namespace in {\n" 3802 "int i;\n" 3803 "} // namespace in\n" 3804 "} // namespace mid\n" 3805 "} // namespace out", 3806 Style)); 3807 } 3808 3809 TEST_F(FormatTest, FormatsExternC) { 3810 verifyFormat("extern \"C\" {\nint a;"); 3811 verifyFormat("extern \"C\" {}"); 3812 verifyFormat("extern \"C\" {\n" 3813 "int foo();\n" 3814 "}"); 3815 verifyFormat("extern \"C\" int foo() {}"); 3816 verifyFormat("extern \"C\" int foo();"); 3817 verifyFormat("extern \"C\" int foo() {\n" 3818 " int i = 42;\n" 3819 " return i;\n" 3820 "}"); 3821 3822 FormatStyle Style = getLLVMStyle(); 3823 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 3824 Style.BraceWrapping.AfterFunction = true; 3825 verifyFormat("extern \"C\" int foo() {}", Style); 3826 verifyFormat("extern \"C\" int foo();", Style); 3827 verifyFormat("extern \"C\" int foo()\n" 3828 "{\n" 3829 " int i = 42;\n" 3830 " return i;\n" 3831 "}", 3832 Style); 3833 3834 Style.BraceWrapping.AfterExternBlock = true; 3835 Style.BraceWrapping.SplitEmptyRecord = false; 3836 verifyFormat("extern \"C\"\n" 3837 "{}", 3838 Style); 3839 verifyFormat("extern \"C\"\n" 3840 "{\n" 3841 " int foo();\n" 3842 "}", 3843 Style); 3844 } 3845 3846 TEST_F(FormatTest, IndentExternBlockStyle) { 3847 FormatStyle Style = getLLVMStyle(); 3848 Style.IndentWidth = 2; 3849 3850 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 3851 verifyFormat("extern \"C\" { /*9*/\n" 3852 "}", 3853 Style); 3854 verifyFormat("extern \"C\" {\n" 3855 " int foo10();\n" 3856 "}", 3857 Style); 3858 3859 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 3860 verifyFormat("extern \"C\" { /*11*/\n" 3861 "}", 3862 Style); 3863 verifyFormat("extern \"C\" {\n" 3864 "int foo12();\n" 3865 "}", 3866 Style); 3867 3868 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 3869 Style.BraceWrapping.AfterExternBlock = true; 3870 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 3871 verifyFormat("extern \"C\"\n" 3872 "{ /*13*/\n" 3873 "}", 3874 Style); 3875 verifyFormat("extern \"C\"\n{\n" 3876 " int foo14();\n" 3877 "}", 3878 Style); 3879 3880 Style.BraceWrapping.AfterExternBlock = false; 3881 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 3882 verifyFormat("extern \"C\" { /*15*/\n" 3883 "}", 3884 Style); 3885 verifyFormat("extern \"C\" {\n" 3886 "int foo16();\n" 3887 "}", 3888 Style); 3889 3890 Style.BraceWrapping.AfterExternBlock = true; 3891 verifyFormat("extern \"C\"\n" 3892 "{ /*13*/\n" 3893 "}", 3894 Style); 3895 verifyFormat("extern \"C\"\n" 3896 "{\n" 3897 "int foo14();\n" 3898 "}", 3899 Style); 3900 3901 Style.IndentExternBlock = FormatStyle::IEBS_Indent; 3902 verifyFormat("extern \"C\"\n" 3903 "{ /*13*/\n" 3904 "}", 3905 Style); 3906 verifyFormat("extern \"C\"\n" 3907 "{\n" 3908 " int foo14();\n" 3909 "}", 3910 Style); 3911 } 3912 3913 TEST_F(FormatTest, FormatsInlineASM) { 3914 verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));"); 3915 verifyFormat("asm(\"nop\" ::: \"memory\");"); 3916 verifyFormat( 3917 "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n" 3918 " \"cpuid\\n\\t\"\n" 3919 " \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n" 3920 " : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n" 3921 " : \"a\"(value));"); 3922 EXPECT_EQ( 3923 "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n" 3924 " __asm {\n" 3925 " mov edx,[that] // vtable in edx\n" 3926 " mov eax,methodIndex\n" 3927 " call [edx][eax*4] // stdcall\n" 3928 " }\n" 3929 "}", 3930 format("void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n" 3931 " __asm {\n" 3932 " mov edx,[that] // vtable in edx\n" 3933 " mov eax,methodIndex\n" 3934 " call [edx][eax*4] // stdcall\n" 3935 " }\n" 3936 "}")); 3937 EXPECT_EQ("_asm {\n" 3938 " xor eax, eax;\n" 3939 " cpuid;\n" 3940 "}", 3941 format("_asm {\n" 3942 " xor eax, eax;\n" 3943 " cpuid;\n" 3944 "}")); 3945 verifyFormat("void function() {\n" 3946 " // comment\n" 3947 " asm(\"\");\n" 3948 "}"); 3949 EXPECT_EQ("__asm {\n" 3950 "}\n" 3951 "int i;", 3952 format("__asm {\n" 3953 "}\n" 3954 "int i;")); 3955 } 3956 3957 TEST_F(FormatTest, FormatTryCatch) { 3958 verifyFormat("try {\n" 3959 " throw a * b;\n" 3960 "} catch (int a) {\n" 3961 " // Do nothing.\n" 3962 "} catch (...) {\n" 3963 " exit(42);\n" 3964 "}"); 3965 3966 // Function-level try statements. 3967 verifyFormat("int f() try { return 4; } catch (...) {\n" 3968 " return 5;\n" 3969 "}"); 3970 verifyFormat("class A {\n" 3971 " int a;\n" 3972 " A() try : a(0) {\n" 3973 " } catch (...) {\n" 3974 " throw;\n" 3975 " }\n" 3976 "};\n"); 3977 verifyFormat("class A {\n" 3978 " int a;\n" 3979 " A() try : a(0), b{1} {\n" 3980 " } catch (...) {\n" 3981 " throw;\n" 3982 " }\n" 3983 "};\n"); 3984 verifyFormat("class A {\n" 3985 " int a;\n" 3986 " A() try : a(0), b{1}, c{2} {\n" 3987 " } catch (...) {\n" 3988 " throw;\n" 3989 " }\n" 3990 "};\n"); 3991 verifyFormat("class A {\n" 3992 " int a;\n" 3993 " A() try : a(0), b{1}, c{2} {\n" 3994 " { // New scope.\n" 3995 " }\n" 3996 " } catch (...) {\n" 3997 " throw;\n" 3998 " }\n" 3999 "};\n"); 4000 4001 // Incomplete try-catch blocks. 4002 verifyIncompleteFormat("try {} catch ("); 4003 } 4004 4005 TEST_F(FormatTest, FormatTryAsAVariable) { 4006 verifyFormat("int try;"); 4007 verifyFormat("int try, size;"); 4008 verifyFormat("try = foo();"); 4009 verifyFormat("if (try < size) {\n return true;\n}"); 4010 4011 verifyFormat("int catch;"); 4012 verifyFormat("int catch, size;"); 4013 verifyFormat("catch = foo();"); 4014 verifyFormat("if (catch < size) {\n return true;\n}"); 4015 4016 FormatStyle Style = getLLVMStyle(); 4017 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4018 Style.BraceWrapping.AfterFunction = true; 4019 Style.BraceWrapping.BeforeCatch = true; 4020 verifyFormat("try {\n" 4021 " int bar = 1;\n" 4022 "}\n" 4023 "catch (...) {\n" 4024 " int bar = 1;\n" 4025 "}", 4026 Style); 4027 verifyFormat("#if NO_EX\n" 4028 "try\n" 4029 "#endif\n" 4030 "{\n" 4031 "}\n" 4032 "#if NO_EX\n" 4033 "catch (...) {\n" 4034 "}", 4035 Style); 4036 verifyFormat("try /* abc */ {\n" 4037 " int bar = 1;\n" 4038 "}\n" 4039 "catch (...) {\n" 4040 " int bar = 1;\n" 4041 "}", 4042 Style); 4043 verifyFormat("try\n" 4044 "// abc\n" 4045 "{\n" 4046 " int bar = 1;\n" 4047 "}\n" 4048 "catch (...) {\n" 4049 " int bar = 1;\n" 4050 "}", 4051 Style); 4052 } 4053 4054 TEST_F(FormatTest, FormatSEHTryCatch) { 4055 verifyFormat("__try {\n" 4056 " int a = b * c;\n" 4057 "} __except (EXCEPTION_EXECUTE_HANDLER) {\n" 4058 " // Do nothing.\n" 4059 "}"); 4060 4061 verifyFormat("__try {\n" 4062 " int a = b * c;\n" 4063 "} __finally {\n" 4064 " // Do nothing.\n" 4065 "}"); 4066 4067 verifyFormat("DEBUG({\n" 4068 " __try {\n" 4069 " } __finally {\n" 4070 " }\n" 4071 "});\n"); 4072 } 4073 4074 TEST_F(FormatTest, IncompleteTryCatchBlocks) { 4075 verifyFormat("try {\n" 4076 " f();\n" 4077 "} catch {\n" 4078 " g();\n" 4079 "}"); 4080 verifyFormat("try {\n" 4081 " f();\n" 4082 "} catch (A a) MACRO(x) {\n" 4083 " g();\n" 4084 "} catch (B b) MACRO(x) {\n" 4085 " g();\n" 4086 "}"); 4087 } 4088 4089 TEST_F(FormatTest, FormatTryCatchBraceStyles) { 4090 FormatStyle Style = getLLVMStyle(); 4091 for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla, 4092 FormatStyle::BS_WebKit}) { 4093 Style.BreakBeforeBraces = BraceStyle; 4094 verifyFormat("try {\n" 4095 " // something\n" 4096 "} catch (...) {\n" 4097 " // something\n" 4098 "}", 4099 Style); 4100 } 4101 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 4102 verifyFormat("try {\n" 4103 " // something\n" 4104 "}\n" 4105 "catch (...) {\n" 4106 " // something\n" 4107 "}", 4108 Style); 4109 verifyFormat("__try {\n" 4110 " // something\n" 4111 "}\n" 4112 "__finally {\n" 4113 " // something\n" 4114 "}", 4115 Style); 4116 verifyFormat("@try {\n" 4117 " // something\n" 4118 "}\n" 4119 "@finally {\n" 4120 " // something\n" 4121 "}", 4122 Style); 4123 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 4124 verifyFormat("try\n" 4125 "{\n" 4126 " // something\n" 4127 "}\n" 4128 "catch (...)\n" 4129 "{\n" 4130 " // something\n" 4131 "}", 4132 Style); 4133 Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 4134 verifyFormat("try\n" 4135 " {\n" 4136 " // something white\n" 4137 " }\n" 4138 "catch (...)\n" 4139 " {\n" 4140 " // something white\n" 4141 " }", 4142 Style); 4143 Style.BreakBeforeBraces = FormatStyle::BS_GNU; 4144 verifyFormat("try\n" 4145 " {\n" 4146 " // something\n" 4147 " }\n" 4148 "catch (...)\n" 4149 " {\n" 4150 " // something\n" 4151 " }", 4152 Style); 4153 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4154 Style.BraceWrapping.BeforeCatch = true; 4155 verifyFormat("try {\n" 4156 " // something\n" 4157 "}\n" 4158 "catch (...) {\n" 4159 " // something\n" 4160 "}", 4161 Style); 4162 } 4163 4164 TEST_F(FormatTest, StaticInitializers) { 4165 verifyFormat("static SomeClass SC = {1, 'a'};"); 4166 4167 verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n" 4168 " 100000000, " 4169 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};"); 4170 4171 // Here, everything other than the "}" would fit on a line. 4172 verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n" 4173 " 10000000000000000000000000};"); 4174 EXPECT_EQ("S s = {a,\n" 4175 "\n" 4176 " b};", 4177 format("S s = {\n" 4178 " a,\n" 4179 "\n" 4180 " b\n" 4181 "};")); 4182 4183 // FIXME: This would fit into the column limit if we'd fit "{ {" on the first 4184 // line. However, the formatting looks a bit off and this probably doesn't 4185 // happen often in practice. 4186 verifyFormat("static int Variable[1] = {\n" 4187 " {1000000000000000000000000000000000000}};", 4188 getLLVMStyleWithColumns(40)); 4189 } 4190 4191 TEST_F(FormatTest, DesignatedInitializers) { 4192 verifyFormat("const struct A a = {.a = 1, .b = 2};"); 4193 verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n" 4194 " .bbbbbbbbbb = 2,\n" 4195 " .cccccccccc = 3,\n" 4196 " .dddddddddd = 4,\n" 4197 " .eeeeeeeeee = 5};"); 4198 verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n" 4199 " .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n" 4200 " .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n" 4201 " .ccccccccccccccccccccccccccc = 3,\n" 4202 " .ddddddddddddddddddddddddddd = 4,\n" 4203 " .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};"); 4204 4205 verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};"); 4206 4207 verifyFormat("const struct A a = {[0] = 1, [1] = 2};"); 4208 verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n" 4209 " [2] = bbbbbbbbbb,\n" 4210 " [3] = cccccccccc,\n" 4211 " [4] = dddddddddd,\n" 4212 " [5] = eeeeeeeeee};"); 4213 verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n" 4214 " [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 4215 " [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 4216 " [3] = cccccccccccccccccccccccccccccccccccccc,\n" 4217 " [4] = dddddddddddddddddddddddddddddddddddddd,\n" 4218 " [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};"); 4219 } 4220 4221 TEST_F(FormatTest, NestedStaticInitializers) { 4222 verifyFormat("static A x = {{{}}};\n"); 4223 verifyFormat("static A x = {{{init1, init2, init3, init4},\n" 4224 " {init1, init2, init3, init4}}};", 4225 getLLVMStyleWithColumns(50)); 4226 4227 verifyFormat("somes Status::global_reps[3] = {\n" 4228 " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n" 4229 " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n" 4230 " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};", 4231 getLLVMStyleWithColumns(60)); 4232 verifyGoogleFormat("SomeType Status::global_reps[3] = {\n" 4233 " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n" 4234 " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n" 4235 " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};"); 4236 verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n" 4237 " {rect.fRight - rect.fLeft, rect.fBottom - " 4238 "rect.fTop}};"); 4239 4240 verifyFormat( 4241 "SomeArrayOfSomeType a = {\n" 4242 " {{1, 2, 3},\n" 4243 " {1, 2, 3},\n" 4244 " {111111111111111111111111111111, 222222222222222222222222222222,\n" 4245 " 333333333333333333333333333333},\n" 4246 " {1, 2, 3},\n" 4247 " {1, 2, 3}}};"); 4248 verifyFormat( 4249 "SomeArrayOfSomeType a = {\n" 4250 " {{1, 2, 3}},\n" 4251 " {{1, 2, 3}},\n" 4252 " {{111111111111111111111111111111, 222222222222222222222222222222,\n" 4253 " 333333333333333333333333333333}},\n" 4254 " {{1, 2, 3}},\n" 4255 " {{1, 2, 3}}};"); 4256 4257 verifyFormat("struct {\n" 4258 " unsigned bit;\n" 4259 " const char *const name;\n" 4260 "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n" 4261 " {kOsWin, \"Windows\"},\n" 4262 " {kOsLinux, \"Linux\"},\n" 4263 " {kOsCrOS, \"Chrome OS\"}};"); 4264 verifyFormat("struct {\n" 4265 " unsigned bit;\n" 4266 " const char *const name;\n" 4267 "} kBitsToOs[] = {\n" 4268 " {kOsMac, \"Mac\"},\n" 4269 " {kOsWin, \"Windows\"},\n" 4270 " {kOsLinux, \"Linux\"},\n" 4271 " {kOsCrOS, \"Chrome OS\"},\n" 4272 "};"); 4273 } 4274 4275 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) { 4276 verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro(" 4277 " \\\n" 4278 " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)"); 4279 } 4280 4281 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) { 4282 verifyFormat("virtual void write(ELFWriter *writerrr,\n" 4283 " OwningPtr<FileOutputBuffer> &buffer) = 0;"); 4284 4285 // Do break defaulted and deleted functions. 4286 verifyFormat("virtual void ~Deeeeeeeestructor() =\n" 4287 " default;", 4288 getLLVMStyleWithColumns(40)); 4289 verifyFormat("virtual void ~Deeeeeeeestructor() =\n" 4290 " delete;", 4291 getLLVMStyleWithColumns(40)); 4292 } 4293 4294 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) { 4295 verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3", 4296 getLLVMStyleWithColumns(40)); 4297 verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"", 4298 getLLVMStyleWithColumns(40)); 4299 EXPECT_EQ("#define Q \\\n" 4300 " \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\" \\\n" 4301 " \"aaaaaaaa.cpp\"", 4302 format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"", 4303 getLLVMStyleWithColumns(40))); 4304 } 4305 4306 TEST_F(FormatTest, UnderstandsLinePPDirective) { 4307 EXPECT_EQ("# 123 \"A string literal\"", 4308 format(" # 123 \"A string literal\"")); 4309 } 4310 4311 TEST_F(FormatTest, LayoutUnknownPPDirective) { 4312 EXPECT_EQ("#;", format("#;")); 4313 verifyFormat("#\n;\n;\n;"); 4314 } 4315 4316 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) { 4317 EXPECT_EQ("#line 42 \"test\"\n", 4318 format("# \\\n line \\\n 42 \\\n \"test\"\n")); 4319 EXPECT_EQ("#define A B\n", format("# \\\n define \\\n A \\\n B\n", 4320 getLLVMStyleWithColumns(12))); 4321 } 4322 4323 TEST_F(FormatTest, EndOfFileEndsPPDirective) { 4324 EXPECT_EQ("#line 42 \"test\"", 4325 format("# \\\n line \\\n 42 \\\n \"test\"")); 4326 EXPECT_EQ("#define A B", format("# \\\n define \\\n A \\\n B")); 4327 } 4328 4329 TEST_F(FormatTest, DoesntRemoveUnknownTokens) { 4330 verifyFormat("#define A \\x20"); 4331 verifyFormat("#define A \\ x20"); 4332 EXPECT_EQ("#define A \\ x20", format("#define A \\ x20")); 4333 verifyFormat("#define A ''"); 4334 verifyFormat("#define A ''qqq"); 4335 verifyFormat("#define A `qqq"); 4336 verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");"); 4337 EXPECT_EQ("const char *c = STRINGIFY(\n" 4338 "\\na : b);", 4339 format("const char * c = STRINGIFY(\n" 4340 "\\na : b);")); 4341 4342 verifyFormat("a\r\\"); 4343 verifyFormat("a\v\\"); 4344 verifyFormat("a\f\\"); 4345 } 4346 4347 TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) { 4348 FormatStyle style = getChromiumStyle(FormatStyle::LK_Cpp); 4349 style.IndentWidth = 4; 4350 style.PPIndentWidth = 1; 4351 4352 style.IndentPPDirectives = FormatStyle::PPDIS_None; 4353 verifyFormat("#ifdef __linux__\n" 4354 "void foo() {\n" 4355 " int x = 0;\n" 4356 "}\n" 4357 "#define FOO\n" 4358 "#endif\n" 4359 "void bar() {\n" 4360 " int y = 0;\n" 4361 "}\n", 4362 style); 4363 4364 style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash; 4365 verifyFormat("#ifdef __linux__\n" 4366 "void foo() {\n" 4367 " int x = 0;\n" 4368 "}\n" 4369 "# define FOO foo\n" 4370 "#endif\n" 4371 "void bar() {\n" 4372 " int y = 0;\n" 4373 "}\n", 4374 style); 4375 4376 style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash; 4377 verifyFormat("#ifdef __linux__\n" 4378 "void foo() {\n" 4379 " int x = 0;\n" 4380 "}\n" 4381 " #define FOO foo\n" 4382 "#endif\n" 4383 "void bar() {\n" 4384 " int y = 0;\n" 4385 "}\n", 4386 style); 4387 } 4388 4389 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) { 4390 verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13)); 4391 verifyFormat("#define A( \\\n BB)", getLLVMStyleWithColumns(12)); 4392 verifyFormat("#define A( \\\n A, B)", getLLVMStyleWithColumns(12)); 4393 // FIXME: We never break before the macro name. 4394 verifyFormat("#define AA( \\\n B)", getLLVMStyleWithColumns(12)); 4395 4396 verifyFormat("#define A A\n#define A A"); 4397 verifyFormat("#define A(X) A\n#define A A"); 4398 4399 verifyFormat("#define Something Other", getLLVMStyleWithColumns(23)); 4400 verifyFormat("#define Something \\\n Other", getLLVMStyleWithColumns(22)); 4401 } 4402 4403 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) { 4404 EXPECT_EQ("// somecomment\n" 4405 "#include \"a.h\"\n" 4406 "#define A( \\\n" 4407 " A, B)\n" 4408 "#include \"b.h\"\n" 4409 "// somecomment\n", 4410 format(" // somecomment\n" 4411 " #include \"a.h\"\n" 4412 "#define A(A,\\\n" 4413 " B)\n" 4414 " #include \"b.h\"\n" 4415 " // somecomment\n", 4416 getLLVMStyleWithColumns(13))); 4417 } 4418 4419 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); } 4420 4421 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) { 4422 EXPECT_EQ("#define A \\\n" 4423 " c; \\\n" 4424 " e;\n" 4425 "f;", 4426 format("#define A c; e;\n" 4427 "f;", 4428 getLLVMStyleWithColumns(14))); 4429 } 4430 4431 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); } 4432 4433 TEST_F(FormatTest, MacroDefinitionInsideStatement) { 4434 EXPECT_EQ("int x,\n" 4435 "#define A\n" 4436 " y;", 4437 format("int x,\n#define A\ny;")); 4438 } 4439 4440 TEST_F(FormatTest, HashInMacroDefinition) { 4441 EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle())); 4442 EXPECT_EQ("#define A(c) u#c", format("#define A(c) u#c", getLLVMStyle())); 4443 EXPECT_EQ("#define A(c) U#c", format("#define A(c) U#c", getLLVMStyle())); 4444 EXPECT_EQ("#define A(c) u8#c", format("#define A(c) u8#c", getLLVMStyle())); 4445 EXPECT_EQ("#define A(c) LR#c", format("#define A(c) LR#c", getLLVMStyle())); 4446 EXPECT_EQ("#define A(c) uR#c", format("#define A(c) uR#c", getLLVMStyle())); 4447 EXPECT_EQ("#define A(c) UR#c", format("#define A(c) UR#c", getLLVMStyle())); 4448 EXPECT_EQ("#define A(c) u8R#c", format("#define A(c) u8R#c", getLLVMStyle())); 4449 verifyFormat("#define A \\\n b #c;", getLLVMStyleWithColumns(11)); 4450 verifyFormat("#define A \\\n" 4451 " { \\\n" 4452 " f(#c); \\\n" 4453 " }", 4454 getLLVMStyleWithColumns(11)); 4455 4456 verifyFormat("#define A(X) \\\n" 4457 " void function##X()", 4458 getLLVMStyleWithColumns(22)); 4459 4460 verifyFormat("#define A(a, b, c) \\\n" 4461 " void a##b##c()", 4462 getLLVMStyleWithColumns(22)); 4463 4464 verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22)); 4465 } 4466 4467 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) { 4468 EXPECT_EQ("#define A (x)", format("#define A (x)")); 4469 EXPECT_EQ("#define A(x)", format("#define A(x)")); 4470 4471 FormatStyle Style = getLLVMStyle(); 4472 Style.SpaceBeforeParens = FormatStyle::SBPO_Never; 4473 verifyFormat("#define true ((foo)1)", Style); 4474 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 4475 verifyFormat("#define false((foo)0)", Style); 4476 } 4477 4478 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) { 4479 EXPECT_EQ("#define A b;", format("#define A \\\n" 4480 " \\\n" 4481 " b;", 4482 getLLVMStyleWithColumns(25))); 4483 EXPECT_EQ("#define A \\\n" 4484 " \\\n" 4485 " a; \\\n" 4486 " b;", 4487 format("#define A \\\n" 4488 " \\\n" 4489 " a; \\\n" 4490 " b;", 4491 getLLVMStyleWithColumns(11))); 4492 EXPECT_EQ("#define A \\\n" 4493 " a; \\\n" 4494 " \\\n" 4495 " b;", 4496 format("#define A \\\n" 4497 " a; \\\n" 4498 " \\\n" 4499 " b;", 4500 getLLVMStyleWithColumns(11))); 4501 } 4502 4503 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) { 4504 verifyIncompleteFormat("#define A :"); 4505 verifyFormat("#define SOMECASES \\\n" 4506 " case 1: \\\n" 4507 " case 2\n", 4508 getLLVMStyleWithColumns(20)); 4509 verifyFormat("#define MACRO(a) \\\n" 4510 " if (a) \\\n" 4511 " f(); \\\n" 4512 " else \\\n" 4513 " g()", 4514 getLLVMStyleWithColumns(18)); 4515 verifyFormat("#define A template <typename T>"); 4516 verifyIncompleteFormat("#define STR(x) #x\n" 4517 "f(STR(this_is_a_string_literal{));"); 4518 verifyFormat("#pragma omp threadprivate( \\\n" 4519 " y)), // expected-warning", 4520 getLLVMStyleWithColumns(28)); 4521 verifyFormat("#d, = };"); 4522 verifyFormat("#if \"a"); 4523 verifyIncompleteFormat("({\n" 4524 "#define b \\\n" 4525 " } \\\n" 4526 " a\n" 4527 "a", 4528 getLLVMStyleWithColumns(15)); 4529 verifyFormat("#define A \\\n" 4530 " { \\\n" 4531 " {\n" 4532 "#define B \\\n" 4533 " } \\\n" 4534 " }", 4535 getLLVMStyleWithColumns(15)); 4536 verifyNoCrash("#if a\na(\n#else\n#endif\n{a"); 4537 verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}"); 4538 verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};"); 4539 verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() { \n)}"); 4540 } 4541 4542 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) { 4543 verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline. 4544 EXPECT_EQ("class A : public QObject {\n" 4545 " Q_OBJECT\n" 4546 "\n" 4547 " A() {}\n" 4548 "};", 4549 format("class A : public QObject {\n" 4550 " Q_OBJECT\n" 4551 "\n" 4552 " A() {\n}\n" 4553 "} ;")); 4554 EXPECT_EQ("MACRO\n" 4555 "/*static*/ int i;", 4556 format("MACRO\n" 4557 " /*static*/ int i;")); 4558 EXPECT_EQ("SOME_MACRO\n" 4559 "namespace {\n" 4560 "void f();\n" 4561 "} // namespace", 4562 format("SOME_MACRO\n" 4563 " namespace {\n" 4564 "void f( );\n" 4565 "} // namespace")); 4566 // Only if the identifier contains at least 5 characters. 4567 EXPECT_EQ("HTTP f();", format("HTTP\nf();")); 4568 EXPECT_EQ("MACRO\nf();", format("MACRO\nf();")); 4569 // Only if everything is upper case. 4570 EXPECT_EQ("class A : public QObject {\n" 4571 " Q_Object A() {}\n" 4572 "};", 4573 format("class A : public QObject {\n" 4574 " Q_Object\n" 4575 " A() {\n}\n" 4576 "} ;")); 4577 4578 // Only if the next line can actually start an unwrapped line. 4579 EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;", 4580 format("SOME_WEIRD_LOG_MACRO\n" 4581 "<< SomeThing;")); 4582 4583 verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), " 4584 "(n, buffers))\n", 4585 getChromiumStyle(FormatStyle::LK_Cpp)); 4586 4587 // See PR41483 4588 EXPECT_EQ("/**/ FOO(a)\n" 4589 "FOO(b)", 4590 format("/**/ FOO(a)\n" 4591 "FOO(b)")); 4592 } 4593 4594 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) { 4595 EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n" 4596 "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n" 4597 "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n" 4598 "class X {};\n" 4599 "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n" 4600 "int *createScopDetectionPass() { return 0; }", 4601 format(" INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n" 4602 " INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n" 4603 " INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n" 4604 " class X {};\n" 4605 " INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n" 4606 " int *createScopDetectionPass() { return 0; }")); 4607 // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as 4608 // braces, so that inner block is indented one level more. 4609 EXPECT_EQ("int q() {\n" 4610 " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n" 4611 " IPC_MESSAGE_HANDLER(xxx, qqq)\n" 4612 " IPC_END_MESSAGE_MAP()\n" 4613 "}", 4614 format("int q() {\n" 4615 " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n" 4616 " IPC_MESSAGE_HANDLER(xxx, qqq)\n" 4617 " IPC_END_MESSAGE_MAP()\n" 4618 "}")); 4619 4620 // Same inside macros. 4621 EXPECT_EQ("#define LIST(L) \\\n" 4622 " L(A) \\\n" 4623 " L(B) \\\n" 4624 " L(C)", 4625 format("#define LIST(L) \\\n" 4626 " L(A) \\\n" 4627 " L(B) \\\n" 4628 " L(C)", 4629 getGoogleStyle())); 4630 4631 // These must not be recognized as macros. 4632 EXPECT_EQ("int q() {\n" 4633 " f(x);\n" 4634 " f(x) {}\n" 4635 " f(x)->g();\n" 4636 " f(x)->*g();\n" 4637 " f(x).g();\n" 4638 " f(x) = x;\n" 4639 " f(x) += x;\n" 4640 " f(x) -= x;\n" 4641 " f(x) *= x;\n" 4642 " f(x) /= x;\n" 4643 " f(x) %= x;\n" 4644 " f(x) &= x;\n" 4645 " f(x) |= x;\n" 4646 " f(x) ^= x;\n" 4647 " f(x) >>= x;\n" 4648 " f(x) <<= x;\n" 4649 " f(x)[y].z();\n" 4650 " LOG(INFO) << x;\n" 4651 " ifstream(x) >> x;\n" 4652 "}\n", 4653 format("int q() {\n" 4654 " f(x)\n;\n" 4655 " f(x)\n {}\n" 4656 " f(x)\n->g();\n" 4657 " f(x)\n->*g();\n" 4658 " f(x)\n.g();\n" 4659 " f(x)\n = x;\n" 4660 " f(x)\n += x;\n" 4661 " f(x)\n -= x;\n" 4662 " f(x)\n *= x;\n" 4663 " f(x)\n /= x;\n" 4664 " f(x)\n %= x;\n" 4665 " f(x)\n &= x;\n" 4666 " f(x)\n |= x;\n" 4667 " f(x)\n ^= x;\n" 4668 " f(x)\n >>= x;\n" 4669 " f(x)\n <<= x;\n" 4670 " f(x)\n[y].z();\n" 4671 " LOG(INFO)\n << x;\n" 4672 " ifstream(x)\n >> x;\n" 4673 "}\n")); 4674 EXPECT_EQ("int q() {\n" 4675 " F(x)\n" 4676 " if (1) {\n" 4677 " }\n" 4678 " F(x)\n" 4679 " while (1) {\n" 4680 " }\n" 4681 " F(x)\n" 4682 " G(x);\n" 4683 " F(x)\n" 4684 " try {\n" 4685 " Q();\n" 4686 " } catch (...) {\n" 4687 " }\n" 4688 "}\n", 4689 format("int q() {\n" 4690 "F(x)\n" 4691 "if (1) {}\n" 4692 "F(x)\n" 4693 "while (1) {}\n" 4694 "F(x)\n" 4695 "G(x);\n" 4696 "F(x)\n" 4697 "try { Q(); } catch (...) {}\n" 4698 "}\n")); 4699 EXPECT_EQ("class A {\n" 4700 " A() : t(0) {}\n" 4701 " A(int i) noexcept() : {}\n" 4702 " A(X x)\n" // FIXME: function-level try blocks are broken. 4703 " try : t(0) {\n" 4704 " } catch (...) {\n" 4705 " }\n" 4706 "};", 4707 format("class A {\n" 4708 " A()\n : t(0) {}\n" 4709 " A(int i)\n noexcept() : {}\n" 4710 " A(X x)\n" 4711 " try : t(0) {} catch (...) {}\n" 4712 "};")); 4713 FormatStyle Style = getLLVMStyle(); 4714 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 4715 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 4716 Style.BraceWrapping.AfterFunction = true; 4717 EXPECT_EQ("void f()\n" 4718 "try\n" 4719 "{\n" 4720 "}", 4721 format("void f() try {\n" 4722 "}", 4723 Style)); 4724 EXPECT_EQ("class SomeClass {\n" 4725 "public:\n" 4726 " SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 4727 "};", 4728 format("class SomeClass {\n" 4729 "public:\n" 4730 " SomeClass()\n" 4731 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 4732 "};")); 4733 EXPECT_EQ("class SomeClass {\n" 4734 "public:\n" 4735 " SomeClass()\n" 4736 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 4737 "};", 4738 format("class SomeClass {\n" 4739 "public:\n" 4740 " SomeClass()\n" 4741 " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" 4742 "};", 4743 getLLVMStyleWithColumns(40))); 4744 4745 verifyFormat("MACRO(>)"); 4746 4747 // Some macros contain an implicit semicolon. 4748 Style = getLLVMStyle(); 4749 Style.StatementMacros.push_back("FOO"); 4750 verifyFormat("FOO(a) int b = 0;"); 4751 verifyFormat("FOO(a)\n" 4752 "int b = 0;", 4753 Style); 4754 verifyFormat("FOO(a);\n" 4755 "int b = 0;", 4756 Style); 4757 verifyFormat("FOO(argc, argv, \"4.0.2\")\n" 4758 "int b = 0;", 4759 Style); 4760 verifyFormat("FOO()\n" 4761 "int b = 0;", 4762 Style); 4763 verifyFormat("FOO\n" 4764 "int b = 0;", 4765 Style); 4766 verifyFormat("void f() {\n" 4767 " FOO(a)\n" 4768 " return a;\n" 4769 "}", 4770 Style); 4771 verifyFormat("FOO(a)\n" 4772 "FOO(b)", 4773 Style); 4774 verifyFormat("int a = 0;\n" 4775 "FOO(b)\n" 4776 "int c = 0;", 4777 Style); 4778 verifyFormat("int a = 0;\n" 4779 "int x = FOO(a)\n" 4780 "int b = 0;", 4781 Style); 4782 verifyFormat("void foo(int a) { FOO(a) }\n" 4783 "uint32_t bar() {}", 4784 Style); 4785 } 4786 4787 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) { 4788 verifyFormat("#define A \\\n" 4789 " f({ \\\n" 4790 " g(); \\\n" 4791 " });", 4792 getLLVMStyleWithColumns(11)); 4793 } 4794 4795 TEST_F(FormatTest, IndentPreprocessorDirectives) { 4796 FormatStyle Style = getLLVMStyle(); 4797 Style.IndentPPDirectives = FormatStyle::PPDIS_None; 4798 Style.ColumnLimit = 40; 4799 verifyFormat("#ifdef _WIN32\n" 4800 "#define A 0\n" 4801 "#ifdef VAR2\n" 4802 "#define B 1\n" 4803 "#include <someheader.h>\n" 4804 "#define MACRO \\\n" 4805 " some_very_long_func_aaaaaaaaaa();\n" 4806 "#endif\n" 4807 "#else\n" 4808 "#define A 1\n" 4809 "#endif", 4810 Style); 4811 Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash; 4812 verifyFormat("#ifdef _WIN32\n" 4813 "# define A 0\n" 4814 "# ifdef VAR2\n" 4815 "# define B 1\n" 4816 "# include <someheader.h>\n" 4817 "# define MACRO \\\n" 4818 " some_very_long_func_aaaaaaaaaa();\n" 4819 "# endif\n" 4820 "#else\n" 4821 "# define A 1\n" 4822 "#endif", 4823 Style); 4824 verifyFormat("#if A\n" 4825 "# define MACRO \\\n" 4826 " void a(int x) { \\\n" 4827 " b(); \\\n" 4828 " c(); \\\n" 4829 " d(); \\\n" 4830 " e(); \\\n" 4831 " f(); \\\n" 4832 " }\n" 4833 "#endif", 4834 Style); 4835 // Comments before include guard. 4836 verifyFormat("// file comment\n" 4837 "// file comment\n" 4838 "#ifndef HEADER_H\n" 4839 "#define HEADER_H\n" 4840 "code();\n" 4841 "#endif", 4842 Style); 4843 // Test with include guards. 4844 verifyFormat("#ifndef HEADER_H\n" 4845 "#define HEADER_H\n" 4846 "code();\n" 4847 "#endif", 4848 Style); 4849 // Include guards must have a #define with the same variable immediately 4850 // after #ifndef. 4851 verifyFormat("#ifndef NOT_GUARD\n" 4852 "# define FOO\n" 4853 "code();\n" 4854 "#endif", 4855 Style); 4856 4857 // Include guards must cover the entire file. 4858 verifyFormat("code();\n" 4859 "code();\n" 4860 "#ifndef NOT_GUARD\n" 4861 "# define NOT_GUARD\n" 4862 "code();\n" 4863 "#endif", 4864 Style); 4865 verifyFormat("#ifndef NOT_GUARD\n" 4866 "# define NOT_GUARD\n" 4867 "code();\n" 4868 "#endif\n" 4869 "code();", 4870 Style); 4871 // Test with trailing blank lines. 4872 verifyFormat("#ifndef HEADER_H\n" 4873 "#define HEADER_H\n" 4874 "code();\n" 4875 "#endif\n", 4876 Style); 4877 // Include guards don't have #else. 4878 verifyFormat("#ifndef NOT_GUARD\n" 4879 "# define NOT_GUARD\n" 4880 "code();\n" 4881 "#else\n" 4882 "#endif", 4883 Style); 4884 verifyFormat("#ifndef NOT_GUARD\n" 4885 "# define NOT_GUARD\n" 4886 "code();\n" 4887 "#elif FOO\n" 4888 "#endif", 4889 Style); 4890 // Non-identifier #define after potential include guard. 4891 verifyFormat("#ifndef FOO\n" 4892 "# define 1\n" 4893 "#endif\n", 4894 Style); 4895 // #if closes past last non-preprocessor line. 4896 verifyFormat("#ifndef FOO\n" 4897 "#define FOO\n" 4898 "#if 1\n" 4899 "int i;\n" 4900 "# define A 0\n" 4901 "#endif\n" 4902 "#endif\n", 4903 Style); 4904 // Don't crash if there is an #elif directive without a condition. 4905 verifyFormat("#if 1\n" 4906 "int x;\n" 4907 "#elif\n" 4908 "int y;\n" 4909 "#else\n" 4910 "int z;\n" 4911 "#endif", 4912 Style); 4913 // FIXME: This doesn't handle the case where there's code between the 4914 // #ifndef and #define but all other conditions hold. This is because when 4915 // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the 4916 // previous code line yet, so we can't detect it. 4917 EXPECT_EQ("#ifndef NOT_GUARD\n" 4918 "code();\n" 4919 "#define NOT_GUARD\n" 4920 "code();\n" 4921 "#endif", 4922 format("#ifndef NOT_GUARD\n" 4923 "code();\n" 4924 "# define NOT_GUARD\n" 4925 "code();\n" 4926 "#endif", 4927 Style)); 4928 // FIXME: This doesn't handle cases where legitimate preprocessor lines may 4929 // be outside an include guard. Examples are #pragma once and 4930 // #pragma GCC diagnostic, or anything else that does not change the meaning 4931 // of the file if it's included multiple times. 4932 EXPECT_EQ("#ifdef WIN32\n" 4933 "# pragma once\n" 4934 "#endif\n" 4935 "#ifndef HEADER_H\n" 4936 "# define HEADER_H\n" 4937 "code();\n" 4938 "#endif", 4939 format("#ifdef WIN32\n" 4940 "# pragma once\n" 4941 "#endif\n" 4942 "#ifndef HEADER_H\n" 4943 "#define HEADER_H\n" 4944 "code();\n" 4945 "#endif", 4946 Style)); 4947 // FIXME: This does not detect when there is a single non-preprocessor line 4948 // in front of an include-guard-like structure where other conditions hold 4949 // because ScopedLineState hides the line. 4950 EXPECT_EQ("code();\n" 4951 "#ifndef HEADER_H\n" 4952 "#define HEADER_H\n" 4953 "code();\n" 4954 "#endif", 4955 format("code();\n" 4956 "#ifndef HEADER_H\n" 4957 "# define HEADER_H\n" 4958 "code();\n" 4959 "#endif", 4960 Style)); 4961 // Keep comments aligned with #, otherwise indent comments normally. These 4962 // tests cannot use verifyFormat because messUp manipulates leading 4963 // whitespace. 4964 { 4965 const char *Expected = "" 4966 "void f() {\n" 4967 "#if 1\n" 4968 "// Preprocessor aligned.\n" 4969 "# define A 0\n" 4970 " // Code. Separated by blank line.\n" 4971 "\n" 4972 "# define B 0\n" 4973 " // Code. Not aligned with #\n" 4974 "# define C 0\n" 4975 "#endif"; 4976 const char *ToFormat = "" 4977 "void f() {\n" 4978 "#if 1\n" 4979 "// Preprocessor aligned.\n" 4980 "# define A 0\n" 4981 "// Code. Separated by blank line.\n" 4982 "\n" 4983 "# define B 0\n" 4984 " // Code. Not aligned with #\n" 4985 "# define C 0\n" 4986 "#endif"; 4987 EXPECT_EQ(Expected, format(ToFormat, Style)); 4988 EXPECT_EQ(Expected, format(Expected, Style)); 4989 } 4990 // Keep block quotes aligned. 4991 { 4992 const char *Expected = "" 4993 "void f() {\n" 4994 "#if 1\n" 4995 "/* Preprocessor aligned. */\n" 4996 "# define A 0\n" 4997 " /* Code. Separated by blank line. */\n" 4998 "\n" 4999 "# define B 0\n" 5000 " /* Code. Not aligned with # */\n" 5001 "# define C 0\n" 5002 "#endif"; 5003 const char *ToFormat = "" 5004 "void f() {\n" 5005 "#if 1\n" 5006 "/* Preprocessor aligned. */\n" 5007 "# define A 0\n" 5008 "/* Code. Separated by blank line. */\n" 5009 "\n" 5010 "# define B 0\n" 5011 " /* Code. Not aligned with # */\n" 5012 "# define C 0\n" 5013 "#endif"; 5014 EXPECT_EQ(Expected, format(ToFormat, Style)); 5015 EXPECT_EQ(Expected, format(Expected, Style)); 5016 } 5017 // Keep comments aligned with un-indented directives. 5018 { 5019 const char *Expected = "" 5020 "void f() {\n" 5021 "// Preprocessor aligned.\n" 5022 "#define A 0\n" 5023 " // Code. Separated by blank line.\n" 5024 "\n" 5025 "#define B 0\n" 5026 " // Code. Not aligned with #\n" 5027 "#define C 0\n"; 5028 const char *ToFormat = "" 5029 "void f() {\n" 5030 "// Preprocessor aligned.\n" 5031 "#define A 0\n" 5032 "// Code. Separated by blank line.\n" 5033 "\n" 5034 "#define B 0\n" 5035 " // Code. Not aligned with #\n" 5036 "#define C 0\n"; 5037 EXPECT_EQ(Expected, format(ToFormat, Style)); 5038 EXPECT_EQ(Expected, format(Expected, Style)); 5039 } 5040 // Test AfterHash with tabs. 5041 { 5042 FormatStyle Tabbed = Style; 5043 Tabbed.UseTab = FormatStyle::UT_Always; 5044 Tabbed.IndentWidth = 8; 5045 Tabbed.TabWidth = 8; 5046 verifyFormat("#ifdef _WIN32\n" 5047 "#\tdefine A 0\n" 5048 "#\tifdef VAR2\n" 5049 "#\t\tdefine B 1\n" 5050 "#\t\tinclude <someheader.h>\n" 5051 "#\t\tdefine MACRO \\\n" 5052 "\t\t\tsome_very_long_func_aaaaaaaaaa();\n" 5053 "#\tendif\n" 5054 "#else\n" 5055 "#\tdefine A 1\n" 5056 "#endif", 5057 Tabbed); 5058 } 5059 5060 // Regression test: Multiline-macro inside include guards. 5061 verifyFormat("#ifndef HEADER_H\n" 5062 "#define HEADER_H\n" 5063 "#define A() \\\n" 5064 " int i; \\\n" 5065 " int j;\n" 5066 "#endif // HEADER_H", 5067 getLLVMStyleWithColumns(20)); 5068 5069 Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash; 5070 // Basic before hash indent tests 5071 verifyFormat("#ifdef _WIN32\n" 5072 " #define A 0\n" 5073 " #ifdef VAR2\n" 5074 " #define B 1\n" 5075 " #include <someheader.h>\n" 5076 " #define MACRO \\\n" 5077 " some_very_long_func_aaaaaaaaaa();\n" 5078 " #endif\n" 5079 "#else\n" 5080 " #define A 1\n" 5081 "#endif", 5082 Style); 5083 verifyFormat("#if A\n" 5084 " #define MACRO \\\n" 5085 " void a(int x) { \\\n" 5086 " b(); \\\n" 5087 " c(); \\\n" 5088 " d(); \\\n" 5089 " e(); \\\n" 5090 " f(); \\\n" 5091 " }\n" 5092 "#endif", 5093 Style); 5094 // Keep comments aligned with indented directives. These 5095 // tests cannot use verifyFormat because messUp manipulates leading 5096 // whitespace. 5097 { 5098 const char *Expected = "void f() {\n" 5099 "// Aligned to preprocessor.\n" 5100 "#if 1\n" 5101 " // Aligned to code.\n" 5102 " int a;\n" 5103 " #if 1\n" 5104 " // Aligned to preprocessor.\n" 5105 " #define A 0\n" 5106 " // Aligned to code.\n" 5107 " int b;\n" 5108 " #endif\n" 5109 "#endif\n" 5110 "}"; 5111 const char *ToFormat = "void f() {\n" 5112 "// Aligned to preprocessor.\n" 5113 "#if 1\n" 5114 "// Aligned to code.\n" 5115 "int a;\n" 5116 "#if 1\n" 5117 "// Aligned to preprocessor.\n" 5118 "#define A 0\n" 5119 "// Aligned to code.\n" 5120 "int b;\n" 5121 "#endif\n" 5122 "#endif\n" 5123 "}"; 5124 EXPECT_EQ(Expected, format(ToFormat, Style)); 5125 EXPECT_EQ(Expected, format(Expected, Style)); 5126 } 5127 { 5128 const char *Expected = "void f() {\n" 5129 "/* Aligned to preprocessor. */\n" 5130 "#if 1\n" 5131 " /* Aligned to code. */\n" 5132 " int a;\n" 5133 " #if 1\n" 5134 " /* Aligned to preprocessor. */\n" 5135 " #define A 0\n" 5136 " /* Aligned to code. */\n" 5137 " int b;\n" 5138 " #endif\n" 5139 "#endif\n" 5140 "}"; 5141 const char *ToFormat = "void f() {\n" 5142 "/* Aligned to preprocessor. */\n" 5143 "#if 1\n" 5144 "/* Aligned to code. */\n" 5145 "int a;\n" 5146 "#if 1\n" 5147 "/* Aligned to preprocessor. */\n" 5148 "#define A 0\n" 5149 "/* Aligned to code. */\n" 5150 "int b;\n" 5151 "#endif\n" 5152 "#endif\n" 5153 "}"; 5154 EXPECT_EQ(Expected, format(ToFormat, Style)); 5155 EXPECT_EQ(Expected, format(Expected, Style)); 5156 } 5157 5158 // Test single comment before preprocessor 5159 verifyFormat("// Comment\n" 5160 "\n" 5161 "#if 1\n" 5162 "#endif", 5163 Style); 5164 } 5165 5166 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) { 5167 verifyFormat("{\n { a #c; }\n}"); 5168 } 5169 5170 TEST_F(FormatTest, FormatUnbalancedStructuralElements) { 5171 EXPECT_EQ("#define A \\\n { \\\n {\nint i;", 5172 format("#define A { {\nint i;", getLLVMStyleWithColumns(11))); 5173 EXPECT_EQ("#define A \\\n } \\\n }\nint i;", 5174 format("#define A } }\nint i;", getLLVMStyleWithColumns(11))); 5175 } 5176 5177 TEST_F(FormatTest, EscapedNewlines) { 5178 FormatStyle Narrow = getLLVMStyleWithColumns(11); 5179 EXPECT_EQ("#define A \\\n int i; \\\n int j;", 5180 format("#define A \\\nint i;\\\n int j;", Narrow)); 5181 EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;")); 5182 EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();")); 5183 EXPECT_EQ("/* \\ \\ \\\n */", format("\\\n/* \\ \\ \\\n */")); 5184 EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>")); 5185 5186 FormatStyle AlignLeft = getLLVMStyle(); 5187 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left; 5188 EXPECT_EQ("#define MACRO(x) \\\n" 5189 "private: \\\n" 5190 " int x(int a);\n", 5191 format("#define MACRO(x) \\\n" 5192 "private: \\\n" 5193 " int x(int a);\n", 5194 AlignLeft)); 5195 5196 // CRLF line endings 5197 EXPECT_EQ("#define A \\\r\n int i; \\\r\n int j;", 5198 format("#define A \\\r\nint i;\\\r\n int j;", Narrow)); 5199 EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;")); 5200 EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();")); 5201 EXPECT_EQ("/* \\ \\ \\\r\n */", format("\\\r\n/* \\ \\ \\\r\n */")); 5202 EXPECT_EQ("<a\r\n\\\\\r\n>", format("<a\r\n\\\\\r\n>")); 5203 EXPECT_EQ("#define MACRO(x) \\\r\n" 5204 "private: \\\r\n" 5205 " int x(int a);\r\n", 5206 format("#define MACRO(x) \\\r\n" 5207 "private: \\\r\n" 5208 " int x(int a);\r\n", 5209 AlignLeft)); 5210 5211 FormatStyle DontAlign = getLLVMStyle(); 5212 DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 5213 DontAlign.MaxEmptyLinesToKeep = 3; 5214 // FIXME: can't use verifyFormat here because the newline before 5215 // "public:" is not inserted the first time it's reformatted 5216 EXPECT_EQ("#define A \\\n" 5217 " class Foo { \\\n" 5218 " void bar(); \\\n" 5219 "\\\n" 5220 "\\\n" 5221 "\\\n" 5222 " public: \\\n" 5223 " void baz(); \\\n" 5224 " };", 5225 format("#define A \\\n" 5226 " class Foo { \\\n" 5227 " void bar(); \\\n" 5228 "\\\n" 5229 "\\\n" 5230 "\\\n" 5231 " public: \\\n" 5232 " void baz(); \\\n" 5233 " };", 5234 DontAlign)); 5235 } 5236 5237 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) { 5238 verifyFormat("#define A \\\n" 5239 " int v( \\\n" 5240 " a); \\\n" 5241 " int i;", 5242 getLLVMStyleWithColumns(11)); 5243 } 5244 5245 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) { 5246 EXPECT_EQ( 5247 "#define ALooooooooooooooooooooooooooooooooooooooongMacro(" 5248 " \\\n" 5249 " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n" 5250 "\n" 5251 "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n" 5252 " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n", 5253 format(" #define ALooooooooooooooooooooooooooooooooooooooongMacro(" 5254 "\\\n" 5255 "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n" 5256 " \n" 5257 " AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n" 5258 " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n")); 5259 } 5260 5261 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) { 5262 EXPECT_EQ("int\n" 5263 "#define A\n" 5264 " a;", 5265 format("int\n#define A\na;")); 5266 verifyFormat("functionCallTo(\n" 5267 " someOtherFunction(\n" 5268 " withSomeParameters, whichInSequence,\n" 5269 " areLongerThanALine(andAnotherCall,\n" 5270 "#define A B\n" 5271 " withMoreParamters,\n" 5272 " whichStronglyInfluenceTheLayout),\n" 5273 " andMoreParameters),\n" 5274 " trailing);", 5275 getLLVMStyleWithColumns(69)); 5276 verifyFormat("Foo::Foo()\n" 5277 "#ifdef BAR\n" 5278 " : baz(0)\n" 5279 "#endif\n" 5280 "{\n" 5281 "}"); 5282 verifyFormat("void f() {\n" 5283 " if (true)\n" 5284 "#ifdef A\n" 5285 " f(42);\n" 5286 " x();\n" 5287 "#else\n" 5288 " g();\n" 5289 " x();\n" 5290 "#endif\n" 5291 "}"); 5292 verifyFormat("void f(param1, param2,\n" 5293 " param3,\n" 5294 "#ifdef A\n" 5295 " param4(param5,\n" 5296 "#ifdef A1\n" 5297 " param6,\n" 5298 "#ifdef A2\n" 5299 " param7),\n" 5300 "#else\n" 5301 " param8),\n" 5302 " param9,\n" 5303 "#endif\n" 5304 " param10,\n" 5305 "#endif\n" 5306 " param11)\n" 5307 "#else\n" 5308 " param12)\n" 5309 "#endif\n" 5310 "{\n" 5311 " x();\n" 5312 "}", 5313 getLLVMStyleWithColumns(28)); 5314 verifyFormat("#if 1\n" 5315 "int i;"); 5316 verifyFormat("#if 1\n" 5317 "#endif\n" 5318 "#if 1\n" 5319 "#else\n" 5320 "#endif\n"); 5321 verifyFormat("DEBUG({\n" 5322 " return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5323 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n" 5324 "});\n" 5325 "#if a\n" 5326 "#else\n" 5327 "#endif"); 5328 5329 verifyIncompleteFormat("void f(\n" 5330 "#if A\n" 5331 ");\n" 5332 "#else\n" 5333 "#endif"); 5334 } 5335 5336 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) { 5337 verifyFormat("#endif\n" 5338 "#if B"); 5339 } 5340 5341 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) { 5342 FormatStyle SingleLine = getLLVMStyle(); 5343 SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse; 5344 verifyFormat("#if 0\n" 5345 "#elif 1\n" 5346 "#endif\n" 5347 "void foo() {\n" 5348 " if (test) foo2();\n" 5349 "}", 5350 SingleLine); 5351 } 5352 5353 TEST_F(FormatTest, LayoutBlockInsideParens) { 5354 verifyFormat("functionCall({ int i; });"); 5355 verifyFormat("functionCall({\n" 5356 " int i;\n" 5357 " int j;\n" 5358 "});"); 5359 verifyFormat("functionCall(\n" 5360 " {\n" 5361 " int i;\n" 5362 " int j;\n" 5363 " },\n" 5364 " aaaa, bbbb, cccc);"); 5365 verifyFormat("functionA(functionB({\n" 5366 " int i;\n" 5367 " int j;\n" 5368 " }),\n" 5369 " aaaa, bbbb, cccc);"); 5370 verifyFormat("functionCall(\n" 5371 " {\n" 5372 " int i;\n" 5373 " int j;\n" 5374 " },\n" 5375 " aaaa, bbbb, // comment\n" 5376 " cccc);"); 5377 verifyFormat("functionA(functionB({\n" 5378 " int i;\n" 5379 " int j;\n" 5380 " }),\n" 5381 " aaaa, bbbb, // comment\n" 5382 " cccc);"); 5383 verifyFormat("functionCall(aaaa, bbbb, { int i; });"); 5384 verifyFormat("functionCall(aaaa, bbbb, {\n" 5385 " int i;\n" 5386 " int j;\n" 5387 "});"); 5388 verifyFormat( 5389 "Aaa(\n" // FIXME: There shouldn't be a linebreak here. 5390 " {\n" 5391 " int i; // break\n" 5392 " },\n" 5393 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 5394 " ccccccccccccccccc));"); 5395 verifyFormat("DEBUG({\n" 5396 " if (a)\n" 5397 " f();\n" 5398 "});"); 5399 } 5400 5401 TEST_F(FormatTest, LayoutBlockInsideStatement) { 5402 EXPECT_EQ("SOME_MACRO { int i; }\n" 5403 "int i;", 5404 format(" SOME_MACRO {int i;} int i;")); 5405 } 5406 5407 TEST_F(FormatTest, LayoutNestedBlocks) { 5408 verifyFormat("void AddOsStrings(unsigned bitmask) {\n" 5409 " struct s {\n" 5410 " int i;\n" 5411 " };\n" 5412 " s kBitsToOs[] = {{10}};\n" 5413 " for (int i = 0; i < 10; ++i)\n" 5414 " return;\n" 5415 "}"); 5416 verifyFormat("call(parameter, {\n" 5417 " something();\n" 5418 " // Comment using all columns.\n" 5419 " somethingelse();\n" 5420 "});", 5421 getLLVMStyleWithColumns(40)); 5422 verifyFormat("DEBUG( //\n" 5423 " { f(); }, a);"); 5424 verifyFormat("DEBUG( //\n" 5425 " {\n" 5426 " f(); //\n" 5427 " },\n" 5428 " a);"); 5429 5430 EXPECT_EQ("call(parameter, {\n" 5431 " something();\n" 5432 " // Comment too\n" 5433 " // looooooooooong.\n" 5434 " somethingElse();\n" 5435 "});", 5436 format("call(parameter, {\n" 5437 " something();\n" 5438 " // Comment too looooooooooong.\n" 5439 " somethingElse();\n" 5440 "});", 5441 getLLVMStyleWithColumns(29))); 5442 EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int i; });")); 5443 EXPECT_EQ("DEBUG({ // comment\n" 5444 " int i;\n" 5445 "});", 5446 format("DEBUG({ // comment\n" 5447 "int i;\n" 5448 "});")); 5449 EXPECT_EQ("DEBUG({\n" 5450 " int i;\n" 5451 "\n" 5452 " // comment\n" 5453 " int j;\n" 5454 "});", 5455 format("DEBUG({\n" 5456 " int i;\n" 5457 "\n" 5458 " // comment\n" 5459 " int j;\n" 5460 "});")); 5461 5462 verifyFormat("DEBUG({\n" 5463 " if (a)\n" 5464 " return;\n" 5465 "});"); 5466 verifyGoogleFormat("DEBUG({\n" 5467 " if (a) return;\n" 5468 "});"); 5469 FormatStyle Style = getGoogleStyle(); 5470 Style.ColumnLimit = 45; 5471 verifyFormat("Debug(\n" 5472 " aaaaa,\n" 5473 " {\n" 5474 " if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n" 5475 " },\n" 5476 " a);", 5477 Style); 5478 5479 verifyFormat("SomeFunction({MACRO({ return output; }), b});"); 5480 5481 verifyNoCrash("^{v^{a}}"); 5482 } 5483 5484 TEST_F(FormatTest, FormatNestedBlocksInMacros) { 5485 EXPECT_EQ("#define MACRO() \\\n" 5486 " Debug(aaa, /* force line break */ \\\n" 5487 " { \\\n" 5488 " int i; \\\n" 5489 " int j; \\\n" 5490 " })", 5491 format("#define MACRO() Debug(aaa, /* force line break */ \\\n" 5492 " { int i; int j; })", 5493 getGoogleStyle())); 5494 5495 EXPECT_EQ("#define A \\\n" 5496 " [] { \\\n" 5497 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 5498 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n" 5499 " }", 5500 format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 5501 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }", 5502 getGoogleStyle())); 5503 } 5504 5505 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) { 5506 EXPECT_EQ("{}", format("{}")); 5507 verifyFormat("enum E {};"); 5508 verifyFormat("enum E {}"); 5509 FormatStyle Style = getLLVMStyle(); 5510 Style.SpaceInEmptyBlock = true; 5511 EXPECT_EQ("void f() { }", format("void f() {}", Style)); 5512 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 5513 EXPECT_EQ("while (true) { }", format("while (true) {}", Style)); 5514 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 5515 Style.BraceWrapping.BeforeElse = false; 5516 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; 5517 verifyFormat("if (a)\n" 5518 "{\n" 5519 "} else if (b)\n" 5520 "{\n" 5521 "} else\n" 5522 "{ }", 5523 Style); 5524 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never; 5525 verifyFormat("if (a) {\n" 5526 "} else if (b) {\n" 5527 "} else {\n" 5528 "}", 5529 Style); 5530 Style.BraceWrapping.BeforeElse = true; 5531 verifyFormat("if (a) { }\n" 5532 "else if (b) { }\n" 5533 "else { }", 5534 Style); 5535 } 5536 5537 TEST_F(FormatTest, FormatBeginBlockEndMacros) { 5538 FormatStyle Style = getLLVMStyle(); 5539 Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$"; 5540 Style.MacroBlockEnd = "^[A-Z_]+_END$"; 5541 verifyFormat("FOO_BEGIN\n" 5542 " FOO_ENTRY\n" 5543 "FOO_END", 5544 Style); 5545 verifyFormat("FOO_BEGIN\n" 5546 " NESTED_FOO_BEGIN\n" 5547 " NESTED_FOO_ENTRY\n" 5548 " NESTED_FOO_END\n" 5549 "FOO_END", 5550 Style); 5551 verifyFormat("FOO_BEGIN(Foo, Bar)\n" 5552 " int x;\n" 5553 " x = 1;\n" 5554 "FOO_END(Baz)", 5555 Style); 5556 } 5557 5558 //===----------------------------------------------------------------------===// 5559 // Line break tests. 5560 //===----------------------------------------------------------------------===// 5561 5562 TEST_F(FormatTest, PreventConfusingIndents) { 5563 verifyFormat( 5564 "void f() {\n" 5565 " SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n" 5566 " parameter, parameter, parameter)),\n" 5567 " SecondLongCall(parameter));\n" 5568 "}"); 5569 verifyFormat( 5570 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5571 " aaaaaaaaaaaaaaaaaaaaaaaa(\n" 5572 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 5573 " aaaaaaaaaaaaaaaaaaaaaaaa);"); 5574 verifyFormat( 5575 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5576 " [aaaaaaaaaaaaaaaaaaaaaaaa\n" 5577 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n" 5578 " [aaaaaaaaaaaaaaaaaaaaaaaa]];"); 5579 verifyFormat( 5580 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 5581 " aaaaaaaaaaaaaaaaaaaaaaaa<\n" 5582 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n" 5583 " aaaaaaaaaaaaaaaaaaaaaaaa>;"); 5584 verifyFormat("int a = bbbb && ccc &&\n" 5585 " fffff(\n" 5586 "#define A Just forcing a new line\n" 5587 " ddd);"); 5588 } 5589 5590 TEST_F(FormatTest, LineBreakingInBinaryExpressions) { 5591 verifyFormat( 5592 "bool aaaaaaa =\n" 5593 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n" 5594 " bbbbbbbb();"); 5595 verifyFormat( 5596 "bool aaaaaaa =\n" 5597 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n" 5598 " bbbbbbbb();"); 5599 5600 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n" 5601 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n" 5602 " ccccccccc == ddddddddddd;"); 5603 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n" 5604 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n" 5605 " ccccccccc == ddddddddddd;"); 5606 verifyFormat( 5607 "bool aaaaaaaaaaaaaaaaaaaaa =\n" 5608 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n" 5609 " ccccccccc == ddddddddddd;"); 5610 5611 verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n" 5612 " aaaaaa) &&\n" 5613 " bbbbbb && cccccc;"); 5614 verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n" 5615 " aaaaaa) >>\n" 5616 " bbbbbb;"); 5617 verifyFormat("aa = Whitespaces.addUntouchableComment(\n" 5618 " SourceMgr.getSpellingColumnNumber(\n" 5619 " TheLine.Last->FormatTok.Tok.getLocation()) -\n" 5620 " 1);"); 5621 5622 verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 5623 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n" 5624 " cccccc) {\n}"); 5625 verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 5626 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n" 5627 " cccccc) {\n}"); 5628 verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 5629 " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n" 5630 " cccccc) {\n}"); 5631 verifyFormat("b = a &&\n" 5632 " // Comment\n" 5633 " b.c && d;"); 5634 5635 // If the LHS of a comparison is not a binary expression itself, the 5636 // additional linebreak confuses many people. 5637 verifyFormat( 5638 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5639 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n" 5640 "}"); 5641 verifyFormat( 5642 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5643 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 5644 "}"); 5645 verifyFormat( 5646 "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n" 5647 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 5648 "}"); 5649 verifyFormat( 5650 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5651 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n" 5652 "}"); 5653 // Even explicit parentheses stress the precedence enough to make the 5654 // additional break unnecessary. 5655 verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5656 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" 5657 "}"); 5658 // This cases is borderline, but with the indentation it is still readable. 5659 verifyFormat( 5660 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 5661 " aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5662 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 5663 "}", 5664 getLLVMStyleWithColumns(75)); 5665 5666 // If the LHS is a binary expression, we should still use the additional break 5667 // as otherwise the formatting hides the operator precedence. 5668 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5669 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 5670 " 5) {\n" 5671 "}"); 5672 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5673 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n" 5674 " 5) {\n" 5675 "}"); 5676 5677 FormatStyle OnePerLine = getLLVMStyle(); 5678 OnePerLine.BinPackParameters = false; 5679 verifyFormat( 5680 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 5681 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 5682 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}", 5683 OnePerLine); 5684 5685 verifyFormat("int i = someFunction(aaaaaaa, 0)\n" 5686 " .aaa(aaaaaaaaaaaaa) *\n" 5687 " aaaaaaa +\n" 5688 " aaaaaaa;", 5689 getLLVMStyleWithColumns(40)); 5690 } 5691 5692 TEST_F(FormatTest, ExpressionIndentation) { 5693 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5694 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5695 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 5696 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 5697 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n" 5698 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n" 5699 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 5700 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n" 5701 " ccccccccccccccccccccccccccccccccccccccccc;"); 5702 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 5703 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5704 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 5705 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 5706 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5707 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 5708 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 5709 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 5710 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" 5711 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" 5712 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5713 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); 5714 verifyFormat("if () {\n" 5715 "} else if (aaaaa && bbbbb > // break\n" 5716 " ccccc) {\n" 5717 "}"); 5718 verifyFormat("if () {\n" 5719 "} else if constexpr (aaaaa && bbbbb > // break\n" 5720 " ccccc) {\n" 5721 "}"); 5722 verifyFormat("if () {\n" 5723 "} else if CONSTEXPR (aaaaa && bbbbb > // break\n" 5724 " ccccc) {\n" 5725 "}"); 5726 verifyFormat("if () {\n" 5727 "} else if (aaaaa &&\n" 5728 " bbbbb > // break\n" 5729 " ccccc &&\n" 5730 " ddddd) {\n" 5731 "}"); 5732 5733 // Presence of a trailing comment used to change indentation of b. 5734 verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n" 5735 " b;\n" 5736 "return aaaaaaaaaaaaaaaaaaa +\n" 5737 " b; //", 5738 getLLVMStyleWithColumns(30)); 5739 } 5740 5741 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) { 5742 // Not sure what the best system is here. Like this, the LHS can be found 5743 // immediately above an operator (everything with the same or a higher 5744 // indent). The RHS is aligned right of the operator and so compasses 5745 // everything until something with the same indent as the operator is found. 5746 // FIXME: Is this a good system? 5747 FormatStyle Style = getLLVMStyle(); 5748 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 5749 verifyFormat( 5750 "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5751 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5752 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5753 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5754 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 5755 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 5756 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5757 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5758 " > ccccccccccccccccccccccccccccccccccccccccc;", 5759 Style); 5760 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5761 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5762 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5763 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 5764 Style); 5765 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5766 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5767 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5768 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 5769 Style); 5770 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5771 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5772 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5773 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 5774 Style); 5775 verifyFormat("if () {\n" 5776 "} else if (aaaaa\n" 5777 " && bbbbb // break\n" 5778 " > ccccc) {\n" 5779 "}", 5780 Style); 5781 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5782 " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 5783 Style); 5784 verifyFormat("return (a)\n" 5785 " // comment\n" 5786 " + b;", 5787 Style); 5788 verifyFormat( 5789 "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5790 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 5791 " + cc;", 5792 Style); 5793 5794 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5795 " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 5796 Style); 5797 5798 // Forced by comments. 5799 verifyFormat( 5800 "unsigned ContentSize =\n" 5801 " sizeof(int16_t) // DWARF ARange version number\n" 5802 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 5803 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 5804 " + sizeof(int8_t); // Segment Size (in bytes)"); 5805 5806 verifyFormat("return boost::fusion::at_c<0>(iiii).second\n" 5807 " == boost::fusion::at_c<1>(iiii).second;", 5808 Style); 5809 5810 Style.ColumnLimit = 60; 5811 verifyFormat("zzzzzzzzzz\n" 5812 " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 5813 " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);", 5814 Style); 5815 5816 Style.ColumnLimit = 80; 5817 Style.IndentWidth = 4; 5818 Style.TabWidth = 4; 5819 Style.UseTab = FormatStyle::UT_Always; 5820 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 5821 Style.AlignOperands = FormatStyle::OAS_DontAlign; 5822 EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n" 5823 "\t&& (someOtherLongishConditionPart1\n" 5824 "\t\t|| someOtherEvenLongerNestedConditionPart2);", 5825 format("return someVeryVeryLongConditionThatBarelyFitsOnALine && " 5826 "(someOtherLongishConditionPart1 || " 5827 "someOtherEvenLongerNestedConditionPart2);", 5828 Style)); 5829 } 5830 5831 TEST_F(FormatTest, ExpressionIndentationStrictAlign) { 5832 FormatStyle Style = getLLVMStyle(); 5833 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 5834 Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator; 5835 5836 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5837 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5838 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5839 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5840 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 5841 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 5842 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5843 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5844 " > ccccccccccccccccccccccccccccccccccccccccc;", 5845 Style); 5846 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5847 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5848 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5849 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 5850 Style); 5851 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5852 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5853 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5854 " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 5855 Style); 5856 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5857 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5858 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5859 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", 5860 Style); 5861 verifyFormat("if () {\n" 5862 "} else if (aaaaa\n" 5863 " && bbbbb // break\n" 5864 " > ccccc) {\n" 5865 "}", 5866 Style); 5867 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5868 " && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 5869 Style); 5870 verifyFormat("return (a)\n" 5871 " // comment\n" 5872 " + b;", 5873 Style); 5874 verifyFormat( 5875 "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5876 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 5877 " + cc;", 5878 Style); 5879 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 5880 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 5881 " : 3333333333333333;", 5882 Style); 5883 verifyFormat( 5884 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 5885 " : ccccccccccccccc ? dddddddddddddddddd\n" 5886 " : eeeeeeeeeeeeeeeeee)\n" 5887 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 5888 " : 3333333333333333;", 5889 Style); 5890 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5891 " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 5892 Style); 5893 5894 verifyFormat("return boost::fusion::at_c<0>(iiii).second\n" 5895 " == boost::fusion::at_c<1>(iiii).second;", 5896 Style); 5897 5898 Style.ColumnLimit = 60; 5899 verifyFormat("zzzzzzzzzzzzz\n" 5900 " = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 5901 " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);", 5902 Style); 5903 5904 // Forced by comments. 5905 Style.ColumnLimit = 80; 5906 verifyFormat( 5907 "unsigned ContentSize\n" 5908 " = sizeof(int16_t) // DWARF ARange version number\n" 5909 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 5910 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 5911 " + sizeof(int8_t); // Segment Size (in bytes)", 5912 Style); 5913 5914 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 5915 verifyFormat( 5916 "unsigned ContentSize =\n" 5917 " sizeof(int16_t) // DWARF ARange version number\n" 5918 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 5919 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 5920 " + sizeof(int8_t); // Segment Size (in bytes)", 5921 Style); 5922 5923 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 5924 verifyFormat( 5925 "unsigned ContentSize =\n" 5926 " sizeof(int16_t) // DWARF ARange version number\n" 5927 " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" 5928 " + sizeof(int8_t) // Pointer Size (in bytes)\n" 5929 " + sizeof(int8_t); // Segment Size (in bytes)", 5930 Style); 5931 } 5932 5933 TEST_F(FormatTest, EnforcedOperatorWraps) { 5934 // Here we'd like to wrap after the || operators, but a comment is forcing an 5935 // earlier wrap. 5936 verifyFormat("bool x = aaaaa //\n" 5937 " || bbbbb\n" 5938 " //\n" 5939 " || cccc;"); 5940 } 5941 5942 TEST_F(FormatTest, NoOperandAlignment) { 5943 FormatStyle Style = getLLVMStyle(); 5944 Style.AlignOperands = FormatStyle::OAS_DontAlign; 5945 verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n" 5946 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 5947 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 5948 Style); 5949 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 5950 verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5951 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5952 " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5953 " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5954 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 5955 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 5956 " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5957 " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5958 " > ccccccccccccccccccccccccccccccccccccccccc;", 5959 Style); 5960 5961 verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5962 " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 5963 " + cc;", 5964 Style); 5965 verifyFormat("int a = aa\n" 5966 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" 5967 " * cccccccccccccccccccccccccccccccccccc;\n", 5968 Style); 5969 5970 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 5971 verifyFormat("return (a > b\n" 5972 " // comment1\n" 5973 " // comment2\n" 5974 " || c);", 5975 Style); 5976 } 5977 5978 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) { 5979 FormatStyle Style = getLLVMStyle(); 5980 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 5981 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 5982 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 5983 " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 5984 Style); 5985 } 5986 5987 TEST_F(FormatTest, AllowBinPackingInsideArguments) { 5988 FormatStyle Style = getLLVMStyle(); 5989 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; 5990 Style.BinPackArguments = false; 5991 Style.ColumnLimit = 40; 5992 verifyFormat("void test() {\n" 5993 " someFunction(\n" 5994 " this + argument + is + quite\n" 5995 " + long + so + it + gets + wrapped\n" 5996 " + but + remains + bin - packed);\n" 5997 "}", 5998 Style); 5999 verifyFormat("void test() {\n" 6000 " someFunction(arg1,\n" 6001 " this + argument + is\n" 6002 " + quite + long + so\n" 6003 " + it + gets + wrapped\n" 6004 " + but + remains + bin\n" 6005 " - packed,\n" 6006 " arg3);\n" 6007 "}", 6008 Style); 6009 verifyFormat("void test() {\n" 6010 " someFunction(\n" 6011 " arg1,\n" 6012 " this + argument + has\n" 6013 " + anotherFunc(nested,\n" 6014 " calls + whose\n" 6015 " + arguments\n" 6016 " + are + also\n" 6017 " + wrapped,\n" 6018 " in + addition)\n" 6019 " + to + being + bin - packed,\n" 6020 " arg3);\n" 6021 "}", 6022 Style); 6023 6024 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 6025 verifyFormat("void test() {\n" 6026 " someFunction(\n" 6027 " arg1,\n" 6028 " this + argument + has +\n" 6029 " anotherFunc(nested,\n" 6030 " calls + whose +\n" 6031 " arguments +\n" 6032 " are + also +\n" 6033 " wrapped,\n" 6034 " in + addition) +\n" 6035 " to + being + bin - packed,\n" 6036 " arg3);\n" 6037 "}", 6038 Style); 6039 } 6040 6041 TEST_F(FormatTest, ConstructorInitializers) { 6042 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}"); 6043 verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}", 6044 getLLVMStyleWithColumns(45)); 6045 verifyFormat("Constructor()\n" 6046 " : Inttializer(FitsOnTheLine) {}", 6047 getLLVMStyleWithColumns(44)); 6048 verifyFormat("Constructor()\n" 6049 " : Inttializer(FitsOnTheLine) {}", 6050 getLLVMStyleWithColumns(43)); 6051 6052 verifyFormat("template <typename T>\n" 6053 "Constructor() : Initializer(FitsOnTheLine) {}", 6054 getLLVMStyleWithColumns(45)); 6055 6056 verifyFormat( 6057 "SomeClass::Constructor()\n" 6058 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}"); 6059 6060 verifyFormat( 6061 "SomeClass::Constructor()\n" 6062 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6063 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}"); 6064 verifyFormat( 6065 "SomeClass::Constructor()\n" 6066 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6067 " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}"); 6068 verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6069 " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 6070 " : aaaaaaaaaa(aaaaaa) {}"); 6071 6072 verifyFormat("Constructor()\n" 6073 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6074 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6075 " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6076 " aaaaaaaaaaaaaaaaaaaaaaa() {}"); 6077 6078 verifyFormat("Constructor()\n" 6079 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6080 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 6081 6082 verifyFormat("Constructor(int Parameter = 0)\n" 6083 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n" 6084 " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}"); 6085 verifyFormat("Constructor()\n" 6086 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n" 6087 "}", 6088 getLLVMStyleWithColumns(60)); 6089 verifyFormat("Constructor()\n" 6090 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6091 " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}"); 6092 6093 // Here a line could be saved by splitting the second initializer onto two 6094 // lines, but that is not desirable. 6095 verifyFormat("Constructor()\n" 6096 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n" 6097 " aaaaaaaaaaa(aaaaaaaaaaa),\n" 6098 " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 6099 6100 FormatStyle OnePerLine = getLLVMStyle(); 6101 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_Never; 6102 verifyFormat("MyClass::MyClass()\n" 6103 " : a(a),\n" 6104 " b(b),\n" 6105 " c(c) {}", 6106 OnePerLine); 6107 verifyFormat("MyClass::MyClass()\n" 6108 " : a(a), // comment\n" 6109 " b(b),\n" 6110 " c(c) {}", 6111 OnePerLine); 6112 verifyFormat("MyClass::MyClass(int a)\n" 6113 " : b(a), // comment\n" 6114 " c(a + 1) { // lined up\n" 6115 "}", 6116 OnePerLine); 6117 verifyFormat("Constructor()\n" 6118 " : a(b, b, b) {}", 6119 OnePerLine); 6120 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6121 OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false; 6122 verifyFormat("SomeClass::Constructor()\n" 6123 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6124 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6125 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6126 OnePerLine); 6127 verifyFormat("SomeClass::Constructor()\n" 6128 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n" 6129 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6130 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6131 OnePerLine); 6132 verifyFormat("MyClass::MyClass(int var)\n" 6133 " : some_var_(var), // 4 space indent\n" 6134 " some_other_var_(var + 1) { // lined up\n" 6135 "}", 6136 OnePerLine); 6137 verifyFormat("Constructor()\n" 6138 " : aaaaa(aaaaaa),\n" 6139 " aaaaa(aaaaaa),\n" 6140 " aaaaa(aaaaaa),\n" 6141 " aaaaa(aaaaaa),\n" 6142 " aaaaa(aaaaaa) {}", 6143 OnePerLine); 6144 verifyFormat("Constructor()\n" 6145 " : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n" 6146 " aaaaaaaaaaaaaaaaaaaaaa) {}", 6147 OnePerLine); 6148 OnePerLine.BinPackParameters = false; 6149 verifyFormat( 6150 "Constructor()\n" 6151 " : aaaaaaaaaaaaaaaaaaaaaaaa(\n" 6152 " aaaaaaaaaaa().aaa(),\n" 6153 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6154 OnePerLine); 6155 OnePerLine.ColumnLimit = 60; 6156 verifyFormat("Constructor()\n" 6157 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6158 " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}", 6159 OnePerLine); 6160 6161 EXPECT_EQ("Constructor()\n" 6162 " : // Comment forcing unwanted break.\n" 6163 " aaaa(aaaa) {}", 6164 format("Constructor() :\n" 6165 " // Comment forcing unwanted break.\n" 6166 " aaaa(aaaa) {}")); 6167 } 6168 6169 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) { 6170 FormatStyle Style = getLLVMStyle(); 6171 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6172 Style.ColumnLimit = 60; 6173 Style.BinPackParameters = false; 6174 6175 for (int i = 0; i < 4; ++i) { 6176 // Test all combinations of parameters that should not have an effect. 6177 Style.AllowAllParametersOfDeclarationOnNextLine = i & 1; 6178 Style.AllowAllArgumentsOnNextLine = i & 2; 6179 6180 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6181 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6182 verifyFormat("Constructor()\n" 6183 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6184 Style); 6185 verifyFormat("Constructor() : a(a), b(b) {}", Style); 6186 6187 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6188 verifyFormat("Constructor()\n" 6189 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6190 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6191 Style); 6192 verifyFormat("Constructor() : a(a), b(b) {}", Style); 6193 6194 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 6195 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6196 verifyFormat("Constructor()\n" 6197 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6198 Style); 6199 6200 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6201 verifyFormat("Constructor()\n" 6202 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6203 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6204 Style); 6205 6206 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6207 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6208 verifyFormat("Constructor() :\n" 6209 " aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6210 Style); 6211 6212 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6213 verifyFormat("Constructor() :\n" 6214 " aaaaaaaaaaaaaaaaaa(a),\n" 6215 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6216 Style); 6217 } 6218 6219 // Test interactions between AllowAllParametersOfDeclarationOnNextLine and 6220 // AllowAllConstructorInitializersOnNextLine in all 6221 // BreakConstructorInitializers modes 6222 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 6223 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6224 verifyFormat("SomeClassWithALongName::Constructor(\n" 6225 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n" 6226 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6227 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6228 Style); 6229 6230 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6231 verifyFormat("SomeClassWithALongName::Constructor(\n" 6232 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6233 " int bbbbbbbbbbbbb,\n" 6234 " int cccccccccccccccc)\n" 6235 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6236 Style); 6237 6238 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6239 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6240 verifyFormat("SomeClassWithALongName::Constructor(\n" 6241 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6242 " int bbbbbbbbbbbbb)\n" 6243 " : aaaaaaaaaaaaaaaaaaaa(a)\n" 6244 " , bbbbbbbbbbbbbbbbbbbbb(b) {}", 6245 Style); 6246 6247 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 6248 6249 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6250 verifyFormat("SomeClassWithALongName::Constructor(\n" 6251 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n" 6252 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6253 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6254 Style); 6255 6256 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6257 verifyFormat("SomeClassWithALongName::Constructor(\n" 6258 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6259 " int bbbbbbbbbbbbb,\n" 6260 " int cccccccccccccccc)\n" 6261 " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6262 Style); 6263 6264 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6265 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6266 verifyFormat("SomeClassWithALongName::Constructor(\n" 6267 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6268 " int bbbbbbbbbbbbb)\n" 6269 " : aaaaaaaaaaaaaaaaaaaa(a),\n" 6270 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6271 Style); 6272 6273 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6274 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6275 verifyFormat("SomeClassWithALongName::Constructor(\n" 6276 " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n" 6277 " aaaaaaaaaaaaaaaaaaaa(a),\n" 6278 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6279 Style); 6280 6281 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6282 verifyFormat("SomeClassWithALongName::Constructor(\n" 6283 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6284 " int bbbbbbbbbbbbb,\n" 6285 " int cccccccccccccccc) :\n" 6286 " aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", 6287 Style); 6288 6289 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6290 Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6291 verifyFormat("SomeClassWithALongName::Constructor(\n" 6292 " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" 6293 " int bbbbbbbbbbbbb) :\n" 6294 " aaaaaaaaaaaaaaaaaaaa(a),\n" 6295 " bbbbbbbbbbbbbbbbbbbbb(b) {}", 6296 Style); 6297 } 6298 6299 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) { 6300 FormatStyle Style = getLLVMStyle(); 6301 Style.ColumnLimit = 60; 6302 Style.BinPackArguments = false; 6303 for (int i = 0; i < 4; ++i) { 6304 // Test all combinations of parameters that should not have an effect. 6305 Style.AllowAllParametersOfDeclarationOnNextLine = i & 1; 6306 Style.PackConstructorInitializers = 6307 i & 2 ? FormatStyle::PCIS_BinPack : FormatStyle::PCIS_Never; 6308 6309 Style.AllowAllArgumentsOnNextLine = true; 6310 verifyFormat("void foo() {\n" 6311 " FunctionCallWithReallyLongName(\n" 6312 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n" 6313 "}", 6314 Style); 6315 Style.AllowAllArgumentsOnNextLine = false; 6316 verifyFormat("void foo() {\n" 6317 " FunctionCallWithReallyLongName(\n" 6318 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6319 " bbbbbbbbbbbb);\n" 6320 "}", 6321 Style); 6322 6323 Style.AllowAllArgumentsOnNextLine = true; 6324 verifyFormat("void foo() {\n" 6325 " auto VariableWithReallyLongName = {\n" 6326 " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n" 6327 "}", 6328 Style); 6329 Style.AllowAllArgumentsOnNextLine = false; 6330 verifyFormat("void foo() {\n" 6331 " auto VariableWithReallyLongName = {\n" 6332 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6333 " bbbbbbbbbbbb};\n" 6334 "}", 6335 Style); 6336 } 6337 6338 // This parameter should not affect declarations. 6339 Style.BinPackParameters = false; 6340 Style.AllowAllArgumentsOnNextLine = false; 6341 Style.AllowAllParametersOfDeclarationOnNextLine = true; 6342 verifyFormat("void FunctionCallWithReallyLongName(\n" 6343 " int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);", 6344 Style); 6345 Style.AllowAllParametersOfDeclarationOnNextLine = false; 6346 verifyFormat("void FunctionCallWithReallyLongName(\n" 6347 " int aaaaaaaaaaaaaaaaaaaaaaa,\n" 6348 " int bbbbbbbbbbbb);", 6349 Style); 6350 } 6351 6352 TEST_F(FormatTest, AllowAllArgumentsOnNextLineDontAlign) { 6353 // Check that AllowAllArgumentsOnNextLine is respected for both BAS_DontAlign 6354 // and BAS_Align. 6355 auto Style = getLLVMStyle(); 6356 Style.ColumnLimit = 35; 6357 StringRef Input = "functionCall(paramA, paramB, paramC);\n" 6358 "void functionDecl(int A, int B, int C);"; 6359 Style.AllowAllArgumentsOnNextLine = false; 6360 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6361 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6362 " paramC);\n" 6363 "void functionDecl(int A, int B,\n" 6364 " int C);"), 6365 format(Input, Style)); 6366 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 6367 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6368 " paramC);\n" 6369 "void functionDecl(int A, int B,\n" 6370 " int C);"), 6371 format(Input, Style)); 6372 // However, BAS_AlwaysBreak should take precedence over 6373 // AllowAllArgumentsOnNextLine. 6374 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 6375 EXPECT_EQ(StringRef("functionCall(\n" 6376 " paramA, paramB, paramC);\n" 6377 "void functionDecl(\n" 6378 " int A, int B, int C);"), 6379 format(Input, Style)); 6380 6381 // When AllowAllArgumentsOnNextLine is set, we prefer breaking before the 6382 // first argument. 6383 Style.AllowAllArgumentsOnNextLine = true; 6384 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 6385 EXPECT_EQ(StringRef("functionCall(\n" 6386 " paramA, paramB, paramC);\n" 6387 "void functionDecl(\n" 6388 " int A, int B, int C);"), 6389 format(Input, Style)); 6390 // It wouldn't fit on one line with aligned parameters so this setting 6391 // doesn't change anything for BAS_Align. 6392 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 6393 EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n" 6394 " paramC);\n" 6395 "void functionDecl(int A, int B,\n" 6396 " int C);"), 6397 format(Input, Style)); 6398 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 6399 EXPECT_EQ(StringRef("functionCall(\n" 6400 " paramA, paramB, paramC);\n" 6401 "void functionDecl(\n" 6402 " int A, int B, int C);"), 6403 format(Input, Style)); 6404 } 6405 6406 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) { 6407 FormatStyle Style = getLLVMStyle(); 6408 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 6409 6410 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}"); 6411 verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}", 6412 getStyleWithColumns(Style, 45)); 6413 verifyFormat("Constructor() :\n" 6414 " Initializer(FitsOnTheLine) {}", 6415 getStyleWithColumns(Style, 44)); 6416 verifyFormat("Constructor() :\n" 6417 " Initializer(FitsOnTheLine) {}", 6418 getStyleWithColumns(Style, 43)); 6419 6420 verifyFormat("template <typename T>\n" 6421 "Constructor() : Initializer(FitsOnTheLine) {}", 6422 getStyleWithColumns(Style, 50)); 6423 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6424 verifyFormat( 6425 "SomeClass::Constructor() :\n" 6426 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 6427 Style); 6428 6429 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 6430 verifyFormat( 6431 "SomeClass::Constructor() :\n" 6432 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 6433 Style); 6434 6435 verifyFormat( 6436 "SomeClass::Constructor() :\n" 6437 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6438 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6439 Style); 6440 verifyFormat( 6441 "SomeClass::Constructor() :\n" 6442 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6443 " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", 6444 Style); 6445 verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6446 " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 6447 " aaaaaaaaaa(aaaaaa) {}", 6448 Style); 6449 6450 verifyFormat("Constructor() :\n" 6451 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6452 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6453 " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 6454 " aaaaaaaaaaaaaaaaaaaaaaa() {}", 6455 Style); 6456 6457 verifyFormat("Constructor() :\n" 6458 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6459 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6460 Style); 6461 6462 verifyFormat("Constructor(int Parameter = 0) :\n" 6463 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n" 6464 " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}", 6465 Style); 6466 verifyFormat("Constructor() :\n" 6467 " aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n" 6468 "}", 6469 getStyleWithColumns(Style, 60)); 6470 verifyFormat("Constructor() :\n" 6471 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6472 " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}", 6473 Style); 6474 6475 // Here a line could be saved by splitting the second initializer onto two 6476 // lines, but that is not desirable. 6477 verifyFormat("Constructor() :\n" 6478 " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n" 6479 " aaaaaaaaaaa(aaaaaaaaaaa),\n" 6480 " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6481 Style); 6482 6483 FormatStyle OnePerLine = Style; 6484 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine; 6485 verifyFormat("SomeClass::Constructor() :\n" 6486 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6487 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6488 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6489 OnePerLine); 6490 verifyFormat("SomeClass::Constructor() :\n" 6491 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n" 6492 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 6493 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 6494 OnePerLine); 6495 verifyFormat("MyClass::MyClass(int var) :\n" 6496 " some_var_(var), // 4 space indent\n" 6497 " some_other_var_(var + 1) { // lined up\n" 6498 "}", 6499 OnePerLine); 6500 verifyFormat("Constructor() :\n" 6501 " aaaaa(aaaaaa),\n" 6502 " aaaaa(aaaaaa),\n" 6503 " aaaaa(aaaaaa),\n" 6504 " aaaaa(aaaaaa),\n" 6505 " aaaaa(aaaaaa) {}", 6506 OnePerLine); 6507 verifyFormat("Constructor() :\n" 6508 " aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n" 6509 " aaaaaaaaaaaaaaaaaaaaaa) {}", 6510 OnePerLine); 6511 OnePerLine.BinPackParameters = false; 6512 verifyFormat("Constructor() :\n" 6513 " aaaaaaaaaaaaaaaaaaaaaaaa(\n" 6514 " aaaaaaaaaaa().aaa(),\n" 6515 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6516 OnePerLine); 6517 OnePerLine.ColumnLimit = 60; 6518 verifyFormat("Constructor() :\n" 6519 " aaaaaaaaaaaaaaaaaaaa(a),\n" 6520 " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}", 6521 OnePerLine); 6522 6523 EXPECT_EQ("Constructor() :\n" 6524 " // Comment forcing unwanted break.\n" 6525 " aaaa(aaaa) {}", 6526 format("Constructor() :\n" 6527 " // Comment forcing unwanted break.\n" 6528 " aaaa(aaaa) {}", 6529 Style)); 6530 6531 Style.ColumnLimit = 0; 6532 verifyFormat("SomeClass::Constructor() :\n" 6533 " a(a) {}", 6534 Style); 6535 verifyFormat("SomeClass::Constructor() noexcept :\n" 6536 " a(a) {}", 6537 Style); 6538 verifyFormat("SomeClass::Constructor() :\n" 6539 " a(a), b(b), c(c) {}", 6540 Style); 6541 verifyFormat("SomeClass::Constructor() :\n" 6542 " a(a) {\n" 6543 " foo();\n" 6544 " bar();\n" 6545 "}", 6546 Style); 6547 6548 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 6549 verifyFormat("SomeClass::Constructor() :\n" 6550 " a(a), b(b), c(c) {\n" 6551 "}", 6552 Style); 6553 verifyFormat("SomeClass::Constructor() :\n" 6554 " a(a) {\n" 6555 "}", 6556 Style); 6557 6558 Style.ColumnLimit = 80; 6559 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 6560 Style.ConstructorInitializerIndentWidth = 2; 6561 verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style); 6562 verifyFormat("SomeClass::Constructor() :\n" 6563 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6564 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}", 6565 Style); 6566 6567 // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as 6568 // well 6569 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 6570 verifyFormat( 6571 "class SomeClass\n" 6572 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6573 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 6574 Style); 6575 Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma; 6576 verifyFormat( 6577 "class SomeClass\n" 6578 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6579 " , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 6580 Style); 6581 Style.BreakInheritanceList = FormatStyle::BILS_AfterColon; 6582 verifyFormat( 6583 "class SomeClass :\n" 6584 " public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6585 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 6586 Style); 6587 Style.BreakInheritanceList = FormatStyle::BILS_AfterComma; 6588 verifyFormat( 6589 "class SomeClass\n" 6590 " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6591 " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", 6592 Style); 6593 } 6594 6595 #ifndef EXPENSIVE_CHECKS 6596 // Expensive checks enables libstdc++ checking which includes validating the 6597 // state of ranges used in std::priority_queue - this blows out the 6598 // runtime/scalability of the function and makes this test unacceptably slow. 6599 TEST_F(FormatTest, MemoizationTests) { 6600 // This breaks if the memoization lookup does not take \c Indent and 6601 // \c LastSpace into account. 6602 verifyFormat( 6603 "extern CFRunLoopTimerRef\n" 6604 "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n" 6605 " CFTimeInterval interval, CFOptionFlags flags,\n" 6606 " CFIndex order, CFRunLoopTimerCallBack callout,\n" 6607 " CFRunLoopTimerContext *context) {}"); 6608 6609 // Deep nesting somewhat works around our memoization. 6610 verifyFormat( 6611 "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 6612 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 6613 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 6614 " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" 6615 " aaaaa())))))))))))))))))))))))))))))))))))))));", 6616 getLLVMStyleWithColumns(65)); 6617 verifyFormat( 6618 "aaaaa(\n" 6619 " aaaaa,\n" 6620 " aaaaa(\n" 6621 " aaaaa,\n" 6622 " aaaaa(\n" 6623 " aaaaa,\n" 6624 " aaaaa(\n" 6625 " aaaaa,\n" 6626 " aaaaa(\n" 6627 " aaaaa,\n" 6628 " aaaaa(\n" 6629 " aaaaa,\n" 6630 " aaaaa(\n" 6631 " aaaaa,\n" 6632 " aaaaa(\n" 6633 " aaaaa,\n" 6634 " aaaaa(\n" 6635 " aaaaa,\n" 6636 " aaaaa(\n" 6637 " aaaaa,\n" 6638 " aaaaa(\n" 6639 " aaaaa,\n" 6640 " aaaaa(\n" 6641 " aaaaa,\n" 6642 " aaaaa))))))))))));", 6643 getLLVMStyleWithColumns(65)); 6644 verifyFormat( 6645 "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" 6646 " a),\n" 6647 " a),\n" 6648 " a),\n" 6649 " a),\n" 6650 " a),\n" 6651 " a),\n" 6652 " a),\n" 6653 " a),\n" 6654 " a),\n" 6655 " a),\n" 6656 " a),\n" 6657 " a),\n" 6658 " a),\n" 6659 " a),\n" 6660 " a),\n" 6661 " a),\n" 6662 " a)", 6663 getLLVMStyleWithColumns(65)); 6664 6665 // This test takes VERY long when memoization is broken. 6666 FormatStyle OnePerLine = getLLVMStyle(); 6667 OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 6668 OnePerLine.BinPackParameters = false; 6669 std::string input = "Constructor()\n" 6670 " : aaaa(a,\n"; 6671 for (unsigned i = 0, e = 80; i != e; ++i) { 6672 input += " a,\n"; 6673 } 6674 input += " a) {}"; 6675 verifyFormat(input, OnePerLine); 6676 } 6677 #endif 6678 6679 TEST_F(FormatTest, BreaksAsHighAsPossible) { 6680 verifyFormat( 6681 "void f() {\n" 6682 " if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n" 6683 " (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n" 6684 " f();\n" 6685 "}"); 6686 verifyFormat("if (Intervals[i].getRange().getFirst() <\n" 6687 " Intervals[i - 1].getRange().getLast()) {\n}"); 6688 } 6689 6690 TEST_F(FormatTest, BreaksFunctionDeclarations) { 6691 // Principially, we break function declarations in a certain order: 6692 // 1) break amongst arguments. 6693 verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n" 6694 " Cccccccccccccc cccccccccccccc);"); 6695 verifyFormat("template <class TemplateIt>\n" 6696 "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n" 6697 " TemplateIt *stop) {}"); 6698 6699 // 2) break after return type. 6700 verifyFormat( 6701 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6702 "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);", 6703 getGoogleStyle()); 6704 6705 // 3) break after (. 6706 verifyFormat( 6707 "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n" 6708 " Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);", 6709 getGoogleStyle()); 6710 6711 // 4) break before after nested name specifiers. 6712 verifyFormat( 6713 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6714 "SomeClasssssssssssssssssssssssssssssssssssssss::\n" 6715 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);", 6716 getGoogleStyle()); 6717 6718 // However, there are exceptions, if a sufficient amount of lines can be 6719 // saved. 6720 // FIXME: The precise cut-offs wrt. the number of saved lines might need some 6721 // more adjusting. 6722 verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n" 6723 " Cccccccccccccc cccccccccc,\n" 6724 " Cccccccccccccc cccccccccc,\n" 6725 " Cccccccccccccc cccccccccc,\n" 6726 " Cccccccccccccc cccccccccc);"); 6727 verifyFormat( 6728 "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6729 "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 6730 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 6731 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);", 6732 getGoogleStyle()); 6733 verifyFormat( 6734 "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n" 6735 " Cccccccccccccc cccccccccc,\n" 6736 " Cccccccccccccc cccccccccc,\n" 6737 " Cccccccccccccc cccccccccc,\n" 6738 " Cccccccccccccc cccccccccc,\n" 6739 " Cccccccccccccc cccccccccc,\n" 6740 " Cccccccccccccc cccccccccc);"); 6741 verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 6742 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 6743 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 6744 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" 6745 " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);"); 6746 6747 // Break after multi-line parameters. 6748 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6749 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6750 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6751 " bbbb bbbb);"); 6752 verifyFormat("void SomeLoooooooooooongFunction(\n" 6753 " std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n" 6754 " aaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6755 " int bbbbbbbbbbbbb);"); 6756 6757 // Treat overloaded operators like other functions. 6758 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 6759 "operator>(const SomeLoooooooooooooooooooooooooogType &other);"); 6760 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 6761 "operator>>(const SomeLooooooooooooooooooooooooogType &other);"); 6762 verifyFormat("SomeLoooooooooooooooooooooooooogType\n" 6763 "operator<<(const SomeLooooooooooooooooooooooooogType &other);"); 6764 verifyGoogleFormat( 6765 "SomeLoooooooooooooooooooooooooooooogType operator>>(\n" 6766 " const SomeLooooooooogType &a, const SomeLooooooooogType &b);"); 6767 verifyGoogleFormat( 6768 "SomeLoooooooooooooooooooooooooooooogType operator<<(\n" 6769 " const SomeLooooooooogType &a, const SomeLooooooooogType &b);"); 6770 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6771 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);"); 6772 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n" 6773 "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);"); 6774 verifyGoogleFormat( 6775 "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n" 6776 "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6777 " bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}"); 6778 verifyGoogleFormat("template <typename T>\n" 6779 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6780 "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n" 6781 " aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);"); 6782 6783 FormatStyle Style = getLLVMStyle(); 6784 Style.PointerAlignment = FormatStyle::PAS_Left; 6785 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6786 " aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}", 6787 Style); 6788 verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n" 6789 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 6790 Style); 6791 } 6792 6793 TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) { 6794 // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516: 6795 // Prefer keeping `::` followed by `operator` together. 6796 EXPECT_EQ("const aaaa::bbbbbbb &\n" 6797 "ccccccccc::operator++() {\n" 6798 " stuff();\n" 6799 "}", 6800 format("const aaaa::bbbbbbb\n" 6801 "&ccccccccc::operator++() { stuff(); }", 6802 getLLVMStyleWithColumns(40))); 6803 } 6804 6805 TEST_F(FormatTest, TrailingReturnType) { 6806 verifyFormat("auto foo() -> int;\n"); 6807 // correct trailing return type spacing 6808 verifyFormat("auto operator->() -> int;\n"); 6809 verifyFormat("auto operator++(int) -> int;\n"); 6810 6811 verifyFormat("struct S {\n" 6812 " auto bar() const -> int;\n" 6813 "};"); 6814 verifyFormat("template <size_t Order, typename T>\n" 6815 "auto load_img(const std::string &filename)\n" 6816 " -> alias::tensor<Order, T, mem::tag::cpu> {}"); 6817 verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n" 6818 " -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}"); 6819 verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}"); 6820 verifyFormat("template <typename T>\n" 6821 "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n" 6822 " -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());"); 6823 6824 // Not trailing return types. 6825 verifyFormat("void f() { auto a = b->c(); }"); 6826 verifyFormat("auto a = p->foo();"); 6827 verifyFormat("int a = p->foo();"); 6828 verifyFormat("auto lmbd = [] NOEXCEPT -> int { return 0; };"); 6829 } 6830 6831 TEST_F(FormatTest, DeductionGuides) { 6832 verifyFormat("template <class T> A(const T &, const T &) -> A<T &>;"); 6833 verifyFormat("template <class T> explicit A(T &, T &&) -> A<T>;"); 6834 verifyFormat("template <class... Ts> S(Ts...) -> S<Ts...>;"); 6835 verifyFormat( 6836 "template <class... T>\n" 6837 "array(T &&...t) -> array<std::common_type_t<T...>, sizeof...(T)>;"); 6838 verifyFormat("template <class T> A() -> A<decltype(p->foo<3>())>;"); 6839 verifyFormat("template <class T> A() -> A<decltype(foo<traits<1>>)>;"); 6840 verifyFormat("template <class T> A() -> A<sizeof(p->foo<1>)>;"); 6841 verifyFormat("template <class T> A() -> A<(3 < 2)>;"); 6842 verifyFormat("template <class T> A() -> A<((3) < (2))>;"); 6843 verifyFormat("template <class T> x() -> x<1>;"); 6844 verifyFormat("template <class T> explicit x(T &) -> x<1>;"); 6845 6846 // Ensure not deduction guides. 6847 verifyFormat("c()->f<int>();"); 6848 verifyFormat("x()->foo<1>;"); 6849 verifyFormat("x = p->foo<3>();"); 6850 verifyFormat("x()->x<1>();"); 6851 verifyFormat("x()->x<1>;"); 6852 } 6853 6854 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) { 6855 // Avoid breaking before trailing 'const' or other trailing annotations, if 6856 // they are not function-like. 6857 FormatStyle Style = getGoogleStyle(); 6858 Style.ColumnLimit = 47; 6859 verifyFormat("void someLongFunction(\n" 6860 " int someLoooooooooooooongParameter) const {\n}", 6861 getLLVMStyleWithColumns(47)); 6862 verifyFormat("LoooooongReturnType\n" 6863 "someLoooooooongFunction() const {}", 6864 getLLVMStyleWithColumns(47)); 6865 verifyFormat("LoooooongReturnType someLoooooooongFunction()\n" 6866 " const {}", 6867 Style); 6868 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 6869 " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;"); 6870 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 6871 " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;"); 6872 verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" 6873 " aaaaa aaaaaaaaaaaaaaaaaaaa) override final;"); 6874 verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n" 6875 " aaaaaaaaaaa aaaaa) const override;"); 6876 verifyGoogleFormat( 6877 "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 6878 " const override;"); 6879 6880 // Even if the first parameter has to be wrapped. 6881 verifyFormat("void someLongFunction(\n" 6882 " int someLongParameter) const {}", 6883 getLLVMStyleWithColumns(46)); 6884 verifyFormat("void someLongFunction(\n" 6885 " int someLongParameter) const {}", 6886 Style); 6887 verifyFormat("void someLongFunction(\n" 6888 " int someLongParameter) override {}", 6889 Style); 6890 verifyFormat("void someLongFunction(\n" 6891 " int someLongParameter) OVERRIDE {}", 6892 Style); 6893 verifyFormat("void someLongFunction(\n" 6894 " int someLongParameter) final {}", 6895 Style); 6896 verifyFormat("void someLongFunction(\n" 6897 " int someLongParameter) FINAL {}", 6898 Style); 6899 verifyFormat("void someLongFunction(\n" 6900 " int parameter) const override {}", 6901 Style); 6902 6903 Style.BreakBeforeBraces = FormatStyle::BS_Allman; 6904 verifyFormat("void someLongFunction(\n" 6905 " int someLongParameter) const\n" 6906 "{\n" 6907 "}", 6908 Style); 6909 6910 Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 6911 verifyFormat("void someLongFunction(\n" 6912 " int someLongParameter) const\n" 6913 " {\n" 6914 " }", 6915 Style); 6916 6917 // Unless these are unknown annotations. 6918 verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n" 6919 " aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 6920 " LONG_AND_UGLY_ANNOTATION;"); 6921 6922 // Breaking before function-like trailing annotations is fine to keep them 6923 // close to their arguments. 6924 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 6925 " LOCKS_EXCLUDED(aaaaaaaaaaaaa);"); 6926 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n" 6927 " LOCKS_EXCLUDED(aaaaaaaaaaaaa);"); 6928 verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n" 6929 " LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}"); 6930 verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n" 6931 " AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);"); 6932 verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});"); 6933 6934 verifyFormat( 6935 "void aaaaaaaaaaaaaaaaaa()\n" 6936 " __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n" 6937 " aaaaaaaaaaaaaaaaaaaaaaaaa));"); 6938 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6939 " __attribute__((unused));"); 6940 verifyGoogleFormat( 6941 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6942 " GUARDED_BY(aaaaaaaaaaaa);"); 6943 verifyGoogleFormat( 6944 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6945 " GUARDED_BY(aaaaaaaaaaaa);"); 6946 verifyGoogleFormat( 6947 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n" 6948 " aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 6949 verifyGoogleFormat( 6950 "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n" 6951 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 6952 } 6953 6954 TEST_F(FormatTest, FunctionAnnotations) { 6955 verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 6956 "int OldFunction(const string ¶meter) {}"); 6957 verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 6958 "string OldFunction(const string ¶meter) {}"); 6959 verifyFormat("template <typename T>\n" 6960 "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" 6961 "string OldFunction(const string ¶meter) {}"); 6962 6963 // Not function annotations. 6964 verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 6965 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"); 6966 verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n" 6967 " ThisIsATestWithAReallyReallyReallyReallyLongName) {}"); 6968 verifyFormat("MACRO(abc).function() // wrap\n" 6969 " << abc;"); 6970 verifyFormat("MACRO(abc)->function() // wrap\n" 6971 " << abc;"); 6972 verifyFormat("MACRO(abc)::function() // wrap\n" 6973 " << abc;"); 6974 } 6975 6976 TEST_F(FormatTest, BreaksDesireably) { 6977 verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n" 6978 " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n" 6979 " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}"); 6980 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6981 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" 6982 "}"); 6983 6984 verifyFormat( 6985 "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 6986 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); 6987 6988 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6989 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6990 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 6991 6992 verifyFormat( 6993 "aaaaaaaa(aaaaaaaaaaaaa,\n" 6994 " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6995 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n" 6996 " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 6997 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));"); 6998 6999 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 7000 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7001 7002 verifyFormat( 7003 "void f() {\n" 7004 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n" 7005 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 7006 "}"); 7007 verifyFormat( 7008 "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7009 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7010 verifyFormat( 7011 "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7012 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 7013 verifyFormat( 7014 "aaaaaa(aaa,\n" 7015 " new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7016 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7017 " aaaa);"); 7018 verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7019 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7020 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7021 7022 // Indent consistently independent of call expression and unary operator. 7023 verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7024 " dddddddddddddddddddddddddddddd));"); 7025 verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 7026 " dddddddddddddddddddddddddddddd));"); 7027 verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n" 7028 " dddddddddddddddddddddddddddddd));"); 7029 7030 // This test case breaks on an incorrect memoization, i.e. an optimization not 7031 // taking into account the StopAt value. 7032 verifyFormat( 7033 "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7034 " aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7035 " aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n" 7036 " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7037 7038 verifyFormat("{\n {\n {\n" 7039 " Annotation.SpaceRequiredBefore =\n" 7040 " Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n" 7041 " Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n" 7042 " }\n }\n}"); 7043 7044 // Break on an outer level if there was a break on an inner level. 7045 EXPECT_EQ("f(g(h(a, // comment\n" 7046 " b, c),\n" 7047 " d, e),\n" 7048 " x, y);", 7049 format("f(g(h(a, // comment\n" 7050 " b, c), d, e), x, y);")); 7051 7052 // Prefer breaking similar line breaks. 7053 verifyFormat( 7054 "const int kTrackingOptions = NSTrackingMouseMoved |\n" 7055 " NSTrackingMouseEnteredAndExited |\n" 7056 " NSTrackingActiveAlways;"); 7057 } 7058 7059 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) { 7060 FormatStyle NoBinPacking = getGoogleStyle(); 7061 NoBinPacking.BinPackParameters = false; 7062 NoBinPacking.BinPackArguments = true; 7063 verifyFormat("void f() {\n" 7064 " f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n" 7065 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 7066 "}", 7067 NoBinPacking); 7068 verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n" 7069 " int aaaaaaaaaaaaaaaaaaaa,\n" 7070 " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7071 NoBinPacking); 7072 7073 NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false; 7074 verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7075 " vector<int> bbbbbbbbbbbbbbb);", 7076 NoBinPacking); 7077 // FIXME: This behavior difference is probably not wanted. However, currently 7078 // we cannot distinguish BreakBeforeParameter being set because of the wrapped 7079 // template arguments from BreakBeforeParameter being set because of the 7080 // one-per-line formatting. 7081 verifyFormat( 7082 "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n" 7083 " aaaaaaaaaa> aaaaaaaaaa);", 7084 NoBinPacking); 7085 verifyFormat( 7086 "void fffffffffff(\n" 7087 " aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n" 7088 " aaaaaaaaaa);"); 7089 } 7090 7091 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) { 7092 FormatStyle NoBinPacking = getGoogleStyle(); 7093 NoBinPacking.BinPackParameters = false; 7094 NoBinPacking.BinPackArguments = false; 7095 verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n" 7096 " aaaaaaaaaaaaaaaaaaaa,\n" 7097 " aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);", 7098 NoBinPacking); 7099 verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n" 7100 " aaaaaaaaaaaaa,\n" 7101 " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));", 7102 NoBinPacking); 7103 verifyFormat( 7104 "aaaaaaaa(aaaaaaaaaaaaa,\n" 7105 " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7106 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n" 7107 " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7108 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));", 7109 NoBinPacking); 7110 verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n" 7111 " .aaaaaaaaaaaaaaaaaa();", 7112 NoBinPacking); 7113 verifyFormat("void f() {\n" 7114 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7115 " aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n" 7116 "}", 7117 NoBinPacking); 7118 7119 verifyFormat( 7120 "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7121 " aaaaaaaaaaaa,\n" 7122 " aaaaaaaaaaaa);", 7123 NoBinPacking); 7124 verifyFormat( 7125 "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n" 7126 " ddddddddddddddddddddddddddddd),\n" 7127 " test);", 7128 NoBinPacking); 7129 7130 verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n" 7131 " aaaaaaaaaaaaaaaaaaaaaaa,\n" 7132 " aaaaaaaaaaaaaaaaaaaaaaa>\n" 7133 " aaaaaaaaaaaaaaaaaa;", 7134 NoBinPacking); 7135 verifyFormat("a(\"a\"\n" 7136 " \"a\",\n" 7137 " a);"); 7138 7139 NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false; 7140 verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n" 7141 " aaaaaaaaa,\n" 7142 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7143 NoBinPacking); 7144 verifyFormat( 7145 "void f() {\n" 7146 " aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n" 7147 " .aaaaaaa();\n" 7148 "}", 7149 NoBinPacking); 7150 verifyFormat( 7151 "template <class SomeType, class SomeOtherType>\n" 7152 "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}", 7153 NoBinPacking); 7154 } 7155 7156 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) { 7157 FormatStyle Style = getLLVMStyleWithColumns(15); 7158 Style.ExperimentalAutoDetectBinPacking = true; 7159 EXPECT_EQ("aaa(aaaa,\n" 7160 " aaaa,\n" 7161 " aaaa);\n" 7162 "aaa(aaaa,\n" 7163 " aaaa,\n" 7164 " aaaa);", 7165 format("aaa(aaaa,\n" // one-per-line 7166 " aaaa,\n" 7167 " aaaa );\n" 7168 "aaa(aaaa, aaaa, aaaa);", // inconclusive 7169 Style)); 7170 EXPECT_EQ("aaa(aaaa, aaaa,\n" 7171 " aaaa);\n" 7172 "aaa(aaaa, aaaa,\n" 7173 " aaaa);", 7174 format("aaa(aaaa, aaaa,\n" // bin-packed 7175 " aaaa );\n" 7176 "aaa(aaaa, aaaa, aaaa);", // inconclusive 7177 Style)); 7178 } 7179 7180 TEST_F(FormatTest, FormatsBuilderPattern) { 7181 verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n" 7182 " .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n" 7183 " .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n" 7184 " .StartsWith(\".init\", ORDER_INIT)\n" 7185 " .StartsWith(\".fini\", ORDER_FINI)\n" 7186 " .StartsWith(\".hash\", ORDER_HASH)\n" 7187 " .Default(ORDER_TEXT);\n"); 7188 7189 verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n" 7190 " aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();"); 7191 verifyFormat("aaaaaaa->aaaaaaa\n" 7192 " ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7193 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7194 " ->aaaaaaaa(aaaaaaaaaaaaaaa);"); 7195 verifyFormat( 7196 "aaaaaaa->aaaaaaa\n" 7197 " ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7198 " ->aaaaaaaa(aaaaaaaaaaaaaaa);"); 7199 verifyFormat( 7200 "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n" 7201 " aaaaaaaaaaaaaa);"); 7202 verifyFormat( 7203 "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n" 7204 " aaaaaa->aaaaaaaaaaaa()\n" 7205 " ->aaaaaaaaaaaaaaaa(\n" 7206 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7207 " ->aaaaaaaaaaaaaaaaa();"); 7208 verifyGoogleFormat( 7209 "void f() {\n" 7210 " someo->Add((new util::filetools::Handler(dir))\n" 7211 " ->OnEvent1(NewPermanentCallback(\n" 7212 " this, &HandlerHolderClass::EventHandlerCBA))\n" 7213 " ->OnEvent2(NewPermanentCallback(\n" 7214 " this, &HandlerHolderClass::EventHandlerCBB))\n" 7215 " ->OnEvent3(NewPermanentCallback(\n" 7216 " this, &HandlerHolderClass::EventHandlerCBC))\n" 7217 " ->OnEvent5(NewPermanentCallback(\n" 7218 " this, &HandlerHolderClass::EventHandlerCBD))\n" 7219 " ->OnEvent6(NewPermanentCallback(\n" 7220 " this, &HandlerHolderClass::EventHandlerCBE)));\n" 7221 "}"); 7222 7223 verifyFormat( 7224 "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();"); 7225 verifyFormat("aaaaaaaaaaaaaaa()\n" 7226 " .aaaaaaaaaaaaaaa()\n" 7227 " .aaaaaaaaaaaaaaa()\n" 7228 " .aaaaaaaaaaaaaaa()\n" 7229 " .aaaaaaaaaaaaaaa();"); 7230 verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7231 " .aaaaaaaaaaaaaaa()\n" 7232 " .aaaaaaaaaaaaaaa()\n" 7233 " .aaaaaaaaaaaaaaa();"); 7234 verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7235 " .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" 7236 " .aaaaaaaaaaaaaaa();"); 7237 verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n" 7238 " ->aaaaaaaaaaaaaae(0)\n" 7239 " ->aaaaaaaaaaaaaaa();"); 7240 7241 // Don't linewrap after very short segments. 7242 verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7243 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7244 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7245 verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7246 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7247 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7248 verifyFormat("aaa()\n" 7249 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7250 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7251 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 7252 7253 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n" 7254 " .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 7255 " .has<bbbbbbbbbbbbbbbbbbbbb>();"); 7256 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n" 7257 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 7258 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();"); 7259 7260 // Prefer not to break after empty parentheses. 7261 verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n" 7262 " First->LastNewlineOffset);"); 7263 7264 // Prefer not to create "hanging" indents. 7265 verifyFormat( 7266 "return !soooooooooooooome_map\n" 7267 " .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7268 " .second;"); 7269 verifyFormat( 7270 "return aaaaaaaaaaaaaaaa\n" 7271 " .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n" 7272 " .aaaa(aaaaaaaaaaaaaa);"); 7273 // No hanging indent here. 7274 verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n" 7275 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7276 verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n" 7277 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7278 verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n" 7279 " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7280 getLLVMStyleWithColumns(60)); 7281 verifyFormat("aaaaaaaaaaaaaaaaaa\n" 7282 " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n" 7283 " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7284 getLLVMStyleWithColumns(59)); 7285 verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7286 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7287 " .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7288 7289 // Dont break if only closing statements before member call 7290 verifyFormat("test() {\n" 7291 " ([]() -> {\n" 7292 " int b = 32;\n" 7293 " return 3;\n" 7294 " }).foo();\n" 7295 "}"); 7296 verifyFormat("test() {\n" 7297 " (\n" 7298 " []() -> {\n" 7299 " int b = 32;\n" 7300 " return 3;\n" 7301 " },\n" 7302 " foo, bar)\n" 7303 " .foo();\n" 7304 "}"); 7305 verifyFormat("test() {\n" 7306 " ([]() -> {\n" 7307 " int b = 32;\n" 7308 " return 3;\n" 7309 " })\n" 7310 " .foo()\n" 7311 " .bar();\n" 7312 "}"); 7313 verifyFormat("test() {\n" 7314 " ([]() -> {\n" 7315 " int b = 32;\n" 7316 " return 3;\n" 7317 " })\n" 7318 " .foo(\"aaaaaaaaaaaaaaaaa\"\n" 7319 " \"bbbb\");\n" 7320 "}", 7321 getLLVMStyleWithColumns(30)); 7322 } 7323 7324 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) { 7325 verifyFormat( 7326 "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n" 7327 " bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}"); 7328 verifyFormat( 7329 "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n" 7330 " bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}"); 7331 7332 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" 7333 " ccccccccccccccccccccccccc) {\n}"); 7334 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n" 7335 " ccccccccccccccccccccccccc) {\n}"); 7336 7337 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" 7338 " ccccccccccccccccccccccccc) {\n}"); 7339 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n" 7340 " ccccccccccccccccccccccccc) {\n}"); 7341 7342 verifyFormat( 7343 "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n" 7344 " ccccccccccccccccccccccccc) {\n}"); 7345 verifyFormat( 7346 "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n" 7347 " ccccccccccccccccccccccccc) {\n}"); 7348 7349 verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n" 7350 " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n" 7351 " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n" 7352 " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;"); 7353 verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n" 7354 " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n" 7355 " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n" 7356 " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;"); 7357 7358 verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n" 7359 " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n" 7360 " aaaaaaaaaaaaaaa != aa) {\n}"); 7361 verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n" 7362 " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n" 7363 " aaaaaaaaaaaaaaa != aa) {\n}"); 7364 } 7365 7366 TEST_F(FormatTest, BreaksAfterAssignments) { 7367 verifyFormat( 7368 "unsigned Cost =\n" 7369 " TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n" 7370 " SI->getPointerAddressSpaceee());\n"); 7371 verifyFormat( 7372 "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n" 7373 " Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());"); 7374 7375 verifyFormat( 7376 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n" 7377 " aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);"); 7378 verifyFormat("unsigned OriginalStartColumn =\n" 7379 " SourceMgr.getSpellingColumnNumber(\n" 7380 " Current.FormatTok.getStartOfNonWhitespace()) -\n" 7381 " 1;"); 7382 } 7383 7384 TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) { 7385 FormatStyle Style = getLLVMStyle(); 7386 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 7387 " bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;", 7388 Style); 7389 7390 Style.PenaltyBreakAssignment = 20; 7391 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n" 7392 " cccccccccccccccccccccccccc;", 7393 Style); 7394 } 7395 7396 TEST_F(FormatTest, AlignsAfterAssignments) { 7397 verifyFormat( 7398 "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7399 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7400 verifyFormat( 7401 "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7402 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7403 verifyFormat( 7404 "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7405 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7406 verifyFormat( 7407 "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7408 " aaaaaaaaaaaaaaaaaaaaaaaaa);"); 7409 verifyFormat( 7410 "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n" 7411 " aaaaaaaaaaaaaaaaaaaaaaaa +\n" 7412 " aaaaaaaaaaaaaaaaaaaaaaaa;"); 7413 } 7414 7415 TEST_F(FormatTest, AlignsAfterReturn) { 7416 verifyFormat( 7417 "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7418 " aaaaaaaaaaaaaaaaaaaaaaaaa;"); 7419 verifyFormat( 7420 "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7421 " aaaaaaaaaaaaaaaaaaaaaaaaa);"); 7422 verifyFormat( 7423 "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n" 7424 " aaaaaaaaaaaaaaaaaaaaaa();"); 7425 verifyFormat( 7426 "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n" 7427 " aaaaaaaaaaaaaaaaaaaaaa());"); 7428 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7429 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7430 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7431 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n" 7432 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7433 verifyFormat("return\n" 7434 " // true if code is one of a or b.\n" 7435 " code == a || code == b;"); 7436 } 7437 7438 TEST_F(FormatTest, AlignsAfterOpenBracket) { 7439 verifyFormat( 7440 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n" 7441 " aaaaaaaaa aaaaaaa) {}"); 7442 verifyFormat( 7443 "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n" 7444 " aaaaaaaaaaa aaaaaaaaa);"); 7445 verifyFormat( 7446 "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n" 7447 " aaaaaaaaaaaaaaaaaaaaa));"); 7448 FormatStyle Style = getLLVMStyle(); 7449 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 7450 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7451 " aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}", 7452 Style); 7453 verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n" 7454 " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);", 7455 Style); 7456 verifyFormat("SomeLongVariableName->someFunction(\n" 7457 " foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));", 7458 Style); 7459 verifyFormat( 7460 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n" 7461 " aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7462 Style); 7463 verifyFormat( 7464 "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n" 7465 " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7466 Style); 7467 verifyFormat( 7468 "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n" 7469 " aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));", 7470 Style); 7471 7472 verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n" 7473 " ccccccc(aaaaaaaaaaaaaaaaa, //\n" 7474 " b));", 7475 Style); 7476 7477 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 7478 Style.BinPackArguments = false; 7479 Style.BinPackParameters = false; 7480 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7481 " aaaaaaaaaaa aaaaaaaa,\n" 7482 " aaaaaaaaa aaaaaaa,\n" 7483 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", 7484 Style); 7485 verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n" 7486 " aaaaaaaaaaa aaaaaaaaa,\n" 7487 " aaaaaaaaaaa aaaaaaaaa,\n" 7488 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7489 Style); 7490 verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n" 7491 " aaaaaaaaaaaaaaa,\n" 7492 " aaaaaaaaaaaaaaaaaaaaa,\n" 7493 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));", 7494 Style); 7495 verifyFormat( 7496 "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n" 7497 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));", 7498 Style); 7499 verifyFormat( 7500 "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n" 7501 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));", 7502 Style); 7503 verifyFormat( 7504 "aaaaaaaaaaaaaaaaaaaaaaaa(\n" 7505 " aaaaaaaaaaaaaaaaaaaaa(\n" 7506 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n" 7507 " aaaaaaaaaaaaaaaa);", 7508 Style); 7509 verifyFormat( 7510 "aaaaaaaaaaaaaaaaaaaaaaaa(\n" 7511 " aaaaaaaaaaaaaaaaaaaaa(\n" 7512 " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n" 7513 " aaaaaaaaaaaaaaaa);", 7514 Style); 7515 } 7516 7517 TEST_F(FormatTest, ParenthesesAndOperandAlignment) { 7518 FormatStyle Style = getLLVMStyleWithColumns(40); 7519 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 7520 " bbbbbbbbbbbbbbbbbbbbbb);", 7521 Style); 7522 Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; 7523 Style.AlignOperands = FormatStyle::OAS_DontAlign; 7524 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 7525 " bbbbbbbbbbbbbbbbbbbbbb);", 7526 Style); 7527 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 7528 Style.AlignOperands = FormatStyle::OAS_Align; 7529 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 7530 " bbbbbbbbbbbbbbbbbbbbbb);", 7531 Style); 7532 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 7533 Style.AlignOperands = FormatStyle::OAS_DontAlign; 7534 verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" 7535 " bbbbbbbbbbbbbbbbbbbbbb);", 7536 Style); 7537 } 7538 7539 TEST_F(FormatTest, BreaksConditionalExpressions) { 7540 verifyFormat( 7541 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7542 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7543 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7544 verifyFormat( 7545 "aaaa(aaaaaaaaaa, aaaaaaaa,\n" 7546 " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7547 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7548 verifyFormat( 7549 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7550 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7551 verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n" 7552 " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7553 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7554 verifyFormat( 7555 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n" 7556 " : aaaaaaaaaaaaa);"); 7557 verifyFormat( 7558 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7559 " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7560 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7561 " aaaaaaaaaaaaa);"); 7562 verifyFormat( 7563 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7564 " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7565 " aaaaaaaaaaaaa);"); 7566 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7567 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7568 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7569 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7570 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7571 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7572 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7573 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7574 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 7575 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7576 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7577 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7578 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7579 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7580 " ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7581 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7582 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 7583 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7584 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7585 " : aaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7586 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n" 7587 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7588 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7589 " : aaaaaaaaaaaaaaaa;"); 7590 verifyFormat( 7591 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7592 " ? aaaaaaaaaaaaaaa\n" 7593 " : aaaaaaaaaaaaaaa;"); 7594 verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n" 7595 " aaaaaaaaa\n" 7596 " ? b\n" 7597 " : c);"); 7598 verifyFormat("return aaaa == bbbb\n" 7599 " // comment\n" 7600 " ? aaaa\n" 7601 " : bbbb;"); 7602 verifyFormat("unsigned Indent =\n" 7603 " format(TheLine.First,\n" 7604 " IndentForLevel[TheLine.Level] >= 0\n" 7605 " ? IndentForLevel[TheLine.Level]\n" 7606 " : TheLine * 2,\n" 7607 " TheLine.InPPDirective, PreviousEndOfLineColumn);", 7608 getLLVMStyleWithColumns(60)); 7609 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n" 7610 " ? aaaaaaaaaaaaaaa\n" 7611 " : bbbbbbbbbbbbbbb //\n" 7612 " ? ccccccccccccccc\n" 7613 " : ddddddddddddddd;"); 7614 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n" 7615 " ? aaaaaaaaaaaaaaa\n" 7616 " : (bbbbbbbbbbbbbbb //\n" 7617 " ? ccccccccccccccc\n" 7618 " : ddddddddddddddd);"); 7619 verifyFormat( 7620 "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7621 " ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n" 7622 " aaaaaaaaaaaaaaaaaaaaa +\n" 7623 " aaaaaaaaaaaaaaaaaaaaa\n" 7624 " : aaaaaaaaaa;"); 7625 verifyFormat( 7626 "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7627 " : aaaaaaaaaaaaaaaaaaaaaa\n" 7628 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 7629 7630 FormatStyle NoBinPacking = getLLVMStyle(); 7631 NoBinPacking.BinPackArguments = false; 7632 verifyFormat( 7633 "void f() {\n" 7634 " g(aaa,\n" 7635 " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n" 7636 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7637 " ? aaaaaaaaaaaaaaa\n" 7638 " : aaaaaaaaaaaaaaa);\n" 7639 "}", 7640 NoBinPacking); 7641 verifyFormat( 7642 "void f() {\n" 7643 " g(aaa,\n" 7644 " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n" 7645 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7646 " ?: aaaaaaaaaaaaaaa);\n" 7647 "}", 7648 NoBinPacking); 7649 7650 verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n" 7651 " // comment.\n" 7652 " ccccccccccccccccccccccccccccccccccccccc\n" 7653 " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 7654 " : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);"); 7655 7656 // Assignments in conditional expressions. Apparently not uncommon :-(. 7657 verifyFormat("return a != b\n" 7658 " // comment\n" 7659 " ? a = b\n" 7660 " : a = b;"); 7661 verifyFormat("return a != b\n" 7662 " // comment\n" 7663 " ? a = a != b\n" 7664 " // comment\n" 7665 " ? a = b\n" 7666 " : a\n" 7667 " : a;\n"); 7668 verifyFormat("return a != b\n" 7669 " // comment\n" 7670 " ? a\n" 7671 " : a = a != b\n" 7672 " // comment\n" 7673 " ? a = b\n" 7674 " : a;"); 7675 7676 // Chained conditionals 7677 FormatStyle Style = getLLVMStyle(); 7678 Style.ColumnLimit = 70; 7679 Style.AlignOperands = FormatStyle::OAS_Align; 7680 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 7681 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7682 " : 3333333333333333;", 7683 Style); 7684 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 7685 " : bbbbbbbbbb ? 2222222222222222\n" 7686 " : 3333333333333333;", 7687 Style); 7688 verifyFormat("return aaaaaaaaaa ? 1111111111111111\n" 7689 " : bbbbbbbbbbbbbbbb ? 2222222222222222\n" 7690 " : 3333333333333333;", 7691 Style); 7692 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 7693 " : bbbbbbbbbbbbbb ? 222222\n" 7694 " : 333333;", 7695 Style); 7696 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 7697 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7698 " : cccccccccccccc ? 3333333333333333\n" 7699 " : 4444444444444444;", 7700 Style); 7701 verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc)\n" 7702 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7703 " : 3333333333333333;", 7704 Style); 7705 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 7706 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7707 " : (aaa ? bbb : ccc);", 7708 Style); 7709 verifyFormat( 7710 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 7711 " : cccccccccccccccccc)\n" 7712 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7713 " : 3333333333333333;", 7714 Style); 7715 verifyFormat( 7716 "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 7717 " : cccccccccccccccccc)\n" 7718 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7719 " : 3333333333333333;", 7720 Style); 7721 verifyFormat( 7722 "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 7723 " : dddddddddddddddddd)\n" 7724 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7725 " : 3333333333333333;", 7726 Style); 7727 verifyFormat( 7728 "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 7729 " : dddddddddddddddddd)\n" 7730 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7731 " : 3333333333333333;", 7732 Style); 7733 verifyFormat( 7734 "return aaaaaaaaa ? 1111111111111111\n" 7735 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7736 " : a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 7737 " : dddddddddddddddddd)\n", 7738 Style); 7739 verifyFormat( 7740 "return aaaaaaaaaaaaaaaa ? 1111111111111111\n" 7741 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7742 " : (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 7743 " : cccccccccccccccccc);", 7744 Style); 7745 verifyFormat( 7746 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 7747 " : ccccccccccccccc ? dddddddddddddddddd\n" 7748 " : eeeeeeeeeeeeeeeeee)\n" 7749 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7750 " : 3333333333333333;", 7751 Style); 7752 verifyFormat( 7753 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 7754 " : ccccccccccccccc ? dddddddddddddddddd\n" 7755 " : eeeeeeeeeeeeeeeeee)\n" 7756 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7757 " : 3333333333333333;", 7758 Style); 7759 verifyFormat( 7760 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 7761 " : cccccccccccc ? dddddddddddddddddd\n" 7762 " : eeeeeeeeeeeeeeeeee)\n" 7763 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7764 " : 3333333333333333;", 7765 Style); 7766 verifyFormat( 7767 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 7768 " : cccccccccccccccccc\n" 7769 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7770 " : 3333333333333333;", 7771 Style); 7772 verifyFormat( 7773 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 7774 " : cccccccccccccccc ? dddddddddddddddddd\n" 7775 " : eeeeeeeeeeeeeeeeee\n" 7776 " : bbbbbbbbbbbbbb ? 2222222222222222\n" 7777 " : 3333333333333333;", 7778 Style); 7779 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa\n" 7780 " ? (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 7781 " : cccccccccccccccccc ? dddddddddddddddddd\n" 7782 " : eeeeeeeeeeeeeeeeee)\n" 7783 " : bbbbbbbbbbbbbbbbbbb ? 2222222222222222\n" 7784 " : 3333333333333333;", 7785 Style); 7786 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaa\n" 7787 " ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n" 7788 " : cccccccccccccccc ? dddddddddddddddddd\n" 7789 " : eeeeeeeeeeeeeeeeee\n" 7790 " : bbbbbbbbbbbbbbbbbbbbbbb ? 2222222222222222\n" 7791 " : 3333333333333333;", 7792 Style); 7793 7794 Style.AlignOperands = FormatStyle::OAS_DontAlign; 7795 Style.BreakBeforeTernaryOperators = false; 7796 // FIXME: Aligning the question marks is weird given DontAlign. 7797 // Consider disabling this alignment in this case. Also check whether this 7798 // will render the adjustment from https://reviews.llvm.org/D82199 7799 // unnecessary. 7800 verifyFormat("int x = aaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa :\n" 7801 " bbbb ? cccccccccccccccccc :\n" 7802 " ddddd;\n", 7803 Style); 7804 7805 EXPECT_EQ( 7806 "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n" 7807 " /*\n" 7808 " */\n" 7809 " function() {\n" 7810 " try {\n" 7811 " return JJJJJJJJJJJJJJ(\n" 7812 " pppppppppppppppppppppppppppppppppppppppppppppppppp);\n" 7813 " }\n" 7814 " } :\n" 7815 " function() {};", 7816 format( 7817 "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n" 7818 " /*\n" 7819 " */\n" 7820 " function() {\n" 7821 " try {\n" 7822 " return JJJJJJJJJJJJJJ(\n" 7823 " pppppppppppppppppppppppppppppppppppppppppppppppppp);\n" 7824 " }\n" 7825 " } :\n" 7826 " function() {};", 7827 getGoogleStyle(FormatStyle::LK_JavaScript))); 7828 } 7829 7830 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) { 7831 FormatStyle Style = getLLVMStyle(); 7832 Style.BreakBeforeTernaryOperators = false; 7833 Style.ColumnLimit = 70; 7834 verifyFormat( 7835 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 7836 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 7837 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7838 Style); 7839 verifyFormat( 7840 "aaaa(aaaaaaaaaa, aaaaaaaa,\n" 7841 " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 7842 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7843 Style); 7844 verifyFormat( 7845 "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 7846 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7847 Style); 7848 verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n" 7849 " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 7850 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7851 Style); 7852 verifyFormat( 7853 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n" 7854 " aaaaaaaaaaaaa);", 7855 Style); 7856 verifyFormat( 7857 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7858 " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 7859 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7860 " aaaaaaaaaaaaa);", 7861 Style); 7862 verifyFormat( 7863 "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7864 " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7865 " aaaaaaaaaaaaa);", 7866 Style); 7867 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 7868 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7869 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 7870 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7871 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7872 Style); 7873 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7874 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 7875 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7876 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" 7877 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7878 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7879 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7880 Style); 7881 verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 7882 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n" 7883 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 7884 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" 7885 " aaaaaaaaaaaaaaaaaaaaaaaaaaa);", 7886 Style); 7887 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 7888 " aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 7889 " aaaaaaaaaaaaaaaaaaaaaaaaaaa;", 7890 Style); 7891 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n" 7892 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 7893 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" 7894 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 7895 Style); 7896 verifyFormat( 7897 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 7898 " aaaaaaaaaaaaaaa :\n" 7899 " aaaaaaaaaaaaaaa;", 7900 Style); 7901 verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n" 7902 " aaaaaaaaa ?\n" 7903 " b :\n" 7904 " c);", 7905 Style); 7906 verifyFormat("unsigned Indent =\n" 7907 " format(TheLine.First,\n" 7908 " IndentForLevel[TheLine.Level] >= 0 ?\n" 7909 " IndentForLevel[TheLine.Level] :\n" 7910 " TheLine * 2,\n" 7911 " TheLine.InPPDirective, PreviousEndOfLineColumn);", 7912 Style); 7913 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n" 7914 " aaaaaaaaaaaaaaa :\n" 7915 " bbbbbbbbbbbbbbb ? //\n" 7916 " ccccccccccccccc :\n" 7917 " ddddddddddddddd;", 7918 Style); 7919 verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n" 7920 " aaaaaaaaaaaaaaa :\n" 7921 " (bbbbbbbbbbbbbbb ? //\n" 7922 " ccccccccccccccc :\n" 7923 " ddddddddddddddd);", 7924 Style); 7925 verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 7926 " /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n" 7927 " ccccccccccccccccccccccccccc;", 7928 Style); 7929 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" 7930 " aaaaa :\n" 7931 " bbbbbbbbbbbbbbb + cccccccccccccccc;", 7932 Style); 7933 7934 // Chained conditionals 7935 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 7936 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 7937 " 3333333333333333;", 7938 Style); 7939 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 7940 " bbbbbbbbbb ? 2222222222222222 :\n" 7941 " 3333333333333333;", 7942 Style); 7943 verifyFormat("return aaaaaaaaaa ? 1111111111111111 :\n" 7944 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 7945 " 3333333333333333;", 7946 Style); 7947 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 7948 " bbbbbbbbbbbbbbbb ? 222222 :\n" 7949 " 333333;", 7950 Style); 7951 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 7952 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 7953 " cccccccccccccccc ? 3333333333333333 :\n" 7954 " 4444444444444444;", 7955 Style); 7956 verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc) :\n" 7957 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 7958 " 3333333333333333;", 7959 Style); 7960 verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 7961 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 7962 " (aaa ? bbb : ccc);", 7963 Style); 7964 verifyFormat( 7965 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 7966 " cccccccccccccccccc) :\n" 7967 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 7968 " 3333333333333333;", 7969 Style); 7970 verifyFormat( 7971 "return aaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 7972 " cccccccccccccccccc) :\n" 7973 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 7974 " 3333333333333333;", 7975 Style); 7976 verifyFormat( 7977 "return aaaaaaaaa ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 7978 " dddddddddddddddddd) :\n" 7979 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 7980 " 3333333333333333;", 7981 Style); 7982 verifyFormat( 7983 "return aaaaaaaaa ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 7984 " dddddddddddddddddd) :\n" 7985 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 7986 " 3333333333333333;", 7987 Style); 7988 verifyFormat( 7989 "return aaaaaaaaa ? 1111111111111111 :\n" 7990 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 7991 " a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 7992 " dddddddddddddddddd)\n", 7993 Style); 7994 verifyFormat( 7995 "return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n" 7996 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 7997 " (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 7998 " cccccccccccccccccc);", 7999 Style); 8000 verifyFormat( 8001 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8002 " ccccccccccccccccc ? dddddddddddddddddd :\n" 8003 " eeeeeeeeeeeeeeeeee) :\n" 8004 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8005 " 3333333333333333;", 8006 Style); 8007 verifyFormat( 8008 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8009 " ccccccccccccc ? dddddddddddddddddd :\n" 8010 " eeeeeeeeeeeeeeeeee) :\n" 8011 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8012 " 3333333333333333;", 8013 Style); 8014 verifyFormat( 8015 "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8016 " ccccccccccccccccc ? dddddddddddddddddd :\n" 8017 " eeeeeeeeeeeeeeeeee) :\n" 8018 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8019 " 3333333333333333;", 8020 Style); 8021 verifyFormat( 8022 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8023 " cccccccccccccccccc :\n" 8024 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8025 " 3333333333333333;", 8026 Style); 8027 verifyFormat( 8028 "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8029 " cccccccccccccccccc ? dddddddddddddddddd :\n" 8030 " eeeeeeeeeeeeeeeeee :\n" 8031 " bbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8032 " 3333333333333333;", 8033 Style); 8034 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n" 8035 " (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8036 " cccccccccccccccccc ? dddddddddddddddddd :\n" 8037 " eeeeeeeeeeeeeeeeee) :\n" 8038 " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8039 " 3333333333333333;", 8040 Style); 8041 verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n" 8042 " aaaaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n" 8043 " cccccccccccccccccccc ? dddddddddddddddddd :\n" 8044 " eeeeeeeeeeeeeeeeee :\n" 8045 " bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n" 8046 " 3333333333333333;", 8047 Style); 8048 } 8049 8050 TEST_F(FormatTest, DeclarationsOfMultipleVariables) { 8051 verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n" 8052 " aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();"); 8053 verifyFormat("bool a = true, b = false;"); 8054 8055 verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n" 8056 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n" 8057 " bbbbbbbbbbbbbbbbbbbbbbbbb =\n" 8058 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);"); 8059 verifyFormat( 8060 "bool aaaaaaaaaaaaaaaaaaaaa =\n" 8061 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n" 8062 " d = e && f;"); 8063 verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n" 8064 " c = cccccccccccccccccccc, d = dddddddddddddddddddd;"); 8065 verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n" 8066 " *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;"); 8067 verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n" 8068 " ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;"); 8069 8070 FormatStyle Style = getGoogleStyle(); 8071 Style.PointerAlignment = FormatStyle::PAS_Left; 8072 Style.DerivePointerAlignment = false; 8073 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8074 " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n" 8075 " *b = bbbbbbbbbbbbbbbbbbb;", 8076 Style); 8077 verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n" 8078 " *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;", 8079 Style); 8080 verifyFormat("vector<int*> a, b;", Style); 8081 verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style); 8082 } 8083 8084 TEST_F(FormatTest, ConditionalExpressionsInBrackets) { 8085 verifyFormat("arr[foo ? bar : baz];"); 8086 verifyFormat("f()[foo ? bar : baz];"); 8087 verifyFormat("(a + b)[foo ? bar : baz];"); 8088 verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];"); 8089 } 8090 8091 TEST_F(FormatTest, AlignsStringLiterals) { 8092 verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n" 8093 " \"short literal\");"); 8094 verifyFormat( 8095 "looooooooooooooooooooooooongFunction(\n" 8096 " \"short literal\"\n" 8097 " \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");"); 8098 verifyFormat("someFunction(\"Always break between multi-line\"\n" 8099 " \" string literals\",\n" 8100 " and, other, parameters);"); 8101 EXPECT_EQ("fun + \"1243\" /* comment */\n" 8102 " \"5678\";", 8103 format("fun + \"1243\" /* comment */\n" 8104 " \"5678\";", 8105 getLLVMStyleWithColumns(28))); 8106 EXPECT_EQ( 8107 "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 8108 " \"aaaaaaaaaaaaaaaaaaaaa\"\n" 8109 " \"aaaaaaaaaaaaaaaa\";", 8110 format("aaaaaa =" 8111 "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa " 8112 "aaaaaaaaaaaaaaaaaaaaa\" " 8113 "\"aaaaaaaaaaaaaaaa\";")); 8114 verifyFormat("a = a + \"a\"\n" 8115 " \"a\"\n" 8116 " \"a\";"); 8117 verifyFormat("f(\"a\", \"b\"\n" 8118 " \"c\");"); 8119 8120 verifyFormat( 8121 "#define LL_FORMAT \"ll\"\n" 8122 "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n" 8123 " \"d, ddddddddd: %\" LL_FORMAT \"d\");"); 8124 8125 verifyFormat("#define A(X) \\\n" 8126 " \"aaaaa\" #X \"bbbbbb\" \\\n" 8127 " \"ccccc\"", 8128 getLLVMStyleWithColumns(23)); 8129 verifyFormat("#define A \"def\"\n" 8130 "f(\"abc\" A \"ghi\"\n" 8131 " \"jkl\");"); 8132 8133 verifyFormat("f(L\"a\"\n" 8134 " L\"b\");"); 8135 verifyFormat("#define A(X) \\\n" 8136 " L\"aaaaa\" #X L\"bbbbbb\" \\\n" 8137 " L\"ccccc\"", 8138 getLLVMStyleWithColumns(25)); 8139 8140 verifyFormat("f(@\"a\"\n" 8141 " @\"b\");"); 8142 verifyFormat("NSString s = @\"a\"\n" 8143 " @\"b\"\n" 8144 " @\"c\";"); 8145 verifyFormat("NSString s = @\"a\"\n" 8146 " \"b\"\n" 8147 " \"c\";"); 8148 } 8149 8150 TEST_F(FormatTest, ReturnTypeBreakingStyle) { 8151 FormatStyle Style = getLLVMStyle(); 8152 // No declarations or definitions should be moved to own line. 8153 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None; 8154 verifyFormat("class A {\n" 8155 " int f() { return 1; }\n" 8156 " int g();\n" 8157 "};\n" 8158 "int f() { return 1; }\n" 8159 "int g();\n", 8160 Style); 8161 8162 // All declarations and definitions should have the return type moved to its 8163 // own line. 8164 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 8165 Style.TypenameMacros = {"LIST"}; 8166 verifyFormat("SomeType\n" 8167 "funcdecl(LIST(uint64_t));", 8168 Style); 8169 verifyFormat("class E {\n" 8170 " int\n" 8171 " f() {\n" 8172 " return 1;\n" 8173 " }\n" 8174 " int\n" 8175 " g();\n" 8176 "};\n" 8177 "int\n" 8178 "f() {\n" 8179 " return 1;\n" 8180 "}\n" 8181 "int\n" 8182 "g();\n", 8183 Style); 8184 8185 // Top-level definitions, and no kinds of declarations should have the 8186 // return type moved to its own line. 8187 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions; 8188 verifyFormat("class B {\n" 8189 " int f() { return 1; }\n" 8190 " int g();\n" 8191 "};\n" 8192 "int\n" 8193 "f() {\n" 8194 " return 1;\n" 8195 "}\n" 8196 "int g();\n", 8197 Style); 8198 8199 // Top-level definitions and declarations should have the return type moved 8200 // to its own line. 8201 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel; 8202 verifyFormat("class C {\n" 8203 " int f() { return 1; }\n" 8204 " int g();\n" 8205 "};\n" 8206 "int\n" 8207 "f() {\n" 8208 " return 1;\n" 8209 "}\n" 8210 "int\n" 8211 "g();\n", 8212 Style); 8213 8214 // All definitions should have the return type moved to its own line, but no 8215 // kinds of declarations. 8216 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions; 8217 verifyFormat("class D {\n" 8218 " int\n" 8219 " f() {\n" 8220 " return 1;\n" 8221 " }\n" 8222 " int g();\n" 8223 "};\n" 8224 "int\n" 8225 "f() {\n" 8226 " return 1;\n" 8227 "}\n" 8228 "int g();\n", 8229 Style); 8230 verifyFormat("const char *\n" 8231 "f(void) {\n" // Break here. 8232 " return \"\";\n" 8233 "}\n" 8234 "const char *bar(void);\n", // No break here. 8235 Style); 8236 verifyFormat("template <class T>\n" 8237 "T *\n" 8238 "f(T &c) {\n" // Break here. 8239 " return NULL;\n" 8240 "}\n" 8241 "template <class T> T *f(T &c);\n", // No break here. 8242 Style); 8243 verifyFormat("class C {\n" 8244 " int\n" 8245 " operator+() {\n" 8246 " return 1;\n" 8247 " }\n" 8248 " int\n" 8249 " operator()() {\n" 8250 " return 1;\n" 8251 " }\n" 8252 "};\n", 8253 Style); 8254 verifyFormat("void\n" 8255 "A::operator()() {}\n" 8256 "void\n" 8257 "A::operator>>() {}\n" 8258 "void\n" 8259 "A::operator+() {}\n" 8260 "void\n" 8261 "A::operator*() {}\n" 8262 "void\n" 8263 "A::operator->() {}\n" 8264 "void\n" 8265 "A::operator void *() {}\n" 8266 "void\n" 8267 "A::operator void &() {}\n" 8268 "void\n" 8269 "A::operator void &&() {}\n" 8270 "void\n" 8271 "A::operator char *() {}\n" 8272 "void\n" 8273 "A::operator[]() {}\n" 8274 "void\n" 8275 "A::operator!() {}\n" 8276 "void\n" 8277 "A::operator**() {}\n" 8278 "void\n" 8279 "A::operator<Foo> *() {}\n" 8280 "void\n" 8281 "A::operator<Foo> **() {}\n" 8282 "void\n" 8283 "A::operator<Foo> &() {}\n" 8284 "void\n" 8285 "A::operator void **() {}\n", 8286 Style); 8287 verifyFormat("constexpr auto\n" 8288 "operator()() const -> reference {}\n" 8289 "constexpr auto\n" 8290 "operator>>() const -> reference {}\n" 8291 "constexpr auto\n" 8292 "operator+() const -> reference {}\n" 8293 "constexpr auto\n" 8294 "operator*() const -> reference {}\n" 8295 "constexpr auto\n" 8296 "operator->() const -> reference {}\n" 8297 "constexpr auto\n" 8298 "operator++() const -> reference {}\n" 8299 "constexpr auto\n" 8300 "operator void *() const -> reference {}\n" 8301 "constexpr auto\n" 8302 "operator void **() const -> reference {}\n" 8303 "constexpr auto\n" 8304 "operator void *() const -> reference {}\n" 8305 "constexpr auto\n" 8306 "operator void &() const -> reference {}\n" 8307 "constexpr auto\n" 8308 "operator void &&() const -> reference {}\n" 8309 "constexpr auto\n" 8310 "operator char *() const -> reference {}\n" 8311 "constexpr auto\n" 8312 "operator!() const -> reference {}\n" 8313 "constexpr auto\n" 8314 "operator[]() const -> reference {}\n", 8315 Style); 8316 verifyFormat("void *operator new(std::size_t s);", // No break here. 8317 Style); 8318 verifyFormat("void *\n" 8319 "operator new(std::size_t s) {}", 8320 Style); 8321 verifyFormat("void *\n" 8322 "operator delete[](void *ptr) {}", 8323 Style); 8324 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 8325 verifyFormat("const char *\n" 8326 "f(void)\n" // Break here. 8327 "{\n" 8328 " return \"\";\n" 8329 "}\n" 8330 "const char *bar(void);\n", // No break here. 8331 Style); 8332 verifyFormat("template <class T>\n" 8333 "T *\n" // Problem here: no line break 8334 "f(T &c)\n" // Break here. 8335 "{\n" 8336 " return NULL;\n" 8337 "}\n" 8338 "template <class T> T *f(T &c);\n", // No break here. 8339 Style); 8340 verifyFormat("int\n" 8341 "foo(A<bool> a)\n" 8342 "{\n" 8343 " return a;\n" 8344 "}\n", 8345 Style); 8346 verifyFormat("int\n" 8347 "foo(A<8> a)\n" 8348 "{\n" 8349 " return a;\n" 8350 "}\n", 8351 Style); 8352 verifyFormat("int\n" 8353 "foo(A<B<bool>, 8> a)\n" 8354 "{\n" 8355 " return a;\n" 8356 "}\n", 8357 Style); 8358 verifyFormat("int\n" 8359 "foo(A<B<8>, bool> a)\n" 8360 "{\n" 8361 " return a;\n" 8362 "}\n", 8363 Style); 8364 verifyFormat("int\n" 8365 "foo(A<B<bool>, bool> a)\n" 8366 "{\n" 8367 " return a;\n" 8368 "}\n", 8369 Style); 8370 verifyFormat("int\n" 8371 "foo(A<B<8>, 8> a)\n" 8372 "{\n" 8373 " return a;\n" 8374 "}\n", 8375 Style); 8376 8377 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 8378 Style.BraceWrapping.AfterFunction = true; 8379 verifyFormat("int f(i);\n" // No break here. 8380 "int\n" // Break here. 8381 "f(i)\n" 8382 "{\n" 8383 " return i + 1;\n" 8384 "}\n" 8385 "int\n" // Break here. 8386 "f(i)\n" 8387 "{\n" 8388 " return i + 1;\n" 8389 "};", 8390 Style); 8391 verifyFormat("int f(a, b, c);\n" // No break here. 8392 "int\n" // Break here. 8393 "f(a, b, c)\n" // Break here. 8394 "short a, b;\n" 8395 "float c;\n" 8396 "{\n" 8397 " return a + b < c;\n" 8398 "}\n" 8399 "int\n" // Break here. 8400 "f(a, b, c)\n" // Break here. 8401 "short a, b;\n" 8402 "float c;\n" 8403 "{\n" 8404 " return a + b < c;\n" 8405 "};", 8406 Style); 8407 verifyFormat("byte *\n" // Break here. 8408 "f(a)\n" // Break here. 8409 "byte a[];\n" 8410 "{\n" 8411 " return a;\n" 8412 "}", 8413 Style); 8414 verifyFormat("bool f(int a, int) override;\n" 8415 "Bar g(int a, Bar) final;\n" 8416 "Bar h(a, Bar) final;", 8417 Style); 8418 verifyFormat("int\n" 8419 "f(a)", 8420 Style); 8421 verifyFormat("bool\n" 8422 "f(size_t = 0, bool b = false)\n" 8423 "{\n" 8424 " return !b;\n" 8425 "}", 8426 Style); 8427 8428 // The return breaking style doesn't affect: 8429 // * function and object definitions with attribute-like macros 8430 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 8431 " ABSL_GUARDED_BY(mutex) = {};", 8432 getGoogleStyleWithColumns(40)); 8433 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 8434 " ABSL_GUARDED_BY(mutex); // comment", 8435 getGoogleStyleWithColumns(40)); 8436 verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n" 8437 " ABSL_GUARDED_BY(mutex1)\n" 8438 " ABSL_GUARDED_BY(mutex2);", 8439 getGoogleStyleWithColumns(40)); 8440 verifyFormat("Tttttt f(int a, int b)\n" 8441 " ABSL_GUARDED_BY(mutex1)\n" 8442 " ABSL_GUARDED_BY(mutex2);", 8443 getGoogleStyleWithColumns(40)); 8444 // * typedefs 8445 verifyFormat("typedef ATTR(X) char x;", getGoogleStyle()); 8446 8447 Style = getGNUStyle(); 8448 8449 // Test for comments at the end of function declarations. 8450 verifyFormat("void\n" 8451 "foo (int a, /*abc*/ int b) // def\n" 8452 "{\n" 8453 "}\n", 8454 Style); 8455 8456 verifyFormat("void\n" 8457 "foo (int a, /* abc */ int b) /* def */\n" 8458 "{\n" 8459 "}\n", 8460 Style); 8461 8462 // Definitions that should not break after return type 8463 verifyFormat("void foo (int a, int b); // def\n", Style); 8464 verifyFormat("void foo (int a, int b); /* def */\n", Style); 8465 verifyFormat("void foo (int a, int b);\n", Style); 8466 } 8467 8468 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) { 8469 FormatStyle NoBreak = getLLVMStyle(); 8470 NoBreak.AlwaysBreakBeforeMultilineStrings = false; 8471 FormatStyle Break = getLLVMStyle(); 8472 Break.AlwaysBreakBeforeMultilineStrings = true; 8473 verifyFormat("aaaa = \"bbbb\"\n" 8474 " \"cccc\";", 8475 NoBreak); 8476 verifyFormat("aaaa =\n" 8477 " \"bbbb\"\n" 8478 " \"cccc\";", 8479 Break); 8480 verifyFormat("aaaa(\"bbbb\"\n" 8481 " \"cccc\");", 8482 NoBreak); 8483 verifyFormat("aaaa(\n" 8484 " \"bbbb\"\n" 8485 " \"cccc\");", 8486 Break); 8487 verifyFormat("aaaa(qqq, \"bbbb\"\n" 8488 " \"cccc\");", 8489 NoBreak); 8490 verifyFormat("aaaa(qqq,\n" 8491 " \"bbbb\"\n" 8492 " \"cccc\");", 8493 Break); 8494 verifyFormat("aaaa(qqq,\n" 8495 " L\"bbbb\"\n" 8496 " L\"cccc\");", 8497 Break); 8498 verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n" 8499 " \"bbbb\"));", 8500 Break); 8501 verifyFormat("string s = someFunction(\n" 8502 " \"abc\"\n" 8503 " \"abc\");", 8504 Break); 8505 8506 // As we break before unary operators, breaking right after them is bad. 8507 verifyFormat("string foo = abc ? \"x\"\n" 8508 " \"blah blah blah blah blah blah\"\n" 8509 " : \"y\";", 8510 Break); 8511 8512 // Don't break if there is no column gain. 8513 verifyFormat("f(\"aaaa\"\n" 8514 " \"bbbb\");", 8515 Break); 8516 8517 // Treat literals with escaped newlines like multi-line string literals. 8518 EXPECT_EQ("x = \"a\\\n" 8519 "b\\\n" 8520 "c\";", 8521 format("x = \"a\\\n" 8522 "b\\\n" 8523 "c\";", 8524 NoBreak)); 8525 EXPECT_EQ("xxxx =\n" 8526 " \"a\\\n" 8527 "b\\\n" 8528 "c\";", 8529 format("xxxx = \"a\\\n" 8530 "b\\\n" 8531 "c\";", 8532 Break)); 8533 8534 EXPECT_EQ("NSString *const kString =\n" 8535 " @\"aaaa\"\n" 8536 " @\"bbbb\";", 8537 format("NSString *const kString = @\"aaaa\"\n" 8538 "@\"bbbb\";", 8539 Break)); 8540 8541 Break.ColumnLimit = 0; 8542 verifyFormat("const char *hello = \"hello llvm\";", Break); 8543 } 8544 8545 TEST_F(FormatTest, AlignsPipes) { 8546 verifyFormat( 8547 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8548 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8549 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8550 verifyFormat( 8551 "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n" 8552 " << aaaaaaaaaaaaaaaaaaaa;"); 8553 verifyFormat( 8554 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8555 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8556 verifyFormat( 8557 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" 8558 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8559 verifyFormat( 8560 "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n" 8561 " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n" 8562 " << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";"); 8563 verifyFormat( 8564 "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8565 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8566 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8567 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8568 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8569 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8570 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 8571 verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n" 8572 " << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);"); 8573 verifyFormat( 8574 "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8575 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8576 verifyFormat( 8577 "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n" 8578 " aaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8579 8580 verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n" 8581 " << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();"); 8582 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8583 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8584 " aaaaaaaaaaaaaaaaaaaaa)\n" 8585 " << aaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8586 verifyFormat("LOG_IF(aaa == //\n" 8587 " bbb)\n" 8588 " << a << b;"); 8589 8590 // But sometimes, breaking before the first "<<" is desirable. 8591 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 8592 " << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);"); 8593 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n" 8594 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8595 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8596 verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n" 8597 " << BEF << IsTemplate << Description << E->getType();"); 8598 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 8599 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8600 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8601 verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" 8602 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8603 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8604 " << aaa;"); 8605 8606 verifyFormat( 8607 "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8608 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 8609 8610 // Incomplete string literal. 8611 EXPECT_EQ("llvm::errs() << \"\n" 8612 " << a;", 8613 format("llvm::errs() << \"\n<<a;")); 8614 8615 verifyFormat("void f() {\n" 8616 " CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n" 8617 " << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n" 8618 "}"); 8619 8620 // Handle 'endl'. 8621 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n" 8622 " << bbbbbbbbbbbbbbbbbbbbbb << endl;"); 8623 verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;"); 8624 8625 // Handle '\n'. 8626 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n" 8627 " << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";"); 8628 verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n" 8629 " << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';"); 8630 verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n" 8631 " << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";"); 8632 verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";"); 8633 } 8634 8635 TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) { 8636 verifyFormat("return out << \"somepacket = {\\n\"\n" 8637 " << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n" 8638 " << \" bbbb = \" << pkt.bbbb << \"\\n\"\n" 8639 " << \" cccccc = \" << pkt.cccccc << \"\\n\"\n" 8640 " << \" ddd = [\" << pkt.ddd << \"]\\n\"\n" 8641 " << \"}\";"); 8642 8643 verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n" 8644 " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n" 8645 " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;"); 8646 verifyFormat( 8647 "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n" 8648 " << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n" 8649 " << \"ccccccccccccccccc = \" << ccccccccccccccccc\n" 8650 " << \"ddddddddddddddddd = \" << ddddddddddddddddd\n" 8651 " << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;"); 8652 verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n" 8653 " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 8654 verifyFormat( 8655 "void f() {\n" 8656 " llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n" 8657 " << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" 8658 "}"); 8659 8660 // Breaking before the first "<<" is generally not desirable. 8661 verifyFormat( 8662 "llvm::errs()\n" 8663 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8664 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8665 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8666 " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 8667 getLLVMStyleWithColumns(70)); 8668 verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n" 8669 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8670 " << \"aaaaaaaaaaaaaaaaaaa: \"\n" 8671 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8672 " << \"aaaaaaaaaaaaaaaaaaa: \"\n" 8673 " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", 8674 getLLVMStyleWithColumns(70)); 8675 8676 verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n" 8677 " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n" 8678 " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;"); 8679 verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n" 8680 " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n" 8681 " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);"); 8682 verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n" 8683 " (aaaa + aaaa);", 8684 getLLVMStyleWithColumns(40)); 8685 verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n" 8686 " (aaaaaaa + aaaaa));", 8687 getLLVMStyleWithColumns(40)); 8688 verifyFormat( 8689 "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n" 8690 " SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n" 8691 " bbbbbbbbbbbbbbbbbbbbbbb);"); 8692 } 8693 8694 TEST_F(FormatTest, UnderstandsEquals) { 8695 verifyFormat( 8696 "aaaaaaaaaaaaaaaaa =\n" 8697 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 8698 verifyFormat( 8699 "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 8700 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 8701 verifyFormat( 8702 "if (a) {\n" 8703 " f();\n" 8704 "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 8705 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" 8706 "}"); 8707 8708 verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 8709 " 100000000 + 10000000) {\n}"); 8710 } 8711 8712 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) { 8713 verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n" 8714 " .looooooooooooooooooooooooooooooooooooooongFunction();"); 8715 8716 verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n" 8717 " ->looooooooooooooooooooooooooooooooooooooongFunction();"); 8718 8719 verifyFormat( 8720 "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n" 8721 " Parameter2);"); 8722 8723 verifyFormat( 8724 "ShortObject->shortFunction(\n" 8725 " LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n" 8726 " LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);"); 8727 8728 verifyFormat("loooooooooooooongFunction(\n" 8729 " LoooooooooooooongObject->looooooooooooooooongFunction());"); 8730 8731 verifyFormat( 8732 "function(LoooooooooooooooooooooooooooooooooooongObject\n" 8733 " ->loooooooooooooooooooooooooooooooooooooooongFunction());"); 8734 8735 verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n" 8736 " .WillRepeatedly(Return(SomeValue));"); 8737 verifyFormat("void f() {\n" 8738 " EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n" 8739 " .Times(2)\n" 8740 " .WillRepeatedly(Return(SomeValue));\n" 8741 "}"); 8742 verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n" 8743 " ccccccccccccccccccccccc);"); 8744 verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8745 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8746 " .aaaaa(aaaaa),\n" 8747 " aaaaaaaaaaaaaaaaaaaaa);"); 8748 verifyFormat("void f() {\n" 8749 " aaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8750 " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n" 8751 "}"); 8752 verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8753 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8754 " .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8755 " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8756 " aaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 8757 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8758 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8759 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 8760 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n" 8761 "}"); 8762 8763 // Here, it is not necessary to wrap at "." or "->". 8764 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n" 8765 " aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); 8766 verifyFormat( 8767 "aaaaaaaaaaa->aaaaaaaaa(\n" 8768 " aaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8769 " aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n"); 8770 8771 verifyFormat( 8772 "aaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8773 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());"); 8774 verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n" 8775 " aaaaaaaaa()->aaaaaa()->aaaaa());"); 8776 verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n" 8777 " aaaaaaaaa()->aaaaaa()->aaaaa());"); 8778 8779 verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8780 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8781 " .a();"); 8782 8783 FormatStyle NoBinPacking = getLLVMStyle(); 8784 NoBinPacking.BinPackParameters = false; 8785 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n" 8786 " .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n" 8787 " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n" 8788 " aaaaaaaaaaaaaaaaaaa,\n" 8789 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 8790 NoBinPacking); 8791 8792 // If there is a subsequent call, change to hanging indentation. 8793 verifyFormat( 8794 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8795 " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n" 8796 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 8797 verifyFormat( 8798 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8799 " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));"); 8800 verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8801 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8802 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 8803 verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8804 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 8805 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());"); 8806 } 8807 8808 TEST_F(FormatTest, WrapsTemplateDeclarations) { 8809 verifyFormat("template <typename T>\n" 8810 "virtual void loooooooooooongFunction(int Param1, int Param2);"); 8811 verifyFormat("template <typename T>\n" 8812 "// T should be one of {A, B}.\n" 8813 "virtual void loooooooooooongFunction(int Param1, int Param2);"); 8814 verifyFormat( 8815 "template <typename T>\n" 8816 "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;"); 8817 verifyFormat("template <typename T>\n" 8818 "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n" 8819 " int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);"); 8820 verifyFormat( 8821 "template <typename T>\n" 8822 "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n" 8823 " int Paaaaaaaaaaaaaaaaaaaaram2);"); 8824 verifyFormat( 8825 "template <typename T>\n" 8826 "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n" 8827 " aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n" 8828 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8829 verifyFormat("template <typename T>\n" 8830 "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8831 " int aaaaaaaaaaaaaaaaaaaaaa);"); 8832 verifyFormat( 8833 "template <typename T1, typename T2 = char, typename T3 = char,\n" 8834 " typename T4 = char>\n" 8835 "void f();"); 8836 verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n" 8837 " template <typename> class cccccccccccccccccccccc,\n" 8838 " typename ddddddddddddd>\n" 8839 "class C {};"); 8840 verifyFormat( 8841 "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n" 8842 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 8843 8844 verifyFormat("void f() {\n" 8845 " a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n" 8846 " a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n" 8847 "}"); 8848 8849 verifyFormat("template <typename T> class C {};"); 8850 verifyFormat("template <typename T> void f();"); 8851 verifyFormat("template <typename T> void f() {}"); 8852 verifyFormat( 8853 "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n" 8854 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8855 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n" 8856 " new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n" 8857 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8858 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n" 8859 " bbbbbbbbbbbbbbbbbbbbbbbb);", 8860 getLLVMStyleWithColumns(72)); 8861 EXPECT_EQ("static_cast<A< //\n" 8862 " B> *>(\n" 8863 "\n" 8864 ");", 8865 format("static_cast<A<//\n" 8866 " B>*>(\n" 8867 "\n" 8868 " );")); 8869 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 8870 " const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);"); 8871 8872 FormatStyle AlwaysBreak = getLLVMStyle(); 8873 AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 8874 verifyFormat("template <typename T>\nclass C {};", AlwaysBreak); 8875 verifyFormat("template <typename T>\nvoid f();", AlwaysBreak); 8876 verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak); 8877 verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8878 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n" 8879 " ccccccccccccccccccccccccccccccccccccccccccccccc);"); 8880 verifyFormat("template <template <typename> class Fooooooo,\n" 8881 " template <typename> class Baaaaaaar>\n" 8882 "struct C {};", 8883 AlwaysBreak); 8884 verifyFormat("template <typename T> // T can be A, B or C.\n" 8885 "struct C {};", 8886 AlwaysBreak); 8887 verifyFormat("template <enum E> class A {\n" 8888 "public:\n" 8889 " E *f();\n" 8890 "};"); 8891 8892 FormatStyle NeverBreak = getLLVMStyle(); 8893 NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No; 8894 verifyFormat("template <typename T> class C {};", NeverBreak); 8895 verifyFormat("template <typename T> void f();", NeverBreak); 8896 verifyFormat("template <typename T> void f() {}", NeverBreak); 8897 verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa " 8898 "bbbbbbbbbbbbbbbbbbbb) {}", 8899 NeverBreak); 8900 verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 8901 " bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n" 8902 " ccccccccccccccccccccccccccccccccccccccccccccccc);", 8903 NeverBreak); 8904 verifyFormat("template <template <typename> class Fooooooo,\n" 8905 " template <typename> class Baaaaaaar>\n" 8906 "struct C {};", 8907 NeverBreak); 8908 verifyFormat("template <typename T> // T can be A, B or C.\n" 8909 "struct C {};", 8910 NeverBreak); 8911 verifyFormat("template <enum E> class A {\n" 8912 "public:\n" 8913 " E *f();\n" 8914 "};", 8915 NeverBreak); 8916 NeverBreak.PenaltyBreakTemplateDeclaration = 100; 8917 verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa " 8918 "bbbbbbbbbbbbbbbbbbbb) {}", 8919 NeverBreak); 8920 } 8921 8922 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) { 8923 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp); 8924 Style.ColumnLimit = 60; 8925 EXPECT_EQ("// Baseline - no comments.\n" 8926 "template <\n" 8927 " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n" 8928 "void f() {}", 8929 format("// Baseline - no comments.\n" 8930 "template <\n" 8931 " typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n" 8932 "void f() {}", 8933 Style)); 8934 8935 EXPECT_EQ("template <\n" 8936 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 8937 "void f() {}", 8938 format("template <\n" 8939 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 8940 "void f() {}", 8941 Style)); 8942 8943 EXPECT_EQ( 8944 "template <\n" 8945 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n" 8946 "void f() {}", 8947 format("template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n" 8948 "void f() {}", 8949 Style)); 8950 8951 EXPECT_EQ( 8952 "template <\n" 8953 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 8954 " // multiline\n" 8955 "void f() {}", 8956 format("template <\n" 8957 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n" 8958 " // multiline\n" 8959 "void f() {}", 8960 Style)); 8961 8962 EXPECT_EQ( 8963 "template <typename aaaaaaaaaa<\n" 8964 " bbbbbbbbbbbb>::value> // trailing loooong\n" 8965 "void f() {}", 8966 format( 8967 "template <\n" 8968 " typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n" 8969 "void f() {}", 8970 Style)); 8971 } 8972 8973 TEST_F(FormatTest, WrapsTemplateParameters) { 8974 FormatStyle Style = getLLVMStyle(); 8975 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 8976 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 8977 verifyFormat( 8978 "template <typename... a> struct q {};\n" 8979 "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n" 8980 " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n" 8981 " y;", 8982 Style); 8983 Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; 8984 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 8985 verifyFormat( 8986 "template <typename... a> struct r {};\n" 8987 "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n" 8988 " aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n" 8989 " y;", 8990 Style); 8991 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 8992 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 8993 verifyFormat("template <typename... a> struct s {};\n" 8994 "extern s<\n" 8995 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 8996 "aaaaaaaaaaaaaaaaaaaaaa,\n" 8997 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 8998 "aaaaaaaaaaaaaaaaaaaaaa>\n" 8999 " y;", 9000 Style); 9001 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 9002 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 9003 verifyFormat("template <typename... a> struct t {};\n" 9004 "extern t<\n" 9005 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9006 "aaaaaaaaaaaaaaaaaaaaaa,\n" 9007 " aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, " 9008 "aaaaaaaaaaaaaaaaaaaaaa>\n" 9009 " y;", 9010 Style); 9011 } 9012 9013 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) { 9014 verifyFormat( 9015 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9016 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9017 verifyFormat( 9018 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9019 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9020 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());"); 9021 9022 // FIXME: Should we have the extra indent after the second break? 9023 verifyFormat( 9024 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9025 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9026 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9027 9028 verifyFormat( 9029 "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n" 9030 " cccccccccccccccccccccccccccccccccccccccccccccc());"); 9031 9032 // Breaking at nested name specifiers is generally not desirable. 9033 verifyFormat( 9034 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9035 " aaaaaaaaaaaaaaaaaaaaaaa);"); 9036 9037 verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n" 9038 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9039 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 9040 " aaaaaaaaaaaaaaaaaaaaa);", 9041 getLLVMStyleWithColumns(74)); 9042 9043 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n" 9044 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9045 " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); 9046 } 9047 9048 TEST_F(FormatTest, UnderstandsTemplateParameters) { 9049 verifyFormat("A<int> a;"); 9050 verifyFormat("A<A<A<int>>> a;"); 9051 verifyFormat("A<A<A<int, 2>, 3>, 4> a;"); 9052 verifyFormat("bool x = a < 1 || 2 > a;"); 9053 verifyFormat("bool x = 5 < f<int>();"); 9054 verifyFormat("bool x = f<int>() > 5;"); 9055 verifyFormat("bool x = 5 < a<int>::x;"); 9056 verifyFormat("bool x = a < 4 ? a > 2 : false;"); 9057 verifyFormat("bool x = f() ? a < 2 : a > 2;"); 9058 9059 verifyGoogleFormat("A<A<int>> a;"); 9060 verifyGoogleFormat("A<A<A<int>>> a;"); 9061 verifyGoogleFormat("A<A<A<A<int>>>> a;"); 9062 verifyGoogleFormat("A<A<int> > a;"); 9063 verifyGoogleFormat("A<A<A<int> > > a;"); 9064 verifyGoogleFormat("A<A<A<A<int> > > > a;"); 9065 verifyGoogleFormat("A<::A<int>> a;"); 9066 verifyGoogleFormat("A<::A> a;"); 9067 verifyGoogleFormat("A< ::A> a;"); 9068 verifyGoogleFormat("A< ::A<int> > a;"); 9069 EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle())); 9070 EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle())); 9071 EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle())); 9072 EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle())); 9073 EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };", 9074 format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle())); 9075 9076 verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp)); 9077 9078 // template closer followed by a token that starts with > or = 9079 verifyFormat("bool b = a<1> > 1;"); 9080 verifyFormat("bool b = a<1> >= 1;"); 9081 verifyFormat("int i = a<1> >> 1;"); 9082 FormatStyle Style = getLLVMStyle(); 9083 Style.SpaceBeforeAssignmentOperators = false; 9084 verifyFormat("bool b= a<1> == 1;", Style); 9085 verifyFormat("a<int> = 1;", Style); 9086 verifyFormat("a<int> >>= 1;", Style); 9087 9088 verifyFormat("test < a | b >> c;"); 9089 verifyFormat("test<test<a | b>> c;"); 9090 verifyFormat("test >> a >> b;"); 9091 verifyFormat("test << a >> b;"); 9092 9093 verifyFormat("f<int>();"); 9094 verifyFormat("template <typename T> void f() {}"); 9095 verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;"); 9096 verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : " 9097 "sizeof(char)>::type>;"); 9098 verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};"); 9099 verifyFormat("f(a.operator()<A>());"); 9100 verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9101 " .template operator()<A>());", 9102 getLLVMStyleWithColumns(35)); 9103 9104 // Not template parameters. 9105 verifyFormat("return a < b && c > d;"); 9106 verifyFormat("void f() {\n" 9107 " while (a < b && c > d) {\n" 9108 " }\n" 9109 "}"); 9110 verifyFormat("template <typename... Types>\n" 9111 "typename enable_if<0 < sizeof...(Types)>::type Foo() {}"); 9112 9113 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9114 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);", 9115 getLLVMStyleWithColumns(60)); 9116 verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");"); 9117 verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}"); 9118 verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <"); 9119 verifyFormat("some_templated_type<decltype([](int i) { return i; })>"); 9120 } 9121 9122 TEST_F(FormatTest, UnderstandsShiftOperators) { 9123 verifyFormat("if (i < x >> 1)"); 9124 verifyFormat("while (i < x >> 1)"); 9125 verifyFormat("for (unsigned i = 0; i < i; ++i, v = v >> 1)"); 9126 verifyFormat("for (unsigned i = 0; i < x >> 1; ++i, v = v >> 1)"); 9127 verifyFormat( 9128 "for (std::vector<int>::iterator i = 0; i < x >> 1; ++i, v = v >> 1)"); 9129 verifyFormat("Foo.call<Bar<Function>>()"); 9130 verifyFormat("if (Foo.call<Bar<Function>>() == 0)"); 9131 verifyFormat("for (std::vector<std::pair<int>>::iterator i = 0; i < x >> 1; " 9132 "++i, v = v >> 1)"); 9133 verifyFormat("if (w<u<v<x>>, 1>::t)"); 9134 } 9135 9136 TEST_F(FormatTest, BitshiftOperatorWidth) { 9137 EXPECT_EQ("int a = 1 << 2; /* foo\n" 9138 " bar */", 9139 format("int a=1<<2; /* foo\n" 9140 " bar */")); 9141 9142 EXPECT_EQ("int b = 256 >> 1; /* foo\n" 9143 " bar */", 9144 format("int b =256>>1 ; /* foo\n" 9145 " bar */")); 9146 } 9147 9148 TEST_F(FormatTest, UnderstandsBinaryOperators) { 9149 verifyFormat("COMPARE(a, ==, b);"); 9150 verifyFormat("auto s = sizeof...(Ts) - 1;"); 9151 } 9152 9153 TEST_F(FormatTest, UnderstandsPointersToMembers) { 9154 verifyFormat("int A::*x;"); 9155 verifyFormat("int (S::*func)(void *);"); 9156 verifyFormat("void f() { int (S::*func)(void *); }"); 9157 verifyFormat("typedef bool *(Class::*Member)() const;"); 9158 verifyFormat("void f() {\n" 9159 " (a->*f)();\n" 9160 " a->*x;\n" 9161 " (a.*f)();\n" 9162 " ((*a).*f)();\n" 9163 " a.*x;\n" 9164 "}"); 9165 verifyFormat("void f() {\n" 9166 " (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n" 9167 " aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n" 9168 "}"); 9169 verifyFormat( 9170 "(aaaaaaaaaa->*bbbbbbb)(\n" 9171 " aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));"); 9172 FormatStyle Style = getLLVMStyle(); 9173 Style.PointerAlignment = FormatStyle::PAS_Left; 9174 verifyFormat("typedef bool* (Class::*Member)() const;", Style); 9175 } 9176 9177 TEST_F(FormatTest, UnderstandsUnaryOperators) { 9178 verifyFormat("int a = -2;"); 9179 verifyFormat("f(-1, -2, -3);"); 9180 verifyFormat("a[-1] = 5;"); 9181 verifyFormat("int a = 5 + -2;"); 9182 verifyFormat("if (i == -1) {\n}"); 9183 verifyFormat("if (i != -1) {\n}"); 9184 verifyFormat("if (i > -1) {\n}"); 9185 verifyFormat("if (i < -1) {\n}"); 9186 verifyFormat("++(a->f());"); 9187 verifyFormat("--(a->f());"); 9188 verifyFormat("(a->f())++;"); 9189 verifyFormat("a[42]++;"); 9190 verifyFormat("if (!(a->f())) {\n}"); 9191 verifyFormat("if (!+i) {\n}"); 9192 verifyFormat("~&a;"); 9193 9194 verifyFormat("a-- > b;"); 9195 verifyFormat("b ? -a : c;"); 9196 verifyFormat("n * sizeof char16;"); 9197 verifyFormat("n * alignof char16;", getGoogleStyle()); 9198 verifyFormat("sizeof(char);"); 9199 verifyFormat("alignof(char);", getGoogleStyle()); 9200 9201 verifyFormat("return -1;"); 9202 verifyFormat("throw -1;"); 9203 verifyFormat("switch (a) {\n" 9204 "case -1:\n" 9205 " break;\n" 9206 "}"); 9207 verifyFormat("#define X -1"); 9208 verifyFormat("#define X -kConstant"); 9209 9210 verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};"); 9211 verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};"); 9212 9213 verifyFormat("int a = /* confusing comment */ -1;"); 9214 // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case. 9215 verifyFormat("int a = i /* confusing comment */++;"); 9216 9217 verifyFormat("co_yield -1;"); 9218 verifyFormat("co_return -1;"); 9219 9220 // Check that * is not treated as a binary operator when we set 9221 // PointerAlignment as PAS_Left after a keyword and not a declaration. 9222 FormatStyle PASLeftStyle = getLLVMStyle(); 9223 PASLeftStyle.PointerAlignment = FormatStyle::PAS_Left; 9224 verifyFormat("co_return *a;", PASLeftStyle); 9225 verifyFormat("co_await *a;", PASLeftStyle); 9226 verifyFormat("co_yield *a", PASLeftStyle); 9227 verifyFormat("return *a;", PASLeftStyle); 9228 } 9229 9230 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) { 9231 verifyFormat("if (!aaaaaaaaaa( // break\n" 9232 " aaaaa)) {\n" 9233 "}"); 9234 verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n" 9235 " aaaaa));"); 9236 verifyFormat("*aaa = aaaaaaa( // break\n" 9237 " bbbbbb);"); 9238 } 9239 9240 TEST_F(FormatTest, UnderstandsOverloadedOperators) { 9241 verifyFormat("bool operator<();"); 9242 verifyFormat("bool operator>();"); 9243 verifyFormat("bool operator=();"); 9244 verifyFormat("bool operator==();"); 9245 verifyFormat("bool operator!=();"); 9246 verifyFormat("int operator+();"); 9247 verifyFormat("int operator++();"); 9248 verifyFormat("int operator++(int) volatile noexcept;"); 9249 verifyFormat("bool operator,();"); 9250 verifyFormat("bool operator();"); 9251 verifyFormat("bool operator()();"); 9252 verifyFormat("bool operator[]();"); 9253 verifyFormat("operator bool();"); 9254 verifyFormat("operator int();"); 9255 verifyFormat("operator void *();"); 9256 verifyFormat("operator SomeType<int>();"); 9257 verifyFormat("operator SomeType<int, int>();"); 9258 verifyFormat("operator SomeType<SomeType<int>>();"); 9259 verifyFormat("void *operator new(std::size_t size);"); 9260 verifyFormat("void *operator new[](std::size_t size);"); 9261 verifyFormat("void operator delete(void *ptr);"); 9262 verifyFormat("void operator delete[](void *ptr);"); 9263 verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n" 9264 "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);"); 9265 verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n" 9266 " aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;"); 9267 9268 verifyFormat( 9269 "ostream &operator<<(ostream &OutputStream,\n" 9270 " SomeReallyLongType WithSomeReallyLongValue);"); 9271 verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n" 9272 " const aaaaaaaaaaaaaaaaaaaaa &right) {\n" 9273 " return left.group < right.group;\n" 9274 "}"); 9275 verifyFormat("SomeType &operator=(const SomeType &S);"); 9276 verifyFormat("f.template operator()<int>();"); 9277 9278 verifyGoogleFormat("operator void*();"); 9279 verifyGoogleFormat("operator SomeType<SomeType<int>>();"); 9280 verifyGoogleFormat("operator ::A();"); 9281 9282 verifyFormat("using A::operator+;"); 9283 verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n" 9284 "int i;"); 9285 9286 // Calling an operator as a member function. 9287 verifyFormat("void f() { a.operator*(); }"); 9288 verifyFormat("void f() { a.operator*(b & b); }"); 9289 verifyFormat("void f() { a->operator&(a * b); }"); 9290 verifyFormat("void f() { NS::a.operator+(*b * *b); }"); 9291 // TODO: Calling an operator as a non-member function is hard to distinguish. 9292 // https://llvm.org/PR50629 9293 // verifyFormat("void f() { operator*(a & a); }"); 9294 // verifyFormat("void f() { operator&(a, b * b); }"); 9295 9296 verifyFormat("::operator delete(foo);"); 9297 verifyFormat("::operator new(n * sizeof(foo));"); 9298 verifyFormat("foo() { ::operator delete(foo); }"); 9299 verifyFormat("foo() { ::operator new(n * sizeof(foo)); }"); 9300 } 9301 9302 TEST_F(FormatTest, UnderstandsFunctionRefQualification) { 9303 verifyFormat("Deleted &operator=(const Deleted &) & = default;"); 9304 verifyFormat("Deleted &operator=(const Deleted &) && = delete;"); 9305 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;"); 9306 verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;"); 9307 verifyFormat("Deleted &operator=(const Deleted &) &;"); 9308 verifyFormat("Deleted &operator=(const Deleted &) &&;"); 9309 verifyFormat("SomeType MemberFunction(const Deleted &) &;"); 9310 verifyFormat("SomeType MemberFunction(const Deleted &) &&;"); 9311 verifyFormat("SomeType MemberFunction(const Deleted &) && {}"); 9312 verifyFormat("SomeType MemberFunction(const Deleted &) && final {}"); 9313 verifyFormat("SomeType MemberFunction(const Deleted &) && override {}"); 9314 verifyFormat("void Fn(T const &) const &;"); 9315 verifyFormat("void Fn(T const volatile &&) const volatile &&;"); 9316 verifyFormat("template <typename T>\n" 9317 "void F(T) && = delete;", 9318 getGoogleStyle()); 9319 9320 FormatStyle AlignLeft = getLLVMStyle(); 9321 AlignLeft.PointerAlignment = FormatStyle::PAS_Left; 9322 verifyFormat("void A::b() && {}", AlignLeft); 9323 verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft); 9324 verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;", 9325 AlignLeft); 9326 verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft); 9327 verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft); 9328 verifyFormat("auto Function(T t) & -> void {}", AlignLeft); 9329 verifyFormat("auto Function(T... t) & -> void {}", AlignLeft); 9330 verifyFormat("auto Function(T) & -> void {}", AlignLeft); 9331 verifyFormat("auto Function(T) & -> void;", AlignLeft); 9332 verifyFormat("void Fn(T const&) const&;", AlignLeft); 9333 verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft); 9334 9335 FormatStyle Spaces = getLLVMStyle(); 9336 Spaces.SpacesInCStyleCastParentheses = true; 9337 verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces); 9338 verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces); 9339 verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces); 9340 verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces); 9341 9342 Spaces.SpacesInCStyleCastParentheses = false; 9343 Spaces.SpacesInParentheses = true; 9344 verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces); 9345 verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;", 9346 Spaces); 9347 verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces); 9348 verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces); 9349 9350 FormatStyle BreakTemplate = getLLVMStyle(); 9351 BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 9352 9353 verifyFormat("struct f {\n" 9354 " template <class T>\n" 9355 " int &foo(const std::string &str) &noexcept {}\n" 9356 "};", 9357 BreakTemplate); 9358 9359 verifyFormat("struct f {\n" 9360 " template <class T>\n" 9361 " int &foo(const std::string &str) &&noexcept {}\n" 9362 "};", 9363 BreakTemplate); 9364 9365 verifyFormat("struct f {\n" 9366 " template <class T>\n" 9367 " int &foo(const std::string &str) const &noexcept {}\n" 9368 "};", 9369 BreakTemplate); 9370 9371 verifyFormat("struct f {\n" 9372 " template <class T>\n" 9373 " int &foo(const std::string &str) const &noexcept {}\n" 9374 "};", 9375 BreakTemplate); 9376 9377 verifyFormat("struct f {\n" 9378 " template <class T>\n" 9379 " auto foo(const std::string &str) &&noexcept -> int & {}\n" 9380 "};", 9381 BreakTemplate); 9382 9383 FormatStyle AlignLeftBreakTemplate = getLLVMStyle(); 9384 AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations = 9385 FormatStyle::BTDS_Yes; 9386 AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left; 9387 9388 verifyFormat("struct f {\n" 9389 " template <class T>\n" 9390 " int& foo(const std::string& str) & noexcept {}\n" 9391 "};", 9392 AlignLeftBreakTemplate); 9393 9394 verifyFormat("struct f {\n" 9395 " template <class T>\n" 9396 " int& foo(const std::string& str) && noexcept {}\n" 9397 "};", 9398 AlignLeftBreakTemplate); 9399 9400 verifyFormat("struct f {\n" 9401 " template <class T>\n" 9402 " int& foo(const std::string& str) const& noexcept {}\n" 9403 "};", 9404 AlignLeftBreakTemplate); 9405 9406 verifyFormat("struct f {\n" 9407 " template <class T>\n" 9408 " int& foo(const std::string& str) const&& noexcept {}\n" 9409 "};", 9410 AlignLeftBreakTemplate); 9411 9412 verifyFormat("struct f {\n" 9413 " template <class T>\n" 9414 " auto foo(const std::string& str) && noexcept -> int& {}\n" 9415 "};", 9416 AlignLeftBreakTemplate); 9417 9418 // The `&` in `Type&` should not be confused with a trailing `&` of 9419 // DEPRECATED(reason) member function. 9420 verifyFormat("struct f {\n" 9421 " template <class T>\n" 9422 " DEPRECATED(reason)\n" 9423 " Type &foo(arguments) {}\n" 9424 "};", 9425 BreakTemplate); 9426 9427 verifyFormat("struct f {\n" 9428 " template <class T>\n" 9429 " DEPRECATED(reason)\n" 9430 " Type& foo(arguments) {}\n" 9431 "};", 9432 AlignLeftBreakTemplate); 9433 9434 verifyFormat("void (*foopt)(int) = &func;"); 9435 } 9436 9437 TEST_F(FormatTest, UnderstandsNewAndDelete) { 9438 verifyFormat("void f() {\n" 9439 " A *a = new A;\n" 9440 " A *a = new (placement) A;\n" 9441 " delete a;\n" 9442 " delete (A *)a;\n" 9443 "}"); 9444 verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n" 9445 " typename aaaaaaaaaaaaaaaaaaaaaaaa();"); 9446 verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 9447 " new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n" 9448 " typename aaaaaaaaaaaaaaaaaaaaaaaa();"); 9449 verifyFormat("delete[] h->p;"); 9450 } 9451 9452 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) { 9453 verifyFormat("int *f(int *a) {}"); 9454 verifyFormat("int main(int argc, char **argv) {}"); 9455 verifyFormat("Test::Test(int b) : a(b * b) {}"); 9456 verifyIndependentOfContext("f(a, *a);"); 9457 verifyFormat("void g() { f(*a); }"); 9458 verifyIndependentOfContext("int a = b * 10;"); 9459 verifyIndependentOfContext("int a = 10 * b;"); 9460 verifyIndependentOfContext("int a = b * c;"); 9461 verifyIndependentOfContext("int a += b * c;"); 9462 verifyIndependentOfContext("int a -= b * c;"); 9463 verifyIndependentOfContext("int a *= b * c;"); 9464 verifyIndependentOfContext("int a /= b * c;"); 9465 verifyIndependentOfContext("int a = *b;"); 9466 verifyIndependentOfContext("int a = *b * c;"); 9467 verifyIndependentOfContext("int a = b * *c;"); 9468 verifyIndependentOfContext("int a = b * (10);"); 9469 verifyIndependentOfContext("S << b * (10);"); 9470 verifyIndependentOfContext("return 10 * b;"); 9471 verifyIndependentOfContext("return *b * *c;"); 9472 verifyIndependentOfContext("return a & ~b;"); 9473 verifyIndependentOfContext("f(b ? *c : *d);"); 9474 verifyIndependentOfContext("int a = b ? *c : *d;"); 9475 verifyIndependentOfContext("*b = a;"); 9476 verifyIndependentOfContext("a * ~b;"); 9477 verifyIndependentOfContext("a * !b;"); 9478 verifyIndependentOfContext("a * +b;"); 9479 verifyIndependentOfContext("a * -b;"); 9480 verifyIndependentOfContext("a * ++b;"); 9481 verifyIndependentOfContext("a * --b;"); 9482 verifyIndependentOfContext("a[4] * b;"); 9483 verifyIndependentOfContext("a[a * a] = 1;"); 9484 verifyIndependentOfContext("f() * b;"); 9485 verifyIndependentOfContext("a * [self dostuff];"); 9486 verifyIndependentOfContext("int x = a * (a + b);"); 9487 verifyIndependentOfContext("(a *)(a + b);"); 9488 verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;"); 9489 verifyIndependentOfContext("int *pa = (int *)&a;"); 9490 verifyIndependentOfContext("return sizeof(int **);"); 9491 verifyIndependentOfContext("return sizeof(int ******);"); 9492 verifyIndependentOfContext("return (int **&)a;"); 9493 verifyIndependentOfContext("f((*PointerToArray)[10]);"); 9494 verifyFormat("void f(Type (*parameter)[10]) {}"); 9495 verifyFormat("void f(Type (¶meter)[10]) {}"); 9496 verifyGoogleFormat("return sizeof(int**);"); 9497 verifyIndependentOfContext("Type **A = static_cast<Type **>(P);"); 9498 verifyGoogleFormat("Type** A = static_cast<Type**>(P);"); 9499 verifyFormat("auto a = [](int **&, int ***) {};"); 9500 verifyFormat("auto PointerBinding = [](const char *S) {};"); 9501 verifyFormat("typedef typeof(int(int, int)) *MyFunc;"); 9502 verifyFormat("[](const decltype(*a) &value) {}"); 9503 verifyFormat("[](const typeof(*a) &value) {}"); 9504 verifyFormat("[](const _Atomic(a *) &value) {}"); 9505 verifyFormat("[](const __underlying_type(a) &value) {}"); 9506 verifyFormat("decltype(a * b) F();"); 9507 verifyFormat("typeof(a * b) F();"); 9508 verifyFormat("#define MACRO() [](A *a) { return 1; }"); 9509 verifyFormat("Constructor() : member([](A *a, B *b) {}) {}"); 9510 verifyIndependentOfContext("typedef void (*f)(int *a);"); 9511 verifyIndependentOfContext("int i{a * b};"); 9512 verifyIndependentOfContext("aaa && aaa->f();"); 9513 verifyIndependentOfContext("int x = ~*p;"); 9514 verifyFormat("Constructor() : a(a), area(width * height) {}"); 9515 verifyFormat("Constructor() : a(a), area(a, width * height) {}"); 9516 verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}"); 9517 verifyFormat("void f() { f(a, c * d); }"); 9518 verifyFormat("void f() { f(new a(), c * d); }"); 9519 verifyFormat("void f(const MyOverride &override);"); 9520 verifyFormat("void f(const MyFinal &final);"); 9521 verifyIndependentOfContext("bool a = f() && override.f();"); 9522 verifyIndependentOfContext("bool a = f() && final.f();"); 9523 9524 verifyIndependentOfContext("InvalidRegions[*R] = 0;"); 9525 9526 verifyIndependentOfContext("A<int *> a;"); 9527 verifyIndependentOfContext("A<int **> a;"); 9528 verifyIndependentOfContext("A<int *, int *> a;"); 9529 verifyIndependentOfContext("A<int *[]> a;"); 9530 verifyIndependentOfContext( 9531 "const char *const p = reinterpret_cast<const char *const>(q);"); 9532 verifyIndependentOfContext("A<int **, int **> a;"); 9533 verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);"); 9534 verifyFormat("for (char **a = b; *a; ++a) {\n}"); 9535 verifyFormat("for (; a && b;) {\n}"); 9536 verifyFormat("bool foo = true && [] { return false; }();"); 9537 9538 verifyFormat( 9539 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 9540 " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 9541 9542 verifyGoogleFormat("int const* a = &b;"); 9543 verifyGoogleFormat("**outparam = 1;"); 9544 verifyGoogleFormat("*outparam = a * b;"); 9545 verifyGoogleFormat("int main(int argc, char** argv) {}"); 9546 verifyGoogleFormat("A<int*> a;"); 9547 verifyGoogleFormat("A<int**> a;"); 9548 verifyGoogleFormat("A<int*, int*> a;"); 9549 verifyGoogleFormat("A<int**, int**> a;"); 9550 verifyGoogleFormat("f(b ? *c : *d);"); 9551 verifyGoogleFormat("int a = b ? *c : *d;"); 9552 verifyGoogleFormat("Type* t = **x;"); 9553 verifyGoogleFormat("Type* t = *++*x;"); 9554 verifyGoogleFormat("*++*x;"); 9555 verifyGoogleFormat("Type* t = const_cast<T*>(&*x);"); 9556 verifyGoogleFormat("Type* t = x++ * y;"); 9557 verifyGoogleFormat( 9558 "const char* const p = reinterpret_cast<const char* const>(q);"); 9559 verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);"); 9560 verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);"); 9561 verifyGoogleFormat("template <typename T>\n" 9562 "void f(int i = 0, SomeType** temps = NULL);"); 9563 9564 FormatStyle Left = getLLVMStyle(); 9565 Left.PointerAlignment = FormatStyle::PAS_Left; 9566 verifyFormat("x = *a(x) = *a(y);", Left); 9567 verifyFormat("for (;; *a = b) {\n}", Left); 9568 verifyFormat("return *this += 1;", Left); 9569 verifyFormat("throw *x;", Left); 9570 verifyFormat("delete *x;", Left); 9571 verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left); 9572 verifyFormat("[](const decltype(*a)* ptr) {}", Left); 9573 verifyFormat("[](const typeof(*a)* ptr) {}", Left); 9574 verifyFormat("[](const _Atomic(a*)* ptr) {}", Left); 9575 verifyFormat("[](const __underlying_type(a)* ptr) {}", Left); 9576 verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left); 9577 verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left); 9578 verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left); 9579 verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left); 9580 9581 verifyIndependentOfContext("a = *(x + y);"); 9582 verifyIndependentOfContext("a = &(x + y);"); 9583 verifyIndependentOfContext("*(x + y).call();"); 9584 verifyIndependentOfContext("&(x + y)->call();"); 9585 verifyFormat("void f() { &(*I).first; }"); 9586 9587 verifyIndependentOfContext("f(b * /* confusing comment */ ++c);"); 9588 verifyFormat("f(* /* confusing comment */ foo);"); 9589 verifyFormat("void (* /*deleter*/)(const Slice &key, void *value)"); 9590 verifyFormat("void foo(int * // this is the first paramters\n" 9591 " ,\n" 9592 " int second);"); 9593 verifyFormat("double term = a * // first\n" 9594 " b;"); 9595 verifyFormat( 9596 "int *MyValues = {\n" 9597 " *A, // Operator detection might be confused by the '{'\n" 9598 " *BB // Operator detection might be confused by previous comment\n" 9599 "};"); 9600 9601 verifyIndependentOfContext("if (int *a = &b)"); 9602 verifyIndependentOfContext("if (int &a = *b)"); 9603 verifyIndependentOfContext("if (a & b[i])"); 9604 verifyIndependentOfContext("if constexpr (a & b[i])"); 9605 verifyIndependentOfContext("if CONSTEXPR (a & b[i])"); 9606 verifyIndependentOfContext("if (a * (b * c))"); 9607 verifyIndependentOfContext("if constexpr (a * (b * c))"); 9608 verifyIndependentOfContext("if CONSTEXPR (a * (b * c))"); 9609 verifyIndependentOfContext("if (a::b::c::d & b[i])"); 9610 verifyIndependentOfContext("if (*b[i])"); 9611 verifyIndependentOfContext("if (int *a = (&b))"); 9612 verifyIndependentOfContext("while (int *a = &b)"); 9613 verifyIndependentOfContext("while (a * (b * c))"); 9614 verifyIndependentOfContext("size = sizeof *a;"); 9615 verifyIndependentOfContext("if (a && (b = c))"); 9616 verifyFormat("void f() {\n" 9617 " for (const int &v : Values) {\n" 9618 " }\n" 9619 "}"); 9620 verifyFormat("for (int i = a * a; i < 10; ++i) {\n}"); 9621 verifyFormat("for (int i = 0; i < a * a; ++i) {\n}"); 9622 verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}"); 9623 9624 verifyFormat("#define A (!a * b)"); 9625 verifyFormat("#define MACRO \\\n" 9626 " int *i = a * b; \\\n" 9627 " void f(a *b);", 9628 getLLVMStyleWithColumns(19)); 9629 9630 verifyIndependentOfContext("A = new SomeType *[Length];"); 9631 verifyIndependentOfContext("A = new SomeType *[Length]();"); 9632 verifyIndependentOfContext("T **t = new T *;"); 9633 verifyIndependentOfContext("T **t = new T *();"); 9634 verifyGoogleFormat("A = new SomeType*[Length]();"); 9635 verifyGoogleFormat("A = new SomeType*[Length];"); 9636 verifyGoogleFormat("T** t = new T*;"); 9637 verifyGoogleFormat("T** t = new T*();"); 9638 9639 verifyFormat("STATIC_ASSERT((a & b) == 0);"); 9640 verifyFormat("STATIC_ASSERT(0 == (a & b));"); 9641 verifyFormat("template <bool a, bool b> " 9642 "typename t::if<x && y>::type f() {}"); 9643 verifyFormat("template <int *y> f() {}"); 9644 verifyFormat("vector<int *> v;"); 9645 verifyFormat("vector<int *const> v;"); 9646 verifyFormat("vector<int *const **const *> v;"); 9647 verifyFormat("vector<int *volatile> v;"); 9648 verifyFormat("vector<a *_Nonnull> v;"); 9649 verifyFormat("vector<a *_Nullable> v;"); 9650 verifyFormat("vector<a *_Null_unspecified> v;"); 9651 verifyFormat("vector<a *__ptr32> v;"); 9652 verifyFormat("vector<a *__ptr64> v;"); 9653 verifyFormat("vector<a *__capability> v;"); 9654 FormatStyle TypeMacros = getLLVMStyle(); 9655 TypeMacros.TypenameMacros = {"LIST"}; 9656 verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros); 9657 verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros); 9658 verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros); 9659 verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros); 9660 verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication 9661 9662 FormatStyle CustomQualifier = getLLVMStyle(); 9663 // Add identifiers that should not be parsed as a qualifier by default. 9664 CustomQualifier.AttributeMacros.push_back("__my_qualifier"); 9665 CustomQualifier.AttributeMacros.push_back("_My_qualifier"); 9666 CustomQualifier.AttributeMacros.push_back("my_other_qualifier"); 9667 verifyFormat("vector<a * __my_qualifier> parse_as_multiply;"); 9668 verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier); 9669 verifyFormat("vector<a * _My_qualifier> parse_as_multiply;"); 9670 verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier); 9671 verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;"); 9672 verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier); 9673 verifyFormat("vector<a * _NotAQualifier> v;"); 9674 verifyFormat("vector<a * __not_a_qualifier> v;"); 9675 verifyFormat("vector<a * b> v;"); 9676 verifyFormat("foo<b && false>();"); 9677 verifyFormat("foo<b & 1>();"); 9678 verifyFormat("decltype(*::std::declval<const T &>()) void F();"); 9679 verifyFormat("typeof(*::std::declval<const T &>()) void F();"); 9680 verifyFormat("_Atomic(*::std::declval<const T &>()) void F();"); 9681 verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();"); 9682 verifyFormat( 9683 "template <class T, class = typename std::enable_if<\n" 9684 " std::is_integral<T>::value &&\n" 9685 " (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n" 9686 "void F();", 9687 getLLVMStyleWithColumns(70)); 9688 verifyFormat("template <class T,\n" 9689 " class = typename std::enable_if<\n" 9690 " std::is_integral<T>::value &&\n" 9691 " (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n" 9692 " class U>\n" 9693 "void F();", 9694 getLLVMStyleWithColumns(70)); 9695 verifyFormat( 9696 "template <class T,\n" 9697 " class = typename ::std::enable_if<\n" 9698 " ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n" 9699 "void F();", 9700 getGoogleStyleWithColumns(68)); 9701 9702 verifyIndependentOfContext("MACRO(int *i);"); 9703 verifyIndependentOfContext("MACRO(auto *a);"); 9704 verifyIndependentOfContext("MACRO(const A *a);"); 9705 verifyIndependentOfContext("MACRO(_Atomic(A) *a);"); 9706 verifyIndependentOfContext("MACRO(decltype(A) *a);"); 9707 verifyIndependentOfContext("MACRO(typeof(A) *a);"); 9708 verifyIndependentOfContext("MACRO(__underlying_type(A) *a);"); 9709 verifyIndependentOfContext("MACRO(A *const a);"); 9710 verifyIndependentOfContext("MACRO(A *restrict a);"); 9711 verifyIndependentOfContext("MACRO(A *__restrict__ a);"); 9712 verifyIndependentOfContext("MACRO(A *__restrict a);"); 9713 verifyIndependentOfContext("MACRO(A *volatile a);"); 9714 verifyIndependentOfContext("MACRO(A *__volatile a);"); 9715 verifyIndependentOfContext("MACRO(A *__volatile__ a);"); 9716 verifyIndependentOfContext("MACRO(A *_Nonnull a);"); 9717 verifyIndependentOfContext("MACRO(A *_Nullable a);"); 9718 verifyIndependentOfContext("MACRO(A *_Null_unspecified a);"); 9719 verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);"); 9720 verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);"); 9721 verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);"); 9722 verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);"); 9723 verifyIndependentOfContext("MACRO(A *__ptr32 a);"); 9724 verifyIndependentOfContext("MACRO(A *__ptr64 a);"); 9725 verifyIndependentOfContext("MACRO(A *__capability);"); 9726 verifyIndependentOfContext("MACRO(A &__capability);"); 9727 verifyFormat("MACRO(A *__my_qualifier);"); // type declaration 9728 verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication 9729 // If we add __my_qualifier to AttributeMacros it should always be parsed as 9730 // a type declaration: 9731 verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier); 9732 verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier); 9733 // Also check that TypenameMacros prevents parsing it as multiplication: 9734 verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication 9735 verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type 9736 9737 verifyIndependentOfContext("MACRO('0' <= c && c <= '9');"); 9738 verifyFormat("void f() { f(float{1}, a * a); }"); 9739 verifyFormat("void f() { f(float(1), a * a); }"); 9740 9741 verifyFormat("f((void (*)(int))g);"); 9742 verifyFormat("f((void (&)(int))g);"); 9743 verifyFormat("f((void (^)(int))g);"); 9744 9745 // FIXME: Is there a way to make this work? 9746 // verifyIndependentOfContext("MACRO(A *a);"); 9747 verifyFormat("MACRO(A &B);"); 9748 verifyFormat("MACRO(A *B);"); 9749 verifyFormat("void f() { MACRO(A * B); }"); 9750 verifyFormat("void f() { MACRO(A & B); }"); 9751 9752 // This lambda was mis-formatted after D88956 (treating it as a binop): 9753 verifyFormat("auto x = [](const decltype(x) &ptr) {};"); 9754 verifyFormat("auto x = [](const decltype(x) *ptr) {};"); 9755 verifyFormat("#define lambda [](const decltype(x) &ptr) {}"); 9756 verifyFormat("#define lambda [](const decltype(x) *ptr) {}"); 9757 9758 verifyFormat("DatumHandle const *operator->() const { return input_; }"); 9759 verifyFormat("return options != nullptr && operator==(*options);"); 9760 9761 EXPECT_EQ("#define OP(x) \\\n" 9762 " ostream &operator<<(ostream &s, const A &a) { \\\n" 9763 " return s << a.DebugString(); \\\n" 9764 " }", 9765 format("#define OP(x) \\\n" 9766 " ostream &operator<<(ostream &s, const A &a) { \\\n" 9767 " return s << a.DebugString(); \\\n" 9768 " }", 9769 getLLVMStyleWithColumns(50))); 9770 9771 // FIXME: We cannot handle this case yet; we might be able to figure out that 9772 // foo<x> d > v; doesn't make sense. 9773 verifyFormat("foo<a<b && c> d> v;"); 9774 9775 FormatStyle PointerMiddle = getLLVMStyle(); 9776 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle; 9777 verifyFormat("delete *x;", PointerMiddle); 9778 verifyFormat("int * x;", PointerMiddle); 9779 verifyFormat("int *[] x;", PointerMiddle); 9780 verifyFormat("template <int * y> f() {}", PointerMiddle); 9781 verifyFormat("int * f(int * a) {}", PointerMiddle); 9782 verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle); 9783 verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle); 9784 verifyFormat("A<int *> a;", PointerMiddle); 9785 verifyFormat("A<int **> a;", PointerMiddle); 9786 verifyFormat("A<int *, int *> a;", PointerMiddle); 9787 verifyFormat("A<int *[]> a;", PointerMiddle); 9788 verifyFormat("A = new SomeType *[Length]();", PointerMiddle); 9789 verifyFormat("A = new SomeType *[Length];", PointerMiddle); 9790 verifyFormat("T ** t = new T *;", PointerMiddle); 9791 9792 // Member function reference qualifiers aren't binary operators. 9793 verifyFormat("string // break\n" 9794 "operator()() & {}"); 9795 verifyFormat("string // break\n" 9796 "operator()() && {}"); 9797 verifyGoogleFormat("template <typename T>\n" 9798 "auto x() & -> int {}"); 9799 9800 // Should be binary operators when used as an argument expression (overloaded 9801 // operator invoked as a member function). 9802 verifyFormat("void f() { a.operator()(a * a); }"); 9803 verifyFormat("void f() { a->operator()(a & a); }"); 9804 verifyFormat("void f() { a.operator()(*a & *a); }"); 9805 verifyFormat("void f() { a->operator()(*a * *a); }"); 9806 9807 verifyFormat("int operator()(T (&&)[N]) { return 1; }"); 9808 verifyFormat("int operator()(T (&)[N]) { return 0; }"); 9809 } 9810 9811 TEST_F(FormatTest, UnderstandsAttributes) { 9812 verifyFormat("SomeType s __attribute__((unused)) (InitValue);"); 9813 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n" 9814 "aaaaaaaaaaaaaaaaaaaaaaa(int i);"); 9815 FormatStyle AfterType = getLLVMStyle(); 9816 AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 9817 verifyFormat("__attribute__((nodebug)) void\n" 9818 "foo() {}\n", 9819 AfterType); 9820 verifyFormat("__unused void\n" 9821 "foo() {}", 9822 AfterType); 9823 9824 FormatStyle CustomAttrs = getLLVMStyle(); 9825 CustomAttrs.AttributeMacros.push_back("__unused"); 9826 CustomAttrs.AttributeMacros.push_back("__attr1"); 9827 CustomAttrs.AttributeMacros.push_back("__attr2"); 9828 CustomAttrs.AttributeMacros.push_back("no_underscore_attr"); 9829 verifyFormat("vector<SomeType *__attribute((foo))> v;"); 9830 verifyFormat("vector<SomeType *__attribute__((foo))> v;"); 9831 verifyFormat("vector<SomeType * __not_attribute__((foo))> v;"); 9832 // Check that it is parsed as a multiplication without AttributeMacros and 9833 // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros. 9834 verifyFormat("vector<SomeType * __attr1> v;"); 9835 verifyFormat("vector<SomeType __attr1 *> v;"); 9836 verifyFormat("vector<SomeType __attr1 *const> v;"); 9837 verifyFormat("vector<SomeType __attr1 * __attr2> v;"); 9838 verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs); 9839 verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs); 9840 verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs); 9841 verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs); 9842 verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs); 9843 verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs); 9844 verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs); 9845 9846 // Check that these are not parsed as function declarations: 9847 CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 9848 CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman; 9849 verifyFormat("SomeType s(InitValue);", CustomAttrs); 9850 verifyFormat("SomeType s{InitValue};", CustomAttrs); 9851 verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs); 9852 verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs); 9853 verifyFormat("SomeType s __unused(InitValue);", CustomAttrs); 9854 verifyFormat("SomeType s __unused{InitValue};", CustomAttrs); 9855 verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs); 9856 verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs); 9857 } 9858 9859 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) { 9860 // Check that qualifiers on pointers don't break parsing of casts. 9861 verifyFormat("x = (foo *const)*v;"); 9862 verifyFormat("x = (foo *volatile)*v;"); 9863 verifyFormat("x = (foo *restrict)*v;"); 9864 verifyFormat("x = (foo *__attribute__((foo)))*v;"); 9865 verifyFormat("x = (foo *_Nonnull)*v;"); 9866 verifyFormat("x = (foo *_Nullable)*v;"); 9867 verifyFormat("x = (foo *_Null_unspecified)*v;"); 9868 verifyFormat("x = (foo *_Nonnull)*v;"); 9869 verifyFormat("x = (foo *[[clang::attr]])*v;"); 9870 verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;"); 9871 verifyFormat("x = (foo *__ptr32)*v;"); 9872 verifyFormat("x = (foo *__ptr64)*v;"); 9873 verifyFormat("x = (foo *__capability)*v;"); 9874 9875 // Check that we handle multiple trailing qualifiers and skip them all to 9876 // determine that the expression is a cast to a pointer type. 9877 FormatStyle LongPointerRight = getLLVMStyleWithColumns(999); 9878 FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999); 9879 LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left; 9880 StringRef AllQualifiers = 9881 "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified " 9882 "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability"; 9883 verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight); 9884 verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft); 9885 9886 // Also check that address-of is not parsed as a binary bitwise-and: 9887 verifyFormat("x = (foo *const)&v;"); 9888 verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight); 9889 verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft); 9890 9891 // Check custom qualifiers: 9892 FormatStyle CustomQualifier = getLLVMStyleWithColumns(999); 9893 CustomQualifier.AttributeMacros.push_back("__my_qualifier"); 9894 verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier. 9895 verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier); 9896 verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(), 9897 CustomQualifier); 9898 verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(), 9899 CustomQualifier); 9900 9901 // Check that unknown identifiers result in binary operator parsing: 9902 verifyFormat("x = (foo * __unknown_qualifier) * v;"); 9903 verifyFormat("x = (foo * __unknown_qualifier) & v;"); 9904 } 9905 9906 TEST_F(FormatTest, UnderstandsSquareAttributes) { 9907 verifyFormat("SomeType s [[unused]] (InitValue);"); 9908 verifyFormat("SomeType s [[gnu::unused]] (InitValue);"); 9909 verifyFormat("SomeType s [[using gnu: unused]] (InitValue);"); 9910 verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}"); 9911 verifyFormat("void f() [[deprecated(\"so sorry\")]];"); 9912 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 9913 " [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);"); 9914 verifyFormat("[[nodiscard]] bool f() { return false; }"); 9915 verifyFormat("class [[nodiscard]] f {\npublic:\n f() {}\n}"); 9916 verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n f() {}\n}"); 9917 verifyFormat("class [[gnu::unused]] f {\npublic:\n f() {}\n}"); 9918 9919 // Make sure we do not mistake attributes for array subscripts. 9920 verifyFormat("int a() {}\n" 9921 "[[unused]] int b() {}\n"); 9922 verifyFormat("NSArray *arr;\n" 9923 "arr[[Foo() bar]];"); 9924 9925 // On the other hand, we still need to correctly find array subscripts. 9926 verifyFormat("int a = std::vector<int>{1, 2, 3}[0];"); 9927 9928 // Make sure that we do not mistake Objective-C method inside array literals 9929 // as attributes, even if those method names are also keywords. 9930 verifyFormat("@[ [foo bar] ];"); 9931 verifyFormat("@[ [NSArray class] ];"); 9932 verifyFormat("@[ [foo enum] ];"); 9933 9934 verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }"); 9935 9936 // Make sure we do not parse attributes as lambda introducers. 9937 FormatStyle MultiLineFunctions = getLLVMStyle(); 9938 MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 9939 verifyFormat("[[unused]] int b() {\n" 9940 " return 42;\n" 9941 "}\n", 9942 MultiLineFunctions); 9943 } 9944 9945 TEST_F(FormatTest, AttributeClass) { 9946 FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp); 9947 verifyFormat("class S {\n" 9948 " S(S&&) = default;\n" 9949 "};", 9950 Style); 9951 verifyFormat("class [[nodiscard]] S {\n" 9952 " S(S&&) = default;\n" 9953 "};", 9954 Style); 9955 verifyFormat("class __attribute((maybeunused)) S {\n" 9956 " S(S&&) = default;\n" 9957 "};", 9958 Style); 9959 verifyFormat("struct S {\n" 9960 " S(S&&) = default;\n" 9961 "};", 9962 Style); 9963 verifyFormat("struct [[nodiscard]] S {\n" 9964 " S(S&&) = default;\n" 9965 "};", 9966 Style); 9967 } 9968 9969 TEST_F(FormatTest, AttributesAfterMacro) { 9970 FormatStyle Style = getLLVMStyle(); 9971 verifyFormat("MACRO;\n" 9972 "__attribute__((maybe_unused)) int foo() {\n" 9973 " //...\n" 9974 "}"); 9975 9976 verifyFormat("MACRO;\n" 9977 "[[nodiscard]] int foo() {\n" 9978 " //...\n" 9979 "}"); 9980 9981 EXPECT_EQ("MACRO\n\n" 9982 "__attribute__((maybe_unused)) int foo() {\n" 9983 " //...\n" 9984 "}", 9985 format("MACRO\n\n" 9986 "__attribute__((maybe_unused)) int foo() {\n" 9987 " //...\n" 9988 "}")); 9989 9990 EXPECT_EQ("MACRO\n\n" 9991 "[[nodiscard]] int foo() {\n" 9992 " //...\n" 9993 "}", 9994 format("MACRO\n\n" 9995 "[[nodiscard]] int foo() {\n" 9996 " //...\n" 9997 "}")); 9998 } 9999 10000 TEST_F(FormatTest, AttributePenaltyBreaking) { 10001 FormatStyle Style = getLLVMStyle(); 10002 verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n" 10003 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}", 10004 Style); 10005 verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n" 10006 " [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}", 10007 Style); 10008 verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const " 10009 "shared_ptr<ALongTypeName> &C d) {\n}", 10010 Style); 10011 } 10012 10013 TEST_F(FormatTest, UnderstandsEllipsis) { 10014 FormatStyle Style = getLLVMStyle(); 10015 verifyFormat("int printf(const char *fmt, ...);"); 10016 verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }"); 10017 verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}"); 10018 10019 verifyFormat("template <int *...PP> a;", Style); 10020 10021 Style.PointerAlignment = FormatStyle::PAS_Left; 10022 verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style); 10023 10024 verifyFormat("template <int*... PP> a;", Style); 10025 10026 Style.PointerAlignment = FormatStyle::PAS_Middle; 10027 verifyFormat("template <int *... PP> a;", Style); 10028 } 10029 10030 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) { 10031 EXPECT_EQ("int *a;\n" 10032 "int *a;\n" 10033 "int *a;", 10034 format("int *a;\n" 10035 "int* a;\n" 10036 "int *a;", 10037 getGoogleStyle())); 10038 EXPECT_EQ("int* a;\n" 10039 "int* a;\n" 10040 "int* a;", 10041 format("int* a;\n" 10042 "int* a;\n" 10043 "int *a;", 10044 getGoogleStyle())); 10045 EXPECT_EQ("int *a;\n" 10046 "int *a;\n" 10047 "int *a;", 10048 format("int *a;\n" 10049 "int * a;\n" 10050 "int * a;", 10051 getGoogleStyle())); 10052 EXPECT_EQ("auto x = [] {\n" 10053 " int *a;\n" 10054 " int *a;\n" 10055 " int *a;\n" 10056 "};", 10057 format("auto x=[]{int *a;\n" 10058 "int * a;\n" 10059 "int * a;};", 10060 getGoogleStyle())); 10061 } 10062 10063 TEST_F(FormatTest, UnderstandsRvalueReferences) { 10064 verifyFormat("int f(int &&a) {}"); 10065 verifyFormat("int f(int a, char &&b) {}"); 10066 verifyFormat("void f() { int &&a = b; }"); 10067 verifyGoogleFormat("int f(int a, char&& b) {}"); 10068 verifyGoogleFormat("void f() { int&& a = b; }"); 10069 10070 verifyIndependentOfContext("A<int &&> a;"); 10071 verifyIndependentOfContext("A<int &&, int &&> a;"); 10072 verifyGoogleFormat("A<int&&> a;"); 10073 verifyGoogleFormat("A<int&&, int&&> a;"); 10074 10075 // Not rvalue references: 10076 verifyFormat("template <bool B, bool C> class A {\n" 10077 " static_assert(B && C, \"Something is wrong\");\n" 10078 "};"); 10079 verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))"); 10080 verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))"); 10081 verifyFormat("#define A(a, b) (a && b)"); 10082 } 10083 10084 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) { 10085 verifyFormat("void f() {\n" 10086 " x[aaaaaaaaa -\n" 10087 " b] = 23;\n" 10088 "}", 10089 getLLVMStyleWithColumns(15)); 10090 } 10091 10092 TEST_F(FormatTest, FormatsCasts) { 10093 verifyFormat("Type *A = static_cast<Type *>(P);"); 10094 verifyFormat("Type *A = (Type *)P;"); 10095 verifyFormat("Type *A = (vector<Type *, int *>)P;"); 10096 verifyFormat("int a = (int)(2.0f);"); 10097 verifyFormat("int a = (int)2.0f;"); 10098 verifyFormat("x[(int32)y];"); 10099 verifyFormat("x = (int32)y;"); 10100 verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)"); 10101 verifyFormat("int a = (int)*b;"); 10102 verifyFormat("int a = (int)2.0f;"); 10103 verifyFormat("int a = (int)~0;"); 10104 verifyFormat("int a = (int)++a;"); 10105 verifyFormat("int a = (int)sizeof(int);"); 10106 verifyFormat("int a = (int)+2;"); 10107 verifyFormat("my_int a = (my_int)2.0f;"); 10108 verifyFormat("my_int a = (my_int)sizeof(int);"); 10109 verifyFormat("return (my_int)aaa;"); 10110 verifyFormat("#define x ((int)-1)"); 10111 verifyFormat("#define LENGTH(x, y) (x) - (y) + 1"); 10112 verifyFormat("#define p(q) ((int *)&q)"); 10113 verifyFormat("fn(a)(b) + 1;"); 10114 10115 verifyFormat("void f() { my_int a = (my_int)*b; }"); 10116 verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }"); 10117 verifyFormat("my_int a = (my_int)~0;"); 10118 verifyFormat("my_int a = (my_int)++a;"); 10119 verifyFormat("my_int a = (my_int)-2;"); 10120 verifyFormat("my_int a = (my_int)1;"); 10121 verifyFormat("my_int a = (my_int *)1;"); 10122 verifyFormat("my_int a = (const my_int)-1;"); 10123 verifyFormat("my_int a = (const my_int *)-1;"); 10124 verifyFormat("my_int a = (my_int)(my_int)-1;"); 10125 verifyFormat("my_int a = (ns::my_int)-2;"); 10126 verifyFormat("case (my_int)ONE:"); 10127 verifyFormat("auto x = (X)this;"); 10128 // Casts in Obj-C style calls used to not be recognized as such. 10129 verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle()); 10130 10131 // FIXME: single value wrapped with paren will be treated as cast. 10132 verifyFormat("void f(int i = (kValue)*kMask) {}"); 10133 10134 verifyFormat("{ (void)F; }"); 10135 10136 // Don't break after a cast's 10137 verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" 10138 " (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n" 10139 " bbbbbbbbbbbbbbbbbbbbbb);"); 10140 10141 // These are not casts. 10142 verifyFormat("void f(int *) {}"); 10143 verifyFormat("f(foo)->b;"); 10144 verifyFormat("f(foo).b;"); 10145 verifyFormat("f(foo)(b);"); 10146 verifyFormat("f(foo)[b];"); 10147 verifyFormat("[](foo) { return 4; }(bar);"); 10148 verifyFormat("(*funptr)(foo)[4];"); 10149 verifyFormat("funptrs[4](foo)[4];"); 10150 verifyFormat("void f(int *);"); 10151 verifyFormat("void f(int *) = 0;"); 10152 verifyFormat("void f(SmallVector<int>) {}"); 10153 verifyFormat("void f(SmallVector<int>);"); 10154 verifyFormat("void f(SmallVector<int>) = 0;"); 10155 verifyFormat("void f(int i = (kA * kB) & kMask) {}"); 10156 verifyFormat("int a = sizeof(int) * b;"); 10157 verifyFormat("int a = alignof(int) * b;", getGoogleStyle()); 10158 verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;"); 10159 verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");"); 10160 verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;"); 10161 10162 // These are not casts, but at some point were confused with casts. 10163 verifyFormat("virtual void foo(int *) override;"); 10164 verifyFormat("virtual void foo(char &) const;"); 10165 verifyFormat("virtual void foo(int *a, char *) const;"); 10166 verifyFormat("int a = sizeof(int *) + b;"); 10167 verifyFormat("int a = alignof(int *) + b;", getGoogleStyle()); 10168 verifyFormat("bool b = f(g<int>) && c;"); 10169 verifyFormat("typedef void (*f)(int i) func;"); 10170 verifyFormat("void operator++(int) noexcept;"); 10171 verifyFormat("void operator++(int &) noexcept;"); 10172 verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t " 10173 "&) noexcept;"); 10174 verifyFormat( 10175 "void operator delete(std::size_t, const std::nothrow_t &) noexcept;"); 10176 verifyFormat("void operator delete(const std::nothrow_t &) noexcept;"); 10177 verifyFormat("void operator delete(std::nothrow_t &) noexcept;"); 10178 verifyFormat("void operator delete(nothrow_t &) noexcept;"); 10179 verifyFormat("void operator delete(foo &) noexcept;"); 10180 verifyFormat("void operator delete(foo) noexcept;"); 10181 verifyFormat("void operator delete(int) noexcept;"); 10182 verifyFormat("void operator delete(int &) noexcept;"); 10183 verifyFormat("void operator delete(int &) volatile noexcept;"); 10184 verifyFormat("void operator delete(int &) const"); 10185 verifyFormat("void operator delete(int &) = default"); 10186 verifyFormat("void operator delete(int &) = delete"); 10187 verifyFormat("void operator delete(int &) [[noreturn]]"); 10188 verifyFormat("void operator delete(int &) throw();"); 10189 verifyFormat("void operator delete(int &) throw(int);"); 10190 verifyFormat("auto operator delete(int &) -> int;"); 10191 verifyFormat("auto operator delete(int &) override"); 10192 verifyFormat("auto operator delete(int &) final"); 10193 10194 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n" 10195 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); 10196 // FIXME: The indentation here is not ideal. 10197 verifyFormat( 10198 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10199 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n" 10200 " [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];"); 10201 } 10202 10203 TEST_F(FormatTest, FormatsFunctionTypes) { 10204 verifyFormat("A<bool()> a;"); 10205 verifyFormat("A<SomeType()> a;"); 10206 verifyFormat("A<void (*)(int, std::string)> a;"); 10207 verifyFormat("A<void *(int)>;"); 10208 verifyFormat("void *(*a)(int *, SomeType *);"); 10209 verifyFormat("int (*func)(void *);"); 10210 verifyFormat("void f() { int (*func)(void *); }"); 10211 verifyFormat("template <class CallbackClass>\n" 10212 "using MyCallback = void (CallbackClass::*)(SomeObject *Data);"); 10213 10214 verifyGoogleFormat("A<void*(int*, SomeType*)>;"); 10215 verifyGoogleFormat("void* (*a)(int);"); 10216 verifyGoogleFormat( 10217 "template <class CallbackClass>\n" 10218 "using MyCallback = void (CallbackClass::*)(SomeObject* Data);"); 10219 10220 // Other constructs can look somewhat like function types: 10221 verifyFormat("A<sizeof(*x)> a;"); 10222 verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)"); 10223 verifyFormat("some_var = function(*some_pointer_var)[0];"); 10224 verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }"); 10225 verifyFormat("int x = f(&h)();"); 10226 verifyFormat("returnsFunction(¶m1, ¶m2)(param);"); 10227 verifyFormat("std::function<\n" 10228 " LooooooooooongTemplatedType<\n" 10229 " SomeType>*(\n" 10230 " LooooooooooooooooongType type)>\n" 10231 " function;", 10232 getGoogleStyleWithColumns(40)); 10233 } 10234 10235 TEST_F(FormatTest, FormatsPointersToArrayTypes) { 10236 verifyFormat("A (*foo_)[6];"); 10237 verifyFormat("vector<int> (*foo_)[6];"); 10238 } 10239 10240 TEST_F(FormatTest, BreaksLongVariableDeclarations) { 10241 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10242 " LoooooooooooooooooooooooooooooooooooooooongVariable;"); 10243 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n" 10244 " LoooooooooooooooooooooooooooooooooooooooongVariable;"); 10245 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10246 " *LoooooooooooooooooooooooooooooooooooooooongVariable;"); 10247 10248 // Different ways of ()-initializiation. 10249 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10250 " LoooooooooooooooooooooooooooooooooooooooongVariable(1);"); 10251 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10252 " LoooooooooooooooooooooooooooooooooooooooongVariable(a);"); 10253 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10254 " LoooooooooooooooooooooooooooooooooooooooongVariable({});"); 10255 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n" 10256 " LoooooooooooooooooooooooooooooooooooooongVariable([A a]);"); 10257 10258 // Lambdas should not confuse the variable declaration heuristic. 10259 verifyFormat("LooooooooooooooooongType\n" 10260 " variable(nullptr, [](A *a) {});", 10261 getLLVMStyleWithColumns(40)); 10262 } 10263 10264 TEST_F(FormatTest, BreaksLongDeclarations) { 10265 verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n" 10266 " AnotherNameForTheLongType;"); 10267 verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n" 10268 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); 10269 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10270 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();"); 10271 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n" 10272 "LoooooooooooooooooooooooooooooooongFunctionDeclaration();"); 10273 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10274 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10275 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n" 10276 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10277 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n" 10278 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10279 verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n" 10280 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10281 verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n" 10282 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10283 verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n" 10284 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10285 verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n" 10286 "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}"); 10287 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10288 "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);"); 10289 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10290 "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}"); 10291 FormatStyle Indented = getLLVMStyle(); 10292 Indented.IndentWrappedFunctionNames = true; 10293 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10294 " LoooooooooooooooooooooooooooooooongFunctionDeclaration();", 10295 Indented); 10296 verifyFormat( 10297 "LoooooooooooooooooooooooooooooooooooooooongReturnType\n" 10298 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 10299 Indented); 10300 verifyFormat( 10301 "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n" 10302 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 10303 Indented); 10304 verifyFormat( 10305 "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n" 10306 " LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}", 10307 Indented); 10308 10309 // FIXME: Without the comment, this breaks after "(". 10310 verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType // break\n" 10311 " (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();", 10312 getGoogleStyle()); 10313 10314 verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n" 10315 " int LoooooooooooooooooooongParam2) {}"); 10316 verifyFormat( 10317 "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n" 10318 " SourceLocation L, IdentifierIn *II,\n" 10319 " Type *T) {}"); 10320 verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n" 10321 "ReallyReaaallyLongFunctionName(\n" 10322 " const std::string &SomeParameter,\n" 10323 " const SomeType<string, SomeOtherTemplateParameter>\n" 10324 " &ReallyReallyLongParameterName,\n" 10325 " const SomeType<string, SomeOtherTemplateParameter>\n" 10326 " &AnotherLongParameterName) {}"); 10327 verifyFormat("template <typename A>\n" 10328 "SomeLoooooooooooooooooooooongType<\n" 10329 " typename some_namespace::SomeOtherType<A>::Type>\n" 10330 "Function() {}"); 10331 10332 verifyGoogleFormat( 10333 "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n" 10334 " aaaaaaaaaaaaaaaaaaaaaaa;"); 10335 verifyGoogleFormat( 10336 "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n" 10337 " SourceLocation L) {}"); 10338 verifyGoogleFormat( 10339 "some_namespace::LongReturnType\n" 10340 "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n" 10341 " int first_long_parameter, int second_parameter) {}"); 10342 10343 verifyGoogleFormat("template <typename T>\n" 10344 "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n" 10345 "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}"); 10346 verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 10347 " int aaaaaaaaaaaaaaaaaaaaaaa);"); 10348 10349 verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n" 10350 " const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 10351 " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 10352 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 10353 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n" 10354 " aaaaaaaaaaaaaaaaaaaaaaaa);"); 10355 verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 10356 " vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" 10357 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n" 10358 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 10359 10360 verifyFormat("template <typename T> // Templates on own line.\n" 10361 "static int // Some comment.\n" 10362 "MyFunction(int a);", 10363 getLLVMStyle()); 10364 } 10365 10366 TEST_F(FormatTest, FormatsAccessModifiers) { 10367 FormatStyle Style = getLLVMStyle(); 10368 EXPECT_EQ(Style.EmptyLineBeforeAccessModifier, 10369 FormatStyle::ELBAMS_LogicalBlock); 10370 verifyFormat("struct foo {\n" 10371 "private:\n" 10372 " void f() {}\n" 10373 "\n" 10374 "private:\n" 10375 " int i;\n" 10376 "\n" 10377 "protected:\n" 10378 " int j;\n" 10379 "};\n", 10380 Style); 10381 verifyFormat("struct foo {\n" 10382 "private:\n" 10383 " void f() {}\n" 10384 "\n" 10385 "private:\n" 10386 " int i;\n" 10387 "\n" 10388 "protected:\n" 10389 " int j;\n" 10390 "};\n", 10391 "struct foo {\n" 10392 "private:\n" 10393 " void f() {}\n" 10394 "private:\n" 10395 " int i;\n" 10396 "protected:\n" 10397 " int j;\n" 10398 "};\n", 10399 Style); 10400 verifyFormat("struct foo { /* comment */\n" 10401 "private:\n" 10402 " int i;\n" 10403 " // comment\n" 10404 "private:\n" 10405 " int j;\n" 10406 "};\n", 10407 Style); 10408 verifyFormat("struct foo {\n" 10409 "#ifdef FOO\n" 10410 "#endif\n" 10411 "private:\n" 10412 " int i;\n" 10413 "#ifdef FOO\n" 10414 "private:\n" 10415 "#endif\n" 10416 " int j;\n" 10417 "};\n", 10418 Style); 10419 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 10420 verifyFormat("struct foo {\n" 10421 "private:\n" 10422 " void f() {}\n" 10423 "private:\n" 10424 " int i;\n" 10425 "protected:\n" 10426 " int j;\n" 10427 "};\n", 10428 Style); 10429 verifyFormat("struct foo {\n" 10430 "private:\n" 10431 " void f() {}\n" 10432 "private:\n" 10433 " int i;\n" 10434 "protected:\n" 10435 " int j;\n" 10436 "};\n", 10437 "struct foo {\n" 10438 "\n" 10439 "private:\n" 10440 " void f() {}\n" 10441 "\n" 10442 "private:\n" 10443 " int i;\n" 10444 "\n" 10445 "protected:\n" 10446 " int j;\n" 10447 "};\n", 10448 Style); 10449 verifyFormat("struct foo { /* comment */\n" 10450 "private:\n" 10451 " int i;\n" 10452 " // comment\n" 10453 "private:\n" 10454 " int j;\n" 10455 "};\n", 10456 "struct foo { /* comment */\n" 10457 "\n" 10458 "private:\n" 10459 " int i;\n" 10460 " // comment\n" 10461 "\n" 10462 "private:\n" 10463 " int j;\n" 10464 "};\n", 10465 Style); 10466 verifyFormat("struct foo {\n" 10467 "#ifdef FOO\n" 10468 "#endif\n" 10469 "private:\n" 10470 " int i;\n" 10471 "#ifdef FOO\n" 10472 "private:\n" 10473 "#endif\n" 10474 " int j;\n" 10475 "};\n", 10476 "struct foo {\n" 10477 "#ifdef FOO\n" 10478 "#endif\n" 10479 "\n" 10480 "private:\n" 10481 " int i;\n" 10482 "#ifdef FOO\n" 10483 "\n" 10484 "private:\n" 10485 "#endif\n" 10486 " int j;\n" 10487 "};\n", 10488 Style); 10489 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 10490 verifyFormat("struct foo {\n" 10491 "private:\n" 10492 " void f() {}\n" 10493 "\n" 10494 "private:\n" 10495 " int i;\n" 10496 "\n" 10497 "protected:\n" 10498 " int j;\n" 10499 "};\n", 10500 Style); 10501 verifyFormat("struct foo {\n" 10502 "private:\n" 10503 " void f() {}\n" 10504 "\n" 10505 "private:\n" 10506 " int i;\n" 10507 "\n" 10508 "protected:\n" 10509 " int j;\n" 10510 "};\n", 10511 "struct foo {\n" 10512 "private:\n" 10513 " void f() {}\n" 10514 "private:\n" 10515 " int i;\n" 10516 "protected:\n" 10517 " int j;\n" 10518 "};\n", 10519 Style); 10520 verifyFormat("struct foo { /* comment */\n" 10521 "private:\n" 10522 " int i;\n" 10523 " // comment\n" 10524 "\n" 10525 "private:\n" 10526 " int j;\n" 10527 "};\n", 10528 "struct foo { /* comment */\n" 10529 "private:\n" 10530 " int i;\n" 10531 " // comment\n" 10532 "\n" 10533 "private:\n" 10534 " int j;\n" 10535 "};\n", 10536 Style); 10537 verifyFormat("struct foo {\n" 10538 "#ifdef FOO\n" 10539 "#endif\n" 10540 "\n" 10541 "private:\n" 10542 " int i;\n" 10543 "#ifdef FOO\n" 10544 "\n" 10545 "private:\n" 10546 "#endif\n" 10547 " int j;\n" 10548 "};\n", 10549 "struct foo {\n" 10550 "#ifdef FOO\n" 10551 "#endif\n" 10552 "private:\n" 10553 " int i;\n" 10554 "#ifdef FOO\n" 10555 "private:\n" 10556 "#endif\n" 10557 " int j;\n" 10558 "};\n", 10559 Style); 10560 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 10561 EXPECT_EQ("struct foo {\n" 10562 "\n" 10563 "private:\n" 10564 " void f() {}\n" 10565 "\n" 10566 "private:\n" 10567 " int i;\n" 10568 "\n" 10569 "protected:\n" 10570 " int j;\n" 10571 "};\n", 10572 format("struct foo {\n" 10573 "\n" 10574 "private:\n" 10575 " void f() {}\n" 10576 "\n" 10577 "private:\n" 10578 " int i;\n" 10579 "\n" 10580 "protected:\n" 10581 " int j;\n" 10582 "};\n", 10583 Style)); 10584 verifyFormat("struct foo {\n" 10585 "private:\n" 10586 " void f() {}\n" 10587 "private:\n" 10588 " int i;\n" 10589 "protected:\n" 10590 " int j;\n" 10591 "};\n", 10592 Style); 10593 EXPECT_EQ("struct foo { /* comment */\n" 10594 "\n" 10595 "private:\n" 10596 " int i;\n" 10597 " // comment\n" 10598 "\n" 10599 "private:\n" 10600 " int j;\n" 10601 "};\n", 10602 format("struct foo { /* comment */\n" 10603 "\n" 10604 "private:\n" 10605 " int i;\n" 10606 " // comment\n" 10607 "\n" 10608 "private:\n" 10609 " int j;\n" 10610 "};\n", 10611 Style)); 10612 verifyFormat("struct foo { /* comment */\n" 10613 "private:\n" 10614 " int i;\n" 10615 " // comment\n" 10616 "private:\n" 10617 " int j;\n" 10618 "};\n", 10619 Style); 10620 EXPECT_EQ("struct foo {\n" 10621 "#ifdef FOO\n" 10622 "#endif\n" 10623 "\n" 10624 "private:\n" 10625 " int i;\n" 10626 "#ifdef FOO\n" 10627 "\n" 10628 "private:\n" 10629 "#endif\n" 10630 " int j;\n" 10631 "};\n", 10632 format("struct foo {\n" 10633 "#ifdef FOO\n" 10634 "#endif\n" 10635 "\n" 10636 "private:\n" 10637 " int i;\n" 10638 "#ifdef FOO\n" 10639 "\n" 10640 "private:\n" 10641 "#endif\n" 10642 " int j;\n" 10643 "};\n", 10644 Style)); 10645 verifyFormat("struct foo {\n" 10646 "#ifdef FOO\n" 10647 "#endif\n" 10648 "private:\n" 10649 " int i;\n" 10650 "#ifdef FOO\n" 10651 "private:\n" 10652 "#endif\n" 10653 " int j;\n" 10654 "};\n", 10655 Style); 10656 10657 FormatStyle NoEmptyLines = getLLVMStyle(); 10658 NoEmptyLines.MaxEmptyLinesToKeep = 0; 10659 verifyFormat("struct foo {\n" 10660 "private:\n" 10661 " void f() {}\n" 10662 "\n" 10663 "private:\n" 10664 " int i;\n" 10665 "\n" 10666 "public:\n" 10667 "protected:\n" 10668 " int j;\n" 10669 "};\n", 10670 NoEmptyLines); 10671 10672 NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 10673 verifyFormat("struct foo {\n" 10674 "private:\n" 10675 " void f() {}\n" 10676 "private:\n" 10677 " int i;\n" 10678 "public:\n" 10679 "protected:\n" 10680 " int j;\n" 10681 "};\n", 10682 NoEmptyLines); 10683 10684 NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 10685 verifyFormat("struct foo {\n" 10686 "private:\n" 10687 " void f() {}\n" 10688 "\n" 10689 "private:\n" 10690 " int i;\n" 10691 "\n" 10692 "public:\n" 10693 "\n" 10694 "protected:\n" 10695 " int j;\n" 10696 "};\n", 10697 NoEmptyLines); 10698 } 10699 10700 TEST_F(FormatTest, FormatsAfterAccessModifiers) { 10701 10702 FormatStyle Style = getLLVMStyle(); 10703 EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never); 10704 verifyFormat("struct foo {\n" 10705 "private:\n" 10706 " void f() {}\n" 10707 "\n" 10708 "private:\n" 10709 " int i;\n" 10710 "\n" 10711 "protected:\n" 10712 " int j;\n" 10713 "};\n", 10714 Style); 10715 10716 // Check if lines are removed. 10717 verifyFormat("struct foo {\n" 10718 "private:\n" 10719 " void f() {}\n" 10720 "\n" 10721 "private:\n" 10722 " int i;\n" 10723 "\n" 10724 "protected:\n" 10725 " int j;\n" 10726 "};\n", 10727 "struct foo {\n" 10728 "private:\n" 10729 "\n" 10730 " void f() {}\n" 10731 "\n" 10732 "private:\n" 10733 "\n" 10734 " int i;\n" 10735 "\n" 10736 "protected:\n" 10737 "\n" 10738 " int j;\n" 10739 "};\n", 10740 Style); 10741 10742 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 10743 verifyFormat("struct foo {\n" 10744 "private:\n" 10745 "\n" 10746 " void f() {}\n" 10747 "\n" 10748 "private:\n" 10749 "\n" 10750 " int i;\n" 10751 "\n" 10752 "protected:\n" 10753 "\n" 10754 " int j;\n" 10755 "};\n", 10756 Style); 10757 10758 // Check if lines are added. 10759 verifyFormat("struct foo {\n" 10760 "private:\n" 10761 "\n" 10762 " void f() {}\n" 10763 "\n" 10764 "private:\n" 10765 "\n" 10766 " int i;\n" 10767 "\n" 10768 "protected:\n" 10769 "\n" 10770 " int j;\n" 10771 "};\n", 10772 "struct foo {\n" 10773 "private:\n" 10774 " void f() {}\n" 10775 "\n" 10776 "private:\n" 10777 " int i;\n" 10778 "\n" 10779 "protected:\n" 10780 " int j;\n" 10781 "};\n", 10782 Style); 10783 10784 // Leave tests rely on the code layout, test::messUp can not be used. 10785 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 10786 Style.MaxEmptyLinesToKeep = 0u; 10787 verifyFormat("struct foo {\n" 10788 "private:\n" 10789 " void f() {}\n" 10790 "\n" 10791 "private:\n" 10792 " int i;\n" 10793 "\n" 10794 "protected:\n" 10795 " int j;\n" 10796 "};\n", 10797 Style); 10798 10799 // Check if MaxEmptyLinesToKeep is respected. 10800 EXPECT_EQ("struct foo {\n" 10801 "private:\n" 10802 " void f() {}\n" 10803 "\n" 10804 "private:\n" 10805 " int i;\n" 10806 "\n" 10807 "protected:\n" 10808 " int j;\n" 10809 "};\n", 10810 format("struct foo {\n" 10811 "private:\n" 10812 "\n\n\n" 10813 " void f() {}\n" 10814 "\n" 10815 "private:\n" 10816 "\n\n\n" 10817 " int i;\n" 10818 "\n" 10819 "protected:\n" 10820 "\n\n\n" 10821 " int j;\n" 10822 "};\n", 10823 Style)); 10824 10825 Style.MaxEmptyLinesToKeep = 1u; 10826 EXPECT_EQ("struct foo {\n" 10827 "private:\n" 10828 "\n" 10829 " void f() {}\n" 10830 "\n" 10831 "private:\n" 10832 "\n" 10833 " int i;\n" 10834 "\n" 10835 "protected:\n" 10836 "\n" 10837 " int j;\n" 10838 "};\n", 10839 format("struct foo {\n" 10840 "private:\n" 10841 "\n" 10842 " void f() {}\n" 10843 "\n" 10844 "private:\n" 10845 "\n" 10846 " int i;\n" 10847 "\n" 10848 "protected:\n" 10849 "\n" 10850 " int j;\n" 10851 "};\n", 10852 Style)); 10853 // Check if no lines are kept. 10854 EXPECT_EQ("struct foo {\n" 10855 "private:\n" 10856 " void f() {}\n" 10857 "\n" 10858 "private:\n" 10859 " int i;\n" 10860 "\n" 10861 "protected:\n" 10862 " int j;\n" 10863 "};\n", 10864 format("struct foo {\n" 10865 "private:\n" 10866 " void f() {}\n" 10867 "\n" 10868 "private:\n" 10869 " int i;\n" 10870 "\n" 10871 "protected:\n" 10872 " int j;\n" 10873 "};\n", 10874 Style)); 10875 // Check if MaxEmptyLinesToKeep is respected. 10876 EXPECT_EQ("struct foo {\n" 10877 "private:\n" 10878 "\n" 10879 " void f() {}\n" 10880 "\n" 10881 "private:\n" 10882 "\n" 10883 " int i;\n" 10884 "\n" 10885 "protected:\n" 10886 "\n" 10887 " int j;\n" 10888 "};\n", 10889 format("struct foo {\n" 10890 "private:\n" 10891 "\n\n\n" 10892 " void f() {}\n" 10893 "\n" 10894 "private:\n" 10895 "\n\n\n" 10896 " int i;\n" 10897 "\n" 10898 "protected:\n" 10899 "\n\n\n" 10900 " int j;\n" 10901 "};\n", 10902 Style)); 10903 10904 Style.MaxEmptyLinesToKeep = 10u; 10905 EXPECT_EQ("struct foo {\n" 10906 "private:\n" 10907 "\n\n\n" 10908 " void f() {}\n" 10909 "\n" 10910 "private:\n" 10911 "\n\n\n" 10912 " int i;\n" 10913 "\n" 10914 "protected:\n" 10915 "\n\n\n" 10916 " int j;\n" 10917 "};\n", 10918 format("struct foo {\n" 10919 "private:\n" 10920 "\n\n\n" 10921 " void f() {}\n" 10922 "\n" 10923 "private:\n" 10924 "\n\n\n" 10925 " int i;\n" 10926 "\n" 10927 "protected:\n" 10928 "\n\n\n" 10929 " int j;\n" 10930 "};\n", 10931 Style)); 10932 10933 // Test with comments. 10934 Style = getLLVMStyle(); 10935 verifyFormat("struct foo {\n" 10936 "private:\n" 10937 " // comment\n" 10938 " void f() {}\n" 10939 "\n" 10940 "private: /* comment */\n" 10941 " int i;\n" 10942 "};\n", 10943 Style); 10944 verifyFormat("struct foo {\n" 10945 "private:\n" 10946 " // comment\n" 10947 " void f() {}\n" 10948 "\n" 10949 "private: /* comment */\n" 10950 " int i;\n" 10951 "};\n", 10952 "struct foo {\n" 10953 "private:\n" 10954 "\n" 10955 " // comment\n" 10956 " void f() {}\n" 10957 "\n" 10958 "private: /* comment */\n" 10959 "\n" 10960 " int i;\n" 10961 "};\n", 10962 Style); 10963 10964 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 10965 verifyFormat("struct foo {\n" 10966 "private:\n" 10967 "\n" 10968 " // comment\n" 10969 " void f() {}\n" 10970 "\n" 10971 "private: /* comment */\n" 10972 "\n" 10973 " int i;\n" 10974 "};\n", 10975 "struct foo {\n" 10976 "private:\n" 10977 " // comment\n" 10978 " void f() {}\n" 10979 "\n" 10980 "private: /* comment */\n" 10981 " int i;\n" 10982 "};\n", 10983 Style); 10984 verifyFormat("struct foo {\n" 10985 "private:\n" 10986 "\n" 10987 " // comment\n" 10988 " void f() {}\n" 10989 "\n" 10990 "private: /* comment */\n" 10991 "\n" 10992 " int i;\n" 10993 "};\n", 10994 Style); 10995 10996 // Test with preprocessor defines. 10997 Style = getLLVMStyle(); 10998 verifyFormat("struct foo {\n" 10999 "private:\n" 11000 "#ifdef FOO\n" 11001 "#endif\n" 11002 " void f() {}\n" 11003 "};\n", 11004 Style); 11005 verifyFormat("struct foo {\n" 11006 "private:\n" 11007 "#ifdef FOO\n" 11008 "#endif\n" 11009 " void f() {}\n" 11010 "};\n", 11011 "struct foo {\n" 11012 "private:\n" 11013 "\n" 11014 "#ifdef FOO\n" 11015 "#endif\n" 11016 " void f() {}\n" 11017 "};\n", 11018 Style); 11019 11020 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11021 verifyFormat("struct foo {\n" 11022 "private:\n" 11023 "\n" 11024 "#ifdef FOO\n" 11025 "#endif\n" 11026 " void f() {}\n" 11027 "};\n", 11028 "struct foo {\n" 11029 "private:\n" 11030 "#ifdef FOO\n" 11031 "#endif\n" 11032 " void f() {}\n" 11033 "};\n", 11034 Style); 11035 verifyFormat("struct foo {\n" 11036 "private:\n" 11037 "\n" 11038 "#ifdef FOO\n" 11039 "#endif\n" 11040 " void f() {}\n" 11041 "};\n", 11042 Style); 11043 } 11044 11045 TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) { 11046 // Combined tests of EmptyLineAfterAccessModifier and 11047 // EmptyLineBeforeAccessModifier. 11048 FormatStyle Style = getLLVMStyle(); 11049 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11050 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11051 verifyFormat("struct foo {\n" 11052 "private:\n" 11053 "\n" 11054 "protected:\n" 11055 "};\n", 11056 Style); 11057 11058 Style.MaxEmptyLinesToKeep = 10u; 11059 // Both remove all new lines. 11060 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11061 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11062 verifyFormat("struct foo {\n" 11063 "private:\n" 11064 "protected:\n" 11065 "};\n", 11066 "struct foo {\n" 11067 "private:\n" 11068 "\n\n\n" 11069 "protected:\n" 11070 "};\n", 11071 Style); 11072 11073 // Leave tests rely on the code layout, test::messUp can not be used. 11074 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11075 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11076 Style.MaxEmptyLinesToKeep = 10u; 11077 EXPECT_EQ("struct foo {\n" 11078 "private:\n" 11079 "\n\n\n" 11080 "protected:\n" 11081 "};\n", 11082 format("struct foo {\n" 11083 "private:\n" 11084 "\n\n\n" 11085 "protected:\n" 11086 "};\n", 11087 Style)); 11088 Style.MaxEmptyLinesToKeep = 3u; 11089 EXPECT_EQ("struct foo {\n" 11090 "private:\n" 11091 "\n\n\n" 11092 "protected:\n" 11093 "};\n", 11094 format("struct foo {\n" 11095 "private:\n" 11096 "\n\n\n" 11097 "protected:\n" 11098 "};\n", 11099 Style)); 11100 Style.MaxEmptyLinesToKeep = 1u; 11101 EXPECT_EQ("struct foo {\n" 11102 "private:\n" 11103 "\n\n\n" 11104 "protected:\n" 11105 "};\n", 11106 format("struct foo {\n" 11107 "private:\n" 11108 "\n\n\n" 11109 "protected:\n" 11110 "};\n", 11111 Style)); // Based on new lines in original document and not 11112 // on the setting. 11113 11114 Style.MaxEmptyLinesToKeep = 10u; 11115 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11116 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11117 // Newlines are kept if they are greater than zero, 11118 // test::messUp removes all new lines which changes the logic 11119 EXPECT_EQ("struct foo {\n" 11120 "private:\n" 11121 "\n\n\n" 11122 "protected:\n" 11123 "};\n", 11124 format("struct foo {\n" 11125 "private:\n" 11126 "\n\n\n" 11127 "protected:\n" 11128 "};\n", 11129 Style)); 11130 11131 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11132 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11133 // test::messUp removes all new lines which changes the logic 11134 EXPECT_EQ("struct foo {\n" 11135 "private:\n" 11136 "\n\n\n" 11137 "protected:\n" 11138 "};\n", 11139 format("struct foo {\n" 11140 "private:\n" 11141 "\n\n\n" 11142 "protected:\n" 11143 "};\n", 11144 Style)); 11145 11146 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave; 11147 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11148 EXPECT_EQ("struct foo {\n" 11149 "private:\n" 11150 "\n\n\n" 11151 "protected:\n" 11152 "};\n", 11153 format("struct foo {\n" 11154 "private:\n" 11155 "\n\n\n" 11156 "protected:\n" 11157 "};\n", 11158 Style)); // test::messUp removes all new lines which changes 11159 // the logic. 11160 11161 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11162 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11163 verifyFormat("struct foo {\n" 11164 "private:\n" 11165 "protected:\n" 11166 "};\n", 11167 "struct foo {\n" 11168 "private:\n" 11169 "\n\n\n" 11170 "protected:\n" 11171 "};\n", 11172 Style); 11173 11174 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always; 11175 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11176 EXPECT_EQ("struct foo {\n" 11177 "private:\n" 11178 "\n\n\n" 11179 "protected:\n" 11180 "};\n", 11181 format("struct foo {\n" 11182 "private:\n" 11183 "\n\n\n" 11184 "protected:\n" 11185 "};\n", 11186 Style)); // test::messUp removes all new lines which changes 11187 // the logic. 11188 11189 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never; 11190 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11191 verifyFormat("struct foo {\n" 11192 "private:\n" 11193 "protected:\n" 11194 "};\n", 11195 "struct foo {\n" 11196 "private:\n" 11197 "\n\n\n" 11198 "protected:\n" 11199 "};\n", 11200 Style); 11201 11202 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11203 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always; 11204 verifyFormat("struct foo {\n" 11205 "private:\n" 11206 "protected:\n" 11207 "};\n", 11208 "struct foo {\n" 11209 "private:\n" 11210 "\n\n\n" 11211 "protected:\n" 11212 "};\n", 11213 Style); 11214 11215 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11216 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave; 11217 verifyFormat("struct foo {\n" 11218 "private:\n" 11219 "protected:\n" 11220 "};\n", 11221 "struct foo {\n" 11222 "private:\n" 11223 "\n\n\n" 11224 "protected:\n" 11225 "};\n", 11226 Style); 11227 11228 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 11229 Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never; 11230 verifyFormat("struct foo {\n" 11231 "private:\n" 11232 "protected:\n" 11233 "};\n", 11234 "struct foo {\n" 11235 "private:\n" 11236 "\n\n\n" 11237 "protected:\n" 11238 "};\n", 11239 Style); 11240 } 11241 11242 TEST_F(FormatTest, FormatsArrays) { 11243 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n" 11244 " [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;"); 11245 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n" 11246 " [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;"); 11247 verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n" 11248 " aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}"); 11249 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11250 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;"); 11251 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11252 " [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;"); 11253 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" 11254 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n" 11255 " [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;"); 11256 verifyFormat( 11257 "llvm::outs() << \"aaaaaaaaaaaa: \"\n" 11258 " << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n" 11259 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];"); 11260 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n" 11261 " .aaaaaaaaaaaaaaaaaaaaaa();"); 11262 11263 verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n" 11264 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];"); 11265 verifyFormat( 11266 "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n" 11267 " .aaaaaaa[0]\n" 11268 " .aaaaaaaaaaaaaaaaaaaaaa();"); 11269 verifyFormat("a[::b::c];"); 11270 11271 verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10)); 11272 11273 FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0); 11274 verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit); 11275 } 11276 11277 TEST_F(FormatTest, LineStartsWithSpecialCharacter) { 11278 verifyFormat("(a)->b();"); 11279 verifyFormat("--a;"); 11280 } 11281 11282 TEST_F(FormatTest, HandlesIncludeDirectives) { 11283 verifyFormat("#include <string>\n" 11284 "#include <a/b/c.h>\n" 11285 "#include \"a/b/string\"\n" 11286 "#include \"string.h\"\n" 11287 "#include \"string.h\"\n" 11288 "#include <a-a>\n" 11289 "#include < path with space >\n" 11290 "#include_next <test.h>" 11291 "#include \"abc.h\" // this is included for ABC\n" 11292 "#include \"some long include\" // with a comment\n" 11293 "#include \"some very long include path\"\n" 11294 "#include <some/very/long/include/path>\n", 11295 getLLVMStyleWithColumns(35)); 11296 EXPECT_EQ("#include \"a.h\"", format("#include \"a.h\"")); 11297 EXPECT_EQ("#include <a>", format("#include<a>")); 11298 11299 verifyFormat("#import <string>"); 11300 verifyFormat("#import <a/b/c.h>"); 11301 verifyFormat("#import \"a/b/string\""); 11302 verifyFormat("#import \"string.h\""); 11303 verifyFormat("#import \"string.h\""); 11304 verifyFormat("#if __has_include(<strstream>)\n" 11305 "#include <strstream>\n" 11306 "#endif"); 11307 11308 verifyFormat("#define MY_IMPORT <a/b>"); 11309 11310 verifyFormat("#if __has_include(<a/b>)"); 11311 verifyFormat("#if __has_include_next(<a/b>)"); 11312 verifyFormat("#define F __has_include(<a/b>)"); 11313 verifyFormat("#define F __has_include_next(<a/b>)"); 11314 11315 // Protocol buffer definition or missing "#". 11316 verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";", 11317 getLLVMStyleWithColumns(30)); 11318 11319 FormatStyle Style = getLLVMStyle(); 11320 Style.AlwaysBreakBeforeMultilineStrings = true; 11321 Style.ColumnLimit = 0; 11322 verifyFormat("#import \"abc.h\"", Style); 11323 11324 // But 'import' might also be a regular C++ namespace. 11325 verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 11326 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); 11327 } 11328 11329 //===----------------------------------------------------------------------===// 11330 // Error recovery tests. 11331 //===----------------------------------------------------------------------===// 11332 11333 TEST_F(FormatTest, IncompleteParameterLists) { 11334 FormatStyle NoBinPacking = getLLVMStyle(); 11335 NoBinPacking.BinPackParameters = false; 11336 verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n" 11337 " double *min_x,\n" 11338 " double *max_x,\n" 11339 " double *min_y,\n" 11340 " double *max_y,\n" 11341 " double *min_z,\n" 11342 " double *max_z, ) {}", 11343 NoBinPacking); 11344 } 11345 11346 TEST_F(FormatTest, IncorrectCodeTrailingStuff) { 11347 verifyFormat("void f() { return; }\n42"); 11348 verifyFormat("void f() {\n" 11349 " if (0)\n" 11350 " return;\n" 11351 "}\n" 11352 "42"); 11353 verifyFormat("void f() { return }\n42"); 11354 verifyFormat("void f() {\n" 11355 " if (0)\n" 11356 " return\n" 11357 "}\n" 11358 "42"); 11359 } 11360 11361 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) { 11362 EXPECT_EQ("void f() { return }", format("void f ( ) { return }")); 11363 EXPECT_EQ("void f() {\n" 11364 " if (a)\n" 11365 " return\n" 11366 "}", 11367 format("void f ( ) { if ( a ) return }")); 11368 EXPECT_EQ("namespace N {\n" 11369 "void f()\n" 11370 "}", 11371 format("namespace N { void f() }")); 11372 EXPECT_EQ("namespace N {\n" 11373 "void f() {}\n" 11374 "void g()\n" 11375 "} // namespace N", 11376 format("namespace N { void f( ) { } void g( ) }")); 11377 } 11378 11379 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) { 11380 verifyFormat("int aaaaaaaa =\n" 11381 " // Overlylongcomment\n" 11382 " b;", 11383 getLLVMStyleWithColumns(20)); 11384 verifyFormat("function(\n" 11385 " ShortArgument,\n" 11386 " LoooooooooooongArgument);\n", 11387 getLLVMStyleWithColumns(20)); 11388 } 11389 11390 TEST_F(FormatTest, IncorrectAccessSpecifier) { 11391 verifyFormat("public:"); 11392 verifyFormat("class A {\n" 11393 "public\n" 11394 " void f() {}\n" 11395 "};"); 11396 verifyFormat("public\n" 11397 "int qwerty;"); 11398 verifyFormat("public\n" 11399 "B {}"); 11400 verifyFormat("public\n" 11401 "{}"); 11402 verifyFormat("public\n" 11403 "B { int x; }"); 11404 } 11405 11406 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) { 11407 verifyFormat("{"); 11408 verifyFormat("#})"); 11409 verifyNoCrash("(/**/[:!] ?[)."); 11410 } 11411 11412 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) { 11413 // Found by oss-fuzz: 11414 // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212 11415 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp); 11416 Style.ColumnLimit = 60; 11417 verifyNoCrash( 11418 "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20" 11419 "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20" 11420 "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a", 11421 Style); 11422 } 11423 11424 TEST_F(FormatTest, IncorrectCodeDoNoWhile) { 11425 verifyFormat("do {\n}"); 11426 verifyFormat("do {\n}\n" 11427 "f();"); 11428 verifyFormat("do {\n}\n" 11429 "wheeee(fun);"); 11430 verifyFormat("do {\n" 11431 " f();\n" 11432 "}"); 11433 } 11434 11435 TEST_F(FormatTest, IncorrectCodeMissingParens) { 11436 verifyFormat("if {\n foo;\n foo();\n}"); 11437 verifyFormat("switch {\n foo;\n foo();\n}"); 11438 verifyIncompleteFormat("for {\n foo;\n foo();\n}"); 11439 verifyFormat("while {\n foo;\n foo();\n}"); 11440 verifyFormat("do {\n foo;\n foo();\n} while;"); 11441 } 11442 11443 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) { 11444 verifyIncompleteFormat("namespace {\n" 11445 "class Foo { Foo (\n" 11446 "};\n" 11447 "} // namespace"); 11448 } 11449 11450 TEST_F(FormatTest, IncorrectCodeErrorDetection) { 11451 EXPECT_EQ("{\n {}\n", format("{\n{\n}\n")); 11452 EXPECT_EQ("{\n {}\n", format("{\n {\n}\n")); 11453 EXPECT_EQ("{\n {}\n", format("{\n {\n }\n")); 11454 EXPECT_EQ("{\n {}\n}\n}\n", format("{\n {\n }\n }\n}\n")); 11455 11456 EXPECT_EQ("{\n" 11457 " {\n" 11458 " breakme(\n" 11459 " qwe);\n" 11460 " }\n", 11461 format("{\n" 11462 " {\n" 11463 " breakme(qwe);\n" 11464 "}\n", 11465 getLLVMStyleWithColumns(10))); 11466 } 11467 11468 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) { 11469 verifyFormat("int x = {\n" 11470 " avariable,\n" 11471 " b(alongervariable)};", 11472 getLLVMStyleWithColumns(25)); 11473 } 11474 11475 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) { 11476 verifyFormat("return (a)(b){1, 2, 3};"); 11477 } 11478 11479 TEST_F(FormatTest, LayoutCxx11BraceInitializers) { 11480 verifyFormat("vector<int> x{1, 2, 3, 4};"); 11481 verifyFormat("vector<int> x{\n" 11482 " 1,\n" 11483 " 2,\n" 11484 " 3,\n" 11485 " 4,\n" 11486 "};"); 11487 verifyFormat("vector<T> x{{}, {}, {}, {}};"); 11488 verifyFormat("f({1, 2});"); 11489 verifyFormat("auto v = Foo{-1};"); 11490 verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});"); 11491 verifyFormat("Class::Class : member{1, 2, 3} {}"); 11492 verifyFormat("new vector<int>{1, 2, 3};"); 11493 verifyFormat("new int[3]{1, 2, 3};"); 11494 verifyFormat("new int{1};"); 11495 verifyFormat("return {arg1, arg2};"); 11496 verifyFormat("return {arg1, SomeType{parameter}};"); 11497 verifyFormat("int count = set<int>{f(), g(), h()}.size();"); 11498 verifyFormat("new T{arg1, arg2};"); 11499 verifyFormat("f(MyMap[{composite, key}]);"); 11500 verifyFormat("class Class {\n" 11501 " T member = {arg1, arg2};\n" 11502 "};"); 11503 verifyFormat("vector<int> foo = {::SomeGlobalFunction()};"); 11504 verifyFormat("const struct A a = {.a = 1, .b = 2};"); 11505 verifyFormat("const struct A a = {[0] = 1, [1] = 2};"); 11506 verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");"); 11507 verifyFormat("int a = std::is_integral<int>{} + 0;"); 11508 11509 verifyFormat("int foo(int i) { return fo1{}(i); }"); 11510 verifyFormat("int foo(int i) { return fo1{}(i); }"); 11511 verifyFormat("auto i = decltype(x){};"); 11512 verifyFormat("auto i = typeof(x){};"); 11513 verifyFormat("auto i = _Atomic(x){};"); 11514 verifyFormat("std::vector<int> v = {1, 0 /* comment */};"); 11515 verifyFormat("Node n{1, Node{1000}, //\n" 11516 " 2};"); 11517 verifyFormat("Aaaa aaaaaaa{\n" 11518 " {\n" 11519 " aaaa,\n" 11520 " },\n" 11521 "};"); 11522 verifyFormat("class C : public D {\n" 11523 " SomeClass SC{2};\n" 11524 "};"); 11525 verifyFormat("class C : public A {\n" 11526 " class D : public B {\n" 11527 " void f() { int i{2}; }\n" 11528 " };\n" 11529 "};"); 11530 verifyFormat("#define A {a, a},"); 11531 // Don't confuse braced list initializers with compound statements. 11532 verifyFormat( 11533 "class A {\n" 11534 " A() : a{} {}\n" 11535 " A(int b) : b(b) {}\n" 11536 " A(int a, int b) : a(a), bs{{bs...}} { f(); }\n" 11537 " int a, b;\n" 11538 " explicit Expr(const Scalar<Result> &x) : u{Constant<Result>{x}} {}\n" 11539 " explicit Expr(Scalar<Result> &&x) : u{Constant<Result>{std::move(x)}} " 11540 "{}\n" 11541 "};"); 11542 11543 // Avoid breaking between equal sign and opening brace 11544 FormatStyle AvoidBreakingFirstArgument = getLLVMStyle(); 11545 AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200; 11546 verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n" 11547 " {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n" 11548 " {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n" 11549 " {\"ccccccccccccccccccccc\", 2}};", 11550 AvoidBreakingFirstArgument); 11551 11552 // Binpacking only if there is no trailing comma 11553 verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n" 11554 " cccccccccc, dddddddddd};", 11555 getLLVMStyleWithColumns(50)); 11556 verifyFormat("const Aaaaaa aaaaa = {\n" 11557 " aaaaaaaaaaa,\n" 11558 " bbbbbbbbbbb,\n" 11559 " ccccccccccc,\n" 11560 " ddddddddddd,\n" 11561 "};", 11562 getLLVMStyleWithColumns(50)); 11563 11564 // Cases where distinguising braced lists and blocks is hard. 11565 verifyFormat("vector<int> v{12} GUARDED_BY(mutex);"); 11566 verifyFormat("void f() {\n" 11567 " return; // comment\n" 11568 "}\n" 11569 "SomeType t;"); 11570 verifyFormat("void f() {\n" 11571 " if (a) {\n" 11572 " f();\n" 11573 " }\n" 11574 "}\n" 11575 "SomeType t;"); 11576 11577 // In combination with BinPackArguments = false. 11578 FormatStyle NoBinPacking = getLLVMStyle(); 11579 NoBinPacking.BinPackArguments = false; 11580 verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n" 11581 " bbbbb,\n" 11582 " ccccc,\n" 11583 " ddddd,\n" 11584 " eeeee,\n" 11585 " ffffff,\n" 11586 " ggggg,\n" 11587 " hhhhhh,\n" 11588 " iiiiii,\n" 11589 " jjjjjj,\n" 11590 " kkkkkk};", 11591 NoBinPacking); 11592 verifyFormat("const Aaaaaa aaaaa = {\n" 11593 " aaaaa,\n" 11594 " bbbbb,\n" 11595 " ccccc,\n" 11596 " ddddd,\n" 11597 " eeeee,\n" 11598 " ffffff,\n" 11599 " ggggg,\n" 11600 " hhhhhh,\n" 11601 " iiiiii,\n" 11602 " jjjjjj,\n" 11603 " kkkkkk,\n" 11604 "};", 11605 NoBinPacking); 11606 verifyFormat( 11607 "const Aaaaaa aaaaa = {\n" 11608 " aaaaa, bbbbb, ccccc, ddddd, eeeee, ffffff, ggggg, hhhhhh,\n" 11609 " iiiiii, jjjjjj, kkkkkk, aaaaa, bbbbb, ccccc, ddddd, eeeee,\n" 11610 " ffffff, ggggg, hhhhhh, iiiiii, jjjjjj, kkkkkk,\n" 11611 "};", 11612 NoBinPacking); 11613 11614 NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 11615 EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n" 11616 " CDDDP83848_BMCR_REGISTER,\n" 11617 " CDDDP83848_BMSR_REGISTER,\n" 11618 " CDDDP83848_RBR_REGISTER};", 11619 format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n" 11620 " CDDDP83848_BMSR_REGISTER,\n" 11621 " CDDDP83848_RBR_REGISTER};", 11622 NoBinPacking)); 11623 11624 // FIXME: The alignment of these trailing comments might be bad. Then again, 11625 // this might be utterly useless in real code. 11626 verifyFormat("Constructor::Constructor()\n" 11627 " : some_value{ //\n" 11628 " aaaaaaa, //\n" 11629 " bbbbbbb} {}"); 11630 11631 // In braced lists, the first comment is always assumed to belong to the 11632 // first element. Thus, it can be moved to the next or previous line as 11633 // appropriate. 11634 EXPECT_EQ("function({// First element:\n" 11635 " 1,\n" 11636 " // Second element:\n" 11637 " 2});", 11638 format("function({\n" 11639 " // First element:\n" 11640 " 1,\n" 11641 " // Second element:\n" 11642 " 2});")); 11643 EXPECT_EQ("std::vector<int> MyNumbers{\n" 11644 " // First element:\n" 11645 " 1,\n" 11646 " // Second element:\n" 11647 " 2};", 11648 format("std::vector<int> MyNumbers{// First element:\n" 11649 " 1,\n" 11650 " // Second element:\n" 11651 " 2};", 11652 getLLVMStyleWithColumns(30))); 11653 // A trailing comma should still lead to an enforced line break and no 11654 // binpacking. 11655 EXPECT_EQ("vector<int> SomeVector = {\n" 11656 " // aaa\n" 11657 " 1,\n" 11658 " 2,\n" 11659 "};", 11660 format("vector<int> SomeVector = { // aaa\n" 11661 " 1, 2, };")); 11662 11663 // C++11 brace initializer list l-braces should not be treated any differently 11664 // when breaking before lambda bodies is enabled 11665 FormatStyle BreakBeforeLambdaBody = getLLVMStyle(); 11666 BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 11667 BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 11668 BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true; 11669 verifyFormat( 11670 "std::runtime_error{\n" 11671 " \"Long string which will force a break onto the next line...\"};", 11672 BreakBeforeLambdaBody); 11673 11674 FormatStyle ExtraSpaces = getLLVMStyle(); 11675 ExtraSpaces.Cpp11BracedListStyle = false; 11676 ExtraSpaces.ColumnLimit = 75; 11677 verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces); 11678 verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces); 11679 verifyFormat("f({ 1, 2 });", ExtraSpaces); 11680 verifyFormat("auto v = Foo{ 1 };", ExtraSpaces); 11681 verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces); 11682 verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces); 11683 verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces); 11684 verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces); 11685 verifyFormat("return { arg1, arg2 };", ExtraSpaces); 11686 verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces); 11687 verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces); 11688 verifyFormat("new T{ arg1, arg2 };", ExtraSpaces); 11689 verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces); 11690 verifyFormat("class Class {\n" 11691 " T member = { arg1, arg2 };\n" 11692 "};", 11693 ExtraSpaces); 11694 verifyFormat( 11695 "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 11696 " aaaaaaaaaaaaaaaaaaaa, aaaaa }\n" 11697 " : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" 11698 " bbbbbbbbbbbbbbbbbbbb, bbbbb };", 11699 ExtraSpaces); 11700 verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces); 11701 verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });", 11702 ExtraSpaces); 11703 verifyFormat( 11704 "someFunction(OtherParam,\n" 11705 " BracedList{ // comment 1 (Forcing interesting break)\n" 11706 " param1, param2,\n" 11707 " // comment 2\n" 11708 " param3, param4 });", 11709 ExtraSpaces); 11710 verifyFormat( 11711 "std::this_thread::sleep_for(\n" 11712 " std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);", 11713 ExtraSpaces); 11714 verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n" 11715 " aaaaaaa,\n" 11716 " aaaaaaaaaa,\n" 11717 " aaaaa,\n" 11718 " aaaaaaaaaaaaaaa,\n" 11719 " aaa,\n" 11720 " aaaaaaaaaa,\n" 11721 " a,\n" 11722 " aaaaaaaaaaaaaaaaaaaaa,\n" 11723 " aaaaaaaaaaaa,\n" 11724 " aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n" 11725 " aaaaaaa,\n" 11726 " a};"); 11727 verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces); 11728 verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces); 11729 verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces); 11730 11731 // Avoid breaking between initializer/equal sign and opening brace 11732 ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200; 11733 verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n" 11734 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n" 11735 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n" 11736 " { \"ccccccccccccccccccccc\", 2 }\n" 11737 "};", 11738 ExtraSpaces); 11739 verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n" 11740 " { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n" 11741 " { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n" 11742 " { \"ccccccccccccccccccccc\", 2 }\n" 11743 "};", 11744 ExtraSpaces); 11745 11746 FormatStyle SpaceBeforeBrace = getLLVMStyle(); 11747 SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true; 11748 verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace); 11749 verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace); 11750 11751 FormatStyle SpaceBetweenBraces = getLLVMStyle(); 11752 SpaceBetweenBraces.SpacesInAngles = FormatStyle::SIAS_Always; 11753 SpaceBetweenBraces.SpacesInParentheses = true; 11754 SpaceBetweenBraces.SpacesInSquareBrackets = true; 11755 verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces); 11756 verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces); 11757 verifyFormat("vector< int > x{ // comment 1\n" 11758 " 1, 2, 3, 4 };", 11759 SpaceBetweenBraces); 11760 SpaceBetweenBraces.ColumnLimit = 20; 11761 EXPECT_EQ("vector< int > x{\n" 11762 " 1, 2, 3, 4 };", 11763 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces)); 11764 SpaceBetweenBraces.ColumnLimit = 24; 11765 EXPECT_EQ("vector< int > x{ 1, 2,\n" 11766 " 3, 4 };", 11767 format("vector<int>x{1,2,3,4};", SpaceBetweenBraces)); 11768 EXPECT_EQ("vector< int > x{\n" 11769 " 1,\n" 11770 " 2,\n" 11771 " 3,\n" 11772 " 4,\n" 11773 "};", 11774 format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces)); 11775 verifyFormat("vector< int > x{};", SpaceBetweenBraces); 11776 SpaceBetweenBraces.SpaceInEmptyParentheses = true; 11777 verifyFormat("vector< int > x{ };", SpaceBetweenBraces); 11778 } 11779 11780 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) { 11781 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n" 11782 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 11783 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 11784 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 11785 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 11786 " 1, 22, 333, 4444, 55555, 666666, 7777777};"); 11787 verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n" 11788 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 11789 " 1, 22, 333, 4444, 55555, //\n" 11790 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 11791 " 1, 22, 333, 4444, 55555, 666666, 7777777};"); 11792 verifyFormat( 11793 "vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n" 11794 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 11795 " 1, 22, 333, 4444, 55555, 666666, // comment\n" 11796 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 11797 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 11798 " 7777777, 1, 22, 333, 4444, 55555, 666666,\n" 11799 " 7777777};"); 11800 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 11801 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 11802 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 11803 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 11804 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 11805 " // Separating comment.\n" 11806 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 11807 verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n" 11808 " // Leading comment\n" 11809 " X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n" 11810 " X86::R8, X86::R9, X86::R10, X86::R11, 0};"); 11811 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 11812 " 1, 1, 1, 1};", 11813 getLLVMStyleWithColumns(39)); 11814 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 11815 " 1, 1, 1, 1};", 11816 getLLVMStyleWithColumns(38)); 11817 verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n" 11818 " 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};", 11819 getLLVMStyleWithColumns(43)); 11820 verifyFormat( 11821 "static unsigned SomeValues[10][3] = {\n" 11822 " {1, 4, 0}, {4, 9, 0}, {4, 5, 9}, {8, 5, 4}, {1, 8, 4},\n" 11823 " {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};"); 11824 verifyFormat("static auto fields = new vector<string>{\n" 11825 " \"aaaaaaaaaaaaa\",\n" 11826 " \"aaaaaaaaaaaaa\",\n" 11827 " \"aaaaaaaaaaaa\",\n" 11828 " \"aaaaaaaaaaaaaa\",\n" 11829 " \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n" 11830 " \"aaaaaaaaaaaa\",\n" 11831 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n" 11832 "};"); 11833 verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};"); 11834 verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n" 11835 " 2, bbbbbbbbbbbbbbbbbbbbbb,\n" 11836 " 3, cccccccccccccccccccccc};", 11837 getLLVMStyleWithColumns(60)); 11838 11839 // Trailing commas. 11840 verifyFormat("vector<int> x = {\n" 11841 " 1, 1, 1, 1, 1, 1, 1, 1,\n" 11842 "};", 11843 getLLVMStyleWithColumns(39)); 11844 verifyFormat("vector<int> x = {\n" 11845 " 1, 1, 1, 1, 1, 1, 1, 1, //\n" 11846 "};", 11847 getLLVMStyleWithColumns(39)); 11848 verifyFormat("vector<int> x = {1, 1, 1, 1,\n" 11849 " 1, 1, 1, 1,\n" 11850 " /**/ /**/};", 11851 getLLVMStyleWithColumns(39)); 11852 11853 // Trailing comment in the first line. 11854 verifyFormat("vector<int> iiiiiiiiiiiiiii = { //\n" 11855 " 1111111111, 2222222222, 33333333333, 4444444444, //\n" 11856 " 111111111, 222222222, 3333333333, 444444444, //\n" 11857 " 11111111, 22222222, 333333333, 44444444};"); 11858 // Trailing comment in the last line. 11859 verifyFormat("int aaaaa[] = {\n" 11860 " 1, 2, 3, // comment\n" 11861 " 4, 5, 6 // comment\n" 11862 "};"); 11863 11864 // With nested lists, we should either format one item per line or all nested 11865 // lists one on line. 11866 // FIXME: For some nested lists, we can do better. 11867 verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n" 11868 " {aaaaaaaaaaaaaaaaaaa},\n" 11869 " {aaaaaaaaaaaaaaaaaaaaa},\n" 11870 " {aaaaaaaaaaaaaaaaa}};", 11871 getLLVMStyleWithColumns(60)); 11872 verifyFormat( 11873 "SomeStruct my_struct_array = {\n" 11874 " {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n" 11875 " aaaaaaaaaaaaa, aaaaaaa, aaa},\n" 11876 " {aaa, aaa},\n" 11877 " {aaa, aaa},\n" 11878 " {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n" 11879 " {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n" 11880 " aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};"); 11881 11882 // No column layout should be used here. 11883 verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n" 11884 " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};"); 11885 11886 verifyNoCrash("a<,"); 11887 11888 // No braced initializer here. 11889 verifyFormat("void f() {\n" 11890 " struct Dummy {};\n" 11891 " f(v);\n" 11892 "}"); 11893 11894 // Long lists should be formatted in columns even if they are nested. 11895 verifyFormat( 11896 "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n" 11897 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 11898 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 11899 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 11900 " 1, 22, 333, 4444, 55555, 666666, 7777777,\n" 11901 " 1, 22, 333, 4444, 55555, 666666, 7777777});"); 11902 11903 // Allow "single-column" layout even if that violates the column limit. There 11904 // isn't going to be a better way. 11905 verifyFormat("std::vector<int> a = {\n" 11906 " aaaaaaaa,\n" 11907 " aaaaaaaa,\n" 11908 " aaaaaaaa,\n" 11909 " aaaaaaaa,\n" 11910 " aaaaaaaaaa,\n" 11911 " aaaaaaaa,\n" 11912 " aaaaaaaaaaaaaaaaaaaaaaaaaaa};", 11913 getLLVMStyleWithColumns(30)); 11914 verifyFormat("vector<int> aaaa = {\n" 11915 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 11916 " aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 11917 " aaaaaa.aaaaaaa,\n" 11918 " aaaaaa.aaaaaaa,\n" 11919 " aaaaaa.aaaaaaa,\n" 11920 " aaaaaa.aaaaaaa,\n" 11921 "};"); 11922 11923 // Don't create hanging lists. 11924 verifyFormat("someFunction(Param, {List1, List2,\n" 11925 " List3});", 11926 getLLVMStyleWithColumns(35)); 11927 verifyFormat("someFunction(Param, Param,\n" 11928 " {List1, List2,\n" 11929 " List3});", 11930 getLLVMStyleWithColumns(35)); 11931 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n" 11932 " aaaaaaaaaaaaaaaaaaaaaaa);"); 11933 } 11934 11935 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) { 11936 FormatStyle DoNotMerge = getLLVMStyle(); 11937 DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 11938 11939 verifyFormat("void f() { return 42; }"); 11940 verifyFormat("void f() {\n" 11941 " return 42;\n" 11942 "}", 11943 DoNotMerge); 11944 verifyFormat("void f() {\n" 11945 " // Comment\n" 11946 "}"); 11947 verifyFormat("{\n" 11948 "#error {\n" 11949 " int a;\n" 11950 "}"); 11951 verifyFormat("{\n" 11952 " int a;\n" 11953 "#error {\n" 11954 "}"); 11955 verifyFormat("void f() {} // comment"); 11956 verifyFormat("void f() { int a; } // comment"); 11957 verifyFormat("void f() {\n" 11958 "} // comment", 11959 DoNotMerge); 11960 verifyFormat("void f() {\n" 11961 " int a;\n" 11962 "} // comment", 11963 DoNotMerge); 11964 verifyFormat("void f() {\n" 11965 "} // comment", 11966 getLLVMStyleWithColumns(15)); 11967 11968 verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23)); 11969 verifyFormat("void f() {\n return 42;\n}", getLLVMStyleWithColumns(22)); 11970 11971 verifyFormat("void f() {}", getLLVMStyleWithColumns(11)); 11972 verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10)); 11973 verifyFormat("class C {\n" 11974 " C()\n" 11975 " : iiiiiiii(nullptr),\n" 11976 " kkkkkkk(nullptr),\n" 11977 " mmmmmmm(nullptr),\n" 11978 " nnnnnnn(nullptr) {}\n" 11979 "};", 11980 getGoogleStyle()); 11981 11982 FormatStyle NoColumnLimit = getLLVMStyle(); 11983 NoColumnLimit.ColumnLimit = 0; 11984 EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit)); 11985 EXPECT_EQ("class C {\n" 11986 " A() : b(0) {}\n" 11987 "};", 11988 format("class C{A():b(0){}};", NoColumnLimit)); 11989 EXPECT_EQ("A()\n" 11990 " : b(0) {\n" 11991 "}", 11992 format("A()\n:b(0)\n{\n}", NoColumnLimit)); 11993 11994 FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit; 11995 DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine = 11996 FormatStyle::SFS_None; 11997 EXPECT_EQ("A()\n" 11998 " : b(0) {\n" 11999 "}", 12000 format("A():b(0){}", DoNotMergeNoColumnLimit)); 12001 EXPECT_EQ("A()\n" 12002 " : b(0) {\n" 12003 "}", 12004 format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit)); 12005 12006 verifyFormat("#define A \\\n" 12007 " void f() { \\\n" 12008 " int i; \\\n" 12009 " }", 12010 getLLVMStyleWithColumns(20)); 12011 verifyFormat("#define A \\\n" 12012 " void f() { int i; }", 12013 getLLVMStyleWithColumns(21)); 12014 verifyFormat("#define A \\\n" 12015 " void f() { \\\n" 12016 " int i; \\\n" 12017 " } \\\n" 12018 " int j;", 12019 getLLVMStyleWithColumns(22)); 12020 verifyFormat("#define A \\\n" 12021 " void f() { int i; } \\\n" 12022 " int j;", 12023 getLLVMStyleWithColumns(23)); 12024 } 12025 12026 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) { 12027 FormatStyle MergeEmptyOnly = getLLVMStyle(); 12028 MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 12029 verifyFormat("class C {\n" 12030 " int f() {}\n" 12031 "};", 12032 MergeEmptyOnly); 12033 verifyFormat("class C {\n" 12034 " int f() {\n" 12035 " return 42;\n" 12036 " }\n" 12037 "};", 12038 MergeEmptyOnly); 12039 verifyFormat("int f() {}", MergeEmptyOnly); 12040 verifyFormat("int f() {\n" 12041 " return 42;\n" 12042 "}", 12043 MergeEmptyOnly); 12044 12045 // Also verify behavior when BraceWrapping.AfterFunction = true 12046 MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12047 MergeEmptyOnly.BraceWrapping.AfterFunction = true; 12048 verifyFormat("int f() {}", MergeEmptyOnly); 12049 verifyFormat("class C {\n" 12050 " int f() {}\n" 12051 "};", 12052 MergeEmptyOnly); 12053 } 12054 12055 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) { 12056 FormatStyle MergeInlineOnly = getLLVMStyle(); 12057 MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 12058 verifyFormat("class C {\n" 12059 " int f() { return 42; }\n" 12060 "};", 12061 MergeInlineOnly); 12062 verifyFormat("int f() {\n" 12063 " return 42;\n" 12064 "}", 12065 MergeInlineOnly); 12066 12067 // SFS_Inline implies SFS_Empty 12068 verifyFormat("class C {\n" 12069 " int f() {}\n" 12070 "};", 12071 MergeInlineOnly); 12072 verifyFormat("int f() {}", MergeInlineOnly); 12073 12074 // Also verify behavior when BraceWrapping.AfterFunction = true 12075 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12076 MergeInlineOnly.BraceWrapping.AfterFunction = true; 12077 verifyFormat("class C {\n" 12078 " int f() { return 42; }\n" 12079 "};", 12080 MergeInlineOnly); 12081 verifyFormat("int f()\n" 12082 "{\n" 12083 " return 42;\n" 12084 "}", 12085 MergeInlineOnly); 12086 12087 // SFS_Inline implies SFS_Empty 12088 verifyFormat("int f() {}", MergeInlineOnly); 12089 verifyFormat("class C {\n" 12090 " int f() {}\n" 12091 "};", 12092 MergeInlineOnly); 12093 } 12094 12095 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) { 12096 FormatStyle MergeInlineOnly = getLLVMStyle(); 12097 MergeInlineOnly.AllowShortFunctionsOnASingleLine = 12098 FormatStyle::SFS_InlineOnly; 12099 verifyFormat("class C {\n" 12100 " int f() { return 42; }\n" 12101 "};", 12102 MergeInlineOnly); 12103 verifyFormat("int f() {\n" 12104 " return 42;\n" 12105 "}", 12106 MergeInlineOnly); 12107 12108 // SFS_InlineOnly does not imply SFS_Empty 12109 verifyFormat("class C {\n" 12110 " int f() {}\n" 12111 "};", 12112 MergeInlineOnly); 12113 verifyFormat("int f() {\n" 12114 "}", 12115 MergeInlineOnly); 12116 12117 // Also verify behavior when BraceWrapping.AfterFunction = true 12118 MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom; 12119 MergeInlineOnly.BraceWrapping.AfterFunction = true; 12120 verifyFormat("class C {\n" 12121 " int f() { return 42; }\n" 12122 "};", 12123 MergeInlineOnly); 12124 verifyFormat("int f()\n" 12125 "{\n" 12126 " return 42;\n" 12127 "}", 12128 MergeInlineOnly); 12129 12130 // SFS_InlineOnly does not imply SFS_Empty 12131 verifyFormat("int f()\n" 12132 "{\n" 12133 "}", 12134 MergeInlineOnly); 12135 verifyFormat("class C {\n" 12136 " int f() {}\n" 12137 "};", 12138 MergeInlineOnly); 12139 } 12140 12141 TEST_F(FormatTest, SplitEmptyFunction) { 12142 FormatStyle Style = getLLVMStyle(); 12143 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12144 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12145 Style.BraceWrapping.AfterFunction = true; 12146 Style.BraceWrapping.SplitEmptyFunction = false; 12147 Style.ColumnLimit = 40; 12148 12149 verifyFormat("int f()\n" 12150 "{}", 12151 Style); 12152 verifyFormat("int f()\n" 12153 "{\n" 12154 " return 42;\n" 12155 "}", 12156 Style); 12157 verifyFormat("int f()\n" 12158 "{\n" 12159 " // some comment\n" 12160 "}", 12161 Style); 12162 12163 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; 12164 verifyFormat("int f() {}", Style); 12165 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12166 "{}", 12167 Style); 12168 verifyFormat("int f()\n" 12169 "{\n" 12170 " return 0;\n" 12171 "}", 12172 Style); 12173 12174 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 12175 verifyFormat("class Foo {\n" 12176 " int f() {}\n" 12177 "};\n", 12178 Style); 12179 verifyFormat("class Foo {\n" 12180 " int f() { return 0; }\n" 12181 "};\n", 12182 Style); 12183 verifyFormat("class Foo {\n" 12184 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12185 " {}\n" 12186 "};\n", 12187 Style); 12188 verifyFormat("class Foo {\n" 12189 " int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12190 " {\n" 12191 " return 0;\n" 12192 " }\n" 12193 "};\n", 12194 Style); 12195 12196 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 12197 verifyFormat("int f() {}", Style); 12198 verifyFormat("int f() { return 0; }", Style); 12199 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12200 "{}", 12201 Style); 12202 verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n" 12203 "{\n" 12204 " return 0;\n" 12205 "}", 12206 Style); 12207 } 12208 12209 TEST_F(FormatTest, SplitEmptyFunctionButNotRecord) { 12210 FormatStyle Style = getLLVMStyle(); 12211 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 12212 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12213 Style.BraceWrapping.AfterFunction = true; 12214 Style.BraceWrapping.SplitEmptyFunction = true; 12215 Style.BraceWrapping.SplitEmptyRecord = false; 12216 Style.ColumnLimit = 40; 12217 12218 verifyFormat("class C {};", Style); 12219 verifyFormat("struct C {};", Style); 12220 verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12221 " int bbbbbbbbbbbbbbbbbbbbbbbb)\n" 12222 "{\n" 12223 "}", 12224 Style); 12225 verifyFormat("class C {\n" 12226 " C()\n" 12227 " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa(),\n" 12228 " bbbbbbbbbbbbbbbbbbb()\n" 12229 " {\n" 12230 " }\n" 12231 " void\n" 12232 " m(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" 12233 " int bbbbbbbbbbbbbbbbbbbbbbbb)\n" 12234 " {\n" 12235 " }\n" 12236 "};", 12237 Style); 12238 } 12239 12240 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) { 12241 FormatStyle Style = getLLVMStyle(); 12242 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 12243 verifyFormat("#ifdef A\n" 12244 "int f() {}\n" 12245 "#else\n" 12246 "int g() {}\n" 12247 "#endif", 12248 Style); 12249 } 12250 12251 TEST_F(FormatTest, SplitEmptyClass) { 12252 FormatStyle Style = getLLVMStyle(); 12253 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12254 Style.BraceWrapping.AfterClass = true; 12255 Style.BraceWrapping.SplitEmptyRecord = false; 12256 12257 verifyFormat("class Foo\n" 12258 "{};", 12259 Style); 12260 verifyFormat("/* something */ class Foo\n" 12261 "{};", 12262 Style); 12263 verifyFormat("template <typename X> class Foo\n" 12264 "{};", 12265 Style); 12266 verifyFormat("class Foo\n" 12267 "{\n" 12268 " Foo();\n" 12269 "};", 12270 Style); 12271 verifyFormat("typedef class Foo\n" 12272 "{\n" 12273 "} Foo_t;", 12274 Style); 12275 12276 Style.BraceWrapping.SplitEmptyRecord = true; 12277 Style.BraceWrapping.AfterStruct = true; 12278 verifyFormat("class rep\n" 12279 "{\n" 12280 "};", 12281 Style); 12282 verifyFormat("struct rep\n" 12283 "{\n" 12284 "};", 12285 Style); 12286 verifyFormat("template <typename T> class rep\n" 12287 "{\n" 12288 "};", 12289 Style); 12290 verifyFormat("template <typename T> struct rep\n" 12291 "{\n" 12292 "};", 12293 Style); 12294 verifyFormat("class rep\n" 12295 "{\n" 12296 " int x;\n" 12297 "};", 12298 Style); 12299 verifyFormat("struct rep\n" 12300 "{\n" 12301 " int x;\n" 12302 "};", 12303 Style); 12304 verifyFormat("template <typename T> class rep\n" 12305 "{\n" 12306 " int x;\n" 12307 "};", 12308 Style); 12309 verifyFormat("template <typename T> struct rep\n" 12310 "{\n" 12311 " int x;\n" 12312 "};", 12313 Style); 12314 verifyFormat("template <typename T> class rep // Foo\n" 12315 "{\n" 12316 " int x;\n" 12317 "};", 12318 Style); 12319 verifyFormat("template <typename T> struct rep // Bar\n" 12320 "{\n" 12321 " int x;\n" 12322 "};", 12323 Style); 12324 12325 verifyFormat("template <typename T> class rep<T>\n" 12326 "{\n" 12327 " int x;\n" 12328 "};", 12329 Style); 12330 12331 verifyFormat("template <typename T> class rep<std::complex<T>>\n" 12332 "{\n" 12333 " int x;\n" 12334 "};", 12335 Style); 12336 verifyFormat("template <typename T> class rep<std::complex<T>>\n" 12337 "{\n" 12338 "};", 12339 Style); 12340 12341 verifyFormat("#include \"stdint.h\"\n" 12342 "namespace rep {}", 12343 Style); 12344 verifyFormat("#include <stdint.h>\n" 12345 "namespace rep {}", 12346 Style); 12347 verifyFormat("#include <stdint.h>\n" 12348 "namespace rep {}", 12349 "#include <stdint.h>\n" 12350 "namespace rep {\n" 12351 "\n" 12352 "\n" 12353 "}", 12354 Style); 12355 } 12356 12357 TEST_F(FormatTest, SplitEmptyStruct) { 12358 FormatStyle Style = getLLVMStyle(); 12359 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12360 Style.BraceWrapping.AfterStruct = true; 12361 Style.BraceWrapping.SplitEmptyRecord = false; 12362 12363 verifyFormat("struct Foo\n" 12364 "{};", 12365 Style); 12366 verifyFormat("/* something */ struct Foo\n" 12367 "{};", 12368 Style); 12369 verifyFormat("template <typename X> struct Foo\n" 12370 "{};", 12371 Style); 12372 verifyFormat("struct Foo\n" 12373 "{\n" 12374 " Foo();\n" 12375 "};", 12376 Style); 12377 verifyFormat("typedef struct Foo\n" 12378 "{\n" 12379 "} Foo_t;", 12380 Style); 12381 // typedef struct Bar {} Bar_t; 12382 } 12383 12384 TEST_F(FormatTest, SplitEmptyUnion) { 12385 FormatStyle Style = getLLVMStyle(); 12386 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12387 Style.BraceWrapping.AfterUnion = true; 12388 Style.BraceWrapping.SplitEmptyRecord = false; 12389 12390 verifyFormat("union Foo\n" 12391 "{};", 12392 Style); 12393 verifyFormat("/* something */ union Foo\n" 12394 "{};", 12395 Style); 12396 verifyFormat("union Foo\n" 12397 "{\n" 12398 " A,\n" 12399 "};", 12400 Style); 12401 verifyFormat("typedef union Foo\n" 12402 "{\n" 12403 "} Foo_t;", 12404 Style); 12405 } 12406 12407 TEST_F(FormatTest, SplitEmptyNamespace) { 12408 FormatStyle Style = getLLVMStyle(); 12409 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12410 Style.BraceWrapping.AfterNamespace = true; 12411 Style.BraceWrapping.SplitEmptyNamespace = false; 12412 12413 verifyFormat("namespace Foo\n" 12414 "{};", 12415 Style); 12416 verifyFormat("/* something */ namespace Foo\n" 12417 "{};", 12418 Style); 12419 verifyFormat("inline namespace Foo\n" 12420 "{};", 12421 Style); 12422 verifyFormat("/* something */ inline namespace Foo\n" 12423 "{};", 12424 Style); 12425 verifyFormat("export namespace Foo\n" 12426 "{};", 12427 Style); 12428 verifyFormat("namespace Foo\n" 12429 "{\n" 12430 "void Bar();\n" 12431 "};", 12432 Style); 12433 } 12434 12435 TEST_F(FormatTest, NeverMergeShortRecords) { 12436 FormatStyle Style = getLLVMStyle(); 12437 12438 verifyFormat("class Foo {\n" 12439 " Foo();\n" 12440 "};", 12441 Style); 12442 verifyFormat("typedef class Foo {\n" 12443 " Foo();\n" 12444 "} Foo_t;", 12445 Style); 12446 verifyFormat("struct Foo {\n" 12447 " Foo();\n" 12448 "};", 12449 Style); 12450 verifyFormat("typedef struct Foo {\n" 12451 " Foo();\n" 12452 "} Foo_t;", 12453 Style); 12454 verifyFormat("union Foo {\n" 12455 " A,\n" 12456 "};", 12457 Style); 12458 verifyFormat("typedef union Foo {\n" 12459 " A,\n" 12460 "} Foo_t;", 12461 Style); 12462 verifyFormat("namespace Foo {\n" 12463 "void Bar();\n" 12464 "};", 12465 Style); 12466 12467 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 12468 Style.BraceWrapping.AfterClass = true; 12469 Style.BraceWrapping.AfterStruct = true; 12470 Style.BraceWrapping.AfterUnion = true; 12471 Style.BraceWrapping.AfterNamespace = true; 12472 verifyFormat("class Foo\n" 12473 "{\n" 12474 " Foo();\n" 12475 "};", 12476 Style); 12477 verifyFormat("typedef class Foo\n" 12478 "{\n" 12479 " Foo();\n" 12480 "} Foo_t;", 12481 Style); 12482 verifyFormat("struct Foo\n" 12483 "{\n" 12484 " Foo();\n" 12485 "};", 12486 Style); 12487 verifyFormat("typedef struct Foo\n" 12488 "{\n" 12489 " Foo();\n" 12490 "} Foo_t;", 12491 Style); 12492 verifyFormat("union Foo\n" 12493 "{\n" 12494 " A,\n" 12495 "};", 12496 Style); 12497 verifyFormat("typedef union Foo\n" 12498 "{\n" 12499 " A,\n" 12500 "} Foo_t;", 12501 Style); 12502 verifyFormat("namespace Foo\n" 12503 "{\n" 12504 "void Bar();\n" 12505 "};", 12506 Style); 12507 } 12508 12509 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) { 12510 // Elaborate type variable declarations. 12511 verifyFormat("struct foo a = {bar};\nint n;"); 12512 verifyFormat("class foo a = {bar};\nint n;"); 12513 verifyFormat("union foo a = {bar};\nint n;"); 12514 12515 // Elaborate types inside function definitions. 12516 verifyFormat("struct foo f() {}\nint n;"); 12517 verifyFormat("class foo f() {}\nint n;"); 12518 verifyFormat("union foo f() {}\nint n;"); 12519 12520 // Templates. 12521 verifyFormat("template <class X> void f() {}\nint n;"); 12522 verifyFormat("template <struct X> void f() {}\nint n;"); 12523 verifyFormat("template <union X> void f() {}\nint n;"); 12524 12525 // Actual definitions... 12526 verifyFormat("struct {\n} n;"); 12527 verifyFormat( 12528 "template <template <class T, class Y>, class Z> class X {\n} n;"); 12529 verifyFormat("union Z {\n int n;\n} x;"); 12530 verifyFormat("class MACRO Z {\n} n;"); 12531 verifyFormat("class MACRO(X) Z {\n} n;"); 12532 verifyFormat("class __attribute__(X) Z {\n} n;"); 12533 verifyFormat("class __declspec(X) Z {\n} n;"); 12534 verifyFormat("class A##B##C {\n} n;"); 12535 verifyFormat("class alignas(16) Z {\n} n;"); 12536 verifyFormat("class MACRO(X) alignas(16) Z {\n} n;"); 12537 verifyFormat("class MACROA MACRO(X) Z {\n} n;"); 12538 12539 // Redefinition from nested context: 12540 verifyFormat("class A::B::C {\n} n;"); 12541 12542 // Template definitions. 12543 verifyFormat( 12544 "template <typename F>\n" 12545 "Matcher(const Matcher<F> &Other,\n" 12546 " typename enable_if_c<is_base_of<F, T>::value &&\n" 12547 " !is_same<F, T>::value>::type * = 0)\n" 12548 " : Implementation(new ImplicitCastMatcher<F>(Other)) {}"); 12549 12550 // FIXME: This is still incorrectly handled at the formatter side. 12551 verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};"); 12552 verifyFormat("int i = SomeFunction(a<b, a> b);"); 12553 12554 // FIXME: 12555 // This now gets parsed incorrectly as class definition. 12556 // verifyFormat("class A<int> f() {\n}\nint n;"); 12557 12558 // Elaborate types where incorrectly parsing the structural element would 12559 // break the indent. 12560 verifyFormat("if (true)\n" 12561 " class X x;\n" 12562 "else\n" 12563 " f();\n"); 12564 12565 // This is simply incomplete. Formatting is not important, but must not crash. 12566 verifyFormat("class A:"); 12567 } 12568 12569 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) { 12570 EXPECT_EQ("#error Leave all white!!!!! space* alone!\n", 12571 format("#error Leave all white!!!!! space* alone!\n")); 12572 EXPECT_EQ( 12573 "#warning Leave all white!!!!! space* alone!\n", 12574 format("#warning Leave all white!!!!! space* alone!\n")); 12575 EXPECT_EQ("#error 1", format(" # error 1")); 12576 EXPECT_EQ("#warning 1", format(" # warning 1")); 12577 } 12578 12579 TEST_F(FormatTest, FormatHashIfExpressions) { 12580 verifyFormat("#if AAAA && BBBB"); 12581 verifyFormat("#if (AAAA && BBBB)"); 12582 verifyFormat("#elif (AAAA && BBBB)"); 12583 // FIXME: Come up with a better indentation for #elif. 12584 verifyFormat( 12585 "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) && \\\n" 12586 " defined(BBBBBBBB)\n" 12587 "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) && \\\n" 12588 " defined(BBBBBBBB)\n" 12589 "#endif", 12590 getLLVMStyleWithColumns(65)); 12591 } 12592 12593 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) { 12594 FormatStyle AllowsMergedIf = getGoogleStyle(); 12595 AllowsMergedIf.AllowShortIfStatementsOnASingleLine = 12596 FormatStyle::SIS_WithoutElse; 12597 verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf); 12598 verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf); 12599 verifyFormat("if (true)\n#error E\n return 42;", AllowsMergedIf); 12600 EXPECT_EQ("if (true) return 42;", 12601 format("if (true)\nreturn 42;", AllowsMergedIf)); 12602 FormatStyle ShortMergedIf = AllowsMergedIf; 12603 ShortMergedIf.ColumnLimit = 25; 12604 verifyFormat("#define A \\\n" 12605 " if (true) return 42;", 12606 ShortMergedIf); 12607 verifyFormat("#define A \\\n" 12608 " f(); \\\n" 12609 " if (true)\n" 12610 "#define B", 12611 ShortMergedIf); 12612 verifyFormat("#define A \\\n" 12613 " f(); \\\n" 12614 " if (true)\n" 12615 "g();", 12616 ShortMergedIf); 12617 verifyFormat("{\n" 12618 "#ifdef A\n" 12619 " // Comment\n" 12620 " if (true) continue;\n" 12621 "#endif\n" 12622 " // Comment\n" 12623 " if (true) continue;\n" 12624 "}", 12625 ShortMergedIf); 12626 ShortMergedIf.ColumnLimit = 33; 12627 verifyFormat("#define A \\\n" 12628 " if constexpr (true) return 42;", 12629 ShortMergedIf); 12630 verifyFormat("#define A \\\n" 12631 " if CONSTEXPR (true) return 42;", 12632 ShortMergedIf); 12633 ShortMergedIf.ColumnLimit = 29; 12634 verifyFormat("#define A \\\n" 12635 " if (aaaaaaaaaa) return 1; \\\n" 12636 " return 2;", 12637 ShortMergedIf); 12638 ShortMergedIf.ColumnLimit = 28; 12639 verifyFormat("#define A \\\n" 12640 " if (aaaaaaaaaa) \\\n" 12641 " return 1; \\\n" 12642 " return 2;", 12643 ShortMergedIf); 12644 verifyFormat("#define A \\\n" 12645 " if constexpr (aaaaaaa) \\\n" 12646 " return 1; \\\n" 12647 " return 2;", 12648 ShortMergedIf); 12649 verifyFormat("#define A \\\n" 12650 " if CONSTEXPR (aaaaaaa) \\\n" 12651 " return 1; \\\n" 12652 " return 2;", 12653 ShortMergedIf); 12654 } 12655 12656 TEST_F(FormatTest, FormatStarDependingOnContext) { 12657 verifyFormat("void f(int *a);"); 12658 verifyFormat("void f() { f(fint * b); }"); 12659 verifyFormat("class A {\n void f(int *a);\n};"); 12660 verifyFormat("class A {\n int *a;\n};"); 12661 verifyFormat("namespace a {\n" 12662 "namespace b {\n" 12663 "class A {\n" 12664 " void f() {}\n" 12665 " int *a;\n" 12666 "};\n" 12667 "} // namespace b\n" 12668 "} // namespace a"); 12669 } 12670 12671 TEST_F(FormatTest, SpecialTokensAtEndOfLine) { 12672 verifyFormat("while"); 12673 verifyFormat("operator"); 12674 } 12675 12676 TEST_F(FormatTest, SkipsDeeplyNestedLines) { 12677 // This code would be painfully slow to format if we didn't skip it. 12678 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 12679 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 12680 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 12681 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 12682 "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" 12683 "A(1, 1)\n" 12684 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x 12685 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 12686 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 12687 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 12688 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 12689 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 12690 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 12691 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 12692 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" 12693 ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n"); 12694 // Deeply nested part is untouched, rest is formatted. 12695 EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n", 12696 format(std::string("int i;\n") + Code + "int j;\n", 12697 getLLVMStyle(), SC_ExpectIncomplete)); 12698 } 12699 12700 //===----------------------------------------------------------------------===// 12701 // Objective-C tests. 12702 //===----------------------------------------------------------------------===// 12703 12704 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) { 12705 verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;"); 12706 EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;", 12707 format("-(NSUInteger)indexOfObject:(id)anObject;")); 12708 EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;")); 12709 EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;")); 12710 EXPECT_EQ("- (NSInteger)Method3:(id)anObject;", 12711 format("-(NSInteger)Method3:(id)anObject;")); 12712 EXPECT_EQ("- (NSInteger)Method4:(id)anObject;", 12713 format("-(NSInteger)Method4:(id)anObject;")); 12714 EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;", 12715 format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;")); 12716 EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;", 12717 format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;")); 12718 EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject " 12719 "forAllCells:(BOOL)flag;", 12720 format("- (void)sendAction:(SEL)aSelector to:(id)anObject " 12721 "forAllCells:(BOOL)flag;")); 12722 12723 // Very long objectiveC method declaration. 12724 verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n" 12725 " (SoooooooooooooooooooooomeType *)bbbbbbbbbb;"); 12726 verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n" 12727 " inRange:(NSRange)range\n" 12728 " outRange:(NSRange)out_range\n" 12729 " outRange1:(NSRange)out_range1\n" 12730 " outRange2:(NSRange)out_range2\n" 12731 " outRange3:(NSRange)out_range3\n" 12732 " outRange4:(NSRange)out_range4\n" 12733 " outRange5:(NSRange)out_range5\n" 12734 " outRange6:(NSRange)out_range6\n" 12735 " outRange7:(NSRange)out_range7\n" 12736 " outRange8:(NSRange)out_range8\n" 12737 " outRange9:(NSRange)out_range9;"); 12738 12739 // When the function name has to be wrapped. 12740 FormatStyle Style = getLLVMStyle(); 12741 // ObjC ignores IndentWrappedFunctionNames when wrapping methods 12742 // and always indents instead. 12743 Style.IndentWrappedFunctionNames = false; 12744 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n" 12745 " veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n" 12746 " anotherName:(NSString)bbbbbbbbbbbbbb {\n" 12747 "}", 12748 Style); 12749 Style.IndentWrappedFunctionNames = true; 12750 verifyFormat("- (SomeLooooooooooooooooooooongType *)\n" 12751 " veryLooooooooooongName:(NSString)cccccccccccccc\n" 12752 " anotherName:(NSString)dddddddddddddd {\n" 12753 "}", 12754 Style); 12755 12756 verifyFormat("- (int)sum:(vector<int>)numbers;"); 12757 verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;"); 12758 // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC 12759 // protocol lists (but not for template classes): 12760 // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;"); 12761 12762 verifyFormat("- (int (*)())foo:(int (*)())f;"); 12763 verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;"); 12764 12765 // If there's no return type (very rare in practice!), LLVM and Google style 12766 // agree. 12767 verifyFormat("- foo;"); 12768 verifyFormat("- foo:(int)f;"); 12769 verifyGoogleFormat("- foo:(int)foo;"); 12770 } 12771 12772 TEST_F(FormatTest, BreaksStringLiterals) { 12773 EXPECT_EQ("\"some text \"\n" 12774 "\"other\";", 12775 format("\"some text other\";", getLLVMStyleWithColumns(12))); 12776 EXPECT_EQ("\"some text \"\n" 12777 "\"other\";", 12778 format("\\\n\"some text other\";", getLLVMStyleWithColumns(12))); 12779 EXPECT_EQ( 12780 "#define A \\\n" 12781 " \"some \" \\\n" 12782 " \"text \" \\\n" 12783 " \"other\";", 12784 format("#define A \"some text other\";", getLLVMStyleWithColumns(12))); 12785 EXPECT_EQ( 12786 "#define A \\\n" 12787 " \"so \" \\\n" 12788 " \"text \" \\\n" 12789 " \"other\";", 12790 format("#define A \"so text other\";", getLLVMStyleWithColumns(12))); 12791 12792 EXPECT_EQ("\"some text\"", 12793 format("\"some text\"", getLLVMStyleWithColumns(1))); 12794 EXPECT_EQ("\"some text\"", 12795 format("\"some text\"", getLLVMStyleWithColumns(11))); 12796 EXPECT_EQ("\"some \"\n" 12797 "\"text\"", 12798 format("\"some text\"", getLLVMStyleWithColumns(10))); 12799 EXPECT_EQ("\"some \"\n" 12800 "\"text\"", 12801 format("\"some text\"", getLLVMStyleWithColumns(7))); 12802 EXPECT_EQ("\"some\"\n" 12803 "\" tex\"\n" 12804 "\"t\"", 12805 format("\"some text\"", getLLVMStyleWithColumns(6))); 12806 EXPECT_EQ("\"some\"\n" 12807 "\" tex\"\n" 12808 "\" and\"", 12809 format("\"some tex and\"", getLLVMStyleWithColumns(6))); 12810 EXPECT_EQ("\"some\"\n" 12811 "\"/tex\"\n" 12812 "\"/and\"", 12813 format("\"some/tex/and\"", getLLVMStyleWithColumns(6))); 12814 12815 EXPECT_EQ("variable =\n" 12816 " \"long string \"\n" 12817 " \"literal\";", 12818 format("variable = \"long string literal\";", 12819 getLLVMStyleWithColumns(20))); 12820 12821 EXPECT_EQ("variable = f(\n" 12822 " \"long string \"\n" 12823 " \"literal\",\n" 12824 " short,\n" 12825 " loooooooooooooooooooong);", 12826 format("variable = f(\"long string literal\", short, " 12827 "loooooooooooooooooooong);", 12828 getLLVMStyleWithColumns(20))); 12829 12830 EXPECT_EQ( 12831 "f(g(\"long string \"\n" 12832 " \"literal\"),\n" 12833 " b);", 12834 format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20))); 12835 EXPECT_EQ("f(g(\"long string \"\n" 12836 " \"literal\",\n" 12837 " a),\n" 12838 " b);", 12839 format("f(g(\"long string literal\", a), b);", 12840 getLLVMStyleWithColumns(20))); 12841 EXPECT_EQ( 12842 "f(\"one two\".split(\n" 12843 " variable));", 12844 format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20))); 12845 EXPECT_EQ("f(\"one two three four five six \"\n" 12846 " \"seven\".split(\n" 12847 " really_looooong_variable));", 12848 format("f(\"one two three four five six seven\"." 12849 "split(really_looooong_variable));", 12850 getLLVMStyleWithColumns(33))); 12851 12852 EXPECT_EQ("f(\"some \"\n" 12853 " \"text\",\n" 12854 " other);", 12855 format("f(\"some text\", other);", getLLVMStyleWithColumns(10))); 12856 12857 // Only break as a last resort. 12858 verifyFormat( 12859 "aaaaaaaaaaaaaaaaaaaa(\n" 12860 " aaaaaaaaaaaaaaaaaaaa,\n" 12861 " aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));"); 12862 12863 EXPECT_EQ("\"splitmea\"\n" 12864 "\"trandomp\"\n" 12865 "\"oint\"", 12866 format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10))); 12867 12868 EXPECT_EQ("\"split/\"\n" 12869 "\"pathat/\"\n" 12870 "\"slashes\"", 12871 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10))); 12872 12873 EXPECT_EQ("\"split/\"\n" 12874 "\"pathat/\"\n" 12875 "\"slashes\"", 12876 format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10))); 12877 EXPECT_EQ("\"split at \"\n" 12878 "\"spaces/at/\"\n" 12879 "\"slashes.at.any$\"\n" 12880 "\"non-alphanumeric%\"\n" 12881 "\"1111111111characte\"\n" 12882 "\"rs\"", 12883 format("\"split at " 12884 "spaces/at/" 12885 "slashes.at." 12886 "any$non-" 12887 "alphanumeric%" 12888 "1111111111characte" 12889 "rs\"", 12890 getLLVMStyleWithColumns(20))); 12891 12892 // Verify that splitting the strings understands 12893 // Style::AlwaysBreakBeforeMultilineStrings. 12894 EXPECT_EQ("aaaaaaaaaaaa(\n" 12895 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n" 12896 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");", 12897 format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa " 12898 "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa " 12899 "aaaaaaaaaaaaaaaaaaaaaa\");", 12900 getGoogleStyle())); 12901 EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 12902 " \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";", 12903 format("return \"aaaaaaaaaaaaaaaaaaaaaa " 12904 "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa " 12905 "aaaaaaaaaaaaaaaaaaaaaa\";", 12906 getGoogleStyle())); 12907 EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 12908 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";", 12909 format("llvm::outs() << " 12910 "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa" 12911 "aaaaaaaaaaaaaaaaaaa\";")); 12912 EXPECT_EQ("ffff(\n" 12913 " {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" 12914 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});", 12915 format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa " 12916 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});", 12917 getGoogleStyle())); 12918 12919 FormatStyle Style = getLLVMStyleWithColumns(12); 12920 Style.BreakStringLiterals = false; 12921 EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style)); 12922 12923 FormatStyle AlignLeft = getLLVMStyleWithColumns(12); 12924 AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left; 12925 EXPECT_EQ("#define A \\\n" 12926 " \"some \" \\\n" 12927 " \"text \" \\\n" 12928 " \"other\";", 12929 format("#define A \"some text other\";", AlignLeft)); 12930 } 12931 12932 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) { 12933 EXPECT_EQ("C a = \"some more \"\n" 12934 " \"text\";", 12935 format("C a = \"some more text\";", getLLVMStyleWithColumns(18))); 12936 } 12937 12938 TEST_F(FormatTest, FullyRemoveEmptyLines) { 12939 FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80); 12940 NoEmptyLines.MaxEmptyLinesToKeep = 0; 12941 EXPECT_EQ("int i = a(b());", 12942 format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines)); 12943 } 12944 12945 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) { 12946 EXPECT_EQ( 12947 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 12948 "(\n" 12949 " \"x\t\");", 12950 format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 12951 "aaaaaaa(" 12952 "\"x\t\");")); 12953 } 12954 12955 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) { 12956 EXPECT_EQ( 12957 "u8\"utf8 string \"\n" 12958 "u8\"literal\";", 12959 format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16))); 12960 EXPECT_EQ( 12961 "u\"utf16 string \"\n" 12962 "u\"literal\";", 12963 format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16))); 12964 EXPECT_EQ( 12965 "U\"utf32 string \"\n" 12966 "U\"literal\";", 12967 format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16))); 12968 EXPECT_EQ("L\"wide string \"\n" 12969 "L\"literal\";", 12970 format("L\"wide string literal\";", getGoogleStyleWithColumns(16))); 12971 EXPECT_EQ("@\"NSString \"\n" 12972 "@\"literal\";", 12973 format("@\"NSString literal\";", getGoogleStyleWithColumns(19))); 12974 verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26)); 12975 12976 // This input makes clang-format try to split the incomplete unicode escape 12977 // sequence, which used to lead to a crasher. 12978 verifyNoCrash( 12979 "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 12980 getLLVMStyleWithColumns(60)); 12981 } 12982 12983 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) { 12984 FormatStyle Style = getGoogleStyleWithColumns(15); 12985 EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style)); 12986 EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style)); 12987 EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style)); 12988 EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style)); 12989 EXPECT_EQ("u8R\"x(raw literal)x\";", 12990 format("u8R\"x(raw literal)x\";", Style)); 12991 } 12992 12993 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) { 12994 FormatStyle Style = getLLVMStyleWithColumns(20); 12995 EXPECT_EQ( 12996 "_T(\"aaaaaaaaaaaaaa\")\n" 12997 "_T(\"aaaaaaaaaaaaaa\")\n" 12998 "_T(\"aaaaaaaaaaaa\")", 12999 format(" _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style)); 13000 EXPECT_EQ("f(x,\n" 13001 " _T(\"aaaaaaaaaaaa\")\n" 13002 " _T(\"aaa\"),\n" 13003 " z);", 13004 format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style)); 13005 13006 // FIXME: Handle embedded spaces in one iteration. 13007 // EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n" 13008 // "_T(\"aaaaaaaaaaaaa\")\n" 13009 // "_T(\"aaaaaaaaaaaaa\")\n" 13010 // "_T(\"a\")", 13011 // format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", 13012 // getLLVMStyleWithColumns(20))); 13013 EXPECT_EQ( 13014 "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", 13015 format(" _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style)); 13016 EXPECT_EQ("f(\n" 13017 "#if !TEST\n" 13018 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n" 13019 "#endif\n" 13020 ");", 13021 format("f(\n" 13022 "#if !TEST\n" 13023 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n" 13024 "#endif\n" 13025 ");")); 13026 EXPECT_EQ("f(\n" 13027 "\n" 13028 " _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));", 13029 format("f(\n" 13030 "\n" 13031 "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));")); 13032 // Regression test for accessing tokens past the end of a vector in the 13033 // TokenLexer. 13034 verifyNoCrash(R"(_T( 13035 " 13036 ) 13037 )"); 13038 } 13039 13040 TEST_F(FormatTest, BreaksStringLiteralOperands) { 13041 // In a function call with two operands, the second can be broken with no line 13042 // break before it. 13043 EXPECT_EQ( 13044 "func(a, \"long long \"\n" 13045 " \"long long\");", 13046 format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24))); 13047 // In a function call with three operands, the second must be broken with a 13048 // line break before it. 13049 EXPECT_EQ("func(a,\n" 13050 " \"long long long \"\n" 13051 " \"long\",\n" 13052 " c);", 13053 format("func(a, \"long long long long\", c);", 13054 getLLVMStyleWithColumns(24))); 13055 // In a function call with three operands, the third must be broken with a 13056 // line break before it. 13057 EXPECT_EQ("func(a, b,\n" 13058 " \"long long long \"\n" 13059 " \"long\");", 13060 format("func(a, b, \"long long long long\");", 13061 getLLVMStyleWithColumns(24))); 13062 // In a function call with three operands, both the second and the third must 13063 // be broken with a line break before them. 13064 EXPECT_EQ("func(a,\n" 13065 " \"long long long \"\n" 13066 " \"long\",\n" 13067 " \"long long long \"\n" 13068 " \"long\");", 13069 format("func(a, \"long long long long\", \"long long long long\");", 13070 getLLVMStyleWithColumns(24))); 13071 // In a chain of << with two operands, the second can be broken with no line 13072 // break before it. 13073 EXPECT_EQ("a << \"line line \"\n" 13074 " \"line\";", 13075 format("a << \"line line line\";", getLLVMStyleWithColumns(20))); 13076 // In a chain of << with three operands, the second can be broken with no line 13077 // break before it. 13078 EXPECT_EQ( 13079 "abcde << \"line \"\n" 13080 " \"line line\"\n" 13081 " << c;", 13082 format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20))); 13083 // In a chain of << with three operands, the third must be broken with a line 13084 // break before it. 13085 EXPECT_EQ( 13086 "a << b\n" 13087 " << \"line line \"\n" 13088 " \"line\";", 13089 format("a << b << \"line line line\";", getLLVMStyleWithColumns(20))); 13090 // In a chain of << with three operands, the second can be broken with no line 13091 // break before it and the third must be broken with a line break before it. 13092 EXPECT_EQ("abcd << \"line line \"\n" 13093 " \"line\"\n" 13094 " << \"line line \"\n" 13095 " \"line\";", 13096 format("abcd << \"line line line\" << \"line line line\";", 13097 getLLVMStyleWithColumns(20))); 13098 // In a chain of binary operators with two operands, the second can be broken 13099 // with no line break before it. 13100 EXPECT_EQ( 13101 "abcd + \"line line \"\n" 13102 " \"line line\";", 13103 format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20))); 13104 // In a chain of binary operators with three operands, the second must be 13105 // broken with a line break before it. 13106 EXPECT_EQ("abcd +\n" 13107 " \"line line \"\n" 13108 " \"line line\" +\n" 13109 " e;", 13110 format("abcd + \"line line line line\" + e;", 13111 getLLVMStyleWithColumns(20))); 13112 // In a function call with two operands, with AlignAfterOpenBracket enabled, 13113 // the first must be broken with a line break before it. 13114 FormatStyle Style = getLLVMStyleWithColumns(25); 13115 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 13116 EXPECT_EQ("someFunction(\n" 13117 " \"long long long \"\n" 13118 " \"long\",\n" 13119 " a);", 13120 format("someFunction(\"long long long long\", a);", Style)); 13121 } 13122 13123 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) { 13124 EXPECT_EQ( 13125 "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13126 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13127 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";", 13128 format("aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13129 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n" 13130 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";")); 13131 } 13132 13133 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) { 13134 EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);", 13135 format("f(g(R\"x(raw literal)x\", a), b);", getGoogleStyle())); 13136 EXPECT_EQ("fffffffffff(g(R\"x(\n" 13137 "multiline raw string literal xxxxxxxxxxxxxx\n" 13138 ")x\",\n" 13139 " a),\n" 13140 " b);", 13141 format("fffffffffff(g(R\"x(\n" 13142 "multiline raw string literal xxxxxxxxxxxxxx\n" 13143 ")x\", a), b);", 13144 getGoogleStyleWithColumns(20))); 13145 EXPECT_EQ("fffffffffff(\n" 13146 " g(R\"x(qqq\n" 13147 "multiline raw string literal xxxxxxxxxxxxxx\n" 13148 ")x\",\n" 13149 " a),\n" 13150 " b);", 13151 format("fffffffffff(g(R\"x(qqq\n" 13152 "multiline raw string literal xxxxxxxxxxxxxx\n" 13153 ")x\", a), b);", 13154 getGoogleStyleWithColumns(20))); 13155 13156 EXPECT_EQ("fffffffffff(R\"x(\n" 13157 "multiline raw string literal xxxxxxxxxxxxxx\n" 13158 ")x\");", 13159 format("fffffffffff(R\"x(\n" 13160 "multiline raw string literal xxxxxxxxxxxxxx\n" 13161 ")x\");", 13162 getGoogleStyleWithColumns(20))); 13163 EXPECT_EQ("fffffffffff(R\"x(\n" 13164 "multiline raw string literal xxxxxxxxxxxxxx\n" 13165 ")x\" + bbbbbb);", 13166 format("fffffffffff(R\"x(\n" 13167 "multiline raw string literal xxxxxxxxxxxxxx\n" 13168 ")x\" + bbbbbb);", 13169 getGoogleStyleWithColumns(20))); 13170 EXPECT_EQ("fffffffffff(\n" 13171 " R\"x(\n" 13172 "multiline raw string literal xxxxxxxxxxxxxx\n" 13173 ")x\" +\n" 13174 " bbbbbb);", 13175 format("fffffffffff(\n" 13176 " R\"x(\n" 13177 "multiline raw string literal xxxxxxxxxxxxxx\n" 13178 ")x\" + bbbbbb);", 13179 getGoogleStyleWithColumns(20))); 13180 EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);", 13181 format("fffffffffff(\n" 13182 " R\"(single line raw string)\" + bbbbbb);")); 13183 } 13184 13185 TEST_F(FormatTest, SkipsUnknownStringLiterals) { 13186 verifyFormat("string a = \"unterminated;"); 13187 EXPECT_EQ("function(\"unterminated,\n" 13188 " OtherParameter);", 13189 format("function( \"unterminated,\n" 13190 " OtherParameter);")); 13191 } 13192 13193 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) { 13194 FormatStyle Style = getLLVMStyle(); 13195 Style.Standard = FormatStyle::LS_Cpp03; 13196 EXPECT_EQ("#define x(_a) printf(\"foo\" _a);", 13197 format("#define x(_a) printf(\"foo\"_a);", Style)); 13198 } 13199 13200 TEST_F(FormatTest, CppLexVersion) { 13201 FormatStyle Style = getLLVMStyle(); 13202 // Formatting of x * y differs if x is a type. 13203 verifyFormat("void foo() { MACRO(a * b); }", Style); 13204 verifyFormat("void foo() { MACRO(int *b); }", Style); 13205 13206 // LLVM style uses latest lexer. 13207 verifyFormat("void foo() { MACRO(char8_t *b); }", Style); 13208 Style.Standard = FormatStyle::LS_Cpp17; 13209 // But in c++17, char8_t isn't a keyword. 13210 verifyFormat("void foo() { MACRO(char8_t * b); }", Style); 13211 } 13212 13213 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); } 13214 13215 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) { 13216 EXPECT_EQ("someFunction(\"aaabbbcccd\"\n" 13217 " \"ddeeefff\");", 13218 format("someFunction(\"aaabbbcccdddeeefff\");", 13219 getLLVMStyleWithColumns(25))); 13220 EXPECT_EQ("someFunction1234567890(\n" 13221 " \"aaabbbcccdddeeefff\");", 13222 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 13223 getLLVMStyleWithColumns(26))); 13224 EXPECT_EQ("someFunction1234567890(\n" 13225 " \"aaabbbcccdddeeeff\"\n" 13226 " \"f\");", 13227 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 13228 getLLVMStyleWithColumns(25))); 13229 EXPECT_EQ("someFunction1234567890(\n" 13230 " \"aaabbbcccdddeeeff\"\n" 13231 " \"f\");", 13232 format("someFunction1234567890(\"aaabbbcccdddeeefff\");", 13233 getLLVMStyleWithColumns(24))); 13234 EXPECT_EQ("someFunction(\n" 13235 " \"aaabbbcc ddde \"\n" 13236 " \"efff\");", 13237 format("someFunction(\"aaabbbcc ddde efff\");", 13238 getLLVMStyleWithColumns(25))); 13239 EXPECT_EQ("someFunction(\"aaabbbccc \"\n" 13240 " \"ddeeefff\");", 13241 format("someFunction(\"aaabbbccc ddeeefff\");", 13242 getLLVMStyleWithColumns(25))); 13243 EXPECT_EQ("someFunction1234567890(\n" 13244 " \"aaabb \"\n" 13245 " \"cccdddeeefff\");", 13246 format("someFunction1234567890(\"aaabb cccdddeeefff\");", 13247 getLLVMStyleWithColumns(25))); 13248 EXPECT_EQ("#define A \\\n" 13249 " string s = \\\n" 13250 " \"123456789\" \\\n" 13251 " \"0\"; \\\n" 13252 " int i;", 13253 format("#define A string s = \"1234567890\"; int i;", 13254 getLLVMStyleWithColumns(20))); 13255 EXPECT_EQ("someFunction(\n" 13256 " \"aaabbbcc \"\n" 13257 " \"dddeeefff\");", 13258 format("someFunction(\"aaabbbcc dddeeefff\");", 13259 getLLVMStyleWithColumns(25))); 13260 } 13261 13262 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) { 13263 EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3))); 13264 EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2))); 13265 EXPECT_EQ("\"test\"\n" 13266 "\"\\n\"", 13267 format("\"test\\n\"", getLLVMStyleWithColumns(7))); 13268 EXPECT_EQ("\"tes\\\\\"\n" 13269 "\"n\"", 13270 format("\"tes\\\\n\"", getLLVMStyleWithColumns(7))); 13271 EXPECT_EQ("\"\\\\\\\\\"\n" 13272 "\"\\n\"", 13273 format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7))); 13274 EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7))); 13275 EXPECT_EQ("\"\\uff01\"\n" 13276 "\"test\"", 13277 format("\"\\uff01test\"", getLLVMStyleWithColumns(8))); 13278 EXPECT_EQ("\"\\Uff01ff02\"", 13279 format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11))); 13280 EXPECT_EQ("\"\\x000000000001\"\n" 13281 "\"next\"", 13282 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16))); 13283 EXPECT_EQ("\"\\x000000000001next\"", 13284 format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15))); 13285 EXPECT_EQ("\"\\x000000000001\"", 13286 format("\"\\x000000000001\"", getLLVMStyleWithColumns(7))); 13287 EXPECT_EQ("\"test\"\n" 13288 "\"\\000000\"\n" 13289 "\"000001\"", 13290 format("\"test\\000000000001\"", getLLVMStyleWithColumns(9))); 13291 EXPECT_EQ("\"test\\000\"\n" 13292 "\"00000000\"\n" 13293 "\"1\"", 13294 format("\"test\\000000000001\"", getLLVMStyleWithColumns(10))); 13295 } 13296 13297 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) { 13298 verifyFormat("void f() {\n" 13299 " return g() {}\n" 13300 " void h() {}"); 13301 verifyFormat("int a[] = {void forgot_closing_brace(){f();\n" 13302 "g();\n" 13303 "}"); 13304 } 13305 13306 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) { 13307 verifyFormat( 13308 "void f() { return C{param1, param2}.SomeCall(param1, param2); }"); 13309 } 13310 13311 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) { 13312 verifyFormat("class X {\n" 13313 " void f() {\n" 13314 " }\n" 13315 "};", 13316 getLLVMStyleWithColumns(12)); 13317 } 13318 13319 TEST_F(FormatTest, ConfigurableIndentWidth) { 13320 FormatStyle EightIndent = getLLVMStyleWithColumns(18); 13321 EightIndent.IndentWidth = 8; 13322 EightIndent.ContinuationIndentWidth = 8; 13323 verifyFormat("void f() {\n" 13324 " someFunction();\n" 13325 " if (true) {\n" 13326 " f();\n" 13327 " }\n" 13328 "}", 13329 EightIndent); 13330 verifyFormat("class X {\n" 13331 " void f() {\n" 13332 " }\n" 13333 "};", 13334 EightIndent); 13335 verifyFormat("int x[] = {\n" 13336 " call(),\n" 13337 " call()};", 13338 EightIndent); 13339 } 13340 13341 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) { 13342 verifyFormat("double\n" 13343 "f();", 13344 getLLVMStyleWithColumns(8)); 13345 } 13346 13347 TEST_F(FormatTest, ConfigurableUseOfTab) { 13348 FormatStyle Tab = getLLVMStyleWithColumns(42); 13349 Tab.IndentWidth = 8; 13350 Tab.UseTab = FormatStyle::UT_Always; 13351 Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left; 13352 13353 EXPECT_EQ("if (aaaaaaaa && // q\n" 13354 " bb)\t\t// w\n" 13355 "\t;", 13356 format("if (aaaaaaaa &&// q\n" 13357 "bb)// w\n" 13358 ";", 13359 Tab)); 13360 EXPECT_EQ("if (aaa && bbb) // w\n" 13361 "\t;", 13362 format("if(aaa&&bbb)// w\n" 13363 ";", 13364 Tab)); 13365 13366 verifyFormat("class X {\n" 13367 "\tvoid f() {\n" 13368 "\t\tsomeFunction(parameter1,\n" 13369 "\t\t\t parameter2);\n" 13370 "\t}\n" 13371 "};", 13372 Tab); 13373 verifyFormat("#define A \\\n" 13374 "\tvoid f() { \\\n" 13375 "\t\tsomeFunction( \\\n" 13376 "\t\t parameter1, \\\n" 13377 "\t\t parameter2); \\\n" 13378 "\t}", 13379 Tab); 13380 verifyFormat("int a;\t // x\n" 13381 "int bbbbbbbb; // x\n", 13382 Tab); 13383 13384 Tab.TabWidth = 4; 13385 Tab.IndentWidth = 8; 13386 verifyFormat("class TabWidth4Indent8 {\n" 13387 "\t\tvoid f() {\n" 13388 "\t\t\t\tsomeFunction(parameter1,\n" 13389 "\t\t\t\t\t\t\t parameter2);\n" 13390 "\t\t}\n" 13391 "};", 13392 Tab); 13393 13394 Tab.TabWidth = 4; 13395 Tab.IndentWidth = 4; 13396 verifyFormat("class TabWidth4Indent4 {\n" 13397 "\tvoid f() {\n" 13398 "\t\tsomeFunction(parameter1,\n" 13399 "\t\t\t\t\t parameter2);\n" 13400 "\t}\n" 13401 "};", 13402 Tab); 13403 13404 Tab.TabWidth = 8; 13405 Tab.IndentWidth = 4; 13406 verifyFormat("class TabWidth8Indent4 {\n" 13407 " void f() {\n" 13408 "\tsomeFunction(parameter1,\n" 13409 "\t\t parameter2);\n" 13410 " }\n" 13411 "};", 13412 Tab); 13413 13414 Tab.TabWidth = 8; 13415 Tab.IndentWidth = 8; 13416 EXPECT_EQ("/*\n" 13417 "\t a\t\tcomment\n" 13418 "\t in multiple lines\n" 13419 " */", 13420 format(" /*\t \t \n" 13421 " \t \t a\t\tcomment\t \t\n" 13422 " \t \t in multiple lines\t\n" 13423 " \t */", 13424 Tab)); 13425 13426 Tab.UseTab = FormatStyle::UT_ForIndentation; 13427 verifyFormat("{\n" 13428 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13429 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13430 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13431 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13432 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13433 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13434 "};", 13435 Tab); 13436 verifyFormat("enum AA {\n" 13437 "\ta1, // Force multiple lines\n" 13438 "\ta2,\n" 13439 "\ta3\n" 13440 "};", 13441 Tab); 13442 EXPECT_EQ("if (aaaaaaaa && // q\n" 13443 " bb) // w\n" 13444 "\t;", 13445 format("if (aaaaaaaa &&// q\n" 13446 "bb)// w\n" 13447 ";", 13448 Tab)); 13449 verifyFormat("class X {\n" 13450 "\tvoid f() {\n" 13451 "\t\tsomeFunction(parameter1,\n" 13452 "\t\t parameter2);\n" 13453 "\t}\n" 13454 "};", 13455 Tab); 13456 verifyFormat("{\n" 13457 "\tQ(\n" 13458 "\t {\n" 13459 "\t\t int a;\n" 13460 "\t\t someFunction(aaaaaaaa,\n" 13461 "\t\t bbbbbbb);\n" 13462 "\t },\n" 13463 "\t p);\n" 13464 "}", 13465 Tab); 13466 EXPECT_EQ("{\n" 13467 "\t/* aaaa\n" 13468 "\t bbbb */\n" 13469 "}", 13470 format("{\n" 13471 "/* aaaa\n" 13472 " bbbb */\n" 13473 "}", 13474 Tab)); 13475 EXPECT_EQ("{\n" 13476 "\t/*\n" 13477 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 13478 "\t bbbbbbbbbbbbb\n" 13479 "\t*/\n" 13480 "}", 13481 format("{\n" 13482 "/*\n" 13483 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 13484 "*/\n" 13485 "}", 13486 Tab)); 13487 EXPECT_EQ("{\n" 13488 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 13489 "\t// bbbbbbbbbbbbb\n" 13490 "}", 13491 format("{\n" 13492 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 13493 "}", 13494 Tab)); 13495 EXPECT_EQ("{\n" 13496 "\t/*\n" 13497 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 13498 "\t bbbbbbbbbbbbb\n" 13499 "\t*/\n" 13500 "}", 13501 format("{\n" 13502 "\t/*\n" 13503 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 13504 "\t*/\n" 13505 "}", 13506 Tab)); 13507 EXPECT_EQ("{\n" 13508 "\t/*\n" 13509 "\n" 13510 "\t*/\n" 13511 "}", 13512 format("{\n" 13513 "\t/*\n" 13514 "\n" 13515 "\t*/\n" 13516 "}", 13517 Tab)); 13518 EXPECT_EQ("{\n" 13519 "\t/*\n" 13520 " asdf\n" 13521 "\t*/\n" 13522 "}", 13523 format("{\n" 13524 "\t/*\n" 13525 " asdf\n" 13526 "\t*/\n" 13527 "}", 13528 Tab)); 13529 13530 verifyFormat("void f() {\n" 13531 "\treturn true ? aaaaaaaaaaaaaaaaaa\n" 13532 "\t : bbbbbbbbbbbbbbbbbb\n" 13533 "}", 13534 Tab); 13535 FormatStyle TabNoBreak = Tab; 13536 TabNoBreak.BreakBeforeTernaryOperators = false; 13537 verifyFormat("void f() {\n" 13538 "\treturn true ? aaaaaaaaaaaaaaaaaa :\n" 13539 "\t bbbbbbbbbbbbbbbbbb\n" 13540 "}", 13541 TabNoBreak); 13542 verifyFormat("void f() {\n" 13543 "\treturn true ?\n" 13544 "\t aaaaaaaaaaaaaaaaaaaa :\n" 13545 "\t bbbbbbbbbbbbbbbbbbbb\n" 13546 "}", 13547 TabNoBreak); 13548 13549 Tab.UseTab = FormatStyle::UT_Never; 13550 EXPECT_EQ("/*\n" 13551 " a\t\tcomment\n" 13552 " in multiple lines\n" 13553 " */", 13554 format(" /*\t \t \n" 13555 " \t \t a\t\tcomment\t \t\n" 13556 " \t \t in multiple lines\t\n" 13557 " \t */", 13558 Tab)); 13559 EXPECT_EQ("/* some\n" 13560 " comment */", 13561 format(" \t \t /* some\n" 13562 " \t \t comment */", 13563 Tab)); 13564 EXPECT_EQ("int a; /* some\n" 13565 " comment */", 13566 format(" \t \t int a; /* some\n" 13567 " \t \t comment */", 13568 Tab)); 13569 13570 EXPECT_EQ("int a; /* some\n" 13571 "comment */", 13572 format(" \t \t int\ta; /* some\n" 13573 " \t \t comment */", 13574 Tab)); 13575 EXPECT_EQ("f(\"\t\t\"); /* some\n" 13576 " comment */", 13577 format(" \t \t f(\"\t\t\"); /* some\n" 13578 " \t \t comment */", 13579 Tab)); 13580 EXPECT_EQ("{\n" 13581 " /*\n" 13582 " * Comment\n" 13583 " */\n" 13584 " int i;\n" 13585 "}", 13586 format("{\n" 13587 "\t/*\n" 13588 "\t * Comment\n" 13589 "\t */\n" 13590 "\t int i;\n" 13591 "}", 13592 Tab)); 13593 13594 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation; 13595 Tab.TabWidth = 8; 13596 Tab.IndentWidth = 8; 13597 EXPECT_EQ("if (aaaaaaaa && // q\n" 13598 " bb) // w\n" 13599 "\t;", 13600 format("if (aaaaaaaa &&// q\n" 13601 "bb)// w\n" 13602 ";", 13603 Tab)); 13604 EXPECT_EQ("if (aaa && bbb) // w\n" 13605 "\t;", 13606 format("if(aaa&&bbb)// w\n" 13607 ";", 13608 Tab)); 13609 verifyFormat("class X {\n" 13610 "\tvoid f() {\n" 13611 "\t\tsomeFunction(parameter1,\n" 13612 "\t\t\t parameter2);\n" 13613 "\t}\n" 13614 "};", 13615 Tab); 13616 verifyFormat("#define A \\\n" 13617 "\tvoid f() { \\\n" 13618 "\t\tsomeFunction( \\\n" 13619 "\t\t parameter1, \\\n" 13620 "\t\t parameter2); \\\n" 13621 "\t}", 13622 Tab); 13623 Tab.TabWidth = 4; 13624 Tab.IndentWidth = 8; 13625 verifyFormat("class TabWidth4Indent8 {\n" 13626 "\t\tvoid f() {\n" 13627 "\t\t\t\tsomeFunction(parameter1,\n" 13628 "\t\t\t\t\t\t\t parameter2);\n" 13629 "\t\t}\n" 13630 "};", 13631 Tab); 13632 Tab.TabWidth = 4; 13633 Tab.IndentWidth = 4; 13634 verifyFormat("class TabWidth4Indent4 {\n" 13635 "\tvoid f() {\n" 13636 "\t\tsomeFunction(parameter1,\n" 13637 "\t\t\t\t\t parameter2);\n" 13638 "\t}\n" 13639 "};", 13640 Tab); 13641 Tab.TabWidth = 8; 13642 Tab.IndentWidth = 4; 13643 verifyFormat("class TabWidth8Indent4 {\n" 13644 " void f() {\n" 13645 "\tsomeFunction(parameter1,\n" 13646 "\t\t parameter2);\n" 13647 " }\n" 13648 "};", 13649 Tab); 13650 Tab.TabWidth = 8; 13651 Tab.IndentWidth = 8; 13652 EXPECT_EQ("/*\n" 13653 "\t a\t\tcomment\n" 13654 "\t in multiple lines\n" 13655 " */", 13656 format(" /*\t \t \n" 13657 " \t \t a\t\tcomment\t \t\n" 13658 " \t \t in multiple lines\t\n" 13659 " \t */", 13660 Tab)); 13661 verifyFormat("{\n" 13662 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13663 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13664 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13665 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13666 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13667 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13668 "};", 13669 Tab); 13670 verifyFormat("enum AA {\n" 13671 "\ta1, // Force multiple lines\n" 13672 "\ta2,\n" 13673 "\ta3\n" 13674 "};", 13675 Tab); 13676 EXPECT_EQ("if (aaaaaaaa && // q\n" 13677 " bb) // w\n" 13678 "\t;", 13679 format("if (aaaaaaaa &&// q\n" 13680 "bb)// w\n" 13681 ";", 13682 Tab)); 13683 verifyFormat("class X {\n" 13684 "\tvoid f() {\n" 13685 "\t\tsomeFunction(parameter1,\n" 13686 "\t\t\t parameter2);\n" 13687 "\t}\n" 13688 "};", 13689 Tab); 13690 verifyFormat("{\n" 13691 "\tQ(\n" 13692 "\t {\n" 13693 "\t\t int a;\n" 13694 "\t\t someFunction(aaaaaaaa,\n" 13695 "\t\t\t\t bbbbbbb);\n" 13696 "\t },\n" 13697 "\t p);\n" 13698 "}", 13699 Tab); 13700 EXPECT_EQ("{\n" 13701 "\t/* aaaa\n" 13702 "\t bbbb */\n" 13703 "}", 13704 format("{\n" 13705 "/* aaaa\n" 13706 " bbbb */\n" 13707 "}", 13708 Tab)); 13709 EXPECT_EQ("{\n" 13710 "\t/*\n" 13711 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 13712 "\t bbbbbbbbbbbbb\n" 13713 "\t*/\n" 13714 "}", 13715 format("{\n" 13716 "/*\n" 13717 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 13718 "*/\n" 13719 "}", 13720 Tab)); 13721 EXPECT_EQ("{\n" 13722 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 13723 "\t// bbbbbbbbbbbbb\n" 13724 "}", 13725 format("{\n" 13726 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 13727 "}", 13728 Tab)); 13729 EXPECT_EQ("{\n" 13730 "\t/*\n" 13731 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 13732 "\t bbbbbbbbbbbbb\n" 13733 "\t*/\n" 13734 "}", 13735 format("{\n" 13736 "\t/*\n" 13737 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 13738 "\t*/\n" 13739 "}", 13740 Tab)); 13741 EXPECT_EQ("{\n" 13742 "\t/*\n" 13743 "\n" 13744 "\t*/\n" 13745 "}", 13746 format("{\n" 13747 "\t/*\n" 13748 "\n" 13749 "\t*/\n" 13750 "}", 13751 Tab)); 13752 EXPECT_EQ("{\n" 13753 "\t/*\n" 13754 " asdf\n" 13755 "\t*/\n" 13756 "}", 13757 format("{\n" 13758 "\t/*\n" 13759 " asdf\n" 13760 "\t*/\n" 13761 "}", 13762 Tab)); 13763 EXPECT_EQ("/* some\n" 13764 " comment */", 13765 format(" \t \t /* some\n" 13766 " \t \t comment */", 13767 Tab)); 13768 EXPECT_EQ("int a; /* some\n" 13769 " comment */", 13770 format(" \t \t int a; /* some\n" 13771 " \t \t comment */", 13772 Tab)); 13773 EXPECT_EQ("int a; /* some\n" 13774 "comment */", 13775 format(" \t \t int\ta; /* some\n" 13776 " \t \t comment */", 13777 Tab)); 13778 EXPECT_EQ("f(\"\t\t\"); /* some\n" 13779 " comment */", 13780 format(" \t \t f(\"\t\t\"); /* some\n" 13781 " \t \t comment */", 13782 Tab)); 13783 EXPECT_EQ("{\n" 13784 "\t/*\n" 13785 "\t * Comment\n" 13786 "\t */\n" 13787 "\tint i;\n" 13788 "}", 13789 format("{\n" 13790 "\t/*\n" 13791 "\t * Comment\n" 13792 "\t */\n" 13793 "\t int i;\n" 13794 "}", 13795 Tab)); 13796 Tab.TabWidth = 2; 13797 Tab.IndentWidth = 2; 13798 EXPECT_EQ("{\n" 13799 "\t/* aaaa\n" 13800 "\t\t bbbb */\n" 13801 "}", 13802 format("{\n" 13803 "/* aaaa\n" 13804 "\t bbbb */\n" 13805 "}", 13806 Tab)); 13807 EXPECT_EQ("{\n" 13808 "\t/*\n" 13809 "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n" 13810 "\t\tbbbbbbbbbbbbb\n" 13811 "\t*/\n" 13812 "}", 13813 format("{\n" 13814 "/*\n" 13815 "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 13816 "*/\n" 13817 "}", 13818 Tab)); 13819 Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 13820 Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 13821 Tab.TabWidth = 4; 13822 Tab.IndentWidth = 4; 13823 verifyFormat("class Assign {\n" 13824 "\tvoid f() {\n" 13825 "\t\tint x = 123;\n" 13826 "\t\tint random = 4;\n" 13827 "\t\tstd::string alphabet =\n" 13828 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n" 13829 "\t}\n" 13830 "};", 13831 Tab); 13832 13833 Tab.UseTab = FormatStyle::UT_AlignWithSpaces; 13834 Tab.TabWidth = 8; 13835 Tab.IndentWidth = 8; 13836 EXPECT_EQ("if (aaaaaaaa && // q\n" 13837 " bb) // w\n" 13838 "\t;", 13839 format("if (aaaaaaaa &&// q\n" 13840 "bb)// w\n" 13841 ";", 13842 Tab)); 13843 EXPECT_EQ("if (aaa && bbb) // w\n" 13844 "\t;", 13845 format("if(aaa&&bbb)// w\n" 13846 ";", 13847 Tab)); 13848 verifyFormat("class X {\n" 13849 "\tvoid f() {\n" 13850 "\t\tsomeFunction(parameter1,\n" 13851 "\t\t parameter2);\n" 13852 "\t}\n" 13853 "};", 13854 Tab); 13855 verifyFormat("#define A \\\n" 13856 "\tvoid f() { \\\n" 13857 "\t\tsomeFunction( \\\n" 13858 "\t\t parameter1, \\\n" 13859 "\t\t parameter2); \\\n" 13860 "\t}", 13861 Tab); 13862 Tab.TabWidth = 4; 13863 Tab.IndentWidth = 8; 13864 verifyFormat("class TabWidth4Indent8 {\n" 13865 "\t\tvoid f() {\n" 13866 "\t\t\t\tsomeFunction(parameter1,\n" 13867 "\t\t\t\t parameter2);\n" 13868 "\t\t}\n" 13869 "};", 13870 Tab); 13871 Tab.TabWidth = 4; 13872 Tab.IndentWidth = 4; 13873 verifyFormat("class TabWidth4Indent4 {\n" 13874 "\tvoid f() {\n" 13875 "\t\tsomeFunction(parameter1,\n" 13876 "\t\t parameter2);\n" 13877 "\t}\n" 13878 "};", 13879 Tab); 13880 Tab.TabWidth = 8; 13881 Tab.IndentWidth = 4; 13882 verifyFormat("class TabWidth8Indent4 {\n" 13883 " void f() {\n" 13884 "\tsomeFunction(parameter1,\n" 13885 "\t parameter2);\n" 13886 " }\n" 13887 "};", 13888 Tab); 13889 Tab.TabWidth = 8; 13890 Tab.IndentWidth = 8; 13891 EXPECT_EQ("/*\n" 13892 " a\t\tcomment\n" 13893 " in multiple lines\n" 13894 " */", 13895 format(" /*\t \t \n" 13896 " \t \t a\t\tcomment\t \t\n" 13897 " \t \t in multiple lines\t\n" 13898 " \t */", 13899 Tab)); 13900 verifyFormat("{\n" 13901 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13902 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13903 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13904 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13905 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13906 "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n" 13907 "};", 13908 Tab); 13909 verifyFormat("enum AA {\n" 13910 "\ta1, // Force multiple lines\n" 13911 "\ta2,\n" 13912 "\ta3\n" 13913 "};", 13914 Tab); 13915 EXPECT_EQ("if (aaaaaaaa && // q\n" 13916 " bb) // w\n" 13917 "\t;", 13918 format("if (aaaaaaaa &&// q\n" 13919 "bb)// w\n" 13920 ";", 13921 Tab)); 13922 verifyFormat("class X {\n" 13923 "\tvoid f() {\n" 13924 "\t\tsomeFunction(parameter1,\n" 13925 "\t\t parameter2);\n" 13926 "\t}\n" 13927 "};", 13928 Tab); 13929 verifyFormat("{\n" 13930 "\tQ(\n" 13931 "\t {\n" 13932 "\t\t int a;\n" 13933 "\t\t someFunction(aaaaaaaa,\n" 13934 "\t\t bbbbbbb);\n" 13935 "\t },\n" 13936 "\t p);\n" 13937 "}", 13938 Tab); 13939 EXPECT_EQ("{\n" 13940 "\t/* aaaa\n" 13941 "\t bbbb */\n" 13942 "}", 13943 format("{\n" 13944 "/* aaaa\n" 13945 " bbbb */\n" 13946 "}", 13947 Tab)); 13948 EXPECT_EQ("{\n" 13949 "\t/*\n" 13950 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 13951 "\t bbbbbbbbbbbbb\n" 13952 "\t*/\n" 13953 "}", 13954 format("{\n" 13955 "/*\n" 13956 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 13957 "*/\n" 13958 "}", 13959 Tab)); 13960 EXPECT_EQ("{\n" 13961 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 13962 "\t// bbbbbbbbbbbbb\n" 13963 "}", 13964 format("{\n" 13965 "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 13966 "}", 13967 Tab)); 13968 EXPECT_EQ("{\n" 13969 "\t/*\n" 13970 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 13971 "\t bbbbbbbbbbbbb\n" 13972 "\t*/\n" 13973 "}", 13974 format("{\n" 13975 "\t/*\n" 13976 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 13977 "\t*/\n" 13978 "}", 13979 Tab)); 13980 EXPECT_EQ("{\n" 13981 "\t/*\n" 13982 "\n" 13983 "\t*/\n" 13984 "}", 13985 format("{\n" 13986 "\t/*\n" 13987 "\n" 13988 "\t*/\n" 13989 "}", 13990 Tab)); 13991 EXPECT_EQ("{\n" 13992 "\t/*\n" 13993 " asdf\n" 13994 "\t*/\n" 13995 "}", 13996 format("{\n" 13997 "\t/*\n" 13998 " asdf\n" 13999 "\t*/\n" 14000 "}", 14001 Tab)); 14002 EXPECT_EQ("/* some\n" 14003 " comment */", 14004 format(" \t \t /* some\n" 14005 " \t \t comment */", 14006 Tab)); 14007 EXPECT_EQ("int a; /* some\n" 14008 " comment */", 14009 format(" \t \t int a; /* some\n" 14010 " \t \t comment */", 14011 Tab)); 14012 EXPECT_EQ("int a; /* some\n" 14013 "comment */", 14014 format(" \t \t int\ta; /* some\n" 14015 " \t \t comment */", 14016 Tab)); 14017 EXPECT_EQ("f(\"\t\t\"); /* some\n" 14018 " comment */", 14019 format(" \t \t f(\"\t\t\"); /* some\n" 14020 " \t \t comment */", 14021 Tab)); 14022 EXPECT_EQ("{\n" 14023 "\t/*\n" 14024 "\t * Comment\n" 14025 "\t */\n" 14026 "\tint i;\n" 14027 "}", 14028 format("{\n" 14029 "\t/*\n" 14030 "\t * Comment\n" 14031 "\t */\n" 14032 "\t int i;\n" 14033 "}", 14034 Tab)); 14035 Tab.TabWidth = 2; 14036 Tab.IndentWidth = 2; 14037 EXPECT_EQ("{\n" 14038 "\t/* aaaa\n" 14039 "\t bbbb */\n" 14040 "}", 14041 format("{\n" 14042 "/* aaaa\n" 14043 " bbbb */\n" 14044 "}", 14045 Tab)); 14046 EXPECT_EQ("{\n" 14047 "\t/*\n" 14048 "\t aaaaaaaaaaaaaaaaaaaaaaaaaa\n" 14049 "\t bbbbbbbbbbbbb\n" 14050 "\t*/\n" 14051 "}", 14052 format("{\n" 14053 "/*\n" 14054 " aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n" 14055 "*/\n" 14056 "}", 14057 Tab)); 14058 Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 14059 Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 14060 Tab.TabWidth = 4; 14061 Tab.IndentWidth = 4; 14062 verifyFormat("class Assign {\n" 14063 "\tvoid f() {\n" 14064 "\t\tint x = 123;\n" 14065 "\t\tint random = 4;\n" 14066 "\t\tstd::string alphabet =\n" 14067 "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n" 14068 "\t}\n" 14069 "};", 14070 Tab); 14071 Tab.AlignOperands = FormatStyle::OAS_Align; 14072 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n" 14073 " cccccccccccccccccccc;", 14074 Tab); 14075 // no alignment 14076 verifyFormat("int aaaaaaaaaa =\n" 14077 "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", 14078 Tab); 14079 verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n" 14080 " : bbbbbbbbbbbbbb ? 222222222222222\n" 14081 " : 333333333333333;", 14082 Tab); 14083 Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 14084 Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator; 14085 verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n" 14086 " + cccccccccccccccccccc;", 14087 Tab); 14088 } 14089 14090 TEST_F(FormatTest, ZeroTabWidth) { 14091 FormatStyle Tab = getLLVMStyleWithColumns(42); 14092 Tab.IndentWidth = 8; 14093 Tab.UseTab = FormatStyle::UT_Never; 14094 Tab.TabWidth = 0; 14095 EXPECT_EQ("void a(){\n" 14096 " // line starts with '\t'\n" 14097 "};", 14098 format("void a(){\n" 14099 "\t// line starts with '\t'\n" 14100 "};", 14101 Tab)); 14102 14103 EXPECT_EQ("void a(){\n" 14104 " // line starts with '\t'\n" 14105 "};", 14106 format("void a(){\n" 14107 "\t\t// line starts with '\t'\n" 14108 "};", 14109 Tab)); 14110 14111 Tab.UseTab = FormatStyle::UT_ForIndentation; 14112 EXPECT_EQ("void a(){\n" 14113 " // line starts with '\t'\n" 14114 "};", 14115 format("void a(){\n" 14116 "\t// line starts with '\t'\n" 14117 "};", 14118 Tab)); 14119 14120 EXPECT_EQ("void a(){\n" 14121 " // line starts with '\t'\n" 14122 "};", 14123 format("void a(){\n" 14124 "\t\t// line starts with '\t'\n" 14125 "};", 14126 Tab)); 14127 14128 Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation; 14129 EXPECT_EQ("void a(){\n" 14130 " // line starts with '\t'\n" 14131 "};", 14132 format("void a(){\n" 14133 "\t// line starts with '\t'\n" 14134 "};", 14135 Tab)); 14136 14137 EXPECT_EQ("void a(){\n" 14138 " // line starts with '\t'\n" 14139 "};", 14140 format("void a(){\n" 14141 "\t\t// line starts with '\t'\n" 14142 "};", 14143 Tab)); 14144 14145 Tab.UseTab = FormatStyle::UT_AlignWithSpaces; 14146 EXPECT_EQ("void a(){\n" 14147 " // line starts with '\t'\n" 14148 "};", 14149 format("void a(){\n" 14150 "\t// line starts with '\t'\n" 14151 "};", 14152 Tab)); 14153 14154 EXPECT_EQ("void a(){\n" 14155 " // line starts with '\t'\n" 14156 "};", 14157 format("void a(){\n" 14158 "\t\t// line starts with '\t'\n" 14159 "};", 14160 Tab)); 14161 14162 Tab.UseTab = FormatStyle::UT_Always; 14163 EXPECT_EQ("void a(){\n" 14164 "// line starts with '\t'\n" 14165 "};", 14166 format("void a(){\n" 14167 "\t// line starts with '\t'\n" 14168 "};", 14169 Tab)); 14170 14171 EXPECT_EQ("void a(){\n" 14172 "// line starts with '\t'\n" 14173 "};", 14174 format("void a(){\n" 14175 "\t\t// line starts with '\t'\n" 14176 "};", 14177 Tab)); 14178 } 14179 14180 TEST_F(FormatTest, CalculatesOriginalColumn) { 14181 EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14182 "q\"; /* some\n" 14183 " comment */", 14184 format(" \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14185 "q\"; /* some\n" 14186 " comment */", 14187 getLLVMStyle())); 14188 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n" 14189 "/* some\n" 14190 " comment */", 14191 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n" 14192 " /* some\n" 14193 " comment */", 14194 getLLVMStyle())); 14195 EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14196 "qqq\n" 14197 "/* some\n" 14198 " comment */", 14199 format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14200 "qqq\n" 14201 " /* some\n" 14202 " comment */", 14203 getLLVMStyle())); 14204 EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14205 "wwww; /* some\n" 14206 " comment */", 14207 format(" inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n" 14208 "wwww; /* some\n" 14209 " comment */", 14210 getLLVMStyle())); 14211 } 14212 14213 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) { 14214 FormatStyle NoSpace = getLLVMStyle(); 14215 NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never; 14216 14217 verifyFormat("while(true)\n" 14218 " continue;", 14219 NoSpace); 14220 verifyFormat("for(;;)\n" 14221 " continue;", 14222 NoSpace); 14223 verifyFormat("if(true)\n" 14224 " f();\n" 14225 "else if(true)\n" 14226 " f();", 14227 NoSpace); 14228 verifyFormat("do {\n" 14229 " do_something();\n" 14230 "} while(something());", 14231 NoSpace); 14232 verifyFormat("switch(x) {\n" 14233 "default:\n" 14234 " break;\n" 14235 "}", 14236 NoSpace); 14237 verifyFormat("auto i = std::make_unique<int>(5);", NoSpace); 14238 verifyFormat("size_t x = sizeof(x);", NoSpace); 14239 verifyFormat("auto f(int x) -> decltype(x);", NoSpace); 14240 verifyFormat("auto f(int x) -> typeof(x);", NoSpace); 14241 verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace); 14242 verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace); 14243 verifyFormat("int f(T x) noexcept(x.create());", NoSpace); 14244 verifyFormat("alignas(128) char a[128];", NoSpace); 14245 verifyFormat("size_t x = alignof(MyType);", NoSpace); 14246 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace); 14247 verifyFormat("int f() throw(Deprecated);", NoSpace); 14248 verifyFormat("typedef void (*cb)(int);", NoSpace); 14249 verifyFormat("T A::operator()();", NoSpace); 14250 verifyFormat("X A::operator++(T);", NoSpace); 14251 verifyFormat("auto lambda = []() { return 0; };", NoSpace); 14252 14253 FormatStyle Space = getLLVMStyle(); 14254 Space.SpaceBeforeParens = FormatStyle::SBPO_Always; 14255 14256 verifyFormat("int f ();", Space); 14257 verifyFormat("void f (int a, T b) {\n" 14258 " while (true)\n" 14259 " continue;\n" 14260 "}", 14261 Space); 14262 verifyFormat("if (true)\n" 14263 " f ();\n" 14264 "else if (true)\n" 14265 " f ();", 14266 Space); 14267 verifyFormat("do {\n" 14268 " do_something ();\n" 14269 "} while (something ());", 14270 Space); 14271 verifyFormat("switch (x) {\n" 14272 "default:\n" 14273 " break;\n" 14274 "}", 14275 Space); 14276 verifyFormat("A::A () : a (1) {}", Space); 14277 verifyFormat("void f () __attribute__ ((asdf));", Space); 14278 verifyFormat("*(&a + 1);\n" 14279 "&((&a)[1]);\n" 14280 "a[(b + c) * d];\n" 14281 "(((a + 1) * 2) + 3) * 4;", 14282 Space); 14283 verifyFormat("#define A(x) x", Space); 14284 verifyFormat("#define A (x) x", Space); 14285 verifyFormat("#if defined(x)\n" 14286 "#endif", 14287 Space); 14288 verifyFormat("auto i = std::make_unique<int> (5);", Space); 14289 verifyFormat("size_t x = sizeof (x);", Space); 14290 verifyFormat("auto f (int x) -> decltype (x);", Space); 14291 verifyFormat("auto f (int x) -> typeof (x);", Space); 14292 verifyFormat("auto f (int x) -> _Atomic (x);", Space); 14293 verifyFormat("auto f (int x) -> __underlying_type (x);", Space); 14294 verifyFormat("int f (T x) noexcept (x.create ());", Space); 14295 verifyFormat("alignas (128) char a[128];", Space); 14296 verifyFormat("size_t x = alignof (MyType);", Space); 14297 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space); 14298 verifyFormat("int f () throw (Deprecated);", Space); 14299 verifyFormat("typedef void (*cb) (int);", Space); 14300 // FIXME these tests regressed behaviour. 14301 // verifyFormat("T A::operator() ();", Space); 14302 // verifyFormat("X A::operator++ (T);", Space); 14303 verifyFormat("auto lambda = [] () { return 0; };", Space); 14304 verifyFormat("int x = int (y);", Space); 14305 14306 FormatStyle SomeSpace = getLLVMStyle(); 14307 SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses; 14308 14309 verifyFormat("[]() -> float {}", SomeSpace); 14310 verifyFormat("[] (auto foo) {}", SomeSpace); 14311 verifyFormat("[foo]() -> int {}", SomeSpace); 14312 verifyFormat("int f();", SomeSpace); 14313 verifyFormat("void f (int a, T b) {\n" 14314 " while (true)\n" 14315 " continue;\n" 14316 "}", 14317 SomeSpace); 14318 verifyFormat("if (true)\n" 14319 " f();\n" 14320 "else if (true)\n" 14321 " f();", 14322 SomeSpace); 14323 verifyFormat("do {\n" 14324 " do_something();\n" 14325 "} while (something());", 14326 SomeSpace); 14327 verifyFormat("switch (x) {\n" 14328 "default:\n" 14329 " break;\n" 14330 "}", 14331 SomeSpace); 14332 verifyFormat("A::A() : a (1) {}", SomeSpace); 14333 verifyFormat("void f() __attribute__ ((asdf));", SomeSpace); 14334 verifyFormat("*(&a + 1);\n" 14335 "&((&a)[1]);\n" 14336 "a[(b + c) * d];\n" 14337 "(((a + 1) * 2) + 3) * 4;", 14338 SomeSpace); 14339 verifyFormat("#define A(x) x", SomeSpace); 14340 verifyFormat("#define A (x) x", SomeSpace); 14341 verifyFormat("#if defined(x)\n" 14342 "#endif", 14343 SomeSpace); 14344 verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace); 14345 verifyFormat("size_t x = sizeof (x);", SomeSpace); 14346 verifyFormat("auto f (int x) -> decltype (x);", SomeSpace); 14347 verifyFormat("auto f (int x) -> typeof (x);", SomeSpace); 14348 verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace); 14349 verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace); 14350 verifyFormat("int f (T x) noexcept (x.create());", SomeSpace); 14351 verifyFormat("alignas (128) char a[128];", SomeSpace); 14352 verifyFormat("size_t x = alignof (MyType);", SomeSpace); 14353 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", 14354 SomeSpace); 14355 verifyFormat("int f() throw (Deprecated);", SomeSpace); 14356 verifyFormat("typedef void (*cb) (int);", SomeSpace); 14357 verifyFormat("T A::operator()();", SomeSpace); 14358 // FIXME these tests regressed behaviour. 14359 // verifyFormat("X A::operator++ (T);", SomeSpace); 14360 verifyFormat("int x = int (y);", SomeSpace); 14361 verifyFormat("auto lambda = []() { return 0; };", SomeSpace); 14362 14363 FormatStyle SpaceControlStatements = getLLVMStyle(); 14364 SpaceControlStatements.SpaceBeforeParens = FormatStyle::SBPO_Custom; 14365 SpaceControlStatements.SpaceBeforeParensOptions.AfterControlStatements = true; 14366 14367 verifyFormat("while (true)\n" 14368 " continue;", 14369 SpaceControlStatements); 14370 verifyFormat("if (true)\n" 14371 " f();\n" 14372 "else if (true)\n" 14373 " f();", 14374 SpaceControlStatements); 14375 verifyFormat("for (;;) {\n" 14376 " do_something();\n" 14377 "}", 14378 SpaceControlStatements); 14379 verifyFormat("do {\n" 14380 " do_something();\n" 14381 "} while (something());", 14382 SpaceControlStatements); 14383 verifyFormat("switch (x) {\n" 14384 "default:\n" 14385 " break;\n" 14386 "}", 14387 SpaceControlStatements); 14388 14389 FormatStyle SpaceFuncDecl = getLLVMStyle(); 14390 SpaceFuncDecl.SpaceBeforeParens = FormatStyle::SBPO_Custom; 14391 SpaceFuncDecl.SpaceBeforeParensOptions.AfterFunctionDeclarationName = true; 14392 14393 verifyFormat("int f ();", SpaceFuncDecl); 14394 verifyFormat("void f(int a, T b) {}", SpaceFuncDecl); 14395 verifyFormat("A::A() : a(1) {}", SpaceFuncDecl); 14396 verifyFormat("void f () __attribute__((asdf));", SpaceFuncDecl); 14397 verifyFormat("#define A(x) x", SpaceFuncDecl); 14398 verifyFormat("#define A (x) x", SpaceFuncDecl); 14399 verifyFormat("#if defined(x)\n" 14400 "#endif", 14401 SpaceFuncDecl); 14402 verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDecl); 14403 verifyFormat("size_t x = sizeof(x);", SpaceFuncDecl); 14404 verifyFormat("auto f (int x) -> decltype(x);", SpaceFuncDecl); 14405 verifyFormat("auto f (int x) -> typeof(x);", SpaceFuncDecl); 14406 verifyFormat("auto f (int x) -> _Atomic(x);", SpaceFuncDecl); 14407 verifyFormat("auto f (int x) -> __underlying_type(x);", SpaceFuncDecl); 14408 verifyFormat("int f (T x) noexcept(x.create());", SpaceFuncDecl); 14409 verifyFormat("alignas(128) char a[128];", SpaceFuncDecl); 14410 verifyFormat("size_t x = alignof(MyType);", SpaceFuncDecl); 14411 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", 14412 SpaceFuncDecl); 14413 verifyFormat("int f () throw(Deprecated);", SpaceFuncDecl); 14414 verifyFormat("typedef void (*cb)(int);", SpaceFuncDecl); 14415 // FIXME these tests regressed behaviour. 14416 // verifyFormat("T A::operator() ();", SpaceFuncDecl); 14417 // verifyFormat("X A::operator++ (T);", SpaceFuncDecl); 14418 verifyFormat("T A::operator()() {}", SpaceFuncDecl); 14419 verifyFormat("auto lambda = []() { return 0; };", SpaceFuncDecl); 14420 verifyFormat("int x = int(y);", SpaceFuncDecl); 14421 verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}", 14422 SpaceFuncDecl); 14423 14424 FormatStyle SpaceFuncDef = getLLVMStyle(); 14425 SpaceFuncDef.SpaceBeforeParens = FormatStyle::SBPO_Custom; 14426 SpaceFuncDef.SpaceBeforeParensOptions.AfterFunctionDefinitionName = true; 14427 14428 verifyFormat("int f();", SpaceFuncDef); 14429 verifyFormat("void f (int a, T b) {}", SpaceFuncDef); 14430 verifyFormat("A::A() : a(1) {}", SpaceFuncDef); 14431 verifyFormat("void f() __attribute__((asdf));", SpaceFuncDef); 14432 verifyFormat("#define A(x) x", SpaceFuncDef); 14433 verifyFormat("#define A (x) x", SpaceFuncDef); 14434 verifyFormat("#if defined(x)\n" 14435 "#endif", 14436 SpaceFuncDef); 14437 verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDef); 14438 verifyFormat("size_t x = sizeof(x);", SpaceFuncDef); 14439 verifyFormat("auto f(int x) -> decltype(x);", SpaceFuncDef); 14440 verifyFormat("auto f(int x) -> typeof(x);", SpaceFuncDef); 14441 verifyFormat("auto f(int x) -> _Atomic(x);", SpaceFuncDef); 14442 verifyFormat("auto f(int x) -> __underlying_type(x);", SpaceFuncDef); 14443 verifyFormat("int f(T x) noexcept(x.create());", SpaceFuncDef); 14444 verifyFormat("alignas(128) char a[128];", SpaceFuncDef); 14445 verifyFormat("size_t x = alignof(MyType);", SpaceFuncDef); 14446 verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", 14447 SpaceFuncDef); 14448 verifyFormat("int f() throw(Deprecated);", SpaceFuncDef); 14449 verifyFormat("typedef void (*cb)(int);", SpaceFuncDef); 14450 verifyFormat("T A::operator()();", SpaceFuncDef); 14451 verifyFormat("X A::operator++(T);", SpaceFuncDef); 14452 // verifyFormat("T A::operator() () {}", SpaceFuncDef); 14453 verifyFormat("auto lambda = [] () { return 0; };", SpaceFuncDef); 14454 verifyFormat("int x = int(y);", SpaceFuncDef); 14455 verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}", 14456 SpaceFuncDef); 14457 14458 FormatStyle SpaceIfMacros = getLLVMStyle(); 14459 SpaceIfMacros.IfMacros.clear(); 14460 SpaceIfMacros.IfMacros.push_back("MYIF"); 14461 SpaceIfMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom; 14462 SpaceIfMacros.SpaceBeforeParensOptions.AfterIfMacros = true; 14463 verifyFormat("MYIF (a)\n return;", SpaceIfMacros); 14464 verifyFormat("MYIF (a)\n return;\nelse MYIF (b)\n return;", SpaceIfMacros); 14465 verifyFormat("MYIF (a)\n return;\nelse\n return;", SpaceIfMacros); 14466 14467 FormatStyle SpaceForeachMacros = getLLVMStyle(); 14468 SpaceForeachMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom; 14469 SpaceForeachMacros.SpaceBeforeParensOptions.AfterForeachMacros = true; 14470 verifyFormat("foreach (Item *item, itemlist) {}", SpaceForeachMacros); 14471 verifyFormat("Q_FOREACH (Item *item, itemlist) {}", SpaceForeachMacros); 14472 verifyFormat("BOOST_FOREACH (Item *item, itemlist) {}", SpaceForeachMacros); 14473 verifyFormat("UNKNOWN_FOREACH(Item *item, itemlist) {}", SpaceForeachMacros); 14474 14475 FormatStyle SomeSpace2 = getLLVMStyle(); 14476 SomeSpace2.SpaceBeforeParens = FormatStyle::SBPO_Custom; 14477 SomeSpace2.SpaceBeforeParensOptions.BeforeNonEmptyParentheses = true; 14478 verifyFormat("[]() -> float {}", SomeSpace2); 14479 verifyFormat("[] (auto foo) {}", SomeSpace2); 14480 verifyFormat("[foo]() -> int {}", SomeSpace2); 14481 verifyFormat("int f();", SomeSpace2); 14482 verifyFormat("void f (int a, T b) {\n" 14483 " while (true)\n" 14484 " continue;\n" 14485 "}", 14486 SomeSpace2); 14487 verifyFormat("if (true)\n" 14488 " f();\n" 14489 "else if (true)\n" 14490 " f();", 14491 SomeSpace2); 14492 verifyFormat("do {\n" 14493 " do_something();\n" 14494 "} while (something());", 14495 SomeSpace2); 14496 verifyFormat("switch (x) {\n" 14497 "default:\n" 14498 " break;\n" 14499 "}", 14500 SomeSpace2); 14501 verifyFormat("A::A() : a (1) {}", SomeSpace2); 14502 verifyFormat("void f() __attribute__ ((asdf));", SomeSpace2); 14503 verifyFormat("*(&a + 1);\n" 14504 "&((&a)[1]);\n" 14505 "a[(b + c) * d];\n" 14506 "(((a + 1) * 2) + 3) * 4;", 14507 SomeSpace2); 14508 verifyFormat("#define A(x) x", SomeSpace2); 14509 verifyFormat("#define A (x) x", SomeSpace2); 14510 verifyFormat("#if defined(x)\n" 14511 "#endif", 14512 SomeSpace2); 14513 verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace2); 14514 verifyFormat("size_t x = sizeof (x);", SomeSpace2); 14515 verifyFormat("auto f (int x) -> decltype (x);", SomeSpace2); 14516 verifyFormat("auto f (int x) -> typeof (x);", SomeSpace2); 14517 verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace2); 14518 verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace2); 14519 verifyFormat("int f (T x) noexcept (x.create());", SomeSpace2); 14520 verifyFormat("alignas (128) char a[128];", SomeSpace2); 14521 verifyFormat("size_t x = alignof (MyType);", SomeSpace2); 14522 verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", 14523 SomeSpace2); 14524 verifyFormat("int f() throw (Deprecated);", SomeSpace2); 14525 verifyFormat("typedef void (*cb) (int);", SomeSpace2); 14526 verifyFormat("T A::operator()();", SomeSpace2); 14527 // verifyFormat("X A::operator++ (T);", SomeSpace2); 14528 verifyFormat("int x = int (y);", SomeSpace2); 14529 verifyFormat("auto lambda = []() { return 0; };", SomeSpace2); 14530 } 14531 14532 TEST_F(FormatTest, SpaceAfterLogicalNot) { 14533 FormatStyle Spaces = getLLVMStyle(); 14534 Spaces.SpaceAfterLogicalNot = true; 14535 14536 verifyFormat("bool x = ! y", Spaces); 14537 verifyFormat("if (! isFailure())", Spaces); 14538 verifyFormat("if (! (a && b))", Spaces); 14539 verifyFormat("\"Error!\"", Spaces); 14540 verifyFormat("! ! x", Spaces); 14541 } 14542 14543 TEST_F(FormatTest, ConfigurableSpacesInParentheses) { 14544 FormatStyle Spaces = getLLVMStyle(); 14545 14546 Spaces.SpacesInParentheses = true; 14547 verifyFormat("do_something( ::globalVar );", Spaces); 14548 verifyFormat("call( x, y, z );", Spaces); 14549 verifyFormat("call();", Spaces); 14550 verifyFormat("std::function<void( int, int )> callback;", Spaces); 14551 verifyFormat("void inFunction() { std::function<void( int, int )> fct; }", 14552 Spaces); 14553 verifyFormat("while ( (bool)1 )\n" 14554 " continue;", 14555 Spaces); 14556 verifyFormat("for ( ;; )\n" 14557 " continue;", 14558 Spaces); 14559 verifyFormat("if ( true )\n" 14560 " f();\n" 14561 "else if ( true )\n" 14562 " f();", 14563 Spaces); 14564 verifyFormat("do {\n" 14565 " do_something( (int)i );\n" 14566 "} while ( something() );", 14567 Spaces); 14568 verifyFormat("switch ( x ) {\n" 14569 "default:\n" 14570 " break;\n" 14571 "}", 14572 Spaces); 14573 14574 Spaces.SpacesInParentheses = false; 14575 Spaces.SpacesInCStyleCastParentheses = true; 14576 verifyFormat("Type *A = ( Type * )P;", Spaces); 14577 verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces); 14578 verifyFormat("x = ( int32 )y;", Spaces); 14579 verifyFormat("int a = ( int )(2.0f);", Spaces); 14580 verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces); 14581 verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces); 14582 verifyFormat("#define x (( int )-1)", Spaces); 14583 14584 // Run the first set of tests again with: 14585 Spaces.SpacesInParentheses = false; 14586 Spaces.SpaceInEmptyParentheses = true; 14587 Spaces.SpacesInCStyleCastParentheses = true; 14588 verifyFormat("call(x, y, z);", Spaces); 14589 verifyFormat("call( );", Spaces); 14590 verifyFormat("std::function<void(int, int)> callback;", Spaces); 14591 verifyFormat("while (( bool )1)\n" 14592 " continue;", 14593 Spaces); 14594 verifyFormat("for (;;)\n" 14595 " continue;", 14596 Spaces); 14597 verifyFormat("if (true)\n" 14598 " f( );\n" 14599 "else if (true)\n" 14600 " f( );", 14601 Spaces); 14602 verifyFormat("do {\n" 14603 " do_something(( int )i);\n" 14604 "} while (something( ));", 14605 Spaces); 14606 verifyFormat("switch (x) {\n" 14607 "default:\n" 14608 " break;\n" 14609 "}", 14610 Spaces); 14611 14612 // Run the first set of tests again with: 14613 Spaces.SpaceAfterCStyleCast = true; 14614 verifyFormat("call(x, y, z);", Spaces); 14615 verifyFormat("call( );", Spaces); 14616 verifyFormat("std::function<void(int, int)> callback;", Spaces); 14617 verifyFormat("while (( bool ) 1)\n" 14618 " continue;", 14619 Spaces); 14620 verifyFormat("for (;;)\n" 14621 " continue;", 14622 Spaces); 14623 verifyFormat("if (true)\n" 14624 " f( );\n" 14625 "else if (true)\n" 14626 " f( );", 14627 Spaces); 14628 verifyFormat("do {\n" 14629 " do_something(( int ) i);\n" 14630 "} while (something( ));", 14631 Spaces); 14632 verifyFormat("switch (x) {\n" 14633 "default:\n" 14634 " break;\n" 14635 "}", 14636 Spaces); 14637 14638 // Run subset of tests again with: 14639 Spaces.SpacesInCStyleCastParentheses = false; 14640 Spaces.SpaceAfterCStyleCast = true; 14641 verifyFormat("while ((bool) 1)\n" 14642 " continue;", 14643 Spaces); 14644 verifyFormat("do {\n" 14645 " do_something((int) i);\n" 14646 "} while (something( ));", 14647 Spaces); 14648 14649 verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces); 14650 verifyFormat("size_t idx = (size_t) a;", Spaces); 14651 verifyFormat("size_t idx = (size_t) (a - 1);", Spaces); 14652 verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces); 14653 verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces); 14654 verifyFormat("size_t idx = (*foo)(a - 1);", Spaces); 14655 verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces); 14656 Spaces.ColumnLimit = 80; 14657 Spaces.IndentWidth = 4; 14658 Spaces.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 14659 verifyFormat("void foo( ) {\n" 14660 " size_t foo = (*(function))(\n" 14661 " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, " 14662 "BarrrrrrrrrrrrLong,\n" 14663 " FoooooooooLooooong);\n" 14664 "}", 14665 Spaces); 14666 Spaces.SpaceAfterCStyleCast = false; 14667 verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces); 14668 verifyFormat("size_t idx = (size_t)a;", Spaces); 14669 verifyFormat("size_t idx = (size_t)(a - 1);", Spaces); 14670 verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces); 14671 verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces); 14672 verifyFormat("size_t idx = (*foo)(a - 1);", Spaces); 14673 verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces); 14674 14675 verifyFormat("void foo( ) {\n" 14676 " size_t foo = (*(function))(\n" 14677 " Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, " 14678 "BarrrrrrrrrrrrLong,\n" 14679 " FoooooooooLooooong);\n" 14680 "}", 14681 Spaces); 14682 } 14683 14684 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) { 14685 verifyFormat("int a[5];"); 14686 verifyFormat("a[3] += 42;"); 14687 14688 FormatStyle Spaces = getLLVMStyle(); 14689 Spaces.SpacesInSquareBrackets = true; 14690 // Not lambdas. 14691 verifyFormat("int a[ 5 ];", Spaces); 14692 verifyFormat("a[ 3 ] += 42;", Spaces); 14693 verifyFormat("constexpr char hello[]{\"hello\"};", Spaces); 14694 verifyFormat("double &operator[](int i) { return 0; }\n" 14695 "int i;", 14696 Spaces); 14697 verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces); 14698 verifyFormat("int i = a[ a ][ a ]->f();", Spaces); 14699 verifyFormat("int i = (*b)[ a ]->f();", Spaces); 14700 // Lambdas. 14701 verifyFormat("int c = []() -> int { return 2; }();\n", Spaces); 14702 verifyFormat("return [ i, args... ] {};", Spaces); 14703 verifyFormat("int foo = [ &bar ]() {};", Spaces); 14704 verifyFormat("int foo = [ = ]() {};", Spaces); 14705 verifyFormat("int foo = [ & ]() {};", Spaces); 14706 verifyFormat("int foo = [ =, &bar ]() {};", Spaces); 14707 verifyFormat("int foo = [ &bar, = ]() {};", Spaces); 14708 } 14709 14710 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) { 14711 FormatStyle NoSpaceStyle = getLLVMStyle(); 14712 verifyFormat("int a[5];", NoSpaceStyle); 14713 verifyFormat("a[3] += 42;", NoSpaceStyle); 14714 14715 verifyFormat("int a[1];", NoSpaceStyle); 14716 verifyFormat("int 1 [a];", NoSpaceStyle); 14717 verifyFormat("int a[1][2];", NoSpaceStyle); 14718 verifyFormat("a[7] = 5;", NoSpaceStyle); 14719 verifyFormat("int a = (f())[23];", NoSpaceStyle); 14720 verifyFormat("f([] {})", NoSpaceStyle); 14721 14722 FormatStyle Space = getLLVMStyle(); 14723 Space.SpaceBeforeSquareBrackets = true; 14724 verifyFormat("int c = []() -> int { return 2; }();\n", Space); 14725 verifyFormat("return [i, args...] {};", Space); 14726 14727 verifyFormat("int a [5];", Space); 14728 verifyFormat("a [3] += 42;", Space); 14729 verifyFormat("constexpr char hello []{\"hello\"};", Space); 14730 verifyFormat("double &operator[](int i) { return 0; }\n" 14731 "int i;", 14732 Space); 14733 verifyFormat("std::unique_ptr<int []> foo() {}", Space); 14734 verifyFormat("int i = a [a][a]->f();", Space); 14735 verifyFormat("int i = (*b) [a]->f();", Space); 14736 14737 verifyFormat("int a [1];", Space); 14738 verifyFormat("int 1 [a];", Space); 14739 verifyFormat("int a [1][2];", Space); 14740 verifyFormat("a [7] = 5;", Space); 14741 verifyFormat("int a = (f()) [23];", Space); 14742 verifyFormat("f([] {})", Space); 14743 } 14744 14745 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) { 14746 verifyFormat("int a = 5;"); 14747 verifyFormat("a += 42;"); 14748 verifyFormat("a or_eq 8;"); 14749 14750 FormatStyle Spaces = getLLVMStyle(); 14751 Spaces.SpaceBeforeAssignmentOperators = false; 14752 verifyFormat("int a= 5;", Spaces); 14753 verifyFormat("a+= 42;", Spaces); 14754 verifyFormat("a or_eq 8;", Spaces); 14755 } 14756 14757 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) { 14758 verifyFormat("class Foo : public Bar {};"); 14759 verifyFormat("Foo::Foo() : foo(1) {}"); 14760 verifyFormat("for (auto a : b) {\n}"); 14761 verifyFormat("int x = a ? b : c;"); 14762 verifyFormat("{\n" 14763 "label0:\n" 14764 " int x = 0;\n" 14765 "}"); 14766 verifyFormat("switch (x) {\n" 14767 "case 1:\n" 14768 "default:\n" 14769 "}"); 14770 verifyFormat("switch (allBraces) {\n" 14771 "case 1: {\n" 14772 " break;\n" 14773 "}\n" 14774 "case 2: {\n" 14775 " [[fallthrough]];\n" 14776 "}\n" 14777 "default: {\n" 14778 " break;\n" 14779 "}\n" 14780 "}"); 14781 14782 FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30); 14783 CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false; 14784 verifyFormat("class Foo : public Bar {};", CtorInitializerStyle); 14785 verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle); 14786 verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle); 14787 verifyFormat("int x = a ? b : c;", CtorInitializerStyle); 14788 verifyFormat("{\n" 14789 "label1:\n" 14790 " int x = 0;\n" 14791 "}", 14792 CtorInitializerStyle); 14793 verifyFormat("switch (x) {\n" 14794 "case 1:\n" 14795 "default:\n" 14796 "}", 14797 CtorInitializerStyle); 14798 verifyFormat("switch (allBraces) {\n" 14799 "case 1: {\n" 14800 " break;\n" 14801 "}\n" 14802 "case 2: {\n" 14803 " [[fallthrough]];\n" 14804 "}\n" 14805 "default: {\n" 14806 " break;\n" 14807 "}\n" 14808 "}", 14809 CtorInitializerStyle); 14810 CtorInitializerStyle.BreakConstructorInitializers = 14811 FormatStyle::BCIS_AfterColon; 14812 verifyFormat("Fooooooooooo::Fooooooooooo():\n" 14813 " aaaaaaaaaaaaaaaa(1),\n" 14814 " bbbbbbbbbbbbbbbb(2) {}", 14815 CtorInitializerStyle); 14816 CtorInitializerStyle.BreakConstructorInitializers = 14817 FormatStyle::BCIS_BeforeComma; 14818 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 14819 " : aaaaaaaaaaaaaaaa(1)\n" 14820 " , bbbbbbbbbbbbbbbb(2) {}", 14821 CtorInitializerStyle); 14822 CtorInitializerStyle.BreakConstructorInitializers = 14823 FormatStyle::BCIS_BeforeColon; 14824 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 14825 " : aaaaaaaaaaaaaaaa(1),\n" 14826 " bbbbbbbbbbbbbbbb(2) {}", 14827 CtorInitializerStyle); 14828 CtorInitializerStyle.ConstructorInitializerIndentWidth = 0; 14829 verifyFormat("Fooooooooooo::Fooooooooooo()\n" 14830 ": aaaaaaaaaaaaaaaa(1),\n" 14831 " bbbbbbbbbbbbbbbb(2) {}", 14832 CtorInitializerStyle); 14833 14834 FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30); 14835 InheritanceStyle.SpaceBeforeInheritanceColon = false; 14836 verifyFormat("class Foo: public Bar {};", InheritanceStyle); 14837 verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle); 14838 verifyFormat("for (auto a : b) {\n}", InheritanceStyle); 14839 verifyFormat("int x = a ? b : c;", InheritanceStyle); 14840 verifyFormat("{\n" 14841 "label2:\n" 14842 " int x = 0;\n" 14843 "}", 14844 InheritanceStyle); 14845 verifyFormat("switch (x) {\n" 14846 "case 1:\n" 14847 "default:\n" 14848 "}", 14849 InheritanceStyle); 14850 verifyFormat("switch (allBraces) {\n" 14851 "case 1: {\n" 14852 " break;\n" 14853 "}\n" 14854 "case 2: {\n" 14855 " [[fallthrough]];\n" 14856 "}\n" 14857 "default: {\n" 14858 " break;\n" 14859 "}\n" 14860 "}", 14861 InheritanceStyle); 14862 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterComma; 14863 verifyFormat("class Foooooooooooooooooooooo\n" 14864 " : public aaaaaaaaaaaaaaaaaa,\n" 14865 " public bbbbbbbbbbbbbbbbbb {\n" 14866 "}", 14867 InheritanceStyle); 14868 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon; 14869 verifyFormat("class Foooooooooooooooooooooo:\n" 14870 " public aaaaaaaaaaaaaaaaaa,\n" 14871 " public bbbbbbbbbbbbbbbbbb {\n" 14872 "}", 14873 InheritanceStyle); 14874 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma; 14875 verifyFormat("class Foooooooooooooooooooooo\n" 14876 " : public aaaaaaaaaaaaaaaaaa\n" 14877 " , public bbbbbbbbbbbbbbbbbb {\n" 14878 "}", 14879 InheritanceStyle); 14880 InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 14881 verifyFormat("class Foooooooooooooooooooooo\n" 14882 " : public aaaaaaaaaaaaaaaaaa,\n" 14883 " public bbbbbbbbbbbbbbbbbb {\n" 14884 "}", 14885 InheritanceStyle); 14886 InheritanceStyle.ConstructorInitializerIndentWidth = 0; 14887 verifyFormat("class Foooooooooooooooooooooo\n" 14888 ": public aaaaaaaaaaaaaaaaaa,\n" 14889 " public bbbbbbbbbbbbbbbbbb {}", 14890 InheritanceStyle); 14891 14892 FormatStyle ForLoopStyle = getLLVMStyle(); 14893 ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false; 14894 verifyFormat("class Foo : public Bar {};", ForLoopStyle); 14895 verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle); 14896 verifyFormat("for (auto a: b) {\n}", ForLoopStyle); 14897 verifyFormat("int x = a ? b : c;", ForLoopStyle); 14898 verifyFormat("{\n" 14899 "label2:\n" 14900 " int x = 0;\n" 14901 "}", 14902 ForLoopStyle); 14903 verifyFormat("switch (x) {\n" 14904 "case 1:\n" 14905 "default:\n" 14906 "}", 14907 ForLoopStyle); 14908 verifyFormat("switch (allBraces) {\n" 14909 "case 1: {\n" 14910 " break;\n" 14911 "}\n" 14912 "case 2: {\n" 14913 " [[fallthrough]];\n" 14914 "}\n" 14915 "default: {\n" 14916 " break;\n" 14917 "}\n" 14918 "}", 14919 ForLoopStyle); 14920 14921 FormatStyle CaseStyle = getLLVMStyle(); 14922 CaseStyle.SpaceBeforeCaseColon = true; 14923 verifyFormat("class Foo : public Bar {};", CaseStyle); 14924 verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle); 14925 verifyFormat("for (auto a : b) {\n}", CaseStyle); 14926 verifyFormat("int x = a ? b : c;", CaseStyle); 14927 verifyFormat("switch (x) {\n" 14928 "case 1 :\n" 14929 "default :\n" 14930 "}", 14931 CaseStyle); 14932 verifyFormat("switch (allBraces) {\n" 14933 "case 1 : {\n" 14934 " break;\n" 14935 "}\n" 14936 "case 2 : {\n" 14937 " [[fallthrough]];\n" 14938 "}\n" 14939 "default : {\n" 14940 " break;\n" 14941 "}\n" 14942 "}", 14943 CaseStyle); 14944 14945 FormatStyle NoSpaceStyle = getLLVMStyle(); 14946 EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false); 14947 NoSpaceStyle.SpaceBeforeCtorInitializerColon = false; 14948 NoSpaceStyle.SpaceBeforeInheritanceColon = false; 14949 NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false; 14950 verifyFormat("class Foo: public Bar {};", NoSpaceStyle); 14951 verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle); 14952 verifyFormat("for (auto a: b) {\n}", NoSpaceStyle); 14953 verifyFormat("int x = a ? b : c;", NoSpaceStyle); 14954 verifyFormat("{\n" 14955 "label3:\n" 14956 " int x = 0;\n" 14957 "}", 14958 NoSpaceStyle); 14959 verifyFormat("switch (x) {\n" 14960 "case 1:\n" 14961 "default:\n" 14962 "}", 14963 NoSpaceStyle); 14964 verifyFormat("switch (allBraces) {\n" 14965 "case 1: {\n" 14966 " break;\n" 14967 "}\n" 14968 "case 2: {\n" 14969 " [[fallthrough]];\n" 14970 "}\n" 14971 "default: {\n" 14972 " break;\n" 14973 "}\n" 14974 "}", 14975 NoSpaceStyle); 14976 14977 FormatStyle InvertedSpaceStyle = getLLVMStyle(); 14978 InvertedSpaceStyle.SpaceBeforeCaseColon = true; 14979 InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false; 14980 InvertedSpaceStyle.SpaceBeforeInheritanceColon = false; 14981 InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false; 14982 verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle); 14983 verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle); 14984 verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle); 14985 verifyFormat("int x = a ? b : c;", InvertedSpaceStyle); 14986 verifyFormat("{\n" 14987 "label3:\n" 14988 " int x = 0;\n" 14989 "}", 14990 InvertedSpaceStyle); 14991 verifyFormat("switch (x) {\n" 14992 "case 1 :\n" 14993 "case 2 : {\n" 14994 " break;\n" 14995 "}\n" 14996 "default :\n" 14997 " break;\n" 14998 "}", 14999 InvertedSpaceStyle); 15000 verifyFormat("switch (allBraces) {\n" 15001 "case 1 : {\n" 15002 " break;\n" 15003 "}\n" 15004 "case 2 : {\n" 15005 " [[fallthrough]];\n" 15006 "}\n" 15007 "default : {\n" 15008 " break;\n" 15009 "}\n" 15010 "}", 15011 InvertedSpaceStyle); 15012 } 15013 15014 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) { 15015 FormatStyle Style = getLLVMStyle(); 15016 15017 Style.PointerAlignment = FormatStyle::PAS_Left; 15018 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default; 15019 verifyFormat("void* const* x = NULL;", Style); 15020 15021 #define verifyQualifierSpaces(Code, Pointers, Qualifiers) \ 15022 do { \ 15023 Style.PointerAlignment = FormatStyle::Pointers; \ 15024 Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers; \ 15025 verifyFormat(Code, Style); \ 15026 } while (false) 15027 15028 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default); 15029 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default); 15030 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default); 15031 15032 verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before); 15033 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before); 15034 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before); 15035 15036 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After); 15037 verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After); 15038 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After); 15039 15040 verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both); 15041 verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both); 15042 verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both); 15043 15044 verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default); 15045 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, 15046 SAPQ_Default); 15047 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15048 SAPQ_Default); 15049 15050 verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before); 15051 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, 15052 SAPQ_Before); 15053 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15054 SAPQ_Before); 15055 15056 verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After); 15057 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After); 15058 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, 15059 SAPQ_After); 15060 15061 verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both); 15062 verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both); 15063 verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both); 15064 15065 #undef verifyQualifierSpaces 15066 15067 FormatStyle Spaces = getLLVMStyle(); 15068 Spaces.AttributeMacros.push_back("qualified"); 15069 Spaces.PointerAlignment = FormatStyle::PAS_Right; 15070 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default; 15071 verifyFormat("SomeType *volatile *a = NULL;", Spaces); 15072 verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces); 15073 verifyFormat("std::vector<SomeType *const *> x;", Spaces); 15074 verifyFormat("std::vector<SomeType *qualified *> x;", Spaces); 15075 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15076 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before; 15077 verifyFormat("SomeType * volatile *a = NULL;", Spaces); 15078 verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces); 15079 verifyFormat("std::vector<SomeType * const *> x;", Spaces); 15080 verifyFormat("std::vector<SomeType * qualified *> x;", Spaces); 15081 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15082 15083 // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left. 15084 Spaces.PointerAlignment = FormatStyle::PAS_Left; 15085 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before; 15086 verifyFormat("SomeType* volatile* a = NULL;", Spaces); 15087 verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces); 15088 verifyFormat("std::vector<SomeType* const*> x;", Spaces); 15089 verifyFormat("std::vector<SomeType* qualified*> x;", Spaces); 15090 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15091 // However, setting it to SAPQ_After should add spaces after __attribute, etc. 15092 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After; 15093 verifyFormat("SomeType* volatile * a = NULL;", Spaces); 15094 verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces); 15095 verifyFormat("std::vector<SomeType* const *> x;", Spaces); 15096 verifyFormat("std::vector<SomeType* qualified *> x;", Spaces); 15097 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15098 15099 // PAS_Middle should not have any noticeable changes even for SAPQ_Both 15100 Spaces.PointerAlignment = FormatStyle::PAS_Middle; 15101 Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After; 15102 verifyFormat("SomeType * volatile * a = NULL;", Spaces); 15103 verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces); 15104 verifyFormat("std::vector<SomeType * const *> x;", Spaces); 15105 verifyFormat("std::vector<SomeType * qualified *> x;", Spaces); 15106 verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces); 15107 } 15108 15109 TEST_F(FormatTest, AlignConsecutiveMacros) { 15110 FormatStyle Style = getLLVMStyle(); 15111 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 15112 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 15113 Style.AlignConsecutiveMacros = FormatStyle::ACS_None; 15114 15115 verifyFormat("#define a 3\n" 15116 "#define bbbb 4\n" 15117 "#define ccc (5)", 15118 Style); 15119 15120 verifyFormat("#define f(x) (x * x)\n" 15121 "#define fff(x, y, z) (x * y + z)\n" 15122 "#define ffff(x, y) (x - y)", 15123 Style); 15124 15125 verifyFormat("#define foo(x, y) (x + y)\n" 15126 "#define bar (5, 6)(2 + 2)", 15127 Style); 15128 15129 verifyFormat("#define a 3\n" 15130 "#define bbbb 4\n" 15131 "#define ccc (5)\n" 15132 "#define f(x) (x * x)\n" 15133 "#define fff(x, y, z) (x * y + z)\n" 15134 "#define ffff(x, y) (x - y)", 15135 Style); 15136 15137 Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 15138 verifyFormat("#define a 3\n" 15139 "#define bbbb 4\n" 15140 "#define ccc (5)", 15141 Style); 15142 15143 verifyFormat("#define f(x) (x * x)\n" 15144 "#define fff(x, y, z) (x * y + z)\n" 15145 "#define ffff(x, y) (x - y)", 15146 Style); 15147 15148 verifyFormat("#define foo(x, y) (x + y)\n" 15149 "#define bar (5, 6)(2 + 2)", 15150 Style); 15151 15152 verifyFormat("#define a 3\n" 15153 "#define bbbb 4\n" 15154 "#define ccc (5)\n" 15155 "#define f(x) (x * x)\n" 15156 "#define fff(x, y, z) (x * y + z)\n" 15157 "#define ffff(x, y) (x - y)", 15158 Style); 15159 15160 verifyFormat("#define a 5\n" 15161 "#define foo(x, y) (x + y)\n" 15162 "#define CCC (6)\n" 15163 "auto lambda = []() {\n" 15164 " auto ii = 0;\n" 15165 " float j = 0;\n" 15166 " return 0;\n" 15167 "};\n" 15168 "int i = 0;\n" 15169 "float i2 = 0;\n" 15170 "auto v = type{\n" 15171 " i = 1, //\n" 15172 " (i = 2), //\n" 15173 " i = 3 //\n" 15174 "};", 15175 Style); 15176 15177 Style.AlignConsecutiveMacros = FormatStyle::ACS_None; 15178 Style.ColumnLimit = 20; 15179 15180 verifyFormat("#define a \\\n" 15181 " \"aabbbbbbbbbbbb\"\n" 15182 "#define D \\\n" 15183 " \"aabbbbbbbbbbbb\" \\\n" 15184 " \"ccddeeeeeeeee\"\n" 15185 "#define B \\\n" 15186 " \"QQQQQQQQQQQQQ\" \\\n" 15187 " \"FFFFFFFFFFFFF\" \\\n" 15188 " \"LLLLLLLL\"\n", 15189 Style); 15190 15191 Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 15192 verifyFormat("#define a \\\n" 15193 " \"aabbbbbbbbbbbb\"\n" 15194 "#define D \\\n" 15195 " \"aabbbbbbbbbbbb\" \\\n" 15196 " \"ccddeeeeeeeee\"\n" 15197 "#define B \\\n" 15198 " \"QQQQQQQQQQQQQ\" \\\n" 15199 " \"FFFFFFFFFFFFF\" \\\n" 15200 " \"LLLLLLLL\"\n", 15201 Style); 15202 15203 // Test across comments 15204 Style.MaxEmptyLinesToKeep = 10; 15205 Style.ReflowComments = false; 15206 Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossComments; 15207 EXPECT_EQ("#define a 3\n" 15208 "// line comment\n" 15209 "#define bbbb 4\n" 15210 "#define ccc (5)", 15211 format("#define a 3\n" 15212 "// line comment\n" 15213 "#define bbbb 4\n" 15214 "#define ccc (5)", 15215 Style)); 15216 15217 EXPECT_EQ("#define a 3\n" 15218 "/* block comment */\n" 15219 "#define bbbb 4\n" 15220 "#define ccc (5)", 15221 format("#define a 3\n" 15222 "/* block comment */\n" 15223 "#define bbbb 4\n" 15224 "#define ccc (5)", 15225 Style)); 15226 15227 EXPECT_EQ("#define a 3\n" 15228 "/* multi-line *\n" 15229 " * block comment */\n" 15230 "#define bbbb 4\n" 15231 "#define ccc (5)", 15232 format("#define a 3\n" 15233 "/* multi-line *\n" 15234 " * block comment */\n" 15235 "#define bbbb 4\n" 15236 "#define ccc (5)", 15237 Style)); 15238 15239 EXPECT_EQ("#define a 3\n" 15240 "// multi-line line comment\n" 15241 "//\n" 15242 "#define bbbb 4\n" 15243 "#define ccc (5)", 15244 format("#define a 3\n" 15245 "// multi-line line comment\n" 15246 "//\n" 15247 "#define bbbb 4\n" 15248 "#define ccc (5)", 15249 Style)); 15250 15251 EXPECT_EQ("#define a 3\n" 15252 "// empty lines still break.\n" 15253 "\n" 15254 "#define bbbb 4\n" 15255 "#define ccc (5)", 15256 format("#define a 3\n" 15257 "// empty lines still break.\n" 15258 "\n" 15259 "#define bbbb 4\n" 15260 "#define ccc (5)", 15261 Style)); 15262 15263 // Test across empty lines 15264 Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLines; 15265 EXPECT_EQ("#define a 3\n" 15266 "\n" 15267 "#define bbbb 4\n" 15268 "#define ccc (5)", 15269 format("#define a 3\n" 15270 "\n" 15271 "#define bbbb 4\n" 15272 "#define ccc (5)", 15273 Style)); 15274 15275 EXPECT_EQ("#define a 3\n" 15276 "\n" 15277 "\n" 15278 "\n" 15279 "#define bbbb 4\n" 15280 "#define ccc (5)", 15281 format("#define a 3\n" 15282 "\n" 15283 "\n" 15284 "\n" 15285 "#define bbbb 4\n" 15286 "#define ccc (5)", 15287 Style)); 15288 15289 EXPECT_EQ("#define a 3\n" 15290 "// comments should break alignment\n" 15291 "//\n" 15292 "#define bbbb 4\n" 15293 "#define ccc (5)", 15294 format("#define a 3\n" 15295 "// comments should break alignment\n" 15296 "//\n" 15297 "#define bbbb 4\n" 15298 "#define ccc (5)", 15299 Style)); 15300 15301 // Test across empty lines and comments 15302 Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLinesAndComments; 15303 verifyFormat("#define a 3\n" 15304 "\n" 15305 "// line comment\n" 15306 "#define bbbb 4\n" 15307 "#define ccc (5)", 15308 Style); 15309 15310 EXPECT_EQ("#define a 3\n" 15311 "\n" 15312 "\n" 15313 "/* multi-line *\n" 15314 " * block comment */\n" 15315 "\n" 15316 "\n" 15317 "#define bbbb 4\n" 15318 "#define ccc (5)", 15319 format("#define a 3\n" 15320 "\n" 15321 "\n" 15322 "/* multi-line *\n" 15323 " * block comment */\n" 15324 "\n" 15325 "\n" 15326 "#define bbbb 4\n" 15327 "#define ccc (5)", 15328 Style)); 15329 15330 EXPECT_EQ("#define a 3\n" 15331 "\n" 15332 "\n" 15333 "/* multi-line *\n" 15334 " * block comment */\n" 15335 "\n" 15336 "\n" 15337 "#define bbbb 4\n" 15338 "#define ccc (5)", 15339 format("#define a 3\n" 15340 "\n" 15341 "\n" 15342 "/* multi-line *\n" 15343 " * block comment */\n" 15344 "\n" 15345 "\n" 15346 "#define bbbb 4\n" 15347 "#define ccc (5)", 15348 Style)); 15349 } 15350 15351 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) { 15352 FormatStyle Alignment = getLLVMStyle(); 15353 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 15354 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossEmptyLines; 15355 15356 Alignment.MaxEmptyLinesToKeep = 10; 15357 /* Test alignment across empty lines */ 15358 EXPECT_EQ("int a = 5;\n" 15359 "\n" 15360 "int oneTwoThree = 123;", 15361 format("int a = 5;\n" 15362 "\n" 15363 "int oneTwoThree= 123;", 15364 Alignment)); 15365 EXPECT_EQ("int a = 5;\n" 15366 "int one = 1;\n" 15367 "\n" 15368 "int oneTwoThree = 123;", 15369 format("int a = 5;\n" 15370 "int one = 1;\n" 15371 "\n" 15372 "int oneTwoThree = 123;", 15373 Alignment)); 15374 EXPECT_EQ("int a = 5;\n" 15375 "int one = 1;\n" 15376 "\n" 15377 "int oneTwoThree = 123;\n" 15378 "int oneTwo = 12;", 15379 format("int a = 5;\n" 15380 "int one = 1;\n" 15381 "\n" 15382 "int oneTwoThree = 123;\n" 15383 "int oneTwo = 12;", 15384 Alignment)); 15385 15386 /* Test across comments */ 15387 EXPECT_EQ("int a = 5;\n" 15388 "/* block comment */\n" 15389 "int oneTwoThree = 123;", 15390 format("int a = 5;\n" 15391 "/* block comment */\n" 15392 "int oneTwoThree=123;", 15393 Alignment)); 15394 15395 EXPECT_EQ("int a = 5;\n" 15396 "// line comment\n" 15397 "int oneTwoThree = 123;", 15398 format("int a = 5;\n" 15399 "// line comment\n" 15400 "int oneTwoThree=123;", 15401 Alignment)); 15402 15403 /* Test across comments and newlines */ 15404 EXPECT_EQ("int a = 5;\n" 15405 "\n" 15406 "/* block comment */\n" 15407 "int oneTwoThree = 123;", 15408 format("int a = 5;\n" 15409 "\n" 15410 "/* block comment */\n" 15411 "int oneTwoThree=123;", 15412 Alignment)); 15413 15414 EXPECT_EQ("int a = 5;\n" 15415 "\n" 15416 "// line comment\n" 15417 "int oneTwoThree = 123;", 15418 format("int a = 5;\n" 15419 "\n" 15420 "// line comment\n" 15421 "int oneTwoThree=123;", 15422 Alignment)); 15423 } 15424 15425 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) { 15426 FormatStyle Alignment = getLLVMStyle(); 15427 Alignment.AlignConsecutiveDeclarations = 15428 FormatStyle::ACS_AcrossEmptyLinesAndComments; 15429 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 15430 15431 Alignment.MaxEmptyLinesToKeep = 10; 15432 /* Test alignment across empty lines */ 15433 EXPECT_EQ("int a = 5;\n" 15434 "\n" 15435 "float const oneTwoThree = 123;", 15436 format("int a = 5;\n" 15437 "\n" 15438 "float const oneTwoThree = 123;", 15439 Alignment)); 15440 EXPECT_EQ("int a = 5;\n" 15441 "float const one = 1;\n" 15442 "\n" 15443 "int oneTwoThree = 123;", 15444 format("int a = 5;\n" 15445 "float const one = 1;\n" 15446 "\n" 15447 "int oneTwoThree = 123;", 15448 Alignment)); 15449 15450 /* Test across comments */ 15451 EXPECT_EQ("float const a = 5;\n" 15452 "/* block comment */\n" 15453 "int oneTwoThree = 123;", 15454 format("float const a = 5;\n" 15455 "/* block comment */\n" 15456 "int oneTwoThree=123;", 15457 Alignment)); 15458 15459 EXPECT_EQ("float const a = 5;\n" 15460 "// line comment\n" 15461 "int oneTwoThree = 123;", 15462 format("float const a = 5;\n" 15463 "// line comment\n" 15464 "int oneTwoThree=123;", 15465 Alignment)); 15466 15467 /* Test across comments and newlines */ 15468 EXPECT_EQ("float const a = 5;\n" 15469 "\n" 15470 "/* block comment */\n" 15471 "int oneTwoThree = 123;", 15472 format("float const a = 5;\n" 15473 "\n" 15474 "/* block comment */\n" 15475 "int oneTwoThree=123;", 15476 Alignment)); 15477 15478 EXPECT_EQ("float const a = 5;\n" 15479 "\n" 15480 "// line comment\n" 15481 "int oneTwoThree = 123;", 15482 format("float const a = 5;\n" 15483 "\n" 15484 "// line comment\n" 15485 "int oneTwoThree=123;", 15486 Alignment)); 15487 } 15488 15489 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) { 15490 FormatStyle Alignment = getLLVMStyle(); 15491 Alignment.AlignConsecutiveBitFields = 15492 FormatStyle::ACS_AcrossEmptyLinesAndComments; 15493 15494 Alignment.MaxEmptyLinesToKeep = 10; 15495 /* Test alignment across empty lines */ 15496 EXPECT_EQ("int a : 5;\n" 15497 "\n" 15498 "int longbitfield : 6;", 15499 format("int a : 5;\n" 15500 "\n" 15501 "int longbitfield : 6;", 15502 Alignment)); 15503 EXPECT_EQ("int a : 5;\n" 15504 "int one : 1;\n" 15505 "\n" 15506 "int longbitfield : 6;", 15507 format("int a : 5;\n" 15508 "int one : 1;\n" 15509 "\n" 15510 "int longbitfield : 6;", 15511 Alignment)); 15512 15513 /* Test across comments */ 15514 EXPECT_EQ("int a : 5;\n" 15515 "/* block comment */\n" 15516 "int longbitfield : 6;", 15517 format("int a : 5;\n" 15518 "/* block comment */\n" 15519 "int longbitfield : 6;", 15520 Alignment)); 15521 EXPECT_EQ("int a : 5;\n" 15522 "int one : 1;\n" 15523 "// line comment\n" 15524 "int longbitfield : 6;", 15525 format("int a : 5;\n" 15526 "int one : 1;\n" 15527 "// line comment\n" 15528 "int longbitfield : 6;", 15529 Alignment)); 15530 15531 /* Test across comments and newlines */ 15532 EXPECT_EQ("int a : 5;\n" 15533 "/* block comment */\n" 15534 "\n" 15535 "int longbitfield : 6;", 15536 format("int a : 5;\n" 15537 "/* block comment */\n" 15538 "\n" 15539 "int longbitfield : 6;", 15540 Alignment)); 15541 EXPECT_EQ("int a : 5;\n" 15542 "int one : 1;\n" 15543 "\n" 15544 "// line comment\n" 15545 "\n" 15546 "int longbitfield : 6;", 15547 format("int a : 5;\n" 15548 "int one : 1;\n" 15549 "\n" 15550 "// line comment \n" 15551 "\n" 15552 "int longbitfield : 6;", 15553 Alignment)); 15554 } 15555 15556 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) { 15557 FormatStyle Alignment = getLLVMStyle(); 15558 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 15559 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossComments; 15560 15561 Alignment.MaxEmptyLinesToKeep = 10; 15562 /* Test alignment across empty lines */ 15563 EXPECT_EQ("int a = 5;\n" 15564 "\n" 15565 "int oneTwoThree = 123;", 15566 format("int a = 5;\n" 15567 "\n" 15568 "int oneTwoThree= 123;", 15569 Alignment)); 15570 EXPECT_EQ("int a = 5;\n" 15571 "int one = 1;\n" 15572 "\n" 15573 "int oneTwoThree = 123;", 15574 format("int a = 5;\n" 15575 "int one = 1;\n" 15576 "\n" 15577 "int oneTwoThree = 123;", 15578 Alignment)); 15579 15580 /* Test across comments */ 15581 EXPECT_EQ("int a = 5;\n" 15582 "/* block comment */\n" 15583 "int oneTwoThree = 123;", 15584 format("int a = 5;\n" 15585 "/* block comment */\n" 15586 "int oneTwoThree=123;", 15587 Alignment)); 15588 15589 EXPECT_EQ("int a = 5;\n" 15590 "// line comment\n" 15591 "int oneTwoThree = 123;", 15592 format("int a = 5;\n" 15593 "// line comment\n" 15594 "int oneTwoThree=123;", 15595 Alignment)); 15596 15597 EXPECT_EQ("int a = 5;\n" 15598 "/*\n" 15599 " * multi-line block comment\n" 15600 " */\n" 15601 "int oneTwoThree = 123;", 15602 format("int a = 5;\n" 15603 "/*\n" 15604 " * multi-line block comment\n" 15605 " */\n" 15606 "int oneTwoThree=123;", 15607 Alignment)); 15608 15609 EXPECT_EQ("int a = 5;\n" 15610 "//\n" 15611 "// multi-line line comment\n" 15612 "//\n" 15613 "int oneTwoThree = 123;", 15614 format("int a = 5;\n" 15615 "//\n" 15616 "// multi-line line comment\n" 15617 "//\n" 15618 "int oneTwoThree=123;", 15619 Alignment)); 15620 15621 /* Test across comments and newlines */ 15622 EXPECT_EQ("int a = 5;\n" 15623 "\n" 15624 "/* block comment */\n" 15625 "int oneTwoThree = 123;", 15626 format("int a = 5;\n" 15627 "\n" 15628 "/* block comment */\n" 15629 "int oneTwoThree=123;", 15630 Alignment)); 15631 15632 EXPECT_EQ("int a = 5;\n" 15633 "\n" 15634 "// line comment\n" 15635 "int oneTwoThree = 123;", 15636 format("int a = 5;\n" 15637 "\n" 15638 "// line comment\n" 15639 "int oneTwoThree=123;", 15640 Alignment)); 15641 } 15642 15643 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) { 15644 FormatStyle Alignment = getLLVMStyle(); 15645 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 15646 Alignment.AlignConsecutiveAssignments = 15647 FormatStyle::ACS_AcrossEmptyLinesAndComments; 15648 verifyFormat("int a = 5;\n" 15649 "int oneTwoThree = 123;", 15650 Alignment); 15651 verifyFormat("int a = method();\n" 15652 "int oneTwoThree = 133;", 15653 Alignment); 15654 verifyFormat("a &= 5;\n" 15655 "bcd *= 5;\n" 15656 "ghtyf += 5;\n" 15657 "dvfvdb -= 5;\n" 15658 "a /= 5;\n" 15659 "vdsvsv %= 5;\n" 15660 "sfdbddfbdfbb ^= 5;\n" 15661 "dvsdsv |= 5;\n" 15662 "int dsvvdvsdvvv = 123;", 15663 Alignment); 15664 verifyFormat("int i = 1, j = 10;\n" 15665 "something = 2000;", 15666 Alignment); 15667 verifyFormat("something = 2000;\n" 15668 "int i = 1, j = 10;\n", 15669 Alignment); 15670 verifyFormat("something = 2000;\n" 15671 "another = 911;\n" 15672 "int i = 1, j = 10;\n" 15673 "oneMore = 1;\n" 15674 "i = 2;", 15675 Alignment); 15676 verifyFormat("int a = 5;\n" 15677 "int one = 1;\n" 15678 "method();\n" 15679 "int oneTwoThree = 123;\n" 15680 "int oneTwo = 12;", 15681 Alignment); 15682 verifyFormat("int oneTwoThree = 123;\n" 15683 "int oneTwo = 12;\n" 15684 "method();\n", 15685 Alignment); 15686 verifyFormat("int oneTwoThree = 123; // comment\n" 15687 "int oneTwo = 12; // comment", 15688 Alignment); 15689 15690 // Bug 25167 15691 /* Uncomment when fixed 15692 verifyFormat("#if A\n" 15693 "#else\n" 15694 "int aaaaaaaa = 12;\n" 15695 "#endif\n" 15696 "#if B\n" 15697 "#else\n" 15698 "int a = 12;\n" 15699 "#endif\n", 15700 Alignment); 15701 verifyFormat("enum foo {\n" 15702 "#if A\n" 15703 "#else\n" 15704 " aaaaaaaa = 12;\n" 15705 "#endif\n" 15706 "#if B\n" 15707 "#else\n" 15708 " a = 12;\n" 15709 "#endif\n" 15710 "};\n", 15711 Alignment); 15712 */ 15713 15714 Alignment.MaxEmptyLinesToKeep = 10; 15715 /* Test alignment across empty lines */ 15716 EXPECT_EQ("int a = 5;\n" 15717 "\n" 15718 "int oneTwoThree = 123;", 15719 format("int a = 5;\n" 15720 "\n" 15721 "int oneTwoThree= 123;", 15722 Alignment)); 15723 EXPECT_EQ("int a = 5;\n" 15724 "int one = 1;\n" 15725 "\n" 15726 "int oneTwoThree = 123;", 15727 format("int a = 5;\n" 15728 "int one = 1;\n" 15729 "\n" 15730 "int oneTwoThree = 123;", 15731 Alignment)); 15732 EXPECT_EQ("int a = 5;\n" 15733 "int one = 1;\n" 15734 "\n" 15735 "int oneTwoThree = 123;\n" 15736 "int oneTwo = 12;", 15737 format("int a = 5;\n" 15738 "int one = 1;\n" 15739 "\n" 15740 "int oneTwoThree = 123;\n" 15741 "int oneTwo = 12;", 15742 Alignment)); 15743 15744 /* Test across comments */ 15745 EXPECT_EQ("int a = 5;\n" 15746 "/* block comment */\n" 15747 "int oneTwoThree = 123;", 15748 format("int a = 5;\n" 15749 "/* block comment */\n" 15750 "int oneTwoThree=123;", 15751 Alignment)); 15752 15753 EXPECT_EQ("int a = 5;\n" 15754 "// line comment\n" 15755 "int oneTwoThree = 123;", 15756 format("int a = 5;\n" 15757 "// line comment\n" 15758 "int oneTwoThree=123;", 15759 Alignment)); 15760 15761 /* Test across comments and newlines */ 15762 EXPECT_EQ("int a = 5;\n" 15763 "\n" 15764 "/* block comment */\n" 15765 "int oneTwoThree = 123;", 15766 format("int a = 5;\n" 15767 "\n" 15768 "/* block comment */\n" 15769 "int oneTwoThree=123;", 15770 Alignment)); 15771 15772 EXPECT_EQ("int a = 5;\n" 15773 "\n" 15774 "// line comment\n" 15775 "int oneTwoThree = 123;", 15776 format("int a = 5;\n" 15777 "\n" 15778 "// line comment\n" 15779 "int oneTwoThree=123;", 15780 Alignment)); 15781 15782 EXPECT_EQ("int a = 5;\n" 15783 "//\n" 15784 "// multi-line line comment\n" 15785 "//\n" 15786 "int oneTwoThree = 123;", 15787 format("int a = 5;\n" 15788 "//\n" 15789 "// multi-line line comment\n" 15790 "//\n" 15791 "int oneTwoThree=123;", 15792 Alignment)); 15793 15794 EXPECT_EQ("int a = 5;\n" 15795 "/*\n" 15796 " * multi-line block comment\n" 15797 " */\n" 15798 "int oneTwoThree = 123;", 15799 format("int a = 5;\n" 15800 "/*\n" 15801 " * multi-line block comment\n" 15802 " */\n" 15803 "int oneTwoThree=123;", 15804 Alignment)); 15805 15806 EXPECT_EQ("int a = 5;\n" 15807 "\n" 15808 "/* block comment */\n" 15809 "\n" 15810 "\n" 15811 "\n" 15812 "int oneTwoThree = 123;", 15813 format("int a = 5;\n" 15814 "\n" 15815 "/* block comment */\n" 15816 "\n" 15817 "\n" 15818 "\n" 15819 "int oneTwoThree=123;", 15820 Alignment)); 15821 15822 EXPECT_EQ("int a = 5;\n" 15823 "\n" 15824 "// line comment\n" 15825 "\n" 15826 "\n" 15827 "\n" 15828 "int oneTwoThree = 123;", 15829 format("int a = 5;\n" 15830 "\n" 15831 "// line comment\n" 15832 "\n" 15833 "\n" 15834 "\n" 15835 "int oneTwoThree=123;", 15836 Alignment)); 15837 15838 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 15839 verifyFormat("#define A \\\n" 15840 " int aaaa = 12; \\\n" 15841 " int b = 23; \\\n" 15842 " int ccc = 234; \\\n" 15843 " int dddddddddd = 2345;", 15844 Alignment); 15845 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 15846 verifyFormat("#define A \\\n" 15847 " int aaaa = 12; \\\n" 15848 " int b = 23; \\\n" 15849 " int ccc = 234; \\\n" 15850 " int dddddddddd = 2345;", 15851 Alignment); 15852 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 15853 verifyFormat("#define A " 15854 " \\\n" 15855 " int aaaa = 12; " 15856 " \\\n" 15857 " int b = 23; " 15858 " \\\n" 15859 " int ccc = 234; " 15860 " \\\n" 15861 " int dddddddddd = 2345;", 15862 Alignment); 15863 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 15864 "k = 4, int l = 5,\n" 15865 " int m = 6) {\n" 15866 " int j = 10;\n" 15867 " otherThing = 1;\n" 15868 "}", 15869 Alignment); 15870 verifyFormat("void SomeFunction(int parameter = 0) {\n" 15871 " int i = 1;\n" 15872 " int j = 2;\n" 15873 " int big = 10000;\n" 15874 "}", 15875 Alignment); 15876 verifyFormat("class C {\n" 15877 "public:\n" 15878 " int i = 1;\n" 15879 " virtual void f() = 0;\n" 15880 "};", 15881 Alignment); 15882 verifyFormat("int i = 1;\n" 15883 "if (SomeType t = getSomething()) {\n" 15884 "}\n" 15885 "int j = 2;\n" 15886 "int big = 10000;", 15887 Alignment); 15888 verifyFormat("int j = 7;\n" 15889 "for (int k = 0; k < N; ++k) {\n" 15890 "}\n" 15891 "int j = 2;\n" 15892 "int big = 10000;\n" 15893 "}", 15894 Alignment); 15895 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 15896 verifyFormat("int i = 1;\n" 15897 "LooooooooooongType loooooooooooooooooooooongVariable\n" 15898 " = someLooooooooooooooooongFunction();\n" 15899 "int j = 2;", 15900 Alignment); 15901 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 15902 verifyFormat("int i = 1;\n" 15903 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 15904 " someLooooooooooooooooongFunction();\n" 15905 "int j = 2;", 15906 Alignment); 15907 15908 verifyFormat("auto lambda = []() {\n" 15909 " auto i = 0;\n" 15910 " return 0;\n" 15911 "};\n" 15912 "int i = 0;\n" 15913 "auto v = type{\n" 15914 " i = 1, //\n" 15915 " (i = 2), //\n" 15916 " i = 3 //\n" 15917 "};", 15918 Alignment); 15919 15920 verifyFormat( 15921 "int i = 1;\n" 15922 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 15923 " loooooooooooooooooooooongParameterB);\n" 15924 "int j = 2;", 15925 Alignment); 15926 15927 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n" 15928 " typename B = very_long_type_name_1,\n" 15929 " typename T_2 = very_long_type_name_2>\n" 15930 "auto foo() {}\n", 15931 Alignment); 15932 verifyFormat("int a, b = 1;\n" 15933 "int c = 2;\n" 15934 "int dd = 3;\n", 15935 Alignment); 15936 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 15937 "float b[1][] = {{3.f}};\n", 15938 Alignment); 15939 verifyFormat("for (int i = 0; i < 1; i++)\n" 15940 " int x = 1;\n", 15941 Alignment); 15942 verifyFormat("for (i = 0; i < 1; i++)\n" 15943 " x = 1;\n" 15944 "y = 1;\n", 15945 Alignment); 15946 15947 Alignment.ReflowComments = true; 15948 Alignment.ColumnLimit = 50; 15949 EXPECT_EQ("int x = 0;\n" 15950 "int yy = 1; /// specificlennospace\n" 15951 "int zzz = 2;\n", 15952 format("int x = 0;\n" 15953 "int yy = 1; ///specificlennospace\n" 15954 "int zzz = 2;\n", 15955 Alignment)); 15956 } 15957 15958 TEST_F(FormatTest, AlignConsecutiveAssignments) { 15959 FormatStyle Alignment = getLLVMStyle(); 15960 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 15961 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 15962 verifyFormat("int a = 5;\n" 15963 "int oneTwoThree = 123;", 15964 Alignment); 15965 verifyFormat("int a = 5;\n" 15966 "int oneTwoThree = 123;", 15967 Alignment); 15968 15969 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 15970 verifyFormat("int a = 5;\n" 15971 "int oneTwoThree = 123;", 15972 Alignment); 15973 verifyFormat("int a = method();\n" 15974 "int oneTwoThree = 133;", 15975 Alignment); 15976 verifyFormat("a &= 5;\n" 15977 "bcd *= 5;\n" 15978 "ghtyf += 5;\n" 15979 "dvfvdb -= 5;\n" 15980 "a /= 5;\n" 15981 "vdsvsv %= 5;\n" 15982 "sfdbddfbdfbb ^= 5;\n" 15983 "dvsdsv |= 5;\n" 15984 "int dsvvdvsdvvv = 123;", 15985 Alignment); 15986 verifyFormat("int i = 1, j = 10;\n" 15987 "something = 2000;", 15988 Alignment); 15989 verifyFormat("something = 2000;\n" 15990 "int i = 1, j = 10;\n", 15991 Alignment); 15992 verifyFormat("something = 2000;\n" 15993 "another = 911;\n" 15994 "int i = 1, j = 10;\n" 15995 "oneMore = 1;\n" 15996 "i = 2;", 15997 Alignment); 15998 verifyFormat("int a = 5;\n" 15999 "int one = 1;\n" 16000 "method();\n" 16001 "int oneTwoThree = 123;\n" 16002 "int oneTwo = 12;", 16003 Alignment); 16004 verifyFormat("int oneTwoThree = 123;\n" 16005 "int oneTwo = 12;\n" 16006 "method();\n", 16007 Alignment); 16008 verifyFormat("int oneTwoThree = 123; // comment\n" 16009 "int oneTwo = 12; // comment", 16010 Alignment); 16011 16012 // Bug 25167 16013 /* Uncomment when fixed 16014 verifyFormat("#if A\n" 16015 "#else\n" 16016 "int aaaaaaaa = 12;\n" 16017 "#endif\n" 16018 "#if B\n" 16019 "#else\n" 16020 "int a = 12;\n" 16021 "#endif\n", 16022 Alignment); 16023 verifyFormat("enum foo {\n" 16024 "#if A\n" 16025 "#else\n" 16026 " aaaaaaaa = 12;\n" 16027 "#endif\n" 16028 "#if B\n" 16029 "#else\n" 16030 " a = 12;\n" 16031 "#endif\n" 16032 "};\n", 16033 Alignment); 16034 */ 16035 16036 EXPECT_EQ("int a = 5;\n" 16037 "\n" 16038 "int oneTwoThree = 123;", 16039 format("int a = 5;\n" 16040 "\n" 16041 "int oneTwoThree= 123;", 16042 Alignment)); 16043 EXPECT_EQ("int a = 5;\n" 16044 "int one = 1;\n" 16045 "\n" 16046 "int oneTwoThree = 123;", 16047 format("int a = 5;\n" 16048 "int one = 1;\n" 16049 "\n" 16050 "int oneTwoThree = 123;", 16051 Alignment)); 16052 EXPECT_EQ("int a = 5;\n" 16053 "int one = 1;\n" 16054 "\n" 16055 "int oneTwoThree = 123;\n" 16056 "int oneTwo = 12;", 16057 format("int a = 5;\n" 16058 "int one = 1;\n" 16059 "\n" 16060 "int oneTwoThree = 123;\n" 16061 "int oneTwo = 12;", 16062 Alignment)); 16063 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 16064 verifyFormat("#define A \\\n" 16065 " int aaaa = 12; \\\n" 16066 " int b = 23; \\\n" 16067 " int ccc = 234; \\\n" 16068 " int dddddddddd = 2345;", 16069 Alignment); 16070 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 16071 verifyFormat("#define A \\\n" 16072 " int aaaa = 12; \\\n" 16073 " int b = 23; \\\n" 16074 " int ccc = 234; \\\n" 16075 " int dddddddddd = 2345;", 16076 Alignment); 16077 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 16078 verifyFormat("#define A " 16079 " \\\n" 16080 " int aaaa = 12; " 16081 " \\\n" 16082 " int b = 23; " 16083 " \\\n" 16084 " int ccc = 234; " 16085 " \\\n" 16086 " int dddddddddd = 2345;", 16087 Alignment); 16088 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 16089 "k = 4, int l = 5,\n" 16090 " int m = 6) {\n" 16091 " int j = 10;\n" 16092 " otherThing = 1;\n" 16093 "}", 16094 Alignment); 16095 verifyFormat("void SomeFunction(int parameter = 0) {\n" 16096 " int i = 1;\n" 16097 " int j = 2;\n" 16098 " int big = 10000;\n" 16099 "}", 16100 Alignment); 16101 verifyFormat("class C {\n" 16102 "public:\n" 16103 " int i = 1;\n" 16104 " virtual void f() = 0;\n" 16105 "};", 16106 Alignment); 16107 verifyFormat("int i = 1;\n" 16108 "if (SomeType t = getSomething()) {\n" 16109 "}\n" 16110 "int j = 2;\n" 16111 "int big = 10000;", 16112 Alignment); 16113 verifyFormat("int j = 7;\n" 16114 "for (int k = 0; k < N; ++k) {\n" 16115 "}\n" 16116 "int j = 2;\n" 16117 "int big = 10000;\n" 16118 "}", 16119 Alignment); 16120 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 16121 verifyFormat("int i = 1;\n" 16122 "LooooooooooongType loooooooooooooooooooooongVariable\n" 16123 " = someLooooooooooooooooongFunction();\n" 16124 "int j = 2;", 16125 Alignment); 16126 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 16127 verifyFormat("int i = 1;\n" 16128 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 16129 " someLooooooooooooooooongFunction();\n" 16130 "int j = 2;", 16131 Alignment); 16132 16133 verifyFormat("auto lambda = []() {\n" 16134 " auto i = 0;\n" 16135 " return 0;\n" 16136 "};\n" 16137 "int i = 0;\n" 16138 "auto v = type{\n" 16139 " i = 1, //\n" 16140 " (i = 2), //\n" 16141 " i = 3 //\n" 16142 "};", 16143 Alignment); 16144 16145 verifyFormat( 16146 "int i = 1;\n" 16147 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 16148 " loooooooooooooooooooooongParameterB);\n" 16149 "int j = 2;", 16150 Alignment); 16151 16152 verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n" 16153 " typename B = very_long_type_name_1,\n" 16154 " typename T_2 = very_long_type_name_2>\n" 16155 "auto foo() {}\n", 16156 Alignment); 16157 verifyFormat("int a, b = 1;\n" 16158 "int c = 2;\n" 16159 "int dd = 3;\n", 16160 Alignment); 16161 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 16162 "float b[1][] = {{3.f}};\n", 16163 Alignment); 16164 verifyFormat("for (int i = 0; i < 1; i++)\n" 16165 " int x = 1;\n", 16166 Alignment); 16167 verifyFormat("for (i = 0; i < 1; i++)\n" 16168 " x = 1;\n" 16169 "y = 1;\n", 16170 Alignment); 16171 16172 Alignment.ReflowComments = true; 16173 Alignment.ColumnLimit = 50; 16174 EXPECT_EQ("int x = 0;\n" 16175 "int yy = 1; /// specificlennospace\n" 16176 "int zzz = 2;\n", 16177 format("int x = 0;\n" 16178 "int yy = 1; ///specificlennospace\n" 16179 "int zzz = 2;\n", 16180 Alignment)); 16181 } 16182 16183 TEST_F(FormatTest, AlignConsecutiveBitFields) { 16184 FormatStyle Alignment = getLLVMStyle(); 16185 Alignment.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive; 16186 verifyFormat("int const a : 5;\n" 16187 "int oneTwoThree : 23;", 16188 Alignment); 16189 16190 // Initializers are allowed starting with c++2a 16191 verifyFormat("int const a : 5 = 1;\n" 16192 "int oneTwoThree : 23 = 0;", 16193 Alignment); 16194 16195 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 16196 verifyFormat("int const a : 5;\n" 16197 "int oneTwoThree : 23;", 16198 Alignment); 16199 16200 verifyFormat("int const a : 5; // comment\n" 16201 "int oneTwoThree : 23; // comment", 16202 Alignment); 16203 16204 verifyFormat("int const a : 5 = 1;\n" 16205 "int oneTwoThree : 23 = 0;", 16206 Alignment); 16207 16208 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 16209 verifyFormat("int const a : 5 = 1;\n" 16210 "int oneTwoThree : 23 = 0;", 16211 Alignment); 16212 verifyFormat("int const a : 5 = {1};\n" 16213 "int oneTwoThree : 23 = 0;", 16214 Alignment); 16215 16216 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None; 16217 verifyFormat("int const a :5;\n" 16218 "int oneTwoThree:23;", 16219 Alignment); 16220 16221 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before; 16222 verifyFormat("int const a :5;\n" 16223 "int oneTwoThree :23;", 16224 Alignment); 16225 16226 Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After; 16227 verifyFormat("int const a : 5;\n" 16228 "int oneTwoThree: 23;", 16229 Alignment); 16230 16231 // Known limitations: ':' is only recognized as a bitfield colon when 16232 // followed by a number. 16233 /* 16234 verifyFormat("int oneTwoThree : SOME_CONSTANT;\n" 16235 "int a : 5;", 16236 Alignment); 16237 */ 16238 } 16239 16240 TEST_F(FormatTest, AlignConsecutiveDeclarations) { 16241 FormatStyle Alignment = getLLVMStyle(); 16242 Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 16243 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_None; 16244 Alignment.PointerAlignment = FormatStyle::PAS_Right; 16245 verifyFormat("float const a = 5;\n" 16246 "int oneTwoThree = 123;", 16247 Alignment); 16248 verifyFormat("int a = 5;\n" 16249 "float const oneTwoThree = 123;", 16250 Alignment); 16251 16252 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 16253 verifyFormat("float const a = 5;\n" 16254 "int oneTwoThree = 123;", 16255 Alignment); 16256 verifyFormat("int a = method();\n" 16257 "float const oneTwoThree = 133;", 16258 Alignment); 16259 verifyFormat("int i = 1, j = 10;\n" 16260 "something = 2000;", 16261 Alignment); 16262 verifyFormat("something = 2000;\n" 16263 "int i = 1, j = 10;\n", 16264 Alignment); 16265 verifyFormat("float something = 2000;\n" 16266 "double another = 911;\n" 16267 "int i = 1, j = 10;\n" 16268 "const int *oneMore = 1;\n" 16269 "unsigned i = 2;", 16270 Alignment); 16271 verifyFormat("float a = 5;\n" 16272 "int one = 1;\n" 16273 "method();\n" 16274 "const double oneTwoThree = 123;\n" 16275 "const unsigned int oneTwo = 12;", 16276 Alignment); 16277 verifyFormat("int oneTwoThree{0}; // comment\n" 16278 "unsigned oneTwo; // comment", 16279 Alignment); 16280 verifyFormat("unsigned int *a;\n" 16281 "int *b;\n" 16282 "unsigned int Const *c;\n" 16283 "unsigned int const *d;\n" 16284 "unsigned int Const &e;\n" 16285 "unsigned int const &f;", 16286 Alignment); 16287 verifyFormat("Const unsigned int *c;\n" 16288 "const unsigned int *d;\n" 16289 "Const unsigned int &e;\n" 16290 "const unsigned int &f;\n" 16291 "const unsigned g;\n" 16292 "Const unsigned h;", 16293 Alignment); 16294 EXPECT_EQ("float const a = 5;\n" 16295 "\n" 16296 "int oneTwoThree = 123;", 16297 format("float const a = 5;\n" 16298 "\n" 16299 "int oneTwoThree= 123;", 16300 Alignment)); 16301 EXPECT_EQ("float a = 5;\n" 16302 "int one = 1;\n" 16303 "\n" 16304 "unsigned oneTwoThree = 123;", 16305 format("float a = 5;\n" 16306 "int one = 1;\n" 16307 "\n" 16308 "unsigned oneTwoThree = 123;", 16309 Alignment)); 16310 EXPECT_EQ("float a = 5;\n" 16311 "int one = 1;\n" 16312 "\n" 16313 "unsigned oneTwoThree = 123;\n" 16314 "int oneTwo = 12;", 16315 format("float a = 5;\n" 16316 "int one = 1;\n" 16317 "\n" 16318 "unsigned oneTwoThree = 123;\n" 16319 "int oneTwo = 12;", 16320 Alignment)); 16321 // Function prototype alignment 16322 verifyFormat("int a();\n" 16323 "double b();", 16324 Alignment); 16325 verifyFormat("int a(int x);\n" 16326 "double b();", 16327 Alignment); 16328 unsigned OldColumnLimit = Alignment.ColumnLimit; 16329 // We need to set ColumnLimit to zero, in order to stress nested alignments, 16330 // otherwise the function parameters will be re-flowed onto a single line. 16331 Alignment.ColumnLimit = 0; 16332 EXPECT_EQ("int a(int x,\n" 16333 " float y);\n" 16334 "double b(int x,\n" 16335 " double y);", 16336 format("int a(int x,\n" 16337 " float y);\n" 16338 "double b(int x,\n" 16339 " double y);", 16340 Alignment)); 16341 // This ensures that function parameters of function declarations are 16342 // correctly indented when their owning functions are indented. 16343 // The failure case here is for 'double y' to not be indented enough. 16344 EXPECT_EQ("double a(int x);\n" 16345 "int b(int y,\n" 16346 " double z);", 16347 format("double a(int x);\n" 16348 "int b(int y,\n" 16349 " double z);", 16350 Alignment)); 16351 // Set ColumnLimit low so that we induce wrapping immediately after 16352 // the function name and opening paren. 16353 Alignment.ColumnLimit = 13; 16354 verifyFormat("int function(\n" 16355 " int x,\n" 16356 " bool y);", 16357 Alignment); 16358 Alignment.ColumnLimit = OldColumnLimit; 16359 // Ensure function pointers don't screw up recursive alignment 16360 verifyFormat("int a(int x, void (*fp)(int y));\n" 16361 "double b();", 16362 Alignment); 16363 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 16364 // Ensure recursive alignment is broken by function braces, so that the 16365 // "a = 1" does not align with subsequent assignments inside the function 16366 // body. 16367 verifyFormat("int func(int a = 1) {\n" 16368 " int b = 2;\n" 16369 " int cc = 3;\n" 16370 "}", 16371 Alignment); 16372 verifyFormat("float something = 2000;\n" 16373 "double another = 911;\n" 16374 "int i = 1, j = 10;\n" 16375 "const int *oneMore = 1;\n" 16376 "unsigned i = 2;", 16377 Alignment); 16378 verifyFormat("int oneTwoThree = {0}; // comment\n" 16379 "unsigned oneTwo = 0; // comment", 16380 Alignment); 16381 // Make sure that scope is correctly tracked, in the absence of braces 16382 verifyFormat("for (int i = 0; i < n; i++)\n" 16383 " j = i;\n" 16384 "double x = 1;\n", 16385 Alignment); 16386 verifyFormat("if (int i = 0)\n" 16387 " j = i;\n" 16388 "double x = 1;\n", 16389 Alignment); 16390 // Ensure operator[] and operator() are comprehended 16391 verifyFormat("struct test {\n" 16392 " long long int foo();\n" 16393 " int operator[](int a);\n" 16394 " double bar();\n" 16395 "};\n", 16396 Alignment); 16397 verifyFormat("struct test {\n" 16398 " long long int foo();\n" 16399 " int operator()(int a);\n" 16400 " double bar();\n" 16401 "};\n", 16402 Alignment); 16403 16404 // PAS_Right 16405 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 16406 " int const i = 1;\n" 16407 " int *j = 2;\n" 16408 " int big = 10000;\n" 16409 "\n" 16410 " unsigned oneTwoThree = 123;\n" 16411 " int oneTwo = 12;\n" 16412 " method();\n" 16413 " float k = 2;\n" 16414 " int ll = 10000;\n" 16415 "}", 16416 format("void SomeFunction(int parameter= 0) {\n" 16417 " int const i= 1;\n" 16418 " int *j=2;\n" 16419 " int big = 10000;\n" 16420 "\n" 16421 "unsigned oneTwoThree =123;\n" 16422 "int oneTwo = 12;\n" 16423 " method();\n" 16424 "float k= 2;\n" 16425 "int ll=10000;\n" 16426 "}", 16427 Alignment)); 16428 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 16429 " int const i = 1;\n" 16430 " int **j = 2, ***k;\n" 16431 " int &k = i;\n" 16432 " int &&l = i + j;\n" 16433 " int big = 10000;\n" 16434 "\n" 16435 " unsigned oneTwoThree = 123;\n" 16436 " int oneTwo = 12;\n" 16437 " method();\n" 16438 " float k = 2;\n" 16439 " int ll = 10000;\n" 16440 "}", 16441 format("void SomeFunction(int parameter= 0) {\n" 16442 " int const i= 1;\n" 16443 " int **j=2,***k;\n" 16444 "int &k=i;\n" 16445 "int &&l=i+j;\n" 16446 " int big = 10000;\n" 16447 "\n" 16448 "unsigned oneTwoThree =123;\n" 16449 "int oneTwo = 12;\n" 16450 " method();\n" 16451 "float k= 2;\n" 16452 "int ll=10000;\n" 16453 "}", 16454 Alignment)); 16455 // variables are aligned at their name, pointers are at the right most 16456 // position 16457 verifyFormat("int *a;\n" 16458 "int **b;\n" 16459 "int ***c;\n" 16460 "int foobar;\n", 16461 Alignment); 16462 16463 // PAS_Left 16464 FormatStyle AlignmentLeft = Alignment; 16465 AlignmentLeft.PointerAlignment = FormatStyle::PAS_Left; 16466 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 16467 " int const i = 1;\n" 16468 " int* j = 2;\n" 16469 " int big = 10000;\n" 16470 "\n" 16471 " unsigned oneTwoThree = 123;\n" 16472 " int oneTwo = 12;\n" 16473 " method();\n" 16474 " float k = 2;\n" 16475 " int ll = 10000;\n" 16476 "}", 16477 format("void SomeFunction(int parameter= 0) {\n" 16478 " int const i= 1;\n" 16479 " int *j=2;\n" 16480 " int big = 10000;\n" 16481 "\n" 16482 "unsigned oneTwoThree =123;\n" 16483 "int oneTwo = 12;\n" 16484 " method();\n" 16485 "float k= 2;\n" 16486 "int ll=10000;\n" 16487 "}", 16488 AlignmentLeft)); 16489 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 16490 " int const i = 1;\n" 16491 " int** j = 2;\n" 16492 " int& k = i;\n" 16493 " int&& l = i + j;\n" 16494 " int big = 10000;\n" 16495 "\n" 16496 " unsigned oneTwoThree = 123;\n" 16497 " int oneTwo = 12;\n" 16498 " method();\n" 16499 " float k = 2;\n" 16500 " int ll = 10000;\n" 16501 "}", 16502 format("void SomeFunction(int parameter= 0) {\n" 16503 " int const i= 1;\n" 16504 " int **j=2;\n" 16505 "int &k=i;\n" 16506 "int &&l=i+j;\n" 16507 " int big = 10000;\n" 16508 "\n" 16509 "unsigned oneTwoThree =123;\n" 16510 "int oneTwo = 12;\n" 16511 " method();\n" 16512 "float k= 2;\n" 16513 "int ll=10000;\n" 16514 "}", 16515 AlignmentLeft)); 16516 // variables are aligned at their name, pointers are at the left most position 16517 verifyFormat("int* a;\n" 16518 "int** b;\n" 16519 "int*** c;\n" 16520 "int foobar;\n", 16521 AlignmentLeft); 16522 16523 // PAS_Middle 16524 FormatStyle AlignmentMiddle = Alignment; 16525 AlignmentMiddle.PointerAlignment = FormatStyle::PAS_Middle; 16526 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 16527 " int const i = 1;\n" 16528 " int * j = 2;\n" 16529 " int big = 10000;\n" 16530 "\n" 16531 " unsigned oneTwoThree = 123;\n" 16532 " int oneTwo = 12;\n" 16533 " method();\n" 16534 " float k = 2;\n" 16535 " int ll = 10000;\n" 16536 "}", 16537 format("void SomeFunction(int parameter= 0) {\n" 16538 " int const i= 1;\n" 16539 " int *j=2;\n" 16540 " int big = 10000;\n" 16541 "\n" 16542 "unsigned oneTwoThree =123;\n" 16543 "int oneTwo = 12;\n" 16544 " method();\n" 16545 "float k= 2;\n" 16546 "int ll=10000;\n" 16547 "}", 16548 AlignmentMiddle)); 16549 EXPECT_EQ("void SomeFunction(int parameter = 0) {\n" 16550 " int const i = 1;\n" 16551 " int ** j = 2, ***k;\n" 16552 " int & k = i;\n" 16553 " int && l = i + j;\n" 16554 " int big = 10000;\n" 16555 "\n" 16556 " unsigned oneTwoThree = 123;\n" 16557 " int oneTwo = 12;\n" 16558 " method();\n" 16559 " float k = 2;\n" 16560 " int ll = 10000;\n" 16561 "}", 16562 format("void SomeFunction(int parameter= 0) {\n" 16563 " int const i= 1;\n" 16564 " int **j=2,***k;\n" 16565 "int &k=i;\n" 16566 "int &&l=i+j;\n" 16567 " int big = 10000;\n" 16568 "\n" 16569 "unsigned oneTwoThree =123;\n" 16570 "int oneTwo = 12;\n" 16571 " method();\n" 16572 "float k= 2;\n" 16573 "int ll=10000;\n" 16574 "}", 16575 AlignmentMiddle)); 16576 // variables are aligned at their name, pointers are in the middle 16577 verifyFormat("int * a;\n" 16578 "int * b;\n" 16579 "int *** c;\n" 16580 "int foobar;\n", 16581 AlignmentMiddle); 16582 16583 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 16584 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; 16585 verifyFormat("#define A \\\n" 16586 " int aaaa = 12; \\\n" 16587 " float b = 23; \\\n" 16588 " const int ccc = 234; \\\n" 16589 " unsigned dddddddddd = 2345;", 16590 Alignment); 16591 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left; 16592 verifyFormat("#define A \\\n" 16593 " int aaaa = 12; \\\n" 16594 " float b = 23; \\\n" 16595 " const int ccc = 234; \\\n" 16596 " unsigned dddddddddd = 2345;", 16597 Alignment); 16598 Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right; 16599 Alignment.ColumnLimit = 30; 16600 verifyFormat("#define A \\\n" 16601 " int aaaa = 12; \\\n" 16602 " float b = 23; \\\n" 16603 " const int ccc = 234; \\\n" 16604 " int dddddddddd = 2345;", 16605 Alignment); 16606 Alignment.ColumnLimit = 80; 16607 verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int " 16608 "k = 4, int l = 5,\n" 16609 " int m = 6) {\n" 16610 " const int j = 10;\n" 16611 " otherThing = 1;\n" 16612 "}", 16613 Alignment); 16614 verifyFormat("void SomeFunction(int parameter = 0) {\n" 16615 " int const i = 1;\n" 16616 " int *j = 2;\n" 16617 " int big = 10000;\n" 16618 "}", 16619 Alignment); 16620 verifyFormat("class C {\n" 16621 "public:\n" 16622 " int i = 1;\n" 16623 " virtual void f() = 0;\n" 16624 "};", 16625 Alignment); 16626 verifyFormat("float i = 1;\n" 16627 "if (SomeType t = getSomething()) {\n" 16628 "}\n" 16629 "const unsigned j = 2;\n" 16630 "int big = 10000;", 16631 Alignment); 16632 verifyFormat("float j = 7;\n" 16633 "for (int k = 0; k < N; ++k) {\n" 16634 "}\n" 16635 "unsigned j = 2;\n" 16636 "int big = 10000;\n" 16637 "}", 16638 Alignment); 16639 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 16640 verifyFormat("float i = 1;\n" 16641 "LooooooooooongType loooooooooooooooooooooongVariable\n" 16642 " = someLooooooooooooooooongFunction();\n" 16643 "int j = 2;", 16644 Alignment); 16645 Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None; 16646 verifyFormat("int i = 1;\n" 16647 "LooooooooooongType loooooooooooooooooooooongVariable =\n" 16648 " someLooooooooooooooooongFunction();\n" 16649 "int j = 2;", 16650 Alignment); 16651 16652 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 16653 verifyFormat("auto lambda = []() {\n" 16654 " auto ii = 0;\n" 16655 " float j = 0;\n" 16656 " return 0;\n" 16657 "};\n" 16658 "int i = 0;\n" 16659 "float i2 = 0;\n" 16660 "auto v = type{\n" 16661 " i = 1, //\n" 16662 " (i = 2), //\n" 16663 " i = 3 //\n" 16664 "};", 16665 Alignment); 16666 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 16667 16668 verifyFormat( 16669 "int i = 1;\n" 16670 "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n" 16671 " loooooooooooooooooooooongParameterB);\n" 16672 "int j = 2;", 16673 Alignment); 16674 16675 // Test interactions with ColumnLimit and AlignConsecutiveAssignments: 16676 // We expect declarations and assignments to align, as long as it doesn't 16677 // exceed the column limit, starting a new alignment sequence whenever it 16678 // happens. 16679 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 16680 Alignment.ColumnLimit = 30; 16681 verifyFormat("float ii = 1;\n" 16682 "unsigned j = 2;\n" 16683 "int someVerylongVariable = 1;\n" 16684 "AnotherLongType ll = 123456;\n" 16685 "VeryVeryLongType k = 2;\n" 16686 "int myvar = 1;", 16687 Alignment); 16688 Alignment.ColumnLimit = 80; 16689 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 16690 16691 verifyFormat( 16692 "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n" 16693 " typename LongType, typename B>\n" 16694 "auto foo() {}\n", 16695 Alignment); 16696 verifyFormat("float a, b = 1;\n" 16697 "int c = 2;\n" 16698 "int dd = 3;\n", 16699 Alignment); 16700 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 16701 "float b[1][] = {{3.f}};\n", 16702 Alignment); 16703 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 16704 verifyFormat("float a, b = 1;\n" 16705 "int c = 2;\n" 16706 "int dd = 3;\n", 16707 Alignment); 16708 verifyFormat("int aa = ((1 > 2) ? 3 : 4);\n" 16709 "float b[1][] = {{3.f}};\n", 16710 Alignment); 16711 Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None; 16712 16713 Alignment.ColumnLimit = 30; 16714 Alignment.BinPackParameters = false; 16715 verifyFormat("void foo(float a,\n" 16716 " float b,\n" 16717 " int c,\n" 16718 " uint32_t *d) {\n" 16719 " int *e = 0;\n" 16720 " float f = 0;\n" 16721 " double g = 0;\n" 16722 "}\n" 16723 "void bar(ino_t a,\n" 16724 " int b,\n" 16725 " uint32_t *c,\n" 16726 " bool d) {}\n", 16727 Alignment); 16728 Alignment.BinPackParameters = true; 16729 Alignment.ColumnLimit = 80; 16730 16731 // Bug 33507 16732 Alignment.PointerAlignment = FormatStyle::PAS_Middle; 16733 verifyFormat( 16734 "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n" 16735 " static const Version verVs2017;\n" 16736 " return true;\n" 16737 "});\n", 16738 Alignment); 16739 Alignment.PointerAlignment = FormatStyle::PAS_Right; 16740 16741 // See llvm.org/PR35641 16742 Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 16743 verifyFormat("int func() { //\n" 16744 " int b;\n" 16745 " unsigned c;\n" 16746 "}", 16747 Alignment); 16748 16749 // See PR37175 16750 FormatStyle Style = getMozillaStyle(); 16751 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 16752 EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n" 16753 "foo(int a);", 16754 format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style)); 16755 16756 Alignment.PointerAlignment = FormatStyle::PAS_Left; 16757 verifyFormat("unsigned int* a;\n" 16758 "int* b;\n" 16759 "unsigned int Const* c;\n" 16760 "unsigned int const* d;\n" 16761 "unsigned int Const& e;\n" 16762 "unsigned int const& f;", 16763 Alignment); 16764 verifyFormat("Const unsigned int* c;\n" 16765 "const unsigned int* d;\n" 16766 "Const unsigned int& e;\n" 16767 "const unsigned int& f;\n" 16768 "const unsigned g;\n" 16769 "Const unsigned h;", 16770 Alignment); 16771 16772 Alignment.PointerAlignment = FormatStyle::PAS_Middle; 16773 verifyFormat("unsigned int * a;\n" 16774 "int * b;\n" 16775 "unsigned int Const * c;\n" 16776 "unsigned int const * d;\n" 16777 "unsigned int Const & e;\n" 16778 "unsigned int const & f;", 16779 Alignment); 16780 verifyFormat("Const unsigned int * c;\n" 16781 "const unsigned int * d;\n" 16782 "Const unsigned int & e;\n" 16783 "const unsigned int & f;\n" 16784 "const unsigned g;\n" 16785 "Const unsigned h;", 16786 Alignment); 16787 } 16788 16789 TEST_F(FormatTest, AlignWithLineBreaks) { 16790 auto Style = getLLVMStyleWithColumns(120); 16791 16792 EXPECT_EQ(Style.AlignConsecutiveAssignments, FormatStyle::ACS_None); 16793 EXPECT_EQ(Style.AlignConsecutiveDeclarations, FormatStyle::ACS_None); 16794 verifyFormat("void foo() {\n" 16795 " int myVar = 5;\n" 16796 " double x = 3.14;\n" 16797 " auto str = \"Hello \"\n" 16798 " \"World\";\n" 16799 " auto s = \"Hello \"\n" 16800 " \"Again\";\n" 16801 "}", 16802 Style); 16803 16804 // clang-format off 16805 verifyFormat("void foo() {\n" 16806 " const int capacityBefore = Entries.capacity();\n" 16807 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 16808 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 16809 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 16810 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 16811 "}", 16812 Style); 16813 // clang-format on 16814 16815 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 16816 verifyFormat("void foo() {\n" 16817 " int myVar = 5;\n" 16818 " double x = 3.14;\n" 16819 " auto str = \"Hello \"\n" 16820 " \"World\";\n" 16821 " auto s = \"Hello \"\n" 16822 " \"Again\";\n" 16823 "}", 16824 Style); 16825 16826 // clang-format off 16827 verifyFormat("void foo() {\n" 16828 " const int capacityBefore = Entries.capacity();\n" 16829 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 16830 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 16831 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 16832 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 16833 "}", 16834 Style); 16835 // clang-format on 16836 16837 Style.AlignConsecutiveAssignments = FormatStyle::ACS_None; 16838 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 16839 verifyFormat("void foo() {\n" 16840 " int myVar = 5;\n" 16841 " double x = 3.14;\n" 16842 " auto str = \"Hello \"\n" 16843 " \"World\";\n" 16844 " auto s = \"Hello \"\n" 16845 " \"Again\";\n" 16846 "}", 16847 Style); 16848 16849 // clang-format off 16850 verifyFormat("void foo() {\n" 16851 " const int capacityBefore = Entries.capacity();\n" 16852 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 16853 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 16854 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 16855 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 16856 "}", 16857 Style); 16858 // clang-format on 16859 16860 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 16861 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 16862 16863 verifyFormat("void foo() {\n" 16864 " int myVar = 5;\n" 16865 " double x = 3.14;\n" 16866 " auto str = \"Hello \"\n" 16867 " \"World\";\n" 16868 " auto s = \"Hello \"\n" 16869 " \"Again\";\n" 16870 "}", 16871 Style); 16872 16873 // clang-format off 16874 verifyFormat("void foo() {\n" 16875 " const int capacityBefore = Entries.capacity();\n" 16876 " const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 16877 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 16878 " const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n" 16879 " std::forward_as_tuple(id, uniqueId, name, threadCreation));\n" 16880 "}", 16881 Style); 16882 // clang-format on 16883 16884 Style = getLLVMStyleWithColumns(120); 16885 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 16886 Style.ContinuationIndentWidth = 4; 16887 Style.IndentWidth = 4; 16888 16889 // clang-format off 16890 verifyFormat("void SomeFunc() {\n" 16891 " newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 16892 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 16893 " newWatcher.maxAge = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 16894 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 16895 " newWatcher.max = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n" 16896 " seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 16897 "}", 16898 Style); 16899 // clang-format on 16900 16901 Style.BinPackArguments = false; 16902 16903 // clang-format off 16904 verifyFormat("void SomeFunc() {\n" 16905 " newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(\n" 16906 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 16907 " newWatcher.maxAge = ToLegacyTimestamp(GetMaxAge(\n" 16908 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 16909 " newWatcher.max = ToLegacyTimestamp(GetMaxAge(\n" 16910 " FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n" 16911 "}", 16912 Style); 16913 // clang-format on 16914 } 16915 16916 TEST_F(FormatTest, AlignWithInitializerPeriods) { 16917 auto Style = getLLVMStyleWithColumns(60); 16918 16919 verifyFormat("void foo1(void) {\n" 16920 " BYTE p[1] = 1;\n" 16921 " A B = {.one_foooooooooooooooo = 2,\n" 16922 " .two_fooooooooooooo = 3,\n" 16923 " .three_fooooooooooooo = 4};\n" 16924 " BYTE payload = 2;\n" 16925 "}", 16926 Style); 16927 16928 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 16929 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_None; 16930 verifyFormat("void foo2(void) {\n" 16931 " BYTE p[1] = 1;\n" 16932 " A B = {.one_foooooooooooooooo = 2,\n" 16933 " .two_fooooooooooooo = 3,\n" 16934 " .three_fooooooooooooo = 4};\n" 16935 " BYTE payload = 2;\n" 16936 "}", 16937 Style); 16938 16939 Style.AlignConsecutiveAssignments = FormatStyle::ACS_None; 16940 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 16941 verifyFormat("void foo3(void) {\n" 16942 " BYTE p[1] = 1;\n" 16943 " A B = {.one_foooooooooooooooo = 2,\n" 16944 " .two_fooooooooooooo = 3,\n" 16945 " .three_fooooooooooooo = 4};\n" 16946 " BYTE payload = 2;\n" 16947 "}", 16948 Style); 16949 16950 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 16951 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 16952 verifyFormat("void foo4(void) {\n" 16953 " BYTE p[1] = 1;\n" 16954 " A B = {.one_foooooooooooooooo = 2,\n" 16955 " .two_fooooooooooooo = 3,\n" 16956 " .three_fooooooooooooo = 4};\n" 16957 " BYTE payload = 2;\n" 16958 "}", 16959 Style); 16960 } 16961 16962 TEST_F(FormatTest, LinuxBraceBreaking) { 16963 FormatStyle LinuxBraceStyle = getLLVMStyle(); 16964 LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux; 16965 verifyFormat("namespace a\n" 16966 "{\n" 16967 "class A\n" 16968 "{\n" 16969 " void f()\n" 16970 " {\n" 16971 " if (true) {\n" 16972 " a();\n" 16973 " b();\n" 16974 " } else {\n" 16975 " a();\n" 16976 " }\n" 16977 " }\n" 16978 " void g() { return; }\n" 16979 "};\n" 16980 "struct B {\n" 16981 " int x;\n" 16982 "};\n" 16983 "} // namespace a\n", 16984 LinuxBraceStyle); 16985 verifyFormat("enum X {\n" 16986 " Y = 0,\n" 16987 "}\n", 16988 LinuxBraceStyle); 16989 verifyFormat("struct S {\n" 16990 " int Type;\n" 16991 " union {\n" 16992 " int x;\n" 16993 " double y;\n" 16994 " } Value;\n" 16995 " class C\n" 16996 " {\n" 16997 " MyFavoriteType Value;\n" 16998 " } Class;\n" 16999 "}\n", 17000 LinuxBraceStyle); 17001 } 17002 17003 TEST_F(FormatTest, MozillaBraceBreaking) { 17004 FormatStyle MozillaBraceStyle = getLLVMStyle(); 17005 MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla; 17006 MozillaBraceStyle.FixNamespaceComments = false; 17007 verifyFormat("namespace a {\n" 17008 "class A\n" 17009 "{\n" 17010 " void f()\n" 17011 " {\n" 17012 " if (true) {\n" 17013 " a();\n" 17014 " b();\n" 17015 " }\n" 17016 " }\n" 17017 " void g() { return; }\n" 17018 "};\n" 17019 "enum E\n" 17020 "{\n" 17021 " A,\n" 17022 " // foo\n" 17023 " B,\n" 17024 " C\n" 17025 "};\n" 17026 "struct B\n" 17027 "{\n" 17028 " int x;\n" 17029 "};\n" 17030 "}\n", 17031 MozillaBraceStyle); 17032 verifyFormat("struct S\n" 17033 "{\n" 17034 " int Type;\n" 17035 " union\n" 17036 " {\n" 17037 " int x;\n" 17038 " double y;\n" 17039 " } Value;\n" 17040 " class C\n" 17041 " {\n" 17042 " MyFavoriteType Value;\n" 17043 " } Class;\n" 17044 "}\n", 17045 MozillaBraceStyle); 17046 } 17047 17048 TEST_F(FormatTest, StroustrupBraceBreaking) { 17049 FormatStyle StroustrupBraceStyle = getLLVMStyle(); 17050 StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 17051 verifyFormat("namespace a {\n" 17052 "class A {\n" 17053 " void f()\n" 17054 " {\n" 17055 " if (true) {\n" 17056 " a();\n" 17057 " b();\n" 17058 " }\n" 17059 " }\n" 17060 " void g() { return; }\n" 17061 "};\n" 17062 "struct B {\n" 17063 " int x;\n" 17064 "};\n" 17065 "} // namespace a\n", 17066 StroustrupBraceStyle); 17067 17068 verifyFormat("void foo()\n" 17069 "{\n" 17070 " if (a) {\n" 17071 " a();\n" 17072 " }\n" 17073 " else {\n" 17074 " b();\n" 17075 " }\n" 17076 "}\n", 17077 StroustrupBraceStyle); 17078 17079 verifyFormat("#ifdef _DEBUG\n" 17080 "int foo(int i = 0)\n" 17081 "#else\n" 17082 "int foo(int i = 5)\n" 17083 "#endif\n" 17084 "{\n" 17085 " return i;\n" 17086 "}", 17087 StroustrupBraceStyle); 17088 17089 verifyFormat("void foo() {}\n" 17090 "void bar()\n" 17091 "#ifdef _DEBUG\n" 17092 "{\n" 17093 " foo();\n" 17094 "}\n" 17095 "#else\n" 17096 "{\n" 17097 "}\n" 17098 "#endif", 17099 StroustrupBraceStyle); 17100 17101 verifyFormat("void foobar() { int i = 5; }\n" 17102 "#ifdef _DEBUG\n" 17103 "void bar() {}\n" 17104 "#else\n" 17105 "void bar() { foobar(); }\n" 17106 "#endif", 17107 StroustrupBraceStyle); 17108 } 17109 17110 TEST_F(FormatTest, AllmanBraceBreaking) { 17111 FormatStyle AllmanBraceStyle = getLLVMStyle(); 17112 AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman; 17113 17114 EXPECT_EQ("namespace a\n" 17115 "{\n" 17116 "void f();\n" 17117 "void g();\n" 17118 "} // namespace a\n", 17119 format("namespace a\n" 17120 "{\n" 17121 "void f();\n" 17122 "void g();\n" 17123 "}\n", 17124 AllmanBraceStyle)); 17125 17126 verifyFormat("namespace a\n" 17127 "{\n" 17128 "class A\n" 17129 "{\n" 17130 " void f()\n" 17131 " {\n" 17132 " if (true)\n" 17133 " {\n" 17134 " a();\n" 17135 " b();\n" 17136 " }\n" 17137 " }\n" 17138 " void g() { return; }\n" 17139 "};\n" 17140 "struct B\n" 17141 "{\n" 17142 " int x;\n" 17143 "};\n" 17144 "union C\n" 17145 "{\n" 17146 "};\n" 17147 "} // namespace a", 17148 AllmanBraceStyle); 17149 17150 verifyFormat("void f()\n" 17151 "{\n" 17152 " if (true)\n" 17153 " {\n" 17154 " a();\n" 17155 " }\n" 17156 " else if (false)\n" 17157 " {\n" 17158 " b();\n" 17159 " }\n" 17160 " else\n" 17161 " {\n" 17162 " c();\n" 17163 " }\n" 17164 "}\n", 17165 AllmanBraceStyle); 17166 17167 verifyFormat("void f()\n" 17168 "{\n" 17169 " for (int i = 0; i < 10; ++i)\n" 17170 " {\n" 17171 " a();\n" 17172 " }\n" 17173 " while (false)\n" 17174 " {\n" 17175 " b();\n" 17176 " }\n" 17177 " do\n" 17178 " {\n" 17179 " c();\n" 17180 " } while (false)\n" 17181 "}\n", 17182 AllmanBraceStyle); 17183 17184 verifyFormat("void f(int a)\n" 17185 "{\n" 17186 " switch (a)\n" 17187 " {\n" 17188 " case 0:\n" 17189 " break;\n" 17190 " case 1:\n" 17191 " {\n" 17192 " break;\n" 17193 " }\n" 17194 " case 2:\n" 17195 " {\n" 17196 " }\n" 17197 " break;\n" 17198 " default:\n" 17199 " break;\n" 17200 " }\n" 17201 "}\n", 17202 AllmanBraceStyle); 17203 17204 verifyFormat("enum X\n" 17205 "{\n" 17206 " Y = 0,\n" 17207 "}\n", 17208 AllmanBraceStyle); 17209 verifyFormat("enum X\n" 17210 "{\n" 17211 " Y = 0\n" 17212 "}\n", 17213 AllmanBraceStyle); 17214 17215 verifyFormat("@interface BSApplicationController ()\n" 17216 "{\n" 17217 "@private\n" 17218 " id _extraIvar;\n" 17219 "}\n" 17220 "@end\n", 17221 AllmanBraceStyle); 17222 17223 verifyFormat("#ifdef _DEBUG\n" 17224 "int foo(int i = 0)\n" 17225 "#else\n" 17226 "int foo(int i = 5)\n" 17227 "#endif\n" 17228 "{\n" 17229 " return i;\n" 17230 "}", 17231 AllmanBraceStyle); 17232 17233 verifyFormat("void foo() {}\n" 17234 "void bar()\n" 17235 "#ifdef _DEBUG\n" 17236 "{\n" 17237 " foo();\n" 17238 "}\n" 17239 "#else\n" 17240 "{\n" 17241 "}\n" 17242 "#endif", 17243 AllmanBraceStyle); 17244 17245 verifyFormat("void foobar() { int i = 5; }\n" 17246 "#ifdef _DEBUG\n" 17247 "void bar() {}\n" 17248 "#else\n" 17249 "void bar() { foobar(); }\n" 17250 "#endif", 17251 AllmanBraceStyle); 17252 17253 EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine, 17254 FormatStyle::SLS_All); 17255 17256 verifyFormat("[](int i) { return i + 2; };\n" 17257 "[](int i, int j)\n" 17258 "{\n" 17259 " auto x = i + j;\n" 17260 " auto y = i * j;\n" 17261 " return x ^ y;\n" 17262 "};\n" 17263 "void foo()\n" 17264 "{\n" 17265 " auto shortLambda = [](int i) { return i + 2; };\n" 17266 " auto longLambda = [](int i, int j)\n" 17267 " {\n" 17268 " auto x = i + j;\n" 17269 " auto y = i * j;\n" 17270 " return x ^ y;\n" 17271 " };\n" 17272 "}", 17273 AllmanBraceStyle); 17274 17275 AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 17276 17277 verifyFormat("[](int i)\n" 17278 "{\n" 17279 " return i + 2;\n" 17280 "};\n" 17281 "[](int i, int j)\n" 17282 "{\n" 17283 " auto x = i + j;\n" 17284 " auto y = i * j;\n" 17285 " return x ^ y;\n" 17286 "};\n" 17287 "void foo()\n" 17288 "{\n" 17289 " auto shortLambda = [](int i)\n" 17290 " {\n" 17291 " return i + 2;\n" 17292 " };\n" 17293 " auto longLambda = [](int i, int j)\n" 17294 " {\n" 17295 " auto x = i + j;\n" 17296 " auto y = i * j;\n" 17297 " return x ^ y;\n" 17298 " };\n" 17299 "}", 17300 AllmanBraceStyle); 17301 17302 // Reset 17303 AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All; 17304 17305 // This shouldn't affect ObjC blocks.. 17306 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n" 17307 " // ...\n" 17308 " int i;\n" 17309 "}];", 17310 AllmanBraceStyle); 17311 verifyFormat("void (^block)(void) = ^{\n" 17312 " // ...\n" 17313 " int i;\n" 17314 "};", 17315 AllmanBraceStyle); 17316 // .. or dict literals. 17317 verifyFormat("void f()\n" 17318 "{\n" 17319 " // ...\n" 17320 " [object someMethod:@{@\"a\" : @\"b\"}];\n" 17321 "}", 17322 AllmanBraceStyle); 17323 verifyFormat("void f()\n" 17324 "{\n" 17325 " // ...\n" 17326 " [object someMethod:@{a : @\"b\"}];\n" 17327 "}", 17328 AllmanBraceStyle); 17329 verifyFormat("int f()\n" 17330 "{ // comment\n" 17331 " return 42;\n" 17332 "}", 17333 AllmanBraceStyle); 17334 17335 AllmanBraceStyle.ColumnLimit = 19; 17336 verifyFormat("void f() { int i; }", AllmanBraceStyle); 17337 AllmanBraceStyle.ColumnLimit = 18; 17338 verifyFormat("void f()\n" 17339 "{\n" 17340 " int i;\n" 17341 "}", 17342 AllmanBraceStyle); 17343 AllmanBraceStyle.ColumnLimit = 80; 17344 17345 FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle; 17346 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = 17347 FormatStyle::SIS_WithoutElse; 17348 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true; 17349 verifyFormat("void f(bool b)\n" 17350 "{\n" 17351 " if (b)\n" 17352 " {\n" 17353 " return;\n" 17354 " }\n" 17355 "}\n", 17356 BreakBeforeBraceShortIfs); 17357 verifyFormat("void f(bool b)\n" 17358 "{\n" 17359 " if constexpr (b)\n" 17360 " {\n" 17361 " return;\n" 17362 " }\n" 17363 "}\n", 17364 BreakBeforeBraceShortIfs); 17365 verifyFormat("void f(bool b)\n" 17366 "{\n" 17367 " if CONSTEXPR (b)\n" 17368 " {\n" 17369 " return;\n" 17370 " }\n" 17371 "}\n", 17372 BreakBeforeBraceShortIfs); 17373 verifyFormat("void f(bool b)\n" 17374 "{\n" 17375 " if (b) return;\n" 17376 "}\n", 17377 BreakBeforeBraceShortIfs); 17378 verifyFormat("void f(bool b)\n" 17379 "{\n" 17380 " if constexpr (b) return;\n" 17381 "}\n", 17382 BreakBeforeBraceShortIfs); 17383 verifyFormat("void f(bool b)\n" 17384 "{\n" 17385 " if CONSTEXPR (b) return;\n" 17386 "}\n", 17387 BreakBeforeBraceShortIfs); 17388 verifyFormat("void f(bool b)\n" 17389 "{\n" 17390 " while (b)\n" 17391 " {\n" 17392 " return;\n" 17393 " }\n" 17394 "}\n", 17395 BreakBeforeBraceShortIfs); 17396 } 17397 17398 TEST_F(FormatTest, WhitesmithsBraceBreaking) { 17399 FormatStyle WhitesmithsBraceStyle = getLLVMStyle(); 17400 WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 17401 17402 // Make a few changes to the style for testing purposes 17403 WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine = 17404 FormatStyle::SFS_Empty; 17405 WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 17406 WhitesmithsBraceStyle.ColumnLimit = 0; 17407 17408 // FIXME: this test case can't decide whether there should be a blank line 17409 // after the ~D() line or not. It adds one if one doesn't exist in the test 17410 // and it removes the line if one exists. 17411 /* 17412 verifyFormat("class A;\n" 17413 "namespace B\n" 17414 " {\n" 17415 "class C;\n" 17416 "// Comment\n" 17417 "class D\n" 17418 " {\n" 17419 "public:\n" 17420 " D();\n" 17421 " ~D() {}\n" 17422 "private:\n" 17423 " enum E\n" 17424 " {\n" 17425 " F\n" 17426 " }\n" 17427 " };\n" 17428 " } // namespace B\n", 17429 WhitesmithsBraceStyle); 17430 */ 17431 17432 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None; 17433 verifyFormat("namespace a\n" 17434 " {\n" 17435 "class A\n" 17436 " {\n" 17437 " void f()\n" 17438 " {\n" 17439 " if (true)\n" 17440 " {\n" 17441 " a();\n" 17442 " b();\n" 17443 " }\n" 17444 " }\n" 17445 " void g()\n" 17446 " {\n" 17447 " return;\n" 17448 " }\n" 17449 " };\n" 17450 "struct B\n" 17451 " {\n" 17452 " int x;\n" 17453 " };\n" 17454 " } // namespace a", 17455 WhitesmithsBraceStyle); 17456 17457 verifyFormat("namespace a\n" 17458 " {\n" 17459 "namespace b\n" 17460 " {\n" 17461 "class A\n" 17462 " {\n" 17463 " void f()\n" 17464 " {\n" 17465 " if (true)\n" 17466 " {\n" 17467 " a();\n" 17468 " b();\n" 17469 " }\n" 17470 " }\n" 17471 " void g()\n" 17472 " {\n" 17473 " return;\n" 17474 " }\n" 17475 " };\n" 17476 "struct B\n" 17477 " {\n" 17478 " int x;\n" 17479 " };\n" 17480 " } // namespace b\n" 17481 " } // namespace a", 17482 WhitesmithsBraceStyle); 17483 17484 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner; 17485 verifyFormat("namespace a\n" 17486 " {\n" 17487 "namespace b\n" 17488 " {\n" 17489 " class A\n" 17490 " {\n" 17491 " void f()\n" 17492 " {\n" 17493 " if (true)\n" 17494 " {\n" 17495 " a();\n" 17496 " b();\n" 17497 " }\n" 17498 " }\n" 17499 " void g()\n" 17500 " {\n" 17501 " return;\n" 17502 " }\n" 17503 " };\n" 17504 " struct B\n" 17505 " {\n" 17506 " int x;\n" 17507 " };\n" 17508 " } // namespace b\n" 17509 " } // namespace a", 17510 WhitesmithsBraceStyle); 17511 17512 WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All; 17513 verifyFormat("namespace a\n" 17514 " {\n" 17515 " namespace b\n" 17516 " {\n" 17517 " class A\n" 17518 " {\n" 17519 " void f()\n" 17520 " {\n" 17521 " if (true)\n" 17522 " {\n" 17523 " a();\n" 17524 " b();\n" 17525 " }\n" 17526 " }\n" 17527 " void g()\n" 17528 " {\n" 17529 " return;\n" 17530 " }\n" 17531 " };\n" 17532 " struct B\n" 17533 " {\n" 17534 " int x;\n" 17535 " };\n" 17536 " } // namespace b\n" 17537 " } // namespace a", 17538 WhitesmithsBraceStyle); 17539 17540 verifyFormat("void f()\n" 17541 " {\n" 17542 " if (true)\n" 17543 " {\n" 17544 " a();\n" 17545 " }\n" 17546 " else if (false)\n" 17547 " {\n" 17548 " b();\n" 17549 " }\n" 17550 " else\n" 17551 " {\n" 17552 " c();\n" 17553 " }\n" 17554 " }\n", 17555 WhitesmithsBraceStyle); 17556 17557 verifyFormat("void f()\n" 17558 " {\n" 17559 " for (int i = 0; i < 10; ++i)\n" 17560 " {\n" 17561 " a();\n" 17562 " }\n" 17563 " while (false)\n" 17564 " {\n" 17565 " b();\n" 17566 " }\n" 17567 " do\n" 17568 " {\n" 17569 " c();\n" 17570 " } while (false)\n" 17571 " }\n", 17572 WhitesmithsBraceStyle); 17573 17574 WhitesmithsBraceStyle.IndentCaseLabels = true; 17575 verifyFormat("void switchTest1(int a)\n" 17576 " {\n" 17577 " switch (a)\n" 17578 " {\n" 17579 " case 2:\n" 17580 " {\n" 17581 " }\n" 17582 " break;\n" 17583 " }\n" 17584 " }\n", 17585 WhitesmithsBraceStyle); 17586 17587 verifyFormat("void switchTest2(int a)\n" 17588 " {\n" 17589 " switch (a)\n" 17590 " {\n" 17591 " case 0:\n" 17592 " break;\n" 17593 " case 1:\n" 17594 " {\n" 17595 " break;\n" 17596 " }\n" 17597 " case 2:\n" 17598 " {\n" 17599 " }\n" 17600 " break;\n" 17601 " default:\n" 17602 " break;\n" 17603 " }\n" 17604 " }\n", 17605 WhitesmithsBraceStyle); 17606 17607 verifyFormat("void switchTest3(int a)\n" 17608 " {\n" 17609 " switch (a)\n" 17610 " {\n" 17611 " case 0:\n" 17612 " {\n" 17613 " foo(x);\n" 17614 " }\n" 17615 " break;\n" 17616 " default:\n" 17617 " {\n" 17618 " foo(1);\n" 17619 " }\n" 17620 " break;\n" 17621 " }\n" 17622 " }\n", 17623 WhitesmithsBraceStyle); 17624 17625 WhitesmithsBraceStyle.IndentCaseLabels = false; 17626 17627 verifyFormat("void switchTest4(int a)\n" 17628 " {\n" 17629 " switch (a)\n" 17630 " {\n" 17631 " case 2:\n" 17632 " {\n" 17633 " }\n" 17634 " break;\n" 17635 " }\n" 17636 " }\n", 17637 WhitesmithsBraceStyle); 17638 17639 verifyFormat("void switchTest5(int a)\n" 17640 " {\n" 17641 " switch (a)\n" 17642 " {\n" 17643 " case 0:\n" 17644 " break;\n" 17645 " case 1:\n" 17646 " {\n" 17647 " foo();\n" 17648 " break;\n" 17649 " }\n" 17650 " case 2:\n" 17651 " {\n" 17652 " }\n" 17653 " break;\n" 17654 " default:\n" 17655 " break;\n" 17656 " }\n" 17657 " }\n", 17658 WhitesmithsBraceStyle); 17659 17660 verifyFormat("void switchTest6(int a)\n" 17661 " {\n" 17662 " switch (a)\n" 17663 " {\n" 17664 " case 0:\n" 17665 " {\n" 17666 " foo(x);\n" 17667 " }\n" 17668 " break;\n" 17669 " default:\n" 17670 " {\n" 17671 " foo(1);\n" 17672 " }\n" 17673 " break;\n" 17674 " }\n" 17675 " }\n", 17676 WhitesmithsBraceStyle); 17677 17678 verifyFormat("enum X\n" 17679 " {\n" 17680 " Y = 0, // testing\n" 17681 " }\n", 17682 WhitesmithsBraceStyle); 17683 17684 verifyFormat("enum X\n" 17685 " {\n" 17686 " Y = 0\n" 17687 " }\n", 17688 WhitesmithsBraceStyle); 17689 verifyFormat("enum X\n" 17690 " {\n" 17691 " Y = 0,\n" 17692 " Z = 1\n" 17693 " };\n", 17694 WhitesmithsBraceStyle); 17695 17696 verifyFormat("@interface BSApplicationController ()\n" 17697 " {\n" 17698 "@private\n" 17699 " id _extraIvar;\n" 17700 " }\n" 17701 "@end\n", 17702 WhitesmithsBraceStyle); 17703 17704 verifyFormat("#ifdef _DEBUG\n" 17705 "int foo(int i = 0)\n" 17706 "#else\n" 17707 "int foo(int i = 5)\n" 17708 "#endif\n" 17709 " {\n" 17710 " return i;\n" 17711 " }", 17712 WhitesmithsBraceStyle); 17713 17714 verifyFormat("void foo() {}\n" 17715 "void bar()\n" 17716 "#ifdef _DEBUG\n" 17717 " {\n" 17718 " foo();\n" 17719 " }\n" 17720 "#else\n" 17721 " {\n" 17722 " }\n" 17723 "#endif", 17724 WhitesmithsBraceStyle); 17725 17726 verifyFormat("void foobar()\n" 17727 " {\n" 17728 " int i = 5;\n" 17729 " }\n" 17730 "#ifdef _DEBUG\n" 17731 "void bar()\n" 17732 " {\n" 17733 " }\n" 17734 "#else\n" 17735 "void bar()\n" 17736 " {\n" 17737 " foobar();\n" 17738 " }\n" 17739 "#endif", 17740 WhitesmithsBraceStyle); 17741 17742 // This shouldn't affect ObjC blocks.. 17743 verifyFormat("[self doSomeThingWithACompletionHandler:^{\n" 17744 " // ...\n" 17745 " int i;\n" 17746 "}];", 17747 WhitesmithsBraceStyle); 17748 verifyFormat("void (^block)(void) = ^{\n" 17749 " // ...\n" 17750 " int i;\n" 17751 "};", 17752 WhitesmithsBraceStyle); 17753 // .. or dict literals. 17754 verifyFormat("void f()\n" 17755 " {\n" 17756 " [object someMethod:@{@\"a\" : @\"b\"}];\n" 17757 " }", 17758 WhitesmithsBraceStyle); 17759 17760 verifyFormat("int f()\n" 17761 " { // comment\n" 17762 " return 42;\n" 17763 " }", 17764 WhitesmithsBraceStyle); 17765 17766 FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle; 17767 BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = 17768 FormatStyle::SIS_OnlyFirstIf; 17769 BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true; 17770 verifyFormat("void f(bool b)\n" 17771 " {\n" 17772 " if (b)\n" 17773 " {\n" 17774 " return;\n" 17775 " }\n" 17776 " }\n", 17777 BreakBeforeBraceShortIfs); 17778 verifyFormat("void f(bool b)\n" 17779 " {\n" 17780 " if (b) return;\n" 17781 " }\n", 17782 BreakBeforeBraceShortIfs); 17783 verifyFormat("void f(bool b)\n" 17784 " {\n" 17785 " while (b)\n" 17786 " {\n" 17787 " return;\n" 17788 " }\n" 17789 " }\n", 17790 BreakBeforeBraceShortIfs); 17791 } 17792 17793 TEST_F(FormatTest, GNUBraceBreaking) { 17794 FormatStyle GNUBraceStyle = getLLVMStyle(); 17795 GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU; 17796 verifyFormat("namespace a\n" 17797 "{\n" 17798 "class A\n" 17799 "{\n" 17800 " void f()\n" 17801 " {\n" 17802 " int a;\n" 17803 " {\n" 17804 " int b;\n" 17805 " }\n" 17806 " if (true)\n" 17807 " {\n" 17808 " a();\n" 17809 " b();\n" 17810 " }\n" 17811 " }\n" 17812 " void g() { return; }\n" 17813 "}\n" 17814 "} // namespace a", 17815 GNUBraceStyle); 17816 17817 verifyFormat("void f()\n" 17818 "{\n" 17819 " if (true)\n" 17820 " {\n" 17821 " a();\n" 17822 " }\n" 17823 " else if (false)\n" 17824 " {\n" 17825 " b();\n" 17826 " }\n" 17827 " else\n" 17828 " {\n" 17829 " c();\n" 17830 " }\n" 17831 "}\n", 17832 GNUBraceStyle); 17833 17834 verifyFormat("void f()\n" 17835 "{\n" 17836 " for (int i = 0; i < 10; ++i)\n" 17837 " {\n" 17838 " a();\n" 17839 " }\n" 17840 " while (false)\n" 17841 " {\n" 17842 " b();\n" 17843 " }\n" 17844 " do\n" 17845 " {\n" 17846 " c();\n" 17847 " }\n" 17848 " while (false);\n" 17849 "}\n", 17850 GNUBraceStyle); 17851 17852 verifyFormat("void f(int a)\n" 17853 "{\n" 17854 " switch (a)\n" 17855 " {\n" 17856 " case 0:\n" 17857 " break;\n" 17858 " case 1:\n" 17859 " {\n" 17860 " break;\n" 17861 " }\n" 17862 " case 2:\n" 17863 " {\n" 17864 " }\n" 17865 " break;\n" 17866 " default:\n" 17867 " break;\n" 17868 " }\n" 17869 "}\n", 17870 GNUBraceStyle); 17871 17872 verifyFormat("enum X\n" 17873 "{\n" 17874 " Y = 0,\n" 17875 "}\n", 17876 GNUBraceStyle); 17877 17878 verifyFormat("@interface BSApplicationController ()\n" 17879 "{\n" 17880 "@private\n" 17881 " id _extraIvar;\n" 17882 "}\n" 17883 "@end\n", 17884 GNUBraceStyle); 17885 17886 verifyFormat("#ifdef _DEBUG\n" 17887 "int foo(int i = 0)\n" 17888 "#else\n" 17889 "int foo(int i = 5)\n" 17890 "#endif\n" 17891 "{\n" 17892 " return i;\n" 17893 "}", 17894 GNUBraceStyle); 17895 17896 verifyFormat("void foo() {}\n" 17897 "void bar()\n" 17898 "#ifdef _DEBUG\n" 17899 "{\n" 17900 " foo();\n" 17901 "}\n" 17902 "#else\n" 17903 "{\n" 17904 "}\n" 17905 "#endif", 17906 GNUBraceStyle); 17907 17908 verifyFormat("void foobar() { int i = 5; }\n" 17909 "#ifdef _DEBUG\n" 17910 "void bar() {}\n" 17911 "#else\n" 17912 "void bar() { foobar(); }\n" 17913 "#endif", 17914 GNUBraceStyle); 17915 } 17916 17917 TEST_F(FormatTest, WebKitBraceBreaking) { 17918 FormatStyle WebKitBraceStyle = getLLVMStyle(); 17919 WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit; 17920 WebKitBraceStyle.FixNamespaceComments = false; 17921 verifyFormat("namespace a {\n" 17922 "class A {\n" 17923 " void f()\n" 17924 " {\n" 17925 " if (true) {\n" 17926 " a();\n" 17927 " b();\n" 17928 " }\n" 17929 " }\n" 17930 " void g() { return; }\n" 17931 "};\n" 17932 "enum E {\n" 17933 " A,\n" 17934 " // foo\n" 17935 " B,\n" 17936 " C\n" 17937 "};\n" 17938 "struct B {\n" 17939 " int x;\n" 17940 "};\n" 17941 "}\n", 17942 WebKitBraceStyle); 17943 verifyFormat("struct S {\n" 17944 " int Type;\n" 17945 " union {\n" 17946 " int x;\n" 17947 " double y;\n" 17948 " } Value;\n" 17949 " class C {\n" 17950 " MyFavoriteType Value;\n" 17951 " } Class;\n" 17952 "};\n", 17953 WebKitBraceStyle); 17954 } 17955 17956 TEST_F(FormatTest, CatchExceptionReferenceBinding) { 17957 verifyFormat("void f() {\n" 17958 " try {\n" 17959 " } catch (const Exception &e) {\n" 17960 " }\n" 17961 "}\n", 17962 getLLVMStyle()); 17963 } 17964 17965 TEST_F(FormatTest, CatchAlignArrayOfStructuresRightAlignment) { 17966 auto Style = getLLVMStyle(); 17967 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 17968 Style.AlignConsecutiveAssignments = 17969 FormatStyle::AlignConsecutiveStyle::ACS_Consecutive; 17970 Style.AlignConsecutiveDeclarations = 17971 FormatStyle::AlignConsecutiveStyle::ACS_Consecutive; 17972 verifyFormat("struct test demo[] = {\n" 17973 " {56, 23, \"hello\"},\n" 17974 " {-1, 93463, \"world\"},\n" 17975 " { 7, 5, \"!!\"}\n" 17976 "};\n", 17977 Style); 17978 17979 verifyFormat("struct test demo[] = {\n" 17980 " {56, 23, \"hello\"}, // first line\n" 17981 " {-1, 93463, \"world\"}, // second line\n" 17982 " { 7, 5, \"!!\"} // third line\n" 17983 "};\n", 17984 Style); 17985 17986 verifyFormat("struct test demo[4] = {\n" 17987 " { 56, 23, 21, \"oh\"}, // first line\n" 17988 " { -1, 93463, 22, \"my\"}, // second line\n" 17989 " { 7, 5, 1, \"goodness\"} // third line\n" 17990 " {234, 5, 1, \"gracious\"} // fourth line\n" 17991 "};\n", 17992 Style); 17993 17994 verifyFormat("struct test demo[3] = {\n" 17995 " {56, 23, \"hello\"},\n" 17996 " {-1, 93463, \"world\"},\n" 17997 " { 7, 5, \"!!\"}\n" 17998 "};\n", 17999 Style); 18000 18001 verifyFormat("struct test demo[3] = {\n" 18002 " {int{56}, 23, \"hello\"},\n" 18003 " {int{-1}, 93463, \"world\"},\n" 18004 " { int{7}, 5, \"!!\"}\n" 18005 "};\n", 18006 Style); 18007 18008 verifyFormat("struct test demo[] = {\n" 18009 " {56, 23, \"hello\"},\n" 18010 " {-1, 93463, \"world\"},\n" 18011 " { 7, 5, \"!!\"},\n" 18012 "};\n", 18013 Style); 18014 18015 verifyFormat("test demo[] = {\n" 18016 " {56, 23, \"hello\"},\n" 18017 " {-1, 93463, \"world\"},\n" 18018 " { 7, 5, \"!!\"},\n" 18019 "};\n", 18020 Style); 18021 18022 verifyFormat("demo = std::array<struct test, 3>{\n" 18023 " test{56, 23, \"hello\"},\n" 18024 " test{-1, 93463, \"world\"},\n" 18025 " test{ 7, 5, \"!!\"},\n" 18026 "};\n", 18027 Style); 18028 18029 verifyFormat("test demo[] = {\n" 18030 " {56, 23, \"hello\"},\n" 18031 "#if X\n" 18032 " {-1, 93463, \"world\"},\n" 18033 "#endif\n" 18034 " { 7, 5, \"!!\"}\n" 18035 "};\n", 18036 Style); 18037 18038 verifyFormat( 18039 "test demo[] = {\n" 18040 " { 7, 23,\n" 18041 " \"hello world i am a very long line that really, in any\"\n" 18042 " \"just world, ought to be split over multiple lines\"},\n" 18043 " {-1, 93463, \"world\"},\n" 18044 " {56, 5, \"!!\"}\n" 18045 "};\n", 18046 Style); 18047 18048 verifyFormat("return GradForUnaryCwise(g, {\n" 18049 " {{\"sign\"}, \"Sign\", " 18050 " {\"x\", \"dy\"}},\n" 18051 " { {\"dx\"}, \"Mul\", {\"dy\"" 18052 ", \"sign\"}},\n" 18053 "});\n", 18054 Style); 18055 18056 Style.ColumnLimit = 0; 18057 EXPECT_EQ( 18058 "test demo[] = {\n" 18059 " {56, 23, \"hello world i am a very long line that really, " 18060 "in any just world, ought to be split over multiple lines\"},\n" 18061 " {-1, 93463, " 18062 " \"world\"},\n" 18063 " { 7, 5, " 18064 " \"!!\"},\n" 18065 "};", 18066 format("test demo[] = {{56, 23, \"hello world i am a very long line " 18067 "that really, in any just world, ought to be split over multiple " 18068 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 18069 Style)); 18070 18071 Style.ColumnLimit = 80; 18072 verifyFormat("test demo[] = {\n" 18073 " {56, 23, /* a comment */ \"hello\"},\n" 18074 " {-1, 93463, \"world\"},\n" 18075 " { 7, 5, \"!!\"}\n" 18076 "};\n", 18077 Style); 18078 18079 verifyFormat("test demo[] = {\n" 18080 " {56, 23, \"hello\"},\n" 18081 " {-1, 93463, \"world\" /* comment here */},\n" 18082 " { 7, 5, \"!!\"}\n" 18083 "};\n", 18084 Style); 18085 18086 verifyFormat("test demo[] = {\n" 18087 " {56, /* a comment */ 23, \"hello\"},\n" 18088 " {-1, 93463, \"world\"},\n" 18089 " { 7, 5, \"!!\"}\n" 18090 "};\n", 18091 Style); 18092 18093 Style.ColumnLimit = 20; 18094 EXPECT_EQ( 18095 "demo = std::array<\n" 18096 " struct test, 3>{\n" 18097 " test{\n" 18098 " 56, 23,\n" 18099 " \"hello \"\n" 18100 " \"world i \"\n" 18101 " \"am a very \"\n" 18102 " \"long line \"\n" 18103 " \"that \"\n" 18104 " \"really, \"\n" 18105 " \"in any \"\n" 18106 " \"just \"\n" 18107 " \"world, \"\n" 18108 " \"ought to \"\n" 18109 " \"be split \"\n" 18110 " \"over \"\n" 18111 " \"multiple \"\n" 18112 " \"lines\"},\n" 18113 " test{-1, 93463,\n" 18114 " \"world\"},\n" 18115 " test{ 7, 5,\n" 18116 " \"!!\" },\n" 18117 "};", 18118 format("demo = std::array<struct test, 3>{test{56, 23, \"hello world " 18119 "i am a very long line that really, in any just world, ought " 18120 "to be split over multiple lines\"},test{-1, 93463, \"world\"}," 18121 "test{7, 5, \"!!\"},};", 18122 Style)); 18123 // This caused a core dump by enabling Alignment in the LLVMStyle globally 18124 Style = getLLVMStyleWithColumns(50); 18125 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 18126 verifyFormat("static A x = {\n" 18127 " {{init1, init2, init3, init4},\n" 18128 " {init1, init2, init3, init4}}\n" 18129 "};", 18130 Style); 18131 Style.ColumnLimit = 100; 18132 EXPECT_EQ( 18133 "test demo[] = {\n" 18134 " {56, 23,\n" 18135 " \"hello world i am a very long line that really, in any just world" 18136 ", ought to be split over \"\n" 18137 " \"multiple lines\" },\n" 18138 " {-1, 93463, \"world\"},\n" 18139 " { 7, 5, \"!!\"},\n" 18140 "};", 18141 format("test demo[] = {{56, 23, \"hello world i am a very long line " 18142 "that really, in any just world, ought to be split over multiple " 18143 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 18144 Style)); 18145 18146 Style = getLLVMStyleWithColumns(50); 18147 Style.AlignArrayOfStructures = FormatStyle::AIAS_Right; 18148 Style.AlignConsecutiveAssignments = 18149 FormatStyle::AlignConsecutiveStyle::ACS_Consecutive; 18150 Style.AlignConsecutiveDeclarations = 18151 FormatStyle::AlignConsecutiveStyle::ACS_Consecutive; 18152 verifyFormat("struct test demo[] = {\n" 18153 " {56, 23, \"hello\"},\n" 18154 " {-1, 93463, \"world\"},\n" 18155 " { 7, 5, \"!!\"}\n" 18156 "};\n" 18157 "static A x = {\n" 18158 " {{init1, init2, init3, init4},\n" 18159 " {init1, init2, init3, init4}}\n" 18160 "};", 18161 Style); 18162 Style.ColumnLimit = 100; 18163 Style.AlignConsecutiveAssignments = 18164 FormatStyle::AlignConsecutiveStyle::ACS_AcrossComments; 18165 Style.AlignConsecutiveDeclarations = 18166 FormatStyle::AlignConsecutiveStyle::ACS_AcrossComments; 18167 verifyFormat("struct test demo[] = {\n" 18168 " {56, 23, \"hello\"},\n" 18169 " {-1, 93463, \"world\"},\n" 18170 " { 7, 5, \"!!\"}\n" 18171 "};\n" 18172 "struct test demo[4] = {\n" 18173 " { 56, 23, 21, \"oh\"}, // first line\n" 18174 " { -1, 93463, 22, \"my\"}, // second line\n" 18175 " { 7, 5, 1, \"goodness\"} // third line\n" 18176 " {234, 5, 1, \"gracious\"} // fourth line\n" 18177 "};\n", 18178 Style); 18179 EXPECT_EQ( 18180 "test demo[] = {\n" 18181 " {56,\n" 18182 " \"hello world i am a very long line that really, in any just world" 18183 ", ought to be split over \"\n" 18184 " \"multiple lines\", 23},\n" 18185 " {-1, \"world\", 93463},\n" 18186 " { 7, \"!!\", 5},\n" 18187 "};", 18188 format("test demo[] = {{56, \"hello world i am a very long line " 18189 "that really, in any just world, ought to be split over multiple " 18190 "lines\", 23},{-1, \"world\", 93463},{7, \"!!\", 5},};", 18191 Style)); 18192 } 18193 18194 TEST_F(FormatTest, CatchAlignArrayOfStructuresLeftAlignment) { 18195 auto Style = getLLVMStyle(); 18196 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 18197 /* FIXME: This case gets misformatted. 18198 verifyFormat("auto foo = Items{\n" 18199 " Section{0, bar(), },\n" 18200 " Section{1, boo() }\n" 18201 "};\n", 18202 Style); 18203 */ 18204 verifyFormat("auto foo = Items{\n" 18205 " Section{\n" 18206 " 0, bar(),\n" 18207 " }\n" 18208 "};\n", 18209 Style); 18210 verifyFormat("struct test demo[] = {\n" 18211 " {56, 23, \"hello\"},\n" 18212 " {-1, 93463, \"world\"},\n" 18213 " {7, 5, \"!!\" }\n" 18214 "};\n", 18215 Style); 18216 verifyFormat("struct test demo[] = {\n" 18217 " {56, 23, \"hello\"}, // first line\n" 18218 " {-1, 93463, \"world\"}, // second line\n" 18219 " {7, 5, \"!!\" } // third line\n" 18220 "};\n", 18221 Style); 18222 verifyFormat("struct test demo[4] = {\n" 18223 " {56, 23, 21, \"oh\" }, // first line\n" 18224 " {-1, 93463, 22, \"my\" }, // second line\n" 18225 " {7, 5, 1, \"goodness\"} // third line\n" 18226 " {234, 5, 1, \"gracious\"} // fourth line\n" 18227 "};\n", 18228 Style); 18229 verifyFormat("struct test demo[3] = {\n" 18230 " {56, 23, \"hello\"},\n" 18231 " {-1, 93463, \"world\"},\n" 18232 " {7, 5, \"!!\" }\n" 18233 "};\n", 18234 Style); 18235 18236 verifyFormat("struct test demo[3] = {\n" 18237 " {int{56}, 23, \"hello\"},\n" 18238 " {int{-1}, 93463, \"world\"},\n" 18239 " {int{7}, 5, \"!!\" }\n" 18240 "};\n", 18241 Style); 18242 verifyFormat("struct test demo[] = {\n" 18243 " {56, 23, \"hello\"},\n" 18244 " {-1, 93463, \"world\"},\n" 18245 " {7, 5, \"!!\" },\n" 18246 "};\n", 18247 Style); 18248 verifyFormat("test demo[] = {\n" 18249 " {56, 23, \"hello\"},\n" 18250 " {-1, 93463, \"world\"},\n" 18251 " {7, 5, \"!!\" },\n" 18252 "};\n", 18253 Style); 18254 verifyFormat("demo = std::array<struct test, 3>{\n" 18255 " test{56, 23, \"hello\"},\n" 18256 " test{-1, 93463, \"world\"},\n" 18257 " test{7, 5, \"!!\" },\n" 18258 "};\n", 18259 Style); 18260 verifyFormat("test demo[] = {\n" 18261 " {56, 23, \"hello\"},\n" 18262 "#if X\n" 18263 " {-1, 93463, \"world\"},\n" 18264 "#endif\n" 18265 " {7, 5, \"!!\" }\n" 18266 "};\n", 18267 Style); 18268 verifyFormat( 18269 "test demo[] = {\n" 18270 " {7, 23,\n" 18271 " \"hello world i am a very long line that really, in any\"\n" 18272 " \"just world, ought to be split over multiple lines\"},\n" 18273 " {-1, 93463, \"world\" },\n" 18274 " {56, 5, \"!!\" }\n" 18275 "};\n", 18276 Style); 18277 18278 verifyFormat("return GradForUnaryCwise(g, {\n" 18279 " {{\"sign\"}, \"Sign\", {\"x\", " 18280 "\"dy\"} },\n" 18281 " {{\"dx\"}, \"Mul\", " 18282 "{\"dy\", \"sign\"}},\n" 18283 "});\n", 18284 Style); 18285 18286 Style.ColumnLimit = 0; 18287 EXPECT_EQ( 18288 "test demo[] = {\n" 18289 " {56, 23, \"hello world i am a very long line that really, in any " 18290 "just world, ought to be split over multiple lines\"},\n" 18291 " {-1, 93463, \"world\" " 18292 " },\n" 18293 " {7, 5, \"!!\" " 18294 " },\n" 18295 "};", 18296 format("test demo[] = {{56, 23, \"hello world i am a very long line " 18297 "that really, in any just world, ought to be split over multiple " 18298 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 18299 Style)); 18300 18301 Style.ColumnLimit = 80; 18302 verifyFormat("test demo[] = {\n" 18303 " {56, 23, /* a comment */ \"hello\"},\n" 18304 " {-1, 93463, \"world\" },\n" 18305 " {7, 5, \"!!\" }\n" 18306 "};\n", 18307 Style); 18308 18309 verifyFormat("test demo[] = {\n" 18310 " {56, 23, \"hello\" },\n" 18311 " {-1, 93463, \"world\" /* comment here */},\n" 18312 " {7, 5, \"!!\" }\n" 18313 "};\n", 18314 Style); 18315 18316 verifyFormat("test demo[] = {\n" 18317 " {56, /* a comment */ 23, \"hello\"},\n" 18318 " {-1, 93463, \"world\"},\n" 18319 " {7, 5, \"!!\" }\n" 18320 "};\n", 18321 Style); 18322 18323 Style.ColumnLimit = 20; 18324 EXPECT_EQ( 18325 "demo = std::array<\n" 18326 " struct test, 3>{\n" 18327 " test{\n" 18328 " 56, 23,\n" 18329 " \"hello \"\n" 18330 " \"world i \"\n" 18331 " \"am a very \"\n" 18332 " \"long line \"\n" 18333 " \"that \"\n" 18334 " \"really, \"\n" 18335 " \"in any \"\n" 18336 " \"just \"\n" 18337 " \"world, \"\n" 18338 " \"ought to \"\n" 18339 " \"be split \"\n" 18340 " \"over \"\n" 18341 " \"multiple \"\n" 18342 " \"lines\"},\n" 18343 " test{-1, 93463,\n" 18344 " \"world\"},\n" 18345 " test{7, 5,\n" 18346 " \"!!\" },\n" 18347 "};", 18348 format("demo = std::array<struct test, 3>{test{56, 23, \"hello world " 18349 "i am a very long line that really, in any just world, ought " 18350 "to be split over multiple lines\"},test{-1, 93463, \"world\"}," 18351 "test{7, 5, \"!!\"},};", 18352 Style)); 18353 18354 // This caused a core dump by enabling Alignment in the LLVMStyle globally 18355 Style = getLLVMStyleWithColumns(50); 18356 Style.AlignArrayOfStructures = FormatStyle::AIAS_Left; 18357 verifyFormat("static A x = {\n" 18358 " {{init1, init2, init3, init4},\n" 18359 " {init1, init2, init3, init4}}\n" 18360 "};", 18361 Style); 18362 Style.ColumnLimit = 100; 18363 EXPECT_EQ( 18364 "test demo[] = {\n" 18365 " {56, 23,\n" 18366 " \"hello world i am a very long line that really, in any just world" 18367 ", ought to be split over \"\n" 18368 " \"multiple lines\" },\n" 18369 " {-1, 93463, \"world\"},\n" 18370 " {7, 5, \"!!\" },\n" 18371 "};", 18372 format("test demo[] = {{56, 23, \"hello world i am a very long line " 18373 "that really, in any just world, ought to be split over multiple " 18374 "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};", 18375 Style)); 18376 } 18377 18378 TEST_F(FormatTest, UnderstandsPragmas) { 18379 verifyFormat("#pragma omp reduction(| : var)"); 18380 verifyFormat("#pragma omp reduction(+ : var)"); 18381 18382 EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string " 18383 "(including parentheses).", 18384 format("#pragma mark Any non-hyphenated or hyphenated string " 18385 "(including parentheses).")); 18386 } 18387 18388 TEST_F(FormatTest, UnderstandPragmaOption) { 18389 verifyFormat("#pragma option -C -A"); 18390 18391 EXPECT_EQ("#pragma option -C -A", format("#pragma option -C -A")); 18392 } 18393 18394 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) { 18395 FormatStyle Style = getLLVMStyle(); 18396 Style.ColumnLimit = 20; 18397 18398 // See PR41213 18399 EXPECT_EQ("/*\n" 18400 " *\t9012345\n" 18401 " * /8901\n" 18402 " */", 18403 format("/*\n" 18404 " *\t9012345 /8901\n" 18405 " */", 18406 Style)); 18407 EXPECT_EQ("/*\n" 18408 " *345678\n" 18409 " *\t/8901\n" 18410 " */", 18411 format("/*\n" 18412 " *345678\t/8901\n" 18413 " */", 18414 Style)); 18415 18416 verifyFormat("int a; // the\n" 18417 " // comment", 18418 Style); 18419 EXPECT_EQ("int a; /* first line\n" 18420 " * second\n" 18421 " * line third\n" 18422 " * line\n" 18423 " */", 18424 format("int a; /* first line\n" 18425 " * second\n" 18426 " * line third\n" 18427 " * line\n" 18428 " */", 18429 Style)); 18430 EXPECT_EQ("int a; // first line\n" 18431 " // second\n" 18432 " // line third\n" 18433 " // line", 18434 format("int a; // first line\n" 18435 " // second line\n" 18436 " // third line", 18437 Style)); 18438 18439 Style.PenaltyExcessCharacter = 90; 18440 verifyFormat("int a; // the comment", Style); 18441 EXPECT_EQ("int a; // the comment\n" 18442 " // aaa", 18443 format("int a; // the comment aaa", Style)); 18444 EXPECT_EQ("int a; /* first line\n" 18445 " * second line\n" 18446 " * third line\n" 18447 " */", 18448 format("int a; /* first line\n" 18449 " * second line\n" 18450 " * third line\n" 18451 " */", 18452 Style)); 18453 EXPECT_EQ("int a; // first line\n" 18454 " // second line\n" 18455 " // third line", 18456 format("int a; // first line\n" 18457 " // second line\n" 18458 " // third line", 18459 Style)); 18460 // FIXME: Investigate why this is not getting the same layout as the test 18461 // above. 18462 EXPECT_EQ("int a; /* first line\n" 18463 " * second line\n" 18464 " * third line\n" 18465 " */", 18466 format("int a; /* first line second line third line" 18467 "\n*/", 18468 Style)); 18469 18470 EXPECT_EQ("// foo bar baz bazfoo\n" 18471 "// foo bar foo bar\n", 18472 format("// foo bar baz bazfoo\n" 18473 "// foo bar foo bar\n", 18474 Style)); 18475 EXPECT_EQ("// foo bar baz bazfoo\n" 18476 "// foo bar foo bar\n", 18477 format("// foo bar baz bazfoo\n" 18478 "// foo bar foo bar\n", 18479 Style)); 18480 18481 // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the 18482 // next one. 18483 EXPECT_EQ("// foo bar baz bazfoo\n" 18484 "// bar foo bar\n", 18485 format("// foo bar baz bazfoo bar\n" 18486 "// foo bar\n", 18487 Style)); 18488 18489 EXPECT_EQ("// foo bar baz bazfoo\n" 18490 "// foo bar baz bazfoo\n" 18491 "// bar foo bar\n", 18492 format("// foo bar baz bazfoo\n" 18493 "// foo bar baz bazfoo bar\n" 18494 "// foo bar\n", 18495 Style)); 18496 18497 EXPECT_EQ("// foo bar baz bazfoo\n" 18498 "// foo bar baz bazfoo\n" 18499 "// bar foo bar\n", 18500 format("// foo bar baz bazfoo\n" 18501 "// foo bar baz bazfoo bar\n" 18502 "// foo bar\n", 18503 Style)); 18504 18505 // Make sure we do not keep protruding characters if strict mode reflow is 18506 // cheaper than keeping protruding characters. 18507 Style.ColumnLimit = 21; 18508 EXPECT_EQ( 18509 "// foo foo foo foo\n" 18510 "// foo foo foo foo\n" 18511 "// foo foo foo foo\n", 18512 format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style)); 18513 18514 EXPECT_EQ("int a = /* long block\n" 18515 " comment */\n" 18516 " 42;", 18517 format("int a = /* long block comment */ 42;", Style)); 18518 } 18519 18520 #define EXPECT_ALL_STYLES_EQUAL(Styles) \ 18521 for (size_t i = 1; i < Styles.size(); ++i) \ 18522 EXPECT_EQ(Styles[0], Styles[i]) \ 18523 << "Style #" << i << " of " << Styles.size() << " differs from Style #0" 18524 18525 TEST_F(FormatTest, GetsPredefinedStyleByName) { 18526 SmallVector<FormatStyle, 3> Styles; 18527 Styles.resize(3); 18528 18529 Styles[0] = getLLVMStyle(); 18530 EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1])); 18531 EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2])); 18532 EXPECT_ALL_STYLES_EQUAL(Styles); 18533 18534 Styles[0] = getGoogleStyle(); 18535 EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1])); 18536 EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2])); 18537 EXPECT_ALL_STYLES_EQUAL(Styles); 18538 18539 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript); 18540 EXPECT_TRUE( 18541 getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1])); 18542 EXPECT_TRUE( 18543 getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2])); 18544 EXPECT_ALL_STYLES_EQUAL(Styles); 18545 18546 Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp); 18547 EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1])); 18548 EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2])); 18549 EXPECT_ALL_STYLES_EQUAL(Styles); 18550 18551 Styles[0] = getMozillaStyle(); 18552 EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1])); 18553 EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2])); 18554 EXPECT_ALL_STYLES_EQUAL(Styles); 18555 18556 Styles[0] = getWebKitStyle(); 18557 EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1])); 18558 EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2])); 18559 EXPECT_ALL_STYLES_EQUAL(Styles); 18560 18561 Styles[0] = getGNUStyle(); 18562 EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1])); 18563 EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2])); 18564 EXPECT_ALL_STYLES_EQUAL(Styles); 18565 18566 EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0])); 18567 } 18568 18569 TEST_F(FormatTest, GetsCorrectBasedOnStyle) { 18570 SmallVector<FormatStyle, 8> Styles; 18571 Styles.resize(2); 18572 18573 Styles[0] = getGoogleStyle(); 18574 Styles[1] = getLLVMStyle(); 18575 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value()); 18576 EXPECT_ALL_STYLES_EQUAL(Styles); 18577 18578 Styles.resize(5); 18579 Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript); 18580 Styles[1] = getLLVMStyle(); 18581 Styles[1].Language = FormatStyle::LK_JavaScript; 18582 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value()); 18583 18584 Styles[2] = getLLVMStyle(); 18585 Styles[2].Language = FormatStyle::LK_JavaScript; 18586 EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n" 18587 "BasedOnStyle: Google", 18588 &Styles[2]) 18589 .value()); 18590 18591 Styles[3] = getLLVMStyle(); 18592 Styles[3].Language = FormatStyle::LK_JavaScript; 18593 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n" 18594 "Language: JavaScript", 18595 &Styles[3]) 18596 .value()); 18597 18598 Styles[4] = getLLVMStyle(); 18599 Styles[4].Language = FormatStyle::LK_JavaScript; 18600 EXPECT_EQ(0, parseConfiguration("---\n" 18601 "BasedOnStyle: LLVM\n" 18602 "IndentWidth: 123\n" 18603 "---\n" 18604 "BasedOnStyle: Google\n" 18605 "Language: JavaScript", 18606 &Styles[4]) 18607 .value()); 18608 EXPECT_ALL_STYLES_EQUAL(Styles); 18609 } 18610 18611 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME) \ 18612 Style.FIELD = false; \ 18613 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value()); \ 18614 EXPECT_TRUE(Style.FIELD); \ 18615 EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value()); \ 18616 EXPECT_FALSE(Style.FIELD); 18617 18618 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD) 18619 18620 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME) \ 18621 Style.STRUCT.FIELD = false; \ 18622 EXPECT_EQ(0, \ 18623 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": true", &Style) \ 18624 .value()); \ 18625 EXPECT_TRUE(Style.STRUCT.FIELD); \ 18626 EXPECT_EQ(0, \ 18627 parseConfiguration(#STRUCT ":\n " CONFIG_NAME ": false", &Style) \ 18628 .value()); \ 18629 EXPECT_FALSE(Style.STRUCT.FIELD); 18630 18631 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD) \ 18632 CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD) 18633 18634 #define CHECK_PARSE(TEXT, FIELD, VALUE) \ 18635 EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!"; \ 18636 EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value()); \ 18637 EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!" 18638 18639 TEST_F(FormatTest, ParsesConfigurationBools) { 18640 FormatStyle Style = {}; 18641 Style.Language = FormatStyle::LK_Cpp; 18642 CHECK_PARSE_BOOL(AlignTrailingComments); 18643 CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine); 18644 CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine); 18645 CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine); 18646 CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine); 18647 CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine); 18648 CHECK_PARSE_BOOL(BinPackArguments); 18649 CHECK_PARSE_BOOL(BinPackParameters); 18650 CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations); 18651 CHECK_PARSE_BOOL(BreakBeforeConceptDeclarations); 18652 CHECK_PARSE_BOOL(BreakBeforeTernaryOperators); 18653 CHECK_PARSE_BOOL(BreakStringLiterals); 18654 CHECK_PARSE_BOOL(CompactNamespaces); 18655 CHECK_PARSE_BOOL(DeriveLineEnding); 18656 CHECK_PARSE_BOOL(DerivePointerAlignment); 18657 CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding"); 18658 CHECK_PARSE_BOOL(DisableFormat); 18659 CHECK_PARSE_BOOL(IndentAccessModifiers); 18660 CHECK_PARSE_BOOL(IndentCaseLabels); 18661 CHECK_PARSE_BOOL(IndentCaseBlocks); 18662 CHECK_PARSE_BOOL(IndentGotoLabels); 18663 CHECK_PARSE_BOOL(IndentRequires); 18664 CHECK_PARSE_BOOL(IndentWrappedFunctionNames); 18665 CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks); 18666 CHECK_PARSE_BOOL(ObjCSpaceAfterProperty); 18667 CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList); 18668 CHECK_PARSE_BOOL(Cpp11BracedListStyle); 18669 CHECK_PARSE_BOOL(ReflowComments); 18670 CHECK_PARSE_BOOL(SortUsingDeclarations); 18671 CHECK_PARSE_BOOL(SpacesInParentheses); 18672 CHECK_PARSE_BOOL(SpacesInSquareBrackets); 18673 CHECK_PARSE_BOOL(SpacesInConditionalStatement); 18674 CHECK_PARSE_BOOL(SpaceInEmptyBlock); 18675 CHECK_PARSE_BOOL(SpaceInEmptyParentheses); 18676 CHECK_PARSE_BOOL(SpacesInContainerLiterals); 18677 CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses); 18678 CHECK_PARSE_BOOL(SpaceAfterCStyleCast); 18679 CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword); 18680 CHECK_PARSE_BOOL(SpaceAfterLogicalNot); 18681 CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators); 18682 CHECK_PARSE_BOOL(SpaceBeforeCaseColon); 18683 CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList); 18684 CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon); 18685 CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon); 18686 CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon); 18687 CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets); 18688 CHECK_PARSE_BOOL(UseCRLF); 18689 18690 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel); 18691 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass); 18692 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum); 18693 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction); 18694 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace); 18695 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration); 18696 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct); 18697 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion); 18698 CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock); 18699 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch); 18700 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse); 18701 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody); 18702 CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile); 18703 CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces); 18704 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction); 18705 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord); 18706 CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace); 18707 } 18708 18709 #undef CHECK_PARSE_BOOL 18710 18711 TEST_F(FormatTest, ParsesConfiguration) { 18712 FormatStyle Style = {}; 18713 Style.Language = FormatStyle::LK_Cpp; 18714 CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234); 18715 CHECK_PARSE("ConstructorInitializerIndentWidth: 1234", 18716 ConstructorInitializerIndentWidth, 1234u); 18717 CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u); 18718 CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u); 18719 CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u); 18720 CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u); 18721 CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234", 18722 PenaltyBreakBeforeFirstCallParameter, 1234u); 18723 CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234", 18724 PenaltyBreakTemplateDeclaration, 1234u); 18725 CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u); 18726 CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234", 18727 PenaltyReturnTypeOnItsOwnLine, 1234u); 18728 CHECK_PARSE("SpacesBeforeTrailingComments: 1234", 18729 SpacesBeforeTrailingComments, 1234u); 18730 CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u); 18731 CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u); 18732 CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$"); 18733 18734 Style.QualifierAlignment = FormatStyle::QAS_Right; 18735 CHECK_PARSE("QualifierAlignment: Leave", QualifierAlignment, 18736 FormatStyle::QAS_Leave); 18737 CHECK_PARSE("QualifierAlignment: Right", QualifierAlignment, 18738 FormatStyle::QAS_Right); 18739 CHECK_PARSE("QualifierAlignment: Left", QualifierAlignment, 18740 FormatStyle::QAS_Left); 18741 CHECK_PARSE("QualifierAlignment: Custom", QualifierAlignment, 18742 FormatStyle::QAS_Custom); 18743 18744 Style.QualifierOrder.clear(); 18745 CHECK_PARSE("QualifierOrder: [ const, volatile, type ]", QualifierOrder, 18746 std::vector<std::string>({"const", "volatile", "type"})); 18747 Style.QualifierOrder.clear(); 18748 CHECK_PARSE("QualifierOrder: [const, type]", QualifierOrder, 18749 std::vector<std::string>({"const", "type"})); 18750 Style.QualifierOrder.clear(); 18751 CHECK_PARSE("QualifierOrder: [volatile, type]", QualifierOrder, 18752 std::vector<std::string>({"volatile", "type"})); 18753 18754 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 18755 CHECK_PARSE("AlignConsecutiveAssignments: None", AlignConsecutiveAssignments, 18756 FormatStyle::ACS_None); 18757 CHECK_PARSE("AlignConsecutiveAssignments: Consecutive", 18758 AlignConsecutiveAssignments, FormatStyle::ACS_Consecutive); 18759 CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLines", 18760 AlignConsecutiveAssignments, FormatStyle::ACS_AcrossEmptyLines); 18761 CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLinesAndComments", 18762 AlignConsecutiveAssignments, 18763 FormatStyle::ACS_AcrossEmptyLinesAndComments); 18764 // For backwards compability, false / true should still parse 18765 CHECK_PARSE("AlignConsecutiveAssignments: false", AlignConsecutiveAssignments, 18766 FormatStyle::ACS_None); 18767 CHECK_PARSE("AlignConsecutiveAssignments: true", AlignConsecutiveAssignments, 18768 FormatStyle::ACS_Consecutive); 18769 18770 Style.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive; 18771 CHECK_PARSE("AlignConsecutiveBitFields: None", AlignConsecutiveBitFields, 18772 FormatStyle::ACS_None); 18773 CHECK_PARSE("AlignConsecutiveBitFields: Consecutive", 18774 AlignConsecutiveBitFields, FormatStyle::ACS_Consecutive); 18775 CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLines", 18776 AlignConsecutiveBitFields, FormatStyle::ACS_AcrossEmptyLines); 18777 CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLinesAndComments", 18778 AlignConsecutiveBitFields, 18779 FormatStyle::ACS_AcrossEmptyLinesAndComments); 18780 // For backwards compability, false / true should still parse 18781 CHECK_PARSE("AlignConsecutiveBitFields: false", AlignConsecutiveBitFields, 18782 FormatStyle::ACS_None); 18783 CHECK_PARSE("AlignConsecutiveBitFields: true", AlignConsecutiveBitFields, 18784 FormatStyle::ACS_Consecutive); 18785 18786 Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive; 18787 CHECK_PARSE("AlignConsecutiveMacros: None", AlignConsecutiveMacros, 18788 FormatStyle::ACS_None); 18789 CHECK_PARSE("AlignConsecutiveMacros: Consecutive", AlignConsecutiveMacros, 18790 FormatStyle::ACS_Consecutive); 18791 CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLines", 18792 AlignConsecutiveMacros, FormatStyle::ACS_AcrossEmptyLines); 18793 CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLinesAndComments", 18794 AlignConsecutiveMacros, 18795 FormatStyle::ACS_AcrossEmptyLinesAndComments); 18796 // For backwards compability, false / true should still parse 18797 CHECK_PARSE("AlignConsecutiveMacros: false", AlignConsecutiveMacros, 18798 FormatStyle::ACS_None); 18799 CHECK_PARSE("AlignConsecutiveMacros: true", AlignConsecutiveMacros, 18800 FormatStyle::ACS_Consecutive); 18801 18802 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 18803 CHECK_PARSE("AlignConsecutiveDeclarations: None", 18804 AlignConsecutiveDeclarations, FormatStyle::ACS_None); 18805 CHECK_PARSE("AlignConsecutiveDeclarations: Consecutive", 18806 AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive); 18807 CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLines", 18808 AlignConsecutiveDeclarations, FormatStyle::ACS_AcrossEmptyLines); 18809 CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLinesAndComments", 18810 AlignConsecutiveDeclarations, 18811 FormatStyle::ACS_AcrossEmptyLinesAndComments); 18812 // For backwards compability, false / true should still parse 18813 CHECK_PARSE("AlignConsecutiveDeclarations: false", 18814 AlignConsecutiveDeclarations, FormatStyle::ACS_None); 18815 CHECK_PARSE("AlignConsecutiveDeclarations: true", 18816 AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive); 18817 18818 Style.PointerAlignment = FormatStyle::PAS_Middle; 18819 CHECK_PARSE("PointerAlignment: Left", PointerAlignment, 18820 FormatStyle::PAS_Left); 18821 CHECK_PARSE("PointerAlignment: Right", PointerAlignment, 18822 FormatStyle::PAS_Right); 18823 CHECK_PARSE("PointerAlignment: Middle", PointerAlignment, 18824 FormatStyle::PAS_Middle); 18825 Style.ReferenceAlignment = FormatStyle::RAS_Middle; 18826 CHECK_PARSE("ReferenceAlignment: Pointer", ReferenceAlignment, 18827 FormatStyle::RAS_Pointer); 18828 CHECK_PARSE("ReferenceAlignment: Left", ReferenceAlignment, 18829 FormatStyle::RAS_Left); 18830 CHECK_PARSE("ReferenceAlignment: Right", ReferenceAlignment, 18831 FormatStyle::RAS_Right); 18832 CHECK_PARSE("ReferenceAlignment: Middle", ReferenceAlignment, 18833 FormatStyle::RAS_Middle); 18834 // For backward compatibility: 18835 CHECK_PARSE("PointerBindsToType: Left", PointerAlignment, 18836 FormatStyle::PAS_Left); 18837 CHECK_PARSE("PointerBindsToType: Right", PointerAlignment, 18838 FormatStyle::PAS_Right); 18839 CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment, 18840 FormatStyle::PAS_Middle); 18841 18842 Style.Standard = FormatStyle::LS_Auto; 18843 CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03); 18844 CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11); 18845 CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14); 18846 CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17); 18847 CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20); 18848 CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto); 18849 CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest); 18850 // Legacy aliases: 18851 CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03); 18852 CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest); 18853 CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03); 18854 CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11); 18855 18856 Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; 18857 CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment", 18858 BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment); 18859 CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators, 18860 FormatStyle::BOS_None); 18861 CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators, 18862 FormatStyle::BOS_All); 18863 // For backward compatibility: 18864 CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators, 18865 FormatStyle::BOS_None); 18866 CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators, 18867 FormatStyle::BOS_All); 18868 18869 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 18870 CHECK_PARSE("BreakConstructorInitializers: BeforeComma", 18871 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma); 18872 CHECK_PARSE("BreakConstructorInitializers: AfterColon", 18873 BreakConstructorInitializers, FormatStyle::BCIS_AfterColon); 18874 CHECK_PARSE("BreakConstructorInitializers: BeforeColon", 18875 BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon); 18876 // For backward compatibility: 18877 CHECK_PARSE("BreakConstructorInitializersBeforeComma: true", 18878 BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma); 18879 18880 Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon; 18881 CHECK_PARSE("BreakInheritanceList: AfterComma", BreakInheritanceList, 18882 FormatStyle::BILS_AfterComma); 18883 CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList, 18884 FormatStyle::BILS_BeforeComma); 18885 CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList, 18886 FormatStyle::BILS_AfterColon); 18887 CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList, 18888 FormatStyle::BILS_BeforeColon); 18889 // For backward compatibility: 18890 CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList, 18891 FormatStyle::BILS_BeforeComma); 18892 18893 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 18894 CHECK_PARSE("PackConstructorInitializers: Never", PackConstructorInitializers, 18895 FormatStyle::PCIS_Never); 18896 CHECK_PARSE("PackConstructorInitializers: BinPack", 18897 PackConstructorInitializers, FormatStyle::PCIS_BinPack); 18898 CHECK_PARSE("PackConstructorInitializers: CurrentLine", 18899 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 18900 CHECK_PARSE("PackConstructorInitializers: NextLine", 18901 PackConstructorInitializers, FormatStyle::PCIS_NextLine); 18902 // For backward compatibility: 18903 CHECK_PARSE("BasedOnStyle: Google\n" 18904 "ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 18905 "AllowAllConstructorInitializersOnNextLine: false", 18906 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 18907 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 18908 CHECK_PARSE("BasedOnStyle: Google\n" 18909 "ConstructorInitializerAllOnOneLineOrOnePerLine: false", 18910 PackConstructorInitializers, FormatStyle::PCIS_BinPack); 18911 CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 18912 "AllowAllConstructorInitializersOnNextLine: true", 18913 PackConstructorInitializers, FormatStyle::PCIS_NextLine); 18914 Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack; 18915 CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n" 18916 "AllowAllConstructorInitializersOnNextLine: false", 18917 PackConstructorInitializers, FormatStyle::PCIS_CurrentLine); 18918 18919 Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock; 18920 CHECK_PARSE("EmptyLineBeforeAccessModifier: Never", 18921 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never); 18922 CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave", 18923 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave); 18924 CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock", 18925 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock); 18926 CHECK_PARSE("EmptyLineBeforeAccessModifier: Always", 18927 EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always); 18928 18929 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 18930 CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket, 18931 FormatStyle::BAS_Align); 18932 CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket, 18933 FormatStyle::BAS_DontAlign); 18934 CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket, 18935 FormatStyle::BAS_AlwaysBreak); 18936 // For backward compatibility: 18937 CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket, 18938 FormatStyle::BAS_DontAlign); 18939 CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket, 18940 FormatStyle::BAS_Align); 18941 18942 Style.AlignEscapedNewlines = FormatStyle::ENAS_Left; 18943 CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines, 18944 FormatStyle::ENAS_DontAlign); 18945 CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines, 18946 FormatStyle::ENAS_Left); 18947 CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines, 18948 FormatStyle::ENAS_Right); 18949 // For backward compatibility: 18950 CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines, 18951 FormatStyle::ENAS_Left); 18952 CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines, 18953 FormatStyle::ENAS_Right); 18954 18955 Style.AlignOperands = FormatStyle::OAS_Align; 18956 CHECK_PARSE("AlignOperands: DontAlign", AlignOperands, 18957 FormatStyle::OAS_DontAlign); 18958 CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align); 18959 CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands, 18960 FormatStyle::OAS_AlignAfterOperator); 18961 // For backward compatibility: 18962 CHECK_PARSE("AlignOperands: false", AlignOperands, 18963 FormatStyle::OAS_DontAlign); 18964 CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align); 18965 18966 Style.UseTab = FormatStyle::UT_ForIndentation; 18967 CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never); 18968 CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation); 18969 CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always); 18970 CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab, 18971 FormatStyle::UT_ForContinuationAndIndentation); 18972 CHECK_PARSE("UseTab: AlignWithSpaces", UseTab, 18973 FormatStyle::UT_AlignWithSpaces); 18974 // For backward compatibility: 18975 CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never); 18976 CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always); 18977 18978 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 18979 CHECK_PARSE("AllowShortBlocksOnASingleLine: Never", 18980 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 18981 CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty", 18982 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty); 18983 CHECK_PARSE("AllowShortBlocksOnASingleLine: Always", 18984 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always); 18985 // For backward compatibility: 18986 CHECK_PARSE("AllowShortBlocksOnASingleLine: false", 18987 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never); 18988 CHECK_PARSE("AllowShortBlocksOnASingleLine: true", 18989 AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always); 18990 18991 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; 18992 CHECK_PARSE("AllowShortFunctionsOnASingleLine: None", 18993 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None); 18994 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline", 18995 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline); 18996 CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty", 18997 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty); 18998 CHECK_PARSE("AllowShortFunctionsOnASingleLine: All", 18999 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All); 19000 // For backward compatibility: 19001 CHECK_PARSE("AllowShortFunctionsOnASingleLine: false", 19002 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None); 19003 CHECK_PARSE("AllowShortFunctionsOnASingleLine: true", 19004 AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All); 19005 19006 Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both; 19007 CHECK_PARSE("SpaceAroundPointerQualifiers: Default", 19008 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default); 19009 CHECK_PARSE("SpaceAroundPointerQualifiers: Before", 19010 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before); 19011 CHECK_PARSE("SpaceAroundPointerQualifiers: After", 19012 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After); 19013 CHECK_PARSE("SpaceAroundPointerQualifiers: Both", 19014 SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both); 19015 19016 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 19017 CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens, 19018 FormatStyle::SBPO_Never); 19019 CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens, 19020 FormatStyle::SBPO_Always); 19021 CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens, 19022 FormatStyle::SBPO_ControlStatements); 19023 CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptControlMacros", 19024 SpaceBeforeParens, 19025 FormatStyle::SBPO_ControlStatementsExceptControlMacros); 19026 CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens, 19027 FormatStyle::SBPO_NonEmptyParentheses); 19028 CHECK_PARSE("SpaceBeforeParens: Custom", SpaceBeforeParens, 19029 FormatStyle::SBPO_Custom); 19030 // For backward compatibility: 19031 CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens, 19032 FormatStyle::SBPO_Never); 19033 CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens, 19034 FormatStyle::SBPO_ControlStatements); 19035 CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptForEachMacros", 19036 SpaceBeforeParens, 19037 FormatStyle::SBPO_ControlStatementsExceptControlMacros); 19038 19039 Style.ColumnLimit = 123; 19040 FormatStyle BaseStyle = getLLVMStyle(); 19041 CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit); 19042 CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u); 19043 19044 Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; 19045 CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces, 19046 FormatStyle::BS_Attach); 19047 CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces, 19048 FormatStyle::BS_Linux); 19049 CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces, 19050 FormatStyle::BS_Mozilla); 19051 CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces, 19052 FormatStyle::BS_Stroustrup); 19053 CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces, 19054 FormatStyle::BS_Allman); 19055 CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces, 19056 FormatStyle::BS_Whitesmiths); 19057 CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU); 19058 CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces, 19059 FormatStyle::BS_WebKit); 19060 CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces, 19061 FormatStyle::BS_Custom); 19062 19063 Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never; 19064 CHECK_PARSE("BraceWrapping:\n" 19065 " AfterControlStatement: MultiLine", 19066 BraceWrapping.AfterControlStatement, 19067 FormatStyle::BWACS_MultiLine); 19068 CHECK_PARSE("BraceWrapping:\n" 19069 " AfterControlStatement: Always", 19070 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always); 19071 CHECK_PARSE("BraceWrapping:\n" 19072 " AfterControlStatement: Never", 19073 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never); 19074 // For backward compatibility: 19075 CHECK_PARSE("BraceWrapping:\n" 19076 " AfterControlStatement: true", 19077 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always); 19078 CHECK_PARSE("BraceWrapping:\n" 19079 " AfterControlStatement: false", 19080 BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never); 19081 19082 Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; 19083 CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType, 19084 FormatStyle::RTBS_None); 19085 CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType, 19086 FormatStyle::RTBS_All); 19087 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel", 19088 AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel); 19089 CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions", 19090 AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions); 19091 CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions", 19092 AlwaysBreakAfterReturnType, 19093 FormatStyle::RTBS_TopLevelDefinitions); 19094 19095 Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 19096 CHECK_PARSE("AlwaysBreakTemplateDeclarations: No", 19097 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No); 19098 CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine", 19099 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine); 19100 CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes", 19101 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes); 19102 CHECK_PARSE("AlwaysBreakTemplateDeclarations: false", 19103 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine); 19104 CHECK_PARSE("AlwaysBreakTemplateDeclarations: true", 19105 AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes); 19106 19107 Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All; 19108 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None", 19109 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None); 19110 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All", 19111 AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All); 19112 CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel", 19113 AlwaysBreakAfterDefinitionReturnType, 19114 FormatStyle::DRTBS_TopLevel); 19115 19116 Style.NamespaceIndentation = FormatStyle::NI_All; 19117 CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation, 19118 FormatStyle::NI_None); 19119 CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation, 19120 FormatStyle::NI_Inner); 19121 CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation, 19122 FormatStyle::NI_All); 19123 19124 Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_OnlyFirstIf; 19125 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never", 19126 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never); 19127 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse", 19128 AllowShortIfStatementsOnASingleLine, 19129 FormatStyle::SIS_WithoutElse); 19130 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: OnlyFirstIf", 19131 AllowShortIfStatementsOnASingleLine, 19132 FormatStyle::SIS_OnlyFirstIf); 19133 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: AllIfsAndElse", 19134 AllowShortIfStatementsOnASingleLine, 19135 FormatStyle::SIS_AllIfsAndElse); 19136 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always", 19137 AllowShortIfStatementsOnASingleLine, 19138 FormatStyle::SIS_OnlyFirstIf); 19139 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false", 19140 AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never); 19141 CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true", 19142 AllowShortIfStatementsOnASingleLine, 19143 FormatStyle::SIS_WithoutElse); 19144 19145 Style.IndentExternBlock = FormatStyle::IEBS_NoIndent; 19146 CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock, 19147 FormatStyle::IEBS_AfterExternBlock); 19148 CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock, 19149 FormatStyle::IEBS_Indent); 19150 CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock, 19151 FormatStyle::IEBS_NoIndent); 19152 CHECK_PARSE("IndentExternBlock: true", IndentExternBlock, 19153 FormatStyle::IEBS_Indent); 19154 CHECK_PARSE("IndentExternBlock: false", IndentExternBlock, 19155 FormatStyle::IEBS_NoIndent); 19156 19157 Style.BitFieldColonSpacing = FormatStyle::BFCS_None; 19158 CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing, 19159 FormatStyle::BFCS_Both); 19160 CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing, 19161 FormatStyle::BFCS_None); 19162 CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing, 19163 FormatStyle::BFCS_Before); 19164 CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing, 19165 FormatStyle::BFCS_After); 19166 19167 Style.SortJavaStaticImport = FormatStyle::SJSIO_Before; 19168 CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport, 19169 FormatStyle::SJSIO_After); 19170 CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport, 19171 FormatStyle::SJSIO_Before); 19172 19173 // FIXME: This is required because parsing a configuration simply overwrites 19174 // the first N elements of the list instead of resetting it. 19175 Style.ForEachMacros.clear(); 19176 std::vector<std::string> BoostForeach; 19177 BoostForeach.push_back("BOOST_FOREACH"); 19178 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach); 19179 std::vector<std::string> BoostAndQForeach; 19180 BoostAndQForeach.push_back("BOOST_FOREACH"); 19181 BoostAndQForeach.push_back("Q_FOREACH"); 19182 CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros, 19183 BoostAndQForeach); 19184 19185 Style.IfMacros.clear(); 19186 std::vector<std::string> CustomIfs; 19187 CustomIfs.push_back("MYIF"); 19188 CHECK_PARSE("IfMacros: [MYIF]", IfMacros, CustomIfs); 19189 19190 Style.AttributeMacros.clear(); 19191 CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros, 19192 std::vector<std::string>{"__capability"}); 19193 CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros, 19194 std::vector<std::string>({"attr1", "attr2"})); 19195 19196 Style.StatementAttributeLikeMacros.clear(); 19197 CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]", 19198 StatementAttributeLikeMacros, 19199 std::vector<std::string>({"emit", "Q_EMIT"})); 19200 19201 Style.StatementMacros.clear(); 19202 CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros, 19203 std::vector<std::string>{"QUNUSED"}); 19204 CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros, 19205 std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"})); 19206 19207 Style.NamespaceMacros.clear(); 19208 CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros, 19209 std::vector<std::string>{"TESTSUITE"}); 19210 CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros, 19211 std::vector<std::string>({"TESTSUITE", "SUITE"})); 19212 19213 Style.WhitespaceSensitiveMacros.clear(); 19214 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]", 19215 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"}); 19216 CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]", 19217 WhitespaceSensitiveMacros, 19218 std::vector<std::string>({"STRINGIZE", "ASSERT"})); 19219 Style.WhitespaceSensitiveMacros.clear(); 19220 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']", 19221 WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"}); 19222 CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']", 19223 WhitespaceSensitiveMacros, 19224 std::vector<std::string>({"STRINGIZE", "ASSERT"})); 19225 19226 Style.IncludeStyle.IncludeCategories.clear(); 19227 std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = { 19228 {"abc/.*", 2, 0, false}, {".*", 1, 0, true}}; 19229 CHECK_PARSE("IncludeCategories:\n" 19230 " - Regex: abc/.*\n" 19231 " Priority: 2\n" 19232 " - Regex: .*\n" 19233 " Priority: 1\n" 19234 " CaseSensitive: true\n", 19235 IncludeStyle.IncludeCategories, ExpectedCategories); 19236 CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex, 19237 "abc$"); 19238 CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'", 19239 IncludeStyle.IncludeIsMainSourceRegex, "abc$"); 19240 19241 Style.SortIncludes = FormatStyle::SI_Never; 19242 CHECK_PARSE("SortIncludes: true", SortIncludes, 19243 FormatStyle::SI_CaseSensitive); 19244 CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never); 19245 CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes, 19246 FormatStyle::SI_CaseInsensitive); 19247 CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes, 19248 FormatStyle::SI_CaseSensitive); 19249 CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never); 19250 19251 Style.RawStringFormats.clear(); 19252 std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = { 19253 { 19254 FormatStyle::LK_TextProto, 19255 {"pb", "proto"}, 19256 {"PARSE_TEXT_PROTO"}, 19257 /*CanonicalDelimiter=*/"", 19258 "llvm", 19259 }, 19260 { 19261 FormatStyle::LK_Cpp, 19262 {"cc", "cpp"}, 19263 {"C_CODEBLOCK", "CPPEVAL"}, 19264 /*CanonicalDelimiter=*/"cc", 19265 /*BasedOnStyle=*/"", 19266 }, 19267 }; 19268 19269 CHECK_PARSE("RawStringFormats:\n" 19270 " - Language: TextProto\n" 19271 " Delimiters:\n" 19272 " - 'pb'\n" 19273 " - 'proto'\n" 19274 " EnclosingFunctions:\n" 19275 " - 'PARSE_TEXT_PROTO'\n" 19276 " BasedOnStyle: llvm\n" 19277 " - Language: Cpp\n" 19278 " Delimiters:\n" 19279 " - 'cc'\n" 19280 " - 'cpp'\n" 19281 " EnclosingFunctions:\n" 19282 " - 'C_CODEBLOCK'\n" 19283 " - 'CPPEVAL'\n" 19284 " CanonicalDelimiter: 'cc'", 19285 RawStringFormats, ExpectedRawStringFormats); 19286 19287 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 19288 " Minimum: 0\n" 19289 " Maximum: 0", 19290 SpacesInLineCommentPrefix.Minimum, 0u); 19291 EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u); 19292 Style.SpacesInLineCommentPrefix.Minimum = 1; 19293 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 19294 " Minimum: 2", 19295 SpacesInLineCommentPrefix.Minimum, 0u); 19296 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 19297 " Maximum: -1", 19298 SpacesInLineCommentPrefix.Maximum, -1u); 19299 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 19300 " Minimum: 2", 19301 SpacesInLineCommentPrefix.Minimum, 2u); 19302 CHECK_PARSE("SpacesInLineCommentPrefix:\n" 19303 " Maximum: 1", 19304 SpacesInLineCommentPrefix.Maximum, 1u); 19305 EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u); 19306 19307 Style.SpacesInAngles = FormatStyle::SIAS_Always; 19308 CHECK_PARSE("SpacesInAngles: Never", SpacesInAngles, FormatStyle::SIAS_Never); 19309 CHECK_PARSE("SpacesInAngles: Always", SpacesInAngles, 19310 FormatStyle::SIAS_Always); 19311 CHECK_PARSE("SpacesInAngles: Leave", SpacesInAngles, FormatStyle::SIAS_Leave); 19312 // For backward compatibility: 19313 CHECK_PARSE("SpacesInAngles: false", SpacesInAngles, FormatStyle::SIAS_Never); 19314 CHECK_PARSE("SpacesInAngles: true", SpacesInAngles, FormatStyle::SIAS_Always); 19315 } 19316 19317 TEST_F(FormatTest, ParsesConfigurationWithLanguages) { 19318 FormatStyle Style = {}; 19319 Style.Language = FormatStyle::LK_Cpp; 19320 CHECK_PARSE("Language: Cpp\n" 19321 "IndentWidth: 12", 19322 IndentWidth, 12u); 19323 EXPECT_EQ(parseConfiguration("Language: JavaScript\n" 19324 "IndentWidth: 34", 19325 &Style), 19326 ParseError::Unsuitable); 19327 FormatStyle BinPackedTCS = {}; 19328 BinPackedTCS.Language = FormatStyle::LK_JavaScript; 19329 EXPECT_EQ(parseConfiguration("BinPackArguments: true\n" 19330 "InsertTrailingCommas: Wrapped", 19331 &BinPackedTCS), 19332 ParseError::BinPackTrailingCommaConflict); 19333 EXPECT_EQ(12u, Style.IndentWidth); 19334 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u); 19335 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language); 19336 19337 Style.Language = FormatStyle::LK_JavaScript; 19338 CHECK_PARSE("Language: JavaScript\n" 19339 "IndentWidth: 12", 19340 IndentWidth, 12u); 19341 CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u); 19342 EXPECT_EQ(parseConfiguration("Language: Cpp\n" 19343 "IndentWidth: 34", 19344 &Style), 19345 ParseError::Unsuitable); 19346 EXPECT_EQ(23u, Style.IndentWidth); 19347 CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u); 19348 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language); 19349 19350 CHECK_PARSE("BasedOnStyle: LLVM\n" 19351 "IndentWidth: 67", 19352 IndentWidth, 67u); 19353 19354 CHECK_PARSE("---\n" 19355 "Language: JavaScript\n" 19356 "IndentWidth: 12\n" 19357 "---\n" 19358 "Language: Cpp\n" 19359 "IndentWidth: 34\n" 19360 "...\n", 19361 IndentWidth, 12u); 19362 19363 Style.Language = FormatStyle::LK_Cpp; 19364 CHECK_PARSE("---\n" 19365 "Language: JavaScript\n" 19366 "IndentWidth: 12\n" 19367 "---\n" 19368 "Language: Cpp\n" 19369 "IndentWidth: 34\n" 19370 "...\n", 19371 IndentWidth, 34u); 19372 CHECK_PARSE("---\n" 19373 "IndentWidth: 78\n" 19374 "---\n" 19375 "Language: JavaScript\n" 19376 "IndentWidth: 56\n" 19377 "...\n", 19378 IndentWidth, 78u); 19379 19380 Style.ColumnLimit = 123; 19381 Style.IndentWidth = 234; 19382 Style.BreakBeforeBraces = FormatStyle::BS_Linux; 19383 Style.TabWidth = 345; 19384 EXPECT_FALSE(parseConfiguration("---\n" 19385 "IndentWidth: 456\n" 19386 "BreakBeforeBraces: Allman\n" 19387 "---\n" 19388 "Language: JavaScript\n" 19389 "IndentWidth: 111\n" 19390 "TabWidth: 111\n" 19391 "---\n" 19392 "Language: Cpp\n" 19393 "BreakBeforeBraces: Stroustrup\n" 19394 "TabWidth: 789\n" 19395 "...\n", 19396 &Style)); 19397 EXPECT_EQ(123u, Style.ColumnLimit); 19398 EXPECT_EQ(456u, Style.IndentWidth); 19399 EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces); 19400 EXPECT_EQ(789u, Style.TabWidth); 19401 19402 EXPECT_EQ(parseConfiguration("---\n" 19403 "Language: JavaScript\n" 19404 "IndentWidth: 56\n" 19405 "---\n" 19406 "IndentWidth: 78\n" 19407 "...\n", 19408 &Style), 19409 ParseError::Error); 19410 EXPECT_EQ(parseConfiguration("---\n" 19411 "Language: JavaScript\n" 19412 "IndentWidth: 56\n" 19413 "---\n" 19414 "Language: JavaScript\n" 19415 "IndentWidth: 78\n" 19416 "...\n", 19417 &Style), 19418 ParseError::Error); 19419 19420 EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language); 19421 } 19422 19423 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) { 19424 FormatStyle Style = {}; 19425 Style.Language = FormatStyle::LK_JavaScript; 19426 Style.BreakBeforeTernaryOperators = true; 19427 EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value()); 19428 EXPECT_FALSE(Style.BreakBeforeTernaryOperators); 19429 19430 Style.BreakBeforeTernaryOperators = true; 19431 EXPECT_EQ(0, parseConfiguration("---\n" 19432 "BasedOnStyle: Google\n" 19433 "---\n" 19434 "Language: JavaScript\n" 19435 "IndentWidth: 76\n" 19436 "...\n", 19437 &Style) 19438 .value()); 19439 EXPECT_FALSE(Style.BreakBeforeTernaryOperators); 19440 EXPECT_EQ(76u, Style.IndentWidth); 19441 EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language); 19442 } 19443 19444 TEST_F(FormatTest, ConfigurationRoundTripTest) { 19445 FormatStyle Style = getLLVMStyle(); 19446 std::string YAML = configurationAsText(Style); 19447 FormatStyle ParsedStyle = {}; 19448 ParsedStyle.Language = FormatStyle::LK_Cpp; 19449 EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value()); 19450 EXPECT_EQ(Style, ParsedStyle); 19451 } 19452 19453 TEST_F(FormatTest, WorksFor8bitEncodings) { 19454 EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n" 19455 "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n" 19456 "\"\xe7\xe8\xec\xed\xfe\xfe \"\n" 19457 "\"\xef\xee\xf0\xf3...\"", 19458 format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 " 19459 "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe " 19460 "\xef\xee\xf0\xf3...\"", 19461 getLLVMStyleWithColumns(12))); 19462 } 19463 19464 TEST_F(FormatTest, HandlesUTF8BOM) { 19465 EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf")); 19466 EXPECT_EQ("\xef\xbb\xbf#include <iostream>", 19467 format("\xef\xbb\xbf#include <iostream>")); 19468 EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>", 19469 format("\xef\xbb\xbf\n#include <iostream>")); 19470 } 19471 19472 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers. 19473 #if !defined(_MSC_VER) 19474 19475 TEST_F(FormatTest, CountsUTF8CharactersProperly) { 19476 verifyFormat("\"Однажды в студёную зимнюю пору...\"", 19477 getLLVMStyleWithColumns(35)); 19478 verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"", 19479 getLLVMStyleWithColumns(31)); 19480 verifyFormat("// Однажды в студёную зимнюю пору...", 19481 getLLVMStyleWithColumns(36)); 19482 verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32)); 19483 verifyFormat("/* Однажды в студёную зимнюю пору... */", 19484 getLLVMStyleWithColumns(39)); 19485 verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */", 19486 getLLVMStyleWithColumns(35)); 19487 } 19488 19489 TEST_F(FormatTest, SplitsUTF8Strings) { 19490 // Non-printable characters' width is currently considered to be the length in 19491 // bytes in UTF8. The characters can be displayed in very different manner 19492 // (zero-width, single width with a substitution glyph, expanded to their code 19493 // (e.g. "<8d>"), so there's no single correct way to handle them. 19494 EXPECT_EQ("\"aaaaÄ\"\n" 19495 "\"\xc2\x8d\";", 19496 format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10))); 19497 EXPECT_EQ("\"aaaaaaaÄ\"\n" 19498 "\"\xc2\x8d\";", 19499 format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10))); 19500 EXPECT_EQ("\"Однажды, в \"\n" 19501 "\"студёную \"\n" 19502 "\"зимнюю \"\n" 19503 "\"пору,\"", 19504 format("\"Однажды, в студёную зимнюю пору,\"", 19505 getLLVMStyleWithColumns(13))); 19506 EXPECT_EQ( 19507 "\"一 二 三 \"\n" 19508 "\"四 五六 \"\n" 19509 "\"七 八 九 \"\n" 19510 "\"十\"", 19511 format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11))); 19512 EXPECT_EQ("\"一\t\"\n" 19513 "\"二 \t\"\n" 19514 "\"三 四 \"\n" 19515 "\"五\t\"\n" 19516 "\"六 \t\"\n" 19517 "\"七 \"\n" 19518 "\"八九十\tqq\"", 19519 format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"", 19520 getLLVMStyleWithColumns(11))); 19521 19522 // UTF8 character in an escape sequence. 19523 EXPECT_EQ("\"aaaaaa\"\n" 19524 "\"\\\xC2\x8D\"", 19525 format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10))); 19526 } 19527 19528 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) { 19529 EXPECT_EQ("const char *sssss =\n" 19530 " \"一二三四五六七八\\\n" 19531 " 九 十\";", 19532 format("const char *sssss = \"一二三四五六七八\\\n" 19533 " 九 十\";", 19534 getLLVMStyleWithColumns(30))); 19535 } 19536 19537 TEST_F(FormatTest, SplitsUTF8LineComments) { 19538 EXPECT_EQ("// aaaaÄ\xc2\x8d", 19539 format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10))); 19540 EXPECT_EQ("// Я из лесу\n" 19541 "// вышел; был\n" 19542 "// сильный\n" 19543 "// мороз.", 19544 format("// Я из лесу вышел; был сильный мороз.", 19545 getLLVMStyleWithColumns(13))); 19546 EXPECT_EQ("// 一二三\n" 19547 "// 四五六七\n" 19548 "// 八 九\n" 19549 "// 十", 19550 format("// 一二三 四五六七 八 九 十", getLLVMStyleWithColumns(9))); 19551 } 19552 19553 TEST_F(FormatTest, SplitsUTF8BlockComments) { 19554 EXPECT_EQ("/* Гляжу,\n" 19555 " * поднимается\n" 19556 " * медленно в\n" 19557 " * гору\n" 19558 " * Лошадка,\n" 19559 " * везущая\n" 19560 " * хворосту\n" 19561 " * воз. */", 19562 format("/* Гляжу, поднимается медленно в гору\n" 19563 " * Лошадка, везущая хворосту воз. */", 19564 getLLVMStyleWithColumns(13))); 19565 EXPECT_EQ( 19566 "/* 一二三\n" 19567 " * 四五六七\n" 19568 " * 八 九\n" 19569 " * 十 */", 19570 format("/* 一二三 四五六七 八 九 十 */", getLLVMStyleWithColumns(9))); 19571 EXPECT_EQ("/* \n" 19572 " * \n" 19573 " * - */", 19574 format("/* - */", getLLVMStyleWithColumns(12))); 19575 } 19576 19577 #endif // _MSC_VER 19578 19579 TEST_F(FormatTest, ConstructorInitializerIndentWidth) { 19580 FormatStyle Style = getLLVMStyle(); 19581 19582 Style.ConstructorInitializerIndentWidth = 4; 19583 verifyFormat( 19584 "SomeClass::Constructor()\n" 19585 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 19586 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 19587 Style); 19588 19589 Style.ConstructorInitializerIndentWidth = 2; 19590 verifyFormat( 19591 "SomeClass::Constructor()\n" 19592 " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 19593 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 19594 Style); 19595 19596 Style.ConstructorInitializerIndentWidth = 0; 19597 verifyFormat( 19598 "SomeClass::Constructor()\n" 19599 ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" 19600 " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", 19601 Style); 19602 Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; 19603 verifyFormat( 19604 "SomeLongTemplateVariableName<\n" 19605 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>", 19606 Style); 19607 verifyFormat("bool smaller = 1 < " 19608 "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" 19609 " " 19610 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", 19611 Style); 19612 19613 Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; 19614 verifyFormat("SomeClass::Constructor() :\n" 19615 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n" 19616 "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}", 19617 Style); 19618 } 19619 19620 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) { 19621 FormatStyle Style = getLLVMStyle(); 19622 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 19623 Style.ConstructorInitializerIndentWidth = 4; 19624 verifyFormat("SomeClass::Constructor()\n" 19625 " : a(a)\n" 19626 " , b(b)\n" 19627 " , c(c) {}", 19628 Style); 19629 verifyFormat("SomeClass::Constructor()\n" 19630 " : a(a) {}", 19631 Style); 19632 19633 Style.ColumnLimit = 0; 19634 verifyFormat("SomeClass::Constructor()\n" 19635 " : a(a) {}", 19636 Style); 19637 verifyFormat("SomeClass::Constructor() noexcept\n" 19638 " : a(a) {}", 19639 Style); 19640 verifyFormat("SomeClass::Constructor()\n" 19641 " : a(a)\n" 19642 " , b(b)\n" 19643 " , c(c) {}", 19644 Style); 19645 verifyFormat("SomeClass::Constructor()\n" 19646 " : a(a) {\n" 19647 " foo();\n" 19648 " bar();\n" 19649 "}", 19650 Style); 19651 19652 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 19653 verifyFormat("SomeClass::Constructor()\n" 19654 " : a(a)\n" 19655 " , b(b)\n" 19656 " , c(c) {\n}", 19657 Style); 19658 verifyFormat("SomeClass::Constructor()\n" 19659 " : a(a) {\n}", 19660 Style); 19661 19662 Style.ColumnLimit = 80; 19663 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; 19664 Style.ConstructorInitializerIndentWidth = 2; 19665 verifyFormat("SomeClass::Constructor()\n" 19666 " : a(a)\n" 19667 " , b(b)\n" 19668 " , c(c) {}", 19669 Style); 19670 19671 Style.ConstructorInitializerIndentWidth = 0; 19672 verifyFormat("SomeClass::Constructor()\n" 19673 ": a(a)\n" 19674 ", b(b)\n" 19675 ", c(c) {}", 19676 Style); 19677 19678 Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine; 19679 Style.ConstructorInitializerIndentWidth = 4; 19680 verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style); 19681 verifyFormat( 19682 "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n", 19683 Style); 19684 verifyFormat( 19685 "SomeClass::Constructor()\n" 19686 " : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}", 19687 Style); 19688 Style.ConstructorInitializerIndentWidth = 4; 19689 Style.ColumnLimit = 60; 19690 verifyFormat("SomeClass::Constructor()\n" 19691 " : aaaaaaaa(aaaaaaaa)\n" 19692 " , aaaaaaaa(aaaaaaaa)\n" 19693 " , aaaaaaaa(aaaaaaaa) {}", 19694 Style); 19695 } 19696 19697 TEST_F(FormatTest, ConstructorInitializersWithPreprocessorDirective) { 19698 FormatStyle Style = getLLVMStyle(); 19699 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; 19700 Style.ConstructorInitializerIndentWidth = 4; 19701 verifyFormat("SomeClass::Constructor()\n" 19702 " : a{a}\n" 19703 " , b{b} {}", 19704 Style); 19705 verifyFormat("SomeClass::Constructor()\n" 19706 " : a{a}\n" 19707 "#if CONDITION\n" 19708 " , b{b}\n" 19709 "#endif\n" 19710 "{\n}", 19711 Style); 19712 Style.ConstructorInitializerIndentWidth = 2; 19713 verifyFormat("SomeClass::Constructor()\n" 19714 "#if CONDITION\n" 19715 " : a{a}\n" 19716 "#endif\n" 19717 " , b{b}\n" 19718 " , c{c} {\n}", 19719 Style); 19720 Style.ConstructorInitializerIndentWidth = 0; 19721 verifyFormat("SomeClass::Constructor()\n" 19722 ": a{a}\n" 19723 "#ifdef CONDITION\n" 19724 ", b{b}\n" 19725 "#else\n" 19726 ", c{c}\n" 19727 "#endif\n" 19728 ", d{d} {\n}", 19729 Style); 19730 Style.ConstructorInitializerIndentWidth = 4; 19731 verifyFormat("SomeClass::Constructor()\n" 19732 " : a{a}\n" 19733 "#if WINDOWS\n" 19734 "#if DEBUG\n" 19735 " , b{0}\n" 19736 "#else\n" 19737 " , b{1}\n" 19738 "#endif\n" 19739 "#else\n" 19740 "#if DEBUG\n" 19741 " , b{2}\n" 19742 "#else\n" 19743 " , b{3}\n" 19744 "#endif\n" 19745 "#endif\n" 19746 "{\n}", 19747 Style); 19748 verifyFormat("SomeClass::Constructor()\n" 19749 " : a{a}\n" 19750 "#if WINDOWS\n" 19751 " , b{0}\n" 19752 "#if DEBUG\n" 19753 " , c{0}\n" 19754 "#else\n" 19755 " , c{1}\n" 19756 "#endif\n" 19757 "#else\n" 19758 "#if DEBUG\n" 19759 " , c{2}\n" 19760 "#else\n" 19761 " , c{3}\n" 19762 "#endif\n" 19763 " , b{1}\n" 19764 "#endif\n" 19765 "{\n}", 19766 Style); 19767 } 19768 19769 TEST_F(FormatTest, Destructors) { 19770 verifyFormat("void F(int &i) { i.~int(); }"); 19771 verifyFormat("void F(int &i) { i->~int(); }"); 19772 } 19773 19774 TEST_F(FormatTest, FormatsWithWebKitStyle) { 19775 FormatStyle Style = getWebKitStyle(); 19776 19777 // Don't indent in outer namespaces. 19778 verifyFormat("namespace outer {\n" 19779 "int i;\n" 19780 "namespace inner {\n" 19781 " int i;\n" 19782 "} // namespace inner\n" 19783 "} // namespace outer\n" 19784 "namespace other_outer {\n" 19785 "int i;\n" 19786 "}", 19787 Style); 19788 19789 // Don't indent case labels. 19790 verifyFormat("switch (variable) {\n" 19791 "case 1:\n" 19792 "case 2:\n" 19793 " doSomething();\n" 19794 " break;\n" 19795 "default:\n" 19796 " ++variable;\n" 19797 "}", 19798 Style); 19799 19800 // Wrap before binary operators. 19801 EXPECT_EQ("void f()\n" 19802 "{\n" 19803 " if (aaaaaaaaaaaaaaaa\n" 19804 " && bbbbbbbbbbbbbbbbbbbbbbbb\n" 19805 " && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n" 19806 " return;\n" 19807 "}", 19808 format("void f() {\n" 19809 "if (aaaaaaaaaaaaaaaa\n" 19810 "&& bbbbbbbbbbbbbbbbbbbbbbbb\n" 19811 "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n" 19812 "return;\n" 19813 "}", 19814 Style)); 19815 19816 // Allow functions on a single line. 19817 verifyFormat("void f() { return; }", Style); 19818 19819 // Allow empty blocks on a single line and insert a space in empty blocks. 19820 EXPECT_EQ("void f() { }", format("void f() {}", Style)); 19821 EXPECT_EQ("while (true) { }", format("while (true) {}", Style)); 19822 // However, don't merge non-empty short loops. 19823 EXPECT_EQ("while (true) {\n" 19824 " continue;\n" 19825 "}", 19826 format("while (true) { continue; }", Style)); 19827 19828 // Constructor initializers are formatted one per line with the "," on the 19829 // new line. 19830 verifyFormat("Constructor()\n" 19831 " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" 19832 " , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n" 19833 " aaaaaaaaaaaaaa)\n" 19834 " , aaaaaaaaaaaaaaaaaaaaaaa()\n" 19835 "{\n" 19836 "}", 19837 Style); 19838 verifyFormat("SomeClass::Constructor()\n" 19839 " : a(a)\n" 19840 "{\n" 19841 "}", 19842 Style); 19843 EXPECT_EQ("SomeClass::Constructor()\n" 19844 " : a(a)\n" 19845 "{\n" 19846 "}", 19847 format("SomeClass::Constructor():a(a){}", Style)); 19848 verifyFormat("SomeClass::Constructor()\n" 19849 " : a(a)\n" 19850 " , b(b)\n" 19851 " , c(c)\n" 19852 "{\n" 19853 "}", 19854 Style); 19855 verifyFormat("SomeClass::Constructor()\n" 19856 " : a(a)\n" 19857 "{\n" 19858 " foo();\n" 19859 " bar();\n" 19860 "}", 19861 Style); 19862 19863 // Access specifiers should be aligned left. 19864 verifyFormat("class C {\n" 19865 "public:\n" 19866 " int i;\n" 19867 "};", 19868 Style); 19869 19870 // Do not align comments. 19871 verifyFormat("int a; // Do not\n" 19872 "double b; // align comments.", 19873 Style); 19874 19875 // Do not align operands. 19876 EXPECT_EQ("ASSERT(aaaa\n" 19877 " || bbbb);", 19878 format("ASSERT ( aaaa\n||bbbb);", Style)); 19879 19880 // Accept input's line breaks. 19881 EXPECT_EQ("if (aaaaaaaaaaaaaaa\n" 19882 " || bbbbbbbbbbbbbbb) {\n" 19883 " i++;\n" 19884 "}", 19885 format("if (aaaaaaaaaaaaaaa\n" 19886 "|| bbbbbbbbbbbbbbb) { i++; }", 19887 Style)); 19888 EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n" 19889 " i++;\n" 19890 "}", 19891 format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style)); 19892 19893 // Don't automatically break all macro definitions (llvm.org/PR17842). 19894 verifyFormat("#define aNumber 10", Style); 19895 // However, generally keep the line breaks that the user authored. 19896 EXPECT_EQ("#define aNumber \\\n" 19897 " 10", 19898 format("#define aNumber \\\n" 19899 " 10", 19900 Style)); 19901 19902 // Keep empty and one-element array literals on a single line. 19903 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n" 19904 " copyItems:YES];", 19905 format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n" 19906 "copyItems:YES];", 19907 Style)); 19908 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n" 19909 " copyItems:YES];", 19910 format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n" 19911 " copyItems:YES];", 19912 Style)); 19913 // FIXME: This does not seem right, there should be more indentation before 19914 // the array literal's entries. Nested blocks have the same problem. 19915 EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n" 19916 " @\"a\",\n" 19917 " @\"a\"\n" 19918 "]\n" 19919 " copyItems:YES];", 19920 format("NSArray* a = [[NSArray alloc] initWithArray:@[\n" 19921 " @\"a\",\n" 19922 " @\"a\"\n" 19923 " ]\n" 19924 " copyItems:YES];", 19925 Style)); 19926 EXPECT_EQ( 19927 "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n" 19928 " copyItems:YES];", 19929 format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n" 19930 " copyItems:YES];", 19931 Style)); 19932 19933 verifyFormat("[self.a b:c c:d];", Style); 19934 EXPECT_EQ("[self.a b:c\n" 19935 " c:d];", 19936 format("[self.a b:c\n" 19937 "c:d];", 19938 Style)); 19939 } 19940 19941 TEST_F(FormatTest, FormatsLambdas) { 19942 verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n"); 19943 verifyFormat( 19944 "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n"); 19945 verifyFormat("int c = [&] { [=] { return b++; }(); }();\n"); 19946 verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n"); 19947 verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n"); 19948 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n"); 19949 verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n"); 19950 verifyFormat("auto c = [a = [b = 42] {}] {};\n"); 19951 verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n"); 19952 verifyFormat("int x = f(*+[] {});"); 19953 verifyFormat("void f() {\n" 19954 " other(x.begin(), x.end(), [&](int, int) { return 1; });\n" 19955 "}\n"); 19956 verifyFormat("void f() {\n" 19957 " other(x.begin(), //\n" 19958 " x.end(), //\n" 19959 " [&](int, int) { return 1; });\n" 19960 "}\n"); 19961 verifyFormat("void f() {\n" 19962 " other.other.other.other.other(\n" 19963 " x.begin(), x.end(),\n" 19964 " [something, rather](int, int, int, int, int, int, int) { " 19965 "return 1; });\n" 19966 "}\n"); 19967 verifyFormat( 19968 "void f() {\n" 19969 " other.other.other.other.other(\n" 19970 " x.begin(), x.end(),\n" 19971 " [something, rather](int, int, int, int, int, int, int) {\n" 19972 " //\n" 19973 " });\n" 19974 "}\n"); 19975 verifyFormat("SomeFunction([]() { // A cool function...\n" 19976 " return 43;\n" 19977 "});"); 19978 EXPECT_EQ("SomeFunction([]() {\n" 19979 "#define A a\n" 19980 " return 43;\n" 19981 "});", 19982 format("SomeFunction([](){\n" 19983 "#define A a\n" 19984 "return 43;\n" 19985 "});")); 19986 verifyFormat("void f() {\n" 19987 " SomeFunction([](decltype(x), A *a) {});\n" 19988 " SomeFunction([](typeof(x), A *a) {});\n" 19989 " SomeFunction([](_Atomic(x), A *a) {});\n" 19990 " SomeFunction([](__underlying_type(x), A *a) {});\n" 19991 "}"); 19992 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 19993 " [](const aaaaaaaaaa &a) { return a; });"); 19994 verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n" 19995 " SomeOtherFunctioooooooooooooooooooooooooon();\n" 19996 "});"); 19997 verifyFormat("Constructor()\n" 19998 " : Field([] { // comment\n" 19999 " int i;\n" 20000 " }) {}"); 20001 verifyFormat("auto my_lambda = [](const string &some_parameter) {\n" 20002 " return some_parameter.size();\n" 20003 "};"); 20004 verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n" 20005 " [](const string &s) { return s; };"); 20006 verifyFormat("int i = aaaaaa ? 1 //\n" 20007 " : [] {\n" 20008 " return 2; //\n" 20009 " }();"); 20010 verifyFormat("llvm::errs() << \"number of twos is \"\n" 20011 " << std::count_if(v.begin(), v.end(), [](int x) {\n" 20012 " return x == 2; // force break\n" 20013 " });"); 20014 verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 20015 " [=](int iiiiiiiiiiii) {\n" 20016 " return aaaaaaaaaaaaaaaaaaaaaaa !=\n" 20017 " aaaaaaaaaaaaaaaaaaaaaaa;\n" 20018 " });", 20019 getLLVMStyleWithColumns(60)); 20020 20021 verifyFormat("SomeFunction({[&] {\n" 20022 " // comment\n" 20023 " },\n" 20024 " [&] {\n" 20025 " // comment\n" 20026 " }});"); 20027 verifyFormat("SomeFunction({[&] {\n" 20028 " // comment\n" 20029 "}});"); 20030 verifyFormat( 20031 "virtual aaaaaaaaaaaaaaaa(\n" 20032 " std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n" 20033 " aaaaa aaaaaaaaa);"); 20034 20035 // Lambdas with return types. 20036 verifyFormat("int c = []() -> int { return 2; }();\n"); 20037 verifyFormat("int c = []() -> int * { return 2; }();\n"); 20038 verifyFormat("int c = []() -> vector<int> { return {2}; }();\n"); 20039 verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());"); 20040 verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};"); 20041 verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};"); 20042 verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};"); 20043 verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};"); 20044 verifyFormat("[a, a]() -> a<1> {};"); 20045 verifyFormat("[]() -> foo<5 + 2> { return {}; };"); 20046 verifyFormat("[]() -> foo<5 - 2> { return {}; };"); 20047 verifyFormat("[]() -> foo<5 / 2> { return {}; };"); 20048 verifyFormat("[]() -> foo<5 * 2> { return {}; };"); 20049 verifyFormat("[]() -> foo<5 % 2> { return {}; };"); 20050 verifyFormat("[]() -> foo<5 << 2> { return {}; };"); 20051 verifyFormat("[]() -> foo<!5> { return {}; };"); 20052 verifyFormat("[]() -> foo<~5> { return {}; };"); 20053 verifyFormat("[]() -> foo<5 | 2> { return {}; };"); 20054 verifyFormat("[]() -> foo<5 || 2> { return {}; };"); 20055 verifyFormat("[]() -> foo<5 & 2> { return {}; };"); 20056 verifyFormat("[]() -> foo<5 && 2> { return {}; };"); 20057 verifyFormat("[]() -> foo<5 == 2> { return {}; };"); 20058 verifyFormat("[]() -> foo<5 != 2> { return {}; };"); 20059 verifyFormat("[]() -> foo<5 >= 2> { return {}; };"); 20060 verifyFormat("[]() -> foo<5 <= 2> { return {}; };"); 20061 verifyFormat("[]() -> foo<5 < 2> { return {}; };"); 20062 verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };"); 20063 verifyFormat("namespace bar {\n" 20064 "// broken:\n" 20065 "auto foo{[]() -> foo<5 + 2> { return {}; }};\n" 20066 "} // namespace bar"); 20067 verifyFormat("namespace bar {\n" 20068 "// broken:\n" 20069 "auto foo{[]() -> foo<5 - 2> { return {}; }};\n" 20070 "} // namespace bar"); 20071 verifyFormat("namespace bar {\n" 20072 "// broken:\n" 20073 "auto foo{[]() -> foo<5 / 2> { return {}; }};\n" 20074 "} // namespace bar"); 20075 verifyFormat("namespace bar {\n" 20076 "// broken:\n" 20077 "auto foo{[]() -> foo<5 * 2> { return {}; }};\n" 20078 "} // namespace bar"); 20079 verifyFormat("namespace bar {\n" 20080 "// broken:\n" 20081 "auto foo{[]() -> foo<5 % 2> { return {}; }};\n" 20082 "} // namespace bar"); 20083 verifyFormat("namespace bar {\n" 20084 "// broken:\n" 20085 "auto foo{[]() -> foo<5 << 2> { return {}; }};\n" 20086 "} // namespace bar"); 20087 verifyFormat("namespace bar {\n" 20088 "// broken:\n" 20089 "auto foo{[]() -> foo<!5> { return {}; }};\n" 20090 "} // namespace bar"); 20091 verifyFormat("namespace bar {\n" 20092 "// broken:\n" 20093 "auto foo{[]() -> foo<~5> { return {}; }};\n" 20094 "} // namespace bar"); 20095 verifyFormat("namespace bar {\n" 20096 "// broken:\n" 20097 "auto foo{[]() -> foo<5 | 2> { return {}; }};\n" 20098 "} // namespace bar"); 20099 verifyFormat("namespace bar {\n" 20100 "// broken:\n" 20101 "auto foo{[]() -> foo<5 || 2> { return {}; }};\n" 20102 "} // namespace bar"); 20103 verifyFormat("namespace bar {\n" 20104 "// broken:\n" 20105 "auto foo{[]() -> foo<5 & 2> { return {}; }};\n" 20106 "} // namespace bar"); 20107 verifyFormat("namespace bar {\n" 20108 "// broken:\n" 20109 "auto foo{[]() -> foo<5 && 2> { return {}; }};\n" 20110 "} // namespace bar"); 20111 verifyFormat("namespace bar {\n" 20112 "// broken:\n" 20113 "auto foo{[]() -> foo<5 == 2> { return {}; }};\n" 20114 "} // namespace bar"); 20115 verifyFormat("namespace bar {\n" 20116 "// broken:\n" 20117 "auto foo{[]() -> foo<5 != 2> { return {}; }};\n" 20118 "} // namespace bar"); 20119 verifyFormat("namespace bar {\n" 20120 "// broken:\n" 20121 "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n" 20122 "} // namespace bar"); 20123 verifyFormat("namespace bar {\n" 20124 "// broken:\n" 20125 "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n" 20126 "} // namespace bar"); 20127 verifyFormat("namespace bar {\n" 20128 "// broken:\n" 20129 "auto foo{[]() -> foo<5 < 2> { return {}; }};\n" 20130 "} // namespace bar"); 20131 verifyFormat("namespace bar {\n" 20132 "// broken:\n" 20133 "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n" 20134 "} // namespace bar"); 20135 verifyFormat("[]() -> a<1> {};"); 20136 verifyFormat("[]() -> a<1> { ; };"); 20137 verifyFormat("[]() -> a<1> { ; }();"); 20138 verifyFormat("[a, a]() -> a<true> {};"); 20139 verifyFormat("[]() -> a<true> {};"); 20140 verifyFormat("[]() -> a<true> { ; };"); 20141 verifyFormat("[]() -> a<true> { ; }();"); 20142 verifyFormat("[a, a]() -> a<false> {};"); 20143 verifyFormat("[]() -> a<false> {};"); 20144 verifyFormat("[]() -> a<false> { ; };"); 20145 verifyFormat("[]() -> a<false> { ; }();"); 20146 verifyFormat("auto foo{[]() -> foo<false> { ; }};"); 20147 verifyFormat("namespace bar {\n" 20148 "auto foo{[]() -> foo<false> { ; }};\n" 20149 "} // namespace bar"); 20150 verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n" 20151 " int j) -> int {\n" 20152 " return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n" 20153 "};"); 20154 verifyFormat( 20155 "aaaaaaaaaaaaaaaaaaaaaa(\n" 20156 " [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n" 20157 " return aaaaaaaaaaaaaaaaa;\n" 20158 " });", 20159 getLLVMStyleWithColumns(70)); 20160 verifyFormat("[]() //\n" 20161 " -> int {\n" 20162 " return 1; //\n" 20163 "};"); 20164 verifyFormat("[]() -> Void<T...> {};"); 20165 verifyFormat("[a, b]() -> Tuple<T...> { return {}; };"); 20166 20167 // Lambdas with explicit template argument lists. 20168 verifyFormat( 20169 "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n"); 20170 20171 // Multiple lambdas in the same parentheses change indentation rules. These 20172 // lambdas are forced to start on new lines. 20173 verifyFormat("SomeFunction(\n" 20174 " []() {\n" 20175 " //\n" 20176 " },\n" 20177 " []() {\n" 20178 " //\n" 20179 " });"); 20180 20181 // A lambda passed as arg0 is always pushed to the next line. 20182 verifyFormat("SomeFunction(\n" 20183 " [this] {\n" 20184 " //\n" 20185 " },\n" 20186 " 1);\n"); 20187 20188 // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like 20189 // the arg0 case above. 20190 auto Style = getGoogleStyle(); 20191 Style.BinPackArguments = false; 20192 verifyFormat("SomeFunction(\n" 20193 " a,\n" 20194 " [this] {\n" 20195 " //\n" 20196 " },\n" 20197 " b);\n", 20198 Style); 20199 verifyFormat("SomeFunction(\n" 20200 " a,\n" 20201 " [this] {\n" 20202 " //\n" 20203 " },\n" 20204 " b);\n"); 20205 20206 // A lambda with a very long line forces arg0 to be pushed out irrespective of 20207 // the BinPackArguments value (as long as the code is wide enough). 20208 verifyFormat( 20209 "something->SomeFunction(\n" 20210 " a,\n" 20211 " [this] {\n" 20212 " " 20213 "D0000000000000000000000000000000000000000000000000000000000001();\n" 20214 " },\n" 20215 " b);\n"); 20216 20217 // A multi-line lambda is pulled up as long as the introducer fits on the 20218 // previous line and there are no further args. 20219 verifyFormat("function(1, [this, that] {\n" 20220 " //\n" 20221 "});\n"); 20222 verifyFormat("function([this, that] {\n" 20223 " //\n" 20224 "});\n"); 20225 // FIXME: this format is not ideal and we should consider forcing the first 20226 // arg onto its own line. 20227 verifyFormat("function(a, b, c, //\n" 20228 " d, [this, that] {\n" 20229 " //\n" 20230 " });\n"); 20231 20232 // Multiple lambdas are treated correctly even when there is a short arg0. 20233 verifyFormat("SomeFunction(\n" 20234 " 1,\n" 20235 " [this] {\n" 20236 " //\n" 20237 " },\n" 20238 " [this] {\n" 20239 " //\n" 20240 " },\n" 20241 " 1);\n"); 20242 20243 // More complex introducers. 20244 verifyFormat("return [i, args...] {};"); 20245 20246 // Not lambdas. 20247 verifyFormat("constexpr char hello[]{\"hello\"};"); 20248 verifyFormat("double &operator[](int i) { return 0; }\n" 20249 "int i;"); 20250 verifyFormat("std::unique_ptr<int[]> foo() {}"); 20251 verifyFormat("int i = a[a][a]->f();"); 20252 verifyFormat("int i = (*b)[a]->f();"); 20253 20254 // Other corner cases. 20255 verifyFormat("void f() {\n" 20256 " bar([]() {} // Did not respect SpacesBeforeTrailingComments\n" 20257 " );\n" 20258 "}"); 20259 20260 // Lambdas created through weird macros. 20261 verifyFormat("void f() {\n" 20262 " MACRO((const AA &a) { return 1; });\n" 20263 " MACRO((AA &a) { return 1; });\n" 20264 "}"); 20265 20266 verifyFormat("if (blah_blah(whatever, whatever, [] {\n" 20267 " doo_dah();\n" 20268 " doo_dah();\n" 20269 " })) {\n" 20270 "}"); 20271 verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n" 20272 " doo_dah();\n" 20273 " doo_dah();\n" 20274 " })) {\n" 20275 "}"); 20276 verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n" 20277 " doo_dah();\n" 20278 " doo_dah();\n" 20279 " })) {\n" 20280 "}"); 20281 verifyFormat("auto lambda = []() {\n" 20282 " int a = 2\n" 20283 "#if A\n" 20284 " + 2\n" 20285 "#endif\n" 20286 " ;\n" 20287 "};"); 20288 20289 // Lambdas with complex multiline introducers. 20290 verifyFormat( 20291 "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 20292 " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n" 20293 " -> ::std::unordered_set<\n" 20294 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n" 20295 " //\n" 20296 " });"); 20297 20298 FormatStyle DoNotMerge = getLLVMStyle(); 20299 DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None; 20300 verifyFormat("auto c = []() {\n" 20301 " return b;\n" 20302 "};", 20303 "auto c = []() { return b; };", DoNotMerge); 20304 verifyFormat("auto c = []() {\n" 20305 "};", 20306 " auto c = []() {};", DoNotMerge); 20307 20308 FormatStyle MergeEmptyOnly = getLLVMStyle(); 20309 MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty; 20310 verifyFormat("auto c = []() {\n" 20311 " return b;\n" 20312 "};", 20313 "auto c = []() {\n" 20314 " return b;\n" 20315 " };", 20316 MergeEmptyOnly); 20317 verifyFormat("auto c = []() {};", 20318 "auto c = []() {\n" 20319 "};", 20320 MergeEmptyOnly); 20321 20322 FormatStyle MergeInline = getLLVMStyle(); 20323 MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline; 20324 verifyFormat("auto c = []() {\n" 20325 " return b;\n" 20326 "};", 20327 "auto c = []() { return b; };", MergeInline); 20328 verifyFormat("function([]() { return b; })", "function([]() { return b; })", 20329 MergeInline); 20330 verifyFormat("function([]() { return b; }, a)", 20331 "function([]() { return b; }, a)", MergeInline); 20332 verifyFormat("function(a, []() { return b; })", 20333 "function(a, []() { return b; })", MergeInline); 20334 20335 // Check option "BraceWrapping.BeforeLambdaBody" and different state of 20336 // AllowShortLambdasOnASingleLine 20337 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle(); 20338 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 20339 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 20340 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 20341 FormatStyle::ShortLambdaStyle::SLS_None; 20342 verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n" 20343 " []()\n" 20344 " {\n" 20345 " return 17;\n" 20346 " });", 20347 LLVMWithBeforeLambdaBody); 20348 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n" 20349 " []()\n" 20350 " {\n" 20351 " });", 20352 LLVMWithBeforeLambdaBody); 20353 verifyFormat("auto fct_SLS_None = []()\n" 20354 "{\n" 20355 " return 17;\n" 20356 "};", 20357 LLVMWithBeforeLambdaBody); 20358 verifyFormat("TwoNestedLambdas_SLS_None(\n" 20359 " []()\n" 20360 " {\n" 20361 " return Call(\n" 20362 " []()\n" 20363 " {\n" 20364 " return 17;\n" 20365 " });\n" 20366 " });", 20367 LLVMWithBeforeLambdaBody); 20368 verifyFormat("void Fct() {\n" 20369 " return {[]()\n" 20370 " {\n" 20371 " return 17;\n" 20372 " }};\n" 20373 "}", 20374 LLVMWithBeforeLambdaBody); 20375 20376 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 20377 FormatStyle::ShortLambdaStyle::SLS_Empty; 20378 verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n" 20379 " []()\n" 20380 " {\n" 20381 " return 17;\n" 20382 " });", 20383 LLVMWithBeforeLambdaBody); 20384 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});", 20385 LLVMWithBeforeLambdaBody); 20386 verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL" 20387 "ongFunctionName_SLS_Empty(\n" 20388 " []() {});", 20389 LLVMWithBeforeLambdaBody); 20390 verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n" 20391 " []()\n" 20392 " {\n" 20393 " return 17;\n" 20394 " });", 20395 LLVMWithBeforeLambdaBody); 20396 verifyFormat("auto fct_SLS_Empty = []()\n" 20397 "{\n" 20398 " return 17;\n" 20399 "};", 20400 LLVMWithBeforeLambdaBody); 20401 verifyFormat("TwoNestedLambdas_SLS_Empty(\n" 20402 " []()\n" 20403 " {\n" 20404 " return Call([]() {});\n" 20405 " });", 20406 LLVMWithBeforeLambdaBody); 20407 verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n" 20408 " []()\n" 20409 " {\n" 20410 " return Call([]() {});\n" 20411 " });", 20412 LLVMWithBeforeLambdaBody); 20413 verifyFormat( 20414 "FctWithLongLineInLambda_SLS_Empty(\n" 20415 " []()\n" 20416 " {\n" 20417 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 20418 " AndShouldNotBeConsiderAsInline,\n" 20419 " LambdaBodyMustBeBreak);\n" 20420 " });", 20421 LLVMWithBeforeLambdaBody); 20422 20423 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 20424 FormatStyle::ShortLambdaStyle::SLS_Inline; 20425 verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });", 20426 LLVMWithBeforeLambdaBody); 20427 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});", 20428 LLVMWithBeforeLambdaBody); 20429 verifyFormat("auto fct_SLS_Inline = []()\n" 20430 "{\n" 20431 " return 17;\n" 20432 "};", 20433 LLVMWithBeforeLambdaBody); 20434 verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return " 20435 "17; }); });", 20436 LLVMWithBeforeLambdaBody); 20437 verifyFormat( 20438 "FctWithLongLineInLambda_SLS_Inline(\n" 20439 " []()\n" 20440 " {\n" 20441 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 20442 " AndShouldNotBeConsiderAsInline,\n" 20443 " LambdaBodyMustBeBreak);\n" 20444 " });", 20445 LLVMWithBeforeLambdaBody); 20446 verifyFormat("FctWithMultipleParams_SLS_Inline(" 20447 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n" 20448 " []() { return 17; });", 20449 LLVMWithBeforeLambdaBody); 20450 verifyFormat( 20451 "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });", 20452 LLVMWithBeforeLambdaBody); 20453 20454 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 20455 FormatStyle::ShortLambdaStyle::SLS_All; 20456 verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });", 20457 LLVMWithBeforeLambdaBody); 20458 verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});", 20459 LLVMWithBeforeLambdaBody); 20460 verifyFormat("auto fct_SLS_All = []() { return 17; };", 20461 LLVMWithBeforeLambdaBody); 20462 verifyFormat("FctWithOneParam_SLS_All(\n" 20463 " []()\n" 20464 " {\n" 20465 " // A cool function...\n" 20466 " return 43;\n" 20467 " });", 20468 LLVMWithBeforeLambdaBody); 20469 verifyFormat("FctWithMultipleParams_SLS_All(" 20470 "VeryLongParameterThatShouldAskToBeOnMultiLine,\n" 20471 " []() { return 17; });", 20472 LLVMWithBeforeLambdaBody); 20473 verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });", 20474 LLVMWithBeforeLambdaBody); 20475 verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });", 20476 LLVMWithBeforeLambdaBody); 20477 verifyFormat( 20478 "FctWithLongLineInLambda_SLS_All(\n" 20479 " []()\n" 20480 " {\n" 20481 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 20482 " AndShouldNotBeConsiderAsInline,\n" 20483 " LambdaBodyMustBeBreak);\n" 20484 " });", 20485 LLVMWithBeforeLambdaBody); 20486 verifyFormat( 20487 "auto fct_SLS_All = []()\n" 20488 "{\n" 20489 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 20490 " AndShouldNotBeConsiderAsInline,\n" 20491 " LambdaBodyMustBeBreak);\n" 20492 "};", 20493 LLVMWithBeforeLambdaBody); 20494 LLVMWithBeforeLambdaBody.BinPackParameters = false; 20495 verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);", 20496 LLVMWithBeforeLambdaBody); 20497 verifyFormat( 20498 "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n" 20499 " FirstParam,\n" 20500 " SecondParam,\n" 20501 " ThirdParam,\n" 20502 " FourthParam);", 20503 LLVMWithBeforeLambdaBody); 20504 verifyFormat("FctWithLongLineInLambda_SLS_All(\n" 20505 " []() { return " 20506 "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n" 20507 " FirstParam,\n" 20508 " SecondParam,\n" 20509 " ThirdParam,\n" 20510 " FourthParam);", 20511 LLVMWithBeforeLambdaBody); 20512 verifyFormat( 20513 "FctWithLongLineInLambda_SLS_All(FirstParam,\n" 20514 " SecondParam,\n" 20515 " ThirdParam,\n" 20516 " FourthParam,\n" 20517 " []() { return SomeValueNotSoLong; });", 20518 LLVMWithBeforeLambdaBody); 20519 verifyFormat("FctWithLongLineInLambda_SLS_All(\n" 20520 " []()\n" 20521 " {\n" 20522 " return " 20523 "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB" 20524 "eConsiderAsInline;\n" 20525 " });", 20526 LLVMWithBeforeLambdaBody); 20527 verifyFormat( 20528 "FctWithLongLineInLambda_SLS_All(\n" 20529 " []()\n" 20530 " {\n" 20531 " return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n" 20532 " AndShouldNotBeConsiderAsInline,\n" 20533 " LambdaBodyMustBeBreak);\n" 20534 " });", 20535 LLVMWithBeforeLambdaBody); 20536 verifyFormat("FctWithTwoParams_SLS_All(\n" 20537 " []()\n" 20538 " {\n" 20539 " // A cool function...\n" 20540 " return 43;\n" 20541 " },\n" 20542 " 87);", 20543 LLVMWithBeforeLambdaBody); 20544 verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);", 20545 LLVMWithBeforeLambdaBody); 20546 verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });", 20547 LLVMWithBeforeLambdaBody); 20548 verifyFormat( 20549 "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });", 20550 LLVMWithBeforeLambdaBody); 20551 verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; " 20552 "}); }, x);", 20553 LLVMWithBeforeLambdaBody); 20554 verifyFormat("TwoNestedLambdas_SLS_All(\n" 20555 " []()\n" 20556 " {\n" 20557 " // A cool function...\n" 20558 " return Call([]() { return 17; });\n" 20559 " });", 20560 LLVMWithBeforeLambdaBody); 20561 verifyFormat("TwoNestedLambdas_SLS_All(\n" 20562 " []()\n" 20563 " {\n" 20564 " return Call(\n" 20565 " []()\n" 20566 " {\n" 20567 " // A cool function...\n" 20568 " return 17;\n" 20569 " });\n" 20570 " });", 20571 LLVMWithBeforeLambdaBody); 20572 20573 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 20574 FormatStyle::ShortLambdaStyle::SLS_None; 20575 20576 verifyFormat("auto select = [this]() -> const Library::Object *\n" 20577 "{\n" 20578 " return MyAssignment::SelectFromList(this);\n" 20579 "};\n", 20580 LLVMWithBeforeLambdaBody); 20581 20582 verifyFormat("auto select = [this]() -> const Library::Object &\n" 20583 "{\n" 20584 " return MyAssignment::SelectFromList(this);\n" 20585 "};\n", 20586 LLVMWithBeforeLambdaBody); 20587 20588 verifyFormat("auto select = [this]() -> std::unique_ptr<Object>\n" 20589 "{\n" 20590 " return MyAssignment::SelectFromList(this);\n" 20591 "};\n", 20592 LLVMWithBeforeLambdaBody); 20593 20594 verifyFormat("namespace test {\n" 20595 "class Test {\n" 20596 "public:\n" 20597 " Test() = default;\n" 20598 "};\n" 20599 "} // namespace test", 20600 LLVMWithBeforeLambdaBody); 20601 20602 // Lambdas with different indentation styles. 20603 Style = getLLVMStyleWithColumns(100); 20604 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 20605 " return promise.then(\n" 20606 " [this, &someVariable, someObject = " 20607 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 20608 " return someObject.startAsyncAction().then(\n" 20609 " [this, &someVariable](AsyncActionResult result) " 20610 "mutable { result.processMore(); });\n" 20611 " });\n" 20612 "}\n", 20613 format("SomeResult doSomething(SomeObject promise) {\n" 20614 " return promise.then([this, &someVariable, someObject = " 20615 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 20616 " return someObject.startAsyncAction().then([this, " 20617 "&someVariable](AsyncActionResult result) mutable {\n" 20618 " result.processMore();\n" 20619 " });\n" 20620 " });\n" 20621 "}\n", 20622 Style)); 20623 Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope; 20624 verifyFormat("test() {\n" 20625 " ([]() -> {\n" 20626 " int b = 32;\n" 20627 " return 3;\n" 20628 " }).foo();\n" 20629 "}", 20630 Style); 20631 verifyFormat("test() {\n" 20632 " []() -> {\n" 20633 " int b = 32;\n" 20634 " return 3;\n" 20635 " }\n" 20636 "}", 20637 Style); 20638 verifyFormat("std::sort(v.begin(), v.end(),\n" 20639 " [](const auto &someLongArgumentName, const auto " 20640 "&someOtherLongArgumentName) {\n" 20641 " return someLongArgumentName.someMemberVariable < " 20642 "someOtherLongArgumentName.someMemberVariable;\n" 20643 "});", 20644 Style); 20645 verifyFormat("test() {\n" 20646 " (\n" 20647 " []() -> {\n" 20648 " int b = 32;\n" 20649 " return 3;\n" 20650 " },\n" 20651 " foo, bar)\n" 20652 " .foo();\n" 20653 "}", 20654 Style); 20655 verifyFormat("test() {\n" 20656 " ([]() -> {\n" 20657 " int b = 32;\n" 20658 " return 3;\n" 20659 " })\n" 20660 " .foo()\n" 20661 " .bar();\n" 20662 "}", 20663 Style); 20664 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 20665 " return promise.then(\n" 20666 " [this, &someVariable, someObject = " 20667 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 20668 " return someObject.startAsyncAction().then(\n" 20669 " [this, &someVariable](AsyncActionResult result) mutable { " 20670 "result.processMore(); });\n" 20671 " });\n" 20672 "}\n", 20673 format("SomeResult doSomething(SomeObject promise) {\n" 20674 " return promise.then([this, &someVariable, someObject = " 20675 "std::mv(s)](std::vector<int> evaluated) mutable {\n" 20676 " return someObject.startAsyncAction().then([this, " 20677 "&someVariable](AsyncActionResult result) mutable {\n" 20678 " result.processMore();\n" 20679 " });\n" 20680 " });\n" 20681 "}\n", 20682 Style)); 20683 EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n" 20684 " return promise.then([this, &someVariable] {\n" 20685 " return someObject.startAsyncAction().then(\n" 20686 " [this, &someVariable](AsyncActionResult result) mutable { " 20687 "result.processMore(); });\n" 20688 " });\n" 20689 "}\n", 20690 format("SomeResult doSomething(SomeObject promise) {\n" 20691 " return promise.then([this, &someVariable] {\n" 20692 " return someObject.startAsyncAction().then([this, " 20693 "&someVariable](AsyncActionResult result) mutable {\n" 20694 " result.processMore();\n" 20695 " });\n" 20696 " });\n" 20697 "}\n", 20698 Style)); 20699 Style = getGoogleStyle(); 20700 Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope; 20701 EXPECT_EQ("#define A \\\n" 20702 " [] { \\\n" 20703 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 20704 " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n" 20705 " }", 20706 format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" 20707 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }", 20708 Style)); 20709 // TODO: The current formatting has a minor issue that's not worth fixing 20710 // right now whereby the closing brace is indented relative to the signature 20711 // instead of being aligned. This only happens with macros. 20712 } 20713 20714 TEST_F(FormatTest, LambdaWithLineComments) { 20715 FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle(); 20716 LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom; 20717 LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true; 20718 LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine = 20719 FormatStyle::ShortLambdaStyle::SLS_All; 20720 20721 verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody); 20722 verifyFormat("auto k = []() // comment\n" 20723 "{ return; }", 20724 LLVMWithBeforeLambdaBody); 20725 verifyFormat("auto k = []() /* comment */ { return; }", 20726 LLVMWithBeforeLambdaBody); 20727 verifyFormat("auto k = []() /* comment */ /* comment */ { return; }", 20728 LLVMWithBeforeLambdaBody); 20729 verifyFormat("auto k = []() // X\n" 20730 "{ return; }", 20731 LLVMWithBeforeLambdaBody); 20732 verifyFormat( 20733 "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" 20734 "{ return; }", 20735 LLVMWithBeforeLambdaBody); 20736 } 20737 20738 TEST_F(FormatTest, EmptyLinesInLambdas) { 20739 verifyFormat("auto lambda = []() {\n" 20740 " x(); //\n" 20741 "};", 20742 "auto lambda = []() {\n" 20743 "\n" 20744 " x(); //\n" 20745 "\n" 20746 "};"); 20747 } 20748 20749 TEST_F(FormatTest, FormatsBlocks) { 20750 FormatStyle ShortBlocks = getLLVMStyle(); 20751 ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 20752 verifyFormat("int (^Block)(int, int);", ShortBlocks); 20753 verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks); 20754 verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks); 20755 verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks); 20756 verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks); 20757 verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks); 20758 20759 verifyFormat("foo(^{ bar(); });", ShortBlocks); 20760 verifyFormat("foo(a, ^{ bar(); });", ShortBlocks); 20761 verifyFormat("{ void (^block)(Object *x); }", ShortBlocks); 20762 20763 verifyFormat("[operation setCompletionBlock:^{\n" 20764 " [self onOperationDone];\n" 20765 "}];"); 20766 verifyFormat("int i = {[operation setCompletionBlock:^{\n" 20767 " [self onOperationDone];\n" 20768 "}]};"); 20769 verifyFormat("[operation setCompletionBlock:^(int *i) {\n" 20770 " f();\n" 20771 "}];"); 20772 verifyFormat("int a = [operation block:^int(int *i) {\n" 20773 " return 1;\n" 20774 "}];"); 20775 verifyFormat("[myObject doSomethingWith:arg1\n" 20776 " aaa:^int(int *a) {\n" 20777 " return 1;\n" 20778 " }\n" 20779 " bbb:f(a * bbbbbbbb)];"); 20780 20781 verifyFormat("[operation setCompletionBlock:^{\n" 20782 " [self.delegate newDataAvailable];\n" 20783 "}];", 20784 getLLVMStyleWithColumns(60)); 20785 verifyFormat("dispatch_async(_fileIOQueue, ^{\n" 20786 " NSString *path = [self sessionFilePath];\n" 20787 " if (path) {\n" 20788 " // ...\n" 20789 " }\n" 20790 "});"); 20791 verifyFormat("[[SessionService sharedService]\n" 20792 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 20793 " if (window) {\n" 20794 " [self windowDidLoad:window];\n" 20795 " } else {\n" 20796 " [self errorLoadingWindow];\n" 20797 " }\n" 20798 " }];"); 20799 verifyFormat("void (^largeBlock)(void) = ^{\n" 20800 " // ...\n" 20801 "};\n", 20802 getLLVMStyleWithColumns(40)); 20803 verifyFormat("[[SessionService sharedService]\n" 20804 " loadWindowWithCompletionBlock: //\n" 20805 " ^(SessionWindow *window) {\n" 20806 " if (window) {\n" 20807 " [self windowDidLoad:window];\n" 20808 " } else {\n" 20809 " [self errorLoadingWindow];\n" 20810 " }\n" 20811 " }];", 20812 getLLVMStyleWithColumns(60)); 20813 verifyFormat("[myObject doSomethingWith:arg1\n" 20814 " firstBlock:^(Foo *a) {\n" 20815 " // ...\n" 20816 " int i;\n" 20817 " }\n" 20818 " secondBlock:^(Bar *b) {\n" 20819 " // ...\n" 20820 " int i;\n" 20821 " }\n" 20822 " thirdBlock:^Foo(Bar *b) {\n" 20823 " // ...\n" 20824 " int i;\n" 20825 " }];"); 20826 verifyFormat("[myObject doSomethingWith:arg1\n" 20827 " firstBlock:-1\n" 20828 " secondBlock:^(Bar *b) {\n" 20829 " // ...\n" 20830 " int i;\n" 20831 " }];"); 20832 20833 verifyFormat("f(^{\n" 20834 " @autoreleasepool {\n" 20835 " if (a) {\n" 20836 " g();\n" 20837 " }\n" 20838 " }\n" 20839 "});"); 20840 verifyFormat("Block b = ^int *(A *a, B *b) {}"); 20841 verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n" 20842 "};"); 20843 20844 FormatStyle FourIndent = getLLVMStyle(); 20845 FourIndent.ObjCBlockIndentWidth = 4; 20846 verifyFormat("[operation setCompletionBlock:^{\n" 20847 " [self onOperationDone];\n" 20848 "}];", 20849 FourIndent); 20850 } 20851 20852 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) { 20853 FormatStyle ZeroColumn = getLLVMStyle(); 20854 ZeroColumn.ColumnLimit = 0; 20855 20856 verifyFormat("[[SessionService sharedService] " 20857 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 20858 " if (window) {\n" 20859 " [self windowDidLoad:window];\n" 20860 " } else {\n" 20861 " [self errorLoadingWindow];\n" 20862 " }\n" 20863 "}];", 20864 ZeroColumn); 20865 EXPECT_EQ("[[SessionService sharedService]\n" 20866 " loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 20867 " if (window) {\n" 20868 " [self windowDidLoad:window];\n" 20869 " } else {\n" 20870 " [self errorLoadingWindow];\n" 20871 " }\n" 20872 " }];", 20873 format("[[SessionService sharedService]\n" 20874 "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n" 20875 " if (window) {\n" 20876 " [self windowDidLoad:window];\n" 20877 " } else {\n" 20878 " [self errorLoadingWindow];\n" 20879 " }\n" 20880 "}];", 20881 ZeroColumn)); 20882 verifyFormat("[myObject doSomethingWith:arg1\n" 20883 " firstBlock:^(Foo *a) {\n" 20884 " // ...\n" 20885 " int i;\n" 20886 " }\n" 20887 " secondBlock:^(Bar *b) {\n" 20888 " // ...\n" 20889 " int i;\n" 20890 " }\n" 20891 " thirdBlock:^Foo(Bar *b) {\n" 20892 " // ...\n" 20893 " int i;\n" 20894 " }];", 20895 ZeroColumn); 20896 verifyFormat("f(^{\n" 20897 " @autoreleasepool {\n" 20898 " if (a) {\n" 20899 " g();\n" 20900 " }\n" 20901 " }\n" 20902 "});", 20903 ZeroColumn); 20904 verifyFormat("void (^largeBlock)(void) = ^{\n" 20905 " // ...\n" 20906 "};", 20907 ZeroColumn); 20908 20909 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; 20910 EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };", 20911 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn)); 20912 ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 20913 EXPECT_EQ("void (^largeBlock)(void) = ^{\n" 20914 " int i;\n" 20915 "};", 20916 format("void (^largeBlock)(void) = ^{ int i; };", ZeroColumn)); 20917 } 20918 20919 TEST_F(FormatTest, SupportsCRLF) { 20920 EXPECT_EQ("int a;\r\n" 20921 "int b;\r\n" 20922 "int c;\r\n", 20923 format("int a;\r\n" 20924 " int b;\r\n" 20925 " int c;\r\n", 20926 getLLVMStyle())); 20927 EXPECT_EQ("int a;\r\n" 20928 "int b;\r\n" 20929 "int c;\r\n", 20930 format("int a;\r\n" 20931 " int b;\n" 20932 " int c;\r\n", 20933 getLLVMStyle())); 20934 EXPECT_EQ("int a;\n" 20935 "int b;\n" 20936 "int c;\n", 20937 format("int a;\r\n" 20938 " int b;\n" 20939 " int c;\n", 20940 getLLVMStyle())); 20941 EXPECT_EQ("\"aaaaaaa \"\r\n" 20942 "\"bbbbbbb\";\r\n", 20943 format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10))); 20944 EXPECT_EQ("#define A \\\r\n" 20945 " b; \\\r\n" 20946 " c; \\\r\n" 20947 " d;\r\n", 20948 format("#define A \\\r\n" 20949 " b; \\\r\n" 20950 " c; d; \r\n", 20951 getGoogleStyle())); 20952 20953 EXPECT_EQ("/*\r\n" 20954 "multi line block comments\r\n" 20955 "should not introduce\r\n" 20956 "an extra carriage return\r\n" 20957 "*/\r\n", 20958 format("/*\r\n" 20959 "multi line block comments\r\n" 20960 "should not introduce\r\n" 20961 "an extra carriage return\r\n" 20962 "*/\r\n")); 20963 EXPECT_EQ("/*\r\n" 20964 "\r\n" 20965 "*/", 20966 format("/*\r\n" 20967 " \r\r\r\n" 20968 "*/")); 20969 20970 FormatStyle style = getLLVMStyle(); 20971 20972 style.DeriveLineEnding = true; 20973 style.UseCRLF = false; 20974 EXPECT_EQ("union FooBarBazQux {\n" 20975 " int foo;\n" 20976 " int bar;\n" 20977 " int baz;\n" 20978 "};", 20979 format("union FooBarBazQux {\r\n" 20980 " int foo;\n" 20981 " int bar;\r\n" 20982 " int baz;\n" 20983 "};", 20984 style)); 20985 style.UseCRLF = true; 20986 EXPECT_EQ("union FooBarBazQux {\r\n" 20987 " int foo;\r\n" 20988 " int bar;\r\n" 20989 " int baz;\r\n" 20990 "};", 20991 format("union FooBarBazQux {\r\n" 20992 " int foo;\n" 20993 " int bar;\r\n" 20994 " int baz;\n" 20995 "};", 20996 style)); 20997 20998 style.DeriveLineEnding = false; 20999 style.UseCRLF = false; 21000 EXPECT_EQ("union FooBarBazQux {\n" 21001 " int foo;\n" 21002 " int bar;\n" 21003 " int baz;\n" 21004 " int qux;\n" 21005 "};", 21006 format("union FooBarBazQux {\r\n" 21007 " int foo;\n" 21008 " int bar;\r\n" 21009 " int baz;\n" 21010 " int qux;\r\n" 21011 "};", 21012 style)); 21013 style.UseCRLF = true; 21014 EXPECT_EQ("union FooBarBazQux {\r\n" 21015 " int foo;\r\n" 21016 " int bar;\r\n" 21017 " int baz;\r\n" 21018 " int qux;\r\n" 21019 "};", 21020 format("union FooBarBazQux {\r\n" 21021 " int foo;\n" 21022 " int bar;\r\n" 21023 " int baz;\n" 21024 " int qux;\n" 21025 "};", 21026 style)); 21027 21028 style.DeriveLineEnding = true; 21029 style.UseCRLF = false; 21030 EXPECT_EQ("union FooBarBazQux {\r\n" 21031 " int foo;\r\n" 21032 " int bar;\r\n" 21033 " int baz;\r\n" 21034 " int qux;\r\n" 21035 "};", 21036 format("union FooBarBazQux {\r\n" 21037 " int foo;\n" 21038 " int bar;\r\n" 21039 " int baz;\n" 21040 " int qux;\r\n" 21041 "};", 21042 style)); 21043 style.UseCRLF = true; 21044 EXPECT_EQ("union FooBarBazQux {\n" 21045 " int foo;\n" 21046 " int bar;\n" 21047 " int baz;\n" 21048 " int qux;\n" 21049 "};", 21050 format("union FooBarBazQux {\r\n" 21051 " int foo;\n" 21052 " int bar;\r\n" 21053 " int baz;\n" 21054 " int qux;\n" 21055 "};", 21056 style)); 21057 } 21058 21059 TEST_F(FormatTest, MunchSemicolonAfterBlocks) { 21060 verifyFormat("MY_CLASS(C) {\n" 21061 " int i;\n" 21062 " int j;\n" 21063 "};"); 21064 } 21065 21066 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) { 21067 FormatStyle TwoIndent = getLLVMStyleWithColumns(15); 21068 TwoIndent.ContinuationIndentWidth = 2; 21069 21070 EXPECT_EQ("int i =\n" 21071 " longFunction(\n" 21072 " arg);", 21073 format("int i = longFunction(arg);", TwoIndent)); 21074 21075 FormatStyle SixIndent = getLLVMStyleWithColumns(20); 21076 SixIndent.ContinuationIndentWidth = 6; 21077 21078 EXPECT_EQ("int i =\n" 21079 " longFunction(\n" 21080 " arg);", 21081 format("int i = longFunction(arg);", SixIndent)); 21082 } 21083 21084 TEST_F(FormatTest, WrappedClosingParenthesisIndent) { 21085 FormatStyle Style = getLLVMStyle(); 21086 verifyFormat("int Foo::getter(\n" 21087 " //\n" 21088 ") const {\n" 21089 " return foo;\n" 21090 "}", 21091 Style); 21092 verifyFormat("void Foo::setter(\n" 21093 " //\n" 21094 ") {\n" 21095 " foo = 1;\n" 21096 "}", 21097 Style); 21098 } 21099 21100 TEST_F(FormatTest, SpacesInAngles) { 21101 FormatStyle Spaces = getLLVMStyle(); 21102 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 21103 21104 verifyFormat("vector< ::std::string > x1;", Spaces); 21105 verifyFormat("Foo< int, Bar > x2;", Spaces); 21106 verifyFormat("Foo< ::int, ::Bar > x3;", Spaces); 21107 21108 verifyFormat("static_cast< int >(arg);", Spaces); 21109 verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces); 21110 verifyFormat("f< int, float >();", Spaces); 21111 verifyFormat("template <> g() {}", Spaces); 21112 verifyFormat("template < std::vector< int > > f() {}", Spaces); 21113 verifyFormat("std::function< void(int, int) > fct;", Spaces); 21114 verifyFormat("void inFunction() { std::function< void(int, int) > fct; }", 21115 Spaces); 21116 21117 Spaces.Standard = FormatStyle::LS_Cpp03; 21118 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 21119 verifyFormat("A< A< int > >();", Spaces); 21120 21121 Spaces.SpacesInAngles = FormatStyle::SIAS_Never; 21122 verifyFormat("A<A<int> >();", Spaces); 21123 21124 Spaces.SpacesInAngles = FormatStyle::SIAS_Leave; 21125 verifyFormat("vector< ::std::string> x4;", "vector<::std::string> x4;", 21126 Spaces); 21127 verifyFormat("vector< ::std::string > x4;", "vector<::std::string > x4;", 21128 Spaces); 21129 21130 verifyFormat("A<A<int> >();", Spaces); 21131 verifyFormat("A<A<int> >();", "A<A<int>>();", Spaces); 21132 verifyFormat("A< A< int > >();", Spaces); 21133 21134 Spaces.Standard = FormatStyle::LS_Cpp11; 21135 Spaces.SpacesInAngles = FormatStyle::SIAS_Always; 21136 verifyFormat("A< A< int > >();", Spaces); 21137 21138 Spaces.SpacesInAngles = FormatStyle::SIAS_Never; 21139 verifyFormat("vector<::std::string> x4;", Spaces); 21140 verifyFormat("vector<int> x5;", Spaces); 21141 verifyFormat("Foo<int, Bar> x6;", Spaces); 21142 verifyFormat("Foo<::int, ::Bar> x7;", Spaces); 21143 21144 verifyFormat("A<A<int>>();", Spaces); 21145 21146 Spaces.SpacesInAngles = FormatStyle::SIAS_Leave; 21147 verifyFormat("vector<::std::string> x4;", Spaces); 21148 verifyFormat("vector< ::std::string > x4;", Spaces); 21149 verifyFormat("vector<int> x5;", Spaces); 21150 verifyFormat("vector< int > x5;", Spaces); 21151 verifyFormat("Foo<int, Bar> x6;", Spaces); 21152 verifyFormat("Foo< int, Bar > x6;", Spaces); 21153 verifyFormat("Foo<::int, ::Bar> x7;", Spaces); 21154 verifyFormat("Foo< ::int, ::Bar > x7;", Spaces); 21155 21156 verifyFormat("A<A<int>>();", Spaces); 21157 verifyFormat("A< A< int > >();", Spaces); 21158 verifyFormat("A<A<int > >();", Spaces); 21159 verifyFormat("A< A< int>>();", Spaces); 21160 } 21161 21162 TEST_F(FormatTest, SpaceAfterTemplateKeyword) { 21163 FormatStyle Style = getLLVMStyle(); 21164 Style.SpaceAfterTemplateKeyword = false; 21165 verifyFormat("template<int> void foo();", Style); 21166 } 21167 21168 TEST_F(FormatTest, TripleAngleBrackets) { 21169 verifyFormat("f<<<1, 1>>>();"); 21170 verifyFormat("f<<<1, 1, 1, s>>>();"); 21171 verifyFormat("f<<<a, b, c, d>>>();"); 21172 EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();")); 21173 verifyFormat("f<param><<<1, 1>>>();"); 21174 verifyFormat("f<1><<<1, 1>>>();"); 21175 EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();")); 21176 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 21177 "aaaaaaaaaaa<<<\n 1, 1>>>();"); 21178 verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n" 21179 " <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();"); 21180 } 21181 21182 TEST_F(FormatTest, MergeLessLessAtEnd) { 21183 verifyFormat("<<"); 21184 EXPECT_EQ("< < <", format("\\\n<<<")); 21185 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 21186 "aaallvm::outs() <<"); 21187 verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" 21188 "aaaallvm::outs()\n <<"); 21189 } 21190 21191 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) { 21192 std::string code = "#if A\n" 21193 "#if B\n" 21194 "a.\n" 21195 "#endif\n" 21196 " a = 1;\n" 21197 "#else\n" 21198 "#endif\n" 21199 "#if C\n" 21200 "#else\n" 21201 "#endif\n"; 21202 EXPECT_EQ(code, format(code)); 21203 } 21204 21205 TEST_F(FormatTest, HandleConflictMarkers) { 21206 // Git/SVN conflict markers. 21207 EXPECT_EQ("int a;\n" 21208 "void f() {\n" 21209 " callme(some(parameter1,\n" 21210 "<<<<<<< text by the vcs\n" 21211 " parameter2),\n" 21212 "||||||| text by the vcs\n" 21213 " parameter2),\n" 21214 " parameter3,\n" 21215 "======= text by the vcs\n" 21216 " parameter2, parameter3),\n" 21217 ">>>>>>> text by the vcs\n" 21218 " otherparameter);\n", 21219 format("int a;\n" 21220 "void f() {\n" 21221 " callme(some(parameter1,\n" 21222 "<<<<<<< text by the vcs\n" 21223 " parameter2),\n" 21224 "||||||| text by the vcs\n" 21225 " parameter2),\n" 21226 " parameter3,\n" 21227 "======= text by the vcs\n" 21228 " parameter2,\n" 21229 " parameter3),\n" 21230 ">>>>>>> text by the vcs\n" 21231 " otherparameter);\n")); 21232 21233 // Perforce markers. 21234 EXPECT_EQ("void f() {\n" 21235 " function(\n" 21236 ">>>> text by the vcs\n" 21237 " parameter,\n" 21238 "==== text by the vcs\n" 21239 " parameter,\n" 21240 "==== text by the vcs\n" 21241 " parameter,\n" 21242 "<<<< text by the vcs\n" 21243 " parameter);\n", 21244 format("void f() {\n" 21245 " function(\n" 21246 ">>>> text by the vcs\n" 21247 " parameter,\n" 21248 "==== text by the vcs\n" 21249 " parameter,\n" 21250 "==== text by the vcs\n" 21251 " parameter,\n" 21252 "<<<< text by the vcs\n" 21253 " parameter);\n")); 21254 21255 EXPECT_EQ("<<<<<<<\n" 21256 "|||||||\n" 21257 "=======\n" 21258 ">>>>>>>", 21259 format("<<<<<<<\n" 21260 "|||||||\n" 21261 "=======\n" 21262 ">>>>>>>")); 21263 21264 EXPECT_EQ("<<<<<<<\n" 21265 "|||||||\n" 21266 "int i;\n" 21267 "=======\n" 21268 ">>>>>>>", 21269 format("<<<<<<<\n" 21270 "|||||||\n" 21271 "int i;\n" 21272 "=======\n" 21273 ">>>>>>>")); 21274 21275 // FIXME: Handle parsing of macros around conflict markers correctly: 21276 EXPECT_EQ("#define Macro \\\n" 21277 "<<<<<<<\n" 21278 "Something \\\n" 21279 "|||||||\n" 21280 "Else \\\n" 21281 "=======\n" 21282 "Other \\\n" 21283 ">>>>>>>\n" 21284 " End int i;\n", 21285 format("#define Macro \\\n" 21286 "<<<<<<<\n" 21287 " Something \\\n" 21288 "|||||||\n" 21289 " Else \\\n" 21290 "=======\n" 21291 " Other \\\n" 21292 ">>>>>>>\n" 21293 " End\n" 21294 "int i;\n")); 21295 21296 verifyFormat(R"(==== 21297 #ifdef A 21298 a 21299 #else 21300 b 21301 #endif 21302 )"); 21303 } 21304 21305 TEST_F(FormatTest, DisableRegions) { 21306 EXPECT_EQ("int i;\n" 21307 "// clang-format off\n" 21308 " int j;\n" 21309 "// clang-format on\n" 21310 "int k;", 21311 format(" int i;\n" 21312 " // clang-format off\n" 21313 " int j;\n" 21314 " // clang-format on\n" 21315 " int k;")); 21316 EXPECT_EQ("int i;\n" 21317 "/* clang-format off */\n" 21318 " int j;\n" 21319 "/* clang-format on */\n" 21320 "int k;", 21321 format(" int i;\n" 21322 " /* clang-format off */\n" 21323 " int j;\n" 21324 " /* clang-format on */\n" 21325 " int k;")); 21326 21327 // Don't reflow comments within disabled regions. 21328 EXPECT_EQ("// clang-format off\n" 21329 "// long long long long long long line\n" 21330 "/* clang-format on */\n" 21331 "/* long long long\n" 21332 " * long long long\n" 21333 " * line */\n" 21334 "int i;\n" 21335 "/* clang-format off */\n" 21336 "/* long long long long long long line */\n", 21337 format("// clang-format off\n" 21338 "// long long long long long long line\n" 21339 "/* clang-format on */\n" 21340 "/* long long long long long long line */\n" 21341 "int i;\n" 21342 "/* clang-format off */\n" 21343 "/* long long long long long long line */\n", 21344 getLLVMStyleWithColumns(20))); 21345 } 21346 21347 TEST_F(FormatTest, DoNotCrashOnInvalidInput) { 21348 format("? ) ="); 21349 verifyNoCrash("#define a\\\n /**/}"); 21350 } 21351 21352 TEST_F(FormatTest, FormatsTableGenCode) { 21353 FormatStyle Style = getLLVMStyle(); 21354 Style.Language = FormatStyle::LK_TableGen; 21355 verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style); 21356 } 21357 21358 TEST_F(FormatTest, ArrayOfTemplates) { 21359 EXPECT_EQ("auto a = new unique_ptr<int>[10];", 21360 format("auto a = new unique_ptr<int > [ 10];")); 21361 21362 FormatStyle Spaces = getLLVMStyle(); 21363 Spaces.SpacesInSquareBrackets = true; 21364 EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];", 21365 format("auto a = new unique_ptr<int > [10];", Spaces)); 21366 } 21367 21368 TEST_F(FormatTest, ArrayAsTemplateType) { 21369 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;", 21370 format("auto a = unique_ptr < Foo < Bar>[ 10]> ;")); 21371 21372 FormatStyle Spaces = getLLVMStyle(); 21373 Spaces.SpacesInSquareBrackets = true; 21374 EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;", 21375 format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces)); 21376 } 21377 21378 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); } 21379 21380 TEST(FormatStyle, GetStyleWithEmptyFileName) { 21381 llvm::vfs::InMemoryFileSystem FS; 21382 auto Style1 = getStyle("file", "", "Google", "", &FS); 21383 ASSERT_TRUE((bool)Style1); 21384 ASSERT_EQ(*Style1, getGoogleStyle()); 21385 } 21386 21387 TEST(FormatStyle, GetStyleOfFile) { 21388 llvm::vfs::InMemoryFileSystem FS; 21389 // Test 1: format file in the same directory. 21390 ASSERT_TRUE( 21391 FS.addFile("/a/.clang-format", 0, 21392 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM"))); 21393 ASSERT_TRUE( 21394 FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 21395 auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS); 21396 ASSERT_TRUE((bool)Style1); 21397 ASSERT_EQ(*Style1, getLLVMStyle()); 21398 21399 // Test 2.1: fallback to default. 21400 ASSERT_TRUE( 21401 FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 21402 auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS); 21403 ASSERT_TRUE((bool)Style2); 21404 ASSERT_EQ(*Style2, getMozillaStyle()); 21405 21406 // Test 2.2: no format on 'none' fallback style. 21407 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS); 21408 ASSERT_TRUE((bool)Style2); 21409 ASSERT_EQ(*Style2, getNoStyle()); 21410 21411 // Test 2.3: format if config is found with no based style while fallback is 21412 // 'none'. 21413 ASSERT_TRUE(FS.addFile("/b/.clang-format", 0, 21414 llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2"))); 21415 Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS); 21416 ASSERT_TRUE((bool)Style2); 21417 ASSERT_EQ(*Style2, getLLVMStyle()); 21418 21419 // Test 2.4: format if yaml with no based style, while fallback is 'none'. 21420 Style2 = getStyle("{}", "a.h", "none", "", &FS); 21421 ASSERT_TRUE((bool)Style2); 21422 ASSERT_EQ(*Style2, getLLVMStyle()); 21423 21424 // Test 3: format file in parent directory. 21425 ASSERT_TRUE( 21426 FS.addFile("/c/.clang-format", 0, 21427 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google"))); 21428 ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0, 21429 llvm::MemoryBuffer::getMemBuffer("int i;"))); 21430 auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS); 21431 ASSERT_TRUE((bool)Style3); 21432 ASSERT_EQ(*Style3, getGoogleStyle()); 21433 21434 // Test 4: error on invalid fallback style 21435 auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS); 21436 ASSERT_FALSE((bool)Style4); 21437 llvm::consumeError(Style4.takeError()); 21438 21439 // Test 5: error on invalid yaml on command line 21440 auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS); 21441 ASSERT_FALSE((bool)Style5); 21442 llvm::consumeError(Style5.takeError()); 21443 21444 // Test 6: error on invalid style 21445 auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS); 21446 ASSERT_FALSE((bool)Style6); 21447 llvm::consumeError(Style6.takeError()); 21448 21449 // Test 7: found config file, error on parsing it 21450 ASSERT_TRUE( 21451 FS.addFile("/d/.clang-format", 0, 21452 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n" 21453 "InvalidKey: InvalidValue"))); 21454 ASSERT_TRUE( 21455 FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;"))); 21456 auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS); 21457 ASSERT_FALSE((bool)Style7a); 21458 llvm::consumeError(Style7a.takeError()); 21459 21460 auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true); 21461 ASSERT_TRUE((bool)Style7b); 21462 21463 // Test 8: inferred per-language defaults apply. 21464 auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS); 21465 ASSERT_TRUE((bool)StyleTd); 21466 ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen)); 21467 21468 // Test 9.1: overwriting a file style, when parent no file exists with no 21469 // fallback style 21470 ASSERT_TRUE(FS.addFile( 21471 "/e/sub/.clang-format", 0, 21472 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n" 21473 "ColumnLimit: 20"))); 21474 ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0, 21475 llvm::MemoryBuffer::getMemBuffer("int i;"))); 21476 auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS); 21477 ASSERT_TRUE(static_cast<bool>(Style9)); 21478 ASSERT_EQ(*Style9, [] { 21479 auto Style = getNoStyle(); 21480 Style.ColumnLimit = 20; 21481 return Style; 21482 }()); 21483 21484 // Test 9.2: with LLVM fallback style 21485 Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS); 21486 ASSERT_TRUE(static_cast<bool>(Style9)); 21487 ASSERT_EQ(*Style9, [] { 21488 auto Style = getLLVMStyle(); 21489 Style.ColumnLimit = 20; 21490 return Style; 21491 }()); 21492 21493 // Test 9.3: with a parent file 21494 ASSERT_TRUE( 21495 FS.addFile("/e/.clang-format", 0, 21496 llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n" 21497 "UseTab: Always"))); 21498 Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS); 21499 ASSERT_TRUE(static_cast<bool>(Style9)); 21500 ASSERT_EQ(*Style9, [] { 21501 auto Style = getGoogleStyle(); 21502 Style.ColumnLimit = 20; 21503 Style.UseTab = FormatStyle::UT_Always; 21504 return Style; 21505 }()); 21506 21507 // Test 9.4: propagate more than one level 21508 ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0, 21509 llvm::MemoryBuffer::getMemBuffer("int i;"))); 21510 ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0, 21511 llvm::MemoryBuffer::getMemBuffer( 21512 "BasedOnStyle: InheritParentConfig\n" 21513 "WhitespaceSensitiveMacros: ['FOO', 'BAR']"))); 21514 std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"}; 21515 21516 const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] { 21517 auto Style = getGoogleStyle(); 21518 Style.ColumnLimit = 20; 21519 Style.UseTab = FormatStyle::UT_Always; 21520 Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros; 21521 return Style; 21522 }(); 21523 21524 ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros); 21525 Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS); 21526 ASSERT_TRUE(static_cast<bool>(Style9)); 21527 ASSERT_EQ(*Style9, SubSubStyle); 21528 21529 // Test 9.5: use InheritParentConfig as style name 21530 Style9 = 21531 getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS); 21532 ASSERT_TRUE(static_cast<bool>(Style9)); 21533 ASSERT_EQ(*Style9, SubSubStyle); 21534 21535 // Test 9.6: use command line style with inheritance 21536 Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp", 21537 "none", "", &FS); 21538 ASSERT_TRUE(static_cast<bool>(Style9)); 21539 ASSERT_EQ(*Style9, SubSubStyle); 21540 21541 // Test 9.7: use command line style with inheritance and own config 21542 Style9 = getStyle("{BasedOnStyle: InheritParentConfig, " 21543 "WhitespaceSensitiveMacros: ['FOO', 'BAR']}", 21544 "/e/sub/code.cpp", "none", "", &FS); 21545 ASSERT_TRUE(static_cast<bool>(Style9)); 21546 ASSERT_EQ(*Style9, SubSubStyle); 21547 21548 // Test 9.8: use inheritance from a file without BasedOnStyle 21549 ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0, 21550 llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123"))); 21551 ASSERT_TRUE( 21552 FS.addFile("/e/withoutbase/sub/.clang-format", 0, 21553 llvm::MemoryBuffer::getMemBuffer( 21554 "BasedOnStyle: InheritParentConfig\nIndentWidth: 7"))); 21555 // Make sure we do not use the fallback style 21556 Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS); 21557 ASSERT_TRUE(static_cast<bool>(Style9)); 21558 ASSERT_EQ(*Style9, [] { 21559 auto Style = getLLVMStyle(); 21560 Style.ColumnLimit = 123; 21561 return Style; 21562 }()); 21563 21564 Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS); 21565 ASSERT_TRUE(static_cast<bool>(Style9)); 21566 ASSERT_EQ(*Style9, [] { 21567 auto Style = getLLVMStyle(); 21568 Style.ColumnLimit = 123; 21569 Style.IndentWidth = 7; 21570 return Style; 21571 }()); 21572 } 21573 21574 TEST_F(ReplacementTest, FormatCodeAfterReplacements) { 21575 // Column limit is 20. 21576 std::string Code = "Type *a =\n" 21577 " new Type();\n" 21578 "g(iiiii, 0, jjjjj,\n" 21579 " 0, kkkkk, 0, mm);\n" 21580 "int bad = format ;"; 21581 std::string Expected = "auto a = new Type();\n" 21582 "g(iiiii, nullptr,\n" 21583 " jjjjj, nullptr,\n" 21584 " kkkkk, nullptr,\n" 21585 " mm);\n" 21586 "int bad = format ;"; 21587 FileID ID = Context.createInMemoryFile("format.cpp", Code); 21588 tooling::Replacements Replaces = toReplacements( 21589 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6, 21590 "auto "), 21591 tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1, 21592 "nullptr"), 21593 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1, 21594 "nullptr"), 21595 tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1, 21596 "nullptr")}); 21597 21598 FormatStyle Style = getLLVMStyle(); 21599 Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility. 21600 auto FormattedReplaces = formatReplacements(Code, Replaces, Style); 21601 EXPECT_TRUE(static_cast<bool>(FormattedReplaces)) 21602 << llvm::toString(FormattedReplaces.takeError()) << "\n"; 21603 auto Result = applyAllReplacements(Code, *FormattedReplaces); 21604 EXPECT_TRUE(static_cast<bool>(Result)); 21605 EXPECT_EQ(Expected, *Result); 21606 } 21607 21608 TEST_F(ReplacementTest, SortIncludesAfterReplacement) { 21609 std::string Code = "#include \"a.h\"\n" 21610 "#include \"c.h\"\n" 21611 "\n" 21612 "int main() {\n" 21613 " return 0;\n" 21614 "}"; 21615 std::string Expected = "#include \"a.h\"\n" 21616 "#include \"b.h\"\n" 21617 "#include \"c.h\"\n" 21618 "\n" 21619 "int main() {\n" 21620 " return 0;\n" 21621 "}"; 21622 FileID ID = Context.createInMemoryFile("fix.cpp", Code); 21623 tooling::Replacements Replaces = toReplacements( 21624 {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0, 21625 "#include \"b.h\"\n")}); 21626 21627 FormatStyle Style = getLLVMStyle(); 21628 Style.SortIncludes = FormatStyle::SI_CaseSensitive; 21629 auto FormattedReplaces = formatReplacements(Code, Replaces, Style); 21630 EXPECT_TRUE(static_cast<bool>(FormattedReplaces)) 21631 << llvm::toString(FormattedReplaces.takeError()) << "\n"; 21632 auto Result = applyAllReplacements(Code, *FormattedReplaces); 21633 EXPECT_TRUE(static_cast<bool>(Result)); 21634 EXPECT_EQ(Expected, *Result); 21635 } 21636 21637 TEST_F(FormatTest, FormatSortsUsingDeclarations) { 21638 EXPECT_EQ("using std::cin;\n" 21639 "using std::cout;", 21640 format("using std::cout;\n" 21641 "using std::cin;", 21642 getGoogleStyle())); 21643 } 21644 21645 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) { 21646 FormatStyle Style = getLLVMStyle(); 21647 Style.Standard = FormatStyle::LS_Cpp03; 21648 // cpp03 recognize this string as identifier u8 and literal character 'a' 21649 EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style)); 21650 } 21651 21652 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) { 21653 // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers 21654 // all modes, including C++11, C++14 and C++17 21655 EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';")); 21656 } 21657 21658 TEST_F(FormatTest, DoNotFormatLikelyXml) { 21659 EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle())); 21660 EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle())); 21661 } 21662 21663 TEST_F(FormatTest, StructuredBindings) { 21664 // Structured bindings is a C++17 feature. 21665 // all modes, including C++11, C++14 and C++17 21666 verifyFormat("auto [a, b] = f();"); 21667 EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();")); 21668 EXPECT_EQ("const auto [a, b] = f();", format("const auto[a, b] = f();")); 21669 EXPECT_EQ("auto const [a, b] = f();", format("auto const[a, b] = f();")); 21670 EXPECT_EQ("auto const volatile [a, b] = f();", 21671 format("auto const volatile[a, b] = f();")); 21672 EXPECT_EQ("auto [a, b, c] = f();", format("auto [ a , b,c ] = f();")); 21673 EXPECT_EQ("auto &[a, b, c] = f();", 21674 format("auto &[ a , b,c ] = f();")); 21675 EXPECT_EQ("auto &&[a, b, c] = f();", 21676 format("auto &&[ a , b,c ] = f();")); 21677 EXPECT_EQ("auto const &[a, b] = f();", format("auto const&[a, b] = f();")); 21678 EXPECT_EQ("auto const volatile &&[a, b] = f();", 21679 format("auto const volatile &&[a, b] = f();")); 21680 EXPECT_EQ("auto const &&[a, b] = f();", 21681 format("auto const && [a, b] = f();")); 21682 EXPECT_EQ("const auto &[a, b] = f();", 21683 format("const auto & [a, b] = f();")); 21684 EXPECT_EQ("const auto volatile &&[a, b] = f();", 21685 format("const auto volatile &&[a, b] = f();")); 21686 EXPECT_EQ("volatile const auto &&[a, b] = f();", 21687 format("volatile const auto &&[a, b] = f();")); 21688 EXPECT_EQ("const auto &&[a, b] = f();", 21689 format("const auto && [a, b] = f();")); 21690 21691 // Make sure we don't mistake structured bindings for lambdas. 21692 FormatStyle PointerMiddle = getLLVMStyle(); 21693 PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle; 21694 verifyFormat("auto [a1, b]{A * i};", getGoogleStyle()); 21695 verifyFormat("auto [a2, b]{A * i};", getLLVMStyle()); 21696 verifyFormat("auto [a3, b]{A * i};", PointerMiddle); 21697 verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle()); 21698 verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle()); 21699 verifyFormat("auto const [a3, b]{A * i};", PointerMiddle); 21700 verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle()); 21701 verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle()); 21702 verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle); 21703 verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle()); 21704 verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle()); 21705 verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle); 21706 21707 EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}", 21708 format("for (const auto && [a, b] : some_range) {\n}")); 21709 EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}", 21710 format("for (const auto & [a, b] : some_range) {\n}")); 21711 EXPECT_EQ("for (const auto [a, b] : some_range) {\n}", 21712 format("for (const auto[a, b] : some_range) {\n}")); 21713 EXPECT_EQ("auto [x, y](expr);", format("auto[x,y] (expr);")); 21714 EXPECT_EQ("auto &[x, y](expr);", format("auto & [x,y] (expr);")); 21715 EXPECT_EQ("auto &&[x, y](expr);", format("auto && [x,y] (expr);")); 21716 EXPECT_EQ("auto const &[x, y](expr);", 21717 format("auto const & [x,y] (expr);")); 21718 EXPECT_EQ("auto const &&[x, y](expr);", 21719 format("auto const && [x,y] (expr);")); 21720 EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y] {expr};")); 21721 EXPECT_EQ("auto const &[x, y]{expr};", 21722 format("auto const & [x,y] {expr};")); 21723 EXPECT_EQ("auto const &&[x, y]{expr};", 21724 format("auto const && [x,y] {expr};")); 21725 21726 FormatStyle Spaces = getLLVMStyle(); 21727 Spaces.SpacesInSquareBrackets = true; 21728 verifyFormat("auto [ a, b ] = f();", Spaces); 21729 verifyFormat("auto &&[ a, b ] = f();", Spaces); 21730 verifyFormat("auto &[ a, b ] = f();", Spaces); 21731 verifyFormat("auto const &&[ a, b ] = f();", Spaces); 21732 verifyFormat("auto const &[ a, b ] = f();", Spaces); 21733 } 21734 21735 TEST_F(FormatTest, FileAndCode) { 21736 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", "")); 21737 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", "")); 21738 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", "")); 21739 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "")); 21740 EXPECT_EQ(FormatStyle::LK_ObjC, 21741 guessLanguage("foo.h", "@interface Foo\n@end\n")); 21742 EXPECT_EQ( 21743 FormatStyle::LK_ObjC, 21744 guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }")); 21745 EXPECT_EQ(FormatStyle::LK_ObjC, 21746 guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))")); 21747 EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;")); 21748 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", "")); 21749 EXPECT_EQ(FormatStyle::LK_ObjC, 21750 guessLanguage("foo", "@interface Foo\n@end\n")); 21751 EXPECT_EQ(FormatStyle::LK_ObjC, 21752 guessLanguage("foo.h", "int DoStuff(CGRect rect);\n")); 21753 EXPECT_EQ( 21754 FormatStyle::LK_ObjC, 21755 guessLanguage("foo.h", 21756 "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n")); 21757 EXPECT_EQ( 21758 FormatStyle::LK_Cpp, 21759 guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;")); 21760 } 21761 21762 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) { 21763 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];")); 21764 EXPECT_EQ(FormatStyle::LK_ObjC, 21765 guessLanguage("foo.h", "array[[calculator getIndex]];")); 21766 EXPECT_EQ(FormatStyle::LK_Cpp, 21767 guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];")); 21768 EXPECT_EQ( 21769 FormatStyle::LK_Cpp, 21770 guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];")); 21771 EXPECT_EQ(FormatStyle::LK_ObjC, 21772 guessLanguage("foo.h", "[[noreturn foo] bar];")); 21773 EXPECT_EQ(FormatStyle::LK_Cpp, 21774 guessLanguage("foo.h", "[[clang::fallthrough]];")); 21775 EXPECT_EQ(FormatStyle::LK_ObjC, 21776 guessLanguage("foo.h", "[[clang:fallthrough] foo];")); 21777 EXPECT_EQ(FormatStyle::LK_Cpp, 21778 guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];")); 21779 EXPECT_EQ(FormatStyle::LK_Cpp, 21780 guessLanguage("foo.h", "[[using clang: fallthrough]];")); 21781 EXPECT_EQ(FormatStyle::LK_ObjC, 21782 guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];")); 21783 EXPECT_EQ(FormatStyle::LK_Cpp, 21784 guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];")); 21785 EXPECT_EQ( 21786 FormatStyle::LK_Cpp, 21787 guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)")); 21788 EXPECT_EQ( 21789 FormatStyle::LK_Cpp, 21790 guessLanguage("foo.h", 21791 "[[clang::callable_when(\"unconsumed\", \"unknown\")]]")); 21792 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]")); 21793 } 21794 21795 TEST_F(FormatTest, GuessLanguageWithCaret) { 21796 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);")); 21797 EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);")); 21798 EXPECT_EQ(FormatStyle::LK_ObjC, 21799 guessLanguage("foo.h", "int(^)(char, float);")); 21800 EXPECT_EQ(FormatStyle::LK_ObjC, 21801 guessLanguage("foo.h", "int(^foo)(char, float);")); 21802 EXPECT_EQ(FormatStyle::LK_ObjC, 21803 guessLanguage("foo.h", "int(^foo[10])(char, float);")); 21804 EXPECT_EQ(FormatStyle::LK_ObjC, 21805 guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);")); 21806 EXPECT_EQ( 21807 FormatStyle::LK_ObjC, 21808 guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);")); 21809 } 21810 21811 TEST_F(FormatTest, GuessLanguageWithPragmas) { 21812 EXPECT_EQ(FormatStyle::LK_Cpp, 21813 guessLanguage("foo.h", "__pragma(warning(disable:))")); 21814 EXPECT_EQ(FormatStyle::LK_Cpp, 21815 guessLanguage("foo.h", "#pragma(warning(disable:))")); 21816 EXPECT_EQ(FormatStyle::LK_Cpp, 21817 guessLanguage("foo.h", "_Pragma(warning(disable:))")); 21818 } 21819 21820 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) { 21821 // ASM symbolic names are identifiers that must be surrounded by [] without 21822 // space in between: 21823 // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands 21824 21825 // Example from https://bugs.llvm.org/show_bug.cgi?id=45108. 21826 verifyFormat(R"(// 21827 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result)); 21828 )"); 21829 21830 // A list of several ASM symbolic names. 21831 verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)"); 21832 21833 // ASM symbolic names in inline ASM with inputs and outputs. 21834 verifyFormat(R"(// 21835 asm("cmoveq %1, %2, %[result]" 21836 : [result] "=r"(result) 21837 : "r"(test), "r"(new), "[result]"(old)); 21838 )"); 21839 21840 // ASM symbolic names in inline ASM with no outputs. 21841 verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)"); 21842 } 21843 21844 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) { 21845 EXPECT_EQ(FormatStyle::LK_Cpp, 21846 guessLanguage("foo.h", "void f() {\n" 21847 " asm (\"mov %[e], %[d]\"\n" 21848 " : [d] \"=rm\" (d)\n" 21849 " [e] \"rm\" (*e));\n" 21850 "}")); 21851 EXPECT_EQ(FormatStyle::LK_Cpp, 21852 guessLanguage("foo.h", "void f() {\n" 21853 " _asm (\"mov %[e], %[d]\"\n" 21854 " : [d] \"=rm\" (d)\n" 21855 " [e] \"rm\" (*e));\n" 21856 "}")); 21857 EXPECT_EQ(FormatStyle::LK_Cpp, 21858 guessLanguage("foo.h", "void f() {\n" 21859 " __asm (\"mov %[e], %[d]\"\n" 21860 " : [d] \"=rm\" (d)\n" 21861 " [e] \"rm\" (*e));\n" 21862 "}")); 21863 EXPECT_EQ(FormatStyle::LK_Cpp, 21864 guessLanguage("foo.h", "void f() {\n" 21865 " __asm__ (\"mov %[e], %[d]\"\n" 21866 " : [d] \"=rm\" (d)\n" 21867 " [e] \"rm\" (*e));\n" 21868 "}")); 21869 EXPECT_EQ(FormatStyle::LK_Cpp, 21870 guessLanguage("foo.h", "void f() {\n" 21871 " asm (\"mov %[e], %[d]\"\n" 21872 " : [d] \"=rm\" (d),\n" 21873 " [e] \"rm\" (*e));\n" 21874 "}")); 21875 EXPECT_EQ(FormatStyle::LK_Cpp, 21876 guessLanguage("foo.h", "void f() {\n" 21877 " asm volatile (\"mov %[e], %[d]\"\n" 21878 " : [d] \"=rm\" (d)\n" 21879 " [e] \"rm\" (*e));\n" 21880 "}")); 21881 } 21882 21883 TEST_F(FormatTest, GuessLanguageWithChildLines) { 21884 EXPECT_EQ(FormatStyle::LK_Cpp, 21885 guessLanguage("foo.h", "#define FOO ({ std::string s; })")); 21886 EXPECT_EQ(FormatStyle::LK_ObjC, 21887 guessLanguage("foo.h", "#define FOO ({ NSString *s; })")); 21888 EXPECT_EQ( 21889 FormatStyle::LK_Cpp, 21890 guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })")); 21891 EXPECT_EQ( 21892 FormatStyle::LK_ObjC, 21893 guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })")); 21894 } 21895 21896 TEST_F(FormatTest, TypenameMacros) { 21897 std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"}; 21898 21899 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353 21900 FormatStyle Google = getGoogleStyleWithColumns(0); 21901 Google.TypenameMacros = TypenameMacros; 21902 verifyFormat("struct foo {\n" 21903 " int bar;\n" 21904 " TAILQ_ENTRY(a) bleh;\n" 21905 "};", 21906 Google); 21907 21908 FormatStyle Macros = getLLVMStyle(); 21909 Macros.TypenameMacros = TypenameMacros; 21910 21911 verifyFormat("STACK_OF(int) a;", Macros); 21912 verifyFormat("STACK_OF(int) *a;", Macros); 21913 verifyFormat("STACK_OF(int const *) *a;", Macros); 21914 verifyFormat("STACK_OF(int *const) *a;", Macros); 21915 verifyFormat("STACK_OF(int, string) a;", Macros); 21916 verifyFormat("STACK_OF(LIST(int)) a;", Macros); 21917 verifyFormat("STACK_OF(LIST(int)) a, b;", Macros); 21918 verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros); 21919 verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros); 21920 verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros); 21921 verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros); 21922 21923 Macros.PointerAlignment = FormatStyle::PAS_Left; 21924 verifyFormat("STACK_OF(int)* a;", Macros); 21925 verifyFormat("STACK_OF(int*)* a;", Macros); 21926 verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros); 21927 verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros); 21928 verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros); 21929 } 21930 21931 TEST_F(FormatTest, AtomicQualifier) { 21932 // Check that we treate _Atomic as a type and not a function call 21933 FormatStyle Google = getGoogleStyleWithColumns(0); 21934 verifyFormat("struct foo {\n" 21935 " int a1;\n" 21936 " _Atomic(a) a2;\n" 21937 " _Atomic(_Atomic(int) *const) a3;\n" 21938 "};", 21939 Google); 21940 verifyFormat("_Atomic(uint64_t) a;"); 21941 verifyFormat("_Atomic(uint64_t) *a;"); 21942 verifyFormat("_Atomic(uint64_t const *) *a;"); 21943 verifyFormat("_Atomic(uint64_t *const) *a;"); 21944 verifyFormat("_Atomic(const uint64_t *) *a;"); 21945 verifyFormat("_Atomic(uint64_t) a;"); 21946 verifyFormat("_Atomic(_Atomic(uint64_t)) a;"); 21947 verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;"); 21948 verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}"); 21949 verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);"); 21950 21951 verifyFormat("_Atomic(uint64_t) *s(InitValue);"); 21952 verifyFormat("_Atomic(uint64_t) *s{InitValue};"); 21953 FormatStyle Style = getLLVMStyle(); 21954 Style.PointerAlignment = FormatStyle::PAS_Left; 21955 verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style); 21956 verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style); 21957 verifyFormat("_Atomic(int)* a;", Style); 21958 verifyFormat("_Atomic(int*)* a;", Style); 21959 verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style); 21960 21961 Style.SpacesInCStyleCastParentheses = true; 21962 Style.SpacesInParentheses = false; 21963 verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style); 21964 Style.SpacesInCStyleCastParentheses = false; 21965 Style.SpacesInParentheses = true; 21966 verifyFormat("x = (_Atomic( uint64_t ))*a;", Style); 21967 verifyFormat("x = (_Atomic( uint64_t ))&a;", Style); 21968 } 21969 21970 TEST_F(FormatTest, AmbersandInLamda) { 21971 // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899 21972 FormatStyle AlignStyle = getLLVMStyle(); 21973 AlignStyle.PointerAlignment = FormatStyle::PAS_Left; 21974 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle); 21975 AlignStyle.PointerAlignment = FormatStyle::PAS_Right; 21976 verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle); 21977 } 21978 21979 TEST_F(FormatTest, SpacesInConditionalStatement) { 21980 FormatStyle Spaces = getLLVMStyle(); 21981 Spaces.IfMacros.clear(); 21982 Spaces.IfMacros.push_back("MYIF"); 21983 Spaces.SpacesInConditionalStatement = true; 21984 verifyFormat("for ( int i = 0; i; i++ )\n continue;", Spaces); 21985 verifyFormat("if ( !a )\n return;", Spaces); 21986 verifyFormat("if ( a )\n return;", Spaces); 21987 verifyFormat("if constexpr ( a )\n return;", Spaces); 21988 verifyFormat("MYIF ( a )\n return;", Spaces); 21989 verifyFormat("MYIF ( a )\n return;\nelse MYIF ( b )\n return;", Spaces); 21990 verifyFormat("MYIF ( a )\n return;\nelse\n return;", Spaces); 21991 verifyFormat("switch ( a )\ncase 1:\n return;", Spaces); 21992 verifyFormat("while ( a )\n return;", Spaces); 21993 verifyFormat("while ( (a && b) )\n return;", Spaces); 21994 verifyFormat("do {\n} while ( 1 != 0 );", Spaces); 21995 verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces); 21996 // Check that space on the left of "::" is inserted as expected at beginning 21997 // of condition. 21998 verifyFormat("while ( ::func() )\n return;", Spaces); 21999 22000 // Check impact of ControlStatementsExceptControlMacros is honored. 22001 Spaces.SpaceBeforeParens = 22002 FormatStyle::SBPO_ControlStatementsExceptControlMacros; 22003 verifyFormat("MYIF( a )\n return;", Spaces); 22004 verifyFormat("MYIF( a )\n return;\nelse MYIF( b )\n return;", Spaces); 22005 verifyFormat("MYIF( a )\n return;\nelse\n return;", Spaces); 22006 } 22007 22008 TEST_F(FormatTest, AlternativeOperators) { 22009 // Test case for ensuring alternate operators are not 22010 // combined with their right most neighbour. 22011 verifyFormat("int a and b;"); 22012 verifyFormat("int a and_eq b;"); 22013 verifyFormat("int a bitand b;"); 22014 verifyFormat("int a bitor b;"); 22015 verifyFormat("int a compl b;"); 22016 verifyFormat("int a not b;"); 22017 verifyFormat("int a not_eq b;"); 22018 verifyFormat("int a or b;"); 22019 verifyFormat("int a xor b;"); 22020 verifyFormat("int a xor_eq b;"); 22021 verifyFormat("return this not_eq bitand other;"); 22022 verifyFormat("bool operator not_eq(const X bitand other)"); 22023 22024 verifyFormat("int a and 5;"); 22025 verifyFormat("int a and_eq 5;"); 22026 verifyFormat("int a bitand 5;"); 22027 verifyFormat("int a bitor 5;"); 22028 verifyFormat("int a compl 5;"); 22029 verifyFormat("int a not 5;"); 22030 verifyFormat("int a not_eq 5;"); 22031 verifyFormat("int a or 5;"); 22032 verifyFormat("int a xor 5;"); 22033 verifyFormat("int a xor_eq 5;"); 22034 22035 verifyFormat("int a compl(5);"); 22036 verifyFormat("int a not(5);"); 22037 22038 /* FIXME handle alternate tokens 22039 * https://en.cppreference.com/w/cpp/language/operator_alternative 22040 // alternative tokens 22041 verifyFormat("compl foo();"); // ~foo(); 22042 verifyFormat("foo() <%%>;"); // foo(); 22043 verifyFormat("void foo() <%%>;"); // void foo(){} 22044 verifyFormat("int a <:1:>;"); // int a[1];[ 22045 verifyFormat("%:define ABC abc"); // #define ABC abc 22046 verifyFormat("%:%:"); // ## 22047 */ 22048 } 22049 22050 TEST_F(FormatTest, STLWhileNotDefineChed) { 22051 verifyFormat("#if defined(while)\n" 22052 "#define while EMIT WARNING C4005\n" 22053 "#endif // while"); 22054 } 22055 22056 TEST_F(FormatTest, OperatorSpacing) { 22057 FormatStyle Style = getLLVMStyle(); 22058 Style.PointerAlignment = FormatStyle::PAS_Right; 22059 verifyFormat("Foo::operator*();", Style); 22060 verifyFormat("Foo::operator void *();", Style); 22061 verifyFormat("Foo::operator void **();", Style); 22062 verifyFormat("Foo::operator void *&();", Style); 22063 verifyFormat("Foo::operator void *&&();", Style); 22064 verifyFormat("Foo::operator void const *();", Style); 22065 verifyFormat("Foo::operator void const **();", Style); 22066 verifyFormat("Foo::operator void const *&();", Style); 22067 verifyFormat("Foo::operator void const *&&();", Style); 22068 verifyFormat("Foo::operator()(void *);", Style); 22069 verifyFormat("Foo::operator*(void *);", Style); 22070 verifyFormat("Foo::operator*();", Style); 22071 verifyFormat("Foo::operator**();", Style); 22072 verifyFormat("Foo::operator&();", Style); 22073 verifyFormat("Foo::operator<int> *();", Style); 22074 verifyFormat("Foo::operator<Foo> *();", Style); 22075 verifyFormat("Foo::operator<int> **();", Style); 22076 verifyFormat("Foo::operator<Foo> **();", Style); 22077 verifyFormat("Foo::operator<int> &();", Style); 22078 verifyFormat("Foo::operator<Foo> &();", Style); 22079 verifyFormat("Foo::operator<int> &&();", Style); 22080 verifyFormat("Foo::operator<Foo> &&();", Style); 22081 verifyFormat("Foo::operator<int> *&();", Style); 22082 verifyFormat("Foo::operator<Foo> *&();", Style); 22083 verifyFormat("Foo::operator<int> *&&();", Style); 22084 verifyFormat("Foo::operator<Foo> *&&();", Style); 22085 verifyFormat("operator*(int (*)(), class Foo);", Style); 22086 22087 verifyFormat("Foo::operator&();", Style); 22088 verifyFormat("Foo::operator void &();", Style); 22089 verifyFormat("Foo::operator void const &();", Style); 22090 verifyFormat("Foo::operator()(void &);", Style); 22091 verifyFormat("Foo::operator&(void &);", Style); 22092 verifyFormat("Foo::operator&();", Style); 22093 verifyFormat("operator&(int (&)(), class Foo);", Style); 22094 verifyFormat("operator&&(int (&)(), class Foo);", Style); 22095 22096 verifyFormat("Foo::operator&&();", Style); 22097 verifyFormat("Foo::operator**();", Style); 22098 verifyFormat("Foo::operator void &&();", Style); 22099 verifyFormat("Foo::operator void const &&();", Style); 22100 verifyFormat("Foo::operator()(void &&);", Style); 22101 verifyFormat("Foo::operator&&(void &&);", Style); 22102 verifyFormat("Foo::operator&&();", Style); 22103 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 22104 verifyFormat("operator const nsTArrayRight<E> &()", Style); 22105 verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()", 22106 Style); 22107 verifyFormat("operator void **()", Style); 22108 verifyFormat("operator const FooRight<Object> &()", Style); 22109 verifyFormat("operator const FooRight<Object> *()", Style); 22110 verifyFormat("operator const FooRight<Object> **()", Style); 22111 verifyFormat("operator const FooRight<Object> *&()", Style); 22112 verifyFormat("operator const FooRight<Object> *&&()", Style); 22113 22114 Style.PointerAlignment = FormatStyle::PAS_Left; 22115 verifyFormat("Foo::operator*();", Style); 22116 verifyFormat("Foo::operator**();", Style); 22117 verifyFormat("Foo::operator void*();", Style); 22118 verifyFormat("Foo::operator void**();", Style); 22119 verifyFormat("Foo::operator void*&();", Style); 22120 verifyFormat("Foo::operator void*&&();", Style); 22121 verifyFormat("Foo::operator void const*();", Style); 22122 verifyFormat("Foo::operator void const**();", Style); 22123 verifyFormat("Foo::operator void const*&();", Style); 22124 verifyFormat("Foo::operator void const*&&();", Style); 22125 verifyFormat("Foo::operator/*comment*/ void*();", Style); 22126 verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style); 22127 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style); 22128 verifyFormat("Foo::operator()(void*);", Style); 22129 verifyFormat("Foo::operator*(void*);", Style); 22130 verifyFormat("Foo::operator*();", Style); 22131 verifyFormat("Foo::operator<int>*();", Style); 22132 verifyFormat("Foo::operator<Foo>*();", Style); 22133 verifyFormat("Foo::operator<int>**();", Style); 22134 verifyFormat("Foo::operator<Foo>**();", Style); 22135 verifyFormat("Foo::operator<Foo>*&();", Style); 22136 verifyFormat("Foo::operator<int>&();", Style); 22137 verifyFormat("Foo::operator<Foo>&();", Style); 22138 verifyFormat("Foo::operator<int>&&();", Style); 22139 verifyFormat("Foo::operator<Foo>&&();", Style); 22140 verifyFormat("Foo::operator<int>*&();", Style); 22141 verifyFormat("Foo::operator<Foo>*&();", Style); 22142 verifyFormat("operator*(int (*)(), class Foo);", Style); 22143 22144 verifyFormat("Foo::operator&();", Style); 22145 verifyFormat("Foo::operator void&();", Style); 22146 verifyFormat("Foo::operator void const&();", Style); 22147 verifyFormat("Foo::operator/*comment*/ void&();", Style); 22148 verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style); 22149 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style); 22150 verifyFormat("Foo::operator()(void&);", Style); 22151 verifyFormat("Foo::operator&(void&);", Style); 22152 verifyFormat("Foo::operator&();", Style); 22153 verifyFormat("operator&(int (&)(), class Foo);", Style); 22154 verifyFormat("operator&(int (&&)(), class Foo);", Style); 22155 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 22156 22157 verifyFormat("Foo::operator&&();", Style); 22158 verifyFormat("Foo::operator void&&();", Style); 22159 verifyFormat("Foo::operator void const&&();", Style); 22160 verifyFormat("Foo::operator/*comment*/ void&&();", Style); 22161 verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style); 22162 verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style); 22163 verifyFormat("Foo::operator()(void&&);", Style); 22164 verifyFormat("Foo::operator&&(void&&);", Style); 22165 verifyFormat("Foo::operator&&();", Style); 22166 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 22167 verifyFormat("operator const nsTArrayLeft<E>&()", Style); 22168 verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()", 22169 Style); 22170 verifyFormat("operator void**()", Style); 22171 verifyFormat("operator const FooLeft<Object>&()", Style); 22172 verifyFormat("operator const FooLeft<Object>*()", Style); 22173 verifyFormat("operator const FooLeft<Object>**()", Style); 22174 verifyFormat("operator const FooLeft<Object>*&()", Style); 22175 verifyFormat("operator const FooLeft<Object>*&&()", Style); 22176 22177 // PR45107 22178 verifyFormat("operator Vector<String>&();", Style); 22179 verifyFormat("operator const Vector<String>&();", Style); 22180 verifyFormat("operator foo::Bar*();", Style); 22181 verifyFormat("operator const Foo<X>::Bar<Y>*();", Style); 22182 verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();", 22183 Style); 22184 22185 Style.PointerAlignment = FormatStyle::PAS_Middle; 22186 verifyFormat("Foo::operator*();", Style); 22187 verifyFormat("Foo::operator void *();", Style); 22188 verifyFormat("Foo::operator()(void *);", Style); 22189 verifyFormat("Foo::operator*(void *);", Style); 22190 verifyFormat("Foo::operator*();", Style); 22191 verifyFormat("operator*(int (*)(), class Foo);", Style); 22192 22193 verifyFormat("Foo::operator&();", Style); 22194 verifyFormat("Foo::operator void &();", Style); 22195 verifyFormat("Foo::operator void const &();", Style); 22196 verifyFormat("Foo::operator()(void &);", Style); 22197 verifyFormat("Foo::operator&(void &);", Style); 22198 verifyFormat("Foo::operator&();", Style); 22199 verifyFormat("operator&(int (&)(), class Foo);", Style); 22200 22201 verifyFormat("Foo::operator&&();", Style); 22202 verifyFormat("Foo::operator void &&();", Style); 22203 verifyFormat("Foo::operator void const &&();", Style); 22204 verifyFormat("Foo::operator()(void &&);", Style); 22205 verifyFormat("Foo::operator&&(void &&);", Style); 22206 verifyFormat("Foo::operator&&();", Style); 22207 verifyFormat("operator&&(int (&&)(), class Foo);", Style); 22208 } 22209 22210 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) { 22211 FormatStyle Style = getLLVMStyle(); 22212 // PR46157 22213 verifyFormat("foo(operator+, -42);", Style); 22214 verifyFormat("foo(operator++, -42);", Style); 22215 verifyFormat("foo(operator--, -42);", Style); 22216 verifyFormat("foo(-42, operator--);", Style); 22217 verifyFormat("foo(-42, operator, );", Style); 22218 verifyFormat("foo(operator, , -42);", Style); 22219 } 22220 22221 TEST_F(FormatTest, WhitespaceSensitiveMacros) { 22222 FormatStyle Style = getLLVMStyle(); 22223 Style.WhitespaceSensitiveMacros.push_back("FOO"); 22224 22225 // Don't use the helpers here, since 'mess up' will change the whitespace 22226 // and these are all whitespace sensitive by definition 22227 EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);", 22228 format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style)); 22229 EXPECT_EQ( 22230 "FOO(String-ized&Messy+But\\(: :Still)=Intentional);", 22231 format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style)); 22232 EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);", 22233 format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style)); 22234 EXPECT_EQ("FOO(String-ized&Messy+But,: :\n" 22235 " Still=Intentional);", 22236 format("FOO(String-ized&Messy+But,: :\n" 22237 " Still=Intentional);", 22238 Style)); 22239 Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive; 22240 EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n" 22241 " Still=Intentional);", 22242 format("FOO(String-ized=&Messy+But,: :\n" 22243 " Still=Intentional);", 22244 Style)); 22245 22246 Style.ColumnLimit = 21; 22247 EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);", 22248 format("FOO(String-ized&Messy+But: :Still=Intentional);", Style)); 22249 } 22250 22251 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) { 22252 // These tests are not in NamespaceFixer because that doesn't 22253 // test its interaction with line wrapping 22254 FormatStyle Style = getLLVMStyle(); 22255 Style.ColumnLimit = 80; 22256 verifyFormat("namespace {\n" 22257 "int i;\n" 22258 "int j;\n" 22259 "} // namespace", 22260 Style); 22261 22262 verifyFormat("namespace AAA {\n" 22263 "int i;\n" 22264 "int j;\n" 22265 "} // namespace AAA", 22266 Style); 22267 22268 EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n" 22269 "int i;\n" 22270 "int j;\n" 22271 "} // namespace Averyveryveryverylongnamespace", 22272 format("namespace Averyveryveryverylongnamespace {\n" 22273 "int i;\n" 22274 "int j;\n" 22275 "}", 22276 Style)); 22277 22278 EXPECT_EQ( 22279 "namespace " 22280 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n" 22281 " went::mad::now {\n" 22282 "int i;\n" 22283 "int j;\n" 22284 "} // namespace\n" 22285 " // " 22286 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::" 22287 "went::mad::now", 22288 format("namespace " 22289 "would::it::save::you::a::lot::of::time::if_::i::" 22290 "just::gave::up::and_::went::mad::now {\n" 22291 "int i;\n" 22292 "int j;\n" 22293 "}", 22294 Style)); 22295 22296 // This used to duplicate the comment again and again on subsequent runs 22297 EXPECT_EQ( 22298 "namespace " 22299 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n" 22300 " went::mad::now {\n" 22301 "int i;\n" 22302 "int j;\n" 22303 "} // namespace\n" 22304 " // " 22305 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::" 22306 "went::mad::now", 22307 format("namespace " 22308 "would::it::save::you::a::lot::of::time::if_::i::" 22309 "just::gave::up::and_::went::mad::now {\n" 22310 "int i;\n" 22311 "int j;\n" 22312 "} // namespace\n" 22313 " // " 22314 "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::" 22315 "and_::went::mad::now", 22316 Style)); 22317 } 22318 22319 TEST_F(FormatTest, LikelyUnlikely) { 22320 FormatStyle Style = getLLVMStyle(); 22321 22322 verifyFormat("if (argc > 5) [[unlikely]] {\n" 22323 " return 29;\n" 22324 "}", 22325 Style); 22326 22327 verifyFormat("if (argc > 5) [[likely]] {\n" 22328 " return 29;\n" 22329 "}", 22330 Style); 22331 22332 verifyFormat("if (argc > 5) [[unlikely]] {\n" 22333 " return 29;\n" 22334 "} else [[likely]] {\n" 22335 " return 42;\n" 22336 "}\n", 22337 Style); 22338 22339 verifyFormat("if (argc > 5) [[unlikely]] {\n" 22340 " return 29;\n" 22341 "} else if (argc > 10) [[likely]] {\n" 22342 " return 99;\n" 22343 "} else {\n" 22344 " return 42;\n" 22345 "}\n", 22346 Style); 22347 22348 verifyFormat("if (argc > 5) [[gnu::unused]] {\n" 22349 " return 29;\n" 22350 "}", 22351 Style); 22352 22353 verifyFormat("if (argc > 5) [[unlikely]]\n" 22354 " return 29;\n", 22355 Style); 22356 verifyFormat("if (argc > 5) [[likely]]\n" 22357 " return 29;\n", 22358 Style); 22359 22360 Style.AttributeMacros.push_back("UNLIKELY"); 22361 Style.AttributeMacros.push_back("LIKELY"); 22362 verifyFormat("if (argc > 5) UNLIKELY\n" 22363 " return 29;\n", 22364 Style); 22365 22366 verifyFormat("if (argc > 5) UNLIKELY {\n" 22367 " return 29;\n" 22368 "}", 22369 Style); 22370 verifyFormat("if (argc > 5) UNLIKELY {\n" 22371 " return 29;\n" 22372 "} else [[likely]] {\n" 22373 " return 42;\n" 22374 "}\n", 22375 Style); 22376 verifyFormat("if (argc > 5) UNLIKELY {\n" 22377 " return 29;\n" 22378 "} else LIKELY {\n" 22379 " return 42;\n" 22380 "}\n", 22381 Style); 22382 verifyFormat("if (argc > 5) [[unlikely]] {\n" 22383 " return 29;\n" 22384 "} else LIKELY {\n" 22385 " return 42;\n" 22386 "}\n", 22387 Style); 22388 } 22389 22390 TEST_F(FormatTest, PenaltyIndentedWhitespace) { 22391 verifyFormat("Constructor()\n" 22392 " : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 22393 " aaaa(aaaaaaaaaaaaaaaaaa, " 22394 "aaaaaaaaaaaaaaaaaat))"); 22395 verifyFormat("Constructor()\n" 22396 " : aaaaaaaaaaaaa(aaaaaa), " 22397 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)"); 22398 22399 FormatStyle StyleWithWhitespacePenalty = getLLVMStyle(); 22400 StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5; 22401 verifyFormat("Constructor()\n" 22402 " : aaaaaa(aaaaaa),\n" 22403 " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" 22404 " aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))", 22405 StyleWithWhitespacePenalty); 22406 verifyFormat("Constructor()\n" 22407 " : aaaaaaaaaaaaa(aaaaaa), " 22408 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)", 22409 StyleWithWhitespacePenalty); 22410 } 22411 22412 TEST_F(FormatTest, LLVMDefaultStyle) { 22413 FormatStyle Style = getLLVMStyle(); 22414 verifyFormat("extern \"C\" {\n" 22415 "int foo();\n" 22416 "}", 22417 Style); 22418 } 22419 TEST_F(FormatTest, GNUDefaultStyle) { 22420 FormatStyle Style = getGNUStyle(); 22421 verifyFormat("extern \"C\"\n" 22422 "{\n" 22423 " int foo ();\n" 22424 "}", 22425 Style); 22426 } 22427 TEST_F(FormatTest, MozillaDefaultStyle) { 22428 FormatStyle Style = getMozillaStyle(); 22429 verifyFormat("extern \"C\"\n" 22430 "{\n" 22431 " int foo();\n" 22432 "}", 22433 Style); 22434 } 22435 TEST_F(FormatTest, GoogleDefaultStyle) { 22436 FormatStyle Style = getGoogleStyle(); 22437 verifyFormat("extern \"C\" {\n" 22438 "int foo();\n" 22439 "}", 22440 Style); 22441 } 22442 TEST_F(FormatTest, ChromiumDefaultStyle) { 22443 FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp); 22444 verifyFormat("extern \"C\" {\n" 22445 "int foo();\n" 22446 "}", 22447 Style); 22448 } 22449 TEST_F(FormatTest, MicrosoftDefaultStyle) { 22450 FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp); 22451 verifyFormat("extern \"C\"\n" 22452 "{\n" 22453 " int foo();\n" 22454 "}", 22455 Style); 22456 } 22457 TEST_F(FormatTest, WebKitDefaultStyle) { 22458 FormatStyle Style = getWebKitStyle(); 22459 verifyFormat("extern \"C\" {\n" 22460 "int foo();\n" 22461 "}", 22462 Style); 22463 } 22464 22465 TEST_F(FormatTest, ConceptsAndRequires) { 22466 FormatStyle Style = getLLVMStyle(); 22467 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 22468 22469 verifyFormat("template <typename T>\n" 22470 "concept Hashable = requires(T a) {\n" 22471 " { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;\n" 22472 "};", 22473 Style); 22474 verifyFormat("template <typename T>\n" 22475 "concept EqualityComparable = requires(T a, T b) {\n" 22476 " { a == b } -> bool;\n" 22477 "};", 22478 Style); 22479 verifyFormat("template <typename T>\n" 22480 "concept EqualityComparable = requires(T a, T b) {\n" 22481 " { a == b } -> bool;\n" 22482 " { a != b } -> bool;\n" 22483 "};", 22484 Style); 22485 verifyFormat("template <typename T>\n" 22486 "concept EqualityComparable = requires(T a, T b) {\n" 22487 " { a == b } -> bool;\n" 22488 " { a != b } -> bool;\n" 22489 "};", 22490 Style); 22491 22492 verifyFormat("template <typename It>\n" 22493 "requires Iterator<It>\n" 22494 "void sort(It begin, It end) {\n" 22495 " //....\n" 22496 "}", 22497 Style); 22498 22499 verifyFormat("template <typename T>\n" 22500 "concept Large = sizeof(T) > 10;", 22501 Style); 22502 22503 verifyFormat("template <typename T, typename U>\n" 22504 "concept FooableWith = requires(T t, U u) {\n" 22505 " typename T::foo_type;\n" 22506 " { t.foo(u) } -> typename T::foo_type;\n" 22507 " t++;\n" 22508 "};\n" 22509 "void doFoo(FooableWith<int> auto t) {\n" 22510 " t.foo(3);\n" 22511 "}", 22512 Style); 22513 verifyFormat("template <typename T>\n" 22514 "concept Context = sizeof(T) == 1;", 22515 Style); 22516 verifyFormat("template <typename T>\n" 22517 "concept Context = is_specialization_of_v<context, T>;", 22518 Style); 22519 verifyFormat("template <typename T>\n" 22520 "concept Node = std::is_object_v<T>;", 22521 Style); 22522 verifyFormat("template <typename T>\n" 22523 "concept Tree = true;", 22524 Style); 22525 22526 verifyFormat("template <typename T> int g(T i) requires Concept1<I> {\n" 22527 " //...\n" 22528 "}", 22529 Style); 22530 22531 verifyFormat( 22532 "template <typename T> int g(T i) requires Concept1<I> && Concept2<I> {\n" 22533 " //...\n" 22534 "}", 22535 Style); 22536 22537 verifyFormat( 22538 "template <typename T> int g(T i) requires Concept1<I> || Concept2<I> {\n" 22539 " //...\n" 22540 "}", 22541 Style); 22542 22543 verifyFormat("template <typename T>\n" 22544 "veryveryvery_long_return_type g(T i) requires Concept1<I> || " 22545 "Concept2<I> {\n" 22546 " //...\n" 22547 "}", 22548 Style); 22549 22550 verifyFormat("template <typename T>\n" 22551 "veryveryvery_long_return_type g(T i) requires Concept1<I> && " 22552 "Concept2<I> {\n" 22553 " //...\n" 22554 "}", 22555 Style); 22556 22557 verifyFormat( 22558 "template <typename T>\n" 22559 "veryveryvery_long_return_type g(T i) requires Concept1 && Concept2 {\n" 22560 " //...\n" 22561 "}", 22562 Style); 22563 22564 verifyFormat( 22565 "template <typename T>\n" 22566 "veryveryvery_long_return_type g(T i) requires Concept1 || Concept2 {\n" 22567 " //...\n" 22568 "}", 22569 Style); 22570 22571 verifyFormat("template <typename It>\n" 22572 "requires Foo<It>() && Bar<It> {\n" 22573 " //....\n" 22574 "}", 22575 Style); 22576 22577 verifyFormat("template <typename It>\n" 22578 "requires Foo<Bar<It>>() && Bar<Foo<It, It>> {\n" 22579 " //....\n" 22580 "}", 22581 Style); 22582 22583 verifyFormat("template <typename It>\n" 22584 "requires Foo<Bar<It, It>>() && Bar<Foo<It, It>> {\n" 22585 " //....\n" 22586 "}", 22587 Style); 22588 22589 verifyFormat( 22590 "template <typename It>\n" 22591 "requires Foo<Bar<It>, Baz<It>>() && Bar<Foo<It>, Baz<It, It>> {\n" 22592 " //....\n" 22593 "}", 22594 Style); 22595 22596 Style.IndentRequires = true; 22597 verifyFormat("template <typename It>\n" 22598 " requires Iterator<It>\n" 22599 "void sort(It begin, It end) {\n" 22600 " //....\n" 22601 "}", 22602 Style); 22603 verifyFormat("template <std::size index_>\n" 22604 " requires(index_ < sizeof...(Children_))\n" 22605 "Tree auto &child() {\n" 22606 " // ...\n" 22607 "}", 22608 Style); 22609 22610 Style.SpaceBeforeParens = FormatStyle::SBPO_Always; 22611 verifyFormat("template <typename T>\n" 22612 "concept Hashable = requires (T a) {\n" 22613 " { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;\n" 22614 "};", 22615 Style); 22616 22617 verifyFormat("template <class T = void>\n" 22618 " requires EqualityComparable<T> || Same<T, void>\n" 22619 "struct equal_to;", 22620 Style); 22621 22622 verifyFormat("template <class T>\n" 22623 " requires requires {\n" 22624 " T{};\n" 22625 " T (int);\n" 22626 " }\n", 22627 Style); 22628 22629 Style.ColumnLimit = 78; 22630 verifyFormat("template <typename T>\n" 22631 "concept Context = Traits<typename T::traits_type> and\n" 22632 " Interface<typename T::interface_type> and\n" 22633 " Request<typename T::request_type> and\n" 22634 " Response<typename T::response_type> and\n" 22635 " ContextExtension<typename T::extension_type> and\n" 22636 " ::std::is_copy_constructable<T> and " 22637 "::std::is_move_constructable<T> and\n" 22638 " requires (T c) {\n" 22639 " { c.response; } -> Response;\n" 22640 "} and requires (T c) {\n" 22641 " { c.request; } -> Request;\n" 22642 "}\n", 22643 Style); 22644 22645 verifyFormat("template <typename T>\n" 22646 "concept Context = Traits<typename T::traits_type> or\n" 22647 " Interface<typename T::interface_type> or\n" 22648 " Request<typename T::request_type> or\n" 22649 " Response<typename T::response_type> or\n" 22650 " ContextExtension<typename T::extension_type> or\n" 22651 " ::std::is_copy_constructable<T> or " 22652 "::std::is_move_constructable<T> or\n" 22653 " requires (T c) {\n" 22654 " { c.response; } -> Response;\n" 22655 "} or requires (T c) {\n" 22656 " { c.request; } -> Request;\n" 22657 "}\n", 22658 Style); 22659 22660 verifyFormat("template <typename T>\n" 22661 "concept Context = Traits<typename T::traits_type> &&\n" 22662 " Interface<typename T::interface_type> &&\n" 22663 " Request<typename T::request_type> &&\n" 22664 " Response<typename T::response_type> &&\n" 22665 " ContextExtension<typename T::extension_type> &&\n" 22666 " ::std::is_copy_constructable<T> && " 22667 "::std::is_move_constructable<T> &&\n" 22668 " requires (T c) {\n" 22669 " { c.response; } -> Response;\n" 22670 "} && requires (T c) {\n" 22671 " { c.request; } -> Request;\n" 22672 "}\n", 22673 Style); 22674 22675 verifyFormat("template <typename T>\nconcept someConcept = Constraint1<T> && " 22676 "Constraint2<T>;"); 22677 22678 Style.BreakBeforeBraces = FormatStyle::BS_Custom; 22679 Style.BraceWrapping.AfterFunction = true; 22680 Style.BraceWrapping.AfterClass = true; 22681 Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; 22682 Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; 22683 verifyFormat("void Foo () requires (std::copyable<T>)\n" 22684 "{\n" 22685 " return\n" 22686 "}\n", 22687 Style); 22688 22689 verifyFormat("void Foo () requires std::copyable<T>\n" 22690 "{\n" 22691 " return\n" 22692 "}\n", 22693 Style); 22694 22695 verifyFormat("template <std::semiregular F, std::semiregular... Args>\n" 22696 " requires (std::invocable<F, std::invoke_result_t<Args>...>)\n" 22697 "struct constant;", 22698 Style); 22699 22700 verifyFormat("template <std::semiregular F, std::semiregular... Args>\n" 22701 " requires std::invocable<F, std::invoke_result_t<Args>...>\n" 22702 "struct constant;", 22703 Style); 22704 22705 verifyFormat("template <class T>\n" 22706 "class plane_with_very_very_very_long_name\n" 22707 "{\n" 22708 " constexpr plane_with_very_very_very_long_name () requires " 22709 "std::copyable<T>\n" 22710 " : plane_with_very_very_very_long_name (1)\n" 22711 " {\n" 22712 " }\n" 22713 "}\n", 22714 Style); 22715 22716 verifyFormat("template <class T>\n" 22717 "class plane_with_long_name\n" 22718 "{\n" 22719 " constexpr plane_with_long_name () requires std::copyable<T>\n" 22720 " : plane_with_long_name (1)\n" 22721 " {\n" 22722 " }\n" 22723 "}\n", 22724 Style); 22725 22726 Style.BreakBeforeConceptDeclarations = false; 22727 verifyFormat("template <typename T> concept Tree = true;", Style); 22728 22729 Style.IndentRequires = false; 22730 verifyFormat("template <std::semiregular F, std::semiregular... Args>\n" 22731 "requires (std::invocable<F, std::invoke_result_t<Args>...>) " 22732 "struct constant;", 22733 Style); 22734 } 22735 22736 TEST_F(FormatTest, StatementAttributeLikeMacros) { 22737 FormatStyle Style = getLLVMStyle(); 22738 StringRef Source = "void Foo::slot() {\n" 22739 " unsigned char MyChar = 'x';\n" 22740 " emit signal(MyChar);\n" 22741 " Q_EMIT signal(MyChar);\n" 22742 "}"; 22743 22744 EXPECT_EQ(Source, format(Source, Style)); 22745 22746 Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive; 22747 EXPECT_EQ("void Foo::slot() {\n" 22748 " unsigned char MyChar = 'x';\n" 22749 " emit signal(MyChar);\n" 22750 " Q_EMIT signal(MyChar);\n" 22751 "}", 22752 format(Source, Style)); 22753 22754 Style.StatementAttributeLikeMacros.push_back("emit"); 22755 EXPECT_EQ(Source, format(Source, Style)); 22756 22757 Style.StatementAttributeLikeMacros = {}; 22758 EXPECT_EQ("void Foo::slot() {\n" 22759 " unsigned char MyChar = 'x';\n" 22760 " emit signal(MyChar);\n" 22761 " Q_EMIT signal(MyChar);\n" 22762 "}", 22763 format(Source, Style)); 22764 } 22765 22766 TEST_F(FormatTest, IndentAccessModifiers) { 22767 FormatStyle Style = getLLVMStyle(); 22768 Style.IndentAccessModifiers = true; 22769 // Members are *two* levels below the record; 22770 // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation. 22771 verifyFormat("class C {\n" 22772 " int i;\n" 22773 "};\n", 22774 Style); 22775 verifyFormat("union C {\n" 22776 " int i;\n" 22777 " unsigned u;\n" 22778 "};\n", 22779 Style); 22780 // Access modifiers should be indented one level below the record. 22781 verifyFormat("class C {\n" 22782 " public:\n" 22783 " int i;\n" 22784 "};\n", 22785 Style); 22786 verifyFormat("struct S {\n" 22787 " private:\n" 22788 " class C {\n" 22789 " int j;\n" 22790 "\n" 22791 " public:\n" 22792 " C();\n" 22793 " };\n" 22794 "\n" 22795 " public:\n" 22796 " int i;\n" 22797 "};\n", 22798 Style); 22799 // Enumerations are not records and should be unaffected. 22800 Style.AllowShortEnumsOnASingleLine = false; 22801 verifyFormat("enum class E {\n" 22802 " A,\n" 22803 " B\n" 22804 "};\n", 22805 Style); 22806 // Test with a different indentation width; 22807 // also proves that the result is Style.AccessModifierOffset agnostic. 22808 Style.IndentWidth = 3; 22809 verifyFormat("class C {\n" 22810 " public:\n" 22811 " int i;\n" 22812 "};\n", 22813 Style); 22814 } 22815 22816 TEST_F(FormatTest, LimitlessStringsAndComments) { 22817 auto Style = getLLVMStyleWithColumns(0); 22818 constexpr StringRef Code = 22819 "/**\n" 22820 " * This is a multiline comment with quite some long lines, at least for " 22821 "the LLVM Style.\n" 22822 " * We will redo this with strings and line comments. Just to check if " 22823 "everything is working.\n" 22824 " */\n" 22825 "bool foo() {\n" 22826 " /* Single line multi line comment. */\n" 22827 " const std::string String = \"This is a multiline string with quite " 22828 "some long lines, at least for the LLVM Style.\"\n" 22829 " \"We already did it with multi line " 22830 "comments, and we will do it with line comments. Just to check if " 22831 "everything is working.\";\n" 22832 " // This is a line comment (block) with quite some long lines, at " 22833 "least for the LLVM Style.\n" 22834 " // We already did this with multi line comments and strings. Just to " 22835 "check if everything is working.\n" 22836 " const std::string SmallString = \"Hello World\";\n" 22837 " // Small line comment\n" 22838 " return String.size() > SmallString.size();\n" 22839 "}"; 22840 EXPECT_EQ(Code, format(Code, Style)); 22841 } 22842 22843 TEST_F(FormatTest, FormatDecayCopy) { 22844 // error cases from unit tests 22845 verifyFormat("foo(auto())"); 22846 verifyFormat("foo(auto{})"); 22847 verifyFormat("foo(auto({}))"); 22848 verifyFormat("foo(auto{{}})"); 22849 22850 verifyFormat("foo(auto(1))"); 22851 verifyFormat("foo(auto{1})"); 22852 verifyFormat("foo(new auto(1))"); 22853 verifyFormat("foo(new auto{1})"); 22854 verifyFormat("decltype(auto(1)) x;"); 22855 verifyFormat("decltype(auto{1}) x;"); 22856 verifyFormat("auto(x);"); 22857 verifyFormat("auto{x};"); 22858 verifyFormat("new auto{x};"); 22859 verifyFormat("auto{x} = y;"); 22860 verifyFormat("auto(x) = y;"); // actually a declaration, but this is clearly 22861 // the user's own fault 22862 verifyFormat("integral auto(x) = y;"); // actually a declaration, but this is 22863 // clearly the user's own fault 22864 verifyFormat("auto(*p)() = f;"); // actually a declaration; TODO FIXME 22865 } 22866 22867 TEST_F(FormatTest, Cpp20ModulesSupport) { 22868 FormatStyle Style = getLLVMStyle(); 22869 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; 22870 Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; 22871 22872 verifyFormat("export import foo;", Style); 22873 verifyFormat("export import foo:bar;", Style); 22874 verifyFormat("export import foo.bar;", Style); 22875 verifyFormat("export import foo.bar:baz;", Style); 22876 verifyFormat("export import :bar;", Style); 22877 verifyFormat("export module foo:bar;", Style); 22878 verifyFormat("export module foo;", Style); 22879 verifyFormat("export module foo.bar;", Style); 22880 verifyFormat("export module foo.bar:baz;", Style); 22881 verifyFormat("export import <string_view>;", Style); 22882 22883 verifyFormat("export type_name var;", Style); 22884 verifyFormat("template <class T> export using A = B<T>;", Style); 22885 verifyFormat("export using A = B;", Style); 22886 verifyFormat("export int func() {\n" 22887 " foo();\n" 22888 "}", 22889 Style); 22890 verifyFormat("export struct {\n" 22891 " int foo;\n" 22892 "};", 22893 Style); 22894 verifyFormat("export {\n" 22895 " int foo;\n" 22896 "};", 22897 Style); 22898 verifyFormat("export export char const *hello() { return \"hello\"; }"); 22899 22900 verifyFormat("import bar;", Style); 22901 verifyFormat("import foo.bar;", Style); 22902 verifyFormat("import foo:bar;", Style); 22903 verifyFormat("import :bar;", Style); 22904 verifyFormat("import <ctime>;", Style); 22905 verifyFormat("import \"header\";", Style); 22906 22907 verifyFormat("module foo;", Style); 22908 verifyFormat("module foo:bar;", Style); 22909 verifyFormat("module foo.bar;", Style); 22910 verifyFormat("module;", Style); 22911 22912 verifyFormat("export namespace hi {\n" 22913 "const char *sayhi();\n" 22914 "}", 22915 Style); 22916 22917 verifyFormat("module :private;", Style); 22918 verifyFormat("import <foo/bar.h>;", Style); 22919 verifyFormat("import foo...bar;", Style); 22920 verifyFormat("import ..........;", Style); 22921 verifyFormat("module foo:private;", Style); 22922 verifyFormat("import a", Style); 22923 verifyFormat("module a", Style); 22924 verifyFormat("export import a", Style); 22925 verifyFormat("export module a", Style); 22926 22927 verifyFormat("import", Style); 22928 verifyFormat("module", Style); 22929 verifyFormat("export", Style); 22930 } 22931 22932 TEST_F(FormatTest, CoroutineForCoawait) { 22933 FormatStyle Style = getLLVMStyle(); 22934 verifyFormat("for co_await (auto x : range())\n ;"); 22935 verifyFormat("for (auto i : arr) {\n" 22936 "}", 22937 Style); 22938 verifyFormat("for co_await (auto i : arr) {\n" 22939 "}", 22940 Style); 22941 verifyFormat("for co_await (auto i : foo(T{})) {\n" 22942 "}", 22943 Style); 22944 } 22945 22946 TEST_F(FormatTest, CoroutineCoAwait) { 22947 verifyFormat("int x = co_await foo();"); 22948 verifyFormat("int x = (co_await foo());"); 22949 verifyFormat("co_await (42);"); 22950 verifyFormat("void operator co_await(int);"); 22951 verifyFormat("void operator co_await(a);"); 22952 verifyFormat("co_await a;"); 22953 verifyFormat("co_await missing_await_resume{};"); 22954 verifyFormat("co_await a; // comment"); 22955 verifyFormat("void test0() { co_await a; }"); 22956 verifyFormat("co_await co_await co_await foo();"); 22957 verifyFormat("co_await foo().bar();"); 22958 verifyFormat("co_await [this]() -> Task { co_return x; }"); 22959 verifyFormat("co_await [this](int a, int b) -> Task { co_return co_await " 22960 "foo(); }(x, y);"); 22961 22962 FormatStyle Style = getLLVMStyle(); 22963 Style.ColumnLimit = 40; 22964 verifyFormat("co_await [this](int a, int b) -> Task {\n" 22965 " co_return co_await foo();\n" 22966 "}(x, y);", 22967 Style); 22968 verifyFormat("co_await;"); 22969 } 22970 22971 TEST_F(FormatTest, CoroutineCoYield) { 22972 verifyFormat("int x = co_yield foo();"); 22973 verifyFormat("int x = (co_yield foo());"); 22974 verifyFormat("co_yield (42);"); 22975 verifyFormat("co_yield {42};"); 22976 verifyFormat("co_yield 42;"); 22977 verifyFormat("co_yield n++;"); 22978 verifyFormat("co_yield ++n;"); 22979 verifyFormat("co_yield;"); 22980 } 22981 22982 TEST_F(FormatTest, CoroutineCoReturn) { 22983 verifyFormat("co_return (42);"); 22984 verifyFormat("co_return;"); 22985 verifyFormat("co_return {};"); 22986 verifyFormat("co_return x;"); 22987 verifyFormat("co_return co_await foo();"); 22988 verifyFormat("co_return co_yield foo();"); 22989 } 22990 22991 TEST_F(FormatTest, EmptyShortBlock) { 22992 auto Style = getLLVMStyle(); 22993 Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; 22994 22995 verifyFormat("try {\n" 22996 " doA();\n" 22997 "} catch (Exception &e) {\n" 22998 " e.printStackTrace();\n" 22999 "}\n", 23000 Style); 23001 23002 verifyFormat("try {\n" 23003 " doA();\n" 23004 "} catch (Exception &e) {}\n", 23005 Style); 23006 } 23007 23008 } // namespace 23009 } // namespace format 23010 } // namespace clang 23011